diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy-2.2.6.dist-info/INSTALLER b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy-2.2.6.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy-2.2.6.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy-2.2.6.dist-info/LICENSE.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy-2.2.6.dist-info/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..f0879448151a25d80a2cbd83e4d9ee8ef598a783 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy-2.2.6.dist-info/LICENSE.txt @@ -0,0 +1,971 @@ +Copyright (c) 2005-2024, 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. + +---- + +The NumPy repository and source distributions bundle several libraries that are +compatibly licensed. We list these here. + +Name: lapack-lite +Files: numpy/linalg/lapack_lite/* +License: BSD-3-Clause + For details, see numpy/linalg/lapack_lite/LICENSE.txt + +Name: dragon4 +Files: numpy/_core/src/multiarray/dragon4.c +License: MIT + For license text, see numpy/_core/src/multiarray/dragon4.c + +Name: libdivide +Files: numpy/_core/include/numpy/libdivide/* +License: Zlib + For license text, see numpy/_core/include/numpy/libdivide/LICENSE.txt + + +Note that the following files are vendored in the repository and sdist but not +installed in built numpy packages: + +Name: Meson +Files: vendored-meson/meson/* +License: Apache 2.0 + For license text, see vendored-meson/meson/COPYING + +Name: spin +Files: .spin/cmds.py +License: BSD-3 + For license text, see .spin/LICENSE + +Name: tempita +Files: numpy/_build_utils/tempita/* +License: MIT + For details, see numpy/_build_utils/tempita/LICENCE.txt + +---- + +This binary distribution of NumPy also bundles the following software: + + +Name: OpenBLAS +Files: numpy.libs/libscipy_openblas*.so +Description: bundled as a dynamically linked library +Availability: https://github.com/OpenMathLib/OpenBLAS/ +License: BSD-3-Clause + Copyright (c) 2011-2014, The OpenBLAS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + 3. Neither the name of the OpenBLAS project nor the names of + its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +Name: LAPACK +Files: numpy.libs/libscipy_openblas*.so +Description: bundled in OpenBLAS +Availability: https://github.com/OpenMathLib/OpenBLAS/ +License: BSD-3-Clause-Attribution + Copyright (c) 1992-2013 The University of Tennessee and The University + of Tennessee Research Foundation. All rights + reserved. + Copyright (c) 2000-2013 The University of California Berkeley. All + rights reserved. + Copyright (c) 2006-2013 The University of Colorado Denver. All rights + reserved. + + $COPYRIGHT$ + + Additional copyrights may follow + + $HEADER$ + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer listed + in this license in the documentation and/or other materials + provided with the distribution. + + - Neither the name of the copyright holders nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + The copyright holders provide no reassurances that the source code + provided does not infringe any patent, copyright, or any other + intellectual property rights of third parties. The copyright holders + disclaim any liability to any recipient for claims brought against + recipient by any third party for infringement of that parties + intellectual property rights. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +Name: GCC runtime library +Files: numpy.libs/libgfortran*.so +Description: dynamically linked to files compiled with gcc +Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libgfortran +License: GPL-3.0-with-GCC-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 +. + +Name: libquadmath +Files: numpy.libs/libquadmath*.so +Description: dynamically linked to files compiled with gcc +Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libquadmath +License: LGPL-2.1-or-later + + GCC Quad-Precision Math Library + Copyright (C) 2010-2019 Free Software Foundation, Inc. + Written by Francois-Xavier Coudert + + This file is part of the libquadmath library. + Libquadmath is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + Libquadmath 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 + Lesser General Public License for more details. + https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy-2.2.6.dist-info/METADATA b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy-2.2.6.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..1c3041826574afca64c0ed3aca89bd92337def13 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy-2.2.6.dist-info/METADATA @@ -0,0 +1,1092 @@ +Metadata-Version: 2.1 +Name: numpy +Version: 2.2.6 +Summary: Fundamental package for array computing in Python +Author: Travis E. Oliphant et al. +Maintainer-Email: NumPy Developers +License: Copyright (c) 2005-2024, 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. + + ---- + + The NumPy repository and source distributions bundle several libraries that are + compatibly licensed. We list these here. + + Name: lapack-lite + Files: numpy/linalg/lapack_lite/* + License: BSD-3-Clause + For details, see numpy/linalg/lapack_lite/LICENSE.txt + + Name: dragon4 + Files: numpy/_core/src/multiarray/dragon4.c + License: MIT + For license text, see numpy/_core/src/multiarray/dragon4.c + + Name: libdivide + Files: numpy/_core/include/numpy/libdivide/* + License: Zlib + For license text, see numpy/_core/include/numpy/libdivide/LICENSE.txt + + + Note that the following files are vendored in the repository and sdist but not + installed in built numpy packages: + + Name: Meson + Files: vendored-meson/meson/* + License: Apache 2.0 + For license text, see vendored-meson/meson/COPYING + + Name: spin + Files: .spin/cmds.py + License: BSD-3 + For license text, see .spin/LICENSE + + Name: tempita + Files: numpy/_build_utils/tempita/* + License: MIT + For details, see numpy/_build_utils/tempita/LICENCE.txt + + ---- + + This binary distribution of NumPy also bundles the following software: + + + Name: OpenBLAS + Files: numpy.libs/libscipy_openblas*.so + Description: bundled as a dynamically linked library + Availability: https://github.com/OpenMathLib/OpenBLAS/ + License: BSD-3-Clause + Copyright (c) 2011-2014, The OpenBLAS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + 3. Neither the name of the OpenBLAS project nor the names of + its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + + Name: LAPACK + Files: numpy.libs/libscipy_openblas*.so + Description: bundled in OpenBLAS + Availability: https://github.com/OpenMathLib/OpenBLAS/ + License: BSD-3-Clause-Attribution + Copyright (c) 1992-2013 The University of Tennessee and The University + of Tennessee Research Foundation. All rights + reserved. + Copyright (c) 2000-2013 The University of California Berkeley. All + rights reserved. + Copyright (c) 2006-2013 The University of Colorado Denver. All rights + reserved. + + $COPYRIGHT$ + + Additional copyrights may follow + + $HEADER$ + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer listed + in this license in the documentation and/or other materials + provided with the distribution. + + - Neither the name of the copyright holders nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + The copyright holders provide no reassurances that the source code + provided does not infringe any patent, copyright, or any other + intellectual property rights of third parties. The copyright holders + disclaim any liability to any recipient for claims brought against + recipient by any third party for infringement of that parties + intellectual property rights. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + + Name: GCC runtime library + Files: numpy.libs/libgfortran*.so + Description: dynamically linked to files compiled with gcc + Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libgfortran + License: GPL-3.0-with-GCC-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 + . + + Name: libquadmath + Files: numpy.libs/libquadmath*.so + Description: dynamically linked to files compiled with gcc + Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libquadmath + License: LGPL-2.1-or-later + + GCC Quad-Precision Math Library + Copyright (C) 2010-2019 Free Software Foundation, Inc. + Written by Francois-Xavier Coudert + + This file is part of the libquadmath library. + Libquadmath is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + Libquadmath 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 + Lesser General Public License for more details. + https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html + +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Science/Research +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Programming Language :: C +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Topic :: Software Development +Classifier: Topic :: Scientific/Engineering +Classifier: Typing :: Typed +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX +Classifier: Operating System :: Unix +Classifier: Operating System :: MacOS +Project-URL: homepage, https://numpy.org +Project-URL: documentation, https://numpy.org/doc/ +Project-URL: source, https://github.com/numpy/numpy +Project-URL: download, https://pypi.org/project/numpy/#files +Project-URL: tracker, https://github.com/numpy/numpy/issues +Project-URL: release notes, https://numpy.org/doc/stable/release +Requires-Python: >=3.10 +Description-Content-Type: text/markdown + +

+ +


+ + +[![Powered by NumFOCUS](https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A)]( +https://numfocus.org) +[![PyPI Downloads](https://img.shields.io/pypi/dm/numpy.svg?label=PyPI%20downloads)]( +https://pypi.org/project/numpy/) +[![Conda Downloads](https://img.shields.io/conda/dn/conda-forge/numpy.svg?label=Conda%20downloads)]( +https://anaconda.org/conda-forge/numpy) +[![Stack Overflow](https://img.shields.io/badge/stackoverflow-Ask%20questions-blue.svg)]( +https://stackoverflow.com/questions/tagged/numpy) +[![Nature Paper](https://img.shields.io/badge/DOI-10.1038%2Fs41586--020--2649--2-blue)]( +https://doi.org/10.1038/s41586-020-2649-2) +[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/numpy/numpy/badge)](https://securityscorecards.dev/viewer/?uri=github.com/numpy/numpy) + + +NumPy is the fundamental package for scientific computing with Python. + +- **Website:** https://www.numpy.org +- **Documentation:** https://numpy.org/doc +- **Mailing list:** https://mail.python.org/mailman/listinfo/numpy-discussion +- **Source code:** https://github.com/numpy/numpy +- **Contributing:** https://www.numpy.org/devdocs/dev/index.html +- **Bug reports:** https://github.com/numpy/numpy/issues +- **Report a security vulnerability:** https://tidelift.com/docs/security + +It provides: + +- a powerful N-dimensional array object +- sophisticated (broadcasting) functions +- tools for integrating C/C++ and Fortran code +- useful linear algebra, Fourier transform, and random number capabilities + +Testing: + +NumPy requires `pytest` and `hypothesis`. Tests can then be run after installation with: + + python -c "import numpy, sys; sys.exit(numpy.test() is False)" + +Code of Conduct +---------------------- + +NumPy is a community-driven open source project developed by a diverse group of +[contributors](https://numpy.org/teams/). The NumPy leadership has made a strong +commitment to creating an open, inclusive, and positive community. Please read the +[NumPy Code of Conduct](https://numpy.org/code-of-conduct/) for guidance on how to interact +with others in a way that makes our community thrive. + +Call for Contributions +---------------------- + +The NumPy project welcomes your expertise and enthusiasm! + +Small improvements or fixes are always appreciated. If you are considering larger contributions +to the source code, please contact us through the [mailing +list](https://mail.python.org/mailman/listinfo/numpy-discussion) first. + +Writing code isn’t the only way to contribute to NumPy. You can also: +- review pull requests +- help us stay on top of new and old issues +- develop tutorials, presentations, and other educational materials +- maintain and improve [our website](https://github.com/numpy/numpy.org) +- develop graphic design for our brand assets and promotional materials +- translate website content +- help with outreach and onboard new contributors +- write grant proposals and help with other fundraising efforts + +For more information about the ways you can contribute to NumPy, visit [our website](https://numpy.org/contribute/). +If you’re unsure where to start or how your skills fit in, reach out! You can +ask on the mailing list or here, on GitHub, by opening a new issue or leaving a +comment on a relevant issue that is already open. + +Our preferred channels of communication are all public, but if you’d like to +speak to us in private first, contact our community coordinators at +numpy-team@googlegroups.com or on Slack (write numpy-team@googlegroups.com for +an invitation). + +We also have a biweekly community call, details of which are announced on the +mailing list. You are very welcome to join. + +If you are new to contributing to open source, [this +guide](https://opensource.guide/how-to-contribute/) helps explain why, what, +and how to successfully get involved. diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy-2.2.6.dist-info/RECORD b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy-2.2.6.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..7171e236f4585036a52d0a3510511057c91f5607 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy-2.2.6.dist-info/RECORD @@ -0,0 +1,1008 @@ +../../../bin/f2py,sha256=tL1Y2JHTcYh6q_0QbfgER6aD_3YllY3LaGnhsmyPB4w,374 +../../../bin/numpy-config,sha256=HSengRbulDcEkTWccSe5Mm5wSxJsG63uSD_dK_fRH4M,374 +numpy-2.2.6.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +numpy-2.2.6.dist-info/LICENSE.txt,sha256=wAK9Jt59x6pGQlCg3gY9WP5Vl0RS5DieXCHDUKggvwY,47755 +numpy-2.2.6.dist-info/METADATA,sha256=ItZI9ThIQpRkymQ7QNc7Sakg1Hh2_HfDldTcpOg0kEo,62026 +numpy-2.2.6.dist-info/RECORD,, +numpy-2.2.6.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy-2.2.6.dist-info/WHEEL,sha256=sZM_NeUMz2G4fDenMf11eikcCxcLaQWiYRmjwQBavQs,137 +numpy-2.2.6.dist-info/entry_points.txt,sha256=4mXDNhJDQ9GHqMBeRJ8B3PlixTFmkXGqU3RVuac20q0,172 +numpy.libs/libgfortran-040039e1-0352e75f.so.5.0.0,sha256=xgkASOzMdjUiwS7wFvgdprYnyzoET1XPBHmoOcQcCYA,2833617 +numpy.libs/libquadmath-96973f99-934c22de.so.0.0.0,sha256=btUTf0Enga14Y0OftUNhP2ILQ8MrYykqACkkYWL1u8Y,250985 +numpy.libs/libscipy_openblas64_-56d6093b.so,sha256=C9gV0EtrVJkOPMzHUo-7aWRW0JVp9TPQOQwT8M3E3Uo,25021457 +numpy/__config__.py,sha256=5DGi8IN_RKTEdFVY33VFCH63IZXeByrXl8ZCcJ1F97E,5281 +numpy/__config__.pyi,sha256=ZKpaYX_mDS5X5VwNaH5wNAVi3X1FP0XkI5LcFOImNPk,2377 +numpy/__init__.cython-30.pxd,sha256=cWfkT3NMZ3X0V3kjbEeS6qZIhR_eBNVYdO_8Mp-ebGk,46791 +numpy/__init__.pxd,sha256=pPfD2-RbhOQKZ7IgCkduBgGYZELhvycWeESYSFh_274,43427 +numpy/__init__.py,sha256=auF7BwwPcKjjytiaUQolaULlofN-pf6xIM7BZ-0qYjY,22147 +numpy/__init__.pyi,sha256=ofWyIU0AzmaLAVNQmCmOEDgOVzffZEyXXE3PmjWOeIs,211670 +numpy/_array_api_info.py,sha256=qiHJDVG58rAk1iTlXsFrnhZ7Y-ghPUkyBpJiMvPK2jg,10381 +numpy/_array_api_info.pyi,sha256=P71pudeW0DUFIlo27p5NHC8hoxkYP2ZhrsoS9uEJcvo,4892 +numpy/_configtool.py,sha256=asiPfz_TX2Dp0msoNjG43pZKRYgNYusSIg2ieczK8as,1007 +numpy/_configtool.pyi,sha256=d4f22QGwpb1ZtDk-1Sn72ftvo4incC5E2JAikmjzfJI,24 +numpy/_core/__init__.py,sha256=H95-zST0CH6pnnObjXUXXiPgtub9M35IBGaYE-q4wrU,5612 +numpy/_core/__init__.pyi,sha256=Mj2I4BtqBVNUZVs5o1T58Z7wSaWjfhX0nCl-a0ULjgA,86 +numpy/_core/_add_newdocs.py,sha256=stKVrZWkWH-g_mp7MwO-N1DkMfKXjLxBsrlurBXmeA4,208755 +numpy/_core/_add_newdocs.pyi,sha256=r__d_-GHkfjzuZ0qyjDztsKgdc1eIyeN-cBoYVgMBuo,168 +numpy/_core/_add_newdocs_scalars.py,sha256=ePmas0mI6OCpq9W8ZszXHyEhktsBUj_hvEt6ozb8Zic,12603 +numpy/_core/_add_newdocs_scalars.pyi,sha256=ZnIk0TgL0szrv6SPCH-4dF469Q_92UvV5_ek47Oj7HM,573 +numpy/_core/_asarray.py,sha256=7oZPqNjuDL0IxIeT7V_UJW19lsKS3eny-jlN4Ha-hoA,3912 +numpy/_core/_asarray.pyi,sha256=xkgqEh4c9lcFktJija8a1w5Tj7-2XfZOV8GjDZsXpzY,1085 +numpy/_core/_dtype.py,sha256=4Pz6KJQJRywlsMhdH8NbIugziDyQi1ekv2ZMw7zomzo,10734 +numpy/_core/_dtype.pyi,sha256=DKUAq45hxO7xO6zVuI6oYkkl1gtodB2z0NJ9JtFNhfc,1951 +numpy/_core/_dtype_ctypes.py,sha256=dcZHQ46qjV0n7l934WIYw7kv-1HoHxelu50oIIX7GWU,3718 +numpy/_core/_dtype_ctypes.pyi,sha256=VwEZFViCPuHlCURv2jpJp9sbHh2hYUpzC_FRZNNGMMw,3682 +numpy/_core/_exceptions.py,sha256=dZWKqfdLRvJvbAEG_fof_8ikEKxjakADMty1kLC_l_M,5379 +numpy/_core/_exceptions.pyi,sha256=xH30RJw6Yi0lyJzcwb32uSS7aMT64Kf1Cr82ZNCu9jQ,2146 +numpy/_core/_internal.py,sha256=B8t6mxvaDouxE-COR010v4_PUHNzOF8mHgFatRPlJWk,29164 +numpy/_core/_internal.pyi,sha256=QKaBqSkdl1mnHLJb376B_5mv-GCZtmn8DXDQufA1D4E,2654 +numpy/_core/_machar.py,sha256=399tphFPGzJy1bpbeXLDjUUZTebWto1lozB1praORfE,11565 +numpy/_core/_machar.pyi,sha256=xH30RJw6Yi0lyJzcwb32uSS7aMT64Kf1Cr82ZNCu9jQ,2146 +numpy/_core/_methods.py,sha256=pjmP1yAbtVesXTytuupGIXojO55y8LBS-8fEQPusNIU,9469 +numpy/_core/_methods.pyi,sha256=-WJkb43KYhpq59UpUxsjTIB30WAIApHjmlBzXFMrc8Y,556 +numpy/_core/_multiarray_tests.cpython-310-x86_64-linux-gnu.so,sha256=jMvfEWtj9yFQwbG0FCIQaaTrUAg39zVEH8LtzmvwBKo,178888 +numpy/_core/_multiarray_umath.cpython-310-x86_64-linux-gnu.so,sha256=xjTq8FNnrwK4Fc89ICD77um0dCavH-Js8xieR5iTLcU,10449209 +numpy/_core/_operand_flag_tests.cpython-310-x86_64-linux-gnu.so,sha256=q6mNJbns3leBgBvrN7tUSqVGhScnareQTn-bLfZeYfk,16984 +numpy/_core/_rational_tests.cpython-310-x86_64-linux-gnu.so,sha256=K53yA2cH8tWPhTHn98pK5aqJYEAUih3qVr-jC9MTA5o,59824 +numpy/_core/_simd.cpython-310-x86_64-linux-gnu.so,sha256=SUlAdaif-Jcb_UajMC0ilqCnKoIraFGUHV32YXhxAm8,3038216 +numpy/_core/_simd.pyi,sha256=2z2sFPgXr3KRzHltbt31HVrhkXM0VwXFp1lUjxaRMAM,669 +numpy/_core/_string_helpers.py,sha256=gu3x0dEnRnh3mnOkviX17r8rCmagVgYHfxILt9Q9irA,2837 +numpy/_core/_string_helpers.pyi,sha256=xLlLKJHutEYzyKnTG2k7clcWvVUTvD319SjnKmDXuac,358 +numpy/_core/_struct_ufunc_tests.cpython-310-x86_64-linux-gnu.so,sha256=gNj0W2VNP4ZCvK24ipNYd4d9PaHqkuzAAgQyBVUfLhU,17120 +numpy/_core/_type_aliases.py,sha256=4AU_cVekBKDIXO1URlOQKsMz8nrDw1tHr_nBdQzvNzo,3489 +numpy/_core/_type_aliases.pyi,sha256=9nNzq_Bxy5ikgnRaFMEcbThUVrb4HYJQvH58gXDWCGE,2400 +numpy/_core/_ufunc_config.py,sha256=LlFpTUnHFeHQlNFiuBHvrqVn-nQ7EvIgUEn3HUclt7k,15030 +numpy/_core/_ufunc_config.pyi,sha256=piQY1VeYD5rKJUOOMYRvLhNPMAdLEik4Yzgx-ioB19A,1172 +numpy/_core/_umath_tests.cpython-310-x86_64-linux-gnu.so,sha256=oPK4BNfdjyyWJTIxXST5WD1eG1dGe-tt0m3ZDfqruO4,46416 +numpy/_core/arrayprint.py,sha256=s5lMLv3Wy_fa3hB1OqUaM4h1Ja9SB_X-3zAkQW1Tu4E,64812 +numpy/_core/arrayprint.pyi,sha256=BmhTDgihJN2U08C0RUzvl36lXp8Cc1CF-uy3MuF3kbI,6934 +numpy/_core/cversions.py,sha256=H_iNIpx9-hY1cQNxqjT2d_5SXZhJbMo_caq4_q6LB7I,347 +numpy/_core/defchararray.py,sha256=hwzNR5D4bYTDU846j0uKoTnRsZk22jmM5KeXZitkvmU,37798 +numpy/_core/defchararray.pyi,sha256=n4P-zXnU8SdMf1cAiKDnJA08L_sVsvoDx7ONFOO-8YM,26962 +numpy/_core/einsumfunc.py,sha256=xsYoawvzK4EA2QIYdtk5KyrFkUCe4kSt5wOtXCm_v1s,52820 +numpy/_core/einsumfunc.pyi,sha256=mx5u6i7mdFuJH4MqLZVU26-ld5y0x5B9ln6lw9RpW-w,4929 +numpy/_core/fromnumeric.py,sha256=gK8m2Y3lSJ5qszgNE-F-ZdN6uab40cW5BBsD4SONHLA,143907 +numpy/_core/fromnumeric.pyi,sha256=VLvvO7t4JLBXEX2EHwSjFOQpDfN_ss9VOLwpgc9NwkQ,41190 +numpy/_core/function_base.py,sha256=hfcYdavNeeDbiYjvTBqDA6OJHxH1fuNDdMtTZUi3RZg,19733 +numpy/_core/function_base.pyi,sha256=_pJUw_NYCDy1EyGL0ABeXAWNOTsj_n7L_8GHPoqPfYs,5690 +numpy/_core/getlimits.py,sha256=Uy3W6eJwu2l7R6ovqdfeOyQybF5jjlPER88pSM3_JPg,26112 +numpy/_core/getlimits.pyi,sha256=q30hQ3wDenmxoZUSoSOqyVrZZVGlsixXCHe6QUthbp8,61 +numpy/_core/include/numpy/__multiarray_api.c,sha256=u7HxPIx7xdxAPTE0gristUOO0-1L-_fl0IeKqR4voxI,12669 +numpy/_core/include/numpy/__multiarray_api.h,sha256=akdAXdNQvHxPFPbdeobhoGzyLUkoVdwzKDjzdbtk5zQ,61383 +numpy/_core/include/numpy/__ufunc_api.c,sha256=Fg7WlH4Ow6jETKRArVL_QF11ABKYz1VpOve56_U3E0w,1755 +numpy/_core/include/numpy/__ufunc_api.h,sha256=tayZuDCeuqm3ggFvWxJuoARz5obz6Saas9L7JcKO_eQ,13166 +numpy/_core/include/numpy/_neighborhood_iterator_imp.h,sha256=s-Hw_l5WRwKtYvsiIghF0bg-mA_CgWnzFFOYVFJ-q4k,1857 +numpy/_core/include/numpy/_numpyconfig.h,sha256=brqqDI4gwfGEFHMIWi0oNA0n_qnBBUWFVJtgfcdpSA0,926 +numpy/_core/include/numpy/_public_dtype_api_table.h,sha256=n6_Kb98SyvsR_X7stiNA6VuGp_c5W1e4fMVcJdO0wis,4574 +numpy/_core/include/numpy/arrayobject.h,sha256=mU5vpcQ95PH1j3bp8KYhJOFHB-GxwRjSUsR7nxlTSRk,204 +numpy/_core/include/numpy/arrayscalars.h,sha256=LlyrZIa_5td11BfqfMCv1hYbiG6__zxxGv1MRj8uIVo,4243 +numpy/_core/include/numpy/dtype_api.h,sha256=Gn37RzObmcTsL6YUYY9aG22Ct8F-r4ZaC53NPFqaIso,19238 +numpy/_core/include/numpy/halffloat.h,sha256=TRZfXgipa-dFppX2uNgkrjrPli-1BfJtadWjAembJ4s,1959 +numpy/_core/include/numpy/ndarrayobject.h,sha256=MnykWmchyS05ler_ZyhFIr_0j6c0IcndEi3X3n0ZWDk,12057 +numpy/_core/include/numpy/ndarraytypes.h,sha256=qnnC60F-oeGzkM65vV8VcMsThLYKcDWkhLQBOfJ3jZk,65053 +numpy/_core/include/numpy/npy_1_7_deprecated_api.h,sha256=90kGcNaBPgT5FJArB_MPgW24_Mpl5RcfUR3Y0rRB5Bw,3746 +numpy/_core/include/numpy/npy_2_compat.h,sha256=wdjB7_-AtW3op67Xbj3EVH6apSF7cRG6h3c5hBz-YMs,8546 +numpy/_core/include/numpy/npy_2_complexcompat.h,sha256=eE9dV_Iq3jEfGGJFH_pQjJnvC6eQ12WgOB7cZMmHByE,857 +numpy/_core/include/numpy/npy_3kcompat.h,sha256=grN6W1n7benj3F2pSAOpl_s6vn1Y50QfAP-DaleD7cA,9648 +numpy/_core/include/numpy/npy_common.h,sha256=wbV1Z6m3w1h4qVcOxfF38s3H13UfFHEuBGRfDhTeUKE,36551 +numpy/_core/include/numpy/npy_cpu.h,sha256=AUJ5CqlguteR3-R0IjPt5rylWtvvccCWtt0GpjZbexU,4703 +numpy/_core/include/numpy/npy_endian.h,sha256=vvK7ZlOt0vgqTVrIyviWzoxQz70S-BvflS4Z_k6X5XE,2834 +numpy/_core/include/numpy/npy_math.h,sha256=aeSFs60QbWPy1gIPyHDPrYExifm5mbDAcjP_mLk_PF0,18858 +numpy/_core/include/numpy/npy_no_deprecated_api.h,sha256=0yZrJcQEJ6MCHJInQk5TP9_qZ4t7EfBuoLOJ34IlJd4,678 +numpy/_core/include/numpy/npy_os.h,sha256=hlQsg_7-RkvS3s8OM8KXy99xxyJbCm-W1AYVcdnO1cw,1256 +numpy/_core/include/numpy/numpyconfig.h,sha256=OvRlre4eb9KBWt6gAE5cQ4K-P2uRmIKU1rAKxWFygmA,7161 +numpy/_core/include/numpy/random/LICENSE.txt,sha256=-8U59H0M-DvGE3gID7hz1cFGMBJsrL_nVANcOSbapew,1018 +numpy/_core/include/numpy/random/bitgen.h,sha256=49AwKOR552r-NkhuSOF1usb_URiMSRMvD22JF5pKIng,488 +numpy/_core/include/numpy/random/distributions.h,sha256=W5tOyETd0m1W0GdaZ5dJP8fKlBtsTpG23V2Zlmrlqpg,9861 +numpy/_core/include/numpy/random/libdivide.h,sha256=ew9MNhPQd1LsCZiWiFmj9IZ7yOnA3HKOXffDeR9X1jw,80138 +numpy/_core/include/numpy/ufuncobject.h,sha256=r2XM6XyILKXLqgmHFVu8jXqvOp_Zv8tLfS8Omn5jbng,11918 +numpy/_core/include/numpy/utils.h,sha256=wMNomSH3Dfj0q78PrjLVtFtN-FPo7UJ4o0ifCUO-6Es,1185 +numpy/_core/lib/libnpymath.a,sha256=Rg3gCXTxpny2Hh-jZFKh6KDYquzjcJklumEnLHhQXQ0,118712 +numpy/_core/lib/npy-pkg-config/mlib.ini,sha256=_LsWV1eStNqwhdiYPa2538GL46dnfVwT4MrI1zbsoFw,147 +numpy/_core/lib/npy-pkg-config/npymath.ini,sha256=0iMzarBfkkZ_EXO95_kz-SHZRcNIEwIeOjE_esVBkRQ,361 +numpy/_core/lib/pkgconfig/numpy.pc,sha256=TixQH5uvO6LvobGP1BrUfGuCdMxvdphpZUy_KczizY4,191 +numpy/_core/memmap.py,sha256=B3k5EZ8QwzjPwWwOtVRVyEofQJSG_pCBcWCFknO-GaU,12664 +numpy/_core/memmap.pyi,sha256=_LKjb_PuhcQwpqc2lFaL379DYzQ9PtuKdlVV3jXOYEM,47 +numpy/_core/multiarray.py,sha256=0P7ZBHKR0mI0tatyqDCHwnfewEEiQ48dwrzVL2PQAk0,58137 +numpy/_core/multiarray.pyi,sha256=MzZt-K2x2BrDebbirvR2so5Tbipw3u189VVsDjkAdyk,33396 +numpy/_core/numeric.py,sha256=vsiEcMig4QHwMf9HP5maqOhFsblqGbh8AtE4cX08D7w,81726 +numpy/_core/numeric.pyi,sha256=Ax8B42cDqwsrlVsYt6NhthEZvQNMGdNzNcpXAy9i1kw,19198 +numpy/_core/numerictypes.py,sha256=W-Eu_Av5zNNBHDZHGLNlmNb2UuMByKRdwWPTsJxA5oQ,16125 +numpy/_core/numerictypes.pyi,sha256=ZlPCN6_8qJ7ZWiDayxfQ9oRnq1Gej2P388BX30SUR7s,3533 +numpy/_core/overrides.py,sha256=czubu5JHSdid31If0WLqOYEM3WiAY03tLmyoa04sWjg,7211 +numpy/_core/overrides.pyi,sha256=4ycXYFRjEycSPOaRtciFKwBTsAjHUoGztX-IkTpXQYw,1743 +numpy/_core/printoptions.py,sha256=FUY--hG0-oobvtHOY64D50Bs_-JFmf-Nza7C9IXORFY,1063 +numpy/_core/printoptions.pyi,sha256=eNiliCnDuZBxla6X9kwZ-7YiCn-UtMbT-U_qTnw8l9w,594 +numpy/_core/records.py,sha256=0Uv2Z2xBvxYQUsAhp5zZ262YFHmSN6R_bazI_EyRE00,36862 +numpy/_core/records.pyi,sha256=nDLqj-5Z8hE8hQ4HiDPuHqGy91srd4Vvpn3_ZbEk2o4,8789 +numpy/_core/shape_base.py,sha256=CK3LrcfWKnChokUm1eHYsL43Q7D5qPq7QxDPuYYMnAU,32883 +numpy/_core/shape_base.pyi,sha256=4UDvO6R4ZtZChKb4HNZUil3P8HOGTM5wOwPMT8tsp6Y,4545 +numpy/_core/strings.py,sha256=wCfZ3b3_WKY3LZ0cPn5IXrTN6wXtCSfa8Jrvpznz85c,45672 +numpy/_core/strings.pyi,sha256=NRCCxdkiEvQO9I__b-rNef4pxiqrCgtIFvyPvs7rLng,12770 +numpy/_core/tests/_locales.py,sha256=_J4MFSLUG1hiIfiifglI0nD--lS3CqwIjKKM3is0S6Q,2176 +numpy/_core/tests/_natype.py,sha256=9N-pE9LuQKrqT7ef-P9mtXpWls3YAsZ8JR-3cR7TRjs,6259 +numpy/_core/tests/data/astype_copy.pkl,sha256=lWSzCcvzRB_wpuRGj92spGIw-rNPFcd9hwJaRVvfWdk,716 +numpy/_core/tests/data/generate_umath_validation_data.cpp,sha256=BQakB5o8Mq60zex5ovVO0IatNa7xbF8JvXmtk6373So,5842 +numpy/_core/tests/data/recarray_from_file.fits,sha256=NA0kliz31FlLnYxv3ppzeruONqNYkuEvts5wzXEeIc4,8640 +numpy/_core/tests/data/umath-validation-set-README.txt,sha256=pxWwOaGGahaRd-AlAidDfocLyrAiDp0whf5hC7hYwqM,967 +numpy/_core/tests/data/umath-validation-set-arccos.csv,sha256=yBlz8r6RnnAYhdlobzGGo2FKY-DoSTQaP26y8138a3I,61365 +numpy/_core/tests/data/umath-validation-set-arccosh.csv,sha256=0GXe7XG1Z3jXAcK-OlEot_Df3MetDQSlbm3MJ__iMQk,61365 +numpy/_core/tests/data/umath-validation-set-arcsin.csv,sha256=w_Sv2NDn-mLZSAqb56JT2g4bqBzxYAihedWxHuf82uU,61339 +numpy/_core/tests/data/umath-validation-set-arcsinh.csv,sha256=DZrMYoZZZyM1DDyXNUxSlzx6bOgajnRSLWAzxcPck8k,60289 +numpy/_core/tests/data/umath-validation-set-arctan.csv,sha256=0aosXZ-9DYTop0lj4bfcBNwYVvjZdW13hbMRTRRTmV0,60305 +numpy/_core/tests/data/umath-validation-set-arctanh.csv,sha256=HEK9ePx1OkKrXIKkMUV0IxrmsDqIlgKddiI-LvF2J20,61339 +numpy/_core/tests/data/umath-validation-set-cbrt.csv,sha256=v855MTZih-fZp_GuEDst2qaIsxU4a7vlAbeIJy2xKpc,60846 +numpy/_core/tests/data/umath-validation-set-cos.csv,sha256=0PNnDqKkokZ7ERVDgbes8KNZc-ISJrZUlVZc5LkW18E,59122 +numpy/_core/tests/data/umath-validation-set-cosh.csv,sha256=JKC4nKr3wTzA_XNSiQvVUq9zkYy4djvtu2-j4ZZ_7Oc,60869 +numpy/_core/tests/data/umath-validation-set-exp.csv,sha256=rUAWIbvyeKh9rPfp2n0Zq7AKq_nvHpgbgzLjAllhsek,17491 +numpy/_core/tests/data/umath-validation-set-exp2.csv,sha256=djosT-3fTpiN_f_2WOumgMuuKgC_XhpVO-QsUFwI6uU,58624 +numpy/_core/tests/data/umath-validation-set-expm1.csv,sha256=K7jL6N4KQGX71fj5hvYkzcMXk7MmQes8FwrNfyrPpgU,60299 +numpy/_core/tests/data/umath-validation-set-log.csv,sha256=ynzbVbKxFzxWFwxHnxX7Fpm-va09oI3oK1_lTe19g4w,11692 +numpy/_core/tests/data/umath-validation-set-log10.csv,sha256=NOBD-rOWI_FPG4Vmbzu3JtX9UA838f2AaDFA-waiqGA,68922 +numpy/_core/tests/data/umath-validation-set-log1p.csv,sha256=tdbYWPqWIz8BEbIyklynh_tpQJzo970Edd4ek6DsPb8,60303 +numpy/_core/tests/data/umath-validation-set-log2.csv,sha256=39EUD0vFMbwyoXoOhgCmid6NeEAQU7Ff7QFjPsVObIE,68917 +numpy/_core/tests/data/umath-validation-set-sin.csv,sha256=8PUjnQ_YfmxFb42XJrvpvmkeSpEOlEXSmNvIK4VgfAM,58611 +numpy/_core/tests/data/umath-validation-set-sinh.csv,sha256=XOsBUuPcMjiO_pevMalpmd0iRv2gmnh9u7bV9ZLLg8I,60293 +numpy/_core/tests/data/umath-validation-set-tan.csv,sha256=Hv2WUMIscfvQJ5Y5BipuHk4oE4VY6QKbQp_kNRdCqYQ,60299 +numpy/_core/tests/data/umath-validation-set-tanh.csv,sha256=iolZF_MOyWRgYSa-SsD4df5mnyFK18zrICI740SWoTc,60299 +numpy/_core/tests/examples/cython/checks.pyx,sha256=7wt61LhY_j0ZPzKcWDKnnbtDR8PoHmQixpFYNlCwMOM,7900 +numpy/_core/tests/examples/cython/meson.build,sha256=uuXVPKemNVMQ5MiEDqS4BXhwGHa96JHjS50WxZuJS_8,1268 +numpy/_core/tests/examples/cython/setup.py,sha256=6k4eEMjzjXPhGAW440qpMp2S2l5Ltv-e9e-FnVnzl3w,857 +numpy/_core/tests/examples/limited_api/limited_api1.c,sha256=htSR9ER3S8AJqv4EZMsrxQ-SufTIlXNpuFI6MXQs87w,346 +numpy/_core/tests/examples/limited_api/limited_api2.pyx,sha256=1q4I59pdkCmMhLcYngN_XwQnPoLmDEo1uTGnhrLRjDc,203 +numpy/_core/tests/examples/limited_api/limited_api_latest.c,sha256=ltBLbrl1g9XxD2wvN_-g3NhIizc8mxnh2Z6wCyXo-8E,452 +numpy/_core/tests/examples/limited_api/meson.build,sha256=YM5RwW_waFymlWSHFhCCOHO6KCknooN0jCiqScL0i5M,1627 +numpy/_core/tests/examples/limited_api/setup.py,sha256=p2w7F1ardi_GRXSrnNIR8W1oeH_pgmw_1P2wS0A2I6M,435 +numpy/_core/tests/test__exceptions.py,sha256=PA9MhiaEITLOaIe86lnOwqAa3RFrA5Ra4IrqKXF-nMU,2881 +numpy/_core/tests/test_abc.py,sha256=mIZtCZ8PEIOd6pxLqdUws3wMfXUjsVO3vOE9vK5YPd8,2221 +numpy/_core/tests/test_api.py,sha256=aCh293oLPnbK7gi0PW_ilL9Gcr6-3UpO0MMzS39D8Sc,22930 +numpy/_core/tests/test_argparse.py,sha256=DRLQD5TxhudrQZ79hm5ds3eKsXh_Ub7QsvEYzsdDSX0,2824 +numpy/_core/tests/test_array_api_info.py,sha256=4CpUWnch1EtLojYabVAF7n_-Fks3QTODHERL2FzR1Ps,3062 +numpy/_core/tests/test_array_coercion.py,sha256=p-qWx0wju9JIwIC3wUrVFUJpi5FeOD88OljtzTzndmk,34833 +numpy/_core/tests/test_array_interface.py,sha256=9ND3Y00rgdBSgst5555zrzkvdWzZ4vZgWJOw3djXZAk,7767 +numpy/_core/tests/test_arraymethod.py,sha256=SL2PN10yYMp6C8CnKEykjit8QBtVBIGwbTPDdSDpCLY,3253 +numpy/_core/tests/test_arrayobject.py,sha256=aVv2eGjunCMEDFgmFujxMpk4xb-zo1MQrFcwQLfblx0,2596 +numpy/_core/tests/test_arrayprint.py,sha256=NKFx165-YwIw-sf7et1_M1cQ2V4t6nh8JN5N4GiohYw,49068 +numpy/_core/tests/test_casting_floatingpoint_errors.py,sha256=nnBEgeRIENrOOZvTzRK7SRYYW9dD6E6npDmIuN0ggCc,5074 +numpy/_core/tests/test_casting_unittests.py,sha256=iXHJR9sjpKk37toV9TMDYJAErVgqOxxEM-SEGOvdyF8,34308 +numpy/_core/tests/test_conversion_utils.py,sha256=fpduQ79yLpvZ8fdLs4H0CCsBEh3TlZs3SMr-lUQ6pTg,6605 +numpy/_core/tests/test_cpu_dispatcher.py,sha256=nqlgFk-Ocfgc18g-b4fprYssfcpReiyvgbWPzsNEoFI,1552 +numpy/_core/tests/test_cpu_features.py,sha256=WcKrpR7sPZkF7V-tALki9KfRaEJedE3WpA9AfXNE2Dw,15419 +numpy/_core/tests/test_custom_dtypes.py,sha256=_T9kvGbPJzjLnAtGqoRIeXQNjEuBgJ2DvLN6lrb-fJA,11623 +numpy/_core/tests/test_cython.py,sha256=G3usNUppvqvlbLqTBREn2II9_bhdlxfuZTg8EFd2LpU,8619 +numpy/_core/tests/test_datetime.py,sha256=KD9WAcYjDoa_dujH3lUQukb3IMyyPy2Gkf2oHm6sdOg,121671 +numpy/_core/tests/test_defchararray.py,sha256=tLrnS4oEVDwjbx74fHyi9r43yAE0J7mJZVfdeHvlSJg,30601 +numpy/_core/tests/test_deprecations.py,sha256=q6yJhSODzcbx6LmQzHJqtFKsW4_xfuuy0BC-RK4t6mI,28510 +numpy/_core/tests/test_dlpack.py,sha256=SQCgw4Ya2iYwEjEVJ0p_XvSYNKY2h_eygTmZp8-T4F8,5801 +numpy/_core/tests/test_dtype.py,sha256=lEpYwt2LZ0MWH3jGliiwLkeoqSi0iNI-KSEoAIwH9cg,77402 +numpy/_core/tests/test_einsum.py,sha256=zcFC5OFRGZA9r53gXKmFZUQV0o_T1BkdTXLZ8vG0YLA,52890 +numpy/_core/tests/test_errstate.py,sha256=5YUzK95WyepGyaJ4nkkXLUiHziNBoU0SFBHjMn5U7G0,4634 +numpy/_core/tests/test_extint128.py,sha256=tVrw3jMHQkA0ebk7Pnq33I5Yu9V24KNHotYIG3V8ds0,5644 +numpy/_core/tests/test_function_base.py,sha256=L_toIAG1hbAiOcRxIiLX7yxK4E-hqVMqdUGCBhg9dMQ,17462 +numpy/_core/tests/test_getlimits.py,sha256=xMcjRyx_hAwR-Q3qTcZSFhneZtIXp6u7KOsihUu7-Yg,6977 +numpy/_core/tests/test_half.py,sha256=EFzZNaNNY_H1hd3dSPBZ2wZt3E67D6KpDE3YaOMx_XY,24313 +numpy/_core/tests/test_hashtable.py,sha256=Ws1EeQWCf7vz8G_VsFTIZUVI-hgKXUEAbtQpvoBjBHo,1147 +numpy/_core/tests/test_indexerrors.py,sha256=wvatr7JlqAAYv-hHAAT-9DwUCnRcKiJ9qLcl6aKe9RU,4734 +numpy/_core/tests/test_indexing.py,sha256=xjJGHu7eZT_KX_LAL-8UBTFTxqFwZoJUZetQVrbjJ7g,55297 +numpy/_core/tests/test_item_selection.py,sha256=kI30kiX8mIrZYPn0jw3lGGw1ruZF4PpE9zw-aai9EPA,6458 +numpy/_core/tests/test_limited_api.py,sha256=ndfWEX3X4s6EqWSTDJzdOe0DDQGH7SqnTnYjce0cYh4,3304 +numpy/_core/tests/test_longdouble.py,sha256=H7VeOyaLfSMHClUDSKloOuHiDbZxeoypJnc5AtsM4xw,13890 +numpy/_core/tests/test_machar.py,sha256=eDTrzJgwfaus0Ts86-HR9YkAPOwOSOPImPTHugn1EOc,1069 +numpy/_core/tests/test_mem_overlap.py,sha256=jM7NXE3N_bOjgP9vMqyzzcIXJwbIREXiRK41iciggAA,29138 +numpy/_core/tests/test_mem_policy.py,sha256=JFou_8xT0-cwccZEQfaingaktY-RH3hrUJZa2_b7t2o,16660 +numpy/_core/tests/test_memmap.py,sha256=LQ4NBQe8s_5DMN5yCeY9dpqTeDBOge6TKN6xxMwCbRI,8142 +numpy/_core/tests/test_multiarray.py,sha256=YsNiZInPpHR1o6-sv7pq9sg4GW5J_v9KCnu1TNuDMIo,392270 +numpy/_core/tests/test_multithreading.py,sha256=DnSUipGmHE3YMI9Dgxfplo1HWyf1sjQgCcHIy41dTL4,8606 +numpy/_core/tests/test_nditer.py,sha256=o-YxH56efHb_yN5-kbJ3mDVpp4Vasa_DPE5lhEzcAc0,131186 +numpy/_core/tests/test_nep50_promotions.py,sha256=96WpsYYNdlaszFOCLmxHCg3iOHna4VPPxHZjdRp1lVU,10064 +numpy/_core/tests/test_numeric.py,sha256=_f1nQWujm2PQZF4Y9Gjxt4W7R0MbVNGJh9OEdjkKFCE,158490 +numpy/_core/tests/test_numerictypes.py,sha256=aADiXLPAkgAFF80_tRczhuH6lVyMLcA3k_AbGcDemp4,23292 +numpy/_core/tests/test_overrides.py,sha256=evrJX5mAWquq0lD6qM2Hn4_1_mkSk8cpNzUj6_QcZFE,27936 +numpy/_core/tests/test_print.py,sha256=mzUSbQ2kSa1aDl7NRUexj5UG4IM4zaZ-5EIoEoXhA_Q,6836 +numpy/_core/tests/test_protocols.py,sha256=6pxSZKmde5KHoN3iEMKReAFHrMldAm3ZZQwVh_kQ9Uw,1189 +numpy/_core/tests/test_records.py,sha256=eyDJb-oglohhgW4b4sZwe-_1PABhkM9_7a9qU3n7oAU,20534 +numpy/_core/tests/test_regression.py,sha256=o4FwvndFMYHPqYQgKuEjgIpoizZ3vvQ-3HIuHqiRD6g,95395 +numpy/_core/tests/test_scalar_ctors.py,sha256=3mhZlumKJs5WazhPgATWf5Y4E4POQy-bcUBSEt5pasc,6719 +numpy/_core/tests/test_scalar_methods.py,sha256=u0Bn-6-mSpOc_mP0C7BHpg3RbGWnsb_zZR1Ooubno2Y,9142 +numpy/_core/tests/test_scalarbuffer.py,sha256=EdiF5tVrZXDchoK0P5sbQgluyyYQCIrLCaxvafaCKNk,5582 +numpy/_core/tests/test_scalarinherit.py,sha256=XbCvtSSEU_c3cHi9Nxg7nt7itZdnREEh0sdqDUU4-ek,2588 +numpy/_core/tests/test_scalarmath.py,sha256=AKHil07nk1xDgcEUUvA3wRDR-xZjWwE2k1zvv6knOYI,46631 +numpy/_core/tests/test_scalarprint.py,sha256=UGxofUYFo3tqu-2fgaNgmS8K-uwhwv7X3tu7Pu7yeQQ,20635 +numpy/_core/tests/test_shape_base.py,sha256=u9ozYhzM-V0GINYi04jYeNsjiD7XtssrD29zhFVaOA0,30982 +numpy/_core/tests/test_simd.py,sha256=DJ-N-Q7E29VBY4VYmQWTR4XzRcxQKptCke5CwxCl_aw,48650 +numpy/_core/tests/test_simd_module.py,sha256=g0XWjB1TE4E0y4McOjkZKhR7OB-K01eqy4pJcGfU2zg,3903 +numpy/_core/tests/test_stringdtype.py,sha256=wgIoYRYlP-2Q2Z7PKBOo76fGbzKewxwN98IECfmBHiM,57658 +numpy/_core/tests/test_strings.py,sha256=UCq7ActPLrMNRG7BDHfrOH52MOZ3uy3Tp35T3-hQV00,51787 +numpy/_core/tests/test_ufunc.py,sha256=qiV2wkNG0-Z2_u_aveRLKI9qEOqaLxyWvch6Btz-Urc,132405 +numpy/_core/tests/test_umath.py,sha256=qeEIqnjBl7_mHhBZh6-S_7oBz94nabMyS-xqdQOXl9o,193188 +numpy/_core/tests/test_umath_accuracy.py,sha256=TRSzuQJ2kN2D3BUQ3IX1WhhT6ttIKvnnaMaaqU-A7ug,5472 +numpy/_core/tests/test_umath_complex.py,sha256=pWRHpzBodvDGoKG1gkRAKJ1uPxQ_fV_VqIm77SD0BlA,23290 +numpy/_core/tests/test_unicode.py,sha256=LotRRPbJke99uyy3uY3rAteaJMMiYpSzcOmargPNKIc,12854 +numpy/_core/umath.py,sha256=OsbavmLRxKNNbV8SnPEc3mVNk9EIVjMhZeRs9nCUsTU,2093 +numpy/_core/umath.pyi,sha256=FIqmlQwQIueIrs-_QehV3guNEnJE2LxVs3NPCj38Vdo,2643 +numpy/_distributor_init.py,sha256=IKy2THwmu5UgBjtVbwbD9H-Ap8uaUJoPJ2btQ4Jatdo,407 +numpy/_distributor_init.pyi,sha256=6IvMzAmr0-Z6oqTkZcgXgrkJrQXVMjBih2AZvLdDgOE,27 +numpy/_expired_attrs_2_0.py,sha256=ZTV3IpeE4UcJSn2RTZLxKAixEl557MkKK4R7xubw1Rw,3903 +numpy/_expired_attrs_2_0.pyi,sha256=dDjT_qRjSq9m3_DcfOJlRaTzFtHacBVRdkYgA0Weeho,1269 +numpy/_globals.py,sha256=XVuUPpFLueqKUTNwqiOjWWahnM-vGxGy4tYA3ph-EAE,3090 +numpy/_globals.pyi,sha256=IrHHIXmibXzgK0VUlECQLw4IEkveXSHo_ZWnTkfnLe4,280 +numpy/_pyinstaller/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/_pyinstaller/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/_pyinstaller/hook-numpy.py,sha256=Ood-XcWlQQkk90SY0yDg7RKsUFVGwas9TqI-Gbc58_s,1393 +numpy/_pyinstaller/hook-numpy.pyi,sha256=tAvtMPovoi-sur0D1NAo3_evSmYKLTh0bgRSC7QrCIk,349 +numpy/_pyinstaller/tests/__init__.py,sha256=IJtzzjPSw419P-c2T4OT48p-Zu4JohoF9svWqhDshgk,329 +numpy/_pyinstaller/tests/pyinstaller-smoke.py,sha256=6iL-eHMQaG3rxnS5EgcvrCqElm9aKL07Cjr1FZJSXls,1143 +numpy/_pyinstaller/tests/test_pyinstaller.py,sha256=8K-7QxmfoXCG0NwR0bhIgCNrDjGlrTzWnrR1sR8btgU,1135 +numpy/_pytesttester.py,sha256=itUxMEXdYQT_mCYqde-7CqjxOA59wiLFyJeIyoVtGgI,6325 +numpy/_pytesttester.pyi,sha256=fRkDNxl5obspW99ujQV3NDXrROXxDiLVFyj8Aew_zyk,497 +numpy/_typing/__init__.py,sha256=0y70ouUj2_lKGcA6vGbm_NWVR48xKoyu_c7rom_AEp4,5047 +numpy/_typing/_add_docstring.py,sha256=GHU_gjWt_A6x7RIcztvfayVCs78Kgi8IeNKJZyfWkWg,3995 +numpy/_typing/_array_like.py,sha256=QD4uxTyvuMERM5AhE6PxzdL5yHUMb2UOi7HdQFFNXoI,5565 +numpy/_typing/_callable.pyi,sha256=bogxuArAdYY-IGWzw0-ayhdb5-P8YhHXK-J0TX_j38g,11811 +numpy/_typing/_char_codes.py,sha256=RJSvAIAy8TAEQbFfoDNouUdLcYngmBmV4X7At62SUbU,8786 +numpy/_typing/_dtype_like.py,sha256=3q7Me_RXr75ba4p1vPy-nw5NRLWsnCnHsfzVGnZMNig,5964 +numpy/_typing/_extended_precision.py,sha256=dGios-1k-QBGew7YFzONZTzVWxz-aYAaqlccl2_h5Bo,777 +numpy/_typing/_nbit.py,sha256=LiAPuMPddJ9CjSStw8zvXQ1m_FbNIzl_iMygO851M0g,632 +numpy/_typing/_nbit_base.py,sha256=HHn2zYWN-3wLsyigd97cs9uyI3NvRYUcQ69OLOdC-ks,2880 +numpy/_typing/_nested_sequence.py,sha256=7idN0EyEI6Nt0VH9xnWVj4syqeu_LK8IESZwczVcK1g,2608 +numpy/_typing/_scalars.py,sha256=9v-1xahC9TZg28FTfBG15vWCcnDB1bfWz7ejT0eDrVw,1031 +numpy/_typing/_shape.py,sha256=fY1qi6UDFjPW1b4GaxhcJ9tRAQu6SXLZINd_Vy60XSY,231 +numpy/_typing/_ufunc.py,sha256=U6OCdDLHzXSt1fbSldHFP0viWHh4u3Y1CDBvzBUY8-M,153 +numpy/_typing/_ufunc.pyi,sha256=h4Gs_FASSm7e_lrJWmsJazZOvZMr_N0XSzrVXeA8jAo,26709 +numpy/_utils/__init__.py,sha256=fDuc2LsC4olo0utoWjAs3LXux-gPYHFKhThlEIi4eOQ,3291 +numpy/_utils/__init__.pyi,sha256=E4kbvhiLuJeW77FvO87VVMcYEazVQy7eTle-7HUU1jc,738 +numpy/_utils/_convertions.py,sha256=0xMxdeLOziDmHsRM_8luEh4S-kQdMoMg6GxNDDas69k,329 +numpy/_utils/_convertions.pyi,sha256=4l-0UmPCyVA70UJ8WAd2A45HrKFSzgC0sFDBSnKcYiQ,118 +numpy/_utils/_inspect.py,sha256=LcbHUJ2KPDpPeNixyIeKOUWvORaLG5J-H0uI3iHIsOA,7435 +numpy/_utils/_inspect.pyi,sha256=hqpbcKWZzVkTaMf6loQup3ZMXifIit-A0vSIhD92D88,2255 +numpy/_utils/_pep440.py,sha256=Vr7B3QsijR5p6h8YAz2LjNGUyzHUJ5gZ4v26NpZAKDc,14069 +numpy/_utils/_pep440.pyi,sha256=xzYJoZ6DnjvgaKr8OsBwim77fAJ0xeQJI9XAt75gvfI,3870 +numpy/char/__init__.py,sha256=WGpEng-lsHKxUlmuANY8hKCl3ZC622HYSAFnpf7sgUE,93 +numpy/char/__init__.pyi,sha256=s5kfrSM9fwhtbUmzC-KlCoA4AyKpR0GzeS45ZoyQkbA,1539 +numpy/compat/__init__.py,sha256=b3rw1J_V3MwU-LZf8uISRKvfXzFaBjFHACbgyLo785Y,727 +numpy/compat/py3k.py,sha256=2jk3PPVI2LB1v4mndi0Ydb-ymcgXzJ5G2hIdvoWavAI,3803 +numpy/compat/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/conftest.py,sha256=G-BY__VpzWy3NY7KjDvHW01CyGkWx-znx2WlhiUShy8,8717 +numpy/core/__init__.py,sha256=FWRkekGqZ1NF4YYNfm46mOAO9u3v4ZYts_lc8ygQfqY,1275 +numpy/core/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/core/_dtype.py,sha256=3SnNsjxlKobD8Dn8B9egjIQuQLdbWz9OtVAZ4_wlDw8,322 +numpy/core/_dtype.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/core/_dtype_ctypes.py,sha256=lLzxauA8PVnopTuGh9USt1nVw2qCI8Z7bL66er3JoHU,350 +numpy/core/_dtype_ctypes.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/core/_internal.py,sha256=f3eVtRx2tKrJxxavZNe_f1Ln-_1shhSlfeRZEDTlxhU,947 +numpy/core/_multiarray_umath.py,sha256=Yb0HORec_wcEV3RNNU4RZnlATYTUQtjAHMYmL4pvNLs,2096 +numpy/core/_utils.py,sha256=5fk18JN43Rg6YHvan6QjdrOeOuLtRlLVmP6MadBEJVA,923 +numpy/core/arrayprint.py,sha256=a1DkStlBSsVViSJw523Mm-lboVaAtCloBNCrigyOpbI,338 +numpy/core/defchararray.py,sha256=G9S6jkdXegRkXl58hSpPnmndjdym4801Yzq2lzzmApM,346 +numpy/core/einsumfunc.py,sha256=px-rSPkwAMbRNmp5uILgVC2QSr73InKFfvW7LSfNGGw,338 +numpy/core/fromnumeric.py,sha256=aNquLnfZX1XZRAz5MJza5ZT7IlgJo0TMHlR62YT2biM,342 +numpy/core/function_base.py,sha256=Sa9Ec2Y21kPmjn4Xsh7Y1V1c7bUdxYjzixIwHZJ4sCo,350 +numpy/core/getlimits.py,sha256=aYJVaVqiSGKuPfSIa7r0MMZMQkJP2NRNJ7Zd2dszygU,334 +numpy/core/multiarray.py,sha256=SwVF8KNm29qyaq7vx8rrljNNxfn0e6G5y1H830n1Rac,792 +numpy/core/numeric.py,sha256=LSuzJ9OsQ0IEpW2rKlAwuvNypZeDZ0AJDoJOt93XB-k,359 +numpy/core/numerictypes.py,sha256=RvhfWFh9KR0SPDNcrAYnW-PO9TKAND75ONXhL5Djs8Q,346 +numpy/core/overrides.py,sha256=sWaAgbH_piO0mWDeVqqoqkFqqpPHM87FqOZFJ3AO8lU,334 +numpy/core/overrides.pyi,sha256=-3xfjHfa4UaCuhTVwwRN4EOM5uz9vZR0gMeTVvEdbYI,525 +numpy/core/records.py,sha256=j9BftQLLljVdcENT41eGflG7DA7miXQ7q3Yf53-zYcY,326 +numpy/core/shape_base.py,sha256=MhuxPRwwg5hIdHcJ-LABdQ0oYEYGVxeD-aomaFs9-f4,338 +numpy/core/umath.py,sha256=f6KbsWYh5oTj3_FWHip_dr51BdczTAtMqgpn9_eHcz4,318 +numpy/ctypeslib.py,sha256=AhgVVThYHjfMEccnSDfH2B3puHU6ZjPwxPcIuFSnzRA,18836 +numpy/ctypeslib.pyi,sha256=I21gEirYRu9BQTndIJ_hwOfHbKxs13GL6A6ndpvWT8Y,8088 +numpy/distutils/__init__.py,sha256=BU1C21439HRo7yH1SsN9me6WCDPpOwRQ37ZpNwDMqCw,2074 +numpy/distutils/__init__.pyi,sha256=D8LRE6BNOmuBGO-oakJGnjT9UJTk9zSR5rxMfZzlX64,119 +numpy/distutils/__pycache__/conv_template.cpython-310.pyc,sha256=PiBXMljlRFoF3SNzw4aG2asII_YzQ0kUusNTexSBz8U,8270 +numpy/distutils/_shell_utils.py,sha256=3G7QGZXCxJQ6-2l1BTu3G_dRrWe6nT4QLlGYeh5oNZk,2538 +numpy/distutils/armccompiler.py,sha256=8qUaYh8QHOJlz7MNvkuJNyYdCOCivuW0pbmf_2OPZu0,962 +numpy/distutils/ccompiler.py,sha256=VV55UeGMGahNVPIIJO6YlgXmL6MqUrDOPR7Bk6HDseQ,28690 +numpy/distutils/ccompiler_opt.py,sha256=-q1HcO9nN3-m3mdYeSyU1QEv2HgD-YDpFZLEBWzOHTA,100396 +numpy/distutils/checks/cpu_asimd.c,sha256=nXUsTLrSlhRL-UzDM8zMqn1uqJnR7TRlJi3Ixqw539w,818 +numpy/distutils/checks/cpu_asimddp.c,sha256=E4b9zT1IdSfGR2ACZJiQoR-BqaeDtzFqRNW8lBOXAaY,432 +numpy/distutils/checks/cpu_asimdfhm.c,sha256=6tXINVEpmA-lYRSbL6CrBu2ejNFmd9WONFGgg-JFXZE,529 +numpy/distutils/checks/cpu_asimdhp.c,sha256=SfwrEEA_091tmyI4vN3BNLs7ypUnrF_VbTg6gPl-ocs,379 +numpy/distutils/checks/cpu_avx.c,sha256=LuZW8o93VZZi7cYEP30dvKWTm7Mw1TLmCt5UaXDxCJg,779 +numpy/distutils/checks/cpu_avx2.c,sha256=jlDlea393op0JOiMJgmmPyKmyAXztLcObPOp9F9FaS0,749 +numpy/distutils/checks/cpu_avx512_clx.c,sha256=P-YHjj2XE4SithBkPwDgShOxGWnVSNUXg72h8O3kpbs,842 +numpy/distutils/checks/cpu_avx512_cnl.c,sha256=f_c2Z0xwAKTJeK3RYMIp1dgXYV8QyeOxUgKkMht4qko,948 +numpy/distutils/checks/cpu_avx512_icl.c,sha256=isI35-gm7Hqn2Qink5hP1XHWlh52a5vwKhEdW_CRviE,1004 +numpy/distutils/checks/cpu_avx512_knl.c,sha256=PVTkczTpHlXbTc7IQKlCFU9Cq4VGG-_JhVnT0_n-t1A,959 +numpy/distutils/checks/cpu_avx512_knm.c,sha256=eszPGr3XC9Js7mQUB0gFxlrNjQwfucQFz_UwFyNLjes,1132 +numpy/distutils/checks/cpu_avx512_skx.c,sha256=59VD8ebEJJHLlbY-4dakZV34bmq_lr9mBKz8BAcsdYc,1010 +numpy/distutils/checks/cpu_avx512_spr.c,sha256=i8DpADB8ZhIucKc8lt9JfYbQANRvR67u59oQf5winvg,904 +numpy/distutils/checks/cpu_avx512cd.c,sha256=Qfh5FJUv9ZWd_P5zxkvYYIkvqsPptgaDuKkeX_F8vyA,759 +numpy/distutils/checks/cpu_avx512f.c,sha256=d97NRcbJhqpvURnw7zyG0TOuEijKXvU0g4qOTWHbwxY,755 +numpy/distutils/checks/cpu_f16c.c,sha256=nzZzpUc8AfTtw-INR3KOxcjx9pyzVUM8OhsrdH2dO_w,868 +numpy/distutils/checks/cpu_fma3.c,sha256=YN6IDwuZALJHVVmpQ2tj-14HI_PcxH_giV8-XjzlmkU,817 +numpy/distutils/checks/cpu_fma4.c,sha256=qKdgTNNFg-n8vSB1Txco60HBLCcOi1aH23gZOX7yKqs,301 +numpy/distutils/checks/cpu_neon.c,sha256=Y0SjuVLzh3upcbY47igHjmKgjHbXxbvzncwB7acfjxw,600 +numpy/distutils/checks/cpu_neon_fp16.c,sha256=E7YOGyYP41u1sqiCHpCGGqjmo7Cs6yUkmJ46K7LZloc,251 +numpy/distutils/checks/cpu_neon_vfpv4.c,sha256=qFY1C_fQYz7M_a_8j0KTdn7vaE3NNVmWY2JGArDGM3w,609 +numpy/distutils/checks/cpu_popcnt.c,sha256=vRcXHVw2j1F9I_07eIZ_xzDX3fd3mqgiQXL1w3pULJk,1049 +numpy/distutils/checks/cpu_rvv.c,sha256=ADmogrRu7XOOsCfB6PMpF0ES4yv8tXsbYduvZjEMTPA,300 +numpy/distutils/checks/cpu_sse.c,sha256=6MHITtC76UpSR9uh0SiURpnkpPkLzT5tbrcXT4xBFxo,686 +numpy/distutils/checks/cpu_sse2.c,sha256=yUZzdjDtBS-vYlhfP-pEzj3m0UPmgZs-hA99TZAEACU,697 +numpy/distutils/checks/cpu_sse3.c,sha256=j5XRHumUuccgN9XPZyjWUUqkq8Nu8XCSWmvUhmJTJ08,689 +numpy/distutils/checks/cpu_sse41.c,sha256=y_k81P-1b-Hx8OeRVDE9V1O9JakS0zPvlFKJ3VbSmEw,675 +numpy/distutils/checks/cpu_sse42.c,sha256=3PXucdI2mII-txO7zFN99TlVveT_QUAETTGvRk-_hYw,692 +numpy/distutils/checks/cpu_ssse3.c,sha256=X6VWxIXMRpdSCBsHPXvot3yTZ4d5yK9Bi1ScQP3WC-Q,705 +numpy/distutils/checks/cpu_sve.c,sha256=Ixj6TJHCdn7h_xE3MWviXrxlvo0OZkKDTT6sFIwNZPY,287 +numpy/distutils/checks/cpu_vsx.c,sha256=FVmR4iliKjcihzMCwloR1F2JYwSZK9P4f_hvIRLHSDQ,478 +numpy/distutils/checks/cpu_vsx2.c,sha256=yESs25Rt5ztb5-stuYbu3TbiyJKmllMpMLu01GOAHqE,263 +numpy/distutils/checks/cpu_vsx3.c,sha256=omC50tbEZNigsKMFPtE3zGRlIS2VuDTm3vZ9TBZWo4U,250 +numpy/distutils/checks/cpu_vsx4.c,sha256=ngezA1KuINqJkLAcMrZJR7bM0IeA25U6I-a5aISGXJo,305 +numpy/distutils/checks/cpu_vx.c,sha256=OpLU6jIfwvGJR4JPVVZLlUfvo7oAZ0YvsjafM2qtPlk,461 +numpy/distutils/checks/cpu_vxe.c,sha256=rYW_nKwXnlB0b8xCrJEr4TmvrEvS-NToxwyqqOHV8Bk,788 +numpy/distutils/checks/cpu_vxe2.c,sha256=Hv4wO23kwC2G6lqqercq4NE4K0nrvBxR7RIzr5HTXCc,624 +numpy/distutils/checks/cpu_xop.c,sha256=7uabsGeqvmVJQvuSEjs8-Sm8kpmvl6uZ9YHMF5h2opQ,234 +numpy/distutils/checks/extra_avx512bw_mask.c,sha256=pVPOhcu80yJVnIhOcHHXOlZ2proJ1MUf0XgccqhPoNk,636 +numpy/distutils/checks/extra_avx512dq_mask.c,sha256=nMfIvepISGFDexPrMYl5LWtdmt6Uy9TKPzF4BVayw2I,504 +numpy/distutils/checks/extra_avx512f_reduce.c,sha256=_NfbtfSAkm_A67umjR1oEb9yRnBL5EnTA76fvQIuNVk,1595 +numpy/distutils/checks/extra_vsx3_half_double.c,sha256=shHvIQZfR0o-sNefOt49BOh4WCmA0BpJvj4b7F9UdvQ,354 +numpy/distutils/checks/extra_vsx4_mma.c,sha256=GiQGZ9-6wYTgH42bJgSlXhWcTIrkjh5xv4uymj6rglk,499 +numpy/distutils/checks/extra_vsx_asm.c,sha256=BngiMVS9nyr22z6zMrOrHLeCloe_5luXhf5T5mYucgI,945 +numpy/distutils/checks/test_flags.c,sha256=uAIbhfAhyGe4nTdK_mZmoCefj9P0TGHNF9AUv_Cdx5A,16 +numpy/distutils/command/__init__.py,sha256=fW49zUB3syMFsKpf1oRBO0h8tmnTwRP3zUPrsB0R22M,1032 +numpy/distutils/command/autodist.py,sha256=8KWwr5mnjX20UpY4ITRDx-PreApyh9M7B92IwsEtTsQ,3718 +numpy/distutils/command/bdist_rpm.py,sha256=-tkZupIJr_jLqeX7xbRhE8-COXHRI0GoRpAKchVte54,709 +numpy/distutils/command/build.py,sha256=aj1SUGsDUTxs4Tch2ALLcPnuAVhaPjEPIZIobzMajm0,2613 +numpy/distutils/command/build_clib.py,sha256=TCuZDpRd8ZPZH6SRwIZcWZC3aoGc18Rll6FYcawS6qY,19317 +numpy/distutils/command/build_ext.py,sha256=UcyG8KKyrd5v1s6qDdKEkzwLwmoMlfHA893Lj-OOgl0,32983 +numpy/distutils/command/build_py.py,sha256=XiLZ2d_tmCE8uG5VAU5OK2zlzQayBfeY4l8FFEltbig,1144 +numpy/distutils/command/build_scripts.py,sha256=P2ytmZb3UpwfmbMXkFB2iMQk15tNUCynzMATllmp-Gs,1665 +numpy/distutils/command/build_src.py,sha256=sxsnfc8KBsnsSvI-8sKIKNo2KA2uvrrvW0WYZCqyjyk,31178 +numpy/distutils/command/config.py,sha256=etJCBJusXp-yzPodZnCBW0NJgxPNhv-FRTon6uV761E,20670 +numpy/distutils/command/config_compiler.py,sha256=N6JHVRAwgzkEsHqK8tqziLPlwbfWvdHaEdPv_sklkHc,4371 +numpy/distutils/command/develop.py,sha256=9SbbnFnVbSJVZxTFoV9pwlOcM1D30GnOWm2QonQDvHI,575 +numpy/distutils/command/egg_info.py,sha256=i-Zk4sftK5cMQVQ2jqSxTMpVI-gYyXN16-p5TvmjURc,921 +numpy/distutils/command/install.py,sha256=nkW2fl7OABcE3sUcoNM7iONkF64CBESdVlRjTLg3hVA,3073 +numpy/distutils/command/install_clib.py,sha256=1xv0_lPVu3g16GgICjjlh7T8zQ6PSlevCuq8Bocx5YM,1399 +numpy/distutils/command/install_data.py,sha256=Y59EBG61MWP_5C8XJvSCVfzYpMNVNVcH_Z6c0qgr9KA,848 +numpy/distutils/command/install_headers.py,sha256=LD_b1bRoprrOOErq2V8DvY8ydFa6KALyi5_fnWymCxc,920 +numpy/distutils/command/sdist.py,sha256=8Tsju1RwXNbPyQcjv8GRMFveFQqYlbNdSZh2X1OV-VU,733 +numpy/distutils/conv_template.py,sha256=F-4vkkfAjCb-fN79WYrXX3BMHMoiQO-W2u09q12OPuI,9536 +numpy/distutils/core.py,sha256=QBJNJdIE0a9Rr4lo-3QnmEaWyVV068l6HbVPdJ75iZg,8173 +numpy/distutils/cpuinfo.py,sha256=XuNhsx_-tyrui_AOgn10yfZ9p4YBM68vW2_bGmKj07I,22639 +numpy/distutils/exec_command.py,sha256=pNi8PhDX_BLc6CspovWMkhbeAQ1vQDlsGZNH8uNKptM,10282 +numpy/distutils/extension.py,sha256=g2Dei8GIkhrKpWttKkgQoVD6707pcx93MhhFt85Z89k,3460 +numpy/distutils/fcompiler/__init__.py,sha256=DqfaiKGVagOFuL0v3VZxZZkRnWWvly0_lYHuLjaZTBo,40625 +numpy/distutils/fcompiler/absoft.py,sha256=yPUHBNZHOr_gxnte16I_X85o1iL9FI4RLHjG9JOuyYU,5516 +numpy/distutils/fcompiler/arm.py,sha256=MCri346qo1bYwjlm32xHRyRl-bAINTlfVIubN6HDz68,2090 +numpy/distutils/fcompiler/compaq.py,sha256=sjU2GKHJGuChtRb_MhnouMqvkIOQflmowFE6ErCWZhE,3903 +numpy/distutils/fcompiler/environment.py,sha256=DOD2FtKDk6O9k6U0h9UKWQ-65wU8z1tSPn3gUlRwCso,3080 +numpy/distutils/fcompiler/fujitsu.py,sha256=yK3wdHoF5qq25UcnIM6FzTXsJGJxdfKa_f__t04Ne7M,1333 +numpy/distutils/fcompiler/g95.py,sha256=FH4uww6re50OUT_BfdoWSLCDUqk8LvmQ2_j5RhF5nLQ,1330 +numpy/distutils/fcompiler/gnu.py,sha256=ag8v_pp-fYpDPKJsVmNaFwN621b1MFQAxew0T1KdE_Y,20502 +numpy/distutils/fcompiler/hpux.py,sha256=gloUjWGo7MgJmukorDq7ZxDnnUKXx-C6AQfryQshVM4,1353 +numpy/distutils/fcompiler/ibm.py,sha256=Ts2PXg2ocrXtX9eguvcHeQ4JB2ktpd5isXtRTpU9F5Y,3534 +numpy/distutils/fcompiler/intel.py,sha256=XYF0GLVhJWjS8noEx4TJ704Eqt-JGBolRZEOkwgNItE,6570 +numpy/distutils/fcompiler/lahey.py,sha256=U63KMfN8zDAd_jnvMkS2N-dvP4UiSRB9Ces290qLNXw,1327 +numpy/distutils/fcompiler/mips.py,sha256=LAwT0DY5yqlYh20hNMYR1-OKu8A9GNw-TbUfI8pvglM,1714 +numpy/distutils/fcompiler/nag.py,sha256=9pQCMUlwjRVHGKwZxvwd4bW5p-9v7VXcflELEImHg1g,2777 +numpy/distutils/fcompiler/none.py,sha256=6RX2X-mV1HuhJZnVfQmDmLVhIUWseIT4P5wf3rdLq9Y,758 +numpy/distutils/fcompiler/nv.py,sha256=NfU4vbXVBiV5FUG69NQciO61T-dFPB6N0Zd0zD8d4eY,1541 +numpy/distutils/fcompiler/pathf95.py,sha256=MiHVar6-beUEYVEpqXORIX4f8G29I47D36kreltdfoQ,1061 +numpy/distutils/fcompiler/pg.py,sha256=NOB1stzrjvQMZS7bIPTgWTcAFe3cjNveA5-SztUZqD0,3568 +numpy/distutils/fcompiler/sun.py,sha256=mfS3RTj9uYT6K9Ikp8RjmsEPIWAtUTzMhX9sGjEyF6I,1577 +numpy/distutils/fcompiler/vast.py,sha256=Xuxa4sNraUPcQmt45SogAfN0kDHFb6C73uNZNmX3RBE,1667 +numpy/distutils/from_template.py,sha256=hpoFQortsLZdMSr_fJILzXzrIwFlZoFjsDSo6jNtvWs,7913 +numpy/distutils/fujitsuccompiler.py,sha256=JDuUUE-GyPahkNnDZLWNHyAmJ2lJPCnLuIUFfHkjMzA,834 +numpy/distutils/intelccompiler.py,sha256=oBZ6MKmPP-RS-UrDvsxy7PAYgxE3pRykcZfrCpoDoas,4022 +numpy/distutils/lib2def.py,sha256=-3rDf9FXsDik3-Qpp-A6N_cYZKTlmVjVi4Jzyo-pSlY,3630 +numpy/distutils/line_endings.py,sha256=a8ZZECrPRffsbs0UygeR47_fOUlZppnx-QPssrIXtB0,2032 +numpy/distutils/log.py,sha256=m8caNBwPhIG7YTnD9iq9jjc6_yJOeU9FHuau2CSulds,2879 +numpy/distutils/mingw/gfortran_vs2003_hack.c,sha256=cbsN3Lk9Hkwzr9c-yOP2xEBg1_ml1X7nwAMDWxGjzc8,77 +numpy/distutils/mingw32ccompiler.py,sha256=RZR2jEjsrVq3iLVKSkQnWIdIA4cokiUUwl0JO2TdPYk,22151 +numpy/distutils/misc_util.py,sha256=pu-AikNhpbmHmGvq5uhcHAdRegvc0jrY5O8JI1M_xj8,89239 +numpy/distutils/msvc9compiler.py,sha256=FCtP7g34AVuMIaqQlH8AV1ZBdIUXbk5G7eBeeTSr1zE,2192 +numpy/distutils/msvccompiler.py,sha256=ILookUifVJF9tAtPJoVCqZ673m5od6MVKuAHuA3Rcfk,2647 +numpy/distutils/npy_pkg_config.py,sha256=LWpcvPQ4ZuGmKO0lrqQHZHAhBe87gTT1Rf6vX0NtZQM,13018 +numpy/distutils/numpy_distribution.py,sha256=10Urolg1aDAG0EHYfcvObzOgqRV0ARh2GhDklEg4vS0,634 +numpy/distutils/pathccompiler.py,sha256=KnJEA5H4cXg7SLrMjwWtidD24VSvOdu72d17votiY9E,713 +numpy/distutils/system_info.py,sha256=kWwNarHCP-D5Qi2q_8WiUSs_ILOo270FpFWOn_JjCtw,113904 +numpy/distutils/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/distutils/tests/test_build_ext.py,sha256=kaKh51tQSetUr4ozxICwUUjOasSXHrg1MCzJAVDNbWY,2779 +numpy/distutils/tests/test_ccompiler_opt.py,sha256=N3pN-9gxPY1KvvMEjoXr7kLxTGN8aQOr8qo5gmlrm90,28778 +numpy/distutils/tests/test_ccompiler_opt_conf.py,sha256=maXytv39amuojbQIieIGIXMV4Cv-s0fsPMZeFEh9XyY,6347 +numpy/distutils/tests/test_exec_command.py,sha256=BK-hHfIIrkCep-jNmS5_Cwq5oESvsvX3V_0XDAkT1Ok,7395 +numpy/distutils/tests/test_fcompiler.py,sha256=mJXezTXDUbduhCwVGAfABHpEARWhnj8hLW9EOU3rn84,1277 +numpy/distutils/tests/test_fcompiler_gnu.py,sha256=nmfaFCVzbViIOQ2-MjgXt-bN8Uj674hCgiwr5Iol-_U,2136 +numpy/distutils/tests/test_fcompiler_intel.py,sha256=mxkfFD2rNfg8nn1pp_413S0uCdYXydPWBcz9ilgGkA0,1058 +numpy/distutils/tests/test_fcompiler_nagfor.py,sha256=CKEjik7YVfSJGL4abuctkmlkIUhAhv-x2aUcXiTR9b0,1102 +numpy/distutils/tests/test_from_template.py,sha256=SDYoe0XUpAayyEQDq7ZhrvEEz7U9upJDLYzhcdoVifc,1103 +numpy/distutils/tests/test_log.py,sha256=0tSM4q-00CjbMIRb9QOJzI4A7GHUiRGOG1SOOLz8dnM,868 +numpy/distutils/tests/test_mingw32ccompiler.py,sha256=rMC8-IyBOiuZVfAoklV_KnD9qVeB_hFVvb5dStxfk08,1609 +numpy/distutils/tests/test_misc_util.py,sha256=xjNaYJ4Ev5YjokxM8J_T2z2oGTzUSs-wCh9ZqO9RNmg,3364 +numpy/distutils/tests/test_npy_pkg_config.py,sha256=apGrmViPcXoPCEOgDthJgL13C9N0qQMs392QjZDxJd4,2557 +numpy/distutils/tests/test_shell_utils.py,sha256=UKU_t5oIa_kVMv89Ys9KN6Z_Fy5beqPDUsDAWPmcoR8,2114 +numpy/distutils/tests/test_system_info.py,sha256=wMV7bH5oB0luLDR2tunHrLaUxsD_-sIhLnNpj1blQPs,11405 +numpy/distutils/tests/utilities.py,sha256=pyfnVJJ7ZprjC2EETB6iFHYMkQeKsZbq1jVQR3cIrws,2287 +numpy/distutils/unixccompiler.py,sha256=fN4-LH6JJp44SLE7JkdG2kKQlK4LC8zuUpVC-RtmJ-U,5426 +numpy/doc/ufuncs.py,sha256=9xt8H34GhrXrFq9cWFUGvJFePa9YuH9Tq1DzAnm2E2E,5414 +numpy/dtypes.py,sha256=zuPwgC0ijF2oDRAOJ6I9JKhaJuhXFAygByLQaoVtT54,1312 +numpy/dtypes.pyi,sha256=BYyUPY0MKF7EzspiOss_FaxqEEzmd0dEpsvGySRfSek,15180 +numpy/exceptions.py,sha256=2EH3OwDVoJtAsRODuGlnLWA1hrjDniolCVkR87-eHIo,7838 +numpy/exceptions.pyi,sha256=rVue0Qxt3GG40b5xKlj0r_JFjbX6s-bPP7YlqdQlvv0,751 +numpy/f2py/__init__.py,sha256=hz6c1M2csKnlKPWbKIDcpSo0cbT5V0UPhQYkELi8zEw,2503 +numpy/f2py/__init__.pyi,sha256=uxcZnHA75gxBi50Z3OTWYSYZaeIuWFQv2Dl0F8_WX-g,1061 +numpy/f2py/__main__.py,sha256=6i2jVH2fPriV1aocTY_dUFvWK18qa-zjpnISA-OpF3w,130 +numpy/f2py/__version__.py,sha256=7HHdjR82FCBmftwMRyrlhcEj-8mGQb6oCH-wlUPH4Nw,34 +numpy/f2py/_backends/__init__.py,sha256=7_bA7c_xDpLc4_8vPfH32-Lxn9fcUTgjQ25srdvwvAM,299 +numpy/f2py/_backends/_backend.py,sha256=GKb9-UaFszT045vUgVukPs1n97iyyjqahrWKxLOKNYo,1187 +numpy/f2py/_backends/_distutils.py,sha256=whJ4xqPet1PffVOcR6W_2NF8yR4LLDh3pZLrKkl0Rh4,2384 +numpy/f2py/_backends/_meson.py,sha256=xRGHWhdQJIs1-c3fHeeGHL50XyjU6NjX4-Wp3gjldMY,8089 +numpy/f2py/_backends/meson.build.template,sha256=hQeTapAY0xtni5Li-QaEtWx9DH9WDKah2lcEuSZfLLo,1599 +numpy/f2py/_isocbind.py,sha256=zaBgpfPNRmxVG3doUIlbZIiyB990MsXiwDabrSj9HnQ,2360 +numpy/f2py/_src_pyf.py,sha256=4Qx_-SQSsDh-ggNw3dmHTLASgu1dUY670_Z06WY8clM,7664 +numpy/f2py/auxfuncs.py,sha256=PSpBh067SNG1XUJNHqCLpxiorTieeuVTj5h8tOTfXeE,27020 +numpy/f2py/capi_maps.py,sha256=MTHjWUSTBngVZtyULdBe1QxAGq9IrxNV8OthujKKr0w,30607 +numpy/f2py/cb_rules.py,sha256=fSxXAxjNaPXt54E957v1-Q3oCM06vbST5gFu1D98ic4,25004 +numpy/f2py/cfuncs.py,sha256=Jz-em0GDHjexh8FiVEYccAMV4xB5Bp9kQVUMM1uBNcY,52484 +numpy/f2py/common_rules.py,sha256=gHB76WypbkVmhaD_RWhy8Od4zDTgj8cbDOdUdIp6PIQ,5131 +numpy/f2py/crackfortran.py,sha256=KfTsGcO947ziTwz9UTmrfyXLbqXGIngrMRkso2C0v5E,148095 +numpy/f2py/diagnose.py,sha256=7-Turk573zFa1PIZiFPbC4Pukm1X0nF8PyGxnlc08Fc,5197 +numpy/f2py/f2py2e.py,sha256=inb09kMkkYig8a6Rizj6xvHuWXfrqZzXh1oZgz0dZvM,28838 +numpy/f2py/f90mod_rules.py,sha256=XGtag5pv2Np-hdtjwmSxofKbLO2U_N49sEK_X4Lp3SA,9874 +numpy/f2py/func2subr.py,sha256=6d2R5awuHRT4xzgfUfwS7JHTqhhAieSXcENlssD_2c4,10298 +numpy/f2py/rules.py,sha256=EhOTqFY3M0UX5dQGlthzkFC0b-R5nCVh4ST4tp0smFY,62938 +numpy/f2py/setup.cfg,sha256=Fpn4sjqTl5OT5sp8haqKIRnUcTPZNM6MIvUJBU7BIhg,48 +numpy/f2py/src/fortranobject.c,sha256=CYrF44_CoUbZy3QHhe5sAPVtqsaCT4x9oCtUeD7IVyc,46049 +numpy/f2py/src/fortranobject.h,sha256=7cfRN_tToAQ1Na13VQ2Kzb2ujMHUAgGsbScnfLVOHqs,5823 +numpy/f2py/symbolic.py,sha256=PvP0bK0FLEDQj14u340HJu7ghzS_2WlxhGQpJ0zbMQE,53254 +numpy/f2py/tests/__init__.py,sha256=46XgeBE0seimp3wD4Ox0KutYeLwdsdRSiGECcG1iYu8,328 +numpy/f2py/tests/src/abstract_interface/foo.f90,sha256=JFU2w98cB_XNwfrqNtI0yDTmpEdxYO_UEl2pgI_rnt8,658 +numpy/f2py/tests/src/abstract_interface/gh18403_mod.f90,sha256=gvQJIzNtvacWE0dhysxn30-iUeI65Hpq7DiE9oRauz8,105 +numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c,sha256=s6XLwujiCr6Xi8yBkvLPBXRmo2WsGVohU7K9ALnKUng,7478 +numpy/f2py/tests/src/assumed_shape/.f2py_f2cmap,sha256=But9r9m4iL7EGq_haMW8IiQ4VivH0TgUozxX4pPvdpE,29 +numpy/f2py/tests/src/assumed_shape/foo_free.f90,sha256=oBwbGSlbr9MkFyhVO2aldjc01dr9GHrMrSiRQek8U64,460 +numpy/f2py/tests/src/assumed_shape/foo_mod.f90,sha256=rfzw3QdI-eaDSl-hslCgGpd5tHftJOVhXvb21Y9Gf6M,499 +numpy/f2py/tests/src/assumed_shape/foo_use.f90,sha256=rmT9k4jP9Ru1PLcGqepw9Jc6P9XNXM0axY7o4hi9lUw,269 +numpy/f2py/tests/src/assumed_shape/precision.f90,sha256=r08JeTVmTTExA-hYZ6HzaxVwBn1GMbPAuuwBhBDtJUk,130 +numpy/f2py/tests/src/block_docstring/foo.f,sha256=y7lPCPu7_Fhs_Tf2hfdpDQo1bhtvNSKRaZAOpM_l3dg,97 +numpy/f2py/tests/src/callback/foo.f,sha256=C1hjfpRCQWiOVVzIHqnsYcnLrqQcixrnHCn8hd9GhVk,1254 +numpy/f2py/tests/src/callback/gh17797.f90,sha256=_Nrl0a2HgUbtymGU0twaJ--7rMa1Uco2A3swbWvHoMo,148 +numpy/f2py/tests/src/callback/gh18335.f90,sha256=NraOyKIXyvv_Y-3xGnmTjtNjW2Znsnlk8AViI8zfovc,506 +numpy/f2py/tests/src/callback/gh25211.f,sha256=a2sxlQhtDVbYn8KOKHUYqwc-aCFt7sDPSnJsXFG35uI,179 +numpy/f2py/tests/src/callback/gh25211.pyf,sha256=FWxo0JWQlw519BpZV8PoYeI_FZ_K6C-3Wk6gLrfBPlw,447 +numpy/f2py/tests/src/callback/gh26681.f90,sha256=-cD69x7omk5wvVsfMHlXiZ-pTcaxs2Bl5G9GHA4UJ2M,566 +numpy/f2py/tests/src/cli/gh_22819.pyf,sha256=5rvOfCv-wSosB354LC9pExJmMoSHnbGZGl_rtA2fogA,142 +numpy/f2py/tests/src/cli/hi77.f,sha256=ttyI6vAP3qLnDqy82V04XmoqrXNM6uhMvvLri2p0dq0,71 +numpy/f2py/tests/src/cli/hiworld.f90,sha256=QWOLPrTxYQu1yrEtyQMbM0fE9M2RmXe7c185KnD5x3o,51 +numpy/f2py/tests/src/common/block.f,sha256=GQ0Pd-VMX3H3a-__f2SuosSdwNXHpBqoGnQDjf8aG9g,224 +numpy/f2py/tests/src/common/gh19161.f90,sha256=BUejyhqpNVfHZHQ-QC7o7ZSo7lQ6YHyX08lSmQqs6YM,193 +numpy/f2py/tests/src/crackfortran/accesstype.f90,sha256=-5Din7YlY1TU7tUHD2p-_DSTxGBpDsWYNeT9WOwGhno,208 +numpy/f2py/tests/src/crackfortran/common_with_division.f,sha256=2LfRa26JEB07_ti-WDmIveq991PxRlL_K6ss28rZDkk,494 +numpy/f2py/tests/src/crackfortran/data_common.f,sha256=ZSUAh3uhn9CCF-cYqK5TNmosBGPfsuHBIEfudgysun4,193 +numpy/f2py/tests/src/crackfortran/data_multiplier.f,sha256=jYrJKZWF_59JF9EMOSALUjn0UupWvp1teuGpcL5s1Sc,197 +numpy/f2py/tests/src/crackfortran/data_stmts.f90,sha256=19YO7OGj0IksyBlmMLZGRBQLjoE3erfkR4tFvhznvvE,693 +numpy/f2py/tests/src/crackfortran/data_with_comments.f,sha256=hoyXw330VHh8duMVmAQZjr1lgLVF4zFCIuEaUIrupv0,175 +numpy/f2py/tests/src/crackfortran/foo_deps.f90,sha256=CaH7mnWTG7FcnJe2vXN_0zDbMadw6NCqK-JJ2HmDjK8,128 +numpy/f2py/tests/src/crackfortran/gh15035.f,sha256=jJly1AzF5L9VxbVQ0vr-sf4LaUo4eQzJguhuemFxnvg,375 +numpy/f2py/tests/src/crackfortran/gh17859.f,sha256=7K5dtOXGuBDAENPNCt-tAGJqTfNKz5OsqVSk16_e7Es,340 +numpy/f2py/tests/src/crackfortran/gh22648.pyf,sha256=qZHPRNQljIeYNwbqPLxREnOrSdVV14f3fnaHqB1M7c0,241 +numpy/f2py/tests/src/crackfortran/gh23533.f,sha256=w3tr_KcY3s7oSWGDmjfMHv5h0RYVGUpyXquNdNFOJQg,126 +numpy/f2py/tests/src/crackfortran/gh23598.f90,sha256=41W6Ire-5wjJTTg6oAo7O1WZfd1Ug9vvNtNgHS5MhEU,101 +numpy/f2py/tests/src/crackfortran/gh23598Warn.f90,sha256=1v-hMCT_K7prhhamoM20nMU9zILam84Hr-imck_dYYk,205 +numpy/f2py/tests/src/crackfortran/gh23879.f90,sha256=LWDJTYR3t9h1IsrKC8dVXZlBfWX7clLeU006X6Ow8oI,332 +numpy/f2py/tests/src/crackfortran/gh27697.f90,sha256=bbnKpDsOuCWluoNodxzCspUQnu169zKTsn4fLTkhwpM,364 +numpy/f2py/tests/src/crackfortran/gh2848.f90,sha256=gPNasx98SIf7Z9ibk_DHiGKCvl7ERtsfoGXiFDT7FbM,282 +numpy/f2py/tests/src/crackfortran/operators.f90,sha256=-Fc-qjW1wBr3Dkvdd5dMTrt0hnjnV-1AYo-NFWcwFSo,1184 +numpy/f2py/tests/src/crackfortran/privatemod.f90,sha256=7bubZGMIn7iD31wDkjF1TlXCUM7naCIK69M9d0e3y-U,174 +numpy/f2py/tests/src/crackfortran/publicmod.f90,sha256=Pnwyf56Qd6W3FUH-ZMgnXEYkb7gn18ptNTdwmGan0Jo,167 +numpy/f2py/tests/src/crackfortran/pubprivmod.f90,sha256=eYpJwBYLKGOxVbKgEqfny1znib-b7uYhxcRXIf7uwXg,165 +numpy/f2py/tests/src/crackfortran/unicode_comment.f90,sha256=aINLh6GlfTwFewxvDoqnMqwuCNb4XAqi5Nj5vXguXYs,98 +numpy/f2py/tests/src/f2cmap/.f2py_f2cmap,sha256=iUOtfHd3OuT1Rz2-yiSgt4uPKGvCt5AzQ1iygJt_yjg,82 +numpy/f2py/tests/src/f2cmap/isoFortranEnvMap.f90,sha256=iJCD8a8MUTmuPuedbcmxW54Nr4alYuLhksBe1sHS4K0,298 +numpy/f2py/tests/src/isocintrin/isoCtests.f90,sha256=jcw-fzrFh0w5U66uJYfeUW4gv94L5MnWQ_NpsV9y0oI,998 +numpy/f2py/tests/src/kind/foo.f90,sha256=zIHpw1KdkWbTzbXb73hPbCg4N2Htj3XL8DIwM7seXpo,347 +numpy/f2py/tests/src/mixed/foo.f,sha256=90zmbSHloY1XQYcPb8B5d9bv9mCZx8Z8AMTtgDwJDz8,85 +numpy/f2py/tests/src/mixed/foo_fixed.f90,sha256=pxKuPzxF3Kn5khyFq9ayCsQiolxB3SaNtcWaK5j6Rv4,179 +numpy/f2py/tests/src/mixed/foo_free.f90,sha256=fIQ71wrBc00JUAVUj_r3QF9SdeNniBiMw6Ly7CGgPWU,139 +numpy/f2py/tests/src/modules/gh25337/data.f90,sha256=9Uz8CHB9i3_mjC3cTOmkTgPAF5tWSwYacG3MUrU-SY0,180 +numpy/f2py/tests/src/modules/gh25337/use_data.f90,sha256=WATiDGAoCKnGgMzm_iMgmfVU0UKOQlk5Fm0iXCmPAkE,179 +numpy/f2py/tests/src/modules/gh26920/two_mods_with_no_public_entities.f90,sha256=c7VU4SbK3yWn-6wksP3tDx_Hxh5u_g8UnlDpjU_-tBg,402 +numpy/f2py/tests/src/modules/gh26920/two_mods_with_one_public_routine.f90,sha256=eEU7RgFPh-TnNXEuJFdtJmTF-wPnpbHLQhG4fEeJnag,403 +numpy/f2py/tests/src/modules/module_data_docstring.f90,sha256=tDZ3fUlazLL8ThJm3VwNGJ75QIlLcW70NnMFv-JA4W0,224 +numpy/f2py/tests/src/modules/use_modules.f90,sha256=UsFfx0B2gu_tS-H-BpLWed_yoMDl1kbydMIOz8fvXWA,398 +numpy/f2py/tests/src/negative_bounds/issue_20853.f90,sha256=fdOPhRi7ipygwYCXcda7p_dlrws5Hd2GlpF9EZ-qnck,157 +numpy/f2py/tests/src/parameter/constant_array.f90,sha256=KRg7Gmq_r3B7t3IEgRkP1FT8ve8AuUFWT0WcTlXoN5U,1468 +numpy/f2py/tests/src/parameter/constant_both.f90,sha256=-bBf2eqHb-uFxgo6Q7iAtVUUQzrGFqzhHDNaxwSICfQ,1939 +numpy/f2py/tests/src/parameter/constant_compound.f90,sha256=re7pfzcuaquiOia53UT7qNNrTYu2euGKOF4IhoLmT6g,469 +numpy/f2py/tests/src/parameter/constant_integer.f90,sha256=nEmMLitKoSAG7gBBEQLWumogN-KS3DBZOAZJWcSDnFw,612 +numpy/f2py/tests/src/parameter/constant_non_compound.f90,sha256=IcxESVLKJUZ1k9uYKoSb8Hfm9-O_4rVnlkiUU2diy8Q,609 +numpy/f2py/tests/src/parameter/constant_real.f90,sha256=quNbDsM1Ts2rN4WtPO67S9Xi_8l2cXabWRO00CPQSSQ,610 +numpy/f2py/tests/src/quoted_character/foo.f,sha256=WjC9D9171fe2f7rkUAZUvik9bkIf9adByfRGzh6V0cM,482 +numpy/f2py/tests/src/regression/AB.inc,sha256=cSNxitwrjTKMiJzhY2AI5FaXJ5y9zDgA27x79jyoI6s,16 +numpy/f2py/tests/src/regression/assignOnlyModule.f90,sha256=c9RvUP1pQ201O_zOXgV0xp_aJF_8llxuA8Uot9z5tr0,608 +numpy/f2py/tests/src/regression/datonly.f90,sha256=9cVvl8zlAuGiqbSHMFzFn6aNWXj2v7sHJdd9A1Oc0qg,392 +numpy/f2py/tests/src/regression/f77comments.f,sha256=bqTsmO8WuSLVFsViIV7Nj7wQbJoZ7IAA3d2tpRDKsnA,626 +numpy/f2py/tests/src/regression/f77fixedform.f95,sha256=hcLZbdozMJ3V9pByVRp3RoeUvZgLMRLFctpZvxK2hTI,139 +numpy/f2py/tests/src/regression/f90continuation.f90,sha256=_W1fj0wXLqT91Q14qpBnM3F7rJKaiSR8upe0mR6_OIE,276 +numpy/f2py/tests/src/regression/incfile.f90,sha256=i7Y1zgMXR9bSxnjeYWSDGeCfsS5jiyn7BLb-wbwjz2U,92 +numpy/f2py/tests/src/regression/inout.f90,sha256=CpHpgMrf0bqA1W3Ozo3vInDz0RP904S7LkpdAH6ODck,277 +numpy/f2py/tests/src/regression/lower_f2py_fortran.f90,sha256=CMQL5RWf9LKnnUDiS-IYa9xc9DGanCYraNq0vGmunOE,100 +numpy/f2py/tests/src/return_character/foo77.f,sha256=WzDNF3d_hUDSSZjtxd3DtE-bSx1ilOMEviGyYHbcFgM,980 +numpy/f2py/tests/src/return_character/foo90.f90,sha256=ULcETDEt7gXHRzmsMhPsGG4o3lGrcx-FEFaJsPGFKyA,1248 +numpy/f2py/tests/src/return_complex/foo77.f,sha256=8ECRJkfX82oFvGWKbIrCvKjf5QQQClx4sSEvsbkB6A8,973 +numpy/f2py/tests/src/return_complex/foo90.f90,sha256=c1BnrtWwL2dkrTr7wvlEqNDg59SeNMo3gyJuGdRwcDw,1238 +numpy/f2py/tests/src/return_integer/foo77.f,sha256=_8k1evlzBwvgZ047ofpdcbwKdF8Bm3eQ7VYl2Y8b5kA,1178 +numpy/f2py/tests/src/return_integer/foo90.f90,sha256=bzxbYtofivGRYH35Ang9ScnbNsVERN8-6ub5-eI-LGQ,1531 +numpy/f2py/tests/src/return_logical/foo77.f,sha256=FxiF_X0HkyXHzJM2rLyTubZJu4JB-ObLnVqfZwAQFl8,1188 +numpy/f2py/tests/src/return_logical/foo90.f90,sha256=9KmCe7yJYpi4ftkKOM3BCDnPOdBPTbUNrKxY3p37O14,1531 +numpy/f2py/tests/src/return_real/foo77.f,sha256=ZTrzb6oDrIDPlrVWP3Bmtkbz3ffHaaSQoXkfTGtCuFE,933 +numpy/f2py/tests/src/return_real/foo90.f90,sha256=gZuH5lj2lG6gqHlH766KQ3J4-Ero-G4WpOOo2MG3ohU,1194 +numpy/f2py/tests/src/routines/funcfortranname.f,sha256=oGPnHo0zL7kjFnuHw41mWUSXauoeRVPXnYXBb2qljio,123 +numpy/f2py/tests/src/routines/funcfortranname.pyf,sha256=coD8AdLyPK4_cGvQJgE2WJW_jH8EAulZCsMeb-Q1gOk,440 +numpy/f2py/tests/src/routines/subrout.f,sha256=RTexoH7RApv_mhu-RcVwyNiU-DXMTUP8LJAMSn2wQjk,90 +numpy/f2py/tests/src/routines/subrout.pyf,sha256=c9qv4XtIh4wA9avdkDJuXNwojK-VBPldrNhxlh446Ic,322 +numpy/f2py/tests/src/size/foo.f90,sha256=IlFAQazwBRr3zyT7v36-tV0-fXtB1d7WFp6S1JVMstg,815 +numpy/f2py/tests/src/string/char.f90,sha256=ihr_BH9lY7eXcQpHHDQhFoKcbu7VMOX5QP2Tlr7xlaM,618 +numpy/f2py/tests/src/string/fixed_string.f90,sha256=5n6IkuASFKgYICXY9foCVoqndfAY0AQZFEK8L8ARBGM,695 +numpy/f2py/tests/src/string/gh24008.f,sha256=UA8Pr-_yplfOFmc6m4v9ryFQ8W9OulaglulefkFWD68,217 +numpy/f2py/tests/src/string/gh24662.f90,sha256=-Tp9Kd1avvM7AIr8ZukFA9RVr-wusziAnE8AvG9QQI4,197 +numpy/f2py/tests/src/string/gh25286.f90,sha256=2EpxvC-0_dA58MBfGQcLyHzpZgKcMf_W9c73C_Mqnok,304 +numpy/f2py/tests/src/string/gh25286.pyf,sha256=GjgWKh1fHNdPGRiX5ek60i1XSeZsfFalydWqjISPVV8,381 +numpy/f2py/tests/src/string/gh25286_bc.pyf,sha256=6Y9zU66NfcGhTXlFOdFjCSMSwKXpq5ZfAe3FwpkAsm4,384 +numpy/f2py/tests/src/string/scalar_string.f90,sha256=ACxV2i6iPDk-a6L_Bs4jryVKYJMEGUTitEIYTjbJes4,176 +numpy/f2py/tests/src/string/string.f,sha256=shr3fLVZaa6SyUJFYIF1OZuhff8v5lCwsVNBU2B-3pk,248 +numpy/f2py/tests/src/value_attrspec/gh21665.f90,sha256=JC0FfVXsnB2lZHb-nGbySnxv_9VHAyD0mKaLDowczFU,190 +numpy/f2py/tests/test_abstract_interface.py,sha256=nGyPJgB0-d9Ttk3XsYb-N9HxfZxTVUz0gkl66u3JNaU,809 +numpy/f2py/tests/test_array_from_pyobj.py,sha256=nXkuHwa0gvVOsyuKI2m1UfVu8HyKiFqBvIK23_zOdxw,23702 +numpy/f2py/tests/test_assumed_shape.py,sha256=FeaqtrWyBf5uyArcmI0D2e_f763aSMpgU3QmdDXe-tA,1466 +numpy/f2py/tests/test_block_docstring.py,sha256=2WGCsNBxtH57BjAYyPAzUZgiBRYWAQpC9zODP02OZec,582 +numpy/f2py/tests/test_callback.py,sha256=8I31S55C4p3WXUFUY78fo8as-VpS6h7kNAPeUZrr7w0,7114 +numpy/f2py/tests/test_character.py,sha256=zUsyZCO1FrhVxF-S_fuET_xjbWoJc3SrFCNY_buT7WU,21905 +numpy/f2py/tests/test_common.py,sha256=VPsy0SLqbKaUGgDqesYXmjYuLpnPK-XyzseqmV5QnhM,641 +numpy/f2py/tests/test_crackfortran.py,sha256=6Y_u1FJYpVkwE9615Bx24eMh67rtJEm1bIEegnpxvCg,16383 +numpy/f2py/tests/test_data.py,sha256=SFYgovu5LBtIbS-zvbqkm9zoahHJx35LDOJoEqYP_kU,2888 +numpy/f2py/tests/test_docs.py,sha256=GiQUqifxttwJRgkmLEoq5wIFjTlYLEAQ1n5Kw4Emsiw,1850 +numpy/f2py/tests/test_f2cmap.py,sha256=-WnN0HlqiG9RPgc1P_KSLZvqgQ4wGYDf0lFcyfWOLfs,385 +numpy/f2py/tests/test_f2py2e.py,sha256=K_883X2rw88Fn5a7bZPI03NFA3YD95NYopX0OHxcZAM,27868 +numpy/f2py/tests/test_isoc.py,sha256=kY7yg7Jtyn_RBlozwe6UpQvtwPbPcpTC0B27s2GRo7s,1428 +numpy/f2py/tests/test_kind.py,sha256=myLQNDPZDdVq7PNjXWUgkY3M-JdzP5MJNZ1PE_ChNEI,1783 +numpy/f2py/tests/test_mixed.py,sha256=iMMRt1q7woHuKSfqiw4LsaU9wIRq2FnvT0lv74fR7V0,860 +numpy/f2py/tests/test_modules.py,sha256=wli_Cq9FroWg9nnOZplGAd9L5OX49h_Z-e8PyVVnk0w,2299 +numpy/f2py/tests/test_parameter.py,sha256=j4sNNiHkj-jbl3FC4v_tnksgpydbHqNvNI2tzlVFGYE,4623 +numpy/f2py/tests/test_pyf_src.py,sha256=eD0bZu_GWfoCq--wWqEKRf-F2h5AwoTyO6GMA9wJPr4,1135 +numpy/f2py/tests/test_quoted_character.py,sha256=T6I2EyopdItKamcokG0ylvhT7krZYhBU6hF3UFIBr2g,476 +numpy/f2py/tests/test_regression.py,sha256=L95aSnN9lOVRkmGPVRaVF4w6hJ3iHgQ8BPM34Uef35I,5849 +numpy/f2py/tests/test_return_character.py,sha256=DP63vrF6bIV-QRBsJ1ZpPsKz-u906Ph8M6_biPEzBJs,1511 +numpy/f2py/tests/test_return_complex.py,sha256=4vtpIYqAZZrbKYi3fnP7l_Zn42YnBbPwl8-eNfZOHHo,2415 +numpy/f2py/tests/test_return_integer.py,sha256=qR8Ismf40Ml2impqjGzjL2i-CRyGTxXVEvzQQMkJfJo,1776 +numpy/f2py/tests/test_return_logical.py,sha256=XCmp8E8I6BOeNYF59HjSFAdv1hM9WaDvl8UDS10_05o,2017 +numpy/f2py/tests/test_return_real.py,sha256=KMIRQP9xjz09-wFX-jeMbkNQPXegnfd-Qhc4W4qKHeA,3247 +numpy/f2py/tests/test_routines.py,sha256=TflyDvptl5dREgZFv6hlauRvsK_FFUo7ZTVsiIYPcio,794 +numpy/f2py/tests/test_semicolon_split.py,sha256=6aGgOdtGpJSgPZlzpow-tcHXSPqrJeKagWnFilheWeM,1626 +numpy/f2py/tests/test_size.py,sha256=CsElZF4N5Tf7fr27TJudu3JD_JKb63SubUXPYjl5Llg,1154 +numpy/f2py/tests/test_string.py,sha256=wfV6jxkOnoJWOM7i5Ee7gc2nXK_Gyb3FqNI4wLfVQhk,2936 +numpy/f2py/tests/test_symbolic.py,sha256=28quk2kTKfWhKe56n4vINJ8G9weKBfc7HysMlE9J3_g,18341 +numpy/f2py/tests/test_value_attrspec.py,sha256=jYtbvVyg8uOZsdcCeLhaXIdR7MOfMh1j04aXbJNbfK8,329 +numpy/f2py/tests/util.py,sha256=WKEixdQq0xJV3Hg60a-6xc1T5GhKDngfPEw-WNfoqjg,12174 +numpy/f2py/use_rules.py,sha256=oMjkw5fP55MhGAqdDcO_dknbQBE9qLljU7y6-HDoerY,3515 +numpy/fft/__init__.py,sha256=cW8oJRorHlG10mhnhAB1OOkg4HpG2NGYHDgonFNI04s,8326 +numpy/fft/__init__.pyi,sha256=KvQQpPxk9LKgqMIB3AGJCsQDu3ownGKjjT7McQKNpXY,514 +numpy/fft/_helper.py,sha256=Yvph-5gksd0HebLSXq4UKfVYOwSiqNIa4THpv0aA2HE,6775 +numpy/fft/_helper.pyi,sha256=dek8ibnRL8Y2erBdDt7ydWyAVXLb46SPTctLy_TEKoE,1341 +numpy/fft/_pocketfft.py,sha256=Q6J5inX10oPBtX-lblPlYExuzycovGr-LFMT7QYe9pc,62692 +numpy/fft/_pocketfft.pyi,sha256=Dvhdy8Y2R1HmTu-99z4Pgd4WCnC6eg3OVzUY4yOQpTo,3155 +numpy/fft/_pocketfft_umath.cpython-310-x86_64-linux-gnu.so,sha256=vfJmvXmCJeWh_twk95K0tF1SvZYK3JT9PLdhCLJT1Cs,649272 +numpy/fft/helper.py,sha256=str0NJ1vpLNlC_3vMfulTu9D9_cThxKG2zkaGuZ5NTY,610 +numpy/fft/helper.pyi,sha256=KsF45bVyZ4_eJbBFpkER9L8MCWmg7dJuhLqY_7uFNZs,891 +numpy/fft/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/fft/tests/test_helper.py,sha256=pVYVLUwNEcE9M8eyHaRi7JOgc6k5p_JVzJ0AKnelgvI,6149 +numpy/fft/tests/test_pocketfft.py,sha256=euC7OA8_h_EQ0aO_UqBNPARx3xb2LgJS-rsWe3XiE-U,24410 +numpy/lib/__init__.py,sha256=IvUoSO27nHWmaTCs4fqJLDIWIcaj-uRIbR9YfkyptAo,3226 +numpy/lib/__init__.pyi,sha256=nevfu40fu_qSozt-vdcUGh_zQijGGWxfdns2x9_LsWI,518 +numpy/lib/_array_utils_impl.py,sha256=eMGdZi7auu6201h4v4eQZ2miF8KmdMGDApbBFgRE-6Q,1689 +numpy/lib/_array_utils_impl.pyi,sha256=2OjfMvbUUlTrJHvGHIcnlrHxPWl7LcpFo3gmuVz6nWg,793 +numpy/lib/_arraypad_impl.py,sha256=xm8Pkunt7DAKAWvnySEsoWbjMvcmZL-OC7qe-LQaruQ,32326 +numpy/lib/_arraypad_impl.pyi,sha256=G9GSX6q0glWgoPN5FGzO-Ql1UdkKadoyfVy1B0HH9iM,1792 +numpy/lib/_arraysetops_impl.py,sha256=CBDoG2fWzx0OITbZEKlFD5WUo9HQRqmsweoMOtHKQjs,39309 +numpy/lib/_arraysetops_impl.pyi,sha256=4BeISAFRLNdag94QdBWWJTOWr2RPaWcNkkiCBuIdejU,9569 +numpy/lib/_arrayterator_impl.py,sha256=qx6gqxLTNY4Lea6Lh6J-Cud4RyLIqnELhi-kMwK8vKU,7186 +numpy/lib/_arrayterator_impl.pyi,sha256=8ozo2UTKx-9fIDXhVMYDyhlfuMa-uPlWCp25TRk61kE,1827 +numpy/lib/_datasource.py,sha256=FJ7k1HghREU7udh8ZuO5ZZF3nHJfOkj7iWijhoVFqIQ,22729 +numpy/lib/_datasource.pyi,sha256=135RvD3p-3mHdNp_sZV4aN9brwEFvEM49VE1eHlFEfs,996 +numpy/lib/_function_base_impl.py,sha256=eeZaizFpsCLeisLcxrQ-eK4R-8enw6YKPV1jeDPwCzU,196038 +numpy/lib/_function_base_impl.pyi,sha256=Ce0vkW7qM9i4G2Br-X8A6V9XwPZ5cKiIB030zlSUFvQ,22228 +numpy/lib/_histograms_impl.py,sha256=Lw_9LfM_Z7qBef3boamH5LtL7qiT10gpIyWy9Uj6lTo,38762 +numpy/lib/_histograms_impl.pyi,sha256=7B4b29m97PW5GDSgOKi_3Ul-XyWbo6NjMW264FFxjSI,1070 +numpy/lib/_index_tricks_impl.py,sha256=12iGjjak3hiMfwnh5zR2JqA78-or-u9P1gTGCcjJD0E,32179 +numpy/lib/_index_tricks_impl.pyi,sha256=WOKkVvojes2D2Uc8itHkjv6fZF1VqwocnqVu05aiCIs,6325 +numpy/lib/_iotools.py,sha256=mMhxeGBt-T8prjWpNhn_xvZCj6u6OWWmmsvKP6vbM5w,30941 +numpy/lib/_iotools.pyi,sha256=4AQxPlLCoIruq04RAa-xtC8swL1ChuLT9SqhQAfeflQ,3387 +numpy/lib/_nanfunctions_impl.py,sha256=gX6NUKgCQKvuFTSAObhqfrqQIXIsxnKIQOc-heOn7rs,72150 +numpy/lib/_nanfunctions_impl.pyi,sha256=o0ILqctzjyHwNJ3zs4bdd8qJ9qVtyGfL6FChCf4IPGg,833 +numpy/lib/_npyio_impl.py,sha256=UA84bpOF9xfELBsagASjHf1E5GgLWvs_Y_Gmtplkovw,99377 +numpy/lib/_npyio_impl.pyi,sha256=byvWXIh9qHzEQGvHKkclD9_oBGn8y6JkU5aUhSjhZyo,9270 +numpy/lib/_polynomial_impl.py,sha256=6rD5Cy4mSDk2CsuAdJOq2he-PSa-ZiqsdgyyQAF5qx0,44294 +numpy/lib/_polynomial_impl.pyi,sha256=NoMMI6aJmcnLKQyaM3B2hSJTFJtx7mAqEHPsCC_rM7s,7117 +numpy/lib/_scimath_impl.py,sha256=dUxb9XD-AJPboK_LO3LA0KgykFSUEOG5BVGrhwm2Qqo,15691 +numpy/lib/_scimath_impl.pyi,sha256=Xdyj3nbEBEE5p6K_ZIjilsAgvaxoGK8TEoV2vdzpLIE,2955 +numpy/lib/_shape_base_impl.py,sha256=AHbXPp4sH0gEJgSyM0A9zgmM9Mwm6jR_p5pWtUXeqV8,39353 +numpy/lib/_shape_base_impl.pyi,sha256=RysQQNQ6fbI_IyavO9AXPMynIGD7vf6I0_dc5_4wUpI,5288 +numpy/lib/_stride_tricks_impl.py,sha256=y3Uxp3jFzDwmIQ137N2zap7-vW_jONUQmXnbfqrs60A,18025 +numpy/lib/_stride_tricks_impl.pyi,sha256=ZX9Dp4oLmi-FSwY8o4FSisswTgfE5xwlTCjk2QkbIG8,1801 +numpy/lib/_twodim_base_impl.py,sha256=r31aBnzCSBpq_em4HyLiSMeTiRzlHAn7Bd4yXYqyEFY,33864 +numpy/lib/_twodim_base_impl.pyi,sha256=30vYsjEVCOaJ8NDgk4KKpvkW-C4_hV-NbJAd3VswVXI,11269 +numpy/lib/_type_check_impl.py,sha256=Dv9a7QCR1bqBHoXgCjmPrGEewG1v2BBtE_8VfcF4ySU,19220 +numpy/lib/_type_check_impl.pyi,sha256=XuaIBCJI1z50pcH6ScB3oMAyBjAxX_LY4KU0gUZaTAM,5165 +numpy/lib/_ufunclike_impl.py,sha256=0eemf_EYlLmSa4inNr3iuJ1eoTMqLyIR0n6dQymga3Y,6309 +numpy/lib/_ufunclike_impl.pyi,sha256=Tle2e2qLfaYNlECFw6AVgazMnAHYCE9WO96ddZiM1dw,1322 +numpy/lib/_user_array_impl.py,sha256=pqmz3qNx620zngeIFmSg8IiXNdTMVBAglt81hEJNh5Y,7971 +numpy/lib/_user_array_impl.pyi,sha256=Zfknkdua_dgoO9U7rDXHYzuachGOVFeLu1X0760dvR8,9301 +numpy/lib/_utils_impl.py,sha256=4xYQczoX7i_wHjugnl0ba1VExSbV48ndVow08S8G0WQ,23388 +numpy/lib/_utils_impl.pyi,sha256=3UJqa7IVH6QVJbQfKAqblyHxjPfaCAR28KmDxXeIpU0,277 +numpy/lib/_version.py,sha256=nyRagTCuE69-0P9JTIcKK7jbzRGbsgnqVtFIrNzTFsM,4854 +numpy/lib/_version.pyi,sha256=vysY5Vl_nh4si6GkMXEoB6pUDl-jJ5g0LpSDa40F124,641 +numpy/lib/array_utils.py,sha256=zoaLw9TvrAFRkh9n8uMyr8kvug3IvVlUT7LcJzB3Tk0,130 +numpy/lib/array_utils.pyi,sha256=kEO5wShp8zEbNTPu-Kw-EHuZQvq1rXHzgjK797xCV0Q,191 +numpy/lib/format.py,sha256=XMMQzYOvc8LgeNpxX7Qpfurli2bG5o9jAaeY55tP85A,36200 +numpy/lib/format.pyi,sha256=cVuydIbVhG_tM7TrxEVBiERRPLOxKS8hLCTOT7ovtzc,748 +numpy/lib/introspect.py,sha256=SiQ5OwgvE-1RoQOv2r__WObS5QEUBohanyCd7Xe80UU,2715 +numpy/lib/introspect.pyi,sha256=AWVX6b9mzdwsxizOY0LydWKBEpGatHaeeXGc2txYJEM,152 +numpy/lib/mixins.py,sha256=_yb3iwwzUfSbN7HpJSp3FhFkgV3WViTHS5SAHkK8Lmc,7337 +numpy/lib/mixins.pyi,sha256=q_lxMe-PpNlvpEJ--nLkyi0qVD0QuNHriF3XHfxyJok,3131 +numpy/lib/npyio.py,sha256=NCxqWedJbSM5M-wr69TED8x7KXcyBJ0x5u49vj4sPkI,62 +numpy/lib/npyio.pyi,sha256=MTP8KyQ2GTU8BTkpaMHnwDQO9ABrHRiCCEO5BfQGgLo,116 +numpy/lib/recfunctions.py,sha256=5fbg0aMuDbgOpfYmDTByhlNKZWgNkCVDdA8BQ4zZXzA,59654 +numpy/lib/recfunctions.pyi,sha256=Ri9FikspmLm_67f86udizNNMZzaOXz1nulRNcxfYDWc,13283 +numpy/lib/scimath.py,sha256=iO0IiDgpHk1EurdUvJIE2KqDzVOfvSsU3MFIlJskIOE,118 +numpy/lib/scimath.pyi,sha256=UND4g92K5-6_I0YWqu7qbDTHU_sePpa0I58MTMH0yhA,233 +numpy/lib/stride_tricks.py,sha256=VGR5M8Jyw8IC4S6XEB9NN_GULTJJQj_1QrItIi_BJiM,82 +numpy/lib/stride_tricks.pyi,sha256=Fqn9EZXdjIgUTce6UMD7rBBb8289QTMzohhjHwYP3TU,124 +numpy/lib/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/lib/tests/data/py2-np0-objarr.npy,sha256=ZLoI7K3iQpXDkuoDF1Ymyc6Jbw4JngbQKC9grauVRsk,258 +numpy/lib/tests/data/py2-objarr.npy,sha256=F4cyUC-_TB9QSFLAo2c7c44rC6NUYIgrfGx9PqWPSKk,258 +numpy/lib/tests/data/py2-objarr.npz,sha256=xo13HBT0FbFZ2qvZz0LWGDb3SuQASSaXh7rKfVcJjx4,366 +numpy/lib/tests/data/py3-objarr.npy,sha256=7mtikKlHXp4unZhM8eBot8Cknlx1BofJdd73Np2PW8o,325 +numpy/lib/tests/data/py3-objarr.npz,sha256=vVRl9_NZ7_q-hjduUr8YWnzRy8ESNlmvMPlaSSC69fk,453 +numpy/lib/tests/data/python3.npy,sha256=X0ad3hAaLGXig9LtSHAo-BgOvLlFfPYMnZuVIxRmj-0,96 +numpy/lib/tests/data/win64python2.npy,sha256=agOcgHVYFJrV-nrRJDbGnUnF4ZTPYXuSeF-Mtg7GMpc,96 +numpy/lib/tests/test__datasource.py,sha256=65KXfUUvp8wXSqgQisuYlkhg-qHjBV5FXYetL8Ba-rc,10571 +numpy/lib/tests/test__iotools.py,sha256=W2gLNsi2S8-4qixUs6EKkTYnOOp55qLLuM3zpBzZoR4,13744 +numpy/lib/tests/test__version.py,sha256=aO3YgkAohLsLzCNQ7vjIwdpFUMz0cPLbcuuxIkjuN74,1999 +numpy/lib/tests/test_array_utils.py,sha256=vOC6AmlPIQbVxQf2DiRL02May5IK5BK2GUFK0nP83FM,1119 +numpy/lib/tests/test_arraypad.py,sha256=PuDd3s7w_r54B2ILXKQheFMUxklylHPN-vHVq_mGjk8,56064 +numpy/lib/tests/test_arraysetops.py,sha256=Y5sS11K5r4KGcPaZHxOaoBUJDZAjcfdF7qSvxpVydqo,38023 +numpy/lib/tests/test_arrayterator.py,sha256=AYs2SwV5ankgwnvKI9RSO1jZck118nu3SyZ4ngzZNso,1291 +numpy/lib/tests/test_format.py,sha256=pbIhtX3E07MU9GN30frL--KKMW3iYm1eFaTiwPq39MU,40911 +numpy/lib/tests/test_function_base.py,sha256=YgxaRTjpKNzw92xkMxdxY2JwHQoBOryb-06gaRiTn1c,168840 +numpy/lib/tests/test_histograms.py,sha256=pSUHeO9nY5Gf5VXyCCZ9qoRjrXT1Y4c0xRcz5FeAPCY,33694 +numpy/lib/tests/test_index_tricks.py,sha256=ZpKsvd3P3p2hwfj6sHlL_lysJp1IevAoM6AdpeTAx8M,20368 +numpy/lib/tests/test_io.py,sha256=1brG0DanJdQhK680J-zR4YlBc-oDfv_QUYkIOb8oPzQ,110047 +numpy/lib/tests/test_loadtxt.py,sha256=uP0SIRUpBGS4rZR7iXtwDsf1vpCZk_1f29NvYcci738,40522 +numpy/lib/tests/test_mixins.py,sha256=Wivwz3XBWsEozGzrzsyyvL3qAuE14t1BHk2LPm9Z9Zc,7030 +numpy/lib/tests/test_nanfunctions.py,sha256=iN7Lyl0FlDjlE23duS6YS_iEoWRSPP8tydQLdmSMWsI,53344 +numpy/lib/tests/test_packbits.py,sha256=2QaNYKH29cVD-S4YYBIQBd1xQ9bc2OqHdZT6yS7Txjk,17544 +numpy/lib/tests/test_polynomial.py,sha256=1gJhzbXglqeGMjo8OnpP4EASiCVvkYPiNOHKirAlNfg,11428 +numpy/lib/tests/test_recfunctions.py,sha256=KHHrlYhCrVVZh4N4e8UMac8oK4aX438Na1AchTdJsxU,43987 +numpy/lib/tests/test_regression.py,sha256=YdZ_xYXzFh3WFyAKF5lN7oFl5HMm5r38C1Lij3J8NuQ,7694 +numpy/lib/tests/test_shape_base.py,sha256=W1q-tgBENS19wpOKSzEi63OSjatE4qC1viQG22qoacE,27488 +numpy/lib/tests/test_stride_tricks.py,sha256=9g25TXSGLsvfeIrlkQ8l1fx_pZ48b4dxCzXXUbsKC5g,22997 +numpy/lib/tests/test_twodim_base.py,sha256=ll-72RhqCItIPB97nOWhH7H292h4nVIX_w1toKTPMUg,18841 +numpy/lib/tests/test_type_check.py,sha256=9ycqRSw0TzrJfu4gknQYblRPEsWlMI9TWPP_jyI8w-c,14680 +numpy/lib/tests/test_ufunclike.py,sha256=5AFySuvUfggh0tpBuQHJ7iZRrP0r_yZZv5xHxOuCZ1s,3023 +numpy/lib/tests/test_utils.py,sha256=zzgwQGId2P8RUgimSsm7uMCYb61xPenrP_N0kcZU8x4,2374 +numpy/lib/user_array.py,sha256=Ev3yeNNLZVNWk9xZuiCIbODYKwQ6XfYGpI5WAoYvtok,49 +numpy/lib/user_array.pyi,sha256=8C-aTekEYA0bVU7F3turaw1w0j8FfFvDp9xKa9Pfe94,53 +numpy/linalg/__init__.py,sha256=XNtdLo33SVTjQbXeimLFa5ZudzpEEwnfJBNorVbxuyc,2106 +numpy/linalg/__init__.pyi,sha256=o8K7PS_GETdEtnE7uXgJV7wnR8B0hH79AKpsmBHbJhA,1006 +numpy/linalg/_linalg.py,sha256=QNeVUH1DXQe7X5Ygp-LV9W1tN7sbwbhMXIQbRNPYJX0,114680 +numpy/linalg/_linalg.pyi,sha256=sCY_eH3ygLI05xCQ278LcS5XofiOPB-G_-cYY1Q2FTA,11385 +numpy/linalg/_umath_linalg.cpython-310-x86_64-linux-gnu.so,sha256=xrydXE22zqMz1G2QXhX7zY9UHsWyNwTKPERUfuLuUYc,227657 +numpy/linalg/_umath_linalg.pyi,sha256=awvRP1FGuomyfeaR0wzHvrXURAI8tUF3u2RRZ24hkXw,1409 +numpy/linalg/lapack_lite.cpython-310-x86_64-linux-gnu.so,sha256=SioRlSGZ3x9sAB3kDvue0hC3LG27o0Ynq631aTAIET0,30009 +numpy/linalg/lapack_lite.pyi,sha256=9HbrKm6Xc3jdXwjNcIm26mvm7M_sT8aug5p-e6lyw2c,2677 +numpy/linalg/linalg.py,sha256=JQWcEvjY_bjhaMHXY5vDk69OIoMzX5Rvbn1eGW2FCvE,584 +numpy/linalg/linalg.pyi,sha256=8E5sbKeM5Ors7r143mM7A4ui8kFZM0SF7NfUGW1eN-4,932 +numpy/linalg/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/linalg/tests/test_deprecations.py,sha256=9p_SRmtxj2zc1doY9Ie3dyy5JzWy-tCQWFoajcAJUmM,640 +numpy/linalg/tests/test_linalg.py,sha256=DhZiFKqO7SVhtNwRqe5jbhcACbqttIiJfruY5rbLj-Q,83315 +numpy/linalg/tests/test_regression.py,sha256=RMl5Jq-fLVDUSMnEmpP2-gigM5dzUfzURywa1tMK8CA,6689 +numpy/ma/API_CHANGES.txt,sha256=F_4jW8X5cYBbzpcwteymkonTmvzgKKY2kGrHF1AtnrI,3405 +numpy/ma/LICENSE,sha256=BfO4g1GYjs-tEKvpLAxQ5YdcZFLVAJoAhMwpFVH_zKY,1593 +numpy/ma/README.rst,sha256=krf2cvVK_zNQf1d3yVYwg0uDHzTiR4vHbr91zwaAyoI,9874 +numpy/ma/__init__.py,sha256=iv-YxXUZe4z7W53QZWY0ndicV43AGsIygArsoN3tQb8,1419 +numpy/ma/__init__.pyi,sha256=H7zEUcvlhWQkYpoOQ9UyrLOuz23vnd_GYO_JiztGG04,6946 +numpy/ma/core.py,sha256=jN3Z0xIb8a3lBAOAcUhGn8YlK-Ko5qm-1XadzBqAp1k,290518 +numpy/ma/core.pyi,sha256=QGAzV8TDIhaffgX-OPFUhnWYCwzwmZs9OOYyGPLhR9U,18179 +numpy/ma/extras.py,sha256=ZbseZmOKCD1f5w8NZP864TtkOWTw5c5KzzPNqmZFeR4,70630 +numpy/ma/extras.pyi,sha256=J8HZzQWyNC1Uf-PV7QzfaQuJ9vyO_A2RwIfro0S9T7s,3804 +numpy/ma/mrecords.py,sha256=7xEqcIH6iY8AT0ApnCCfrJvr17boJrgl9loqgbRuhso,27114 +numpy/ma/mrecords.pyi,sha256=xHMSbdNKOeXtZP73NUA7aVmGs9F7sTiqAcYJ1o7QNMA,1983 +numpy/ma/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/ma/tests/test_arrayobject.py,sha256=MSvEcxlsVt4YZ7mVXU8q_hkwM0I7xsxWejEqnUQx6hE,1099 +numpy/ma/tests/test_core.py,sha256=KufMvdrDZ8FIgTQW6UWl4M1WzDY32y1rYHwyJbvn13g,219264 +numpy/ma/tests/test_deprecations.py,sha256=nq_wFVt2EBHcT3AHxattfKXx2JDf1K5D-QBzUU0_15A,2566 +numpy/ma/tests/test_extras.py,sha256=h0Zc0u4dXlQ3E0qADNYlH7iF4XX3K2A6HiY5hseRwSs,78314 +numpy/ma/tests/test_mrecords.py,sha256=-nFjKUNYG_-gJ6RpZbWnx_TJlmkRAagA7AnVaf9YJfI,19855 +numpy/ma/tests/test_old_ma.py,sha256=BW01_4m8wZcHvAkZ8FIjDmFfusnjgFmGVbRyqbWD000,32753 +numpy/ma/tests/test_regression.py,sha256=foMpI0luAvwkkRpAfPDV_810h1URISXDZhmaNhxb50k,3287 +numpy/ma/tests/test_subclassing.py,sha256=p5N5b5LY1J0pwDCbju0Qt28wZ1Dd2OfZ1dR4tphiFFY,17009 +numpy/ma/testutils.py,sha256=sbiHivmwPQX3fPAPUe9OMktEqrwg1rcr8xgKfMM1Ex0,10272 +numpy/ma/timer_comparison.py,sha256=FC9KhuSVUdyDP-YQUDQXKhUmrTzC8zsOIBrarMISrc4,15711 +numpy/matlib.py,sha256=_SLwSvwuHVy4nzc2lFd49OqK1m6aWPX1YyKgzyW3A-E,10657 +numpy/matlib.pyi,sha256=jochXdHIBmB5qMHiMVarjfdFUyu7AcRucxVrf2UoGpA,9628 +numpy/matrixlib/__init__.py,sha256=BHBpQKoQv4EjT0UpWBA-Ck4L5OsMqTI2IuY24p-ucXk,242 +numpy/matrixlib/__init__.pyi,sha256=hoxSBzgGaB2axvVIKt8wMefSseGWKDjFg3nAx-ZjNoU,105 +numpy/matrixlib/defmatrix.py,sha256=BGV3oVcQ98-gzqMs3WNC0-x76fmfaGS_2bDnLBHPh90,30800 +numpy/matrixlib/defmatrix.pyi,sha256=ijXIceS3SMbjt_fEn8qCUX_KllbJqDWIo4x6aDKLoqg,478 +numpy/matrixlib/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/matrixlib/tests/test_defmatrix.py,sha256=tLHvsnn2xIKLLZULYqhQ1IJOtSdS52BfOOhU8-7jjvA,15035 +numpy/matrixlib/tests/test_interaction.py,sha256=jiLmXS0JtwEx0smkb5hUnY5Slp9I8FwGlYGHKE3iG1w,11895 +numpy/matrixlib/tests/test_masked_matrix.py,sha256=1x3mzFol1GYvVxKXcmRYLi-On3cmK7gEjSVEyvbkh-w,8914 +numpy/matrixlib/tests/test_matrix_linalg.py,sha256=ObbSUXU4R2pWajH__xAdizADrU2kBKDDCxkDV-oVBXc,2059 +numpy/matrixlib/tests/test_multiarray.py,sha256=jB3XCBmAtcqf-Wb9PwBW6uIykPpMPthuXLJ0giTKzZE,554 +numpy/matrixlib/tests/test_numeric.py,sha256=MP70qUwgshTtThKZaZDp7_6U-Z66NIV1geVhasGXejQ,441 +numpy/matrixlib/tests/test_regression.py,sha256=LBkm6_moDjuU9RY4FszgaknOj3IyCp3t-Ej3HJfqpdk,932 +numpy/polynomial/__init__.py,sha256=XNK7ZWsBECCoHnJZ0NqKiF1ErZqvdxszE1NJ6Hc2Vz0,6760 +numpy/polynomial/__init__.pyi,sha256=6NI7z3v8xTwVp3MBMxi_9W0-IZplayxzdx8BWaqymuI,687 +numpy/polynomial/_polybase.py,sha256=Nhq-h1fKS_ARFPd6BRqya1gROmqA0KX1_eGON5AyYsw,39451 +numpy/polynomial/_polybase.pyi,sha256=fZLj1aw9-tRf0yQSAXHjETPGgrAeqW9v36nlhDNDeyc,8534 +numpy/polynomial/_polytypes.pyi,sha256=zqNdSGV9EIKoVcZSugAb3sDgFXj99m70Yngkt3jVPW8,22567 +numpy/polynomial/chebyshev.py,sha256=U8Pl0r9l3AV96xISmaDjb-bvbCVT61rm7zWiT5L8_wg,62165 +numpy/polynomial/chebyshev.pyi,sha256=9cJoCeRvzHuunQoCEy2pGOUdCp0KU65q7Tb8pTqLvGU,4725 +numpy/polynomial/hermite.py,sha256=p1bX18L-fUwWFtmu0J4FnahBB9cWLCsUWLkXItQ7zB0,54466 +numpy/polynomial/hermite.pyi,sha256=dm1gYq04GxQu5T4N5LqTYbZblLoXDqZDs6CtmycCU3w,2445 +numpy/polynomial/hermite_e.py,sha256=ce0POlSbqQTqvkcXLIn7v7GqtmEaxc3J1xmaaD8VEfw,52208 +numpy/polynomial/hermite_e.pyi,sha256=klpXixSq5MRTlh6AlN1jRXPDXcnRdgUZPTxQjZpFKhM,2537 +numpy/polynomial/laguerre.py,sha256=dzeRDPs1lvJyVz6XeLu_ynPDF4SEFGjpIhLdmIMkf94,52379 +numpy/polynomial/laguerre.pyi,sha256=QiCFjYZRAuYaty8LelfOvomgal1xFU9-4oKL68l1jyc,2174 +numpy/polynomial/legendre.py,sha256=xoXBoVGToSllDsWHU3nBQJSBQLhJZBhMpA_bemYXDHQ,50994 +numpy/polynomial/legendre.pyi,sha256=SaQ9PZG50KF4g0iQd6B-xYOBz1vTDGtI4wChAINlFZY,2173 +numpy/polynomial/polynomial.py,sha256=lto2jYRcSVM3_PuKm3rbbYkHp4eMbOVX3VSO6rHmBrc,52202 +numpy/polynomial/polynomial.pyi,sha256=Y4yeYfi879s5_Xm3SqdRmhQhbgJJBRRbajhCj1irTSw,2002 +numpy/polynomial/polyutils.py,sha256=gF4_BiLkY8ySFlzawPVxr2Zcnoos3SMRn2dpsB0yP4c,22530 +numpy/polynomial/polyutils.pyi,sha256=XYAYqUmjZVS_49uDszZE3SNI_lxJgx1SkjqqBVDrz44,10426 +numpy/polynomial/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/polynomial/tests/test_chebyshev.py,sha256=6tMsFP1h7K8Zf72mNOta6Tv52_fVTlXknseuffj080c,20522 +numpy/polynomial/tests/test_classes.py,sha256=Tf6p3qCINxOfh7hsOdVp81-CJPkqNg1HnH2smcWbRBw,18450 +numpy/polynomial/tests/test_hermite.py,sha256=0iUoYpgXiLrqm_dWD45Cs1PFJ8fHADFtlBN4TkLNNQw,18576 +numpy/polynomial/tests/test_hermite_e.py,sha256=_A3ohAWS4HXrQG06S8L47dImdZGTwYosCXnoyw7L45o,18911 +numpy/polynomial/tests/test_laguerre.py,sha256=5ku3xe4Gv5-eAGhyqwKj460mqoHvM5r_qsGu6P8J0es,17510 +numpy/polynomial/tests/test_legendre.py,sha256=4AXrwrxCQoQ5cIMlYJpHJnAiaikLfvlL-T5TY7z9mzo,18672 +numpy/polynomial/tests/test_polynomial.py,sha256=bkIpTFGh3ypMAZCulWYw6ZPFpqrlbbSAoivrIwBQAtw,22013 +numpy/polynomial/tests/test_polyutils.py,sha256=ULZMU2soHOZ4uO0eJoRjxNkT3yGURuX35MXx1Bg5Wyk,3772 +numpy/polynomial/tests/test_printing.py,sha256=99Qi6N880A3iyRZG5_AsZkDAKkFCUKgOZCp9ZhNMrOQ,21302 +numpy/polynomial/tests/test_symbol.py,sha256=Hg-V7jR7qz5FKg_DrlkaiFcCI1UujYFUJfpf2TuoJZM,5372 +numpy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/random/LICENSE.md,sha256=EDFmtiuARDr7nrNIjgUuoGvgz_VmuQjxmeVh_eSa8Z8,3511 +numpy/random/__init__.pxd,sha256=9JbnX540aJNSothGs-7e23ozhilG6U8tINOUEp08M_k,431 +numpy/random/__init__.py,sha256=81Thnexg5umN5WZwD5TRyzNc2Yp-d14B6UC7NBgVKh8,7506 +numpy/random/__init__.pyi,sha256=ETVwiw_jFxeouKFkzq0ociR0bJgLz3L3OBixxBv9Jho,2158 +numpy/random/_bounded_integers.cpython-310-x86_64-linux-gnu.so,sha256=S0_5jyuw99skCRt5lt1NXGulrlhPNoP8-nKti86SbvE,362560 +numpy/random/_bounded_integers.pxd,sha256=SH_FwJDigFEInhdliSaNH2H2ZIZoX02xYhNQA81g2-g,1678 +numpy/random/_common.cpython-310-x86_64-linux-gnu.so,sha256=IJZToRuhkU9wbpcv0HG-N8MgfhgpGMgfx_q0PNZsXCg,251664 +numpy/random/_common.pxd,sha256=7kGArYkBcemrxJcSttwvtDGbimLszdQnZdNvPMgN5xQ,4982 +numpy/random/_examples/cffi/extending.py,sha256=xSla3zWqxi6Hj48EvnYfD3WHfE189VvC4XsKu4_T_Iw,880 +numpy/random/_examples/cffi/parse.py,sha256=Z69FYSY6QQnZAJdIVlE-I2JAkEutRbdvZDXlm633Ynk,1751 +numpy/random/_examples/cython/extending.pyx,sha256=ePnHDNfMQcTUzAqgFiEqrTFr9BoDmbqgjxzrDLvV8fE,2267 +numpy/random/_examples/cython/extending_distributions.pyx,sha256=YCgFXHb7esnir-QmoAlde4y91FYuRMT94UNg9yb-Y4A,3847 +numpy/random/_examples/cython/meson.build,sha256=GxZZT_Lu3nZsgcqo_7sTR_IdMJaHA1fxyjwrQTcodPs,1694 +numpy/random/_examples/numba/extending.py,sha256=Ipyzel_h5iU_DMJ_vnXUgQC38uMDMn7adUpWSeEQLFE,1957 +numpy/random/_examples/numba/extending_distributions.py,sha256=M3Rt9RKupwEq71JjxpQFbUO7WKSOuLfR1skRM2a-hbI,2036 +numpy/random/_generator.cpython-310-x86_64-linux-gnu.so,sha256=txs7dIHoQqIHqisGrHVHch7VY2bFvMt5Q2FlkeYHX7k,996144 +numpy/random/_generator.pyi,sha256=YrqaEq8SfCo-C2EvuMDL9Kg3n1YZPSzF_1EshkuB3Ec,24009 +numpy/random/_mt19937.cpython-310-x86_64-linux-gnu.so,sha256=YkVYXa4gJERrnMb4b49df_uQBU8sUL4O3ksFZjOS9Sc,129912 +numpy/random/_mt19937.pyi,sha256=nX9OPiLcGFXn5cIE9k1TpvmVB0UBi9rlTsvGW5GP-Z0,775 +numpy/random/_pcg64.cpython-310-x86_64-linux-gnu.so,sha256=g5vQOqeeg9OqZ3M0I8pl_Ufkr1NRRcD3OE18iGQtPvg,136480 +numpy/random/_pcg64.pyi,sha256=gljmVLjVlgAMWGzQa6pzlzNW5H8kBvgDseQfIQcjy3k,1142 +numpy/random/_philox.cpython-310-x86_64-linux-gnu.so,sha256=sWbAZy7bRsHJy_cghn2VrqLpoyO8BpFXyfDBWITqWII,116832 +numpy/random/_philox.pyi,sha256=xf8EUX7Wa7-tYSU0LntUxMDVrNVcmjgACbubrb0O5sI,1005 +numpy/random/_pickle.py,sha256=4iS9ofvvuD0KKMtRpZEdBslH79blhK8wtjqxeWN_gcE,2743 +numpy/random/_pickle.pyi,sha256=Qdd9MkruVUeduANTkweO8dLNbeYegtOLVgnF6j0lRQE,1608 +numpy/random/_sfc64.cpython-310-x86_64-linux-gnu.so,sha256=szXEbXBD24KLfxJJV5grxfpRCngMNi6_AtTRgcujQWw,89864 +numpy/random/_sfc64.pyi,sha256=gdDHDFsH-o-OB6zKJJqj8vNYvRm0GMXHApikapFvv50,682 +numpy/random/bit_generator.cpython-310-x86_64-linux-gnu.so,sha256=-gJgI4T2aNVVF2GhTGFok6AawCllCSza9SuG_SWE2cM,242528 +numpy/random/bit_generator.pxd,sha256=lArpIXSgTwVnJMYc4XX0NGxegXq3h_QsUDK6qeZKbNc,1007 +numpy/random/bit_generator.pyi,sha256=sXPTnGMgICncbhgGBPZvwTv2mcS4ENKB4G4PIhCqTaQ,3534 +numpy/random/c_distributions.pxd,sha256=UCtqx0Nf-vHuJVaqPlLFURWnaI1vH-vJRE01BZDTL9o,6335 +numpy/random/lib/libnpyrandom.a,sha256=-1eNSFrUGkCTqr47fgZpBAXE8Qa0kpQAYOlGJJctVWw,72270 +numpy/random/mtrand.cpython-310-x86_64-linux-gnu.so,sha256=DvNDctGI7c15R3enKi64YBDxdzbT1xlbS9a_hI6nkGw,797808 +numpy/random/mtrand.pyi,sha256=NUzAPLtDaft-xJlKUx4u1e3QwnofZbWgt2KEV8_GiAY,22018 +numpy/random/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/random/tests/data/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/random/tests/data/generator_pcg64_np121.pkl.gz,sha256=EfQ-X70KkHgBAFX2pIPcCUl4MNP1ZNROaXOU75vdiqM,203 +numpy/random/tests/data/generator_pcg64_np126.pkl.gz,sha256=fN8deNVxX-HELA1eIZ32kdtYvc4hwKya6wv00GJeH0Y,208 +numpy/random/tests/data/mt19937-testset-1.csv,sha256=Xkef402AVB-eZgYQkVtoxERHkxffCA9Jyt_oMbtJGwY,15844 +numpy/random/tests/data/mt19937-testset-2.csv,sha256=nsBEQNnff-aFjHYK4thjvUK4xSXDSfv5aTbcE59pOkE,15825 +numpy/random/tests/data/pcg64-testset-1.csv,sha256=xB00DpknGUTTCxDr9L6aNo9Hs-sfzEMbUSS4t11TTfE,23839 +numpy/random/tests/data/pcg64-testset-2.csv,sha256=NTdzTKvG2U7_WyU_IoQUtMzU3kEvDH39CgnR6VzhTkw,23845 +numpy/random/tests/data/pcg64dxsm-testset-1.csv,sha256=vNSUT-gXS_oEw_awR3O30ziVO4seNPUv1UIZ01SfVnI,23833 +numpy/random/tests/data/pcg64dxsm-testset-2.csv,sha256=uylS8PU2AIKZ185OC04RBr_OePweGRtvn-dE4YN0yYA,23839 +numpy/random/tests/data/philox-testset-1.csv,sha256=SedRaIy5zFadmk71nKrGxCFZ6BwKz8g1A9-OZp3IkkY,23852 +numpy/random/tests/data/philox-testset-2.csv,sha256=dWECt-sbfvaSiK8-Ygp5AqyjoN5i26VEOrXqg01rk3g,23838 +numpy/random/tests/data/sfc64-testset-1.csv,sha256=iHs6iX6KR8bxGwKk-3tedAdMPz6ZW8slDSUECkAqC8Q,23840 +numpy/random/tests/data/sfc64-testset-2.csv,sha256=FIDIDFCaPZfWUSxsJMAe58hPNmMrU27kCd9FhCEYt_k,23833 +numpy/random/tests/data/sfc64_np126.pkl.gz,sha256=MVa1ylFy7DUPgUBK-oIeKSdVl4UYEiN3AZ7G3sdzzaw,290 +numpy/random/tests/test_direct.py,sha256=Ce2wQHcNV33qnkeHbORji-SW55RnHQ2vUdGXK1YVJBk,19956 +numpy/random/tests/test_extending.py,sha256=po8h6ASy9-C0LHPKKpjYyAokOSj_xKh9FeQAavb4GBA,4435 +numpy/random/tests/test_generator_mt19937.py,sha256=Z7D8PciFoaYF_XCtINHzfjovWZHqgWmVOJ2UjvNkWlM,117288 +numpy/random/tests/test_generator_mt19937_regressions.py,sha256=r2wzyXTRfyVk__f2PO9yKPRdwx5ez671OQyAglMfPpc,8094 +numpy/random/tests/test_random.py,sha256=i44DXCHEBtKtOzwSBfADh_kBSjMPgaCJYHdFfs6sfCQ,70150 +numpy/random/tests/test_randomstate.py,sha256=Cp-op2kfopZ8wq-SBQ12Mh5RQ0p8mcBQHYSh0h-DegU,85275 +numpy/random/tests/test_randomstate_regression.py,sha256=xS_HOwtijRdgq-gZn0IDUcm0NxdjjJXYv6ex8WN7FPU,7999 +numpy/random/tests/test_regression.py,sha256=RbAzZYLfyzUKmup5uJR19sK2N17L_d1rLRy-CWjtIaQ,5462 +numpy/random/tests/test_seed_sequence.py,sha256=GNRJ4jyzrtfolOND3gUWamnbvK6-b_p1bBK_RIG0sfU,3311 +numpy/random/tests/test_smoke.py,sha256=CsXvEgv1T3wvCAH6qYu8RCWoQOaI4_gm7aWNhAS4QRg,28174 +numpy/rec/__init__.py,sha256=w2G_npkmqm5vrWgds8V6Gusehmi1bRbiqCxsl9yOjow,83 +numpy/rec/__init__.pyi,sha256=NWclXeZGtb9EvxymXj71lqOCKxcZPZawS-JJkc54_zQ,346 +numpy/strings/__init__.py,sha256=-hT1HYpbswLkRWswieJQwAYn72IAwuaSCA5S1sdSPMk,83 +numpy/strings/__init__.pyi,sha256=lDQvuJEXEx7Iw-8E-srZS6RkJzN19GQ_POsbyhFWMec,1295 +numpy/testing/__init__.py,sha256=InpVKoDAzMKO_l_HNcatziW_u1k9_JZze__t2nybrL0,595 +numpy/testing/__init__.pyi,sha256=1jr2Gj9BmCdtK4bqNGkwUAuqwC4n2JPOy6lqczK7xpA,2045 +numpy/testing/_private/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/testing/_private/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/testing/_private/extbuild.py,sha256=fy4Dl-CqMtqBu6MShJNIe9DAuYH8kN_XZlUdOVcb1hQ,8106 +numpy/testing/_private/extbuild.pyi,sha256=aNH6UnAhh4Zny81W45GrAcScB12b6_84y8M0Vdtpm2I,626 +numpy/testing/_private/utils.py,sha256=UrWpMfsgQD54K46uj00dAVx1Pbl8JFCr0_yb7m1uZkQ,95700 +numpy/testing/_private/utils.pyi,sha256=y4UuOhHLN9aThPfajrNL9Q86zqYmk03uB0Wv3MlOamo,12967 +numpy/testing/overrides.py,sha256=IiVwsm3cDwnJdrk0FUFh7JLJYEnR_AfYWQRqWIeOFNQ,2133 +numpy/testing/overrides.pyi,sha256=IQvQLxD-dHcbTQOZEO5bnCtCp8Uv3vj51dl0dZ0htjg,397 +numpy/testing/print_coercion_tables.py,sha256=v9RlpFnOlaw34QGWnDIovDGhG1clwGhha0UnCqni0RE,6223 +numpy/testing/print_coercion_tables.pyi,sha256=02D1q0WeMJ8B6txT_dy2Kn7IWse2RLRJQV0M6ifLD_w,821 +numpy/testing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/testing/tests/test_utils.py,sha256=eMHfDFj21KcKuv8-aWhwdm3rHhIirtUkZJss-Qffggw,70456 +numpy/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/tests/test__all__.py,sha256=L3mCnYPTpzAgNfedVuq9g7xPWbc0c1Pot94k9jZ9NpI,221 +numpy/tests/test_configtool.py,sha256=lhtwsoUPSOSdgnSdxvrvS4roiid86eWzSrGjdrKkH7g,1555 +numpy/tests/test_ctypeslib.py,sha256=c0x56qlAMnxTCO9MiuV05LCoqju8cidHj1URV5gOwQE,12351 +numpy/tests/test_lazyloading.py,sha256=R3Idpr9XIZ8C83sy8NvWSsh9knKxi42TAON13HpGRq0,1159 +numpy/tests/test_matlib.py,sha256=gwhIXrJJo9DiecaGLCHLJBjhx2nVGl6yHq80AOUQSRM,1852 +numpy/tests/test_numpy_config.py,sha256=x0OH4_gNx-13qw1_GYihFel1S4bWEzbrR_VT-H9x4tQ,1233 +numpy/tests/test_numpy_version.py,sha256=2d0EtPJZYP3XRE6C6rfJW6QsPlFoDxqgO1yPxObaiE0,1754 +numpy/tests/test_public_api.py,sha256=mG_c04GeGEue8ppN5G8djdNyVFe4vKUiBLoiO4h-dhU,27664 +numpy/tests/test_reloading.py,sha256=sGu5XM-_VCNphyJcY5VCoQCmy5MgtL6_hDnsqf2j_ro,2367 +numpy/tests/test_scripts.py,sha256=jluCLfG94VM1cuX-5RcLFBli_yaJZpIvmVuMxRKRJrc,1645 +numpy/tests/test_warnings.py,sha256=HOqWSVu80PY-zacrgMfzPF0XPqEC24BNSw6Lmvw32Vg,2346 +numpy/typing/__init__.py,sha256=ph9_WtDCJ7tKrbbRcz5OZEbXwxRXZfzSd2K1mLab910,5267 +numpy/typing/mypy_plugin.py,sha256=eghgizS6dx7VuQiNbQg_cCfzNBb7Kyt3AomPNB8uml0,6470 +numpy/typing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy/typing/tests/data/fail/arithmetic.pyi,sha256=OMnzSP_4S06yDMzOWeMS36r8Ew5EYzc0cFcr5JURf7c,3963 +numpy/typing/tests/data/fail/array_constructors.pyi,sha256=SjiwoGrefYsuScJcBQZlwzfvENADeRMxHYCDCo685Vc,1129 +numpy/typing/tests/data/fail/array_like.pyi,sha256=V9lNwYrNOvOyHf5xtCZerofTXdubpvl1pzZMsEWD2U0,526 +numpy/typing/tests/data/fail/array_pad.pyi,sha256=57oK0Yp53rtKjjIrRFYLcxa-IfIGhtI-bEem7ggJKwI,132 +numpy/typing/tests/data/fail/arrayprint.pyi,sha256=NZlON-sYl2s6-iUFKZZpXF4WnGVHQbTn8yIsQm0Alg4,586 +numpy/typing/tests/data/fail/arrayterator.pyi,sha256=Qb7oMI1GdDQO_jcoJEAsMkXLjzOdcb3sx-b5mW73cAE,470 +numpy/typing/tests/data/fail/bitwise_ops.pyi,sha256=gJ-ZL-e-yMbHMRKUv8r2KqJ08Mkgpg74nUe6lgi2RDU,583 +numpy/typing/tests/data/fail/char.pyi,sha256=Zi3dygeaxHT8-5aFNCAreGU-T89zLg5pcE6c9NBCs6c,2712 +numpy/typing/tests/data/fail/chararray.pyi,sha256=wdBMnihqJoeEMdSKz5Ur60qCDCVmiuHdTl4WmriTanc,2307 +numpy/typing/tests/data/fail/comparisons.pyi,sha256=YrcL2POtM1g8GEWW4AJMl9vAkV-lG_6kEb7FzueeiLU,822 +numpy/typing/tests/data/fail/constants.pyi,sha256=IzmswvmTKbAOkCjgyxu1jChlikIwqeAETHGVH2TtY0k,85 +numpy/typing/tests/data/fail/datasource.pyi,sha256=gACpSdzMDej9WZbNvDQlkWX9DvHD7DjucesbH0EWEaM,405 +numpy/typing/tests/data/fail/dtype.pyi,sha256=OAGABqdXNB8gClJFEGMckoycuZcIasMaAlS2RkiKROI,334 +numpy/typing/tests/data/fail/einsumfunc.pyi,sha256=32Bsrr3ueX2CMaiBZN1xLGGsbjqKZWF2WopvNWRqCT4,487 +numpy/typing/tests/data/fail/flatiter.pyi,sha256=JcggwDkKcMWDBz0Ky8-dkJzjwnKxQ-kyea5br5DDqq0,866 +numpy/typing/tests/data/fail/fromnumeric.pyi,sha256=NuOpn-kPy4g80PlAVVQZfhXwP6wITijvyTs0_uuzAyw,5703 +numpy/typing/tests/data/fail/histograms.pyi,sha256=yAPVt0rYTwtxnigoGT-u7hhKCE9iYxsXc24x2HGBrmA,367 +numpy/typing/tests/data/fail/index_tricks.pyi,sha256=moINir9iQoi6Q1ZuVg5BuSB9hSBtbg_uzv-Qm_lLYZk,509 +numpy/typing/tests/data/fail/lib_function_base.pyi,sha256=0FBv6CYJMDrL0U9cGsiO5a0boUrBCSB4eFHHLVjBzEo,2689 +numpy/typing/tests/data/fail/lib_polynomial.pyi,sha256=Ur7Y4iZX6WmoH5SDm0ePi8C8LPsuPs2Yr7g7P5O613g,899 +numpy/typing/tests/data/fail/lib_utils.pyi,sha256=6oI_kPhJqL0P0q-rsC3WtGso3V-hF7ntbNUmbhUPfXE,96 +numpy/typing/tests/data/fail/lib_version.pyi,sha256=7-ZJDZwDcB-wzpMN8TeYtZAgaqc7xnQ8Dnx2ISiX2Ts,158 +numpy/typing/tests/data/fail/linalg.pyi,sha256=yDd05aK1dI37RPt3pD2eJYo4dZFaT2yB1PEu3K0y9Tg,1322 +numpy/typing/tests/data/fail/memmap.pyi,sha256=HSTCQYNuW1Y6X1Woj361pN4rusSPs4oDCXywqk20yUo,159 +numpy/typing/tests/data/fail/modules.pyi,sha256=K73WuMJxw7zo3oALIcTuNfU4sPlKeGzEUxPlL1f97cM,621 +numpy/typing/tests/data/fail/multiarray.pyi,sha256=1_9X7BW6hukiappz0kn3WCWN6OWXtT6OQqmJmJpdkfQ,1643 +numpy/typing/tests/data/fail/ndarray.pyi,sha256=cgoWlpQqBQ5pkfiYsoz2f6o-DASrVRCraKBCgXLJQSk,404 +numpy/typing/tests/data/fail/ndarray_misc.pyi,sha256=H2bpfqfd04Syto7SLWJOq-gWmCCzRWJpLIiQVPI0qE0,1000 +numpy/typing/tests/data/fail/nditer.pyi,sha256=w7emjnOxnf3NcvLktNLlke6Cuivn2gU3sVmGCfbG6rw,325 +numpy/typing/tests/data/fail/nested_sequence.pyi,sha256=em4GZwLDFE0QSxxg081wVwhh-Dmtkn8f7wThI0DiXVs,427 +numpy/typing/tests/data/fail/npyio.pyi,sha256=Jsl8KB55PwQ2Xz9jXtL3j-G1RIQLCcEuLJmO_o3hZBI,628 +numpy/typing/tests/data/fail/numerictypes.pyi,sha256=jl_pxMAq_VmkaK13-sfhUOUYGAQ4OV2pQ1d7wG-DNZg,120 +numpy/typing/tests/data/fail/random.pyi,sha256=0sFOsJeHwYc1cUNF-MByWONEF_MP8CQWTjdyGFvgl90,2821 +numpy/typing/tests/data/fail/rec.pyi,sha256=Ws3TyesnoQjt7Q0wwtpShRDJmZCs2jjP17buFMomVGA,704 +numpy/typing/tests/data/fail/scalars.pyi,sha256=P_l-XImP_R7YQirkuv5aRmYaLgExJs8Djl0_mDbdKsk,2862 +numpy/typing/tests/data/fail/shape.pyi,sha256=pSxiQ6Stq60xGFKOGZUsisxIO0y4inJ8UpKeio89K04,137 +numpy/typing/tests/data/fail/shape_base.pyi,sha256=Y_f4buHtX2Q2ZA4kaDTyR8LErlPXTzCB_-jBoScGh_Q,152 +numpy/typing/tests/data/fail/stride_tricks.pyi,sha256=IjA0Xrnx0lG3m07d1Hjbhtyo1Te5cXgjgr5fLUo4LYQ,315 +numpy/typing/tests/data/fail/strings.pyi,sha256=AiH368QQsUT6JVWgePOei4TRpKGGT-3z2NvswSoRT_U,2370 +numpy/typing/tests/data/fail/testing.pyi,sha256=xEUrFKLL8_gt3RV7d6NbF9a6zu2uaKcWBIN_pqGS_Ds,1343 +numpy/typing/tests/data/fail/twodim_base.pyi,sha256=eRFtqBbwkVI6G6MZMVpep1UKnFMDYzhrN82fO3ilnH0,898 +numpy/typing/tests/data/fail/type_check.pyi,sha256=CIyI0j0Buxv0QgCvNG2urjaKpoIZ-ZNawC2m6NzGlbo,379 +numpy/typing/tests/data/fail/ufunc_config.pyi,sha256=0t_yJ4eVOhneDSfa3EsoTh6RreyMtkHVOi9oQ35_EW0,734 +numpy/typing/tests/data/fail/ufunclike.pyi,sha256=JsJ3M8QZv9-6GKwRnojJGIfeIkdtJFe-3ix5reLXx-M,627 +numpy/typing/tests/data/fail/ufuncs.pyi,sha256=8N8m_GbRAH0bWjDEzYnH4MREX86iBD46Ug9mm-vc1co,476 +numpy/typing/tests/data/fail/warnings_and_errors.pyi,sha256=KXExnFGz9O7Veut_U7YEIpi6x-BdfeaGtpqWf1Yd274,185 +numpy/typing/tests/data/misc/extended_precision.pyi,sha256=bS8bBeCFqjgtOiy-8_y39wfa7rwhdjLz2Vmo-RXAYD4,884 +numpy/typing/tests/data/mypy.ini,sha256=6yPaDeYIVWc-WNRdSjAYOGlSVCWkmcge2Te8JAmhjpI,285 +numpy/typing/tests/data/pass/arithmetic.py,sha256=e71PA71VJitjkF8wrmui2F2zoTt0iOCW2tfbCpNDYlQ,7447 +numpy/typing/tests/data/pass/array_constructors.py,sha256=rfJ8SRB4raElxRjsHBCsZIkZAfqZMie0VE8sSKMgkHg,2447 +numpy/typing/tests/data/pass/array_like.py,sha256=ddPI6pA27qnp1INWs4Yi3wCqoVypSRMxstO771WQS5c,1056 +numpy/typing/tests/data/pass/arrayprint.py,sha256=y_KkuLz1uM7pv53qfq7GQOuud4LoXE3apK1wtARdVyM,766 +numpy/typing/tests/data/pass/arrayterator.py,sha256=FqcpKdUQBQ0FazHFxr9MsLEZG-jnJVGKWZX2owRr4DQ,393 +numpy/typing/tests/data/pass/bitwise_ops.py,sha256=FmEs_sKaU9ox-5f0NU3_TRIv0XxLQVEZ8rou9VNehb4,964 +numpy/typing/tests/data/pass/comparisons.py,sha256=5aGrNl3D7Yd1m9WVkHrjJtqi7SricTxrEMtmIV9x0aE,3298 +numpy/typing/tests/data/pass/dtype.py,sha256=YDuYAb0oKoJc9eOnKJuoPfLbIKOgEdE04_CYxRS4U5I,1070 +numpy/typing/tests/data/pass/einsumfunc.py,sha256=eXj5L5MWPtQHgrHPsJ36qqrmBHqct9UoujjJCvHnF1k,1370 +numpy/typing/tests/data/pass/flatiter.py,sha256=0BnbuLMBC7MQlprNZ0QhNSscfYwPhEhXOhWoyiRACWU,174 +numpy/typing/tests/data/pass/fromnumeric.py,sha256=d_hVLyrVDFPVx33aqLIyAGYYQ8XAJFIzrAsE8QCoof4,3991 +numpy/typing/tests/data/pass/index_tricks.py,sha256=dmonWJMUKsXg23zD_mibEEtd4b5ys-sEfT9Fnnq08x8,1402 +numpy/typing/tests/data/pass/lib_user_array.py,sha256=Za_n84msWtV8dqQZhMhvh7lzu5WZvO8ixTPkEqO2Hms,590 +numpy/typing/tests/data/pass/lib_utils.py,sha256=bj1sEA4gsmezqbYdqKnVtKzY_fb64w7PEoZwNvaaUdA,317 +numpy/typing/tests/data/pass/lib_version.py,sha256=HnuGOx7tQA_bcxFIJ3dRoMAR0fockxg4lGqQ4g7LGIw,299 +numpy/typing/tests/data/pass/literal.py,sha256=WKT1I15Iw37bqkgBlY1h1_Kb_gs1Qme8Wy3wTr0op90,1504 +numpy/typing/tests/data/pass/ma.py,sha256=slJZQFGPI4I13qc-CRfreEGhIUk4TdFk-Pv75yWanNM,171 +numpy/typing/tests/data/pass/mod.py,sha256=owFL1fys3LPTWpAlsjS-IzW4sSu98ncp2BnsIetLSrA,1576 +numpy/typing/tests/data/pass/modules.py,sha256=g9PhyLO6rflYHZtmryx1VWTubphN4TAPUSfoiYriTqE,625 +numpy/typing/tests/data/pass/multiarray.py,sha256=MxHax6l94yqlTVZleAqG77ILEbW6wU5osPcHzxJ85ns,1331 +numpy/typing/tests/data/pass/ndarray_conversion.py,sha256=d7cFNUrofdLXh9T_9RG3Esz1XOihWWQNlz5Lb0yt6dM,1525 +numpy/typing/tests/data/pass/ndarray_misc.py,sha256=om45RP2VtXvEhbprrJzh09S6OGQvlqrLi2B9JFTOKxc,3466 +numpy/typing/tests/data/pass/ndarray_shape_manipulation.py,sha256=37eYwMNqMLwanIW9-63hrokacnSz2K_qtPUlkdpsTjo,640 +numpy/typing/tests/data/pass/nditer.py,sha256=nYO45Lw3ZNbQq75Vht86zzLZ4cWzP3ml0rxDPlYt8_8,63 +numpy/typing/tests/data/pass/numeric.py,sha256=wbmYMkK1LM34jjFek8VFJYyade_L6u7XqjpdqGyoRwU,1625 +numpy/typing/tests/data/pass/numerictypes.py,sha256=6x6eN9-5NsSQUSc6rf3fYieS2poYEY0t_ujbwgF9S5Q,331 +numpy/typing/tests/data/pass/random.py,sha256=UJF6epKYGfGq9QlrR9YuA7EK_mI8AQ2osdA4Uhsh1ms,61824 +numpy/typing/tests/data/pass/recfunctions.py,sha256=_rcCY44c3LnxMFjoLcnOlVc9yXKbRUIY2nIkNoar9h4,5037 +numpy/typing/tests/data/pass/scalars.py,sha256=OAfNg3VYmO-iSxQCSmY_OUyUjCwcRIKwiT-OR52FFP4,3725 +numpy/typing/tests/data/pass/shape.py,sha256=0nyLAArcbN6JQQDqBhLkJ_nYj5z0zpQnaZLWIMPO8PQ,449 +numpy/typing/tests/data/pass/simple.py,sha256=lPj620zkTA8Sg893eu2mGuj-Xq2BGZ_1dcmfsVDkz8g,2751 +numpy/typing/tests/data/pass/simple_py3.py,sha256=HuLrc5aphThQkLjU2_19KgGFaXwKOfSzXe0p2xMm8ZI,96 +numpy/typing/tests/data/pass/ufunc_config.py,sha256=uzXOhCl9N4LPV9hV2Iqg_skgkKMbBPBF0GXPU9EMeuE,1205 +numpy/typing/tests/data/pass/ufunclike.py,sha256=U4Aay11VALvm22bWEX0eDWuN5qxJlg_hH5IpOL62M3I,1125 +numpy/typing/tests/data/pass/ufuncs.py,sha256=1Rem_geEm4qyD3XaRA1NAPKwr3YjRq68zbIlC_Xhi9M,422 +numpy/typing/tests/data/pass/warnings_and_errors.py,sha256=ETLZkDTGpZspvwjVYAZlnA1gH4PJ4bSY5PkWyxTjusU,161 +numpy/typing/tests/data/reveal/arithmetic.pyi,sha256=pI3XrneSswKnOSa0a-9hsr7v9e4jDWO7v-gMQ81KLs4,25295 +numpy/typing/tests/data/reveal/array_api_info.pyi,sha256=1LZSBV-FCdju6HBjBCJOLdcuMVuEdSN8-fkx-rldUZg,3047 +numpy/typing/tests/data/reveal/array_constructors.pyi,sha256=RcwCSgtaDh4hjU7dcqoLb1tzxDp6vaifGosO3niJ33c,12573 +numpy/typing/tests/data/reveal/arraypad.pyi,sha256=m8yoSEuxGmbHDnTIXBN-ZHAI6rMEtre65Yk3Uopdogg,688 +numpy/typing/tests/data/reveal/arrayprint.pyi,sha256=8I-_vItFAU5e4B6Ty9wsa_Y1Nzw3lh_EvmSokbClUW8,817 +numpy/typing/tests/data/reveal/arraysetops.pyi,sha256=SlBlsdITj2PeaR_by03nysRHYPh3G9gkvvcj5cKgFWA,4424 +numpy/typing/tests/data/reveal/arrayterator.pyi,sha256=LKnpHT_L3_qzzeAORwVlWCLtJoo_42GXN2ZHyuWx9T0,1069 +numpy/typing/tests/data/reveal/bitwise_ops.pyi,sha256=sEVMpf-QBsTDAEaiM9obInASKTDRQLVk2Ej8DWN5nLY,5049 +numpy/typing/tests/data/reveal/char.pyi,sha256=wzkpRgHWgv4wQ1_KMnjakWN3B_p283kHn8TmP5nYJTY,10846 +numpy/typing/tests/data/reveal/chararray.pyi,sha256=mbUYgjsaPHUcsQsCXkUo8Fi3H6gB84hQEo4DaM0US_o,6651 +numpy/typing/tests/data/reveal/comparisons.pyi,sha256=iZeK0iGQIiYt1IULgT7S1tR_feHyGkaY8wUaO9KOK3o,7225 +numpy/typing/tests/data/reveal/constants.pyi,sha256=rXWIPvzafsXTbyTNOYfbUlK_j5xiz3XFNIGIrl7aKQI,362 +numpy/typing/tests/data/reveal/ctypeslib.pyi,sha256=DIPa9-dZLtghcevcABNQ3hpWiiPqdbpA2TT7SmrWyJE,4737 +numpy/typing/tests/data/reveal/datasource.pyi,sha256=ROEU-LBTqzDCV_afVI-cb4qdn0UFWvSj9pjHsArBQyE,613 +numpy/typing/tests/data/reveal/dtype.pyi,sha256=YclNqAAyjzNK6YCMvuHJWmVDVu_Kr30l2vPqz4GSrm8,5213 +numpy/typing/tests/data/reveal/einsumfunc.pyi,sha256=BZZQikSpk-ePbbWkW2b1VO1_BXFlaqQt2d0BYKE7WTQ,1956 +numpy/typing/tests/data/reveal/emath.pyi,sha256=CHRd-4151gruyI2sao65epcdtaLdnGzmHfF3MJFIeNc,2335 +numpy/typing/tests/data/reveal/fft.pyi,sha256=lcl6ZRCWilYyynSB12HyTmGa0ZEKDIhKqMRrgOLisiM,1661 +numpy/typing/tests/data/reveal/flatiter.pyi,sha256=M4dnFct3SheA2EkpIrR3ECxP5pAjjnC5C5Aelkb6DAk,1377 +numpy/typing/tests/data/reveal/fromnumeric.pyi,sha256=44SIUac6GFQH-quhitXIU2AaFvFfEPubswM-yvIAw_c,14917 +numpy/typing/tests/data/reveal/getlimits.pyi,sha256=FP6d4LrkydJ7KRJ2tIfBvjKW0FyAio6XxIhKca8EJvs,1582 +numpy/typing/tests/data/reveal/histograms.pyi,sha256=ttfsdZBRqQzIfujkhNHExs20tH8qtCwJv5Yc4EAUwlk,1287 +numpy/typing/tests/data/reveal/index_tricks.pyi,sha256=jdU0xs46CnK8haxTqZ-Z-aONablqKeJrN5cQGxCw7bg,3271 +numpy/typing/tests/data/reveal/lib_function_base.pyi,sha256=EkWPmm41sgaDg7On5EkEKvTXsy74juuuxV36VdrCwtE,9877 +numpy/typing/tests/data/reveal/lib_polynomial.pyi,sha256=Z2mFp-281D_zd5YbtgiliDTKk6akckOiLkOXbLnwPO4,5895 +numpy/typing/tests/data/reveal/lib_utils.pyi,sha256=ysQO1QVJvj9Z5iTLW1z7xMJmNch2qwTGbHL77aVOHKw,448 +numpy/typing/tests/data/reveal/lib_version.pyi,sha256=9KSTL1-sf93KZmAFyc_xXTIufDMapHAfXHtXVR8gO-4,583 +numpy/typing/tests/data/reveal/linalg.pyi,sha256=DvWeTqPSyO_OlSxnkZbJkkEV7igdd-iMvMju2Zd2z2w,6236 +numpy/typing/tests/data/reveal/matrix.pyi,sha256=C1-xZV_MN3wSeRxiPOg3r2_kmOhYrMXCmJC_U4dVcDc,3048 +numpy/typing/tests/data/reveal/memmap.pyi,sha256=UdYaTVuRbMceCVMozcMTzdZ5qRrplzvovHChCvW55jg,754 +numpy/typing/tests/data/reveal/mod.pyi,sha256=vroL10xpg449us1stjWkWFLBF6kPt9vQbsR1IF17-Z4,7611 +numpy/typing/tests/data/reveal/modules.pyi,sha256=zOe7G_ofnwwwPQMdkKjI3mwt-xIy1kN-DjvWLQvm0r8,1870 +numpy/typing/tests/data/reveal/multiarray.pyi,sha256=ZYxzWuPoPn88crNn92hINm07OFBRiSv2A2l26yi0w2I,7865 +numpy/typing/tests/data/reveal/nbit_base_example.pyi,sha256=x6QK76bchnI-u4D6b0AFxcLp2Kvzv-BJCwUwe3NY9N4,587 +numpy/typing/tests/data/reveal/ndarray_assignability.pyi,sha256=vEDA7m6QDxM_sAR2PyY19IUCmspR3Te-bdD50M-RhJM,2698 +numpy/typing/tests/data/reveal/ndarray_conversion.pyi,sha256=N635zekh5wJfvTIFFI5tNc4NQVkyLLna1Wy4auihJMM,3377 +numpy/typing/tests/data/reveal/ndarray_misc.pyi,sha256=kmW4gdoV3TvOiO3jWKqoBnuiWp1tBunnsvs3Aggvf-4,7903 +numpy/typing/tests/data/reveal/ndarray_shape_manipulation.pyi,sha256=9mPnQJofJ8vh9WQwWqNFxgQ6_f9Mv9rEU3iDXWnfbbQ,1405 +numpy/typing/tests/data/reveal/nditer.pyi,sha256=c9DdxgUOnm886w3f3L2trxHMyOF5s-w8_2DZHRdbhwM,1933 +numpy/typing/tests/data/reveal/nested_sequence.pyi,sha256=-o-5gOFUflvmU_pJRIfuKVP0xi4oxTAUYRPeHRtHiLk,646 +numpy/typing/tests/data/reveal/npyio.pyi,sha256=vrJNIovhI6cCpV0XrdISixluzR83i3z0PKr5jk6PuNo,3523 +numpy/typing/tests/data/reveal/numeric.pyi,sha256=9wq71fIj5gT5xMditz8zM79adfF1bvyfJJCy7DfKok0,6081 +numpy/typing/tests/data/reveal/numerictypes.pyi,sha256=nIJSi3T3S5v9sOyvh0IgllEHjGLE-a1W0sMowo11-_A,1361 +numpy/typing/tests/data/reveal/polynomial_polybase.pyi,sha256=EwzpzZnJnqxbe7W6MR0xJC-kzTRR428pXJDE6MgoNd4,7999 +numpy/typing/tests/data/reveal/polynomial_polyutils.pyi,sha256=T1c-C1-b0k0j61OnlrhTkWUN6Pftdaccw8bwGX7dDN0,10764 +numpy/typing/tests/data/reveal/polynomial_series.pyi,sha256=2h3B9w8TPr7Gypr0-s6ITeOZ3iQ4VDgpaKi5T440U_I,7128 +numpy/typing/tests/data/reveal/random.pyi,sha256=TlY_xhK3U--2Q1KiEkErDOvIxAHaqafHnTKMA_rv6U0,104329 +numpy/typing/tests/data/reveal/rec.pyi,sha256=ZvdqHUobAT4UeiogaAm_nVg27YSJRwUQwMtqJOJawT4,3776 +numpy/typing/tests/data/reveal/scalars.pyi,sha256=e7J0o8MAE_Henqh6Zcwv24NgCKgOlvOQ95MUdptmDzA,6449 +numpy/typing/tests/data/reveal/shape.pyi,sha256=r0y0iSyVabz6hnIRQFdomLV6yvPqiXrGm0pVtTmm1Eg,292 +numpy/typing/tests/data/reveal/shape_base.pyi,sha256=W1wxdfVHMxzuX-c0BcR3UJkDiE2re6ODypZjSX1nNnY,2046 +numpy/typing/tests/data/reveal/stride_tricks.pyi,sha256=J3Kagblme0GxDnJFW_v1M1Ak28Bdep-8P0LA3tl3KuA,1345 +numpy/typing/tests/data/reveal/strings.pyi,sha256=hZepuR_eOIKB2Ja6sw7VQ1LpIDE0cu9Z38YmlVTG-8Q,9415 +numpy/typing/tests/data/reveal/testing.pyi,sha256=-XIbu-GFxdz3AuiEa8Xwlq9n02eRbyJWacIgFwEtEYk,8483 +numpy/typing/tests/data/reveal/twodim_base.pyi,sha256=x5EgqxESpsFtvBsuTY1EmoyHBCr9aTCeg133oBUQuv0,4299 +numpy/typing/tests/data/reveal/type_check.pyi,sha256=H4d9guDEa4Hn_hty1Wy_R7q9UpACIzB2_pgoaHO4kZw,2711 +numpy/typing/tests/data/reveal/ufunc_config.pyi,sha256=tXala6x3dbwUI1S1yYPMo47oXti_1aX84ZHlrbI5WcI,1191 +numpy/typing/tests/data/reveal/ufunclike.pyi,sha256=F223MWONHITGeiJcpik_eLp8s56U2EsfLy73W-luTzM,1233 +numpy/typing/tests/data/reveal/ufuncs.pyi,sha256=Gf3782hgHd0-tW1bVhzJhJBSk9GvL-lki8vDpjblMFk,4819 +numpy/typing/tests/data/reveal/warnings_and_errors.pyi,sha256=quHpFR_zwWzV7WGpYDMzf7RkHbomqRYrc93JUB09tkg,460 +numpy/typing/tests/test_isfile.py,sha256=77lnjlxFqhrIRfGpSrqmvIVwpo9VoOPGiS7rRQSdKT0,865 +numpy/typing/tests/test_runtime.py,sha256=2qu8JEliITnZCBJ_QJpohacj_OQ08o73ixS2w2ooNXI,3275 +numpy/typing/tests/test_typing.py,sha256=wfRq_DQZg99tsuEQElXDtfbSmEOjkzEVizQB0cVp8-I,8308 +numpy/version.py,sha256=p_z6CLw9cwp3p9MewCe_U6lpWBLDU6Um3Qd9wUUbfXo,293 +numpy/version.pyi,sha256=tgN523dUbCHUTYs0QYz0HKchUfFwI9HKgoJY20rkewM,388 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy-2.2.6.dist-info/REQUESTED b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy-2.2.6.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy-2.2.6.dist-info/WHEEL b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy-2.2.6.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..4e4c38ae320920b8f083b87f408214cdecd350d2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy-2.2.6.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: meson +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_17_x86_64 +Tag: cp310-cp310-manylinux2014_x86_64 + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy-2.2.6.dist-info/entry_points.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy-2.2.6.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..963c00f7069bbcd2075093df390c8bfd73a109ce --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/numpy-2.2.6.dist-info/entry_points.txt @@ -0,0 +1,10 @@ +[array_api] +numpy = numpy + +[pyinstaller40] +hook-dirs = numpy:_pyinstaller_hooks_dir + +[console_scripts] +f2py = numpy.f2py.f2py2e:main +numpy-config = numpy._configtool:main + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_cupti_cu12-12.8.90.dist-info/INSTALLER b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_cupti_cu12-12.8.90.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_cupti_cu12-12.8.90.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_cupti_cu12-12.8.90.dist-info/License.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_cupti_cu12-12.8.90.dist-info/License.txt new file mode 100644 index 0000000000000000000000000000000000000000..b491c70e0aef319022ded661e111ddbd45b8a17f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_cupti_cu12-12.8.90.dist-info/License.txt @@ -0,0 +1,1568 @@ +End User License Agreement +-------------------------- + + +Preface +------- + +The Software License Agreement in Chapter 1 and the Supplement +in Chapter 2 contain license terms and conditions that govern +the use of NVIDIA software. By accepting this agreement, you +agree to comply with all the terms and conditions applicable +to the product(s) included herein. + + +NVIDIA Driver + + +Description + +This package contains the operating system driver and +fundamental system software components for NVIDIA GPUs. + + +NVIDIA CUDA Toolkit + + +Description + +The NVIDIA CUDA Toolkit provides command-line and graphical +tools for building, debugging and optimizing the performance +of applications accelerated by NVIDIA GPUs, runtime and math +libraries, and documentation including programming guides, +user manuals, and API references. + + +Default Install Location of CUDA Toolkit + +Windows platform: + +%ProgramFiles%\NVIDIA GPU Computing Toolkit\CUDA\v#.# + +Linux platform: + +/usr/local/cuda-#.# + +Mac platform: + +/Developer/NVIDIA/CUDA-#.# + + +NVIDIA CUDA Samples + + +Description + +This package includes over 100+ CUDA examples that demonstrate +various CUDA programming principles, and efficient CUDA +implementation of algorithms in specific application domains. + + +Default Install Location of CUDA Samples + +Windows platform: + +%ProgramData%\NVIDIA Corporation\CUDA Samples\v#.# + +Linux platform: + +/usr/local/cuda-#.#/samples + +and + +$HOME/NVIDIA_CUDA-#.#_Samples + +Mac platform: + +/Developer/NVIDIA/CUDA-#.#/samples + + +NVIDIA Nsight Visual Studio Edition (Windows only) + + +Description + +NVIDIA Nsight Development Platform, Visual Studio Edition is a +development environment integrated into Microsoft Visual +Studio that provides tools for debugging, profiling, analyzing +and optimizing your GPU computing and graphics applications. + + +Default Install Location of Nsight Visual Studio Edition + +Windows platform: + +%ProgramFiles(x86)%\NVIDIA Corporation\Nsight Visual Studio Edition #.# + + +1. License Agreement for NVIDIA Software Development Kits +--------------------------------------------------------- + + +Release Date: July 26, 2018 +--------------------------- + + +Important NoticeRead before downloading, installing, +copying or using the licensed software: +------------------------------------------------------- + +This license agreement, including exhibits attached +("Agreement”) is a legal agreement between you and NVIDIA +Corporation ("NVIDIA") and governs your use of a NVIDIA +software development kit (“SDK”). + +Each SDK has its own set of software and materials, but here +is a description of the types of items that may be included in +a SDK: source code, header files, APIs, data sets and assets +(examples include images, textures, models, scenes, videos, +native API input/output files), binary software, sample code, +libraries, utility programs, programming code and +documentation. + +This Agreement can be accepted only by an adult of legal age +of majority in the country in which the SDK is used. + +If you are entering into this Agreement on behalf of a company +or other legal entity, you represent that you have the legal +authority to bind the entity to this Agreement, in which case +“you” will mean the entity you represent. + +If you don’t have the required age or authority to accept +this Agreement, or if you don’t accept all the terms and +conditions of this Agreement, do not download, install or use +the SDK. + +You agree to use the SDK only for purposes that are permitted +by (a) this Agreement, and (b) any applicable law, regulation +or generally accepted practices or guidelines in the relevant +jurisdictions. + + +1.1. License + + +1.1.1. License Grant + +Subject to the terms of this Agreement, NVIDIA hereby grants +you a non-exclusive, non-transferable license, without the +right to sublicense (except as expressly provided in this +Agreement) to: + + 1. Install and use the SDK, + + 2. Modify and create derivative works of sample source code + delivered in the SDK, and + + 3. Distribute those portions of the SDK that are identified + in this Agreement as distributable, as incorporated in + object code format into a software application that meets + the distribution requirements indicated in this Agreement. + + +1.1.2. Distribution Requirements + +These are the distribution requirements for you to exercise +the distribution grant: + + 1. Your application must have material additional + functionality, beyond the included portions of the SDK. + + 2. The distributable portions of the SDK shall only be + accessed by your application. + + 3. The following notice shall be included in modifications + and derivative works of sample source code distributed: + “This software contains source code provided by NVIDIA + Corporation.” + + 4. Unless a developer tool is identified in this Agreement + as distributable, it is delivered for your internal use + only. + + 5. The terms under which you distribute your application + must be consistent with the terms of this Agreement, + including (without limitation) terms relating to the + license grant and license restrictions and protection of + NVIDIA’s intellectual property rights. Additionally, you + agree that you will protect the privacy, security and + legal rights of your application users. + + 6. You agree to notify NVIDIA in writing of any known or + suspected distribution or use of the SDK not in compliance + with the requirements of this Agreement, and to enforce + the terms of your agreements with respect to distributed + SDK. + + +1.1.3. Authorized Users + +You may allow employees and contractors of your entity or of +your subsidiary(ies) to access and use the SDK from your +secure network to perform work on your behalf. + +If you are an academic institution you may allow users +enrolled or employed by the academic institution to access and +use the SDK from your secure network. + +You are responsible for the compliance with the terms of this +Agreement by your authorized users. If you become aware that +your authorized users didn’t follow the terms of this +Agreement, you agree to take reasonable steps to resolve the +non-compliance and prevent new occurrences. + + +1.1.4. Pre-Release SDK + +The SDK versions identified as alpha, beta, preview or +otherwise as pre-release, may not be fully functional, may +contain errors or design flaws, and may have reduced or +different security, privacy, accessibility, availability, and +reliability standards relative to commercial versions of +NVIDIA software and materials. Use of a pre-release SDK may +result in unexpected results, loss of data, project delays or +other unpredictable damage or loss. + +You may use a pre-release SDK at your own risk, understanding +that pre-release SDKs are not intended for use in production +or business-critical systems. + +NVIDIA may choose not to make available a commercial version +of any pre-release SDK. NVIDIA may also choose to abandon +development and terminate the availability of a pre-release +SDK at any time without liability. + + +1.1.5. Updates + +NVIDIA may, at its option, make available patches, workarounds +or other updates to this SDK. Unless the updates are provided +with their separate governing terms, they are deemed part of +the SDK licensed to you as provided in this Agreement. You +agree that the form and content of the SDK that NVIDIA +provides may change without prior notice to you. While NVIDIA +generally maintains compatibility between versions, NVIDIA may +in some cases make changes that introduce incompatibilities in +future versions of the SDK. + + +1.1.6. Third Party Licenses + +The SDK may come bundled with, or otherwise include or be +distributed with, third party software licensed by a NVIDIA +supplier and/or open source software provided under an open +source license. Use of third party software is subject to the +third-party license terms, or in the absence of third party +terms, the terms of this Agreement. Copyright to third party +software is held by the copyright holders indicated in the +third-party software or license. + + +1.1.7. Reservation of Rights + +NVIDIA reserves all rights, title, and interest in and to the +SDK, not expressly granted to you under this Agreement. + + +1.2. Limitations + +The following license limitations apply to your use of the +SDK: + + 1. You may not reverse engineer, decompile or disassemble, + or remove copyright or other proprietary notices from any + portion of the SDK or copies of the SDK. + + 2. Except as expressly provided in this Agreement, you may + not copy, sell, rent, sublicense, transfer, distribute, + modify, or create derivative works of any portion of the + SDK. For clarity, you may not distribute or sublicense the + SDK as a stand-alone product. + + 3. Unless you have an agreement with NVIDIA for this + purpose, you may not indicate that an application created + with the SDK is sponsored or endorsed by NVIDIA. + + 4. You may not bypass, disable, or circumvent any + encryption, security, digital rights management or + authentication mechanism in the SDK. + + 5. You may not use the SDK in any manner that would cause it + to become subject to an open source software license. As + examples, licenses that require as a condition of use, + modification, and/or distribution that the SDK be: + + a. Disclosed or distributed in source code form; + + b. Licensed for the purpose of making derivative works; + or + + c. Redistributable at no charge. + + 6. Unless you have an agreement with NVIDIA for this + purpose, you may not use the SDK with any system or + application where the use or failure of the system or + application can reasonably be expected to threaten or + result in personal injury, death, or catastrophic loss. + Examples include use in avionics, navigation, military, + medical, life support or other life critical applications. + NVIDIA does not design, test or manufacture the SDK for + these critical uses and NVIDIA shall not be liable to you + or any third party, in whole or in part, for any claims or + damages arising from such uses. + + 7. You agree to defend, indemnify and hold harmless NVIDIA + and its affiliates, and their respective employees, + contractors, agents, officers and directors, from and + against any and all claims, damages, obligations, losses, + liabilities, costs or debt, fines, restitutions and + expenses (including but not limited to attorney’s fees + and costs incident to establishing the right of + indemnification) arising out of or related to your use of + the SDK outside of the scope of this Agreement, or not in + compliance with its terms. + + +1.3. Ownership + + 1. NVIDIA or its licensors hold all rights, title and + interest in and to the SDK and its modifications and + derivative works, including their respective intellectual + property rights, subject to your rights described in this + section. This SDK may include software and materials from + NVIDIA’s licensors, and these licensors are intended + third party beneficiaries that may enforce this Agreement + with respect to their intellectual property rights. + + 2. You hold all rights, title and interest in and to your + applications and your derivative works of the sample + source code delivered in the SDK, including their + respective intellectual property rights, subject to + NVIDIA’s rights described in this section. + + 3. You may, but don’t have to, provide to NVIDIA + suggestions, feature requests or other feedback regarding + the SDK, including possible enhancements or modifications + to the SDK. For any feedback that you voluntarily provide, + you hereby grant NVIDIA and its affiliates a perpetual, + non-exclusive, worldwide, irrevocable license to use, + reproduce, modify, license, sublicense (through multiple + tiers of sublicensees), and distribute (through multiple + tiers of distributors) it without the payment of any + royalties or fees to you. NVIDIA will use feedback at its + choice. NVIDIA is constantly looking for ways to improve + its products, so you may send feedback to NVIDIA through + the developer portal at https://developer.nvidia.com. + + +1.4. No Warranties + +THE SDK IS PROVIDED BY NVIDIA “AS IS” AND “WITH ALL +FAULTS.” TO THE MAXIMUM EXTENT PERMITTED BY LAW, NVIDIA AND +ITS AFFILIATES EXPRESSLY DISCLAIM ALL WARRANTIES OF ANY KIND +OR NATURE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, +BUT NOT LIMITED TO, ANY WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT, OR THE +ABSENCE OF ANY DEFECTS THEREIN, WHETHER LATENT OR PATENT. NO +WARRANTY IS MADE ON THE BASIS OF TRADE USAGE, COURSE OF +DEALING OR COURSE OF TRADE. + + +1.5. Limitation of Liability + +TO THE MAXIMUM EXTENT PERMITTED BY LAW, NVIDIA AND ITS +AFFILIATES SHALL NOT BE LIABLE FOR ANY SPECIAL, INCIDENTAL, +PUNITIVE OR CONSEQUENTIAL DAMAGES, OR ANY LOST PROFITS, LOSS +OF USE, LOSS OF DATA OR LOSS OF GOODWILL, OR THE COSTS OF +PROCURING SUBSTITUTE PRODUCTS, ARISING OUT OF OR IN CONNECTION +WITH THIS AGREEMENT OR THE USE OR PERFORMANCE OF THE SDK, +WHETHER SUCH LIABILITY ARISES FROM ANY CLAIM BASED UPON BREACH +OF CONTRACT, BREACH OF WARRANTY, TORT (INCLUDING NEGLIGENCE), +PRODUCT LIABILITY OR ANY OTHER CAUSE OF ACTION OR THEORY OF +LIABILITY. IN NO EVENT WILL NVIDIA’S AND ITS AFFILIATES +TOTAL CUMULATIVE LIABILITY UNDER OR ARISING OUT OF THIS +AGREEMENT EXCEED US$10.00. THE NATURE OF THE LIABILITY OR THE +NUMBER OF CLAIMS OR SUITS SHALL NOT ENLARGE OR EXTEND THIS +LIMIT. + +These exclusions and limitations of liability shall apply +regardless if NVIDIA or its affiliates have been advised of +the possibility of such damages, and regardless of whether a +remedy fails its essential purpose. These exclusions and +limitations of liability form an essential basis of the +bargain between the parties, and, absent any of these +exclusions or limitations of liability, the provisions of this +Agreement, including, without limitation, the economic terms, +would be substantially different. + + +1.6. Termination + + 1. This Agreement will continue to apply until terminated by + either you or NVIDIA as described below. + + 2. If you want to terminate this Agreement, you may do so by + stopping to use the SDK. + + 3. NVIDIA may, at any time, terminate this Agreement if: + + a. (i) you fail to comply with any term of this + Agreement and the non-compliance is not fixed within + thirty (30) days following notice from NVIDIA (or + immediately if you violate NVIDIA’s intellectual + property rights); + + b. (ii) you commence or participate in any legal + proceeding against NVIDIA with respect to the SDK; or + + c. (iii) NVIDIA decides to no longer provide the SDK in + a country or, in NVIDIA’s sole discretion, the + continued use of it is no longer commercially viable. + + 4. Upon any termination of this Agreement, you agree to + promptly discontinue use of the SDK and destroy all copies + in your possession or control. Your prior distributions in + accordance with this Agreement are not affected by the + termination of this Agreement. Upon written request, you + will certify in writing that you have complied with your + commitments under this section. Upon any termination of + this Agreement all provisions survive except for the + license grant provisions. + + +1.7. General + +If you wish to assign this Agreement or your rights and +obligations, including by merger, consolidation, dissolution +or operation of law, contact NVIDIA to ask for permission. Any +attempted assignment not approved by NVIDIA in writing shall +be void and of no effect. NVIDIA may assign, delegate or +transfer this Agreement and its rights and obligations, and if +to a non-affiliate you will be notified. + +You agree to cooperate with NVIDIA and provide reasonably +requested information to verify your compliance with this +Agreement. + +This Agreement will be governed in all respects by the laws of +the United States and of the State of Delaware as those laws +are applied to contracts entered into and performed entirely +within Delaware by Delaware residents, without regard to the +conflicts of laws principles. The United Nations Convention on +Contracts for the International Sale of Goods is specifically +disclaimed. You agree to all terms of this Agreement in the +English language. + +The state or federal courts residing in Santa Clara County, +California shall have exclusive jurisdiction over any dispute +or claim arising out of this Agreement. Notwithstanding this, +you agree that NVIDIA shall still be allowed to apply for +injunctive remedies or an equivalent type of urgent legal +relief in any jurisdiction. + +If any court of competent jurisdiction determines that any +provision of this Agreement is illegal, invalid or +unenforceable, such provision will be construed as limited to +the extent necessary to be consistent with and fully +enforceable under the law and the remaining provisions will +remain in full force and effect. Unless otherwise specified, +remedies are cumulative. + +Each party acknowledges and agrees that the other is an +independent contractor in the performance of this Agreement. + +The SDK has been developed entirely at private expense and is +“commercial items” consisting of “commercial computer +software” and “commercial computer software +documentation” provided with RESTRICTED RIGHTS. Use, +duplication or disclosure by the U.S. Government or a U.S. +Government subcontractor is subject to the restrictions in +this Agreement pursuant to DFARS 227.7202-3(a) or as set forth +in subparagraphs (c)(1) and (2) of the Commercial Computer +Software - Restricted Rights clause at FAR 52.227-19, as +applicable. Contractor/manufacturer is NVIDIA, 2788 San Tomas +Expressway, Santa Clara, CA 95051. + +The SDK is subject to United States export laws and +regulations. You agree that you will not ship, transfer or +export the SDK into any country, or use the SDK in any manner, +prohibited by the United States Bureau of Industry and +Security or economic sanctions regulations administered by the +U.S. Department of Treasury’s Office of Foreign Assets +Control (OFAC), or any applicable export laws, restrictions or +regulations. These laws include restrictions on destinations, +end users and end use. By accepting this Agreement, you +confirm that you are not a resident or citizen of any country +currently embargoed by the U.S. and that you are not otherwise +prohibited from receiving the SDK. + +Any notice delivered by NVIDIA to you under this Agreement +will be delivered via mail, email or fax. You agree that any +notices that NVIDIA sends you electronically will satisfy any +legal communication requirements. Please direct your legal +notices or other correspondence to NVIDIA Corporation, 2788 +San Tomas Expressway, Santa Clara, California 95051, United +States of America, Attention: Legal Department. + +This Agreement and any exhibits incorporated into this +Agreement constitute the entire agreement of the parties with +respect to the subject matter of this Agreement and supersede +all prior negotiations or documentation exchanged between the +parties relating to this SDK license. Any additional and/or +conflicting terms on documents issued by you are null, void, +and invalid. Any amendment or waiver under this Agreement +shall be in writing and signed by representatives of both +parties. + + +2. CUDA Toolkit Supplement to Software License Agreement for +NVIDIA Software Development Kits +------------------------------------------------------------ + + +Release date: August 16, 2018 +----------------------------- + +The terms in this supplement govern your use of the NVIDIA +CUDA Toolkit SDK under the terms of your license agreement +(“Agreement”) as modified by this supplement. Capitalized +terms used but not defined below have the meaning assigned to +them in the Agreement. + +This supplement is an exhibit to the Agreement and is +incorporated as an integral part of the Agreement. In the +event of conflict between the terms in this supplement and the +terms in the Agreement, the terms in this supplement govern. + + +2.1. License Scope + +The SDK is licensed for you to develop applications only for +use in systems with NVIDIA GPUs. + + +2.2. Distribution + +The portions of the SDK that are distributable under the +Agreement are listed in Attachment A. + + +2.3. Operating Systems + +Those portions of the SDK designed exclusively for use on the +Linux or FreeBSD operating systems, or other operating systems +derived from the source code to these operating systems, may +be copied and redistributed for use in accordance with this +Agreement, provided that the object code files are not +modified in any way (except for unzipping of compressed +files). + + +2.4. Audio and Video Encoders and Decoders + +You acknowledge and agree that it is your sole responsibility +to obtain any additional third-party licenses required to +make, have made, use, have used, sell, import, and offer for +sale your products or services that include or incorporate any +third-party software and content relating to audio and/or +video encoders and decoders from, including but not limited +to, Microsoft, Thomson, Fraunhofer IIS, Sisvel S.p.A., +MPEG-LA, and Coding Technologies. NVIDIA does not grant to you +under this Agreement any necessary patent or other rights with +respect to any audio and/or video encoders and decoders. + + +2.5. Licensing + +If the distribution terms in this Agreement are not suitable +for your organization, or for any questions regarding this +Agreement, please contact NVIDIA at +nvidia-compute-license-questions@nvidia.com. + + +2.6. Attachment A + +The following portions of the SDK are distributable under the +Agreement: + +Component + +CUDA Runtime + +Windows + +cudart.dll, cudart_static.lib, cudadevrt.lib + +Mac OSX + +libcudart.dylib, libcudart_static.a, libcudadevrt.a + +Linux + +libcudart.so, libcudart_static.a, libcudadevrt.a + +Android + +libcudart.so, libcudart_static.a, libcudadevrt.a + +Component + +CUDA FFT Library + +Windows + +cufft.dll, cufftw.dll, cufft.lib, cufftw.lib + +Mac OSX + +libcufft.dylib, libcufft_static.a, libcufftw.dylib, +libcufftw_static.a + +Linux + +libcufft.so, libcufft_static.a, libcufftw.so, +libcufftw_static.a + +Android + +libcufft.so, libcufft_static.a, libcufftw.so, +libcufftw_static.a + +Component + +CUDA BLAS Library + +Windows + +cublas.dll, cublasLt.dll + +Mac OSX + +libcublas.dylib, libcublasLt.dylib, libcublas_static.a, +libcublasLt_static.a + +Linux + +libcublas.so, libcublasLt.so, libcublas_static.a, +libcublasLt_static.a + +Android + +libcublas.so, libcublasLt.so, libcublas_static.a, +libcublasLt_static.a + +Component + +NVIDIA "Drop-in" BLAS Library + +Windows + +nvblas.dll + +Mac OSX + +libnvblas.dylib + +Linux + +libnvblas.so + +Component + +CUDA Sparse Matrix Library + +Windows + +cusparse.dll, cusparse.lib + +Mac OSX + +libcusparse.dylib, libcusparse_static.a + +Linux + +libcusparse.so, libcusparse_static.a + +Android + +libcusparse.so, libcusparse_static.a + +Component + +CUDA Linear Solver Library + +Windows + +cusolver.dll, cusolver.lib + +Mac OSX + +libcusolver.dylib, libcusolver_static.a + +Linux + +libcusolver.so, libcusolver_static.a + +Android + +libcusolver.so, libcusolver_static.a + +Component + +CUDA Random Number Generation Library + +Windows + +curand.dll, curand.lib + +Mac OSX + +libcurand.dylib, libcurand_static.a + +Linux + +libcurand.so, libcurand_static.a + +Android + +libcurand.so, libcurand_static.a + +Component + +CUDA Accelerated Graph Library + +Component + +NVIDIA Performance Primitives Library + +Windows + +nppc.dll, nppc.lib, nppial.dll, nppial.lib, nppicc.dll, +nppicc.lib, nppicom.dll, nppicom.lib, nppidei.dll, +nppidei.lib, nppif.dll, nppif.lib, nppig.dll, nppig.lib, +nppim.dll, nppim.lib, nppist.dll, nppist.lib, nppisu.dll, +nppisu.lib, nppitc.dll, nppitc.lib, npps.dll, npps.lib + +Mac OSX + +libnppc.dylib, libnppc_static.a, libnppial.dylib, +libnppial_static.a, libnppicc.dylib, libnppicc_static.a, +libnppicom.dylib, libnppicom_static.a, libnppidei.dylib, +libnppidei_static.a, libnppif.dylib, libnppif_static.a, +libnppig.dylib, libnppig_static.a, libnppim.dylib, +libnppisu_static.a, libnppitc.dylib, libnppitc_static.a, +libnpps.dylib, libnpps_static.a + +Linux + +libnppc.so, libnppc_static.a, libnppial.so, +libnppial_static.a, libnppicc.so, libnppicc_static.a, +libnppicom.so, libnppicom_static.a, libnppidei.so, +libnppidei_static.a, libnppif.so, libnppif_static.a +libnppig.so, libnppig_static.a, libnppim.so, +libnppim_static.a, libnppist.so, libnppist_static.a, +libnppisu.so, libnppisu_static.a, libnppitc.so +libnppitc_static.a, libnpps.so, libnpps_static.a + +Android + +libnppc.so, libnppc_static.a, libnppial.so, +libnppial_static.a, libnppicc.so, libnppicc_static.a, +libnppicom.so, libnppicom_static.a, libnppidei.so, +libnppidei_static.a, libnppif.so, libnppif_static.a +libnppig.so, libnppig_static.a, libnppim.so, +libnppim_static.a, libnppist.so, libnppist_static.a, +libnppisu.so, libnppisu_static.a, libnppitc.so +libnppitc_static.a, libnpps.so, libnpps_static.a + +Component + +NVIDIA JPEG Library + +Linux + +libnvjpeg.so, libnvjpeg_static.a + +Component + +Internal common library required for statically linking to +cuBLAS, cuSPARSE, cuFFT, cuRAND, nvJPEG and NPP + +Mac OSX + +libculibos.a + +Linux + +libculibos.a + +Component + +NVIDIA Runtime Compilation Library and Header + +All + +nvrtc.h + +Windows + +nvrtc.dll, nvrtc-builtins.dll + +Mac OSX + +libnvrtc.dylib, libnvrtc-builtins.dylib + +Linux + +libnvrtc.so, libnvrtc-builtins.so + +Component + +NVIDIA Optimizing Compiler Library + +Windows + +nvvm.dll + +Mac OSX + +libnvvm.dylib + +Linux + +libnvvm.so + +Component + +NVIDIA Common Device Math Functions Library + +Windows + +libdevice.10.bc + +Mac OSX + +libdevice.10.bc + +Linux + +libdevice.10.bc + +Component + +CUDA Occupancy Calculation Header Library + +All + +cuda_occupancy.h + +Component + +CUDA Half Precision Headers + +All + +cuda_fp16.h, cuda_fp16.hpp + +Component + +CUDA Profiling Tools Interface (CUPTI) Library + +Windows + +cupti.dll + +Mac OSX + +libcupti.dylib + +Linux + +libcupti.so + +Component + +NVIDIA Tools Extension Library + +Windows + +nvToolsExt.dll, nvToolsExt.lib + +Mac OSX + +libnvToolsExt.dylib + +Linux + +libnvToolsExt.so + +Component + +NVIDIA CUDA Driver Libraries + +Linux + +libcuda.so, libnvidia-fatbinaryloader.so, +libnvidia-ptxjitcompiler.so + +The NVIDIA CUDA Driver Libraries are only distributable in +applications that meet this criteria: + + 1. The application was developed starting from a NVIDIA CUDA + container obtained from Docker Hub or the NVIDIA GPU + Cloud, and + + 2. The resulting application is packaged as a Docker + container and distributed to users on Docker Hub or the + NVIDIA GPU Cloud only. + + +2.7. Attachment B + + +Additional Licensing Obligations + +The following third party components included in the SOFTWARE +are licensed to Licensee pursuant to the following terms and +conditions: + + 1. Licensee's use of the GDB third party component is + subject to the terms and conditions of GNU GPL v3: + + This product includes copyrighted third-party software licensed + under the terms of the GNU General Public License v3 ("GPL v3"). + All third-party software packages are copyright by their respective + authors. GPL v3 terms and conditions are hereby incorporated into + the Agreement by this reference: http://www.gnu.org/licenses/gpl.txt + + Consistent with these licensing requirements, the software + listed below is provided under the terms of the specified + open source software licenses. To obtain source code for + software provided under licenses that require + redistribution of source code, including the GNU General + Public License (GPL) and GNU Lesser General Public License + (LGPL), contact oss-requests@nvidia.com. This offer is + valid for a period of three (3) years from the date of the + distribution of this product by NVIDIA CORPORATION. + + Component License + CUDA-GDB GPL v3 + + 2. Licensee represents and warrants that any and all third + party licensing and/or royalty payment obligations in + connection with Licensee's use of the H.264 video codecs + are solely the responsibility of Licensee. + + 3. Licensee's use of the Thrust library is subject to the + terms and conditions of the Apache License Version 2.0. + All third-party software packages are copyright by their + respective authors. Apache License Version 2.0 terms and + conditions are hereby incorporated into the Agreement by + this reference. + http://www.apache.org/licenses/LICENSE-2.0.html + + In addition, Licensee acknowledges the following notice: + Thrust includes source code from the Boost Iterator, + Tuple, System, and Random Number libraries. + + Boost Software License - Version 1.0 - August 17th, 2003 + . . . . + + Permission is hereby granted, free of charge, to any person or + organization obtaining a copy of the software and accompanying + documentation covered by this license (the "Software") to use, + reproduce, display, distribute, execute, and transmit the Software, + and to prepare derivative works of the Software, and to permit + third-parties to whom the Software is furnished to do so, all + subject to the following: + + The copyright notices in the Software and this entire statement, + including the above license grant, this restriction and the following + disclaimer, must be included in all copies of the Software, in whole + or in part, and all derivative works of the Software, unless such + copies or derivative works are solely in the form of machine-executable + object code generated by a source language processor. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND + NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR + OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + 4. Licensee's use of the LLVM third party component is + subject to the following terms and conditions: + + ====================================================== + LLVM Release License + ====================================================== + University of Illinois/NCSA + Open Source License + + Copyright (c) 2003-2010 University of Illinois at Urbana-Champaign. + All rights reserved. + + Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to + deal with the Software without restriction, including without limitation the + rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + sell copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at Urbana- + Champaign, nor the names of its contributors may be used to endorse or + promote products derived from this Software without specific prior + written permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. + + 5. Licensee's use (e.g. nvprof) of the PCRE third party + component is subject to the following terms and + conditions: + + ------------ + PCRE LICENCE + ------------ + PCRE is a library of functions to support regular expressions whose syntax + and semantics are as close as possible to those of the Perl 5 language. + Release 8 of PCRE is distributed under the terms of the "BSD" licence, as + specified below. The documentation for PCRE, supplied in the "doc" + directory, is distributed under the same terms as the software itself. The + basic library functions are written in C and are freestanding. Also + included in the distribution is a set of C++ wrapper functions, and a just- + in-time compiler that can be used to optimize pattern matching. These are + both optional features that can be omitted when the library is built. + + THE BASIC LIBRARY FUNCTIONS + --------------------------- + Written by: Philip Hazel + Email local part: ph10 + Email domain: cam.ac.uk + University of Cambridge Computing Service, + Cambridge, England. + Copyright (c) 1997-2012 University of Cambridge + All rights reserved. + + PCRE JUST-IN-TIME COMPILATION SUPPORT + ------------------------------------- + Written by: Zoltan Herczeg + Email local part: hzmester + Emain domain: freemail.hu + Copyright(c) 2010-2012 Zoltan Herczeg + All rights reserved. + + STACK-LESS JUST-IN-TIME COMPILER + -------------------------------- + Written by: Zoltan Herczeg + Email local part: hzmester + Emain domain: freemail.hu + Copyright(c) 2009-2012 Zoltan Herczeg + All rights reserved. + + THE C++ WRAPPER FUNCTIONS + ------------------------- + Contributed by: Google Inc. + Copyright (c) 2007-2012, Google Inc. + All rights reserved. + + THE "BSD" LICENCE + ----------------- + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the name of Google + Inc. nor the names of their 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. + + 6. Some of the cuBLAS library routines were written by or + derived from code written by Vasily Volkov and are subject + to the Modified Berkeley Software Distribution License as + follows: + + Copyright (c) 2007-2009, Regents of the University of California + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the University of California, Berkeley 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 AUTHOR "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 AUTHOR 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. + + 7. Some of the cuBLAS library routines were written by or + derived from code written by Davide Barbieri and are + subject to the Modified Berkeley Software Distribution + License as follows: + + Copyright (c) 2008-2009 Davide Barbieri @ University of Rome Tor Vergata. + + 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. + * The name of the author may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 AUTHOR 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. + + 8. Some of the cuBLAS library routines were derived from + code developed by the University of Tennessee and are + subject to the Modified Berkeley Software Distribution + License as follows: + + Copyright (c) 2010 The University of Tennessee. + + 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 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. + + 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. + + 9. Some of the cuBLAS library routines were written by or + derived from code written by Jonathan Hogg and are subject + to the Modified Berkeley Software Distribution License as + follows: + + Copyright (c) 2012, The Science and Technology Facilities Council (STFC). + + 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 STFC 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 STFC 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. + + 10. Some of the cuBLAS library routines were written by or + derived from code written by Ahmad M. Abdelfattah, David + Keyes, and Hatem Ltaief, and are subject to the Apache + License, Version 2.0, as follows: + + -- (C) Copyright 2013 King Abdullah University of Science and Technology + Authors: + Ahmad Abdelfattah (ahmad.ahmad@kaust.edu.sa) + David Keyes (david.keyes@kaust.edu.sa) + Hatem Ltaief (hatem.ltaief@kaust.edu.sa) + + 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 King Abdullah University of Science and + Technology 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 + HOLDERS 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 + + 11. Some of the cuSPARSE library routines were written by or + derived from code written by Li-Wen Chang and are subject + to the NCSA Open Source License as follows: + + Copyright (c) 2012, University of Illinois. + + All rights reserved. + + Developed by: IMPACT Group, University of Illinois, http://impact.crhc.illinois.edu + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal with the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimers in the documentation and/or other materials provided + with the distribution. + * Neither the names of IMPACT Group, University of Illinois, nor + the names of its contributors may be used to endorse or promote + products derived from this Software without specific prior + written permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR + IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE + SOFTWARE. + + 12. Some of the cuRAND library routines were written by or + derived from code written by Mutsuo Saito and Makoto + Matsumoto and are subject to the following license: + + Copyright (c) 2009, 2010 Mutsuo Saito, Makoto Matsumoto and Hiroshima + University. All rights reserved. + + Copyright (c) 2011 Mutsuo Saito, Makoto Matsumoto, Hiroshima + University and University of Tokyo. 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 Hiroshima University 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. + + 13. Some of the cuRAND library routines were derived from + code developed by D. E. Shaw Research and are subject to + the following license: + + Copyright 2010-2011, D. E. Shaw Research. + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions, and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions, and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of D. E. Shaw Research nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + 14. Some of the Math library routines were written by or + derived from code developed by Norbert Juffa and are + subject to the following license: + + Copyright (c) 2015-2017, Norbert Juffa + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + 15. Licensee's use of the lz4 third party component is + subject to the following terms and conditions: + + Copyright (C) 2011-2013, Yann Collet. + BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + + 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. + + 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. + + 16. The NPP library uses code from the Boost Math Toolkit, + and is subject to the following license: + + Boost Software License - Version 1.0 - August 17th, 2003 + . . . . + + Permission is hereby granted, free of charge, to any person or + organization obtaining a copy of the software and accompanying + documentation covered by this license (the "Software") to use, + reproduce, display, distribute, execute, and transmit the Software, + and to prepare derivative works of the Software, and to permit + third-parties to whom the Software is furnished to do so, all + subject to the following: + + The copyright notices in the Software and this entire statement, + including the above license grant, this restriction and the following + disclaimer, must be included in all copies of the Software, in whole + or in part, and all derivative works of the Software, unless such + copies or derivative works are solely in the form of machine-executable + object code generated by a source language processor. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND + NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR + OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + 17. Portions of the Nsight Eclipse Edition is subject to the + following license: + + The Eclipse Foundation makes available all content in this plug-in + ("Content"). Unless otherwise indicated below, the Content is provided + to you under the terms and conditions of the Eclipse Public License + Version 1.0 ("EPL"). A copy of the EPL is available at http:// + www.eclipse.org/legal/epl-v10.html. For purposes of the EPL, "Program" + will mean the Content. + + If you did not receive this Content directly from the Eclipse + Foundation, the Content is being redistributed by another party + ("Redistributor") and different terms and conditions may apply to your + use of any object code in the Content. Check the Redistributor's + license that was provided with the Content. If no such license exists, + contact the Redistributor. Unless otherwise indicated below, the terms + and conditions of the EPL still apply to any source code in the + Content and such source code may be obtained at http://www.eclipse.org. + + 18. Some of the cuBLAS library routines uses code from + OpenAI, which is subject to the following license: + + License URL + https://github.com/openai/openai-gemm/blob/master/LICENSE + + License Text + The MIT License + + Copyright (c) 2016 OpenAI (http://openai.com), 2016 Google Inc. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + + 19. Licensee's use of the Visual Studio Setup Configuration + Samples is subject to the following license: + + The MIT License (MIT) + Copyright (C) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + 20. Licensee's use of linmath.h header for CPU functions for + GL vector/matrix operations from lunarG is subject to the + Apache License Version 2.0. + + 21. The DX12-CUDA sample uses the d3dx12.h header, which is + subject to the MIT license . + +----------------- diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_cupti_cu12-12.8.90.dist-info/METADATA b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_cupti_cu12-12.8.90.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..c36cf7041f12162438176dfa15e5ff5deb561f11 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_cupti_cu12-12.8.90.dist-info/METADATA @@ -0,0 +1,44 @@ +Metadata-Version: 2.2 +Name: nvidia-cuda-cupti-cu12 +Version: 12.8.90 +Summary: CUDA profiling tools runtime libs. +Home-page: https://developer.nvidia.com/cuda-zone +Author: Nvidia CUDA Installer Team +Author-email: compute_installer@nvidia.com +License: NVIDIA Proprietary Software +Keywords: cuda,nvidia,runtime,machine learning,deep learning +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: Other/Proprietary License +Classifier: Natural Language :: English +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX :: Linux +Requires-Python: >=3 +License-File: License.txt +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: requires-python +Dynamic: summary + +Provides libraries to enable third party tools using GPU profiling APIs. diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_cupti_cu12-12.8.90.dist-info/RECORD b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_cupti_cu12-12.8.90.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..d86780a1993f445b318dc8a469971a7708055a86 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_cupti_cu12-12.8.90.dist-info/RECORD @@ -0,0 +1,53 @@ +nvidia/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cuda_cupti/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cuda_cupti/include/Openacc/cupti_openacc.h,sha256=Z0OM5e_hbd3cxdXyn3SCHqBBQawLg4QORnlm57Cr2-M,3513 +nvidia/cuda_cupti/include/Openmp/cupti_openmp.h,sha256=E1WNmeb_7HaUSmBegtUNe4IV1i7pXeNxgzIlyKn1zrM,3491 +nvidia/cuda_cupti/include/Openmp/omp-tools.h,sha256=AmuC_xPC7VPu3B-W4PmXuCNufFawhY8PjNXePaQFAOg,37403 +nvidia/cuda_cupti/include/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cuda_cupti/include/cuda_stdint.h,sha256=XbFOk9CtJjKqk7PpYNqbSVsDxAsVM8avA4rWpPi0BjQ,4093 +nvidia/cuda_cupti/include/cupti.h,sha256=JkVyAGTIMYzwm62dfVqas3nMcILhgP_Wdz6fh4_NED0,4697 +nvidia/cuda_cupti/include/cupti_activity.h,sha256=gJKGlG2JifW36Lx-ujJcKBlnUrNOoTxar51k28GrUtU,229848 +nvidia/cuda_cupti/include/cupti_activity_deprecated.h,sha256=B0p4zbll2vUn1j0ImTG6QIbpp6Hiw8y-X021Zmf7flE,137602 +nvidia/cuda_cupti/include/cupti_callbacks.h,sha256=aZ-SE0YMFfT9R-Uh5MHboPg0ypHMjeSSAJw3zdP7OCs,29689 +nvidia/cuda_cupti/include/cupti_checkpoint.h,sha256=rTz8JoWxqESBXyZWUhZJGm4xeYcx4OJOtJ7Ld13T_b0,5264 +nvidia/cuda_cupti/include/cupti_common.h,sha256=85m74bxUgXp3tEaPQpezeazmpsNMw41PsjNSYmQdT20,3514 +nvidia/cuda_cupti/include/cupti_driver_cbid.h,sha256=mkBNPYkLfcExhQZFDo0iYHlaHJWGD2vOMdtzaV-lEUk,77280 +nvidia/cuda_cupti/include/cupti_events.h,sha256=81wcvFvvHj8RmECbbEp5FfgjJIQDoC_81FhvqznFupY,51923 +nvidia/cuda_cupti/include/cupti_metrics.h,sha256=zmfZxq5VkUJp6Tj7oXEkP9oycRNw1zB9VNhoQlbhiN4,32175 +nvidia/cuda_cupti/include/cupti_nvtx_cbid.h,sha256=_azPtR1g4qivvX7qbvHRUg0RHCWF7iEOJyHMN9qZe9E,5912 +nvidia/cuda_cupti/include/cupti_pcsampling.h,sha256=ycJHT36DmPIaVzHsB3xxjXkhFyEfMCJOl3LbCsHFgyA,32144 +nvidia/cuda_cupti/include/cupti_pcsampling_util.h,sha256=lx8CaNXowJe5Zvc06LE-u_Zry_jODs1mM6j9Q5WIX9E,12430 +nvidia/cuda_cupti/include/cupti_pmsampling.h,sha256=U95hKOwIkZSbGNVP11QSmMawB8qdJsljY_tUJY4vedc,20440 +nvidia/cuda_cupti/include/cupti_profiler_host.h,sha256=MkkfXlKBRrRL4NfaPFiuE4D4z_gpmxiBWWTBixyyMTk,22155 +nvidia/cuda_cupti/include/cupti_profiler_target.h,sha256=MdLutIefwdMTI7wsce0LO3NuCm3FRgFR3GxAkqadMs4,32294 +nvidia/cuda_cupti/include/cupti_range_profiler.h,sha256=ue5bUA-3xCwAtQGyDe5O1d5rAmRbVbcrXKfITd4xM1I,18779 +nvidia/cuda_cupti/include/cupti_result.h,sha256=xQqBsZRoicBSWdk1lZAE_WeZj88MLH6ClTo58oshx-8,13114 +nvidia/cuda_cupti/include/cupti_runtime_cbid.h,sha256=BZJnzsvf2RjRlHKEhPjCk0CdjLI9_L-nClTwe4v9NUc,48372 +nvidia/cuda_cupti/include/cupti_sass_metrics.h,sha256=3RW9snJuFQdOhrEn3wDJOru05q0V_zssWrqD7tvVJKw,19674 +nvidia/cuda_cupti/include/cupti_target.h,sha256=x4Vz1Upb6m9ixmVpmGaKQldDWYQI3OZ-ocEXGzNK0EE,1263 +nvidia/cuda_cupti/include/cupti_version.h,sha256=KFXmjB4o-iZGvO8la9Sf9Urg4q4srmEimnxbPCyd2N8,4506 +nvidia/cuda_cupti/include/generated_cudaGL_meta.h,sha256=dfd2QuaRdEjbStOKvaQLi1Md_qrpRQh8PfyZznJ8bWY,3115 +nvidia/cuda_cupti/include/generated_cudaVDPAU_meta.h,sha256=fAedsoQxaU3hIAApAWDOKsa9kgcuQw4tdyf8klLm-3k,1453 +nvidia/cuda_cupti/include/generated_cuda_gl_interop_meta.h,sha256=LXOqvQCej0sCgAT1LUKKYZ466EFxN4hIwf9oIhXOLF0,2250 +nvidia/cuda_cupti/include/generated_cuda_meta.h,sha256=DDdgfW84GVtsGbr7daNJchmmZDS_xfvDHvFCm3I1OEc,98664 +nvidia/cuda_cupti/include/generated_cuda_runtime_api_meta.h,sha256=CuziaDwO2Mh33paCLGKqi73PQfYNmzp38wYrhAK-fng,72208 +nvidia/cuda_cupti/include/generated_cuda_vdpau_interop_meta.h,sha256=8OLqWN26aEYpTWUXtbHJvA5GYhVv3ybYVOTW7yK37z8,1367 +nvidia/cuda_cupti/include/generated_cudart_removed_meta.h,sha256=X3I5WXmhtsJNNlgY7coJ5vg4t11G5FRR6Xo7MboIeck,5172 +nvidia/cuda_cupti/include/generated_nvtx_meta.h,sha256=YHb_RD8g3s4m8PJn7Z0wnxvUHarl7BOAX5ADr-BL3HI,7513 +nvidia/cuda_cupti/include/nvperf_common.h,sha256=ykeTJ5I6c0z8KqMQh13hlJaMaHiqqVUB60oGXOCu7Bg,17255 +nvidia/cuda_cupti/include/nvperf_cuda_host.h,sha256=gC0JWoUdTyAOJs8y4uoJIhie9Xq4yF4HzoumLsYNVzU,7562 +nvidia/cuda_cupti/include/nvperf_host.h,sha256=wCB4mR8aIHWiqT1TsxztQgWBRh_yiq5ABFm8sb3_jwg,49197 +nvidia/cuda_cupti/include/nvperf_target.h,sha256=jRqQtuNLTrCzPDdyeANkTrPEijSCTjLy2A1qjKu0SdM,23607 +nvidia/cuda_cupti/lib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cuda_cupti/lib/libcheckpoint.so,sha256=BrqCvQkje5NM8W2iFy7VlDxYLKo1x5tSz8_rD_cfclA,1644872 +nvidia/cuda_cupti/lib/libcupti.so.12,sha256=_M3F_MfDL4z0s-2bF_fxh6GFpvoKW8wG40NMvRaHyAg,7595792 +nvidia/cuda_cupti/lib/libnvperf_host.so,sha256=YJ9UBjwlPa_277p5_kklL90jJDCKsP-5kcwSXT6aHqs,25825936 +nvidia/cuda_cupti/lib/libnvperf_target.so,sha256=LxDhEJ_DQaV0NMKOQAa0WokkeAHiD1rOE1wwLBc-B3A,5275312 +nvidia/cuda_cupti/lib/libpcsamplingutil.so,sha256=5vongwd5dPsnZb-py66_mAc233Tuv5lMWcdZaYiuyDs,970064 +nvidia_cuda_cupti_cu12-12.8.90.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +nvidia_cuda_cupti_cu12-12.8.90.dist-info/License.txt,sha256=rW9YU_ugyg0VnQ9Y1JrkmDDC-Mk_epJki5zpCttMbM0,59262 +nvidia_cuda_cupti_cu12-12.8.90.dist-info/METADATA,sha256=bff6L836BG65UvP4wXL1JLLhmmVOwDfaPbsy6T2WcdE,1730 +nvidia_cuda_cupti_cu12-12.8.90.dist-info/RECORD,, +nvidia_cuda_cupti_cu12-12.8.90.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia_cuda_cupti_cu12-12.8.90.dist-info/WHEEL,sha256=ygM8qpYgOvrn5C-8vbfzPi-0iFPECh71lLWqkqrTjYw,144 +nvidia_cuda_cupti_cu12-12.8.90.dist-info/top_level.txt,sha256=fTkAtiFuL16nUrB9ytDDtpytz2t0B4NvYTnRzwAhO14,7 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_cupti_cu12-12.8.90.dist-info/REQUESTED b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_cupti_cu12-12.8.90.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_cupti_cu12-12.8.90.dist-info/WHEEL b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_cupti_cu12-12.8.90.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..287a9d7e1a3d4435e9542cc8216b8c5eaf2c0ed2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_cupti_cu12-12.8.90.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.8.0) +Root-Is-Purelib: true +Tag: py3-none-manylinux2014_x86_64 +Tag: py3-none-manylinux_2_17_x86_64 + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_cupti_cu12-12.8.90.dist-info/top_level.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_cupti_cu12-12.8.90.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..862f7abf232cdfbb928609856247292e81c9decb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_cupti_cu12-12.8.90.dist-info/top_level.txt @@ -0,0 +1 @@ +nvidia diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_runtime_cu12-12.8.90.dist-info/INSTALLER b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_runtime_cu12-12.8.90.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_runtime_cu12-12.8.90.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_runtime_cu12-12.8.90.dist-info/License.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_runtime_cu12-12.8.90.dist-info/License.txt new file mode 100644 index 0000000000000000000000000000000000000000..b491c70e0aef319022ded661e111ddbd45b8a17f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_runtime_cu12-12.8.90.dist-info/License.txt @@ -0,0 +1,1568 @@ +End User License Agreement +-------------------------- + + +Preface +------- + +The Software License Agreement in Chapter 1 and the Supplement +in Chapter 2 contain license terms and conditions that govern +the use of NVIDIA software. By accepting this agreement, you +agree to comply with all the terms and conditions applicable +to the product(s) included herein. + + +NVIDIA Driver + + +Description + +This package contains the operating system driver and +fundamental system software components for NVIDIA GPUs. + + +NVIDIA CUDA Toolkit + + +Description + +The NVIDIA CUDA Toolkit provides command-line and graphical +tools for building, debugging and optimizing the performance +of applications accelerated by NVIDIA GPUs, runtime and math +libraries, and documentation including programming guides, +user manuals, and API references. + + +Default Install Location of CUDA Toolkit + +Windows platform: + +%ProgramFiles%\NVIDIA GPU Computing Toolkit\CUDA\v#.# + +Linux platform: + +/usr/local/cuda-#.# + +Mac platform: + +/Developer/NVIDIA/CUDA-#.# + + +NVIDIA CUDA Samples + + +Description + +This package includes over 100+ CUDA examples that demonstrate +various CUDA programming principles, and efficient CUDA +implementation of algorithms in specific application domains. + + +Default Install Location of CUDA Samples + +Windows platform: + +%ProgramData%\NVIDIA Corporation\CUDA Samples\v#.# + +Linux platform: + +/usr/local/cuda-#.#/samples + +and + +$HOME/NVIDIA_CUDA-#.#_Samples + +Mac platform: + +/Developer/NVIDIA/CUDA-#.#/samples + + +NVIDIA Nsight Visual Studio Edition (Windows only) + + +Description + +NVIDIA Nsight Development Platform, Visual Studio Edition is a +development environment integrated into Microsoft Visual +Studio that provides tools for debugging, profiling, analyzing +and optimizing your GPU computing and graphics applications. + + +Default Install Location of Nsight Visual Studio Edition + +Windows platform: + +%ProgramFiles(x86)%\NVIDIA Corporation\Nsight Visual Studio Edition #.# + + +1. License Agreement for NVIDIA Software Development Kits +--------------------------------------------------------- + + +Release Date: July 26, 2018 +--------------------------- + + +Important NoticeRead before downloading, installing, +copying or using the licensed software: +------------------------------------------------------- + +This license agreement, including exhibits attached +("Agreement”) is a legal agreement between you and NVIDIA +Corporation ("NVIDIA") and governs your use of a NVIDIA +software development kit (“SDK”). + +Each SDK has its own set of software and materials, but here +is a description of the types of items that may be included in +a SDK: source code, header files, APIs, data sets and assets +(examples include images, textures, models, scenes, videos, +native API input/output files), binary software, sample code, +libraries, utility programs, programming code and +documentation. + +This Agreement can be accepted only by an adult of legal age +of majority in the country in which the SDK is used. + +If you are entering into this Agreement on behalf of a company +or other legal entity, you represent that you have the legal +authority to bind the entity to this Agreement, in which case +“you” will mean the entity you represent. + +If you don’t have the required age or authority to accept +this Agreement, or if you don’t accept all the terms and +conditions of this Agreement, do not download, install or use +the SDK. + +You agree to use the SDK only for purposes that are permitted +by (a) this Agreement, and (b) any applicable law, regulation +or generally accepted practices or guidelines in the relevant +jurisdictions. + + +1.1. License + + +1.1.1. License Grant + +Subject to the terms of this Agreement, NVIDIA hereby grants +you a non-exclusive, non-transferable license, without the +right to sublicense (except as expressly provided in this +Agreement) to: + + 1. Install and use the SDK, + + 2. Modify and create derivative works of sample source code + delivered in the SDK, and + + 3. Distribute those portions of the SDK that are identified + in this Agreement as distributable, as incorporated in + object code format into a software application that meets + the distribution requirements indicated in this Agreement. + + +1.1.2. Distribution Requirements + +These are the distribution requirements for you to exercise +the distribution grant: + + 1. Your application must have material additional + functionality, beyond the included portions of the SDK. + + 2. The distributable portions of the SDK shall only be + accessed by your application. + + 3. The following notice shall be included in modifications + and derivative works of sample source code distributed: + “This software contains source code provided by NVIDIA + Corporation.” + + 4. Unless a developer tool is identified in this Agreement + as distributable, it is delivered for your internal use + only. + + 5. The terms under which you distribute your application + must be consistent with the terms of this Agreement, + including (without limitation) terms relating to the + license grant and license restrictions and protection of + NVIDIA’s intellectual property rights. Additionally, you + agree that you will protect the privacy, security and + legal rights of your application users. + + 6. You agree to notify NVIDIA in writing of any known or + suspected distribution or use of the SDK not in compliance + with the requirements of this Agreement, and to enforce + the terms of your agreements with respect to distributed + SDK. + + +1.1.3. Authorized Users + +You may allow employees and contractors of your entity or of +your subsidiary(ies) to access and use the SDK from your +secure network to perform work on your behalf. + +If you are an academic institution you may allow users +enrolled or employed by the academic institution to access and +use the SDK from your secure network. + +You are responsible for the compliance with the terms of this +Agreement by your authorized users. If you become aware that +your authorized users didn’t follow the terms of this +Agreement, you agree to take reasonable steps to resolve the +non-compliance and prevent new occurrences. + + +1.1.4. Pre-Release SDK + +The SDK versions identified as alpha, beta, preview or +otherwise as pre-release, may not be fully functional, may +contain errors or design flaws, and may have reduced or +different security, privacy, accessibility, availability, and +reliability standards relative to commercial versions of +NVIDIA software and materials. Use of a pre-release SDK may +result in unexpected results, loss of data, project delays or +other unpredictable damage or loss. + +You may use a pre-release SDK at your own risk, understanding +that pre-release SDKs are not intended for use in production +or business-critical systems. + +NVIDIA may choose not to make available a commercial version +of any pre-release SDK. NVIDIA may also choose to abandon +development and terminate the availability of a pre-release +SDK at any time without liability. + + +1.1.5. Updates + +NVIDIA may, at its option, make available patches, workarounds +or other updates to this SDK. Unless the updates are provided +with their separate governing terms, they are deemed part of +the SDK licensed to you as provided in this Agreement. You +agree that the form and content of the SDK that NVIDIA +provides may change without prior notice to you. While NVIDIA +generally maintains compatibility between versions, NVIDIA may +in some cases make changes that introduce incompatibilities in +future versions of the SDK. + + +1.1.6. Third Party Licenses + +The SDK may come bundled with, or otherwise include or be +distributed with, third party software licensed by a NVIDIA +supplier and/or open source software provided under an open +source license. Use of third party software is subject to the +third-party license terms, or in the absence of third party +terms, the terms of this Agreement. Copyright to third party +software is held by the copyright holders indicated in the +third-party software or license. + + +1.1.7. Reservation of Rights + +NVIDIA reserves all rights, title, and interest in and to the +SDK, not expressly granted to you under this Agreement. + + +1.2. Limitations + +The following license limitations apply to your use of the +SDK: + + 1. You may not reverse engineer, decompile or disassemble, + or remove copyright or other proprietary notices from any + portion of the SDK or copies of the SDK. + + 2. Except as expressly provided in this Agreement, you may + not copy, sell, rent, sublicense, transfer, distribute, + modify, or create derivative works of any portion of the + SDK. For clarity, you may not distribute or sublicense the + SDK as a stand-alone product. + + 3. Unless you have an agreement with NVIDIA for this + purpose, you may not indicate that an application created + with the SDK is sponsored or endorsed by NVIDIA. + + 4. You may not bypass, disable, or circumvent any + encryption, security, digital rights management or + authentication mechanism in the SDK. + + 5. You may not use the SDK in any manner that would cause it + to become subject to an open source software license. As + examples, licenses that require as a condition of use, + modification, and/or distribution that the SDK be: + + a. Disclosed or distributed in source code form; + + b. Licensed for the purpose of making derivative works; + or + + c. Redistributable at no charge. + + 6. Unless you have an agreement with NVIDIA for this + purpose, you may not use the SDK with any system or + application where the use or failure of the system or + application can reasonably be expected to threaten or + result in personal injury, death, or catastrophic loss. + Examples include use in avionics, navigation, military, + medical, life support or other life critical applications. + NVIDIA does not design, test or manufacture the SDK for + these critical uses and NVIDIA shall not be liable to you + or any third party, in whole or in part, for any claims or + damages arising from such uses. + + 7. You agree to defend, indemnify and hold harmless NVIDIA + and its affiliates, and their respective employees, + contractors, agents, officers and directors, from and + against any and all claims, damages, obligations, losses, + liabilities, costs or debt, fines, restitutions and + expenses (including but not limited to attorney’s fees + and costs incident to establishing the right of + indemnification) arising out of or related to your use of + the SDK outside of the scope of this Agreement, or not in + compliance with its terms. + + +1.3. Ownership + + 1. NVIDIA or its licensors hold all rights, title and + interest in and to the SDK and its modifications and + derivative works, including their respective intellectual + property rights, subject to your rights described in this + section. This SDK may include software and materials from + NVIDIA’s licensors, and these licensors are intended + third party beneficiaries that may enforce this Agreement + with respect to their intellectual property rights. + + 2. You hold all rights, title and interest in and to your + applications and your derivative works of the sample + source code delivered in the SDK, including their + respective intellectual property rights, subject to + NVIDIA’s rights described in this section. + + 3. You may, but don’t have to, provide to NVIDIA + suggestions, feature requests or other feedback regarding + the SDK, including possible enhancements or modifications + to the SDK. For any feedback that you voluntarily provide, + you hereby grant NVIDIA and its affiliates a perpetual, + non-exclusive, worldwide, irrevocable license to use, + reproduce, modify, license, sublicense (through multiple + tiers of sublicensees), and distribute (through multiple + tiers of distributors) it without the payment of any + royalties or fees to you. NVIDIA will use feedback at its + choice. NVIDIA is constantly looking for ways to improve + its products, so you may send feedback to NVIDIA through + the developer portal at https://developer.nvidia.com. + + +1.4. No Warranties + +THE SDK IS PROVIDED BY NVIDIA “AS IS” AND “WITH ALL +FAULTS.” TO THE MAXIMUM EXTENT PERMITTED BY LAW, NVIDIA AND +ITS AFFILIATES EXPRESSLY DISCLAIM ALL WARRANTIES OF ANY KIND +OR NATURE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, +BUT NOT LIMITED TO, ANY WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT, OR THE +ABSENCE OF ANY DEFECTS THEREIN, WHETHER LATENT OR PATENT. NO +WARRANTY IS MADE ON THE BASIS OF TRADE USAGE, COURSE OF +DEALING OR COURSE OF TRADE. + + +1.5. Limitation of Liability + +TO THE MAXIMUM EXTENT PERMITTED BY LAW, NVIDIA AND ITS +AFFILIATES SHALL NOT BE LIABLE FOR ANY SPECIAL, INCIDENTAL, +PUNITIVE OR CONSEQUENTIAL DAMAGES, OR ANY LOST PROFITS, LOSS +OF USE, LOSS OF DATA OR LOSS OF GOODWILL, OR THE COSTS OF +PROCURING SUBSTITUTE PRODUCTS, ARISING OUT OF OR IN CONNECTION +WITH THIS AGREEMENT OR THE USE OR PERFORMANCE OF THE SDK, +WHETHER SUCH LIABILITY ARISES FROM ANY CLAIM BASED UPON BREACH +OF CONTRACT, BREACH OF WARRANTY, TORT (INCLUDING NEGLIGENCE), +PRODUCT LIABILITY OR ANY OTHER CAUSE OF ACTION OR THEORY OF +LIABILITY. IN NO EVENT WILL NVIDIA’S AND ITS AFFILIATES +TOTAL CUMULATIVE LIABILITY UNDER OR ARISING OUT OF THIS +AGREEMENT EXCEED US$10.00. THE NATURE OF THE LIABILITY OR THE +NUMBER OF CLAIMS OR SUITS SHALL NOT ENLARGE OR EXTEND THIS +LIMIT. + +These exclusions and limitations of liability shall apply +regardless if NVIDIA or its affiliates have been advised of +the possibility of such damages, and regardless of whether a +remedy fails its essential purpose. These exclusions and +limitations of liability form an essential basis of the +bargain between the parties, and, absent any of these +exclusions or limitations of liability, the provisions of this +Agreement, including, without limitation, the economic terms, +would be substantially different. + + +1.6. Termination + + 1. This Agreement will continue to apply until terminated by + either you or NVIDIA as described below. + + 2. If you want to terminate this Agreement, you may do so by + stopping to use the SDK. + + 3. NVIDIA may, at any time, terminate this Agreement if: + + a. (i) you fail to comply with any term of this + Agreement and the non-compliance is not fixed within + thirty (30) days following notice from NVIDIA (or + immediately if you violate NVIDIA’s intellectual + property rights); + + b. (ii) you commence or participate in any legal + proceeding against NVIDIA with respect to the SDK; or + + c. (iii) NVIDIA decides to no longer provide the SDK in + a country or, in NVIDIA’s sole discretion, the + continued use of it is no longer commercially viable. + + 4. Upon any termination of this Agreement, you agree to + promptly discontinue use of the SDK and destroy all copies + in your possession or control. Your prior distributions in + accordance with this Agreement are not affected by the + termination of this Agreement. Upon written request, you + will certify in writing that you have complied with your + commitments under this section. Upon any termination of + this Agreement all provisions survive except for the + license grant provisions. + + +1.7. General + +If you wish to assign this Agreement or your rights and +obligations, including by merger, consolidation, dissolution +or operation of law, contact NVIDIA to ask for permission. Any +attempted assignment not approved by NVIDIA in writing shall +be void and of no effect. NVIDIA may assign, delegate or +transfer this Agreement and its rights and obligations, and if +to a non-affiliate you will be notified. + +You agree to cooperate with NVIDIA and provide reasonably +requested information to verify your compliance with this +Agreement. + +This Agreement will be governed in all respects by the laws of +the United States and of the State of Delaware as those laws +are applied to contracts entered into and performed entirely +within Delaware by Delaware residents, without regard to the +conflicts of laws principles. The United Nations Convention on +Contracts for the International Sale of Goods is specifically +disclaimed. You agree to all terms of this Agreement in the +English language. + +The state or federal courts residing in Santa Clara County, +California shall have exclusive jurisdiction over any dispute +or claim arising out of this Agreement. Notwithstanding this, +you agree that NVIDIA shall still be allowed to apply for +injunctive remedies or an equivalent type of urgent legal +relief in any jurisdiction. + +If any court of competent jurisdiction determines that any +provision of this Agreement is illegal, invalid or +unenforceable, such provision will be construed as limited to +the extent necessary to be consistent with and fully +enforceable under the law and the remaining provisions will +remain in full force and effect. Unless otherwise specified, +remedies are cumulative. + +Each party acknowledges and agrees that the other is an +independent contractor in the performance of this Agreement. + +The SDK has been developed entirely at private expense and is +“commercial items” consisting of “commercial computer +software” and “commercial computer software +documentation” provided with RESTRICTED RIGHTS. Use, +duplication or disclosure by the U.S. Government or a U.S. +Government subcontractor is subject to the restrictions in +this Agreement pursuant to DFARS 227.7202-3(a) or as set forth +in subparagraphs (c)(1) and (2) of the Commercial Computer +Software - Restricted Rights clause at FAR 52.227-19, as +applicable. Contractor/manufacturer is NVIDIA, 2788 San Tomas +Expressway, Santa Clara, CA 95051. + +The SDK is subject to United States export laws and +regulations. You agree that you will not ship, transfer or +export the SDK into any country, or use the SDK in any manner, +prohibited by the United States Bureau of Industry and +Security or economic sanctions regulations administered by the +U.S. Department of Treasury’s Office of Foreign Assets +Control (OFAC), or any applicable export laws, restrictions or +regulations. These laws include restrictions on destinations, +end users and end use. By accepting this Agreement, you +confirm that you are not a resident or citizen of any country +currently embargoed by the U.S. and that you are not otherwise +prohibited from receiving the SDK. + +Any notice delivered by NVIDIA to you under this Agreement +will be delivered via mail, email or fax. You agree that any +notices that NVIDIA sends you electronically will satisfy any +legal communication requirements. Please direct your legal +notices or other correspondence to NVIDIA Corporation, 2788 +San Tomas Expressway, Santa Clara, California 95051, United +States of America, Attention: Legal Department. + +This Agreement and any exhibits incorporated into this +Agreement constitute the entire agreement of the parties with +respect to the subject matter of this Agreement and supersede +all prior negotiations or documentation exchanged between the +parties relating to this SDK license. Any additional and/or +conflicting terms on documents issued by you are null, void, +and invalid. Any amendment or waiver under this Agreement +shall be in writing and signed by representatives of both +parties. + + +2. CUDA Toolkit Supplement to Software License Agreement for +NVIDIA Software Development Kits +------------------------------------------------------------ + + +Release date: August 16, 2018 +----------------------------- + +The terms in this supplement govern your use of the NVIDIA +CUDA Toolkit SDK under the terms of your license agreement +(“Agreement”) as modified by this supplement. Capitalized +terms used but not defined below have the meaning assigned to +them in the Agreement. + +This supplement is an exhibit to the Agreement and is +incorporated as an integral part of the Agreement. In the +event of conflict between the terms in this supplement and the +terms in the Agreement, the terms in this supplement govern. + + +2.1. License Scope + +The SDK is licensed for you to develop applications only for +use in systems with NVIDIA GPUs. + + +2.2. Distribution + +The portions of the SDK that are distributable under the +Agreement are listed in Attachment A. + + +2.3. Operating Systems + +Those portions of the SDK designed exclusively for use on the +Linux or FreeBSD operating systems, or other operating systems +derived from the source code to these operating systems, may +be copied and redistributed for use in accordance with this +Agreement, provided that the object code files are not +modified in any way (except for unzipping of compressed +files). + + +2.4. Audio and Video Encoders and Decoders + +You acknowledge and agree that it is your sole responsibility +to obtain any additional third-party licenses required to +make, have made, use, have used, sell, import, and offer for +sale your products or services that include or incorporate any +third-party software and content relating to audio and/or +video encoders and decoders from, including but not limited +to, Microsoft, Thomson, Fraunhofer IIS, Sisvel S.p.A., +MPEG-LA, and Coding Technologies. NVIDIA does not grant to you +under this Agreement any necessary patent or other rights with +respect to any audio and/or video encoders and decoders. + + +2.5. Licensing + +If the distribution terms in this Agreement are not suitable +for your organization, or for any questions regarding this +Agreement, please contact NVIDIA at +nvidia-compute-license-questions@nvidia.com. + + +2.6. Attachment A + +The following portions of the SDK are distributable under the +Agreement: + +Component + +CUDA Runtime + +Windows + +cudart.dll, cudart_static.lib, cudadevrt.lib + +Mac OSX + +libcudart.dylib, libcudart_static.a, libcudadevrt.a + +Linux + +libcudart.so, libcudart_static.a, libcudadevrt.a + +Android + +libcudart.so, libcudart_static.a, libcudadevrt.a + +Component + +CUDA FFT Library + +Windows + +cufft.dll, cufftw.dll, cufft.lib, cufftw.lib + +Mac OSX + +libcufft.dylib, libcufft_static.a, libcufftw.dylib, +libcufftw_static.a + +Linux + +libcufft.so, libcufft_static.a, libcufftw.so, +libcufftw_static.a + +Android + +libcufft.so, libcufft_static.a, libcufftw.so, +libcufftw_static.a + +Component + +CUDA BLAS Library + +Windows + +cublas.dll, cublasLt.dll + +Mac OSX + +libcublas.dylib, libcublasLt.dylib, libcublas_static.a, +libcublasLt_static.a + +Linux + +libcublas.so, libcublasLt.so, libcublas_static.a, +libcublasLt_static.a + +Android + +libcublas.so, libcublasLt.so, libcublas_static.a, +libcublasLt_static.a + +Component + +NVIDIA "Drop-in" BLAS Library + +Windows + +nvblas.dll + +Mac OSX + +libnvblas.dylib + +Linux + +libnvblas.so + +Component + +CUDA Sparse Matrix Library + +Windows + +cusparse.dll, cusparse.lib + +Mac OSX + +libcusparse.dylib, libcusparse_static.a + +Linux + +libcusparse.so, libcusparse_static.a + +Android + +libcusparse.so, libcusparse_static.a + +Component + +CUDA Linear Solver Library + +Windows + +cusolver.dll, cusolver.lib + +Mac OSX + +libcusolver.dylib, libcusolver_static.a + +Linux + +libcusolver.so, libcusolver_static.a + +Android + +libcusolver.so, libcusolver_static.a + +Component + +CUDA Random Number Generation Library + +Windows + +curand.dll, curand.lib + +Mac OSX + +libcurand.dylib, libcurand_static.a + +Linux + +libcurand.so, libcurand_static.a + +Android + +libcurand.so, libcurand_static.a + +Component + +CUDA Accelerated Graph Library + +Component + +NVIDIA Performance Primitives Library + +Windows + +nppc.dll, nppc.lib, nppial.dll, nppial.lib, nppicc.dll, +nppicc.lib, nppicom.dll, nppicom.lib, nppidei.dll, +nppidei.lib, nppif.dll, nppif.lib, nppig.dll, nppig.lib, +nppim.dll, nppim.lib, nppist.dll, nppist.lib, nppisu.dll, +nppisu.lib, nppitc.dll, nppitc.lib, npps.dll, npps.lib + +Mac OSX + +libnppc.dylib, libnppc_static.a, libnppial.dylib, +libnppial_static.a, libnppicc.dylib, libnppicc_static.a, +libnppicom.dylib, libnppicom_static.a, libnppidei.dylib, +libnppidei_static.a, libnppif.dylib, libnppif_static.a, +libnppig.dylib, libnppig_static.a, libnppim.dylib, +libnppisu_static.a, libnppitc.dylib, libnppitc_static.a, +libnpps.dylib, libnpps_static.a + +Linux + +libnppc.so, libnppc_static.a, libnppial.so, +libnppial_static.a, libnppicc.so, libnppicc_static.a, +libnppicom.so, libnppicom_static.a, libnppidei.so, +libnppidei_static.a, libnppif.so, libnppif_static.a +libnppig.so, libnppig_static.a, libnppim.so, +libnppim_static.a, libnppist.so, libnppist_static.a, +libnppisu.so, libnppisu_static.a, libnppitc.so +libnppitc_static.a, libnpps.so, libnpps_static.a + +Android + +libnppc.so, libnppc_static.a, libnppial.so, +libnppial_static.a, libnppicc.so, libnppicc_static.a, +libnppicom.so, libnppicom_static.a, libnppidei.so, +libnppidei_static.a, libnppif.so, libnppif_static.a +libnppig.so, libnppig_static.a, libnppim.so, +libnppim_static.a, libnppist.so, libnppist_static.a, +libnppisu.so, libnppisu_static.a, libnppitc.so +libnppitc_static.a, libnpps.so, libnpps_static.a + +Component + +NVIDIA JPEG Library + +Linux + +libnvjpeg.so, libnvjpeg_static.a + +Component + +Internal common library required for statically linking to +cuBLAS, cuSPARSE, cuFFT, cuRAND, nvJPEG and NPP + +Mac OSX + +libculibos.a + +Linux + +libculibos.a + +Component + +NVIDIA Runtime Compilation Library and Header + +All + +nvrtc.h + +Windows + +nvrtc.dll, nvrtc-builtins.dll + +Mac OSX + +libnvrtc.dylib, libnvrtc-builtins.dylib + +Linux + +libnvrtc.so, libnvrtc-builtins.so + +Component + +NVIDIA Optimizing Compiler Library + +Windows + +nvvm.dll + +Mac OSX + +libnvvm.dylib + +Linux + +libnvvm.so + +Component + +NVIDIA Common Device Math Functions Library + +Windows + +libdevice.10.bc + +Mac OSX + +libdevice.10.bc + +Linux + +libdevice.10.bc + +Component + +CUDA Occupancy Calculation Header Library + +All + +cuda_occupancy.h + +Component + +CUDA Half Precision Headers + +All + +cuda_fp16.h, cuda_fp16.hpp + +Component + +CUDA Profiling Tools Interface (CUPTI) Library + +Windows + +cupti.dll + +Mac OSX + +libcupti.dylib + +Linux + +libcupti.so + +Component + +NVIDIA Tools Extension Library + +Windows + +nvToolsExt.dll, nvToolsExt.lib + +Mac OSX + +libnvToolsExt.dylib + +Linux + +libnvToolsExt.so + +Component + +NVIDIA CUDA Driver Libraries + +Linux + +libcuda.so, libnvidia-fatbinaryloader.so, +libnvidia-ptxjitcompiler.so + +The NVIDIA CUDA Driver Libraries are only distributable in +applications that meet this criteria: + + 1. The application was developed starting from a NVIDIA CUDA + container obtained from Docker Hub or the NVIDIA GPU + Cloud, and + + 2. The resulting application is packaged as a Docker + container and distributed to users on Docker Hub or the + NVIDIA GPU Cloud only. + + +2.7. Attachment B + + +Additional Licensing Obligations + +The following third party components included in the SOFTWARE +are licensed to Licensee pursuant to the following terms and +conditions: + + 1. Licensee's use of the GDB third party component is + subject to the terms and conditions of GNU GPL v3: + + This product includes copyrighted third-party software licensed + under the terms of the GNU General Public License v3 ("GPL v3"). + All third-party software packages are copyright by their respective + authors. GPL v3 terms and conditions are hereby incorporated into + the Agreement by this reference: http://www.gnu.org/licenses/gpl.txt + + Consistent with these licensing requirements, the software + listed below is provided under the terms of the specified + open source software licenses. To obtain source code for + software provided under licenses that require + redistribution of source code, including the GNU General + Public License (GPL) and GNU Lesser General Public License + (LGPL), contact oss-requests@nvidia.com. This offer is + valid for a period of three (3) years from the date of the + distribution of this product by NVIDIA CORPORATION. + + Component License + CUDA-GDB GPL v3 + + 2. Licensee represents and warrants that any and all third + party licensing and/or royalty payment obligations in + connection with Licensee's use of the H.264 video codecs + are solely the responsibility of Licensee. + + 3. Licensee's use of the Thrust library is subject to the + terms and conditions of the Apache License Version 2.0. + All third-party software packages are copyright by their + respective authors. Apache License Version 2.0 terms and + conditions are hereby incorporated into the Agreement by + this reference. + http://www.apache.org/licenses/LICENSE-2.0.html + + In addition, Licensee acknowledges the following notice: + Thrust includes source code from the Boost Iterator, + Tuple, System, and Random Number libraries. + + Boost Software License - Version 1.0 - August 17th, 2003 + . . . . + + Permission is hereby granted, free of charge, to any person or + organization obtaining a copy of the software and accompanying + documentation covered by this license (the "Software") to use, + reproduce, display, distribute, execute, and transmit the Software, + and to prepare derivative works of the Software, and to permit + third-parties to whom the Software is furnished to do so, all + subject to the following: + + The copyright notices in the Software and this entire statement, + including the above license grant, this restriction and the following + disclaimer, must be included in all copies of the Software, in whole + or in part, and all derivative works of the Software, unless such + copies or derivative works are solely in the form of machine-executable + object code generated by a source language processor. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND + NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR + OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + 4. Licensee's use of the LLVM third party component is + subject to the following terms and conditions: + + ====================================================== + LLVM Release License + ====================================================== + University of Illinois/NCSA + Open Source License + + Copyright (c) 2003-2010 University of Illinois at Urbana-Champaign. + All rights reserved. + + Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to + deal with the Software without restriction, including without limitation the + rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + sell copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at Urbana- + Champaign, nor the names of its contributors may be used to endorse or + promote products derived from this Software without specific prior + written permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. + + 5. Licensee's use (e.g. nvprof) of the PCRE third party + component is subject to the following terms and + conditions: + + ------------ + PCRE LICENCE + ------------ + PCRE is a library of functions to support regular expressions whose syntax + and semantics are as close as possible to those of the Perl 5 language. + Release 8 of PCRE is distributed under the terms of the "BSD" licence, as + specified below. The documentation for PCRE, supplied in the "doc" + directory, is distributed under the same terms as the software itself. The + basic library functions are written in C and are freestanding. Also + included in the distribution is a set of C++ wrapper functions, and a just- + in-time compiler that can be used to optimize pattern matching. These are + both optional features that can be omitted when the library is built. + + THE BASIC LIBRARY FUNCTIONS + --------------------------- + Written by: Philip Hazel + Email local part: ph10 + Email domain: cam.ac.uk + University of Cambridge Computing Service, + Cambridge, England. + Copyright (c) 1997-2012 University of Cambridge + All rights reserved. + + PCRE JUST-IN-TIME COMPILATION SUPPORT + ------------------------------------- + Written by: Zoltan Herczeg + Email local part: hzmester + Emain domain: freemail.hu + Copyright(c) 2010-2012 Zoltan Herczeg + All rights reserved. + + STACK-LESS JUST-IN-TIME COMPILER + -------------------------------- + Written by: Zoltan Herczeg + Email local part: hzmester + Emain domain: freemail.hu + Copyright(c) 2009-2012 Zoltan Herczeg + All rights reserved. + + THE C++ WRAPPER FUNCTIONS + ------------------------- + Contributed by: Google Inc. + Copyright (c) 2007-2012, Google Inc. + All rights reserved. + + THE "BSD" LICENCE + ----------------- + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the name of Google + Inc. nor the names of their 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. + + 6. Some of the cuBLAS library routines were written by or + derived from code written by Vasily Volkov and are subject + to the Modified Berkeley Software Distribution License as + follows: + + Copyright (c) 2007-2009, Regents of the University of California + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the University of California, Berkeley 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 AUTHOR "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 AUTHOR 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. + + 7. Some of the cuBLAS library routines were written by or + derived from code written by Davide Barbieri and are + subject to the Modified Berkeley Software Distribution + License as follows: + + Copyright (c) 2008-2009 Davide Barbieri @ University of Rome Tor Vergata. + + 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. + * The name of the author may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 AUTHOR 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. + + 8. Some of the cuBLAS library routines were derived from + code developed by the University of Tennessee and are + subject to the Modified Berkeley Software Distribution + License as follows: + + Copyright (c) 2010 The University of Tennessee. + + 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 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. + + 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. + + 9. Some of the cuBLAS library routines were written by or + derived from code written by Jonathan Hogg and are subject + to the Modified Berkeley Software Distribution License as + follows: + + Copyright (c) 2012, The Science and Technology Facilities Council (STFC). + + 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 STFC 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 STFC 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. + + 10. Some of the cuBLAS library routines were written by or + derived from code written by Ahmad M. Abdelfattah, David + Keyes, and Hatem Ltaief, and are subject to the Apache + License, Version 2.0, as follows: + + -- (C) Copyright 2013 King Abdullah University of Science and Technology + Authors: + Ahmad Abdelfattah (ahmad.ahmad@kaust.edu.sa) + David Keyes (david.keyes@kaust.edu.sa) + Hatem Ltaief (hatem.ltaief@kaust.edu.sa) + + 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 King Abdullah University of Science and + Technology 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 + HOLDERS 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 + + 11. Some of the cuSPARSE library routines were written by or + derived from code written by Li-Wen Chang and are subject + to the NCSA Open Source License as follows: + + Copyright (c) 2012, University of Illinois. + + All rights reserved. + + Developed by: IMPACT Group, University of Illinois, http://impact.crhc.illinois.edu + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal with the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimers in the documentation and/or other materials provided + with the distribution. + * Neither the names of IMPACT Group, University of Illinois, nor + the names of its contributors may be used to endorse or promote + products derived from this Software without specific prior + written permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR + IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE + SOFTWARE. + + 12. Some of the cuRAND library routines were written by or + derived from code written by Mutsuo Saito and Makoto + Matsumoto and are subject to the following license: + + Copyright (c) 2009, 2010 Mutsuo Saito, Makoto Matsumoto and Hiroshima + University. All rights reserved. + + Copyright (c) 2011 Mutsuo Saito, Makoto Matsumoto, Hiroshima + University and University of Tokyo. 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 Hiroshima University 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. + + 13. Some of the cuRAND library routines were derived from + code developed by D. E. Shaw Research and are subject to + the following license: + + Copyright 2010-2011, D. E. Shaw Research. + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions, and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions, and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of D. E. Shaw Research nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + 14. Some of the Math library routines were written by or + derived from code developed by Norbert Juffa and are + subject to the following license: + + Copyright (c) 2015-2017, Norbert Juffa + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + 15. Licensee's use of the lz4 third party component is + subject to the following terms and conditions: + + Copyright (C) 2011-2013, Yann Collet. + BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + + 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. + + 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. + + 16. The NPP library uses code from the Boost Math Toolkit, + and is subject to the following license: + + Boost Software License - Version 1.0 - August 17th, 2003 + . . . . + + Permission is hereby granted, free of charge, to any person or + organization obtaining a copy of the software and accompanying + documentation covered by this license (the "Software") to use, + reproduce, display, distribute, execute, and transmit the Software, + and to prepare derivative works of the Software, and to permit + third-parties to whom the Software is furnished to do so, all + subject to the following: + + The copyright notices in the Software and this entire statement, + including the above license grant, this restriction and the following + disclaimer, must be included in all copies of the Software, in whole + or in part, and all derivative works of the Software, unless such + copies or derivative works are solely in the form of machine-executable + object code generated by a source language processor. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND + NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR + OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + 17. Portions of the Nsight Eclipse Edition is subject to the + following license: + + The Eclipse Foundation makes available all content in this plug-in + ("Content"). Unless otherwise indicated below, the Content is provided + to you under the terms and conditions of the Eclipse Public License + Version 1.0 ("EPL"). A copy of the EPL is available at http:// + www.eclipse.org/legal/epl-v10.html. For purposes of the EPL, "Program" + will mean the Content. + + If you did not receive this Content directly from the Eclipse + Foundation, the Content is being redistributed by another party + ("Redistributor") and different terms and conditions may apply to your + use of any object code in the Content. Check the Redistributor's + license that was provided with the Content. If no such license exists, + contact the Redistributor. Unless otherwise indicated below, the terms + and conditions of the EPL still apply to any source code in the + Content and such source code may be obtained at http://www.eclipse.org. + + 18. Some of the cuBLAS library routines uses code from + OpenAI, which is subject to the following license: + + License URL + https://github.com/openai/openai-gemm/blob/master/LICENSE + + License Text + The MIT License + + Copyright (c) 2016 OpenAI (http://openai.com), 2016 Google Inc. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + + 19. Licensee's use of the Visual Studio Setup Configuration + Samples is subject to the following license: + + The MIT License (MIT) + Copyright (C) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + 20. Licensee's use of linmath.h header for CPU functions for + GL vector/matrix operations from lunarG is subject to the + Apache License Version 2.0. + + 21. The DX12-CUDA sample uses the d3dx12.h header, which is + subject to the MIT license . + +----------------- diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_runtime_cu12-12.8.90.dist-info/METADATA b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_runtime_cu12-12.8.90.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..14b471170862b26f1dc2b83800d568d5c38533ec --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_runtime_cu12-12.8.90.dist-info/METADATA @@ -0,0 +1,44 @@ +Metadata-Version: 2.2 +Name: nvidia-cuda-runtime-cu12 +Version: 12.8.90 +Summary: CUDA Runtime native Libraries +Home-page: https://developer.nvidia.com/cuda-zone +Author: Nvidia CUDA Installer Team +Author-email: compute_installer@nvidia.com +License: NVIDIA Proprietary Software +Keywords: cuda,nvidia,runtime,machine learning,deep learning +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: Other/Proprietary License +Classifier: Natural Language :: English +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX :: Linux +Requires-Python: >=3 +License-File: License.txt +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: requires-python +Dynamic: summary + +CUDA Runtime native Libraries diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_runtime_cu12-12.8.90.dist-info/RECORD b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_runtime_cu12-12.8.90.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..4c994e833b38144d3fc8ce6392a94d6f11b45e58 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_runtime_cu12-12.8.90.dist-info/RECORD @@ -0,0 +1,107 @@ +nvidia/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cuda_runtime/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cuda_runtime/include/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cuda_runtime/include/builtin_types.h,sha256=JxT9Vf2q2snxTBOL9ACzNmYzTWACO2VOVUu1KdFt7_g,3150 +nvidia/cuda_runtime/include/channel_descriptor.h,sha256=oZIDO1kdexPb9jltUx1AsXAFknvRWAAr1456925Pqig,21846 +nvidia/cuda_runtime/include/common_functions.h,sha256=22LTZRVcPZzEH6MJda7nNMCvMgIjSTe0OKR7sEQj6kc,3410 +nvidia/cuda_runtime/include/cooperative_groups.h,sha256=y2cFxa6e-saEFA9aW22ZuTwi0wud7eEHq7XN3v30LT0,60684 +nvidia/cuda_runtime/include/cooperative_groups/details/async.h,sha256=xsEHCZP3nuEY3l2p8SU2d1226XiXumUvDP_Gyh8PdVY,19122 +nvidia/cuda_runtime/include/cooperative_groups/details/coalesced_reduce.h,sha256=pBQgFY7i64V87XNATg1UEIQHVNYOItQtHjS5B4yn8pc,4257 +nvidia/cuda_runtime/include/cooperative_groups/details/coalesced_scan.h,sha256=DfZv5d5W0XJv-tZVhgrIdjLjs6aCx_u0oy1lDIpjo1Q,7314 +nvidia/cuda_runtime/include/cooperative_groups/details/driver_abi.h,sha256=v-ZUb4UgGKJk6NR2WCWHD3x_42y-togI1urFn70Gi-g,3964 +nvidia/cuda_runtime/include/cooperative_groups/details/functional.h,sha256=2BV8i8Bidz0kgxuYkJCAbwFxOIZRyzHgG-c_rVKhRzc,8905 +nvidia/cuda_runtime/include/cooperative_groups/details/helpers.h,sha256=K9jvxnXc5-6Fum1KG4EQKJJrVZ4BhHOSAJbZR4uDL0c,26476 +nvidia/cuda_runtime/include/cooperative_groups/details/info.h,sha256=FOrp3Ltt4PcbK2fAM5UX9jssFZtj_LqVShzLFcKiSaY,12465 +nvidia/cuda_runtime/include/cooperative_groups/details/invoke.h,sha256=Osq3K-tZuXHVCMQJ708PjPo-BwMhjhjApO4b0TYLFJg,8616 +nvidia/cuda_runtime/include/cooperative_groups/details/memory.h,sha256=hES3SfgXIBsj2MFrC_M5COXlOirSBuuhPMAJnWoI92w,5606 +nvidia/cuda_runtime/include/cooperative_groups/details/partitioning.h,sha256=AQz-TheqX3onqX2RmIUipzYUVB273zhLlHJw_kX9D2U,7153 +nvidia/cuda_runtime/include/cooperative_groups/details/reduce.h,sha256=MjqMDwT0TyWZk4JWcF3WHw8xtwMqyizA4C3zy7f8ee0,23296 +nvidia/cuda_runtime/include/cooperative_groups/details/scan.h,sha256=-Ttwb2AfEEY_tsmqJjR2dojkPpoRx387SoqxgvfdBtQ,17166 +nvidia/cuda_runtime/include/cooperative_groups/details/sync.h,sha256=Ed4K9QrPZi43ddSqZwv1X8NG_CTsXUowSQndoUv82LU,10795 +nvidia/cuda_runtime/include/cooperative_groups/memcpy_async.h,sha256=erOIHuObdfxRhBWfrXE3wsZF4B2GUuqwzQrsPwKPpbg,2960 +nvidia/cuda_runtime/include/cooperative_groups/reduce.h,sha256=B0hgDkqM-6ueqTTgb3b34A0RH4vGz8mBf5e2jT1dJ1o,2949 +nvidia/cuda_runtime/include/cooperative_groups/scan.h,sha256=2EU6T5cWNwftm2B7FicV31PojoI61yo5fHXGRYkGk40,2940 +nvidia/cuda_runtime/include/cuComplex.h,sha256=WpcgpaiPhU_o9sTPMcNTEZuyXDIc8x3sz4dUWSztL2g,12186 +nvidia/cuda_runtime/include/cuda.h,sha256=RWjMnnoyHkdwfNZAOYDyGsLi5VFwUA0OCj9U_rA6mss,1156988 +nvidia/cuda_runtime/include/cudaEGL.h,sha256=iruZU9xSGAcJ29OEX4K_Uo1o4NGP9hggv2fiOZOfDQo,39955 +nvidia/cuda_runtime/include/cudaEGLTypedefs.h,sha256=xF_FAN1Kar9oyHJ3cCU7jztTpxX8WylpiuYyYpGGHek,5645 +nvidia/cuda_runtime/include/cudaGL.h,sha256=gMT1HPGa-siuji0gAsKYr4X45Lc29HKglC_ttNSGyUM,22501 +nvidia/cuda_runtime/include/cudaGLTypedefs.h,sha256=dClpQI-LuXgF9rPSBsj7OkIg8g_fXDjT0hLZS8TGpOg,6576 +nvidia/cuda_runtime/include/cudaProfilerTypedefs.h,sha256=F2aWLIKv_AhNbxNOaZVcRsxIh0kuscnV8UMWWxkBAlY,3297 +nvidia/cuda_runtime/include/cudaTypedefs.h,sha256=SKfAvTOj19zxsiLGKhoxXPiopKqoe5hjj5iXkR2_v6E,115169 +nvidia/cuda_runtime/include/cudaVDPAU.h,sha256=Np7Nc2Wjaz--hkpbhW6f9aapr-NbcPDAgkot0sJerco,12694 +nvidia/cuda_runtime/include/cudaVDPAUTypedefs.h,sha256=wz8nyOUdwM9mH9JO3QZW-A9dyxt-IufSX7nggSXpCNs,4144 +nvidia/cuda_runtime/include/cuda_awbarrier.h,sha256=3ZH-ZlXODhSiwSY9rqSni_EQwi25QMHP6Tm-zOdxBwE,9340 +nvidia/cuda_runtime/include/cuda_awbarrier_helpers.h,sha256=OCskCts5bCKl_RKBe9M74zKSIsVpePn44S_aJp1tFXE,12489 +nvidia/cuda_runtime/include/cuda_awbarrier_primitives.h,sha256=n5__E1jYYDhlgH-f3u8MQjtz57UZ7v5VshhMye1eicM,4699 +nvidia/cuda_runtime/include/cuda_bf16.h,sha256=TVoq2IrbF5g67wUF7W7SoGA0l8ecEDu6gskoMB6hIxA,204512 +nvidia/cuda_runtime/include/cuda_bf16.hpp,sha256=OukWXoN6bgRlC-p8CFbhUN0G0uAJb_zos1mCPagscnI,136544 +nvidia/cuda_runtime/include/cuda_device_runtime_api.h,sha256=54l66QbwerX0wPKoJC2y7qCdGP8nv1_GgdmMV8A0x4k,46986 +nvidia/cuda_runtime/include/cuda_egl_interop.h,sha256=awWBBEYvUFM7AURNp2mND8H7_5kGQLRswRveXYBy-3s,37509 +nvidia/cuda_runtime/include/cuda_fp16.h,sha256=jrFgCo4uM9QFcr_-cAGif2BGp0lJ2ANT_gLPiLJWPdo,206851 +nvidia/cuda_runtime/include/cuda_fp16.hpp,sha256=o1ITDmuN67N8YUGUcvTpV3IdpS-6wwlm65M_H-8LYKs,120927 +nvidia/cuda_runtime/include/cuda_fp4.h,sha256=pTEQf5rLfiaU_UMXgnnsS13NH5H9FtHgdeiNuW_NkHY,13823 +nvidia/cuda_runtime/include/cuda_fp4.hpp,sha256=YYaUu-YRgYdj9xYu4ZDh_uPVffxkDlEr0CD_bhlF8BE,35423 +nvidia/cuda_runtime/include/cuda_fp6.h,sha256=6xh0E4SNmjmJZD3H5_HoZe08bQ0loUE8y3cbO19-Ad4,13963 +nvidia/cuda_runtime/include/cuda_fp6.hpp,sha256=qa838buZeLP32xBVqbo71uFSW5RnBWx9qp5D-SR_xc0,56455 +nvidia/cuda_runtime/include/cuda_fp8.h,sha256=QSTMRb9l7I9mnvT1_8KXNqLO48wWaWEgG97bDjEh1ic,18072 +nvidia/cuda_runtime/include/cuda_fp8.hpp,sha256=4L694zXu22I9-DaAP77zm-gZQLpOdgsqkWaGM2_20X0,97282 +nvidia/cuda_runtime/include/cuda_gl_interop.h,sha256=VQEswFeOBF6JN6Q0pdlkvc5WT7bD1FnTfKewvANulCc,19150 +nvidia/cuda_runtime/include/cuda_occupancy.h,sha256=0HavrMIWXGxIujaq72iX31-73Zprx0WBYdiln3ZNP2w,71302 +nvidia/cuda_runtime/include/cuda_pipeline.h,sha256=0enXG49wN4JajlQi3ahbp2ei_ufTY_Mznic7zfWmKHM,8130 +nvidia/cuda_runtime/include/cuda_pipeline_helpers.h,sha256=bo1L7e6vCuM-K3Il8K1z4wJUja5DyXQKdo_hSWUME-E,13852 +nvidia/cuda_runtime/include/cuda_pipeline_primitives.h,sha256=FnJJtuV6rHr6LgL56XDwilcSbFr6W1Hj6mf1AJaMI20,8675 +nvidia/cuda_runtime/include/cuda_runtime.h,sha256=GqqE7SrECGrN-Qg5Dk90LSjs-xvKlHZpRLlpH7LUehM,98570 +nvidia/cuda_runtime/include/cuda_runtime_api.h,sha256=EWhSESFT_vV5eYZpTBEu4EvgNtE9rhmHP503XnIGHIs,655943 +nvidia/cuda_runtime/include/cuda_surface_types.h,sha256=Mw5Lo4b8Q-f9mogOvATGyHhu9d2t2K6XOxuqtZrSh3A,3688 +nvidia/cuda_runtime/include/cuda_texture_types.h,sha256=ITbX-JNnP7Rm-JSgNVdJ9pq6k8FVor8RbnruDsKq6sk,3688 +nvidia/cuda_runtime/include/cuda_vdpau_interop.h,sha256=bXQanWc2IFXZAKWNGl2xAz9nLvFmQpWyGrsDvfeS9FA,7727 +nvidia/cuda_runtime/include/cudart_platform.h,sha256=YN6sKhB0b9w5tGX1IYL7ulJVPrWAiX9A44qLv4EtW5Q,2717 +nvidia/cuda_runtime/include/device_atomic_functions.h,sha256=OR2jNSfSKzaFri74zh4Vtz5M0z9UDBU3rKeC1rYaVQs,9500 +nvidia/cuda_runtime/include/device_atomic_functions.hpp,sha256=0e7MOiNNUnnloXpB_r9WT5YOws5cxgzQQAzRCYvgaFA,10486 +nvidia/cuda_runtime/include/device_double_functions.h,sha256=KUxId5Z1fx8SWfLRTxPD7RB-zN7zslzb4n7JaJLfL3I,3452 +nvidia/cuda_runtime/include/device_functions.h,sha256=bWSrhTYE9NQlss7xMSMEVusvto9j2fgUDXWVH2W_cOA,3410 +nvidia/cuda_runtime/include/device_launch_parameters.h,sha256=H1_CC-vvAaS26ys4XsTFkMgTxUTciAjdjswjizkisvQ,3846 +nvidia/cuda_runtime/include/device_types.h,sha256=2LFxoZBJPoA5V0H1EbKTEaXDi3GDJPtzOPdRHDaucIQ,3588 +nvidia/cuda_runtime/include/driver_functions.h,sha256=cN3IjRAz2Mj2Pj35SyxJIkZNDDusnJqaqzBdMzpQKbA,4625 +nvidia/cuda_runtime/include/driver_types.h,sha256=mMNbiIwg5E3k7Sk685YCSvnKYmfQ3bxWv3bkEgzOtNU,200083 +nvidia/cuda_runtime/include/host_config.h,sha256=BscH_GazAZbbotddVzL5RmafbQ-QjRx8f-I1O01IBW8,3380 +nvidia/cuda_runtime/include/host_defines.h,sha256=bBQwQF5C1N1c2qpLV56g1c-weu9Ysgz-gIf2Kn3uz_A,3386 +nvidia/cuda_runtime/include/library_types.h,sha256=i-GFcw92wvcixs2bQjOj4I_q26HYY_VY4DpDvHWQCjY,5156 +nvidia/cuda_runtime/include/math_constants.h,sha256=cV6hAyQe8X7f7MBtaKjjIJq3BycOUDp6I5cizJX5HLw,7608 +nvidia/cuda_runtime/include/math_functions.h,sha256=5XcC6j-fJKttvhwc4hZNoLHNw808a2ZYIOtZ7ry7yd0,3398 +nvidia/cuda_runtime/include/mma.h,sha256=IY_VenxuEncwGq92MhrWUb-Xswh0ekAXLy9Rbxhxa2Y,2932 +nvidia/cuda_runtime/include/sm_20_atomic_functions.h,sha256=x4ycINVq__l9B4SQPD-I48jQbKxxdBmgp8Vf2GO0Qfg,4478 +nvidia/cuda_runtime/include/sm_20_atomic_functions.hpp,sha256=1l5NLM8DhDbqYZ_E51LoqElQJXObkbwo57d3r-4uEbE,4107 +nvidia/cuda_runtime/include/sm_20_intrinsics.h,sha256=axeDr7y6nT1V6LzrSWNSaHUwXgiNjPbXn1T6Uh7hlNM,57702 +nvidia/cuda_runtime/include/sm_20_intrinsics.hpp,sha256=mJTejRhw1prNiP_ax1OPbkYlhEqBqO4nVI3DRDXIzpo,8392 +nvidia/cuda_runtime/include/sm_30_intrinsics.h,sha256=b6W8Vxp9vD9OCJI6lZuGyZYXEdQ3Ei8PTAloHNkwCcQ,16978 +nvidia/cuda_runtime/include/sm_30_intrinsics.hpp,sha256=yX0ebd265tJ-BDhvluP2BhadPuWXpRZPI2eeQFFt5ys,24567 +nvidia/cuda_runtime/include/sm_32_atomic_functions.h,sha256=HGnZgQHACE2AAb6zabGUURc53IsVZelc2BSJqvs9OgY,5703 +nvidia/cuda_runtime/include/sm_32_atomic_functions.hpp,sha256=CQTTvOEYp-s5hqAgLvAon11vLYDrDp8cTHdel-XRzBQ,6592 +nvidia/cuda_runtime/include/sm_32_intrinsics.h,sha256=Xdkogdsjy1vh8u3eGu0i5xTmHxBGAjj6_vVGR-spdOE,33539 +nvidia/cuda_runtime/include/sm_32_intrinsics.hpp,sha256=Gl8aSLDLcit4W3pKQS19GsDG8RYcwD65HwYB_CeZe8M,70616 +nvidia/cuda_runtime/include/sm_35_atomic_functions.h,sha256=a3XoEsKRCEOf0Q_5Y__rMfmC4pScv4VkUggVgVJVn44,2909 +nvidia/cuda_runtime/include/sm_35_intrinsics.h,sha256=0mS5-LCgvZiTvL7-MG_4YwI-zWGvM-s4xyRuMkunMC8,2664 +nvidia/cuda_runtime/include/sm_60_atomic_functions.h,sha256=_anfNaJsvQpDEorYeUKIkbizYkwrinBcG_ZCiECtLqI,13178 +nvidia/cuda_runtime/include/sm_60_atomic_functions.hpp,sha256=cgIKddDn2B3QzYlzeBILAP1IRys74QCCxsH0QqaVGls,22903 +nvidia/cuda_runtime/include/sm_61_intrinsics.h,sha256=h_MBL1UUDxQX_qOddSImzqyFjcrhhm_63G97pGDyreU,10902 +nvidia/cuda_runtime/include/sm_61_intrinsics.hpp,sha256=N-nQvcBsPMT2Umy5zR69c9K1q366W-Jqe7NpoLTqTmg,6787 +nvidia/cuda_runtime/include/surface_functions.h,sha256=b1O82SAvEgWWxA9uZTWQcGimzZUoem2QbAET3wh3fZc,6782 +nvidia/cuda_runtime/include/surface_indirect_functions.h,sha256=vy9QuFVV-ezZP-x2RT9RLp2qIUgdngACOCmalSfVFPA,10877 +nvidia/cuda_runtime/include/surface_types.h,sha256=XkFXD1nHbeSMgajR-UJE9uQ7TByzJnjdnUL4-yGiufk,4530 +nvidia/cuda_runtime/include/texture_fetch_functions.h,sha256=KLCmUxf5aY5_UalX8tSFB6e4TrjA8hyUPxLOkMFltAo,12468 +nvidia/cuda_runtime/include/texture_indirect_functions.h,sha256=lH_y3Ni-hq4RZ0_PMFbBM0th5-OmTn3TtqtpkHHhA8w,21163 +nvidia/cuda_runtime/include/texture_types.h,sha256=73ntVyg8r8fzKy5VIk6yuvC45GDeWepaLIqIk-M3Ri8,6360 +nvidia/cuda_runtime/include/vector_functions.h,sha256=WypGkL-IDbGOlay7g_G0p3HO7OLGRE0Do__JtiFoWxY,8003 +nvidia/cuda_runtime/include/vector_functions.hpp,sha256=afXhNSd3LFTZo96EPtesTLfvxd4nTmLVzgkj967rTRg,10060 +nvidia/cuda_runtime/include/vector_types.h,sha256=6CJ4yt3KD7zQVfm1NhrgqNYYEDEIZWwaivlFx12nhNg,13396 +nvidia/cuda_runtime/lib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cuda_runtime/lib/libcudart.so.12,sha256=w6dbM68zSjSG0Zfb0VhKKYUYO6RojSN6K-Xy9nkymSA,728800 +nvidia_cuda_runtime_cu12-12.8.90.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +nvidia_cuda_runtime_cu12-12.8.90.dist-info/License.txt,sha256=rW9YU_ugyg0VnQ9Y1JrkmDDC-Mk_epJki5zpCttMbM0,59262 +nvidia_cuda_runtime_cu12-12.8.90.dist-info/METADATA,sha256=AEMTOOqYPUvi9G-f0pzsL9m_o5VTkzyln9NxkufQ-C8,1684 +nvidia_cuda_runtime_cu12-12.8.90.dist-info/RECORD,, +nvidia_cuda_runtime_cu12-12.8.90.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia_cuda_runtime_cu12-12.8.90.dist-info/WHEEL,sha256=ygM8qpYgOvrn5C-8vbfzPi-0iFPECh71lLWqkqrTjYw,144 +nvidia_cuda_runtime_cu12-12.8.90.dist-info/top_level.txt,sha256=fTkAtiFuL16nUrB9ytDDtpytz2t0B4NvYTnRzwAhO14,7 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_runtime_cu12-12.8.90.dist-info/REQUESTED b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_runtime_cu12-12.8.90.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_runtime_cu12-12.8.90.dist-info/WHEEL b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_runtime_cu12-12.8.90.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..287a9d7e1a3d4435e9542cc8216b8c5eaf2c0ed2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_runtime_cu12-12.8.90.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.8.0) +Root-Is-Purelib: true +Tag: py3-none-manylinux2014_x86_64 +Tag: py3-none-manylinux_2_17_x86_64 + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_runtime_cu12-12.8.90.dist-info/top_level.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_runtime_cu12-12.8.90.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..862f7abf232cdfbb928609856247292e81c9decb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cuda_runtime_cu12-12.8.90.dist-info/top_level.txt @@ -0,0 +1 @@ +nvidia diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.3.3.83.dist-info/License.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.3.3.83.dist-info/License.txt new file mode 100644 index 0000000000000000000000000000000000000000..b491c70e0aef319022ded661e111ddbd45b8a17f --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.3.3.83.dist-info/License.txt @@ -0,0 +1,1568 @@ +End User License Agreement +-------------------------- + + +Preface +------- + +The Software License Agreement in Chapter 1 and the Supplement +in Chapter 2 contain license terms and conditions that govern +the use of NVIDIA software. By accepting this agreement, you +agree to comply with all the terms and conditions applicable +to the product(s) included herein. + + +NVIDIA Driver + + +Description + +This package contains the operating system driver and +fundamental system software components for NVIDIA GPUs. + + +NVIDIA CUDA Toolkit + + +Description + +The NVIDIA CUDA Toolkit provides command-line and graphical +tools for building, debugging and optimizing the performance +of applications accelerated by NVIDIA GPUs, runtime and math +libraries, and documentation including programming guides, +user manuals, and API references. + + +Default Install Location of CUDA Toolkit + +Windows platform: + +%ProgramFiles%\NVIDIA GPU Computing Toolkit\CUDA\v#.# + +Linux platform: + +/usr/local/cuda-#.# + +Mac platform: + +/Developer/NVIDIA/CUDA-#.# + + +NVIDIA CUDA Samples + + +Description + +This package includes over 100+ CUDA examples that demonstrate +various CUDA programming principles, and efficient CUDA +implementation of algorithms in specific application domains. + + +Default Install Location of CUDA Samples + +Windows platform: + +%ProgramData%\NVIDIA Corporation\CUDA Samples\v#.# + +Linux platform: + +/usr/local/cuda-#.#/samples + +and + +$HOME/NVIDIA_CUDA-#.#_Samples + +Mac platform: + +/Developer/NVIDIA/CUDA-#.#/samples + + +NVIDIA Nsight Visual Studio Edition (Windows only) + + +Description + +NVIDIA Nsight Development Platform, Visual Studio Edition is a +development environment integrated into Microsoft Visual +Studio that provides tools for debugging, profiling, analyzing +and optimizing your GPU computing and graphics applications. + + +Default Install Location of Nsight Visual Studio Edition + +Windows platform: + +%ProgramFiles(x86)%\NVIDIA Corporation\Nsight Visual Studio Edition #.# + + +1. License Agreement for NVIDIA Software Development Kits +--------------------------------------------------------- + + +Release Date: July 26, 2018 +--------------------------- + + +Important NoticeRead before downloading, installing, +copying or using the licensed software: +------------------------------------------------------- + +This license agreement, including exhibits attached +("Agreement”) is a legal agreement between you and NVIDIA +Corporation ("NVIDIA") and governs your use of a NVIDIA +software development kit (“SDK”). + +Each SDK has its own set of software and materials, but here +is a description of the types of items that may be included in +a SDK: source code, header files, APIs, data sets and assets +(examples include images, textures, models, scenes, videos, +native API input/output files), binary software, sample code, +libraries, utility programs, programming code and +documentation. + +This Agreement can be accepted only by an adult of legal age +of majority in the country in which the SDK is used. + +If you are entering into this Agreement on behalf of a company +or other legal entity, you represent that you have the legal +authority to bind the entity to this Agreement, in which case +“you” will mean the entity you represent. + +If you don’t have the required age or authority to accept +this Agreement, or if you don’t accept all the terms and +conditions of this Agreement, do not download, install or use +the SDK. + +You agree to use the SDK only for purposes that are permitted +by (a) this Agreement, and (b) any applicable law, regulation +or generally accepted practices or guidelines in the relevant +jurisdictions. + + +1.1. License + + +1.1.1. License Grant + +Subject to the terms of this Agreement, NVIDIA hereby grants +you a non-exclusive, non-transferable license, without the +right to sublicense (except as expressly provided in this +Agreement) to: + + 1. Install and use the SDK, + + 2. Modify and create derivative works of sample source code + delivered in the SDK, and + + 3. Distribute those portions of the SDK that are identified + in this Agreement as distributable, as incorporated in + object code format into a software application that meets + the distribution requirements indicated in this Agreement. + + +1.1.2. Distribution Requirements + +These are the distribution requirements for you to exercise +the distribution grant: + + 1. Your application must have material additional + functionality, beyond the included portions of the SDK. + + 2. The distributable portions of the SDK shall only be + accessed by your application. + + 3. The following notice shall be included in modifications + and derivative works of sample source code distributed: + “This software contains source code provided by NVIDIA + Corporation.” + + 4. Unless a developer tool is identified in this Agreement + as distributable, it is delivered for your internal use + only. + + 5. The terms under which you distribute your application + must be consistent with the terms of this Agreement, + including (without limitation) terms relating to the + license grant and license restrictions and protection of + NVIDIA’s intellectual property rights. Additionally, you + agree that you will protect the privacy, security and + legal rights of your application users. + + 6. You agree to notify NVIDIA in writing of any known or + suspected distribution or use of the SDK not in compliance + with the requirements of this Agreement, and to enforce + the terms of your agreements with respect to distributed + SDK. + + +1.1.3. Authorized Users + +You may allow employees and contractors of your entity or of +your subsidiary(ies) to access and use the SDK from your +secure network to perform work on your behalf. + +If you are an academic institution you may allow users +enrolled or employed by the academic institution to access and +use the SDK from your secure network. + +You are responsible for the compliance with the terms of this +Agreement by your authorized users. If you become aware that +your authorized users didn’t follow the terms of this +Agreement, you agree to take reasonable steps to resolve the +non-compliance and prevent new occurrences. + + +1.1.4. Pre-Release SDK + +The SDK versions identified as alpha, beta, preview or +otherwise as pre-release, may not be fully functional, may +contain errors or design flaws, and may have reduced or +different security, privacy, accessibility, availability, and +reliability standards relative to commercial versions of +NVIDIA software and materials. Use of a pre-release SDK may +result in unexpected results, loss of data, project delays or +other unpredictable damage or loss. + +You may use a pre-release SDK at your own risk, understanding +that pre-release SDKs are not intended for use in production +or business-critical systems. + +NVIDIA may choose not to make available a commercial version +of any pre-release SDK. NVIDIA may also choose to abandon +development and terminate the availability of a pre-release +SDK at any time without liability. + + +1.1.5. Updates + +NVIDIA may, at its option, make available patches, workarounds +or other updates to this SDK. Unless the updates are provided +with their separate governing terms, they are deemed part of +the SDK licensed to you as provided in this Agreement. You +agree that the form and content of the SDK that NVIDIA +provides may change without prior notice to you. While NVIDIA +generally maintains compatibility between versions, NVIDIA may +in some cases make changes that introduce incompatibilities in +future versions of the SDK. + + +1.1.6. Third Party Licenses + +The SDK may come bundled with, or otherwise include or be +distributed with, third party software licensed by a NVIDIA +supplier and/or open source software provided under an open +source license. Use of third party software is subject to the +third-party license terms, or in the absence of third party +terms, the terms of this Agreement. Copyright to third party +software is held by the copyright holders indicated in the +third-party software or license. + + +1.1.7. Reservation of Rights + +NVIDIA reserves all rights, title, and interest in and to the +SDK, not expressly granted to you under this Agreement. + + +1.2. Limitations + +The following license limitations apply to your use of the +SDK: + + 1. You may not reverse engineer, decompile or disassemble, + or remove copyright or other proprietary notices from any + portion of the SDK or copies of the SDK. + + 2. Except as expressly provided in this Agreement, you may + not copy, sell, rent, sublicense, transfer, distribute, + modify, or create derivative works of any portion of the + SDK. For clarity, you may not distribute or sublicense the + SDK as a stand-alone product. + + 3. Unless you have an agreement with NVIDIA for this + purpose, you may not indicate that an application created + with the SDK is sponsored or endorsed by NVIDIA. + + 4. You may not bypass, disable, or circumvent any + encryption, security, digital rights management or + authentication mechanism in the SDK. + + 5. You may not use the SDK in any manner that would cause it + to become subject to an open source software license. As + examples, licenses that require as a condition of use, + modification, and/or distribution that the SDK be: + + a. Disclosed or distributed in source code form; + + b. Licensed for the purpose of making derivative works; + or + + c. Redistributable at no charge. + + 6. Unless you have an agreement with NVIDIA for this + purpose, you may not use the SDK with any system or + application where the use or failure of the system or + application can reasonably be expected to threaten or + result in personal injury, death, or catastrophic loss. + Examples include use in avionics, navigation, military, + medical, life support or other life critical applications. + NVIDIA does not design, test or manufacture the SDK for + these critical uses and NVIDIA shall not be liable to you + or any third party, in whole or in part, for any claims or + damages arising from such uses. + + 7. You agree to defend, indemnify and hold harmless NVIDIA + and its affiliates, and their respective employees, + contractors, agents, officers and directors, from and + against any and all claims, damages, obligations, losses, + liabilities, costs or debt, fines, restitutions and + expenses (including but not limited to attorney’s fees + and costs incident to establishing the right of + indemnification) arising out of or related to your use of + the SDK outside of the scope of this Agreement, or not in + compliance with its terms. + + +1.3. Ownership + + 1. NVIDIA or its licensors hold all rights, title and + interest in and to the SDK and its modifications and + derivative works, including their respective intellectual + property rights, subject to your rights described in this + section. This SDK may include software and materials from + NVIDIA’s licensors, and these licensors are intended + third party beneficiaries that may enforce this Agreement + with respect to their intellectual property rights. + + 2. You hold all rights, title and interest in and to your + applications and your derivative works of the sample + source code delivered in the SDK, including their + respective intellectual property rights, subject to + NVIDIA’s rights described in this section. + + 3. You may, but don’t have to, provide to NVIDIA + suggestions, feature requests or other feedback regarding + the SDK, including possible enhancements or modifications + to the SDK. For any feedback that you voluntarily provide, + you hereby grant NVIDIA and its affiliates a perpetual, + non-exclusive, worldwide, irrevocable license to use, + reproduce, modify, license, sublicense (through multiple + tiers of sublicensees), and distribute (through multiple + tiers of distributors) it without the payment of any + royalties or fees to you. NVIDIA will use feedback at its + choice. NVIDIA is constantly looking for ways to improve + its products, so you may send feedback to NVIDIA through + the developer portal at https://developer.nvidia.com. + + +1.4. No Warranties + +THE SDK IS PROVIDED BY NVIDIA “AS IS” AND “WITH ALL +FAULTS.” TO THE MAXIMUM EXTENT PERMITTED BY LAW, NVIDIA AND +ITS AFFILIATES EXPRESSLY DISCLAIM ALL WARRANTIES OF ANY KIND +OR NATURE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, +BUT NOT LIMITED TO, ANY WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT, OR THE +ABSENCE OF ANY DEFECTS THEREIN, WHETHER LATENT OR PATENT. NO +WARRANTY IS MADE ON THE BASIS OF TRADE USAGE, COURSE OF +DEALING OR COURSE OF TRADE. + + +1.5. Limitation of Liability + +TO THE MAXIMUM EXTENT PERMITTED BY LAW, NVIDIA AND ITS +AFFILIATES SHALL NOT BE LIABLE FOR ANY SPECIAL, INCIDENTAL, +PUNITIVE OR CONSEQUENTIAL DAMAGES, OR ANY LOST PROFITS, LOSS +OF USE, LOSS OF DATA OR LOSS OF GOODWILL, OR THE COSTS OF +PROCURING SUBSTITUTE PRODUCTS, ARISING OUT OF OR IN CONNECTION +WITH THIS AGREEMENT OR THE USE OR PERFORMANCE OF THE SDK, +WHETHER SUCH LIABILITY ARISES FROM ANY CLAIM BASED UPON BREACH +OF CONTRACT, BREACH OF WARRANTY, TORT (INCLUDING NEGLIGENCE), +PRODUCT LIABILITY OR ANY OTHER CAUSE OF ACTION OR THEORY OF +LIABILITY. IN NO EVENT WILL NVIDIA’S AND ITS AFFILIATES +TOTAL CUMULATIVE LIABILITY UNDER OR ARISING OUT OF THIS +AGREEMENT EXCEED US$10.00. THE NATURE OF THE LIABILITY OR THE +NUMBER OF CLAIMS OR SUITS SHALL NOT ENLARGE OR EXTEND THIS +LIMIT. + +These exclusions and limitations of liability shall apply +regardless if NVIDIA or its affiliates have been advised of +the possibility of such damages, and regardless of whether a +remedy fails its essential purpose. These exclusions and +limitations of liability form an essential basis of the +bargain between the parties, and, absent any of these +exclusions or limitations of liability, the provisions of this +Agreement, including, without limitation, the economic terms, +would be substantially different. + + +1.6. Termination + + 1. This Agreement will continue to apply until terminated by + either you or NVIDIA as described below. + + 2. If you want to terminate this Agreement, you may do so by + stopping to use the SDK. + + 3. NVIDIA may, at any time, terminate this Agreement if: + + a. (i) you fail to comply with any term of this + Agreement and the non-compliance is not fixed within + thirty (30) days following notice from NVIDIA (or + immediately if you violate NVIDIA’s intellectual + property rights); + + b. (ii) you commence or participate in any legal + proceeding against NVIDIA with respect to the SDK; or + + c. (iii) NVIDIA decides to no longer provide the SDK in + a country or, in NVIDIA’s sole discretion, the + continued use of it is no longer commercially viable. + + 4. Upon any termination of this Agreement, you agree to + promptly discontinue use of the SDK and destroy all copies + in your possession or control. Your prior distributions in + accordance with this Agreement are not affected by the + termination of this Agreement. Upon written request, you + will certify in writing that you have complied with your + commitments under this section. Upon any termination of + this Agreement all provisions survive except for the + license grant provisions. + + +1.7. General + +If you wish to assign this Agreement or your rights and +obligations, including by merger, consolidation, dissolution +or operation of law, contact NVIDIA to ask for permission. Any +attempted assignment not approved by NVIDIA in writing shall +be void and of no effect. NVIDIA may assign, delegate or +transfer this Agreement and its rights and obligations, and if +to a non-affiliate you will be notified. + +You agree to cooperate with NVIDIA and provide reasonably +requested information to verify your compliance with this +Agreement. + +This Agreement will be governed in all respects by the laws of +the United States and of the State of Delaware as those laws +are applied to contracts entered into and performed entirely +within Delaware by Delaware residents, without regard to the +conflicts of laws principles. The United Nations Convention on +Contracts for the International Sale of Goods is specifically +disclaimed. You agree to all terms of this Agreement in the +English language. + +The state or federal courts residing in Santa Clara County, +California shall have exclusive jurisdiction over any dispute +or claim arising out of this Agreement. Notwithstanding this, +you agree that NVIDIA shall still be allowed to apply for +injunctive remedies or an equivalent type of urgent legal +relief in any jurisdiction. + +If any court of competent jurisdiction determines that any +provision of this Agreement is illegal, invalid or +unenforceable, such provision will be construed as limited to +the extent necessary to be consistent with and fully +enforceable under the law and the remaining provisions will +remain in full force and effect. Unless otherwise specified, +remedies are cumulative. + +Each party acknowledges and agrees that the other is an +independent contractor in the performance of this Agreement. + +The SDK has been developed entirely at private expense and is +“commercial items” consisting of “commercial computer +software” and “commercial computer software +documentation” provided with RESTRICTED RIGHTS. Use, +duplication or disclosure by the U.S. Government or a U.S. +Government subcontractor is subject to the restrictions in +this Agreement pursuant to DFARS 227.7202-3(a) or as set forth +in subparagraphs (c)(1) and (2) of the Commercial Computer +Software - Restricted Rights clause at FAR 52.227-19, as +applicable. Contractor/manufacturer is NVIDIA, 2788 San Tomas +Expressway, Santa Clara, CA 95051. + +The SDK is subject to United States export laws and +regulations. You agree that you will not ship, transfer or +export the SDK into any country, or use the SDK in any manner, +prohibited by the United States Bureau of Industry and +Security or economic sanctions regulations administered by the +U.S. Department of Treasury’s Office of Foreign Assets +Control (OFAC), or any applicable export laws, restrictions or +regulations. These laws include restrictions on destinations, +end users and end use. By accepting this Agreement, you +confirm that you are not a resident or citizen of any country +currently embargoed by the U.S. and that you are not otherwise +prohibited from receiving the SDK. + +Any notice delivered by NVIDIA to you under this Agreement +will be delivered via mail, email or fax. You agree that any +notices that NVIDIA sends you electronically will satisfy any +legal communication requirements. Please direct your legal +notices or other correspondence to NVIDIA Corporation, 2788 +San Tomas Expressway, Santa Clara, California 95051, United +States of America, Attention: Legal Department. + +This Agreement and any exhibits incorporated into this +Agreement constitute the entire agreement of the parties with +respect to the subject matter of this Agreement and supersede +all prior negotiations or documentation exchanged between the +parties relating to this SDK license. Any additional and/or +conflicting terms on documents issued by you are null, void, +and invalid. Any amendment or waiver under this Agreement +shall be in writing and signed by representatives of both +parties. + + +2. CUDA Toolkit Supplement to Software License Agreement for +NVIDIA Software Development Kits +------------------------------------------------------------ + + +Release date: August 16, 2018 +----------------------------- + +The terms in this supplement govern your use of the NVIDIA +CUDA Toolkit SDK under the terms of your license agreement +(“Agreement”) as modified by this supplement. Capitalized +terms used but not defined below have the meaning assigned to +them in the Agreement. + +This supplement is an exhibit to the Agreement and is +incorporated as an integral part of the Agreement. In the +event of conflict between the terms in this supplement and the +terms in the Agreement, the terms in this supplement govern. + + +2.1. License Scope + +The SDK is licensed for you to develop applications only for +use in systems with NVIDIA GPUs. + + +2.2. Distribution + +The portions of the SDK that are distributable under the +Agreement are listed in Attachment A. + + +2.3. Operating Systems + +Those portions of the SDK designed exclusively for use on the +Linux or FreeBSD operating systems, or other operating systems +derived from the source code to these operating systems, may +be copied and redistributed for use in accordance with this +Agreement, provided that the object code files are not +modified in any way (except for unzipping of compressed +files). + + +2.4. Audio and Video Encoders and Decoders + +You acknowledge and agree that it is your sole responsibility +to obtain any additional third-party licenses required to +make, have made, use, have used, sell, import, and offer for +sale your products or services that include or incorporate any +third-party software and content relating to audio and/or +video encoders and decoders from, including but not limited +to, Microsoft, Thomson, Fraunhofer IIS, Sisvel S.p.A., +MPEG-LA, and Coding Technologies. NVIDIA does not grant to you +under this Agreement any necessary patent or other rights with +respect to any audio and/or video encoders and decoders. + + +2.5. Licensing + +If the distribution terms in this Agreement are not suitable +for your organization, or for any questions regarding this +Agreement, please contact NVIDIA at +nvidia-compute-license-questions@nvidia.com. + + +2.6. Attachment A + +The following portions of the SDK are distributable under the +Agreement: + +Component + +CUDA Runtime + +Windows + +cudart.dll, cudart_static.lib, cudadevrt.lib + +Mac OSX + +libcudart.dylib, libcudart_static.a, libcudadevrt.a + +Linux + +libcudart.so, libcudart_static.a, libcudadevrt.a + +Android + +libcudart.so, libcudart_static.a, libcudadevrt.a + +Component + +CUDA FFT Library + +Windows + +cufft.dll, cufftw.dll, cufft.lib, cufftw.lib + +Mac OSX + +libcufft.dylib, libcufft_static.a, libcufftw.dylib, +libcufftw_static.a + +Linux + +libcufft.so, libcufft_static.a, libcufftw.so, +libcufftw_static.a + +Android + +libcufft.so, libcufft_static.a, libcufftw.so, +libcufftw_static.a + +Component + +CUDA BLAS Library + +Windows + +cublas.dll, cublasLt.dll + +Mac OSX + +libcublas.dylib, libcublasLt.dylib, libcublas_static.a, +libcublasLt_static.a + +Linux + +libcublas.so, libcublasLt.so, libcublas_static.a, +libcublasLt_static.a + +Android + +libcublas.so, libcublasLt.so, libcublas_static.a, +libcublasLt_static.a + +Component + +NVIDIA "Drop-in" BLAS Library + +Windows + +nvblas.dll + +Mac OSX + +libnvblas.dylib + +Linux + +libnvblas.so + +Component + +CUDA Sparse Matrix Library + +Windows + +cusparse.dll, cusparse.lib + +Mac OSX + +libcusparse.dylib, libcusparse_static.a + +Linux + +libcusparse.so, libcusparse_static.a + +Android + +libcusparse.so, libcusparse_static.a + +Component + +CUDA Linear Solver Library + +Windows + +cusolver.dll, cusolver.lib + +Mac OSX + +libcusolver.dylib, libcusolver_static.a + +Linux + +libcusolver.so, libcusolver_static.a + +Android + +libcusolver.so, libcusolver_static.a + +Component + +CUDA Random Number Generation Library + +Windows + +curand.dll, curand.lib + +Mac OSX + +libcurand.dylib, libcurand_static.a + +Linux + +libcurand.so, libcurand_static.a + +Android + +libcurand.so, libcurand_static.a + +Component + +CUDA Accelerated Graph Library + +Component + +NVIDIA Performance Primitives Library + +Windows + +nppc.dll, nppc.lib, nppial.dll, nppial.lib, nppicc.dll, +nppicc.lib, nppicom.dll, nppicom.lib, nppidei.dll, +nppidei.lib, nppif.dll, nppif.lib, nppig.dll, nppig.lib, +nppim.dll, nppim.lib, nppist.dll, nppist.lib, nppisu.dll, +nppisu.lib, nppitc.dll, nppitc.lib, npps.dll, npps.lib + +Mac OSX + +libnppc.dylib, libnppc_static.a, libnppial.dylib, +libnppial_static.a, libnppicc.dylib, libnppicc_static.a, +libnppicom.dylib, libnppicom_static.a, libnppidei.dylib, +libnppidei_static.a, libnppif.dylib, libnppif_static.a, +libnppig.dylib, libnppig_static.a, libnppim.dylib, +libnppisu_static.a, libnppitc.dylib, libnppitc_static.a, +libnpps.dylib, libnpps_static.a + +Linux + +libnppc.so, libnppc_static.a, libnppial.so, +libnppial_static.a, libnppicc.so, libnppicc_static.a, +libnppicom.so, libnppicom_static.a, libnppidei.so, +libnppidei_static.a, libnppif.so, libnppif_static.a +libnppig.so, libnppig_static.a, libnppim.so, +libnppim_static.a, libnppist.so, libnppist_static.a, +libnppisu.so, libnppisu_static.a, libnppitc.so +libnppitc_static.a, libnpps.so, libnpps_static.a + +Android + +libnppc.so, libnppc_static.a, libnppial.so, +libnppial_static.a, libnppicc.so, libnppicc_static.a, +libnppicom.so, libnppicom_static.a, libnppidei.so, +libnppidei_static.a, libnppif.so, libnppif_static.a +libnppig.so, libnppig_static.a, libnppim.so, +libnppim_static.a, libnppist.so, libnppist_static.a, +libnppisu.so, libnppisu_static.a, libnppitc.so +libnppitc_static.a, libnpps.so, libnpps_static.a + +Component + +NVIDIA JPEG Library + +Linux + +libnvjpeg.so, libnvjpeg_static.a + +Component + +Internal common library required for statically linking to +cuBLAS, cuSPARSE, cuFFT, cuRAND, nvJPEG and NPP + +Mac OSX + +libculibos.a + +Linux + +libculibos.a + +Component + +NVIDIA Runtime Compilation Library and Header + +All + +nvrtc.h + +Windows + +nvrtc.dll, nvrtc-builtins.dll + +Mac OSX + +libnvrtc.dylib, libnvrtc-builtins.dylib + +Linux + +libnvrtc.so, libnvrtc-builtins.so + +Component + +NVIDIA Optimizing Compiler Library + +Windows + +nvvm.dll + +Mac OSX + +libnvvm.dylib + +Linux + +libnvvm.so + +Component + +NVIDIA Common Device Math Functions Library + +Windows + +libdevice.10.bc + +Mac OSX + +libdevice.10.bc + +Linux + +libdevice.10.bc + +Component + +CUDA Occupancy Calculation Header Library + +All + +cuda_occupancy.h + +Component + +CUDA Half Precision Headers + +All + +cuda_fp16.h, cuda_fp16.hpp + +Component + +CUDA Profiling Tools Interface (CUPTI) Library + +Windows + +cupti.dll + +Mac OSX + +libcupti.dylib + +Linux + +libcupti.so + +Component + +NVIDIA Tools Extension Library + +Windows + +nvToolsExt.dll, nvToolsExt.lib + +Mac OSX + +libnvToolsExt.dylib + +Linux + +libnvToolsExt.so + +Component + +NVIDIA CUDA Driver Libraries + +Linux + +libcuda.so, libnvidia-fatbinaryloader.so, +libnvidia-ptxjitcompiler.so + +The NVIDIA CUDA Driver Libraries are only distributable in +applications that meet this criteria: + + 1. The application was developed starting from a NVIDIA CUDA + container obtained from Docker Hub or the NVIDIA GPU + Cloud, and + + 2. The resulting application is packaged as a Docker + container and distributed to users on Docker Hub or the + NVIDIA GPU Cloud only. + + +2.7. Attachment B + + +Additional Licensing Obligations + +The following third party components included in the SOFTWARE +are licensed to Licensee pursuant to the following terms and +conditions: + + 1. Licensee's use of the GDB third party component is + subject to the terms and conditions of GNU GPL v3: + + This product includes copyrighted third-party software licensed + under the terms of the GNU General Public License v3 ("GPL v3"). + All third-party software packages are copyright by their respective + authors. GPL v3 terms and conditions are hereby incorporated into + the Agreement by this reference: http://www.gnu.org/licenses/gpl.txt + + Consistent with these licensing requirements, the software + listed below is provided under the terms of the specified + open source software licenses. To obtain source code for + software provided under licenses that require + redistribution of source code, including the GNU General + Public License (GPL) and GNU Lesser General Public License + (LGPL), contact oss-requests@nvidia.com. This offer is + valid for a period of three (3) years from the date of the + distribution of this product by NVIDIA CORPORATION. + + Component License + CUDA-GDB GPL v3 + + 2. Licensee represents and warrants that any and all third + party licensing and/or royalty payment obligations in + connection with Licensee's use of the H.264 video codecs + are solely the responsibility of Licensee. + + 3. Licensee's use of the Thrust library is subject to the + terms and conditions of the Apache License Version 2.0. + All third-party software packages are copyright by their + respective authors. Apache License Version 2.0 terms and + conditions are hereby incorporated into the Agreement by + this reference. + http://www.apache.org/licenses/LICENSE-2.0.html + + In addition, Licensee acknowledges the following notice: + Thrust includes source code from the Boost Iterator, + Tuple, System, and Random Number libraries. + + Boost Software License - Version 1.0 - August 17th, 2003 + . . . . + + Permission is hereby granted, free of charge, to any person or + organization obtaining a copy of the software and accompanying + documentation covered by this license (the "Software") to use, + reproduce, display, distribute, execute, and transmit the Software, + and to prepare derivative works of the Software, and to permit + third-parties to whom the Software is furnished to do so, all + subject to the following: + + The copyright notices in the Software and this entire statement, + including the above license grant, this restriction and the following + disclaimer, must be included in all copies of the Software, in whole + or in part, and all derivative works of the Software, unless such + copies or derivative works are solely in the form of machine-executable + object code generated by a source language processor. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND + NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR + OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + 4. Licensee's use of the LLVM third party component is + subject to the following terms and conditions: + + ====================================================== + LLVM Release License + ====================================================== + University of Illinois/NCSA + Open Source License + + Copyright (c) 2003-2010 University of Illinois at Urbana-Champaign. + All rights reserved. + + Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to + deal with the Software without restriction, including without limitation the + rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + sell copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at Urbana- + Champaign, nor the names of its contributors may be used to endorse or + promote products derived from this Software without specific prior + written permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS WITH THE SOFTWARE. + + 5. Licensee's use (e.g. nvprof) of the PCRE third party + component is subject to the following terms and + conditions: + + ------------ + PCRE LICENCE + ------------ + PCRE is a library of functions to support regular expressions whose syntax + and semantics are as close as possible to those of the Perl 5 language. + Release 8 of PCRE is distributed under the terms of the "BSD" licence, as + specified below. The documentation for PCRE, supplied in the "doc" + directory, is distributed under the same terms as the software itself. The + basic library functions are written in C and are freestanding. Also + included in the distribution is a set of C++ wrapper functions, and a just- + in-time compiler that can be used to optimize pattern matching. These are + both optional features that can be omitted when the library is built. + + THE BASIC LIBRARY FUNCTIONS + --------------------------- + Written by: Philip Hazel + Email local part: ph10 + Email domain: cam.ac.uk + University of Cambridge Computing Service, + Cambridge, England. + Copyright (c) 1997-2012 University of Cambridge + All rights reserved. + + PCRE JUST-IN-TIME COMPILATION SUPPORT + ------------------------------------- + Written by: Zoltan Herczeg + Email local part: hzmester + Emain domain: freemail.hu + Copyright(c) 2010-2012 Zoltan Herczeg + All rights reserved. + + STACK-LESS JUST-IN-TIME COMPILER + -------------------------------- + Written by: Zoltan Herczeg + Email local part: hzmester + Emain domain: freemail.hu + Copyright(c) 2009-2012 Zoltan Herczeg + All rights reserved. + + THE C++ WRAPPER FUNCTIONS + ------------------------- + Contributed by: Google Inc. + Copyright (c) 2007-2012, Google Inc. + All rights reserved. + + THE "BSD" LICENCE + ----------------- + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the name of Google + Inc. nor the names of their 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. + + 6. Some of the cuBLAS library routines were written by or + derived from code written by Vasily Volkov and are subject + to the Modified Berkeley Software Distribution License as + follows: + + Copyright (c) 2007-2009, Regents of the University of California + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the University of California, Berkeley 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 AUTHOR "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 AUTHOR 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. + + 7. Some of the cuBLAS library routines were written by or + derived from code written by Davide Barbieri and are + subject to the Modified Berkeley Software Distribution + License as follows: + + Copyright (c) 2008-2009 Davide Barbieri @ University of Rome Tor Vergata. + + 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. + * The name of the author may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 AUTHOR 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. + + 8. Some of the cuBLAS library routines were derived from + code developed by the University of Tennessee and are + subject to the Modified Berkeley Software Distribution + License as follows: + + Copyright (c) 2010 The University of Tennessee. + + 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 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. + + 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. + + 9. Some of the cuBLAS library routines were written by or + derived from code written by Jonathan Hogg and are subject + to the Modified Berkeley Software Distribution License as + follows: + + Copyright (c) 2012, The Science and Technology Facilities Council (STFC). + + 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 STFC 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 STFC 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. + + 10. Some of the cuBLAS library routines were written by or + derived from code written by Ahmad M. Abdelfattah, David + Keyes, and Hatem Ltaief, and are subject to the Apache + License, Version 2.0, as follows: + + -- (C) Copyright 2013 King Abdullah University of Science and Technology + Authors: + Ahmad Abdelfattah (ahmad.ahmad@kaust.edu.sa) + David Keyes (david.keyes@kaust.edu.sa) + Hatem Ltaief (hatem.ltaief@kaust.edu.sa) + + 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 King Abdullah University of Science and + Technology 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 + HOLDERS 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 + + 11. Some of the cuSPARSE library routines were written by or + derived from code written by Li-Wen Chang and are subject + to the NCSA Open Source License as follows: + + Copyright (c) 2012, University of Illinois. + + All rights reserved. + + Developed by: IMPACT Group, University of Illinois, http://impact.crhc.illinois.edu + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal with the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimers in the documentation and/or other materials provided + with the distribution. + * Neither the names of IMPACT Group, University of Illinois, nor + the names of its contributors may be used to endorse or promote + products derived from this Software without specific prior + written permission. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR + IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE + SOFTWARE. + + 12. Some of the cuRAND library routines were written by or + derived from code written by Mutsuo Saito and Makoto + Matsumoto and are subject to the following license: + + Copyright (c) 2009, 2010 Mutsuo Saito, Makoto Matsumoto and Hiroshima + University. All rights reserved. + + Copyright (c) 2011 Mutsuo Saito, Makoto Matsumoto, Hiroshima + University and University of Tokyo. 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 Hiroshima University 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. + + 13. Some of the cuRAND library routines were derived from + code developed by D. E. Shaw Research and are subject to + the following license: + + Copyright 2010-2011, D. E. Shaw Research. + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions, and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions, and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of D. E. Shaw Research nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + 14. Some of the Math library routines were written by or + derived from code developed by Norbert Juffa and are + subject to the following license: + + Copyright (c) 2015-2017, Norbert Juffa + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + 15. Licensee's use of the lz4 third party component is + subject to the following terms and conditions: + + Copyright (C) 2011-2013, Yann Collet. + BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + + 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. + + 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. + + 16. The NPP library uses code from the Boost Math Toolkit, + and is subject to the following license: + + Boost Software License - Version 1.0 - August 17th, 2003 + . . . . + + Permission is hereby granted, free of charge, to any person or + organization obtaining a copy of the software and accompanying + documentation covered by this license (the "Software") to use, + reproduce, display, distribute, execute, and transmit the Software, + and to prepare derivative works of the Software, and to permit + third-parties to whom the Software is furnished to do so, all + subject to the following: + + The copyright notices in the Software and this entire statement, + including the above license grant, this restriction and the following + disclaimer, must be included in all copies of the Software, in whole + or in part, and all derivative works of the Software, unless such + copies or derivative works are solely in the form of machine-executable + object code generated by a source language processor. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND + NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR + OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + 17. Portions of the Nsight Eclipse Edition is subject to the + following license: + + The Eclipse Foundation makes available all content in this plug-in + ("Content"). Unless otherwise indicated below, the Content is provided + to you under the terms and conditions of the Eclipse Public License + Version 1.0 ("EPL"). A copy of the EPL is available at http:// + www.eclipse.org/legal/epl-v10.html. For purposes of the EPL, "Program" + will mean the Content. + + If you did not receive this Content directly from the Eclipse + Foundation, the Content is being redistributed by another party + ("Redistributor") and different terms and conditions may apply to your + use of any object code in the Content. Check the Redistributor's + license that was provided with the Content. If no such license exists, + contact the Redistributor. Unless otherwise indicated below, the terms + and conditions of the EPL still apply to any source code in the + Content and such source code may be obtained at http://www.eclipse.org. + + 18. Some of the cuBLAS library routines uses code from + OpenAI, which is subject to the following license: + + License URL + https://github.com/openai/openai-gemm/blob/master/LICENSE + + License Text + The MIT License + + Copyright (c) 2016 OpenAI (http://openai.com), 2016 Google Inc. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + + 19. Licensee's use of the Visual Studio Setup Configuration + Samples is subject to the following license: + + The MIT License (MIT) + Copyright (C) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + 20. Licensee's use of linmath.h header for CPU functions for + GL vector/matrix operations from lunarG is subject to the + Apache License Version 2.0. + + 21. The DX12-CUDA sample uses the d3dx12.h header, which is + subject to the MIT license . + +----------------- diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.3.3.83.dist-info/METADATA b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.3.3.83.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..82f85353688d5a5d26114a8ee58082974d0a0a6c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.3.3.83.dist-info/METADATA @@ -0,0 +1,46 @@ +Metadata-Version: 2.2 +Name: nvidia-cufft-cu12 +Version: 11.3.3.83 +Summary: CUFFT native runtime libraries +Home-page: https://developer.nvidia.com/cuda-zone +Author: Nvidia CUDA Installer Team +Author-email: compute_installer@nvidia.com +License: NVIDIA Proprietary Software +Keywords: cuda,nvidia,runtime,machine learning,deep learning +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: Other/Proprietary License +Classifier: Natural Language :: English +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX :: Linux +Requires-Python: >=3 +License-File: License.txt +Requires-Dist: nvidia-nvjitlink-cu12 +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +CUFFT native runtime libraries diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.3.3.83.dist-info/RECORD b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.3.3.83.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..e261a10553eca4dd6b64a7c545891d0283709903 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.3.3.83.dist-info/RECORD @@ -0,0 +1,17 @@ +nvidia/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cufft/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cufft/include/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cufft/include/cudalibxt.h,sha256=9GDuRiOzJuO61zRDhIpWpF7XHp8FXSOIlHJNoIMwOZQ,4105 +nvidia/cufft/include/cufft.h,sha256=KX0MfP_vIrghXh0nxaLf1Pxg2giCmX8sJaCkDbhtWoo,13169 +nvidia/cufft/include/cufftXt.h,sha256=R3MUFHMNqMae71HwFKPPcShI1HTJbHJYdrr-cRvqXe8,12945 +nvidia/cufft/include/cufftw.h,sha256=Uzfj1IVMlLQU_G50u84hXYX1K95HLXIwOcjQoAg5pGE,20051 +nvidia/cufft/lib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cufft/lib/libcufft.so.11,sha256=XJEhRkSWFPnXPr0aXLYEJC2muBnZS6W0qZJyoGSfN2E,278925016 +nvidia/cufft/lib/libcufftw.so.11,sha256=D-TbBTPDF-Ie9zqmUp7F-vxu3qgKr8_xA-tY8AUSuOo,2101472 +nvidia_cufft_cu12-11.3.3.83.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +nvidia_cufft_cu12-11.3.3.83.dist-info/License.txt,sha256=rW9YU_ugyg0VnQ9Y1JrkmDDC-Mk_epJki5zpCttMbM0,59262 +nvidia_cufft_cu12-11.3.3.83.dist-info/METADATA,sha256=7RHSJzuY44l9yHroj816BmG4pMllKbk6XSJ5n9SJjeU,1741 +nvidia_cufft_cu12-11.3.3.83.dist-info/RECORD,, +nvidia_cufft_cu12-11.3.3.83.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia_cufft_cu12-11.3.3.83.dist-info/WHEEL,sha256=C-9JuWX7zPIcETbq0g2dQ83ne4_xEDQIPmC-cSMWixI,144 +nvidia_cufft_cu12-11.3.3.83.dist-info/top_level.txt,sha256=fTkAtiFuL16nUrB9ytDDtpytz2t0B4NvYTnRzwAhO14,7 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.3.3.83.dist-info/REQUESTED b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.3.3.83.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.3.3.83.dist-info/top_level.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.3.3.83.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..862f7abf232cdfbb928609856247292e81c9decb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.3.3.83.dist-info/top_level.txt @@ -0,0 +1 @@ +nvidia diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/INSTALLER b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/METADATA b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..3d5b2613e8b60616b55580f66be43c8b237d3f20 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/METADATA @@ -0,0 +1,175 @@ +Metadata-Version: 2.4 +Name: pillow +Version: 12.0.0 +Summary: Python Imaging Library (fork) +Author-email: "Jeffrey A. Clark" +License-Expression: MIT-CMU +Project-URL: Changelog, https://github.com/python-pillow/Pillow/releases +Project-URL: Documentation, https://pillow.readthedocs.io +Project-URL: Funding, https://tidelift.com/subscription/pkg/pypi-pillow?utm_source=pypi-pillow&utm_medium=pypi +Project-URL: Homepage, https://python-pillow.github.io +Project-URL: Mastodon, https://fosstodon.org/@pillow +Project-URL: Release notes, https://pillow.readthedocs.io/en/stable/releasenotes/index.html +Project-URL: Source, https://github.com/python-pillow/Pillow +Keywords: Imaging +Classifier: Development Status :: 6 - Mature +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Multimedia :: Graphics +Classifier: Topic :: Multimedia :: Graphics :: Capture :: Digital Camera +Classifier: Topic :: Multimedia :: Graphics :: Capture :: Screen Capture +Classifier: Topic :: Multimedia :: Graphics :: Graphics Conversion +Classifier: Topic :: Multimedia :: Graphics :: Viewers +Classifier: Typing :: Typed +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +License-File: LICENSE +Provides-Extra: docs +Requires-Dist: furo; extra == "docs" +Requires-Dist: olefile; extra == "docs" +Requires-Dist: sphinx>=8.2; extra == "docs" +Requires-Dist: sphinx-autobuild; extra == "docs" +Requires-Dist: sphinx-copybutton; extra == "docs" +Requires-Dist: sphinx-inline-tabs; extra == "docs" +Requires-Dist: sphinxext-opengraph; extra == "docs" +Provides-Extra: fpx +Requires-Dist: olefile; extra == "fpx" +Provides-Extra: mic +Requires-Dist: olefile; extra == "mic" +Provides-Extra: test-arrow +Requires-Dist: arro3-compute; extra == "test-arrow" +Requires-Dist: arro3-core; extra == "test-arrow" +Requires-Dist: nanoarrow; extra == "test-arrow" +Requires-Dist: pyarrow; extra == "test-arrow" +Provides-Extra: tests +Requires-Dist: check-manifest; extra == "tests" +Requires-Dist: coverage>=7.4.2; extra == "tests" +Requires-Dist: defusedxml; extra == "tests" +Requires-Dist: markdown2; extra == "tests" +Requires-Dist: olefile; extra == "tests" +Requires-Dist: packaging; extra == "tests" +Requires-Dist: pyroma>=5; extra == "tests" +Requires-Dist: pytest; extra == "tests" +Requires-Dist: pytest-cov; extra == "tests" +Requires-Dist: pytest-timeout; extra == "tests" +Requires-Dist: pytest-xdist; extra == "tests" +Requires-Dist: trove-classifiers>=2024.10.12; extra == "tests" +Provides-Extra: xmp +Requires-Dist: defusedxml; extra == "xmp" +Dynamic: license-file + +

+ Pillow logo +

+ +# Pillow + +## Python Imaging Library (Fork) + +Pillow is the friendly PIL fork by [Jeffrey A. Clark and +contributors](https://github.com/python-pillow/Pillow/graphs/contributors). +PIL is the Python Imaging Library by Fredrik Lundh and contributors. +As of 2019, Pillow development is +[supported by Tidelift](https://tidelift.com/subscription/pkg/pypi-pillow?utm_source=pypi-pillow&utm_medium=readme&utm_campaign=enterprise). + + + + + + + + + + + + + + + + + + +
docs + Documentation Status +
tests + GitHub Actions build status (Lint) + GitHub Actions build status (Test Linux and macOS) + GitHub Actions build status (Test Windows) + GitHub Actions build status (Test MinGW) + GitHub Actions build status (Test Docker) + GitHub Actions build status (Wheels) + Code coverage + Fuzzing Status +
package + Zenodo + Tidelift + Newest PyPI version + Number of PyPI downloads + OpenSSF Best Practices +
social + Join the chat at https://gitter.im/python-pillow/Pillow + Follow on https://fosstodon.org/@pillow +
+ +## Overview + +The Python Imaging Library adds image processing capabilities to your Python interpreter. + +This library provides extensive file format support, an efficient internal representation, and fairly powerful image processing capabilities. + +The core image library is designed for fast access to data stored in a few basic pixel formats. It should provide a solid foundation for a general image processing tool. + +## More information + +- [Documentation](https://pillow.readthedocs.io/) + - [Installation](https://pillow.readthedocs.io/en/latest/installation/basic-installation.html) + - [Handbook](https://pillow.readthedocs.io/en/latest/handbook/index.html) +- [Contribute](https://github.com/python-pillow/Pillow/blob/main/.github/CONTRIBUTING.md) + - [Issues](https://github.com/python-pillow/Pillow/issues) + - [Pull requests](https://github.com/python-pillow/Pillow/pulls) +- [Release notes](https://pillow.readthedocs.io/en/stable/releasenotes/index.html) +- [Changelog](https://github.com/python-pillow/Pillow/releases) + - [Pre-fork](https://github.com/python-pillow/Pillow/blob/main/CHANGES.rst#pre-fork) + +## Report a vulnerability + +To report a security vulnerability, please follow the procedure described in the [Tidelift security policy](https://tidelift.com/docs/security). diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/RECORD b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..ada4f66a9475fec4e7ba4a2462bed2ede7c2d399 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/RECORD @@ -0,0 +1,140 @@ +PIL/AvifImagePlugin.py,sha256=5IiDMvMZQXLnS3t25XJjlwgNWmeVSNaGfReWAp-V5lo,8994 +PIL/BdfFontFile.py,sha256=PhlZfIRmEfmorbhZZeSM5eebGo1Ei7fL-lR9XlfTZZA,3285 +PIL/BlpImagePlugin.py,sha256=Ub4vVKBEniiNBEgNizxScEpO1VKbC1w6iecWUU7T-Vs,16533 +PIL/BmpImagePlugin.py,sha256=-SNdj2godmaKYAc08dEng6z3mRPbYYHezjveIR5e-tU,19855 +PIL/BufrStubImagePlugin.py,sha256=JSqDhkPNPnFw0Qcz-gQJl-D_iSCFdtcLvPynshKJ4WM,1730 +PIL/ContainerIO.py,sha256=wkBqL2GDAb5fh3wrtfTGUfqioJipCl-lg2GxbjQrTZw,4604 +PIL/CurImagePlugin.py,sha256=-WEsgwQbA9rQzXB0HG0LK1V_qbuwHosPZ0T2IjfN8r0,1791 +PIL/DcxImagePlugin.py,sha256=DhqsmW7MjmnUSTGZ-Skv9hz1XeX3XoQQoAl9GWLAEEY,2145 +PIL/DdsImagePlugin.py,sha256=fjdfZK_eQtUp_-bjoRmt-5wgOT5GTmvg6aI-itch4mo,18906 +PIL/EpsImagePlugin.py,sha256=Q91Of8yr6VY12picGSU6k6HvgU9FgnQJvWrJQryiLnU,16552 +PIL/ExifTags.py,sha256=zW6kVikCosiyoCo7J7R62evD3hoxjKPchnVh8po7CZc,9931 +PIL/FitsImagePlugin.py,sha256=-oDJnAH113CK5qPvwz9lL81fkV1gla_tNfqLcq8zKgo,4644 +PIL/FliImagePlugin.py,sha256=4zxH8IXBX9DGi6dJRM6Y5NMdbA1d99x696mcGZHxHzI,4929 +PIL/FontFile.py,sha256=St7MxO5Q-oakCLWn3ZrgrtaT3wSsmAarxm8AU-G8Moc,3577 +PIL/FpxImagePlugin.py,sha256=aXfg0YdvNeJhxqh-f-f22D1NobQ8tSVCj-tpLE2PKfE,7293 +PIL/FtexImagePlugin.py,sha256=v2I5YkdfNA3iW35JzKnWry9v6Rgvr0oezGVOuArREac,3535 +PIL/GbrImagePlugin.py,sha256=ADLgy4hlBcC_3Rr2HsnIuXPoUvof1ddkhbEo5Yw8OMQ,2979 +PIL/GdImageFile.py,sha256=LP4Uxv3Y2ivGZIyOVuGJarDDVS7zK6F1Q6SNl4wyGuQ,2788 +PIL/GifImagePlugin.py,sha256=VNTEgDJRP6OIze8JVt0EXY1gMv3Xx90oECxawggCFAE,42213 +PIL/GimpGradientFile.py,sha256=gqqUkDbKVFCtBxt5VAhPS0HtLZDYFI6KWEaUhhTNNE8,3982 +PIL/GimpPaletteFile.py,sha256=hIHQ9LJ5ri0hy1e_vZYeD-n67UWdhEDlKc4vDxgaUdg,1860 +PIL/GribStubImagePlugin.py,sha256=I-_ZlKsSKANo7adUTnIx7pTUhQt-0B60DacLDOVm_3E,1759 +PIL/Hdf5StubImagePlugin.py,sha256=OuEQijGqVwTTSG4dB2vAyQzmN-NYT22tiuZHFH0Q0Sw,1741 +PIL/IcnsImagePlugin.py,sha256=dr_p68k2ECoONrw3Dqw3ISig39uXo39YY3nTfshUNHw,12405 +PIL/IcoImagePlugin.py,sha256=QCo29Toh08UX8vEcdCAaIeuidSolbPiZlCnQ4rUu2SQ,12491 +PIL/ImImagePlugin.py,sha256=wo5OL2PAcQW2MwRkJnS-N16toZzXWL95jx9FBM7l9ok,11567 +PIL/Image.py,sha256=2naP8UMkmSyU64EFc5crz4t02nV4f8ptFKfZdvbtBHQ,148085 +PIL/ImageChops.py,sha256=GEjlymcoDtA5OOeIxQVIX96BD-s6AXhb7TmSLYn2tUg,7946 +PIL/ImageCms.py,sha256=IuCm3gXKpb5Eu1kn-TB8cD9XJLZEa8fpkEjzVqAIKNk,40676 +PIL/ImageColor.py,sha256=IGA9C2umeED_EzS2Cvj6KsU0VutC9RstWIYPe8uDsVk,9441 +PIL/ImageDraw.py,sha256=FMn0AK_gxxJBYB8afOGF2FUP2KJPFvUf3UZp_KrJz7A,36287 +PIL/ImageDraw2.py,sha256=pdVMW7bVw3KwhXvRZh28Md4y-2xFfuo5fHcDnaYqVK4,7227 +PIL/ImageEnhance.py,sha256=4Elhz_lyyxLmx0GkSHrwOAmNJ2TkqVQPHejzGihZUMI,3627 +PIL/ImageFile.py,sha256=m6Se6q-5zsmnE7Bezp13q-H5F2yt5d4tO7YD06FGHx4,29600 +PIL/ImageFilter.py,sha256=MO1MBrbXDiX2IAGESdGm_0087bwmSZ_14ecAj28ojCY,18729 +PIL/ImageFont.py,sha256=2PGC3YI127GKrXYg4zP7_Tul2KCQ3c4ajU8LONVO9bc,63101 +PIL/ImageGrab.py,sha256=I9PHpsQf2VyNX4T8QL-8awFNotyAzB1mGxTt_I5FbTE,6471 +PIL/ImageMath.py,sha256=RQl6cRXGuszba4KwtbIudin_8U65shpWrajr9gTn1rw,10369 +PIL/ImageMode.py,sha256=aaZVHAiCEanOA2K1jN3DlW3NPKa8Dm5nIXTXErzyFms,2395 +PIL/ImageMorph.py,sha256=dobO2v2w7c8SjH7stFc3TP6HtU9O7JAWQz5Nu6mBxYg,8562 +PIL/ImageOps.py,sha256=bIcQFK_MtovfNSYTcOesp4So9OgsGrwt3cGsB7xlGRM,25567 +PIL/ImagePalette.py,sha256=M5tYUgadWR7mxUEByyVl7IV9QFFzAGiKKmAhCZtdG0w,9009 +PIL/ImagePath.py,sha256=5yUG5XCUil1KKTTA_8PgGhcmg-mnue-GK0FwTBlhjw4,371 +PIL/ImageQt.py,sha256=PTt5TPyngWL-Vuvx_bwnH17EOBe3tE7l4huVmvGQP5Y,6684 +PIL/ImageSequence.py,sha256=Mphgkr79scmYBgmi9ZguhDfVwHvpLSX5uZVHDZlrn0I,2253 +PIL/ImageShow.py,sha256=Ju0_Db2B4_n3yKJV9sDsF7_HAgciEdXlq6I1Eiw1YTo,10106 +PIL/ImageStat.py,sha256=FVTiYWGCciPW1QD61b7DYZlcDqR0dS6hsLjq-gcKcG4,5495 +PIL/ImageText.py,sha256=rkdTrW6pQCquXFOTu_0OoBfvCYiC9zQG__8JjGwnPYE,12103 +PIL/ImageTk.py,sha256=b5SntckGXs0ECsI2MmdJg3CSX6AtELsWh0Ohxu41u_k,8132 +PIL/ImageTransform.py,sha256=-qek7P3lzLddcXt9cWt5w_L11JGp2yY3AJtOfmJAkDc,3916 +PIL/ImageWin.py,sha256=LT05w8_vTfRrC3n9S9pM0TNbXrzZLEJHlCJil7Xv80k,8085 +PIL/ImtImagePlugin.py,sha256=SL5IrsHcblltxtX4v_HVFhYnR6haJ0AOd2NHhZKMImY,2665 +PIL/IptcImagePlugin.py,sha256=cOFy4epsqpMOWNgQ3Gj_dOrt2TPjbO0gjCvp_f1mUxk,6444 +PIL/Jpeg2KImagePlugin.py,sha256=IabyXVrNchWV9oOUU79eNjGSudq5tlvnihFimZH4VAA,13932 +PIL/JpegImagePlugin.py,sha256=ZMvTMZTxi2UHu87NXauQmhLC3tWEMxa2CgUhYcFq7yw,31318 +PIL/JpegPresets.py,sha256=lnqWHo4DLIHIulcdHp0NJ7CWexHt8T3w51kIKlLfkIA,12379 +PIL/McIdasImagePlugin.py,sha256=baOIkD-CIIeCgBFTf8kos928PKBuCUqYYa38u3WES_8,1877 +PIL/MicImagePlugin.py,sha256=aoIwkWVyr_X-dPvB6ldZOJF3a9kd_OeuEW3say5Y0QM,2564 +PIL/MpegImagePlugin.py,sha256=g7BZd93kWpFi41SG_wKFoi0yEPsioI4kj45b2F-3Vrw,2010 +PIL/MpoImagePlugin.py,sha256=S45qt7OcY7rBjYlwEk0nUmEj5IOu5z8KVLo066V1RBE,6722 +PIL/MspImagePlugin.py,sha256=oxk_MLUDvzJ4JDuOZCHkmqOPXniG42PHOyNGwe60slY,5892 +PIL/PSDraw.py,sha256=KMBGj3vXaFpblaIcA9KjFFTpdal41AQggY-UgzqoMkQ,6918 +PIL/PaletteFile.py,sha256=suDdAL6VMljXw4oEn1vhTt4DQ4vbpIHGd3A4oxOgE6s,1216 +PIL/PalmImagePlugin.py,sha256=WJ1b8I1xTSAXYDJhIpkVFCLu2LlpbiBD5d1Hr-m2l08,8748 +PIL/PcdImagePlugin.py,sha256=-gnMUqQH0R-aljsd3nZS9eBI1j75ijWD_HZfadE3RsQ,1774 +PIL/PcfFontFile.py,sha256=DqcyydQgP2vtiPFzj57KYHLuF2v-0oMTB-VkgYYHKhE,7223 +PIL/PcxImagePlugin.py,sha256=1xAq6CdH34cOsOgTPi4Wu2SKQCdQiTLVyqaMkYQZUP4,6245 +PIL/PdfImagePlugin.py,sha256=6lZLoQMVbAE-x1ESrv6PgGSyM9Ueck7e6E6ps-YQ-vI,9321 +PIL/PdfParser.py,sha256=Hr3ImLDSIKwUF6OrQ1GjlAnGi6ZpGVLWhGfKhqQ_DRM,37996 +PIL/PixarImagePlugin.py,sha256=l_4GwBd0mATnIXYJbwmmODU2vP7wewLu6BRviHCB2EI,1758 +PIL/PngImagePlugin.py,sha256=jGtbaGMrt9x0i9c500Nh1ofQ4M6w23Wlu67oTuwYEIA,51144 +PIL/PpmImagePlugin.py,sha256=vb5SP0IjQPzDRDE8jSPtcJv9K3Rh1LczAlt0Pg26i90,12391 +PIL/PsdImagePlugin.py,sha256=ImnNRG4VANs2GATXVEB5Q-yy1Jskc6XRVRtZYi2fALg,8685 +PIL/QoiImagePlugin.py,sha256=RPO63QsgHAsyPpcxh7ymeMYlnjVu5gT5ELolkvJt0vc,8572 +PIL/SgiImagePlugin.py,sha256=3Ql89s8vycNWjcxJwMw28iksV9Yj2xWoKBQ6c5DHXBg,6389 +PIL/SpiderImagePlugin.py,sha256=Bsg6pfZMctas1xYx__oL-ZZseUReZdnLy5a-aKEJhpE,10249 +PIL/SunImagePlugin.py,sha256=Hdxkhk0pxpBGxYhPJfCDLwsYcO1KjxjtplNMFYibIvk,4589 +PIL/TarIO.py,sha256=BqYUChCBb9F7Sh-uZ86iz1Dtoy2D0obNwGm65z1rdc0,1442 +PIL/TgaImagePlugin.py,sha256=2vDsFTcBUBHw1V80wpVv4tgpLDbPr6yVHi6Fvaqf0HY,6980 +PIL/TiffImagePlugin.py,sha256=cIQ48x3zmm5PFSG01wqweC8DJUhJxrX1R62c8Edw1Jg,85002 +PIL/TiffTags.py,sha256=cMmOVPxiq8Yt99J9DEQz4tXu8IZvsJFCSL3zJDGw3fM,17251 +PIL/WalImageFile.py,sha256=4o52MngMxr9dlMmCyIXu-11-QpEN6-MRcJnEfyjdc4M,5687 +PIL/WebPImagePlugin.py,sha256=h8hosK6SWJ5tAuSFFCboKTJ_dQCFthCGT9ooYq6TVCk,10054 +PIL/WmfImagePlugin.py,sha256=y1z3RPYozRQY8AOEs-iark--cv835yF9xENm7b0GNXo,5244 +PIL/XVThumbImagePlugin.py,sha256=cJSapkBasFt11O6XYXxqcyA-njxA5BD3wHhNj6VC7Fk,2115 +PIL/XbmImagePlugin.py,sha256=Fd6GVDEo73nyFICA3Z3w4LjkwoZWvhHB6rKCm5yVrho,2669 +PIL/XpmImagePlugin.py,sha256=jtUKavJCYwIAsJaJwSx8vJsx1oTbCywfDxePENmA93w,4400 +PIL/__init__.py,sha256=Q4KOEpR7S_Xsj30fvOsvR94xEpX4KUsVeUwaVP1fU80,2031 +PIL/__main__.py,sha256=Lpj4vef8mI7jA1sRCUAoVYaeePD_Uc898xF5c7XLx1A,133 +PIL/_avif.cpython-310-x86_64-linux-gnu.so,sha256=hPbJfk_-phRx-TB1I918qbJg6aI7_m-lV_pp5zkwuQA,87889 +PIL/_avif.pyi,sha256=3fBxcSppJr6EOEcUojvflG3Eegg7lv2Qp0dNQQILrP4,63 +PIL/_binary.py,sha256=pcM6AL04GxgmGeLfcH1V1BZHENwIrQH0uxhJ7r0HIL0,2550 +PIL/_deprecate.py,sha256=2t747uUfRLL0rYxIEvykqyDaB_1b0eDSnwgpTh5O5fI,1970 +PIL/_imaging.cpython-310-x86_64-linux-gnu.so,sha256=HU0KrYAaFpYYHz4D6fDK3WEX0YXfefCp1MZpCjaVZDk,3320681 +PIL/_imaging.pyi,sha256=StMbXUZS32AegATP1sUHfs5P05A3TD_BiQKsDHQBW40,868 +PIL/_imagingcms.cpython-310-x86_64-linux-gnu.so,sha256=P8zeod3ZI31LJXSX9QPh1N_P0OZHzQV_ynbLbejNcUc,157841 +PIL/_imagingcms.pyi,sha256=ZZ8iIoi6EHWLvgAdfm1hPD5CQmxi75LiJl5x8yGxYoU,4433 +PIL/_imagingft.cpython-310-x86_64-linux-gnu.so,sha256=RYNDE8kjaeyAKOnzgY8_894-ogteJM2Z2OEZu16Vrq8,314777 +PIL/_imagingft.pyi,sha256=cYySzvcKBCiHPBsvttMie9AdfUcEsqZR-3256YQtz2Q,1833 +PIL/_imagingmath.cpython-310-x86_64-linux-gnu.so,sha256=tKr1VDBoDhJz02NT1FfUNcalxbrTjpKFKr97CTAO4Cc,162480 +PIL/_imagingmath.pyi,sha256=3fBxcSppJr6EOEcUojvflG3Eegg7lv2Qp0dNQQILrP4,63 +PIL/_imagingmorph.cpython-310-x86_64-linux-gnu.so,sha256=jIU7JR_UbZj4tonWFHeuyL-mLMg84KptN-G9wo0dSSA,36480 +PIL/_imagingmorph.pyi,sha256=3fBxcSppJr6EOEcUojvflG3Eegg7lv2Qp0dNQQILrP4,63 +PIL/_imagingtk.cpython-310-x86_64-linux-gnu.so,sha256=M01LHJMcp7W9c2_L5ARqfo5asWhxT8UmiisLeXwVovM,45920 +PIL/_imagingtk.pyi,sha256=3fBxcSppJr6EOEcUojvflG3Eegg7lv2Qp0dNQQILrP4,63 +PIL/_tkinter_finder.py,sha256=GIZ4stmFhUosmHKSrdxcjStiocDNfyJn7RBie2SWxU0,538 +PIL/_typing.py,sha256=2z33ZUp9aQnkSqXzNR3Zn7l04d2W-oAj1OiZhiyFF68,919 +PIL/_util.py,sha256=fxhWdrLARyc2PsMgN3m9_U1dY3oUKbV7mkoHcXgoeeA,684 +PIL/_version.py,sha256=OYLJ24lJylQ6NFpzq3LMRSnDyAJmp1pnFQ_c3PMZR44,87 +PIL/_webp.cpython-310-x86_64-linux-gnu.so,sha256=uFrT8o5JP3sCsciW1gH9Jb-LG_hftx78tHk9QzyXSrw,108849 +PIL/_webp.pyi,sha256=3fBxcSppJr6EOEcUojvflG3Eegg7lv2Qp0dNQQILrP4,63 +PIL/features.py,sha256=FPkEhjtBaRSqpkgHNYduwxiFtycu4NjZKwEMWxtemPU,10775 +PIL/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +PIL/report.py,sha256=4JY6-IU7sH1RKuRbOvy1fUt0dAoi79FX4tYJN3p1DT0,100 +pillow-12.0.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +pillow-12.0.0.dist-info/METADATA,sha256=rWIEUr-lPL-ilNfae2bataCGpU7eDOF4vXTjgOvENMg,8808 +pillow-12.0.0.dist-info/RECORD,, +pillow-12.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pillow-12.0.0.dist-info/WHEEL,sha256=Obtqci3x5vy5ZivY2BiOH9GHO8-xQ0d4HFhTOtXMNhw,152 +pillow-12.0.0.dist-info/licenses/LICENSE,sha256=MBeL96_5-NyCr-01CGzTeKkGTnf8tDgEhfOLXaM3cFI,68061 +pillow-12.0.0.dist-info/top_level.txt,sha256=riZqrk-hyZqh5f1Z0Zwii3dKfxEsByhu9cU9IODF-NY,4 +pillow-12.0.0.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +pillow.libs/libXau-154567c4.so.6.0.0,sha256=BUhNJL94y47QMWnxywZyBNgpy3ryHeiCBADSnRFeQyA,22081 +pillow.libs/libavif-01e67780.so.16.3.0,sha256=xCXlA8_rggzsCA_EsWKFzgqPBmT1ihpZCo3iMyvD1P0,5142057 +pillow.libs/libbrotlicommon-c55a5f7a.so.1.1.0,sha256=HaLbMm3YehX759wgF7ZU0kVwhdgX4ukfvQNKytoarw8,144425 +pillow.libs/libbrotlidec-2ced2f3a.so.1.1.0,sha256=BOwekVTiRipkYusnBXmzGGhiPsBwBI6DDWPLkvxAbRE,62337 +pillow.libs/libfreetype-5bb46249.so.6.20.4,sha256=Tg7wTbDEPfL0YvLbadZ40tNwy4fKxjhuxuCsaDHzCrw,1463609 +pillow.libs/libharfbuzz-525aa570.so.0.61210.0,sha256=HyXdr1Fa9eEK7Q3VvhhzDw8DA-kp-BjzV6Ql5oX-lbc,941033 +pillow.libs/libjpeg-a41b0190.so.62.4.0,sha256=nMxHb3xGeNHn_aC68P7_-TP__RdUvJooSl_7JEFa1mU,836273 +pillow.libs/liblcms2-cc10e42f.so.2.0.17,sha256=5JMjEDVKMwxcinhbQl6qhRLaezAiQFYEPSz-KultHe0,519073 +pillow.libs/liblzma-64b7ab39.so.5.8.1,sha256=hN2B2RPEM6wOgvER_g43fNjbNQ_SsrenX2wlAfHW-nA,266369 +pillow.libs/libopenjp2-94e588ba.so.2.5.4,sha256=5ye2mwzPYSo447VzscBGO_ZWXyBgFEPFRY45hlXLIw0,585849 +pillow.libs/libpng16-00127801.so.16.50.0,sha256=KIB4XEQDJkGL2nMIrURzNgiSxMwl87FIyB0em53ffx8,278001 +pillow.libs/libsharpyuv-95d8a097.so.0.1.2,sha256=EtR2hzr_XVKswxcXrVFfDixKeUd1TMu56F0oHwH3Els,46113 +pillow.libs/libtiff-295fd75c.so.6.2.0,sha256=fkRD5oAmt0kNw9iL_CfKz0aqsJ3AgnDyVs1U0CRkEZU,754729 +pillow.libs/libwebp-d8b9687f.so.7.2.0,sha256=k-gbdtoXnzmBItYhvYxdhV11ff08TsQgWSMUUHmMzPs,731209 +pillow.libs/libwebpdemux-747f2b49.so.2.0.17,sha256=jsiJz7rjNfyn9TOqFT2OPydmTYax0iNBCCBQg9st9vw,30217 +pillow.libs/libwebpmux-7f11e5ce.so.3.1.2,sha256=Pes9BQ-MFyCzlQH9n07pWNtt7O0afgVlBsMJ-6kuU_o,58617 +pillow.libs/libxcb-64009ff3.so.1.1.0,sha256=t0N-0WuuesRJgEn9FOENG9HD59FdDl6rHS6tQqg6SdE,251425 +pillow.libs/libzstd-761a17b6.so.1.5.7,sha256=jKEGQObGqZaFbxpkGZX8jzstJVcHhJPh4SShnGgZjB8,1800497 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/REQUESTED b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/WHEEL b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12e67ca29ff180ca4133d9ec4769226edb266ce4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_27_x86_64 +Tag: cp310-cp310-manylinux_2_28_x86_64 + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/licenses/LICENSE b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a5ad83b9b79dbb611fd7f68dce93043625c305be --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/licenses/LICENSE @@ -0,0 +1,1523 @@ +The Python Imaging Library (PIL) is + + Copyright © 1997-2011 by Secret Labs AB + Copyright © 1995-2011 by Fredrik Lundh and contributors + +Pillow is the friendly PIL fork. It is + + Copyright © 2010 by Jeffrey A. Clark and contributors + +Like PIL, Pillow is licensed under the open source MIT-CMU License: + +By obtaining, using, and/or copying this software and/or its associated +documentation, you agree that you have read, understood, and will comply +with the following terms and conditions: + +Permission to use, copy, modify and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appears in all copies, and that +both that copyright notice and this permission notice appear in supporting +documentation, and that the name of Secret Labs AB or the author not be +used in advertising or publicity pertaining to distribution of the software +without specific, written prior permission. + +SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, +INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + + +---- + +AOM + +Copyright (c) 2016, Alliance for Open Media. 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. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + + +---- + +BROTLI + +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +---- + +BZIP2 + + +-------------------------------------------------------------------------- + +This program, "bzip2", the associated library "libbzip2", and all +documentation, are copyright (C) 1996-2019 Julian R Seward. 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. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + +3. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + +4. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. + +Julian Seward, jseward@acm.org +bzip2/libbzip2 version 1.0.8 of 13 July 2019 + +-------------------------------------------------------------------------- + + +---- + +DAV1D + +Copyright © 2018-2019, VideoLAN and dav1d authors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +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. + + +---- + +FREETYPE2 + +The FreeType 2 font engine is copyrighted work and cannot be used +legally without a software license. In order to make this project +usable to a vast majority of developers, we distribute it under two +mutually exclusive open-source licenses. + +This means that *you* must choose *one* of the two licenses described +below, then obey all its terms and conditions when using FreeType 2 in +any of your projects or products. + + - The FreeType License, found in the file `docs/FTL.TXT`, which is + similar to the original BSD license *with* an advertising clause + that forces you to explicitly cite the FreeType project in your + product's documentation. All details are in the license file. + This license is suited to products which don't use the GNU General + Public License. + + Note that this license is compatible to the GNU General Public + License version 3, but not version 2. + + - The GNU General Public License version 2, found in + `docs/GPLv2.TXT` (any later version can be used also), for + programs which already use the GPL. Note that the FTL is + incompatible with GPLv2 due to its advertisement clause. + +The contributed BDF and PCF drivers come with a license similar to +that of the X Window System. It is compatible to the above two +licenses (see files `src/bdf/README` and `src/pcf/README`). The same +holds for the source code files `src/base/fthash.c` and +`include/freetype/internal/fthash.h`; they were part of the BDF driver +in earlier FreeType versions. + +The gzip module uses the zlib license (see `src/gzip/zlib.h`) which +too is compatible to the above two licenses. + +The files `src/autofit/ft-hb.c` and `src/autofit/ft-hb.h` contain code +taken almost verbatim from the HarfBuzz file `hb-ft.cc`, which uses +the 'Old MIT' license, compatible to the above two licenses. + +The MD5 checksum support (only used for debugging in development +builds) is in the public domain. + +-------------------------------------------------------------------------- + + The FreeType Project LICENSE + ---------------------------- + + 2006-Jan-27 + + Copyright 1996-2002, 2006 by + David Turner, Robert Wilhelm, and Werner Lemberg + + + +Introduction +============ + + The FreeType Project is distributed in several archive packages; + some of them may contain, in addition to the FreeType font engine, + various tools and contributions which rely on, or relate to, the + FreeType Project. + + This license applies to all files found in such packages, and + which do not fall under their own explicit license. The license + affects thus the FreeType font engine, the test programs, + documentation and makefiles, at the very least. + + This license was inspired by the BSD, Artistic, and IJG + (Independent JPEG Group) licenses, which all encourage inclusion + and use of free software in commercial and freeware products + alike. As a consequence, its main points are that: + + o We don't promise that this software works. However, we will be + interested in any kind of bug reports. (`as is' distribution) + + o You can use this software for whatever you want, in parts or + full form, without having to pay us. (`royalty-free' usage) + + o You may not pretend that you wrote this software. If you use + it, or only parts of it, in a program, you must acknowledge + somewhere in your documentation that you have used the + FreeType code. (`credits') + + We specifically permit and encourage the inclusion of this + software, with or without modifications, in commercial products. + We disclaim all warranties covering The FreeType Project and + assume no liability related to The FreeType Project. + + + Finally, many people asked us for a preferred form for a + credit/disclaimer to use in compliance with this license. We thus + encourage you to use the following text: + + """ + Portions of this software are copyright © The FreeType + Project (www.freetype.org). All rights reserved. + """ + + Please replace with the value from the FreeType version you + actually use. + + +Legal Terms +=========== + +0. Definitions +-------------- + + Throughout this license, the terms `package', `FreeType Project', + and `FreeType archive' refer to the set of files originally + distributed by the authors (David Turner, Robert Wilhelm, and + Werner Lemberg) as the `FreeType Project', be they named as alpha, + beta or final release. + + `You' refers to the licensee, or person using the project, where + `using' is a generic term including compiling the project's source + code as well as linking it to form a `program' or `executable'. + This program is referred to as `a program using the FreeType + engine'. + + This license applies to all files distributed in the original + FreeType Project, including all source code, binaries and + documentation, unless otherwise stated in the file in its + original, unmodified form as distributed in the original archive. + If you are unsure whether or not a particular file is covered by + this license, you must contact us to verify this. + + The FreeType Project is copyright (C) 1996-2000 by David Turner, + Robert Wilhelm, and Werner Lemberg. All rights reserved except as + specified below. + +1. No Warranty +-------------- + + THE FREETYPE PROJECT IS PROVIDED `AS IS' WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE. IN NO EVENT WILL ANY OF THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY DAMAGES CAUSED BY THE USE OR THE INABILITY TO + USE, OF THE FREETYPE PROJECT. + +2. Redistribution +----------------- + + This license grants a worldwide, royalty-free, perpetual and + irrevocable right and license to use, execute, perform, compile, + display, copy, create derivative works of, distribute and + sublicense the FreeType Project (in both source and object code + forms) and derivative works thereof for any purpose; and to + authorize others to exercise some or all of the rights granted + herein, subject to the following conditions: + + o Redistribution of source code must retain this license file + (`FTL.TXT') unaltered; any additions, deletions or changes to + the original files must be clearly indicated in accompanying + documentation. The copyright notices of the unaltered, + original files must be preserved in all copies of source + files. + + o Redistribution in binary form must provide a disclaimer that + states that the software is based in part of the work of the + FreeType Team, in the distribution documentation. We also + encourage you to put an URL to the FreeType web page in your + documentation, though this isn't mandatory. + + These conditions apply to any software derived from or based on + the FreeType Project, not just the unmodified files. If you use + our work, you must acknowledge us. However, no fee need be paid + to us. + +3. Advertising +-------------- + + Neither the FreeType authors and contributors nor you shall use + the name of the other for commercial, advertising, or promotional + purposes without specific prior written permission. + + We suggest, but do not require, that you use one or more of the + following phrases to refer to this software in your documentation + or advertising materials: `FreeType Project', `FreeType Engine', + `FreeType library', or `FreeType Distribution'. + + As you have not signed this license, you are not required to + accept it. However, as the FreeType Project is copyrighted + material, only this license, or another one contracted with the + authors, grants you the right to use, distribute, and modify it. + Therefore, by using, distributing, or modifying the FreeType + Project, you indicate that you understand and accept all the terms + of this license. + +4. Contacts +----------- + + There are two mailing lists related to FreeType: + + o freetype@nongnu.org + + Discusses general use and applications of FreeType, as well as + future and wanted additions to the library and distribution. + If you are looking for support, start in this list if you + haven't found anything to help you in the documentation. + + o freetype-devel@nongnu.org + + Discusses bugs, as well as engine internals, design issues, + specific licenses, porting, etc. + + Our home page can be found at + + https://www.freetype.org + + +--- end of FTL.TXT --- + +The following license details are part of `src/bdf/README`: + +``` +License +******* + +Copyright (C) 2001-2002 by Francesco Zappa Nardelli + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +*** Portions of the driver (that is, bdflib.c and bdf.h): + +Copyright 2000 Computing Research Labs, New Mexico State University +Copyright 2001-2002, 2011 Francesco Zappa Nardelli + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE COMPUTING RESEARCH LAB OR NEW MEXICO STATE UNIVERSITY BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT +OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR +THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +Credits +******* + +This driver is based on excellent Mark Leisher's bdf library. If you +find something good in this driver you should probably thank him, not +me. +``` + +The following license details are part of `src/pcf/README`: + +``` +License +******* + +Copyright (C) 2000 by Francesco Zappa Nardelli + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +Credits +******* + +Keith Packard wrote the pcf driver found in XFree86. His work is at +the same time the specification and the sample implementation of the +PCF format. Undoubtedly, this driver is inspired from his work. +``` + + +---- + +HARFBUZZ + +HarfBuzz is licensed under the so-called "Old MIT" license. Details follow. +For parts of HarfBuzz that are licensed under different licenses see individual +files names COPYING in subdirectories where applicable. + +Copyright © 2010-2022 Google, Inc. +Copyright © 2015-2020 Ebrahim Byagowi +Copyright © 2019,2020 Facebook, Inc. +Copyright © 2012,2015 Mozilla Foundation +Copyright © 2011 Codethink Limited +Copyright © 2008,2010 Nokia Corporation and/or its subsidiary(-ies) +Copyright © 2009 Keith Stribley +Copyright © 2011 Martin Hosken and SIL International +Copyright © 2007 Chris Wilson +Copyright © 2005,2006,2020,2021,2022,2023 Behdad Esfahbod +Copyright © 2004,2007,2008,2009,2010,2013,2021,2022,2023 Red Hat, Inc. +Copyright © 1998-2005 David Turner and Werner Lemberg +Copyright © 2016 Igalia S.L. +Copyright © 2022 Matthias Clasen +Copyright © 2018,2021 Khaled Hosny +Copyright © 2018,2019,2020 Adobe, Inc +Copyright © 2013-2015 Alexei Podtelezhnikov + +For full copyright notices consult the individual files in the package. + + +Permission is hereby granted, without written agreement and without +license or royalty fees, to use, copy, modify, and distribute this +software and its documentation for any purpose, provided that the +above copyright notice and the following two paragraphs appear in +all copies of this software. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR +DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN +IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGE. + +THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, +BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS +ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO +PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + + +---- + +LCMS2 + +Little CMS +Copyright (c) 1998-2020 Marti Maria Saguer + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +---- + +LIBAVIF + +Copyright 2019 Joe Drago. 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. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------------------ + +Files: src/obu.c + +Copyright © 2018-2019, VideoLAN and dav1d authors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +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. + +------------------------------------------------------------------------------ + +Files: third_party/iccjpeg/* + +In plain English: + +1. We don't promise that this software works. (But if you find any bugs, + please let us know!) +2. You can use this software for whatever you want. You don't have to pay us. +3. You may not pretend that you wrote this software. If you use it in a + program, you must acknowledge somewhere in your documentation that + you've used the IJG code. + +In legalese: + +The authors make NO WARRANTY or representation, either express or implied, +with respect to this software, its quality, accuracy, merchantability, or +fitness for a particular purpose. This software is provided "AS IS", and you, +its user, assume the entire risk as to its quality and accuracy. + +This software is copyright (C) 1991-2013, Thomas G. Lane, Guido Vollbeding. +All Rights Reserved except as specified below. + +Permission is hereby granted to use, copy, modify, and distribute this +software (or portions thereof) for any purpose, without fee, subject to these +conditions: +(1) If any part of the source code for this software is distributed, then this +README file must be included, with this copyright and no-warranty notice +unaltered; and any additions, deletions, or changes to the original files +must be clearly indicated in accompanying documentation. +(2) If only executable code is distributed, then the accompanying +documentation must state that "this software is based in part on the work of +the Independent JPEG Group". +(3) Permission for use of this software is granted only if the user accepts +full responsibility for any undesirable consequences; the authors accept +NO LIABILITY for damages of any kind. + +These conditions apply to any software derived from or based on the IJG code, +not just to the unmodified library. If you use our work, you ought to +acknowledge us. + +Permission is NOT granted for the use of any IJG author's name or company name +in advertising or publicity relating to this software or products derived from +it. This software may be referred to only as "the Independent JPEG Group's +software". + +We specifically permit and encourage the use of this software as the basis of +commercial products, provided that all warranty or liability claims are +assumed by the product vendor. + + +The Unix configuration script "configure" was produced with GNU Autoconf. +It is copyright by the Free Software Foundation but is freely distributable. +The same holds for its supporting scripts (config.guess, config.sub, +ltmain.sh). Another support script, install-sh, is copyright by X Consortium +but is also freely distributable. + +The IJG distribution formerly included code to read and write GIF files. +To avoid entanglement with the Unisys LZW patent, GIF reading support has +been removed altogether, and the GIF writer has been simplified to produce +"uncompressed GIFs". This technique does not use the LZW algorithm; the +resulting GIF files are larger than usual, but are readable by all standard +GIF decoders. + +We are required to state that + "The Graphics Interchange Format(c) is the Copyright property of + CompuServe Incorporated. GIF(sm) is a Service Mark property of + CompuServe Incorporated." + +------------------------------------------------------------------------------ + +Files: contrib/gdk-pixbuf/* + +Copyright 2020 Emmanuel Gil Peyrot. 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. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------------------ + +Files: android_jni/gradlew* + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +------------------------------------------------------------------------------ + +Files: third_party/libyuv/* + +Copyright 2011 The LibYuv Project Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * 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 Google nor the names of its contributors may + be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +---- + +LIBJPEG + +1. We don't promise that this software works. (But if you find any bugs, + please let us know!) +2. You can use this software for whatever you want. You don't have to pay us. +3. You may not pretend that you wrote this software. If you use it in a + program, you must acknowledge somewhere in your documentation that + you've used the IJG code. + +In legalese: + +The authors make NO WARRANTY or representation, either express or implied, +with respect to this software, its quality, accuracy, merchantability, or +fitness for a particular purpose. This software is provided "AS IS", and you, +its user, assume the entire risk as to its quality and accuracy. + +This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding. +All Rights Reserved except as specified below. + +Permission is hereby granted to use, copy, modify, and distribute this +software (or portions thereof) for any purpose, without fee, subject to these +conditions: +(1) If any part of the source code for this software is distributed, then this +README file must be included, with this copyright and no-warranty notice +unaltered; and any additions, deletions, or changes to the original files +must be clearly indicated in accompanying documentation. +(2) If only executable code is distributed, then the accompanying +documentation must state that "this software is based in part on the work of +the Independent JPEG Group". +(3) Permission for use of this software is granted only if the user accepts +full responsibility for any undesirable consequences; the authors accept +NO LIABILITY for damages of any kind. + +These conditions apply to any software derived from or based on the IJG code, +not just to the unmodified library. If you use our work, you ought to +acknowledge us. + +Permission is NOT granted for the use of any IJG author's name or company name +in advertising or publicity relating to this software or products derived from +it. This software may be referred to only as "the Independent JPEG Group's +software". + +We specifically permit and encourage the use of this software as the basis of +commercial products, provided that all warranty or liability claims are +assumed by the product vendor. + + +---- + +LIBLZMA + +XZ Utils Licensing +================== + + Different licenses apply to different files in this package. Here + is a rough summary of which licenses apply to which parts of this + package (but check the individual files to be sure!): + + - liblzma is in the public domain. + + - xz, xzdec, and lzmadec command line tools are in the public + domain unless GNU getopt_long had to be compiled and linked + in from the lib directory. The getopt_long code is under + GNU LGPLv2.1+. + + - The scripts to grep, diff, and view compressed files have been + adapted from gzip. These scripts and their documentation are + under GNU GPLv2+. + + - All the documentation in the doc directory and most of the + XZ Utils specific documentation files in other directories + are in the public domain. + + - Translated messages are in the public domain. + + - The build system contains public domain files, and files that + are under GNU GPLv2+ or GNU GPLv3+. None of these files end up + in the binaries being built. + + - Test files and test code in the tests directory, and debugging + utilities in the debug directory are in the public domain. + + - The extra directory may contain public domain files, and files + that are under various free software licenses. + + You can do whatever you want with the files that have been put into + the public domain. If you find public domain legally problematic, + take the previous sentence as a license grant. If you still find + the lack of copyright legally problematic, you have too many + lawyers. + + As usual, this software is provided "as is", without any warranty. + + If you copy significant amounts of public domain code from XZ Utils + into your project, acknowledging this somewhere in your software is + polite (especially if it is proprietary, non-free software), but + naturally it is not legally required. Here is an example of a good + notice to put into "about box" or into documentation: + + This software includes code from XZ Utils . + + The following license texts are included in the following files: + - COPYING.LGPLv2.1: GNU Lesser General Public License version 2.1 + - COPYING.GPLv2: GNU General Public License version 2 + - COPYING.GPLv3: GNU General Public License version 3 + + Note that the toolchain (compiler, linker etc.) may add some code + pieces that are copyrighted. Thus, it is possible that e.g. liblzma + binary wouldn't actually be in the public domain in its entirety + even though it contains no copyrighted code from the XZ Utils source + package. + + If you have questions, don't hesitate to ask the author(s) for more + information. + + +---- + +LIBPNG + +COPYRIGHT NOTICE, DISCLAIMER, and LICENSE +========================================= + +PNG Reference Library License version 2 +--------------------------------------- + + * Copyright (c) 1995-2022 The PNG Reference Library Authors. + * Copyright (c) 2018-2022 Cosmin Truta. + * Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson. + * Copyright (c) 1996-1997 Andreas Dilger. + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. + +The software is supplied "as is", without warranty of any kind, +express or implied, including, without limitation, the warranties +of merchantability, fitness for a particular purpose, title, and +non-infringement. In no event shall the Copyright owners, or +anyone distributing the software, be liable for any damages or +other liability, whether in contract, tort or otherwise, arising +from, out of, or in connection with the software, or the use or +other dealings in the software, even if advised of the possibility +of such damage. + +Permission is hereby granted to use, copy, modify, and distribute +this software, or portions hereof, for any purpose, without fee, +subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you + must not claim that you wrote the original software. If you + use this software in a product, an acknowledgment in the product + documentation would be appreciated, but is not required. + + 2. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 3. This Copyright notice may not be removed or altered from any + source or altered source distribution. + + +PNG Reference Library License version 1 (for libpng 0.5 through 1.6.35) +----------------------------------------------------------------------- + +libpng versions 1.0.7, July 1, 2000, through 1.6.35, July 15, 2018 are +Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson, are +derived from libpng-1.0.6, and are distributed according to the same +disclaimer and license as libpng-1.0.6 with the following individuals +added to the list of Contributing Authors: + + Simon-Pierre Cadieux + Eric S. Raymond + Mans Rullgard + Cosmin Truta + Gilles Vollant + James Yu + Mandar Sahastrabuddhe + Google Inc. + Vadim Barkov + +and with the following additions to the disclaimer: + + There is no warranty against interference with your enjoyment of + the library or against infringement. There is no warranty that our + efforts or the library will fulfill any of your particular purposes + or needs. This library is provided with all faults, and the entire + risk of satisfactory quality, performance, accuracy, and effort is + with the user. + +Some files in the "contrib" directory and some configure-generated +files that are distributed with libpng have other copyright owners, and +are released under other open source licenses. + +libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are +Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from +libpng-0.96, and are distributed according to the same disclaimer and +license as libpng-0.96, with the following individuals added to the +list of Contributing Authors: + + Tom Lane + Glenn Randers-Pehrson + Willem van Schaik + +libpng versions 0.89, June 1996, through 0.96, May 1997, are +Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88, +and are distributed according to the same disclaimer and license as +libpng-0.88, with the following individuals added to the list of +Contributing Authors: + + John Bowler + Kevin Bracey + Sam Bushell + Magnus Holmgren + Greg Roelofs + Tom Tanner + +Some files in the "scripts" directory have other copyright owners, +but are released under this license. + +libpng versions 0.5, May 1995, through 0.88, January 1996, are +Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. + +For the purposes of this copyright and license, "Contributing Authors" +is defined as the following set of individuals: + + Andreas Dilger + Dave Martindale + Guy Eric Schalnat + Paul Schmidt + Tim Wegner + +The PNG Reference Library is supplied "AS IS". The Contributing +Authors and Group 42, Inc. disclaim all warranties, expressed or +implied, including, without limitation, the warranties of +merchantability and of fitness for any purpose. The Contributing +Authors and Group 42, Inc. assume no liability for direct, indirect, +incidental, special, exemplary, or consequential damages, which may +result from the use of the PNG Reference Library, even if advised of +the possibility of such damage. + +Permission is hereby granted to use, copy, modify, and distribute this +source code, or portions hereof, for any purpose, without fee, subject +to the following restrictions: + + 1. The origin of this source code must not be misrepresented. + + 2. Altered versions must be plainly marked as such and must not + be misrepresented as being the original source. + + 3. This Copyright notice may not be removed or altered from any + source or altered source distribution. + +The Contributing Authors and Group 42, Inc. specifically permit, +without fee, and encourage the use of this source code as a component +to supporting the PNG file format in commercial products. If you use +this source code in a product, acknowledgment is not required but would +be appreciated. + + +---- + +LIBTIFF + +Copyright (c) 1988-1997 Sam Leffler +Copyright (c) 1991-1997 Silicon Graphics, Inc. + +Permission to use, copy, modify, distribute, and sell this software and +its documentation for any purpose is hereby granted without fee, provided +that (i) the above copyright notices and this permission notice appear in +all copies of the software and related documentation, and (ii) the names of +Sam Leffler and Silicon Graphics may not be used in any advertising or +publicity relating to the software without the specific, prior written +permission of Sam Leffler and Silicon Graphics. + +THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, +EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY +WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + +IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR +ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF +LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE +OF THIS SOFTWARE. + + +---- + +LIBWEBP + +Copyright (c) 2010, Google Inc. 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 Google nor the names of its contributors may + be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +---- + +LIBYUV + +Copyright 2011 The LibYuv Project Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * 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 Google nor the names of its contributors may + be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +---- + +OPENJPEG + +* + * The copyright in this software is being made available under the 2-clauses + * BSD License, included below. This software may be subject to other third + * party and contributor rights, including patent rights, and no such rights + * are granted under this license. + * + * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium + * Copyright (c) 2002-2014, Professor Benoit Macq + * Copyright (c) 2003-2014, Antonin Descampe + * Copyright (c) 2003-2009, Francois-Olivier Devaux + * Copyright (c) 2005, Herve Drolon, FreeImage Team + * Copyright (c) 2002-2003, Yannick Verschueren + * Copyright (c) 2001-2003, David Janssens + * Copyright (c) 2011-2012, Centre National d'Etudes Spatiales (CNES), France + * Copyright (c) 2012, CS Systemes d'Information, France + * + * 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. + * + * 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. + */ + + +---- + +RAQM + +The MIT License (MIT) + +Copyright © 2015 Information Technology Authority (ITA) +Copyright © 2016 Khaled Hosny + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +---- + +XAU + +Copyright 1988, 1993, 1994, 1998 The Open Group + +Permission to use, copy, modify, distribute, and sell this software and its +documentation for any purpose is hereby granted without fee, provided that +the above copyright notice appear in all copies and that both that +copyright notice and this permission notice appear in supporting +documentation. + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN +AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Except as contained in this notice, the name of The Open Group shall not be +used in advertising or otherwise to promote the sale, use or other dealings +in this Software without prior written authorization from The Open Group. + + +---- + +XCB + +Copyright (C) 2001-2006 Bart Massey, Jamey Sharp, and Josh Triplett. +All Rights Reserved. + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall +be included in all copies or substantial portions of the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +Except as contained in this notice, the names of the authors +or their institutions shall not be used in advertising or +otherwise to promote the sale, use or other dealings in this +Software without prior written authorization from the +authors. + + +---- + +XDMCP + +Copyright 1989, 1998 The Open Group + +Permission to use, copy, modify, distribute, and sell this software and its +documentation for any purpose is hereby granted without fee, provided that +the above copyright notice appear in all copies and that both that +copyright notice and this permission notice appear in supporting +documentation. + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN +AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Except as contained in this notice, the name of The Open Group shall not be +used in advertising or otherwise to promote the sale, use or other dealings +in this Software without prior written authorization from The Open Group. + +Author: Keith Packard, MIT X Consortium + + +---- + +ZLIB + + (C) 1995-2017 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +If you use the zlib library in a product, we would appreciate *not* receiving +lengthy legal documents to sign. The sources are provided for free but without +warranty of any kind. The library has been entirely written by Jean-loup +Gailly and Mark Adler; it does not include third-party code. + +If you redistribute modified sources, we would appreciate that you include in +the file ChangeLog history information documenting your changes. Please read +the FAQ for more information on the distribution of modified source versions. + + +---- + +ZSTD + +BSD License + +For Zstandard software + +Copyright (c) Meta Platforms, Inc. and affiliates. 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 Facebook, nor Meta, nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/top_level.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..b338169ce0c740c335bfe82912227ae8637bd492 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/top_level.txt @@ -0,0 +1 @@ +PIL diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/zip-safe b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/zip-safe new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pillow-12.0.0.dist-info/zip-safe @@ -0,0 +1 @@ + diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..502519cdef323b2fcca9c3e96e6509333c5321fa --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__init__.py @@ -0,0 +1,330 @@ +# module pyparsing.py +# +# Copyright (c) 2003-2022 Paul T. McGuire +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +# + +__doc__ = """ +pyparsing - Classes and methods to define and execute parsing grammars +====================================================================== + +Pyparsing is an alternative approach to creating and executing simple +grammars, vs. the traditional lex/yacc approach, or the use of regular +expressions. With pyparsing, you don't need to learn a new syntax for +defining grammars or matching expressions - the parsing module provides +a library of classes that you use to construct the grammar directly in +Python. + +Here is a program to parse "Hello, World!" (or any greeting of the form +``", !"``), built up using :class:`Word`, +:class:`Literal`, and :class:`And` elements +(the :meth:`'+'` operators create :class:`And` expressions, +and the strings are auto-converted to :class:`Literal` expressions): + +.. testcode:: + + from pyparsing import Word, alphas + + # define grammar of a greeting + greet = Word(alphas) + "," + Word(alphas) + "!" + + hello = "Hello, World!" + print(hello, "->", greet.parse_string(hello)) + +The program outputs the following: + +.. testoutput:: + + Hello, World! -> ['Hello', ',', 'World', '!'] + +The Python representation of the grammar is quite readable, owing to the +self-explanatory class names, and the use of :class:`'+'`, +:class:`'|'`, :class:`'^'` and :class:`'&'` operators. + +The :class:`ParseResults` object returned from +:class:`ParserElement.parse_string` can be +accessed as a nested list, a dictionary, or an object with named +attributes. + +The pyparsing module handles some of the problems that are typically +vexing when writing text parsers: + + - extra or missing whitespace (the above program will also handle + "Hello,World!", "Hello , World !", etc.) + - quoted strings + - embedded comments + + +Getting Started +--------------- +Visit the classes :class:`ParserElement` and :class:`ParseResults` to +see the base classes that most other pyparsing +classes inherit from. Use the docstrings for examples of how to: + + - construct literal match expressions from :class:`Literal` and + :class:`CaselessLiteral` classes + - construct character word-group expressions using the :class:`Word` + class + - see how to create repetitive expressions using :class:`ZeroOrMore` + and :class:`OneOrMore` classes + - use :class:`'+'`, :class:`'|'`, :class:`'^'`, + and :class:`'&'` operators to combine simple expressions into + more complex ones + - associate names with your parsed results using + :class:`ParserElement.set_results_name` + - access the parsed data, which is returned as a :class:`ParseResults` + object + - find some helpful expression short-cuts like :class:`DelimitedList` + and :class:`one_of` + - find more useful common expressions in the :class:`pyparsing_common` + namespace class +""" +from typing import NamedTuple + + +class version_info(NamedTuple): + major: int + minor: int + micro: int + releaselevel: str + serial: int + + @property + def __version__(self): + return ( + f"{self.major}.{self.minor}.{self.micro}" + + ( + f"{'r' if self.releaselevel[0] == 'c' else ''}{self.releaselevel[0]}{self.serial}", + "", + )[self.releaselevel == "final"] + ) + + def __str__(self): + return f"{__name__} {self.__version__} / {__version_time__}" + + def __repr__(self): + return f"{__name__}.{type(self).__name__}({', '.join('{}={!r}'.format(*nv) for nv in zip(self._fields, self))})" + + +__version_info__ = version_info(3, 2, 5, "final", 1) +__version_time__ = "16 Sep 2025 22:24 UTC" +__version__ = __version_info__.__version__ +__versionTime__ = __version_time__ +__author__ = "Paul McGuire " + +from .util import * +from .exceptions import * +from .actions import * +from .core import __diag__, __compat__ +from .results import * +from .core import * +from .core import _builtin_exprs as core_builtin_exprs +from .helpers import * +from .helpers import _builtin_exprs as helper_builtin_exprs + +from .unicode import unicode_set, UnicodeRangeList, pyparsing_unicode as unicode +from .testing import pyparsing_test as testing +from .common import ( + pyparsing_common as common, + _builtin_exprs as common_builtin_exprs, +) + +# Compatibility synonyms +if "pyparsing_unicode" not in globals(): + pyparsing_unicode = unicode # type: ignore[misc] +if "pyparsing_common" not in globals(): + pyparsing_common = common +if "pyparsing_test" not in globals(): + pyparsing_test = testing + +core_builtin_exprs += common_builtin_exprs + helper_builtin_exprs + + +__all__ = [ + "__version__", + "__version_time__", + "__author__", + "__compat__", + "__diag__", + "And", + "AtLineStart", + "AtStringStart", + "CaselessKeyword", + "CaselessLiteral", + "CharsNotIn", + "CloseMatch", + "Combine", + "DelimitedList", + "Dict", + "Each", + "Empty", + "FollowedBy", + "Forward", + "GoToColumn", + "Group", + "IndentedBlock", + "Keyword", + "LineEnd", + "LineStart", + "Literal", + "Located", + "PrecededBy", + "MatchFirst", + "NoMatch", + "NotAny", + "OneOrMore", + "OnlyOnce", + "OpAssoc", + "Opt", + "Optional", + "Or", + "ParseBaseException", + "ParseElementEnhance", + "ParseException", + "ParseExpression", + "ParseFatalException", + "ParseResults", + "ParseSyntaxException", + "ParserElement", + "PositionToken", + "QuotedString", + "RecursiveGrammarException", + "Regex", + "SkipTo", + "StringEnd", + "StringStart", + "Suppress", + "Tag", + "Token", + "TokenConverter", + "White", + "Word", + "WordEnd", + "WordStart", + "ZeroOrMore", + "Char", + "alphanums", + "alphas", + "alphas8bit", + "any_close_tag", + "any_open_tag", + "autoname_elements", + "c_style_comment", + "col", + "common_html_entity", + "condition_as_parse_action", + "counted_array", + "cpp_style_comment", + "dbl_quoted_string", + "dbl_slash_comment", + "delimited_list", + "dict_of", + "empty", + "hexnums", + "html_comment", + "identchars", + "identbodychars", + "infix_notation", + "java_style_comment", + "line", + "line_end", + "line_start", + "lineno", + "make_html_tags", + "make_xml_tags", + "match_only_at_col", + "match_previous_expr", + "match_previous_literal", + "nested_expr", + "null_debug_action", + "nums", + "one_of", + "original_text_for", + "printables", + "punc8bit", + "pyparsing_common", + "pyparsing_test", + "pyparsing_unicode", + "python_style_comment", + "quoted_string", + "remove_quotes", + "replace_with", + "replace_html_entity", + "rest_of_line", + "sgl_quoted_string", + "srange", + "string_end", + "string_start", + "token_map", + "trace_parse_action", + "ungroup", + "unicode_set", + "unicode_string", + "with_attribute", + "with_class", + # pre-PEP8 compatibility names + "__versionTime__", + "anyCloseTag", + "anyOpenTag", + "cStyleComment", + "commonHTMLEntity", + "conditionAsParseAction", + "countedArray", + "cppStyleComment", + "dblQuotedString", + "dblSlashComment", + "delimitedList", + "dictOf", + "htmlComment", + "indentedBlock", + "infixNotation", + "javaStyleComment", + "lineEnd", + "lineStart", + "locatedExpr", + "makeHTMLTags", + "makeXMLTags", + "matchOnlyAtCol", + "matchPreviousExpr", + "matchPreviousLiteral", + "nestedExpr", + "nullDebugAction", + "oneOf", + "opAssoc", + "originalTextFor", + "pythonStyleComment", + "quotedString", + "removeQuotes", + "replaceHTMLEntity", + "replaceWith", + "restOfLine", + "sglQuotedString", + "stringEnd", + "stringStart", + "tokenMap", + "traceParseAction", + "unicodeString", + "withAttribute", + "withClass", + "common", + "unicode", + "testing", +] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..feb3a9d995765e6e01d23411529468d4d9e0a330 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/actions.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/actions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f592a8ee4ff8ecf49fe2a3334416b2db3330b9f Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/actions.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/common.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d682ded2ebb986341e27ee6a147cdfde6da066e7 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/common.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/exceptions.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/exceptions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb283897e178dfc72cb372d3aa039928b60db3fb Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/exceptions.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/helpers.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/helpers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..602ef79cf415ca4506d60ed3557fd9300b1509aa Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/helpers.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/results.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/results.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28ae116d0bacbaaee2e769e6f0110849a4c6d8d0 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/results.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/testing.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/testing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0491cf0d7f90c075584c0af97c6ceb261ffeff3 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/testing.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/unicode.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/unicode.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e61c2189e2023f042e56d3389a9fc7eb1d435f19 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/unicode.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/util.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ee2a9a74f9111a2fc850face80398b25cba0243 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/__pycache__/util.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/actions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/actions.py new file mode 100644 index 0000000000000000000000000000000000000000..0d80d2cf9111f92b4ecc80b9c854aa67e35b5bd4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/actions.py @@ -0,0 +1,263 @@ +# actions.py +from __future__ import annotations + +from typing import Union, Callable, Any + +from .exceptions import ParseException +from .util import col, replaced_by_pep8 +from .results import ParseResults + + +ParseAction = Union[ + Callable[[], Any], + Callable[[ParseResults], Any], + Callable[[int, ParseResults], Any], + Callable[[str, int, ParseResults], Any], +] + + +class OnlyOnce: + """ + Wrapper for parse actions, to ensure they are only called once. + Note: parse action signature must include all 3 arguments. + """ + + def __init__(self, method_call: Callable[[str, int, ParseResults], Any]) -> None: + from .core import _trim_arity + + self.callable = _trim_arity(method_call) + self.called = False + + def __call__(self, s: str, l: int, t: ParseResults) -> ParseResults: + if not self.called: + results = self.callable(s, l, t) + self.called = True + return results + raise ParseException(s, l, "OnlyOnce obj called multiple times w/out reset") + + def reset(self): + """ + Allow the associated parse action to be called once more. + """ + + self.called = False + + +def match_only_at_col(n: int) -> ParseAction: + """ + Helper method for defining parse actions that require matching at + a specific column in the input text. + """ + + def verify_col(strg: str, locn: int, toks: ParseResults) -> None: + if col(locn, strg) != n: + raise ParseException(strg, locn, f"matched token not at column {n}") + + return verify_col + + +def replace_with(repl_str: Any) -> ParseAction: + """ + Helper method for common parse actions that simply return + a literal value. Especially useful when used with + :meth:`~ParserElement.transform_string`. + + Example: + + .. doctest:: + + >>> num = Word(nums).set_parse_action(lambda toks: int(toks[0])) + >>> na = one_of("N/A NA").set_parse_action(replace_with(math.nan)) + >>> term = na | num + + >>> term[1, ...].parse_string("324 234 N/A 234") + ParseResults([324, 234, nan, 234], {}) + """ + return lambda s, l, t: [repl_str] + + +def remove_quotes(s: str, l: int, t: ParseResults) -> Any: + r""" + Helper parse action for removing quotation marks from parsed + quoted strings, that use a single character for quoting. For parsing + strings that may have multiple characters, use the :class:`QuotedString` + class. + + Example: + + .. doctest:: + + >>> # by default, quotation marks are included in parsed results + >>> quoted_string.parse_string("'Now is the Winter of our Discontent'") + ParseResults(["'Now is the Winter of our Discontent'"], {}) + + >>> # use remove_quotes to strip quotation marks from parsed results + >>> dequoted = quoted_string().set_parse_action(remove_quotes) + >>> dequoted.parse_string("'Now is the Winter of our Discontent'") + ParseResults(['Now is the Winter of our Discontent'], {}) + """ + return t[0][1:-1] + + +def with_attribute(*args: tuple[str, str], **attr_dict) -> ParseAction: + """ + Helper to create a validating parse action to be used with start + tags created with :class:`make_xml_tags` or + :class:`make_html_tags`. Use ``with_attribute`` to qualify + a starting tag with a required attribute value, to avoid false + matches on common tags such as ```` or ``
``. + + Call ``with_attribute`` with a series of attribute names and + values. Specify the list of filter attributes names and values as: + + - keyword arguments, as in ``(align="right")``, or + - as an explicit dict with ``**`` operator, when an attribute + name is also a Python reserved word, as in ``**{"class":"Customer", "align":"right"}`` + - a list of name-value tuples, as in ``(("ns1:class", "Customer"), ("ns2:align", "right"))`` + + For attribute names with a namespace prefix, you must use the second + form. Attribute names are matched insensitive to upper/lower case. + + If just testing for ``class`` (with or without a namespace), use + :class:`with_class`. + + To verify that the attribute exists, but without specifying a value, + pass ``with_attribute.ANY_VALUE`` as the value. + + The next two examples use the following input data and tag parsers: + + .. testcode:: + + html = ''' +
+ Some text +
1 4 0 1 0
+
1,3 2,3 1,1
+
this has no type
+
+ ''' + div,div_end = make_html_tags("div") + + Only match div tag having a type attribute with value "grid": + + .. testcode:: + + div_grid = div().set_parse_action(with_attribute(type="grid")) + grid_expr = div_grid + SkipTo(div | div_end)("body") + for grid_header in grid_expr.search_string(html): + print(grid_header.body) + + prints: + + .. testoutput:: + + 1 4 0 1 0 + + Construct a match with any div tag having a type attribute, + regardless of the value: + + .. testcode:: + + div_any_type = div().set_parse_action( + with_attribute(type=with_attribute.ANY_VALUE) + ) + div_expr = div_any_type + SkipTo(div | div_end)("body") + for div_header in div_expr.search_string(html): + print(div_header.body) + + prints: + + .. testoutput:: + + 1 4 0 1 0 + 1,3 2,3 1,1 + """ + attrs_list: list[tuple[str, str]] = [] + if args: + attrs_list.extend(args) + else: + attrs_list.extend(attr_dict.items()) + + def pa(s: str, l: int, tokens: ParseResults) -> None: + for attrName, attrValue in attrs_list: + if attrName not in tokens: + raise ParseException(s, l, "no matching attribute " + attrName) + if attrValue != with_attribute.ANY_VALUE and tokens[attrName] != attrValue: # type: ignore [attr-defined] + raise ParseException( + s, + l, + f"attribute {attrName!r} has value {tokens[attrName]!r}, must be {attrValue!r}", + ) + + return pa + + +with_attribute.ANY_VALUE = object() # type: ignore [attr-defined] + + +def with_class(classname: str, namespace: str = "") -> ParseAction: + """ + Simplified version of :meth:`with_attribute` when + matching on a div class - made difficult because ``class`` is + a reserved word in Python. + + Using similar input data to the :meth:`with_attribute` examples: + + .. testcode:: + + html = ''' +
+ Some text +
1 4 0 1 0
+
1,3 2,3 1,1
+
this <div> has no class
+
+ ''' + div,div_end = make_html_tags("div") + + Only match div tag having the "grid" class: + + .. testcode:: + + div_grid = div().set_parse_action(with_class("grid")) + grid_expr = div_grid + SkipTo(div | div_end)("body") + for grid_header in grid_expr.search_string(html): + print(grid_header.body) + + prints: + + .. testoutput:: + + 1 4 0 1 0 + + Construct a match with any div tag having a class attribute, + regardless of the value: + + .. testcode:: + + div_any_type = div().set_parse_action( + with_class(withAttribute.ANY_VALUE) + ) + div_expr = div_any_type + SkipTo(div | div_end)("body") + for div_header in div_expr.search_string(html): + print(div_header.body) + + prints: + + .. testoutput:: + + 1 4 0 1 0 + 1,3 2,3 1,1 + """ + classattr = f"{namespace}:class" if namespace else "class" + return with_attribute(**{classattr: classname}) + + +# Compatibility synonyms +# fmt: off +replaceWith = replaced_by_pep8("replaceWith", replace_with) +removeQuotes = replaced_by_pep8("removeQuotes", remove_quotes) +withAttribute = replaced_by_pep8("withAttribute", with_attribute) +withClass = replaced_by_pep8("withClass", with_class) +matchOnlyAtCol = replaced_by_pep8("matchOnlyAtCol", match_only_at_col) +# fmt: on diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/common.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/common.py new file mode 100644 index 0000000000000000000000000000000000000000..dbf9ba88e9d838fcc46539999289523c9ab3a051 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/common.py @@ -0,0 +1,485 @@ +# common.py +from .core import * +from .helpers import DelimitedList, any_open_tag, any_close_tag +from datetime import datetime + + +# some other useful expressions - using lower-case class name since we are really using this as a namespace +class pyparsing_common: + """Here are some common low-level expressions that may be useful in + jump-starting parser development: + + - numeric forms (:class:`integers`, :class:`reals`, + :class:`scientific notation`) + - common :class:`programming identifiers` + - network addresses (:class:`MAC`, + :class:`IPv4`, :class:`IPv6`) + - ISO8601 :class:`dates` and + :class:`datetime` + - :class:`UUID` + - :class:`comma-separated list` + - :class:`url` + + Parse actions: + + - :class:`convert_to_integer` + - :class:`convert_to_float` + - :class:`convert_to_date` + - :class:`convert_to_datetime` + - :class:`strip_html_tags` + - :class:`upcase_tokens` + - :class:`downcase_tokens` + + Examples: + + .. testcode:: + + pyparsing_common.number.run_tests(''' + # any int or real number, returned as the appropriate type + 100 + -100 + +100 + 3.14159 + 6.02e23 + 1e-12 + ''') + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # any int or real number, returned as the appropriate type + 100 + [100] + + -100 + [-100] + + +100 + [100] + + 3.14159 + [3.14159] + + 6.02e23 + [6.02e+23] + + 1e-12 + [1e-12] + + .. testcode:: + + pyparsing_common.fnumber.run_tests(''' + # any int or real number, returned as float + 100 + -100 + +100 + 3.14159 + 6.02e23 + 1e-12 + ''') + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # any int or real number, returned as float + 100 + [100.0] + + -100 + [-100.0] + + +100 + [100.0] + + 3.14159 + [3.14159] + + 6.02e23 + [6.02e+23] + + 1e-12 + [1e-12] + + .. testcode:: + + pyparsing_common.hex_integer.run_tests(''' + # hex numbers + 100 + FF + ''') + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # hex numbers + 100 + [256] + + FF + [255] + + .. testcode:: + + pyparsing_common.fraction.run_tests(''' + # fractions + 1/2 + -3/4 + ''') + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # fractions + 1/2 + [0.5] + + -3/4 + [-0.75] + + .. testcode:: + + pyparsing_common.mixed_integer.run_tests(''' + # mixed fractions + 1 + 1/2 + -3/4 + 1-3/4 + ''') + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # mixed fractions + 1 + [1] + + 1/2 + [0.5] + + -3/4 + [-0.75] + + 1-3/4 + [1.75] + .. testcode:: + + import uuid + pyparsing_common.uuid.set_parse_action(token_map(uuid.UUID)) + pyparsing_common.uuid.run_tests(''' + # uuid + 12345678-1234-5678-1234-567812345678 + ''') + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # uuid + 12345678-1234-5678-1234-567812345678 + [UUID('12345678-1234-5678-1234-567812345678')] + """ + + convert_to_integer = token_map(int) + """ + Parse action for converting parsed integers to Python int + """ + + convert_to_float = token_map(float) + """ + Parse action for converting parsed numbers to Python float + """ + + integer = Word(nums).set_name("integer").set_parse_action(convert_to_integer) + """expression that parses an unsigned integer, returns an int""" + + hex_integer = ( + Word(hexnums).set_name("hex integer").set_parse_action(token_map(int, 16)) + ) + """expression that parses a hexadecimal integer, returns an int""" + + signed_integer = ( + Regex(r"[+-]?\d+") + .set_name("signed integer") + .set_parse_action(convert_to_integer) + ) + """expression that parses an integer with optional leading sign, returns an int""" + + fraction = ( + signed_integer().set_parse_action(convert_to_float) + + "/" + + signed_integer().set_parse_action(convert_to_float) + ).set_name("fraction") + """fractional expression of an integer divided by an integer, returns a float""" + fraction.add_parse_action(lambda tt: tt[0] / tt[-1]) + + mixed_integer = ( + fraction | signed_integer + Opt(Opt("-").suppress() + fraction) + ).set_name("fraction or mixed integer-fraction") + """mixed integer of the form 'integer - fraction', with optional leading integer, returns float""" + mixed_integer.add_parse_action(sum) + + real = ( + Regex(r"[+-]?(?:\d+\.\d*|\.\d+)") + .set_name("real number") + .set_parse_action(convert_to_float) + ) + """expression that parses a floating point number and returns a float""" + + sci_real = ( + Regex(r"[+-]?(?:\d+(?:[eE][+-]?\d+)|(?:\d+\.\d*|\.\d+)(?:[eE][+-]?\d+)?)") + .set_name("real number with scientific notation") + .set_parse_action(convert_to_float) + ) + """expression that parses a floating point number with optional + scientific notation and returns a float""" + + # streamlining this expression makes the docs nicer-looking + number = (sci_real | real | signed_integer).set_name("number").streamline() + """any numeric expression, returns the corresponding Python type""" + + fnumber = ( + Regex(r"[+-]?\d+\.?\d*(?:[eE][+-]?\d+)?") + .set_name("fnumber") + .set_parse_action(convert_to_float) + ) + """any int or real number, returned as float""" + + ieee_float = ( + Regex(r"(?i:[+-]?(?:(?:\d+\.?\d*(?:e[+-]?\d+)?)|nan|inf(?:inity)?))") + .set_name("ieee_float") + .set_parse_action(convert_to_float) + ) + """any floating-point literal (int, real number, infinity, or NaN), returned as float""" + + identifier = Word(identchars, identbodychars).set_name("identifier") + """typical code identifier (leading alpha or '_', followed by 0 or more alphas, nums, or '_')""" + + ipv4_address = Regex( + r"(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})){3}" + ).set_name("IPv4 address") + "IPv4 address (``0.0.0.0 - 255.255.255.255``)" + + _ipv6_part = Regex(r"[0-9a-fA-F]{1,4}").set_name("hex_integer") + _full_ipv6_address = (_ipv6_part + (":" + _ipv6_part) * 7).set_name( + "full IPv6 address" + ) + _short_ipv6_address = ( + Opt(_ipv6_part + (":" + _ipv6_part) * (0, 6)) + + "::" + + Opt(_ipv6_part + (":" + _ipv6_part) * (0, 6)) + ).set_name("short IPv6 address") + _short_ipv6_address.add_condition( + lambda t: sum(1 for tt in t if pyparsing_common._ipv6_part.matches(tt)) < 8 + ) + _mixed_ipv6_address = ("::ffff:" + ipv4_address).set_name("mixed IPv6 address") + ipv6_address = Combine( + (_full_ipv6_address | _mixed_ipv6_address | _short_ipv6_address).set_name( + "IPv6 address" + ) + ).set_name("IPv6 address") + "IPv6 address (long, short, or mixed form)" + + mac_address = Regex( + r"[0-9a-fA-F]{2}([:.-])[0-9a-fA-F]{2}(?:\1[0-9a-fA-F]{2}){4}" + ).set_name("MAC address") + "MAC address xx:xx:xx:xx:xx (may also have '-' or '.' delimiters)" + + @staticmethod + def convert_to_date(fmt: str = "%Y-%m-%d"): + """ + Helper to create a parse action for converting parsed date string to Python datetime.date + + Params - + - fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%d"``) + + Example: + + .. testcode:: + + date_expr = pyparsing_common.iso8601_date.copy() + date_expr.set_parse_action(pyparsing_common.convert_to_date()) + print(date_expr.parse_string("1999-12-31")) + + prints: + + .. testoutput:: + + [datetime.date(1999, 12, 31)] + """ + + def cvt_fn(ss, ll, tt): + try: + return datetime.strptime(tt[0], fmt).date() + except ValueError as ve: + raise ParseException(ss, ll, str(ve)) + + return cvt_fn + + @staticmethod + def convert_to_datetime(fmt: str = "%Y-%m-%dT%H:%M:%S.%f"): + """Helper to create a parse action for converting parsed + datetime string to Python datetime.datetime + + Params - + - fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%dT%H:%M:%S.%f"``) + + Example: + + .. testcode:: + + dt_expr = pyparsing_common.iso8601_datetime.copy() + dt_expr.set_parse_action(pyparsing_common.convert_to_datetime()) + print(dt_expr.parse_string("1999-12-31T23:59:59.999")) + + prints: + + .. testoutput:: + + [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)] + """ + + def cvt_fn(s, l, t): + try: + return datetime.strptime(t[0], fmt) + except ValueError as ve: + raise ParseException(s, l, str(ve)) + + return cvt_fn + + iso8601_date = Regex( + r"(?P\d{4})(?:-(?P\d\d)(?:-(?P\d\d))?)?" + ).set_name("ISO8601 date") + "ISO8601 date (``yyyy-mm-dd``)" + + iso8601_datetime = Regex( + r"(?P\d{4})-(?P\d\d)-(?P\d\d)[T ](?P\d\d):(?P\d\d)(:(?P\d\d(\.\d*)?)?)?(?PZ|[+-]\d\d:?\d\d)?" + ).set_name("ISO8601 datetime") + "ISO8601 datetime (``yyyy-mm-ddThh:mm:ss.s(Z|+-00:00)``) - trailing seconds, milliseconds, and timezone optional; accepts separating ``'T'`` or ``' '``" + + uuid = Regex(r"[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}").set_name("UUID") + "UUID (``xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx``)" + + _html_stripper = any_open_tag.suppress() | any_close_tag.suppress() + + @staticmethod + def strip_html_tags(s: str, l: int, tokens: ParseResults): + """Parse action to remove HTML tags from web page HTML source + + Example: + + .. testcode:: + + # strip HTML links from normal text + text = 'More info at the pyparsing wiki page' + td, td_end = make_html_tags("TD") + table_text = td + SkipTo(td_end).set_parse_action( + pyparsing_common.strip_html_tags)("body") + td_end + print(table_text.parse_string(text).body) + + Prints: + + .. testoutput:: + + More info at the pyparsing wiki page + """ + return pyparsing_common._html_stripper.transform_string(tokens[0]) + + _commasepitem = ( + Combine( + OneOrMore( + ~Literal(",") + + ~LineEnd() + + Word(printables, exclude_chars=",") + + Opt(White(" \t") + ~FollowedBy(LineEnd() | ",")) + ) + ) + .streamline() + .set_name("commaItem") + ) + comma_separated_list = DelimitedList( + Opt(quoted_string.copy() | _commasepitem, default="") + ).set_name("comma separated list") + """Predefined expression of 1 or more printable words or quoted strings, separated by commas.""" + + upcase_tokens = staticmethod(token_map(lambda t: t.upper())) + """Parse action to convert tokens to upper case.""" + + downcase_tokens = staticmethod(token_map(lambda t: t.lower())) + """Parse action to convert tokens to lower case.""" + + # fmt: off + url = Regex( + # https://mathiasbynens.be/demo/url-regex + # https://gist.github.com/dperini/729294 + r"(?P" + + # protocol identifier (optional) + # short syntax // still required + r"(?:(?:(?Phttps?|ftp):)?\/\/)" + + # user:pass BasicAuth (optional) + r"(?:(?P\S+(?::\S*)?)@)?" + + r"(?P" + + # IP address exclusion + # private & local networks + r"(?!(?:10|127)(?:\.\d{1,3}){3})" + + r"(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})" + + r"(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})" + + # IP address dotted notation octets + # excludes loopback network 0.0.0.0 + # excludes reserved space >= 224.0.0.0 + # excludes network & broadcast addresses + # (first & last IP address of each class) + r"(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])" + + r"(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}" + + r"(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))" + + r"|" + + # host & domain names, may end with dot + # can be replaced by a shortest alternative + # (?![-_])(?:[-\w\u00a1-\uffff]{0,63}[^-_]\.)+ + r"(?:" + + r"(?:" + + r"[a-z0-9\u00a1-\uffff]" + + r"[a-z0-9\u00a1-\uffff_-]{0,62}" + + r")?" + + r"[a-z0-9\u00a1-\uffff]\." + + r")+" + + # TLD identifier name, may end with dot + r"(?:[a-z\u00a1-\uffff]{2,}\.?)" + + r")" + + # port number (optional) + r"(:(?P\d{2,5}))?" + + # resource path (optional) + r"(?P\/[^?# ]*)?" + + # query string (optional) + r"(\?(?P[^#]*))?" + + # fragment (optional) + r"(#(?P\S*))?" + + r")" + ).set_name("url") + """ + URL (http/https/ftp scheme) + + .. versionchanged:: 3.1.0 + ``url`` named group added + """ + # fmt: on + + # pre-PEP8 compatibility names + # fmt: off + convertToInteger = staticmethod(replaced_by_pep8("convertToInteger", convert_to_integer)) + convertToFloat = staticmethod(replaced_by_pep8("convertToFloat", convert_to_float)) + convertToDate = staticmethod(replaced_by_pep8("convertToDate", convert_to_date)) + convertToDatetime = staticmethod(replaced_by_pep8("convertToDatetime", convert_to_datetime)) + stripHTMLTags = staticmethod(replaced_by_pep8("stripHTMLTags", strip_html_tags)) + upcaseTokens = staticmethod(replaced_by_pep8("upcaseTokens", upcase_tokens)) + downcaseTokens = staticmethod(replaced_by_pep8("downcaseTokens", downcase_tokens)) + # fmt: on + + +_builtin_exprs = [ + v for v in vars(pyparsing_common).values() if isinstance(v, ParserElement) +] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/core.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/core.py new file mode 100644 index 0000000000000000000000000000000000000000..9c5894eb42a9e79567e21e1f7446427212427f44 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/core.py @@ -0,0 +1,6730 @@ +# +# core.py +# +from __future__ import annotations + +import collections.abc +from collections import deque +import os +import typing +from typing import ( + Any, + Callable, + Generator, + NamedTuple, + Sequence, + TextIO, + Union, + cast, +) +from abc import ABC, abstractmethod +from enum import Enum +import string +import copy +import warnings +import re +import sys +from collections.abc import Iterable +import traceback +import types +from operator import itemgetter +from functools import wraps +from threading import RLock +from pathlib import Path + +from .util import ( + _FifoCache, + _UnboundedCache, + __config_flags, + _collapse_string_to_ranges, + _escape_regex_range_chars, + _flatten, + LRUMemo as _LRUMemo, + UnboundedMemo as _UnboundedMemo, + replaced_by_pep8, +) +from .exceptions import * +from .actions import * +from .results import ParseResults, _ParseResultsWithOffset +from .unicode import pyparsing_unicode + +_MAX_INT = sys.maxsize +str_type: tuple[type, ...] = (str, bytes) + +# +# Copyright (c) 2003-2022 Paul T. McGuire +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +# + +from functools import cached_property + + +class __compat__(__config_flags): + """ + A cross-version compatibility configuration for pyparsing features that will be + released in a future version. By setting values in this configuration to True, + those features can be enabled in prior versions for compatibility development + and testing. + + - ``collect_all_And_tokens`` - flag to enable fix for Issue #63 that fixes erroneous grouping + of results names when an :class:`And` expression is nested within an :class:`Or` or :class:`MatchFirst`; + maintained for compatibility, but setting to ``False`` no longer restores pre-2.3.1 + behavior + """ + + _type_desc = "compatibility" + + collect_all_And_tokens = True + + _all_names = [__ for __ in locals() if not __.startswith("_")] + _fixed_names = """ + collect_all_And_tokens + """.split() + + +class __diag__(__config_flags): + _type_desc = "diagnostic" + + warn_multiple_tokens_in_named_alternation = False + warn_ungrouped_named_tokens_in_collection = False + warn_name_set_on_empty_Forward = False + warn_on_parse_using_empty_Forward = False + warn_on_assignment_to_Forward = False + warn_on_multiple_string_args_to_oneof = False + warn_on_match_first_with_lshift_operator = False + enable_debug_on_named_expressions = False + + _all_names = [__ for __ in locals() if not __.startswith("_")] + _warning_names = [name for name in _all_names if name.startswith("warn")] + _debug_names = [name for name in _all_names if name.startswith("enable_debug")] + + @classmethod + def enable_all_warnings(cls) -> None: + for name in cls._warning_names: + cls.enable(name) + + +class Diagnostics(Enum): + """ + Diagnostic configuration (all default to disabled) + + - ``warn_multiple_tokens_in_named_alternation`` - flag to enable warnings when a results + name is defined on a :class:`MatchFirst` or :class:`Or` expression with one or more :class:`And` subexpressions + - ``warn_ungrouped_named_tokens_in_collection`` - flag to enable warnings when a results + name is defined on a containing expression with ungrouped subexpressions that also + have results names + - ``warn_name_set_on_empty_Forward`` - flag to enable warnings when a :class:`Forward` is defined + with a results name, but has no contents defined + - ``warn_on_parse_using_empty_Forward`` - flag to enable warnings when a :class:`Forward` is + defined in a grammar but has never had an expression attached to it + - ``warn_on_assignment_to_Forward`` - flag to enable warnings when a :class:`Forward` is defined + but is overwritten by assigning using ``'='`` instead of ``'<<='`` or ``'<<'`` + - ``warn_on_multiple_string_args_to_oneof`` - flag to enable warnings when :class:`one_of` is + incorrectly called with multiple str arguments + - ``enable_debug_on_named_expressions`` - flag to auto-enable debug on all subsequent + calls to :class:`ParserElement.set_name` + + Diagnostics are enabled/disabled by calling :class:`enable_diag` and :class:`disable_diag`. + All warnings can be enabled by calling :class:`enable_all_warnings`. + """ + + warn_multiple_tokens_in_named_alternation = 0 + warn_ungrouped_named_tokens_in_collection = 1 + warn_name_set_on_empty_Forward = 2 + warn_on_parse_using_empty_Forward = 3 + warn_on_assignment_to_Forward = 4 + warn_on_multiple_string_args_to_oneof = 5 + warn_on_match_first_with_lshift_operator = 6 + enable_debug_on_named_expressions = 7 + + +def enable_diag(diag_enum: Diagnostics) -> None: + """ + Enable a global pyparsing diagnostic flag (see :class:`Diagnostics`). + """ + __diag__.enable(diag_enum.name) + + +def disable_diag(diag_enum: Diagnostics) -> None: + """ + Disable a global pyparsing diagnostic flag (see :class:`Diagnostics`). + """ + __diag__.disable(diag_enum.name) + + +def enable_all_warnings() -> None: + """ + Enable all global pyparsing diagnostic warnings (see :class:`Diagnostics`). + """ + __diag__.enable_all_warnings() + + +# hide abstract class +del __config_flags + + +def _should_enable_warnings( + cmd_line_warn_options: typing.Iterable[str], warn_env_var: typing.Optional[str] +) -> bool: + enable = bool(warn_env_var) + for warn_opt in cmd_line_warn_options: + w_action, w_message, w_category, w_module, w_line = (warn_opt + "::::").split( + ":" + )[:5] + if not w_action.lower().startswith("i") and ( + not (w_message or w_category or w_module) or w_module == "pyparsing" + ): + enable = True + elif w_action.lower().startswith("i") and w_module in ("pyparsing", ""): + enable = False + return enable + + +if _should_enable_warnings( + sys.warnoptions, os.environ.get("PYPARSINGENABLEALLWARNINGS") +): + enable_all_warnings() + + +# build list of single arg builtins, that can be used as parse actions +# fmt: off +_single_arg_builtins = { + sum, len, sorted, reversed, list, tuple, set, any, all, min, max +} +# fmt: on + +_generatorType = types.GeneratorType +ParseImplReturnType = tuple[int, Any] +PostParseReturnType = Union[ParseResults, Sequence[ParseResults]] + +ParseCondition = Union[ + Callable[[], bool], + Callable[[ParseResults], bool], + Callable[[int, ParseResults], bool], + Callable[[str, int, ParseResults], bool], +] +ParseFailAction = Callable[[str, int, "ParserElement", Exception], None] +DebugStartAction = Callable[[str, int, "ParserElement", bool], None] +DebugSuccessAction = Callable[ + [str, int, int, "ParserElement", ParseResults, bool], None +] +DebugExceptionAction = Callable[[str, int, "ParserElement", Exception, bool], None] + + +alphas: str = string.ascii_uppercase + string.ascii_lowercase +identchars: str = pyparsing_unicode.Latin1.identchars +identbodychars: str = pyparsing_unicode.Latin1.identbodychars +nums: str = "0123456789" +hexnums: str = nums + "ABCDEFabcdef" +alphanums: str = alphas + nums +printables: str = "".join([c for c in string.printable if c not in string.whitespace]) + + +class _ParseActionIndexError(Exception): + """ + Internal wrapper around IndexError so that IndexErrors raised inside + parse actions aren't misinterpreted as IndexErrors raised inside + ParserElement parseImpl methods. + """ + + def __init__(self, msg: str, exc: BaseException) -> None: + self.msg: str = msg + self.exc: BaseException = exc + + +_trim_arity_call_line: traceback.StackSummary = None # type: ignore[assignment] +pa_call_line_synth = () + + +def _trim_arity(func, max_limit=3): + """decorator to trim function calls to match the arity of the target""" + global _trim_arity_call_line, pa_call_line_synth + + if func in _single_arg_builtins: + return lambda s, l, t: func(t) + + limit = 0 + found_arity = False + + # synthesize what would be returned by traceback.extract_stack at the call to + # user's parse action 'func', so that we don't incur call penalty at parse time + + # fmt: off + LINE_DIFF = 9 + # IF ANY CODE CHANGES, EVEN JUST COMMENTS OR BLANK LINES, BETWEEN THE NEXT LINE AND + # THE CALL TO FUNC INSIDE WRAPPER, LINE_DIFF MUST BE MODIFIED!!!! + _trim_arity_call_line = _trim_arity_call_line or traceback.extract_stack(limit=2)[-1] + pa_call_line_synth = pa_call_line_synth or (_trim_arity_call_line[0], _trim_arity_call_line[1] + LINE_DIFF) + + def wrapper(*args): + nonlocal found_arity, limit + if found_arity: + return func(*args[limit:]) + while 1: + try: + ret = func(*args[limit:]) + found_arity = True + return ret + except TypeError as te: + # re-raise TypeErrors if they did not come from our arity testing + if found_arity: + raise + else: + tb = te.__traceback__ + frames = traceback.extract_tb(tb, limit=2) + frame_summary = frames[-1] + trim_arity_type_error = ( + [frame_summary[:2]][-1][:2] == pa_call_line_synth + ) + del tb + + if trim_arity_type_error: + if limit < max_limit: + limit += 1 + continue + + raise + except IndexError as ie: + # wrap IndexErrors inside a _ParseActionIndexError + raise _ParseActionIndexError( + "IndexError raised in parse action", ie + ).with_traceback(None) + # fmt: on + + # copy func name to wrapper for sensible debug output + # (can't use functools.wraps, since that messes with function signature) + func_name = getattr(func, "__name__", getattr(func, "__class__").__name__) + wrapper.__name__ = func_name + wrapper.__doc__ = func.__doc__ + + return wrapper + + +def condition_as_parse_action( + fn: ParseCondition, message: typing.Optional[str] = None, fatal: bool = False +) -> ParseAction: + """ + Function to convert a simple predicate function that returns ``True`` or ``False`` + into a parse action. Can be used in places when a parse action is required + and :meth:`ParserElement.add_condition` cannot be used (such as when adding a condition + to an operator level in :class:`infix_notation`). + + Optional keyword arguments: + + :param message: define a custom message to be used in the raised exception + :param fatal: if ``True``, will raise :class:`ParseFatalException` + to stop parsing immediately; + otherwise will raise :class:`ParseException` + + """ + msg = message if message is not None else "failed user-defined condition" + exc_type = ParseFatalException if fatal else ParseException + fn = _trim_arity(fn) + + @wraps(fn) + def pa(s, l, t): + if not bool(fn(s, l, t)): + raise exc_type(s, l, msg) + + return pa + + +def _default_start_debug_action( + instring: str, loc: int, expr: ParserElement, cache_hit: bool = False +): + cache_hit_str = "*" if cache_hit else "" + print( + ( + f"{cache_hit_str}Match {expr} at loc {loc}({lineno(loc, instring)},{col(loc, instring)})\n" + f" {line(loc, instring)}\n" + f" {'^':>{col(loc, instring)}}" + ) + ) + + +def _default_success_debug_action( + instring: str, + startloc: int, + endloc: int, + expr: ParserElement, + toks: ParseResults, + cache_hit: bool = False, +): + cache_hit_str = "*" if cache_hit else "" + print(f"{cache_hit_str}Matched {expr} -> {toks.as_list()}") + + +def _default_exception_debug_action( + instring: str, + loc: int, + expr: ParserElement, + exc: Exception, + cache_hit: bool = False, +): + cache_hit_str = "*" if cache_hit else "" + print(f"{cache_hit_str}Match {expr} failed, {type(exc).__name__} raised: {exc}") + + +def null_debug_action(*args): + """'Do-nothing' debug action, to suppress debugging output during parsing.""" + + +class ParserElement(ABC): + """Abstract base level parser element class.""" + + DEFAULT_WHITE_CHARS: str = " \n\t\r" + verbose_stacktrace: bool = False + _literalStringClass: type = None # type: ignore[assignment] + + @staticmethod + def set_default_whitespace_chars(chars: str) -> None: + r""" + Overrides the default whitespace chars + + Example: + + .. doctest:: + + # default whitespace chars are space, and newline + >>> Word(alphas)[1, ...].parse_string("abc def\nghi jkl") + ParseResults(['abc', 'def', 'ghi', 'jkl'], {}) + + # change to just treat newline as significant + >>> ParserElement.set_default_whitespace_chars(" \t") + >>> Word(alphas)[1, ...].parse_string("abc def\nghi jkl") + ParseResults(['abc', 'def'], {}) + + # Reset to default + >>> ParserElement.set_default_whitespace_chars(" \n\t\r") + """ + ParserElement.DEFAULT_WHITE_CHARS = chars + + # update whitespace all parse expressions defined in this module + for expr in _builtin_exprs: + if expr.copyDefaultWhiteChars: + expr.whiteChars = set(chars) + + @staticmethod + def inline_literals_using(cls: type) -> None: + """ + Set class to be used for inclusion of string literals into a parser. + + Example: + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + # default literal class used is Literal + >>> integer = Word(nums) + >>> date_str = ( + ... integer("year") + '/' + ... + integer("month") + '/' + ... + integer("day") + ... ) + + >>> date_str.parse_string("1999/12/31") + ParseResults(['1999', '/', '12', '/', '31'], + {'year': '1999', 'month': '12', 'day': '31'}) + + # change to Suppress + >>> ParserElement.inline_literals_using(Suppress) + >>> date_str = ( + ... integer("year") + '/' + ... + integer("month") + '/' + ... + integer("day") + ... ) + + >>> date_str.parse_string("1999/12/31") + ParseResults(['1999', '12', '31'], + {'year': '1999', 'month': '12', 'day': '31'}) + + # Reset + >>> ParserElement.inline_literals_using(Literal) + """ + ParserElement._literalStringClass = cls + + @classmethod + def using_each(cls, seq, **class_kwargs): + """ + Yields a sequence of ``class(obj, **class_kwargs)`` for obj in seq. + + Example: + + .. testcode:: + + LPAR, RPAR, LBRACE, RBRACE, SEMI = Suppress.using_each("(){};") + + .. versionadded:: 3.1.0 + """ + yield from (cls(obj, **class_kwargs) for obj in seq) + + class DebugActions(NamedTuple): + debug_try: typing.Optional[DebugStartAction] + debug_match: typing.Optional[DebugSuccessAction] + debug_fail: typing.Optional[DebugExceptionAction] + + def __init__(self, savelist: bool = False) -> None: + self.parseAction: list[ParseAction] = list() + self.failAction: typing.Optional[ParseFailAction] = None + self.customName: str = None # type: ignore[assignment] + self._defaultName: typing.Optional[str] = None + self.resultsName: str = None # type: ignore[assignment] + self.saveAsList = savelist + self.skipWhitespace = True + self.whiteChars = set(ParserElement.DEFAULT_WHITE_CHARS) + self.copyDefaultWhiteChars = True + # used when checking for left-recursion + self._may_return_empty = False + self.keepTabs = False + self.ignoreExprs: list[ParserElement] = list() + self.debug = False + self.streamlined = False + # optimize exception handling for subclasses that don't advance parse index + self.mayIndexError = True + self.errmsg: Union[str, None] = "" + # mark results names as modal (report only last) or cumulative (list all) + self.modalResults = True + # custom debug actions + self.debugActions = self.DebugActions(None, None, None) + # avoid redundant calls to preParse + self.callPreparse = True + self.callDuringTry = False + self.suppress_warnings_: list[Diagnostics] = [] + self.show_in_diagram = True + + @property + def mayReturnEmpty(self): + return self._may_return_empty + + @mayReturnEmpty.setter + def mayReturnEmpty(self, value): + self._may_return_empty = value + + def suppress_warning(self, warning_type: Diagnostics) -> ParserElement: + """ + Suppress warnings emitted for a particular diagnostic on this expression. + + Example: + + .. doctest:: + + >>> label = pp.Word(pp.alphas) + + # Normally using an empty Forward in a grammar + # would print a warning, but we can suppress that + >>> base = pp.Forward().suppress_warning( + ... pp.Diagnostics.warn_on_parse_using_empty_Forward) + + >>> grammar = base | label + >>> print(grammar.parse_string("x")) + ['x'] + """ + self.suppress_warnings_.append(warning_type) + return self + + def visit_all(self): + """General-purpose method to yield all expressions and sub-expressions + in a grammar. Typically just for internal use. + """ + to_visit = deque([self]) + seen = set() + while to_visit: + cur = to_visit.popleft() + + # guard against looping forever through recursive grammars + if cur in seen: + continue + seen.add(cur) + + to_visit.extend(cur.recurse()) + yield cur + + def copy(self) -> ParserElement: + """ + Make a copy of this :class:`ParserElement`. Useful for defining + different parse actions for the same parsing pattern, using copies of + the original parse element. + + Example: + + .. testcode:: + + integer = Word(nums).set_parse_action( + lambda toks: int(toks[0])) + integerK = integer.copy().add_parse_action( + lambda toks: toks[0] * 1024) + Suppress("K") + integerM = integer.copy().add_parse_action( + lambda toks: toks[0] * 1024 * 1024) + Suppress("M") + + print( + (integerK | integerM | integer)[1, ...].parse_string( + "5K 100 640K 256M") + ) + + prints: + + .. testoutput:: + + [5120, 100, 655360, 268435456] + + Equivalent form of ``expr.copy()`` is just ``expr()``: + + .. testcode:: + + integerM = integer().add_parse_action( + lambda toks: toks[0] * 1024 * 1024) + Suppress("M") + """ + cpy = copy.copy(self) + cpy.parseAction = self.parseAction[:] + cpy.ignoreExprs = self.ignoreExprs[:] + if self.copyDefaultWhiteChars: + cpy.whiteChars = set(ParserElement.DEFAULT_WHITE_CHARS) + return cpy + + def set_results_name( + self, name: str, list_all_matches: bool = False, *, listAllMatches: bool = False + ) -> ParserElement: + """ + Define name for referencing matching tokens as a nested attribute + of the returned parse results. + + Normally, results names are assigned as you would assign keys in a dict: + any existing value is overwritten by later values. If it is necessary to + keep all values captured for a particular results name, call ``set_results_name`` + with ``list_all_matches`` = True. + + NOTE: ``set_results_name`` returns a *copy* of the original :class:`ParserElement` object; + this is so that the client can define a basic element, such as an + integer, and reference it in multiple places with different names. + + You can also set results names using the abbreviated syntax, + ``expr("name")`` in place of ``expr.set_results_name("name")`` + - see :meth:`__call__`. If ``list_all_matches`` is required, use + ``expr("name*")``. + + Example: + + .. testcode:: + + integer = Word(nums) + date_str = (integer.set_results_name("year") + '/' + + integer.set_results_name("month") + '/' + + integer.set_results_name("day")) + + # equivalent form: + date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + """ + listAllMatches = listAllMatches or list_all_matches + return self._setResultsName(name, listAllMatches) + + def _setResultsName(self, name, list_all_matches=False) -> ParserElement: + if name is None: + return self + newself = self.copy() + if name.endswith("*"): + name = name[:-1] + list_all_matches = True + newself.resultsName = name + newself.modalResults = not list_all_matches + return newself + + def set_break(self, break_flag: bool = True) -> ParserElement: + """ + Method to invoke the Python pdb debugger when this element is + about to be parsed. Set ``break_flag`` to ``True`` to enable, ``False`` to + disable. + """ + if break_flag: + _parseMethod = self._parse + + def breaker(instring, loc, do_actions=True, callPreParse=True): + # this call to breakpoint() is intentional, not a checkin error + breakpoint() + return _parseMethod(instring, loc, do_actions, callPreParse) + + breaker._originalParseMethod = _parseMethod # type: ignore [attr-defined] + self._parse = breaker # type: ignore [method-assign] + elif hasattr(self._parse, "_originalParseMethod"): + self._parse = self._parse._originalParseMethod # type: ignore [method-assign] + return self + + def set_parse_action(self, *fns: ParseAction, **kwargs: Any) -> ParserElement: + """ + Define one or more actions to perform when successfully matching parse element definition. + + Parse actions can be called to perform data conversions, do extra validation, + update external data structures, or enhance or replace the parsed tokens. + Each parse action ``fn`` is a callable method with 0-3 arguments, called as + ``fn(s, loc, toks)`` , ``fn(loc, toks)`` , ``fn(toks)`` , or just ``fn()`` , where: + + - ``s`` = the original string being parsed (see note below) + - ``loc`` = the location of the matching substring + - ``toks`` = a list of the matched tokens, packaged as a :class:`ParseResults` object + + The parsed tokens are passed to the parse action as ParseResults. They can be + modified in place using list-style append, extend, and pop operations to update + the parsed list elements; and with dictionary-style item set and del operations + to add, update, or remove any named results. If the tokens are modified in place, + it is not necessary to return them with a return statement. + + Parse actions can also completely replace the given tokens, with another ``ParseResults`` + object, or with some entirely different object (common for parse actions that perform data + conversions). A convenient way to build a new parse result is to define the values + using a dict, and then create the return value using :class:`ParseResults.from_dict`. + + If None is passed as the ``fn`` parse action, all previously added parse actions for this + expression are cleared. + + Optional keyword arguments: + + :param call_during_try: (default= ``False``) indicate if parse action + should be run during lookaheads and alternate + testing. For parse actions that have side + effects, it is important to only call the parse + action once it is determined that it is being + called as part of a successful parse. + For parse actions that perform additional + validation, then ``call_during_try`` should + be passed as True, so that the validation code + is included in the preliminary "try" parses. + + .. Note:: + The default parsing behavior is to expand tabs in the input string + before starting the parsing process. + See :meth:`parse_string` for more information on parsing strings + containing ```` s, and suggested methods to maintain a + consistent view of the parsed string, the parse location, and + line and column positions within the parsed string. + + Example: Parse dates in the form ``YYYY/MM/DD`` + ----------------------------------------------- + + Setup code: + + .. testcode:: + + def convert_to_int(toks): + '''a parse action to convert toks from str to int + at parse time''' + return int(toks[0]) + + def is_valid_date(instring, loc, toks): + '''a parse action to verify that the date is a valid date''' + from datetime import date + year, month, day = toks[::2] + try: + date(year, month, day) + except ValueError: + raise ParseException(instring, loc, "invalid date given") + + integer = Word(nums) + date_str = integer + '/' + integer + '/' + integer + + # add parse actions + integer.set_parse_action(convert_to_int) + date_str.set_parse_action(is_valid_date) + + Successful parse - note that integer fields are converted to ints: + + .. testcode:: + + print(date_str.parse_string("1999/12/31")) + + prints: + + .. testoutput:: + + [1999, '/', 12, '/', 31] + + Failure - invalid date: + + .. testcode:: + + date_str.parse_string("1999/13/31") + + prints: + + .. testoutput:: + + Traceback (most recent call last): + ParseException: invalid date given, found '1999' ... + """ + if list(fns) == [None]: + self.parseAction.clear() + return self + + if not all(callable(fn) for fn in fns): + raise TypeError("parse actions must be callable") + self.parseAction[:] = [_trim_arity(fn) for fn in fns] + self.callDuringTry = kwargs.get( + "call_during_try", kwargs.get("callDuringTry", False) + ) + + return self + + def add_parse_action(self, *fns: ParseAction, **kwargs: Any) -> ParserElement: + """ + Add one or more parse actions to expression's list of parse actions. See :class:`set_parse_action`. + + See examples in :class:`copy`. + """ + self.parseAction += [_trim_arity(fn) for fn in fns] + self.callDuringTry = self.callDuringTry or kwargs.get( + "call_during_try", kwargs.get("callDuringTry", False) + ) + return self + + def add_condition(self, *fns: ParseCondition, **kwargs: Any) -> ParserElement: + """Add a boolean predicate function to expression's list of parse actions. See + :class:`set_parse_action` for function call signatures. Unlike ``set_parse_action``, + functions passed to ``add_condition`` need to return boolean success/fail of the condition. + + Optional keyword arguments: + + - ``message`` = define a custom message to be used in the raised exception + - ``fatal`` = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise + ParseException + - ``call_during_try`` = boolean to indicate if this method should be called during internal tryParse calls, + default=False + + Example: + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> integer = Word(nums).set_parse_action(lambda toks: int(toks[0])) + >>> year_int = integer.copy().add_condition( + ... lambda toks: toks[0] >= 2000, + ... message="Only support years 2000 and later") + >>> date_str = year_int + '/' + integer + '/' + integer + + >>> result = date_str.parse_string("1999/12/31") + Traceback (most recent call last): + ParseException: Only support years 2000 and later... + """ + for fn in fns: + self.parseAction.append( + condition_as_parse_action( + fn, + message=str(kwargs.get("message")), + fatal=bool(kwargs.get("fatal", False)), + ) + ) + + self.callDuringTry = self.callDuringTry or kwargs.get( + "call_during_try", kwargs.get("callDuringTry", False) + ) + return self + + def set_fail_action(self, fn: ParseFailAction) -> ParserElement: + """ + Define action to perform if parsing fails at this expression. + Fail acton fn is a callable function that takes the arguments + ``fn(s, loc, expr, err)`` where: + + - ``s`` = string being parsed + - ``loc`` = location where expression match was attempted and failed + - ``expr`` = the parse expression that failed + - ``err`` = the exception thrown + + The function returns no value. It may throw :class:`ParseFatalException` + if it is desired to stop parsing immediately.""" + self.failAction = fn + return self + + def _skipIgnorables(self, instring: str, loc: int) -> int: + if not self.ignoreExprs: + return loc + exprsFound = True + ignore_expr_fns = [e._parse for e in self.ignoreExprs] + last_loc = loc + while exprsFound: + exprsFound = False + for ignore_fn in ignore_expr_fns: + try: + while 1: + loc, dummy = ignore_fn(instring, loc) + exprsFound = True + except ParseException: + pass + # check if all ignore exprs matched but didn't actually advance the parse location + if loc == last_loc: + break + last_loc = loc + return loc + + def preParse(self, instring: str, loc: int) -> int: + if self.ignoreExprs: + loc = self._skipIgnorables(instring, loc) + + if self.skipWhitespace: + instrlen = len(instring) + white_chars = self.whiteChars + while loc < instrlen and instring[loc] in white_chars: + loc += 1 + + return loc + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + return loc, [] + + def postParse(self, instring, loc, tokenlist): + return tokenlist + + # @profile + def _parseNoCache( + self, instring, loc, do_actions=True, callPreParse=True + ) -> tuple[int, ParseResults]: + debugging = self.debug # and do_actions) + len_instring = len(instring) + + if debugging or self.failAction: + # print("Match {} at loc {}({}, {})".format(self, loc, lineno(loc, instring), col(loc, instring))) + try: + if callPreParse and self.callPreparse: + pre_loc = self.preParse(instring, loc) + else: + pre_loc = loc + tokens_start = pre_loc + if self.debugActions.debug_try: + self.debugActions.debug_try(instring, tokens_start, self, False) + if self.mayIndexError or pre_loc >= len_instring: + try: + loc, tokens = self.parseImpl(instring, pre_loc, do_actions) + except IndexError: + raise ParseException(instring, len_instring, self.errmsg, self) + else: + loc, tokens = self.parseImpl(instring, pre_loc, do_actions) + except Exception as err: + # print("Exception raised:", err) + if self.debugActions.debug_fail: + self.debugActions.debug_fail( + instring, tokens_start, self, err, False + ) + if self.failAction: + self.failAction(instring, tokens_start, self, err) + raise + else: + if callPreParse and self.callPreparse: + pre_loc = self.preParse(instring, loc) + else: + pre_loc = loc + tokens_start = pre_loc + if self.mayIndexError or pre_loc >= len_instring: + try: + loc, tokens = self.parseImpl(instring, pre_loc, do_actions) + except IndexError: + raise ParseException(instring, len_instring, self.errmsg, self) + else: + loc, tokens = self.parseImpl(instring, pre_loc, do_actions) + + tokens = self.postParse(instring, loc, tokens) + + ret_tokens = ParseResults( + tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults + ) + if self.parseAction and (do_actions or self.callDuringTry): + if debugging: + try: + for fn in self.parseAction: + try: + tokens = fn(instring, tokens_start, ret_tokens) # type: ignore [call-arg, arg-type] + except IndexError as parse_action_exc: + exc = ParseException("exception raised in parse action") + raise exc from parse_action_exc + + if tokens is not None and tokens is not ret_tokens: + ret_tokens = ParseResults( + tokens, + self.resultsName, + asList=self.saveAsList + and isinstance(tokens, (ParseResults, list)), + modal=self.modalResults, + ) + except Exception as err: + # print "Exception raised in user parse action:", err + if self.debugActions.debug_fail: + self.debugActions.debug_fail( + instring, tokens_start, self, err, False + ) + raise + else: + for fn in self.parseAction: + try: + tokens = fn(instring, tokens_start, ret_tokens) # type: ignore [call-arg, arg-type] + except IndexError as parse_action_exc: + exc = ParseException("exception raised in parse action") + raise exc from parse_action_exc + + if tokens is not None and tokens is not ret_tokens: + ret_tokens = ParseResults( + tokens, + self.resultsName, + asList=self.saveAsList + and isinstance(tokens, (ParseResults, list)), + modal=self.modalResults, + ) + if debugging: + # print("Matched", self, "->", ret_tokens.as_list()) + if self.debugActions.debug_match: + self.debugActions.debug_match( + instring, tokens_start, loc, self, ret_tokens, False + ) + + return loc, ret_tokens + + def try_parse( + self, + instring: str, + loc: int, + *, + raise_fatal: bool = False, + do_actions: bool = False, + ) -> int: + try: + return self._parse(instring, loc, do_actions=do_actions)[0] + except ParseFatalException: + if raise_fatal: + raise + raise ParseException(instring, loc, self.errmsg, self) + + def can_parse_next(self, instring: str, loc: int, do_actions: bool = False) -> bool: + try: + self.try_parse(instring, loc, do_actions=do_actions) + except (ParseException, IndexError): + return False + else: + return True + + # cache for left-recursion in Forward references + recursion_lock = RLock() + recursion_memos: collections.abc.MutableMapping[ + tuple[int, Forward, bool], tuple[int, Union[ParseResults, Exception]] + ] = {} + + class _CacheType(typing.Protocol): + """ + Class to be used for packrat and left-recursion cacheing of results + and exceptions. + """ + + not_in_cache: bool + + def get(self, *args) -> typing.Any: ... + + def set(self, *args) -> None: ... + + def clear(self) -> None: ... + + class NullCache(dict): + """ + A null cache type for initialization of the packrat_cache class variable. + If/when enable_packrat() is called, this null cache will be replaced by a + proper _CacheType class instance. + """ + + not_in_cache: bool = True + + def get(self, *args) -> typing.Any: ... + + def set(self, *args) -> None: ... + + def clear(self) -> None: ... + + # class-level argument cache for optimizing repeated calls when backtracking + # through recursive expressions + packrat_cache: _CacheType = NullCache() + packrat_cache_lock = RLock() + packrat_cache_stats = [0, 0] + + # this method gets repeatedly called during backtracking with the same arguments - + # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression + def _parseCache( + self, instring, loc, do_actions=True, callPreParse=True + ) -> tuple[int, ParseResults]: + HIT, MISS = 0, 1 + lookup = (self, instring, loc, callPreParse, do_actions) + with ParserElement.packrat_cache_lock: + cache = ParserElement.packrat_cache + value = cache.get(lookup) + if value is cache.not_in_cache: + ParserElement.packrat_cache_stats[MISS] += 1 + try: + value = self._parseNoCache(instring, loc, do_actions, callPreParse) + except ParseBaseException as pe: + # cache a copy of the exception, without the traceback + cache.set(lookup, pe.__class__(*pe.args)) + raise + else: + cache.set(lookup, (value[0], value[1].copy(), loc)) + return value + else: + ParserElement.packrat_cache_stats[HIT] += 1 + if self.debug and self.debugActions.debug_try: + try: + self.debugActions.debug_try(instring, loc, self, cache_hit=True) # type: ignore [call-arg] + except TypeError: + pass + if isinstance(value, Exception): + if self.debug and self.debugActions.debug_fail: + try: + self.debugActions.debug_fail( + instring, loc, self, value, cache_hit=True # type: ignore [call-arg] + ) + except TypeError: + pass + raise value + + value = cast(tuple[int, ParseResults, int], value) + loc_, result, endloc = value[0], value[1].copy(), value[2] + if self.debug and self.debugActions.debug_match: + try: + self.debugActions.debug_match( + instring, loc_, endloc, self, result, cache_hit=True # type: ignore [call-arg] + ) + except TypeError: + pass + + return loc_, result + + _parse = _parseNoCache + + @staticmethod + def reset_cache() -> None: + with ParserElement.packrat_cache_lock: + ParserElement.packrat_cache.clear() + ParserElement.packrat_cache_stats[:] = [0] * len( + ParserElement.packrat_cache_stats + ) + ParserElement.recursion_memos.clear() + + # class attributes to keep caching status + _packratEnabled = False + _left_recursion_enabled = False + + @staticmethod + def disable_memoization() -> None: + """ + Disables active Packrat or Left Recursion parsing and their memoization + + This method also works if neither Packrat nor Left Recursion are enabled. + This makes it safe to call before activating Packrat nor Left Recursion + to clear any previous settings. + """ + with ParserElement.packrat_cache_lock: + ParserElement.reset_cache() + ParserElement._left_recursion_enabled = False + ParserElement._packratEnabled = False + ParserElement._parse = ParserElement._parseNoCache + + @staticmethod + def enable_left_recursion( + cache_size_limit: typing.Optional[int] = None, *, force=False + ) -> None: + """ + Enables "bounded recursion" parsing, which allows for both direct and indirect + left-recursion. During parsing, left-recursive :class:`Forward` elements are + repeatedly matched with a fixed recursion depth that is gradually increased + until finding the longest match. + + Example: + + .. testcode:: + + import pyparsing as pp + pp.ParserElement.enable_left_recursion() + + E = pp.Forward("E") + num = pp.Word(pp.nums) + + # match `num`, or `num '+' num`, or `num '+' num '+' num`, ... + E <<= E + '+' - num | num + + print(E.parse_string("1+2+3+4")) + + prints: + + .. testoutput:: + + ['1', '+', '2', '+', '3', '+', '4'] + + Recursion search naturally memoizes matches of ``Forward`` elements and may + thus skip reevaluation of parse actions during backtracking. This may break + programs with parse actions which rely on strict ordering of side-effects. + + Parameters: + + - ``cache_size_limit`` - (default=``None``) - memoize at most this many + ``Forward`` elements during matching; if ``None`` (the default), + memoize all ``Forward`` elements. + + Bounded Recursion parsing works similar but not identical to Packrat parsing, + thus the two cannot be used together. Use ``force=True`` to disable any + previous, conflicting settings. + """ + with ParserElement.packrat_cache_lock: + if force: + ParserElement.disable_memoization() + elif ParserElement._packratEnabled: + raise RuntimeError("Packrat and Bounded Recursion are not compatible") + if cache_size_limit is None: + ParserElement.recursion_memos = _UnboundedMemo() + elif cache_size_limit > 0: + ParserElement.recursion_memos = _LRUMemo(capacity=cache_size_limit) # type: ignore[assignment] + else: + raise NotImplementedError(f"Memo size of {cache_size_limit}") + ParserElement._left_recursion_enabled = True + + @staticmethod + def enable_packrat( + cache_size_limit: Union[int, None] = 128, *, force: bool = False + ) -> None: + """ + Enables "packrat" parsing, which adds memoizing to the parsing logic. + Repeated parse attempts at the same string location (which happens + often in many complex grammars) can immediately return a cached value, + instead of re-executing parsing/validating code. Memoizing is done of + both valid results and parsing exceptions. + + Parameters: + + - ``cache_size_limit`` - (default= ``128``) - if an integer value is provided + will limit the size of the packrat cache; if None is passed, then + the cache size will be unbounded; if 0 is passed, the cache will + be effectively disabled. + + This speedup may break existing programs that use parse actions that + have side-effects. For this reason, packrat parsing is disabled when + you first import pyparsing. To activate the packrat feature, your + program must call the class method :class:`ParserElement.enable_packrat`. + For best results, call ``enable_packrat()`` immediately after + importing pyparsing. + + .. Can't really be doctested, alas + + Example:: + + import pyparsing + pyparsing.ParserElement.enable_packrat() + + Packrat parsing works similar but not identical to Bounded Recursion parsing, + thus the two cannot be used together. Use ``force=True`` to disable any + previous, conflicting settings. + """ + with ParserElement.packrat_cache_lock: + if force: + ParserElement.disable_memoization() + elif ParserElement._left_recursion_enabled: + raise RuntimeError("Packrat and Bounded Recursion are not compatible") + + if ParserElement._packratEnabled: + return + + ParserElement._packratEnabled = True + if cache_size_limit is None: + ParserElement.packrat_cache = _UnboundedCache() + else: + ParserElement.packrat_cache = _FifoCache(cache_size_limit) + ParserElement._parse = ParserElement._parseCache + + def parse_string( + self, instring: str, parse_all: bool = False, *, parseAll: bool = False + ) -> ParseResults: + """ + Parse a string with respect to the parser definition. This function is intended as the primary interface to the + client code. + + :param instring: The input string to be parsed. + :param parse_all: If set, the entire input string must match the grammar. + :param parseAll: retained for pre-PEP8 compatibility, will be removed in a future release. + :raises ParseException: Raised if ``parse_all`` is set and the input string does not match the whole grammar. + :returns: the parsed data as a :class:`ParseResults` object, which may be accessed as a `list`, a `dict`, or + an object with attributes if the given parser includes results names. + + If the input string is required to match the entire grammar, ``parse_all`` flag must be set to ``True``. This + is also equivalent to ending the grammar with :class:`StringEnd`\\ (). + + To report proper column numbers, ``parse_string`` operates on a copy of the input string where all tabs are + converted to spaces (8 spaces per tab, as per the default in ``string.expandtabs``). If the input string + contains tabs and the grammar uses parse actions that use the ``loc`` argument to index into the string + being parsed, one can ensure a consistent view of the input string by doing one of the following: + + - calling ``parse_with_tabs`` on your grammar before calling ``parse_string`` (see :class:`parse_with_tabs`), + - define your parse action using the full ``(s,loc,toks)`` signature, and reference the input string using the + parse action's ``s`` argument, or + - explicitly expand the tabs in your input string before calling ``parse_string``. + + Examples: + + By default, partial matches are OK. + + .. doctest:: + + >>> res = Word('a').parse_string('aaaaabaaa') + >>> print(res) + ['aaaaa'] + + The parsing behavior varies by the inheriting class of this abstract class. Please refer to the children + directly to see more examples. + + It raises an exception if parse_all flag is set and instring does not match the whole grammar. + + .. doctest:: + + >>> res = Word('a').parse_string('aaaaabaaa', parse_all=True) + Traceback (most recent call last): + ParseException: Expected end of text, found 'b' ... + """ + parseAll = parse_all or parseAll + + ParserElement.reset_cache() + if not self.streamlined: + self.streamline() + for e in self.ignoreExprs: + e.streamline() + if not self.keepTabs: + instring = instring.expandtabs() + try: + loc, tokens = self._parse(instring, 0) + if parseAll: + loc = self.preParse(instring, loc) + se = Empty() + StringEnd().set_debug(False) + se._parse(instring, loc) + except _ParseActionIndexError as pa_exc: + raise pa_exc.exc + except ParseBaseException as exc: + if ParserElement.verbose_stacktrace: + raise + + # catch and re-raise exception from here, clearing out pyparsing internal stack trace + raise exc.with_traceback(None) + else: + return tokens + + def scan_string( + self, + instring: str, + max_matches: int = _MAX_INT, + overlap: bool = False, + always_skip_whitespace=True, + *, + debug: bool = False, + maxMatches: int = _MAX_INT, + ) -> Generator[tuple[ParseResults, int, int], None, None]: + """ + Scan the input string for expression matches. Each match will return the + matching tokens, start location, and end location. May be called with optional + ``max_matches`` argument, to clip scanning after 'n' matches are found. If + ``overlap`` is specified, then overlapping matches will be reported. + + Note that the start and end locations are reported relative to the string + being parsed. See :class:`parse_string` for more information on parsing + strings with embedded tabs. + + Example: + + .. testcode:: + + source = "sldjf123lsdjjkf345sldkjf879lkjsfd987" + print(source) + for tokens, start, end in Word(alphas).scan_string(source): + print(' '*start + '^'*(end-start)) + print(' '*start + tokens[0]) + + prints: + + .. testoutput:: + + sldjf123lsdjjkf345sldkjf879lkjsfd987 + ^^^^^ + sldjf + ^^^^^^^ + lsdjjkf + ^^^^^^ + sldkjf + ^^^^^^ + lkjsfd + """ + maxMatches = min(maxMatches, max_matches) + if not self.streamlined: + self.streamline() + for e in self.ignoreExprs: + e.streamline() + + if not self.keepTabs: + instring = str(instring).expandtabs() + instrlen = len(instring) + loc = 0 + if always_skip_whitespace: + preparser = Empty() + preparser.ignoreExprs = self.ignoreExprs + preparser.whiteChars = self.whiteChars + preparseFn = preparser.preParse + else: + preparseFn = self.preParse + parseFn = self._parse + ParserElement.resetCache() + matches = 0 + try: + while loc <= instrlen and matches < maxMatches: + try: + preloc: int = preparseFn(instring, loc) + nextLoc: int + tokens: ParseResults + nextLoc, tokens = parseFn(instring, preloc, callPreParse=False) + except ParseException: + loc = preloc + 1 + else: + if nextLoc > loc: + matches += 1 + if debug: + print( + { + "tokens": tokens.asList(), + "start": preloc, + "end": nextLoc, + } + ) + yield tokens, preloc, nextLoc + if overlap: + nextloc = preparseFn(instring, loc) + if nextloc > loc: + loc = nextLoc + else: + loc += 1 + else: + loc = nextLoc + else: + loc = preloc + 1 + except ParseBaseException as exc: + if ParserElement.verbose_stacktrace: + raise + + # catch and re-raise exception from here, clears out pyparsing internal stack trace + raise exc.with_traceback(None) + + def transform_string(self, instring: str, *, debug: bool = False) -> str: + """ + Extension to :class:`scan_string`, to modify matching text with modified tokens that may + be returned from a parse action. To use ``transform_string``, define a grammar and + attach a parse action to it that modifies the returned token list. + Invoking ``transform_string()`` on a target string will then scan for matches, + and replace the matched text patterns according to the logic in the parse + action. ``transform_string()`` returns the resulting transformed string. + + Example: + + .. testcode:: + + quote = '''now is the winter of our discontent, + made glorious summer by this sun of york.''' + + wd = Word(alphas) + wd.set_parse_action(lambda toks: toks[0].title()) + + print(wd.transform_string(quote)) + + prints: + + .. testoutput:: + + Now Is The Winter Of Our Discontent, + Made Glorious Summer By This Sun Of York. + """ + out: list[str] = [] + lastE = 0 + # force preservation of s, to minimize unwanted transformation of string, and to + # keep string locs straight between transform_string and scan_string + self.keepTabs = True + try: + for t, s, e in self.scan_string(instring, debug=debug): + if s > lastE: + out.append(instring[lastE:s]) + lastE = e + + if not t: + continue + + if isinstance(t, ParseResults): + out += t.as_list() + elif isinstance(t, Iterable) and not isinstance(t, str_type): + out.extend(t) + else: + out.append(t) + + out.append(instring[lastE:]) + out = [o for o in out if o] + return "".join([str(s) for s in _flatten(out)]) + except ParseBaseException as exc: + if ParserElement.verbose_stacktrace: + raise + + # catch and re-raise exception from here, clears out pyparsing internal stack trace + raise exc.with_traceback(None) + + def search_string( + self, + instring: str, + max_matches: int = _MAX_INT, + *, + debug: bool = False, + maxMatches: int = _MAX_INT, + ) -> ParseResults: + """ + Another extension to :class:`scan_string`, simplifying the access to the tokens found + to match the given parse expression. May be called with optional + ``max_matches`` argument, to clip searching after 'n' matches are found. + + Example: + + .. testcode:: + + quote = '''More than Iron, more than Lead, + more than Gold I need Electricity''' + + # a capitalized word starts with an uppercase letter, + # followed by zero or more lowercase letters + cap_word = Word(alphas.upper(), alphas.lower()) + + print(cap_word.search_string(quote)) + + # the sum() builtin can be used to merge results + # into a single ParseResults object + print(sum(cap_word.search_string(quote))) + + prints: + + .. testoutput:: + + [['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']] + ['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity'] + """ + maxMatches = min(maxMatches, max_matches) + try: + return ParseResults( + [ + t + for t, s, e in self.scan_string( + instring, maxMatches, always_skip_whitespace=False, debug=debug + ) + ] + ) + except ParseBaseException as exc: + if ParserElement.verbose_stacktrace: + raise + + # catch and re-raise exception from here, clears out pyparsing internal stack trace + raise exc.with_traceback(None) + + def split( + self, + instring: str, + maxsplit: int = _MAX_INT, + include_separators: bool = False, + *, + includeSeparators=False, + ) -> Generator[str, None, None]: + """ + Generator method to split a string using the given expression as a separator. + May be called with optional ``maxsplit`` argument, to limit the number of splits; + and the optional ``include_separators`` argument (default= ``False``), if the separating + matching text should be included in the split results. + + Example: + + .. testcode:: + + punc = one_of(list(".,;:/-!?")) + print(list(punc.split( + "This, this?, this sentence, is badly punctuated!"))) + + prints: + + .. testoutput:: + + ['This', ' this', '', ' this sentence', ' is badly punctuated', ''] + """ + includeSeparators = includeSeparators or include_separators + last = 0 + for t, s, e in self.scan_string(instring, max_matches=maxsplit): + yield instring[last:s] + if includeSeparators: + yield t[0] + last = e + yield instring[last:] + + def __add__(self, other) -> ParserElement: + """ + Implementation of ``+`` operator - returns :class:`And`. Adding strings to a :class:`ParserElement` + converts them to :class:`Literal`\\ s by default. + + Example: + + .. testcode:: + + greet = Word(alphas) + "," + Word(alphas) + "!" + hello = "Hello, World!" + print(hello, "->", greet.parse_string(hello)) + + prints: + + .. testoutput:: + + Hello, World! -> ['Hello', ',', 'World', '!'] + + ``...`` may be used as a parse expression as a short form of :class:`SkipTo`: + + .. testcode:: + + Literal('start') + ... + Literal('end') + + is equivalent to: + + .. testcode:: + + Literal('start') + SkipTo('end')("_skipped*") + Literal('end') + + Note that the skipped text is returned with '_skipped' as a results name, + and to support having multiple skips in the same parser, the value returned is + a list of all skipped text. + """ + if other is Ellipsis: + return _PendingSkip(self) + + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return And([self, other]) + + def __radd__(self, other) -> ParserElement: + """ + Implementation of ``+`` operator when left operand is not a :class:`ParserElement` + """ + if other is Ellipsis: + return SkipTo(self)("_skipped*") + self + + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return other + self + + def __sub__(self, other) -> ParserElement: + """ + Implementation of ``-`` operator, returns :class:`And` with error stop + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return self + And._ErrorStop() + other + + def __rsub__(self, other) -> ParserElement: + """ + Implementation of ``-`` operator when left operand is not a :class:`ParserElement` + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return other - self + + def __mul__(self, other) -> ParserElement: + """ + Implementation of ``*`` operator, allows use of ``expr * 3`` in place of + ``expr + expr + expr``. Expressions may also be multiplied by a 2-integer + tuple, similar to ``{min, max}`` multipliers in regular expressions. Tuples + may also include ``None`` as in: + + - ``expr*(n, None)`` or ``expr*(n, )`` is equivalent + to ``expr*n + ZeroOrMore(expr)`` + (read as "at least n instances of ``expr``") + - ``expr*(None, n)`` is equivalent to ``expr*(0, n)`` + (read as "0 to n instances of ``expr``") + - ``expr*(None, None)`` is equivalent to ``ZeroOrMore(expr)`` + - ``expr*(1, None)`` is equivalent to ``OneOrMore(expr)`` + + Note that ``expr*(None, n)`` does not raise an exception if + more than n exprs exist in the input stream; that is, + ``expr*(None, n)`` does not enforce a maximum number of expr + occurrences. If this behavior is desired, then write + ``expr*(None, n) + ~expr`` + """ + if other is Ellipsis: + other = (0, None) + elif isinstance(other, tuple) and other[:1] == (Ellipsis,): + other = ((0,) + other[1:] + (None,))[:2] + + if not isinstance(other, (int, tuple)): + return NotImplemented + + if isinstance(other, int): + minElements, optElements = other, 0 + else: + other = tuple(o if o is not Ellipsis else None for o in other) + other = (other + (None, None))[:2] + if other[0] is None: + other = (0, other[1]) + if isinstance(other[0], int) and other[1] is None: + if other[0] == 0: + return ZeroOrMore(self) + if other[0] == 1: + return OneOrMore(self) + else: + return self * other[0] + ZeroOrMore(self) + elif isinstance(other[0], int) and isinstance(other[1], int): + minElements, optElements = other + optElements -= minElements + else: + return NotImplemented + + if minElements < 0: + raise ValueError("cannot multiply ParserElement by negative value") + if optElements < 0: + raise ValueError( + "second tuple value must be greater or equal to first tuple value" + ) + if minElements == optElements == 0: + return And([]) + + if optElements: + + def makeOptionalList(n): + if n > 1: + return Opt(self + makeOptionalList(n - 1)) + else: + return Opt(self) + + if minElements: + if minElements == 1: + ret = self + makeOptionalList(optElements) + else: + ret = And([self] * minElements) + makeOptionalList(optElements) + else: + ret = makeOptionalList(optElements) + else: + if minElements == 1: + ret = self + else: + ret = And([self] * minElements) + return ret + + def __rmul__(self, other) -> ParserElement: + return self.__mul__(other) + + def __or__(self, other) -> ParserElement: + """ + Implementation of ``|`` operator - returns :class:`MatchFirst` + + .. versionchanged:: 3.1.0 + Support ``expr | ""`` as a synonym for ``Optional(expr)``. + """ + if other is Ellipsis: + return _PendingSkip(self, must_skip=True) + + if isinstance(other, str_type): + # `expr | ""` is equivalent to `Opt(expr)` + if other == "": + return Opt(self) + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return MatchFirst([self, other]) + + def __ror__(self, other) -> ParserElement: + """ + Implementation of ``|`` operator when left operand is not a :class:`ParserElement` + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return other | self + + def __xor__(self, other) -> ParserElement: + """ + Implementation of ``^`` operator - returns :class:`Or` + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return Or([self, other]) + + def __rxor__(self, other) -> ParserElement: + """ + Implementation of ``^`` operator when left operand is not a :class:`ParserElement` + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return other ^ self + + def __and__(self, other) -> ParserElement: + """ + Implementation of ``&`` operator - returns :class:`Each` + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return Each([self, other]) + + def __rand__(self, other) -> ParserElement: + """ + Implementation of ``&`` operator when left operand is not a :class:`ParserElement` + """ + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return other & self + + def __invert__(self) -> ParserElement: + """ + Implementation of ``~`` operator - returns :class:`NotAny` + """ + return NotAny(self) + + # disable __iter__ to override legacy use of sequential access to __getitem__ to + # iterate over a sequence + __iter__ = None + + def __getitem__(self, key): + """ + use ``[]`` indexing notation as a short form for expression repetition: + + - ``expr[n]`` is equivalent to ``expr*n`` + - ``expr[m, n]`` is equivalent to ``expr*(m, n)`` + - ``expr[n, ...]`` or ``expr[n,]`` is equivalent + to ``expr*n + ZeroOrMore(expr)`` + (read as "at least n instances of ``expr``") + - ``expr[..., n]`` is equivalent to ``expr*(0, n)`` + (read as "0 to n instances of ``expr``") + - ``expr[...]`` and ``expr[0, ...]`` are equivalent to ``ZeroOrMore(expr)`` + - ``expr[1, ...]`` is equivalent to ``OneOrMore(expr)`` + + ``None`` may be used in place of ``...``. + + Note that ``expr[..., n]`` and ``expr[m, n]`` do not raise an exception + if more than ``n`` ``expr``\\ s exist in the input stream. If this behavior is + desired, then write ``expr[..., n] + ~expr``. + + For repetition with a stop_on expression, use slice notation: + + - ``expr[...: end_expr]`` and ``expr[0, ...: end_expr]`` are equivalent to ``ZeroOrMore(expr, stop_on=end_expr)`` + - ``expr[1, ...: end_expr]`` is equivalent to ``OneOrMore(expr, stop_on=end_expr)`` + + .. versionchanged:: 3.1.0 + Support for slice notation. + """ + + stop_on_defined = False + stop_on = NoMatch() + if isinstance(key, slice): + key, stop_on = key.start, key.stop + if key is None: + key = ... + stop_on_defined = True + elif isinstance(key, tuple) and isinstance(key[-1], slice): + key, stop_on = (key[0], key[1].start), key[1].stop + stop_on_defined = True + + # convert single arg keys to tuples + if isinstance(key, str_type): + key = (key,) + try: + iter(key) + except TypeError: + key = (key, key) + + if len(key) > 2: + raise TypeError( + f"only 1 or 2 index arguments supported ({key[:5]}{f'... [{len(key)}]' if len(key) > 5 else ''})" + ) + + # clip to 2 elements + ret = self * tuple(key[:2]) + ret = typing.cast(_MultipleMatch, ret) + + if stop_on_defined: + ret.stopOn(stop_on) + + return ret + + def __call__(self, name: typing.Optional[str] = None) -> ParserElement: + """ + Shortcut for :class:`set_results_name`, with ``list_all_matches=False``. + + If ``name`` is given with a trailing ``'*'`` character, then ``list_all_matches`` will be + passed as ``True``. + + If ``name`` is omitted, same as calling :class:`copy`. + + Example: + + .. testcode:: + + # these are equivalent + userdata = ( + Word(alphas).set_results_name("name") + + Word(nums + "-").set_results_name("socsecno") + ) + + userdata = Word(alphas)("name") + Word(nums + "-")("socsecno") + """ + if name is not None: + return self._setResultsName(name) + + return self.copy() + + def suppress(self) -> ParserElement: + """ + Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from + cluttering up returned output. + """ + return Suppress(self) + + def ignore_whitespace(self, recursive: bool = True) -> ParserElement: + """ + Enables the skipping of whitespace before matching the characters in the + :class:`ParserElement`'s defined pattern. + + :param recursive: If ``True`` (the default), also enable whitespace skipping in child elements (if any) + """ + self.skipWhitespace = True + return self + + def leave_whitespace(self, recursive: bool = True) -> ParserElement: + """ + Disables the skipping of whitespace before matching the characters in the + :class:`ParserElement`'s defined pattern. This is normally only used internally by + the pyparsing module, but may be needed in some whitespace-sensitive grammars. + + :param recursive: If true (the default), also disable whitespace skipping in child elements (if any) + """ + self.skipWhitespace = False + return self + + def set_whitespace_chars( + self, chars: Union[set[str], str], copy_defaults: bool = False + ) -> ParserElement: + """ + Overrides the default whitespace chars + """ + self.skipWhitespace = True + self.whiteChars = set(chars) + self.copyDefaultWhiteChars = copy_defaults + return self + + def parse_with_tabs(self) -> ParserElement: + """ + Overrides default behavior to expand ```` s to spaces before parsing the input string. + Must be called before ``parse_string`` when the input grammar contains elements that + match ```` characters. + """ + self.keepTabs = True + return self + + def ignore(self, other: ParserElement) -> ParserElement: + """ + Define expression to be ignored (e.g., comments) while doing pattern + matching; may be called repeatedly, to define multiple comment or other + ignorable patterns. + + Example: + + .. doctest:: + + >>> patt = Word(alphas)[...] + >>> print(patt.parse_string('ablaj /* comment */ lskjd')) + ['ablaj'] + + >>> patt = Word(alphas)[...].ignore(c_style_comment) + >>> print(patt.parse_string('ablaj /* comment */ lskjd')) + ['ablaj', 'lskjd'] + """ + if isinstance(other, str_type): + other = Suppress(other) + + if isinstance(other, Suppress): + if other not in self.ignoreExprs: + self.ignoreExprs.append(other) + else: + self.ignoreExprs.append(Suppress(other.copy())) + return self + + def set_debug_actions( + self, + start_action: DebugStartAction, + success_action: DebugSuccessAction, + exception_action: DebugExceptionAction, + ) -> ParserElement: + """ + Customize display of debugging messages while doing pattern matching: + + :param start_action: method to be called when an expression is about to be parsed; + should have the signature:: + + fn(input_string: str, + location: int, + expression: ParserElement, + cache_hit: bool) + + :param success_action: method to be called when an expression has successfully parsed; + should have the signature:: + + fn(input_string: str, + start_location: int, + end_location: int, + expression: ParserELement, + parsed_tokens: ParseResults, + cache_hit: bool) + + :param exception_action: method to be called when expression fails to parse; + should have the signature:: + + fn(input_string: str, + location: int, + expression: ParserElement, + exception: Exception, + cache_hit: bool) + """ + self.debugActions = self.DebugActions( + start_action or _default_start_debug_action, # type: ignore[truthy-function] + success_action or _default_success_debug_action, # type: ignore[truthy-function] + exception_action or _default_exception_debug_action, # type: ignore[truthy-function] + ) + self.debug = True + return self + + def set_debug(self, flag: bool = True, recurse: bool = False) -> ParserElement: + """ + Enable display of debugging messages while doing pattern matching. + Set ``flag`` to ``True`` to enable, ``False`` to disable. + Set ``recurse`` to ``True`` to set the debug flag on this expression and all sub-expressions. + + Example: + + .. testcode:: + + wd = Word(alphas).set_name("alphaword") + integer = Word(nums).set_name("numword") + term = wd | integer + + # turn on debugging for wd + wd.set_debug() + + term[1, ...].parse_string("abc 123 xyz 890") + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + Match alphaword at loc 0(1,1) + abc 123 xyz 890 + ^ + Matched alphaword -> ['abc'] + Match alphaword at loc 4(1,5) + abc 123 xyz 890 + ^ + Match alphaword failed, ParseException raised: Expected alphaword, ... + Match alphaword at loc 8(1,9) + abc 123 xyz 890 + ^ + Matched alphaword -> ['xyz'] + Match alphaword at loc 12(1,13) + abc 123 xyz 890 + ^ + Match alphaword failed, ParseException raised: Expected alphaword, ... + abc 123 xyz 890 + ^ + Match alphaword failed, ParseException raised: Expected alphaword, found end of text ... + + The output shown is that produced by the default debug actions - custom debug actions can be + specified using :meth:`set_debug_actions`. Prior to attempting + to match the ``wd`` expression, the debugging message ``"Match at loc (,)"`` + is shown. Then if the parse succeeds, a ``"Matched"`` message is shown, or an ``"Exception raised"`` + message is shown. Also note the use of :meth:`set_name` to assign a human-readable name to the expression, + which makes debugging and exception messages easier to understand - for instance, the default + name created for the :class:`Word` expression without calling :meth:`set_name` is ``"W:(A-Za-z)"``. + + .. versionchanged:: 3.1.0 + ``recurse`` argument added. + """ + if recurse: + for expr in self.visit_all(): + expr.set_debug(flag, recurse=False) + return self + + if flag: + self.set_debug_actions( + _default_start_debug_action, + _default_success_debug_action, + _default_exception_debug_action, + ) + else: + self.debug = False + return self + + @property + def default_name(self) -> str: + if self._defaultName is None: + self._defaultName = self._generateDefaultName() + return self._defaultName + + @abstractmethod + def _generateDefaultName(self) -> str: + """ + Child classes must define this method, which defines how the ``default_name`` is set. + """ + + def set_name(self, name: typing.Optional[str]) -> ParserElement: + """ + Define name for this expression, makes debugging and exception messages clearer. If + `__diag__.enable_debug_on_named_expressions` is set to True, setting a name will also + enable debug for this expression. + + If `name` is None, clears any custom name for this expression, and clears the + debug flag is it was enabled via `__diag__.enable_debug_on_named_expressions`. + + Example: + + .. doctest:: + + >>> integer = Word(nums) + >>> integer.parse_string("ABC") + Traceback (most recent call last): + ParseException: Expected W:(0-9) (at char 0), (line:1, col:1) + + >>> integer.set_name("integer") + integer + >>> integer.parse_string("ABC") + Traceback (most recent call last): + ParseException: Expected integer (at char 0), (line:1, col:1) + + .. versionchanged:: 3.1.0 + Accept ``None`` as the ``name`` argument. + """ + self.customName = name # type: ignore[assignment] + self.errmsg = f"Expected {str(self)}" + + if __diag__.enable_debug_on_named_expressions: + self.set_debug(name is not None) + + return self + + @property + def name(self) -> str: + # This will use a user-defined name if available, but otherwise defaults back to the auto-generated name + return self.customName if self.customName is not None else self.default_name + + @name.setter + def name(self, new_name) -> None: + self.set_name(new_name) + + def __str__(self) -> str: + return self.name + + def __repr__(self) -> str: + return str(self) + + def streamline(self) -> ParserElement: + self.streamlined = True + self._defaultName = None + return self + + def recurse(self) -> list[ParserElement]: + return [] + + def _checkRecursion(self, parseElementList): + subRecCheckList = parseElementList[:] + [self] + for e in self.recurse(): + e._checkRecursion(subRecCheckList) + + def validate(self, validateTrace=None) -> None: + """ + .. deprecated:: 3.0.0 + Do not use to check for left recursion. + + Check defined expressions for valid structure, check for infinite recursive definitions. + + """ + warnings.warn( + "ParserElement.validate() is deprecated, and should not be used to check for left recursion", + DeprecationWarning, + stacklevel=2, + ) + self._checkRecursion([]) + + def parse_file( + self, + file_or_filename: Union[str, Path, TextIO], + encoding: str = "utf-8", + parse_all: bool = False, + *, + parseAll: bool = False, + ) -> ParseResults: + """ + Execute the parse expression on the given file or filename. + If a filename is specified (instead of a file object), + the entire file is opened, read, and closed before parsing. + """ + parseAll = parseAll or parse_all + try: + file_or_filename = typing.cast(TextIO, file_or_filename) + file_contents = file_or_filename.read() + except AttributeError: + file_or_filename = typing.cast(str, file_or_filename) + with open(file_or_filename, "r", encoding=encoding) as f: + file_contents = f.read() + try: + return self.parse_string(file_contents, parseAll) + except ParseBaseException as exc: + if ParserElement.verbose_stacktrace: + raise + + # catch and re-raise exception from here, clears out pyparsing internal stack trace + raise exc.with_traceback(None) + + def __eq__(self, other): + if self is other: + return True + elif isinstance(other, str_type): + return self.matches(other, parse_all=True) + elif isinstance(other, ParserElement): + return vars(self) == vars(other) + return False + + def __hash__(self): + return id(self) + + def matches( + self, test_string: str, parse_all: bool = True, *, parseAll: bool = True + ) -> bool: + """ + Method for quick testing of a parser against a test string. Good for simple + inline microtests of sub expressions while building up larger parser. + + :param test_string: to test against this expression for a match + :param parse_all: flag to pass to :meth:`parse_string` when running tests + + Example: + + .. doctest:: + + >>> expr = Word(nums) + >>> expr.matches("100") + True + """ + parseAll = parseAll and parse_all + try: + self.parse_string(str(test_string), parse_all=parseAll) + return True + except ParseBaseException: + return False + + def run_tests( + self, + tests: Union[str, list[str]], + parse_all: bool = True, + comment: typing.Optional[Union[ParserElement, str]] = "#", + full_dump: bool = True, + print_results: bool = True, + failure_tests: bool = False, + post_parse: typing.Optional[ + Callable[[str, ParseResults], typing.Optional[str]] + ] = None, + file: typing.Optional[TextIO] = None, + with_line_numbers: bool = False, + *, + parseAll: bool = True, + fullDump: bool = True, + printResults: bool = True, + failureTests: bool = False, + postParse: typing.Optional[ + Callable[[str, ParseResults], typing.Optional[str]] + ] = None, + ) -> tuple[bool, list[tuple[str, Union[ParseResults, Exception]]]]: + """ + Execute the parse expression on a series of test strings, showing each + test, the parsed results or where the parse failed. Quick and easy way to + run a parse expression against a list of sample strings. + + Parameters: + + - ``tests`` - a list of separate test strings, or a multiline string of test strings + - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests + - ``comment`` - (default= ``'#'``) - expression for indicating embedded comments in the test + string; pass None to disable comment filtering + - ``full_dump`` - (default= ``True``) - dump results as list followed by results names in nested outline; + if False, only dump nested list + - ``print_results`` - (default= ``True``) prints test output to stdout + - ``failure_tests`` - (default= ``False``) indicates if these tests are expected to fail parsing + - ``post_parse`` - (default= ``None``) optional callback for successful parse results; called as + `fn(test_string, parse_results)` and returns a string to be added to the test output + - ``file`` - (default= ``None``) optional file-like object to which test output will be written; + if None, will default to ``sys.stdout`` + - ``with_line_numbers`` - default= ``False``) show test strings with line and column numbers + + Returns: a (success, results) tuple, where success indicates that all tests succeeded + (or failed if ``failure_tests`` is True), and the results contain a list of lines of each + test's output + + Passing example: + + .. testcode:: + + number_expr = pyparsing_common.number.copy() + + result = number_expr.run_tests(''' + # unsigned integer + 100 + # negative integer + -100 + # float with scientific notation + 6.02e23 + # integer with scientific notation + 1e-12 + # negative decimal number without leading digit + -.100 + ''') + print("Success" if result[0] else "Failed!") + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # unsigned integer + 100 + [100] + + # negative integer + -100 + [-100] + + # float with scientific notation + 6.02e23 + [6.02e+23] + + # integer with scientific notation + 1e-12 + [1e-12] + + # negative decimal number without leading digit + -.100 + [-0.1] + Success + + Failure-test example: + + .. testcode:: + + result = number_expr.run_tests(''' + # stray character + 100Z + # too many '.' + 3.14.159 + ''', failure_tests=True) + print("Success" if result[0] else "Failed!") + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # stray character + 100Z + 100Z + ^ + ParseException: Expected end of text, found 'Z' ... + + # too many '.' + 3.14.159 + 3.14.159 + ^ + ParseException: Expected end of text, found '.' ... + FAIL: Expected end of text, found '.' ... + Success + + Each test string must be on a single line. If you want to test a string that spans multiple + lines, create a test like this: + + .. testcode:: + + expr = Word(alphanums)[1,...] + expr.run_tests(r"this is a test\\n of strings that spans \\n 3 lines") + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + :hide: + + + this is a test\\n of strings that spans \\n 3 lines + ['this', 'is', 'a', 'test', 'of', 'strings', 'that', 'spans', '3', 'lines'] + + (Note that this is a raw string literal, you must include the leading ``'r'``.) + """ + from .testing import pyparsing_test + + parseAll = parseAll and parse_all + fullDump = fullDump and full_dump + printResults = printResults and print_results + failureTests = failureTests or failure_tests + postParse = postParse or post_parse + if isinstance(tests, str_type): + tests = typing.cast(str, tests) + line_strip = type(tests).strip + tests = [line_strip(test_line) for test_line in tests.rstrip().splitlines()] + comment_specified = comment is not None + if comment_specified: + if isinstance(comment, str_type): + comment = typing.cast(str, comment) + comment = Literal(comment) + comment = typing.cast(ParserElement, comment) + if file is None: + file = sys.stdout + print_ = file.write + + result: Union[ParseResults, Exception] + allResults: list[tuple[str, Union[ParseResults, Exception]]] = [] + comments: list[str] = [] + success = True + NL = Literal(r"\n").add_parse_action(replace_with("\n")).ignore(quoted_string) + BOM = "\ufeff" + nlstr = "\n" + for t in tests: + if comment_specified and comment.matches(t, False) or comments and not t: + comments.append( + pyparsing_test.with_line_numbers(t) if with_line_numbers else t + ) + continue + if not t: + continue + out = [ + f"{nlstr}{nlstr.join(comments) if comments else ''}", + pyparsing_test.with_line_numbers(t) if with_line_numbers else t, + ] + comments.clear() + try: + # convert newline marks to actual newlines, and strip leading BOM if present + t = NL.transform_string(t.lstrip(BOM)) + result = self.parse_string(t, parse_all=parseAll) + except ParseBaseException as pe: + fatal = "(FATAL) " if isinstance(pe, ParseFatalException) else "" + out.append(pe.explain()) + out.append(f"FAIL: {fatal}{pe}") + if ParserElement.verbose_stacktrace: + out.extend(traceback.format_tb(pe.__traceback__)) + success = success and failureTests + result = pe + except Exception as exc: + tag = "FAIL-EXCEPTION" + + # see if this exception was raised in a parse action + tb = exc.__traceback__ + it = iter(traceback.walk_tb(tb)) + for f, line in it: + if (f.f_code.co_filename, line) == pa_call_line_synth: + next_f = next(it)[0] + tag += f" (raised in parse action {next_f.f_code.co_name!r})" + break + + out.append(f"{tag}: {type(exc).__name__}: {exc}") + if ParserElement.verbose_stacktrace: + out.extend(traceback.format_tb(exc.__traceback__)) + success = success and failureTests + result = exc + else: + success = success and not failureTests + if postParse is not None: + try: + pp_value = postParse(t, result) + if pp_value is not None: + if isinstance(pp_value, ParseResults): + out.append(pp_value.dump()) + else: + out.append(str(pp_value)) + else: + out.append(result.dump()) + except Exception as e: + out.append(result.dump(full=fullDump)) + out.append( + f"{postParse.__name__} failed: {type(e).__name__}: {e}" + ) + else: + out.append(result.dump(full=fullDump)) + out.append("") + + if printResults: + print_("\n".join(out)) + + allResults.append((t, result)) + + return success, allResults + + def create_diagram( + self, + output_html: Union[TextIO, Path, str], + vertical: int = 3, + show_results_names: bool = False, + show_groups: bool = False, + embed: bool = False, + show_hidden: bool = False, + **kwargs, + ) -> None: + """ + Create a railroad diagram for the parser. + + Parameters: + + - ``output_html`` (str or file-like object) - output target for generated + diagram HTML + - ``vertical`` (int) - threshold for formatting multiple alternatives vertically + instead of horizontally (default=3) + - ``show_results_names`` - bool flag whether diagram should show annotations for + defined results names + - ``show_groups`` - bool flag whether groups should be highlighted with an unlabeled surrounding box + - ``show_hidden`` - bool flag to show diagram elements for internal elements that are usually hidden + - ``embed`` - bool flag whether generated HTML should omit , , and tags to embed + the resulting HTML in an enclosing HTML source + - ``head`` - str containing additional HTML to insert into the section of the generated code; + can be used to insert custom CSS styling + - ``body`` - str containing additional HTML to insert at the beginning of the section of the + generated code + + Additional diagram-formatting keyword arguments can also be included; + see railroad.Diagram class. + + .. versionchanged:: 3.1.0 + ``embed`` argument added. + """ + + try: + from .diagram import to_railroad, railroad_to_html + except ImportError as ie: + raise Exception( + "must ``pip install pyparsing[diagrams]`` to generate parser railroad diagrams" + ) from ie + + self.streamline() + + railroad = to_railroad( + self, + vertical=vertical, + show_results_names=show_results_names, + show_groups=show_groups, + show_hidden=show_hidden, + diagram_kwargs=kwargs, + ) + if not isinstance(output_html, (str, Path)): + # we were passed a file-like object, just write to it + output_html.write(railroad_to_html(railroad, embed=embed, **kwargs)) + return + + with open(output_html, "w", encoding="utf-8") as diag_file: + diag_file.write(railroad_to_html(railroad, embed=embed, **kwargs)) + + # Compatibility synonyms + # fmt: off + inlineLiteralsUsing = staticmethod(replaced_by_pep8("inlineLiteralsUsing", inline_literals_using)) + setDefaultWhitespaceChars = staticmethod(replaced_by_pep8( + "setDefaultWhitespaceChars", set_default_whitespace_chars + )) + disableMemoization = staticmethod(replaced_by_pep8("disableMemoization", disable_memoization)) + enableLeftRecursion = staticmethod(replaced_by_pep8("enableLeftRecursion", enable_left_recursion)) + enablePackrat = staticmethod(replaced_by_pep8("enablePackrat", enable_packrat)) + resetCache = staticmethod(replaced_by_pep8("resetCache", reset_cache)) + + setResultsName = replaced_by_pep8("setResultsName", set_results_name) + setBreak = replaced_by_pep8("setBreak", set_break) + setParseAction = replaced_by_pep8("setParseAction", set_parse_action) + addParseAction = replaced_by_pep8("addParseAction", add_parse_action) + addCondition = replaced_by_pep8("addCondition", add_condition) + setFailAction = replaced_by_pep8("setFailAction", set_fail_action) + tryParse = replaced_by_pep8("tryParse", try_parse) + parseString = replaced_by_pep8("parseString", parse_string) + scanString = replaced_by_pep8("scanString", scan_string) + transformString = replaced_by_pep8("transformString", transform_string) + searchString = replaced_by_pep8("searchString", search_string) + ignoreWhitespace = replaced_by_pep8("ignoreWhitespace", ignore_whitespace) + leaveWhitespace = replaced_by_pep8("leaveWhitespace", leave_whitespace) + setWhitespaceChars = replaced_by_pep8("setWhitespaceChars", set_whitespace_chars) + parseWithTabs = replaced_by_pep8("parseWithTabs", parse_with_tabs) + setDebugActions = replaced_by_pep8("setDebugActions", set_debug_actions) + setDebug = replaced_by_pep8("setDebug", set_debug) + setName = replaced_by_pep8("setName", set_name) + parseFile = replaced_by_pep8("parseFile", parse_file) + runTests = replaced_by_pep8("runTests", run_tests) + canParseNext = replaced_by_pep8("canParseNext", can_parse_next) + defaultName = default_name + # fmt: on + + +class _PendingSkip(ParserElement): + # internal placeholder class to hold a place were '...' is added to a parser element, + # once another ParserElement is added, this placeholder will be replaced with a SkipTo + def __init__(self, expr: ParserElement, must_skip: bool = False) -> None: + super().__init__() + self.anchor = expr + self.must_skip = must_skip + + def _generateDefaultName(self) -> str: + return str(self.anchor + Empty()).replace("Empty", "...") + + def __add__(self, other) -> ParserElement: + skipper = SkipTo(other).set_name("...")("_skipped*") + if self.must_skip: + + def must_skip(t): + if not t._skipped or t._skipped.as_list() == [""]: + del t[0] + t.pop("_skipped", None) + + def show_skip(t): + if t._skipped.as_list()[-1:] == [""]: + t.pop("_skipped") + t["_skipped"] = f"missing <{self.anchor!r}>" + + return ( + self.anchor + skipper().add_parse_action(must_skip) + | skipper().add_parse_action(show_skip) + ) + other + + return self.anchor + skipper + other + + def __repr__(self): + return self.defaultName + + def parseImpl(self, *args) -> ParseImplReturnType: + raise Exception( + "use of `...` expression without following SkipTo target expression" + ) + + +class Token(ParserElement): + """Abstract :class:`ParserElement` subclass, for defining atomic + matching patterns. + """ + + def __init__(self) -> None: + super().__init__(savelist=False) + + def _generateDefaultName(self) -> str: + return type(self).__name__ + + +class NoMatch(Token): + """ + A token that will never match. + """ + + def __init__(self) -> None: + super().__init__() + self._may_return_empty = True + self.mayIndexError = False + self.errmsg = "Unmatchable token" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + raise ParseException(instring, loc, self.errmsg, self) + + +class Literal(Token): + """ + Token to exactly match a specified string. + + Example: + + .. doctest:: + + >>> Literal('abc').parse_string('abc') + ParseResults(['abc'], {}) + >>> Literal('abc').parse_string('abcdef') + ParseResults(['abc'], {}) + >>> Literal('abc').parse_string('ab') + Traceback (most recent call last): + ParseException: Expected 'abc', found 'ab' (at char 0), (line: 1, col: 1) + + For case-insensitive matching, use :class:`CaselessLiteral`. + + For keyword matching (force word break before and after the matched string), + use :class:`Keyword` or :class:`CaselessKeyword`. + """ + + def __new__(cls, match_string: str = "", *, matchString: str = ""): + # Performance tuning: select a subclass with optimized parseImpl + if cls is Literal: + match_string = matchString or match_string + if not match_string: + return super().__new__(Empty) + if len(match_string) == 1: + return super().__new__(_SingleCharLiteral) + + # Default behavior + return super().__new__(cls) + + # Needed to make copy.copy() work correctly if we customize __new__ + def __getnewargs__(self): + return (self.match,) + + def __init__(self, match_string: str = "", *, matchString: str = "") -> None: + super().__init__() + match_string = matchString or match_string + self.match = match_string + self.matchLen = len(match_string) + self.firstMatchChar = match_string[:1] + self.errmsg = f"Expected {self.name}" + self._may_return_empty = False + self.mayIndexError = False + + def _generateDefaultName(self) -> str: + return repr(self.match) + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if instring[loc] == self.firstMatchChar and instring.startswith( + self.match, loc + ): + return loc + self.matchLen, self.match + raise ParseException(instring, loc, self.errmsg, self) + + +class Empty(Literal): + """ + An empty token, will always match. + """ + + def __init__(self, match_string="", *, matchString="") -> None: + super().__init__("") + self._may_return_empty = True + self.mayIndexError = False + + def _generateDefaultName(self) -> str: + return "Empty" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + return loc, [] + + +class _SingleCharLiteral(Literal): + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if instring[loc] == self.firstMatchChar: + return loc + 1, self.match + raise ParseException(instring, loc, self.errmsg, self) + + +ParserElement._literalStringClass = Literal + + +class Keyword(Token): + """ + Token to exactly match a specified string as a keyword, that is, + it must be immediately preceded and followed by whitespace or + non-keyword characters. Compare with :class:`Literal`: + + - ``Literal("if")`` will match the leading ``'if'`` in + ``'ifAndOnlyIf'``. + - ``Keyword("if")`` will not; it will only match the leading + ``'if'`` in ``'if x=1'``, or ``'if(y==2)'`` + + Accepts two optional constructor arguments in addition to the + keyword string: + + - ``ident_chars`` is a string of characters that would be valid + identifier characters, defaulting to all alphanumerics + "_" and + "$" + - ``caseless`` allows case-insensitive matching, default is ``False``. + + Example: + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> Keyword("start").parse_string("start") + ParseResults(['start'], {}) + >>> Keyword("start").parse_string("starting") + Traceback (most recent call last): + ParseException: Expected Keyword 'start', keyword was immediately + followed by keyword character, found 'ing' (at char 5), (line:1, col:6) + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> Keyword("start").parse_string("starting").debug() + Traceback (most recent call last): + ParseException: Expected Keyword "start", keyword was immediately + followed by keyword character, found 'ing' ... + + For case-insensitive matching, use :class:`CaselessKeyword`. + """ + + DEFAULT_KEYWORD_CHARS = alphanums + "_$" + + def __init__( + self, + match_string: str = "", + ident_chars: typing.Optional[str] = None, + caseless: bool = False, + *, + matchString: str = "", + identChars: typing.Optional[str] = None, + ) -> None: + super().__init__() + identChars = identChars or ident_chars + if identChars is None: + identChars = Keyword.DEFAULT_KEYWORD_CHARS + match_string = matchString or match_string + self.match = match_string + self.matchLen = len(match_string) + self.firstMatchChar = match_string[:1] + if not self.firstMatchChar: + raise ValueError("null string passed to Keyword; use Empty() instead") + self.errmsg = f"Expected {type(self).__name__} {self.name}" + self._may_return_empty = False + self.mayIndexError = False + self.caseless = caseless + if caseless: + self.caselessmatch = match_string.upper() + identChars = identChars.upper() + self.identChars = set(identChars) + + def _generateDefaultName(self) -> str: + return repr(self.match) + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + errmsg = self.errmsg or "" + errloc = loc + if self.caseless: + if instring[loc : loc + self.matchLen].upper() == self.caselessmatch: + if loc == 0 or instring[loc - 1].upper() not in self.identChars: + if ( + loc >= len(instring) - self.matchLen + or instring[loc + self.matchLen].upper() not in self.identChars + ): + return loc + self.matchLen, self.match + + # followed by keyword char + errmsg += ", was immediately followed by keyword character" + errloc = loc + self.matchLen + else: + # preceded by keyword char + errmsg += ", keyword was immediately preceded by keyword character" + errloc = loc - 1 + # else no match just raise plain exception + + elif ( + instring[loc] == self.firstMatchChar + and self.matchLen == 1 + or instring.startswith(self.match, loc) + ): + if loc == 0 or instring[loc - 1] not in self.identChars: + if ( + loc >= len(instring) - self.matchLen + or instring[loc + self.matchLen] not in self.identChars + ): + return loc + self.matchLen, self.match + + # followed by keyword char + errmsg += ", keyword was immediately followed by keyword character" + errloc = loc + self.matchLen + else: + # preceded by keyword char + errmsg += ", keyword was immediately preceded by keyword character" + errloc = loc - 1 + # else no match just raise plain exception + + raise ParseException(instring, errloc, errmsg, self) + + @staticmethod + def set_default_keyword_chars(chars) -> None: + """ + Overrides the default characters used by :class:`Keyword` expressions. + """ + Keyword.DEFAULT_KEYWORD_CHARS = chars + + # Compatibility synonyms + setDefaultKeywordChars = staticmethod( + replaced_by_pep8("setDefaultKeywordChars", set_default_keyword_chars) + ) + + +class CaselessLiteral(Literal): + """ + Token to match a specified string, ignoring case of letters. + Note: the matched results will always be in the case of the given + match string, NOT the case of the input text. + + Example: + + .. doctest:: + + >>> CaselessLiteral("CMD")[1, ...].parse_string("cmd CMD Cmd10") + ParseResults(['CMD', 'CMD', 'CMD'], {}) + + (Contrast with example for :class:`CaselessKeyword`.) + """ + + def __init__(self, match_string: str = "", *, matchString: str = "") -> None: + match_string = matchString or match_string + super().__init__(match_string.upper()) + # Preserve the defining literal. + self.returnString = match_string + self.errmsg = f"Expected {self.name}" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if instring[loc : loc + self.matchLen].upper() == self.match: + return loc + self.matchLen, self.returnString + raise ParseException(instring, loc, self.errmsg, self) + + +class CaselessKeyword(Keyword): + """ + Caseless version of :class:`Keyword`. + + Example: + + .. doctest:: + + >>> CaselessKeyword("CMD")[1, ...].parse_string("cmd CMD Cmd10") + ParseResults(['CMD', 'CMD'], {}) + + (Contrast with example for :class:`CaselessLiteral`.) + """ + + def __init__( + self, + match_string: str = "", + ident_chars: typing.Optional[str] = None, + *, + matchString: str = "", + identChars: typing.Optional[str] = None, + ) -> None: + identChars = identChars or ident_chars + match_string = matchString or match_string + super().__init__(match_string, identChars, caseless=True) + + +class CloseMatch(Token): + """A variation on :class:`Literal` which matches "close" matches, + that is, strings with at most 'n' mismatching characters. + :class:`CloseMatch` takes parameters: + + - ``match_string`` - string to be matched + - ``caseless`` - a boolean indicating whether to ignore casing when comparing characters + - ``max_mismatches`` - (``default=1``) maximum number of + mismatches allowed to count as a match + + The results from a successful parse will contain the matched text + from the input string and the following named results: + + - ``mismatches`` - a list of the positions within the + match_string where mismatches were found + - ``original`` - the original match_string used to compare + against the input string + + If ``mismatches`` is an empty list, then the match was an exact + match. + + Example: + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> patt = CloseMatch("ATCATCGAATGGA") + >>> patt.parse_string("ATCATCGAAXGGA") + ParseResults(['ATCATCGAAXGGA'], + {'original': 'ATCATCGAATGGA', 'mismatches': [9]}) + + >>> patt.parse_string("ATCAXCGAAXGGA") + Traceback (most recent call last): + ParseException: Expected 'ATCATCGAATGGA' (with up to 1 mismatches), + found 'ATCAXCGAAXGGA' (at char 0), (line:1, col:1) + + # exact match + >>> patt.parse_string("ATCATCGAATGGA") + ParseResults(['ATCATCGAATGGA'], + {'original': 'ATCATCGAATGGA', 'mismatches': []}) + + # close match allowing up to 2 mismatches + >>> patt = CloseMatch("ATCATCGAATGGA", max_mismatches=2) + >>> patt.parse_string("ATCAXCGAAXGGA") + ParseResults(['ATCAXCGAAXGGA'], + {'original': 'ATCATCGAATGGA', 'mismatches': [4, 9]}) + """ + + def __init__( + self, + match_string: str, + max_mismatches: typing.Optional[int] = None, + *, + maxMismatches: int = 1, + caseless=False, + ) -> None: + maxMismatches = max_mismatches if max_mismatches is not None else maxMismatches + super().__init__() + self.match_string = match_string + self.maxMismatches = maxMismatches + self.errmsg = f"Expected {self.match_string!r} (with up to {self.maxMismatches} mismatches)" + self.caseless = caseless + self.mayIndexError = False + self._may_return_empty = False + + def _generateDefaultName(self) -> str: + return f"{type(self).__name__}:{self.match_string!r}" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + start = loc + instrlen = len(instring) + maxloc = start + len(self.match_string) + + if maxloc <= instrlen: + match_string = self.match_string + match_stringloc = 0 + mismatches = [] + maxMismatches = self.maxMismatches + + for match_stringloc, s_m in enumerate( + zip(instring[loc:maxloc], match_string) + ): + src, mat = s_m + if self.caseless: + src, mat = src.lower(), mat.lower() + + if src != mat: + mismatches.append(match_stringloc) + if len(mismatches) > maxMismatches: + break + else: + loc = start + match_stringloc + 1 + results = ParseResults([instring[start:loc]]) + results["original"] = match_string + results["mismatches"] = mismatches + return loc, results + + raise ParseException(instring, loc, self.errmsg, self) + + +class Word(Token): + """Token for matching words composed of allowed character sets. + + Parameters: + + - ``init_chars`` - string of all characters that should be used to + match as a word; "ABC" will match "AAA", "ABAB", "CBAC", etc.; + if ``body_chars`` is also specified, then this is the string of + initial characters + - ``body_chars`` - string of characters that + can be used for matching after a matched initial character as + given in ``init_chars``; if omitted, same as the initial characters + (default=``None``) + - ``min`` - minimum number of characters to match (default=1) + - ``max`` - maximum number of characters to match (default=0) + - ``exact`` - exact number of characters to match (default=0) + - ``as_keyword`` - match as a keyword (default=``False``) + - ``exclude_chars`` - characters that might be + found in the input ``body_chars`` string but which should not be + accepted for matching ;useful to define a word of all + printables except for one or two characters, for instance + (default=``None``) + + :class:`srange` is useful for defining custom character set strings + for defining :class:`Word` expressions, using range notation from + regular expression character sets. + + A common mistake is to use :class:`Word` to match a specific literal + string, as in ``Word("Address")``. Remember that :class:`Word` + uses the string argument to define *sets* of matchable characters. + This expression would match "Add", "AAA", "dAred", or any other word + made up of the characters 'A', 'd', 'r', 'e', and 's'. To match an + exact literal string, use :class:`Literal` or :class:`Keyword`. + + pyparsing includes helper strings for building Words: + + - :attr:`alphas` + - :attr:`nums` + - :attr:`alphanums` + - :attr:`hexnums` + - :attr:`alphas8bit` (alphabetic characters in ASCII range 128-255 + - accented, tilded, umlauted, etc.) + - :attr:`punc8bit` (non-alphabetic characters in ASCII range + 128-255 - currency, symbols, superscripts, diacriticals, etc.) + - :attr:`printables` (any non-whitespace character) + + ``alphas``, ``nums``, and ``printables`` are also defined in several + Unicode sets - see :class:`pyparsing_unicode`. + + Example: + + .. testcode:: + + # a word composed of digits + integer = Word(nums) + # Two equivalent alternate forms: + Word("0123456789") + Word(srange("[0-9]")) + + # a word with a leading capital, and zero or more lowercase + capitalized_word = Word(alphas.upper(), alphas.lower()) + + # hostnames are alphanumeric, with leading alpha, and '-' + hostname = Word(alphas, alphanums + '-') + + # roman numeral + # (not a strict parser, accepts invalid mix of characters) + roman = Word("IVXLCDM") + + # any string of non-whitespace characters, except for ',' + csv_value = Word(printables, exclude_chars=",") + + :raises ValueError: If ``min`` and ``max`` are both specified + and the test ``min <= max`` fails. + + .. versionchanged:: 3.1.0 + Raises :exc:`ValueError` if ``min`` > ``max``. + """ + + def __init__( + self, + init_chars: str = "", + body_chars: typing.Optional[str] = None, + min: int = 1, + max: int = 0, + exact: int = 0, + as_keyword: bool = False, + exclude_chars: typing.Optional[str] = None, + *, + initChars: typing.Optional[str] = None, + bodyChars: typing.Optional[str] = None, + asKeyword: bool = False, + excludeChars: typing.Optional[str] = None, + ) -> None: + initChars = initChars or init_chars + bodyChars = bodyChars or body_chars + asKeyword = asKeyword or as_keyword + excludeChars = excludeChars or exclude_chars + super().__init__() + if not initChars: + raise ValueError( + f"invalid {type(self).__name__}, initChars cannot be empty string" + ) + + initChars_set = set(initChars) + if excludeChars: + excludeChars_set = set(excludeChars) + initChars_set -= excludeChars_set + if bodyChars: + bodyChars = "".join(set(bodyChars) - excludeChars_set) + self.initChars = initChars_set + self.initCharsOrig = "".join(sorted(initChars_set)) + + if bodyChars: + self.bodyChars = set(bodyChars) + self.bodyCharsOrig = "".join(sorted(bodyChars)) + else: + self.bodyChars = initChars_set + self.bodyCharsOrig = self.initCharsOrig + + self.maxSpecified = max > 0 + + if min < 1: + raise ValueError( + "cannot specify a minimum length < 1; use Opt(Word()) if zero-length word is permitted" + ) + + if self.maxSpecified and min > max: + raise ValueError( + f"invalid args, if min and max both specified min must be <= max (min={min}, max={max})" + ) + + self.minLen = min + + if max > 0: + self.maxLen = max + else: + self.maxLen = _MAX_INT + + if exact > 0: + min = max = exact + self.maxLen = exact + self.minLen = exact + + self.errmsg = f"Expected {self.name}" + self.mayIndexError = False + self.asKeyword = asKeyword + if self.asKeyword: + self.errmsg += " as a keyword" + + # see if we can make a regex for this Word + if " " not in (self.initChars | self.bodyChars): + if len(self.initChars) == 1: + re_leading_fragment = re.escape(self.initCharsOrig) + else: + re_leading_fragment = f"[{_collapse_string_to_ranges(self.initChars)}]" + + if self.bodyChars == self.initChars: + if max == 0 and self.minLen == 1: + repeat = "+" + elif max == 1: + repeat = "" + else: + if self.minLen != self.maxLen: + repeat = f"{{{self.minLen},{'' if self.maxLen == _MAX_INT else self.maxLen}}}" + else: + repeat = f"{{{self.minLen}}}" + self.reString = f"{re_leading_fragment}{repeat}" + else: + if max == 1: + re_body_fragment = "" + repeat = "" + else: + re_body_fragment = f"[{_collapse_string_to_ranges(self.bodyChars)}]" + if max == 0 and self.minLen == 1: + repeat = "*" + elif max == 2: + repeat = "?" if min <= 1 else "" + else: + if min != max: + repeat = f"{{{min - 1 if min > 0 else ''},{max - 1 if max > 0 else ''}}}" + else: + repeat = f"{{{min - 1 if min > 0 else ''}}}" + + self.reString = f"{re_leading_fragment}{re_body_fragment}{repeat}" + + if self.asKeyword: + self.reString = rf"\b{self.reString}\b" + + try: + self.re = re.compile(self.reString) + except re.error: + self.re = None # type: ignore[assignment] + else: + self.re_match = self.re.match + self.parseImpl = self.parseImpl_regex # type: ignore[method-assign] + + def copy(self) -> Word: + ret: Word = cast(Word, super().copy()) + if hasattr(self, "re_match"): + ret.re_match = self.re_match + ret.parseImpl = ret.parseImpl_regex # type: ignore[method-assign] + return ret + + def _generateDefaultName(self) -> str: + def charsAsStr(s): + max_repr_len = 16 + s = _collapse_string_to_ranges(s, re_escape=False) + + if len(s) > max_repr_len: + return s[: max_repr_len - 3] + "..." + + return s + + if self.initChars != self.bodyChars: + base = f"W:({charsAsStr(self.initChars)}, {charsAsStr(self.bodyChars)})" + else: + base = f"W:({charsAsStr(self.initChars)})" + + # add length specification + if self.minLen > 1 or self.maxLen != _MAX_INT: + if self.minLen == self.maxLen: + if self.minLen == 1: + return base[2:] + else: + return base + f"{{{self.minLen}}}" + elif self.maxLen == _MAX_INT: + return base + f"{{{self.minLen},...}}" + else: + return base + f"{{{self.minLen},{self.maxLen}}}" + return base + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if instring[loc] not in self.initChars: + raise ParseException(instring, loc, self.errmsg, self) + + start = loc + loc += 1 + instrlen = len(instring) + body_chars: set[str] = self.bodyChars + maxloc = start + self.maxLen + maxloc = min(maxloc, instrlen) + while loc < maxloc and instring[loc] in body_chars: + loc += 1 + + throw_exception = False + if loc - start < self.minLen: + throw_exception = True + elif self.maxSpecified and loc < instrlen and instring[loc] in body_chars: + throw_exception = True + elif self.asKeyword and ( + (start > 0 and instring[start - 1] in body_chars) + or (loc < instrlen and instring[loc] in body_chars) + ): + throw_exception = True + + if throw_exception: + raise ParseException(instring, loc, self.errmsg, self) + + return loc, instring[start:loc] + + def parseImpl_regex(self, instring, loc, do_actions=True) -> ParseImplReturnType: + result = self.re_match(instring, loc) + if not result: + raise ParseException(instring, loc, self.errmsg, self) + + loc = result.end() + return loc, result.group() + + +class Char(Word): + """A short-cut class for defining :class:`Word` ``(characters, exact=1)``, + when defining a match of any single character in a string of + characters. + """ + + def __init__( + self, + charset: str, + as_keyword: bool = False, + exclude_chars: typing.Optional[str] = None, + *, + asKeyword: bool = False, + excludeChars: typing.Optional[str] = None, + ) -> None: + asKeyword = asKeyword or as_keyword + excludeChars = excludeChars or exclude_chars + super().__init__( + charset, exact=1, as_keyword=asKeyword, exclude_chars=excludeChars + ) + + +class Regex(Token): + r"""Token for matching strings that match a given regular + expression. Defined with string specifying the regular expression in + a form recognized by the stdlib Python `re module `_. + If the given regex contains named groups (defined using ``(?P...)``), + these will be preserved as named :class:`ParseResults`. + + If instead of the Python stdlib ``re`` module you wish to use a different RE module + (such as the ``regex`` module), you can do so by building your ``Regex`` object with + a compiled RE that was compiled using ``regex``. + + The parameters ``pattern`` and ``flags`` are passed + to the ``re.compile()`` function as-is. See the Python + `re module `_ module for an + explanation of the acceptable patterns and flags. + + Example: + + .. testcode:: + + realnum = Regex(r"[+-]?\d+\.\d*") + # ref: https://stackoverflow.com/questions/267399/how-do-you-match-only-valid-roman-numerals-with-a-regular-expression + roman = Regex(r"M{0,4}(CM|CD|D?{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})") + + # named fields in a regex will be returned as named results + date = Regex(r'(?P\d{4})-(?P\d\d?)-(?P\d\d?)') + + # the Regex class will accept regular expressions compiled using the + # re module + import re + parser = pp.Regex(re.compile(r'[0-9]')) + """ + + def __init__( + self, + pattern: Any, + flags: Union[re.RegexFlag, int] = 0, + as_group_list: bool = False, + as_match: bool = False, + *, + asGroupList: bool = False, + asMatch: bool = False, + ) -> None: + super().__init__() + asGroupList = asGroupList or as_group_list + asMatch = asMatch or as_match + + if isinstance(pattern, str_type): + if not pattern: + raise ValueError("null string passed to Regex; use Empty() instead") + + self._re = None + self._may_return_empty = None # type: ignore [assignment] + self.reString = self.pattern = pattern + + elif hasattr(pattern, "pattern") and hasattr(pattern, "match"): + self._re = pattern + self._may_return_empty = None # type: ignore [assignment] + self.pattern = self.reString = pattern.pattern + + elif callable(pattern): + # defer creating this pattern until we really need it + self.pattern = pattern + self._may_return_empty = None # type: ignore [assignment] + self._re = None + + else: + raise TypeError( + "Regex may only be constructed with a string or a compiled RE object," + " or a callable that takes no arguments and returns a string or a" + " compiled RE object" + ) + + self.flags = flags + self.errmsg = f"Expected {self.name}" + self.mayIndexError = False + self.asGroupList = asGroupList + self.asMatch = asMatch + if self.asGroupList: + self.parseImpl = self.parseImplAsGroupList # type: ignore [method-assign] + if self.asMatch: + self.parseImpl = self.parseImplAsMatch # type: ignore [method-assign] + + def copy(self): + ret: Regex = cast(Regex, super().copy()) + if self.asGroupList: + ret.parseImpl = ret.parseImplAsGroupList + if self.asMatch: + ret.parseImpl = ret.parseImplAsMatch + return ret + + @cached_property + def re(self) -> re.Pattern: + if self._re: + return self._re + + if callable(self.pattern): + # replace self.pattern with the string returned by calling self.pattern() + self.pattern = cast(Callable[[], str], self.pattern)() + + # see if we got a compiled RE back instead of a str - if so, we're done + if hasattr(self.pattern, "pattern") and hasattr(self.pattern, "match"): + self._re = cast(re.Pattern[str], self.pattern) + self.pattern = self.reString = self._re.pattern + return self._re + + try: + self._re = re.compile(self.pattern, self.flags) + except re.error: + raise ValueError(f"invalid pattern ({self.pattern!r}) passed to Regex") + else: + self._may_return_empty = self.re.match("", pos=0) is not None + return self._re + + @cached_property + def re_match(self) -> Callable[[str, int], Any]: + return self.re.match + + @property + def mayReturnEmpty(self): + if self._may_return_empty is None: + # force compile of regex pattern, to set may_return_empty flag + self.re # noqa + return self._may_return_empty + + @mayReturnEmpty.setter + def mayReturnEmpty(self, value): + self._may_return_empty = value + + def _generateDefaultName(self) -> str: + unescaped = repr(self.pattern).replace("\\\\", "\\") + return f"Re:({unescaped})" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + # explicit check for matching past the length of the string; + # this is done because the re module will not complain about + # a match with `pos > len(instring)`, it will just return "" + if loc > len(instring) and self.mayReturnEmpty: + raise ParseException(instring, loc, self.errmsg, self) + + result = self.re_match(instring, loc) + if not result: + raise ParseException(instring, loc, self.errmsg, self) + + loc = result.end() + ret = ParseResults(result.group()) + d = result.groupdict() + + for k, v in d.items(): + ret[k] = v + + return loc, ret + + def parseImplAsGroupList(self, instring, loc, do_actions=True): + if loc > len(instring) and self.mayReturnEmpty: + raise ParseException(instring, loc, self.errmsg, self) + + result = self.re_match(instring, loc) + if not result: + raise ParseException(instring, loc, self.errmsg, self) + + loc = result.end() + ret = result.groups() + return loc, ret + + def parseImplAsMatch(self, instring, loc, do_actions=True): + if loc > len(instring) and self.mayReturnEmpty: + raise ParseException(instring, loc, self.errmsg, self) + + result = self.re_match(instring, loc) + if not result: + raise ParseException(instring, loc, self.errmsg, self) + + loc = result.end() + ret = result + return loc, ret + + def sub(self, repl: str) -> ParserElement: + r""" + Return :class:`Regex` with an attached parse action to transform the parsed + result as if called using `re.sub(expr, repl, string) `_. + + Example: + + .. testcode:: + + make_html = Regex(r"(\w+):(.*?):").sub(r"<\1>\2") + print(make_html.transform_string("h1:main title:")) + + .. testoutput:: + +

main title

+ """ + if self.asGroupList: + raise TypeError("cannot use sub() with Regex(as_group_list=True)") + + if self.asMatch and callable(repl): + raise TypeError( + "cannot use sub() with a callable with Regex(as_match=True)" + ) + + if self.asMatch: + + def pa(tokens): + return tokens[0].expand(repl) + + else: + + def pa(tokens): + return self.re.sub(repl, tokens[0]) + + return self.add_parse_action(pa) + + +class QuotedString(Token): + r""" + Token for matching strings that are delimited by quoting characters. + + Defined with the following parameters: + + - ``quote_char`` - string of one or more characters defining the + quote delimiting string + - ``esc_char`` - character to re_escape quotes, typically backslash + (default= ``None``) + - ``esc_quote`` - special quote sequence to re_escape an embedded quote + string (such as SQL's ``""`` to re_escape an embedded ``"``) + (default= ``None``) + - ``multiline`` - boolean indicating whether quotes can span + multiple lines (default= ``False``) + - ``unquote_results`` - boolean indicating whether the matched text + should be unquoted (default= ``True``) + - ``end_quote_char`` - string of one or more characters defining the + end of the quote delimited string (default= ``None`` => same as + quote_char) + - ``convert_whitespace_escapes`` - convert escaped whitespace + (``'\t'``, ``'\n'``, etc.) to actual whitespace + (default= ``True``) + + .. caution:: ``convert_whitespace_escapes`` has no effect if + ``unquote_results`` is ``False``. + + Example: + + .. doctest:: + + >>> qs = QuotedString('"') + >>> print(qs.search_string('lsjdf "This is the quote" sldjf')) + [['This is the quote']] + >>> complex_qs = QuotedString('{{', end_quote_char='}}') + >>> print(complex_qs.search_string( + ... 'lsjdf {{This is the "quote"}} sldjf')) + [['This is the "quote"']] + >>> sql_qs = QuotedString('"', esc_quote='""') + >>> print(sql_qs.search_string( + ... 'lsjdf "This is the quote with ""embedded"" quotes" sldjf')) + [['This is the quote with "embedded" quotes']] + """ + + ws_map = dict(((r"\t", "\t"), (r"\n", "\n"), (r"\f", "\f"), (r"\r", "\r"))) + + def __init__( + self, + quote_char: str = "", + esc_char: typing.Optional[str] = None, + esc_quote: typing.Optional[str] = None, + multiline: bool = False, + unquote_results: bool = True, + end_quote_char: typing.Optional[str] = None, + convert_whitespace_escapes: bool = True, + *, + quoteChar: str = "", + escChar: typing.Optional[str] = None, + escQuote: typing.Optional[str] = None, + unquoteResults: bool = True, + endQuoteChar: typing.Optional[str] = None, + convertWhitespaceEscapes: bool = True, + ) -> None: + super().__init__() + esc_char = escChar or esc_char + esc_quote = escQuote or esc_quote + unquote_results = unquoteResults and unquote_results + end_quote_char = endQuoteChar or end_quote_char + convert_whitespace_escapes = ( + convertWhitespaceEscapes and convert_whitespace_escapes + ) + quote_char = quoteChar or quote_char + + # remove white space from quote chars + quote_char = quote_char.strip() + if not quote_char: + raise ValueError("quote_char cannot be the empty string") + + if end_quote_char is None: + end_quote_char = quote_char + else: + end_quote_char = end_quote_char.strip() + if not end_quote_char: + raise ValueError("end_quote_char cannot be the empty string") + + self.quote_char: str = quote_char + self.quote_char_len: int = len(quote_char) + self.first_quote_char: str = quote_char[0] + self.end_quote_char: str = end_quote_char + self.end_quote_char_len: int = len(end_quote_char) + self.esc_char: str = esc_char or "" + self.has_esc_char: bool = esc_char is not None + self.esc_quote: str = esc_quote or "" + self.unquote_results: bool = unquote_results + self.convert_whitespace_escapes: bool = convert_whitespace_escapes + self.multiline = multiline + self.re_flags = re.RegexFlag(0) + + # fmt: off + # build up re pattern for the content between the quote delimiters + inner_pattern: list[str] = [] + + if esc_quote: + inner_pattern.append(rf"(?:{re.escape(esc_quote)})") + + if esc_char: + inner_pattern.append(rf"(?:{re.escape(esc_char)}.)") + + if len(self.end_quote_char) > 1: + inner_pattern.append( + "(?:" + + "|".join( + f"(?:{re.escape(self.end_quote_char[:i])}(?!{re.escape(self.end_quote_char[i:])}))" + for i in range(len(self.end_quote_char) - 1, 0, -1) + ) + + ")" + ) + + if self.multiline: + self.re_flags |= re.MULTILINE | re.DOTALL + inner_pattern.append( + rf"(?:[^{_escape_regex_range_chars(self.end_quote_char[0])}" + rf"{(_escape_regex_range_chars(self.esc_char) if self.has_esc_char else '')}])" + ) + else: + inner_pattern.append( + rf"(?:[^{_escape_regex_range_chars(self.end_quote_char[0])}\n\r" + rf"{(_escape_regex_range_chars(self.esc_char) if self.has_esc_char else '')}])" + ) + + self.pattern = "".join( + [ + re.escape(self.quote_char), + "(?:", + '|'.join(inner_pattern), + ")*", + re.escape(self.end_quote_char), + ] + ) + + if self.unquote_results: + if self.convert_whitespace_escapes: + self.unquote_scan_re = re.compile( + rf"({'|'.join(re.escape(k) for k in self.ws_map)})" + rf"|(\\[0-7]{3}|\\0|\\x[0-9a-fA-F]{2}|\\u[0-9a-fA-F]{4})" + rf"|({re.escape(self.esc_char)}.)" + rf"|(\n|.)", + flags=self.re_flags, + ) + else: + self.unquote_scan_re = re.compile( + rf"({re.escape(self.esc_char)}.)" + rf"|(\n|.)", + flags=self.re_flags + ) + # fmt: on + + try: + self.re = re.compile(self.pattern, self.re_flags) + self.reString = self.pattern + self.re_match = self.re.match + except re.error: + raise ValueError(f"invalid pattern {self.pattern!r} passed to Regex") + + self.errmsg = f"Expected {self.name}" + self.mayIndexError = False + self._may_return_empty = True + + def _generateDefaultName(self) -> str: + if self.quote_char == self.end_quote_char and isinstance( + self.quote_char, str_type + ): + return f"string enclosed in {self.quote_char!r}" + + return f"quoted string, starting with {self.quote_char} ending with {self.end_quote_char}" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + # check first character of opening quote to see if that is a match + # before doing the more complicated regex match + result = ( + instring[loc] == self.first_quote_char + and self.re_match(instring, loc) + or None + ) + if not result: + raise ParseException(instring, loc, self.errmsg, self) + + # get ending loc and matched string from regex matching result + loc = result.end() + ret = result.group() + + def convert_escaped_numerics(s: str) -> str: + if s == "0": + return "\0" + if s.isdigit() and len(s) == 3: + return chr(int(s, base=8)) + elif s.startswith(("u", "x")): + return chr(int(s[1:], base=16)) + else: + return s + + if self.unquote_results: + # strip off quotes + ret = ret[self.quote_char_len : -self.end_quote_char_len] + + if isinstance(ret, str_type): + # fmt: off + if self.convert_whitespace_escapes: + # as we iterate over matches in the input string, + # collect from whichever match group of the unquote_scan_re + # regex matches (only 1 group will match at any given time) + ret = "".join( + # match group 1 matches \t, \n, etc. + self.ws_map[match.group(1)] if match.group(1) + # match group 2 matches escaped octal, null, hex, and Unicode + # sequences + else convert_escaped_numerics(match.group(2)[1:]) if match.group(2) + # match group 3 matches escaped characters + else match.group(3)[-1] if match.group(3) + # match group 4 matches any character + else match.group(4) + for match in self.unquote_scan_re.finditer(ret) + ) + else: + ret = "".join( + # match group 1 matches escaped characters + match.group(1)[-1] if match.group(1) + # match group 2 matches any character + else match.group(2) + for match in self.unquote_scan_re.finditer(ret) + ) + # fmt: on + + # replace escaped quotes + if self.esc_quote: + ret = ret.replace(self.esc_quote, self.end_quote_char) + + return loc, ret + + +class CharsNotIn(Token): + """Token for matching words composed of characters *not* in a given + set (will include whitespace in matched characters if not listed in + the provided exclusion set - see example). Defined with string + containing all disallowed characters, and an optional minimum, + maximum, and/or exact length. The default value for ``min`` is + 1 (a minimum value < 1 is not valid); the default values for + ``max`` and ``exact`` are 0, meaning no maximum or exact + length restriction. + + Example: + + .. testcode:: + + # define a comma-separated-value as anything that is not a ',' + csv_value = CharsNotIn(',') + print( + DelimitedList(csv_value).parse_string( + "dkls,lsdkjf,s12 34,@!#,213" + ) + ) + + prints: + + .. testoutput:: + + ['dkls', 'lsdkjf', 's12 34', '@!#', '213'] + """ + + def __init__( + self, + not_chars: str = "", + min: int = 1, + max: int = 0, + exact: int = 0, + *, + notChars: str = "", + ) -> None: + super().__init__() + self.skipWhitespace = False + self.notChars = not_chars or notChars + self.notCharsSet = set(self.notChars) + + if min < 1: + raise ValueError( + "cannot specify a minimum length < 1; use" + " Opt(CharsNotIn()) if zero-length char group is permitted" + ) + + self.minLen = min + + if max > 0: + self.maxLen = max + else: + self.maxLen = _MAX_INT + + if exact > 0: + self.maxLen = exact + self.minLen = exact + + self.errmsg = f"Expected {self.name}" + self._may_return_empty = self.minLen == 0 + self.mayIndexError = False + + def _generateDefaultName(self) -> str: + not_chars_str = _collapse_string_to_ranges(self.notChars) + if len(not_chars_str) > 16: + return f"!W:({self.notChars[: 16 - 3]}...)" + else: + return f"!W:({self.notChars})" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + notchars = self.notCharsSet + if instring[loc] in notchars: + raise ParseException(instring, loc, self.errmsg, self) + + start = loc + loc += 1 + maxlen = min(start + self.maxLen, len(instring)) + while loc < maxlen and instring[loc] not in notchars: + loc += 1 + + if loc - start < self.minLen: + raise ParseException(instring, loc, self.errmsg, self) + + return loc, instring[start:loc] + + +class White(Token): + """Special matching class for matching whitespace. Normally, + whitespace is ignored by pyparsing grammars. This class is included + when some whitespace structures are significant. Define with + a string containing the whitespace characters to be matched; default + is ``" \\t\\r\\n"``. Also takes optional ``min``, + ``max``, and ``exact`` arguments, as defined for the + :class:`Word` class. + """ + + whiteStrs = { + " ": "", + "\t": "", + "\n": "", + "\r": "", + "\f": "", + "\u00A0": "", + "\u1680": "", + "\u180E": "", + "\u2000": "", + "\u2001": "", + "\u2002": "", + "\u2003": "", + "\u2004": "", + "\u2005": "", + "\u2006": "", + "\u2007": "", + "\u2008": "", + "\u2009": "", + "\u200A": "", + "\u200B": "", + "\u202F": "", + "\u205F": "", + "\u3000": "", + } + + def __init__( + self, ws: str = " \t\r\n", min: int = 1, max: int = 0, exact: int = 0 + ) -> None: + super().__init__() + self.matchWhite = ws + self.set_whitespace_chars( + "".join(c for c in self.whiteStrs if c not in self.matchWhite), + copy_defaults=True, + ) + # self.leave_whitespace() + self._may_return_empty = True + self.errmsg = f"Expected {self.name}" + + self.minLen = min + + if max > 0: + self.maxLen = max + else: + self.maxLen = _MAX_INT + + if exact > 0: + self.maxLen = exact + self.minLen = exact + + def _generateDefaultName(self) -> str: + return "".join(White.whiteStrs[c] for c in self.matchWhite) + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if instring[loc] not in self.matchWhite: + raise ParseException(instring, loc, self.errmsg, self) + start = loc + loc += 1 + maxloc = start + self.maxLen + maxloc = min(maxloc, len(instring)) + while loc < maxloc and instring[loc] in self.matchWhite: + loc += 1 + + if loc - start < self.minLen: + raise ParseException(instring, loc, self.errmsg, self) + + return loc, instring[start:loc] + + +class PositionToken(Token): + def __init__(self) -> None: + super().__init__() + self._may_return_empty = True + self.mayIndexError = False + + +class GoToColumn(PositionToken): + """Token to advance to a specific column of input text; useful for + tabular report scraping. + """ + + def __init__(self, colno: int) -> None: + super().__init__() + self.col = colno + + def preParse(self, instring: str, loc: int) -> int: + if col(loc, instring) == self.col: + return loc + + instrlen = len(instring) + if self.ignoreExprs: + loc = self._skipIgnorables(instring, loc) + while ( + loc < instrlen + and instring[loc].isspace() + and col(loc, instring) != self.col + ): + loc += 1 + + return loc + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + thiscol = col(loc, instring) + if thiscol > self.col: + raise ParseException(instring, loc, "Text not in expected column", self) + newloc = loc + self.col - thiscol + ret = instring[loc:newloc] + return newloc, ret + + +class LineStart(PositionToken): + r"""Matches if current position is at the beginning of a line within + the parse string + + Example: + + .. testcode:: + + test = '''\ + AAA this line + AAA and this line + AAA and even this line + B AAA but definitely not this line + ''' + + for t in (LineStart() + 'AAA' + rest_of_line).search_string(test): + print(t) + + prints: + + .. testoutput:: + + ['AAA', ' this line'] + ['AAA', ' and this line'] + ['AAA', ' and even this line'] + + """ + + def __init__(self) -> None: + super().__init__() + self.leave_whitespace() + self.orig_whiteChars = set() | self.whiteChars + self.whiteChars.discard("\n") + self.skipper = Empty().set_whitespace_chars(self.whiteChars) + self.set_name("start of line") + + def preParse(self, instring: str, loc: int) -> int: + if loc == 0: + return loc + + ret = self.skipper.preParse(instring, loc) + + if "\n" in self.orig_whiteChars: + while instring[ret : ret + 1] == "\n": + ret = self.skipper.preParse(instring, ret + 1) + + return ret + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if col(loc, instring) == 1: + return loc, [] + raise ParseException(instring, loc, self.errmsg, self) + + +class LineEnd(PositionToken): + """Matches if current position is at the end of a line within the + parse string + """ + + def __init__(self) -> None: + super().__init__() + self.whiteChars.discard("\n") + self.set_whitespace_chars(self.whiteChars, copy_defaults=False) + self.set_name("end of line") + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if loc < len(instring): + if instring[loc] == "\n": + return loc + 1, "\n" + else: + raise ParseException(instring, loc, self.errmsg, self) + elif loc == len(instring): + return loc + 1, [] + else: + raise ParseException(instring, loc, self.errmsg, self) + + +class StringStart(PositionToken): + """Matches if current position is at the beginning of the parse + string + """ + + def __init__(self) -> None: + super().__init__() + self.set_name("start of text") + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + # see if entire string up to here is just whitespace and ignoreables + if loc != 0 and loc != self.preParse(instring, 0): + raise ParseException(instring, loc, self.errmsg, self) + + return loc, [] + + +class StringEnd(PositionToken): + """ + Matches if current position is at the end of the parse string + """ + + def __init__(self) -> None: + super().__init__() + self.set_name("end of text") + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if loc < len(instring): + raise ParseException(instring, loc, self.errmsg, self) + if loc == len(instring): + return loc + 1, [] + if loc > len(instring): + return loc, [] + + raise ParseException(instring, loc, self.errmsg, self) + + +class WordStart(PositionToken): + """Matches if the current position is at the beginning of a + :class:`Word`, and is not preceded by any character in a given + set of ``word_chars`` (default= ``printables``). To emulate the + ``\b`` behavior of regular expressions, use + ``WordStart(alphanums)``. ``WordStart`` will also match at + the beginning of the string being parsed, or at the beginning of + a line. + """ + + def __init__( + self, word_chars: str = printables, *, wordChars: str = printables + ) -> None: + wordChars = word_chars if wordChars == printables else wordChars + super().__init__() + self.wordChars = set(wordChars) + self.set_name("start of a word") + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if loc != 0: + if ( + instring[loc - 1] in self.wordChars + or instring[loc] not in self.wordChars + ): + raise ParseException(instring, loc, self.errmsg, self) + return loc, [] + + +class WordEnd(PositionToken): + """Matches if the current position is at the end of a :class:`Word`, + and is not followed by any character in a given set of ``word_chars`` + (default= ``printables``). To emulate the ``\b`` behavior of + regular expressions, use ``WordEnd(alphanums)``. ``WordEnd`` + will also match at the end of the string being parsed, or at the end + of a line. + """ + + def __init__( + self, word_chars: str = printables, *, wordChars: str = printables + ) -> None: + wordChars = word_chars if wordChars == printables else wordChars + super().__init__() + self.wordChars = set(wordChars) + self.skipWhitespace = False + self.set_name("end of a word") + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + instrlen = len(instring) + if instrlen > 0 and loc < instrlen: + if ( + instring[loc] in self.wordChars + or instring[loc - 1] not in self.wordChars + ): + raise ParseException(instring, loc, self.errmsg, self) + return loc, [] + + +class Tag(Token): + """ + A meta-element for inserting a named result into the parsed + tokens that may be checked later in a parse action or while + processing the parsed results. Accepts an optional tag value, + defaulting to `True`. + + Example: + + .. doctest:: + + >>> end_punc = "." | ("!" + Tag("enthusiastic")) + >>> greeting = "Hello," + Word(alphas) + end_punc + + >>> result = greeting.parse_string("Hello, World.") + >>> print(result.dump()) + ['Hello,', 'World', '.'] + + >>> result = greeting.parse_string("Hello, World!") + >>> print(result.dump()) + ['Hello,', 'World', '!'] + - enthusiastic: True + + .. versionadded:: 3.1.0 + """ + + def __init__(self, tag_name: str, value: Any = True) -> None: + super().__init__() + self._may_return_empty = True + self.mayIndexError = False + self.leave_whitespace() + self.tag_name = tag_name + self.tag_value = value + self.add_parse_action(self._add_tag) + self.show_in_diagram = False + + def _add_tag(self, tokens: ParseResults): + tokens[self.tag_name] = self.tag_value + + def _generateDefaultName(self) -> str: + return f"{type(self).__name__}:{self.tag_name}={self.tag_value!r}" + + +class ParseExpression(ParserElement): + """Abstract subclass of ParserElement, for combining and + post-processing parsed tokens. + """ + + def __init__( + self, exprs: typing.Iterable[ParserElement], savelist: bool = False + ) -> None: + super().__init__(savelist) + self.exprs: list[ParserElement] + if isinstance(exprs, _generatorType): + exprs = list(exprs) + + if isinstance(exprs, str_type): + self.exprs = [self._literalStringClass(exprs)] + elif isinstance(exprs, ParserElement): + self.exprs = [exprs] + elif isinstance(exprs, Iterable): + exprs = list(exprs) + # if sequence of strings provided, wrap with Literal + if any(isinstance(expr, str_type) for expr in exprs): + exprs = ( + self._literalStringClass(e) if isinstance(e, str_type) else e + for e in exprs + ) + self.exprs = list(exprs) + else: + try: + self.exprs = list(exprs) + except TypeError: + self.exprs = [exprs] + self.callPreparse = False + + def recurse(self) -> list[ParserElement]: + return self.exprs[:] + + def append(self, other) -> ParserElement: + self.exprs.append(other) + self._defaultName = None + return self + + def leave_whitespace(self, recursive: bool = True) -> ParserElement: + """ + Extends ``leave_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on + all contained expressions. + """ + super().leave_whitespace(recursive) + + if recursive: + self.exprs = [e.copy() for e in self.exprs] + for e in self.exprs: + e.leave_whitespace(recursive) + return self + + def ignore_whitespace(self, recursive: bool = True) -> ParserElement: + """ + Extends ``ignore_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on + all contained expressions. + """ + super().ignore_whitespace(recursive) + if recursive: + self.exprs = [e.copy() for e in self.exprs] + for e in self.exprs: + e.ignore_whitespace(recursive) + return self + + def ignore(self, other) -> ParserElement: + if isinstance(other, Suppress): + if other not in self.ignoreExprs: + super().ignore(other) + for e in self.exprs: + e.ignore(self.ignoreExprs[-1]) + else: + super().ignore(other) + for e in self.exprs: + e.ignore(self.ignoreExprs[-1]) + return self + + def _generateDefaultName(self) -> str: + return f"{type(self).__name__}:({self.exprs})" + + def streamline(self) -> ParserElement: + if self.streamlined: + return self + + super().streamline() + + for e in self.exprs: + e.streamline() + + # collapse nested :class:`And`'s of the form ``And(And(And(a, b), c), d)`` to ``And(a, b, c, d)`` + # but only if there are no parse actions or resultsNames on the nested And's + # (likewise for :class:`Or`'s and :class:`MatchFirst`'s) + if len(self.exprs) == 2: + other = self.exprs[0] + if ( + isinstance(other, self.__class__) + and not other.parseAction + and other.resultsName is None + and not other.debug + ): + self.exprs = other.exprs[:] + [self.exprs[1]] + self._defaultName = None + self._may_return_empty |= other.mayReturnEmpty + self.mayIndexError |= other.mayIndexError + + other = self.exprs[-1] + if ( + isinstance(other, self.__class__) + and not other.parseAction + and other.resultsName is None + and not other.debug + ): + self.exprs = self.exprs[:-1] + other.exprs[:] + self._defaultName = None + self._may_return_empty |= other.mayReturnEmpty + self.mayIndexError |= other.mayIndexError + + self.errmsg = f"Expected {self}" + + return self + + def validate(self, validateTrace=None) -> None: + warnings.warn( + "ParserElement.validate() is deprecated, and should not be used to check for left recursion", + DeprecationWarning, + stacklevel=2, + ) + tmp = (validateTrace if validateTrace is not None else [])[:] + [self] + for e in self.exprs: + e.validate(tmp) + self._checkRecursion([]) + + def copy(self) -> ParserElement: + ret = super().copy() + ret = typing.cast(ParseExpression, ret) + ret.exprs = [e.copy() for e in self.exprs] + return ret + + def _setResultsName(self, name, list_all_matches=False) -> ParserElement: + if not ( + __diag__.warn_ungrouped_named_tokens_in_collection + and Diagnostics.warn_ungrouped_named_tokens_in_collection + not in self.suppress_warnings_ + ): + return super()._setResultsName(name, list_all_matches) + + for e in self.exprs: + if ( + isinstance(e, ParserElement) + and e.resultsName + and ( + Diagnostics.warn_ungrouped_named_tokens_in_collection + not in e.suppress_warnings_ + ) + ): + warning = ( + "warn_ungrouped_named_tokens_in_collection:" + f" setting results name {name!r} on {type(self).__name__} expression" + f" collides with {e.resultsName!r} on contained expression" + ) + warnings.warn(warning, stacklevel=3) + break + + return super()._setResultsName(name, list_all_matches) + + # Compatibility synonyms + # fmt: off + leaveWhitespace = replaced_by_pep8("leaveWhitespace", leave_whitespace) + ignoreWhitespace = replaced_by_pep8("ignoreWhitespace", ignore_whitespace) + # fmt: on + + +class And(ParseExpression): + """ + Requires all given :class:`ParserElement` s to be found in the given order. + Expressions may be separated by whitespace. + May be constructed using the ``'+'`` operator. + May also be constructed using the ``'-'`` operator, which will + suppress backtracking. + + Example: + + .. testcode:: + + integer = Word(nums) + name_expr = Word(alphas)[1, ...] + + expr = And([integer("id"), name_expr("name"), integer("age")]) + # more easily written as: + expr = integer("id") + name_expr("name") + integer("age") + """ + + class _ErrorStop(Empty): + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + self.leave_whitespace() + + def _generateDefaultName(self) -> str: + return "-" + + def __init__( + self, + exprs_arg: typing.Iterable[Union[ParserElement, str]], + savelist: bool = True, + ) -> None: + # instantiate exprs as a list, converting strs to ParserElements + exprs: list[ParserElement] = [ + self._literalStringClass(e) if isinstance(e, str) else e for e in exprs_arg + ] + + # convert any Ellipsis elements to SkipTo + if Ellipsis in exprs: + + # Ellipsis cannot be the last element + if exprs[-1] is Ellipsis: + raise Exception("cannot construct And with sequence ending in ...") + + tmp: list[ParserElement] = [] + for cur_expr, next_expr in zip(exprs, exprs[1:]): + if cur_expr is Ellipsis: + tmp.append(SkipTo(next_expr)("_skipped*")) + else: + tmp.append(cur_expr) + + exprs[:-1] = tmp + + super().__init__(exprs, savelist) + if self.exprs: + self._may_return_empty = all(e.mayReturnEmpty for e in self.exprs) + if not isinstance(self.exprs[0], White): + self.set_whitespace_chars( + self.exprs[0].whiteChars, + copy_defaults=self.exprs[0].copyDefaultWhiteChars, + ) + self.skipWhitespace = self.exprs[0].skipWhitespace + else: + self.skipWhitespace = False + else: + self._may_return_empty = True + self.callPreparse = True + + def streamline(self) -> ParserElement: + # collapse any _PendingSkip's + if self.exprs and any( + isinstance(e, ParseExpression) + and e.exprs + and isinstance(e.exprs[-1], _PendingSkip) + for e in self.exprs[:-1] + ): + deleted_expr_marker = NoMatch() + for i, e in enumerate(self.exprs[:-1]): + if e is deleted_expr_marker: + continue + if ( + isinstance(e, ParseExpression) + and e.exprs + and isinstance(e.exprs[-1], _PendingSkip) + ): + e.exprs[-1] = e.exprs[-1] + self.exprs[i + 1] + self.exprs[i + 1] = deleted_expr_marker + self.exprs = [e for e in self.exprs if e is not deleted_expr_marker] + + super().streamline() + + # link any IndentedBlocks to the prior expression + prev: ParserElement + cur: ParserElement + for prev, cur in zip(self.exprs, self.exprs[1:]): + # traverse cur or any first embedded expr of cur looking for an IndentedBlock + # (but watch out for recursive grammar) + seen = set() + while True: + if id(cur) in seen: + break + seen.add(id(cur)) + if isinstance(cur, IndentedBlock): + prev.add_parse_action( + lambda s, l, t, cur_=cur: setattr( + cur_, "parent_anchor", col(l, s) + ) + ) + break + subs = cur.recurse() + next_first = next(iter(subs), None) + if next_first is None: + break + cur = typing.cast(ParserElement, next_first) + + self._may_return_empty = all(e.mayReturnEmpty for e in self.exprs) + return self + + def parseImpl(self, instring, loc, do_actions=True): + # pass False as callPreParse arg to _parse for first element, since we already + # pre-parsed the string as part of our And pre-parsing + loc, resultlist = self.exprs[0]._parse( + instring, loc, do_actions, callPreParse=False + ) + errorStop = False + for e in self.exprs[1:]: + # if isinstance(e, And._ErrorStop): + if type(e) is And._ErrorStop: + errorStop = True + continue + if errorStop: + try: + loc, exprtokens = e._parse(instring, loc, do_actions) + except ParseSyntaxException: + raise + except ParseBaseException as pe: + pe.__traceback__ = None + raise ParseSyntaxException._from_exception(pe) + except IndexError: + raise ParseSyntaxException( + instring, len(instring), self.errmsg, self + ) + else: + loc, exprtokens = e._parse(instring, loc, do_actions) + resultlist += exprtokens + return loc, resultlist + + def __iadd__(self, other): + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return self.append(other) # And([self, other]) + + def _checkRecursion(self, parseElementList): + subRecCheckList = parseElementList[:] + [self] + for e in self.exprs: + e._checkRecursion(subRecCheckList) + if not e.mayReturnEmpty: + break + + def _generateDefaultName(self) -> str: + inner = " ".join(str(e) for e in self.exprs) + # strip off redundant inner {}'s + while len(inner) > 1 and inner[0 :: len(inner) - 1] == "{}": + inner = inner[1:-1] + return f"{{{inner}}}" + + +class Or(ParseExpression): + """Requires that at least one :class:`ParserElement` is found. If + two expressions match, the expression that matches the longest + string will be used. May be constructed using the ``'^'`` + operator. + + Example: + + .. testcode:: + + # construct Or using '^' operator + + number = Word(nums) ^ Combine(Word(nums) + '.' + Word(nums)) + print(number.search_string("123 3.1416 789")) + + prints: + + .. testoutput:: + + [['123'], ['3.1416'], ['789']] + """ + + def __init__( + self, exprs: typing.Iterable[ParserElement], savelist: bool = False + ) -> None: + super().__init__(exprs, savelist) + if self.exprs: + self._may_return_empty = any(e.mayReturnEmpty for e in self.exprs) + self.skipWhitespace = all(e.skipWhitespace for e in self.exprs) + else: + self._may_return_empty = True + + def streamline(self) -> ParserElement: + super().streamline() + if self.exprs: + self._may_return_empty = any(e.mayReturnEmpty for e in self.exprs) + self.saveAsList = any(e.saveAsList for e in self.exprs) + self.skipWhitespace = all( + e.skipWhitespace and not isinstance(e, White) for e in self.exprs + ) + else: + self.saveAsList = False + return self + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + maxExcLoc = -1 + maxException = None + matches: list[tuple[int, ParserElement]] = [] + fatals: list[ParseFatalException] = [] + if all(e.callPreparse for e in self.exprs): + loc = self.preParse(instring, loc) + for e in self.exprs: + try: + loc2 = e.try_parse(instring, loc, raise_fatal=True) + except ParseFatalException as pfe: + pfe.__traceback__ = None + pfe.parser_element = e + fatals.append(pfe) + maxException = None + maxExcLoc = -1 + except ParseException as err: + if not fatals: + err.__traceback__ = None + if err.loc > maxExcLoc: + maxException = err + maxExcLoc = err.loc + except IndexError: + if len(instring) > maxExcLoc: + maxException = ParseException( + instring, len(instring), e.errmsg, self + ) + maxExcLoc = len(instring) + else: + # save match among all matches, to retry longest to shortest + matches.append((loc2, e)) + + if matches: + # re-evaluate all matches in descending order of length of match, in case attached actions + # might change whether or how much they match of the input. + matches.sort(key=itemgetter(0), reverse=True) + + if not do_actions: + # no further conditions or parse actions to change the selection of + # alternative, so the first match will be the best match + best_expr = matches[0][1] + return best_expr._parse(instring, loc, do_actions) + + longest: tuple[int, typing.Optional[ParseResults]] = -1, None + for loc1, expr1 in matches: + if loc1 <= longest[0]: + # already have a longer match than this one will deliver, we are done + return longest + + try: + loc2, toks = expr1._parse(instring, loc, do_actions) + except ParseException as err: + err.__traceback__ = None + if err.loc > maxExcLoc: + maxException = err + maxExcLoc = err.loc + else: + if loc2 >= loc1: + return loc2, toks + # didn't match as much as before + elif loc2 > longest[0]: + longest = loc2, toks + + if longest != (-1, None): + return longest + + if fatals: + if len(fatals) > 1: + fatals.sort(key=lambda e: -e.loc) + if fatals[0].loc == fatals[1].loc: + fatals.sort(key=lambda e: (-e.loc, -len(str(e.parser_element)))) + max_fatal = fatals[0] + raise max_fatal + + if maxException is not None: + # infer from this check that all alternatives failed at the current position + # so emit this collective error message instead of any single error message + parse_start_loc = self.preParse(instring, loc) + if maxExcLoc == parse_start_loc: + maxException.msg = self.errmsg or "" + raise maxException + + raise ParseException(instring, loc, "no defined alternatives to match", self) + + def __ixor__(self, other): + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return self.append(other) # Or([self, other]) + + def _generateDefaultName(self) -> str: + return f"{{{' ^ '.join(str(e) for e in self.exprs)}}}" + + def _setResultsName(self, name, list_all_matches=False) -> ParserElement: + if ( + __diag__.warn_multiple_tokens_in_named_alternation + and Diagnostics.warn_multiple_tokens_in_named_alternation + not in self.suppress_warnings_ + ): + if any( + isinstance(e, And) + and Diagnostics.warn_multiple_tokens_in_named_alternation + not in e.suppress_warnings_ + for e in self.exprs + ): + warning = ( + "warn_multiple_tokens_in_named_alternation:" + f" setting results name {name!r} on {type(self).__name__} expression" + " will return a list of all parsed tokens in an And alternative," + " in prior versions only the first token was returned; enclose" + " contained argument in Group" + ) + warnings.warn(warning, stacklevel=3) + + return super()._setResultsName(name, list_all_matches) + + +class MatchFirst(ParseExpression): + """Requires that at least one :class:`ParserElement` is found. If + more than one expression matches, the first one listed is the one that will + match. May be constructed using the ``'|'`` operator. + + Example: Construct MatchFirst using '|' operator + + .. doctest:: + + # watch the order of expressions to match + >>> number = Word(nums) | Combine(Word(nums) + '.' + Word(nums)) + >>> print(number.search_string("123 3.1416 789")) # Fail! + [['123'], ['3'], ['1416'], ['789']] + + # put more selective expression first + >>> number = Combine(Word(nums) + '.' + Word(nums)) | Word(nums) + >>> print(number.search_string("123 3.1416 789")) # Better + [['123'], ['3.1416'], ['789']] + """ + + def __init__( + self, exprs: typing.Iterable[ParserElement], savelist: bool = False + ) -> None: + super().__init__(exprs, savelist) + if self.exprs: + self._may_return_empty = any(e.mayReturnEmpty for e in self.exprs) + self.skipWhitespace = all(e.skipWhitespace for e in self.exprs) + else: + self._may_return_empty = True + + def streamline(self) -> ParserElement: + if self.streamlined: + return self + + super().streamline() + if self.exprs: + self.saveAsList = any(e.saveAsList for e in self.exprs) + self._may_return_empty = any(e.mayReturnEmpty for e in self.exprs) + self.skipWhitespace = all( + e.skipWhitespace and not isinstance(e, White) for e in self.exprs + ) + else: + self.saveAsList = False + self._may_return_empty = True + return self + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + maxExcLoc = -1 + maxException = None + + for e in self.exprs: + try: + return e._parse(instring, loc, do_actions) + except ParseFatalException as pfe: + pfe.__traceback__ = None + pfe.parser_element = e + raise + except ParseException as err: + if err.loc > maxExcLoc: + maxException = err + maxExcLoc = err.loc + except IndexError: + if len(instring) > maxExcLoc: + maxException = ParseException( + instring, len(instring), e.errmsg, self + ) + maxExcLoc = len(instring) + + if maxException is not None: + # infer from this check that all alternatives failed at the current position + # so emit this collective error message instead of any individual error message + parse_start_loc = self.preParse(instring, loc) + if maxExcLoc == parse_start_loc: + maxException.msg = self.errmsg or "" + raise maxException + + raise ParseException(instring, loc, "no defined alternatives to match", self) + + def __ior__(self, other): + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return self.append(other) # MatchFirst([self, other]) + + def _generateDefaultName(self) -> str: + return f"{{{' | '.join(str(e) for e in self.exprs)}}}" + + def _setResultsName(self, name, list_all_matches=False) -> ParserElement: + if ( + __diag__.warn_multiple_tokens_in_named_alternation + and Diagnostics.warn_multiple_tokens_in_named_alternation + not in self.suppress_warnings_ + ): + if any( + isinstance(e, And) + and Diagnostics.warn_multiple_tokens_in_named_alternation + not in e.suppress_warnings_ + for e in self.exprs + ): + warning = ( + "warn_multiple_tokens_in_named_alternation:" + f" setting results name {name!r} on {type(self).__name__} expression" + " will return a list of all parsed tokens in an And alternative," + " in prior versions only the first token was returned; enclose" + " contained argument in Group" + ) + warnings.warn(warning, stacklevel=3) + + return super()._setResultsName(name, list_all_matches) + + +class Each(ParseExpression): + """Requires all given :class:`ParserElement` s to be found, but in + any order. Expressions may be separated by whitespace. + + May be constructed using the ``'&'`` operator. + + Example: + + .. testcode:: + + color = one_of("RED ORANGE YELLOW GREEN BLUE PURPLE BLACK WHITE BROWN") + shape_type = one_of("SQUARE CIRCLE TRIANGLE STAR HEXAGON OCTAGON") + integer = Word(nums) + shape_attr = "shape:" + shape_type("shape") + posn_attr = "posn:" + Group(integer("x") + ',' + integer("y"))("posn") + color_attr = "color:" + color("color") + size_attr = "size:" + integer("size") + + # use Each (using operator '&') to accept attributes in any order + # (shape and posn are required, color and size are optional) + shape_spec = shape_attr & posn_attr & Opt(color_attr) & Opt(size_attr) + + shape_spec.run_tests(''' + shape: SQUARE color: BLACK posn: 100, 120 + shape: CIRCLE size: 50 color: BLUE posn: 50,80 + color:GREEN size:20 shape:TRIANGLE posn:20,40 + ''' + ) + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + shape: SQUARE color: BLACK posn: 100, 120 + ['shape:', 'SQUARE', 'color:', 'BLACK', 'posn:', ['100', ',', '120']] + - color: 'BLACK' + - posn: ['100', ',', '120'] + - x: '100' + - y: '120' + - shape: 'SQUARE' + ... + + shape: CIRCLE size: 50 color: BLUE posn: 50,80 + ['shape:', 'CIRCLE', 'size:', '50', 'color:', 'BLUE', + 'posn:', ['50', ',', '80']] + - color: 'BLUE' + - posn: ['50', ',', '80'] + - x: '50' + - y: '80' + - shape: 'CIRCLE' + - size: '50' + ... + + color:GREEN size:20 shape:TRIANGLE posn:20,40 + ['color:', 'GREEN', 'size:', '20', 'shape:', 'TRIANGLE', + 'posn:', ['20', ',', '40']] + - color: 'GREEN' + - posn: ['20', ',', '40'] + - x: '20' + - y: '40' + - shape: 'TRIANGLE' + - size: '20' + ... + """ + + def __init__( + self, exprs: typing.Iterable[ParserElement], savelist: bool = True + ) -> None: + super().__init__(exprs, savelist) + if self.exprs: + self._may_return_empty = all(e.mayReturnEmpty for e in self.exprs) + else: + self._may_return_empty = True + self.skipWhitespace = True + self.initExprGroups = True + self.saveAsList = True + + def __iand__(self, other): + if isinstance(other, str_type): + other = self._literalStringClass(other) + if not isinstance(other, ParserElement): + return NotImplemented + return self.append(other) # Each([self, other]) + + def streamline(self) -> ParserElement: + super().streamline() + if self.exprs: + self._may_return_empty = all(e.mayReturnEmpty for e in self.exprs) + else: + self._may_return_empty = True + return self + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if self.initExprGroups: + self.opt1map = dict( + (id(e.expr), e) for e in self.exprs if isinstance(e, Opt) + ) + opt1 = [e.expr for e in self.exprs if isinstance(e, Opt)] + opt2 = [ + e + for e in self.exprs + if e.mayReturnEmpty and not isinstance(e, (Opt, Regex, ZeroOrMore)) + ] + self.optionals = opt1 + opt2 + self.multioptionals = [ + e.expr.set_results_name(e.resultsName, list_all_matches=True) + for e in self.exprs + if isinstance(e, _MultipleMatch) + ] + self.multirequired = [ + e.expr.set_results_name(e.resultsName, list_all_matches=True) + for e in self.exprs + if isinstance(e, OneOrMore) + ] + self.required = [ + e for e in self.exprs if not isinstance(e, (Opt, ZeroOrMore, OneOrMore)) + ] + self.required += self.multirequired + self.initExprGroups = False + + tmpLoc = loc + tmpReqd = self.required[:] + tmpOpt = self.optionals[:] + multis = self.multioptionals[:] + matchOrder: list[ParserElement] = [] + + keepMatching = True + failed: list[ParserElement] = [] + fatals: list[ParseFatalException] = [] + while keepMatching: + tmpExprs = tmpReqd + tmpOpt + multis + failed.clear() + fatals.clear() + for e in tmpExprs: + try: + tmpLoc = e.try_parse(instring, tmpLoc, raise_fatal=True) + except ParseFatalException as pfe: + pfe.__traceback__ = None + pfe.parser_element = e + fatals.append(pfe) + failed.append(e) + except ParseException: + failed.append(e) + else: + matchOrder.append(self.opt1map.get(id(e), e)) + if e in tmpReqd: + tmpReqd.remove(e) + elif e in tmpOpt: + tmpOpt.remove(e) + if len(failed) == len(tmpExprs): + keepMatching = False + + # look for any ParseFatalExceptions + if fatals: + if len(fatals) > 1: + fatals.sort(key=lambda e: -e.loc) + if fatals[0].loc == fatals[1].loc: + fatals.sort(key=lambda e: (-e.loc, -len(str(e.parser_element)))) + max_fatal = fatals[0] + raise max_fatal + + if tmpReqd: + missing = ", ".join([str(e) for e in tmpReqd]) + raise ParseException( + instring, + loc, + f"Missing one or more required elements ({missing})", + ) + + # add any unmatched Opts, in case they have default values defined + matchOrder += [e for e in self.exprs if isinstance(e, Opt) and e.expr in tmpOpt] + + total_results = ParseResults([]) + for e in matchOrder: + loc, results = e._parse(instring, loc, do_actions) + total_results += results + + return loc, total_results + + def _generateDefaultName(self) -> str: + return f"{{{' & '.join(str(e) for e in self.exprs)}}}" + + +class ParseElementEnhance(ParserElement): + """Abstract subclass of :class:`ParserElement`, for combining and + post-processing parsed tokens. + """ + + def __init__(self, expr: Union[ParserElement, str], savelist: bool = False) -> None: + super().__init__(savelist) + if isinstance(expr, str_type): + expr_str = typing.cast(str, expr) + if issubclass(self._literalStringClass, Token): + expr = self._literalStringClass(expr_str) # type: ignore[call-arg] + elif issubclass(type(self), self._literalStringClass): + expr = Literal(expr_str) + else: + expr = self._literalStringClass(Literal(expr_str)) # type: ignore[assignment, call-arg] + expr = typing.cast(ParserElement, expr) + self.expr = expr + if expr is not None: + self.mayIndexError = expr.mayIndexError + self._may_return_empty = expr.mayReturnEmpty + self.set_whitespace_chars( + expr.whiteChars, copy_defaults=expr.copyDefaultWhiteChars + ) + self.skipWhitespace = expr.skipWhitespace + self.saveAsList = expr.saveAsList + self.callPreparse = expr.callPreparse + self.ignoreExprs.extend(expr.ignoreExprs) + + def recurse(self) -> list[ParserElement]: + return [self.expr] if self.expr is not None else [] + + def parseImpl(self, instring, loc, do_actions=True): + if self.expr is None: + raise ParseException(instring, loc, "No expression defined", self) + + try: + return self.expr._parse(instring, loc, do_actions, callPreParse=False) + except ParseSyntaxException: + raise + except ParseBaseException as pbe: + pbe.pstr = pbe.pstr or instring + pbe.loc = pbe.loc or loc + pbe.parser_element = pbe.parser_element or self + if not isinstance(self, Forward) and self.customName is not None: + if self.errmsg: + pbe.msg = self.errmsg + raise + + def leave_whitespace(self, recursive: bool = True) -> ParserElement: + super().leave_whitespace(recursive) + + if recursive: + if self.expr is not None: + self.expr = self.expr.copy() + self.expr.leave_whitespace(recursive) + return self + + def ignore_whitespace(self, recursive: bool = True) -> ParserElement: + super().ignore_whitespace(recursive) + + if recursive: + if self.expr is not None: + self.expr = self.expr.copy() + self.expr.ignore_whitespace(recursive) + return self + + def ignore(self, other) -> ParserElement: + if not isinstance(other, Suppress) or other not in self.ignoreExprs: + super().ignore(other) + if self.expr is not None: + self.expr.ignore(self.ignoreExprs[-1]) + + return self + + def streamline(self) -> ParserElement: + super().streamline() + if self.expr is not None: + self.expr.streamline() + return self + + def _checkRecursion(self, parseElementList): + if self in parseElementList: + raise RecursiveGrammarException(parseElementList + [self]) + subRecCheckList = parseElementList[:] + [self] + if self.expr is not None: + self.expr._checkRecursion(subRecCheckList) + + def validate(self, validateTrace=None) -> None: + warnings.warn( + "ParserElement.validate() is deprecated, and should not be used to check for left recursion", + DeprecationWarning, + stacklevel=2, + ) + if validateTrace is None: + validateTrace = [] + tmp = validateTrace[:] + [self] + if self.expr is not None: + self.expr.validate(tmp) + self._checkRecursion([]) + + def _generateDefaultName(self) -> str: + return f"{type(self).__name__}:({self.expr})" + + # Compatibility synonyms + # fmt: off + leaveWhitespace = replaced_by_pep8("leaveWhitespace", leave_whitespace) + ignoreWhitespace = replaced_by_pep8("ignoreWhitespace", ignore_whitespace) + # fmt: on + + +class IndentedBlock(ParseElementEnhance): + """ + Expression to match one or more expressions at a given indentation level. + Useful for parsing text where structure is implied by indentation (like Python source code). + """ + + class _Indent(Empty): + def __init__(self, ref_col: int) -> None: + super().__init__() + self.errmsg = f"expected indent at column {ref_col}" + self.add_condition(lambda s, l, t: col(l, s) == ref_col) + + class _IndentGreater(Empty): + def __init__(self, ref_col: int) -> None: + super().__init__() + self.errmsg = f"expected indent at column greater than {ref_col}" + self.add_condition(lambda s, l, t: col(l, s) > ref_col) + + def __init__( + self, expr: ParserElement, *, recursive: bool = False, grouped: bool = True + ) -> None: + super().__init__(expr, savelist=True) + # if recursive: + # raise NotImplementedError("IndentedBlock with recursive is not implemented") + self._recursive = recursive + self._grouped = grouped + self.parent_anchor = 1 + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + # advance parse position to non-whitespace by using an Empty() + # this should be the column to be used for all subsequent indented lines + anchor_loc = Empty().preParse(instring, loc) + + # see if self.expr matches at the current location - if not it will raise an exception + # and no further work is necessary + self.expr.try_parse(instring, anchor_loc, do_actions=do_actions) + + indent_col = col(anchor_loc, instring) + peer_detect_expr = self._Indent(indent_col) + + inner_expr = Empty() + peer_detect_expr + self.expr + if self._recursive: + sub_indent = self._IndentGreater(indent_col) + nested_block = IndentedBlock( + self.expr, recursive=self._recursive, grouped=self._grouped + ) + nested_block.set_debug(self.debug) + nested_block.parent_anchor = indent_col + inner_expr += Opt(sub_indent + nested_block) + + inner_expr.set_name(f"inner {hex(id(inner_expr))[-4:].upper()}@{indent_col}") + block = OneOrMore(inner_expr) + + trailing_undent = self._Indent(self.parent_anchor) | StringEnd() + + if self._grouped: + wrapper = Group + else: + wrapper = lambda expr: expr # type: ignore[misc, assignment] + return (wrapper(block) + Optional(trailing_undent)).parseImpl( + instring, anchor_loc, do_actions + ) + + +class AtStringStart(ParseElementEnhance): + """Matches if expression matches at the beginning of the parse + string:: + + AtStringStart(Word(nums)).parse_string("123") + # prints ["123"] + + AtStringStart(Word(nums)).parse_string(" 123") + # raises ParseException + """ + + def __init__(self, expr: Union[ParserElement, str]) -> None: + super().__init__(expr) + self.callPreparse = False + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if loc != 0: + raise ParseException(instring, loc, "not found at string start") + return super().parseImpl(instring, loc, do_actions) + + +class AtLineStart(ParseElementEnhance): + r"""Matches if an expression matches at the beginning of a line within + the parse string + + Example: + + .. testcode:: + + test = '''\ + BBB this line + BBB and this line + BBB but not this one + A BBB and definitely not this one + ''' + + for t in (AtLineStart('BBB') + rest_of_line).search_string(test): + print(t) + + prints: + + .. testoutput:: + + ['BBB', ' this line'] + ['BBB', ' and this line'] + """ + + def __init__(self, expr: Union[ParserElement, str]) -> None: + super().__init__(expr) + self.callPreparse = False + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if col(loc, instring) != 1: + raise ParseException(instring, loc, "not found at line start") + return super().parseImpl(instring, loc, do_actions) + + +class FollowedBy(ParseElementEnhance): + """Lookahead matching of the given parse expression. + ``FollowedBy`` does *not* advance the parsing position within + the input string, it only verifies that the specified parse + expression matches at the current position. ``FollowedBy`` + always returns a null token list. If any results names are defined + in the lookahead expression, those *will* be returned for access by + name. + + Example: + + .. testcode:: + + # use FollowedBy to match a label only if it is followed by a ':' + data_word = Word(alphas) + label = data_word + FollowedBy(':') + attr_expr = Group( + label + Suppress(':') + + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join) + ) + + attr_expr[1, ...].parse_string( + "shape: SQUARE color: BLACK posn: upper left").pprint() + + prints: + + .. testoutput:: + + [['shape', 'SQUARE'], ['color', 'BLACK'], ['posn', 'upper left']] + """ + + def __init__(self, expr: Union[ParserElement, str]) -> None: + super().__init__(expr) + self._may_return_empty = True + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + # by using self._expr.parse and deleting the contents of the returned ParseResults list + # we keep any named results that were defined in the FollowedBy expression + _, ret = self.expr._parse(instring, loc, do_actions=do_actions) + del ret[:] + + return loc, ret + + +class PrecededBy(ParseElementEnhance): + """Lookbehind matching of the given parse expression. + ``PrecededBy`` does not advance the parsing position within the + input string, it only verifies that the specified parse expression + matches prior to the current position. ``PrecededBy`` always + returns a null token list, but if a results name is defined on the + given expression, it is returned. + + Parameters: + + - ``expr`` - expression that must match prior to the current parse + location + - ``retreat`` - (default= ``None``) - (int) maximum number of characters + to lookbehind prior to the current parse location + + If the lookbehind expression is a string, :class:`Literal`, + :class:`Keyword`, or a :class:`Word` or :class:`CharsNotIn` + with a specified exact or maximum length, then the retreat + parameter is not required. Otherwise, retreat must be specified to + give a maximum number of characters to look back from + the current parse position for a lookbehind match. + + Example: + + .. testcode:: + + # VB-style variable names with type prefixes + int_var = PrecededBy("#") + pyparsing_common.identifier + str_var = PrecededBy("$") + pyparsing_common.identifier + """ + + def __init__(self, expr: Union[ParserElement, str], retreat: int = 0) -> None: + super().__init__(expr) + self.expr = self.expr().leave_whitespace() + self._may_return_empty = True + self.mayIndexError = False + self.exact = False + if isinstance(expr, str_type): + expr = typing.cast(str, expr) + retreat = len(expr) + self.exact = True + elif isinstance(expr, (Literal, Keyword)): + retreat = expr.matchLen + self.exact = True + elif isinstance(expr, (Word, CharsNotIn)) and expr.maxLen != _MAX_INT: + retreat = expr.maxLen + self.exact = True + elif isinstance(expr, PositionToken): + retreat = 0 + self.exact = True + self.retreat = retreat + self.errmsg = f"not preceded by {expr}" + self.skipWhitespace = False + self.parseAction.append(lambda s, l, t: t.__delitem__(slice(None, None))) + + def parseImpl(self, instring, loc=0, do_actions=True) -> ParseImplReturnType: + if self.exact: + if loc < self.retreat: + raise ParseException(instring, loc, self.errmsg, self) + start = loc - self.retreat + _, ret = self.expr._parse(instring, start) + return loc, ret + + # retreat specified a maximum lookbehind window, iterate + test_expr = self.expr + StringEnd() + instring_slice = instring[max(0, loc - self.retreat) : loc] + last_expr: ParseBaseException = ParseException(instring, loc, self.errmsg, self) + + for offset in range(1, min(loc, self.retreat + 1) + 1): + try: + # print('trying', offset, instring_slice, repr(instring_slice[loc - offset:])) + _, ret = test_expr._parse(instring_slice, len(instring_slice) - offset) + except ParseBaseException as pbe: + last_expr = pbe + else: + break + else: + raise last_expr + + return loc, ret + + +class Located(ParseElementEnhance): + """ + Decorates a returned token with its starting and ending + locations in the input string. + + This helper adds the following results names: + + - ``locn_start`` - location where matched expression begins + - ``locn_end`` - location where matched expression ends + - ``value`` - the actual parsed results + + Be careful if the input text contains ```` characters, you + may want to call :class:`ParserElement.parse_with_tabs` + + Example: + + .. testcode:: + + wd = Word(alphas) + for match in Located(wd).search_string("ljsdf123lksdjjf123lkkjj1222"): + print(match) + + prints: + + .. testoutput:: + + [0, ['ljsdf'], 5] + [8, ['lksdjjf'], 15] + [18, ['lkkjj'], 23] + """ + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + start = loc + loc, tokens = self.expr._parse(instring, start, do_actions, callPreParse=False) + ret_tokens = ParseResults([start, tokens, loc]) + ret_tokens["locn_start"] = start + ret_tokens["value"] = tokens + ret_tokens["locn_end"] = loc + if self.resultsName: + # must return as a list, so that the name will be attached to the complete group + return loc, [ret_tokens] + else: + return loc, ret_tokens + + +class NotAny(ParseElementEnhance): + """ + Lookahead to disallow matching with the given parse expression. + ``NotAny`` does *not* advance the parsing position within the + input string, it only verifies that the specified parse expression + does *not* match at the current position. Also, ``NotAny`` does + *not* skip over leading whitespace. ``NotAny`` always returns + a null token list. May be constructed using the ``'~'`` operator. + + Example: + + .. testcode:: + + AND, OR, NOT = map(CaselessKeyword, "AND OR NOT".split()) + + # take care not to mistake keywords for identifiers + ident = ~(AND | OR | NOT) + Word(alphas) + boolean_term = Opt(NOT) + ident + + # very crude boolean expression - to support parenthesis groups and + # operation hierarchy, use infix_notation + boolean_expr = boolean_term + ((AND | OR) + boolean_term)[...] + + # integers that are followed by "." are actually floats + integer = Word(nums) + ~Char(".") + """ + + def __init__(self, expr: Union[ParserElement, str]) -> None: + super().__init__(expr) + # do NOT use self.leave_whitespace(), don't want to propagate to exprs + # self.leave_whitespace() + self.skipWhitespace = False + + self._may_return_empty = True + self.errmsg = f"Found unwanted token, {self.expr}" + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if self.expr.can_parse_next(instring, loc, do_actions=do_actions): + raise ParseException(instring, loc, self.errmsg, self) + return loc, [] + + def _generateDefaultName(self) -> str: + return f"~{{{self.expr}}}" + + +class _MultipleMatch(ParseElementEnhance): + def __init__( + self, + expr: Union[str, ParserElement], + stop_on: typing.Optional[Union[ParserElement, str]] = None, + *, + stopOn: typing.Optional[Union[ParserElement, str]] = None, + ) -> None: + super().__init__(expr) + stopOn = stopOn or stop_on + self.saveAsList = True + ender = stopOn + if isinstance(ender, str_type): + ender = self._literalStringClass(ender) + self.stopOn(ender) + + def stopOn(self, ender) -> ParserElement: + if isinstance(ender, str_type): + ender = self._literalStringClass(ender) + self.not_ender = ~ender if ender is not None else None + return self + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + self_expr_parse = self.expr._parse + self_skip_ignorables = self._skipIgnorables + check_ender = False + if self.not_ender is not None: + try_not_ender = self.not_ender.try_parse + check_ender = True + + # must be at least one (but first see if we are the stopOn sentinel; + # if so, fail) + if check_ender: + try_not_ender(instring, loc) + loc, tokens = self_expr_parse(instring, loc, do_actions) + try: + hasIgnoreExprs = not not self.ignoreExprs + while 1: + if check_ender: + try_not_ender(instring, loc) + if hasIgnoreExprs: + preloc = self_skip_ignorables(instring, loc) + else: + preloc = loc + loc, tmptokens = self_expr_parse(instring, preloc, do_actions) + tokens += tmptokens + except (ParseException, IndexError): + pass + + return loc, tokens + + def _setResultsName(self, name, list_all_matches=False) -> ParserElement: + if ( + __diag__.warn_ungrouped_named_tokens_in_collection + and Diagnostics.warn_ungrouped_named_tokens_in_collection + not in self.suppress_warnings_ + ): + for e in [self.expr] + self.expr.recurse(): + if ( + isinstance(e, ParserElement) + and e.resultsName + and ( + Diagnostics.warn_ungrouped_named_tokens_in_collection + not in e.suppress_warnings_ + ) + ): + warning = ( + "warn_ungrouped_named_tokens_in_collection:" + f" setting results name {name!r} on {type(self).__name__} expression" + f" collides with {e.resultsName!r} on contained expression" + ) + warnings.warn(warning, stacklevel=3) + break + + return super()._setResultsName(name, list_all_matches) + + +class OneOrMore(_MultipleMatch): + """ + Repetition of one or more of the given expression. + + Parameters: + + - ``expr`` - expression that must match one or more times + - ``stop_on`` - (default= ``None``) - expression for a terminating sentinel + (only required if the sentinel would ordinarily match the repetition + expression) + + Example: + + .. doctest:: + + >>> data_word = Word(alphas) + >>> label = data_word + FollowedBy(':') + >>> attr_expr = Group( + ... label + Suppress(':') + ... + OneOrMore(data_word).set_parse_action(' '.join)) + + >>> text = "shape: SQUARE posn: upper left color: BLACK" + + # Fail! read 'posn' as data instead of next label + >>> attr_expr[1, ...].parse_string(text).pprint() + [['shape', 'SQUARE posn']] + + # use stop_on attribute for OneOrMore + # to avoid reading label string as part of the data + >>> attr_expr = Group( + ... label + Suppress(':') + ... + OneOrMore( + ... data_word, stop_on=label).set_parse_action(' '.join)) + >>> OneOrMore(attr_expr).parse_string(text).pprint() # Better + [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']] + + # could also be written as + >>> (attr_expr * (1,)).parse_string(text).pprint() + [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']] + """ + + def _generateDefaultName(self) -> str: + return f"{{{self.expr}}}..." + + +class ZeroOrMore(_MultipleMatch): + """ + Optional repetition of zero or more of the given expression. + + Parameters: + + - ``expr`` - expression that must match zero or more times + - ``stop_on`` - expression for a terminating sentinel + (only required if the sentinel would ordinarily match the repetition + expression) - (default= ``None``) + + Example: similar to :class:`OneOrMore` + """ + + def __init__( + self, + expr: Union[str, ParserElement], + stop_on: typing.Optional[Union[ParserElement, str]] = None, + *, + stopOn: typing.Optional[Union[ParserElement, str]] = None, + ) -> None: + super().__init__(expr, stopOn=stopOn or stop_on) + self._may_return_empty = True + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + try: + return super().parseImpl(instring, loc, do_actions) + except (ParseException, IndexError): + return loc, ParseResults([], name=self.resultsName) + + def _generateDefaultName(self) -> str: + return f"[{self.expr}]..." + + +class DelimitedList(ParseElementEnhance): + """Helper to define a delimited list of expressions - the delimiter + defaults to ','. By default, the list elements and delimiters can + have intervening whitespace, and comments, but this can be + overridden by passing ``combine=True`` in the constructor. If + ``combine`` is set to ``True``, the matching tokens are + returned as a single token string, with the delimiters included; + otherwise, the matching tokens are returned as a list of tokens, + with the delimiters suppressed. + + If ``allow_trailing_delim`` is set to True, then the list may end with + a delimiter. + + Example: + + .. doctest:: + + >>> DelimitedList(Word(alphas)).parse_string("aa,bb,cc") + ParseResults(['aa', 'bb', 'cc'], {}) + >>> DelimitedList(Word(hexnums), delim=':', combine=True + ... ).parse_string("AA:BB:CC:DD:EE") + ParseResults(['AA:BB:CC:DD:EE'], {}) + + .. versionadded:: 3.1.0 + """ + + def __init__( + self, + expr: Union[str, ParserElement], + delim: Union[str, ParserElement] = ",", + combine: bool = False, + min: typing.Optional[int] = None, + max: typing.Optional[int] = None, + *, + allow_trailing_delim: bool = False, + ) -> None: + if isinstance(expr, str_type): + expr = ParserElement._literalStringClass(expr) + expr = typing.cast(ParserElement, expr) + + if min is not None and min < 1: + raise ValueError("min must be greater than 0") + + if max is not None and min is not None and max < min: + raise ValueError("max must be greater than, or equal to min") + + self.content = expr + self.raw_delim = str(delim) + self.delim = delim + self.combine = combine + if not combine: + self.delim = Suppress(delim) + self.min = min or 1 + self.max = max + self.allow_trailing_delim = allow_trailing_delim + + delim_list_expr = self.content + (self.delim + self.content) * ( + self.min - 1, + None if self.max is None else self.max - 1, + ) + if self.allow_trailing_delim: + delim_list_expr += Opt(self.delim) + + if self.combine: + delim_list_expr = Combine(delim_list_expr) + + super().__init__(delim_list_expr, savelist=True) + + def _generateDefaultName(self) -> str: + content_expr = self.content.streamline() + return f"{content_expr} [{self.raw_delim} {content_expr}]..." + + +class _NullToken: + def __bool__(self): + return False + + def __str__(self): + return "" + + +class Opt(ParseElementEnhance): + """ + Optional matching of the given expression. + + :param expr: expression that must match zero or more times + :param default: (optional) - value to be returned + if the optional expression is not found. + + Example: + + .. testcode:: + + # US postal code can be a 5-digit zip, plus optional 4-digit qualifier + zip = Combine(Word(nums, exact=5) + Opt('-' + Word(nums, exact=4))) + zip.run_tests(''' + # traditional ZIP code + 12345 + + # ZIP+4 form + 12101-0001 + + # invalid ZIP + 98765- + ''') + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + # traditional ZIP code + 12345 + ['12345'] + + # ZIP+4 form + 12101-0001 + ['12101-0001'] + + # invalid ZIP + 98765- + 98765- + ^ + ParseException: Expected end of text, found '-' (at char 5), (line:1, col:6) + FAIL: Expected end of text, found '-' (at char 5), (line:1, col:6) + """ + + __optionalNotMatched = _NullToken() + + def __init__( + self, expr: Union[ParserElement, str], default: Any = __optionalNotMatched + ) -> None: + super().__init__(expr, savelist=False) + self.saveAsList = self.expr.saveAsList + self.defaultValue = default + self._may_return_empty = True + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + self_expr = self.expr + try: + loc, tokens = self_expr._parse( + instring, loc, do_actions, callPreParse=False + ) + except (ParseException, IndexError): + default_value = self.defaultValue + if default_value is not self.__optionalNotMatched: + if self_expr.resultsName: + tokens = ParseResults([default_value]) + tokens[self_expr.resultsName] = default_value + else: + tokens = [default_value] # type: ignore[assignment] + else: + tokens = [] # type: ignore[assignment] + return loc, tokens + + def _generateDefaultName(self) -> str: + inner = str(self.expr) + # strip off redundant inner {}'s + while len(inner) > 1 and inner[0 :: len(inner) - 1] == "{}": + inner = inner[1:-1] + return f"[{inner}]" + + +Optional = Opt + + +class SkipTo(ParseElementEnhance): + """ + Token for skipping over all undefined text until the matched + expression is found. + + :param expr: target expression marking the end of the data to be skipped + :param include: if ``True``, the target expression is also parsed + (the skipped text and target expression are returned + as a 2-element list) (default= ``False``). + + :param ignore: (default= ``None``) used to define grammars + (typically quoted strings and comments) + that might contain false matches to the target expression + + :param fail_on: (default= ``None``) define expressions that + are not allowed to be included in the skipped test; + if found before the target expression is found, + the :class:`SkipTo` is not a match + + Example: + + .. testcode:: + + report = ''' + Outstanding Issues Report - 1 Jan 2000 + + # | Severity | Description | Days Open + -----+----------+-------------------------------------------+----------- + 101 | Critical | Intermittent system crash | 6 + 94 | Cosmetic | Spelling error on Login ('log|n') | 14 + 79 | Minor | System slow when running too many reports | 47 + ''' + integer = Word(nums) + SEP = Suppress('|') + # use SkipTo to simply match everything up until the next SEP + # - ignore quoted strings, so that a '|' character inside a quoted string does not match + # - parse action will call token.strip() for each matched token, i.e., the description body + string_data = SkipTo(SEP, ignore=quoted_string) + string_data.set_parse_action(token_map(str.strip)) + ticket_expr = (integer("issue_num") + SEP + + string_data("sev") + SEP + + string_data("desc") + SEP + + integer("days_open")) + + for tkt in ticket_expr.search_string(report): + print(tkt.dump()) + + prints: + + .. testoutput:: + + ['101', 'Critical', 'Intermittent system crash', '6'] + - days_open: '6' + - desc: 'Intermittent system crash' + - issue_num: '101' + - sev: 'Critical' + ['94', 'Cosmetic', "Spelling error on Login ('log|n')", '14'] + - days_open: '14' + - desc: "Spelling error on Login ('log|n')" + - issue_num: '94' + - sev: 'Cosmetic' + ['79', 'Minor', 'System slow when running too many reports', '47'] + - days_open: '47' + - desc: 'System slow when running too many reports' + - issue_num: '79' + - sev: 'Minor' + """ + + def __init__( + self, + other: Union[ParserElement, str], + include: bool = False, + ignore: typing.Optional[Union[ParserElement, str]] = None, + fail_on: typing.Optional[Union[ParserElement, str]] = None, + *, + failOn: typing.Optional[Union[ParserElement, str]] = None, + ) -> None: + super().__init__(other) + failOn = failOn or fail_on + self.ignoreExpr = ignore + self._may_return_empty = True + self.mayIndexError = False + self.includeMatch = include + self.saveAsList = False + if isinstance(failOn, str_type): + self.failOn = self._literalStringClass(failOn) + else: + self.failOn = failOn + self.errmsg = f"No match found for {self.expr}" + self.ignorer = Empty().leave_whitespace() + self._update_ignorer() + + def _update_ignorer(self): + # rebuild internal ignore expr from current ignore exprs and assigned ignoreExpr + self.ignorer.ignoreExprs.clear() + for e in self.expr.ignoreExprs: + self.ignorer.ignore(e) + if self.ignoreExpr: + self.ignorer.ignore(self.ignoreExpr) + + def ignore(self, expr): + super().ignore(expr) + self._update_ignorer() + + def parseImpl(self, instring, loc, do_actions=True): + startloc = loc + instrlen = len(instring) + self_expr_parse = self.expr._parse + self_failOn_canParseNext = ( + self.failOn.canParseNext if self.failOn is not None else None + ) + ignorer_try_parse = self.ignorer.try_parse if self.ignorer.ignoreExprs else None + + tmploc = loc + while tmploc <= instrlen: + if self_failOn_canParseNext is not None: + # break if failOn expression matches + if self_failOn_canParseNext(instring, tmploc): + break + + if ignorer_try_parse is not None: + # advance past ignore expressions + prev_tmploc = tmploc + while 1: + try: + tmploc = ignorer_try_parse(instring, tmploc) + except ParseBaseException: + break + # see if all ignorers matched, but didn't actually ignore anything + if tmploc == prev_tmploc: + break + prev_tmploc = tmploc + + try: + self_expr_parse(instring, tmploc, do_actions=False, callPreParse=False) + except (ParseException, IndexError): + # no match, advance loc in string + tmploc += 1 + else: + # matched skipto expr, done + break + + else: + # ran off the end of the input string without matching skipto expr, fail + raise ParseException(instring, loc, self.errmsg, self) + + # build up return values + loc = tmploc + skiptext = instring[startloc:loc] + skipresult = ParseResults(skiptext) + + if self.includeMatch: + loc, mat = self_expr_parse(instring, loc, do_actions, callPreParse=False) + skipresult += mat + + return loc, skipresult + + +class Forward(ParseElementEnhance): + """ + Forward declaration of an expression to be defined later - + used for recursive grammars, such as algebraic infix notation. + When the expression is known, it is assigned to the ``Forward`` + instance using the ``'<<'`` operator. + + .. Note:: + + Take care when assigning to ``Forward`` not to overlook + precedence of operators. + + Specifically, ``'|'`` has a lower precedence than ``'<<'``, so that:: + + fwd_expr << a | b | c + + will actually be evaluated as:: + + (fwd_expr << a) | b | c + + thereby leaving b and c out as parseable alternatives. + It is recommended that you explicitly group the values + inserted into the :class:`Forward`:: + + fwd_expr << (a | b | c) + + Converting to use the ``'<<='`` operator instead will avoid this problem. + + See :meth:`ParseResults.pprint` for an example of a recursive + parser created using :class:`Forward`. + """ + + def __init__( + self, other: typing.Optional[Union[ParserElement, str]] = None + ) -> None: + self.caller_frame = traceback.extract_stack(limit=2)[0] + super().__init__(other, savelist=False) # type: ignore[arg-type] + self.lshift_line = None + + def __lshift__(self, other) -> Forward: + if hasattr(self, "caller_frame"): + del self.caller_frame + if isinstance(other, str_type): + other = self._literalStringClass(other) + + if not isinstance(other, ParserElement): + return NotImplemented + + self.expr = other + self.streamlined = other.streamlined + self.mayIndexError = self.expr.mayIndexError + self._may_return_empty = self.expr.mayReturnEmpty + self.set_whitespace_chars( + self.expr.whiteChars, copy_defaults=self.expr.copyDefaultWhiteChars + ) + self.skipWhitespace = self.expr.skipWhitespace + self.saveAsList = self.expr.saveAsList + self.ignoreExprs.extend(self.expr.ignoreExprs) + self.lshift_line = traceback.extract_stack(limit=2)[-2] # type: ignore[assignment] + return self + + def __ilshift__(self, other) -> Forward: + if not isinstance(other, ParserElement): + return NotImplemented + + return self << other + + def __or__(self, other) -> ParserElement: + caller_line = traceback.extract_stack(limit=2)[-2] + if ( + __diag__.warn_on_match_first_with_lshift_operator + and caller_line == self.lshift_line + and Diagnostics.warn_on_match_first_with_lshift_operator + not in self.suppress_warnings_ + ): + warnings.warn( + "warn_on_match_first_with_lshift_operator:" + " using '<<' operator with '|' is probably an error, use '<<='", + stacklevel=2, + ) + ret = super().__or__(other) + return ret + + def __del__(self): + # see if we are getting dropped because of '=' reassignment of var instead of '<<=' or '<<' + if ( + self.expr is None + and __diag__.warn_on_assignment_to_Forward + and Diagnostics.warn_on_assignment_to_Forward not in self.suppress_warnings_ + ): + warnings.warn_explicit( + "warn_on_assignment_to_Forward:" + " Forward defined here but no expression attached later using '<<=' or '<<'", + UserWarning, + filename=self.caller_frame.filename, + lineno=self.caller_frame.lineno, + ) + + def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: + if ( + self.expr is None + and __diag__.warn_on_parse_using_empty_Forward + and Diagnostics.warn_on_parse_using_empty_Forward + not in self.suppress_warnings_ + ): + # walk stack until parse_string, scan_string, search_string, or transform_string is found + parse_fns = ( + "parse_string", + "scan_string", + "search_string", + "transform_string", + ) + tb = traceback.extract_stack(limit=200) + for i, frm in enumerate(reversed(tb), start=1): + if frm.name in parse_fns: + stacklevel = i + 1 + break + else: + stacklevel = 2 + warnings.warn( + "warn_on_parse_using_empty_Forward:" + " Forward expression was never assigned a value, will not parse any input", + stacklevel=stacklevel, + ) + if not ParserElement._left_recursion_enabled: + return super().parseImpl(instring, loc, do_actions) + # ## Bounded Recursion algorithm ## + # Recursion only needs to be processed at ``Forward`` elements, since they are + # the only ones that can actually refer to themselves. The general idea is + # to handle recursion stepwise: We start at no recursion, then recurse once, + # recurse twice, ..., until more recursion offers no benefit (we hit the bound). + # + # The "trick" here is that each ``Forward`` gets evaluated in two contexts + # - to *match* a specific recursion level, and + # - to *search* the bounded recursion level + # and the two run concurrently. The *search* must *match* each recursion level + # to find the best possible match. This is handled by a memo table, which + # provides the previous match to the next level match attempt. + # + # See also "Left Recursion in Parsing Expression Grammars", Medeiros et al. + # + # There is a complication since we not only *parse* but also *transform* via + # actions: We do not want to run the actions too often while expanding. Thus, + # we expand using `do_actions=False` and only run `do_actions=True` if the next + # recursion level is acceptable. + with ParserElement.recursion_lock: + memo = ParserElement.recursion_memos + try: + # we are parsing at a specific recursion expansion - use it as-is + prev_loc, prev_result = memo[loc, self, do_actions] + if isinstance(prev_result, Exception): + raise prev_result + return prev_loc, prev_result.copy() + except KeyError: + act_key = (loc, self, True) + peek_key = (loc, self, False) + # we are searching for the best recursion expansion - keep on improving + # both `do_actions` cases must be tracked separately here! + prev_loc, prev_peek = memo[peek_key] = ( + loc - 1, + ParseException( + instring, loc, "Forward recursion without base case", self + ), + ) + if do_actions: + memo[act_key] = memo[peek_key] + while True: + try: + new_loc, new_peek = super().parseImpl(instring, loc, False) + except ParseException: + # we failed before getting any match - do not hide the error + if isinstance(prev_peek, Exception): + raise + new_loc, new_peek = prev_loc, prev_peek + # the match did not get better: we are done + if new_loc <= prev_loc: + if do_actions: + # replace the match for do_actions=False as well, + # in case the action did backtrack + prev_loc, prev_result = memo[peek_key] = memo[act_key] + del memo[peek_key], memo[act_key] + return prev_loc, copy.copy(prev_result) + del memo[peek_key] + return prev_loc, copy.copy(prev_peek) + # the match did get better: see if we can improve further + if do_actions: + try: + memo[act_key] = super().parseImpl(instring, loc, True) + except ParseException as e: + memo[peek_key] = memo[act_key] = (new_loc, e) + raise + prev_loc, prev_peek = memo[peek_key] = new_loc, new_peek + + def leave_whitespace(self, recursive: bool = True) -> ParserElement: + self.skipWhitespace = False + return self + + def ignore_whitespace(self, recursive: bool = True) -> ParserElement: + self.skipWhitespace = True + return self + + def streamline(self) -> ParserElement: + if not self.streamlined: + self.streamlined = True + if self.expr is not None: + self.expr.streamline() + return self + + def validate(self, validateTrace=None) -> None: + warnings.warn( + "ParserElement.validate() is deprecated, and should not be used to check for left recursion", + DeprecationWarning, + stacklevel=2, + ) + if validateTrace is None: + validateTrace = [] + + if self not in validateTrace: + tmp = validateTrace[:] + [self] + if self.expr is not None: + self.expr.validate(tmp) + self._checkRecursion([]) + + def _generateDefaultName(self) -> str: + # Avoid infinite recursion by setting a temporary _defaultName + save_default_name = self._defaultName + self._defaultName = ": ..." + + # Use the string representation of main expression. + try: + if self.expr is not None: + ret_string = str(self.expr)[:1000] + else: + ret_string = "None" + except Exception: + ret_string = "..." + + self._defaultName = save_default_name + return f"{type(self).__name__}: {ret_string}" + + def copy(self) -> ParserElement: + if self.expr is not None: + return super().copy() + else: + ret = Forward() + ret <<= self + return ret + + def _setResultsName(self, name, list_all_matches=False) -> ParserElement: + # fmt: off + if ( + __diag__.warn_name_set_on_empty_Forward + and Diagnostics.warn_name_set_on_empty_Forward not in self.suppress_warnings_ + and self.expr is None + ): + warning = ( + "warn_name_set_on_empty_Forward:" + f" setting results name {name!r} on {type(self).__name__} expression" + " that has no contained expression" + ) + warnings.warn(warning, stacklevel=3) + # fmt: on + + return super()._setResultsName(name, list_all_matches) + + # Compatibility synonyms + # fmt: off + leaveWhitespace = replaced_by_pep8("leaveWhitespace", leave_whitespace) + ignoreWhitespace = replaced_by_pep8("ignoreWhitespace", ignore_whitespace) + # fmt: on + + +class TokenConverter(ParseElementEnhance): + """ + Abstract subclass of :class:`ParseElementEnhance`, for converting parsed results. + """ + + def __init__(self, expr: Union[ParserElement, str], savelist=False) -> None: + super().__init__(expr) # , savelist) + self.saveAsList = False + + +class Combine(TokenConverter): + """Converter to concatenate all matching tokens to a single string. + By default, the matching patterns must also be contiguous in the + input string; this can be disabled by specifying + ``'adjacent=False'`` in the constructor. + + Example: + + .. doctest:: + + >>> real = Word(nums) + '.' + Word(nums) + >>> print(real.parse_string('3.1416')) + ['3', '.', '1416'] + + >>> # will also erroneously match the following + >>> print(real.parse_string('3. 1416')) + ['3', '.', '1416'] + + >>> real = Combine(Word(nums) + '.' + Word(nums)) + >>> print(real.parse_string('3.1416')) + ['3.1416'] + + >>> # no match when there are internal spaces + >>> print(real.parse_string('3. 1416')) + Traceback (most recent call last): + ParseException: Expected W:(0123...) + """ + + def __init__( + self, + expr: ParserElement, + join_string: str = "", + adjacent: bool = True, + *, + joinString: typing.Optional[str] = None, + ) -> None: + super().__init__(expr) + joinString = joinString if joinString is not None else join_string + # suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself + if adjacent: + self.leave_whitespace() + self.adjacent = adjacent + self.skipWhitespace = True + self.joinString = joinString + self.callPreparse = True + + def ignore(self, other) -> ParserElement: + if self.adjacent: + ParserElement.ignore(self, other) + else: + super().ignore(other) + return self + + def postParse(self, instring, loc, tokenlist): + retToks = tokenlist.copy() + del retToks[:] + retToks += ParseResults( + ["".join(tokenlist._asStringList(self.joinString))], modal=self.modalResults + ) + + if self.resultsName and retToks.haskeys(): + return [retToks] + else: + return retToks + + +class Group(TokenConverter): + """Converter to return the matched tokens as a list - useful for + returning tokens of :class:`ZeroOrMore` and :class:`OneOrMore` expressions. + + The optional ``aslist`` argument when set to True will return the + parsed tokens as a Python list instead of a pyparsing ParseResults. + + Example: + + .. doctest:: + + >>> ident = Word(alphas) + >>> num = Word(nums) + >>> term = ident | num + >>> func = ident + Opt(DelimitedList(term)) + >>> print(func.parse_string("fn a, b, 100")) + ['fn', 'a', 'b', '100'] + + >>> func = ident + Group(Opt(DelimitedList(term))) + >>> print(func.parse_string("fn a, b, 100")) + ['fn', ['a', 'b', '100']] + """ + + def __init__(self, expr: ParserElement, aslist: bool = False) -> None: + super().__init__(expr) + self.saveAsList = True + self._asPythonList = aslist + + def postParse(self, instring, loc, tokenlist): + if self._asPythonList: + return ParseResults.List( + tokenlist.asList() + if isinstance(tokenlist, ParseResults) + else list(tokenlist) + ) + + return [tokenlist] + + +class Dict(TokenConverter): + """Converter to return a repetitive expression as a list, but also + as a dictionary. Each element can also be referenced using the first + token in the expression as its key. Useful for tabular report + scraping when the first column can be used as a item key. + + The optional ``asdict`` argument when set to True will return the + parsed tokens as a Python dict instead of a pyparsing ParseResults. + + Example: + + .. doctest:: + + >>> data_word = Word(alphas) + >>> label = data_word + FollowedBy(':') + + >>> attr_expr = ( + ... label + Suppress(':') + ... + OneOrMore(data_word, stop_on=label) + ... .set_parse_action(' '.join) + ... ) + + >>> text = "shape: SQUARE posn: upper left color: light blue texture: burlap" + + >>> # print attributes as plain groups + >>> print(attr_expr[1, ...].parse_string(text).dump()) + ['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap'] + + # instead of OneOrMore(expr), parse using Dict(Group(expr)[1, ...]) + # Dict will auto-assign names. + >>> result = Dict(Group(attr_expr)[1, ...]).parse_string(text) + >>> print(result.dump()) + [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] + - color: 'light blue' + - posn: 'upper left' + - shape: 'SQUARE' + - texture: 'burlap' + [0]: + ['shape', 'SQUARE'] + [1]: + ['posn', 'upper left'] + [2]: + ['color', 'light blue'] + [3]: + ['texture', 'burlap'] + + # access named fields as dict entries, or output as dict + >>> print(result['shape']) + SQUARE + >>> print(result.as_dict()) + {'shape': 'SQUARE', 'posn': 'upper left', 'color': 'light blue', 'texture': 'burlap'} + + See more examples at :class:`ParseResults` of accessing fields by results name. + """ + + def __init__(self, expr: ParserElement, asdict: bool = False) -> None: + super().__init__(expr) + self.saveAsList = True + self._asPythonDict = asdict + + def postParse(self, instring, loc, tokenlist): + for i, tok in enumerate(tokenlist): + if len(tok) == 0: + continue + + ikey = tok[0] + if isinstance(ikey, int): + ikey = str(ikey).strip() + + if len(tok) == 1: + tokenlist[ikey] = _ParseResultsWithOffset("", i) + + elif len(tok) == 2 and not isinstance(tok[1], ParseResults): + tokenlist[ikey] = _ParseResultsWithOffset(tok[1], i) + + else: + try: + dictvalue = tok.copy() # ParseResults(i) + except Exception: + exc = TypeError( + "could not extract dict values from parsed results" + " - Dict expression must contain Grouped expressions" + ) + raise exc from None + + del dictvalue[0] + + if len(dictvalue) != 1 or ( + isinstance(dictvalue, ParseResults) and dictvalue.haskeys() + ): + tokenlist[ikey] = _ParseResultsWithOffset(dictvalue, i) + else: + tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0], i) + + if self._asPythonDict: + return [tokenlist.as_dict()] if self.resultsName else tokenlist.as_dict() + + return [tokenlist] if self.resultsName else tokenlist + + +class Suppress(TokenConverter): + """Converter for ignoring the results of a parsed expression. + + Example: + + .. doctest:: + + >>> source = "a, b, c,d" + >>> wd = Word(alphas) + >>> wd_list1 = wd + (',' + wd)[...] + >>> print(wd_list1.parse_string(source)) + ['a', ',', 'b', ',', 'c', ',', 'd'] + + # often, delimiters that are useful during parsing are just in the + # way afterward - use Suppress to keep them out of the parsed output + >>> wd_list2 = wd + (Suppress(',') + wd)[...] + >>> print(wd_list2.parse_string(source)) + ['a', 'b', 'c', 'd'] + + # Skipped text (using '...') can be suppressed as well + >>> source = "lead in START relevant text END trailing text" + >>> start_marker = Keyword("START") + >>> end_marker = Keyword("END") + >>> find_body = Suppress(...) + start_marker + ... + end_marker + >>> print(find_body.parse_string(source)) + ['START', 'relevant text ', 'END'] + + (See also :class:`DelimitedList`.) + """ + + def __init__(self, expr: Union[ParserElement, str], savelist: bool = False) -> None: + if expr is ...: + expr = _PendingSkip(NoMatch()) + super().__init__(expr) + + def __add__(self, other) -> ParserElement: + if isinstance(self.expr, _PendingSkip): + return Suppress(SkipTo(other)) + other + + return super().__add__(other) + + def __sub__(self, other) -> ParserElement: + if isinstance(self.expr, _PendingSkip): + return Suppress(SkipTo(other)) - other + + return super().__sub__(other) + + def postParse(self, instring, loc, tokenlist): + return [] + + def suppress(self) -> ParserElement: + return self + + +# XXX: Example needs to be re-done for updated output +def trace_parse_action(f: ParseAction) -> ParseAction: + """Decorator for debugging parse actions. + + When the parse action is called, this decorator will print + ``">> entering method-name(line:, , )"``. + When the parse action completes, the decorator will print + ``"<<"`` followed by the returned value, or any exception that the parse action raised. + + Example: + + .. testsetup:: stderr + + import sys + sys.stderr = sys.stdout + + .. testcleanup:: stderr + + sys.stderr = sys.__stderr__ + + .. testcode:: stderr + + wd = Word(alphas) + + @trace_parse_action + def remove_duplicate_chars(tokens): + return ''.join(sorted(set(''.join(tokens)))) + + wds = wd[1, ...].set_parse_action(remove_duplicate_chars) + print(wds.parse_string("slkdjs sld sldd sdlf sdljf")) + + prints: + + .. testoutput:: stderr + :options: +NORMALIZE_WHITESPACE + + >>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', + 0, ParseResults(['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {})) + < 3: + thisFunc = f"{type(paArgs[0]).__name__}.{thisFunc}" + sys.stderr.write(f">>entering {thisFunc}(line: {line(l, s)!r}, {l}, {t!r})\n") + try: + ret = f(*paArgs) + except Exception as exc: + sys.stderr.write( + f"< str: + r"""Helper to easily define string ranges for use in :class:`Word` + construction. Borrows syntax from regexp ``'[]'`` string range + definitions:: + + srange("[0-9]") -> "0123456789" + srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz" + srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_" + + The input string must be enclosed in []'s, and the returned string + is the expanded character set joined into a single string. The + values enclosed in the []'s may be: + + - a single character + - an escaped character with a leading backslash (such as ``\-`` + or ``\]``) + - an escaped hex character with a leading ``'\x'`` + (``\x21``, which is a ``'!'`` character) (``\0x##`` + is also supported for backwards compatibility) + - an escaped octal character with a leading ``'\0'`` + (``\041``, which is a ``'!'`` character) + - a range of any of the above, separated by a dash (``'a-z'``, + etc.) + - any combination of the above (``'aeiouy'``, + ``'a-zA-Z0-9_$'``, etc.) + """ + + def _expanded(p): + if isinstance(p, ParseResults): + yield from (chr(c) for c in range(ord(p[0]), ord(p[1]) + 1)) + else: + yield p + + try: + return "".join( + [c for part in _reBracketExpr.parse_string(s).body for c in _expanded(part)] + ) + except Exception as e: + return "" + + +def token_map(func, *args) -> ParseAction: + """Helper to define a parse action by mapping a function to all + elements of a :class:`ParseResults` list. If any additional args are passed, + they are forwarded to the given function as additional arguments + after the token, as in + ``hex_integer = Word(hexnums).set_parse_action(token_map(int, 16))``, + which will convert the parsed data to an integer using base 16. + + Example (compare the last to example in :class:`ParserElement.transform_string`:: + + hex_ints = Word(hexnums)[1, ...].set_parse_action(token_map(int, 16)) + hex_ints.run_tests(''' + 00 11 22 aa FF 0a 0d 1a + ''') + + upperword = Word(alphas).set_parse_action(token_map(str.upper)) + upperword[1, ...].run_tests(''' + my kingdom for a horse + ''') + + wd = Word(alphas).set_parse_action(token_map(str.title)) + wd[1, ...].set_parse_action(' '.join).run_tests(''' + now is the winter of our discontent made glorious summer by this sun of york + ''') + + prints:: + + 00 11 22 aa FF 0a 0d 1a + [0, 17, 34, 170, 255, 10, 13, 26] + + my kingdom for a horse + ['MY', 'KINGDOM', 'FOR', 'A', 'HORSE'] + + now is the winter of our discontent made glorious summer by this sun of york + ['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York'] + """ + + def pa(s, l, t): + return [func(tokn, *args) for tokn in t] + + func_name = getattr(func, "__name__", getattr(func, "__class__").__name__) + pa.__name__ = func_name + + return pa + + +def autoname_elements() -> None: + """ + Utility to simplify mass-naming of parser elements, for + generating railroad diagram with named subdiagrams. + """ + + # guard against _getframe not being implemented in the current Python + getframe_fn = getattr(sys, "_getframe", lambda _: None) + calling_frame = getframe_fn(1) + if calling_frame is None: + return + + # find all locals in the calling frame that are ParserElements + calling_frame = typing.cast(types.FrameType, calling_frame) + for name, var in calling_frame.f_locals.items(): + # if no custom name defined, set the name to the var name + if isinstance(var, ParserElement) and not var.customName: + var.set_name(name) + + +dbl_quoted_string = Combine( + Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"' +).set_name("string enclosed in double quotes") + +sgl_quoted_string = Combine( + Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*") + "'" +).set_name("string enclosed in single quotes") + +quoted_string = Combine( + (Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"').set_name( + "double quoted string" + ) + | (Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*") + "'").set_name( + "single quoted string" + ) +).set_name("quoted string using single or double quotes") + +# XXX: Is there some way to make this show up in API docs? +# .. versionadded:: 3.1.0 +python_quoted_string = Combine( + (Regex(r'"""(?:[^"\\]|""(?!")|"(?!"")|\\.)*', flags=re.MULTILINE) + '"""').set_name( + "multiline double quoted string" + ) + ^ ( + Regex(r"'''(?:[^'\\]|''(?!')|'(?!'')|\\.)*", flags=re.MULTILINE) + "'''" + ).set_name("multiline single quoted string") + ^ (Regex(r'"(?:[^"\n\r\\]|(?:\\")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"').set_name( + "double quoted string" + ) + ^ (Regex(r"'(?:[^'\n\r\\]|(?:\\')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*") + "'").set_name( + "single quoted string" + ) +).set_name("Python quoted string") + +unicode_string = Combine("u" + quoted_string.copy()).set_name("unicode string literal") + + +alphas8bit = srange(r"[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]") +punc8bit = srange(r"[\0xa1-\0xbf\0xd7\0xf7]") + +# build list of built-in expressions, for future reference if a global default value +# gets updated +_builtin_exprs: list[ParserElement] = [ + v for v in vars().values() if isinstance(v, ParserElement) +] + +# Compatibility synonyms +# fmt: off +sglQuotedString = sgl_quoted_string +dblQuotedString = dbl_quoted_string +quotedString = quoted_string +unicodeString = unicode_string +lineStart = line_start +lineEnd = line_end +stringStart = string_start +stringEnd = string_end +nullDebugAction = replaced_by_pep8("nullDebugAction", null_debug_action) +traceParseAction = replaced_by_pep8("traceParseAction", trace_parse_action) +conditionAsParseAction = replaced_by_pep8("conditionAsParseAction", condition_as_parse_action) +tokenMap = replaced_by_pep8("tokenMap", token_map) +# fmt: on diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/diagram/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/diagram/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..af1aa47bbca1d7ece35a05e95246de4fe92e04f0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/diagram/__init__.py @@ -0,0 +1,768 @@ +# mypy: ignore-errors +from __future__ import annotations + +import itertools +import railroad +import pyparsing +import dataclasses +import typing +from typing import ( + Generic, + TypeVar, + Callable, + Iterable, +) +from jinja2 import Template +from io import StringIO +import inspect +import re + + +jinja2_template_source = """\ +{% if not embed %} + + + +{% endif %} + {% if not head %} + + {% else %} + {{ head | safe }} + {% endif %} +{% if not embed %} + + +{% endif %} + +{{ body | safe }} +{% for diagram in diagrams %} +
+

{{ diagram.title }}

+
{{ diagram.text }}
+
+ {{ diagram.svg }} +
+
+{% endfor %} +{% if not embed %} + + +{% endif %} +""" + +template = Template(jinja2_template_source) + + +_bookmark_lookup = {} +_bookmark_ids = itertools.count(start=1) + +def _make_bookmark(s: str) -> str: + """ + Converts a string into a valid HTML bookmark (ID or anchor name). + """ + if s in _bookmark_lookup: + return _bookmark_lookup[s] + + # Replace invalid characters with hyphens and ensure only valid characters + bookmark = re.sub(r'[^a-zA-Z0-9-]+', '-', s) + + # Ensure it starts with a letter by adding 'z' if necessary + if not bookmark[:1].isalpha(): + bookmark = f"z{bookmark}" + + # Convert to lowercase and strip hyphens + bookmark = bookmark.lower().strip('-') + + _bookmark_lookup[s] = bookmark = f"{bookmark}-{next(_bookmark_ids):04d}" + + return bookmark + + +def _collapse_verbose_regex(regex_str: str) -> str: + if "\n" not in regex_str: + return regex_str + collapsed = pyparsing.Regex(r"#.*$").suppress().transform_string(regex_str) + collapsed = re.sub(r"\s*\n\s*", "", collapsed) + return collapsed + + +@dataclasses.dataclass +class NamedDiagram: + """ + A simple structure for associating a name with a railroad diagram + """ + + name: str + index: int + diagram: railroad.DiagramItem = None + + @property + def bookmark(self): + bookmark = _make_bookmark(self.name) + return bookmark + + +T = TypeVar("T") + + +class EachItem(railroad.Group): + """ + Custom railroad item to compose a: + + - :class:`railroad.Group` containing a + + - :class:`railroad.OneOrMore` containing a + + - :class:`railroad.Choice` of the elements in the + :class:`railroad.Each` + + with the group label indicating that all must be matched + """ + + all_label = "[ALL]" + + def __init__(self, *items) -> None: + choice_item = railroad.Choice(len(items) - 1, *items) + one_or_more_item = railroad.OneOrMore(item=choice_item) + super().__init__(one_or_more_item, label=self.all_label) + + +class AnnotatedItem(railroad.Group): + """ + Simple subclass of Group that creates an annotation label + """ + + def __init__(self, label: str, item) -> None: + super().__init__(item=item, label=f"[{label}]" if label else "") + + +class EditablePartial(Generic[T]): + """ + Acts like a functools.partial, but can be edited. In other words, it represents a type that hasn't yet been + constructed. + """ + + # We need this here because the railroad constructors actually transform the data, so can't be called until the + # entire tree is assembled + + def __init__(self, func: Callable[..., T], args: list, kwargs: dict) -> None: + self.func = func + self.args = args + self.kwargs = kwargs + + @classmethod + def from_call(cls, func: Callable[..., T], *args, **kwargs) -> EditablePartial[T]: + """ + If you call this function in the same way that you would call the constructor, + it will store the arguments as you expect. For example + ``EditablePartial.from_call(Fraction, 1, 3)() == Fraction(1, 3)`` + """ + return EditablePartial(func=func, args=list(args), kwargs=kwargs) + + @property + def name(self): + return self.kwargs["name"] + + def __call__(self) -> T: + """ + Evaluate the partial and return the result + """ + args = self.args.copy() + kwargs = self.kwargs.copy() + + # This is a helpful hack to allow you to specify varargs parameters (e.g. *args) as keyword args (e.g. + # args=['list', 'of', 'things']) + arg_spec = inspect.getfullargspec(self.func) + if arg_spec.varargs in self.kwargs: + args += kwargs.pop(arg_spec.varargs) + + return self.func(*args, **kwargs) + + +def railroad_to_html(diagrams: list[NamedDiagram], embed=False, **kwargs) -> str: + """ + Given a list of :class:`NamedDiagram`, produce a single HTML string + that visualises those diagrams. + + :params kwargs: kwargs to be passed in to the template + """ + data = [] + for diagram in diagrams: + if diagram.diagram is None: + continue + io = StringIO() + try: + css = kwargs.get("css") + diagram.diagram.writeStandalone(io.write, css=css) + except AttributeError: + diagram.diagram.writeSvg(io.write) + title = diagram.name + if diagram.index == 0: + title += " (root)" + data.append( + { + "title": title, "text": "", "svg": io.getvalue(), "bookmark": diagram.bookmark + } + ) + + return template.render(diagrams=data, embed=embed, **kwargs) + + +def resolve_partial(partial: EditablePartial[T]) -> T: + """ + Recursively resolves a collection of Partials into whatever type they are + """ + if isinstance(partial, EditablePartial): + partial.args = resolve_partial(partial.args) + partial.kwargs = resolve_partial(partial.kwargs) + return partial() + elif isinstance(partial, list): + return [resolve_partial(x) for x in partial] + elif isinstance(partial, dict): + return {key: resolve_partial(x) for key, x in partial.items()} + else: + return partial + + +def to_railroad( + element: pyparsing.ParserElement, + diagram_kwargs: typing.Optional[dict] = None, + vertical: int = 3, + show_results_names: bool = False, + show_groups: bool = False, + show_hidden: bool = False, +) -> list[NamedDiagram]: + """ + Convert a pyparsing element tree into a list of diagrams. This is the recommended entrypoint to diagram + creation if you want to access the Railroad tree before it is converted to HTML + + :param element: base element of the parser being diagrammed + + :param diagram_kwargs: kwargs to pass to the :meth:`Diagram` constructor + + :param vertical: (optional) int - limit at which number of alternatives + should be shown vertically instead of horizontally + + :param show_results_names: bool to indicate whether results name + annotations should be included in the diagram + + :param show_groups: bool to indicate whether groups should be highlighted + with an unlabeled surrounding box + + :param show_hidden: bool to indicate whether internal elements that are + typically hidden should be shown + """ + # Convert the whole tree underneath the root + lookup = ConverterState(diagram_kwargs=diagram_kwargs or {}) + _to_diagram_element( + element, + lookup=lookup, + parent=None, + vertical=vertical, + show_results_names=show_results_names, + show_groups=show_groups, + show_hidden=show_hidden, + ) + + root_id = id(element) + # Convert the root if it hasn't been already + if root_id in lookup: + if not element.customName: + lookup[root_id].name = "" + lookup[root_id].mark_for_extraction(root_id, lookup, force=True) + + # Now that we're finished, we can convert from intermediate structures into Railroad elements + diags = list(lookup.diagrams.values()) + if len(diags) > 1: + # collapse out duplicate diags with the same name + seen = set() + deduped_diags = [] + for d in diags: + # don't extract SkipTo elements, they are uninformative as subdiagrams + if d.name == "...": + continue + if d.name is not None and d.name not in seen: + seen.add(d.name) + deduped_diags.append(d) + resolved = [resolve_partial(partial) for partial in deduped_diags] + else: + # special case - if just one diagram, always display it, even if + # it has no name + resolved = [resolve_partial(partial) for partial in diags] + return sorted(resolved, key=lambda diag: diag.index) + + +def _should_vertical( + specification: int, exprs: Iterable[pyparsing.ParserElement] +) -> bool: + """ + Returns true if we should return a vertical list of elements + """ + if specification is None: + return False + else: + return len(_visible_exprs(exprs)) >= specification + + +@dataclasses.dataclass +class ElementState: + """ + State recorded for an individual pyparsing Element + """ + + #: The pyparsing element that this represents + element: pyparsing.ParserElement + #: The output Railroad element in an unconverted state + converted: EditablePartial + #: The parent Railroad element, which we store so that we can extract this if it's duplicated + parent: EditablePartial + #: The order in which we found this element, used for sorting diagrams if this is extracted into a diagram + number: int + #: The name of the element + name: str = None + #: The index of this inside its parent + parent_index: typing.Optional[int] = None + #: If true, we should extract this out into a subdiagram + extract: bool = False + #: If true, all of this element's children have been filled out + complete: bool = False + + def mark_for_extraction( + self, el_id: int, state: ConverterState, name: str = None, force: bool = False + ): + """ + Called when this instance has been seen twice, and thus should eventually be extracted into a sub-diagram + :param el_id: id of the element + :param state: element/diagram state tracker + :param name: name to use for this element's text + :param force: If true, force extraction now, regardless of the state of this. Only useful for extracting the + root element when we know we're finished + """ + self.extract = True + + # Set the name + if not self.name: + if name: + # Allow forcing a custom name + self.name = name + elif self.element.customName: + self.name = self.element.customName + else: + self.name = "" + + # Just because this is marked for extraction doesn't mean we can do it yet. We may have to wait for children + # to be added + # Also, if this is just a string literal etc, don't bother extracting it + if force or (self.complete and _worth_extracting(self.element)): + state.extract_into_diagram(el_id) + + +class ConverterState: + """ + Stores some state that persists between recursions into the element tree + """ + + def __init__(self, diagram_kwargs: typing.Optional[dict] = None) -> None: + #: A dictionary mapping ParserElements to state relating to them + self._element_diagram_states: dict[int, ElementState] = {} + #: A dictionary mapping ParserElement IDs to subdiagrams generated from them + self.diagrams: dict[int, EditablePartial[NamedDiagram]] = {} + #: The index of the next unnamed element + self.unnamed_index: int = 1 + #: The index of the next element. This is used for sorting + self.index: int = 0 + #: Shared kwargs that are used to customize the construction of diagrams + self.diagram_kwargs: dict = diagram_kwargs or {} + self.extracted_diagram_names: set[str] = set() + + def __setitem__(self, key: int, value: ElementState): + self._element_diagram_states[key] = value + + def __getitem__(self, key: int) -> ElementState: + return self._element_diagram_states[key] + + def __delitem__(self, key: int): + del self._element_diagram_states[key] + + def __contains__(self, key: int): + return key in self._element_diagram_states + + def get(self, key, default=None): + try: + return self[key] + except KeyError: + return default + + def generate_unnamed(self) -> int: + """ + Generate a number used in the name of an otherwise unnamed diagram + """ + self.unnamed_index += 1 + return self.unnamed_index + + def generate_index(self) -> int: + """ + Generate a number used to index a diagram + """ + self.index += 1 + return self.index + + def extract_into_diagram(self, el_id: int): + """ + Used when we encounter the same token twice in the same tree. When this + happens, we replace all instances of that token with a terminal, and + create a new subdiagram for the token + """ + position = self[el_id] + + # Replace the original definition of this element with a regular block + if position.parent: + href = f"#{_make_bookmark(position.name)}" + ret = EditablePartial.from_call(railroad.NonTerminal, text=position.name, href=href) + if "item" in position.parent.kwargs: + position.parent.kwargs["item"] = ret + elif "items" in position.parent.kwargs: + position.parent.kwargs["items"][position.parent_index] = ret + + # If the element we're extracting is a group, skip to its content but keep the title + if position.converted.func == railroad.Group: + content = position.converted.kwargs["item"] + else: + content = position.converted + + self.diagrams[el_id] = EditablePartial.from_call( + NamedDiagram, + name=position.name, + diagram=EditablePartial.from_call( + railroad.Diagram, content, **self.diagram_kwargs + ), + index=position.number, + ) + + del self[el_id] + + +def _worth_extracting(element: pyparsing.ParserElement) -> bool: + """ + Returns true if this element is worth having its own sub-diagram. Simply, if any of its children + themselves have children, then its complex enough to extract + """ + children = element.recurse() + return any(child.recurse() for child in children) + + +def _apply_diagram_item_enhancements(fn): + """ + decorator to ensure enhancements to a diagram item (such as results name annotations) + get applied on return from _to_diagram_element (we do this since there are several + returns in _to_diagram_element) + """ + + def _inner( + element: pyparsing.ParserElement, + parent: typing.Optional[EditablePartial], + lookup: ConverterState = None, + vertical: int = None, + index: int = 0, + name_hint: str = None, + show_results_names: bool = False, + show_groups: bool = False, + show_hidden: bool = False, + ) -> typing.Optional[EditablePartial]: + ret = fn( + element, + parent, + lookup, + vertical, + index, + name_hint, + show_results_names, + show_groups, + show_hidden, + ) + + # apply annotation for results name, if present + if show_results_names and ret is not None: + element_results_name = element.resultsName + if element_results_name: + # add "*" to indicate if this is a "list all results" name + modal_tag = "" if element.modalResults else "*" + ret = EditablePartial.from_call( + railroad.Group, + item=ret, + label=f"{repr(element_results_name)}{modal_tag}", + ) + + return ret + + return _inner + + +def _visible_exprs(exprs: Iterable[pyparsing.ParserElement]): + non_diagramming_exprs = ( + pyparsing.ParseElementEnhance, + pyparsing.PositionToken, + pyparsing.And._ErrorStop, + ) + return [ + e + for e in exprs + if not isinstance(e, non_diagramming_exprs) + ] + + +@_apply_diagram_item_enhancements +def _to_diagram_element( + element: pyparsing.ParserElement, + parent: typing.Optional[EditablePartial], + lookup: ConverterState = None, + vertical: int = None, + index: int = 0, + name_hint: str = None, + show_results_names: bool = False, + show_groups: bool = False, + show_hidden: bool = False, +) -> typing.Optional[EditablePartial]: + """ + Recursively converts a PyParsing Element to a railroad Element + :param lookup: The shared converter state that keeps track of useful things + :param index: The index of this element within the parent + :param parent: The parent of this element in the output tree + :param vertical: Controls at what point we make a list of elements vertical. If this is an integer (the default), + it sets the threshold of the number of items before we go vertical. If True, always go vertical, if False, never + do so + :param name_hint: If provided, this will override the generated name + :param show_results_names: bool flag indicating whether to add annotations for results names + :param show_groups: bool flag indicating whether to show groups using bounding box + :param show_hidden: bool flag indicating whether to show elements that are typically hidden + :returns: The converted version of the input element, but as a Partial that hasn't yet been constructed + """ + exprs = element.recurse() + name = name_hint or element.customName or type(element).__name__ + + # Python's id() is used to provide a unique identifier for elements + el_id = id(element) + + element_results_name = element.resultsName + + # Here we basically bypass processing certain wrapper elements if they contribute nothing to the diagram + if not element.customName: + if isinstance( + element, + ( + # pyparsing.TokenConverter, + pyparsing.Forward, + pyparsing.Located, + ), + ): + # However, if this element has a useful custom name, and its child does not, we can pass it on to the child + if exprs: + if not exprs[0].customName: + propagated_name = name + else: + propagated_name = None + + return _to_diagram_element( + element.expr, + parent=parent, + lookup=lookup, + vertical=vertical, + index=index, + name_hint=propagated_name, + show_results_names=show_results_names, + show_groups=show_groups, + show_hidden=show_hidden, + ) + + # If the element isn't worth extracting, we always treat it as the first time we say it + if _worth_extracting(element): + looked_up = lookup.get(el_id) + if looked_up and looked_up.name is not None: + # If we've seen this element exactly once before, we are only just now finding out that it's a duplicate, + # so we have to extract it into a new diagram. + looked_up.mark_for_extraction(el_id, lookup, name=name_hint) + href = f"#{_make_bookmark(looked_up.name)}" + ret = EditablePartial.from_call(railroad.NonTerminal, text=looked_up.name, href=href) + return ret + + elif el_id in lookup.diagrams: + # If we have seen the element at least twice before, and have already extracted it into a subdiagram, we + # just put in a marker element that refers to the sub-diagram + text = lookup.diagrams[el_id].kwargs["name"] + ret = EditablePartial.from_call( + railroad.NonTerminal, text=text, href=f"#{_make_bookmark(text)}" + ) + return ret + + # Recursively convert child elements + # Here we find the most relevant Railroad element for matching pyparsing Element + # We use ``items=[]`` here to hold the place for where the child elements will go once created + + # see if this element is normally hidden, and whether hidden elements are desired + # if not, just return None + if not element.show_in_diagram and not show_hidden: + return None + + if isinstance(element, pyparsing.And): + # detect And's created with ``expr*N`` notation - for these use a OneOrMore with a repeat + # (all will have the same name, and resultsName) + if not exprs: + return None + if len(set((e.name, e.resultsName) for e in exprs)) == 1 and len(exprs) > 2: + ret = EditablePartial.from_call( + railroad.OneOrMore, item="", repeat=str(len(exprs)) + ) + elif _should_vertical(vertical, exprs): + ret = EditablePartial.from_call(railroad.Stack, items=[]) + else: + ret = EditablePartial.from_call(railroad.Sequence, items=[]) + elif isinstance(element, (pyparsing.Or, pyparsing.MatchFirst)): + if not exprs: + return None + if _should_vertical(vertical, exprs): + ret = EditablePartial.from_call(railroad.Choice, 0, items=[]) + else: + ret = EditablePartial.from_call(railroad.HorizontalChoice, items=[]) + elif isinstance(element, pyparsing.Each): + if not exprs: + return None + ret = EditablePartial.from_call(EachItem, items=[]) + elif isinstance(element, pyparsing.NotAny): + ret = EditablePartial.from_call(AnnotatedItem, label="NOT", item="") + elif isinstance(element, pyparsing.FollowedBy): + ret = EditablePartial.from_call(AnnotatedItem, label="LOOKAHEAD", item="") + elif isinstance(element, pyparsing.PrecededBy): + ret = EditablePartial.from_call(AnnotatedItem, label="LOOKBEHIND", item="") + elif isinstance(element, pyparsing.Group): + if show_groups: + ret = EditablePartial.from_call(AnnotatedItem, label="", item="") + else: + ret = EditablePartial.from_call( + railroad.Group, item=None, label=element_results_name + ) + elif isinstance(element, pyparsing.TokenConverter): + label = type(element).__name__.lower() + if label == "tokenconverter": + ret = EditablePartial.from_call(railroad.Sequence, items=[]) + else: + ret = EditablePartial.from_call(AnnotatedItem, label=label, item="") + elif isinstance(element, pyparsing.Opt): + ret = EditablePartial.from_call(railroad.Optional, item="") + elif isinstance(element, pyparsing.OneOrMore): + if element.not_ender is not None: + args = [ + parent, + lookup, + vertical, + index, + name_hint, + show_results_names, + show_groups, + show_hidden, + ] + return _to_diagram_element( + (~element.not_ender.expr + element.expr)[1, ...].set_name(element.name), + *args, + ) + ret = EditablePartial.from_call(railroad.OneOrMore, item=None) + elif isinstance(element, pyparsing.ZeroOrMore): + if element.not_ender is not None: + args = [ + parent, + lookup, + vertical, + index, + name_hint, + show_results_names, + show_groups, + show_hidden, + ] + return _to_diagram_element( + (~element.not_ender.expr + element.expr)[...].set_name(element.name), + *args, + ) + ret = EditablePartial.from_call(railroad.ZeroOrMore, item="") + elif isinstance(element, pyparsing.Empty) and not element.customName: + # Skip unnamed "Empty" elements + ret = None + elif isinstance(element, pyparsing.ParseElementEnhance): + ret = EditablePartial.from_call(railroad.Sequence, items=[]) + elif len(exprs) > 0 and not element_results_name: + ret = EditablePartial.from_call(railroad.Group, item="", label=name) + elif isinstance(element, pyparsing.Regex): + collapsed_patt = _collapse_verbose_regex(element.pattern) + ret = EditablePartial.from_call(railroad.Terminal, collapsed_patt) + elif len(exprs) > 0: + ret = EditablePartial.from_call(railroad.Sequence, items=[]) + else: + terminal = EditablePartial.from_call(railroad.Terminal, element.defaultName) + ret = terminal + + if ret is None: + return + + # Indicate this element's position in the tree so we can extract it if necessary + lookup[el_id] = ElementState( + element=element, + converted=ret, + parent=parent, + parent_index=index, + number=lookup.generate_index(), + ) + if element.customName: + lookup[el_id].mark_for_extraction(el_id, lookup, element.customName) + + i = 0 + for expr in exprs: + # Add a placeholder index in case we have to extract the child before we even add it to the parent + if "items" in ret.kwargs: + ret.kwargs["items"].insert(i, None) + + item = _to_diagram_element( + expr, + parent=ret, + lookup=lookup, + vertical=vertical, + index=i, + show_results_names=show_results_names, + show_groups=show_groups, + show_hidden=show_hidden, + ) + + # Some elements don't need to be shown in the diagram + if item is not None: + if "item" in ret.kwargs: + ret.kwargs["item"] = item + elif "items" in ret.kwargs: + # If we've already extracted the child, don't touch this index, since it's occupied by a nonterminal + ret.kwargs["items"][i] = item + i += 1 + elif "items" in ret.kwargs: + # If we're supposed to skip this element, remove it from the parent + del ret.kwargs["items"][i] + + # If all this items children are none, skip this item + if ret and ( + ("items" in ret.kwargs and len(ret.kwargs["items"]) == 0) + or ("item" in ret.kwargs and ret.kwargs["item"] is None) + ): + ret = EditablePartial.from_call(railroad.Terminal, name) + + # Mark this element as "complete", ie it has all of its children + if el_id in lookup: + lookup[el_id].complete = True + + if el_id in lookup and lookup[el_id].extract and lookup[el_id].complete: + lookup.extract_into_diagram(el_id) + if ret is not None: + text = lookup.diagrams[el_id].kwargs["name"] + href = f"#{_make_bookmark(text)}" + ret = EditablePartial.from_call( + railroad.NonTerminal, text=text, href=href + ) + + return ret diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/exceptions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..2c62ee357d61dbca30c8eacf61b06a8ec14d68f6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/exceptions.py @@ -0,0 +1,332 @@ +# exceptions.py +from __future__ import annotations + +import copy +import re +import sys +import typing +from functools import cached_property + +from .unicode import pyparsing_unicode as ppu +from .util import ( + _collapse_string_to_ranges, + col, + line, + lineno, + replaced_by_pep8, +) + + +class _ExceptionWordUnicodeSet( + ppu.Latin1, ppu.LatinA, ppu.LatinB, ppu.Greek, ppu.Cyrillic +): + pass + + +_extract_alphanums = _collapse_string_to_ranges(_ExceptionWordUnicodeSet.alphanums) +_exception_word_extractor = re.compile("([" + _extract_alphanums + "]{1,16})|.") + + +class ParseBaseException(Exception): + """base exception class for all parsing runtime exceptions""" + + loc: int + msg: str + pstr: str + parser_element: typing.Any # "ParserElement" + args: tuple[str, int, typing.Optional[str]] + + __slots__ = ( + "loc", + "msg", + "pstr", + "parser_element", + "args", + ) + + # Performance tuning: we construct a *lot* of these, so keep this + # constructor as small and fast as possible + def __init__( + self, + pstr: str, + loc: int = 0, + msg: typing.Optional[str] = None, + elem=None, + ) -> None: + if msg is None: + msg, pstr = pstr, "" + + self.loc = loc + self.msg = msg + self.pstr = pstr + self.parser_element = elem + self.args = (pstr, loc, msg) + + @staticmethod + def explain_exception(exc: Exception, depth: int = 16) -> str: + """ + Method to take an exception and translate the Python internal traceback into a list + of the pyparsing expressions that caused the exception to be raised. + + Parameters: + + - exc - exception raised during parsing (need not be a ParseException, in support + of Python exceptions that might be raised in a parse action) + - depth (default=16) - number of levels back in the stack trace to list expression + and function names; if None, the full stack trace names will be listed; if 0, only + the failing input line, marker, and exception string will be shown + + Returns a multi-line string listing the ParserElements and/or function names in the + exception's stack trace. + """ + import inspect + from .core import ParserElement + + if depth is None: + depth = sys.getrecursionlimit() + ret: list[str] = [] + if isinstance(exc, ParseBaseException): + ret.append(exc.line) + ret.append(f"{'^':>{exc.column}}") + ret.append(f"{type(exc).__name__}: {exc}") + + if depth <= 0 or exc.__traceback__ is None: + return "\n".join(ret) + + callers = inspect.getinnerframes(exc.__traceback__, context=depth) + seen: set[int] = set() + for ff in callers[-depth:]: + frm = ff[0] + + f_self = frm.f_locals.get("self", None) + if isinstance(f_self, ParserElement): + if not frm.f_code.co_name.startswith(("parseImpl", "_parseNoCache")): + continue + if id(f_self) in seen: + continue + seen.add(id(f_self)) + + self_type = type(f_self) + ret.append(f"{self_type.__module__}.{self_type.__name__} - {f_self}") + + elif f_self is not None: + self_type = type(f_self) + ret.append(f"{self_type.__module__}.{self_type.__name__}") + + else: + code = frm.f_code + if code.co_name in ("wrapper", ""): + continue + + ret.append(code.co_name) + + depth -= 1 + if not depth: + break + + return "\n".join(ret) + + @classmethod + def _from_exception(cls, pe) -> ParseBaseException: + """ + internal factory method to simplify creating one type of ParseException + from another - avoids having __init__ signature conflicts among subclasses + """ + return cls(pe.pstr, pe.loc, pe.msg, pe.parser_element) + + @cached_property + def line(self) -> str: + """ + Return the line of text where the exception occurred. + """ + return line(self.loc, self.pstr) + + @cached_property + def lineno(self) -> int: + """ + Return the 1-based line number of text where the exception occurred. + """ + return lineno(self.loc, self.pstr) + + @cached_property + def col(self) -> int: + """ + Return the 1-based column on the line of text where the exception occurred. + """ + return col(self.loc, self.pstr) + + @cached_property + def column(self) -> int: + """ + Return the 1-based column on the line of text where the exception occurred. + """ + return col(self.loc, self.pstr) + + @cached_property + def found(self) -> str: + if not self.pstr: + return "" + + if self.loc >= len(self.pstr): + return "end of text" + + # pull out next word at error location + found_match = _exception_word_extractor.match(self.pstr, self.loc) + if found_match is not None: + found_text = found_match.group(0) + else: + found_text = self.pstr[self.loc : self.loc + 1] + + return repr(found_text).replace(r"\\", "\\") + + # pre-PEP8 compatibility + @property + def parserElement(self): + return self.parser_element + + @parserElement.setter + def parserElement(self, elem): + self.parser_element = elem + + def copy(self): + return copy.copy(self) + + def formatted_message(self) -> str: + """ + Output the formatted exception message. + Can be overridden to customize the message formatting or contents. + + .. versionadded:: 3.2.0 + """ + found_phrase = f", found {self.found}" if self.found else "" + return f"{self.msg}{found_phrase} (at char {self.loc}), (line:{self.lineno}, col:{self.column})" + + def __str__(self) -> str: + """ + .. versionchanged:: 3.2.0 + Now uses :meth:`formatted_message` to format message. + """ + return self.formatted_message() + + def __repr__(self): + return str(self) + + def mark_input_line( + self, marker_string: typing.Optional[str] = None, *, markerString: str = ">!<" + ) -> str: + """ + Extracts the exception line from the input string, and marks + the location of the exception with a special symbol. + """ + markerString = marker_string if marker_string is not None else markerString + line_str = self.line + line_column = self.column - 1 + if markerString: + line_str = f"{line_str[:line_column]}{markerString}{line_str[line_column:]}" + return line_str.strip() + + def explain(self, depth: int = 16) -> str: + """ + Method to translate the Python internal traceback into a list + of the pyparsing expressions that caused the exception to be raised. + + Parameters: + + - depth (default=16) - number of levels back in the stack trace to list expression + and function names; if None, the full stack trace names will be listed; if 0, only + the failing input line, marker, and exception string will be shown + + Returns a multi-line string listing the ParserElements and/or function names in the + exception's stack trace. + + Example: + + .. testcode:: + + # an expression to parse 3 integers + expr = pp.Word(pp.nums) * 3 + try: + # a failing parse - the third integer is prefixed with "A" + expr.parse_string("123 456 A789") + except pp.ParseException as pe: + print(pe.explain(depth=0)) + + prints: + + .. testoutput:: + + 123 456 A789 + ^ + ParseException: Expected W:(0-9), found 'A789' (at char 8), (line:1, col:9) + + Note: the diagnostic output will include string representations of the expressions + that failed to parse. These representations will be more helpful if you use `set_name` to + give identifiable names to your expressions. Otherwise they will use the default string + forms, which may be cryptic to read. + + Note: pyparsing's default truncation of exception tracebacks may also truncate the + stack of expressions that are displayed in the ``explain`` output. To get the full listing + of parser expressions, you may have to set ``ParserElement.verbose_stacktrace = True`` + """ + return self.explain_exception(self, depth) + + # Compatibility synonyms + # fmt: off + markInputline = replaced_by_pep8("markInputline", mark_input_line) + # fmt: on + + +class ParseException(ParseBaseException): + """ + Exception thrown when a parse expression doesn't match the input string + + Example: + + .. testcode:: + + integer = Word(nums).set_name("integer") + try: + integer.parse_string("ABC") + except ParseException as pe: + print(pe, f"column: {pe.column}") + + prints: + + .. testoutput:: + + Expected integer, found 'ABC' (at char 0), (line:1, col:1) column: 1 + + """ + + +class ParseFatalException(ParseBaseException): + """ + User-throwable exception thrown when inconsistent parse content + is found; stops all parsing immediately + """ + + +class ParseSyntaxException(ParseFatalException): + """ + Just like :class:`ParseFatalException`, but thrown internally + when an :class:`ErrorStop` ('-' operator) indicates + that parsing is to stop immediately because an unbacktrackable + syntax error has been found. + """ + + +class RecursiveGrammarException(Exception): + """ + .. deprecated:: 3.0.0 + Only used by the deprecated :meth:`ParserElement.validate`. + + Exception thrown by :class:`ParserElement.validate` if the + grammar could be left-recursive; parser may need to enable + left recursion using :class:`ParserElement.enable_left_recursion` + """ + + def __init__(self, parseElementList) -> None: + self.parseElementTrace = parseElementList + + def __str__(self) -> str: + return f"RecursiveGrammarException: {self.parseElementTrace}" diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/helpers.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..09697eda1569affb32a9516041f96bae4784abca --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/helpers.py @@ -0,0 +1,1202 @@ +# helpers.py +import html.entities +import operator +import re +import sys +import typing + +from . import __diag__ +from .core import * +from .util import ( + _bslash, + _flatten, + _escape_regex_range_chars, + make_compressed_re, + replaced_by_pep8, +) + + +# +# global helpers +# +def counted_array( + expr: ParserElement, + int_expr: typing.Optional[ParserElement] = None, + *, + intExpr: typing.Optional[ParserElement] = None, +) -> ParserElement: + """Helper to define a counted list of expressions. + + This helper defines a pattern of the form:: + + integer expr expr expr... + + where the leading integer tells how many expr expressions follow. + The matched tokens returns the array of expr tokens as a list - the + leading count token is suppressed. + + If ``int_expr`` is specified, it should be a pyparsing expression + that produces an integer value. + + Examples: + + .. doctest:: + + >>> counted_array(Word(alphas)).parse_string('2 ab cd ef') + ParseResults(['ab', 'cd'], {}) + + - In this parser, the leading integer value is given in binary, + '10' indicating that 2 values are in the array: + + .. doctest:: + + >>> binary_constant = Word('01').set_parse_action(lambda t: int(t[0], 2)) + >>> counted_array(Word(alphas), int_expr=binary_constant + ... ).parse_string('10 ab cd ef') + ParseResults(['ab', 'cd'], {}) + + - If other fields must be parsed after the count but before the + list items, give the fields results names and they will + be preserved in the returned ParseResults: + + .. doctest:: + + >>> ppc = pyparsing.common + >>> count_with_metadata = ppc.integer + Word(alphas)("type") + >>> typed_array = counted_array(Word(alphanums), + ... int_expr=count_with_metadata)("items") + >>> result = typed_array.parse_string("3 bool True True False") + >>> print(result.dump()) + ['True', 'True', 'False'] + - items: ['True', 'True', 'False'] + - type: 'bool' + """ + intExpr = intExpr or int_expr + array_expr = Forward() + + def count_field_parse_action(s, l, t): + nonlocal array_expr + n = t[0] + array_expr <<= (expr * n) if n else Empty() + # clear list contents, but keep any named results + del t[:] + + if intExpr is None: + intExpr = Word(nums).set_parse_action(lambda t: int(t[0])) + else: + intExpr = intExpr.copy() + intExpr.set_name("arrayLen") + intExpr.add_parse_action(count_field_parse_action, call_during_try=True) + return (intExpr + array_expr).set_name(f"(len) {expr}...") + + +def match_previous_literal(expr: ParserElement) -> ParserElement: + """Helper to define an expression that is indirectly defined from + the tokens matched in a previous expression, that is, it looks for + a 'repeat' of a previous expression. For example:: + + .. testcode:: + + first = Word(nums) + second = match_previous_literal(first) + match_expr = first + ":" + second + + will match ``"1:1"``, but not ``"1:2"``. Because this + matches a previous literal, will also match the leading + ``"1:1"`` in ``"1:10"``. If this is not desired, use + :class:`match_previous_expr`. Do *not* use with packrat parsing + enabled. + """ + rep = Forward() + + def copy_token_to_repeater(s, l, t): + if not t: + rep << Empty() + return + + if len(t) == 1: + rep << t[0] + return + + # flatten t tokens + tflat = _flatten(t.as_list()) + rep << And(Literal(tt) for tt in tflat) + + expr.add_parse_action(copy_token_to_repeater, callDuringTry=True) + rep.set_name("(prev) " + str(expr)) + return rep + + +def match_previous_expr(expr: ParserElement) -> ParserElement: + """Helper to define an expression that is indirectly defined from + the tokens matched in a previous expression, that is, it looks for + a 'repeat' of a previous expression. For example: + + .. testcode:: + + first = Word(nums) + second = match_previous_expr(first) + match_expr = first + ":" + second + + will match ``"1:1"``, but not ``"1:2"``. Because this + matches by expressions, will *not* match the leading ``"1:1"`` + in ``"1:10"``; the expressions are evaluated first, and then + compared, so ``"1"`` is compared with ``"10"``. Do *not* use + with packrat parsing enabled. + """ + rep = Forward() + e2 = expr.copy() + rep <<= e2 + + def copy_token_to_repeater(s, l, t): + matchTokens = _flatten(t.as_list()) + + def must_match_these_tokens(s, l, t): + theseTokens = _flatten(t.as_list()) + if theseTokens != matchTokens: + raise ParseException( + s, l, f"Expected {matchTokens}, found{theseTokens}" + ) + + rep.set_parse_action(must_match_these_tokens, callDuringTry=True) + + expr.add_parse_action(copy_token_to_repeater, callDuringTry=True) + rep.set_name("(prev) " + str(expr)) + return rep + + +def one_of( + strs: Union[typing.Iterable[str], str], + caseless: bool = False, + use_regex: bool = True, + as_keyword: bool = False, + *, + useRegex: bool = True, + asKeyword: bool = False, +) -> ParserElement: + """Helper to quickly define a set of alternative :class:`Literal` s, + and makes sure to do longest-first testing when there is a conflict, + regardless of the input order, but returns + a :class:`MatchFirst` for best performance. + + :param strs: a string of space-delimited literals, or a collection of + string literals + :param caseless: treat all literals as caseless + :param use_regex: bool - as an optimization, will + generate a :class:`Regex` object; otherwise, will generate + a :class:`MatchFirst` object (if ``caseless=True`` or + ``as_keyword=True``, or if creating a :class:`Regex` raises an exception) + :param as_keyword: bool - enforce :class:`Keyword`-style matching on the + generated expressions + + Parameters ``asKeyword`` and ``useRegex`` are retained for pre-PEP8 + compatibility, but will be removed in a future release. + + Example: + + .. testcode:: + + comp_oper = one_of("< = > <= >= !=") + var = Word(alphas) + number = Word(nums) + term = var | number + comparison_expr = term + comp_oper + term + print(comparison_expr.search_string("B = 12 AA=23 B<=AA AA>12")) + + prints: + + .. testoutput:: + + [['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']] + """ + asKeyword = asKeyword or as_keyword + useRegex = useRegex and use_regex + + if ( + isinstance(caseless, str_type) + and __diag__.warn_on_multiple_string_args_to_oneof + ): + warnings.warn( + "warn_on_multiple_string_args_to_oneof:" + " More than one string argument passed to one_of, pass" + " choices as a list or space-delimited string", + stacklevel=2, + ) + + if caseless: + is_equal = lambda a, b: a.upper() == b.upper() + masks = lambda a, b: b.upper().startswith(a.upper()) + else: + is_equal = operator.eq + masks = lambda a, b: b.startswith(a) + + symbols: list[str] + if isinstance(strs, str_type): + strs = typing.cast(str, strs) + symbols = strs.split() + elif isinstance(strs, Iterable): + symbols = list(strs) + else: + raise TypeError("Invalid argument to one_of, expected string or iterable") + if not symbols: + return NoMatch() + + # reorder given symbols to take care to avoid masking longer choices with shorter ones + # (but only if the given symbols are not just single characters) + i = 0 + while i < len(symbols) - 1: + cur = symbols[i] + for j, other in enumerate(symbols[i + 1 :]): + if is_equal(other, cur): + del symbols[i + j + 1] + break + if len(other) > len(cur) and masks(cur, other): + del symbols[i + j + 1] + symbols.insert(i, other) + break + else: + i += 1 + + if useRegex: + re_flags: int = re.IGNORECASE if caseless else 0 + + try: + if all(len(sym) == 1 for sym in symbols): + # symbols are just single characters, create range regex pattern + patt = f"[{''.join(_escape_regex_range_chars(sym) for sym in symbols)}]" + else: + patt = "|".join(re.escape(sym) for sym in symbols) + + # wrap with \b word break markers if defining as keywords + if asKeyword: + patt = rf"\b(?:{patt})\b" + + ret = Regex(patt, flags=re_flags) + ret.set_name(" | ".join(repr(s) for s in symbols)) + + if caseless: + # add parse action to return symbols as specified, not in random + # casing as found in input string + symbol_map = {sym.lower(): sym for sym in symbols} + ret.add_parse_action(lambda s, l, t: symbol_map[t[0].lower()]) + + return ret + + except re.error: + warnings.warn( + "Exception creating Regex for one_of, building MatchFirst", stacklevel=2 + ) + + # last resort, just use MatchFirst of Token class corresponding to caseless + # and asKeyword settings + CASELESS = KEYWORD = True + parse_element_class = { + (CASELESS, KEYWORD): CaselessKeyword, + (CASELESS, not KEYWORD): CaselessLiteral, + (not CASELESS, KEYWORD): Keyword, + (not CASELESS, not KEYWORD): Literal, + }[(caseless, asKeyword)] + return MatchFirst(parse_element_class(sym) for sym in symbols).set_name( + " | ".join(symbols) + ) + + +def dict_of(key: ParserElement, value: ParserElement) -> Dict: + """Helper to easily and clearly define a dictionary by specifying + the respective patterns for the key and value. Takes care of + defining the :class:`Dict`, :class:`ZeroOrMore`, and + :class:`Group` tokens in the proper order. The key pattern + can include delimiting markers or punctuation, as long as they are + suppressed, thereby leaving the significant key text. The value + pattern can include named results, so that the :class:`Dict` results + can include named token fields. + + Example: + + .. doctest:: + + >>> text = "shape: SQUARE posn: upper left color: light blue texture: burlap" + + >>> data_word = Word(alphas) + >>> label = data_word + FollowedBy(':') + >>> attr_expr = ( + ... label + ... + Suppress(':') + ... + OneOrMore(data_word, stop_on=label) + ... .set_parse_action(' '.join)) + >>> print(attr_expr[1, ...].parse_string(text).dump()) + ['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap'] + + >>> attr_label = label + >>> attr_value = Suppress(':') + OneOrMore(data_word, stop_on=label + ... ).set_parse_action(' '.join) + + # similar to Dict, but simpler call format + >>> result = dict_of(attr_label, attr_value).parse_string(text) + >>> print(result.dump()) + [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] + - color: 'light blue' + - posn: 'upper left' + - shape: 'SQUARE' + - texture: 'burlap' + [0]: + ['shape', 'SQUARE'] + [1]: + ['posn', 'upper left'] + [2]: + ['color', 'light blue'] + [3]: + ['texture', 'burlap'] + + >>> print(result['shape']) + SQUARE + >>> print(result.shape) # object attribute access works too + SQUARE + >>> print(result.as_dict()) + {'shape': 'SQUARE', 'posn': 'upper left', 'color': 'light blue', 'texture': 'burlap'} + """ + return Dict(OneOrMore(Group(key + value))) + + +def original_text_for( + expr: ParserElement, as_string: bool = True, *, asString: bool = True +) -> ParserElement: + """Helper to return the original, untokenized text for a given + expression. Useful to restore the parsed fields of an HTML start + tag into the raw tag text itself, or to revert separate tokens with + intervening whitespace back to the original matching input text. By + default, returns a string containing the original parsed text. + + If the optional ``as_string`` argument is passed as + ``False``, then the return value is + a :class:`ParseResults` containing any results names that + were originally matched, and a single token containing the original + matched text from the input string. So if the expression passed to + :class:`original_text_for` contains expressions with defined + results names, you must set ``as_string`` to ``False`` if you + want to preserve those results name values. + + The ``asString`` pre-PEP8 argument is retained for compatibility, + but will be removed in a future release. + + Example: + + .. testcode:: + + src = "this is test bold text normal text " + for tag in ("b", "i"): + opener, closer = make_html_tags(tag) + patt = original_text_for(opener + ... + closer) + print(patt.search_string(src)[0]) + + prints: + + .. testoutput:: + + [' bold text '] + ['text'] + """ + asString = asString and as_string + + locMarker = Empty().set_parse_action(lambda s, loc, t: loc) + endlocMarker = locMarker.copy() + endlocMarker.callPreparse = False + matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end") + if asString: + extractText = lambda s, l, t: s[t._original_start : t._original_end] + else: + + def extractText(s, l, t): + t[:] = [s[t.pop("_original_start") : t.pop("_original_end")]] + + matchExpr.set_parse_action(extractText) + matchExpr.ignoreExprs = expr.ignoreExprs + matchExpr.suppress_warning(Diagnostics.warn_ungrouped_named_tokens_in_collection) + return matchExpr + + +def ungroup(expr: ParserElement) -> ParserElement: + """Helper to undo pyparsing's default grouping of And expressions, + even if all but one are non-empty. + """ + return TokenConverter(expr).add_parse_action(lambda t: t[0]) + + +def locatedExpr(expr: ParserElement) -> ParserElement: + """ + .. deprecated:: 3.0.0 + Use the :class:`Located` class instead. + + Helper to decorate a returned token with its starting and ending + locations in the input string. + + This helper adds the following results names: + + - ``locn_start`` - location where matched expression begins + - ``locn_end`` - location where matched expression ends + - ``value`` - the actual parsed results + + Be careful if the input text contains ```` characters, you + may want to call :meth:`ParserElement.parse_with_tabs` + + Example: + + .. testcode:: + + wd = Word(alphas) + res = locatedExpr(wd).search_string("ljsdf123lksdjjf123lkkjj1222") + for match in res: + print(match) + + prints: + + .. testoutput:: + + [[0, 'ljsdf', 5]] + [[8, 'lksdjjf', 15]] + [[18, 'lkkjj', 23]] + """ + locator = Empty().set_parse_action(lambda ss, ll, tt: ll) + return Group( + locator("locn_start") + + expr("value") + + locator.copy().leaveWhitespace()("locn_end") + ) + + +# define special default value to permit None as a significant value for +# ignore_expr +_NO_IGNORE_EXPR_GIVEN = NoMatch() + + +def nested_expr( + opener: Union[str, ParserElement] = "(", + closer: Union[str, ParserElement] = ")", + content: typing.Optional[ParserElement] = None, + ignore_expr: typing.Optional[ParserElement] = _NO_IGNORE_EXPR_GIVEN, + *, + ignoreExpr: typing.Optional[ParserElement] = _NO_IGNORE_EXPR_GIVEN, +) -> ParserElement: + """Helper method for defining nested lists enclosed in opening and + closing delimiters (``"("`` and ``")"`` are the default). + + :param opener: str - opening character for a nested list + (default= ``"("``); can also be a pyparsing expression + + :param closer: str - closing character for a nested list + (default= ``")"``); can also be a pyparsing expression + + :param content: expression for items within the nested lists + + :param ignore_expr: expression for ignoring opening and closing delimiters + (default = :class:`quoted_string`) + + Parameter ``ignoreExpr`` is retained for compatibility + but will be removed in a future release. + + If an expression is not provided for the content argument, the + nested expression will capture all whitespace-delimited content + between delimiters as a list of separate values. + + Use the ``ignore_expr`` argument to define expressions that may + contain opening or closing characters that should not be treated as + opening or closing characters for nesting, such as quoted_string or + a comment expression. Specify multiple expressions using an + :class:`Or` or :class:`MatchFirst`. The default is + :class:`quoted_string`, but if no expressions are to be ignored, then + pass ``None`` for this argument. + + Example: + + .. testcode:: + + data_type = one_of("void int short long char float double") + decl_data_type = Combine(data_type + Opt(Word('*'))) + ident = Word(alphas+'_', alphanums+'_') + number = pyparsing_common.number + arg = Group(decl_data_type + ident) + LPAR, RPAR = map(Suppress, "()") + + code_body = nested_expr('{', '}', ignore_expr=(quoted_string | c_style_comment)) + + c_function = (decl_data_type("type") + + ident("name") + + LPAR + Opt(DelimitedList(arg), [])("args") + RPAR + + code_body("body")) + c_function.ignore(c_style_comment) + + source_code = ''' + int is_odd(int x) { + return (x%2); + } + + int dec_to_hex(char hchar) { + if (hchar >= '0' && hchar <= '9') { + return (ord(hchar)-ord('0')); + } else { + return (10+ord(hchar)-ord('A')); + } + } + ''' + for func in c_function.search_string(source_code): + print(f"{func.name} ({func.type}) args: {func.args}") + + + prints: + + .. testoutput:: + + is_odd (int) args: [['int', 'x']] + dec_to_hex (int) args: [['char', 'hchar']] + """ + if ignoreExpr != ignore_expr: + ignoreExpr = ignore_expr if ignoreExpr is _NO_IGNORE_EXPR_GIVEN else ignoreExpr + + if ignoreExpr is _NO_IGNORE_EXPR_GIVEN: + ignoreExpr = quoted_string() + + if opener == closer: + raise ValueError("opening and closing strings cannot be the same") + + if content is None: + if isinstance(opener, str_type) and isinstance(closer, str_type): + opener = typing.cast(str, opener) + closer = typing.cast(str, closer) + if len(opener) == 1 and len(closer) == 1: + if ignoreExpr is not None: + content = Combine( + OneOrMore( + ~ignoreExpr + + CharsNotIn( + opener + closer + ParserElement.DEFAULT_WHITE_CHARS, + exact=1, + ) + ) + ) + else: + content = Combine( + Empty() + + CharsNotIn( + opener + closer + ParserElement.DEFAULT_WHITE_CHARS + ) + ) + else: + if ignoreExpr is not None: + content = Combine( + OneOrMore( + ~ignoreExpr + + ~Literal(opener) + + ~Literal(closer) + + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1) + ) + ) + else: + content = Combine( + OneOrMore( + ~Literal(opener) + + ~Literal(closer) + + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1) + ) + ) + else: + raise ValueError( + "opening and closing arguments must be strings if no content expression is given" + ) + + # for these internally-created context expressions, simulate whitespace-skipping + if ParserElement.DEFAULT_WHITE_CHARS: + content.set_parse_action( + lambda t: t[0].strip(ParserElement.DEFAULT_WHITE_CHARS) + ) + + ret = Forward() + if ignoreExpr is not None: + ret <<= Group( + Suppress(opener) + ZeroOrMore(ignoreExpr | ret | content) + Suppress(closer) + ) + else: + ret <<= Group(Suppress(opener) + ZeroOrMore(ret | content) + Suppress(closer)) + + ret.set_name(f"nested {opener}{closer} expression") + + # don't override error message from content expressions + ret.errmsg = None + return ret + + +def _makeTags(tagStr, xml, suppress_LT=Suppress("<"), suppress_GT=Suppress(">")): + """Internal helper to construct opening and closing tag expressions, + given a tag name""" + if isinstance(tagStr, str_type): + resname = tagStr + tagStr = Keyword(tagStr, caseless=not xml) + else: + resname = tagStr.name + + tagAttrName = Word(alphas, alphanums + "_-:") + if xml: + tagAttrValue = dbl_quoted_string.copy().set_parse_action(remove_quotes) + openTag = ( + suppress_LT + + tagStr("tag") + + Dict(ZeroOrMore(Group(tagAttrName + Suppress("=") + tagAttrValue))) + + Opt("/", default=[False])("empty").set_parse_action( + lambda s, l, t: t[0] == "/" + ) + + suppress_GT + ) + else: + tagAttrValue = quoted_string.copy().set_parse_action(remove_quotes) | Word( + printables, exclude_chars=">" + ) + openTag = ( + suppress_LT + + tagStr("tag") + + Dict( + ZeroOrMore( + Group( + tagAttrName.set_parse_action(lambda t: t[0].lower()) + + Opt(Suppress("=") + tagAttrValue) + ) + ) + ) + + Opt("/", default=[False])("empty").set_parse_action( + lambda s, l, t: t[0] == "/" + ) + + suppress_GT + ) + closeTag = Combine(Literal("", adjacent=False) + + openTag.set_name(f"<{resname}>") + # add start results name in parse action now that ungrouped names are not reported at two levels + openTag.add_parse_action( + lambda t: t.__setitem__( + "start" + "".join(resname.replace(":", " ").title().split()), t.copy() + ) + ) + closeTag = closeTag( + "end" + "".join(resname.replace(":", " ").title().split()) + ).set_name(f"") + openTag.tag = resname + closeTag.tag = resname + openTag.tag_body = SkipTo(closeTag()) + return openTag, closeTag + + +def make_html_tags( + tag_str: Union[str, ParserElement], +) -> tuple[ParserElement, ParserElement]: + """Helper to construct opening and closing tag expressions for HTML, + given a tag name. Matches tags in either upper or lower case, + attributes with namespaces and with quoted or unquoted values. + + Example: + + .. testcode:: + + text = 'More info at the pyparsing wiki page' + # make_html_tags returns pyparsing expressions for the opening and + # closing tags as a 2-tuple + a, a_end = make_html_tags("A") + link_expr = a + SkipTo(a_end)("link_text") + a_end + + for link in link_expr.search_string(text): + # attributes in the tag (like "href" shown here) are + # also accessible as named results + print(link.link_text, '->', link.href) + + prints: + + .. testoutput:: + + pyparsing -> https://github.com/pyparsing/pyparsing/wiki + """ + return _makeTags(tag_str, False) + + +def make_xml_tags( + tag_str: Union[str, ParserElement], +) -> tuple[ParserElement, ParserElement]: + """Helper to construct opening and closing tag expressions for XML, + given a tag name. Matches tags only in the given upper/lower case. + + Example: similar to :class:`make_html_tags` + """ + return _makeTags(tag_str, True) + + +any_open_tag: ParserElement +any_close_tag: ParserElement +any_open_tag, any_close_tag = make_html_tags( + Word(alphas, alphanums + "_:").set_name("any tag") +) + +_htmlEntityMap = {k.rstrip(";"): v for k, v in html.entities.html5.items()} +_most_common_entities = "nbsp lt gt amp quot apos cent pound euro copy".replace( + " ", "|" +) +common_html_entity = Regex( + lambda: f"&(?P{_most_common_entities}|{make_compressed_re(_htmlEntityMap)});" +).set_name("common HTML entity") + + +def replace_html_entity(s, l, t): + """Helper parser action to replace common HTML entities with their special characters""" + return _htmlEntityMap.get(t.entity) + + +class OpAssoc(Enum): + """Enumeration of operator associativity + - used in constructing InfixNotationOperatorSpec for :class:`infix_notation`""" + + LEFT = 1 + RIGHT = 2 + + +InfixNotationOperatorArgType = Union[ + ParserElement, str, tuple[Union[ParserElement, str], Union[ParserElement, str]] +] +InfixNotationOperatorSpec = Union[ + tuple[ + InfixNotationOperatorArgType, + int, + OpAssoc, + typing.Optional[ParseAction], + ], + tuple[ + InfixNotationOperatorArgType, + int, + OpAssoc, + ], +] + + +def infix_notation( + base_expr: ParserElement, + op_list: list[InfixNotationOperatorSpec], + lpar: Union[str, ParserElement] = Suppress("("), + rpar: Union[str, ParserElement] = Suppress(")"), +) -> Forward: + """Helper method for constructing grammars of expressions made up of + operators working in a precedence hierarchy. Operators may be unary + or binary, left- or right-associative. Parse actions can also be + attached to operator expressions. The generated parser will also + recognize the use of parentheses to override operator precedences + (see example below). + + Note: if you define a deep operator list, you may see performance + issues when using infix_notation. See + :class:`ParserElement.enable_packrat` for a mechanism to potentially + improve your parser performance. + + Parameters: + + :param base_expr: expression representing the most basic operand to + be used in the expression + :param op_list: list of tuples, one for each operator precedence level + in the expression grammar; each tuple is of the form ``(op_expr, + num_operands, right_left_assoc, (optional)parse_action)``, where: + + - ``op_expr`` is the pyparsing expression for the operator; may also + be a string, which will be converted to a Literal; if ``num_operands`` + is 3, ``op_expr`` is a tuple of two expressions, for the two + operators separating the 3 terms + - ``num_operands`` is the number of terms for this operator (must be 1, + 2, or 3) + - ``right_left_assoc`` is the indicator whether the operator is right + or left associative, using the pyparsing-defined constants + ``OpAssoc.RIGHT`` and ``OpAssoc.LEFT``. + - ``parse_action`` is the parse action to be associated with + expressions matching this operator expression (the parse action + tuple member may be omitted); if the parse action is passed + a tuple or list of functions, this is equivalent to calling + ``set_parse_action(*fn)`` + (:class:`ParserElement.set_parse_action`) + + :param lpar: expression for matching left-parentheses; if passed as a + str, then will be parsed as ``Suppress(lpar)``. If lpar is passed as + an expression (such as ``Literal('(')``), then it will be kept in + the parsed results, and grouped with them. (default= ``Suppress('(')``) + :param rpar: expression for matching right-parentheses; if passed as a + str, then will be parsed as ``Suppress(rpar)``. If rpar is passed as + an expression (such as ``Literal(')')``), then it will be kept in + the parsed results, and grouped with them. (default= ``Suppress(')')``) + + Example: + + .. testcode:: + + # simple example of four-function arithmetic with ints and + # variable names + integer = pyparsing_common.signed_integer + varname = pyparsing_common.identifier + + arith_expr = infix_notation(integer | varname, + [ + ('-', 1, OpAssoc.RIGHT), + (one_of('* /'), 2, OpAssoc.LEFT), + (one_of('+ -'), 2, OpAssoc.LEFT), + ]) + + arith_expr.run_tests(''' + 5+3*6 + (5+3)*6 + (5+x)*y + -2--11 + ''', full_dump=False) + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + 5+3*6 + [[5, '+', [3, '*', 6]]] + + (5+3)*6 + [[[5, '+', 3], '*', 6]] + + (5+x)*y + [[[5, '+', 'x'], '*', 'y']] + + -2--11 + [[['-', 2], '-', ['-', 11]]] + """ + + # captive version of FollowedBy that does not do parse actions or capture results names + class _FB(FollowedBy): + def parseImpl(self, instring, loc, doActions=True): + self.expr.try_parse(instring, loc) + return loc, [] + + _FB.__name__ = "FollowedBy>" + + ret = Forward() + ret.set_name(f"{base_expr.name}_expression") + if isinstance(lpar, str): + lpar = Suppress(lpar) + if isinstance(rpar, str): + rpar = Suppress(rpar) + + nested_expr = (lpar + ret + rpar).set_name(f"nested_{base_expr.name}_expression") + + # if lpar and rpar are not suppressed, wrap in group + if not (isinstance(lpar, Suppress) and isinstance(rpar, Suppress)): + lastExpr = base_expr | Group(nested_expr) + else: + lastExpr = base_expr | nested_expr + + arity: int + rightLeftAssoc: opAssoc + pa: typing.Optional[ParseAction] + opExpr1: ParserElement + opExpr2: ParserElement + matchExpr: ParserElement + match_lookahead: ParserElement + for operDef in op_list: + opExpr, arity, rightLeftAssoc, pa = (operDef + (None,))[:4] # type: ignore[assignment] + if isinstance(opExpr, str_type): + opExpr = ParserElement._literalStringClass(opExpr) + opExpr = typing.cast(ParserElement, opExpr) + if arity == 3: + if not isinstance(opExpr, (tuple, list)) or len(opExpr) != 2: + raise ValueError( + "if numterms=3, opExpr must be a tuple or list of two expressions" + ) + opExpr1, opExpr2 = opExpr + term_name = f"{opExpr1}{opExpr2} operations" + else: + term_name = f"{opExpr} operations" + + if not 1 <= arity <= 3: + raise ValueError("operator must be unary (1), binary (2), or ternary (3)") + + if rightLeftAssoc not in (OpAssoc.LEFT, OpAssoc.RIGHT): + raise ValueError("operator must indicate right or left associativity") + + thisExpr: ParserElement = Forward().set_name(term_name) + thisExpr = typing.cast(Forward, thisExpr) + match_lookahead = And([]) + if rightLeftAssoc is OpAssoc.LEFT: + if arity == 1: + match_lookahead = _FB(lastExpr + opExpr) + matchExpr = Group(lastExpr + opExpr[1, ...]) + elif arity == 2: + if opExpr is not None: + match_lookahead = _FB(lastExpr + opExpr + lastExpr) + matchExpr = Group(lastExpr + (opExpr + lastExpr)[1, ...]) + else: + match_lookahead = _FB(lastExpr + lastExpr) + matchExpr = Group(lastExpr[2, ...]) + elif arity == 3: + match_lookahead = _FB( + lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr + ) + matchExpr = Group( + lastExpr + (opExpr1 + lastExpr + opExpr2 + lastExpr)[1, ...] + ) + elif rightLeftAssoc is OpAssoc.RIGHT: + if arity == 1: + # try to avoid LR with this extra test + if not isinstance(opExpr, Opt): + opExpr = Opt(opExpr) + match_lookahead = _FB(opExpr.expr + thisExpr) + matchExpr = Group(opExpr + thisExpr) + elif arity == 2: + if opExpr is not None: + match_lookahead = _FB(lastExpr + opExpr + thisExpr) + matchExpr = Group(lastExpr + (opExpr + thisExpr)[1, ...]) + else: + match_lookahead = _FB(lastExpr + thisExpr) + matchExpr = Group(lastExpr + thisExpr[1, ...]) + elif arity == 3: + match_lookahead = _FB( + lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr + ) + matchExpr = Group(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr) + + # suppress lookahead expr from railroad diagrams + match_lookahead.show_in_diagram = False + + # TODO - determine why this statement can't be included in the following + # if pa block + matchExpr = match_lookahead + matchExpr + + if pa: + if isinstance(pa, (tuple, list)): + matchExpr.set_parse_action(*pa) + else: + matchExpr.set_parse_action(pa) + + thisExpr <<= (matchExpr | lastExpr).setName(term_name) + lastExpr = thisExpr + + ret <<= lastExpr + return ret + + +def indentedBlock(blockStatementExpr, indentStack, indent=True, backup_stacks=[]): + """ + .. deprecated:: 3.0.0 + Use the :class:`IndentedBlock` class instead. + + Helper method for defining space-delimited indentation blocks, + such as those used to define block statements in Python source code. + + :param blockStatementExpr: expression defining syntax of statement that + is repeated within the indented block + + :param indentStack: list created by caller to manage indentation stack + (multiple ``statementWithIndentedBlock`` expressions within a single + grammar should share a common ``indentStack``) + + :param indent: boolean indicating whether block must be indented beyond + the current level; set to ``False`` for block of left-most statements + + A valid block must contain at least one ``blockStatement``. + + (Note that indentedBlock uses internal parse actions which make it + incompatible with packrat parsing.) + + Example: + + .. testcode:: + + data = ''' + def A(z): + A1 + B = 100 + G = A2 + A2 + A3 + B + def BB(a,b,c): + BB1 + def BBA(): + bba1 + bba2 + bba3 + C + D + def spam(x,y): + def eggs(z): + pass + ''' + + indentStack = [1] + stmt = Forward() + + identifier = Word(alphas, alphanums) + funcDecl = ("def" + identifier + Group("(" + Opt(delimitedList(identifier)) + ")") + ":") + func_body = indentedBlock(stmt, indentStack) + funcDef = Group(funcDecl + func_body) + + rvalue = Forward() + funcCall = Group(identifier + "(" + Opt(delimitedList(rvalue)) + ")") + rvalue << (funcCall | identifier | Word(nums)) + assignment = Group(identifier + "=" + rvalue) + stmt << (funcDef | assignment | identifier) + + module_body = stmt[1, ...] + + parseTree = module_body.parseString(data) + parseTree.pprint() + + prints: + + .. testoutput:: + + [['def', + 'A', + ['(', 'z', ')'], + ':', + [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]], + 'B', + ['def', + 'BB', + ['(', 'a', 'b', 'c', ')'], + ':', + [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]], + 'C', + 'D', + ['def', + 'spam', + ['(', 'x', 'y', ')'], + ':', + [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]] + """ + backup_stacks.append(indentStack[:]) + + def reset_stack(): + indentStack[:] = backup_stacks[-1] + + def checkPeerIndent(s, l, t): + if l >= len(s): + return + curCol = col(l, s) + if curCol != indentStack[-1]: + if curCol > indentStack[-1]: + raise ParseException(s, l, "illegal nesting") + raise ParseException(s, l, "not a peer entry") + + def checkSubIndent(s, l, t): + curCol = col(l, s) + if curCol > indentStack[-1]: + indentStack.append(curCol) + else: + raise ParseException(s, l, "not a subentry") + + def checkUnindent(s, l, t): + if l >= len(s): + return + curCol = col(l, s) + if not (indentStack and curCol in indentStack): + raise ParseException(s, l, "not an unindent") + if curCol < indentStack[-1]: + indentStack.pop() + + NL = OneOrMore(LineEnd().set_whitespace_chars("\t ").suppress()) + INDENT = (Empty() + Empty().set_parse_action(checkSubIndent)).set_name("INDENT") + PEER = Empty().set_parse_action(checkPeerIndent).set_name("") + UNDENT = Empty().set_parse_action(checkUnindent).set_name("UNINDENT") + if indent: + smExpr = Group( + Opt(NL) + + INDENT + + OneOrMore(PEER + Group(blockStatementExpr) + Opt(NL)) + + UNDENT + ) + else: + smExpr = Group( + Opt(NL) + + OneOrMore(PEER + Group(blockStatementExpr) + Opt(NL)) + + Opt(UNDENT) + ) + + # add a parse action to remove backup_stack from list of backups + smExpr.add_parse_action( + lambda: backup_stacks.pop(-1) and None if backup_stacks else None + ) + smExpr.set_fail_action(lambda a, b, c, d: reset_stack()) + blockStatementExpr.ignore(_bslash + LineEnd()) + return smExpr.set_name("indented block") + + +# it's easy to get these comment structures wrong - they're very common, +# so may as well make them available +c_style_comment = Regex(r"/\*(?:[^*]|\*(?!/))*\*\/").set_name("C style comment") +"Comment of the form ``/* ... */``" + +html_comment = Regex(r"").set_name("HTML comment") +"Comment of the form ````" + +rest_of_line = Regex(r".*").leave_whitespace().set_name("rest of line") +dbl_slash_comment = Regex(r"//(?:\\\n|[^\n])*").set_name("// comment") +"Comment of the form ``// ... (to end of line)``" + +cpp_style_comment = Regex( + r"(?:/\*(?:[^*]|\*(?!/))*\*\/)|(?://(?:\\\n|[^\n])*)" +).set_name("C++ style comment") +"Comment of either form :class:`c_style_comment` or :class:`dbl_slash_comment`" + +java_style_comment = cpp_style_comment +"Same as :class:`cpp_style_comment`" + +python_style_comment = Regex(r"#.*").set_name("Python style comment") +"Comment of the form ``# ... (to end of line)``" + + +# build list of built-in expressions, for future reference if a global default value +# gets updated +_builtin_exprs: list[ParserElement] = [ + v for v in vars().values() if isinstance(v, ParserElement) +] + + +# compatibility function, superseded by DelimitedList class +def delimited_list( + expr: Union[str, ParserElement], + delim: Union[str, ParserElement] = ",", + combine: bool = False, + min: typing.Optional[int] = None, + max: typing.Optional[int] = None, + *, + allow_trailing_delim: bool = False, +) -> ParserElement: + """ + .. deprecated:: 3.1.0 + Use the :class:`DelimitedList` class instead. + """ + return DelimitedList( + expr, delim, combine, min, max, allow_trailing_delim=allow_trailing_delim + ) + + +# Compatibility synonyms +# fmt: off +opAssoc = OpAssoc +anyOpenTag = any_open_tag +anyCloseTag = any_close_tag +commonHTMLEntity = common_html_entity +cStyleComment = c_style_comment +htmlComment = html_comment +restOfLine = rest_of_line +dblSlashComment = dbl_slash_comment +cppStyleComment = cpp_style_comment +javaStyleComment = java_style_comment +pythonStyleComment = python_style_comment +delimitedList = replaced_by_pep8("delimitedList", DelimitedList) +delimited_list = replaced_by_pep8("delimited_list", DelimitedList) +countedArray = replaced_by_pep8("countedArray", counted_array) +matchPreviousLiteral = replaced_by_pep8("matchPreviousLiteral", match_previous_literal) +matchPreviousExpr = replaced_by_pep8("matchPreviousExpr", match_previous_expr) +oneOf = replaced_by_pep8("oneOf", one_of) +dictOf = replaced_by_pep8("dictOf", dict_of) +originalTextFor = replaced_by_pep8("originalTextFor", original_text_for) +nestedExpr = replaced_by_pep8("nestedExpr", nested_expr) +makeHTMLTags = replaced_by_pep8("makeHTMLTags", make_html_tags) +makeXMLTags = replaced_by_pep8("makeXMLTags", make_xml_tags) +replaceHTMLEntity = replaced_by_pep8("replaceHTMLEntity", replace_html_entity) +infixNotation = replaced_by_pep8("infixNotation", infix_notation) +# fmt: on diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/py.typed b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/results.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/results.py new file mode 100644 index 0000000000000000000000000000000000000000..5dabe58a90d545503b37e6ecfc99cef41c159351 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/results.py @@ -0,0 +1,932 @@ +# results.py + +from __future__ import annotations + +import collections +from collections.abc import ( + MutableMapping, + Mapping, + MutableSequence, + Iterator, + Iterable, +) +import pprint +from typing import Any + +from .util import replaced_by_pep8 + + +str_type: tuple[type, ...] = (str, bytes) +_generator_type = type((_ for _ in ())) + + +class _ParseResultsWithOffset: + tup: tuple[ParseResults, int] + __slots__ = ["tup"] + + def __init__(self, p1: ParseResults, p2: int) -> None: + self.tup: tuple[ParseResults, int] = (p1, p2) + + def __getitem__(self, i): + return self.tup[i] + + def __getstate__(self): + return self.tup + + def __setstate__(self, *args): + self.tup = args[0] + + +class ParseResults: + """Structured parse results, to provide multiple means of access to + the parsed data: + + - as a list (``len(results)``) + - by list index (``results[0], results[1]``, etc.) + - by attribute (``results.`` - see :class:`ParserElement.set_results_name`) + + Example: + + .. testcode:: + + integer = Word(nums) + date_str = (integer.set_results_name("year") + '/' + + integer.set_results_name("month") + '/' + + integer.set_results_name("day")) + # equivalent form: + # date_str = (integer("year") + '/' + # + integer("month") + '/' + # + integer("day")) + + # parse_string returns a ParseResults object + result = date_str.parse_string("1999/12/31") + + def test(s, fn=repr): + print(f"{s} -> {fn(eval(s))}") + + test("list(result)") + test("result[0]") + test("result['month']") + test("result.day") + test("'month' in result") + test("'minutes' in result") + test("result.dump()", str) + + prints: + + .. testoutput:: + + list(result) -> ['1999', '/', '12', '/', '31'] + result[0] -> '1999' + result['month'] -> '12' + result.day -> '31' + 'month' in result -> True + 'minutes' in result -> False + result.dump() -> ['1999', '/', '12', '/', '31'] + - day: '31' + - month: '12' + - year: '1999' + + """ + + _null_values: tuple[Any, ...] = (None, [], ()) + + _name: str + _parent: ParseResults + _all_names: set[str] + _modal: bool + _toklist: list[Any] + _tokdict: dict[str, Any] + + __slots__ = ( + "_name", + "_parent", + "_all_names", + "_modal", + "_toklist", + "_tokdict", + ) + + class List(list): + """ + Simple wrapper class to distinguish parsed list results that should be preserved + as actual Python lists, instead of being converted to :class:`ParseResults`: + + .. testcode:: + + import pyparsing as pp + ppc = pp.common + + LBRACK, RBRACK, LPAR, RPAR = pp.Suppress.using_each("[]()") + element = pp.Forward() + item = ppc.integer + item_list = pp.DelimitedList(element) + element_list = LBRACK + item_list + RBRACK | LPAR + item_list + RPAR + element <<= item | element_list + + # add parse action to convert from ParseResults + # to actual Python collection types + @element_list.add_parse_action + def as_python_list(t): + return pp.ParseResults.List(t.as_list()) + + element.run_tests(''' + 100 + [2,3,4] + [[2, 1],3,4] + [(2, 1),3,4] + (2,3,4) + ([2, 3], 4) + ''', post_parse=lambda s, r: (r[0], type(r[0])) + ) + + prints: + + .. testoutput:: + :options: +NORMALIZE_WHITESPACE + + + 100 + (100, ) + + [2,3,4] + ([2, 3, 4], ) + + [[2, 1],3,4] + ([[2, 1], 3, 4], ) + + [(2, 1),3,4] + ([[2, 1], 3, 4], ) + + (2,3,4) + ([2, 3, 4], ) + + ([2, 3], 4) + ([[2, 3], 4], ) + + (Used internally by :class:`Group` when `aslist=True`.) + """ + + def __new__(cls, contained=None): + if contained is None: + contained = [] + + if not isinstance(contained, list): + raise TypeError( + f"{cls.__name__} may only be constructed with a list, not {type(contained).__name__}" + ) + + return list.__new__(cls) + + def __new__(cls, toklist=None, name=None, **kwargs): + if isinstance(toklist, ParseResults): + return toklist + self = object.__new__(cls) + self._name = None + self._parent = None + self._all_names = set() + + if toklist is None: + self._toklist = [] + elif isinstance(toklist, (list, _generator_type)): + self._toklist = ( + [toklist[:]] + if isinstance(toklist, ParseResults.List) + else list(toklist) + ) + else: + self._toklist = [toklist] + self._tokdict = dict() + return self + + # Performance tuning: we construct a *lot* of these, so keep this + # constructor as small and fast as possible + def __init__( + self, toklist=None, name=None, asList=True, modal=True, isinstance=isinstance + ) -> None: + self._tokdict: dict[str, _ParseResultsWithOffset] + self._modal = modal + + if name is None or name == "": + return + + if isinstance(name, int): + name = str(name) + + if not modal: + self._all_names = {name} + + self._name = name + + if toklist in self._null_values: + return + + if isinstance(toklist, (str_type, type)): + toklist = [toklist] + + if asList: + if isinstance(toklist, ParseResults): + self[name] = _ParseResultsWithOffset(ParseResults(toklist._toklist), 0) + else: + self[name] = _ParseResultsWithOffset(ParseResults(toklist[0]), 0) + self[name]._name = name + return + + try: + self[name] = toklist[0] + except (KeyError, TypeError, IndexError): + if toklist is not self: + self[name] = toklist + else: + self._name = name + + def __getitem__(self, i): + if isinstance(i, (int, slice)): + return self._toklist[i] + + if i not in self._all_names: + return self._tokdict[i][-1][0] + + return ParseResults([v[0] for v in self._tokdict[i]]) + + def __setitem__(self, k, v, isinstance=isinstance): + if isinstance(v, _ParseResultsWithOffset): + self._tokdict[k] = self._tokdict.get(k, list()) + [v] + sub = v[0] + elif isinstance(k, (int, slice)): + self._toklist[k] = v + sub = v + else: + self._tokdict[k] = self._tokdict.get(k, []) + [ + _ParseResultsWithOffset(v, 0) + ] + sub = v + if isinstance(sub, ParseResults): + sub._parent = self + + def __delitem__(self, i): + if not isinstance(i, (int, slice)): + del self._tokdict[i] + return + + mylen = len(self._toklist) + del self._toklist[i] + + # convert int to slice + if isinstance(i, int): + if i < 0: + i += mylen + i = slice(i, i + 1) + # get removed indices + removed = list(range(*i.indices(mylen))) + removed.reverse() + # fixup indices in token dictionary + for occurrences in self._tokdict.values(): + for j in removed: + for k, (value, position) in enumerate(occurrences): + occurrences[k] = _ParseResultsWithOffset( + value, position - (position > j) + ) + + def __contains__(self, k) -> bool: + return k in self._tokdict + + def __len__(self) -> int: + return len(self._toklist) + + def __bool__(self) -> bool: + return not not (self._toklist or self._tokdict) + + def __iter__(self) -> Iterator: + return iter(self._toklist) + + def __reversed__(self) -> Iterator: + return iter(self._toklist[::-1]) + + def keys(self): + return iter(self._tokdict) + + def values(self): + return (self[k] for k in self.keys()) + + def items(self): + return ((k, self[k]) for k in self.keys()) + + def haskeys(self) -> bool: + """ + Since ``keys()`` returns an iterator, this method is helpful in bypassing + code that looks for the existence of any defined results names.""" + return not not self._tokdict + + def pop(self, *args, **kwargs): + """ + Removes and returns item at specified index (default= ``last``). + Supports both ``list`` and ``dict`` semantics for ``pop()``. If + passed no argument or an integer argument, it will use ``list`` + semantics and pop tokens from the list of parsed tokens. If passed + a non-integer argument (most likely a string), it will use ``dict`` + semantics and pop the corresponding value from any defined results + names. A second default return value argument is supported, just as in + ``dict.pop()``. + + Example: + + .. doctest:: + + >>> numlist = Word(nums)[...] + >>> print(numlist.parse_string("0 123 321")) + ['0', '123', '321'] + + >>> def remove_first(tokens): + ... tokens.pop(0) + ... + >>> numlist.add_parse_action(remove_first) + [W:(0-9)]... + >>> print(numlist.parse_string("0 123 321")) + ['123', '321'] + + >>> label = Word(alphas) + >>> patt = label("LABEL") + Word(nums)[1, ...] + >>> print(patt.parse_string("AAB 123 321").dump()) + ['AAB', '123', '321'] + - LABEL: 'AAB' + + >>> # Use pop() in a parse action to remove named result + >>> # (note that corresponding value is not + >>> # removed from list form of results) + >>> def remove_LABEL(tokens): + ... tokens.pop("LABEL") + ... return tokens + ... + >>> patt.add_parse_action(remove_LABEL) + {W:(A-Za-z) {W:(0-9)}...} + >>> print(patt.parse_string("AAB 123 321").dump()) + ['AAB', '123', '321'] + + """ + if not args: + args = [-1] + for k, v in kwargs.items(): + if k == "default": + args = (args[0], v) + else: + raise TypeError(f"pop() got an unexpected keyword argument {k!r}") + if isinstance(args[0], int) or len(args) == 1 or args[0] in self: + index = args[0] + ret = self[index] + del self[index] + return ret + else: + defaultvalue = args[1] + return defaultvalue + + def get(self, key, default_value=None): + """ + Returns named result matching the given key, or if there is no + such name, then returns the given ``default_value`` or ``None`` if no + ``default_value`` is specified. + + Similar to ``dict.get()``. + + Example: + + .. doctest:: + + >>> integer = Word(nums) + >>> date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + >>> result = date_str.parse_string("1999/12/31") + >>> result.get("year") + '1999' + >>> result.get("hour", "not specified") + 'not specified' + >>> result.get("hour") + + """ + if key in self: + return self[key] + else: + return default_value + + def insert(self, index, ins_string): + """ + Inserts new element at location index in the list of parsed tokens. + + Similar to ``list.insert()``. + + Example: + + .. doctest:: + + >>> numlist = Word(nums)[...] + >>> print(numlist.parse_string("0 123 321")) + ['0', '123', '321'] + + >>> # use a parse action to insert the parse location + >>> # in the front of the parsed results + >>> def insert_locn(locn, tokens): + ... tokens.insert(0, locn) + ... + >>> numlist.add_parse_action(insert_locn) + [W:(0-9)]... + >>> print(numlist.parse_string("0 123 321")) + [0, '0', '123', '321'] + + """ + self._toklist.insert(index, ins_string) + # fixup indices in token dictionary + for occurrences in self._tokdict.values(): + for k, (value, position) in enumerate(occurrences): + occurrences[k] = _ParseResultsWithOffset( + value, position + (position > index) + ) + + def append(self, item): + """ + Add single element to end of ``ParseResults`` list of elements. + + Example: + + .. doctest:: + + >>> numlist = Word(nums)[...] + >>> print(numlist.parse_string("0 123 321")) + ['0', '123', '321'] + + >>> # use a parse action to compute the sum of the parsed integers, + >>> # and add it to the end + >>> def append_sum(tokens): + ... tokens.append(sum(map(int, tokens))) + ... + >>> numlist.add_parse_action(append_sum) + [W:(0-9)]... + >>> print(numlist.parse_string("0 123 321")) + ['0', '123', '321', 444] + """ + self._toklist.append(item) + + def extend(self, itemseq): + """ + Add sequence of elements to end of :class:`ParseResults` list of elements. + + Example: + + .. testcode:: + + patt = Word(alphas)[1, ...] + + # use a parse action to append the reverse of the matched strings, + # to make a palindrome + def make_palindrome(tokens): + tokens.extend(reversed([t[::-1] for t in tokens])) + return ''.join(tokens) + + patt.add_parse_action(make_palindrome) + print(patt.parse_string("lskdj sdlkjf lksd")) + + prints: + + .. testoutput:: + + ['lskdjsdlkjflksddsklfjkldsjdksl'] + """ + if isinstance(itemseq, ParseResults): + self.__iadd__(itemseq) + else: + self._toklist.extend(itemseq) + + def clear(self): + """ + Clear all elements and results names. + """ + del self._toklist[:] + self._tokdict.clear() + + def __getattr__(self, name): + try: + return self[name] + except KeyError: + if name.startswith("__"): + raise AttributeError(name) + return "" + + def __add__(self, other: ParseResults) -> ParseResults: + ret = self.copy() + ret += other + return ret + + def __iadd__(self, other: ParseResults) -> ParseResults: + if not other: + return self + + if other._tokdict: + offset = len(self._toklist) + addoffset = lambda a: offset if a < 0 else a + offset + otheritems = other._tokdict.items() + otherdictitems = [ + (k, _ParseResultsWithOffset(v[0], addoffset(v[1]))) + for k, vlist in otheritems + for v in vlist + ] + for k, v in otherdictitems: + self[k] = v + if isinstance(v[0], ParseResults): + v[0]._parent = self + + self._toklist += other._toklist + self._all_names |= other._all_names + return self + + def __radd__(self, other) -> ParseResults: + if isinstance(other, int) and other == 0: + # useful for merging many ParseResults using sum() builtin + return self.copy() + else: + # this may raise a TypeError - so be it + return other + self + + def __repr__(self) -> str: + return f"{type(self).__name__}({self._toklist!r}, {self.as_dict()})" + + def __str__(self) -> str: + return ( + "[" + + ", ".join( + [ + str(i) if isinstance(i, ParseResults) else repr(i) + for i in self._toklist + ] + ) + + "]" + ) + + def _asStringList(self, sep=""): + out = [] + for item in self._toklist: + if out and sep: + out.append(sep) + if isinstance(item, ParseResults): + out += item._asStringList() + else: + out.append(str(item)) + return out + + def as_list(self, *, flatten: bool = False) -> list: + """ + Returns the parse results as a nested list of matching tokens, all converted to strings. + If ``flatten`` is True, all the nesting levels in the returned list are collapsed. + + Example: + + .. doctest:: + + >>> patt = Word(alphas)[1, ...] + >>> result = patt.parse_string("sldkj lsdkj sldkj") + >>> # even though the result prints in string-like form, + >>> # it is actually a pyparsing ParseResults + >>> type(result) + + >>> print(result) + ['sldkj', 'lsdkj', 'sldkj'] + + .. doctest:: + + >>> # Use as_list() to create an actual list + >>> result_list = result.as_list() + >>> type(result_list) + + >>> print(result_list) + ['sldkj', 'lsdkj', 'sldkj'] + + .. versionchanged:: 3.2.0 + New ``flatten`` argument. + """ + + def flattened(pr): + to_visit = collections.deque([*self]) + while to_visit: + to_do = to_visit.popleft() + if isinstance(to_do, ParseResults): + to_visit.extendleft(to_do[::-1]) + else: + yield to_do + + if flatten: + return [*flattened(self)] + else: + return [ + res.as_list() if isinstance(res, ParseResults) else res + for res in self._toklist + ] + + def as_dict(self) -> dict: + """ + Returns the named parse results as a nested dictionary. + + Example: + + .. doctest:: + + >>> integer = pp.Word(pp.nums) + >>> date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + >>> result = date_str.parse_string('1999/12/31') + >>> type(result) + + >>> result + ParseResults(['1999', '/', '12', '/', '31'], {'year': '1999', 'month': '12', 'day': '31'}) + + >>> result_dict = result.as_dict() + >>> type(result_dict) + + >>> result_dict + {'year': '1999', 'month': '12', 'day': '31'} + + >>> # even though a ParseResults supports dict-like access, + >>> # sometime you just need to have a dict + >>> import json + >>> print(json.dumps(result)) + Traceback (most recent call last): + TypeError: Object of type ParseResults is not JSON serializable + >>> print(json.dumps(result.as_dict())) + {"year": "1999", "month": "12", "day": "31"} + """ + + def to_item(obj): + if isinstance(obj, ParseResults): + return obj.as_dict() if obj.haskeys() else [to_item(v) for v in obj] + else: + return obj + + return dict((k, to_item(v)) for k, v in self.items()) + + def copy(self) -> ParseResults: + """ + Returns a new shallow copy of a :class:`ParseResults` object. + :class:`ParseResults` items contained within the source are + shared with the copy. Use :meth:`ParseResults.deepcopy` to + create a copy with its own separate content values. + """ + ret = ParseResults(self._toklist) + ret._tokdict = self._tokdict.copy() + ret._parent = self._parent + ret._all_names |= self._all_names + ret._name = self._name + return ret + + def deepcopy(self) -> ParseResults: + """ + Returns a new deep copy of a :class:`ParseResults` object. + + .. versionadded:: 3.1.0 + """ + ret = self.copy() + # replace values with copies if they are of known mutable types + for i, obj in enumerate(self._toklist): + if isinstance(obj, ParseResults): + ret._toklist[i] = obj.deepcopy() + elif isinstance(obj, (str, bytes)): + pass + elif isinstance(obj, MutableMapping): + ret._toklist[i] = dest = type(obj)() + for k, v in obj.items(): + dest[k] = v.deepcopy() if isinstance(v, ParseResults) else v + elif isinstance(obj, Iterable): + ret._toklist[i] = type(obj)( + v.deepcopy() if isinstance(v, ParseResults) else v for v in obj # type: ignore[call-arg] + ) + return ret + + def get_name(self) -> str | None: + r""" + Returns the results name for this token expression. + + Useful when several different expressions might match + at a particular location. + + Example: + + .. testcode:: + + integer = Word(nums) + ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d") + house_number_expr = Suppress('#') + Word(nums, alphanums) + user_data = (Group(house_number_expr)("house_number") + | Group(ssn_expr)("ssn") + | Group(integer)("age")) + user_info = user_data[1, ...] + + result = user_info.parse_string("22 111-22-3333 #221B") + for item in result: + print(item.get_name(), ':', item[0]) + + prints: + + .. testoutput:: + + age : 22 + ssn : 111-22-3333 + house_number : 221B + + """ + if self._name: + return self._name + elif self._parent: + par: ParseResults = self._parent + parent_tokdict_items = par._tokdict.items() + return next( + ( + k + for k, vlist in parent_tokdict_items + for v, loc in vlist + if v is self + ), + None, + ) + elif ( + len(self) == 1 + and len(self._tokdict) == 1 + and next(iter(self._tokdict.values()))[0][1] in (0, -1) + ): + return next(iter(self._tokdict.keys())) + else: + return None + + def dump(self, indent="", full=True, include_list=True, _depth=0) -> str: + """ + Diagnostic method for listing out the contents of + a :class:`ParseResults`. Accepts an optional ``indent`` argument so + that this string can be embedded in a nested display of other data. + + Example: + + .. testcode:: + + integer = Word(nums) + date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + result = date_str.parse_string('1999/12/31') + print(result.dump()) + + prints: + + .. testoutput:: + + ['1999', '/', '12', '/', '31'] + - day: '31' + - month: '12' + - year: '1999' + """ + out = [] + NL = "\n" + out.append(indent + str(self.as_list()) if include_list else "") + + if not full: + return "".join(out) + + if self.haskeys(): + items = sorted((str(k), v) for k, v in self.items()) + for k, v in items: + if out: + out.append(NL) + out.append(f"{indent}{(' ' * _depth)}- {k}: ") + if not isinstance(v, ParseResults): + out.append(repr(v)) + continue + + if not v: + out.append(str(v)) + continue + + out.append( + v.dump( + indent=indent, + full=full, + include_list=include_list, + _depth=_depth + 1, + ) + ) + if not any(isinstance(vv, ParseResults) for vv in self): + return "".join(out) + + v = self + incr = " " + nl = "\n" + for i, vv in enumerate(v): + if isinstance(vv, ParseResults): + vv_dump = vv.dump( + indent=indent, + full=full, + include_list=include_list, + _depth=_depth + 1, + ) + out.append( + f"{nl}{indent}{incr * _depth}[{i}]:{nl}{indent}{incr * (_depth + 1)}{vv_dump}" + ) + else: + out.append( + f"{nl}{indent}{incr * _depth}[{i}]:{nl}{indent}{incr * (_depth + 1)}{vv}" + ) + + return "".join(out) + + def pprint(self, *args, **kwargs): + """ + Pretty-printer for parsed results as a list, using the + `pprint `_ module. + Accepts additional positional or keyword args as defined for + `pprint.pprint `_ . + + Example: + + .. testcode:: + + ident = Word(alphas, alphanums) + num = Word(nums) + func = Forward() + term = ident | num | Group('(' + func + ')') + func <<= ident + Group(Optional(DelimitedList(term))) + result = func.parse_string("fna a,b,(fnb c,d,200),100") + result.pprint(width=40) + + prints: + + .. testoutput:: + + ['fna', + ['a', + 'b', + ['(', 'fnb', ['c', 'd', '200'], ')'], + '100']] + """ + pprint.pprint(self.as_list(), *args, **kwargs) + + # add support for pickle protocol + def __getstate__(self): + return ( + self._toklist, + ( + self._tokdict.copy(), + None, + self._all_names, + self._name, + ), + ) + + def __setstate__(self, state): + self._toklist, (self._tokdict, par, inAccumNames, self._name) = state + self._all_names = set(inAccumNames) + self._parent = None + + def __getnewargs__(self): + return self._toklist, self._name + + def __dir__(self): + return dir(type(self)) + list(self.keys()) + + @classmethod + def from_dict(cls, other, name=None) -> ParseResults: + """ + Helper classmethod to construct a :class:`ParseResults` from a ``dict``, preserving the + name-value relations as results names. If an optional ``name`` argument is + given, a nested :class:`ParseResults` will be returned. + """ + + def is_iterable(obj): + try: + iter(obj) + except Exception: + return False + # str's are iterable, but in pyparsing, we don't want to iterate over them + else: + return not isinstance(obj, str_type) + + ret = cls([]) + for k, v in other.items(): + if isinstance(v, Mapping): + ret += cls.from_dict(v, name=k) + else: + ret += cls([v], name=k, asList=is_iterable(v)) + if name is not None: + ret = cls([ret], name=name) + return ret + + asList = as_list + """ + .. deprecated:: 3.0.0 + use :meth:`as_list` + """ + asDict = as_dict + """ + .. deprecated:: 3.0.0 + use :meth:`as_dict` + """ + getName = get_name + """ + .. deprecated:: 3.0.0 + use :meth:`get_name` + """ + + +MutableMapping.register(ParseResults) +MutableSequence.register(ParseResults) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/testing.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..7def5d37b87140abbd0d638b18411fd7c45c24ee --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/testing.py @@ -0,0 +1,388 @@ +# testing.py + +from contextlib import contextmanager +import re +import typing + + +from .core import ( + ParserElement, + ParseException, + Keyword, + __diag__, + __compat__, +) + + +class pyparsing_test: + """ + namespace class for classes useful in writing unit tests + """ + + class reset_pyparsing_context: + """ + Context manager to be used when writing unit tests that modify pyparsing config values: + - packrat parsing + - bounded recursion parsing + - default whitespace characters + - default keyword characters + - literal string auto-conversion class + - ``__diag__`` settings + + Example: + + .. testcode:: + + ppt = pyparsing.pyparsing_test + + class MyTestClass(ppt.TestParseResultsAsserts): + def test_literal(self): + with ppt.reset_pyparsing_context(): + # test that literals used to construct + # a grammar are automatically suppressed + ParserElement.inline_literals_using(Suppress) + + term = Word(alphas) | Word(nums) + group = Group('(' + term[...] + ')') + + # assert that the '()' characters + # are not included in the parsed tokens + self.assertParseAndCheckList( + group, + "(abc 123 def)", + ['abc', '123', 'def'] + ) + + # after exiting context manager, literals + # are converted to Literal expressions again + """ + + def __init__(self): + self._save_context = {} + + def save(self): + self._save_context["default_whitespace"] = ParserElement.DEFAULT_WHITE_CHARS + self._save_context["default_keyword_chars"] = Keyword.DEFAULT_KEYWORD_CHARS + + self._save_context["literal_string_class"] = ( + ParserElement._literalStringClass + ) + + self._save_context["verbose_stacktrace"] = ParserElement.verbose_stacktrace + + self._save_context["packrat_enabled"] = ParserElement._packratEnabled + if ParserElement._packratEnabled: + self._save_context["packrat_cache_size"] = ( + ParserElement.packrat_cache.size + ) + else: + self._save_context["packrat_cache_size"] = None + self._save_context["packrat_parse"] = ParserElement._parse + self._save_context["recursion_enabled"] = ( + ParserElement._left_recursion_enabled + ) + + self._save_context["__diag__"] = { + name: getattr(__diag__, name) for name in __diag__._all_names + } + + self._save_context["__compat__"] = { + "collect_all_And_tokens": __compat__.collect_all_And_tokens + } + + return self + + def restore(self): + # reset pyparsing global state + if ( + ParserElement.DEFAULT_WHITE_CHARS + != self._save_context["default_whitespace"] + ): + ParserElement.set_default_whitespace_chars( + self._save_context["default_whitespace"] + ) + + ParserElement.verbose_stacktrace = self._save_context["verbose_stacktrace"] + + Keyword.DEFAULT_KEYWORD_CHARS = self._save_context["default_keyword_chars"] + ParserElement.inlineLiteralsUsing( + self._save_context["literal_string_class"] + ) + + for name, value in self._save_context["__diag__"].items(): + (__diag__.enable if value else __diag__.disable)(name) + + ParserElement._packratEnabled = False + if self._save_context["packrat_enabled"]: + ParserElement.enable_packrat(self._save_context["packrat_cache_size"]) + else: + ParserElement._parse = self._save_context["packrat_parse"] + ParserElement._left_recursion_enabled = self._save_context[ + "recursion_enabled" + ] + + __compat__.collect_all_And_tokens = self._save_context["__compat__"] + + return self + + def copy(self): + ret = type(self)() + ret._save_context.update(self._save_context) + return ret + + def __enter__(self): + return self.save() + + def __exit__(self, *args): + self.restore() + + class TestParseResultsAsserts: + """ + A mixin class to add parse results assertion methods to normal unittest.TestCase classes. + """ + + def assertParseResultsEquals( + self, result, expected_list=None, expected_dict=None, msg=None + ): + """ + Unit test assertion to compare a :class:`ParseResults` object with an optional ``expected_list``, + and compare any defined results names with an optional ``expected_dict``. + """ + if expected_list is not None: + self.assertEqual(expected_list, result.as_list(), msg=msg) + if expected_dict is not None: + self.assertEqual(expected_dict, result.as_dict(), msg=msg) + + def assertParseAndCheckList( + self, expr, test_string, expected_list, msg=None, verbose=True + ): + """ + Convenience wrapper assert to test a parser element and input string, and assert that + the resulting :meth:`ParseResults.as_list` is equal to the ``expected_list``. + """ + result = expr.parse_string(test_string, parse_all=True) + if verbose: + print(result.dump()) + else: + print(result.as_list()) + self.assertParseResultsEquals(result, expected_list=expected_list, msg=msg) + + def assertParseAndCheckDict( + self, expr, test_string, expected_dict, msg=None, verbose=True + ): + """ + Convenience wrapper assert to test a parser element and input string, and assert that + the resulting :meth:`ParseResults.as_dict` is equal to the ``expected_dict``. + """ + result = expr.parse_string(test_string, parseAll=True) + if verbose: + print(result.dump()) + else: + print(result.as_list()) + self.assertParseResultsEquals(result, expected_dict=expected_dict, msg=msg) + + def assertRunTestResults( + self, run_tests_report, expected_parse_results=None, msg=None + ): + """ + Unit test assertion to evaluate output of + :meth:`~ParserElement.run_tests`. + + If a list of list-dict tuples is given as the + ``expected_parse_results`` argument, then these are zipped + with the report tuples returned by ``run_tests()`` + and evaluated using :meth:`assertParseResultsEquals`. + Finally, asserts that the overall + `:meth:~ParserElement.run_tests` success value is ``True``. + + :param run_tests_report: the return value from :meth:`ParserElement.run_tests` + :type run_tests_report: tuple[bool, list[tuple[str, ParseResults | Exception]]] + :param expected_parse_results: (optional) + :type expected_parse_results: list[tuple[str | list | dict | Exception, ...]] + """ + run_test_success, run_test_results = run_tests_report + + if expected_parse_results is None: + self.assertTrue( + run_test_success, msg=msg if msg is not None else "failed runTests" + ) + return + + merged = [ + (*rpt, expected) + for rpt, expected in zip(run_test_results, expected_parse_results) + ] + for test_string, result, expected in merged: + # expected should be a tuple containing a list and/or a dict or an exception, + # and optional failure message string + # an empty tuple will skip any result validation + fail_msg = next((exp for exp in expected if isinstance(exp, str)), None) + expected_exception = next( + ( + exp + for exp in expected + if isinstance(exp, type) and issubclass(exp, Exception) + ), + None, + ) + if expected_exception is not None: + with self.assertRaises( + expected_exception=expected_exception, msg=fail_msg or msg + ): + if isinstance(result, Exception): + raise result + else: + expected_list = next( + (exp for exp in expected if isinstance(exp, list)), None + ) + expected_dict = next( + (exp for exp in expected if isinstance(exp, dict)), None + ) + if (expected_list, expected_dict) != (None, None): + self.assertParseResultsEquals( + result, + expected_list=expected_list, + expected_dict=expected_dict, + msg=fail_msg or msg, + ) + else: + # warning here maybe? + print(f"no validation for {test_string!r}") + + # do this last, in case some specific test results can be reported instead + self.assertTrue( + run_test_success, msg=msg if msg is not None else "failed runTests" + ) + + @contextmanager + def assertRaisesParseException( + self, exc_type=ParseException, expected_msg=None, msg=None + ): + if expected_msg is not None: + if isinstance(expected_msg, str): + expected_msg = re.escape(expected_msg) + with self.assertRaisesRegex(exc_type, expected_msg, msg=msg) as ctx: + yield ctx + + else: + with self.assertRaises(exc_type, msg=msg) as ctx: + yield ctx + + @staticmethod + def with_line_numbers( + s: str, + start_line: typing.Optional[int] = None, + end_line: typing.Optional[int] = None, + expand_tabs: bool = True, + eol_mark: str = "|", + mark_spaces: typing.Optional[str] = None, + mark_control: typing.Optional[str] = None, + *, + indent: typing.Union[str, int] = "", + base_1: bool = True, + ) -> str: + """ + Helpful method for debugging a parser - prints a string with line and column numbers. + (Line and column numbers are 1-based by default - if debugging a parse action, + pass base_1=False, to correspond to the loc value passed to the parse action.) + + :param s: string to be printed with line and column numbers + :param start_line: starting line number in s to print (default=1) + :param end_line: ending line number in s to print (default=len(s)) + :param expand_tabs: expand tabs to spaces, to match the pyparsing default + :param eol_mark: string to mark the end of lines, helps visualize trailing spaces + :param mark_spaces: special character to display in place of spaces + :param mark_control: convert non-printing control characters to a placeholding + character; valid values: + + - ``"unicode"`` - replaces control chars with Unicode symbols, such as "␍" and "␊" + - any single character string - replace control characters with given string + - ``None`` (default) - string is displayed as-is + + + :param indent: string to indent with line and column numbers; if an int + is passed, converted to ``" " * indent`` + :param base_1: whether to label string using base 1; if False, string will be + labeled based at 0 + + :returns: input string with leading line numbers and column number headers + + .. versionchanged:: 3.2.0 + New ``indent`` and ``base_1`` arguments. + """ + if expand_tabs: + s = s.expandtabs() + if isinstance(indent, int): + indent = " " * indent + indent = indent.expandtabs() + if mark_control is not None: + mark_control = typing.cast(str, mark_control) + if mark_control == "unicode": + transtable_map = { + c: u for c, u in zip(range(0, 33), range(0x2400, 0x2433)) + } + transtable_map[127] = 0x2421 + tbl = str.maketrans(transtable_map) + eol_mark = "" + else: + ord_mark_control = ord(mark_control) + tbl = str.maketrans( + {c: ord_mark_control for c in list(range(0, 32)) + [127]} + ) + s = s.translate(tbl) + if mark_spaces is not None and mark_spaces != " ": + if mark_spaces == "unicode": + tbl = str.maketrans({9: 0x2409, 32: 0x2423}) + s = s.translate(tbl) + else: + s = s.replace(" ", mark_spaces) + if start_line is None: + start_line = 0 + if end_line is None: + end_line = len(s) + end_line = min(end_line, len(s)) + start_line = min(max(0, start_line), end_line) + + if mark_control != "unicode": + s_lines = s.splitlines()[start_line - base_1 : end_line] + else: + s_lines = [ + line + "␊" for line in s.split("␊")[start_line - base_1 : end_line] + ] + if not s_lines: + return "" + + lineno_width = len(str(end_line)) + max_line_len = max(len(line) for line in s_lines) + lead = indent + " " * (lineno_width + 1) + if max_line_len >= 99: + header0 = ( + lead + + ("" if base_1 else " ") + + "".join( + f"{' ' * 99}{(i + 1) % 100}" + for i in range(1 if base_1 else 0, max(max_line_len // 100, 1)) + ) + + "\n" + ) + else: + header0 = "" + header1 = ( + ("" if base_1 else " ") + + lead + + "".join(f" {(i + 1) % 10}" for i in range(-(-max_line_len // 10))) + + "\n" + ) + digits = "1234567890" + header2 = ( + lead + ("" if base_1 else "0") + digits * (-(-max_line_len // 10)) + "\n" + ) + return ( + header1 + + header2 + + "\n".join( + f"{indent}{i:{lineno_width}d}:{line}{eol_mark}" + for i, line in enumerate(s_lines, start=start_line + base_1) + ) + + "\n" + ) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/tools/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/tools/cvt_pyparsing_pep8_names.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/tools/cvt_pyparsing_pep8_names.py new file mode 100644 index 0000000000000000000000000000000000000000..f4a8bd9f516994ce6b9734ca07c5895bb8276fd4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/tools/cvt_pyparsing_pep8_names.py @@ -0,0 +1,116 @@ +from functools import lru_cache +import pyparsing as pp + + +@lru_cache(maxsize=None) +def camel_to_snake(s: str) -> str: + """ + Convert CamelCase to snake_case. + """ + return "".join("_" + c.lower() if c.isupper() else c for c in s).lstrip("_") + + +pre_pep8_method_names = """ +addCondition addParseAction anyCloseTag anyOpenTag asDict asList cStyleComment canParseNext conditionAsParseAction +convertToDate convertToDatetime convertToFloat convertToInteger countedArray cppStyleComment dblQuotedString +dblSlashComment defaultName dictOf disableMemoization downcaseTokens enableLeftRecursion enablePackrat getName +htmlComment ignoreWhitespace indentedBlock infixNotation inlineLiteralsUsing javaStyleComment leaveWhitespace +lineEnd lineStart locatedExpr matchOnlyAtCol matchPreviousExpr matchPreviousLiteral nestedExpr nullDebugAction oneOf +originalTextFor parseFile parseString parseWithTabs pythonStyleComment quotedString removeQuotes replaceWith +resetCache restOfLine runTests scanString searchString setBreak setDebug setDebugActions setDefaultWhitespaceChars +setFailAction setName setParseAction setResultsName setWhitespaceChars sglQuotedString stringEnd stringStart tokenMap +traceParseAction transformString tryParse unicodeString upcaseTokens withAttribute withClass +""".split() + +special_changes = { + "opAssoc": "OpAssoc", + "delimitedList": "DelimitedList", + "delimited_list": "DelimitedList", + "replaceHTMLEntity": "replace_html_entity", + "makeHTMLTags": "make_html_tags", + "makeXMLTags": "make_xml_tags", + "commonHTMLEntity": "common_html_entity", + "stripHTMLTags": "strip_html_tags", +} + +pre_pep8_arg_names = """parseAll maxMatches listAllMatches callDuringTry includeSeparators fullDump printResults +failureTests postParse matchString identChars maxMismatches initChars bodyChars asKeyword excludeChars asGroupList +asMatch quoteChar escChar escQuote unquoteResults endQuoteChar convertWhitespaceEscapes notChars wordChars stopOn +failOn joinString markerString intExpr useRegex asString ignoreExpr""".split() + +pre_pep8_method_name = pp.one_of(pre_pep8_method_names, as_keyword=True) +pre_pep8_method_name.set_parse_action(lambda t: camel_to_snake(t[0])) +special_pre_pep8_name = pp.one_of(special_changes, as_keyword=True) +special_pre_pep8_name.set_parse_action(lambda t: special_changes[t[0]]) +# only replace arg names if part of an arg list +pre_pep8_arg_name = pp.Regex( + rf"{pp.util.make_compressed_re(pre_pep8_arg_names)}\s*=" +) +pre_pep8_arg_name.set_parse_action(lambda t: camel_to_snake(t[0])) + +pep8_converter = pre_pep8_method_name | special_pre_pep8_name | pre_pep8_arg_name + +if __name__ == "__main__": + import argparse + from pathlib import Path + import sys + + argparser = argparse.ArgumentParser( + description = ( + "Utility to convert Python pyparsing scripts using legacy" + " camelCase names to use PEP8 snake_case names." + "\nBy default, this script will only show whether this script would make any changes." + ) + ) + argparser.add_argument("--verbose", "-v", action="store_true", help="Show unified diff for each source file") + argparser.add_argument("-vv", action="store_true", dest="verbose2", help="Show unified diff for each source file, plus names of scanned files with no changes") + argparser.add_argument("--update", "-u", action="store_true", help="Update source files in-place") + argparser.add_argument("--encoding", type=str, default="utf-8", help="Encoding of source files (default: utf-8)") + argparser.add_argument("--exit-zero-even-if-changed", "-exit0", action="store_true", help="Exit with status code 0 even if changes were made") + argparser.add_argument("source_filename", nargs="+", help="Source filenames or filename patterns of Python files to be converted") + args = argparser.parse_args() + + + def show_diffs(original, modified): + import difflib + + diff = difflib.unified_diff( + original.splitlines(), modified.splitlines(), lineterm="" + ) + sys.stdout.writelines(f"{diff_line}\n" for diff_line in diff) + + exit_status = 0 + + for filename_pattern in args.source_filename: + + for filename in Path().glob(filename_pattern): + if not Path(filename).is_file(): + continue + + try: + original_contents = Path(filename).read_text(encoding=args.encoding) + modified_contents = pep8_converter.transform_string( + original_contents + ) + + if modified_contents != original_contents: + if args.update: + Path(filename).write_text(modified_contents, encoding=args.encoding) + print(f"Converted {filename}") + else: + print(f"Found required changes in {filename}") + + if args.verbose: + show_diffs(original_contents, modified_contents) + print() + + exit_status = 1 + + else: + if args.verbose2: + print(f"No required changes in {filename}") + + except Exception as e: + print(f"Failed to convert {filename}: {type(e).__name__}: {e}") + + sys.exit(exit_status if not args.exit_zero_even_if_changed else 0) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/unicode.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/unicode.py new file mode 100644 index 0000000000000000000000000000000000000000..066486c28eea020d420c2e90fdda76f69f1c9ead --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/unicode.py @@ -0,0 +1,356 @@ +# unicode.py + +import sys +from itertools import filterfalse +from typing import Union + + +class _lazyclassproperty: + def __init__(self, fn): + self.fn = fn + self.__doc__ = fn.__doc__ + self.__name__ = fn.__name__ + + def __get__(self, obj, cls): + if cls is None: + cls = type(obj) + if not hasattr(cls, "_intern") or any( + cls._intern is getattr(superclass, "_intern", []) + for superclass in cls.__mro__[1:] + ): + cls._intern = {} + attrname = self.fn.__name__ + if attrname not in cls._intern: + cls._intern[attrname] = self.fn(cls) + return cls._intern[attrname] + + +UnicodeRangeList = list[Union[tuple[int, int], tuple[int]]] + + +class unicode_set: + """ + A set of Unicode characters, for language-specific strings for + ``alphas``, ``nums``, ``alphanums``, and ``printables``. + A unicode_set is defined by a list of ranges in the Unicode character + set, in a class attribute ``_ranges``. Ranges can be specified using + 2-tuples or a 1-tuple, such as:: + + _ranges = [ + (0x0020, 0x007e), + (0x00a0, 0x00ff), + (0x0100,), + ] + + Ranges are left- and right-inclusive. A 1-tuple of (x,) is treated as (x, x). + + A unicode set can also be defined using multiple inheritance of other unicode sets:: + + class CJK(Chinese, Japanese, Korean): + pass + """ + + _ranges: UnicodeRangeList = [] + + @_lazyclassproperty + def _chars_for_ranges(cls) -> list[str]: + ret: list[int] = [] + for cc in cls.__mro__: # type: ignore[attr-defined] + if cc is unicode_set: + break + for rr in getattr(cc, "_ranges", ()): + ret.extend(range(rr[0], rr[-1] + 1)) + return sorted(chr(c) for c in set(ret)) + + @_lazyclassproperty + def printables(cls) -> str: + """all non-whitespace characters in this range""" + return "".join(filterfalse(str.isspace, cls._chars_for_ranges)) + + @_lazyclassproperty + def alphas(cls) -> str: + """all alphabetic characters in this range""" + return "".join(filter(str.isalpha, cls._chars_for_ranges)) + + @_lazyclassproperty + def nums(cls) -> str: + """all numeric digit characters in this range""" + return "".join(filter(str.isdigit, cls._chars_for_ranges)) + + @_lazyclassproperty + def alphanums(cls) -> str: + """all alphanumeric characters in this range""" + return cls.alphas + cls.nums + + @_lazyclassproperty + def identchars(cls) -> str: + """all characters in this range that are valid identifier characters, plus underscore '_'""" + return "".join( + sorted( + set(filter(str.isidentifier, cls._chars_for_ranges)) + | set( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzªµº" + "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ" + "_" + ) + ) + ) + + @_lazyclassproperty + def identbodychars(cls) -> str: + """ + all characters in this range that are valid identifier body characters, + plus the digits 0-9, and · (Unicode MIDDLE DOT) + """ + identifier_chars = set( + c for c in cls._chars_for_ranges if ("_" + c).isidentifier() + ) + return "".join( + sorted(identifier_chars | set(cls.identchars) | set("0123456789·")) + ) + + @_lazyclassproperty + def identifier(cls): + """ + a pyparsing Word expression for an identifier using this range's definitions for + identchars and identbodychars + """ + from pyparsing import Word + + return Word(cls.identchars, cls.identbodychars) + + +class pyparsing_unicode(unicode_set): + """ + A namespace class for defining common language unicode_sets. + """ + + # fmt: off + + # define ranges in language character sets + _ranges: UnicodeRangeList = [ + (0x0020, sys.maxunicode), + ] + + class BasicMultilingualPlane(unicode_set): + """Unicode set for the Basic Multilingual Plane""" + _ranges: UnicodeRangeList = [ + (0x0020, 0xFFFF), + ] + + class Latin1(unicode_set): + """Unicode set for Latin-1 Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0020, 0x007E), + (0x00A0, 0x00FF), + ] + + class LatinA(unicode_set): + """Unicode set for Latin-A Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0100, 0x017F), + ] + + class LatinB(unicode_set): + """Unicode set for Latin-B Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0180, 0x024F), + ] + + class Greek(unicode_set): + """Unicode set for Greek Unicode Character Ranges""" + _ranges: UnicodeRangeList = [ + (0x0342, 0x0345), + (0x0370, 0x0377), + (0x037A, 0x037F), + (0x0384, 0x038A), + (0x038C,), + (0x038E, 0x03A1), + (0x03A3, 0x03E1), + (0x03F0, 0x03FF), + (0x1D26, 0x1D2A), + (0x1D5E,), + (0x1D60,), + (0x1D66, 0x1D6A), + (0x1F00, 0x1F15), + (0x1F18, 0x1F1D), + (0x1F20, 0x1F45), + (0x1F48, 0x1F4D), + (0x1F50, 0x1F57), + (0x1F59,), + (0x1F5B,), + (0x1F5D,), + (0x1F5F, 0x1F7D), + (0x1F80, 0x1FB4), + (0x1FB6, 0x1FC4), + (0x1FC6, 0x1FD3), + (0x1FD6, 0x1FDB), + (0x1FDD, 0x1FEF), + (0x1FF2, 0x1FF4), + (0x1FF6, 0x1FFE), + (0x2129,), + (0x2719, 0x271A), + (0xAB65,), + (0x10140, 0x1018D), + (0x101A0,), + (0x1D200, 0x1D245), + (0x1F7A1, 0x1F7A7), + ] + + class Cyrillic(unicode_set): + """Unicode set for Cyrillic Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0400, 0x052F), + (0x1C80, 0x1C88), + (0x1D2B,), + (0x1D78,), + (0x2DE0, 0x2DFF), + (0xA640, 0xA672), + (0xA674, 0xA69F), + (0xFE2E, 0xFE2F), + ] + + class Chinese(unicode_set): + """Unicode set for Chinese Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x2E80, 0x2E99), + (0x2E9B, 0x2EF3), + (0x31C0, 0x31E3), + (0x3400, 0x4DB5), + (0x4E00, 0x9FEF), + (0xA700, 0xA707), + (0xF900, 0xFA6D), + (0xFA70, 0xFAD9), + (0x16FE2, 0x16FE3), + (0x1F210, 0x1F212), + (0x1F214, 0x1F23B), + (0x1F240, 0x1F248), + (0x20000, 0x2A6D6), + (0x2A700, 0x2B734), + (0x2B740, 0x2B81D), + (0x2B820, 0x2CEA1), + (0x2CEB0, 0x2EBE0), + (0x2F800, 0x2FA1D), + ] + + class Japanese(unicode_set): + """Unicode set for Japanese Unicode Character Range, combining Kanji, Hiragana, and Katakana ranges""" + + class Kanji(unicode_set): + "Unicode set for Kanji Unicode Character Range" + _ranges: UnicodeRangeList = [ + (0x4E00, 0x9FBF), + (0x3000, 0x303F), + ] + + class Hiragana(unicode_set): + """Unicode set for Hiragana Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x3041, 0x3096), + (0x3099, 0x30A0), + (0x30FC,), + (0xFF70,), + (0x1B001,), + (0x1B150, 0x1B152), + (0x1F200,), + ] + + class Katakana(unicode_set): + """Unicode set for Katakana Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x3099, 0x309C), + (0x30A0, 0x30FF), + (0x31F0, 0x31FF), + (0x32D0, 0x32FE), + (0xFF65, 0xFF9F), + (0x1B000,), + (0x1B164, 0x1B167), + (0x1F201, 0x1F202), + (0x1F213,), + ] + + 漢字 = Kanji + カタカナ = Katakana + ひらがな = Hiragana + + _ranges = ( + Kanji._ranges + + Hiragana._ranges + + Katakana._ranges + ) + + class Hangul(unicode_set): + """Unicode set for Hangul (Korean) Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x1100, 0x11FF), + (0x302E, 0x302F), + (0x3131, 0x318E), + (0x3200, 0x321C), + (0x3260, 0x327B), + (0x327E,), + (0xA960, 0xA97C), + (0xAC00, 0xD7A3), + (0xD7B0, 0xD7C6), + (0xD7CB, 0xD7FB), + (0xFFA0, 0xFFBE), + (0xFFC2, 0xFFC7), + (0xFFCA, 0xFFCF), + (0xFFD2, 0xFFD7), + (0xFFDA, 0xFFDC), + ] + + Korean = Hangul + + class CJK(Chinese, Japanese, Hangul): + """Unicode set for combined Chinese, Japanese, and Korean (CJK) Unicode Character Range""" + + class Thai(unicode_set): + """Unicode set for Thai Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0E01, 0x0E3A), + (0x0E3F, 0x0E5B) + ] + + class Arabic(unicode_set): + """Unicode set for Arabic Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0600, 0x061B), + (0x061E, 0x06FF), + (0x0700, 0x077F), + ] + + class Hebrew(unicode_set): + """Unicode set for Hebrew Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0591, 0x05C7), + (0x05D0, 0x05EA), + (0x05EF, 0x05F4), + (0xFB1D, 0xFB36), + (0xFB38, 0xFB3C), + (0xFB3E,), + (0xFB40, 0xFB41), + (0xFB43, 0xFB44), + (0xFB46, 0xFB4F), + ] + + class Devanagari(unicode_set): + """Unicode set for Devanagari Unicode Character Range""" + _ranges: UnicodeRangeList = [ + (0x0900, 0x097F), + (0xA8E0, 0xA8FF) + ] + + BMP = BasicMultilingualPlane + + # add language identifiers using language Unicode + العربية = Arabic + 中文 = Chinese + кириллица = Cyrillic + Ελληνικά = Greek + עִברִית = Hebrew + 日本語 = Japanese + 한국어 = Korean + ไทย = Thai + देवनागरी = Devanagari + + # fmt: on diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/util.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/util.py new file mode 100644 index 0000000000000000000000000000000000000000..7909240bbd16c6507ab9bd09de2064106c0f2eca --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/pyparsing/util.py @@ -0,0 +1,460 @@ +# util.py +import contextlib +import re +from functools import lru_cache, wraps +import inspect +import itertools +import types +from typing import Callable, Union, Iterable, TypeVar, cast +import warnings + +_bslash = chr(92) +C = TypeVar("C", bound=Callable) + + +class __config_flags: + """Internal class for defining compatibility and debugging flags""" + + _all_names: list[str] = [] + _fixed_names: list[str] = [] + _type_desc = "configuration" + + @classmethod + def _set(cls, dname, value): + if dname in cls._fixed_names: + warnings.warn( + f"{cls.__name__}.{dname} {cls._type_desc} is {str(getattr(cls, dname)).upper()}" + f" and cannot be overridden", + stacklevel=3, + ) + return + if dname in cls._all_names: + setattr(cls, dname, value) + else: + raise ValueError(f"no such {cls._type_desc} {dname!r}") + + enable = classmethod(lambda cls, name: cls._set(name, True)) + disable = classmethod(lambda cls, name: cls._set(name, False)) + + +@lru_cache(maxsize=128) +def col(loc: int, strg: str) -> int: + """ + Returns current column within a string, counting newlines as line separators. + The first column is number 1. + + Note: the default parsing behavior is to expand tabs in the input string + before starting the parsing process. See + :meth:`ParserElement.parse_string` for more + information on parsing strings containing ```` s, and suggested + methods to maintain a consistent view of the parsed string, the parse + location, and line and column positions within the parsed string. + """ + s = strg + return 1 if 0 < loc < len(s) and s[loc - 1] == "\n" else loc - s.rfind("\n", 0, loc) + + +@lru_cache(maxsize=128) +def lineno(loc: int, strg: str) -> int: + """Returns current line number within a string, counting newlines as line separators. + The first line is number 1. + + Note - the default parsing behavior is to expand tabs in the input string + before starting the parsing process. See :meth:`ParserElement.parse_string` + for more information on parsing strings containing ```` s, and + suggested methods to maintain a consistent view of the parsed string, the + parse location, and line and column positions within the parsed string. + """ + return strg.count("\n", 0, loc) + 1 + + +@lru_cache(maxsize=128) +def line(loc: int, strg: str) -> str: + """ + Returns the line of text containing loc within a string, counting newlines as line separators. + """ + last_cr = strg.rfind("\n", 0, loc) + next_cr = strg.find("\n", loc) + return strg[last_cr + 1 : next_cr] if next_cr >= 0 else strg[last_cr + 1 :] + + +class _UnboundedCache: + def __init__(self): + cache = {} + cache_get = cache.get + self.not_in_cache = not_in_cache = object() + + def get(_, key): + return cache_get(key, not_in_cache) + + def set_(_, key, value): + cache[key] = value + + def clear(_): + cache.clear() + + self.size = None + self.get = types.MethodType(get, self) + self.set = types.MethodType(set_, self) + self.clear = types.MethodType(clear, self) + + +class _FifoCache: + def __init__(self, size): + cache = {} + self.size = size + self.not_in_cache = not_in_cache = object() + cache_get = cache.get + cache_pop = cache.pop + + def get(_, key): + return cache_get(key, not_in_cache) + + def set_(_, key, value): + cache[key] = value + while len(cache) > size: + # pop oldest element in cache by getting the first key + cache_pop(next(iter(cache))) + + def clear(_): + cache.clear() + + self.get = types.MethodType(get, self) + self.set = types.MethodType(set_, self) + self.clear = types.MethodType(clear, self) + + +class LRUMemo: + """ + A memoizing mapping that retains `capacity` deleted items + + The memo tracks retained items by their access order; once `capacity` items + are retained, the least recently used item is discarded. + """ + + def __init__(self, capacity): + self._capacity = capacity + self._active = {} + self._memory = {} + + def __getitem__(self, key): + try: + return self._active[key] + except KeyError: + self._memory[key] = self._memory.pop(key) + return self._memory[key] + + def __setitem__(self, key, value): + self._memory.pop(key, None) + self._active[key] = value + + def __delitem__(self, key): + try: + value = self._active.pop(key) + except KeyError: + pass + else: + oldest_keys = list(self._memory)[: -(self._capacity + 1)] + for key_to_delete in oldest_keys: + self._memory.pop(key_to_delete) + self._memory[key] = value + + def clear(self): + self._active.clear() + self._memory.clear() + + +class UnboundedMemo(dict): + """ + A memoizing mapping that retains all deleted items + """ + + def __delitem__(self, key): + pass + + +def _escape_regex_range_chars(s: str) -> str: + # escape these chars: ^-[] + for c in r"\^-[]": + s = s.replace(c, _bslash + c) + s = s.replace("\n", r"\n") + s = s.replace("\t", r"\t") + return str(s) + + +class _GroupConsecutive: + """ + Used as a callable `key` for itertools.groupby to group + characters that are consecutive: + + .. testcode:: + + from itertools import groupby + from pyparsing.util import _GroupConsecutive + + grouped = groupby("abcdejkmpqrs", key=_GroupConsecutive()) + for index, group in grouped: + print(tuple([index, list(group)])) + + prints: + + .. testoutput:: + + (0, ['a', 'b', 'c', 'd', 'e']) + (1, ['j', 'k']) + (2, ['m']) + (3, ['p', 'q', 'r', 's']) + """ + + def __init__(self) -> None: + self.prev = 0 + self.counter = itertools.count() + self.value = -1 + + def __call__(self, char: str) -> int: + c_int = ord(char) + self.prev, prev = c_int, self.prev + if c_int - prev > 1: + self.value = next(self.counter) + return self.value + + +def _collapse_string_to_ranges( + s: Union[str, Iterable[str]], re_escape: bool = True +) -> str: + r""" + Take a string or list of single-character strings, and return + a string of the consecutive characters in that string collapsed + into groups, as might be used in a regular expression '[a-z]' + character set:: + + 'a' -> 'a' -> '[a]' + 'bc' -> 'bc' -> '[bc]' + 'defgh' -> 'd-h' -> '[d-h]' + 'fdgeh' -> 'd-h' -> '[d-h]' + 'jklnpqrtu' -> 'j-lnp-rtu' -> '[j-lnp-rtu]' + + Duplicates get collapsed out:: + + 'aaa' -> 'a' -> '[a]' + 'bcbccb' -> 'bc' -> '[bc]' + 'defghhgf' -> 'd-h' -> '[d-h]' + 'jklnpqrjjjtu' -> 'j-lnp-rtu' -> '[j-lnp-rtu]' + + Spaces are preserved:: + + 'ab c' -> ' a-c' -> '[ a-c]' + + Characters that are significant when defining regex ranges + get escaped:: + + 'acde[]-' -> r'\-\[\]ac-e' -> r'[\-\[\]ac-e]' + """ + + # Developer notes: + # - Do not optimize this code assuming that the given input string + # or internal lists will be short (such as in loading generators into + # lists to make it easier to find the last element); this method is also + # used to generate regex ranges for character sets in the pyparsing.unicode + # classes, and these can be _very_ long lists of strings + + def escape_re_range_char(c: str) -> str: + return "\\" + c if c in r"\^-][" else c + + def no_escape_re_range_char(c: str) -> str: + return c + + if not re_escape: + escape_re_range_char = no_escape_re_range_char + + ret = [] + + # reduce input string to remove duplicates, and put in sorted order + s_chars: list[str] = sorted(set(s)) + + if len(s_chars) > 2: + # find groups of characters that are consecutive (can be collapsed + # down to "-") + for _, chars in itertools.groupby(s_chars, key=_GroupConsecutive()): + # _ is unimportant, is just used to identify groups + # chars is an iterator of one or more consecutive characters + # that comprise the current group + first = last = next(chars) + with contextlib.suppress(ValueError): + *_, last = chars + + if first == last: + # there was only a single char in this group + ret.append(escape_re_range_char(first)) + + elif last == chr(ord(first) + 1): + # there were only 2 characters in this group + # 'a','b' -> 'ab' + ret.append(f"{escape_re_range_char(first)}{escape_re_range_char(last)}") + + else: + # there were > 2 characters in this group, make into a range + # 'c','d','e' -> 'c-e' + ret.append( + f"{escape_re_range_char(first)}-{escape_re_range_char(last)}" + ) + else: + # only 1 or 2 chars were given to form into groups + # 'a' -> ['a'] + # 'bc' -> ['b', 'c'] + # 'dg' -> ['d', 'g'] + # no need to list them with "-", just return as a list + # (after escaping) + ret = [escape_re_range_char(c) for c in s_chars] + + return "".join(ret) + + +def _flatten(ll: Iterable) -> list: + ret = [] + to_visit = [*ll] + while to_visit: + i = to_visit.pop(0) + if isinstance(i, Iterable) and not isinstance(i, str): + to_visit[:0] = i + else: + ret.append(i) + return ret + + +def make_compressed_re( + word_list: Iterable[str], + max_level: int = 2, + *, + non_capturing_groups: bool = True, + _level: int = 1, +) -> str: + """ + Create a regular expression string from a list of words, collapsing by common + prefixes and optional suffixes. + + Calls itself recursively to build nested sublists for each group of suffixes + that have a shared prefix. + """ + + def get_suffixes_from_common_prefixes(namelist: list[str]): + if len(namelist) > 1: + for prefix, suffixes in itertools.groupby(namelist, key=lambda s: s[:1]): + yield prefix, sorted([s[1:] for s in suffixes], key=len, reverse=True) + else: + yield namelist[0][0], [namelist[0][1:]] + + if _level == 1: + if not word_list: + raise ValueError("no words given to make_compressed_re()") + + if "" in word_list: + raise ValueError("word list cannot contain empty string") + else: + # internal recursive call, just return empty string if no words + if not word_list: + return "" + + # dedupe the word list + word_list = list({}.fromkeys(word_list)) + + if max_level == 0: + if any(len(wd) > 1 for wd in word_list): + return "|".join( + sorted([re.escape(wd) for wd in word_list], key=len, reverse=True) + ) + else: + return f"[{''.join(_escape_regex_range_chars(wd) for wd in word_list)}]" + + ret = [] + sep = "" + ncgroup = "?:" if non_capturing_groups else "" + + for initial, suffixes in get_suffixes_from_common_prefixes(sorted(word_list)): + ret.append(sep) + sep = "|" + + initial = re.escape(initial) + + trailing = "" + if "" in suffixes: + trailing = "?" + suffixes.remove("") + + if len(suffixes) > 1: + if all(len(s) == 1 for s in suffixes): + ret.append( + f"{initial}[{''.join(_escape_regex_range_chars(s) for s in suffixes)}]{trailing}" + ) + else: + if _level < max_level: + suffix_re = make_compressed_re( + sorted(suffixes), + max_level, + non_capturing_groups=non_capturing_groups, + _level=_level + 1, + ) + ret.append(f"{initial}({ncgroup}{suffix_re}){trailing}") + else: + if all(len(s) == 1 for s in suffixes): + ret.append( + f"{initial}[{''.join(_escape_regex_range_chars(s) for s in suffixes)}]{trailing}" + ) + else: + suffixes.sort(key=len, reverse=True) + ret.append( + f"{initial}({ncgroup}{'|'.join(re.escape(s) for s in suffixes)}){trailing}" + ) + else: + if suffixes: + suffix = re.escape(suffixes[0]) + if len(suffix) > 1 and trailing: + ret.append(f"{initial}({ncgroup}{suffix}){trailing}") + else: + ret.append(f"{initial}{suffix}{trailing}") + else: + ret.append(initial) + return "".join(ret) + + +def replaced_by_pep8(compat_name: str, fn: C) -> C: + # In a future version, uncomment the code in the internal _inner() functions + # to begin emitting DeprecationWarnings. + + # Unwrap staticmethod/classmethod + fn = getattr(fn, "__func__", fn) + + # (Presence of 'self' arg in signature is used by explain_exception() methods, so we take + # some extra steps to add it if present in decorated function.) + if ["self"] == list(inspect.signature(fn).parameters)[:1]: + + @wraps(fn) + def _inner(self, *args, **kwargs): + # warnings.warn( + # f"Deprecated - use {fn.__name__}", DeprecationWarning, stacklevel=2 + # ) + return fn(self, *args, **kwargs) + + else: + + @wraps(fn) + def _inner(*args, **kwargs): + # warnings.warn( + # f"Deprecated - use {fn.__name__}", DeprecationWarning, stacklevel=2 + # ) + return fn(*args, **kwargs) + + _inner.__doc__ = f""" + .. deprecated:: 3.0.0 + Use :class:`{fn.__name__}` instead + """ + _inner.__name__ = compat_name + _inner.__annotations__ = fn.__annotations__ + if isinstance(fn, types.FunctionType): + _inner.__kwdefaults__ = fn.__kwdefaults__ # type: ignore [attr-defined] + elif isinstance(fn, type) and hasattr(fn, "__init__"): + _inner.__kwdefaults__ = fn.__init__.__kwdefaults__ # type: ignore [misc,attr-defined] + else: + _inner.__kwdefaults__ = None # type: ignore [attr-defined] + _inner.__qualname__ = fn.__qualname__ + return cast(C, _inner) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/_build_utils/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/_build_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/_build_utils/tempita.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/_build_utils/tempita.py new file mode 100644 index 0000000000000000000000000000000000000000..c8a7a35a62feeed47fbb10ace87411c9bdc16370 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/_build_utils/tempita.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import argparse +import os + +from Cython import Tempita as tempita + +# XXX: If this import ever fails (does it really?), vendor either +# cython.tempita or numpy/npy_tempita. + + +def process_tempita(fromfile, outfile=None): + """Process tempita templated file and write out the result. + + The template file is expected to end in `.c.tp` or `.pyx.tp`: + E.g. processing `template.c.in` generates `template.c`. + + """ + with open(fromfile, "r", encoding="utf-8") as f: + template_content = f.read() + + template = tempita.Template(template_content) + content = template.substitute() + + with open(outfile, "w", encoding="utf-8") as f: + f.write(content) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("infile", type=str, help="Path to the input file") + parser.add_argument("-o", "--outdir", type=str, help="Path to the output directory") + parser.add_argument( + "-i", + "--ignore", + type=str, + help=( + "An ignored input - may be useful to add a " + "dependency between custom targets" + ), + ) + args = parser.parse_args() + + if not args.infile.endswith(".tp"): + raise ValueError(f"Unexpected extension: {args.infile}") + + if not args.outdir: + raise ValueError("Missing `--outdir` argument to tempita.py") + + outdir_abs = os.path.join(os.getcwd(), args.outdir) + outfile = os.path.join( + outdir_abs, os.path.splitext(os.path.split(args.infile)[1])[0] + ) + + process_tempita(args.infile, outfile) + + +if __name__ == "__main__": + main() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/_build_utils/version.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/_build_utils/version.py new file mode 100644 index 0000000000000000000000000000000000000000..922a14917bf3fd2d395a4f5002a39c4d9d9c7ee2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/_build_utils/version.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python3 +"""Extract version number from __init__.py""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import os + +sklearn_init = os.path.join(os.path.dirname(__file__), "../__init__.py") + +data = open(sklearn_init).readlines() +version_line = next(line for line in data if line.startswith("__version__")) + +version = version_line.strip().split(" = ")[1].replace('"', "").replace("'", "") + +print(version) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..de86a59e07113dcc7f9c656e65c7708ee230afa6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/__init__.py @@ -0,0 +1,56 @@ +"""Popular unsupervised clustering algorithms.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from ._affinity_propagation import AffinityPropagation, affinity_propagation +from ._agglomerative import ( + AgglomerativeClustering, + FeatureAgglomeration, + linkage_tree, + ward_tree, +) +from ._bicluster import SpectralBiclustering, SpectralCoclustering +from ._birch import Birch +from ._bisect_k_means import BisectingKMeans +from ._dbscan import DBSCAN, dbscan +from ._hdbscan.hdbscan import HDBSCAN +from ._kmeans import KMeans, MiniBatchKMeans, k_means, kmeans_plusplus +from ._mean_shift import MeanShift, estimate_bandwidth, get_bin_seeds, mean_shift +from ._optics import ( + OPTICS, + cluster_optics_dbscan, + cluster_optics_xi, + compute_optics_graph, +) +from ._spectral import SpectralClustering, spectral_clustering + +__all__ = [ + "DBSCAN", + "HDBSCAN", + "OPTICS", + "AffinityPropagation", + "AgglomerativeClustering", + "Birch", + "BisectingKMeans", + "FeatureAgglomeration", + "KMeans", + "MeanShift", + "MiniBatchKMeans", + "SpectralBiclustering", + "SpectralClustering", + "SpectralCoclustering", + "affinity_propagation", + "cluster_optics_dbscan", + "cluster_optics_xi", + "compute_optics_graph", + "dbscan", + "estimate_bandwidth", + "get_bin_seeds", + "k_means", + "kmeans_plusplus", + "linkage_tree", + "mean_shift", + "spectral_clustering", + "ward_tree", +] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_affinity_propagation.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_affinity_propagation.py new file mode 100644 index 0000000000000000000000000000000000000000..c7ae6ed63580d60eb2d889c11cfe84875380c55c --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_affinity_propagation.py @@ -0,0 +1,607 @@ +"""Affinity Propagation clustering algorithm.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from numbers import Integral, Real + +import numpy as np + +from .._config import config_context +from ..base import BaseEstimator, ClusterMixin, _fit_context +from ..exceptions import ConvergenceWarning +from ..metrics import euclidean_distances, pairwise_distances_argmin +from ..utils import check_random_state +from ..utils._param_validation import Interval, StrOptions, validate_params +from ..utils.validation import check_is_fitted, validate_data + + +def _equal_similarities_and_preferences(S, preference): + def all_equal_preferences(): + return np.all(preference == preference.flat[0]) + + def all_equal_similarities(): + # Create mask to ignore diagonal of S + mask = np.ones(S.shape, dtype=bool) + np.fill_diagonal(mask, 0) + + return np.all(S[mask].flat == S[mask].flat[0]) + + return all_equal_preferences() and all_equal_similarities() + + +def _affinity_propagation( + S, + *, + preference, + convergence_iter, + max_iter, + damping, + verbose, + return_n_iter, + random_state, +): + """Main affinity propagation algorithm.""" + n_samples = S.shape[0] + if n_samples == 1 or _equal_similarities_and_preferences(S, preference): + # It makes no sense to run the algorithm in this case, so return 1 or + # n_samples clusters, depending on preferences + warnings.warn( + "All samples have mutually equal similarities. " + "Returning arbitrary cluster center(s)." + ) + if preference.flat[0] > S.flat[n_samples - 1]: + return ( + (np.arange(n_samples), np.arange(n_samples), 0) + if return_n_iter + else (np.arange(n_samples), np.arange(n_samples)) + ) + else: + return ( + (np.array([0]), np.array([0] * n_samples), 0) + if return_n_iter + else (np.array([0]), np.array([0] * n_samples)) + ) + + # Place preference on the diagonal of S + S.flat[:: (n_samples + 1)] = preference + + A = np.zeros((n_samples, n_samples)) + R = np.zeros((n_samples, n_samples)) # Initialize messages + # Intermediate results + tmp = np.zeros((n_samples, n_samples)) + + # Remove degeneracies + S += ( + np.finfo(S.dtype).eps * S + np.finfo(S.dtype).tiny * 100 + ) * random_state.standard_normal(size=(n_samples, n_samples)) + + # Execute parallel affinity propagation updates + e = np.zeros((n_samples, convergence_iter)) + + ind = np.arange(n_samples) + + for it in range(max_iter): + # tmp = A + S; compute responsibilities + np.add(A, S, tmp) + I = np.argmax(tmp, axis=1) + Y = tmp[ind, I] # np.max(A + S, axis=1) + tmp[ind, I] = -np.inf + Y2 = np.max(tmp, axis=1) + + # tmp = Rnew + np.subtract(S, Y[:, None], tmp) + tmp[ind, I] = S[ind, I] - Y2 + + # Damping + tmp *= 1 - damping + R *= damping + R += tmp + + # tmp = Rp; compute availabilities + np.maximum(R, 0, tmp) + tmp.flat[:: n_samples + 1] = R.flat[:: n_samples + 1] + + # tmp = -Anew + tmp -= np.sum(tmp, axis=0) + dA = np.diag(tmp).copy() + tmp.clip(0, np.inf, tmp) + tmp.flat[:: n_samples + 1] = dA + + # Damping + tmp *= 1 - damping + A *= damping + A -= tmp + + # Check for convergence + E = (np.diag(A) + np.diag(R)) > 0 + e[:, it % convergence_iter] = E + K = np.sum(E, axis=0) + + if it >= convergence_iter: + se = np.sum(e, axis=1) + unconverged = np.sum((se == convergence_iter) + (se == 0)) != n_samples + if (not unconverged and (K > 0)) or (it == max_iter): + never_converged = False + if verbose: + print("Converged after %d iterations." % it) + break + else: + never_converged = True + if verbose: + print("Did not converge") + + I = np.flatnonzero(E) + K = I.size # Identify exemplars + + if K > 0: + if never_converged: + warnings.warn( + ( + "Affinity propagation did not converge, this model " + "may return degenerate cluster centers and labels." + ), + ConvergenceWarning, + ) + c = np.argmax(S[:, I], axis=1) + c[I] = np.arange(K) # Identify clusters + # Refine the final set of exemplars and clusters and return results + for k in range(K): + ii = np.asarray(c == k).nonzero()[0] + j = np.argmax(np.sum(S[ii[:, np.newaxis], ii], axis=0)) + I[k] = ii[j] + + c = np.argmax(S[:, I], axis=1) + c[I] = np.arange(K) + labels = I[c] + # Reduce labels to a sorted, gapless, list + cluster_centers_indices = np.unique(labels) + labels = np.searchsorted(cluster_centers_indices, labels) + else: + warnings.warn( + ( + "Affinity propagation did not converge and this model " + "will not have any cluster centers." + ), + ConvergenceWarning, + ) + labels = np.array([-1] * n_samples) + cluster_centers_indices = [] + + if return_n_iter: + return cluster_centers_indices, labels, it + 1 + else: + return cluster_centers_indices, labels + + +############################################################################### +# Public API + + +@validate_params( + { + "S": ["array-like"], + "return_n_iter": ["boolean"], + }, + prefer_skip_nested_validation=False, +) +def affinity_propagation( + S, + *, + preference=None, + convergence_iter=15, + max_iter=200, + damping=0.5, + copy=True, + verbose=False, + return_n_iter=False, + random_state=None, +): + """Perform Affinity Propagation Clustering of data. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + S : array-like of shape (n_samples, n_samples) + Matrix of similarities between points. + + preference : array-like of shape (n_samples,) or float, default=None + Preferences for each point - points with larger values of + preferences are more likely to be chosen as exemplars. The number of + exemplars, i.e. of clusters, is influenced by the input preferences + value. If the preferences are not passed as arguments, they will be + set to the median of the input similarities (resulting in a moderate + number of clusters). For a smaller amount of clusters, this can be set + to the minimum value of the similarities. + + convergence_iter : int, default=15 + Number of iterations with no change in the number + of estimated clusters that stops the convergence. + + max_iter : int, default=200 + Maximum number of iterations. + + damping : float, default=0.5 + Damping factor between 0.5 and 1. + + copy : bool, default=True + If copy is False, the affinity matrix is modified inplace by the + algorithm, for memory efficiency. + + verbose : bool, default=False + The verbosity level. + + return_n_iter : bool, default=False + Whether or not to return the number of iterations. + + random_state : int, RandomState instance or None, default=None + Pseudo-random number generator to control the starting state. + Use an int for reproducible results across function calls. + See the :term:`Glossary `. + + .. versionadded:: 0.23 + this parameter was previously hardcoded as 0. + + Returns + ------- + cluster_centers_indices : ndarray of shape (n_clusters,) + Index of clusters centers. + + labels : ndarray of shape (n_samples,) + Cluster labels for each point. + + n_iter : int + Number of iterations run. Returned only if `return_n_iter` is + set to True. + + Notes + ----- + For an example usage, + see :ref:`sphx_glr_auto_examples_cluster_plot_affinity_propagation.py`. + You may also check out, + :ref:`sphx_glr_auto_examples_applications_plot_stock_market.py` + + When the algorithm does not converge, it will still return a arrays of + ``cluster_center_indices`` and labels if there are any exemplars/clusters, + however they may be degenerate and should be used with caution. + + When all training samples have equal similarities and equal preferences, + the assignment of cluster centers and labels depends on the preference. + If the preference is smaller than the similarities, a single cluster center + and label ``0`` for every sample will be returned. Otherwise, every + training sample becomes its own cluster center and is assigned a unique + label. + + References + ---------- + Brendan J. Frey and Delbert Dueck, "Clustering by Passing Messages + Between Data Points", Science Feb. 2007 + + Examples + -------- + >>> import numpy as np + >>> from sklearn.cluster import affinity_propagation + >>> from sklearn.metrics.pairwise import euclidean_distances + >>> X = np.array([[1, 2], [1, 4], [1, 0], + ... [4, 2], [4, 4], [4, 0]]) + >>> S = -euclidean_distances(X, squared=True) + >>> cluster_centers_indices, labels = affinity_propagation(S, random_state=0) + >>> cluster_centers_indices + array([0, 3]) + >>> labels + array([0, 0, 0, 1, 1, 1]) + """ + estimator = AffinityPropagation( + damping=damping, + max_iter=max_iter, + convergence_iter=convergence_iter, + copy=copy, + preference=preference, + affinity="precomputed", + verbose=verbose, + random_state=random_state, + ).fit(S) + + if return_n_iter: + return estimator.cluster_centers_indices_, estimator.labels_, estimator.n_iter_ + return estimator.cluster_centers_indices_, estimator.labels_ + + +class AffinityPropagation(ClusterMixin, BaseEstimator): + """Perform Affinity Propagation Clustering of data. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + damping : float, default=0.5 + Damping factor in the range `[0.5, 1.0)` is the extent to + which the current value is maintained relative to + incoming values (weighted 1 - damping). This in order + to avoid numerical oscillations when updating these + values (messages). + + max_iter : int, default=200 + Maximum number of iterations. + + convergence_iter : int, default=15 + Number of iterations with no change in the number + of estimated clusters that stops the convergence. + + copy : bool, default=True + Make a copy of input data. + + preference : array-like of shape (n_samples,) or float, default=None + Preferences for each point - points with larger values of + preferences are more likely to be chosen as exemplars. The number + of exemplars, ie of clusters, is influenced by the input + preferences value. If the preferences are not passed as arguments, + they will be set to the median of the input similarities. + + affinity : {'euclidean', 'precomputed'}, default='euclidean' + Which affinity to use. At the moment 'precomputed' and + ``euclidean`` are supported. 'euclidean' uses the + negative squared euclidean distance between points. + + verbose : bool, default=False + Whether to be verbose. + + random_state : int, RandomState instance or None, default=None + Pseudo-random number generator to control the starting state. + Use an int for reproducible results across function calls. + See the :term:`Glossary `. + + .. versionadded:: 0.23 + this parameter was previously hardcoded as 0. + + Attributes + ---------- + cluster_centers_indices_ : ndarray of shape (n_clusters,) + Indices of cluster centers. + + cluster_centers_ : ndarray of shape (n_clusters, n_features) + Cluster centers (if affinity != ``precomputed``). + + labels_ : ndarray of shape (n_samples,) + Labels of each point. + + affinity_matrix_ : ndarray of shape (n_samples, n_samples) + Stores the affinity matrix used in ``fit``. + + n_iter_ : int + Number of iterations taken to converge. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + AgglomerativeClustering : Recursively merges the pair of + clusters that minimally increases a given linkage distance. + FeatureAgglomeration : Similar to AgglomerativeClustering, + but recursively merges features instead of samples. + KMeans : K-Means clustering. + MiniBatchKMeans : Mini-Batch K-Means clustering. + MeanShift : Mean shift clustering using a flat kernel. + SpectralClustering : Apply clustering to a projection + of the normalized Laplacian. + + Notes + ----- + The algorithmic complexity of affinity propagation is quadratic + in the number of points. + + When the algorithm does not converge, it will still return a arrays of + ``cluster_center_indices`` and labels if there are any exemplars/clusters, + however they may be degenerate and should be used with caution. + + When ``fit`` does not converge, ``cluster_centers_`` is still populated + however it may be degenerate. In such a case, proceed with caution. + If ``fit`` does not converge and fails to produce any ``cluster_centers_`` + then ``predict`` will label every sample as ``-1``. + + When all training samples have equal similarities and equal preferences, + the assignment of cluster centers and labels depends on the preference. + If the preference is smaller than the similarities, ``fit`` will result in + a single cluster center and label ``0`` for every sample. Otherwise, every + training sample becomes its own cluster center and is assigned a unique + label. + + References + ---------- + + Brendan J. Frey and Delbert Dueck, "Clustering by Passing Messages + Between Data Points", Science Feb. 2007 + + Examples + -------- + >>> from sklearn.cluster import AffinityPropagation + >>> import numpy as np + >>> X = np.array([[1, 2], [1, 4], [1, 0], + ... [4, 2], [4, 4], [4, 0]]) + >>> clustering = AffinityPropagation(random_state=5).fit(X) + >>> clustering + AffinityPropagation(random_state=5) + >>> clustering.labels_ + array([0, 0, 0, 1, 1, 1]) + >>> clustering.predict([[0, 0], [4, 4]]) + array([0, 1]) + >>> clustering.cluster_centers_ + array([[1, 2], + [4, 2]]) + + For an example usage, + see :ref:`sphx_glr_auto_examples_cluster_plot_affinity_propagation.py`. + + For a comparison of Affinity Propagation with other clustering algorithms, see + :ref:`sphx_glr_auto_examples_cluster_plot_cluster_comparison.py` + """ + + _parameter_constraints: dict = { + "damping": [Interval(Real, 0.5, 1.0, closed="left")], + "max_iter": [Interval(Integral, 1, None, closed="left")], + "convergence_iter": [Interval(Integral, 1, None, closed="left")], + "copy": ["boolean"], + "preference": [ + "array-like", + Interval(Real, None, None, closed="neither"), + None, + ], + "affinity": [StrOptions({"euclidean", "precomputed"})], + "verbose": ["verbose"], + "random_state": ["random_state"], + } + + def __init__( + self, + *, + damping=0.5, + max_iter=200, + convergence_iter=15, + copy=True, + preference=None, + affinity="euclidean", + verbose=False, + random_state=None, + ): + self.damping = damping + self.max_iter = max_iter + self.convergence_iter = convergence_iter + self.copy = copy + self.verbose = verbose + self.preference = preference + self.affinity = affinity + self.random_state = random_state + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.pairwise = self.affinity == "precomputed" + tags.input_tags.sparse = self.affinity != "precomputed" + return tags + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Fit the clustering from features, or affinity matrix. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features), or \ + array-like of shape (n_samples, n_samples) + Training instances to cluster, or similarities / affinities between + instances if ``affinity='precomputed'``. If a sparse feature matrix + is provided, it will be converted into a sparse ``csr_matrix``. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self + Returns the instance itself. + """ + if self.affinity == "precomputed": + X = validate_data(self, X, copy=self.copy, force_writeable=True) + self.affinity_matrix_ = X + else: # self.affinity == "euclidean" + X = validate_data(self, X, accept_sparse="csr") + self.affinity_matrix_ = -euclidean_distances(X, squared=True) + + if self.affinity_matrix_.shape[0] != self.affinity_matrix_.shape[1]: + raise ValueError( + "The matrix of similarities must be a square array. " + f"Got {self.affinity_matrix_.shape} instead." + ) + + if self.preference is None: + preference = np.median(self.affinity_matrix_) + else: + preference = self.preference + preference = np.asarray(preference) + + random_state = check_random_state(self.random_state) + + ( + self.cluster_centers_indices_, + self.labels_, + self.n_iter_, + ) = _affinity_propagation( + self.affinity_matrix_, + max_iter=self.max_iter, + convergence_iter=self.convergence_iter, + preference=preference, + damping=self.damping, + verbose=self.verbose, + return_n_iter=True, + random_state=random_state, + ) + + if self.affinity != "precomputed": + self.cluster_centers_ = X[self.cluster_centers_indices_].copy() + + return self + + def predict(self, X): + """Predict the closest cluster each sample in X belongs to. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + New data to predict. If a sparse matrix is provided, it will be + converted into a sparse ``csr_matrix``. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Cluster labels. + """ + check_is_fitted(self) + X = validate_data(self, X, reset=False, accept_sparse="csr") + if not hasattr(self, "cluster_centers_"): + raise ValueError( + "Predict method is not supported when affinity='precomputed'." + ) + + if self.cluster_centers_.shape[0] > 0: + with config_context(assume_finite=True): + return pairwise_distances_argmin(X, self.cluster_centers_) + else: + warnings.warn( + ( + "This model does not have any cluster centers " + "because affinity propagation did not converge. " + "Labeling every sample as '-1'." + ), + ConvergenceWarning, + ) + return np.array([-1] * X.shape[0]) + + def fit_predict(self, X, y=None): + """Fit clustering from features/affinity matrix; return cluster labels. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features), or \ + array-like of shape (n_samples, n_samples) + Training instances to cluster, or similarities / affinities between + instances if ``affinity='precomputed'``. If a sparse feature matrix + is provided, it will be converted into a sparse ``csr_matrix``. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Cluster labels. + """ + return super().fit_predict(X, y) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_agglomerative.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_agglomerative.py new file mode 100644 index 0000000000000000000000000000000000000000..f068dc934151d0f4a03f32000fb79e2d657f45a2 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_agglomerative.py @@ -0,0 +1,1333 @@ +"""Hierarchical Agglomerative Clustering + +These routines perform some hierarchical agglomerative clustering of some +input data. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from heapq import heapify, heappop, heappush, heappushpop +from numbers import Integral, Real + +import numpy as np +from scipy import sparse +from scipy.sparse.csgraph import connected_components + +from ..base import ( + BaseEstimator, + ClassNamePrefixFeaturesOutMixin, + ClusterMixin, + _fit_context, +) +from ..metrics import DistanceMetric +from ..metrics._dist_metrics import METRIC_MAPPING64 +from ..metrics.pairwise import _VALID_METRICS, paired_distances +from ..utils import check_array +from ..utils._fast_dict import IntFloatDict +from ..utils._param_validation import ( + HasMethods, + Interval, + StrOptions, + validate_params, +) +from ..utils.graph import _fix_connected_components +from ..utils.validation import check_memory, validate_data + +# mypy error: Module 'sklearn.cluster' has no attribute '_hierarchical_fast' +from . import _hierarchical_fast as _hierarchical # type: ignore[attr-defined] +from ._feature_agglomeration import AgglomerationTransform + +############################################################################### +# For non fully-connected graphs + + +def _fix_connectivity(X, connectivity, affinity): + """ + Fixes the connectivity matrix. + + The different steps are: + + - copies it + - makes it symmetric + - converts it to LIL if necessary + - completes it if necessary. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Feature matrix representing `n_samples` samples to be clustered. + + connectivity : sparse matrix, default=None + Connectivity matrix. Defines for each sample the neighboring samples + following a given structure of the data. The matrix is assumed to + be symmetric and only the upper triangular half is used. + Default is `None`, i.e, the Ward algorithm is unstructured. + + affinity : {"euclidean", "precomputed"}, default="euclidean" + Which affinity to use. At the moment `precomputed` and + ``euclidean`` are supported. `euclidean` uses the + negative squared Euclidean distance between points. + + Returns + ------- + connectivity : sparse matrix + The fixed connectivity matrix. + + n_connected_components : int + The number of connected components in the graph. + """ + n_samples = X.shape[0] + if connectivity.shape[0] != n_samples or connectivity.shape[1] != n_samples: + raise ValueError( + "Wrong shape for connectivity matrix: %s when X is %s" + % (connectivity.shape, X.shape) + ) + + # Make the connectivity matrix symmetric: + connectivity = connectivity + connectivity.T + + # Convert connectivity matrix to LIL + if not sparse.issparse(connectivity): + connectivity = sparse.lil_matrix(connectivity) + + # `connectivity` is a sparse matrix at this point + if connectivity.format != "lil": + connectivity = connectivity.tolil() + + # Compute the number of nodes + n_connected_components, labels = connected_components(connectivity) + + if n_connected_components > 1: + warnings.warn( + "the number of connected components of the " + "connectivity matrix is %d > 1. Completing it to avoid " + "stopping the tree early." % n_connected_components, + stacklevel=2, + ) + # XXX: Can we do without completing the matrix? + connectivity = _fix_connected_components( + X=X, + graph=connectivity, + n_connected_components=n_connected_components, + component_labels=labels, + metric=affinity, + mode="connectivity", + ) + + return connectivity, n_connected_components + + +def _single_linkage_tree( + connectivity, + n_samples, + n_nodes, + n_clusters, + n_connected_components, + return_distance, +): + """ + Perform single linkage clustering on sparse data via the minimum + spanning tree from scipy.sparse.csgraph, then using union-find to label. + The parent array is then generated by walking through the tree. + """ + from scipy.sparse.csgraph import minimum_spanning_tree + + # explicitly cast connectivity to ensure safety + connectivity = connectivity.astype(np.float64, copy=False) + + # Ensure zero distances aren't ignored by setting them to "epsilon" + epsilon_value = np.finfo(dtype=connectivity.data.dtype).eps + connectivity.data[connectivity.data == 0] = epsilon_value + + # Use scipy.sparse.csgraph to generate a minimum spanning tree + mst = minimum_spanning_tree(connectivity.tocsr()) + + # Convert the graph to scipy.cluster.hierarchy array format + mst = mst.tocoo() + + # Undo the epsilon values + mst.data[mst.data == epsilon_value] = 0 + + mst_array = np.vstack([mst.row, mst.col, mst.data]).T + + # Sort edges of the min_spanning_tree by weight + mst_array = mst_array[np.argsort(mst_array.T[2], kind="mergesort"), :] + + # Convert edge list into standard hierarchical clustering format + single_linkage_tree = _hierarchical._single_linkage_label(mst_array) + children_ = single_linkage_tree[:, :2].astype(int) + + # Compute parents + parent = np.arange(n_nodes, dtype=np.intp) + for i, (left, right) in enumerate(children_, n_samples): + if n_clusters is not None and i >= n_nodes: + break + if left < n_nodes: + parent[left] = i + if right < n_nodes: + parent[right] = i + + if return_distance: + distances = single_linkage_tree[:, 2] + return children_, n_connected_components, n_samples, parent, distances + return children_, n_connected_components, n_samples, parent + + +############################################################################### +# Hierarchical tree building functions + + +@validate_params( + { + "X": ["array-like"], + "connectivity": ["array-like", "sparse matrix", None], + "n_clusters": [Interval(Integral, 1, None, closed="left"), None], + "return_distance": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def ward_tree(X, *, connectivity=None, n_clusters=None, return_distance=False): + """Ward clustering based on a Feature matrix. + + Recursively merges the pair of clusters that minimally increases + within-cluster variance. + + The inertia matrix uses a Heapq-based representation. + + This is the structured version, that takes into account some topological + structure between samples. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Feature matrix representing `n_samples` samples to be clustered. + + connectivity : {array-like, sparse matrix}, default=None + Connectivity matrix. Defines for each sample the neighboring samples + following a given structure of the data. The matrix is assumed to + be symmetric and only the upper triangular half is used. + Default is None, i.e, the Ward algorithm is unstructured. + + n_clusters : int, default=None + `n_clusters` should be less than `n_samples`. Stop early the + construction of the tree at `n_clusters.` This is useful to decrease + computation time if the number of clusters is not small compared to the + number of samples. In this case, the complete tree is not computed, thus + the 'children' output is of limited use, and the 'parents' output should + rather be used. This option is valid only when specifying a connectivity + matrix. + + return_distance : bool, default=False + If `True`, return the distance between the clusters. + + Returns + ------- + children : ndarray of shape (n_nodes-1, 2) + The children of each non-leaf node. Values less than `n_samples` + correspond to leaves of the tree which are the original samples. + A node `i` greater than or equal to `n_samples` is a non-leaf + node and has children `children_[i - n_samples]`. Alternatively + at the i-th iteration, children[i][0] and children[i][1] + are merged to form node `n_samples + i`. + + n_connected_components : int + The number of connected components in the graph. + + n_leaves : int + The number of leaves in the tree. + + parents : ndarray of shape (n_nodes,) or None + The parent of each node. Only returned when a connectivity matrix + is specified, elsewhere 'None' is returned. + + distances : ndarray of shape (n_nodes-1,) + Only returned if `return_distance` is set to `True` (for compatibility). + The distances between the centers of the nodes. `distances[i]` + corresponds to a weighted Euclidean distance between + the nodes `children[i, 1]` and `children[i, 2]`. If the nodes refer to + leaves of the tree, then `distances[i]` is their unweighted Euclidean + distance. Distances are updated in the following way + (from scipy.hierarchy.linkage): + + The new entry :math:`d(u,v)` is computed as follows, + + .. math:: + + d(u,v) = \\sqrt{\\frac{|v|+|s|} + {T}d(v,s)^2 + + \\frac{|v|+|t|} + {T}d(v,t)^2 + - \\frac{|v|} + {T}d(s,t)^2} + + where :math:`u` is the newly joined cluster consisting of + clusters :math:`s` and :math:`t`, :math:`v` is an unused + cluster in the forest, :math:`T=|v|+|s|+|t|`, and + :math:`|*|` is the cardinality of its argument. This is also + known as the incremental algorithm. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.cluster import ward_tree + >>> X = np.array([[1, 2], [1, 4], [1, 0], + ... [4, 2], [4, 4], [4, 0]]) + >>> children, n_connected_components, n_leaves, parents = ward_tree(X) + >>> children + array([[0, 1], + [3, 5], + [2, 6], + [4, 7], + [8, 9]]) + >>> n_connected_components + 1 + >>> n_leaves + 6 + """ + X = np.asarray(X) + if X.ndim == 1: + X = np.reshape(X, (-1, 1)) + n_samples, n_features = X.shape + + if connectivity is None: + from scipy.cluster import hierarchy # imports PIL + + if n_clusters is not None: + warnings.warn( + ( + "Partial build of the tree is implemented " + "only for structured clustering (i.e. with " + "explicit connectivity). The algorithm " + "will build the full tree and only " + "retain the lower branches required " + "for the specified number of clusters" + ), + stacklevel=2, + ) + X = np.require(X, requirements="W") + out = hierarchy.ward(X) + children_ = out[:, :2].astype(np.intp) + + if return_distance: + distances = out[:, 2] + return children_, 1, n_samples, None, distances + else: + return children_, 1, n_samples, None + + connectivity, n_connected_components = _fix_connectivity( + X, connectivity, affinity="euclidean" + ) + if n_clusters is None: + n_nodes = 2 * n_samples - 1 + else: + if n_clusters > n_samples: + raise ValueError( + "Cannot provide more clusters than samples. " + "%i n_clusters was asked, and there are %i " + "samples." % (n_clusters, n_samples) + ) + n_nodes = 2 * n_samples - n_clusters + + # create inertia matrix + coord_row = [] + coord_col = [] + A = [] + for ind, row in enumerate(connectivity.rows): + A.append(row) + # We keep only the upper triangular for the moments + # Generator expressions are faster than arrays on the following + row = [i for i in row if i < ind] + coord_row.extend( + len(row) + * [ + ind, + ] + ) + coord_col.extend(row) + + coord_row = np.array(coord_row, dtype=np.intp, order="C") + coord_col = np.array(coord_col, dtype=np.intp, order="C") + + # build moments as a list + moments_1 = np.zeros(n_nodes, order="C") + moments_1[:n_samples] = 1 + moments_2 = np.zeros((n_nodes, n_features), order="C") + moments_2[:n_samples] = X + inertia = np.empty(len(coord_row), dtype=np.float64, order="C") + _hierarchical.compute_ward_dist(moments_1, moments_2, coord_row, coord_col, inertia) + inertia = list(zip(inertia, coord_row, coord_col)) + heapify(inertia) + + # prepare the main fields + parent = np.arange(n_nodes, dtype=np.intp) + used_node = np.ones(n_nodes, dtype=bool) + children = [] + if return_distance: + distances = np.empty(n_nodes - n_samples) + + not_visited = np.empty(n_nodes, dtype=bool, order="C") + + # recursive merge loop + for k in range(n_samples, n_nodes): + # identify the merge + while True: + inert, i, j = heappop(inertia) + if used_node[i] and used_node[j]: + break + parent[i], parent[j] = k, k + children.append((i, j)) + used_node[i] = used_node[j] = False + if return_distance: # store inertia value + distances[k - n_samples] = inert + + # update the moments + moments_1[k] = moments_1[i] + moments_1[j] + moments_2[k] = moments_2[i] + moments_2[j] + + # update the structure matrix A and the inertia matrix + coord_col = [] + not_visited.fill(1) + not_visited[k] = 0 + _hierarchical._get_parents(A[i], coord_col, parent, not_visited) + _hierarchical._get_parents(A[j], coord_col, parent, not_visited) + # List comprehension is faster than a for loop + [A[col].append(k) for col in coord_col] + A.append(coord_col) + coord_col = np.array(coord_col, dtype=np.intp, order="C") + coord_row = np.empty(coord_col.shape, dtype=np.intp, order="C") + coord_row.fill(k) + n_additions = len(coord_row) + ini = np.empty(n_additions, dtype=np.float64, order="C") + + _hierarchical.compute_ward_dist(moments_1, moments_2, coord_row, coord_col, ini) + + # List comprehension is faster than a for loop + [heappush(inertia, (ini[idx], k, coord_col[idx])) for idx in range(n_additions)] + + # Separate leaves in children (empty lists up to now) + n_leaves = n_samples + # sort children to get consistent output with unstructured version + children = [c[::-1] for c in children] + children = np.array(children) # return numpy array for efficient caching + + if return_distance: + # 2 is scaling factor to compare w/ unstructured version + distances = np.sqrt(2.0 * distances) + return children, n_connected_components, n_leaves, parent, distances + else: + return children, n_connected_components, n_leaves, parent + + +# single average and complete linkage +def linkage_tree( + X, + connectivity=None, + n_clusters=None, + linkage="complete", + affinity="euclidean", + return_distance=False, +): + """Linkage agglomerative clustering based on a Feature matrix. + + The inertia matrix uses a Heapq-based representation. + + This is the structured version, that takes into account some topological + structure between samples. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Feature matrix representing `n_samples` samples to be clustered. + + connectivity : sparse matrix, default=None + Connectivity matrix. Defines for each sample the neighboring samples + following a given structure of the data. The matrix is assumed to + be symmetric and only the upper triangular half is used. + Default is `None`, i.e, the Ward algorithm is unstructured. + + n_clusters : int, default=None + Stop early the construction of the tree at `n_clusters`. This is + useful to decrease computation time if the number of clusters is + not small compared to the number of samples. In this case, the + complete tree is not computed, thus the 'children' output is of + limited use, and the 'parents' output should rather be used. + This option is valid only when specifying a connectivity matrix. + + linkage : {"average", "complete", "single"}, default="complete" + Which linkage criteria to use. The linkage criterion determines which + distance to use between sets of observation. + - "average" uses the average of the distances of each observation of + the two sets. + - "complete" or maximum linkage uses the maximum distances between + all observations of the two sets. + - "single" uses the minimum of the distances between all + observations of the two sets. + + affinity : str or callable, default='euclidean' + Which metric to use. Can be 'euclidean', 'manhattan', or any + distance known to paired distance (see metric.pairwise). + + return_distance : bool, default=False + Whether or not to return the distances between the clusters. + + Returns + ------- + children : ndarray of shape (n_nodes-1, 2) + The children of each non-leaf node. Values less than `n_samples` + correspond to leaves of the tree which are the original samples. + A node `i` greater than or equal to `n_samples` is a non-leaf + node and has children `children_[i - n_samples]`. Alternatively + at the i-th iteration, children[i][0] and children[i][1] + are merged to form node `n_samples + i`. + + n_connected_components : int + The number of connected components in the graph. + + n_leaves : int + The number of leaves in the tree. + + parents : ndarray of shape (n_nodes, ) or None + The parent of each node. Only returned when a connectivity matrix + is specified, elsewhere 'None' is returned. + + distances : ndarray of shape (n_nodes-1,) + Returned when `return_distance` is set to `True`. + + distances[i] refers to the distance between children[i][0] and + children[i][1] when they are merged. + + See Also + -------- + ward_tree : Hierarchical clustering with ward linkage. + """ + X = np.asarray(X) + if X.ndim == 1: + X = np.reshape(X, (-1, 1)) + n_samples, n_features = X.shape + + linkage_choices = { + "complete": _hierarchical.max_merge, + "average": _hierarchical.average_merge, + "single": None, + } # Single linkage is handled differently + try: + join_func = linkage_choices[linkage] + except KeyError as e: + raise ValueError( + "Unknown linkage option, linkage should be one of %s, but %s was given" + % (linkage_choices.keys(), linkage) + ) from e + + if affinity == "cosine" and np.any(~np.any(X, axis=1)): + raise ValueError("Cosine affinity cannot be used when X contains zero vectors") + + if connectivity is None: + from scipy.cluster import hierarchy # imports PIL + + if n_clusters is not None: + warnings.warn( + ( + "Partial build of the tree is implemented " + "only for structured clustering (i.e. with " + "explicit connectivity). The algorithm " + "will build the full tree and only " + "retain the lower branches required " + "for the specified number of clusters" + ), + stacklevel=2, + ) + + if affinity == "precomputed": + # for the linkage function of hierarchy to work on precomputed + # data, provide as first argument an ndarray of the shape returned + # by sklearn.metrics.pairwise_distances. + if X.shape[0] != X.shape[1]: + raise ValueError( + f"Distance matrix should be square, got matrix of shape {X.shape}" + ) + i, j = np.triu_indices(X.shape[0], k=1) + X = X[i, j] + elif affinity == "l2": + # Translate to something understood by scipy + affinity = "euclidean" + elif affinity in ("l1", "manhattan"): + affinity = "cityblock" + elif callable(affinity): + X = affinity(X) + i, j = np.triu_indices(X.shape[0], k=1) + X = X[i, j] + if ( + linkage == "single" + and affinity != "precomputed" + and not callable(affinity) + and affinity in METRIC_MAPPING64 + ): + # We need the fast cythonized metric from neighbors + dist_metric = DistanceMetric.get_metric(affinity) + + # The Cython routines used require contiguous arrays + X = np.ascontiguousarray(X, dtype=np.double) + + mst = _hierarchical.mst_linkage_core(X, dist_metric) + # Sort edges of the min_spanning_tree by weight + mst = mst[np.argsort(mst.T[2], kind="mergesort"), :] + + # Convert edge list into standard hierarchical clustering format + out = _hierarchical.single_linkage_label(mst) + else: + out = hierarchy.linkage(X, method=linkage, metric=affinity) + children_ = out[:, :2].astype(int, copy=False) + + if return_distance: + distances = out[:, 2] + return children_, 1, n_samples, None, distances + return children_, 1, n_samples, None + + connectivity, n_connected_components = _fix_connectivity( + X, connectivity, affinity=affinity + ) + connectivity = connectivity.tocoo() + # Put the diagonal to zero + diag_mask = connectivity.row != connectivity.col + connectivity.row = connectivity.row[diag_mask] + connectivity.col = connectivity.col[diag_mask] + connectivity.data = connectivity.data[diag_mask] + del diag_mask + + if affinity == "precomputed": + distances = X[connectivity.row, connectivity.col].astype(np.float64, copy=False) + else: + # FIXME We compute all the distances, while we could have only computed + # the "interesting" distances + distances = paired_distances( + X[connectivity.row], X[connectivity.col], metric=affinity + ) + connectivity.data = distances + + if n_clusters is None: + n_nodes = 2 * n_samples - 1 + else: + assert n_clusters <= n_samples + n_nodes = 2 * n_samples - n_clusters + + if linkage == "single": + return _single_linkage_tree( + connectivity, + n_samples, + n_nodes, + n_clusters, + n_connected_components, + return_distance, + ) + + if return_distance: + distances = np.empty(n_nodes - n_samples) + # create inertia heap and connection matrix + A = np.empty(n_nodes, dtype=object) + inertia = list() + + # LIL seems to the best format to access the rows quickly, + # without the numpy overhead of slicing CSR indices and data. + connectivity = connectivity.tolil() + # We are storing the graph in a list of IntFloatDict + for ind, (data, row) in enumerate(zip(connectivity.data, connectivity.rows)): + A[ind] = IntFloatDict( + np.asarray(row, dtype=np.intp), np.asarray(data, dtype=np.float64) + ) + # We keep only the upper triangular for the heap + # Generator expressions are faster than arrays on the following + inertia.extend( + _hierarchical.WeightedEdge(d, ind, r) for r, d in zip(row, data) if r < ind + ) + del connectivity + + heapify(inertia) + + # prepare the main fields + parent = np.arange(n_nodes, dtype=np.intp) + used_node = np.ones(n_nodes, dtype=np.intp) + children = [] + + # recursive merge loop + for k in range(n_samples, n_nodes): + # identify the merge + while True: + edge = heappop(inertia) + if used_node[edge.a] and used_node[edge.b]: + break + i = edge.a + j = edge.b + + if return_distance: + # store distances + distances[k - n_samples] = edge.weight + + parent[i] = parent[j] = k + children.append((i, j)) + # Keep track of the number of elements per cluster + n_i = used_node[i] + n_j = used_node[j] + used_node[k] = n_i + n_j + used_node[i] = used_node[j] = False + + # update the structure matrix A and the inertia matrix + # a clever 'min', or 'max' operation between A[i] and A[j] + coord_col = join_func(A[i], A[j], used_node, n_i, n_j) + for col, d in coord_col: + A[col].append(k, d) + # Here we use the information from coord_col (containing the + # distances) to update the heap + heappush(inertia, _hierarchical.WeightedEdge(d, k, col)) + A[k] = coord_col + # Clear A[i] and A[j] to save memory + A[i] = A[j] = 0 + + # Separate leaves in children (empty lists up to now) + n_leaves = n_samples + + # # return numpy array for efficient caching + children = np.array(children)[:, ::-1] + + if return_distance: + return children, n_connected_components, n_leaves, parent, distances + return children, n_connected_components, n_leaves, parent + + +# Matching names to tree-building strategies +def _complete_linkage(*args, **kwargs): + kwargs["linkage"] = "complete" + return linkage_tree(*args, **kwargs) + + +def _average_linkage(*args, **kwargs): + kwargs["linkage"] = "average" + return linkage_tree(*args, **kwargs) + + +def _single_linkage(*args, **kwargs): + kwargs["linkage"] = "single" + return linkage_tree(*args, **kwargs) + + +_TREE_BUILDERS = dict( + ward=ward_tree, + complete=_complete_linkage, + average=_average_linkage, + single=_single_linkage, +) + +############################################################################### +# Functions for cutting hierarchical clustering tree + + +def _hc_cut(n_clusters, children, n_leaves): + """Function cutting the ward tree for a given number of clusters. + + Parameters + ---------- + n_clusters : int or ndarray + The number of clusters to form. + + children : ndarray of shape (n_nodes-1, 2) + The children of each non-leaf node. Values less than `n_samples` + correspond to leaves of the tree which are the original samples. + A node `i` greater than or equal to `n_samples` is a non-leaf + node and has children `children_[i - n_samples]`. Alternatively + at the i-th iteration, children[i][0] and children[i][1] + are merged to form node `n_samples + i`. + + n_leaves : int + Number of leaves of the tree. + + Returns + ------- + labels : array [n_samples] + Cluster labels for each point. + """ + if n_clusters > n_leaves: + raise ValueError( + "Cannot extract more clusters than samples: " + f"{n_clusters} clusters were given for a tree with {n_leaves} leaves." + ) + # In this function, we store nodes as a heap to avoid recomputing + # the max of the nodes: the first element is always the smallest + # We use negated indices as heaps work on smallest elements, and we + # are interested in largest elements + # children[-1] is the root of the tree + nodes = [-(max(children[-1]) + 1)] + for _ in range(n_clusters - 1): + # As we have a heap, nodes[0] is the smallest element + these_children = children[-nodes[0] - n_leaves] + # Insert the 2 children and remove the largest node + heappush(nodes, -these_children[0]) + heappushpop(nodes, -these_children[1]) + label = np.zeros(n_leaves, dtype=np.intp) + for i, node in enumerate(nodes): + label[_hierarchical._hc_get_descendent(-node, children, n_leaves)] = i + return label + + +############################################################################### + + +class AgglomerativeClustering(ClusterMixin, BaseEstimator): + """ + Agglomerative Clustering. + + Recursively merges pair of clusters of sample data; uses linkage distance. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_clusters : int or None, default=2 + The number of clusters to find. It must be ``None`` if + ``distance_threshold`` is not ``None``. + + metric : str or callable, default="euclidean" + Metric used to compute the linkage. Can be "euclidean", "l1", "l2", + "manhattan", "cosine", or "precomputed". If linkage is "ward", only + "euclidean" is accepted. If "precomputed", a distance matrix is needed + as input for the fit method. If connectivity is None, linkage is + "single" and affinity is not "precomputed" any valid pairwise distance + metric can be assigned. + + For an example of agglomerative clustering with different metrics, see + :ref:`sphx_glr_auto_examples_cluster_plot_agglomerative_clustering_metrics.py`. + + .. versionadded:: 1.2 + + memory : str or object with the joblib.Memory interface, default=None + Used to cache the output of the computation of the tree. + By default, no caching is done. If a string is given, it is the + path to the caching directory. + + connectivity : array-like, sparse matrix, or callable, default=None + Connectivity matrix. Defines for each sample the neighboring + samples following a given structure of the data. + This can be a connectivity matrix itself or a callable that transforms + the data into a connectivity matrix, such as derived from + `kneighbors_graph`. Default is ``None``, i.e, the + hierarchical clustering algorithm is unstructured. + + For an example of connectivity matrix using + :class:`~sklearn.neighbors.kneighbors_graph`, see + :ref:`sphx_glr_auto_examples_cluster_plot_agglomerative_clustering.py`. + + compute_full_tree : 'auto' or bool, default='auto' + Stop early the construction of the tree at ``n_clusters``. This is + useful to decrease computation time if the number of clusters is not + small compared to the number of samples. This option is useful only + when specifying a connectivity matrix. Note also that when varying the + number of clusters and using caching, it may be advantageous to compute + the full tree. It must be ``True`` if ``distance_threshold`` is not + ``None``. By default `compute_full_tree` is "auto", which is equivalent + to `True` when `distance_threshold` is not `None` or that `n_clusters` + is inferior to the maximum between 100 or `0.02 * n_samples`. + Otherwise, "auto" is equivalent to `False`. + + linkage : {'ward', 'complete', 'average', 'single'}, default='ward' + Which linkage criterion to use. The linkage criterion determines which + distance to use between sets of observation. The algorithm will merge + the pairs of cluster that minimize this criterion. + + - 'ward' minimizes the variance of the clusters being merged. + - 'average' uses the average of the distances of each observation of + the two sets. + - 'complete' or 'maximum' linkage uses the maximum distances between + all observations of the two sets. + - 'single' uses the minimum of the distances between all observations + of the two sets. + + .. versionadded:: 0.20 + Added the 'single' option + + For examples comparing different `linkage` criteria, see + :ref:`sphx_glr_auto_examples_cluster_plot_linkage_comparison.py`. + + distance_threshold : float, default=None + The linkage distance threshold at or above which clusters will not be + merged. If not ``None``, ``n_clusters`` must be ``None`` and + ``compute_full_tree`` must be ``True``. + + .. versionadded:: 0.21 + + compute_distances : bool, default=False + Computes distances between clusters even if `distance_threshold` is not + used. This can be used to make dendrogram visualization, but introduces + a computational and memory overhead. + + .. versionadded:: 0.24 + + For an example of dendrogram visualization, see + :ref:`sphx_glr_auto_examples_cluster_plot_agglomerative_dendrogram.py`. + + Attributes + ---------- + n_clusters_ : int + The number of clusters found by the algorithm. If + ``distance_threshold=None``, it will be equal to the given + ``n_clusters``. + + labels_ : ndarray of shape (n_samples) + Cluster labels for each point. + + n_leaves_ : int + Number of leaves in the hierarchical tree. + + n_connected_components_ : int + The estimated number of connected components in the graph. + + .. versionadded:: 0.21 + ``n_connected_components_`` was added to replace ``n_components_``. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + children_ : array-like of shape (n_samples-1, 2) + The children of each non-leaf node. Values less than `n_samples` + correspond to leaves of the tree which are the original samples. + A node `i` greater than or equal to `n_samples` is a non-leaf + node and has children `children_[i - n_samples]`. Alternatively + at the i-th iteration, children[i][0] and children[i][1] + are merged to form node `n_samples + i`. + + distances_ : array-like of shape (n_nodes-1,) + Distances between nodes in the corresponding place in `children_`. + Only computed if `distance_threshold` is used or `compute_distances` + is set to `True`. + + See Also + -------- + FeatureAgglomeration : Agglomerative clustering but for features instead of + samples. + ward_tree : Hierarchical clustering with ward linkage. + + Examples + -------- + >>> from sklearn.cluster import AgglomerativeClustering + >>> import numpy as np + >>> X = np.array([[1, 2], [1, 4], [1, 0], + ... [4, 2], [4, 4], [4, 0]]) + >>> clustering = AgglomerativeClustering().fit(X) + >>> clustering + AgglomerativeClustering() + >>> clustering.labels_ + array([1, 1, 1, 0, 0, 0]) + + For a comparison of Agglomerative clustering with other clustering algorithms, see + :ref:`sphx_glr_auto_examples_cluster_plot_cluster_comparison.py` + """ + + _parameter_constraints: dict = { + "n_clusters": [Interval(Integral, 1, None, closed="left"), None], + "metric": [ + StrOptions(set(_VALID_METRICS) | {"precomputed"}), + callable, + ], + "memory": [str, HasMethods("cache"), None], + "connectivity": ["array-like", "sparse matrix", callable, None], + "compute_full_tree": [StrOptions({"auto"}), "boolean"], + "linkage": [StrOptions(set(_TREE_BUILDERS.keys()))], + "distance_threshold": [Interval(Real, 0, None, closed="left"), None], + "compute_distances": ["boolean"], + } + + def __init__( + self, + n_clusters=2, + *, + metric="euclidean", + memory=None, + connectivity=None, + compute_full_tree="auto", + linkage="ward", + distance_threshold=None, + compute_distances=False, + ): + self.n_clusters = n_clusters + self.distance_threshold = distance_threshold + self.memory = memory + self.connectivity = connectivity + self.compute_full_tree = compute_full_tree + self.linkage = linkage + self.metric = metric + self.compute_distances = compute_distances + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Fit the hierarchical clustering from features, or distance matrix. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) or \ + (n_samples, n_samples) + Training instances to cluster, or distances between instances if + ``metric='precomputed'``. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self : object + Returns the fitted instance. + """ + X = validate_data(self, X, ensure_min_samples=2) + return self._fit(X) + + def _fit(self, X): + """Fit without validation + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) or (n_samples, n_samples) + Training instances to cluster, or distances between instances if + ``metric='precomputed'``. + + Returns + ------- + self : object + Returns the fitted instance. + """ + memory = check_memory(self.memory) + + if not ((self.n_clusters is None) ^ (self.distance_threshold is None)): + raise ValueError( + "Exactly one of n_clusters and " + "distance_threshold has to be set, and the other " + "needs to be None." + ) + + if self.distance_threshold is not None and not self.compute_full_tree: + raise ValueError( + "compute_full_tree must be True if distance_threshold is set." + ) + + if self.linkage == "ward" and self.metric != "euclidean": + raise ValueError( + f"{self.metric} was provided as metric. Ward can only " + "work with euclidean distances." + ) + + tree_builder = _TREE_BUILDERS[self.linkage] + + connectivity = self.connectivity + if self.connectivity is not None: + if callable(self.connectivity): + connectivity = self.connectivity(X) + connectivity = check_array( + connectivity, accept_sparse=["csr", "coo", "lil"] + ) + + n_samples = len(X) + compute_full_tree = self.compute_full_tree + if self.connectivity is None: + compute_full_tree = True + if compute_full_tree == "auto": + if self.distance_threshold is not None: + compute_full_tree = True + else: + # Early stopping is likely to give a speed up only for + # a large number of clusters. The actual threshold + # implemented here is heuristic + compute_full_tree = self.n_clusters < max(100, 0.02 * n_samples) + n_clusters = self.n_clusters + if compute_full_tree: + n_clusters = None + + # Construct the tree + kwargs = {} + if self.linkage != "ward": + kwargs["linkage"] = self.linkage + kwargs["affinity"] = self.metric + + distance_threshold = self.distance_threshold + + return_distance = (distance_threshold is not None) or self.compute_distances + + out = memory.cache(tree_builder)( + X, + connectivity=connectivity, + n_clusters=n_clusters, + return_distance=return_distance, + **kwargs, + ) + (self.children_, self.n_connected_components_, self.n_leaves_, parents) = out[ + :4 + ] + + if return_distance: + self.distances_ = out[-1] + + if self.distance_threshold is not None: # distance_threshold is used + self.n_clusters_ = ( + np.count_nonzero(self.distances_ >= distance_threshold) + 1 + ) + else: # n_clusters is used + self.n_clusters_ = self.n_clusters + + # Cut the tree + if compute_full_tree: + self.labels_ = _hc_cut(self.n_clusters_, self.children_, self.n_leaves_) + else: + labels = _hierarchical.hc_get_heads(parents, copy=False) + # copy to avoid holding a reference on the original array + labels = np.copy(labels[:n_samples]) + # Reassign cluster numbers + self.labels_ = np.searchsorted(np.unique(labels), labels) + return self + + def fit_predict(self, X, y=None): + """Fit and return the result of each sample's clustering assignment. + + In addition to fitting, this method also return the result of the + clustering assignment for each sample in the training set. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) or \ + (n_samples, n_samples) + Training instances to cluster, or distances between instances if + ``affinity='precomputed'``. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Cluster labels. + """ + return super().fit_predict(X, y) + + +class FeatureAgglomeration( + ClassNamePrefixFeaturesOutMixin, AgglomerationTransform, AgglomerativeClustering +): + """Agglomerate features. + + Recursively merges pair of clusters of features. + + Refer to + :ref:`sphx_glr_auto_examples_cluster_plot_feature_agglomeration_vs_univariate_selection.py` + for an example comparison of :class:`FeatureAgglomeration` strategy with a + univariate feature selection strategy (based on ANOVA). + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_clusters : int or None, default=2 + The number of clusters to find. It must be ``None`` if + ``distance_threshold`` is not ``None``. + + metric : str or callable, default="euclidean" + Metric used to compute the linkage. Can be "euclidean", "l1", "l2", + "manhattan", "cosine", or "precomputed". If linkage is "ward", only + "euclidean" is accepted. If "precomputed", a distance matrix is needed + as input for the fit method. + + .. versionadded:: 1.2 + + memory : str or object with the joblib.Memory interface, default=None + Used to cache the output of the computation of the tree. + By default, no caching is done. If a string is given, it is the + path to the caching directory. + + connectivity : array-like, sparse matrix, or callable, default=None + Connectivity matrix. Defines for each feature the neighboring + features following a given structure of the data. + This can be a connectivity matrix itself or a callable that transforms + the data into a connectivity matrix, such as derived from + `kneighbors_graph`. Default is `None`, i.e, the + hierarchical clustering algorithm is unstructured. + + compute_full_tree : 'auto' or bool, default='auto' + Stop early the construction of the tree at `n_clusters`. This is useful + to decrease computation time if the number of clusters is not small + compared to the number of features. This option is useful only when + specifying a connectivity matrix. Note also that when varying the + number of clusters and using caching, it may be advantageous to compute + the full tree. It must be ``True`` if ``distance_threshold`` is not + ``None``. By default `compute_full_tree` is "auto", which is equivalent + to `True` when `distance_threshold` is not `None` or that `n_clusters` + is inferior to the maximum between 100 or `0.02 * n_samples`. + Otherwise, "auto" is equivalent to `False`. + + linkage : {"ward", "complete", "average", "single"}, default="ward" + Which linkage criterion to use. The linkage criterion determines which + distance to use between sets of features. The algorithm will merge + the pairs of cluster that minimize this criterion. + + - "ward" minimizes the variance of the clusters being merged. + - "complete" or maximum linkage uses the maximum distances between + all features of the two sets. + - "average" uses the average of the distances of each feature of + the two sets. + - "single" uses the minimum of the distances between all features + of the two sets. + + pooling_func : callable, default=np.mean + This combines the values of agglomerated features into a single + value, and should accept an array of shape [M, N] and the keyword + argument `axis=1`, and reduce it to an array of size [M]. + + distance_threshold : float, default=None + The linkage distance threshold at or above which clusters will not be + merged. If not ``None``, ``n_clusters`` must be ``None`` and + ``compute_full_tree`` must be ``True``. + + .. versionadded:: 0.21 + + compute_distances : bool, default=False + Computes distances between clusters even if `distance_threshold` is not + used. This can be used to make dendrogram visualization, but introduces + a computational and memory overhead. + + .. versionadded:: 0.24 + + Attributes + ---------- + n_clusters_ : int + The number of clusters found by the algorithm. If + ``distance_threshold=None``, it will be equal to the given + ``n_clusters``. + + labels_ : array-like of (n_features,) + Cluster labels for each feature. + + n_leaves_ : int + Number of leaves in the hierarchical tree. + + n_connected_components_ : int + The estimated number of connected components in the graph. + + .. versionadded:: 0.21 + ``n_connected_components_`` was added to replace ``n_components_``. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + children_ : array-like of shape (n_nodes-1, 2) + The children of each non-leaf node. Values less than `n_features` + correspond to leaves of the tree which are the original samples. + A node `i` greater than or equal to `n_features` is a non-leaf + node and has children `children_[i - n_features]`. Alternatively + at the i-th iteration, children[i][0] and children[i][1] + are merged to form node `n_features + i`. + + distances_ : array-like of shape (n_nodes-1,) + Distances between nodes in the corresponding place in `children_`. + Only computed if `distance_threshold` is used or `compute_distances` + is set to `True`. + + See Also + -------- + AgglomerativeClustering : Agglomerative clustering samples instead of + features. + ward_tree : Hierarchical clustering with ward linkage. + + Examples + -------- + >>> import numpy as np + >>> from sklearn import datasets, cluster + >>> digits = datasets.load_digits() + >>> images = digits.images + >>> X = np.reshape(images, (len(images), -1)) + >>> agglo = cluster.FeatureAgglomeration(n_clusters=32) + >>> agglo.fit(X) + FeatureAgglomeration(n_clusters=32) + >>> X_reduced = agglo.transform(X) + >>> X_reduced.shape + (1797, 32) + """ + + _parameter_constraints: dict = { + "n_clusters": [Interval(Integral, 1, None, closed="left"), None], + "metric": [ + StrOptions(set(_VALID_METRICS) | {"precomputed"}), + callable, + ], + "memory": [str, HasMethods("cache"), None], + "connectivity": ["array-like", "sparse matrix", callable, None], + "compute_full_tree": [StrOptions({"auto"}), "boolean"], + "linkage": [StrOptions(set(_TREE_BUILDERS.keys()))], + "pooling_func": [callable], + "distance_threshold": [Interval(Real, 0, None, closed="left"), None], + "compute_distances": ["boolean"], + } + + def __init__( + self, + n_clusters=2, + *, + metric="euclidean", + memory=None, + connectivity=None, + compute_full_tree="auto", + linkage="ward", + pooling_func=np.mean, + distance_threshold=None, + compute_distances=False, + ): + super().__init__( + n_clusters=n_clusters, + memory=memory, + connectivity=connectivity, + compute_full_tree=compute_full_tree, + linkage=linkage, + metric=metric, + distance_threshold=distance_threshold, + compute_distances=compute_distances, + ) + self.pooling_func = pooling_func + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Fit the hierarchical clustering on the data. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self : object + Returns the transformer. + """ + X = validate_data(self, X, ensure_min_features=2) + super()._fit(X.T) + self._n_features_out = self.n_clusters_ + return self + + @property + def fit_predict(self): + """Fit and return the result of each sample's clustering assignment.""" + raise AttributeError diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_bicluster.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_bicluster.py new file mode 100644 index 0000000000000000000000000000000000000000..04a4e68024d33350b9fdd844f6bc614e4c22f39a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_bicluster.py @@ -0,0 +1,621 @@ +"""Spectral biclustering algorithms.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from abc import ABCMeta, abstractmethod +from numbers import Integral + +import numpy as np +from scipy.linalg import norm +from scipy.sparse import dia_matrix, issparse +from scipy.sparse.linalg import eigsh, svds + +from ..base import BaseEstimator, BiclusterMixin, _fit_context +from ..utils import check_random_state, check_scalar +from ..utils._param_validation import Interval, StrOptions +from ..utils.extmath import _randomized_svd, make_nonnegative, safe_sparse_dot +from ..utils.validation import assert_all_finite, validate_data +from ._kmeans import KMeans, MiniBatchKMeans + +__all__ = ["SpectralBiclustering", "SpectralCoclustering"] + + +def _scale_normalize(X): + """Normalize ``X`` by scaling rows and columns independently. + + Returns the normalized matrix and the row and column scaling + factors. + """ + X = make_nonnegative(X) + row_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=1))).squeeze() + col_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=0))).squeeze() + row_diag = np.where(np.isnan(row_diag), 0, row_diag) + col_diag = np.where(np.isnan(col_diag), 0, col_diag) + if issparse(X): + n_rows, n_cols = X.shape + r = dia_matrix((row_diag, [0]), shape=(n_rows, n_rows)) + c = dia_matrix((col_diag, [0]), shape=(n_cols, n_cols)) + an = r @ X @ c + else: + an = row_diag[:, np.newaxis] * X * col_diag + return an, row_diag, col_diag + + +def _bistochastic_normalize(X, max_iter=1000, tol=1e-5): + """Normalize rows and columns of ``X`` simultaneously so that all + rows sum to one constant and all columns sum to a different + constant. + """ + # According to paper, this can also be done more efficiently with + # deviation reduction and balancing algorithms. + X = make_nonnegative(X) + X_scaled = X + for _ in range(max_iter): + X_new, _, _ = _scale_normalize(X_scaled) + if issparse(X): + dist = norm(X_scaled.data - X.data) + else: + dist = norm(X_scaled - X_new) + X_scaled = X_new + if dist is not None and dist < tol: + break + return X_scaled + + +def _log_normalize(X): + """Normalize ``X`` according to Kluger's log-interactions scheme.""" + X = make_nonnegative(X, min_value=1) + if issparse(X): + raise ValueError( + "Cannot compute log of a sparse matrix," + " because log(x) diverges to -infinity as x" + " goes to 0." + ) + L = np.log(X) + row_avg = L.mean(axis=1)[:, np.newaxis] + col_avg = L.mean(axis=0) + avg = L.mean() + return L - row_avg - col_avg + avg + + +class BaseSpectral(BiclusterMixin, BaseEstimator, metaclass=ABCMeta): + """Base class for spectral biclustering.""" + + _parameter_constraints: dict = { + "svd_method": [StrOptions({"randomized", "arpack"})], + "n_svd_vecs": [Interval(Integral, 0, None, closed="left"), None], + "mini_batch": ["boolean"], + "init": [StrOptions({"k-means++", "random"}), np.ndarray], + "n_init": [Interval(Integral, 1, None, closed="left")], + "random_state": ["random_state"], + } + + @abstractmethod + def __init__( + self, + n_clusters=3, + svd_method="randomized", + n_svd_vecs=None, + mini_batch=False, + init="k-means++", + n_init=10, + random_state=None, + ): + self.n_clusters = n_clusters + self.svd_method = svd_method + self.n_svd_vecs = n_svd_vecs + self.mini_batch = mini_batch + self.init = init + self.n_init = n_init + self.random_state = random_state + + @abstractmethod + def _check_parameters(self, n_samples): + """Validate parameters depending on the input data.""" + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Create a biclustering for X. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + self : object + SpectralBiclustering instance. + """ + X = validate_data(self, X, accept_sparse="csr", dtype=np.float64) + self._check_parameters(X.shape[0]) + self._fit(X) + return self + + def _svd(self, array, n_components, n_discard): + """Returns first `n_components` left and right singular + vectors u and v, discarding the first `n_discard`. + """ + if self.svd_method == "randomized": + kwargs = {} + if self.n_svd_vecs is not None: + kwargs["n_oversamples"] = self.n_svd_vecs + u, _, vt = _randomized_svd( + array, n_components, random_state=self.random_state, **kwargs + ) + + elif self.svd_method == "arpack": + u, _, vt = svds(array, k=n_components, ncv=self.n_svd_vecs) + if np.any(np.isnan(vt)): + # some eigenvalues of A * A.T are negative, causing + # sqrt() to be np.nan. This causes some vectors in vt + # to be np.nan. + A = safe_sparse_dot(array.T, array) + random_state = check_random_state(self.random_state) + # initialize with [-1,1] as in ARPACK + v0 = random_state.uniform(-1, 1, A.shape[0]) + _, v = eigsh(A, ncv=self.n_svd_vecs, v0=v0) + vt = v.T + if np.any(np.isnan(u)): + A = safe_sparse_dot(array, array.T) + random_state = check_random_state(self.random_state) + # initialize with [-1,1] as in ARPACK + v0 = random_state.uniform(-1, 1, A.shape[0]) + _, u = eigsh(A, ncv=self.n_svd_vecs, v0=v0) + + assert_all_finite(u) + assert_all_finite(vt) + u = u[:, n_discard:] + vt = vt[n_discard:] + return u, vt.T + + def _k_means(self, data, n_clusters): + if self.mini_batch: + model = MiniBatchKMeans( + n_clusters, + init=self.init, + n_init=self.n_init, + random_state=self.random_state, + ) + else: + model = KMeans( + n_clusters, + init=self.init, + n_init=self.n_init, + random_state=self.random_state, + ) + model.fit(data) + centroid = model.cluster_centers_ + labels = model.labels_ + return centroid, labels + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + return tags + + +class SpectralCoclustering(BaseSpectral): + """Spectral Co-Clustering algorithm (Dhillon, 2001). + + Clusters rows and columns of an array `X` to solve the relaxed + normalized cut of the bipartite graph created from `X` as follows: + the edge between row vertex `i` and column vertex `j` has weight + `X[i, j]`. + + The resulting bicluster structure is block-diagonal, since each + row and each column belongs to exactly one bicluster. + + Supports sparse matrices, as long as they are nonnegative. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_clusters : int, default=3 + The number of biclusters to find. + + svd_method : {'randomized', 'arpack'}, default='randomized' + Selects the algorithm for finding singular vectors. May be + 'randomized' or 'arpack'. If 'randomized', use + :func:`sklearn.utils.extmath.randomized_svd`, which may be faster + for large matrices. If 'arpack', use + :func:`scipy.sparse.linalg.svds`, which is more accurate, but + possibly slower in some cases. + + n_svd_vecs : int, default=None + Number of vectors to use in calculating the SVD. Corresponds + to `ncv` when `svd_method=arpack` and `n_oversamples` when + `svd_method` is 'randomized`. + + mini_batch : bool, default=False + Whether to use mini-batch k-means, which is faster but may get + different results. + + init : {'k-means++', 'random'}, or ndarray of shape \ + (n_clusters, n_features), default='k-means++' + Method for initialization of k-means algorithm; defaults to + 'k-means++'. + + n_init : int, default=10 + Number of random initializations that are tried with the + k-means algorithm. + + If mini-batch k-means is used, the best initialization is + chosen and the algorithm runs once. Otherwise, the algorithm + is run for each initialization and the best solution chosen. + + random_state : int, RandomState instance, default=None + Used for randomizing the singular value decomposition and the k-means + initialization. Use an int to make the randomness deterministic. + See :term:`Glossary `. + + Attributes + ---------- + rows_ : array-like of shape (n_row_clusters, n_rows) + Results of the clustering. `rows[i, r]` is True if + cluster `i` contains row `r`. Available only after calling ``fit``. + + columns_ : array-like of shape (n_column_clusters, n_columns) + Results of the clustering, like `rows`. + + row_labels_ : array-like of shape (n_rows,) + The bicluster label of each row. + + column_labels_ : array-like of shape (n_cols,) + The bicluster label of each column. + + biclusters_ : tuple of two ndarrays + The tuple contains the `rows_` and `columns_` arrays. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + SpectralBiclustering : Partitions rows and columns under the assumption + that the data has an underlying checkerboard structure. + + References + ---------- + * :doi:`Dhillon, Inderjit S, 2001. Co-clustering documents and words using + bipartite spectral graph partitioning. + <10.1145/502512.502550>` + + Examples + -------- + >>> from sklearn.cluster import SpectralCoclustering + >>> import numpy as np + >>> X = np.array([[1, 1], [2, 1], [1, 0], + ... [4, 7], [3, 5], [3, 6]]) + >>> clustering = SpectralCoclustering(n_clusters=2, random_state=0).fit(X) + >>> clustering.row_labels_ #doctest: +SKIP + array([0, 1, 1, 0, 0, 0], dtype=int32) + >>> clustering.column_labels_ #doctest: +SKIP + array([0, 0], dtype=int32) + >>> clustering + SpectralCoclustering(n_clusters=2, random_state=0) + + For a more detailed example, see the following: + :ref:`sphx_glr_auto_examples_bicluster_plot_spectral_coclustering.py`. + """ + + _parameter_constraints: dict = { + **BaseSpectral._parameter_constraints, + "n_clusters": [Interval(Integral, 1, None, closed="left")], + } + + def __init__( + self, + n_clusters=3, + *, + svd_method="randomized", + n_svd_vecs=None, + mini_batch=False, + init="k-means++", + n_init=10, + random_state=None, + ): + super().__init__( + n_clusters, svd_method, n_svd_vecs, mini_batch, init, n_init, random_state + ) + + def _check_parameters(self, n_samples): + if self.n_clusters > n_samples: + raise ValueError( + f"n_clusters should be <= n_samples={n_samples}. Got" + f" {self.n_clusters} instead." + ) + + def _fit(self, X): + normalized_data, row_diag, col_diag = _scale_normalize(X) + n_sv = 1 + int(np.ceil(np.log2(self.n_clusters))) + u, v = self._svd(normalized_data, n_sv, n_discard=1) + z = np.vstack((row_diag[:, np.newaxis] * u, col_diag[:, np.newaxis] * v)) + + _, labels = self._k_means(z, self.n_clusters) + + n_rows = X.shape[0] + self.row_labels_ = labels[:n_rows] + self.column_labels_ = labels[n_rows:] + + self.rows_ = np.vstack([self.row_labels_ == c for c in range(self.n_clusters)]) + self.columns_ = np.vstack( + [self.column_labels_ == c for c in range(self.n_clusters)] + ) + + +class SpectralBiclustering(BaseSpectral): + """Spectral biclustering (Kluger, 2003). + + Partitions rows and columns under the assumption that the data has + an underlying checkerboard structure. For instance, if there are + two row partitions and three column partitions, each row will + belong to three biclusters, and each column will belong to two + biclusters. The outer product of the corresponding row and column + label vectors gives this checkerboard structure. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_clusters : int or tuple (n_row_clusters, n_column_clusters), default=3 + The number of row and column clusters in the checkerboard + structure. + + method : {'bistochastic', 'scale', 'log'}, default='bistochastic' + Method of normalizing and converting singular vectors into + biclusters. May be one of 'scale', 'bistochastic', or 'log'. + The authors recommend using 'log'. If the data is sparse, + however, log normalization will not work, which is why the + default is 'bistochastic'. + + .. warning:: + if `method='log'`, the data must not be sparse. + + n_components : int, default=6 + Number of singular vectors to check. + + n_best : int, default=3 + Number of best singular vectors to which to project the data + for clustering. + + svd_method : {'randomized', 'arpack'}, default='randomized' + Selects the algorithm for finding singular vectors. May be + 'randomized' or 'arpack'. If 'randomized', uses + :func:`~sklearn.utils.extmath.randomized_svd`, which may be faster + for large matrices. If 'arpack', uses + `scipy.sparse.linalg.svds`, which is more accurate, but + possibly slower in some cases. + + n_svd_vecs : int, default=None + Number of vectors to use in calculating the SVD. Corresponds + to `ncv` when `svd_method=arpack` and `n_oversamples` when + `svd_method` is 'randomized`. + + mini_batch : bool, default=False + Whether to use mini-batch k-means, which is faster but may get + different results. + + init : {'k-means++', 'random'} or ndarray of shape (n_clusters, n_features), \ + default='k-means++' + Method for initialization of k-means algorithm; defaults to + 'k-means++'. + + n_init : int, default=10 + Number of random initializations that are tried with the + k-means algorithm. + + If mini-batch k-means is used, the best initialization is + chosen and the algorithm runs once. Otherwise, the algorithm + is run for each initialization and the best solution chosen. + + random_state : int, RandomState instance, default=None + Used for randomizing the singular value decomposition and the k-means + initialization. Use an int to make the randomness deterministic. + See :term:`Glossary `. + + Attributes + ---------- + rows_ : array-like of shape (n_row_clusters, n_rows) + Results of the clustering. `rows[i, r]` is True if + cluster `i` contains row `r`. Available only after calling ``fit``. + + columns_ : array-like of shape (n_column_clusters, n_columns) + Results of the clustering, like `rows`. + + row_labels_ : array-like of shape (n_rows,) + Row partition labels. + + column_labels_ : array-like of shape (n_cols,) + Column partition labels. + + biclusters_ : tuple of two ndarrays + The tuple contains the `rows_` and `columns_` arrays. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + SpectralCoclustering : Spectral Co-Clustering algorithm (Dhillon, 2001). + + References + ---------- + + * :doi:`Kluger, Yuval, et. al., 2003. Spectral biclustering of microarray + data: coclustering genes and conditions. + <10.1101/gr.648603>` + + Examples + -------- + >>> from sklearn.cluster import SpectralBiclustering + >>> import numpy as np + >>> X = np.array([[1, 1], [2, 1], [1, 0], + ... [4, 7], [3, 5], [3, 6]]) + >>> clustering = SpectralBiclustering(n_clusters=2, random_state=0).fit(X) + >>> clustering.row_labels_ + array([1, 1, 1, 0, 0, 0], dtype=int32) + >>> clustering.column_labels_ + array([1, 0], dtype=int32) + >>> clustering + SpectralBiclustering(n_clusters=2, random_state=0) + + For a more detailed example, see + :ref:`sphx_glr_auto_examples_bicluster_plot_spectral_biclustering.py` + """ + + _parameter_constraints: dict = { + **BaseSpectral._parameter_constraints, + "n_clusters": [Interval(Integral, 1, None, closed="left"), tuple], + "method": [StrOptions({"bistochastic", "scale", "log"})], + "n_components": [Interval(Integral, 1, None, closed="left")], + "n_best": [Interval(Integral, 1, None, closed="left")], + } + + def __init__( + self, + n_clusters=3, + *, + method="bistochastic", + n_components=6, + n_best=3, + svd_method="randomized", + n_svd_vecs=None, + mini_batch=False, + init="k-means++", + n_init=10, + random_state=None, + ): + super().__init__( + n_clusters, svd_method, n_svd_vecs, mini_batch, init, n_init, random_state + ) + self.method = method + self.n_components = n_components + self.n_best = n_best + + def _check_parameters(self, n_samples): + if isinstance(self.n_clusters, Integral): + if self.n_clusters > n_samples: + raise ValueError( + f"n_clusters should be <= n_samples={n_samples}. Got" + f" {self.n_clusters} instead." + ) + else: # tuple + try: + n_row_clusters, n_column_clusters = self.n_clusters + check_scalar( + n_row_clusters, + "n_row_clusters", + target_type=Integral, + min_val=1, + max_val=n_samples, + ) + check_scalar( + n_column_clusters, + "n_column_clusters", + target_type=Integral, + min_val=1, + max_val=n_samples, + ) + except (ValueError, TypeError) as e: + raise ValueError( + "Incorrect parameter n_clusters has value:" + f" {self.n_clusters}. It should either be a single integer" + " or an iterable with two integers:" + " (n_row_clusters, n_column_clusters)" + " And the values are should be in the" + " range: (1, n_samples)" + ) from e + + if self.n_best > self.n_components: + raise ValueError( + f"n_best={self.n_best} must be <= n_components={self.n_components}." + ) + + def _fit(self, X): + n_sv = self.n_components + if self.method == "bistochastic": + normalized_data = _bistochastic_normalize(X) + n_sv += 1 + elif self.method == "scale": + normalized_data, _, _ = _scale_normalize(X) + n_sv += 1 + elif self.method == "log": + normalized_data = _log_normalize(X) + n_discard = 0 if self.method == "log" else 1 + u, v = self._svd(normalized_data, n_sv, n_discard) + ut = u.T + vt = v.T + + try: + n_row_clusters, n_col_clusters = self.n_clusters + except TypeError: + n_row_clusters = n_col_clusters = self.n_clusters + + best_ut = self._fit_best_piecewise(ut, self.n_best, n_row_clusters) + + best_vt = self._fit_best_piecewise(vt, self.n_best, n_col_clusters) + + self.row_labels_ = self._project_and_cluster(X, best_vt.T, n_row_clusters) + + self.column_labels_ = self._project_and_cluster(X.T, best_ut.T, n_col_clusters) + + self.rows_ = np.vstack( + [ + self.row_labels_ == label + for label in range(n_row_clusters) + for _ in range(n_col_clusters) + ] + ) + self.columns_ = np.vstack( + [ + self.column_labels_ == label + for _ in range(n_row_clusters) + for label in range(n_col_clusters) + ] + ) + + def _fit_best_piecewise(self, vectors, n_best, n_clusters): + """Find the ``n_best`` vectors that are best approximated by piecewise + constant vectors. + + The piecewise vectors are found by k-means; the best is chosen + according to Euclidean distance. + + """ + + def make_piecewise(v): + centroid, labels = self._k_means(v.reshape(-1, 1), n_clusters) + return centroid[labels].ravel() + + piecewise_vectors = np.apply_along_axis(make_piecewise, axis=1, arr=vectors) + dists = np.apply_along_axis(norm, axis=1, arr=(vectors - piecewise_vectors)) + result = vectors[np.argsort(dists)[:n_best]] + return result + + def _project_and_cluster(self, data, vectors, n_clusters): + """Project ``data`` to ``vectors`` and cluster the result.""" + projected = safe_sparse_dot(data, vectors) + _, labels = self._k_means(projected, n_clusters) + return labels diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_birch.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_birch.py new file mode 100644 index 0000000000000000000000000000000000000000..4c894a644c8bc8b96b1c285358fd6a9cbf803a47 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_birch.py @@ -0,0 +1,749 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from math import sqrt +from numbers import Integral, Real + +import numpy as np +from scipy import sparse + +from .._config import config_context +from ..base import ( + BaseEstimator, + ClassNamePrefixFeaturesOutMixin, + ClusterMixin, + TransformerMixin, + _fit_context, +) +from ..exceptions import ConvergenceWarning +from ..metrics import pairwise_distances_argmin +from ..metrics.pairwise import euclidean_distances +from ..utils._param_validation import Hidden, Interval, StrOptions +from ..utils.extmath import row_norms +from ..utils.validation import check_is_fitted, validate_data +from . import AgglomerativeClustering + + +def _iterate_sparse_X(X): + """This little hack returns a densified row when iterating over a sparse + matrix, instead of constructing a sparse matrix for every row that is + expensive. + """ + n_samples = X.shape[0] + X_indices = X.indices + X_data = X.data + X_indptr = X.indptr + + for i in range(n_samples): + row = np.zeros(X.shape[1]) + startptr, endptr = X_indptr[i], X_indptr[i + 1] + nonzero_indices = X_indices[startptr:endptr] + row[nonzero_indices] = X_data[startptr:endptr] + yield row + + +def _split_node(node, threshold, branching_factor): + """The node has to be split if there is no place for a new subcluster + in the node. + 1. Two empty nodes and two empty subclusters are initialized. + 2. The pair of distant subclusters are found. + 3. The properties of the empty subclusters and nodes are updated + according to the nearest distance between the subclusters to the + pair of distant subclusters. + 4. The two nodes are set as children to the two subclusters. + """ + new_subcluster1 = _CFSubcluster() + new_subcluster2 = _CFSubcluster() + new_node1 = _CFNode( + threshold=threshold, + branching_factor=branching_factor, + is_leaf=node.is_leaf, + n_features=node.n_features, + dtype=node.init_centroids_.dtype, + ) + new_node2 = _CFNode( + threshold=threshold, + branching_factor=branching_factor, + is_leaf=node.is_leaf, + n_features=node.n_features, + dtype=node.init_centroids_.dtype, + ) + new_subcluster1.child_ = new_node1 + new_subcluster2.child_ = new_node2 + + if node.is_leaf: + if node.prev_leaf_ is not None: + node.prev_leaf_.next_leaf_ = new_node1 + new_node1.prev_leaf_ = node.prev_leaf_ + new_node1.next_leaf_ = new_node2 + new_node2.prev_leaf_ = new_node1 + new_node2.next_leaf_ = node.next_leaf_ + if node.next_leaf_ is not None: + node.next_leaf_.prev_leaf_ = new_node2 + + dist = euclidean_distances( + node.centroids_, Y_norm_squared=node.squared_norm_, squared=True + ) + n_clusters = dist.shape[0] + + farthest_idx = np.unravel_index(dist.argmax(), (n_clusters, n_clusters)) + node1_dist, node2_dist = dist[(farthest_idx,)] + + node1_closer = node1_dist < node2_dist + # make sure node1 is closest to itself even if all distances are equal. + # This can only happen when all node.centroids_ are duplicates leading to all + # distances between centroids being zero. + node1_closer[farthest_idx[0]] = True + + for idx, subcluster in enumerate(node.subclusters_): + if node1_closer[idx]: + new_node1.append_subcluster(subcluster) + new_subcluster1.update(subcluster) + else: + new_node2.append_subcluster(subcluster) + new_subcluster2.update(subcluster) + return new_subcluster1, new_subcluster2 + + +class _CFNode: + """Each node in a CFTree is called a CFNode. + + The CFNode can have a maximum of branching_factor + number of CFSubclusters. + + Parameters + ---------- + threshold : float + Threshold needed for a new subcluster to enter a CFSubcluster. + + branching_factor : int + Maximum number of CF subclusters in each node. + + is_leaf : bool + We need to know if the CFNode is a leaf or not, in order to + retrieve the final subclusters. + + n_features : int + The number of features. + + Attributes + ---------- + subclusters_ : list + List of subclusters for a particular CFNode. + + prev_leaf_ : _CFNode + Useful only if is_leaf is True. + + next_leaf_ : _CFNode + next_leaf. Useful only if is_leaf is True. + the final subclusters. + + init_centroids_ : ndarray of shape (branching_factor + 1, n_features) + Manipulate ``init_centroids_`` throughout rather than centroids_ since + the centroids are just a view of the ``init_centroids_`` . + + init_sq_norm_ : ndarray of shape (branching_factor + 1,) + manipulate init_sq_norm_ throughout. similar to ``init_centroids_``. + + centroids_ : ndarray of shape (branching_factor + 1, n_features) + View of ``init_centroids_``. + + squared_norm_ : ndarray of shape (branching_factor + 1,) + View of ``init_sq_norm_``. + + """ + + def __init__(self, *, threshold, branching_factor, is_leaf, n_features, dtype): + self.threshold = threshold + self.branching_factor = branching_factor + self.is_leaf = is_leaf + self.n_features = n_features + + # The list of subclusters, centroids and squared norms + # to manipulate throughout. + self.subclusters_ = [] + self.init_centroids_ = np.zeros((branching_factor + 1, n_features), dtype=dtype) + self.init_sq_norm_ = np.zeros((branching_factor + 1), dtype) + self.squared_norm_ = [] + self.prev_leaf_ = None + self.next_leaf_ = None + + def append_subcluster(self, subcluster): + n_samples = len(self.subclusters_) + self.subclusters_.append(subcluster) + self.init_centroids_[n_samples] = subcluster.centroid_ + self.init_sq_norm_[n_samples] = subcluster.sq_norm_ + + # Keep centroids and squared norm as views. In this way + # if we change init_centroids and init_sq_norm_, it is + # sufficient, + self.centroids_ = self.init_centroids_[: n_samples + 1, :] + self.squared_norm_ = self.init_sq_norm_[: n_samples + 1] + + def update_split_subclusters(self, subcluster, new_subcluster1, new_subcluster2): + """Remove a subcluster from a node and update it with the + split subclusters. + """ + ind = self.subclusters_.index(subcluster) + self.subclusters_[ind] = new_subcluster1 + self.init_centroids_[ind] = new_subcluster1.centroid_ + self.init_sq_norm_[ind] = new_subcluster1.sq_norm_ + self.append_subcluster(new_subcluster2) + + def insert_cf_subcluster(self, subcluster): + """Insert a new subcluster into the node.""" + if not self.subclusters_: + self.append_subcluster(subcluster) + return False + + threshold = self.threshold + branching_factor = self.branching_factor + # We need to find the closest subcluster among all the + # subclusters so that we can insert our new subcluster. + dist_matrix = np.dot(self.centroids_, subcluster.centroid_) + dist_matrix *= -2.0 + dist_matrix += self.squared_norm_ + closest_index = np.argmin(dist_matrix) + closest_subcluster = self.subclusters_[closest_index] + + # If the subcluster has a child, we need a recursive strategy. + if closest_subcluster.child_ is not None: + split_child = closest_subcluster.child_.insert_cf_subcluster(subcluster) + + if not split_child: + # If it is determined that the child need not be split, we + # can just update the closest_subcluster + closest_subcluster.update(subcluster) + self.init_centroids_[closest_index] = self.subclusters_[ + closest_index + ].centroid_ + self.init_sq_norm_[closest_index] = self.subclusters_[ + closest_index + ].sq_norm_ + return False + + # things not too good. we need to redistribute the subclusters in + # our child node, and add a new subcluster in the parent + # subcluster to accommodate the new child. + else: + new_subcluster1, new_subcluster2 = _split_node( + closest_subcluster.child_, + threshold, + branching_factor, + ) + self.update_split_subclusters( + closest_subcluster, new_subcluster1, new_subcluster2 + ) + + if len(self.subclusters_) > self.branching_factor: + return True + return False + + # good to go! + else: + merged = closest_subcluster.merge_subcluster(subcluster, self.threshold) + if merged: + self.init_centroids_[closest_index] = closest_subcluster.centroid_ + self.init_sq_norm_[closest_index] = closest_subcluster.sq_norm_ + return False + + # not close to any other subclusters, and we still + # have space, so add. + elif len(self.subclusters_) < self.branching_factor: + self.append_subcluster(subcluster) + return False + + # We do not have enough space nor is it closer to an + # other subcluster. We need to split. + else: + self.append_subcluster(subcluster) + return True + + +class _CFSubcluster: + """Each subcluster in a CFNode is called a CFSubcluster. + + A CFSubcluster can have a CFNode has its child. + + Parameters + ---------- + linear_sum : ndarray of shape (n_features,), default=None + Sample. This is kept optional to allow initialization of empty + subclusters. + + Attributes + ---------- + n_samples_ : int + Number of samples that belong to each subcluster. + + linear_sum_ : ndarray + Linear sum of all the samples in a subcluster. Prevents holding + all sample data in memory. + + squared_sum_ : float + Sum of the squared l2 norms of all samples belonging to a subcluster. + + centroid_ : ndarray of shape (branching_factor + 1, n_features) + Centroid of the subcluster. Prevent recomputing of centroids when + ``CFNode.centroids_`` is called. + + child_ : _CFNode + Child Node of the subcluster. Once a given _CFNode is set as the child + of the _CFNode, it is set to ``self.child_``. + + sq_norm_ : ndarray of shape (branching_factor + 1,) + Squared norm of the subcluster. Used to prevent recomputing when + pairwise minimum distances are computed. + """ + + def __init__(self, *, linear_sum=None): + if linear_sum is None: + self.n_samples_ = 0 + self.squared_sum_ = 0.0 + self.centroid_ = self.linear_sum_ = 0 + else: + self.n_samples_ = 1 + self.centroid_ = self.linear_sum_ = linear_sum + self.squared_sum_ = self.sq_norm_ = np.dot( + self.linear_sum_, self.linear_sum_ + ) + self.child_ = None + + def update(self, subcluster): + self.n_samples_ += subcluster.n_samples_ + self.linear_sum_ += subcluster.linear_sum_ + self.squared_sum_ += subcluster.squared_sum_ + self.centroid_ = self.linear_sum_ / self.n_samples_ + self.sq_norm_ = np.dot(self.centroid_, self.centroid_) + + def merge_subcluster(self, nominee_cluster, threshold): + """Check if a cluster is worthy enough to be merged. If + yes then merge. + """ + new_ss = self.squared_sum_ + nominee_cluster.squared_sum_ + new_ls = self.linear_sum_ + nominee_cluster.linear_sum_ + new_n = self.n_samples_ + nominee_cluster.n_samples_ + new_centroid = (1 / new_n) * new_ls + new_sq_norm = np.dot(new_centroid, new_centroid) + + # The squared radius of the cluster is defined: + # r^2 = sum_i ||x_i - c||^2 / n + # with x_i the n points assigned to the cluster and c its centroid: + # c = sum_i x_i / n + # This can be expanded to: + # r^2 = sum_i ||x_i||^2 / n - 2 < sum_i x_i / n, c> + n ||c||^2 / n + # and therefore simplifies to: + # r^2 = sum_i ||x_i||^2 / n - ||c||^2 + sq_radius = new_ss / new_n - new_sq_norm + + if sq_radius <= threshold**2: + ( + self.n_samples_, + self.linear_sum_, + self.squared_sum_, + self.centroid_, + self.sq_norm_, + ) = (new_n, new_ls, new_ss, new_centroid, new_sq_norm) + return True + return False + + @property + def radius(self): + """Return radius of the subcluster""" + # Because of numerical issues, this could become negative + sq_radius = self.squared_sum_ / self.n_samples_ - self.sq_norm_ + return sqrt(max(0, sq_radius)) + + +class Birch( + ClassNamePrefixFeaturesOutMixin, ClusterMixin, TransformerMixin, BaseEstimator +): + """Implements the BIRCH clustering algorithm. + + It is a memory-efficient, online-learning algorithm provided as an + alternative to :class:`MiniBatchKMeans`. It constructs a tree + data structure with the cluster centroids being read off the leaf. + These can be either the final cluster centroids or can be provided as input + to another clustering algorithm such as :class:`AgglomerativeClustering`. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.16 + + Parameters + ---------- + threshold : float, default=0.5 + The radius of the subcluster obtained by merging a new sample and the + closest subcluster should be lesser than the threshold. Otherwise a new + subcluster is started. Setting this value to be very low promotes + splitting and vice-versa. + + branching_factor : int, default=50 + Maximum number of CF subclusters in each node. If a new samples enters + such that the number of subclusters exceed the branching_factor then + that node is split into two nodes with the subclusters redistributed + in each. The parent subcluster of that node is removed and two new + subclusters are added as parents of the 2 split nodes. + + n_clusters : int, instance of sklearn.cluster model or None, default=3 + Number of clusters after the final clustering step, which treats the + subclusters from the leaves as new samples. + + - `None` : the final clustering step is not performed and the + subclusters are returned as they are. + + - :mod:`sklearn.cluster` Estimator : If a model is provided, the model + is fit treating the subclusters as new samples and the initial data + is mapped to the label of the closest subcluster. + + - `int` : the model fit is :class:`AgglomerativeClustering` with + `n_clusters` set to be equal to the int. + + compute_labels : bool, default=True + Whether or not to compute labels for each fit. + + copy : bool, default=True + Whether or not to make a copy of the given data. If set to False, + the initial data will be overwritten. + + .. deprecated:: 1.6 + `copy` was deprecated in 1.6 and will be removed in 1.8. It has no effect + as the estimator does not perform in-place operations on the input data. + + Attributes + ---------- + root_ : _CFNode + Root of the CFTree. + + dummy_leaf_ : _CFNode + Start pointer to all the leaves. + + subcluster_centers_ : ndarray + Centroids of all subclusters read directly from the leaves. + + subcluster_labels_ : ndarray + Labels assigned to the centroids of the subclusters after + they are clustered globally. + + labels_ : ndarray of shape (n_samples,) + Array of labels assigned to the input data. + if partial_fit is used instead of fit, they are assigned to the + last batch of data. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + MiniBatchKMeans : Alternative implementation that does incremental updates + of the centers' positions using mini-batches. + + Notes + ----- + The tree data structure consists of nodes with each node consisting of + a number of subclusters. The maximum number of subclusters in a node + is determined by the branching factor. Each subcluster maintains a + linear sum, squared sum and the number of samples in that subcluster. + In addition, each subcluster can also have a node as its child, if the + subcluster is not a member of a leaf node. + + For a new point entering the root, it is merged with the subcluster closest + to it and the linear sum, squared sum and the number of samples of that + subcluster are updated. This is done recursively till the properties of + the leaf node are updated. + + See :ref:`sphx_glr_auto_examples_cluster_plot_birch_vs_minibatchkmeans.py` for a + comparison with :class:`~sklearn.cluster.MiniBatchKMeans`. + + References + ---------- + * Tian Zhang, Raghu Ramakrishnan, Maron Livny + BIRCH: An efficient data clustering method for large databases. + https://www.cs.sfu.ca/CourseCentral/459/han/papers/zhang96.pdf + + * Roberto Perdisci + JBirch - Java implementation of BIRCH clustering algorithm + https://code.google.com/archive/p/jbirch + + Examples + -------- + >>> from sklearn.cluster import Birch + >>> X = [[0, 1], [0.3, 1], [-0.3, 1], [0, -1], [0.3, -1], [-0.3, -1]] + >>> brc = Birch(n_clusters=None) + >>> brc.fit(X) + Birch(n_clusters=None) + >>> brc.predict(X) + array([0, 0, 0, 1, 1, 1]) + + For a comparison of the BIRCH clustering algorithm with other clustering algorithms, + see :ref:`sphx_glr_auto_examples_cluster_plot_cluster_comparison.py` + """ + + _parameter_constraints: dict = { + "threshold": [Interval(Real, 0.0, None, closed="neither")], + "branching_factor": [Interval(Integral, 1, None, closed="neither")], + "n_clusters": [None, ClusterMixin, Interval(Integral, 1, None, closed="left")], + "compute_labels": ["boolean"], + "copy": ["boolean", Hidden(StrOptions({"deprecated"}))], + } + + def __init__( + self, + *, + threshold=0.5, + branching_factor=50, + n_clusters=3, + compute_labels=True, + copy="deprecated", + ): + self.threshold = threshold + self.branching_factor = branching_factor + self.n_clusters = n_clusters + self.compute_labels = compute_labels + self.copy = copy + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """ + Build a CF Tree for the input data. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input data. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self + Fitted estimator. + """ + return self._fit(X, partial=False) + + def _fit(self, X, partial): + has_root = getattr(self, "root_", None) + first_call = not (partial and has_root) + + if self.copy != "deprecated" and first_call: + warnings.warn( + "`copy` was deprecated in 1.6 and will be removed in 1.8 since it " + "has no effect internally. Simply leave this parameter to its default " + "value to avoid this warning.", + FutureWarning, + ) + + X = validate_data( + self, + X, + accept_sparse="csr", + reset=first_call, + dtype=[np.float64, np.float32], + ) + threshold = self.threshold + branching_factor = self.branching_factor + + n_samples, n_features = X.shape + + # If partial_fit is called for the first time or fit is called, we + # start a new tree. + if first_call: + # The first root is the leaf. Manipulate this object throughout. + self.root_ = _CFNode( + threshold=threshold, + branching_factor=branching_factor, + is_leaf=True, + n_features=n_features, + dtype=X.dtype, + ) + + # To enable getting back subclusters. + self.dummy_leaf_ = _CFNode( + threshold=threshold, + branching_factor=branching_factor, + is_leaf=True, + n_features=n_features, + dtype=X.dtype, + ) + self.dummy_leaf_.next_leaf_ = self.root_ + self.root_.prev_leaf_ = self.dummy_leaf_ + + # Cannot vectorize. Enough to convince to use cython. + if not sparse.issparse(X): + iter_func = iter + else: + iter_func = _iterate_sparse_X + + for sample in iter_func(X): + subcluster = _CFSubcluster(linear_sum=sample) + split = self.root_.insert_cf_subcluster(subcluster) + + if split: + new_subcluster1, new_subcluster2 = _split_node( + self.root_, threshold, branching_factor + ) + del self.root_ + self.root_ = _CFNode( + threshold=threshold, + branching_factor=branching_factor, + is_leaf=False, + n_features=n_features, + dtype=X.dtype, + ) + self.root_.append_subcluster(new_subcluster1) + self.root_.append_subcluster(new_subcluster2) + + centroids = np.concatenate([leaf.centroids_ for leaf in self._get_leaves()]) + self.subcluster_centers_ = centroids + self._n_features_out = self.subcluster_centers_.shape[0] + + self._global_clustering(X) + return self + + def _get_leaves(self): + """ + Retrieve the leaves of the CF Node. + + Returns + ------- + leaves : list of shape (n_leaves,) + List of the leaf nodes. + """ + leaf_ptr = self.dummy_leaf_.next_leaf_ + leaves = [] + while leaf_ptr is not None: + leaves.append(leaf_ptr) + leaf_ptr = leaf_ptr.next_leaf_ + return leaves + + @_fit_context(prefer_skip_nested_validation=True) + def partial_fit(self, X=None, y=None): + """ + Online learning. Prevents rebuilding of CFTree from scratch. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features), \ + default=None + Input data. If X is not provided, only the global clustering + step is done. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self + Fitted estimator. + """ + if X is None: + # Perform just the final global clustering step. + self._global_clustering() + return self + else: + return self._fit(X, partial=True) + + def predict(self, X): + """ + Predict data using the ``centroids_`` of subclusters. + + Avoid computation of the row norms of X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input data. + + Returns + ------- + labels : ndarray of shape(n_samples,) + Labelled data. + """ + check_is_fitted(self) + X = validate_data(self, X, accept_sparse="csr", reset=False) + return self._predict(X) + + def _predict(self, X): + """Predict data using the ``centroids_`` of subclusters.""" + kwargs = {"Y_norm_squared": self._subcluster_norms} + + with config_context(assume_finite=True): + argmin = pairwise_distances_argmin( + X, self.subcluster_centers_, metric_kwargs=kwargs + ) + return self.subcluster_labels_[argmin] + + def transform(self, X): + """ + Transform X into subcluster centroids dimension. + + Each dimension represents the distance from the sample point to each + cluster centroid. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input data. + + Returns + ------- + X_trans : {array-like, sparse matrix} of shape (n_samples, n_clusters) + Transformed data. + """ + check_is_fitted(self) + X = validate_data(self, X, accept_sparse="csr", reset=False) + with config_context(assume_finite=True): + return euclidean_distances(X, self.subcluster_centers_) + + def _global_clustering(self, X=None): + """ + Global clustering for the subclusters obtained after fitting + """ + clusterer = self.n_clusters + centroids = self.subcluster_centers_ + compute_labels = (X is not None) and self.compute_labels + + # Preprocessing for the global clustering. + not_enough_centroids = False + if isinstance(clusterer, Integral): + clusterer = AgglomerativeClustering(n_clusters=self.n_clusters) + # There is no need to perform the global clustering step. + if len(centroids) < self.n_clusters: + not_enough_centroids = True + + # To use in predict to avoid recalculation. + self._subcluster_norms = row_norms(self.subcluster_centers_, squared=True) + + if clusterer is None or not_enough_centroids: + self.subcluster_labels_ = np.arange(len(centroids)) + if not_enough_centroids: + warnings.warn( + "Number of subclusters found (%d) by BIRCH is less " + "than (%d). Decrease the threshold." + % (len(centroids), self.n_clusters), + ConvergenceWarning, + ) + else: + # The global clustering step that clusters the subclusters of + # the leaves. It assumes the centroids of the subclusters as + # samples and finds the final centroids. + self.subcluster_labels_ = clusterer.fit_predict(self.subcluster_centers_) + + if compute_labels: + self.labels_ = self._predict(X) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.transformer_tags.preserves_dtype = ["float64", "float32"] + tags.input_tags.sparse = True + return tags diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_bisect_k_means.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_bisect_k_means.py new file mode 100644 index 0000000000000000000000000000000000000000..77e24adbf80848b13f36adc1151686746024bf25 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_bisect_k_means.py @@ -0,0 +1,543 @@ +"""Bisecting K-means clustering.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings + +import numpy as np +import scipy.sparse as sp + +from ..base import _fit_context +from ..utils._openmp_helpers import _openmp_effective_n_threads +from ..utils._param_validation import Integral, Interval, StrOptions +from ..utils.extmath import row_norms +from ..utils.validation import ( + _check_sample_weight, + check_is_fitted, + check_random_state, + validate_data, +) +from ._k_means_common import _inertia_dense, _inertia_sparse +from ._kmeans import ( + _BaseKMeans, + _kmeans_single_elkan, + _kmeans_single_lloyd, + _labels_inertia_threadpool_limit, +) + + +class _BisectingTree: + """Tree structure representing the hierarchical clusters of BisectingKMeans.""" + + def __init__(self, center, indices, score): + """Create a new cluster node in the tree. + + The node holds the center of this cluster and the indices of the data points + that belong to it. + """ + self.center = center + self.indices = indices + self.score = score + + self.left = None + self.right = None + + def split(self, labels, centers, scores): + """Split the cluster node into two subclusters.""" + self.left = _BisectingTree( + indices=self.indices[labels == 0], center=centers[0], score=scores[0] + ) + self.right = _BisectingTree( + indices=self.indices[labels == 1], center=centers[1], score=scores[1] + ) + + # reset the indices attribute to save memory + self.indices = None + + def get_cluster_to_bisect(self): + """Return the cluster node to bisect next. + + It's based on the score of the cluster, which can be either the number of + data points assigned to that cluster or the inertia of that cluster + (see `bisecting_strategy` for details). + """ + max_score = None + + for cluster_leaf in self.iter_leaves(): + if max_score is None or cluster_leaf.score > max_score: + max_score = cluster_leaf.score + best_cluster_leaf = cluster_leaf + + return best_cluster_leaf + + def iter_leaves(self): + """Iterate over all the cluster leaves in the tree.""" + if self.left is None: + yield self + else: + yield from self.left.iter_leaves() + yield from self.right.iter_leaves() + + +class BisectingKMeans(_BaseKMeans): + """Bisecting K-Means clustering. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.1 + + Parameters + ---------- + n_clusters : int, default=8 + The number of clusters to form as well as the number of + centroids to generate. + + init : {'k-means++', 'random'} or callable, default='random' + Method for initialization: + + 'k-means++' : selects initial cluster centers for k-mean + clustering in a smart way to speed up convergence. See section + Notes in k_init for more details. + + 'random': choose `n_clusters` observations (rows) at random from data + for the initial centroids. + + If a callable is passed, it should take arguments X, n_clusters and a + random state and return an initialization. + + n_init : int, default=1 + Number of time the inner k-means algorithm will be run with different + centroid seeds in each bisection. + That will result producing for each bisection best output of n_init + consecutive runs in terms of inertia. + + random_state : int, RandomState instance or None, default=None + Determines random number generation for centroid initialization + in inner K-Means. Use an int to make the randomness deterministic. + See :term:`Glossary `. + + max_iter : int, default=300 + Maximum number of iterations of the inner k-means algorithm at each + bisection. + + verbose : int, default=0 + Verbosity mode. + + tol : float, default=1e-4 + Relative tolerance with regards to Frobenius norm of the difference + in the cluster centers of two consecutive iterations to declare + convergence. Used in inner k-means algorithm at each bisection to pick + best possible clusters. + + copy_x : bool, default=True + When pre-computing distances it is more numerically accurate to center + the data first. If copy_x is True (default), then the original data is + not modified. If False, the original data is modified, and put back + before the function returns, but small numerical differences may be + introduced by subtracting and then adding the data mean. Note that if + the original data is not C-contiguous, a copy will be made even if + copy_x is False. If the original data is sparse, but not in CSR format, + a copy will be made even if copy_x is False. + + algorithm : {"lloyd", "elkan"}, default="lloyd" + Inner K-means algorithm used in bisection. + The classical EM-style algorithm is `"lloyd"`. + The `"elkan"` variation can be more efficient on some datasets with + well-defined clusters, by using the triangle inequality. However it's + more memory intensive due to the allocation of an extra array of shape + `(n_samples, n_clusters)`. + + bisecting_strategy : {"biggest_inertia", "largest_cluster"},\ + default="biggest_inertia" + Defines how bisection should be performed: + + - "biggest_inertia" means that BisectingKMeans will always check + all calculated cluster for cluster with biggest SSE + (Sum of squared errors) and bisect it. This approach concentrates on + precision, but may be costly in terms of execution time (especially for + larger amount of data points). + + - "largest_cluster" - BisectingKMeans will always split cluster with + largest amount of points assigned to it from all clusters + previously calculated. That should work faster than picking by SSE + ('biggest_inertia') and may produce similar results in most cases. + + Attributes + ---------- + cluster_centers_ : ndarray of shape (n_clusters, n_features) + Coordinates of cluster centers. If the algorithm stops before fully + converging (see ``tol`` and ``max_iter``), these will not be + consistent with ``labels_``. + + labels_ : ndarray of shape (n_samples,) + Labels of each point. + + inertia_ : float + Sum of squared distances of samples to their closest cluster center, + weighted by the sample weights if provided. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + See Also + -------- + KMeans : Original implementation of K-Means algorithm. + + Notes + ----- + It might be inefficient when n_cluster is less than 3, due to unnecessary + calculations for that case. + + Examples + -------- + >>> from sklearn.cluster import BisectingKMeans + >>> import numpy as np + >>> X = np.array([[1, 1], [10, 1], [3, 1], + ... [10, 0], [2, 1], [10, 2], + ... [10, 8], [10, 9], [10, 10]]) + >>> bisect_means = BisectingKMeans(n_clusters=3, random_state=0).fit(X) + >>> bisect_means.labels_ + array([0, 2, 0, 2, 0, 2, 1, 1, 1], dtype=int32) + >>> bisect_means.predict([[0, 0], [12, 3]]) + array([0, 2], dtype=int32) + >>> bisect_means.cluster_centers_ + array([[ 2., 1.], + [10., 9.], + [10., 1.]]) + + For a comparison between BisectingKMeans and K-Means refer to example + :ref:`sphx_glr_auto_examples_cluster_plot_bisect_kmeans.py`. + """ + + _parameter_constraints: dict = { + **_BaseKMeans._parameter_constraints, + "init": [StrOptions({"k-means++", "random"}), callable], + "n_init": [Interval(Integral, 1, None, closed="left")], + "copy_x": ["boolean"], + "algorithm": [StrOptions({"lloyd", "elkan"})], + "bisecting_strategy": [StrOptions({"biggest_inertia", "largest_cluster"})], + } + + def __init__( + self, + n_clusters=8, + *, + init="random", + n_init=1, + random_state=None, + max_iter=300, + verbose=0, + tol=1e-4, + copy_x=True, + algorithm="lloyd", + bisecting_strategy="biggest_inertia", + ): + super().__init__( + n_clusters=n_clusters, + init=init, + max_iter=max_iter, + verbose=verbose, + random_state=random_state, + tol=tol, + n_init=n_init, + ) + + self.copy_x = copy_x + self.algorithm = algorithm + self.bisecting_strategy = bisecting_strategy + + def _warn_mkl_vcomp(self, n_active_threads): + """Warn when vcomp and mkl are both present""" + warnings.warn( + "BisectingKMeans is known to have a memory leak on Windows " + "with MKL, when there are less chunks than available " + "threads. You can avoid it by setting the environment" + f" variable OMP_NUM_THREADS={n_active_threads}." + ) + + def _inertia_per_cluster(self, X, centers, labels, sample_weight): + """Calculate the sum of squared errors (inertia) per cluster. + + Parameters + ---------- + X : {ndarray, csr_matrix} of shape (n_samples, n_features) + The input samples. + + centers : ndarray of shape (n_clusters=2, n_features) + The cluster centers. + + labels : ndarray of shape (n_samples,) + Index of the cluster each sample belongs to. + + sample_weight : ndarray of shape (n_samples,) + The weights for each observation in X. + + Returns + ------- + inertia_per_cluster : ndarray of shape (n_clusters=2,) + Sum of squared errors (inertia) for each cluster. + """ + n_clusters = centers.shape[0] # = 2 since centers comes from a bisection + _inertia = _inertia_sparse if sp.issparse(X) else _inertia_dense + + inertia_per_cluster = np.empty(n_clusters) + for label in range(n_clusters): + inertia_per_cluster[label] = _inertia( + X, sample_weight, centers, labels, self._n_threads, single_label=label + ) + + return inertia_per_cluster + + def _bisect(self, X, x_squared_norms, sample_weight, cluster_to_bisect): + """Split a cluster into 2 subsclusters. + + Parameters + ---------- + X : {ndarray, csr_matrix} of shape (n_samples, n_features) + Training instances to cluster. + + x_squared_norms : ndarray of shape (n_samples,) + Squared euclidean norm of each data point. + + sample_weight : ndarray of shape (n_samples,) + The weights for each observation in X. + + cluster_to_bisect : _BisectingTree node object + The cluster node to split. + """ + X = X[cluster_to_bisect.indices] + x_squared_norms = x_squared_norms[cluster_to_bisect.indices] + sample_weight = sample_weight[cluster_to_bisect.indices] + + best_inertia = None + + # Split samples in X into 2 clusters. + # Repeating `n_init` times to obtain best clusters + for _ in range(self.n_init): + centers_init = self._init_centroids( + X, + x_squared_norms=x_squared_norms, + init=self.init, + random_state=self._random_state, + n_centroids=2, + sample_weight=sample_weight, + ) + + labels, inertia, centers, _ = self._kmeans_single( + X, + sample_weight, + centers_init, + max_iter=self.max_iter, + verbose=self.verbose, + tol=self.tol, + n_threads=self._n_threads, + ) + + # allow small tolerance on the inertia to accommodate for + # non-deterministic rounding errors due to parallel computation + if best_inertia is None or inertia < best_inertia * (1 - 1e-6): + best_labels = labels + best_centers = centers + best_inertia = inertia + + if self.verbose: + print(f"New centroids from bisection: {best_centers}") + + if self.bisecting_strategy == "biggest_inertia": + scores = self._inertia_per_cluster( + X, best_centers, best_labels, sample_weight + ) + else: # bisecting_strategy == "largest_cluster" + # Using minlength to make sure that we have the counts for both labels even + # if all samples are labelled 0. + scores = np.bincount(best_labels, minlength=2) + + cluster_to_bisect.split(best_labels, best_centers, scores) + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None, sample_weight=None): + """Compute bisecting k-means clustering. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + + Training instances to cluster. + + .. note:: The data will be converted to C ordering, + which will cause a memory copy + if the given data is not C-contiguous. + + y : Ignored + Not used, present here for API consistency by convention. + + sample_weight : array-like of shape (n_samples,), default=None + The weights for each observation in X. If None, all observations + are assigned equal weight. `sample_weight` is not used during + initialization if `init` is a callable. + + Returns + ------- + self + Fitted estimator. + """ + X = validate_data( + self, + X, + accept_sparse="csr", + dtype=[np.float64, np.float32], + order="C", + copy=self.copy_x, + accept_large_sparse=False, + ) + + self._check_params_vs_input(X) + + self._random_state = check_random_state(self.random_state) + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + self._n_threads = _openmp_effective_n_threads() + + if self.algorithm == "lloyd" or self.n_clusters == 1: + self._kmeans_single = _kmeans_single_lloyd + self._check_mkl_vcomp(X, X.shape[0]) + else: + self._kmeans_single = _kmeans_single_elkan + + # Subtract of mean of X for more accurate distance computations + if not sp.issparse(X): + self._X_mean = X.mean(axis=0) + X -= self._X_mean + + # Initialize the hierarchical clusters tree + self._bisecting_tree = _BisectingTree( + indices=np.arange(X.shape[0]), + center=X.mean(axis=0), + score=0, + ) + + x_squared_norms = row_norms(X, squared=True) + + for _ in range(self.n_clusters - 1): + # Chose cluster to bisect + cluster_to_bisect = self._bisecting_tree.get_cluster_to_bisect() + + # Split this cluster into 2 subclusters + self._bisect(X, x_squared_norms, sample_weight, cluster_to_bisect) + + # Aggregate final labels and centers from the bisecting tree + self.labels_ = np.full(X.shape[0], -1, dtype=np.int32) + self.cluster_centers_ = np.empty((self.n_clusters, X.shape[1]), dtype=X.dtype) + + for i, cluster_node in enumerate(self._bisecting_tree.iter_leaves()): + self.labels_[cluster_node.indices] = i + self.cluster_centers_[i] = cluster_node.center + cluster_node.label = i # label final clusters for future prediction + cluster_node.indices = None # release memory + + # Restore original data + if not sp.issparse(X): + X += self._X_mean + self.cluster_centers_ += self._X_mean + + _inertia = _inertia_sparse if sp.issparse(X) else _inertia_dense + self.inertia_ = _inertia( + X, sample_weight, self.cluster_centers_, self.labels_, self._n_threads + ) + + self._n_features_out = self.cluster_centers_.shape[0] + + return self + + def predict(self, X): + """Predict which cluster each sample in X belongs to. + + Prediction is made by going down the hierarchical tree + in searching of closest leaf cluster. + + In the vector quantization literature, `cluster_centers_` is called + the code book and each value returned by `predict` is the index of + the closest code in the code book. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + New data to predict. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Index of the cluster each sample belongs to. + """ + check_is_fitted(self) + + X = self._check_test_data(X) + x_squared_norms = row_norms(X, squared=True) + + # sample weights are unused but necessary in cython helpers + sample_weight = np.ones_like(x_squared_norms) + + labels = self._predict_recursive(X, sample_weight, self._bisecting_tree) + + return labels + + def _predict_recursive(self, X, sample_weight, cluster_node): + """Predict recursively by going down the hierarchical tree. + + Parameters + ---------- + X : {ndarray, csr_matrix} of shape (n_samples, n_features) + The data points, currently assigned to `cluster_node`, to predict between + the subclusters of this node. + + sample_weight : ndarray of shape (n_samples,) + The weights for each observation in X. + + cluster_node : _BisectingTree node object + The cluster node of the hierarchical tree. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Index of the cluster each sample belongs to. + """ + if cluster_node.left is None: + # This cluster has no subcluster. Labels are just the label of the cluster. + return np.full(X.shape[0], cluster_node.label, dtype=np.int32) + + # Determine if data points belong to the left or right subcluster + centers = np.vstack((cluster_node.left.center, cluster_node.right.center)) + if hasattr(self, "_X_mean"): + centers += self._X_mean + + cluster_labels = _labels_inertia_threadpool_limit( + X, + sample_weight, + centers, + self._n_threads, + return_inertia=False, + ) + mask = cluster_labels == 0 + + # Compute the labels for each subset of the data points. + labels = np.full(X.shape[0], -1, dtype=np.int32) + + labels[mask] = self._predict_recursive( + X[mask], sample_weight[mask], cluster_node.left + ) + + labels[~mask] = self._predict_recursive( + X[~mask], sample_weight[~mask], cluster_node.right + ) + + return labels + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + tags.transformer_tags.preserves_dtype = ["float64", "float32"] + return tags diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_dbscan.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_dbscan.py new file mode 100644 index 0000000000000000000000000000000000000000..857a332cc2371a6cbbcc8b69c21cd7e432ccbcc6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_dbscan.py @@ -0,0 +1,480 @@ +""" +DBSCAN: Density-Based Spatial Clustering of Applications with Noise +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from numbers import Integral, Real + +import numpy as np +from scipy import sparse + +from ..base import BaseEstimator, ClusterMixin, _fit_context +from ..metrics.pairwise import _VALID_METRICS +from ..neighbors import NearestNeighbors +from ..utils._param_validation import Interval, StrOptions, validate_params +from ..utils.validation import _check_sample_weight, validate_data +from ._dbscan_inner import dbscan_inner + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "sample_weight": ["array-like", None], + }, + prefer_skip_nested_validation=False, +) +def dbscan( + X, + eps=0.5, + *, + min_samples=5, + metric="minkowski", + metric_params=None, + algorithm="auto", + leaf_size=30, + p=2, + sample_weight=None, + n_jobs=None, +): + """Perform DBSCAN clustering from vector array or distance matrix. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse (CSR) matrix} of shape (n_samples, n_features) or \ + (n_samples, n_samples) + A feature array, or array of distances between samples if + ``metric='precomputed'``. + + eps : float, default=0.5 + The maximum distance between two samples for one to be considered + as in the neighborhood of the other. This is not a maximum bound + on the distances of points within a cluster. This is the most + important DBSCAN parameter to choose appropriately for your data set + and distance function. + + min_samples : int, default=5 + The number of samples (or total weight) in a neighborhood for a point + to be considered as a core point. This includes the point itself. + + metric : str or callable, default='minkowski' + The metric to use when calculating distance between instances in a + feature array. If metric is a string or callable, it must be one of + the options allowed by :func:`sklearn.metrics.pairwise_distances` for + its metric parameter. + If metric is "precomputed", X is assumed to be a distance matrix and + must be square during fit. + X may be a :term:`sparse graph `, + in which case only "nonzero" elements may be considered neighbors. + + metric_params : dict, default=None + Additional keyword arguments for the metric function. + + .. versionadded:: 0.19 + + algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto' + The algorithm to be used by the NearestNeighbors module + to compute pointwise distances and find nearest neighbors. + See NearestNeighbors module documentation for details. + + leaf_size : int, default=30 + Leaf size passed to BallTree or cKDTree. This can affect the speed + of the construction and query, as well as the memory required + to store the tree. The optimal value depends + on the nature of the problem. + + p : float, default=2 + The power of the Minkowski metric to be used to calculate distance + between points. + + sample_weight : array-like of shape (n_samples,), default=None + Weight of each sample, such that a sample with a weight of at least + ``min_samples`` is by itself a core sample; a sample with negative + weight may inhibit its eps-neighbor from being core. + Note that weights are absolute, and default to 1. + + n_jobs : int, default=None + The number of parallel jobs to run for neighbors search. ``None`` means + 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means + using all processors. See :term:`Glossary ` for more details. + If precomputed distance are used, parallel execution is not available + and thus n_jobs will have no effect. + + Returns + ------- + core_samples : ndarray of shape (n_core_samples,) + Indices of core samples. + + labels : ndarray of shape (n_samples,) + Cluster labels for each point. Noisy samples are given the label -1. + + See Also + -------- + DBSCAN : An estimator interface for this clustering algorithm. + OPTICS : A similar estimator interface clustering at multiple values of + eps. Our implementation is optimized for memory usage. + + Notes + ----- + For an example, see :ref:`sphx_glr_auto_examples_cluster_plot_dbscan.py`. + + This implementation bulk-computes all neighborhood queries, which increases + the memory complexity to O(n.d) where d is the average number of neighbors, + while original DBSCAN had memory complexity O(n). It may attract a higher + memory complexity when querying these nearest neighborhoods, depending + on the ``algorithm``. + + One way to avoid the query complexity is to pre-compute sparse + neighborhoods in chunks using + :func:`NearestNeighbors.radius_neighbors_graph + ` with + ``mode='distance'``, then using ``metric='precomputed'`` here. + + Another way to reduce memory and computation time is to remove + (near-)duplicate points and use ``sample_weight`` instead. + + :class:`~sklearn.cluster.OPTICS` provides a similar clustering with lower + memory usage. + + References + ---------- + Ester, M., H. P. Kriegel, J. Sander, and X. Xu, `"A Density-Based + Algorithm for Discovering Clusters in Large Spatial Databases with Noise" + `_. + In: Proceedings of the 2nd International Conference on Knowledge Discovery + and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996 + + Schubert, E., Sander, J., Ester, M., Kriegel, H. P., & Xu, X. (2017). + :doi:`"DBSCAN revisited, revisited: why and how you should (still) use DBSCAN." + <10.1145/3068335>` + ACM Transactions on Database Systems (TODS), 42(3), 19. + + Examples + -------- + >>> from sklearn.cluster import dbscan + >>> X = [[1, 2], [2, 2], [2, 3], [8, 7], [8, 8], [25, 80]] + >>> core_samples, labels = dbscan(X, eps=3, min_samples=2) + >>> core_samples + array([0, 1, 2, 3, 4]) + >>> labels + array([ 0, 0, 0, 1, 1, -1]) + """ + + est = DBSCAN( + eps=eps, + min_samples=min_samples, + metric=metric, + metric_params=metric_params, + algorithm=algorithm, + leaf_size=leaf_size, + p=p, + n_jobs=n_jobs, + ) + est.fit(X, sample_weight=sample_weight) + return est.core_sample_indices_, est.labels_ + + +class DBSCAN(ClusterMixin, BaseEstimator): + """Perform DBSCAN clustering from vector array or distance matrix. + + DBSCAN - Density-Based Spatial Clustering of Applications with Noise. + Finds core samples of high density and expands clusters from them. + Good for data which contains clusters of similar density. + + This implementation has a worst case memory complexity of :math:`O({n}^2)`, + which can occur when the `eps` param is large and `min_samples` is low, + while the original DBSCAN only uses linear memory. + For further details, see the Notes below. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + eps : float, default=0.5 + The maximum distance between two samples for one to be considered + as in the neighborhood of the other. This is not a maximum bound + on the distances of points within a cluster. This is the most + important DBSCAN parameter to choose appropriately for your data set + and distance function. + + min_samples : int, default=5 + The number of samples (or total weight) in a neighborhood for a point to + be considered as a core point. This includes the point itself. If + `min_samples` is set to a higher value, DBSCAN will find denser clusters, + whereas if it is set to a lower value, the found clusters will be more + sparse. + + metric : str, or callable, default='euclidean' + The metric to use when calculating distance between instances in a + feature array. If metric is a string or callable, it must be one of + the options allowed by :func:`sklearn.metrics.pairwise_distances` for + its metric parameter. + If metric is "precomputed", X is assumed to be a distance matrix and + must be square. X may be a :term:`sparse graph`, in which + case only "nonzero" elements may be considered neighbors for DBSCAN. + + .. versionadded:: 0.17 + metric *precomputed* to accept precomputed sparse matrix. + + metric_params : dict, default=None + Additional keyword arguments for the metric function. + + .. versionadded:: 0.19 + + algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto' + The algorithm to be used by the NearestNeighbors module + to compute pointwise distances and find nearest neighbors. + See NearestNeighbors module documentation for details. + + leaf_size : int, default=30 + Leaf size passed to BallTree or cKDTree. This can affect the speed + of the construction and query, as well as the memory required + to store the tree. The optimal value depends + on the nature of the problem. + + p : float, default=None + The power of the Minkowski metric to be used to calculate distance + between points. If None, then ``p=2`` (equivalent to the Euclidean + distance). + + n_jobs : int, default=None + The number of parallel jobs to run. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + Attributes + ---------- + core_sample_indices_ : ndarray of shape (n_core_samples,) + Indices of core samples. + + components_ : ndarray of shape (n_core_samples, n_features) + Copy of each core sample found by training. + + labels_ : ndarray of shape (n_samples) + Cluster labels for each point in the dataset given to fit(). + Noisy samples are given the label -1. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + OPTICS : A similar clustering at multiple values of eps. Our implementation + is optimized for memory usage. + + Notes + ----- + This implementation bulk-computes all neighborhood queries, which increases + the memory complexity to O(n.d) where d is the average number of neighbors, + while original DBSCAN had memory complexity O(n). It may attract a higher + memory complexity when querying these nearest neighborhoods, depending + on the ``algorithm``. + + One way to avoid the query complexity is to pre-compute sparse + neighborhoods in chunks using + :func:`NearestNeighbors.radius_neighbors_graph + ` with + ``mode='distance'``, then using ``metric='precomputed'`` here. + + Another way to reduce memory and computation time is to remove + (near-)duplicate points and use ``sample_weight`` instead. + + :class:`~sklearn.cluster.OPTICS` provides a similar clustering with lower memory + usage. + + References + ---------- + Ester, M., H. P. Kriegel, J. Sander, and X. Xu, `"A Density-Based + Algorithm for Discovering Clusters in Large Spatial Databases with Noise" + `_. + In: Proceedings of the 2nd International Conference on Knowledge Discovery + and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996 + + Schubert, E., Sander, J., Ester, M., Kriegel, H. P., & Xu, X. (2017). + :doi:`"DBSCAN revisited, revisited: why and how you should (still) use DBSCAN." + <10.1145/3068335>` + ACM Transactions on Database Systems (TODS), 42(3), 19. + + Examples + -------- + >>> from sklearn.cluster import DBSCAN + >>> import numpy as np + >>> X = np.array([[1, 2], [2, 2], [2, 3], + ... [8, 7], [8, 8], [25, 80]]) + >>> clustering = DBSCAN(eps=3, min_samples=2).fit(X) + >>> clustering.labels_ + array([ 0, 0, 0, 1, 1, -1]) + >>> clustering + DBSCAN(eps=3, min_samples=2) + + For an example, see + :ref:`sphx_glr_auto_examples_cluster_plot_dbscan.py`. + + For a comparison of DBSCAN with other clustering algorithms, see + :ref:`sphx_glr_auto_examples_cluster_plot_cluster_comparison.py` + """ + + _parameter_constraints: dict = { + "eps": [Interval(Real, 0.0, None, closed="neither")], + "min_samples": [Interval(Integral, 1, None, closed="left")], + "metric": [ + StrOptions(set(_VALID_METRICS) | {"precomputed"}), + callable, + ], + "metric_params": [dict, None], + "algorithm": [StrOptions({"auto", "ball_tree", "kd_tree", "brute"})], + "leaf_size": [Interval(Integral, 1, None, closed="left")], + "p": [Interval(Real, 0.0, None, closed="left"), None], + "n_jobs": [Integral, None], + } + + def __init__( + self, + eps=0.5, + *, + min_samples=5, + metric="euclidean", + metric_params=None, + algorithm="auto", + leaf_size=30, + p=None, + n_jobs=None, + ): + self.eps = eps + self.min_samples = min_samples + self.metric = metric + self.metric_params = metric_params + self.algorithm = algorithm + self.leaf_size = leaf_size + self.p = p + self.n_jobs = n_jobs + + @_fit_context( + # DBSCAN.metric is not validated yet + prefer_skip_nested_validation=False + ) + def fit(self, X, y=None, sample_weight=None): + """Perform DBSCAN clustering from features, or distance matrix. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features), or \ + (n_samples, n_samples) + Training instances to cluster, or distances between instances if + ``metric='precomputed'``. If a sparse matrix is provided, it will + be converted into a sparse ``csr_matrix``. + + y : Ignored + Not used, present here for API consistency by convention. + + sample_weight : array-like of shape (n_samples,), default=None + Weight of each sample, such that a sample with a weight of at least + ``min_samples`` is by itself a core sample; a sample with a + negative weight may inhibit its eps-neighbor from being core. + Note that weights are absolute, and default to 1. + + Returns + ------- + self : object + Returns a fitted instance of self. + """ + X = validate_data(self, X, accept_sparse="csr") + + if sample_weight is not None: + sample_weight = _check_sample_weight(sample_weight, X) + + # Calculate neighborhood for all samples. This leaves the original + # point in, which needs to be considered later (i.e. point i is in the + # neighborhood of point i. While True, its useless information) + if self.metric == "precomputed" and sparse.issparse(X): + # set the diagonal to explicit values, as a point is its own + # neighbor + X = X.copy() # copy to avoid in-place modification + with warnings.catch_warnings(): + warnings.simplefilter("ignore", sparse.SparseEfficiencyWarning) + X.setdiag(X.diagonal()) + + neighbors_model = NearestNeighbors( + radius=self.eps, + algorithm=self.algorithm, + leaf_size=self.leaf_size, + metric=self.metric, + metric_params=self.metric_params, + p=self.p, + n_jobs=self.n_jobs, + ) + neighbors_model.fit(X) + # This has worst case O(n^2) memory complexity + neighborhoods = neighbors_model.radius_neighbors(X, return_distance=False) + + if sample_weight is None: + n_neighbors = np.array([len(neighbors) for neighbors in neighborhoods]) + else: + n_neighbors = np.array( + [np.sum(sample_weight[neighbors]) for neighbors in neighborhoods] + ) + + # Initially, all samples are noise. + labels = np.full(X.shape[0], -1, dtype=np.intp) + + # A list of all core samples found. + core_samples = np.asarray(n_neighbors >= self.min_samples, dtype=np.uint8) + dbscan_inner(core_samples, neighborhoods, labels) + + self.core_sample_indices_ = np.where(core_samples)[0] + self.labels_ = labels + + if len(self.core_sample_indices_): + # fix for scipy sparse indexing issue + self.components_ = X[self.core_sample_indices_].copy() + else: + # no core samples + self.components_ = np.empty((0, X.shape[1])) + return self + + def fit_predict(self, X, y=None, sample_weight=None): + """Compute clusters from a data or distance matrix and predict labels. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features), or \ + (n_samples, n_samples) + Training instances to cluster, or distances between instances if + ``metric='precomputed'``. If a sparse matrix is provided, it will + be converted into a sparse ``csr_matrix``. + + y : Ignored + Not used, present here for API consistency by convention. + + sample_weight : array-like of shape (n_samples,), default=None + Weight of each sample, such that a sample with a weight of at least + ``min_samples`` is by itself a core sample; a sample with a + negative weight may inhibit its eps-neighbor from being core. + Note that weights are absolute, and default to 1. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Cluster labels. Noisy samples are given the label -1. + """ + self.fit(X, sample_weight=sample_weight) + return self.labels_ + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.pairwise = self.metric == "precomputed" + tags.input_tags.sparse = True + return tags diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_dbscan_inner.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_dbscan_inner.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..ce45bf1d355ade266248a0f433e97bac698c22b8 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_dbscan_inner.cpython-310-x86_64-linux-gnu.so differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_dbscan_inner.pyx b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_dbscan_inner.pyx new file mode 100644 index 0000000000000000000000000000000000000000..266b214bb269a717fd2eea300fe7445b96bd7cba --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_dbscan_inner.pyx @@ -0,0 +1,41 @@ +# Fast inner loop for DBSCAN. + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from libcpp.vector cimport vector + +from ..utils._typedefs cimport uint8_t, intp_t + + +def dbscan_inner(const uint8_t[::1] is_core, + object[:] neighborhoods, + intp_t[::1] labels): + cdef intp_t i, label_num = 0, v + cdef intp_t[:] neighb + cdef vector[intp_t] stack + + for i in range(labels.shape[0]): + if labels[i] != -1 or not is_core[i]: + continue + + # Depth-first search starting from i, ending at the non-core points. + # This is very similar to the classic algorithm for computing connected + # components, the difference being that we label non-core points as + # part of a cluster (component), but don't expand their neighborhoods. + while True: + if labels[i] == -1: + labels[i] = label_num + if is_core[i]: + neighb = neighborhoods[i] + for i in range(neighb.shape[0]): + v = neighb[i] + if labels[v] == -1: + stack.push_back(v) + + if stack.size() == 0: + break + i = stack.back() + stack.pop_back() + + label_num += 1 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_feature_agglomeration.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_feature_agglomeration.py new file mode 100644 index 0000000000000000000000000000000000000000..32fcb85625f354bf0dcece88453e7e8f931e03cb --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_feature_agglomeration.py @@ -0,0 +1,76 @@ +""" +Feature agglomeration. Base classes and functions for performing feature +agglomeration. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numpy as np +from scipy.sparse import issparse + +from ..base import TransformerMixin +from ..utils.validation import check_is_fitted, validate_data + +############################################################################### +# Mixin class for feature agglomeration. + + +class AgglomerationTransform(TransformerMixin): + """ + A class for feature agglomeration via the transform interface. + """ + + def transform(self, X): + """ + Transform a new matrix using the built clustering. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) or \ + (n_samples, n_samples) + A M by N array of M observations in N dimensions or a length + M array of M one-dimensional observations. + + Returns + ------- + Y : ndarray of shape (n_samples, n_clusters) or (n_clusters,) + The pooled values for each feature cluster. + """ + check_is_fitted(self) + + X = validate_data(self, X, reset=False) + if self.pooling_func == np.mean and not issparse(X): + size = np.bincount(self.labels_) + n_samples = X.shape[0] + # a fast way to compute the mean of grouped features + nX = np.array( + [np.bincount(self.labels_, X[i, :]) / size for i in range(n_samples)] + ) + else: + nX = [ + self.pooling_func(X[:, self.labels_ == l], axis=1) + for l in np.unique(self.labels_) + ] + nX = np.array(nX).T + return nX + + def inverse_transform(self, X): + """ + Inverse the transformation and return a vector of size `n_features`. + + Parameters + ---------- + X : array-like of shape (n_samples, n_clusters) or (n_clusters,) + The values to be assigned to each cluster of samples. + + Returns + ------- + X_original : ndarray of shape (n_samples, n_features) or (n_features,) + A vector of size `n_samples` with the values of `X` assigned to + each of the cluster of samples. + """ + check_is_fitted(self) + + unil, inverse = np.unique(self.labels_, return_inverse=True) + return X[..., inverse] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..67dd18fb94b593f0a3125c1f5833f3b9597614ba --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/__init__.py @@ -0,0 +1,2 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/_linkage.pyx b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/_linkage.pyx new file mode 100644 index 0000000000000000000000000000000000000000..5684193a13d40ed68cabe9b8502a4b59b18d4e1b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/_linkage.pyx @@ -0,0 +1,274 @@ +# Minimum spanning tree single linkage implementation for hdbscan + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# 3. Neither the name of the copyright holder nor the names of its contributors +# may be used to endorse or promote products derived from this software without +# specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +cimport numpy as cnp +from libc.float cimport DBL_MAX + +import numpy as np +from ...metrics._dist_metrics cimport DistanceMetric64 +from ...cluster._hierarchical_fast cimport UnionFind +from ...cluster._hdbscan._tree cimport HIERARCHY_t +from ...cluster._hdbscan._tree import HIERARCHY_dtype +from ...utils._typedefs cimport intp_t, float64_t, int64_t, uint8_t + +cnp.import_array() + +cdef extern from "numpy/arrayobject.h": + intp_t * PyArray_SHAPE(cnp.PyArrayObject *) + +# Numpy structured dtype representing a single ordered edge in Prim's algorithm +MST_edge_dtype = np.dtype([ + ("current_node", np.int64), + ("next_node", np.int64), + ("distance", np.float64), +]) + +# Packed shouldn't make a difference since they're all 8-byte quantities, +# but it's included just to be safe. +ctypedef packed struct MST_edge_t: + int64_t current_node + int64_t next_node + float64_t distance + +cpdef cnp.ndarray[MST_edge_t, ndim=1, mode='c'] mst_from_mutual_reachability( + cnp.ndarray[float64_t, ndim=2] mutual_reachability +): + """Compute the Minimum Spanning Tree (MST) representation of the mutual- + reachability graph using Prim's algorithm. + + Parameters + ---------- + mutual_reachability : ndarray of shape (n_samples, n_samples) + Array of mutual-reachabilities between samples. + + Returns + ------- + mst : ndarray of shape (n_samples - 1,), dtype=MST_edge_dtype + The MST representation of the mutual-reachability graph. The MST is + represented as a collection of edges. + """ + cdef: + # Note: we utilize ndarray's over memory-views to make use of numpy + # binary indexing and sub-selection below. + cnp.ndarray[int64_t, ndim=1, mode='c'] current_labels + cnp.ndarray[float64_t, ndim=1, mode='c'] min_reachability, left, right + cnp.ndarray[MST_edge_t, ndim=1, mode='c'] mst + + cnp.ndarray[uint8_t, mode='c'] label_filter + + int64_t n_samples = PyArray_SHAPE( mutual_reachability)[0] + int64_t current_node, new_node_index, new_node, i + + mst = np.empty(n_samples - 1, dtype=MST_edge_dtype) + current_labels = np.arange(n_samples, dtype=np.int64) + current_node = 0 + min_reachability = np.full(n_samples, fill_value=np.inf, dtype=np.float64) + for i in range(0, n_samples - 1): + label_filter = current_labels != current_node + current_labels = current_labels[label_filter] + left = min_reachability[label_filter] + right = mutual_reachability[current_node][current_labels] + min_reachability = np.minimum(left, right) + + new_node_index = np.argmin(min_reachability) + new_node = current_labels[new_node_index] + mst[i].current_node = current_node + mst[i].next_node = new_node + mst[i].distance = min_reachability[new_node_index] + current_node = new_node + + return mst + + +cpdef cnp.ndarray[MST_edge_t, ndim=1, mode='c'] mst_from_data_matrix( + const float64_t[:, ::1] raw_data, + const float64_t[::1] core_distances, + DistanceMetric64 dist_metric, + float64_t alpha=1.0 +): + """Compute the Minimum Spanning Tree (MST) representation of the mutual- + reachability graph generated from the provided `raw_data` and + `core_distances` using Prim's algorithm. + + Parameters + ---------- + raw_data : ndarray of shape (n_samples, n_features) + Input array of data samples. + + core_distances : ndarray of shape (n_samples,) + An array containing the core-distance calculated for each corresponding + sample. + + dist_metric : DistanceMetric + The distance metric to use when calculating pairwise distances for + determining mutual-reachability. + + Returns + ------- + mst : ndarray of shape (n_samples - 1,), dtype=MST_edge_dtype + The MST representation of the mutual-reachability graph. The MST is + represented as a collection of edges. + """ + + cdef: + uint8_t[::1] in_tree + float64_t[::1] min_reachability + int64_t[::1] current_sources + cnp.ndarray[MST_edge_t, ndim=1, mode='c'] mst + + int64_t current_node, source_node, new_node, next_node_source + int64_t i, j, n_samples, num_features + + float64_t current_node_core_dist, new_reachability, mutual_reachability_distance + float64_t next_node_min_reach, pair_distance, next_node_core_dist + + n_samples = raw_data.shape[0] + num_features = raw_data.shape[1] + + mst = np.empty(n_samples - 1, dtype=MST_edge_dtype) + + in_tree = np.zeros(n_samples, dtype=np.uint8) + min_reachability = np.full(n_samples, fill_value=np.inf, dtype=np.float64) + current_sources = np.ones(n_samples, dtype=np.int64) + + current_node = 0 + + # The following loop dynamically updates minimum reachability node-by-node, + # avoiding unnecessary computation where possible. + for i in range(0, n_samples - 1): + + in_tree[current_node] = 1 + + current_node_core_dist = core_distances[current_node] + + new_reachability = DBL_MAX + source_node = 0 + new_node = 0 + + for j in range(n_samples): + if in_tree[j]: + continue + + next_node_min_reach = min_reachability[j] + next_node_source = current_sources[j] + + pair_distance = dist_metric.dist( + &raw_data[current_node, 0], + &raw_data[j, 0], + num_features + ) + + pair_distance /= alpha + + next_node_core_dist = core_distances[j] + mutual_reachability_distance = max( + current_node_core_dist, + next_node_core_dist, + pair_distance + ) + + # If MRD(i, j) is smaller than node j's min_reachability, we update + # node j's min_reachability for future reference. + if mutual_reachability_distance < next_node_min_reach: + min_reachability[j] = mutual_reachability_distance + current_sources[j] = current_node + + # If MRD(i, j) is also smaller than node i's current + # min_reachability, we update and set their edge as the current + # MST edge candidate. + if mutual_reachability_distance < new_reachability: + new_reachability = mutual_reachability_distance + source_node = current_node + new_node = j + + # If the node j is closer to another node already in the tree, we + # make their edge the current MST candidate edge. + elif next_node_min_reach < new_reachability: + new_reachability = next_node_min_reach + source_node = next_node_source + new_node = j + + mst[i].current_node = source_node + mst[i].next_node = new_node + mst[i].distance = new_reachability + current_node = new_node + + return mst + +cpdef cnp.ndarray[HIERARCHY_t, ndim=1, mode="c"] make_single_linkage(const MST_edge_t[::1] mst): + """Construct a single-linkage tree from an MST. + + Parameters + ---------- + mst : ndarray of shape (n_samples - 1,), dtype=MST_edge_dtype + The MST representation of the mutual-reachability graph. The MST is + represented as a collection of edges. + + Returns + ------- + single_linkage : ndarray of shape (n_samples - 1,), dtype=HIERARCHY_dtype + The single-linkage tree tree (dendrogram) built from the MST. Each + of the array represents the following: + + - left node/cluster + - right node/cluster + - distance + - new cluster size + """ + cdef: + cnp.ndarray[HIERARCHY_t, ndim=1, mode="c"] single_linkage + + # Note mst.shape[0] is one fewer than the number of samples + int64_t n_samples = mst.shape[0] + 1 + intp_t current_node_cluster, next_node_cluster + int64_t current_node, next_node, i + float64_t distance + UnionFind U = UnionFind(n_samples) + + single_linkage = np.zeros(n_samples - 1, dtype=HIERARCHY_dtype) + + for i in range(n_samples - 1): + + current_node = mst[i].current_node + next_node = mst[i].next_node + distance = mst[i].distance + + current_node_cluster = U.fast_find(current_node) + next_node_cluster = U.fast_find(next_node) + + single_linkage[i].left_node = current_node_cluster + single_linkage[i].right_node = next_node_cluster + single_linkage[i].value = distance + single_linkage[i].cluster_size = U.size[current_node_cluster] + U.size[next_node_cluster] + + U.union(current_node_cluster, next_node_cluster) + + return single_linkage diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/_reachability.pyx b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/_reachability.pyx new file mode 100644 index 0000000000000000000000000000000000000000..bff686ae0a6369a7891525433a3fd79341dd2022 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/_reachability.pyx @@ -0,0 +1,210 @@ +# mutual reachability distance computations + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# 3. Neither the name of the copyright holder nor the names of its contributors +# may be used to endorse or promote products derived from this software without +# specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +cimport numpy as cnp + +import numpy as np +from scipy.sparse import issparse +from cython cimport floating, integral +from libc.math cimport isfinite, INFINITY +from ...utils._typedefs cimport intp_t +cnp.import_array() + + +def mutual_reachability_graph( + distance_matrix, min_samples=5, max_distance=0.0 +): + """Compute the weighted adjacency matrix of the mutual reachability graph. + + The mutual reachability distance used to build the graph is defined as:: + + max(d_core(x_p), d_core(x_q), d(x_p, x_q)) + + and the core distance `d_core` is defined as the distance between a point + `x_p` and its k-th nearest neighbor. + + Note that all computations are done in-place. + + Parameters + ---------- + distance_matrix : {ndarray, sparse matrix} of shape (n_samples, n_samples) + Array of distances between samples. If sparse, the array must be in + `CSR` format. + + min_samples : int, default=5 + The parameter `k` used to calculate the distance between a point + `x_p` and its k-th nearest neighbor. + + max_distance : float, default=0.0 + The distance which `np.inf` is replaced with. When the true mutual- + reachability distance is measured to be infinite, it is instead + truncated to `max_dist`. Only used when `distance_matrix` is a sparse + matrix. + + Returns + ------- + mututal_reachability_graph: {ndarray, sparse matrix} of shape \ + (n_samples, n_samples) + Weighted adjacency matrix of the mutual reachability graph. + + References + ---------- + .. [1] Campello, R. J., Moulavi, D., & Sander, J. (2013, April). + Density-based clustering based on hierarchical density estimates. + In Pacific-Asia Conference on Knowledge Discovery and Data Mining + (pp. 160-172). Springer Berlin Heidelberg. + """ + further_neighbor_idx = min_samples - 1 + if issparse(distance_matrix): + if distance_matrix.format != "csr": + raise ValueError( + "Only sparse CSR matrices are supported for `distance_matrix`." + ) + _sparse_mutual_reachability_graph( + distance_matrix.data, + distance_matrix.indices, + distance_matrix.indptr, + distance_matrix.shape[0], + further_neighbor_idx=further_neighbor_idx, + max_distance=max_distance, + ) + else: + _dense_mutual_reachability_graph( + distance_matrix, further_neighbor_idx=further_neighbor_idx + ) + return distance_matrix + + +def _dense_mutual_reachability_graph( + floating[:, :] distance_matrix, + intp_t further_neighbor_idx, +): + """Dense implementation of mutual reachability graph. + + The computation is done in-place, i.e. the distance matrix is modified + directly. + + Parameters + ---------- + distance_matrix : ndarray of shape (n_samples, n_samples) + Array of distances between samples. + + further_neighbor_idx : int + The index of the furthest neighbor to use to define the core distances. + """ + cdef: + intp_t i, j, n_samples = distance_matrix.shape[0] + floating mutual_reachability_distance + floating[::1] core_distances + + # We assume that the distance matrix is symmetric. We choose to sort every + # row to have the same implementation than the sparse case that requires + # CSR matrix. + core_distances = np.ascontiguousarray( + np.partition( + distance_matrix, further_neighbor_idx, axis=1 + )[:, further_neighbor_idx] + ) + + with nogil: + # TODO: Update w/ prange with thread count based on + # _openmp_effective_n_threads + for i in range(n_samples): + for j in range(n_samples): + mutual_reachability_distance = max( + core_distances[i], + core_distances[j], + distance_matrix[i, j], + ) + distance_matrix[i, j] = mutual_reachability_distance + + +def _sparse_mutual_reachability_graph( + cnp.ndarray[floating, ndim=1, mode="c"] data, + cnp.ndarray[integral, ndim=1, mode="c"] indices, + cnp.ndarray[integral, ndim=1, mode="c"] indptr, + intp_t n_samples, + intp_t further_neighbor_idx, + floating max_distance, +): + """Sparse implementation of mutual reachability graph. + + The computation is done in-place, i.e. the distance matrix is modified + directly. This implementation only accepts `CSR` format sparse matrices. + + Parameters + ---------- + distance_matrix : sparse matrix of shape (n_samples, n_samples) + Sparse matrix of distances between samples. The sparse format should + be `CSR`. + + further_neighbor_idx : int + The index of the furthest neighbor to use to define the core distances. + + max_distance : float + The distance which `np.inf` is replaced with. When the true mutual- + reachability distance is measured to be infinite, it is instead + truncated to `max_dist`. Only used when `distance_matrix` is a sparse + matrix. + """ + cdef: + integral i, col_ind, row_ind + floating mutual_reachability_distance + floating[:] core_distances + floating[:] row_data + + if floating is float: + dtype = np.float32 + else: + dtype = np.float64 + + core_distances = np.empty(n_samples, dtype=dtype) + + for i in range(n_samples): + row_data = data[indptr[i]:indptr[i + 1]] + if further_neighbor_idx < row_data.size: + core_distances[i] = np.partition( + row_data, further_neighbor_idx + )[further_neighbor_idx] + else: + core_distances[i] = INFINITY + + with nogil: + for row_ind in range(n_samples): + for i in range(indptr[row_ind], indptr[row_ind + 1]): + col_ind = indices[i] + mutual_reachability_distance = max( + core_distances[row_ind], core_distances[col_ind], data[i] + ) + if isfinite(mutual_reachability_distance): + data[i] = mutual_reachability_distance + elif max_distance > 0: + data[i] = max_distance diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/_tree.pxd b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/_tree.pxd new file mode 100644 index 0000000000000000000000000000000000000000..23708b9a38d07884c035b88e260821146075f861 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/_tree.pxd @@ -0,0 +1,49 @@ +# Copyright (c) 2015, Leland McInnes +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# 3. Neither the name of the copyright holder nor the names of its contributors +# may be used to endorse or promote products derived from this software without +# specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +from ...utils._typedefs cimport intp_t, float64_t, uint8_t +cimport numpy as cnp + +# This corresponds to the scipy.cluster.hierarchy format +ctypedef packed struct HIERARCHY_t: + intp_t left_node + intp_t right_node + float64_t value + intp_t cluster_size + +# Effectively an edgelist encoding a parent/child pair, along with a value and +# the corresponding cluster_size in each row providing a tree structure. +ctypedef packed struct CONDENSED_t: + intp_t parent + intp_t child + float64_t value + intp_t cluster_size + +cdef extern from "numpy/arrayobject.h": + intp_t * PyArray_SHAPE(cnp.PyArrayObject *) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/_tree.pyx b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/_tree.pyx new file mode 100644 index 0000000000000000000000000000000000000000..161092033b915bd9bb51f87750fb156c6a598833 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/_tree.pyx @@ -0,0 +1,799 @@ +# Tree handling (condensing, finding stable clusters) for hdbscan + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# 3. Neither the name of the copyright holder nor the names of its contributors +# may be used to endorse or promote products derived from this software without +# specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + + +cimport numpy as cnp +from libc.math cimport isinf +import cython + +import numpy as np + +cnp.import_array() + +cdef extern from "numpy/arrayobject.h": + intp_t * PyArray_SHAPE(cnp.PyArrayObject *) + +cdef cnp.float64_t INFTY = np.inf +cdef cnp.intp_t NOISE = -1 + +HIERARCHY_dtype = np.dtype([ + ("left_node", np.intp), + ("right_node", np.intp), + ("value", np.float64), + ("cluster_size", np.intp), +]) + +CONDENSED_dtype = np.dtype([ + ("parent", np.intp), + ("child", np.intp), + ("value", np.float64), + ("cluster_size", np.intp), +]) + +cpdef tuple tree_to_labels( + const HIERARCHY_t[::1] single_linkage_tree, + cnp.intp_t min_cluster_size=10, + cluster_selection_method="eom", + bint allow_single_cluster=False, + cnp.float64_t cluster_selection_epsilon=0.0, + max_cluster_size=None, +): + cdef: + cnp.ndarray[CONDENSED_t, ndim=1, mode='c'] condensed_tree + cnp.ndarray[cnp.intp_t, ndim=1, mode='c'] labels + cnp.ndarray[cnp.float64_t, ndim=1, mode='c'] probabilities + + condensed_tree = _condense_tree(single_linkage_tree, min_cluster_size) + labels, probabilities = _get_clusters( + condensed_tree, + _compute_stability(condensed_tree), + cluster_selection_method, + allow_single_cluster, + cluster_selection_epsilon, + max_cluster_size, + ) + + return (labels, probabilities) + +cdef list bfs_from_hierarchy( + const HIERARCHY_t[::1] hierarchy, + cnp.intp_t bfs_root +): + """ + Perform a breadth first search on a tree in scipy hclust format. + """ + + cdef list process_queue, next_queue, result + cdef cnp.intp_t n_samples = hierarchy.shape[0] + 1 + cdef cnp.intp_t node + process_queue = [bfs_root] + result = [] + + while process_queue: + result.extend(process_queue) + # By construction, node i is formed by the union of nodes + # hierarchy[i - n_samples, 0] and hierarchy[i - n_samples, 1] + process_queue = [ + x - n_samples + for x in process_queue + if x >= n_samples + ] + if process_queue: + next_queue = [] + for node in process_queue: + next_queue.extend( + [ + hierarchy[node].left_node, + hierarchy[node].right_node, + ] + ) + process_queue = next_queue + return result + + +cpdef cnp.ndarray[CONDENSED_t, ndim=1, mode='c'] _condense_tree( + const HIERARCHY_t[::1] hierarchy, + cnp.intp_t min_cluster_size=10 +): + """Condense a tree according to a minimum cluster size. This is akin + to the runt pruning procedure of Stuetzle. The result is a much simpler + tree that is easier to visualize. We include extra information on the + lambda value at which individual points depart clusters for later + analysis and computation. + + Parameters + ---------- + hierarchy : ndarray of shape (n_samples,), dtype=HIERARCHY_dtype + A single linkage hierarchy in scipy.cluster.hierarchy format. + + min_cluster_size : int, optional (default 10) + The minimum size of clusters to consider. Clusters smaller than this + are pruned from the tree. + + Returns + ------- + condensed_tree : ndarray of shape (n_samples,), dtype=CONDENSED_dtype + Effectively an edgelist encoding a parent/child pair, along with a + value and the corresponding cluster_size in each row providing a tree + structure. + """ + + cdef: + cnp.intp_t root = 2 * hierarchy.shape[0] + cnp.intp_t n_samples = hierarchy.shape[0] + 1 + cnp.intp_t next_label = n_samples + 1 + list result_list, node_list = bfs_from_hierarchy(hierarchy, root) + + cnp.intp_t[::1] relabel + cnp.uint8_t[::1] ignore + + cnp.intp_t node, sub_node, left, right + cnp.float64_t lambda_value, distance + cnp.intp_t left_count, right_count + HIERARCHY_t children + + relabel = np.empty(root + 1, dtype=np.intp) + relabel[root] = n_samples + result_list = [] + ignore = np.zeros(len(node_list), dtype=bool) + + for node in node_list: + if ignore[node] or node < n_samples: + continue + + children = hierarchy[node - n_samples] + left = children.left_node + right = children.right_node + distance = children.value + if distance > 0.0: + lambda_value = 1.0 / distance + else: + lambda_value = INFTY + + if left >= n_samples: + left_count = hierarchy[left - n_samples].cluster_size + else: + left_count = 1 + + if right >= n_samples: + right_count = hierarchy[right - n_samples].cluster_size + else: + right_count = 1 + + if left_count >= min_cluster_size and right_count >= min_cluster_size: + relabel[left] = next_label + next_label += 1 + result_list.append( + (relabel[node], relabel[left], lambda_value, left_count) + ) + + relabel[right] = next_label + next_label += 1 + result_list.append( + (relabel[node], relabel[right], lambda_value, right_count) + ) + + elif left_count < min_cluster_size and right_count < min_cluster_size: + for sub_node in bfs_from_hierarchy(hierarchy, left): + if sub_node < n_samples: + result_list.append( + (relabel[node], sub_node, lambda_value, 1) + ) + ignore[sub_node] = True + + for sub_node in bfs_from_hierarchy(hierarchy, right): + if sub_node < n_samples: + result_list.append( + (relabel[node], sub_node, lambda_value, 1) + ) + ignore[sub_node] = True + + elif left_count < min_cluster_size: + relabel[right] = relabel[node] + for sub_node in bfs_from_hierarchy(hierarchy, left): + if sub_node < n_samples: + result_list.append( + (relabel[node], sub_node, lambda_value, 1) + ) + ignore[sub_node] = True + + else: + relabel[left] = relabel[node] + for sub_node in bfs_from_hierarchy(hierarchy, right): + if sub_node < n_samples: + result_list.append( + (relabel[node], sub_node, lambda_value, 1) + ) + ignore[sub_node] = True + + return np.array(result_list, dtype=CONDENSED_dtype) + + +cdef dict _compute_stability( + cnp.ndarray[CONDENSED_t, ndim=1, mode='c'] condensed_tree +): + + cdef: + cnp.float64_t[::1] result, births + cnp.intp_t[:] parents = condensed_tree['parent'] + + cnp.intp_t parent, cluster_size, result_index, idx + cnp.float64_t lambda_val + CONDENSED_t condensed_node + cnp.intp_t largest_child = condensed_tree['child'].max() + cnp.intp_t smallest_cluster = np.min(parents) + cnp.intp_t num_clusters = np.max(parents) - smallest_cluster + 1 + dict stability_dict = {} + + largest_child = max(largest_child, smallest_cluster) + births = np.full(largest_child + 1, np.nan, dtype=np.float64) + + for idx in range(PyArray_SHAPE( condensed_tree)[0]): + condensed_node = condensed_tree[idx] + births[condensed_node.child] = condensed_node.value + + births[smallest_cluster] = 0.0 + + result = np.zeros(num_clusters, dtype=np.float64) + for idx in range(PyArray_SHAPE( condensed_tree)[0]): + condensed_node = condensed_tree[idx] + parent = condensed_node.parent + lambda_val = condensed_node.value + cluster_size = condensed_node.cluster_size + + result_index = parent - smallest_cluster + result[result_index] += (lambda_val - births[parent]) * cluster_size + + for idx in range(num_clusters): + stability_dict[idx + smallest_cluster] = result[idx] + + return stability_dict + + +cdef list bfs_from_cluster_tree( + cnp.ndarray[CONDENSED_t, ndim=1, mode='c'] condensed_tree, + cnp.intp_t bfs_root +): + + cdef: + list result = [] + cnp.ndarray[cnp.intp_t, ndim=1] process_queue = ( + np.array([bfs_root], dtype=np.intp) + ) + cnp.ndarray[cnp.intp_t, ndim=1] children = condensed_tree['child'] + cnp.intp_t[:] parents = condensed_tree['parent'] + + while len(process_queue) > 0: + result.extend(process_queue.tolist()) + process_queue = children[np.isin(parents, process_queue)] + + return result + + +cdef cnp.float64_t[::1] max_lambdas(cnp.ndarray[CONDENSED_t, ndim=1, mode='c'] condensed_tree): + + cdef: + cnp.intp_t parent, current_parent, idx + cnp.float64_t lambda_val, max_lambda + cnp.float64_t[::1] deaths + cnp.intp_t largest_parent = condensed_tree['parent'].max() + + deaths = np.zeros(largest_parent + 1, dtype=np.float64) + current_parent = condensed_tree[0].parent + max_lambda = condensed_tree[0].value + + for idx in range(1, PyArray_SHAPE( condensed_tree)[0]): + parent = condensed_tree[idx].parent + lambda_val = condensed_tree[idx].value + + if parent == current_parent: + max_lambda = max(max_lambda, lambda_val) + else: + deaths[current_parent] = max_lambda + current_parent = parent + max_lambda = lambda_val + + deaths[current_parent] = max_lambda # value for last parent + return deaths + + +@cython.final +cdef class TreeUnionFind: + + cdef cnp.intp_t[:, ::1] data + cdef cnp.uint8_t[::1] is_component + + def __init__(self, size): + cdef cnp.intp_t idx + self.data = np.zeros((size, 2), dtype=np.intp) + for idx in range(size): + self.data[idx, 0] = idx + self.is_component = np.ones(size, dtype=np.uint8) + + cdef void union(self, cnp.intp_t x, cnp.intp_t y): + cdef cnp.intp_t x_root = self.find(x) + cdef cnp.intp_t y_root = self.find(y) + + if self.data[x_root, 1] < self.data[y_root, 1]: + self.data[x_root, 0] = y_root + elif self.data[x_root, 1] > self.data[y_root, 1]: + self.data[y_root, 0] = x_root + else: + self.data[y_root, 0] = x_root + self.data[x_root, 1] += 1 + return + + cdef cnp.intp_t find(self, cnp.intp_t x): + if self.data[x, 0] != x: + self.data[x, 0] = self.find(self.data[x, 0]) + self.is_component[x] = False + return self.data[x, 0] + + +cpdef cnp.ndarray[cnp.intp_t, ndim=1, mode='c'] labelling_at_cut( + const HIERARCHY_t[::1] linkage, + cnp.float64_t cut, + cnp.intp_t min_cluster_size +): + """Given a single linkage tree and a cut value, return the + vector of cluster labels at that cut value. This is useful + for Robust Single Linkage, and extracting DBSCAN results + from a single HDBSCAN run. + + Parameters + ---------- + linkage : ndarray of shape (n_samples,), dtype=HIERARCHY_dtype + The single linkage tree in scipy.cluster.hierarchy format. + + cut : double + The cut value at which to find clusters. + + min_cluster_size : int + The minimum cluster size; clusters below this size at + the cut will be considered noise. + + Returns + ------- + labels : ndarray of shape (n_samples,) + The cluster labels for each point in the data set; + a label of -1 denotes a noise assignment. + """ + + cdef: + cnp.intp_t n, cluster, root, n_samples, cluster_label + cnp.intp_t[::1] unique_labels, cluster_size + cnp.ndarray[cnp.intp_t, ndim=1, mode='c'] result + TreeUnionFind union_find + dict cluster_label_map + HIERARCHY_t node + + root = 2 * linkage.shape[0] + n_samples = root // 2 + 1 + result = np.empty(n_samples, dtype=np.intp) + union_find = TreeUnionFind(root + 1) + + cluster = n_samples + for node in linkage: + if node.value < cut: + union_find.union(node.left_node, cluster) + union_find.union(node.right_node, cluster) + cluster += 1 + + cluster_size = np.zeros(cluster, dtype=np.intp) + for n in range(n_samples): + cluster = union_find.find(n) + cluster_size[cluster] += 1 + result[n] = cluster + + cluster_label_map = {-1: NOISE} + cluster_label = 0 + unique_labels = np.unique(result) + + for cluster in unique_labels: + if cluster_size[cluster] < min_cluster_size: + cluster_label_map[cluster] = NOISE + else: + cluster_label_map[cluster] = cluster_label + cluster_label += 1 + + for n in range(n_samples): + result[n] = cluster_label_map[result[n]] + + return result + + +cpdef cnp.ndarray[cnp.intp_t, ndim=1, mode='c'] _do_labelling( + cnp.ndarray[CONDENSED_t, ndim=1, mode='c'] condensed_tree, + set clusters, + dict cluster_label_map, + cnp.intp_t allow_single_cluster, + cnp.float64_t cluster_selection_epsilon +): + """Given a condensed tree, clusters and a labeling map for the clusters, + return an array containing the labels of each point based on cluster + membership. Note that this is where points may be marked as noisy + outliers. The determination of some points as noise is in large, single- + cluster datasets is controlled by the `allow_single_cluster` and + `cluster_selection_epsilon` parameters. + + Parameters + ---------- + condensed_tree : ndarray of shape (n_samples,), dtype=CONDENSED_dtype + Effectively an edgelist encoding a parent/child pair, along with a + value and the corresponding cluster_size in each row providing a tree + structure. + + clusters : set + The set of nodes corresponding to identified clusters. These node + values should be the same as those present in `condensed_tree`. + + cluster_label_map : dict + A mapping from the node values present in `clusters` to the labels + which will be returned. + + Returns + ------- + labels : ndarray of shape (n_samples,) + The cluster labels for each point in the data set; + a label of -1 denotes a noise assignment. + """ + + cdef: + cnp.intp_t root_cluster + cnp.ndarray[cnp.intp_t, ndim=1, mode='c'] result + cnp.ndarray[cnp.intp_t, ndim=1] parent_array, child_array + cnp.ndarray[cnp.float64_t, ndim=1] lambda_array + TreeUnionFind union_find + cnp.intp_t n, parent, child, cluster + cnp.float64_t threshold + + child_array = condensed_tree['child'] + parent_array = condensed_tree['parent'] + lambda_array = condensed_tree['value'] + + root_cluster = np.min(parent_array) + result = np.empty(root_cluster, dtype=np.intp) + union_find = TreeUnionFind(np.max(parent_array) + 1) + + for n in range(PyArray_SHAPE( condensed_tree)[0]): + child = child_array[n] + parent = parent_array[n] + if child not in clusters: + union_find.union(parent, child) + + for n in range(root_cluster): + cluster = union_find.find(n) + label = NOISE + if cluster != root_cluster: + label = cluster_label_map[cluster] + elif len(clusters) == 1 and allow_single_cluster: + # There can only be one edge with this particular child hence this + # expression extracts a unique, scalar lambda value. + parent_lambda = lambda_array[child_array == n] + if cluster_selection_epsilon != 0.0: + threshold = 1 / cluster_selection_epsilon + else: + # The threshold should be calculated per-sample based on the + # largest lambda of any simbling node. + threshold = lambda_array[parent_array == cluster].max() + if parent_lambda >= threshold: + label = cluster_label_map[cluster] + + result[n] = label + + return result + + +cdef cnp.ndarray[cnp.float64_t, ndim=1, mode='c'] get_probabilities( + cnp.ndarray[CONDENSED_t, ndim=1, mode='c'] condensed_tree, + dict cluster_map, + cnp.intp_t[::1] labels +): + + cdef: + cnp.ndarray[cnp.float64_t, ndim=1, mode='c'] result + cnp.float64_t[:] lambda_array + cnp.float64_t[::1] deaths + cnp.intp_t[:] child_array, parent_array + cnp.intp_t root_cluster, n, point, cluster_num, cluster + cnp.float64_t max_lambda, lambda_val + + child_array = condensed_tree['child'] + parent_array = condensed_tree['parent'] + lambda_array = condensed_tree['value'] + + result = np.zeros(labels.shape[0]) + deaths = max_lambdas(condensed_tree) + root_cluster = np.min(parent_array) + + for n in range(PyArray_SHAPE( condensed_tree)[0]): + point = child_array[n] + if point >= root_cluster: + continue + + cluster_num = labels[point] + if cluster_num == -1: + continue + + cluster = cluster_map[cluster_num] + max_lambda = deaths[cluster] + if max_lambda == 0.0 or isinf(lambda_array[n]): + result[point] = 1.0 + else: + lambda_val = min(lambda_array[n], max_lambda) + result[point] = lambda_val / max_lambda + + return result + + +cpdef list recurse_leaf_dfs( + cnp.ndarray[CONDENSED_t, ndim=1, mode='c'] cluster_tree, + cnp.intp_t current_node +): + cdef cnp.intp_t[:] children + cdef cnp.intp_t child + + children = cluster_tree[cluster_tree['parent'] == current_node]['child'] + if children.shape[0] == 0: + return [current_node,] + else: + return sum([recurse_leaf_dfs(cluster_tree, child) for child in children], []) + + +cpdef list get_cluster_tree_leaves(cnp.ndarray[CONDENSED_t, ndim=1, mode='c'] cluster_tree): + cdef cnp.intp_t root + if PyArray_SHAPE( cluster_tree)[0] == 0: + return [] + root = cluster_tree['parent'].min() + return recurse_leaf_dfs(cluster_tree, root) + +cdef cnp.intp_t traverse_upwards( + cnp.ndarray[CONDENSED_t, ndim=1, mode='c'] cluster_tree, + cnp.float64_t cluster_selection_epsilon, + cnp.intp_t leaf, + cnp.intp_t allow_single_cluster +): + cdef cnp.intp_t root, parent + cdef cnp.float64_t parent_eps + + root = cluster_tree['parent'].min() + parent = cluster_tree[cluster_tree['child'] == leaf]['parent'] + if parent == root: + if allow_single_cluster: + return parent + else: + return leaf # return node closest to root + + parent_eps = 1 / cluster_tree[cluster_tree['child'] == parent]['value'] + if parent_eps > cluster_selection_epsilon: + return parent + else: + return traverse_upwards( + cluster_tree, + cluster_selection_epsilon, + parent, + allow_single_cluster + ) + +cdef set epsilon_search( + set leaves, + cnp.ndarray[CONDENSED_t, ndim=1, mode='c'] cluster_tree, + cnp.float64_t cluster_selection_epsilon, + cnp.intp_t allow_single_cluster +): + cdef: + list selected_clusters = list() + list processed = list() + cnp.intp_t leaf, epsilon_child, sub_node + cnp.float64_t eps + cnp.uint8_t[:] leaf_nodes + cnp.ndarray[cnp.intp_t, ndim=1] children = cluster_tree['child'] + cnp.ndarray[cnp.float64_t, ndim=1] distances = cluster_tree['value'] + + for leaf in leaves: + leaf_nodes = children == leaf + eps = 1 / distances[leaf_nodes][0] + if eps < cluster_selection_epsilon: + if leaf not in processed: + epsilon_child = traverse_upwards( + cluster_tree, + cluster_selection_epsilon, + leaf, + allow_single_cluster + ) + selected_clusters.append(epsilon_child) + + for sub_node in bfs_from_cluster_tree(cluster_tree, epsilon_child): + if sub_node != epsilon_child: + processed.append(sub_node) + else: + selected_clusters.append(leaf) + + return set(selected_clusters) + + +@cython.wraparound(True) +cdef tuple _get_clusters( + cnp.ndarray[CONDENSED_t, ndim=1, mode='c'] condensed_tree, + dict stability, + cluster_selection_method='eom', + cnp.uint8_t allow_single_cluster=False, + cnp.float64_t cluster_selection_epsilon=0.0, + max_cluster_size=None +): + """Given a tree and stability dict, produce the cluster labels + (and probabilities) for a flat clustering based on the chosen + cluster selection method. + + Parameters + ---------- + condensed_tree : ndarray of shape (n_samples,), dtype=CONDENSED_dtype + Effectively an edgelist encoding a parent/child pair, along with a + value and the corresponding cluster_size in each row providing a tree + structure. + + stability : dict + A dictionary mapping cluster_ids to stability values + + cluster_selection_method : string, optional (default 'eom') + The method of selecting clusters. The default is the + Excess of Mass algorithm specified by 'eom'. The alternate + option is 'leaf'. + + allow_single_cluster : boolean, optional (default False) + Whether to allow a single cluster to be selected by the + Excess of Mass algorithm. + + cluster_selection_epsilon: double, optional (default 0.0) + A distance threshold for cluster splits. + + max_cluster_size: int, default=None + The maximum size for clusters located by the EOM clusterer. Can + be overridden by the cluster_selection_epsilon parameter in + rare cases. + + Returns + ------- + labels : ndarray of shape (n_samples,) + An integer array of cluster labels, with -1 denoting noise. + + probabilities : ndarray (n_samples,) + The cluster membership strength of each sample. + + stabilities : ndarray (n_clusters,) + The cluster coherence strengths of each cluster. + """ + cdef: + list node_list + cnp.ndarray[CONDENSED_t, ndim=1, mode='c'] cluster_tree + cnp.uint8_t[::1] child_selection + cnp.ndarray[cnp.intp_t, ndim=1, mode='c'] labels + dict is_cluster, cluster_sizes + cnp.float64_t subtree_stability + cnp.intp_t node, sub_node, cluster, n_samples + cnp.ndarray[cnp.float64_t, ndim=1, mode='c'] probs + + # Assume clusters are ordered by numeric id equivalent to + # a topological sort of the tree; This is valid given the + # current implementation above, so don't change that ... or + # if you do, change this accordingly! + if allow_single_cluster: + node_list = sorted(stability.keys(), reverse=True) + else: + node_list = sorted(stability.keys(), reverse=True)[:-1] + # (exclude root) + + cluster_tree = condensed_tree[condensed_tree['cluster_size'] > 1] + is_cluster = {cluster: True for cluster in node_list} + n_samples = np.max(condensed_tree[condensed_tree['cluster_size'] == 1]['child']) + 1 + + if max_cluster_size is None: + max_cluster_size = n_samples + 1 # Set to a value that will never be triggered + cluster_sizes = { + child: cluster_size for child, cluster_size + in zip(cluster_tree['child'], cluster_tree['cluster_size']) + } + if allow_single_cluster: + # Compute cluster size for the root node + cluster_sizes[node_list[-1]] = np.sum( + cluster_tree[cluster_tree['parent'] == node_list[-1]]['cluster_size']) + + if cluster_selection_method == 'eom': + for node in node_list: + child_selection = (cluster_tree['parent'] == node) + subtree_stability = np.sum([ + stability[child] for + child in cluster_tree['child'][child_selection]]) + if subtree_stability > stability[node] or cluster_sizes[node] > max_cluster_size: + is_cluster[node] = False + stability[node] = subtree_stability + else: + for sub_node in bfs_from_cluster_tree(cluster_tree, node): + if sub_node != node: + is_cluster[sub_node] = False + + if cluster_selection_epsilon != 0.0 and PyArray_SHAPE( cluster_tree)[0] > 0: + eom_clusters = [c for c in is_cluster if is_cluster[c]] + selected_clusters = [] + # first check if eom_clusters only has root node, which skips epsilon check. + if (len(eom_clusters) == 1 and eom_clusters[0] == cluster_tree['parent'].min()): + if allow_single_cluster: + selected_clusters = eom_clusters + else: + selected_clusters = epsilon_search( + set(eom_clusters), + cluster_tree, + cluster_selection_epsilon, + allow_single_cluster + ) + for c in is_cluster: + if c in selected_clusters: + is_cluster[c] = True + else: + is_cluster[c] = False + + elif cluster_selection_method == 'leaf': + leaves = set(get_cluster_tree_leaves(cluster_tree)) + if len(leaves) == 0: + for c in is_cluster: + is_cluster[c] = False + is_cluster[condensed_tree['parent'].min()] = True + + if cluster_selection_epsilon != 0.0: + selected_clusters = epsilon_search( + leaves, + cluster_tree, + cluster_selection_epsilon, + allow_single_cluster + ) + else: + selected_clusters = leaves + + for c in is_cluster: + if c in selected_clusters: + is_cluster[c] = True + else: + is_cluster[c] = False + + clusters = set([c for c in is_cluster if is_cluster[c]]) + cluster_map = {c: n for n, c in enumerate(sorted(list(clusters)))} + reverse_cluster_map = {n: c for c, n in cluster_map.items()} + + labels = _do_labelling( + condensed_tree, + clusters, + cluster_map, + allow_single_cluster, + cluster_selection_epsilon + ) + probs = get_probabilities(condensed_tree, reverse_cluster_map, labels) + + return (labels, probs) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/hdbscan.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/hdbscan.py new file mode 100644 index 0000000000000000000000000000000000000000..f292a1f65909b6a5a1a0287adbc2996a3dc36381 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/hdbscan.py @@ -0,0 +1,1000 @@ +""" +HDBSCAN: Hierarchical Density-Based Spatial Clustering + of Applications with Noise +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. + +# 3. Neither the name of the copyright holder nor the names of its contributors +# may be used to endorse or promote products derived from this software without +# specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +from numbers import Integral, Real +from warnings import warn + +import numpy as np +from scipy.sparse import csgraph, issparse + +from ...base import BaseEstimator, ClusterMixin, _fit_context +from ...metrics import pairwise_distances +from ...metrics._dist_metrics import DistanceMetric +from ...metrics.pairwise import _VALID_METRICS +from ...neighbors import BallTree, KDTree, NearestNeighbors +from ...utils._param_validation import Interval, StrOptions +from ...utils.validation import ( + _allclose_dense_sparse, + _assert_all_finite, + validate_data, +) +from ._linkage import ( + MST_edge_dtype, + make_single_linkage, + mst_from_data_matrix, + mst_from_mutual_reachability, +) +from ._reachability import mutual_reachability_graph +from ._tree import HIERARCHY_dtype, labelling_at_cut, tree_to_labels + +FAST_METRICS = set(KDTree.valid_metrics + BallTree.valid_metrics) + +# Encodings are arbitrary but must be strictly negative. +# The current encodings are chosen as extensions to the -1 noise label. +# Avoided enums so that the end user only deals with simple labels. +_OUTLIER_ENCODING: dict = { + "infinite": { + "label": -2, + # The probability could also be 1, since infinite points are certainly + # infinite outliers, however 0 is convention from the HDBSCAN library + # implementation. + "prob": 0, + }, + "missing": { + "label": -3, + # A nan probability is chosen to emphasize the fact that the + # corresponding data was not considered in the clustering problem. + "prob": np.nan, + }, +} + + +def _brute_mst(mutual_reachability, min_samples): + """ + Builds a minimum spanning tree (MST) from the provided mutual-reachability + values. This function dispatches to a custom Cython implementation for + dense arrays, and `scipy.sparse.csgraph.minimum_spanning_tree` for sparse + arrays/matrices. + + Parameters + ---------- + mututal_reachability_graph: {ndarray, sparse matrix} of shape \ + (n_samples, n_samples) + Weighted adjacency matrix of the mutual reachability graph. + + min_samples : int, default=None + The number of samples in a neighborhood for a point + to be considered as a core point. This includes the point itself. + + Returns + ------- + mst : ndarray of shape (n_samples - 1,), dtype=MST_edge_dtype + The MST representation of the mutual-reachability graph. The MST is + represented as a collection of edges. + """ + if not issparse(mutual_reachability): + return mst_from_mutual_reachability(mutual_reachability) + + # Check if the mutual reachability matrix has any rows which have + # less than `min_samples` non-zero elements. + indptr = mutual_reachability.indptr + num_points = mutual_reachability.shape[0] + if any((indptr[i + 1] - indptr[i]) < min_samples for i in range(num_points)): + raise ValueError( + f"There exists points with fewer than {min_samples} neighbors. Ensure" + " your distance matrix has non-zero values for at least" + f" `min_sample`={min_samples} neighbors for each points (i.e. K-nn" + " graph), or specify a `max_distance` in `metric_params` to use when" + " distances are missing." + ) + # Check connected component on mutual reachability. + # If more than one connected component is present, + # it means that the graph is disconnected. + n_components = csgraph.connected_components( + mutual_reachability, directed=False, return_labels=False + ) + if n_components > 1: + raise ValueError( + f"Sparse mutual reachability matrix has {n_components} connected" + " components. HDBSCAN cannot be performed on a disconnected graph. Ensure" + " that the sparse distance matrix has only one connected component." + ) + + # Compute the minimum spanning tree for the sparse graph + sparse_min_spanning_tree = csgraph.minimum_spanning_tree(mutual_reachability) + rows, cols = sparse_min_spanning_tree.nonzero() + mst = np.rec.fromarrays( + [rows, cols, sparse_min_spanning_tree.data], + dtype=MST_edge_dtype, + ) + return mst + + +def _process_mst(min_spanning_tree): + """ + Builds a single-linkage tree (SLT) from the provided minimum spanning tree + (MST). The MST is first sorted then processed by a custom Cython routine. + + Parameters + ---------- + min_spanning_tree : ndarray of shape (n_samples - 1,), dtype=MST_edge_dtype + The MST representation of the mutual-reachability graph. The MST is + represented as a collection of edges. + + Returns + ------- + single_linkage : ndarray of shape (n_samples - 1,), dtype=HIERARCHY_dtype + The single-linkage tree tree (dendrogram) built from the MST. + """ + # Sort edges of the min_spanning_tree by weight + row_order = np.argsort(min_spanning_tree["distance"]) + min_spanning_tree = min_spanning_tree[row_order] + # Convert edge list into standard hierarchical clustering format + return make_single_linkage(min_spanning_tree) + + +def _hdbscan_brute( + X, + min_samples=5, + alpha=None, + metric="euclidean", + n_jobs=None, + copy=False, + **metric_params, +): + """ + Builds a single-linkage tree (SLT) from the input data `X`. If + `metric="precomputed"` then `X` must be a symmetric array of distances. + Otherwise, the pairwise distances are calculated directly and passed to + `mutual_reachability_graph`. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) or (n_samples, n_samples) + Either the raw data from which to compute the pairwise distances, + or the precomputed distances. + + min_samples : int, default=None + The number of samples in a neighborhood for a point + to be considered as a core point. This includes the point itself. + + alpha : float, default=1.0 + A distance scaling parameter as used in robust single linkage. + + metric : str or callable, default='euclidean' + The metric to use when calculating distance between instances in a + feature array. + + - If metric is a string or callable, it must be one of + the options allowed by :func:`~sklearn.metrics.pairwise_distances` + for its metric parameter. + + - If metric is "precomputed", X is assumed to be a distance matrix and + must be square. + + n_jobs : int, default=None + The number of jobs to use for computing the pairwise distances. This + works by breaking down the pairwise matrix into n_jobs even slices and + computing them in parallel. This parameter is passed directly to + :func:`~sklearn.metrics.pairwise_distances`. + + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + copy : bool, default=False + If `copy=True` then any time an in-place modifications would be made + that would overwrite `X`, a copy will first be made, guaranteeing that + the original data will be unchanged. Currently, it only applies when + `metric="precomputed"`, when passing a dense array or a CSR sparse + array/matrix. + + metric_params : dict, default=None + Arguments passed to the distance metric. + + Returns + ------- + single_linkage : ndarray of shape (n_samples - 1,), dtype=HIERARCHY_dtype + The single-linkage tree tree (dendrogram) built from the MST. + """ + if metric == "precomputed": + if X.shape[0] != X.shape[1]: + raise ValueError( + "The precomputed distance matrix is expected to be symmetric, however" + f" it has shape {X.shape}. Please verify that the" + " distance matrix was constructed correctly." + ) + if not _allclose_dense_sparse(X, X.T): + raise ValueError( + "The precomputed distance matrix is expected to be symmetric, however" + " its values appear to be asymmetric. Please verify that the distance" + " matrix was constructed correctly." + ) + + distance_matrix = X.copy() if copy else X + else: + distance_matrix = pairwise_distances( + X, metric=metric, n_jobs=n_jobs, **metric_params + ) + distance_matrix /= alpha + + max_distance = metric_params.get("max_distance", 0.0) + if issparse(distance_matrix) and distance_matrix.format != "csr": + # we need CSR format to avoid a conversion in `_brute_mst` when calling + # `csgraph.connected_components` + distance_matrix = distance_matrix.tocsr() + + # Note that `distance_matrix` is manipulated in-place, however we do not + # need it for anything else past this point, hence the operation is safe. + mutual_reachability_ = mutual_reachability_graph( + distance_matrix, min_samples=min_samples, max_distance=max_distance + ) + min_spanning_tree = _brute_mst(mutual_reachability_, min_samples=min_samples) + # Warn if the MST couldn't be constructed around the missing distances + if np.isinf(min_spanning_tree["distance"]).any(): + warn( + ( + "The minimum spanning tree contains edge weights with value " + "infinity. Potentially, you are missing too many distances " + "in the initial distance matrix for the given neighborhood " + "size." + ), + UserWarning, + ) + return _process_mst(min_spanning_tree) + + +def _hdbscan_prims( + X, + algo, + min_samples=5, + alpha=1.0, + metric="euclidean", + leaf_size=40, + n_jobs=None, + **metric_params, +): + """ + Builds a single-linkage tree (SLT) from the input data `X`. If + `metric="precomputed"` then `X` must be a symmetric array of distances. + Otherwise, the pairwise distances are calculated directly and passed to + `mutual_reachability_graph`. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The raw data. + + min_samples : int, default=None + The number of samples in a neighborhood for a point + to be considered as a core point. This includes the point itself. + + alpha : float, default=1.0 + A distance scaling parameter as used in robust single linkage. + + metric : str or callable, default='euclidean' + The metric to use when calculating distance between instances in a + feature array. `metric` must be one of the options allowed by + :func:`~sklearn.metrics.pairwise_distances` for its metric + parameter. + + n_jobs : int, default=None + The number of jobs to use for computing the pairwise distances. This + works by breaking down the pairwise matrix into n_jobs even slices and + computing them in parallel. This parameter is passed directly to + :func:`~sklearn.metrics.pairwise_distances`. + + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + copy : bool, default=False + If `copy=True` then any time an in-place modifications would be made + that would overwrite `X`, a copy will first be made, guaranteeing that + the original data will be unchanged. Currently, it only applies when + `metric="precomputed"`, when passing a dense array or a CSR sparse + array/matrix. + + metric_params : dict, default=None + Arguments passed to the distance metric. + + Returns + ------- + single_linkage : ndarray of shape (n_samples - 1,), dtype=HIERARCHY_dtype + The single-linkage tree tree (dendrogram) built from the MST. + """ + # The Cython routines used require contiguous arrays + X = np.asarray(X, order="C") + + # Get distance to kth nearest neighbour + nbrs = NearestNeighbors( + n_neighbors=min_samples, + algorithm=algo, + leaf_size=leaf_size, + metric=metric, + metric_params=metric_params, + n_jobs=n_jobs, + p=None, + ).fit(X) + + neighbors_distances, _ = nbrs.kneighbors(X, min_samples, return_distance=True) + core_distances = np.ascontiguousarray(neighbors_distances[:, -1]) + dist_metric = DistanceMetric.get_metric(metric, **metric_params) + + # Mutual reachability distance is implicit in mst_from_data_matrix + min_spanning_tree = mst_from_data_matrix(X, core_distances, dist_metric, alpha) + return _process_mst(min_spanning_tree) + + +def remap_single_linkage_tree(tree, internal_to_raw, non_finite): + """ + Takes an internal single_linkage_tree structure and adds back in a set of points + that were initially detected as non-finite and returns that new tree. + These points will all be merged into the final node at np.inf distance and + considered noise points. + + Parameters + ---------- + tree : ndarray of shape (n_samples - 1,), dtype=HIERARCHY_dtype + The single-linkage tree tree (dendrogram) built from the MST. + internal_to_raw: dict + A mapping from internal integer index to the raw integer index + non_finite : ndarray + Boolean array of which entries in the raw data are non-finite + """ + finite_count = len(internal_to_raw) + + outlier_count = len(non_finite) + for i, _ in enumerate(tree): + left = tree[i]["left_node"] + right = tree[i]["right_node"] + + if left < finite_count: + tree[i]["left_node"] = internal_to_raw[left] + else: + tree[i]["left_node"] = left + outlier_count + if right < finite_count: + tree[i]["right_node"] = internal_to_raw[right] + else: + tree[i]["right_node"] = right + outlier_count + + outlier_tree = np.zeros(len(non_finite), dtype=HIERARCHY_dtype) + last_cluster_id = max( + tree[tree.shape[0] - 1]["left_node"], tree[tree.shape[0] - 1]["right_node"] + ) + last_cluster_size = tree[tree.shape[0] - 1]["cluster_size"] + for i, outlier in enumerate(non_finite): + outlier_tree[i] = (outlier, last_cluster_id + 1, np.inf, last_cluster_size + 1) + last_cluster_id += 1 + last_cluster_size += 1 + tree = np.concatenate([tree, outlier_tree]) + return tree + + +def _get_finite_row_indices(matrix): + """ + Returns the indices of the purely finite rows of a + sparse matrix or dense ndarray + """ + if issparse(matrix): + row_indices = np.array( + [i for i, row in enumerate(matrix.tolil().data) if np.all(np.isfinite(row))] + ) + else: + (row_indices,) = np.isfinite(matrix.sum(axis=1)).nonzero() + return row_indices + + +class HDBSCAN(ClusterMixin, BaseEstimator): + """Cluster data using hierarchical density-based clustering. + + HDBSCAN - Hierarchical Density-Based Spatial Clustering of Applications + with Noise. Performs :class:`~sklearn.cluster.DBSCAN` over varying epsilon + values and integrates the result to find a clustering that gives the best + stability over epsilon. + This allows HDBSCAN to find clusters of varying densities (unlike + :class:`~sklearn.cluster.DBSCAN`), and be more robust to parameter selection. + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.3 + + Parameters + ---------- + min_cluster_size : int, default=5 + The minimum number of samples in a group for that group to be + considered a cluster; groupings smaller than this size will be left + as noise. + + min_samples : int, default=None + The parameter `k` used to calculate the distance between a point + `x_p` and its k-th nearest neighbor. + When `None`, defaults to `min_cluster_size`. + + cluster_selection_epsilon : float, default=0.0 + A distance threshold. Clusters below this value will be merged. + See [5]_ for more information. + + max_cluster_size : int, default=None + A limit to the size of clusters returned by the `"eom"` cluster + selection algorithm. There is no limit when `max_cluster_size=None`. + Has no effect if `cluster_selection_method="leaf"`. + + metric : str or callable, default='euclidean' + The metric to use when calculating distance between instances in a + feature array. + + - If metric is a string or callable, it must be one of + the options allowed by :func:`~sklearn.metrics.pairwise_distances` + for its metric parameter. + + - If metric is "precomputed", X is assumed to be a distance matrix and + must be square. + + metric_params : dict, default=None + Arguments passed to the distance metric. + + alpha : float, default=1.0 + A distance scaling parameter as used in robust single linkage. + See [3]_ for more information. + + algorithm : {"auto", "brute", "kd_tree", "ball_tree"}, default="auto" + Exactly which algorithm to use for computing core distances; By default + this is set to `"auto"` which attempts to use a + :class:`~sklearn.neighbors.KDTree` tree if possible, otherwise it uses + a :class:`~sklearn.neighbors.BallTree` tree. Both `"kd_tree"` and + `"ball_tree"` algorithms use the + :class:`~sklearn.neighbors.NearestNeighbors` estimator. + + If the `X` passed during `fit` is sparse or `metric` is invalid for + both :class:`~sklearn.neighbors.KDTree` and + :class:`~sklearn.neighbors.BallTree`, then it resolves to use the + `"brute"` algorithm. + + leaf_size : int, default=40 + Leaf size for trees responsible for fast nearest neighbour queries when + a KDTree or a BallTree are used as core-distance algorithms. A large + dataset size and small `leaf_size` may induce excessive memory usage. + If you are running out of memory consider increasing the `leaf_size` + parameter. Ignored for `algorithm="brute"`. + + n_jobs : int, default=None + Number of jobs to run in parallel to calculate distances. + `None` means 1 unless in a :obj:`joblib.parallel_backend` context. + `-1` means using all processors. See :term:`Glossary ` + for more details. + + cluster_selection_method : {"eom", "leaf"}, default="eom" + The method used to select clusters from the condensed tree. The + standard approach for HDBSCAN* is to use an Excess of Mass (`"eom"`) + algorithm to find the most persistent clusters. Alternatively you can + instead select the clusters at the leaves of the tree -- this provides + the most fine grained and homogeneous clusters. + + allow_single_cluster : bool, default=False + By default HDBSCAN* will not produce a single cluster, setting this + to True will override this and allow single cluster results in + the case that you feel this is a valid result for your dataset. + + store_centers : str, default=None + Which, if any, cluster centers to compute and store. The options are: + + - `None` which does not compute nor store any centers. + - `"centroid"` which calculates the center by taking the weighted + average of their positions. Note that the algorithm uses the + euclidean metric and does not guarantee that the output will be + an observed data point. + - `"medoid"` which calculates the center by taking the point in the + fitted data which minimizes the distance to all other points in + the cluster. This is slower than "centroid" since it requires + computing additional pairwise distances between points of the + same cluster but guarantees the output is an observed data point. + The medoid is also well-defined for arbitrary metrics, and does not + depend on a euclidean metric. + - `"both"` which computes and stores both forms of centers. + + copy : bool, default=False + If `copy=True` then any time an in-place modifications would be made + that would overwrite data passed to :term:`fit`, a copy will first be + made, guaranteeing that the original data will be unchanged. + Currently, it only applies when `metric="precomputed"`, when passing + a dense array or a CSR sparse matrix and when `algorithm="brute"`. + + Attributes + ---------- + labels_ : ndarray of shape (n_samples,) + Cluster labels for each point in the dataset given to :term:`fit`. + Outliers are labeled as follows: + + - Noisy samples are given the label -1. + - Samples with infinite elements (+/- np.inf) are given the label -2. + - Samples with missing data are given the label -3, even if they + also have infinite elements. + + probabilities_ : ndarray of shape (n_samples,) + The strength with which each sample is a member of its assigned + cluster. + + - Clustered samples have probabilities proportional to the degree that + they persist as part of the cluster. + - Noisy samples have probability zero. + - Samples with infinite elements (+/- np.inf) have probability 0. + - Samples with missing data have probability `np.nan`. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + centroids_ : ndarray of shape (n_clusters, n_features) + A collection containing the centroid of each cluster calculated under + the standard euclidean metric. The centroids may fall "outside" their + respective clusters if the clusters themselves are non-convex. + + Note that `n_clusters` only counts non-outlier clusters. That is to + say, the `-1, -2, -3` labels for the outlier clusters are excluded. + + medoids_ : ndarray of shape (n_clusters, n_features) + A collection containing the medoid of each cluster calculated under + the whichever metric was passed to the `metric` parameter. The + medoids are points in the original cluster which minimize the average + distance to all other points in that cluster under the chosen metric. + These can be thought of as the result of projecting the `metric`-based + centroid back onto the cluster. + + Note that `n_clusters` only counts non-outlier clusters. That is to + say, the `-1, -2, -3` labels for the outlier clusters are excluded. + + See Also + -------- + DBSCAN : Density-Based Spatial Clustering of Applications + with Noise. + OPTICS : Ordering Points To Identify the Clustering Structure. + Birch : Memory-efficient, online-learning algorithm. + + Notes + ----- + The `min_samples` parameter includes the point itself, whereas the implementation in + `scikit-learn-contrib/hdbscan `_ + does not. To get the same results in both versions, the value of `min_samples` here + must be 1 greater than the value used in `scikit-learn-contrib/hdbscan + `_. + + References + ---------- + + .. [1] :doi:`Campello, R. J., Moulavi, D., & Sander, J. Density-based clustering + based on hierarchical density estimates. + <10.1007/978-3-642-37456-2_14>` + .. [2] :doi:`Campello, R. J., Moulavi, D., Zimek, A., & Sander, J. + Hierarchical density estimates for data clustering, visualization, + and outlier detection.<10.1145/2733381>` + + .. [3] `Chaudhuri, K., & Dasgupta, S. Rates of convergence for the + cluster tree. + `_ + + .. [4] `Moulavi, D., Jaskowiak, P.A., Campello, R.J., Zimek, A. and + Sander, J. Density-Based Clustering Validation. + `_ + + .. [5] :arxiv:`Malzer, C., & Baum, M. "A Hybrid Approach To Hierarchical + Density-based Cluster Selection."<1911.02282>`. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.cluster import HDBSCAN + >>> from sklearn.datasets import load_digits + >>> X, _ = load_digits(return_X_y=True) + >>> hdb = HDBSCAN(min_cluster_size=20) + >>> hdb.fit(X) + HDBSCAN(min_cluster_size=20) + >>> hdb.labels_.shape == (X.shape[0],) + True + >>> np.unique(hdb.labels_).tolist() + [-1, 0, 1, 2, 3, 4, 5, 6, 7] + """ + + _parameter_constraints = { + "min_cluster_size": [Interval(Integral, left=2, right=None, closed="left")], + "min_samples": [Interval(Integral, left=1, right=None, closed="left"), None], + "cluster_selection_epsilon": [ + Interval(Real, left=0, right=None, closed="left") + ], + "max_cluster_size": [ + None, + Interval(Integral, left=1, right=None, closed="left"), + ], + "metric": [ + StrOptions(FAST_METRICS | set(_VALID_METRICS) | {"precomputed"}), + callable, + ], + "metric_params": [dict, None], + "alpha": [Interval(Real, left=0, right=None, closed="neither")], + "algorithm": [StrOptions({"auto", "brute", "kd_tree", "ball_tree"})], + "leaf_size": [Interval(Integral, left=1, right=None, closed="left")], + "n_jobs": [Integral, None], + "cluster_selection_method": [StrOptions({"eom", "leaf"})], + "allow_single_cluster": ["boolean"], + "store_centers": [None, StrOptions({"centroid", "medoid", "both"})], + "copy": ["boolean"], + } + + def __init__( + self, + min_cluster_size=5, + min_samples=None, + cluster_selection_epsilon=0.0, + max_cluster_size=None, + metric="euclidean", + metric_params=None, + alpha=1.0, + algorithm="auto", + leaf_size=40, + n_jobs=None, + cluster_selection_method="eom", + allow_single_cluster=False, + store_centers=None, + copy=False, + ): + self.min_cluster_size = min_cluster_size + self.min_samples = min_samples + self.alpha = alpha + self.max_cluster_size = max_cluster_size + self.cluster_selection_epsilon = cluster_selection_epsilon + self.metric = metric + self.metric_params = metric_params + self.algorithm = algorithm + self.leaf_size = leaf_size + self.n_jobs = n_jobs + self.cluster_selection_method = cluster_selection_method + self.allow_single_cluster = allow_single_cluster + self.store_centers = store_centers + self.copy = copy + + @_fit_context( + # HDBSCAN.metric is not validated yet + prefer_skip_nested_validation=False + ) + def fit(self, X, y=None): + """Find clusters based on hierarchical density-based clustering. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features), or \ + ndarray of shape (n_samples, n_samples) + A feature array, or array of distances between samples if + `metric='precomputed'`. + + y : None + Ignored. + + Returns + ------- + self : object + Returns self. + """ + if self.metric == "precomputed" and self.store_centers is not None: + raise ValueError( + "Cannot store centers when using a precomputed distance matrix." + ) + + self._metric_params = self.metric_params or {} + if self.metric != "precomputed": + # Non-precomputed matrices may contain non-finite values. + X = validate_data( + self, + X, + accept_sparse=["csr", "lil"], + ensure_all_finite=False, + dtype=np.float64, + ) + self._raw_data = X + all_finite = True + try: + _assert_all_finite(X.data if issparse(X) else X) + except ValueError: + all_finite = False + + if not all_finite: + # Pass only the purely finite indices into hdbscan + # We will later assign all non-finite points their + # corresponding labels, as specified in `_OUTLIER_ENCODING` + + # Reduce X to make the checks for missing/outlier samples more + # convenient. + reduced_X = X.sum(axis=1) + + # Samples with missing data are denoted by the presence of + # `np.nan` + missing_index = np.isnan(reduced_X).nonzero()[0] + + # Outlier samples are denoted by the presence of `np.inf` + infinite_index = np.isinf(reduced_X).nonzero()[0] + + # Continue with only finite samples + finite_index = _get_finite_row_indices(X) + internal_to_raw = {x: y for x, y in enumerate(finite_index)} + X = X[finite_index] + elif issparse(X): + # Handle sparse precomputed distance matrices separately + X = validate_data( + self, + X, + accept_sparse=["csr", "lil"], + dtype=np.float64, + force_writeable=True, + ) + else: + # Only non-sparse, precomputed distance matrices are handled here + # and thereby allowed to contain numpy.inf for missing distances + + # Perform data validation after removing infinite values (numpy.inf) + # from the given distance matrix. + X = validate_data( + self, X, ensure_all_finite=False, dtype=np.float64, force_writeable=True + ) + if np.isnan(X).any(): + # TODO: Support np.nan in Cython implementation for precomputed + # dense HDBSCAN + raise ValueError("np.nan values found in precomputed-dense") + if X.shape[0] == 1: + raise ValueError("n_samples=1 while HDBSCAN requires more than one sample") + self._min_samples = ( + self.min_cluster_size if self.min_samples is None else self.min_samples + ) + + if self._min_samples > X.shape[0]: + raise ValueError( + f"min_samples ({self._min_samples}) must be at most the number of" + f" samples in X ({X.shape[0]})" + ) + + mst_func = None + kwargs = dict( + X=X, + min_samples=self._min_samples, + alpha=self.alpha, + metric=self.metric, + n_jobs=self.n_jobs, + **self._metric_params, + ) + if self.algorithm == "kd_tree" and self.metric not in KDTree.valid_metrics: + raise ValueError( + f"{self.metric} is not a valid metric for a KDTree-based algorithm." + " Please select a different metric." + ) + elif ( + self.algorithm == "ball_tree" and self.metric not in BallTree.valid_metrics + ): + raise ValueError( + f"{self.metric} is not a valid metric for a BallTree-based algorithm." + " Please select a different metric." + ) + + if self.algorithm != "auto": + if ( + self.metric != "precomputed" + and issparse(X) + and self.algorithm != "brute" + ): + raise ValueError("Sparse data matrices only support algorithm `brute`.") + + if self.algorithm == "brute": + mst_func = _hdbscan_brute + kwargs["copy"] = self.copy + elif self.algorithm == "kd_tree": + mst_func = _hdbscan_prims + kwargs["algo"] = "kd_tree" + kwargs["leaf_size"] = self.leaf_size + else: + mst_func = _hdbscan_prims + kwargs["algo"] = "ball_tree" + kwargs["leaf_size"] = self.leaf_size + else: + if issparse(X) or self.metric not in FAST_METRICS: + # We can't do much with sparse matrices ... + mst_func = _hdbscan_brute + kwargs["copy"] = self.copy + elif self.metric in KDTree.valid_metrics: + # TODO: Benchmark KD vs Ball Tree efficiency + mst_func = _hdbscan_prims + kwargs["algo"] = "kd_tree" + kwargs["leaf_size"] = self.leaf_size + else: + # Metric is a valid BallTree metric + mst_func = _hdbscan_prims + kwargs["algo"] = "ball_tree" + kwargs["leaf_size"] = self.leaf_size + + self._single_linkage_tree_ = mst_func(**kwargs) + + self.labels_, self.probabilities_ = tree_to_labels( + self._single_linkage_tree_, + self.min_cluster_size, + self.cluster_selection_method, + self.allow_single_cluster, + self.cluster_selection_epsilon, + self.max_cluster_size, + ) + if self.metric != "precomputed" and not all_finite: + # Remap indices to align with original data in the case of + # non-finite entries. Samples with np.inf are mapped to -1 and + # those with np.nan are mapped to -2. + self._single_linkage_tree_ = remap_single_linkage_tree( + self._single_linkage_tree_, + internal_to_raw, + # There may be overlap for points w/ both `np.inf` and `np.nan` + non_finite=set(np.hstack([infinite_index, missing_index])), + ) + new_labels = np.empty(self._raw_data.shape[0], dtype=np.int32) + new_labels[finite_index] = self.labels_ + new_labels[infinite_index] = _OUTLIER_ENCODING["infinite"]["label"] + new_labels[missing_index] = _OUTLIER_ENCODING["missing"]["label"] + self.labels_ = new_labels + + new_probabilities = np.zeros(self._raw_data.shape[0], dtype=np.float64) + new_probabilities[finite_index] = self.probabilities_ + # Infinite outliers have probability 0 by convention, though this + # is arbitrary. + new_probabilities[infinite_index] = _OUTLIER_ENCODING["infinite"]["prob"] + new_probabilities[missing_index] = _OUTLIER_ENCODING["missing"]["prob"] + self.probabilities_ = new_probabilities + + if self.store_centers: + self._weighted_cluster_center(X) + return self + + def fit_predict(self, X, y=None): + """Cluster X and return the associated cluster labels. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features), or \ + ndarray of shape (n_samples, n_samples) + A feature array, or array of distances between samples if + `metric='precomputed'`. + + y : None + Ignored. + + Returns + ------- + y : ndarray of shape (n_samples,) + Cluster labels. + """ + self.fit(X) + return self.labels_ + + def _weighted_cluster_center(self, X): + """Calculate and store the centroids/medoids of each cluster. + + This requires `X` to be a raw feature array, not precomputed + distances. Rather than return outputs directly, this helper method + instead stores them in the `self.{centroids, medoids}_` attributes. + The choice for which attributes are calculated and stored is mediated + by the value of `self.store_centers`. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The feature array that the estimator was fit with. + + """ + # Number of non-noise clusters + n_clusters = len(set(self.labels_) - {-1, -2}) + mask = np.empty((X.shape[0],), dtype=np.bool_) + make_centroids = self.store_centers in ("centroid", "both") + make_medoids = self.store_centers in ("medoid", "both") + + if make_centroids: + self.centroids_ = np.empty((n_clusters, X.shape[1]), dtype=np.float64) + if make_medoids: + self.medoids_ = np.empty((n_clusters, X.shape[1]), dtype=np.float64) + + # Need to handle iteratively seen each cluster may have a different + # number of samples, hence we can't create a homogeneous 3D array. + for idx in range(n_clusters): + mask = self.labels_ == idx + data = X[mask] + strength = self.probabilities_[mask] + if make_centroids: + self.centroids_[idx] = np.average(data, weights=strength, axis=0) + if make_medoids: + # TODO: Implement weighted argmin PWD backend + dist_mat = pairwise_distances( + data, metric=self.metric, **self._metric_params + ) + dist_mat = dist_mat * strength + medoid_index = np.argmin(dist_mat.sum(axis=1)) + self.medoids_[idx] = data[medoid_index] + return + + def dbscan_clustering(self, cut_distance, min_cluster_size=5): + """Return clustering given by DBSCAN without border points. + + Return clustering that would be equivalent to running DBSCAN* for a + particular cut_distance (or epsilon) DBSCAN* can be thought of as + DBSCAN without the border points. As such these results may differ + slightly from `cluster.DBSCAN` due to the difference in implementation + over the non-core points. + + This can also be thought of as a flat clustering derived from constant + height cut through the single linkage tree. + + This represents the result of selecting a cut value for robust single linkage + clustering. The `min_cluster_size` allows the flat clustering to declare noise + points (and cluster smaller than `min_cluster_size`). + + Parameters + ---------- + cut_distance : float + The mutual reachability distance cut value to use to generate a + flat clustering. + + min_cluster_size : int, default=5 + Clusters smaller than this value with be called 'noise' and remain + unclustered in the resulting flat clustering. + + Returns + ------- + labels : ndarray of shape (n_samples,) + An array of cluster labels, one per datapoint. + Outliers are labeled as follows: + + - Noisy samples are given the label -1. + - Samples with infinite elements (+/- np.inf) are given the label -2. + - Samples with missing data are given the label -3, even if they + also have infinite elements. + """ + labels = labelling_at_cut( + self._single_linkage_tree_, cut_distance, min_cluster_size + ) + # Infer indices from labels generated during `fit` + infinite_index = self.labels_ == _OUTLIER_ENCODING["infinite"]["label"] + missing_index = self.labels_ == _OUTLIER_ENCODING["missing"]["label"] + + # Overwrite infinite/missing outlier samples (otherwise simple noise) + labels[infinite_index] = _OUTLIER_ENCODING["infinite"]["label"] + labels[missing_index] = _OUTLIER_ENCODING["missing"]["label"] + return labels + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + tags.input_tags.allow_nan = self.metric != "precomputed" + return tags diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/meson.build b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/meson.build new file mode 100644 index 0000000000000000000000000000000000000000..8d880b39a4db58dffa1b282c3633c873755f5245 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/meson.build @@ -0,0 +1,15 @@ +cluster_hdbscan_extension_metadata = { + '_linkage': {'sources': [cython_gen.process('_linkage.pyx'), metrics_cython_tree]}, + '_reachability': {'sources': [cython_gen.process('_reachability.pyx')]}, + '_tree': {'sources': [cython_gen.process('_tree.pyx')]} +} + +foreach ext_name, ext_dict : cluster_hdbscan_extension_metadata + py.extension_module( + ext_name, + ext_dict.get('sources'), + dependencies: [np_dep], + subdir: 'sklearn/cluster/_hdbscan', + install: true + ) +endforeach diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/tests/test_reachibility.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/tests/test_reachibility.py new file mode 100644 index 0000000000000000000000000000000000000000..a336e6be6116d1345a1d4eb0448c2e2f58cd8ecd --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hdbscan/tests/test_reachibility.py @@ -0,0 +1,63 @@ +import numpy as np +import pytest + +from sklearn.cluster._hdbscan._reachability import mutual_reachability_graph +from sklearn.utils._testing import ( + _convert_container, + assert_allclose, +) + + +def test_mutual_reachability_graph_error_sparse_format(): + """Check that we raise an error if the sparse format is not CSR.""" + rng = np.random.RandomState(0) + X = rng.randn(10, 10) + X = X.T @ X + np.fill_diagonal(X, 0.0) + X = _convert_container(X, "sparse_csc") + + err_msg = "Only sparse CSR matrices are supported" + with pytest.raises(ValueError, match=err_msg): + mutual_reachability_graph(X) + + +@pytest.mark.parametrize("array_type", ["array", "sparse_csr"]) +def test_mutual_reachability_graph_inplace(array_type): + """Check that the operation is happening inplace.""" + rng = np.random.RandomState(0) + X = rng.randn(10, 10) + X = X.T @ X + np.fill_diagonal(X, 0.0) + X = _convert_container(X, array_type) + + mr_graph = mutual_reachability_graph(X) + + assert id(mr_graph) == id(X) + + +def test_mutual_reachability_graph_equivalence_dense_sparse(): + """Check that we get the same results for dense and sparse implementation.""" + rng = np.random.RandomState(0) + X = rng.randn(5, 5) + X_dense = X.T @ X + X_sparse = _convert_container(X_dense, "sparse_csr") + + mr_graph_dense = mutual_reachability_graph(X_dense, min_samples=3) + mr_graph_sparse = mutual_reachability_graph(X_sparse, min_samples=3) + + assert_allclose(mr_graph_dense, mr_graph_sparse.toarray()) + + +@pytest.mark.parametrize("array_type", ["array", "sparse_csr"]) +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_mutual_reachability_graph_preserves_dtype(array_type, dtype): + """Check that the computation preserve dtype thanks to fused types.""" + rng = np.random.RandomState(0) + X = rng.randn(10, 10) + X = (X.T @ X).astype(dtype) + np.fill_diagonal(X, 0.0) + X = _convert_container(X, array_type) + + assert X.dtype == dtype + mr_graph = mutual_reachability_graph(X) + assert mr_graph.dtype == dtype diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.pxd b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.pxd new file mode 100644 index 0000000000000000000000000000000000000000..a10f8c12f34402c872ccc3bd7c14266dcc9b5e7a --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.pxd @@ -0,0 +1,9 @@ +from ..utils._typedefs cimport intp_t + +cdef class UnionFind: + cdef intp_t next_label + cdef intp_t[:] parent + cdef intp_t[:] size + + cdef void union(self, intp_t m, intp_t n) noexcept + cdef intp_t fast_find(self, intp_t n) noexcept diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.pyx b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.pyx new file mode 100644 index 0000000000000000000000000000000000000000..36ae0ab0d241432df9f5833901580dc88c30d925 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.pyx @@ -0,0 +1,507 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numpy as np +cimport cython + +from ..metrics._dist_metrics cimport DistanceMetric64 +from ..utils._fast_dict cimport IntFloatDict +from ..utils._typedefs cimport float64_t, intp_t, uint8_t + +# C++ +from cython.operator cimport dereference as deref, preincrement as inc +from libcpp.map cimport map as cpp_map +from libc.math cimport fmax, INFINITY + + +############################################################################### +# Utilities for computing the ward momentum + +def compute_ward_dist( + const float64_t[::1] m_1, + const float64_t[:, ::1] m_2, + const intp_t[::1] coord_row, + const intp_t[::1] coord_col, + float64_t[::1] res +): + cdef intp_t size_max = coord_row.shape[0] + cdef intp_t n_features = m_2.shape[1] + cdef intp_t i, j, row, col + cdef float64_t pa, n + + for i in range(size_max): + row = coord_row[i] + col = coord_col[i] + n = (m_1[row] * m_1[col]) / (m_1[row] + m_1[col]) + pa = 0. + for j in range(n_features): + pa += (m_2[row, j] / m_1[row] - m_2[col, j] / m_1[col]) ** 2 + res[i] = pa * n + + +############################################################################### +# Utilities for cutting and exploring a hierarchical tree + +def _hc_get_descendent(intp_t node, children, intp_t n_leaves): + """ + Function returning all the descendent leaves of a set of nodes in the tree. + + Parameters + ---------- + node : integer + The node for which we want the descendents. + + children : list of pairs, length n_nodes + The children of each non-leaf node. Values less than `n_samples` refer + to leaves of the tree. A greater value `i` indicates a node with + children `children[i - n_samples]`. + + n_leaves : integer + Number of leaves. + + Returns + ------- + descendent : list of int + """ + ind = [node] + if node < n_leaves: + return ind + descendent = [] + + # It is actually faster to do the accounting of the number of + # elements is the list ourselves: len is a lengthy operation on a + # chained list + cdef intp_t i, n_indices = 1 + + while n_indices: + i = ind.pop() + if i < n_leaves: + descendent.append(i) + n_indices -= 1 + else: + ind.extend(children[i - n_leaves]) + n_indices += 1 + return descendent + + +def hc_get_heads(intp_t[:] parents, copy=True): + """Returns the heads of the forest, as defined by parents. + + Parameters + ---------- + parents : array of integers + The parent structure defining the forest (ensemble of trees) + copy : boolean + If copy is False, the input 'parents' array is modified inplace + + Returns + ------- + heads : array of integers of same shape as parents + The indices in the 'parents' of the tree heads + + """ + cdef intp_t parent, node0, node, size + if copy: + parents = np.copy(parents) + size = parents.size + + # Start from the top of the tree and go down + for node0 in range(size - 1, -1, -1): + node = node0 + parent = parents[node] + while parent != node: + parents[node0] = parent + node = parent + parent = parents[node] + return parents + + +def _get_parents( + nodes, + heads, + const intp_t[:] parents, + uint8_t[::1] not_visited +): + """Returns the heads of the given nodes, as defined by parents. + + Modifies 'heads' and 'not_visited' in-place. + + Parameters + ---------- + nodes : list of integers + The nodes to start from + heads : list of integers + A list to hold the results (modified inplace) + parents : array of integers + The parent structure defining the tree + not_visited + The tree nodes to consider (modified inplace) + + """ + cdef intp_t parent, node + + for node in nodes: + parent = parents[node] + while parent != node: + node = parent + parent = parents[node] + if not_visited[node]: + not_visited[node] = 0 + heads.append(node) + + +############################################################################### +# merge strategies implemented on IntFloatDicts + +# These are used in the hierarchical clustering code, to implement +# merging between two clusters, defined as a dict containing node number +# as keys and edge weights as values. + + +def max_merge( + IntFloatDict a, + IntFloatDict b, + const intp_t[:] mask, + intp_t n_a, + intp_t n_b +): + """Merge two IntFloatDicts with the max strategy: when the same key is + present in the two dicts, the max of the two values is used. + + Parameters + ========== + a, b : IntFloatDict object + The IntFloatDicts to merge + mask : ndarray array of dtype integer and of dimension 1 + a mask for keys to ignore: if not mask[key] the corresponding key + is skipped in the output dictionary + n_a, n_b : float + n_a and n_b are weights for a and b for the merge strategy. + They are not used in the case of a max merge. + + Returns + ======= + out : IntFloatDict object + The IntFloatDict resulting from the merge + """ + cdef IntFloatDict out_obj = IntFloatDict.__new__(IntFloatDict) + cdef cpp_map[intp_t, float64_t].iterator a_it = a.my_map.begin() + cdef cpp_map[intp_t, float64_t].iterator a_end = a.my_map.end() + cdef intp_t key + cdef float64_t value + # First copy a into out + while a_it != a_end: + key = deref(a_it).first + if mask[key]: + out_obj.my_map[key] = deref(a_it).second + inc(a_it) + + # Then merge b into out + cdef cpp_map[intp_t, float64_t].iterator out_it = out_obj.my_map.begin() + cdef cpp_map[intp_t, float64_t].iterator out_end = out_obj.my_map.end() + cdef cpp_map[intp_t, float64_t].iterator b_it = b.my_map.begin() + cdef cpp_map[intp_t, float64_t].iterator b_end = b.my_map.end() + while b_it != b_end: + key = deref(b_it).first + value = deref(b_it).second + if mask[key]: + out_it = out_obj.my_map.find(key) + if out_it == out_end: + # Key not found + out_obj.my_map[key] = value + else: + deref(out_it).second = fmax(deref(out_it).second, value) + inc(b_it) + return out_obj + + +def average_merge( + IntFloatDict a, + IntFloatDict b, + const intp_t[:] mask, + intp_t n_a, + intp_t n_b +): + """Merge two IntFloatDicts with the average strategy: when the + same key is present in the two dicts, the weighted average of the two + values is used. + + Parameters + ========== + a, b : IntFloatDict object + The IntFloatDicts to merge + mask : ndarray array of dtype integer and of dimension 1 + a mask for keys to ignore: if not mask[key] the corresponding key + is skipped in the output dictionary + n_a, n_b : float + n_a and n_b are weights for a and b for the merge strategy. + They are used for a weighted mean. + + Returns + ======= + out : IntFloatDict object + The IntFloatDict resulting from the merge + """ + cdef IntFloatDict out_obj = IntFloatDict.__new__(IntFloatDict) + cdef cpp_map[intp_t, float64_t].iterator a_it = a.my_map.begin() + cdef cpp_map[intp_t, float64_t].iterator a_end = a.my_map.end() + cdef intp_t key + cdef float64_t value + cdef float64_t n_out = (n_a + n_b) + # First copy a into out + while a_it != a_end: + key = deref(a_it).first + if mask[key]: + out_obj.my_map[key] = deref(a_it).second + inc(a_it) + + # Then merge b into out + cdef cpp_map[intp_t, float64_t].iterator out_it = out_obj.my_map.begin() + cdef cpp_map[intp_t, float64_t].iterator out_end = out_obj.my_map.end() + cdef cpp_map[intp_t, float64_t].iterator b_it = b.my_map.begin() + cdef cpp_map[intp_t, float64_t].iterator b_end = b.my_map.end() + while b_it != b_end: + key = deref(b_it).first + value = deref(b_it).second + if mask[key]: + out_it = out_obj.my_map.find(key) + if out_it == out_end: + # Key not found + out_obj.my_map[key] = value + else: + deref(out_it).second = (n_a * deref(out_it).second + + n_b * value) / n_out + inc(b_it) + return out_obj + + +############################################################################### +# An edge object for fast comparisons + +cdef class WeightedEdge: + cdef public intp_t a + cdef public intp_t b + cdef public float64_t weight + + def __init__(self, float64_t weight, intp_t a, intp_t b): + self.weight = weight + self.a = a + self.b = b + + def __richcmp__(self, WeightedEdge other, int op): + """Cython-specific comparison method. + + op is the comparison code:: + < 0 + == 2 + > 4 + <= 1 + != 3 + >= 5 + """ + if op == 0: + return self.weight < other.weight + elif op == 1: + return self.weight <= other.weight + elif op == 2: + return self.weight == other.weight + elif op == 3: + return self.weight != other.weight + elif op == 4: + return self.weight > other.weight + elif op == 5: + return self.weight >= other.weight + + def __repr__(self): + return "%s(weight=%f, a=%i, b=%i)" % (self.__class__.__name__, + self.weight, + self.a, self.b) + + +################################################################################ +# Efficient labelling/conversion of MSTs to single linkage hierarchies + +cdef class UnionFind(object): + + def __init__(self, N): + self.parent = np.full(2 * N - 1, -1., dtype=np.intp, order='C') + self.next_label = N + self.size = np.hstack((np.ones(N, dtype=np.intp), + np.zeros(N - 1, dtype=np.intp))) + + cdef void union(self, intp_t m, intp_t n) noexcept: + self.parent[m] = self.next_label + self.parent[n] = self.next_label + self.size[self.next_label] = self.size[m] + self.size[n] + self.next_label += 1 + return + + @cython.wraparound(True) + cdef intp_t fast_find(self, intp_t n) noexcept: + cdef intp_t p + p = n + # find the highest node in the linkage graph so far + while self.parent[n] != -1: + n = self.parent[n] + # provide a shortcut up to the highest node + while self.parent[p] != n: + p, self.parent[p] = self.parent[p], n + return n + + +def _single_linkage_label(const float64_t[:, :] L): + """ + Convert an linkage array or MST to a tree by labelling clusters at merges. + This is done by using a Union find structure to keep track of merges + efficiently. This is the private version of the function that assumes that + ``L`` has been properly validated. See ``single_linkage_label`` for the + user facing version of this function. + + Parameters + ---------- + L: array of shape (n_samples - 1, 3) + The linkage array or MST where each row specifies two samples + to be merged and a distance or weight at which the merge occurs. This + array is assumed to be sorted by the distance/weight. + + Returns + ------- + A tree in the format used by scipy.cluster.hierarchy. + """ + + cdef float64_t[:, ::1] result_arr + + cdef intp_t left, left_cluster, right, right_cluster, index + cdef float64_t delta + + result_arr = np.zeros((L.shape[0], 4), dtype=np.float64) + U = UnionFind(L.shape[0] + 1) + + for index in range(L.shape[0]): + + left = L[index, 0] + right = L[index, 1] + delta = L[index, 2] + + left_cluster = U.fast_find(left) + right_cluster = U.fast_find(right) + + result_arr[index][0] = left_cluster + result_arr[index][1] = right_cluster + result_arr[index][2] = delta + result_arr[index][3] = U.size[left_cluster] + U.size[right_cluster] + + U.union(left_cluster, right_cluster) + + return np.asarray(result_arr) + + +@cython.wraparound(True) +def single_linkage_label(L): + """ + Convert an linkage array or MST to a tree by labelling clusters at merges. + This is done by using a Union find structure to keep track of merges + efficiently. + + Parameters + ---------- + L: array of shape (n_samples - 1, 3) + The linkage array or MST where each row specifies two samples + to be merged and a distance or weight at which the merge occurs. This + array is assumed to be sorted by the distance/weight. + + Returns + ------- + A tree in the format used by scipy.cluster.hierarchy. + """ + # Validate L + if L[:, :2].min() < 0 or L[:, :2].max() >= 2 * L.shape[0] + 1: + raise ValueError("Input MST array is not a validly formatted MST array") + + is_sorted = lambda x: np.all(x[:-1] <= x[1:]) + if not is_sorted(L[:, 2]): + raise ValueError("Input MST array must be sorted by weight") + + return _single_linkage_label(L) + + +# Implements MST-LINKAGE-CORE from https://arxiv.org/abs/1109.2378 +def mst_linkage_core( + const float64_t [:, ::1] raw_data, + DistanceMetric64 dist_metric): + """ + Compute the necessary elements of a minimum spanning + tree for computation of single linkage clustering. This + represents the MST-LINKAGE-CORE algorithm (Figure 6) from + :arxiv:`Daniel Mullner, "Modern hierarchical, agglomerative clustering + algorithms" <1109.2378>`. + + In contrast to the scipy implementation is never computes + a full distance matrix, generating distances only as they + are needed and releasing them when no longer needed. + + Parameters + ---------- + raw_data: array of shape (n_samples, n_features) + The array of feature data to be clustered. Must be C-aligned + + dist_metric: DistanceMetric64 + A DistanceMetric64 object conforming to the API from + ``sklearn.metrics._dist_metrics.pxd`` that will be + used to compute distances. + + Returns + ------- + mst_core_data: array of shape (n_samples, 3) + An array providing information from which one + can either compute an MST, or the linkage hierarchy + very efficiently. See :arxiv:`Daniel Mullner, "Modern hierarchical, + agglomerative clustering algorithms" <1109.2378>` algorithm + MST-LINKAGE-CORE for more details. + """ + cdef: + intp_t n_samples = raw_data.shape[0] + uint8_t[:] in_tree = np.zeros(n_samples, dtype=bool) + float64_t[:, ::1] result = np.zeros((n_samples - 1, 3)) + + intp_t current_node = 0 + intp_t new_node + intp_t i + intp_t j + intp_t num_features = raw_data.shape[1] + + float64_t right_value + float64_t left_value + float64_t new_distance + + float64_t[:] current_distances = np.full(n_samples, INFINITY) + + for i in range(n_samples - 1): + + in_tree[current_node] = 1 + + new_distance = INFINITY + new_node = 0 + + for j in range(n_samples): + if in_tree[j]: + continue + + right_value = current_distances[j] + left_value = dist_metric.dist(&raw_data[current_node, 0], + &raw_data[j, 0], + num_features) + + if left_value < right_value: + current_distances[j] = left_value + + if current_distances[j] < new_distance: + new_distance = current_distances[j] + new_node = j + + result[i, 0] = current_node + result[i, 1] = new_node + result[i, 2] = new_distance + current_node = new_node + + return np.array(result) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.pxd b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.pxd new file mode 100644 index 0000000000000000000000000000000000000000..9a41ea68d1bafc0cad55c028e0413e463ddb6d2e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.pxd @@ -0,0 +1,48 @@ +from cython cimport floating + + +cdef floating _euclidean_dense_dense( + const floating*, + const floating*, + int, + bint +) noexcept nogil + +cdef floating _euclidean_sparse_dense( + const floating[::1], + const int[::1], + const floating[::1], + floating, + bint +) noexcept nogil + +cpdef void _relocate_empty_clusters_dense( + const floating[:, ::1], + const floating[::1], + const floating[:, ::1], + floating[:, ::1], + floating[::1], + const int[::1] +) + +cpdef void _relocate_empty_clusters_sparse( + const floating[::1], + const int[::1], + const int[::1], + const floating[::1], + const floating[:, ::1], + floating[:, ::1], + floating[::1], + const int[::1] +) + +cdef void _average_centers( + floating[:, ::1], + const floating[::1] +) + +cdef void _center_shift( + const floating[:, ::1], + const floating[:, ::1], + floating[::1] +) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.pyx b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.pyx new file mode 100644 index 0000000000000000000000000000000000000000..674d4026a67564f266ec709a9f47d77f8f912386 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.pyx @@ -0,0 +1,328 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numpy as np +from cython cimport floating +from cython.parallel cimport prange +from libc.math cimport sqrt + +from ..utils.extmath import row_norms + + +# Number of samples per data chunk defined as a global constant. +CHUNK_SIZE = 256 + + +cdef floating _euclidean_dense_dense( + const floating* a, # IN + const floating* b, # IN + int n_features, + bint squared +) noexcept nogil: + """Euclidean distance between a dense and b dense""" + cdef: + int i + int n = n_features // 4 + int rem = n_features % 4 + floating result = 0 + + # We manually unroll the loop for better cache optimization. + for i in range(n): + result += ( + (a[0] - b[0]) * (a[0] - b[0]) + + (a[1] - b[1]) * (a[1] - b[1]) + + (a[2] - b[2]) * (a[2] - b[2]) + + (a[3] - b[3]) * (a[3] - b[3]) + ) + a += 4 + b += 4 + + for i in range(rem): + result += (a[i] - b[i]) * (a[i] - b[i]) + + return result if squared else sqrt(result) + + +def _euclidean_dense_dense_wrapper( + const floating[::1] a, + const floating[::1] b, + bint squared +): + """Wrapper of _euclidean_dense_dense for testing purpose""" + return _euclidean_dense_dense(&a[0], &b[0], a.shape[0], squared) + + +cdef floating _euclidean_sparse_dense( + const floating[::1] a_data, # IN + const int[::1] a_indices, # IN + const floating[::1] b, # IN + floating b_squared_norm, + bint squared +) noexcept nogil: + """Euclidean distance between a sparse and b dense""" + cdef: + int nnz = a_indices.shape[0] + int i + floating tmp, bi + floating result = 0.0 + + for i in range(nnz): + bi = b[a_indices[i]] + tmp = a_data[i] - bi + result += tmp * tmp - bi * bi + + result += b_squared_norm + + if result < 0: + result = 0.0 + + return result if squared else sqrt(result) + + +def _euclidean_sparse_dense_wrapper( + const floating[::1] a_data, + const int[::1] a_indices, + const floating[::1] b, + floating b_squared_norm, + bint squared +): + """Wrapper of _euclidean_sparse_dense for testing purpose""" + return _euclidean_sparse_dense( + a_data, a_indices, b, b_squared_norm, squared) + + +cpdef floating _inertia_dense( + const floating[:, ::1] X, # IN + const floating[::1] sample_weight, # IN + const floating[:, ::1] centers, # IN + const int[::1] labels, # IN + int n_threads, + int single_label=-1, +): + """Compute inertia for dense input data + + Sum of squared distance between each sample and its assigned center. + + If single_label is >= 0, the inertia is computed only for that label. + """ + cdef: + int n_samples = X.shape[0] + int n_features = X.shape[1] + int i, j + + floating sq_dist = 0.0 + floating inertia = 0.0 + + for i in prange(n_samples, nogil=True, num_threads=n_threads, + schedule='static'): + j = labels[i] + if single_label < 0 or single_label == j: + sq_dist = _euclidean_dense_dense(&X[i, 0], ¢ers[j, 0], + n_features, True) + inertia += sq_dist * sample_weight[i] + + return inertia + + +cpdef floating _inertia_sparse( + X, # IN + const floating[::1] sample_weight, # IN + const floating[:, ::1] centers, # IN + const int[::1] labels, # IN + int n_threads, + int single_label=-1, +): + """Compute inertia for sparse input data + + Sum of squared distance between each sample and its assigned center. + + If single_label is >= 0, the inertia is computed only for that label. + """ + cdef: + floating[::1] X_data = X.data + int[::1] X_indices = X.indices + int[::1] X_indptr = X.indptr + + int n_samples = X.shape[0] + int i, j + + floating sq_dist = 0.0 + floating inertia = 0.0 + + floating[::1] centers_squared_norms = row_norms(centers, squared=True) + + for i in prange(n_samples, nogil=True, num_threads=n_threads, + schedule='static'): + j = labels[i] + if single_label < 0 or single_label == j: + sq_dist = _euclidean_sparse_dense( + X_data[X_indptr[i]: X_indptr[i + 1]], + X_indices[X_indptr[i]: X_indptr[i + 1]], + centers[j], centers_squared_norms[j], True) + inertia += sq_dist * sample_weight[i] + + return inertia + + +cpdef void _relocate_empty_clusters_dense( + const floating[:, ::1] X, # IN + const floating[::1] sample_weight, # IN + const floating[:, ::1] centers_old, # IN + floating[:, ::1] centers_new, # INOUT + floating[::1] weight_in_clusters, # INOUT + const int[::1] labels # IN +): + """Relocate centers which have no sample assigned to them.""" + cdef: + int[::1] empty_clusters = np.where(np.equal(weight_in_clusters, 0))[0].astype(np.int32) + int n_empty = empty_clusters.shape[0] + + if n_empty == 0: + return + + cdef: + int n_features = X.shape[1] + + floating[::1] distances = ((np.asarray(X) - np.asarray(centers_old)[labels])**2).sum(axis=1) + int[::1] far_from_centers = np.argpartition(distances, -n_empty)[:-n_empty-1:-1].astype(np.int32) + + int new_cluster_id, old_cluster_id, far_idx, idx, k + floating weight + + if np.max(distances) == 0: + # Happens when there are more clusters than non-duplicate samples. Relocating + # is pointless in this case. + return + + for idx in range(n_empty): + + new_cluster_id = empty_clusters[idx] + + far_idx = far_from_centers[idx] + weight = sample_weight[far_idx] + + old_cluster_id = labels[far_idx] + + for k in range(n_features): + centers_new[old_cluster_id, k] -= X[far_idx, k] * weight + centers_new[new_cluster_id, k] = X[far_idx, k] * weight + + weight_in_clusters[new_cluster_id] = weight + weight_in_clusters[old_cluster_id] -= weight + + +cpdef void _relocate_empty_clusters_sparse( + const floating[::1] X_data, # IN + const int[::1] X_indices, # IN + const int[::1] X_indptr, # IN + const floating[::1] sample_weight, # IN + const floating[:, ::1] centers_old, # IN + floating[:, ::1] centers_new, # INOUT + floating[::1] weight_in_clusters, # INOUT + const int[::1] labels # IN +): + """Relocate centers which have no sample assigned to them.""" + cdef: + int[::1] empty_clusters = np.where(np.equal(weight_in_clusters, 0))[0].astype(np.int32) + int n_empty = empty_clusters.shape[0] + + if n_empty == 0: + return + + cdef: + int n_samples = X_indptr.shape[0] - 1 + int i, j, k + + floating[::1] distances = np.zeros(n_samples, dtype=X_data.base.dtype) + floating[::1] centers_squared_norms = row_norms(centers_old, squared=True) + + for i in range(n_samples): + j = labels[i] + distances[i] = _euclidean_sparse_dense( + X_data[X_indptr[i]: X_indptr[i + 1]], + X_indices[X_indptr[i]: X_indptr[i + 1]], + centers_old[j], centers_squared_norms[j], True) + + if np.max(distances) == 0: + # Happens when there are more clusters than non-duplicate samples. Relocating + # is pointless in this case. + return + + cdef: + int[::1] far_from_centers = np.argpartition(distances, -n_empty)[:-n_empty-1:-1].astype(np.int32) + + int new_cluster_id, old_cluster_id, far_idx, idx + floating weight + + for idx in range(n_empty): + + new_cluster_id = empty_clusters[idx] + + far_idx = far_from_centers[idx] + weight = sample_weight[far_idx] + + old_cluster_id = labels[far_idx] + + for k in range(X_indptr[far_idx], X_indptr[far_idx + 1]): + centers_new[old_cluster_id, X_indices[k]] -= X_data[k] * weight + centers_new[new_cluster_id, X_indices[k]] = X_data[k] * weight + + weight_in_clusters[new_cluster_id] = weight + weight_in_clusters[old_cluster_id] -= weight + + +cdef void _average_centers( + floating[:, ::1] centers, # INOUT + const floating[::1] weight_in_clusters # IN +): + """Average new centers wrt weights.""" + cdef: + int n_clusters = centers.shape[0] + int n_features = centers.shape[1] + int j, k + floating alpha + int argmax_weight = np.argmax(weight_in_clusters) + + for j in range(n_clusters): + if weight_in_clusters[j] > 0: + alpha = 1.0 / weight_in_clusters[j] + for k in range(n_features): + centers[j, k] *= alpha + else: + # For convenience, we avoid setting empty clusters at the origin but place + # them at the location of the biggest cluster. + for k in range(n_features): + centers[j, k] = centers[argmax_weight, k] + + +cdef void _center_shift( + const floating[:, ::1] centers_old, # IN + const floating[:, ::1] centers_new, # IN + floating[::1] center_shift # OUT +): + """Compute shift between old and new centers.""" + cdef: + int n_clusters = centers_old.shape[0] + int n_features = centers_old.shape[1] + int j + + for j in range(n_clusters): + center_shift[j] = _euclidean_dense_dense( + ¢ers_new[j, 0], ¢ers_old[j, 0], n_features, False) + + +def _is_same_clustering( + const int[::1] labels1, + const int[::1] labels2, + n_clusters +): + """Check if two arrays of labels are the same up to a permutation of the labels""" + cdef int[::1] mapping = np.full(fill_value=-1, shape=(n_clusters,), dtype=np.int32) + cdef int i + + for i in range(labels1.shape[0]): + if mapping[labels1[i]] == -1: + mapping[labels1[i]] = labels2[i] + elif mapping[labels1[i]] != labels2[i]: + return False + return True diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_k_means_elkan.pyx b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_k_means_elkan.pyx new file mode 100644 index 0000000000000000000000000000000000000000..564218a17f7018241d43dd33f55d3f516746a145 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_k_means_elkan.pyx @@ -0,0 +1,686 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from cython cimport floating +from cython.parallel import prange, parallel +from libc.stdlib cimport calloc, free +from libc.string cimport memset + +from ..utils._openmp_helpers cimport omp_lock_t +from ..utils._openmp_helpers cimport omp_init_lock +from ..utils._openmp_helpers cimport omp_destroy_lock +from ..utils._openmp_helpers cimport omp_set_lock +from ..utils._openmp_helpers cimport omp_unset_lock +from ..utils.extmath import row_norms +from ._k_means_common import CHUNK_SIZE +from ._k_means_common cimport _relocate_empty_clusters_dense +from ._k_means_common cimport _relocate_empty_clusters_sparse +from ._k_means_common cimport _euclidean_dense_dense +from ._k_means_common cimport _euclidean_sparse_dense +from ._k_means_common cimport _average_centers +from ._k_means_common cimport _center_shift + + +def init_bounds_dense( + const floating[:, ::1] X, # IN + const floating[:, ::1] centers, # IN + const floating[:, ::1] center_half_distances, # IN + int[::1] labels, # OUT + floating[::1] upper_bounds, # OUT + floating[:, ::1] lower_bounds, # OUT + int n_threads): + """Initialize upper and lower bounds for each sample for dense input data. + + Given X, centers and the pairwise distances divided by 2.0 between the + centers this calculates the upper bounds and lower bounds for each sample. + The upper bound for each sample is set to the distance between the sample + and the closest center. + + The lower bound for each sample is a one-dimensional array of n_clusters. + For each sample i assume that the previously assigned cluster is c1 and the + previous closest distance is dist, for a new cluster c2, the + lower_bound[i][c2] is set to distance between the sample and this new + cluster, if and only if dist > center_half_distances[c1][c2]. This prevents + computation of unnecessary distances for each sample to the clusters that + it is unlikely to be assigned to. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features), dtype=floating + The input data. + + centers : ndarray of shape (n_clusters, n_features), dtype=floating + The cluster centers. + + center_half_distances : ndarray of shape (n_clusters, n_clusters), \ + dtype=floating + The half of the distance between any 2 clusters centers. + + labels : ndarray of shape(n_samples), dtype=int + The label for each sample. This array is modified in place. + + upper_bounds : ndarray of shape(n_samples,), dtype=floating + The upper bound on the distance between each sample and its closest + cluster center. This array is modified in place. + + lower_bounds : ndarray, of shape(n_samples, n_clusters), dtype=floating + The lower bound on the distance between each sample and each cluster + center. This array is modified in place. + + n_threads : int + The number of threads to be used by openmp. + """ + cdef: + int n_samples = X.shape[0] + int n_clusters = centers.shape[0] + int n_features = X.shape[1] + + floating min_dist, dist + int best_cluster, i, j + + for i in prange( + n_samples, num_threads=n_threads, schedule='static', nogil=True + ): + best_cluster = 0 + min_dist = _euclidean_dense_dense(&X[i, 0], ¢ers[0, 0], + n_features, False) + lower_bounds[i, 0] = min_dist + for j in range(1, n_clusters): + if min_dist > center_half_distances[best_cluster, j]: + dist = _euclidean_dense_dense(&X[i, 0], ¢ers[j, 0], + n_features, False) + lower_bounds[i, j] = dist + if dist < min_dist: + min_dist = dist + best_cluster = j + labels[i] = best_cluster + upper_bounds[i] = min_dist + + +def init_bounds_sparse( + X, # IN + const floating[:, ::1] centers, # IN + const floating[:, ::1] center_half_distances, # IN + int[::1] labels, # OUT + floating[::1] upper_bounds, # OUT + floating[:, ::1] lower_bounds, # OUT + int n_threads): + """Initialize upper and lower bounds for each sample for sparse input data. + + Given X, centers and the pairwise distances divided by 2.0 between the + centers this calculates the upper bounds and lower bounds for each sample. + The upper bound for each sample is set to the distance between the sample + and the closest center. + + The lower bound for each sample is a one-dimensional array of n_clusters. + For each sample i assume that the previously assigned cluster is c1 and the + previous closest distance is dist, for a new cluster c2, the + lower_bound[i][c2] is set to distance between the sample and this new + cluster, if and only if dist > center_half_distances[c1][c2]. This prevents + computation of unnecessary distances for each sample to the clusters that + it is unlikely to be assigned to. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features), dtype=floating + The input data. Must be in CSR format. + + centers : ndarray of shape (n_clusters, n_features), dtype=floating + The cluster centers. + + center_half_distances : ndarray of shape (n_clusters, n_clusters), \ + dtype=floating + The half of the distance between any 2 clusters centers. + + labels : ndarray of shape(n_samples), dtype=int + The label for each sample. This array is modified in place. + + upper_bounds : ndarray of shape(n_samples,), dtype=floating + The upper bound on the distance between each sample and its closest + cluster center. This array is modified in place. + + lower_bounds : ndarray of shape(n_samples, n_clusters), dtype=floating + The lower bound on the distance between each sample and each cluster + center. This array is modified in place. + + n_threads : int + The number of threads to be used by openmp. + """ + cdef: + int n_samples = X.shape[0] + int n_clusters = centers.shape[0] + + floating[::1] X_data = X.data + int[::1] X_indices = X.indices + int[::1] X_indptr = X.indptr + + floating min_dist, dist + int best_cluster, i, j + + floating[::1] centers_squared_norms = row_norms(centers, squared=True) + + for i in prange( + n_samples, num_threads=n_threads, schedule='static', nogil=True + ): + best_cluster = 0 + min_dist = _euclidean_sparse_dense( + X_data[X_indptr[i]: X_indptr[i + 1]], + X_indices[X_indptr[i]: X_indptr[i + 1]], + centers[0], centers_squared_norms[0], False) + + lower_bounds[i, 0] = min_dist + for j in range(1, n_clusters): + if min_dist > center_half_distances[best_cluster, j]: + dist = _euclidean_sparse_dense( + X_data[X_indptr[i]: X_indptr[i + 1]], + X_indices[X_indptr[i]: X_indptr[i + 1]], + centers[j], centers_squared_norms[j], False) + lower_bounds[i, j] = dist + if dist < min_dist: + min_dist = dist + best_cluster = j + labels[i] = best_cluster + upper_bounds[i] = min_dist + + +def elkan_iter_chunked_dense( + const floating[:, ::1] X, # IN + const floating[::1] sample_weight, # IN + const floating[:, ::1] centers_old, # IN + floating[:, ::1] centers_new, # OUT + floating[::1] weight_in_clusters, # OUT + const floating[:, ::1] center_half_distances, # IN + const floating[::1] distance_next_center, # IN + floating[::1] upper_bounds, # INOUT + floating[:, ::1] lower_bounds, # INOUT + int[::1] labels, # INOUT + floating[::1] center_shift, # OUT + int n_threads, + bint update_centers=True): + """Single iteration of K-means Elkan algorithm with dense input. + + Update labels and centers (inplace), for one iteration, distributed + over data chunks. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features), dtype=floating + The observations to cluster. + + sample_weight : ndarray of shape (n_samples,), dtype=floating + The weights for each observation in X. + + centers_old : ndarray of shape (n_clusters, n_features), dtype=floating + Centers before previous iteration, placeholder for the centers after + previous iteration. + + centers_new : ndarray of shape (n_clusters, n_features), dtype=floating + Centers after previous iteration, placeholder for the new centers + computed during this iteration. + + weight_in_clusters : ndarray of shape (n_clusters,), dtype=floating + Placeholder for the sums of the weights of every observation assigned + to each center. + + center_half_distances : ndarray of shape (n_clusters, n_clusters), \ + dtype=floating + Half pairwise distances between centers. + + distance_next_center : ndarray of shape (n_clusters,), dtype=floating + Distance between each center its closest center. + + upper_bounds : ndarray of shape (n_samples,), dtype=floating + Upper bound for the distance between each sample and its center, + updated inplace. + + lower_bounds : ndarray of shape (n_samples, n_clusters), dtype=floating + Lower bound for the distance between each sample and each center, + updated inplace. + + labels : ndarray of shape (n_samples,), dtype=int + labels assignment. + + center_shift : ndarray of shape (n_clusters,), dtype=floating + Distance between old and new centers. + + n_threads : int + The number of threads to be used by openmp. + + update_centers : bool + - If True, the labels and the new centers will be computed, i.e. runs + the E-step and the M-step of the algorithm. + - If False, only the labels will be computed, i.e runs the E-step of + the algorithm. This is useful especially when calling predict on a + fitted model. + """ + cdef: + int n_samples = X.shape[0] + int n_features = X.shape[1] + int n_clusters = centers_new.shape[0] + + if n_samples == 0: + # An empty array was passed, do nothing and return early (before + # attempting to compute n_chunks). This can typically happen when + # calling the prediction function of a bisecting k-means model with a + # large fraction of outliers. + return + + cdef: + # hard-coded number of samples per chunk. Splitting in chunks is + # necessary to get parallelism. Chunk size chosen to be same as lloyd's + int n_samples_chunk = CHUNK_SIZE if n_samples > CHUNK_SIZE else n_samples + int n_chunks = n_samples // n_samples_chunk + int n_samples_rem = n_samples % n_samples_chunk + int chunk_idx + int start, end + + int i, j, k + + floating *centers_new_chunk + floating *weight_in_clusters_chunk + + omp_lock_t lock + + # count remainder chunk in total number of chunks + n_chunks += n_samples != n_chunks * n_samples_chunk + + # number of threads should not be bigger than number of chunks + n_threads = min(n_threads, n_chunks) + + if update_centers: + memset(¢ers_new[0, 0], 0, n_clusters * n_features * sizeof(floating)) + memset(&weight_in_clusters[0], 0, n_clusters * sizeof(floating)) + omp_init_lock(&lock) + + with nogil, parallel(num_threads=n_threads): + # thread local buffers + centers_new_chunk = calloc(n_clusters * n_features, sizeof(floating)) + weight_in_clusters_chunk = calloc(n_clusters, sizeof(floating)) + + for chunk_idx in prange(n_chunks, schedule='static'): + start = chunk_idx * n_samples_chunk + if chunk_idx == n_chunks - 1 and n_samples_rem > 0: + end = start + n_samples_rem + else: + end = start + n_samples_chunk + + _update_chunk_dense( + X[start: end], + sample_weight[start: end], + centers_old, + center_half_distances, + distance_next_center, + labels[start: end], + upper_bounds[start: end], + lower_bounds[start: end], + centers_new_chunk, + weight_in_clusters_chunk, + update_centers) + + # reduction from local buffers. + if update_centers: + # The lock is necessary to avoid race conditions when aggregating + # info from different thread-local buffers. + omp_set_lock(&lock) + for j in range(n_clusters): + weight_in_clusters[j] += weight_in_clusters_chunk[j] + for k in range(n_features): + centers_new[j, k] += centers_new_chunk[j * n_features + k] + omp_unset_lock(&lock) + + free(centers_new_chunk) + free(weight_in_clusters_chunk) + + if update_centers: + omp_destroy_lock(&lock) + _relocate_empty_clusters_dense(X, sample_weight, centers_old, + centers_new, weight_in_clusters, labels) + + _average_centers(centers_new, weight_in_clusters) + _center_shift(centers_old, centers_new, center_shift) + + # update lower and upper bounds + for i in range(n_samples): + upper_bounds[i] += center_shift[labels[i]] + + for j in range(n_clusters): + lower_bounds[i, j] -= center_shift[j] + if lower_bounds[i, j] < 0: + lower_bounds[i, j] = 0 + + +cdef void _update_chunk_dense( + const floating[:, ::1] X, # IN + const floating[::1] sample_weight, # IN + const floating[:, ::1] centers_old, # IN + const floating[:, ::1] center_half_distances, # IN + const floating[::1] distance_next_center, # IN + int[::1] labels, # INOUT + floating[::1] upper_bounds, # INOUT + floating[:, ::1] lower_bounds, # INOUT + floating *centers_new, # OUT + floating *weight_in_clusters, # OUT + bint update_centers) noexcept nogil: + """K-means combined EM step for one dense data chunk. + + Compute the partial contribution of a single data chunk to the labels and + centers. + """ + cdef: + int n_samples = labels.shape[0] + int n_clusters = centers_old.shape[0] + int n_features = centers_old.shape[1] + + floating upper_bound, distance + int i, j, k, label + + for i in range(n_samples): + upper_bound = upper_bounds[i] + bounds_tight = 0 + label = labels[i] + + # Next center is not far away from the currently assigned center. + # Sample might need to be assigned to another center. + if not distance_next_center[label] >= upper_bound: + + for j in range(n_clusters): + + # If this holds, then center_index is a good candidate for the + # sample to be relabelled, and we need to confirm this by + # recomputing the upper and lower bounds. + if ( + j != label + and (upper_bound > lower_bounds[i, j]) + and (upper_bound > center_half_distances[label, j]) + ): + + # Recompute upper bound by calculating the actual distance + # between the sample and its current assigned center. + if not bounds_tight: + upper_bound = _euclidean_dense_dense( + &X[i, 0], ¢ers_old[label, 0], n_features, False) + lower_bounds[i, label] = upper_bound + bounds_tight = 1 + + # If the condition still holds, then compute the actual + # distance between the sample and center. If this is less + # than the previous distance, reassign label. + if ( + upper_bound > lower_bounds[i, j] + or (upper_bound > center_half_distances[label, j]) + ): + + distance = _euclidean_dense_dense( + &X[i, 0], ¢ers_old[j, 0], n_features, False) + lower_bounds[i, j] = distance + if distance < upper_bound: + label = j + upper_bound = distance + + labels[i] = label + upper_bounds[i] = upper_bound + + if update_centers: + weight_in_clusters[label] += sample_weight[i] + for k in range(n_features): + centers_new[label * n_features + k] += X[i, k] * sample_weight[i] + + +def elkan_iter_chunked_sparse( + X, # IN + const floating[::1] sample_weight, # IN + const floating[:, ::1] centers_old, # IN + floating[:, ::1] centers_new, # OUT + floating[::1] weight_in_clusters, # OUT + const floating[:, ::1] center_half_distances, # IN + const floating[::1] distance_next_center, # IN + floating[::1] upper_bounds, # INOUT + floating[:, ::1] lower_bounds, # INOUT + int[::1] labels, # INOUT + floating[::1] center_shift, # OUT + int n_threads, + bint update_centers=True): + """Single iteration of K-means Elkan algorithm with sparse input. + + Update labels and centers (inplace), for one iteration, distributed + over data chunks. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + The observations to cluster. Must be in CSR format. + + sample_weight : ndarray of shape (n_samples,), dtype=floating + The weights for each observation in X. + + centers_old : ndarray of shape (n_clusters, n_features), dtype=floating + Centers before previous iteration, placeholder for the centers after + previous iteration. + + centers_new : ndarray of shape (n_clusters, n_features), dtype=floating + Centers after previous iteration, placeholder for the new centers + computed during this iteration. + + weight_in_clusters : ndarray of shape (n_clusters,), dtype=floating + Placeholder for the sums of the weights of every observation assigned + to each center. + + center_half_distances : ndarray of shape (n_clusters, n_clusters), \ + dtype=floating + Half pairwise distances between centers. + + distance_next_center : ndarray of shape (n_clusters,), dtype=floating + Distance between each center its closest center. + + upper_bounds : ndarray of shape (n_samples,), dtype=floating + Upper bound for the distance between each sample and its center, + updated inplace. + + lower_bounds : ndarray of shape (n_samples, n_clusters), dtype=floating + Lower bound for the distance between each sample and each center, + updated inplace. + + labels : ndarray of shape (n_samples,), dtype=int + labels assignment. + + center_shift : ndarray of shape (n_clusters,), dtype=floating + Distance between old and new centers. + + n_threads : int + The number of threads to be used by openmp. + + update_centers : bool + - If True, the labels and the new centers will be computed, i.e. runs + the E-step and the M-step of the algorithm. + - If False, only the labels will be computed, i.e runs the E-step of + the algorithm. This is useful especially when calling predict on a + fitted model. + """ + cdef: + int n_samples = X.shape[0] + int n_features = X.shape[1] + int n_clusters = centers_new.shape[0] + + if n_samples == 0: + # An empty array was passed, do nothing and return early (before + # attempting to compute n_chunks). This can typically happen when + # calling the prediction function of a bisecting k-means model with a + # large fraction of outliers. + return + + cdef: + floating[::1] X_data = X.data + int[::1] X_indices = X.indices + int[::1] X_indptr = X.indptr + + # hard-coded number of samples per chunk. Splitting in chunks is + # necessary to get parallelism. Chunk size chosen to be same as lloyd's + int n_samples_chunk = CHUNK_SIZE if n_samples > CHUNK_SIZE else n_samples + int n_chunks = n_samples // n_samples_chunk + int n_samples_rem = n_samples % n_samples_chunk + int chunk_idx + int start, end + + int i, j, k + + floating[::1] centers_squared_norms = row_norms(centers_old, squared=True) + + floating *centers_new_chunk + floating *weight_in_clusters_chunk + + omp_lock_t lock + + # count remainder chunk in total number of chunks + n_chunks += n_samples != n_chunks * n_samples_chunk + + # number of threads should not be bigger than number of chunks + n_threads = min(n_threads, n_chunks) + + if update_centers: + memset(¢ers_new[0, 0], 0, n_clusters * n_features * sizeof(floating)) + memset(&weight_in_clusters[0], 0, n_clusters * sizeof(floating)) + omp_init_lock(&lock) + + with nogil, parallel(num_threads=n_threads): + # thread local buffers + centers_new_chunk = calloc(n_clusters * n_features, sizeof(floating)) + weight_in_clusters_chunk = calloc(n_clusters, sizeof(floating)) + + for chunk_idx in prange(n_chunks, schedule='static'): + start = chunk_idx * n_samples_chunk + if chunk_idx == n_chunks - 1 and n_samples_rem > 0: + end = start + n_samples_rem + else: + end = start + n_samples_chunk + + _update_chunk_sparse( + X_data[X_indptr[start]: X_indptr[end]], + X_indices[X_indptr[start]: X_indptr[end]], + X_indptr[start: end+1], + sample_weight[start: end], + centers_old, + centers_squared_norms, + center_half_distances, + distance_next_center, + labels[start: end], + upper_bounds[start: end], + lower_bounds[start: end], + centers_new_chunk, + weight_in_clusters_chunk, + update_centers) + + # reduction from local buffers. + if update_centers: + # The lock is necessary to avoid race conditions when aggregating + # info from different thread-local buffers. + omp_set_lock(&lock) + for j in range(n_clusters): + weight_in_clusters[j] += weight_in_clusters_chunk[j] + for k in range(n_features): + centers_new[j, k] += centers_new_chunk[j * n_features + k] + omp_unset_lock(&lock) + + free(centers_new_chunk) + free(weight_in_clusters_chunk) + + if update_centers: + omp_destroy_lock(&lock) + _relocate_empty_clusters_sparse( + X_data, X_indices, X_indptr, sample_weight, + centers_old, centers_new, weight_in_clusters, labels) + + _average_centers(centers_new, weight_in_clusters) + _center_shift(centers_old, centers_new, center_shift) + + # update lower and upper bounds + for i in range(n_samples): + upper_bounds[i] += center_shift[labels[i]] + + for j in range(n_clusters): + lower_bounds[i, j] -= center_shift[j] + if lower_bounds[i, j] < 0: + lower_bounds[i, j] = 0 + + +cdef void _update_chunk_sparse( + const floating[::1] X_data, # IN + const int[::1] X_indices, # IN + const int[::1] X_indptr, # IN + const floating[::1] sample_weight, # IN + const floating[:, ::1] centers_old, # IN + const floating[::1] centers_squared_norms, # IN + const floating[:, ::1] center_half_distances, # IN + const floating[::1] distance_next_center, # IN + int[::1] labels, # INOUT + floating[::1] upper_bounds, # INOUT + floating[:, ::1] lower_bounds, # INOUT + floating *centers_new, # OUT + floating *weight_in_clusters, # OUT + bint update_centers) noexcept nogil: + """K-means combined EM step for one sparse data chunk. + + Compute the partial contribution of a single data chunk to the labels and + centers. + """ + cdef: + int n_samples = labels.shape[0] + int n_clusters = centers_old.shape[0] + int n_features = centers_old.shape[1] + + floating upper_bound, distance + int i, j, k, label + int s = X_indptr[0] + + for i in range(n_samples): + upper_bound = upper_bounds[i] + bounds_tight = 0 + label = labels[i] + + # Next center is not far away from the currently assigned center. + # Sample might need to be assigned to another center. + if not distance_next_center[label] >= upper_bound: + + for j in range(n_clusters): + + # If this holds, then center_index is a good candidate for the + # sample to be relabelled, and we need to confirm this by + # recomputing the upper and lower bounds. + if ( + j != label + and (upper_bound > lower_bounds[i, j]) + and (upper_bound > center_half_distances[label, j]) + ): + + # Recompute upper bound by calculating the actual distance + # between the sample and its current assigned center. + if not bounds_tight: + upper_bound = _euclidean_sparse_dense( + X_data[X_indptr[i] - s: X_indptr[i + 1] - s], + X_indices[X_indptr[i] - s: X_indptr[i + 1] - s], + centers_old[label], centers_squared_norms[label], False) + lower_bounds[i, label] = upper_bound + bounds_tight = 1 + + # If the condition still holds, then compute the actual + # distance between the sample and center. If this is less + # than the previous distance, reassign label. + if ( + upper_bound > lower_bounds[i, j] + or (upper_bound > center_half_distances[label, j]) + ): + distance = _euclidean_sparse_dense( + X_data[X_indptr[i] - s: X_indptr[i + 1] - s], + X_indices[X_indptr[i] - s: X_indptr[i + 1] - s], + centers_old[j], centers_squared_norms[j], False) + lower_bounds[i, j] = distance + if distance < upper_bound: + label = j + upper_bound = distance + + labels[i] = label + upper_bounds[i] = upper_bound + + if update_centers: + weight_in_clusters[label] += sample_weight[i] + for k in range(X_indptr[i] - s, X_indptr[i + 1] - s): + centers_new[label * n_features + X_indices[k]] += X_data[k] * sample_weight[i] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_k_means_lloyd.pyx b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_k_means_lloyd.pyx new file mode 100644 index 0000000000000000000000000000000000000000..a507a6239ab5f836e8c7d23ac0e3e2ab2f7f4d11 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_k_means_lloyd.pyx @@ -0,0 +1,420 @@ +# Licence: BSD 3 clause + +from cython cimport floating +from cython.parallel import prange, parallel +from libc.stdlib cimport malloc, calloc, free +from libc.string cimport memset +from libc.float cimport DBL_MAX, FLT_MAX + +from ..utils._openmp_helpers cimport omp_lock_t +from ..utils._openmp_helpers cimport omp_init_lock +from ..utils._openmp_helpers cimport omp_destroy_lock +from ..utils._openmp_helpers cimport omp_set_lock +from ..utils._openmp_helpers cimport omp_unset_lock +from ..utils.extmath import row_norms +from ..utils._cython_blas cimport _gemm +from ..utils._cython_blas cimport RowMajor, Trans, NoTrans +from ._k_means_common import CHUNK_SIZE +from ._k_means_common cimport _relocate_empty_clusters_dense +from ._k_means_common cimport _relocate_empty_clusters_sparse +from ._k_means_common cimport _average_centers, _center_shift + + +def lloyd_iter_chunked_dense( + const floating[:, ::1] X, # IN + const floating[::1] sample_weight, # IN + const floating[:, ::1] centers_old, # IN + floating[:, ::1] centers_new, # OUT + floating[::1] weight_in_clusters, # OUT + int[::1] labels, # OUT + floating[::1] center_shift, # OUT + int n_threads, + bint update_centers=True): + """Single iteration of K-means lloyd algorithm with dense input. + + Update labels and centers (inplace), for one iteration, distributed + over data chunks. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features), dtype=floating + The observations to cluster. + + sample_weight : ndarray of shape (n_samples,), dtype=floating + The weights for each observation in X. + + centers_old : ndarray of shape (n_clusters, n_features), dtype=floating + Centers before previous iteration, placeholder for the centers after + previous iteration. + + centers_new : ndarray of shape (n_clusters, n_features), dtype=floating + Centers after previous iteration, placeholder for the new centers + computed during this iteration. `centers_new` can be `None` if + `update_centers` is False. + + weight_in_clusters : ndarray of shape (n_clusters,), dtype=floating + Placeholder for the sums of the weights of every observation assigned + to each center. `weight_in_clusters` can be `None` if `update_centers` + is False. + + labels : ndarray of shape (n_samples,), dtype=int + labels assignment. + + center_shift : ndarray of shape (n_clusters,), dtype=floating + Distance between old and new centers. + + n_threads : int + The number of threads to be used by openmp. + + update_centers : bool + - If True, the labels and the new centers will be computed, i.e. runs + the E-step and the M-step of the algorithm. + - If False, only the labels will be computed, i.e runs the E-step of + the algorithm. This is useful especially when calling predict on a + fitted model. + """ + cdef: + int n_samples = X.shape[0] + int n_features = X.shape[1] + int n_clusters = centers_old.shape[0] + + if n_samples == 0: + # An empty array was passed, do nothing and return early (before + # attempting to compute n_chunks). This can typically happen when + # calling the prediction function of a bisecting k-means model with a + # large fraction of outliers. + return + + cdef: + # hard-coded number of samples per chunk. Appeared to be close to + # optimal in all situations. + int n_samples_chunk = CHUNK_SIZE if n_samples > CHUNK_SIZE else n_samples + int n_chunks = n_samples // n_samples_chunk + int n_samples_rem = n_samples % n_samples_chunk + int chunk_idx + int start, end + + int j, k + + floating[::1] centers_squared_norms = row_norms(centers_old, squared=True) + + floating *centers_new_chunk + floating *weight_in_clusters_chunk + floating *pairwise_distances_chunk + + omp_lock_t lock + + # count remainder chunk in total number of chunks + n_chunks += n_samples != n_chunks * n_samples_chunk + + # number of threads should not be bigger than number of chunks + n_threads = min(n_threads, n_chunks) + + if update_centers: + memset(¢ers_new[0, 0], 0, n_clusters * n_features * sizeof(floating)) + memset(&weight_in_clusters[0], 0, n_clusters * sizeof(floating)) + omp_init_lock(&lock) + + with nogil, parallel(num_threads=n_threads): + # thread local buffers + centers_new_chunk = calloc(n_clusters * n_features, sizeof(floating)) + weight_in_clusters_chunk = calloc(n_clusters, sizeof(floating)) + pairwise_distances_chunk = malloc(n_samples_chunk * n_clusters * sizeof(floating)) + + for chunk_idx in prange(n_chunks, schedule='static'): + start = chunk_idx * n_samples_chunk + if chunk_idx == n_chunks - 1 and n_samples_rem > 0: + end = start + n_samples_rem + else: + end = start + n_samples_chunk + + _update_chunk_dense( + X[start: end], + sample_weight[start: end], + centers_old, + centers_squared_norms, + labels[start: end], + centers_new_chunk, + weight_in_clusters_chunk, + pairwise_distances_chunk, + update_centers) + + # reduction from local buffers. + if update_centers: + # The lock is necessary to avoid race conditions when aggregating + # info from different thread-local buffers. + omp_set_lock(&lock) + for j in range(n_clusters): + weight_in_clusters[j] += weight_in_clusters_chunk[j] + for k in range(n_features): + centers_new[j, k] += centers_new_chunk[j * n_features + k] + + omp_unset_lock(&lock) + + free(centers_new_chunk) + free(weight_in_clusters_chunk) + free(pairwise_distances_chunk) + + if update_centers: + omp_destroy_lock(&lock) + _relocate_empty_clusters_dense( + X, sample_weight, centers_old, centers_new, weight_in_clusters, labels + ) + + _average_centers(centers_new, weight_in_clusters) + _center_shift(centers_old, centers_new, center_shift) + + +cdef void _update_chunk_dense( + const floating[:, ::1] X, # IN + const floating[::1] sample_weight, # IN + const floating[:, ::1] centers_old, # IN + const floating[::1] centers_squared_norms, # IN + int[::1] labels, # OUT + floating *centers_new, # OUT + floating *weight_in_clusters, # OUT + floating *pairwise_distances, # OUT + bint update_centers) noexcept nogil: + """K-means combined EM step for one dense data chunk. + + Compute the partial contribution of a single data chunk to the labels and + centers. + """ + cdef: + int n_samples = labels.shape[0] + int n_clusters = centers_old.shape[0] + int n_features = centers_old.shape[1] + + floating sq_dist, min_sq_dist + int i, j, k, label + + # Instead of computing the full pairwise squared distances matrix, + # ||X - C||² = ||X||² - 2 X.C^T + ||C||², we only need to store + # the - 2 X.C^T + ||C||² term since the argmin for a given sample only + # depends on the centers. + # pairwise_distances = ||C||² + for i in range(n_samples): + for j in range(n_clusters): + pairwise_distances[i * n_clusters + j] = centers_squared_norms[j] + + # pairwise_distances += -2 * X.dot(C.T) + _gemm(RowMajor, NoTrans, Trans, n_samples, n_clusters, n_features, + -2.0, &X[0, 0], n_features, ¢ers_old[0, 0], n_features, + 1.0, pairwise_distances, n_clusters) + + for i in range(n_samples): + min_sq_dist = pairwise_distances[i * n_clusters] + label = 0 + for j in range(1, n_clusters): + sq_dist = pairwise_distances[i * n_clusters + j] + if sq_dist < min_sq_dist: + min_sq_dist = sq_dist + label = j + labels[i] = label + + if update_centers: + weight_in_clusters[label] += sample_weight[i] + for k in range(n_features): + centers_new[label * n_features + k] += X[i, k] * sample_weight[i] + + +def lloyd_iter_chunked_sparse( + X, # IN + const floating[::1] sample_weight, # IN + const floating[:, ::1] centers_old, # IN + floating[:, ::1] centers_new, # OUT + floating[::1] weight_in_clusters, # OUT + int[::1] labels, # OUT + floating[::1] center_shift, # OUT + int n_threads, + bint update_centers=True): + """Single iteration of K-means lloyd algorithm with sparse input. + + Update labels and centers (inplace), for one iteration, distributed + over data chunks. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features), dtype=floating + The observations to cluster. Must be in CSR format. + + sample_weight : ndarray of shape (n_samples,), dtype=floating + The weights for each observation in X. + + centers_old : ndarray of shape (n_clusters, n_features), dtype=floating + Centers before previous iteration, placeholder for the centers after + previous iteration. + + centers_new : ndarray of shape (n_clusters, n_features), dtype=floating + Centers after previous iteration, placeholder for the new centers + computed during this iteration. `centers_new` can be `None` if + `update_centers` is False. + + weight_in_clusters : ndarray of shape (n_clusters,), dtype=floating + Placeholder for the sums of the weights of every observation assigned + to each center. `weight_in_clusters` can be `None` if `update_centers` + is False. + + labels : ndarray of shape (n_samples,), dtype=int + labels assignment. + + center_shift : ndarray of shape (n_clusters,), dtype=floating + Distance between old and new centers. + + n_threads : int + The number of threads to be used by openmp. + + update_centers : bool + - If True, the labels and the new centers will be computed, i.e. runs + the E-step and the M-step of the algorithm. + - If False, only the labels will be computed, i.e runs the E-step of + the algorithm. This is useful especially when calling predict on a + fitted model. + """ + cdef: + int n_samples = X.shape[0] + int n_features = X.shape[1] + int n_clusters = centers_old.shape[0] + + if n_samples == 0: + # An empty array was passed, do nothing and return early (before + # attempting to compute n_chunks). This can typically happen when + # calling the prediction function of a bisecting k-means model with a + # large fraction of outliers. + return + + cdef: + # Choose same as for dense. Does not have the same impact since with + # sparse data the pairwise distances matrix is not precomputed. + # However, splitting in chunks is necessary to get parallelism. + int n_samples_chunk = CHUNK_SIZE if n_samples > CHUNK_SIZE else n_samples + int n_chunks = n_samples // n_samples_chunk + int n_samples_rem = n_samples % n_samples_chunk + int chunk_idx + int start = 0, end = 0 + + int j, k + + floating[::1] X_data = X.data + int[::1] X_indices = X.indices + int[::1] X_indptr = X.indptr + + floating[::1] centers_squared_norms = row_norms(centers_old, squared=True) + + floating *centers_new_chunk + floating *weight_in_clusters_chunk + + omp_lock_t lock + + # count remainder chunk in total number of chunks + n_chunks += n_samples != n_chunks * n_samples_chunk + + # number of threads should not be bigger than number of chunks + n_threads = min(n_threads, n_chunks) + + if update_centers: + memset(¢ers_new[0, 0], 0, n_clusters * n_features * sizeof(floating)) + memset(&weight_in_clusters[0], 0, n_clusters * sizeof(floating)) + omp_init_lock(&lock) + + with nogil, parallel(num_threads=n_threads): + # thread local buffers + centers_new_chunk = calloc(n_clusters * n_features, sizeof(floating)) + weight_in_clusters_chunk = calloc(n_clusters, sizeof(floating)) + + for chunk_idx in prange(n_chunks, schedule='static'): + start = chunk_idx * n_samples_chunk + if chunk_idx == n_chunks - 1 and n_samples_rem > 0: + end = start + n_samples_rem + else: + end = start + n_samples_chunk + + _update_chunk_sparse( + X_data[X_indptr[start]: X_indptr[end]], + X_indices[X_indptr[start]: X_indptr[end]], + X_indptr[start: end+1], + sample_weight[start: end], + centers_old, + centers_squared_norms, + labels[start: end], + centers_new_chunk, + weight_in_clusters_chunk, + update_centers) + + # reduction from local buffers. + if update_centers: + # The lock is necessary to avoid race conditions when aggregating + # info from different thread-local buffers. + omp_set_lock(&lock) + for j in range(n_clusters): + weight_in_clusters[j] += weight_in_clusters_chunk[j] + for k in range(n_features): + centers_new[j, k] += centers_new_chunk[j * n_features + k] + omp_unset_lock(&lock) + + free(centers_new_chunk) + free(weight_in_clusters_chunk) + + if update_centers: + omp_destroy_lock(&lock) + _relocate_empty_clusters_sparse( + X_data, X_indices, X_indptr, sample_weight, + centers_old, centers_new, weight_in_clusters, labels) + + _average_centers(centers_new, weight_in_clusters) + _center_shift(centers_old, centers_new, center_shift) + + +cdef void _update_chunk_sparse( + const floating[::1] X_data, # IN + const int[::1] X_indices, # IN + const int[::1] X_indptr, # IN + const floating[::1] sample_weight, # IN + const floating[:, ::1] centers_old, # IN + const floating[::1] centers_squared_norms, # IN + int[::1] labels, # OUT + floating *centers_new, # OUT + floating *weight_in_clusters, # OUT + bint update_centers) noexcept nogil: + """K-means combined EM step for one sparse data chunk. + + Compute the partial contribution of a single data chunk to the labels and + centers. + """ + cdef: + int n_samples = labels.shape[0] + int n_clusters = centers_old.shape[0] + int n_features = centers_old.shape[1] + + floating sq_dist, min_sq_dist + int i, j, k, label + floating max_floating = FLT_MAX if floating is float else DBL_MAX + int s = X_indptr[0] + + # XXX Precompute the pairwise distances matrix is not worth for sparse + # currently. Should be tested when BLAS (sparse x dense) matrix + # multiplication is available. + for i in range(n_samples): + min_sq_dist = max_floating + label = 0 + + for j in range(n_clusters): + sq_dist = 0.0 + for k in range(X_indptr[i] - s, X_indptr[i + 1] - s): + sq_dist += centers_old[j, X_indices[k]] * X_data[k] + + # Instead of computing the full squared distance with each cluster, + # ||X - C||² = ||X||² - 2 X.C^T + ||C||², we only need to compute + # the - 2 X.C^T + ||C||² term since the argmin for a given sample + # only depends on the centers C. + sq_dist = centers_squared_norms[j] -2 * sq_dist + if sq_dist < min_sq_dist: + min_sq_dist = sq_dist + label = j + + labels[i] = label + + if update_centers: + weight_in_clusters[label] += sample_weight[i] + for k in range(X_indptr[i] - s, X_indptr[i + 1] - s): + centers_new[label * n_features + X_indices[k]] += X_data[k] * sample_weight[i] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_k_means_minibatch.pyx b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_k_means_minibatch.pyx new file mode 100644 index 0000000000000000000000000000000000000000..22ca5255e3889574d7155f1e077f84111832cf92 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_k_means_minibatch.pyx @@ -0,0 +1,218 @@ +from cython cimport floating +from cython.parallel cimport parallel, prange +from libc.stdlib cimport malloc, free + + +def _minibatch_update_dense( + const floating[:, ::1] X, # IN + const floating[::1] sample_weight, # IN + const floating[:, ::1] centers_old, # IN + floating[:, ::1] centers_new, # OUT + floating[::1] weight_sums, # INOUT + const int[::1] labels, # IN + int n_threads): + """Update of the centers for dense MiniBatchKMeans. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features), dtype=floating + The observations to cluster. + + sample_weight : ndarray of shape (n_samples,), dtype=floating + The weights for each observation in X. + + centers_old : ndarray of shape (n_clusters, n_features), dtype=floating + Centers before previous iteration, placeholder for the centers after + previous iteration. + + centers_new : ndarray of shape (n_clusters, n_features), dtype=floating + Centers after previous iteration, placeholder for the new centers + computed during this iteration. + + weight_sums : ndarray of shape (n_clusters,), dtype=floating + Current sums of the accumulated weights for each center. + + labels : ndarray of shape (n_samples,), dtype=int + labels assignment. + + n_threads : int + The number of threads to be used by openmp. + """ + cdef: + int n_samples = X.shape[0] + int n_clusters = centers_old.shape[0] + int cluster_idx + + int *indices + + with nogil, parallel(num_threads=n_threads): + indices = malloc(n_samples * sizeof(int)) + + for cluster_idx in prange(n_clusters, schedule="static"): + update_center_dense(cluster_idx, X, sample_weight, + centers_old, centers_new, weight_sums, labels, + indices) + + free(indices) + + +cdef void update_center_dense( + int cluster_idx, + const floating[:, ::1] X, # IN + const floating[::1] sample_weight, # IN + const floating[:, ::1] centers_old, # IN + floating[:, ::1] centers_new, # OUT + floating[::1] weight_sums, # INOUT + const int[::1] labels, # IN + int *indices) noexcept nogil: # TMP + """Update of a single center for dense MinibatchKMeans""" + cdef: + int n_samples = sample_weight.shape[0] + int n_features = centers_old.shape[1] + floating alpha + int n_indices + int k, sample_idx, feature_idx + + floating wsum = 0 + + # indices = np.where(labels == cluster_idx)[0] + k = 0 + for sample_idx in range(n_samples): + if labels[sample_idx] == cluster_idx: + indices[k] = sample_idx + wsum += sample_weight[sample_idx] + k += 1 + n_indices = k + + if wsum > 0: + # Undo the previous count-based scaling for this cluster center + for feature_idx in range(n_features): + centers_new[cluster_idx, feature_idx] = centers_old[cluster_idx, feature_idx] * weight_sums[cluster_idx] + + # Update cluster with new point members + for k in range(n_indices): + sample_idx = indices[k] + for feature_idx in range(n_features): + centers_new[cluster_idx, feature_idx] += X[sample_idx, feature_idx] * sample_weight[sample_idx] + + # Update the count statistics for this center + weight_sums[cluster_idx] += wsum + + # Rescale to compute mean of all points (old and new) + alpha = 1 / weight_sums[cluster_idx] + for feature_idx in range(n_features): + centers_new[cluster_idx, feature_idx] *= alpha + else: + # No sample was assigned to this cluster in this batch of data + for feature_idx in range(n_features): + centers_new[cluster_idx, feature_idx] = centers_old[cluster_idx, feature_idx] + + +def _minibatch_update_sparse( + X, # IN + const floating[::1] sample_weight, # IN + const floating[:, ::1] centers_old, # IN + floating[:, ::1] centers_new, # OUT + floating[::1] weight_sums, # INOUT + const int[::1] labels, # IN + int n_threads): + """Update of the centers for sparse MiniBatchKMeans. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features), dtype=floating + The observations to cluster. Must be in CSR format. + + sample_weight : ndarray of shape (n_samples,), dtype=floating + The weights for each observation in X. + + centers_old : ndarray of shape (n_clusters, n_features), dtype=floating + Centers before previous iteration, placeholder for the centers after + previous iteration. + + centers_new : ndarray of shape (n_clusters, n_features), dtype=floating + Centers after previous iteration, placeholder for the new centers + computed during this iteration. + + weight_sums : ndarray of shape (n_clusters,), dtype=floating + Current sums of the accumulated weights for each center. + + labels : ndarray of shape (n_samples,), dtype=int + labels assignment. + + n_threads : int + The number of threads to be used by openmp. + """ + cdef: + floating[::1] X_data = X.data + int[::1] X_indices = X.indices + int[::1] X_indptr = X.indptr + int n_samples = X.shape[0] + int n_clusters = centers_old.shape[0] + int cluster_idx + + int *indices + + with nogil, parallel(num_threads=n_threads): + indices = malloc(n_samples * sizeof(int)) + + for cluster_idx in prange(n_clusters, schedule="static"): + update_center_sparse(cluster_idx, X_data, X_indices, X_indptr, + sample_weight, centers_old, centers_new, + weight_sums, labels, indices) + + free(indices) + + +cdef void update_center_sparse( + int cluster_idx, + const floating[::1] X_data, # IN + const int[::1] X_indices, # IN + const int[::1] X_indptr, # IN + const floating[::1] sample_weight, # IN + const floating[:, ::1] centers_old, # IN + floating[:, ::1] centers_new, # OUT + floating[::1] weight_sums, # INOUT + const int[::1] labels, # IN + int *indices) noexcept nogil: # TMP + """Update of a single center for sparse MinibatchKMeans""" + cdef: + int n_samples = sample_weight.shape[0] + int n_features = centers_old.shape[1] + floating alpha + int n_indices + int k, sample_idx, feature_idx + + floating wsum = 0 + + # indices = np.where(labels == cluster_idx)[0] + k = 0 + for sample_idx in range(n_samples): + if labels[sample_idx] == cluster_idx: + indices[k] = sample_idx + wsum += sample_weight[sample_idx] + k += 1 + n_indices = k + + if wsum > 0: + # Undo the previous count-based scaling for this cluster center: + for feature_idx in range(n_features): + centers_new[cluster_idx, feature_idx] = centers_old[cluster_idx, feature_idx] * weight_sums[cluster_idx] + + # Update cluster with new point members + for k in range(n_indices): + sample_idx = indices[k] + for feature_idx in range(X_indptr[sample_idx], X_indptr[sample_idx + 1]): + centers_new[cluster_idx, X_indices[feature_idx]] += X_data[feature_idx] * sample_weight[sample_idx] + + # Update the count statistics for this center + weight_sums[cluster_idx] += wsum + + # Rescale to compute mean of all points (old and new) + alpha = 1 / weight_sums[cluster_idx] + for feature_idx in range(n_features): + centers_new[cluster_idx, feature_idx] *= alpha + else: + # No sample was assigned to this cluster in this batch of data + for feature_idx in range(n_features): + centers_new[cluster_idx, feature_idx] = centers_old[cluster_idx, feature_idx] diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_kmeans.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_kmeans.py new file mode 100644 index 0000000000000000000000000000000000000000..11c85610239ccae163137a1ced0f990325864390 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_kmeans.py @@ -0,0 +1,2303 @@ +"""K-means clustering.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from abc import ABC, abstractmethod +from numbers import Integral, Real + +import numpy as np +import scipy.sparse as sp + +from ..base import ( + BaseEstimator, + ClassNamePrefixFeaturesOutMixin, + ClusterMixin, + TransformerMixin, + _fit_context, +) +from ..exceptions import ConvergenceWarning +from ..metrics.pairwise import _euclidean_distances, euclidean_distances +from ..utils import check_array, check_random_state +from ..utils._openmp_helpers import _openmp_effective_n_threads +from ..utils._param_validation import Interval, StrOptions, validate_params +from ..utils.extmath import row_norms, stable_cumsum +from ..utils.parallel import ( + _get_threadpool_controller, + _threadpool_controller_decorator, +) +from ..utils.sparsefuncs import mean_variance_axis +from ..utils.sparsefuncs_fast import assign_rows_csr +from ..utils.validation import ( + _check_sample_weight, + _is_arraylike_not_scalar, + check_is_fitted, + validate_data, +) +from ._k_means_common import ( + CHUNK_SIZE, + _inertia_dense, + _inertia_sparse, + _is_same_clustering, +) +from ._k_means_elkan import ( + elkan_iter_chunked_dense, + elkan_iter_chunked_sparse, + init_bounds_dense, + init_bounds_sparse, +) +from ._k_means_lloyd import lloyd_iter_chunked_dense, lloyd_iter_chunked_sparse +from ._k_means_minibatch import _minibatch_update_dense, _minibatch_update_sparse + +############################################################################### +# Initialization heuristic + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "n_clusters": [Interval(Integral, 1, None, closed="left")], + "sample_weight": ["array-like", None], + "x_squared_norms": ["array-like", None], + "random_state": ["random_state"], + "n_local_trials": [Interval(Integral, 1, None, closed="left"), None], + }, + prefer_skip_nested_validation=True, +) +def kmeans_plusplus( + X, + n_clusters, + *, + sample_weight=None, + x_squared_norms=None, + random_state=None, + n_local_trials=None, +): + """Init n_clusters seeds according to k-means++. + + .. versionadded:: 0.24 + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data to pick seeds from. + + n_clusters : int + The number of centroids to initialize. + + sample_weight : array-like of shape (n_samples,), default=None + The weights for each observation in `X`. If `None`, all observations + are assigned equal weight. `sample_weight` is ignored if `init` + is a callable or a user provided array. + + .. versionadded:: 1.3 + + x_squared_norms : array-like of shape (n_samples,), default=None + Squared Euclidean norm of each data point. + + random_state : int or RandomState instance, default=None + Determines random number generation for centroid initialization. Pass + an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + n_local_trials : int, default=None + The number of seeding trials for each center (except the first), + of which the one reducing inertia the most is greedily chosen. + Set to None to make the number of trials depend logarithmically + on the number of seeds (2+log(k)) which is the recommended setting. + Setting to 1 disables the greedy cluster selection and recovers the + vanilla k-means++ algorithm which was empirically shown to work less + well than its greedy variant. + + Returns + ------- + centers : ndarray of shape (n_clusters, n_features) + The initial centers for k-means. + + indices : ndarray of shape (n_clusters,) + The index location of the chosen centers in the data array X. For a + given index and center, X[index] = center. + + Notes + ----- + Selects initial cluster centers for k-mean clustering in a smart way + to speed up convergence. see: Arthur, D. and Vassilvitskii, S. + "k-means++: the advantages of careful seeding". ACM-SIAM symposium + on Discrete algorithms. 2007 + + Examples + -------- + + >>> from sklearn.cluster import kmeans_plusplus + >>> import numpy as np + >>> X = np.array([[1, 2], [1, 4], [1, 0], + ... [10, 2], [10, 4], [10, 0]]) + >>> centers, indices = kmeans_plusplus(X, n_clusters=2, random_state=0) + >>> centers + array([[10, 2], + [ 1, 0]]) + >>> indices + array([3, 2]) + """ + # Check data + check_array(X, accept_sparse="csr", dtype=[np.float64, np.float32]) + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + + if X.shape[0] < n_clusters: + raise ValueError( + f"n_samples={X.shape[0]} should be >= n_clusters={n_clusters}." + ) + + # Check parameters + if x_squared_norms is None: + x_squared_norms = row_norms(X, squared=True) + else: + x_squared_norms = check_array(x_squared_norms, dtype=X.dtype, ensure_2d=False) + + if x_squared_norms.shape[0] != X.shape[0]: + raise ValueError( + f"The length of x_squared_norms {x_squared_norms.shape[0]} should " + f"be equal to the length of n_samples {X.shape[0]}." + ) + + random_state = check_random_state(random_state) + + # Call private k-means++ + centers, indices = _kmeans_plusplus( + X, n_clusters, x_squared_norms, sample_weight, random_state, n_local_trials + ) + + return centers, indices + + +def _kmeans_plusplus( + X, n_clusters, x_squared_norms, sample_weight, random_state, n_local_trials=None +): + """Computational component for initialization of n_clusters by + k-means++. Prior validation of data is assumed. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + The data to pick seeds for. + + n_clusters : int + The number of seeds to choose. + + sample_weight : ndarray of shape (n_samples,) + The weights for each observation in `X`. + + x_squared_norms : ndarray of shape (n_samples,) + Squared Euclidean norm of each data point. + + random_state : RandomState instance + The generator used to initialize the centers. + See :term:`Glossary `. + + n_local_trials : int, default=None + The number of seeding trials for each center (except the first), + of which the one reducing inertia the most is greedily chosen. + Set to None to make the number of trials depend logarithmically + on the number of seeds (2+log(k)); this is the default. + + Returns + ------- + centers : ndarray of shape (n_clusters, n_features) + The initial centers for k-means. + + indices : ndarray of shape (n_clusters,) + The index location of the chosen centers in the data array X. For a + given index and center, X[index] = center. + """ + n_samples, n_features = X.shape + + centers = np.empty((n_clusters, n_features), dtype=X.dtype) + + # Set the number of local seeding trials if none is given + if n_local_trials is None: + # This is what Arthur/Vassilvitskii tried, but did not report + # specific results for other than mentioning in the conclusion + # that it helped. + n_local_trials = 2 + int(np.log(n_clusters)) + + # Pick first center randomly and track index of point + center_id = random_state.choice(n_samples, p=sample_weight / sample_weight.sum()) + indices = np.full(n_clusters, -1, dtype=int) + if sp.issparse(X): + centers[0] = X[[center_id]].toarray() + else: + centers[0] = X[center_id] + indices[0] = center_id + + # Initialize list of closest distances and calculate current potential + closest_dist_sq = _euclidean_distances( + centers[0, np.newaxis], X, Y_norm_squared=x_squared_norms, squared=True + ) + current_pot = closest_dist_sq @ sample_weight + + # Pick the remaining n_clusters-1 points + for c in range(1, n_clusters): + # Choose center candidates by sampling with probability proportional + # to the squared distance to the closest existing center + rand_vals = random_state.uniform(size=n_local_trials) * current_pot + candidate_ids = np.searchsorted( + stable_cumsum(sample_weight * closest_dist_sq), rand_vals + ) + # XXX: numerical imprecision can result in a candidate_id out of range + np.clip(candidate_ids, None, closest_dist_sq.size - 1, out=candidate_ids) + + # Compute distances to center candidates + distance_to_candidates = _euclidean_distances( + X[candidate_ids], X, Y_norm_squared=x_squared_norms, squared=True + ) + + # update closest distances squared and potential for each candidate + np.minimum(closest_dist_sq, distance_to_candidates, out=distance_to_candidates) + candidates_pot = distance_to_candidates @ sample_weight.reshape(-1, 1) + + # Decide which candidate is the best + best_candidate = np.argmin(candidates_pot) + current_pot = candidates_pot[best_candidate] + closest_dist_sq = distance_to_candidates[best_candidate] + best_candidate = candidate_ids[best_candidate] + + # Permanently add best center candidate found in local tries + if sp.issparse(X): + centers[c] = X[[best_candidate]].toarray() + else: + centers[c] = X[best_candidate] + indices[c] = best_candidate + + return centers, indices + + +############################################################################### +# K-means batch estimation by EM (expectation maximization) + + +def _tolerance(X, tol): + """Return a tolerance which is dependent on the dataset.""" + if tol == 0: + return 0 + if sp.issparse(X): + variances = mean_variance_axis(X, axis=0)[1] + else: + variances = np.var(X, axis=0) + return np.mean(variances) * tol + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "sample_weight": ["array-like", None], + "return_n_iter": [bool], + }, + prefer_skip_nested_validation=False, +) +def k_means( + X, + n_clusters, + *, + sample_weight=None, + init="k-means++", + n_init="auto", + max_iter=300, + verbose=False, + tol=1e-4, + random_state=None, + copy_x=True, + algorithm="lloyd", + return_n_iter=False, +): + """Perform K-means clustering algorithm. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The observations to cluster. It must be noted that the data + will be converted to C ordering, which will cause a memory copy + if the given data is not C-contiguous. + + n_clusters : int + The number of clusters to form as well as the number of + centroids to generate. + + sample_weight : array-like of shape (n_samples,), default=None + The weights for each observation in `X`. If `None`, all observations + are assigned equal weight. `sample_weight` is not used during + initialization if `init` is a callable or a user provided array. + + init : {'k-means++', 'random'}, callable or array-like of shape \ + (n_clusters, n_features), default='k-means++' + Method for initialization: + + - `'k-means++'` : selects initial cluster centers for k-mean + clustering in a smart way to speed up convergence. See section + Notes in k_init for more details. + - `'random'`: choose `n_clusters` observations (rows) at random from data + for the initial centroids. + - If an array is passed, it should be of shape `(n_clusters, n_features)` + and gives the initial centers. + - If a callable is passed, it should take arguments `X`, `n_clusters` and a + random state and return an initialization. + + n_init : 'auto' or int, default="auto" + Number of time the k-means algorithm will be run with different + centroid seeds. The final results will be the best output of + n_init consecutive runs in terms of inertia. + + When `n_init='auto'`, the number of runs depends on the value of init: + 10 if using `init='random'` or `init` is a callable; + 1 if using `init='k-means++'` or `init` is an array-like. + + .. versionadded:: 1.2 + Added 'auto' option for `n_init`. + + .. versionchanged:: 1.4 + Default value for `n_init` changed to `'auto'`. + + max_iter : int, default=300 + Maximum number of iterations of the k-means algorithm to run. + + verbose : bool, default=False + Verbosity mode. + + tol : float, default=1e-4 + Relative tolerance with regards to Frobenius norm of the difference + in the cluster centers of two consecutive iterations to declare + convergence. + + random_state : int, RandomState instance or None, default=None + Determines random number generation for centroid initialization. Use + an int to make the randomness deterministic. + See :term:`Glossary `. + + copy_x : bool, default=True + When pre-computing distances it is more numerically accurate to center + the data first. If `copy_x` is True (default), then the original data is + not modified. If False, the original data is modified, and put back + before the function returns, but small numerical differences may be + introduced by subtracting and then adding the data mean. Note that if + the original data is not C-contiguous, a copy will be made even if + `copy_x` is False. If the original data is sparse, but not in CSR format, + a copy will be made even if `copy_x` is False. + + algorithm : {"lloyd", "elkan"}, default="lloyd" + K-means algorithm to use. The classical EM-style algorithm is `"lloyd"`. + The `"elkan"` variation can be more efficient on some datasets with + well-defined clusters, by using the triangle inequality. However it's + more memory intensive due to the allocation of an extra array of shape + `(n_samples, n_clusters)`. + + .. versionchanged:: 0.18 + Added Elkan algorithm + + .. versionchanged:: 1.1 + Renamed "full" to "lloyd", and deprecated "auto" and "full". + Changed "auto" to use "lloyd" instead of "elkan". + + return_n_iter : bool, default=False + Whether or not to return the number of iterations. + + Returns + ------- + centroid : ndarray of shape (n_clusters, n_features) + Centroids found at the last iteration of k-means. + + label : ndarray of shape (n_samples,) + The `label[i]` is the code or index of the centroid the + i'th observation is closest to. + + inertia : float + The final value of the inertia criterion (sum of squared distances to + the closest centroid for all observations in the training set). + + best_n_iter : int + Number of iterations corresponding to the best results. + Returned only if `return_n_iter` is set to True. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.cluster import k_means + >>> X = np.array([[1, 2], [1, 4], [1, 0], + ... [10, 2], [10, 4], [10, 0]]) + >>> centroid, label, inertia = k_means( + ... X, n_clusters=2, n_init="auto", random_state=0 + ... ) + >>> centroid + array([[10., 2.], + [ 1., 2.]]) + >>> label + array([1, 1, 1, 0, 0, 0], dtype=int32) + >>> inertia + 16.0 + """ + est = KMeans( + n_clusters=n_clusters, + init=init, + n_init=n_init, + max_iter=max_iter, + verbose=verbose, + tol=tol, + random_state=random_state, + copy_x=copy_x, + algorithm=algorithm, + ).fit(X, sample_weight=sample_weight) + if return_n_iter: + return est.cluster_centers_, est.labels_, est.inertia_, est.n_iter_ + else: + return est.cluster_centers_, est.labels_, est.inertia_ + + +def _kmeans_single_elkan( + X, + sample_weight, + centers_init, + max_iter=300, + verbose=False, + tol=1e-4, + n_threads=1, +): + """A single run of k-means elkan, assumes preparation completed prior. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + The observations to cluster. If sparse matrix, must be in CSR format. + + sample_weight : array-like of shape (n_samples,) + The weights for each observation in X. + + centers_init : ndarray of shape (n_clusters, n_features) + The initial centers. + + max_iter : int, default=300 + Maximum number of iterations of the k-means algorithm to run. + + verbose : bool, default=False + Verbosity mode. + + tol : float, default=1e-4 + Relative tolerance with regards to Frobenius norm of the difference + in the cluster centers of two consecutive iterations to declare + convergence. + It's not advised to set `tol=0` since convergence might never be + declared due to rounding errors. Use a very small number instead. + + n_threads : int, default=1 + The number of OpenMP threads to use for the computation. Parallelism is + sample-wise on the main cython loop which assigns each sample to its + closest center. + + Returns + ------- + centroid : ndarray of shape (n_clusters, n_features) + Centroids found at the last iteration of k-means. + + label : ndarray of shape (n_samples,) + label[i] is the code or index of the centroid the + i'th observation is closest to. + + inertia : float + The final value of the inertia criterion (sum of squared distances to + the closest centroid for all observations in the training set). + + n_iter : int + Number of iterations run. + """ + n_samples = X.shape[0] + n_clusters = centers_init.shape[0] + + # Buffers to avoid new allocations at each iteration. + centers = centers_init + centers_new = np.zeros_like(centers) + weight_in_clusters = np.zeros(n_clusters, dtype=X.dtype) + labels = np.full(n_samples, -1, dtype=np.int32) + labels_old = labels.copy() + center_half_distances = euclidean_distances(centers) / 2 + distance_next_center = np.partition( + np.asarray(center_half_distances), kth=1, axis=0 + )[1] + upper_bounds = np.zeros(n_samples, dtype=X.dtype) + lower_bounds = np.zeros((n_samples, n_clusters), dtype=X.dtype) + center_shift = np.zeros(n_clusters, dtype=X.dtype) + + if sp.issparse(X): + init_bounds = init_bounds_sparse + elkan_iter = elkan_iter_chunked_sparse + _inertia = _inertia_sparse + else: + init_bounds = init_bounds_dense + elkan_iter = elkan_iter_chunked_dense + _inertia = _inertia_dense + + init_bounds( + X, + centers, + center_half_distances, + labels, + upper_bounds, + lower_bounds, + n_threads=n_threads, + ) + + strict_convergence = False + + for i in range(max_iter): + elkan_iter( + X, + sample_weight, + centers, + centers_new, + weight_in_clusters, + center_half_distances, + distance_next_center, + upper_bounds, + lower_bounds, + labels, + center_shift, + n_threads, + ) + + # compute new pairwise distances between centers and closest other + # center of each center for next iterations + center_half_distances = euclidean_distances(centers_new) / 2 + distance_next_center = np.partition( + np.asarray(center_half_distances), kth=1, axis=0 + )[1] + + if verbose: + inertia = _inertia(X, sample_weight, centers, labels, n_threads) + print(f"Iteration {i}, inertia {inertia}") + + centers, centers_new = centers_new, centers + + if np.array_equal(labels, labels_old): + # First check the labels for strict convergence. + if verbose: + print(f"Converged at iteration {i}: strict convergence.") + strict_convergence = True + break + else: + # No strict convergence, check for tol based convergence. + center_shift_tot = (center_shift**2).sum() + if center_shift_tot <= tol: + if verbose: + print( + f"Converged at iteration {i}: center shift " + f"{center_shift_tot} within tolerance {tol}." + ) + break + + labels_old[:] = labels + + if not strict_convergence: + # rerun E-step so that predicted labels match cluster centers + elkan_iter( + X, + sample_weight, + centers, + centers, + weight_in_clusters, + center_half_distances, + distance_next_center, + upper_bounds, + lower_bounds, + labels, + center_shift, + n_threads, + update_centers=False, + ) + + inertia = _inertia(X, sample_weight, centers, labels, n_threads) + + return labels, inertia, centers, i + 1 + + +# Threadpoolctl context to limit the number of threads in second level of +# nested parallelism (i.e. BLAS) to avoid oversubscription. +@_threadpool_controller_decorator(limits=1, user_api="blas") +def _kmeans_single_lloyd( + X, + sample_weight, + centers_init, + max_iter=300, + verbose=False, + tol=1e-4, + n_threads=1, +): + """A single run of k-means lloyd, assumes preparation completed prior. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + The observations to cluster. If sparse matrix, must be in CSR format. + + sample_weight : ndarray of shape (n_samples,) + The weights for each observation in X. + + centers_init : ndarray of shape (n_clusters, n_features) + The initial centers. + + max_iter : int, default=300 + Maximum number of iterations of the k-means algorithm to run. + + verbose : bool, default=False + Verbosity mode + + tol : float, default=1e-4 + Relative tolerance with regards to Frobenius norm of the difference + in the cluster centers of two consecutive iterations to declare + convergence. + It's not advised to set `tol=0` since convergence might never be + declared due to rounding errors. Use a very small number instead. + + n_threads : int, default=1 + The number of OpenMP threads to use for the computation. Parallelism is + sample-wise on the main cython loop which assigns each sample to its + closest center. + + Returns + ------- + centroid : ndarray of shape (n_clusters, n_features) + Centroids found at the last iteration of k-means. + + label : ndarray of shape (n_samples,) + label[i] is the code or index of the centroid the + i'th observation is closest to. + + inertia : float + The final value of the inertia criterion (sum of squared distances to + the closest centroid for all observations in the training set). + + n_iter : int + Number of iterations run. + """ + n_clusters = centers_init.shape[0] + + # Buffers to avoid new allocations at each iteration. + centers = centers_init + centers_new = np.zeros_like(centers) + labels = np.full(X.shape[0], -1, dtype=np.int32) + labels_old = labels.copy() + weight_in_clusters = np.zeros(n_clusters, dtype=X.dtype) + center_shift = np.zeros(n_clusters, dtype=X.dtype) + + if sp.issparse(X): + lloyd_iter = lloyd_iter_chunked_sparse + _inertia = _inertia_sparse + else: + lloyd_iter = lloyd_iter_chunked_dense + _inertia = _inertia_dense + + strict_convergence = False + + for i in range(max_iter): + lloyd_iter( + X, + sample_weight, + centers, + centers_new, + weight_in_clusters, + labels, + center_shift, + n_threads, + ) + + if verbose: + inertia = _inertia(X, sample_weight, centers, labels, n_threads) + print(f"Iteration {i}, inertia {inertia}.") + + centers, centers_new = centers_new, centers + + if np.array_equal(labels, labels_old): + # First check the labels for strict convergence. + if verbose: + print(f"Converged at iteration {i}: strict convergence.") + strict_convergence = True + break + else: + # No strict convergence, check for tol based convergence. + center_shift_tot = (center_shift**2).sum() + if center_shift_tot <= tol: + if verbose: + print( + f"Converged at iteration {i}: center shift " + f"{center_shift_tot} within tolerance {tol}." + ) + break + + labels_old[:] = labels + + if not strict_convergence: + # rerun E-step so that predicted labels match cluster centers + lloyd_iter( + X, + sample_weight, + centers, + centers, + weight_in_clusters, + labels, + center_shift, + n_threads, + update_centers=False, + ) + + inertia = _inertia(X, sample_weight, centers, labels, n_threads) + + return labels, inertia, centers, i + 1 + + +def _labels_inertia(X, sample_weight, centers, n_threads=1, return_inertia=True): + """E step of the K-means EM algorithm. + + Compute the labels and the inertia of the given samples and centers. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + The input samples to assign to the labels. If sparse matrix, must + be in CSR format. + + sample_weight : ndarray of shape (n_samples,) + The weights for each observation in X. + + x_squared_norms : ndarray of shape (n_samples,) + Precomputed squared euclidean norm of each data point, to speed up + computations. + + centers : ndarray of shape (n_clusters, n_features) + The cluster centers. + + n_threads : int, default=1 + The number of OpenMP threads to use for the computation. Parallelism is + sample-wise on the main cython loop which assigns each sample to its + closest center. + + return_inertia : bool, default=True + Whether to compute and return the inertia. + + Returns + ------- + labels : ndarray of shape (n_samples,) + The resulting assignment. + + inertia : float + Sum of squared distances of samples to their closest cluster center. + Inertia is only returned if return_inertia is True. + """ + n_samples = X.shape[0] + n_clusters = centers.shape[0] + + labels = np.full(n_samples, -1, dtype=np.int32) + center_shift = np.zeros(n_clusters, dtype=centers.dtype) + + if sp.issparse(X): + _labels = lloyd_iter_chunked_sparse + _inertia = _inertia_sparse + else: + _labels = lloyd_iter_chunked_dense + _inertia = _inertia_dense + + _labels( + X, + sample_weight, + centers, + centers_new=None, + weight_in_clusters=None, + labels=labels, + center_shift=center_shift, + n_threads=n_threads, + update_centers=False, + ) + + if return_inertia: + inertia = _inertia(X, sample_weight, centers, labels, n_threads) + return labels, inertia + + return labels + + +# Same as _labels_inertia but in a threadpool_limits context. +_labels_inertia_threadpool_limit = _threadpool_controller_decorator( + limits=1, user_api="blas" +)(_labels_inertia) + + +class _BaseKMeans( + ClassNamePrefixFeaturesOutMixin, TransformerMixin, ClusterMixin, BaseEstimator, ABC +): + """Base class for KMeans and MiniBatchKMeans""" + + _parameter_constraints: dict = { + "n_clusters": [Interval(Integral, 1, None, closed="left")], + "init": [StrOptions({"k-means++", "random"}), callable, "array-like"], + "n_init": [ + StrOptions({"auto"}), + Interval(Integral, 1, None, closed="left"), + ], + "max_iter": [Interval(Integral, 1, None, closed="left")], + "tol": [Interval(Real, 0, None, closed="left")], + "verbose": ["verbose"], + "random_state": ["random_state"], + } + + def __init__( + self, + n_clusters, + *, + init, + n_init, + max_iter, + tol, + verbose, + random_state, + ): + self.n_clusters = n_clusters + self.init = init + self.max_iter = max_iter + self.tol = tol + self.n_init = n_init + self.verbose = verbose + self.random_state = random_state + + def _check_params_vs_input(self, X, default_n_init=None): + # n_clusters + if X.shape[0] < self.n_clusters: + raise ValueError( + f"n_samples={X.shape[0]} should be >= n_clusters={self.n_clusters}." + ) + + # tol + self._tol = _tolerance(X, self.tol) + + # n-init + if self.n_init == "auto": + if isinstance(self.init, str) and self.init == "k-means++": + self._n_init = 1 + elif isinstance(self.init, str) and self.init == "random": + self._n_init = default_n_init + elif callable(self.init): + self._n_init = default_n_init + else: # array-like + self._n_init = 1 + else: + self._n_init = self.n_init + + if _is_arraylike_not_scalar(self.init) and self._n_init != 1: + warnings.warn( + ( + "Explicit initial center position passed: performing only" + f" one init in {self.__class__.__name__} instead of " + f"n_init={self._n_init}." + ), + RuntimeWarning, + stacklevel=2, + ) + self._n_init = 1 + + @abstractmethod + def _warn_mkl_vcomp(self, n_active_threads): + """Issue an estimator specific warning when vcomp and mkl are both present + + This method is called by `_check_mkl_vcomp`. + """ + + def _check_mkl_vcomp(self, X, n_samples): + """Check when vcomp and mkl are both present""" + # The BLAS call inside a prange in lloyd_iter_chunked_dense is known to + # cause a small memory leak when there are less chunks than the number + # of available threads. It only happens when the OpenMP library is + # vcomp (microsoft OpenMP) and the BLAS library is MKL. see #18653 + if sp.issparse(X): + return + + n_active_threads = int(np.ceil(n_samples / CHUNK_SIZE)) + if n_active_threads < self._n_threads: + modules = _get_threadpool_controller().info() + has_vcomp = "vcomp" in [module["prefix"] for module in modules] + has_mkl = ("mkl", "intel") in [ + (module["internal_api"], module.get("threading_layer", None)) + for module in modules + ] + if has_vcomp and has_mkl: + self._warn_mkl_vcomp(n_active_threads) + + def _validate_center_shape(self, X, centers): + """Check if centers is compatible with X and n_clusters.""" + if centers.shape[0] != self.n_clusters: + raise ValueError( + f"The shape of the initial centers {centers.shape} does not " + f"match the number of clusters {self.n_clusters}." + ) + if centers.shape[1] != X.shape[1]: + raise ValueError( + f"The shape of the initial centers {centers.shape} does not " + f"match the number of features of the data {X.shape[1]}." + ) + + def _check_test_data(self, X): + X = validate_data( + self, + X, + accept_sparse="csr", + reset=False, + dtype=[np.float64, np.float32], + order="C", + accept_large_sparse=False, + ) + return X + + def _init_centroids( + self, + X, + x_squared_norms, + init, + random_state, + sample_weight, + init_size=None, + n_centroids=None, + ): + """Compute the initial centroids. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + The input samples. + + x_squared_norms : ndarray of shape (n_samples,) + Squared euclidean norm of each data point. Pass it if you have it + at hands already to avoid it being recomputed here. + + init : {'k-means++', 'random'}, callable or ndarray of shape \ + (n_clusters, n_features) + Method for initialization. + + random_state : RandomState instance + Determines random number generation for centroid initialization. + See :term:`Glossary `. + + sample_weight : ndarray of shape (n_samples,) + The weights for each observation in X. `sample_weight` is not used + during initialization if `init` is a callable or a user provided + array. + + init_size : int, default=None + Number of samples to randomly sample for speeding up the + initialization (sometimes at the expense of accuracy). + + n_centroids : int, default=None + Number of centroids to initialize. + If left to 'None' the number of centroids will be equal to + number of clusters to form (self.n_clusters). + + Returns + ------- + centers : ndarray of shape (n_clusters, n_features) + Initial centroids of clusters. + """ + n_samples = X.shape[0] + n_clusters = self.n_clusters if n_centroids is None else n_centroids + + if init_size is not None and init_size < n_samples: + init_indices = random_state.randint(0, n_samples, init_size) + X = X[init_indices] + x_squared_norms = x_squared_norms[init_indices] + n_samples = X.shape[0] + sample_weight = sample_weight[init_indices] + + if isinstance(init, str) and init == "k-means++": + centers, _ = _kmeans_plusplus( + X, + n_clusters, + random_state=random_state, + x_squared_norms=x_squared_norms, + sample_weight=sample_weight, + ) + elif isinstance(init, str) and init == "random": + seeds = random_state.choice( + n_samples, + size=n_clusters, + replace=False, + p=sample_weight / sample_weight.sum(), + ) + centers = X[seeds] + elif _is_arraylike_not_scalar(self.init): + centers = init + elif callable(init): + centers = init(X, n_clusters, random_state=random_state) + centers = check_array(centers, dtype=X.dtype, copy=False, order="C") + self._validate_center_shape(X, centers) + + if sp.issparse(centers): + centers = centers.toarray() + + return centers + + def fit_predict(self, X, y=None, sample_weight=None): + """Compute cluster centers and predict cluster index for each sample. + + Convenience method; equivalent to calling fit(X) followed by + predict(X). + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + New data to transform. + + y : Ignored + Not used, present here for API consistency by convention. + + sample_weight : array-like of shape (n_samples,), default=None + The weights for each observation in X. If None, all observations + are assigned equal weight. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Index of the cluster each sample belongs to. + """ + return self.fit(X, sample_weight=sample_weight).labels_ + + def predict(self, X): + """Predict the closest cluster each sample in X belongs to. + + In the vector quantization literature, `cluster_centers_` is called + the code book and each value returned by `predict` is the index of + the closest code in the code book. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + New data to predict. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Index of the cluster each sample belongs to. + """ + check_is_fitted(self) + + X = self._check_test_data(X) + + # sample weights are not used by predict but cython helpers expect an array + sample_weight = np.ones(X.shape[0], dtype=X.dtype) + + labels = _labels_inertia_threadpool_limit( + X, + sample_weight, + self.cluster_centers_, + n_threads=self._n_threads, + return_inertia=False, + ) + + return labels + + def fit_transform(self, X, y=None, sample_weight=None): + """Compute clustering and transform X to cluster-distance space. + + Equivalent to fit(X).transform(X), but more efficiently implemented. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + New data to transform. + + y : Ignored + Not used, present here for API consistency by convention. + + sample_weight : array-like of shape (n_samples,), default=None + The weights for each observation in X. If None, all observations + are assigned equal weight. + + Returns + ------- + X_new : ndarray of shape (n_samples, n_clusters) + X transformed in the new space. + """ + return self.fit(X, sample_weight=sample_weight)._transform(X) + + def transform(self, X): + """Transform X to a cluster-distance space. + + In the new space, each dimension is the distance to the cluster + centers. Note that even if X is sparse, the array returned by + `transform` will typically be dense. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + New data to transform. + + Returns + ------- + X_new : ndarray of shape (n_samples, n_clusters) + X transformed in the new space. + """ + check_is_fitted(self) + + X = self._check_test_data(X) + return self._transform(X) + + def _transform(self, X): + """Guts of transform method; no input validation.""" + return euclidean_distances(X, self.cluster_centers_) + + def score(self, X, y=None, sample_weight=None): + """Opposite of the value of X on the K-means objective. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + New data. + + y : Ignored + Not used, present here for API consistency by convention. + + sample_weight : array-like of shape (n_samples,), default=None + The weights for each observation in X. If None, all observations + are assigned equal weight. + + Returns + ------- + score : float + Opposite of the value of X on the K-means objective. + """ + check_is_fitted(self) + + X = self._check_test_data(X) + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + + _, scores = _labels_inertia_threadpool_limit( + X, sample_weight, self.cluster_centers_, self._n_threads + ) + return -scores + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + return tags + + +class KMeans(_BaseKMeans): + """K-Means clustering. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + + n_clusters : int, default=8 + The number of clusters to form as well as the number of + centroids to generate. + + For an example of how to choose an optimal value for `n_clusters` refer to + :ref:`sphx_glr_auto_examples_cluster_plot_kmeans_silhouette_analysis.py`. + + init : {'k-means++', 'random'}, callable or array-like of shape \ + (n_clusters, n_features), default='k-means++' + Method for initialization: + + * 'k-means++' : selects initial cluster centroids using sampling \ + based on an empirical probability distribution of the points' \ + contribution to the overall inertia. This technique speeds up \ + convergence. The algorithm implemented is "greedy k-means++". It \ + differs from the vanilla k-means++ by making several trials at \ + each sampling step and choosing the best centroid among them. + + * 'random': choose `n_clusters` observations (rows) at random from \ + data for the initial centroids. + + * If an array is passed, it should be of shape (n_clusters, n_features)\ + and gives the initial centers. + + * If a callable is passed, it should take arguments X, n_clusters and a\ + random state and return an initialization. + + For an example of how to use the different `init` strategies, see + :ref:`sphx_glr_auto_examples_cluster_plot_kmeans_digits.py`. + + For an evaluation of the impact of initialization, see the example + :ref:`sphx_glr_auto_examples_cluster_plot_kmeans_stability_low_dim_dense.py`. + + n_init : 'auto' or int, default='auto' + Number of times the k-means algorithm is run with different centroid + seeds. The final results is the best output of `n_init` consecutive runs + in terms of inertia. Several runs are recommended for sparse + high-dimensional problems (see :ref:`kmeans_sparse_high_dim`). + + When `n_init='auto'`, the number of runs depends on the value of init: + 10 if using `init='random'` or `init` is a callable; + 1 if using `init='k-means++'` or `init` is an array-like. + + .. versionadded:: 1.2 + Added 'auto' option for `n_init`. + + .. versionchanged:: 1.4 + Default value for `n_init` changed to `'auto'`. + + max_iter : int, default=300 + Maximum number of iterations of the k-means algorithm for a + single run. + + tol : float, default=1e-4 + Relative tolerance with regards to Frobenius norm of the difference + in the cluster centers of two consecutive iterations to declare + convergence. + + verbose : int, default=0 + Verbosity mode. + + random_state : int, RandomState instance or None, default=None + Determines random number generation for centroid initialization. Use + an int to make the randomness deterministic. + See :term:`Glossary `. + + copy_x : bool, default=True + When pre-computing distances it is more numerically accurate to center + the data first. If copy_x is True (default), then the original data is + not modified. If False, the original data is modified, and put back + before the function returns, but small numerical differences may be + introduced by subtracting and then adding the data mean. Note that if + the original data is not C-contiguous, a copy will be made even if + copy_x is False. If the original data is sparse, but not in CSR format, + a copy will be made even if copy_x is False. + + algorithm : {"lloyd", "elkan"}, default="lloyd" + K-means algorithm to use. The classical EM-style algorithm is `"lloyd"`. + The `"elkan"` variation can be more efficient on some datasets with + well-defined clusters, by using the triangle inequality. However it's + more memory intensive due to the allocation of an extra array of shape + `(n_samples, n_clusters)`. + + .. versionchanged:: 0.18 + Added Elkan algorithm + + .. versionchanged:: 1.1 + Renamed "full" to "lloyd", and deprecated "auto" and "full". + Changed "auto" to use "lloyd" instead of "elkan". + + Attributes + ---------- + cluster_centers_ : ndarray of shape (n_clusters, n_features) + Coordinates of cluster centers. If the algorithm stops before fully + converging (see ``tol`` and ``max_iter``), these will not be + consistent with ``labels_``. + + labels_ : ndarray of shape (n_samples,) + Labels of each point + + inertia_ : float + Sum of squared distances of samples to their closest cluster center, + weighted by the sample weights if provided. + + n_iter_ : int + Number of iterations run. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + MiniBatchKMeans : Alternative online implementation that does incremental + updates of the centers positions using mini-batches. + For large scale learning (say n_samples > 10k) MiniBatchKMeans is + probably much faster than the default batch implementation. + + Notes + ----- + The k-means problem is solved using either Lloyd's or Elkan's algorithm. + + The average complexity is given by O(k n T), where n is the number of + samples and T is the number of iteration. + + The worst case complexity is given by O(n^(k+2/p)) with + n = n_samples, p = n_features. + Refer to :doi:`"How slow is the k-means method?" D. Arthur and S. Vassilvitskii - + SoCG2006.<10.1145/1137856.1137880>` for more details. + + In practice, the k-means algorithm is very fast (one of the fastest + clustering algorithms available), but it falls in local minima. That's why + it can be useful to restart it several times. + + If the algorithm stops before fully converging (because of ``tol`` or + ``max_iter``), ``labels_`` and ``cluster_centers_`` will not be consistent, + i.e. the ``cluster_centers_`` will not be the means of the points in each + cluster. Also, the estimator will reassign ``labels_`` after the last + iteration to make ``labels_`` consistent with ``predict`` on the training + set. + + Examples + -------- + + >>> from sklearn.cluster import KMeans + >>> import numpy as np + >>> X = np.array([[1, 2], [1, 4], [1, 0], + ... [10, 2], [10, 4], [10, 0]]) + >>> kmeans = KMeans(n_clusters=2, random_state=0, n_init="auto").fit(X) + >>> kmeans.labels_ + array([1, 1, 1, 0, 0, 0], dtype=int32) + >>> kmeans.predict([[0, 0], [12, 3]]) + array([1, 0], dtype=int32) + >>> kmeans.cluster_centers_ + array([[10., 2.], + [ 1., 2.]]) + + For examples of common problems with K-Means and how to address them see + :ref:`sphx_glr_auto_examples_cluster_plot_kmeans_assumptions.py`. + + For a demonstration of how K-Means can be used to cluster text documents see + :ref:`sphx_glr_auto_examples_text_plot_document_clustering.py`. + + For a comparison between K-Means and MiniBatchKMeans refer to example + :ref:`sphx_glr_auto_examples_cluster_plot_mini_batch_kmeans.py`. + + For a comparison between K-Means and BisectingKMeans refer to example + :ref:`sphx_glr_auto_examples_cluster_plot_bisect_kmeans.py`. + """ + + _parameter_constraints: dict = { + **_BaseKMeans._parameter_constraints, + "copy_x": ["boolean"], + "algorithm": [StrOptions({"lloyd", "elkan"})], + } + + def __init__( + self, + n_clusters=8, + *, + init="k-means++", + n_init="auto", + max_iter=300, + tol=1e-4, + verbose=0, + random_state=None, + copy_x=True, + algorithm="lloyd", + ): + super().__init__( + n_clusters=n_clusters, + init=init, + n_init=n_init, + max_iter=max_iter, + tol=tol, + verbose=verbose, + random_state=random_state, + ) + + self.copy_x = copy_x + self.algorithm = algorithm + + def _check_params_vs_input(self, X): + super()._check_params_vs_input(X, default_n_init=10) + + self._algorithm = self.algorithm + if self._algorithm == "elkan" and self.n_clusters == 1: + warnings.warn( + ( + "algorithm='elkan' doesn't make sense for a single " + "cluster. Using 'lloyd' instead." + ), + RuntimeWarning, + ) + self._algorithm = "lloyd" + + def _warn_mkl_vcomp(self, n_active_threads): + """Warn when vcomp and mkl are both present""" + warnings.warn( + "KMeans is known to have a memory leak on Windows " + "with MKL, when there are less chunks than available " + "threads. You can avoid it by setting the environment" + f" variable OMP_NUM_THREADS={n_active_threads}." + ) + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None, sample_weight=None): + """Compute k-means clustering. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training instances to cluster. It must be noted that the data + will be converted to C ordering, which will cause a memory + copy if the given data is not C-contiguous. + If a sparse matrix is passed, a copy will be made if it's not in + CSR format. + + y : Ignored + Not used, present here for API consistency by convention. + + sample_weight : array-like of shape (n_samples,), default=None + The weights for each observation in X. If None, all observations + are assigned equal weight. `sample_weight` is not used during + initialization if `init` is a callable or a user provided array. + + .. versionadded:: 0.20 + + Returns + ------- + self : object + Fitted estimator. + """ + X = validate_data( + self, + X, + accept_sparse="csr", + dtype=[np.float64, np.float32], + order="C", + copy=self.copy_x, + accept_large_sparse=False, + ) + + self._check_params_vs_input(X) + + random_state = check_random_state(self.random_state) + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + self._n_threads = _openmp_effective_n_threads() + + # Validate init array + init = self.init + init_is_array_like = _is_arraylike_not_scalar(init) + if init_is_array_like: + init = check_array(init, dtype=X.dtype, copy=True, order="C") + self._validate_center_shape(X, init) + + # subtract of mean of x for more accurate distance computations + if not sp.issparse(X): + X_mean = X.mean(axis=0) + # The copy was already done above + X -= X_mean + + if init_is_array_like: + init -= X_mean + + # precompute squared norms of data points + x_squared_norms = row_norms(X, squared=True) + + if self._algorithm == "elkan": + kmeans_single = _kmeans_single_elkan + else: + kmeans_single = _kmeans_single_lloyd + self._check_mkl_vcomp(X, X.shape[0]) + + best_inertia, best_labels = None, None + + for i in range(self._n_init): + # Initialize centers + centers_init = self._init_centroids( + X, + x_squared_norms=x_squared_norms, + init=init, + random_state=random_state, + sample_weight=sample_weight, + ) + if self.verbose: + print("Initialization complete") + + # run a k-means once + labels, inertia, centers, n_iter_ = kmeans_single( + X, + sample_weight, + centers_init, + max_iter=self.max_iter, + verbose=self.verbose, + tol=self._tol, + n_threads=self._n_threads, + ) + + # determine if these results are the best so far + # we chose a new run if it has a better inertia and the clustering is + # different from the best so far (it's possible that the inertia is + # slightly better even if the clustering is the same with potentially + # permuted labels, due to rounding errors) + if best_inertia is None or ( + inertia < best_inertia + and not _is_same_clustering(labels, best_labels, self.n_clusters) + ): + best_labels = labels + best_centers = centers + best_inertia = inertia + best_n_iter = n_iter_ + + if not sp.issparse(X): + if not self.copy_x: + X += X_mean + best_centers += X_mean + + distinct_clusters = len(set(best_labels)) + if distinct_clusters < self.n_clusters: + warnings.warn( + "Number of distinct clusters ({}) found smaller than " + "n_clusters ({}). Possibly due to duplicate points " + "in X.".format(distinct_clusters, self.n_clusters), + ConvergenceWarning, + stacklevel=2, + ) + + self.cluster_centers_ = best_centers + self._n_features_out = self.cluster_centers_.shape[0] + self.labels_ = best_labels + self.inertia_ = best_inertia + self.n_iter_ = best_n_iter + return self + + +def _mini_batch_step( + X, + sample_weight, + centers, + centers_new, + weight_sums, + random_state, + random_reassign=False, + reassignment_ratio=0.01, + verbose=False, + n_threads=1, +): + """Incremental update of the centers for the Minibatch K-Means algorithm. + + Parameters + ---------- + + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + The original data array. If sparse, must be in CSR format. + + x_squared_norms : ndarray of shape (n_samples,) + Squared euclidean norm of each data point. + + sample_weight : ndarray of shape (n_samples,) + The weights for each observation in `X`. + + centers : ndarray of shape (n_clusters, n_features) + The cluster centers before the current iteration + + centers_new : ndarray of shape (n_clusters, n_features) + The cluster centers after the current iteration. Modified in-place. + + weight_sums : ndarray of shape (n_clusters,) + The vector in which we keep track of the numbers of points in a + cluster. This array is modified in place. + + random_state : RandomState instance + Determines random number generation for low count centers reassignment. + See :term:`Glossary `. + + random_reassign : boolean, default=False + If True, centers with very low counts are randomly reassigned + to observations. + + reassignment_ratio : float, default=0.01 + Control the fraction of the maximum number of counts for a + center to be reassigned. A higher value means that low count + centers are more likely to be reassigned, which means that the + model will take longer to converge, but should converge in a + better clustering. + + verbose : bool, default=False + Controls the verbosity. + + n_threads : int, default=1 + The number of OpenMP threads to use for the computation. + + Returns + ------- + inertia : float + Sum of squared distances of samples to their closest cluster center. + The inertia is computed after finding the labels and before updating + the centers. + """ + # Perform label assignment to nearest centers + # For better efficiency, it's better to run _mini_batch_step in a + # threadpool_limit context than using _labels_inertia_threadpool_limit here + labels, inertia = _labels_inertia(X, sample_weight, centers, n_threads=n_threads) + + # Update centers according to the labels + if sp.issparse(X): + _minibatch_update_sparse( + X, sample_weight, centers, centers_new, weight_sums, labels, n_threads + ) + else: + _minibatch_update_dense( + X, + sample_weight, + centers, + centers_new, + weight_sums, + labels, + n_threads, + ) + + # Reassign clusters that have very low weight + if random_reassign and reassignment_ratio > 0: + to_reassign = weight_sums < reassignment_ratio * weight_sums.max() + + # pick at most .5 * batch_size samples as new centers + if to_reassign.sum() > 0.5 * X.shape[0]: + indices_dont_reassign = np.argsort(weight_sums)[int(0.5 * X.shape[0]) :] + to_reassign[indices_dont_reassign] = False + n_reassigns = to_reassign.sum() + + if n_reassigns: + # Pick new clusters amongst observations with uniform probability + new_centers = random_state.choice( + X.shape[0], replace=False, size=n_reassigns + ) + if verbose: + print(f"[MiniBatchKMeans] Reassigning {n_reassigns} cluster centers.") + + if sp.issparse(X): + assign_rows_csr( + X, + new_centers.astype(np.intp, copy=False), + np.where(to_reassign)[0].astype(np.intp, copy=False), + centers_new, + ) + else: + centers_new[to_reassign] = X[new_centers] + + # reset counts of reassigned centers, but don't reset them too small + # to avoid instant reassignment. This is a pretty dirty hack as it + # also modifies the learning rates. + weight_sums[to_reassign] = np.min(weight_sums[~to_reassign]) + + return inertia + + +class MiniBatchKMeans(_BaseKMeans): + """ + Mini-Batch K-Means clustering. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + + n_clusters : int, default=8 + The number of clusters to form as well as the number of + centroids to generate. + + init : {'k-means++', 'random'}, callable or array-like of shape \ + (n_clusters, n_features), default='k-means++' + Method for initialization: + + 'k-means++' : selects initial cluster centroids using sampling based on + an empirical probability distribution of the points' contribution to the + overall inertia. This technique speeds up convergence. The algorithm + implemented is "greedy k-means++". It differs from the vanilla k-means++ + by making several trials at each sampling step and choosing the best centroid + among them. + + 'random': choose `n_clusters` observations (rows) at random from data + for the initial centroids. + + If an array is passed, it should be of shape (n_clusters, n_features) + and gives the initial centers. + + If a callable is passed, it should take arguments X, n_clusters and a + random state and return an initialization. + + For an evaluation of the impact of initialization, see the example + :ref:`sphx_glr_auto_examples_cluster_plot_kmeans_stability_low_dim_dense.py`. + + max_iter : int, default=100 + Maximum number of iterations over the complete dataset before + stopping independently of any early stopping criterion heuristics. + + batch_size : int, default=1024 + Size of the mini batches. + For faster computations, you can set the ``batch_size`` greater than + 256 * number of cores to enable parallelism on all cores. + + .. versionchanged:: 1.0 + `batch_size` default changed from 100 to 1024. + + verbose : int, default=0 + Verbosity mode. + + compute_labels : bool, default=True + Compute label assignment and inertia for the complete dataset + once the minibatch optimization has converged in fit. + + random_state : int, RandomState instance or None, default=None + Determines random number generation for centroid initialization and + random reassignment. Use an int to make the randomness deterministic. + See :term:`Glossary `. + + tol : float, default=0.0 + Control early stopping based on the relative center changes as + measured by a smoothed, variance-normalized of the mean center + squared position changes. This early stopping heuristics is + closer to the one used for the batch variant of the algorithms + but induces a slight computational and memory overhead over the + inertia heuristic. + + To disable convergence detection based on normalized center + change, set tol to 0.0 (default). + + max_no_improvement : int, default=10 + Control early stopping based on the consecutive number of mini + batches that does not yield an improvement on the smoothed inertia. + + To disable convergence detection based on inertia, set + max_no_improvement to None. + + init_size : int, default=None + Number of samples to randomly sample for speeding up the + initialization (sometimes at the expense of accuracy): the + only algorithm is initialized by running a batch KMeans on a + random subset of the data. This needs to be larger than n_clusters. + + If `None`, the heuristic is `init_size = 3 * batch_size` if + `3 * batch_size < n_clusters`, else `init_size = 3 * n_clusters`. + + n_init : 'auto' or int, default="auto" + Number of random initializations that are tried. + In contrast to KMeans, the algorithm is only run once, using the best of + the `n_init` initializations as measured by inertia. Several runs are + recommended for sparse high-dimensional problems (see + :ref:`kmeans_sparse_high_dim`). + + When `n_init='auto'`, the number of runs depends on the value of init: + 3 if using `init='random'` or `init` is a callable; + 1 if using `init='k-means++'` or `init` is an array-like. + + .. versionadded:: 1.2 + Added 'auto' option for `n_init`. + + .. versionchanged:: 1.4 + Default value for `n_init` changed to `'auto'` in version. + + reassignment_ratio : float, default=0.01 + Control the fraction of the maximum number of counts for a center to + be reassigned. A higher value means that low count centers are more + easily reassigned, which means that the model will take longer to + converge, but should converge in a better clustering. However, too high + a value may cause convergence issues, especially with a small batch + size. + + Attributes + ---------- + + cluster_centers_ : ndarray of shape (n_clusters, n_features) + Coordinates of cluster centers. + + labels_ : ndarray of shape (n_samples,) + Labels of each point (if compute_labels is set to True). + + inertia_ : float + The value of the inertia criterion associated with the chosen + partition if compute_labels is set to True. If compute_labels is set to + False, it's an approximation of the inertia based on an exponentially + weighted average of the batch inertiae. + The inertia is defined as the sum of square distances of samples to + their cluster center, weighted by the sample weights if provided. + + n_iter_ : int + Number of iterations over the full dataset. + + n_steps_ : int + Number of minibatches processed. + + .. versionadded:: 1.0 + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + KMeans : The classic implementation of the clustering method based on the + Lloyd's algorithm. It consumes the whole set of input data at each + iteration. + + Notes + ----- + See https://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf + + When there are too few points in the dataset, some centers may be + duplicated, which means that a proper clustering in terms of the number + of requesting clusters and the number of returned clusters will not + always match. One solution is to set `reassignment_ratio=0`, which + prevents reassignments of clusters that are too small. + + See :ref:`sphx_glr_auto_examples_cluster_plot_birch_vs_minibatchkmeans.py` for a + comparison with :class:`~sklearn.cluster.BIRCH`. + + Examples + -------- + >>> from sklearn.cluster import MiniBatchKMeans + >>> import numpy as np + >>> X = np.array([[1, 2], [1, 4], [1, 0], + ... [4, 2], [4, 0], [4, 4], + ... [4, 5], [0, 1], [2, 2], + ... [3, 2], [5, 5], [1, -1]]) + >>> # manually fit on batches + >>> kmeans = MiniBatchKMeans(n_clusters=2, + ... random_state=0, + ... batch_size=6, + ... n_init="auto") + >>> kmeans = kmeans.partial_fit(X[0:6,:]) + >>> kmeans = kmeans.partial_fit(X[6:12,:]) + >>> kmeans.cluster_centers_ + array([[3.375, 3. ], + [0.75 , 0.5 ]]) + >>> kmeans.predict([[0, 0], [4, 4]]) + array([1, 0], dtype=int32) + >>> # fit on the whole data + >>> kmeans = MiniBatchKMeans(n_clusters=2, + ... random_state=0, + ... batch_size=6, + ... max_iter=10, + ... n_init="auto").fit(X) + >>> kmeans.cluster_centers_ + array([[3.55102041, 2.48979592], + [1.06896552, 1. ]]) + >>> kmeans.predict([[0, 0], [4, 4]]) + array([1, 0], dtype=int32) + + For a comparison of Mini-Batch K-Means clustering with other clustering algorithms, + see :ref:`sphx_glr_auto_examples_cluster_plot_cluster_comparison.py` + """ + + _parameter_constraints: dict = { + **_BaseKMeans._parameter_constraints, + "batch_size": [Interval(Integral, 1, None, closed="left")], + "compute_labels": ["boolean"], + "max_no_improvement": [Interval(Integral, 0, None, closed="left"), None], + "init_size": [Interval(Integral, 1, None, closed="left"), None], + "reassignment_ratio": [Interval(Real, 0, None, closed="left")], + } + + def __init__( + self, + n_clusters=8, + *, + init="k-means++", + max_iter=100, + batch_size=1024, + verbose=0, + compute_labels=True, + random_state=None, + tol=0.0, + max_no_improvement=10, + init_size=None, + n_init="auto", + reassignment_ratio=0.01, + ): + super().__init__( + n_clusters=n_clusters, + init=init, + max_iter=max_iter, + verbose=verbose, + random_state=random_state, + tol=tol, + n_init=n_init, + ) + + self.max_no_improvement = max_no_improvement + self.batch_size = batch_size + self.compute_labels = compute_labels + self.init_size = init_size + self.reassignment_ratio = reassignment_ratio + + def _check_params_vs_input(self, X): + super()._check_params_vs_input(X, default_n_init=3) + + self._batch_size = min(self.batch_size, X.shape[0]) + + # init_size + self._init_size = self.init_size + if self._init_size is None: + self._init_size = 3 * self._batch_size + if self._init_size < self.n_clusters: + self._init_size = 3 * self.n_clusters + elif self._init_size < self.n_clusters: + warnings.warn( + ( + f"init_size={self._init_size} should be larger than " + f"n_clusters={self.n_clusters}. Setting it to " + "min(3*n_clusters, n_samples)" + ), + RuntimeWarning, + stacklevel=2, + ) + self._init_size = 3 * self.n_clusters + self._init_size = min(self._init_size, X.shape[0]) + + # reassignment_ratio + if self.reassignment_ratio < 0: + raise ValueError( + "reassignment_ratio should be >= 0, got " + f"{self.reassignment_ratio} instead." + ) + + def _warn_mkl_vcomp(self, n_active_threads): + """Warn when vcomp and mkl are both present""" + warnings.warn( + "MiniBatchKMeans is known to have a memory leak on " + "Windows with MKL, when there are less chunks than " + "available threads. You can prevent it by setting " + f"batch_size >= {self._n_threads * CHUNK_SIZE} or by " + "setting the environment variable " + f"OMP_NUM_THREADS={n_active_threads}" + ) + + def _mini_batch_convergence( + self, step, n_steps, n_samples, centers_squared_diff, batch_inertia + ): + """Helper function to encapsulate the early stopping logic""" + # Normalize inertia to be able to compare values when + # batch_size changes + batch_inertia /= self._batch_size + + # count steps starting from 1 for user friendly verbose mode. + step = step + 1 + + # Ignore first iteration because it's inertia from initialization. + if step == 1: + if self.verbose: + print( + f"Minibatch step {step}/{n_steps}: mean batch " + f"inertia: {batch_inertia}" + ) + return False + + # Compute an Exponentially Weighted Average of the inertia to + # monitor the convergence while discarding minibatch-local stochastic + # variability: https://en.wikipedia.org/wiki/Moving_average + if self._ewa_inertia is None: + self._ewa_inertia = batch_inertia + else: + alpha = self._batch_size * 2.0 / (n_samples + 1) + alpha = min(alpha, 1) + self._ewa_inertia = self._ewa_inertia * (1 - alpha) + batch_inertia * alpha + + # Log progress to be able to monitor convergence + if self.verbose: + print( + f"Minibatch step {step}/{n_steps}: mean batch inertia: " + f"{batch_inertia}, ewa inertia: {self._ewa_inertia}" + ) + + # Early stopping based on absolute tolerance on squared change of + # centers position + if self._tol > 0.0 and centers_squared_diff <= self._tol: + if self.verbose: + print(f"Converged (small centers change) at step {step}/{n_steps}") + return True + + # Early stopping heuristic due to lack of improvement on smoothed + # inertia + if self._ewa_inertia_min is None or self._ewa_inertia < self._ewa_inertia_min: + self._no_improvement = 0 + self._ewa_inertia_min = self._ewa_inertia + else: + self._no_improvement += 1 + + if ( + self.max_no_improvement is not None + and self._no_improvement >= self.max_no_improvement + ): + if self.verbose: + print( + "Converged (lack of improvement in inertia) at step " + f"{step}/{n_steps}" + ) + return True + + return False + + def _random_reassign(self): + """Check if a random reassignment needs to be done. + + Do random reassignments each time 10 * n_clusters samples have been + processed. + + If there are empty clusters we always want to reassign. + """ + self._n_since_last_reassign += self._batch_size + if (self._counts == 0).any() or self._n_since_last_reassign >= ( + 10 * self.n_clusters + ): + self._n_since_last_reassign = 0 + return True + return False + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None, sample_weight=None): + """Compute the centroids on X by chunking it into mini-batches. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training instances to cluster. It must be noted that the data + will be converted to C ordering, which will cause a memory copy + if the given data is not C-contiguous. + If a sparse matrix is passed, a copy will be made if it's not in + CSR format. + + y : Ignored + Not used, present here for API consistency by convention. + + sample_weight : array-like of shape (n_samples,), default=None + The weights for each observation in X. If None, all observations + are assigned equal weight. `sample_weight` is not used during + initialization if `init` is a callable or a user provided array. + + .. versionadded:: 0.20 + + Returns + ------- + self : object + Fitted estimator. + """ + X = validate_data( + self, + X, + accept_sparse="csr", + dtype=[np.float64, np.float32], + order="C", + accept_large_sparse=False, + ) + + self._check_params_vs_input(X) + random_state = check_random_state(self.random_state) + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + self._n_threads = _openmp_effective_n_threads() + n_samples, n_features = X.shape + + # Validate init array + init = self.init + if _is_arraylike_not_scalar(init): + init = check_array(init, dtype=X.dtype, copy=True, order="C") + self._validate_center_shape(X, init) + + self._check_mkl_vcomp(X, self._batch_size) + + # precompute squared norms of data points + x_squared_norms = row_norms(X, squared=True) + + # Validation set for the init + validation_indices = random_state.randint(0, n_samples, self._init_size) + X_valid = X[validation_indices] + sample_weight_valid = sample_weight[validation_indices] + + # perform several inits with random subsets + best_inertia = None + for init_idx in range(self._n_init): + if self.verbose: + print(f"Init {init_idx + 1}/{self._n_init} with method {init}") + + # Initialize the centers using only a fraction of the data as we + # expect n_samples to be very large when using MiniBatchKMeans. + cluster_centers = self._init_centroids( + X, + x_squared_norms=x_squared_norms, + init=init, + random_state=random_state, + init_size=self._init_size, + sample_weight=sample_weight, + ) + + # Compute inertia on a validation set. + _, inertia = _labels_inertia_threadpool_limit( + X_valid, + sample_weight_valid, + cluster_centers, + n_threads=self._n_threads, + ) + + if self.verbose: + print(f"Inertia for init {init_idx + 1}/{self._n_init}: {inertia}") + if best_inertia is None or inertia < best_inertia: + init_centers = cluster_centers + best_inertia = inertia + + centers = init_centers + centers_new = np.empty_like(centers) + + # Initialize counts + self._counts = np.zeros(self.n_clusters, dtype=X.dtype) + + # Attributes to monitor the convergence + self._ewa_inertia = None + self._ewa_inertia_min = None + self._no_improvement = 0 + + # Initialize number of samples seen since last reassignment + self._n_since_last_reassign = 0 + + n_steps = (self.max_iter * n_samples) // self._batch_size + + with _get_threadpool_controller().limit(limits=1, user_api="blas"): + # Perform the iterative optimization until convergence + for i in range(n_steps): + # Sample a minibatch from the full dataset + minibatch_indices = random_state.randint(0, n_samples, self._batch_size) + + # Perform the actual update step on the minibatch data + batch_inertia = _mini_batch_step( + X=X[minibatch_indices], + sample_weight=sample_weight[minibatch_indices], + centers=centers, + centers_new=centers_new, + weight_sums=self._counts, + random_state=random_state, + random_reassign=self._random_reassign(), + reassignment_ratio=self.reassignment_ratio, + verbose=self.verbose, + n_threads=self._n_threads, + ) + + if self._tol > 0.0: + centers_squared_diff = np.sum((centers_new - centers) ** 2) + else: + centers_squared_diff = 0 + + centers, centers_new = centers_new, centers + + # Monitor convergence and do early stopping if necessary + if self._mini_batch_convergence( + i, n_steps, n_samples, centers_squared_diff, batch_inertia + ): + break + + self.cluster_centers_ = centers + self._n_features_out = self.cluster_centers_.shape[0] + + self.n_steps_ = i + 1 + self.n_iter_ = int(np.ceil(((i + 1) * self._batch_size) / n_samples)) + + if self.compute_labels: + self.labels_, self.inertia_ = _labels_inertia_threadpool_limit( + X, + sample_weight, + self.cluster_centers_, + n_threads=self._n_threads, + ) + else: + self.inertia_ = self._ewa_inertia * n_samples + + return self + + @_fit_context(prefer_skip_nested_validation=True) + def partial_fit(self, X, y=None, sample_weight=None): + """Update k means estimate on a single mini-batch X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training instances to cluster. It must be noted that the data + will be converted to C ordering, which will cause a memory copy + if the given data is not C-contiguous. + If a sparse matrix is passed, a copy will be made if it's not in + CSR format. + + y : Ignored + Not used, present here for API consistency by convention. + + sample_weight : array-like of shape (n_samples,), default=None + The weights for each observation in X. If None, all observations + are assigned equal weight. `sample_weight` is not used during + initialization if `init` is a callable or a user provided array. + + Returns + ------- + self : object + Return updated estimator. + """ + has_centers = hasattr(self, "cluster_centers_") + + X = validate_data( + self, + X, + accept_sparse="csr", + dtype=[np.float64, np.float32], + order="C", + accept_large_sparse=False, + reset=not has_centers, + ) + + self._random_state = getattr( + self, "_random_state", check_random_state(self.random_state) + ) + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + self.n_steps_ = getattr(self, "n_steps_", 0) + + # precompute squared norms of data points + x_squared_norms = row_norms(X, squared=True) + + if not has_centers: + # this instance has not been fitted yet (fit or partial_fit) + self._check_params_vs_input(X) + self._n_threads = _openmp_effective_n_threads() + + # Validate init array + init = self.init + if _is_arraylike_not_scalar(init): + init = check_array(init, dtype=X.dtype, copy=True, order="C") + self._validate_center_shape(X, init) + + self._check_mkl_vcomp(X, X.shape[0]) + + # initialize the cluster centers + self.cluster_centers_ = self._init_centroids( + X, + x_squared_norms=x_squared_norms, + init=init, + random_state=self._random_state, + init_size=self._init_size, + sample_weight=sample_weight, + ) + + # Initialize counts + self._counts = np.zeros(self.n_clusters, dtype=X.dtype) + + # Initialize number of samples seen since last reassignment + self._n_since_last_reassign = 0 + + with _get_threadpool_controller().limit(limits=1, user_api="blas"): + _mini_batch_step( + X, + sample_weight=sample_weight, + centers=self.cluster_centers_, + centers_new=self.cluster_centers_, + weight_sums=self._counts, + random_state=self._random_state, + random_reassign=self._random_reassign(), + reassignment_ratio=self.reassignment_ratio, + verbose=self.verbose, + n_threads=self._n_threads, + ) + + if self.compute_labels: + self.labels_, self.inertia_ = _labels_inertia_threadpool_limit( + X, + sample_weight, + self.cluster_centers_, + n_threads=self._n_threads, + ) + + self.n_steps_ += 1 + self._n_features_out = self.cluster_centers_.shape[0] + + return self diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_mean_shift.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_mean_shift.py new file mode 100644 index 0000000000000000000000000000000000000000..1ba4409d14698b482a6854fd1558f014ea3d9f70 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_mean_shift.py @@ -0,0 +1,579 @@ +"""Mean shift clustering algorithm. + +Mean shift clustering aims to discover *blobs* in a smooth density of +samples. It is a centroid based algorithm, which works by updating candidates +for centroids to be the mean of the points within a given region. These +candidates are then filtered in a post-processing stage to eliminate +near-duplicates to form the final set of centroids. + +Seeding is performed using a binning technique for scalability. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from collections import defaultdict +from numbers import Integral, Real + +import numpy as np + +from .._config import config_context +from ..base import BaseEstimator, ClusterMixin, _fit_context +from ..metrics.pairwise import pairwise_distances_argmin +from ..neighbors import NearestNeighbors +from ..utils import check_array, check_random_state, gen_batches +from ..utils._param_validation import Interval, validate_params +from ..utils.parallel import Parallel, delayed +from ..utils.validation import check_is_fitted, validate_data + + +@validate_params( + { + "X": ["array-like"], + "quantile": [Interval(Real, 0, 1, closed="both")], + "n_samples": [Interval(Integral, 1, None, closed="left"), None], + "random_state": ["random_state"], + "n_jobs": [Integral, None], + }, + prefer_skip_nested_validation=True, +) +def estimate_bandwidth(X, *, quantile=0.3, n_samples=None, random_state=0, n_jobs=None): + """Estimate the bandwidth to use with the mean-shift algorithm. + + This function takes time at least quadratic in `n_samples`. For large + datasets, it is wise to subsample by setting `n_samples`. Alternatively, + the parameter `bandwidth` can be set to a small value without estimating + it. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Input points. + + quantile : float, default=0.3 + Should be between [0, 1] + 0.5 means that the median of all pairwise distances is used. + + n_samples : int, default=None + The number of samples to use. If not given, all samples are used. + + random_state : int, RandomState instance, default=None + The generator used to randomly select the samples from input points + for bandwidth estimation. Use an int to make the randomness + deterministic. + See :term:`Glossary `. + + n_jobs : int, default=None + The number of parallel jobs to run for neighbors search. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + Returns + ------- + bandwidth : float + The bandwidth parameter. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.cluster import estimate_bandwidth + >>> X = np.array([[1, 1], [2, 1], [1, 0], + ... [4, 7], [3, 5], [3, 6]]) + >>> estimate_bandwidth(X, quantile=0.5) + np.float64(1.61) + """ + X = check_array(X) + + random_state = check_random_state(random_state) + if n_samples is not None: + idx = random_state.permutation(X.shape[0])[:n_samples] + X = X[idx] + n_neighbors = int(X.shape[0] * quantile) + if n_neighbors < 1: # cannot fit NearestNeighbors with n_neighbors = 0 + n_neighbors = 1 + nbrs = NearestNeighbors(n_neighbors=n_neighbors, n_jobs=n_jobs) + nbrs.fit(X) + + bandwidth = 0.0 + for batch in gen_batches(len(X), 500): + d, _ = nbrs.kneighbors(X[batch, :], return_distance=True) + bandwidth += np.max(d, axis=1).sum() + + return bandwidth / X.shape[0] + + +# separate function for each seed's iterative loop +def _mean_shift_single_seed(my_mean, X, nbrs, max_iter): + # For each seed, climb gradient until convergence or max_iter + bandwidth = nbrs.get_params()["radius"] + stop_thresh = 1e-3 * bandwidth # when mean has converged + completed_iterations = 0 + while True: + # Find mean of points within bandwidth + i_nbrs = nbrs.radius_neighbors([my_mean], bandwidth, return_distance=False)[0] + points_within = X[i_nbrs] + if len(points_within) == 0: + break # Depending on seeding strategy this condition may occur + my_old_mean = my_mean # save the old mean + my_mean = np.mean(points_within, axis=0) + # If converged or at max_iter, adds the cluster + if ( + np.linalg.norm(my_mean - my_old_mean) <= stop_thresh + or completed_iterations == max_iter + ): + break + completed_iterations += 1 + return tuple(my_mean), len(points_within), completed_iterations + + +@validate_params( + {"X": ["array-like"]}, + prefer_skip_nested_validation=False, +) +def mean_shift( + X, + *, + bandwidth=None, + seeds=None, + bin_seeding=False, + min_bin_freq=1, + cluster_all=True, + max_iter=300, + n_jobs=None, +): + """Perform mean shift clustering of data using a flat kernel. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + + X : array-like of shape (n_samples, n_features) + Input data. + + bandwidth : float, default=None + Kernel bandwidth. If not None, must be in the range [0, +inf). + + If None, the bandwidth is determined using a heuristic based on + the median of all pairwise distances. This will take quadratic time in + the number of samples. The sklearn.cluster.estimate_bandwidth function + can be used to do this more efficiently. + + seeds : array-like of shape (n_seeds, n_features) or None + Point used as initial kernel locations. If None and bin_seeding=False, + each data point is used as a seed. If None and bin_seeding=True, + see bin_seeding. + + bin_seeding : bool, default=False + If true, initial kernel locations are not locations of all + points, but rather the location of the discretized version of + points, where points are binned onto a grid whose coarseness + corresponds to the bandwidth. Setting this option to True will speed + up the algorithm because fewer seeds will be initialized. + Ignored if seeds argument is not None. + + min_bin_freq : int, default=1 + To speed up the algorithm, accept only those bins with at least + min_bin_freq points as seeds. + + cluster_all : bool, default=True + If true, then all points are clustered, even those orphans that are + not within any kernel. Orphans are assigned to the nearest kernel. + If false, then orphans are given cluster label -1. + + max_iter : int, default=300 + Maximum number of iterations, per seed point before the clustering + operation terminates (for that seed point), if has not converged yet. + + n_jobs : int, default=None + The number of jobs to use for the computation. The following tasks benefit + from the parallelization: + + - The search of nearest neighbors for bandwidth estimation and label + assignments. See the details in the docstring of the + ``NearestNeighbors`` class. + - Hill-climbing optimization for all seeds. + + See :term:`Glossary ` for more details. + + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + .. versionadded:: 0.17 + Parallel Execution using *n_jobs*. + + Returns + ------- + + cluster_centers : ndarray of shape (n_clusters, n_features) + Coordinates of cluster centers. + + labels : ndarray of shape (n_samples,) + Cluster labels for each point. + + Notes + ----- + For a usage example, see + :ref:`sphx_glr_auto_examples_cluster_plot_mean_shift.py`. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.cluster import mean_shift + >>> X = np.array([[1, 1], [2, 1], [1, 0], + ... [4, 7], [3, 5], [3, 6]]) + >>> cluster_centers, labels = mean_shift(X, bandwidth=2) + >>> cluster_centers + array([[3.33, 6. ], + [1.33, 0.66]]) + >>> labels + array([1, 1, 1, 0, 0, 0]) + """ + model = MeanShift( + bandwidth=bandwidth, + seeds=seeds, + min_bin_freq=min_bin_freq, + bin_seeding=bin_seeding, + cluster_all=cluster_all, + n_jobs=n_jobs, + max_iter=max_iter, + ).fit(X) + return model.cluster_centers_, model.labels_ + + +def get_bin_seeds(X, bin_size, min_bin_freq=1): + """Find seeds for mean_shift. + + Finds seeds by first binning data onto a grid whose lines are + spaced bin_size apart, and then choosing those bins with at least + min_bin_freq points. + + Parameters + ---------- + + X : array-like of shape (n_samples, n_features) + Input points, the same points that will be used in mean_shift. + + bin_size : float + Controls the coarseness of the binning. Smaller values lead + to more seeding (which is computationally more expensive). If you're + not sure how to set this, set it to the value of the bandwidth used + in clustering.mean_shift. + + min_bin_freq : int, default=1 + Only bins with at least min_bin_freq will be selected as seeds. + Raising this value decreases the number of seeds found, which + makes mean_shift computationally cheaper. + + Returns + ------- + bin_seeds : array-like of shape (n_samples, n_features) + Points used as initial kernel positions in clustering.mean_shift. + """ + if bin_size == 0: + return X + + # Bin points + bin_sizes = defaultdict(int) + for point in X: + binned_point = np.round(point / bin_size) + bin_sizes[tuple(binned_point)] += 1 + + # Select only those bins as seeds which have enough members + bin_seeds = np.array( + [point for point, freq in bin_sizes.items() if freq >= min_bin_freq], + dtype=np.float32, + ) + if len(bin_seeds) == len(X): + warnings.warn( + "Binning data failed with provided bin_size=%f, using data points as seeds." + % bin_size + ) + return X + bin_seeds = bin_seeds * bin_size + return bin_seeds + + +class MeanShift(ClusterMixin, BaseEstimator): + """Mean shift clustering using a flat kernel. + + Mean shift clustering aims to discover "blobs" in a smooth density of + samples. It is a centroid-based algorithm, which works by updating + candidates for centroids to be the mean of the points within a given + region. These candidates are then filtered in a post-processing stage to + eliminate near-duplicates to form the final set of centroids. + + Seeding is performed using a binning technique for scalability. + + For an example of how to use MeanShift clustering, refer to: + :ref:`sphx_glr_auto_examples_cluster_plot_mean_shift.py`. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + bandwidth : float, default=None + Bandwidth used in the flat kernel. + + If not given, the bandwidth is estimated using + sklearn.cluster.estimate_bandwidth; see the documentation for that + function for hints on scalability (see also the Notes, below). + + seeds : array-like of shape (n_samples, n_features), default=None + Seeds used to initialize kernels. If not set, + the seeds are calculated by clustering.get_bin_seeds + with bandwidth as the grid size and default values for + other parameters. + + bin_seeding : bool, default=False + If true, initial kernel locations are not locations of all + points, but rather the location of the discretized version of + points, where points are binned onto a grid whose coarseness + corresponds to the bandwidth. Setting this option to True will speed + up the algorithm because fewer seeds will be initialized. + The default value is False. + Ignored if seeds argument is not None. + + min_bin_freq : int, default=1 + To speed up the algorithm, accept only those bins with at least + min_bin_freq points as seeds. + + cluster_all : bool, default=True + If true, then all points are clustered, even those orphans that are + not within any kernel. Orphans are assigned to the nearest kernel. + If false, then orphans are given cluster label -1. + + n_jobs : int, default=None + The number of jobs to use for the computation. The following tasks benefit + from the parallelization: + + - The search of nearest neighbors for bandwidth estimation and label + assignments. See the details in the docstring of the + ``NearestNeighbors`` class. + - Hill-climbing optimization for all seeds. + + See :term:`Glossary ` for more details. + + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + max_iter : int, default=300 + Maximum number of iterations, per seed point before the clustering + operation terminates (for that seed point), if has not converged yet. + + .. versionadded:: 0.22 + + Attributes + ---------- + cluster_centers_ : ndarray of shape (n_clusters, n_features) + Coordinates of cluster centers. + + labels_ : ndarray of shape (n_samples,) + Labels of each point. + + n_iter_ : int + Maximum number of iterations performed on each seed. + + .. versionadded:: 0.22 + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + KMeans : K-Means clustering. + + Notes + ----- + + Scalability: + + Because this implementation uses a flat kernel and + a Ball Tree to look up members of each kernel, the complexity will tend + towards O(T*n*log(n)) in lower dimensions, with n the number of samples + and T the number of points. In higher dimensions the complexity will + tend towards O(T*n^2). + + Scalability can be boosted by using fewer seeds, for example by using + a higher value of min_bin_freq in the get_bin_seeds function. + + Note that the estimate_bandwidth function is much less scalable than the + mean shift algorithm and will be the bottleneck if it is used. + + References + ---------- + + Dorin Comaniciu and Peter Meer, "Mean Shift: A robust approach toward + feature space analysis". IEEE Transactions on Pattern Analysis and + Machine Intelligence. 2002. pp. 603-619. + + Examples + -------- + >>> from sklearn.cluster import MeanShift + >>> import numpy as np + >>> X = np.array([[1, 1], [2, 1], [1, 0], + ... [4, 7], [3, 5], [3, 6]]) + >>> clustering = MeanShift(bandwidth=2).fit(X) + >>> clustering.labels_ + array([1, 1, 1, 0, 0, 0]) + >>> clustering.predict([[0, 0], [5, 5]]) + array([1, 0]) + >>> clustering + MeanShift(bandwidth=2) + + For a comparison of Mean Shift clustering with other clustering algorithms, see + :ref:`sphx_glr_auto_examples_cluster_plot_cluster_comparison.py` + """ + + _parameter_constraints: dict = { + "bandwidth": [Interval(Real, 0, None, closed="neither"), None], + "seeds": ["array-like", None], + "bin_seeding": ["boolean"], + "min_bin_freq": [Interval(Integral, 1, None, closed="left")], + "cluster_all": ["boolean"], + "n_jobs": [Integral, None], + "max_iter": [Interval(Integral, 0, None, closed="left")], + } + + def __init__( + self, + *, + bandwidth=None, + seeds=None, + bin_seeding=False, + min_bin_freq=1, + cluster_all=True, + n_jobs=None, + max_iter=300, + ): + self.bandwidth = bandwidth + self.seeds = seeds + self.bin_seeding = bin_seeding + self.cluster_all = cluster_all + self.min_bin_freq = min_bin_freq + self.n_jobs = n_jobs + self.max_iter = max_iter + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Perform clustering. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Samples to cluster. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + self : object + Fitted instance. + """ + X = validate_data(self, X) + bandwidth = self.bandwidth + if bandwidth is None: + bandwidth = estimate_bandwidth(X, n_jobs=self.n_jobs) + + seeds = self.seeds + if seeds is None: + if self.bin_seeding: + seeds = get_bin_seeds(X, bandwidth, self.min_bin_freq) + else: + seeds = X + n_samples, n_features = X.shape + center_intensity_dict = {} + + # We use n_jobs=1 because this will be used in nested calls under + # parallel calls to _mean_shift_single_seed so there is no need for + # for further parallelism. + nbrs = NearestNeighbors(radius=bandwidth, n_jobs=1).fit(X) + + # execute iterations on all seeds in parallel + all_res = Parallel(n_jobs=self.n_jobs)( + delayed(_mean_shift_single_seed)(seed, X, nbrs, self.max_iter) + for seed in seeds + ) + # copy results in a dictionary + for i in range(len(seeds)): + if all_res[i][1]: # i.e. len(points_within) > 0 + center_intensity_dict[all_res[i][0]] = all_res[i][1] + + self.n_iter_ = max([x[2] for x in all_res]) + + if not center_intensity_dict: + # nothing near seeds + raise ValueError( + "No point was within bandwidth=%f of any seed. Try a different seeding" + " strategy or increase the bandwidth." + % bandwidth + ) + + # POST PROCESSING: remove near duplicate points + # If the distance between two kernels is less than the bandwidth, + # then we have to remove one because it is a duplicate. Remove the + # one with fewer points. + + sorted_by_intensity = sorted( + center_intensity_dict.items(), + key=lambda tup: (tup[1], tup[0]), + reverse=True, + ) + sorted_centers = np.array([tup[0] for tup in sorted_by_intensity]) + unique = np.ones(len(sorted_centers), dtype=bool) + nbrs = NearestNeighbors(radius=bandwidth, n_jobs=self.n_jobs).fit( + sorted_centers + ) + for i, center in enumerate(sorted_centers): + if unique[i]: + neighbor_idxs = nbrs.radius_neighbors([center], return_distance=False)[ + 0 + ] + unique[neighbor_idxs] = 0 + unique[i] = 1 # leave the current point as unique + cluster_centers = sorted_centers[unique] + + # ASSIGN LABELS: a point belongs to the cluster that it is closest to + nbrs = NearestNeighbors(n_neighbors=1, n_jobs=self.n_jobs).fit(cluster_centers) + labels = np.zeros(n_samples, dtype=int) + distances, idxs = nbrs.kneighbors(X) + if self.cluster_all: + labels = idxs.flatten() + else: + labels.fill(-1) + bool_selector = distances.flatten() <= bandwidth + labels[bool_selector] = idxs.flatten()[bool_selector] + + self.cluster_centers_, self.labels_ = cluster_centers, labels + return self + + def predict(self, X): + """Predict the closest cluster each sample in X belongs to. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + New data to predict. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Index of the cluster each sample belongs to. + """ + check_is_fitted(self) + X = validate_data(self, X, reset=False) + with config_context(assume_finite=True): + return pairwise_distances_argmin(X, self.cluster_centers_) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_optics.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_optics.py new file mode 100644 index 0000000000000000000000000000000000000000..4a1a80c9065c2d1504a6c97a926b919374e0a1ee --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_optics.py @@ -0,0 +1,1202 @@ +"""Ordering Points To Identify the Clustering Structure (OPTICS) + +These routines execute the OPTICS algorithm, and implement various +cluster extraction methods of the ordered list. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from numbers import Integral, Real + +import numpy as np +from scipy.sparse import SparseEfficiencyWarning, issparse + +from ..base import BaseEstimator, ClusterMixin, _fit_context +from ..exceptions import DataConversionWarning +from ..metrics import pairwise_distances +from ..metrics.pairwise import _VALID_METRICS, PAIRWISE_BOOLEAN_FUNCTIONS +from ..neighbors import NearestNeighbors +from ..utils import gen_batches +from ..utils._chunking import get_chunk_n_rows +from ..utils._param_validation import ( + HasMethods, + Interval, + RealNotInt, + StrOptions, + validate_params, +) +from ..utils.validation import check_memory, validate_data + + +class OPTICS(ClusterMixin, BaseEstimator): + """Estimate clustering structure from vector array. + + OPTICS (Ordering Points To Identify the Clustering Structure), closely + related to DBSCAN, finds core samples of high density and expands clusters + from them [1]_. Unlike DBSCAN, it keeps cluster hierarchy for a variable + neighborhood radius. Better suited for usage on large datasets than the + current scikit-learn implementation of DBSCAN. + + Clusters are then extracted from the cluster-order using a + DBSCAN-like method (cluster_method = 'dbscan') or an automatic + technique proposed in [1]_ (cluster_method = 'xi'). + + This implementation deviates from the original OPTICS by first performing + k-nearest-neighborhood searches on all points to identify core sizes of + all points (instead of computing neighbors while looping through points). + Reachability distances to only unprocessed points are then computed, to + construct the cluster order, similar to the original OPTICS. + Note that we do not employ a heap to manage the expansion + candidates, so the time complexity will be O(n^2). + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + min_samples : int > 1 or float between 0 and 1, default=5 + The number of samples in a neighborhood for a point to be considered as + a core point. Also, up and down steep regions can't have more than + ``min_samples`` consecutive non-steep points. Expressed as an absolute + number or a fraction of the number of samples (rounded to be at least + 2). + + max_eps : float, default=np.inf + The maximum distance between two samples for one to be considered as + in the neighborhood of the other. Default value of ``np.inf`` will + identify clusters across all scales; reducing ``max_eps`` will result + in shorter run times. + + metric : str or callable, default='minkowski' + Metric to use for distance computation. Any metric from scikit-learn + or :mod:`scipy.spatial.distance` can be used. + + If `metric` is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two arrays as input and return one value indicating the + distance between them. This works for Scipy's metrics, but is less + efficient than passing the metric name as a string. If metric is + "precomputed", `X` is assumed to be a distance matrix and must be + square. + + Valid values for metric are: + + - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', + 'manhattan'] + + - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', + 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', + 'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao', + 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', + 'yule'] + + Sparse matrices are only supported by scikit-learn metrics. + See :mod:`scipy.spatial.distance` for details on these metrics. + + .. note:: + `'kulsinski'` is deprecated from SciPy 1.9 and will be removed in SciPy 1.11. + + p : float, default=2 + Parameter for the Minkowski metric from + :class:`~sklearn.metrics.pairwise_distances`. When p = 1, this is + equivalent to using manhattan_distance (l1), and euclidean_distance + (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. + + metric_params : dict, default=None + Additional keyword arguments for the metric function. + + cluster_method : {'xi', 'dbscan'}, default='xi' + The extraction method used to extract clusters using the calculated + reachability and ordering. + + eps : float, default=None + The maximum distance between two samples for one to be considered as + in the neighborhood of the other. By default it assumes the same value + as ``max_eps``. + Used only when ``cluster_method='dbscan'``. + + xi : float between 0 and 1, default=0.05 + Determines the minimum steepness on the reachability plot that + constitutes a cluster boundary. For example, an upwards point in the + reachability plot is defined by the ratio from one point to its + successor being at most 1-xi. + Used only when ``cluster_method='xi'``. + + predecessor_correction : bool, default=True + Correct clusters according to the predecessors calculated by OPTICS + [2]_. This parameter has minimal effect on most datasets. + Used only when ``cluster_method='xi'``. + + min_cluster_size : int > 1 or float between 0 and 1, default=None + Minimum number of samples in an OPTICS cluster, expressed as an + absolute number or a fraction of the number of samples (rounded to be + at least 2). If ``None``, the value of ``min_samples`` is used instead. + Used only when ``cluster_method='xi'``. + + algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto' + Algorithm used to compute the nearest neighbors: + + - 'ball_tree' will use :class:`~sklearn.neighbors.BallTree`. + - 'kd_tree' will use :class:`~sklearn.neighbors.KDTree`. + - 'brute' will use a brute-force search. + - 'auto' (default) will attempt to decide the most appropriate + algorithm based on the values passed to :meth:`fit` method. + + Note: fitting on sparse input will override the setting of + this parameter, using brute force. + + leaf_size : int, default=30 + Leaf size passed to :class:`~sklearn.neighbors.BallTree` or + :class:`~sklearn.neighbors.KDTree`. This can affect the speed of the + construction and query, as well as the memory required to store the + tree. The optimal value depends on the nature of the problem. + + memory : str or object with the joblib.Memory interface, default=None + Used to cache the output of the computation of the tree. + By default, no caching is done. If a string is given, it is the + path to the caching directory. + + n_jobs : int, default=None + The number of parallel jobs to run for neighbors search. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + Attributes + ---------- + labels_ : ndarray of shape (n_samples,) + Cluster labels for each point in the dataset given to fit(). + Noisy samples and points which are not included in a leaf cluster + of ``cluster_hierarchy_`` are labeled as -1. + + reachability_ : ndarray of shape (n_samples,) + Reachability distances per sample, indexed by object order. Use + ``clust.reachability_[clust.ordering_]`` to access in cluster order. + + ordering_ : ndarray of shape (n_samples,) + The cluster ordered list of sample indices. + + core_distances_ : ndarray of shape (n_samples,) + Distance at which each sample becomes a core point, indexed by object + order. Points which will never be core have a distance of inf. Use + ``clust.core_distances_[clust.ordering_]`` to access in cluster order. + + predecessor_ : ndarray of shape (n_samples,) + Point that a sample was reached from, indexed by object order. + Seed points have a predecessor of -1. + + cluster_hierarchy_ : ndarray of shape (n_clusters, 2) + The list of clusters in the form of ``[start, end]`` in each row, with + all indices inclusive. The clusters are ordered according to + ``(end, -start)`` (ascending) so that larger clusters encompassing + smaller clusters come after those smaller ones. Since ``labels_`` does + not reflect the hierarchy, usually + ``len(cluster_hierarchy_) > np.unique(optics.labels_)``. Please also + note that these indices are of the ``ordering_``, i.e. + ``X[ordering_][start:end + 1]`` form a cluster. + Only available when ``cluster_method='xi'``. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + DBSCAN : A similar clustering for a specified neighborhood radius (eps). + Our implementation is optimized for runtime. + + References + ---------- + .. [1] Ankerst, Mihael, Markus M. Breunig, Hans-Peter Kriegel, + and Jörg Sander. "OPTICS: ordering points to identify the clustering + structure." ACM SIGMOD Record 28, no. 2 (1999): 49-60. + + .. [2] Schubert, Erich, Michael Gertz. + "Improving the Cluster Structure Extracted from OPTICS Plots." Proc. of + the Conference "Lernen, Wissen, Daten, Analysen" (LWDA) (2018): 318-329. + + Examples + -------- + >>> from sklearn.cluster import OPTICS + >>> import numpy as np + >>> X = np.array([[1, 2], [2, 5], [3, 6], + ... [8, 7], [8, 8], [7, 3]]) + >>> clustering = OPTICS(min_samples=2).fit(X) + >>> clustering.labels_ + array([0, 0, 0, 1, 1, 1]) + + For a more detailed example see + :ref:`sphx_glr_auto_examples_cluster_plot_optics.py`. + + For a comparison of OPTICS with other clustering algorithms, see + :ref:`sphx_glr_auto_examples_cluster_plot_cluster_comparison.py` + """ + + _parameter_constraints: dict = { + "min_samples": [ + Interval(Integral, 2, None, closed="left"), + Interval(RealNotInt, 0, 1, closed="both"), + ], + "max_eps": [Interval(Real, 0, None, closed="both")], + "metric": [StrOptions(set(_VALID_METRICS) | {"precomputed"}), callable], + "p": [Interval(Real, 1, None, closed="left")], + "metric_params": [dict, None], + "cluster_method": [StrOptions({"dbscan", "xi"})], + "eps": [Interval(Real, 0, None, closed="both"), None], + "xi": [Interval(Real, 0, 1, closed="both")], + "predecessor_correction": ["boolean"], + "min_cluster_size": [ + Interval(Integral, 2, None, closed="left"), + Interval(RealNotInt, 0, 1, closed="right"), + None, + ], + "algorithm": [StrOptions({"auto", "brute", "ball_tree", "kd_tree"})], + "leaf_size": [Interval(Integral, 1, None, closed="left")], + "memory": [str, HasMethods("cache"), None], + "n_jobs": [Integral, None], + } + + def __init__( + self, + *, + min_samples=5, + max_eps=np.inf, + metric="minkowski", + p=2, + metric_params=None, + cluster_method="xi", + eps=None, + xi=0.05, + predecessor_correction=True, + min_cluster_size=None, + algorithm="auto", + leaf_size=30, + memory=None, + n_jobs=None, + ): + self.max_eps = max_eps + self.min_samples = min_samples + self.min_cluster_size = min_cluster_size + self.algorithm = algorithm + self.metric = metric + self.metric_params = metric_params + self.p = p + self.leaf_size = leaf_size + self.cluster_method = cluster_method + self.eps = eps + self.xi = xi + self.predecessor_correction = predecessor_correction + self.memory = memory + self.n_jobs = n_jobs + + @_fit_context( + # Optics.metric is not validated yet + prefer_skip_nested_validation=False + ) + def fit(self, X, y=None): + """Perform OPTICS clustering. + + Extracts an ordered list of points and reachability distances, and + performs initial clustering using ``max_eps`` distance specified at + OPTICS object instantiation. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features), or \ + (n_samples, n_samples) if metric='precomputed' + A feature array, or array of distances between samples if + metric='precomputed'. If a sparse matrix is provided, it will be + converted into CSR format. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + self : object + Returns a fitted instance of self. + """ + dtype = bool if self.metric in PAIRWISE_BOOLEAN_FUNCTIONS else float + if dtype is bool and X.dtype != bool: + msg = ( + "Data will be converted to boolean for" + f" metric {self.metric}, to avoid this warning," + " you may convert the data prior to calling fit." + ) + warnings.warn(msg, DataConversionWarning) + + X = validate_data(self, X, dtype=dtype, accept_sparse="csr") + if self.metric == "precomputed" and issparse(X): + X = X.copy() # copy to avoid in-place modification + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SparseEfficiencyWarning) + # Set each diagonal to an explicit value so each point is its + # own neighbor + X.setdiag(X.diagonal()) + memory = check_memory(self.memory) + + ( + self.ordering_, + self.core_distances_, + self.reachability_, + self.predecessor_, + ) = memory.cache(compute_optics_graph)( + X=X, + min_samples=self.min_samples, + algorithm=self.algorithm, + leaf_size=self.leaf_size, + metric=self.metric, + metric_params=self.metric_params, + p=self.p, + n_jobs=self.n_jobs, + max_eps=self.max_eps, + ) + + # Extract clusters from the calculated orders and reachability + if self.cluster_method == "xi": + labels_, clusters_ = cluster_optics_xi( + reachability=self.reachability_, + predecessor=self.predecessor_, + ordering=self.ordering_, + min_samples=self.min_samples, + min_cluster_size=self.min_cluster_size, + xi=self.xi, + predecessor_correction=self.predecessor_correction, + ) + self.cluster_hierarchy_ = clusters_ + elif self.cluster_method == "dbscan": + if self.eps is None: + eps = self.max_eps + else: + eps = self.eps + + if eps > self.max_eps: + raise ValueError( + "Specify an epsilon smaller than %s. Got %s." % (self.max_eps, eps) + ) + + labels_ = cluster_optics_dbscan( + reachability=self.reachability_, + core_distances=self.core_distances_, + ordering=self.ordering_, + eps=eps, + ) + + self.labels_ = labels_ + return self + + +def _validate_size(size, n_samples, param_name): + if size > n_samples: + raise ValueError( + "%s must be no greater than the number of samples (%d). Got %d" + % (param_name, n_samples, size) + ) + + +# OPTICS helper functions +def _compute_core_distances_(X, neighbors, min_samples, working_memory): + """Compute the k-th nearest neighbor of each sample. + + Equivalent to neighbors.kneighbors(X, self.min_samples)[0][:, -1] + but with more memory efficiency. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data. + neighbors : NearestNeighbors instance + The fitted nearest neighbors estimator. + working_memory : int, default=None + The sought maximum memory for temporary distance matrix chunks. + When None (default), the value of + ``sklearn.get_config()['working_memory']`` is used. + + Returns + ------- + core_distances : ndarray of shape (n_samples,) + Distance at which each sample becomes a core point. + Points which will never be core have a distance of inf. + """ + n_samples = X.shape[0] + core_distances = np.empty(n_samples) + core_distances.fill(np.nan) + + chunk_n_rows = get_chunk_n_rows( + row_bytes=16 * min_samples, max_n_rows=n_samples, working_memory=working_memory + ) + slices = gen_batches(n_samples, chunk_n_rows) + for sl in slices: + core_distances[sl] = neighbors.kneighbors(X[sl], min_samples)[0][:, -1] + return core_distances + + +@validate_params( + { + "X": [np.ndarray, "sparse matrix"], + "min_samples": [ + Interval(Integral, 2, None, closed="left"), + Interval(RealNotInt, 0, 1, closed="both"), + ], + "max_eps": [Interval(Real, 0, None, closed="both")], + "metric": [StrOptions(set(_VALID_METRICS) | {"precomputed"}), callable], + "p": [Interval(Real, 0, None, closed="right"), None], + "metric_params": [dict, None], + "algorithm": [StrOptions({"auto", "brute", "ball_tree", "kd_tree"})], + "leaf_size": [Interval(Integral, 1, None, closed="left")], + "n_jobs": [Integral, None], + }, + prefer_skip_nested_validation=False, # metric is not validated yet +) +def compute_optics_graph( + X, *, min_samples, max_eps, metric, p, metric_params, algorithm, leaf_size, n_jobs +): + """Compute the OPTICS reachability graph. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features), or \ + (n_samples, n_samples) if metric='precomputed' + A feature array, or array of distances between samples if + metric='precomputed'. + + min_samples : int > 1 or float between 0 and 1 + The number of samples in a neighborhood for a point to be considered + as a core point. Expressed as an absolute number or a fraction of the + number of samples (rounded to be at least 2). + + max_eps : float, default=np.inf + The maximum distance between two samples for one to be considered as + in the neighborhood of the other. Default value of ``np.inf`` will + identify clusters across all scales; reducing ``max_eps`` will result + in shorter run times. + + metric : str or callable, default='minkowski' + Metric to use for distance computation. Any metric from scikit-learn + or scipy.spatial.distance can be used. + + If metric is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two arrays as input and return one value indicating the + distance between them. This works for Scipy's metrics, but is less + efficient than passing the metric name as a string. If metric is + "precomputed", X is assumed to be a distance matrix and must be square. + + Valid values for metric are: + + - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', + 'manhattan'] + + - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', + 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', + 'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao', + 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', + 'yule'] + + See the documentation for scipy.spatial.distance for details on these + metrics. + + .. note:: + `'kulsinski'` is deprecated from SciPy 1.9 and will be removed in SciPy 1.11. + + p : float, default=2 + Parameter for the Minkowski metric from + :class:`~sklearn.metrics.pairwise_distances`. When p = 1, this is + equivalent to using manhattan_distance (l1), and euclidean_distance + (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. + + metric_params : dict, default=None + Additional keyword arguments for the metric function. + + algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto' + Algorithm used to compute the nearest neighbors: + + - 'ball_tree' will use :class:`~sklearn.neighbors.BallTree`. + - 'kd_tree' will use :class:`~sklearn.neighbors.KDTree`. + - 'brute' will use a brute-force search. + - 'auto' will attempt to decide the most appropriate algorithm + based on the values passed to `fit` method. (default) + + Note: fitting on sparse input will override the setting of + this parameter, using brute force. + + leaf_size : int, default=30 + Leaf size passed to :class:`~sklearn.neighbors.BallTree` or + :class:`~sklearn.neighbors.KDTree`. This can affect the speed of the + construction and query, as well as the memory required to store the + tree. The optimal value depends on the nature of the problem. + + n_jobs : int, default=None + The number of parallel jobs to run for neighbors search. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + Returns + ------- + ordering_ : array of shape (n_samples,) + The cluster ordered list of sample indices. + + core_distances_ : array of shape (n_samples,) + Distance at which each sample becomes a core point, indexed by object + order. Points which will never be core have a distance of inf. Use + ``clust.core_distances_[clust.ordering_]`` to access in cluster order. + + reachability_ : array of shape (n_samples,) + Reachability distances per sample, indexed by object order. Use + ``clust.reachability_[clust.ordering_]`` to access in cluster order. + + predecessor_ : array of shape (n_samples,) + Point that a sample was reached from, indexed by object order. + Seed points have a predecessor of -1. + + References + ---------- + .. [1] Ankerst, Mihael, Markus M. Breunig, Hans-Peter Kriegel, + and Jörg Sander. "OPTICS: ordering points to identify the clustering + structure." ACM SIGMOD Record 28, no. 2 (1999): 49-60. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.cluster import compute_optics_graph + >>> X = np.array([[1, 2], [2, 5], [3, 6], + ... [8, 7], [8, 8], [7, 3]]) + >>> ordering, core_distances, reachability, predecessor = compute_optics_graph( + ... X, + ... min_samples=2, + ... max_eps=np.inf, + ... metric="minkowski", + ... p=2, + ... metric_params=None, + ... algorithm="auto", + ... leaf_size=30, + ... n_jobs=None, + ... ) + >>> ordering + array([0, 1, 2, 5, 3, 4]) + >>> core_distances + array([3.16, 1.41, 1.41, 1. , 1. , + 4.12]) + >>> reachability + array([ inf, 3.16, 1.41, 4.12, 1. , + 5. ]) + >>> predecessor + array([-1, 0, 1, 5, 3, 2]) + """ + n_samples = X.shape[0] + _validate_size(min_samples, n_samples, "min_samples") + if min_samples <= 1: + min_samples = max(2, int(min_samples * n_samples)) + + # Start all points as 'unprocessed' ## + reachability_ = np.empty(n_samples) + reachability_.fill(np.inf) + predecessor_ = np.empty(n_samples, dtype=int) + predecessor_.fill(-1) + + nbrs = NearestNeighbors( + n_neighbors=min_samples, + algorithm=algorithm, + leaf_size=leaf_size, + metric=metric, + metric_params=metric_params, + p=p, + n_jobs=n_jobs, + ) + + nbrs.fit(X) + # Here we first do a kNN query for each point, this differs from + # the original OPTICS that only used epsilon range queries. + # TODO: handle working_memory somehow? + core_distances_ = _compute_core_distances_( + X=X, neighbors=nbrs, min_samples=min_samples, working_memory=None + ) + # OPTICS puts an upper limit on these, use inf for undefined. + core_distances_[core_distances_ > max_eps] = np.inf + np.around( + core_distances_, + decimals=np.finfo(core_distances_.dtype).precision, + out=core_distances_, + ) + + # Main OPTICS loop. Not parallelizable. The order that entries are + # written to the 'ordering_' list is important! + # Note that this implementation is O(n^2) theoretically, but + # supposedly with very low constant factors. + processed = np.zeros(X.shape[0], dtype=bool) + ordering = np.zeros(X.shape[0], dtype=int) + for ordering_idx in range(X.shape[0]): + # Choose next based on smallest reachability distance + # (And prefer smaller ids on ties, possibly np.inf!) + index = np.where(processed == 0)[0] + point = index[np.argmin(reachability_[index])] + + processed[point] = True + ordering[ordering_idx] = point + if core_distances_[point] != np.inf: + _set_reach_dist( + core_distances_=core_distances_, + reachability_=reachability_, + predecessor_=predecessor_, + point_index=point, + processed=processed, + X=X, + nbrs=nbrs, + metric=metric, + metric_params=metric_params, + p=p, + max_eps=max_eps, + ) + if np.all(np.isinf(reachability_)): + warnings.warn( + ( + "All reachability values are inf. Set a larger" + " max_eps or all data will be considered outliers." + ), + UserWarning, + ) + return ordering, core_distances_, reachability_, predecessor_ + + +def _set_reach_dist( + core_distances_, + reachability_, + predecessor_, + point_index, + processed, + X, + nbrs, + metric, + metric_params, + p, + max_eps, +): + P = X[point_index : point_index + 1] + # Assume that radius_neighbors is faster without distances + # and we don't need all distances, nevertheless, this means + # we may be doing some work twice. + indices = nbrs.radius_neighbors(P, radius=max_eps, return_distance=False)[0] + + # Getting indices of neighbors that have not been processed + unproc = np.compress(~np.take(processed, indices), indices) + # Neighbors of current point are already processed. + if not unproc.size: + return + + # Only compute distances to unprocessed neighbors: + if metric == "precomputed": + dists = X[[point_index], unproc] + if isinstance(dists, np.matrix): + dists = np.asarray(dists) + dists = dists.ravel() + else: + _params = dict() if metric_params is None else metric_params.copy() + if metric == "minkowski" and "p" not in _params: + # the same logic as neighbors, p is ignored if explicitly set + # in the dict params + _params["p"] = p + dists = pairwise_distances(P, X[unproc], metric, n_jobs=None, **_params).ravel() + + rdists = np.maximum(dists, core_distances_[point_index]) + np.around(rdists, decimals=np.finfo(rdists.dtype).precision, out=rdists) + improved = np.where(rdists < np.take(reachability_, unproc)) + reachability_[unproc[improved]] = rdists[improved] + predecessor_[unproc[improved]] = point_index + + +@validate_params( + { + "reachability": [np.ndarray], + "core_distances": [np.ndarray], + "ordering": [np.ndarray], + "eps": [Interval(Real, 0, None, closed="both")], + }, + prefer_skip_nested_validation=True, +) +def cluster_optics_dbscan(*, reachability, core_distances, ordering, eps): + """Perform DBSCAN extraction for an arbitrary epsilon. + + Extracting the clusters runs in linear time. Note that this results in + ``labels_`` which are close to a :class:`~sklearn.cluster.DBSCAN` with + similar settings and ``eps``, only if ``eps`` is close to ``max_eps``. + + Parameters + ---------- + reachability : ndarray of shape (n_samples,) + Reachability distances calculated by OPTICS (``reachability_``). + + core_distances : ndarray of shape (n_samples,) + Distances at which points become core (``core_distances_``). + + ordering : ndarray of shape (n_samples,) + OPTICS ordered point indices (``ordering_``). + + eps : float + DBSCAN ``eps`` parameter. Must be set to < ``max_eps``. Results + will be close to DBSCAN algorithm if ``eps`` and ``max_eps`` are close + to one another. + + Returns + ------- + labels_ : array of shape (n_samples,) + The estimated labels. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.cluster import cluster_optics_dbscan, compute_optics_graph + >>> X = np.array([[1, 2], [2, 5], [3, 6], + ... [8, 7], [8, 8], [7, 3]]) + >>> ordering, core_distances, reachability, predecessor = compute_optics_graph( + ... X, + ... min_samples=2, + ... max_eps=np.inf, + ... metric="minkowski", + ... p=2, + ... metric_params=None, + ... algorithm="auto", + ... leaf_size=30, + ... n_jobs=None, + ... ) + >>> eps = 4.5 + >>> labels = cluster_optics_dbscan( + ... reachability=reachability, + ... core_distances=core_distances, + ... ordering=ordering, + ... eps=eps, + ... ) + >>> labels + array([0, 0, 0, 1, 1, 1]) + """ + n_samples = len(core_distances) + labels = np.zeros(n_samples, dtype=int) + + far_reach = reachability > eps + near_core = core_distances <= eps + labels[ordering] = np.cumsum(far_reach[ordering] & near_core[ordering]) - 1 + labels[far_reach & ~near_core] = -1 + return labels + + +@validate_params( + { + "reachability": [np.ndarray], + "predecessor": [np.ndarray], + "ordering": [np.ndarray], + "min_samples": [ + Interval(Integral, 2, None, closed="left"), + Interval(RealNotInt, 0, 1, closed="both"), + ], + "min_cluster_size": [ + Interval(Integral, 2, None, closed="left"), + Interval(RealNotInt, 0, 1, closed="both"), + None, + ], + "xi": [Interval(Real, 0, 1, closed="both")], + "predecessor_correction": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def cluster_optics_xi( + *, + reachability, + predecessor, + ordering, + min_samples, + min_cluster_size=None, + xi=0.05, + predecessor_correction=True, +): + """Automatically extract clusters according to the Xi-steep method. + + Parameters + ---------- + reachability : ndarray of shape (n_samples,) + Reachability distances calculated by OPTICS (`reachability_`). + + predecessor : ndarray of shape (n_samples,) + Predecessors calculated by OPTICS. + + ordering : ndarray of shape (n_samples,) + OPTICS ordered point indices (`ordering_`). + + min_samples : int > 1 or float between 0 and 1 + The same as the min_samples given to OPTICS. Up and down steep regions + can't have more then ``min_samples`` consecutive non-steep points. + Expressed as an absolute number or a fraction of the number of samples + (rounded to be at least 2). + + min_cluster_size : int > 1 or float between 0 and 1, default=None + Minimum number of samples in an OPTICS cluster, expressed as an + absolute number or a fraction of the number of samples (rounded to be + at least 2). If ``None``, the value of ``min_samples`` is used instead. + + xi : float between 0 and 1, default=0.05 + Determines the minimum steepness on the reachability plot that + constitutes a cluster boundary. For example, an upwards point in the + reachability plot is defined by the ratio from one point to its + successor being at most 1-xi. + + predecessor_correction : bool, default=True + Correct clusters based on the calculated predecessors. + + Returns + ------- + labels : ndarray of shape (n_samples,) + The labels assigned to samples. Points which are not included + in any cluster are labeled as -1. + + clusters : ndarray of shape (n_clusters, 2) + The list of clusters in the form of ``[start, end]`` in each row, with + all indices inclusive. The clusters are ordered according to ``(end, + -start)`` (ascending) so that larger clusters encompassing smaller + clusters come after such nested smaller clusters. Since ``labels`` does + not reflect the hierarchy, usually ``len(clusters) > + np.unique(labels)``. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.cluster import cluster_optics_xi, compute_optics_graph + >>> X = np.array([[1, 2], [2, 5], [3, 6], + ... [8, 7], [8, 8], [7, 3]]) + >>> ordering, core_distances, reachability, predecessor = compute_optics_graph( + ... X, + ... min_samples=2, + ... max_eps=np.inf, + ... metric="minkowski", + ... p=2, + ... metric_params=None, + ... algorithm="auto", + ... leaf_size=30, + ... n_jobs=None + ... ) + >>> min_samples = 2 + >>> labels, clusters = cluster_optics_xi( + ... reachability=reachability, + ... predecessor=predecessor, + ... ordering=ordering, + ... min_samples=min_samples, + ... ) + >>> labels + array([0, 0, 0, 1, 1, 1]) + >>> clusters + array([[0, 2], + [3, 5], + [0, 5]]) + """ + n_samples = len(reachability) + _validate_size(min_samples, n_samples, "min_samples") + if min_samples <= 1: + min_samples = max(2, int(min_samples * n_samples)) + if min_cluster_size is None: + min_cluster_size = min_samples + _validate_size(min_cluster_size, n_samples, "min_cluster_size") + if min_cluster_size <= 1: + min_cluster_size = max(2, int(min_cluster_size * n_samples)) + + clusters = _xi_cluster( + reachability[ordering], + predecessor[ordering], + ordering, + xi, + min_samples, + min_cluster_size, + predecessor_correction, + ) + labels = _extract_xi_labels(ordering, clusters) + return labels, clusters + + +def _extend_region(steep_point, xward_point, start, min_samples): + """Extend the area until it's maximal. + + It's the same function for both upward and downward reagions, depending on + the given input parameters. Assuming: + + - steep_{upward/downward}: bool array indicating whether a point is a + steep {upward/downward}; + - upward/downward: bool array indicating whether a point is + upward/downward; + + To extend an upward reagion, ``steep_point=steep_upward`` and + ``xward_point=downward`` are expected, and to extend a downward region, + ``steep_point=steep_downward`` and ``xward_point=upward``. + + Parameters + ---------- + steep_point : ndarray of shape (n_samples,), dtype=bool + True if the point is steep downward (upward). + + xward_point : ndarray of shape (n_samples,), dtype=bool + True if the point is an upward (respectively downward) point. + + start : int + The start of the xward region. + + min_samples : int + The same as the min_samples given to OPTICS. Up and down steep + regions can't have more then ``min_samples`` consecutive non-steep + points. + + Returns + ------- + index : int + The current index iterating over all the samples, i.e. where we are up + to in our search. + + end : int + The end of the region, which can be behind the index. The region + includes the ``end`` index. + """ + n_samples = len(steep_point) + non_xward_points = 0 + index = start + end = start + # find a maximal area + while index < n_samples: + if steep_point[index]: + non_xward_points = 0 + end = index + elif not xward_point[index]: + # it's not a steep point, but still goes up. + non_xward_points += 1 + # region should include no more than min_samples consecutive + # non steep xward points. + if non_xward_points > min_samples: + break + else: + return end + index += 1 + return end + + +def _update_filter_sdas(sdas, mib, xi_complement, reachability_plot): + """Update steep down areas (SDAs) using the new maximum in between (mib) + value, and the given complement of xi, i.e. ``1 - xi``. + """ + if np.isinf(mib): + return [] + res = [ + sda for sda in sdas if mib <= reachability_plot[sda["start"]] * xi_complement + ] + for sda in res: + sda["mib"] = max(sda["mib"], mib) + return res + + +def _correct_predecessor(reachability_plot, predecessor_plot, ordering, s, e): + """Correct for predecessors. + + Applies Algorithm 2 of [1]_. + + Input parameters are ordered by the computer OPTICS ordering. + + .. [1] Schubert, Erich, Michael Gertz. + "Improving the Cluster Structure Extracted from OPTICS Plots." Proc. of + the Conference "Lernen, Wissen, Daten, Analysen" (LWDA) (2018): 318-329. + """ + while s < e: + if reachability_plot[s] > reachability_plot[e]: + return s, e + p_e = predecessor_plot[e] + for i in range(s, e): + if p_e == ordering[i]: + return s, e + e -= 1 + return None, None + + +def _xi_cluster( + reachability_plot, + predecessor_plot, + ordering, + xi, + min_samples, + min_cluster_size, + predecessor_correction, +): + """Automatically extract clusters according to the Xi-steep method. + + This is rouphly an implementation of Figure 19 of the OPTICS paper. + + Parameters + ---------- + reachability_plot : array-like of shape (n_samples,) + The reachability plot, i.e. reachability ordered according to + the calculated ordering, all computed by OPTICS. + + predecessor_plot : array-like of shape (n_samples,) + Predecessors ordered according to the calculated ordering. + + xi : float, between 0 and 1 + Determines the minimum steepness on the reachability plot that + constitutes a cluster boundary. For example, an upwards point in the + reachability plot is defined by the ratio from one point to its + successor being at most 1-xi. + + min_samples : int > 1 + The same as the min_samples given to OPTICS. Up and down steep regions + can't have more then ``min_samples`` consecutive non-steep points. + + min_cluster_size : int > 1 + Minimum number of samples in an OPTICS cluster. + + predecessor_correction : bool + Correct clusters based on the calculated predecessors. + + Returns + ------- + clusters : ndarray of shape (n_clusters, 2) + The list of clusters in the form of [start, end] in each row, with all + indices inclusive. The clusters are ordered in a way that larger + clusters encompassing smaller clusters come after those smaller + clusters. + """ + + # Our implementation adds an inf to the end of reachability plot + # this helps to find potential clusters at the end of the + # reachability plot even if there's no upward region at the end of it. + reachability_plot = np.hstack((reachability_plot, np.inf)) + + xi_complement = 1 - xi + sdas = [] # steep down areas, introduced in section 4.3.2 of the paper + clusters = [] + index = 0 + mib = 0.0 # maximum in between, section 4.3.2 + + # Our implementation corrects a mistake in the original + # paper, i.e., in Definition 9 steep downward point, + # r(p) * (1 - x1) <= r(p + 1) should be + # r(p) * (1 - x1) >= r(p + 1) + with np.errstate(invalid="ignore"): + ratio = reachability_plot[:-1] / reachability_plot[1:] + steep_upward = ratio <= xi_complement + steep_downward = ratio >= 1 / xi_complement + downward = ratio > 1 + upward = ratio < 1 + + # the following loop is almost exactly as Figure 19 of the paper. + # it jumps over the areas which are not either steep down or up areas + for steep_index in iter(np.flatnonzero(steep_upward | steep_downward)): + # just continue if steep_index has been a part of a discovered xward + # area. + if steep_index < index: + continue + + mib = max(mib, np.max(reachability_plot[index : steep_index + 1])) + + # steep downward areas + if steep_downward[steep_index]: + sdas = _update_filter_sdas(sdas, mib, xi_complement, reachability_plot) + D_start = steep_index + D_end = _extend_region(steep_downward, upward, D_start, min_samples) + D = {"start": D_start, "end": D_end, "mib": 0.0} + sdas.append(D) + index = D_end + 1 + mib = reachability_plot[index] + + # steep upward areas + else: + sdas = _update_filter_sdas(sdas, mib, xi_complement, reachability_plot) + U_start = steep_index + U_end = _extend_region(steep_upward, downward, U_start, min_samples) + index = U_end + 1 + mib = reachability_plot[index] + + U_clusters = [] + for D in sdas: + c_start = D["start"] + c_end = U_end + + # line (**), sc2* + if reachability_plot[c_end + 1] * xi_complement < D["mib"]: + continue + + # Definition 11: criterion 4 + D_max = reachability_plot[D["start"]] + if D_max * xi_complement >= reachability_plot[c_end + 1]: + # Find the first index from the left side which is almost + # at the same level as the end of the detected cluster. + while ( + reachability_plot[c_start + 1] > reachability_plot[c_end + 1] + and c_start < D["end"] + ): + c_start += 1 + elif reachability_plot[c_end + 1] * xi_complement >= D_max: + # Find the first index from the right side which is almost + # at the same level as the beginning of the detected + # cluster. + # Our implementation corrects a mistake in the original + # paper, i.e., in Definition 11 4c, r(x) < r(sD) should be + # r(x) > r(sD). + while reachability_plot[c_end - 1] > D_max and c_end > U_start: + c_end -= 1 + + # predecessor correction + if predecessor_correction: + c_start, c_end = _correct_predecessor( + reachability_plot, predecessor_plot, ordering, c_start, c_end + ) + if c_start is None: + continue + + # Definition 11: criterion 3.a + if c_end - c_start + 1 < min_cluster_size: + continue + + # Definition 11: criterion 1 + if c_start > D["end"]: + continue + + # Definition 11: criterion 2 + if c_end < U_start: + continue + + U_clusters.append((c_start, c_end)) + + # add smaller clusters first. + U_clusters.reverse() + clusters.extend(U_clusters) + + return np.array(clusters) + + +def _extract_xi_labels(ordering, clusters): + """Extracts the labels from the clusters returned by `_xi_cluster`. + We rely on the fact that clusters are stored + with the smaller clusters coming before the larger ones. + + Parameters + ---------- + ordering : array-like of shape (n_samples,) + The ordering of points calculated by OPTICS + + clusters : array-like of shape (n_clusters, 2) + List of clusters i.e. (start, end) tuples, + as returned by `_xi_cluster`. + + Returns + ------- + labels : ndarray of shape (n_samples,) + """ + + labels = np.full(len(ordering), -1, dtype=int) + label = 0 + for c in clusters: + if not np.any(labels[c[0] : (c[1] + 1)] != -1): + labels[c[0] : (c[1] + 1)] = label + label += 1 + labels[ordering] = labels.copy() + return labels diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_spectral.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..00d23437504e5ad019e49583972f244d85a5dae6 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/_spectral.py @@ -0,0 +1,805 @@ +"""Algorithms for spectral clustering""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from numbers import Integral, Real + +import numpy as np +from scipy.linalg import LinAlgError, qr, svd +from scipy.sparse import csc_matrix + +from ..base import BaseEstimator, ClusterMixin, _fit_context +from ..manifold._spectral_embedding import _spectral_embedding +from ..metrics.pairwise import KERNEL_PARAMS, pairwise_kernels +from ..neighbors import NearestNeighbors, kneighbors_graph +from ..utils import as_float_array, check_random_state +from ..utils._param_validation import Interval, StrOptions, validate_params +from ..utils.validation import validate_data +from ._kmeans import k_means + + +def cluster_qr(vectors): + """Find the discrete partition closest to the eigenvector embedding. + + This implementation was proposed in [1]_. + + .. versionadded:: 1.1 + + Parameters + ---------- + vectors : array-like, shape: (n_samples, n_clusters) + The embedding space of the samples. + + Returns + ------- + labels : array of integers, shape: n_samples + The cluster labels of vectors. + + References + ---------- + .. [1] :doi:`Simple, direct, and efficient multi-way spectral clustering, 2019 + Anil Damle, Victor Minden, Lexing Ying + <10.1093/imaiai/iay008>` + + """ + + k = vectors.shape[1] + _, _, piv = qr(vectors.T, pivoting=True) + ut, _, v = svd(vectors[piv[:k], :].T) + vectors = abs(np.dot(vectors, np.dot(ut, v.conj()))) + return vectors.argmax(axis=1) + + +def discretize( + vectors, *, copy=True, max_svd_restarts=30, n_iter_max=20, random_state=None +): + """Search for a partition matrix which is closest to the eigenvector embedding. + + This implementation was proposed in [1]_. + + Parameters + ---------- + vectors : array-like of shape (n_samples, n_clusters) + The embedding space of the samples. + + copy : bool, default=True + Whether to copy vectors, or perform in-place normalization. + + max_svd_restarts : int, default=30 + Maximum number of attempts to restart SVD if convergence fails + + n_iter_max : int, default=30 + Maximum number of iterations to attempt in rotation and partition + matrix search if machine precision convergence is not reached + + random_state : int, RandomState instance, default=None + Determines random number generation for rotation matrix initialization. + Use an int to make the randomness deterministic. + See :term:`Glossary `. + + Returns + ------- + labels : array of integers, shape: n_samples + The labels of the clusters. + + References + ---------- + + .. [1] `Multiclass spectral clustering, 2003 + Stella X. Yu, Jianbo Shi + `_ + + Notes + ----- + + The eigenvector embedding is used to iteratively search for the + closest discrete partition. First, the eigenvector embedding is + normalized to the space of partition matrices. An optimal discrete + partition matrix closest to this normalized embedding multiplied by + an initial rotation is calculated. Fixing this discrete partition + matrix, an optimal rotation matrix is calculated. These two + calculations are performed until convergence. The discrete partition + matrix is returned as the clustering solution. Used in spectral + clustering, this method tends to be faster and more robust to random + initialization than k-means. + + """ + + random_state = check_random_state(random_state) + + vectors = as_float_array(vectors, copy=copy) + + eps = np.finfo(float).eps + n_samples, n_components = vectors.shape + + # Normalize the eigenvectors to an equal length of a vector of ones. + # Reorient the eigenvectors to point in the negative direction with respect + # to the first element. This may have to do with constraining the + # eigenvectors to lie in a specific quadrant to make the discretization + # search easier. + norm_ones = np.sqrt(n_samples) + for i in range(vectors.shape[1]): + vectors[:, i] = (vectors[:, i] / np.linalg.norm(vectors[:, i])) * norm_ones + if vectors[0, i] != 0: + vectors[:, i] = -1 * vectors[:, i] * np.sign(vectors[0, i]) + + # Normalize the rows of the eigenvectors. Samples should lie on the unit + # hypersphere centered at the origin. This transforms the samples in the + # embedding space to the space of partition matrices. + vectors = vectors / np.sqrt((vectors**2).sum(axis=1))[:, np.newaxis] + + svd_restarts = 0 + has_converged = False + + # If there is an exception we try to randomize and rerun SVD again + # do this max_svd_restarts times. + while (svd_restarts < max_svd_restarts) and not has_converged: + # Initialize first column of rotation matrix with a row of the + # eigenvectors + rotation = np.zeros((n_components, n_components)) + rotation[:, 0] = vectors[random_state.randint(n_samples), :].T + + # To initialize the rest of the rotation matrix, find the rows + # of the eigenvectors that are as orthogonal to each other as + # possible + c = np.zeros(n_samples) + for j in range(1, n_components): + # Accumulate c to ensure row is as orthogonal as possible to + # previous picks as well as current one + c += np.abs(np.dot(vectors, rotation[:, j - 1])) + rotation[:, j] = vectors[c.argmin(), :].T + + last_objective_value = 0.0 + n_iter = 0 + + while not has_converged: + n_iter += 1 + + t_discrete = np.dot(vectors, rotation) + + labels = t_discrete.argmax(axis=1) + vectors_discrete = csc_matrix( + (np.ones(len(labels)), (np.arange(0, n_samples), labels)), + shape=(n_samples, n_components), + ) + + t_svd = vectors_discrete.T @ vectors + + try: + U, S, Vh = np.linalg.svd(t_svd) + except LinAlgError: + svd_restarts += 1 + print("SVD did not converge, randomizing and trying again") + break + + ncut_value = 2.0 * (n_samples - S.sum()) + if (abs(ncut_value - last_objective_value) < eps) or (n_iter > n_iter_max): + has_converged = True + else: + # otherwise calculate rotation and continue + last_objective_value = ncut_value + rotation = np.dot(Vh.T, U.T) + + if not has_converged: + raise LinAlgError("SVD did not converge") + return labels + + +@validate_params( + {"affinity": ["array-like", "sparse matrix"]}, + prefer_skip_nested_validation=False, +) +def spectral_clustering( + affinity, + *, + n_clusters=8, + n_components=None, + eigen_solver=None, + random_state=None, + n_init=10, + eigen_tol="auto", + assign_labels="kmeans", + verbose=False, +): + """Apply clustering to a projection of the normalized Laplacian. + + In practice Spectral Clustering is very useful when the structure of + the individual clusters is highly non-convex or more generally when + a measure of the center and spread of the cluster is not a suitable + description of the complete cluster. For instance, when clusters are + nested circles on the 2D plane. + + If affinity is the adjacency matrix of a graph, this method can be + used to find normalized graph cuts [1]_, [2]_. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + affinity : {array-like, sparse matrix} of shape (n_samples, n_samples) + The affinity matrix describing the relationship of the samples to + embed. **Must be symmetric**. + + Possible examples: + - adjacency matrix of a graph, + - heat kernel of the pairwise distance matrix of the samples, + - symmetric k-nearest neighbours connectivity matrix of the samples. + + n_clusters : int, default=None + Number of clusters to extract. + + n_components : int, default=n_clusters + Number of eigenvectors to use for the spectral embedding. + + eigen_solver : {None, 'arpack', 'lobpcg', or 'amg'} + The eigenvalue decomposition method. If None then ``'arpack'`` is used. + See [4]_ for more details regarding ``'lobpcg'``. + Eigensolver ``'amg'`` runs ``'lobpcg'`` with optional + Algebraic MultiGrid preconditioning and requires pyamg to be installed. + It can be faster on very large sparse problems [6]_ and [7]_. + + random_state : int, RandomState instance, default=None + A pseudo random number generator used for the initialization + of the lobpcg eigenvectors decomposition when `eigen_solver == + 'amg'`, and for the K-Means initialization. Use an int to make + the results deterministic across calls (See + :term:`Glossary `). + + .. note:: + When using `eigen_solver == 'amg'`, + it is necessary to also fix the global numpy seed with + `np.random.seed(int)` to get deterministic results. See + https://github.com/pyamg/pyamg/issues/139 for further + information. + + n_init : int, default=10 + Number of time the k-means algorithm will be run with different + centroid seeds. The final results will be the best output of n_init + consecutive runs in terms of inertia. Only used if + ``assign_labels='kmeans'``. + + eigen_tol : float, default="auto" + Stopping criterion for eigendecomposition of the Laplacian matrix. + If `eigen_tol="auto"` then the passed tolerance will depend on the + `eigen_solver`: + + - If `eigen_solver="arpack"`, then `eigen_tol=0.0`; + - If `eigen_solver="lobpcg"` or `eigen_solver="amg"`, then + `eigen_tol=None` which configures the underlying `lobpcg` solver to + automatically resolve the value according to their heuristics. See, + :func:`scipy.sparse.linalg.lobpcg` for details. + + Note that when using `eigen_solver="lobpcg"` or `eigen_solver="amg"` + values of `tol<1e-5` may lead to convergence issues and should be + avoided. + + .. versionadded:: 1.2 + Added 'auto' option. + + assign_labels : {'kmeans', 'discretize', 'cluster_qr'}, default='kmeans' + The strategy to use to assign labels in the embedding + space. There are three ways to assign labels after the Laplacian + embedding. k-means can be applied and is a popular choice. But it can + also be sensitive to initialization. Discretization is another + approach which is less sensitive to random initialization [3]_. + The cluster_qr method [5]_ directly extracts clusters from eigenvectors + in spectral clustering. In contrast to k-means and discretization, cluster_qr + has no tuning parameters and is not an iterative method, yet may outperform + k-means and discretization in terms of both quality and speed. For a detailed + comparison of clustering strategies, refer to the following example: + :ref:`sphx_glr_auto_examples_cluster_plot_coin_segmentation.py`. + + .. versionchanged:: 1.1 + Added new labeling method 'cluster_qr'. + + verbose : bool, default=False + Verbosity mode. + + .. versionadded:: 0.24 + + Returns + ------- + labels : array of integers, shape: n_samples + The labels of the clusters. + + Notes + ----- + The graph should contain only one connected component, elsewhere + the results make little sense. + + This algorithm solves the normalized cut for `k=2`: it is a + normalized spectral clustering. + + References + ---------- + + .. [1] :doi:`Normalized cuts and image segmentation, 2000 + Jianbo Shi, Jitendra Malik + <10.1109/34.868688>` + + .. [2] :doi:`A Tutorial on Spectral Clustering, 2007 + Ulrike von Luxburg + <10.1007/s11222-007-9033-z>` + + .. [3] `Multiclass spectral clustering, 2003 + Stella X. Yu, Jianbo Shi + `_ + + .. [4] :doi:`Toward the Optimal Preconditioned Eigensolver: + Locally Optimal Block Preconditioned Conjugate Gradient Method, 2001 + A. V. Knyazev + SIAM Journal on Scientific Computing 23, no. 2, pp. 517-541. + <10.1137/S1064827500366124>` + + .. [5] :doi:`Simple, direct, and efficient multi-way spectral clustering, 2019 + Anil Damle, Victor Minden, Lexing Ying + <10.1093/imaiai/iay008>` + + .. [6] :doi:`Multiscale Spectral Image Segmentation Multiscale preconditioning + for computing eigenvalues of graph Laplacians in image segmentation, 2006 + Andrew Knyazev + <10.13140/RG.2.2.35280.02565>` + + .. [7] :doi:`Preconditioned spectral clustering for stochastic block partition + streaming graph challenge (Preliminary version at arXiv.) + David Zhuzhunashvili, Andrew Knyazev + <10.1109/HPEC.2017.8091045>` + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics.pairwise import pairwise_kernels + >>> from sklearn.cluster import spectral_clustering + >>> X = np.array([[1, 1], [2, 1], [1, 0], + ... [4, 7], [3, 5], [3, 6]]) + >>> affinity = pairwise_kernels(X, metric='rbf') + >>> spectral_clustering( + ... affinity=affinity, n_clusters=2, assign_labels="discretize", random_state=0 + ... ) + array([1, 1, 1, 0, 0, 0]) + """ + + clusterer = SpectralClustering( + n_clusters=n_clusters, + n_components=n_components, + eigen_solver=eigen_solver, + random_state=random_state, + n_init=n_init, + affinity="precomputed", + eigen_tol=eigen_tol, + assign_labels=assign_labels, + verbose=verbose, + ).fit(affinity) + + return clusterer.labels_ + + +class SpectralClustering(ClusterMixin, BaseEstimator): + """Apply clustering to a projection of the normalized Laplacian. + + In practice Spectral Clustering is very useful when the structure of + the individual clusters is highly non-convex, or more generally when + a measure of the center and spread of the cluster is not a suitable + description of the complete cluster, such as when clusters are + nested circles on the 2D plane. + + If the affinity matrix is the adjacency matrix of a graph, this method + can be used to find normalized graph cuts [1]_, [2]_. + + When calling ``fit``, an affinity matrix is constructed using either + a kernel function such the Gaussian (aka RBF) kernel with Euclidean + distance ``d(X, X)``:: + + np.exp(-gamma * d(X,X) ** 2) + + or a k-nearest neighbors connectivity matrix. + + Alternatively, a user-provided affinity matrix can be specified by + setting ``affinity='precomputed'``. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_clusters : int, default=8 + The dimension of the projection subspace. + + eigen_solver : {'arpack', 'lobpcg', 'amg'}, default=None + The eigenvalue decomposition strategy to use. AMG requires pyamg + to be installed. It can be faster on very large, sparse problems, + but may also lead to instabilities. If None, then ``'arpack'`` is + used. See [4]_ for more details regarding `'lobpcg'`. + + n_components : int, default=None + Number of eigenvectors to use for the spectral embedding. If None, + defaults to `n_clusters`. + + random_state : int, RandomState instance, default=None + A pseudo random number generator used for the initialization + of the lobpcg eigenvectors decomposition when `eigen_solver == + 'amg'`, and for the K-Means initialization. Use an int to make + the results deterministic across calls (See + :term:`Glossary `). + + .. note:: + When using `eigen_solver == 'amg'`, + it is necessary to also fix the global numpy seed with + `np.random.seed(int)` to get deterministic results. See + https://github.com/pyamg/pyamg/issues/139 for further + information. + + n_init : int, default=10 + Number of time the k-means algorithm will be run with different + centroid seeds. The final results will be the best output of n_init + consecutive runs in terms of inertia. Only used if + ``assign_labels='kmeans'``. + + gamma : float, default=1.0 + Kernel coefficient for rbf, poly, sigmoid, laplacian and chi2 kernels. + Ignored for ``affinity='nearest_neighbors'``, ``affinity='precomputed'`` + or ``affinity='precomputed_nearest_neighbors'``. + + affinity : str or callable, default='rbf' + How to construct the affinity matrix. + - 'nearest_neighbors': construct the affinity matrix by computing a + graph of nearest neighbors. + - 'rbf': construct the affinity matrix using a radial basis function + (RBF) kernel. + - 'precomputed': interpret ``X`` as a precomputed affinity matrix, + where larger values indicate greater similarity between instances. + - 'precomputed_nearest_neighbors': interpret ``X`` as a sparse graph + of precomputed distances, and construct a binary affinity matrix + from the ``n_neighbors`` nearest neighbors of each instance. + - one of the kernels supported by + :func:`~sklearn.metrics.pairwise.pairwise_kernels`. + + Only kernels that produce similarity scores (non-negative values that + increase with similarity) should be used. This property is not checked + by the clustering algorithm. + + n_neighbors : int, default=10 + Number of neighbors to use when constructing the affinity matrix using + the nearest neighbors method. Ignored for ``affinity='rbf'``. + + eigen_tol : float, default="auto" + Stopping criterion for eigen decomposition of the Laplacian matrix. + If `eigen_tol="auto"` then the passed tolerance will depend on the + `eigen_solver`: + + - If `eigen_solver="arpack"`, then `eigen_tol=0.0`; + - If `eigen_solver="lobpcg"` or `eigen_solver="amg"`, then + `eigen_tol=None` which configures the underlying `lobpcg` solver to + automatically resolve the value according to their heuristics. See, + :func:`scipy.sparse.linalg.lobpcg` for details. + + Note that when using `eigen_solver="lobpcg"` or `eigen_solver="amg"` + values of `tol<1e-5` may lead to convergence issues and should be + avoided. + + .. versionadded:: 1.2 + Added 'auto' option. + + assign_labels : {'kmeans', 'discretize', 'cluster_qr'}, default='kmeans' + The strategy for assigning labels in the embedding space. There are two + ways to assign labels after the Laplacian embedding. k-means is a + popular choice, but it can be sensitive to initialization. + Discretization is another approach which is less sensitive to random + initialization [3]_. + The cluster_qr method [5]_ directly extract clusters from eigenvectors + in spectral clustering. In contrast to k-means and discretization, cluster_qr + has no tuning parameters and runs no iterations, yet may outperform + k-means and discretization in terms of both quality and speed. + + .. versionchanged:: 1.1 + Added new labeling method 'cluster_qr'. + + degree : float, default=3 + Degree of the polynomial kernel. Ignored by other kernels. + + coef0 : float, default=1 + Zero coefficient for polynomial and sigmoid kernels. + Ignored by other kernels. + + kernel_params : dict of str to any, default=None + Parameters (keyword arguments) and values for kernel passed as + callable object. Ignored by other kernels. + + n_jobs : int, default=None + The number of parallel jobs to run when `affinity='nearest_neighbors'` + or `affinity='precomputed_nearest_neighbors'`. The neighbors search + will be done in parallel. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + verbose : bool, default=False + Verbosity mode. + + .. versionadded:: 0.24 + + Attributes + ---------- + affinity_matrix_ : array-like of shape (n_samples, n_samples) + Affinity matrix used for clustering. Available only after calling + ``fit``. + + labels_ : ndarray of shape (n_samples,) + Labels of each point + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + sklearn.cluster.KMeans : K-Means clustering. + sklearn.cluster.DBSCAN : Density-Based Spatial Clustering of + Applications with Noise. + + Notes + ----- + A distance matrix for which 0 indicates identical elements and high values + indicate very dissimilar elements can be transformed into an affinity / + similarity matrix that is well-suited for the algorithm by + applying the Gaussian (aka RBF, heat) kernel:: + + np.exp(- dist_matrix ** 2 / (2. * delta ** 2)) + + where ``delta`` is a free parameter representing the width of the Gaussian + kernel. + + An alternative is to take a symmetric version of the k-nearest neighbors + connectivity matrix of the points. + + If the pyamg package is installed, it is used: this greatly + speeds up computation. + + References + ---------- + .. [1] :doi:`Normalized cuts and image segmentation, 2000 + Jianbo Shi, Jitendra Malik + <10.1109/34.868688>` + + .. [2] :doi:`A Tutorial on Spectral Clustering, 2007 + Ulrike von Luxburg + <10.1007/s11222-007-9033-z>` + + .. [3] `Multiclass spectral clustering, 2003 + Stella X. Yu, Jianbo Shi + `_ + + .. [4] :doi:`Toward the Optimal Preconditioned Eigensolver: + Locally Optimal Block Preconditioned Conjugate Gradient Method, 2001 + A. V. Knyazev + SIAM Journal on Scientific Computing 23, no. 2, pp. 517-541. + <10.1137/S1064827500366124>` + + .. [5] :doi:`Simple, direct, and efficient multi-way spectral clustering, 2019 + Anil Damle, Victor Minden, Lexing Ying + <10.1093/imaiai/iay008>` + + Examples + -------- + >>> from sklearn.cluster import SpectralClustering + >>> import numpy as np + >>> X = np.array([[1, 1], [2, 1], [1, 0], + ... [4, 7], [3, 5], [3, 6]]) + >>> clustering = SpectralClustering(n_clusters=2, + ... assign_labels='discretize', + ... random_state=0).fit(X) + >>> clustering.labels_ + array([1, 1, 1, 0, 0, 0]) + >>> clustering + SpectralClustering(assign_labels='discretize', n_clusters=2, + random_state=0) + + For a comparison of Spectral clustering with other clustering algorithms, see + :ref:`sphx_glr_auto_examples_cluster_plot_cluster_comparison.py` + """ + + _parameter_constraints: dict = { + "n_clusters": [Interval(Integral, 1, None, closed="left")], + "eigen_solver": [StrOptions({"arpack", "lobpcg", "amg"}), None], + "n_components": [Interval(Integral, 1, None, closed="left"), None], + "random_state": ["random_state"], + "n_init": [Interval(Integral, 1, None, closed="left")], + "gamma": [Interval(Real, 0, None, closed="left")], + "affinity": [ + callable, + StrOptions( + set(KERNEL_PARAMS) + | {"nearest_neighbors", "precomputed", "precomputed_nearest_neighbors"} + ), + ], + "n_neighbors": [Interval(Integral, 1, None, closed="left")], + "eigen_tol": [ + Interval(Real, 0.0, None, closed="left"), + StrOptions({"auto"}), + ], + "assign_labels": [StrOptions({"kmeans", "discretize", "cluster_qr"})], + "degree": [Interval(Real, 0, None, closed="left")], + "coef0": [Interval(Real, None, None, closed="neither")], + "kernel_params": [dict, None], + "n_jobs": [Integral, None], + "verbose": ["verbose"], + } + + def __init__( + self, + n_clusters=8, + *, + eigen_solver=None, + n_components=None, + random_state=None, + n_init=10, + gamma=1.0, + affinity="rbf", + n_neighbors=10, + eigen_tol="auto", + assign_labels="kmeans", + degree=3, + coef0=1, + kernel_params=None, + n_jobs=None, + verbose=False, + ): + self.n_clusters = n_clusters + self.eigen_solver = eigen_solver + self.n_components = n_components + self.random_state = random_state + self.n_init = n_init + self.gamma = gamma + self.affinity = affinity + self.n_neighbors = n_neighbors + self.eigen_tol = eigen_tol + self.assign_labels = assign_labels + self.degree = degree + self.coef0 = coef0 + self.kernel_params = kernel_params + self.n_jobs = n_jobs + self.verbose = verbose + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Perform spectral clustering from features, or affinity matrix. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) or \ + (n_samples, n_samples) + Training instances to cluster, similarities / affinities between + instances if ``affinity='precomputed'``, or distances between + instances if ``affinity='precomputed_nearest_neighbors``. If a + sparse matrix is provided in a format other than ``csr_matrix``, + ``csc_matrix``, or ``coo_matrix``, it will be converted into a + sparse ``csr_matrix``. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self : object + A fitted instance of the estimator. + """ + X = validate_data( + self, + X, + accept_sparse=["csr", "csc", "coo"], + dtype=np.float64, + ensure_min_samples=2, + ) + allow_squared = self.affinity in [ + "precomputed", + "precomputed_nearest_neighbors", + ] + if X.shape[0] == X.shape[1] and not allow_squared: + warnings.warn( + "The spectral clustering API has changed. ``fit``" + "now constructs an affinity matrix from data. To use" + " a custom affinity matrix, " + "set ``affinity=precomputed``." + ) + + if self.affinity == "nearest_neighbors": + connectivity = kneighbors_graph( + X, n_neighbors=self.n_neighbors, include_self=True, n_jobs=self.n_jobs + ) + self.affinity_matrix_ = 0.5 * (connectivity + connectivity.T) + elif self.affinity == "precomputed_nearest_neighbors": + estimator = NearestNeighbors( + n_neighbors=self.n_neighbors, n_jobs=self.n_jobs, metric="precomputed" + ).fit(X) + connectivity = estimator.kneighbors_graph(X=X, mode="connectivity") + self.affinity_matrix_ = 0.5 * (connectivity + connectivity.T) + elif self.affinity == "precomputed": + self.affinity_matrix_ = X + else: + params = self.kernel_params + if params is None: + params = {} + if not callable(self.affinity): + params["gamma"] = self.gamma + params["degree"] = self.degree + params["coef0"] = self.coef0 + self.affinity_matrix_ = pairwise_kernels( + X, metric=self.affinity, filter_params=True, **params + ) + + random_state = check_random_state(self.random_state) + n_components = ( + self.n_clusters if self.n_components is None else self.n_components + ) + # We now obtain the real valued solution matrix to the + # relaxed Ncut problem, solving the eigenvalue problem + # L_sym x = lambda x and recovering u = D^-1/2 x. + # The first eigenvector is constant only for fully connected graphs + # and should be kept for spectral clustering (drop_first = False) + # See spectral_embedding documentation. + maps = _spectral_embedding( + self.affinity_matrix_, + n_components=n_components, + eigen_solver=self.eigen_solver, + random_state=random_state, + eigen_tol=self.eigen_tol, + drop_first=False, + ) + if self.verbose: + print(f"Computing label assignment using {self.assign_labels}") + + if self.assign_labels == "kmeans": + _, self.labels_, _ = k_means( + maps, + self.n_clusters, + random_state=random_state, + n_init=self.n_init, + verbose=self.verbose, + ) + elif self.assign_labels == "cluster_qr": + self.labels_ = cluster_qr(maps) + else: + self.labels_ = discretize(maps, random_state=random_state) + + return self + + def fit_predict(self, X, y=None): + """Perform spectral clustering on `X` and return cluster labels. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) or \ + (n_samples, n_samples) + Training instances to cluster, similarities / affinities between + instances if ``affinity='precomputed'``, or distances between + instances if ``affinity='precomputed_nearest_neighbors``. If a + sparse matrix is provided in a format other than ``csr_matrix``, + ``csc_matrix``, or ``coo_matrix``, it will be converted into a + sparse ``csr_matrix``. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Cluster labels. + """ + return super().fit_predict(X, y) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + tags.input_tags.pairwise = self.affinity in [ + "precomputed", + "precomputed_nearest_neighbors", + ] + return tags diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/meson.build b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/meson.build new file mode 100644 index 0000000000000000000000000000000000000000..6c11619f3ca555c58ed43b1d579548d75cf6aea4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/meson.build @@ -0,0 +1,26 @@ +cluster_extension_metadata = { + '_dbscan_inner': + {'sources': [cython_gen_cpp.process('_dbscan_inner.pyx')]}, + '_hierarchical_fast': + {'sources': [cython_gen_cpp.process('_hierarchical_fast.pyx'), metrics_cython_tree]}, + '_k_means_common': + {'sources': [cython_gen.process('_k_means_common.pyx')], 'dependencies': [openmp_dep]}, + '_k_means_lloyd': + {'sources': [cython_gen.process('_k_means_lloyd.pyx')], 'dependencies': [openmp_dep]}, + '_k_means_elkan': + {'sources': [cython_gen.process('_k_means_elkan.pyx')], 'dependencies': [openmp_dep]}, + '_k_means_minibatch': + {'sources': [cython_gen.process('_k_means_minibatch.pyx')], 'dependencies': [openmp_dep]}, +} + +foreach ext_name, ext_dict : cluster_extension_metadata + py.extension_module( + ext_name, + [ext_dict.get('sources'), utils_cython_tree], + dependencies: [np_dep] + ext_dict.get('dependencies', []), + subdir: 'sklearn/cluster', + install: true + ) +endforeach + +subdir('_hdbscan') diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/common.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/common.py new file mode 100644 index 0000000000000000000000000000000000000000..b1fe047fe230af1c3fbb2ec0b72f3ef20e5aa3aa --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/common.py @@ -0,0 +1,37 @@ +""" +Common utilities for testing clustering. + +""" + +import numpy as np + +############################################################################### +# Generate sample data + + +def generate_clustered_data( + seed=0, n_clusters=3, n_features=2, n_samples_per_cluster=20, std=0.4 +): + prng = np.random.RandomState(seed) + + # the data is voluntary shifted away from zero to check clustering + # algorithm robustness with regards to non centered data + means = ( + np.array( + [ + [1, 1, 1, 0], + [-1, -1, 0, 1], + [1, -1, 1, 1], + [-1, 1, 1, 0], + ] + ) + + 10 + ) + + X = np.empty((0, n_features)) + for i in range(n_clusters): + X = np.r_[ + X, + means[i][:n_features] + std * prng.randn(n_samples_per_cluster, n_features), + ] + return X diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_affinity_propagation.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_affinity_propagation.py new file mode 100644 index 0000000000000000000000000000000000000000..c3138e59111ed849988dd0e6d3433a4bb251e2a1 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_affinity_propagation.py @@ -0,0 +1,321 @@ +""" +Testing for Clustering methods + +""" + +import warnings + +import numpy as np +import pytest + +from sklearn.cluster import AffinityPropagation, affinity_propagation +from sklearn.cluster._affinity_propagation import _equal_similarities_and_preferences +from sklearn.datasets import make_blobs +from sklearn.exceptions import ConvergenceWarning, NotFittedError +from sklearn.metrics import euclidean_distances +from sklearn.utils._testing import assert_allclose, assert_array_equal +from sklearn.utils.fixes import CSR_CONTAINERS + +n_clusters = 3 +centers = np.array([[1, 1], [-1, -1], [1, -1]]) + 10 +X, _ = make_blobs( + n_samples=60, + n_features=2, + centers=centers, + cluster_std=0.4, + shuffle=True, + random_state=0, +) + +# TODO: AffinityPropagation must preserve dtype for its fitted attributes +# and test must be created accordingly to this new behavior. +# For more details, see: https://github.com/scikit-learn/scikit-learn/issues/11000 + + +def test_affinity_propagation(global_random_seed, global_dtype): + """Test consistency of the affinity propagations.""" + S = -euclidean_distances(X.astype(global_dtype, copy=False), squared=True) + preference = np.median(S) * 10 + cluster_centers_indices, labels = affinity_propagation( + S, preference=preference, random_state=global_random_seed + ) + + n_clusters_ = len(cluster_centers_indices) + + assert n_clusters == n_clusters_ + + +def test_affinity_propagation_precomputed(): + """Check equality of precomputed affinity matrix to internally computed affinity + matrix. + """ + S = -euclidean_distances(X, squared=True) + preference = np.median(S) * 10 + af = AffinityPropagation( + preference=preference, affinity="precomputed", random_state=28 + ) + labels_precomputed = af.fit(S).labels_ + + af = AffinityPropagation(preference=preference, verbose=True, random_state=37) + labels = af.fit(X).labels_ + + assert_array_equal(labels, labels_precomputed) + + cluster_centers_indices = af.cluster_centers_indices_ + + n_clusters_ = len(cluster_centers_indices) + assert np.unique(labels).size == n_clusters_ + assert n_clusters == n_clusters_ + + +def test_affinity_propagation_no_copy(): + """Check behaviour of not copying the input data.""" + S = -euclidean_distances(X, squared=True) + S_original = S.copy() + preference = np.median(S) * 10 + assert not np.allclose(S.diagonal(), preference) + + # with copy=True S should not be modified + affinity_propagation(S, preference=preference, copy=True, random_state=0) + assert_allclose(S, S_original) + assert not np.allclose(S.diagonal(), preference) + assert_allclose(S.diagonal(), np.zeros(S.shape[0])) + + # with copy=False S will be modified inplace + affinity_propagation(S, preference=preference, copy=False, random_state=0) + assert_allclose(S.diagonal(), preference) + + # test that copy=True and copy=False lead to the same result + S = S_original.copy() + af = AffinityPropagation(preference=preference, verbose=True, random_state=0) + + labels = af.fit(X).labels_ + _, labels_no_copy = affinity_propagation( + S, preference=preference, copy=False, random_state=74 + ) + assert_array_equal(labels, labels_no_copy) + + +def test_affinity_propagation_affinity_shape(): + """Check the shape of the affinity matrix when using `affinity_propagation.""" + S = -euclidean_distances(X, squared=True) + err_msg = "The matrix of similarities must be a square array" + with pytest.raises(ValueError, match=err_msg): + affinity_propagation(S[:, :-1]) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_affinity_propagation_precomputed_with_sparse_input(csr_container): + err_msg = "Sparse data was passed for X, but dense data is required" + with pytest.raises(TypeError, match=err_msg): + AffinityPropagation(affinity="precomputed").fit(csr_container((3, 3))) + + +def test_affinity_propagation_predict(global_random_seed, global_dtype): + # Test AffinityPropagation.predict + af = AffinityPropagation(affinity="euclidean", random_state=global_random_seed) + X_ = X.astype(global_dtype, copy=False) + labels = af.fit_predict(X_) + labels2 = af.predict(X_) + assert_array_equal(labels, labels2) + + +def test_affinity_propagation_predict_error(): + # Test exception in AffinityPropagation.predict + # Not fitted. + af = AffinityPropagation(affinity="euclidean") + with pytest.raises(NotFittedError): + af.predict(X) + + # Predict not supported when affinity="precomputed". + S = np.dot(X, X.T) + af = AffinityPropagation(affinity="precomputed", random_state=57) + af.fit(S) + with pytest.raises(ValueError, match="expecting 60 features as input"): + af.predict(X) + + +def test_affinity_propagation_fit_non_convergence(global_dtype): + # In case of non-convergence of affinity_propagation(), the cluster + # centers should be an empty array and training samples should be labelled + # as noise (-1) + X = np.array([[0, 0], [1, 1], [-2, -2]], dtype=global_dtype) + + # Force non-convergence by allowing only a single iteration + af = AffinityPropagation(preference=-10, max_iter=1, random_state=82) + + with pytest.warns(ConvergenceWarning): + af.fit(X) + assert_allclose(np.empty((0, 2)), af.cluster_centers_) + assert_array_equal(np.array([-1, -1, -1]), af.labels_) + + +def test_affinity_propagation_equal_mutual_similarities(global_dtype): + X = np.array([[-1, 1], [1, -1]], dtype=global_dtype) + S = -euclidean_distances(X, squared=True) + + # setting preference > similarity + with pytest.warns(UserWarning, match="mutually equal"): + cluster_center_indices, labels = affinity_propagation(S, preference=0) + + # expect every sample to become an exemplar + assert_array_equal([0, 1], cluster_center_indices) + assert_array_equal([0, 1], labels) + + # setting preference < similarity + with pytest.warns(UserWarning, match="mutually equal"): + cluster_center_indices, labels = affinity_propagation(S, preference=-10) + + # expect one cluster, with arbitrary (first) sample as exemplar + assert_array_equal([0], cluster_center_indices) + assert_array_equal([0, 0], labels) + + # setting different preferences + with warnings.catch_warnings(): + warnings.simplefilter("error", UserWarning) + cluster_center_indices, labels = affinity_propagation( + S, preference=[-20, -10], random_state=37 + ) + + # expect one cluster, with highest-preference sample as exemplar + assert_array_equal([1], cluster_center_indices) + assert_array_equal([0, 0], labels) + + +def test_affinity_propagation_predict_non_convergence(global_dtype): + # In case of non-convergence of affinity_propagation(), the cluster + # centers should be an empty array + X = np.array([[0, 0], [1, 1], [-2, -2]], dtype=global_dtype) + + # Force non-convergence by allowing only a single iteration + with pytest.warns(ConvergenceWarning): + af = AffinityPropagation(preference=-10, max_iter=1, random_state=75).fit(X) + + # At prediction time, consider new samples as noise since there are no + # clusters + to_predict = np.array([[2, 2], [3, 3], [4, 4]]) + with pytest.warns(ConvergenceWarning): + y = af.predict(to_predict) + assert_array_equal(np.array([-1, -1, -1]), y) + + +def test_affinity_propagation_non_convergence_regressiontest(global_dtype): + X = np.array( + [[1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0], [0, 0, 1, 0, 0, 1]], dtype=global_dtype + ) + af = AffinityPropagation(affinity="euclidean", max_iter=2, random_state=34) + msg = ( + "Affinity propagation did not converge, this model may return degenerate" + " cluster centers and labels." + ) + with pytest.warns(ConvergenceWarning, match=msg): + af.fit(X) + + assert_array_equal(np.array([0, 0, 0]), af.labels_) + + +def test_equal_similarities_and_preferences(global_dtype): + # Unequal distances + X = np.array([[0, 0], [1, 1], [-2, -2]], dtype=global_dtype) + S = -euclidean_distances(X, squared=True) + + assert not _equal_similarities_and_preferences(S, np.array(0)) + assert not _equal_similarities_and_preferences(S, np.array([0, 0])) + assert not _equal_similarities_and_preferences(S, np.array([0, 1])) + + # Equal distances + X = np.array([[0, 0], [1, 1]], dtype=global_dtype) + S = -euclidean_distances(X, squared=True) + + # Different preferences + assert not _equal_similarities_and_preferences(S, np.array([0, 1])) + + # Same preferences + assert _equal_similarities_and_preferences(S, np.array([0, 0])) + assert _equal_similarities_and_preferences(S, np.array(0)) + + +def test_affinity_propagation_random_state(): + """Check that different random states lead to different initialisations + by looking at the center locations after two iterations. + """ + centers = [[1, 1], [-1, -1], [1, -1]] + X, labels_true = make_blobs( + n_samples=300, centers=centers, cluster_std=0.5, random_state=0 + ) + # random_state = 0 + ap = AffinityPropagation(convergence_iter=1, max_iter=2, random_state=0) + ap.fit(X) + centers0 = ap.cluster_centers_ + + # random_state = 76 + ap = AffinityPropagation(convergence_iter=1, max_iter=2, random_state=76) + ap.fit(X) + centers76 = ap.cluster_centers_ + # check that the centers have not yet converged to the same solution + assert np.mean((centers0 - centers76) ** 2) > 1 + + +@pytest.mark.parametrize("container", CSR_CONTAINERS + [np.array]) +def test_affinity_propagation_convergence_warning_dense_sparse(container, global_dtype): + """ + Check that having sparse or dense `centers` format should not + influence the convergence. + Non-regression test for gh-13334. + """ + centers = container(np.zeros((1, 10))) + rng = np.random.RandomState(42) + X = rng.rand(40, 10).astype(global_dtype, copy=False) + y = (4 * rng.rand(40)).astype(int) + ap = AffinityPropagation(random_state=46) + ap.fit(X, y) + ap.cluster_centers_ = centers + with warnings.catch_warnings(): + warnings.simplefilter("error", ConvergenceWarning) + assert_array_equal(ap.predict(X), np.zeros(X.shape[0], dtype=int)) + + +# FIXME; this test is broken with different random states, needs to be revisited +def test_correct_clusters(global_dtype): + # Test to fix incorrect clusters due to dtype change + # (non-regression test for issue #10832) + X = np.array( + [[1, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 1]], dtype=global_dtype + ) + afp = AffinityPropagation(preference=1, affinity="precomputed", random_state=0).fit( + X + ) + expected = np.array([0, 1, 1, 2]) + assert_array_equal(afp.labels_, expected) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_sparse_input_for_predict(csr_container): + # Test to make sure sparse inputs are accepted for predict + # (non-regression test for issue #20049) + af = AffinityPropagation(affinity="euclidean", random_state=42) + af.fit(X) + labels = af.predict(csr_container((2, 2))) + assert_array_equal(labels, (2, 2)) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_sparse_input_for_fit_predict(csr_container): + # Test to make sure sparse inputs are accepted for fit_predict + # (non-regression test for issue #20049) + af = AffinityPropagation(affinity="euclidean", random_state=42) + rng = np.random.RandomState(42) + X = csr_container(rng.randint(0, 2, size=(5, 5))) + labels = af.fit_predict(X) + assert_array_equal(labels, (0, 1, 1, 2, 3)) + + +def test_affinity_propagation_equal_points(): + """Make sure we do not assign multiple clusters to equal points. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/pull/20043 + """ + X = np.zeros((8, 1)) + af = AffinityPropagation(affinity="euclidean", damping=0.5, random_state=42).fit(X) + assert np.all(af.labels_ == 0) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_bicluster.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_bicluster.py new file mode 100644 index 0000000000000000000000000000000000000000..ebc845a7bf262c60cf9f039e5ce021d841bdf4d4 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_bicluster.py @@ -0,0 +1,264 @@ +"""Testing for Spectral Biclustering methods""" + +import numpy as np +import pytest +from scipy.sparse import issparse + +from sklearn.base import BaseEstimator, BiclusterMixin +from sklearn.cluster import SpectralBiclustering, SpectralCoclustering +from sklearn.cluster._bicluster import ( + _bistochastic_normalize, + _log_normalize, + _scale_normalize, +) +from sklearn.datasets import make_biclusters, make_checkerboard +from sklearn.metrics import consensus_score, v_measure_score +from sklearn.model_selection import ParameterGrid +from sklearn.utils._testing import ( + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, +) +from sklearn.utils.fixes import CSR_CONTAINERS + + +class MockBiclustering(BiclusterMixin, BaseEstimator): + # Mock object for testing get_submatrix. + def __init__(self): + pass + + def get_indices(self, i): + # Overridden to reproduce old get_submatrix test. + return ( + np.where([True, True, False, False, True])[0], + np.where([False, False, True, True])[0], + ) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_get_submatrix(csr_container): + data = np.arange(20).reshape(5, 4) + model = MockBiclustering() + + for X in (data, csr_container(data), data.tolist()): + submatrix = model.get_submatrix(0, X) + if issparse(submatrix): + submatrix = submatrix.toarray() + assert_array_equal(submatrix, [[2, 3], [6, 7], [18, 19]]) + submatrix[:] = -1 + if issparse(X): + X = X.toarray() + assert np.all(X != -1) + + +def _test_shape_indices(model): + # Test get_shape and get_indices on fitted model. + for i in range(model.n_clusters): + m, n = model.get_shape(i) + i_ind, j_ind = model.get_indices(i) + assert len(i_ind) == m + assert len(j_ind) == n + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_spectral_coclustering(global_random_seed, csr_container): + # Test Dhillon's Spectral CoClustering on a simple problem. + param_grid = { + "svd_method": ["randomized", "arpack"], + "n_svd_vecs": [None, 20], + "mini_batch": [False, True], + "init": ["k-means++"], + "n_init": [10], + } + S, rows, cols = make_biclusters( + (30, 30), 3, noise=0.1, random_state=global_random_seed + ) + S -= S.min() # needs to be nonnegative before making it sparse + S = np.where(S < 1, 0, S) # threshold some values + for mat in (S, csr_container(S)): + for kwargs in ParameterGrid(param_grid): + model = SpectralCoclustering( + n_clusters=3, random_state=global_random_seed, **kwargs + ) + model.fit(mat) + + assert model.rows_.shape == (3, 30) + assert_array_equal(model.rows_.sum(axis=0), np.ones(30)) + assert_array_equal(model.columns_.sum(axis=0), np.ones(30)) + assert consensus_score(model.biclusters_, (rows, cols)) == 1 + + _test_shape_indices(model) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_spectral_biclustering(global_random_seed, csr_container): + # Test Kluger methods on a checkerboard dataset. + S, rows, cols = make_checkerboard( + (30, 30), 3, noise=0.5, random_state=global_random_seed + ) + + non_default_params = { + "method": ["scale", "log"], + "svd_method": ["arpack"], + "n_svd_vecs": [20], + "mini_batch": [True], + } + + for mat in (S, csr_container(S)): + for param_name, param_values in non_default_params.items(): + for param_value in param_values: + model = SpectralBiclustering( + n_clusters=3, + n_init=3, + init="k-means++", + random_state=global_random_seed, + ) + model.set_params(**dict([(param_name, param_value)])) + + if issparse(mat) and model.get_params().get("method") == "log": + # cannot take log of sparse matrix + with pytest.raises(ValueError): + model.fit(mat) + continue + else: + model.fit(mat) + + assert model.rows_.shape == (9, 30) + assert model.columns_.shape == (9, 30) + assert_array_equal(model.rows_.sum(axis=0), np.repeat(3, 30)) + assert_array_equal(model.columns_.sum(axis=0), np.repeat(3, 30)) + assert consensus_score(model.biclusters_, (rows, cols)) == 1 + + _test_shape_indices(model) + + +def _do_scale_test(scaled): + """Check that rows sum to one constant, and columns to another.""" + row_sum = scaled.sum(axis=1) + col_sum = scaled.sum(axis=0) + if issparse(scaled): + row_sum = np.asarray(row_sum).squeeze() + col_sum = np.asarray(col_sum).squeeze() + assert_array_almost_equal(row_sum, np.tile(row_sum.mean(), 100), decimal=1) + assert_array_almost_equal(col_sum, np.tile(col_sum.mean(), 100), decimal=1) + + +def _do_bistochastic_test(scaled): + """Check that rows and columns sum to the same constant.""" + _do_scale_test(scaled) + assert_almost_equal(scaled.sum(axis=0).mean(), scaled.sum(axis=1).mean(), decimal=1) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_scale_normalize(global_random_seed, csr_container): + generator = np.random.RandomState(global_random_seed) + X = generator.rand(100, 100) + for mat in (X, csr_container(X)): + scaled, _, _ = _scale_normalize(mat) + _do_scale_test(scaled) + if issparse(mat): + assert issparse(scaled) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_bistochastic_normalize(global_random_seed, csr_container): + generator = np.random.RandomState(global_random_seed) + X = generator.rand(100, 100) + for mat in (X, csr_container(X)): + scaled = _bistochastic_normalize(mat) + _do_bistochastic_test(scaled) + if issparse(mat): + assert issparse(scaled) + + +def test_log_normalize(global_random_seed): + # adding any constant to a log-scaled matrix should make it + # bistochastic + generator = np.random.RandomState(global_random_seed) + mat = generator.rand(100, 100) + scaled = _log_normalize(mat) + 1 + _do_bistochastic_test(scaled) + + +def test_fit_best_piecewise(global_random_seed): + model = SpectralBiclustering(random_state=global_random_seed) + vectors = np.array([[0, 0, 0, 1, 1, 1], [2, 2, 2, 3, 3, 3], [0, 1, 2, 3, 4, 5]]) + best = model._fit_best_piecewise(vectors, n_best=2, n_clusters=2) + assert_array_equal(best, vectors[:2]) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_project_and_cluster(global_random_seed, csr_container): + model = SpectralBiclustering(random_state=global_random_seed) + data = np.array([[1, 1, 1], [1, 1, 1], [3, 6, 3], [3, 6, 3]]) + vectors = np.array([[1, 0], [0, 1], [0, 0]]) + for mat in (data, csr_container(data)): + labels = model._project_and_cluster(mat, vectors, n_clusters=2) + assert_almost_equal(v_measure_score(labels, [0, 0, 1, 1]), 1.0) + + +def test_perfect_checkerboard(global_random_seed): + # XXX Previously failed on build bot (not reproducible) + model = SpectralBiclustering( + 3, svd_method="arpack", random_state=global_random_seed + ) + + S, rows, cols = make_checkerboard( + (30, 30), 3, noise=0, random_state=global_random_seed + ) + model.fit(S) + assert consensus_score(model.biclusters_, (rows, cols)) == 1 + + S, rows, cols = make_checkerboard( + (40, 30), 3, noise=0, random_state=global_random_seed + ) + model.fit(S) + assert consensus_score(model.biclusters_, (rows, cols)) == 1 + + S, rows, cols = make_checkerboard( + (30, 40), 3, noise=0, random_state=global_random_seed + ) + model.fit(S) + assert consensus_score(model.biclusters_, (rows, cols)) == 1 + + +@pytest.mark.parametrize( + "params, type_err, err_msg", + [ + ( + {"n_clusters": 6}, + ValueError, + "n_clusters should be <= n_samples=5", + ), + ( + {"n_clusters": (3, 3, 3)}, + ValueError, + "Incorrect parameter n_clusters", + ), + ( + {"n_clusters": (3, 6)}, + ValueError, + "Incorrect parameter n_clusters", + ), + ( + {"n_components": 3, "n_best": 4}, + ValueError, + "n_best=4 must be <= n_components=3", + ), + ], +) +def test_spectralbiclustering_parameter_validation(params, type_err, err_msg): + """Check parameters validation in `SpectralBiClustering`""" + data = np.arange(25).reshape((5, 5)) + model = SpectralBiclustering(**params) + with pytest.raises(type_err, match=err_msg): + model.fit(data) + + +@pytest.mark.parametrize("est", (SpectralBiclustering(), SpectralCoclustering())) +def test_n_features_in_(est): + X, _, _ = make_biclusters((3, 3), 3, random_state=0) + + assert not hasattr(est, "n_features_in_") + est.fit(X) + assert est.n_features_in_ == 3 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_birch.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_birch.py new file mode 100644 index 0000000000000000000000000000000000000000..bc87934adaecdb507126097e2de945c677587bee --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_birch.py @@ -0,0 +1,250 @@ +""" +Tests for the birch clustering algorithm. +""" + +import numpy as np +import pytest + +from sklearn.cluster import AgglomerativeClustering, Birch +from sklearn.cluster.tests.common import generate_clustered_data +from sklearn.datasets import make_blobs +from sklearn.exceptions import ConvergenceWarning +from sklearn.metrics import pairwise_distances_argmin, v_measure_score +from sklearn.utils._testing import assert_allclose, assert_array_equal +from sklearn.utils.fixes import CSR_CONTAINERS + + +def test_n_samples_leaves_roots(global_random_seed, global_dtype): + # Sanity check for the number of samples in leaves and roots + X, y = make_blobs(n_samples=10, random_state=global_random_seed) + X = X.astype(global_dtype, copy=False) + brc = Birch() + brc.fit(X) + n_samples_root = sum([sc.n_samples_ for sc in brc.root_.subclusters_]) + n_samples_leaves = sum( + [sc.n_samples_ for leaf in brc._get_leaves() for sc in leaf.subclusters_] + ) + assert n_samples_leaves == X.shape[0] + assert n_samples_root == X.shape[0] + + +def test_partial_fit(global_random_seed, global_dtype): + # Test that fit is equivalent to calling partial_fit multiple times + X, y = make_blobs(n_samples=100, random_state=global_random_seed) + X = X.astype(global_dtype, copy=False) + brc = Birch(n_clusters=3) + brc.fit(X) + brc_partial = Birch(n_clusters=None) + brc_partial.partial_fit(X[:50]) + brc_partial.partial_fit(X[50:]) + assert_allclose(brc_partial.subcluster_centers_, brc.subcluster_centers_) + + # Test that same global labels are obtained after calling partial_fit + # with None + brc_partial.set_params(n_clusters=3) + brc_partial.partial_fit(None) + assert_array_equal(brc_partial.subcluster_labels_, brc.subcluster_labels_) + + +def test_birch_predict(global_random_seed, global_dtype): + # Test the predict method predicts the nearest centroid. + rng = np.random.RandomState(global_random_seed) + X = generate_clustered_data(n_clusters=3, n_features=3, n_samples_per_cluster=10) + X = X.astype(global_dtype, copy=False) + + # n_samples * n_samples_per_cluster + shuffle_indices = np.arange(30) + rng.shuffle(shuffle_indices) + X_shuffle = X[shuffle_indices, :] + brc = Birch(n_clusters=4, threshold=1.0) + brc.fit(X_shuffle) + + # Birch must preserve inputs' dtype + assert brc.subcluster_centers_.dtype == global_dtype + + assert_array_equal(brc.labels_, brc.predict(X_shuffle)) + centroids = brc.subcluster_centers_ + nearest_centroid = brc.subcluster_labels_[ + pairwise_distances_argmin(X_shuffle, centroids) + ] + assert_allclose(v_measure_score(nearest_centroid, brc.labels_), 1.0) + + +def test_n_clusters(global_random_seed, global_dtype): + # Test that n_clusters param works properly + X, y = make_blobs(n_samples=100, centers=10, random_state=global_random_seed) + X = X.astype(global_dtype, copy=False) + brc1 = Birch(n_clusters=10) + brc1.fit(X) + assert len(brc1.subcluster_centers_) > 10 + assert len(np.unique(brc1.labels_)) == 10 + + # Test that n_clusters = Agglomerative Clustering gives + # the same results. + gc = AgglomerativeClustering(n_clusters=10) + brc2 = Birch(n_clusters=gc) + brc2.fit(X) + assert_array_equal(brc1.subcluster_labels_, brc2.subcluster_labels_) + assert_array_equal(brc1.labels_, brc2.labels_) + + # Test that a small number of clusters raises a warning. + brc4 = Birch(threshold=10000.0) + with pytest.warns(ConvergenceWarning): + brc4.fit(X) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_sparse_X(global_random_seed, global_dtype, csr_container): + # Test that sparse and dense data give same results + X, y = make_blobs(n_samples=100, centers=10, random_state=global_random_seed) + X = X.astype(global_dtype, copy=False) + brc = Birch(n_clusters=10) + brc.fit(X) + + csr = csr_container(X) + brc_sparse = Birch(n_clusters=10) + brc_sparse.fit(csr) + + # Birch must preserve inputs' dtype + assert brc_sparse.subcluster_centers_.dtype == global_dtype + + assert_array_equal(brc.labels_, brc_sparse.labels_) + assert_allclose(brc.subcluster_centers_, brc_sparse.subcluster_centers_) + + +def test_partial_fit_second_call_error_checks(): + # second partial fit calls will error when n_features is not consistent + # with the first call + X, y = make_blobs(n_samples=100) + brc = Birch(n_clusters=3) + brc.partial_fit(X, y) + + msg = "X has 1 features, but Birch is expecting 2 features" + with pytest.raises(ValueError, match=msg): + brc.partial_fit(X[:, [0]], y) + + +def check_branching_factor(node, branching_factor): + subclusters = node.subclusters_ + assert branching_factor >= len(subclusters) + for cluster in subclusters: + if cluster.child_: + check_branching_factor(cluster.child_, branching_factor) + + +def test_branching_factor(global_random_seed, global_dtype): + # Test that nodes have at max branching_factor number of subclusters + X, y = make_blobs(random_state=global_random_seed) + X = X.astype(global_dtype, copy=False) + branching_factor = 9 + + # Purposefully set a low threshold to maximize the subclusters. + brc = Birch(n_clusters=None, branching_factor=branching_factor, threshold=0.01) + brc.fit(X) + check_branching_factor(brc.root_, branching_factor) + brc = Birch(n_clusters=3, branching_factor=branching_factor, threshold=0.01) + brc.fit(X) + check_branching_factor(brc.root_, branching_factor) + + +def check_threshold(birch_instance, threshold): + """Use the leaf linked list for traversal""" + current_leaf = birch_instance.dummy_leaf_.next_leaf_ + while current_leaf: + subclusters = current_leaf.subclusters_ + for sc in subclusters: + assert threshold >= sc.radius + current_leaf = current_leaf.next_leaf_ + + +def test_threshold(global_random_seed, global_dtype): + # Test that the leaf subclusters have a threshold lesser than radius + X, y = make_blobs(n_samples=80, centers=4, random_state=global_random_seed) + X = X.astype(global_dtype, copy=False) + brc = Birch(threshold=0.5, n_clusters=None) + brc.fit(X) + check_threshold(brc, 0.5) + + brc = Birch(threshold=5.0, n_clusters=None) + brc.fit(X) + check_threshold(brc, 5.0) + + +def test_birch_n_clusters_long_int(): + # Check that birch supports n_clusters with np.int64 dtype, for instance + # coming from np.arange. #16484 + X, _ = make_blobs(random_state=0) + n_clusters = np.int64(5) + Birch(n_clusters=n_clusters).fit(X) + + +def test_feature_names_out(): + """Check `get_feature_names_out` for `Birch`.""" + X, _ = make_blobs(n_samples=80, n_features=4, random_state=0) + brc = Birch(n_clusters=4) + brc.fit(X) + n_clusters = brc.subcluster_centers_.shape[0] + + names_out = brc.get_feature_names_out() + assert_array_equal([f"birch{i}" for i in range(n_clusters)], names_out) + + +def test_transform_match_across_dtypes(global_random_seed): + X, _ = make_blobs(n_samples=80, n_features=4, random_state=global_random_seed) + brc = Birch(n_clusters=4, threshold=1.1) + Y_64 = brc.fit_transform(X) + Y_32 = brc.fit_transform(X.astype(np.float32)) + + assert_allclose(Y_64, Y_32, atol=1e-6) + + +def test_subcluster_dtype(global_dtype): + X = make_blobs(n_samples=80, n_features=4, random_state=0)[0].astype( + global_dtype, copy=False + ) + brc = Birch(n_clusters=4) + assert brc.fit(X).subcluster_centers_.dtype == global_dtype + + +def test_both_subclusters_updated(): + """Check that both subclusters are updated when a node a split, even when there are + duplicated data points. Non-regression test for #23269. + """ + + X = np.array( + [ + [-2.6192791, -1.5053215], + [-2.9993038, -1.6863596], + [-2.3724914, -1.3438171], + [-2.336792, -1.3417323], + [-2.4089134, -1.3290224], + [-2.3724914, -1.3438171], + [-3.364009, -1.8846745], + [-2.3724914, -1.3438171], + [-2.617677, -1.5003285], + [-2.2960556, -1.3260119], + [-2.3724914, -1.3438171], + [-2.5459878, -1.4533926], + [-2.25979, -1.3003055], + [-2.4089134, -1.3290224], + [-2.3724914, -1.3438171], + [-2.4089134, -1.3290224], + [-2.5459878, -1.4533926], + [-2.3724914, -1.3438171], + [-2.9720619, -1.7058647], + [-2.336792, -1.3417323], + [-2.3724914, -1.3438171], + ], + dtype=np.float32, + ) + + # no error + Birch(branching_factor=5, threshold=1e-5, n_clusters=None).fit(X) + + +# TODO(1.8): Remove +def test_birch_copy_deprecated(): + X, _ = make_blobs(n_samples=80, n_features=4, random_state=0) + brc = Birch(n_clusters=4, copy=True) + with pytest.warns(FutureWarning, match="`copy` was deprecated"): + brc.fit(X) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_bisect_k_means.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_bisect_k_means.py new file mode 100644 index 0000000000000000000000000000000000000000..799ddbc086ce0a14397fe5cb4aef607903c01228 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_bisect_k_means.py @@ -0,0 +1,158 @@ +import numpy as np +import pytest + +from sklearn.cluster import BisectingKMeans +from sklearn.metrics import v_measure_score +from sklearn.utils._testing import assert_allclose, assert_array_equal +from sklearn.utils.fixes import CSR_CONTAINERS + + +@pytest.mark.parametrize("bisecting_strategy", ["biggest_inertia", "largest_cluster"]) +@pytest.mark.parametrize("init", ["k-means++", "random"]) +def test_three_clusters(bisecting_strategy, init): + """Tries to perform bisect k-means for three clusters to check + if splitting data is performed correctly. + """ + X = np.array( + [[1, 1], [10, 1], [3, 1], [10, 0], [2, 1], [10, 2], [10, 8], [10, 9], [10, 10]] + ) + bisect_means = BisectingKMeans( + n_clusters=3, + random_state=0, + bisecting_strategy=bisecting_strategy, + init=init, + ) + bisect_means.fit(X) + + expected_centers = [[2, 1], [10, 1], [10, 9]] + expected_labels = [0, 1, 0, 1, 0, 1, 2, 2, 2] + + assert_allclose( + sorted(expected_centers), sorted(bisect_means.cluster_centers_.tolist()) + ) + assert_allclose(v_measure_score(expected_labels, bisect_means.labels_), 1.0) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_sparse(csr_container): + """Test Bisecting K-Means with sparse data. + + Checks if labels and centers are the same between dense and sparse. + """ + + rng = np.random.RandomState(0) + + X = rng.rand(20, 2) + X[X < 0.8] = 0 + X_csr = csr_container(X) + + bisect_means = BisectingKMeans(n_clusters=3, random_state=0) + + bisect_means.fit(X_csr) + sparse_centers = bisect_means.cluster_centers_ + + bisect_means.fit(X) + normal_centers = bisect_means.cluster_centers_ + + # Check if results is the same for dense and sparse data + assert_allclose(normal_centers, sparse_centers, atol=1e-8) + + +@pytest.mark.parametrize("n_clusters", [4, 5]) +def test_n_clusters(n_clusters): + """Test if resulting labels are in range [0, n_clusters - 1].""" + + rng = np.random.RandomState(0) + X = rng.rand(10, 2) + + bisect_means = BisectingKMeans(n_clusters=n_clusters, random_state=0) + bisect_means.fit(X) + + assert_array_equal(np.unique(bisect_means.labels_), np.arange(n_clusters)) + + +def test_one_cluster(): + """Test single cluster.""" + + X = np.array([[1, 2], [10, 2], [10, 8]]) + + bisect_means = BisectingKMeans(n_clusters=1, random_state=0).fit(X) + + # All labels from fit or predict should be equal 0 + assert all(bisect_means.labels_ == 0) + assert all(bisect_means.predict(X) == 0) + + assert_allclose(bisect_means.cluster_centers_, X.mean(axis=0).reshape(1, -1)) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS + [None]) +def test_fit_predict(csr_container): + """Check if labels from fit(X) method are same as from fit(X).predict(X).""" + rng = np.random.RandomState(0) + + X = rng.rand(10, 2) + + if csr_container is not None: + X[X < 0.8] = 0 + X = csr_container(X) + + bisect_means = BisectingKMeans(n_clusters=3, random_state=0) + bisect_means.fit(X) + + assert_array_equal(bisect_means.labels_, bisect_means.predict(X)) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS + [None]) +def test_dtype_preserved(csr_container, global_dtype): + """Check that centers dtype is the same as input data dtype.""" + rng = np.random.RandomState(0) + X = rng.rand(10, 2).astype(global_dtype, copy=False) + + if csr_container is not None: + X[X < 0.8] = 0 + X = csr_container(X) + + km = BisectingKMeans(n_clusters=3, random_state=0) + km.fit(X) + + assert km.cluster_centers_.dtype == global_dtype + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS + [None]) +def test_float32_float64_equivalence(csr_container): + """Check that the results are the same between float32 and float64.""" + rng = np.random.RandomState(0) + X = rng.rand(10, 2) + + if csr_container is not None: + X[X < 0.8] = 0 + X = csr_container(X) + + km64 = BisectingKMeans(n_clusters=3, random_state=0).fit(X) + km32 = BisectingKMeans(n_clusters=3, random_state=0).fit(X.astype(np.float32)) + + assert_allclose(km32.cluster_centers_, km64.cluster_centers_) + assert_array_equal(km32.labels_, km64.labels_) + + +@pytest.mark.parametrize("algorithm", ("lloyd", "elkan")) +def test_no_crash_on_empty_bisections(algorithm): + # Non-regression test for: + # https://github.com/scikit-learn/scikit-learn/issues/27081 + rng = np.random.RandomState(0) + X_train = rng.rand(3000, 10) + bkm = BisectingKMeans(n_clusters=10, algorithm=algorithm).fit(X_train) + + # predict on scaled data to trigger pathologic case + # where the inner mask leads to empty bisections. + X_test = 50 * rng.rand(100, 10) + labels = bkm.predict(X_test) # should not crash with idiv by 0 + assert np.isin(np.unique(labels), np.arange(10)).all() + + +def test_one_feature(): + # Check that no error is raised when there is only one feature + # Non-regression test for: + # https://github.com/scikit-learn/scikit-learn/issues/27236 + X = np.random.normal(size=(128, 1)) + BisectingKMeans(bisecting_strategy="biggest_inertia", random_state=0).fit(X) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_dbscan.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_dbscan.py new file mode 100644 index 0000000000000000000000000000000000000000..556f89312d2fc87ab962ab84551f4941ec8b359b --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_dbscan.py @@ -0,0 +1,434 @@ +""" +Tests for DBSCAN clustering algorithm +""" + +import pickle +import warnings + +import numpy as np +import pytest +from scipy.spatial import distance + +from sklearn.cluster import DBSCAN, dbscan +from sklearn.cluster.tests.common import generate_clustered_data +from sklearn.metrics.pairwise import pairwise_distances +from sklearn.neighbors import NearestNeighbors +from sklearn.utils._testing import assert_array_equal +from sklearn.utils.fixes import CSR_CONTAINERS, LIL_CONTAINERS + +n_clusters = 3 +X = generate_clustered_data(n_clusters=n_clusters) + + +def test_dbscan_similarity(): + # Tests the DBSCAN algorithm with a similarity array. + # Parameters chosen specifically for this task. + eps = 0.15 + min_samples = 10 + # Compute similarities + D = distance.squareform(distance.pdist(X)) + D /= np.max(D) + # Compute DBSCAN + core_samples, labels = dbscan( + D, metric="precomputed", eps=eps, min_samples=min_samples + ) + # number of clusters, ignoring noise if present + n_clusters_1 = len(set(labels)) - (1 if -1 in labels else 0) + + assert n_clusters_1 == n_clusters + + db = DBSCAN(metric="precomputed", eps=eps, min_samples=min_samples) + labels = db.fit(D).labels_ + + n_clusters_2 = len(set(labels)) - int(-1 in labels) + assert n_clusters_2 == n_clusters + + +def test_dbscan_feature(): + # Tests the DBSCAN algorithm with a feature vector array. + # Parameters chosen specifically for this task. + # Different eps to other test, because distance is not normalised. + eps = 0.8 + min_samples = 10 + metric = "euclidean" + # Compute DBSCAN + # parameters chosen for task + core_samples, labels = dbscan(X, metric=metric, eps=eps, min_samples=min_samples) + + # number of clusters, ignoring noise if present + n_clusters_1 = len(set(labels)) - int(-1 in labels) + assert n_clusters_1 == n_clusters + + db = DBSCAN(metric=metric, eps=eps, min_samples=min_samples) + labels = db.fit(X).labels_ + + n_clusters_2 = len(set(labels)) - int(-1 in labels) + assert n_clusters_2 == n_clusters + + +@pytest.mark.parametrize("lil_container", LIL_CONTAINERS) +def test_dbscan_sparse(lil_container): + core_sparse, labels_sparse = dbscan(lil_container(X), eps=0.8, min_samples=10) + core_dense, labels_dense = dbscan(X, eps=0.8, min_samples=10) + assert_array_equal(core_dense, core_sparse) + assert_array_equal(labels_dense, labels_sparse) + + +@pytest.mark.parametrize("include_self", [False, True]) +def test_dbscan_sparse_precomputed(include_self): + D = pairwise_distances(X) + nn = NearestNeighbors(radius=0.9).fit(X) + X_ = X if include_self else None + D_sparse = nn.radius_neighbors_graph(X=X_, mode="distance") + # Ensure it is sparse not merely on diagonals: + assert D_sparse.nnz < D.shape[0] * (D.shape[0] - 1) + core_sparse, labels_sparse = dbscan( + D_sparse, eps=0.8, min_samples=10, metric="precomputed" + ) + core_dense, labels_dense = dbscan(D, eps=0.8, min_samples=10, metric="precomputed") + assert_array_equal(core_dense, core_sparse) + assert_array_equal(labels_dense, labels_sparse) + + +def test_dbscan_sparse_precomputed_different_eps(): + # test that precomputed neighbors graph is filtered if computed with + # a radius larger than DBSCAN's eps. + lower_eps = 0.2 + nn = NearestNeighbors(radius=lower_eps).fit(X) + D_sparse = nn.radius_neighbors_graph(X, mode="distance") + dbscan_lower = dbscan(D_sparse, eps=lower_eps, metric="precomputed") + + higher_eps = lower_eps + 0.7 + nn = NearestNeighbors(radius=higher_eps).fit(X) + D_sparse = nn.radius_neighbors_graph(X, mode="distance") + dbscan_higher = dbscan(D_sparse, eps=lower_eps, metric="precomputed") + + assert_array_equal(dbscan_lower[0], dbscan_higher[0]) + assert_array_equal(dbscan_lower[1], dbscan_higher[1]) + + +@pytest.mark.parametrize("metric", ["precomputed", "minkowski"]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS + [None]) +def test_dbscan_input_not_modified(metric, csr_container): + # test that the input is not modified by dbscan + X = np.random.RandomState(0).rand(10, 10) + X = csr_container(X) if csr_container is not None else X + X_copy = X.copy() + dbscan(X, metric=metric) + + if csr_container is not None: + assert_array_equal(X.toarray(), X_copy.toarray()) + else: + assert_array_equal(X, X_copy) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_dbscan_input_not_modified_precomputed_sparse_nodiag(csr_container): + """Check that we don't modify in-place the pre-computed sparse matrix. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/27508 + """ + X = np.random.RandomState(0).rand(10, 10) + # Add zeros on the diagonal that will be implicit when creating + # the sparse matrix. If `X` is modified in-place, the zeros from + # the diagonal will be made explicit. + np.fill_diagonal(X, 0) + X = csr_container(X) + assert all(row != col for row, col in zip(*X.nonzero())) + X_copy = X.copy() + dbscan(X, metric="precomputed") + # Make sure that we did not modify `X` in-place even by creating + # explicit 0s values. + assert X.nnz == X_copy.nnz + assert_array_equal(X.toarray(), X_copy.toarray()) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_dbscan_no_core_samples(csr_container): + rng = np.random.RandomState(0) + X = rng.rand(40, 10) + X[X < 0.8] = 0 + + for X_ in [X, csr_container(X)]: + db = DBSCAN(min_samples=6).fit(X_) + assert_array_equal(db.components_, np.empty((0, X_.shape[1]))) + assert_array_equal(db.labels_, -1) + assert db.core_sample_indices_.shape == (0,) + + +def test_dbscan_callable(): + # Tests the DBSCAN algorithm with a callable metric. + # Parameters chosen specifically for this task. + # Different eps to other test, because distance is not normalised. + eps = 0.8 + min_samples = 10 + # metric is the function reference, not the string key. + metric = distance.euclidean + # Compute DBSCAN + # parameters chosen for task + core_samples, labels = dbscan( + X, metric=metric, eps=eps, min_samples=min_samples, algorithm="ball_tree" + ) + + # number of clusters, ignoring noise if present + n_clusters_1 = len(set(labels)) - int(-1 in labels) + assert n_clusters_1 == n_clusters + + db = DBSCAN(metric=metric, eps=eps, min_samples=min_samples, algorithm="ball_tree") + labels = db.fit(X).labels_ + + n_clusters_2 = len(set(labels)) - int(-1 in labels) + assert n_clusters_2 == n_clusters + + +def test_dbscan_metric_params(): + # Tests that DBSCAN works with the metrics_params argument. + eps = 0.8 + min_samples = 10 + p = 1 + + # Compute DBSCAN with metric_params arg + + with warnings.catch_warnings(record=True) as warns: + db = DBSCAN( + metric="minkowski", + metric_params={"p": p}, + eps=eps, + p=None, + min_samples=min_samples, + algorithm="ball_tree", + ).fit(X) + assert not warns, warns[0].message + core_sample_1, labels_1 = db.core_sample_indices_, db.labels_ + + # Test that sample labels are the same as passing Minkowski 'p' directly + db = DBSCAN( + metric="minkowski", eps=eps, min_samples=min_samples, algorithm="ball_tree", p=p + ).fit(X) + core_sample_2, labels_2 = db.core_sample_indices_, db.labels_ + + assert_array_equal(core_sample_1, core_sample_2) + assert_array_equal(labels_1, labels_2) + + # Minkowski with p=1 should be equivalent to Manhattan distance + db = DBSCAN( + metric="manhattan", eps=eps, min_samples=min_samples, algorithm="ball_tree" + ).fit(X) + core_sample_3, labels_3 = db.core_sample_indices_, db.labels_ + + assert_array_equal(core_sample_1, core_sample_3) + assert_array_equal(labels_1, labels_3) + + with pytest.warns( + SyntaxWarning, + match=( + "Parameter p is found in metric_params. " + "The corresponding parameter from __init__ " + "is ignored." + ), + ): + # Test that checks p is ignored in favor of metric_params={'p': } + db = DBSCAN( + metric="minkowski", + metric_params={"p": p}, + eps=eps, + p=p + 1, + min_samples=min_samples, + algorithm="ball_tree", + ).fit(X) + core_sample_4, labels_4 = db.core_sample_indices_, db.labels_ + + assert_array_equal(core_sample_1, core_sample_4) + assert_array_equal(labels_1, labels_4) + + +def test_dbscan_balltree(): + # Tests the DBSCAN algorithm with balltree for neighbor calculation. + eps = 0.8 + min_samples = 10 + + D = pairwise_distances(X) + core_samples, labels = dbscan( + D, metric="precomputed", eps=eps, min_samples=min_samples + ) + + # number of clusters, ignoring noise if present + n_clusters_1 = len(set(labels)) - int(-1 in labels) + assert n_clusters_1 == n_clusters + + db = DBSCAN(p=2.0, eps=eps, min_samples=min_samples, algorithm="ball_tree") + labels = db.fit(X).labels_ + + n_clusters_2 = len(set(labels)) - int(-1 in labels) + assert n_clusters_2 == n_clusters + + db = DBSCAN(p=2.0, eps=eps, min_samples=min_samples, algorithm="kd_tree") + labels = db.fit(X).labels_ + + n_clusters_3 = len(set(labels)) - int(-1 in labels) + assert n_clusters_3 == n_clusters + + db = DBSCAN(p=1.0, eps=eps, min_samples=min_samples, algorithm="ball_tree") + labels = db.fit(X).labels_ + + n_clusters_4 = len(set(labels)) - int(-1 in labels) + assert n_clusters_4 == n_clusters + + db = DBSCAN(leaf_size=20, eps=eps, min_samples=min_samples, algorithm="ball_tree") + labels = db.fit(X).labels_ + + n_clusters_5 = len(set(labels)) - int(-1 in labels) + assert n_clusters_5 == n_clusters + + +def test_input_validation(): + # DBSCAN.fit should accept a list of lists. + X = [[1.0, 2.0], [3.0, 4.0]] + DBSCAN().fit(X) # must not raise exception + + +def test_pickle(): + obj = DBSCAN() + s = pickle.dumps(obj) + assert type(pickle.loads(s)) is obj.__class__ + + +def test_boundaries(): + # ensure min_samples is inclusive of core point + core, _ = dbscan([[0], [1]], eps=2, min_samples=2) + assert 0 in core + # ensure eps is inclusive of circumference + core, _ = dbscan([[0], [1], [1]], eps=1, min_samples=2) + assert 0 in core + core, _ = dbscan([[0], [1], [1]], eps=0.99, min_samples=2) + assert 0 not in core + + +def test_weighted_dbscan(global_random_seed): + # ensure sample_weight is validated + with pytest.raises(ValueError): + dbscan([[0], [1]], sample_weight=[2]) + with pytest.raises(ValueError): + dbscan([[0], [1]], sample_weight=[2, 3, 4]) + + # ensure sample_weight has an effect + assert_array_equal([], dbscan([[0], [1]], sample_weight=None, min_samples=6)[0]) + assert_array_equal([], dbscan([[0], [1]], sample_weight=[5, 5], min_samples=6)[0]) + assert_array_equal([0], dbscan([[0], [1]], sample_weight=[6, 5], min_samples=6)[0]) + assert_array_equal( + [0, 1], dbscan([[0], [1]], sample_weight=[6, 6], min_samples=6)[0] + ) + + # points within eps of each other: + assert_array_equal( + [0, 1], dbscan([[0], [1]], eps=1.5, sample_weight=[5, 1], min_samples=6)[0] + ) + # and effect of non-positive and non-integer sample_weight: + assert_array_equal( + [], dbscan([[0], [1]], sample_weight=[5, 0], eps=1.5, min_samples=6)[0] + ) + assert_array_equal( + [0, 1], dbscan([[0], [1]], sample_weight=[5.9, 0.1], eps=1.5, min_samples=6)[0] + ) + assert_array_equal( + [0, 1], dbscan([[0], [1]], sample_weight=[6, 0], eps=1.5, min_samples=6)[0] + ) + assert_array_equal( + [], dbscan([[0], [1]], sample_weight=[6, -1], eps=1.5, min_samples=6)[0] + ) + + # for non-negative sample_weight, cores should be identical to repetition + rng = np.random.RandomState(global_random_seed) + sample_weight = rng.randint(0, 5, X.shape[0]) + core1, label1 = dbscan(X, sample_weight=sample_weight) + assert len(label1) == len(X) + + X_repeated = np.repeat(X, sample_weight, axis=0) + core_repeated, label_repeated = dbscan(X_repeated) + core_repeated_mask = np.zeros(X_repeated.shape[0], dtype=bool) + core_repeated_mask[core_repeated] = True + core_mask = np.zeros(X.shape[0], dtype=bool) + core_mask[core1] = True + assert_array_equal(np.repeat(core_mask, sample_weight), core_repeated_mask) + + # sample_weight should work with precomputed distance matrix + D = pairwise_distances(X) + core3, label3 = dbscan(D, sample_weight=sample_weight, metric="precomputed") + assert_array_equal(core1, core3) + assert_array_equal(label1, label3) + + # sample_weight should work with estimator + est = DBSCAN().fit(X, sample_weight=sample_weight) + core4 = est.core_sample_indices_ + label4 = est.labels_ + assert_array_equal(core1, core4) + assert_array_equal(label1, label4) + + est = DBSCAN() + label5 = est.fit_predict(X, sample_weight=sample_weight) + core5 = est.core_sample_indices_ + assert_array_equal(core1, core5) + assert_array_equal(label1, label5) + assert_array_equal(label1, est.labels_) + + +@pytest.mark.parametrize("algorithm", ["brute", "kd_tree", "ball_tree"]) +def test_dbscan_core_samples_toy(algorithm): + X = [[0], [2], [3], [4], [6], [8], [10]] + n_samples = len(X) + + # Degenerate case: every sample is a core sample, either with its own + # cluster or including other close core samples. + core_samples, labels = dbscan(X, algorithm=algorithm, eps=1, min_samples=1) + assert_array_equal(core_samples, np.arange(n_samples)) + assert_array_equal(labels, [0, 1, 1, 1, 2, 3, 4]) + + # With eps=1 and min_samples=2 only the 3 samples from the denser area + # are core samples. All other points are isolated and considered noise. + core_samples, labels = dbscan(X, algorithm=algorithm, eps=1, min_samples=2) + assert_array_equal(core_samples, [1, 2, 3]) + assert_array_equal(labels, [-1, 0, 0, 0, -1, -1, -1]) + + # Only the sample in the middle of the dense area is core. Its two + # neighbors are edge samples. Remaining samples are noise. + core_samples, labels = dbscan(X, algorithm=algorithm, eps=1, min_samples=3) + assert_array_equal(core_samples, [2]) + assert_array_equal(labels, [-1, 0, 0, 0, -1, -1, -1]) + + # It's no longer possible to extract core samples with eps=1: + # everything is noise. + core_samples, labels = dbscan(X, algorithm=algorithm, eps=1, min_samples=4) + assert_array_equal(core_samples, []) + assert_array_equal(labels, np.full(n_samples, -1.0)) + + +def test_dbscan_precomputed_metric_with_degenerate_input_arrays(): + # see https://github.com/scikit-learn/scikit-learn/issues/4641 for + # more details + X = np.eye(10) + labels = DBSCAN(eps=0.5, metric="precomputed").fit(X).labels_ + assert len(set(labels)) == 1 + + X = np.zeros((10, 10)) + labels = DBSCAN(eps=0.5, metric="precomputed").fit(X).labels_ + assert len(set(labels)) == 1 + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_dbscan_precomputed_metric_with_initial_rows_zero(csr_container): + # sample matrix with initial two row all zero + ar = np.array( + [ + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.1, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.1, 0.0, 0.0], + [0.0, 0.0, 0.1, 0.1, 0.0, 0.0, 0.3], + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1], + [0.0, 0.0, 0.0, 0.0, 0.3, 0.1, 0.0], + ] + ) + matrix = csr_container(ar) + labels = DBSCAN(eps=0.2, metric="precomputed", min_samples=2).fit(matrix).labels_ + assert_array_equal(labels, [-1, -1, 0, 0, 0, 1, 1]) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_feature_agglomeration.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_feature_agglomeration.py new file mode 100644 index 0000000000000000000000000000000000000000..80aa251c358153b0771bd201067fa87f8fb6bfdc --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_feature_agglomeration.py @@ -0,0 +1,55 @@ +""" +Tests for sklearn.cluster._feature_agglomeration +""" + +import numpy as np +from numpy.testing import assert_array_equal + +from sklearn.cluster import FeatureAgglomeration +from sklearn.datasets import make_blobs +from sklearn.utils._testing import assert_array_almost_equal + + +def test_feature_agglomeration(): + n_clusters = 1 + X = np.array([0, 0, 1]).reshape(1, 3) # (n_samples, n_features) + + agglo_mean = FeatureAgglomeration(n_clusters=n_clusters, pooling_func=np.mean) + agglo_median = FeatureAgglomeration(n_clusters=n_clusters, pooling_func=np.median) + agglo_mean.fit(X) + agglo_median.fit(X) + + assert np.size(np.unique(agglo_mean.labels_)) == n_clusters + assert np.size(np.unique(agglo_median.labels_)) == n_clusters + assert np.size(agglo_mean.labels_) == X.shape[1] + assert np.size(agglo_median.labels_) == X.shape[1] + + # Test transform + Xt_mean = agglo_mean.transform(X) + Xt_median = agglo_median.transform(X) + assert Xt_mean.shape[1] == n_clusters + assert Xt_median.shape[1] == n_clusters + assert Xt_mean == np.array([1 / 3.0]) + assert Xt_median == np.array([0.0]) + + # Test inverse transform + X_full_mean = agglo_mean.inverse_transform(Xt_mean) + X_full_median = agglo_median.inverse_transform(Xt_median) + assert np.unique(X_full_mean[0]).size == n_clusters + assert np.unique(X_full_median[0]).size == n_clusters + + assert_array_almost_equal(agglo_mean.transform(X_full_mean), Xt_mean) + assert_array_almost_equal(agglo_median.transform(X_full_median), Xt_median) + + +def test_feature_agglomeration_feature_names_out(): + """Check `get_feature_names_out` for `FeatureAgglomeration`.""" + X, _ = make_blobs(n_features=6, random_state=0) + agglo = FeatureAgglomeration(n_clusters=3) + agglo.fit(X) + n_clusters = agglo.n_clusters_ + + names_out = agglo.get_feature_names_out() + assert_array_equal( + [f"featureagglomeration{i}" for i in range(n_clusters)], names_out + ) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_hdbscan.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_hdbscan.py new file mode 100644 index 0000000000000000000000000000000000000000..3b45d9d3cb7aa290e7fac62f359ac518d105579e --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_hdbscan.py @@ -0,0 +1,582 @@ +""" +Tests for HDBSCAN clustering algorithm +Based on the DBSCAN test code +""" + +import numpy as np +import pytest +from scipy import stats +from scipy.spatial import distance + +from sklearn.cluster import HDBSCAN +from sklearn.cluster._hdbscan._tree import ( + CONDENSED_dtype, + _condense_tree, + _do_labelling, +) +from sklearn.cluster._hdbscan.hdbscan import _OUTLIER_ENCODING +from sklearn.datasets import make_blobs +from sklearn.metrics import fowlkes_mallows_score +from sklearn.metrics.pairwise import _VALID_METRICS, euclidean_distances +from sklearn.neighbors import BallTree, KDTree +from sklearn.preprocessing import StandardScaler +from sklearn.utils import shuffle +from sklearn.utils._testing import assert_allclose, assert_array_equal +from sklearn.utils.fixes import CSC_CONTAINERS, CSR_CONTAINERS + +X, y = make_blobs(n_samples=200, random_state=10) +X, y = shuffle(X, y, random_state=7) +X = StandardScaler().fit_transform(X) + +ALGORITHMS = [ + "kd_tree", + "ball_tree", + "brute", + "auto", +] + +OUTLIER_SET = {-1} | {out["label"] for _, out in _OUTLIER_ENCODING.items()} + + +def check_label_quality(labels, threshold=0.99): + n_clusters = len(set(labels) - OUTLIER_SET) + assert n_clusters == 3 + assert fowlkes_mallows_score(labels, y) > threshold + + +@pytest.mark.parametrize("outlier_type", _OUTLIER_ENCODING) +def test_outlier_data(outlier_type): + """ + Tests if np.inf and np.nan data are each treated as special outliers. + """ + outlier = { + "infinite": np.inf, + "missing": np.nan, + }[outlier_type] + prob_check = { + "infinite": lambda x, y: x == y, + "missing": lambda x, y: np.isnan(x), + }[outlier_type] + label = _OUTLIER_ENCODING[outlier_type]["label"] + prob = _OUTLIER_ENCODING[outlier_type]["prob"] + + X_outlier = X.copy() + X_outlier[0] = [outlier, 1] + X_outlier[5] = [outlier, outlier] + model = HDBSCAN().fit(X_outlier) + + (missing_labels_idx,) = (model.labels_ == label).nonzero() + assert_array_equal(missing_labels_idx, [0, 5]) + + (missing_probs_idx,) = (prob_check(model.probabilities_, prob)).nonzero() + assert_array_equal(missing_probs_idx, [0, 5]) + + clean_indices = list(range(1, 5)) + list(range(6, 200)) + clean_model = HDBSCAN().fit(X_outlier[clean_indices]) + assert_array_equal(clean_model.labels_, model.labels_[clean_indices]) + + +def test_hdbscan_distance_matrix(): + """ + Tests that HDBSCAN works with precomputed distance matrices, and throws the + appropriate errors when needed. + """ + D = euclidean_distances(X) + D_original = D.copy() + labels = HDBSCAN(metric="precomputed", copy=True).fit_predict(D) + + assert_allclose(D, D_original) + check_label_quality(labels) + + msg = r"The precomputed distance matrix.*has shape" + with pytest.raises(ValueError, match=msg): + HDBSCAN(metric="precomputed", copy=True).fit_predict(X) + + msg = r"The precomputed distance matrix.*values" + # Ensure the matrix is not symmetric + D[0, 1] = 10 + D[1, 0] = 1 + with pytest.raises(ValueError, match=msg): + HDBSCAN(metric="precomputed").fit_predict(D) + + +@pytest.mark.parametrize("sparse_constructor", [*CSR_CONTAINERS, *CSC_CONTAINERS]) +def test_hdbscan_sparse_distance_matrix(sparse_constructor): + """ + Tests that HDBSCAN works with sparse distance matrices. + """ + D = distance.squareform(distance.pdist(X)) + D /= np.max(D) + + threshold = stats.scoreatpercentile(D.flatten(), 50) + + D[D >= threshold] = 0.0 + D = sparse_constructor(D) + D.eliminate_zeros() + + labels = HDBSCAN(metric="precomputed").fit_predict(D) + check_label_quality(labels) + + +def test_hdbscan_feature_array(): + """ + Tests that HDBSCAN works with feature array, including an arbitrary + goodness of fit check. Note that the check is a simple heuristic. + """ + labels = HDBSCAN().fit_predict(X) + + # Check that clustering is arbitrarily good + # This is a heuristic to guard against regression + check_label_quality(labels) + + +@pytest.mark.parametrize("algo", ALGORITHMS) +@pytest.mark.parametrize("metric", _VALID_METRICS) +def test_hdbscan_algorithms(algo, metric): + """ + Tests that HDBSCAN works with the expected combinations of algorithms and + metrics, or raises the expected errors. + """ + labels = HDBSCAN(algorithm=algo).fit_predict(X) + check_label_quality(labels) + + # Validation for brute is handled by `pairwise_distances` + if algo in ("brute", "auto"): + return + + ALGOS_TREES = { + "kd_tree": KDTree, + "ball_tree": BallTree, + } + metric_params = { + "mahalanobis": {"V": np.eye(X.shape[1])}, + "seuclidean": {"V": np.ones(X.shape[1])}, + "minkowski": {"p": 2}, + "wminkowski": {"p": 2, "w": np.ones(X.shape[1])}, + }.get(metric, None) + + hdb = HDBSCAN( + algorithm=algo, + metric=metric, + metric_params=metric_params, + ) + + if metric not in ALGOS_TREES[algo].valid_metrics: + with pytest.raises(ValueError): + hdb.fit(X) + elif metric == "wminkowski": + with pytest.warns(FutureWarning): + hdb.fit(X) + else: + hdb.fit(X) + + +def test_dbscan_clustering(): + """ + Tests that HDBSCAN can generate a sufficiently accurate dbscan clustering. + This test is more of a sanity check than a rigorous evaluation. + """ + clusterer = HDBSCAN().fit(X) + labels = clusterer.dbscan_clustering(0.3) + + # We use a looser threshold due to dbscan producing a more constrained + # clustering representation + check_label_quality(labels, threshold=0.92) + + +@pytest.mark.parametrize("cut_distance", (0.1, 0.5, 1)) +def test_dbscan_clustering_outlier_data(cut_distance): + """ + Tests if np.inf and np.nan data are each treated as special outliers. + """ + missing_label = _OUTLIER_ENCODING["missing"]["label"] + infinite_label = _OUTLIER_ENCODING["infinite"]["label"] + + X_outlier = X.copy() + X_outlier[0] = [np.inf, 1] + X_outlier[2] = [1, np.nan] + X_outlier[5] = [np.inf, np.nan] + model = HDBSCAN().fit(X_outlier) + labels = model.dbscan_clustering(cut_distance=cut_distance) + + missing_labels_idx = np.flatnonzero(labels == missing_label) + assert_array_equal(missing_labels_idx, [2, 5]) + + infinite_labels_idx = np.flatnonzero(labels == infinite_label) + assert_array_equal(infinite_labels_idx, [0]) + + clean_idx = list(set(range(200)) - set(missing_labels_idx + infinite_labels_idx)) + clean_model = HDBSCAN().fit(X_outlier[clean_idx]) + clean_labels = clean_model.dbscan_clustering(cut_distance=cut_distance) + assert_array_equal(clean_labels, labels[clean_idx]) + + +def test_hdbscan_best_balltree_metric(): + """ + Tests that HDBSCAN using `BallTree` works. + """ + labels = HDBSCAN( + metric="seuclidean", metric_params={"V": np.ones(X.shape[1])} + ).fit_predict(X) + check_label_quality(labels) + + +def test_hdbscan_no_clusters(): + """ + Tests that HDBSCAN correctly does not generate a valid cluster when the + `min_cluster_size` is too large for the data. + """ + labels = HDBSCAN(min_cluster_size=len(X) - 1).fit_predict(X) + assert set(labels).issubset(OUTLIER_SET) + + +def test_hdbscan_min_cluster_size(): + """ + Test that the smallest non-noise cluster has at least `min_cluster_size` + many points + """ + for min_cluster_size in range(2, len(X), 1): + labels = HDBSCAN(min_cluster_size=min_cluster_size).fit_predict(X) + true_labels = [label for label in labels if label != -1] + if len(true_labels) != 0: + assert np.min(np.bincount(true_labels)) >= min_cluster_size + + +def test_hdbscan_callable_metric(): + """ + Tests that HDBSCAN works when passed a callable metric. + """ + metric = distance.euclidean + labels = HDBSCAN(metric=metric).fit_predict(X) + check_label_quality(labels) + + +@pytest.mark.parametrize("tree", ["kd_tree", "ball_tree"]) +def test_hdbscan_precomputed_non_brute(tree): + """ + Tests that HDBSCAN correctly raises an error when passing precomputed data + while requesting a tree-based algorithm. + """ + hdb = HDBSCAN(metric="precomputed", algorithm=tree) + msg = "precomputed is not a valid metric for" + with pytest.raises(ValueError, match=msg): + hdb.fit(X) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_hdbscan_sparse(csr_container): + """ + Tests that HDBSCAN works correctly when passing sparse feature data. + Evaluates correctness by comparing against the same data passed as a dense + array. + """ + + dense_labels = HDBSCAN().fit(X).labels_ + check_label_quality(dense_labels) + + _X_sparse = csr_container(X) + X_sparse = _X_sparse.copy() + sparse_labels = HDBSCAN().fit(X_sparse).labels_ + assert_array_equal(dense_labels, sparse_labels) + + # Compare that the sparse and dense non-precomputed routines return the same labels + # where the 0th observation contains the outlier. + for outlier_val, outlier_type in ((np.inf, "infinite"), (np.nan, "missing")): + X_dense = X.copy() + X_dense[0, 0] = outlier_val + dense_labels = HDBSCAN().fit(X_dense).labels_ + check_label_quality(dense_labels) + assert dense_labels[0] == _OUTLIER_ENCODING[outlier_type]["label"] + + X_sparse = _X_sparse.copy() + X_sparse[0, 0] = outlier_val + sparse_labels = HDBSCAN().fit(X_sparse).labels_ + assert_array_equal(dense_labels, sparse_labels) + + msg = "Sparse data matrices only support algorithm `brute`." + with pytest.raises(ValueError, match=msg): + HDBSCAN(metric="euclidean", algorithm="ball_tree").fit(X_sparse) + + +@pytest.mark.parametrize("algorithm", ALGORITHMS) +def test_hdbscan_centers(algorithm): + """ + Tests that HDBSCAN centers are calculated and stored properly, and are + accurate to the data. + """ + centers = [(0.0, 0.0), (3.0, 3.0)] + H, _ = make_blobs(n_samples=2000, random_state=0, centers=centers, cluster_std=0.5) + hdb = HDBSCAN(store_centers="both").fit(H) + + for center, centroid, medoid in zip(centers, hdb.centroids_, hdb.medoids_): + assert_allclose(center, centroid, rtol=1, atol=0.05) + assert_allclose(center, medoid, rtol=1, atol=0.05) + + # Ensure that nothing is done for noise + hdb = HDBSCAN( + algorithm=algorithm, store_centers="both", min_cluster_size=X.shape[0] + ).fit(X) + assert hdb.centroids_.shape[0] == 0 + assert hdb.medoids_.shape[0] == 0 + + +def test_hdbscan_allow_single_cluster_with_epsilon(): + """ + Tests that HDBSCAN single-cluster selection with epsilon works correctly. + """ + rng = np.random.RandomState(0) + no_structure = rng.rand(150, 2) + # without epsilon we should see many noise points as children of root. + labels = HDBSCAN( + min_cluster_size=5, + cluster_selection_epsilon=0.0, + cluster_selection_method="eom", + allow_single_cluster=True, + ).fit_predict(no_structure) + unique_labels, counts = np.unique(labels, return_counts=True) + assert len(unique_labels) == 2 + + # Arbitrary heuristic. Would prefer something more precise. + assert counts[unique_labels == -1] > 30 + + # for this random seed an epsilon of 0.18 will produce exactly 2 noise + # points at that cut in single linkage. + labels = HDBSCAN( + min_cluster_size=5, + cluster_selection_epsilon=0.18, + cluster_selection_method="eom", + allow_single_cluster=True, + algorithm="kd_tree", + ).fit_predict(no_structure) + unique_labels, counts = np.unique(labels, return_counts=True) + assert len(unique_labels) == 2 + assert counts[unique_labels == -1] == 2 + + +def test_hdbscan_better_than_dbscan(): + """ + Validate that HDBSCAN can properly cluster this difficult synthetic + dataset. Note that DBSCAN fails on this (see HDBSCAN plotting + example) + """ + centers = [[-0.85, -0.85], [-0.85, 0.85], [3, 3], [3, -3]] + X, y = make_blobs( + n_samples=750, + centers=centers, + cluster_std=[0.2, 0.35, 1.35, 1.35], + random_state=0, + ) + labels = HDBSCAN().fit(X).labels_ + + n_clusters = len(set(labels)) - int(-1 in labels) + assert n_clusters == 4 + fowlkes_mallows_score(labels, y) > 0.99 + + +@pytest.mark.parametrize( + "kwargs, X", + [ + ({"metric": "precomputed"}, np.array([[1, np.inf], [np.inf, 1]])), + ({"metric": "precomputed"}, [[1, 2], [2, 1]]), + ({}, [[1, 2], [3, 4]]), + ], +) +def test_hdbscan_usable_inputs(X, kwargs): + """ + Tests that HDBSCAN works correctly for array-likes and precomputed inputs + with non-finite points. + """ + HDBSCAN(min_samples=1, **kwargs).fit(X) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_hdbscan_sparse_distances_too_few_nonzero(csr_container): + """ + Tests that HDBSCAN raises the correct error when there are too few + non-zero distances. + """ + X = csr_container(np.zeros((10, 10))) + + msg = "There exists points with fewer than" + with pytest.raises(ValueError, match=msg): + HDBSCAN(metric="precomputed").fit(X) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_hdbscan_sparse_distances_disconnected_graph(csr_container): + """ + Tests that HDBSCAN raises the correct error when the distance matrix + has multiple connected components. + """ + # Create symmetric sparse matrix with 2 connected components + X = np.zeros((20, 20)) + X[:5, :5] = 1 + X[5:, 15:] = 1 + X = X + X.T + X = csr_container(X) + msg = "HDBSCAN cannot be performed on a disconnected graph" + with pytest.raises(ValueError, match=msg): + HDBSCAN(metric="precomputed").fit(X) + + +def test_hdbscan_tree_invalid_metric(): + """ + Tests that HDBSCAN correctly raises an error for invalid metric choices. + """ + metric_callable = lambda x: x + msg = ( + ".* is not a valid metric for a .*-based algorithm\\. Please select a different" + " metric\\." + ) + + # Callables are not supported for either + with pytest.raises(ValueError, match=msg): + HDBSCAN(algorithm="kd_tree", metric=metric_callable).fit(X) + with pytest.raises(ValueError, match=msg): + HDBSCAN(algorithm="ball_tree", metric=metric_callable).fit(X) + + # The set of valid metrics for KDTree at the time of writing this test is a + # strict subset of those supported in BallTree + metrics_not_kd = list(set(BallTree.valid_metrics) - set(KDTree.valid_metrics)) + if len(metrics_not_kd) > 0: + with pytest.raises(ValueError, match=msg): + HDBSCAN(algorithm="kd_tree", metric=metrics_not_kd[0]).fit(X) + + +def test_hdbscan_too_many_min_samples(): + """ + Tests that HDBSCAN correctly raises an error when setting `min_samples` + larger than the number of samples. + """ + hdb = HDBSCAN(min_samples=len(X) + 1) + msg = r"min_samples (.*) must be at most" + with pytest.raises(ValueError, match=msg): + hdb.fit(X) + + +def test_hdbscan_precomputed_dense_nan(): + """ + Tests that HDBSCAN correctly raises an error when providing precomputed + distances with `np.nan` values. + """ + X_nan = X.copy() + X_nan[0, 0] = np.nan + msg = "np.nan values found in precomputed-dense" + hdb = HDBSCAN(metric="precomputed") + with pytest.raises(ValueError, match=msg): + hdb.fit(X_nan) + + +@pytest.mark.parametrize("allow_single_cluster", [True, False]) +@pytest.mark.parametrize("epsilon", [0, 0.1]) +def test_labelling_distinct(global_random_seed, allow_single_cluster, epsilon): + """ + Tests that the `_do_labelling` helper function correctly assigns labels. + """ + n_samples = 48 + X, y = make_blobs( + n_samples, + random_state=global_random_seed, + # Ensure the clusters are distinct with no overlap + centers=[ + [0, 0], + [10, 0], + [0, 10], + ], + ) + + est = HDBSCAN().fit(X) + condensed_tree = _condense_tree( + est._single_linkage_tree_, min_cluster_size=est.min_cluster_size + ) + clusters = {n_samples + 2, n_samples + 3, n_samples + 4} + cluster_label_map = {n_samples + 2: 0, n_samples + 3: 1, n_samples + 4: 2} + labels = _do_labelling( + condensed_tree=condensed_tree, + clusters=clusters, + cluster_label_map=cluster_label_map, + allow_single_cluster=allow_single_cluster, + cluster_selection_epsilon=epsilon, + ) + + first_with_label = {_y: np.where(y == _y)[0][0] for _y in list(set(y))} + y_to_labels = {_y: labels[first_with_label[_y]] for _y in list(set(y))} + aligned_target = np.vectorize(y_to_labels.get)(y) + assert_array_equal(labels, aligned_target) + + +def test_labelling_thresholding(): + """ + Tests that the `_do_labelling` helper function correctly thresholds the + incoming lambda values given various `cluster_selection_epsilon` values. + """ + n_samples = 5 + MAX_LAMBDA = 1.5 + condensed_tree = np.array( + [ + (5, 2, MAX_LAMBDA, 1), + (5, 1, 0.1, 1), + (5, 0, MAX_LAMBDA, 1), + (5, 3, 0.2, 1), + (5, 4, 0.3, 1), + ], + dtype=CONDENSED_dtype, + ) + labels = _do_labelling( + condensed_tree=condensed_tree, + clusters={n_samples}, + cluster_label_map={n_samples: 0, n_samples + 1: 1}, + allow_single_cluster=True, + cluster_selection_epsilon=1, + ) + num_noise = condensed_tree["value"] < 1 + assert sum(num_noise) == sum(labels == -1) + + labels = _do_labelling( + condensed_tree=condensed_tree, + clusters={n_samples}, + cluster_label_map={n_samples: 0, n_samples + 1: 1}, + allow_single_cluster=True, + cluster_selection_epsilon=0, + ) + # The threshold should be calculated per-sample based on the largest + # lambda of any simbling node. In this case, all points are siblings + # and the largest value is exactly MAX_LAMBDA. + num_noise = condensed_tree["value"] < MAX_LAMBDA + assert sum(num_noise) == sum(labels == -1) + + +@pytest.mark.parametrize("store_centers", ["centroid", "medoid"]) +def test_hdbscan_error_precomputed_and_store_centers(store_centers): + """Check that we raise an error if the centers are requested together with + a precomputed input matrix. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/27893 + """ + rng = np.random.RandomState(0) + X = rng.random((100, 2)) + X_dist = euclidean_distances(X) + err_msg = "Cannot store centers when using a precomputed distance matrix." + with pytest.raises(ValueError, match=err_msg): + HDBSCAN(metric="precomputed", store_centers=store_centers).fit(X_dist) + + +@pytest.mark.parametrize("valid_algo", ["auto", "brute"]) +def test_hdbscan_cosine_metric_valid_algorithm(valid_algo): + """Test that HDBSCAN works with the "cosine" metric when the algorithm is set + to "brute" or "auto". + + Non-regression test for issue #28631 + """ + HDBSCAN(metric="cosine", algorithm=valid_algo).fit_predict(X) + + +@pytest.mark.parametrize("invalid_algo", ["kd_tree", "ball_tree"]) +def test_hdbscan_cosine_metric_invalid_algorithm(invalid_algo): + """Test that HDBSCAN raises an informative error is raised when an unsupported + algorithm is used with the "cosine" metric. + """ + hdbscan = HDBSCAN(metric="cosine", algorithm=invalid_algo) + with pytest.raises(ValueError, match="cosine is not a valid metric"): + hdbscan.fit_predict(X) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_hierarchical.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_hierarchical.py new file mode 100644 index 0000000000000000000000000000000000000000..222d4f6cd92649b9d59cb3f69f3d350414493984 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_hierarchical.py @@ -0,0 +1,889 @@ +""" +Several basic tests for hierarchical clustering procedures + +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import itertools +import shutil +from functools import partial +from tempfile import mkdtemp + +import numpy as np +import pytest +from scipy.cluster import hierarchy +from scipy.sparse.csgraph import connected_components + +from sklearn.cluster import AgglomerativeClustering, FeatureAgglomeration, ward_tree +from sklearn.cluster._agglomerative import ( + _TREE_BUILDERS, + _fix_connectivity, + _hc_cut, + linkage_tree, +) +from sklearn.cluster._hierarchical_fast import ( + average_merge, + max_merge, + mst_linkage_core, +) +from sklearn.datasets import make_circles, make_moons +from sklearn.feature_extraction.image import grid_to_graph +from sklearn.metrics import DistanceMetric +from sklearn.metrics.cluster import adjusted_rand_score, normalized_mutual_info_score +from sklearn.metrics.pairwise import ( + PAIRED_DISTANCES, + cosine_distances, + manhattan_distances, + pairwise_distances, +) +from sklearn.metrics.tests.test_dist_metrics import METRICS_DEFAULT_PARAMS +from sklearn.neighbors import kneighbors_graph +from sklearn.utils._fast_dict import IntFloatDict +from sklearn.utils._testing import ( + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, + create_memmap_backed_data, + ignore_warnings, +) +from sklearn.utils.fixes import LIL_CONTAINERS + + +def test_linkage_misc(): + # Misc tests on linkage + rng = np.random.RandomState(42) + X = rng.normal(size=(5, 5)) + + with pytest.raises(ValueError): + linkage_tree(X, linkage="foo") + + with pytest.raises(ValueError): + linkage_tree(X, connectivity=np.ones((4, 4))) + + # Smoke test FeatureAgglomeration + FeatureAgglomeration().fit(X) + + # test hierarchical clustering on a precomputed distances matrix + dis = cosine_distances(X) + + res = linkage_tree(dis, affinity="precomputed") + assert_array_equal(res[0], linkage_tree(X, affinity="cosine")[0]) + + # test hierarchical clustering on a precomputed distances matrix + res = linkage_tree(X, affinity=manhattan_distances) + assert_array_equal(res[0], linkage_tree(X, affinity="manhattan")[0]) + + +def test_structured_linkage_tree(): + # Check that we obtain the correct solution for structured linkage trees. + rng = np.random.RandomState(0) + mask = np.ones([10, 10], dtype=bool) + # Avoiding a mask with only 'True' entries + mask[4:7, 4:7] = 0 + X = rng.randn(50, 100) + connectivity = grid_to_graph(*mask.shape) + for tree_builder in _TREE_BUILDERS.values(): + children, n_components, n_leaves, parent = tree_builder( + X.T, connectivity=connectivity + ) + n_nodes = 2 * X.shape[1] - 1 + assert len(children) + n_leaves == n_nodes + # Check that ward_tree raises a ValueError with a connectivity matrix + # of the wrong shape + with pytest.raises(ValueError): + tree_builder(X.T, connectivity=np.ones((4, 4))) + # Check that fitting with no samples raises an error + with pytest.raises(ValueError): + tree_builder(X.T[:0], connectivity=connectivity) + + +def test_unstructured_linkage_tree(): + # Check that we obtain the correct solution for unstructured linkage trees. + rng = np.random.RandomState(0) + X = rng.randn(50, 100) + for this_X in (X, X[0]): + # With specified a number of clusters just for the sake of + # raising a warning and testing the warning code + with ignore_warnings(): + with pytest.warns(UserWarning): + children, n_nodes, n_leaves, parent = ward_tree(this_X.T, n_clusters=10) + n_nodes = 2 * X.shape[1] - 1 + assert len(children) + n_leaves == n_nodes + + for tree_builder in _TREE_BUILDERS.values(): + for this_X in (X, X[0]): + with ignore_warnings(): + with pytest.warns(UserWarning): + children, n_nodes, n_leaves, parent = tree_builder( + this_X.T, n_clusters=10 + ) + n_nodes = 2 * X.shape[1] - 1 + assert len(children) + n_leaves == n_nodes + + +def test_height_linkage_tree(): + # Check that the height of the results of linkage tree is sorted. + rng = np.random.RandomState(0) + mask = np.ones([10, 10], dtype=bool) + X = rng.randn(50, 100) + connectivity = grid_to_graph(*mask.shape) + for linkage_func in _TREE_BUILDERS.values(): + children, n_nodes, n_leaves, parent = linkage_func( + X.T, connectivity=connectivity + ) + n_nodes = 2 * X.shape[1] - 1 + assert len(children) + n_leaves == n_nodes + + +def test_zero_cosine_linkage_tree(): + # Check that zero vectors in X produce an error when + # 'cosine' affinity is used + X = np.array([[0, 1], [0, 0]]) + msg = "Cosine affinity cannot be used when X contains zero vectors" + with pytest.raises(ValueError, match=msg): + linkage_tree(X, affinity="cosine") + + +@pytest.mark.parametrize("n_clusters, distance_threshold", [(None, 0.5), (10, None)]) +@pytest.mark.parametrize("compute_distances", [True, False]) +@pytest.mark.parametrize("linkage", ["ward", "complete", "average", "single"]) +def test_agglomerative_clustering_distances( + n_clusters, compute_distances, distance_threshold, linkage +): + # Check that when `compute_distances` is True or `distance_threshold` is + # given, the fitted model has an attribute `distances_`. + rng = np.random.RandomState(0) + mask = np.ones([10, 10], dtype=bool) + n_samples = 100 + X = rng.randn(n_samples, 50) + connectivity = grid_to_graph(*mask.shape) + + clustering = AgglomerativeClustering( + n_clusters=n_clusters, + connectivity=connectivity, + linkage=linkage, + distance_threshold=distance_threshold, + compute_distances=compute_distances, + ) + clustering.fit(X) + if compute_distances or (distance_threshold is not None): + assert hasattr(clustering, "distances_") + n_children = clustering.children_.shape[0] + n_nodes = n_children + 1 + assert clustering.distances_.shape == (n_nodes - 1,) + else: + assert not hasattr(clustering, "distances_") + + +@pytest.mark.parametrize("lil_container", LIL_CONTAINERS) +def test_agglomerative_clustering(global_random_seed, lil_container): + # Check that we obtain the correct number of clusters with + # agglomerative clustering. + rng = np.random.RandomState(global_random_seed) + mask = np.ones([10, 10], dtype=bool) + n_samples = 100 + X = rng.randn(n_samples, 50) + connectivity = grid_to_graph(*mask.shape) + for linkage in ("ward", "complete", "average", "single"): + clustering = AgglomerativeClustering( + n_clusters=10, connectivity=connectivity, linkage=linkage + ) + clustering.fit(X) + # test caching + try: + tempdir = mkdtemp() + clustering = AgglomerativeClustering( + n_clusters=10, + connectivity=connectivity, + memory=tempdir, + linkage=linkage, + ) + clustering.fit(X) + labels = clustering.labels_ + assert np.size(np.unique(labels)) == 10 + finally: + shutil.rmtree(tempdir) + # Turn caching off now + clustering = AgglomerativeClustering( + n_clusters=10, connectivity=connectivity, linkage=linkage + ) + # Check that we obtain the same solution with early-stopping of the + # tree building + clustering.compute_full_tree = False + clustering.fit(X) + assert_almost_equal(normalized_mutual_info_score(clustering.labels_, labels), 1) + clustering.connectivity = None + clustering.fit(X) + assert np.size(np.unique(clustering.labels_)) == 10 + # Check that we raise a TypeError on dense matrices + clustering = AgglomerativeClustering( + n_clusters=10, + connectivity=lil_container(connectivity.toarray()[:10, :10]), + linkage=linkage, + ) + with pytest.raises(ValueError): + clustering.fit(X) + + # Test that using ward with another metric than euclidean raises an + # exception + clustering = AgglomerativeClustering( + n_clusters=10, + connectivity=connectivity.toarray(), + metric="manhattan", + linkage="ward", + ) + with pytest.raises(ValueError): + clustering.fit(X) + + # Test using another metric than euclidean works with linkage complete + for metric in PAIRED_DISTANCES.keys(): + # Compare our (structured) implementation to scipy + clustering = AgglomerativeClustering( + n_clusters=10, + connectivity=np.ones((n_samples, n_samples)), + metric=metric, + linkage="complete", + ) + clustering.fit(X) + clustering2 = AgglomerativeClustering( + n_clusters=10, connectivity=None, metric=metric, linkage="complete" + ) + clustering2.fit(X) + assert_almost_equal( + normalized_mutual_info_score(clustering2.labels_, clustering.labels_), 1 + ) + + # Test that using a distance matrix (affinity = 'precomputed') has same + # results (with connectivity constraints) + clustering = AgglomerativeClustering( + n_clusters=10, connectivity=connectivity, linkage="complete" + ) + clustering.fit(X) + X_dist = pairwise_distances(X) + clustering2 = AgglomerativeClustering( + n_clusters=10, + connectivity=connectivity, + metric="precomputed", + linkage="complete", + ) + clustering2.fit(X_dist) + assert_array_equal(clustering.labels_, clustering2.labels_) + + +def test_agglomerative_clustering_memory_mapped(): + """AgglomerativeClustering must work on mem-mapped dataset. + + Non-regression test for issue #19875. + """ + rng = np.random.RandomState(0) + Xmm = create_memmap_backed_data(rng.randn(50, 100)) + AgglomerativeClustering(metric="euclidean", linkage="single").fit(Xmm) + + +def test_ward_agglomeration(global_random_seed): + # Check that we obtain the correct solution in a simplistic case + rng = np.random.RandomState(global_random_seed) + mask = np.ones([10, 10], dtype=bool) + X = rng.randn(50, 100) + connectivity = grid_to_graph(*mask.shape) + agglo = FeatureAgglomeration(n_clusters=5, connectivity=connectivity) + agglo.fit(X) + assert np.size(np.unique(agglo.labels_)) == 5 + + X_red = agglo.transform(X) + assert X_red.shape[1] == 5 + X_full = agglo.inverse_transform(X_red) + assert np.unique(X_full[0]).size == 5 + assert_array_almost_equal(agglo.transform(X_full), X_red) + + # Check that fitting with no samples raises a ValueError + with pytest.raises(ValueError): + agglo.fit(X[:0]) + + +def test_single_linkage_clustering(): + # Check that we get the correct result in two emblematic cases + moons, moon_labels = make_moons(noise=0.05, random_state=42) + clustering = AgglomerativeClustering(n_clusters=2, linkage="single") + clustering.fit(moons) + assert_almost_equal( + normalized_mutual_info_score(clustering.labels_, moon_labels), 1 + ) + + circles, circle_labels = make_circles(factor=0.5, noise=0.025, random_state=42) + clustering = AgglomerativeClustering(n_clusters=2, linkage="single") + clustering.fit(circles) + assert_almost_equal( + normalized_mutual_info_score(clustering.labels_, circle_labels), 1 + ) + + +def assess_same_labelling(cut1, cut2): + """Util for comparison with scipy""" + co_clust = [] + for cut in [cut1, cut2]: + n = len(cut) + k = cut.max() + 1 + ecut = np.zeros((n, k)) + ecut[np.arange(n), cut] = 1 + co_clust.append(np.dot(ecut, ecut.T)) + assert (co_clust[0] == co_clust[1]).all() + + +def test_sparse_scikit_vs_scipy(global_random_seed): + # Test scikit linkage with full connectivity (i.e. unstructured) vs scipy + n, p, k = 10, 5, 3 + rng = np.random.RandomState(global_random_seed) + + # Not using a lil_matrix here, just to check that non sparse + # matrices are well handled + connectivity = np.ones((n, n)) + for linkage in _TREE_BUILDERS.keys(): + for i in range(5): + X = 0.1 * rng.normal(size=(n, p)) + X -= 4.0 * np.arange(n)[:, np.newaxis] + X -= X.mean(axis=1)[:, np.newaxis] + + out = hierarchy.linkage(X, method=linkage) + + children_ = out[:, :2].astype(int, copy=False) + children, _, n_leaves, _ = _TREE_BUILDERS[linkage]( + X, connectivity=connectivity + ) + + # Sort the order of child nodes per row for consistency + children.sort(axis=1) + assert_array_equal( + children, + children_, + "linkage tree differs from scipy impl for linkage: " + linkage, + ) + + cut = _hc_cut(k, children, n_leaves) + cut_ = _hc_cut(k, children_, n_leaves) + assess_same_labelling(cut, cut_) + + # Test error management in _hc_cut + with pytest.raises(ValueError): + _hc_cut(n_leaves + 1, children, n_leaves) + + +# Make sure our custom mst_linkage_core gives +# the same results as scipy's builtin +def test_vector_scikit_single_vs_scipy_single(global_random_seed): + n_samples, n_features, n_clusters = 10, 5, 3 + rng = np.random.RandomState(global_random_seed) + X = 0.1 * rng.normal(size=(n_samples, n_features)) + X -= 4.0 * np.arange(n_samples)[:, np.newaxis] + X -= X.mean(axis=1)[:, np.newaxis] + + out = hierarchy.linkage(X, method="single") + children_scipy = out[:, :2].astype(int) + + children, _, n_leaves, _ = _TREE_BUILDERS["single"](X) + + # Sort the order of child nodes per row for consistency + children.sort(axis=1) + assert_array_equal( + children, + children_scipy, + "linkage tree differs from scipy impl for single linkage.", + ) + + cut = _hc_cut(n_clusters, children, n_leaves) + cut_scipy = _hc_cut(n_clusters, children_scipy, n_leaves) + assess_same_labelling(cut, cut_scipy) + + +@pytest.mark.parametrize("metric_param_grid", METRICS_DEFAULT_PARAMS) +def test_mst_linkage_core_memory_mapped(metric_param_grid): + """The MST-LINKAGE-CORE algorithm must work on mem-mapped dataset. + + Non-regression test for issue #19875. + """ + rng = np.random.RandomState(seed=1) + X = rng.normal(size=(20, 4)) + Xmm = create_memmap_backed_data(X) + metric, param_grid = metric_param_grid + keys = param_grid.keys() + for vals in itertools.product(*param_grid.values()): + kwargs = dict(zip(keys, vals)) + distance_metric = DistanceMetric.get_metric(metric, **kwargs) + mst = mst_linkage_core(X, distance_metric) + mst_mm = mst_linkage_core(Xmm, distance_metric) + np.testing.assert_equal(mst, mst_mm) + + +def test_identical_points(): + # Ensure identical points are handled correctly when using mst with + # a sparse connectivity matrix + X = np.array([[0, 0, 0], [0, 0, 0], [1, 1, 1], [1, 1, 1], [2, 2, 2], [2, 2, 2]]) + true_labels = np.array([0, 0, 1, 1, 2, 2]) + connectivity = kneighbors_graph(X, n_neighbors=3, include_self=False) + connectivity = 0.5 * (connectivity + connectivity.T) + connectivity, n_components = _fix_connectivity(X, connectivity, "euclidean") + + for linkage in ("single", "average", "average", "ward"): + clustering = AgglomerativeClustering( + n_clusters=3, linkage=linkage, connectivity=connectivity + ) + clustering.fit(X) + + assert_almost_equal( + normalized_mutual_info_score(clustering.labels_, true_labels), 1 + ) + + +def test_connectivity_propagation(): + # Check that connectivity in the ward tree is propagated correctly during + # merging. + X = np.array( + [ + (0.014, 0.120), + (0.014, 0.099), + (0.014, 0.097), + (0.017, 0.153), + (0.017, 0.153), + (0.018, 0.153), + (0.018, 0.153), + (0.018, 0.153), + (0.018, 0.153), + (0.018, 0.153), + (0.018, 0.153), + (0.018, 0.153), + (0.018, 0.152), + (0.018, 0.149), + (0.018, 0.144), + ] + ) + connectivity = kneighbors_graph(X, 10, include_self=False) + ward = AgglomerativeClustering( + n_clusters=4, connectivity=connectivity, linkage="ward" + ) + # If changes are not propagated correctly, fit crashes with an + # IndexError + ward.fit(X) + + +def test_ward_tree_children_order(global_random_seed): + # Check that children are ordered in the same way for both structured and + # unstructured versions of ward_tree. + + # test on five random datasets + n, p = 10, 5 + rng = np.random.RandomState(global_random_seed) + + connectivity = np.ones((n, n)) + for i in range(5): + X = 0.1 * rng.normal(size=(n, p)) + X -= 4.0 * np.arange(n)[:, np.newaxis] + X -= X.mean(axis=1)[:, np.newaxis] + + out_unstructured = ward_tree(X) + out_structured = ward_tree(X, connectivity=connectivity) + + assert_array_equal(out_unstructured[0], out_structured[0]) + + +def test_ward_linkage_tree_return_distance(global_random_seed): + # Test return_distance option on linkage and ward trees + + # test that return_distance when set true, gives same + # output on both structured and unstructured clustering. + n, p = 10, 5 + rng = np.random.RandomState(global_random_seed) + + connectivity = np.ones((n, n)) + for i in range(5): + X = 0.1 * rng.normal(size=(n, p)) + X -= 4.0 * np.arange(n)[:, np.newaxis] + X -= X.mean(axis=1)[:, np.newaxis] + + out_unstructured = ward_tree(X, return_distance=True) + out_structured = ward_tree(X, connectivity=connectivity, return_distance=True) + + # get children + children_unstructured = out_unstructured[0] + children_structured = out_structured[0] + + # check if we got the same clusters + assert_array_equal(children_unstructured, children_structured) + + # check if the distances are the same + dist_unstructured = out_unstructured[-1] + dist_structured = out_structured[-1] + + assert_array_almost_equal(dist_unstructured, dist_structured) + + for linkage in ["average", "complete", "single"]: + structured_items = linkage_tree( + X, connectivity=connectivity, linkage=linkage, return_distance=True + )[-1] + unstructured_items = linkage_tree(X, linkage=linkage, return_distance=True)[ + -1 + ] + structured_dist = structured_items[-1] + unstructured_dist = unstructured_items[-1] + structured_children = structured_items[0] + unstructured_children = unstructured_items[0] + assert_array_almost_equal(structured_dist, unstructured_dist) + assert_array_almost_equal(structured_children, unstructured_children) + + # test on the following dataset where we know the truth + # taken from scipy/cluster/tests/hierarchy_test_data.py + X = np.array( + [ + [1.43054825, -7.5693489], + [6.95887839, 6.82293382], + [2.87137846, -9.68248579], + [7.87974764, -6.05485803], + [8.24018364, -6.09495602], + [7.39020262, 8.54004355], + ] + ) + # truth + linkage_X_ward = np.array( + [ + [3.0, 4.0, 0.36265956, 2.0], + [1.0, 5.0, 1.77045373, 2.0], + [0.0, 2.0, 2.55760419, 2.0], + [6.0, 8.0, 9.10208346, 4.0], + [7.0, 9.0, 24.7784379, 6.0], + ] + ) + + linkage_X_complete = np.array( + [ + [3.0, 4.0, 0.36265956, 2.0], + [1.0, 5.0, 1.77045373, 2.0], + [0.0, 2.0, 2.55760419, 2.0], + [6.0, 8.0, 6.96742194, 4.0], + [7.0, 9.0, 18.77445997, 6.0], + ] + ) + + linkage_X_average = np.array( + [ + [3.0, 4.0, 0.36265956, 2.0], + [1.0, 5.0, 1.77045373, 2.0], + [0.0, 2.0, 2.55760419, 2.0], + [6.0, 8.0, 6.55832839, 4.0], + [7.0, 9.0, 15.44089605, 6.0], + ] + ) + + n_samples, n_features = np.shape(X) + connectivity_X = np.ones((n_samples, n_samples)) + + out_X_unstructured = ward_tree(X, return_distance=True) + out_X_structured = ward_tree(X, connectivity=connectivity_X, return_distance=True) + + # check that the labels are the same + assert_array_equal(linkage_X_ward[:, :2], out_X_unstructured[0]) + assert_array_equal(linkage_X_ward[:, :2], out_X_structured[0]) + + # check that the distances are correct + assert_array_almost_equal(linkage_X_ward[:, 2], out_X_unstructured[4]) + assert_array_almost_equal(linkage_X_ward[:, 2], out_X_structured[4]) + + linkage_options = ["complete", "average", "single"] + X_linkage_truth = [linkage_X_complete, linkage_X_average] + for linkage, X_truth in zip(linkage_options, X_linkage_truth): + out_X_unstructured = linkage_tree(X, return_distance=True, linkage=linkage) + out_X_structured = linkage_tree( + X, connectivity=connectivity_X, linkage=linkage, return_distance=True + ) + + # check that the labels are the same + assert_array_equal(X_truth[:, :2], out_X_unstructured[0]) + assert_array_equal(X_truth[:, :2], out_X_structured[0]) + + # check that the distances are correct + assert_array_almost_equal(X_truth[:, 2], out_X_unstructured[4]) + assert_array_almost_equal(X_truth[:, 2], out_X_structured[4]) + + +def test_connectivity_fixing_non_lil(): + # Check non regression of a bug if a non item assignable connectivity is + # provided with more than one component. + # create dummy data + x = np.array([[0, 0], [1, 1]]) + # create a mask with several components to force connectivity fixing + m = np.array([[True, False], [False, True]]) + c = grid_to_graph(n_x=2, n_y=2, mask=m) + w = AgglomerativeClustering(connectivity=c, linkage="ward") + with pytest.warns(UserWarning): + w.fit(x) + + +def test_int_float_dict(): + rng = np.random.RandomState(0) + keys = np.unique(rng.randint(100, size=10).astype(np.intp, copy=False)) + values = rng.rand(len(keys)) + + d = IntFloatDict(keys, values) + for key, value in zip(keys, values): + assert d[key] == value + + other_keys = np.arange(50, dtype=np.intp)[::2] + other_values = np.full(50, 0.5)[::2] + other = IntFloatDict(other_keys, other_values) + # Complete smoke test + max_merge(d, other, mask=np.ones(100, dtype=np.intp), n_a=1, n_b=1) + average_merge(d, other, mask=np.ones(100, dtype=np.intp), n_a=1, n_b=1) + + +def test_connectivity_callable(): + rng = np.random.RandomState(0) + X = rng.rand(20, 5) + connectivity = kneighbors_graph(X, 3, include_self=False) + aglc1 = AgglomerativeClustering(connectivity=connectivity) + aglc2 = AgglomerativeClustering( + connectivity=partial(kneighbors_graph, n_neighbors=3, include_self=False) + ) + aglc1.fit(X) + aglc2.fit(X) + assert_array_equal(aglc1.labels_, aglc2.labels_) + + +def test_connectivity_ignores_diagonal(): + rng = np.random.RandomState(0) + X = rng.rand(20, 5) + connectivity = kneighbors_graph(X, 3, include_self=False) + connectivity_include_self = kneighbors_graph(X, 3, include_self=True) + aglc1 = AgglomerativeClustering(connectivity=connectivity) + aglc2 = AgglomerativeClustering(connectivity=connectivity_include_self) + aglc1.fit(X) + aglc2.fit(X) + assert_array_equal(aglc1.labels_, aglc2.labels_) + + +def test_compute_full_tree(): + # Test that the full tree is computed if n_clusters is small + rng = np.random.RandomState(0) + X = rng.randn(10, 2) + connectivity = kneighbors_graph(X, 5, include_self=False) + + # When n_clusters is less, the full tree should be built + # that is the number of merges should be n_samples - 1 + agc = AgglomerativeClustering(n_clusters=2, connectivity=connectivity) + agc.fit(X) + n_samples = X.shape[0] + n_nodes = agc.children_.shape[0] + assert n_nodes == n_samples - 1 + + # When n_clusters is large, greater than max of 100 and 0.02 * n_samples. + # we should stop when there are n_clusters. + n_clusters = 101 + X = rng.randn(200, 2) + connectivity = kneighbors_graph(X, 10, include_self=False) + agc = AgglomerativeClustering(n_clusters=n_clusters, connectivity=connectivity) + agc.fit(X) + n_samples = X.shape[0] + n_nodes = agc.children_.shape[0] + assert n_nodes == n_samples - n_clusters + + +def test_n_components(): + # Test n_components returned by linkage, average and ward tree + rng = np.random.RandomState(0) + X = rng.rand(5, 5) + + # Connectivity matrix having five components. + connectivity = np.eye(5) + + for linkage_func in _TREE_BUILDERS.values(): + assert ignore_warnings(linkage_func)(X, connectivity=connectivity)[1] == 5 + + +def test_affinity_passed_to_fix_connectivity(): + # Test that the affinity parameter is actually passed to the pairwise + # function + + size = 2 + rng = np.random.RandomState(0) + X = rng.randn(size, size) + mask = np.array([True, False, False, True]) + + connectivity = grid_to_graph(n_x=size, n_y=size, mask=mask, return_as=np.ndarray) + + class FakeAffinity: + def __init__(self): + self.counter = 0 + + def increment(self, *args, **kwargs): + self.counter += 1 + return self.counter + + fa = FakeAffinity() + + linkage_tree(X, connectivity=connectivity, affinity=fa.increment) + + assert fa.counter == 3 + + +@pytest.mark.parametrize("linkage", ["ward", "complete", "average"]) +def test_agglomerative_clustering_with_distance_threshold(linkage, global_random_seed): + # Check that we obtain the correct number of clusters with + # agglomerative clustering with distance_threshold. + rng = np.random.RandomState(global_random_seed) + mask = np.ones([10, 10], dtype=bool) + n_samples = 100 + X = rng.randn(n_samples, 50) + connectivity = grid_to_graph(*mask.shape) + # test when distance threshold is set to 10 + distance_threshold = 10 + for conn in [None, connectivity]: + clustering = AgglomerativeClustering( + n_clusters=None, + distance_threshold=distance_threshold, + connectivity=conn, + linkage=linkage, + ) + clustering.fit(X) + clusters_produced = clustering.labels_ + num_clusters_produced = len(np.unique(clustering.labels_)) + # test if the clusters produced match the point in the linkage tree + # where the distance exceeds the threshold + tree_builder = _TREE_BUILDERS[linkage] + children, n_components, n_leaves, parent, distances = tree_builder( + X, connectivity=conn, n_clusters=None, return_distance=True + ) + num_clusters_at_threshold = ( + np.count_nonzero(distances >= distance_threshold) + 1 + ) + # test number of clusters produced + assert num_clusters_at_threshold == num_clusters_produced + # test clusters produced + clusters_at_threshold = _hc_cut( + n_clusters=num_clusters_produced, children=children, n_leaves=n_leaves + ) + assert np.array_equiv(clusters_produced, clusters_at_threshold) + + +def test_small_distance_threshold(global_random_seed): + rng = np.random.RandomState(global_random_seed) + n_samples = 10 + X = rng.randint(-300, 300, size=(n_samples, 3)) + # this should result in all data in their own clusters, given that + # their pairwise distances are bigger than .1 (which may not be the case + # with a different random seed). + clustering = AgglomerativeClustering( + n_clusters=None, distance_threshold=1.0, linkage="single" + ).fit(X) + # check that the pairwise distances are indeed all larger than .1 + all_distances = pairwise_distances(X, metric="minkowski", p=2) + np.fill_diagonal(all_distances, np.inf) + assert np.all(all_distances > 0.1) + assert clustering.n_clusters_ == n_samples + + +def test_cluster_distances_with_distance_threshold(global_random_seed): + rng = np.random.RandomState(global_random_seed) + n_samples = 100 + X = rng.randint(-10, 10, size=(n_samples, 3)) + # check the distances within the clusters and with other clusters + distance_threshold = 4 + clustering = AgglomerativeClustering( + n_clusters=None, distance_threshold=distance_threshold, linkage="single" + ).fit(X) + labels = clustering.labels_ + D = pairwise_distances(X, metric="minkowski", p=2) + # to avoid taking the 0 diagonal in min() + np.fill_diagonal(D, np.inf) + for label in np.unique(labels): + in_cluster_mask = labels == label + max_in_cluster_distance = ( + D[in_cluster_mask][:, in_cluster_mask].min(axis=0).max() + ) + min_out_cluster_distance = ( + D[in_cluster_mask][:, ~in_cluster_mask].min(axis=0).min() + ) + # single data point clusters only have that inf diagonal here + if in_cluster_mask.sum() > 1: + assert max_in_cluster_distance < distance_threshold + assert min_out_cluster_distance >= distance_threshold + + +@pytest.mark.parametrize("linkage", ["ward", "complete", "average"]) +@pytest.mark.parametrize( + ("threshold", "y_true"), [(0.5, [1, 0]), (1.0, [1, 0]), (1.5, [0, 0])] +) +def test_agglomerative_clustering_with_distance_threshold_edge_case( + linkage, threshold, y_true +): + # test boundary case of distance_threshold matching the distance + X = [[0], [1]] + clusterer = AgglomerativeClustering( + n_clusters=None, distance_threshold=threshold, linkage=linkage + ) + y_pred = clusterer.fit_predict(X) + assert adjusted_rand_score(y_true, y_pred) == 1 + + +def test_dist_threshold_invalid_parameters(): + X = [[0], [1]] + with pytest.raises(ValueError, match="Exactly one of "): + AgglomerativeClustering(n_clusters=None, distance_threshold=None).fit(X) + + with pytest.raises(ValueError, match="Exactly one of "): + AgglomerativeClustering(n_clusters=2, distance_threshold=1).fit(X) + + X = [[0], [1]] + with pytest.raises(ValueError, match="compute_full_tree must be True if"): + AgglomerativeClustering( + n_clusters=None, distance_threshold=1, compute_full_tree=False + ).fit(X) + + +def test_invalid_shape_precomputed_dist_matrix(): + # Check that an error is raised when affinity='precomputed' + # and a non square matrix is passed (PR #16257). + rng = np.random.RandomState(0) + X = rng.rand(5, 3) + with pytest.raises( + ValueError, + match=r"Distance matrix should be square, got matrix of shape \(5, 3\)", + ): + AgglomerativeClustering(metric="precomputed", linkage="complete").fit(X) + + +def test_precomputed_connectivity_metric_with_2_connected_components(): + """Check that connecting components works when connectivity and + affinity are both precomputed and the number of connected components is + greater than 1. Non-regression test for #16151. + """ + + connectivity_matrix = np.array( + [ + [0, 1, 1, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 1], + [0, 0, 0, 0, 0], + ] + ) + # ensure that connectivity_matrix has two connected components + assert connected_components(connectivity_matrix)[0] == 2 + + rng = np.random.RandomState(0) + X = rng.randn(5, 10) + + X_dist = pairwise_distances(X) + clusterer_precomputed = AgglomerativeClustering( + metric="precomputed", connectivity=connectivity_matrix, linkage="complete" + ) + msg = "Completing it to avoid stopping the tree early" + with pytest.warns(UserWarning, match=msg): + clusterer_precomputed.fit(X_dist) + + clusterer = AgglomerativeClustering( + connectivity=connectivity_matrix, linkage="complete" + ) + with pytest.warns(UserWarning, match=msg): + clusterer.fit(X) + + assert_array_equal(clusterer.labels_, clusterer_precomputed.labels_) + assert_array_equal(clusterer.children_, clusterer_precomputed.children_) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_k_means.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_k_means.py new file mode 100644 index 0000000000000000000000000000000000000000..0ab602d32d1330fe738ce7a24cd4b4c68cdf9c15 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_k_means.py @@ -0,0 +1,1364 @@ +"""Testing for K-means""" + +import re +import sys +from io import StringIO + +import numpy as np +import pytest +from scipy import sparse as sp + +from sklearn.base import clone +from sklearn.cluster import KMeans, MiniBatchKMeans, k_means, kmeans_plusplus +from sklearn.cluster._k_means_common import ( + _euclidean_dense_dense_wrapper, + _euclidean_sparse_dense_wrapper, + _inertia_dense, + _inertia_sparse, + _is_same_clustering, + _relocate_empty_clusters_dense, + _relocate_empty_clusters_sparse, +) +from sklearn.cluster._kmeans import _labels_inertia, _mini_batch_step +from sklearn.datasets import make_blobs +from sklearn.exceptions import ConvergenceWarning +from sklearn.metrics import pairwise_distances, pairwise_distances_argmin +from sklearn.metrics.cluster import v_measure_score +from sklearn.metrics.pairwise import euclidean_distances +from sklearn.utils._testing import ( + assert_allclose, + assert_array_equal, + create_memmap_backed_data, +) +from sklearn.utils.extmath import row_norms +from sklearn.utils.fixes import CSR_CONTAINERS +from sklearn.utils.parallel import _get_threadpool_controller + +# non centered, sparse centers to check the +centers = np.array( + [ + [0.0, 5.0, 0.0, 0.0, 0.0], + [1.0, 1.0, 4.0, 0.0, 0.0], + [1.0, 0.0, 0.0, 5.0, 1.0], + ] +) +n_samples = 100 +n_clusters, n_features = centers.shape +X, true_labels = make_blobs( + n_samples=n_samples, centers=centers, cluster_std=1.0, random_state=42 +) +X_as_any_csr = [container(X) for container in CSR_CONTAINERS] +data_containers = [np.array] + CSR_CONTAINERS +data_containers_ids = ( + ["dense", "sparse_matrix", "sparse_array"] + if len(X_as_any_csr) == 2 + else ["dense", "sparse_matrix"] +) + + +@pytest.mark.parametrize("array_constr", data_containers, ids=data_containers_ids) +@pytest.mark.parametrize("algo", ["lloyd", "elkan"]) +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_kmeans_results(array_constr, algo, dtype): + # Checks that KMeans works as intended on toy dataset by comparing with + # expected results computed by hand. + X = array_constr([[0, 0], [0.5, 0], [0.5, 1], [1, 1]], dtype=dtype) + sample_weight = [3, 1, 1, 3] + init_centers = np.array([[0, 0], [1, 1]], dtype=dtype) + + expected_labels = [0, 0, 1, 1] + expected_inertia = 0.375 + expected_centers = np.array([[0.125, 0], [0.875, 1]], dtype=dtype) + expected_n_iter = 2 + + kmeans = KMeans(n_clusters=2, n_init=1, init=init_centers, algorithm=algo) + kmeans.fit(X, sample_weight=sample_weight) + + assert_array_equal(kmeans.labels_, expected_labels) + assert_allclose(kmeans.inertia_, expected_inertia) + assert_allclose(kmeans.cluster_centers_, expected_centers) + assert kmeans.n_iter_ == expected_n_iter + + +@pytest.mark.parametrize("array_constr", data_containers, ids=data_containers_ids) +@pytest.mark.parametrize("algo", ["lloyd", "elkan"]) +def test_kmeans_relocated_clusters(array_constr, algo): + # check that empty clusters are relocated as expected + X = array_constr([[0, 0], [0.5, 0], [0.5, 1], [1, 1]]) + + # second center too far from others points will be empty at first iter + init_centers = np.array([[0.5, 0.5], [3, 3]]) + + kmeans = KMeans(n_clusters=2, n_init=1, init=init_centers, algorithm=algo) + kmeans.fit(X) + + expected_n_iter = 3 + expected_inertia = 0.25 + assert_allclose(kmeans.inertia_, expected_inertia) + assert kmeans.n_iter_ == expected_n_iter + + # There are two acceptable ways of relocating clusters in this example, the output + # depends on how the argpartition strategy breaks ties. We accept both outputs. + try: + expected_labels = [0, 0, 1, 1] + expected_centers = [[0.25, 0], [0.75, 1]] + assert_array_equal(kmeans.labels_, expected_labels) + assert_allclose(kmeans.cluster_centers_, expected_centers) + except AssertionError: + expected_labels = [1, 1, 0, 0] + expected_centers = [[0.75, 1.0], [0.25, 0.0]] + assert_array_equal(kmeans.labels_, expected_labels) + assert_allclose(kmeans.cluster_centers_, expected_centers) + + +@pytest.mark.parametrize("array_constr", data_containers, ids=data_containers_ids) +def test_relocate_empty_clusters(array_constr): + # test for the _relocate_empty_clusters_(dense/sparse) helpers + + # Synthetic dataset with 3 obvious clusters of different sizes + X = np.array([-10.0, -9.5, -9, -8.5, -8, -1, 1, 9, 9.5, 10]).reshape(-1, 1) + X = array_constr(X) + sample_weight = np.ones(10) + + # centers all initialized to the first point of X + centers_old = np.array([-10.0, -10, -10]).reshape(-1, 1) + + # With this initialization, all points will be assigned to the first center + # At this point a center in centers_new is the weighted sum of the points + # it contains if it's not empty, otherwise it is the same as before. + centers_new = np.array([-16.5, -10, -10]).reshape(-1, 1) + weight_in_clusters = np.array([10.0, 0, 0]) + labels = np.zeros(10, dtype=np.int32) + + if array_constr is np.array: + _relocate_empty_clusters_dense( + X, sample_weight, centers_old, centers_new, weight_in_clusters, labels + ) + else: + _relocate_empty_clusters_sparse( + X.data, + X.indices, + X.indptr, + sample_weight, + centers_old, + centers_new, + weight_in_clusters, + labels, + ) + + # The relocation scheme will take the 2 points farthest from the center and + # assign them to the 2 empty clusters, i.e. points at 10 and at 9.9. The + # first center will be updated to contain the other 8 points. + assert_array_equal(weight_in_clusters, [8, 1, 1]) + assert_allclose(centers_new, [[-36], [10], [9.5]]) + + +@pytest.mark.parametrize("distribution", ["normal", "blobs"]) +@pytest.mark.parametrize("array_constr", data_containers, ids=data_containers_ids) +@pytest.mark.parametrize("tol", [1e-2, 1e-8, 1e-100, 0]) +def test_kmeans_elkan_results(distribution, array_constr, tol, global_random_seed): + # Check that results are identical between lloyd and elkan algorithms + rnd = np.random.RandomState(global_random_seed) + if distribution == "normal": + X = rnd.normal(size=(5000, 10)) + else: + X, _ = make_blobs(random_state=rnd) + X[X < 0] = 0 + X = array_constr(X) + + km_lloyd = KMeans(n_clusters=5, random_state=global_random_seed, n_init=1, tol=tol) + km_elkan = KMeans( + algorithm="elkan", + n_clusters=5, + random_state=global_random_seed, + n_init=1, + tol=tol, + ) + + km_lloyd.fit(X) + km_elkan.fit(X) + assert_allclose(km_elkan.cluster_centers_, km_lloyd.cluster_centers_) + assert_array_equal(km_elkan.labels_, km_lloyd.labels_) + assert km_elkan.n_iter_ == km_lloyd.n_iter_ + assert km_elkan.inertia_ == pytest.approx(km_lloyd.inertia_, rel=1e-6) + + +@pytest.mark.parametrize("algorithm", ["lloyd", "elkan"]) +def test_kmeans_convergence(algorithm, global_random_seed): + # Check that KMeans stops when convergence is reached when tol=0. (#16075) + rnd = np.random.RandomState(global_random_seed) + X = rnd.normal(size=(5000, 10)) + max_iter = 300 + + km = KMeans( + algorithm=algorithm, + n_clusters=5, + random_state=global_random_seed, + n_init=1, + tol=0, + max_iter=max_iter, + ).fit(X) + + assert km.n_iter_ < max_iter + + +@pytest.mark.parametrize("X_csr", X_as_any_csr) +def test_minibatch_update_consistency(X_csr, global_random_seed): + # Check that dense and sparse minibatch update give the same results + rng = np.random.RandomState(global_random_seed) + + centers_old = centers + rng.normal(size=centers.shape) + centers_old_csr = centers_old.copy() + + centers_new = np.zeros_like(centers_old) + centers_new_csr = np.zeros_like(centers_old_csr) + + weight_sums = np.zeros(centers_old.shape[0], dtype=X.dtype) + weight_sums_csr = np.zeros(centers_old.shape[0], dtype=X.dtype) + + sample_weight = np.ones(X.shape[0], dtype=X.dtype) + + # extract a small minibatch + X_mb = X[:10] + X_mb_csr = X_csr[:10] + sample_weight_mb = sample_weight[:10] + + # step 1: compute the dense minibatch update + old_inertia = _mini_batch_step( + X_mb, + sample_weight_mb, + centers_old, + centers_new, + weight_sums, + np.random.RandomState(global_random_seed), + random_reassign=False, + ) + assert old_inertia > 0.0 + + # compute the new inertia on the same batch to check that it decreased + labels, new_inertia = _labels_inertia(X_mb, sample_weight_mb, centers_new) + assert new_inertia > 0.0 + assert new_inertia < old_inertia + + # step 2: compute the sparse minibatch update + old_inertia_csr = _mini_batch_step( + X_mb_csr, + sample_weight_mb, + centers_old_csr, + centers_new_csr, + weight_sums_csr, + np.random.RandomState(global_random_seed), + random_reassign=False, + ) + assert old_inertia_csr > 0.0 + + # compute the new inertia on the same batch to check that it decreased + labels_csr, new_inertia_csr = _labels_inertia( + X_mb_csr, sample_weight_mb, centers_new_csr + ) + assert new_inertia_csr > 0.0 + assert new_inertia_csr < old_inertia_csr + + # step 3: check that sparse and dense updates lead to the same results + assert_array_equal(labels, labels_csr) + assert_allclose(centers_new, centers_new_csr) + assert_allclose(old_inertia, old_inertia_csr) + assert_allclose(new_inertia, new_inertia_csr) + + +def _check_fitted_model(km): + # check that the number of clusters centers and distinct labels match + # the expectation + centers = km.cluster_centers_ + assert centers.shape == (n_clusters, n_features) + + labels = km.labels_ + assert np.unique(labels).shape[0] == n_clusters + + # check that the labels assignment are perfect (up to a permutation) + assert_allclose(v_measure_score(true_labels, labels), 1.0) + assert km.inertia_ > 0.0 + + +@pytest.mark.parametrize( + "input_data", + [X] + X_as_any_csr, + ids=data_containers_ids, +) +@pytest.mark.parametrize( + "init", + ["random", "k-means++", centers, lambda X, k, random_state: centers], + ids=["random", "k-means++", "ndarray", "callable"], +) +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_all_init(Estimator, input_data, init): + # Check KMeans and MiniBatchKMeans with all possible init. + n_init = 10 if isinstance(init, str) else 1 + km = Estimator( + init=init, n_clusters=n_clusters, random_state=42, n_init=n_init + ).fit(input_data) + _check_fitted_model(km) + + +@pytest.mark.parametrize( + "init", + ["random", "k-means++", centers, lambda X, k, random_state: centers], + ids=["random", "k-means++", "ndarray", "callable"], +) +def test_minibatch_kmeans_partial_fit_init(init): + # Check MiniBatchKMeans init with partial_fit + n_init = 10 if isinstance(init, str) else 1 + km = MiniBatchKMeans( + init=init, n_clusters=n_clusters, random_state=0, n_init=n_init + ) + for i in range(100): + # "random" init requires many batches to recover the true labels. + km.partial_fit(X) + _check_fitted_model(km) + + +@pytest.mark.parametrize( + "init, expected_n_init", + [ + ("k-means++", 1), + ("random", "default"), + ( + lambda X, n_clusters, random_state: random_state.uniform( + size=(n_clusters, X.shape[1]) + ), + "default", + ), + ("array-like", 1), + ], +) +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_kmeans_init_auto_with_initial_centroids(Estimator, init, expected_n_init): + """Check that `n_init="auto"` chooses the right number of initializations. + Non-regression test for #26657: + https://github.com/scikit-learn/scikit-learn/pull/26657 + """ + n_sample, n_features, n_clusters = 100, 10, 5 + X = np.random.randn(n_sample, n_features) + if init == "array-like": + init = np.random.randn(n_clusters, n_features) + if expected_n_init == "default": + expected_n_init = 3 if Estimator is MiniBatchKMeans else 10 + + kmeans = Estimator(n_clusters=n_clusters, init=init, n_init="auto").fit(X) + assert kmeans._n_init == expected_n_init + + +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_fortran_aligned_data(Estimator, global_random_seed): + # Check that KMeans works with fortran-aligned data. + X_fortran = np.asfortranarray(X) + centers_fortran = np.asfortranarray(centers) + + km_c = Estimator( + n_clusters=n_clusters, init=centers, n_init=1, random_state=global_random_seed + ).fit(X) + km_f = Estimator( + n_clusters=n_clusters, + init=centers_fortran, + n_init=1, + random_state=global_random_seed, + ).fit(X_fortran) + assert_allclose(km_c.cluster_centers_, km_f.cluster_centers_) + assert_array_equal(km_c.labels_, km_f.labels_) + + +def test_minibatch_kmeans_verbose(): + # Check verbose mode of MiniBatchKMeans for better coverage. + km = MiniBatchKMeans(n_clusters=n_clusters, random_state=42, verbose=1) + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + km.fit(X) + finally: + sys.stdout = old_stdout + + +@pytest.mark.parametrize("algorithm", ["lloyd", "elkan"]) +@pytest.mark.parametrize("tol", [1e-2, 0]) +def test_kmeans_verbose(algorithm, tol, capsys): + # Check verbose mode of KMeans for better coverage. + X = np.random.RandomState(0).normal(size=(5000, 10)) + + KMeans( + algorithm=algorithm, + n_clusters=n_clusters, + random_state=42, + init="random", + n_init=1, + tol=tol, + verbose=1, + ).fit(X) + + captured = capsys.readouterr() + + assert re.search(r"Initialization complete", captured.out) + assert re.search(r"Iteration [0-9]+, inertia", captured.out) + + if tol == 0: + assert re.search(r"strict convergence", captured.out) + else: + assert re.search(r"center shift .* within tolerance", captured.out) + + +def test_minibatch_kmeans_warning_init_size(): + # Check that a warning is raised when init_size is smaller than n_clusters + with pytest.warns( + RuntimeWarning, match=r"init_size.* should be larger than n_clusters" + ): + MiniBatchKMeans(init_size=10, n_clusters=20).fit(X) + + +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_warning_n_init_precomputed_centers(Estimator): + # Check that a warning is raised when n_init > 1 and an array is passed for + # the init parameter. + with pytest.warns( + RuntimeWarning, + match="Explicit initial center position passed: performing only one init", + ): + Estimator(init=centers, n_clusters=n_clusters, n_init=10).fit(X) + + +def test_minibatch_sensible_reassign(global_random_seed): + # check that identical initial clusters are reassigned + # also a regression test for when there are more desired reassignments than + # samples. + zeroed_X, true_labels = make_blobs( + n_samples=100, centers=5, random_state=global_random_seed + ) + zeroed_X[::2, :] = 0 + + km = MiniBatchKMeans( + n_clusters=20, batch_size=10, random_state=global_random_seed, init="random" + ).fit(zeroed_X) + # there should not be too many exact zero cluster centers + num_non_zero_clusters = km.cluster_centers_.any(axis=1).sum() + assert num_non_zero_clusters > 9, f"{num_non_zero_clusters=} is too small" + + # do the same with batch-size > X.shape[0] (regression test) + km = MiniBatchKMeans( + n_clusters=20, batch_size=200, random_state=global_random_seed, init="random" + ).fit(zeroed_X) + # there should not be too many exact zero cluster centers + num_non_zero_clusters = km.cluster_centers_.any(axis=1).sum() + assert num_non_zero_clusters > 9, f"{num_non_zero_clusters=} is too small" + + # do the same with partial_fit API + km = MiniBatchKMeans(n_clusters=20, random_state=global_random_seed, init="random") + for i in range(100): + km.partial_fit(zeroed_X) + # there should not be too many exact zero cluster centers + num_non_zero_clusters = km.cluster_centers_.any(axis=1).sum() + assert num_non_zero_clusters > 9, f"{num_non_zero_clusters=} is too small" + + +@pytest.mark.parametrize( + "input_data", + [X] + X_as_any_csr, + ids=data_containers_ids, +) +def test_minibatch_reassign(input_data, global_random_seed): + # Check the reassignment part of the minibatch step with very high or very + # low reassignment ratio. + perfect_centers = np.empty((n_clusters, n_features)) + for i in range(n_clusters): + perfect_centers[i] = X[true_labels == i].mean(axis=0) + + sample_weight = np.ones(n_samples) + centers_new = np.empty_like(perfect_centers) + + # Give a perfect initialization, but a large reassignment_ratio, as a + # result many centers should be reassigned and the model should no longer + # be good + score_before = -_labels_inertia(input_data, sample_weight, perfect_centers, 1)[1] + + _mini_batch_step( + input_data, + sample_weight, + perfect_centers, + centers_new, + np.zeros(n_clusters), + np.random.RandomState(global_random_seed), + random_reassign=True, + reassignment_ratio=1, + ) + + score_after = -_labels_inertia(input_data, sample_weight, centers_new, 1)[1] + + assert score_before > score_after + + # Give a perfect initialization, with a small reassignment_ratio, + # no center should be reassigned. + _mini_batch_step( + input_data, + sample_weight, + perfect_centers, + centers_new, + np.zeros(n_clusters), + np.random.RandomState(global_random_seed), + random_reassign=True, + reassignment_ratio=1e-15, + ) + + assert_allclose(centers_new, perfect_centers) + + +def test_minibatch_with_many_reassignments(): + # Test for the case that the number of clusters to reassign is bigger + # than the batch_size. Run the test with 100 clusters and a batch_size of + # 10 because it turned out that these values ensure that the number of + # clusters to reassign is always bigger than the batch_size. + MiniBatchKMeans( + n_clusters=100, + batch_size=10, + init_size=n_samples, + random_state=42, + verbose=True, + ).fit(X) + + +def test_minibatch_kmeans_init_size(): + # Check the internal _init_size attribute of MiniBatchKMeans + + # default init size should be 3 * batch_size + km = MiniBatchKMeans(n_clusters=10, batch_size=5, n_init=1).fit(X) + assert km._init_size == 15 + + # if 3 * batch size < n_clusters, it should then be 3 * n_clusters + km = MiniBatchKMeans(n_clusters=10, batch_size=1, n_init=1).fit(X) + assert km._init_size == 30 + + # it should not be larger than n_samples + km = MiniBatchKMeans( + n_clusters=10, batch_size=5, n_init=1, init_size=n_samples + 1 + ).fit(X) + assert km._init_size == n_samples + + +@pytest.mark.parametrize("tol, max_no_improvement", [(1e-4, None), (0, 10)]) +def test_minibatch_declared_convergence(capsys, tol, max_no_improvement): + # Check convergence detection based on ewa batch inertia or on + # small center change. + X, _, centers = make_blobs(centers=3, random_state=0, return_centers=True) + + km = MiniBatchKMeans( + n_clusters=3, + init=centers, + batch_size=20, + tol=tol, + random_state=0, + max_iter=10, + n_init=1, + verbose=1, + max_no_improvement=max_no_improvement, + ) + + km.fit(X) + assert 1 < km.n_iter_ < 10 + + captured = capsys.readouterr() + if max_no_improvement is None: + assert "Converged (small centers change)" in captured.out + if tol == 0: + assert "Converged (lack of improvement in inertia)" in captured.out + + +def test_minibatch_iter_steps(): + # Check consistency of n_iter_ and n_steps_ attributes. + batch_size = 30 + n_samples = X.shape[0] + km = MiniBatchKMeans(n_clusters=3, batch_size=batch_size, random_state=0).fit(X) + + # n_iter_ is the number of started epochs + assert km.n_iter_ == np.ceil((km.n_steps_ * batch_size) / n_samples) + assert isinstance(km.n_iter_, int) + + # without stopping condition, max_iter should be reached + km = MiniBatchKMeans( + n_clusters=3, + batch_size=batch_size, + random_state=0, + tol=0, + max_no_improvement=None, + max_iter=10, + ).fit(X) + + assert km.n_iter_ == 10 + assert km.n_steps_ == (10 * n_samples) // batch_size + assert isinstance(km.n_steps_, int) + + +def test_kmeans_copyx(): + # Check that copy_x=False returns nearly equal X after de-centering. + my_X = X.copy() + km = KMeans(copy_x=False, n_clusters=n_clusters, random_state=42) + km.fit(my_X) + _check_fitted_model(km) + + # check that my_X is de-centered + assert_allclose(my_X, X) + + +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_score_max_iter(Estimator, global_random_seed): + # Check that fitting KMeans or MiniBatchKMeans with more iterations gives + # better score + X = np.random.RandomState(global_random_seed).randn(100, 10) + + km1 = Estimator(n_init=1, random_state=global_random_seed, max_iter=1) + s1 = km1.fit(X).score(X) + km2 = Estimator(n_init=1, random_state=global_random_seed, max_iter=10) + s2 = km2.fit(X).score(X) + assert s2 > s1 + + +@pytest.mark.parametrize("array_constr", data_containers, ids=data_containers_ids) +@pytest.mark.parametrize( + "Estimator, algorithm", + [(KMeans, "lloyd"), (KMeans, "elkan"), (MiniBatchKMeans, None)], +) +@pytest.mark.parametrize("max_iter", [2, 100]) +def test_kmeans_predict( + Estimator, algorithm, array_constr, max_iter, global_dtype, global_random_seed +): + # Check the predict method and the equivalence between fit.predict and + # fit_predict. + X, _ = make_blobs( + n_samples=200, n_features=10, centers=10, random_state=global_random_seed + ) + X = array_constr(X, dtype=global_dtype) + + km = Estimator( + n_clusters=10, + init="random", + n_init=10, + max_iter=max_iter, + random_state=global_random_seed, + ) + if algorithm is not None: + km.set_params(algorithm=algorithm) + km.fit(X) + labels = km.labels_ + + # re-predict labels for training set using predict + pred = km.predict(X) + assert_array_equal(pred, labels) + + # re-predict labels for training set using fit_predict + pred = km.fit_predict(X) + assert_array_equal(pred, labels) + + # predict centroid labels + pred = km.predict(km.cluster_centers_) + assert_array_equal(pred, np.arange(10)) + + +@pytest.mark.parametrize("X_csr", X_as_any_csr) +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_dense_sparse(Estimator, X_csr, global_random_seed): + # Check that the results are the same for dense and sparse input. + sample_weight = np.random.RandomState(global_random_seed).random_sample( + (n_samples,) + ) + km_dense = Estimator( + n_clusters=n_clusters, random_state=global_random_seed, n_init=1 + ) + km_dense.fit(X, sample_weight=sample_weight) + km_sparse = Estimator( + n_clusters=n_clusters, random_state=global_random_seed, n_init=1 + ) + km_sparse.fit(X_csr, sample_weight=sample_weight) + + assert_array_equal(km_dense.labels_, km_sparse.labels_) + assert_allclose(km_dense.cluster_centers_, km_sparse.cluster_centers_) + + +@pytest.mark.parametrize("X_csr", X_as_any_csr) +@pytest.mark.parametrize( + "init", ["random", "k-means++", centers], ids=["random", "k-means++", "ndarray"] +) +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_predict_dense_sparse(Estimator, init, X_csr): + # check that models trained on sparse input also works for dense input at + # predict time and vice versa. + n_init = 10 if isinstance(init, str) else 1 + km = Estimator(n_clusters=n_clusters, init=init, n_init=n_init, random_state=0) + + km.fit(X_csr) + assert_array_equal(km.predict(X), km.labels_) + + km.fit(X) + assert_array_equal(km.predict(X_csr), km.labels_) + + +@pytest.mark.parametrize("array_constr", data_containers, ids=data_containers_ids) +@pytest.mark.parametrize("dtype", [np.int32, np.int64]) +@pytest.mark.parametrize("init", ["k-means++", "ndarray"]) +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_integer_input(Estimator, array_constr, dtype, init, global_random_seed): + # Check that KMeans and MiniBatchKMeans work with integer input. + X_dense = np.array([[0, 0], [10, 10], [12, 9], [-1, 1], [2, 0], [8, 10]]) + X = array_constr(X_dense, dtype=dtype) + + n_init = 1 if init == "ndarray" else 10 + init = X_dense[:2] if init == "ndarray" else init + + km = Estimator( + n_clusters=2, init=init, n_init=n_init, random_state=global_random_seed + ) + if Estimator is MiniBatchKMeans: + km.set_params(batch_size=2) + + km.fit(X) + + # Internally integer input should be converted to float64 + assert km.cluster_centers_.dtype == np.float64 + + expected_labels = [0, 1, 1, 0, 0, 1] + assert_allclose(v_measure_score(km.labels_, expected_labels), 1.0) + + # Same with partial_fit (#14314) + if Estimator is MiniBatchKMeans: + km = clone(km).partial_fit(X) + assert km.cluster_centers_.dtype == np.float64 + + +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_transform(Estimator, global_random_seed): + # Check the transform method + km = Estimator(n_clusters=n_clusters, random_state=global_random_seed).fit(X) + + # Transorfming cluster_centers_ should return the pairwise distances + # between centers + Xt = km.transform(km.cluster_centers_) + assert_allclose(Xt, pairwise_distances(km.cluster_centers_)) + # In particular, diagonal must be 0 + assert_array_equal(Xt.diagonal(), np.zeros(n_clusters)) + + # Transorfming X should return the pairwise distances between X and the + # centers + Xt = km.transform(X) + assert_allclose(Xt, pairwise_distances(X, km.cluster_centers_)) + + +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_fit_transform(Estimator, global_random_seed): + # Check equivalence between fit.transform and fit_transform + X1 = Estimator(random_state=global_random_seed, n_init=1).fit(X).transform(X) + X2 = Estimator(random_state=global_random_seed, n_init=1).fit_transform(X) + assert_allclose(X1, X2) + + +def test_n_init(global_random_seed): + # Check that increasing the number of init increases the quality + previous_inertia = np.inf + for n_init in [1, 5, 10]: + # set max_iter=1 to avoid finding the global minimum and get the same + # inertia each time + km = KMeans( + n_clusters=n_clusters, + init="random", + n_init=n_init, + random_state=global_random_seed, + max_iter=1, + ).fit(X) + assert km.inertia_ <= previous_inertia + + +def test_k_means_function(global_random_seed): + # test calling the k_means function directly + cluster_centers, labels, inertia = k_means( + X, n_clusters=n_clusters, sample_weight=None, random_state=global_random_seed + ) + + assert cluster_centers.shape == (n_clusters, n_features) + assert np.unique(labels).shape[0] == n_clusters + + # check that the labels assignment are perfect (up to a permutation) + assert_allclose(v_measure_score(true_labels, labels), 1.0) + assert inertia > 0.0 + + +@pytest.mark.parametrize( + "input_data", + [X] + X_as_any_csr, + ids=data_containers_ids, +) +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_float_precision(Estimator, input_data, global_random_seed): + # Check that the results are the same for single and double precision. + km = Estimator(n_init=1, random_state=global_random_seed) + + inertia = {} + Xt = {} + centers = {} + labels = {} + + for dtype in [np.float64, np.float32]: + X = input_data.astype(dtype, copy=False) + km.fit(X) + + inertia[dtype] = km.inertia_ + Xt[dtype] = km.transform(X) + centers[dtype] = km.cluster_centers_ + labels[dtype] = km.labels_ + + # dtype of cluster centers has to be the dtype of the input data + assert km.cluster_centers_.dtype == dtype + + # same with partial_fit + if Estimator is MiniBatchKMeans: + km.partial_fit(X[0:3]) + assert km.cluster_centers_.dtype == dtype + + # compare arrays with low precision since the difference between 32 and + # 64 bit comes from an accumulation of rounding errors. + assert_allclose(inertia[np.float32], inertia[np.float64], rtol=1e-4) + assert_allclose(Xt[np.float32], Xt[np.float64], atol=Xt[np.float64].max() * 1e-4) + assert_allclose( + centers[np.float32], centers[np.float64], atol=centers[np.float64].max() * 1e-4 + ) + assert_array_equal(labels[np.float32], labels[np.float64]) + + +@pytest.mark.parametrize("dtype", [np.int32, np.int64, np.float32, np.float64]) +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_centers_not_mutated(Estimator, dtype): + # Check that KMeans and MiniBatchKMeans won't mutate the user provided + # init centers silently even if input data and init centers have the same + # type. + X_new_type = X.astype(dtype, copy=False) + centers_new_type = centers.astype(dtype, copy=False) + + km = Estimator(init=centers_new_type, n_clusters=n_clusters, n_init=1) + km.fit(X_new_type) + + assert not np.may_share_memory(km.cluster_centers_, centers_new_type) + + +@pytest.mark.parametrize( + "input_data", + [X] + X_as_any_csr, + ids=data_containers_ids, +) +def test_kmeans_init_fitted_centers(input_data): + # Check that starting fitting from a local optimum shouldn't change the + # solution + km1 = KMeans(n_clusters=n_clusters).fit(input_data) + km2 = KMeans(n_clusters=n_clusters, init=km1.cluster_centers_, n_init=1).fit( + input_data + ) + + assert_allclose(km1.cluster_centers_, km2.cluster_centers_) + + +def test_kmeans_warns_less_centers_than_unique_points(global_random_seed): + # Check KMeans when the number of found clusters is smaller than expected + X = np.asarray([[0, 0], [0, 1], [1, 0], [1, 0]]) # last point is duplicated + km = KMeans(n_clusters=4, random_state=global_random_seed) + + # KMeans should warn that fewer labels than cluster centers have been used + msg = ( + r"Number of distinct clusters \(3\) found smaller than " + r"n_clusters \(4\). Possibly due to duplicate points in X." + ) + with pytest.warns(ConvergenceWarning, match=msg): + km.fit(X) + # only three distinct points, so only three clusters + # can have points assigned to them + assert set(km.labels_) == set(range(3)) + + +def _sort_centers(centers): + return np.sort(centers, axis=0) + + +def test_weighted_vs_repeated(global_random_seed): + # Check that a sample weight of N should yield the same result as an N-fold + # repetition of the sample. Valid only if init is precomputed, otherwise + # rng produces different results. Not valid for MinibatchKMeans due to rng + # to extract minibatches. + sample_weight = np.random.RandomState(global_random_seed).randint( + 1, 5, size=n_samples + ) + X_repeat = np.repeat(X, sample_weight, axis=0) + + km = KMeans( + init=centers, n_init=1, n_clusters=n_clusters, random_state=global_random_seed + ) + + km_weighted = clone(km).fit(X, sample_weight=sample_weight) + repeated_labels = np.repeat(km_weighted.labels_, sample_weight) + km_repeated = clone(km).fit(X_repeat) + + assert_array_equal(km_repeated.labels_, repeated_labels) + assert_allclose(km_weighted.inertia_, km_repeated.inertia_) + assert_allclose( + _sort_centers(km_weighted.cluster_centers_), + _sort_centers(km_repeated.cluster_centers_), + ) + + +@pytest.mark.parametrize( + "input_data", + [X] + X_as_any_csr, + ids=data_containers_ids, +) +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_unit_weights_vs_no_weights(Estimator, input_data, global_random_seed): + # Check that not passing sample weights should be equivalent to passing + # sample weights all equal to one. + sample_weight = np.ones(n_samples) + + km = Estimator(n_clusters=n_clusters, random_state=global_random_seed, n_init=1) + km_none = clone(km).fit(input_data, sample_weight=None) + km_ones = clone(km).fit(input_data, sample_weight=sample_weight) + + assert_array_equal(km_none.labels_, km_ones.labels_) + assert_allclose(km_none.cluster_centers_, km_ones.cluster_centers_) + + +@pytest.mark.parametrize( + "input_data", + [X] + X_as_any_csr, + ids=data_containers_ids, +) +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_scaled_weights(Estimator, input_data, global_random_seed): + # Check that scaling all sample weights by a common factor + # shouldn't change the result + sample_weight = np.random.RandomState(global_random_seed).uniform(size=n_samples) + + km = Estimator(n_clusters=n_clusters, random_state=global_random_seed, n_init=1) + km_orig = clone(km).fit(input_data, sample_weight=sample_weight) + km_scaled = clone(km).fit(input_data, sample_weight=0.5 * sample_weight) + + assert_array_equal(km_orig.labels_, km_scaled.labels_) + assert_allclose(km_orig.cluster_centers_, km_scaled.cluster_centers_) + + +def test_kmeans_elkan_iter_attribute(): + # Regression test on bad n_iter_ value. Previous bug n_iter_ was one off + # it's right value (#11340). + km = KMeans(algorithm="elkan", max_iter=1).fit(X) + assert km.n_iter_ == 1 + + +@pytest.mark.parametrize("array_constr", data_containers, ids=data_containers_ids) +def test_kmeans_empty_cluster_relocated(array_constr): + # check that empty clusters are correctly relocated when using sample + # weights (#13486) + X = array_constr([[-1], [1]]) + sample_weight = [1.9, 0.1] + init = np.array([[-1], [10]]) + + km = KMeans(n_clusters=2, init=init, n_init=1) + km.fit(X, sample_weight=sample_weight) + + assert len(set(km.labels_)) == 2 + assert_allclose(km.cluster_centers_, [[-1], [1]]) + + +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_result_equal_in_diff_n_threads(Estimator, global_random_seed): + # Check that KMeans/MiniBatchKMeans give the same results in parallel mode + # than in sequential mode. + rnd = np.random.RandomState(global_random_seed) + X = rnd.normal(size=(50, 10)) + + with _get_threadpool_controller().limit(limits=1, user_api="openmp"): + result_1 = ( + Estimator(n_clusters=n_clusters, random_state=global_random_seed) + .fit(X) + .labels_ + ) + with _get_threadpool_controller().limit(limits=2, user_api="openmp"): + result_2 = ( + Estimator(n_clusters=n_clusters, random_state=global_random_seed) + .fit(X) + .labels_ + ) + assert_array_equal(result_1, result_2) + + +def test_warning_elkan_1_cluster(): + # Check warning messages specific to KMeans + with pytest.warns( + RuntimeWarning, + match="algorithm='elkan' doesn't make sense for a single cluster", + ): + KMeans(n_clusters=1, algorithm="elkan").fit(X) + + +@pytest.mark.parametrize("array_constr", data_containers, ids=data_containers_ids) +@pytest.mark.parametrize("algo", ["lloyd", "elkan"]) +def test_k_means_1_iteration(array_constr, algo, global_random_seed): + # check the results after a single iteration (E-step M-step E-step) by + # comparing against a pure python implementation. + X = np.random.RandomState(global_random_seed).uniform(size=(100, 5)) + init_centers = X[:5] + X = array_constr(X) + + def py_kmeans(X, init): + new_centers = init.copy() + labels = pairwise_distances_argmin(X, init) + for label in range(init.shape[0]): + new_centers[label] = X[labels == label].mean(axis=0) + labels = pairwise_distances_argmin(X, new_centers) + return labels, new_centers + + py_labels, py_centers = py_kmeans(X, init_centers) + + cy_kmeans = KMeans( + n_clusters=5, n_init=1, init=init_centers, algorithm=algo, max_iter=1 + ).fit(X) + cy_labels = cy_kmeans.labels_ + cy_centers = cy_kmeans.cluster_centers_ + + assert_array_equal(py_labels, cy_labels) + assert_allclose(py_centers, cy_centers) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +@pytest.mark.parametrize("squared", [True, False]) +def test_euclidean_distance(dtype, squared, global_random_seed): + # Check that the _euclidean_(dense/sparse)_dense helpers produce correct + # results + rng = np.random.RandomState(global_random_seed) + a_sparse = sp.random( + 1, 100, density=0.5, format="csr", random_state=rng, dtype=dtype + ) + a_dense = a_sparse.toarray().reshape(-1) + b = rng.randn(100).astype(dtype, copy=False) + b_squared_norm = (b**2).sum() + + expected = ((a_dense - b) ** 2).sum() + expected = expected if squared else np.sqrt(expected) + + distance_dense_dense = _euclidean_dense_dense_wrapper(a_dense, b, squared) + distance_sparse_dense = _euclidean_sparse_dense_wrapper( + a_sparse.data, a_sparse.indices, b, b_squared_norm, squared + ) + + rtol = 1e-4 if dtype == np.float32 else 1e-7 + assert_allclose(distance_dense_dense, distance_sparse_dense, rtol=rtol) + assert_allclose(distance_dense_dense, expected, rtol=rtol) + assert_allclose(distance_sparse_dense, expected, rtol=rtol) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_inertia(dtype, global_random_seed): + # Check that the _inertia_(dense/sparse) helpers produce correct results. + rng = np.random.RandomState(global_random_seed) + X_sparse = sp.random( + 100, 10, density=0.5, format="csr", random_state=rng, dtype=dtype + ) + X_dense = X_sparse.toarray() + sample_weight = rng.randn(100).astype(dtype, copy=False) + centers = rng.randn(5, 10).astype(dtype, copy=False) + labels = rng.randint(5, size=100, dtype=np.int32) + + distances = ((X_dense - centers[labels]) ** 2).sum(axis=1) + expected = np.sum(distances * sample_weight) + + inertia_dense = _inertia_dense(X_dense, sample_weight, centers, labels, n_threads=1) + inertia_sparse = _inertia_sparse( + X_sparse, sample_weight, centers, labels, n_threads=1 + ) + + rtol = 1e-4 if dtype == np.float32 else 1e-6 + assert_allclose(inertia_dense, inertia_sparse, rtol=rtol) + assert_allclose(inertia_dense, expected, rtol=rtol) + assert_allclose(inertia_sparse, expected, rtol=rtol) + + # Check the single_label parameter. + label = 1 + mask = labels == label + distances = ((X_dense[mask] - centers[label]) ** 2).sum(axis=1) + expected = np.sum(distances * sample_weight[mask]) + + inertia_dense = _inertia_dense( + X_dense, sample_weight, centers, labels, n_threads=1, single_label=label + ) + inertia_sparse = _inertia_sparse( + X_sparse, sample_weight, centers, labels, n_threads=1, single_label=label + ) + + assert_allclose(inertia_dense, inertia_sparse, rtol=rtol) + assert_allclose(inertia_dense, expected, rtol=rtol) + assert_allclose(inertia_sparse, expected, rtol=rtol) + + +@pytest.mark.parametrize("Klass, default_n_init", [(KMeans, 10), (MiniBatchKMeans, 3)]) +def test_n_init_auto(Klass, default_n_init): + est = Klass(n_init="auto", init="k-means++") + est.fit(X) + assert est._n_init == 1 + + est = Klass(n_init="auto", init="random") + est.fit(X) + assert est._n_init == 10 if Klass.__name__ == "KMeans" else 3 + + +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_sample_weight_unchanged(Estimator): + # Check that sample_weight is not modified in place by KMeans (#17204) + X = np.array([[1], [2], [4]]) + sample_weight = np.array([0.5, 0.2, 0.3]) + Estimator(n_clusters=2, random_state=0).fit(X, sample_weight=sample_weight) + + assert_array_equal(sample_weight, np.array([0.5, 0.2, 0.3])) + + +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +@pytest.mark.parametrize( + "param, match", + [ + ({"n_clusters": n_samples + 1}, r"n_samples.* should be >= n_clusters"), + ( + {"init": X[:2]}, + r"The shape of the initial centers .* does not match " + r"the number of clusters", + ), + ( + {"init": lambda X_, k, random_state: X_[:2]}, + r"The shape of the initial centers .* does not match " + r"the number of clusters", + ), + ( + {"init": X[:8, :2]}, + r"The shape of the initial centers .* does not match " + r"the number of features of the data", + ), + ( + {"init": lambda X_, k, random_state: X_[:8, :2]}, + r"The shape of the initial centers .* does not match " + r"the number of features of the data", + ), + ], +) +def test_wrong_params(Estimator, param, match): + # Check that error are raised with clear error message when wrong values + # are passed for the parameters + # Set n_init=1 by default to avoid warning with precomputed init + km = Estimator(n_init=1) + with pytest.raises(ValueError, match=match): + km.set_params(**param).fit(X) + + +@pytest.mark.parametrize( + "param, match", + [ + ( + {"x_squared_norms": X[:2]}, + r"The length of x_squared_norms .* should " + r"be equal to the length of n_samples", + ), + ], +) +def test_kmeans_plusplus_wrong_params(param, match): + with pytest.raises(ValueError, match=match): + kmeans_plusplus(X, n_clusters, **param) + + +@pytest.mark.parametrize( + "input_data", + [X] + X_as_any_csr, +) +@pytest.mark.parametrize("dtype", [np.float64, np.float32]) +def test_kmeans_plusplus_output(input_data, dtype, global_random_seed): + # Check for the correct number of seeds and all positive values + data = input_data.astype(dtype) + centers, indices = kmeans_plusplus( + data, n_clusters, random_state=global_random_seed + ) + + # Check there are the correct number of indices and that all indices are + # positive and within the number of samples + assert indices.shape[0] == n_clusters + assert (indices >= 0).all() + assert (indices <= data.shape[0]).all() + + # Check for the correct number of seeds and that they are bound by the data + assert centers.shape[0] == n_clusters + assert (centers.max(axis=0) <= data.max(axis=0)).all() + assert (centers.min(axis=0) >= data.min(axis=0)).all() + + # Check that indices correspond to reported centers + # Use X for comparison rather than data, test still works against centers + # calculated with sparse data. + assert_allclose(X[indices].astype(dtype), centers) + + +@pytest.mark.parametrize("x_squared_norms", [row_norms(X, squared=True), None]) +def test_kmeans_plusplus_norms(x_squared_norms): + # Check that defining x_squared_norms returns the same as default=None. + centers, indices = kmeans_plusplus(X, n_clusters, x_squared_norms=x_squared_norms) + + assert_allclose(X[indices], centers) + + +def test_kmeans_plusplus_dataorder(global_random_seed): + # Check that memory layout does not effect result + centers_c, _ = kmeans_plusplus(X, n_clusters, random_state=global_random_seed) + + X_fortran = np.asfortranarray(X) + + centers_fortran, _ = kmeans_plusplus( + X_fortran, n_clusters, random_state=global_random_seed + ) + + assert_allclose(centers_c, centers_fortran) + + +def test_is_same_clustering(): + # Sanity check for the _is_same_clustering utility function + labels1 = np.array([1, 0, 0, 1, 2, 0, 2, 1], dtype=np.int32) + assert _is_same_clustering(labels1, labels1, 3) + + # these other labels represent the same clustering since we can retrieve the first + # labels by simply renaming the labels: 0 -> 1, 1 -> 2, 2 -> 0. + labels2 = np.array([0, 2, 2, 0, 1, 2, 1, 0], dtype=np.int32) + assert _is_same_clustering(labels1, labels2, 3) + + # these other labels do not represent the same clustering since not all ones are + # mapped to a same value + labels3 = np.array([1, 0, 0, 2, 2, 0, 2, 1], dtype=np.int32) + assert not _is_same_clustering(labels1, labels3, 3) + + +@pytest.mark.parametrize( + "kwargs", ({"init": np.str_("k-means++")}, {"init": [[0, 0], [1, 1]], "n_init": 1}) +) +def test_kmeans_with_array_like_or_np_scalar_init(kwargs): + """Check that init works with numpy scalar strings. + + Non-regression test for #21964. + """ + X = np.asarray([[0, 0], [0.5, 0], [0.5, 1], [1, 1]], dtype=np.float64) + + clustering = KMeans(n_clusters=2, **kwargs) + # Does not raise + clustering.fit(X) + + +@pytest.mark.parametrize( + "Klass, method", + [(KMeans, "fit"), (MiniBatchKMeans, "fit"), (MiniBatchKMeans, "partial_fit")], +) +def test_feature_names_out(Klass, method): + """Check `feature_names_out` for `KMeans` and `MiniBatchKMeans`.""" + class_name = Klass.__name__.lower() + kmeans = Klass() + getattr(kmeans, method)(X) + n_clusters = kmeans.cluster_centers_.shape[0] + + names_out = kmeans.get_feature_names_out() + assert_array_equal([f"{class_name}{i}" for i in range(n_clusters)], names_out) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS + [None]) +def test_predict_does_not_change_cluster_centers(csr_container): + """Check that predict does not change cluster centers. + + Non-regression test for gh-24253. + """ + X, _ = make_blobs(n_samples=200, n_features=10, centers=10, random_state=0) + if csr_container is not None: + X = csr_container(X) + + kmeans = KMeans() + y_pred1 = kmeans.fit_predict(X) + # Make cluster_centers readonly + kmeans.cluster_centers_ = create_memmap_backed_data(kmeans.cluster_centers_) + kmeans.labels_ = create_memmap_backed_data(kmeans.labels_) + + y_pred2 = kmeans.predict(X) + assert_array_equal(y_pred1, y_pred2) + + +@pytest.mark.parametrize("init", ["k-means++", "random"]) +def test_sample_weight_init(init, global_random_seed): + """Check that sample weight is used during init. + + `_init_centroids` is shared across all classes inheriting from _BaseKMeans so + it's enough to check for KMeans. + """ + rng = np.random.RandomState(global_random_seed) + X, _ = make_blobs( + n_samples=200, n_features=10, centers=10, random_state=global_random_seed + ) + x_squared_norms = row_norms(X, squared=True) + + kmeans = KMeans() + clusters_weighted = kmeans._init_centroids( + X=X, + x_squared_norms=x_squared_norms, + init=init, + sample_weight=rng.uniform(size=X.shape[0]), + n_centroids=5, + random_state=np.random.RandomState(global_random_seed), + ) + clusters = kmeans._init_centroids( + X=X, + x_squared_norms=x_squared_norms, + init=init, + sample_weight=np.ones(X.shape[0]), + n_centroids=5, + random_state=np.random.RandomState(global_random_seed), + ) + with pytest.raises(AssertionError): + assert_allclose(clusters_weighted, clusters) + + +@pytest.mark.parametrize("init", ["k-means++", "random"]) +def test_sample_weight_zero(init, global_random_seed): + """Check that if sample weight is 0, this sample won't be chosen. + + `_init_centroids` is shared across all classes inheriting from _BaseKMeans so + it's enough to check for KMeans. + """ + rng = np.random.RandomState(global_random_seed) + X, _ = make_blobs( + n_samples=100, n_features=5, centers=5, random_state=global_random_seed + ) + sample_weight = rng.uniform(size=X.shape[0]) + sample_weight[::2] = 0 + x_squared_norms = row_norms(X, squared=True) + + kmeans = KMeans() + clusters_weighted = kmeans._init_centroids( + X=X, + x_squared_norms=x_squared_norms, + init=init, + sample_weight=sample_weight, + n_centroids=10, + random_state=np.random.RandomState(global_random_seed), + ) + # No center should be one of the 0 sample weight point + # (i.e. be at a distance=0 from it) + d = euclidean_distances(X[::2], clusters_weighted) + assert not np.any(np.isclose(d, 0)) + + +@pytest.mark.parametrize("array_constr", data_containers, ids=data_containers_ids) +@pytest.mark.parametrize("algorithm", ["lloyd", "elkan"]) +def test_relocating_with_duplicates(algorithm, array_constr): + """Check that kmeans stops when there are more centers than non-duplicate samples + + Non-regression test for issue: + https://github.com/scikit-learn/scikit-learn/issues/28055 + """ + X = np.array([[0, 0], [1, 1], [1, 1], [1, 0], [0, 1]]) + km = KMeans(n_clusters=5, init=X, algorithm=algorithm) + + msg = r"Number of distinct clusters \(4\) found smaller than n_clusters \(5\)" + with pytest.warns(ConvergenceWarning, match=msg): + km.fit(array_constr(X)) + + assert km.n_iter_ == 1 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_mean_shift.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_mean_shift.py new file mode 100644 index 0000000000000000000000000000000000000000..7216a064ccbc729de42688a48cae3b0be6e89bfa --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_mean_shift.py @@ -0,0 +1,215 @@ +""" +Testing for mean shift clustering methods + +""" + +import warnings + +import numpy as np +import pytest + +from sklearn.cluster import MeanShift, estimate_bandwidth, get_bin_seeds, mean_shift +from sklearn.datasets import make_blobs +from sklearn.metrics import v_measure_score +from sklearn.utils._testing import assert_allclose, assert_array_equal + +n_clusters = 3 +centers = np.array([[1, 1], [-1, -1], [1, -1]]) + 10 +X, _ = make_blobs( + n_samples=300, + n_features=2, + centers=centers, + cluster_std=0.4, + shuffle=True, + random_state=11, +) + + +def test_convergence_of_1d_constant_data(): + # Test convergence using 1D constant data + # Non-regression test for: + # https://github.com/scikit-learn/scikit-learn/issues/28926 + model = MeanShift() + n_iter = model.fit(np.ones(10).reshape(-1, 1)).n_iter_ + assert n_iter < model.max_iter + + +def test_estimate_bandwidth(): + # Test estimate_bandwidth + bandwidth = estimate_bandwidth(X, n_samples=200) + assert 0.9 <= bandwidth <= 1.5 + + +def test_estimate_bandwidth_1sample(global_dtype): + # Test estimate_bandwidth when n_samples=1 and quantile<1, so that + # n_neighbors is set to 1. + bandwidth = estimate_bandwidth( + X.astype(global_dtype, copy=False), n_samples=1, quantile=0.3 + ) + + assert bandwidth.dtype == X.dtype + assert bandwidth == pytest.approx(0.0, abs=1e-5) + + +@pytest.mark.parametrize( + "bandwidth, cluster_all, expected, first_cluster_label", + [(1.2, True, 3, 0), (1.2, False, 4, -1)], +) +def test_mean_shift( + global_dtype, bandwidth, cluster_all, expected, first_cluster_label +): + # Test MeanShift algorithm + X_with_global_dtype = X.astype(global_dtype, copy=False) + ms = MeanShift(bandwidth=bandwidth, cluster_all=cluster_all) + labels = ms.fit(X_with_global_dtype).labels_ + labels_unique = np.unique(labels) + n_clusters_ = len(labels_unique) + assert n_clusters_ == expected + assert labels_unique[0] == first_cluster_label + assert ms.cluster_centers_.dtype == global_dtype + + cluster_centers, labels_mean_shift = mean_shift( + X_with_global_dtype, cluster_all=cluster_all + ) + labels_mean_shift_unique = np.unique(labels_mean_shift) + n_clusters_mean_shift = len(labels_mean_shift_unique) + assert n_clusters_mean_shift == expected + assert labels_mean_shift_unique[0] == first_cluster_label + assert cluster_centers.dtype == global_dtype + + +def test_parallel(global_dtype, global_random_seed): + centers = np.array([[1, 1], [-1, -1], [1, -1]]) + 10 + X, _ = make_blobs( + n_samples=50, + n_features=2, + centers=centers, + cluster_std=0.4, + shuffle=True, + random_state=global_random_seed, + ) + + X = X.astype(global_dtype, copy=False) + + ms1 = MeanShift(n_jobs=2) + ms1.fit(X) + + ms2 = MeanShift() + ms2.fit(X) + + assert_allclose(ms1.cluster_centers_, ms2.cluster_centers_) + assert ms1.cluster_centers_.dtype == ms2.cluster_centers_.dtype + assert_array_equal(ms1.labels_, ms2.labels_) + + +def test_meanshift_predict(global_dtype): + # Test MeanShift.predict + ms = MeanShift(bandwidth=1.2) + X_with_global_dtype = X.astype(global_dtype, copy=False) + labels = ms.fit_predict(X_with_global_dtype) + labels2 = ms.predict(X_with_global_dtype) + assert_array_equal(labels, labels2) + + +def test_meanshift_all_orphans(): + # init away from the data, crash with a sensible warning + ms = MeanShift(bandwidth=0.1, seeds=[[-9, -9], [-10, -10]]) + msg = "No point was within bandwidth=0.1" + with pytest.raises(ValueError, match=msg): + ms.fit( + X, + ) + + +def test_unfitted(): + # Non-regression: before fit, there should be not fitted attributes. + ms = MeanShift() + assert not hasattr(ms, "cluster_centers_") + assert not hasattr(ms, "labels_") + + +def test_cluster_intensity_tie(global_dtype): + X = np.array([[1, 1], [2, 1], [1, 0], [4, 7], [3, 5], [3, 6]], dtype=global_dtype) + c1 = MeanShift(bandwidth=2).fit(X) + + X = np.array([[4, 7], [3, 5], [3, 6], [1, 1], [2, 1], [1, 0]], dtype=global_dtype) + c2 = MeanShift(bandwidth=2).fit(X) + assert_array_equal(c1.labels_, [1, 1, 1, 0, 0, 0]) + assert_array_equal(c2.labels_, [0, 0, 0, 1, 1, 1]) + + +def test_bin_seeds(global_dtype): + # Test the bin seeding technique which can be used in the mean shift + # algorithm + # Data is just 6 points in the plane + X = np.array( + [[1.0, 1.0], [1.4, 1.4], [1.8, 1.2], [2.0, 1.0], [2.1, 1.1], [0.0, 0.0]], + dtype=global_dtype, + ) + + # With a bin coarseness of 1.0 and min_bin_freq of 1, 3 bins should be + # found + ground_truth = {(1.0, 1.0), (2.0, 1.0), (0.0, 0.0)} + test_bins = get_bin_seeds(X, 1, 1) + test_result = set(tuple(p) for p in test_bins) + assert len(ground_truth.symmetric_difference(test_result)) == 0 + + # With a bin coarseness of 1.0 and min_bin_freq of 2, 2 bins should be + # found + ground_truth = {(1.0, 1.0), (2.0, 1.0)} + test_bins = get_bin_seeds(X, 1, 2) + test_result = set(tuple(p) for p in test_bins) + assert len(ground_truth.symmetric_difference(test_result)) == 0 + + # With a bin size of 0.01 and min_bin_freq of 1, 6 bins should be found + # we bail and use the whole data here. + with warnings.catch_warnings(record=True): + test_bins = get_bin_seeds(X, 0.01, 1) + assert_allclose(test_bins, X) + + # tight clusters around [0, 0] and [1, 1], only get two bins + X, _ = make_blobs( + n_samples=100, + n_features=2, + centers=[[0, 0], [1, 1]], + cluster_std=0.1, + random_state=0, + ) + X = X.astype(global_dtype, copy=False) + test_bins = get_bin_seeds(X, 1) + assert_array_equal(test_bins, [[0, 0], [1, 1]]) + + +@pytest.mark.parametrize("max_iter", [1, 100]) +def test_max_iter(max_iter): + clusters1, _ = mean_shift(X, max_iter=max_iter) + ms = MeanShift(max_iter=max_iter).fit(X) + clusters2 = ms.cluster_centers_ + + assert ms.n_iter_ <= ms.max_iter + assert len(clusters1) == len(clusters2) + + for c1, c2 in zip(clusters1, clusters2): + assert np.allclose(c1, c2) + + +def test_mean_shift_zero_bandwidth(global_dtype): + # Check that mean shift works when the estimated bandwidth is 0. + X = np.array([1, 1, 1, 2, 2, 2, 3, 3], dtype=global_dtype).reshape(-1, 1) + + # estimate_bandwidth with default args returns 0 on this dataset + bandwidth = estimate_bandwidth(X) + assert bandwidth == 0 + + # get_bin_seeds with a 0 bin_size should return the dataset itself + assert get_bin_seeds(X, bin_size=bandwidth) is X + + # MeanShift with binning and a 0 estimated bandwidth should be equivalent + # to no binning. + ms_binning = MeanShift(bin_seeding=True, bandwidth=None).fit(X) + ms_nobinning = MeanShift(bin_seeding=False).fit(X) + expected_labels = np.array([0, 0, 0, 1, 1, 1, 2, 2]) + + assert v_measure_score(ms_binning.labels_, expected_labels) == pytest.approx(1) + assert v_measure_score(ms_nobinning.labels_, expected_labels) == pytest.approx(1) + assert_allclose(ms_binning.cluster_centers_, ms_nobinning.cluster_centers_) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_optics.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_optics.py new file mode 100644 index 0000000000000000000000000000000000000000..02184ea454d65cc1f2d9d95f265e52d307c30543 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_optics.py @@ -0,0 +1,874 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings + +import numpy as np +import pytest + +from sklearn.cluster import DBSCAN, OPTICS +from sklearn.cluster._optics import _extend_region, _extract_xi_labels +from sklearn.cluster.tests.common import generate_clustered_data +from sklearn.datasets import make_blobs +from sklearn.exceptions import DataConversionWarning, EfficiencyWarning +from sklearn.metrics.cluster import contingency_matrix +from sklearn.metrics.pairwise import pairwise_distances +from sklearn.utils import shuffle +from sklearn.utils._testing import assert_allclose, assert_array_equal +from sklearn.utils.fixes import CSR_CONTAINERS + +rng = np.random.RandomState(0) +n_points_per_cluster = 10 +C1 = [-5, -2] + 0.8 * rng.randn(n_points_per_cluster, 2) +C2 = [4, -1] + 0.1 * rng.randn(n_points_per_cluster, 2) +C3 = [1, -2] + 0.2 * rng.randn(n_points_per_cluster, 2) +C4 = [-2, 3] + 0.3 * rng.randn(n_points_per_cluster, 2) +C5 = [3, -2] + 1.6 * rng.randn(n_points_per_cluster, 2) +C6 = [5, 6] + 2 * rng.randn(n_points_per_cluster, 2) +X = np.vstack((C1, C2, C3, C4, C5, C6)) + + +@pytest.mark.parametrize( + ("r_plot", "end"), + [ + [[10, 8.9, 8.8, 8.7, 7, 10], 3], + [[10, 8.9, 8.8, 8.7, 8.6, 7, 10], 0], + [[10, 8.9, 8.8, 8.7, 7, 6, np.inf], 4], + [[10, 8.9, 8.8, 8.7, 7, 6, np.inf], 4], + ], +) +def test_extend_downward(r_plot, end): + r_plot = np.array(r_plot) + ratio = r_plot[:-1] / r_plot[1:] + steep_downward = ratio >= 1 / 0.9 + upward = ratio < 1 + + e = _extend_region(steep_downward, upward, 0, 2) + assert e == end + + +@pytest.mark.parametrize( + ("r_plot", "end"), + [ + [[1, 2, 2.1, 2.2, 4, 8, 8, np.inf], 6], + [[1, 2, 2.1, 2.2, 2.3, 4, 8, 8, np.inf], 0], + [[1, 2, 2.1, 2, np.inf], 0], + [[1, 2, 2.1, np.inf], 2], + ], +) +def test_extend_upward(r_plot, end): + r_plot = np.array(r_plot) + ratio = r_plot[:-1] / r_plot[1:] + steep_upward = ratio <= 0.9 + downward = ratio > 1 + + e = _extend_region(steep_upward, downward, 0, 2) + assert e == end + + +@pytest.mark.parametrize( + ("ordering", "clusters", "expected"), + [ + [[0, 1, 2, 3], [[0, 1], [2, 3]], [0, 0, 1, 1]], + [[0, 1, 2, 3], [[0, 1], [3, 3]], [0, 0, -1, 1]], + [[0, 1, 2, 3], [[0, 1], [3, 3], [0, 3]], [0, 0, -1, 1]], + [[3, 1, 2, 0], [[0, 1], [3, 3], [0, 3]], [1, 0, -1, 0]], + ], +) +def test_the_extract_xi_labels(ordering, clusters, expected): + labels = _extract_xi_labels(ordering, clusters) + + assert_array_equal(labels, expected) + + +def test_extract_xi(global_dtype): + # small and easy test (no clusters around other clusters) + # but with a clear noise data. + # global_random_seed is not used here since the expected labels + # are hardcoded for these specific data. + rng = np.random.RandomState(0) + n_points_per_cluster = 5 + + C1 = [-5, -2] + 0.8 * rng.randn(n_points_per_cluster, 2) + C2 = [4, -1] + 0.1 * rng.randn(n_points_per_cluster, 2) + C3 = [1, -2] + 0.2 * rng.randn(n_points_per_cluster, 2) + C4 = [-2, 3] + 0.3 * rng.randn(n_points_per_cluster, 2) + C5 = [3, -2] + 0.6 * rng.randn(n_points_per_cluster, 2) + C6 = [5, 6] + 0.2 * rng.randn(n_points_per_cluster, 2) + + X = np.vstack((C1, C2, C3, C4, C5, np.array([[100, 100]]), C6)).astype( + global_dtype, copy=False + ) + expected_labels = np.r_[[2] * 5, [0] * 5, [1] * 5, [3] * 5, [1] * 5, -1, [4] * 5] + X, expected_labels = shuffle(X, expected_labels, random_state=rng) + + clust = OPTICS( + min_samples=3, min_cluster_size=2, max_eps=20, cluster_method="xi", xi=0.4 + ).fit(X) + assert_array_equal(clust.labels_, expected_labels) + + # check float min_samples and min_cluster_size + clust = OPTICS( + min_samples=0.1, min_cluster_size=0.08, max_eps=20, cluster_method="xi", xi=0.4 + ).fit(X) + assert_array_equal(clust.labels_, expected_labels) + + X = np.vstack((C1, C2, C3, C4, C5, np.array([[100, 100]] * 2), C6)).astype( + global_dtype, copy=False + ) + expected_labels = np.r_[ + [1] * 5, [3] * 5, [2] * 5, [0] * 5, [2] * 5, -1, -1, [4] * 5 + ] + X, expected_labels = shuffle(X, expected_labels, random_state=rng) + + clust = OPTICS( + min_samples=3, min_cluster_size=3, max_eps=20, cluster_method="xi", xi=0.3 + ).fit(X) + # this may fail if the predecessor correction is not at work! + assert_array_equal(clust.labels_, expected_labels) + + C1 = [[0, 0], [0, 0.1], [0, -0.1], [0.1, 0]] + C2 = [[10, 10], [10, 9], [10, 11], [9, 10]] + C3 = [[100, 100], [100, 90], [100, 110], [90, 100]] + X = np.vstack((C1, C2, C3)).astype(global_dtype, copy=False) + expected_labels = np.r_[[0] * 4, [1] * 4, [2] * 4] + X, expected_labels = shuffle(X, expected_labels, random_state=rng) + + clust = OPTICS( + min_samples=2, min_cluster_size=2, max_eps=np.inf, cluster_method="xi", xi=0.04 + ).fit(X) + assert_array_equal(clust.labels_, expected_labels) + + +def test_cluster_hierarchy(global_dtype, global_random_seed): + rng = np.random.RandomState(global_random_seed) + n_points_per_cluster = 100 + C1 = [0, 0] + 2 * rng.randn(n_points_per_cluster, 2).astype( + global_dtype, copy=False + ) + C2 = [0, 0] + 50 * rng.randn(n_points_per_cluster, 2).astype( + global_dtype, copy=False + ) + X = np.vstack((C1, C2)) + X = shuffle(X, random_state=rng) + + clusters = OPTICS(min_samples=20, xi=0.2).fit(X).cluster_hierarchy_ + assert clusters.shape == (2, 2) + + # The first cluster should contain all point from C1 but due to how the data is + # generated, some points from C2 may end up in it. + assert 100 <= np.diff(clusters[0]) + 1 <= 115 + # The second cluster should contain all points from C1 and C2. + assert np.diff(clusters[-1]) + 1 == 200 + + +@pytest.mark.parametrize( + "csr_container, metric", + [(None, "minkowski")] + [(container, "euclidean") for container in CSR_CONTAINERS], +) +def test_correct_number_of_clusters(metric, csr_container): + # in 'auto' mode + + n_clusters = 3 + X = generate_clustered_data(n_clusters=n_clusters) + # Parameters chosen specifically for this task. + # Compute OPTICS + clust = OPTICS(max_eps=5.0 * 6.0, min_samples=4, xi=0.1, metric=metric) + clust.fit(csr_container(X) if csr_container is not None else X) + # number of clusters, ignoring noise if present + n_clusters_1 = len(set(clust.labels_)) - int(-1 in clust.labels_) + assert n_clusters_1 == n_clusters + + # check attribute types and sizes + assert clust.labels_.shape == (len(X),) + assert clust.labels_.dtype.kind == "i" + + assert clust.reachability_.shape == (len(X),) + assert clust.reachability_.dtype.kind == "f" + + assert clust.core_distances_.shape == (len(X),) + assert clust.core_distances_.dtype.kind == "f" + + assert clust.ordering_.shape == (len(X),) + assert clust.ordering_.dtype.kind == "i" + assert set(clust.ordering_) == set(range(len(X))) + + +def test_minimum_number_of_sample_check(): + # test that we check a minimum number of samples + msg = "min_samples must be no greater than" + + # Compute OPTICS + X = [[1, 1]] + clust = OPTICS(max_eps=5.0 * 0.3, min_samples=10, min_cluster_size=1.0) + + # Run the fit + with pytest.raises(ValueError, match=msg): + clust.fit(X) + + +def test_bad_extract(): + # Test an extraction of eps too close to original eps + msg = "Specify an epsilon smaller than 0.15. Got 0.3." + centers = [[1, 1], [-1, -1], [1, -1]] + X, labels_true = make_blobs( + n_samples=750, centers=centers, cluster_std=0.4, random_state=0 + ) + + # Compute OPTICS + clust = OPTICS(max_eps=5.0 * 0.03, cluster_method="dbscan", eps=0.3, min_samples=10) + with pytest.raises(ValueError, match=msg): + clust.fit(X) + + +def test_bad_reachability(): + msg = "All reachability values are inf. Set a larger max_eps." + centers = [[1, 1], [-1, -1], [1, -1]] + X, labels_true = make_blobs( + n_samples=750, centers=centers, cluster_std=0.4, random_state=0 + ) + + with pytest.warns(UserWarning, match=msg): + clust = OPTICS(max_eps=5.0 * 0.003, min_samples=10, eps=0.015) + clust.fit(X) + + +def test_nowarn_if_metric_bool_data_bool(): + # make sure no warning is raised if metric and data are both boolean + # non-regression test for + # https://github.com/scikit-learn/scikit-learn/issues/18996 + + pairwise_metric = "rogerstanimoto" + X = np.random.randint(2, size=(5, 2), dtype=bool) + + with warnings.catch_warnings(): + warnings.simplefilter("error", DataConversionWarning) + + OPTICS(metric=pairwise_metric).fit(X) + + +def test_warn_if_metric_bool_data_no_bool(): + # make sure a *single* conversion warning is raised if metric is boolean + # but data isn't + # non-regression test for + # https://github.com/scikit-learn/scikit-learn/issues/18996 + + pairwise_metric = "rogerstanimoto" + X = np.random.randint(2, size=(5, 2), dtype=np.int32) + msg = f"Data will be converted to boolean for metric {pairwise_metric}" + + with pytest.warns(DataConversionWarning, match=msg) as warn_record: + # Silence a DeprecationWarning from joblib <= 1.5.1 in Python 3.14+. + warnings.filterwarnings( + "ignore", + message="'asyncio.iscoroutinefunction' is deprecated", + category=DeprecationWarning, + ) + OPTICS(metric=pairwise_metric).fit(X) + assert len(warn_record) == 1 + + +def test_nowarn_if_metric_no_bool(): + # make sure no conversion warning is raised if + # metric isn't boolean, no matter what the data type is + pairwise_metric = "minkowski" + X_bool = np.random.randint(2, size=(5, 2), dtype=bool) + X_num = np.random.randint(2, size=(5, 2), dtype=np.int32) + + with warnings.catch_warnings(): + warnings.simplefilter("error", DataConversionWarning) + + # fit boolean data + OPTICS(metric=pairwise_metric).fit(X_bool) + # fit numeric data + OPTICS(metric=pairwise_metric).fit(X_num) + + +def test_close_extract(): + # Test extract where extraction eps is close to scaled max_eps + + centers = [[1, 1], [-1, -1], [1, -1]] + X, labels_true = make_blobs( + n_samples=750, centers=centers, cluster_std=0.4, random_state=0 + ) + + # Compute OPTICS + clust = OPTICS(max_eps=1.0, cluster_method="dbscan", eps=0.3, min_samples=10).fit(X) + # Cluster ordering starts at 0; max cluster label = 2 is 3 clusters + assert max(clust.labels_) == 2 + + +@pytest.mark.parametrize("eps", [0.1, 0.3, 0.5]) +@pytest.mark.parametrize("min_samples", [3, 10, 20]) +@pytest.mark.parametrize( + "csr_container, metric", + [(None, "minkowski"), (None, "euclidean")] + + [(container, "euclidean") for container in CSR_CONTAINERS], +) +def test_dbscan_optics_parity(eps, min_samples, metric, global_dtype, csr_container): + # Test that OPTICS clustering labels are <= 5% difference of DBSCAN + + centers = [[1, 1], [-1, -1], [1, -1]] + X, labels_true = make_blobs( + n_samples=150, centers=centers, cluster_std=0.4, random_state=0 + ) + X = csr_container(X) if csr_container is not None else X + + X = X.astype(global_dtype, copy=False) + + # calculate optics with dbscan extract at 0.3 epsilon + op = OPTICS( + min_samples=min_samples, cluster_method="dbscan", eps=eps, metric=metric + ).fit(X) + + # calculate dbscan labels + db = DBSCAN(eps=eps, min_samples=min_samples).fit(X) + + contingency = contingency_matrix(db.labels_, op.labels_) + agree = min( + np.sum(np.max(contingency, axis=0)), np.sum(np.max(contingency, axis=1)) + ) + disagree = X.shape[0] - agree + + percent_mismatch = np.round((disagree - 1) / X.shape[0], 2) + + # verify label mismatch is <= 5% labels + assert percent_mismatch <= 0.05 + + +def test_min_samples_edge_case(global_dtype): + C1 = [[0, 0], [0, 0.1], [0, -0.1]] + C2 = [[10, 10], [10, 9], [10, 11]] + C3 = [[100, 100], [100, 96], [100, 106]] + X = np.vstack((C1, C2, C3)).astype(global_dtype, copy=False) + + expected_labels = np.r_[[0] * 3, [1] * 3, [2] * 3] + clust = OPTICS(min_samples=3, max_eps=7, cluster_method="xi", xi=0.04).fit(X) + assert_array_equal(clust.labels_, expected_labels) + + expected_labels = np.r_[[0] * 3, [1] * 3, [-1] * 3] + clust = OPTICS(min_samples=3, max_eps=3, cluster_method="xi", xi=0.04).fit(X) + assert_array_equal(clust.labels_, expected_labels) + + expected_labels = np.r_[[-1] * 9] + with pytest.warns(UserWarning, match="All reachability values"): + clust = OPTICS(min_samples=4, max_eps=3, cluster_method="xi", xi=0.04).fit(X) + assert_array_equal(clust.labels_, expected_labels) + + +# try arbitrary minimum sizes +@pytest.mark.parametrize("min_cluster_size", range(2, X.shape[0] // 10, 23)) +def test_min_cluster_size(min_cluster_size, global_dtype): + redX = X[::2].astype(global_dtype, copy=False) # reduce for speed + clust = OPTICS(min_samples=9, min_cluster_size=min_cluster_size).fit(redX) + cluster_sizes = np.bincount(clust.labels_[clust.labels_ != -1]) + if cluster_sizes.size: + assert min(cluster_sizes) >= min_cluster_size + # check behaviour is the same when min_cluster_size is a fraction + clust_frac = OPTICS( + min_samples=9, + min_cluster_size=min_cluster_size / redX.shape[0], + ) + clust_frac.fit(redX) + assert_array_equal(clust.labels_, clust_frac.labels_) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_min_cluster_size_invalid2(csr_container): + clust = OPTICS(min_cluster_size=len(X) + 1) + with pytest.raises(ValueError, match="must be no greater than the "): + clust.fit(X) + + clust = OPTICS(min_cluster_size=len(X) + 1, metric="euclidean") + with pytest.raises(ValueError, match="must be no greater than the "): + clust.fit(csr_container(X)) + + +def test_processing_order(): + # Ensure that we consider all unprocessed points, + # not only direct neighbors. when picking the next point. + Y = [[0], [10], [-10], [25]] + + clust = OPTICS(min_samples=3, max_eps=15).fit(Y) + assert_array_equal(clust.reachability_, [np.inf, 10, 10, 15]) + assert_array_equal(clust.core_distances_, [10, 15, np.inf, np.inf]) + assert_array_equal(clust.ordering_, [0, 1, 2, 3]) + + +def test_compare_to_ELKI(): + # Expected values, computed with (future) ELKI 0.7.5 using: + # java -jar elki.jar cli -dbc.in csv -dbc.filter FixedDBIDsFilter + # -algorithm clustering.optics.OPTICSHeap -optics.minpts 5 + # where the FixedDBIDsFilter gives 0-indexed ids. + r1 = [ + np.inf, + 1.0574896366427478, + 0.7587934993548423, + 0.7290174038973836, + 0.7290174038973836, + 0.7290174038973836, + 0.6861627576116127, + 0.7587934993548423, + 0.9280118450166668, + 1.1748022534146194, + 3.3355455741292257, + 0.49618389254482587, + 0.2552805046961355, + 0.2552805046961355, + 0.24944622248445714, + 0.24944622248445714, + 0.24944622248445714, + 0.2552805046961355, + 0.2552805046961355, + 0.3086779122185853, + 4.163024452756142, + 1.623152630340929, + 0.45315840475822655, + 0.25468325192031926, + 0.2254004358159971, + 0.18765711877083036, + 0.1821471333893275, + 0.1821471333893275, + 0.18765711877083036, + 0.18765711877083036, + 0.2240202988740153, + 1.154337614548715, + 1.342604473837069, + 1.323308536402633, + 0.8607514948648837, + 0.27219111215810565, + 0.13260875220533205, + 0.13260875220533205, + 0.09890587675958984, + 0.09890587675958984, + 0.13548790801634494, + 0.1575483940837384, + 0.17515137170530226, + 0.17575920159442388, + 0.27219111215810565, + 0.6101447895405373, + 1.3189208094864302, + 1.323308536402633, + 2.2509184159764577, + 2.4517810628594527, + 3.675977064404973, + 3.8264795626020365, + 2.9130735341510614, + 2.9130735341510614, + 2.9130735341510614, + 2.9130735341510614, + 2.8459300127258036, + 2.8459300127258036, + 2.8459300127258036, + 3.0321982337972537, + ] + o1 = [ + 0, + 3, + 6, + 4, + 7, + 8, + 2, + 9, + 5, + 1, + 31, + 30, + 32, + 34, + 33, + 38, + 39, + 35, + 37, + 36, + 44, + 21, + 23, + 24, + 22, + 25, + 27, + 29, + 26, + 28, + 20, + 40, + 45, + 46, + 10, + 15, + 11, + 13, + 17, + 19, + 18, + 12, + 16, + 14, + 47, + 49, + 43, + 48, + 42, + 41, + 53, + 57, + 51, + 52, + 56, + 59, + 54, + 55, + 58, + 50, + ] + p1 = [ + -1, + 0, + 3, + 6, + 6, + 6, + 8, + 3, + 7, + 5, + 1, + 31, + 30, + 30, + 34, + 34, + 34, + 32, + 32, + 37, + 36, + 44, + 21, + 23, + 24, + 22, + 25, + 25, + 22, + 22, + 22, + 21, + 40, + 45, + 46, + 10, + 15, + 15, + 13, + 13, + 15, + 11, + 19, + 15, + 10, + 47, + 12, + 45, + 14, + 43, + 42, + 53, + 57, + 57, + 57, + 57, + 59, + 59, + 59, + 58, + ] + + # Tests against known extraction array + # Does NOT work with metric='euclidean', because sklearn euclidean has + # worse numeric precision. 'minkowski' is slower but more accurate. + clust1 = OPTICS(min_samples=5).fit(X) + + assert_array_equal(clust1.ordering_, np.array(o1)) + assert_array_equal(clust1.predecessor_[clust1.ordering_], np.array(p1)) + assert_allclose(clust1.reachability_[clust1.ordering_], np.array(r1)) + # ELKI currently does not print the core distances (which are not used much + # in literature, but we can at least ensure to have this consistency: + for i in clust1.ordering_[1:]: + assert clust1.reachability_[i] >= clust1.core_distances_[clust1.predecessor_[i]] + + # Expected values, computed with (future) ELKI 0.7.5 using + r2 = [ + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + 0.27219111215810565, + 0.13260875220533205, + 0.13260875220533205, + 0.09890587675958984, + 0.09890587675958984, + 0.13548790801634494, + 0.1575483940837384, + 0.17515137170530226, + 0.17575920159442388, + 0.27219111215810565, + 0.4928068613197889, + np.inf, + 0.2666183922512113, + 0.18765711877083036, + 0.1821471333893275, + 0.1821471333893275, + 0.1821471333893275, + 0.18715928772277457, + 0.18765711877083036, + 0.18765711877083036, + 0.25468325192031926, + np.inf, + 0.2552805046961355, + 0.2552805046961355, + 0.24944622248445714, + 0.24944622248445714, + 0.24944622248445714, + 0.2552805046961355, + 0.2552805046961355, + 0.3086779122185853, + 0.34466409325984865, + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + np.inf, + ] + o2 = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 15, + 11, + 13, + 17, + 19, + 18, + 12, + 16, + 14, + 47, + 46, + 20, + 22, + 25, + 23, + 27, + 29, + 24, + 26, + 28, + 21, + 30, + 32, + 34, + 33, + 38, + 39, + 35, + 37, + 36, + 31, + 40, + 41, + 42, + 43, + 44, + 45, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + ] + p2 = [ + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 15, + 15, + 13, + 13, + 15, + 11, + 19, + 15, + 10, + 47, + -1, + 20, + 22, + 25, + 25, + 25, + 25, + 22, + 22, + 23, + -1, + 30, + 30, + 34, + 34, + 34, + 32, + 32, + 37, + 38, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + ] + clust2 = OPTICS(min_samples=5, max_eps=0.5).fit(X) + + assert_array_equal(clust2.ordering_, np.array(o2)) + assert_array_equal(clust2.predecessor_[clust2.ordering_], np.array(p2)) + assert_allclose(clust2.reachability_[clust2.ordering_], np.array(r2)) + + index = np.where(clust1.core_distances_ <= 0.5)[0] + assert_allclose(clust1.core_distances_[index], clust2.core_distances_[index]) + + +def test_extract_dbscan(global_dtype, global_random_seed): + # testing an easy dbscan case. Not including clusters with different + # densities. + rng = np.random.RandomState(global_random_seed) + n_points_per_cluster = 20 + C1 = [-5, -2] + 0.2 * rng.randn(n_points_per_cluster, 2) + C2 = [4, -1] + 0.2 * rng.randn(n_points_per_cluster, 2) + C3 = [1, 2] + 0.2 * rng.randn(n_points_per_cluster, 2) + C4 = [-2, 3] + 0.2 * rng.randn(n_points_per_cluster, 2) + X = np.vstack((C1, C2, C3, C4)).astype(global_dtype, copy=False) + + clust = OPTICS(cluster_method="dbscan", eps=0.5).fit(X) + assert_array_equal( + np.sort(np.unique(clust.labels_[clust.labels_ != -1])), [0, 1, 2, 3] + ) + + +@pytest.mark.parametrize("csr_container", [None] + CSR_CONTAINERS) +def test_precomputed_dists(global_dtype, csr_container): + redX = X[::2].astype(global_dtype, copy=False) + dists = pairwise_distances(redX, metric="euclidean") + dists = csr_container(dists) if csr_container is not None else dists + with warnings.catch_warnings(): + warnings.simplefilter("ignore", EfficiencyWarning) + clust1 = OPTICS(min_samples=10, algorithm="brute", metric="precomputed").fit( + dists + ) + clust2 = OPTICS(min_samples=10, algorithm="brute", metric="euclidean").fit(redX) + + assert_allclose(clust1.reachability_, clust2.reachability_) + assert_array_equal(clust1.labels_, clust2.labels_) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_optics_input_not_modified_precomputed_sparse_nodiag( + csr_container, global_random_seed +): + """Check that we don't modify in-place the pre-computed sparse matrix. + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/27508 + """ + X = np.random.RandomState(global_random_seed).rand(6, 6) + # Add zeros on the diagonal that will be implicit when creating + # the sparse matrix. If `X` is modified in-place, the zeros from + # the diagonal will be made explicit. + np.fill_diagonal(X, 0) + X = csr_container(X) + assert all(row != col for row, col in zip(*X.nonzero())) + X_copy = X.copy() + OPTICS(metric="precomputed").fit(X) + # Make sure that we did not modify `X` in-place even by creating + # explicit 0s values. + assert X.nnz == X_copy.nnz + assert_array_equal(X.toarray(), X_copy.toarray()) + + +def test_optics_predecessor_correction_ordering(): + """Check that cluster correction using predecessor is working as expected. + + In the following example, the predecessor correction was not working properly + since it was not using the right indices. + + This non-regression test check that reordering the data does not change the results. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/26324 + """ + X_1 = np.array([1, 2, 3, 1, 8, 8, 7, 100]).reshape(-1, 1) + reorder = [0, 1, 2, 4, 5, 6, 7, 3] + X_2 = X_1[reorder] + + optics_1 = OPTICS(min_samples=3, metric="euclidean").fit(X_1) + optics_2 = OPTICS(min_samples=3, metric="euclidean").fit(X_2) + + assert_array_equal(optics_1.labels_[reorder], optics_2.labels_) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_spectral.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..71b11c9fe151c310f4fd5a60f99323360e493506 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/cluster/tests/test_spectral.py @@ -0,0 +1,335 @@ +"""Testing for Spectral Clustering methods""" + +import pickle +import re + +import numpy as np +import pytest +from scipy.linalg import LinAlgError + +from sklearn.cluster import SpectralClustering, spectral_clustering +from sklearn.cluster._spectral import cluster_qr, discretize +from sklearn.datasets import make_blobs +from sklearn.feature_extraction import img_to_graph +from sklearn.metrics import adjusted_rand_score +from sklearn.metrics.pairwise import kernel_metrics, rbf_kernel +from sklearn.neighbors import NearestNeighbors +from sklearn.utils import check_random_state +from sklearn.utils._testing import assert_array_equal +from sklearn.utils.fixes import COO_CONTAINERS, CSR_CONTAINERS + +try: + from pyamg import smoothed_aggregation_solver # noqa: F401 + + amg_loaded = True +except ImportError: + amg_loaded = False + +centers = np.array([[1, 1], [-1, -1], [1, -1]]) + 10 +X, _ = make_blobs( + n_samples=60, + n_features=2, + centers=centers, + cluster_std=0.4, + shuffle=True, + random_state=0, +) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +@pytest.mark.parametrize("eigen_solver", ("arpack", "lobpcg")) +@pytest.mark.parametrize("assign_labels", ("kmeans", "discretize", "cluster_qr")) +def test_spectral_clustering( + eigen_solver, assign_labels, csr_container, global_random_seed +): + S = np.array( + [ + [1.0, 1.0, 1.0, 0.2, 0.0, 0.0, 0.0], + [1.0, 1.0, 1.0, 0.2, 0.0, 0.0, 0.0], + [1.0, 1.0, 1.0, 0.2, 0.0, 0.0, 0.0], + [0.2, 0.2, 0.2, 1.0, 1.0, 1.0, 1.0], + [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], + [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], + [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], + ] + ) + + for mat in (S, csr_container(S)): + model = SpectralClustering( + random_state=global_random_seed, + n_clusters=2, + affinity="precomputed", + eigen_solver=eigen_solver, + assign_labels=assign_labels, + ).fit(mat) + labels = model.labels_ + if labels[0] == 0: + labels = 1 - labels + + assert adjusted_rand_score(labels, [1, 1, 1, 0, 0, 0, 0]) == 1 + + model_copy = pickle.loads(pickle.dumps(model)) + assert model_copy.n_clusters == model.n_clusters + assert model_copy.eigen_solver == model.eigen_solver + assert_array_equal(model_copy.labels_, model.labels_) + + +@pytest.mark.parametrize("coo_container", COO_CONTAINERS) +@pytest.mark.parametrize("assign_labels", ("kmeans", "discretize", "cluster_qr")) +def test_spectral_clustering_sparse(assign_labels, coo_container, global_random_seed): + X, y = make_blobs( + n_samples=20, + random_state=global_random_seed, + centers=[[1, 1], [-1, -1]], + cluster_std=0.01, + ) + + S = rbf_kernel(X, gamma=1) + S = np.maximum(S - 1e-4, 0) + S = coo_container(S) + + labels = ( + SpectralClustering( + random_state=global_random_seed, + n_clusters=2, + affinity="precomputed", + assign_labels=assign_labels, + ) + .fit(S) + .labels_ + ) + assert adjusted_rand_score(y, labels) == 1 + + +def test_precomputed_nearest_neighbors_filtering(global_random_seed): + # Test precomputed graph filtering when containing too many neighbors + X, y = make_blobs( + n_samples=250, + random_state=global_random_seed, + centers=[[1, 1, 1], [-1, -1, -1]], + cluster_std=0.01, + ) + + n_neighbors = 2 + results = [] + for additional_neighbors in [0, 10]: + nn = NearestNeighbors(n_neighbors=n_neighbors + additional_neighbors).fit(X) + graph = nn.kneighbors_graph(X, mode="distance") + labels = ( + SpectralClustering( + random_state=global_random_seed, + n_clusters=2, + affinity="precomputed_nearest_neighbors", + n_neighbors=n_neighbors, + ) + .fit(graph) + .labels_ + ) + results.append(labels) + + assert_array_equal(results[0], results[1]) + + +def test_affinities(global_random_seed): + # Note: in the following, random_state has been selected to have + # a dataset that yields a stable eigen decomposition both when built + # on OSX and Linux + X, y = make_blobs( + n_samples=20, random_state=0, centers=[[1, 1], [-1, -1]], cluster_std=0.01 + ) + # nearest neighbors affinity + sp = SpectralClustering(n_clusters=2, affinity="nearest_neighbors", random_state=0) + with pytest.warns(UserWarning, match="not fully connected"): + sp.fit(X) + assert adjusted_rand_score(y, sp.labels_) == 1 + + sp = SpectralClustering(n_clusters=2, gamma=2, random_state=global_random_seed) + labels = sp.fit(X).labels_ + assert adjusted_rand_score(y, labels) == 1 + + X = check_random_state(10).rand(10, 5) * 10 + + kernels_available = kernel_metrics() + for kern in kernels_available: + # Additive chi^2 gives a negative similarity matrix which + # doesn't make sense for spectral clustering + if kern != "additive_chi2": + sp = SpectralClustering(n_clusters=2, affinity=kern, random_state=0) + labels = sp.fit(X).labels_ + assert (X.shape[0],) == labels.shape + + sp = SpectralClustering(n_clusters=2, affinity=lambda x, y: 1, random_state=0) + labels = sp.fit(X).labels_ + assert (X.shape[0],) == labels.shape + + def histogram(x, y, **kwargs): + # Histogram kernel implemented as a callable. + assert kwargs == {} # no kernel_params that we didn't ask for + return np.minimum(x, y).sum() + + sp = SpectralClustering(n_clusters=2, affinity=histogram, random_state=0) + labels = sp.fit(X).labels_ + assert (X.shape[0],) == labels.shape + + +def test_cluster_qr(global_random_seed): + # cluster_qr by itself should not be used for clustering generic data + # other than the rows of the eigenvectors within spectral clustering, + # but cluster_qr must still preserve the labels for different dtypes + # of the generic fixed input even if the labels may be meaningless. + random_state = np.random.RandomState(seed=global_random_seed) + n_samples, n_components = 10, 5 + data = random_state.randn(n_samples, n_components) + labels_float64 = cluster_qr(data.astype(np.float64)) + # Each sample is assigned a cluster identifier + assert labels_float64.shape == (n_samples,) + # All components should be covered by the assignment + assert np.array_equal(np.unique(labels_float64), np.arange(n_components)) + # Single precision data should yield the same cluster assignments + labels_float32 = cluster_qr(data.astype(np.float32)) + assert np.array_equal(labels_float64, labels_float32) + + +def test_cluster_qr_permutation_invariance(global_random_seed): + # cluster_qr must be invariant to sample permutation. + random_state = np.random.RandomState(seed=global_random_seed) + n_samples, n_components = 100, 5 + data = random_state.randn(n_samples, n_components) + perm = random_state.permutation(n_samples) + assert np.array_equal( + cluster_qr(data)[perm], + cluster_qr(data[perm]), + ) + + +@pytest.mark.parametrize("coo_container", COO_CONTAINERS) +@pytest.mark.parametrize("n_samples", [50, 100, 150, 500]) +def test_discretize(n_samples, coo_container, global_random_seed): + # Test the discretize using a noise assignment matrix + random_state = np.random.RandomState(seed=global_random_seed) + for n_class in range(2, 10): + # random class labels + y_true = random_state.randint(0, n_class + 1, n_samples) + y_true = np.array(y_true, float) + # noise class assignment matrix + y_indicator = coo_container( + (np.ones(n_samples), (np.arange(n_samples), y_true)), + shape=(n_samples, n_class + 1), + ) + y_true_noisy = y_indicator.toarray() + 0.1 * random_state.randn( + n_samples, n_class + 1 + ) + y_pred = discretize(y_true_noisy, random_state=random_state) + assert adjusted_rand_score(y_true, y_pred) > 0.8 + + +def test_spectral_clustering_with_arpack_amg_solvers(global_random_seed): + # Test that spectral_clustering is the same for arpack and amg solver + # Based on toy example from plot_segmentation_toy.py + + # a small two coin image + x, y = np.indices((40, 40)) + + center1, center2 = (14, 12), (20, 25) + radius1, radius2 = 8, 7 + + circle1 = (x - center1[0]) ** 2 + (y - center1[1]) ** 2 < radius1**2 + circle2 = (x - center2[0]) ** 2 + (y - center2[1]) ** 2 < radius2**2 + + circles = circle1 | circle2 + mask = circles.copy() + img = circles.astype(float) + + graph = img_to_graph(img, mask=mask) + graph.data = np.exp(-graph.data / graph.data.std()) + + labels_arpack = spectral_clustering( + graph, n_clusters=2, eigen_solver="arpack", random_state=global_random_seed + ) + + assert len(np.unique(labels_arpack)) == 2 + + if amg_loaded: + labels_amg = spectral_clustering( + graph, n_clusters=2, eigen_solver="amg", random_state=global_random_seed + ) + assert adjusted_rand_score(labels_arpack, labels_amg) == 1 + else: + with pytest.raises(ValueError): + spectral_clustering(graph, n_clusters=2, eigen_solver="amg", random_state=0) + + +def test_n_components(global_random_seed): + # Test that after adding n_components, result is different and + # n_components = n_clusters by default + X, y = make_blobs( + n_samples=20, + random_state=global_random_seed, + centers=[[1, 1], [-1, -1]], + cluster_std=0.01, + ) + sp = SpectralClustering(n_clusters=2, random_state=global_random_seed) + labels = sp.fit(X).labels_ + # set n_components = n_cluster and test if result is the same + labels_same_ncomp = ( + SpectralClustering( + n_clusters=2, n_components=2, random_state=global_random_seed + ) + .fit(X) + .labels_ + ) + # test that n_components=n_clusters by default + assert_array_equal(labels, labels_same_ncomp) + + # test that n_components affect result + # n_clusters=8 by default, and set n_components=2 + labels_diff_ncomp = ( + SpectralClustering(n_components=2, random_state=global_random_seed) + .fit(X) + .labels_ + ) + assert not np.array_equal(labels, labels_diff_ncomp) + + +@pytest.mark.parametrize("assign_labels", ("kmeans", "discretize", "cluster_qr")) +def test_verbose(assign_labels, capsys): + # Check verbose mode of KMeans for better coverage. + X, y = make_blobs( + n_samples=20, random_state=0, centers=[[1, 1], [-1, -1]], cluster_std=0.01 + ) + + SpectralClustering(n_clusters=2, random_state=42, verbose=1).fit(X) + + captured = capsys.readouterr() + + assert re.search(r"Computing label assignment using", captured.out) + + if assign_labels == "kmeans": + assert re.search(r"Initialization complete", captured.out) + assert re.search(r"Iteration [0-9]+, inertia", captured.out) + + +def test_spectral_clustering_np_matrix_raises(): + """Check that spectral_clustering raises an informative error when passed + a np.matrix. See #10993""" + X = np.matrix([[0.0, 2.0], [2.0, 0.0]]) + + msg = r"np\.matrix is not supported. Please convert to a numpy array" + with pytest.raises(TypeError, match=msg): + spectral_clustering(X) + + +def test_spectral_clustering_not_infinite_loop(capsys, monkeypatch): + """Check that discretize raises LinAlgError when svd never converges. + + Non-regression test for #21380 + """ + + def new_svd(*args, **kwargs): + raise LinAlgError() + + monkeypatch.setattr(np.linalg, "svd", new_svd) + vectors = np.ones((10, 4)) + + with pytest.raises(LinAlgError, match="SVD did not converge"): + discretize(vectors) diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d062882087ba4520742e0dc77d3d232b3ba6cada Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/__pycache__/_array_api_compat_vendor.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/__pycache__/_array_api_compat_vendor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4bae7230c8b63938ab538f6632bc36fb8f147a48 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/__pycache__/_array_api_compat_vendor.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_packaging/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_packaging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_packaging/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_packaging/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d1ce1793b6ae0dc351c19f317a83d2b435e1bda Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_packaging/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_packaging/__pycache__/_structures.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_packaging/__pycache__/_structures.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f36c2907d480c8fb8d29a3f5da5f5eac428b8c48 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_packaging/__pycache__/_structures.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_packaging/__pycache__/version.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_packaging/__pycache__/version.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a55f3f4d47a33a965dac7b45512a7f8e18bdc38 Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_packaging/__pycache__/version.cpython-310.pyc differ diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_packaging/_structures.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_packaging/_structures.py new file mode 100644 index 0000000000000000000000000000000000000000..837e3a7946d70355b46606d20a4b6c0f038b0815 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_packaging/_structures.py @@ -0,0 +1,90 @@ +"""Vendoered from +https://github.com/pypa/packaging/blob/main/packaging/_structures.py +""" +# Copyright (c) Donald Stufft and individual contributors. +# 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. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +class InfinityType: + def __repr__(self) -> str: + return "Infinity" + + def __hash__(self) -> int: + return hash(repr(self)) + + def __lt__(self, other: object) -> bool: + return False + + def __le__(self, other: object) -> bool: + return False + + def __eq__(self, other: object) -> bool: + return isinstance(other, self.__class__) + + def __ne__(self, other: object) -> bool: + return not isinstance(other, self.__class__) + + def __gt__(self, other: object) -> bool: + return True + + def __ge__(self, other: object) -> bool: + return True + + def __neg__(self: object) -> "NegativeInfinityType": + return NegativeInfinity + + +Infinity = InfinityType() + + +class NegativeInfinityType: + def __repr__(self) -> str: + return "-Infinity" + + def __hash__(self) -> int: + return hash(repr(self)) + + def __lt__(self, other: object) -> bool: + return True + + def __le__(self, other: object) -> bool: + return True + + def __eq__(self, other: object) -> bool: + return isinstance(other, self.__class__) + + def __ne__(self, other: object) -> bool: + return not isinstance(other, self.__class__) + + def __gt__(self, other: object) -> bool: + return False + + def __ge__(self, other: object) -> bool: + return False + + def __neg__(self: object) -> InfinityType: + return Infinity + + +NegativeInfinity = NegativeInfinityType() diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_packaging/version.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_packaging/version.py new file mode 100644 index 0000000000000000000000000000000000000000..0f1e5b833699c38690679515bb788820de4168b0 --- /dev/null +++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_packaging/version.py @@ -0,0 +1,535 @@ +"""Vendoered from +https://github.com/pypa/packaging/blob/main/packaging/version.py +""" +# Copyright (c) Donald Stufft and individual contributors. +# 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. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import collections +import itertools +import re +import warnings +from typing import Callable, Iterator, List, Optional, SupportsInt, Tuple, Union + +from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType + +__all__ = ["parse", "Version", "LegacyVersion", "InvalidVersion", "VERSION_PATTERN"] + +InfiniteTypes = Union[InfinityType, NegativeInfinityType] +PrePostDevType = Union[InfiniteTypes, Tuple[str, int]] +SubLocalType = Union[InfiniteTypes, int, str] +LocalType = Union[ + NegativeInfinityType, + Tuple[ + Union[ + SubLocalType, + Tuple[SubLocalType, str], + Tuple[NegativeInfinityType, SubLocalType], + ], + ..., + ], +] +CmpKey = Tuple[ + int, Tuple[int, ...], PrePostDevType, PrePostDevType, PrePostDevType, LocalType +] +LegacyCmpKey = Tuple[int, Tuple[str, ...]] +VersionComparisonMethod = Callable[ + [Union[CmpKey, LegacyCmpKey], Union[CmpKey, LegacyCmpKey]], bool +] + +_Version = collections.namedtuple( + "_Version", ["epoch", "release", "dev", "pre", "post", "local"] +) + + +def parse(version: str) -> Union["LegacyVersion", "Version"]: + """Parse the given version from a string to an appropriate class. + + Parameters + ---------- + version : str + Version in a string format, eg. "0.9.1" or "1.2.dev0". + + Returns + ------- + version : :class:`Version` object or a :class:`LegacyVersion` object + Returned class depends on the given version: if is a valid + PEP 440 version or a legacy version. + """ + try: + return Version(version) + except InvalidVersion: + return LegacyVersion(version) + + +class InvalidVersion(ValueError): + """ + An invalid version was found, users should refer to PEP 440. + """ + + +class _BaseVersion: + _key: Union[CmpKey, LegacyCmpKey] + + def __hash__(self) -> int: + return hash(self._key) + + # Please keep the duplicated `isinstance` check + # in the six comparisons hereunder + # unless you find a way to avoid adding overhead function calls. + def __lt__(self, other: "_BaseVersion") -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key < other._key + + def __le__(self, other: "_BaseVersion") -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key <= other._key + + def __eq__(self, other: object) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key == other._key + + def __ge__(self, other: "_BaseVersion") -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key >= other._key + + def __gt__(self, other: "_BaseVersion") -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key > other._key + + def __ne__(self, other: object) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key != other._key + + +class LegacyVersion(_BaseVersion): + def __init__(self, version: str) -> None: + self._version = str(version) + self._key = _legacy_cmpkey(self._version) + + warnings.warn( + "Creating a LegacyVersion has been deprecated and will be " + "removed in the next major release", + DeprecationWarning, + ) + + def __str__(self) -> str: + return self._version + + def __repr__(self) -> str: + return f"" + + @property + def public(self) -> str: + return self._version + + @property + def base_version(self) -> str: + return self._version + + @property + def epoch(self) -> int: + return -1 + + @property + def release(self) -> None: + return None + + @property + def pre(self) -> None: + return None + + @property + def post(self) -> None: + return None + + @property + def dev(self) -> None: + return None + + @property + def local(self) -> None: + return None + + @property + def is_prerelease(self) -> bool: + return False + + @property + def is_postrelease(self) -> bool: + return False + + @property + def is_devrelease(self) -> bool: + return False + + +_legacy_version_component_re = re.compile(r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE) + +_legacy_version_replacement_map = { + "pre": "c", + "preview": "c", + "-": "final-", + "rc": "c", + "dev": "@", +} + + +def _parse_version_parts(s: str) -> Iterator[str]: + for part in _legacy_version_component_re.split(s): + part = _legacy_version_replacement_map.get(part, part) + + if not part or part == ".": + continue + + if part[:1] in "0123456789": + # pad for numeric comparison + yield part.zfill(8) + else: + yield "*" + part + + # ensure that alpha/beta/candidate are before final + yield "*final" + + +def _legacy_cmpkey(version: str) -> LegacyCmpKey: + + # We hardcode an epoch of -1 here. A PEP 440 version can only have a epoch + # greater than or equal to 0. This will effectively put the LegacyVersion, + # which uses the defacto standard originally implemented by setuptools, + # as before all PEP 440 versions. + epoch = -1 + + # This scheme is taken from pkg_resources.parse_version setuptools prior to + # it's adoption of the packaging library. + parts: List[str] = [] + for part in _parse_version_parts(version.lower()): + if part.startswith("*"): + # remove "-" before a prerelease tag + if part < "*final": + while parts and parts[-1] == "*final-": + parts.pop() + + # remove trailing zeros from each series of numeric parts + while parts and parts[-1] == "00000000": + parts.pop() + + parts.append(part) + + return epoch, tuple(parts) + + +# Deliberately not anchored to the start and end of the string, to make it +# easier for 3rd party code to reuse +VERSION_PATTERN = r""" + v? + (?: + (?:(?P[0-9]+)!)? # epoch + (?P[0-9]+(?:\.[0-9]+)*) # release segment + (?P
                                          # pre-release
+            [-_\.]?
+            (?P(a|b|c|rc|alpha|beta|pre|preview))
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+        (?P                                         # post release
+            (?:-(?P[0-9]+))
+            |
+            (?:
+                [-_\.]?
+                (?Ppost|rev|r)
+                [-_\.]?
+                (?P[0-9]+)?
+            )
+        )?
+        (?P                                          # dev release
+            [-_\.]?
+            (?Pdev)
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+    )
+    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
+"""
+
+
+class Version(_BaseVersion):
+
+    _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
+
+    def __init__(self, version: str) -> None:
+
+        # Validate the version and parse it into pieces
+        match = self._regex.search(version)
+        if not match:
+            raise InvalidVersion(f"Invalid version: '{version}'")
+
+        # Store the parsed out pieces of the version
+        self._version = _Version(
+            epoch=int(match.group("epoch")) if match.group("epoch") else 0,
+            release=tuple(int(i) for i in match.group("release").split(".")),
+            pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")),
+            post=_parse_letter_version(
+                match.group("post_l"), match.group("post_n1") or match.group("post_n2")
+            ),
+            dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),
+            local=_parse_local_version(match.group("local")),
+        )
+
+        # Generate a key which will be used for sorting
+        self._key = _cmpkey(
+            self._version.epoch,
+            self._version.release,
+            self._version.pre,
+            self._version.post,
+            self._version.dev,
+            self._version.local,
+        )
+
+    def __repr__(self) -> str:
+        return f""
+
+    def __str__(self) -> str:
+        parts = []
+
+        # Epoch
+        if self.epoch != 0:
+            parts.append(f"{self.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self.release))
+
+        # Pre-release
+        if self.pre is not None:
+            parts.append("".join(str(x) for x in self.pre))
+
+        # Post-release
+        if self.post is not None:
+            parts.append(f".post{self.post}")
+
+        # Development release
+        if self.dev is not None:
+            parts.append(f".dev{self.dev}")
+
+        # Local version segment
+        if self.local is not None:
+            parts.append(f"+{self.local}")
+
+        return "".join(parts)
+
+    @property
+    def epoch(self) -> int:
+        _epoch: int = self._version.epoch
+        return _epoch
+
+    @property
+    def release(self) -> Tuple[int, ...]:
+        _release: Tuple[int, ...] = self._version.release
+        return _release
+
+    @property
+    def pre(self) -> Optional[Tuple[str, int]]:
+        _pre: Optional[Tuple[str, int]] = self._version.pre
+        return _pre
+
+    @property
+    def post(self) -> Optional[int]:
+        return self._version.post[1] if self._version.post else None
+
+    @property
+    def dev(self) -> Optional[int]:
+        return self._version.dev[1] if self._version.dev else None
+
+    @property
+    def local(self) -> Optional[str]:
+        if self._version.local:
+            return ".".join(str(x) for x in self._version.local)
+        else:
+            return None
+
+    @property
+    def public(self) -> str:
+        return str(self).split("+", 1)[0]
+
+    @property
+    def base_version(self) -> str:
+        parts = []
+
+        # Epoch
+        if self.epoch != 0:
+            parts.append(f"{self.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self.release))
+
+        return "".join(parts)
+
+    @property
+    def is_prerelease(self) -> bool:
+        return self.dev is not None or self.pre is not None
+
+    @property
+    def is_postrelease(self) -> bool:
+        return self.post is not None
+
+    @property
+    def is_devrelease(self) -> bool:
+        return self.dev is not None
+
+    @property
+    def major(self) -> int:
+        return self.release[0] if len(self.release) >= 1 else 0
+
+    @property
+    def minor(self) -> int:
+        return self.release[1] if len(self.release) >= 2 else 0
+
+    @property
+    def micro(self) -> int:
+        return self.release[2] if len(self.release) >= 3 else 0
+
+
+def _parse_letter_version(
+    letter: str, number: Union[str, bytes, SupportsInt]
+) -> Optional[Tuple[str, int]]:
+
+    if letter:
+        # We consider there to be an implicit 0 in a pre-release if there is
+        # not a numeral associated with it.
+        if number is None:
+            number = 0
+
+        # We normalize any letters to their lower case form
+        letter = letter.lower()
+
+        # We consider some words to be alternate spellings of other words and
+        # in those cases we want to normalize the spellings to our preferred
+        # spelling.
+        if letter == "alpha":
+            letter = "a"
+        elif letter == "beta":
+            letter = "b"
+        elif letter in ["c", "pre", "preview"]:
+            letter = "rc"
+        elif letter in ["rev", "r"]:
+            letter = "post"
+
+        return letter, int(number)
+    if not letter and number:
+        # We assume if we are given a number, but we are not given a letter
+        # then this is using the implicit post release syntax (e.g. 1.0-1)
+        letter = "post"
+
+        return letter, int(number)
+
+    return None
+
+
+_local_version_separators = re.compile(r"[\._-]")
+
+
+def _parse_local_version(local: str) -> Optional[LocalType]:
+    """
+    Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
+    """
+    if local is not None:
+        return tuple(
+            part.lower() if not part.isdigit() else int(part)
+            for part in _local_version_separators.split(local)
+        )
+    return None
+
+
+def _cmpkey(
+    epoch: int,
+    release: Tuple[int, ...],
+    pre: Optional[Tuple[str, int]],
+    post: Optional[Tuple[str, int]],
+    dev: Optional[Tuple[str, int]],
+    local: Optional[Tuple[SubLocalType]],
+) -> CmpKey:
+
+    # When we compare a release version, we want to compare it with all of the
+    # trailing zeros removed. So we'll use a reverse the list, drop all the now
+    # leading zeros until we come to something non zero, then take the rest
+    # re-reverse it back into the correct order and make it a tuple and use
+    # that for our sorting key.
+    _release = tuple(
+        reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
+    )
+
+    # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
+    # We'll do this by abusing the pre segment, but we _only_ want to do this
+    # if there is not a pre or a post segment. If we have one of those then
+    # the normal sorting rules will handle this case correctly.
+    if pre is None and post is None and dev is not None:
+        _pre: PrePostDevType = NegativeInfinity
+    # Versions without a pre-release (except as noted above) should sort after
+    # those with one.
+    elif pre is None:
+        _pre = Infinity
+    else:
+        _pre = pre
+
+    # Versions without a post segment should sort before those with one.
+    if post is None:
+        _post: PrePostDevType = NegativeInfinity
+
+    else:
+        _post = post
+
+    # Versions without a development segment should sort after those with one.
+    if dev is None:
+        _dev: PrePostDevType = Infinity
+
+    else:
+        _dev = dev
+
+    if local is None:
+        # Versions without a local segment should sort before those with one.
+        _local: LocalType = NegativeInfinity
+    else:
+        # Versions with a local segment need that segment parsed to implement
+        # the sorting rules in PEP440.
+        # - Alpha numeric segments sort before numeric segments
+        # - Alpha numeric segments sort lexicographically
+        # - Numeric segments sort numerically
+        # - Shorter versions sort before longer versions when the prefixes
+        #   match exactly
+        _local = tuple(
+            (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
+        )
+
+    return epoch, _release, _pre, _post, _dev, _local
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_scipy/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_scipy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_scipy/sparse/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_scipy/sparse/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_scipy/sparse/csgraph/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_scipy/sparse/csgraph/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..15fc11fc81f20138388335f81cbdfca5b366e348
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_scipy/sparse/csgraph/__init__.py
@@ -0,0 +1 @@
+from ._laplacian import laplacian
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_scipy/sparse/csgraph/_laplacian.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_scipy/sparse/csgraph/_laplacian.py
new file mode 100644
index 0000000000000000000000000000000000000000..34c816628ee736deb6ba1696a422d9a34df80266
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/_scipy/sparse/csgraph/_laplacian.py
@@ -0,0 +1,557 @@
+"""
+This file is a copy of the scipy.sparse.csgraph._laplacian module from SciPy 1.12
+
+scipy.sparse.csgraph.laplacian supports sparse arrays only starting from Scipy 1.12,
+see https://github.com/scipy/scipy/pull/19156. This vendored file can be removed as
+soon as Scipy 1.12 becomes the minimum supported version.
+
+Laplacian of a compressed-sparse graph
+"""
+
+# SPDX-License-Identifier: BSD-3-Clause
+
+import numpy as np
+from scipy.sparse import issparse
+from scipy.sparse.linalg import LinearOperator
+
+
+###############################################################################
+# Graph laplacian
+def laplacian(
+    csgraph,
+    normed=False,
+    return_diag=False,
+    use_out_degree=False,
+    *,
+    copy=True,
+    form="array",
+    dtype=None,
+    symmetrized=False,
+):
+    """
+    Return the Laplacian of a directed graph.
+
+    Parameters
+    ----------
+    csgraph : array_like or sparse matrix, 2 dimensions
+        Compressed-sparse graph, with shape (N, N).
+    normed : bool, optional
+        If True, then compute symmetrically normalized Laplacian.
+        Default: False.
+    return_diag : bool, optional
+        If True, then also return an array related to vertex degrees.
+        Default: False.
+    use_out_degree : bool, optional
+        If True, then use out-degree instead of in-degree.
+        This distinction matters only if the graph is asymmetric.
+        Default: False.
+    copy : bool, optional
+        If False, then change `csgraph` in place if possible,
+        avoiding doubling the memory use.
+        Default: True, for backward compatibility.
+    form : 'array', or 'function', or 'lo'
+        Determines the format of the output Laplacian:
+
+        * 'array' is a numpy array;
+        * 'function' is a pointer to evaluating the Laplacian-vector
+          or Laplacian-matrix product;
+        * 'lo' results in the format of the `LinearOperator`.
+
+        Choosing 'function' or 'lo' always avoids doubling
+        the memory use, ignoring `copy` value.
+        Default: 'array', for backward compatibility.
+    dtype : None or one of numeric numpy dtypes, optional
+        The dtype of the output. If ``dtype=None``, the dtype of the
+        output matches the dtype of the input csgraph, except for
+        the case ``normed=True`` and integer-like csgraph, where
+        the output dtype is 'float' allowing accurate normalization,
+        but dramatically increasing the memory use.
+        Default: None, for backward compatibility.
+    symmetrized : bool, optional
+        If True, then the output Laplacian is symmetric/Hermitian.
+        The symmetrization is done by ``csgraph + csgraph.T.conj``
+        without dividing by 2 to preserve integer dtypes if possible
+        prior to the construction of the Laplacian.
+        The symmetrization will increase the memory footprint of
+        sparse matrices unless the sparsity pattern is symmetric or
+        `form` is 'function' or 'lo'.
+        Default: False, for backward compatibility.
+
+    Returns
+    -------
+    lap : ndarray, or sparse matrix, or `LinearOperator`
+        The N x N Laplacian of csgraph. It will be a NumPy array (dense)
+        if the input was dense, or a sparse matrix otherwise, or
+        the format of a function or `LinearOperator` if
+        `form` equals 'function' or 'lo', respectively.
+    diag : ndarray, optional
+        The length-N main diagonal of the Laplacian matrix.
+        For the normalized Laplacian, this is the array of square roots
+        of vertex degrees or 1 if the degree is zero.
+
+    Notes
+    -----
+    The Laplacian matrix of a graph is sometimes referred to as the
+    "Kirchhoff matrix" or just the "Laplacian", and is useful in many
+    parts of spectral graph theory.
+    In particular, the eigen-decomposition of the Laplacian can give
+    insight into many properties of the graph, e.g.,
+    is commonly used for spectral data embedding and clustering.
+
+    The constructed Laplacian doubles the memory use if ``copy=True`` and
+    ``form="array"`` which is the default.
+    Choosing ``copy=False`` has no effect unless ``form="array"``
+    or the matrix is sparse in the ``coo`` format, or dense array, except
+    for the integer input with ``normed=True`` that forces the float output.
+
+    Sparse input is reformatted into ``coo`` if ``form="array"``,
+    which is the default.
+
+    If the input adjacency matrix is not symmetric, the Laplacian is
+    also non-symmetric unless ``symmetrized=True`` is used.
+
+    Diagonal entries of the input adjacency matrix are ignored and
+    replaced with zeros for the purpose of normalization where ``normed=True``.
+    The normalization uses the inverse square roots of row-sums of the input
+    adjacency matrix, and thus may fail if the row-sums contain
+    negative or complex with a non-zero imaginary part values.
+
+    The normalization is symmetric, making the normalized Laplacian also
+    symmetric if the input csgraph was symmetric.
+
+    References
+    ----------
+    .. [1] Laplacian matrix. https://en.wikipedia.org/wiki/Laplacian_matrix
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csgraph
+
+    Our first illustration is the symmetric graph
+
+    >>> G = np.arange(4) * np.arange(4)[:, np.newaxis]
+    >>> G
+    array([[0, 0, 0, 0],
+           [0, 1, 2, 3],
+           [0, 2, 4, 6],
+           [0, 3, 6, 9]])
+
+    and its symmetric Laplacian matrix
+
+    >>> csgraph.laplacian(G)
+    array([[ 0,  0,  0,  0],
+           [ 0,  5, -2, -3],
+           [ 0, -2,  8, -6],
+           [ 0, -3, -6,  9]])
+
+    The non-symmetric graph
+
+    >>> G = np.arange(9).reshape(3, 3)
+    >>> G
+    array([[0, 1, 2],
+           [3, 4, 5],
+           [6, 7, 8]])
+
+    has different row- and column sums, resulting in two varieties
+    of the Laplacian matrix, using an in-degree, which is the default
+
+    >>> L_in_degree = csgraph.laplacian(G)
+    >>> L_in_degree
+    array([[ 9, -1, -2],
+           [-3,  8, -5],
+           [-6, -7,  7]])
+
+    or alternatively an out-degree
+
+    >>> L_out_degree = csgraph.laplacian(G, use_out_degree=True)
+    >>> L_out_degree
+    array([[ 3, -1, -2],
+           [-3,  8, -5],
+           [-6, -7, 13]])
+
+    Constructing a symmetric Laplacian matrix, one can add the two as
+
+    >>> L_in_degree + L_out_degree.T
+    array([[ 12,  -4,  -8],
+            [ -4,  16, -12],
+            [ -8, -12,  20]])
+
+    or use the ``symmetrized=True`` option
+
+    >>> csgraph.laplacian(G, symmetrized=True)
+    array([[ 12,  -4,  -8],
+           [ -4,  16, -12],
+           [ -8, -12,  20]])
+
+    that is equivalent to symmetrizing the original graph
+
+    >>> csgraph.laplacian(G + G.T)
+    array([[ 12,  -4,  -8],
+           [ -4,  16, -12],
+           [ -8, -12,  20]])
+
+    The goal of normalization is to make the non-zero diagonal entries
+    of the Laplacian matrix to be all unit, also scaling off-diagonal
+    entries correspondingly. The normalization can be done manually, e.g.,
+
+    >>> G = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]])
+    >>> L, d = csgraph.laplacian(G, return_diag=True)
+    >>> L
+    array([[ 2, -1, -1],
+           [-1,  2, -1],
+           [-1, -1,  2]])
+    >>> d
+    array([2, 2, 2])
+    >>> scaling = np.sqrt(d)
+    >>> scaling
+    array([1.41421356, 1.41421356, 1.41421356])
+    >>> (1/scaling)*L*(1/scaling)
+    array([[ 1. , -0.5, -0.5],
+           [-0.5,  1. , -0.5],
+           [-0.5, -0.5,  1. ]])
+
+    Or using ``normed=True`` option
+
+    >>> L, d = csgraph.laplacian(G, return_diag=True, normed=True)
+    >>> L
+    array([[ 1. , -0.5, -0.5],
+           [-0.5,  1. , -0.5],
+           [-0.5, -0.5,  1. ]])
+
+    which now instead of the diagonal returns the scaling coefficients
+
+    >>> d
+    array([1.41421356, 1.41421356, 1.41421356])
+
+    Zero scaling coefficients are substituted with 1s, where scaling
+    has thus no effect, e.g.,
+
+    >>> G = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0]])
+    >>> G
+    array([[0, 0, 0],
+           [0, 0, 1],
+           [0, 1, 0]])
+    >>> L, d = csgraph.laplacian(G, return_diag=True, normed=True)
+    >>> L
+    array([[ 0., -0., -0.],
+           [-0.,  1., -1.],
+           [-0., -1.,  1.]])
+    >>> d
+    array([1., 1., 1.])
+
+    Only the symmetric normalization is implemented, resulting
+    in a symmetric Laplacian matrix if and only if its graph is symmetric
+    and has all non-negative degrees, like in the examples above.
+
+    The output Laplacian matrix is by default a dense array or a sparse matrix
+    inferring its shape, format, and dtype from the input graph matrix:
+
+    >>> G = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]).astype(np.float32)
+    >>> G
+    array([[0., 1., 1.],
+           [1., 0., 1.],
+           [1., 1., 0.]], dtype=float32)
+    >>> csgraph.laplacian(G)
+    array([[ 2., -1., -1.],
+           [-1.,  2., -1.],
+           [-1., -1.,  2.]], dtype=float32)
+
+    but can alternatively be generated matrix-free as a LinearOperator:
+
+    >>> L = csgraph.laplacian(G, form="lo")
+    >>> L
+    <3x3 _CustomLinearOperator with dtype=float32>
+    >>> L(np.eye(3))
+    array([[ 2., -1., -1.],
+           [-1.,  2., -1.],
+           [-1., -1.,  2.]])
+
+    or as a lambda-function:
+
+    >>> L = csgraph.laplacian(G, form="function")
+    >>> L
+    . at 0x0000012AE6F5A598>
+    >>> L(np.eye(3))
+    array([[ 2., -1., -1.],
+           [-1.,  2., -1.],
+           [-1., -1.,  2.]])
+
+    The Laplacian matrix is used for
+    spectral data clustering and embedding
+    as well as for spectral graph partitioning.
+    Our final example illustrates the latter
+    for a noisy directed linear graph.
+
+    >>> from scipy.sparse import diags, random
+    >>> from scipy.sparse.linalg import lobpcg
+
+    Create a directed linear graph with ``N=35`` vertices
+    using a sparse adjacency matrix ``G``:
+
+    >>> N = 35
+    >>> G = diags(np.ones(N-1), 1, format="csr")
+
+    Fix a random seed ``rng`` and add a random sparse noise to the graph ``G``:
+
+    >>> rng = np.random.default_rng()
+    >>> G += 1e-2 * random(N, N, density=0.1, random_state=rng)
+
+    Set initial approximations for eigenvectors:
+
+    >>> X = rng.random((N, 2))
+
+    The constant vector of ones is always a trivial eigenvector
+    of the non-normalized Laplacian to be filtered out:
+
+    >>> Y = np.ones((N, 1))
+
+    Alternating (1) the sign of the graph weights allows determining
+    labels for spectral max- and min- cuts in a single loop.
+    Since the graph is undirected, the option ``symmetrized=True``
+    must be used in the construction of the Laplacian.
+    The option ``normed=True`` cannot be used in (2) for the negative weights
+    here as the symmetric normalization evaluates square roots.
+    The option ``form="lo"`` in (2) is matrix-free, i.e., guarantees
+    a fixed memory footprint and read-only access to the graph.
+    Calling the eigenvalue solver ``lobpcg`` (3) computes the Fiedler vector
+    that determines the labels as the signs of its components in (5).
+    Since the sign in an eigenvector is not deterministic and can flip,
+    we fix the sign of the first component to be always +1 in (4).
+
+    >>> for cut in ["max", "min"]:
+    ...     G = -G  # 1.
+    ...     L = csgraph.laplacian(G, symmetrized=True, form="lo")  # 2.
+    ...     _, eves = lobpcg(L, X, Y=Y, largest=False, tol=1e-3)  # 3.
+    ...     eves *= np.sign(eves[0, 0])  # 4.
+    ...     print(cut + "-cut labels:\\n", 1 * (eves[:, 0]>0))  # 5.
+    max-cut labels:
+    [1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1]
+    min-cut labels:
+    [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
+
+    As anticipated for a (slightly noisy) linear graph,
+    the max-cut strips all the edges of the graph coloring all
+    odd vertices into one color and all even vertices into another one,
+    while the balanced min-cut partitions the graph
+    in the middle by deleting a single edge.
+    Both determined partitions are optimal.
+    """
+    if csgraph.ndim != 2 or csgraph.shape[0] != csgraph.shape[1]:
+        raise ValueError("csgraph must be a square matrix or array")
+
+    if normed and (
+        np.issubdtype(csgraph.dtype, np.signedinteger)
+        or np.issubdtype(csgraph.dtype, np.uint)
+    ):
+        csgraph = csgraph.astype(np.float64)
+
+    if form == "array":
+        create_lap = _laplacian_sparse if issparse(csgraph) else _laplacian_dense
+    else:
+        create_lap = (
+            _laplacian_sparse_flo if issparse(csgraph) else _laplacian_dense_flo
+        )
+
+    degree_axis = 1 if use_out_degree else 0
+
+    lap, d = create_lap(
+        csgraph,
+        normed=normed,
+        axis=degree_axis,
+        copy=copy,
+        form=form,
+        dtype=dtype,
+        symmetrized=symmetrized,
+    )
+    if return_diag:
+        return lap, d
+    return lap
+
+
+def _setdiag_dense(m, d):
+    step = len(d) + 1
+    m.flat[::step] = d
+
+
+def _laplace(m, d):
+    return lambda v: v * d[:, np.newaxis] - m @ v
+
+
+def _laplace_normed(m, d, nd):
+    laplace = _laplace(m, d)
+    return lambda v: nd[:, np.newaxis] * laplace(v * nd[:, np.newaxis])
+
+
+def _laplace_sym(m, d):
+    return (
+        lambda v: v * d[:, np.newaxis]
+        - m @ v
+        - np.transpose(np.conjugate(np.transpose(np.conjugate(v)) @ m))
+    )
+
+
+def _laplace_normed_sym(m, d, nd):
+    laplace_sym = _laplace_sym(m, d)
+    return lambda v: nd[:, np.newaxis] * laplace_sym(v * nd[:, np.newaxis])
+
+
+def _linearoperator(mv, shape, dtype):
+    return LinearOperator(matvec=mv, matmat=mv, shape=shape, dtype=dtype)
+
+
+def _laplacian_sparse_flo(graph, normed, axis, copy, form, dtype, symmetrized):
+    # The keyword argument `copy` is unused and has no effect here.
+    del copy
+
+    if dtype is None:
+        dtype = graph.dtype
+
+    graph_sum = np.asarray(graph.sum(axis=axis)).ravel()
+    graph_diagonal = graph.diagonal()
+    diag = graph_sum - graph_diagonal
+    if symmetrized:
+        graph_sum += np.asarray(graph.sum(axis=1 - axis)).ravel()
+        diag = graph_sum - graph_diagonal - graph_diagonal
+
+    if normed:
+        isolated_node_mask = diag == 0
+        w = np.where(isolated_node_mask, 1, np.sqrt(diag))
+        if symmetrized:
+            md = _laplace_normed_sym(graph, graph_sum, 1.0 / w)
+        else:
+            md = _laplace_normed(graph, graph_sum, 1.0 / w)
+        if form == "function":
+            return md, w.astype(dtype, copy=False)
+        elif form == "lo":
+            m = _linearoperator(md, shape=graph.shape, dtype=dtype)
+            return m, w.astype(dtype, copy=False)
+        else:
+            raise ValueError(f"Invalid form: {form!r}")
+    else:
+        if symmetrized:
+            md = _laplace_sym(graph, graph_sum)
+        else:
+            md = _laplace(graph, graph_sum)
+        if form == "function":
+            return md, diag.astype(dtype, copy=False)
+        elif form == "lo":
+            m = _linearoperator(md, shape=graph.shape, dtype=dtype)
+            return m, diag.astype(dtype, copy=False)
+        else:
+            raise ValueError(f"Invalid form: {form!r}")
+
+
+def _laplacian_sparse(graph, normed, axis, copy, form, dtype, symmetrized):
+    # The keyword argument `form` is unused and has no effect here.
+    del form
+
+    if dtype is None:
+        dtype = graph.dtype
+
+    needs_copy = False
+    if graph.format in ("lil", "dok"):
+        m = graph.tocoo()
+    else:
+        m = graph
+        if copy:
+            needs_copy = True
+
+    if symmetrized:
+        m += m.T.conj()
+
+    w = np.asarray(m.sum(axis=axis)).ravel() - m.diagonal()
+    if normed:
+        m = m.tocoo(copy=needs_copy)
+        isolated_node_mask = w == 0
+        w = np.where(isolated_node_mask, 1, np.sqrt(w))
+        m.data /= w[m.row]
+        m.data /= w[m.col]
+        m.data *= -1
+        m.setdiag(1 - isolated_node_mask)
+    else:
+        if m.format == "dia":
+            m = m.copy()
+        else:
+            m = m.tocoo(copy=needs_copy)
+        m.data *= -1
+        m.setdiag(w)
+
+    return m.astype(dtype, copy=False), w.astype(dtype)
+
+
+def _laplacian_dense_flo(graph, normed, axis, copy, form, dtype, symmetrized):
+    if copy:
+        m = np.array(graph)
+    else:
+        m = np.asarray(graph)
+
+    if dtype is None:
+        dtype = m.dtype
+
+    graph_sum = m.sum(axis=axis)
+    graph_diagonal = m.diagonal()
+    diag = graph_sum - graph_diagonal
+    if symmetrized:
+        graph_sum += m.sum(axis=1 - axis)
+        diag = graph_sum - graph_diagonal - graph_diagonal
+
+    if normed:
+        isolated_node_mask = diag == 0
+        w = np.where(isolated_node_mask, 1, np.sqrt(diag))
+        if symmetrized:
+            md = _laplace_normed_sym(m, graph_sum, 1.0 / w)
+        else:
+            md = _laplace_normed(m, graph_sum, 1.0 / w)
+        if form == "function":
+            return md, w.astype(dtype, copy=False)
+        elif form == "lo":
+            m = _linearoperator(md, shape=graph.shape, dtype=dtype)
+            return m, w.astype(dtype, copy=False)
+        else:
+            raise ValueError(f"Invalid form: {form!r}")
+    else:
+        if symmetrized:
+            md = _laplace_sym(m, graph_sum)
+        else:
+            md = _laplace(m, graph_sum)
+        if form == "function":
+            return md, diag.astype(dtype, copy=False)
+        elif form == "lo":
+            m = _linearoperator(md, shape=graph.shape, dtype=dtype)
+            return m, diag.astype(dtype, copy=False)
+        else:
+            raise ValueError(f"Invalid form: {form!r}")
+
+
+def _laplacian_dense(graph, normed, axis, copy, form, dtype, symmetrized):
+    if form != "array":
+        raise ValueError(f'{form!r} must be "array"')
+
+    if dtype is None:
+        dtype = graph.dtype
+
+    if copy:
+        m = np.array(graph)
+    else:
+        m = np.asarray(graph)
+
+    if dtype is None:
+        dtype = m.dtype
+
+    if symmetrized:
+        m += m.T.conj()
+    np.fill_diagonal(m, 0)
+    w = m.sum(axis=axis)
+    if normed:
+        isolated_node_mask = w == 0
+        w = np.where(isolated_node_mask, 1, np.sqrt(w))
+        m /= w
+        m /= w[:, np.newaxis]
+        m *= -1
+        _setdiag_dense(m, 1 - isolated_node_mask)
+    else:
+        m *= -1
+        _setdiag_dense(m, w)
+
+    return m.astype(dtype, copy=False), w.astype(dtype, copy=False)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/LICENSE b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..ca9f2fee821caf1a99a27ea17e3467cccd8c73b8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2022 Consortium for Python Data API Standards
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/README.md b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..a3360988cbc1cd2d9710d9b010b44300122ca6ef
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/README.md
@@ -0,0 +1 @@
+Update this directory using maint_tools/vendor_array_api_compat.sh
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..653cb40a37607e0e82b6e91d57a96bf0021a95a8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/__init__.py
@@ -0,0 +1,22 @@
+"""
+NumPy Array API compatibility library
+
+This is a small wrapper around NumPy, CuPy, JAX, sparse and others that are
+compatible with the Array API standard https://data-apis.org/array-api/latest/.
+See also NEP 47 https://numpy.org/neps/nep-0047-array-api-standard.html.
+
+Unlike array_api_strict, this is not a strict minimal implementation of the
+Array API, but rather just an extension of the main NumPy namespace with
+changes needed to be compliant with the Array API. See
+https://numpy.org/doc/stable/reference/array_api.html for a full list of
+changes. In particular, unlike array_api_strict, this package does not use a
+separate Array object, but rather just uses numpy.ndarray directly.
+
+Library authors using the Array API may wish to test against array_api_strict
+to ensure they are not using functionality outside of the standard, but prefer
+this implementation for the default when working with NumPy arrays.
+
+"""
+__version__ = '1.12.0'
+
+from .common import *  # noqa: F401, F403
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a7eef87ba6e47d662be727830fe6aab317ea23f3
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/__pycache__/_internal.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/__pycache__/_internal.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b4baf4c2222b396338177d1b2056b599d31e0a56
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/__pycache__/_internal.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/_internal.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/_internal.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd8d939f36de23e31f794792fd289d1706626c56
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/_internal.py
@@ -0,0 +1,59 @@
+"""
+Internal helpers
+"""
+
+from collections.abc import Callable
+from functools import wraps
+from inspect import signature
+from types import ModuleType
+from typing import TypeVar
+
+_T = TypeVar("_T")
+
+
+def get_xp(xp: ModuleType) -> Callable[[Callable[..., _T]], Callable[..., _T]]:
+    """
+    Decorator to automatically replace xp with the corresponding array module.
+
+    Use like
+
+    import numpy as np
+
+    @get_xp(np)
+    def func(x, /, xp, kwarg=None):
+        return xp.func(x, kwarg=kwarg)
+
+    Note that xp must be a keyword argument and come after all non-keyword
+    arguments.
+
+    """
+
+    def inner(f: Callable[..., _T], /) -> Callable[..., _T]:
+        @wraps(f)
+        def wrapped_f(*args: object, **kwargs: object) -> object:
+            return f(*args, xp=xp, **kwargs)
+
+        sig = signature(f)
+        new_sig = sig.replace(
+            parameters=[par for i, par in sig.parameters.items() if i != "xp"]
+        )
+
+        if wrapped_f.__doc__ is None:
+            wrapped_f.__doc__ = f"""\
+Array API compatibility wrapper for {f.__name__}.
+
+See the corresponding documentation in NumPy/CuPy and/or the array API
+specification for more details.
+
+"""
+        wrapped_f.__signature__ = new_sig  # pyright: ignore[reportAttributeAccessIssue]
+        return wrapped_f  # pyright: ignore[reportReturnType]
+
+    return inner
+
+
+__all__ = ["get_xp"]
+
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8236080738175f0fb7d1f47fcc52522306b43050
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__init__.py
@@ -0,0 +1 @@
+from ._helpers import *  # noqa: F403
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1254da9770ad0334de53065baa0e600c3735bc4f
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__pycache__/_aliases.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__pycache__/_aliases.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..048eb285fd773b4e33c6032d5d12c49605d9f79a
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__pycache__/_aliases.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__pycache__/_fft.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__pycache__/_fft.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6cfbae76cf2ead3db296e3d521c5301c79b81747
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__pycache__/_fft.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__pycache__/_helpers.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__pycache__/_helpers.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d1622c3e9f9ba39a6e815aba45377b7a6f635d8
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__pycache__/_helpers.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__pycache__/_linalg.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__pycache__/_linalg.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a301bf3e4062df220552771768828cfef95a9e8b
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__pycache__/_linalg.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__pycache__/_typing.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__pycache__/_typing.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..574f424b66e6be5a2bd339b6c45773d91d0fc584
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/__pycache__/_typing.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/_aliases.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ea9162a9edc84a668685b4b82e68626c9f30ba7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/_aliases.py
@@ -0,0 +1,727 @@
+"""
+These are functions that are just aliases of existing functions in NumPy.
+"""
+
+from __future__ import annotations
+
+import inspect
+from typing import TYPE_CHECKING, Any, NamedTuple, Optional, Sequence, cast
+
+from ._helpers import _check_device, array_namespace
+from ._helpers import device as _get_device
+from ._helpers import is_cupy_namespace as _is_cupy_namespace
+from ._typing import Array, Device, DType, Namespace
+
+if TYPE_CHECKING:
+    # TODO: import from typing (requires Python >=3.13)
+    from typing_extensions import TypeIs
+
+# These functions are modified from the NumPy versions.
+
+# Creation functions add the device keyword (which does nothing for NumPy and Dask)
+
+
+def arange(
+    start: float,
+    /,
+    stop: float | None = None,
+    step: float = 1,
+    *,
+    xp: Namespace,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.arange(start, stop=stop, step=step, dtype=dtype, **kwargs)
+
+
+def empty(
+    shape: int | tuple[int, ...],
+    xp: Namespace,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.empty(shape, dtype=dtype, **kwargs)
+
+
+def empty_like(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.empty_like(x, dtype=dtype, **kwargs)
+
+
+def eye(
+    n_rows: int,
+    n_cols: int | None = None,
+    /,
+    *,
+    xp: Namespace,
+    k: int = 0,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.eye(n_rows, M=n_cols, k=k, dtype=dtype, **kwargs)
+
+
+def full(
+    shape: int | tuple[int, ...],
+    fill_value: complex,
+    xp: Namespace,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.full(shape, fill_value, dtype=dtype, **kwargs)
+
+
+def full_like(
+    x: Array,
+    /,
+    fill_value: complex,
+    *,
+    xp: Namespace,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.full_like(x, fill_value, dtype=dtype, **kwargs)
+
+
+def linspace(
+    start: float,
+    stop: float,
+    /,
+    num: int,
+    *,
+    xp: Namespace,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    endpoint: bool = True,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.linspace(start, stop, num, dtype=dtype, endpoint=endpoint, **kwargs)
+
+
+def ones(
+    shape: int | tuple[int, ...],
+    xp: Namespace,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.ones(shape, dtype=dtype, **kwargs)
+
+
+def ones_like(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.ones_like(x, dtype=dtype, **kwargs)
+
+
+def zeros(
+    shape: int | tuple[int, ...],
+    xp: Namespace,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.zeros(shape, dtype=dtype, **kwargs)
+
+
+def zeros_like(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    _check_device(xp, device)
+    return xp.zeros_like(x, dtype=dtype, **kwargs)
+
+
+# np.unique() is split into four functions in the array API:
+# unique_all, unique_counts, unique_inverse, and unique_values (this is done
+# to remove polymorphic return types).
+
+# The functions here return namedtuples (np.unique() returns a normal
+# tuple).
+
+
+# Note that these named tuples aren't actually part of the standard namespace,
+# but I don't see any issue with exporting the names here regardless.
+class UniqueAllResult(NamedTuple):
+    values: Array
+    indices: Array
+    inverse_indices: Array
+    counts: Array
+
+
+class UniqueCountsResult(NamedTuple):
+    values: Array
+    counts: Array
+
+
+class UniqueInverseResult(NamedTuple):
+    values: Array
+    inverse_indices: Array
+
+
+def _unique_kwargs(xp: Namespace) -> dict[str, bool]:
+    # Older versions of NumPy and CuPy do not have equal_nan. Rather than
+    # trying to parse version numbers, just check if equal_nan is in the
+    # signature.
+    s = inspect.signature(xp.unique)
+    if "equal_nan" in s.parameters:
+        return {"equal_nan": False}
+    return {}
+
+
+def unique_all(x: Array, /, xp: Namespace) -> UniqueAllResult:
+    kwargs = _unique_kwargs(xp)
+    values, indices, inverse_indices, counts = xp.unique(
+        x,
+        return_counts=True,
+        return_index=True,
+        return_inverse=True,
+        **kwargs,
+    )
+    # np.unique() flattens inverse indices, but they need to share x's shape
+    # See https://github.com/numpy/numpy/issues/20638
+    inverse_indices = inverse_indices.reshape(x.shape)
+    return UniqueAllResult(
+        values,
+        indices,
+        inverse_indices,
+        counts,
+    )
+
+
+def unique_counts(x: Array, /, xp: Namespace) -> UniqueCountsResult:
+    kwargs = _unique_kwargs(xp)
+    res = xp.unique(
+        x, return_counts=True, return_index=False, return_inverse=False, **kwargs
+    )
+
+    return UniqueCountsResult(*res)
+
+
+def unique_inverse(x: Array, /, xp: Namespace) -> UniqueInverseResult:
+    kwargs = _unique_kwargs(xp)
+    values, inverse_indices = xp.unique(
+        x,
+        return_counts=False,
+        return_index=False,
+        return_inverse=True,
+        **kwargs,
+    )
+    # xp.unique() flattens inverse indices, but they need to share x's shape
+    # See https://github.com/numpy/numpy/issues/20638
+    inverse_indices = inverse_indices.reshape(x.shape)
+    return UniqueInverseResult(values, inverse_indices)
+
+
+def unique_values(x: Array, /, xp: Namespace) -> Array:
+    kwargs = _unique_kwargs(xp)
+    return xp.unique(
+        x,
+        return_counts=False,
+        return_index=False,
+        return_inverse=False,
+        **kwargs,
+    )
+
+
+# These functions have different keyword argument names
+
+
+def std(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    axis: int | tuple[int, ...] | None = None,
+    correction: float = 0.0,  # correction instead of ddof
+    keepdims: bool = False,
+    **kwargs: object,
+) -> Array:
+    return xp.std(x, axis=axis, ddof=correction, keepdims=keepdims, **kwargs)
+
+
+def var(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    axis: int | tuple[int, ...] | None = None,
+    correction: float = 0.0,  # correction instead of ddof
+    keepdims: bool = False,
+    **kwargs: object,
+) -> Array:
+    return xp.var(x, axis=axis, ddof=correction, keepdims=keepdims, **kwargs)
+
+
+# cumulative_sum is renamed from cumsum, and adds the include_initial keyword
+# argument
+
+
+def cumulative_sum(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    axis: int | None = None,
+    dtype: DType | None = None,
+    include_initial: bool = False,
+    **kwargs: object,
+) -> Array:
+    wrapped_xp = array_namespace(x)
+
+    # TODO: The standard is not clear about what should happen when x.ndim == 0.
+    if axis is None:
+        if x.ndim > 1:
+            raise ValueError(
+                "axis must be specified in cumulative_sum for more than one dimension"
+            )
+        axis = 0
+
+    res = xp.cumsum(x, axis=axis, dtype=dtype, **kwargs)
+
+    # np.cumsum does not support include_initial
+    if include_initial:
+        initial_shape = list(x.shape)
+        initial_shape[axis] = 1
+        res = xp.concatenate(
+            [
+                wrapped_xp.zeros(
+                    shape=initial_shape, dtype=res.dtype, device=_get_device(res)
+                ),
+                res,
+            ],
+            axis=axis,
+        )
+    return res
+
+
+def cumulative_prod(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    axis: int | None = None,
+    dtype: DType | None = None,
+    include_initial: bool = False,
+    **kwargs: object,
+) -> Array:
+    wrapped_xp = array_namespace(x)
+
+    if axis is None:
+        if x.ndim > 1:
+            raise ValueError(
+                "axis must be specified in cumulative_prod for more than one dimension"
+            )
+        axis = 0
+
+    res = xp.cumprod(x, axis=axis, dtype=dtype, **kwargs)
+
+    # np.cumprod does not support include_initial
+    if include_initial:
+        initial_shape = list(x.shape)
+        initial_shape[axis] = 1
+        res = xp.concatenate(
+            [
+                wrapped_xp.ones(
+                    shape=initial_shape, dtype=res.dtype, device=_get_device(res)
+                ),
+                res,
+            ],
+            axis=axis,
+        )
+    return res
+
+
+# The min and max argument names in clip are different and not optional in numpy, and type
+# promotion behavior is different.
+def clip(
+    x: Array,
+    /,
+    min: float | Array | None = None,
+    max: float | Array | None = None,
+    *,
+    xp: Namespace,
+    # TODO: np.clip has other ufunc kwargs
+    out: Array | None = None,
+) -> Array:
+    def _isscalar(a: object) -> TypeIs[int | float | None]:
+        return isinstance(a, (int, float, type(None)))
+
+    min_shape = () if _isscalar(min) else min.shape
+    max_shape = () if _isscalar(max) else max.shape
+
+    wrapped_xp = array_namespace(x)
+
+    result_shape = xp.broadcast_shapes(x.shape, min_shape, max_shape)
+
+    # np.clip does type promotion but the array API clip requires that the
+    # output have the same dtype as x. We do this instead of just downcasting
+    # the result of xp.clip() to handle some corner cases better (e.g.,
+    # avoiding uint64 -> float64 promotion).
+
+    # Note: cases where min or max overflow (integer) or round (float) in the
+    # wrong direction when downcasting to x.dtype are unspecified. This code
+    # just does whatever NumPy does when it downcasts in the assignment, but
+    # other behavior could be preferred, especially for integers. For example,
+    # this code produces:
+
+    # >>> clip(asarray(0, dtype=int8), asarray(128, dtype=int16), None)
+    # -128
+
+    # but an answer of 0 might be preferred. See
+    # https://github.com/numpy/numpy/issues/24976 for more discussion on this issue.
+
+    # At least handle the case of Python integers correctly (see
+    # https://github.com/numpy/numpy/pull/26892).
+    if wrapped_xp.isdtype(x.dtype, "integral"):
+        if type(min) is int and min <= wrapped_xp.iinfo(x.dtype).min:
+            min = None
+        if type(max) is int and max >= wrapped_xp.iinfo(x.dtype).max:
+            max = None
+
+    dev = _get_device(x)
+    if out is None:
+        out = wrapped_xp.empty(result_shape, dtype=x.dtype, device=dev)
+    assert out is not None  # workaround for a type-narrowing issue in pyright
+    out[()] = x
+
+    if min is not None:
+        a = wrapped_xp.asarray(min, dtype=x.dtype, device=dev)
+        a = xp.broadcast_to(a, result_shape)
+        ia = (out < a) | xp.isnan(a)
+        out[ia] = a[ia]
+
+    if max is not None:
+        b = wrapped_xp.asarray(max, dtype=x.dtype, device=dev)
+        b = xp.broadcast_to(b, result_shape)
+        ib = (out > b) | xp.isnan(b)
+        out[ib] = b[ib]
+
+    # Return a scalar for 0-D
+    return out[()]
+
+
+# Unlike transpose(), the axes argument to permute_dims() is required.
+def permute_dims(x: Array, /, axes: tuple[int, ...], xp: Namespace) -> Array:
+    return xp.transpose(x, axes)
+
+
+# np.reshape calls the keyword argument 'newshape' instead of 'shape'
+def reshape(
+    x: Array,
+    /,
+    shape: tuple[int, ...],
+    xp: Namespace,
+    *,
+    copy: Optional[bool] = None,
+    **kwargs: object,
+) -> Array:
+    if copy is True:
+        x = x.copy()
+    elif copy is False:
+        y = x.view()
+        y.shape = shape
+        return y
+    return xp.reshape(x, shape, **kwargs)
+
+
+# The descending keyword is new in sort and argsort, and 'kind' replaced with
+# 'stable'
+def argsort(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    axis: int = -1,
+    descending: bool = False,
+    stable: bool = True,
+    **kwargs: object,
+) -> Array:
+    # Note: this keyword argument is different, and the default is different.
+    # We set it in kwargs like this because numpy.sort uses kind='quicksort'
+    # as the default whereas cupy.sort uses kind=None.
+    if stable:
+        kwargs["kind"] = "stable"
+    if not descending:
+        res = xp.argsort(x, axis=axis, **kwargs)
+    else:
+        # As NumPy has no native descending sort, we imitate it here. Note that
+        # simply flipping the results of xp.argsort(x, ...) would not
+        # respect the relative order like it would in native descending sorts.
+        res = xp.flip(
+            xp.argsort(xp.flip(x, axis=axis), axis=axis, **kwargs),
+            axis=axis,
+        )
+        # Rely on flip()/argsort() to validate axis
+        normalised_axis = axis if axis >= 0 else x.ndim + axis
+        max_i = x.shape[normalised_axis] - 1
+        res = max_i - res
+    return res
+
+
+def sort(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    axis: int = -1,
+    descending: bool = False,
+    stable: bool = True,
+    **kwargs: object,
+) -> Array:
+    # Note: this keyword argument is different, and the default is different.
+    # We set it in kwargs like this because numpy.sort uses kind='quicksort'
+    # as the default whereas cupy.sort uses kind=None.
+    if stable:
+        kwargs["kind"] = "stable"
+    res = xp.sort(x, axis=axis, **kwargs)
+    if descending:
+        res = xp.flip(res, axis=axis)
+    return res
+
+
+# nonzero should error for zero-dimensional arrays
+def nonzero(x: Array, /, xp: Namespace, **kwargs: object) -> tuple[Array, ...]:
+    if x.ndim == 0:
+        raise ValueError("nonzero() does not support zero-dimensional arrays")
+    return xp.nonzero(x, **kwargs)
+
+
+# ceil, floor, and trunc return integers for integer inputs
+
+
+def ceil(x: Array, /, xp: Namespace, **kwargs: object) -> Array:
+    if xp.issubdtype(x.dtype, xp.integer):
+        return x
+    return xp.ceil(x, **kwargs)
+
+
+def floor(x: Array, /, xp: Namespace, **kwargs: object) -> Array:
+    if xp.issubdtype(x.dtype, xp.integer):
+        return x
+    return xp.floor(x, **kwargs)
+
+
+def trunc(x: Array, /, xp: Namespace, **kwargs: object) -> Array:
+    if xp.issubdtype(x.dtype, xp.integer):
+        return x
+    return xp.trunc(x, **kwargs)
+
+
+# linear algebra functions
+
+
+def matmul(x1: Array, x2: Array, /, xp: Namespace, **kwargs: object) -> Array:
+    return xp.matmul(x1, x2, **kwargs)
+
+
+# Unlike transpose, matrix_transpose only transposes the last two axes.
+def matrix_transpose(x: Array, /, xp: Namespace) -> Array:
+    if x.ndim < 2:
+        raise ValueError("x must be at least 2-dimensional for matrix_transpose")
+    return xp.swapaxes(x, -1, -2)
+
+
+def tensordot(
+    x1: Array,
+    x2: Array,
+    /,
+    xp: Namespace,
+    *,
+    axes: int | tuple[Sequence[int], Sequence[int]] = 2,
+    **kwargs: object,
+) -> Array:
+    return xp.tensordot(x1, x2, axes=axes, **kwargs)
+
+
+def vecdot(x1: Array, x2: Array, /, xp: Namespace, *, axis: int = -1) -> Array:
+    if x1.shape[axis] != x2.shape[axis]:
+        raise ValueError("x1 and x2 must have the same size along the given axis")
+
+    if hasattr(xp, "broadcast_tensors"):
+        _broadcast = xp.broadcast_tensors
+    else:
+        _broadcast = xp.broadcast_arrays
+
+    x1_ = xp.moveaxis(x1, axis, -1)
+    x2_ = xp.moveaxis(x2, axis, -1)
+    x1_, x2_ = _broadcast(x1_, x2_)
+
+    res = xp.conj(x1_[..., None, :]) @ x2_[..., None]
+    return res[..., 0, 0]
+
+
+# isdtype is a new function in the 2022.12 array API specification.
+
+
+def isdtype(
+    dtype: DType,
+    kind: DType | str | tuple[DType | str, ...],
+    xp: Namespace,
+    *,
+    _tuple: bool = True,  # Disallow nested tuples
+) -> bool:
+    """
+    Returns a boolean indicating whether a provided dtype is of a specified data type ``kind``.
+
+    Note that outside of this function, this compat library does not yet fully
+    support complex numbers.
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/generated/array_api.isdtype.html
+    for more details
+    """
+    if isinstance(kind, tuple) and _tuple:
+        return any(
+            isdtype(dtype, k, xp, _tuple=False)
+            for k in cast("tuple[DType | str, ...]", kind)
+        )
+    elif isinstance(kind, str):
+        if kind == "bool":
+            return dtype == xp.bool_
+        elif kind == "signed integer":
+            return xp.issubdtype(dtype, xp.signedinteger)
+        elif kind == "unsigned integer":
+            return xp.issubdtype(dtype, xp.unsignedinteger)
+        elif kind == "integral":
+            return xp.issubdtype(dtype, xp.integer)
+        elif kind == "real floating":
+            return xp.issubdtype(dtype, xp.floating)
+        elif kind == "complex floating":
+            return xp.issubdtype(dtype, xp.complexfloating)
+        elif kind == "numeric":
+            return xp.issubdtype(dtype, xp.number)
+        else:
+            raise ValueError(f"Unrecognized data type kind: {kind!r}")
+    else:
+        # This will allow things that aren't required by the spec, like
+        # isdtype(np.float64, float) or isdtype(np.int64, 'l'). Should we be
+        # more strict here to match the type annotation? Note that the
+        # array_api_strict implementation will be very strict.
+        return dtype == kind
+
+
+# unstack is a new function in the 2023.12 array API standard
+def unstack(x: Array, /, xp: Namespace, *, axis: int = 0) -> tuple[Array, ...]:
+    if x.ndim == 0:
+        raise ValueError("Input array must be at least 1-d.")
+    return tuple(xp.moveaxis(x, axis, 0))
+
+
+# numpy 1.26 does not use the standard definition for sign on complex numbers
+
+
+def sign(x: Array, /, xp: Namespace, **kwargs: object) -> Array:
+    if isdtype(x.dtype, "complex floating", xp=xp):
+        out = (x / xp.abs(x, **kwargs))[...]
+        # sign(0) = 0 but the above formula would give nan
+        out[x == 0j] = 0j
+    else:
+        out = xp.sign(x, **kwargs)
+    # CuPy sign() does not propagate nans. See
+    # https://github.com/data-apis/array-api-compat/issues/136
+    if _is_cupy_namespace(xp) and isdtype(x.dtype, "real floating", xp=xp):
+        out[xp.isnan(x)] = xp.nan
+    return out[()]
+
+
+def finfo(type_: DType | Array, /, xp: Namespace) -> Any:
+    # It is surprisingly difficult to recognize a dtype apart from an array.
+    # np.int64 is not the same as np.asarray(1).dtype!
+    try:
+        return xp.finfo(type_)
+    except (ValueError, TypeError):
+        return xp.finfo(type_.dtype)
+
+
+def iinfo(type_: DType | Array, /, xp: Namespace) -> Any:
+    try:
+        return xp.iinfo(type_)
+    except (ValueError, TypeError):
+        return xp.iinfo(type_.dtype)
+
+
+__all__ = [
+    "arange",
+    "empty",
+    "empty_like",
+    "eye",
+    "full",
+    "full_like",
+    "linspace",
+    "ones",
+    "ones_like",
+    "zeros",
+    "zeros_like",
+    "UniqueAllResult",
+    "UniqueCountsResult",
+    "UniqueInverseResult",
+    "unique_all",
+    "unique_counts",
+    "unique_inverse",
+    "unique_values",
+    "std",
+    "var",
+    "cumulative_sum",
+    "cumulative_prod",
+    "clip",
+    "permute_dims",
+    "reshape",
+    "argsort",
+    "sort",
+    "nonzero",
+    "ceil",
+    "floor",
+    "trunc",
+    "matmul",
+    "matrix_transpose",
+    "tensordot",
+    "vecdot",
+    "isdtype",
+    "unstack",
+    "sign",
+    "finfo",
+    "iinfo",
+]
+_all_ignore = ["inspect", "array_namespace", "NamedTuple"]
+
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/_fft.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/_fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..18839d37f84949ec2bf851b548c2e13b5179e04e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/_fft.py
@@ -0,0 +1,213 @@
+from __future__ import annotations
+
+from collections.abc import Sequence
+from typing import Literal, TypeAlias
+
+from ._typing import Array, Device, DType, Namespace
+
+_Norm: TypeAlias = Literal["backward", "ortho", "forward"]
+
+# Note: NumPy fft functions improperly upcast float32 and complex64 to
+# complex128, which is why we require wrapping them all here.
+
+def fft(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    n: int | None = None,
+    axis: int = -1,
+    norm: _Norm = "backward",
+) -> Array:
+    res = xp.fft.fft(x, n=n, axis=axis, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.complex64)
+    return res
+
+def ifft(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    n: int | None = None,
+    axis: int = -1,
+    norm: _Norm = "backward",
+) -> Array:
+    res = xp.fft.ifft(x, n=n, axis=axis, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.complex64)
+    return res
+
+def fftn(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    s: Sequence[int] | None = None,
+    axes: Sequence[int] | None = None,
+    norm: _Norm = "backward",
+) -> Array:
+    res = xp.fft.fftn(x, s=s, axes=axes, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.complex64)
+    return res
+
+def ifftn(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    s: Sequence[int] | None = None,
+    axes: Sequence[int] | None = None,
+    norm: _Norm = "backward",
+) -> Array:
+    res = xp.fft.ifftn(x, s=s, axes=axes, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.complex64)
+    return res
+
+def rfft(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    n: int | None = None,
+    axis: int = -1,
+    norm: _Norm = "backward",
+) -> Array:
+    res = xp.fft.rfft(x, n=n, axis=axis, norm=norm)
+    if x.dtype == xp.float32:
+        return res.astype(xp.complex64)
+    return res
+
+def irfft(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    n: int | None = None,
+    axis: int = -1,
+    norm: _Norm = "backward",
+) -> Array:
+    res = xp.fft.irfft(x, n=n, axis=axis, norm=norm)
+    if x.dtype == xp.complex64:
+        return res.astype(xp.float32)
+    return res
+
+def rfftn(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    s: Sequence[int] | None = None,
+    axes: Sequence[int] | None = None,
+    norm: _Norm = "backward",
+) -> Array:
+    res = xp.fft.rfftn(x, s=s, axes=axes, norm=norm)
+    if x.dtype == xp.float32:
+        return res.astype(xp.complex64)
+    return res
+
+def irfftn(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    s: Sequence[int] | None = None,
+    axes: Sequence[int] | None = None,
+    norm: _Norm = "backward",
+) -> Array:
+    res = xp.fft.irfftn(x, s=s, axes=axes, norm=norm)
+    if x.dtype == xp.complex64:
+        return res.astype(xp.float32)
+    return res
+
+def hfft(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    n: int | None = None,
+    axis: int = -1,
+    norm: _Norm = "backward",
+) -> Array:
+    res = xp.fft.hfft(x, n=n, axis=axis, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.float32)
+    return res
+
+def ihfft(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    n: int | None = None,
+    axis: int = -1,
+    norm: _Norm = "backward",
+) -> Array:
+    res = xp.fft.ihfft(x, n=n, axis=axis, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.complex64)
+    return res
+
+def fftfreq(
+    n: int,
+    /,
+    xp: Namespace,
+    *,
+    d: float = 1.0,
+    dtype: DType | None = None,
+    device: Device | None = None,
+) -> Array:
+    if device not in ["cpu", None]:
+        raise ValueError(f"Unsupported device {device!r}")
+    res = xp.fft.fftfreq(n, d=d)
+    if dtype is not None:
+        return res.astype(dtype)
+    return res
+
+def rfftfreq(
+    n: int,
+    /,
+    xp: Namespace,
+    *,
+    d: float = 1.0,
+    dtype: DType | None = None,
+    device: Device | None = None,
+) -> Array:
+    if device not in ["cpu", None]:
+        raise ValueError(f"Unsupported device {device!r}")
+    res = xp.fft.rfftfreq(n, d=d)
+    if dtype is not None:
+        return res.astype(dtype)
+    return res
+
+def fftshift(
+    x: Array, /, xp: Namespace, *, axes: int | Sequence[int] | None = None
+) -> Array:
+    return xp.fft.fftshift(x, axes=axes)
+
+def ifftshift(
+    x: Array, /, xp: Namespace, *, axes: int | Sequence[int] | None = None
+) -> Array:
+    return xp.fft.ifftshift(x, axes=axes)
+
+__all__ = [
+    "fft",
+    "ifft",
+    "fftn",
+    "ifftn",
+    "rfft",
+    "irfft",
+    "rfftn",
+    "irfftn",
+    "hfft",
+    "ihfft",
+    "fftfreq",
+    "rfftfreq",
+    "fftshift",
+    "ifftshift",
+]
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/_helpers.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..77175d0d1e97425567f90421e5805c64612c4b4a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/_helpers.py
@@ -0,0 +1,1058 @@
+"""
+Various helper functions which are not part of the spec.
+
+Functions which start with an underscore are for internal use only but helpers
+that are in __all__ are intended as additional helper functions for use by end
+users of the compat library.
+"""
+
+from __future__ import annotations
+
+import inspect
+import math
+import sys
+import warnings
+from collections.abc import Collection, Hashable
+from functools import lru_cache
+from typing import (
+    TYPE_CHECKING,
+    Any,
+    Final,
+    Literal,
+    SupportsIndex,
+    TypeAlias,
+    TypeGuard,
+    TypeVar,
+    cast,
+    overload,
+)
+
+from ._typing import Array, Device, HasShape, Namespace, SupportsArrayNamespace
+
+if TYPE_CHECKING:
+
+    import dask.array as da
+    import jax
+    import ndonnx as ndx
+    import numpy as np
+    import numpy.typing as npt
+    import sparse  # pyright: ignore[reportMissingTypeStubs]
+    import torch
+
+    # TODO: import from typing (requires Python >=3.13)
+    from typing_extensions import TypeIs, TypeVar
+
+    _SizeT = TypeVar("_SizeT", bound = int | None)
+
+    _ZeroGradientArray: TypeAlias = npt.NDArray[np.void]
+    _CupyArray: TypeAlias = Any  # cupy has no py.typed
+
+    _ArrayApiObj: TypeAlias = (
+        npt.NDArray[Any]
+        | da.Array
+        | jax.Array
+        | ndx.Array
+        | sparse.SparseArray
+        | torch.Tensor
+        | SupportsArrayNamespace[Any]
+        | _CupyArray
+    )
+
+_API_VERSIONS_OLD: Final = frozenset({"2021.12", "2022.12", "2023.12"})
+_API_VERSIONS: Final = _API_VERSIONS_OLD | frozenset({"2024.12"})
+
+
+@lru_cache(100)
+def _issubclass_fast(cls: type, modname: str, clsname: str) -> bool:
+    try:
+        mod = sys.modules[modname]
+    except KeyError:
+        return False
+    parent_cls = getattr(mod, clsname)
+    return issubclass(cls, parent_cls)
+
+
+def _is_jax_zero_gradient_array(x: object) -> TypeGuard[_ZeroGradientArray]:
+    """Return True if `x` is a zero-gradient array.
+
+    These arrays are a design quirk of Jax that may one day be removed.
+    See https://github.com/google/jax/issues/20620.
+    """
+    # Fast exit
+    try:
+        dtype = x.dtype  # type: ignore[attr-defined]
+    except AttributeError:
+        return False
+    cls = cast(Hashable, type(dtype))
+    if not _issubclass_fast(cls, "numpy.dtypes", "VoidDType"):
+        return False
+
+    if "jax" not in sys.modules:
+        return False
+
+    import jax
+    # jax.float0 is a np.dtype([('float0', 'V')])
+    return dtype == jax.float0
+
+
+def is_numpy_array(x: object) -> TypeGuard[npt.NDArray[Any]]:
+    """
+    Return True if `x` is a NumPy array.
+
+    This function does not import NumPy if it has not already been imported
+    and is therefore cheap to use.
+
+    This also returns True for `ndarray` subclasses and NumPy scalar objects.
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_cupy_array
+    is_torch_array
+    is_ndonnx_array
+    is_dask_array
+    is_jax_array
+    is_pydata_sparse_array
+    """
+    # TODO: Should we reject ndarray subclasses?
+    cls = cast(Hashable, type(x))
+    return (
+        _issubclass_fast(cls, "numpy", "ndarray") 
+        or _issubclass_fast(cls, "numpy", "generic")
+    ) and not _is_jax_zero_gradient_array(x)
+
+
+def is_cupy_array(x: object) -> bool:
+    """
+    Return True if `x` is a CuPy array.
+
+    This function does not import CuPy if it has not already been imported
+    and is therefore cheap to use.
+
+    This also returns True for `cupy.ndarray` subclasses and CuPy scalar objects.
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_torch_array
+    is_ndonnx_array
+    is_dask_array
+    is_jax_array
+    is_pydata_sparse_array
+    """
+    cls = cast(Hashable, type(x))
+    return _issubclass_fast(cls, "cupy", "ndarray")
+
+
+def is_torch_array(x: object) -> TypeIs[torch.Tensor]:
+    """
+    Return True if `x` is a PyTorch tensor.
+
+    This function does not import PyTorch if it has not already been imported
+    and is therefore cheap to use.
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_dask_array
+    is_jax_array
+    is_pydata_sparse_array
+    """
+    cls = cast(Hashable, type(x))
+    return _issubclass_fast(cls, "torch", "Tensor")
+
+
+def is_ndonnx_array(x: object) -> TypeIs[ndx.Array]:
+    """
+    Return True if `x` is a ndonnx Array.
+
+    This function does not import ndonnx if it has not already been imported
+    and is therefore cheap to use.
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_ndonnx_array
+    is_dask_array
+    is_jax_array
+    is_pydata_sparse_array
+    """
+    cls = cast(Hashable, type(x))
+    return _issubclass_fast(cls, "ndonnx", "Array")
+
+
+def is_dask_array(x: object) -> TypeIs[da.Array]:
+    """
+    Return True if `x` is a dask.array Array.
+
+    This function does not import dask if it has not already been imported
+    and is therefore cheap to use.
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_torch_array
+    is_ndonnx_array
+    is_jax_array
+    is_pydata_sparse_array
+    """
+    cls = cast(Hashable, type(x))
+    return _issubclass_fast(cls, "dask.array", "Array")
+
+
+def is_jax_array(x: object) -> TypeIs[jax.Array]:
+    """
+    Return True if `x` is a JAX array.
+
+    This function does not import JAX if it has not already been imported
+    and is therefore cheap to use.
+
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_torch_array
+    is_ndonnx_array
+    is_dask_array
+    is_pydata_sparse_array
+    """
+    cls = cast(Hashable, type(x))
+    return _issubclass_fast(cls, "jax", "Array") or _is_jax_zero_gradient_array(x)
+
+
+def is_pydata_sparse_array(x: object) -> TypeIs[sparse.SparseArray]:
+    """
+    Return True if `x` is an array from the `sparse` package.
+
+    This function does not import `sparse` if it has not already been imported
+    and is therefore cheap to use.
+
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_torch_array
+    is_ndonnx_array
+    is_dask_array
+    is_jax_array
+    """
+    # TODO: Account for other backends.
+    cls = cast(Hashable, type(x))
+    return _issubclass_fast(cls, "sparse", "SparseArray")
+
+
+def is_array_api_obj(x: object) -> TypeIs[_ArrayApiObj]:  # pyright: ignore[reportUnknownParameterType]
+    """
+    Return True if `x` is an array API compatible array object.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_array
+    is_cupy_array
+    is_torch_array
+    is_ndonnx_array
+    is_dask_array
+    is_jax_array
+    """
+    return (
+        hasattr(x, '__array_namespace__') 
+        or _is_array_api_cls(cast(Hashable, type(x)))
+    )
+
+
+@lru_cache(100)
+def _is_array_api_cls(cls: type) -> bool:
+    return (
+        # TODO: drop support for numpy<2 which didn't have __array_namespace__
+        _issubclass_fast(cls, "numpy", "ndarray")
+        or _issubclass_fast(cls, "numpy", "generic")
+        or _issubclass_fast(cls, "cupy", "ndarray")
+        or _issubclass_fast(cls, "torch", "Tensor")
+        or _issubclass_fast(cls, "dask.array", "Array")
+        or _issubclass_fast(cls, "sparse", "SparseArray")
+        # TODO: drop support for jax<0.4.32 which didn't have __array_namespace__
+        or _issubclass_fast(cls, "jax", "Array")
+    )
+
+
+def _compat_module_name() -> str:
+    assert __name__.endswith(".common._helpers")
+    return __name__.removesuffix(".common._helpers")
+
+
+@lru_cache(100)
+def is_numpy_namespace(xp: Namespace) -> bool:
+    """
+    Returns True if `xp` is a NumPy namespace.
+
+    This includes both NumPy itself and the version wrapped by array-api-compat.
+
+    See Also
+    --------
+
+    array_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ in {"numpy", _compat_module_name() + ".numpy"}
+
+
+@lru_cache(100)
+def is_cupy_namespace(xp: Namespace) -> bool:
+    """
+    Returns True if `xp` is a CuPy namespace.
+
+    This includes both CuPy itself and the version wrapped by array-api-compat.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ in {"cupy", _compat_module_name() + ".cupy"}
+
+
+@lru_cache(100)
+def is_torch_namespace(xp: Namespace) -> bool:
+    """
+    Returns True if `xp` is a PyTorch namespace.
+
+    This includes both PyTorch itself and the version wrapped by array-api-compat.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ in {"torch", _compat_module_name() + ".torch"}
+
+
+def is_ndonnx_namespace(xp: Namespace) -> bool:
+    """
+    Returns True if `xp` is an NDONNX namespace.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ == "ndonnx"
+
+
+@lru_cache(100)
+def is_dask_namespace(xp: Namespace) -> bool:
+    """
+    Returns True if `xp` is a Dask namespace.
+
+    This includes both ``dask.array`` itself and the version wrapped by array-api-compat.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ in {"dask.array", _compat_module_name() + ".dask.array"}
+
+
+def is_jax_namespace(xp: Namespace) -> bool:
+    """
+    Returns True if `xp` is a JAX namespace.
+
+    This includes ``jax.numpy`` and ``jax.experimental.array_api`` which existed in
+    older versions of JAX.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ in {"jax.numpy", "jax.experimental.array_api"}
+
+
+def is_pydata_sparse_namespace(xp: Namespace) -> bool:
+    """
+    Returns True if `xp` is a pydata/sparse namespace.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ == "sparse"
+
+
+def is_array_api_strict_namespace(xp: Namespace) -> bool:
+    """
+    Returns True if `xp` is an array-api-strict namespace.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    """
+    return xp.__name__ == "array_api_strict"
+
+
+def _check_api_version(api_version: str | None) -> None:
+    if api_version in _API_VERSIONS_OLD:
+        warnings.warn(
+            f"The {api_version} version of the array API specification was requested but the returned namespace is actually version 2024.12"
+        )
+    elif api_version is not None and api_version not in _API_VERSIONS:
+        raise ValueError(
+            "Only the 2024.12 version of the array API specification is currently supported"
+        )
+
+
+def array_namespace(
+    *xs: Array | complex | None,
+    api_version: str | None = None,
+    use_compat: bool | None = None,
+) -> Namespace:
+    """
+    Get the array API compatible namespace for the arrays `xs`.
+
+    Parameters
+    ----------
+    xs: arrays
+        one or more arrays. xs can also be Python scalars (bool, int, float,
+        complex, or None), which are ignored.
+
+    api_version: str
+        The newest version of the spec that you need support for (currently
+        the compat library wrapped APIs support v2024.12).
+
+    use_compat: bool or None
+        If None (the default), the native namespace will be returned if it is
+        already array API compatible, otherwise a compat wrapper is used. If
+        True, the compat library wrapped library will be returned. If False,
+        the native library namespace is returned.
+
+    Returns
+    -------
+
+    out: namespace
+        The array API compatible namespace corresponding to the arrays in `xs`.
+
+    Raises
+    ------
+    TypeError
+        If `xs` contains arrays from different array libraries or contains a
+        non-array.
+
+
+    Typical usage is to pass the arguments of a function to
+    `array_namespace()` at the top of a function to get the corresponding
+    array API namespace:
+
+    .. code:: python
+
+       def your_function(x, y):
+           xp = array_api_compat.array_namespace(x, y)
+           # Now use xp as the array library namespace
+           return xp.mean(x, axis=0) + 2*xp.std(y, axis=0)
+
+
+    Wrapped array namespaces can also be imported directly. For example,
+    `array_namespace(np.array(...))` will return `array_api_compat.numpy`.
+    This function will also work for any array library not wrapped by
+    array-api-compat if it explicitly defines `__array_namespace__
+    `__
+    (the wrapped namespace is always preferred if it exists).
+
+    See Also
+    --------
+
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_torch_array
+    is_dask_array
+    is_jax_array
+    is_pydata_sparse_array
+
+    """
+    if use_compat not in [None, True, False]:
+        raise ValueError("use_compat must be None, True, or False")
+
+    _use_compat = use_compat in [None, True]
+
+    namespaces: set[Namespace] = set()
+    for x in xs:
+        if is_numpy_array(x):
+            import numpy as np
+
+            from .. import numpy as numpy_namespace
+
+            if use_compat is True:
+                _check_api_version(api_version)
+                namespaces.add(numpy_namespace)
+            elif use_compat is False:
+                namespaces.add(np)
+            else:
+                # numpy 2.0+ have __array_namespace__, however, they are not yet fully array API
+                # compatible.
+                namespaces.add(numpy_namespace)
+        elif is_cupy_array(x):
+            if _use_compat:
+                _check_api_version(api_version)
+                from .. import cupy as cupy_namespace
+
+                namespaces.add(cupy_namespace)
+            else:
+                import cupy as cp  # pyright: ignore[reportMissingTypeStubs]
+
+                namespaces.add(cp)
+        elif is_torch_array(x):
+            if _use_compat:
+                _check_api_version(api_version)
+                from .. import torch as torch_namespace
+
+                namespaces.add(torch_namespace)
+            else:
+                import torch
+
+                namespaces.add(torch)
+        elif is_dask_array(x):
+            if _use_compat:
+                _check_api_version(api_version)
+                from ..dask import array as dask_namespace
+
+                namespaces.add(dask_namespace)
+            else:
+                import dask.array as da
+
+                namespaces.add(da)
+        elif is_jax_array(x):
+            if use_compat is True:
+                _check_api_version(api_version)
+                raise ValueError("JAX does not have an array-api-compat wrapper")
+            elif use_compat is False:
+                import jax.numpy as jnp
+            else:
+                # JAX v0.4.32 and newer implements the array API directly in jax.numpy.
+                # For older JAX versions, it is available via jax.experimental.array_api.
+                import jax.numpy
+
+                if hasattr(jax.numpy, "__array_api_version__"):
+                    jnp = jax.numpy
+                else:
+                    import jax.experimental.array_api as jnp  # pyright: ignore[reportMissingImports]
+            namespaces.add(jnp)
+        elif is_pydata_sparse_array(x):
+            if use_compat is True:
+                _check_api_version(api_version)
+                raise ValueError("`sparse` does not have an array-api-compat wrapper")
+            else:
+                import sparse  # pyright: ignore[reportMissingTypeStubs]
+            # `sparse` is already an array namespace. We do not have a wrapper
+            # submodule for it.
+            namespaces.add(sparse)
+        elif hasattr(x, "__array_namespace__"):
+            if use_compat is True:
+                raise ValueError(
+                    "The given array does not have an array-api-compat wrapper"
+                )
+            x = cast("SupportsArrayNamespace[Any]", x)
+            namespaces.add(x.__array_namespace__(api_version=api_version))
+        elif isinstance(x, (bool, int, float, complex, type(None))):
+            continue
+        else:
+            # TODO: Support Python scalars?
+            raise TypeError(f"{type(x).__name__} is not a supported array type")
+
+    if not namespaces:
+        raise TypeError("Unrecognized array input")
+
+    if len(namespaces) != 1:
+        raise TypeError(f"Multiple namespaces for array inputs: {namespaces}")
+
+    (xp,) = namespaces
+
+    return xp
+
+
+# backwards compatibility alias
+get_namespace = array_namespace
+
+
+def _check_device(bare_xp: Namespace, device: Device) -> None:  # pyright: ignore[reportUnusedFunction]
+    """
+    Validate dummy device on device-less array backends.
+
+    Notes
+    -----
+    This function is also invoked by CuPy, which does have multiple devices
+    if there are multiple GPUs available.
+    However, CuPy multi-device support is currently impossible
+    without using the global device or a context manager:
+
+    https://github.com/data-apis/array-api-compat/pull/293
+    """
+    if bare_xp is sys.modules.get("numpy"):
+        if device not in ("cpu", None):
+            raise ValueError(f"Unsupported device for NumPy: {device!r}")
+
+    elif bare_xp is sys.modules.get("dask.array"):
+        if device not in ("cpu", _DASK_DEVICE, None):
+            raise ValueError(f"Unsupported device for Dask: {device!r}")
+
+
+# Placeholder object to represent the dask device
+# when the array backend is not the CPU.
+# (since it is not easy to tell which device a dask array is on)
+class _dask_device:
+    def __repr__(self) -> Literal["DASK_DEVICE"]:
+        return "DASK_DEVICE"
+
+
+_DASK_DEVICE = _dask_device()
+
+
+# device() is not on numpy.ndarray or dask.array and to_device() is not on numpy.ndarray
+# or cupy.ndarray. They are not included in array objects of this library
+# because this library just reuses the respective ndarray classes without
+# wrapping or subclassing them. These helper functions can be used instead of
+# the wrapper functions for libraries that need to support both NumPy/CuPy and
+# other libraries that use devices.
+def device(x: _ArrayApiObj, /) -> Device:
+    """
+    Hardware device the array data resides on.
+
+    This is equivalent to `x.device` according to the `standard
+    `__.
+    This helper is included because some array libraries either do not have
+    the `device` attribute or include it with an incompatible API.
+
+    Parameters
+    ----------
+    x: array
+        array instance from an array API compatible library.
+
+    Returns
+    -------
+    out: device
+        a ``device`` object (see the `Device Support `__
+        section of the array API specification).
+
+    Notes
+    -----
+
+    For NumPy the device is always `"cpu"`. For Dask, the device is always a
+    special `DASK_DEVICE` object.
+
+    See Also
+    --------
+
+    to_device : Move array data to a different device.
+
+    """
+    if is_numpy_array(x):
+        return "cpu"
+    elif is_dask_array(x):
+        # Peek at the metadata of the Dask array to determine type
+        if is_numpy_array(x._meta):  # pyright: ignore
+            # Must be on CPU since backed by numpy
+            return "cpu"
+        return _DASK_DEVICE
+    elif is_jax_array(x):
+        # FIXME Jitted JAX arrays do not have a device attribute
+        #       https://github.com/jax-ml/jax/issues/26000
+        #       Return None in this case. Note that this workaround breaks
+        #       the standard and will result in new arrays being created on the
+        #       default device instead of the same device as the input array(s).
+        x_device = getattr(x, "device", None)
+        # Older JAX releases had .device() as a method, which has been replaced
+        # with a property in accordance with the standard.
+        if inspect.ismethod(x_device):
+            return x_device()
+        else:
+            return x_device
+    elif is_pydata_sparse_array(x):
+        # `sparse` will gain `.device`, so check for this first.
+        x_device = getattr(x, "device", None)
+        if x_device is not None:
+            return x_device
+        # Everything but DOK has this attr.
+        try:
+            inner = x.data  # pyright: ignore
+        except AttributeError:
+            return "cpu"
+        # Return the device of the constituent array
+        return device(inner)  # pyright: ignore
+    return x.device  # pyright: ignore
+
+
+# Prevent shadowing, used below
+_device = device
+
+
+# Based on cupy.array_api.Array.to_device
+def _cupy_to_device(
+    x: _CupyArray,
+    device: Device,
+    /,
+    stream: int | Any | None = None,
+) -> _CupyArray:
+    import cupy as cp
+
+    if device == "cpu":
+        # allowing us to use `to_device(x, "cpu")`
+        # is useful for portable test swapping between
+        # host and device backends
+        return x.get()
+    if not isinstance(device, cp.cuda.Device):
+        raise TypeError(f"Unsupported device type {device!r}")
+
+    if stream is None:
+        with device:
+            return cp.asarray(x)
+
+    # stream can be an int as specified in __dlpack__, or a CuPy stream
+    if isinstance(stream, int):
+        stream = cp.cuda.ExternalStream(stream)
+    elif not isinstance(stream, cp.cuda.Stream):
+        raise TypeError(f"Unsupported stream type {stream!r}")
+
+    with device, stream:
+        return cp.asarray(x)
+
+
+def _torch_to_device(
+    x: torch.Tensor,
+    device: torch.device | str | int,
+    /,
+    stream: None = None,
+) -> torch.Tensor:
+    if stream is not None:
+        raise NotImplementedError
+    return x.to(device)
+
+
+def to_device(x: Array, device: Device, /, *, stream: int | Any | None = None) -> Array:
+    """
+    Copy the array from the device on which it currently resides to the specified ``device``.
+
+    This is equivalent to `x.to_device(device, stream=stream)` according to
+    the `standard
+    `__.
+    This helper is included because some array libraries do not have the
+    `to_device` method.
+
+    Parameters
+    ----------
+
+    x: array
+        array instance from an array API compatible library.
+
+    device: device
+        a ``device`` object (see the `Device Support `__
+        section of the array API specification).
+
+    stream: int | Any | None
+        stream object to use during copy. In addition to the types supported
+        in ``array.__dlpack__``, implementations may choose to support any
+        library-specific stream object with the caveat that any code using
+        such an object would not be portable.
+
+    Returns
+    -------
+
+    out: array
+        an array with the same data and data type as ``x`` and located on the
+        specified ``device``.
+
+    Notes
+    -----
+
+    For NumPy, this function effectively does nothing since the only supported
+    device is the CPU. For CuPy, this method supports CuPy CUDA
+    :external+cupy:class:`Device ` and
+    :external+cupy:class:`Stream ` objects. For PyTorch,
+    this is the same as :external+torch:meth:`x.to(device) `
+    (the ``stream`` argument is not supported in PyTorch).
+
+    See Also
+    --------
+
+    device : Hardware device the array data resides on.
+
+    """
+    if is_numpy_array(x):
+        if stream is not None:
+            raise ValueError("The stream argument to to_device() is not supported")
+        if device == "cpu":
+            return x
+        raise ValueError(f"Unsupported device {device!r}")
+    elif is_cupy_array(x):
+        # cupy does not yet have to_device
+        return _cupy_to_device(x, device, stream=stream)
+    elif is_torch_array(x):
+        return _torch_to_device(x, device, stream=stream)  # pyright: ignore[reportArgumentType]
+    elif is_dask_array(x):
+        if stream is not None:
+            raise ValueError("The stream argument to to_device() is not supported")
+        # TODO: What if our array is on the GPU already?
+        if device == "cpu":
+            return x
+        raise ValueError(f"Unsupported device {device!r}")
+    elif is_jax_array(x):
+        if not hasattr(x, "__array_namespace__"):
+            # In JAX v0.4.31 and older, this import adds to_device method to x...
+            import jax.experimental.array_api  # noqa: F401  # pyright: ignore
+
+            # ... but only on eager JAX. It won't work inside jax.jit.
+            if not hasattr(x, "to_device"):
+                return x
+        return x.to_device(device, stream=stream)
+    elif is_pydata_sparse_array(x) and device == _device(x):
+        # Perform trivial check to return the same array if
+        # device is same instead of err-ing.
+        return x
+    return x.to_device(device, stream=stream)  # pyright: ignore
+
+
+@overload
+def size(x: HasShape[Collection[SupportsIndex]]) -> int: ...
+@overload
+def size(x: HasShape[Collection[None]]) -> None: ...
+@overload
+def size(x: HasShape[Collection[SupportsIndex | None]]) -> int | None: ...
+def size(x: HasShape[Collection[SupportsIndex | None]]) -> int | None:
+    """
+    Return the total number of elements of x.
+
+    This is equivalent to `x.size` according to the `standard
+    `__.
+
+    This helper is included because PyTorch defines `size` in an
+    :external+torch:meth:`incompatible way `.
+    It also fixes dask.array's behaviour which returns nan for unknown sizes, whereas
+    the standard requires None.
+    """
+    # Lazy API compliant arrays, such as ndonnx, can contain None in their shape
+    if None in x.shape:
+        return None
+    out = math.prod(cast("Collection[SupportsIndex]", x.shape))
+    # dask.array.Array.shape can contain NaN
+    return None if math.isnan(out) else out
+
+
+@lru_cache(100)
+def _is_writeable_cls(cls: type) -> bool | None:
+    if (
+        _issubclass_fast(cls, "numpy", "generic")
+        or _issubclass_fast(cls, "jax", "Array")
+        or _issubclass_fast(cls, "sparse", "SparseArray")
+    ):
+        return False
+    if _is_array_api_cls(cls):
+        return True
+    return None
+
+
+def is_writeable_array(x: object) -> bool:
+    """
+    Return False if ``x.__setitem__`` is expected to raise; True otherwise.
+    Return False if `x` is not an array API compatible object.
+
+    Warning
+    -------
+    As there is no standard way to check if an array is writeable without actually
+    writing to it, this function blindly returns True for all unknown array types.
+    """
+    cls = cast(Hashable, type(x))
+    if _issubclass_fast(cls, "numpy", "ndarray"):
+        return cast("npt.NDArray", x).flags.writeable
+    res = _is_writeable_cls(cls)
+    if res is not None:
+        return res
+    return hasattr(x, '__array_namespace__')
+
+
+@lru_cache(100)
+def _is_lazy_cls(cls: type) -> bool | None:
+    if (
+        _issubclass_fast(cls, "numpy", "ndarray")
+        or _issubclass_fast(cls, "numpy", "generic")
+        or _issubclass_fast(cls, "cupy", "ndarray")
+        or _issubclass_fast(cls, "torch", "Tensor")
+        or _issubclass_fast(cls, "sparse", "SparseArray")
+    ):
+        return False
+    if (
+        _issubclass_fast(cls, "jax", "Array")
+        or _issubclass_fast(cls, "dask.array", "Array")
+        or _issubclass_fast(cls, "ndonnx", "Array")
+    ):
+        return True
+    return  None
+
+
+def is_lazy_array(x: object) -> bool:
+    """Return True if x is potentially a future or it may be otherwise impossible or
+    expensive to eagerly read its contents, regardless of their size, e.g. by
+    calling ``bool(x)`` or ``float(x)``.
+
+    Return False otherwise; e.g. ``bool(x)`` etc. is guaranteed to succeed and to be
+    cheap as long as the array has the right dtype and size.
+
+    Note
+    ----
+    This function errs on the side of caution for array types that may or may not be
+    lazy, e.g. JAX arrays, by always returning True for them.
+    """
+    # **JAX note:** while it is possible to determine if you're inside or outside
+    # jax.jit by testing the subclass of a jax.Array object, as well as testing bool()
+    # as we do below for unknown arrays, this is not recommended by JAX best practices.
+
+    # **Dask note:** Dask eagerly computes the graph on __bool__, __float__, and so on.
+    # This behaviour, while impossible to change without breaking backwards
+    # compatibility, is highly detrimental to performance as the whole graph will end
+    # up being computed multiple times.
+
+    # Note: skipping reclassification of JAX zero gradient arrays, as one will
+    # exclusively get them once they leave a jax.grad JIT context.
+    cls = cast(Hashable, type(x))
+    res = _is_lazy_cls(cls)
+    if res is not None:
+        return res
+
+    if not hasattr(x, "__array_namespace__"):
+        return False
+
+    # Unknown Array API compatible object. Note that this test may have dire consequences
+    # in terms of performance, e.g. for a lazy object that eagerly computes the graph
+    # on __bool__ (dask is one such example, which however is special-cased above).
+
+    # Select a single point of the array
+    s = size(cast("HasShape[Collection[SupportsIndex | None]]", x))
+    if s is None:
+        return True
+    xp = array_namespace(x)
+    if s > 1:
+        x = xp.reshape(x, (-1,))[0]
+    # Cast to dtype=bool and deal with size 0 arrays
+    x = xp.any(x)
+
+    try:
+        bool(x)
+        return False
+    # The Array API standard dictactes that __bool__ should raise TypeError if the
+    # output cannot be defined.
+    # Here we allow for it to raise arbitrary exceptions, e.g. like Dask does.
+    except Exception:
+        return True
+
+
+__all__ = [
+    "array_namespace",
+    "device",
+    "get_namespace",
+    "is_array_api_obj",
+    "is_array_api_strict_namespace",
+    "is_cupy_array",
+    "is_cupy_namespace",
+    "is_dask_array",
+    "is_dask_namespace",
+    "is_jax_array",
+    "is_jax_namespace",
+    "is_numpy_array",
+    "is_numpy_namespace",
+    "is_torch_array",
+    "is_torch_namespace",
+    "is_ndonnx_array",
+    "is_ndonnx_namespace",
+    "is_pydata_sparse_array",
+    "is_pydata_sparse_namespace",
+    "is_writeable_array",
+    "is_lazy_array",
+    "size",
+    "to_device",
+]
+
+_all_ignore = ['lru_cache', 'sys', 'math', 'inspect', 'warnings']
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/_linalg.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/_linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ad87a1be91057a6c7ee3a4e49cfa26396809650
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/_linalg.py
@@ -0,0 +1,232 @@
+from __future__ import annotations
+
+import math
+from typing import Literal, NamedTuple, cast
+
+import numpy as np
+
+if np.__version__[0] == "2":
+    from numpy.lib.array_utils import normalize_axis_tuple
+else:
+    from numpy.core.numeric import normalize_axis_tuple
+
+from .._internal import get_xp
+from ._aliases import isdtype, matmul, matrix_transpose, tensordot, vecdot
+from ._typing import Array, DType, JustFloat, JustInt, Namespace
+
+
+# These are in the main NumPy namespace but not in numpy.linalg
+def cross(
+    x1: Array,
+    x2: Array,
+    /,
+    xp: Namespace,
+    *,
+    axis: int = -1,
+    **kwargs: object,
+) -> Array:
+    return xp.cross(x1, x2, axis=axis, **kwargs)
+
+def outer(x1: Array, x2: Array, /, xp: Namespace, **kwargs: object) -> Array:
+    return xp.outer(x1, x2, **kwargs)
+
+class EighResult(NamedTuple):
+    eigenvalues: Array
+    eigenvectors: Array
+
+class QRResult(NamedTuple):
+    Q: Array
+    R: Array
+
+class SlogdetResult(NamedTuple):
+    sign: Array
+    logabsdet: Array
+
+class SVDResult(NamedTuple):
+    U: Array
+    S: Array
+    Vh: Array
+
+# These functions are the same as their NumPy counterparts except they return
+# a namedtuple.
+def eigh(x: Array, /, xp: Namespace, **kwargs: object) -> EighResult:
+    return EighResult(*xp.linalg.eigh(x, **kwargs))
+
+def qr(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    mode: Literal["reduced", "complete"] = "reduced",
+    **kwargs: object,
+) -> QRResult:
+    return QRResult(*xp.linalg.qr(x, mode=mode, **kwargs))
+
+def slogdet(x: Array, /, xp: Namespace, **kwargs: object) -> SlogdetResult:
+    return SlogdetResult(*xp.linalg.slogdet(x, **kwargs))
+
+def svd(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    full_matrices: bool = True,
+    **kwargs: object,
+) -> SVDResult:
+    return SVDResult(*xp.linalg.svd(x, full_matrices=full_matrices, **kwargs))
+
+# These functions have additional keyword arguments
+
+# The upper keyword argument is new from NumPy
+def cholesky(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    upper: bool = False,
+    **kwargs: object,
+) -> Array:
+    L = xp.linalg.cholesky(x, **kwargs)
+    if upper:
+        U = get_xp(xp)(matrix_transpose)(L)
+        if get_xp(xp)(isdtype)(U.dtype, 'complex floating'):
+            U = xp.conj(U)  # pyright: ignore[reportConstantRedefinition]
+        return U
+    return L
+
+# The rtol keyword argument of matrix_rank() and pinv() is new from NumPy.
+# Note that it has a different semantic meaning from tol and rcond.
+def matrix_rank(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    rtol: float | Array | None = None,
+    **kwargs: object,
+) -> Array:
+    # this is different from xp.linalg.matrix_rank, which supports 1
+    # dimensional arrays.
+    if x.ndim < 2:
+        raise xp.linalg.LinAlgError("1-dimensional array given. Array must be at least two-dimensional")
+    S: Array = get_xp(xp)(svdvals)(x, **kwargs)
+    if rtol is None:
+        tol = S.max(axis=-1, keepdims=True) * max(x.shape[-2:]) * xp.finfo(S.dtype).eps
+    else:
+        # this is different from xp.linalg.matrix_rank, which does not
+        # multiply the tolerance by the largest singular value.
+        tol = S.max(axis=-1, keepdims=True)*xp.asarray(rtol)[..., xp.newaxis]
+    return xp.count_nonzero(S > tol, axis=-1)
+
+def pinv(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    rtol: float | Array | None = None,
+    **kwargs: object,
+) -> Array:
+    # this is different from xp.linalg.pinv, which does not multiply the
+    # default tolerance by max(M, N).
+    if rtol is None:
+        rtol = max(x.shape[-2:]) * xp.finfo(x.dtype).eps
+    return xp.linalg.pinv(x, rcond=rtol, **kwargs)
+
+# These functions are new in the array API spec
+
+def matrix_norm(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    keepdims: bool = False,
+    ord: Literal[1, 2, -1, -2] | JustFloat | Literal["fro", "nuc"] | None = "fro",
+) -> Array:
+    return xp.linalg.norm(x, axis=(-2, -1), keepdims=keepdims, ord=ord)
+
+# svdvals is not in NumPy (but it is in SciPy). It is equivalent to
+# xp.linalg.svd(compute_uv=False).
+def svdvals(x: Array, /, xp: Namespace) -> Array | tuple[Array, ...]:
+    return xp.linalg.svd(x, compute_uv=False)
+
+def vector_norm(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    axis: int | tuple[int, ...] | None = None,
+    keepdims: bool = False,
+    ord: JustInt | JustFloat = 2,
+) -> Array:
+    # xp.linalg.norm tries to do a matrix norm whenever axis is a 2-tuple or
+    # when axis=None and the input is 2-D, so to force a vector norm, we make
+    # it so the input is 1-D (for axis=None), or reshape so that norm is done
+    # on a single dimension.
+    if axis is None:
+        # Note: xp.linalg.norm() doesn't handle 0-D arrays
+        _x = x.ravel()
+        _axis = 0
+    elif isinstance(axis, tuple):
+        # Note: The axis argument supports any number of axes, whereas
+        # xp.linalg.norm() only supports a single axis for vector norm.
+        normalized_axis = cast(
+            "tuple[int, ...]",
+            normalize_axis_tuple(axis, x.ndim),  # pyright: ignore[reportCallIssue]
+        )
+        rest = tuple(i for i in range(x.ndim) if i not in normalized_axis)
+        newshape = axis + rest
+        _x = xp.transpose(x, newshape).reshape(
+            (math.prod([x.shape[i] for i in axis]), *[x.shape[i] for i in rest]))
+        _axis = 0
+    else:
+        _x = x
+        _axis = axis
+
+    res = xp.linalg.norm(_x, axis=_axis, ord=ord)
+
+    if keepdims:
+        # We can't reuse xp.linalg.norm(keepdims) because of the reshape hacks
+        # above to avoid matrix norm logic.
+        shape = list(x.shape)
+        _axis = cast(
+            "tuple[int, ...]",
+            normalize_axis_tuple(  # pyright: ignore[reportCallIssue]
+                range(x.ndim) if axis is None else axis,
+                x.ndim,
+            ),
+        )
+        for i in _axis:
+            shape[i] = 1
+        res = xp.reshape(res, tuple(shape))
+
+    return res
+
+# xp.diagonal and xp.trace operate on the first two axes whereas these
+# operates on the last two
+
+def diagonal(x: Array, /, xp: Namespace, *, offset: int = 0, **kwargs: object) -> Array:
+    return xp.diagonal(x, offset=offset, axis1=-2, axis2=-1, **kwargs)
+
+def trace(
+    x: Array,
+    /,
+    xp: Namespace,
+    *,
+    offset: int = 0,
+    dtype: DType | None = None,
+    **kwargs: object,
+) -> Array:
+    return xp.asarray(
+        xp.trace(x, offset=offset, dtype=dtype, axis1=-2, axis2=-1, **kwargs)
+    )
+
+__all__ = ['cross', 'matmul', 'outer', 'tensordot', 'EighResult',
+           'QRResult', 'SlogdetResult', 'SVDResult', 'eigh', 'qr', 'slogdet',
+           'svd', 'cholesky', 'matrix_rank', 'pinv', 'matrix_norm',
+           'matrix_transpose', 'svdvals', 'vecdot', 'vector_norm', 'diagonal',
+           'trace']
+
+_all_ignore = ['math', 'normalize_axis_tuple', 'get_xp', 'np', 'isdtype']
+
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/_typing.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd26feeba4dffefaf38df52faf2b28c804bfa50a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/common/_typing.py
@@ -0,0 +1,192 @@
+from __future__ import annotations
+
+from collections.abc import Mapping
+from types import ModuleType as Namespace
+from typing import (
+    TYPE_CHECKING,
+    Literal,
+    Protocol,
+    TypeAlias,
+    TypedDict,
+    TypeVar,
+    final,
+)
+
+if TYPE_CHECKING:
+    from _typeshed import Incomplete
+
+    SupportsBufferProtocol: TypeAlias = Incomplete
+    Array: TypeAlias = Incomplete
+    Device: TypeAlias = Incomplete
+    DType: TypeAlias = Incomplete
+else:
+    SupportsBufferProtocol = object
+    Array = object
+    Device = object
+    DType = object
+
+
+_T_co = TypeVar("_T_co", covariant=True)
+
+
+# These "Just" types are equivalent to the `Just` type from the `optype` library,
+# apart from them not being `@runtime_checkable`.
+# - docs: https://github.com/jorenham/optype/blob/master/README.md#just
+# - code: https://github.com/jorenham/optype/blob/master/optype/_core/_just.py
+@final
+class JustInt(Protocol):
+    @property
+    def __class__(self, /) -> type[int]: ...
+    @__class__.setter
+    def __class__(self, value: type[int], /) -> None: ...  # pyright: ignore[reportIncompatibleMethodOverride]
+
+
+@final
+class JustFloat(Protocol):
+    @property
+    def __class__(self, /) -> type[float]: ...
+    @__class__.setter
+    def __class__(self, value: type[float], /) -> None: ...  # pyright: ignore[reportIncompatibleMethodOverride]
+
+
+@final
+class JustComplex(Protocol):
+    @property
+    def __class__(self, /) -> type[complex]: ...
+    @__class__.setter
+    def __class__(self, value: type[complex], /) -> None: ...  # pyright: ignore[reportIncompatibleMethodOverride]
+
+
+#
+
+
+class NestedSequence(Protocol[_T_co]):
+    def __getitem__(self, key: int, /) -> _T_co | NestedSequence[_T_co]: ...
+    def __len__(self, /) -> int: ...
+
+
+class SupportsArrayNamespace(Protocol[_T_co]):
+    def __array_namespace__(self, /, *, api_version: str | None) -> _T_co: ...
+
+
+class HasShape(Protocol[_T_co]):
+    @property
+    def shape(self, /) -> _T_co: ...
+
+
+# Return type of `__array_namespace_info__.default_dtypes`
+Capabilities = TypedDict(
+    "Capabilities",
+    {
+        "boolean indexing": bool,
+        "data-dependent shapes": bool,
+        "max dimensions": int,
+    },
+)
+
+# Return type of `__array_namespace_info__.default_dtypes`
+DefaultDTypes = TypedDict(
+    "DefaultDTypes",
+    {
+        "real floating": DType,
+        "complex floating": DType,
+        "integral": DType,
+        "indexing": DType,
+    },
+)
+
+
+_DTypeKind: TypeAlias = Literal[
+    "bool",
+    "signed integer",
+    "unsigned integer",
+    "integral",
+    "real floating",
+    "complex floating",
+    "numeric",
+]
+# Type of the `kind` parameter in `__array_namespace_info__.dtypes`
+DTypeKind: TypeAlias = _DTypeKind | tuple[_DTypeKind, ...]
+
+
+# `__array_namespace_info__.dtypes(kind="bool")`
+class DTypesBool(TypedDict):
+    bool: DType
+
+
+# `__array_namespace_info__.dtypes(kind="signed integer")`
+class DTypesSigned(TypedDict):
+    int8: DType
+    int16: DType
+    int32: DType
+    int64: DType
+
+
+# `__array_namespace_info__.dtypes(kind="unsigned integer")`
+class DTypesUnsigned(TypedDict):
+    uint8: DType
+    uint16: DType
+    uint32: DType
+    uint64: DType
+
+
+# `__array_namespace_info__.dtypes(kind="integral")`
+class DTypesIntegral(DTypesSigned, DTypesUnsigned):
+    pass
+
+
+# `__array_namespace_info__.dtypes(kind="real floating")`
+class DTypesReal(TypedDict):
+    float32: DType
+    float64: DType
+
+
+# `__array_namespace_info__.dtypes(kind="complex floating")`
+class DTypesComplex(TypedDict):
+    complex64: DType
+    complex128: DType
+
+
+# `__array_namespace_info__.dtypes(kind="numeric")`
+class DTypesNumeric(DTypesIntegral, DTypesReal, DTypesComplex):
+    pass
+
+
+# `__array_namespace_info__.dtypes(kind=None)` (default)
+class DTypesAll(DTypesBool, DTypesNumeric):
+    pass
+
+
+# `__array_namespace_info__.dtypes(kind=?)` (fallback)
+DTypesAny: TypeAlias = Mapping[str, DType]
+
+
+__all__ = [
+    "Array",
+    "Capabilities",
+    "DType",
+    "DTypeKind",
+    "DTypesAny",
+    "DTypesAll",
+    "DTypesBool",
+    "DTypesNumeric",
+    "DTypesIntegral",
+    "DTypesSigned",
+    "DTypesUnsigned",
+    "DTypesReal",
+    "DTypesComplex",
+    "DefaultDTypes",
+    "Device",
+    "HasShape",
+    "Namespace",
+    "JustInt",
+    "JustFloat",
+    "JustComplex",
+    "NestedSequence",
+    "SupportsArrayNamespace",
+    "SupportsBufferProtocol",
+]
+
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/cupy/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/cupy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a30f95ddf12c3853626e0645c431155ef507107
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/cupy/__init__.py
@@ -0,0 +1,13 @@
+from cupy import * # noqa: F403
+
+# from cupy import * doesn't overwrite these builtin names
+from cupy import abs, max, min, round # noqa: F401
+
+# These imports may overwrite names from the import * above.
+from ._aliases import * # noqa: F403
+
+# See the comment in the numpy __init__.py
+__import__(__package__ + '.linalg')
+__import__(__package__ + '.fft')
+
+__array_api_version__ = '2024.12'
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/cupy/_aliases.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/cupy/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..90b48f059bafad6d9016e6284d5a3fb9ca18f6d6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/cupy/_aliases.py
@@ -0,0 +1,156 @@
+from __future__ import annotations
+
+from typing import Optional
+
+import cupy as cp
+
+from ..common import _aliases, _helpers
+from ..common._typing import NestedSequence, SupportsBufferProtocol
+from .._internal import get_xp
+from ._info import __array_namespace_info__
+from ._typing import Array, Device, DType
+
+bool = cp.bool_
+
+# Basic renames
+acos = cp.arccos
+acosh = cp.arccosh
+asin = cp.arcsin
+asinh = cp.arcsinh
+atan = cp.arctan
+atan2 = cp.arctan2
+atanh = cp.arctanh
+bitwise_left_shift = cp.left_shift
+bitwise_invert = cp.invert
+bitwise_right_shift = cp.right_shift
+concat = cp.concatenate
+pow = cp.power
+
+arange = get_xp(cp)(_aliases.arange)
+empty = get_xp(cp)(_aliases.empty)
+empty_like = get_xp(cp)(_aliases.empty_like)
+eye = get_xp(cp)(_aliases.eye)
+full = get_xp(cp)(_aliases.full)
+full_like = get_xp(cp)(_aliases.full_like)
+linspace = get_xp(cp)(_aliases.linspace)
+ones = get_xp(cp)(_aliases.ones)
+ones_like = get_xp(cp)(_aliases.ones_like)
+zeros = get_xp(cp)(_aliases.zeros)
+zeros_like = get_xp(cp)(_aliases.zeros_like)
+UniqueAllResult = get_xp(cp)(_aliases.UniqueAllResult)
+UniqueCountsResult = get_xp(cp)(_aliases.UniqueCountsResult)
+UniqueInverseResult = get_xp(cp)(_aliases.UniqueInverseResult)
+unique_all = get_xp(cp)(_aliases.unique_all)
+unique_counts = get_xp(cp)(_aliases.unique_counts)
+unique_inverse = get_xp(cp)(_aliases.unique_inverse)
+unique_values = get_xp(cp)(_aliases.unique_values)
+std = get_xp(cp)(_aliases.std)
+var = get_xp(cp)(_aliases.var)
+cumulative_sum = get_xp(cp)(_aliases.cumulative_sum)
+cumulative_prod = get_xp(cp)(_aliases.cumulative_prod)
+clip = get_xp(cp)(_aliases.clip)
+permute_dims = get_xp(cp)(_aliases.permute_dims)
+reshape = get_xp(cp)(_aliases.reshape)
+argsort = get_xp(cp)(_aliases.argsort)
+sort = get_xp(cp)(_aliases.sort)
+nonzero = get_xp(cp)(_aliases.nonzero)
+ceil = get_xp(cp)(_aliases.ceil)
+floor = get_xp(cp)(_aliases.floor)
+trunc = get_xp(cp)(_aliases.trunc)
+matmul = get_xp(cp)(_aliases.matmul)
+matrix_transpose = get_xp(cp)(_aliases.matrix_transpose)
+tensordot = get_xp(cp)(_aliases.tensordot)
+sign = get_xp(cp)(_aliases.sign)
+finfo = get_xp(cp)(_aliases.finfo)
+iinfo = get_xp(cp)(_aliases.iinfo)
+
+
+# asarray also adds the copy keyword, which is not present in numpy 1.0.
+def asarray(
+    obj: (
+        Array 
+        | bool | int | float | complex 
+        | NestedSequence[bool | int | float | complex] 
+        | SupportsBufferProtocol
+    ),
+    /,
+    *,
+    dtype: Optional[DType] = None,
+    device: Optional[Device] = None,
+    copy: Optional[bool] = None,
+    **kwargs,
+) -> Array:
+    """
+    Array API compatibility wrapper for asarray().
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+    with cp.cuda.Device(device):
+        if copy is None:
+            return cp.asarray(obj, dtype=dtype, **kwargs)
+        else:
+            res = cp.array(obj, dtype=dtype, copy=copy, **kwargs)
+            if not copy and res is not obj:
+                raise ValueError("Unable to avoid copy while creating an array as requested")
+            return res
+
+
+def astype(
+    x: Array,
+    dtype: DType,
+    /,
+    *,
+    copy: bool = True,
+    device: Optional[Device] = None,
+) -> Array:
+    if device is None:
+        return x.astype(dtype=dtype, copy=copy)
+    out = _helpers.to_device(x.astype(dtype=dtype, copy=False), device)
+    return out.copy() if copy and out is x else out
+
+
+# cupy.count_nonzero does not have keepdims
+def count_nonzero(
+    x: Array,
+    axis=None,
+    keepdims=False
+) -> Array:
+   result = cp.count_nonzero(x, axis)
+   if keepdims:
+       if axis is None:
+            return cp.reshape(result, [1]*x.ndim)
+       return cp.expand_dims(result, axis)
+   return result
+
+
+# take_along_axis: axis defaults to -1 but in cupy (and numpy) axis is a required arg
+def take_along_axis(x: Array, indices: Array, /, *, axis: int = -1):
+    return cp.take_along_axis(x, indices, axis=axis)
+
+
+# These functions are completely new here. If the library already has them
+# (i.e., numpy 2.0), use the library version instead of our wrapper.
+if hasattr(cp, 'vecdot'):
+    vecdot = cp.vecdot
+else:
+    vecdot = get_xp(cp)(_aliases.vecdot)
+
+if hasattr(cp, 'isdtype'):
+    isdtype = cp.isdtype
+else:
+    isdtype = get_xp(cp)(_aliases.isdtype)
+
+if hasattr(cp, 'unstack'):
+    unstack = cp.unstack
+else:
+    unstack = get_xp(cp)(_aliases.unstack)
+
+__all__ = _aliases.__all__ + ['__array_namespace_info__', 'asarray', 'astype',
+                              'acos', 'acosh', 'asin', 'asinh', 'atan',
+                              'atan2', 'atanh', 'bitwise_left_shift',
+                              'bitwise_invert', 'bitwise_right_shift',
+                              'bool', 'concat', 'count_nonzero', 'pow', 'sign',
+                              'take_along_axis']
+
+_all_ignore = ['cp', 'get_xp']
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/cupy/_info.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/cupy/_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..78e48a3358cf547a9a77c5ebdc95fa81c3d4e144
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/cupy/_info.py
@@ -0,0 +1,336 @@
+"""
+Array API Inspection namespace
+
+This is the namespace for inspection functions as defined by the array API
+standard. See
+https://data-apis.org/array-api/latest/API_specification/inspection.html for
+more details.
+
+"""
+from cupy import (
+    dtype,
+    cuda,
+    bool_ as bool,
+    intp,
+    int8,
+    int16,
+    int32,
+    int64,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+    float32,
+    float64,
+    complex64,
+    complex128,
+)
+
+
+class __array_namespace_info__:
+    """
+    Get the array API inspection namespace for CuPy.
+
+    The array API inspection namespace defines the following functions:
+
+    - capabilities()
+    - default_device()
+    - default_dtypes()
+    - dtypes()
+    - devices()
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/inspection.html
+    for more details.
+
+    Returns
+    -------
+    info : ModuleType
+        The array API inspection namespace for CuPy.
+
+    Examples
+    --------
+    >>> info = xp.__array_namespace_info__()
+    >>> info.default_dtypes()
+    {'real floating': cupy.float64,
+     'complex floating': cupy.complex128,
+     'integral': cupy.int64,
+     'indexing': cupy.int64}
+
+    """
+
+    __module__ = 'cupy'
+
+    def capabilities(self):
+        """
+        Return a dictionary of array API library capabilities.
+
+        The resulting dictionary has the following keys:
+
+        - **"boolean indexing"**: boolean indicating whether an array library
+          supports boolean indexing. Always ``True`` for CuPy.
+
+        - **"data-dependent shapes"**: boolean indicating whether an array
+          library supports data-dependent output shapes. Always ``True`` for
+          CuPy.
+
+        See
+        https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html
+        for more details.
+
+        See Also
+        --------
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        capabilities : dict
+            A dictionary of array API library capabilities.
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.capabilities()
+        {'boolean indexing': True,
+         'data-dependent shapes': True,
+         'max dimensions': 64}
+
+        """
+        return {
+            "boolean indexing": True,
+            "data-dependent shapes": True,
+            "max dimensions": 64,
+        }
+
+    def default_device(self):
+        """
+        The default device used for new CuPy arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        device : Device
+            The default device used for new CuPy arrays.
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.default_device()
+        Device(0)
+
+        Notes
+        -----
+        This method returns the static default device when CuPy is initialized.
+        However, the *current* device used by creation functions (``empty`` etc.)
+        can be changed globally or with a context manager.
+
+        See Also
+        --------
+        https://github.com/data-apis/array-api/issues/835
+        """
+        return cuda.Device(0)
+
+    def default_dtypes(self, *, device=None):
+        """
+        The default data types used for new CuPy arrays.
+
+        For CuPy, this always returns the following dictionary:
+
+        - **"real floating"**: ``cupy.float64``
+        - **"complex floating"**: ``cupy.complex128``
+        - **"integral"**: ``cupy.intp``
+        - **"indexing"**: ``cupy.intp``
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the default data types for.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary describing the default data types used for new CuPy
+            arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.default_dtypes()
+        {'real floating': cupy.float64,
+         'complex floating': cupy.complex128,
+         'integral': cupy.int64,
+         'indexing': cupy.int64}
+
+        """
+        # TODO: Does this depend on device?
+        return {
+            "real floating": dtype(float64),
+            "complex floating": dtype(complex128),
+            "integral": dtype(intp),
+            "indexing": dtype(intp),
+        }
+
+    def dtypes(self, *, device=None, kind=None):
+        """
+        The array API data types supported by CuPy.
+
+        Note that this function only returns data types that are defined by
+        the array API.
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the data types for.
+        kind : str or tuple of str, optional
+            The kind of data types to return. If ``None``, all data types are
+            returned. If a string, only data types of that kind are returned.
+            If a tuple, a dictionary containing the union of the given kinds
+            is returned. The following kinds are supported:
+
+            - ``'bool'``: boolean data types (i.e., ``bool``).
+            - ``'signed integer'``: signed integer data types (i.e., ``int8``,
+              ``int16``, ``int32``, ``int64``).
+            - ``'unsigned integer'``: unsigned integer data types (i.e.,
+              ``uint8``, ``uint16``, ``uint32``, ``uint64``).
+            - ``'integral'``: integer data types. Shorthand for ``('signed
+              integer', 'unsigned integer')``.
+            - ``'real floating'``: real-valued floating-point data types
+              (i.e., ``float32``, ``float64``).
+            - ``'complex floating'``: complex floating-point data types (i.e.,
+              ``complex64``, ``complex128``).
+            - ``'numeric'``: numeric data types. Shorthand for ``('integral',
+              'real floating', 'complex floating')``.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary mapping the names of data types to the corresponding
+            CuPy data types.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.dtypes(kind='signed integer')
+        {'int8': cupy.int8,
+         'int16': cupy.int16,
+         'int32': cupy.int32,
+         'int64': cupy.int64}
+
+        """
+        # TODO: Does this depend on device?
+        if kind is None:
+            return {
+                "bool": dtype(bool),
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "bool":
+            return {"bool": bool}
+        if kind == "signed integer":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+            }
+        if kind == "unsigned integer":
+            return {
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "integral":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "real floating":
+            return {
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+            }
+        if kind == "complex floating":
+            return {
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "numeric":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if isinstance(kind, tuple):
+            res = {}
+            for k in kind:
+                res.update(self.dtypes(kind=k))
+            return res
+        raise ValueError(f"unsupported kind: {kind!r}")
+
+    def devices(self):
+        """
+        The devices supported by CuPy.
+
+        Returns
+        -------
+        devices : list[Device]
+            The devices supported by CuPy.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes
+
+        """
+        return [cuda.Device(i) for i in range(cuda.runtime.getDeviceCount())]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/cupy/_typing.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/cupy/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8e49ca773dc553cfbc14e526c2c48054e564a12
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/cupy/_typing.py
@@ -0,0 +1,31 @@
+from __future__ import annotations
+
+__all__ = ["Array", "DType", "Device"]
+_all_ignore = ["cp"]
+
+from typing import TYPE_CHECKING
+
+import cupy as cp
+from cupy import ndarray as Array
+from cupy.cuda.device import Device
+
+if TYPE_CHECKING:
+    # NumPy 1.x on Python 3.10 fails to parse np.dtype[]
+    DType = cp.dtype[
+        cp.intp
+        | cp.int8
+        | cp.int16
+        | cp.int32
+        | cp.int64
+        | cp.uint8
+        | cp.uint16
+        | cp.uint32
+        | cp.uint64
+        | cp.float32
+        | cp.float64
+        | cp.complex64
+        | cp.complex128
+        | cp.bool_
+    ]
+else:
+    DType = cp.dtype
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/cupy/fft.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/cupy/fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..307e0f7277710693063ef8c4d2cd7893275ad44a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/cupy/fft.py
@@ -0,0 +1,36 @@
+from cupy.fft import * # noqa: F403
+# cupy.fft doesn't have __all__. If it is added, replace this with
+#
+# from cupy.fft import __all__ as linalg_all
+_n = {}
+exec('from cupy.fft import *', _n)
+del _n['__builtins__']
+fft_all = list(_n)
+del _n
+
+from ..common import _fft
+from .._internal import get_xp
+
+import cupy as cp
+
+fft = get_xp(cp)(_fft.fft)
+ifft = get_xp(cp)(_fft.ifft)
+fftn = get_xp(cp)(_fft.fftn)
+ifftn = get_xp(cp)(_fft.ifftn)
+rfft = get_xp(cp)(_fft.rfft)
+irfft = get_xp(cp)(_fft.irfft)
+rfftn = get_xp(cp)(_fft.rfftn)
+irfftn = get_xp(cp)(_fft.irfftn)
+hfft = get_xp(cp)(_fft.hfft)
+ihfft = get_xp(cp)(_fft.ihfft)
+fftfreq = get_xp(cp)(_fft.fftfreq)
+rfftfreq = get_xp(cp)(_fft.rfftfreq)
+fftshift = get_xp(cp)(_fft.fftshift)
+ifftshift = get_xp(cp)(_fft.ifftshift)
+
+__all__ = fft_all + _fft.__all__
+
+del get_xp
+del cp
+del fft_all
+del _fft
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/cupy/linalg.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/cupy/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fcdd498e0073ada094a20a9ae423e01cb0f8ceb
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/cupy/linalg.py
@@ -0,0 +1,49 @@
+from cupy.linalg import * # noqa: F403
+# cupy.linalg doesn't have __all__. If it is added, replace this with
+#
+# from cupy.linalg import __all__ as linalg_all
+_n = {}
+exec('from cupy.linalg import *', _n)
+del _n['__builtins__']
+linalg_all = list(_n)
+del _n
+
+from ..common import _linalg
+from .._internal import get_xp
+
+import cupy as cp
+
+# These functions are in both the main and linalg namespaces
+from ._aliases import matmul, matrix_transpose, tensordot, vecdot # noqa: F401
+
+cross = get_xp(cp)(_linalg.cross)
+outer = get_xp(cp)(_linalg.outer)
+EighResult = _linalg.EighResult
+QRResult = _linalg.QRResult
+SlogdetResult = _linalg.SlogdetResult
+SVDResult = _linalg.SVDResult
+eigh = get_xp(cp)(_linalg.eigh)
+qr = get_xp(cp)(_linalg.qr)
+slogdet = get_xp(cp)(_linalg.slogdet)
+svd = get_xp(cp)(_linalg.svd)
+cholesky = get_xp(cp)(_linalg.cholesky)
+matrix_rank = get_xp(cp)(_linalg.matrix_rank)
+pinv = get_xp(cp)(_linalg.pinv)
+matrix_norm = get_xp(cp)(_linalg.matrix_norm)
+svdvals = get_xp(cp)(_linalg.svdvals)
+diagonal = get_xp(cp)(_linalg.diagonal)
+trace = get_xp(cp)(_linalg.trace)
+
+# These functions are completely new here. If the library already has them
+# (i.e., numpy 2.0), use the library version instead of our wrapper.
+if hasattr(cp.linalg, 'vector_norm'):
+    vector_norm = cp.linalg.vector_norm
+else:
+    vector_norm = get_xp(cp)(_linalg.vector_norm)
+
+__all__ = linalg_all + _linalg.__all__
+
+del get_xp
+del cp
+del linalg_all
+del _linalg
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/dask/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/dask/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/dask/array/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/dask/array/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e47b9606b7744620f41e9888b7c064f9c504520
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/dask/array/__init__.py
@@ -0,0 +1,12 @@
+from typing import Final
+
+from dask.array import *  # noqa: F403
+
+# These imports may overwrite names from the import * above.
+from ._aliases import *  # noqa: F403
+
+__array_api_version__: Final = "2024.12"
+
+# See the comment in the numpy __init__.py
+__import__(__package__ + '.linalg')
+__import__(__package__ + '.fft')
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/dask/array/_aliases.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/dask/array/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..d43881ab18f1c0e11efcbd38598a5ca285842919
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/dask/array/_aliases.py
@@ -0,0 +1,376 @@
+# pyright: reportPrivateUsage=false
+# pyright: reportUnknownArgumentType=false
+# pyright: reportUnknownMemberType=false
+# pyright: reportUnknownVariableType=false
+
+from __future__ import annotations
+
+from builtins import bool as py_bool
+from collections.abc import Callable
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+    from typing_extensions import TypeIs
+
+import dask.array as da
+import numpy as np
+from numpy import bool_ as bool
+from numpy import (
+    can_cast,
+    complex64,
+    complex128,
+    float32,
+    float64,
+    int8,
+    int16,
+    int32,
+    int64,
+    result_type,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+)
+
+from ..._internal import get_xp
+from ...common import _aliases, _helpers, array_namespace
+from ...common._typing import (
+    Array,
+    Device,
+    DType,
+    NestedSequence,
+    SupportsBufferProtocol,
+)
+from ._info import __array_namespace_info__
+
+isdtype = get_xp(np)(_aliases.isdtype)
+unstack = get_xp(da)(_aliases.unstack)
+
+
+# da.astype doesn't respect copy=True
+def astype(
+    x: Array,
+    dtype: DType,
+    /,
+    *,
+    copy: py_bool = True,
+    device: Device | None = None,
+) -> Array:
+    """
+    Array API compatibility wrapper for astype().
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+    # TODO: respect device keyword?
+    _helpers._check_device(da, device)
+
+    if not copy and dtype == x.dtype:
+        return x
+    x = x.astype(dtype)
+    return x.copy() if copy else x
+
+
+# Common aliases
+
+
+# This arange func is modified from the common one to
+# not pass stop/step as keyword arguments, which will cause
+# an error with dask
+def arange(
+    start: float,
+    /,
+    stop: float | None = None,
+    step: float = 1,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    **kwargs: object,
+) -> Array:
+    """
+    Array API compatibility wrapper for arange().
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+    # TODO: respect device keyword?
+    _helpers._check_device(da, device)
+
+    args: list[Any] = [start]
+    if stop is not None:
+        args.append(stop)
+    else:
+        # stop is None, so start is actually stop
+        # prepend the default value for start which is 0
+        args.insert(0, 0)
+    args.append(step)
+
+    return da.arange(*args, dtype=dtype, **kwargs)
+
+
+eye = get_xp(da)(_aliases.eye)
+linspace = get_xp(da)(_aliases.linspace)
+UniqueAllResult = get_xp(da)(_aliases.UniqueAllResult)
+UniqueCountsResult = get_xp(da)(_aliases.UniqueCountsResult)
+UniqueInverseResult = get_xp(da)(_aliases.UniqueInverseResult)
+unique_all = get_xp(da)(_aliases.unique_all)
+unique_counts = get_xp(da)(_aliases.unique_counts)
+unique_inverse = get_xp(da)(_aliases.unique_inverse)
+unique_values = get_xp(da)(_aliases.unique_values)
+permute_dims = get_xp(da)(_aliases.permute_dims)
+std = get_xp(da)(_aliases.std)
+var = get_xp(da)(_aliases.var)
+cumulative_sum = get_xp(da)(_aliases.cumulative_sum)
+cumulative_prod = get_xp(da)(_aliases.cumulative_prod)
+empty = get_xp(da)(_aliases.empty)
+empty_like = get_xp(da)(_aliases.empty_like)
+full = get_xp(da)(_aliases.full)
+full_like = get_xp(da)(_aliases.full_like)
+ones = get_xp(da)(_aliases.ones)
+ones_like = get_xp(da)(_aliases.ones_like)
+zeros = get_xp(da)(_aliases.zeros)
+zeros_like = get_xp(da)(_aliases.zeros_like)
+reshape = get_xp(da)(_aliases.reshape)
+matrix_transpose = get_xp(da)(_aliases.matrix_transpose)
+vecdot = get_xp(da)(_aliases.vecdot)
+nonzero = get_xp(da)(_aliases.nonzero)
+ceil = get_xp(np)(_aliases.ceil)
+floor = get_xp(np)(_aliases.floor)
+trunc = get_xp(np)(_aliases.trunc)
+matmul = get_xp(np)(_aliases.matmul)
+tensordot = get_xp(np)(_aliases.tensordot)
+sign = get_xp(np)(_aliases.sign)
+finfo = get_xp(np)(_aliases.finfo)
+iinfo = get_xp(np)(_aliases.iinfo)
+
+
+# asarray also adds the copy keyword, which is not present in numpy 1.0.
+def asarray(
+    obj: complex | NestedSequence[complex] | Array | SupportsBufferProtocol,
+    /,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    copy: py_bool | None = None,
+    **kwargs: object,
+) -> Array:
+    """
+    Array API compatibility wrapper for asarray().
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+    # TODO: respect device keyword?
+    _helpers._check_device(da, device)
+
+    if isinstance(obj, da.Array):
+        if dtype is not None and dtype != obj.dtype:
+            if copy is False:
+                raise ValueError("Unable to avoid copy when changing dtype")
+            obj = obj.astype(dtype)
+        return obj.copy() if copy else obj  # pyright: ignore[reportAttributeAccessIssue]
+
+    if copy is False:
+        raise ValueError(
+            "Unable to avoid copy when converting a non-dask object to dask"
+        )
+
+    # copy=None to be uniform across dask < 2024.12 and >= 2024.12
+    # see https://github.com/dask/dask/pull/11524/
+    obj = np.array(obj, dtype=dtype, copy=True)
+    return da.from_array(obj)
+
+
+# Element wise aliases
+from dask.array import arccos as acos
+from dask.array import arccosh as acosh
+from dask.array import arcsin as asin
+from dask.array import arcsinh as asinh
+from dask.array import arctan as atan
+from dask.array import arctan2 as atan2
+from dask.array import arctanh as atanh
+
+# Other
+from dask.array import concatenate as concat
+from dask.array import invert as bitwise_invert
+from dask.array import left_shift as bitwise_left_shift
+from dask.array import power as pow
+from dask.array import right_shift as bitwise_right_shift
+
+
+# dask.array.clip does not work unless all three arguments are provided.
+# Furthermore, the masking workaround in common._aliases.clip cannot work with
+# dask (meaning uint64 promoting to float64 is going to just be unfixed for
+# now).
+def clip(
+    x: Array,
+    /,
+    min: float | Array | None = None,
+    max: float | Array | None = None,
+) -> Array:
+    """
+    Array API compatibility wrapper for clip().
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+
+    def _isscalar(a: float | Array | None, /) -> TypeIs[float | None]:
+        return a is None or isinstance(a, (int, float))
+
+    min_shape = () if _isscalar(min) else min.shape
+    max_shape = () if _isscalar(max) else max.shape
+
+    # TODO: This won't handle dask unknown shapes
+    result_shape = np.broadcast_shapes(x.shape, min_shape, max_shape)
+
+    if min is not None:
+        min = da.broadcast_to(da.asarray(min), result_shape)
+    if max is not None:
+        max = da.broadcast_to(da.asarray(max), result_shape)
+
+    if min is None and max is None:
+        return da.positive(x)
+
+    if min is None:
+        return astype(da.minimum(x, max), x.dtype)
+    if max is None:
+        return astype(da.maximum(x, min), x.dtype)
+
+    return astype(da.minimum(da.maximum(x, min), max), x.dtype)
+
+
+def _ensure_single_chunk(x: Array, axis: int) -> tuple[Array, Callable[[Array], Array]]:
+    """
+    Make sure that Array is not broken into multiple chunks along axis.
+
+    Returns
+    -------
+    x : Array
+        The input Array with a single chunk along axis.
+    restore : Callable[Array, Array]
+        function to apply to the output to rechunk it back into reasonable chunks
+    """
+    if axis < 0:
+        axis += x.ndim
+    if x.numblocks[axis] < 2:
+        return x, lambda x: x
+
+    # Break chunks on other axes in an attempt to keep chunk size low
+    x = x.rechunk({i: -1 if i == axis else "auto" for i in range(x.ndim)})
+
+    # Rather than reconstructing the original chunks, which can be a
+    # very expensive affair, just break down oversized chunks without
+    # incurring in any transfers over the network.
+    # This has the downside of a risk of overchunking if the array is
+    # then used in operations against other arrays that match the
+    # original chunking pattern.
+    return x, lambda x: x.rechunk()
+
+
+def sort(
+    x: Array,
+    /,
+    *,
+    axis: int = -1,
+    descending: py_bool = False,
+    stable: py_bool = True,
+) -> Array:
+    """
+    Array API compatibility layer around the lack of sort() in Dask.
+
+    Warnings
+    --------
+    This function temporarily rechunks the array along `axis` to a single chunk.
+    This can be extremely inefficient and can lead to out-of-memory errors.
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+    x, restore = _ensure_single_chunk(x, axis)
+
+    meta_xp = array_namespace(x._meta)
+    x = da.map_blocks(
+        meta_xp.sort,
+        x,
+        axis=axis,
+        meta=x._meta,
+        dtype=x.dtype,
+        descending=descending,
+        stable=stable,
+    )
+
+    return restore(x)
+
+
+def argsort(
+    x: Array,
+    /,
+    *,
+    axis: int = -1,
+    descending: py_bool = False,
+    stable: py_bool = True,
+) -> Array:
+    """
+    Array API compatibility layer around the lack of argsort() in Dask.
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+
+    Warnings
+    --------
+    This function temporarily rechunks the array along `axis` into a single chunk.
+    This can be extremely inefficient and can lead to out-of-memory errors.
+    """
+    x, restore = _ensure_single_chunk(x, axis)
+
+    meta_xp = array_namespace(x._meta)
+    dtype = meta_xp.argsort(x._meta).dtype
+    meta = meta_xp.astype(x._meta, dtype)
+    x = da.map_blocks(
+        meta_xp.argsort,
+        x,
+        axis=axis,
+        meta=meta,
+        dtype=dtype,
+        descending=descending,
+        stable=stable,
+    )
+
+    return restore(x)
+
+
+# dask.array.count_nonzero does not have keepdims
+def count_nonzero(
+    x: Array,
+    axis: int | None = None,
+    keepdims: py_bool = False,
+) -> Array:
+    result = da.count_nonzero(x, axis)
+    if keepdims:
+        if axis is None:
+            return da.reshape(result, [1] * x.ndim)
+        return da.expand_dims(result, axis)
+    return result
+
+
+__all__ = [
+    "__array_namespace_info__",
+    "count_nonzero",
+    "bool",
+    "int8", "int16", "int32", "int64",
+    "uint8", "uint16", "uint32", "uint64",
+    "float32", "float64",
+    "complex64", "complex128",
+    "asarray", "astype", "can_cast", "result_type",
+    "pow",
+    "concat",
+    "acos", "acosh", "asin", "asinh", "atan", "atan2", "atanh",
+    "bitwise_left_shift", "bitwise_right_shift", "bitwise_invert",
+]  # fmt: skip
+__all__ += _aliases.__all__
+_all_ignore = ["array_namespace", "get_xp", "da", "np"]
+
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/dask/array/_info.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/dask/array/_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e4d736f99657e11b972739ceead83c18fefe1e2
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/dask/array/_info.py
@@ -0,0 +1,416 @@
+"""
+Array API Inspection namespace
+
+This is the namespace for inspection functions as defined by the array API
+standard. See
+https://data-apis.org/array-api/latest/API_specification/inspection.html for
+more details.
+
+"""
+
+# pyright: reportPrivateUsage=false
+
+from __future__ import annotations
+
+from typing import Literal as L
+from typing import TypeAlias, overload
+
+from numpy import bool_ as bool
+from numpy import (
+    complex64,
+    complex128,
+    dtype,
+    float32,
+    float64,
+    int8,
+    int16,
+    int32,
+    int64,
+    intp,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+)
+
+from ...common._helpers import _DASK_DEVICE, _dask_device
+from ...common._typing import (
+    Capabilities,
+    DefaultDTypes,
+    DType,
+    DTypeKind,
+    DTypesAll,
+    DTypesAny,
+    DTypesBool,
+    DTypesComplex,
+    DTypesIntegral,
+    DTypesNumeric,
+    DTypesReal,
+    DTypesSigned,
+    DTypesUnsigned,
+)
+
+_Device: TypeAlias = L["cpu"] | _dask_device
+
+
+class __array_namespace_info__:
+    """
+    Get the array API inspection namespace for Dask.
+
+    The array API inspection namespace defines the following functions:
+
+    - capabilities()
+    - default_device()
+    - default_dtypes()
+    - dtypes()
+    - devices()
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/inspection.html
+    for more details.
+
+    Returns
+    -------
+    info : ModuleType
+        The array API inspection namespace for Dask.
+
+    Examples
+    --------
+    >>> info = xp.__array_namespace_info__()
+    >>> info.default_dtypes()
+    {'real floating': dask.float64,
+     'complex floating': dask.complex128,
+     'integral': dask.int64,
+     'indexing': dask.int64}
+
+    """
+
+    __module__ = "dask.array"
+
+    def capabilities(self) -> Capabilities:
+        """
+        Return a dictionary of array API library capabilities.
+
+        The resulting dictionary has the following keys:
+
+        - **"boolean indexing"**: boolean indicating whether an array library
+          supports boolean indexing.
+
+          Dask support boolean indexing as long as both the index
+          and the indexed arrays have known shapes.
+          Note however that the output .shape and .size properties
+          will contain a non-compliant math.nan instead of None.
+
+        - **"data-dependent shapes"**: boolean indicating whether an array
+          library supports data-dependent output shapes.
+
+          Dask implements unique_values et.al.
+          Note however that the output .shape and .size properties
+          will contain a non-compliant math.nan instead of None.
+
+        - **"max dimensions"**: integer indicating the maximum number of
+          dimensions supported by the array library.
+
+        See
+        https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html
+        for more details.
+
+        See Also
+        --------
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        capabilities : dict
+            A dictionary of array API library capabilities.
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.capabilities()
+        {'boolean indexing': True,
+         'data-dependent shapes': True,
+         'max dimensions': 64}
+
+        """
+        return {
+            "boolean indexing": True,
+            "data-dependent shapes": True,
+            "max dimensions": 64,
+        }
+
+    def default_device(self) -> L["cpu"]:
+        """
+        The default device used for new Dask arrays.
+
+        For Dask, this always returns ``'cpu'``.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        device : Device
+            The default device used for new Dask arrays.
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.default_device()
+        'cpu'
+
+        """
+        return "cpu"
+
+    def default_dtypes(self, /, *, device: _Device | None = None) -> DefaultDTypes:
+        """
+        The default data types used for new Dask arrays.
+
+        For Dask, this always returns the following dictionary:
+
+        - **"real floating"**: ``numpy.float64``
+        - **"complex floating"**: ``numpy.complex128``
+        - **"integral"**: ``numpy.intp``
+        - **"indexing"**: ``numpy.intp``
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the default data types for.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary describing the default data types used for new Dask
+            arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.default_dtypes()
+        {'real floating': dask.float64,
+         'complex floating': dask.complex128,
+         'integral': dask.int64,
+         'indexing': dask.int64}
+
+        """
+        if device not in ["cpu", _DASK_DEVICE, None]:
+            raise ValueError(
+                f'Device not understood. Only "cpu" or _DASK_DEVICE is allowed, '
+                f"but received: {device!r}"
+            )
+        return {
+            "real floating": dtype(float64),
+            "complex floating": dtype(complex128),
+            "integral": dtype(intp),
+            "indexing": dtype(intp),
+        }
+
+    @overload
+    def dtypes(
+        self, /, *, device: _Device | None = None, kind: None = None
+    ) -> DTypesAll: ...
+    @overload
+    def dtypes(
+        self, /, *, device: _Device | None = None, kind: L["bool"]
+    ) -> DTypesBool: ...
+    @overload
+    def dtypes(
+        self, /, *, device: _Device | None = None, kind: L["signed integer"]
+    ) -> DTypesSigned: ...
+    @overload
+    def dtypes(
+        self, /, *, device: _Device | None = None, kind: L["unsigned integer"]
+    ) -> DTypesUnsigned: ...
+    @overload
+    def dtypes(
+        self, /, *, device: _Device | None = None, kind: L["integral"]
+    ) -> DTypesIntegral: ...
+    @overload
+    def dtypes(
+        self, /, *, device: _Device | None = None, kind: L["real floating"]
+    ) -> DTypesReal: ...
+    @overload
+    def dtypes(
+        self, /, *, device: _Device | None = None, kind: L["complex floating"]
+    ) -> DTypesComplex: ...
+    @overload
+    def dtypes(
+        self, /, *, device: _Device | None = None, kind: L["numeric"]
+    ) -> DTypesNumeric: ...
+    def dtypes(
+        self, /, *, device: _Device | None = None, kind: DTypeKind | None = None
+    ) -> DTypesAny:
+        """
+        The array API data types supported by Dask.
+
+        Note that this function only returns data types that are defined by
+        the array API.
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the data types for.
+        kind : str or tuple of str, optional
+            The kind of data types to return. If ``None``, all data types are
+            returned. If a string, only data types of that kind are returned.
+            If a tuple, a dictionary containing the union of the given kinds
+            is returned. The following kinds are supported:
+
+            - ``'bool'``: boolean data types (i.e., ``bool``).
+            - ``'signed integer'``: signed integer data types (i.e., ``int8``,
+              ``int16``, ``int32``, ``int64``).
+            - ``'unsigned integer'``: unsigned integer data types (i.e.,
+              ``uint8``, ``uint16``, ``uint32``, ``uint64``).
+            - ``'integral'``: integer data types. Shorthand for ``('signed
+              integer', 'unsigned integer')``.
+            - ``'real floating'``: real-valued floating-point data types
+              (i.e., ``float32``, ``float64``).
+            - ``'complex floating'``: complex floating-point data types (i.e.,
+              ``complex64``, ``complex128``).
+            - ``'numeric'``: numeric data types. Shorthand for ``('integral',
+              'real floating', 'complex floating')``.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary mapping the names of data types to the corresponding
+            Dask data types.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.dtypes(kind='signed integer')
+        {'int8': dask.int8,
+         'int16': dask.int16,
+         'int32': dask.int32,
+         'int64': dask.int64}
+
+        """
+        if device not in ["cpu", _DASK_DEVICE, None]:
+            raise ValueError(
+                'Device not understood. Only "cpu" or _DASK_DEVICE is allowed, but received:'
+                f" {device}"
+            )
+        if kind is None:
+            return {
+                "bool": dtype(bool),
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "bool":
+            return {"bool": bool}
+        if kind == "signed integer":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+            }
+        if kind == "unsigned integer":
+            return {
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "integral":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "real floating":
+            return {
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+            }
+        if kind == "complex floating":
+            return {
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "numeric":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if isinstance(kind, tuple):  # type: ignore[reportUnnecessaryIsinstanceCall]
+            res: dict[str, DType] = {}
+            for k in kind:
+                res.update(self.dtypes(kind=k))
+            return res
+        raise ValueError(f"unsupported kind: {kind!r}")
+
+    def devices(self) -> list[_Device]:
+        """
+        The devices supported by Dask.
+
+        For Dask, this always returns ``['cpu', DASK_DEVICE]``.
+
+        Returns
+        -------
+        devices : list[Device]
+            The devices supported by Dask.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.devices()
+        ['cpu', DASK_DEVICE]
+
+        """
+        return ["cpu", _DASK_DEVICE]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/dask/array/fft.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/dask/array/fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f40dffe7abd51d5b4c12d29949e70d883b1c405
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/dask/array/fft.py
@@ -0,0 +1,21 @@
+from dask.array.fft import * # noqa: F403
+# dask.array.fft doesn't have __all__. If it is added, replace this with
+#
+# from dask.array.fft import __all__ as linalg_all
+_n = {}
+exec('from dask.array.fft import *', _n)
+for k in ("__builtins__", "Sequence", "annotations", "warnings"):
+    _n.pop(k, None)
+fft_all = list(_n)
+del _n, k
+
+from ...common import _fft
+from ..._internal import get_xp
+
+import dask.array as da
+
+fftfreq = get_xp(da)(_fft.fftfreq)
+rfftfreq = get_xp(da)(_fft.rfftfreq)
+
+__all__ = fft_all + ["fftfreq", "rfftfreq"]
+_all_ignore = ["da", "fft_all", "get_xp", "warnings"]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/dask/array/linalg.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/dask/array/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..0825386ed5dc3418d06b3bbe04e7ddac5945ed82
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/dask/array/linalg.py
@@ -0,0 +1,72 @@
+from __future__ import annotations
+
+from typing import Literal
+
+import dask.array as da
+
+# The `matmul` and `tensordot` functions are in both the main and linalg namespaces
+from dask.array import matmul, outer, tensordot
+
+# Exports
+from dask.array.linalg import *  # noqa: F403
+
+from ..._internal import get_xp
+from ...common import _linalg
+from ...common._typing import Array as _Array
+from ._aliases import matrix_transpose, vecdot
+
+# dask.array.linalg doesn't have __all__. If it is added, replace this with
+#
+# from dask.array.linalg import __all__ as linalg_all
+_n = {}
+exec('from dask.array.linalg import *', _n)
+for k in ('__builtins__', 'annotations', 'operator', 'warnings', 'Array'):
+    _n.pop(k, None)
+linalg_all = list(_n)
+del _n, k
+
+EighResult = _linalg.EighResult
+QRResult = _linalg.QRResult
+SlogdetResult = _linalg.SlogdetResult
+SVDResult = _linalg.SVDResult
+# TODO: use the QR wrapper once dask
+# supports the mode keyword on QR
+# https://github.com/dask/dask/issues/10388
+#qr = get_xp(da)(_linalg.qr)
+def qr(
+    x: _Array,
+    mode: Literal["reduced", "complete"] = "reduced",
+    **kwargs: object,
+) -> QRResult:
+    if mode != "reduced":
+        raise ValueError("dask arrays only support using mode='reduced'")
+    return QRResult(*da.linalg.qr(x, **kwargs))
+trace = get_xp(da)(_linalg.trace)
+cholesky = get_xp(da)(_linalg.cholesky)
+matrix_rank = get_xp(da)(_linalg.matrix_rank)
+matrix_norm = get_xp(da)(_linalg.matrix_norm)
+
+
+# Wrap the svd functions to not pass full_matrices to dask
+# when full_matrices=False (as that is the default behavior for dask),
+# and dask doesn't have the full_matrices keyword
+def svd(x: _Array, full_matrices: bool = True, **kwargs) -> SVDResult:
+    if full_matrices:
+        raise ValueError("full_matrics=True is not supported by dask.")
+    return da.linalg.svd(x, coerce_signs=False, **kwargs)
+
+def svdvals(x: _Array) -> _Array:
+    # TODO: can't avoid computing U or V for dask
+    _, s, _ =  svd(x)
+    return s
+
+vector_norm = get_xp(da)(_linalg.vector_norm)
+diagonal = get_xp(da)(_linalg.diagonal)
+
+__all__ = linalg_all + ["trace", "outer", "matmul", "tensordot",
+                        "matrix_transpose", "vecdot", "EighResult",
+                        "QRResult", "SlogdetResult", "SVDResult", "qr",
+                        "cholesky", "matrix_rank", "matrix_norm", "svdvals",
+                        "vector_norm", "diagonal"]
+
+_all_ignore = ['get_xp', 'da', 'linalg_all', 'warnings']
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e138f53db006566b19857bd2ef4c26ce988f020
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__init__.py
@@ -0,0 +1,28 @@
+# ruff: noqa: PLC0414
+from typing import Final
+
+from numpy import *  # noqa: F403  # pyright: ignore[reportWildcardImportFromLibrary]
+
+# from numpy import * doesn't overwrite these builtin names
+from numpy import abs as abs
+from numpy import max as max
+from numpy import min as min
+from numpy import round as round
+
+# These imports may overwrite names from the import * above.
+from ._aliases import *  # noqa: F403
+
+# Don't know why, but we have to do an absolute import to import linalg. If we
+# instead do
+#
+# from . import linalg
+#
+# It doesn't overwrite np.linalg from above. The import is generated
+# dynamically so that the library can be vendored.
+__import__(__package__ + ".linalg")
+
+__import__(__package__ + ".fft")
+
+from .linalg import matrix_transpose, vecdot  # type: ignore[no-redef]  # noqa: F401
+
+__array_api_version__: Final = "2024.12"
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d891b97ceca2b2ae989131ba7b3c6fc922f1dba
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__pycache__/_aliases.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__pycache__/_aliases.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ccb6b974878618a8e76fd0a58739d4b46db61688
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__pycache__/_aliases.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__pycache__/_info.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__pycache__/_info.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..293287bba7233bd909a618fcc2328be4995bafa6
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__pycache__/_info.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__pycache__/_typing.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__pycache__/_typing.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fe9d4d180b85a31760ffe4afd2860ba60695deeb
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__pycache__/_typing.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__pycache__/fft.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__pycache__/fft.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59eaff1508138452e71b2325f84c63fba84e0e7f
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__pycache__/fft.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__pycache__/linalg.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__pycache__/linalg.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ca82513c4032f49191daad912ec8a4e2c264bc1
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/__pycache__/linalg.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/_aliases.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1aee5c0df7969ba8308980d194f7ee92f307eed
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/_aliases.py
@@ -0,0 +1,190 @@
+# pyright: reportPrivateUsage=false
+from __future__ import annotations
+
+from builtins import bool as py_bool
+from typing import TYPE_CHECKING, Any, Literal, TypeAlias, cast
+
+import numpy as np
+
+from .._internal import get_xp
+from ..common import _aliases, _helpers
+from ..common._typing import NestedSequence, SupportsBufferProtocol
+from ._info import __array_namespace_info__
+from ._typing import Array, Device, DType
+
+if TYPE_CHECKING:
+    from typing_extensions import Buffer, TypeIs
+
+# The values of the `_CopyMode` enum can be either `False`, `True`, or `2`:
+# https://github.com/numpy/numpy/blob/5a8a6a79d9c2fff8f07dcab5d41e14f8508d673f/numpy/_globals.pyi#L7-L10
+_Copy: TypeAlias = py_bool | Literal[2] | np._CopyMode
+
+bool = np.bool_
+
+# Basic renames
+acos = np.arccos
+acosh = np.arccosh
+asin = np.arcsin
+asinh = np.arcsinh
+atan = np.arctan
+atan2 = np.arctan2
+atanh = np.arctanh
+bitwise_left_shift = np.left_shift
+bitwise_invert = np.invert
+bitwise_right_shift = np.right_shift
+concat = np.concatenate
+pow = np.power
+
+arange = get_xp(np)(_aliases.arange)
+empty = get_xp(np)(_aliases.empty)
+empty_like = get_xp(np)(_aliases.empty_like)
+eye = get_xp(np)(_aliases.eye)
+full = get_xp(np)(_aliases.full)
+full_like = get_xp(np)(_aliases.full_like)
+linspace = get_xp(np)(_aliases.linspace)
+ones = get_xp(np)(_aliases.ones)
+ones_like = get_xp(np)(_aliases.ones_like)
+zeros = get_xp(np)(_aliases.zeros)
+zeros_like = get_xp(np)(_aliases.zeros_like)
+UniqueAllResult = get_xp(np)(_aliases.UniqueAllResult)
+UniqueCountsResult = get_xp(np)(_aliases.UniqueCountsResult)
+UniqueInverseResult = get_xp(np)(_aliases.UniqueInverseResult)
+unique_all = get_xp(np)(_aliases.unique_all)
+unique_counts = get_xp(np)(_aliases.unique_counts)
+unique_inverse = get_xp(np)(_aliases.unique_inverse)
+unique_values = get_xp(np)(_aliases.unique_values)
+std = get_xp(np)(_aliases.std)
+var = get_xp(np)(_aliases.var)
+cumulative_sum = get_xp(np)(_aliases.cumulative_sum)
+cumulative_prod = get_xp(np)(_aliases.cumulative_prod)
+clip = get_xp(np)(_aliases.clip)
+permute_dims = get_xp(np)(_aliases.permute_dims)
+reshape = get_xp(np)(_aliases.reshape)
+argsort = get_xp(np)(_aliases.argsort)
+sort = get_xp(np)(_aliases.sort)
+nonzero = get_xp(np)(_aliases.nonzero)
+ceil = get_xp(np)(_aliases.ceil)
+floor = get_xp(np)(_aliases.floor)
+trunc = get_xp(np)(_aliases.trunc)
+matmul = get_xp(np)(_aliases.matmul)
+matrix_transpose = get_xp(np)(_aliases.matrix_transpose)
+tensordot = get_xp(np)(_aliases.tensordot)
+sign = get_xp(np)(_aliases.sign)
+finfo = get_xp(np)(_aliases.finfo)
+iinfo = get_xp(np)(_aliases.iinfo)
+
+
+def _supports_buffer_protocol(obj: object) -> TypeIs[Buffer]:  # pyright: ignore[reportUnusedFunction]
+    try:
+        memoryview(obj)  # pyright: ignore[reportArgumentType]
+    except TypeError:
+        return False
+    return True
+
+
+# asarray also adds the copy keyword, which is not present in numpy 1.0.
+# asarray() is different enough between numpy, cupy, and dask, the logic
+# complicated enough that it's easier to define it separately for each module
+# rather than trying to combine everything into one function in common/
+def asarray(
+    obj: Array | complex | NestedSequence[complex] | SupportsBufferProtocol,
+    /,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    copy: _Copy | None = None,
+    **kwargs: Any,
+) -> Array:
+    """
+    Array API compatibility wrapper for asarray().
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+    _helpers._check_device(np, device)
+
+    if copy is None:
+        copy = np._CopyMode.IF_NEEDED
+    elif copy is False:
+        copy = np._CopyMode.NEVER
+    elif copy is True:
+        copy = np._CopyMode.ALWAYS
+
+    return np.array(obj, copy=copy, dtype=dtype, **kwargs)  # pyright: ignore
+
+
+def astype(
+    x: Array,
+    dtype: DType,
+    /,
+    *,
+    copy: py_bool = True,
+    device: Device | None = None,
+) -> Array:
+    _helpers._check_device(np, device)
+    return x.astype(dtype=dtype, copy=copy)
+
+
+# count_nonzero returns a python int for axis=None and keepdims=False
+# https://github.com/numpy/numpy/issues/17562
+def count_nonzero(
+    x: Array,
+    axis: int | tuple[int, ...] | None = None,
+    keepdims: py_bool = False,
+) -> Array:
+    # NOTE: this is currently incorrectly typed in numpy, but will be fixed in
+    # numpy 2.2.5 and 2.3.0: https://github.com/numpy/numpy/pull/28750
+    result = cast("Any", np.count_nonzero(x, axis=axis, keepdims=keepdims))  # pyright: ignore[reportArgumentType, reportCallIssue]
+    if axis is None and not keepdims:
+        return np.asarray(result)
+    return result
+
+
+# take_along_axis: axis defaults to -1 but in numpy axis is a required arg
+def take_along_axis(x: Array, indices: Array, /, *, axis: int = -1):
+    return np.take_along_axis(x, indices, axis=axis)
+
+
+# These functions are completely new here. If the library already has them
+# (i.e., numpy 2.0), use the library version instead of our wrapper.
+if hasattr(np, "vecdot"):
+    vecdot = np.vecdot
+else:
+    vecdot = get_xp(np)(_aliases.vecdot)
+
+if hasattr(np, "isdtype"):
+    isdtype = np.isdtype
+else:
+    isdtype = get_xp(np)(_aliases.isdtype)
+
+if hasattr(np, "unstack"):
+    unstack = np.unstack
+else:
+    unstack = get_xp(np)(_aliases.unstack)
+
+__all__ = [
+    "__array_namespace_info__",
+    "asarray",
+    "astype",
+    "acos",
+    "acosh",
+    "asin",
+    "asinh",
+    "atan",
+    "atan2",
+    "atanh",
+    "bitwise_left_shift",
+    "bitwise_invert",
+    "bitwise_right_shift",
+    "bool",
+    "concat",
+    "count_nonzero",
+    "pow",
+    "take_along_axis"
+]
+__all__ += _aliases.__all__
+_all_ignore = ["np", "get_xp"]
+
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/_info.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..f307f62c5d5d5d3b100de9adb8c9beb70b754cb3
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/_info.py
@@ -0,0 +1,366 @@
+"""
+Array API Inspection namespace
+
+This is the namespace for inspection functions as defined by the array API
+standard. See
+https://data-apis.org/array-api/latest/API_specification/inspection.html for
+more details.
+
+"""
+from __future__ import annotations
+
+from numpy import bool_ as bool
+from numpy import (
+    complex64,
+    complex128,
+    dtype,
+    float32,
+    float64,
+    int8,
+    int16,
+    int32,
+    int64,
+    intp,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+)
+
+from ._typing import Device, DType
+
+
+class __array_namespace_info__:
+    """
+    Get the array API inspection namespace for NumPy.
+
+    The array API inspection namespace defines the following functions:
+
+    - capabilities()
+    - default_device()
+    - default_dtypes()
+    - dtypes()
+    - devices()
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/inspection.html
+    for more details.
+
+    Returns
+    -------
+    info : ModuleType
+        The array API inspection namespace for NumPy.
+
+    Examples
+    --------
+    >>> info = np.__array_namespace_info__()
+    >>> info.default_dtypes()
+    {'real floating': numpy.float64,
+     'complex floating': numpy.complex128,
+     'integral': numpy.int64,
+     'indexing': numpy.int64}
+
+    """
+
+    __module__ = 'numpy'
+
+    def capabilities(self):
+        """
+        Return a dictionary of array API library capabilities.
+
+        The resulting dictionary has the following keys:
+
+        - **"boolean indexing"**: boolean indicating whether an array library
+          supports boolean indexing. Always ``True`` for NumPy.
+
+        - **"data-dependent shapes"**: boolean indicating whether an array
+          library supports data-dependent output shapes. Always ``True`` for
+          NumPy.
+
+        See
+        https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html
+        for more details.
+
+        See Also
+        --------
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        capabilities : dict
+            A dictionary of array API library capabilities.
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.capabilities()
+        {'boolean indexing': True,
+         'data-dependent shapes': True,
+         'max dimensions': 64}
+
+        """
+        return {
+            "boolean indexing": True,
+            "data-dependent shapes": True,
+            "max dimensions": 64,
+        }
+
+    def default_device(self):
+        """
+        The default device used for new NumPy arrays.
+
+        For NumPy, this always returns ``'cpu'``.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        device : Device
+            The default device used for new NumPy arrays.
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.default_device()
+        'cpu'
+
+        """
+        return "cpu"
+
+    def default_dtypes(
+        self,
+        *,
+        device: Device | None = None,
+    ) -> dict[str, dtype[intp | float64 | complex128]]:
+        """
+        The default data types used for new NumPy arrays.
+
+        For NumPy, this always returns the following dictionary:
+
+        - **"real floating"**: ``numpy.float64``
+        - **"complex floating"**: ``numpy.complex128``
+        - **"integral"**: ``numpy.intp``
+        - **"indexing"**: ``numpy.intp``
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the default data types for. For NumPy, only
+            ``'cpu'`` is allowed.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary describing the default data types used for new NumPy
+            arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.default_dtypes()
+        {'real floating': numpy.float64,
+         'complex floating': numpy.complex128,
+         'integral': numpy.int64,
+         'indexing': numpy.int64}
+
+        """
+        if device not in ["cpu", None]:
+            raise ValueError(
+                'Device not understood. Only "cpu" is allowed, but received:'
+                f' {device}'
+            )
+        return {
+            "real floating": dtype(float64),
+            "complex floating": dtype(complex128),
+            "integral": dtype(intp),
+            "indexing": dtype(intp),
+        }
+
+    def dtypes(
+        self,
+        *,
+        device: Device | None = None,
+        kind: str | tuple[str, ...] | None = None,
+    ) -> dict[str, DType]:
+        """
+        The array API data types supported by NumPy.
+
+        Note that this function only returns data types that are defined by
+        the array API.
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the data types for. For NumPy, only ``'cpu'`` is
+            allowed.
+        kind : str or tuple of str, optional
+            The kind of data types to return. If ``None``, all data types are
+            returned. If a string, only data types of that kind are returned.
+            If a tuple, a dictionary containing the union of the given kinds
+            is returned. The following kinds are supported:
+
+            - ``'bool'``: boolean data types (i.e., ``bool``).
+            - ``'signed integer'``: signed integer data types (i.e., ``int8``,
+              ``int16``, ``int32``, ``int64``).
+            - ``'unsigned integer'``: unsigned integer data types (i.e.,
+              ``uint8``, ``uint16``, ``uint32``, ``uint64``).
+            - ``'integral'``: integer data types. Shorthand for ``('signed
+              integer', 'unsigned integer')``.
+            - ``'real floating'``: real-valued floating-point data types
+              (i.e., ``float32``, ``float64``).
+            - ``'complex floating'``: complex floating-point data types (i.e.,
+              ``complex64``, ``complex128``).
+            - ``'numeric'``: numeric data types. Shorthand for ``('integral',
+              'real floating', 'complex floating')``.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary mapping the names of data types to the corresponding
+            NumPy data types.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.dtypes(kind='signed integer')
+        {'int8': numpy.int8,
+         'int16': numpy.int16,
+         'int32': numpy.int32,
+         'int64': numpy.int64}
+
+        """
+        if device not in ["cpu", None]:
+            raise ValueError(
+                'Device not understood. Only "cpu" is allowed, but received:'
+                f' {device}'
+            )
+        if kind is None:
+            return {
+                "bool": dtype(bool),
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "bool":
+            return {"bool": dtype(bool)}
+        if kind == "signed integer":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+            }
+        if kind == "unsigned integer":
+            return {
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "integral":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "real floating":
+            return {
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+            }
+        if kind == "complex floating":
+            return {
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "numeric":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if isinstance(kind, tuple):
+            res: dict[str, DType] = {}
+            for k in kind:
+                res.update(self.dtypes(kind=k))
+            return res
+        raise ValueError(f"unsupported kind: {kind!r}")
+
+    def devices(self) -> list[Device]:
+        """
+        The devices supported by NumPy.
+
+        For NumPy, this always returns ``['cpu']``.
+
+        Returns
+        -------
+        devices : list[Device]
+            The devices supported by NumPy.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.devices()
+        ['cpu']
+
+        """
+        return ["cpu"]
+
+
+__all__ = ["__array_namespace_info__"]
+
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/_typing.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..e771c788bbcab3c289304790acb664df0c0b5b5a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/_typing.py
@@ -0,0 +1,30 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Literal, TypeAlias
+
+import numpy as np
+
+Device: TypeAlias = Literal["cpu"]
+
+if TYPE_CHECKING:
+
+    # NumPy 1.x on Python 3.10 fails to parse np.dtype[]
+    DType: TypeAlias = np.dtype[
+        np.bool_
+        | np.integer[Any]
+        | np.float32
+        | np.float64
+        | np.complex64
+        | np.complex128
+    ]
+    Array: TypeAlias = np.ndarray[Any, DType]
+else:
+    DType: TypeAlias = np.dtype
+    Array: TypeAlias = np.ndarray
+
+__all__ = ["Array", "DType", "Device"]
+_all_ignore = ["np"]
+
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/fft.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..06875f00b4312c65f27c6afe62ccee00619e86ff
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/fft.py
@@ -0,0 +1,35 @@
+import numpy as np
+from numpy.fft import __all__ as fft_all
+from numpy.fft import fft2, ifft2, irfft2, rfft2
+
+from .._internal import get_xp
+from ..common import _fft
+
+fft = get_xp(np)(_fft.fft)
+ifft = get_xp(np)(_fft.ifft)
+fftn = get_xp(np)(_fft.fftn)
+ifftn = get_xp(np)(_fft.ifftn)
+rfft = get_xp(np)(_fft.rfft)
+irfft = get_xp(np)(_fft.irfft)
+rfftn = get_xp(np)(_fft.rfftn)
+irfftn = get_xp(np)(_fft.irfftn)
+hfft = get_xp(np)(_fft.hfft)
+ihfft = get_xp(np)(_fft.ihfft)
+fftfreq = get_xp(np)(_fft.fftfreq)
+rfftfreq = get_xp(np)(_fft.rfftfreq)
+fftshift = get_xp(np)(_fft.fftshift)
+ifftshift = get_xp(np)(_fft.ifftshift)
+
+
+__all__ = ["rfft2", "irfft2", "fft2", "ifft2"]
+__all__ += _fft.__all__
+
+
+def __dir__() -> list[str]:
+    return __all__
+
+
+del get_xp
+del np
+del fft_all
+del _fft
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/linalg.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d3e731da3fc037949cc1f4c8f0bff385aef8bdc
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/numpy/linalg.py
@@ -0,0 +1,143 @@
+# pyright: reportAttributeAccessIssue=false
+# pyright: reportUnknownArgumentType=false
+# pyright: reportUnknownMemberType=false
+# pyright: reportUnknownVariableType=false
+
+from __future__ import annotations
+
+import numpy as np
+
+# intersection of `np.linalg.__all__` on numpy 1.22 and 2.2, minus `_linalg.__all__`
+from numpy.linalg import (
+    LinAlgError,
+    cond,
+    det,
+    eig,
+    eigvals,
+    eigvalsh,
+    inv,
+    lstsq,
+    matrix_power,
+    multi_dot,
+    norm,
+    tensorinv,
+    tensorsolve,
+)
+
+from .._internal import get_xp
+from ..common import _linalg
+
+# These functions are in both the main and linalg namespaces
+from ._aliases import matmul, matrix_transpose, tensordot, vecdot  # noqa: F401
+from ._typing import Array
+
+cross = get_xp(np)(_linalg.cross)
+outer = get_xp(np)(_linalg.outer)
+EighResult = _linalg.EighResult
+QRResult = _linalg.QRResult
+SlogdetResult = _linalg.SlogdetResult
+SVDResult = _linalg.SVDResult
+eigh = get_xp(np)(_linalg.eigh)
+qr = get_xp(np)(_linalg.qr)
+slogdet = get_xp(np)(_linalg.slogdet)
+svd = get_xp(np)(_linalg.svd)
+cholesky = get_xp(np)(_linalg.cholesky)
+matrix_rank = get_xp(np)(_linalg.matrix_rank)
+pinv = get_xp(np)(_linalg.pinv)
+matrix_norm = get_xp(np)(_linalg.matrix_norm)
+svdvals = get_xp(np)(_linalg.svdvals)
+diagonal = get_xp(np)(_linalg.diagonal)
+trace = get_xp(np)(_linalg.trace)
+
+# Note: unlike np.linalg.solve, the array API solve() only accepts x2 as a
+# vector when it is exactly 1-dimensional. All other cases treat x2 as a stack
+# of matrices. The np.linalg.solve behavior of allowing stacks of both
+# matrices and vectors is ambiguous c.f.
+# https://github.com/numpy/numpy/issues/15349 and
+# https://github.com/data-apis/array-api/issues/285.
+
+# To workaround this, the below is the code from np.linalg.solve except
+# only calling solve1 in the exactly 1D case.
+
+
+# This code is here instead of in common because it is numpy specific. Also
+# note that CuPy's solve() does not currently support broadcasting (see
+# https://github.com/cupy/cupy/blob/main/cupy/cublas.py#L43).
+def solve(x1: Array, x2: Array, /) -> Array:
+    try:
+        from numpy.linalg._linalg import (
+            _assert_stacked_2d,
+            _assert_stacked_square,
+            _commonType,
+            _makearray,
+            _raise_linalgerror_singular,
+            isComplexType,
+        )
+    except ImportError:
+        from numpy.linalg.linalg import (
+            _assert_stacked_2d,
+            _assert_stacked_square,
+            _commonType,
+            _makearray,
+            _raise_linalgerror_singular,
+            isComplexType,
+        )
+    from numpy.linalg import _umath_linalg
+
+    x1, _ = _makearray(x1)
+    _assert_stacked_2d(x1)
+    _assert_stacked_square(x1)
+    x2, wrap = _makearray(x2)
+    t, result_t = _commonType(x1, x2)
+
+    # This part is different from np.linalg.solve
+    gufunc: np.ufunc
+    if x2.ndim == 1:
+        gufunc = _umath_linalg.solve1
+    else:
+        gufunc = _umath_linalg.solve
+
+    # This does nothing currently but is left in because it will be relevant
+    # when complex dtype support is added to the spec in 2022.
+    signature = "DD->D" if isComplexType(t) else "dd->d"
+    with np.errstate(
+        call=_raise_linalgerror_singular,
+        invalid="call",
+        over="ignore",
+        divide="ignore",
+        under="ignore",
+    ):
+        r: Array = gufunc(x1, x2, signature=signature)
+
+    return wrap(r.astype(result_t, copy=False))
+
+
+# These functions are completely new here. If the library already has them
+# (i.e., numpy 2.0), use the library version instead of our wrapper.
+if hasattr(np.linalg, "vector_norm"):
+    vector_norm = np.linalg.vector_norm
+else:
+    vector_norm = get_xp(np)(_linalg.vector_norm)
+
+
+__all__ = [
+    "LinAlgError",
+    "cond",
+    "det",
+    "eig",
+    "eigvals",
+    "eigvalsh",
+    "inv",
+    "lstsq",
+    "matrix_power",
+    "multi_dot",
+    "norm",
+    "tensorinv",
+    "tensorsolve",
+]
+__all__ += _linalg.__all__
+__all__ += ["solve", "vector_norm"]
+
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/py.typed b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/torch/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/torch/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..69fd19ce83a5672a9ee574fd30599b55adb26cb0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/torch/__init__.py
@@ -0,0 +1,22 @@
+from torch import * # noqa: F403
+
+# Several names are not included in the above import *
+import torch
+for n in dir(torch):
+    if (n.startswith('_')
+        or n.endswith('_')
+        or 'cuda' in n
+        or 'cpu' in n
+        or 'backward' in n):
+        continue
+    exec(f"{n} = torch.{n}")
+del n
+
+# These imports may overwrite names from the import * above.
+from ._aliases import * # noqa: F403
+
+# See the comment in the numpy __init__.py
+__import__(__package__ + '.linalg')
+__import__(__package__ + '.fft')
+
+__array_api_version__ = '2024.12'
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/torch/_aliases.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/torch/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..de5d1a5d40eb5e17e8a935003e02bd2039a33c1a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/torch/_aliases.py
@@ -0,0 +1,855 @@
+from __future__ import annotations
+
+from functools import reduce as _reduce, wraps as _wraps
+from builtins import all as _builtin_all, any as _builtin_any
+from typing import Any, List, Optional, Sequence, Tuple, Union, Literal
+
+import torch
+
+from .._internal import get_xp
+from ..common import _aliases
+from ..common._typing import NestedSequence, SupportsBufferProtocol
+from ._info import __array_namespace_info__
+from ._typing import Array, Device, DType
+
+_int_dtypes = {
+    torch.uint8,
+    torch.int8,
+    torch.int16,
+    torch.int32,
+    torch.int64,
+}
+try:
+    # torch >=2.3
+    _int_dtypes |= {torch.uint16, torch.uint32, torch.uint64}
+except AttributeError:
+    pass
+
+
+_array_api_dtypes = {
+    torch.bool,
+    *_int_dtypes,
+    torch.float32,
+    torch.float64,
+    torch.complex64,
+    torch.complex128,
+}
+
+_promotion_table = {
+    # ints
+    (torch.int8, torch.int16): torch.int16,
+    (torch.int8, torch.int32): torch.int32,
+    (torch.int8, torch.int64): torch.int64,
+    (torch.int16, torch.int32): torch.int32,
+    (torch.int16, torch.int64): torch.int64,
+    (torch.int32, torch.int64): torch.int64,
+    # ints and uints (mixed sign)
+    (torch.uint8, torch.int8): torch.int16,
+    (torch.uint8, torch.int16): torch.int16,
+    (torch.uint8, torch.int32): torch.int32,
+    (torch.uint8, torch.int64): torch.int64,
+    # floats
+    (torch.float32, torch.float64): torch.float64,
+    # complexes
+    (torch.complex64, torch.complex128): torch.complex128,
+    # Mixed float and complex
+    (torch.float32, torch.complex64): torch.complex64,
+    (torch.float32, torch.complex128): torch.complex128,
+    (torch.float64, torch.complex64): torch.complex128,
+    (torch.float64, torch.complex128): torch.complex128,
+}
+
+_promotion_table.update({(b, a): c for (a, b), c in _promotion_table.items()})
+_promotion_table.update({(a, a): a for a in _array_api_dtypes})
+
+
+def _two_arg(f):
+    @_wraps(f)
+    def _f(x1, x2, /, **kwargs):
+        x1, x2 = _fix_promotion(x1, x2)
+        return f(x1, x2, **kwargs)
+    if _f.__doc__ is None:
+        _f.__doc__ = f"""\
+Array API compatibility wrapper for torch.{f.__name__}.
+
+See the corresponding PyTorch documentation and/or the array API specification
+for more details.
+
+"""
+    return _f
+
+def _fix_promotion(x1, x2, only_scalar=True):
+    if not isinstance(x1, torch.Tensor) or not isinstance(x2, torch.Tensor):
+        return x1, x2
+    if x1.dtype not in _array_api_dtypes or x2.dtype not in _array_api_dtypes:
+        return x1, x2
+    # If an argument is 0-D pytorch downcasts the other argument
+    if not only_scalar or x1.shape == ():
+        dtype = result_type(x1, x2)
+        x2 = x2.to(dtype)
+    if not only_scalar or x2.shape == ():
+        dtype = result_type(x1, x2)
+        x1 = x1.to(dtype)
+    return x1, x2
+
+
+_py_scalars = (bool, int, float, complex)
+
+
+def result_type(
+    *arrays_and_dtypes: Array | DType | bool | int | float | complex
+) -> DType:
+    num = len(arrays_and_dtypes)
+
+    if num == 0:
+        raise ValueError("At least one array or dtype must be provided")
+
+    elif num == 1:
+        x = arrays_and_dtypes[0]
+        if isinstance(x, torch.dtype):
+            return x
+        return x.dtype
+
+    if num == 2:
+        x, y = arrays_and_dtypes
+        return _result_type(x, y)
+
+    else:
+        # sort scalars so that they are treated last
+        scalars, others = [], []
+        for x in arrays_and_dtypes:
+            if isinstance(x, _py_scalars):
+                scalars.append(x)
+            else:
+                others.append(x)
+        if not others:
+            raise ValueError("At least one array or dtype must be provided")
+
+        # combine left-to-right
+        return _reduce(_result_type, others + scalars)
+
+
+def _result_type(
+    x: Array | DType | bool | int | float | complex,
+    y: Array | DType | bool | int | float | complex,
+) -> DType:
+    if not (isinstance(x, _py_scalars) or isinstance(y, _py_scalars)):
+        xdt = x if isinstance(x, torch.dtype) else x.dtype
+        ydt = y if isinstance(y, torch.dtype) else y.dtype
+
+        try:
+            return _promotion_table[xdt, ydt]
+        except KeyError:
+            pass
+
+    # This doesn't result_type(dtype, dtype) for non-array API dtypes
+    # because torch.result_type only accepts tensors. This does however, allow
+    # cross-kind promotion.
+    x = torch.tensor([], dtype=x) if isinstance(x, torch.dtype) else x
+    y = torch.tensor([], dtype=y) if isinstance(y, torch.dtype) else y
+    return torch.result_type(x, y)
+
+
+def can_cast(from_: Union[DType, Array], to: DType, /) -> bool:
+    if not isinstance(from_, torch.dtype):
+        from_ = from_.dtype
+    return torch.can_cast(from_, to)
+
+# Basic renames
+bitwise_invert = torch.bitwise_not
+newaxis = None
+# torch.conj sets the conjugation bit, which breaks conversion to other
+# libraries. See https://github.com/data-apis/array-api-compat/issues/173
+conj = torch.conj_physical
+
+# Two-arg elementwise functions
+# These require a wrapper to do the correct type promotion on 0-D tensors
+add = _two_arg(torch.add)
+atan2 = _two_arg(torch.atan2)
+bitwise_and = _two_arg(torch.bitwise_and)
+bitwise_left_shift = _two_arg(torch.bitwise_left_shift)
+bitwise_or = _two_arg(torch.bitwise_or)
+bitwise_right_shift = _two_arg(torch.bitwise_right_shift)
+bitwise_xor = _two_arg(torch.bitwise_xor)
+copysign = _two_arg(torch.copysign)
+divide = _two_arg(torch.divide)
+# Also a rename. torch.equal does not broadcast
+equal = _two_arg(torch.eq)
+floor_divide = _two_arg(torch.floor_divide)
+greater = _two_arg(torch.greater)
+greater_equal = _two_arg(torch.greater_equal)
+hypot = _two_arg(torch.hypot)
+less = _two_arg(torch.less)
+less_equal = _two_arg(torch.less_equal)
+logaddexp = _two_arg(torch.logaddexp)
+# logical functions are not included here because they only accept bool in the
+# spec, so type promotion is irrelevant.
+maximum = _two_arg(torch.maximum)
+minimum = _two_arg(torch.minimum)
+multiply = _two_arg(torch.multiply)
+not_equal = _two_arg(torch.not_equal)
+pow = _two_arg(torch.pow)
+remainder = _two_arg(torch.remainder)
+subtract = _two_arg(torch.subtract)
+
+
+def asarray(
+    obj: (
+    Array 
+        | bool | int | float | complex 
+        | NestedSequence[bool | int | float | complex] 
+        | SupportsBufferProtocol
+    ),
+    /,
+    *,
+    dtype: DType | None = None,
+    device: Device | None = None,
+    copy: bool | None = None,
+    **kwargs: Any,
+) -> Array:
+    # torch.asarray does not respect input->output device propagation
+    # https://github.com/pytorch/pytorch/issues/150199
+    if device is None and isinstance(obj, torch.Tensor):
+        device = obj.device
+    return torch.asarray(obj, dtype=dtype, device=device, copy=copy, **kwargs)
+
+
+# These wrappers are mostly based on the fact that pytorch uses 'dim' instead
+# of 'axis'.
+
+# torch.min and torch.max return a tuple and don't support multiple axes https://github.com/pytorch/pytorch/issues/58745
+def max(x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False) -> Array:
+    # https://github.com/pytorch/pytorch/issues/29137
+    if axis == ():
+        return torch.clone(x)
+    return torch.amax(x, axis, keepdims=keepdims)
+
+def min(x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False) -> Array:
+    # https://github.com/pytorch/pytorch/issues/29137
+    if axis == ():
+        return torch.clone(x)
+    return torch.amin(x, axis, keepdims=keepdims)
+
+clip = get_xp(torch)(_aliases.clip)
+unstack = get_xp(torch)(_aliases.unstack)
+cumulative_sum = get_xp(torch)(_aliases.cumulative_sum)
+cumulative_prod = get_xp(torch)(_aliases.cumulative_prod)
+finfo = get_xp(torch)(_aliases.finfo)
+iinfo = get_xp(torch)(_aliases.iinfo)
+
+
+# torch.sort also returns a tuple
+# https://github.com/pytorch/pytorch/issues/70921
+def sort(x: Array, /, *, axis: int = -1, descending: bool = False, stable: bool = True, **kwargs) -> Array:
+    return torch.sort(x, dim=axis, descending=descending, stable=stable, **kwargs).values
+
+def _normalize_axes(axis, ndim):
+    axes = []
+    if ndim == 0 and axis:
+        # Better error message in this case
+        raise IndexError(f"Dimension out of range: {axis[0]}")
+    lower, upper = -ndim, ndim - 1
+    for a in axis:
+        if a < lower or a > upper:
+            # Match torch error message (e.g., from sum())
+            raise IndexError(f"Dimension out of range (expected to be in range of [{lower}, {upper}], but got {a}")
+        if a < 0:
+            a = a + ndim
+        if a in axes:
+            # Use IndexError instead of RuntimeError, and "axis" instead of "dim"
+            raise IndexError(f"Axis {a} appears multiple times in the list of axes")
+        axes.append(a)
+    return sorted(axes)
+
+def _axis_none_keepdims(x, ndim, keepdims):
+    # Apply keepdims when axis=None
+    # (https://github.com/pytorch/pytorch/issues/71209)
+    # Note that this is only valid for the axis=None case.
+    if keepdims:
+        for i in range(ndim):
+            x = torch.unsqueeze(x, 0)
+    return x
+
+def _reduce_multiple_axes(f, x, axis, keepdims=False, **kwargs):
+    # Some reductions don't support multiple axes
+    # (https://github.com/pytorch/pytorch/issues/56586).
+    axes = _normalize_axes(axis, x.ndim)
+    for a in reversed(axes):
+        x = torch.movedim(x, a, -1)
+    x = torch.flatten(x, -len(axes))
+
+    out = f(x, -1, **kwargs)
+
+    if keepdims:
+        for a in axes:
+            out = torch.unsqueeze(out, a)
+    return out
+
+
+def _sum_prod_no_axis(x: Array, dtype: DType | None) -> Array:
+    """
+    Implements `sum(..., axis=())` and `prod(..., axis=())`.
+    
+    Works around https://github.com/pytorch/pytorch/issues/29137
+    """
+    if dtype is not None:
+        return x.clone() if dtype == x.dtype else x.to(dtype)
+
+    # We can't upcast uint8 according to the spec because there is no
+    # torch.uint64, so at least upcast to int64 which is what prod does
+    # when axis=None.
+    if x.dtype in (torch.uint8, torch.int8, torch.int16, torch.int32):
+        return x.to(torch.int64)
+
+    return x.clone()
+
+
+def prod(x: Array,
+         /,
+         *,
+         axis: Optional[Union[int, Tuple[int, ...]]] = None,
+         dtype: Optional[DType] = None,
+         keepdims: bool = False,
+         **kwargs) -> Array:
+
+    if axis == ():
+        return _sum_prod_no_axis(x, dtype)
+    # torch.prod doesn't support multiple axes
+    # (https://github.com/pytorch/pytorch/issues/56586).
+    if isinstance(axis, tuple):
+        return _reduce_multiple_axes(torch.prod, x, axis, keepdims=keepdims, dtype=dtype, **kwargs)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.prod(x, dtype=dtype, **kwargs)
+        res = _axis_none_keepdims(res, x.ndim, keepdims)
+        return res
+
+    return torch.prod(x, axis, dtype=dtype, keepdims=keepdims, **kwargs)
+
+
+def sum(x: Array,
+         /,
+         *,
+         axis: Optional[Union[int, Tuple[int, ...]]] = None,
+         dtype: Optional[DType] = None,
+         keepdims: bool = False,
+         **kwargs) -> Array:
+
+    if axis == ():
+        return _sum_prod_no_axis(x, dtype)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.sum(x, dtype=dtype, **kwargs)
+        res = _axis_none_keepdims(res, x.ndim, keepdims)
+        return res
+
+    return torch.sum(x, axis, dtype=dtype, keepdims=keepdims, **kwargs)
+
+def any(x: Array,
+        /,
+        *,
+        axis: Optional[Union[int, Tuple[int, ...]]] = None,
+        keepdims: bool = False,
+        **kwargs) -> Array:
+
+    if axis == ():
+        return x.to(torch.bool)
+    # torch.any doesn't support multiple axes
+    # (https://github.com/pytorch/pytorch/issues/56586).
+    if isinstance(axis, tuple):
+        res = _reduce_multiple_axes(torch.any, x, axis, keepdims=keepdims, **kwargs)
+        return res.to(torch.bool)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.any(x, **kwargs)
+        res = _axis_none_keepdims(res, x.ndim, keepdims)
+        return res.to(torch.bool)
+
+    # torch.any doesn't return bool for uint8
+    return torch.any(x, axis, keepdims=keepdims).to(torch.bool)
+
+def all(x: Array,
+        /,
+        *,
+        axis: Optional[Union[int, Tuple[int, ...]]] = None,
+        keepdims: bool = False,
+        **kwargs) -> Array:
+
+    if axis == ():
+        return x.to(torch.bool)
+    # torch.all doesn't support multiple axes
+    # (https://github.com/pytorch/pytorch/issues/56586).
+    if isinstance(axis, tuple):
+        res = _reduce_multiple_axes(torch.all, x, axis, keepdims=keepdims, **kwargs)
+        return res.to(torch.bool)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.all(x, **kwargs)
+        res = _axis_none_keepdims(res, x.ndim, keepdims)
+        return res.to(torch.bool)
+
+    # torch.all doesn't return bool for uint8
+    return torch.all(x, axis, keepdims=keepdims).to(torch.bool)
+
+def mean(x: Array,
+         /,
+         *,
+         axis: Optional[Union[int, Tuple[int, ...]]] = None,
+         keepdims: bool = False,
+         **kwargs) -> Array:
+    # https://github.com/pytorch/pytorch/issues/29137
+    if axis == ():
+        return torch.clone(x)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.mean(x, **kwargs)
+        res = _axis_none_keepdims(res, x.ndim, keepdims)
+        return res
+    return torch.mean(x, axis, keepdims=keepdims, **kwargs)
+
+def std(x: Array,
+        /,
+        *,
+        axis: Optional[Union[int, Tuple[int, ...]]] = None,
+        correction: Union[int, float] = 0.0,
+        keepdims: bool = False,
+        **kwargs) -> Array:
+    # Note, float correction is not supported
+    # https://github.com/pytorch/pytorch/issues/61492. We don't try to
+    # implement it here for now.
+
+    if isinstance(correction, float):
+        _correction = int(correction)
+        if correction != _correction:
+            raise NotImplementedError("float correction in torch std() is not yet supported")
+    else:
+        _correction = correction
+
+    # https://github.com/pytorch/pytorch/issues/29137
+    if axis == ():
+        return torch.zeros_like(x)
+    if isinstance(axis, int):
+        axis = (axis,)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.std(x, tuple(range(x.ndim)), correction=_correction, **kwargs)
+        res = _axis_none_keepdims(res, x.ndim, keepdims)
+        return res
+    return torch.std(x, axis, correction=_correction, keepdims=keepdims, **kwargs)
+
+def var(x: Array,
+        /,
+        *,
+        axis: Optional[Union[int, Tuple[int, ...]]] = None,
+        correction: Union[int, float] = 0.0,
+        keepdims: bool = False,
+        **kwargs) -> Array:
+    # Note, float correction is not supported
+    # https://github.com/pytorch/pytorch/issues/61492. We don't try to
+    # implement it here for now.
+
+    # if isinstance(correction, float):
+    #     correction = int(correction)
+
+    # https://github.com/pytorch/pytorch/issues/29137
+    if axis == ():
+        return torch.zeros_like(x)
+    if isinstance(axis, int):
+        axis = (axis,)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.var(x, tuple(range(x.ndim)), correction=correction, **kwargs)
+        res = _axis_none_keepdims(res, x.ndim, keepdims)
+        return res
+    return torch.var(x, axis, correction=correction, keepdims=keepdims, **kwargs)
+
+# torch.concat doesn't support dim=None
+# https://github.com/pytorch/pytorch/issues/70925
+def concat(arrays: Union[Tuple[Array, ...], List[Array]],
+           /,
+           *,
+           axis: Optional[int] = 0,
+           **kwargs) -> Array:
+    if axis is None:
+        arrays = tuple(ar.flatten() for ar in arrays)
+        axis = 0
+    return torch.concat(arrays, axis, **kwargs)
+
+# torch.squeeze only accepts int dim and doesn't require it
+# https://github.com/pytorch/pytorch/issues/70924. Support for tuple dim was
+# added at https://github.com/pytorch/pytorch/pull/89017.
+def squeeze(x: Array, /, axis: Union[int, Tuple[int, ...]]) -> Array:
+    if isinstance(axis, int):
+        axis = (axis,)
+    for a in axis:
+        if x.shape[a] != 1:
+            raise ValueError("squeezed dimensions must be equal to 1")
+    axes = _normalize_axes(axis, x.ndim)
+    # Remove this once pytorch 1.14 is released with the above PR #89017.
+    sequence = [a - i for i, a in enumerate(axes)]
+    for a in sequence:
+        x = torch.squeeze(x, a)
+    return x
+
+# torch.broadcast_to uses size instead of shape
+def broadcast_to(x: Array, /, shape: Tuple[int, ...], **kwargs) -> Array:
+    return torch.broadcast_to(x, shape, **kwargs)
+
+# torch.permute uses dims instead of axes
+def permute_dims(x: Array, /, axes: Tuple[int, ...]) -> Array:
+    return torch.permute(x, axes)
+
+# The axis parameter doesn't work for flip() and roll()
+# https://github.com/pytorch/pytorch/issues/71210. Also torch.flip() doesn't
+# accept axis=None
+def flip(x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, **kwargs) -> Array:
+    if axis is None:
+        axis = tuple(range(x.ndim))
+    # torch.flip doesn't accept dim as an int but the method does
+    # https://github.com/pytorch/pytorch/issues/18095
+    return x.flip(axis, **kwargs)
+
+def roll(x: Array, /, shift: Union[int, Tuple[int, ...]], *, axis: Optional[Union[int, Tuple[int, ...]]] = None, **kwargs) -> Array:
+    return torch.roll(x, shift, axis, **kwargs)
+
+def nonzero(x: Array, /, **kwargs) -> Tuple[Array, ...]:
+    if x.ndim == 0:
+        raise ValueError("nonzero() does not support zero-dimensional arrays")
+    return torch.nonzero(x, as_tuple=True, **kwargs)
+
+
+# torch uses `dim` instead of `axis`
+def diff(
+    x: Array,
+    /,
+    *,
+    axis: int = -1,
+    n: int = 1,
+    prepend: Optional[Array] = None,
+    append: Optional[Array] = None,
+) -> Array:
+    return torch.diff(x, dim=axis, n=n, prepend=prepend, append=append)
+
+
+# torch uses `dim` instead of `axis`, does not have keepdims
+def count_nonzero(
+    x: Array,
+    /,
+    *,
+    axis: Optional[Union[int, Tuple[int, ...]]] = None,
+    keepdims: bool = False,
+) -> Array:
+    result = torch.count_nonzero(x, dim=axis)
+    if keepdims:
+        if isinstance(axis, int):
+            return result.unsqueeze(axis)
+        elif isinstance(axis, tuple):
+            n_axis = [x.ndim + ax if ax < 0 else ax for ax in axis]
+            sh = [1 if i in n_axis else x.shape[i] for i in range(x.ndim)]
+            return torch.reshape(result, sh)
+        return _axis_none_keepdims(result, x.ndim, keepdims)
+    else:
+        return result
+
+
+# "repeat" is torch.repeat_interleave;  also the dim argument
+def repeat(x: Array, repeats: int | Array, /, *, axis: int | None = None) -> Array:
+    return torch.repeat_interleave(x, repeats, axis)
+
+
+def where(
+    condition: Array, 
+    x1: Array | bool | int | float | complex, 
+    x2: Array | bool | int | float | complex,
+    /,
+) -> Array:
+    x1, x2 = _fix_promotion(x1, x2)
+    return torch.where(condition, x1, x2)
+
+
+# torch.reshape doesn't have the copy keyword
+def reshape(x: Array,
+            /,
+            shape: Tuple[int, ...],
+            *,
+            copy: Optional[bool] = None,
+            **kwargs) -> Array:
+    if copy is not None:
+        raise NotImplementedError("torch.reshape doesn't yet support the copy keyword")
+    return torch.reshape(x, shape, **kwargs)
+
+# torch.arange doesn't support returning empty arrays
+# (https://github.com/pytorch/pytorch/issues/70915), and doesn't support some
+# keyword argument combinations
+# (https://github.com/pytorch/pytorch/issues/70914)
+def arange(start: Union[int, float],
+           /,
+           stop: Optional[Union[int, float]] = None,
+           step: Union[int, float] = 1,
+           *,
+           dtype: Optional[DType] = None,
+           device: Optional[Device] = None,
+           **kwargs) -> Array:
+    if stop is None:
+        start, stop = 0, start
+    if step > 0 and stop <= start or step < 0 and stop >= start:
+        if dtype is None:
+            if _builtin_all(isinstance(i, int) for i in [start, stop, step]):
+                dtype = torch.int64
+            else:
+                dtype = torch.float32
+        return torch.empty(0, dtype=dtype, device=device, **kwargs)
+    return torch.arange(start, stop, step, dtype=dtype, device=device, **kwargs)
+
+# torch.eye does not accept None as a default for the second argument and
+# doesn't support off-diagonals (https://github.com/pytorch/pytorch/issues/70910)
+def eye(n_rows: int,
+        n_cols: Optional[int] = None,
+        /,
+        *,
+        k: int = 0,
+        dtype: Optional[DType] = None,
+        device: Optional[Device] = None,
+        **kwargs) -> Array:
+    if n_cols is None:
+        n_cols = n_rows
+    z = torch.zeros(n_rows, n_cols, dtype=dtype, device=device, **kwargs)
+    if abs(k) <= n_rows + n_cols:
+        z.diagonal(k).fill_(1)
+    return z
+
+# torch.linspace doesn't have the endpoint parameter
+def linspace(start: Union[int, float],
+             stop: Union[int, float],
+             /,
+             num: int,
+             *,
+             dtype: Optional[DType] = None,
+             device: Optional[Device] = None,
+             endpoint: bool = True,
+             **kwargs) -> Array:
+    if not endpoint:
+        return torch.linspace(start, stop, num+1, dtype=dtype, device=device, **kwargs)[:-1]
+    return torch.linspace(start, stop, num, dtype=dtype, device=device, **kwargs)
+
+# torch.full does not accept an int size
+# https://github.com/pytorch/pytorch/issues/70906
+def full(shape: Union[int, Tuple[int, ...]],
+         fill_value: bool | int | float | complex,
+         *,
+         dtype: Optional[DType] = None,
+         device: Optional[Device] = None,
+         **kwargs) -> Array:
+    if isinstance(shape, int):
+        shape = (shape,)
+
+    return torch.full(shape, fill_value, dtype=dtype, device=device, **kwargs)
+
+# ones, zeros, and empty do not accept shape as a keyword argument
+def ones(shape: Union[int, Tuple[int, ...]],
+         *,
+         dtype: Optional[DType] = None,
+         device: Optional[Device] = None,
+         **kwargs) -> Array:
+    return torch.ones(shape, dtype=dtype, device=device, **kwargs)
+
+def zeros(shape: Union[int, Tuple[int, ...]],
+         *,
+         dtype: Optional[DType] = None,
+         device: Optional[Device] = None,
+         **kwargs) -> Array:
+    return torch.zeros(shape, dtype=dtype, device=device, **kwargs)
+
+def empty(shape: Union[int, Tuple[int, ...]],
+         *,
+         dtype: Optional[DType] = None,
+         device: Optional[Device] = None,
+         **kwargs) -> Array:
+    return torch.empty(shape, dtype=dtype, device=device, **kwargs)
+
+# tril and triu do not call the keyword argument k
+
+def tril(x: Array, /, *, k: int = 0) -> Array:
+    return torch.tril(x, k)
+
+def triu(x: Array, /, *, k: int = 0) -> Array:
+    return torch.triu(x, k)
+
+# Functions that aren't in torch https://github.com/pytorch/pytorch/issues/58742
+def expand_dims(x: Array, /, *, axis: int = 0) -> Array:
+    return torch.unsqueeze(x, axis)
+
+
+def astype(
+    x: Array,
+    dtype: DType,
+    /,
+    *,
+    copy: bool = True,
+    device: Optional[Device] = None,
+) -> Array:
+    if device is not None:
+        return x.to(device, dtype=dtype, copy=copy)
+    return x.to(dtype=dtype, copy=copy)
+
+
+def broadcast_arrays(*arrays: Array) -> List[Array]:
+    shape = torch.broadcast_shapes(*[a.shape for a in arrays])
+    return [torch.broadcast_to(a, shape) for a in arrays]
+
+# Note that these named tuples aren't actually part of the standard namespace,
+# but I don't see any issue with exporting the names here regardless.
+from ..common._aliases import (UniqueAllResult, UniqueCountsResult,
+                               UniqueInverseResult)
+
+# https://github.com/pytorch/pytorch/issues/70920
+def unique_all(x: Array) -> UniqueAllResult:
+    # torch.unique doesn't support returning indices.
+    # https://github.com/pytorch/pytorch/issues/36748. The workaround
+    # suggested in that issue doesn't actually function correctly (it relies
+    # on non-deterministic behavior of scatter()).
+    raise NotImplementedError("unique_all() not yet implemented for pytorch (see https://github.com/pytorch/pytorch/issues/36748)")
+
+    # values, inverse_indices, counts = torch.unique(x, return_counts=True, return_inverse=True)
+    # # torch.unique incorrectly gives a 0 count for nan values.
+    # # https://github.com/pytorch/pytorch/issues/94106
+    # counts[torch.isnan(values)] = 1
+    # return UniqueAllResult(values, indices, inverse_indices, counts)
+
+def unique_counts(x: Array) -> UniqueCountsResult:
+    values, counts = torch.unique(x, return_counts=True)
+
+    # torch.unique incorrectly gives a 0 count for nan values.
+    # https://github.com/pytorch/pytorch/issues/94106
+    counts[torch.isnan(values)] = 1
+    return UniqueCountsResult(values, counts)
+
+def unique_inverse(x: Array) -> UniqueInverseResult:
+    values, inverse = torch.unique(x, return_inverse=True)
+    return UniqueInverseResult(values, inverse)
+
+def unique_values(x: Array) -> Array:
+    return torch.unique(x)
+
+def matmul(x1: Array, x2: Array, /, **kwargs) -> Array:
+    # torch.matmul doesn't type promote (but differently from _fix_promotion)
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+    return torch.matmul(x1, x2, **kwargs)
+
+matrix_transpose = get_xp(torch)(_aliases.matrix_transpose)
+_vecdot = get_xp(torch)(_aliases.vecdot)
+
+def vecdot(x1: Array, x2: Array, /, *, axis: int = -1) -> Array:
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+    return _vecdot(x1, x2, axis=axis)
+
+# torch.tensordot uses dims instead of axes
+def tensordot(
+    x1: Array,
+    x2: Array,
+    /,
+    *, 
+    axes: Union[int, Tuple[Sequence[int], Sequence[int]]] = 2, 
+    **kwargs,
+) -> Array:
+    # Note: torch.tensordot fails with integer dtypes when there is only 1
+    # element in the axis (https://github.com/pytorch/pytorch/issues/84530).
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+    return torch.tensordot(x1, x2, dims=axes, **kwargs)
+
+
+def isdtype(
+    dtype: DType, kind: Union[DType, str, Tuple[Union[DType, str], ...]],
+    *, _tuple=True, # Disallow nested tuples
+) -> bool:
+    """
+    Returns a boolean indicating whether a provided dtype is of a specified data type ``kind``.
+
+    Note that outside of this function, this compat library does not yet fully
+    support complex numbers.
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/generated/array_api.isdtype.html
+    for more details
+    """
+    if isinstance(kind, tuple) and _tuple:
+        return _builtin_any(isdtype(dtype, k, _tuple=False) for k in kind)
+    elif isinstance(kind, str):
+        if kind == 'bool':
+            return dtype == torch.bool
+        elif kind == 'signed integer':
+            return dtype in _int_dtypes and dtype.is_signed
+        elif kind == 'unsigned integer':
+            return dtype in _int_dtypes and not dtype.is_signed
+        elif kind == 'integral':
+            return dtype in _int_dtypes
+        elif kind == 'real floating':
+            return dtype.is_floating_point
+        elif kind == 'complex floating':
+            return dtype.is_complex
+        elif kind == 'numeric':
+            return isdtype(dtype, ('integral', 'real floating', 'complex floating'))
+        else:
+            raise ValueError(f"Unrecognized data type kind: {kind!r}")
+    else:
+        return dtype == kind
+
+def take(x: Array, indices: Array, /, *, axis: Optional[int] = None, **kwargs) -> Array:
+    if axis is None:
+        if x.ndim != 1:
+            raise ValueError("axis must be specified when ndim > 1")
+        axis = 0
+    return torch.index_select(x, axis, indices, **kwargs)
+
+
+def take_along_axis(x: Array, indices: Array, /, *, axis: int = -1) -> Array:
+    return torch.take_along_dim(x, indices, dim=axis)
+
+
+def sign(x: Array, /) -> Array:
+    # torch sign() does not support complex numbers and does not propagate
+    # nans. See https://github.com/data-apis/array-api-compat/issues/136
+    if x.dtype.is_complex:
+        out = x/torch.abs(x)
+        # sign(0) = 0 but the above formula would give nan
+        out[x == 0+0j] = 0+0j
+        return out
+    else:
+        out = torch.sign(x)
+        if x.dtype.is_floating_point:
+            out[torch.isnan(x)] = torch.nan
+        return out
+
+
+def meshgrid(*arrays: Array, indexing: Literal['xy', 'ij'] = 'xy') -> List[Array]:
+    # enforce the default of 'xy'
+    # TODO: is the return type a list or a tuple
+    return list(torch.meshgrid(*arrays, indexing='xy'))
+
+
+__all__ = ['__array_namespace_info__', 'asarray', 'result_type', 'can_cast',
+           'permute_dims', 'bitwise_invert', 'newaxis', 'conj', 'add',
+           'atan2', 'bitwise_and', 'bitwise_left_shift', 'bitwise_or',
+           'bitwise_right_shift', 'bitwise_xor', 'copysign', 'count_nonzero',
+           'diff', 'divide',
+           'equal', 'floor_divide', 'greater', 'greater_equal', 'hypot',
+           'less', 'less_equal', 'logaddexp', 'maximum', 'minimum',
+           'multiply', 'not_equal', 'pow', 'remainder', 'subtract', 'max',
+           'min', 'clip', 'unstack', 'cumulative_sum', 'cumulative_prod', 'sort', 'prod', 'sum',
+           'any', 'all', 'mean', 'std', 'var', 'concat', 'squeeze',
+           'broadcast_to', 'flip', 'roll', 'nonzero', 'where', 'reshape',
+           'arange', 'eye', 'linspace', 'full', 'ones', 'zeros', 'empty',
+           'tril', 'triu', 'expand_dims', 'astype', 'broadcast_arrays',
+           'UniqueAllResult', 'UniqueCountsResult', 'UniqueInverseResult',
+           'unique_all', 'unique_counts', 'unique_inverse', 'unique_values',
+           'matmul', 'matrix_transpose', 'vecdot', 'tensordot', 'isdtype',
+           'take', 'take_along_axis', 'sign', 'finfo', 'iinfo', 'repeat', 'meshgrid']
+
+_all_ignore = ['torch', 'get_xp']
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/torch/_info.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/torch/_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..818e5d3702e38281a607e1d4462a0819c8594a1e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/torch/_info.py
@@ -0,0 +1,369 @@
+"""
+Array API Inspection namespace
+
+This is the namespace for inspection functions as defined by the array API
+standard. See
+https://data-apis.org/array-api/latest/API_specification/inspection.html for
+more details.
+
+"""
+import torch
+
+from functools import cache
+
+class __array_namespace_info__:
+    """
+    Get the array API inspection namespace for PyTorch.
+
+    The array API inspection namespace defines the following functions:
+
+    - capabilities()
+    - default_device()
+    - default_dtypes()
+    - dtypes()
+    - devices()
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/inspection.html
+    for more details.
+
+    Returns
+    -------
+    info : ModuleType
+        The array API inspection namespace for PyTorch.
+
+    Examples
+    --------
+    >>> info = xp.__array_namespace_info__()
+    >>> info.default_dtypes()
+    {'real floating': numpy.float64,
+     'complex floating': numpy.complex128,
+     'integral': numpy.int64,
+     'indexing': numpy.int64}
+
+    """
+
+    __module__ = 'torch'
+
+    def capabilities(self):
+        """
+        Return a dictionary of array API library capabilities.
+
+        The resulting dictionary has the following keys:
+
+        - **"boolean indexing"**: boolean indicating whether an array library
+          supports boolean indexing. Always ``True`` for PyTorch.
+
+        - **"data-dependent shapes"**: boolean indicating whether an array
+          library supports data-dependent output shapes. Always ``True`` for
+          PyTorch.
+
+        See
+        https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html
+        for more details.
+
+        See Also
+        --------
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        capabilities : dict
+            A dictionary of array API library capabilities.
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.capabilities()
+        {'boolean indexing': True,
+         'data-dependent shapes': True,
+         'max dimensions': 64}
+
+        """
+        return {
+            "boolean indexing": True,
+            "data-dependent shapes": True,
+            "max dimensions": 64,
+        }
+
+    def default_device(self):
+        """
+        The default device used for new PyTorch arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        device : Device
+            The default device used for new PyTorch arrays.
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.default_device()
+        device(type='cpu')
+
+        Notes
+        -----
+        This method returns the static default device when PyTorch is initialized.
+        However, the *current* device used by creation functions (``empty`` etc.)
+        can be changed at runtime.
+
+        See Also
+        --------
+        https://github.com/data-apis/array-api/issues/835
+        """
+        return torch.device("cpu")
+
+    def default_dtypes(self, *, device=None):
+        """
+        The default data types used for new PyTorch arrays.
+
+        Parameters
+        ----------
+        device : Device, optional
+            The device to get the default data types for.
+            Unused for PyTorch, as all devices use the same default dtypes.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary describing the default data types used for new PyTorch
+            arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.default_dtypes()
+        {'real floating': torch.float32,
+         'complex floating': torch.complex64,
+         'integral': torch.int64,
+         'indexing': torch.int64}
+
+        """
+        # Note: if the default is set to float64, the devices like MPS that
+        # don't support float64 will error. We still return the default_dtype
+        # value here because this error doesn't represent a different default
+        # per-device.
+        default_floating = torch.get_default_dtype()
+        default_complex = torch.complex64 if default_floating == torch.float32 else torch.complex128
+        default_integral = torch.int64
+        return {
+            "real floating": default_floating,
+            "complex floating": default_complex,
+            "integral": default_integral,
+            "indexing": default_integral,
+        }
+
+
+    def _dtypes(self, kind):
+        bool = torch.bool
+        int8 = torch.int8
+        int16 = torch.int16
+        int32 = torch.int32
+        int64 = torch.int64
+        uint8 = torch.uint8
+        # uint16, uint32, and uint64 are present in newer versions of pytorch,
+        # but they aren't generally supported by the array API functions, so
+        # we omit them from this function.
+        float32 = torch.float32
+        float64 = torch.float64
+        complex64 = torch.complex64
+        complex128 = torch.complex128
+
+        if kind is None:
+            return {
+                "bool": bool,
+                "int8": int8,
+                "int16": int16,
+                "int32": int32,
+                "int64": int64,
+                "uint8": uint8,
+                "float32": float32,
+                "float64": float64,
+                "complex64": complex64,
+                "complex128": complex128,
+            }
+        if kind == "bool":
+            return {"bool": bool}
+        if kind == "signed integer":
+            return {
+                "int8": int8,
+                "int16": int16,
+                "int32": int32,
+                "int64": int64,
+            }
+        if kind == "unsigned integer":
+            return {
+                "uint8": uint8,
+            }
+        if kind == "integral":
+            return {
+                "int8": int8,
+                "int16": int16,
+                "int32": int32,
+                "int64": int64,
+                "uint8": uint8,
+            }
+        if kind == "real floating":
+            return {
+                "float32": float32,
+                "float64": float64,
+            }
+        if kind == "complex floating":
+            return {
+                "complex64": complex64,
+                "complex128": complex128,
+            }
+        if kind == "numeric":
+            return {
+                "int8": int8,
+                "int16": int16,
+                "int32": int32,
+                "int64": int64,
+                "uint8": uint8,
+                "float32": float32,
+                "float64": float64,
+                "complex64": complex64,
+                "complex128": complex128,
+            }
+        if isinstance(kind, tuple):
+            res = {}
+            for k in kind:
+                res.update(self.dtypes(kind=k))
+            return res
+        raise ValueError(f"unsupported kind: {kind!r}")
+
+    @cache
+    def dtypes(self, *, device=None, kind=None):
+        """
+        The array API data types supported by PyTorch.
+
+        Note that this function only returns data types that are defined by
+        the array API.
+
+        Parameters
+        ----------
+        device : Device, optional
+            The device to get the data types for.
+            Unused for PyTorch, as all devices use the same dtypes.
+        kind : str or tuple of str, optional
+            The kind of data types to return. If ``None``, all data types are
+            returned. If a string, only data types of that kind are returned.
+            If a tuple, a dictionary containing the union of the given kinds
+            is returned. The following kinds are supported:
+
+            - ``'bool'``: boolean data types (i.e., ``bool``).
+            - ``'signed integer'``: signed integer data types (i.e., ``int8``,
+              ``int16``, ``int32``, ``int64``).
+            - ``'unsigned integer'``: unsigned integer data types (i.e.,
+              ``uint8``, ``uint16``, ``uint32``, ``uint64``).
+            - ``'integral'``: integer data types. Shorthand for ``('signed
+              integer', 'unsigned integer')``.
+            - ``'real floating'``: real-valued floating-point data types
+              (i.e., ``float32``, ``float64``).
+            - ``'complex floating'``: complex floating-point data types (i.e.,
+              ``complex64``, ``complex128``).
+            - ``'numeric'``: numeric data types. Shorthand for ``('integral',
+              'real floating', 'complex floating')``.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary mapping the names of data types to the corresponding
+            PyTorch data types.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.dtypes(kind='signed integer')
+        {'int8': numpy.int8,
+         'int16': numpy.int16,
+         'int32': numpy.int32,
+         'int64': numpy.int64}
+
+        """
+        res = self._dtypes(kind)
+        for k, v in res.copy().items():
+            try:
+                torch.empty((0,), dtype=v, device=device)
+            except:
+                del res[k]
+        return res
+
+    @cache
+    def devices(self):
+        """
+        The devices supported by PyTorch.
+
+        Returns
+        -------
+        devices : list[Device]
+            The devices supported by PyTorch.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.devices()
+        [device(type='cpu'), device(type='mps', index=0), device(type='meta')]
+
+        """
+        # Torch doesn't have a straightforward way to get the list of all
+        # currently supported devices. To do this, we first parse the error
+        # message of torch.device to get the list of all possible types of
+        # device:
+        try:
+            torch.device('notadevice')
+            raise AssertionError("unreachable")  # pragma: nocover
+        except RuntimeError as e:
+            # The error message is something like:
+            # "Expected one of cpu, cuda, ipu, xpu, mkldnn, opengl, opencl, ideep, hip, ve, fpga, ort, xla, lazy, vulkan, mps, meta, hpu, mtia, privateuseone device type at start of device string: notadevice"
+            devices_names = e.args[0].split('Expected one of ')[1].split(' device type')[0].split(', ')
+
+        # Next we need to check for different indices for different devices.
+        # device(device_name, index=index) doesn't actually check if the
+        # device name or index is valid. We have to try to create a tensor
+        # with it (which is why this function is cached).
+        devices = []
+        for device_name in devices_names:
+            i = 0
+            while True:
+                try:
+                    a = torch.empty((0,), device=torch.device(device_name, index=i))
+                    if a.device in devices:
+                        break
+                    devices.append(a.device)
+                except:
+                    break
+                i += 1
+
+        return devices
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/torch/_typing.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/torch/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..52670871563710d326b0a114a7a517bf87098bf0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/torch/_typing.py
@@ -0,0 +1,3 @@
+__all__ = ["Array", "Device", "DType"]
+
+from torch import device as Device, dtype as DType, Tensor as Array
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/torch/fft.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/torch/fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..50e6a0d0a396863568132e5ab2136078ac28649c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/torch/fft.py
@@ -0,0 +1,85 @@
+from __future__ import annotations
+
+from typing import Union, Sequence, Literal
+
+import torch
+import torch.fft
+from torch.fft import * # noqa: F403
+
+from ._typing import Array
+
+# Several torch fft functions do not map axes to dim
+
+def fftn(
+    x: Array,
+    /,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+    **kwargs,
+) -> Array:
+    return torch.fft.fftn(x, s=s, dim=axes, norm=norm, **kwargs)
+
+def ifftn(
+    x: Array,
+    /,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+    **kwargs,
+) -> Array:
+    return torch.fft.ifftn(x, s=s, dim=axes, norm=norm, **kwargs)
+
+def rfftn(
+    x: Array,
+    /,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+    **kwargs,
+) -> Array:
+    return torch.fft.rfftn(x, s=s, dim=axes, norm=norm, **kwargs)
+
+def irfftn(
+    x: Array,
+    /,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+    **kwargs,
+) -> Array:
+    return torch.fft.irfftn(x, s=s, dim=axes, norm=norm, **kwargs)
+
+def fftshift(
+    x: Array,
+    /,
+    *,
+    axes: Union[int, Sequence[int]] = None,
+    **kwargs,
+) -> Array:
+    return torch.fft.fftshift(x, dim=axes, **kwargs)
+
+def ifftshift(
+    x: Array,
+    /,
+    *,
+    axes: Union[int, Sequence[int]] = None,
+    **kwargs,
+) -> Array:
+    return torch.fft.ifftshift(x, dim=axes, **kwargs)
+
+
+__all__ = torch.fft.__all__ + [
+    "fftn",
+    "ifftn",
+    "rfftn",
+    "irfftn",
+    "fftshift",
+    "ifftshift",
+]
+
+_all_ignore = ['torch']
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/torch/linalg.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/torch/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..70d7240500ce41dbd5e2d7d184c7991025592235
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_compat/torch/linalg.py
@@ -0,0 +1,121 @@
+from __future__ import annotations
+
+import torch
+from typing import Optional, Union, Tuple
+
+from torch.linalg import * # noqa: F403
+
+# torch.linalg doesn't define __all__
+# from torch.linalg import __all__ as linalg_all
+from torch import linalg as torch_linalg
+linalg_all = [i for i in dir(torch_linalg) if not i.startswith('_')]
+
+# outer is implemented in torch but aren't in the linalg namespace
+from torch import outer
+from ._aliases import _fix_promotion, sum
+# These functions are in both the main and linalg namespaces
+from ._aliases import matmul, matrix_transpose, tensordot
+from ._typing import Array, DType
+from ..common._typing import JustInt, JustFloat
+
+# Note: torch.linalg.cross does not default to axis=-1 (it defaults to the
+# first axis with size 3), see https://github.com/pytorch/pytorch/issues/58743
+
+# torch.cross also does not support broadcasting when it would add new
+# dimensions https://github.com/pytorch/pytorch/issues/39656
+def cross(x1: Array, x2: Array, /, *, axis: int = -1) -> Array:
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+    if not (-min(x1.ndim, x2.ndim) <= axis < max(x1.ndim, x2.ndim)):
+        raise ValueError(f"axis {axis} out of bounds for cross product of arrays with shapes {x1.shape} and {x2.shape}")
+    if not (x1.shape[axis] == x2.shape[axis] == 3):
+        raise ValueError(f"cross product axis must have size 3, got {x1.shape[axis]} and {x2.shape[axis]}")
+    x1, x2 = torch.broadcast_tensors(x1, x2)
+    return torch_linalg.cross(x1, x2, dim=axis)
+
+def vecdot(x1: Array, x2: Array, /, *, axis: int = -1, **kwargs) -> Array:
+    from ._aliases import isdtype
+
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+
+    # torch.linalg.vecdot incorrectly allows broadcasting along the contracted dimension
+    if x1.shape[axis] != x2.shape[axis]:
+        raise ValueError("x1 and x2 must have the same size along the given axis")
+
+    # torch.linalg.vecdot doesn't support integer dtypes
+    if isdtype(x1.dtype, 'integral') or isdtype(x2.dtype, 'integral'):
+        if kwargs:
+            raise RuntimeError("vecdot kwargs not supported for integral dtypes")
+
+        x1_ = torch.moveaxis(x1, axis, -1)
+        x2_ = torch.moveaxis(x2, axis, -1)
+        x1_, x2_ = torch.broadcast_tensors(x1_, x2_)
+
+        res = x1_[..., None, :] @ x2_[..., None]
+        return res[..., 0, 0]
+    return torch.linalg.vecdot(x1, x2, dim=axis, **kwargs)
+
+def solve(x1: Array, x2: Array, /, **kwargs) -> Array:
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+    # Torch tries to emulate NumPy 1 solve behavior by using batched 1-D solve
+    # whenever
+    # 1. x1.ndim - 1 == x2.ndim
+    # 2. x1.shape[:-1] == x2.shape
+    #
+    # See linalg_solve_is_vector_rhs in
+    # aten/src/ATen/native/LinearAlgebraUtils.h and
+    # TORCH_META_FUNC(_linalg_solve_ex) in
+    # aten/src/ATen/native/BatchLinearAlgebra.cpp in the PyTorch source code.
+    #
+    # The easiest way to work around this is to prepend a size 1 dimension to
+    # x2, since x2 is already one dimension less than x1.
+    #
+    # See https://github.com/pytorch/pytorch/issues/52915
+    if x2.ndim != 1 and x1.ndim - 1 == x2.ndim and x1.shape[:-1] == x2.shape:
+        x2 = x2[None]
+    return torch.linalg.solve(x1, x2, **kwargs)
+
+# torch.trace doesn't support the offset argument and doesn't support stacking
+def trace(x: Array, /, *, offset: int = 0, dtype: Optional[DType] = None) -> Array:
+    # Use our wrapped sum to make sure it does upcasting correctly
+    return sum(torch.diagonal(x, offset=offset, dim1=-2, dim2=-1), axis=-1, dtype=dtype)
+
+def vector_norm(
+    x: Array,
+    /,
+    *,
+    axis: Optional[Union[int, Tuple[int, ...]]] = None,
+    keepdims: bool = False,
+    # JustFloat stands for inf | -inf, which are not valid for Literal
+    ord: JustInt | JustFloat = 2,
+    **kwargs,
+) -> Array:
+    # torch.vector_norm incorrectly treats axis=() the same as axis=None
+    if axis == ():
+        out = kwargs.get('out')
+        if out is None:
+            dtype = None
+            if x.dtype == torch.complex64:
+                dtype = torch.float32
+            elif x.dtype == torch.complex128:
+                dtype = torch.float64
+
+            out = torch.zeros_like(x, dtype=dtype)
+
+        # The norm of a single scalar works out to abs(x) in every case except
+        # for ord=0, which is x != 0.
+        if ord == 0:
+            out[:] = (x != 0)
+        else:
+            out[:] = torch.abs(x)
+        return out
+    return torch.linalg.vector_norm(x, ord=ord, axis=axis, keepdim=keepdims, **kwargs)
+
+__all__ = linalg_all + ['outer', 'matmul', 'matrix_transpose', 'tensordot',
+                        'cross', 'vecdot', 'solve', 'trace', 'vector_norm']
+
+_all_ignore = ['torch_linalg', 'sum']
+
+del linalg_all
+
+def __dir__() -> list[str]:
+    return __all__
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9f21ca0151d2292bcf682ced91ed65657a39231e
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/__pycache__/_delegation.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/__pycache__/_delegation.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3b455a40c31177a9d623572982a225779aa7a039
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/__pycache__/_delegation.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aec07b28f6de266ffd7bb31c6070bf0f283c1739
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/__pycache__/_at.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/__pycache__/_at.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..039f405e91753518687bf8e9e3ce34f9471f96a5
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/__pycache__/_at.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/__pycache__/_backends.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/__pycache__/_backends.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d24e77290863403af5ed95213dc1debfec745037
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/__pycache__/_backends.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/__pycache__/_funcs.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/__pycache__/_funcs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1ae0e4b41df8bec34d2732722c4b3d5be7d32753
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/__pycache__/_funcs.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/__pycache__/_lazy.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/__pycache__/_lazy.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cbe3fd12dd9b2e0e7243c3e8f8a1593d15b077c8
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/__pycache__/_lazy.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_lazy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_lazy.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b45eff91cda48e4e79c9549a6086aa494e698c9
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_lazy.py
@@ -0,0 +1,352 @@
+"""Public API Functions."""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Callable, Sequence
+from functools import partial, wraps
+from types import ModuleType
+from typing import TYPE_CHECKING, Any, ParamSpec, TypeAlias, cast, overload
+
+from ._funcs import broadcast_shapes
+from ._utils import _compat
+from ._utils._compat import (
+    array_namespace,
+    is_dask_namespace,
+    is_jax_namespace,
+)
+from ._utils._helpers import is_python_scalar
+from ._utils._typing import Array, DType
+
+if TYPE_CHECKING:  # pragma: no cover
+    import numpy as np
+    from numpy.typing import ArrayLike
+
+    NumPyObject: TypeAlias = np.ndarray[Any, Any] | np.generic  # type: ignore[explicit-any]
+else:
+    # Sphinx hack
+    NumPyObject = Any
+
+P = ParamSpec("P")
+
+
+@overload
+def lazy_apply(  # type: ignore[decorated-any, valid-type]
+    func: Callable[P, Array | ArrayLike],
+    *args: Array | complex | None,
+    shape: tuple[int | None, ...] | None = None,
+    dtype: DType | None = None,
+    as_numpy: bool = False,
+    xp: ModuleType | None = None,
+    **kwargs: P.kwargs,  # pyright: ignore[reportGeneralTypeIssues]
+) -> Array: ...  # numpydoc ignore=GL08
+
+
+@overload
+def lazy_apply(  # type: ignore[decorated-any, valid-type]
+    func: Callable[P, Sequence[Array | ArrayLike]],
+    *args: Array | complex | None,
+    shape: Sequence[tuple[int | None, ...]],
+    dtype: Sequence[DType] | None = None,
+    as_numpy: bool = False,
+    xp: ModuleType | None = None,
+    **kwargs: P.kwargs,  # pyright: ignore[reportGeneralTypeIssues]
+) -> tuple[Array, ...]: ...  # numpydoc ignore=GL08
+
+
+def lazy_apply(  # type: ignore[valid-type]  # numpydoc ignore=GL07,SA04
+    func: Callable[P, Array | ArrayLike | Sequence[Array | ArrayLike]],
+    *args: Array | complex | None,
+    shape: tuple[int | None, ...] | Sequence[tuple[int | None, ...]] | None = None,
+    dtype: DType | Sequence[DType] | None = None,
+    as_numpy: bool = False,
+    xp: ModuleType | None = None,
+    **kwargs: P.kwargs,  # pyright: ignore[reportGeneralTypeIssues]
+) -> Array | tuple[Array, ...]:
+    """
+    Lazily apply an eager function.
+
+    If the backend of the input arrays is lazy, e.g. Dask or jitted JAX, the execution
+    of the function is delayed until the graph is materialized; if it's eager, the
+    function is executed immediately.
+
+    Parameters
+    ----------
+    func : callable
+        The function to apply.
+
+        It must accept one or more array API compliant arrays as positional arguments.
+        If `as_numpy=True`, inputs are converted to NumPy before they are passed to
+        `func`.
+        It must return either a single array-like or a sequence of array-likes.
+
+        `func` must be a pure function, i.e. without side effects, as depending on the
+        backend it may be executed more than once or never.
+    *args : Array | int | float | complex | bool | None
+        One or more Array API compliant arrays, Python scalars, or None's.
+
+        If `as_numpy=True`, you need to be able to apply :func:`numpy.asarray` to
+        non-None args to convert them to NumPy; read notes below about specific
+        backends.
+    shape : tuple[int | None, ...] | Sequence[tuple[int | None, ...]], optional
+        Output shape or sequence of output shapes, one for each output of `func`.
+        Default: assume single output and broadcast shapes of the input arrays.
+    dtype : DType | Sequence[DType], optional
+        Output dtype or sequence of output dtypes, one for each output of `func`.
+        dtype(s) must belong to the same array namespace as the input arrays.
+        Default: infer the result type(s) from the input arrays.
+    as_numpy : bool, optional
+        If True, convert the input arrays to NumPy before passing them to `func`.
+        This is particularly useful to make NumPy-only functions, e.g. written in Cython
+       or Numba, work transparently with array API-compliant arrays.
+        Default: False.
+    xp : array_namespace, optional
+        The standard-compatible namespace for `args`. Default: infer.
+    **kwargs : Any, optional
+        Additional keyword arguments to pass verbatim to `func`.
+        They cannot contain Array objects.
+
+    Returns
+    -------
+    Array | tuple[Array, ...]
+        The result(s) of `func` applied to the input arrays, wrapped in the same
+        array namespace as the inputs.
+        If shape is omitted or a single `tuple[int | None, ...]`, return a single array.
+        Otherwise, return a tuple of arrays.
+
+    Notes
+    -----
+    JAX
+        This allows applying eager functions to jitted JAX arrays, which are lazy.
+        The function won't be applied until the JAX array is materialized.
+        When running inside ``jax.jit``, `shape` must be fully known, i.e. it cannot
+        contain any `None` elements.
+
+        .. warning::
+
+            `func` must never raise inside ``jax.jit``, as the resulting behavior is
+            undefined.
+
+        Using this with `as_numpy=False` is particularly useful to apply non-jittable
+        JAX functions to arrays on GPU devices.
+        If ``as_numpy=True``, the :doc:`jax:transfer_guard` may prevent arrays on a GPU
+        device from being transferred back to CPU. This is treated as an implicit
+        transfer.
+
+    PyTorch, CuPy
+        If ``as_numpy=True``, these backends raise by default if you attempt to convert
+        arrays on a GPU device to NumPy.
+
+    Sparse
+        If ``as_numpy=True``, by default sparse prevents implicit densification through
+        :func:`numpy.asarray`. `This safety mechanism can be disabled
+        `_.
+
+    Dask
+        This allows applying eager functions to Dask arrays.
+        The Dask graph won't be computed.
+
+        `lazy_apply` doesn't know if `func` reduces along any axes; also, shape
+        changes are non-trivial in chunked Dask arrays. For these reasons, all inputs
+        will be rechunked into a single chunk.
+
+        .. warning::
+
+           The whole operation needs to fit in memory all at once on a single worker.
+
+        The outputs will also be returned as a single chunk and you should consider
+        rechunking them into smaller chunks afterwards.
+
+        If you want to distribute the calculation across multiple workers, you
+        should use :func:`dask.array.map_blocks`, :func:`dask.array.map_overlap`,
+        :func:`dask.array.blockwise`, or a native Dask wrapper instead of
+        `lazy_apply`.
+
+    Dask wrapping around other backends
+        If ``as_numpy=False``, `func` will receive in input eager arrays of the meta
+        namespace, as defined by the ``._meta`` attribute of the input Dask arrays.
+        The outputs of `func` will be wrapped by the meta namespace, and then wrapped
+        again by Dask.
+
+    Raises
+    ------
+    ValueError
+        When ``xp=jax.numpy``, the output `shape` is unknown (it contains ``None`` on
+        one or more axes) and this function was called inside ``jax.jit``.
+    RuntimeError
+        When ``xp=sparse`` and auto-densification is disabled.
+    Exception (backend-specific)
+        When the backend disallows implicit device to host transfers and the input
+        arrays are on a non-CPU device, e.g. on GPU.
+
+    See Also
+    --------
+    jax.transfer_guard
+    jax.pure_callback
+    dask.array.map_blocks
+    dask.array.map_overlap
+    dask.array.blockwise
+    """
+    args_not_none = [arg for arg in args if arg is not None]
+    array_args = [arg for arg in args_not_none if not is_python_scalar(arg)]
+    if not array_args:
+        msg = "Must have at least one argument array"
+        raise ValueError(msg)
+    if xp is None:
+        xp = array_namespace(*args)
+
+    # Normalize and validate shape and dtype
+    shapes: list[tuple[int | None, ...]]
+    dtypes: list[DType]
+    multi_output = False
+
+    if shape is None:
+        shapes = [broadcast_shapes(*(arg.shape for arg in array_args))]
+    elif all(isinstance(s, int | None) for s in shape):
+        # Do not test for shape to be a tuple
+        # https://github.com/data-apis/array-api/issues/891#issuecomment-2637430522
+        shapes = [cast(tuple[int | None, ...], shape)]
+    else:
+        shapes = list(shape)  # type: ignore[arg-type]  # pyright: ignore[reportAssignmentType]
+        multi_output = True
+
+    if dtype is None:
+        dtypes = [xp.result_type(*args_not_none)] * len(shapes)
+    elif multi_output:
+        if not isinstance(dtype, Sequence):
+            msg = "Got multiple shapes but only one dtype"
+            raise ValueError(msg)
+        dtypes = list(dtype)  # pyright: ignore[reportUnknownArgumentType]
+    else:
+        if isinstance(dtype, Sequence):
+            msg = "Got single shape but multiple dtypes"
+            raise ValueError(msg)
+
+        dtypes = [dtype]
+
+    if len(shapes) != len(dtypes):
+        msg = f"Got {len(shapes)} shapes and {len(dtypes)} dtypes"
+        raise ValueError(msg)
+    del shape
+    del dtype
+    # End of shape and dtype parsing
+
+    # Backend-specific branches
+    if is_dask_namespace(xp):
+        import dask
+
+        metas: list[Array] = [arg._meta for arg in array_args]  # pylint: disable=protected-access    # pyright: ignore[reportAttributeAccessIssue]
+        meta_xp = array_namespace(*metas)
+
+        wrapped = dask.delayed(  # type: ignore[attr-defined]  # pyright: ignore[reportPrivateImportUsage]
+            _lazy_apply_wrapper(func, as_numpy, multi_output, meta_xp),
+            pure=True,
+        )
+        # This finalizes each arg, which is the same as arg.rechunk(-1).
+        # Please read docstring above for why we're not using
+        # dask.array.map_blocks or dask.array.blockwise!
+        delayed_out = wrapped(*args, **kwargs)
+
+        out = tuple(
+            xp.from_delayed(
+                delayed_out[i],  # pyright: ignore[reportIndexIssue]
+                # Dask's unknown shapes diverge from the Array API specification
+                shape=tuple(math.nan if s is None else s for s in shape),
+                dtype=dtype,
+                meta=metas[0],
+            )
+            for i, (shape, dtype) in enumerate(zip(shapes, dtypes, strict=True))
+        )
+
+    elif is_jax_namespace(xp) and _is_jax_jit_enabled(xp):
+        # Delay calling func with jax.pure_callback, which will forward to func eager
+        # JAX arrays. Do not use jax.pure_callback when running outside of the JIT,
+        # as it does not support raising exceptions:
+        # https://github.com/jax-ml/jax/issues/26102
+        import jax
+
+        if any(None in shape for shape in shapes):
+            msg = "Output shape must be fully known when running inside jax.jit"
+            raise ValueError(msg)
+
+        # Shield kwargs from being coerced into JAX arrays.
+        # jax.pure_callback calls jax.jit under the hood, but without the chance of
+        # passing static_argnames / static_argnums.
+        wrapped = _lazy_apply_wrapper(
+            partial(func, **kwargs), as_numpy, multi_output, xp
+        )
+
+        # suppress unused-ignore to run mypy in -e lint as well as -e dev
+        out = cast(  # type: ignore[bad-cast,unused-ignore]
+            tuple[Array, ...],
+            jax.pure_callback(
+                wrapped,
+                tuple(
+                    jax.ShapeDtypeStruct(shape, dtype)  # pyright: ignore[reportUnknownArgumentType]
+                    for shape, dtype in zip(shapes, dtypes, strict=True)
+                ),
+                *args,
+            ),
+        )
+
+    else:
+        # Eager backends, including non-jitted JAX
+        wrapped = _lazy_apply_wrapper(func, as_numpy, multi_output, xp)
+        out = wrapped(*args, **kwargs)
+
+    return out if multi_output else out[0]
+
+
+def _is_jax_jit_enabled(xp: ModuleType) -> bool:  # numpydoc ignore=PR01,RT01
+    """Return True if this function is being called inside ``jax.jit``."""
+    import jax  # pylint: disable=import-outside-toplevel
+
+    x = xp.asarray(False)
+    try:
+        return bool(x)
+    except jax.errors.TracerBoolConversionError:
+        return True
+
+
+def _lazy_apply_wrapper(  # type: ignore[explicit-any]  # numpydoc ignore=PR01,RT01
+    func: Callable[..., Array | ArrayLike | Sequence[Array | ArrayLike]],
+    as_numpy: bool,
+    multi_output: bool,
+    xp: ModuleType,
+) -> Callable[..., tuple[Array, ...]]:
+    """
+    Helper of `lazy_apply`.
+
+    Given a function that accepts one or more arrays as positional arguments and returns
+    a single array-like or a sequence of array-likes, return a function that accepts the
+    same number of Array API arrays and always returns a tuple of Array API array.
+
+    Any keyword arguments are passed through verbatim to the wrapped function.
+    """
+
+    # On Dask, @wraps causes the graph key to contain the wrapped function's name
+    @wraps(func)
+    def wrapper(  # type: ignore[decorated-any,explicit-any]
+        *args: Array | complex | None, **kwargs: Any
+    ) -> tuple[Array, ...]:  # numpydoc ignore=GL08
+        args_list = []
+        device = None
+        for arg in args:
+            if arg is not None and not is_python_scalar(arg):
+                if device is None:
+                    device = _compat.device(arg)
+                if as_numpy:
+                    import numpy as np
+
+                    arg = cast(Array, np.asarray(arg))  # type: ignore[bad-cast]  # noqa: PLW2901
+            args_list.append(arg)
+        assert device is not None
+
+        out = func(*args_list, **kwargs)
+
+        if multi_output:
+            assert isinstance(out, Sequence)
+            return tuple(xp.asarray(o, device=device) for o in out)
+        return (xp.asarray(out, device=device),)
+
+    return wrapper
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3628c45f0e0a48ba403abd0ba4a6bec76dc8a9f1
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/__init__.py
@@ -0,0 +1 @@
+"""Modules housing private utility functions."""
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3a9511616c5f707a3ec70c67dd3810566470bf04
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/__pycache__/_compat.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/__pycache__/_compat.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d8ea1ff328c25776c8624b46c1ac6711b0b1346d
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/__pycache__/_compat.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/__pycache__/_helpers.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/__pycache__/_helpers.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..35e33f5274485a03693688d9fa689dc933f81daf
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/__pycache__/_helpers.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/__pycache__/_typing.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/__pycache__/_typing.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cd2e0b737906616ad90a6c66892babcb8494ab2d
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/__pycache__/_typing.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/_compat.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/_compat.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9997450d23b58601323c1def9be7e7e62f8dccd
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/_compat.py
@@ -0,0 +1,70 @@
+"""Acquire helpers from array-api-compat."""
+# Allow packages that vendor both `array-api-extra` and
+# `array-api-compat` to override the import location
+
+try:
+    from ...._array_api_compat_vendor import (
+        array_namespace,
+        device,
+        is_array_api_obj,
+        is_array_api_strict_namespace,
+        is_cupy_array,
+        is_cupy_namespace,
+        is_dask_array,
+        is_dask_namespace,
+        is_jax_array,
+        is_jax_namespace,
+        is_lazy_array,
+        is_numpy_array,
+        is_numpy_namespace,
+        is_pydata_sparse_array,
+        is_pydata_sparse_namespace,
+        is_torch_array,
+        is_torch_namespace,
+        is_writeable_array,
+        size,
+    )
+except ImportError:
+    from array_api_compat import (
+        array_namespace,
+        device,
+        is_array_api_obj,
+        is_array_api_strict_namespace,
+        is_cupy_array,
+        is_cupy_namespace,
+        is_dask_array,
+        is_dask_namespace,
+        is_jax_array,
+        is_jax_namespace,
+        is_lazy_array,
+        is_numpy_array,
+        is_numpy_namespace,
+        is_pydata_sparse_array,
+        is_pydata_sparse_namespace,
+        is_torch_array,
+        is_torch_namespace,
+        is_writeable_array,
+        size,
+    )
+
+__all__ = [
+    "array_namespace",
+    "device",
+    "is_array_api_obj",
+    "is_array_api_strict_namespace",
+    "is_cupy_array",
+    "is_cupy_namespace",
+    "is_dask_array",
+    "is_dask_namespace",
+    "is_jax_array",
+    "is_jax_namespace",
+    "is_lazy_array",
+    "is_numpy_array",
+    "is_numpy_namespace",
+    "is_pydata_sparse_array",
+    "is_pydata_sparse_namespace",
+    "is_torch_array",
+    "is_torch_namespace",
+    "is_writeable_array",
+    "size",
+]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/_compat.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/_compat.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..f40d7556dee87d2107f7b18708f03040bc04a3f2
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/_compat.pyi
@@ -0,0 +1,40 @@
+"""Static type stubs for `_compat.py`."""
+
+# https://github.com/scikit-learn/scikit-learn/pull/27910#issuecomment-2568023972
+from __future__ import annotations
+
+from types import ModuleType
+
+# TODO import from typing (requires Python >=3.13)
+from typing_extensions import TypeIs
+
+from ._typing import Array, Device
+
+# pylint: disable=missing-class-docstring,unused-argument
+
+class Namespace(ModuleType):
+    def device(self, x: Array, /) -> Device: ...
+
+def array_namespace(
+    *xs: Array | complex | None,
+    api_version: str | None = None,
+    use_compat: bool | None = None,
+) -> Namespace: ...
+def device(x: Array, /) -> Device: ...
+def is_array_api_obj(x: object, /) -> TypeIs[Array]: ...
+def is_array_api_strict_namespace(xp: ModuleType, /) -> TypeIs[Namespace]: ...
+def is_cupy_namespace(xp: ModuleType, /) -> TypeIs[Namespace]: ...
+def is_dask_namespace(xp: ModuleType, /) -> TypeIs[Namespace]: ...
+def is_jax_namespace(xp: ModuleType, /) -> TypeIs[Namespace]: ...
+def is_numpy_namespace(xp: ModuleType, /) -> TypeIs[Namespace]: ...
+def is_pydata_sparse_namespace(xp: ModuleType, /) -> TypeIs[Namespace]: ...
+def is_torch_namespace(xp: ModuleType, /) -> TypeIs[Namespace]: ...
+def is_cupy_array(x: object, /) -> TypeIs[Array]: ...
+def is_dask_array(x: object, /) -> TypeIs[Array]: ...
+def is_jax_array(x: object, /) -> TypeIs[Array]: ...
+def is_numpy_array(x: object, /) -> TypeIs[Array]: ...
+def is_pydata_sparse_array(x: object, /) -> TypeIs[Array]: ...
+def is_torch_array(x: object, /) -> TypeIs[Array]: ...
+def is_lazy_array(x: object, /) -> TypeIs[Array]: ...
+def is_writeable_array(x: object, /) -> TypeIs[Array]: ...
+def size(x: Array, /) -> int | None: ...
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/_helpers.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..9882d72e6c0ac1b1660256df0e0656659a908bc4
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/_helpers.py
@@ -0,0 +1,272 @@
+"""Helper functions used by `array_api_extra/_funcs.py`."""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Generator, Iterable
+from types import ModuleType
+from typing import TYPE_CHECKING, cast
+
+from . import _compat
+from ._compat import (
+    array_namespace,
+    is_array_api_obj,
+    is_dask_namespace,
+    is_numpy_array,
+)
+from ._typing import Array
+
+if TYPE_CHECKING:  # pragma: no cover
+    # TODO import from typing (requires Python >=3.13)
+    from typing_extensions import TypeIs
+
+
+__all__ = [
+    "asarrays",
+    "eager_shape",
+    "in1d",
+    "is_python_scalar",
+    "mean",
+    "meta_namespace",
+]
+
+
+def in1d(
+    x1: Array,
+    x2: Array,
+    /,
+    *,
+    assume_unique: bool = False,
+    invert: bool = False,
+    xp: ModuleType | None = None,
+) -> Array:  # numpydoc ignore=PR01,RT01
+    """
+    Check whether each element of an array is also present in a second array.
+
+    Returns a boolean array the same length as `x1` that is True
+    where an element of `x1` is in `x2` and False otherwise.
+
+    This function has been adapted using the original implementation
+    present in numpy:
+    https://github.com/numpy/numpy/blob/v1.26.0/numpy/lib/arraysetops.py#L524-L758
+    """
+    if xp is None:
+        xp = array_namespace(x1, x2)
+
+    x1_shape = eager_shape(x1)
+    x2_shape = eager_shape(x2)
+
+    # This code is run to make the code significantly faster
+    if x2_shape[0] < 10 * x1_shape[0] ** 0.145 and isinstance(x2, Iterable):
+        if invert:
+            mask = xp.ones(x1_shape[0], dtype=xp.bool, device=_compat.device(x1))
+            for a in x2:
+                mask &= x1 != a
+        else:
+            mask = xp.zeros(x1_shape[0], dtype=xp.bool, device=_compat.device(x1))
+            for a in x2:
+                mask |= x1 == a
+        return mask
+
+    rev_idx = xp.empty(0)  # placeholder
+    if not assume_unique:
+        x1, rev_idx = xp.unique_inverse(x1)
+        x2 = xp.unique_values(x2)
+
+    ar = xp.concat((x1, x2))
+    device_ = _compat.device(ar)
+    # We need this to be a stable sort.
+    order = xp.argsort(ar, stable=True)
+    reverse_order = xp.argsort(order, stable=True)
+    sar = xp.take(ar, order, axis=0)
+    ar_size = _compat.size(sar)
+    assert ar_size is not None, "xp.unique*() on lazy backends raises"
+    if ar_size >= 1:
+        bool_ar = sar[1:] != sar[:-1] if invert else sar[1:] == sar[:-1]
+    else:
+        bool_ar = xp.asarray([False]) if invert else xp.asarray([True])
+    flag = xp.concat((bool_ar, xp.asarray([invert], device=device_)))
+    ret = xp.take(flag, reverse_order, axis=0)
+
+    if assume_unique:
+        return ret[: x1.shape[0]]
+    return xp.take(ret, rev_idx, axis=0)
+
+
+def mean(
+    x: Array,
+    /,
+    *,
+    axis: int | tuple[int, ...] | None = None,
+    keepdims: bool = False,
+    xp: ModuleType | None = None,
+) -> Array:  # numpydoc ignore=PR01,RT01
+    """
+    Complex mean, https://github.com/data-apis/array-api/issues/846.
+    """
+    if xp is None:
+        xp = array_namespace(x)
+
+    if xp.isdtype(x.dtype, "complex floating"):
+        x_real = xp.real(x)
+        x_imag = xp.imag(x)
+        mean_real = xp.mean(x_real, axis=axis, keepdims=keepdims)
+        mean_imag = xp.mean(x_imag, axis=axis, keepdims=keepdims)
+        return mean_real + (mean_imag * xp.asarray(1j))
+    return xp.mean(x, axis=axis, keepdims=keepdims)
+
+
+def is_python_scalar(x: object) -> TypeIs[complex]:  # numpydoc ignore=PR01,RT01
+    """Return True if `x` is a Python scalar, False otherwise."""
+    # isinstance(x, float) returns True for np.float64
+    # isinstance(x, complex) returns True for np.complex128
+    # bool is a subclass of int
+    return isinstance(x, int | float | complex) and not is_numpy_array(x)
+
+
+def asarrays(
+    a: Array | complex,
+    b: Array | complex,
+    xp: ModuleType,
+) -> tuple[Array, Array]:
+    """
+    Ensure both `a` and `b` are arrays.
+
+    If `b` is a python scalar, it is converted to the same dtype as `a`, and vice versa.
+
+    Behavior is not specified when mixing a Python ``float`` and an array with an
+    integer data type; this may give ``float32``, ``float64``, or raise an exception.
+    Behavior is implementation-specific.
+
+    Similarly, behavior is not specified when mixing a Python ``complex`` and an array
+    with a real-valued data type; this may give ``complex64``, ``complex128``, or raise
+    an exception. Behavior is implementation-specific.
+
+    Parameters
+    ----------
+    a, b : Array | int | float | complex | bool
+        Input arrays or scalars. At least one must be an array.
+    xp : array_namespace, optional
+        The standard-compatible namespace for `x`. Default: infer.
+
+    Returns
+    -------
+    Array, Array
+        The input arrays, possibly converted to arrays if they were scalars.
+
+    See Also
+    --------
+    mixing-arrays-with-python-scalars : Array API specification for the behavior.
+    """
+    a_scalar = is_python_scalar(a)
+    b_scalar = is_python_scalar(b)
+    if not a_scalar and not b_scalar:
+        # This includes misc. malformed input e.g. str
+        return a, b  # type: ignore[return-value]
+
+    swap = False
+    if a_scalar:
+        swap = True
+        b, a = a, b
+
+    if is_array_api_obj(a):
+        # a is an Array API object
+        # b is a int | float | complex | bool
+        xa = a
+
+        # https://data-apis.org/array-api/draft/API_specification/type_promotion.html#mixing-arrays-with-python-scalars
+        same_dtype = {
+            bool: "bool",
+            int: ("integral", "real floating", "complex floating"),
+            float: ("real floating", "complex floating"),
+            complex: "complex floating",
+        }
+        kind = same_dtype[type(cast(complex, b))]  # type: ignore[index]
+        if xp.isdtype(a.dtype, kind):
+            xb = xp.asarray(b, dtype=a.dtype)
+        else:
+            # Undefined behaviour. Let the function deal with it, if it can.
+            xb = xp.asarray(b)
+
+    else:
+        # Neither a nor b are Array API objects.
+        # Note: we can only reach this point when one explicitly passes
+        # xp=xp to the calling function; otherwise we fail earlier on
+        # array_namespace(a, b).
+        xa, xb = xp.asarray(a), xp.asarray(b)
+
+    return (xb, xa) if swap else (xa, xb)
+
+
+def ndindex(*x: int) -> Generator[tuple[int, ...]]:
+    """
+    Generate all N-dimensional indices for a given array shape.
+
+    Given the shape of an array, an ndindex instance iterates over the N-dimensional
+    index of the array. At each iteration a tuple of indices is returned, the last
+    dimension is iterated over first.
+
+    This has an identical API to numpy.ndindex.
+
+    Parameters
+    ----------
+    *x : int
+        The shape of the array.
+    """
+    if not x:
+        yield ()
+        return
+    for i in ndindex(*x[:-1]):
+        for j in range(x[-1]):
+            yield *i, j
+
+
+def eager_shape(x: Array, /) -> tuple[int, ...]:
+    """
+    Return shape of an array. Raise if shape is not fully defined.
+
+    Parameters
+    ----------
+    x : Array
+        Input array.
+
+    Returns
+    -------
+    tuple[int, ...]
+        Shape of the array.
+    """
+    shape = x.shape
+    # Dask arrays uses non-standard NaN instead of None
+    if any(s is None or math.isnan(s) for s in shape):
+        msg = "Unsupported lazy shape"
+        raise TypeError(msg)
+    return cast(tuple[int, ...], shape)
+
+
+def meta_namespace(
+    *arrays: Array | complex | None, xp: ModuleType | None = None
+) -> ModuleType:
+    """
+    Get the namespace of Dask chunks.
+
+    On all other backends, just return the namespace of the arrays.
+
+    Parameters
+    ----------
+    *arrays : Array | int | float | complex | bool | None
+        Input arrays.
+    xp : array_namespace, optional
+        The standard-compatible namespace for the input arrays. Default: infer.
+
+    Returns
+    -------
+    array_namespace
+        If xp is Dask, the namespace of the Dask chunks;
+        otherwise, the namespace of the arrays.
+    """
+    xp = array_namespace(*arrays) if xp is None else xp
+    if not is_dask_namespace(xp):
+        return xp
+    # Quietly skip scalars and None's
+    metas = [cast(Array | None, getattr(a, "_meta", None)) for a in arrays]
+    return array_namespace(*metas)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/_typing.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..d32a3a07c1ee94d0c3de24b7e93fd8c978b21d58
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/_typing.py
@@ -0,0 +1,10 @@
+# numpydoc ignore=GL08
+# pylint: disable=missing-module-docstring
+
+Array = object
+DType = object
+Device = object
+GetIndex = object
+SetIndex = object
+
+__all__ = ["Array", "DType", "Device", "GetIndex", "SetIndex"]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/_typing.pyi b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/_typing.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..e32a59bd0cb9ed7fa69630587be579dacdc2aa07
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/externals/array_api_extra/_lib/_utils/_typing.pyi
@@ -0,0 +1,105 @@
+"""Static typing helpers."""
+
+from __future__ import annotations
+
+from types import EllipsisType
+from typing import Protocol, TypeAlias
+
+# TODO import from typing (requires Python >=3.12)
+from typing_extensions import override
+
+# TODO: use array-api-typing once it is available
+
+class Array(Protocol):  # pylint: disable=missing-class-docstring
+    # Unary operations
+    def __abs__(self) -> Array: ...
+    def __pos__(self) -> Array: ...
+    def __neg__(self) -> Array: ...
+    def __invert__(self) -> Array: ...
+    # Binary operations
+    def __add__(self, other: Array | complex, /) -> Array: ...
+    def __sub__(self, other: Array | complex, /) -> Array: ...
+    def __mul__(self, other: Array | complex, /) -> Array: ...
+    def __truediv__(self, other: Array | complex, /) -> Array: ...
+    def __floordiv__(self, other: Array | complex, /) -> Array: ...
+    def __mod__(self, other: Array | complex, /) -> Array: ...
+    def __pow__(self, other: Array | complex, /) -> Array: ...
+    def __matmul__(self, other: Array, /) -> Array: ...
+    def __and__(self, other: Array | int, /) -> Array: ...
+    def __or__(self, other: Array | int, /) -> Array: ...
+    def __xor__(self, other: Array | int, /) -> Array: ...
+    def __lshift__(self, other: Array | int, /) -> Array: ...
+    def __rshift__(self, other: Array | int, /) -> Array: ...
+    def __lt__(self, other: Array | complex, /) -> Array: ...
+    def __le__(self, other: Array | complex, /) -> Array: ...
+    def __gt__(self, other: Array | complex, /) -> Array: ...
+    def __ge__(self, other: Array | complex, /) -> Array: ...
+    @override
+    def __eq__(self, other: Array | complex, /) -> Array: ...  # type: ignore[override]  # pyright: ignore[reportIncompatibleMethodOverride]
+    @override
+    def __ne__(self, other: Array | complex, /) -> Array: ...  # type: ignore[override]  # pyright: ignore[reportIncompatibleMethodOverride]
+    # Reflected operations
+    def __radd__(self, other: Array | complex, /) -> Array: ...
+    def __rsub__(self, other: Array | complex, /) -> Array: ...
+    def __rmul__(self, other: Array | complex, /) -> Array: ...
+    def __rtruediv__(self, other: Array | complex, /) -> Array: ...
+    def __rfloordiv__(self, other: Array | complex, /) -> Array: ...
+    def __rmod__(self, other: Array | complex, /) -> Array: ...
+    def __rpow__(self, other: Array | complex, /) -> Array: ...
+    def __rmatmul__(self, other: Array, /) -> Array: ...
+    def __rand__(self, other: Array | int, /) -> Array: ...
+    def __ror__(self, other: Array | int, /) -> Array: ...
+    def __rxor__(self, other: Array | int, /) -> Array: ...
+    def __rlshift__(self, other: Array | int, /) -> Array: ...
+    def __rrshift__(self, other: Array | int, /) -> Array: ...
+    # Attributes
+    @property
+    def dtype(self) -> DType: ...
+    @property
+    def device(self) -> Device: ...
+    @property
+    def mT(self) -> Array: ...  # pylint: disable=invalid-name
+    @property
+    def ndim(self) -> int: ...
+    @property
+    def shape(self) -> tuple[int | None, ...]: ...
+    @property
+    def size(self) -> int | None: ...
+    @property
+    def T(self) -> Array: ...  # pylint: disable=invalid-name
+    # Collection operations (note: an Array does not have to be Sized or Iterable)
+    def __getitem__(self, key: GetIndex, /) -> Array: ...
+    def __setitem__(self, key: SetIndex, value: Array | complex, /) -> None: ...
+    # Materialization methods (may raise on lazy arrays)
+    def __bool__(self) -> bool: ...
+    def __complex__(self) -> complex: ...
+    def __float__(self) -> float: ...
+    def __index__(self) -> int: ...
+    def __int__(self) -> int: ...
+
+    # Misc methods (frequently not implemented in Arrays wrapped by array-api-compat)
+    # def __array_namespace__(*, api_version: str | None) -> ModuleType: ...
+    # def __dlpack__(
+    #     *,
+    #     stream: int | Any | None = None,
+    #     max_version: tuple[int, int] | None = None,
+    #     dl_device: tuple[int, int] | None = None,  # tuple[Enum, int]
+    #     copy: bool | None = None,
+    # ) -> Any: ...
+    # def __dlpack_device__() -> tuple[int, int]: ...  # tuple[Enum, int]
+    # def to_device(device: Device, /, *, stream: int | Any | None = None) -> Array: ...
+
+class DType(Protocol):  # pylint: disable=missing-class-docstring
+    pass
+
+class Device(Protocol):  # pylint: disable=missing-class-docstring
+    pass
+
+SetIndex: TypeAlias = (  # type: ignore[explicit-any]
+    int | slice | EllipsisType | Array | tuple[int | slice | EllipsisType | Array, ...]
+)
+GetIndex: TypeAlias = (  # type: ignore[explicit-any]
+    SetIndex | None | tuple[int | slice | EllipsisType | None | Array, ...]
+)
+
+__all__ = ["Array", "DType", "Device", "GetIndex", "SetIndex"]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0d2dcee909f4741d7ba79093812118dd14459d8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/__init__.py
@@ -0,0 +1,50 @@
+"""Feature selection algorithms.
+
+These include univariate filter selection methods and the recursive feature elimination
+algorithm.
+"""
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+from ._base import SelectorMixin
+from ._from_model import SelectFromModel
+from ._mutual_info import mutual_info_classif, mutual_info_regression
+from ._rfe import RFE, RFECV
+from ._sequential import SequentialFeatureSelector
+from ._univariate_selection import (
+    GenericUnivariateSelect,
+    SelectFdr,
+    SelectFpr,
+    SelectFwe,
+    SelectKBest,
+    SelectPercentile,
+    chi2,
+    f_classif,
+    f_oneway,
+    f_regression,
+    r_regression,
+)
+from ._variance_threshold import VarianceThreshold
+
+__all__ = [
+    "RFE",
+    "RFECV",
+    "GenericUnivariateSelect",
+    "SelectFdr",
+    "SelectFpr",
+    "SelectFromModel",
+    "SelectFwe",
+    "SelectKBest",
+    "SelectPercentile",
+    "SelectorMixin",
+    "SequentialFeatureSelector",
+    "VarianceThreshold",
+    "chi2",
+    "f_classif",
+    "f_oneway",
+    "f_regression",
+    "mutual_info_classif",
+    "mutual_info_regression",
+    "r_regression",
+]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_base.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..56e50e49ca30c6970366b1c7799dcca46deef859
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_base.py
@@ -0,0 +1,267 @@
+"""Generic feature selection mixin"""
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+import warnings
+from abc import ABCMeta, abstractmethod
+from operator import attrgetter
+
+import numpy as np
+from scipy.sparse import csc_matrix, issparse
+
+from ..base import TransformerMixin
+from ..utils import _safe_indexing, check_array, safe_sqr
+from ..utils._set_output import _get_output_config
+from ..utils._tags import get_tags
+from ..utils.validation import (
+    _check_feature_names_in,
+    _is_pandas_df,
+    check_is_fitted,
+    validate_data,
+)
+
+
+class SelectorMixin(TransformerMixin, metaclass=ABCMeta):
+    """
+    Transformer mixin that performs feature selection given a support mask
+
+    This mixin provides a feature selector implementation with `transform` and
+    `inverse_transform` functionality given an implementation of
+    `_get_support_mask`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from sklearn.datasets import load_iris
+    >>> from sklearn.base import BaseEstimator
+    >>> from sklearn.feature_selection import SelectorMixin
+    >>> class FeatureSelector(SelectorMixin, BaseEstimator):
+    ...    def fit(self, X, y=None):
+    ...        self.n_features_in_ = X.shape[1]
+    ...        return self
+    ...    def _get_support_mask(self):
+    ...        mask = np.zeros(self.n_features_in_, dtype=bool)
+    ...        mask[:2] = True  # select the first two features
+    ...        return mask
+    >>> X, y = load_iris(return_X_y=True)
+    >>> FeatureSelector().fit_transform(X, y).shape
+    (150, 2)
+    """
+
+    def get_support(self, indices=False):
+        """
+        Get a mask, or integer index, of the features selected.
+
+        Parameters
+        ----------
+        indices : bool, default=False
+            If True, the return value will be an array of integers, rather
+            than a boolean mask.
+
+        Returns
+        -------
+        support : array
+            An index that selects the retained features from a feature vector.
+            If `indices` is False, this is a boolean array of shape
+            [# input features], in which an element is True iff its
+            corresponding feature is selected for retention. If `indices` is
+            True, this is an integer array of shape [# output features] whose
+            values are indices into the input feature vector.
+        """
+        mask = self._get_support_mask()
+        return mask if not indices else np.nonzero(mask)[0]
+
+    @abstractmethod
+    def _get_support_mask(self):
+        """
+        Get the boolean mask indicating which features are selected
+
+        Returns
+        -------
+        support : boolean array of shape [# input features]
+            An element is True iff its corresponding feature is selected for
+            retention.
+        """
+
+    def transform(self, X):
+        """Reduce X to the selected features.
+
+        Parameters
+        ----------
+        X : array of shape [n_samples, n_features]
+            The input samples.
+
+        Returns
+        -------
+        X_r : array of shape [n_samples, n_selected_features]
+            The input samples with only the selected features.
+        """
+        # Preserve X when X is a dataframe and the output is configured to
+        # be pandas.
+        output_config_dense = _get_output_config("transform", estimator=self)["dense"]
+        preserve_X = output_config_dense != "default" and _is_pandas_df(X)
+
+        # note: we use get_tags instead of __sklearn_tags__ because this is a
+        # public Mixin.
+        X = validate_data(
+            self,
+            X,
+            dtype=None,
+            accept_sparse="csr",
+            ensure_all_finite=not get_tags(self).input_tags.allow_nan,
+            skip_check_array=preserve_X,
+            reset=False,
+        )
+        return self._transform(X)
+
+    def _transform(self, X):
+        """Reduce X to the selected features."""
+        mask = self.get_support()
+        if not mask.any():
+            warnings.warn(
+                (
+                    "No features were selected: either the data is"
+                    " too noisy or the selection test too strict."
+                ),
+                UserWarning,
+            )
+            if hasattr(X, "iloc"):
+                return X.iloc[:, :0]
+            return np.empty(0, dtype=X.dtype).reshape((X.shape[0], 0))
+        return _safe_indexing(X, mask, axis=1)
+
+    def inverse_transform(self, X):
+        """Reverse the transformation operation.
+
+        Parameters
+        ----------
+        X : array of shape [n_samples, n_selected_features]
+            The input samples.
+
+        Returns
+        -------
+        X_original : array of shape [n_samples, n_original_features]
+            `X` with columns of zeros inserted where features would have
+            been removed by :meth:`transform`.
+        """
+        if issparse(X):
+            X = X.tocsc()
+            # insert additional entries in indptr:
+            # e.g. if transform changed indptr from [0 2 6 7] to [0 2 3]
+            # col_nonzeros here will be [2 0 1] so indptr becomes [0 2 2 3]
+            it = self.inverse_transform(np.diff(X.indptr).reshape(1, -1))
+            col_nonzeros = it.ravel()
+            indptr = np.concatenate([[0], np.cumsum(col_nonzeros)])
+            Xt = csc_matrix(
+                (X.data, X.indices, indptr),
+                shape=(X.shape[0], len(indptr) - 1),
+                dtype=X.dtype,
+            )
+            return Xt
+
+        support = self.get_support()
+        X = check_array(X, dtype=None)
+        if support.sum() != X.shape[1]:
+            raise ValueError("X has a different shape than during fitting.")
+
+        if X.ndim == 1:
+            X = X[None, :]
+        Xt = np.zeros((X.shape[0], support.size), dtype=X.dtype)
+        Xt[:, support] = X
+        return Xt
+
+    def get_feature_names_out(self, input_features=None):
+        """Mask feature names according to selected features.
+
+        Parameters
+        ----------
+        input_features : array-like of str or None, default=None
+            Input features.
+
+            - If `input_features` is `None`, then `feature_names_in_` is
+              used as feature names in. If `feature_names_in_` is not defined,
+              then the following input feature names are generated:
+              `["x0", "x1", ..., "x(n_features_in_ - 1)"]`.
+            - If `input_features` is an array-like, then `input_features` must
+              match `feature_names_in_` if `feature_names_in_` is defined.
+
+        Returns
+        -------
+        feature_names_out : ndarray of str objects
+            Transformed feature names.
+        """
+        check_is_fitted(self)
+        input_features = _check_feature_names_in(self, input_features)
+        return input_features[self.get_support()]
+
+
+def _get_feature_importances(estimator, getter, transform_func=None, norm_order=1):
+    """
+    Retrieve and aggregate (ndim > 1)  the feature importances
+    from an estimator. Also optionally applies transformation.
+
+    Parameters
+    ----------
+    estimator : estimator
+        A scikit-learn estimator from which we want to get the feature
+        importances.
+
+    getter : "auto", str or callable
+        An attribute or a callable to get the feature importance. If `"auto"`,
+        `estimator` is expected to expose `coef_` or `feature_importances`.
+
+    transform_func : {"norm", "square"}, default=None
+        The transform to apply to the feature importances. By default (`None`)
+        no transformation is applied.
+
+    norm_order : int, default=1
+        The norm order to apply when `transform_func="norm"`. Only applied
+        when `importances.ndim > 1`.
+
+    Returns
+    -------
+    importances : ndarray of shape (n_features,)
+        The features importances, optionally transformed.
+    """
+    if isinstance(getter, str):
+        if getter == "auto":
+            if hasattr(estimator, "coef_"):
+                getter = attrgetter("coef_")
+            elif hasattr(estimator, "feature_importances_"):
+                getter = attrgetter("feature_importances_")
+            else:
+                raise ValueError(
+                    "when `importance_getter=='auto'`, the underlying "
+                    f"estimator {estimator.__class__.__name__} should have "
+                    "`coef_` or `feature_importances_` attribute. Either "
+                    "pass a fitted estimator to feature selector or call fit "
+                    "before calling transform."
+                )
+        else:
+            getter = attrgetter(getter)
+    elif not callable(getter):
+        raise ValueError("`importance_getter` has to be a string or `callable`")
+
+    importances = getter(estimator)
+
+    if transform_func is None:
+        return importances
+    elif transform_func == "norm":
+        if importances.ndim == 1:
+            importances = np.abs(importances)
+        else:
+            importances = np.linalg.norm(importances, axis=0, ord=norm_order)
+    elif transform_func == "square":
+        if importances.ndim == 1:
+            importances = safe_sqr(importances)
+        else:
+            importances = safe_sqr(importances).sum(axis=0)
+    else:
+        raise ValueError(
+            "Valid values for `transform_func` are "
+            "None, 'norm' and 'square'. Those two "
+            "transformation are only supported now"
+        )
+
+    return importances
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_from_model.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_from_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b2c73c6cbfaeeca449af4b0c04388dbe10be8b7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_from_model.py
@@ -0,0 +1,513 @@
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+from copy import deepcopy
+from numbers import Integral, Real
+
+import numpy as np
+
+from ..base import BaseEstimator, MetaEstimatorMixin, _fit_context, clone
+from ..exceptions import NotFittedError
+from ..utils._param_validation import HasMethods, Interval, Options
+from ..utils._tags import get_tags
+from ..utils.metadata_routing import (
+    MetadataRouter,
+    MethodMapping,
+    _routing_enabled,
+    process_routing,
+)
+from ..utils.metaestimators import available_if
+from ..utils.validation import (
+    _check_feature_names,
+    _estimator_has,
+    _num_features,
+    check_is_fitted,
+    check_scalar,
+)
+from ._base import SelectorMixin, _get_feature_importances
+
+
+def _calculate_threshold(estimator, importances, threshold):
+    """Interpret the threshold value"""
+
+    if threshold is None:
+        # determine default from estimator
+        est_name = estimator.__class__.__name__
+        is_l1_penalized = hasattr(estimator, "penalty") and estimator.penalty == "l1"
+        is_lasso = "Lasso" in est_name
+        is_elasticnet_l1_penalized = est_name == "ElasticNet" and (
+            hasattr(estimator, "l1_ratio") and np.isclose(estimator.l1_ratio, 1.0)
+        )
+        is_elasticnetcv_l1_penalized = est_name == "ElasticNetCV" and (
+            hasattr(estimator, "l1_ratio_") and np.isclose(estimator.l1_ratio_, 1.0)
+        )
+        if (
+            is_l1_penalized
+            or is_lasso
+            or is_elasticnet_l1_penalized
+            or is_elasticnetcv_l1_penalized
+        ):
+            # the natural default threshold is 0 when l1 penalty was used
+            threshold = 1e-5
+        else:
+            threshold = "mean"
+
+    if isinstance(threshold, str):
+        if "*" in threshold:
+            scale, reference = threshold.split("*")
+            scale = float(scale.strip())
+            reference = reference.strip()
+
+            if reference == "median":
+                reference = np.median(importances)
+            elif reference == "mean":
+                reference = np.mean(importances)
+            else:
+                raise ValueError("Unknown reference: " + reference)
+
+            threshold = scale * reference
+
+        elif threshold == "median":
+            threshold = np.median(importances)
+
+        elif threshold == "mean":
+            threshold = np.mean(importances)
+
+        else:
+            raise ValueError(
+                "Expected threshold='mean' or threshold='median' got %s" % threshold
+            )
+
+    else:
+        threshold = float(threshold)
+
+    return threshold
+
+
+class SelectFromModel(MetaEstimatorMixin, SelectorMixin, BaseEstimator):
+    """Meta-transformer for selecting features based on importance weights.
+
+    .. versionadded:: 0.17
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    estimator : object
+        The base estimator from which the transformer is built.
+        This can be both a fitted (if ``prefit`` is set to True)
+        or a non-fitted estimator. The estimator should have a
+        ``feature_importances_`` or ``coef_`` attribute after fitting.
+        Otherwise, the ``importance_getter`` parameter should be used.
+
+    threshold : str or float, default=None
+        The threshold value to use for feature selection. Features whose
+        absolute importance value is greater or equal are kept while the others
+        are discarded. If "median" (resp. "mean"), then the ``threshold`` value
+        is the median (resp. the mean) of the feature importances. A scaling
+        factor (e.g., "1.25*mean") may also be used. If None and if the
+        estimator has a parameter penalty set to l1, either explicitly
+        or implicitly (e.g, Lasso), the threshold used is 1e-5.
+        Otherwise, "mean" is used by default.
+
+    prefit : bool, default=False
+        Whether a prefit model is expected to be passed into the constructor
+        directly or not.
+        If `True`, `estimator` must be a fitted estimator.
+        If `False`, `estimator` is fitted and updated by calling
+        `fit` and `partial_fit`, respectively.
+
+    norm_order : non-zero int, inf, -inf, default=1
+        Order of the norm used to filter the vectors of coefficients below
+        ``threshold`` in the case where the ``coef_`` attribute of the
+        estimator is of dimension 2.
+
+    max_features : int, callable, default=None
+        The maximum number of features to select.
+
+        - If an integer, then it specifies the maximum number of features to
+          allow.
+        - If a callable, then it specifies how to calculate the maximum number of
+          features allowed by using the output of `max_features(X)`.
+        - If `None`, then all features are kept.
+
+        To only select based on ``max_features``, set ``threshold=-np.inf``.
+
+        .. versionadded:: 0.20
+        .. versionchanged:: 1.1
+           `max_features` accepts a callable.
+
+    importance_getter : str or callable, default='auto'
+        If 'auto', uses the feature importance either through a ``coef_``
+        attribute or ``feature_importances_`` attribute of estimator.
+
+        Also accepts a string that specifies an attribute name/path
+        for extracting feature importance (implemented with `attrgetter`).
+        For example, give `regressor_.coef_` in case of
+        :class:`~sklearn.compose.TransformedTargetRegressor`  or
+        `named_steps.clf.feature_importances_` in case of
+        :class:`~sklearn.pipeline.Pipeline` with its last step named `clf`.
+
+        If `callable`, overrides the default feature importance getter.
+        The callable is passed with the fitted estimator and it should
+        return importance for each feature.
+
+        .. versionadded:: 0.24
+
+    Attributes
+    ----------
+    estimator_ : estimator
+        The base estimator from which the transformer is built. This attribute
+        exist only when `fit` has been called.
+
+        - If `prefit=True`, it is a deep copy of `estimator`.
+        - If `prefit=False`, it is a clone of `estimator` and fit on the data
+          passed to `fit` or `partial_fit`.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`. Only defined if the
+        underlying estimator exposes such an attribute when fit.
+
+        .. versionadded:: 0.24
+
+    max_features_ : int
+        Maximum number of features calculated during :term:`fit`. Only defined
+        if the ``max_features`` is not `None`.
+
+        - If `max_features` is an `int`, then `max_features_ = max_features`.
+        - If `max_features` is a callable, then `max_features_ = max_features(X)`.
+
+        .. versionadded:: 1.1
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    threshold_ : float
+        The threshold value used for feature selection.
+
+    See Also
+    --------
+    RFE : Recursive feature elimination based on importance weights.
+    RFECV : Recursive feature elimination with built-in cross-validated
+        selection of the best number of features.
+    SequentialFeatureSelector : Sequential cross-validation based feature
+        selection. Does not rely on importance weights.
+
+    Notes
+    -----
+    Allows NaN/Inf in the input if the underlying estimator does as well.
+
+    Examples
+    --------
+    >>> from sklearn.feature_selection import SelectFromModel
+    >>> from sklearn.linear_model import LogisticRegression
+    >>> X = [[ 0.87, -1.34,  0.31 ],
+    ...      [-2.79, -0.02, -0.85 ],
+    ...      [-1.34, -0.48, -2.55 ],
+    ...      [ 1.92,  1.48,  0.65 ]]
+    >>> y = [0, 1, 0, 1]
+    >>> selector = SelectFromModel(estimator=LogisticRegression()).fit(X, y)
+    >>> selector.estimator_.coef_
+    array([[-0.3252,  0.8345,  0.4976]])
+    >>> selector.threshold_
+    np.float64(0.55249)
+    >>> selector.get_support()
+    array([False,  True, False])
+    >>> selector.transform(X)
+    array([[-1.34],
+           [-0.02],
+           [-0.48],
+           [ 1.48]])
+
+    Using a callable to create a selector that can use no more than half
+    of the input features.
+
+    >>> def half_callable(X):
+    ...     return round(len(X[0]) / 2)
+    >>> half_selector = SelectFromModel(estimator=LogisticRegression(),
+    ...                                 max_features=half_callable)
+    >>> _ = half_selector.fit(X, y)
+    >>> half_selector.max_features_
+    2
+    """
+
+    _parameter_constraints: dict = {
+        "estimator": [HasMethods("fit")],
+        "threshold": [Interval(Real, None, None, closed="both"), str, None],
+        "prefit": ["boolean"],
+        "norm_order": [
+            Interval(Integral, None, -1, closed="right"),
+            Interval(Integral, 1, None, closed="left"),
+            Options(Real, {np.inf, -np.inf}),
+        ],
+        "max_features": [Interval(Integral, 0, None, closed="left"), callable, None],
+        "importance_getter": [str, callable],
+    }
+
+    def __init__(
+        self,
+        estimator,
+        *,
+        threshold=None,
+        prefit=False,
+        norm_order=1,
+        max_features=None,
+        importance_getter="auto",
+    ):
+        self.estimator = estimator
+        self.threshold = threshold
+        self.prefit = prefit
+        self.importance_getter = importance_getter
+        self.norm_order = norm_order
+        self.max_features = max_features
+
+    def _get_support_mask(self):
+        estimator = getattr(self, "estimator_", self.estimator)
+        max_features = getattr(self, "max_features_", self.max_features)
+
+        if self.prefit:
+            try:
+                check_is_fitted(self.estimator)
+            except NotFittedError as exc:
+                raise NotFittedError(
+                    "When `prefit=True`, `estimator` is expected to be a fitted "
+                    "estimator."
+                ) from exc
+        if callable(max_features):
+            # This branch is executed when `transform` is called directly and thus
+            # `max_features_` is not set and we fallback using `self.max_features`
+            # that is not validated
+            raise NotFittedError(
+                "When `prefit=True` and `max_features` is a callable, call `fit` "
+                "before calling `transform`."
+            )
+        elif max_features is not None and not isinstance(max_features, Integral):
+            raise ValueError(
+                f"`max_features` must be an integer. Got `max_features={max_features}` "
+                "instead."
+            )
+
+        scores = _get_feature_importances(
+            estimator=estimator,
+            getter=self.importance_getter,
+            transform_func="norm",
+            norm_order=self.norm_order,
+        )
+        threshold = _calculate_threshold(estimator, scores, self.threshold)
+        if self.max_features is not None:
+            mask = np.zeros_like(scores, dtype=bool)
+            candidate_indices = np.argsort(-scores, kind="mergesort")[:max_features]
+            mask[candidate_indices] = True
+        else:
+            mask = np.ones_like(scores, dtype=bool)
+        mask[scores < threshold] = False
+        return mask
+
+    def _check_max_features(self, X):
+        if self.max_features is not None:
+            n_features = _num_features(X)
+
+            if callable(self.max_features):
+                max_features = self.max_features(X)
+            else:  # int
+                max_features = self.max_features
+
+            check_scalar(
+                max_features,
+                "max_features",
+                Integral,
+                min_val=0,
+                max_val=n_features,
+            )
+            self.max_features_ = max_features
+
+    @_fit_context(
+        # SelectFromModel.estimator is not validated yet
+        prefer_skip_nested_validation=False
+    )
+    def fit(self, X, y=None, **fit_params):
+        """Fit the SelectFromModel meta-transformer.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            The training input samples.
+
+        y : array-like of shape (n_samples,), default=None
+            The target values (integers that correspond to classes in
+            classification, real numbers in regression).
+
+        **fit_params : dict
+            - If `enable_metadata_routing=False` (default): Parameters directly passed
+              to the `fit` method of the sub-estimator. They are ignored if
+              `prefit=True`.
+
+            - If `enable_metadata_routing=True`: Parameters safely routed to the `fit`
+              method of the sub-estimator. They are ignored if `prefit=True`.
+
+            .. versionchanged:: 1.4
+                See :ref:`Metadata Routing User Guide ` for
+                more details.
+
+        Returns
+        -------
+        self : object
+            Fitted estimator.
+        """
+        self._check_max_features(X)
+
+        if self.prefit:
+            try:
+                check_is_fitted(self.estimator)
+            except NotFittedError as exc:
+                raise NotFittedError(
+                    "When `prefit=True`, `estimator` is expected to be a fitted "
+                    "estimator."
+                ) from exc
+            self.estimator_ = deepcopy(self.estimator)
+        else:
+            if _routing_enabled():
+                routed_params = process_routing(self, "fit", **fit_params)
+                self.estimator_ = clone(self.estimator)
+                self.estimator_.fit(X, y, **routed_params.estimator.fit)
+            else:
+                # TODO(SLEP6): remove when metadata routing cannot be disabled.
+                self.estimator_ = clone(self.estimator)
+                self.estimator_.fit(X, y, **fit_params)
+
+        if hasattr(self.estimator_, "feature_names_in_"):
+            self.feature_names_in_ = self.estimator_.feature_names_in_
+        else:
+            _check_feature_names(self, X, reset=True)
+
+        return self
+
+    @property
+    def threshold_(self):
+        """Threshold value used for feature selection."""
+        scores = _get_feature_importances(
+            estimator=self.estimator_,
+            getter=self.importance_getter,
+            transform_func="norm",
+            norm_order=self.norm_order,
+        )
+        return _calculate_threshold(self.estimator, scores, self.threshold)
+
+    @available_if(_estimator_has("partial_fit"))
+    @_fit_context(
+        # SelectFromModel.estimator is not validated yet
+        prefer_skip_nested_validation=False
+    )
+    def partial_fit(self, X, y=None, **partial_fit_params):
+        """Fit the SelectFromModel meta-transformer only once.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            The training input samples.
+
+        y : array-like of shape (n_samples,), default=None
+            The target values (integers that correspond to classes in
+            classification, real numbers in regression).
+
+        **partial_fit_params : dict
+            - If `enable_metadata_routing=False` (default): Parameters directly passed
+              to the `partial_fit` method of the sub-estimator.
+
+            - If `enable_metadata_routing=True`: Parameters passed to the `partial_fit`
+              method of the sub-estimator. They are ignored if `prefit=True`.
+
+            .. versionchanged:: 1.4
+
+                `**partial_fit_params` are routed to the sub-estimator, if
+                `enable_metadata_routing=True` is set via
+                :func:`~sklearn.set_config`, which allows for aliasing.
+
+                See :ref:`Metadata Routing User Guide ` for
+                more details.
+
+        Returns
+        -------
+        self : object
+            Fitted estimator.
+        """
+        first_call = not hasattr(self, "estimator_")
+
+        if first_call:
+            self._check_max_features(X)
+
+        if self.prefit:
+            if first_call:
+                try:
+                    check_is_fitted(self.estimator)
+                except NotFittedError as exc:
+                    raise NotFittedError(
+                        "When `prefit=True`, `estimator` is expected to be a fitted "
+                        "estimator."
+                    ) from exc
+                self.estimator_ = deepcopy(self.estimator)
+            return self
+
+        if first_call:
+            self.estimator_ = clone(self.estimator)
+        if _routing_enabled():
+            routed_params = process_routing(self, "partial_fit", **partial_fit_params)
+            self.estimator_ = clone(self.estimator)
+            self.estimator_.partial_fit(X, y, **routed_params.estimator.partial_fit)
+        else:
+            # TODO(SLEP6): remove when metadata routing cannot be disabled.
+            self.estimator_.partial_fit(X, y, **partial_fit_params)
+
+        if hasattr(self.estimator_, "feature_names_in_"):
+            self.feature_names_in_ = self.estimator_.feature_names_in_
+        else:
+            _check_feature_names(self, X, reset=first_call)
+
+        return self
+
+    @property
+    def n_features_in_(self):
+        """Number of features seen during `fit`."""
+        # For consistency with other estimators we raise a AttributeError so
+        # that hasattr() fails if the estimator isn't fitted.
+        try:
+            check_is_fitted(self)
+        except NotFittedError as nfe:
+            raise AttributeError(
+                "{} object has no n_features_in_ attribute.".format(
+                    self.__class__.__name__
+                )
+            ) from nfe
+
+        return self.estimator_.n_features_in_
+
+    def get_metadata_routing(self):
+        """Get metadata routing of this object.
+
+        Please check :ref:`User Guide ` on how the routing
+        mechanism works.
+
+        .. versionadded:: 1.4
+
+        Returns
+        -------
+        routing : MetadataRouter
+            A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
+            routing information.
+        """
+        router = MetadataRouter(owner=self.__class__.__name__).add(
+            estimator=self.estimator,
+            method_mapping=MethodMapping()
+            .add(caller="partial_fit", callee="partial_fit")
+            .add(caller="fit", callee="fit"),
+        )
+        return router
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.input_tags.sparse = get_tags(self.estimator).input_tags.sparse
+        tags.input_tags.allow_nan = get_tags(self.estimator).input_tags.allow_nan
+        return tags
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_mutual_info.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_mutual_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..aef9097879fcaf02efa50f7c5e3d33f492e14495
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_mutual_info.py
@@ -0,0 +1,580 @@
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+from numbers import Integral
+
+import numpy as np
+from scipy.sparse import issparse
+from scipy.special import digamma
+
+from ..metrics.cluster import mutual_info_score
+from ..neighbors import KDTree, NearestNeighbors
+from ..preprocessing import scale
+from ..utils import check_random_state
+from ..utils._param_validation import Interval, StrOptions, validate_params
+from ..utils.multiclass import check_classification_targets
+from ..utils.parallel import Parallel, delayed
+from ..utils.validation import check_array, check_X_y
+
+
+def _compute_mi_cc(x, y, n_neighbors):
+    """Compute mutual information between two continuous variables.
+
+    Parameters
+    ----------
+    x, y : ndarray, shape (n_samples,)
+        Samples of two continuous random variables, must have an identical
+        shape.
+
+    n_neighbors : int
+        Number of nearest neighbors to search for each point, see [1]_.
+
+    Returns
+    -------
+    mi : float
+        Estimated mutual information in nat units. If it turned out to be
+        negative it is replaced by 0.
+
+    Notes
+    -----
+    True mutual information can't be negative. If its estimate by a numerical
+    method is negative, it means (providing the method is adequate) that the
+    mutual information is close to 0 and replacing it by 0 is a reasonable
+    strategy.
+
+    References
+    ----------
+    .. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
+           information". Phys. Rev. E 69, 2004.
+    """
+    n_samples = x.size
+
+    x = x.reshape((-1, 1))
+    y = y.reshape((-1, 1))
+    xy = np.hstack((x, y))
+
+    # Here we rely on NearestNeighbors to select the fastest algorithm.
+    nn = NearestNeighbors(metric="chebyshev", n_neighbors=n_neighbors)
+
+    nn.fit(xy)
+    radius = nn.kneighbors()[0]
+    radius = np.nextafter(radius[:, -1], 0)
+
+    # KDTree is explicitly fit to allow for the querying of number of
+    # neighbors within a specified radius
+    kd = KDTree(x, metric="chebyshev")
+    nx = kd.query_radius(x, radius, count_only=True, return_distance=False)
+    nx = np.array(nx) - 1.0
+
+    kd = KDTree(y, metric="chebyshev")
+    ny = kd.query_radius(y, radius, count_only=True, return_distance=False)
+    ny = np.array(ny) - 1.0
+
+    mi = (
+        digamma(n_samples)
+        + digamma(n_neighbors)
+        - np.mean(digamma(nx + 1))
+        - np.mean(digamma(ny + 1))
+    )
+
+    return max(0, mi)
+
+
+def _compute_mi_cd(c, d, n_neighbors):
+    """Compute mutual information between continuous and discrete variables.
+
+    Parameters
+    ----------
+    c : ndarray, shape (n_samples,)
+        Samples of a continuous random variable.
+
+    d : ndarray, shape (n_samples,)
+        Samples of a discrete random variable.
+
+    n_neighbors : int
+        Number of nearest neighbors to search for each point, see [1]_.
+
+    Returns
+    -------
+    mi : float
+        Estimated mutual information in nat units. If it turned out to be
+        negative it is replaced by 0.
+
+    Notes
+    -----
+    True mutual information can't be negative. If its estimate by a numerical
+    method is negative, it means (providing the method is adequate) that the
+    mutual information is close to 0 and replacing it by 0 is a reasonable
+    strategy.
+
+    References
+    ----------
+    .. [1] B. C. Ross "Mutual Information between Discrete and Continuous
+       Data Sets". PLoS ONE 9(2), 2014.
+    """
+    n_samples = c.shape[0]
+    c = c.reshape((-1, 1))
+
+    radius = np.empty(n_samples)
+    label_counts = np.empty(n_samples)
+    k_all = np.empty(n_samples)
+    nn = NearestNeighbors()
+    for label in np.unique(d):
+        mask = d == label
+        count = np.sum(mask)
+        if count > 1:
+            k = min(n_neighbors, count - 1)
+            nn.set_params(n_neighbors=k)
+            nn.fit(c[mask])
+            r = nn.kneighbors()[0]
+            radius[mask] = np.nextafter(r[:, -1], 0)
+            k_all[mask] = k
+        label_counts[mask] = count
+
+    # Ignore points with unique labels.
+    mask = label_counts > 1
+    n_samples = np.sum(mask)
+    label_counts = label_counts[mask]
+    k_all = k_all[mask]
+    c = c[mask]
+    radius = radius[mask]
+
+    kd = KDTree(c)
+    m_all = kd.query_radius(c, radius, count_only=True, return_distance=False)
+    m_all = np.array(m_all)
+
+    mi = (
+        digamma(n_samples)
+        + np.mean(digamma(k_all))
+        - np.mean(digamma(label_counts))
+        - np.mean(digamma(m_all))
+    )
+
+    return max(0, mi)
+
+
+def _compute_mi(x, y, x_discrete, y_discrete, n_neighbors=3):
+    """Compute mutual information between two variables.
+
+    This is a simple wrapper which selects a proper function to call based on
+    whether `x` and `y` are discrete or not.
+    """
+    if x_discrete and y_discrete:
+        return mutual_info_score(x, y)
+    elif x_discrete and not y_discrete:
+        return _compute_mi_cd(y, x, n_neighbors)
+    elif not x_discrete and y_discrete:
+        return _compute_mi_cd(x, y, n_neighbors)
+    else:
+        return _compute_mi_cc(x, y, n_neighbors)
+
+
+def _iterate_columns(X, columns=None):
+    """Iterate over columns of a matrix.
+
+    Parameters
+    ----------
+    X : ndarray or csc_matrix, shape (n_samples, n_features)
+        Matrix over which to iterate.
+
+    columns : iterable or None, default=None
+        Indices of columns to iterate over. If None, iterate over all columns.
+
+    Yields
+    ------
+    x : ndarray, shape (n_samples,)
+        Columns of `X` in dense format.
+    """
+    if columns is None:
+        columns = range(X.shape[1])
+
+    if issparse(X):
+        for i in columns:
+            x = np.zeros(X.shape[0])
+            start_ptr, end_ptr = X.indptr[i], X.indptr[i + 1]
+            x[X.indices[start_ptr:end_ptr]] = X.data[start_ptr:end_ptr]
+            yield x
+    else:
+        for i in columns:
+            yield X[:, i]
+
+
+def _estimate_mi(
+    X,
+    y,
+    *,
+    discrete_features="auto",
+    discrete_target=False,
+    n_neighbors=3,
+    copy=True,
+    random_state=None,
+    n_jobs=None,
+):
+    """Estimate mutual information between the features and the target.
+
+    Parameters
+    ----------
+    X : array-like or sparse matrix, shape (n_samples, n_features)
+        Feature matrix.
+
+    y : array-like of shape (n_samples,)
+        Target vector.
+
+    discrete_features : {'auto', bool, array-like}, default='auto'
+        If bool, then determines whether to consider all features discrete
+        or continuous. If array, then it should be either a boolean mask
+        with shape (n_features,) or array with indices of discrete features.
+        If 'auto', it is assigned to False for dense `X` and to True for
+        sparse `X`.
+
+    discrete_target : bool, default=False
+        Whether to consider `y` as a discrete variable.
+
+    n_neighbors : int, default=3
+        Number of neighbors to use for MI estimation for continuous variables,
+        see [1]_ and [2]_. Higher values reduce variance of the estimation, but
+        could introduce a bias.
+
+    copy : bool, default=True
+        Whether to make a copy of the given data. If set to False, the initial
+        data will be overwritten.
+
+    random_state : int, RandomState instance or None, default=None
+        Determines random number generation for adding small noise to
+        continuous variables in order to remove repeated values.
+        Pass an int for reproducible results across multiple function calls.
+        See :term:`Glossary `.
+
+    n_jobs : int, default=None
+        The number of jobs to use for computing the mutual information.
+        The parallelization is done on the columns of `X`.
+        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+        ``-1`` means using all processors. See :term:`Glossary `
+        for more details.
+
+        .. versionadded:: 1.5
+
+
+    Returns
+    -------
+    mi : ndarray, shape (n_features,)
+        Estimated mutual information between each feature and the target in
+        nat units. A negative value will be replaced by 0.
+
+    References
+    ----------
+    .. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
+           information". Phys. Rev. E 69, 2004.
+    .. [2] B. C. Ross "Mutual Information between Discrete and Continuous
+           Data Sets". PLoS ONE 9(2), 2014.
+    """
+    X, y = check_X_y(X, y, accept_sparse="csc", y_numeric=not discrete_target)
+    n_samples, n_features = X.shape
+
+    if isinstance(discrete_features, (str, bool)):
+        if isinstance(discrete_features, str):
+            if discrete_features == "auto":
+                discrete_features = issparse(X)
+            else:
+                raise ValueError("Invalid string value for discrete_features.")
+        discrete_mask = np.empty(n_features, dtype=bool)
+        discrete_mask.fill(discrete_features)
+    else:
+        discrete_features = check_array(discrete_features, ensure_2d=False)
+        if discrete_features.dtype != "bool":
+            discrete_mask = np.zeros(n_features, dtype=bool)
+            discrete_mask[discrete_features] = True
+        else:
+            discrete_mask = discrete_features
+
+    continuous_mask = ~discrete_mask
+    if np.any(continuous_mask) and issparse(X):
+        raise ValueError("Sparse matrix `X` can't have continuous features.")
+
+    rng = check_random_state(random_state)
+    if np.any(continuous_mask):
+        X = X.astype(np.float64, copy=copy)
+        X[:, continuous_mask] = scale(
+            X[:, continuous_mask], with_mean=False, copy=False
+        )
+
+        # Add small noise to continuous features as advised in Kraskov et. al.
+        means = np.maximum(1, np.mean(np.abs(X[:, continuous_mask]), axis=0))
+        X[:, continuous_mask] += (
+            1e-10
+            * means
+            * rng.standard_normal(size=(n_samples, np.sum(continuous_mask)))
+        )
+
+    if not discrete_target:
+        y = scale(y, with_mean=False)
+        y += (
+            1e-10
+            * np.maximum(1, np.mean(np.abs(y)))
+            * rng.standard_normal(size=n_samples)
+        )
+
+    mi = Parallel(n_jobs=n_jobs)(
+        delayed(_compute_mi)(x, y, discrete_feature, discrete_target, n_neighbors)
+        for x, discrete_feature in zip(_iterate_columns(X), discrete_mask)
+    )
+
+    return np.array(mi)
+
+
+@validate_params(
+    {
+        "X": ["array-like", "sparse matrix"],
+        "y": ["array-like"],
+        "discrete_features": [StrOptions({"auto"}), "boolean", "array-like"],
+        "n_neighbors": [Interval(Integral, 1, None, closed="left")],
+        "copy": ["boolean"],
+        "random_state": ["random_state"],
+        "n_jobs": [Integral, None],
+    },
+    prefer_skip_nested_validation=True,
+)
+def mutual_info_regression(
+    X,
+    y,
+    *,
+    discrete_features="auto",
+    n_neighbors=3,
+    copy=True,
+    random_state=None,
+    n_jobs=None,
+):
+    """Estimate mutual information for a continuous target variable.
+
+    Mutual information (MI) [1]_ between two random variables is a non-negative
+    value, which measures the dependency between the variables. It is equal
+    to zero if and only if two random variables are independent, and higher
+    values mean higher dependency.
+
+    The function relies on nonparametric methods based on entropy estimation
+    from k-nearest neighbors distances as described in [2]_ and [3]_. Both
+    methods are based on the idea originally proposed in [4]_.
+
+    It can be used for univariate features selection, read more in the
+    :ref:`User Guide `.
+
+    Parameters
+    ----------
+    X : array-like or sparse matrix, shape (n_samples, n_features)
+        Feature matrix.
+
+    y : array-like of shape (n_samples,)
+        Target vector.
+
+    discrete_features : {'auto', bool, array-like}, default='auto'
+        If bool, then determines whether to consider all features discrete
+        or continuous. If array, then it should be either a boolean mask
+        with shape (n_features,) or array with indices of discrete features.
+        If 'auto', it is assigned to False for dense `X` and to True for
+        sparse `X`.
+
+    n_neighbors : int, default=3
+        Number of neighbors to use for MI estimation for continuous variables,
+        see [2]_ and [3]_. Higher values reduce variance of the estimation, but
+        could introduce a bias.
+
+    copy : bool, default=True
+        Whether to make a copy of the given data. If set to False, the initial
+        data will be overwritten.
+
+    random_state : int, RandomState instance or None, default=None
+        Determines random number generation for adding small noise to
+        continuous variables in order to remove repeated values.
+        Pass an int for reproducible results across multiple function calls.
+        See :term:`Glossary `.
+
+    n_jobs : int, default=None
+        The number of jobs to use for computing the mutual information.
+        The parallelization is done on the columns of `X`.
+
+        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+        ``-1`` means using all processors. See :term:`Glossary `
+        for more details.
+
+        .. versionadded:: 1.5
+
+    Returns
+    -------
+    mi : ndarray, shape (n_features,)
+        Estimated mutual information between each feature and the target in
+        nat units.
+
+    Notes
+    -----
+    1. The term "discrete features" is used instead of naming them
+       "categorical", because it describes the essence more accurately.
+       For example, pixel intensities of an image are discrete features
+       (but hardly categorical) and you will get better results if mark them
+       as such. Also note, that treating a continuous variable as discrete and
+       vice versa will usually give incorrect results, so be attentive about
+       that.
+    2. True mutual information can't be negative. If its estimate turns out
+       to be negative, it is replaced by zero.
+
+    References
+    ----------
+    .. [1] `Mutual Information
+           `_
+           on Wikipedia.
+    .. [2] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
+           information". Phys. Rev. E 69, 2004.
+    .. [3] B. C. Ross "Mutual Information between Discrete and Continuous
+           Data Sets". PLoS ONE 9(2), 2014.
+    .. [4] L. F. Kozachenko, N. N. Leonenko, "Sample Estimate of the Entropy
+           of a Random Vector", Probl. Peredachi Inf., 23:2 (1987), 9-16
+
+    Examples
+    --------
+    >>> from sklearn.datasets import make_regression
+    >>> from sklearn.feature_selection import mutual_info_regression
+    >>> X, y = make_regression(
+    ...     n_samples=50, n_features=3, n_informative=1, noise=1e-4, random_state=42
+    ... )
+    >>> mutual_info_regression(X, y)
+    array([0.117, 2.645, 0.0287])
+    """
+    return _estimate_mi(
+        X,
+        y,
+        discrete_features=discrete_features,
+        discrete_target=False,
+        n_neighbors=n_neighbors,
+        copy=copy,
+        random_state=random_state,
+        n_jobs=n_jobs,
+    )
+
+
+@validate_params(
+    {
+        "X": ["array-like", "sparse matrix"],
+        "y": ["array-like"],
+        "discrete_features": [StrOptions({"auto"}), "boolean", "array-like"],
+        "n_neighbors": [Interval(Integral, 1, None, closed="left")],
+        "copy": ["boolean"],
+        "random_state": ["random_state"],
+        "n_jobs": [Integral, None],
+    },
+    prefer_skip_nested_validation=True,
+)
+def mutual_info_classif(
+    X,
+    y,
+    *,
+    discrete_features="auto",
+    n_neighbors=3,
+    copy=True,
+    random_state=None,
+    n_jobs=None,
+):
+    """Estimate mutual information for a discrete target variable.
+
+    Mutual information (MI) [1]_ between two random variables is a non-negative
+    value, which measures the dependency between the variables. It is equal
+    to zero if and only if two random variables are independent, and higher
+    values mean higher dependency.
+
+    The function relies on nonparametric methods based on entropy estimation
+    from k-nearest neighbors distances as described in [2]_ and [3]_. Both
+    methods are based on the idea originally proposed in [4]_.
+
+    It can be used for univariate features selection, read more in the
+    :ref:`User Guide `.
+
+    Parameters
+    ----------
+    X : {array-like, sparse matrix} of shape (n_samples, n_features)
+        Feature matrix.
+
+    y : array-like of shape (n_samples,)
+        Target vector.
+
+    discrete_features : 'auto', bool or array-like, default='auto'
+        If bool, then determines whether to consider all features discrete
+        or continuous. If array, then it should be either a boolean mask
+        with shape (n_features,) or array with indices of discrete features.
+        If 'auto', it is assigned to False for dense `X` and to True for
+        sparse `X`.
+
+    n_neighbors : int, default=3
+        Number of neighbors to use for MI estimation for continuous variables,
+        see [2]_ and [3]_. Higher values reduce variance of the estimation, but
+        could introduce a bias.
+
+    copy : bool, default=True
+        Whether to make a copy of the given data. If set to False, the initial
+        data will be overwritten.
+
+    random_state : int, RandomState instance or None, default=None
+        Determines random number generation for adding small noise to
+        continuous variables in order to remove repeated values.
+        Pass an int for reproducible results across multiple function calls.
+        See :term:`Glossary `.
+
+    n_jobs : int, default=None
+        The number of jobs to use for computing the mutual information.
+        The parallelization is done on the columns of `X`.
+        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+        ``-1`` means using all processors. See :term:`Glossary `
+        for more details.
+
+        .. versionadded:: 1.5
+
+    Returns
+    -------
+    mi : ndarray, shape (n_features,)
+        Estimated mutual information between each feature and the target in
+        nat units.
+
+    Notes
+    -----
+    1. The term "discrete features" is used instead of naming them
+       "categorical", because it describes the essence more accurately.
+       For example, pixel intensities of an image are discrete features
+       (but hardly categorical) and you will get better results if mark them
+       as such. Also note, that treating a continuous variable as discrete and
+       vice versa will usually give incorrect results, so be attentive about
+       that.
+    2. True mutual information can't be negative. If its estimate turns out
+       to be negative, it is replaced by zero.
+
+    References
+    ----------
+    .. [1] `Mutual Information
+           `_
+           on Wikipedia.
+    .. [2] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
+           information". Phys. Rev. E 69, 2004.
+    .. [3] B. C. Ross "Mutual Information between Discrete and Continuous
+           Data Sets". PLoS ONE 9(2), 2014.
+    .. [4] L. F. Kozachenko, N. N. Leonenko, "Sample Estimate of the Entropy
+           of a Random Vector:, Probl. Peredachi Inf., 23:2 (1987), 9-16
+
+    Examples
+    --------
+    >>> from sklearn.datasets import make_classification
+    >>> from sklearn.feature_selection import mutual_info_classif
+    >>> X, y = make_classification(
+    ...     n_samples=100, n_features=10, n_informative=2, n_clusters_per_class=1,
+    ...     shuffle=False, random_state=42
+    ... )
+    >>> mutual_info_classif(X, y)
+    array([0.589, 0.107, 0.196, 0.0968 , 0.,
+           0.   , 0.   , 0.   , 0.     , 0.])
+    """
+    check_classification_targets(y)
+    return _estimate_mi(
+        X,
+        y,
+        discrete_features=discrete_features,
+        discrete_target=True,
+        n_neighbors=n_neighbors,
+        copy=copy,
+        random_state=random_state,
+        n_jobs=n_jobs,
+    )
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_rfe.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_rfe.py
new file mode 100644
index 0000000000000000000000000000000000000000..d647ad0ca19b10d36bcf4bb9f5ccf698f506f24b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_rfe.py
@@ -0,0 +1,1025 @@
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Recursive feature elimination for feature ranking"""
+
+import warnings
+from copy import deepcopy
+from numbers import Integral
+
+import numpy as np
+from joblib import effective_n_jobs
+
+from ..base import BaseEstimator, MetaEstimatorMixin, _fit_context, clone, is_classifier
+from ..metrics import get_scorer
+from ..model_selection import check_cv
+from ..model_selection._validation import _score
+from ..utils import Bunch, metadata_routing
+from ..utils._metadata_requests import (
+    MetadataRouter,
+    MethodMapping,
+    _raise_for_params,
+    _routing_enabled,
+    process_routing,
+)
+from ..utils._param_validation import HasMethods, Interval, RealNotInt
+from ..utils._tags import get_tags
+from ..utils.metaestimators import _safe_split, available_if
+from ..utils.parallel import Parallel, delayed
+from ..utils.validation import (
+    _check_method_params,
+    _deprecate_positional_args,
+    _estimator_has,
+    check_is_fitted,
+    validate_data,
+)
+from ._base import SelectorMixin, _get_feature_importances
+
+
+def _rfe_single_fit(rfe, estimator, X, y, train, test, scorer, routed_params):
+    """
+    Return the score and n_features per step for a fit across one fold.
+    """
+    X_train, y_train = _safe_split(estimator, X, y, train)
+    X_test, y_test = _safe_split(estimator, X, y, test, train)
+    fit_params = _check_method_params(
+        X, params=routed_params.estimator.fit, indices=train
+    )
+    score_params = _check_method_params(
+        X=X, params=routed_params.scorer.score, indices=test
+    )
+
+    rfe._fit(
+        X_train,
+        y_train,
+        lambda estimator, features: _score(
+            estimator,
+            X_test[:, features],
+            y_test,
+            scorer,
+            score_params=score_params,
+        ),
+        **fit_params,
+    )
+
+    return rfe.step_scores_, rfe.step_support_, rfe.step_ranking_, rfe.step_n_features_
+
+
+class RFE(SelectorMixin, MetaEstimatorMixin, BaseEstimator):
+    """Feature ranking with recursive feature elimination.
+
+    Given an external estimator that assigns weights to features (e.g., the
+    coefficients of a linear model), the goal of recursive feature elimination
+    (RFE) is to select features by recursively considering smaller and smaller
+    sets of features. First, the estimator is trained on the initial set of
+    features and the importance of each feature is obtained either through
+    any specific attribute or callable.
+    Then, the least important features are pruned from current set of features.
+    That procedure is recursively repeated on the pruned set until the desired
+    number of features to select is eventually reached.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    estimator : ``Estimator`` instance
+        A supervised learning estimator with a ``fit`` method that provides
+        information about feature importance
+        (e.g. `coef_`, `feature_importances_`).
+
+    n_features_to_select : int or float, default=None
+        The number of features to select. If `None`, half of the features are
+        selected. If integer, the parameter is the absolute number of features
+        to select. If float between 0 and 1, it is the fraction of features to
+        select.
+
+        .. versionchanged:: 0.24
+           Added float values for fractions.
+
+    step : int or float, default=1
+        If greater than or equal to 1, then ``step`` corresponds to the
+        (integer) number of features to remove at each iteration.
+        If within (0.0, 1.0), then ``step`` corresponds to the percentage
+        (rounded down) of features to remove at each iteration.
+
+    verbose : int, default=0
+        Controls verbosity of output.
+
+    importance_getter : str or callable, default='auto'
+        If 'auto', uses the feature importance either through a `coef_`
+        or `feature_importances_` attributes of estimator.
+
+        Also accepts a string that specifies an attribute name/path
+        for extracting feature importance (implemented with `attrgetter`).
+        For example, give `regressor_.coef_` in case of
+        :class:`~sklearn.compose.TransformedTargetRegressor`  or
+        `named_steps.clf.feature_importances_` in case of
+        class:`~sklearn.pipeline.Pipeline` with its last step named `clf`.
+
+        If `callable`, overrides the default feature importance getter.
+        The callable is passed with the fitted estimator and it should
+        return importance for each feature.
+
+        .. versionadded:: 0.24
+
+    Attributes
+    ----------
+    classes_ : ndarray of shape (n_classes,)
+        The classes labels. Only available when `estimator` is a classifier.
+
+    estimator_ : ``Estimator`` instance
+        The fitted estimator used to select features.
+
+    n_features_ : int
+        The number of selected features.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`. Only defined if the
+        underlying estimator exposes such an attribute when fit.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    ranking_ : ndarray of shape (n_features,)
+        The feature ranking, such that ``ranking_[i]`` corresponds to the
+        ranking position of the i-th feature. Selected (i.e., estimated
+        best) features are assigned rank 1.
+
+    support_ : ndarray of shape (n_features,)
+        The mask of selected features.
+
+    See Also
+    --------
+    RFECV : Recursive feature elimination with built-in cross-validated
+        selection of the best number of features.
+    SelectFromModel : Feature selection based on thresholds of importance
+        weights.
+    SequentialFeatureSelector : Sequential cross-validation based feature
+        selection. Does not rely on importance weights.
+
+    Notes
+    -----
+    Allows NaN/Inf in the input if the underlying estimator does as well.
+
+    References
+    ----------
+
+    .. [1] Guyon, I., Weston, J., Barnhill, S., & Vapnik, V., "Gene selection
+           for cancer classification using support vector machines",
+           Mach. Learn., 46(1-3), 389--422, 2002.
+
+    Examples
+    --------
+    The following example shows how to retrieve the 5 most informative
+    features in the Friedman #1 dataset.
+
+    >>> from sklearn.datasets import make_friedman1
+    >>> from sklearn.feature_selection import RFE
+    >>> from sklearn.svm import SVR
+    >>> X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)
+    >>> estimator = SVR(kernel="linear")
+    >>> selector = RFE(estimator, n_features_to_select=5, step=1)
+    >>> selector = selector.fit(X, y)
+    >>> selector.support_
+    array([ True,  True,  True,  True,  True, False, False, False, False,
+           False])
+    >>> selector.ranking_
+    array([1, 1, 1, 1, 1, 6, 4, 3, 2, 5])
+    """
+
+    _parameter_constraints: dict = {
+        "estimator": [HasMethods(["fit"])],
+        "n_features_to_select": [
+            None,
+            Interval(RealNotInt, 0, 1, closed="right"),
+            Interval(Integral, 0, None, closed="neither"),
+        ],
+        "step": [
+            Interval(Integral, 0, None, closed="neither"),
+            Interval(RealNotInt, 0, 1, closed="neither"),
+        ],
+        "verbose": ["verbose"],
+        "importance_getter": [str, callable],
+    }
+
+    def __init__(
+        self,
+        estimator,
+        *,
+        n_features_to_select=None,
+        step=1,
+        verbose=0,
+        importance_getter="auto",
+    ):
+        self.estimator = estimator
+        self.n_features_to_select = n_features_to_select
+        self.step = step
+        self.importance_getter = importance_getter
+        self.verbose = verbose
+
+    # TODO(1.8) remove this property
+    @property
+    def _estimator_type(self):
+        return self.estimator._estimator_type
+
+    @property
+    def classes_(self):
+        """Classes labels available when `estimator` is a classifier.
+
+        Returns
+        -------
+        ndarray of shape (n_classes,)
+        """
+        return self.estimator_.classes_
+
+    @_fit_context(
+        # RFE.estimator is not validated yet
+        prefer_skip_nested_validation=False
+    )
+    def fit(self, X, y, **fit_params):
+        """Fit the RFE model and then the underlying estimator on the selected features.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            The training input samples.
+
+        y : array-like of shape (n_samples,)
+            The target values.
+
+        **fit_params : dict
+            - If `enable_metadata_routing=False` (default): Parameters directly passed
+              to the ``fit`` method of the underlying estimator.
+
+            - If `enable_metadata_routing=True`: Parameters safely routed to the ``fit``
+              method of the underlying estimator.
+
+            .. versionchanged:: 1.6
+                See :ref:`Metadata Routing User Guide `
+                for more details.
+
+        Returns
+        -------
+        self : object
+            Fitted estimator.
+        """
+        if _routing_enabled():
+            routed_params = process_routing(self, "fit", **fit_params)
+        else:
+            routed_params = Bunch(estimator=Bunch(fit=fit_params))
+
+        return self._fit(X, y, **routed_params.estimator.fit)
+
+    def _fit(self, X, y, step_score=None, **fit_params):
+        # Parameter step_score controls the calculation of self.step_scores_
+        # step_score is not exposed to users and is used when implementing RFECV
+        # self.step_scores_ will not be calculated when calling _fit through fit
+
+        X, y = validate_data(
+            self,
+            X,
+            y,
+            accept_sparse="csc",
+            ensure_min_features=2,
+            ensure_all_finite=False,
+            multi_output=True,
+        )
+
+        # Initialization
+        n_features = X.shape[1]
+        if self.n_features_to_select is None:
+            n_features_to_select = n_features // 2
+        elif isinstance(self.n_features_to_select, Integral):  # int
+            n_features_to_select = self.n_features_to_select
+            if n_features_to_select > n_features:
+                warnings.warn(
+                    (
+                        f"Found {n_features_to_select=} > {n_features=}. There will be"
+                        " no feature selection and all features will be kept."
+                    ),
+                    UserWarning,
+                )
+        else:  # float
+            n_features_to_select = int(n_features * self.n_features_to_select)
+
+        if 0.0 < self.step < 1.0:
+            step = int(max(1, self.step * n_features))
+        else:
+            step = int(self.step)
+
+        support_ = np.ones(n_features, dtype=bool)
+        ranking_ = np.ones(n_features, dtype=int)
+
+        if step_score:
+            self.step_n_features_ = []
+            self.step_scores_ = []
+            self.step_support_ = []
+            self.step_ranking_ = []
+
+        # Elimination
+        while np.sum(support_) > n_features_to_select:
+            # Remaining features
+            features = np.arange(n_features)[support_]
+
+            # Rank the remaining features
+            estimator = clone(self.estimator)
+            if self.verbose > 0:
+                print("Fitting estimator with %d features." % np.sum(support_))
+
+            estimator.fit(X[:, features], y, **fit_params)
+
+            # Compute step values on the previous selection iteration because
+            # 'estimator' must use features that have not been eliminated yet
+            if step_score:
+                self.step_n_features_.append(len(features))
+                self.step_scores_.append(step_score(estimator, features))
+                self.step_support_.append(list(support_))
+                self.step_ranking_.append(list(ranking_))
+
+            # Get importance and rank them
+            importances = _get_feature_importances(
+                estimator,
+                self.importance_getter,
+                transform_func="square",
+            )
+            ranks = np.argsort(importances)
+
+            # for sparse case ranks is matrix
+            ranks = np.ravel(ranks)
+
+            # Eliminate the worse features
+            threshold = min(step, np.sum(support_) - n_features_to_select)
+
+            support_[features[ranks][:threshold]] = False
+            ranking_[np.logical_not(support_)] += 1
+
+        # Set final attributes
+        features = np.arange(n_features)[support_]
+        self.estimator_ = clone(self.estimator)
+        self.estimator_.fit(X[:, features], y, **fit_params)
+
+        # Compute step values when only n_features_to_select features left
+        if step_score:
+            self.step_n_features_.append(len(features))
+            self.step_scores_.append(step_score(self.estimator_, features))
+            self.step_support_.append(support_)
+            self.step_ranking_.append(ranking_)
+        self.n_features_ = support_.sum()
+        self.support_ = support_
+        self.ranking_ = ranking_
+
+        return self
+
+    @available_if(_estimator_has("predict"))
+    def predict(self, X, **predict_params):
+        """Reduce X to the selected features and predict using the estimator.
+
+        Parameters
+        ----------
+        X : array of shape [n_samples, n_features]
+            The input samples.
+
+        **predict_params : dict
+            Parameters to route to the ``predict`` method of the
+            underlying estimator.
+
+            .. versionadded:: 1.6
+                Only available if `enable_metadata_routing=True`,
+                which can be set by using
+                ``sklearn.set_config(enable_metadata_routing=True)``.
+                See :ref:`Metadata Routing User Guide `
+                for more details.
+
+        Returns
+        -------
+        y : array of shape [n_samples]
+            The predicted target values.
+        """
+        _raise_for_params(predict_params, self, "predict")
+        check_is_fitted(self)
+        if _routing_enabled():
+            routed_params = process_routing(self, "predict", **predict_params)
+        else:
+            routed_params = Bunch(estimator=Bunch(predict={}))
+
+        return self.estimator_.predict(
+            self.transform(X), **routed_params.estimator.predict
+        )
+
+    @available_if(_estimator_has("score"))
+    def score(self, X, y, **score_params):
+        """Reduce X to the selected features and return the score of the estimator.
+
+        Parameters
+        ----------
+        X : array of shape [n_samples, n_features]
+            The input samples.
+
+        y : array of shape [n_samples]
+            The target values.
+
+        **score_params : dict
+            - If `enable_metadata_routing=False` (default): Parameters directly passed
+              to the ``score`` method of the underlying estimator.
+
+            - If `enable_metadata_routing=True`: Parameters safely routed to the `score`
+              method of the underlying estimator.
+
+            .. versionadded:: 1.0
+
+            .. versionchanged:: 1.6
+                See :ref:`Metadata Routing User Guide `
+                for more details.
+
+        Returns
+        -------
+        score : float
+            Score of the underlying base estimator computed with the selected
+            features returned by `rfe.transform(X)` and `y`.
+        """
+        check_is_fitted(self)
+        if _routing_enabled():
+            routed_params = process_routing(self, "score", **score_params)
+        else:
+            routed_params = Bunch(estimator=Bunch(score=score_params))
+
+        return self.estimator_.score(
+            self.transform(X), y, **routed_params.estimator.score
+        )
+
+    def _get_support_mask(self):
+        check_is_fitted(self)
+        return self.support_
+
+    @available_if(_estimator_has("decision_function"))
+    def decision_function(self, X):
+        """Compute the decision function of ``X``.
+
+        Parameters
+        ----------
+        X : {array-like or sparse matrix} of shape (n_samples, n_features)
+            The input samples. Internally, it will be converted to
+            ``dtype=np.float32`` and if a sparse matrix is provided
+            to a sparse ``csr_matrix``.
+
+        Returns
+        -------
+        score : array, shape = [n_samples, n_classes] or [n_samples]
+            The decision function of the input samples. The order of the
+            classes corresponds to that in the attribute :term:`classes_`.
+            Regression and binary classification produce an array of shape
+            [n_samples].
+        """
+        check_is_fitted(self)
+        return self.estimator_.decision_function(self.transform(X))
+
+    @available_if(_estimator_has("predict_proba"))
+    def predict_proba(self, X):
+        """Predict class probabilities for X.
+
+        Parameters
+        ----------
+        X : {array-like or sparse matrix} of shape (n_samples, n_features)
+            The input samples. Internally, it will be converted to
+            ``dtype=np.float32`` and if a sparse matrix is provided
+            to a sparse ``csr_matrix``.
+
+        Returns
+        -------
+        p : array of shape (n_samples, n_classes)
+            The class probabilities of the input samples. The order of the
+            classes corresponds to that in the attribute :term:`classes_`.
+        """
+        check_is_fitted(self)
+        return self.estimator_.predict_proba(self.transform(X))
+
+    @available_if(_estimator_has("predict_log_proba"))
+    def predict_log_proba(self, X):
+        """Predict class log-probabilities for X.
+
+        Parameters
+        ----------
+        X : array of shape [n_samples, n_features]
+            The input samples.
+
+        Returns
+        -------
+        p : array of shape (n_samples, n_classes)
+            The class log-probabilities of the input samples. The order of the
+            classes corresponds to that in the attribute :term:`classes_`.
+        """
+        check_is_fitted(self)
+        return self.estimator_.predict_log_proba(self.transform(X))
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        sub_estimator_tags = get_tags(self.estimator)
+        tags.estimator_type = sub_estimator_tags.estimator_type
+        tags.classifier_tags = deepcopy(sub_estimator_tags.classifier_tags)
+        tags.regressor_tags = deepcopy(sub_estimator_tags.regressor_tags)
+        if tags.classifier_tags is not None:
+            tags.classifier_tags.poor_score = True
+        if tags.regressor_tags is not None:
+            tags.regressor_tags.poor_score = True
+        tags.target_tags.required = True
+        tags.input_tags.sparse = sub_estimator_tags.input_tags.sparse
+        tags.input_tags.allow_nan = sub_estimator_tags.input_tags.allow_nan
+        return tags
+
+    def get_metadata_routing(self):
+        """Get metadata routing of this object.
+
+        Please check :ref:`User Guide ` on how the routing
+        mechanism works.
+
+        .. versionadded:: 1.6
+
+        Returns
+        -------
+        routing : MetadataRouter
+            A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
+            routing information.
+        """
+        router = MetadataRouter(owner=self.__class__.__name__).add(
+            estimator=self.estimator,
+            method_mapping=MethodMapping()
+            .add(caller="fit", callee="fit")
+            .add(caller="predict", callee="predict")
+            .add(caller="score", callee="score"),
+        )
+        return router
+
+
+class RFECV(RFE):
+    """Recursive feature elimination with cross-validation to select features.
+
+    The number of features selected is tuned automatically by fitting an :class:`RFE`
+    selector on the different cross-validation splits (provided by the `cv` parameter).
+    The performance of each :class:`RFE` selector is evaluated using `scoring` for
+    different numbers of selected features and aggregated together. Finally, the scores
+    are averaged across folds and the number of features selected is set to the number
+    of features that maximize the cross-validation score.
+
+    See glossary entry for :term:`cross-validation estimator`.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    estimator : ``Estimator`` instance
+        A supervised learning estimator with a ``fit`` method that provides
+        information about feature importance either through a ``coef_``
+        attribute or through a ``feature_importances_`` attribute.
+
+    step : int or float, default=1
+        If greater than or equal to 1, then ``step`` corresponds to the
+        (integer) number of features to remove at each iteration.
+        If within (0.0, 1.0), then ``step`` corresponds to the percentage
+        (rounded down) of features to remove at each iteration.
+        Note that the last iteration may remove fewer than ``step`` features in
+        order to reach ``min_features_to_select``.
+
+    min_features_to_select : int, default=1
+        The minimum number of features to be selected. This number of features
+        will always be scored, even if the difference between the original
+        feature count and ``min_features_to_select`` isn't divisible by
+        ``step``.
+
+        .. versionadded:: 0.20
+
+    cv : int, cross-validation generator or an iterable, default=None
+        Determines the cross-validation splitting strategy.
+        Possible inputs for cv are:
+
+        - None, to use the default 5-fold cross-validation,
+        - integer, to specify the number of folds.
+        - :term:`CV splitter`,
+        - An iterable yielding (train, test) splits as arrays of indices.
+
+        For integer/None inputs, if ``y`` is binary or multiclass,
+        :class:`~sklearn.model_selection.StratifiedKFold` is used. If the
+        estimator is not a classifier or if ``y`` is neither binary nor multiclass,
+        :class:`~sklearn.model_selection.KFold` is used.
+
+        Refer :ref:`User Guide ` for the various
+        cross-validation strategies that can be used here.
+
+        .. versionchanged:: 0.22
+            ``cv`` default value of None changed from 3-fold to 5-fold.
+
+    scoring : str or callable, default=None
+        Scoring method to evaluate the :class:`RFE` selectors' performance. Options:
+
+        - str: see :ref:`scoring_string_names` for options.
+        - callable: a scorer callable object (e.g., function) with signature
+          ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details.
+        - `None`: the `estimator`'s
+          :ref:`default evaluation criterion ` is used.
+
+    verbose : int, default=0
+        Controls verbosity of output.
+
+    n_jobs : int or None, default=None
+        Number of cores to run in parallel while fitting across folds.
+        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+        ``-1`` means using all processors. See :term:`Glossary `
+        for more details.
+
+        .. versionadded:: 0.18
+
+    importance_getter : str or callable, default='auto'
+        If 'auto', uses the feature importance either through a `coef_`
+        or `feature_importances_` attributes of estimator.
+
+        Also accepts a string that specifies an attribute name/path
+        for extracting feature importance.
+        For example, give `regressor_.coef_` in case of
+        :class:`~sklearn.compose.TransformedTargetRegressor`  or
+        `named_steps.clf.feature_importances_` in case of
+        :class:`~sklearn.pipeline.Pipeline` with its last step named `clf`.
+
+        If `callable`, overrides the default feature importance getter.
+        The callable is passed with the fitted estimator and it should
+        return importance for each feature.
+
+        .. versionadded:: 0.24
+
+    Attributes
+    ----------
+    classes_ : ndarray of shape (n_classes,)
+        The classes labels. Only available when `estimator` is a classifier.
+
+    estimator_ : ``Estimator`` instance
+        The fitted estimator used to select features.
+
+    cv_results_ : dict of ndarrays
+        All arrays (values of the dictionary) are sorted in ascending order
+        by the number of features used (i.e., the first element of the array
+        represents the models that used the least number of features, while the
+        last element represents the models that used all available features).
+
+        .. versionadded:: 1.0
+
+        This dictionary contains the following keys:
+
+        split(k)_test_score : ndarray of shape (n_subsets_of_features,)
+            The cross-validation scores across (k)th fold.
+
+        mean_test_score : ndarray of shape (n_subsets_of_features,)
+            Mean of scores over the folds.
+
+        std_test_score : ndarray of shape (n_subsets_of_features,)
+            Standard deviation of scores over the folds.
+
+        n_features : ndarray of shape (n_subsets_of_features,)
+            Number of features used at each step.
+
+            .. versionadded:: 1.5
+
+        split(k)_ranking : ndarray of shape (n_subsets_of_features,)
+            The cross-validation rankings across (k)th fold.
+            Selected (i.e., estimated best) features are assigned rank 1.
+            Illustration in
+            :ref:`sphx_glr_auto_examples_feature_selection_plot_rfe_with_cross_validation.py`
+
+            .. versionadded:: 1.7
+
+        split(k)_support : ndarray of shape (n_subsets_of_features,)
+            The cross-validation supports across (k)th fold. The support
+            is the mask of selected features.
+
+            .. versionadded:: 1.7
+
+    n_features_ : int
+        The number of selected features with cross-validation.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`. Only defined if the
+        underlying estimator exposes such an attribute when fit.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    ranking_ : narray of shape (n_features,)
+        The feature ranking, such that `ranking_[i]`
+        corresponds to the ranking
+        position of the i-th feature.
+        Selected (i.e., estimated best)
+        features are assigned rank 1.
+
+    support_ : ndarray of shape (n_features,)
+        The mask of selected features.
+
+    See Also
+    --------
+    RFE : Recursive feature elimination.
+
+    Notes
+    -----
+    The size of all values in ``cv_results_`` is equal to
+    ``ceil((n_features - min_features_to_select) / step) + 1``,
+    where step is the number of features removed at each iteration.
+
+    Allows NaN/Inf in the input if the underlying estimator does as well.
+
+    References
+    ----------
+
+    .. [1] Guyon, I., Weston, J., Barnhill, S., & Vapnik, V., "Gene selection
+           for cancer classification using support vector machines",
+           Mach. Learn., 46(1-3), 389--422, 2002.
+
+    Examples
+    --------
+    The following example shows how to retrieve the a-priori not known 5
+    informative features in the Friedman #1 dataset.
+
+    >>> from sklearn.datasets import make_friedman1
+    >>> from sklearn.feature_selection import RFECV
+    >>> from sklearn.svm import SVR
+    >>> X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)
+    >>> estimator = SVR(kernel="linear")
+    >>> selector = RFECV(estimator, step=1, cv=5)
+    >>> selector = selector.fit(X, y)
+    >>> selector.support_
+    array([ True,  True,  True,  True,  True, False, False, False, False,
+           False])
+    >>> selector.ranking_
+    array([1, 1, 1, 1, 1, 6, 4, 3, 2, 5])
+
+    For a detailed example of using RFECV to select features when training a
+    :class:`~sklearn.linear_model.LogisticRegression`, see
+    :ref:`sphx_glr_auto_examples_feature_selection_plot_rfe_with_cross_validation.py`.
+    """
+
+    _parameter_constraints: dict = {
+        **RFE._parameter_constraints,
+        "min_features_to_select": [Interval(Integral, 0, None, closed="neither")],
+        "cv": ["cv_object"],
+        "scoring": [None, str, callable],
+        "n_jobs": [None, Integral],
+    }
+    _parameter_constraints.pop("n_features_to_select")
+    __metadata_request__fit = {"groups": metadata_routing.UNUSED}
+
+    def __init__(
+        self,
+        estimator,
+        *,
+        step=1,
+        min_features_to_select=1,
+        cv=None,
+        scoring=None,
+        verbose=0,
+        n_jobs=None,
+        importance_getter="auto",
+    ):
+        self.estimator = estimator
+        self.step = step
+        self.importance_getter = importance_getter
+        self.cv = cv
+        self.scoring = scoring
+        self.verbose = verbose
+        self.n_jobs = n_jobs
+        self.min_features_to_select = min_features_to_select
+
+    # TODO(1.8): remove `groups` from the signature after deprecation cycle.
+    @_deprecate_positional_args(version="1.8")
+    @_fit_context(
+        # RFECV.estimator is not validated yet
+        prefer_skip_nested_validation=False
+    )
+    def fit(self, X, y, *, groups=None, **params):
+        """Fit the RFE model and automatically tune the number of selected features.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            Training vector, where `n_samples` is the number of samples and
+            `n_features` is the total number of features.
+
+        y : array-like of shape (n_samples,)
+            Target values (integers for classification, real numbers for
+            regression).
+
+        groups : array-like of shape (n_samples,) or None, default=None
+            Group labels for the samples used while splitting the dataset into
+            train/test set. Only used in conjunction with a "Group" :term:`cv`
+            instance (e.g., :class:`~sklearn.model_selection.GroupKFold`).
+
+            .. versionadded:: 0.20
+
+        **params : dict of str -> object
+            Parameters passed to the ``fit`` method of the estimator,
+            the scorer, and the CV splitter.
+
+            .. versionadded:: 1.6
+                Only available if `enable_metadata_routing=True`,
+                which can be set by using
+                ``sklearn.set_config(enable_metadata_routing=True)``.
+                See :ref:`Metadata Routing User Guide `
+                for more details.
+
+        Returns
+        -------
+        self : object
+            Fitted estimator.
+        """
+        _raise_for_params(params, self, "fit")
+        X, y = validate_data(
+            self,
+            X,
+            y,
+            accept_sparse="csr",
+            ensure_min_features=2,
+            ensure_all_finite=False,
+            multi_output=True,
+        )
+
+        if _routing_enabled():
+            if groups is not None:
+                params.update({"groups": groups})
+            routed_params = process_routing(self, "fit", **params)
+        else:
+            routed_params = Bunch(
+                estimator=Bunch(fit={}),
+                splitter=Bunch(split={"groups": groups}),
+                scorer=Bunch(score={}),
+            )
+
+        # Initialization
+        cv = check_cv(self.cv, y, classifier=is_classifier(self.estimator))
+        scorer = self._get_scorer()
+
+        # Build an RFE object, which will evaluate and score each possible
+        # feature count, down to self.min_features_to_select
+        n_features = X.shape[1]
+        if self.min_features_to_select > n_features:
+            warnings.warn(
+                (
+                    f"Found min_features_to_select={self.min_features_to_select} > "
+                    f"{n_features=}. There will be no feature selection and all "
+                    "features will be kept."
+                ),
+                UserWarning,
+            )
+        rfe = RFE(
+            estimator=self.estimator,
+            n_features_to_select=min(self.min_features_to_select, n_features),
+            importance_getter=self.importance_getter,
+            step=self.step,
+            verbose=self.verbose,
+        )
+
+        # Determine the number of subsets of features by fitting across
+        # the train folds and choosing the "features_to_select" parameter
+        # that gives the least averaged error across all folds.
+
+        # Note that joblib raises a non-picklable error for bound methods
+        # even if n_jobs is set to 1 with the default multiprocessing
+        # backend.
+        # This branching is done so that to
+        # make sure that user code that sets n_jobs to 1
+        # and provides bound methods as scorers is not broken with the
+        # addition of n_jobs parameter in version 0.18.
+
+        if effective_n_jobs(self.n_jobs) == 1:
+            parallel, func = list, _rfe_single_fit
+        else:
+            parallel = Parallel(n_jobs=self.n_jobs)
+            func = delayed(_rfe_single_fit)
+
+        step_results = parallel(
+            func(clone(rfe), self.estimator, X, y, train, test, scorer, routed_params)
+            for train, test in cv.split(X, y, **routed_params.splitter.split)
+        )
+        scores, supports, rankings, step_n_features = zip(*step_results)
+
+        step_n_features_rev = np.array(step_n_features[0])[::-1]
+        scores = np.array(scores)
+        rankings = np.array(rankings)
+        supports = np.array(supports)
+
+        # Reverse order such that lowest number of features is selected in case of tie.
+        scores_sum_rev = np.sum(scores, axis=0)[::-1]
+        n_features_to_select = step_n_features_rev[np.argmax(scores_sum_rev)]
+
+        # Re-execute an elimination with best_k over the whole set
+        rfe = RFE(
+            estimator=self.estimator,
+            n_features_to_select=n_features_to_select,
+            step=self.step,
+            importance_getter=self.importance_getter,
+            verbose=self.verbose,
+        )
+
+        rfe.fit(X, y, **routed_params.estimator.fit)
+
+        # Set final attributes
+        self.support_ = rfe.support_
+        self.n_features_ = rfe.n_features_
+        self.ranking_ = rfe.ranking_
+        self.estimator_ = clone(self.estimator)
+        self.estimator_.fit(self._transform(X), y, **routed_params.estimator.fit)
+
+        # reverse to stay consistent with before
+        scores_rev = scores[:, ::-1]
+        supports_rev = supports[:, ::-1]
+        rankings_rev = rankings[:, ::-1]
+        self.cv_results_ = {
+            "mean_test_score": np.mean(scores_rev, axis=0),
+            "std_test_score": np.std(scores_rev, axis=0),
+            **{f"split{i}_test_score": scores_rev[i] for i in range(scores.shape[0])},
+            **{f"split{i}_ranking": rankings_rev[i] for i in range(rankings.shape[0])},
+            **{f"split{i}_support": supports_rev[i] for i in range(supports.shape[0])},
+            "n_features": step_n_features_rev,
+        }
+        return self
+
+    def score(self, X, y, **score_params):
+        """Score using the `scoring` option on the given test data and labels.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            Test samples.
+
+        y : array-like of shape (n_samples,)
+            True labels for X.
+
+        **score_params : dict
+            Parameters to pass to the `score` method of the underlying scorer.
+
+            .. versionadded:: 1.6
+                Only available if `enable_metadata_routing=True`,
+                which can be set by using
+                ``sklearn.set_config(enable_metadata_routing=True)``.
+                See :ref:`Metadata Routing User Guide `
+                for more details.
+
+        Returns
+        -------
+        score : float
+            Score of self.predict(X) w.r.t. y defined by `scoring`.
+        """
+        _raise_for_params(score_params, self, "score")
+        scoring = self._get_scorer()
+        if _routing_enabled():
+            routed_params = process_routing(self, "score", **score_params)
+        else:
+            routed_params = Bunch()
+            routed_params.scorer = Bunch(score={})
+
+        return scoring(self, X, y, **routed_params.scorer.score)
+
+    def get_metadata_routing(self):
+        """Get metadata routing of this object.
+
+        Please check :ref:`User Guide ` on how the routing
+        mechanism works.
+
+        .. versionadded:: 1.6
+
+        Returns
+        -------
+        routing : MetadataRouter
+            A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
+            routing information.
+        """
+        router = MetadataRouter(owner=self.__class__.__name__)
+        router.add(
+            estimator=self.estimator,
+            method_mapping=MethodMapping().add(caller="fit", callee="fit"),
+        )
+        router.add(
+            splitter=check_cv(self.cv),
+            method_mapping=MethodMapping().add(
+                caller="fit",
+                callee="split",
+            ),
+        )
+        router.add(
+            scorer=self._get_scorer(),
+            method_mapping=MethodMapping()
+            .add(caller="fit", callee="score")
+            .add(caller="score", callee="score"),
+        )
+
+        return router
+
+    def _get_scorer(self):
+        if self.scoring is None:
+            scoring = "accuracy" if is_classifier(self.estimator) else "r2"
+        else:
+            scoring = self.scoring
+        return get_scorer(scoring)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_sequential.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_sequential.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6d6ed9e2e72e278bee29638945bc9a2456826f6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_sequential.py
@@ -0,0 +1,363 @@
+"""
+Sequential feature selection
+"""
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+from numbers import Integral, Real
+
+import numpy as np
+
+from ..base import BaseEstimator, MetaEstimatorMixin, _fit_context, clone, is_classifier
+from ..metrics import check_scoring, get_scorer_names
+from ..model_selection import check_cv, cross_val_score
+from ..utils._metadata_requests import (
+    MetadataRouter,
+    MethodMapping,
+    _raise_for_params,
+    _routing_enabled,
+    process_routing,
+)
+from ..utils._param_validation import HasMethods, Interval, RealNotInt, StrOptions
+from ..utils._tags import get_tags
+from ..utils.validation import check_is_fitted, validate_data
+from ._base import SelectorMixin
+
+
+class SequentialFeatureSelector(SelectorMixin, MetaEstimatorMixin, BaseEstimator):
+    """Transformer that performs Sequential Feature Selection.
+
+    This Sequential Feature Selector adds (forward selection) or
+    removes (backward selection) features to form a feature subset in a
+    greedy fashion. At each stage, this estimator chooses the best feature to
+    add or remove based on the cross-validation score of an estimator. In
+    the case of unsupervised learning, this Sequential Feature Selector
+    looks only at the features (X), not the desired outputs (y).
+
+    Read more in the :ref:`User Guide `.
+
+    .. versionadded:: 0.24
+
+    Parameters
+    ----------
+    estimator : estimator instance
+        An unfitted estimator.
+
+    n_features_to_select : "auto", int or float, default="auto"
+        If `"auto"`, the behaviour depends on the `tol` parameter:
+
+        - if `tol` is not `None`, then features are selected while the score
+          change does not exceed `tol`.
+        - otherwise, half of the features are selected.
+
+        If integer, the parameter is the absolute number of features to select.
+        If float between 0 and 1, it is the fraction of features to select.
+
+        .. versionadded:: 1.1
+           The option `"auto"` was added in version 1.1.
+
+        .. versionchanged:: 1.3
+           The default changed from `"warn"` to `"auto"` in 1.3.
+
+    tol : float, default=None
+        If the score is not incremented by at least `tol` between two
+        consecutive feature additions or removals, stop adding or removing.
+
+        `tol` can be negative when removing features using `direction="backward"`.
+        `tol` is required to be strictly positive when doing forward selection.
+        It can be useful to reduce the number of features at the cost of a small
+        decrease in the score.
+
+        `tol` is enabled only when `n_features_to_select` is `"auto"`.
+
+        .. versionadded:: 1.1
+
+    direction : {'forward', 'backward'}, default='forward'
+        Whether to perform forward selection or backward selection.
+
+    scoring : str or callable, default=None
+        Scoring method to use for cross-validation. Options:
+
+        - str: see :ref:`scoring_string_names` for options.
+        - callable: a scorer callable object (e.g., function) with signature
+          ``scorer(estimator, X, y)`` that returns a single value.
+          See :ref:`scoring_callable` for details.
+        - `None`: the `estimator`'s
+          :ref:`default evaluation criterion ` is used.
+
+    cv : int, cross-validation generator or an iterable, default=None
+        Determines the cross-validation splitting strategy.
+        Possible inputs for cv are:
+
+        - None, to use the default 5-fold cross validation,
+        - integer, to specify the number of folds in a `(Stratified)KFold`,
+        - :term:`CV splitter`,
+        - An iterable yielding (train, test) splits as arrays of indices.
+
+        For integer/None inputs, if the estimator is a classifier and ``y`` is
+        either binary or multiclass,
+        :class:`~sklearn.model_selection.StratifiedKFold` is used. In all other
+        cases, :class:`~sklearn.model_selection.KFold` is used. These splitters
+        are instantiated with `shuffle=False` so the splits will be the same
+        across calls.
+
+        Refer :ref:`User Guide ` for the various
+        cross-validation strategies that can be used here.
+
+    n_jobs : int, default=None
+        Number of jobs to run in parallel. When evaluating a new feature to
+        add or remove, the cross-validation procedure is parallel over the
+        folds.
+        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+        ``-1`` means using all processors. See :term:`Glossary `
+        for more details.
+
+    Attributes
+    ----------
+    n_features_in_ : int
+        Number of features seen during :term:`fit`. Only defined if the
+        underlying estimator exposes such an attribute when fit.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    n_features_to_select_ : int
+        The number of features that were selected.
+
+    support_ : ndarray of shape (n_features,), dtype=bool
+        The mask of selected features.
+
+    See Also
+    --------
+    GenericUnivariateSelect : Univariate feature selector with configurable
+        strategy.
+    RFE : Recursive feature elimination based on importance weights.
+    RFECV : Recursive feature elimination based on importance weights, with
+        automatic selection of the number of features.
+    SelectFromModel : Feature selection based on thresholds of importance
+        weights.
+
+    Examples
+    --------
+    >>> from sklearn.feature_selection import SequentialFeatureSelector
+    >>> from sklearn.neighbors import KNeighborsClassifier
+    >>> from sklearn.datasets import load_iris
+    >>> X, y = load_iris(return_X_y=True)
+    >>> knn = KNeighborsClassifier(n_neighbors=3)
+    >>> sfs = SequentialFeatureSelector(knn, n_features_to_select=3)
+    >>> sfs.fit(X, y)
+    SequentialFeatureSelector(estimator=KNeighborsClassifier(n_neighbors=3),
+                              n_features_to_select=3)
+    >>> sfs.get_support()
+    array([ True, False,  True,  True])
+    >>> sfs.transform(X).shape
+    (150, 3)
+    """
+
+    _parameter_constraints: dict = {
+        "estimator": [HasMethods(["fit"])],
+        "n_features_to_select": [
+            StrOptions({"auto"}),
+            Interval(RealNotInt, 0, 1, closed="right"),
+            Interval(Integral, 0, None, closed="neither"),
+        ],
+        "tol": [None, Interval(Real, None, None, closed="neither")],
+        "direction": [StrOptions({"forward", "backward"})],
+        "scoring": [None, StrOptions(set(get_scorer_names())), callable],
+        "cv": ["cv_object"],
+        "n_jobs": [None, Integral],
+    }
+
+    def __init__(
+        self,
+        estimator,
+        *,
+        n_features_to_select="auto",
+        tol=None,
+        direction="forward",
+        scoring=None,
+        cv=5,
+        n_jobs=None,
+    ):
+        self.estimator = estimator
+        self.n_features_to_select = n_features_to_select
+        self.tol = tol
+        self.direction = direction
+        self.scoring = scoring
+        self.cv = cv
+        self.n_jobs = n_jobs
+
+    @_fit_context(
+        # SequentialFeatureSelector.estimator is not validated yet
+        prefer_skip_nested_validation=False
+    )
+    def fit(self, X, y=None, **params):
+        """Learn the features to select from X.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            Training vectors, where `n_samples` is the number of samples and
+            `n_features` is the number of predictors.
+
+        y : array-like of shape (n_samples,), default=None
+            Target values. This parameter may be ignored for
+            unsupervised learning.
+
+        **params : dict, default=None
+            Parameters to be passed to the underlying `estimator`, `cv`
+            and `scorer` objects.
+
+            .. versionadded:: 1.6
+
+                Only available if `enable_metadata_routing=True`,
+                which can be set by using
+                ``sklearn.set_config(enable_metadata_routing=True)``.
+                See :ref:`Metadata Routing User Guide ` for
+                more details.
+
+        Returns
+        -------
+        self : object
+            Returns the instance itself.
+        """
+        _raise_for_params(params, self, "fit")
+        tags = self.__sklearn_tags__()
+        X = validate_data(
+            self,
+            X,
+            accept_sparse="csc",
+            ensure_min_features=2,
+            ensure_all_finite=not tags.input_tags.allow_nan,
+        )
+        n_features = X.shape[1]
+
+        if self.n_features_to_select == "auto":
+            if self.tol is not None:
+                # With auto feature selection, `n_features_to_select_` will be updated
+                # to `support_.sum()` after features are selected.
+                self.n_features_to_select_ = n_features - 1
+            else:
+                self.n_features_to_select_ = n_features // 2
+        elif isinstance(self.n_features_to_select, Integral):
+            if self.n_features_to_select >= n_features:
+                raise ValueError("n_features_to_select must be < n_features.")
+            self.n_features_to_select_ = self.n_features_to_select
+        elif isinstance(self.n_features_to_select, Real):
+            self.n_features_to_select_ = int(n_features * self.n_features_to_select)
+
+        if self.tol is not None and self.tol < 0 and self.direction == "forward":
+            raise ValueError(
+                "tol must be strictly positive when doing forward selection"
+            )
+
+        cv = check_cv(self.cv, y, classifier=is_classifier(self.estimator))
+
+        cloned_estimator = clone(self.estimator)
+
+        # the current mask corresponds to the set of features:
+        # - that we have already *selected* if we do forward selection
+        # - that we have already *excluded* if we do backward selection
+        current_mask = np.zeros(shape=n_features, dtype=bool)
+        n_iterations = (
+            self.n_features_to_select_
+            if self.n_features_to_select == "auto" or self.direction == "forward"
+            else n_features - self.n_features_to_select_
+        )
+
+        old_score = -np.inf
+        is_auto_select = self.tol is not None and self.n_features_to_select == "auto"
+
+        # We only need to verify the routing here and not use the routed params
+        # because internally the actual routing will also take place inside the
+        # `cross_val_score` function.
+        if _routing_enabled():
+            process_routing(self, "fit", **params)
+        for _ in range(n_iterations):
+            new_feature_idx, new_score = self._get_best_new_feature_score(
+                cloned_estimator, X, y, cv, current_mask, **params
+            )
+            if is_auto_select and ((new_score - old_score) < self.tol):
+                break
+
+            old_score = new_score
+            current_mask[new_feature_idx] = True
+
+        if self.direction == "backward":
+            current_mask = ~current_mask
+
+        self.support_ = current_mask
+        self.n_features_to_select_ = self.support_.sum()
+
+        return self
+
+    def _get_best_new_feature_score(self, estimator, X, y, cv, current_mask, **params):
+        # Return the best new feature and its score to add to the current_mask,
+        # i.e. return the best new feature and its score to add (resp. remove)
+        # when doing forward selection (resp. backward selection).
+        # Feature will be added if the current score and past score are greater
+        # than tol when n_feature is auto,
+        candidate_feature_indices = np.flatnonzero(~current_mask)
+        scores = {}
+        for feature_idx in candidate_feature_indices:
+            candidate_mask = current_mask.copy()
+            candidate_mask[feature_idx] = True
+            if self.direction == "backward":
+                candidate_mask = ~candidate_mask
+            X_new = X[:, candidate_mask]
+            scores[feature_idx] = cross_val_score(
+                estimator,
+                X_new,
+                y,
+                cv=cv,
+                scoring=self.scoring,
+                n_jobs=self.n_jobs,
+                params=params,
+            ).mean()
+        new_feature_idx = max(scores, key=lambda feature_idx: scores[feature_idx])
+        return new_feature_idx, scores[new_feature_idx]
+
+    def _get_support_mask(self):
+        check_is_fitted(self)
+        return self.support_
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.input_tags.allow_nan = get_tags(self.estimator).input_tags.allow_nan
+        tags.input_tags.sparse = get_tags(self.estimator).input_tags.sparse
+        return tags
+
+    def get_metadata_routing(self):
+        """Get metadata routing of this object.
+
+        Please check :ref:`User Guide ` on how the routing
+        mechanism works.
+
+        .. versionadded:: 1.6
+
+        Returns
+        -------
+        routing : MetadataRouter
+            A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
+            routing information.
+        """
+        router = MetadataRouter(owner=self.__class__.__name__)
+        router.add(
+            estimator=self.estimator,
+            method_mapping=MethodMapping().add(caller="fit", callee="fit"),
+        )
+        router.add(
+            splitter=check_cv(self.cv, classifier=is_classifier(self.estimator)),
+            method_mapping=MethodMapping().add(caller="fit", callee="split"),
+        )
+        router.add(
+            scorer=check_scoring(self.estimator, scoring=self.scoring),
+            method_mapping=MethodMapping().add(caller="fit", callee="score"),
+        )
+        return router
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_univariate_selection.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_univariate_selection.py
new file mode 100644
index 0000000000000000000000000000000000000000..7671a7ad7921d618cfdb98ba6baa60f24e3a9316
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_univariate_selection.py
@@ -0,0 +1,1171 @@
+"""Univariate features selection."""
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+import warnings
+from numbers import Integral, Real
+
+import numpy as np
+from scipy import special, stats
+from scipy.sparse import issparse
+
+from ..base import BaseEstimator, _fit_context
+from ..preprocessing import LabelBinarizer
+from ..utils import as_float_array, check_array, check_X_y, safe_mask, safe_sqr
+from ..utils._param_validation import Interval, StrOptions, validate_params
+from ..utils.extmath import row_norms, safe_sparse_dot
+from ..utils.validation import check_is_fitted, validate_data
+from ._base import SelectorMixin
+
+
+def _clean_nans(scores):
+    """
+    Fixes Issue #1240: NaNs can't be properly compared, so change them to the
+    smallest value of scores's dtype. -inf seems to be unreliable.
+    """
+    # XXX where should this function be called? fit? scoring functions
+    # themselves?
+    scores = as_float_array(scores, copy=True)
+    scores[np.isnan(scores)] = np.finfo(scores.dtype).min
+    return scores
+
+
+######################################################################
+# Scoring functions
+
+
+# The following function is a rewriting of scipy.stats.f_oneway
+# Contrary to the scipy.stats.f_oneway implementation it does not
+# copy the data while keeping the inputs unchanged.
+def f_oneway(*args):
+    """Perform a 1-way ANOVA.
+
+    The one-way ANOVA tests the null hypothesis that 2 or more groups have
+    the same population mean. The test is applied to samples from two or
+    more groups, possibly with differing sizes.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    *args : {array-like, sparse matrix}
+        Sample1, sample2... The sample measurements should be given as
+        arguments.
+
+    Returns
+    -------
+    f_statistic : float
+        The computed F-value of the test.
+    p_value : float
+        The associated p-value from the F-distribution.
+
+    Notes
+    -----
+    The ANOVA test has important assumptions that must be satisfied in order
+    for the associated p-value to be valid.
+
+    1. The samples are independent
+    2. Each sample is from a normally distributed population
+    3. The population standard deviations of the groups are all equal. This
+       property is known as homoscedasticity.
+
+    If these assumptions are not true for a given set of data, it may still be
+    possible to use the Kruskal-Wallis H-test (`scipy.stats.kruskal`_) although
+    with some loss of power.
+
+    The algorithm is from Heiman[2], pp.394-7.
+
+    See ``scipy.stats.f_oneway`` that should give the same results while
+    being less efficient.
+
+    References
+    ----------
+    .. [1] Lowry, Richard.  "Concepts and Applications of Inferential
+           Statistics". Chapter 14.
+           http://vassarstats.net/textbook
+
+    .. [2] Heiman, G.W.  Research Methods in Statistics. 2002.
+    """
+    n_classes = len(args)
+    args = [as_float_array(a) for a in args]
+    n_samples_per_class = np.array([a.shape[0] for a in args])
+    n_samples = np.sum(n_samples_per_class)
+    ss_alldata = sum(safe_sqr(a).sum(axis=0) for a in args)
+    sums_args = [np.asarray(a.sum(axis=0)) for a in args]
+    square_of_sums_alldata = sum(sums_args) ** 2
+    square_of_sums_args = [s**2 for s in sums_args]
+    sstot = ss_alldata - square_of_sums_alldata / float(n_samples)
+    ssbn = 0.0
+    for k, _ in enumerate(args):
+        ssbn += square_of_sums_args[k] / n_samples_per_class[k]
+    ssbn -= square_of_sums_alldata / float(n_samples)
+    sswn = sstot - ssbn
+    dfbn = n_classes - 1
+    dfwn = n_samples - n_classes
+    msb = ssbn / float(dfbn)
+    msw = sswn / float(dfwn)
+    constant_features_idx = np.where(msw == 0.0)[0]
+    if np.nonzero(msb)[0].size != msb.size and constant_features_idx.size:
+        warnings.warn("Features %s are constant." % constant_features_idx, UserWarning)
+    f = msb / msw
+    # flatten matrix to vector in sparse case
+    f = np.asarray(f).ravel()
+    prob = special.fdtrc(dfbn, dfwn, f)
+    return f, prob
+
+
+@validate_params(
+    {
+        "X": ["array-like", "sparse matrix"],
+        "y": ["array-like"],
+    },
+    prefer_skip_nested_validation=True,
+)
+def f_classif(X, y):
+    """Compute the ANOVA F-value for the provided sample.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    X : {array-like, sparse matrix} of shape (n_samples, n_features)
+        The set of regressors that will be tested sequentially.
+
+    y : array-like of shape (n_samples,)
+        The target vector.
+
+    Returns
+    -------
+    f_statistic : ndarray of shape (n_features,)
+        F-statistic for each feature.
+
+    p_values : ndarray of shape (n_features,)
+        P-values associated with the F-statistic.
+
+    See Also
+    --------
+    chi2 : Chi-squared stats of non-negative features for classification tasks.
+    f_regression : F-value between label/feature for regression tasks.
+
+    Examples
+    --------
+    >>> from sklearn.datasets import make_classification
+    >>> from sklearn.feature_selection import f_classif
+    >>> X, y = make_classification(
+    ...     n_samples=100, n_features=10, n_informative=2, n_clusters_per_class=1,
+    ...     shuffle=False, random_state=42
+    ... )
+    >>> f_statistic, p_values = f_classif(X, y)
+    >>> f_statistic
+    array([2.21e+02, 7.02e-01, 1.70e+00, 9.31e-01,
+           5.41e+00, 3.25e-01, 4.71e-02, 5.72e-01,
+           7.54e-01, 8.90e-02])
+    >>> p_values
+    array([7.14e-27, 4.04e-01, 1.96e-01, 3.37e-01,
+           2.21e-02, 5.70e-01, 8.29e-01, 4.51e-01,
+           3.87e-01, 7.66e-01])
+    """
+    X, y = check_X_y(X, y, accept_sparse=["csr", "csc", "coo"])
+    args = [X[safe_mask(X, y == k)] for k in np.unique(y)]
+    return f_oneway(*args)
+
+
+def _chisquare(f_obs, f_exp):
+    """Fast replacement for scipy.stats.chisquare.
+
+    Version from https://github.com/scipy/scipy/pull/2525 with additional
+    optimizations.
+    """
+    f_obs = np.asarray(f_obs, dtype=np.float64)
+
+    k = len(f_obs)
+    # Reuse f_obs for chi-squared statistics
+    chisq = f_obs
+    chisq -= f_exp
+    chisq **= 2
+    with np.errstate(invalid="ignore"):
+        chisq /= f_exp
+    chisq = chisq.sum(axis=0)
+    return chisq, special.chdtrc(k - 1, chisq)
+
+
+@validate_params(
+    {
+        "X": ["array-like", "sparse matrix"],
+        "y": ["array-like"],
+    },
+    prefer_skip_nested_validation=True,
+)
+def chi2(X, y):
+    """Compute chi-squared stats between each non-negative feature and class.
+
+    This score can be used to select the `n_features` features with the
+    highest values for the test chi-squared statistic from X, which must
+    contain only **non-negative integer feature values** such as booleans or frequencies
+    (e.g., term counts in document classification), relative to the classes.
+
+    If some of your features are continuous, you need to bin them, for
+    example by using :class:`~sklearn.preprocessing.KBinsDiscretizer`.
+
+    Recall that the chi-square test measures dependence between stochastic
+    variables, so using this function "weeds out" the features that are the
+    most likely to be independent of class and therefore irrelevant for
+    classification.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    X : {array-like, sparse matrix} of shape (n_samples, n_features)
+        Sample vectors.
+
+    y : array-like of shape (n_samples,)
+        Target vector (class labels).
+
+    Returns
+    -------
+    chi2 : ndarray of shape (n_features,)
+        Chi2 statistics for each feature.
+
+    p_values : ndarray of shape (n_features,)
+        P-values for each feature.
+
+    See Also
+    --------
+    f_classif : ANOVA F-value between label/feature for classification tasks.
+    f_regression : F-value between label/feature for regression tasks.
+
+    Notes
+    -----
+    Complexity of this algorithm is O(n_classes * n_features).
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from sklearn.feature_selection import chi2
+    >>> X = np.array([[1, 1, 3],
+    ...               [0, 1, 5],
+    ...               [5, 4, 1],
+    ...               [6, 6, 2],
+    ...               [1, 4, 0],
+    ...               [0, 0, 0]])
+    >>> y = np.array([1, 1, 0, 0, 2, 2])
+    >>> chi2_stats, p_values = chi2(X, y)
+    >>> chi2_stats
+    array([15.3,  6.5       ,  8.9])
+    >>> p_values
+    array([0.000456, 0.0387, 0.0116 ])
+    """
+
+    # XXX: we might want to do some of the following in logspace instead for
+    # numerical stability.
+    # Converting X to float allows getting better performance for the
+    # safe_sparse_dot call made below.
+    X = check_array(X, accept_sparse="csr", dtype=(np.float64, np.float32))
+    if np.any((X.data if issparse(X) else X) < 0):
+        raise ValueError("Input X must be non-negative.")
+
+    # Use a sparse representation for Y by default to reduce memory usage when
+    # y has many unique classes.
+    Y = LabelBinarizer(sparse_output=True).fit_transform(y)
+    if Y.shape[1] == 1:
+        Y = Y.toarray()
+        Y = np.append(1 - Y, Y, axis=1)
+
+    observed = safe_sparse_dot(Y.T, X)  # n_classes * n_features
+
+    if issparse(observed):
+        # convert back to a dense array before calling _chisquare
+        # XXX: could _chisquare be reimplement to accept sparse matrices for
+        # cases where both n_classes and n_features are large (and X is
+        # sparse)?
+        observed = observed.toarray()
+
+    feature_count = X.sum(axis=0).reshape(1, -1)
+    class_prob = Y.mean(axis=0).reshape(1, -1)
+    expected = np.dot(class_prob.T, feature_count)
+
+    return _chisquare(observed, expected)
+
+
+@validate_params(
+    {
+        "X": ["array-like", "sparse matrix"],
+        "y": ["array-like"],
+        "center": ["boolean"],
+        "force_finite": ["boolean"],
+    },
+    prefer_skip_nested_validation=True,
+)
+def r_regression(X, y, *, center=True, force_finite=True):
+    """Compute Pearson's r for each features and the target.
+
+    Pearson's r is also known as the Pearson correlation coefficient.
+
+    Linear model for testing the individual effect of each of many regressors.
+    This is a scoring function to be used in a feature selection procedure, not
+    a free standing feature selection procedure.
+
+    The cross correlation between each regressor and the target is computed
+    as::
+
+        E[(X[:, i] - mean(X[:, i])) * (y - mean(y))] / (std(X[:, i]) * std(y))
+
+    For more on usage see the :ref:`User Guide `.
+
+    .. versionadded:: 1.0
+
+    Parameters
+    ----------
+    X : {array-like, sparse matrix} of shape (n_samples, n_features)
+        The data matrix.
+
+    y : array-like of shape (n_samples,)
+        The target vector.
+
+    center : bool, default=True
+        Whether or not to center the data matrix `X` and the target vector `y`.
+        By default, `X` and `y` will be centered.
+
+    force_finite : bool, default=True
+        Whether or not to force the Pearson's R correlation to be finite.
+        In the particular case where some features in `X` or the target `y`
+        are constant, the Pearson's R correlation is not defined. When
+        `force_finite=False`, a correlation of `np.nan` is returned to
+        acknowledge this case. When `force_finite=True`, this value will be
+        forced to a minimal correlation of `0.0`.
+
+        .. versionadded:: 1.1
+
+    Returns
+    -------
+    correlation_coefficient : ndarray of shape (n_features,)
+        Pearson's R correlation coefficients of features.
+
+    See Also
+    --------
+    f_regression: Univariate linear regression tests returning f-statistic
+        and p-values.
+    mutual_info_regression: Mutual information for a continuous target.
+    f_classif: ANOVA F-value between label/feature for classification tasks.
+    chi2: Chi-squared stats of non-negative features for classification tasks.
+
+    Examples
+    --------
+    >>> from sklearn.datasets import make_regression
+    >>> from sklearn.feature_selection import r_regression
+    >>> X, y = make_regression(
+    ...     n_samples=50, n_features=3, n_informative=1, noise=1e-4, random_state=42
+    ... )
+    >>> r_regression(X, y)
+    array([-0.157,  1.        , -0.229])
+    """
+    X, y = check_X_y(X, y, accept_sparse=["csr", "csc", "coo"], dtype=np.float64)
+    n_samples = X.shape[0]
+
+    # Compute centered values
+    # Note that E[(x - mean(x))*(y - mean(y))] = E[x*(y - mean(y))], so we
+    # need not center X
+    if center:
+        y = y - np.mean(y)
+        # TODO: for Scipy <= 1.10, `isspmatrix(X)` returns `True` for sparse arrays.
+        # Here, we check the output of the `.mean` operation that returns a `np.matrix`
+        # for sparse matrices while a `np.array` for dense and sparse arrays.
+        # We can reconsider using `isspmatrix` when the minimum version is
+        # SciPy >= 1.11
+        X_means = X.mean(axis=0)
+        X_means = X_means.getA1() if isinstance(X_means, np.matrix) else X_means
+        # Compute the scaled standard deviations via moments
+        X_norms = np.sqrt(row_norms(X.T, squared=True) - n_samples * X_means**2)
+    else:
+        X_norms = row_norms(X.T)
+
+    correlation_coefficient = safe_sparse_dot(y, X)
+    with np.errstate(divide="ignore", invalid="ignore"):
+        correlation_coefficient /= X_norms
+        correlation_coefficient /= np.linalg.norm(y)
+
+    if force_finite and not np.isfinite(correlation_coefficient).all():
+        # case where the target or some features are constant
+        # the correlation coefficient(s) is/are set to the minimum (i.e. 0.0)
+        nan_mask = np.isnan(correlation_coefficient)
+        correlation_coefficient[nan_mask] = 0.0
+    return correlation_coefficient
+
+
+@validate_params(
+    {
+        "X": ["array-like", "sparse matrix"],
+        "y": ["array-like"],
+        "center": ["boolean"],
+        "force_finite": ["boolean"],
+    },
+    prefer_skip_nested_validation=True,
+)
+def f_regression(X, y, *, center=True, force_finite=True):
+    """Univariate linear regression tests returning F-statistic and p-values.
+
+    Quick linear model for testing the effect of a single regressor,
+    sequentially for many regressors.
+
+    This is done in 2 steps:
+
+    1. The cross correlation between each regressor and the target is computed
+       using :func:`r_regression` as::
+
+           E[(X[:, i] - mean(X[:, i])) * (y - mean(y))] / (std(X[:, i]) * std(y))
+
+    2. It is converted to an F score and then to a p-value.
+
+    :func:`f_regression` is derived from :func:`r_regression` and will rank
+    features in the same order if all the features are positively correlated
+    with the target.
+
+    Note however that contrary to :func:`f_regression`, :func:`r_regression`
+    values lie in [-1, 1] and can thus be negative. :func:`f_regression` is
+    therefore recommended as a feature selection criterion to identify
+    potentially predictive feature for a downstream classifier, irrespective of
+    the sign of the association with the target variable.
+
+    Furthermore :func:`f_regression` returns p-values while
+    :func:`r_regression` does not.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    X : {array-like, sparse matrix} of shape (n_samples, n_features)
+        The data matrix.
+
+    y : array-like of shape (n_samples,)
+        The target vector.
+
+    center : bool, default=True
+        Whether or not to center the data matrix `X` and the target vector `y`.
+        By default, `X` and `y` will be centered.
+
+    force_finite : bool, default=True
+        Whether or not to force the F-statistics and associated p-values to
+        be finite. There are two cases where the F-statistic is expected to not
+        be finite:
+
+        - when the target `y` or some features in `X` are constant. In this
+          case, the Pearson's R correlation is not defined leading to obtain
+          `np.nan` values in the F-statistic and p-value. When
+          `force_finite=True`, the F-statistic is set to `0.0` and the
+          associated p-value is set to `1.0`.
+        - when a feature in `X` is perfectly correlated (or
+          anti-correlated) with the target `y`. In this case, the F-statistic
+          is expected to be `np.inf`. When `force_finite=True`, the F-statistic
+          is set to `np.finfo(dtype).max` and the associated p-value is set to
+          `0.0`.
+
+        .. versionadded:: 1.1
+
+    Returns
+    -------
+    f_statistic : ndarray of shape (n_features,)
+        F-statistic for each feature.
+
+    p_values : ndarray of shape (n_features,)
+        P-values associated with the F-statistic.
+
+    See Also
+    --------
+    r_regression: Pearson's R between label/feature for regression tasks.
+    f_classif: ANOVA F-value between label/feature for classification tasks.
+    chi2: Chi-squared stats of non-negative features for classification tasks.
+    SelectKBest: Select features based on the k highest scores.
+    SelectFpr: Select features based on a false positive rate test.
+    SelectFdr: Select features based on an estimated false discovery rate.
+    SelectFwe: Select features based on family-wise error rate.
+    SelectPercentile: Select features based on percentile of the highest
+        scores.
+
+    Examples
+    --------
+    >>> from sklearn.datasets import make_regression
+    >>> from sklearn.feature_selection import f_regression
+    >>> X, y = make_regression(
+    ...     n_samples=50, n_features=3, n_informative=1, noise=1e-4, random_state=42
+    ... )
+    >>> f_statistic, p_values = f_regression(X, y)
+    >>> f_statistic
+    array([1.21, 2.67e13, 2.66])
+    >>> p_values
+    array([0.276, 1.54e-283, 0.11])
+    """
+    correlation_coefficient = r_regression(
+        X, y, center=center, force_finite=force_finite
+    )
+    deg_of_freedom = y.size - (2 if center else 1)
+
+    corr_coef_squared = correlation_coefficient**2
+
+    with np.errstate(divide="ignore", invalid="ignore"):
+        f_statistic = corr_coef_squared / (1 - corr_coef_squared) * deg_of_freedom
+        p_values = stats.f.sf(f_statistic, 1, deg_of_freedom)
+
+    if force_finite and not np.isfinite(f_statistic).all():
+        # case where there is a perfect (anti-)correlation
+        # f-statistics can be set to the maximum and p-values to zero
+        mask_inf = np.isinf(f_statistic)
+        f_statistic[mask_inf] = np.finfo(f_statistic.dtype).max
+        # case where the target or some features are constant
+        # f-statistics would be minimum and thus p-values large
+        mask_nan = np.isnan(f_statistic)
+        f_statistic[mask_nan] = 0.0
+        p_values[mask_nan] = 1.0
+    return f_statistic, p_values
+
+
+######################################################################
+# Base classes
+
+
+class _BaseFilter(SelectorMixin, BaseEstimator):
+    """Initialize the univariate feature selection.
+
+    Parameters
+    ----------
+    score_func : callable
+        Function taking two arrays X and y, and returning a pair of arrays
+        (scores, pvalues) or a single array with scores.
+    """
+
+    _parameter_constraints: dict = {"score_func": [callable]}
+
+    def __init__(self, score_func):
+        self.score_func = score_func
+
+    @_fit_context(prefer_skip_nested_validation=True)
+    def fit(self, X, y=None):
+        """Run score function on (X, y) and get the appropriate features.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            The training input samples.
+
+        y : array-like of shape (n_samples,) or None
+            The target values (class labels in classification, real numbers in
+            regression). If the selector is unsupervised then `y` can be set to `None`.
+
+        Returns
+        -------
+        self : object
+            Returns the instance itself.
+        """
+        if y is None:
+            X = validate_data(self, X, accept_sparse=["csr", "csc"])
+        else:
+            X, y = validate_data(
+                self, X, y, accept_sparse=["csr", "csc"], multi_output=True
+            )
+
+        self._check_params(X, y)
+        score_func_ret = self.score_func(X, y)
+        if isinstance(score_func_ret, (list, tuple)):
+            self.scores_, self.pvalues_ = score_func_ret
+            self.pvalues_ = np.asarray(self.pvalues_)
+        else:
+            self.scores_ = score_func_ret
+            self.pvalues_ = None
+
+        self.scores_ = np.asarray(self.scores_)
+
+        return self
+
+    def _check_params(self, X, y):
+        pass
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.target_tags.required = True
+        tags.input_tags.sparse = True
+        return tags
+
+
+######################################################################
+# Specific filters
+######################################################################
+class SelectPercentile(_BaseFilter):
+    """Select features according to a percentile of the highest scores.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    score_func : callable, default=f_classif
+        Function taking two arrays X and y, and returning a pair of arrays
+        (scores, pvalues) or a single array with scores.
+        Default is f_classif (see below "See Also"). The default function only
+        works with classification tasks.
+
+        .. versionadded:: 0.18
+
+    percentile : int, default=10
+        Percent of features to keep.
+
+    Attributes
+    ----------
+    scores_ : array-like of shape (n_features,)
+        Scores of features.
+
+    pvalues_ : array-like of shape (n_features,)
+        p-values of feature scores, None if `score_func` returned only scores.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    f_classif : ANOVA F-value between label/feature for classification tasks.
+    mutual_info_classif : Mutual information for a discrete target.
+    chi2 : Chi-squared stats of non-negative features for classification tasks.
+    f_regression : F-value between label/feature for regression tasks.
+    mutual_info_regression : Mutual information for a continuous target.
+    SelectKBest : Select features based on the k highest scores.
+    SelectFpr : Select features based on a false positive rate test.
+    SelectFdr : Select features based on an estimated false discovery rate.
+    SelectFwe : Select features based on family-wise error rate.
+    GenericUnivariateSelect : Univariate feature selector with configurable
+        mode.
+
+    Notes
+    -----
+    Ties between features with equal scores will be broken in an unspecified
+    way.
+
+    This filter supports unsupervised feature selection that only requests `X` for
+    computing the scores.
+
+    Examples
+    --------
+    >>> from sklearn.datasets import load_digits
+    >>> from sklearn.feature_selection import SelectPercentile, chi2
+    >>> X, y = load_digits(return_X_y=True)
+    >>> X.shape
+    (1797, 64)
+    >>> X_new = SelectPercentile(chi2, percentile=10).fit_transform(X, y)
+    >>> X_new.shape
+    (1797, 7)
+    """
+
+    _parameter_constraints: dict = {
+        **_BaseFilter._parameter_constraints,
+        "percentile": [Interval(Real, 0, 100, closed="both")],
+    }
+
+    def __init__(self, score_func=f_classif, *, percentile=10):
+        super().__init__(score_func=score_func)
+        self.percentile = percentile
+
+    def _get_support_mask(self):
+        check_is_fitted(self)
+
+        # Cater for NaNs
+        if self.percentile == 100:
+            return np.ones(len(self.scores_), dtype=bool)
+        elif self.percentile == 0:
+            return np.zeros(len(self.scores_), dtype=bool)
+
+        scores = _clean_nans(self.scores_)
+        threshold = np.percentile(scores, 100 - self.percentile)
+        mask = scores > threshold
+        ties = np.where(scores == threshold)[0]
+        if len(ties):
+            max_feats = int(len(scores) * self.percentile / 100)
+            kept_ties = ties[: max_feats - mask.sum()]
+            mask[kept_ties] = True
+        return mask
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.target_tags.required = False
+        return tags
+
+
+class SelectKBest(_BaseFilter):
+    """Select features according to the k highest scores.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    score_func : callable, default=f_classif
+        Function taking two arrays X and y, and returning a pair of arrays
+        (scores, pvalues) or a single array with scores.
+        Default is f_classif (see below "See Also"). The default function only
+        works with classification tasks.
+
+        .. versionadded:: 0.18
+
+    k : int or "all", default=10
+        Number of top features to select.
+        The "all" option bypasses selection, for use in a parameter search.
+
+    Attributes
+    ----------
+    scores_ : array-like of shape (n_features,)
+        Scores of features.
+
+    pvalues_ : array-like of shape (n_features,)
+        p-values of feature scores, None if `score_func` returned only scores.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    f_classif: ANOVA F-value between label/feature for classification tasks.
+    mutual_info_classif: Mutual information for a discrete target.
+    chi2: Chi-squared stats of non-negative features for classification tasks.
+    f_regression: F-value between label/feature for regression tasks.
+    mutual_info_regression: Mutual information for a continuous target.
+    SelectPercentile: Select features based on percentile of the highest
+        scores.
+    SelectFpr : Select features based on a false positive rate test.
+    SelectFdr : Select features based on an estimated false discovery rate.
+    SelectFwe : Select features based on family-wise error rate.
+    GenericUnivariateSelect : Univariate feature selector with configurable
+        mode.
+
+    Notes
+    -----
+    Ties between features with equal scores will be broken in an unspecified
+    way.
+
+    This filter supports unsupervised feature selection that only requests `X` for
+    computing the scores.
+
+    Examples
+    --------
+    >>> from sklearn.datasets import load_digits
+    >>> from sklearn.feature_selection import SelectKBest, chi2
+    >>> X, y = load_digits(return_X_y=True)
+    >>> X.shape
+    (1797, 64)
+    >>> X_new = SelectKBest(chi2, k=20).fit_transform(X, y)
+    >>> X_new.shape
+    (1797, 20)
+    """
+
+    _parameter_constraints: dict = {
+        **_BaseFilter._parameter_constraints,
+        "k": [StrOptions({"all"}), Interval(Integral, 0, None, closed="left")],
+    }
+
+    def __init__(self, score_func=f_classif, *, k=10):
+        super().__init__(score_func=score_func)
+        self.k = k
+
+    def _check_params(self, X, y):
+        if not isinstance(self.k, str) and self.k > X.shape[1]:
+            warnings.warn(
+                f"k={self.k} is greater than n_features={X.shape[1]}. "
+                "All the features will be returned."
+            )
+
+    def _get_support_mask(self):
+        check_is_fitted(self)
+
+        if self.k == "all":
+            return np.ones(self.scores_.shape, dtype=bool)
+        elif self.k == 0:
+            return np.zeros(self.scores_.shape, dtype=bool)
+        else:
+            scores = _clean_nans(self.scores_)
+            mask = np.zeros(scores.shape, dtype=bool)
+
+            # Request a stable sort. Mergesort takes more memory (~40MB per
+            # megafeature on x86-64).
+            mask[np.argsort(scores, kind="mergesort")[-self.k :]] = 1
+            return mask
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.target_tags.required = False
+        return tags
+
+
+class SelectFpr(_BaseFilter):
+    """Filter: Select the pvalues below alpha based on a FPR test.
+
+    FPR test stands for False Positive Rate test. It controls the total
+    amount of false detections.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    score_func : callable, default=f_classif
+        Function taking two arrays X and y, and returning a pair of arrays
+        (scores, pvalues).
+        Default is f_classif (see below "See Also"). The default function only
+        works with classification tasks.
+
+    alpha : float, default=5e-2
+        Features with p-values less than `alpha` are selected.
+
+    Attributes
+    ----------
+    scores_ : array-like of shape (n_features,)
+        Scores of features.
+
+    pvalues_ : array-like of shape (n_features,)
+        p-values of feature scores.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    f_classif : ANOVA F-value between label/feature for classification tasks.
+    chi2 : Chi-squared stats of non-negative features for classification tasks.
+    mutual_info_classif: Mutual information for a discrete target.
+    f_regression : F-value between label/feature for regression tasks.
+    mutual_info_regression : Mutual information for a continuous target.
+    SelectPercentile : Select features based on percentile of the highest
+        scores.
+    SelectKBest : Select features based on the k highest scores.
+    SelectFdr : Select features based on an estimated false discovery rate.
+    SelectFwe : Select features based on family-wise error rate.
+    GenericUnivariateSelect : Univariate feature selector with configurable
+        mode.
+
+    Examples
+    --------
+    >>> from sklearn.datasets import load_breast_cancer
+    >>> from sklearn.feature_selection import SelectFpr, chi2
+    >>> X, y = load_breast_cancer(return_X_y=True)
+    >>> X.shape
+    (569, 30)
+    >>> X_new = SelectFpr(chi2, alpha=0.01).fit_transform(X, y)
+    >>> X_new.shape
+    (569, 16)
+    """
+
+    _parameter_constraints: dict = {
+        **_BaseFilter._parameter_constraints,
+        "alpha": [Interval(Real, 0, 1, closed="both")],
+    }
+
+    def __init__(self, score_func=f_classif, *, alpha=5e-2):
+        super().__init__(score_func=score_func)
+        self.alpha = alpha
+
+    def _get_support_mask(self):
+        check_is_fitted(self)
+
+        return self.pvalues_ < self.alpha
+
+
+class SelectFdr(_BaseFilter):
+    """Filter: Select the p-values for an estimated false discovery rate.
+
+    This uses the Benjamini-Hochberg procedure. ``alpha`` is an upper bound
+    on the expected false discovery rate.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    score_func : callable, default=f_classif
+        Function taking two arrays X and y, and returning a pair of arrays
+        (scores, pvalues).
+        Default is f_classif (see below "See Also"). The default function only
+        works with classification tasks.
+
+    alpha : float, default=5e-2
+        The highest uncorrected p-value for features to keep.
+
+    Attributes
+    ----------
+    scores_ : array-like of shape (n_features,)
+        Scores of features.
+
+    pvalues_ : array-like of shape (n_features,)
+        p-values of feature scores.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    f_classif : ANOVA F-value between label/feature for classification tasks.
+    mutual_info_classif : Mutual information for a discrete target.
+    chi2 : Chi-squared stats of non-negative features for classification tasks.
+    f_regression : F-value between label/feature for regression tasks.
+    mutual_info_regression : Mutual information for a continuous target.
+    SelectPercentile : Select features based on percentile of the highest
+        scores.
+    SelectKBest : Select features based on the k highest scores.
+    SelectFpr : Select features based on a false positive rate test.
+    SelectFwe : Select features based on family-wise error rate.
+    GenericUnivariateSelect : Univariate feature selector with configurable
+        mode.
+
+    References
+    ----------
+    https://en.wikipedia.org/wiki/False_discovery_rate
+
+    Examples
+    --------
+    >>> from sklearn.datasets import load_breast_cancer
+    >>> from sklearn.feature_selection import SelectFdr, chi2
+    >>> X, y = load_breast_cancer(return_X_y=True)
+    >>> X.shape
+    (569, 30)
+    >>> X_new = SelectFdr(chi2, alpha=0.01).fit_transform(X, y)
+    >>> X_new.shape
+    (569, 16)
+    """
+
+    _parameter_constraints: dict = {
+        **_BaseFilter._parameter_constraints,
+        "alpha": [Interval(Real, 0, 1, closed="both")],
+    }
+
+    def __init__(self, score_func=f_classif, *, alpha=5e-2):
+        super().__init__(score_func=score_func)
+        self.alpha = alpha
+
+    def _get_support_mask(self):
+        check_is_fitted(self)
+
+        n_features = len(self.pvalues_)
+        sv = np.sort(self.pvalues_)
+        selected = sv[
+            sv <= float(self.alpha) / n_features * np.arange(1, n_features + 1)
+        ]
+        if selected.size == 0:
+            return np.zeros_like(self.pvalues_, dtype=bool)
+        return self.pvalues_ <= selected.max()
+
+
+class SelectFwe(_BaseFilter):
+    """Filter: Select the p-values corresponding to Family-wise error rate.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    score_func : callable, default=f_classif
+        Function taking two arrays X and y, and returning a pair of arrays
+        (scores, pvalues).
+        Default is f_classif (see below "See Also"). The default function only
+        works with classification tasks.
+
+    alpha : float, default=5e-2
+        The highest uncorrected p-value for features to keep.
+
+    Attributes
+    ----------
+    scores_ : array-like of shape (n_features,)
+        Scores of features.
+
+    pvalues_ : array-like of shape (n_features,)
+        p-values of feature scores.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    f_classif : ANOVA F-value between label/feature for classification tasks.
+    chi2 : Chi-squared stats of non-negative features for classification tasks.
+    f_regression : F-value between label/feature for regression tasks.
+    SelectPercentile : Select features based on percentile of the highest
+        scores.
+    SelectKBest : Select features based on the k highest scores.
+    SelectFpr : Select features based on a false positive rate test.
+    SelectFdr : Select features based on an estimated false discovery rate.
+    GenericUnivariateSelect : Univariate feature selector with configurable
+        mode.
+
+    Examples
+    --------
+    >>> from sklearn.datasets import load_breast_cancer
+    >>> from sklearn.feature_selection import SelectFwe, chi2
+    >>> X, y = load_breast_cancer(return_X_y=True)
+    >>> X.shape
+    (569, 30)
+    >>> X_new = SelectFwe(chi2, alpha=0.01).fit_transform(X, y)
+    >>> X_new.shape
+    (569, 15)
+    """
+
+    _parameter_constraints: dict = {
+        **_BaseFilter._parameter_constraints,
+        "alpha": [Interval(Real, 0, 1, closed="both")],
+    }
+
+    def __init__(self, score_func=f_classif, *, alpha=5e-2):
+        super().__init__(score_func=score_func)
+        self.alpha = alpha
+
+    def _get_support_mask(self):
+        check_is_fitted(self)
+
+        return self.pvalues_ < self.alpha / len(self.pvalues_)
+
+
+######################################################################
+# Generic filter
+######################################################################
+
+
+# TODO this class should fit on either p-values or scores,
+# depending on the mode.
+class GenericUnivariateSelect(_BaseFilter):
+    """Univariate feature selector with configurable strategy.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    score_func : callable, default=f_classif
+        Function taking two arrays X and y, and returning a pair of arrays
+        (scores, pvalues). For modes 'percentile' or 'kbest' it can return
+        a single array scores.
+
+    mode : {'percentile', 'k_best', 'fpr', 'fdr', 'fwe'}, default='percentile'
+        Feature selection mode. Note that the `'percentile'` and `'kbest'`
+        modes are supporting unsupervised feature selection (when `y` is `None`).
+
+    param : "all", float or int, default=1e-5
+        Parameter of the corresponding mode.
+
+    Attributes
+    ----------
+    scores_ : array-like of shape (n_features,)
+        Scores of features.
+
+    pvalues_ : array-like of shape (n_features,)
+        p-values of feature scores, None if `score_func` returned scores only.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    f_classif : ANOVA F-value between label/feature for classification tasks.
+    mutual_info_classif : Mutual information for a discrete target.
+    chi2 : Chi-squared stats of non-negative features for classification tasks.
+    f_regression : F-value between label/feature for regression tasks.
+    mutual_info_regression : Mutual information for a continuous target.
+    SelectPercentile : Select features based on percentile of the highest
+        scores.
+    SelectKBest : Select features based on the k highest scores.
+    SelectFpr : Select features based on a false positive rate test.
+    SelectFdr : Select features based on an estimated false discovery rate.
+    SelectFwe : Select features based on family-wise error rate.
+
+    Examples
+    --------
+    >>> from sklearn.datasets import load_breast_cancer
+    >>> from sklearn.feature_selection import GenericUnivariateSelect, chi2
+    >>> X, y = load_breast_cancer(return_X_y=True)
+    >>> X.shape
+    (569, 30)
+    >>> transformer = GenericUnivariateSelect(chi2, mode='k_best', param=20)
+    >>> X_new = transformer.fit_transform(X, y)
+    >>> X_new.shape
+    (569, 20)
+    """
+
+    _selection_modes: dict = {
+        "percentile": SelectPercentile,
+        "k_best": SelectKBest,
+        "fpr": SelectFpr,
+        "fdr": SelectFdr,
+        "fwe": SelectFwe,
+    }
+
+    _parameter_constraints: dict = {
+        **_BaseFilter._parameter_constraints,
+        "mode": [StrOptions(set(_selection_modes.keys()))],
+        "param": [Interval(Real, 0, None, closed="left"), StrOptions({"all"})],
+    }
+
+    def __init__(self, score_func=f_classif, *, mode="percentile", param=1e-5):
+        super().__init__(score_func=score_func)
+        self.mode = mode
+        self.param = param
+
+    def _make_selector(self):
+        selector = self._selection_modes[self.mode](score_func=self.score_func)
+
+        # Now perform some acrobatics to set the right named parameter in
+        # the selector
+        possible_params = selector._get_param_names()
+        possible_params.remove("score_func")
+        selector.set_params(**{possible_params[0]: self.param})
+
+        return selector
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.transformer_tags.preserves_dtype = ["float64", "float32"]
+        return tags
+
+    def _check_params(self, X, y):
+        self._make_selector()._check_params(X, y)
+
+    def _get_support_mask(self):
+        check_is_fitted(self)
+
+        selector = self._make_selector()
+        selector.pvalues_ = self.pvalues_
+        selector.scores_ = self.scores_
+        return selector._get_support_mask()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_variance_threshold.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_variance_threshold.py
new file mode 100644
index 0000000000000000000000000000000000000000..f26d70ecf8f82ab317103ba73b52f85b3af5e524
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/_variance_threshold.py
@@ -0,0 +1,141 @@
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+from numbers import Real
+
+import numpy as np
+
+from ..base import BaseEstimator, _fit_context
+from ..utils._param_validation import Interval
+from ..utils.sparsefuncs import mean_variance_axis, min_max_axis
+from ..utils.validation import check_is_fitted, validate_data
+from ._base import SelectorMixin
+
+
+class VarianceThreshold(SelectorMixin, BaseEstimator):
+    """Feature selector that removes all low-variance features.
+
+    This feature selection algorithm looks only at the features (X), not the
+    desired outputs (y), and can thus be used for unsupervised learning.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    threshold : float, default=0
+        Features with a training-set variance lower than this threshold will
+        be removed. The default is to keep all features with non-zero variance,
+        i.e. remove the features that have the same value in all samples.
+
+    Attributes
+    ----------
+    variances_ : array, shape (n_features,)
+        Variances of individual features.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    SelectFromModel: Meta-transformer for selecting features based on
+        importance weights.
+    SelectPercentile : Select features according to a percentile of the highest
+        scores.
+    SequentialFeatureSelector : Transformer that performs Sequential Feature
+        Selection.
+
+    Notes
+    -----
+    Allows NaN in the input.
+    Raises ValueError if no feature in X meets the variance threshold.
+
+    Examples
+    --------
+    The following dataset has integer features, two of which are the same
+    in every sample. These are removed with the default setting for threshold::
+
+        >>> from sklearn.feature_selection import VarianceThreshold
+        >>> X = [[0, 2, 0, 3], [0, 1, 4, 3], [0, 1, 1, 3]]
+        >>> selector = VarianceThreshold()
+        >>> selector.fit_transform(X)
+        array([[2, 0],
+               [1, 4],
+               [1, 1]])
+    """
+
+    _parameter_constraints: dict = {
+        "threshold": [Interval(Real, 0, None, closed="left")]
+    }
+
+    def __init__(self, threshold=0.0):
+        self.threshold = threshold
+
+    @_fit_context(prefer_skip_nested_validation=True)
+    def fit(self, X, y=None):
+        """Learn empirical variances from X.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix}, shape (n_samples, n_features)
+            Data from which to compute variances, where `n_samples` is
+            the number of samples and `n_features` is the number of features.
+
+        y : any, default=None
+            Ignored. This parameter exists only for compatibility with
+            sklearn.pipeline.Pipeline.
+
+        Returns
+        -------
+        self : object
+            Returns the instance itself.
+        """
+        X = validate_data(
+            self,
+            X,
+            accept_sparse=("csr", "csc"),
+            dtype=np.float64,
+            ensure_all_finite="allow-nan",
+        )
+
+        if hasattr(X, "toarray"):  # sparse matrix
+            _, self.variances_ = mean_variance_axis(X, axis=0)
+            if self.threshold == 0:
+                mins, maxes = min_max_axis(X, axis=0)
+                peak_to_peaks = maxes - mins
+        else:
+            self.variances_ = np.nanvar(X, axis=0)
+            if self.threshold == 0:
+                peak_to_peaks = np.ptp(X, axis=0)
+
+        if self.threshold == 0:
+            # Use peak-to-peak to avoid numeric precision issues
+            # for constant features
+            compare_arr = np.array([self.variances_, peak_to_peaks])
+            self.variances_ = np.nanmin(compare_arr, axis=0)
+
+        if np.all(~np.isfinite(self.variances_) | (self.variances_ <= self.threshold)):
+            msg = "No feature in X meets the variance threshold {0:.5f}"
+            if X.shape[0] == 1:
+                msg += " (X contains only one sample)"
+            raise ValueError(msg.format(self.threshold))
+
+        return self
+
+    def _get_support_mask(self):
+        check_is_fitted(self)
+
+        return self.variances_ > self.threshold
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.input_tags.allow_nan = True
+        tags.input_tags.sparse = True
+        return tags
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_base.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bf51a80f01baa1a4340335ce397aeb0ca3e4b5f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_base.py
@@ -0,0 +1,154 @@
+import numpy as np
+import pytest
+from numpy.testing import assert_array_equal
+
+from sklearn.base import BaseEstimator
+from sklearn.feature_selection._base import SelectorMixin
+from sklearn.utils.fixes import CSC_CONTAINERS
+from sklearn.utils.validation import validate_data
+
+
+class StepSelector(SelectorMixin, BaseEstimator):
+    """Retain every `step` features (beginning with 0).
+
+    If `step < 1`, then no features are selected.
+    """
+
+    def __init__(self, step=2):
+        self.step = step
+
+    def fit(self, X, y=None):
+        X = validate_data(self, X, accept_sparse="csc")
+        return self
+
+    def _get_support_mask(self):
+        mask = np.zeros(self.n_features_in_, dtype=bool)
+        if self.step >= 1:
+            mask[:: self.step] = True
+        return mask
+
+
+support = [True, False] * 5
+support_inds = [0, 2, 4, 6, 8]
+X = np.arange(20).reshape(2, 10)
+Xt = np.arange(0, 20, 2).reshape(2, 5)
+Xinv = X.copy()
+Xinv[:, 1::2] = 0
+y = [0, 1]
+feature_names = list("ABCDEFGHIJ")
+feature_names_t = feature_names[::2]
+feature_names_inv = np.array(feature_names)
+feature_names_inv[1::2] = ""
+
+
+def test_transform_dense():
+    sel = StepSelector()
+    Xt_actual = sel.fit(X, y).transform(X)
+    Xt_actual2 = StepSelector().fit_transform(X, y)
+    assert_array_equal(Xt, Xt_actual)
+    assert_array_equal(Xt, Xt_actual2)
+
+    # Check dtype matches
+    assert np.int32 == sel.transform(X.astype(np.int32)).dtype
+    assert np.float32 == sel.transform(X.astype(np.float32)).dtype
+
+    # Check 1d list and other dtype:
+    names_t_actual = sel.transform([feature_names])
+    assert_array_equal(feature_names_t, names_t_actual.ravel())
+
+    # Check wrong shape raises error
+    with pytest.raises(ValueError):
+        sel.transform(np.array([[1], [2]]))
+
+
+@pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
+def test_transform_sparse(csc_container):
+    X_sp = csc_container(X)
+    sel = StepSelector()
+    Xt_actual = sel.fit(X_sp).transform(X_sp)
+    Xt_actual2 = sel.fit_transform(X_sp)
+    assert_array_equal(Xt, Xt_actual.toarray())
+    assert_array_equal(Xt, Xt_actual2.toarray())
+
+    # Check dtype matches
+    assert np.int32 == sel.transform(X_sp.astype(np.int32)).dtype
+    assert np.float32 == sel.transform(X_sp.astype(np.float32)).dtype
+
+    # Check wrong shape raises error
+    with pytest.raises(ValueError):
+        sel.transform(np.array([[1], [2]]))
+
+
+def test_inverse_transform_dense():
+    sel = StepSelector()
+    Xinv_actual = sel.fit(X, y).inverse_transform(Xt)
+    assert_array_equal(Xinv, Xinv_actual)
+
+    # Check dtype matches
+    assert np.int32 == sel.inverse_transform(Xt.astype(np.int32)).dtype
+    assert np.float32 == sel.inverse_transform(Xt.astype(np.float32)).dtype
+
+    # Check 1d list and other dtype:
+    names_inv_actual = sel.inverse_transform([feature_names_t])
+    assert_array_equal(feature_names_inv, names_inv_actual.ravel())
+
+    # Check wrong shape raises error
+    with pytest.raises(ValueError):
+        sel.inverse_transform(np.array([[1], [2]]))
+
+
+@pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
+def test_inverse_transform_sparse(csc_container):
+    X_sp = csc_container(X)
+    Xt_sp = csc_container(Xt)
+    sel = StepSelector()
+    Xinv_actual = sel.fit(X_sp).inverse_transform(Xt_sp)
+    assert_array_equal(Xinv, Xinv_actual.toarray())
+
+    # Check dtype matches
+    assert np.int32 == sel.inverse_transform(Xt_sp.astype(np.int32)).dtype
+    assert np.float32 == sel.inverse_transform(Xt_sp.astype(np.float32)).dtype
+
+    # Check wrong shape raises error
+    with pytest.raises(ValueError):
+        sel.inverse_transform(np.array([[1], [2]]))
+
+
+def test_get_support():
+    sel = StepSelector()
+    sel.fit(X, y)
+    assert_array_equal(support, sel.get_support())
+    assert_array_equal(support_inds, sel.get_support(indices=True))
+
+
+def test_output_dataframe():
+    """Check output dtypes for dataframes is consistent with the input dtypes."""
+    pd = pytest.importorskip("pandas")
+
+    X = pd.DataFrame(
+        {
+            "a": pd.Series([1.0, 2.4, 4.5], dtype=np.float32),
+            "b": pd.Series(["a", "b", "a"], dtype="category"),
+            "c": pd.Series(["j", "b", "b"], dtype="category"),
+            "d": pd.Series([3.0, 2.4, 1.2], dtype=np.float64),
+        }
+    )
+
+    for step in [2, 3]:
+        sel = StepSelector(step=step).set_output(transform="pandas")
+        sel.fit(X)
+
+        output = sel.transform(X)
+        for name, dtype in output.dtypes.items():
+            assert dtype == X.dtypes[name]
+
+    # step=0 will select nothing
+    sel0 = StepSelector(step=0).set_output(transform="pandas")
+    sel0.fit(X, y)
+
+    msg = "No features were selected"
+    with pytest.warns(UserWarning, match=msg):
+        output0 = sel0.transform(X)
+
+    assert_array_equal(output0.index, X.index)
+    assert output0.shape == (X.shape[0], 0)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_chi2.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_chi2.py
new file mode 100644
index 0000000000000000000000000000000000000000..c50def36f1b6c281e6c96019355b901bf4326a38
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_chi2.py
@@ -0,0 +1,93 @@
+"""
+Tests for chi2, currently the only feature selection function designed
+specifically to work with sparse matrices.
+"""
+
+import warnings
+
+import numpy as np
+import pytest
+import scipy.stats
+
+from sklearn.feature_selection import SelectKBest, chi2
+from sklearn.feature_selection._univariate_selection import _chisquare
+from sklearn.utils._testing import assert_array_almost_equal, assert_array_equal
+from sklearn.utils.fixes import COO_CONTAINERS, CSR_CONTAINERS
+
+# Feature 0 is highly informative for class 1;
+# feature 1 is the same everywhere;
+# feature 2 is a bit informative for class 2.
+X = [[2, 1, 2], [9, 1, 1], [6, 1, 2], [0, 1, 2]]
+y = [0, 1, 2, 2]
+
+
+def mkchi2(k):
+    """Make k-best chi2 selector"""
+    return SelectKBest(chi2, k=k)
+
+
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_chi2(csr_container):
+    # Test Chi2 feature extraction
+
+    chi2 = mkchi2(k=1).fit(X, y)
+    chi2 = mkchi2(k=1).fit(X, y)
+    assert_array_equal(chi2.get_support(indices=True), [0])
+    assert_array_equal(chi2.transform(X), np.array(X)[:, [0]])
+
+    chi2 = mkchi2(k=2).fit(X, y)
+    assert_array_equal(sorted(chi2.get_support(indices=True)), [0, 2])
+
+    Xsp = csr_container(X, dtype=np.float64)
+    chi2 = mkchi2(k=2).fit(Xsp, y)
+    assert_array_equal(sorted(chi2.get_support(indices=True)), [0, 2])
+    Xtrans = chi2.transform(Xsp)
+    assert_array_equal(Xtrans.shape, [Xsp.shape[0], 2])
+
+    # == doesn't work on scipy.sparse matrices
+    Xtrans = Xtrans.toarray()
+    Xtrans2 = mkchi2(k=2).fit_transform(Xsp, y).toarray()
+    assert_array_almost_equal(Xtrans, Xtrans2)
+
+
+@pytest.mark.parametrize("coo_container", COO_CONTAINERS)
+def test_chi2_coo(coo_container):
+    # Check that chi2 works with a COO matrix
+    # (as returned by CountVectorizer, DictVectorizer)
+    Xcoo = coo_container(X)
+    mkchi2(k=2).fit_transform(Xcoo, y)
+    # if we got here without an exception, we're safe
+
+
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_chi2_negative(csr_container):
+    # Check for proper error on negative numbers in the input X.
+    X, y = [[0, 1], [-1e-20, 1]], [0, 1]
+    for X in (X, np.array(X), csr_container(X)):
+        with pytest.raises(ValueError):
+            chi2(X, y)
+
+
+def test_chi2_unused_feature():
+    # Unused feature should evaluate to NaN
+    # and should issue no runtime warning
+    with warnings.catch_warnings(record=True) as warned:
+        warnings.simplefilter("always")
+        chi, p = chi2([[1, 0], [0, 0]], [1, 0])
+        for w in warned:
+            if "divide by zero" in repr(w):
+                raise AssertionError("Found unexpected warning %s" % w)
+    assert_array_equal(chi, [1, np.nan])
+    assert_array_equal(p[1], np.nan)
+
+
+def test_chisquare():
+    # Test replacement for scipy.stats.chisquare against the original.
+    obs = np.array([[2.0, 2.0], [1.0, 1.0]])
+    exp = np.array([[1.5, 1.5], [1.5, 1.5]])
+    # call SciPy first because our version overwrites obs
+    chi_scp, p_scp = scipy.stats.chisquare(obs, exp)
+    chi_our, p_our = _chisquare(obs, exp)
+
+    assert_array_almost_equal(chi_scp, chi_our)
+    assert_array_almost_equal(p_scp, p_our)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_feature_select.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_feature_select.py
new file mode 100644
index 0000000000000000000000000000000000000000..d7bffec5159bfc7ba8faf452a218d5147906419c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_feature_select.py
@@ -0,0 +1,1018 @@
+"""
+Todo: cross-check the F-value with stats model
+"""
+
+import itertools
+import warnings
+
+import numpy as np
+import pytest
+from numpy.testing import assert_allclose
+from scipy import sparse, stats
+
+from sklearn.datasets import load_iris, make_classification, make_regression
+from sklearn.feature_selection import (
+    GenericUnivariateSelect,
+    SelectFdr,
+    SelectFpr,
+    SelectFwe,
+    SelectKBest,
+    SelectPercentile,
+    chi2,
+    f_classif,
+    f_oneway,
+    f_regression,
+    mutual_info_classif,
+    mutual_info_regression,
+    r_regression,
+)
+from sklearn.utils import safe_mask
+from sklearn.utils._testing import (
+    _convert_container,
+    assert_almost_equal,
+    assert_array_almost_equal,
+    assert_array_equal,
+    ignore_warnings,
+)
+from sklearn.utils.fixes import CSR_CONTAINERS
+
+##############################################################################
+# Test the score functions
+
+
+def test_f_oneway_vs_scipy_stats():
+    # Test that our f_oneway gives the same result as scipy.stats
+    rng = np.random.RandomState(0)
+    X1 = rng.randn(10, 3)
+    X2 = 1 + rng.randn(10, 3)
+    f, pv = stats.f_oneway(X1, X2)
+    f2, pv2 = f_oneway(X1, X2)
+    assert np.allclose(f, f2)
+    assert np.allclose(pv, pv2)
+
+
+def test_f_oneway_ints():
+    # Smoke test f_oneway on integers: that it does raise casting errors
+    # with recent numpys
+    rng = np.random.RandomState(0)
+    X = rng.randint(10, size=(10, 10))
+    y = np.arange(10)
+    fint, pint = f_oneway(X, y)
+
+    # test that is gives the same result as with float
+    f, p = f_oneway(X.astype(float), y)
+    assert_array_almost_equal(f, fint, decimal=4)
+    assert_array_almost_equal(p, pint, decimal=4)
+
+
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_f_classif(csr_container):
+    # Test whether the F test yields meaningful results
+    # on a simple simulated classification problem
+    X, y = make_classification(
+        n_samples=200,
+        n_features=20,
+        n_informative=3,
+        n_redundant=2,
+        n_repeated=0,
+        n_classes=8,
+        n_clusters_per_class=1,
+        flip_y=0.0,
+        class_sep=10,
+        shuffle=False,
+        random_state=0,
+    )
+
+    F, pv = f_classif(X, y)
+    F_sparse, pv_sparse = f_classif(csr_container(X), y)
+    assert (F > 0).all()
+    assert (pv > 0).all()
+    assert (pv < 1).all()
+    assert (pv[:5] < 0.05).all()
+    assert (pv[5:] > 1.0e-4).all()
+    assert_array_almost_equal(F_sparse, F)
+    assert_array_almost_equal(pv_sparse, pv)
+
+
+@pytest.mark.parametrize("center", [True, False])
+def test_r_regression(center):
+    X, y = make_regression(
+        n_samples=2000, n_features=20, n_informative=5, shuffle=False, random_state=0
+    )
+
+    corr_coeffs = r_regression(X, y, center=center)
+    assert (-1 < corr_coeffs).all()
+    assert (corr_coeffs < 1).all()
+
+    sparse_X = _convert_container(X, "sparse")
+
+    sparse_corr_coeffs = r_regression(sparse_X, y, center=center)
+    assert_allclose(sparse_corr_coeffs, corr_coeffs)
+
+    # Testing against numpy for reference
+    Z = np.hstack((X, y[:, np.newaxis]))
+    correlation_matrix = np.corrcoef(Z, rowvar=False)
+    np_corr_coeffs = correlation_matrix[:-1, -1]
+    assert_array_almost_equal(np_corr_coeffs, corr_coeffs, decimal=3)
+
+
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_f_regression(csr_container):
+    # Test whether the F test yields meaningful results
+    # on a simple simulated regression problem
+    X, y = make_regression(
+        n_samples=200, n_features=20, n_informative=5, shuffle=False, random_state=0
+    )
+
+    F, pv = f_regression(X, y)
+    assert (F > 0).all()
+    assert (pv > 0).all()
+    assert (pv < 1).all()
+    assert (pv[:5] < 0.05).all()
+    assert (pv[5:] > 1.0e-4).all()
+
+    # with centering, compare with sparse
+    F, pv = f_regression(X, y, center=True)
+    F_sparse, pv_sparse = f_regression(csr_container(X), y, center=True)
+    assert_allclose(F_sparse, F)
+    assert_allclose(pv_sparse, pv)
+
+    # again without centering, compare with sparse
+    F, pv = f_regression(X, y, center=False)
+    F_sparse, pv_sparse = f_regression(csr_container(X), y, center=False)
+    assert_allclose(F_sparse, F)
+    assert_allclose(pv_sparse, pv)
+
+
+def test_f_regression_input_dtype():
+    # Test whether f_regression returns the same value
+    # for any numeric data_type
+    rng = np.random.RandomState(0)
+    X = rng.rand(10, 20)
+    y = np.arange(10).astype(int)
+
+    F1, pv1 = f_regression(X, y)
+    F2, pv2 = f_regression(X, y.astype(float))
+    assert_allclose(F1, F2, 5)
+    assert_allclose(pv1, pv2, 5)
+
+
+def test_f_regression_center():
+    # Test whether f_regression preserves dof according to 'center' argument
+    # We use two centered variates so we have a simple relationship between
+    # F-score with variates centering and F-score without variates centering.
+    # Create toy example
+    X = np.arange(-5, 6).reshape(-1, 1)  # X has zero mean
+    n_samples = X.size
+    Y = np.ones(n_samples)
+    Y[::2] *= -1.0
+    Y[0] = 0.0  # have Y mean being null
+
+    F1, _ = f_regression(X, Y, center=True)
+    F2, _ = f_regression(X, Y, center=False)
+    assert_allclose(F1 * (n_samples - 1.0) / (n_samples - 2.0), F2)
+    assert_almost_equal(F2[0], 0.232558139)  # value from statsmodels OLS
+
+
+@pytest.mark.parametrize(
+    "X, y, expected_corr_coef, force_finite",
+    [
+        (
+            # A feature in X is constant - forcing finite
+            np.array([[2, 1], [2, 0], [2, 10], [2, 4]]),
+            np.array([0, 1, 1, 0]),
+            np.array([0.0, 0.32075]),
+            True,
+        ),
+        (
+            # The target y is constant - forcing finite
+            np.array([[5, 1], [3, 0], [2, 10], [8, 4]]),
+            np.array([0, 0, 0, 0]),
+            np.array([0.0, 0.0]),
+            True,
+        ),
+        (
+            # A feature in X is constant - not forcing finite
+            np.array([[2, 1], [2, 0], [2, 10], [2, 4]]),
+            np.array([0, 1, 1, 0]),
+            np.array([np.nan, 0.32075]),
+            False,
+        ),
+        (
+            # The target y is constant - not forcing finite
+            np.array([[5, 1], [3, 0], [2, 10], [8, 4]]),
+            np.array([0, 0, 0, 0]),
+            np.array([np.nan, np.nan]),
+            False,
+        ),
+    ],
+)
+def test_r_regression_force_finite(X, y, expected_corr_coef, force_finite):
+    """Check the behaviour of `force_finite` for some corner cases with `r_regression`.
+
+    Non-regression test for:
+    https://github.com/scikit-learn/scikit-learn/issues/15672
+    """
+    with warnings.catch_warnings():
+        warnings.simplefilter("error", RuntimeWarning)
+        corr_coef = r_regression(X, y, force_finite=force_finite)
+    np.testing.assert_array_almost_equal(corr_coef, expected_corr_coef)
+
+
+@pytest.mark.parametrize(
+    "X, y, expected_f_statistic, expected_p_values, force_finite",
+    [
+        (
+            # A feature in X is constant - forcing finite
+            np.array([[2, 1], [2, 0], [2, 10], [2, 4]]),
+            np.array([0, 1, 1, 0]),
+            np.array([0.0, 0.2293578]),
+            np.array([1.0, 0.67924985]),
+            True,
+        ),
+        (
+            # The target y is constant - forcing finite
+            np.array([[5, 1], [3, 0], [2, 10], [8, 4]]),
+            np.array([0, 0, 0, 0]),
+            np.array([0.0, 0.0]),
+            np.array([1.0, 1.0]),
+            True,
+        ),
+        (
+            # Feature in X correlated with y - forcing finite
+            np.array([[0, 1], [1, 0], [2, 10], [3, 4]]),
+            np.array([0, 1, 2, 3]),
+            np.array([np.finfo(np.float64).max, 0.845433]),
+            np.array([0.0, 0.454913]),
+            True,
+        ),
+        (
+            # Feature in X anti-correlated with y - forcing finite
+            np.array([[3, 1], [2, 0], [1, 10], [0, 4]]),
+            np.array([0, 1, 2, 3]),
+            np.array([np.finfo(np.float64).max, 0.845433]),
+            np.array([0.0, 0.454913]),
+            True,
+        ),
+        (
+            # A feature in X is constant - not forcing finite
+            np.array([[2, 1], [2, 0], [2, 10], [2, 4]]),
+            np.array([0, 1, 1, 0]),
+            np.array([np.nan, 0.2293578]),
+            np.array([np.nan, 0.67924985]),
+            False,
+        ),
+        (
+            # The target y is constant - not forcing finite
+            np.array([[5, 1], [3, 0], [2, 10], [8, 4]]),
+            np.array([0, 0, 0, 0]),
+            np.array([np.nan, np.nan]),
+            np.array([np.nan, np.nan]),
+            False,
+        ),
+        (
+            # Feature in X correlated with y - not forcing finite
+            np.array([[0, 1], [1, 0], [2, 10], [3, 4]]),
+            np.array([0, 1, 2, 3]),
+            np.array([np.inf, 0.845433]),
+            np.array([0.0, 0.454913]),
+            False,
+        ),
+        (
+            # Feature in X anti-correlated with y - not forcing finite
+            np.array([[3, 1], [2, 0], [1, 10], [0, 4]]),
+            np.array([0, 1, 2, 3]),
+            np.array([np.inf, 0.845433]),
+            np.array([0.0, 0.454913]),
+            False,
+        ),
+    ],
+)
+def test_f_regression_corner_case(
+    X, y, expected_f_statistic, expected_p_values, force_finite
+):
+    """Check the behaviour of `force_finite` for some corner cases with `f_regression`.
+
+    Non-regression test for:
+    https://github.com/scikit-learn/scikit-learn/issues/15672
+    """
+    with warnings.catch_warnings():
+        warnings.simplefilter("error", RuntimeWarning)
+        f_statistic, p_values = f_regression(X, y, force_finite=force_finite)
+    np.testing.assert_array_almost_equal(f_statistic, expected_f_statistic)
+    np.testing.assert_array_almost_equal(p_values, expected_p_values)
+
+
+def test_f_classif_multi_class():
+    # Test whether the F test yields meaningful results
+    # on a simple simulated classification problem
+    X, y = make_classification(
+        n_samples=200,
+        n_features=20,
+        n_informative=3,
+        n_redundant=2,
+        n_repeated=0,
+        n_classes=8,
+        n_clusters_per_class=1,
+        flip_y=0.0,
+        class_sep=10,
+        shuffle=False,
+        random_state=0,
+    )
+
+    F, pv = f_classif(X, y)
+    assert (F > 0).all()
+    assert (pv > 0).all()
+    assert (pv < 1).all()
+    assert (pv[:5] < 0.05).all()
+    assert (pv[5:] > 1.0e-4).all()
+
+
+def test_select_percentile_classif():
+    # Test whether the relative univariate feature selection
+    # gets the correct items in a simple classification problem
+    # with the percentile heuristic
+    X, y = make_classification(
+        n_samples=200,
+        n_features=20,
+        n_informative=3,
+        n_redundant=2,
+        n_repeated=0,
+        n_classes=8,
+        n_clusters_per_class=1,
+        flip_y=0.0,
+        class_sep=10,
+        shuffle=False,
+        random_state=0,
+    )
+
+    univariate_filter = SelectPercentile(f_classif, percentile=25)
+    X_r = univariate_filter.fit(X, y).transform(X)
+    X_r2 = (
+        GenericUnivariateSelect(f_classif, mode="percentile", param=25)
+        .fit(X, y)
+        .transform(X)
+    )
+    assert_array_equal(X_r, X_r2)
+    support = univariate_filter.get_support()
+    gtruth = np.zeros(20)
+    gtruth[:5] = 1
+    assert_array_equal(support, gtruth)
+
+
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_select_percentile_classif_sparse(csr_container):
+    # Test whether the relative univariate feature selection
+    # gets the correct items in a simple classification problem
+    # with the percentile heuristic
+    X, y = make_classification(
+        n_samples=200,
+        n_features=20,
+        n_informative=3,
+        n_redundant=2,
+        n_repeated=0,
+        n_classes=8,
+        n_clusters_per_class=1,
+        flip_y=0.0,
+        class_sep=10,
+        shuffle=False,
+        random_state=0,
+    )
+    X = csr_container(X)
+    univariate_filter = SelectPercentile(f_classif, percentile=25)
+    X_r = univariate_filter.fit(X, y).transform(X)
+    X_r2 = (
+        GenericUnivariateSelect(f_classif, mode="percentile", param=25)
+        .fit(X, y)
+        .transform(X)
+    )
+    assert_array_equal(X_r.toarray(), X_r2.toarray())
+    support = univariate_filter.get_support()
+    gtruth = np.zeros(20)
+    gtruth[:5] = 1
+    assert_array_equal(support, gtruth)
+
+    X_r2inv = univariate_filter.inverse_transform(X_r2)
+    assert sparse.issparse(X_r2inv)
+    support_mask = safe_mask(X_r2inv, support)
+    assert X_r2inv.shape == X.shape
+    assert_array_equal(X_r2inv[:, support_mask].toarray(), X_r.toarray())
+    # Check other columns are empty
+    assert X_r2inv.nnz == X_r.nnz
+
+
+##############################################################################
+# Test univariate selection in classification settings
+
+
+def test_select_kbest_classif():
+    # Test whether the relative univariate feature selection
+    # gets the correct items in a simple classification problem
+    # with the k best heuristic
+    X, y = make_classification(
+        n_samples=200,
+        n_features=20,
+        n_informative=3,
+        n_redundant=2,
+        n_repeated=0,
+        n_classes=8,
+        n_clusters_per_class=1,
+        flip_y=0.0,
+        class_sep=10,
+        shuffle=False,
+        random_state=0,
+    )
+
+    univariate_filter = SelectKBest(f_classif, k=5)
+    X_r = univariate_filter.fit(X, y).transform(X)
+    X_r2 = (
+        GenericUnivariateSelect(f_classif, mode="k_best", param=5)
+        .fit(X, y)
+        .transform(X)
+    )
+    assert_array_equal(X_r, X_r2)
+    support = univariate_filter.get_support()
+    gtruth = np.zeros(20)
+    gtruth[:5] = 1
+    assert_array_equal(support, gtruth)
+
+
+def test_select_kbest_all():
+    # Test whether k="all" correctly returns all features.
+    X, y = make_classification(
+        n_samples=20, n_features=10, shuffle=False, random_state=0
+    )
+
+    univariate_filter = SelectKBest(f_classif, k="all")
+    X_r = univariate_filter.fit(X, y).transform(X)
+    assert_array_equal(X, X_r)
+    # Non-regression test for:
+    # https://github.com/scikit-learn/scikit-learn/issues/24949
+    X_r2 = (
+        GenericUnivariateSelect(f_classif, mode="k_best", param="all")
+        .fit(X, y)
+        .transform(X)
+    )
+    assert_array_equal(X_r, X_r2)
+
+
+@pytest.mark.parametrize("dtype_in", [np.float32, np.float64])
+def test_select_kbest_zero(dtype_in):
+    # Test whether k=0 correctly returns no features.
+    X, y = make_classification(
+        n_samples=20, n_features=10, shuffle=False, random_state=0
+    )
+    X = X.astype(dtype_in)
+
+    univariate_filter = SelectKBest(f_classif, k=0)
+    univariate_filter.fit(X, y)
+    support = univariate_filter.get_support()
+    gtruth = np.zeros(10, dtype=bool)
+    assert_array_equal(support, gtruth)
+    with pytest.warns(UserWarning, match="No features were selected"):
+        X_selected = univariate_filter.transform(X)
+    assert X_selected.shape == (20, 0)
+    assert X_selected.dtype == dtype_in
+
+
+def test_select_heuristics_classif():
+    # Test whether the relative univariate feature selection
+    # gets the correct items in a simple classification problem
+    # with the fdr, fwe and fpr heuristics
+    X, y = make_classification(
+        n_samples=200,
+        n_features=20,
+        n_informative=3,
+        n_redundant=2,
+        n_repeated=0,
+        n_classes=8,
+        n_clusters_per_class=1,
+        flip_y=0.0,
+        class_sep=10,
+        shuffle=False,
+        random_state=0,
+    )
+
+    univariate_filter = SelectFwe(f_classif, alpha=0.01)
+    X_r = univariate_filter.fit(X, y).transform(X)
+    gtruth = np.zeros(20)
+    gtruth[:5] = 1
+    for mode in ["fdr", "fpr", "fwe"]:
+        X_r2 = (
+            GenericUnivariateSelect(f_classif, mode=mode, param=0.01)
+            .fit(X, y)
+            .transform(X)
+        )
+        assert_array_equal(X_r, X_r2)
+        support = univariate_filter.get_support()
+        assert_allclose(support, gtruth)
+
+
+##############################################################################
+# Test univariate selection in regression settings
+
+
+def assert_best_scores_kept(score_filter):
+    scores = score_filter.scores_
+    support = score_filter.get_support()
+    assert_allclose(np.sort(scores[support]), np.sort(scores)[-support.sum() :])
+
+
+def test_select_percentile_regression():
+    # Test whether the relative univariate feature selection
+    # gets the correct items in a simple regression problem
+    # with the percentile heuristic
+    X, y = make_regression(
+        n_samples=200, n_features=20, n_informative=5, shuffle=False, random_state=0
+    )
+
+    univariate_filter = SelectPercentile(f_regression, percentile=25)
+    X_r = univariate_filter.fit(X, y).transform(X)
+    assert_best_scores_kept(univariate_filter)
+    X_r2 = (
+        GenericUnivariateSelect(f_regression, mode="percentile", param=25)
+        .fit(X, y)
+        .transform(X)
+    )
+    assert_array_equal(X_r, X_r2)
+    support = univariate_filter.get_support()
+    gtruth = np.zeros(20)
+    gtruth[:5] = 1
+    assert_array_equal(support, gtruth)
+    X_2 = X.copy()
+    X_2[:, np.logical_not(support)] = 0
+    assert_array_equal(X_2, univariate_filter.inverse_transform(X_r))
+    # Check inverse_transform respects dtype
+    assert_array_equal(
+        X_2.astype(bool), univariate_filter.inverse_transform(X_r.astype(bool))
+    )
+
+
+def test_select_percentile_regression_full():
+    # Test whether the relative univariate feature selection
+    # selects all features when '100%' is asked.
+    X, y = make_regression(
+        n_samples=200, n_features=20, n_informative=5, shuffle=False, random_state=0
+    )
+
+    univariate_filter = SelectPercentile(f_regression, percentile=100)
+    X_r = univariate_filter.fit(X, y).transform(X)
+    assert_best_scores_kept(univariate_filter)
+    X_r2 = (
+        GenericUnivariateSelect(f_regression, mode="percentile", param=100)
+        .fit(X, y)
+        .transform(X)
+    )
+    assert_array_equal(X_r, X_r2)
+    support = univariate_filter.get_support()
+    gtruth = np.ones(20)
+    assert_array_equal(support, gtruth)
+
+
+def test_select_kbest_regression():
+    # Test whether the relative univariate feature selection
+    # gets the correct items in a simple regression problem
+    # with the k best heuristic
+    X, y = make_regression(
+        n_samples=200,
+        n_features=20,
+        n_informative=5,
+        shuffle=False,
+        random_state=0,
+        noise=10,
+    )
+
+    univariate_filter = SelectKBest(f_regression, k=5)
+    X_r = univariate_filter.fit(X, y).transform(X)
+    assert_best_scores_kept(univariate_filter)
+    X_r2 = (
+        GenericUnivariateSelect(f_regression, mode="k_best", param=5)
+        .fit(X, y)
+        .transform(X)
+    )
+    assert_array_equal(X_r, X_r2)
+    support = univariate_filter.get_support()
+    gtruth = np.zeros(20)
+    gtruth[:5] = 1
+    assert_array_equal(support, gtruth)
+
+
+def test_select_heuristics_regression():
+    # Test whether the relative univariate feature selection
+    # gets the correct items in a simple regression problem
+    # with the fpr, fdr or fwe heuristics
+    X, y = make_regression(
+        n_samples=200,
+        n_features=20,
+        n_informative=5,
+        shuffle=False,
+        random_state=0,
+        noise=10,
+    )
+
+    univariate_filter = SelectFpr(f_regression, alpha=0.01)
+    X_r = univariate_filter.fit(X, y).transform(X)
+    gtruth = np.zeros(20)
+    gtruth[:5] = 1
+    for mode in ["fdr", "fpr", "fwe"]:
+        X_r2 = (
+            GenericUnivariateSelect(f_regression, mode=mode, param=0.01)
+            .fit(X, y)
+            .transform(X)
+        )
+        assert_array_equal(X_r, X_r2)
+        support = univariate_filter.get_support()
+        assert_array_equal(support[:5], np.ones((5,), dtype=bool))
+        assert np.sum(support[5:] == 1) < 3
+
+
+def test_boundary_case_ch2():
+    # Test boundary case, and always aim to select 1 feature.
+    X = np.array([[10, 20], [20, 20], [20, 30]])
+    y = np.array([[1], [0], [0]])
+    scores, pvalues = chi2(X, y)
+    assert_array_almost_equal(scores, np.array([4.0, 0.71428571]))
+    assert_array_almost_equal(pvalues, np.array([0.04550026, 0.39802472]))
+
+    filter_fdr = SelectFdr(chi2, alpha=0.1)
+    filter_fdr.fit(X, y)
+    support_fdr = filter_fdr.get_support()
+    assert_array_equal(support_fdr, np.array([True, False]))
+
+    filter_kbest = SelectKBest(chi2, k=1)
+    filter_kbest.fit(X, y)
+    support_kbest = filter_kbest.get_support()
+    assert_array_equal(support_kbest, np.array([True, False]))
+
+    filter_percentile = SelectPercentile(chi2, percentile=50)
+    filter_percentile.fit(X, y)
+    support_percentile = filter_percentile.get_support()
+    assert_array_equal(support_percentile, np.array([True, False]))
+
+    filter_fpr = SelectFpr(chi2, alpha=0.1)
+    filter_fpr.fit(X, y)
+    support_fpr = filter_fpr.get_support()
+    assert_array_equal(support_fpr, np.array([True, False]))
+
+    filter_fwe = SelectFwe(chi2, alpha=0.1)
+    filter_fwe.fit(X, y)
+    support_fwe = filter_fwe.get_support()
+    assert_array_equal(support_fwe, np.array([True, False]))
+
+
+@pytest.mark.parametrize("alpha", [0.001, 0.01, 0.1])
+@pytest.mark.parametrize("n_informative", [1, 5, 10])
+def test_select_fdr_regression(alpha, n_informative):
+    # Test that fdr heuristic actually has low FDR.
+    def single_fdr(alpha, n_informative, random_state):
+        X, y = make_regression(
+            n_samples=150,
+            n_features=20,
+            n_informative=n_informative,
+            shuffle=False,
+            random_state=random_state,
+            noise=10,
+        )
+
+        with warnings.catch_warnings(record=True):
+            # Warnings can be raised when no features are selected
+            # (low alpha or very noisy data)
+            univariate_filter = SelectFdr(f_regression, alpha=alpha)
+            X_r = univariate_filter.fit(X, y).transform(X)
+            X_r2 = (
+                GenericUnivariateSelect(f_regression, mode="fdr", param=alpha)
+                .fit(X, y)
+                .transform(X)
+            )
+
+        assert_array_equal(X_r, X_r2)
+        support = univariate_filter.get_support()
+        num_false_positives = np.sum(support[n_informative:] == 1)
+        num_true_positives = np.sum(support[:n_informative] == 1)
+
+        if num_false_positives == 0:
+            return 0.0
+        false_discovery_rate = num_false_positives / (
+            num_true_positives + num_false_positives
+        )
+        return false_discovery_rate
+
+    # As per Benjamini-Hochberg, the expected false discovery rate
+    # should be lower than alpha:
+    # FDR = E(FP / (TP + FP)) <= alpha
+    false_discovery_rate = np.mean(
+        [single_fdr(alpha, n_informative, random_state) for random_state in range(100)]
+    )
+    assert alpha >= false_discovery_rate
+
+    # Make sure that the empirical false discovery rate increases
+    # with alpha:
+    if false_discovery_rate != 0:
+        assert false_discovery_rate > alpha / 10
+
+
+def test_select_fwe_regression():
+    # Test whether the relative univariate feature selection
+    # gets the correct items in a simple regression problem
+    # with the fwe heuristic
+    X, y = make_regression(
+        n_samples=200, n_features=20, n_informative=5, shuffle=False, random_state=0
+    )
+
+    univariate_filter = SelectFwe(f_regression, alpha=0.01)
+    X_r = univariate_filter.fit(X, y).transform(X)
+    X_r2 = (
+        GenericUnivariateSelect(f_regression, mode="fwe", param=0.01)
+        .fit(X, y)
+        .transform(X)
+    )
+    assert_array_equal(X_r, X_r2)
+    support = univariate_filter.get_support()
+    gtruth = np.zeros(20)
+    gtruth[:5] = 1
+    assert_array_equal(support[:5], np.ones((5,), dtype=bool))
+    assert np.sum(support[5:] == 1) < 2
+
+
+def test_selectkbest_tiebreaking():
+    # Test whether SelectKBest actually selects k features in case of ties.
+    # Prior to 0.11, SelectKBest would return more features than requested.
+    Xs = [[0, 1, 1], [0, 0, 1], [1, 0, 0], [1, 1, 0]]
+    y = [1]
+    dummy_score = lambda X, y: (X[0], X[0])
+    for X in Xs:
+        sel = SelectKBest(dummy_score, k=1)
+        X1 = ignore_warnings(sel.fit_transform)([X], y)
+        assert X1.shape[1] == 1
+        assert_best_scores_kept(sel)
+
+        sel = SelectKBest(dummy_score, k=2)
+        X2 = ignore_warnings(sel.fit_transform)([X], y)
+        assert X2.shape[1] == 2
+        assert_best_scores_kept(sel)
+
+
+def test_selectpercentile_tiebreaking():
+    # Test if SelectPercentile selects the right n_features in case of ties.
+    Xs = [[0, 1, 1], [0, 0, 1], [1, 0, 0], [1, 1, 0]]
+    y = [1]
+    dummy_score = lambda X, y: (X[0], X[0])
+    for X in Xs:
+        sel = SelectPercentile(dummy_score, percentile=34)
+        X1 = ignore_warnings(sel.fit_transform)([X], y)
+        assert X1.shape[1] == 1
+        assert_best_scores_kept(sel)
+
+        sel = SelectPercentile(dummy_score, percentile=67)
+        X2 = ignore_warnings(sel.fit_transform)([X], y)
+        assert X2.shape[1] == 2
+        assert_best_scores_kept(sel)
+
+
+def test_tied_pvalues():
+    # Test whether k-best and percentiles work with tied pvalues from chi2.
+    # chi2 will return the same p-values for the following features, but it
+    # will return different scores.
+    X0 = np.array([[10000, 9999, 9998], [1, 1, 1]])
+    y = [0, 1]
+
+    for perm in itertools.permutations((0, 1, 2)):
+        X = X0[:, perm]
+        Xt = SelectKBest(chi2, k=2).fit_transform(X, y)
+        assert Xt.shape == (2, 2)
+        assert 9998 not in Xt
+
+        Xt = SelectPercentile(chi2, percentile=67).fit_transform(X, y)
+        assert Xt.shape == (2, 2)
+        assert 9998 not in Xt
+
+
+def test_scorefunc_multilabel():
+    # Test whether k-best and percentiles works with multilabels with chi2.
+
+    X = np.array([[10000, 9999, 0], [100, 9999, 0], [1000, 99, 0]])
+    y = [[1, 1], [0, 1], [1, 0]]
+
+    Xt = SelectKBest(chi2, k=2).fit_transform(X, y)
+    assert Xt.shape == (3, 2)
+    assert 0 not in Xt
+
+    Xt = SelectPercentile(chi2, percentile=67).fit_transform(X, y)
+    assert Xt.shape == (3, 2)
+    assert 0 not in Xt
+
+
+def test_tied_scores():
+    # Test for stable sorting in k-best with tied scores.
+    X_train = np.array([[0, 0, 0], [1, 1, 1]])
+    y_train = [0, 1]
+
+    for n_features in [1, 2, 3]:
+        sel = SelectKBest(chi2, k=n_features).fit(X_train, y_train)
+        X_test = sel.transform([[0, 1, 2]])
+        assert_array_equal(X_test[0], np.arange(3)[-n_features:])
+
+
+def test_nans():
+    # Assert that SelectKBest and SelectPercentile can handle NaNs.
+    # First feature has zero variance to confuse f_classif (ANOVA) and
+    # make it return a NaN.
+    X = [[0, 1, 0], [0, -1, -1], [0, 0.5, 0.5]]
+    y = [1, 0, 1]
+
+    for select in (
+        SelectKBest(f_classif, k=2),
+        SelectPercentile(f_classif, percentile=67),
+    ):
+        ignore_warnings(select.fit)(X, y)
+        assert_array_equal(select.get_support(indices=True), np.array([1, 2]))
+
+
+def test_invalid_k():
+    X = [[0, 1, 0], [0, -1, -1], [0, 0.5, 0.5]]
+    y = [1, 0, 1]
+
+    msg = "k=4 is greater than n_features=3. All the features will be returned."
+    with pytest.warns(UserWarning, match=msg):
+        SelectKBest(k=4).fit(X, y)
+    with pytest.warns(UserWarning, match=msg):
+        GenericUnivariateSelect(mode="k_best", param=4).fit(X, y)
+
+
+def test_f_classif_constant_feature():
+    # Test that f_classif warns if a feature is constant throughout.
+
+    X, y = make_classification(n_samples=10, n_features=5)
+    X[:, 0] = 2.0
+    with pytest.warns(UserWarning):
+        f_classif(X, y)
+
+
+def test_no_feature_selected():
+    rng = np.random.RandomState(0)
+
+    # Generate random uncorrelated data: a strict univariate test should
+    # rejects all the features
+    X = rng.rand(40, 10)
+    y = rng.randint(0, 4, size=40)
+    strict_selectors = [
+        SelectFwe(alpha=0.01).fit(X, y),
+        SelectFdr(alpha=0.01).fit(X, y),
+        SelectFpr(alpha=0.01).fit(X, y),
+        SelectPercentile(percentile=0).fit(X, y),
+        SelectKBest(k=0).fit(X, y),
+    ]
+    for selector in strict_selectors:
+        assert_array_equal(selector.get_support(), np.zeros(10))
+        with pytest.warns(UserWarning, match="No features were selected"):
+            X_selected = selector.transform(X)
+        assert X_selected.shape == (40, 0)
+
+
+def test_mutual_info_classif():
+    X, y = make_classification(
+        n_samples=100,
+        n_features=5,
+        n_informative=1,
+        n_redundant=1,
+        n_repeated=0,
+        n_classes=2,
+        n_clusters_per_class=1,
+        flip_y=0.0,
+        class_sep=10,
+        shuffle=False,
+        random_state=0,
+    )
+
+    # Test in KBest mode.
+    univariate_filter = SelectKBest(mutual_info_classif, k=2)
+    X_r = univariate_filter.fit(X, y).transform(X)
+    X_r2 = (
+        GenericUnivariateSelect(mutual_info_classif, mode="k_best", param=2)
+        .fit(X, y)
+        .transform(X)
+    )
+    assert_array_equal(X_r, X_r2)
+    support = univariate_filter.get_support()
+    gtruth = np.zeros(5)
+    gtruth[:2] = 1
+    assert_array_equal(support, gtruth)
+
+    # Test in Percentile mode.
+    univariate_filter = SelectPercentile(mutual_info_classif, percentile=40)
+    X_r = univariate_filter.fit(X, y).transform(X)
+    X_r2 = (
+        GenericUnivariateSelect(mutual_info_classif, mode="percentile", param=40)
+        .fit(X, y)
+        .transform(X)
+    )
+    assert_array_equal(X_r, X_r2)
+    support = univariate_filter.get_support()
+    gtruth = np.zeros(5)
+    gtruth[:2] = 1
+    assert_array_equal(support, gtruth)
+
+
+def test_mutual_info_regression():
+    X, y = make_regression(
+        n_samples=100,
+        n_features=10,
+        n_informative=2,
+        shuffle=False,
+        random_state=0,
+        noise=10,
+    )
+
+    # Test in KBest mode.
+    univariate_filter = SelectKBest(mutual_info_regression, k=2)
+    X_r = univariate_filter.fit(X, y).transform(X)
+    assert_best_scores_kept(univariate_filter)
+    X_r2 = (
+        GenericUnivariateSelect(mutual_info_regression, mode="k_best", param=2)
+        .fit(X, y)
+        .transform(X)
+    )
+    assert_array_equal(X_r, X_r2)
+    support = univariate_filter.get_support()
+    gtruth = np.zeros(10)
+    gtruth[:2] = 1
+    assert_array_equal(support, gtruth)
+
+    # Test in Percentile mode.
+    univariate_filter = SelectPercentile(mutual_info_regression, percentile=20)
+    X_r = univariate_filter.fit(X, y).transform(X)
+    X_r2 = (
+        GenericUnivariateSelect(mutual_info_regression, mode="percentile", param=20)
+        .fit(X, y)
+        .transform(X)
+    )
+    assert_array_equal(X_r, X_r2)
+    support = univariate_filter.get_support()
+    gtruth = np.zeros(10)
+    gtruth[:2] = 1
+    assert_array_equal(support, gtruth)
+
+
+def test_dataframe_output_dtypes():
+    """Check that the output datafarme dtypes are the same as the input.
+
+    Non-regression test for gh-24860.
+    """
+    pd = pytest.importorskip("pandas")
+
+    X, y = load_iris(return_X_y=True, as_frame=True)
+    X = X.astype(
+        {
+            "petal length (cm)": np.float32,
+            "petal width (cm)": np.float64,
+        }
+    )
+    X["petal_width_binned"] = pd.cut(X["petal width (cm)"], bins=10)
+
+    column_order = X.columns
+
+    def selector(X, y):
+        ranking = {
+            "sepal length (cm)": 1,
+            "sepal width (cm)": 2,
+            "petal length (cm)": 3,
+            "petal width (cm)": 4,
+            "petal_width_binned": 5,
+        }
+        return np.asarray([ranking[name] for name in column_order])
+
+    univariate_filter = SelectKBest(selector, k=3).set_output(transform="pandas")
+    output = univariate_filter.fit_transform(X, y)
+
+    assert_array_equal(
+        output.columns, ["petal length (cm)", "petal width (cm)", "petal_width_binned"]
+    )
+    for name, dtype in output.dtypes.items():
+        assert dtype == X.dtypes[name]
+
+
+@pytest.mark.parametrize(
+    "selector",
+    [
+        SelectKBest(k=4),
+        SelectPercentile(percentile=80),
+        GenericUnivariateSelect(mode="k_best", param=4),
+        GenericUnivariateSelect(mode="percentile", param=80),
+    ],
+)
+def test_unsupervised_filter(selector):
+    """Check support for unsupervised feature selection for the filter that could
+    require only `X`.
+    """
+    rng = np.random.RandomState(0)
+    X = rng.randn(10, 5)
+
+    def score_func(X, y=None):
+        return np.array([1, 1, 1, 1, 0])
+
+    selector.set_params(score_func=score_func)
+    selector.fit(X)
+    X_trans = selector.transform(X)
+    assert_allclose(X_trans, X[:, :4])
+    X_trans = selector.fit_transform(X)
+    assert_allclose(X_trans, X[:, :4])
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_from_model.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_from_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..17bedf44748fbcf9e65e9b2aee1a94621d1b709e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_from_model.py
@@ -0,0 +1,704 @@
+import re
+import warnings
+from unittest.mock import Mock
+
+import numpy as np
+import pytest
+
+from sklearn import datasets
+from sklearn.base import BaseEstimator
+from sklearn.cross_decomposition import CCA, PLSCanonical, PLSRegression
+from sklearn.datasets import make_friedman1, make_regression
+from sklearn.decomposition import PCA
+from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier
+from sklearn.exceptions import NotFittedError
+from sklearn.feature_selection import SelectFromModel
+from sklearn.linear_model import (
+    ElasticNet,
+    ElasticNetCV,
+    Lasso,
+    LassoCV,
+    LinearRegression,
+    LogisticRegression,
+    PassiveAggressiveClassifier,
+    SGDClassifier,
+)
+from sklearn.pipeline import make_pipeline
+from sklearn.svm import LinearSVC
+from sklearn.utils._testing import (
+    MinimalClassifier,
+    assert_allclose,
+    assert_array_almost_equal,
+    assert_array_equal,
+    skip_if_32bit,
+)
+
+
+class NaNTag(BaseEstimator):
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.input_tags.allow_nan = True
+        return tags
+
+
+class NoNaNTag(BaseEstimator):
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.input_tags.allow_nan = False
+        return tags
+
+
+class NaNTagRandomForest(RandomForestClassifier):
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.input_tags.allow_nan = True
+        return tags
+
+
+iris = datasets.load_iris()
+data, y = iris.data, iris.target
+
+
+def test_invalid_input():
+    clf = SGDClassifier(
+        alpha=0.1, max_iter=10, shuffle=True, random_state=None, tol=None
+    )
+    for threshold in ["gobbledigook", ".5 * gobbledigook"]:
+        model = SelectFromModel(clf, threshold=threshold)
+        model.fit(data, y)
+        with pytest.raises(ValueError):
+            model.transform(data)
+
+
+def test_input_estimator_unchanged():
+    # Test that SelectFromModel fits on a clone of the estimator.
+    est = RandomForestClassifier()
+    transformer = SelectFromModel(estimator=est)
+    transformer.fit(data, y)
+    assert transformer.estimator is est
+
+
+@pytest.mark.parametrize(
+    "max_features, err_type, err_msg",
+    [
+        (
+            data.shape[1] + 1,
+            ValueError,
+            "max_features ==",
+        ),
+        (
+            lambda X: 1.5,
+            TypeError,
+            "max_features must be an instance of int, not float.",
+        ),
+        (
+            lambda X: data.shape[1] + 1,
+            ValueError,
+            "max_features ==",
+        ),
+        (
+            lambda X: -1,
+            ValueError,
+            "max_features ==",
+        ),
+    ],
+)
+def test_max_features_error(max_features, err_type, err_msg):
+    err_msg = re.escape(err_msg)
+    clf = RandomForestClassifier(n_estimators=5, random_state=0)
+
+    transformer = SelectFromModel(
+        estimator=clf, max_features=max_features, threshold=-np.inf
+    )
+    with pytest.raises(err_type, match=err_msg):
+        transformer.fit(data, y)
+
+
+@pytest.mark.parametrize("max_features", [0, 2, data.shape[1], None])
+def test_inferred_max_features_integer(max_features):
+    """Check max_features_ and output shape for integer max_features."""
+    clf = RandomForestClassifier(n_estimators=5, random_state=0)
+    transformer = SelectFromModel(
+        estimator=clf, max_features=max_features, threshold=-np.inf
+    )
+    X_trans = transformer.fit_transform(data, y)
+    if max_features is not None:
+        assert transformer.max_features_ == max_features
+        assert X_trans.shape[1] == transformer.max_features_
+    else:
+        assert not hasattr(transformer, "max_features_")
+        assert X_trans.shape[1] == data.shape[1]
+
+
+@pytest.mark.parametrize(
+    "max_features",
+    [lambda X: 1, lambda X: X.shape[1], lambda X: min(X.shape[1], 10000)],
+)
+def test_inferred_max_features_callable(max_features):
+    """Check max_features_ and output shape for callable max_features."""
+    clf = RandomForestClassifier(n_estimators=5, random_state=0)
+    transformer = SelectFromModel(
+        estimator=clf, max_features=max_features, threshold=-np.inf
+    )
+    X_trans = transformer.fit_transform(data, y)
+    assert transformer.max_features_ == max_features(data)
+    assert X_trans.shape[1] == transformer.max_features_
+
+
+@pytest.mark.parametrize("max_features", [lambda X: round(len(X[0]) / 2), 2])
+def test_max_features_array_like(max_features):
+    X = [
+        [0.87, -1.34, 0.31],
+        [-2.79, -0.02, -0.85],
+        [-1.34, -0.48, -2.55],
+        [1.92, 1.48, 0.65],
+    ]
+    y = [0, 1, 0, 1]
+
+    clf = RandomForestClassifier(n_estimators=5, random_state=0)
+    transformer = SelectFromModel(
+        estimator=clf, max_features=max_features, threshold=-np.inf
+    )
+    X_trans = transformer.fit_transform(X, y)
+    assert X_trans.shape[1] == transformer.max_features_
+
+
+@pytest.mark.parametrize(
+    "max_features",
+    [lambda X: min(X.shape[1], 10000), lambda X: X.shape[1], lambda X: 1],
+)
+def test_max_features_callable_data(max_features):
+    """Tests that the callable passed to `fit` is called on X."""
+    clf = RandomForestClassifier(n_estimators=50, random_state=0)
+    m = Mock(side_effect=max_features)
+    transformer = SelectFromModel(estimator=clf, max_features=m, threshold=-np.inf)
+    transformer.fit_transform(data, y)
+    m.assert_called_with(data)
+
+
+class FixedImportanceEstimator(BaseEstimator):
+    def __init__(self, importances):
+        self.importances = importances
+
+    def fit(self, X, y=None):
+        self.feature_importances_ = np.array(self.importances)
+
+
+def test_max_features():
+    # Test max_features parameter using various values
+    X, y = datasets.make_classification(
+        n_samples=1000,
+        n_features=10,
+        n_informative=3,
+        n_redundant=0,
+        n_repeated=0,
+        shuffle=False,
+        random_state=0,
+    )
+    max_features = X.shape[1]
+    est = RandomForestClassifier(n_estimators=50, random_state=0)
+
+    transformer1 = SelectFromModel(estimator=est, threshold=-np.inf)
+    transformer2 = SelectFromModel(
+        estimator=est, max_features=max_features, threshold=-np.inf
+    )
+    X_new1 = transformer1.fit_transform(X, y)
+    X_new2 = transformer2.fit_transform(X, y)
+    assert_allclose(X_new1, X_new2)
+
+    # Test max_features against actual model.
+    transformer1 = SelectFromModel(estimator=Lasso(alpha=0.025, random_state=42))
+    X_new1 = transformer1.fit_transform(X, y)
+    scores1 = np.abs(transformer1.estimator_.coef_)
+    candidate_indices1 = np.argsort(-scores1, kind="mergesort")
+
+    for n_features in range(1, X_new1.shape[1] + 1):
+        transformer2 = SelectFromModel(
+            estimator=Lasso(alpha=0.025, random_state=42),
+            max_features=n_features,
+            threshold=-np.inf,
+        )
+        X_new2 = transformer2.fit_transform(X, y)
+        scores2 = np.abs(transformer2.estimator_.coef_)
+        candidate_indices2 = np.argsort(-scores2, kind="mergesort")
+        assert_allclose(
+            X[:, candidate_indices1[:n_features]], X[:, candidate_indices2[:n_features]]
+        )
+    assert_allclose(transformer1.estimator_.coef_, transformer2.estimator_.coef_)
+
+
+def test_max_features_tiebreak():
+    # Test if max_features can break tie among feature importance
+    X, y = datasets.make_classification(
+        n_samples=1000,
+        n_features=10,
+        n_informative=3,
+        n_redundant=0,
+        n_repeated=0,
+        shuffle=False,
+        random_state=0,
+    )
+    max_features = X.shape[1]
+
+    feature_importances = np.array([4, 4, 4, 4, 3, 3, 3, 2, 2, 1])
+    for n_features in range(1, max_features + 1):
+        transformer = SelectFromModel(
+            FixedImportanceEstimator(feature_importances),
+            max_features=n_features,
+            threshold=-np.inf,
+        )
+        X_new = transformer.fit_transform(X, y)
+        selected_feature_indices = np.where(transformer._get_support_mask())[0]
+        assert_array_equal(selected_feature_indices, np.arange(n_features))
+        assert X_new.shape[1] == n_features
+
+
+def test_threshold_and_max_features():
+    X, y = datasets.make_classification(
+        n_samples=1000,
+        n_features=10,
+        n_informative=3,
+        n_redundant=0,
+        n_repeated=0,
+        shuffle=False,
+        random_state=0,
+    )
+    est = RandomForestClassifier(n_estimators=50, random_state=0)
+
+    transformer1 = SelectFromModel(estimator=est, max_features=3, threshold=-np.inf)
+    X_new1 = transformer1.fit_transform(X, y)
+
+    transformer2 = SelectFromModel(estimator=est, threshold=0.04)
+    X_new2 = transformer2.fit_transform(X, y)
+
+    transformer3 = SelectFromModel(estimator=est, max_features=3, threshold=0.04)
+    X_new3 = transformer3.fit_transform(X, y)
+    assert X_new3.shape[1] == min(X_new1.shape[1], X_new2.shape[1])
+    selected_indices = transformer3.transform(np.arange(X.shape[1])[np.newaxis, :])
+    assert_allclose(X_new3, X[:, selected_indices[0]])
+
+
+@skip_if_32bit
+def test_feature_importances():
+    X, y = datasets.make_classification(
+        n_samples=1000,
+        n_features=10,
+        n_informative=3,
+        n_redundant=0,
+        n_repeated=0,
+        shuffle=False,
+        random_state=0,
+    )
+
+    est = RandomForestClassifier(n_estimators=50, random_state=0)
+    for threshold, func in zip(["mean", "median"], [np.mean, np.median]):
+        transformer = SelectFromModel(estimator=est, threshold=threshold)
+        transformer.fit(X, y)
+        assert hasattr(transformer.estimator_, "feature_importances_")
+
+        X_new = transformer.transform(X)
+        assert X_new.shape[1] < X.shape[1]
+        importances = transformer.estimator_.feature_importances_
+
+        feature_mask = np.abs(importances) > func(importances)
+        assert_array_almost_equal(X_new, X[:, feature_mask])
+
+
+def test_sample_weight():
+    # Ensure sample weights are passed to underlying estimator
+    X, y = datasets.make_classification(
+        n_samples=100,
+        n_features=10,
+        n_informative=3,
+        n_redundant=0,
+        n_repeated=0,
+        shuffle=False,
+        random_state=0,
+    )
+
+    # Check with sample weights
+    sample_weight = np.ones(y.shape)
+    sample_weight[y == 1] *= 100
+
+    est = LogisticRegression(random_state=0, fit_intercept=False)
+    transformer = SelectFromModel(estimator=est)
+    transformer.fit(X, y, sample_weight=None)
+    mask = transformer._get_support_mask()
+    transformer.fit(X, y, sample_weight=sample_weight)
+    weighted_mask = transformer._get_support_mask()
+    assert not np.all(weighted_mask == mask)
+    transformer.fit(X, y, sample_weight=3 * sample_weight)
+    reweighted_mask = transformer._get_support_mask()
+    assert np.all(weighted_mask == reweighted_mask)
+
+
+@pytest.mark.parametrize(
+    "estimator",
+    [
+        Lasso(alpha=0.1, random_state=42),
+        LassoCV(random_state=42),
+        ElasticNet(l1_ratio=1, random_state=42),
+        ElasticNetCV(l1_ratio=[1], random_state=42),
+    ],
+)
+def test_coef_default_threshold(estimator):
+    X, y = datasets.make_classification(
+        n_samples=100,
+        n_features=10,
+        n_informative=3,
+        n_redundant=0,
+        n_repeated=0,
+        shuffle=False,
+        random_state=0,
+    )
+
+    # For the Lasso and related models, the threshold defaults to 1e-5
+    transformer = SelectFromModel(estimator=estimator)
+    transformer.fit(X, y)
+    X_new = transformer.transform(X)
+    mask = np.abs(transformer.estimator_.coef_) > 1e-5
+    assert_array_almost_equal(X_new, X[:, mask])
+
+
+@skip_if_32bit
+def test_2d_coef():
+    X, y = datasets.make_classification(
+        n_samples=1000,
+        n_features=10,
+        n_informative=3,
+        n_redundant=0,
+        n_repeated=0,
+        shuffle=False,
+        random_state=0,
+        n_classes=4,
+    )
+
+    est = LogisticRegression()
+    for threshold, func in zip(["mean", "median"], [np.mean, np.median]):
+        for order in [1, 2, np.inf]:
+            # Fit SelectFromModel a multi-class problem
+            transformer = SelectFromModel(
+                estimator=LogisticRegression(), threshold=threshold, norm_order=order
+            )
+            transformer.fit(X, y)
+            assert hasattr(transformer.estimator_, "coef_")
+            X_new = transformer.transform(X)
+            assert X_new.shape[1] < X.shape[1]
+
+            # Manually check that the norm is correctly performed
+            est.fit(X, y)
+            importances = np.linalg.norm(est.coef_, axis=0, ord=order)
+            feature_mask = importances > func(importances)
+            assert_array_almost_equal(X_new, X[:, feature_mask])
+
+
+def test_partial_fit():
+    est = PassiveAggressiveClassifier(
+        random_state=0, shuffle=False, max_iter=5, tol=None
+    )
+    transformer = SelectFromModel(estimator=est)
+    transformer.partial_fit(data, y, classes=np.unique(y))
+    old_model = transformer.estimator_
+    transformer.partial_fit(data, y, classes=np.unique(y))
+    new_model = transformer.estimator_
+    assert old_model is new_model
+
+    X_transform = transformer.transform(data)
+    transformer.fit(np.vstack((data, data)), np.concatenate((y, y)))
+    assert_array_almost_equal(X_transform, transformer.transform(data))
+
+    # check that if est doesn't have partial_fit, neither does SelectFromModel
+    transformer = SelectFromModel(estimator=RandomForestClassifier())
+    assert not hasattr(transformer, "partial_fit")
+
+
+def test_calling_fit_reinitializes():
+    est = LinearSVC(random_state=0)
+    transformer = SelectFromModel(estimator=est)
+    transformer.fit(data, y)
+    transformer.set_params(estimator__C=100)
+    transformer.fit(data, y)
+    assert transformer.estimator_.C == 100
+
+
+def test_prefit():
+    # Test all possible combinations of the prefit parameter.
+
+    # Passing a prefit parameter with the selected model
+    # and fitting a unfit model with prefit=False should give same results.
+    clf = SGDClassifier(alpha=0.1, max_iter=10, shuffle=True, random_state=0, tol=None)
+    model = SelectFromModel(clf)
+    model.fit(data, y)
+    X_transform = model.transform(data)
+    clf.fit(data, y)
+    model = SelectFromModel(clf, prefit=True)
+    assert_array_almost_equal(model.transform(data), X_transform)
+    model.fit(data, y)
+    assert model.estimator_ is not clf
+
+    # Check that the model is rewritten if prefit=False and a fitted model is
+    # passed
+    model = SelectFromModel(clf, prefit=False)
+    model.fit(data, y)
+    assert_array_almost_equal(model.transform(data), X_transform)
+
+    # Check that passing an unfitted estimator with `prefit=True` raises a
+    # `ValueError`
+    clf = SGDClassifier(alpha=0.1, max_iter=10, shuffle=True, random_state=0, tol=None)
+    model = SelectFromModel(clf, prefit=True)
+    err_msg = "When `prefit=True`, `estimator` is expected to be a fitted estimator."
+    with pytest.raises(NotFittedError, match=err_msg):
+        model.fit(data, y)
+    with pytest.raises(NotFittedError, match=err_msg):
+        model.partial_fit(data, y)
+    with pytest.raises(NotFittedError, match=err_msg):
+        model.transform(data)
+
+    # Check that the internal parameters of prefitted model are not changed
+    # when calling `fit` or `partial_fit` with `prefit=True`
+    clf = SGDClassifier(alpha=0.1, max_iter=10, shuffle=True, tol=None).fit(data, y)
+    model = SelectFromModel(clf, prefit=True)
+    model.fit(data, y)
+    assert_allclose(model.estimator_.coef_, clf.coef_)
+    model.partial_fit(data, y)
+    assert_allclose(model.estimator_.coef_, clf.coef_)
+
+
+def test_prefit_max_features():
+    """Check the interaction between `prefit` and `max_features`."""
+    # case 1: an error should be raised at `transform` if `fit` was not called to
+    # validate the attributes
+    estimator = RandomForestClassifier(n_estimators=5, random_state=0)
+    estimator.fit(data, y)
+    model = SelectFromModel(estimator, prefit=True, max_features=lambda X: X.shape[1])
+
+    err_msg = (
+        "When `prefit=True` and `max_features` is a callable, call `fit` "
+        "before calling `transform`."
+    )
+    with pytest.raises(NotFittedError, match=err_msg):
+        model.transform(data)
+
+    # case 2: `max_features` is not validated and different from an integer
+    # FIXME: we cannot validate the upper bound of the attribute at transform
+    # and we should force calling `fit` if we intend to force the attribute
+    # to have such an upper bound.
+    max_features = 2.5
+    model.set_params(max_features=max_features)
+    with pytest.raises(ValueError, match="`max_features` must be an integer"):
+        model.transform(data)
+
+
+def test_get_feature_names_out_elasticnetcv():
+    """Check if ElasticNetCV works with a list of floats.
+
+    Non-regression test for #30936."""
+    X, y = make_regression(n_features=5, n_informative=3, random_state=0)
+    estimator = ElasticNetCV(l1_ratio=[0.25, 0.5, 0.75], random_state=0)
+    selector = SelectFromModel(estimator=estimator)
+    selector.fit(X, y)
+
+    names_out = selector.get_feature_names_out()
+    mask = selector.get_support()
+    expected = np.array([f"x{i}" for i in range(X.shape[1])])[mask]
+    assert_array_equal(names_out, expected)
+
+
+def test_prefit_get_feature_names_out():
+    """Check the interaction between prefit and the feature names."""
+    clf = RandomForestClassifier(n_estimators=2, random_state=0)
+    clf.fit(data, y)
+    model = SelectFromModel(clf, prefit=True, max_features=1)
+
+    name = type(model).__name__
+    err_msg = (
+        f"This {name} instance is not fitted yet. Call 'fit' with "
+        "appropriate arguments before using this estimator."
+    )
+    with pytest.raises(NotFittedError, match=err_msg):
+        model.get_feature_names_out()
+
+    model.fit(data, y)
+    feature_names = model.get_feature_names_out()
+    assert feature_names == ["x3"]
+
+
+def test_threshold_string():
+    est = RandomForestClassifier(n_estimators=50, random_state=0)
+    model = SelectFromModel(est, threshold="0.5*mean")
+    model.fit(data, y)
+    X_transform = model.transform(data)
+
+    # Calculate the threshold from the estimator directly.
+    est.fit(data, y)
+    threshold = 0.5 * np.mean(est.feature_importances_)
+    mask = est.feature_importances_ > threshold
+    assert_array_almost_equal(X_transform, data[:, mask])
+
+
+def test_threshold_without_refitting():
+    # Test that the threshold can be set without refitting the model.
+    clf = SGDClassifier(alpha=0.1, max_iter=10, shuffle=True, random_state=0, tol=None)
+    model = SelectFromModel(clf, threshold="0.1 * mean")
+    model.fit(data, y)
+    X_transform = model.transform(data)
+
+    # Set a higher threshold to filter out more features.
+    model.threshold = "1.0 * mean"
+    assert X_transform.shape[1] > model.transform(data).shape[1]
+
+
+def test_fit_accepts_nan_inf():
+    # Test that fit doesn't check for np.inf and np.nan values.
+    clf = HistGradientBoostingClassifier(random_state=0)
+
+    model = SelectFromModel(estimator=clf)
+
+    nan_data = data.copy()
+    nan_data[0] = np.nan
+    nan_data[1] = np.inf
+
+    model.fit(data, y)
+
+
+def test_transform_accepts_nan_inf():
+    # Test that transform doesn't check for np.inf and np.nan values.
+    clf = NaNTagRandomForest(n_estimators=100, random_state=0)
+    nan_data = data.copy()
+
+    model = SelectFromModel(estimator=clf)
+    model.fit(nan_data, y)
+
+    nan_data[0] = np.nan
+    nan_data[1] = np.inf
+
+    model.transform(nan_data)
+
+
+def test_allow_nan_tag_comes_from_estimator():
+    allow_nan_est = NaNTag()
+    model = SelectFromModel(estimator=allow_nan_est)
+    assert model.__sklearn_tags__().input_tags.allow_nan is True
+
+    no_nan_est = NoNaNTag()
+    model = SelectFromModel(estimator=no_nan_est)
+    assert model.__sklearn_tags__().input_tags.allow_nan is False
+
+
+def _pca_importances(pca_estimator):
+    return np.abs(pca_estimator.explained_variance_)
+
+
+@pytest.mark.parametrize(
+    "estimator, importance_getter",
+    [
+        (
+            make_pipeline(PCA(random_state=0), LogisticRegression()),
+            "named_steps.logisticregression.coef_",
+        ),
+        (PCA(random_state=0), _pca_importances),
+    ],
+)
+def test_importance_getter(estimator, importance_getter):
+    selector = SelectFromModel(
+        estimator, threshold="mean", importance_getter=importance_getter
+    )
+    selector.fit(data, y)
+    assert selector.transform(data).shape[1] == 1
+
+
+@pytest.mark.parametrize("PLSEstimator", [CCA, PLSCanonical, PLSRegression])
+def test_select_from_model_pls(PLSEstimator):
+    """Check the behaviour of SelectFromModel with PLS estimators.
+
+    Non-regression test for:
+    https://github.com/scikit-learn/scikit-learn/issues/12410
+    """
+    X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)
+    estimator = PLSEstimator(n_components=1)
+    model = make_pipeline(SelectFromModel(estimator), estimator).fit(X, y)
+    assert model.score(X, y) > 0.5
+
+
+def test_estimator_does_not_support_feature_names():
+    """SelectFromModel works with estimators that do not support feature_names_in_.
+
+    Non-regression test for #21949.
+    """
+    pytest.importorskip("pandas")
+    X, y = datasets.load_iris(as_frame=True, return_X_y=True)
+    all_feature_names = set(X.columns)
+
+    def importance_getter(estimator):
+        return np.arange(X.shape[1])
+
+    selector = SelectFromModel(
+        MinimalClassifier(), importance_getter=importance_getter
+    ).fit(X, y)
+
+    # selector learns the feature names itself
+    assert_array_equal(selector.feature_names_in_, X.columns)
+
+    feature_names_out = set(selector.get_feature_names_out())
+    assert feature_names_out < all_feature_names
+
+    with warnings.catch_warnings():
+        warnings.simplefilter("error", UserWarning)
+
+        selector.transform(X.iloc[1:3])
+
+
+@pytest.mark.parametrize(
+    "error, err_msg, max_features",
+    (
+        [ValueError, "max_features == 10, must be <= 4", 10],
+        [ValueError, "max_features == 5, must be <= 4", lambda x: x.shape[1] + 1],
+    ),
+)
+def test_partial_fit_validate_max_features(error, err_msg, max_features):
+    """Test that partial_fit from SelectFromModel validates `max_features`."""
+    X, y = datasets.make_classification(
+        n_samples=100,
+        n_features=4,
+        random_state=0,
+    )
+
+    with pytest.raises(error, match=err_msg):
+        SelectFromModel(
+            estimator=SGDClassifier(), max_features=max_features
+        ).partial_fit(X, y, classes=[0, 1])
+
+
+@pytest.mark.parametrize("as_frame", [True, False])
+def test_partial_fit_validate_feature_names(as_frame):
+    """Test that partial_fit from SelectFromModel validates `feature_names_in_`."""
+    pytest.importorskip("pandas")
+    X, y = datasets.load_iris(as_frame=as_frame, return_X_y=True)
+
+    selector = SelectFromModel(estimator=SGDClassifier(), max_features=4).partial_fit(
+        X, y, classes=[0, 1, 2]
+    )
+    if as_frame:
+        assert_array_equal(selector.feature_names_in_, X.columns)
+    else:
+        assert not hasattr(selector, "feature_names_in_")
+
+
+def test_from_model_estimator_attribute_error():
+    """Check that we raise the proper AttributeError when the estimator
+    does not implement the `partial_fit` method, which is decorated with
+    `available_if`.
+
+    Non-regression test for:
+    https://github.com/scikit-learn/scikit-learn/issues/28108
+    """
+    # `LinearRegression` does not implement 'partial_fit' and should raise an
+    # AttributeError
+    from_model = SelectFromModel(estimator=LinearRegression())
+
+    outer_msg = "This 'SelectFromModel' has no attribute 'partial_fit'"
+    inner_msg = "'LinearRegression' object has no attribute 'partial_fit'"
+    with pytest.raises(AttributeError, match=outer_msg) as exec_info:
+        from_model.fit(data, y).partial_fit(data)
+    assert isinstance(exec_info.value.__cause__, AttributeError)
+    assert inner_msg in str(exec_info.value.__cause__)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_mutual_info.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_mutual_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..4922b7e4e57b352456e8295d7dba44feb4eef535
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_mutual_info.py
@@ -0,0 +1,270 @@
+import numpy as np
+import pytest
+
+from sklearn.datasets import make_classification, make_regression
+from sklearn.feature_selection import mutual_info_classif, mutual_info_regression
+from sklearn.feature_selection._mutual_info import _compute_mi
+from sklearn.utils import check_random_state
+from sklearn.utils._testing import (
+    assert_allclose,
+    assert_array_equal,
+)
+from sklearn.utils.fixes import CSR_CONTAINERS
+
+
+def test_compute_mi_dd():
+    # In discrete case computations are straightforward and can be done
+    # by hand on given vectors.
+    x = np.array([0, 1, 1, 0, 0])
+    y = np.array([1, 0, 0, 0, 1])
+
+    H_x = H_y = -(3 / 5) * np.log(3 / 5) - (2 / 5) * np.log(2 / 5)
+    H_xy = -1 / 5 * np.log(1 / 5) - 2 / 5 * np.log(2 / 5) - 2 / 5 * np.log(2 / 5)
+    I_xy = H_x + H_y - H_xy
+
+    assert_allclose(_compute_mi(x, y, x_discrete=True, y_discrete=True), I_xy)
+
+
+def test_compute_mi_cc(global_dtype):
+    # For two continuous variables a good approach is to test on bivariate
+    # normal distribution, where mutual information is known.
+
+    # Mean of the distribution, irrelevant for mutual information.
+    mean = np.zeros(2)
+
+    # Setup covariance matrix with correlation coeff. equal 0.5.
+    sigma_1 = 1
+    sigma_2 = 10
+    corr = 0.5
+    cov = np.array(
+        [
+            [sigma_1**2, corr * sigma_1 * sigma_2],
+            [corr * sigma_1 * sigma_2, sigma_2**2],
+        ]
+    )
+
+    # True theoretical mutual information.
+    I_theory = np.log(sigma_1) + np.log(sigma_2) - 0.5 * np.log(np.linalg.det(cov))
+
+    rng = check_random_state(0)
+    Z = rng.multivariate_normal(mean, cov, size=1000).astype(global_dtype, copy=False)
+
+    x, y = Z[:, 0], Z[:, 1]
+
+    # Theory and computed values won't be very close
+    # We here check with a large relative tolerance
+    for n_neighbors in [3, 5, 7]:
+        I_computed = _compute_mi(
+            x, y, x_discrete=False, y_discrete=False, n_neighbors=n_neighbors
+        )
+        assert_allclose(I_computed, I_theory, rtol=1e-1)
+
+
+def test_compute_mi_cd(global_dtype):
+    # To test define a joint distribution as follows:
+    # p(x, y) = p(x) p(y | x)
+    # X ~ Bernoulli(p)
+    # (Y | x = 0) ~ Uniform(-1, 1)
+    # (Y | x = 1) ~ Uniform(0, 2)
+
+    # Use the following formula for mutual information:
+    # I(X; Y) = H(Y) - H(Y | X)
+    # Two entropies can be computed by hand:
+    # H(Y) = -(1-p)/2 * ln((1-p)/2) - p/2*log(p/2) - 1/2*log(1/2)
+    # H(Y | X) = ln(2)
+
+    # Now we need to implement sampling from out distribution, which is
+    # done easily using conditional distribution logic.
+
+    n_samples = 1000
+    rng = check_random_state(0)
+
+    for p in [0.3, 0.5, 0.7]:
+        x = rng.uniform(size=n_samples) > p
+
+        y = np.empty(n_samples, global_dtype)
+        mask = x == 0
+        y[mask] = rng.uniform(-1, 1, size=np.sum(mask))
+        y[~mask] = rng.uniform(0, 2, size=np.sum(~mask))
+
+        I_theory = -0.5 * (
+            (1 - p) * np.log(0.5 * (1 - p)) + p * np.log(0.5 * p) + np.log(0.5)
+        ) - np.log(2)
+
+        # Assert the same tolerance.
+        for n_neighbors in [3, 5, 7]:
+            I_computed = _compute_mi(
+                x, y, x_discrete=True, y_discrete=False, n_neighbors=n_neighbors
+            )
+            assert_allclose(I_computed, I_theory, rtol=1e-1)
+
+
+def test_compute_mi_cd_unique_label(global_dtype):
+    # Test that adding unique label doesn't change MI.
+    n_samples = 100
+    x = np.random.uniform(size=n_samples) > 0.5
+
+    y = np.empty(n_samples, global_dtype)
+    mask = x == 0
+    y[mask] = np.random.uniform(-1, 1, size=np.sum(mask))
+    y[~mask] = np.random.uniform(0, 2, size=np.sum(~mask))
+
+    mi_1 = _compute_mi(x, y, x_discrete=True, y_discrete=False)
+
+    x = np.hstack((x, 2))
+    y = np.hstack((y, 10))
+    mi_2 = _compute_mi(x, y, x_discrete=True, y_discrete=False)
+
+    assert_allclose(mi_1, mi_2)
+
+
+# We are going test that feature ordering by MI matches our expectations.
+def test_mutual_info_classif_discrete(global_dtype):
+    X = np.array(
+        [[0, 0, 0], [1, 1, 0], [2, 0, 1], [2, 0, 1], [2, 0, 1]], dtype=global_dtype
+    )
+    y = np.array([0, 1, 2, 2, 1])
+
+    # Here X[:, 0] is the most informative feature, and X[:, 1] is weakly
+    # informative.
+    mi = mutual_info_classif(X, y, discrete_features=True)
+    assert_array_equal(np.argsort(-mi), np.array([0, 2, 1]))
+
+
+def test_mutual_info_regression(global_dtype):
+    # We generate sample from multivariate normal distribution, using
+    # transformation from initially uncorrelated variables. The zero
+    # variables after transformation is selected as the target vector,
+    # it has the strongest correlation with the variable 2, and
+    # the weakest correlation with the variable 1.
+    T = np.array([[1, 0.5, 2, 1], [0, 1, 0.1, 0.0], [0, 0.1, 1, 0.1], [0, 0.1, 0.1, 1]])
+    cov = T.dot(T.T)
+    mean = np.zeros(4)
+
+    rng = check_random_state(0)
+    Z = rng.multivariate_normal(mean, cov, size=1000).astype(global_dtype, copy=False)
+    X = Z[:, 1:]
+    y = Z[:, 0]
+
+    mi = mutual_info_regression(X, y, random_state=0)
+    assert_array_equal(np.argsort(-mi), np.array([1, 2, 0]))
+    # XXX: should mutual_info_regression be fixed to avoid
+    # up-casting float32 inputs to float64?
+    assert mi.dtype == np.float64
+
+
+def test_mutual_info_classif_mixed(global_dtype):
+    # Here the target is discrete and there are two continuous and one
+    # discrete feature. The idea of this test is clear from the code.
+    rng = check_random_state(0)
+    X = rng.rand(1000, 3).astype(global_dtype, copy=False)
+    X[:, 1] += X[:, 0]
+    y = ((0.5 * X[:, 0] + X[:, 2]) > 0.5).astype(int)
+    X[:, 2] = X[:, 2] > 0.5
+
+    mi = mutual_info_classif(X, y, discrete_features=[2], n_neighbors=3, random_state=0)
+    assert_array_equal(np.argsort(-mi), [2, 0, 1])
+    for n_neighbors in [5, 7, 9]:
+        mi_nn = mutual_info_classif(
+            X, y, discrete_features=[2], n_neighbors=n_neighbors, random_state=0
+        )
+        # Check that the continuous values have an higher MI with greater
+        # n_neighbors
+        assert mi_nn[0] > mi[0]
+        assert mi_nn[1] > mi[1]
+        # The n_neighbors should not have any effect on the discrete value
+        # The MI should be the same
+        assert mi_nn[2] == mi[2]
+
+
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_mutual_info_options(global_dtype, csr_container):
+    X = np.array(
+        [[0, 0, 0], [1, 1, 0], [2, 0, 1], [2, 0, 1], [2, 0, 1]], dtype=global_dtype
+    )
+    y = np.array([0, 1, 2, 2, 1], dtype=global_dtype)
+    X_csr = csr_container(X)
+
+    for mutual_info in (mutual_info_regression, mutual_info_classif):
+        with pytest.raises(ValueError):
+            mutual_info(X_csr, y, discrete_features=False)
+        with pytest.raises(ValueError):
+            mutual_info(X, y, discrete_features="manual")
+        with pytest.raises(ValueError):
+            mutual_info(X_csr, y, discrete_features=[True, False, True])
+        with pytest.raises(IndexError):
+            mutual_info(X, y, discrete_features=[True, False, True, False])
+        with pytest.raises(IndexError):
+            mutual_info(X, y, discrete_features=[1, 4])
+
+        mi_1 = mutual_info(X, y, discrete_features="auto", random_state=0)
+        mi_2 = mutual_info(X, y, discrete_features=False, random_state=0)
+        mi_3 = mutual_info(X_csr, y, discrete_features="auto", random_state=0)
+        mi_4 = mutual_info(X_csr, y, discrete_features=True, random_state=0)
+        mi_5 = mutual_info(X, y, discrete_features=[True, False, True], random_state=0)
+        mi_6 = mutual_info(X, y, discrete_features=[0, 2], random_state=0)
+
+        assert_allclose(mi_1, mi_2)
+        assert_allclose(mi_3, mi_4)
+        assert_allclose(mi_5, mi_6)
+
+        assert not np.allclose(mi_1, mi_3)
+
+
+@pytest.mark.parametrize("correlated", [True, False])
+def test_mutual_information_symmetry_classif_regression(correlated, global_random_seed):
+    """Check that `mutual_info_classif` and `mutual_info_regression` are
+    symmetric by switching the target `y` as `feature` in `X` and vice
+    versa.
+
+    Non-regression test for:
+    https://github.com/scikit-learn/scikit-learn/issues/23720
+    """
+    rng = np.random.RandomState(global_random_seed)
+    n = 100
+    d = rng.randint(10, size=n)
+
+    if correlated:
+        c = d.astype(np.float64)
+    else:
+        c = rng.normal(0, 1, size=n)
+
+    mi_classif = mutual_info_classif(
+        c[:, None], d, discrete_features=[False], random_state=global_random_seed
+    )
+
+    mi_regression = mutual_info_regression(
+        d[:, None], c, discrete_features=[True], random_state=global_random_seed
+    )
+
+    assert mi_classif == pytest.approx(mi_regression)
+
+
+def test_mutual_info_regression_X_int_dtype(global_random_seed):
+    """Check that results agree when X is integer dtype and float dtype.
+
+    Non-regression test for Issue #26696.
+    """
+    rng = np.random.RandomState(global_random_seed)
+    X = rng.randint(100, size=(100, 10))
+    X_float = X.astype(np.float64, copy=True)
+    y = rng.randint(100, size=100)
+
+    expected = mutual_info_regression(X_float, y, random_state=global_random_seed)
+    result = mutual_info_regression(X, y, random_state=global_random_seed)
+    assert_allclose(result, expected)
+
+
+@pytest.mark.parametrize(
+    "mutual_info_func, data_generator",
+    [
+        (mutual_info_regression, make_regression),
+        (mutual_info_classif, make_classification),
+    ],
+)
+def test_mutual_info_n_jobs(global_random_seed, mutual_info_func, data_generator):
+    """Check that results are consistent with different `n_jobs`."""
+    X, y = data_generator(random_state=global_random_seed)
+    single_job = mutual_info_func(X, y, random_state=global_random_seed, n_jobs=1)
+    multi_job = mutual_info_func(X, y, random_state=global_random_seed, n_jobs=2)
+    assert_allclose(single_job, multi_job)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_rfe.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_rfe.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f5672545874c057847a5d135f1c29a7211647e0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_rfe.py
@@ -0,0 +1,755 @@
+"""
+Testing Recursive feature elimination
+"""
+
+import re
+from operator import attrgetter
+
+import numpy as np
+import pytest
+from joblib import parallel_backend
+from numpy.testing import assert_allclose, assert_array_almost_equal, assert_array_equal
+
+from sklearn.base import BaseEstimator, ClassifierMixin, is_classifier
+from sklearn.compose import TransformedTargetRegressor
+from sklearn.cross_decomposition import CCA, PLSCanonical, PLSRegression
+from sklearn.datasets import load_iris, make_classification, make_friedman1
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.feature_selection import RFE, RFECV
+from sklearn.impute import SimpleImputer
+from sklearn.linear_model import LinearRegression, LogisticRegression
+from sklearn.metrics import get_scorer, make_scorer, zero_one_loss
+from sklearn.model_selection import GroupKFold, cross_val_score
+from sklearn.pipeline import make_pipeline
+from sklearn.preprocessing import StandardScaler
+from sklearn.svm import SVC, SVR, LinearSVR
+from sklearn.utils import check_random_state
+from sklearn.utils._testing import ignore_warnings
+from sklearn.utils.fixes import CSR_CONTAINERS
+
+
+class MockClassifier(ClassifierMixin, BaseEstimator):
+    """
+    Dummy classifier to test recursive feature elimination
+    """
+
+    def __init__(self, foo_param=0):
+        self.foo_param = foo_param
+
+    def fit(self, X, y):
+        assert len(X) == len(y)
+        self.coef_ = np.ones(X.shape[1], dtype=np.float64)
+        self.classes_ = sorted(set(y))
+        return self
+
+    def predict(self, T):
+        return np.ones(T.shape[0])
+
+    predict_proba = predict
+    decision_function = predict
+    transform = predict
+
+    def score(self, X=None, y=None):
+        return 0.0
+
+    def get_params(self, deep=True):
+        return {"foo_param": self.foo_param}
+
+    def set_params(self, **params):
+        return self
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.input_tags.allow_nan = True
+        return tags
+
+
+def test_rfe_features_importance():
+    generator = check_random_state(0)
+    iris = load_iris()
+    # Add some irrelevant features. Random seed is set to make sure that
+    # irrelevant features are always irrelevant.
+    X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))]
+    y = iris.target
+
+    clf = RandomForestClassifier(n_estimators=20, random_state=generator, max_depth=2)
+    rfe = RFE(estimator=clf, n_features_to_select=4, step=0.1)
+    rfe.fit(X, y)
+    assert len(rfe.ranking_) == X.shape[1]
+
+    clf_svc = SVC(kernel="linear")
+    rfe_svc = RFE(estimator=clf_svc, n_features_to_select=4, step=0.1)
+    rfe_svc.fit(X, y)
+
+    # Check if the supports are equal
+    assert_array_equal(rfe.get_support(), rfe_svc.get_support())
+
+
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_rfe(csr_container):
+    generator = check_random_state(0)
+    iris = load_iris()
+    # Add some irrelevant features. Random seed is set to make sure that
+    # irrelevant features are always irrelevant.
+    X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))]
+    X_sparse = csr_container(X)
+    y = iris.target
+
+    # dense model
+    clf = SVC(kernel="linear")
+    rfe = RFE(estimator=clf, n_features_to_select=4, step=0.1)
+    rfe.fit(X, y)
+    X_r = rfe.transform(X)
+    clf.fit(X_r, y)
+    assert len(rfe.ranking_) == X.shape[1]
+
+    # sparse model
+    clf_sparse = SVC(kernel="linear")
+    rfe_sparse = RFE(estimator=clf_sparse, n_features_to_select=4, step=0.1)
+    rfe_sparse.fit(X_sparse, y)
+    X_r_sparse = rfe_sparse.transform(X_sparse)
+
+    assert X_r.shape == iris.data.shape
+    assert_array_almost_equal(X_r[:10], iris.data[:10])
+
+    assert_array_almost_equal(rfe.predict(X), clf.predict(iris.data))
+    assert rfe.score(X, y) == clf.score(iris.data, iris.target)
+    assert_array_almost_equal(X_r, X_r_sparse.toarray())
+
+
+def test_RFE_fit_score_params():
+    # Make sure RFE passes the metadata down to fit and score methods of the
+    # underlying estimator
+    class TestEstimator(BaseEstimator, ClassifierMixin):
+        def fit(self, X, y, prop=None):
+            if prop is None:
+                raise ValueError("fit: prop cannot be None")
+            self.svc_ = SVC(kernel="linear").fit(X, y)
+            self.coef_ = self.svc_.coef_
+            return self
+
+        def score(self, X, y, prop=None):
+            if prop is None:
+                raise ValueError("score: prop cannot be None")
+            return self.svc_.score(X, y)
+
+    X, y = load_iris(return_X_y=True)
+    with pytest.raises(ValueError, match="fit: prop cannot be None"):
+        RFE(estimator=TestEstimator()).fit(X, y)
+    with pytest.raises(ValueError, match="score: prop cannot be None"):
+        RFE(estimator=TestEstimator()).fit(X, y, prop="foo").score(X, y)
+
+    RFE(estimator=TestEstimator()).fit(X, y, prop="foo").score(X, y, prop="foo")
+
+
+def test_rfe_percent_n_features():
+    # test that the results are the same
+    generator = check_random_state(0)
+    iris = load_iris()
+    # Add some irrelevant features. Random seed is set to make sure that
+    # irrelevant features are always irrelevant.
+    X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))]
+    y = iris.target
+    # there are 10 features in the data. We select 40%.
+    clf = SVC(kernel="linear")
+    rfe_num = RFE(estimator=clf, n_features_to_select=4, step=0.1)
+    rfe_num.fit(X, y)
+
+    rfe_perc = RFE(estimator=clf, n_features_to_select=0.4, step=0.1)
+    rfe_perc.fit(X, y)
+
+    assert_array_equal(rfe_perc.ranking_, rfe_num.ranking_)
+    assert_array_equal(rfe_perc.support_, rfe_num.support_)
+
+
+def test_rfe_mockclassifier():
+    generator = check_random_state(0)
+    iris = load_iris()
+    # Add some irrelevant features. Random seed is set to make sure that
+    # irrelevant features are always irrelevant.
+    X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))]
+    y = iris.target
+
+    # dense model
+    clf = MockClassifier()
+    rfe = RFE(estimator=clf, n_features_to_select=4, step=0.1)
+    rfe.fit(X, y)
+    X_r = rfe.transform(X)
+    clf.fit(X_r, y)
+    assert len(rfe.ranking_) == X.shape[1]
+    assert X_r.shape == iris.data.shape
+
+
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_rfecv(csr_container):
+    generator = check_random_state(0)
+    iris = load_iris()
+    # Add some irrelevant features. Random seed is set to make sure that
+    # irrelevant features are always irrelevant.
+    X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))]
+    y = list(iris.target)  # regression test: list should be supported
+
+    # Test using the score function
+    rfecv = RFECV(estimator=SVC(kernel="linear"), step=1)
+    rfecv.fit(X, y)
+    # non-regression test for missing worst feature:
+
+    for key in rfecv.cv_results_.keys():
+        assert len(rfecv.cv_results_[key]) == X.shape[1]
+
+    assert len(rfecv.ranking_) == X.shape[1]
+    X_r = rfecv.transform(X)
+
+    # All the noisy variable were filtered out
+    assert_array_equal(X_r, iris.data)
+
+    # same in sparse
+    rfecv_sparse = RFECV(estimator=SVC(kernel="linear"), step=1)
+    X_sparse = csr_container(X)
+    rfecv_sparse.fit(X_sparse, y)
+    X_r_sparse = rfecv_sparse.transform(X_sparse)
+    assert_array_equal(X_r_sparse.toarray(), iris.data)
+
+    # Test using a customized loss function
+    scoring = make_scorer(zero_one_loss, greater_is_better=False)
+    rfecv = RFECV(estimator=SVC(kernel="linear"), step=1, scoring=scoring)
+    ignore_warnings(rfecv.fit)(X, y)
+    X_r = rfecv.transform(X)
+    assert_array_equal(X_r, iris.data)
+
+    # Test using a scorer
+    scorer = get_scorer("accuracy")
+    rfecv = RFECV(estimator=SVC(kernel="linear"), step=1, scoring=scorer)
+    rfecv.fit(X, y)
+    X_r = rfecv.transform(X)
+    assert_array_equal(X_r, iris.data)
+
+    # Test fix on cv_results_
+    def test_scorer(estimator, X, y):
+        return 1.0
+
+    rfecv = RFECV(estimator=SVC(kernel="linear"), step=1, scoring=test_scorer)
+    rfecv.fit(X, y)
+
+    # In the event of cross validation score ties, the expected behavior of
+    # RFECV is to return the FEWEST features that maximize the CV score.
+    # Because test_scorer always returns 1.0 in this example, RFECV should
+    # reduce the dimensionality to a single feature (i.e. n_features_ = 1)
+    assert rfecv.n_features_ == 1
+
+    # Same as the first two tests, but with step=2
+    rfecv = RFECV(estimator=SVC(kernel="linear"), step=2)
+    rfecv.fit(X, y)
+
+    for key in rfecv.cv_results_.keys():
+        assert len(rfecv.cv_results_[key]) == 6
+
+    assert len(rfecv.ranking_) == X.shape[1]
+    X_r = rfecv.transform(X)
+    assert_array_equal(X_r, iris.data)
+
+    rfecv_sparse = RFECV(estimator=SVC(kernel="linear"), step=2)
+    X_sparse = csr_container(X)
+    rfecv_sparse.fit(X_sparse, y)
+    X_r_sparse = rfecv_sparse.transform(X_sparse)
+    assert_array_equal(X_r_sparse.toarray(), iris.data)
+
+    # Verifying that steps < 1 don't blow up.
+    rfecv_sparse = RFECV(estimator=SVC(kernel="linear"), step=0.2)
+    X_sparse = csr_container(X)
+    rfecv_sparse.fit(X_sparse, y)
+    X_r_sparse = rfecv_sparse.transform(X_sparse)
+    assert_array_equal(X_r_sparse.toarray(), iris.data)
+
+
+def test_rfecv_mockclassifier():
+    generator = check_random_state(0)
+    iris = load_iris()
+    X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))]
+    y = list(iris.target)  # regression test: list should be supported
+
+    # Test using the score function
+    rfecv = RFECV(estimator=MockClassifier(), step=1)
+    rfecv.fit(X, y)
+    # non-regression test for missing worst feature:
+
+    for key in rfecv.cv_results_.keys():
+        assert len(rfecv.cv_results_[key]) == X.shape[1]
+
+    assert len(rfecv.ranking_) == X.shape[1]
+
+
+def test_rfecv_verbose_output():
+    # Check verbose=1 is producing an output.
+    import sys
+    from io import StringIO
+
+    sys.stdout = StringIO()
+
+    generator = check_random_state(0)
+    iris = load_iris()
+    X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))]
+    y = list(iris.target)
+
+    rfecv = RFECV(estimator=SVC(kernel="linear"), step=1, verbose=1)
+    rfecv.fit(X, y)
+
+    verbose_output = sys.stdout
+    verbose_output.seek(0)
+    assert len(verbose_output.readline()) > 0
+
+
+def test_rfecv_cv_results_size(global_random_seed):
+    generator = check_random_state(global_random_seed)
+    iris = load_iris()
+    X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))]
+    y = list(iris.target)  # regression test: list should be supported
+
+    # Non-regression test for varying combinations of step and
+    # min_features_to_select.
+    for step, min_features_to_select in [[2, 1], [2, 2], [3, 3]]:
+        rfecv = RFECV(
+            estimator=MockClassifier(),
+            step=step,
+            min_features_to_select=min_features_to_select,
+        )
+        rfecv.fit(X, y)
+
+        score_len = np.ceil((X.shape[1] - min_features_to_select) / step) + 1
+
+        for key in rfecv.cv_results_.keys():
+            assert len(rfecv.cv_results_[key]) == score_len
+
+        assert len(rfecv.ranking_) == X.shape[1]
+        assert rfecv.n_features_ >= min_features_to_select
+
+
+def test_rfe_estimator_tags():
+    rfe = RFE(SVC(kernel="linear"))
+    assert is_classifier(rfe)
+    # make sure that cross-validation is stratified
+    iris = load_iris()
+    score = cross_val_score(rfe, iris.data, iris.target)
+    assert score.min() > 0.7
+
+
+def test_rfe_min_step(global_random_seed):
+    n_features = 10
+    X, y = make_friedman1(
+        n_samples=50, n_features=n_features, random_state=global_random_seed
+    )
+    n_samples, n_features = X.shape
+    estimator = SVR(kernel="linear")
+
+    # Test when floor(step * n_features) <= 0
+    selector = RFE(estimator, step=0.01)
+    sel = selector.fit(X, y)
+    assert sel.support_.sum() == n_features // 2
+
+    # Test when step is between (0,1) and floor(step * n_features) > 0
+    selector = RFE(estimator, step=0.20)
+    sel = selector.fit(X, y)
+    assert sel.support_.sum() == n_features // 2
+
+    # Test when step is an integer
+    selector = RFE(estimator, step=5)
+    sel = selector.fit(X, y)
+    assert sel.support_.sum() == n_features // 2
+
+
+def test_number_of_subsets_of_features(global_random_seed):
+    # In RFE, 'number_of_subsets_of_features'
+    # = the number of iterations in '_fit'
+    # = max(ranking_)
+    # = 1 + (n_features + step - n_features_to_select - 1) // step
+    # After optimization #4534, this number
+    # = 1 + np.ceil((n_features - n_features_to_select) / float(step))
+    # This test case is to test their equivalence, refer to #4534 and #3824
+
+    def formula1(n_features, n_features_to_select, step):
+        return 1 + ((n_features + step - n_features_to_select - 1) // step)
+
+    def formula2(n_features, n_features_to_select, step):
+        return 1 + np.ceil((n_features - n_features_to_select) / float(step))
+
+    # RFE
+    # Case 1, n_features - n_features_to_select is divisible by step
+    # Case 2, n_features - n_features_to_select is not divisible by step
+    n_features_list = [11, 11]
+    n_features_to_select_list = [3, 3]
+    step_list = [2, 3]
+    for n_features, n_features_to_select, step in zip(
+        n_features_list, n_features_to_select_list, step_list
+    ):
+        generator = check_random_state(global_random_seed)
+        X = generator.normal(size=(100, n_features))
+        y = generator.rand(100).round()
+        rfe = RFE(
+            estimator=SVC(kernel="linear"),
+            n_features_to_select=n_features_to_select,
+            step=step,
+        )
+        rfe.fit(X, y)
+        # this number also equals to the maximum of ranking_
+        assert np.max(rfe.ranking_) == formula1(n_features, n_features_to_select, step)
+        assert np.max(rfe.ranking_) == formula2(n_features, n_features_to_select, step)
+
+    # In RFECV, 'fit' calls 'RFE._fit'
+    # 'number_of_subsets_of_features' of RFE
+    # = the size of each score in 'cv_results_' of RFECV
+    # = the number of iterations of the for loop before optimization #4534
+
+    # RFECV, n_features_to_select = 1
+    # Case 1, n_features - 1 is divisible by step
+    # Case 2, n_features - 1 is not divisible by step
+
+    n_features_to_select = 1
+    n_features_list = [11, 10]
+    step_list = [2, 2]
+    for n_features, step in zip(n_features_list, step_list):
+        generator = check_random_state(global_random_seed)
+        X = generator.normal(size=(100, n_features))
+        y = generator.rand(100).round()
+        rfecv = RFECV(estimator=SVC(kernel="linear"), step=step)
+        rfecv.fit(X, y)
+
+        for key in rfecv.cv_results_.keys():
+            assert len(rfecv.cv_results_[key]) == formula1(
+                n_features, n_features_to_select, step
+            )
+            assert len(rfecv.cv_results_[key]) == formula2(
+                n_features, n_features_to_select, step
+            )
+
+
+def test_rfe_cv_n_jobs(global_random_seed):
+    generator = check_random_state(global_random_seed)
+    iris = load_iris()
+    X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))]
+    y = iris.target
+
+    rfecv = RFECV(estimator=SVC(kernel="linear"))
+    rfecv.fit(X, y)
+    rfecv_ranking = rfecv.ranking_
+
+    rfecv_cv_results_ = rfecv.cv_results_
+
+    rfecv.set_params(n_jobs=2)
+    rfecv.fit(X, y)
+    assert_array_almost_equal(rfecv.ranking_, rfecv_ranking)
+
+    assert rfecv_cv_results_.keys() == rfecv.cv_results_.keys()
+    for key in rfecv_cv_results_.keys():
+        assert rfecv_cv_results_[key] == pytest.approx(rfecv.cv_results_[key])
+
+
+def test_rfe_cv_groups():
+    generator = check_random_state(0)
+    iris = load_iris()
+    number_groups = 4
+    groups = np.floor(np.linspace(0, number_groups, len(iris.target)))
+    X = iris.data
+    y = (iris.target > 0).astype(int)
+
+    est_groups = RFECV(
+        estimator=RandomForestClassifier(random_state=generator),
+        step=1,
+        scoring="accuracy",
+        cv=GroupKFold(n_splits=2),
+    )
+    est_groups.fit(X, y, groups=groups)
+    assert est_groups.n_features_ > 0
+
+
+@pytest.mark.parametrize(
+    "importance_getter", [attrgetter("regressor_.coef_"), "regressor_.coef_"]
+)
+@pytest.mark.parametrize("selector, expected_n_features", [(RFE, 5), (RFECV, 4)])
+def test_rfe_wrapped_estimator(importance_getter, selector, expected_n_features):
+    # Non-regression test for
+    # https://github.com/scikit-learn/scikit-learn/issues/15312
+    X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)
+    estimator = LinearSVR(random_state=0)
+
+    log_estimator = TransformedTargetRegressor(
+        regressor=estimator, func=np.log, inverse_func=np.exp
+    )
+
+    selector = selector(log_estimator, importance_getter=importance_getter)
+    sel = selector.fit(X, y)
+    assert sel.support_.sum() == expected_n_features
+
+
+@pytest.mark.parametrize(
+    "importance_getter, err_type",
+    [
+        ("auto", ValueError),
+        ("random", AttributeError),
+        (lambda x: x.importance, AttributeError),
+    ],
+)
+@pytest.mark.parametrize("Selector", [RFE, RFECV])
+def test_rfe_importance_getter_validation(importance_getter, err_type, Selector):
+    X, y = make_friedman1(n_samples=50, n_features=10, random_state=42)
+    estimator = LinearSVR()
+    log_estimator = TransformedTargetRegressor(
+        regressor=estimator, func=np.log, inverse_func=np.exp
+    )
+
+    with pytest.raises(err_type):
+        model = Selector(log_estimator, importance_getter=importance_getter)
+        model.fit(X, y)
+
+
+@pytest.mark.parametrize("cv", [None, 5])
+def test_rfe_allow_nan_inf_in_x(cv):
+    iris = load_iris()
+    X = iris.data
+    y = iris.target
+
+    # add nan and inf value to X
+    X[0][0] = np.nan
+    X[0][1] = np.inf
+
+    clf = MockClassifier()
+    if cv is not None:
+        rfe = RFECV(estimator=clf, cv=cv)
+    else:
+        rfe = RFE(estimator=clf)
+    rfe.fit(X, y)
+    rfe.transform(X)
+
+
+def test_w_pipeline_2d_coef_():
+    pipeline = make_pipeline(StandardScaler(), LogisticRegression())
+
+    data, y = load_iris(return_X_y=True)
+    sfm = RFE(
+        pipeline,
+        n_features_to_select=2,
+        importance_getter="named_steps.logisticregression.coef_",
+    )
+
+    sfm.fit(data, y)
+    assert sfm.transform(data).shape[1] == 2
+
+
+def test_rfecv_std_and_mean(global_random_seed):
+    generator = check_random_state(global_random_seed)
+    iris = load_iris()
+    X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))]
+    y = iris.target
+
+    rfecv = RFECV(estimator=SVC(kernel="linear"))
+    rfecv.fit(X, y)
+    split_keys = [
+        key
+        for key in rfecv.cv_results_.keys()
+        if re.search(r"split\d+_test_score", key)
+    ]
+    cv_scores = np.asarray([rfecv.cv_results_[key] for key in split_keys])
+    expected_mean = np.mean(cv_scores, axis=0)
+    expected_std = np.std(cv_scores, axis=0)
+
+    assert_allclose(rfecv.cv_results_["mean_test_score"], expected_mean)
+    assert_allclose(rfecv.cv_results_["std_test_score"], expected_std)
+
+
+@pytest.mark.parametrize(
+    ["min_features_to_select", "n_features", "step", "cv_results_n_features"],
+    [
+        [1, 4, 1, np.array([1, 2, 3, 4])],
+        [1, 5, 1, np.array([1, 2, 3, 4, 5])],
+        [1, 4, 2, np.array([1, 2, 4])],
+        [1, 5, 2, np.array([1, 3, 5])],
+        [1, 4, 3, np.array([1, 4])],
+        [1, 5, 3, np.array([1, 2, 5])],
+        [1, 4, 4, np.array([1, 4])],
+        [1, 5, 4, np.array([1, 5])],
+        [4, 4, 2, np.array([4])],
+        [4, 5, 1, np.array([4, 5])],
+        [4, 5, 2, np.array([4, 5])],
+    ],
+)
+def test_rfecv_cv_results_n_features(
+    min_features_to_select,
+    n_features,
+    step,
+    cv_results_n_features,
+):
+    X, y = make_classification(
+        n_samples=20, n_features=n_features, n_informative=n_features, n_redundant=0
+    )
+    rfecv = RFECV(
+        estimator=SVC(kernel="linear"),
+        step=step,
+        min_features_to_select=min_features_to_select,
+    )
+    rfecv.fit(X, y)
+    assert_array_equal(rfecv.cv_results_["n_features"], cv_results_n_features)
+    assert all(
+        len(value) == len(rfecv.cv_results_["n_features"])
+        for value in rfecv.cv_results_.values()
+    )
+
+
+@pytest.mark.parametrize("ClsRFE", [RFE, RFECV])
+def test_multioutput(ClsRFE):
+    X = np.random.normal(size=(10, 3))
+    y = np.random.randint(2, size=(10, 2))
+    clf = RandomForestClassifier(n_estimators=5)
+    rfe_test = ClsRFE(clf)
+    rfe_test.fit(X, y)
+
+
+@pytest.mark.parametrize("ClsRFE", [RFE, RFECV])
+def test_pipeline_with_nans(ClsRFE):
+    """Check that RFE works with pipeline that accept nans.
+
+    Non-regression test for gh-21743.
+    """
+    X, y = load_iris(return_X_y=True)
+    X[0, 0] = np.nan
+
+    pipe = make_pipeline(
+        SimpleImputer(),
+        StandardScaler(),
+        LogisticRegression(),
+    )
+
+    fs = ClsRFE(
+        estimator=pipe,
+        importance_getter="named_steps.logisticregression.coef_",
+    )
+    fs.fit(X, y)
+
+
+@pytest.mark.parametrize("ClsRFE", [RFE, RFECV])
+@pytest.mark.parametrize("PLSEstimator", [CCA, PLSCanonical, PLSRegression])
+def test_rfe_pls(ClsRFE, PLSEstimator):
+    """Check the behaviour of RFE with PLS estimators.
+
+    Non-regression test for:
+    https://github.com/scikit-learn/scikit-learn/issues/12410
+    """
+    X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)
+    estimator = PLSEstimator(n_components=1)
+    selector = ClsRFE(estimator, step=1).fit(X, y)
+    assert selector.score(X, y) > 0.5
+
+
+def test_rfe_estimator_attribute_error():
+    """Check that we raise the proper AttributeError when the estimator
+    does not implement the `decision_function` method, which is decorated with
+    `available_if`.
+
+    Non-regression test for:
+    https://github.com/scikit-learn/scikit-learn/issues/28108
+    """
+    iris = load_iris()
+
+    # `LinearRegression` does not implement 'decision_function' and should raise an
+    # AttributeError
+    rfe = RFE(estimator=LinearRegression())
+
+    outer_msg = "This 'RFE' has no attribute 'decision_function'"
+    inner_msg = "'LinearRegression' object has no attribute 'decision_function'"
+    with pytest.raises(AttributeError, match=outer_msg) as exec_info:
+        rfe.fit(iris.data, iris.target).decision_function(iris.data)
+    assert isinstance(exec_info.value.__cause__, AttributeError)
+    assert inner_msg in str(exec_info.value.__cause__)
+
+
+@pytest.mark.parametrize(
+    "ClsRFE, param", [(RFE, "n_features_to_select"), (RFECV, "min_features_to_select")]
+)
+def test_rfe_n_features_to_select_warning(ClsRFE, param):
+    """Check if the correct warning is raised when trying to initialize a RFE
+    object with a n_features_to_select attribute larger than the number of
+    features present in the X variable that is passed to the fit method
+    """
+    X, y = make_classification(n_features=20, random_state=0)
+
+    with pytest.warns(UserWarning, match=f"{param}=21 > n_features=20"):
+        # Create RFE/RFECV with n_features_to_select/min_features_to_select
+        # larger than the number of features present in the X variable
+        clsrfe = ClsRFE(estimator=LogisticRegression(), **{param: 21})
+        clsrfe.fit(X, y)
+
+
+def test_rfe_with_sample_weight():
+    """Test that `RFE` works correctly with sample weights."""
+    X, y = make_classification(random_state=0)
+    n_samples = X.shape[0]
+
+    # Assign the first half of the samples with twice the weight
+    sample_weight = np.ones_like(y)
+    sample_weight[: n_samples // 2] = 2
+
+    # Duplicate the first half of the data samples to replicate the effect
+    # of sample weights for comparison
+    X2 = np.concatenate([X, X[: n_samples // 2]], axis=0)
+    y2 = np.concatenate([y, y[: n_samples // 2]])
+
+    estimator = SVC(kernel="linear")
+
+    rfe_sw = RFE(estimator=estimator, step=0.1)
+    rfe_sw.fit(X, y, sample_weight=sample_weight)
+
+    rfe = RFE(estimator=estimator, step=0.1)
+    rfe.fit(X2, y2)
+
+    assert_array_equal(rfe_sw.ranking_, rfe.ranking_)
+
+    # Also verify that when sample weights are not doubled the results
+    # are different from the duplicated data
+    rfe_sw_2 = RFE(estimator=estimator, step=0.1)
+    sample_weight_2 = np.ones_like(y)
+    rfe_sw_2.fit(X, y, sample_weight=sample_weight_2)
+
+    assert not np.array_equal(rfe_sw_2.ranking_, rfe.ranking_)
+
+
+def test_rfe_with_joblib_threading_backend(global_random_seed):
+    X, y = make_classification(random_state=global_random_seed)
+
+    clf = LogisticRegression()
+    rfe = RFECV(
+        estimator=clf,
+        n_jobs=2,
+    )
+
+    rfe.fit(X, y)
+    ranking_ref = rfe.ranking_
+
+    with parallel_backend("threading"):
+        rfe.fit(X, y)
+
+    assert_array_equal(ranking_ref, rfe.ranking_)
+
+
+def test_results_per_cv_in_rfecv(global_random_seed):
+    """
+    Test that the results of RFECV are consistent across the different folds
+    in terms of length of the arrays.
+    """
+    X, y = make_classification(random_state=global_random_seed)
+
+    clf = LogisticRegression()
+    rfecv = RFECV(
+        estimator=clf,
+        n_jobs=2,
+        cv=5,
+    )
+
+    rfecv.fit(X, y)
+
+    assert len(rfecv.cv_results_["split1_test_score"]) == len(
+        rfecv.cv_results_["split2_test_score"]
+    )
+    assert len(rfecv.cv_results_["split1_support"]) == len(
+        rfecv.cv_results_["split2_support"]
+    )
+    assert len(rfecv.cv_results_["split1_ranking"]) == len(
+        rfecv.cv_results_["split2_ranking"]
+    )
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_sequential.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_sequential.py
new file mode 100644
index 0000000000000000000000000000000000000000..b98d5b400b84eaa68440c0dbc3891b99372444a2
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_sequential.py
@@ -0,0 +1,332 @@
+import numpy as np
+import pytest
+from numpy.testing import assert_array_equal
+
+from sklearn.cluster import KMeans
+from sklearn.datasets import make_blobs, make_classification, make_regression
+from sklearn.ensemble import HistGradientBoostingRegressor
+from sklearn.feature_selection import SequentialFeatureSelector
+from sklearn.linear_model import LinearRegression
+from sklearn.model_selection import LeaveOneGroupOut, cross_val_score
+from sklearn.neighbors import KNeighborsClassifier
+from sklearn.pipeline import make_pipeline
+from sklearn.preprocessing import StandardScaler
+from sklearn.utils.fixes import CSR_CONTAINERS
+
+
+def test_bad_n_features_to_select():
+    n_features = 5
+    X, y = make_regression(n_features=n_features)
+    sfs = SequentialFeatureSelector(LinearRegression(), n_features_to_select=n_features)
+    with pytest.raises(ValueError, match="n_features_to_select must be < n_features"):
+        sfs.fit(X, y)
+
+
+@pytest.mark.parametrize("direction", ("forward", "backward"))
+@pytest.mark.parametrize("n_features_to_select", (1, 5, 9, "auto"))
+def test_n_features_to_select(direction, n_features_to_select):
+    # Make sure n_features_to_select is respected
+
+    n_features = 10
+    X, y = make_regression(n_features=n_features, random_state=0)
+    sfs = SequentialFeatureSelector(
+        LinearRegression(),
+        n_features_to_select=n_features_to_select,
+        direction=direction,
+        cv=2,
+    )
+    sfs.fit(X, y)
+
+    if n_features_to_select == "auto":
+        n_features_to_select = n_features // 2
+
+    assert sfs.get_support(indices=True).shape[0] == n_features_to_select
+    assert sfs.n_features_to_select_ == n_features_to_select
+    assert sfs.transform(X).shape[1] == n_features_to_select
+
+
+@pytest.mark.parametrize("direction", ("forward", "backward"))
+def test_n_features_to_select_auto(direction):
+    """Check the behaviour of `n_features_to_select="auto"` with different
+    values for the parameter `tol`.
+    """
+
+    n_features = 10
+    tol = 1e-3
+    X, y = make_regression(n_features=n_features, random_state=0)
+    sfs = SequentialFeatureSelector(
+        LinearRegression(),
+        n_features_to_select="auto",
+        tol=tol,
+        direction=direction,
+        cv=2,
+    )
+    sfs.fit(X, y)
+
+    max_features_to_select = n_features - 1
+
+    assert sfs.get_support(indices=True).shape[0] <= max_features_to_select
+    assert sfs.n_features_to_select_ <= max_features_to_select
+    assert sfs.transform(X).shape[1] <= max_features_to_select
+    assert sfs.get_support(indices=True).shape[0] == sfs.n_features_to_select_
+
+
+@pytest.mark.parametrize("direction", ("forward", "backward"))
+def test_n_features_to_select_stopping_criterion(direction):
+    """Check the behaviour stopping criterion for feature selection
+    depending on the values of `n_features_to_select` and `tol`.
+
+    When `direction` is `'forward'`, select a new features at random
+    among those not currently selected in selector.support_,
+    build a new version of the data that includes all the features
+    in selector.support_ + this newly selected feature.
+    And check that the cross-validation score of the model trained on
+    this new dataset variant is lower than the model with
+    the selected forward selected features or at least does not improve
+    by more than the tol margin.
+
+    When `direction` is `'backward'`, instead of adding a new feature
+    to selector.support_, try to remove one of those selected features at random
+    And check that the cross-validation score is either decreasing or
+    not improving by more than the tol margin.
+    """
+
+    X, y = make_regression(n_features=50, n_informative=10, random_state=0)
+
+    tol = 1e-3
+
+    sfs = SequentialFeatureSelector(
+        LinearRegression(),
+        n_features_to_select="auto",
+        tol=tol,
+        direction=direction,
+        cv=2,
+    )
+    sfs.fit(X, y)
+    selected_X = sfs.transform(X)
+
+    rng = np.random.RandomState(0)
+
+    added_candidates = list(set(range(X.shape[1])) - set(sfs.get_support(indices=True)))
+    added_X = np.hstack(
+        [
+            selected_X,
+            (X[:, rng.choice(added_candidates)])[:, np.newaxis],
+        ]
+    )
+
+    removed_candidate = rng.choice(list(range(sfs.n_features_to_select_)))
+    removed_X = np.delete(selected_X, removed_candidate, axis=1)
+
+    plain_cv_score = cross_val_score(LinearRegression(), X, y, cv=2).mean()
+    sfs_cv_score = cross_val_score(LinearRegression(), selected_X, y, cv=2).mean()
+    added_cv_score = cross_val_score(LinearRegression(), added_X, y, cv=2).mean()
+    removed_cv_score = cross_val_score(LinearRegression(), removed_X, y, cv=2).mean()
+
+    assert sfs_cv_score >= plain_cv_score
+
+    if direction == "forward":
+        assert (sfs_cv_score - added_cv_score) <= tol
+        assert (sfs_cv_score - removed_cv_score) >= tol
+    else:
+        assert (added_cv_score - sfs_cv_score) <= tol
+        assert (removed_cv_score - sfs_cv_score) <= tol
+
+
+@pytest.mark.parametrize("direction", ("forward", "backward"))
+@pytest.mark.parametrize(
+    "n_features_to_select, expected",
+    (
+        (0.1, 1),
+        (1.0, 10),
+        (0.5, 5),
+    ),
+)
+def test_n_features_to_select_float(direction, n_features_to_select, expected):
+    # Test passing a float as n_features_to_select
+    X, y = make_regression(n_features=10)
+    sfs = SequentialFeatureSelector(
+        LinearRegression(),
+        n_features_to_select=n_features_to_select,
+        direction=direction,
+        cv=2,
+    )
+    sfs.fit(X, y)
+    assert sfs.n_features_to_select_ == expected
+
+
+@pytest.mark.parametrize("seed", range(10))
+@pytest.mark.parametrize("direction", ("forward", "backward"))
+@pytest.mark.parametrize(
+    "n_features_to_select, expected_selected_features",
+    [
+        (2, [0, 2]),  # f1 is dropped since it has no predictive power
+        (1, [2]),  # f2 is more predictive than f0 so it's kept
+    ],
+)
+def test_sanity(seed, direction, n_features_to_select, expected_selected_features):
+    # Basic sanity check: 3 features, only f0 and f2 are correlated with the
+    # target, f2 having a stronger correlation than f0. We expect f1 to be
+    # dropped, and f2 to always be selected.
+
+    rng = np.random.RandomState(seed)
+    n_samples = 100
+    X = rng.randn(n_samples, 3)
+    y = 3 * X[:, 0] - 10 * X[:, 2]
+
+    sfs = SequentialFeatureSelector(
+        LinearRegression(),
+        n_features_to_select=n_features_to_select,
+        direction=direction,
+        cv=2,
+    )
+    sfs.fit(X, y)
+    assert_array_equal(sfs.get_support(indices=True), expected_selected_features)
+
+
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_sparse_support(csr_container):
+    # Make sure sparse data is supported
+
+    X, y = make_regression(n_features=10)
+    X = csr_container(X)
+    sfs = SequentialFeatureSelector(
+        LinearRegression(), n_features_to_select="auto", cv=2
+    )
+    sfs.fit(X, y)
+    sfs.transform(X)
+
+
+def test_nan_support():
+    # Make sure nans are OK if the underlying estimator supports nans
+
+    rng = np.random.RandomState(0)
+    n_samples, n_features = 40, 4
+    X, y = make_regression(n_samples, n_features, random_state=0)
+    nan_mask = rng.randint(0, 2, size=(n_samples, n_features), dtype=bool)
+    X[nan_mask] = np.nan
+    sfs = SequentialFeatureSelector(
+        HistGradientBoostingRegressor(), n_features_to_select="auto", cv=2
+    )
+    sfs.fit(X, y)
+    sfs.transform(X)
+
+    with pytest.raises(ValueError, match="Input X contains NaN"):
+        # LinearRegression does not support nans
+        SequentialFeatureSelector(
+            LinearRegression(), n_features_to_select="auto", cv=2
+        ).fit(X, y)
+
+
+def test_pipeline_support():
+    # Make sure that pipelines can be passed into SFS and that SFS can be
+    # passed into a pipeline
+
+    n_samples, n_features = 50, 3
+    X, y = make_regression(n_samples, n_features, random_state=0)
+
+    # pipeline in SFS
+    pipe = make_pipeline(StandardScaler(), LinearRegression())
+    sfs = SequentialFeatureSelector(pipe, n_features_to_select="auto", cv=2)
+    sfs.fit(X, y)
+    sfs.transform(X)
+
+    # SFS in pipeline
+    sfs = SequentialFeatureSelector(
+        LinearRegression(), n_features_to_select="auto", cv=2
+    )
+    pipe = make_pipeline(StandardScaler(), sfs)
+    pipe.fit(X, y)
+    pipe.transform(X)
+
+
+@pytest.mark.parametrize("n_features_to_select", (2, 3))
+def test_unsupervised_model_fit(n_features_to_select):
+    # Make sure that models without classification labels are not being
+    # validated
+
+    X, y = make_blobs(n_features=4)
+    sfs = SequentialFeatureSelector(
+        KMeans(n_init=1),
+        n_features_to_select=n_features_to_select,
+    )
+    sfs.fit(X)
+    assert sfs.transform(X).shape[1] == n_features_to_select
+
+
+@pytest.mark.parametrize("y", ("no_validation", 1j, 99.9, np.nan, 3))
+def test_no_y_validation_model_fit(y):
+    # Make sure that other non-conventional y labels are not accepted
+
+    X, clusters = make_blobs(n_features=6)
+    sfs = SequentialFeatureSelector(
+        KMeans(),
+        n_features_to_select=3,
+    )
+
+    with pytest.raises((TypeError, ValueError)):
+        sfs.fit(X, y)
+
+
+def test_forward_neg_tol_error():
+    """Check that we raise an error when tol<0 and direction='forward'"""
+    X, y = make_regression(n_features=10, random_state=0)
+    sfs = SequentialFeatureSelector(
+        LinearRegression(),
+        n_features_to_select="auto",
+        direction="forward",
+        tol=-1e-3,
+    )
+
+    with pytest.raises(ValueError, match="tol must be strictly positive"):
+        sfs.fit(X, y)
+
+
+def test_backward_neg_tol():
+    """Check that SequentialFeatureSelector works negative tol
+
+    non-regression test for #25525
+    """
+    X, y = make_regression(n_features=10, random_state=0)
+    lr = LinearRegression()
+    initial_score = lr.fit(X, y).score(X, y)
+
+    sfs = SequentialFeatureSelector(
+        lr,
+        n_features_to_select="auto",
+        direction="backward",
+        tol=-1e-3,
+    )
+    Xr = sfs.fit_transform(X, y)
+    new_score = lr.fit(Xr, y).score(Xr, y)
+
+    assert 0 < sfs.get_support().sum() < X.shape[1]
+    assert new_score < initial_score
+
+
+def test_cv_generator_support():
+    """Check that no exception raised when cv is generator
+
+    non-regression test for #25957
+    """
+    X, y = make_classification(random_state=0)
+
+    groups = np.zeros_like(y, dtype=int)
+    groups[y.size // 2 :] = 1
+
+    cv = LeaveOneGroupOut()
+    splits = cv.split(X, y, groups=groups)
+
+    knc = KNeighborsClassifier(n_neighbors=5)
+
+    sfs = SequentialFeatureSelector(knc, n_features_to_select=5, cv=splits)
+    sfs.fit(X, y)
+
+
+def test_fit_rejects_params_with_no_routing_enabled():
+    X, y = make_classification(random_state=42)
+    est = LinearRegression()
+    sfs = SequentialFeatureSelector(estimator=est)
+
+    with pytest.raises(ValueError, match="is only supported if"):
+        sfs.fit(X, y, sample_weight=np.ones_like(y))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_variance_threshold.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_variance_threshold.py
new file mode 100644
index 0000000000000000000000000000000000000000..45e66cb338a4b7a5a410db669a13f6f9213451dc
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_variance_threshold.py
@@ -0,0 +1,72 @@
+import numpy as np
+import pytest
+
+from sklearn.feature_selection import VarianceThreshold
+from sklearn.utils._testing import assert_array_equal
+from sklearn.utils.fixes import BSR_CONTAINERS, CSC_CONTAINERS, CSR_CONTAINERS
+
+data = [[0, 1, 2, 3, 4], [0, 2, 2, 3, 5], [1, 1, 2, 4, 0]]
+
+data2 = [[-0.13725701]] * 10
+
+
+@pytest.mark.parametrize(
+    "sparse_container", [None] + BSR_CONTAINERS + CSC_CONTAINERS + CSR_CONTAINERS
+)
+def test_zero_variance(sparse_container):
+    # Test VarianceThreshold with default setting, zero variance.
+    X = data if sparse_container is None else sparse_container(data)
+    sel = VarianceThreshold().fit(X)
+    assert_array_equal([0, 1, 3, 4], sel.get_support(indices=True))
+
+
+def test_zero_variance_value_error():
+    # Test VarianceThreshold with default setting, zero variance, error cases.
+    with pytest.raises(ValueError):
+        VarianceThreshold().fit([[0, 1, 2, 3]])
+    with pytest.raises(ValueError):
+        VarianceThreshold().fit([[0, 1], [0, 1]])
+
+
+@pytest.mark.parametrize("sparse_container", [None] + CSR_CONTAINERS)
+def test_variance_threshold(sparse_container):
+    # Test VarianceThreshold with custom variance.
+    X = data if sparse_container is None else sparse_container(data)
+    X = VarianceThreshold(threshold=0.4).fit_transform(X)
+    assert (len(data), 1) == X.shape
+
+
+@pytest.mark.skipif(
+    np.var(data2) == 0,
+    reason=(
+        "This test is not valid for this platform, "
+        "as it relies on numerical instabilities."
+    ),
+)
+@pytest.mark.parametrize(
+    "sparse_container", [None] + BSR_CONTAINERS + CSC_CONTAINERS + CSR_CONTAINERS
+)
+def test_zero_variance_floating_point_error(sparse_container):
+    # Test that VarianceThreshold(0.0).fit eliminates features that have
+    # the same value in every sample, even when floating point errors
+    # cause np.var not to be 0 for the feature.
+    # See #13691
+    X = data2 if sparse_container is None else sparse_container(data2)
+    msg = "No feature in X meets the variance threshold 0.00000"
+    with pytest.raises(ValueError, match=msg):
+        VarianceThreshold().fit(X)
+
+
+@pytest.mark.parametrize(
+    "sparse_container", [None] + BSR_CONTAINERS + CSC_CONTAINERS + CSR_CONTAINERS
+)
+def test_variance_nan(sparse_container):
+    arr = np.array(data, dtype=np.float64)
+    # add single NaN and feature should still be included
+    arr[0, 0] = np.nan
+    # make all values in feature NaN and feature should be rejected
+    arr[:, 1] = np.nan
+
+    X = arr if sparse_container is None else sparse_container(arr)
+    sel = VarianceThreshold().fit(X)
+    assert_array_equal([0, 3, 4], sel.get_support(indices=True))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/linear_model/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/linear_model/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..541f164daf46a336719b4148b7b25cea73fe212c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/linear_model/__init__.py
@@ -0,0 +1,95 @@
+"""A variety of linear models."""
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+# See http://scikit-learn.sourceforge.net/modules/sgd.html and
+# http://scikit-learn.sourceforge.net/modules/linear_model.html for
+# complete documentation.
+
+from ._base import LinearRegression
+from ._bayes import ARDRegression, BayesianRidge
+from ._coordinate_descent import (
+    ElasticNet,
+    ElasticNetCV,
+    Lasso,
+    LassoCV,
+    MultiTaskElasticNet,
+    MultiTaskElasticNetCV,
+    MultiTaskLasso,
+    MultiTaskLassoCV,
+    enet_path,
+    lasso_path,
+)
+from ._glm import GammaRegressor, PoissonRegressor, TweedieRegressor
+from ._huber import HuberRegressor
+from ._least_angle import (
+    Lars,
+    LarsCV,
+    LassoLars,
+    LassoLarsCV,
+    LassoLarsIC,
+    lars_path,
+    lars_path_gram,
+)
+from ._logistic import LogisticRegression, LogisticRegressionCV
+from ._omp import (
+    OrthogonalMatchingPursuit,
+    OrthogonalMatchingPursuitCV,
+    orthogonal_mp,
+    orthogonal_mp_gram,
+)
+from ._passive_aggressive import PassiveAggressiveClassifier, PassiveAggressiveRegressor
+from ._perceptron import Perceptron
+from ._quantile import QuantileRegressor
+from ._ransac import RANSACRegressor
+from ._ridge import Ridge, RidgeClassifier, RidgeClassifierCV, RidgeCV, ridge_regression
+from ._stochastic_gradient import SGDClassifier, SGDOneClassSVM, SGDRegressor
+from ._theil_sen import TheilSenRegressor
+
+__all__ = [
+    "ARDRegression",
+    "BayesianRidge",
+    "ElasticNet",
+    "ElasticNetCV",
+    "GammaRegressor",
+    "HuberRegressor",
+    "Lars",
+    "LarsCV",
+    "Lasso",
+    "LassoCV",
+    "LassoLars",
+    "LassoLarsCV",
+    "LassoLarsIC",
+    "LinearRegression",
+    "LogisticRegression",
+    "LogisticRegressionCV",
+    "MultiTaskElasticNet",
+    "MultiTaskElasticNetCV",
+    "MultiTaskLasso",
+    "MultiTaskLassoCV",
+    "OrthogonalMatchingPursuit",
+    "OrthogonalMatchingPursuitCV",
+    "PassiveAggressiveClassifier",
+    "PassiveAggressiveRegressor",
+    "Perceptron",
+    "PoissonRegressor",
+    "QuantileRegressor",
+    "RANSACRegressor",
+    "Ridge",
+    "RidgeCV",
+    "RidgeClassifier",
+    "RidgeClassifierCV",
+    "SGDClassifier",
+    "SGDOneClassSVM",
+    "SGDRegressor",
+    "TheilSenRegressor",
+    "TweedieRegressor",
+    "enet_path",
+    "lars_path",
+    "lars_path_gram",
+    "lasso_path",
+    "orthogonal_mp",
+    "orthogonal_mp_gram",
+    "ridge_regression",
+]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/linear_model/_base.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/linear_model/_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..c059e3fa84310e4bc022d43cf159eaed3aa752fc
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/linear_model/_base.py
@@ -0,0 +1,869 @@
+"""
+Generalized Linear Models.
+"""
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+import numbers
+import warnings
+from abc import ABCMeta, abstractmethod
+from numbers import Integral, Real
+
+import numpy as np
+import scipy.sparse as sp
+from scipy import linalg, optimize, sparse
+from scipy.sparse.linalg import lsqr
+from scipy.special import expit
+
+from ..base import (
+    BaseEstimator,
+    ClassifierMixin,
+    MultiOutputMixin,
+    RegressorMixin,
+    _fit_context,
+)
+from ..utils import check_array, check_random_state
+from ..utils._array_api import (
+    _asarray_with_order,
+    _average,
+    get_namespace,
+    get_namespace_and_device,
+    indexing_dtype,
+    supported_float_dtypes,
+)
+from ..utils._param_validation import Interval
+from ..utils._seq_dataset import (
+    ArrayDataset32,
+    ArrayDataset64,
+    CSRDataset32,
+    CSRDataset64,
+)
+from ..utils.extmath import safe_sparse_dot
+from ..utils.parallel import Parallel, delayed
+from ..utils.sparsefuncs import mean_variance_axis
+from ..utils.validation import _check_sample_weight, check_is_fitted, validate_data
+
+# TODO: bayesian_ridge_regression and bayesian_regression_ard
+# should be squashed into its respective objects.
+
+SPARSE_INTERCEPT_DECAY = 0.01
+# For sparse data intercept updates are scaled by this decay factor to avoid
+# intercept oscillation.
+
+
+def make_dataset(X, y, sample_weight, random_state=None):
+    """Create ``Dataset`` abstraction for sparse and dense inputs.
+
+    This also returns the ``intercept_decay`` which is different
+    for sparse datasets.
+
+    Parameters
+    ----------
+    X : array-like, shape (n_samples, n_features)
+        Training data
+
+    y : array-like, shape (n_samples, )
+        Target values.
+
+    sample_weight : numpy array of shape (n_samples,)
+        The weight of each sample
+
+    random_state : int, RandomState instance or None (default)
+        Determines random number generation for dataset random sampling. It is not
+        used for dataset shuffling.
+        Pass an int for reproducible output across multiple function calls.
+        See :term:`Glossary `.
+
+    Returns
+    -------
+    dataset
+        The ``Dataset`` abstraction
+    intercept_decay
+        The intercept decay
+    """
+
+    rng = check_random_state(random_state)
+    # seed should never be 0 in SequentialDataset64
+    seed = rng.randint(1, np.iinfo(np.int32).max)
+
+    if X.dtype == np.float32:
+        CSRData = CSRDataset32
+        ArrayData = ArrayDataset32
+    else:
+        CSRData = CSRDataset64
+        ArrayData = ArrayDataset64
+
+    if sp.issparse(X):
+        dataset = CSRData(X.data, X.indptr, X.indices, y, sample_weight, seed=seed)
+        intercept_decay = SPARSE_INTERCEPT_DECAY
+    else:
+        X = np.ascontiguousarray(X)
+        dataset = ArrayData(X, y, sample_weight, seed=seed)
+        intercept_decay = 1.0
+
+    return dataset, intercept_decay
+
+
+def _preprocess_data(
+    X,
+    y,
+    *,
+    fit_intercept,
+    copy=True,
+    copy_y=True,
+    sample_weight=None,
+    check_input=True,
+):
+    """Common data preprocessing for fitting linear models.
+
+    This helper is in charge of the following steps:
+
+    - Ensure that `sample_weight` is an array or `None`.
+    - If `check_input=True`, perform standard input validation of `X`, `y`.
+    - Perform copies if requested to avoid side-effects in case of inplace
+      modifications of the input.
+
+    Then, if `fit_intercept=True` this preprocessing centers both `X` and `y` as
+    follows:
+        - if `X` is dense, center the data and
+        store the mean vector in `X_offset`.
+        - if `X` is sparse, store the mean in `X_offset`
+        without centering `X`. The centering is expected to be handled by the
+        linear solver where appropriate.
+        - in either case, always center `y` and store the mean in `y_offset`.
+        - both `X_offset` and `y_offset` are always weighted by `sample_weight`
+          if not set to `None`.
+
+    If `fit_intercept=False`, no centering is performed and `X_offset`, `y_offset`
+    are set to zero.
+
+    Returns
+    -------
+    X_out : {ndarray, sparse matrix} of shape (n_samples, n_features)
+        If copy=True a copy of the input X is triggered, otherwise operations are
+        inplace.
+        If input X is dense, then X_out is centered.
+    y_out : {ndarray, sparse matrix} of shape (n_samples,) or (n_samples, n_targets)
+        Centered version of y. Possibly performed inplace on input y depending
+        on the copy_y parameter.
+    X_offset : ndarray of shape (n_features,)
+        The mean per column of input X.
+    y_offset : float or ndarray of shape (n_features,)
+    X_scale : ndarray of shape (n_features,)
+        Always an array of ones. TODO: refactor the code base to make it
+        possible to remove this unused variable.
+    """
+    xp, _, device_ = get_namespace_and_device(X, y, sample_weight)
+    n_samples, n_features = X.shape
+    X_is_sparse = sp.issparse(X)
+
+    if isinstance(sample_weight, numbers.Number):
+        sample_weight = None
+    if sample_weight is not None:
+        sample_weight = xp.asarray(sample_weight)
+
+    if check_input:
+        X = check_array(
+            X, copy=copy, accept_sparse=["csr", "csc"], dtype=supported_float_dtypes(xp)
+        )
+        y = check_array(y, dtype=X.dtype, copy=copy_y, ensure_2d=False)
+    else:
+        y = xp.astype(y, X.dtype, copy=copy_y)
+        if copy:
+            if X_is_sparse:
+                X = X.copy()
+            else:
+                X = _asarray_with_order(X, order="K", copy=True, xp=xp)
+
+    dtype_ = X.dtype
+
+    if fit_intercept:
+        if X_is_sparse:
+            X_offset, X_var = mean_variance_axis(X, axis=0, weights=sample_weight)
+        else:
+            X_offset = _average(X, axis=0, weights=sample_weight, xp=xp)
+
+            X_offset = xp.astype(X_offset, X.dtype, copy=False)
+            X -= X_offset
+
+        y_offset = _average(y, axis=0, weights=sample_weight, xp=xp)
+        y -= y_offset
+    else:
+        X_offset = xp.zeros(n_features, dtype=X.dtype, device=device_)
+        if y.ndim == 1:
+            y_offset = xp.asarray(0.0, dtype=dtype_, device=device_)
+        else:
+            y_offset = xp.zeros(y.shape[1], dtype=dtype_, device=device_)
+
+    # XXX: X_scale is no longer needed. It is an historic artifact from the
+    # time where linear model exposed the normalize parameter.
+    X_scale = xp.ones(n_features, dtype=X.dtype, device=device_)
+    return X, y, X_offset, y_offset, X_scale
+
+
+# TODO: _rescale_data should be factored into _preprocess_data.
+# Currently, the fact that sag implements its own way to deal with
+# sample_weight makes the refactoring tricky.
+
+
+def _rescale_data(X, y, sample_weight, inplace=False):
+    """Rescale data sample-wise by square root of sample_weight.
+
+    For many linear models, this enables easy support for sample_weight because
+
+        (y - X w)' S (y - X w)
+
+    with S = diag(sample_weight) becomes
+
+        ||y_rescaled - X_rescaled w||_2^2
+
+    when setting
+
+        y_rescaled = sqrt(S) y
+        X_rescaled = sqrt(S) X
+
+    Returns
+    -------
+    X_rescaled : {array-like, sparse matrix}
+
+    y_rescaled : {array-like, sparse matrix}
+    """
+    # Assume that _validate_data and _check_sample_weight have been called by
+    # the caller.
+    xp, _ = get_namespace(X, y, sample_weight)
+    n_samples = X.shape[0]
+    sample_weight_sqrt = xp.sqrt(sample_weight)
+
+    if sp.issparse(X) or sp.issparse(y):
+        sw_matrix = sparse.dia_matrix(
+            (sample_weight_sqrt, 0), shape=(n_samples, n_samples)
+        )
+
+    if sp.issparse(X):
+        X = safe_sparse_dot(sw_matrix, X)
+    else:
+        if inplace:
+            X *= sample_weight_sqrt[:, None]
+        else:
+            X = X * sample_weight_sqrt[:, None]
+
+    if sp.issparse(y):
+        y = safe_sparse_dot(sw_matrix, y)
+    else:
+        if inplace:
+            if y.ndim == 1:
+                y *= sample_weight_sqrt
+            else:
+                y *= sample_weight_sqrt[:, None]
+        else:
+            if y.ndim == 1:
+                y = y * sample_weight_sqrt
+            else:
+                y = y * sample_weight_sqrt[:, None]
+    return X, y, sample_weight_sqrt
+
+
+class LinearModel(BaseEstimator, metaclass=ABCMeta):
+    """Base class for Linear Models"""
+
+    @abstractmethod
+    def fit(self, X, y):
+        """Fit model."""
+
+    def _decision_function(self, X):
+        check_is_fitted(self)
+
+        X = validate_data(self, X, accept_sparse=["csr", "csc", "coo"], reset=False)
+        coef_ = self.coef_
+        if coef_.ndim == 1:
+            return X @ coef_ + self.intercept_
+        else:
+            return X @ coef_.T + self.intercept_
+
+    def predict(self, X):
+        """
+        Predict using the linear model.
+
+        Parameters
+        ----------
+        X : array-like or sparse matrix, shape (n_samples, n_features)
+            Samples.
+
+        Returns
+        -------
+        C : array, shape (n_samples,)
+            Returns predicted values.
+        """
+        return self._decision_function(X)
+
+    def _set_intercept(self, X_offset, y_offset, X_scale):
+        """Set the intercept_"""
+
+        xp, _ = get_namespace(X_offset, y_offset, X_scale)
+
+        if self.fit_intercept:
+            # We always want coef_.dtype=X.dtype. For instance, X.dtype can differ from
+            # coef_.dtype if warm_start=True.
+            coef_ = xp.astype(self.coef_, X_scale.dtype, copy=False)
+            coef_ = self.coef_ = xp.divide(coef_, X_scale)
+
+            if coef_.ndim == 1:
+                intercept_ = y_offset - X_offset @ coef_
+            else:
+                intercept_ = y_offset - X_offset @ coef_.T
+
+            self.intercept_ = intercept_
+
+        else:
+            self.intercept_ = 0.0
+
+
+# XXX Should this derive from LinearModel? It should be a mixin, not an ABC.
+# Maybe the n_features checking can be moved to LinearModel.
+class LinearClassifierMixin(ClassifierMixin):
+    """Mixin for linear classifiers.
+
+    Handles prediction for sparse and dense X.
+    """
+
+    def decision_function(self, X):
+        """
+        Predict confidence scores for samples.
+
+        The confidence score for a sample is proportional to the signed
+        distance of that sample to the hyperplane.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            The data matrix for which we want to get the confidence scores.
+
+        Returns
+        -------
+        scores : ndarray of shape (n_samples,) or (n_samples, n_classes)
+            Confidence scores per `(n_samples, n_classes)` combination. In the
+            binary case, confidence score for `self.classes_[1]` where >0 means
+            this class would be predicted.
+        """
+        check_is_fitted(self)
+        xp, _ = get_namespace(X)
+
+        X = validate_data(self, X, accept_sparse="csr", reset=False)
+        scores = safe_sparse_dot(X, self.coef_.T, dense_output=True) + self.intercept_
+        return (
+            xp.reshape(scores, (-1,))
+            if (scores.ndim > 1 and scores.shape[1] == 1)
+            else scores
+        )
+
+    def predict(self, X):
+        """
+        Predict class labels for samples in X.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            The data matrix for which we want to get the predictions.
+
+        Returns
+        -------
+        y_pred : ndarray of shape (n_samples,)
+            Vector containing the class labels for each sample.
+        """
+        xp, _ = get_namespace(X)
+        scores = self.decision_function(X)
+        if len(scores.shape) == 1:
+            indices = xp.astype(scores > 0, indexing_dtype(xp))
+        else:
+            indices = xp.argmax(scores, axis=1)
+
+        return xp.take(self.classes_, indices, axis=0)
+
+    def _predict_proba_lr(self, X):
+        """Probability estimation for OvR logistic regression.
+
+        Positive class probabilities are computed as
+        1. / (1. + np.exp(-self.decision_function(X)));
+        multiclass is handled by normalizing that over all classes.
+        """
+        prob = self.decision_function(X)
+        expit(prob, out=prob)
+        if prob.ndim == 1:
+            return np.vstack([1 - prob, prob]).T
+        else:
+            # OvR normalization, like LibLinear's predict_probability
+            prob /= prob.sum(axis=1).reshape((prob.shape[0], -1))
+            return prob
+
+
+class SparseCoefMixin:
+    """Mixin for converting coef_ to and from CSR format.
+
+    L1-regularizing estimators should inherit this.
+    """
+
+    def densify(self):
+        """
+        Convert coefficient matrix to dense array format.
+
+        Converts the ``coef_`` member (back) to a numpy.ndarray. This is the
+        default format of ``coef_`` and is required for fitting, so calling
+        this method is only required on models that have previously been
+        sparsified; otherwise, it is a no-op.
+
+        Returns
+        -------
+        self
+            Fitted estimator.
+        """
+        msg = "Estimator, %(name)s, must be fitted before densifying."
+        check_is_fitted(self, msg=msg)
+        if sp.issparse(self.coef_):
+            self.coef_ = self.coef_.toarray()
+        return self
+
+    def sparsify(self):
+        """
+        Convert coefficient matrix to sparse format.
+
+        Converts the ``coef_`` member to a scipy.sparse matrix, which for
+        L1-regularized models can be much more memory- and storage-efficient
+        than the usual numpy.ndarray representation.
+
+        The ``intercept_`` member is not converted.
+
+        Returns
+        -------
+        self
+            Fitted estimator.
+
+        Notes
+        -----
+        For non-sparse models, i.e. when there are not many zeros in ``coef_``,
+        this may actually *increase* memory usage, so use this method with
+        care. A rule of thumb is that the number of zero elements, which can
+        be computed with ``(coef_ == 0).sum()``, must be more than 50% for this
+        to provide significant benefits.
+
+        After calling this method, further fitting with the partial_fit
+        method (if any) will not work until you call densify.
+        """
+        msg = "Estimator, %(name)s, must be fitted before sparsifying."
+        check_is_fitted(self, msg=msg)
+        self.coef_ = sp.csr_matrix(self.coef_)
+        return self
+
+
+class LinearRegression(MultiOutputMixin, RegressorMixin, LinearModel):
+    """
+    Ordinary least squares Linear Regression.
+
+    LinearRegression fits a linear model with coefficients w = (w1, ..., wp)
+    to minimize the residual sum of squares between the observed targets in
+    the dataset, and the targets predicted by the linear approximation.
+
+    Parameters
+    ----------
+    fit_intercept : bool, default=True
+        Whether to calculate the intercept for this model. If set
+        to False, no intercept will be used in calculations
+        (i.e. data is expected to be centered).
+
+    copy_X : bool, default=True
+        If True, X will be copied; else, it may be overwritten.
+
+    tol : float, default=1e-6
+        The precision of the solution (`coef_`) is determined by `tol` which
+        specifies a different convergence criterion for the `lsqr` solver.
+        `tol` is set as `atol` and `btol` of `scipy.sparse.linalg.lsqr` when
+        fitting on sparse training data. This parameter has no effect when fitting
+        on dense data.
+
+        .. versionadded:: 1.7
+
+    n_jobs : int, default=None
+        The number of jobs to use for the computation. This will only provide
+        speedup in case of sufficiently large problems, that is if firstly
+        `n_targets > 1` and secondly `X` is sparse or if `positive` is set
+        to `True`. ``None`` means 1 unless in a
+        :obj:`joblib.parallel_backend` context. ``-1`` means using all
+        processors. See :term:`Glossary ` for more details.
+
+    positive : bool, default=False
+        When set to ``True``, forces the coefficients to be positive. This
+        option is only supported for dense arrays.
+
+        For a comparison between a linear regression model with positive constraints
+        on the regression coefficients and a linear regression without such constraints,
+        see :ref:`sphx_glr_auto_examples_linear_model_plot_nnls.py`.
+
+        .. versionadded:: 0.24
+
+    Attributes
+    ----------
+    coef_ : array of shape (n_features, ) or (n_targets, n_features)
+        Estimated coefficients for the linear regression problem.
+        If multiple targets are passed during the fit (y 2D), this
+        is a 2D array of shape (n_targets, n_features), while if only
+        one target is passed, this is a 1D array of length n_features.
+
+    rank_ : int
+        Rank of matrix `X`. Only available when `X` is dense.
+
+    singular_ : array of shape (min(X, y),)
+        Singular values of `X`. Only available when `X` is dense.
+
+    intercept_ : float or array of shape (n_targets,)
+        Independent term in the linear model. Set to 0.0 if
+        `fit_intercept = False`.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    Ridge : Ridge regression addresses some of the
+        problems of Ordinary Least Squares by imposing a penalty on the
+        size of the coefficients with l2 regularization.
+    Lasso : The Lasso is a linear model that estimates
+        sparse coefficients with l1 regularization.
+    ElasticNet : Elastic-Net is a linear regression
+        model trained with both l1 and l2 -norm regularization of the
+        coefficients.
+
+    Notes
+    -----
+    From the implementation point of view, this is just plain Ordinary
+    Least Squares (scipy.linalg.lstsq) or Non Negative Least Squares
+    (scipy.optimize.nnls) wrapped as a predictor object.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from sklearn.linear_model import LinearRegression
+    >>> X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])
+    >>> # y = 1 * x_0 + 2 * x_1 + 3
+    >>> y = np.dot(X, np.array([1, 2])) + 3
+    >>> reg = LinearRegression().fit(X, y)
+    >>> reg.score(X, y)
+    1.0
+    >>> reg.coef_
+    array([1., 2.])
+    >>> reg.intercept_
+    np.float64(3.0)
+    >>> reg.predict(np.array([[3, 5]]))
+    array([16.])
+    """
+
+    _parameter_constraints: dict = {
+        "fit_intercept": ["boolean"],
+        "copy_X": ["boolean"],
+        "n_jobs": [None, Integral],
+        "positive": ["boolean"],
+        "tol": [Interval(Real, 0, None, closed="left")],
+    }
+
+    def __init__(
+        self,
+        *,
+        fit_intercept=True,
+        copy_X=True,
+        tol=1e-6,
+        n_jobs=None,
+        positive=False,
+    ):
+        self.fit_intercept = fit_intercept
+        self.copy_X = copy_X
+        self.tol = tol
+        self.n_jobs = n_jobs
+        self.positive = positive
+
+    @_fit_context(prefer_skip_nested_validation=True)
+    def fit(self, X, y, sample_weight=None):
+        """
+        Fit linear model.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            Training data.
+
+        y : array-like of shape (n_samples,) or (n_samples, n_targets)
+            Target values. Will be cast to X's dtype if necessary.
+
+        sample_weight : array-like of shape (n_samples,), default=None
+            Individual weights for each sample.
+
+            .. versionadded:: 0.17
+               parameter *sample_weight* support to LinearRegression.
+
+        Returns
+        -------
+        self : object
+            Fitted Estimator.
+        """
+        n_jobs_ = self.n_jobs
+
+        accept_sparse = False if self.positive else ["csr", "csc", "coo"]
+
+        X, y = validate_data(
+            self,
+            X,
+            y,
+            accept_sparse=accept_sparse,
+            y_numeric=True,
+            multi_output=True,
+            force_writeable=True,
+        )
+
+        has_sw = sample_weight is not None
+        if has_sw:
+            sample_weight = _check_sample_weight(
+                sample_weight, X, dtype=X.dtype, ensure_non_negative=True
+            )
+
+        # Note that neither _rescale_data nor the rest of the fit method of
+        # LinearRegression can benefit from in-place operations when X is a
+        # sparse matrix. Therefore, let's not copy X when it is sparse.
+        copy_X_in_preprocess_data = self.copy_X and not sp.issparse(X)
+
+        X, y, X_offset, y_offset, X_scale = _preprocess_data(
+            X,
+            y,
+            fit_intercept=self.fit_intercept,
+            copy=copy_X_in_preprocess_data,
+            sample_weight=sample_weight,
+        )
+
+        if has_sw:
+            # Sample weight can be implemented via a simple rescaling. Note
+            # that we safely do inplace rescaling when _preprocess_data has
+            # already made a copy if requested.
+            X, y, sample_weight_sqrt = _rescale_data(
+                X, y, sample_weight, inplace=copy_X_in_preprocess_data
+            )
+
+        if self.positive:
+            if y.ndim < 2:
+                self.coef_ = optimize.nnls(X, y)[0]
+            else:
+                # scipy.optimize.nnls cannot handle y with shape (M, K)
+                outs = Parallel(n_jobs=n_jobs_)(
+                    delayed(optimize.nnls)(X, y[:, j]) for j in range(y.shape[1])
+                )
+                self.coef_ = np.vstack([out[0] for out in outs])
+        elif sp.issparse(X):
+            X_offset_scale = X_offset / X_scale
+
+            if has_sw:
+
+                def matvec(b):
+                    return X.dot(b) - sample_weight_sqrt * b.dot(X_offset_scale)
+
+                def rmatvec(b):
+                    return X.T.dot(b) - X_offset_scale * b.dot(sample_weight_sqrt)
+
+            else:
+
+                def matvec(b):
+                    return X.dot(b) - b.dot(X_offset_scale)
+
+                def rmatvec(b):
+                    return X.T.dot(b) - X_offset_scale * b.sum()
+
+            X_centered = sparse.linalg.LinearOperator(
+                shape=X.shape, matvec=matvec, rmatvec=rmatvec
+            )
+
+            if y.ndim < 2:
+                self.coef_ = lsqr(X_centered, y, atol=self.tol, btol=self.tol)[0]
+            else:
+                # sparse_lstsq cannot handle y with shape (M, K)
+                outs = Parallel(n_jobs=n_jobs_)(
+                    delayed(lsqr)(
+                        X_centered, y[:, j].ravel(), atol=self.tol, btol=self.tol
+                    )
+                    for j in range(y.shape[1])
+                )
+                self.coef_ = np.vstack([out[0] for out in outs])
+        else:
+            # cut-off ratio for small singular values
+            cond = max(X.shape) * np.finfo(X.dtype).eps
+            self.coef_, _, self.rank_, self.singular_ = linalg.lstsq(X, y, cond=cond)
+            self.coef_ = self.coef_.T
+
+        if y.ndim == 1:
+            self.coef_ = np.ravel(self.coef_)
+        self._set_intercept(X_offset, y_offset, X_scale)
+        return self
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.input_tags.sparse = not self.positive
+        return tags
+
+
+def _check_precomputed_gram_matrix(
+    X, precompute, X_offset, X_scale, rtol=None, atol=1e-5
+):
+    """Computes a single element of the gram matrix and compares it to
+    the corresponding element of the user supplied gram matrix.
+
+    If the values do not match a ValueError will be thrown.
+
+    Parameters
+    ----------
+    X : ndarray of shape (n_samples, n_features)
+        Data array.
+
+    precompute : array-like of shape (n_features, n_features)
+        User-supplied gram matrix.
+
+    X_offset : ndarray of shape (n_features,)
+        Array of feature means used to center design matrix.
+
+    X_scale : ndarray of shape (n_features,)
+        Array of feature scale factors used to normalize design matrix.
+
+    rtol : float, default=None
+        Relative tolerance; see numpy.allclose
+        If None, it is set to 1e-4 for arrays of dtype numpy.float32 and 1e-7
+        otherwise.
+
+    atol : float, default=1e-5
+        absolute tolerance; see :func`numpy.allclose`. Note that the default
+        here is more tolerant than the default for
+        :func:`numpy.testing.assert_allclose`, where `atol=0`.
+
+    Raises
+    ------
+    ValueError
+        Raised when the provided Gram matrix is not consistent.
+    """
+
+    n_features = X.shape[1]
+    f1 = n_features // 2
+    f2 = min(f1 + 1, n_features - 1)
+
+    v1 = (X[:, f1] - X_offset[f1]) * X_scale[f1]
+    v2 = (X[:, f2] - X_offset[f2]) * X_scale[f2]
+
+    expected = np.dot(v1, v2)
+    actual = precompute[f1, f2]
+
+    dtypes = [precompute.dtype, expected.dtype]
+    if rtol is None:
+        rtols = [1e-4 if dtype == np.float32 else 1e-7 for dtype in dtypes]
+        rtol = max(rtols)
+
+    if not np.isclose(expected, actual, rtol=rtol, atol=atol):
+        raise ValueError(
+            "Gram matrix passed in via 'precompute' parameter "
+            "did not pass validation when a single element was "
+            "checked - please check that it was computed "
+            f"properly. For element ({f1},{f2}) we computed "
+            f"{expected} but the user-supplied value was "
+            f"{actual}."
+        )
+
+
+def _pre_fit(
+    X,
+    y,
+    Xy,
+    precompute,
+    fit_intercept,
+    copy,
+    check_input=True,
+    sample_weight=None,
+):
+    """Function used at beginning of fit in linear models with L1 or L0 penalty.
+
+    This function applies _preprocess_data and additionally computes the gram matrix
+    `precompute` as needed as well as `Xy`.
+    """
+    n_samples, n_features = X.shape
+
+    if sparse.issparse(X):
+        # copy is not needed here as X is not modified inplace when X is sparse
+        precompute = False
+        X, y, X_offset, y_offset, X_scale = _preprocess_data(
+            X,
+            y,
+            fit_intercept=fit_intercept,
+            copy=False,
+            check_input=check_input,
+            sample_weight=sample_weight,
+        )
+    else:
+        # copy was done in fit if necessary
+        X, y, X_offset, y_offset, X_scale = _preprocess_data(
+            X,
+            y,
+            fit_intercept=fit_intercept,
+            copy=copy,
+            check_input=check_input,
+            sample_weight=sample_weight,
+        )
+        # Rescale only in dense case. Sparse cd solver directly deals with
+        # sample_weight.
+        if sample_weight is not None:
+            # This triggers copies anyway.
+            X, y, _ = _rescale_data(X, y, sample_weight=sample_weight)
+
+    if hasattr(precompute, "__array__"):
+        if fit_intercept and not np.allclose(X_offset, np.zeros(n_features)):
+            warnings.warn(
+                (
+                    "Gram matrix was provided but X was centered to fit "
+                    "intercept: recomputing Gram matrix."
+                ),
+                UserWarning,
+            )
+            # TODO: instead of warning and recomputing, we could just center
+            # the user provided Gram matrix a-posteriori (after making a copy
+            # when `copy=True`).
+            # recompute Gram
+            precompute = "auto"
+            Xy = None
+        elif check_input:
+            # If we're going to use the user's precomputed gram matrix, we
+            # do a quick check to make sure its not totally bogus.
+            _check_precomputed_gram_matrix(X, precompute, X_offset, X_scale)
+
+    # precompute if n_samples > n_features
+    if isinstance(precompute, str) and precompute == "auto":
+        precompute = n_samples > n_features
+
+    if precompute is True:
+        # make sure that the 'precompute' array is contiguous.
+        precompute = np.empty(shape=(n_features, n_features), dtype=X.dtype, order="C")
+        np.dot(X.T, X, out=precompute)
+
+    if not hasattr(precompute, "__array__"):
+        Xy = None  # cannot use Xy if precompute is not Gram
+
+    if hasattr(precompute, "__array__") and Xy is None:
+        common_dtype = np.result_type(X.dtype, y.dtype)
+        if y.ndim == 1:
+            # Xy is 1d, make sure it is contiguous.
+            Xy = np.empty(shape=n_features, dtype=common_dtype, order="C")
+            np.dot(X.T, y, out=Xy)
+        else:
+            # Make sure that Xy is always F contiguous even if X or y are not
+            # contiguous: the goal is to make it fast to extract the data for a
+            # specific target.
+            n_targets = y.shape[1]
+            Xy = np.empty(shape=(n_features, n_targets), dtype=common_dtype, order="F")
+            np.dot(y.T, X, out=Xy.T)
+
+    return X, y, X_offset, y_offset, X_scale, precompute, Xy
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/linear_model/_bayes.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/linear_model/_bayes.py
new file mode 100644
index 0000000000000000000000000000000000000000..e519660323d80f8d8f7f607451f59d26ecb62f19
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/linear_model/_bayes.py
@@ -0,0 +1,826 @@
+"""
+Various bayesian regression
+"""
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+from math import log
+from numbers import Integral, Real
+
+import numpy as np
+from scipy import linalg
+from scipy.linalg import pinvh
+
+from ..base import RegressorMixin, _fit_context
+from ..utils import _safe_indexing
+from ..utils._param_validation import Interval
+from ..utils.extmath import fast_logdet
+from ..utils.validation import _check_sample_weight, validate_data
+from ._base import LinearModel, _preprocess_data, _rescale_data
+
+###############################################################################
+# BayesianRidge regression
+
+
+class BayesianRidge(RegressorMixin, LinearModel):
+    """Bayesian ridge regression.
+
+    Fit a Bayesian ridge model. See the Notes section for details on this
+    implementation and the optimization of the regularization parameters
+    lambda (precision of the weights) and alpha (precision of the noise).
+
+    Read more in the :ref:`User Guide `.
+    For an intuitive visualization of how the sinusoid is approximated by
+    a polynomial using different pairs of initial values, see
+    :ref:`sphx_glr_auto_examples_linear_model_plot_bayesian_ridge_curvefit.py`.
+
+    Parameters
+    ----------
+    max_iter : int, default=300
+        Maximum number of iterations over the complete dataset before
+        stopping independently of any early stopping criterion.
+
+        .. versionchanged:: 1.3
+
+    tol : float, default=1e-3
+        Stop the algorithm if w has converged.
+
+    alpha_1 : float, default=1e-6
+        Hyper-parameter : shape parameter for the Gamma distribution prior
+        over the alpha parameter.
+
+    alpha_2 : float, default=1e-6
+        Hyper-parameter : inverse scale parameter (rate parameter) for the
+        Gamma distribution prior over the alpha parameter.
+
+    lambda_1 : float, default=1e-6
+        Hyper-parameter : shape parameter for the Gamma distribution prior
+        over the lambda parameter.
+
+    lambda_2 : float, default=1e-6
+        Hyper-parameter : inverse scale parameter (rate parameter) for the
+        Gamma distribution prior over the lambda parameter.
+
+    alpha_init : float, default=None
+        Initial value for alpha (precision of the noise).
+        If not set, alpha_init is 1/Var(y).
+
+        .. versionadded:: 0.22
+
+    lambda_init : float, default=None
+        Initial value for lambda (precision of the weights).
+        If not set, lambda_init is 1.
+
+        .. versionadded:: 0.22
+
+    compute_score : bool, default=False
+        If True, compute the log marginal likelihood at each iteration of the
+        optimization.
+
+    fit_intercept : bool, default=True
+        Whether to calculate the intercept for this model.
+        The intercept is not treated as a probabilistic parameter
+        and thus has no associated variance. If set
+        to False, no intercept will be used in calculations
+        (i.e. data is expected to be centered).
+
+    copy_X : bool, default=True
+        If True, X will be copied; else, it may be overwritten.
+
+    verbose : bool, default=False
+        Verbose mode when fitting the model.
+
+    Attributes
+    ----------
+    coef_ : array-like of shape (n_features,)
+        Coefficients of the regression model (mean of distribution)
+
+    intercept_ : float
+        Independent term in decision function. Set to 0.0 if
+        `fit_intercept = False`.
+
+    alpha_ : float
+       Estimated precision of the noise.
+
+    lambda_ : float
+       Estimated precision of the weights.
+
+    sigma_ : array-like of shape (n_features, n_features)
+        Estimated variance-covariance matrix of the weights
+
+    scores_ : array-like of shape (n_iter_+1,)
+        If computed_score is True, value of the log marginal likelihood (to be
+        maximized) at each iteration of the optimization. The array starts
+        with the value of the log marginal likelihood obtained for the initial
+        values of alpha and lambda and ends with the value obtained for the
+        estimated alpha and lambda.
+
+    n_iter_ : int
+        The actual number of iterations to reach the stopping criterion.
+
+    X_offset_ : ndarray of shape (n_features,)
+        If `fit_intercept=True`, offset subtracted for centering data to a
+        zero mean. Set to np.zeros(n_features) otherwise.
+
+    X_scale_ : ndarray of shape (n_features,)
+        Set to np.ones(n_features).
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    ARDRegression : Bayesian ARD regression.
+
+    Notes
+    -----
+    There exist several strategies to perform Bayesian ridge regression. This
+    implementation is based on the algorithm described in Appendix A of
+    (Tipping, 2001) where updates of the regularization parameters are done as
+    suggested in (MacKay, 1992). Note that according to A New
+    View of Automatic Relevance Determination (Wipf and Nagarajan, 2008) these
+    update rules do not guarantee that the marginal likelihood is increasing
+    between two consecutive iterations of the optimization.
+
+    References
+    ----------
+    D. J. C. MacKay, Bayesian Interpolation, Computation and Neural Systems,
+    Vol. 4, No. 3, 1992.
+
+    M. E. Tipping, Sparse Bayesian Learning and the Relevance Vector Machine,
+    Journal of Machine Learning Research, Vol. 1, 2001.
+
+    Examples
+    --------
+    >>> from sklearn import linear_model
+    >>> clf = linear_model.BayesianRidge()
+    >>> clf.fit([[0,0], [1, 1], [2, 2]], [0, 1, 2])
+    BayesianRidge()
+    >>> clf.predict([[1, 1]])
+    array([1.])
+    """
+
+    _parameter_constraints: dict = {
+        "max_iter": [Interval(Integral, 1, None, closed="left")],
+        "tol": [Interval(Real, 0, None, closed="neither")],
+        "alpha_1": [Interval(Real, 0, None, closed="left")],
+        "alpha_2": [Interval(Real, 0, None, closed="left")],
+        "lambda_1": [Interval(Real, 0, None, closed="left")],
+        "lambda_2": [Interval(Real, 0, None, closed="left")],
+        "alpha_init": [None, Interval(Real, 0, None, closed="left")],
+        "lambda_init": [None, Interval(Real, 0, None, closed="left")],
+        "compute_score": ["boolean"],
+        "fit_intercept": ["boolean"],
+        "copy_X": ["boolean"],
+        "verbose": ["verbose"],
+    }
+
+    def __init__(
+        self,
+        *,
+        max_iter=300,
+        tol=1.0e-3,
+        alpha_1=1.0e-6,
+        alpha_2=1.0e-6,
+        lambda_1=1.0e-6,
+        lambda_2=1.0e-6,
+        alpha_init=None,
+        lambda_init=None,
+        compute_score=False,
+        fit_intercept=True,
+        copy_X=True,
+        verbose=False,
+    ):
+        self.max_iter = max_iter
+        self.tol = tol
+        self.alpha_1 = alpha_1
+        self.alpha_2 = alpha_2
+        self.lambda_1 = lambda_1
+        self.lambda_2 = lambda_2
+        self.alpha_init = alpha_init
+        self.lambda_init = lambda_init
+        self.compute_score = compute_score
+        self.fit_intercept = fit_intercept
+        self.copy_X = copy_X
+        self.verbose = verbose
+
+    @_fit_context(prefer_skip_nested_validation=True)
+    def fit(self, X, y, sample_weight=None):
+        """Fit the model.
+
+        Parameters
+        ----------
+        X : ndarray of shape (n_samples, n_features)
+            Training data.
+        y : ndarray of shape (n_samples,)
+            Target values. Will be cast to X's dtype if necessary.
+
+        sample_weight : ndarray of shape (n_samples,), default=None
+            Individual weights for each sample.
+
+            .. versionadded:: 0.20
+               parameter *sample_weight* support to BayesianRidge.
+
+        Returns
+        -------
+        self : object
+            Returns the instance itself.
+        """
+        X, y = validate_data(
+            self,
+            X,
+            y,
+            dtype=[np.float64, np.float32],
+            force_writeable=True,
+            y_numeric=True,
+        )
+        dtype = X.dtype
+        n_samples, n_features = X.shape
+
+        sw_sum = n_samples
+        y_var = y.var()
+        if sample_weight is not None:
+            sample_weight = _check_sample_weight(sample_weight, X, dtype=dtype)
+            sw_sum = sample_weight.sum()
+            y_mean = np.average(y, weights=sample_weight)
+            y_var = np.average((y - y_mean) ** 2, weights=sample_weight)
+
+        X, y, X_offset_, y_offset_, X_scale_ = _preprocess_data(
+            X,
+            y,
+            fit_intercept=self.fit_intercept,
+            copy=self.copy_X,
+            sample_weight=sample_weight,
+        )
+
+        if sample_weight is not None:
+            # Sample weight can be implemented via a simple rescaling.
+            X, y, _ = _rescale_data(X, y, sample_weight)
+
+        self.X_offset_ = X_offset_
+        self.X_scale_ = X_scale_
+
+        # Initialization of the values of the parameters
+        eps = np.finfo(np.float64).eps
+        # Add `eps` in the denominator to omit division by zero
+        alpha_ = self.alpha_init
+        lambda_ = self.lambda_init
+        if alpha_ is None:
+            alpha_ = 1.0 / (y_var + eps)
+        if lambda_ is None:
+            lambda_ = 1.0
+
+        # Avoid unintended type promotion to float64 with numpy 2
+        alpha_ = np.asarray(alpha_, dtype=dtype)
+        lambda_ = np.asarray(lambda_, dtype=dtype)
+
+        verbose = self.verbose
+        lambda_1 = self.lambda_1
+        lambda_2 = self.lambda_2
+        alpha_1 = self.alpha_1
+        alpha_2 = self.alpha_2
+
+        self.scores_ = list()
+        coef_old_ = None
+
+        XT_y = np.dot(X.T, y)
+        # Let M, N = n_samples, n_features and K = min(M, N).
+        # The posterior covariance matrix needs Vh_full: (N, N).
+        # The full SVD is only required when n_samples < n_features.
+        # When n_samples < n_features, K=M and full_matrices=True
+        # U: (M, M), S: M, Vh_full: (N, N), Vh: (M, N)
+        # When n_samples > n_features, K=N and full_matrices=False
+        # U: (M, N), S: N, Vh_full: (N, N), Vh: (N, N)
+        U, S, Vh_full = linalg.svd(X, full_matrices=(n_samples < n_features))
+        K = len(S)
+        eigen_vals_ = S**2
+        eigen_vals_full = np.zeros(n_features, dtype=dtype)
+        eigen_vals_full[0:K] = eigen_vals_
+        Vh = Vh_full[0:K, :]
+
+        # Convergence loop of the bayesian ridge regression
+        for iter_ in range(self.max_iter):
+            # update posterior mean coef_ based on alpha_ and lambda_ and
+            # compute corresponding sse (sum of squared errors)
+            coef_, sse_ = self._update_coef_(
+                X, y, n_samples, n_features, XT_y, U, Vh, eigen_vals_, alpha_, lambda_
+            )
+            if self.compute_score:
+                # compute the log marginal likelihood
+                s = self._log_marginal_likelihood(
+                    n_samples,
+                    n_features,
+                    sw_sum,
+                    eigen_vals_,
+                    alpha_,
+                    lambda_,
+                    coef_,
+                    sse_,
+                )
+                self.scores_.append(s)
+
+            # Update alpha and lambda according to (MacKay, 1992)
+            gamma_ = np.sum((alpha_ * eigen_vals_) / (lambda_ + alpha_ * eigen_vals_))
+            lambda_ = (gamma_ + 2 * lambda_1) / (np.sum(coef_**2) + 2 * lambda_2)
+            alpha_ = (sw_sum - gamma_ + 2 * alpha_1) / (sse_ + 2 * alpha_2)
+
+            # Check for convergence
+            if iter_ != 0 and np.sum(np.abs(coef_old_ - coef_)) < self.tol:
+                if verbose:
+                    print("Convergence after ", str(iter_), " iterations")
+                break
+            coef_old_ = np.copy(coef_)
+
+        self.n_iter_ = iter_ + 1
+
+        # return regularization parameters and corresponding posterior mean,
+        # log marginal likelihood and posterior covariance
+        self.alpha_ = alpha_
+        self.lambda_ = lambda_
+        self.coef_, sse_ = self._update_coef_(
+            X, y, n_samples, n_features, XT_y, U, Vh, eigen_vals_, alpha_, lambda_
+        )
+        if self.compute_score:
+            # compute the log marginal likelihood
+            s = self._log_marginal_likelihood(
+                n_samples,
+                n_features,
+                sw_sum,
+                eigen_vals_,
+                alpha_,
+                lambda_,
+                coef_,
+                sse_,
+            )
+            self.scores_.append(s)
+            self.scores_ = np.array(self.scores_)
+
+        # posterior covariance
+        self.sigma_ = np.dot(
+            Vh_full.T, Vh_full / (alpha_ * eigen_vals_full + lambda_)[:, np.newaxis]
+        )
+
+        self._set_intercept(X_offset_, y_offset_, X_scale_)
+
+        return self
+
+    def predict(self, X, return_std=False):
+        """Predict using the linear model.
+
+        In addition to the mean of the predictive distribution, also its
+        standard deviation can be returned.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            Samples.
+
+        return_std : bool, default=False
+            Whether to return the standard deviation of posterior prediction.
+
+        Returns
+        -------
+        y_mean : array-like of shape (n_samples,)
+            Mean of predictive distribution of query points.
+
+        y_std : array-like of shape (n_samples,)
+            Standard deviation of predictive distribution of query points.
+        """
+        y_mean = self._decision_function(X)
+        if not return_std:
+            return y_mean
+        else:
+            sigmas_squared_data = (np.dot(X, self.sigma_) * X).sum(axis=1)
+            y_std = np.sqrt(sigmas_squared_data + (1.0 / self.alpha_))
+            return y_mean, y_std
+
+    def _update_coef_(
+        self, X, y, n_samples, n_features, XT_y, U, Vh, eigen_vals_, alpha_, lambda_
+    ):
+        """Update posterior mean and compute corresponding sse (sum of squared errors).
+
+        Posterior mean is given by coef_ = scaled_sigma_ * X.T * y where
+        scaled_sigma_ = (lambda_/alpha_ * np.eye(n_features)
+                         + np.dot(X.T, X))^-1
+        """
+
+        if n_samples > n_features:
+            coef_ = np.linalg.multi_dot(
+                [Vh.T, Vh / (eigen_vals_ + lambda_ / alpha_)[:, np.newaxis], XT_y]
+            )
+        else:
+            coef_ = np.linalg.multi_dot(
+                [X.T, U / (eigen_vals_ + lambda_ / alpha_)[None, :], U.T, y]
+            )
+
+        # Note: we do not need to explicitly use the weights in this sum because
+        # y and X were preprocessed by _rescale_data to handle the weights.
+        sse_ = np.sum((y - np.dot(X, coef_)) ** 2)
+
+        return coef_, sse_
+
+    def _log_marginal_likelihood(
+        self, n_samples, n_features, sw_sum, eigen_vals, alpha_, lambda_, coef, sse
+    ):
+        """Log marginal likelihood."""
+        alpha_1 = self.alpha_1
+        alpha_2 = self.alpha_2
+        lambda_1 = self.lambda_1
+        lambda_2 = self.lambda_2
+
+        # compute the log of the determinant of the posterior covariance.
+        # posterior covariance is given by
+        # sigma = (lambda_ * np.eye(n_features) + alpha_ * np.dot(X.T, X))^-1
+        if n_samples > n_features:
+            logdet_sigma = -np.sum(np.log(lambda_ + alpha_ * eigen_vals))
+        else:
+            logdet_sigma = np.full(n_features, lambda_, dtype=np.array(lambda_).dtype)
+            logdet_sigma[:n_samples] += alpha_ * eigen_vals
+            logdet_sigma = -np.sum(np.log(logdet_sigma))
+
+        score = lambda_1 * log(lambda_) - lambda_2 * lambda_
+        score += alpha_1 * log(alpha_) - alpha_2 * alpha_
+        score += 0.5 * (
+            n_features * log(lambda_)
+            + sw_sum * log(alpha_)
+            - alpha_ * sse
+            - lambda_ * np.sum(coef**2)
+            + logdet_sigma
+            - sw_sum * log(2 * np.pi)
+        )
+
+        return score
+
+
+###############################################################################
+# ARD (Automatic Relevance Determination) regression
+
+
+class ARDRegression(RegressorMixin, LinearModel):
+    """Bayesian ARD regression.
+
+    Fit the weights of a regression model, using an ARD prior. The weights of
+    the regression model are assumed to be in Gaussian distributions.
+    Also estimate the parameters lambda (precisions of the distributions of the
+    weights) and alpha (precision of the distribution of the noise).
+    The estimation is done by an iterative procedures (Evidence Maximization)
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    max_iter : int, default=300
+        Maximum number of iterations.
+
+        .. versionchanged:: 1.3
+
+    tol : float, default=1e-3
+        Stop the algorithm if w has converged.
+
+    alpha_1 : float, default=1e-6
+        Hyper-parameter : shape parameter for the Gamma distribution prior
+        over the alpha parameter.
+
+    alpha_2 : float, default=1e-6
+        Hyper-parameter : inverse scale parameter (rate parameter) for the
+        Gamma distribution prior over the alpha parameter.
+
+    lambda_1 : float, default=1e-6
+        Hyper-parameter : shape parameter for the Gamma distribution prior
+        over the lambda parameter.
+
+    lambda_2 : float, default=1e-6
+        Hyper-parameter : inverse scale parameter (rate parameter) for the
+        Gamma distribution prior over the lambda parameter.
+
+    compute_score : bool, default=False
+        If True, compute the objective function at each step of the model.
+
+    threshold_lambda : float, default=10 000
+        Threshold for removing (pruning) weights with high precision from
+        the computation.
+
+    fit_intercept : bool, default=True
+        Whether to calculate the intercept for this model. If set
+        to false, no intercept will be used in calculations
+        (i.e. data is expected to be centered).
+
+    copy_X : bool, default=True
+        If True, X will be copied; else, it may be overwritten.
+
+    verbose : bool, default=False
+        Verbose mode when fitting the model.
+
+    Attributes
+    ----------
+    coef_ : array-like of shape (n_features,)
+        Coefficients of the regression model (mean of distribution)
+
+    alpha_ : float
+       estimated precision of the noise.
+
+    lambda_ : array-like of shape (n_features,)
+       estimated precisions of the weights.
+
+    sigma_ : array-like of shape (n_features, n_features)
+        estimated variance-covariance matrix of the weights
+
+    scores_ : float
+        if computed, value of the objective function (to be maximized)
+
+    n_iter_ : int
+        The actual number of iterations to reach the stopping criterion.
+
+        .. versionadded:: 1.3
+
+    intercept_ : float
+        Independent term in decision function. Set to 0.0 if
+        ``fit_intercept = False``.
+
+    X_offset_ : float
+        If `fit_intercept=True`, offset subtracted for centering data to a
+        zero mean. Set to np.zeros(n_features) otherwise.
+
+    X_scale_ : float
+        Set to np.ones(n_features).
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    BayesianRidge : Bayesian ridge regression.
+
+    References
+    ----------
+    D. J. C. MacKay, Bayesian nonlinear modeling for the prediction
+    competition, ASHRAE Transactions, 1994.
+
+    R. Salakhutdinov, Lecture notes on Statistical Machine Learning,
+    http://www.utstat.toronto.edu/~rsalakhu/sta4273/notes/Lecture2.pdf#page=15
+    Their beta is our ``self.alpha_``
+    Their alpha is our ``self.lambda_``
+    ARD is a little different than the slide: only dimensions/features for
+    which ``self.lambda_ < self.threshold_lambda`` are kept and the rest are
+    discarded.
+
+    Examples
+    --------
+    >>> from sklearn import linear_model
+    >>> clf = linear_model.ARDRegression()
+    >>> clf.fit([[0,0], [1, 1], [2, 2]], [0, 1, 2])
+    ARDRegression()
+    >>> clf.predict([[1, 1]])
+    array([1.])
+
+    -   :ref:`sphx_glr_auto_examples_linear_model_plot_ard.py` demonstrates ARD
+        Regression.
+    -   :ref:`sphx_glr_auto_examples_linear_model_plot_lasso_and_elasticnet.py`
+        showcases ARD Regression alongside Lasso and Elastic-Net for sparse,
+        correlated signals, in the presence of noise.
+    """
+
+    _parameter_constraints: dict = {
+        "max_iter": [Interval(Integral, 1, None, closed="left")],
+        "tol": [Interval(Real, 0, None, closed="left")],
+        "alpha_1": [Interval(Real, 0, None, closed="left")],
+        "alpha_2": [Interval(Real, 0, None, closed="left")],
+        "lambda_1": [Interval(Real, 0, None, closed="left")],
+        "lambda_2": [Interval(Real, 0, None, closed="left")],
+        "compute_score": ["boolean"],
+        "threshold_lambda": [Interval(Real, 0, None, closed="left")],
+        "fit_intercept": ["boolean"],
+        "copy_X": ["boolean"],
+        "verbose": ["verbose"],
+    }
+
+    def __init__(
+        self,
+        *,
+        max_iter=300,
+        tol=1.0e-3,
+        alpha_1=1.0e-6,
+        alpha_2=1.0e-6,
+        lambda_1=1.0e-6,
+        lambda_2=1.0e-6,
+        compute_score=False,
+        threshold_lambda=1.0e4,
+        fit_intercept=True,
+        copy_X=True,
+        verbose=False,
+    ):
+        self.max_iter = max_iter
+        self.tol = tol
+        self.fit_intercept = fit_intercept
+        self.alpha_1 = alpha_1
+        self.alpha_2 = alpha_2
+        self.lambda_1 = lambda_1
+        self.lambda_2 = lambda_2
+        self.compute_score = compute_score
+        self.threshold_lambda = threshold_lambda
+        self.copy_X = copy_X
+        self.verbose = verbose
+
+    @_fit_context(prefer_skip_nested_validation=True)
+    def fit(self, X, y):
+        """Fit the model according to the given training data and parameters.
+
+        Iterative procedure to maximize the evidence
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            Training vector, where `n_samples` is the number of samples and
+            `n_features` is the number of features.
+        y : array-like of shape (n_samples,)
+            Target values (integers). Will be cast to X's dtype if necessary.
+
+        Returns
+        -------
+        self : object
+            Fitted estimator.
+        """
+        X, y = validate_data(
+            self,
+            X,
+            y,
+            dtype=[np.float64, np.float32],
+            force_writeable=True,
+            y_numeric=True,
+            ensure_min_samples=2,
+        )
+        dtype = X.dtype
+
+        n_samples, n_features = X.shape
+        coef_ = np.zeros(n_features, dtype=dtype)
+
+        X, y, X_offset_, y_offset_, X_scale_ = _preprocess_data(
+            X, y, fit_intercept=self.fit_intercept, copy=self.copy_X
+        )
+
+        self.X_offset_ = X_offset_
+        self.X_scale_ = X_scale_
+
+        # Launch the convergence loop
+        keep_lambda = np.ones(n_features, dtype=bool)
+
+        lambda_1 = self.lambda_1
+        lambda_2 = self.lambda_2
+        alpha_1 = self.alpha_1
+        alpha_2 = self.alpha_2
+        verbose = self.verbose
+
+        # Initialization of the values of the parameters
+        eps = np.finfo(np.float64).eps
+        # Add `eps` in the denominator to omit division by zero if `np.var(y)`
+        # is zero.
+        # Explicitly set dtype to avoid unintended type promotion with numpy 2.
+        alpha_ = np.asarray(1.0 / (np.var(y) + eps), dtype=dtype)
+        lambda_ = np.ones(n_features, dtype=dtype)
+
+        self.scores_ = list()
+        coef_old_ = None
+
+        def update_coeff(X, y, coef_, alpha_, keep_lambda, sigma_):
+            coef_[keep_lambda] = alpha_ * np.linalg.multi_dot(
+                [sigma_, X[:, keep_lambda].T, y]
+            )
+            return coef_
+
+        update_sigma = (
+            self._update_sigma
+            if n_samples >= n_features
+            else self._update_sigma_woodbury
+        )
+        # Iterative procedure of ARDRegression
+        for iter_ in range(self.max_iter):
+            sigma_ = update_sigma(X, alpha_, lambda_, keep_lambda)
+            coef_ = update_coeff(X, y, coef_, alpha_, keep_lambda, sigma_)
+
+            # Update alpha and lambda
+            sse_ = np.sum((y - np.dot(X, coef_)) ** 2)
+            gamma_ = 1.0 - lambda_[keep_lambda] * np.diag(sigma_)
+            lambda_[keep_lambda] = (gamma_ + 2.0 * lambda_1) / (
+                (coef_[keep_lambda]) ** 2 + 2.0 * lambda_2
+            )
+            alpha_ = (n_samples - gamma_.sum() + 2.0 * alpha_1) / (sse_ + 2.0 * alpha_2)
+
+            # Prune the weights with a precision over a threshold
+            keep_lambda = lambda_ < self.threshold_lambda
+            coef_[~keep_lambda] = 0
+
+            # Compute the objective function
+            if self.compute_score:
+                s = (lambda_1 * np.log(lambda_) - lambda_2 * lambda_).sum()
+                s += alpha_1 * log(alpha_) - alpha_2 * alpha_
+                s += 0.5 * (
+                    fast_logdet(sigma_)
+                    + n_samples * log(alpha_)
+                    + np.sum(np.log(lambda_))
+                )
+                s -= 0.5 * (alpha_ * sse_ + (lambda_ * coef_**2).sum())
+                self.scores_.append(s)
+
+            # Check for convergence
+            if iter_ > 0 and np.sum(np.abs(coef_old_ - coef_)) < self.tol:
+                if verbose:
+                    print("Converged after %s iterations" % iter_)
+                break
+            coef_old_ = np.copy(coef_)
+
+            if not keep_lambda.any():
+                break
+
+        self.n_iter_ = iter_ + 1
+
+        if keep_lambda.any():
+            # update sigma and mu using updated params from the last iteration
+            sigma_ = update_sigma(X, alpha_, lambda_, keep_lambda)
+            coef_ = update_coeff(X, y, coef_, alpha_, keep_lambda, sigma_)
+        else:
+            sigma_ = np.array([]).reshape(0, 0)
+
+        self.coef_ = coef_
+        self.alpha_ = alpha_
+        self.sigma_ = sigma_
+        self.lambda_ = lambda_
+        self._set_intercept(X_offset_, y_offset_, X_scale_)
+        return self
+
+    def _update_sigma_woodbury(self, X, alpha_, lambda_, keep_lambda):
+        # See slides as referenced in the docstring note
+        # this function is used when n_samples < n_features and will invert
+        # a matrix of shape (n_samples, n_samples) making use of the
+        # woodbury formula:
+        # https://en.wikipedia.org/wiki/Woodbury_matrix_identity
+        n_samples = X.shape[0]
+        X_keep = X[:, keep_lambda]
+        inv_lambda = 1 / lambda_[keep_lambda].reshape(1, -1)
+        sigma_ = pinvh(
+            np.eye(n_samples, dtype=X.dtype) / alpha_
+            + np.dot(X_keep * inv_lambda, X_keep.T)
+        )
+        sigma_ = np.dot(sigma_, X_keep * inv_lambda)
+        sigma_ = -np.dot(inv_lambda.reshape(-1, 1) * X_keep.T, sigma_)
+        sigma_[np.diag_indices(sigma_.shape[1])] += 1.0 / lambda_[keep_lambda]
+        return sigma_
+
+    def _update_sigma(self, X, alpha_, lambda_, keep_lambda):
+        # See slides as referenced in the docstring note
+        # this function is used when n_samples >= n_features and will
+        # invert a matrix of shape (n_features, n_features)
+        X_keep = X[:, keep_lambda]
+        gram = np.dot(X_keep.T, X_keep)
+        eye = np.eye(gram.shape[0], dtype=X.dtype)
+        sigma_inv = lambda_[keep_lambda] * eye + alpha_ * gram
+        sigma_ = pinvh(sigma_inv)
+        return sigma_
+
+    def predict(self, X, return_std=False):
+        """Predict using the linear model.
+
+        In addition to the mean of the predictive distribution, also its
+        standard deviation can be returned.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            Samples.
+
+        return_std : bool, default=False
+            Whether to return the standard deviation of posterior prediction.
+
+        Returns
+        -------
+        y_mean : array-like of shape (n_samples,)
+            Mean of predictive distribution of query points.
+
+        y_std : array-like of shape (n_samples,)
+            Standard deviation of predictive distribution of query points.
+        """
+        y_mean = self._decision_function(X)
+        if return_std is False:
+            return y_mean
+        else:
+            col_index = self.lambda_ < self.threshold_lambda
+            X = _safe_indexing(X, indices=col_index, axis=1)
+            sigmas_squared_data = (np.dot(X, self.sigma_) * X).sum(axis=1)
+            y_std = np.sqrt(sigmas_squared_data + (1.0 / self.alpha_))
+            return y_mean, y_std
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/linear_model/_cd_fast.pyx b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/linear_model/_cd_fast.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..ce598ebb011d216ffdbbd70cbed507ad14bdb848
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/linear_model/_cd_fast.pyx
@@ -0,0 +1,962 @@
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+from libc.math cimport fabs
+import numpy as np
+
+from cython cimport floating
+import warnings
+from ..exceptions import ConvergenceWarning
+
+from ..utils._cython_blas cimport (
+    _axpy, _dot, _asum, _gemv, _nrm2, _copy, _scal
+)
+from ..utils._cython_blas cimport ColMajor, Trans, NoTrans
+from ..utils._typedefs cimport uint32_t
+from ..utils._random cimport our_rand_r
+
+
+# The following two functions are shamelessly copied from the tree code.
+
+cdef enum:
+    # Max value for our rand_r replacement (near the bottom).
+    # We don't use RAND_MAX because it's different across platforms and
+    # particularly tiny on Windows/MSVC.
+    # It corresponds to the maximum representable value for
+    # 32-bit signed integers (i.e. 2^31 - 1).
+    RAND_R_MAX = 2147483647
+
+
+cdef inline uint32_t rand_int(uint32_t end, uint32_t* random_state) noexcept nogil:
+    """Generate a random integer in [0; end)."""
+    return our_rand_r(random_state) % end
+
+
+cdef inline floating fmax(floating x, floating y) noexcept nogil:
+    if x > y:
+        return x
+    return y
+
+
+cdef inline floating fsign(floating f) noexcept nogil:
+    if f == 0:
+        return 0
+    elif f > 0:
+        return 1.0
+    else:
+        return -1.0
+
+
+cdef floating abs_max(int n, const floating* a) noexcept nogil:
+    """np.max(np.abs(a))"""
+    cdef int i
+    cdef floating m = fabs(a[0])
+    cdef floating d
+    for i in range(1, n):
+        d = fabs(a[i])
+        if d > m:
+            m = d
+    return m
+
+
+cdef floating max(int n, floating* a) noexcept nogil:
+    """np.max(a)"""
+    cdef int i
+    cdef floating m = a[0]
+    cdef floating d
+    for i in range(1, n):
+        d = a[i]
+        if d > m:
+            m = d
+    return m
+
+
+cdef floating diff_abs_max(int n, const floating* a, floating* b) noexcept nogil:
+    """np.max(np.abs(a - b))"""
+    cdef int i
+    cdef floating m = fabs(a[0] - b[0])
+    cdef floating d
+    for i in range(1, n):
+        d = fabs(a[i] - b[i])
+        if d > m:
+            m = d
+    return m
+
+
+message_conv = (
+    "Objective did not converge. You might want to increase "
+    "the number of iterations, check the scale of the "
+    "features or consider increasing regularisation."
+)
+
+
+message_ridge = (
+    "Linear regression models with a zero l1 penalization "
+    "strength are more efficiently fitted using one of the "
+    "solvers implemented in "
+    "sklearn.linear_model.Ridge/RidgeCV instead."
+)
+
+
+def enet_coordinate_descent(
+    floating[::1] w,
+    floating alpha,
+    floating beta,
+    const floating[::1, :] X,
+    const floating[::1] y,
+    unsigned int max_iter,
+    floating tol,
+    object rng,
+    bint random=0,
+    bint positive=0
+):
+    """Cython version of the coordinate descent algorithm
+        for Elastic-Net regression
+
+        We minimize
+
+        (1/2) * norm(y - X w, 2)^2 + alpha norm(w, 1) + (beta/2) norm(w, 2)^2
+
+    Returns
+    -------
+    w : ndarray of shape (n_features,)
+        ElasticNet coefficients.
+    gap : float
+        Achieved dual gap.
+    tol : float
+        Equals input `tol` times `np.dot(y, y)`. The tolerance used for the dual gap.
+    n_iter : int
+        Number of coordinate descent iterations.
+    """
+
+    if floating is float:
+        dtype = np.float32
+    else:
+        dtype = np.float64
+
+    # get the data information into easy vars
+    cdef unsigned int n_samples = X.shape[0]
+    cdef unsigned int n_features = X.shape[1]
+
+    # compute norms of the columns of X
+    cdef floating[::1] norm_cols_X = np.square(X).sum(axis=0)
+
+    # initial value of the residuals
+    cdef floating[::1] R = np.empty(n_samples, dtype=dtype)
+    cdef floating[::1] XtA = np.empty(n_features, dtype=dtype)
+
+    cdef floating tmp
+    cdef floating w_ii
+    cdef floating d_w_max
+    cdef floating w_max
+    cdef floating d_w_ii
+    cdef floating gap = tol + 1.0
+    cdef floating d_w_tol = tol
+    cdef floating dual_norm_XtA
+    cdef floating R_norm2
+    cdef floating w_norm2
+    cdef floating l1_norm
+    cdef floating const_
+    cdef floating A_norm2
+    cdef unsigned int ii
+    cdef unsigned int n_iter = 0
+    cdef unsigned int f_iter
+    cdef uint32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX)
+    cdef uint32_t* rand_r_state = &rand_r_state_seed
+
+    if alpha == 0 and beta == 0:
+        warnings.warn("Coordinate descent with no regularization may lead to "
+                      "unexpected results and is discouraged.")
+
+    with nogil:
+        # R = y - np.dot(X, w)
+        _copy(n_samples, &y[0], 1, &R[0], 1)
+        _gemv(ColMajor, NoTrans, n_samples, n_features, -1.0, &X[0, 0],
+              n_samples, &w[0], 1, 1.0, &R[0], 1)
+
+        # tol *= np.dot(y, y)
+        tol *= _dot(n_samples, &y[0], 1, &y[0], 1)
+
+        for n_iter in range(max_iter):
+            w_max = 0.0
+            d_w_max = 0.0
+            for f_iter in range(n_features):  # Loop over coordinates
+                if random:
+                    ii = rand_int(n_features, rand_r_state)
+                else:
+                    ii = f_iter
+
+                if norm_cols_X[ii] == 0.0:
+                    continue
+
+                w_ii = w[ii]  # Store previous value
+
+                if w_ii != 0.0:
+                    # R += w_ii * X[:,ii]
+                    _axpy(n_samples, w_ii, &X[0, ii], 1, &R[0], 1)
+
+                # tmp = (X[:,ii]*R).sum()
+                tmp = _dot(n_samples, &X[0, ii], 1, &R[0], 1)
+
+                if positive and tmp < 0:
+                    w[ii] = 0.0
+                else:
+                    w[ii] = (fsign(tmp) * fmax(fabs(tmp) - alpha, 0)
+                             / (norm_cols_X[ii] + beta))
+
+                if w[ii] != 0.0:
+                    # R -=  w[ii] * X[:,ii] # Update residual
+                    _axpy(n_samples, -w[ii], &X[0, ii], 1, &R[0], 1)
+
+                # update the maximum absolute coefficient update
+                d_w_ii = fabs(w[ii] - w_ii)
+                d_w_max = fmax(d_w_max, d_w_ii)
+
+                w_max = fmax(w_max, fabs(w[ii]))
+
+            if (
+                w_max == 0.0
+                or d_w_max / w_max < d_w_tol
+                or n_iter == max_iter - 1
+            ):
+                # the biggest coordinate update of this iteration was smaller
+                # than the tolerance: check the duality gap as ultimate
+                # stopping criterion
+
+                # XtA = np.dot(X.T, R) - beta * w
+                _copy(n_features, &w[0], 1, &XtA[0], 1)
+                _gemv(ColMajor, Trans,
+                      n_samples, n_features, 1.0, &X[0, 0], n_samples,
+                      &R[0], 1,
+                      -beta, &XtA[0], 1)
+
+                if positive:
+                    dual_norm_XtA = max(n_features, &XtA[0])
+                else:
+                    dual_norm_XtA = abs_max(n_features, &XtA[0])
+
+                # R_norm2 = np.dot(R, R)
+                R_norm2 = _dot(n_samples, &R[0], 1, &R[0], 1)
+
+                # w_norm2 = np.dot(w, w)
+                w_norm2 = _dot(n_features, &w[0], 1, &w[0], 1)
+
+                if (dual_norm_XtA > alpha):
+                    const_ = alpha / dual_norm_XtA
+                    A_norm2 = R_norm2 * (const_ ** 2)
+                    gap = 0.5 * (R_norm2 + A_norm2)
+                else:
+                    const_ = 1.0
+                    gap = R_norm2
+
+                l1_norm = _asum(n_features, &w[0], 1)
+
+                gap += (alpha * l1_norm
+                        - const_ * _dot(n_samples, &R[0], 1, &y[0], 1)  # np.dot(R.T, y)
+                        + 0.5 * beta * (1 + const_ ** 2) * (w_norm2))
+
+                if gap < tol:
+                    # return if we reached desired tolerance
+                    break
+
+        else:
+            # for/else, runs if for doesn't end with a `break`
+            with gil:
+                message = (
+                    message_conv +
+                    f" Duality gap: {gap:.3e}, tolerance: {tol:.3e}"
+                )
+                if alpha < np.finfo(np.float64).eps:
+                    message += "\n" + message_ridge
+                warnings.warn(message, ConvergenceWarning)
+
+    return np.asarray(w), gap, tol, n_iter + 1
+
+
+def sparse_enet_coordinate_descent(
+    floating[::1] w,
+    floating alpha,
+    floating beta,
+    const floating[::1] X_data,
+    const int[::1] X_indices,
+    const int[::1] X_indptr,
+    const floating[::1] y,
+    const floating[::1] sample_weight,
+    const floating[::1] X_mean,
+    unsigned int max_iter,
+    floating tol,
+    object rng,
+    bint random=0,
+    bint positive=0,
+):
+    """Cython version of the coordinate descent algorithm for Elastic-Net
+
+    We minimize:
+
+        1/2 * norm(y - Z w, 2)^2 + alpha * norm(w, 1) + (beta/2) * norm(w, 2)^2
+
+    where Z = X - X_mean.
+    With sample weights sw, this becomes
+
+        1/2 * sum(sw * (y - Z w)^2, axis=0) + alpha * norm(w, 1)
+        + (beta/2) * norm(w, 2)^2
+
+    and X_mean is the weighted average of X (per column).
+
+    Returns
+    -------
+    w : ndarray of shape (n_features,)
+        ElasticNet coefficients.
+    gap : float
+        Achieved dual gap.
+    tol : float
+        Equals input `tol` times `np.dot(y, y)`. The tolerance used for the dual gap.
+    n_iter : int
+        Number of coordinate descent iterations.
+    """
+    # Notes for sample_weight:
+    # For dense X, one centers X and y and then rescales them by sqrt(sample_weight).
+    # Here, for sparse X, we get the sample_weight averaged center X_mean. We take care
+    # that every calculation results as if we had rescaled y and X (and therefore also
+    # X_mean) by sqrt(sample_weight) without actually calculating the square root.
+    # We work with:
+    #     yw = sample_weight * y
+    #     R = sample_weight * residual
+    #     norm_cols_X = np.sum(sample_weight * (X - X_mean)**2, axis=0)
+
+    if floating is float:
+        dtype = np.float32
+    else:
+        dtype = np.float64
+
+    # get the data information into easy vars
+    cdef unsigned int n_samples = y.shape[0]
+    cdef unsigned int n_features = w.shape[0]
+
+    # compute norms of the columns of X
+    cdef floating[:] norm_cols_X = np.zeros(n_features, dtype=dtype)
+
+    # initial value of the residuals
+    # R = y - Zw, weighted version R = sample_weight * (y - Zw)
+    cdef floating[::1] R
+    cdef floating[::1] XtA = np.empty(n_features, dtype=dtype)
+    cdef const floating[::1] yw
+
+    cdef floating tmp
+    cdef floating w_ii
+    cdef floating d_w_max
+    cdef floating w_max
+    cdef floating d_w_ii
+    cdef floating gap = tol + 1.0
+    cdef floating d_w_tol = tol
+    cdef floating dual_norm_XtA
+    cdef floating X_mean_ii
+    cdef floating R_sum = 0.0
+    cdef floating R_norm2
+    cdef floating w_norm2
+    cdef floating l1_norm
+    cdef floating const_
+    cdef floating A_norm2
+    cdef floating normalize_sum
+    cdef unsigned int ii
+    cdef unsigned int jj
+    cdef unsigned int n_iter = 0
+    cdef unsigned int f_iter
+    cdef unsigned int startptr = X_indptr[0]
+    cdef unsigned int endptr
+    cdef uint32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX)
+    cdef uint32_t* rand_r_state = &rand_r_state_seed
+    cdef bint center = False
+    cdef bint no_sample_weights = sample_weight is None
+    cdef int kk
+
+    if no_sample_weights:
+        yw = y
+        R = y.copy()
+    else:
+        yw = np.multiply(sample_weight, y)
+        R = yw.copy()
+
+    with nogil:
+        # center = (X_mean != 0).any()
+        for ii in range(n_features):
+            if X_mean[ii]:
+                center = True
+                break
+
+        # R = y - np.dot(X, w)
+        for ii in range(n_features):
+            X_mean_ii = X_mean[ii]
+            endptr = X_indptr[ii + 1]
+            normalize_sum = 0.0
+            w_ii = w[ii]
+
+            if no_sample_weights:
+                for jj in range(startptr, endptr):
+                    normalize_sum += (X_data[jj] - X_mean_ii) ** 2
+                    R[X_indices[jj]] -= X_data[jj] * w_ii
+                norm_cols_X[ii] = normalize_sum + \
+                    (n_samples - endptr + startptr) * X_mean_ii ** 2
+                if center:
+                    for jj in range(n_samples):
+                        R[jj] += X_mean_ii * w_ii
+                        R_sum += R[jj]
+            else:
+                # R = sw * (y - np.dot(X, w))
+                for jj in range(startptr, endptr):
+                    tmp = sample_weight[X_indices[jj]]
+                    # second term will be subtracted by loop over range(n_samples)
+                    normalize_sum += (tmp * (X_data[jj] - X_mean_ii) ** 2
+                                      - tmp * X_mean_ii ** 2)
+                    R[X_indices[jj]] -= tmp * X_data[jj] * w_ii
+                if center:
+                    for jj in range(n_samples):
+                        normalize_sum += sample_weight[jj] * X_mean_ii ** 2
+                        R[jj] += sample_weight[jj] * X_mean_ii * w_ii
+                        R_sum += R[jj]
+                norm_cols_X[ii] = normalize_sum
+            startptr = endptr
+
+        # Note: No need to update R_sum from here on because the update terms cancel
+        # each other: w_ii * np.sum(X[:,ii] - X_mean[ii]) = 0. R_sum is only ever
+        # needed and calculated if X_mean is provided.
+
+        # tol *= np.dot(y, y)
+        # with sample weights: tol *= y @ (sw * y)
+        tol *= _dot(n_samples, &y[0], 1, &yw[0], 1)
+
+        for n_iter in range(max_iter):
+
+            w_max = 0.0
+            d_w_max = 0.0
+
+            for f_iter in range(n_features):  # Loop over coordinates
+                if random:
+                    ii = rand_int(n_features, rand_r_state)
+                else:
+                    ii = f_iter
+
+                if norm_cols_X[ii] == 0.0:
+                    continue
+
+                startptr = X_indptr[ii]
+                endptr = X_indptr[ii + 1]
+                w_ii = w[ii]  # Store previous value
+                X_mean_ii = X_mean[ii]
+
+                if w_ii != 0.0:
+                    # R += w_ii * X[:,ii]
+                    if no_sample_weights:
+                        for jj in range(startptr, endptr):
+                            R[X_indices[jj]] += X_data[jj] * w_ii
+                        if center:
+                            for jj in range(n_samples):
+                                R[jj] -= X_mean_ii * w_ii
+                    else:
+                        for jj in range(startptr, endptr):
+                            tmp = sample_weight[X_indices[jj]]
+                            R[X_indices[jj]] += tmp * X_data[jj] * w_ii
+                        if center:
+                            for jj in range(n_samples):
+                                R[jj] -= sample_weight[jj] * X_mean_ii * w_ii
+
+                # tmp = (X[:,ii] * R).sum()
+                tmp = 0.0
+                for jj in range(startptr, endptr):
+                    tmp += R[X_indices[jj]] * X_data[jj]
+
+                if center:
+                    tmp -= R_sum * X_mean_ii
+
+                if positive and tmp < 0.0:
+                    w[ii] = 0.0
+                else:
+                    w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \
+                            / (norm_cols_X[ii] + beta)
+
+                if w[ii] != 0.0:
+                    # R -=  w[ii] * X[:,ii] # Update residual
+                    if no_sample_weights:
+                        for jj in range(startptr, endptr):
+                            R[X_indices[jj]] -= X_data[jj] * w[ii]
+                        if center:
+                            for jj in range(n_samples):
+                                R[jj] += X_mean_ii * w[ii]
+                    else:
+                        for jj in range(startptr, endptr):
+                            tmp = sample_weight[X_indices[jj]]
+                            R[X_indices[jj]] -= tmp * X_data[jj] * w[ii]
+                        if center:
+                            for jj in range(n_samples):
+                                R[jj] += sample_weight[jj] * X_mean_ii * w[ii]
+
+                # update the maximum absolute coefficient update
+                d_w_ii = fabs(w[ii] - w_ii)
+                d_w_max = fmax(d_w_max, d_w_ii)
+
+                w_max = fmax(w_max, fabs(w[ii]))
+
+            if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1:
+                # the biggest coordinate update of this iteration was smaller than
+                # the tolerance: check the duality gap as ultimate stopping
+                # criterion
+
+                # XtA = X.T @ R - beta * w
+                # sparse X.T / dense R dot product
+                for ii in range(n_features):
+                    XtA[ii] = 0.0
+                    for kk in range(X_indptr[ii], X_indptr[ii + 1]):
+                        XtA[ii] += X_data[kk] * R[X_indices[kk]]
+
+                    if center:
+                        XtA[ii] -= X_mean[ii] * R_sum
+                    XtA[ii] -= beta * w[ii]
+
+                if positive:
+                    dual_norm_XtA = max(n_features, &XtA[0])
+                else:
+                    dual_norm_XtA = abs_max(n_features, &XtA[0])
+
+                # R_norm2 = np.dot(R, R)
+                if no_sample_weights:
+                    R_norm2 = _dot(n_samples, &R[0], 1, &R[0], 1)
+                else:
+                    R_norm2 = 0.0
+                    for jj in range(n_samples):
+                        # R is already multiplied by sample_weight
+                        if sample_weight[jj] != 0:
+                            R_norm2 += (R[jj] ** 2) / sample_weight[jj]
+
+                # w_norm2 = np.dot(w, w)
+                w_norm2 = _dot(n_features, &w[0], 1, &w[0], 1)
+                if (dual_norm_XtA > alpha):
+                    const_ = alpha / dual_norm_XtA
+                    A_norm2 = R_norm2 * const_**2
+                    gap = 0.5 * (R_norm2 + A_norm2)
+                else:
+                    const_ = 1.0
+                    gap = R_norm2
+
+                l1_norm = _asum(n_features, &w[0], 1)
+
+                gap += (alpha * l1_norm
+                        - const_ * _dot(n_samples, &R[0], 1, &y[0], 1)  # np.dot(R.T, y)
+                        + 0.5 * beta * (1 + const_ ** 2) * w_norm2)
+
+                if gap < tol:
+                    # return if we reached desired tolerance
+                    break
+
+        else:
+            # for/else, runs if for doesn't end with a `break`
+            with gil:
+                message = (
+                    message_conv +
+                    f" Duality gap: {gap:.3e}, tolerance: {tol:.3e}"
+                )
+                if alpha < np.finfo(np.float64).eps:
+                    message += "\n" + message_ridge
+                warnings.warn(message, ConvergenceWarning)
+
+    return np.asarray(w), gap, tol, n_iter + 1
+
+
+def enet_coordinate_descent_gram(
+    floating[::1] w,
+    floating alpha,
+    floating beta,
+    const floating[:, ::1] Q,
+    const floating[::1] q,
+    const floating[:] y,
+    unsigned int max_iter,
+    floating tol,
+    object rng,
+    bint random=0,
+    bint positive=0
+):
+    """Cython version of the coordinate descent algorithm
+        for Elastic-Net regression
+
+        We minimize
+
+        (1/2) * w^T Q w - q^T w + alpha norm(w, 1) + (beta/2) * norm(w, 2)^2
+
+        which amount to the Elastic-Net problem when:
+        Q = X^T X (Gram matrix)
+        q = X^T y
+
+    Returns
+    -------
+    w : ndarray of shape (n_features,)
+        ElasticNet coefficients.
+    gap : float
+        Achieved dual gap.
+    tol : float
+        Equals input `tol` times `np.dot(y, y)`. The tolerance used for the dual gap.
+    n_iter : int
+        Number of coordinate descent iterations.
+    """
+
+    if floating is float:
+        dtype = np.float32
+    else:
+        dtype = np.float64
+
+    # get the data information into easy vars
+    cdef unsigned int n_features = Q.shape[0]
+
+    # initial value "Q w" which will be kept of up to date in the iterations
+    cdef floating[:] H = np.dot(Q, w)
+
+    cdef floating[:] XtA = np.zeros(n_features, dtype=dtype)
+    cdef floating tmp
+    cdef floating w_ii
+    cdef floating d_w_max
+    cdef floating w_max
+    cdef floating d_w_ii
+    cdef floating q_dot_w
+    cdef floating w_norm2
+    cdef floating gap = tol + 1.0
+    cdef floating d_w_tol = tol
+    cdef floating dual_norm_XtA
+    cdef unsigned int ii
+    cdef unsigned int n_iter = 0
+    cdef unsigned int f_iter
+    cdef uint32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX)
+    cdef uint32_t* rand_r_state = &rand_r_state_seed
+
+    cdef floating y_norm2 = np.dot(y, y)
+    cdef floating* w_ptr = &w[0]
+    cdef const floating* Q_ptr = &Q[0, 0]
+    cdef const floating* q_ptr = &q[0]
+    cdef floating* H_ptr = &H[0]
+    cdef floating* XtA_ptr = &XtA[0]
+    tol = tol * y_norm2
+
+    if alpha == 0:
+        warnings.warn(
+            "Coordinate descent without L1 regularization may "
+            "lead to unexpected results and is discouraged. "
+            "Set l1_ratio > 0 to add L1 regularization."
+        )
+
+    with nogil:
+        for n_iter in range(max_iter):
+            w_max = 0.0
+            d_w_max = 0.0
+            for f_iter in range(n_features):  # Loop over coordinates
+                if random:
+                    ii = rand_int(n_features, rand_r_state)
+                else:
+                    ii = f_iter
+
+                if Q[ii, ii] == 0.0:
+                    continue
+
+                w_ii = w[ii]  # Store previous value
+
+                if w_ii != 0.0:
+                    # H -= w_ii * Q[ii]
+                    _axpy(n_features, -w_ii, Q_ptr + ii * n_features, 1,
+                          H_ptr, 1)
+
+                tmp = q[ii] - H[ii]
+
+                if positive and tmp < 0:
+                    w[ii] = 0.0
+                else:
+                    w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \
+                        / (Q[ii, ii] + beta)
+
+                if w[ii] != 0.0:
+                    # H +=  w[ii] * Q[ii] # Update H = X.T X w
+                    _axpy(n_features, w[ii], Q_ptr + ii * n_features, 1,
+                          H_ptr, 1)
+
+                # update the maximum absolute coefficient update
+                d_w_ii = fabs(w[ii] - w_ii)
+                if d_w_ii > d_w_max:
+                    d_w_max = d_w_ii
+
+                if fabs(w[ii]) > w_max:
+                    w_max = fabs(w[ii])
+
+            if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1:
+                # the biggest coordinate update of this iteration was smaller than
+                # the tolerance: check the duality gap as ultimate stopping
+                # criterion
+
+                # q_dot_w = np.dot(w, q)
+                q_dot_w = _dot(n_features, w_ptr, 1, q_ptr, 1)
+
+                for ii in range(n_features):
+                    XtA[ii] = q[ii] - H[ii] - beta * w[ii]
+                if positive:
+                    dual_norm_XtA = max(n_features, XtA_ptr)
+                else:
+                    dual_norm_XtA = abs_max(n_features, XtA_ptr)
+
+                # temp = np.sum(w * H)
+                tmp = 0.0
+                for ii in range(n_features):
+                    tmp += w[ii] * H[ii]
+                R_norm2 = y_norm2 + tmp - 2.0 * q_dot_w
+
+                # w_norm2 = np.dot(w, w)
+                w_norm2 = _dot(n_features, &w[0], 1, &w[0], 1)
+
+                if (dual_norm_XtA > alpha):
+                    const_ = alpha / dual_norm_XtA
+                    A_norm2 = R_norm2 * (const_ ** 2)
+                    gap = 0.5 * (R_norm2 + A_norm2)
+                else:
+                    const_ = 1.0
+                    gap = R_norm2
+
+                # The call to asum is equivalent to the L1 norm of w
+                gap += (
+                    alpha * _asum(n_features, &w[0], 1)
+                    - const_ * y_norm2
+                    + const_ * q_dot_w
+                    + 0.5 * beta * (1 + const_ ** 2) * w_norm2
+                )
+
+                if gap < tol:
+                    # return if we reached desired tolerance
+                    break
+
+        else:
+            # for/else, runs if for doesn't end with a `break`
+            with gil:
+                message = (
+                    message_conv +
+                    f" Duality gap: {gap:.3e}, tolerance: {tol:.3e}"
+                )
+                warnings.warn(message, ConvergenceWarning)
+
+    return np.asarray(w), gap, tol, n_iter + 1
+
+
+def enet_coordinate_descent_multi_task(
+    const floating[::1, :] W,
+    floating l1_reg,
+    floating l2_reg,
+    const floating[::1, :] X,
+    const floating[::1, :] Y,
+    unsigned int max_iter,
+    floating tol,
+    object rng,
+    bint random=0
+):
+    """Cython version of the coordinate descent algorithm
+        for Elastic-Net multi-task regression
+
+        We minimize
+
+        0.5 * norm(Y - X W.T, 2)^2 + l1_reg ||W.T||_21 + 0.5 * l2_reg norm(W.T, 2)^2
+
+    Returns
+    -------
+    W : ndarray of shape (n_tasks, n_features)
+        ElasticNet coefficients.
+    gap : float
+        Achieved dual gap.
+    tol : float
+        Equals input `tol` times `np.dot(y, y)`. The tolerance used for the dual gap.
+    n_iter : int
+        Number of coordinate descent iterations.
+    """
+
+    if floating is float:
+        dtype = np.float32
+    else:
+        dtype = np.float64
+
+    # get the data information into easy vars
+    cdef unsigned int n_samples = X.shape[0]
+    cdef unsigned int n_features = X.shape[1]
+    cdef unsigned int n_tasks = Y.shape[1]
+
+    # to store XtA
+    cdef floating[:, ::1] XtA = np.zeros((n_features, n_tasks), dtype=dtype)
+    cdef floating XtA_axis1norm
+    cdef floating dual_norm_XtA
+
+    # initial value of the residuals
+    cdef floating[::1, :] R = np.zeros((n_samples, n_tasks), dtype=dtype, order='F')
+
+    cdef floating[::1] norm_cols_X = np.zeros(n_features, dtype=dtype)
+    cdef floating[::1] tmp = np.zeros(n_tasks, dtype=dtype)
+    cdef floating[::1] w_ii = np.zeros(n_tasks, dtype=dtype)
+    cdef floating d_w_max
+    cdef floating w_max
+    cdef floating d_w_ii
+    cdef floating nn
+    cdef floating W_ii_abs_max
+    cdef floating gap = tol + 1.0
+    cdef floating d_w_tol = tol
+    cdef floating R_norm
+    cdef floating w_norm
+    cdef floating ry_sum
+    cdef floating l21_norm
+    cdef unsigned int ii
+    cdef unsigned int jj
+    cdef unsigned int n_iter = 0
+    cdef unsigned int f_iter
+    cdef uint32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX)
+    cdef uint32_t* rand_r_state = &rand_r_state_seed
+
+    cdef const floating* X_ptr = &X[0, 0]
+    cdef const floating* Y_ptr = &Y[0, 0]
+
+    if l1_reg == 0:
+        warnings.warn(
+            "Coordinate descent with l1_reg=0 may lead to unexpected"
+            " results and is discouraged."
+        )
+
+    with nogil:
+        # norm_cols_X = (np.asarray(X) ** 2).sum(axis=0)
+        for ii in range(n_features):
+            norm_cols_X[ii] = _nrm2(n_samples, X_ptr + ii * n_samples, 1) ** 2
+
+        # R = Y - np.dot(X, W.T)
+        _copy(n_samples * n_tasks, Y_ptr, 1, &R[0, 0], 1)
+        for ii in range(n_features):
+            for jj in range(n_tasks):
+                if W[jj, ii] != 0:
+                    _axpy(n_samples, -W[jj, ii], X_ptr + ii * n_samples, 1,
+                          &R[0, jj], 1)
+
+        # tol = tol * linalg.norm(Y, ord='fro') ** 2
+        tol = tol * _nrm2(n_samples * n_tasks, Y_ptr, 1) ** 2
+
+        for n_iter in range(max_iter):
+            w_max = 0.0
+            d_w_max = 0.0
+            for f_iter in range(n_features):  # Loop over coordinates
+                if random:
+                    ii = rand_int(n_features, rand_r_state)
+                else:
+                    ii = f_iter
+
+                if norm_cols_X[ii] == 0.0:
+                    continue
+
+                # w_ii = W[:, ii] # Store previous value
+                _copy(n_tasks, &W[0, ii], 1, &w_ii[0], 1)
+
+                # Using Numpy:
+                # R += np.dot(X[:, ii][:, None], w_ii[None, :]) # rank 1 update
+                # Using Blas Level2:
+                # _ger(RowMajor, n_samples, n_tasks, 1.0,
+                #      &X[0, ii], 1,
+                #      &w_ii[0], 1, &R[0, 0], n_tasks)
+                # Using Blas Level1 and for loop to avoid slower threads
+                # for such small vectors
+                for jj in range(n_tasks):
+                    if w_ii[jj] != 0:
+                        _axpy(n_samples, w_ii[jj], X_ptr + ii * n_samples, 1,
+                              &R[0, jj], 1)
+
+                # Using numpy:
+                # tmp = np.dot(X[:, ii][None, :], R).ravel()
+                # Using BLAS Level 2:
+                # _gemv(RowMajor, Trans, n_samples, n_tasks, 1.0, &R[0, 0],
+                #       n_tasks, &X[0, ii], 1, 0.0, &tmp[0], 1)
+                # Using BLAS Level 1 (faster for small vectors like here):
+                for jj in range(n_tasks):
+                    tmp[jj] = _dot(n_samples, X_ptr + ii * n_samples, 1,
+                                   &R[0, jj], 1)
+
+                # nn = sqrt(np.sum(tmp ** 2))
+                nn = _nrm2(n_tasks, &tmp[0], 1)
+
+                # W[:, ii] = tmp * fmax(1. - l1_reg / nn, 0) / (norm_cols_X[ii] + l2_reg)
+                _copy(n_tasks, &tmp[0], 1, &W[0, ii], 1)
+                _scal(n_tasks, fmax(1. - l1_reg / nn, 0) / (norm_cols_X[ii] + l2_reg),
+                      &W[0, ii], 1)
+
+                # Using numpy:
+                # R -= np.dot(X[:, ii][:, None], W[:, ii][None, :])
+                # Using BLAS Level 2:
+                # Update residual : rank 1 update
+                # _ger(RowMajor, n_samples, n_tasks, -1.0,
+                #      &X[0, ii], 1, &W[0, ii], 1,
+                #      &R[0, 0], n_tasks)
+                # Using BLAS Level 1 (faster for small vectors like here):
+                for jj in range(n_tasks):
+                    if W[jj, ii] != 0:
+                        _axpy(n_samples, -W[jj, ii], X_ptr + ii * n_samples, 1,
+                              &R[0, jj], 1)
+
+                # update the maximum absolute coefficient update
+                d_w_ii = diff_abs_max(n_tasks, &W[0, ii], &w_ii[0])
+
+                if d_w_ii > d_w_max:
+                    d_w_max = d_w_ii
+
+                W_ii_abs_max = abs_max(n_tasks, &W[0, ii])
+                if W_ii_abs_max > w_max:
+                    w_max = W_ii_abs_max
+
+            if w_max == 0.0 or d_w_max / w_max < d_w_tol or n_iter == max_iter - 1:
+                # the biggest coordinate update of this iteration was smaller than
+                # the tolerance: check the duality gap as ultimate stopping
+                # criterion
+
+                # XtA = np.dot(X.T, R) - l2_reg * W.T
+                for ii in range(n_features):
+                    for jj in range(n_tasks):
+                        XtA[ii, jj] = _dot(
+                            n_samples, X_ptr + ii * n_samples, 1, &R[0, jj], 1
+                            ) - l2_reg * W[jj, ii]
+
+                # dual_norm_XtA = np.max(np.sqrt(np.sum(XtA ** 2, axis=1)))
+                dual_norm_XtA = 0.0
+                for ii in range(n_features):
+                    # np.sqrt(np.sum(XtA ** 2, axis=1))
+                    XtA_axis1norm = _nrm2(n_tasks, &XtA[ii, 0], 1)
+                    if XtA_axis1norm > dual_norm_XtA:
+                        dual_norm_XtA = XtA_axis1norm
+
+                # TODO: use squared L2 norm directly
+                # R_norm = linalg.norm(R, ord='fro')
+                # w_norm = linalg.norm(W, ord='fro')
+                R_norm = _nrm2(n_samples * n_tasks, &R[0, 0], 1)
+                w_norm = _nrm2(n_features * n_tasks, &W[0, 0], 1)
+                if (dual_norm_XtA > l1_reg):
+                    const_ = l1_reg / dual_norm_XtA
+                    A_norm = R_norm * const_
+                    gap = 0.5 * (R_norm ** 2 + A_norm ** 2)
+                else:
+                    const_ = 1.0
+                    gap = R_norm ** 2
+
+                # ry_sum = np.sum(R * y)
+                ry_sum = _dot(n_samples * n_tasks, &R[0, 0], 1, &Y[0, 0], 1)
+
+                # l21_norm = np.sqrt(np.sum(W ** 2, axis=0)).sum()
+                l21_norm = 0.0
+                for ii in range(n_features):
+                    l21_norm += _nrm2(n_tasks, &W[0, ii], 1)
+
+                gap += (
+                    l1_reg * l21_norm
+                    - const_ * ry_sum
+                    + 0.5 * l2_reg * (1 + const_ ** 2) * (w_norm ** 2)
+                )
+
+                if gap <= tol:
+                    # return if we reached desired tolerance
+                    break
+        else:
+            # for/else, runs if for doesn't end with a `break`
+            with gil:
+                message = (
+                    message_conv +
+                    f" Duality gap: {gap:.3e}, tolerance: {tol:.3e}"
+                )
+                warnings.warn(message, ConvergenceWarning)
+
+    return np.asarray(W), gap, tol, n_iter + 1
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/linear_model/_coordinate_descent.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/linear_model/_coordinate_descent.py
new file mode 100644
index 0000000000000000000000000000000000000000..940ae6f5e3a3010f7fe2f21d28d68f538d893d8c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/linear_model/_coordinate_descent.py
@@ -0,0 +1,3403 @@
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+import numbers
+import sys
+import warnings
+from abc import ABC, abstractmethod
+from functools import partial
+from numbers import Integral, Real
+
+import numpy as np
+from joblib import effective_n_jobs
+from scipy import sparse
+
+from sklearn.utils import metadata_routing
+
+from ..base import MultiOutputMixin, RegressorMixin, _fit_context
+from ..model_selection import check_cv
+from ..utils import Bunch, check_array, check_scalar
+from ..utils._metadata_requests import (
+    MetadataRouter,
+    MethodMapping,
+    _raise_for_params,
+    get_routing_for_object,
+)
+from ..utils._param_validation import Hidden, Interval, StrOptions, validate_params
+from ..utils.extmath import safe_sparse_dot
+from ..utils.metadata_routing import (
+    _routing_enabled,
+    process_routing,
+)
+from ..utils.parallel import Parallel, delayed
+from ..utils.validation import (
+    _check_sample_weight,
+    check_consistent_length,
+    check_is_fitted,
+    check_random_state,
+    column_or_1d,
+    has_fit_parameter,
+    validate_data,
+)
+
+# mypy error: Module 'sklearn.linear_model' has no attribute '_cd_fast'
+from . import _cd_fast as cd_fast  # type: ignore[attr-defined]
+from ._base import LinearModel, _pre_fit, _preprocess_data
+
+
+def _set_order(X, y, order="C"):
+    """Change the order of X and y if necessary.
+
+    Parameters
+    ----------
+    X : {array-like, sparse matrix} of shape (n_samples, n_features)
+        Training data.
+
+    y : ndarray of shape (n_samples,)
+        Target values.
+
+    order : {None, 'C', 'F'}
+        If 'C', dense arrays are returned as C-ordered, sparse matrices in csr
+        format. If 'F', dense arrays are return as F-ordered, sparse matrices
+        in csc format.
+
+    Returns
+    -------
+    X : {array-like, sparse matrix} of shape (n_samples, n_features)
+        Training data with guaranteed order.
+
+    y : ndarray of shape (n_samples,)
+        Target values with guaranteed order.
+    """
+    if order not in [None, "C", "F"]:
+        raise ValueError(
+            "Unknown value for order. Got {} instead of None, 'C' or 'F'.".format(order)
+        )
+    sparse_X = sparse.issparse(X)
+    sparse_y = sparse.issparse(y)
+    if order is not None:
+        sparse_format = "csc" if order == "F" else "csr"
+        if sparse_X:
+            X = X.asformat(sparse_format, copy=False)
+        else:
+            X = np.asarray(X, order=order)
+        if sparse_y:
+            y = y.asformat(sparse_format)
+        else:
+            y = np.asarray(y, order=order)
+    return X, y
+
+
+###############################################################################
+# Paths functions
+
+
+def _alpha_grid(
+    X,
+    y,
+    Xy=None,
+    l1_ratio=1.0,
+    fit_intercept=True,
+    eps=1e-3,
+    n_alphas=100,
+    copy_X=True,
+    sample_weight=None,
+):
+    """Compute the grid of alpha values for elastic net parameter search
+
+    Parameters
+    ----------
+    X : {array-like, sparse matrix} of shape (n_samples, n_features)
+        Training data. Pass directly as Fortran-contiguous data to avoid
+        unnecessary memory duplication
+
+    y : ndarray of shape (n_samples,) or (n_samples, n_outputs)
+        Target values
+
+    Xy : array-like of shape (n_features,) or (n_features, n_outputs),\
+         default=None
+        Xy = np.dot(X.T, y) that can be precomputed.
+
+    l1_ratio : float, default=1.0
+        The elastic net mixing parameter, with ``0 < l1_ratio <= 1``.
+        For ``l1_ratio = 0`` the penalty is an L2 penalty. (currently not
+        supported) ``For l1_ratio = 1`` it is an L1 penalty. For
+        ``0 < l1_ratio <1``, the penalty is a combination of L1 and L2.
+
+    eps : float, default=1e-3
+        Length of the path. ``eps=1e-3`` means that
+        ``alpha_min / alpha_max = 1e-3``
+
+    n_alphas : int, default=100
+        Number of alphas along the regularization path
+
+    fit_intercept : bool, default=True
+        Whether to fit an intercept or not
+
+    copy_X : bool, default=True
+        If ``True``, X will be copied; else, it may be overwritten.
+
+    sample_weight : ndarray of shape (n_samples,), default=None
+    """
+    if l1_ratio == 0:
+        raise ValueError(
+            "Automatic alpha grid generation is not supported for"
+            " l1_ratio=0. Please supply a grid by providing "
+            "your estimator with the appropriate `alphas=` "
+            "argument."
+        )
+    if Xy is not None:
+        Xyw = Xy
+    else:
+        X, y, X_offset, _, _ = _preprocess_data(
+            X,
+            y,
+            fit_intercept=fit_intercept,
+            copy=copy_X,
+            sample_weight=sample_weight,
+            check_input=False,
+        )
+        if sample_weight is not None:
+            if y.ndim > 1:
+                yw = y * sample_weight.reshape(-1, 1)
+            else:
+                yw = y * sample_weight
+        else:
+            yw = y
+        if sparse.issparse(X):
+            Xyw = safe_sparse_dot(X.T, yw, dense_output=True) - np.sum(yw) * X_offset
+        else:
+            Xyw = np.dot(X.T, yw)
+
+    if Xyw.ndim == 1:
+        Xyw = Xyw[:, np.newaxis]
+    if sample_weight is not None:
+        n_samples = sample_weight.sum()
+    else:
+        n_samples = X.shape[0]
+    alpha_max = np.sqrt(np.sum(Xyw**2, axis=1)).max() / (n_samples * l1_ratio)
+
+    if alpha_max <= np.finfo(np.float64).resolution:
+        return np.full(n_alphas, np.finfo(np.float64).resolution)
+
+    return np.geomspace(alpha_max, alpha_max * eps, num=n_alphas)
+
+
+@validate_params(
+    {
+        "X": ["array-like", "sparse matrix"],
+        "y": ["array-like", "sparse matrix"],
+        "eps": [Interval(Real, 0, None, closed="neither")],
+        "n_alphas": [Interval(Integral, 1, None, closed="left")],
+        "alphas": ["array-like", None],
+        "precompute": [StrOptions({"auto"}), "boolean", "array-like"],
+        "Xy": ["array-like", None],
+        "copy_X": ["boolean"],
+        "coef_init": ["array-like", None],
+        "verbose": ["verbose"],
+        "return_n_iter": ["boolean"],
+        "positive": ["boolean"],
+    },
+    prefer_skip_nested_validation=True,
+)
+def lasso_path(
+    X,
+    y,
+    *,
+    eps=1e-3,
+    n_alphas=100,
+    alphas=None,
+    precompute="auto",
+    Xy=None,
+    copy_X=True,
+    coef_init=None,
+    verbose=False,
+    return_n_iter=False,
+    positive=False,
+    **params,
+):
+    """Compute Lasso path with coordinate descent.
+
+    The Lasso optimization function varies for mono and multi-outputs.
+
+    For mono-output tasks it is::
+
+        (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1
+
+    For multi-output tasks it is::
+
+        (1 / (2 * n_samples)) * ||Y - XW||^2_Fro + alpha * ||W||_21
+
+    Where::
+
+        ||W||_21 = \\sum_i \\sqrt{\\sum_j w_{ij}^2}
+
+    i.e. the sum of norm of each row.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    X : {array-like, sparse matrix} of shape (n_samples, n_features)
+        Training data. Pass directly as Fortran-contiguous data to avoid
+        unnecessary memory duplication. If ``y`` is mono-output then ``X``
+        can be sparse.
+
+    y : {array-like, sparse matrix} of shape (n_samples,) or \
+        (n_samples, n_targets)
+        Target values.
+
+    eps : float, default=1e-3
+        Length of the path. ``eps=1e-3`` means that
+        ``alpha_min / alpha_max = 1e-3``.
+
+    n_alphas : int, default=100
+        Number of alphas along the regularization path.
+
+    alphas : array-like, default=None
+        List of alphas where to compute the models.
+        If ``None`` alphas are set automatically.
+
+    precompute : 'auto', bool or array-like of shape \
+            (n_features, n_features), default='auto'
+        Whether to use a precomputed Gram matrix to speed up
+        calculations. If set to ``'auto'`` let us decide. The Gram
+        matrix can also be passed as argument.
+
+    Xy : array-like of shape (n_features,) or (n_features, n_targets),\
+         default=None
+        Xy = np.dot(X.T, y) that can be precomputed. It is useful
+        only when the Gram matrix is precomputed.
+
+    copy_X : bool, default=True
+        If ``True``, X will be copied; else, it may be overwritten.
+
+    coef_init : array-like of shape (n_features, ), default=None
+        The initial values of the coefficients.
+
+    verbose : bool or int, default=False
+        Amount of verbosity.
+
+    return_n_iter : bool, default=False
+        Whether to return the number of iterations or not.
+
+    positive : bool, default=False
+        If set to True, forces coefficients to be positive.
+        (Only allowed when ``y.ndim == 1``).
+
+    **params : kwargs
+        Keyword arguments passed to the coordinate descent solver.
+
+    Returns
+    -------
+    alphas : ndarray of shape (n_alphas,)
+        The alphas along the path where models are computed.
+
+    coefs : ndarray of shape (n_features, n_alphas) or \
+            (n_targets, n_features, n_alphas)
+        Coefficients along the path.
+
+    dual_gaps : ndarray of shape (n_alphas,)
+        The dual gaps at the end of the optimization for each alpha.
+
+    n_iters : list of int
+        The number of iterations taken by the coordinate descent optimizer to
+        reach the specified tolerance for each alpha.
+
+    See Also
+    --------
+    lars_path : Compute Least Angle Regression or Lasso path using LARS
+        algorithm.
+    Lasso : The Lasso is a linear model that estimates sparse coefficients.
+    LassoLars : Lasso model fit with Least Angle Regression a.k.a. Lars.
+    LassoCV : Lasso linear model with iterative fitting along a regularization
+        path.
+    LassoLarsCV : Cross-validated Lasso using the LARS algorithm.
+    sklearn.decomposition.sparse_encode : Estimator that can be used to
+        transform signals into sparse linear combination of atoms from a fixed.
+
+    Notes
+    -----
+    For an example, see
+    :ref:`examples/linear_model/plot_lasso_lasso_lars_elasticnet_path.py
+    `.
+
+    To avoid unnecessary memory duplication the X argument of the fit method
+    should be directly passed as a Fortran-contiguous numpy array.
+
+    Note that in certain cases, the Lars solver may be significantly
+    faster to implement this functionality. In particular, linear
+    interpolation can be used to retrieve model coefficients between the
+    values output by lars_path
+
+    Examples
+    --------
+
+    Comparing lasso_path and lars_path with interpolation:
+
+    >>> import numpy as np
+    >>> from sklearn.linear_model import lasso_path
+    >>> X = np.array([[1, 2, 3.1], [2.3, 5.4, 4.3]]).T
+    >>> y = np.array([1, 2, 3.1])
+    >>> # Use lasso_path to compute a coefficient path
+    >>> _, coef_path, _ = lasso_path(X, y, alphas=[5., 1., .5])
+    >>> print(coef_path)
+    [[0.         0.         0.46874778]
+     [0.2159048  0.4425765  0.23689075]]
+
+    >>> # Now use lars_path and 1D linear interpolation to compute the
+    >>> # same path
+    >>> from sklearn.linear_model import lars_path
+    >>> alphas, active, coef_path_lars = lars_path(X, y, method='lasso')
+    >>> from scipy import interpolate
+    >>> coef_path_continuous = interpolate.interp1d(alphas[::-1],
+    ...                                             coef_path_lars[:, ::-1])
+    >>> print(coef_path_continuous([5., 1., .5]))
+    [[0.         0.         0.46915237]
+     [0.2159048  0.4425765  0.23668876]]
+    """
+    return enet_path(
+        X,
+        y,
+        l1_ratio=1.0,
+        eps=eps,
+        n_alphas=n_alphas,
+        alphas=alphas,
+        precompute=precompute,
+        Xy=Xy,
+        copy_X=copy_X,
+        coef_init=coef_init,
+        verbose=verbose,
+        positive=positive,
+        return_n_iter=return_n_iter,
+        **params,
+    )
+
+
+@validate_params(
+    {
+        "X": ["array-like", "sparse matrix"],
+        "y": ["array-like", "sparse matrix"],
+        "l1_ratio": [Interval(Real, 0.0, 1.0, closed="both")],
+        "eps": [Interval(Real, 0.0, None, closed="neither")],
+        "n_alphas": [Interval(Integral, 1, None, closed="left")],
+        "alphas": ["array-like", None],
+        "precompute": [StrOptions({"auto"}), "boolean", "array-like"],
+        "Xy": ["array-like", None],
+        "copy_X": ["boolean"],
+        "coef_init": ["array-like", None],
+        "verbose": ["verbose"],
+        "return_n_iter": ["boolean"],
+        "positive": ["boolean"],
+        "check_input": ["boolean"],
+    },
+    prefer_skip_nested_validation=True,
+)
+def enet_path(
+    X,
+    y,
+    *,
+    l1_ratio=0.5,
+    eps=1e-3,
+    n_alphas=100,
+    alphas=None,
+    precompute="auto",
+    Xy=None,
+    copy_X=True,
+    coef_init=None,
+    verbose=False,
+    return_n_iter=False,
+    positive=False,
+    check_input=True,
+    **params,
+):
+    """Compute elastic net path with coordinate descent.
+
+    The elastic net optimization function varies for mono and multi-outputs.
+
+    For mono-output tasks it is::
+
+        1 / (2 * n_samples) * ||y - Xw||^2_2
+        + alpha * l1_ratio * ||w||_1
+        + 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2
+
+    For multi-output tasks it is::
+
+        (1 / (2 * n_samples)) * ||Y - XW||_Fro^2
+        + alpha * l1_ratio * ||W||_21
+        + 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
+
+    Where::
+
+        ||W||_21 = \\sum_i \\sqrt{\\sum_j w_{ij}^2}
+
+    i.e. the sum of norm of each row.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    X : {array-like, sparse matrix} of shape (n_samples, n_features)
+        Training data. Pass directly as Fortran-contiguous data to avoid
+        unnecessary memory duplication. If ``y`` is mono-output then ``X``
+        can be sparse.
+
+    y : {array-like, sparse matrix} of shape (n_samples,) or \
+        (n_samples, n_targets)
+        Target values.
+
+    l1_ratio : float, default=0.5
+        Number between 0 and 1 passed to elastic net (scaling between
+        l1 and l2 penalties). ``l1_ratio=1`` corresponds to the Lasso.
+
+    eps : float, default=1e-3
+        Length of the path. ``eps=1e-3`` means that
+        ``alpha_min / alpha_max = 1e-3``.
+
+    n_alphas : int, default=100
+        Number of alphas along the regularization path.
+
+    alphas : array-like, default=None
+        List of alphas where to compute the models.
+        If None alphas are set automatically.
+
+    precompute : 'auto', bool or array-like of shape \
+            (n_features, n_features), default='auto'
+        Whether to use a precomputed Gram matrix to speed up
+        calculations. If set to ``'auto'`` let us decide. The Gram
+        matrix can also be passed as argument.
+
+    Xy : array-like of shape (n_features,) or (n_features, n_targets),\
+         default=None
+        Xy = np.dot(X.T, y) that can be precomputed. It is useful
+        only when the Gram matrix is precomputed.
+
+    copy_X : bool, default=True
+        If ``True``, X will be copied; else, it may be overwritten.
+
+    coef_init : array-like of shape (n_features, ), default=None
+        The initial values of the coefficients.
+
+    verbose : bool or int, default=False
+        Amount of verbosity.
+
+    return_n_iter : bool, default=False
+        Whether to return the number of iterations or not.
+
+    positive : bool, default=False
+        If set to True, forces coefficients to be positive.
+        (Only allowed when ``y.ndim == 1``).
+
+    check_input : bool, default=True
+        If set to False, the input validation checks are skipped (including the
+        Gram matrix when provided). It is assumed that they are handled
+        by the caller.
+
+    **params : kwargs
+        Keyword arguments passed to the coordinate descent solver.
+
+    Returns
+    -------
+    alphas : ndarray of shape (n_alphas,)
+        The alphas along the path where models are computed.
+
+    coefs : ndarray of shape (n_features, n_alphas) or \
+            (n_targets, n_features, n_alphas)
+        Coefficients along the path.
+
+    dual_gaps : ndarray of shape (n_alphas,)
+        The dual gaps at the end of the optimization for each alpha.
+
+    n_iters : list of int
+        The number of iterations taken by the coordinate descent optimizer to
+        reach the specified tolerance for each alpha.
+        (Is returned when ``return_n_iter`` is set to True).
+
+    See Also
+    --------
+    MultiTaskElasticNet : Multi-task ElasticNet model trained with L1/L2 mixed-norm \
+    as regularizer.
+    MultiTaskElasticNetCV : Multi-task L1/L2 ElasticNet with built-in cross-validation.
+    ElasticNet : Linear regression with combined L1 and L2 priors as regularizer.
+    ElasticNetCV : Elastic Net model with iterative fitting along a regularization path.
+
+    Notes
+    -----
+    For an example, see
+    :ref:`examples/linear_model/plot_lasso_lasso_lars_elasticnet_path.py
+    `.
+
+    Examples
+    --------
+    >>> from sklearn.linear_model import enet_path
+    >>> from sklearn.datasets import make_regression
+    >>> X, y, true_coef = make_regression(
+    ...    n_samples=100, n_features=5, n_informative=2, coef=True, random_state=0
+    ... )
+    >>> true_coef
+    array([ 0.        ,  0.        ,  0.        , 97.9, 45.7])
+    >>> alphas, estimated_coef, _ = enet_path(X, y, n_alphas=3)
+    >>> alphas.shape
+    (3,)
+    >>> estimated_coef
+     array([[ 0.,  0.787,  0.568],
+            [ 0.,  1.120,  0.620],
+            [-0., -2.129, -1.128],
+            [ 0., 23.046, 88.939],
+            [ 0., 10.637, 41.566]])
+    """
+    X_offset_param = params.pop("X_offset", None)
+    X_scale_param = params.pop("X_scale", None)
+    sample_weight = params.pop("sample_weight", None)
+    tol = params.pop("tol", 1e-4)
+    max_iter = params.pop("max_iter", 1000)
+    random_state = params.pop("random_state", None)
+    selection = params.pop("selection", "cyclic")
+
+    if len(params) > 0:
+        raise ValueError("Unexpected parameters in params", params.keys())
+
+    # We expect X and y to be already Fortran ordered when bypassing
+    # checks
+    if check_input:
+        X = check_array(
+            X,
+            accept_sparse="csc",
+            dtype=[np.float64, np.float32],
+            order="F",
+            copy=copy_X,
+        )
+        y = check_array(
+            y,
+            accept_sparse="csc",
+            dtype=X.dtype.type,
+            order="F",
+            copy=False,
+            ensure_2d=False,
+        )
+        if Xy is not None:
+            # Xy should be a 1d contiguous array or a 2D C ordered array
+            Xy = check_array(
+                Xy, dtype=X.dtype.type, order="C", copy=False, ensure_2d=False
+            )
+
+    n_samples, n_features = X.shape
+
+    multi_output = False
+    if y.ndim != 1:
+        multi_output = True
+        n_targets = y.shape[1]
+
+    if multi_output and positive:
+        raise ValueError("positive=True is not allowed for multi-output (y.ndim != 1)")
+
+    # MultiTaskElasticNet does not support sparse matrices
+    if not multi_output and sparse.issparse(X):
+        if X_offset_param is not None:
+            # As sparse matrices are not actually centered we need this to be passed to
+            # the CD solver.
+            X_sparse_scaling = X_offset_param / X_scale_param
+            X_sparse_scaling = np.asarray(X_sparse_scaling, dtype=X.dtype)
+        else:
+            X_sparse_scaling = np.zeros(n_features, dtype=X.dtype)
+
+    # X should have been passed through _pre_fit already if function is called
+    # from ElasticNet.fit
+    if check_input:
+        X, y, _, _, _, precompute, Xy = _pre_fit(
+            X,
+            y,
+            Xy,
+            precompute,
+            fit_intercept=False,
+            copy=False,
+            check_input=check_input,
+        )
+    if alphas is None:
+        # No need to normalize of fit_intercept: it has been done
+        # above
+        alphas = _alpha_grid(
+            X,
+            y,
+            Xy=Xy,
+            l1_ratio=l1_ratio,
+            fit_intercept=False,
+            eps=eps,
+            n_alphas=n_alphas,
+            copy_X=False,
+        )
+    elif len(alphas) > 1:
+        alphas = np.sort(alphas)[::-1]  # make sure alphas are properly ordered
+
+    n_alphas = len(alphas)
+    dual_gaps = np.empty(n_alphas)
+    n_iters = []
+
+    rng = check_random_state(random_state)
+    if selection not in ["random", "cyclic"]:
+        raise ValueError("selection should be either random or cyclic.")
+    random = selection == "random"
+
+    if not multi_output:
+        coefs = np.empty((n_features, n_alphas), dtype=X.dtype)
+    else:
+        coefs = np.empty((n_targets, n_features, n_alphas), dtype=X.dtype)
+
+    if coef_init is None:
+        coef_ = np.zeros(coefs.shape[:-1], dtype=X.dtype, order="F")
+    else:
+        coef_ = np.asfortranarray(coef_init, dtype=X.dtype)
+
+    for i, alpha in enumerate(alphas):
+        # account for n_samples scaling in objectives between here and cd_fast
+        l1_reg = alpha * l1_ratio * n_samples
+        l2_reg = alpha * (1.0 - l1_ratio) * n_samples
+        if not multi_output and sparse.issparse(X):
+            model = cd_fast.sparse_enet_coordinate_descent(
+                w=coef_,
+                alpha=l1_reg,
+                beta=l2_reg,
+                X_data=X.data,
+                X_indices=X.indices,
+                X_indptr=X.indptr,
+                y=y,
+                sample_weight=sample_weight,
+                X_mean=X_sparse_scaling,
+                max_iter=max_iter,
+                tol=tol,
+                rng=rng,
+                random=random,
+                positive=positive,
+            )
+        elif multi_output:
+            model = cd_fast.enet_coordinate_descent_multi_task(
+                coef_, l1_reg, l2_reg, X, y, max_iter, tol, rng, random
+            )
+        elif isinstance(precompute, np.ndarray):
+            # We expect precompute to be already Fortran ordered when bypassing
+            # checks
+            if check_input:
+                precompute = check_array(precompute, dtype=X.dtype.type, order="C")
+            model = cd_fast.enet_coordinate_descent_gram(
+                coef_,
+                l1_reg,
+                l2_reg,
+                precompute,
+                Xy,
+                y,
+                max_iter,
+                tol,
+                rng,
+                random,
+                positive,
+            )
+        elif precompute is False:
+            model = cd_fast.enet_coordinate_descent(
+                coef_, l1_reg, l2_reg, X, y, max_iter, tol, rng, random, positive
+            )
+        else:
+            raise ValueError(
+                "Precompute should be one of True, False, 'auto' or array-like. Got %r"
+                % precompute
+            )
+        coef_, dual_gap_, eps_, n_iter_ = model
+        coefs[..., i] = coef_
+        # we correct the scale of the returned dual gap, as the objective
+        # in cd_fast is n_samples * the objective in this docstring.
+        dual_gaps[i] = dual_gap_ / n_samples
+        n_iters.append(n_iter_)
+
+        if verbose:
+            if verbose > 2:
+                print(model)
+            elif verbose > 1:
+                print("Path: %03i out of %03i" % (i, n_alphas))
+            else:
+                sys.stderr.write(".")
+
+    if return_n_iter:
+        return alphas, coefs, dual_gaps, n_iters
+    return alphas, coefs, dual_gaps
+
+
+###############################################################################
+# ElasticNet model
+
+
+class ElasticNet(MultiOutputMixin, RegressorMixin, LinearModel):
+    """Linear regression with combined L1 and L2 priors as regularizer.
+
+    Minimizes the objective function::
+
+            1 / (2 * n_samples) * ||y - Xw||^2_2
+            + alpha * l1_ratio * ||w||_1
+            + 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2
+
+    If you are interested in controlling the L1 and L2 penalty
+    separately, keep in mind that this is equivalent to::
+
+            a * ||w||_1 + 0.5 * b * ||w||_2^2
+
+    where::
+
+            alpha = a + b and l1_ratio = a / (a + b)
+
+    The parameter l1_ratio corresponds to alpha in the glmnet R package while
+    alpha corresponds to the lambda parameter in glmnet. Specifically, l1_ratio
+    = 1 is the lasso penalty. Currently, l1_ratio <= 0.01 is not reliable,
+    unless you supply your own sequence of alpha.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    alpha : float, default=1.0
+        Constant that multiplies the penalty terms. Defaults to 1.0.
+        See the notes for the exact mathematical meaning of this
+        parameter. ``alpha = 0`` is equivalent to an ordinary least square,
+        solved by the :class:`LinearRegression` object. For numerical
+        reasons, using ``alpha = 0`` with the ``Lasso`` object is not advised.
+        Given this, you should use the :class:`LinearRegression` object.
+
+    l1_ratio : float, default=0.5
+        The ElasticNet mixing parameter, with ``0 <= l1_ratio <= 1``. For
+        ``l1_ratio = 0`` the penalty is an L2 penalty. ``For l1_ratio = 1`` it
+        is an L1 penalty.  For ``0 < l1_ratio < 1``, the penalty is a
+        combination of L1 and L2.
+
+    fit_intercept : bool, default=True
+        Whether the intercept should be estimated or not. If ``False``, the
+        data is assumed to be already centered.
+
+    precompute : bool or array-like of shape (n_features, n_features),\
+                 default=False
+        Whether to use a precomputed Gram matrix to speed up
+        calculations. The Gram matrix can also be passed as argument.
+        For sparse input this option is always ``False`` to preserve sparsity.
+        Check :ref:`an example on how to use a precomputed Gram Matrix in ElasticNet
+        `
+        for details.
+
+    max_iter : int, default=1000
+        The maximum number of iterations.
+
+    copy_X : bool, default=True
+        If ``True``, X will be copied; else, it may be overwritten.
+
+    tol : float, default=1e-4
+        The tolerance for the optimization: if the updates are
+        smaller than ``tol``, the optimization code checks the
+        dual gap for optimality and continues until it is smaller
+        than ``tol``, see Notes below.
+
+    warm_start : bool, default=False
+        When set to ``True``, reuse the solution of the previous call to fit as
+        initialization, otherwise, just erase the previous solution.
+        See :term:`the Glossary `.
+
+    positive : bool, default=False
+        When set to ``True``, forces the coefficients to be positive.
+
+    random_state : int, RandomState instance, default=None
+        The seed of the pseudo random number generator that selects a random
+        feature to update. Used when ``selection`` == 'random'.
+        Pass an int for reproducible output across multiple function calls.
+        See :term:`Glossary `.
+
+    selection : {'cyclic', 'random'}, default='cyclic'
+        If set to 'random', a random coefficient is updated every iteration
+        rather than looping over features sequentially by default. This
+        (setting to 'random') often leads to significantly faster convergence
+        especially when tol is higher than 1e-4.
+
+    Attributes
+    ----------
+    coef_ : ndarray of shape (n_features,) or (n_targets, n_features)
+        Parameter vector (w in the cost function formula).
+
+    sparse_coef_ : sparse matrix of shape (n_features,) or \
+            (n_targets, n_features)
+        Sparse representation of the `coef_`.
+
+    intercept_ : float or ndarray of shape (n_targets,)
+        Independent term in decision function.
+
+    n_iter_ : list of int
+        Number of iterations run by the coordinate descent solver to reach
+        the specified tolerance.
+
+    dual_gap_ : float or ndarray of shape (n_targets,)
+        Given param alpha, the dual gaps at the end of the optimization,
+        same shape as each observation of y.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    ElasticNetCV : Elastic net model with best model selection by
+        cross-validation.
+    SGDRegressor : Implements elastic net regression with incremental training.
+    SGDClassifier : Implements logistic regression with elastic net penalty
+        (``SGDClassifier(loss="log_loss", penalty="elasticnet")``).
+
+    Notes
+    -----
+    To avoid unnecessary memory duplication the X argument of the fit method
+    should be directly passed as a Fortran-contiguous numpy array.
+
+    The precise stopping criteria based on `tol` are the following: First, check that
+    that maximum coordinate update, i.e. :math:`\\max_j |w_j^{new} - w_j^{old}|`
+    is smaller than `tol` times the maximum absolute coefficient, :math:`\\max_j |w_j|`.
+    If so, then additionally check whether the dual gap is smaller than `tol` times
+    :math:`||y||_2^2 / n_{\text{samples}}`.
+
+    Examples
+    --------
+    >>> from sklearn.linear_model import ElasticNet
+    >>> from sklearn.datasets import make_regression
+
+    >>> X, y = make_regression(n_features=2, random_state=0)
+    >>> regr = ElasticNet(random_state=0)
+    >>> regr.fit(X, y)
+    ElasticNet(random_state=0)
+    >>> print(regr.coef_)
+    [18.83816048 64.55968825]
+    >>> print(regr.intercept_)
+    1.451
+    >>> print(regr.predict([[0, 0]]))
+    [1.451]
+
+    -   :ref:`sphx_glr_auto_examples_linear_model_plot_lasso_and_elasticnet.py`
+        showcases ElasticNet alongside Lasso and ARD Regression for sparse
+        signal recovery in the presence of noise and feature correlation.
+    """
+
+    # "check_input" is used for optimisation and isn't something to be passed
+    # around in a pipeline.
+    __metadata_request__fit = {"check_input": metadata_routing.UNUSED}
+
+    _parameter_constraints: dict = {
+        "alpha": [Interval(Real, 0, None, closed="left")],
+        "l1_ratio": [Interval(Real, 0, 1, closed="both")],
+        "fit_intercept": ["boolean"],
+        "precompute": ["boolean", "array-like"],
+        "max_iter": [Interval(Integral, 1, None, closed="left"), None],
+        "copy_X": ["boolean"],
+        "tol": [Interval(Real, 0, None, closed="left")],
+        "warm_start": ["boolean"],
+        "positive": ["boolean"],
+        "random_state": ["random_state"],
+        "selection": [StrOptions({"cyclic", "random"})],
+    }
+
+    path = staticmethod(enet_path)
+
+    def __init__(
+        self,
+        alpha=1.0,
+        *,
+        l1_ratio=0.5,
+        fit_intercept=True,
+        precompute=False,
+        max_iter=1000,
+        copy_X=True,
+        tol=1e-4,
+        warm_start=False,
+        positive=False,
+        random_state=None,
+        selection="cyclic",
+    ):
+        self.alpha = alpha
+        self.l1_ratio = l1_ratio
+        self.fit_intercept = fit_intercept
+        self.precompute = precompute
+        self.max_iter = max_iter
+        self.copy_X = copy_X
+        self.tol = tol
+        self.warm_start = warm_start
+        self.positive = positive
+        self.random_state = random_state
+        self.selection = selection
+
+    @_fit_context(prefer_skip_nested_validation=True)
+    def fit(self, X, y, sample_weight=None, check_input=True):
+        """Fit model with coordinate descent.
+
+        Parameters
+        ----------
+        X : {ndarray, sparse matrix, sparse array} of (n_samples, n_features)
+            Data.
+
+            Note that large sparse matrices and arrays requiring `int64`
+            indices are not accepted.
+
+        y : ndarray of shape (n_samples,) or (n_samples, n_targets)
+            Target. Will be cast to X's dtype if necessary.
+
+        sample_weight : float or array-like of shape (n_samples,), default=None
+            Sample weights. Internally, the `sample_weight` vector will be
+            rescaled to sum to `n_samples`.
+
+            .. versionadded:: 0.23
+
+        check_input : bool, default=True
+            Allow to bypass several input checking.
+            Don't use this parameter unless you know what you do.
+
+        Returns
+        -------
+        self : object
+            Fitted estimator.
+
+        Notes
+        -----
+        Coordinate descent is an algorithm that considers each column of
+        data at a time hence it will automatically convert the X input
+        as a Fortran-contiguous numpy array if necessary.
+
+        To avoid memory re-allocation it is advised to allocate the
+        initial data in memory directly using that format.
+        """
+        if self.alpha == 0:
+            warnings.warn(
+                (
+                    "With alpha=0, this algorithm does not converge "
+                    "well. You are advised to use the LinearRegression "
+                    "estimator"
+                ),
+                stacklevel=2,
+            )
+
+        # Remember if X is copied
+        X_copied = False
+        # We expect X and y to be float64 or float32 Fortran ordered arrays
+        # when bypassing checks
+        if check_input:
+            X_copied = self.copy_X and self.fit_intercept
+            X, y = validate_data(
+                self,
+                X,
+                y,
+                accept_sparse="csc",
+                order="F",
+                dtype=[np.float64, np.float32],
+                force_writeable=True,
+                accept_large_sparse=False,
+                copy=X_copied,
+                multi_output=True,
+                y_numeric=True,
+            )
+            y = check_array(
+                y, order="F", copy=False, dtype=X.dtype.type, ensure_2d=False
+            )
+
+        n_samples, n_features = X.shape
+        alpha = self.alpha
+
+        if isinstance(sample_weight, numbers.Number):
+            sample_weight = None
+        if sample_weight is not None:
+            if check_input:
+                sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype)
+            # TLDR: Rescale sw to sum up to n_samples.
+            # Long: The objective function of Enet
+            #
+            #    1/2 * np.average(squared error, weights=sw)
+            #    + alpha * penalty                                             (1)
+            #
+            # is invariant under rescaling of sw.
+            # But enet_path coordinate descent minimizes
+            #
+            #     1/2 * sum(squared error) + alpha' * penalty                  (2)
+            #
+            # and therefore sets
+            #
+            #     alpha' = n_samples * alpha                                   (3)
+            #
+            # inside its function body, which results in objective (2) being
+            # equivalent to (1) in case of no sw.
+            # With sw, however, enet_path should set
+            #
+            #     alpha' = sum(sw) * alpha                                     (4)
+            #
+            # Therefore, we use the freedom of Eq. (1) to rescale sw before
+            # calling enet_path, i.e.
+            #
+            #     sw *= n_samples / sum(sw)
+            #
+            # such that sum(sw) = n_samples. This way, (3) and (4) are the same.
+            sample_weight = sample_weight * (n_samples / np.sum(sample_weight))
+            # Note: Alternatively, we could also have rescaled alpha instead
+            # of sample_weight:
+            #
+            #     alpha *= np.sum(sample_weight) / n_samples
+
+        # Ensure copying happens only once, don't do it again if done above.
+        # X and y will be rescaled if sample_weight is not None, order='F'
+        # ensures that the returned X and y are still F-contiguous.
+        should_copy = self.copy_X and not X_copied
+        X, y, X_offset, y_offset, X_scale, precompute, Xy = _pre_fit(
+            X,
+            y,
+            None,
+            self.precompute,
+            fit_intercept=self.fit_intercept,
+            copy=should_copy,
+            check_input=check_input,
+            sample_weight=sample_weight,
+        )
+        # coordinate descent needs F-ordered arrays and _pre_fit might have
+        # called _rescale_data
+        if check_input or sample_weight is not None:
+            X, y = _set_order(X, y, order="F")
+        if y.ndim == 1:
+            y = y[:, np.newaxis]
+        if Xy is not None and Xy.ndim == 1:
+            Xy = Xy[:, np.newaxis]
+
+        n_targets = y.shape[1]
+
+        if not self.warm_start or not hasattr(self, "coef_"):
+            coef_ = np.zeros((n_targets, n_features), dtype=X.dtype, order="F")
+        else:
+            coef_ = self.coef_
+            if coef_.ndim == 1:
+                coef_ = coef_[np.newaxis, :]
+
+        dual_gaps_ = np.zeros(n_targets, dtype=X.dtype)
+        self.n_iter_ = []
+
+        for k in range(n_targets):
+            if Xy is not None:
+                this_Xy = Xy[:, k]
+            else:
+                this_Xy = None
+            _, this_coef, this_dual_gap, this_iter = self.path(
+                X,
+                y[:, k],
+                l1_ratio=self.l1_ratio,
+                eps=None,
+                n_alphas=None,
+                alphas=[alpha],
+                precompute=precompute,
+                Xy=this_Xy,
+                copy_X=True,
+                coef_init=coef_[k],
+                verbose=False,
+                return_n_iter=True,
+                positive=self.positive,
+                check_input=False,
+                # from here on **params
+                tol=self.tol,
+                X_offset=X_offset,
+                X_scale=X_scale,
+                max_iter=self.max_iter,
+                random_state=self.random_state,
+                selection=self.selection,
+                sample_weight=sample_weight,
+            )
+            coef_[k] = this_coef[:, 0]
+            dual_gaps_[k] = this_dual_gap[0]
+            self.n_iter_.append(this_iter[0])
+
+        if n_targets == 1:
+            self.n_iter_ = self.n_iter_[0]
+            self.coef_ = coef_[0]
+            self.dual_gap_ = dual_gaps_[0]
+        else:
+            self.coef_ = coef_
+            self.dual_gap_ = dual_gaps_
+
+        self._set_intercept(X_offset, y_offset, X_scale)
+
+        # check for finiteness of coefficients
+        if not all(np.isfinite(w).all() for w in [self.coef_, self.intercept_]):
+            raise ValueError(
+                "Coordinate descent iterations resulted in non-finite parameter"
+                " values. The input data may contain large values and need to"
+                " be preprocessed."
+            )
+
+        # return self for chaining fit and predict calls
+        return self
+
+    @property
+    def sparse_coef_(self):
+        """Sparse representation of the fitted `coef_`."""
+        return sparse.csr_matrix(self.coef_)
+
+    def _decision_function(self, X):
+        """Decision function of the linear model.
+
+        Parameters
+        ----------
+        X : numpy array or scipy.sparse matrix of shape (n_samples, n_features)
+
+        Returns
+        -------
+        T : ndarray of shape (n_samples,)
+            The predicted decision function.
+        """
+        check_is_fitted(self)
+        if sparse.issparse(X):
+            return safe_sparse_dot(X, self.coef_.T, dense_output=True) + self.intercept_
+        else:
+            return super()._decision_function(X)
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.input_tags.sparse = True
+        return tags
+
+
+###############################################################################
+# Lasso model
+
+
+class Lasso(ElasticNet):
+    """Linear Model trained with L1 prior as regularizer (aka the Lasso).
+
+    The optimization objective for Lasso is::
+
+        (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1
+
+    Technically the Lasso model is optimizing the same objective function as
+    the Elastic Net with ``l1_ratio=1.0`` (no L2 penalty).
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    alpha : float, default=1.0
+        Constant that multiplies the L1 term, controlling regularization
+        strength. `alpha` must be a non-negative float i.e. in `[0, inf)`.
+
+        When `alpha = 0`, the objective is equivalent to ordinary least
+        squares, solved by the :class:`LinearRegression` object. For numerical
+        reasons, using `alpha = 0` with the `Lasso` object is not advised.
+        Instead, you should use the :class:`LinearRegression` object.
+
+    fit_intercept : bool, default=True
+        Whether to calculate the intercept for this model. If set
+        to False, no intercept will be used in calculations
+        (i.e. data is expected to be centered).
+
+    precompute : bool or array-like of shape (n_features, n_features),\
+                 default=False
+        Whether to use a precomputed Gram matrix to speed up
+        calculations. The Gram matrix can also be passed as argument.
+        For sparse input this option is always ``False`` to preserve sparsity.
+
+    copy_X : bool, default=True
+        If ``True``, X will be copied; else, it may be overwritten.
+
+    max_iter : int, default=1000
+        The maximum number of iterations.
+
+    tol : float, default=1e-4
+        The tolerance for the optimization: if the updates are
+        smaller than ``tol``, the optimization code checks the
+        dual gap for optimality and continues until it is smaller
+        than ``tol``, see Notes below.
+
+    warm_start : bool, default=False
+        When set to True, reuse the solution of the previous call to fit as
+        initialization, otherwise, just erase the previous solution.
+        See :term:`the Glossary `.
+
+    positive : bool, default=False
+        When set to ``True``, forces the coefficients to be positive.
+
+    random_state : int, RandomState instance, default=None
+        The seed of the pseudo random number generator that selects a random
+        feature to update. Used when ``selection`` == 'random'.
+        Pass an int for reproducible output across multiple function calls.
+        See :term:`Glossary `.
+
+    selection : {'cyclic', 'random'}, default='cyclic'
+        If set to 'random', a random coefficient is updated every iteration
+        rather than looping over features sequentially by default. This
+        (setting to 'random') often leads to significantly faster convergence
+        especially when tol is higher than 1e-4.
+
+    Attributes
+    ----------
+    coef_ : ndarray of shape (n_features,) or (n_targets, n_features)
+        Parameter vector (w in the cost function formula).
+
+    dual_gap_ : float or ndarray of shape (n_targets,)
+        Given param alpha, the dual gaps at the end of the optimization,
+        same shape as each observation of y.
+
+    sparse_coef_ : sparse matrix of shape (n_features, 1) or \
+            (n_targets, n_features)
+        Readonly property derived from ``coef_``.
+
+    intercept_ : float or ndarray of shape (n_targets,)
+        Independent term in decision function.
+
+    n_iter_ : int or list of int
+        Number of iterations run by the coordinate descent solver to reach
+        the specified tolerance.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    lars_path : Regularization path using LARS.
+    lasso_path : Regularization path using Lasso.
+    LassoLars : Lasso Path along the regularization parameter using LARS algorithm.
+    LassoCV : Lasso alpha parameter by cross-validation.
+    LassoLarsCV : Lasso least angle parameter algorithm by cross-validation.
+    sklearn.decomposition.sparse_encode : Sparse coding array estimator.
+
+    Notes
+    -----
+    The algorithm used to fit the model is coordinate descent.
+
+    To avoid unnecessary memory duplication the X argument of the fit method
+    should be directly passed as a Fortran-contiguous numpy array.
+
+    Regularization improves the conditioning of the problem and
+    reduces the variance of the estimates. Larger values specify stronger
+    regularization. Alpha corresponds to `1 / (2C)` in other linear
+    models such as :class:`~sklearn.linear_model.LogisticRegression` or
+    :class:`~sklearn.svm.LinearSVC`.
+
+    The precise stopping criteria based on `tol` are the following: First, check that
+    that maximum coordinate update, i.e. :math:`\\max_j |w_j^{new} - w_j^{old}|`
+    is smaller than `tol` times the maximum absolute coefficient, :math:`\\max_j |w_j|`.
+    If so, then additionally check whether the dual gap is smaller than `tol` times
+    :math:`||y||_2^2 / n_{\\text{samples}}`.
+
+    The target can be a 2-dimensional array, resulting in the optimization of the
+    following objective::
+
+        (1 / (2 * n_samples)) * ||Y - XW||^2_F + alpha * ||W||_11
+
+    where :math:`||W||_{1,1}` is the sum of the magnitude of the matrix coefficients.
+    It should not be confused with :class:`~sklearn.linear_model.MultiTaskLasso` which
+    instead penalizes the :math:`L_{2,1}` norm of the coefficients, yielding row-wise
+    sparsity in the coefficients.
+
+    Examples
+    --------
+    >>> from sklearn import linear_model
+    >>> clf = linear_model.Lasso(alpha=0.1)
+    >>> clf.fit([[0,0], [1, 1], [2, 2]], [0, 1, 2])
+    Lasso(alpha=0.1)
+    >>> print(clf.coef_)
+    [0.85 0.  ]
+    >>> print(clf.intercept_)
+    0.15
+
+    -   :ref:`sphx_glr_auto_examples_linear_model_plot_lasso_and_elasticnet.py`
+        compares Lasso with other L1-based regression models (ElasticNet and ARD
+        Regression) for sparse signal recovery in the presence of noise and
+        feature correlation.
+    """
+
+    _parameter_constraints: dict = {
+        **ElasticNet._parameter_constraints,
+    }
+    _parameter_constraints.pop("l1_ratio")
+
+    path = staticmethod(enet_path)
+
+    def __init__(
+        self,
+        alpha=1.0,
+        *,
+        fit_intercept=True,
+        precompute=False,
+        copy_X=True,
+        max_iter=1000,
+        tol=1e-4,
+        warm_start=False,
+        positive=False,
+        random_state=None,
+        selection="cyclic",
+    ):
+        super().__init__(
+            alpha=alpha,
+            l1_ratio=1.0,
+            fit_intercept=fit_intercept,
+            precompute=precompute,
+            copy_X=copy_X,
+            max_iter=max_iter,
+            tol=tol,
+            warm_start=warm_start,
+            positive=positive,
+            random_state=random_state,
+            selection=selection,
+        )
+
+
+###############################################################################
+# Functions for CV with paths functions
+
+
+def _path_residuals(
+    X,
+    y,
+    sample_weight,
+    train,
+    test,
+    fit_intercept,
+    path,
+    path_params,
+    alphas=None,
+    l1_ratio=1,
+    X_order=None,
+    dtype=None,
+):
+    """Returns the MSE for the models computed by 'path'.
+
+    Parameters
+    ----------
+    X : {array-like, sparse matrix} of shape (n_samples, n_features)
+        Training data.
+
+    y : array-like of shape (n_samples,) or (n_samples, n_targets)
+        Target values.
+
+    sample_weight : None or array-like of shape (n_samples,)
+        Sample weights.
+
+    train : list of indices
+        The indices of the train set.
+
+    test : list of indices
+        The indices of the test set.
+
+    path : callable
+        Function returning a list of models on the path. See
+        enet_path for an example of signature.
+
+    path_params : dictionary
+        Parameters passed to the path function.
+
+    alphas : array-like, default=None
+        Array of float that is used for cross-validation. If not
+        provided, computed using 'path'.
+
+    l1_ratio : float, default=1
+        float between 0 and 1 passed to ElasticNet (scaling between
+        l1 and l2 penalties). For ``l1_ratio = 0`` the penalty is an
+        L2 penalty. For ``l1_ratio = 1`` it is an L1 penalty. For ``0
+        < l1_ratio < 1``, the penalty is a combination of L1 and L2.
+
+    X_order : {'F', 'C'}, default=None
+        The order of the arrays expected by the path function to
+        avoid memory copies.
+
+    dtype : a numpy dtype, default=None
+        The dtype of the arrays expected by the path function to
+        avoid memory copies.
+    """
+    X_train = X[train]
+    y_train = y[train]
+    X_test = X[test]
+    y_test = y[test]
+    if sample_weight is None:
+        sw_train, sw_test = None, None
+    else:
+        sw_train = sample_weight[train]
+        sw_test = sample_weight[test]
+        n_samples = X_train.shape[0]
+        # TLDR: Rescale sw_train to sum up to n_samples on the training set.
+        # See TLDR and long comment inside ElasticNet.fit.
+        sw_train *= n_samples / np.sum(sw_train)
+        # Note: Alternatively, we could also have rescaled alpha instead
+        # of sample_weight:
+        #
+        #     alpha *= np.sum(sample_weight) / n_samples
+
+    if not sparse.issparse(X):
+        for array, array_input in (
+            (X_train, X),
+            (y_train, y),
+            (X_test, X),
+            (y_test, y),
+        ):
+            if array.base is not array_input and not array.flags["WRITEABLE"]:
+                # fancy indexing should create a writable copy but it doesn't
+                # for read-only memmaps (cf. numpy#14132).
+                array.setflags(write=True)
+
+    if y.ndim == 1:
+        precompute = path_params["precompute"]
+    else:
+        # No Gram variant of multi-task exists right now.
+        # Fall back to default enet_multitask
+        precompute = False
+
+    X_train, y_train, X_offset, y_offset, X_scale, precompute, Xy = _pre_fit(
+        X_train,
+        y_train,
+        None,
+        precompute,
+        fit_intercept=fit_intercept,
+        copy=False,
+        sample_weight=sw_train,
+    )
+
+    path_params = path_params.copy()
+    path_params["Xy"] = Xy
+    path_params["X_offset"] = X_offset
+    path_params["X_scale"] = X_scale
+    path_params["precompute"] = precompute
+    path_params["copy_X"] = False
+    path_params["alphas"] = alphas
+    # needed for sparse cd solver
+    path_params["sample_weight"] = sw_train
+
+    if "l1_ratio" in path_params:
+        path_params["l1_ratio"] = l1_ratio
+
+    # Do the ordering and type casting here, as if it is done in the path,
+    # X is copied and a reference is kept here
+    X_train = check_array(X_train, accept_sparse="csc", dtype=dtype, order=X_order)
+    alphas, coefs, _ = path(X_train, y_train, **path_params)
+    del X_train, y_train
+
+    if y.ndim == 1:
+        # Doing this so that it becomes coherent with multioutput.
+        coefs = coefs[np.newaxis, :, :]
+        y_offset = np.atleast_1d(y_offset)
+        y_test = y_test[:, np.newaxis]
+
+    intercepts = y_offset[:, np.newaxis] - np.dot(X_offset, coefs)
+    X_test_coefs = safe_sparse_dot(X_test, coefs)
+    residues = X_test_coefs - y_test[:, :, np.newaxis]
+    residues += intercepts
+    if sample_weight is None:
+        this_mse = (residues**2).mean(axis=0)
+    else:
+        this_mse = np.average(residues**2, weights=sw_test, axis=0)
+
+    return this_mse.mean(axis=0)
+
+
+class LinearModelCV(MultiOutputMixin, LinearModel, ABC):
+    """Base class for iterative model fitting along a regularization path."""
+
+    _parameter_constraints: dict = {
+        "eps": [Interval(Real, 0, None, closed="neither")],
+        "n_alphas": [
+            Interval(Integral, 1, None, closed="left"),
+            Hidden(StrOptions({"deprecated"})),
+        ],
+        # TODO(1.9): remove "warn" and None options.
+        "alphas": [
+            Interval(Integral, 1, None, closed="left"),
+            "array-like",
+            None,
+            Hidden(StrOptions({"warn"})),
+        ],
+        "fit_intercept": ["boolean"],
+        "precompute": [StrOptions({"auto"}), "array-like", "boolean"],
+        "max_iter": [Interval(Integral, 1, None, closed="left")],
+        "tol": [Interval(Real, 0, None, closed="left")],
+        "copy_X": ["boolean"],
+        "cv": ["cv_object"],
+        "verbose": ["verbose"],
+        "n_jobs": [Integral, None],
+        "positive": ["boolean"],
+        "random_state": ["random_state"],
+        "selection": [StrOptions({"cyclic", "random"})],
+    }
+
+    @abstractmethod
+    def __init__(
+        self,
+        eps=1e-3,
+        n_alphas="deprecated",
+        alphas="warn",
+        fit_intercept=True,
+        precompute="auto",
+        max_iter=1000,
+        tol=1e-4,
+        copy_X=True,
+        cv=None,
+        verbose=False,
+        n_jobs=None,
+        positive=False,
+        random_state=None,
+        selection="cyclic",
+    ):
+        self.eps = eps
+        self.n_alphas = n_alphas
+        self.alphas = alphas
+        self.fit_intercept = fit_intercept
+        self.precompute = precompute
+        self.max_iter = max_iter
+        self.tol = tol
+        self.copy_X = copy_X
+        self.cv = cv
+        self.verbose = verbose
+        self.n_jobs = n_jobs
+        self.positive = positive
+        self.random_state = random_state
+        self.selection = selection
+
+    @abstractmethod
+    def _get_estimator(self):
+        """Model to be fitted after the best alpha has been determined."""
+
+    @abstractmethod
+    def _is_multitask(self):
+        """Bool indicating if class is meant for multidimensional target."""
+
+    @staticmethod
+    @abstractmethod
+    def path(X, y, **kwargs):
+        """Compute path with coordinate descent."""
+
+    @_fit_context(prefer_skip_nested_validation=True)
+    def fit(self, X, y, sample_weight=None, **params):
+        """Fit linear model with coordinate descent.
+
+        Fit is on grid of alphas and best alpha estimated by cross-validation.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            Training data. Pass directly as Fortran-contiguous data
+            to avoid unnecessary memory duplication. If y is mono-output,
+            X can be sparse. Note that large sparse matrices and arrays
+            requiring `int64` indices are not accepted.
+
+        y : array-like of shape (n_samples,) or (n_samples, n_targets)
+            Target values.
+
+        sample_weight : float or array-like of shape (n_samples,), \
+                default=None
+            Sample weights used for fitting and evaluation of the weighted
+            mean squared error of each cv-fold. Note that the cross validated
+            MSE that is finally used to find the best model is the unweighted
+            mean over the (weighted) MSEs of each test fold.
+
+        **params : dict, default=None
+            Parameters to be passed to the CV splitter.
+
+            .. versionadded:: 1.4
+                Only available if `enable_metadata_routing=True`,
+                which can be set by using
+                ``sklearn.set_config(enable_metadata_routing=True)``.
+                See :ref:`Metadata Routing User Guide ` for
+                more details.
+
+        Returns
+        -------
+        self : object
+            Returns an instance of fitted model.
+        """
+        _raise_for_params(params, self, "fit")
+
+        # TODO(1.9): remove n_alphas and alphas={"warn", None}; set alphas=100 by
+        # default. Remove these deprecations messages and use self.alphas directly
+        # instead of self._alphas.
+        if self.n_alphas == "deprecated":
+            self._alphas = 100
+        else:
+            warnings.warn(
+                "'n_alphas' was deprecated in 1.7 and will be removed in 1.9. "
+                "'alphas' now accepts an integer value which removes the need to pass "
+                "'n_alphas'. The default value of 'alphas' will change from None to "
+                "100 in 1.9. Pass an explicit value to 'alphas' and leave 'n_alphas' "
+                "to its default value to silence this warning.",
+                FutureWarning,
+            )
+            self._alphas = self.n_alphas
+
+        if isinstance(self.alphas, str) and self.alphas == "warn":
+            # - If self.n_alphas == "deprecated", both are left to their default values
+            #   so we don't warn since the future default behavior will be the same as
+            #   the current default behavior.
+            # - If self.n_alphas != "deprecated", then we already warned about it
+            #   and the warning message mentions the future self.alphas default, so
+            #   no need to warn a second time.
+            pass
+        elif self.alphas is None:
+            warnings.warn(
+                "'alphas=None' is deprecated and will be removed in 1.9, at which "
+                "point the default value will be set to 100. Set 'alphas=100' "
+                "to silence this warning.",
+                FutureWarning,
+            )
+        else:
+            self._alphas = self.alphas
+
+        # This makes sure that there is no duplication in memory.
+        # Dealing right with copy_X is important in the following:
+        # Multiple functions touch X and subsamples of X and can induce a
+        # lot of duplication of memory
+        copy_X = self.copy_X and self.fit_intercept
+
+        check_y_params = dict(
+            copy=False, dtype=[np.float64, np.float32], ensure_2d=False
+        )
+        if isinstance(X, np.ndarray) or sparse.issparse(X):
+            # Keep a reference to X
+            reference_to_old_X = X
+            # Let us not impose fortran ordering so far: it is
+            # not useful for the cross-validation loop and will be done
+            # by the model fitting itself
+
+            # Need to validate separately here.
+            # We can't pass multi_output=True because that would allow y to be
+            # csr. We also want to allow y to be 64 or 32 but check_X_y only
+            # allows to convert for 64.
+            check_X_params = dict(
+                accept_sparse="csc",
+                dtype=[np.float64, np.float32],
+                force_writeable=True,
+                copy=False,
+                accept_large_sparse=False,
+            )
+            X, y = validate_data(
+                self, X, y, validate_separately=(check_X_params, check_y_params)
+            )
+            if sparse.issparse(X):
+                if hasattr(reference_to_old_X, "data") and not np.may_share_memory(
+                    reference_to_old_X.data, X.data
+                ):
+                    # X is a sparse matrix and has been copied
+                    copy_X = False
+            elif not np.may_share_memory(reference_to_old_X, X):
+                # X has been copied
+                copy_X = False
+            del reference_to_old_X
+        else:
+            # Need to validate separately here.
+            # We can't pass multi_output=True because that would allow y to be
+            # csr. We also want to allow y to be 64 or 32 but check_X_y only
+            # allows to convert for 64.
+            check_X_params = dict(
+                accept_sparse="csc",
+                dtype=[np.float64, np.float32],
+                order="F",
+                force_writeable=True,
+                copy=copy_X,
+            )
+            X, y = validate_data(
+                self, X, y, validate_separately=(check_X_params, check_y_params)
+            )
+            copy_X = False
+
+        check_consistent_length(X, y)
+
+        if not self._is_multitask():
+            if y.ndim > 1 and y.shape[1] > 1:
+                raise ValueError(
+                    "For multi-task outputs, use MultiTask%s" % self.__class__.__name__
+                )
+            y = column_or_1d(y, warn=True)
+        else:
+            if sparse.issparse(X):
+                raise TypeError("X should be dense but a sparse matrix waspassed")
+            elif y.ndim == 1:
+                raise ValueError(
+                    "For mono-task outputs, use %sCV" % self.__class__.__name__[9:]
+                )
+
+        if isinstance(sample_weight, numbers.Number):
+            sample_weight = None
+        if sample_weight is not None:
+            sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype)
+
+        model = self._get_estimator()
+
+        # All LinearModelCV parameters except 'cv' are acceptable
+        path_params = self.get_params()
+
+        # Pop `intercept` that is not parameter of the path function
+        path_params.pop("fit_intercept", None)
+
+        if "l1_ratio" in path_params:
+            l1_ratios = np.atleast_1d(path_params["l1_ratio"])
+            # For the first path, we need to set l1_ratio
+            path_params["l1_ratio"] = l1_ratios[0]
+        else:
+            l1_ratios = [
+                1,
+            ]
+        path_params.pop("cv", None)
+        path_params.pop("n_jobs", None)
+
+        n_l1_ratio = len(l1_ratios)
+
+        check_scalar_alpha = partial(
+            check_scalar,
+            target_type=Real,
+            min_val=0.0,
+            include_boundaries="left",
+        )
+
+        if isinstance(self._alphas, Integral):
+            alphas = [
+                _alpha_grid(
+                    X,
+                    y,
+                    l1_ratio=l1_ratio,
+                    fit_intercept=self.fit_intercept,
+                    eps=self.eps,
+                    n_alphas=self._alphas,
+                    copy_X=self.copy_X,
+                    sample_weight=sample_weight,
+                )
+                for l1_ratio in l1_ratios
+            ]
+        else:
+            # Making sure alphas entries are scalars.
+            for index, alpha in enumerate(self._alphas):
+                check_scalar_alpha(alpha, f"alphas[{index}]")
+            # Making sure alphas is properly ordered.
+            alphas = np.tile(np.sort(self._alphas)[::-1], (n_l1_ratio, 1))
+
+        # We want n_alphas to be the number of alphas used for each l1_ratio.
+        n_alphas = len(alphas[0])
+        path_params.update({"n_alphas": n_alphas})
+
+        path_params["copy_X"] = copy_X
+        # We are not computing in parallel, we can modify X
+        # inplace in the folds
+        if effective_n_jobs(self.n_jobs) > 1:
+            path_params["copy_X"] = False
+
+        # init cross-validation generator
+        cv = check_cv(self.cv)
+
+        if _routing_enabled():
+            splitter_supports_sample_weight = get_routing_for_object(cv).consumes(
+                method="split", params=["sample_weight"]
+            )
+            if (
+                sample_weight is not None
+                and not splitter_supports_sample_weight
+                and not has_fit_parameter(self, "sample_weight")
+            ):
+                raise ValueError(
+                    "The CV splitter and underlying estimator do not support"
+                    " sample weights."
+                )
+
+            if splitter_supports_sample_weight:
+                params["sample_weight"] = sample_weight
+
+            routed_params = process_routing(self, "fit", **params)
+
+            if sample_weight is not None and not has_fit_parameter(
+                self, "sample_weight"
+            ):
+                # MultiTaskElasticNetCV does not (yet) support sample_weight
+                sample_weight = None
+        else:
+            routed_params = Bunch()
+            routed_params.splitter = Bunch(split=Bunch())
+
+        # Compute path for all folds and compute MSE to get the best alpha
+        folds = list(cv.split(X, y, **routed_params.splitter.split))
+        best_mse = np.inf
+
+        # We do a double for loop folded in one, in order to be able to
+        # iterate in parallel on l1_ratio and folds
+        jobs = (
+            delayed(_path_residuals)(
+                X,
+                y,
+                sample_weight,
+                train,
+                test,
+                self.fit_intercept,
+                self.path,
+                path_params,
+                alphas=this_alphas,
+                l1_ratio=this_l1_ratio,
+                X_order="F",
+                dtype=X.dtype.type,
+            )
+            for this_l1_ratio, this_alphas in zip(l1_ratios, alphas)
+            for train, test in folds
+        )
+        mse_paths = Parallel(
+            n_jobs=self.n_jobs,
+            verbose=self.verbose,
+            prefer="threads",
+        )(jobs)
+        mse_paths = np.reshape(mse_paths, (n_l1_ratio, len(folds), -1))
+        # The mean is computed over folds.
+        mean_mse = np.mean(mse_paths, axis=1)
+        self.mse_path_ = np.squeeze(np.moveaxis(mse_paths, 2, 1))
+        for l1_ratio, l1_alphas, mse_alphas in zip(l1_ratios, alphas, mean_mse):
+            i_best_alpha = np.argmin(mse_alphas)
+            this_best_mse = mse_alphas[i_best_alpha]
+            if this_best_mse < best_mse:
+                best_alpha = l1_alphas[i_best_alpha]
+                best_l1_ratio = l1_ratio
+                best_mse = this_best_mse
+
+        self.l1_ratio_ = best_l1_ratio
+        self.alpha_ = best_alpha
+        if isinstance(self._alphas, Integral):
+            self.alphas_ = np.asarray(alphas)
+            if n_l1_ratio == 1:
+                self.alphas_ = self.alphas_[0]
+        # Remove duplicate alphas in case alphas is provided.
+        else:
+            self.alphas_ = np.asarray(alphas[0])
+
+        # Refit the model with the parameters selected
+        common_params = {
+            name: value
+            for name, value in self.get_params().items()
+            if name in model.get_params()
+        }
+        model.set_params(**common_params)
+        model.alpha = best_alpha
+        model.l1_ratio = best_l1_ratio
+        model.copy_X = copy_X
+        precompute = getattr(self, "precompute", None)
+        if isinstance(precompute, str) and precompute == "auto":
+            model.precompute = False
+
+        if sample_weight is None:
+            # MultiTaskElasticNetCV does not (yet) support sample_weight, even
+            # not sample_weight=None.
+            model.fit(X, y)
+        else:
+            model.fit(X, y, sample_weight=sample_weight)
+        if not hasattr(self, "l1_ratio"):
+            del self.l1_ratio_
+        self.coef_ = model.coef_
+        self.intercept_ = model.intercept_
+        self.dual_gap_ = model.dual_gap_
+        self.n_iter_ = model.n_iter_
+        return self
+
+    def get_metadata_routing(self):
+        """Get metadata routing of this object.
+
+        Please check :ref:`User Guide ` on how the routing
+        mechanism works.
+
+        .. versionadded:: 1.4
+
+        Returns
+        -------
+        routing : MetadataRouter
+            A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
+            routing information.
+        """
+        router = (
+            MetadataRouter(owner=self.__class__.__name__)
+            .add_self_request(self)
+            .add(
+                splitter=check_cv(self.cv),
+                method_mapping=MethodMapping().add(caller="fit", callee="split"),
+            )
+        )
+        return router
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        multitask = self._is_multitask()
+        tags.input_tags.sparse = not multitask
+        tags.target_tags.multi_output = multitask
+        return tags
+
+
+class LassoCV(RegressorMixin, LinearModelCV):
+    """Lasso linear model with iterative fitting along a regularization path.
+
+    See glossary entry for :term:`cross-validation estimator`.
+
+    The best model is selected by cross-validation.
+
+    The optimization objective for Lasso is::
+
+        (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    eps : float, default=1e-3
+        Length of the path. ``eps=1e-3`` means that
+        ``alpha_min / alpha_max = 1e-3``.
+
+    n_alphas : int, default=100
+        Number of alphas along the regularization path.
+
+        .. deprecated:: 1.7
+            `n_alphas` was deprecated in 1.7 and will be removed in 1.9. Use `alphas`
+            instead.
+
+    alphas : array-like or int, default=None
+        Values of alphas to test along the regularization path.
+        If int, `alphas` values are generated automatically.
+        If array-like, list of alpha values to use.
+
+        .. versionchanged:: 1.7
+            `alphas` accepts an integer value which removes the need to pass
+            `n_alphas`.
+
+        .. deprecated:: 1.7
+            `alphas=None` was deprecated in 1.7 and will be removed in 1.9, at which
+            point the default value will be set to 100.
+
+    fit_intercept : bool, default=True
+        Whether to calculate the intercept for this model. If set
+        to false, no intercept will be used in calculations
+        (i.e. data is expected to be centered).
+
+    precompute : 'auto', bool or array-like of shape \
+            (n_features, n_features), default='auto'
+        Whether to use a precomputed Gram matrix to speed up
+        calculations. If set to ``'auto'`` let us decide. The Gram
+        matrix can also be passed as argument.
+
+    max_iter : int, default=1000
+        The maximum number of iterations.
+
+    tol : float, default=1e-4
+        The tolerance for the optimization: if the updates are
+        smaller than ``tol``, the optimization code checks the
+        dual gap for optimality and continues until it is smaller
+        than ``tol``.
+
+    copy_X : bool, default=True
+        If ``True``, X will be copied; else, it may be overwritten.
+
+    cv : int, cross-validation generator or iterable, default=None
+        Determines the cross-validation splitting strategy.
+        Possible inputs for cv are:
+
+        - None, to use the default 5-fold cross-validation,
+        - int, to specify the number of folds.
+        - :term:`CV splitter`,
+        - An iterable yielding (train, test) splits as arrays of indices.
+
+        For int/None inputs, :class:`~sklearn.model_selection.KFold` is used.
+
+        Refer :ref:`User Guide ` for the various
+        cross-validation strategies that can be used here.
+
+        .. versionchanged:: 0.22
+            ``cv`` default value if None changed from 3-fold to 5-fold.
+
+    verbose : bool or int, default=False
+        Amount of verbosity.
+
+    n_jobs : int, default=None
+        Number of CPUs to use during the cross validation.
+        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+        ``-1`` means using all processors. See :term:`Glossary `
+        for more details.
+
+    positive : bool, default=False
+        If positive, restrict regression coefficients to be positive.
+
+    random_state : int, RandomState instance, default=None
+        The seed of the pseudo random number generator that selects a random
+        feature to update. Used when ``selection`` == 'random'.
+        Pass an int for reproducible output across multiple function calls.
+        See :term:`Glossary `.
+
+    selection : {'cyclic', 'random'}, default='cyclic'
+        If set to 'random', a random coefficient is updated every iteration
+        rather than looping over features sequentially by default. This
+        (setting to 'random') often leads to significantly faster convergence
+        especially when tol is higher than 1e-4.
+
+    Attributes
+    ----------
+    alpha_ : float
+        The amount of penalization chosen by cross validation.
+
+    coef_ : ndarray of shape (n_features,) or (n_targets, n_features)
+        Parameter vector (w in the cost function formula).
+
+    intercept_ : float or ndarray of shape (n_targets,)
+        Independent term in decision function.
+
+    mse_path_ : ndarray of shape (n_alphas, n_folds)
+        Mean square error for the test set on each fold, varying alpha.
+
+    alphas_ : ndarray of shape (n_alphas,)
+        The grid of alphas used for fitting.
+
+    dual_gap_ : float or ndarray of shape (n_targets,)
+        The dual gap at the end of the optimization for the optimal alpha
+        (``alpha_``).
+
+    n_iter_ : int
+        Number of iterations run by the coordinate descent solver to reach
+        the specified tolerance for the optimal alpha.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    lars_path : Compute Least Angle Regression or Lasso path using LARS
+        algorithm.
+    lasso_path : Compute Lasso path with coordinate descent.
+    Lasso : The Lasso is a linear model that estimates sparse coefficients.
+    LassoLars : Lasso model fit with Least Angle Regression a.k.a. Lars.
+    LassoCV : Lasso linear model with iterative fitting along a regularization
+        path.
+    LassoLarsCV : Cross-validated Lasso using the LARS algorithm.
+
+    Notes
+    -----
+    In `fit`, once the best parameter `alpha` is found through
+    cross-validation, the model is fit again using the entire training set.
+
+    To avoid unnecessary memory duplication the `X` argument of the `fit`
+    method should be directly passed as a Fortran-contiguous numpy array.
+
+    For an example, see :ref:`examples/linear_model/plot_lasso_model_selection.py
+    `.
+
+    :class:`LassoCV` leads to different results than a hyperparameter
+    search using :class:`~sklearn.model_selection.GridSearchCV` with a
+    :class:`Lasso` model. In :class:`LassoCV`, a model for a given
+    penalty `alpha` is warm started using the coefficients of the
+    closest model (trained at the previous iteration) on the
+    regularization path. It tends to speed up the hyperparameter
+    search.
+
+    Examples
+    --------
+    >>> from sklearn.linear_model import LassoCV
+    >>> from sklearn.datasets import make_regression
+    >>> X, y = make_regression(noise=4, random_state=0)
+    >>> reg = LassoCV(cv=5, random_state=0).fit(X, y)
+    >>> reg.score(X, y)
+    0.9993
+    >>> reg.predict(X[:1,])
+    array([-78.4951])
+    """
+
+    path = staticmethod(lasso_path)
+
+    def __init__(
+        self,
+        *,
+        eps=1e-3,
+        n_alphas="deprecated",
+        alphas="warn",
+        fit_intercept=True,
+        precompute="auto",
+        max_iter=1000,
+        tol=1e-4,
+        copy_X=True,
+        cv=None,
+        verbose=False,
+        n_jobs=None,
+        positive=False,
+        random_state=None,
+        selection="cyclic",
+    ):
+        super().__init__(
+            eps=eps,
+            n_alphas=n_alphas,
+            alphas=alphas,
+            fit_intercept=fit_intercept,
+            precompute=precompute,
+            max_iter=max_iter,
+            tol=tol,
+            copy_X=copy_X,
+            cv=cv,
+            verbose=verbose,
+            n_jobs=n_jobs,
+            positive=positive,
+            random_state=random_state,
+            selection=selection,
+        )
+
+    def _get_estimator(self):
+        return Lasso()
+
+    def _is_multitask(self):
+        return False
+
+    def fit(self, X, y, sample_weight=None, **params):
+        """Fit Lasso model with coordinate descent.
+
+        Fit is on grid of alphas and best alpha estimated by cross-validation.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            Training data. Pass directly as Fortran-contiguous data
+            to avoid unnecessary memory duplication. If y is mono-output,
+            X can be sparse. Note that large sparse matrices and arrays
+            requiring `int64` indices are not accepted.
+
+        y : array-like of shape (n_samples,)
+            Target values.
+
+        sample_weight : float or array-like of shape (n_samples,), \
+                default=None
+            Sample weights used for fitting and evaluation of the weighted
+            mean squared error of each cv-fold. Note that the cross validated
+            MSE that is finally used to find the best model is the unweighted
+            mean over the (weighted) MSEs of each test fold.
+
+        **params : dict, default=None
+            Parameters to be passed to the CV splitter.
+
+            .. versionadded:: 1.4
+                Only available if `enable_metadata_routing=True`,
+                which can be set by using
+                ``sklearn.set_config(enable_metadata_routing=True)``.
+                See :ref:`Metadata Routing User Guide ` for
+                more details.
+
+        Returns
+        -------
+        self : object
+            Returns an instance of fitted model.
+        """
+        return super().fit(X, y, sample_weight=sample_weight, **params)
+
+
+class ElasticNetCV(RegressorMixin, LinearModelCV):
+    """Elastic Net model with iterative fitting along a regularization path.
+
+    See glossary entry for :term:`cross-validation estimator`.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    l1_ratio : float or list of float, default=0.5
+        Float between 0 and 1 passed to ElasticNet (scaling between
+        l1 and l2 penalties). For ``l1_ratio = 0``
+        the penalty is an L2 penalty. For ``l1_ratio = 1`` it is an L1 penalty.
+        For ``0 < l1_ratio < 1``, the penalty is a combination of L1 and L2
+        This parameter can be a list, in which case the different
+        values are tested by cross-validation and the one giving the best
+        prediction score is used. Note that a good choice of list of
+        values for l1_ratio is often to put more values close to 1
+        (i.e. Lasso) and less close to 0 (i.e. Ridge), as in ``[.1, .5, .7,
+        .9, .95, .99, 1]``.
+
+    eps : float, default=1e-3
+        Length of the path. ``eps=1e-3`` means that
+        ``alpha_min / alpha_max = 1e-3``.
+
+    n_alphas : int, default=100
+        Number of alphas along the regularization path, used for each l1_ratio.
+
+        .. deprecated:: 1.7
+            `n_alphas` was deprecated in 1.7 and will be removed in 1.9. Use `alphas`
+            instead.
+
+    alphas : array-like or int, default=None
+        Values of alphas to test along the regularization path, used for each l1_ratio.
+        If int, `alphas` values are generated automatically.
+        If array-like, list of alpha values to use.
+
+        .. versionchanged:: 1.7
+            `alphas` accepts an integer value which removes the need to pass
+            `n_alphas`.
+
+        .. deprecated:: 1.7
+            `alphas=None` was deprecated in 1.7 and will be removed in 1.9, at which
+            point the default value will be set to 100.
+
+    fit_intercept : bool, default=True
+        Whether to calculate the intercept for this model. If set
+        to false, no intercept will be used in calculations
+        (i.e. data is expected to be centered).
+
+    precompute : 'auto', bool or array-like of shape \
+            (n_features, n_features), default='auto'
+        Whether to use a precomputed Gram matrix to speed up
+        calculations. If set to ``'auto'`` let us decide. The Gram
+        matrix can also be passed as argument.
+
+    max_iter : int, default=1000
+        The maximum number of iterations.
+
+    tol : float, default=1e-4
+        The tolerance for the optimization: if the updates are
+        smaller than ``tol``, the optimization code checks the
+        dual gap for optimality and continues until it is smaller
+        than ``tol``.
+
+    cv : int, cross-validation generator or iterable, default=None
+        Determines the cross-validation splitting strategy.
+        Possible inputs for cv are:
+
+        - None, to use the default 5-fold cross-validation,
+        - int, to specify the number of folds.
+        - :term:`CV splitter`,
+        - An iterable yielding (train, test) splits as arrays of indices.
+
+        For int/None inputs, :class:`~sklearn.model_selection.KFold` is used.
+
+        Refer :ref:`User Guide ` for the various
+        cross-validation strategies that can be used here.
+
+        .. versionchanged:: 0.22
+            ``cv`` default value if None changed from 3-fold to 5-fold.
+
+    copy_X : bool, default=True
+        If ``True``, X will be copied; else, it may be overwritten.
+
+    verbose : bool or int, default=0
+        Amount of verbosity.
+
+    n_jobs : int, default=None
+        Number of CPUs to use during the cross validation.
+        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+        ``-1`` means using all processors. See :term:`Glossary `
+        for more details.
+
+    positive : bool, default=False
+        When set to ``True``, forces the coefficients to be positive.
+
+    random_state : int, RandomState instance, default=None
+        The seed of the pseudo random number generator that selects a random
+        feature to update. Used when ``selection`` == 'random'.
+        Pass an int for reproducible output across multiple function calls.
+        See :term:`Glossary `.
+
+    selection : {'cyclic', 'random'}, default='cyclic'
+        If set to 'random', a random coefficient is updated every iteration
+        rather than looping over features sequentially by default. This
+        (setting to 'random') often leads to significantly faster convergence
+        especially when tol is higher than 1e-4.
+
+    Attributes
+    ----------
+    alpha_ : float
+        The amount of penalization chosen by cross validation.
+
+    l1_ratio_ : float
+        The compromise between l1 and l2 penalization chosen by
+        cross validation.
+
+    coef_ : ndarray of shape (n_features,) or (n_targets, n_features)
+        Parameter vector (w in the cost function formula).
+
+    intercept_ : float or ndarray of shape (n_targets, n_features)
+        Independent term in the decision function.
+
+    mse_path_ : ndarray of shape (n_l1_ratio, n_alpha, n_folds)
+        Mean square error for the test set on each fold, varying l1_ratio and
+        alpha.
+
+    alphas_ : ndarray of shape (n_alphas,) or (n_l1_ratio, n_alphas)
+        The grid of alphas used for fitting, for each l1_ratio.
+
+    dual_gap_ : float
+        The dual gaps at the end of the optimization for the optimal alpha.
+
+    n_iter_ : int
+        Number of iterations run by the coordinate descent solver to reach
+        the specified tolerance for the optimal alpha.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    enet_path : Compute elastic net path with coordinate descent.
+    ElasticNet : Linear regression with combined L1 and L2 priors as regularizer.
+
+    Notes
+    -----
+    In `fit`, once the best parameters `l1_ratio` and `alpha` are found through
+    cross-validation, the model is fit again using the entire training set.
+
+    To avoid unnecessary memory duplication the `X` argument of the `fit`
+    method should be directly passed as a Fortran-contiguous numpy array.
+
+    The parameter `l1_ratio` corresponds to alpha in the glmnet R package
+    while alpha corresponds to the lambda parameter in glmnet.
+    More specifically, the optimization objective is::
+
+        1 / (2 * n_samples) * ||y - Xw||^2_2
+        + alpha * l1_ratio * ||w||_1
+        + 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2
+
+    If you are interested in controlling the L1 and L2 penalty
+    separately, keep in mind that this is equivalent to::
+
+        a * L1 + b * L2
+
+    for::
+
+        alpha = a + b and l1_ratio = a / (a + b).
+
+    For an example, see
+    :ref:`examples/linear_model/plot_lasso_model_selection.py
+    `.
+
+    Examples
+    --------
+    >>> from sklearn.linear_model import ElasticNetCV
+    >>> from sklearn.datasets import make_regression
+
+    >>> X, y = make_regression(n_features=2, random_state=0)
+    >>> regr = ElasticNetCV(cv=5, random_state=0)
+    >>> regr.fit(X, y)
+    ElasticNetCV(cv=5, random_state=0)
+    >>> print(regr.alpha_)
+    0.199
+    >>> print(regr.intercept_)
+    0.398
+    >>> print(regr.predict([[0, 0]]))
+    [0.398]
+    """
+
+    _parameter_constraints: dict = {
+        **LinearModelCV._parameter_constraints,
+        "l1_ratio": [Interval(Real, 0, 1, closed="both"), "array-like"],
+    }
+
+    path = staticmethod(enet_path)
+
+    def __init__(
+        self,
+        *,
+        l1_ratio=0.5,
+        eps=1e-3,
+        n_alphas="deprecated",
+        alphas="warn",
+        fit_intercept=True,
+        precompute="auto",
+        max_iter=1000,
+        tol=1e-4,
+        cv=None,
+        copy_X=True,
+        verbose=0,
+        n_jobs=None,
+        positive=False,
+        random_state=None,
+        selection="cyclic",
+    ):
+        self.l1_ratio = l1_ratio
+        self.eps = eps
+        self.n_alphas = n_alphas
+        self.alphas = alphas
+        self.fit_intercept = fit_intercept
+        self.precompute = precompute
+        self.max_iter = max_iter
+        self.tol = tol
+        self.cv = cv
+        self.copy_X = copy_X
+        self.verbose = verbose
+        self.n_jobs = n_jobs
+        self.positive = positive
+        self.random_state = random_state
+        self.selection = selection
+
+    def _get_estimator(self):
+        return ElasticNet()
+
+    def _is_multitask(self):
+        return False
+
+    def fit(self, X, y, sample_weight=None, **params):
+        """Fit ElasticNet model with coordinate descent.
+
+        Fit is on grid of alphas and best alpha estimated by cross-validation.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            Training data. Pass directly as Fortran-contiguous data
+            to avoid unnecessary memory duplication. If y is mono-output,
+            X can be sparse. Note that large sparse matrices and arrays
+            requiring `int64` indices are not accepted.
+
+        y : array-like of shape (n_samples,)
+            Target values.
+
+        sample_weight : float or array-like of shape (n_samples,), \
+                default=None
+            Sample weights used for fitting and evaluation of the weighted
+            mean squared error of each cv-fold. Note that the cross validated
+            MSE that is finally used to find the best model is the unweighted
+            mean over the (weighted) MSEs of each test fold.
+
+        **params : dict, default=None
+            Parameters to be passed to the CV splitter.
+
+            .. versionadded:: 1.4
+                Only available if `enable_metadata_routing=True`,
+                which can be set by using
+                ``sklearn.set_config(enable_metadata_routing=True)``.
+                See :ref:`Metadata Routing User Guide ` for
+                more details.
+
+        Returns
+        -------
+        self : object
+            Returns an instance of fitted model.
+        """
+        return super().fit(X, y, sample_weight=sample_weight, **params)
+
+
+###############################################################################
+# Multi Task ElasticNet and Lasso models (with joint feature selection)
+
+
+class MultiTaskElasticNet(Lasso):
+    """Multi-task ElasticNet model trained with L1/L2 mixed-norm as regularizer.
+
+    The optimization objective for MultiTaskElasticNet is::
+
+        (1 / (2 * n_samples)) * ||Y - XW||_Fro^2
+        + alpha * l1_ratio * ||W||_21
+        + 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
+
+    Where::
+
+        ||W||_21 = sum_i sqrt(sum_j W_ij ^ 2)
+
+    i.e. the sum of norms of each row.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    alpha : float, default=1.0
+        Constant that multiplies the L1/L2 term. Defaults to 1.0.
+
+    l1_ratio : float, default=0.5
+        The ElasticNet mixing parameter, with 0 < l1_ratio <= 1.
+        For l1_ratio = 1 the penalty is an L1/L2 penalty. For l1_ratio = 0 it
+        is an L2 penalty.
+        For ``0 < l1_ratio < 1``, the penalty is a combination of L1/L2 and L2.
+
+    fit_intercept : bool, default=True
+        Whether to calculate the intercept for this model. If set
+        to false, no intercept will be used in calculations
+        (i.e. data is expected to be centered).
+
+    copy_X : bool, default=True
+        If ``True``, X will be copied; else, it may be overwritten.
+
+    max_iter : int, default=1000
+        The maximum number of iterations.
+
+    tol : float, default=1e-4
+        The tolerance for the optimization: if the updates are
+        smaller than ``tol``, the optimization code checks the
+        dual gap for optimality and continues until it is smaller
+        than ``tol``.
+
+    warm_start : bool, default=False
+        When set to ``True``, reuse the solution of the previous call to fit as
+        initialization, otherwise, just erase the previous solution.
+        See :term:`the Glossary `.
+
+    random_state : int, RandomState instance, default=None
+        The seed of the pseudo random number generator that selects a random
+        feature to update. Used when ``selection`` == 'random'.
+        Pass an int for reproducible output across multiple function calls.
+        See :term:`Glossary `.
+
+    selection : {'cyclic', 'random'}, default='cyclic'
+        If set to 'random', a random coefficient is updated every iteration
+        rather than looping over features sequentially by default. This
+        (setting to 'random') often leads to significantly faster convergence
+        especially when tol is higher than 1e-4.
+
+    Attributes
+    ----------
+    intercept_ : ndarray of shape (n_targets,)
+        Independent term in decision function.
+
+    coef_ : ndarray of shape (n_targets, n_features)
+        Parameter vector (W in the cost function formula). If a 1D y is
+        passed in at fit (non multi-task usage), ``coef_`` is then a 1D array.
+        Note that ``coef_`` stores the transpose of ``W``, ``W.T``.
+
+    n_iter_ : int
+        Number of iterations run by the coordinate descent solver to reach
+        the specified tolerance.
+
+    dual_gap_ : float
+        The dual gaps at the end of the optimization.
+
+    eps_ : float
+        The tolerance scaled scaled by the variance of the target `y`.
+
+    sparse_coef_ : sparse matrix of shape (n_features,) or \
+            (n_targets, n_features)
+        Sparse representation of the `coef_`.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    MultiTaskElasticNetCV : Multi-task L1/L2 ElasticNet with built-in
+        cross-validation.
+    ElasticNet : Linear regression with combined L1 and L2 priors as regularizer.
+    MultiTaskLasso : Multi-task Lasso model trained with L1/L2
+        mixed-norm as regularizer.
+
+    Notes
+    -----
+    The algorithm used to fit the model is coordinate descent.
+
+    To avoid unnecessary memory duplication the X and y arguments of the fit
+    method should be directly passed as Fortran-contiguous numpy arrays.
+
+    Examples
+    --------
+    >>> from sklearn import linear_model
+    >>> clf = linear_model.MultiTaskElasticNet(alpha=0.1)
+    >>> clf.fit([[0,0], [1, 1], [2, 2]], [[0, 0], [1, 1], [2, 2]])
+    MultiTaskElasticNet(alpha=0.1)
+    >>> print(clf.coef_)
+    [[0.45663524 0.45612256]
+     [0.45663524 0.45612256]]
+    >>> print(clf.intercept_)
+    [0.0872422 0.0872422]
+    """
+
+    _parameter_constraints: dict = {
+        **ElasticNet._parameter_constraints,
+    }
+    for param in ("precompute", "positive"):
+        _parameter_constraints.pop(param)
+
+    def __init__(
+        self,
+        alpha=1.0,
+        *,
+        l1_ratio=0.5,
+        fit_intercept=True,
+        copy_X=True,
+        max_iter=1000,
+        tol=1e-4,
+        warm_start=False,
+        random_state=None,
+        selection="cyclic",
+    ):
+        self.l1_ratio = l1_ratio
+        self.alpha = alpha
+        self.fit_intercept = fit_intercept
+        self.max_iter = max_iter
+        self.copy_X = copy_X
+        self.tol = tol
+        self.warm_start = warm_start
+        self.random_state = random_state
+        self.selection = selection
+
+    @_fit_context(prefer_skip_nested_validation=True)
+    def fit(self, X, y):
+        """Fit MultiTaskElasticNet model with coordinate descent.
+
+        Parameters
+        ----------
+        X : ndarray of shape (n_samples, n_features)
+            Data.
+        y : ndarray of shape (n_samples, n_targets)
+            Target. Will be cast to X's dtype if necessary.
+
+        Returns
+        -------
+        self : object
+            Fitted estimator.
+
+        Notes
+        -----
+        Coordinate descent is an algorithm that considers each column of
+        data at a time hence it will automatically convert the X input
+        as a Fortran-contiguous numpy array if necessary.
+
+        To avoid memory re-allocation it is advised to allocate the
+        initial data in memory directly using that format.
+        """
+        # Need to validate separately here.
+        # We can't pass multi_output=True because that would allow y to be csr.
+        check_X_params = dict(
+            dtype=[np.float64, np.float32],
+            order="F",
+            force_writeable=True,
+            copy=self.copy_X and self.fit_intercept,
+        )
+        check_y_params = dict(ensure_2d=False, order="F")
+        X, y = validate_data(
+            self, X, y, validate_separately=(check_X_params, check_y_params)
+        )
+        check_consistent_length(X, y)
+        y = y.astype(X.dtype)
+
+        if hasattr(self, "l1_ratio"):
+            model_str = "ElasticNet"
+        else:
+            model_str = "Lasso"
+        if y.ndim == 1:
+            raise ValueError("For mono-task outputs, use %s" % model_str)
+
+        n_samples, n_features = X.shape
+        n_targets = y.shape[1]
+
+        X, y, X_offset, y_offset, X_scale = _preprocess_data(
+            X, y, fit_intercept=self.fit_intercept, copy=False
+        )
+
+        if not self.warm_start or not hasattr(self, "coef_"):
+            self.coef_ = np.zeros(
+                (n_targets, n_features), dtype=X.dtype.type, order="F"
+            )
+
+        l1_reg = self.alpha * self.l1_ratio * n_samples
+        l2_reg = self.alpha * (1.0 - self.l1_ratio) * n_samples
+
+        self.coef_ = np.asfortranarray(self.coef_)  # coef contiguous in memory
+
+        random = self.selection == "random"
+
+        (
+            self.coef_,
+            self.dual_gap_,
+            self.eps_,
+            self.n_iter_,
+        ) = cd_fast.enet_coordinate_descent_multi_task(
+            self.coef_,
+            l1_reg,
+            l2_reg,
+            X,
+            y,
+            self.max_iter,
+            self.tol,
+            check_random_state(self.random_state),
+            random,
+        )
+
+        # account for different objective scaling here and in cd_fast
+        self.dual_gap_ /= n_samples
+
+        self._set_intercept(X_offset, y_offset, X_scale)
+
+        # return self for chaining fit and predict calls
+        return self
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.input_tags.sparse = False
+        tags.target_tags.multi_output = True
+        tags.target_tags.single_output = False
+        return tags
+
+
+class MultiTaskLasso(MultiTaskElasticNet):
+    """Multi-task Lasso model trained with L1/L2 mixed-norm as regularizer.
+
+    The optimization objective for Lasso is::
+
+        (1 / (2 * n_samples)) * ||Y - XW||^2_Fro + alpha * ||W||_21
+
+    Where::
+
+        ||W||_21 = \\sum_i \\sqrt{\\sum_j w_{ij}^2}
+
+    i.e. the sum of norm of each row.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    alpha : float, default=1.0
+        Constant that multiplies the L1/L2 term. Defaults to 1.0.
+
+    fit_intercept : bool, default=True
+        Whether to calculate the intercept for this model. If set
+        to false, no intercept will be used in calculations
+        (i.e. data is expected to be centered).
+
+    copy_X : bool, default=True
+        If ``True``, X will be copied; else, it may be overwritten.
+
+    max_iter : int, default=1000
+        The maximum number of iterations.
+
+    tol : float, default=1e-4
+        The tolerance for the optimization: if the updates are
+        smaller than ``tol``, the optimization code checks the
+        dual gap for optimality and continues until it is smaller
+        than ``tol``.
+
+    warm_start : bool, default=False
+        When set to ``True``, reuse the solution of the previous call to fit as
+        initialization, otherwise, just erase the previous solution.
+        See :term:`the Glossary `.
+
+    random_state : int, RandomState instance, default=None
+        The seed of the pseudo random number generator that selects a random
+        feature to update. Used when ``selection`` == 'random'.
+        Pass an int for reproducible output across multiple function calls.
+        See :term:`Glossary `.
+
+    selection : {'cyclic', 'random'}, default='cyclic'
+        If set to 'random', a random coefficient is updated every iteration
+        rather than looping over features sequentially by default. This
+        (setting to 'random') often leads to significantly faster convergence
+        especially when tol is higher than 1e-4.
+
+    Attributes
+    ----------
+    coef_ : ndarray of shape (n_targets, n_features)
+        Parameter vector (W in the cost function formula).
+        Note that ``coef_`` stores the transpose of ``W``, ``W.T``.
+
+    intercept_ : ndarray of shape (n_targets,)
+        Independent term in decision function.
+
+    n_iter_ : int
+        Number of iterations run by the coordinate descent solver to reach
+        the specified tolerance.
+
+    dual_gap_ : ndarray of shape (n_alphas,)
+        The dual gaps at the end of the optimization for each alpha.
+
+    eps_ : float
+        The tolerance scaled scaled by the variance of the target `y`.
+
+    sparse_coef_ : sparse matrix of shape (n_features,) or \
+            (n_targets, n_features)
+        Sparse representation of the `coef_`.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    Lasso: Linear Model trained with L1 prior as regularizer (aka the Lasso).
+    MultiTaskLassoCV: Multi-task L1 regularized linear model with built-in
+        cross-validation.
+    MultiTaskElasticNetCV: Multi-task L1/L2 ElasticNet with built-in cross-validation.
+
+    Notes
+    -----
+    The algorithm used to fit the model is coordinate descent.
+
+    To avoid unnecessary memory duplication the X and y arguments of the fit
+    method should be directly passed as Fortran-contiguous numpy arrays.
+
+    Examples
+    --------
+    >>> from sklearn import linear_model
+    >>> clf = linear_model.MultiTaskLasso(alpha=0.1)
+    >>> clf.fit([[0, 1], [1, 2], [2, 4]], [[0, 0], [1, 1], [2, 3]])
+    MultiTaskLasso(alpha=0.1)
+    >>> print(clf.coef_)
+    [[0.         0.60809415]
+    [0.         0.94592424]]
+    >>> print(clf.intercept_)
+    [-0.41888636 -0.87382323]
+    """
+
+    _parameter_constraints: dict = {
+        **MultiTaskElasticNet._parameter_constraints,
+    }
+    _parameter_constraints.pop("l1_ratio")
+
+    def __init__(
+        self,
+        alpha=1.0,
+        *,
+        fit_intercept=True,
+        copy_X=True,
+        max_iter=1000,
+        tol=1e-4,
+        warm_start=False,
+        random_state=None,
+        selection="cyclic",
+    ):
+        self.alpha = alpha
+        self.fit_intercept = fit_intercept
+        self.max_iter = max_iter
+        self.copy_X = copy_X
+        self.tol = tol
+        self.warm_start = warm_start
+        self.l1_ratio = 1.0
+        self.random_state = random_state
+        self.selection = selection
+
+
+class MultiTaskElasticNetCV(RegressorMixin, LinearModelCV):
+    """Multi-task L1/L2 ElasticNet with built-in cross-validation.
+
+    See glossary entry for :term:`cross-validation estimator`.
+
+    The optimization objective for MultiTaskElasticNet is::
+
+        (1 / (2 * n_samples)) * ||Y - XW||^Fro_2
+        + alpha * l1_ratio * ||W||_21
+        + 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
+
+    Where::
+
+        ||W||_21 = \\sum_i \\sqrt{\\sum_j w_{ij}^2}
+
+    i.e. the sum of norm of each row.
+
+    Read more in the :ref:`User Guide `.
+
+    .. versionadded:: 0.15
+
+    Parameters
+    ----------
+    l1_ratio : float or list of float, default=0.5
+        The ElasticNet mixing parameter, with 0 < l1_ratio <= 1.
+        For l1_ratio = 1 the penalty is an L1/L2 penalty. For l1_ratio = 0 it
+        is an L2 penalty.
+        For ``0 < l1_ratio < 1``, the penalty is a combination of L1/L2 and L2.
+        This parameter can be a list, in which case the different
+        values are tested by cross-validation and the one giving the best
+        prediction score is used. Note that a good choice of list of
+        values for l1_ratio is often to put more values close to 1
+        (i.e. Lasso) and less close to 0 (i.e. Ridge), as in ``[.1, .5, .7,
+        .9, .95, .99, 1]``.
+
+    eps : float, default=1e-3
+        Length of the path. ``eps=1e-3`` means that
+        ``alpha_min / alpha_max = 1e-3``.
+
+    n_alphas : int, default=100
+        Number of alphas along the regularization path.
+
+        .. deprecated:: 1.7
+            `n_alphas` was deprecated in 1.7 and will be removed in 1.9. Use `alphas`
+            instead.
+
+    alphas : array-like or int, default=None
+        Values of alphas to test along the regularization path, used for each l1_ratio.
+        If int, `alphas` values are generated automatically.
+        If array-like, list of alpha values to use.
+
+        .. versionchanged:: 1.7
+            `alphas` accepts an integer value which removes the need to pass
+            `n_alphas`.
+
+        .. deprecated:: 1.7
+            `alphas=None` was deprecated in 1.7 and will be removed in 1.9, at which
+            point the default value will be set to 100.
+
+    fit_intercept : bool, default=True
+        Whether to calculate the intercept for this model. If set
+        to false, no intercept will be used in calculations
+        (i.e. data is expected to be centered).
+
+    max_iter : int, default=1000
+        The maximum number of iterations.
+
+    tol : float, default=1e-4
+        The tolerance for the optimization: if the updates are
+        smaller than ``tol``, the optimization code checks the
+        dual gap for optimality and continues until it is smaller
+        than ``tol``.
+
+    cv : int, cross-validation generator or iterable, default=None
+        Determines the cross-validation splitting strategy.
+        Possible inputs for cv are:
+
+        - None, to use the default 5-fold cross-validation,
+        - int, to specify the number of folds.
+        - :term:`CV splitter`,
+        - An iterable yielding (train, test) splits as arrays of indices.
+
+        For int/None inputs, :class:`~sklearn.model_selection.KFold` is used.
+
+        Refer :ref:`User Guide ` for the various
+        cross-validation strategies that can be used here.
+
+        .. versionchanged:: 0.22
+            ``cv`` default value if None changed from 3-fold to 5-fold.
+
+    copy_X : bool, default=True
+        If ``True``, X will be copied; else, it may be overwritten.
+
+    verbose : bool or int, default=0
+        Amount of verbosity.
+
+    n_jobs : int, default=None
+        Number of CPUs to use during the cross validation. Note that this is
+        used only if multiple values for l1_ratio are given.
+        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+        ``-1`` means using all processors. See :term:`Glossary `
+        for more details.
+
+    random_state : int, RandomState instance, default=None
+        The seed of the pseudo random number generator that selects a random
+        feature to update. Used when ``selection`` == 'random'.
+        Pass an int for reproducible output across multiple function calls.
+        See :term:`Glossary `.
+
+    selection : {'cyclic', 'random'}, default='cyclic'
+        If set to 'random', a random coefficient is updated every iteration
+        rather than looping over features sequentially by default. This
+        (setting to 'random') often leads to significantly faster convergence
+        especially when tol is higher than 1e-4.
+
+    Attributes
+    ----------
+    intercept_ : ndarray of shape (n_targets,)
+        Independent term in decision function.
+
+    coef_ : ndarray of shape (n_targets, n_features)
+        Parameter vector (W in the cost function formula).
+        Note that ``coef_`` stores the transpose of ``W``, ``W.T``.
+
+    alpha_ : float
+        The amount of penalization chosen by cross validation.
+
+    mse_path_ : ndarray of shape (n_alphas, n_folds) or \
+                (n_l1_ratio, n_alphas, n_folds)
+        Mean square error for the test set on each fold, varying alpha.
+
+    alphas_ : ndarray of shape (n_alphas,) or (n_l1_ratio, n_alphas)
+        The grid of alphas used for fitting, for each l1_ratio.
+
+    l1_ratio_ : float
+        Best l1_ratio obtained by cross-validation.
+
+    n_iter_ : int
+        Number of iterations run by the coordinate descent solver to reach
+        the specified tolerance for the optimal alpha.
+
+    dual_gap_ : float
+        The dual gap at the end of the optimization for the optimal alpha.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    MultiTaskElasticNet : Multi-task L1/L2 ElasticNet with built-in cross-validation.
+    ElasticNetCV : Elastic net model with best model selection by
+        cross-validation.
+    MultiTaskLassoCV : Multi-task Lasso model trained with L1 norm
+        as regularizer and built-in cross-validation.
+
+    Notes
+    -----
+    The algorithm used to fit the model is coordinate descent.
+
+    In `fit`, once the best parameters `l1_ratio` and `alpha` are found through
+    cross-validation, the model is fit again using the entire training set.
+
+    To avoid unnecessary memory duplication the `X` and `y` arguments of the
+    `fit` method should be directly passed as Fortran-contiguous numpy arrays.
+
+    Examples
+    --------
+    >>> from sklearn import linear_model
+    >>> clf = linear_model.MultiTaskElasticNetCV(cv=3)
+    >>> clf.fit([[0,0], [1, 1], [2, 2]],
+    ...         [[0, 0], [1, 1], [2, 2]])
+    MultiTaskElasticNetCV(cv=3)
+    >>> print(clf.coef_)
+    [[0.52875032 0.46958558]
+     [0.52875032 0.46958558]]
+    >>> print(clf.intercept_)
+    [0.00166409 0.00166409]
+    """
+
+    _parameter_constraints: dict = {
+        **LinearModelCV._parameter_constraints,
+        "l1_ratio": [Interval(Real, 0, 1, closed="both"), "array-like"],
+    }
+    _parameter_constraints.pop("precompute")
+    _parameter_constraints.pop("positive")
+
+    path = staticmethod(enet_path)
+
+    def __init__(
+        self,
+        *,
+        l1_ratio=0.5,
+        eps=1e-3,
+        n_alphas="deprecated",
+        alphas="warn",
+        fit_intercept=True,
+        max_iter=1000,
+        tol=1e-4,
+        cv=None,
+        copy_X=True,
+        verbose=0,
+        n_jobs=None,
+        random_state=None,
+        selection="cyclic",
+    ):
+        self.l1_ratio = l1_ratio
+        self.eps = eps
+        self.n_alphas = n_alphas
+        self.alphas = alphas
+        self.fit_intercept = fit_intercept
+        self.max_iter = max_iter
+        self.tol = tol
+        self.cv = cv
+        self.copy_X = copy_X
+        self.verbose = verbose
+        self.n_jobs = n_jobs
+        self.random_state = random_state
+        self.selection = selection
+
+    def _get_estimator(self):
+        return MultiTaskElasticNet()
+
+    def _is_multitask(self):
+        return True
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.target_tags.single_output = False
+        return tags
+
+    # This is necessary as LinearModelCV now supports sample_weight while
+    # MultiTaskElasticNetCV does not (yet).
+    def fit(self, X, y, **params):
+        """Fit MultiTaskElasticNet model with coordinate descent.
+
+        Fit is on grid of alphas and best alpha estimated by cross-validation.
+
+        Parameters
+        ----------
+        X : ndarray of shape (n_samples, n_features)
+            Training data.
+        y : ndarray of shape (n_samples, n_targets)
+            Training target variable. Will be cast to X's dtype if necessary.
+
+        **params : dict, default=None
+            Parameters to be passed to the CV splitter.
+
+            .. versionadded:: 1.4
+                Only available if `enable_metadata_routing=True`,
+                which can be set by using
+                ``sklearn.set_config(enable_metadata_routing=True)``.
+                See :ref:`Metadata Routing User Guide ` for
+                more details.
+
+        Returns
+        -------
+        self : object
+            Returns MultiTaskElasticNet instance.
+        """
+        return super().fit(X, y, **params)
+
+
+class MultiTaskLassoCV(RegressorMixin, LinearModelCV):
+    """Multi-task Lasso model trained with L1/L2 mixed-norm as regularizer.
+
+    See glossary entry for :term:`cross-validation estimator`.
+
+    The optimization objective for MultiTaskLasso is::
+
+        (1 / (2 * n_samples)) * ||Y - XW||^Fro_2 + alpha * ||W||_21
+
+    Where::
+
+        ||W||_21 = \\sum_i \\sqrt{\\sum_j w_{ij}^2}
+
+    i.e. the sum of norm of each row.
+
+    Read more in the :ref:`User Guide `.
+
+    .. versionadded:: 0.15
+
+    Parameters
+    ----------
+    eps : float, default=1e-3
+        Length of the path. ``eps=1e-3`` means that
+        ``alpha_min / alpha_max = 1e-3``.
+
+    n_alphas : int, default=100
+        Number of alphas along the regularization path.
+
+        .. deprecated:: 1.7
+            `n_alphas` was deprecated in 1.7 and will be removed in 1.9. Use `alphas`
+            instead.
+
+    alphas : array-like or int, default=None
+        Values of alphas to test along the regularization path.
+        If int, `alphas` values are generated automatically.
+        If array-like, list of alpha values to use.
+
+        .. versionchanged:: 1.7
+            `alphas` accepts an integer value which removes the need to pass
+            `n_alphas`.
+
+        .. deprecated:: 1.7
+            `alphas=None` was deprecated in 1.7 and will be removed in 1.9, at which
+            point the default value will be set to 100.
+
+    fit_intercept : bool, default=True
+        Whether to calculate the intercept for this model. If set
+        to false, no intercept will be used in calculations
+        (i.e. data is expected to be centered).
+
+    max_iter : int, default=1000
+        The maximum number of iterations.
+
+    tol : float, default=1e-4
+        The tolerance for the optimization: if the updates are
+        smaller than ``tol``, the optimization code checks the
+        dual gap for optimality and continues until it is smaller
+        than ``tol``.
+
+    copy_X : bool, default=True
+        If ``True``, X will be copied; else, it may be overwritten.
+
+    cv : int, cross-validation generator or iterable, default=None
+        Determines the cross-validation splitting strategy.
+        Possible inputs for cv are:
+
+        - None, to use the default 5-fold cross-validation,
+        - int, to specify the number of folds.
+        - :term:`CV splitter`,
+        - An iterable yielding (train, test) splits as arrays of indices.
+
+        For int/None inputs, :class:`~sklearn.model_selection.KFold` is used.
+
+        Refer :ref:`User Guide ` for the various
+        cross-validation strategies that can be used here.
+
+        .. versionchanged:: 0.22
+            ``cv`` default value if None changed from 3-fold to 5-fold.
+
+    verbose : bool or int, default=False
+        Amount of verbosity.
+
+    n_jobs : int, default=None
+        Number of CPUs to use during the cross validation. Note that this is
+        used only if multiple values for l1_ratio are given.
+        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+        ``-1`` means using all processors. See :term:`Glossary `
+        for more details.
+
+    random_state : int, RandomState instance, default=None
+        The seed of the pseudo random number generator that selects a random
+        feature to update. Used when ``selection`` == 'random'.
+        Pass an int for reproducible output across multiple function calls.
+        See :term:`Glossary `.
+
+    selection : {'cyclic', 'random'}, default='cyclic'
+        If set to 'random', a random coefficient is updated every iteration
+        rather than looping over features sequentially by default. This
+        (setting to 'random') often leads to significantly faster convergence
+        especially when tol is higher than 1e-4.
+
+    Attributes
+    ----------
+    intercept_ : ndarray of shape (n_targets,)
+        Independent term in decision function.
+
+    coef_ : ndarray of shape (n_targets, n_features)
+        Parameter vector (W in the cost function formula).
+        Note that ``coef_`` stores the transpose of ``W``, ``W.T``.
+
+    alpha_ : float
+        The amount of penalization chosen by cross validation.
+
+    mse_path_ : ndarray of shape (n_alphas, n_folds)
+        Mean square error for the test set on each fold, varying alpha.
+
+    alphas_ : ndarray of shape (n_alphas,)
+        The grid of alphas used for fitting.
+
+    n_iter_ : int
+        Number of iterations run by the coordinate descent solver to reach
+        the specified tolerance for the optimal alpha.
+
+    dual_gap_ : float
+        The dual gap at the end of the optimization for the optimal alpha.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    MultiTaskElasticNet : Multi-task ElasticNet model trained with L1/L2
+        mixed-norm as regularizer.
+    ElasticNetCV : Elastic net model with best model selection by
+        cross-validation.
+    MultiTaskElasticNetCV : Multi-task L1/L2 ElasticNet with built-in
+        cross-validation.
+
+    Notes
+    -----
+    The algorithm used to fit the model is coordinate descent.
+
+    In `fit`, once the best parameter `alpha` is found through
+    cross-validation, the model is fit again using the entire training set.
+
+    To avoid unnecessary memory duplication the `X` and `y` arguments of the
+    `fit` method should be directly passed as Fortran-contiguous numpy arrays.
+
+    Examples
+    --------
+    >>> from sklearn.linear_model import MultiTaskLassoCV
+    >>> from sklearn.datasets import make_regression
+    >>> from sklearn.metrics import r2_score
+    >>> X, y = make_regression(n_targets=2, noise=4, random_state=0)
+    >>> reg = MultiTaskLassoCV(cv=5, random_state=0).fit(X, y)
+    >>> r2_score(y, reg.predict(X))
+    0.9994
+    >>> reg.alpha_
+    np.float64(0.5713)
+    >>> reg.predict(X[:1,])
+    array([[153.7971,  94.9015]])
+    """
+
+    _parameter_constraints: dict = {
+        **LinearModelCV._parameter_constraints,
+    }
+    _parameter_constraints.pop("precompute")
+    _parameter_constraints.pop("positive")
+
+    path = staticmethod(lasso_path)
+
+    def __init__(
+        self,
+        *,
+        eps=1e-3,
+        n_alphas="deprecated",
+        alphas="warn",
+        fit_intercept=True,
+        max_iter=1000,
+        tol=1e-4,
+        copy_X=True,
+        cv=None,
+        verbose=False,
+        n_jobs=None,
+        random_state=None,
+        selection="cyclic",
+    ):
+        super().__init__(
+            eps=eps,
+            n_alphas=n_alphas,
+            alphas=alphas,
+            fit_intercept=fit_intercept,
+            max_iter=max_iter,
+            tol=tol,
+            copy_X=copy_X,
+            cv=cv,
+            verbose=verbose,
+            n_jobs=n_jobs,
+            random_state=random_state,
+            selection=selection,
+        )
+
+    def _get_estimator(self):
+        return MultiTaskLasso()
+
+    def _is_multitask(self):
+        return True
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.target_tags.single_output = False
+        return tags
+
+    # This is necessary as LinearModelCV now supports sample_weight while
+    # MultiTaskLassoCV does not (yet).
+    def fit(self, X, y, **params):
+        """Fit MultiTaskLasso model with coordinate descent.
+
+        Fit is on grid of alphas and best alpha estimated by cross-validation.
+
+        Parameters
+        ----------
+        X : ndarray of shape (n_samples, n_features)
+            Data.
+        y : ndarray of shape (n_samples, n_targets)
+            Target. Will be cast to X's dtype if necessary.
+
+        **params : dict, default=None
+            Parameters to be passed to the CV splitter.
+
+            .. versionadded:: 1.4
+                Only available if `enable_metadata_routing=True`,
+                which can be set by using
+                ``sklearn.set_config(enable_metadata_routing=True)``.
+                See :ref:`Metadata Routing User Guide ` for
+                more details.
+
+        Returns
+        -------
+        self : object
+            Returns an instance of fitted model.
+        """
+        return super().fit(X, y, **params)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/linear_model/_omp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/linear_model/_omp.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f4dbac2d7634b0fe4e6a02771e64f80adcf490b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/linear_model/_omp.py
@@ -0,0 +1,1121 @@
+"""Orthogonal matching pursuit algorithms"""
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+import warnings
+from math import sqrt
+from numbers import Integral, Real
+
+import numpy as np
+from scipy import linalg
+from scipy.linalg.lapack import get_lapack_funcs
+
+from ..base import MultiOutputMixin, RegressorMixin, _fit_context
+from ..model_selection import check_cv
+from ..utils import Bunch, as_float_array, check_array
+from ..utils._param_validation import Interval, StrOptions, validate_params
+from ..utils.metadata_routing import (
+    MetadataRouter,
+    MethodMapping,
+    _raise_for_params,
+    _routing_enabled,
+    process_routing,
+)
+from ..utils.parallel import Parallel, delayed
+from ..utils.validation import validate_data
+from ._base import LinearModel, _pre_fit
+
+premature = (
+    "Orthogonal matching pursuit ended prematurely due to linear"
+    " dependence in the dictionary. The requested precision might"
+    " not have been met."
+)
+
+
+def _cholesky_omp(X, y, n_nonzero_coefs, tol=None, copy_X=True, return_path=False):
+    """Orthogonal Matching Pursuit step using the Cholesky decomposition.
+
+    Parameters
+    ----------
+    X : ndarray of shape (n_samples, n_features)
+        Input dictionary. Columns are assumed to have unit norm.
+
+    y : ndarray of shape (n_samples,)
+        Input targets.
+
+    n_nonzero_coefs : int
+        Targeted number of non-zero elements.
+
+    tol : float, default=None
+        Targeted squared error, if not None overrides n_nonzero_coefs.
+
+    copy_X : bool, default=True
+        Whether the design matrix X must be copied by the algorithm. A false
+        value is only helpful if X is already Fortran-ordered, otherwise a
+        copy is made anyway.
+
+    return_path : bool, default=False
+        Whether to return every value of the nonzero coefficients along the
+        forward path. Useful for cross-validation.
+
+    Returns
+    -------
+    gamma : ndarray of shape (n_nonzero_coefs,)
+        Non-zero elements of the solution.
+
+    idx : ndarray of shape (n_nonzero_coefs,)
+        Indices of the positions of the elements in gamma within the solution
+        vector.
+
+    coef : ndarray of shape (n_features, n_nonzero_coefs)
+        The first k values of column k correspond to the coefficient value
+        for the active features at that step. The lower left triangle contains
+        garbage. Only returned if ``return_path=True``.
+
+    n_active : int
+        Number of active features at convergence.
+    """
+    if copy_X:
+        X = X.copy("F")
+    else:  # even if we are allowed to overwrite, still copy it if bad order
+        X = np.asfortranarray(X)
+
+    min_float = np.finfo(X.dtype).eps
+    nrm2, swap = linalg.get_blas_funcs(("nrm2", "swap"), (X,))
+    (potrs,) = get_lapack_funcs(("potrs",), (X,))
+
+    alpha = np.dot(X.T, y)
+    residual = y
+    gamma = np.empty(0)
+    n_active = 0
+    indices = np.arange(X.shape[1])  # keeping track of swapping
+
+    max_features = X.shape[1] if tol is not None else n_nonzero_coefs
+
+    L = np.empty((max_features, max_features), dtype=X.dtype)
+
+    if return_path:
+        coefs = np.empty_like(L)
+
+    while True:
+        lam = np.argmax(np.abs(np.dot(X.T, residual)))
+        if lam < n_active or alpha[lam] ** 2 < min_float:
+            # atom already selected or inner product too small
+            warnings.warn(premature, RuntimeWarning, stacklevel=2)
+            break
+
+        if n_active > 0:
+            # Updates the Cholesky decomposition of X' X
+            L[n_active, :n_active] = np.dot(X[:, :n_active].T, X[:, lam])
+            linalg.solve_triangular(
+                L[:n_active, :n_active],
+                L[n_active, :n_active],
+                trans=0,
+                lower=1,
+                overwrite_b=True,
+                check_finite=False,
+            )
+            v = nrm2(L[n_active, :n_active]) ** 2
+            Lkk = linalg.norm(X[:, lam]) ** 2 - v
+            if Lkk <= min_float:  # selected atoms are dependent
+                warnings.warn(premature, RuntimeWarning, stacklevel=2)
+                break
+            L[n_active, n_active] = sqrt(Lkk)
+        else:
+            L[0, 0] = linalg.norm(X[:, lam])
+
+        X.T[n_active], X.T[lam] = swap(X.T[n_active], X.T[lam])
+        alpha[n_active], alpha[lam] = alpha[lam], alpha[n_active]
+        indices[n_active], indices[lam] = indices[lam], indices[n_active]
+        n_active += 1
+
+        # solves LL'x = X'y as a composition of two triangular systems
+        gamma, _ = potrs(
+            L[:n_active, :n_active], alpha[:n_active], lower=True, overwrite_b=False
+        )
+
+        if return_path:
+            coefs[:n_active, n_active - 1] = gamma
+        residual = y - np.dot(X[:, :n_active], gamma)
+        if tol is not None and nrm2(residual) ** 2 <= tol:
+            break
+        elif n_active == max_features:
+            break
+
+    if return_path:
+        return gamma, indices[:n_active], coefs[:, :n_active], n_active
+    else:
+        return gamma, indices[:n_active], n_active
+
+
+def _gram_omp(
+    Gram,
+    Xy,
+    n_nonzero_coefs,
+    tol_0=None,
+    tol=None,
+    copy_Gram=True,
+    copy_Xy=True,
+    return_path=False,
+):
+    """Orthogonal Matching Pursuit step on a precomputed Gram matrix.
+
+    This function uses the Cholesky decomposition method.
+
+    Parameters
+    ----------
+    Gram : ndarray of shape (n_features, n_features)
+        Gram matrix of the input data matrix.
+
+    Xy : ndarray of shape (n_features,)
+        Input targets.
+
+    n_nonzero_coefs : int
+        Targeted number of non-zero elements.
+
+    tol_0 : float, default=None
+        Squared norm of y, required if tol is not None.
+
+    tol : float, default=None
+        Targeted squared error, if not None overrides n_nonzero_coefs.
+
+    copy_Gram : bool, default=True
+        Whether the gram matrix must be copied by the algorithm. A false
+        value is only helpful if it is already Fortran-ordered, otherwise a
+        copy is made anyway.
+
+    copy_Xy : bool, default=True
+        Whether the covariance vector Xy must be copied by the algorithm.
+        If False, it may be overwritten.
+
+    return_path : bool, default=False
+        Whether to return every value of the nonzero coefficients along the
+        forward path. Useful for cross-validation.
+
+    Returns
+    -------
+    gamma : ndarray of shape (n_nonzero_coefs,)
+        Non-zero elements of the solution.
+
+    idx : ndarray of shape (n_nonzero_coefs,)
+        Indices of the positions of the elements in gamma within the solution
+        vector.
+
+    coefs : ndarray of shape (n_features, n_nonzero_coefs)
+        The first k values of column k correspond to the coefficient value
+        for the active features at that step. The lower left triangle contains
+        garbage. Only returned if ``return_path=True``.
+
+    n_active : int
+        Number of active features at convergence.
+    """
+    Gram = Gram.copy("F") if copy_Gram else np.asfortranarray(Gram)
+
+    if copy_Xy or not Xy.flags.writeable:
+        Xy = Xy.copy()
+
+    min_float = np.finfo(Gram.dtype).eps
+    nrm2, swap = linalg.get_blas_funcs(("nrm2", "swap"), (Gram,))
+    (potrs,) = get_lapack_funcs(("potrs",), (Gram,))
+
+    indices = np.arange(len(Gram))  # keeping track of swapping
+    alpha = Xy
+    tol_curr = tol_0
+    delta = 0
+    gamma = np.empty(0)
+    n_active = 0
+
+    max_features = len(Gram) if tol is not None else n_nonzero_coefs
+
+    L = np.empty((max_features, max_features), dtype=Gram.dtype)
+
+    L[0, 0] = 1.0
+    if return_path:
+        coefs = np.empty_like(L)
+
+    while True:
+        lam = np.argmax(np.abs(alpha))
+        if lam < n_active or alpha[lam] ** 2 < min_float:
+            # selected same atom twice, or inner product too small
+            warnings.warn(premature, RuntimeWarning, stacklevel=3)
+            break
+        if n_active > 0:
+            L[n_active, :n_active] = Gram[lam, :n_active]
+            linalg.solve_triangular(
+                L[:n_active, :n_active],
+                L[n_active, :n_active],
+                trans=0,
+                lower=1,
+                overwrite_b=True,
+                check_finite=False,
+            )
+            v = nrm2(L[n_active, :n_active]) ** 2
+            Lkk = Gram[lam, lam] - v
+            if Lkk <= min_float:  # selected atoms are dependent
+                warnings.warn(premature, RuntimeWarning, stacklevel=3)
+                break
+            L[n_active, n_active] = sqrt(Lkk)
+        else:
+            L[0, 0] = sqrt(Gram[lam, lam])
+
+        Gram[n_active], Gram[lam] = swap(Gram[n_active], Gram[lam])
+        Gram.T[n_active], Gram.T[lam] = swap(Gram.T[n_active], Gram.T[lam])
+        indices[n_active], indices[lam] = indices[lam], indices[n_active]
+        Xy[n_active], Xy[lam] = Xy[lam], Xy[n_active]
+        n_active += 1
+        # solves LL'x = X'y as a composition of two triangular systems
+        gamma, _ = potrs(
+            L[:n_active, :n_active], Xy[:n_active], lower=True, overwrite_b=False
+        )
+        if return_path:
+            coefs[:n_active, n_active - 1] = gamma
+        beta = np.dot(Gram[:, :n_active], gamma)
+        alpha = Xy - beta
+        if tol is not None:
+            tol_curr += delta
+            delta = np.inner(gamma, beta[:n_active])
+            tol_curr -= delta
+            if abs(tol_curr) <= tol:
+                break
+        elif n_active == max_features:
+            break
+
+    if return_path:
+        return gamma, indices[:n_active], coefs[:, :n_active], n_active
+    else:
+        return gamma, indices[:n_active], n_active
+
+
+@validate_params(
+    {
+        "X": ["array-like"],
+        "y": [np.ndarray],
+        "n_nonzero_coefs": [Interval(Integral, 1, None, closed="left"), None],
+        "tol": [Interval(Real, 0, None, closed="left"), None],
+        "precompute": ["boolean", StrOptions({"auto"})],
+        "copy_X": ["boolean"],
+        "return_path": ["boolean"],
+        "return_n_iter": ["boolean"],
+    },
+    prefer_skip_nested_validation=True,
+)
+def orthogonal_mp(
+    X,
+    y,
+    *,
+    n_nonzero_coefs=None,
+    tol=None,
+    precompute=False,
+    copy_X=True,
+    return_path=False,
+    return_n_iter=False,
+):
+    r"""Orthogonal Matching Pursuit (OMP).
+
+    Solves n_targets Orthogonal Matching Pursuit problems.
+    An instance of the problem has the form:
+
+    When parametrized by the number of non-zero coefficients using
+    `n_nonzero_coefs`:
+    argmin ||y - X\gamma||^2 subject to ||\gamma||_0 <= n_{nonzero coefs}
+
+    When parametrized by error using the parameter `tol`:
+    argmin ||\gamma||_0 subject to ||y - X\gamma||^2 <= tol
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    X : array-like of shape (n_samples, n_features)
+        Input data. Columns are assumed to have unit norm.
+
+    y : ndarray of shape (n_samples,) or (n_samples, n_targets)
+        Input targets.
+
+    n_nonzero_coefs : int, default=None
+        Desired number of non-zero entries in the solution. If None (by
+        default) this value is set to 10% of n_features.
+
+    tol : float, default=None
+        Maximum squared norm of the residual. If not None, overrides n_nonzero_coefs.
+
+    precompute : 'auto' or bool, default=False
+        Whether to perform precomputations. Improves performance when n_targets
+        or n_samples is very large.
+
+    copy_X : bool, default=True
+        Whether the design matrix X must be copied by the algorithm. A false
+        value is only helpful if X is already Fortran-ordered, otherwise a
+        copy is made anyway.
+
+    return_path : bool, default=False
+        Whether to return every value of the nonzero coefficients along the
+        forward path. Useful for cross-validation.
+
+    return_n_iter : bool, default=False
+        Whether or not to return the number of iterations.
+
+    Returns
+    -------
+    coef : ndarray of shape (n_features,) or (n_features, n_targets)
+        Coefficients of the OMP solution. If `return_path=True`, this contains
+        the whole coefficient path. In this case its shape is
+        (n_features, n_features) or (n_features, n_targets, n_features) and
+        iterating over the last axis generates coefficients in increasing order
+        of active features.
+
+    n_iters : array-like or int
+        Number of active features across every target. Returned only if
+        `return_n_iter` is set to True.
+
+    See Also
+    --------
+    OrthogonalMatchingPursuit : Orthogonal Matching Pursuit model.
+    orthogonal_mp_gram : Solve OMP problems using Gram matrix and the product X.T * y.
+    lars_path : Compute Least Angle Regression or Lasso path using LARS algorithm.
+    sklearn.decomposition.sparse_encode : Sparse coding.
+
+    Notes
+    -----
+    Orthogonal matching pursuit was introduced in S. Mallat, Z. Zhang,
+    Matching pursuits with time-frequency dictionaries, IEEE Transactions on
+    Signal Processing, Vol. 41, No. 12. (December 1993), pp. 3397-3415.
+    (https://www.di.ens.fr/~mallat/papiers/MallatPursuit93.pdf)
+
+    This implementation is based on Rubinstein, R., Zibulevsky, M. and Elad,
+    M., Efficient Implementation of the K-SVD Algorithm using Batch Orthogonal
+    Matching Pursuit Technical Report - CS Technion, April 2008.
+    https://www.cs.technion.ac.il/~ronrubin/Publications/KSVD-OMP-v2.pdf
+
+    Examples
+    --------
+    >>> from sklearn.datasets import make_regression
+    >>> from sklearn.linear_model import orthogonal_mp
+    >>> X, y = make_regression(noise=4, random_state=0)
+    >>> coef = orthogonal_mp(X, y)
+    >>> coef.shape
+    (100,)
+    >>> X[:1,] @ coef
+    array([-78.68])
+    """
+    X = check_array(X, order="F", copy=copy_X)
+    copy_X = False
+    if y.ndim == 1:
+        y = y.reshape(-1, 1)
+    y = check_array(y)
+    if y.shape[1] > 1:  # subsequent targets will be affected
+        copy_X = True
+    if n_nonzero_coefs is None and tol is None:
+        # default for n_nonzero_coefs is 0.1 * n_features
+        # but at least one.
+        n_nonzero_coefs = max(int(0.1 * X.shape[1]), 1)
+    if tol is None and n_nonzero_coefs > X.shape[1]:
+        raise ValueError(
+            "The number of atoms cannot be more than the number of features"
+        )
+    if precompute == "auto":
+        precompute = X.shape[0] > X.shape[1]
+    if precompute:
+        G = np.dot(X.T, X)
+        G = np.asfortranarray(G)
+        Xy = np.dot(X.T, y)
+        if tol is not None:
+            norms_squared = np.sum((y**2), axis=0)
+        else:
+            norms_squared = None
+        return orthogonal_mp_gram(
+            G,
+            Xy,
+            n_nonzero_coefs=n_nonzero_coefs,
+            tol=tol,
+            norms_squared=norms_squared,
+            copy_Gram=copy_X,
+            copy_Xy=False,
+            return_path=return_path,
+        )
+
+    if return_path:
+        coef = np.zeros((X.shape[1], y.shape[1], X.shape[1]))
+    else:
+        coef = np.zeros((X.shape[1], y.shape[1]))
+    n_iters = []
+
+    for k in range(y.shape[1]):
+        out = _cholesky_omp(
+            X, y[:, k], n_nonzero_coefs, tol, copy_X=copy_X, return_path=return_path
+        )
+        if return_path:
+            _, idx, coefs, n_iter = out
+            coef = coef[:, :, : len(idx)]
+            for n_active, x in enumerate(coefs.T):
+                coef[idx[: n_active + 1], k, n_active] = x[: n_active + 1]
+        else:
+            x, idx, n_iter = out
+            coef[idx, k] = x
+        n_iters.append(n_iter)
+
+    if y.shape[1] == 1:
+        n_iters = n_iters[0]
+
+    if return_n_iter:
+        return np.squeeze(coef), n_iters
+    else:
+        return np.squeeze(coef)
+
+
+@validate_params(
+    {
+        "Gram": ["array-like"],
+        "Xy": ["array-like"],
+        "n_nonzero_coefs": [Interval(Integral, 0, None, closed="neither"), None],
+        "tol": [Interval(Real, 0, None, closed="left"), None],
+        "norms_squared": ["array-like", None],
+        "copy_Gram": ["boolean"],
+        "copy_Xy": ["boolean"],
+        "return_path": ["boolean"],
+        "return_n_iter": ["boolean"],
+    },
+    prefer_skip_nested_validation=True,
+)
+def orthogonal_mp_gram(
+    Gram,
+    Xy,
+    *,
+    n_nonzero_coefs=None,
+    tol=None,
+    norms_squared=None,
+    copy_Gram=True,
+    copy_Xy=True,
+    return_path=False,
+    return_n_iter=False,
+):
+    """Gram Orthogonal Matching Pursuit (OMP).
+
+    Solves n_targets Orthogonal Matching Pursuit problems using only
+    the Gram matrix X.T * X and the product X.T * y.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    Gram : array-like of shape (n_features, n_features)
+        Gram matrix of the input data: `X.T * X`.
+
+    Xy : array-like of shape (n_features,) or (n_features, n_targets)
+        Input targets multiplied by `X`: `X.T * y`.
+
+    n_nonzero_coefs : int, default=None
+        Desired number of non-zero entries in the solution. If `None` (by
+        default) this value is set to 10% of n_features.
+
+    tol : float, default=None
+        Maximum squared norm of the residual. If not `None`,
+        overrides `n_nonzero_coefs`.
+
+    norms_squared : array-like of shape (n_targets,), default=None
+        Squared L2 norms of the lines of `y`. Required if `tol` is not None.
+
+    copy_Gram : bool, default=True
+        Whether the gram matrix must be copied by the algorithm. A `False`
+        value is only helpful if it is already Fortran-ordered, otherwise a
+        copy is made anyway.
+
+    copy_Xy : bool, default=True
+        Whether the covariance vector `Xy` must be copied by the algorithm.
+        If `False`, it may be overwritten.
+
+    return_path : bool, default=False
+        Whether to return every value of the nonzero coefficients along the
+        forward path. Useful for cross-validation.
+
+    return_n_iter : bool, default=False
+        Whether or not to return the number of iterations.
+
+    Returns
+    -------
+    coef : ndarray of shape (n_features,) or (n_features, n_targets)
+        Coefficients of the OMP solution. If `return_path=True`, this contains
+        the whole coefficient path. In this case its shape is
+        `(n_features, n_features)` or `(n_features, n_targets, n_features)` and
+        iterating over the last axis yields coefficients in increasing order
+        of active features.
+
+    n_iters : list or int
+        Number of active features across every target. Returned only if
+        `return_n_iter` is set to True.
+
+    See Also
+    --------
+    OrthogonalMatchingPursuit : Orthogonal Matching Pursuit model (OMP).
+    orthogonal_mp : Solves n_targets Orthogonal Matching Pursuit problems.
+    lars_path : Compute Least Angle Regression or Lasso path using
+        LARS algorithm.
+    sklearn.decomposition.sparse_encode : Generic sparse coding.
+        Each column of the result is the solution to a Lasso problem.
+
+    Notes
+    -----
+    Orthogonal matching pursuit was introduced in G. Mallat, Z. Zhang,
+    Matching pursuits with time-frequency dictionaries, IEEE Transactions on
+    Signal Processing, Vol. 41, No. 12. (December 1993), pp. 3397-3415.
+    (https://www.di.ens.fr/~mallat/papiers/MallatPursuit93.pdf)
+
+    This implementation is based on Rubinstein, R., Zibulevsky, M. and Elad,
+    M., Efficient Implementation of the K-SVD Algorithm using Batch Orthogonal
+    Matching Pursuit Technical Report - CS Technion, April 2008.
+    https://www.cs.technion.ac.il/~ronrubin/Publications/KSVD-OMP-v2.pdf
+
+    Examples
+    --------
+    >>> from sklearn.datasets import make_regression
+    >>> from sklearn.linear_model import orthogonal_mp_gram
+    >>> X, y = make_regression(noise=4, random_state=0)
+    >>> coef = orthogonal_mp_gram(X.T @ X, X.T @ y)
+    >>> coef.shape
+    (100,)
+    >>> X[:1,] @ coef
+    array([-78.68])
+    """
+    Gram = check_array(Gram, order="F", copy=copy_Gram)
+    Xy = np.asarray(Xy)
+    if Xy.ndim > 1 and Xy.shape[1] > 1:
+        # or subsequent target will be affected
+        copy_Gram = True
+    if Xy.ndim == 1:
+        Xy = Xy[:, np.newaxis]
+        if tol is not None:
+            norms_squared = [norms_squared]
+    if copy_Xy or not Xy.flags.writeable:
+        # Make the copy once instead of many times in _gram_omp itself.
+        Xy = Xy.copy()
+
+    if n_nonzero_coefs is None and tol is None:
+        n_nonzero_coefs = int(0.1 * len(Gram))
+    if tol is not None and norms_squared is None:
+        raise ValueError(
+            "Gram OMP needs the precomputed norms in order "
+            "to evaluate the error sum of squares."
+        )
+    if tol is not None and tol < 0:
+        raise ValueError("Epsilon cannot be negative")
+    if tol is None and n_nonzero_coefs <= 0:
+        raise ValueError("The number of atoms must be positive")
+    if tol is None and n_nonzero_coefs > len(Gram):
+        raise ValueError(
+            "The number of atoms cannot be more than the number of features"
+        )
+
+    if return_path:
+        coef = np.zeros((len(Gram), Xy.shape[1], len(Gram)), dtype=Gram.dtype)
+    else:
+        coef = np.zeros((len(Gram), Xy.shape[1]), dtype=Gram.dtype)
+
+    n_iters = []
+    for k in range(Xy.shape[1]):
+        out = _gram_omp(
+            Gram,
+            Xy[:, k],
+            n_nonzero_coefs,
+            norms_squared[k] if tol is not None else None,
+            tol,
+            copy_Gram=copy_Gram,
+            copy_Xy=False,
+            return_path=return_path,
+        )
+        if return_path:
+            _, idx, coefs, n_iter = out
+            coef = coef[:, :, : len(idx)]
+            for n_active, x in enumerate(coefs.T):
+                coef[idx[: n_active + 1], k, n_active] = x[: n_active + 1]
+        else:
+            x, idx, n_iter = out
+            coef[idx, k] = x
+        n_iters.append(n_iter)
+
+    if Xy.shape[1] == 1:
+        n_iters = n_iters[0]
+
+    if return_n_iter:
+        return np.squeeze(coef), n_iters
+    else:
+        return np.squeeze(coef)
+
+
+class OrthogonalMatchingPursuit(MultiOutputMixin, RegressorMixin, LinearModel):
+    """Orthogonal Matching Pursuit model (OMP).
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    n_nonzero_coefs : int, default=None
+        Desired number of non-zero entries in the solution. Ignored if `tol` is set.
+        When `None` and `tol` is also `None`, this value is either set to 10% of
+        `n_features` or 1, whichever is greater.
+
+    tol : float, default=None
+        Maximum squared norm of the residual. If not None, overrides n_nonzero_coefs.
+
+    fit_intercept : bool, default=True
+        Whether to calculate the intercept for this model. If set
+        to false, no intercept will be used in calculations
+        (i.e. data is expected to be centered).
+
+    precompute : 'auto' or bool, default='auto'
+        Whether to use a precomputed Gram and Xy matrix to speed up
+        calculations. Improves performance when :term:`n_targets` or
+        :term:`n_samples` is very large. Note that if you already have such
+        matrices, you can pass them directly to the fit method.
+
+    Attributes
+    ----------
+    coef_ : ndarray of shape (n_features,) or (n_targets, n_features)
+        Parameter vector (w in the formula).
+
+    intercept_ : float or ndarray of shape (n_targets,)
+        Independent term in decision function.
+
+    n_iter_ : int or array-like
+        Number of active features across every target.
+
+    n_nonzero_coefs_ : int or None
+        The number of non-zero coefficients in the solution or `None` when `tol` is
+        set. If `n_nonzero_coefs` is None and `tol` is None this value is either set
+        to 10% of `n_features` or 1, whichever is greater.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    orthogonal_mp : Solves n_targets Orthogonal Matching Pursuit problems.
+    orthogonal_mp_gram :  Solves n_targets Orthogonal Matching Pursuit
+        problems using only the Gram matrix X.T * X and the product X.T * y.
+    lars_path : Compute Least Angle Regression or Lasso path using LARS algorithm.
+    Lars : Least Angle Regression model a.k.a. LAR.
+    LassoLars : Lasso model fit with Least Angle Regression a.k.a. Lars.
+    sklearn.decomposition.sparse_encode : Generic sparse coding.
+        Each column of the result is the solution to a Lasso problem.
+    OrthogonalMatchingPursuitCV : Cross-validated
+        Orthogonal Matching Pursuit model (OMP).
+
+    Notes
+    -----
+    Orthogonal matching pursuit was introduced in G. Mallat, Z. Zhang,
+    Matching pursuits with time-frequency dictionaries, IEEE Transactions on
+    Signal Processing, Vol. 41, No. 12. (December 1993), pp. 3397-3415.
+    (https://www.di.ens.fr/~mallat/papiers/MallatPursuit93.pdf)
+
+    This implementation is based on Rubinstein, R., Zibulevsky, M. and Elad,
+    M., Efficient Implementation of the K-SVD Algorithm using Batch Orthogonal
+    Matching Pursuit Technical Report - CS Technion, April 2008.
+    https://www.cs.technion.ac.il/~ronrubin/Publications/KSVD-OMP-v2.pdf
+
+    Examples
+    --------
+    >>> from sklearn.linear_model import OrthogonalMatchingPursuit
+    >>> from sklearn.datasets import make_regression
+    >>> X, y = make_regression(noise=4, random_state=0)
+    >>> reg = OrthogonalMatchingPursuit().fit(X, y)
+    >>> reg.score(X, y)
+    0.9991
+    >>> reg.predict(X[:1,])
+    array([-78.3854])
+    """
+
+    _parameter_constraints: dict = {
+        "n_nonzero_coefs": [Interval(Integral, 1, None, closed="left"), None],
+        "tol": [Interval(Real, 0, None, closed="left"), None],
+        "fit_intercept": ["boolean"],
+        "precompute": [StrOptions({"auto"}), "boolean"],
+    }
+
+    def __init__(
+        self,
+        *,
+        n_nonzero_coefs=None,
+        tol=None,
+        fit_intercept=True,
+        precompute="auto",
+    ):
+        self.n_nonzero_coefs = n_nonzero_coefs
+        self.tol = tol
+        self.fit_intercept = fit_intercept
+        self.precompute = precompute
+
+    @_fit_context(prefer_skip_nested_validation=True)
+    def fit(self, X, y):
+        """Fit the model using X, y as training data.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            Training data.
+
+        y : array-like of shape (n_samples,) or (n_samples, n_targets)
+            Target values. Will be cast to X's dtype if necessary.
+
+        Returns
+        -------
+        self : object
+            Returns an instance of self.
+        """
+        X, y = validate_data(self, X, y, multi_output=True, y_numeric=True)
+        n_features = X.shape[1]
+
+        X, y, X_offset, y_offset, X_scale, Gram, Xy = _pre_fit(
+            X, y, None, self.precompute, self.fit_intercept, copy=True
+        )
+
+        if y.ndim == 1:
+            y = y[:, np.newaxis]
+
+        if self.n_nonzero_coefs is None and self.tol is None:
+            # default for n_nonzero_coefs is 0.1 * n_features
+            # but at least one.
+            self.n_nonzero_coefs_ = max(int(0.1 * n_features), 1)
+        elif self.tol is not None:
+            self.n_nonzero_coefs_ = None
+        else:
+            self.n_nonzero_coefs_ = self.n_nonzero_coefs
+
+        if Gram is False:
+            coef_, self.n_iter_ = orthogonal_mp(
+                X,
+                y,
+                n_nonzero_coefs=self.n_nonzero_coefs_,
+                tol=self.tol,
+                precompute=False,
+                copy_X=True,
+                return_n_iter=True,
+            )
+        else:
+            norms_sq = np.sum(y**2, axis=0) if self.tol is not None else None
+
+            coef_, self.n_iter_ = orthogonal_mp_gram(
+                Gram,
+                Xy=Xy,
+                n_nonzero_coefs=self.n_nonzero_coefs_,
+                tol=self.tol,
+                norms_squared=norms_sq,
+                copy_Gram=True,
+                copy_Xy=True,
+                return_n_iter=True,
+            )
+        self.coef_ = coef_.T
+        self._set_intercept(X_offset, y_offset, X_scale)
+        return self
+
+
+def _omp_path_residues(
+    X_train,
+    y_train,
+    X_test,
+    y_test,
+    copy=True,
+    fit_intercept=True,
+    max_iter=100,
+):
+    """Compute the residues on left-out data for a full LARS path.
+
+    Parameters
+    ----------
+    X_train : ndarray of shape (n_samples, n_features)
+        The data to fit the LARS on.
+
+    y_train : ndarray of shape (n_samples)
+        The target variable to fit LARS on.
+
+    X_test : ndarray of shape (n_samples, n_features)
+        The data to compute the residues on.
+
+    y_test : ndarray of shape (n_samples)
+        The target variable to compute the residues on.
+
+    copy : bool, default=True
+        Whether X_train, X_test, y_train and y_test should be copied.  If
+        False, they may be overwritten.
+
+    fit_intercept : bool, default=True
+        Whether to calculate the intercept for this model. If set
+        to false, no intercept will be used in calculations
+        (i.e. data is expected to be centered).
+
+    max_iter : int, default=100
+        Maximum numbers of iterations to perform, therefore maximum features
+        to include. 100 by default.
+
+    Returns
+    -------
+    residues : ndarray of shape (n_samples, max_features)
+        Residues of the prediction on the test data.
+    """
+
+    if copy:
+        X_train = X_train.copy()
+        y_train = y_train.copy()
+        X_test = X_test.copy()
+        y_test = y_test.copy()
+
+    if fit_intercept:
+        X_mean = X_train.mean(axis=0)
+        X_train -= X_mean
+        X_test -= X_mean
+        y_mean = y_train.mean(axis=0)
+        y_train = as_float_array(y_train, copy=False)
+        y_train -= y_mean
+        y_test = as_float_array(y_test, copy=False)
+        y_test -= y_mean
+
+    coefs = orthogonal_mp(
+        X_train,
+        y_train,
+        n_nonzero_coefs=max_iter,
+        tol=None,
+        precompute=False,
+        copy_X=False,
+        return_path=True,
+    )
+    if coefs.ndim == 1:
+        coefs = coefs[:, np.newaxis]
+
+    return np.dot(coefs.T, X_test.T) - y_test
+
+
+class OrthogonalMatchingPursuitCV(RegressorMixin, LinearModel):
+    """Cross-validated Orthogonal Matching Pursuit model (OMP).
+
+    See glossary entry for :term:`cross-validation estimator`.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    copy : bool, default=True
+        Whether the design matrix X must be copied by the algorithm. A false
+        value is only helpful if X is already Fortran-ordered, otherwise a
+        copy is made anyway.
+
+    fit_intercept : bool, default=True
+        Whether to calculate the intercept for this model. If set
+        to false, no intercept will be used in calculations
+        (i.e. data is expected to be centered).
+
+    max_iter : int, default=None
+        Maximum numbers of iterations to perform, therefore maximum features
+        to include. 10% of ``n_features`` but at least 5 if available.
+
+    cv : int, cross-validation generator or iterable, default=None
+        Determines the cross-validation splitting strategy.
+        Possible inputs for cv are:
+
+        - None, to use the default 5-fold cross-validation,
+        - integer, to specify the number of folds.
+        - :term:`CV splitter`,
+        - An iterable yielding (train, test) splits as arrays of indices.
+
+        For integer/None inputs, :class:`~sklearn.model_selection.KFold` is used.
+
+        Refer :ref:`User Guide ` for the various
+        cross-validation strategies that can be used here.
+
+        .. versionchanged:: 0.22
+            ``cv`` default value if None changed from 3-fold to 5-fold.
+
+    n_jobs : int, default=None
+        Number of CPUs to use during the cross validation.
+        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+        ``-1`` means using all processors. See :term:`Glossary `
+        for more details.
+
+    verbose : bool or int, default=False
+        Sets the verbosity amount.
+
+    Attributes
+    ----------
+    intercept_ : float or ndarray of shape (n_targets,)
+        Independent term in decision function.
+
+    coef_ : ndarray of shape (n_features,) or (n_targets, n_features)
+        Parameter vector (w in the problem formulation).
+
+    n_nonzero_coefs_ : int
+        Estimated number of non-zero coefficients giving the best mean squared
+        error over the cross-validation folds.
+
+    n_iter_ : int or array-like
+        Number of active features across every target for the model refit with
+        the best hyperparameters got by cross-validating across all folds.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    orthogonal_mp : Solves n_targets Orthogonal Matching Pursuit problems.
+    orthogonal_mp_gram : Solves n_targets Orthogonal Matching Pursuit
+        problems using only the Gram matrix X.T * X and the product X.T * y.
+    lars_path : Compute Least Angle Regression or Lasso path using LARS algorithm.
+    Lars : Least Angle Regression model a.k.a. LAR.
+    LassoLars : Lasso model fit with Least Angle Regression a.k.a. Lars.
+    OrthogonalMatchingPursuit : Orthogonal Matching Pursuit model (OMP).
+    LarsCV : Cross-validated Least Angle Regression model.
+    LassoLarsCV : Cross-validated Lasso model fit with Least Angle Regression.
+    sklearn.decomposition.sparse_encode : Generic sparse coding.
+        Each column of the result is the solution to a Lasso problem.
+
+    Notes
+    -----
+    In `fit`, once the optimal number of non-zero coefficients is found through
+    cross-validation, the model is fit again using the entire training set.
+
+    Examples
+    --------
+    >>> from sklearn.linear_model import OrthogonalMatchingPursuitCV
+    >>> from sklearn.datasets import make_regression
+    >>> X, y = make_regression(n_features=100, n_informative=10,
+    ...                        noise=4, random_state=0)
+    >>> reg = OrthogonalMatchingPursuitCV(cv=5).fit(X, y)
+    >>> reg.score(X, y)
+    0.9991
+    >>> reg.n_nonzero_coefs_
+    np.int64(10)
+    >>> reg.predict(X[:1,])
+    array([-78.3854])
+    """
+
+    _parameter_constraints: dict = {
+        "copy": ["boolean"],
+        "fit_intercept": ["boolean"],
+        "max_iter": [Interval(Integral, 0, None, closed="left"), None],
+        "cv": ["cv_object"],
+        "n_jobs": [Integral, None],
+        "verbose": ["verbose"],
+    }
+
+    def __init__(
+        self,
+        *,
+        copy=True,
+        fit_intercept=True,
+        max_iter=None,
+        cv=None,
+        n_jobs=None,
+        verbose=False,
+    ):
+        self.copy = copy
+        self.fit_intercept = fit_intercept
+        self.max_iter = max_iter
+        self.cv = cv
+        self.n_jobs = n_jobs
+        self.verbose = verbose
+
+    @_fit_context(prefer_skip_nested_validation=True)
+    def fit(self, X, y, **fit_params):
+        """Fit the model using X, y as training data.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            Training data.
+
+        y : array-like of shape (n_samples,)
+            Target values. Will be cast to X's dtype if necessary.
+
+        **fit_params : dict
+            Parameters to pass to the underlying splitter.
+
+            .. versionadded:: 1.4
+                Only available if `enable_metadata_routing=True`,
+                which can be set by using
+                ``sklearn.set_config(enable_metadata_routing=True)``.
+                See :ref:`Metadata Routing User Guide ` for
+                more details.
+
+        Returns
+        -------
+        self : object
+            Returns an instance of self.
+        """
+        _raise_for_params(fit_params, self, "fit")
+
+        X, y = validate_data(self, X, y, y_numeric=True, ensure_min_features=2)
+        X = as_float_array(X, copy=False, ensure_all_finite=False)
+        cv = check_cv(self.cv, classifier=False)
+        if _routing_enabled():
+            routed_params = process_routing(self, "fit", **fit_params)
+        else:
+            # TODO(SLEP6): remove when metadata routing cannot be disabled.
+            routed_params = Bunch()
+            routed_params.splitter = Bunch(split={})
+        max_iter = (
+            min(max(int(0.1 * X.shape[1]), 5), X.shape[1])
+            if not self.max_iter
+            else self.max_iter
+        )
+        cv_paths = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)(
+            delayed(_omp_path_residues)(
+                X[train],
+                y[train],
+                X[test],
+                y[test],
+                self.copy,
+                self.fit_intercept,
+                max_iter,
+            )
+            for train, test in cv.split(X, **routed_params.splitter.split)
+        )
+
+        min_early_stop = min(fold.shape[0] for fold in cv_paths)
+        mse_folds = np.array(
+            [(fold[:min_early_stop] ** 2).mean(axis=1) for fold in cv_paths]
+        )
+        best_n_nonzero_coefs = np.argmin(mse_folds.mean(axis=0)) + 1
+        self.n_nonzero_coefs_ = best_n_nonzero_coefs
+        omp = OrthogonalMatchingPursuit(
+            n_nonzero_coefs=best_n_nonzero_coefs,
+            fit_intercept=self.fit_intercept,
+        ).fit(X, y)
+
+        self.coef_ = omp.coef_
+        self.intercept_ = omp.intercept_
+        self.n_iter_ = omp.n_iter_
+        return self
+
+    def get_metadata_routing(self):
+        """Get metadata routing of this object.
+
+        Please check :ref:`User Guide ` on how the routing
+        mechanism works.
+
+        .. versionadded:: 1.4
+
+        Returns
+        -------
+        routing : MetadataRouter
+            A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
+            routing information.
+        """
+
+        router = MetadataRouter(owner=self.__class__.__name__).add(
+            splitter=self.cv,
+            method_mapping=MethodMapping().add(caller="fit", callee="split"),
+        )
+        return router
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e0de99f5e7e37bb92643ad29f3c859c689d4918
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/__init__.py
@@ -0,0 +1,42 @@
+"""The k-nearest neighbors algorithms."""
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+from ._ball_tree import BallTree
+from ._base import VALID_METRICS, VALID_METRICS_SPARSE, sort_graph_by_row_values
+from ._classification import KNeighborsClassifier, RadiusNeighborsClassifier
+from ._graph import (
+    KNeighborsTransformer,
+    RadiusNeighborsTransformer,
+    kneighbors_graph,
+    radius_neighbors_graph,
+)
+from ._kd_tree import KDTree
+from ._kde import KernelDensity
+from ._lof import LocalOutlierFactor
+from ._nca import NeighborhoodComponentsAnalysis
+from ._nearest_centroid import NearestCentroid
+from ._regression import KNeighborsRegressor, RadiusNeighborsRegressor
+from ._unsupervised import NearestNeighbors
+
+__all__ = [
+    "VALID_METRICS",
+    "VALID_METRICS_SPARSE",
+    "BallTree",
+    "KDTree",
+    "KNeighborsClassifier",
+    "KNeighborsRegressor",
+    "KNeighborsTransformer",
+    "KernelDensity",
+    "LocalOutlierFactor",
+    "NearestCentroid",
+    "NearestNeighbors",
+    "NeighborhoodComponentsAnalysis",
+    "RadiusNeighborsClassifier",
+    "RadiusNeighborsRegressor",
+    "RadiusNeighborsTransformer",
+    "kneighbors_graph",
+    "radius_neighbors_graph",
+    "sort_graph_by_row_values",
+]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_ball_tree.pyx.tp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_ball_tree.pyx.tp
new file mode 100644
index 0000000000000000000000000000000000000000..44d876187c54f370a6acaa72645c39371526fac8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_ball_tree.pyx.tp
@@ -0,0 +1,284 @@
+{{py:
+
+# Generated file: _ball_tree.pyx
+
+implementation_specific_values = [
+    # The values are arranged as follows:
+    #
+    #       name_suffix, INPUT_DTYPE_t, INPUT_DTYPE
+    #
+    ('64', 'float64_t', 'np.float64'),
+    ('32', 'float32_t', 'np.float32')
+]
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+}}
+
+
+__all__ = ['BallTree', 'BallTree64', 'BallTree32']
+
+{{for name_suffix, INPUT_DTYPE_t, INPUT_DTYPE in implementation_specific_values}}
+
+DOC_DICT{{name_suffix}} = {
+    'BinaryTree': 'BallTree{{name_suffix}}',
+    'binary_tree': 'ball_tree{{name_suffix}}',
+}
+
+VALID_METRICS{{name_suffix}} = [
+    'BrayCurtisDistance{{name_suffix}}',
+    'CanberraDistance{{name_suffix}}',
+    'ChebyshevDistance{{name_suffix}}',
+    'DiceDistance{{name_suffix}}',
+    'EuclideanDistance{{name_suffix}}',
+    'HammingDistance{{name_suffix}}',
+    'HaversineDistance{{name_suffix}}',
+    'JaccardDistance{{name_suffix}}',
+    'MahalanobisDistance{{name_suffix}}',
+    'ManhattanDistance{{name_suffix}}',
+    'MinkowskiDistance{{name_suffix}}',
+    'PyFuncDistance{{name_suffix}}',
+    'RogersTanimotoDistance{{name_suffix}}',
+    'RussellRaoDistance{{name_suffix}}',
+    'SEuclideanDistance{{name_suffix}}',
+    'SokalMichenerDistance{{name_suffix}}',
+    'SokalSneathDistance{{name_suffix}}',
+    'WMinkowskiDistance{{name_suffix}}',
+]
+
+{{endfor}}
+
+include "_binary_tree.pxi"
+
+{{for name_suffix, INPUT_DTYPE_t, INPUT_DTYPE in implementation_specific_values}}
+
+# Inherit BallTree{{name_suffix}} from BinaryTree{{name_suffix}}
+cdef class BallTree{{name_suffix}}(BinaryTree{{name_suffix}}):
+    __doc__ = CLASS_DOC.format(**DOC_DICT{{name_suffix}})
+    pass
+
+{{endfor}}
+
+
+#----------------------------------------------------------------------
+# The functions below specialized the Binary Tree as a Ball Tree
+#
+#   Note that these functions use the concept of "reduced distance".
+#   The reduced distance, defined for some metrics, is a quantity which
+#   is more efficient to compute than the distance, but preserves the
+#   relative rankings of the true distance.  For example, the reduced
+#   distance for the Euclidean metric is the squared-euclidean distance.
+#   For some metrics, the reduced distance is simply the distance.
+
+{{for name_suffix, INPUT_DTYPE_t, INPUT_DTYPE in implementation_specific_values}}
+
+cdef int allocate_data{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree,
+    intp_t n_nodes,
+    intp_t n_features,
+) except -1:
+    """Allocate arrays needed for the KD Tree"""
+    tree.node_bounds = np.zeros((1, n_nodes, n_features), dtype={{INPUT_DTYPE}})
+    return 0
+
+
+cdef int init_node{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree,
+    NodeData_t[::1] node_data,
+    intp_t i_node,
+    intp_t idx_start,
+    intp_t idx_end,
+) except -1:
+    """Initialize the node for the dataset stored in tree.data"""
+    cdef intp_t n_features = tree.data.shape[1]
+    cdef intp_t n_points = idx_end - idx_start
+
+    cdef intp_t i, j
+    cdef float64_t radius
+    cdef const {{INPUT_DTYPE_t}} *this_pt
+
+    cdef intp_t* idx_array = &tree.idx_array[0]
+    cdef const {{INPUT_DTYPE_t}}* data = &tree.data[0, 0]
+    cdef {{INPUT_DTYPE_t}}* centroid = &tree.node_bounds[0, i_node, 0]
+
+    cdef bint with_sample_weight = tree.sample_weight is not None
+    cdef const {{INPUT_DTYPE_t}}* sample_weight
+    cdef float64_t sum_weight_node
+    if with_sample_weight:
+        sample_weight = &tree.sample_weight[0]
+
+    # determine Node centroid
+    for j in range(n_features):
+        centroid[j] = 0
+
+    if with_sample_weight:
+        sum_weight_node = 0
+        for i in range(idx_start, idx_end):
+            sum_weight_node += sample_weight[idx_array[i]]
+            this_pt = data + n_features * idx_array[i]
+            for j from 0 <= j < n_features:
+                centroid[j] += this_pt[j] * sample_weight[idx_array[i]]
+
+        for j in range(n_features):
+            centroid[j] /= sum_weight_node
+    else:
+        for i in range(idx_start, idx_end):
+            this_pt = data + n_features * idx_array[i]
+            for j from 0 <= j < n_features:
+                centroid[j] += this_pt[j]
+
+        for j in range(n_features):
+            centroid[j] /= n_points
+
+    # determine Node radius
+    radius = 0
+    for i in range(idx_start, idx_end):
+        radius = fmax(radius,
+                      tree.rdist(centroid,
+                                 data + n_features * idx_array[i],
+                                 n_features))
+
+    node_data[i_node].radius = tree.dist_metric._rdist_to_dist(radius)
+    node_data[i_node].idx_start = idx_start
+    node_data[i_node].idx_end = idx_end
+    return 0
+
+
+cdef inline float64_t min_dist{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree,
+    intp_t i_node,
+    const {{INPUT_DTYPE_t}}* pt,
+) except -1 nogil:
+    """Compute the minimum distance between a point and a node"""
+    cdef float64_t dist_pt = tree.dist(pt, &tree.node_bounds[0, i_node, 0],
+                                     tree.data.shape[1])
+    return fmax(0, dist_pt - tree.node_data[i_node].radius)
+
+
+cdef inline float64_t max_dist{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree,
+    intp_t i_node,
+    const {{INPUT_DTYPE_t}}* pt,
+) except -1:
+    """Compute the maximum distance between a point and a node"""
+    cdef float64_t dist_pt = tree.dist(pt, &tree.node_bounds[0, i_node, 0],
+                                     tree.data.shape[1])
+    return dist_pt + tree.node_data[i_node].radius
+
+
+cdef inline int min_max_dist{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree,
+    intp_t i_node,
+    const {{INPUT_DTYPE_t}}* pt,
+    float64_t* min_dist,
+    float64_t* max_dist,
+) except -1 nogil:
+    """Compute the minimum and maximum distance between a point and a node"""
+    cdef float64_t dist_pt = tree.dist(pt, &tree.node_bounds[0, i_node, 0],
+                                     tree.data.shape[1])
+    cdef float64_t rad = tree.node_data[i_node].radius
+    min_dist[0] = fmax(0, dist_pt - rad)
+    max_dist[0] = dist_pt + rad
+    return 0
+
+
+cdef inline float64_t min_rdist{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree,
+    intp_t i_node,
+    const {{INPUT_DTYPE_t}}* pt,
+) except -1 nogil:
+    """Compute the minimum reduced-distance between a point and a node"""
+    if tree.euclidean:
+        return euclidean_dist_to_rdist{{name_suffix}}(
+            min_dist{{name_suffix}}(tree, i_node, pt)
+        )
+    else:
+        return tree.dist_metric._dist_to_rdist(
+            min_dist{{name_suffix}}(tree, i_node, pt)
+        )
+
+
+cdef inline float64_t max_rdist{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree,
+    intp_t i_node,
+    const {{INPUT_DTYPE_t}}* pt,
+) except -1:
+    """Compute the maximum reduced-distance between a point and a node"""
+    if tree.euclidean:
+        return euclidean_dist_to_rdist{{name_suffix}}(
+            max_dist{{name_suffix}}(tree, i_node, pt)
+        )
+    else:
+        return tree.dist_metric._dist_to_rdist(
+            max_dist{{name_suffix}}(tree, i_node, pt)
+        )
+
+
+cdef inline float64_t min_dist_dual{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree1,
+    intp_t i_node1,
+    BinaryTree{{name_suffix}} tree2,
+    intp_t i_node2,
+) except -1:
+    """compute the minimum distance between two nodes"""
+    cdef float64_t dist_pt = tree1.dist(&tree2.node_bounds[0, i_node2, 0],
+                                      &tree1.node_bounds[0, i_node1, 0],
+                                      tree1.data.shape[1])
+    return fmax(0, (dist_pt - tree1.node_data[i_node1].radius
+                    - tree2.node_data[i_node2].radius))
+
+
+cdef inline float64_t max_dist_dual{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree1,
+    intp_t i_node1,
+    BinaryTree{{name_suffix}} tree2,
+    intp_t i_node2,
+) except -1:
+    """compute the maximum distance between two nodes"""
+    cdef float64_t dist_pt = tree1.dist(&tree2.node_bounds[0, i_node2, 0],
+                                      &tree1.node_bounds[0, i_node1, 0],
+                                      tree1.data.shape[1])
+    return (dist_pt + tree1.node_data[i_node1].radius
+            + tree2.node_data[i_node2].radius)
+
+
+cdef inline float64_t min_rdist_dual{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree1,
+    intp_t i_node1,
+    BinaryTree{{name_suffix}} tree2,
+    intp_t i_node2,
+) except -1:
+    """compute the minimum reduced distance between two nodes"""
+    if tree1.euclidean:
+        return euclidean_dist_to_rdist{{name_suffix}}(
+            min_dist_dual{{name_suffix}}(tree1, i_node1, tree2, i_node2)
+        )
+    else:
+        return tree1.dist_metric._dist_to_rdist(
+            min_dist_dual{{name_suffix}}(tree1, i_node1, tree2, i_node2)
+        )
+
+
+cdef inline float64_t max_rdist_dual{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree1,
+    intp_t i_node1,
+    BinaryTree{{name_suffix}} tree2,
+    intp_t i_node2,
+) except -1:
+    """compute the maximum reduced distance between two nodes"""
+    if tree1.euclidean:
+        return euclidean_dist_to_rdist{{name_suffix}}(
+            max_dist_dual{{name_suffix}}(tree1, i_node1, tree2, i_node2)
+        )
+    else:
+        return tree1.dist_metric._dist_to_rdist(
+            max_dist_dual{{name_suffix}}(tree1, i_node1, tree2, i_node2)
+        )
+
+{{endfor}}
+
+
+class BallTree(BallTree64):
+    __doc__ = CLASS_DOC.format(BinaryTree="BallTree")
+    pass
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_base.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..767eee1358aa873808ab7796d080cea06bae97bc
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_base.py
@@ -0,0 +1,1404 @@
+"""Base and mixin classes for nearest neighbors."""
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+import itertools
+import numbers
+import warnings
+from abc import ABCMeta, abstractmethod
+from functools import partial
+from numbers import Integral, Real
+
+import numpy as np
+from joblib import effective_n_jobs
+from scipy.sparse import csr_matrix, issparse
+
+from ..base import BaseEstimator, MultiOutputMixin, is_classifier
+from ..exceptions import DataConversionWarning, EfficiencyWarning
+from ..metrics import DistanceMetric, pairwise_distances_chunked
+from ..metrics._pairwise_distances_reduction import (
+    ArgKmin,
+    RadiusNeighbors,
+)
+from ..metrics.pairwise import PAIRWISE_DISTANCE_FUNCTIONS
+from ..utils import (
+    check_array,
+    gen_even_slices,
+    get_tags,
+)
+from ..utils._param_validation import Interval, StrOptions, validate_params
+from ..utils.fixes import parse_version, sp_base_version
+from ..utils.multiclass import check_classification_targets
+from ..utils.parallel import Parallel, delayed
+from ..utils.validation import _to_object_array, check_is_fitted, validate_data
+from ._ball_tree import BallTree
+from ._kd_tree import KDTree
+
+SCIPY_METRICS = [
+    "braycurtis",
+    "canberra",
+    "chebyshev",
+    "correlation",
+    "cosine",
+    "dice",
+    "hamming",
+    "jaccard",
+    "mahalanobis",
+    "minkowski",
+    "rogerstanimoto",
+    "russellrao",
+    "seuclidean",
+    "sokalsneath",
+    "sqeuclidean",
+    "yule",
+]
+if sp_base_version < parse_version("1.17"):
+    # Deprecated in SciPy 1.15 and removed in SciPy 1.17
+    SCIPY_METRICS += ["sokalmichener"]
+if sp_base_version < parse_version("1.11"):
+    # Deprecated in SciPy 1.9 and removed in SciPy 1.11
+    SCIPY_METRICS += ["kulsinski"]
+if sp_base_version < parse_version("1.9"):
+    # Deprecated in SciPy 1.0 and removed in SciPy 1.9
+    SCIPY_METRICS += ["matching"]
+
+VALID_METRICS = dict(
+    ball_tree=BallTree.valid_metrics,
+    kd_tree=KDTree.valid_metrics,
+    # The following list comes from the
+    # sklearn.metrics.pairwise doc string
+    brute=sorted(set(PAIRWISE_DISTANCE_FUNCTIONS).union(SCIPY_METRICS)),
+)
+
+VALID_METRICS_SPARSE = dict(
+    ball_tree=[],
+    kd_tree=[],
+    brute=(PAIRWISE_DISTANCE_FUNCTIONS.keys() - {"haversine", "nan_euclidean"}),
+)
+
+
+def _get_weights(dist, weights):
+    """Get the weights from an array of distances and a parameter ``weights``.
+
+    Assume weights have already been validated.
+
+    Parameters
+    ----------
+    dist : ndarray
+        The input distances.
+
+    weights : {'uniform', 'distance'}, callable or None
+        The kind of weighting used.
+
+    Returns
+    -------
+    weights_arr : array of the same shape as ``dist``
+        If ``weights == 'uniform'``, then returns None.
+    """
+    if weights in (None, "uniform"):
+        return None
+
+    if weights == "distance":
+        # if user attempts to classify a point that was zero distance from one
+        # or more training points, those training points are weighted as 1.0
+        # and the other points as 0.0
+        if dist.dtype is np.dtype(object):
+            for point_dist_i, point_dist in enumerate(dist):
+                # check if point_dist is iterable
+                # (ex: RadiusNeighborClassifier.predict may set an element of
+                # dist to 1e-6 to represent an 'outlier')
+                if hasattr(point_dist, "__contains__") and 0.0 in point_dist:
+                    dist[point_dist_i] = point_dist == 0.0
+                else:
+                    dist[point_dist_i] = 1.0 / point_dist
+        else:
+            with np.errstate(divide="ignore"):
+                dist = 1.0 / dist
+            inf_mask = np.isinf(dist)
+            inf_row = np.any(inf_mask, axis=1)
+            dist[inf_row] = inf_mask[inf_row]
+        return dist
+
+    if callable(weights):
+        return weights(dist)
+
+
+def _is_sorted_by_data(graph):
+    """Return whether the graph's non-zero entries are sorted by data.
+
+    The non-zero entries are stored in graph.data and graph.indices.
+    For each row (or sample), the non-zero entries can be either:
+        - sorted by indices, as after graph.sort_indices();
+        - sorted by data, as after _check_precomputed(graph);
+        - not sorted.
+
+    Parameters
+    ----------
+    graph : sparse matrix of shape (n_samples, n_samples)
+        Neighbors graph as given by `kneighbors_graph` or
+        `radius_neighbors_graph`. Matrix should be of format CSR format.
+
+    Returns
+    -------
+    res : bool
+        Whether input graph is sorted by data.
+    """
+    assert graph.format == "csr"
+    out_of_order = graph.data[:-1] > graph.data[1:]
+    line_change = np.unique(graph.indptr[1:-1] - 1)
+    line_change = line_change[line_change < out_of_order.shape[0]]
+    return out_of_order.sum() == out_of_order[line_change].sum()
+
+
+def _check_precomputed(X):
+    """Check precomputed distance matrix.
+
+    If the precomputed distance matrix is sparse, it checks that the non-zero
+    entries are sorted by distances. If not, the matrix is copied and sorted.
+
+    Parameters
+    ----------
+    X : {sparse matrix, array-like}, (n_samples, n_samples)
+        Distance matrix to other samples. X may be a sparse matrix, in which
+        case only non-zero elements may be considered neighbors.
+
+    Returns
+    -------
+    X : {sparse matrix, array-like}, (n_samples, n_samples)
+        Distance matrix to other samples. X may be a sparse matrix, in which
+        case only non-zero elements may be considered neighbors.
+    """
+    if not issparse(X):
+        X = check_array(X, ensure_non_negative=True, input_name="X")
+        return X
+    else:
+        graph = X
+
+    if graph.format not in ("csr", "csc", "coo", "lil"):
+        raise TypeError(
+            "Sparse matrix in {!r} format is not supported due to "
+            "its handling of explicit zeros".format(graph.format)
+        )
+    copied = graph.format != "csr"
+    graph = check_array(
+        graph,
+        accept_sparse="csr",
+        ensure_non_negative=True,
+        input_name="precomputed distance matrix",
+    )
+    graph = sort_graph_by_row_values(graph, copy=not copied, warn_when_not_sorted=True)
+
+    return graph
+
+
+@validate_params(
+    {
+        "graph": ["sparse matrix"],
+        "copy": ["boolean"],
+        "warn_when_not_sorted": ["boolean"],
+    },
+    prefer_skip_nested_validation=True,
+)
+def sort_graph_by_row_values(graph, copy=False, warn_when_not_sorted=True):
+    """Sort a sparse graph such that each row is stored with increasing values.
+
+    .. versionadded:: 1.2
+
+    Parameters
+    ----------
+    graph : sparse matrix of shape (n_samples, n_samples)
+        Distance matrix to other samples, where only non-zero elements are
+        considered neighbors. Matrix is converted to CSR format if not already.
+
+    copy : bool, default=False
+        If True, the graph is copied before sorting. If False, the sorting is
+        performed inplace. If the graph is not of CSR format, `copy` must be
+        True to allow the conversion to CSR format, otherwise an error is
+        raised.
+
+    warn_when_not_sorted : bool, default=True
+        If True, a :class:`~sklearn.exceptions.EfficiencyWarning` is raised
+        when the input graph is not sorted by row values.
+
+    Returns
+    -------
+    graph : sparse matrix of shape (n_samples, n_samples)
+        Distance matrix to other samples, where only non-zero elements are
+        considered neighbors. Matrix is in CSR format.
+
+    Examples
+    --------
+    >>> from scipy.sparse import csr_matrix
+    >>> from sklearn.neighbors import sort_graph_by_row_values
+    >>> X = csr_matrix(
+    ...     [[0., 3., 1.],
+    ...      [3., 0., 2.],
+    ...      [1., 2., 0.]])
+    >>> X.data
+    array([3., 1., 3., 2., 1., 2.])
+    >>> X_ = sort_graph_by_row_values(X)
+    >>> X_.data
+    array([1., 3., 2., 3., 1., 2.])
+    """
+    if graph.format == "csr" and _is_sorted_by_data(graph):
+        return graph
+
+    if warn_when_not_sorted:
+        warnings.warn(
+            (
+                "Precomputed sparse input was not sorted by row values. Use the"
+                " function sklearn.neighbors.sort_graph_by_row_values to sort the input"
+                " by row values, with warn_when_not_sorted=False to remove this"
+                " warning."
+            ),
+            EfficiencyWarning,
+        )
+
+    if graph.format not in ("csr", "csc", "coo", "lil"):
+        raise TypeError(
+            f"Sparse matrix in {graph.format!r} format is not supported due to "
+            "its handling of explicit zeros"
+        )
+    elif graph.format != "csr":
+        if not copy:
+            raise ValueError(
+                "The input graph is not in CSR format. Use copy=True to allow "
+                "the conversion to CSR format."
+            )
+        graph = graph.asformat("csr")
+    elif copy:  # csr format with copy=True
+        graph = graph.copy()
+
+    row_nnz = np.diff(graph.indptr)
+    if row_nnz.max() == row_nnz.min():
+        # if each sample has the same number of provided neighbors
+        n_samples = graph.shape[0]
+        distances = graph.data.reshape(n_samples, -1)
+
+        order = np.argsort(distances, kind="mergesort")
+        order += np.arange(n_samples)[:, None] * row_nnz[0]
+        order = order.ravel()
+        graph.data = graph.data[order]
+        graph.indices = graph.indices[order]
+
+    else:
+        for start, stop in zip(graph.indptr, graph.indptr[1:]):
+            order = np.argsort(graph.data[start:stop], kind="mergesort")
+            graph.data[start:stop] = graph.data[start:stop][order]
+            graph.indices[start:stop] = graph.indices[start:stop][order]
+
+    return graph
+
+
+def _kneighbors_from_graph(graph, n_neighbors, return_distance):
+    """Decompose a nearest neighbors sparse graph into distances and indices.
+
+    Parameters
+    ----------
+    graph : sparse matrix of shape (n_samples, n_samples)
+        Neighbors graph as given by `kneighbors_graph` or
+        `radius_neighbors_graph`. Matrix should be of format CSR format.
+
+    n_neighbors : int
+        Number of neighbors required for each sample.
+
+    return_distance : bool
+        Whether or not to return the distances.
+
+    Returns
+    -------
+    neigh_dist : ndarray of shape (n_samples, n_neighbors)
+        Distances to nearest neighbors. Only present if `return_distance=True`.
+
+    neigh_ind : ndarray of shape (n_samples, n_neighbors)
+        Indices of nearest neighbors.
+    """
+    n_samples = graph.shape[0]
+    assert graph.format == "csr"
+
+    # number of neighbors by samples
+    row_nnz = np.diff(graph.indptr)
+    row_nnz_min = row_nnz.min()
+    if n_neighbors is not None and row_nnz_min < n_neighbors:
+        raise ValueError(
+            "%d neighbors per samples are required, but some samples have only"
+            " %d neighbors in precomputed graph matrix. Decrease number of "
+            "neighbors used or recompute the graph with more neighbors."
+            % (n_neighbors, row_nnz_min)
+        )
+
+    def extract(a):
+        # if each sample has the same number of provided neighbors
+        if row_nnz.max() == row_nnz_min:
+            return a.reshape(n_samples, -1)[:, :n_neighbors]
+        else:
+            idx = np.tile(np.arange(n_neighbors), (n_samples, 1))
+            idx += graph.indptr[:-1, None]
+            return a.take(idx, mode="clip").reshape(n_samples, n_neighbors)
+
+    if return_distance:
+        return extract(graph.data), extract(graph.indices)
+    else:
+        return extract(graph.indices)
+
+
+def _radius_neighbors_from_graph(graph, radius, return_distance):
+    """Decompose a nearest neighbors sparse graph into distances and indices.
+
+    Parameters
+    ----------
+    graph : sparse matrix of shape (n_samples, n_samples)
+        Neighbors graph as given by `kneighbors_graph` or
+        `radius_neighbors_graph`. Matrix should be of format CSR format.
+
+    radius : float
+        Radius of neighborhoods which should be strictly positive.
+
+    return_distance : bool
+        Whether or not to return the distances.
+
+    Returns
+    -------
+    neigh_dist : ndarray of shape (n_samples,) of arrays
+        Distances to nearest neighbors. Only present if `return_distance=True`.
+
+    neigh_ind : ndarray of shape (n_samples,) of arrays
+        Indices of nearest neighbors.
+    """
+    assert graph.format == "csr"
+
+    no_filter_needed = bool(graph.data.max() <= radius)
+
+    if no_filter_needed:
+        data, indices, indptr = graph.data, graph.indices, graph.indptr
+    else:
+        mask = graph.data <= radius
+        if return_distance:
+            data = np.compress(mask, graph.data)
+        indices = np.compress(mask, graph.indices)
+        indptr = np.concatenate(([0], np.cumsum(mask)))[graph.indptr]
+
+    indices = indices.astype(np.intp, copy=no_filter_needed)
+
+    if return_distance:
+        neigh_dist = _to_object_array(np.split(data, indptr[1:-1]))
+    neigh_ind = _to_object_array(np.split(indices, indptr[1:-1]))
+
+    if return_distance:
+        return neigh_dist, neigh_ind
+    else:
+        return neigh_ind
+
+
+class NeighborsBase(MultiOutputMixin, BaseEstimator, metaclass=ABCMeta):
+    """Base class for nearest neighbors estimators."""
+
+    _parameter_constraints: dict = {
+        "n_neighbors": [Interval(Integral, 1, None, closed="left"), None],
+        "radius": [Interval(Real, 0, None, closed="both"), None],
+        "algorithm": [StrOptions({"auto", "ball_tree", "kd_tree", "brute"})],
+        "leaf_size": [Interval(Integral, 1, None, closed="left")],
+        "p": [Interval(Real, 0, None, closed="right"), None],
+        "metric": [StrOptions(set(itertools.chain(*VALID_METRICS.values()))), callable],
+        "metric_params": [dict, None],
+        "n_jobs": [Integral, None],
+    }
+
+    @abstractmethod
+    def __init__(
+        self,
+        n_neighbors=None,
+        radius=None,
+        algorithm="auto",
+        leaf_size=30,
+        metric="minkowski",
+        p=2,
+        metric_params=None,
+        n_jobs=None,
+    ):
+        self.n_neighbors = n_neighbors
+        self.radius = radius
+        self.algorithm = algorithm
+        self.leaf_size = leaf_size
+        self.metric = metric
+        self.metric_params = metric_params
+        self.p = p
+        self.n_jobs = n_jobs
+
+    def _check_algorithm_metric(self):
+        if self.algorithm == "auto":
+            if self.metric == "precomputed":
+                alg_check = "brute"
+            elif (
+                callable(self.metric)
+                or self.metric in VALID_METRICS["ball_tree"]
+                or isinstance(self.metric, DistanceMetric)
+            ):
+                alg_check = "ball_tree"
+            else:
+                alg_check = "brute"
+        else:
+            alg_check = self.algorithm
+
+        if callable(self.metric):
+            if self.algorithm == "kd_tree":
+                # callable metric is only valid for brute force and ball_tree
+                raise ValueError(
+                    "kd_tree does not support callable metric '%s'"
+                    "Function call overhead will result"
+                    "in very poor performance." % self.metric
+                )
+        elif self.metric not in VALID_METRICS[alg_check] and not isinstance(
+            self.metric, DistanceMetric
+        ):
+            raise ValueError(
+                "Metric '%s' not valid. Use "
+                "sorted(sklearn.neighbors.VALID_METRICS['%s']) "
+                "to get valid options. "
+                "Metric can also be a callable function." % (self.metric, alg_check)
+            )
+
+        if self.metric_params is not None and "p" in self.metric_params:
+            if self.p is not None:
+                warnings.warn(
+                    (
+                        "Parameter p is found in metric_params. "
+                        "The corresponding parameter from __init__ "
+                        "is ignored."
+                    ),
+                    SyntaxWarning,
+                    stacklevel=3,
+                )
+
+    def _fit(self, X, y=None):
+        ensure_all_finite = "allow-nan" if get_tags(self).input_tags.allow_nan else True
+        if self.__sklearn_tags__().target_tags.required:
+            if not isinstance(X, (KDTree, BallTree, NeighborsBase)):
+                X, y = validate_data(
+                    self,
+                    X,
+                    y,
+                    accept_sparse="csr",
+                    multi_output=True,
+                    order="C",
+                    ensure_all_finite=ensure_all_finite,
+                )
+
+            if is_classifier(self):
+                # Classification targets require a specific format
+                if y.ndim == 1 or (y.ndim == 2 and y.shape[1] == 1):
+                    if y.ndim != 1:
+                        warnings.warn(
+                            (
+                                "A column-vector y was passed when a "
+                                "1d array was expected. Please change "
+                                "the shape of y to (n_samples,), for "
+                                "example using ravel()."
+                            ),
+                            DataConversionWarning,
+                            stacklevel=2,
+                        )
+
+                    self.outputs_2d_ = False
+                    y = y.reshape((-1, 1))
+                else:
+                    self.outputs_2d_ = True
+
+                check_classification_targets(y)
+                self.classes_ = []
+                # Using `dtype=np.intp` is necessary since `np.bincount`
+                # (called in _classification.py) fails when dealing
+                # with a float64 array on 32bit systems.
+                self._y = np.empty(y.shape, dtype=np.intp)
+                for k in range(self._y.shape[1]):
+                    classes, self._y[:, k] = np.unique(y[:, k], return_inverse=True)
+                    self.classes_.append(classes)
+
+                if not self.outputs_2d_:
+                    self.classes_ = self.classes_[0]
+                    self._y = self._y.ravel()
+            else:
+                self._y = y
+
+        else:
+            if not isinstance(X, (KDTree, BallTree, NeighborsBase)):
+                X = validate_data(
+                    self,
+                    X,
+                    ensure_all_finite=ensure_all_finite,
+                    accept_sparse="csr",
+                    order="C",
+                )
+
+        self._check_algorithm_metric()
+        if self.metric_params is None:
+            self.effective_metric_params_ = {}
+        else:
+            self.effective_metric_params_ = self.metric_params.copy()
+
+        effective_p = self.effective_metric_params_.get("p", self.p)
+        if self.metric == "minkowski":
+            self.effective_metric_params_["p"] = effective_p
+
+        self.effective_metric_ = self.metric
+        # For minkowski distance, use more efficient methods where available
+        if self.metric == "minkowski":
+            p = self.effective_metric_params_.pop("p", 2)
+            w = self.effective_metric_params_.pop("w", None)
+
+            if p == 1 and w is None:
+                self.effective_metric_ = "manhattan"
+            elif p == 2 and w is None:
+                self.effective_metric_ = "euclidean"
+            elif p == np.inf and w is None:
+                self.effective_metric_ = "chebyshev"
+            else:
+                # Use the generic minkowski metric, possibly weighted.
+                self.effective_metric_params_["p"] = p
+                self.effective_metric_params_["w"] = w
+
+        if isinstance(X, NeighborsBase):
+            self._fit_X = X._fit_X
+            self._tree = X._tree
+            self._fit_method = X._fit_method
+            self.n_samples_fit_ = X.n_samples_fit_
+            return self
+
+        elif isinstance(X, BallTree):
+            self._fit_X = X.data
+            self._tree = X
+            self._fit_method = "ball_tree"
+            self.n_samples_fit_ = X.data.shape[0]
+            return self
+
+        elif isinstance(X, KDTree):
+            self._fit_X = X.data
+            self._tree = X
+            self._fit_method = "kd_tree"
+            self.n_samples_fit_ = X.data.shape[0]
+            return self
+
+        if self.metric == "precomputed":
+            X = _check_precomputed(X)
+            # Precomputed matrix X must be squared
+            if X.shape[0] != X.shape[1]:
+                raise ValueError(
+                    "Precomputed matrix must be square."
+                    " Input is a {}x{} matrix.".format(X.shape[0], X.shape[1])
+                )
+            self.n_features_in_ = X.shape[1]
+
+        n_samples = X.shape[0]
+        if n_samples == 0:
+            raise ValueError("n_samples must be greater than 0")
+
+        if issparse(X):
+            if self.algorithm not in ("auto", "brute"):
+                warnings.warn("cannot use tree with sparse input: using brute force")
+
+            if (
+                self.effective_metric_ not in VALID_METRICS_SPARSE["brute"]
+                and not callable(self.effective_metric_)
+                and not isinstance(self.effective_metric_, DistanceMetric)
+            ):
+                raise ValueError(
+                    "Metric '%s' not valid for sparse input. "
+                    "Use sorted(sklearn.neighbors."
+                    "VALID_METRICS_SPARSE['brute']) "
+                    "to get valid options. "
+                    "Metric can also be a callable function." % (self.effective_metric_)
+                )
+            self._fit_X = X.copy()
+            self._tree = None
+            self._fit_method = "brute"
+            self.n_samples_fit_ = X.shape[0]
+            return self
+
+        self._fit_method = self.algorithm
+        self._fit_X = X
+        self.n_samples_fit_ = X.shape[0]
+
+        if self._fit_method == "auto":
+            # A tree approach is better for small number of neighbors or small
+            # number of features, with KDTree generally faster when available
+            if (
+                self.metric == "precomputed"
+                or self._fit_X.shape[1] > 15
+                or (
+                    self.n_neighbors is not None
+                    and self.n_neighbors >= self._fit_X.shape[0] // 2
+                )
+            ):
+                self._fit_method = "brute"
+            else:
+                if (
+                    self.effective_metric_ == "minkowski"
+                    and self.effective_metric_params_["p"] < 1
+                ):
+                    self._fit_method = "brute"
+                elif (
+                    self.effective_metric_ == "minkowski"
+                    and self.effective_metric_params_.get("w") is not None
+                ):
+                    # 'minkowski' with weights is not supported by KDTree but is
+                    # supported byBallTree.
+                    self._fit_method = "ball_tree"
+                elif self.effective_metric_ in VALID_METRICS["kd_tree"]:
+                    self._fit_method = "kd_tree"
+                elif (
+                    callable(self.effective_metric_)
+                    or self.effective_metric_ in VALID_METRICS["ball_tree"]
+                ):
+                    self._fit_method = "ball_tree"
+                else:
+                    self._fit_method = "brute"
+
+        if (
+            self.effective_metric_ == "minkowski"
+            and self.effective_metric_params_["p"] < 1
+        ):
+            # For 0 < p < 1 Minkowski distances aren't valid distance
+            # metric as they do not satisfy triangular inequality:
+            # they are semi-metrics.
+            # algorithm="kd_tree" and algorithm="ball_tree" can't be used because
+            # KDTree and BallTree require a proper distance metric to work properly.
+            # However, the brute-force algorithm supports semi-metrics.
+            if self._fit_method == "brute":
+                warnings.warn(
+                    "Mind that for 0 < p < 1, Minkowski metrics are not distance"
+                    " metrics. Continuing the execution with `algorithm='brute'`."
+                )
+            else:  # self._fit_method in ("kd_tree", "ball_tree")
+                raise ValueError(
+                    f'algorithm="{self._fit_method}" does not support 0 < p < 1 for '
+                    "the Minkowski metric. To resolve this problem either "
+                    'set p >= 1 or algorithm="brute".'
+                )
+
+        if self._fit_method == "ball_tree":
+            self._tree = BallTree(
+                X,
+                self.leaf_size,
+                metric=self.effective_metric_,
+                **self.effective_metric_params_,
+            )
+        elif self._fit_method == "kd_tree":
+            if (
+                self.effective_metric_ == "minkowski"
+                and self.effective_metric_params_.get("w") is not None
+            ):
+                raise ValueError(
+                    "algorithm='kd_tree' is not valid for "
+                    "metric='minkowski' with a weight parameter 'w': "
+                    "try algorithm='ball_tree' "
+                    "or algorithm='brute' instead."
+                )
+            self._tree = KDTree(
+                X,
+                self.leaf_size,
+                metric=self.effective_metric_,
+                **self.effective_metric_params_,
+            )
+        elif self._fit_method == "brute":
+            self._tree = None
+
+        return self
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.input_tags.sparse = True
+        # For cross-validation routines to split data correctly
+        tags.input_tags.pairwise = self.metric == "precomputed"
+        # when input is precomputed metric values, all those values need to be positive
+        tags.input_tags.positive_only = tags.input_tags.pairwise
+        tags.input_tags.allow_nan = self.metric == "nan_euclidean"
+        return tags
+
+
+class KNeighborsMixin:
+    """Mixin for k-neighbors searches."""
+
+    def _kneighbors_reduce_func(self, dist, start, n_neighbors, return_distance):
+        """Reduce a chunk of distances to the nearest neighbors.
+
+        Callback to :func:`sklearn.metrics.pairwise.pairwise_distances_chunked`
+
+        Parameters
+        ----------
+        dist : ndarray of shape (n_samples_chunk, n_samples)
+            The distance matrix.
+
+        start : int
+            The index in X which the first row of dist corresponds to.
+
+        n_neighbors : int
+            Number of neighbors required for each sample.
+
+        return_distance : bool
+            Whether or not to return the distances.
+
+        Returns
+        -------
+        dist : array of shape (n_samples_chunk, n_neighbors)
+            Returned only if `return_distance=True`.
+
+        neigh : array of shape (n_samples_chunk, n_neighbors)
+            The neighbors indices.
+        """
+        sample_range = np.arange(dist.shape[0])[:, None]
+        neigh_ind = np.argpartition(dist, n_neighbors - 1, axis=1)
+        neigh_ind = neigh_ind[:, :n_neighbors]
+        # argpartition doesn't guarantee sorted order, so we sort again
+        neigh_ind = neigh_ind[sample_range, np.argsort(dist[sample_range, neigh_ind])]
+        if return_distance:
+            if self.effective_metric_ == "euclidean":
+                result = np.sqrt(dist[sample_range, neigh_ind]), neigh_ind
+            else:
+                result = dist[sample_range, neigh_ind], neigh_ind
+        else:
+            result = neigh_ind
+        return result
+
+    def kneighbors(self, X=None, n_neighbors=None, return_distance=True):
+        """Find the K-neighbors of a point.
+
+        Returns indices of and distances to the neighbors of each point.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix}, shape (n_queries, n_features), \
+            or (n_queries, n_indexed) if metric == 'precomputed', default=None
+            The query point or points.
+            If not provided, neighbors of each indexed point are returned.
+            In this case, the query point is not considered its own neighbor.
+
+        n_neighbors : int, default=None
+            Number of neighbors required for each sample. The default is the
+            value passed to the constructor.
+
+        return_distance : bool, default=True
+            Whether or not to return the distances.
+
+        Returns
+        -------
+        neigh_dist : ndarray of shape (n_queries, n_neighbors)
+            Array representing the lengths to points, only present if
+            return_distance=True.
+
+        neigh_ind : ndarray of shape (n_queries, n_neighbors)
+            Indices of the nearest points in the population matrix.
+
+        Examples
+        --------
+        In the following example, we construct a NearestNeighbors
+        class from an array representing our data set and ask who's
+        the closest point to [1,1,1]
+
+        >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]]
+        >>> from sklearn.neighbors import NearestNeighbors
+        >>> neigh = NearestNeighbors(n_neighbors=1)
+        >>> neigh.fit(samples)
+        NearestNeighbors(n_neighbors=1)
+        >>> print(neigh.kneighbors([[1., 1., 1.]]))
+        (array([[0.5]]), array([[2]]))
+
+        As you can see, it returns [[0.5]], and [[2]], which means that the
+        element is at distance 0.5 and is the third element of samples
+        (indexes start at 0). You can also query for multiple points:
+
+        >>> X = [[0., 1., 0.], [1., 0., 1.]]
+        >>> neigh.kneighbors(X, return_distance=False)
+        array([[1],
+               [2]]...)
+        """
+        check_is_fitted(self)
+
+        if n_neighbors is None:
+            n_neighbors = self.n_neighbors
+        elif n_neighbors <= 0:
+            raise ValueError("Expected n_neighbors > 0. Got %d" % n_neighbors)
+        elif not isinstance(n_neighbors, numbers.Integral):
+            raise TypeError(
+                "n_neighbors does not take %s value, enter integer value"
+                % type(n_neighbors)
+            )
+
+        ensure_all_finite = "allow-nan" if get_tags(self).input_tags.allow_nan else True
+        query_is_train = X is None
+        if query_is_train:
+            X = self._fit_X
+            # Include an extra neighbor to account for the sample itself being
+            # returned, which is removed later
+            n_neighbors += 1
+        else:
+            if self.metric == "precomputed":
+                X = _check_precomputed(X)
+            else:
+                X = validate_data(
+                    self,
+                    X,
+                    ensure_all_finite=ensure_all_finite,
+                    accept_sparse="csr",
+                    reset=False,
+                    order="C",
+                )
+
+        n_samples_fit = self.n_samples_fit_
+        if n_neighbors > n_samples_fit:
+            if query_is_train:
+                n_neighbors -= 1  # ok to modify inplace because an error is raised
+                inequality_str = "n_neighbors < n_samples_fit"
+            else:
+                inequality_str = "n_neighbors <= n_samples_fit"
+            raise ValueError(
+                f"Expected {inequality_str}, but "
+                f"n_neighbors = {n_neighbors}, n_samples_fit = {n_samples_fit}, "
+                f"n_samples = {X.shape[0]}"  # include n_samples for common tests
+            )
+
+        n_jobs = effective_n_jobs(self.n_jobs)
+        chunked_results = None
+        use_pairwise_distances_reductions = (
+            self._fit_method == "brute"
+            and ArgKmin.is_usable_for(
+                X if X is not None else self._fit_X, self._fit_X, self.effective_metric_
+            )
+        )
+        if use_pairwise_distances_reductions:
+            results = ArgKmin.compute(
+                X=X,
+                Y=self._fit_X,
+                k=n_neighbors,
+                metric=self.effective_metric_,
+                metric_kwargs=self.effective_metric_params_,
+                strategy="auto",
+                return_distance=return_distance,
+            )
+
+        elif (
+            self._fit_method == "brute" and self.metric == "precomputed" and issparse(X)
+        ):
+            results = _kneighbors_from_graph(
+                X, n_neighbors=n_neighbors, return_distance=return_distance
+            )
+
+        elif self._fit_method == "brute":
+            # Joblib-based backend, which is used when user-defined callable
+            # are passed for metric.
+
+            # This won't be used in the future once PairwiseDistancesReductions
+            # support:
+            #   - DistanceMetrics which work on supposedly binary data
+            #   - CSR-dense and dense-CSR case if 'euclidean' in metric.
+            reduce_func = partial(
+                self._kneighbors_reduce_func,
+                n_neighbors=n_neighbors,
+                return_distance=return_distance,
+            )
+
+            # for efficiency, use squared euclidean distances
+            if self.effective_metric_ == "euclidean":
+                kwds = {"squared": True}
+            else:
+                kwds = self.effective_metric_params_
+
+            chunked_results = list(
+                pairwise_distances_chunked(
+                    X,
+                    self._fit_X,
+                    reduce_func=reduce_func,
+                    metric=self.effective_metric_,
+                    n_jobs=n_jobs,
+                    **kwds,
+                )
+            )
+
+        elif self._fit_method in ["ball_tree", "kd_tree"]:
+            if issparse(X):
+                raise ValueError(
+                    "%s does not work with sparse matrices. Densify the data, "
+                    "or set algorithm='brute'" % self._fit_method
+                )
+            chunked_results = Parallel(n_jobs, prefer="threads")(
+                delayed(self._tree.query)(X[s], n_neighbors, return_distance)
+                for s in gen_even_slices(X.shape[0], n_jobs)
+            )
+        else:
+            raise ValueError("internal: _fit_method not recognized")
+
+        if chunked_results is not None:
+            if return_distance:
+                neigh_dist, neigh_ind = zip(*chunked_results)
+                results = np.vstack(neigh_dist), np.vstack(neigh_ind)
+            else:
+                results = np.vstack(chunked_results)
+
+        if not query_is_train:
+            return results
+        else:
+            # If the query data is the same as the indexed data, we would like
+            # to ignore the first nearest neighbor of every sample, i.e
+            # the sample itself.
+            if return_distance:
+                neigh_dist, neigh_ind = results
+            else:
+                neigh_ind = results
+
+            n_queries, _ = X.shape
+            sample_range = np.arange(n_queries)[:, None]
+            sample_mask = neigh_ind != sample_range
+
+            # Corner case: When the number of duplicates are more
+            # than the number of neighbors, the first NN will not
+            # be the sample, but a duplicate.
+            # In that case mask the first duplicate.
+            dup_gr_nbrs = np.all(sample_mask, axis=1)
+            sample_mask[:, 0][dup_gr_nbrs] = False
+            neigh_ind = np.reshape(neigh_ind[sample_mask], (n_queries, n_neighbors - 1))
+
+            if return_distance:
+                neigh_dist = np.reshape(
+                    neigh_dist[sample_mask], (n_queries, n_neighbors - 1)
+                )
+                return neigh_dist, neigh_ind
+            return neigh_ind
+
+    def kneighbors_graph(self, X=None, n_neighbors=None, mode="connectivity"):
+        """Compute the (weighted) graph of k-Neighbors for points in X.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_queries, n_features), \
+            or (n_queries, n_indexed) if metric == 'precomputed', default=None
+            The query point or points.
+            If not provided, neighbors of each indexed point are returned.
+            In this case, the query point is not considered its own neighbor.
+            For ``metric='precomputed'`` the shape should be
+            (n_queries, n_indexed). Otherwise the shape should be
+            (n_queries, n_features).
+
+        n_neighbors : int, default=None
+            Number of neighbors for each sample. The default is the value
+            passed to the constructor.
+
+        mode : {'connectivity', 'distance'}, default='connectivity'
+            Type of returned matrix: 'connectivity' will return the
+            connectivity matrix with ones and zeros, in 'distance' the
+            edges are distances between points, type of distance
+            depends on the selected metric parameter in
+            NearestNeighbors class.
+
+        Returns
+        -------
+        A : sparse-matrix of shape (n_queries, n_samples_fit)
+            `n_samples_fit` is the number of samples in the fitted data.
+            `A[i, j]` gives the weight of the edge connecting `i` to `j`.
+            The matrix is of CSR format.
+
+        See Also
+        --------
+        NearestNeighbors.radius_neighbors_graph : Compute the (weighted) graph
+            of Neighbors for points in X.
+
+        Examples
+        --------
+        >>> X = [[0], [3], [1]]
+        >>> from sklearn.neighbors import NearestNeighbors
+        >>> neigh = NearestNeighbors(n_neighbors=2)
+        >>> neigh.fit(X)
+        NearestNeighbors(n_neighbors=2)
+        >>> A = neigh.kneighbors_graph(X)
+        >>> A.toarray()
+        array([[1., 0., 1.],
+               [0., 1., 1.],
+               [1., 0., 1.]])
+        """
+        check_is_fitted(self)
+        if n_neighbors is None:
+            n_neighbors = self.n_neighbors
+
+        # check the input only in self.kneighbors
+
+        # construct CSR matrix representation of the k-NN graph
+        if mode == "connectivity":
+            A_ind = self.kneighbors(X, n_neighbors, return_distance=False)
+            n_queries = A_ind.shape[0]
+            A_data = np.ones(n_queries * n_neighbors)
+
+        elif mode == "distance":
+            A_data, A_ind = self.kneighbors(X, n_neighbors, return_distance=True)
+            A_data = np.ravel(A_data)
+
+        else:
+            raise ValueError(
+                'Unsupported mode, must be one of "connectivity", '
+                f'or "distance" but got "{mode}" instead'
+            )
+
+        n_queries = A_ind.shape[0]
+        n_samples_fit = self.n_samples_fit_
+        n_nonzero = n_queries * n_neighbors
+        A_indptr = np.arange(0, n_nonzero + 1, n_neighbors)
+
+        kneighbors_graph = csr_matrix(
+            (A_data, A_ind.ravel(), A_indptr), shape=(n_queries, n_samples_fit)
+        )
+
+        return kneighbors_graph
+
+
+class RadiusNeighborsMixin:
+    """Mixin for radius-based neighbors searches."""
+
+    def _radius_neighbors_reduce_func(self, dist, start, radius, return_distance):
+        """Reduce a chunk of distances to the nearest neighbors.
+
+        Callback to :func:`sklearn.metrics.pairwise.pairwise_distances_chunked`
+
+        Parameters
+        ----------
+        dist : ndarray of shape (n_samples_chunk, n_samples)
+            The distance matrix.
+
+        start : int
+            The index in X which the first row of dist corresponds to.
+
+        radius : float
+            The radius considered when making the nearest neighbors search.
+
+        return_distance : bool
+            Whether or not to return the distances.
+
+        Returns
+        -------
+        dist : list of ndarray of shape (n_samples_chunk,)
+            Returned only if `return_distance=True`.
+
+        neigh : list of ndarray of shape (n_samples_chunk,)
+            The neighbors indices.
+        """
+        neigh_ind = [np.where(d <= radius)[0] for d in dist]
+
+        if return_distance:
+            if self.effective_metric_ == "euclidean":
+                dist = [np.sqrt(d[neigh_ind[i]]) for i, d in enumerate(dist)]
+            else:
+                dist = [d[neigh_ind[i]] for i, d in enumerate(dist)]
+            results = dist, neigh_ind
+        else:
+            results = neigh_ind
+        return results
+
+    def radius_neighbors(
+        self, X=None, radius=None, return_distance=True, sort_results=False
+    ):
+        """Find the neighbors within a given radius of a point or points.
+
+        Return the indices and distances of each point from the dataset
+        lying in a ball with size ``radius`` around the points of the query
+        array. Points lying on the boundary are included in the results.
+
+        The result points are *not* necessarily sorted by distance to their
+        query point.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of (n_samples, n_features), default=None
+            The query point or points.
+            If not provided, neighbors of each indexed point are returned.
+            In this case, the query point is not considered its own neighbor.
+
+        radius : float, default=None
+            Limiting distance of neighbors to return. The default is the value
+            passed to the constructor.
+
+        return_distance : bool, default=True
+            Whether or not to return the distances.
+
+        sort_results : bool, default=False
+            If True, the distances and indices will be sorted by increasing
+            distances before being returned. If False, the results may not
+            be sorted. If `return_distance=False`, setting `sort_results=True`
+            will result in an error.
+
+            .. versionadded:: 0.22
+
+        Returns
+        -------
+        neigh_dist : ndarray of shape (n_samples,) of arrays
+            Array representing the distances to each point, only present if
+            `return_distance=True`. The distance values are computed according
+            to the ``metric`` constructor parameter.
+
+        neigh_ind : ndarray of shape (n_samples,) of arrays
+            An array of arrays of indices of the approximate nearest points
+            from the population matrix that lie within a ball of size
+            ``radius`` around the query points.
+
+        Notes
+        -----
+        Because the number of neighbors of each point is not necessarily
+        equal, the results for multiple query points cannot be fit in a
+        standard data array.
+        For efficiency, `radius_neighbors` returns arrays of objects, where
+        each object is a 1D array of indices or distances.
+
+        Examples
+        --------
+        In the following example, we construct a NeighborsClassifier
+        class from an array representing our data set and ask who's
+        the closest point to [1, 1, 1]:
+
+        >>> import numpy as np
+        >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]]
+        >>> from sklearn.neighbors import NearestNeighbors
+        >>> neigh = NearestNeighbors(radius=1.6)
+        >>> neigh.fit(samples)
+        NearestNeighbors(radius=1.6)
+        >>> rng = neigh.radius_neighbors([[1., 1., 1.]])
+        >>> print(np.asarray(rng[0][0]))
+        [1.5 0.5]
+        >>> print(np.asarray(rng[1][0]))
+        [1 2]
+
+        The first array returned contains the distances to all points which
+        are closer than 1.6, while the second array returned contains their
+        indices.  In general, multiple points can be queried at the same time.
+        """
+        check_is_fitted(self)
+
+        if sort_results and not return_distance:
+            raise ValueError("return_distance must be True if sort_results is True.")
+
+        ensure_all_finite = "allow-nan" if get_tags(self).input_tags.allow_nan else True
+        query_is_train = X is None
+        if query_is_train:
+            X = self._fit_X
+        else:
+            if self.metric == "precomputed":
+                X = _check_precomputed(X)
+            else:
+                X = validate_data(
+                    self,
+                    X,
+                    ensure_all_finite=ensure_all_finite,
+                    accept_sparse="csr",
+                    reset=False,
+                    order="C",
+                )
+
+        if radius is None:
+            radius = self.radius
+
+        use_pairwise_distances_reductions = (
+            self._fit_method == "brute"
+            and RadiusNeighbors.is_usable_for(
+                X if X is not None else self._fit_X, self._fit_X, self.effective_metric_
+            )
+        )
+
+        if use_pairwise_distances_reductions:
+            results = RadiusNeighbors.compute(
+                X=X,
+                Y=self._fit_X,
+                radius=radius,
+                metric=self.effective_metric_,
+                metric_kwargs=self.effective_metric_params_,
+                strategy="auto",
+                return_distance=return_distance,
+                sort_results=sort_results,
+            )
+
+        elif (
+            self._fit_method == "brute" and self.metric == "precomputed" and issparse(X)
+        ):
+            results = _radius_neighbors_from_graph(
+                X, radius=radius, return_distance=return_distance
+            )
+
+        elif self._fit_method == "brute":
+            # Joblib-based backend, which is used when user-defined callable
+            # are passed for metric.
+
+            # This won't be used in the future once PairwiseDistancesReductions
+            # support:
+            #   - DistanceMetrics which work on supposedly binary data
+            #   - CSR-dense and dense-CSR case if 'euclidean' in metric.
+
+            # for efficiency, use squared euclidean distances
+            if self.effective_metric_ == "euclidean":
+                radius *= radius
+                kwds = {"squared": True}
+            else:
+                kwds = self.effective_metric_params_
+
+            reduce_func = partial(
+                self._radius_neighbors_reduce_func,
+                radius=radius,
+                return_distance=return_distance,
+            )
+
+            chunked_results = pairwise_distances_chunked(
+                X,
+                self._fit_X,
+                reduce_func=reduce_func,
+                metric=self.effective_metric_,
+                n_jobs=self.n_jobs,
+                **kwds,
+            )
+            if return_distance:
+                neigh_dist_chunks, neigh_ind_chunks = zip(*chunked_results)
+                neigh_dist_list = list(itertools.chain.from_iterable(neigh_dist_chunks))
+                neigh_ind_list = list(itertools.chain.from_iterable(neigh_ind_chunks))
+                neigh_dist = _to_object_array(neigh_dist_list)
+                neigh_ind = _to_object_array(neigh_ind_list)
+                results = neigh_dist, neigh_ind
+            else:
+                neigh_ind_list = list(itertools.chain.from_iterable(chunked_results))
+                results = _to_object_array(neigh_ind_list)
+
+            if sort_results:
+                for ii in range(len(neigh_dist)):
+                    order = np.argsort(neigh_dist[ii], kind="mergesort")
+                    neigh_ind[ii] = neigh_ind[ii][order]
+                    neigh_dist[ii] = neigh_dist[ii][order]
+                results = neigh_dist, neigh_ind
+
+        elif self._fit_method in ["ball_tree", "kd_tree"]:
+            if issparse(X):
+                raise ValueError(
+                    "%s does not work with sparse matrices. Densify the data, "
+                    "or set algorithm='brute'" % self._fit_method
+                )
+
+            n_jobs = effective_n_jobs(self.n_jobs)
+            delayed_query = delayed(self._tree.query_radius)
+            chunked_results = Parallel(n_jobs, prefer="threads")(
+                delayed_query(X[s], radius, return_distance, sort_results=sort_results)
+                for s in gen_even_slices(X.shape[0], n_jobs)
+            )
+            if return_distance:
+                neigh_ind, neigh_dist = tuple(zip(*chunked_results))
+                results = np.hstack(neigh_dist), np.hstack(neigh_ind)
+            else:
+                results = np.hstack(chunked_results)
+        else:
+            raise ValueError("internal: _fit_method not recognized")
+
+        if not query_is_train:
+            return results
+        else:
+            # If the query data is the same as the indexed data, we would like
+            # to ignore the first nearest neighbor of every sample, i.e
+            # the sample itself.
+            if return_distance:
+                neigh_dist, neigh_ind = results
+            else:
+                neigh_ind = results
+
+            for ind, ind_neighbor in enumerate(neigh_ind):
+                mask = ind_neighbor != ind
+
+                neigh_ind[ind] = ind_neighbor[mask]
+                if return_distance:
+                    neigh_dist[ind] = neigh_dist[ind][mask]
+
+            if return_distance:
+                return neigh_dist, neigh_ind
+            return neigh_ind
+
+    def radius_neighbors_graph(
+        self, X=None, radius=None, mode="connectivity", sort_results=False
+    ):
+        """Compute the (weighted) graph of Neighbors for points in X.
+
+        Neighborhoods are restricted the points at a distance lower than
+        radius.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features), default=None
+            The query point or points.
+            If not provided, neighbors of each indexed point are returned.
+            In this case, the query point is not considered its own neighbor.
+
+        radius : float, default=None
+            Radius of neighborhoods. The default is the value passed to the
+            constructor.
+
+        mode : {'connectivity', 'distance'}, default='connectivity'
+            Type of returned matrix: 'connectivity' will return the
+            connectivity matrix with ones and zeros, in 'distance' the
+            edges are distances between points, type of distance
+            depends on the selected metric parameter in
+            NearestNeighbors class.
+
+        sort_results : bool, default=False
+            If True, in each row of the result, the non-zero entries will be
+            sorted by increasing distances. If False, the non-zero entries may
+            not be sorted. Only used with mode='distance'.
+
+            .. versionadded:: 0.22
+
+        Returns
+        -------
+        A : sparse-matrix of shape (n_queries, n_samples_fit)
+            `n_samples_fit` is the number of samples in the fitted data.
+            `A[i, j]` gives the weight of the edge connecting `i` to `j`.
+            The matrix is of CSR format.
+
+        See Also
+        --------
+        kneighbors_graph : Compute the (weighted) graph of k-Neighbors for
+            points in X.
+
+        Examples
+        --------
+        >>> X = [[0], [3], [1]]
+        >>> from sklearn.neighbors import NearestNeighbors
+        >>> neigh = NearestNeighbors(radius=1.5)
+        >>> neigh.fit(X)
+        NearestNeighbors(radius=1.5)
+        >>> A = neigh.radius_neighbors_graph(X)
+        >>> A.toarray()
+        array([[1., 0., 1.],
+               [0., 1., 0.],
+               [1., 0., 1.]])
+        """
+        check_is_fitted(self)
+
+        # check the input only in self.radius_neighbors
+
+        if radius is None:
+            radius = self.radius
+
+        # construct CSR matrix representation of the NN graph
+        if mode == "connectivity":
+            A_ind = self.radius_neighbors(X, radius, return_distance=False)
+            A_data = None
+        elif mode == "distance":
+            dist, A_ind = self.radius_neighbors(
+                X, radius, return_distance=True, sort_results=sort_results
+            )
+            A_data = np.concatenate(list(dist))
+        else:
+            raise ValueError(
+                'Unsupported mode, must be one of "connectivity", '
+                f'or "distance" but got "{mode}" instead'
+            )
+
+        n_queries = A_ind.shape[0]
+        n_samples_fit = self.n_samples_fit_
+        n_neighbors = np.array([len(a) for a in A_ind])
+        A_ind = np.concatenate(list(A_ind))
+        if A_data is None:
+            A_data = np.ones(len(A_ind))
+        A_indptr = np.concatenate((np.zeros(1, dtype=int), np.cumsum(n_neighbors)))
+
+        return csr_matrix((A_data, A_ind, A_indptr), shape=(n_queries, n_samples_fit))
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.input_tags.allow_nan = self.metric == "nan_euclidean"
+        return tags
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_binary_tree.pxi.tp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_binary_tree.pxi.tp
new file mode 100644
index 0000000000000000000000000000000000000000..de3bcb0e5d916d3153b7d41c8c975927385b8aac
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_binary_tree.pxi.tp
@@ -0,0 +1,2478 @@
+{{py:
+
+# Generated file: _binary_tree.pxi
+
+implementation_specific_values = [
+    # The values are arranged as follows:
+    #
+    #       name_suffix, INPUT_DTYPE_t, INPUT_DTYPE, NPY_TYPE
+    #
+    ('64', 'float64_t', 'np.float64', 'cnp.NPY_DOUBLE'),
+    ('32', 'float32_t', 'np.float32', 'cnp.NPY_FLOAT')
+]
+
+# KD Tree and Ball Tree
+# =====================
+#
+# _binary_tree.pxi is generated and is then literally Cython included in
+# ball_tree.pyx and kd_tree.pyx. See ball_tree.pyx.tp and kd_tree.pyx.tp.
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+}}
+
+
+# KD Tree and Ball Tree
+# =====================
+#
+# The routines here are the core algorithms of the KDTree and BallTree
+# structures.  If Cython supported polymorphism, we would be able to
+# create a subclass and derive KDTree and BallTree from it.  Because
+# polymorphism is not an option, we use this single BinaryTree class
+# as a literal include to avoid duplicating the entire file.
+#
+# A series of functions are implemented in kd_tree.pyx and ball_tree.pyx
+# which use the information here to calculate the lower and upper bounds
+# between a node and a point, and between two nodes.  These functions are
+# used here, and are all that are needed to differentiate between the two
+# tree types.
+#
+# Description of Binary Tree Algorithms
+# -------------------------------------
+# A binary tree can be thought of as a collection of nodes.  The top node
+# contains all the points.  The next level consists of two nodes with half
+# the points in each, and this continues recursively.  Each node contains
+# metadata which allow fast computation of distance bounds: in the case of
+# a ball tree, the metadata is a center and a radius.  In the case of a
+# KD tree, the metadata is the minimum and maximum bound along each dimension.
+#
+# In a typical KD Tree or Ball Tree implementation, the nodes are implemented
+# as dynamically allocated structures with pointers linking them.  Here we
+# take a different approach, storing all relevant data in a set of arrays
+# so that the entire tree object can be saved in a pickle file. For efficiency,
+# the data can be stored in such a way that explicit pointers are not
+# necessary: for node data stored at index i, the two child nodes are at
+# index (2 * i + 1) and (2 * i + 2); the parent node is (i - 1) // 2
+# (where // indicates integer division).
+#
+# The data arrays used here are as follows:
+#   data : the [n_samples x n_features] array of data from which the tree
+#          is built
+#   idx_array : the length n_samples array used to keep track of the indices
+#          of data within each node.  Each node has values idx_start and
+#          idx_end: the points within the node are given by (using numpy
+#          syntax) data[idx_array[idx_start:idx_end]].
+#   node_data : the length n_nodes array of structures which store the node
+#          indices, node radii, and leaf information for each node.
+#   node_bounds : the [* x n_nodes x n_features] array containing the node
+#          bound information.  For ball tree, the first dimension is 1, and
+#          each row contains the centroid of the node.  For kd tree, the first
+#          dimension is 2 and the rows for each point contain the arrays of
+#          lower bounds and upper bounds in each direction.
+#
+# The lack of dynamic allocation means the number of nodes must be computed
+# before the building of the tree. This can be done assuming the points are
+# divided equally between child nodes at each step; although this removes
+# some flexibility in tree creation, it ensures a balanced tree and ensures
+# that the number of nodes required can be computed beforehand.  Given a
+# specified leaf_size (the minimum number of points in any node), it is
+# possible to show that a balanced tree will have
+#
+#     n_levels = 1 + max(0, floor(log2((n_samples - 1) / leaf_size)))
+#
+# in order to satisfy
+#
+#     leaf_size <= min(n_points) <= 2 * leaf_size
+#
+# with the exception of the special case where n_samples < leaf_size.
+# for a given number of levels, the number of nodes in the tree is given by
+#
+#     n_nodes = 2 ** n_levels - 1
+#
+# both these results can be straightforwardly shown by induction.  The
+# following code uses these values in the construction of the tree.
+#
+# Distance Metrics
+# ----------------
+# For flexibility, the trees can be built using a variety of distance metrics.
+# The metrics are described in the DistanceMetric class: the standard
+# Euclidean distance is the default, and is inlined to be faster than other
+# metrics.  In addition, each metric defines both a distance and a
+# "reduced distance", which is often faster to compute, and is therefore
+# used in the query architecture whenever possible. (For example, in the
+# case of the standard Euclidean distance, the reduced distance is the
+# squared-distance).
+#
+# Implementation Notes
+# --------------------
+# This implementation uses the common object-oriented approach of having an
+# abstract base class which is extended by the KDTree and BallTree
+# specializations.
+#
+# The BinaryTree "base class" is defined here and then subclassed in the BallTree
+# and KDTree pyx files. These files include implementations of the
+# "abstract" methods.
+
+# Necessary Helper Functions
+# --------------------------
+# These are the names and descriptions of the "abstract" functions which are
+# defined in kd_tree.pyx and ball_tree.pyx:
+
+# cdef int allocate_data(BinaryTree tree, intp_t n_nodes, intp_t n_features):
+#     """Allocate arrays needed for the KD Tree"""
+
+# cdef int init_node(BinaryTree tree, intp_t i_node,
+#                    intp_t idx_start, intp_t idx_end):
+#    """Initialize the node for the dataset stored in tree.data"""
+
+# cdef float64_t min_rdist(BinaryTree tree, intp_t i_node, float64_t* pt):
+#     """Compute the minimum reduced-distance between a point and a node"""
+
+# cdef float64_t min_dist(BinaryTree tree, intp_t i_node, float64_t* pt):
+#     """Compute the minimum distance between a point and a node"""
+
+# cdef float64_t max_rdist(BinaryTree tree, intp_t i_node, float64_t* pt):
+#     """Compute the maximum reduced-distance between a point and a node"""
+
+# cdef float64_t max_dist(BinaryTree tree, intp_t i_node, float64_t* pt):
+#     """Compute the maximum distance between a point and a node"""
+
+# cdef inline int min_max_dist(BinaryTree tree, intp_t i_node, float64_t* pt,
+#                              float64_t* min_dist, float64_t* max_dist):
+#     """Compute the minimum and maximum distance between a point and a node"""
+
+# cdef inline float64_t min_rdist_dual(BinaryTree tree1, intp_t i_node1,
+#                                    BinaryTree tree2, intp_t i_node2):
+#     """Compute the minimum reduced distance between two nodes"""
+
+# cdef inline float64_t min_dist_dual(BinaryTree tree1, intp_t i_node1,
+#                                   BinaryTree tree2, intp_t i_node2):
+#     """Compute the minimum distance between two nodes"""
+
+# cdef inline float64_t max_rdist_dual(BinaryTree tree1, intp_t i_node1,
+#                                    BinaryTree tree2, intp_t i_node2):
+#     """Compute the maximum reduced distance between two nodes"""
+
+# cdef inline float64_t max_dist_dual(BinaryTree tree1, intp_t i_node1,
+#                                   BinaryTree tree2, intp_t i_node2):
+#     """Compute the maximum distance between two nodes"""
+
+cimport numpy as cnp
+from cython cimport floating
+from libc.math cimport fabs, sqrt, exp, cos, pow, log, lgamma
+from libc.math cimport fmin, fmax
+from libc.stdlib cimport calloc, malloc, free
+from libc.string cimport memcpy
+
+import numpy as np
+import warnings
+
+from ..metrics._dist_metrics cimport (
+    DistanceMetric,
+    DistanceMetric64,
+    DistanceMetric32,
+    euclidean_dist64,
+    euclidean_dist32,
+    euclidean_rdist64,
+    euclidean_rdist32,
+    euclidean_dist_to_rdist64,
+    euclidean_dist_to_rdist32,
+)
+
+from ._partition_nodes cimport partition_node_indices
+
+from ..utils import check_array
+from ..utils._typedefs cimport float32_t, float64_t, intp_t
+from ..utils._heap cimport heap_push
+from ..utils._sorting cimport simultaneous_sort as _simultaneous_sort
+
+cnp.import_array()
+
+
+# TODO: use cnp.PyArray_ENABLEFLAGS when Cython>=3.0 is used.
+cdef extern from "numpy/arrayobject.h":
+    void PyArray_ENABLEFLAGS(cnp.ndarray arr, int flags)
+
+
+# some handy constants
+cdef float64_t INF = np.inf
+cdef float64_t NEG_INF = -np.inf
+cdef float64_t PI = np.pi
+cdef float64_t ROOT_2PI = sqrt(2 * PI)
+cdef float64_t LOG_PI = log(PI)
+cdef float64_t LOG_2PI = log(2 * PI)
+
+
+# Some compound datatypes used below:
+cdef struct NodeHeapData_t:
+    float64_t val
+    intp_t i1
+    intp_t i2
+
+# build the corresponding numpy dtype for NodeHeapData
+cdef NodeHeapData_t nhd_tmp
+NodeHeapData = np.asarray((&nhd_tmp)).dtype
+
+cdef struct NodeData_t:
+    intp_t idx_start
+    intp_t idx_end
+    intp_t is_leaf
+    float64_t radius
+
+# build the corresponding numpy dtype for NodeData
+cdef NodeData_t nd_tmp
+NodeData = np.asarray((&nd_tmp)).dtype
+
+
+######################################################################
+# Define doc strings, substituting the appropriate class name using
+# the DOC_DICT variable defined in the pyx files.
+CLASS_DOC = """{BinaryTree} for fast generalized N-point problems
+
+Read more in the :ref:`User Guide `.
+
+Parameters
+----------
+X : array-like of shape (n_samples, n_features)
+    n_samples is the number of points in the data set, and
+    n_features is the dimension of the parameter space.
+    Note: if X is a C-contiguous array of doubles then data will
+    not be copied. Otherwise, an internal copy will be made.
+
+leaf_size : positive int, default=40
+    Number of points at which to switch to brute-force. Changing
+    leaf_size will not affect the results of a query, but can
+    significantly impact the speed of a query and the memory required
+    to store the constructed tree.  The amount of memory needed to
+    store the tree scales as approximately n_samples / leaf_size.
+    For a specified ``leaf_size``, a leaf node is guaranteed to
+    satisfy ``leaf_size <= n_points <= 2 * leaf_size``, except in
+    the case that ``n_samples < leaf_size``.
+
+metric : str or DistanceMetric64 object, default='minkowski'
+    Metric to use for distance computation. Default is "minkowski", which
+    results in the standard Euclidean distance when p = 2.
+    A list of valid metrics for {BinaryTree} is given by the attribute
+    `valid_metrics`.
+    See the documentation of `scipy.spatial.distance
+    `_ and
+    the metrics listed in :class:`~sklearn.metrics.pairwise.distance_metrics` for
+    more information on any distance metric.
+
+Additional keywords are passed to the distance metric class.
+Note: Callable functions in the metric parameter are NOT supported for KDTree
+and Ball Tree. Function call overhead will result in very poor performance.
+
+Attributes
+----------
+data : memory view
+    The training data
+valid_metrics: list of str
+    List of valid distance metrics.
+
+Examples
+--------
+Query for k-nearest neighbors
+
+    >>> import numpy as np
+    >>> from sklearn.neighbors import {BinaryTree}
+    >>> rng = np.random.RandomState(0)
+    >>> X = rng.random_sample((10, 3))  # 10 points in 3 dimensions
+    >>> tree = {BinaryTree}(X, leaf_size=2)              # doctest: +SKIP
+    >>> dist, ind = tree.query(X[:1], k=3)                # doctest: +SKIP
+    >>> print(ind)  # indices of 3 closest neighbors
+    [0 3 1]
+    >>> print(dist)  # distances to 3 closest neighbors
+    [ 0.          0.19662693  0.29473397]
+
+Pickle and Unpickle a tree.  Note that the state of the tree is saved in the
+pickle operation: the tree needs not be rebuilt upon unpickling.
+
+    >>> import numpy as np
+    >>> import pickle
+    >>> rng = np.random.RandomState(0)
+    >>> X = rng.random_sample((10, 3))  # 10 points in 3 dimensions
+    >>> tree = {BinaryTree}(X, leaf_size=2)        # doctest: +SKIP
+    >>> s = pickle.dumps(tree)                     # doctest: +SKIP
+    >>> tree_copy = pickle.loads(s)                # doctest: +SKIP
+    >>> dist, ind = tree_copy.query(X[:1], k=3)     # doctest: +SKIP
+    >>> print(ind)  # indices of 3 closest neighbors
+    [0 3 1]
+    >>> print(dist)  # distances to 3 closest neighbors
+    [ 0.          0.19662693  0.29473397]
+
+Query for neighbors within a given radius
+
+    >>> import numpy as np
+    >>> rng = np.random.RandomState(0)
+    >>> X = rng.random_sample((10, 3))  # 10 points in 3 dimensions
+    >>> tree = {BinaryTree}(X, leaf_size=2)     # doctest: +SKIP
+    >>> print(tree.query_radius(X[:1], r=0.3, count_only=True))
+    3
+    >>> ind = tree.query_radius(X[:1], r=0.3)  # doctest: +SKIP
+    >>> print(ind)  # indices of neighbors within distance 0.3
+    [3 0 1]
+
+
+Compute a gaussian kernel density estimate:
+
+    >>> import numpy as np
+    >>> rng = np.random.RandomState(42)
+    >>> X = rng.random_sample((100, 3))
+    >>> tree = {BinaryTree}(X)                # doctest: +SKIP
+    >>> tree.kernel_density(X[:3], h=0.1, kernel='gaussian')
+    array([ 6.94114649,  7.83281226,  7.2071716 ])
+
+Compute a two-point auto-correlation function
+
+    >>> import numpy as np
+    >>> rng = np.random.RandomState(0)
+    >>> X = rng.random_sample((30, 3))
+    >>> r = np.linspace(0, 1, 5)
+    >>> tree = {BinaryTree}(X)                # doctest: +SKIP
+    >>> tree.two_point_correlation(X, r)
+    array([ 30,  62, 278, 580, 820])
+
+"""
+
+
+######################################################################
+# Utility functions
+cdef float64_t logaddexp(float64_t x1, float64_t x2):
+    """logaddexp(x1, x2) -> log(exp(x1) + exp(x2))"""
+    cdef float64_t a = fmax(x1, x2)
+    if a == NEG_INF:
+        return NEG_INF
+    else:
+        return a + log(exp(x1 - a) + exp(x2 - a))
+
+cdef float64_t logsubexp(float64_t x1, float64_t x2):
+    """logsubexp(x1, x2) -> log(exp(x1) - exp(x2))"""
+    if x1 <= x2:
+        return NEG_INF
+    else:
+        return x1 + log(1 - exp(x2 - x1))
+
+
+######################################################################
+# Kernel functions
+#
+# Note: Kernels assume dist is non-negative and h is positive
+#       All kernel functions are normalized such that K(0, h) = 1.
+#       The fully normalized kernel is:
+#         K = exp[kernel_norm(h, d, kernel) + compute_kernel(dist, h, kernel)]
+#       The code only works with non-negative kernels: i.e. K(d, h) >= 0
+#       for all valid d and h.  Note that for precision, the log of both
+#       the kernel and kernel norm is returned.
+cdef enum KernelType:
+    GAUSSIAN_KERNEL = 1
+    TOPHAT_KERNEL = 2
+    EPANECHNIKOV_KERNEL = 3
+    EXPONENTIAL_KERNEL = 4
+    LINEAR_KERNEL = 5
+    COSINE_KERNEL = 6
+
+
+cdef inline float64_t log_gaussian_kernel(float64_t dist, float64_t h):
+    """log of the gaussian kernel for bandwidth h (unnormalized)"""
+    return -0.5 * (dist * dist) / (h * h)
+
+
+cdef inline float64_t log_tophat_kernel(float64_t dist, float64_t h):
+    """log of the tophat kernel for bandwidth h (unnormalized)"""
+    if dist < h:
+        return 0.0
+    else:
+        return NEG_INF
+
+
+cdef inline float64_t log_epanechnikov_kernel(float64_t dist, float64_t h):
+    """log of the epanechnikov kernel for bandwidth h (unnormalized)"""
+    if dist < h:
+        return log(1.0 - (dist * dist) / (h * h))
+    else:
+        return NEG_INF
+
+
+cdef inline float64_t log_exponential_kernel(float64_t dist, float64_t h):
+    """log of the exponential kernel for bandwidth h (unnormalized)"""
+    return -dist / h
+
+
+cdef inline float64_t log_linear_kernel(float64_t dist, float64_t h):
+    """log of the linear kernel for bandwidth h (unnormalized)"""
+    if dist < h:
+        return log(1 - dist / h)
+    else:
+        return NEG_INF
+
+
+cdef inline float64_t log_cosine_kernel(float64_t dist, float64_t h):
+    """log of the cosine kernel for bandwidth h (unnormalized)"""
+    if dist < h:
+        return log(cos(0.5 * PI * dist / h))
+    else:
+        return NEG_INF
+
+
+cdef inline float64_t compute_log_kernel(float64_t dist, float64_t h,
+                                         KernelType kernel):
+    """Given a KernelType enumeration, compute the appropriate log-kernel"""
+    if kernel == GAUSSIAN_KERNEL:
+        return log_gaussian_kernel(dist, h)
+    elif kernel == TOPHAT_KERNEL:
+        return log_tophat_kernel(dist, h)
+    elif kernel == EPANECHNIKOV_KERNEL:
+        return log_epanechnikov_kernel(dist, h)
+    elif kernel == EXPONENTIAL_KERNEL:
+        return log_exponential_kernel(dist, h)
+    elif kernel == LINEAR_KERNEL:
+        return log_linear_kernel(dist, h)
+    elif kernel == COSINE_KERNEL:
+        return log_cosine_kernel(dist, h)
+
+
+# ------------------------------------------------------------
+# Kernel norms are defined via the volume element V_n
+# and surface element S_(n-1) of an n-sphere.
+cdef float64_t logVn(intp_t n):
+    """V_n = pi^(n/2) / gamma(n/2 - 1)"""
+    return 0.5 * n * LOG_PI - lgamma(0.5 * n + 1)
+
+
+cdef float64_t logSn(intp_t n):
+    """V_(n+1) = int_0^1 S_n r^n dr"""
+    return LOG_2PI + logVn(n - 1)
+
+
+cdef float64_t _log_kernel_norm(float64_t h, intp_t d,
+                                KernelType kernel) except -1:
+    """Given a KernelType enumeration, compute the kernel normalization.
+
+    h is the bandwidth, d is the dimension.
+    """
+    cdef float64_t tmp, factor = 0
+    cdef intp_t k
+    if kernel == GAUSSIAN_KERNEL:
+        factor = 0.5 * d * LOG_2PI
+    elif kernel == TOPHAT_KERNEL:
+        factor = logVn(d)
+    elif kernel == EPANECHNIKOV_KERNEL:
+        factor = logVn(d) + log(2. / (d + 2.))
+    elif kernel == EXPONENTIAL_KERNEL:
+        factor = logSn(d - 1) + lgamma(d)
+    elif kernel == LINEAR_KERNEL:
+        factor = logVn(d) - log(d + 1.)
+    elif kernel == COSINE_KERNEL:
+        # this is derived from a chain rule integration
+        factor = 0
+        tmp = 2. / PI
+        for k in range(1, d + 1, 2):
+            factor += tmp
+            tmp *= -(d - k) * (d - k - 1) * (2. / PI) ** 2
+        factor = log(factor) + logSn(d - 1)
+    else:
+        raise ValueError("Kernel code not recognized")
+    return -factor - d * log(h)
+
+
+def kernel_norm(h, d, kernel, return_log=False):
+    """Given a string specification of a kernel, compute the normalization.
+
+    Parameters
+    ----------
+    h : float
+        The bandwidth of the kernel.
+    d : int
+        The dimension of the space in which the kernel norm is computed.
+    kernel : str
+        The kernel identifier.  Must be one of
+        ['gaussian'|'tophat'|'epanechnikov'|
+         'exponential'|'linear'|'cosine']
+    return_log : bool, default=False
+        If True, return the log of the kernel norm.  Otherwise, return the
+        kernel norm.
+    Returns
+    -------
+    knorm or log_knorm : float
+        the kernel norm or logarithm of the kernel norm.
+    """
+    if kernel == 'gaussian':
+        result = _log_kernel_norm(h, d, GAUSSIAN_KERNEL)
+    elif kernel == 'tophat':
+        result = _log_kernel_norm(h, d, TOPHAT_KERNEL)
+    elif kernel == 'epanechnikov':
+        result = _log_kernel_norm(h, d, EPANECHNIKOV_KERNEL)
+    elif kernel == 'exponential':
+        result = _log_kernel_norm(h, d, EXPONENTIAL_KERNEL)
+    elif kernel == 'linear':
+        result = _log_kernel_norm(h, d, LINEAR_KERNEL)
+    elif kernel == 'cosine':
+        result = _log_kernel_norm(h, d, COSINE_KERNEL)
+    else:
+        raise ValueError('kernel not recognized')
+
+    if return_log:
+        return result
+    else:
+        return np.exp(result)
+
+{{for name_suffix, INPUT_DTYPE_t, INPUT_DTYPE, NPY_TYPE in implementation_specific_values}}
+
+cdef class NeighborsHeap{{name_suffix}}:
+    """A max-heap structure to keep track of distances/indices of neighbors
+
+    This implements an efficient pre-allocated set of fixed-size heaps
+    for chasing neighbors, holding both an index and a distance.
+    When any row of the heap is full, adding an additional point will push
+    the furthest point off the heap.
+
+    Parameters
+    ----------
+    n_pts : int
+        the number of heaps to use
+    n_nbrs : int
+        the size of each heap.
+    """
+    cdef {{INPUT_DTYPE_t}}[:, ::1] distances
+    cdef intp_t[:, ::1] indices
+
+    def __cinit__(self):
+        # One-element arrays are used as placeholders to prevent
+        # any problem due to potential access to those attributes
+        # (e.g. assigning to NULL or a to value in another segment).
+        self.distances = np.zeros((1, 1), dtype={{INPUT_DTYPE}}, order='C')
+        self.indices = np.zeros((1, 1), dtype=np.intp, order='C')
+
+    def __init__(self, n_pts, n_nbrs):
+        self.distances = np.full(
+            (n_pts, n_nbrs), np.inf, dtype={{INPUT_DTYPE}}, order='C'
+        )
+        self.indices = np.zeros((n_pts, n_nbrs), dtype=np.intp, order='C')
+
+    def get_arrays(self, sort=True):
+        """Get the arrays of distances and indices within the heap.
+
+        If sort=True, then simultaneously sort the indices and distances,
+        so the closer points are listed first.
+        """
+        if sort:
+            self._sort()
+        return self.distances.base, self.indices.base
+
+    cdef inline float64_t largest(self, intp_t row) except -1 nogil:
+        """Return the largest distance in the given row"""
+        return self.distances[row, 0]
+
+    def push(self, intp_t row, float64_t val, intp_t i_val):
+        return self._push(row, val, i_val)
+
+    cdef int _push(self, intp_t row, float64_t val,
+                   intp_t i_val) except -1 nogil:
+        """push (val, i_val) into the given row"""
+        return heap_push(
+            values=&self.distances[row, 0],
+            indices=&self.indices[row, 0],
+            size=self.distances.shape[1],
+            val=val,
+            val_idx=i_val,
+        )
+
+    cdef int _sort(self) except -1:
+        """simultaneously sort the distances and indices"""
+        cdef intp_t row
+        for row in range(self.distances.shape[0]):
+            _simultaneous_sort(
+                dist=&self.distances[row, 0],
+                idx=&self.indices[row, 0],
+                size=self.distances.shape[1],
+            )
+        return 0
+
+{{endfor}}
+
+#------------------------------------------------------------
+# find_node_split_dim:
+#  this computes the equivalent of
+#  j_max = np.argmax(np.max(data, 0) - np.min(data, 0))
+cdef intp_t find_node_split_dim(const floating* data,
+                                 const intp_t* node_indices,
+                                 intp_t n_features,
+                                 intp_t n_points) except -1:
+    """Find the dimension with the largest spread.
+
+    Parameters
+    ----------
+    data : double pointer
+        Pointer to a 2D array of the training data, of shape [N, n_features].
+        N must be greater than any of the values in node_indices.
+    node_indices : int pointer
+        Pointer to a 1D array of length n_points.  This lists the indices of
+        each of the points within the current node.
+
+    Returns
+    -------
+    i_max : int
+        The index of the feature (dimension) within the node that has the
+        largest spread.
+
+    Notes
+    -----
+    In numpy, this operation is equivalent to
+
+    def find_node_split_dim(data, node_indices):
+        return np.argmax(data[node_indices].max(0) - data[node_indices].min(0))
+
+    The cython version is much more efficient in both computation and memory.
+    """
+    cdef float64_t min_val, max_val, val, spread, max_spread
+    cdef intp_t i, j, j_max
+
+    j_max = 0
+    max_spread = 0
+
+    for j in range(n_features):
+        max_val = data[node_indices[0] * n_features + j]
+        min_val = max_val
+        for i in range(1, n_points):
+            val = data[node_indices[i] * n_features + j]
+            max_val = fmax(max_val, val)
+            min_val = fmin(min_val, val)
+        spread = max_val - min_val
+        if spread > max_spread:
+            max_spread = spread
+            j_max = j
+    return j_max
+
+
+######################################################################
+# NodeHeap : min-heap used to keep track of nodes during
+#            breadth-first query
+cdef inline void swap_nodes(NodeHeapData_t* arr, intp_t i1, intp_t i2):
+    cdef NodeHeapData_t tmp = arr[i1]
+    arr[i1] = arr[i2]
+    arr[i2] = tmp
+
+
+cdef class NodeHeap:
+    """NodeHeap
+
+    This is a min-heap implementation for keeping track of nodes
+    during a breadth-first search.  Unlike the NeighborsHeap above,
+    the NodeHeap does not have a fixed size and must be able to grow
+    as elements are added.
+
+    Internally, the data is stored in a simple binary heap which meets
+    the min heap condition:
+
+        heap[i].val < min(heap[2 * i + 1].val, heap[2 * i + 2].val)
+    """
+    cdef NodeHeapData_t[:] data
+    cdef intp_t n
+
+    def __cinit__(self):
+        # A one-elements array is used as a placeholder to prevent
+        # any problem due to potential access to this attribute
+        # (e.g. assigning to NULL or a to value in another segment).
+        self.data = np.zeros(1, dtype=NodeHeapData, order='C')
+
+    def __init__(self, size_guess=100):
+        size_guess = max(size_guess, 1)  # need space for at least one item
+        self.data = np.zeros(size_guess, dtype=NodeHeapData, order='C')
+        self.n = size_guess
+        self.clear()
+
+    cdef int resize(self, intp_t new_size) except -1:
+        """Resize the heap to be either larger or smaller"""
+        cdef:
+            NodeHeapData_t *data_ptr
+            NodeHeapData_t *new_data_ptr
+            intp_t i
+            intp_t size = self.data.shape[0]
+            NodeHeapData_t[:] new_data = np.zeros(
+                new_size,
+                dtype=NodeHeapData,
+            )
+
+        if size > 0 and new_size > 0:
+            data_ptr = &self.data[0]
+            new_data_ptr = &new_data[0]
+            for i in range(min(size, new_size)):
+                new_data_ptr[i] = data_ptr[i]
+
+        if new_size < size:
+            self.n = new_size
+
+        self.data = new_data
+        return 0
+
+    cdef int push(self, NodeHeapData_t data) except -1:
+        """Push a new item onto the heap"""
+        cdef intp_t i, i_parent
+        cdef NodeHeapData_t* data_arr
+        self.n += 1
+        if self.n > self.data.shape[0]:
+            self.resize(2 * self.n)
+
+        # put the new element at the end,
+        # and then perform swaps until the heap is in order
+        data_arr = &self.data[0]
+        i = self.n - 1
+        data_arr[i] = data
+
+        while i > 0:
+            i_parent = (i - 1) // 2
+            if data_arr[i_parent].val <= data_arr[i].val:
+                break
+            else:
+                swap_nodes(data_arr, i, i_parent)
+                i = i_parent
+        return 0
+
+    cdef NodeHeapData_t peek(self):
+        """Peek at the root of the heap, without removing it"""
+        return self.data[0]
+
+    cdef NodeHeapData_t pop(self):
+        """Remove the root of the heap, and update the remaining nodes"""
+        if self.n == 0:
+            raise ValueError('cannot pop on empty heap')
+
+        cdef intp_t i, i_child1, i_child2, i_swap
+        cdef NodeHeapData_t* data_arr = &self.data[0]
+        cdef NodeHeapData_t popped_element = data_arr[0]
+
+        # pop off the first element, move the last element to the front,
+        # and then perform swaps until the heap is back in order
+        data_arr[0] = data_arr[self.n - 1]
+        self.n -= 1
+
+        i = 0
+
+        while (i < self.n):
+            i_child1 = 2 * i + 1
+            i_child2 = 2 * i + 2
+            i_swap = 0
+
+            if i_child2 < self.n:
+                if data_arr[i_child1].val <= data_arr[i_child2].val:
+                    i_swap = i_child1
+                else:
+                    i_swap = i_child2
+            elif i_child1 < self.n:
+                i_swap = i_child1
+            else:
+                break
+
+            if (i_swap > 0) and (data_arr[i_swap].val <= data_arr[i].val):
+                swap_nodes(data_arr, i, i_swap)
+                i = i_swap
+            else:
+                break
+
+        return popped_element
+
+    cdef void clear(self):
+        """Clear the heap"""
+        self.n = 0
+
+
+######################################################################
+# newObj function
+#  this is a helper function for pickling
+def newObj(obj):
+    return obj.__new__(obj)
+
+
+{{for name_suffix, INPUT_DTYPE_t, INPUT_DTYPE, NPY_TYPE in implementation_specific_values}}
+
+######################################################################
+# define the reverse mapping of VALID_METRICS{{name_suffix}}
+from sklearn.metrics._dist_metrics import get_valid_metric_ids
+VALID_METRIC_IDS{{name_suffix}} = get_valid_metric_ids(VALID_METRICS{{name_suffix}})
+
+
+######################################################################
+# Binary Tree class
+cdef class BinaryTree{{name_suffix}}:
+
+    cdef readonly const {{INPUT_DTYPE_t}}[:, ::1] data
+    cdef readonly const {{INPUT_DTYPE_t}}[::1] sample_weight
+    cdef public float64_t sum_weight
+
+    # TODO: idx_array and node_bounds must not be const, but this change needs
+    # to happen in a way which preserves pickling
+    # See also: https://github.com/cython/cython/issues/5639
+    cdef public const intp_t[::1] idx_array
+    cdef public const NodeData_t[::1] node_data
+    cdef public const {{INPUT_DTYPE_t}}[:, :, ::1] node_bounds
+
+    cdef intp_t leaf_size
+    cdef intp_t n_levels
+    cdef intp_t n_nodes
+
+    cdef DistanceMetric{{name_suffix}} dist_metric
+    cdef int euclidean
+
+    # variables to keep track of building & querying stats
+    cdef int n_trims
+    cdef int n_leaves
+    cdef int n_splits
+    cdef int n_calls
+
+    valid_metrics = VALID_METRIC_IDS{{name_suffix}}
+
+    # Use cinit to initialize all arrays to empty: this will prevent memory
+    # errors and seg-faults in rare cases where __init__ is not called
+    # A one-elements array is used as a placeholder to prevent
+    # any problem due to potential access to this attribute
+    # (e.g. assigning to NULL or a to value in another segment).
+    def __cinit__(self):
+        self.data = np.empty((1, 1), dtype={{INPUT_DTYPE}}, order='C')
+        self.sample_weight = np.empty(1, dtype={{INPUT_DTYPE}}, order='C')
+        self.idx_array = np.empty(1, dtype=np.intp, order='C')
+        self.node_data = np.empty(1, dtype=NodeData, order='C')
+        self.node_bounds = np.empty((1, 1, 1), dtype={{INPUT_DTYPE}})
+
+        self.leaf_size = 0
+        self.n_levels = 0
+        self.n_nodes = 0
+
+        self.euclidean = False
+
+        self.n_trims = 0
+        self.n_leaves = 0
+        self.n_splits = 0
+        self.n_calls = 0
+
+    def __init__(self, data,
+                 leaf_size=40, metric='minkowski', sample_weight=None, **kwargs):
+        # validate data
+        self.data = check_array(data, dtype={{INPUT_DTYPE}}, order='C')
+        if self.data.size == 0:
+            raise ValueError("X is an empty array")
+
+        n_samples = self.data.shape[0]
+        n_features = self.data.shape[1]
+
+        if leaf_size < 1:
+            raise ValueError("leaf_size must be greater than or equal to 1")
+        self.leaf_size = leaf_size
+
+        self.dist_metric = DistanceMetric.get_metric(metric, dtype={{INPUT_DTYPE}}, **kwargs)
+        self.euclidean = (self.dist_metric.__class__.__name__
+                          == 'EuclideanDistance{{name_suffix}}')
+
+        metric = self.dist_metric.__class__.__name__
+        if metric not in VALID_METRICS{{name_suffix}}:
+            raise ValueError('metric {metric} is not valid for '
+                             '{BinaryTree}'.format(metric=metric,
+                                                   **DOC_DICT{{name_suffix}}))
+        self.dist_metric._validate_data(self.data)
+
+        # determine number of levels in the tree, and from this
+        # the number of nodes in the tree.  This results in leaf nodes
+        # with numbers of points between leaf_size and 2 * leaf_size
+        self.n_levels = int(
+            np.log2(fmax(1, (n_samples - 1) / self.leaf_size)) + 1)
+        self.n_nodes =  (2 ** self.n_levels) - 1
+
+        # allocate arrays for storage
+        self.idx_array = np.arange(n_samples, dtype=np.intp)
+        self.node_data = np.zeros(self.n_nodes, dtype=NodeData)
+
+        self._update_sample_weight(n_samples, sample_weight)
+
+        # Allocate tree-specific data
+        allocate_data{{name_suffix}}(self, self.n_nodes, n_features)
+        self._recursive_build(
+            node_data=self.node_data.base,
+            i_node=0,
+            idx_start=0,
+            idx_end=n_samples
+        )
+
+    def _update_sample_weight(self, n_samples, sample_weight):
+        if sample_weight is not None:
+            self.sample_weight = np.asarray(
+                sample_weight, dtype={{INPUT_DTYPE}}, order='C')
+            self.sum_weight = np.sum(self.sample_weight)
+        else:
+            self.sample_weight = None
+            self.sum_weight =  n_samples
+
+    def __reduce__(self):
+        """
+        reduce method used for pickling
+        """
+        return (newObj, (type(self),), self.__getstate__())
+
+    def __getstate__(self):
+        """
+        get state for pickling
+        """
+        if self.sample_weight is not None:
+            # pass the numpy array
+            sample_weight = self.sample_weight.base
+        else:
+            # pass None to avoid confusion with the empty place holder
+            # of size 1 from __cinit__
+            sample_weight = None
+        return (self.data.base,
+                self.idx_array.base,
+                self.node_data.base,
+                self.node_bounds.base,
+                int(self.leaf_size),
+                int(self.n_levels),
+                int(self.n_nodes),
+                int(self.n_trims),
+                int(self.n_leaves),
+                int(self.n_splits),
+                int(self.n_calls),
+                self.dist_metric,
+                sample_weight)
+
+    def __setstate__(self, state):
+        """
+        set state for pickling
+        """
+        self.data = state[0]
+        self.idx_array = state[1]
+        self.node_data = state[2]
+        self.node_bounds = state[3]
+        self.leaf_size = state[4]
+        self.n_levels = state[5]
+        self.n_nodes = state[6]
+        self.n_trims = state[7]
+        self.n_leaves = state[8]
+        self.n_splits = state[9]
+        self.n_calls = state[10]
+        self.dist_metric = state[11]
+        sample_weight = state[12]
+
+        self.euclidean = (self.dist_metric.__class__.__name__
+                          == 'EuclideanDistance64')
+        n_samples = self.data.shape[0]
+        self._update_sample_weight(n_samples, sample_weight)
+
+    def get_tree_stats(self):
+        """
+        get_tree_stats()
+
+        Get tree status.
+
+        Returns
+        -------
+        tree_stats: tuple of int
+            (number of trims, number of leaves, number of splits)
+        """
+        return (self.n_trims, self.n_leaves, self.n_splits)
+
+    def reset_n_calls(self):
+        """
+        reset_n_calls()
+
+        Reset number of calls to 0.
+        """
+        self.n_calls = 0
+
+    def get_n_calls(self):
+        """
+        get_n_calls()
+
+        Get number of calls.
+
+        Returns
+        -------
+        n_calls: int
+            number of distance computation calls
+        """
+        return self.n_calls
+
+    def get_arrays(self):
+        """
+        get_arrays()
+
+        Get data and node arrays.
+
+        Returns
+        -------
+        arrays: tuple of array
+            Arrays for storing tree data, index, node data and node bounds.
+        """
+        return (
+            self.data.base,
+            self.idx_array.base,
+            self.node_data.base,
+            self.node_bounds.base,
+        )
+
+    cdef inline float64_t dist(self, const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2,
+                             intp_t size) except -1 nogil:
+        """Compute the distance between arrays x1 and x2"""
+        self.n_calls += 1
+        if self.euclidean:
+            return euclidean_dist{{name_suffix}}(x1, x2, size)
+        else:
+            return self.dist_metric.dist(x1, x2, size)
+
+    cdef inline float64_t rdist(self, const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2,
+                              intp_t size) except -1 nogil:
+        """Compute the reduced distance between arrays x1 and x2.
+
+        The reduced distance, defined for some metrics, is a quantity which
+        is more efficient to compute than the distance, but preserves the
+        relative rankings of the true distance.  For example, the reduced
+        distance for the Euclidean metric is the squared-euclidean distance.
+        """
+        self.n_calls += 1
+        if self.euclidean:
+            return euclidean_rdist{{name_suffix}}(x1, x2, size)
+        else:
+            return self.dist_metric.rdist(x1, x2, size)
+
+    cdef int _recursive_build(self, NodeData_t[::1] node_data, intp_t i_node, intp_t idx_start,
+                              intp_t idx_end) except -1:
+        """Recursively build the tree.
+
+        Parameters
+        ----------
+        i_node : int
+            the node for the current step
+        idx_start, idx_end : int
+            the bounding indices in the idx_array which define the points that
+            belong to this node.
+        """
+        cdef intp_t imax
+        cdef intp_t n_features = self.data.shape[1]
+        cdef intp_t n_points = idx_end - idx_start
+        cdef intp_t n_mid = n_points / 2
+        cdef intp_t* idx_array = &self.idx_array[idx_start]
+        cdef const {{INPUT_DTYPE_t}}* data = &self.data[0, 0]
+
+        # initialize node data
+        init_node{{name_suffix}}(self, node_data, i_node, idx_start, idx_end)
+
+        if 2 * i_node + 1 >= self.n_nodes:
+            node_data[i_node].is_leaf = True
+            if idx_end - idx_start > 2 * self.leaf_size:
+                # this shouldn't happen if our memory allocation is correct
+                # we'll proactively prevent memory errors, but raise a
+                # warning saying we're doing so.
+                import warnings
+                warnings.warn("Internal: memory layout is flawed: "
+                              "not enough nodes allocated")
+
+        elif idx_end - idx_start < 2:
+            # again, this shouldn't happen if our memory allocation
+            # is correct.  Raise a warning.
+            import warnings
+            warnings.warn("Internal: memory layout is flawed: "
+                          "too many nodes allocated")
+            node_data[i_node].is_leaf = True
+
+        else:
+            # split node and recursively construct child nodes.
+            node_data[i_node].is_leaf = False
+            i_max = find_node_split_dim(data, idx_array,
+                                        n_features, n_points)
+            partition_node_indices(data, idx_array, i_max, n_mid,
+                                   n_features, n_points)
+            self._recursive_build(node_data, 2 * i_node + 1,
+                                  idx_start, idx_start + n_mid)
+            self._recursive_build(node_data, 2 * i_node + 2,
+                                  idx_start + n_mid, idx_end)
+
+    def query(self, X, k=1, return_distance=True,
+              dualtree=False, breadth_first=False,
+              sort_results=True):
+        """
+        query(X, k=1, return_distance=True,
+              dualtree=False, breadth_first=False)
+
+        query the tree for the k nearest neighbors
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            An array of points to query
+        k : int, default=1
+            The number of nearest neighbors to return
+        return_distance : bool, default=True
+            if True, return a tuple (d, i) of distances and indices
+            if False, return array i
+        dualtree : bool, default=False
+            if True, use the dual tree formalism for the query: a tree is
+            built for the query points, and the pair of trees is used to
+            efficiently search this space.  This can lead to better
+            performance as the number of points grows large.
+        breadth_first : bool, default=False
+            if True, then query the nodes in a breadth-first manner.
+            Otherwise, query the nodes in a depth-first manner.
+        sort_results : bool, default=True
+            if True, then distances and indices of each point are sorted
+            on return, so that the first column contains the closest points.
+            Otherwise, neighbors are returned in an arbitrary order.
+
+        Returns
+        -------
+        i    : if return_distance == False
+        (d,i) : if return_distance == True
+
+        d : ndarray of shape X.shape[:-1] + (k,), dtype=double
+            Each entry gives the list of distances to the neighbors of the
+            corresponding point.
+
+        i : ndarray of shape X.shape[:-1] + (k,), dtype=int
+            Each entry gives the list of indices of neighbors of the
+            corresponding point.
+        """
+        # XXX: we should allow X to be a pre-built tree.
+        X = check_array(X, dtype={{INPUT_DTYPE}}, order='C')
+
+        if X.shape[X.ndim - 1] != self.data.shape[1]:
+            raise ValueError("query data dimension must "
+                             "match training data dimension")
+
+        if self.data.shape[0] < k:
+            raise ValueError("k must be less than or equal "
+                             "to the number of training points")
+
+        # flatten X, and save original shape information
+        np_Xarr = X.reshape((-1, self.data.shape[1]))
+        cdef const {{INPUT_DTYPE_t}}[:, ::1] Xarr = np_Xarr
+        cdef float64_t reduced_dist_LB
+        cdef intp_t i
+        cdef const {{INPUT_DTYPE_t}}* pt
+
+        # initialize heap for neighbors
+        cdef NeighborsHeap{{name_suffix}} heap = NeighborsHeap{{name_suffix}}(Xarr.shape[0], k)
+
+        # node heap for breadth-first queries
+        cdef NodeHeap nodeheap
+        if breadth_first:
+            nodeheap = NodeHeap(self.data.shape[0] // self.leaf_size)
+
+        # bounds is needed for the dual tree algorithm
+        cdef float64_t[::1] bounds
+
+        self.n_trims = 0
+        self.n_leaves = 0
+        self.n_splits = 0
+
+        if dualtree:
+            other = self.__class__(np_Xarr, metric=self.dist_metric,
+                                   leaf_size=self.leaf_size)
+            if breadth_first:
+                self._query_dual_breadthfirst(other, heap, nodeheap)
+            else:
+                reduced_dist_LB = min_rdist_dual{{name_suffix}}(self, 0, other, 0)
+                bounds = np.full(other.node_data.shape[0], np.inf)
+                self._query_dual_depthfirst(0, other, 0, bounds,
+                                            heap, reduced_dist_LB)
+
+        else:
+            pt = &Xarr[0, 0]
+            if breadth_first:
+                for i in range(Xarr.shape[0]):
+                    self._query_single_breadthfirst(pt, i, heap, nodeheap)
+                    pt += Xarr.shape[1]
+            else:
+                with nogil:
+                    for i in range(Xarr.shape[0]):
+                        reduced_dist_LB = min_rdist{{name_suffix}}(self, 0, pt)
+                        self._query_single_depthfirst(0, pt, i, heap,
+                                                      reduced_dist_LB)
+                        pt += Xarr.shape[1]
+
+        distances, indices = heap.get_arrays(sort=sort_results)
+        distances = self.dist_metric.rdist_to_dist(distances)
+
+        # deflatten results
+        if return_distance:
+            return (distances.reshape(X.shape[:X.ndim - 1] + (k,)),
+                    indices.reshape(X.shape[:X.ndim - 1] + (k,)))
+        else:
+            return indices.reshape(X.shape[:X.ndim - 1] + (k,))
+
+    def query_radius(self, X, r, int return_distance=False,
+                     int count_only=False, int sort_results=False):
+        """
+        query_radius(X, r, return_distance=False,
+        count_only=False, sort_results=False)
+
+        query the tree for neighbors within a radius r
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            An array of points to query
+        r : distance within which neighbors are returned
+            r can be a single value, or an array of values of shape
+            x.shape[:-1] if different radii are desired for each point.
+        return_distance : bool, default=False
+            if True,  return distances to neighbors of each point
+            if False, return only neighbors
+            Note that unlike the query() method, setting return_distance=True
+            here adds to the computation time.  Not all distances need to be
+            calculated explicitly for return_distance=False.  Results are
+            not sorted by default: see ``sort_results`` keyword.
+        count_only : bool, default=False
+            if True,  return only the count of points within distance r
+            if False, return the indices of all points within distance r
+            If return_distance==True, setting count_only=True will
+            result in an error.
+        sort_results : bool, default=False
+            if True, the distances and indices will be sorted before being
+            returned.  If False, the results will not be sorted.  If
+            return_distance == False, setting sort_results = True will
+            result in an error.
+
+        Returns
+        -------
+        count       : if count_only == True
+        ind         : if count_only == False and return_distance == False
+        (ind, dist) : if count_only == False and return_distance == True
+
+        count : ndarray of shape X.shape[:-1], dtype=int
+            Each entry gives the number of neighbors within a distance r of the
+            corresponding point.
+
+        ind : ndarray of shape X.shape[:-1], dtype=object
+            Each element is a numpy integer array listing the indices of
+            neighbors of the corresponding point.  Note that unlike
+            the results of a k-neighbors query, the returned neighbors
+            are not sorted by distance by default.
+
+        dist : ndarray of shape X.shape[:-1], dtype=object
+            Each element is a numpy double array listing the distances
+            corresponding to indices in i.
+        """
+        if count_only and return_distance:
+            raise ValueError("count_only and return_distance "
+                             "cannot both be true")
+
+        if sort_results and not return_distance:
+            raise ValueError("return_distance must be True "
+                             "if sort_results is True")
+
+        cdef intp_t i, count_i = 0
+        cdef intp_t n_features = self.data.shape[1]
+        cdef {{INPUT_DTYPE_t}}[::1] dist_arr_i
+        cdef intp_t[::1] idx_arr_i, counts
+        cdef const {{INPUT_DTYPE_t}}* pt
+        cdef intp_t** indices = NULL
+        cdef {{INPUT_DTYPE_t}}** distances = NULL
+
+        # validate X and prepare for query
+        X = check_array(X, dtype={{INPUT_DTYPE}}, order='C')
+
+        if X.shape[X.ndim - 1] != self.data.shape[1]:
+            raise ValueError("query data dimension must "
+                             "match training data dimension")
+
+        cdef const {{INPUT_DTYPE_t}}[:, ::1] Xarr = X.reshape((-1, self.data.shape[1]))
+
+        # prepare r for query
+        r = np.asarray(r, dtype=np.float64, order='C')
+        r = np.atleast_1d(r)
+        if r.shape == (1,):
+            r = np.full(X.shape[:X.ndim - 1], r[0], dtype=np.float64)
+        else:
+            if r.shape != X.shape[:X.ndim - 1]:
+                raise ValueError("r must be broadcastable to X.shape")
+
+        rarr_np = r.reshape(-1)  # store explicitly to keep in scope
+        cdef float64_t[::1] rarr = rarr_np
+
+        if not count_only:
+            indices = calloc(Xarr.shape[0], sizeof(intp_t*))
+            if indices == NULL:
+                raise MemoryError()
+            if return_distance:
+                distances = <{{INPUT_DTYPE_t}}**>calloc(Xarr.shape[0], sizeof({{INPUT_DTYPE_t}}*))
+                if distances == NULL:
+                    free(indices)
+                    raise MemoryError()
+
+        np_idx_arr = np.zeros(self.data.shape[0], dtype=np.intp)
+        idx_arr_i = np_idx_arr
+
+        np_dist_arr = np.zeros(self.data.shape[0], dtype={{INPUT_DTYPE}})
+        dist_arr_i = np_dist_arr
+
+        counts_arr = np.zeros(Xarr.shape[0], dtype=np.intp)
+        counts = counts_arr
+
+        pt = &Xarr[0, 0]
+        memory_error = False
+        with nogil:
+            for i in range(Xarr.shape[0]):
+                counts[i] = self._query_radius_single(0, pt, rarr[i],
+                                                      &idx_arr_i[0],
+                                                      &dist_arr_i[0],
+                                                      0, count_only,
+                                                      return_distance)
+                pt += n_features
+
+                if count_only:
+                    continue
+
+                if sort_results:
+                    _simultaneous_sort(&dist_arr_i[0], &idx_arr_i[0],
+                                       counts[i])
+
+                # equivalent to: indices[i] = np_idx_arr[:counts[i]].copy()
+                indices[i] = malloc(counts[i] * sizeof(intp_t))
+                if indices[i] == NULL:
+                    memory_error = True
+                    break
+                memcpy(indices[i], &idx_arr_i[0], counts[i] * sizeof(intp_t))
+
+                if return_distance:
+                    # equivalent to: distances[i] = np_dist_arr[:counts[i]].copy()
+                    distances[i] = <{{INPUT_DTYPE_t}}*>malloc(counts[i] * sizeof({{INPUT_DTYPE_t}}))
+                    if distances[i] == NULL:
+                        memory_error = True
+                        break
+                    memcpy(distances[i], &dist_arr_i[0], counts[i] * sizeof({{INPUT_DTYPE_t}}))
+
+        try:
+            if memory_error:
+                raise MemoryError()
+
+            if count_only:
+                # deflatten results
+                return counts_arr.reshape(X.shape[:X.ndim - 1])
+            elif return_distance:
+                indices_npy = np.zeros(Xarr.shape[0], dtype='object')
+                distances_npy = np.zeros(Xarr.shape[0], dtype='object')
+                for i in range(Xarr.shape[0]):
+                    # make a new numpy array that wraps the existing data
+                    # TODO: remove the explicit cast to cnp.intp_t* when cython min version >= 3.0
+                    indices_npy[i] = cnp.PyArray_SimpleNewFromData(1, &counts[i], cnp.NPY_INTP, indices[i])
+                    # make sure the data will be freed when the numpy array is garbage collected
+                    PyArray_ENABLEFLAGS(indices_npy[i], cnp.NPY_ARRAY_OWNDATA)
+                    # make sure the data is not freed twice
+                    indices[i] = NULL
+
+                    # make a new numpy array that wraps the existing data
+                    # TODO: remove the explicit cast to cnp.intp_t* when cython min version >= 3.0
+                    distances_npy[i] = cnp.PyArray_SimpleNewFromData(1, &counts[i], {{NPY_TYPE}}, distances[i])
+                    # make sure the data will be freed when the numpy array is garbage collected
+                    PyArray_ENABLEFLAGS(distances_npy[i], cnp.NPY_ARRAY_OWNDATA)
+                    # make sure the data is not freed twice
+                    distances[i] = NULL
+
+                # deflatten results
+                return (indices_npy.reshape(X.shape[:X.ndim - 1]),
+                        distances_npy.reshape(X.shape[:X.ndim - 1]))
+            else:
+                indices_npy = np.zeros(Xarr.shape[0], dtype='object')
+                for i in range(Xarr.shape[0]):
+                    # make a new numpy array that wraps the existing data
+                    # TODO: remove the explicit cast to cnp.intp_t* when cython min version >= 3.0
+                    indices_npy[i] = cnp.PyArray_SimpleNewFromData(1, &counts[i], cnp.NPY_INTP, indices[i])
+                    # make sure the data will be freed when the numpy array is garbage collected
+                    PyArray_ENABLEFLAGS(indices_npy[i], cnp.NPY_ARRAY_OWNDATA)
+                    # make sure the data is not freed twice
+                    indices[i] = NULL
+
+                # deflatten results
+                return indices_npy.reshape(X.shape[:X.ndim - 1])
+        except MemoryError:
+            # free any buffer that is not owned by a numpy array
+            for i in range(Xarr.shape[0]):
+                free(indices[i])
+                if return_distance:
+                    free(distances[i])
+            raise
+        finally:
+            free(indices)
+            free(distances)
+
+    def kernel_density(self, X, h, kernel='gaussian',
+                       atol=0, rtol=1E-8,
+                       breadth_first=True, return_log=False):
+        """
+        kernel_density(X, h, kernel='gaussian', atol=0, rtol=1E-8,
+                       breadth_first=True, return_log=False)
+
+        Compute the kernel density estimate at points X with the given kernel,
+        using the distance metric specified at tree creation.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            An array of points to query.  Last dimension should match dimension
+            of training data.
+        h : float
+            the bandwidth of the kernel
+        kernel : str, default="gaussian"
+            specify the kernel to use.  Options are
+            - 'gaussian'
+            - 'tophat'
+            - 'epanechnikov'
+            - 'exponential'
+            - 'linear'
+            - 'cosine'
+            Default is kernel = 'gaussian'
+        atol : float, default=0
+            Specify the desired absolute tolerance of the result.
+            If the true result is `K_true`, then the returned result `K_ret`
+            satisfies ``abs(K_true - K_ret) < atol + rtol * K_ret``
+            The default is zero (i.e. machine precision).
+        rtol : float, default=1e-8
+            Specify the desired relative tolerance of the result.
+            If the true result is `K_true`, then the returned result `K_ret`
+            satisfies ``abs(K_true - K_ret) < atol + rtol * K_ret``
+            The default is `1e-8` (i.e. machine precision).
+        breadth_first : bool, default=False
+            If True, use a breadth-first search.  If False (default) use a
+            depth-first search.  Breadth-first is generally faster for
+            compact kernels and/or high tolerances.
+        return_log : bool, default=False
+            Return the logarithm of the result.  This can be more accurate
+            than returning the result itself for narrow kernels.
+
+        Returns
+        -------
+        density : ndarray of shape X.shape[:-1]
+            The array of (log)-density evaluations
+        """
+        cdef float64_t h_c = h
+        cdef float64_t log_atol = log(atol)
+        cdef float64_t log_rtol = log(rtol)
+        cdef float64_t log_min_bound, log_max_bound, log_bound_spread
+        cdef float64_t dist_LB = 0, dist_UB = 0
+
+        cdef intp_t n_samples = self.data.shape[0]
+        cdef intp_t n_features = self.data.shape[1]
+        cdef intp_t i
+        cdef KernelType kernel_c
+
+        # validate kernel
+        if kernel == 'gaussian':
+            kernel_c = GAUSSIAN_KERNEL
+        elif kernel == 'tophat':
+            kernel_c = TOPHAT_KERNEL
+        elif kernel == 'epanechnikov':
+            kernel_c = EPANECHNIKOV_KERNEL
+        elif kernel == 'exponential':
+            kernel_c = EXPONENTIAL_KERNEL
+        elif kernel == 'linear':
+            kernel_c = LINEAR_KERNEL
+        elif kernel == 'cosine':
+            kernel_c = COSINE_KERNEL
+        else:
+            raise ValueError("kernel = '%s' not recognized" % kernel)
+
+        cdef float64_t log_knorm = _log_kernel_norm(h_c, n_features, kernel_c)
+
+        # validate X and prepare for query
+        X = check_array(X, dtype={{INPUT_DTYPE}}, order='C')
+
+        if X.shape[X.ndim - 1] != n_features:
+            raise ValueError("query data dimension must "
+                             "match training data dimension")
+        Xarr_np = X.reshape((-1, n_features))
+        cdef const {{INPUT_DTYPE_t}}[:, ::1] Xarr = Xarr_np
+
+        log_density_arr = np.zeros(Xarr.shape[0], dtype={{INPUT_DTYPE}})
+        cdef {{INPUT_DTYPE_t}}[::1] log_density = log_density_arr
+
+        cdef const {{INPUT_DTYPE_t}}* pt = &Xarr[0, 0]
+
+        cdef NodeHeap nodeheap
+        if breadth_first:
+            nodeheap = NodeHeap(self.data.shape[0] // self.leaf_size)
+        cdef float64_t[::1] node_log_min_bounds
+        cdef float64_t[::1] node_bound_widths
+        # TODO: implement dual tree approach.
+        #       this is difficult because of the need to cache values
+        #       computed between node pairs.
+        if breadth_first:
+            node_log_min_bounds_arr = np.full(self.n_nodes, -np.inf)
+            node_log_min_bounds = node_log_min_bounds_arr
+            node_bound_widths_arr = np.zeros(self.n_nodes)
+            node_bound_widths = node_bound_widths_arr
+            for i in range(Xarr.shape[0]):
+                log_density[i] = self._kde_single_breadthfirst(
+                                            pt, kernel_c, h_c,
+                                            log_knorm, log_atol, log_rtol,
+                                            nodeheap,
+                                            &node_log_min_bounds[0],
+                                            &node_bound_widths[0])
+                pt += n_features
+        else:
+            for i in range(Xarr.shape[0]):
+                min_max_dist{{name_suffix}}(self, 0, pt, &dist_LB, &dist_UB)
+                # compute max & min bounds on density within top node
+                log_min_bound = (log(self.sum_weight) +
+                                 compute_log_kernel(dist_UB,
+                                                    h_c, kernel_c))
+                log_max_bound = (log(self.sum_weight) +
+                                 compute_log_kernel(dist_LB,
+                                                    h_c, kernel_c))
+                log_bound_spread = logsubexp(log_max_bound, log_min_bound)
+                self._kde_single_depthfirst(0, pt, kernel_c, h_c,
+                                            log_knorm, log_atol, log_rtol,
+                                            log_min_bound,
+                                            log_bound_spread,
+                                            &log_min_bound,
+                                            &log_bound_spread)
+                log_density[i] = logaddexp(log_min_bound,
+                                           log_bound_spread - log(2))
+                pt += n_features
+
+        # normalize the results
+        for i in range(log_density.shape[0]):
+            log_density[i] += log_knorm
+
+        log_density_arr = log_density_arr.reshape(X.shape[:X.ndim - 1])
+
+        if return_log:
+            return log_density_arr
+        else:
+            return np.exp(log_density_arr)
+
+    def two_point_correlation(self, X, r, dualtree=False):
+        """
+        two_point_correlation(X, r, dualtree=False)
+
+        Compute the two-point correlation function
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            An array of points to query.  Last dimension should match dimension
+            of training data.
+        r : array-like
+            A one-dimensional array of distances
+        dualtree : bool, default=False
+            If True, use a dualtree algorithm.  Otherwise, use a single-tree
+            algorithm.  Dual tree algorithms can have better scaling for
+            large N.
+
+        Returns
+        -------
+        counts : ndarray
+            counts[i] contains the number of pairs of points with distance
+            less than or equal to r[i]
+        """
+        cdef intp_t n_features = self.data.shape[1]
+        cdef intp_t i
+
+        # validate X and prepare for query
+        X = check_array(X, dtype={{INPUT_DTYPE}}, order='C')
+
+        if X.shape[X.ndim - 1] != self.data.shape[1]:
+            raise ValueError("query data dimension must "
+                             "match training data dimension")
+
+        np_Xarr = X.reshape((-1, self.data.shape[1]))
+        cdef {{INPUT_DTYPE_t}}[:, ::1] Xarr = np_Xarr
+
+        # prepare r for query
+        r = np.asarray(r, dtype=np.float64, order='C')
+        r = np.atleast_1d(r)
+        if r.ndim != 1:
+            raise ValueError("r must be a 1-dimensional array")
+        i_rsort = np.argsort(r)
+        rarr_np = r[i_rsort]  # needed to keep memory in scope
+        cdef float64_t[::1] rarr = rarr_np
+
+        # create array to hold counts
+        count = np.zeros(r.shape[0], dtype=np.intp)
+        cdef intp_t[::1] carr = count
+
+        cdef const {{INPUT_DTYPE_t}}* pt = &Xarr[0, 0]
+
+        if dualtree:
+            other = self.__class__(Xarr, metric=self.dist_metric,
+                                   leaf_size=self.leaf_size)
+            self._two_point_dual(0, other, 0, &rarr[0], &carr[0],
+                                 0, rarr.shape[0])
+        else:
+            for i in range(Xarr.shape[0]):
+                self._two_point_single(0, pt, &rarr[0], &carr[0],
+                                       0, rarr.shape[0])
+                pt += n_features
+
+        return count
+
+    cdef int _query_single_depthfirst(
+        self,
+        intp_t i_node,
+        const {{INPUT_DTYPE_t}}* pt,
+        intp_t i_pt,
+        NeighborsHeap{{name_suffix}} heap,
+        float64_t reduced_dist_LB,
+    ) except -1 nogil:
+        """Recursive Single-tree k-neighbors query, depth-first approach"""
+        cdef NodeData_t node_info = self.node_data[i_node]
+
+        cdef float64_t dist_pt, reduced_dist_LB_1, reduced_dist_LB_2
+        cdef intp_t i, i1, i2
+
+        cdef const {{INPUT_DTYPE_t}}* data = &self.data[0, 0]
+
+        # ------------------------------------------------------------
+        # Case 1: query point is outside node radius:
+        #         trim it from the query
+        if reduced_dist_LB > heap.largest(i_pt):
+            self.n_trims += 1
+
+        # ------------------------------------------------------------
+        # Case 2: this is a leaf node.  Update set of nearby points
+        elif node_info.is_leaf:
+            self.n_leaves += 1
+            for i in range(node_info.idx_start, node_info.idx_end):
+                dist_pt = self.rdist(pt,
+                                     &self.data[self.idx_array[i], 0],
+                                     self.data.shape[1])
+                heap._push(i_pt, dist_pt, self.idx_array[i])
+
+        # ------------------------------------------------------------
+        # Case 3: Node is not a leaf.  Recursively query subnodes
+        #         starting with the closest
+        else:
+            self.n_splits += 1
+            i1 = 2 * i_node + 1
+            i2 = i1 + 1
+            reduced_dist_LB_1 = min_rdist{{name_suffix}}(self, i1, pt)
+            reduced_dist_LB_2 = min_rdist{{name_suffix}}(self, i2, pt)
+
+            # recursively query subnodes
+            if reduced_dist_LB_1 <= reduced_dist_LB_2:
+                self._query_single_depthfirst(i1, pt, i_pt, heap,
+                                              reduced_dist_LB_1)
+                self._query_single_depthfirst(i2, pt, i_pt, heap,
+                                              reduced_dist_LB_2)
+            else:
+                self._query_single_depthfirst(i2, pt, i_pt, heap,
+                                              reduced_dist_LB_2)
+                self._query_single_depthfirst(i1, pt, i_pt, heap,
+                                              reduced_dist_LB_1)
+        return 0
+
+    cdef int _query_single_breadthfirst(
+        self,
+        const {{INPUT_DTYPE_t}}* pt,
+        intp_t i_pt,
+        NeighborsHeap{{name_suffix}} heap,
+        NodeHeap nodeheap,
+    ) except -1:
+        """Non-recursive single-tree k-neighbors query, breadth-first search"""
+        cdef intp_t i, i_node
+        cdef float64_t dist_pt, reduced_dist_LB
+        cdef const NodeData_t* node_data = &self.node_data[0]
+        cdef const {{INPUT_DTYPE_t}}* data = &self.data[0, 0]
+
+        # Set up the node heap and push the head node onto it
+        cdef NodeHeapData_t nodeheap_item
+        nodeheap_item.val = min_rdist{{name_suffix}}(self, 0, pt)
+        nodeheap_item.i1 = 0
+        nodeheap.push(nodeheap_item)
+
+        while nodeheap.n > 0:
+            nodeheap_item = nodeheap.pop()
+            reduced_dist_LB = nodeheap_item.val
+            i_node = nodeheap_item.i1
+            node_info = node_data[i_node]
+
+            # ------------------------------------------------------------
+            # Case 1: query point is outside node radius:
+            #         trim it from the query
+            if reduced_dist_LB > heap.largest(i_pt):
+                self.n_trims += 1
+
+            # ------------------------------------------------------------
+            # Case 2: this is a leaf node.  Update set of nearby points
+            elif node_data[i_node].is_leaf:
+                self.n_leaves += 1
+                for i in range(node_data[i_node].idx_start,
+                               node_data[i_node].idx_end):
+                    dist_pt = self.rdist(pt,
+                                         &self.data[self.idx_array[i], 0],
+                                         self.data.shape[1])
+                    heap._push(i_pt, dist_pt, self.idx_array[i])
+
+            # ------------------------------------------------------------
+            # Case 3: Node is not a leaf.  Add subnodes to the node heap
+            else:
+                self.n_splits += 1
+                for i in range(2 * i_node + 1, 2 * i_node + 3):
+                    nodeheap_item.i1 = i
+                    nodeheap_item.val = min_rdist{{name_suffix}}(self, i, pt)
+                    nodeheap.push(nodeheap_item)
+        return 0
+
+    cdef int _query_dual_depthfirst(
+        self,
+        intp_t i_node1,
+        BinaryTree{{name_suffix}} other,
+        intp_t i_node2,
+        float64_t[::1] bounds,
+        NeighborsHeap{{name_suffix}} heap,
+        float64_t reduced_dist_LB,
+    ) except -1:
+        """Recursive dual-tree k-neighbors query, depth-first"""
+        # note that the array `bounds` is maintained such that
+        # bounds[i] is the largest distance among any of the
+        # current neighbors in node i of the other tree.
+        cdef NodeData_t node_info1 = self.node_data[i_node1]
+        cdef NodeData_t node_info2 = other.node_data[i_node2]
+
+        cdef const {{INPUT_DTYPE_t}}* data1 = &self.data[0, 0]
+        cdef const {{INPUT_DTYPE_t}}* data2 = &other.data[0, 0]
+        cdef intp_t n_features = self.data.shape[1]
+
+        cdef float64_t bound_max, dist_pt, reduced_dist_LB1, reduced_dist_LB2
+        cdef intp_t i1, i2, i_pt, i_parent
+
+        # ------------------------------------------------------------
+        # Case 1: nodes are further apart than the current bound:
+        #         trim both from the query
+        if reduced_dist_LB > bounds[i_node2]:
+            pass
+
+        # ------------------------------------------------------------
+        # Case 2: both nodes are leaves:
+        #         do a brute-force search comparing all pairs
+        elif node_info1.is_leaf and node_info2.is_leaf:
+            bounds[i_node2] = 0
+
+            for i2 in range(node_info2.idx_start, node_info2.idx_end):
+                i_pt = other.idx_array[i2]
+
+                if heap.largest(i_pt) <= reduced_dist_LB:
+                    continue
+
+                for i1 in range(node_info1.idx_start, node_info1.idx_end):
+                    dist_pt = self.rdist(
+                        data1 + n_features * self.idx_array[i1],
+                        data2 + n_features * i_pt,
+                        n_features)
+                    heap._push(i_pt, dist_pt, self.idx_array[i1])
+
+                # keep track of node bound
+                bounds[i_node2] = fmax(bounds[i_node2],
+                                       heap.largest(i_pt))
+
+            # update bounds up the tree
+            while i_node2 > 0:
+                i_parent = (i_node2 - 1) // 2
+                bound_max = fmax(bounds[2 * i_parent + 1],
+                                 bounds[2 * i_parent + 2])
+                if bound_max < bounds[i_parent]:
+                    bounds[i_parent] = bound_max
+                    i_node2 = i_parent
+                else:
+                    break
+
+        # ------------------------------------------------------------
+        # Case 3a: node 1 is a leaf or is smaller: split node 2 and
+        #          recursively query, starting with the nearest subnode
+        elif node_info1.is_leaf or (not node_info2.is_leaf
+                                    and node_info2.radius > node_info1.radius):
+            reduced_dist_LB1 = min_rdist_dual{{name_suffix}}(self, i_node1,
+                                              other, 2 * i_node2 + 1)
+            reduced_dist_LB2 = min_rdist_dual{{name_suffix}}(self, i_node1,
+                                              other, 2 * i_node2 + 2)
+
+            if reduced_dist_LB1 < reduced_dist_LB2:
+                self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 1,
+                                            bounds, heap, reduced_dist_LB1)
+                self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 2,
+                                            bounds, heap, reduced_dist_LB2)
+            else:
+                self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 2,
+                                            bounds, heap, reduced_dist_LB2)
+                self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 1,
+                                            bounds, heap, reduced_dist_LB1)
+
+        # ------------------------------------------------------------
+        # Case 3b: node 2 is a leaf or is smaller: split node 1 and
+        #          recursively query, starting with the nearest subnode
+        else:
+            reduced_dist_LB1 = min_rdist_dual{{name_suffix}}(self, 2 * i_node1 + 1,
+                                              other, i_node2)
+            reduced_dist_LB2 = min_rdist_dual{{name_suffix}}(self, 2 * i_node1 + 2,
+                                              other, i_node2)
+
+            if reduced_dist_LB1 < reduced_dist_LB2:
+                self._query_dual_depthfirst(2 * i_node1 + 1, other, i_node2,
+                                            bounds, heap, reduced_dist_LB1)
+                self._query_dual_depthfirst(2 * i_node1 + 2, other, i_node2,
+                                            bounds, heap, reduced_dist_LB2)
+            else:
+                self._query_dual_depthfirst(2 * i_node1 + 2, other, i_node2,
+                                            bounds, heap, reduced_dist_LB2)
+                self._query_dual_depthfirst(2 * i_node1 + 1, other, i_node2,
+                                            bounds, heap, reduced_dist_LB1)
+        return 0
+
+    cdef int _query_dual_breadthfirst(
+        self,
+        BinaryTree{{name_suffix}} other,
+        NeighborsHeap{{name_suffix}} heap,
+        NodeHeap nodeheap,
+    ) except -1:
+        """Non-recursive dual-tree k-neighbors query, breadth-first"""
+        cdef intp_t i, i1, i2, i_node1, i_node2, i_pt
+        cdef float64_t dist_pt, reduced_dist_LB
+        cdef float64_t[::1] bounds = np.full(other.node_data.shape[0], np.inf)
+        cdef const NodeData_t* node_data1 = &self.node_data[0]
+        cdef const NodeData_t* node_data2 = &other.node_data[0]
+        cdef NodeData_t node_info1, node_info2
+        cdef const {{INPUT_DTYPE_t}}* data1 = &self.data[0, 0]
+        cdef const {{INPUT_DTYPE_t}}* data2 = &other.data[0, 0]
+        cdef intp_t n_features = self.data.shape[1]
+
+        # Set up the node heap and push the head nodes onto it
+        cdef NodeHeapData_t nodeheap_item
+        nodeheap_item.val = min_rdist_dual{{name_suffix}}(self, 0, other, 0)
+        nodeheap_item.i1 = 0
+        nodeheap_item.i2 = 0
+        nodeheap.push(nodeheap_item)
+
+        while nodeheap.n > 0:
+            nodeheap_item = nodeheap.pop()
+            reduced_dist_LB = nodeheap_item.val
+            i_node1 = nodeheap_item.i1
+            i_node2 = nodeheap_item.i2
+
+            node_info1 = node_data1[i_node1]
+            node_info2 = node_data2[i_node2]
+
+            # ------------------------------------------------------------
+            # Case 1: nodes are further apart than the current bound:
+            #         trim both from the query
+            if reduced_dist_LB > bounds[i_node2]:
+                pass
+
+            # ------------------------------------------------------------
+            # Case 2: both nodes are leaves:
+            #         do a brute-force search comparing all pairs
+            elif node_info1.is_leaf and node_info2.is_leaf:
+                bounds[i_node2] = -1
+
+                for i2 in range(node_info2.idx_start, node_info2.idx_end):
+                    i_pt = other.idx_array[i2]
+
+                    if heap.largest(i_pt) <= reduced_dist_LB:
+                        continue
+
+                    for i1 in range(node_info1.idx_start, node_info1.idx_end):
+                        dist_pt = self.rdist(
+                            data1 + n_features * self.idx_array[i1],
+                            data2 + n_features * i_pt,
+                            n_features)
+                        heap._push(i_pt, dist_pt, self.idx_array[i1])
+
+                    # keep track of node bound
+                    bounds[i_node2] = fmax(bounds[i_node2],
+                                           heap.largest(i_pt))
+
+            # ------------------------------------------------------------
+            # Case 3a: node 1 is a leaf or is smaller: split node 2 and
+            #          recursively query, starting with the nearest subnode
+            elif node_info1.is_leaf or (not node_info2.is_leaf
+                                        and (node_info2.radius
+                                             > node_info1.radius)):
+                nodeheap_item.i1 = i_node1
+                for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3):
+                    nodeheap_item.i2 = i2
+                    nodeheap_item.val = min_rdist_dual{{name_suffix}}(self, i_node1,
+                                                       other, i2)
+                    nodeheap.push(nodeheap_item)
+
+            # ------------------------------------------------------------
+            # Case 3b: node 2 is a leaf or is smaller: split node 1 and
+            #          recursively query, starting with the nearest subnode
+            else:
+                nodeheap_item.i2 = i_node2
+                for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3):
+                    nodeheap_item.i1 = i1
+                    nodeheap_item.val = min_rdist_dual{{name_suffix}}(self, i1,
+                                                       other, i_node2)
+                    nodeheap.push(nodeheap_item)
+        return 0
+
+    cdef intp_t _query_radius_single(
+        self,
+        intp_t i_node,
+        const {{INPUT_DTYPE_t}}* pt,
+        float64_t r,
+        intp_t* indices,
+        {{INPUT_DTYPE_t}}* distances,
+        intp_t count,
+        int count_only,
+        int return_distance,
+    ) noexcept nogil:
+        """recursive single-tree radius query, depth-first"""
+        cdef const {{INPUT_DTYPE_t}}* data = &self.data[0, 0]
+        cdef intp_t* idx_array = &self.idx_array[0]
+        cdef intp_t n_features = self.data.shape[1]
+        cdef NodeData_t node_info = self.node_data[i_node]
+
+        cdef intp_t i
+        cdef float64_t reduced_r
+
+        cdef float64_t dist_pt, dist_LB = 0, dist_UB = 0
+        min_max_dist{{name_suffix}}(self, i_node, pt, &dist_LB, &dist_UB)
+
+        # ------------------------------------------------------------
+        # Case 1: all node points are outside distance r.
+        #         prune this branch.
+        if dist_LB > r:
+            pass
+
+        # ------------------------------------------------------------
+        # Case 2: all node points are within distance r
+        #         add all points to neighbors
+        elif dist_UB <= r:
+            if count_only:
+                count += (node_info.idx_end - node_info.idx_start)
+            else:
+                for i in range(node_info.idx_start, node_info.idx_end):
+                    if (count < 0) or (count >= self.data.shape[0]):
+                        return -1
+                    indices[count] = idx_array[i]
+                    if return_distance:
+                        distances[count] = self.dist(pt, (data + n_features
+                                                          * idx_array[i]),
+                                                     n_features)
+                    count += 1
+
+        # ------------------------------------------------------------
+        # Case 3: this is a leaf node.  Go through all points to
+        #         determine if they fall within radius
+        elif node_info.is_leaf:
+            reduced_r = self.dist_metric._dist_to_rdist(r)
+
+            for i in range(node_info.idx_start, node_info.idx_end):
+                dist_pt = self.rdist(pt, (data + n_features * idx_array[i]),
+                                     n_features)
+                if dist_pt <= reduced_r:
+                    if (count < 0) or (count >= self.data.shape[0]):
+                        return -1
+                    if count_only:
+                        pass
+                    else:
+                        indices[count] = idx_array[i]
+                        if return_distance:
+                            distances[count] =\
+                                self.dist_metric._rdist_to_dist(dist_pt)
+                    count += 1
+
+        # ------------------------------------------------------------
+        # Case 4: Node is not a leaf.  Recursively query subnodes
+        else:
+            count = self._query_radius_single(2 * i_node + 1, pt, r,
+                                              indices, distances, count,
+                                              count_only, return_distance)
+            count = self._query_radius_single(2 * i_node + 2, pt, r,
+                                              indices, distances, count,
+                                              count_only, return_distance)
+
+        return count
+
+    cdef float64_t _kde_single_breadthfirst(
+        self, const {{INPUT_DTYPE_t}}* pt,
+        KernelType kernel,
+        float64_t h,
+        float64_t log_knorm,
+        float64_t log_atol,
+        float64_t log_rtol,
+        NodeHeap nodeheap,
+        float64_t* node_log_min_bounds,
+        float64_t* node_log_bound_spreads,
+    ):
+        """non-recursive single-tree kernel density estimation"""
+        # For the given point, node_log_min_bounds and node_log_bound_spreads
+        # will encode the current bounds on the density between the point
+        # and the associated node.
+        # The variables global_log_min_bound and global_log_bound_spread
+        # keep track of the global bounds on density.  The procedure here is
+        # to split nodes, updating these bounds, until the bounds are within
+        # atol & rtol.
+        cdef intp_t i, i1, i2, i_node
+        cdef float64_t N1, N2
+        cdef float64_t global_log_min_bound, global_log_bound_spread
+        cdef float64_t global_log_max_bound
+
+        cdef const {{INPUT_DTYPE_t}}* data = &self.data[0, 0]
+        cdef bint with_sample_weight = self.sample_weight is not None
+        cdef const {{INPUT_DTYPE_t}}* sample_weight
+        if with_sample_weight:
+            sample_weight = &self.sample_weight[0]
+        cdef intp_t* idx_array = &self.idx_array[0]
+        cdef const NodeData_t* node_data = &self.node_data[0]
+        cdef float64_t N
+        cdef float64_t log_weight
+        if with_sample_weight:
+            N = self.sum_weight
+        else:
+            N =  self.data.shape[0]
+        cdef intp_t n_features = self.data.shape[1]
+
+        cdef NodeData_t node_info
+        cdef float64_t dist_pt, log_density
+        cdef float64_t dist_LB_1 = 0, dist_LB_2 = 0
+        cdef float64_t dist_UB_1 = 0, dist_UB_2 = 0
+
+        cdef float64_t dist_UB, dist_LB
+
+        # push the top node to the heap
+        cdef NodeHeapData_t nodeheap_item
+        nodeheap_item.val = min_dist{{name_suffix}}(self, 0, pt)
+        nodeheap_item.i1 = 0
+        nodeheap.push(nodeheap_item)
+
+        global_log_min_bound = log(N) + compute_log_kernel(
+            max_dist{{name_suffix}}(self, 0, pt), h, kernel
+        )
+        global_log_max_bound = log(N) + compute_log_kernel(nodeheap_item.val,
+                                                           h, kernel)
+        global_log_bound_spread = logsubexp(global_log_max_bound,
+                                            global_log_min_bound)
+
+        node_log_min_bounds[0] = global_log_min_bound
+        node_log_bound_spreads[0] = global_log_bound_spread
+
+        while nodeheap.n > 0:
+            nodeheap_item = nodeheap.pop()
+            i_node = nodeheap_item.i1
+
+            node_info = node_data[i_node]
+            if with_sample_weight:
+                N1 = _total_node_weight(node_data, sample_weight,
+                                        idx_array, i_node)
+            else:
+                N1 = node_info.idx_end - node_info.idx_start
+
+            # ------------------------------------------------------------
+            # Case 1: local bounds are equal to within per-point tolerance.
+            if (log_knorm + node_log_bound_spreads[i_node] - log(N1) + log(N)
+                <= logaddexp(log_atol, (log_rtol + log_knorm
+                                        + node_log_min_bounds[i_node]))):
+                pass
+
+            # ------------------------------------------------------------
+            # Case 2: global bounds are within rtol & atol.
+            elif (log_knorm + global_log_bound_spread
+                  <= logaddexp(log_atol,
+                               log_rtol + log_knorm + global_log_min_bound)):
+                break
+
+            # ------------------------------------------------------------
+            # Case 3: node is a leaf. Count contributions from all points
+            elif node_info.is_leaf:
+                global_log_min_bound =\
+                    logsubexp(global_log_min_bound,
+                              node_log_min_bounds[i_node])
+                global_log_bound_spread =\
+                    logsubexp(global_log_bound_spread,
+                              node_log_bound_spreads[i_node])
+                for i in range(node_info.idx_start, node_info.idx_end):
+                    dist_pt = self.dist(pt, data + n_features * idx_array[i],
+                                        n_features)
+                    log_density = compute_log_kernel(dist_pt, h, kernel)
+                    if with_sample_weight:
+                        log_weight = np.log(sample_weight[idx_array[i]])
+                    else:
+                        log_weight = 0.
+                    global_log_min_bound = logaddexp(global_log_min_bound,
+                                                     log_density + log_weight)
+
+            # ------------------------------------------------------------
+            # Case 4: split node and query subnodes
+            else:
+                i1 = 2 * i_node + 1
+                i2 = 2 * i_node + 2
+
+                if with_sample_weight:
+                    N1 = _total_node_weight(node_data, sample_weight,
+                                            idx_array, i1)
+                    N2 = _total_node_weight(node_data, sample_weight,
+                                            idx_array, i2)
+                else:
+                    N1 = node_data[i1].idx_end - node_data[i1].idx_start
+                    N2 = node_data[i2].idx_end - node_data[i2].idx_start
+
+                min_max_dist{{name_suffix}}(self, i1, pt, &dist_LB_1, &dist_UB_1)
+                min_max_dist{{name_suffix}}(self, i2, pt, &dist_LB_2, &dist_UB_2)
+
+                node_log_min_bounds[i1] = (log(N1) +
+                                           compute_log_kernel(dist_UB_1,
+                                                              h, kernel))
+                node_log_bound_spreads[i1] = (log(N1) +
+                                              compute_log_kernel(dist_LB_1,
+                                                                 h, kernel))
+
+                node_log_min_bounds[i2] = (log(N2) +
+                                           compute_log_kernel(dist_UB_2,
+                                                              h, kernel))
+                node_log_bound_spreads[i2] = (log(N2) +
+                                              compute_log_kernel(dist_LB_2,
+                                                                 h, kernel))
+
+                global_log_min_bound = logsubexp(global_log_min_bound,
+                                                 node_log_min_bounds[i_node])
+                global_log_min_bound = logaddexp(global_log_min_bound,
+                                                 node_log_min_bounds[i1])
+                global_log_min_bound = logaddexp(global_log_min_bound,
+                                                 node_log_min_bounds[i2])
+
+                global_log_bound_spread =\
+                    logsubexp(global_log_bound_spread,
+                              node_log_bound_spreads[i_node])
+                global_log_bound_spread = logaddexp(global_log_bound_spread,
+                                                    node_log_bound_spreads[i1])
+                global_log_bound_spread = logaddexp(global_log_bound_spread,
+                                                    node_log_bound_spreads[i2])
+
+                # TODO: rank by the spread rather than the distance?
+                nodeheap_item.val = dist_LB_1
+                nodeheap_item.i1 = i1
+                nodeheap.push(nodeheap_item)
+
+                nodeheap_item.val = dist_LB_2
+                nodeheap_item.i1 = i2
+                nodeheap.push(nodeheap_item)
+
+        nodeheap.clear()
+        return logaddexp(global_log_min_bound,
+                         global_log_bound_spread - log(2))
+
+    cdef int _kde_single_depthfirst(
+        self,
+        intp_t i_node,
+        const {{INPUT_DTYPE_t}}* pt,
+        KernelType kernel,
+        float64_t h,
+        float64_t log_knorm,
+        float64_t log_atol,
+        float64_t log_rtol,
+        float64_t local_log_min_bound,
+        float64_t local_log_bound_spread,
+        float64_t* global_log_min_bound,
+        float64_t* global_log_bound_spread,
+    ) except -1:
+        """recursive single-tree kernel density estimate, depth-first"""
+        # For the given point, local_min_bound and local_max_bound give the
+        # minimum and maximum density for the current node, while
+        # global_min_bound and global_max_bound give the minimum and maximum
+        # density over the entire tree.  We recurse down until global_min_bound
+        # and global_max_bound are within rtol and atol.
+        cdef intp_t i, i1, i2, iw, start, end
+        cdef float64_t N1, N2
+
+        cdef const {{INPUT_DTYPE_t}}* data = &self.data[0, 0]
+        cdef const NodeData_t* node_data = &self.node_data[0]
+        cdef bint with_sample_weight = self.sample_weight is not None
+        cdef const {{INPUT_DTYPE_t}}* sample_weight
+        cdef float64_t log_weight
+        if with_sample_weight:
+            sample_weight = &self.sample_weight[0]
+        cdef intp_t* idx_array = &self.idx_array[0]
+        cdef intp_t n_features = self.data.shape[1]
+
+        cdef NodeData_t node_info = self.node_data[i_node]
+        cdef float64_t dist_pt, log_dens_contribution
+
+        cdef float64_t child1_log_min_bound, child2_log_min_bound
+        cdef float64_t child1_log_bound_spread, child2_log_bound_spread
+        cdef float64_t dist_UB = 0, dist_LB = 0
+
+        if with_sample_weight:
+            N1 = _total_node_weight(node_data, sample_weight,
+                                    idx_array, i_node)
+            N2 = self.sum_weight
+        else:
+            N1 = (node_info.idx_end - node_info.idx_start)
+            N2 = self.data.shape[0]
+
+        # ------------------------------------------------------------
+        # Case 1: local bounds are equal to within errors.  Return
+        if (
+            log_knorm + local_log_bound_spread - log(N1) + log(N2)
+            <= logaddexp(log_atol, (log_rtol + log_knorm + local_log_min_bound))
+        ):
+            pass
+
+        # ------------------------------------------------------------
+        # Case 2: global bounds are within rtol & atol. Return
+        elif (
+            log_knorm + global_log_bound_spread[0]
+            <= logaddexp(log_atol, (log_rtol + log_knorm + global_log_min_bound[0]))
+        ):
+            pass
+
+        # ------------------------------------------------------------
+        # Case 3: node is a leaf. Count contributions from all points
+        elif node_info.is_leaf:
+            global_log_min_bound[0] = logsubexp(global_log_min_bound[0],
+                                                local_log_min_bound)
+            global_log_bound_spread[0] = logsubexp(global_log_bound_spread[0],
+                                                   local_log_bound_spread)
+            for i in range(node_info.idx_start, node_info.idx_end):
+                dist_pt = self.dist(pt, (data + n_features * idx_array[i]),
+                                    n_features)
+                log_dens_contribution = compute_log_kernel(dist_pt, h, kernel)
+                if with_sample_weight:
+                    log_weight = np.log(sample_weight[idx_array[i]])
+                else:
+                    log_weight = 0.
+                global_log_min_bound[0] = logaddexp(global_log_min_bound[0],
+                                                    (log_dens_contribution +
+                                                     log_weight))
+
+        # ------------------------------------------------------------
+        # Case 4: split node and query subnodes
+        else:
+            i1 = 2 * i_node + 1
+            i2 = 2 * i_node + 2
+
+            if with_sample_weight:
+                N1 = _total_node_weight(node_data, sample_weight,
+                                        idx_array, i1)
+                N2 = _total_node_weight(node_data, sample_weight,
+                                        idx_array, i2)
+            else:
+                N1 = (self.node_data[i1].idx_end - self.node_data[i1].idx_start)
+                N2 = (self.node_data[i2].idx_end - self.node_data[i2].idx_start)
+
+            min_max_dist{{name_suffix}}(self, i1, pt, &dist_LB, &dist_UB)
+            child1_log_min_bound = log(N1) + compute_log_kernel(dist_UB, h,
+                                                                kernel)
+            child1_log_bound_spread = logsubexp(log(N1) +
+                                                compute_log_kernel(dist_LB, h,
+                                                                   kernel),
+                                                child1_log_min_bound)
+
+            min_max_dist{{name_suffix}}(self, i2, pt, &dist_LB, &dist_UB)
+            child2_log_min_bound = log(N2) + compute_log_kernel(dist_UB, h,
+                                                                kernel)
+            child2_log_bound_spread = logsubexp(log(N2) +
+                                                compute_log_kernel(dist_LB, h,
+                                                                   kernel),
+                                                child2_log_min_bound)
+
+            global_log_min_bound[0] = logsubexp(global_log_min_bound[0],
+                                                local_log_min_bound)
+            global_log_min_bound[0] = logaddexp(global_log_min_bound[0],
+                                                child1_log_min_bound)
+            global_log_min_bound[0] = logaddexp(global_log_min_bound[0],
+                                                child2_log_min_bound)
+
+            global_log_bound_spread[0] = logsubexp(global_log_bound_spread[0],
+                                                   local_log_bound_spread)
+            global_log_bound_spread[0] = logaddexp(global_log_bound_spread[0],
+                                                   child1_log_bound_spread)
+            global_log_bound_spread[0] = logaddexp(global_log_bound_spread[0],
+                                                   child2_log_bound_spread)
+
+            self._kde_single_depthfirst(i1, pt, kernel, h, log_knorm,
+                                        log_atol, log_rtol,
+                                        child1_log_min_bound,
+                                        child1_log_bound_spread,
+                                        global_log_min_bound,
+                                        global_log_bound_spread)
+            self._kde_single_depthfirst(i2, pt, kernel, h, log_knorm,
+                                        log_atol, log_rtol,
+                                        child2_log_min_bound,
+                                        child2_log_bound_spread,
+                                        global_log_min_bound,
+                                        global_log_bound_spread)
+        return 0
+
+    cdef int _two_point_single(
+        self,
+        intp_t i_node,
+        const {{INPUT_DTYPE_t}}* pt,
+        float64_t* r,
+        intp_t* count,
+        intp_t i_min,
+        intp_t i_max,
+    ) except -1:
+        """recursive single-tree two-point correlation function query"""
+        cdef const {{INPUT_DTYPE_t}}* data = &self.data[0, 0]
+        cdef intp_t* idx_array = &self.idx_array[0]
+        cdef intp_t n_features = self.data.shape[1]
+        cdef NodeData_t node_info = self.node_data[i_node]
+
+        cdef intp_t i, j, Npts
+        cdef float64_t reduced_r
+
+        cdef float64_t dist_pt, dist_LB = 0, dist_UB = 0
+        min_max_dist{{name_suffix}}(self, i_node, pt, &dist_LB, &dist_UB)
+
+        # ------------------------------------------------------------
+        # Go through bounds and check for cuts
+        while i_min < i_max:
+            if dist_LB > r[i_min]:
+                i_min += 1
+            else:
+                break
+
+        while i_max > i_min:
+            Npts = (node_info.idx_end - node_info.idx_start)
+            if dist_UB <= r[i_max - 1]:
+                count[i_max - 1] += Npts
+                i_max -= 1
+            else:
+                break
+
+        if i_min < i_max:
+            # If node is a leaf, go through all points
+            if node_info.is_leaf:
+                for i in range(node_info.idx_start, node_info.idx_end):
+                    dist_pt = self.dist(pt, (data + n_features * idx_array[i]),
+                                        n_features)
+                    j = i_max - 1
+                    while (j >= i_min) and (dist_pt <= r[j]):
+                        count[j] += 1
+                        j -= 1
+
+            else:
+                self._two_point_single(2 * i_node + 1, pt, r,
+                                       count, i_min, i_max)
+                self._two_point_single(2 * i_node + 2, pt, r,
+                                       count, i_min, i_max)
+        return 0
+
+    cdef int _two_point_dual(
+        self,
+        intp_t i_node1,
+        BinaryTree{{name_suffix}} other,
+        intp_t i_node2,
+        float64_t* r,
+        intp_t* count,
+        intp_t i_min,
+        intp_t i_max,
+    ) except -1:
+        """recursive dual-tree two-point correlation function query"""
+        cdef const {{INPUT_DTYPE_t}}* data1 = &self.data[0, 0]
+        cdef const {{INPUT_DTYPE_t}}* data2 = &other.data[0, 0]
+        cdef intp_t* idx_array1 = &self.idx_array[0]
+        cdef intp_t* idx_array2 = &other.idx_array[0]
+        cdef NodeData_t node_info1 = self.node_data[i_node1]
+        cdef NodeData_t node_info2 = other.node_data[i_node2]
+
+        cdef intp_t n_features = self.data.shape[1]
+
+        cdef intp_t i1, i2, j, Npts
+        cdef float64_t reduced_r
+
+        cdef float64_t dist_pt, dist_LB = 0, dist_UB = 0
+        dist_LB = min_dist_dual{{name_suffix}}(self, i_node1, other, i_node2)
+        dist_UB = max_dist_dual{{name_suffix}}(self, i_node1, other, i_node2)
+
+        # ------------------------------------------------------------
+        # Go through bounds and check for cuts
+        while i_min < i_max:
+            if dist_LB > r[i_min]:
+                i_min += 1
+            else:
+                break
+
+        while i_max > i_min:
+            Npts = ((node_info1.idx_end - node_info1.idx_start)
+                    * (node_info2.idx_end - node_info2.idx_start))
+            if dist_UB <= r[i_max - 1]:
+                count[i_max - 1] += Npts
+                i_max -= 1
+            else:
+                break
+
+        if i_min < i_max:
+            if node_info1.is_leaf and node_info2.is_leaf:
+                # If both nodes are leaves, go through all points
+                for i1 in range(node_info1.idx_start, node_info1.idx_end):
+                    for i2 in range(node_info2.idx_start, node_info2.idx_end):
+                        dist_pt = self.dist((data1 + n_features
+                                             * idx_array1[i1]),
+                                            (data2 + n_features
+                                             * idx_array2[i2]),
+                                            n_features)
+                        j = i_max - 1
+                        while (j >= i_min) and (dist_pt <= r[j]):
+                            count[j] += 1
+                            j -= 1
+
+            elif node_info1.is_leaf:
+                # If only one is a leaf, split the other
+                for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3):
+                    self._two_point_dual(i_node1, other, i2,
+                                         r, count, i_min, i_max)
+
+            elif node_info2.is_leaf:
+                for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3):
+                    self._two_point_dual(i1, other, i_node2,
+                                         r, count, i_min, i_max)
+
+            else:
+                # neither is a leaf: split & query both
+                for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3):
+                    for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3):
+                        self._two_point_dual(i1, other, i2,
+                                             r, count, i_min, i_max)
+        return 0
+
+{{endfor}}
+
+######################################################################
+# Python functions for benchmarking and testing C implementations
+
+def simultaneous_sort(float64_t[:, ::1] distances, intp_t[:, ::1] indices):
+    """In-place simultaneous sort the given row of the arrays
+
+    This python wrapper exists primarily to enable unit testing
+    of the _simultaneous_sort C routine.
+    """
+    assert distances.shape[0] == indices.shape[0]
+    assert distances.shape[1] == indices.shape[1]
+    cdef intp_t row
+    for row in range(distances.shape[0]):
+        _simultaneous_sort(&distances[row, 0],
+                           &indices[row, 0],
+                           distances.shape[1])
+
+
+def nodeheap_sort(float64_t[::1] vals):
+    """In-place reverse sort of vals using NodeHeap"""
+    cdef intp_t[::1] indices = np.zeros(vals.shape[0], dtype=np.intp)
+    cdef float64_t[::1] vals_sorted = np.zeros_like(vals)
+
+    # use initial size 0 to check corner case
+    cdef NodeHeap heap = NodeHeap(0)
+    cdef NodeHeapData_t data
+    cdef intp_t i
+    for i in range(vals.shape[0]):
+        data.val = vals[i]
+        data.i1 = i
+        data.i2 = i + 1
+        heap.push(data)
+
+    for i in range(vals.shape[0]):
+        data = heap.pop()
+        vals_sorted[i] = data.val
+        indices[i] = data.i1
+
+    return np.asarray(vals_sorted), np.asarray(indices)
+
+
+cdef inline float64_t _total_node_weight(
+    const NodeData_t* node_data,
+    const floating* sample_weight,
+    const intp_t* idx_array,
+    intp_t i_node,
+):
+    cdef intp_t i
+    cdef float64_t N = 0.0
+    for i in range(node_data[i_node].idx_start, node_data[i_node].idx_end):
+        N += sample_weight[idx_array[i]]
+    return N
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_classification.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_classification.py
new file mode 100644
index 0000000000000000000000000000000000000000..c70b83cb1d3bdbcab4f241bf19416d410cbaf9e4
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_classification.py
@@ -0,0 +1,919 @@
+"""Nearest Neighbor Classification"""
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+import warnings
+from numbers import Integral
+
+import numpy as np
+
+from sklearn.neighbors._base import _check_precomputed
+
+from ..base import ClassifierMixin, _fit_context
+from ..metrics._pairwise_distances_reduction import (
+    ArgKminClassMode,
+    RadiusNeighborsClassMode,
+)
+from ..utils._param_validation import StrOptions
+from ..utils.arrayfuncs import _all_with_any_reduction_axis_1
+from ..utils.extmath import weighted_mode
+from ..utils.fixes import _mode
+from ..utils.validation import (
+    _is_arraylike,
+    _num_samples,
+    check_is_fitted,
+    validate_data,
+)
+from ._base import KNeighborsMixin, NeighborsBase, RadiusNeighborsMixin, _get_weights
+
+
+def _adjusted_metric(metric, metric_kwargs, p=None):
+    metric_kwargs = metric_kwargs or {}
+    if metric == "minkowski":
+        metric_kwargs["p"] = p
+        if p == 2:
+            metric = "euclidean"
+    return metric, metric_kwargs
+
+
+class KNeighborsClassifier(KNeighborsMixin, ClassifierMixin, NeighborsBase):
+    """Classifier implementing the k-nearest neighbors vote.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    n_neighbors : int, default=5
+        Number of neighbors to use by default for :meth:`kneighbors` queries.
+
+    weights : {'uniform', 'distance'}, callable or None, default='uniform'
+        Weight function used in prediction.  Possible values:
+
+        - 'uniform' : uniform weights.  All points in each neighborhood
+          are weighted equally.
+        - 'distance' : weight points by the inverse of their distance.
+          in this case, closer neighbors of a query point will have a
+          greater influence than neighbors which are further away.
+        - [callable] : a user-defined function which accepts an
+          array of distances, and returns an array of the same shape
+          containing the weights.
+
+        Refer to the example entitled
+        :ref:`sphx_glr_auto_examples_neighbors_plot_classification.py`
+        showing the impact of the `weights` parameter on the decision
+        boundary.
+
+    algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto'
+        Algorithm used to compute the nearest neighbors:
+
+        - 'ball_tree' will use :class:`BallTree`
+        - 'kd_tree' will use :class:`KDTree`
+        - 'brute' will use a brute-force search.
+        - 'auto' will attempt to decide the most appropriate algorithm
+          based on the values passed to :meth:`fit` method.
+
+        Note: fitting on sparse input will override the setting of
+        this parameter, using brute force.
+
+    leaf_size : int, default=30
+        Leaf size passed to BallTree or KDTree.  This can affect the
+        speed of the construction and query, as well as the memory
+        required to store the tree.  The optimal value depends on the
+        nature of the problem.
+
+    p : float, default=2
+        Power parameter for the Minkowski metric. When p = 1, this is equivalent
+        to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2.
+        For arbitrary p, minkowski_distance (l_p) is used. This parameter is expected
+        to be positive.
+
+    metric : str or callable, default='minkowski'
+        Metric to use for distance computation. Default is "minkowski", which
+        results in the standard Euclidean distance when p = 2. See the
+        documentation of `scipy.spatial.distance
+        `_ and
+        the metrics listed in
+        :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric
+        values.
+
+        If metric is "precomputed", X is assumed to be a distance matrix and
+        must be square during fit. X may be a :term:`sparse graph`, in which
+        case only "nonzero" elements may be considered neighbors.
+
+        If metric is a callable function, it takes two arrays representing 1D
+        vectors as inputs and must return one value indicating the distance
+        between those vectors. This works for Scipy's metrics, but is less
+        efficient than passing the metric name as a string.
+
+    metric_params : dict, default=None
+        Additional keyword arguments for the metric function.
+
+    n_jobs : int, default=None
+        The number of parallel jobs to run for neighbors search.
+        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+        ``-1`` means using all processors. See :term:`Glossary `
+        for more details.
+        Doesn't affect :meth:`fit` method.
+
+    Attributes
+    ----------
+    classes_ : array of shape (n_classes,)
+        Class labels known to the classifier
+
+    effective_metric_ : str or callble
+        The distance metric used. It will be same as the `metric` parameter
+        or a synonym of it, e.g. 'euclidean' if the `metric` parameter set to
+        'minkowski' and `p` parameter set to 2.
+
+    effective_metric_params_ : dict
+        Additional keyword arguments for the metric function. For most metrics
+        will be same with `metric_params` parameter, but may also contain the
+        `p` parameter value if the `effective_metric_` attribute is set to
+        'minkowski'.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    n_samples_fit_ : int
+        Number of samples in the fitted data.
+
+    outputs_2d_ : bool
+        False when `y`'s shape is (n_samples, ) or (n_samples, 1) during fit
+        otherwise True.
+
+    See Also
+    --------
+    RadiusNeighborsClassifier: Classifier based on neighbors within a fixed radius.
+    KNeighborsRegressor: Regression based on k-nearest neighbors.
+    RadiusNeighborsRegressor: Regression based on neighbors within a fixed radius.
+    NearestNeighbors: Unsupervised learner for implementing neighbor searches.
+
+    Notes
+    -----
+    See :ref:`Nearest Neighbors ` in the online documentation
+    for a discussion of the choice of ``algorithm`` and ``leaf_size``.
+
+    .. warning::
+
+       Regarding the Nearest Neighbors algorithms, if it is found that two
+       neighbors, neighbor `k+1` and `k`, have identical distances
+       but different labels, the results will depend on the ordering of the
+       training data.
+
+    https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm
+
+    Examples
+    --------
+    >>> X = [[0], [1], [2], [3]]
+    >>> y = [0, 0, 1, 1]
+    >>> from sklearn.neighbors import KNeighborsClassifier
+    >>> neigh = KNeighborsClassifier(n_neighbors=3)
+    >>> neigh.fit(X, y)
+    KNeighborsClassifier(...)
+    >>> print(neigh.predict([[1.1]]))
+    [0]
+    >>> print(neigh.predict_proba([[0.9]]))
+    [[0.666 0.333]]
+    """
+
+    _parameter_constraints: dict = {**NeighborsBase._parameter_constraints}
+    _parameter_constraints.pop("radius")
+    _parameter_constraints.update(
+        {"weights": [StrOptions({"uniform", "distance"}), callable, None]}
+    )
+
+    def __init__(
+        self,
+        n_neighbors=5,
+        *,
+        weights="uniform",
+        algorithm="auto",
+        leaf_size=30,
+        p=2,
+        metric="minkowski",
+        metric_params=None,
+        n_jobs=None,
+    ):
+        super().__init__(
+            n_neighbors=n_neighbors,
+            algorithm=algorithm,
+            leaf_size=leaf_size,
+            metric=metric,
+            p=p,
+            metric_params=metric_params,
+            n_jobs=n_jobs,
+        )
+        self.weights = weights
+
+    @_fit_context(
+        # KNeighborsClassifier.metric is not validated yet
+        prefer_skip_nested_validation=False
+    )
+    def fit(self, X, y):
+        """Fit the k-nearest neighbors classifier from the training dataset.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
+                (n_samples, n_samples) if metric='precomputed'
+            Training data.
+
+        y : {array-like, sparse matrix} of shape (n_samples,) or \
+                (n_samples, n_outputs)
+            Target values.
+
+        Returns
+        -------
+        self : KNeighborsClassifier
+            The fitted k-nearest neighbors classifier.
+        """
+        return self._fit(X, y)
+
+    def predict(self, X):
+        """Predict the class labels for the provided data.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_queries, n_features), \
+                or (n_queries, n_indexed) if metric == 'precomputed', or None
+            Test samples. If `None`, predictions for all indexed points are
+            returned; in this case, points are not considered their own
+            neighbors.
+
+        Returns
+        -------
+        y : ndarray of shape (n_queries,) or (n_queries, n_outputs)
+            Class labels for each data sample.
+        """
+        check_is_fitted(self, "_fit_method")
+        if self.weights == "uniform":
+            if self._fit_method == "brute" and ArgKminClassMode.is_usable_for(
+                X, self._fit_X, self.metric
+            ):
+                probabilities = self.predict_proba(X)
+                if self.outputs_2d_:
+                    return np.stack(
+                        [
+                            self.classes_[idx][np.argmax(probas, axis=1)]
+                            for idx, probas in enumerate(probabilities)
+                        ],
+                        axis=1,
+                    )
+                return self.classes_[np.argmax(probabilities, axis=1)]
+            # In that case, we do not need the distances to perform
+            # the weighting so we do not compute them.
+            neigh_ind = self.kneighbors(X, return_distance=False)
+            neigh_dist = None
+        else:
+            neigh_dist, neigh_ind = self.kneighbors(X)
+
+        classes_ = self.classes_
+        _y = self._y
+        if not self.outputs_2d_:
+            _y = self._y.reshape((-1, 1))
+            classes_ = [self.classes_]
+
+        n_outputs = len(classes_)
+        n_queries = _num_samples(self._fit_X if X is None else X)
+        weights = _get_weights(neigh_dist, self.weights)
+        if weights is not None and _all_with_any_reduction_axis_1(weights, value=0):
+            raise ValueError(
+                "All neighbors of some sample is getting zero weights. "
+                "Please modify 'weights' to avoid this case if you are "
+                "using a user-defined function."
+            )
+
+        y_pred = np.empty((n_queries, n_outputs), dtype=classes_[0].dtype)
+        for k, classes_k in enumerate(classes_):
+            if weights is None:
+                mode, _ = _mode(_y[neigh_ind, k], axis=1)
+            else:
+                mode, _ = weighted_mode(_y[neigh_ind, k], weights, axis=1)
+
+            mode = np.asarray(mode.ravel(), dtype=np.intp)
+            y_pred[:, k] = classes_k.take(mode)
+
+        if not self.outputs_2d_:
+            y_pred = y_pred.ravel()
+
+        return y_pred
+
+    def predict_proba(self, X):
+        """Return probability estimates for the test data X.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_queries, n_features), \
+                or (n_queries, n_indexed) if metric == 'precomputed', or None
+            Test samples. If `None`, predictions for all indexed points are
+            returned; in this case, points are not considered their own
+            neighbors.
+
+        Returns
+        -------
+        p : ndarray of shape (n_queries, n_classes), or a list of n_outputs \
+                of such arrays if n_outputs > 1.
+            The class probabilities of the input samples. Classes are ordered
+            by lexicographic order.
+        """
+        check_is_fitted(self, "_fit_method")
+        if self.weights == "uniform":
+            # TODO: systematize this mapping of metric for
+            # PairwiseDistancesReductions.
+            metric, metric_kwargs = _adjusted_metric(
+                metric=self.metric, metric_kwargs=self.metric_params, p=self.p
+            )
+            if (
+                self._fit_method == "brute"
+                and ArgKminClassMode.is_usable_for(X, self._fit_X, metric)
+                # TODO: Implement efficient multi-output solution
+                and not self.outputs_2d_
+            ):
+                if self.metric == "precomputed":
+                    X = _check_precomputed(X)
+                else:
+                    X = validate_data(
+                        self, X, accept_sparse="csr", reset=False, order="C"
+                    )
+
+                probabilities = ArgKminClassMode.compute(
+                    X,
+                    self._fit_X,
+                    k=self.n_neighbors,
+                    weights=self.weights,
+                    Y_labels=self._y,
+                    unique_Y_labels=self.classes_,
+                    metric=metric,
+                    metric_kwargs=metric_kwargs,
+                    # `strategy="parallel_on_X"` has in practice be shown
+                    # to be more efficient than `strategy="parallel_on_Y``
+                    # on many combination of datasets.
+                    # Hence, we choose to enforce it here.
+                    # For more information, see:
+                    # https://github.com/scikit-learn/scikit-learn/pull/24076#issuecomment-1445258342
+                    # TODO: adapt the heuristic for `strategy="auto"` for
+                    # `ArgKminClassMode` and use `strategy="auto"`.
+                    strategy="parallel_on_X",
+                )
+                return probabilities
+
+            # In that case, we do not need the distances to perform
+            # the weighting so we do not compute them.
+            neigh_ind = self.kneighbors(X, return_distance=False)
+            neigh_dist = None
+        else:
+            neigh_dist, neigh_ind = self.kneighbors(X)
+
+        classes_ = self.classes_
+        _y = self._y
+        if not self.outputs_2d_:
+            _y = self._y.reshape((-1, 1))
+            classes_ = [self.classes_]
+
+        n_queries = _num_samples(self._fit_X if X is None else X)
+
+        weights = _get_weights(neigh_dist, self.weights)
+        if weights is None:
+            weights = np.ones_like(neigh_ind)
+        elif _all_with_any_reduction_axis_1(weights, value=0):
+            raise ValueError(
+                "All neighbors of some sample is getting zero weights. "
+                "Please modify 'weights' to avoid this case if you are "
+                "using a user-defined function."
+            )
+
+        all_rows = np.arange(n_queries)
+        probabilities = []
+        for k, classes_k in enumerate(classes_):
+            pred_labels = _y[:, k][neigh_ind]
+            proba_k = np.zeros((n_queries, classes_k.size))
+
+            # a simple ':' index doesn't work right
+            for i, idx in enumerate(pred_labels.T):  # loop is O(n_neighbors)
+                proba_k[all_rows, idx] += weights[:, i]
+
+            # normalize 'votes' into real [0,1] probabilities
+            normalizer = proba_k.sum(axis=1)[:, np.newaxis]
+            proba_k /= normalizer
+
+            probabilities.append(proba_k)
+
+        if not self.outputs_2d_:
+            probabilities = probabilities[0]
+
+        return probabilities
+
+    # This function is defined here only to modify the parent docstring
+    # and add information about X=None
+    def score(self, X, y, sample_weight=None):
+        """
+        Return the mean accuracy on the given test data and labels.
+
+        In multi-label classification, this is the subset accuracy
+        which is a harsh metric since you require for each sample that
+        each label set be correctly predicted.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features), or None
+            Test samples. If `None`, predictions for all indexed points are
+            used; in this case, points are not considered their own
+            neighbors. This means that `knn.fit(X, y).score(None, y)`
+            implicitly performs a leave-one-out cross-validation procedure
+            and is equivalent to `cross_val_score(knn, X, y, cv=LeaveOneOut())`
+            but typically much faster.
+
+        y : array-like of shape (n_samples,) or (n_samples, n_outputs)
+            True labels for `X`.
+
+        sample_weight : array-like of shape (n_samples,), default=None
+            Sample weights.
+
+        Returns
+        -------
+        score : float
+            Mean accuracy of ``self.predict(X)`` w.r.t. `y`.
+        """
+        return super().score(X, y, sample_weight)
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.classifier_tags.multi_label = True
+        tags.input_tags.pairwise = self.metric == "precomputed"
+        return tags
+
+
+class RadiusNeighborsClassifier(RadiusNeighborsMixin, ClassifierMixin, NeighborsBase):
+    """Classifier implementing a vote among neighbors within a given radius.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    radius : float, default=1.0
+        Range of parameter space to use by default for :meth:`radius_neighbors`
+        queries.
+
+    weights : {'uniform', 'distance'}, callable or None, default='uniform'
+        Weight function used in prediction.  Possible values:
+
+        - 'uniform' : uniform weights.  All points in each neighborhood
+          are weighted equally.
+        - 'distance' : weight points by the inverse of their distance.
+          in this case, closer neighbors of a query point will have a
+          greater influence than neighbors which are further away.
+        - [callable] : a user-defined function which accepts an
+          array of distances, and returns an array of the same shape
+          containing the weights.
+
+        Uniform weights are used by default.
+
+    algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto'
+        Algorithm used to compute the nearest neighbors:
+
+        - 'ball_tree' will use :class:`BallTree`
+        - 'kd_tree' will use :class:`KDTree`
+        - 'brute' will use a brute-force search.
+        - 'auto' will attempt to decide the most appropriate algorithm
+          based on the values passed to :meth:`fit` method.
+
+        Note: fitting on sparse input will override the setting of
+        this parameter, using brute force.
+
+    leaf_size : int, default=30
+        Leaf size passed to BallTree or KDTree.  This can affect the
+        speed of the construction and query, as well as the memory
+        required to store the tree.  The optimal value depends on the
+        nature of the problem.
+
+    p : float, default=2
+        Power parameter for the Minkowski metric. When p = 1, this is
+        equivalent to using manhattan_distance (l1), and euclidean_distance
+        (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.
+        This parameter is expected to be positive.
+
+    metric : str or callable, default='minkowski'
+        Metric to use for distance computation. Default is "minkowski", which
+        results in the standard Euclidean distance when p = 2. See the
+        documentation of `scipy.spatial.distance
+        `_ and
+        the metrics listed in
+        :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric
+        values.
+
+        If metric is "precomputed", X is assumed to be a distance matrix and
+        must be square during fit. X may be a :term:`sparse graph`, in which
+        case only "nonzero" elements may be considered neighbors.
+
+        If metric is a callable function, it takes two arrays representing 1D
+        vectors as inputs and must return one value indicating the distance
+        between those vectors. This works for Scipy's metrics, but is less
+        efficient than passing the metric name as a string.
+
+    outlier_label : {manual label, 'most_frequent'}, default=None
+        Label for outlier samples (samples with no neighbors in given radius).
+
+        - manual label: str or int label (should be the same type as y)
+          or list of manual labels if multi-output is used.
+        - 'most_frequent' : assign the most frequent label of y to outliers.
+        - None : when any outlier is detected, ValueError will be raised.
+
+        The outlier label should be selected from among the unique 'Y' labels.
+        If it is specified with a different value a warning will be raised and
+        all class probabilities of outliers will be assigned to be 0.
+
+    metric_params : dict, default=None
+        Additional keyword arguments for the metric function.
+
+    n_jobs : int, default=None
+        The number of parallel jobs to run for neighbors search.
+        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+        ``-1`` means using all processors. See :term:`Glossary `
+        for more details.
+
+    Attributes
+    ----------
+    classes_ : ndarray of shape (n_classes,)
+        Class labels known to the classifier.
+
+    effective_metric_ : str or callable
+        The distance metric used. It will be same as the `metric` parameter
+        or a synonym of it, e.g. 'euclidean' if the `metric` parameter set to
+        'minkowski' and `p` parameter set to 2.
+
+    effective_metric_params_ : dict
+        Additional keyword arguments for the metric function. For most metrics
+        will be same with `metric_params` parameter, but may also contain the
+        `p` parameter value if the `effective_metric_` attribute is set to
+        'minkowski'.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    n_samples_fit_ : int
+        Number of samples in the fitted data.
+
+    outlier_label_ : int or array-like of shape (n_class,)
+        Label which is given for outlier samples (samples with no neighbors
+        on given radius).
+
+    outputs_2d_ : bool
+        False when `y`'s shape is (n_samples, ) or (n_samples, 1) during fit
+        otherwise True.
+
+    See Also
+    --------
+    KNeighborsClassifier : Classifier implementing the k-nearest neighbors
+        vote.
+    RadiusNeighborsRegressor : Regression based on neighbors within a
+        fixed radius.
+    KNeighborsRegressor : Regression based on k-nearest neighbors.
+    NearestNeighbors : Unsupervised learner for implementing neighbor
+        searches.
+
+    Notes
+    -----
+    See :ref:`Nearest Neighbors ` in the online documentation
+    for a discussion of the choice of ``algorithm`` and ``leaf_size``.
+
+    https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm
+
+    Examples
+    --------
+    >>> X = [[0], [1], [2], [3]]
+    >>> y = [0, 0, 1, 1]
+    >>> from sklearn.neighbors import RadiusNeighborsClassifier
+    >>> neigh = RadiusNeighborsClassifier(radius=1.0)
+    >>> neigh.fit(X, y)
+    RadiusNeighborsClassifier(...)
+    >>> print(neigh.predict([[1.5]]))
+    [0]
+    >>> print(neigh.predict_proba([[1.0]]))
+    [[0.66666667 0.33333333]]
+    """
+
+    _parameter_constraints: dict = {
+        **NeighborsBase._parameter_constraints,
+        "weights": [StrOptions({"uniform", "distance"}), callable, None],
+        "outlier_label": [Integral, str, "array-like", None],
+    }
+    _parameter_constraints.pop("n_neighbors")
+
+    def __init__(
+        self,
+        radius=1.0,
+        *,
+        weights="uniform",
+        algorithm="auto",
+        leaf_size=30,
+        p=2,
+        metric="minkowski",
+        outlier_label=None,
+        metric_params=None,
+        n_jobs=None,
+    ):
+        super().__init__(
+            radius=radius,
+            algorithm=algorithm,
+            leaf_size=leaf_size,
+            metric=metric,
+            p=p,
+            metric_params=metric_params,
+            n_jobs=n_jobs,
+        )
+        self.weights = weights
+        self.outlier_label = outlier_label
+
+    @_fit_context(
+        # RadiusNeighborsClassifier.metric is not validated yet
+        prefer_skip_nested_validation=False
+    )
+    def fit(self, X, y):
+        """Fit the radius neighbors classifier from the training dataset.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
+                (n_samples, n_samples) if metric='precomputed'
+            Training data.
+
+        y : {array-like, sparse matrix} of shape (n_samples,) or \
+                (n_samples, n_outputs)
+            Target values.
+
+        Returns
+        -------
+        self : RadiusNeighborsClassifier
+            The fitted radius neighbors classifier.
+        """
+        self._fit(X, y)
+
+        classes_ = self.classes_
+        _y = self._y
+        if not self.outputs_2d_:
+            _y = self._y.reshape((-1, 1))
+            classes_ = [self.classes_]
+
+        if self.outlier_label is None:
+            outlier_label_ = None
+
+        elif self.outlier_label == "most_frequent":
+            outlier_label_ = []
+            # iterate over multi-output, get the most frequent label for each
+            # output.
+            for k, classes_k in enumerate(classes_):
+                label_count = np.bincount(_y[:, k])
+                outlier_label_.append(classes_k[label_count.argmax()])
+
+        else:
+            if _is_arraylike(self.outlier_label) and not isinstance(
+                self.outlier_label, str
+            ):
+                if len(self.outlier_label) != len(classes_):
+                    raise ValueError(
+                        "The length of outlier_label: {} is "
+                        "inconsistent with the output "
+                        "length: {}".format(self.outlier_label, len(classes_))
+                    )
+                outlier_label_ = self.outlier_label
+            else:
+                outlier_label_ = [self.outlier_label] * len(classes_)
+
+            for classes, label in zip(classes_, outlier_label_):
+                if _is_arraylike(label) and not isinstance(label, str):
+                    # ensure the outlier label for each output is a scalar.
+                    raise TypeError(
+                        "The outlier_label of classes {} is "
+                        "supposed to be a scalar, got "
+                        "{}.".format(classes, label)
+                    )
+                if np.append(classes, label).dtype != classes.dtype:
+                    # ensure the dtype of outlier label is consistent with y.
+                    raise TypeError(
+                        "The dtype of outlier_label {} is "
+                        "inconsistent with classes {} in "
+                        "y.".format(label, classes)
+                    )
+
+        self.outlier_label_ = outlier_label_
+
+        return self
+
+    def predict(self, X):
+        """Predict the class labels for the provided data.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_queries, n_features), \
+                or (n_queries, n_indexed) if metric == 'precomputed', or None
+            Test samples. If `None`, predictions for all indexed points are
+            returned; in this case, points are not considered their own
+            neighbors.
+
+        Returns
+        -------
+        y : ndarray of shape (n_queries,) or (n_queries, n_outputs)
+            Class labels for each data sample.
+        """
+
+        probs = self.predict_proba(X)
+        classes_ = self.classes_
+
+        if not self.outputs_2d_:
+            probs = [probs]
+            classes_ = [self.classes_]
+
+        n_outputs = len(classes_)
+        n_queries = probs[0].shape[0]
+        y_pred = np.empty((n_queries, n_outputs), dtype=classes_[0].dtype)
+
+        for k, prob in enumerate(probs):
+            # iterate over multi-output, assign labels based on probabilities
+            # of each output.
+            max_prob_index = prob.argmax(axis=1)
+            y_pred[:, k] = classes_[k].take(max_prob_index)
+
+            outlier_zero_probs = (prob == 0).all(axis=1)
+            if outlier_zero_probs.any():
+                zero_prob_index = np.flatnonzero(outlier_zero_probs)
+                y_pred[zero_prob_index, k] = self.outlier_label_[k]
+
+        if not self.outputs_2d_:
+            y_pred = y_pred.ravel()
+
+        return y_pred
+
+    def predict_proba(self, X):
+        """Return probability estimates for the test data X.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_queries, n_features), \
+                or (n_queries, n_indexed) if metric == 'precomputed', or None
+            Test samples. If `None`, predictions for all indexed points are
+            returned; in this case, points are not considered their own
+            neighbors.
+
+        Returns
+        -------
+        p : ndarray of shape (n_queries, n_classes), or a list of \
+                n_outputs of such arrays if n_outputs > 1.
+            The class probabilities of the input samples. Classes are ordered
+            by lexicographic order.
+        """
+        check_is_fitted(self, "_fit_method")
+        n_queries = _num_samples(self._fit_X if X is None else X)
+
+        metric, metric_kwargs = _adjusted_metric(
+            metric=self.metric, metric_kwargs=self.metric_params, p=self.p
+        )
+
+        if (
+            self.weights == "uniform"
+            and self._fit_method == "brute"
+            and not self.outputs_2d_
+            and RadiusNeighborsClassMode.is_usable_for(X, self._fit_X, metric)
+        ):
+            probabilities = RadiusNeighborsClassMode.compute(
+                X=X,
+                Y=self._fit_X,
+                radius=self.radius,
+                weights=self.weights,
+                Y_labels=self._y,
+                unique_Y_labels=self.classes_,
+                outlier_label=self.outlier_label,
+                metric=metric,
+                metric_kwargs=metric_kwargs,
+                strategy="parallel_on_X",
+                # `strategy="parallel_on_X"` has in practice be shown
+                # to be more efficient than `strategy="parallel_on_Y``
+                # on many combination of datasets.
+                # Hence, we choose to enforce it here.
+                # For more information, see:
+                # https://github.com/scikit-learn/scikit-learn/pull/26828/files#r1282398471
+            )
+            return probabilities
+
+        neigh_dist, neigh_ind = self.radius_neighbors(X)
+        outlier_mask = np.zeros(n_queries, dtype=bool)
+        outlier_mask[:] = [len(nind) == 0 for nind in neigh_ind]
+        outliers = np.flatnonzero(outlier_mask)
+        inliers = np.flatnonzero(~outlier_mask)
+
+        classes_ = self.classes_
+        _y = self._y
+        if not self.outputs_2d_:
+            _y = self._y.reshape((-1, 1))
+            classes_ = [self.classes_]
+
+        if self.outlier_label_ is None and outliers.size > 0:
+            raise ValueError(
+                "No neighbors found for test samples %r, "
+                "you can try using larger radius, "
+                "giving a label for outliers, "
+                "or considering removing them from your dataset." % outliers
+            )
+
+        weights = _get_weights(neigh_dist, self.weights)
+        if weights is not None:
+            weights = weights[inliers]
+
+        probabilities = []
+        # iterate over multi-output, measure probabilities of the k-th output.
+        for k, classes_k in enumerate(classes_):
+            pred_labels = np.zeros(len(neigh_ind), dtype=object)
+            pred_labels[:] = [_y[ind, k] for ind in neigh_ind]
+
+            proba_k = np.zeros((n_queries, classes_k.size))
+            proba_inl = np.zeros((len(inliers), classes_k.size))
+
+            # samples have different size of neighbors within the same radius
+            if weights is None:
+                for i, idx in enumerate(pred_labels[inliers]):
+                    proba_inl[i, :] = np.bincount(idx, minlength=classes_k.size)
+            else:
+                for i, idx in enumerate(pred_labels[inliers]):
+                    proba_inl[i, :] = np.bincount(
+                        idx, weights[i], minlength=classes_k.size
+                    )
+            proba_k[inliers, :] = proba_inl
+
+            if outliers.size > 0:
+                _outlier_label = self.outlier_label_[k]
+                label_index = np.flatnonzero(classes_k == _outlier_label)
+                if label_index.size == 1:
+                    proba_k[outliers, label_index[0]] = 1.0
+                else:
+                    warnings.warn(
+                        "Outlier label {} is not in training "
+                        "classes. All class probabilities of "
+                        "outliers will be assigned with 0."
+                        "".format(self.outlier_label_[k])
+                    )
+
+            # normalize 'votes' into real [0,1] probabilities
+            normalizer = proba_k.sum(axis=1)[:, np.newaxis]
+            normalizer[normalizer == 0.0] = 1.0
+            proba_k /= normalizer
+
+            probabilities.append(proba_k)
+
+        if not self.outputs_2d_:
+            probabilities = probabilities[0]
+
+        return probabilities
+
+    # This function is defined here only to modify the parent docstring
+    # and add information about X=None
+    def score(self, X, y, sample_weight=None):
+        """
+        Return the mean accuracy on the given test data and labels.
+
+        In multi-label classification, this is the subset accuracy
+        which is a harsh metric since you require for each sample that
+        each label set be correctly predicted.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features), or None
+            Test samples. If `None`, predictions for all indexed points are
+            used; in this case, points are not considered their own
+            neighbors. This means that `knn.fit(X, y).score(None, y)`
+            implicitly performs a leave-one-out cross-validation procedure
+            and is equivalent to `cross_val_score(knn, X, y, cv=LeaveOneOut())`
+            but typically much faster.
+
+        y : array-like of shape (n_samples,) or (n_samples, n_outputs)
+            True labels for `X`.
+
+        sample_weight : array-like of shape (n_samples,), default=None
+            Sample weights.
+
+        Returns
+        -------
+        score : float
+            Mean accuracy of ``self.predict(X)`` w.r.t. `y`.
+        """
+        return super().score(X, y, sample_weight)
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.classifier_tags.multi_label = True
+        return tags
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_graph.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_graph.py
new file mode 100644
index 0000000000000000000000000000000000000000..3562fab1fcf01b5487d210a11d83d203bffd7835
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_graph.py
@@ -0,0 +1,704 @@
+"""Nearest Neighbors graph functions"""
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+import itertools
+
+from ..base import ClassNamePrefixFeaturesOutMixin, TransformerMixin, _fit_context
+from ..utils._param_validation import (
+    Integral,
+    Interval,
+    Real,
+    StrOptions,
+    validate_params,
+)
+from ..utils.validation import check_is_fitted
+from ._base import VALID_METRICS, KNeighborsMixin, NeighborsBase, RadiusNeighborsMixin
+from ._unsupervised import NearestNeighbors
+
+
+def _check_params(X, metric, p, metric_params):
+    """Check the validity of the input parameters"""
+    params = zip(["metric", "p", "metric_params"], [metric, p, metric_params])
+    est_params = X.get_params()
+    for param_name, func_param in params:
+        if func_param != est_params[param_name]:
+            raise ValueError(
+                "Got %s for %s, while the estimator has %s for the same parameter."
+                % (func_param, param_name, est_params[param_name])
+            )
+
+
+def _query_include_self(X, include_self, mode):
+    """Return the query based on include_self param"""
+    if include_self == "auto":
+        include_self = mode == "connectivity"
+
+    # it does not include each sample as its own neighbors
+    if not include_self:
+        X = None
+
+    return X
+
+
+@validate_params(
+    {
+        "X": ["array-like", "sparse matrix", KNeighborsMixin],
+        "n_neighbors": [Interval(Integral, 1, None, closed="left")],
+        "mode": [StrOptions({"connectivity", "distance"})],
+        "metric": [StrOptions(set(itertools.chain(*VALID_METRICS.values()))), callable],
+        "p": [Interval(Real, 0, None, closed="right"), None],
+        "metric_params": [dict, None],
+        "include_self": ["boolean", StrOptions({"auto"})],
+        "n_jobs": [Integral, None],
+    },
+    prefer_skip_nested_validation=False,  # metric is not validated yet
+)
+def kneighbors_graph(
+    X,
+    n_neighbors,
+    *,
+    mode="connectivity",
+    metric="minkowski",
+    p=2,
+    metric_params=None,
+    include_self=False,
+    n_jobs=None,
+):
+    """Compute the (weighted) graph of k-Neighbors for points in X.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    X : {array-like, sparse matrix} of shape (n_samples, n_features)
+        Sample data.
+
+    n_neighbors : int
+        Number of neighbors for each sample.
+
+    mode : {'connectivity', 'distance'}, default='connectivity'
+        Type of returned matrix: 'connectivity' will return the connectivity
+        matrix with ones and zeros, and 'distance' will return the distances
+        between neighbors according to the given metric.
+
+    metric : str, default='minkowski'
+        Metric to use for distance computation. Default is "minkowski", which
+        results in the standard Euclidean distance when p = 2. See the
+        documentation of `scipy.spatial.distance
+        `_ and
+        the metrics listed in
+        :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric
+        values.
+
+    p : float, default=2
+        Power parameter for the Minkowski metric. When p = 1, this is equivalent
+        to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2.
+        For arbitrary p, minkowski_distance (l_p) is used. This parameter is expected
+        to be positive.
+
+    metric_params : dict, default=None
+        Additional keyword arguments for the metric function.
+
+    include_self : bool or 'auto', default=False
+        Whether or not to mark each sample as the first nearest neighbor to
+        itself. If 'auto', then True is used for mode='connectivity' and False
+        for mode='distance'.
+
+    n_jobs : int, default=None
+        The number of parallel jobs to run for neighbors search.
+        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+        ``-1`` means using all processors. See :term:`Glossary `
+        for more details.
+
+    Returns
+    -------
+    A : sparse matrix of shape (n_samples, n_samples)
+        Graph where A[i, j] is assigned the weight of edge that
+        connects i to j. The matrix is of CSR format.
+
+    See Also
+    --------
+    radius_neighbors_graph: Compute the (weighted) graph of Neighbors for points in X.
+
+    Examples
+    --------
+    >>> X = [[0], [3], [1]]
+    >>> from sklearn.neighbors import kneighbors_graph
+    >>> A = kneighbors_graph(X, 2, mode='connectivity', include_self=True)
+    >>> A.toarray()
+    array([[1., 0., 1.],
+           [0., 1., 1.],
+           [1., 0., 1.]])
+    """
+    if not isinstance(X, KNeighborsMixin):
+        X = NearestNeighbors(
+            n_neighbors=n_neighbors,
+            metric=metric,
+            p=p,
+            metric_params=metric_params,
+            n_jobs=n_jobs,
+        ).fit(X)
+    else:
+        _check_params(X, metric, p, metric_params)
+
+    query = _query_include_self(X._fit_X, include_self, mode)
+    return X.kneighbors_graph(X=query, n_neighbors=n_neighbors, mode=mode)
+
+
+@validate_params(
+    {
+        "X": ["array-like", "sparse matrix", RadiusNeighborsMixin],
+        "radius": [Interval(Real, 0, None, closed="both")],
+        "mode": [StrOptions({"connectivity", "distance"})],
+        "metric": [StrOptions(set(itertools.chain(*VALID_METRICS.values()))), callable],
+        "p": [Interval(Real, 0, None, closed="right"), None],
+        "metric_params": [dict, None],
+        "include_self": ["boolean", StrOptions({"auto"})],
+        "n_jobs": [Integral, None],
+    },
+    prefer_skip_nested_validation=False,  # metric is not validated yet
+)
+def radius_neighbors_graph(
+    X,
+    radius,
+    *,
+    mode="connectivity",
+    metric="minkowski",
+    p=2,
+    metric_params=None,
+    include_self=False,
+    n_jobs=None,
+):
+    """Compute the (weighted) graph of Neighbors for points in X.
+
+    Neighborhoods are restricted the points at a distance lower than
+    radius.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    X : {array-like, sparse matrix} of shape (n_samples, n_features)
+        Sample data.
+
+    radius : float
+        Radius of neighborhoods.
+
+    mode : {'connectivity', 'distance'}, default='connectivity'
+        Type of returned matrix: 'connectivity' will return the connectivity
+        matrix with ones and zeros, and 'distance' will return the distances
+        between neighbors according to the given metric.
+
+    metric : str, default='minkowski'
+        Metric to use for distance computation. Default is "minkowski", which
+        results in the standard Euclidean distance when p = 2. See the
+        documentation of `scipy.spatial.distance
+        `_ and
+        the metrics listed in
+        :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric
+        values.
+
+    p : float, default=2
+        Power parameter for the Minkowski metric. When p = 1, this is
+        equivalent to using manhattan_distance (l1), and euclidean_distance
+        (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.
+
+    metric_params : dict, default=None
+        Additional keyword arguments for the metric function.
+
+    include_self : bool or 'auto', default=False
+        Whether or not to mark each sample as the first nearest neighbor to
+        itself. If 'auto', then True is used for mode='connectivity' and False
+        for mode='distance'.
+
+    n_jobs : int, default=None
+        The number of parallel jobs to run for neighbors search.
+        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+        ``-1`` means using all processors. See :term:`Glossary `
+        for more details.
+
+    Returns
+    -------
+    A : sparse matrix of shape (n_samples, n_samples)
+        Graph where A[i, j] is assigned the weight of edge that connects
+        i to j. The matrix is of CSR format.
+
+    See Also
+    --------
+    kneighbors_graph: Compute the weighted graph of k-neighbors for points in X.
+
+    Examples
+    --------
+    >>> X = [[0], [3], [1]]
+    >>> from sklearn.neighbors import radius_neighbors_graph
+    >>> A = radius_neighbors_graph(X, 1.5, mode='connectivity',
+    ...                            include_self=True)
+    >>> A.toarray()
+    array([[1., 0., 1.],
+           [0., 1., 0.],
+           [1., 0., 1.]])
+    """
+    if not isinstance(X, RadiusNeighborsMixin):
+        X = NearestNeighbors(
+            radius=radius,
+            metric=metric,
+            p=p,
+            metric_params=metric_params,
+            n_jobs=n_jobs,
+        ).fit(X)
+    else:
+        _check_params(X, metric, p, metric_params)
+
+    query = _query_include_self(X._fit_X, include_self, mode)
+    return X.radius_neighbors_graph(query, radius, mode)
+
+
+class KNeighborsTransformer(
+    ClassNamePrefixFeaturesOutMixin, KNeighborsMixin, TransformerMixin, NeighborsBase
+):
+    """Transform X into a (weighted) graph of k nearest neighbors.
+
+    The transformed data is a sparse graph as returned by kneighbors_graph.
+
+    Read more in the :ref:`User Guide `.
+
+    .. versionadded:: 0.22
+
+    Parameters
+    ----------
+    mode : {'distance', 'connectivity'}, default='distance'
+        Type of returned matrix: 'connectivity' will return the connectivity
+        matrix with ones and zeros, and 'distance' will return the distances
+        between neighbors according to the given metric.
+
+    n_neighbors : int, default=5
+        Number of neighbors for each sample in the transformed sparse graph.
+        For compatibility reasons, as each sample is considered as its own
+        neighbor, one extra neighbor will be computed when mode == 'distance'.
+        In this case, the sparse graph contains (n_neighbors + 1) neighbors.
+
+    algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto'
+        Algorithm used to compute the nearest neighbors:
+
+        - 'ball_tree' will use :class:`BallTree`
+        - 'kd_tree' will use :class:`KDTree`
+        - 'brute' will use a brute-force search.
+        - 'auto' will attempt to decide the most appropriate algorithm
+          based on the values passed to :meth:`fit` method.
+
+        Note: fitting on sparse input will override the setting of
+        this parameter, using brute force.
+
+    leaf_size : int, default=30
+        Leaf size passed to BallTree or KDTree.  This can affect the
+        speed of the construction and query, as well as the memory
+        required to store the tree.  The optimal value depends on the
+        nature of the problem.
+
+    metric : str or callable, default='minkowski'
+        Metric to use for distance computation. Default is "minkowski", which
+        results in the standard Euclidean distance when p = 2. See the
+        documentation of `scipy.spatial.distance
+        `_ and
+        the metrics listed in
+        :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric
+        values.
+
+        If metric is a callable function, it takes two arrays representing 1D
+        vectors as inputs and must return one value indicating the distance
+        between those vectors. This works for Scipy's metrics, but is less
+        efficient than passing the metric name as a string.
+
+        Distance matrices are not supported.
+
+    p : float, default=2
+        Parameter for the Minkowski metric from
+        sklearn.metrics.pairwise.pairwise_distances. When p = 1, this is
+        equivalent to using manhattan_distance (l1), and euclidean_distance
+        (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.
+        This parameter is expected to be positive.
+
+    metric_params : dict, default=None
+        Additional keyword arguments for the metric function.
+
+    n_jobs : int, default=None
+        The number of parallel jobs to run for neighbors search.
+        If ``-1``, then the number of jobs is set to the number of CPU cores.
+
+    Attributes
+    ----------
+    effective_metric_ : str or callable
+        The distance metric used. It will be same as the `metric` parameter
+        or a synonym of it, e.g. 'euclidean' if the `metric` parameter set to
+        'minkowski' and `p` parameter set to 2.
+
+    effective_metric_params_ : dict
+        Additional keyword arguments for the metric function. For most metrics
+        will be same with `metric_params` parameter, but may also contain the
+        `p` parameter value if the `effective_metric_` attribute is set to
+        'minkowski'.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    n_samples_fit_ : int
+        Number of samples in the fitted data.
+
+    See Also
+    --------
+    kneighbors_graph : Compute the weighted graph of k-neighbors for
+        points in X.
+    RadiusNeighborsTransformer : Transform X into a weighted graph of
+        neighbors nearer than a radius.
+
+    Notes
+    -----
+    For an example of using :class:`~sklearn.neighbors.KNeighborsTransformer`
+    in combination with :class:`~sklearn.manifold.TSNE` see
+    :ref:`sphx_glr_auto_examples_neighbors_approximate_nearest_neighbors.py`.
+
+    Examples
+    --------
+    >>> from sklearn.datasets import load_wine
+    >>> from sklearn.neighbors import KNeighborsTransformer
+    >>> X, _ = load_wine(return_X_y=True)
+    >>> X.shape
+    (178, 13)
+    >>> transformer = KNeighborsTransformer(n_neighbors=5, mode='distance')
+    >>> X_dist_graph = transformer.fit_transform(X)
+    >>> X_dist_graph.shape
+    (178, 178)
+    """
+
+    _parameter_constraints: dict = {
+        **NeighborsBase._parameter_constraints,
+        "mode": [StrOptions({"distance", "connectivity"})],
+    }
+    _parameter_constraints.pop("radius")
+
+    def __init__(
+        self,
+        *,
+        mode="distance",
+        n_neighbors=5,
+        algorithm="auto",
+        leaf_size=30,
+        metric="minkowski",
+        p=2,
+        metric_params=None,
+        n_jobs=None,
+    ):
+        super().__init__(
+            n_neighbors=n_neighbors,
+            radius=None,
+            algorithm=algorithm,
+            leaf_size=leaf_size,
+            metric=metric,
+            p=p,
+            metric_params=metric_params,
+            n_jobs=n_jobs,
+        )
+        self.mode = mode
+
+    @_fit_context(
+        # KNeighborsTransformer.metric is not validated yet
+        prefer_skip_nested_validation=False
+    )
+    def fit(self, X, y=None):
+        """Fit the k-nearest neighbors transformer from the training dataset.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
+                (n_samples, n_samples) if metric='precomputed'
+            Training data.
+        y : Ignored
+            Not used, present for API consistency by convention.
+
+        Returns
+        -------
+        self : KNeighborsTransformer
+            The fitted k-nearest neighbors transformer.
+        """
+        self._fit(X)
+        self._n_features_out = self.n_samples_fit_
+        return self
+
+    def transform(self, X):
+        """Compute the (weighted) graph of Neighbors for points in X.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples_transform, n_features)
+            Sample data.
+
+        Returns
+        -------
+        Xt : sparse matrix of shape (n_samples_transform, n_samples_fit)
+            Xt[i, j] is assigned the weight of edge that connects i to j.
+            Only the neighbors have an explicit value.
+            The diagonal is always explicit.
+            The matrix is of CSR format.
+        """
+        check_is_fitted(self)
+        add_one = self.mode == "distance"
+        return self.kneighbors_graph(
+            X, mode=self.mode, n_neighbors=self.n_neighbors + add_one
+        )
+
+    def fit_transform(self, X, y=None):
+        """Fit to data, then transform it.
+
+        Fits transformer to X and y with optional parameters fit_params
+        and returns a transformed version of X.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            Training set.
+
+        y : Ignored
+            Not used, present for API consistency by convention.
+
+        Returns
+        -------
+        Xt : sparse matrix of shape (n_samples, n_samples)
+            Xt[i, j] is assigned the weight of edge that connects i to j.
+            Only the neighbors have an explicit value.
+            The diagonal is always explicit.
+            The matrix is of CSR format.
+        """
+        return self.fit(X).transform(X)
+
+
+class RadiusNeighborsTransformer(
+    ClassNamePrefixFeaturesOutMixin,
+    RadiusNeighborsMixin,
+    TransformerMixin,
+    NeighborsBase,
+):
+    """Transform X into a (weighted) graph of neighbors nearer than a radius.
+
+    The transformed data is a sparse graph as returned by
+    `radius_neighbors_graph`.
+
+    Read more in the :ref:`User Guide `.
+
+    .. versionadded:: 0.22
+
+    Parameters
+    ----------
+    mode : {'distance', 'connectivity'}, default='distance'
+        Type of returned matrix: 'connectivity' will return the connectivity
+        matrix with ones and zeros, and 'distance' will return the distances
+        between neighbors according to the given metric.
+
+    radius : float, default=1.0
+        Radius of neighborhood in the transformed sparse graph.
+
+    algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto'
+        Algorithm used to compute the nearest neighbors:
+
+        - 'ball_tree' will use :class:`BallTree`
+        - 'kd_tree' will use :class:`KDTree`
+        - 'brute' will use a brute-force search.
+        - 'auto' will attempt to decide the most appropriate algorithm
+          based on the values passed to :meth:`fit` method.
+
+        Note: fitting on sparse input will override the setting of
+        this parameter, using brute force.
+
+    leaf_size : int, default=30
+        Leaf size passed to BallTree or KDTree.  This can affect the
+        speed of the construction and query, as well as the memory
+        required to store the tree.  The optimal value depends on the
+        nature of the problem.
+
+    metric : str or callable, default='minkowski'
+        Metric to use for distance computation. Default is "minkowski", which
+        results in the standard Euclidean distance when p = 2. See the
+        documentation of `scipy.spatial.distance
+        `_ and
+        the metrics listed in
+        :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric
+        values.
+
+        If metric is a callable function, it takes two arrays representing 1D
+        vectors as inputs and must return one value indicating the distance
+        between those vectors. This works for Scipy's metrics, but is less
+        efficient than passing the metric name as a string.
+
+        Distance matrices are not supported.
+
+    p : float, default=2
+        Parameter for the Minkowski metric from
+        sklearn.metrics.pairwise.pairwise_distances. When p = 1, this is
+        equivalent to using manhattan_distance (l1), and euclidean_distance
+        (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.
+        This parameter is expected to be positive.
+
+    metric_params : dict, default=None
+        Additional keyword arguments for the metric function.
+
+    n_jobs : int, default=None
+        The number of parallel jobs to run for neighbors search.
+        If ``-1``, then the number of jobs is set to the number of CPU cores.
+
+    Attributes
+    ----------
+    effective_metric_ : str or callable
+        The distance metric used. It will be same as the `metric` parameter
+        or a synonym of it, e.g. 'euclidean' if the `metric` parameter set to
+        'minkowski' and `p` parameter set to 2.
+
+    effective_metric_params_ : dict
+        Additional keyword arguments for the metric function. For most metrics
+        will be same with `metric_params` parameter, but may also contain the
+        `p` parameter value if the `effective_metric_` attribute is set to
+        'minkowski'.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    n_samples_fit_ : int
+        Number of samples in the fitted data.
+
+    See Also
+    --------
+    kneighbors_graph : Compute the weighted graph of k-neighbors for
+        points in X.
+    KNeighborsTransformer : Transform X into a weighted graph of k
+        nearest neighbors.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from sklearn.datasets import load_wine
+    >>> from sklearn.cluster import DBSCAN
+    >>> from sklearn.neighbors import RadiusNeighborsTransformer
+    >>> from sklearn.pipeline import make_pipeline
+    >>> X, _ = load_wine(return_X_y=True)
+    >>> estimator = make_pipeline(
+    ...     RadiusNeighborsTransformer(radius=42.0, mode='distance'),
+    ...     DBSCAN(eps=25.0, metric='precomputed'))
+    >>> X_clustered = estimator.fit_predict(X)
+    >>> clusters, counts = np.unique(X_clustered, return_counts=True)
+    >>> print(counts)
+    [ 29  15 111  11  12]
+    """
+
+    _parameter_constraints: dict = {
+        **NeighborsBase._parameter_constraints,
+        "mode": [StrOptions({"distance", "connectivity"})],
+    }
+    _parameter_constraints.pop("n_neighbors")
+
+    def __init__(
+        self,
+        *,
+        mode="distance",
+        radius=1.0,
+        algorithm="auto",
+        leaf_size=30,
+        metric="minkowski",
+        p=2,
+        metric_params=None,
+        n_jobs=None,
+    ):
+        super().__init__(
+            n_neighbors=None,
+            radius=radius,
+            algorithm=algorithm,
+            leaf_size=leaf_size,
+            metric=metric,
+            p=p,
+            metric_params=metric_params,
+            n_jobs=n_jobs,
+        )
+        self.mode = mode
+
+    @_fit_context(
+        # RadiusNeighborsTransformer.metric is not validated yet
+        prefer_skip_nested_validation=False
+    )
+    def fit(self, X, y=None):
+        """Fit the radius neighbors transformer from the training dataset.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
+                (n_samples, n_samples) if metric='precomputed'
+            Training data.
+
+        y : Ignored
+            Not used, present for API consistency by convention.
+
+        Returns
+        -------
+        self : RadiusNeighborsTransformer
+            The fitted radius neighbors transformer.
+        """
+        self._fit(X)
+        self._n_features_out = self.n_samples_fit_
+        return self
+
+    def transform(self, X):
+        """Compute the (weighted) graph of Neighbors for points in X.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples_transform, n_features)
+            Sample data.
+
+        Returns
+        -------
+        Xt : sparse matrix of shape (n_samples_transform, n_samples_fit)
+            Xt[i, j] is assigned the weight of edge that connects i to j.
+            Only the neighbors have an explicit value.
+            The diagonal is always explicit.
+            The matrix is of CSR format.
+        """
+        check_is_fitted(self)
+        return self.radius_neighbors_graph(X, mode=self.mode, sort_results=True)
+
+    def fit_transform(self, X, y=None):
+        """Fit to data, then transform it.
+
+        Fits transformer to X and y with optional parameters fit_params
+        and returns a transformed version of X.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            Training set.
+
+        y : Ignored
+            Not used, present for API consistency by convention.
+
+        Returns
+        -------
+        Xt : sparse matrix of shape (n_samples, n_samples)
+            Xt[i, j] is assigned the weight of edge that connects i to j.
+            Only the neighbors have an explicit value.
+            The diagonal is always explicit.
+            The matrix is of CSR format.
+        """
+        return self.fit(X).transform(X)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_kd_tree.pyx.tp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_kd_tree.pyx.tp
new file mode 100644
index 0000000000000000000000000000000000000000..d21af05270b9aad33560ea6ff72d55c3fa5c91b4
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_kd_tree.pyx.tp
@@ -0,0 +1,336 @@
+{{py:
+
+# Generated file: _kd_tree.pyx
+
+implementation_specific_values = [
+    # The values are arranged as follows:
+    #
+    #       name_suffix, INPUT_DTYPE_t, INPUT_DTYPE
+    #
+    ('64', 'float64_t', 'np.float64'),
+    ('32', 'float32_t', 'np.float32')
+]
+
+# By Jake Vanderplas (2013) 
+# written for the scikit-learn project
+# SPDX-License-Identifier: BSD-3-Clause
+
+}}
+
+
+__all__ = ['KDTree', 'KDTree64', 'KDTree32']
+
+{{for name_suffix, INPUT_DTYPE_t, INPUT_DTYPE in implementation_specific_values}}
+
+DOC_DICT{{name_suffix}} = {
+    'BinaryTree': 'KDTree{{name_suffix}}',
+    'binary_tree': 'kd_tree{{name_suffix}}',
+}
+
+VALID_METRICS{{name_suffix}} = [
+    'EuclideanDistance{{name_suffix}}',
+    'ManhattanDistance{{name_suffix}}',
+    'ChebyshevDistance{{name_suffix}}',
+    'MinkowskiDistance{{name_suffix}}'
+]
+
+{{endfor}}
+
+include "_binary_tree.pxi"
+
+{{for name_suffix, INPUT_DTYPE_t, INPUT_DTYPE in implementation_specific_values}}
+
+# Inherit KDTree{{name_suffix}} from BinaryTree{{name_suffix}}
+cdef class KDTree{{name_suffix}}(BinaryTree{{name_suffix}}):
+    __doc__ = CLASS_DOC.format(**DOC_DICT{{name_suffix}})
+    pass
+
+{{endfor}}
+
+
+# ----------------------------------------------------------------------
+# The functions below specialized the Binary Tree as a KD Tree
+#
+#   Note that these functions use the concept of "reduced distance".
+#   The reduced distance, defined for some metrics, is a quantity which
+#   is more efficient to compute than the distance, but preserves the
+#   relative rankings of the true distance.  For example, the reduced
+#   distance for the Euclidean metric is the squared-euclidean distance.
+#   For some metrics, the reduced distance is simply the distance.
+
+{{for name_suffix, INPUT_DTYPE_t, INPUT_DTYPE in implementation_specific_values}}
+
+cdef int allocate_data{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree,
+    intp_t n_nodes,
+    intp_t n_features,
+) except -1:
+    """Allocate arrays needed for the KD Tree"""
+    tree.node_bounds = np.zeros((2, n_nodes, n_features), dtype={{INPUT_DTYPE}})
+    return 0
+
+
+cdef int init_node{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree,
+    NodeData_t[::1] node_data,
+    intp_t i_node,
+    intp_t idx_start,
+    intp_t idx_end,
+) except -1:
+    """Initialize the node for the dataset stored in tree.data"""
+    cdef intp_t n_features = tree.data.shape[1]
+    cdef intp_t i, j
+    cdef float64_t rad = 0
+
+    cdef {{INPUT_DTYPE_t}}* lower_bounds = &tree.node_bounds[0, i_node, 0]
+    cdef {{INPUT_DTYPE_t}}* upper_bounds = &tree.node_bounds[1, i_node, 0]
+    cdef const {{INPUT_DTYPE_t}}* data = &tree.data[0, 0]
+    cdef const intp_t* idx_array = &tree.idx_array[0]
+
+    cdef const {{INPUT_DTYPE_t}}* data_row
+
+    # determine Node bounds
+    for j in range(n_features):
+        lower_bounds[j] = INF
+        upper_bounds[j] = -INF
+
+    # Compute the actual data range.  At build time, this is slightly
+    # slower than using the previously-computed bounds of the parent node,
+    # but leads to more compact trees and thus faster queries.
+    for i in range(idx_start, idx_end):
+        data_row = data + idx_array[i] * n_features
+        for j in range(n_features):
+            lower_bounds[j] = fmin(lower_bounds[j], data_row[j])
+            upper_bounds[j] = fmax(upper_bounds[j], data_row[j])
+
+    for j in range(n_features):
+        if tree.dist_metric.p == INF:
+            rad = fmax(rad, 0.5 * (upper_bounds[j] - lower_bounds[j]))
+        else:
+            rad += pow(0.5 * abs(upper_bounds[j] - lower_bounds[j]),
+                       tree.dist_metric.p)
+
+    node_data[i_node].idx_start = idx_start
+    node_data[i_node].idx_end = idx_end
+
+    # The radius will hold the size of the circumscribed hypersphere measured
+    # with the specified metric: in querying, this is used as a measure of the
+    # size of each node when deciding which nodes to split.
+    node_data[i_node].radius = pow(rad, 1. / tree.dist_metric.p)
+    return 0
+
+
+cdef float64_t min_rdist{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree,
+    intp_t i_node,
+    const {{INPUT_DTYPE_t}}* pt,
+) except -1 nogil:
+    """Compute the minimum reduced-distance between a point and a node"""
+    cdef intp_t n_features = tree.data.shape[1]
+    cdef float64_t d, d_lo, d_hi, rdist=0.0
+    cdef intp_t j
+
+    if tree.dist_metric.p == INF:
+        for j in range(n_features):
+            d_lo = tree.node_bounds[0, i_node, j] - pt[j]
+            d_hi = pt[j] - tree.node_bounds[1, i_node, j]
+            d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi))
+            rdist = fmax(rdist, 0.5 * d)
+    else:
+        # here we'll use the fact that x + abs(x) = 2 * max(x, 0)
+        for j in range(n_features):
+            d_lo = tree.node_bounds[0, i_node, j] - pt[j]
+            d_hi = pt[j] - tree.node_bounds[1, i_node, j]
+            d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi))
+            rdist += pow(0.5 * d, tree.dist_metric.p)
+
+    return rdist
+
+
+cdef float64_t min_dist{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree,
+    intp_t i_node,
+    const {{INPUT_DTYPE_t}}* pt,
+) except -1:
+    """Compute the minimum distance between a point and a node"""
+    if tree.dist_metric.p == INF:
+        return min_rdist{{name_suffix}}(tree, i_node, pt)
+    else:
+        return pow(
+            min_rdist{{name_suffix}}(tree, i_node, pt),
+            1. / tree.dist_metric.p
+        )
+
+
+cdef float64_t max_rdist{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree,
+    intp_t i_node,
+    const {{INPUT_DTYPE_t}}* pt,
+) except -1:
+    """Compute the maximum reduced-distance between a point and a node"""
+    cdef intp_t n_features = tree.data.shape[1]
+
+    cdef float64_t d_lo, d_hi, rdist=0.0
+    cdef intp_t j
+
+    if tree.dist_metric.p == INF:
+        for j in range(n_features):
+            rdist = fmax(rdist, fabs(pt[j] - tree.node_bounds[0, i_node, j]))
+            rdist = fmax(rdist, fabs(pt[j] - tree.node_bounds[1, i_node, j]))
+    else:
+        for j in range(n_features):
+            d_lo = fabs(pt[j] - tree.node_bounds[0, i_node, j])
+            d_hi = fabs(pt[j] - tree.node_bounds[1, i_node, j])
+            rdist += pow(fmax(d_lo, d_hi), tree.dist_metric.p)
+
+    return rdist
+
+
+cdef float64_t max_dist{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree,
+    intp_t i_node,
+    const {{INPUT_DTYPE_t}}* pt,
+) except -1:
+    """Compute the maximum distance between a point and a node"""
+    if tree.dist_metric.p == INF:
+        return max_rdist{{name_suffix}}(tree, i_node, pt)
+    else:
+        return pow(
+            max_rdist{{name_suffix}}(tree, i_node, pt),
+            1. / tree.dist_metric.p
+        )
+
+
+cdef inline int min_max_dist{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree,
+    intp_t i_node,
+    const {{INPUT_DTYPE_t}}* pt,
+    float64_t* min_dist,
+    float64_t* max_dist,
+) except -1 nogil:
+    """Compute the minimum and maximum distance between a point and a node"""
+    cdef intp_t n_features = tree.data.shape[1]
+
+    cdef float64_t d, d_lo, d_hi
+    cdef intp_t j
+
+    min_dist[0] = 0.0
+    max_dist[0] = 0.0
+
+    if tree.dist_metric.p == INF:
+        for j in range(n_features):
+            d_lo = tree.node_bounds[0, i_node, j] - pt[j]
+            d_hi = pt[j] - tree.node_bounds[1, i_node, j]
+            d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi))
+            min_dist[0] = fmax(min_dist[0], 0.5 * d)
+            max_dist[0] = fmax(max_dist[0], fabs(d_lo))
+            max_dist[0] = fmax(max_dist[0], fabs(d_hi))
+    else:
+        # as above, use the fact that x + abs(x) = 2 * max(x, 0)
+        for j in range(n_features):
+            d_lo = tree.node_bounds[0, i_node, j] - pt[j]
+            d_hi = pt[j] - tree.node_bounds[1, i_node, j]
+            d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi))
+            min_dist[0] += pow(0.5 * d, tree.dist_metric.p)
+            max_dist[0] += pow(fmax(fabs(d_lo), fabs(d_hi)),
+                               tree.dist_metric.p)
+
+        min_dist[0] = pow(min_dist[0], 1. / tree.dist_metric.p)
+        max_dist[0] = pow(max_dist[0], 1. / tree.dist_metric.p)
+
+    return 0
+
+
+cdef inline float64_t min_rdist_dual{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree1,
+    intp_t i_node1,
+    BinaryTree{{name_suffix}} tree2,
+    intp_t i_node2,
+) except -1:
+    """Compute the minimum reduced distance between two nodes"""
+    cdef intp_t n_features = tree1.data.shape[1]
+
+    cdef float64_t d, d1, d2, rdist=0.0
+    cdef intp_t j
+
+    if tree1.dist_metric.p == INF:
+        for j in range(n_features):
+            d1 = (tree1.node_bounds[0, i_node1, j]
+                  - tree2.node_bounds[1, i_node2, j])
+            d2 = (tree2.node_bounds[0, i_node2, j]
+                  - tree1.node_bounds[1, i_node1, j])
+            d = (d1 + fabs(d1)) + (d2 + fabs(d2))
+
+            rdist = fmax(rdist, 0.5 * d)
+    else:
+        # here we'll use the fact that x + abs(x) = 2 * max(x, 0)
+        for j in range(n_features):
+            d1 = (tree1.node_bounds[0, i_node1, j]
+                  - tree2.node_bounds[1, i_node2, j])
+            d2 = (tree2.node_bounds[0, i_node2, j]
+                  - tree1.node_bounds[1, i_node1, j])
+            d = (d1 + fabs(d1)) + (d2 + fabs(d2))
+
+            rdist += pow(0.5 * d, tree1.dist_metric.p)
+
+    return rdist
+
+
+cdef inline float64_t min_dist_dual{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree1,
+    intp_t i_node1,
+    BinaryTree{{name_suffix}} tree2,
+    intp_t i_node2,
+) except -1:
+    """Compute the minimum distance between two nodes"""
+    return tree1.dist_metric._rdist_to_dist(
+        min_rdist_dual{{name_suffix}}(tree1, i_node1, tree2, i_node2)
+    )
+
+
+cdef inline float64_t max_rdist_dual{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree1,
+    intp_t i_node1,
+    BinaryTree{{name_suffix}} tree2,
+    intp_t i_node2,
+) except -1:
+    """Compute the maximum reduced distance between two nodes"""
+    cdef intp_t n_features = tree1.data.shape[1]
+
+    cdef float64_t d1, d2, rdist=0.0
+    cdef intp_t j
+
+    if tree1.dist_metric.p == INF:
+        for j in range(n_features):
+            rdist = fmax(rdist, fabs(tree1.node_bounds[0, i_node1, j]
+                                     - tree2.node_bounds[1, i_node2, j]))
+            rdist = fmax(rdist, fabs(tree1.node_bounds[1, i_node1, j]
+                                     - tree2.node_bounds[0, i_node2, j]))
+    else:
+        for j in range(n_features):
+            d1 = fabs(tree1.node_bounds[0, i_node1, j]
+                      - tree2.node_bounds[1, i_node2, j])
+            d2 = fabs(tree1.node_bounds[1, i_node1, j]
+                      - tree2.node_bounds[0, i_node2, j])
+            rdist += pow(fmax(d1, d2), tree1.dist_metric.p)
+
+    return rdist
+
+
+cdef inline float64_t max_dist_dual{{name_suffix}}(
+    BinaryTree{{name_suffix}} tree1,
+    intp_t i_node1,
+    BinaryTree{{name_suffix}} tree2,
+    intp_t i_node2,
+) except -1:
+    """Compute the maximum distance between two nodes"""
+    return tree1.dist_metric._rdist_to_dist(
+        max_rdist_dual{{name_suffix}}(tree1, i_node1, tree2, i_node2)
+    )
+
+{{endfor}}
+
+
+class KDTree(KDTree64):
+    __doc__ = CLASS_DOC.format(BinaryTree="KDTree")
+    pass
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_kde.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_kde.py
new file mode 100644
index 0000000000000000000000000000000000000000..7661308db2e01665c82cf82985586006b7c39a56
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_kde.py
@@ -0,0 +1,359 @@
+"""
+Kernel Density Estimation
+-------------------------
+"""
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+import itertools
+from numbers import Integral, Real
+
+import numpy as np
+from scipy.special import gammainc
+
+from ..base import BaseEstimator, _fit_context
+from ..neighbors._base import VALID_METRICS
+from ..utils import check_random_state
+from ..utils._param_validation import Interval, StrOptions
+from ..utils.extmath import row_norms
+from ..utils.validation import _check_sample_weight, check_is_fitted, validate_data
+from ._ball_tree import BallTree
+from ._kd_tree import KDTree
+
+VALID_KERNELS = [
+    "gaussian",
+    "tophat",
+    "epanechnikov",
+    "exponential",
+    "linear",
+    "cosine",
+]
+
+TREE_DICT = {"ball_tree": BallTree, "kd_tree": KDTree}
+
+
+# TODO: implement a brute force version for testing purposes
+# TODO: create a density estimation base class?
+class KernelDensity(BaseEstimator):
+    """Kernel Density Estimation.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    bandwidth : float or {"scott", "silverman"}, default=1.0
+        The bandwidth of the kernel. If bandwidth is a float, it defines the
+        bandwidth of the kernel. If bandwidth is a string, one of the estimation
+        methods is implemented.
+
+    algorithm : {'kd_tree', 'ball_tree', 'auto'}, default='auto'
+        The tree algorithm to use.
+
+    kernel : {'gaussian', 'tophat', 'epanechnikov', 'exponential', 'linear', \
+                 'cosine'}, default='gaussian'
+        The kernel to use.
+
+    metric : str, default='euclidean'
+        Metric to use for distance computation. See the
+        documentation of `scipy.spatial.distance
+        `_ and
+        the metrics listed in
+        :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric
+        values.
+
+        Not all metrics are valid with all algorithms: refer to the
+        documentation of :class:`BallTree` and :class:`KDTree`. Note that the
+        normalization of the density output is correct only for the Euclidean
+        distance metric.
+
+    atol : float, default=0
+        The desired absolute tolerance of the result.  A larger tolerance will
+        generally lead to faster execution.
+
+    rtol : float, default=0
+        The desired relative tolerance of the result.  A larger tolerance will
+        generally lead to faster execution.
+
+    breadth_first : bool, default=True
+        If true (default), use a breadth-first approach to the problem.
+        Otherwise use a depth-first approach.
+
+    leaf_size : int, default=40
+        Specify the leaf size of the underlying tree.  See :class:`BallTree`
+        or :class:`KDTree` for details.
+
+    metric_params : dict, default=None
+        Additional parameters to be passed to the tree for use with the
+        metric.  For more information, see the documentation of
+        :class:`BallTree` or :class:`KDTree`.
+
+    Attributes
+    ----------
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    tree_ : ``BinaryTree`` instance
+        The tree algorithm for fast generalized N-point problems.
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+    bandwidth_ : float
+        Value of the bandwidth, given directly by the bandwidth parameter or
+        estimated using the 'scott' or 'silverman' method.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    sklearn.neighbors.KDTree : K-dimensional tree for fast generalized N-point
+        problems.
+    sklearn.neighbors.BallTree : Ball tree for fast generalized N-point
+        problems.
+
+    Examples
+    --------
+    Compute a gaussian kernel density estimate with a fixed bandwidth.
+
+    >>> from sklearn.neighbors import KernelDensity
+    >>> import numpy as np
+    >>> rng = np.random.RandomState(42)
+    >>> X = rng.random_sample((100, 3))
+    >>> kde = KernelDensity(kernel='gaussian', bandwidth=0.5).fit(X)
+    >>> log_density = kde.score_samples(X[:3])
+    >>> log_density
+    array([-1.52955942, -1.51462041, -1.60244657])
+    """
+
+    _parameter_constraints: dict = {
+        "bandwidth": [
+            Interval(Real, 0, None, closed="neither"),
+            StrOptions({"scott", "silverman"}),
+        ],
+        "algorithm": [StrOptions(set(TREE_DICT.keys()) | {"auto"})],
+        "kernel": [StrOptions(set(VALID_KERNELS))],
+        "metric": [
+            StrOptions(
+                set(itertools.chain(*[VALID_METRICS[alg] for alg in TREE_DICT.keys()]))
+            )
+        ],
+        "atol": [Interval(Real, 0, None, closed="left")],
+        "rtol": [Interval(Real, 0, None, closed="left")],
+        "breadth_first": ["boolean"],
+        "leaf_size": [Interval(Integral, 1, None, closed="left")],
+        "metric_params": [None, dict],
+    }
+
+    def __init__(
+        self,
+        *,
+        bandwidth=1.0,
+        algorithm="auto",
+        kernel="gaussian",
+        metric="euclidean",
+        atol=0,
+        rtol=0,
+        breadth_first=True,
+        leaf_size=40,
+        metric_params=None,
+    ):
+        self.algorithm = algorithm
+        self.bandwidth = bandwidth
+        self.kernel = kernel
+        self.metric = metric
+        self.atol = atol
+        self.rtol = rtol
+        self.breadth_first = breadth_first
+        self.leaf_size = leaf_size
+        self.metric_params = metric_params
+
+    def _choose_algorithm(self, algorithm, metric):
+        # given the algorithm string + metric string, choose the optimal
+        # algorithm to compute the result.
+        if algorithm == "auto":
+            # use KD Tree if possible
+            if metric in KDTree.valid_metrics:
+                return "kd_tree"
+            elif metric in BallTree.valid_metrics:
+                return "ball_tree"
+        else:  # kd_tree or ball_tree
+            if metric not in TREE_DICT[algorithm].valid_metrics:
+                raise ValueError(
+                    "invalid metric for {0}: '{1}'".format(TREE_DICT[algorithm], metric)
+                )
+            return algorithm
+
+    @_fit_context(
+        # KernelDensity.metric is not validated yet
+        prefer_skip_nested_validation=False
+    )
+    def fit(self, X, y=None, sample_weight=None):
+        """Fit the Kernel Density model on the data.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            List of n_features-dimensional data points.  Each row
+            corresponds to a single data point.
+
+        y : None
+            Ignored. This parameter exists only for compatibility with
+            :class:`~sklearn.pipeline.Pipeline`.
+
+        sample_weight : array-like of shape (n_samples,), default=None
+            List of sample weights attached to the data X.
+
+            .. versionadded:: 0.20
+
+        Returns
+        -------
+        self : object
+            Returns the instance itself.
+        """
+        algorithm = self._choose_algorithm(self.algorithm, self.metric)
+
+        if isinstance(self.bandwidth, str):
+            if self.bandwidth == "scott":
+                self.bandwidth_ = X.shape[0] ** (-1 / (X.shape[1] + 4))
+            elif self.bandwidth == "silverman":
+                self.bandwidth_ = (X.shape[0] * (X.shape[1] + 2) / 4) ** (
+                    -1 / (X.shape[1] + 4)
+                )
+        else:
+            self.bandwidth_ = self.bandwidth
+
+        X = validate_data(self, X, order="C", dtype=np.float64)
+
+        if sample_weight is not None:
+            sample_weight = _check_sample_weight(
+                sample_weight, X, dtype=np.float64, ensure_non_negative=True
+            )
+
+        kwargs = self.metric_params
+        if kwargs is None:
+            kwargs = {}
+        self.tree_ = TREE_DICT[algorithm](
+            X,
+            metric=self.metric,
+            leaf_size=self.leaf_size,
+            sample_weight=sample_weight,
+            **kwargs,
+        )
+        return self
+
+    def score_samples(self, X):
+        """Compute the log-likelihood of each sample under the model.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            An array of points to query.  Last dimension should match dimension
+            of training data (n_features).
+
+        Returns
+        -------
+        density : ndarray of shape (n_samples,)
+            Log-likelihood of each sample in `X`. These are normalized to be
+            probability densities, so values will be low for high-dimensional
+            data.
+        """
+        check_is_fitted(self)
+        # The returned density is normalized to the number of points.
+        # For it to be a probability, we must scale it.  For this reason
+        # we'll also scale atol.
+        X = validate_data(self, X, order="C", dtype=np.float64, reset=False)
+        if self.tree_.sample_weight is None:
+            N = self.tree_.data.shape[0]
+        else:
+            N = self.tree_.sum_weight
+        atol_N = self.atol * N
+        log_density = self.tree_.kernel_density(
+            X,
+            h=self.bandwidth_,
+            kernel=self.kernel,
+            atol=atol_N,
+            rtol=self.rtol,
+            breadth_first=self.breadth_first,
+            return_log=True,
+        )
+        log_density -= np.log(N)
+        return log_density
+
+    def score(self, X, y=None):
+        """Compute the total log-likelihood under the model.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            List of n_features-dimensional data points.  Each row
+            corresponds to a single data point.
+
+        y : None
+            Ignored. This parameter exists only for compatibility with
+            :class:`~sklearn.pipeline.Pipeline`.
+
+        Returns
+        -------
+        logprob : float
+            Total log-likelihood of the data in X. This is normalized to be a
+            probability density, so the value will be low for high-dimensional
+            data.
+        """
+        return np.sum(self.score_samples(X))
+
+    def sample(self, n_samples=1, random_state=None):
+        """Generate random samples from the model.
+
+        Currently, this is implemented only for gaussian and tophat kernels.
+
+        Parameters
+        ----------
+        n_samples : int, default=1
+            Number of samples to generate.
+
+        random_state : int, RandomState instance or None, default=None
+            Determines random number generation used to generate
+            random samples. Pass an int for reproducible results
+            across multiple function calls.
+            See :term:`Glossary `.
+
+        Returns
+        -------
+        X : array-like of shape (n_samples, n_features)
+            List of samples.
+        """
+        check_is_fitted(self)
+        # TODO: implement sampling for other valid kernel shapes
+        if self.kernel not in ["gaussian", "tophat"]:
+            raise NotImplementedError()
+
+        data = np.asarray(self.tree_.data)
+
+        rng = check_random_state(random_state)
+        u = rng.uniform(0, 1, size=n_samples)
+        if self.tree_.sample_weight is None:
+            i = (u * data.shape[0]).astype(np.int64)
+        else:
+            cumsum_weight = np.cumsum(np.asarray(self.tree_.sample_weight))
+            sum_weight = cumsum_weight[-1]
+            i = np.searchsorted(cumsum_weight, u * sum_weight)
+        if self.kernel == "gaussian":
+            return np.atleast_2d(rng.normal(data[i], self.bandwidth_))
+
+        elif self.kernel == "tophat":
+            # we first draw points from a d-dimensional normal distribution,
+            # then use an incomplete gamma function to map them to a uniform
+            # d-dimensional tophat distribution.
+            dim = data.shape[1]
+            X = rng.normal(size=(n_samples, dim))
+            s_sq = row_norms(X, squared=True)
+            correction = (
+                gammainc(0.5 * dim, 0.5 * s_sq) ** (1.0 / dim)
+                * self.bandwidth_
+                / np.sqrt(s_sq)
+            )
+            return data[i] + X * correction[:, np.newaxis]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_lof.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_lof.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9f00be42570e2841e5445b5fd68e1dec5413c6a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_lof.py
@@ -0,0 +1,518 @@
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+import warnings
+from numbers import Real
+
+import numpy as np
+
+from ..base import OutlierMixin, _fit_context
+from ..utils import check_array
+from ..utils._param_validation import Interval, StrOptions
+from ..utils.metaestimators import available_if
+from ..utils.validation import check_is_fitted
+from ._base import KNeighborsMixin, NeighborsBase
+
+__all__ = ["LocalOutlierFactor"]
+
+
+class LocalOutlierFactor(KNeighborsMixin, OutlierMixin, NeighborsBase):
+    """Unsupervised Outlier Detection using the Local Outlier Factor (LOF).
+
+    The anomaly score of each sample is called the Local Outlier Factor.
+    It measures the local deviation of the density of a given sample with respect
+    to its neighbors.
+    It is local in that the anomaly score depends on how isolated the object
+    is with respect to the surrounding neighborhood.
+    More precisely, locality is given by k-nearest neighbors, whose distance
+    is used to estimate the local density.
+    By comparing the local density of a sample to the local densities of its
+    neighbors, one can identify samples that have a substantially lower density
+    than their neighbors. These are considered outliers.
+
+    .. versionadded:: 0.19
+
+    Parameters
+    ----------
+    n_neighbors : int, default=20
+        Number of neighbors to use by default for :meth:`kneighbors` queries.
+        If n_neighbors is larger than the number of samples provided,
+        all samples will be used.
+
+    algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto'
+        Algorithm used to compute the nearest neighbors:
+
+        - 'ball_tree' will use :class:`BallTree`
+        - 'kd_tree' will use :class:`KDTree`
+        - 'brute' will use a brute-force search.
+        - 'auto' will attempt to decide the most appropriate algorithm
+          based on the values passed to :meth:`fit` method.
+
+        Note: fitting on sparse input will override the setting of
+        this parameter, using brute force.
+
+    leaf_size : int, default=30
+        Leaf is size passed to :class:`BallTree` or :class:`KDTree`. This can
+        affect the speed of the construction and query, as well as the memory
+        required to store the tree. The optimal value depends on the
+        nature of the problem.
+
+    metric : str or callable, default='minkowski'
+        Metric to use for distance computation. Default is "minkowski", which
+        results in the standard Euclidean distance when p = 2. See the
+        documentation of `scipy.spatial.distance
+        `_ and
+        the metrics listed in
+        :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric
+        values.
+
+        If metric is "precomputed", X is assumed to be a distance matrix and
+        must be square during fit. X may be a :term:`sparse graph`, in which
+        case only "nonzero" elements may be considered neighbors.
+
+        If metric is a callable function, it takes two arrays representing 1D
+        vectors as inputs and must return one value indicating the distance
+        between those vectors. This works for Scipy's metrics, but is less
+        efficient than passing the metric name as a string.
+
+    p : float, default=2
+        Parameter for the Minkowski metric from
+        :func:`sklearn.metrics.pairwise_distances`. When p = 1, this
+        is equivalent to using manhattan_distance (l1), and euclidean_distance
+        (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.
+
+    metric_params : dict, default=None
+        Additional keyword arguments for the metric function.
+
+    contamination : 'auto' or float, default='auto'
+        The amount of contamination of the data set, i.e. the proportion
+        of outliers in the data set. When fitting this is used to define the
+        threshold on the scores of the samples.
+
+        - if 'auto', the threshold is determined as in the
+          original paper,
+        - if a float, the contamination should be in the range (0, 0.5].
+
+        .. versionchanged:: 0.22
+           The default value of ``contamination`` changed from 0.1
+           to ``'auto'``.
+
+    novelty : bool, default=False
+        By default, LocalOutlierFactor is only meant to be used for outlier
+        detection (novelty=False). Set novelty to True if you want to use
+        LocalOutlierFactor for novelty detection. In this case be aware that
+        you should only use predict, decision_function and score_samples
+        on new unseen data and not on the training set; and note that the
+        results obtained this way may differ from the standard LOF results.
+
+        .. versionadded:: 0.20
+
+    n_jobs : int, default=None
+        The number of parallel jobs to run for neighbors search.
+        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+        ``-1`` means using all processors. See :term:`Glossary `
+        for more details.
+
+    Attributes
+    ----------
+    negative_outlier_factor_ : ndarray of shape (n_samples,)
+        The opposite LOF of the training samples. The higher, the more normal.
+        Inliers tend to have a LOF score close to 1
+        (``negative_outlier_factor_`` close to -1), while outliers tend to have
+        a larger LOF score.
+
+        The local outlier factor (LOF) of a sample captures its
+        supposed 'degree of abnormality'.
+        It is the average of the ratio of the local reachability density of
+        a sample and those of its k-nearest neighbors.
+
+    n_neighbors_ : int
+        The actual number of neighbors used for :meth:`kneighbors` queries.
+
+    offset_ : float
+        Offset used to obtain binary labels from the raw scores.
+        Observations having a negative_outlier_factor smaller than `offset_`
+        are detected as abnormal.
+        The offset is set to -1.5 (inliers score around -1), except when a
+        contamination parameter different than "auto" is provided. In that
+        case, the offset is defined in such a way we obtain the expected
+        number of outliers in training.
+
+        .. versionadded:: 0.20
+
+    effective_metric_ : str
+        The effective metric used for the distance computation.
+
+    effective_metric_params_ : dict
+        The effective additional keyword arguments for the metric function.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    n_samples_fit_ : int
+        It is the number of samples in the fitted data.
+
+    See Also
+    --------
+    sklearn.svm.OneClassSVM: Unsupervised Outlier Detection using
+        Support Vector Machine.
+
+    References
+    ----------
+    .. [1] Breunig, M. M., Kriegel, H. P., Ng, R. T., & Sander, J. (2000, May).
+           LOF: identifying density-based local outliers. In ACM sigmod record.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from sklearn.neighbors import LocalOutlierFactor
+    >>> X = [[-1.1], [0.2], [101.1], [0.3]]
+    >>> clf = LocalOutlierFactor(n_neighbors=2)
+    >>> clf.fit_predict(X)
+    array([ 1,  1, -1,  1])
+    >>> clf.negative_outlier_factor_
+    array([ -0.9821,  -1.0370, -73.3697,  -0.9821])
+    """
+
+    _parameter_constraints: dict = {
+        **NeighborsBase._parameter_constraints,
+        "contamination": [
+            StrOptions({"auto"}),
+            Interval(Real, 0, 0.5, closed="right"),
+        ],
+        "novelty": ["boolean"],
+    }
+    _parameter_constraints.pop("radius")
+
+    def __init__(
+        self,
+        n_neighbors=20,
+        *,
+        algorithm="auto",
+        leaf_size=30,
+        metric="minkowski",
+        p=2,
+        metric_params=None,
+        contamination="auto",
+        novelty=False,
+        n_jobs=None,
+    ):
+        super().__init__(
+            n_neighbors=n_neighbors,
+            algorithm=algorithm,
+            leaf_size=leaf_size,
+            metric=metric,
+            p=p,
+            metric_params=metric_params,
+            n_jobs=n_jobs,
+        )
+        self.contamination = contamination
+        self.novelty = novelty
+
+    def _check_novelty_fit_predict(self):
+        if self.novelty:
+            msg = (
+                "fit_predict is not available when novelty=True. Use "
+                "novelty=False if you want to predict on the training set."
+            )
+            raise AttributeError(msg)
+        return True
+
+    @available_if(_check_novelty_fit_predict)
+    def fit_predict(self, X, y=None):
+        """Fit the model to the training set X and return the labels.
+
+        **Not available for novelty detection (when novelty is set to True).**
+        Label is 1 for an inlier and -1 for an outlier according to the LOF
+        score and the contamination parameter.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features), default=None
+            The query sample or samples to compute the Local Outlier Factor
+            w.r.t. the training samples.
+
+        y : Ignored
+            Not used, present for API consistency by convention.
+
+        Returns
+        -------
+        is_inlier : ndarray of shape (n_samples,)
+            Returns -1 for anomalies/outliers and 1 for inliers.
+        """
+
+        # As fit_predict would be different from fit.predict, fit_predict is
+        # only available for outlier detection (novelty=False)
+
+        return self.fit(X)._predict()
+
+    @_fit_context(
+        # LocalOutlierFactor.metric is not validated yet
+        prefer_skip_nested_validation=False
+    )
+    def fit(self, X, y=None):
+        """Fit the local outlier factor detector from the training dataset.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
+                (n_samples, n_samples) if metric='precomputed'
+            Training data.
+
+        y : Ignored
+            Not used, present for API consistency by convention.
+
+        Returns
+        -------
+        self : LocalOutlierFactor
+            The fitted local outlier factor detector.
+        """
+        self._fit(X)
+
+        n_samples = self.n_samples_fit_
+        if self.n_neighbors > n_samples:
+            warnings.warn(
+                "n_neighbors (%s) is greater than the "
+                "total number of samples (%s). n_neighbors "
+                "will be set to (n_samples - 1) for estimation."
+                % (self.n_neighbors, n_samples)
+            )
+        self.n_neighbors_ = max(1, min(self.n_neighbors, n_samples - 1))
+
+        self._distances_fit_X_, _neighbors_indices_fit_X_ = self.kneighbors(
+            n_neighbors=self.n_neighbors_
+        )
+
+        if self._fit_X.dtype == np.float32:
+            self._distances_fit_X_ = self._distances_fit_X_.astype(
+                self._fit_X.dtype,
+                copy=False,
+            )
+
+        self._lrd = self._local_reachability_density(
+            self._distances_fit_X_, _neighbors_indices_fit_X_
+        )
+
+        # Compute lof score over training samples to define offset_:
+        lrd_ratios_array = (
+            self._lrd[_neighbors_indices_fit_X_] / self._lrd[:, np.newaxis]
+        )
+
+        self.negative_outlier_factor_ = -np.mean(lrd_ratios_array, axis=1)
+
+        if self.contamination == "auto":
+            # inliers score around -1 (the higher, the less abnormal).
+            self.offset_ = -1.5
+        else:
+            self.offset_ = np.percentile(
+                self.negative_outlier_factor_, 100.0 * self.contamination
+            )
+
+        # Verify if negative_outlier_factor_ values are within acceptable range.
+        # Novelty must also be false to detect outliers
+        if np.min(self.negative_outlier_factor_) < -1e7 and not self.novelty:
+            warnings.warn(
+                "Duplicate values are leading to incorrect results. "
+                "Increase the number of neighbors for more accurate results."
+            )
+
+        return self
+
+    def _check_novelty_predict(self):
+        if not self.novelty:
+            msg = (
+                "predict is not available when novelty=False, use "
+                "fit_predict if you want to predict on training data. Use "
+                "novelty=True if you want to use LOF for novelty detection "
+                "and predict on new unseen data."
+            )
+            raise AttributeError(msg)
+        return True
+
+    @available_if(_check_novelty_predict)
+    def predict(self, X=None):
+        """Predict the labels (1 inlier, -1 outlier) of X according to LOF.
+
+        **Only available for novelty detection (when novelty is set to True).**
+        This method allows to generalize prediction to *new observations* (not
+        in the training set). Note that the result of ``clf.fit(X)`` then
+        ``clf.predict(X)`` with ``novelty=True`` may differ from the result
+        obtained by ``clf.fit_predict(X)`` with ``novelty=False``.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            The query sample or samples to compute the Local Outlier Factor
+            w.r.t. the training samples.
+
+        Returns
+        -------
+        is_inlier : ndarray of shape (n_samples,)
+            Returns -1 for anomalies/outliers and +1 for inliers.
+        """
+        return self._predict(X)
+
+    def _predict(self, X=None):
+        """Predict the labels (1 inlier, -1 outlier) of X according to LOF.
+
+        If X is None, returns the same as fit_predict(X_train).
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features), default=None
+            The query sample or samples to compute the Local Outlier Factor
+            w.r.t. the training samples. If None, makes prediction on the
+            training data without considering them as their own neighbors.
+
+        Returns
+        -------
+        is_inlier : ndarray of shape (n_samples,)
+            Returns -1 for anomalies/outliers and +1 for inliers.
+        """
+        check_is_fitted(self)
+
+        if X is not None:
+            shifted_opposite_lof_scores = self.decision_function(X)
+            is_inlier = np.ones(shifted_opposite_lof_scores.shape[0], dtype=int)
+            is_inlier[shifted_opposite_lof_scores < 0] = -1
+        else:
+            is_inlier = np.ones(self.n_samples_fit_, dtype=int)
+            is_inlier[self.negative_outlier_factor_ < self.offset_] = -1
+
+        return is_inlier
+
+    def _check_novelty_decision_function(self):
+        if not self.novelty:
+            msg = (
+                "decision_function is not available when novelty=False. "
+                "Use novelty=True if you want to use LOF for novelty "
+                "detection and compute decision_function for new unseen "
+                "data. Note that the opposite LOF of the training samples "
+                "is always available by considering the "
+                "negative_outlier_factor_ attribute."
+            )
+            raise AttributeError(msg)
+        return True
+
+    @available_if(_check_novelty_decision_function)
+    def decision_function(self, X):
+        """Shifted opposite of the Local Outlier Factor of X.
+
+        Bigger is better, i.e. large values correspond to inliers.
+
+        **Only available for novelty detection (when novelty is set to True).**
+        The shift offset allows a zero threshold for being an outlier.
+        The argument X is supposed to contain *new data*: if X contains a
+        point from training, it considers the later in its own neighborhood.
+        Also, the samples in X are not considered in the neighborhood of any
+        point.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            The query sample or samples to compute the Local Outlier Factor
+            w.r.t. the training samples.
+
+        Returns
+        -------
+        shifted_opposite_lof_scores : ndarray of shape (n_samples,)
+            The shifted opposite of the Local Outlier Factor of each input
+            samples. The lower, the more abnormal. Negative scores represent
+            outliers, positive scores represent inliers.
+        """
+        return self.score_samples(X) - self.offset_
+
+    def _check_novelty_score_samples(self):
+        if not self.novelty:
+            msg = (
+                "score_samples is not available when novelty=False. The "
+                "scores of the training samples are always available "
+                "through the negative_outlier_factor_ attribute. Use "
+                "novelty=True if you want to use LOF for novelty detection "
+                "and compute score_samples for new unseen data."
+            )
+            raise AttributeError(msg)
+        return True
+
+    @available_if(_check_novelty_score_samples)
+    def score_samples(self, X):
+        """Opposite of the Local Outlier Factor of X.
+
+        It is the opposite as bigger is better, i.e. large values correspond
+        to inliers.
+
+        **Only available for novelty detection (when novelty is set to True).**
+        The argument X is supposed to contain *new data*: if X contains a
+        point from training, it considers the later in its own neighborhood.
+        Also, the samples in X are not considered in the neighborhood of any
+        point. Because of this, the scores obtained via ``score_samples`` may
+        differ from the standard LOF scores.
+        The standard LOF scores for the training data is available via the
+        ``negative_outlier_factor_`` attribute.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            The query sample or samples to compute the Local Outlier Factor
+            w.r.t. the training samples.
+
+        Returns
+        -------
+        opposite_lof_scores : ndarray of shape (n_samples,)
+            The opposite of the Local Outlier Factor of each input samples.
+            The lower, the more abnormal.
+        """
+        check_is_fitted(self)
+        X = check_array(X, accept_sparse="csr")
+
+        distances_X, neighbors_indices_X = self.kneighbors(
+            X, n_neighbors=self.n_neighbors_
+        )
+
+        if X.dtype == np.float32:
+            distances_X = distances_X.astype(X.dtype, copy=False)
+
+        X_lrd = self._local_reachability_density(
+            distances_X,
+            neighbors_indices_X,
+        )
+
+        lrd_ratios_array = self._lrd[neighbors_indices_X] / X_lrd[:, np.newaxis]
+
+        # as bigger is better:
+        return -np.mean(lrd_ratios_array, axis=1)
+
+    def _local_reachability_density(self, distances_X, neighbors_indices):
+        """The local reachability density (LRD)
+
+        The LRD of a sample is the inverse of the average reachability
+        distance of its k-nearest neighbors.
+
+        Parameters
+        ----------
+        distances_X : ndarray of shape (n_queries, self.n_neighbors)
+            Distances to the neighbors (in the training samples `self._fit_X`)
+            of each query point to compute the LRD.
+
+        neighbors_indices : ndarray of shape (n_queries, self.n_neighbors)
+            Neighbors indices (of each query point) among training samples
+            self._fit_X.
+
+        Returns
+        -------
+        local_reachability_density : ndarray of shape (n_queries,)
+            The local reachability density of each sample.
+        """
+        dist_k = self._distances_fit_X_[neighbors_indices, self.n_neighbors_ - 1]
+        reach_dist_array = np.maximum(distances_X, dist_k)
+
+        # 1e-10 to avoid `nan' when nb of duplicates > n_neighbors_:
+        return 1.0 / (np.mean(reach_dist_array, axis=1) + 1e-10)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_nca.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_nca.py
new file mode 100644
index 0000000000000000000000000000000000000000..8383f95338932cd4a5a88fda6e5e5b9211b9ca0a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_nca.py
@@ -0,0 +1,534 @@
+"""
+Neighborhood Component Analysis
+"""
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+import sys
+import time
+from numbers import Integral, Real
+from warnings import warn
+
+import numpy as np
+from scipy.optimize import minimize
+
+from ..base import (
+    BaseEstimator,
+    ClassNamePrefixFeaturesOutMixin,
+    TransformerMixin,
+    _fit_context,
+)
+from ..decomposition import PCA
+from ..exceptions import ConvergenceWarning
+from ..metrics import pairwise_distances
+from ..preprocessing import LabelEncoder
+from ..utils._param_validation import Interval, StrOptions
+from ..utils.extmath import softmax
+from ..utils.fixes import _get_additional_lbfgs_options_dict
+from ..utils.multiclass import check_classification_targets
+from ..utils.random import check_random_state
+from ..utils.validation import check_array, check_is_fitted, validate_data
+
+
+class NeighborhoodComponentsAnalysis(
+    ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator
+):
+    """Neighborhood Components Analysis.
+
+    Neighborhood Component Analysis (NCA) is a machine learning algorithm for
+    metric learning. It learns a linear transformation in a supervised fashion
+    to improve the classification accuracy of a stochastic nearest neighbors
+    rule in the transformed space.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    n_components : int, default=None
+        Preferred dimensionality of the projected space.
+        If None it will be set to `n_features`.
+
+    init : {'auto', 'pca', 'lda', 'identity', 'random'} or ndarray of shape \
+            (n_features_a, n_features_b), default='auto'
+        Initialization of the linear transformation. Possible options are
+        `'auto'`, `'pca'`, `'lda'`, `'identity'`, `'random'`, and a numpy
+        array of shape `(n_features_a, n_features_b)`.
+
+        - `'auto'`
+            Depending on `n_components`, the most reasonable initialization
+            is chosen. If `n_components <= min(n_features, n_classes - 1)`
+            we use `'lda'`, as it uses labels information. If not, but
+            `n_components < min(n_features, n_samples)`, we use `'pca'`, as
+            it projects data in meaningful directions (those of higher
+            variance). Otherwise, we just use `'identity'`.
+
+        - `'pca'`
+            `n_components` principal components of the inputs passed
+            to :meth:`fit` will be used to initialize the transformation.
+            (See :class:`~sklearn.decomposition.PCA`)
+
+        - `'lda'`
+            `min(n_components, n_classes)` most discriminative
+            components of the inputs passed to :meth:`fit` will be used to
+            initialize the transformation. (If `n_components > n_classes`,
+            the rest of the components will be zero.) (See
+            :class:`~sklearn.discriminant_analysis.LinearDiscriminantAnalysis`)
+
+        - `'identity'`
+            If `n_components` is strictly smaller than the
+            dimensionality of the inputs passed to :meth:`fit`, the identity
+            matrix will be truncated to the first `n_components` rows.
+
+        - `'random'`
+            The initial transformation will be a random array of shape
+            `(n_components, n_features)`. Each value is sampled from the
+            standard normal distribution.
+
+        - numpy array
+            `n_features_b` must match the dimensionality of the inputs passed
+            to :meth:`fit` and n_features_a must be less than or equal to that.
+            If `n_components` is not `None`, `n_features_a` must match it.
+
+    warm_start : bool, default=False
+        If `True` and :meth:`fit` has been called before, the solution of the
+        previous call to :meth:`fit` is used as the initial linear
+        transformation (`n_components` and `init` will be ignored).
+
+    max_iter : int, default=50
+        Maximum number of iterations in the optimization.
+
+    tol : float, default=1e-5
+        Convergence tolerance for the optimization.
+
+    callback : callable, default=None
+        If not `None`, this function is called after every iteration of the
+        optimizer, taking as arguments the current solution (flattened
+        transformation matrix) and the number of iterations. This might be
+        useful in case one wants to examine or store the transformation
+        found after each iteration.
+
+    verbose : int, default=0
+        If 0, no progress messages will be printed.
+        If 1, progress messages will be printed to stdout.
+        If > 1, progress messages will be printed and the `disp`
+        parameter of :func:`scipy.optimize.minimize` will be set to
+        `verbose - 2`.
+
+    random_state : int or numpy.RandomState, default=None
+        A pseudo random number generator object or a seed for it if int. If
+        `init='random'`, `random_state` is used to initialize the random
+        transformation. If `init='pca'`, `random_state` is passed as an
+        argument to PCA when initializing the transformation. Pass an int
+        for reproducible results across multiple function calls.
+        See :term:`Glossary `.
+
+    Attributes
+    ----------
+    components_ : ndarray of shape (n_components, n_features)
+        The linear transformation learned during fitting.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    n_iter_ : int
+        Counts the number of iterations performed by the optimizer.
+
+    random_state_ : numpy.RandomState
+        Pseudo random number generator object used during initialization.
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    See Also
+    --------
+    sklearn.discriminant_analysis.LinearDiscriminantAnalysis : Linear
+        Discriminant Analysis.
+    sklearn.decomposition.PCA : Principal component analysis (PCA).
+
+    References
+    ----------
+    .. [1] J. Goldberger, G. Hinton, S. Roweis, R. Salakhutdinov.
+           "Neighbourhood Components Analysis". Advances in Neural Information
+           Processing Systems. 17, 513-520, 2005.
+           http://www.cs.nyu.edu/~roweis/papers/ncanips.pdf
+
+    .. [2] Wikipedia entry on Neighborhood Components Analysis
+           https://en.wikipedia.org/wiki/Neighbourhood_components_analysis
+
+    Examples
+    --------
+    >>> from sklearn.neighbors import NeighborhoodComponentsAnalysis
+    >>> from sklearn.neighbors import KNeighborsClassifier
+    >>> from sklearn.datasets import load_iris
+    >>> from sklearn.model_selection import train_test_split
+    >>> X, y = load_iris(return_X_y=True)
+    >>> X_train, X_test, y_train, y_test = train_test_split(X, y,
+    ... stratify=y, test_size=0.7, random_state=42)
+    >>> nca = NeighborhoodComponentsAnalysis(random_state=42)
+    >>> nca.fit(X_train, y_train)
+    NeighborhoodComponentsAnalysis(...)
+    >>> knn = KNeighborsClassifier(n_neighbors=3)
+    >>> knn.fit(X_train, y_train)
+    KNeighborsClassifier(...)
+    >>> print(knn.score(X_test, y_test))
+    0.933333...
+    >>> knn.fit(nca.transform(X_train), y_train)
+    KNeighborsClassifier(...)
+    >>> print(knn.score(nca.transform(X_test), y_test))
+    0.961904...
+    """
+
+    _parameter_constraints: dict = {
+        "n_components": [
+            Interval(Integral, 1, None, closed="left"),
+            None,
+        ],
+        "init": [
+            StrOptions({"auto", "pca", "lda", "identity", "random"}),
+            np.ndarray,
+        ],
+        "warm_start": ["boolean"],
+        "max_iter": [Interval(Integral, 1, None, closed="left")],
+        "tol": [Interval(Real, 0, None, closed="left")],
+        "callback": [callable, None],
+        "verbose": ["verbose"],
+        "random_state": ["random_state"],
+    }
+
+    def __init__(
+        self,
+        n_components=None,
+        *,
+        init="auto",
+        warm_start=False,
+        max_iter=50,
+        tol=1e-5,
+        callback=None,
+        verbose=0,
+        random_state=None,
+    ):
+        self.n_components = n_components
+        self.init = init
+        self.warm_start = warm_start
+        self.max_iter = max_iter
+        self.tol = tol
+        self.callback = callback
+        self.verbose = verbose
+        self.random_state = random_state
+
+    @_fit_context(prefer_skip_nested_validation=True)
+    def fit(self, X, y):
+        """Fit the model according to the given training data.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            The training samples.
+
+        y : array-like of shape (n_samples,)
+            The corresponding training labels.
+
+        Returns
+        -------
+        self : object
+            Fitted estimator.
+        """
+        # Validate the inputs X and y, and converts y to numerical classes.
+        X, y = validate_data(self, X, y, ensure_min_samples=2)
+        check_classification_targets(y)
+        y = LabelEncoder().fit_transform(y)
+
+        # Check the preferred dimensionality of the projected space
+        if self.n_components is not None and self.n_components > X.shape[1]:
+            raise ValueError(
+                "The preferred dimensionality of the "
+                f"projected space `n_components` ({self.n_components}) cannot "
+                "be greater than the given data "
+                f"dimensionality ({X.shape[1]})!"
+            )
+        # If warm_start is enabled, check that the inputs are consistent
+        if (
+            self.warm_start
+            and hasattr(self, "components_")
+            and self.components_.shape[1] != X.shape[1]
+        ):
+            raise ValueError(
+                f"The new inputs dimensionality ({X.shape[1]}) does not "
+                "match the input dimensionality of the "
+                f"previously learned transformation ({self.components_.shape[1]})."
+            )
+        # Check how the linear transformation should be initialized
+        init = self.init
+        if isinstance(init, np.ndarray):
+            init = check_array(init)
+            # Assert that init.shape[1] = X.shape[1]
+            if init.shape[1] != X.shape[1]:
+                raise ValueError(
+                    f"The input dimensionality ({init.shape[1]}) of the given "
+                    "linear transformation `init` must match the "
+                    f"dimensionality of the given inputs `X` ({X.shape[1]})."
+                )
+            # Assert that init.shape[0] <= init.shape[1]
+            if init.shape[0] > init.shape[1]:
+                raise ValueError(
+                    f"The output dimensionality ({init.shape[0]}) of the given "
+                    "linear transformation `init` cannot be "
+                    f"greater than its input dimensionality ({init.shape[1]})."
+                )
+            # Assert that self.n_components = init.shape[0]
+            if self.n_components is not None and self.n_components != init.shape[0]:
+                raise ValueError(
+                    "The preferred dimensionality of the "
+                    f"projected space `n_components` ({self.n_components}) does"
+                    " not match the output dimensionality of "
+                    "the given linear transformation "
+                    f"`init` ({init.shape[0]})!"
+                )
+
+        # Initialize the random generator
+        self.random_state_ = check_random_state(self.random_state)
+
+        # Measure the total training time
+        t_train = time.time()
+
+        # Compute a mask that stays fixed during optimization:
+        same_class_mask = y[:, np.newaxis] == y[np.newaxis, :]
+        # (n_samples, n_samples)
+
+        # Initialize the transformation
+        transformation = np.ravel(self._initialize(X, y, init))
+
+        # Create a dictionary of parameters to be passed to the optimizer
+        disp = self.verbose - 2 if self.verbose > 1 else -1
+        optimizer_params = {
+            "method": "L-BFGS-B",
+            "fun": self._loss_grad_lbfgs,
+            "args": (X, same_class_mask, -1.0),
+            "jac": True,
+            "x0": transformation,
+            "tol": self.tol,
+            "options": dict(
+                maxiter=self.max_iter,
+                **_get_additional_lbfgs_options_dict("disp", disp),
+            ),
+            "callback": self._callback,
+        }
+
+        # Call the optimizer
+        self.n_iter_ = 0
+        opt_result = minimize(**optimizer_params)
+
+        # Reshape the solution found by the optimizer
+        self.components_ = opt_result.x.reshape(-1, X.shape[1])
+
+        # Stop timer
+        t_train = time.time() - t_train
+        if self.verbose:
+            cls_name = self.__class__.__name__
+
+            # Warn the user if the algorithm did not converge
+            if not opt_result.success:
+                warn(
+                    "[{}] NCA did not converge: {}".format(
+                        cls_name, opt_result.message
+                    ),
+                    ConvergenceWarning,
+                )
+
+            print("[{}] Training took {:8.2f}s.".format(cls_name, t_train))
+
+        return self
+
+    def transform(self, X):
+        """Apply the learned transformation to the given data.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            Data samples.
+
+        Returns
+        -------
+        X_embedded: ndarray of shape (n_samples, n_components)
+            The data samples transformed.
+
+        Raises
+        ------
+        NotFittedError
+            If :meth:`fit` has not been called before.
+        """
+
+        check_is_fitted(self)
+        X = validate_data(self, X, reset=False)
+
+        return np.dot(X, self.components_.T)
+
+    def _initialize(self, X, y, init):
+        """Initialize the transformation.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            The training samples.
+
+        y : array-like of shape (n_samples,)
+            The training labels.
+
+        init : str or ndarray of shape (n_features_a, n_features_b)
+            The validated initialization of the linear transformation.
+
+        Returns
+        -------
+        transformation : ndarray of shape (n_components, n_features)
+            The initialized linear transformation.
+
+        """
+
+        transformation = init
+        if self.warm_start and hasattr(self, "components_"):
+            transformation = self.components_
+        elif isinstance(init, np.ndarray):
+            pass
+        else:
+            n_samples, n_features = X.shape
+            n_components = self.n_components or n_features
+            if init == "auto":
+                n_classes = len(np.unique(y))
+                if n_components <= min(n_features, n_classes - 1):
+                    init = "lda"
+                elif n_components < min(n_features, n_samples):
+                    init = "pca"
+                else:
+                    init = "identity"
+            if init == "identity":
+                transformation = np.eye(n_components, X.shape[1])
+            elif init == "random":
+                transformation = self.random_state_.standard_normal(
+                    size=(n_components, X.shape[1])
+                )
+            elif init in {"pca", "lda"}:
+                init_time = time.time()
+                if init == "pca":
+                    pca = PCA(
+                        n_components=n_components, random_state=self.random_state_
+                    )
+                    if self.verbose:
+                        print("Finding principal components... ", end="")
+                        sys.stdout.flush()
+                    pca.fit(X)
+                    transformation = pca.components_
+                elif init == "lda":
+                    from ..discriminant_analysis import LinearDiscriminantAnalysis
+
+                    lda = LinearDiscriminantAnalysis(n_components=n_components)
+                    if self.verbose:
+                        print("Finding most discriminative components... ", end="")
+                        sys.stdout.flush()
+                    lda.fit(X, y)
+                    transformation = lda.scalings_.T[:n_components]
+                if self.verbose:
+                    print("done in {:5.2f}s".format(time.time() - init_time))
+        return transformation
+
+    def _callback(self, transformation):
+        """Called after each iteration of the optimizer.
+
+        Parameters
+        ----------
+        transformation : ndarray of shape (n_components * n_features,)
+            The solution computed by the optimizer in this iteration.
+        """
+        if self.callback is not None:
+            self.callback(transformation, self.n_iter_)
+
+        self.n_iter_ += 1
+
+    def _loss_grad_lbfgs(self, transformation, X, same_class_mask, sign=1.0):
+        """Compute the loss and the loss gradient w.r.t. `transformation`.
+
+        Parameters
+        ----------
+        transformation : ndarray of shape (n_components * n_features,)
+            The raveled linear transformation on which to compute loss and
+            evaluate gradient.
+
+        X : ndarray of shape (n_samples, n_features)
+            The training samples.
+
+        same_class_mask : ndarray of shape (n_samples, n_samples)
+            A mask where `mask[i, j] == 1` if `X[i]` and `X[j]` belong
+            to the same class, and `0` otherwise.
+
+        Returns
+        -------
+        loss : float
+            The loss computed for the given transformation.
+
+        gradient : ndarray of shape (n_components * n_features,)
+            The new (flattened) gradient of the loss.
+        """
+
+        if self.n_iter_ == 0:
+            self.n_iter_ += 1
+            if self.verbose:
+                header_fields = ["Iteration", "Objective Value", "Time(s)"]
+                header_fmt = "{:>10} {:>20} {:>10}"
+                header = header_fmt.format(*header_fields)
+                cls_name = self.__class__.__name__
+                print("[{}]".format(cls_name))
+                print(
+                    "[{}] {}\n[{}] {}".format(
+                        cls_name, header, cls_name, "-" * len(header)
+                    )
+                )
+
+        t_funcall = time.time()
+
+        transformation = transformation.reshape(-1, X.shape[1])
+        X_embedded = np.dot(X, transformation.T)  # (n_samples, n_components)
+
+        # Compute softmax distances
+        p_ij = pairwise_distances(X_embedded, squared=True)
+        np.fill_diagonal(p_ij, np.inf)
+        p_ij = softmax(-p_ij)  # (n_samples, n_samples)
+
+        # Compute loss
+        masked_p_ij = p_ij * same_class_mask
+        p = np.sum(masked_p_ij, axis=1, keepdims=True)  # (n_samples, 1)
+        loss = np.sum(p)
+
+        # Compute gradient of loss w.r.t. `transform`
+        weighted_p_ij = masked_p_ij - p_ij * p
+        weighted_p_ij_sym = weighted_p_ij + weighted_p_ij.T
+        np.fill_diagonal(weighted_p_ij_sym, -weighted_p_ij.sum(axis=0))
+        gradient = 2 * X_embedded.T.dot(weighted_p_ij_sym).dot(X)
+        # time complexity of the gradient: O(n_components x n_samples x (
+        # n_samples + n_features))
+
+        if self.verbose:
+            t_funcall = time.time() - t_funcall
+            values_fmt = "[{}] {:>10} {:>20.6e} {:>10.2f}"
+            print(
+                values_fmt.format(
+                    self.__class__.__name__, self.n_iter_, loss, t_funcall
+                )
+            )
+            sys.stdout.flush()
+
+        return sign * loss, sign * gradient.ravel()
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.target_tags.required = True
+        return tags
+
+    @property
+    def _n_features_out(self):
+        """Number of transformed output features."""
+        return self.components_.shape[0]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_nearest_centroid.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_nearest_centroid.py
new file mode 100644
index 0000000000000000000000000000000000000000..a780c27587792478fcef0965127310d35238040d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_nearest_centroid.py
@@ -0,0 +1,359 @@
+"""
+Nearest Centroid Classification
+"""
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+import warnings
+from numbers import Real
+
+import numpy as np
+from scipy import sparse as sp
+
+from ..base import BaseEstimator, ClassifierMixin, _fit_context
+from ..discriminant_analysis import DiscriminantAnalysisPredictionMixin
+from ..metrics.pairwise import (
+    pairwise_distances,
+    pairwise_distances_argmin,
+)
+from ..preprocessing import LabelEncoder
+from ..utils import get_tags
+from ..utils._available_if import available_if
+from ..utils._param_validation import Interval, StrOptions
+from ..utils.multiclass import check_classification_targets
+from ..utils.sparsefuncs import csc_median_axis_0
+from ..utils.validation import check_is_fitted, validate_data
+
+
+class NearestCentroid(
+    DiscriminantAnalysisPredictionMixin, ClassifierMixin, BaseEstimator
+):
+    """Nearest centroid classifier.
+
+    Each class is represented by its centroid, with test samples classified to
+    the class with the nearest centroid.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    metric : {"euclidean", "manhattan"}, default="euclidean"
+        Metric to use for distance computation.
+
+        If `metric="euclidean"`, the centroid for the samples corresponding to each
+        class is the arithmetic mean, which minimizes the sum of squared L1 distances.
+        If `metric="manhattan"`, the centroid is the feature-wise median, which
+        minimizes the sum of L1 distances.
+
+        .. versionchanged:: 1.5
+            All metrics but `"euclidean"` and `"manhattan"` were deprecated and
+            now raise an error.
+
+        .. versionchanged:: 0.19
+            `metric='precomputed'` was deprecated and now raises an error
+
+    shrink_threshold : float, default=None
+        Threshold for shrinking centroids to remove features.
+
+    priors : {"uniform", "empirical"} or array-like of shape (n_classes,), \
+        default="uniform"
+        The class prior probabilities. By default, the class proportions are
+        inferred from the training data.
+
+        .. versionadded:: 1.6
+
+    Attributes
+    ----------
+    centroids_ : array-like of shape (n_classes, n_features)
+        Centroid of each class.
+
+    classes_ : array of shape (n_classes,)
+        The unique classes labels.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    deviations_ : ndarray of shape (n_classes, n_features)
+        Deviations (or shrinkages) of the centroids of each class from the
+        overall centroid. Equal to eq. (18.4) if `shrink_threshold=None`,
+        else (18.5) p. 653 of [2]. Can be used to identify features used
+        for classification.
+
+        .. versionadded:: 1.6
+
+    within_class_std_dev_ : ndarray of shape (n_features,)
+        Pooled or within-class standard deviation of input data.
+
+        .. versionadded:: 1.6
+
+    class_prior_ : ndarray of shape (n_classes,)
+        The class prior probabilities.
+
+        .. versionadded:: 1.6
+
+    See Also
+    --------
+    KNeighborsClassifier : Nearest neighbors classifier.
+
+    Notes
+    -----
+    When used for text classification with tf-idf vectors, this classifier is
+    also known as the Rocchio classifier.
+
+    References
+    ----------
+    [1] Tibshirani, R., Hastie, T., Narasimhan, B., & Chu, G. (2002). Diagnosis of
+    multiple cancer types by shrunken centroids of gene expression. Proceedings
+    of the National Academy of Sciences of the United States of America,
+    99(10), 6567-6572. The National Academy of Sciences.
+
+    [2] Hastie, T., Tibshirani, R., Friedman, J. (2009). The Elements of Statistical
+    Learning Data Mining, Inference, and Prediction. 2nd Edition. New York, Springer.
+
+    Examples
+    --------
+    >>> from sklearn.neighbors import NearestCentroid
+    >>> import numpy as np
+    >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
+    >>> y = np.array([1, 1, 1, 2, 2, 2])
+    >>> clf = NearestCentroid()
+    >>> clf.fit(X, y)
+    NearestCentroid()
+    >>> print(clf.predict([[-0.8, -1]]))
+    [1]
+    """
+
+    _parameter_constraints: dict = {
+        "metric": [StrOptions({"manhattan", "euclidean"})],
+        "shrink_threshold": [Interval(Real, 0, None, closed="neither"), None],
+        "priors": ["array-like", StrOptions({"empirical", "uniform"})],
+    }
+
+    def __init__(
+        self,
+        metric="euclidean",
+        *,
+        shrink_threshold=None,
+        priors="uniform",
+    ):
+        self.metric = metric
+        self.shrink_threshold = shrink_threshold
+        self.priors = priors
+
+    @_fit_context(prefer_skip_nested_validation=True)
+    def fit(self, X, y):
+        """
+        Fit the NearestCentroid model according to the given training data.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            Training vector, where `n_samples` is the number of samples and
+            `n_features` is the number of features.
+            Note that centroid shrinking cannot be used with sparse matrices.
+        y : array-like of shape (n_samples,)
+            Target values.
+
+        Returns
+        -------
+        self : object
+            Fitted estimator.
+        """
+        # If X is sparse and the metric is "manhattan", store it in a csc
+        # format is easier to calculate the median.
+        if self.metric == "manhattan":
+            X, y = validate_data(self, X, y, accept_sparse=["csc"])
+        else:
+            ensure_all_finite = (
+                "allow-nan" if get_tags(self).input_tags.allow_nan else True
+            )
+            X, y = validate_data(
+                self,
+                X,
+                y,
+                ensure_all_finite=ensure_all_finite,
+                accept_sparse=["csr", "csc"],
+            )
+        is_X_sparse = sp.issparse(X)
+        check_classification_targets(y)
+
+        n_samples, n_features = X.shape
+        le = LabelEncoder()
+        y_ind = le.fit_transform(y)
+        self.classes_ = classes = le.classes_
+        n_classes = classes.size
+        if n_classes < 2:
+            raise ValueError(
+                "The number of classes has to be greater than one; got %d class"
+                % (n_classes)
+            )
+
+        if self.priors == "empirical":  # estimate priors from sample
+            _, class_counts = np.unique(y, return_inverse=True)  # non-negative ints
+            self.class_prior_ = np.bincount(class_counts) / float(len(y))
+        elif self.priors == "uniform":
+            self.class_prior_ = np.asarray([1 / n_classes] * n_classes)
+        else:
+            self.class_prior_ = np.asarray(self.priors)
+
+        if (self.class_prior_ < 0).any():
+            raise ValueError("priors must be non-negative")
+        if not np.isclose(self.class_prior_.sum(), 1.0):
+            warnings.warn(
+                "The priors do not sum to 1. Normalizing such that it sums to one.",
+                UserWarning,
+            )
+            self.class_prior_ = self.class_prior_ / self.class_prior_.sum()
+
+        # Mask mapping each class to its members.
+        self.centroids_ = np.empty((n_classes, n_features), dtype=np.float64)
+
+        # Number of clusters in each class.
+        nk = np.zeros(n_classes)
+
+        for cur_class in range(n_classes):
+            center_mask = y_ind == cur_class
+            nk[cur_class] = np.sum(center_mask)
+            if is_X_sparse:
+                center_mask = np.where(center_mask)[0]
+
+            if self.metric == "manhattan":
+                # NumPy does not calculate median of sparse matrices.
+                if not is_X_sparse:
+                    self.centroids_[cur_class] = np.median(X[center_mask], axis=0)
+                else:
+                    self.centroids_[cur_class] = csc_median_axis_0(X[center_mask])
+            else:  # metric == "euclidean"
+                self.centroids_[cur_class] = X[center_mask].mean(axis=0)
+
+        # Compute within-class std_dev with unshrunked centroids
+        variance = np.array(X - self.centroids_[y_ind], copy=False) ** 2
+        self.within_class_std_dev_ = np.array(
+            np.sqrt(variance.sum(axis=0) / (n_samples - n_classes)), copy=False
+        )
+        if any(self.within_class_std_dev_ == 0):
+            warnings.warn(
+                "self.within_class_std_dev_ has at least 1 zero standard deviation."
+                "Inputs within the same classes for at least 1 feature are identical."
+            )
+
+        err_msg = "All features have zero variance. Division by zero."
+        if is_X_sparse and np.all((X.max(axis=0) - X.min(axis=0)).toarray() == 0):
+            raise ValueError(err_msg)
+        elif not is_X_sparse and np.all(np.ptp(X, axis=0) == 0):
+            raise ValueError(err_msg)
+
+        dataset_centroid_ = X.mean(axis=0)
+        # m parameter for determining deviation
+        m = np.sqrt((1.0 / nk) - (1.0 / n_samples))
+        # Calculate deviation using the standard deviation of centroids.
+        # To deter outliers from affecting the results.
+        s = self.within_class_std_dev_ + np.median(self.within_class_std_dev_)
+        mm = m.reshape(len(m), 1)  # Reshape to allow broadcasting.
+        ms = mm * s
+        self.deviations_ = np.array(
+            (self.centroids_ - dataset_centroid_) / ms, copy=False
+        )
+        # Soft thresholding: if the deviation crosses 0 during shrinking,
+        # it becomes zero.
+        if self.shrink_threshold:
+            signs = np.sign(self.deviations_)
+            self.deviations_ = np.abs(self.deviations_) - self.shrink_threshold
+            np.clip(self.deviations_, 0, None, out=self.deviations_)
+            self.deviations_ *= signs
+            # Now adjust the centroids using the deviation
+            msd = ms * self.deviations_
+            self.centroids_ = np.array(dataset_centroid_ + msd, copy=False)
+        return self
+
+    def predict(self, X):
+        """Perform classification on an array of test vectors `X`.
+
+        The predicted class `C` for each sample in `X` is returned.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            Input data.
+
+        Returns
+        -------
+        y_pred : ndarray of shape (n_samples,)
+            The predicted classes.
+        """
+        check_is_fitted(self)
+        if np.isclose(self.class_prior_, 1 / len(self.classes_)).all():
+            # `validate_data` is called here since we are not calling `super()`
+            ensure_all_finite = (
+                "allow-nan" if get_tags(self).input_tags.allow_nan else True
+            )
+            X = validate_data(
+                self,
+                X,
+                ensure_all_finite=ensure_all_finite,
+                accept_sparse="csr",
+                reset=False,
+            )
+            return self.classes_[
+                pairwise_distances_argmin(X, self.centroids_, metric=self.metric)
+            ]
+        else:
+            return super().predict(X)
+
+    def _decision_function(self, X):
+        # return discriminant scores, see eq. (18.2) p. 652 of the ESL.
+        check_is_fitted(self, "centroids_")
+
+        X_normalized = validate_data(
+            self, X, copy=True, reset=False, accept_sparse="csr", dtype=np.float64
+        )
+
+        discriminant_score = np.empty(
+            (X_normalized.shape[0], self.classes_.size), dtype=np.float64
+        )
+
+        mask = self.within_class_std_dev_ != 0
+        X_normalized[:, mask] /= self.within_class_std_dev_[mask]
+        centroids_normalized = self.centroids_.copy()
+        centroids_normalized[:, mask] /= self.within_class_std_dev_[mask]
+
+        for class_idx in range(self.classes_.size):
+            distances = pairwise_distances(
+                X_normalized, centroids_normalized[[class_idx]], metric=self.metric
+            ).ravel()
+            distances **= 2
+            discriminant_score[:, class_idx] = np.squeeze(
+                -distances + 2.0 * np.log(self.class_prior_[class_idx])
+            )
+
+        return discriminant_score
+
+    def _check_euclidean_metric(self):
+        return self.metric == "euclidean"
+
+    decision_function = available_if(_check_euclidean_metric)(
+        DiscriminantAnalysisPredictionMixin.decision_function
+    )
+
+    predict_proba = available_if(_check_euclidean_metric)(
+        DiscriminantAnalysisPredictionMixin.predict_proba
+    )
+
+    predict_log_proba = available_if(_check_euclidean_metric)(
+        DiscriminantAnalysisPredictionMixin.predict_log_proba
+    )
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.input_tags.allow_nan = self.metric == "nan_euclidean"
+        tags.input_tags.sparse = True
+        return tags
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_partition_nodes.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_partition_nodes.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..16d0fa305b66c2ccf6a57a23e285e8f3c6d5b4ae
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_partition_nodes.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_partition_nodes.pxd b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_partition_nodes.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..bd2160cc3b26f4eaf0821735aeb278fd3a16eb15
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_partition_nodes.pxd
@@ -0,0 +1,10 @@
+from cython cimport floating
+from ..utils._typedefs cimport float64_t, intp_t
+
+cdef int partition_node_indices(
+        const floating *data,
+        intp_t *node_indices,
+        intp_t split_dim,
+        intp_t split_index,
+        intp_t n_features,
+        intp_t n_points) except -1
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_partition_nodes.pyx b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_partition_nodes.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..111353c49a22becb74cf2d3d609241d208784508
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_partition_nodes.pyx
@@ -0,0 +1,122 @@
+# BinaryTrees rely on partial sorts to partition their nodes during their
+# initialisation.
+#
+# The C++ std library exposes nth_element, an efficient partial sort for this
+# situation which has a linear time complexity as well as the best performances.
+#
+# To use std::algorithm::nth_element, a few fixture are defined using Cython:
+# - partition_node_indices, a Cython function used in BinaryTrees, that calls
+# - partition_node_indices_inner, a C++ function that wraps nth_element and uses
+# - an IndexComparator to state how to compare KDTrees' indices
+#
+# IndexComparator has been defined so that partial sorts are stable with
+# respect to the nodes initial indices.
+#
+# See for reference:
+#  - https://en.cppreference.com/w/cpp/algorithm/nth_element.
+#  - https://github.com/scikit-learn/scikit-learn/pull/11103
+#  - https://github.com/scikit-learn/scikit-learn/pull/19473
+from cython cimport floating
+
+
+cdef extern from *:
+    """
+    #include 
+
+    template
+    class IndexComparator {
+    private:
+        const D *data;
+        I split_dim, n_features;
+    public:
+        IndexComparator(const D *data, const I &split_dim, const I &n_features):
+            data(data), split_dim(split_dim), n_features(n_features) {}
+
+        bool operator()(const I &a, const I &b) const {
+            D a_value = data[a * n_features + split_dim];
+            D b_value = data[b * n_features + split_dim];
+            return a_value == b_value ? a < b : a_value < b_value;
+        }
+    };
+
+    template
+    void partition_node_indices_inner(
+        const D *data,
+        I *node_indices,
+        const I &split_dim,
+        const I &split_index,
+        const I &n_features,
+        const I &n_points) {
+        IndexComparator index_comparator(data, split_dim, n_features);
+        std::nth_element(
+            node_indices,
+            node_indices + split_index,
+            node_indices + n_points,
+            index_comparator);
+    }
+    """
+    void partition_node_indices_inner[D, I](
+                const D *data,
+                I *node_indices,
+                I split_dim,
+                I split_index,
+                I n_features,
+                I n_points) except +
+
+
+cdef int partition_node_indices(
+        const floating *data,
+        intp_t *node_indices,
+        intp_t split_dim,
+        intp_t split_index,
+        intp_t n_features,
+        intp_t n_points) except -1:
+    """Partition points in the node into two equal-sized groups.
+
+    Upon return, the values in node_indices will be rearranged such that
+    (assuming numpy-style indexing):
+
+        data[node_indices[0:split_index], split_dim]
+          <= data[node_indices[split_index], split_dim]
+
+    and
+
+        data[node_indices[split_index], split_dim]
+          <= data[node_indices[split_index:n_points], split_dim]
+
+    The algorithm is essentially a partial in-place quicksort around a
+    set pivot.
+
+    Parameters
+    ----------
+    data : double pointer
+        Pointer to a 2D array of the training data, of shape [N, n_features].
+        N must be greater than any of the values in node_indices.
+    node_indices : int pointer
+        Pointer to a 1D array of length n_points.  This lists the indices of
+        each of the points within the current node.  This will be modified
+        in-place.
+    split_dim : int
+        the dimension on which to split.  This will usually be computed via
+        the routine ``find_node_split_dim``.
+    split_index : int
+        the index within node_indices around which to split the points.
+    n_features: int
+        the number of features (i.e columns) in the 2D array pointed by data.
+    n_points : int
+        the length of node_indices. This is also the number of points in
+        the original dataset.
+    Returns
+    -------
+    status : int
+        integer exit status.  On return, the contents of node_indices are
+        modified as noted above.
+    """
+    partition_node_indices_inner(
+        data,
+        node_indices,
+        split_dim,
+        split_index,
+        n_features,
+        n_points)
+    return 0
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_quad_tree.pxd b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_quad_tree.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..e7e817902f103fe6e42f37516e56ad273884c507
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_quad_tree.pxd
@@ -0,0 +1,92 @@
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+# See quad_tree.pyx for details.
+
+cimport numpy as cnp
+from ..utils._typedefs cimport float32_t, intp_t
+
+# This is effectively an ifdef statement in Cython
+# It allows us to write printf debugging lines
+# and remove them at compile time
+cdef enum:
+    DEBUGFLAG = 0
+
+cdef float EPSILON = 1e-6
+
+# XXX: Careful to not change the order of the arguments. It is important to
+# have is_leaf and max_width consecutive as it permits to avoid padding by
+# the compiler and keep the size coherent for both C and numpy data structures.
+cdef struct Cell:
+    # Base storage structure for cells in a QuadTree object
+
+    # Tree structure
+    intp_t parent                # Parent cell of this cell
+    intp_t[8] children           # Array pointing to children of this cell
+
+    # Cell description
+    intp_t cell_id               # Id of the cell in the cells array in the Tree
+    intp_t point_index           # Index of the point at this cell (only defined
+    #                            # in non empty leaf)
+    bint is_leaf                 # Does this cell have children?
+    float32_t squared_max_width  # Squared value of the maximum width w
+    intp_t depth                 # Depth of the cell in the tree
+    intp_t cumulative_size       # Number of points included in the subtree with
+    #                            # this cell as a root.
+
+    # Internal constants
+    float32_t[3] center          # Store the center for quick split of cells
+    float32_t[3] barycenter      # Keep track of the center of mass of the cell
+
+    # Cell boundaries
+    float32_t[3] min_bounds      # Inferior boundaries of this cell (inclusive)
+    float32_t[3] max_bounds      # Superior boundaries of this cell (exclusive)
+
+
+cdef class _QuadTree:
+    # The QuadTree object is a quad tree structure constructed by inserting
+    # recursively points in the tree and splitting cells in 4 so that each
+    # leaf cell contains at most one point.
+    # This structure also handle 3D data, inserted in trees with 8 children
+    # for each node.
+
+    # Parameters of the tree
+    cdef public int n_dimensions         # Number of dimensions in X
+    cdef public int verbose              # Verbosity of the output
+    cdef intp_t n_cells_per_cell         # Number of children per node. (2 ** n_dimension)
+
+    # Tree inner structure
+    cdef public intp_t max_depth         # Max depth of the tree
+    cdef public intp_t cell_count        # Counter for node IDs
+    cdef public intp_t capacity          # Capacity of tree, in terms of nodes
+    cdef public intp_t n_points          # Total number of points
+    cdef Cell* cells                     # Array of nodes
+
+    # Point insertion methods
+    cdef int insert_point(self, float32_t[3] point, intp_t point_index,
+                          intp_t cell_id=*) except -1 nogil
+    cdef intp_t _insert_point_in_new_child(self, float32_t[3] point, Cell* cell,
+                                           intp_t point_index, intp_t size=*
+                                           ) noexcept nogil
+    cdef intp_t _select_child(self, float32_t[3] point, Cell* cell) noexcept nogil
+    cdef bint _is_duplicate(self, float32_t[3] point1, float32_t[3] point2) noexcept nogil
+
+    # Create a summary of the Tree compare to a query point
+    cdef long summarize(self, float32_t[3] point, float32_t* results,
+                        float squared_theta=*, intp_t cell_id=*, long idx=*
+                        ) noexcept nogil
+
+    # Internal cell initialization methods
+    cdef void _init_cell(self, Cell* cell, intp_t parent, intp_t depth) noexcept nogil
+    cdef void _init_root(self, float32_t[3] min_bounds, float32_t[3] max_bounds
+                         ) noexcept nogil
+
+    # Private methods
+    cdef int _check_point_in_cell(self, float32_t[3] point, Cell* cell
+                                  ) except -1 nogil
+
+    # Private array manipulation to manage the ``cells`` array
+    cdef int _resize(self, intp_t capacity) except -1 nogil
+    cdef int _resize_c(self, intp_t capacity=*) except -1 nogil
+    cdef int _get_cell(self, float32_t[3] point, intp_t cell_id=*) except -1 nogil
+    cdef Cell[:] _get_cell_ndarray(self)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_quad_tree.pyx b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_quad_tree.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..aec79da505f52b9620568b3dd7c329a144259a76
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_quad_tree.pyx
@@ -0,0 +1,609 @@
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+
+from cpython cimport Py_INCREF, PyObject, PyTypeObject
+
+from libc.math cimport fabsf
+from libc.stdlib cimport free
+from libc.string cimport memcpy
+from libc.stdio cimport printf
+from libc.stdint cimport SIZE_MAX
+
+from ..tree._utils cimport safe_realloc
+
+import numpy as np
+cimport numpy as cnp
+cnp.import_array()
+
+cdef extern from "numpy/arrayobject.h":
+    object PyArray_NewFromDescr(PyTypeObject* subtype, cnp.dtype descr,
+                                int nd, cnp.npy_intp* dims,
+                                cnp.npy_intp* strides,
+                                void* data, int flags, object obj)
+    int PyArray_SetBaseObject(cnp.ndarray arr, PyObject* obj)
+
+# Build the corresponding numpy dtype for Cell.
+# This works by casting `dummy` to an array of Cell of length 1, which numpy
+# can construct a `dtype`-object for. See https://stackoverflow.com/q/62448946
+# for a more detailed explanation.
+cdef Cell dummy
+CELL_DTYPE = np.asarray((&dummy)).dtype
+
+assert CELL_DTYPE.itemsize == sizeof(Cell)
+
+
+cdef class _QuadTree:
+    """Array-based representation of a QuadTree.
+
+    This class is currently working for indexing 2D data (regular QuadTree) and
+    for indexing 3D data (OcTree). It is planned to split the 2 implementations
+    using `Cython.Tempita` to save some memory for QuadTree.
+
+    Note that this code is currently internally used only by the Barnes-Hut
+    method in `sklearn.manifold.TSNE`. It is planned to be refactored and
+    generalized in the future to be compatible with nearest neighbors API of
+    `sklearn.neighbors` with 2D and 3D data.
+    """
+    def __cinit__(self, int n_dimensions, int verbose):
+        """Constructor."""
+        # Parameters of the tree
+        self.n_dimensions = n_dimensions
+        self.verbose = verbose
+        self.n_cells_per_cell =  (2 ** self.n_dimensions)
+
+        # Inner structures
+        self.max_depth = 0
+        self.cell_count = 0
+        self.capacity = 0
+        self.n_points = 0
+        self.cells = NULL
+
+    def __dealloc__(self):
+        """Destructor."""
+        # Free all inner structures
+        free(self.cells)
+
+    @property
+    def cumulative_size(self):
+        cdef Cell[:] cell_mem_view = self._get_cell_ndarray()
+        return cell_mem_view.base['cumulative_size'][:self.cell_count]
+
+    @property
+    def leafs(self):
+        cdef Cell[:] cell_mem_view = self._get_cell_ndarray()
+        return cell_mem_view.base['is_leaf'][:self.cell_count]
+
+    def build_tree(self, X):
+        """Build a tree from an array of points X."""
+        cdef:
+            int i
+            float32_t[3] pt
+            float32_t[3] min_bounds, max_bounds
+
+        # validate X and prepare for query
+        # X = check_array(X, dtype=float32_t, order='C')
+        n_samples = X.shape[0]
+
+        capacity = 100
+        self._resize(capacity)
+        m = np.min(X, axis=0)
+        M = np.max(X, axis=0)
+        # Scale the maximum to get all points strictly in the tree bounding box
+        # The 3 bounds are for positive, negative and small values
+        M = np.maximum(M * (1. + 1e-3 * np.sign(M)), M + 1e-3)
+        for i in range(self.n_dimensions):
+            min_bounds[i] = m[i]
+            max_bounds[i] = M[i]
+
+            if self.verbose > 10:
+                printf("[QuadTree] bounding box axis %i : [%f, %f]\n",
+                       i, min_bounds[i], max_bounds[i])
+
+        # Create the initial node with boundaries from the dataset
+        self._init_root(min_bounds, max_bounds)
+
+        for i in range(n_samples):
+            for j in range(self.n_dimensions):
+                pt[j] = X[i, j]
+            self.insert_point(pt, i)
+
+        # Shrink the cells array to reduce memory usage
+        self._resize(capacity=self.cell_count)
+
+    cdef int insert_point(self, float32_t[3] point, intp_t point_index,
+                          intp_t cell_id=0) except -1 nogil:
+        """Insert a point in the QuadTree."""
+        cdef int ax
+        cdef intp_t selected_child
+        cdef Cell* cell = &self.cells[cell_id]
+        cdef intp_t n_point = cell.cumulative_size
+
+        if self.verbose > 10:
+            printf("[QuadTree] Inserting depth %li\n", cell.depth)
+
+        # Assert that the point is in the right range
+        if DEBUGFLAG:
+            self._check_point_in_cell(point, cell)
+
+        # If the cell is an empty leaf, insert the point in it
+        if cell.cumulative_size == 0:
+            cell.cumulative_size = 1
+            self.n_points += 1
+            for i in range(self.n_dimensions):
+                cell.barycenter[i] = point[i]
+            cell.point_index = point_index
+            if self.verbose > 10:
+                printf("[QuadTree] inserted point %li in cell %li\n",
+                       point_index, cell_id)
+            return cell_id
+
+        # If the cell is not a leaf, update cell internals and
+        # recurse in selected child
+        if not cell.is_leaf:
+            for ax in range(self.n_dimensions):
+                # barycenter update using a weighted mean
+                cell.barycenter[ax] = (
+                    n_point * cell.barycenter[ax] + point[ax]) / (n_point + 1)
+
+            # Increase the size of the subtree starting from this cell
+            cell.cumulative_size += 1
+
+            # Insert child in the correct subtree
+            selected_child = self._select_child(point, cell)
+            if self.verbose > 49:
+                printf("[QuadTree] selected child %li\n", selected_child)
+            if selected_child == -1:
+                self.n_points += 1
+                return self._insert_point_in_new_child(point, cell, point_index)
+            return self.insert_point(point, point_index, selected_child)
+
+        # Finally, if the cell is a leaf with a point already inserted,
+        # split the cell in n_cells_per_cell if the point is not a duplicate.
+        # If it is a duplicate, increase the size of the leaf and return.
+        if self._is_duplicate(point, cell.barycenter):
+            if self.verbose > 10:
+                printf("[QuadTree] found a duplicate!\n")
+            cell.cumulative_size += 1
+            self.n_points += 1
+            return cell_id
+
+        # In a leaf, the barycenter correspond to the only point included
+        # in it.
+        self._insert_point_in_new_child(cell.barycenter, cell, cell.point_index,
+                                        cell.cumulative_size)
+        return self.insert_point(point, point_index, cell_id)
+
+    # XXX: This operation is not Thread safe
+    cdef intp_t _insert_point_in_new_child(
+        self, float32_t[3] point, Cell* cell, intp_t point_index, intp_t size=1
+    ) noexcept nogil:
+        """Create a child of cell which will contain point."""
+
+        # Local variable definition
+        cdef:
+            intp_t cell_id, cell_child_id, parent_id
+            float32_t[3] save_point
+            float32_t width
+            Cell* child
+            int i
+
+        # If the maximal capacity of the Tree have been reached, double the capacity
+        # We need to save the current cell id and the current point to retrieve them
+        # in case the reallocation
+        if self.cell_count + 1 > self.capacity:
+            parent_id = cell.cell_id
+            for i in range(self.n_dimensions):
+                save_point[i] = point[i]
+            self._resize(SIZE_MAX)
+            cell = &self.cells[parent_id]
+            point = save_point
+
+        # Get an empty cell and initialize it
+        cell_id = self.cell_count
+        self.cell_count += 1
+        child = &self.cells[cell_id]
+
+        self._init_cell(child, cell.cell_id, cell.depth + 1)
+        child.cell_id = cell_id
+
+        # Set the cell as an inner cell of the Tree
+        cell.is_leaf = False
+        cell.point_index = -1
+
+        # Set the correct boundary for the cell, store the point in the cell
+        # and compute its index in the children array.
+        cell_child_id = 0
+        for i in range(self.n_dimensions):
+            cell_child_id *= 2
+            if point[i] >= cell.center[i]:
+                cell_child_id += 1
+                child.min_bounds[i] = cell.center[i]
+                child.max_bounds[i] = cell.max_bounds[i]
+            else:
+                child.min_bounds[i] = cell.min_bounds[i]
+                child.max_bounds[i] = cell.center[i]
+            child.center[i] = (child.min_bounds[i] + child.max_bounds[i]) / 2.
+            width = child.max_bounds[i] - child.min_bounds[i]
+
+            child.barycenter[i] = point[i]
+            child.squared_max_width = max(child.squared_max_width, width*width)
+
+        # Store the point info and the size to account for duplicated points
+        child.point_index = point_index
+        child.cumulative_size = size
+
+        # Store the child cell in the correct place in children
+        cell.children[cell_child_id] = child.cell_id
+
+        if DEBUGFLAG:
+            # Assert that the point is in the right range
+            self._check_point_in_cell(point, child)
+        if self.verbose > 10:
+            printf("[QuadTree] inserted point %li in new child %li\n",
+                   point_index, cell_id)
+
+        return cell_id
+
+    cdef bint _is_duplicate(self, float32_t[3] point1, float32_t[3] point2) noexcept nogil:
+        """Check if the two given points are equals."""
+        cdef int i
+        cdef bint res = True
+        for i in range(self.n_dimensions):
+            # Use EPSILON to avoid numerical error that would overgrow the tree
+            res &= fabsf(point1[i] - point2[i]) <= EPSILON
+        return res
+
+    cdef intp_t _select_child(self, float32_t[3] point, Cell* cell) noexcept nogil:
+        """Select the child of cell which contains the given query point."""
+        cdef:
+            int i
+            intp_t selected_child = 0
+
+        for i in range(self.n_dimensions):
+            # Select the correct child cell to insert the point by comparing
+            # it to the borders of the cells using precomputed center.
+            selected_child *= 2
+            if point[i] >= cell.center[i]:
+                selected_child += 1
+        return cell.children[selected_child]
+
+    cdef void _init_cell(self, Cell* cell, intp_t parent, intp_t depth) noexcept nogil:
+        """Initialize a cell structure with some constants."""
+        cell.parent = parent
+        cell.is_leaf = True
+        cell.depth = depth
+        cell.squared_max_width = 0
+        cell.cumulative_size = 0
+        for i in range(self.n_cells_per_cell):
+            cell.children[i] = SIZE_MAX
+
+    cdef void _init_root(self, float32_t[3] min_bounds, float32_t[3] max_bounds
+                         ) noexcept nogil:
+        """Initialize the root node with the given space boundaries"""
+        cdef:
+            int i
+            float32_t width
+            Cell* root = &self.cells[0]
+
+        self._init_cell(root, -1, 0)
+        for i in range(self.n_dimensions):
+            root.min_bounds[i] = min_bounds[i]
+            root.max_bounds[i] = max_bounds[i]
+            root.center[i] = (max_bounds[i] + min_bounds[i]) / 2.
+            width = max_bounds[i] - min_bounds[i]
+            root.squared_max_width = max(root.squared_max_width, width*width)
+        root.cell_id = 0
+
+        self.cell_count += 1
+
+    cdef int _check_point_in_cell(self, float32_t[3] point, Cell* cell
+                                  ) except -1 nogil:
+        """Check that the given point is in the cell boundaries."""
+
+        if self.verbose >= 50:
+            if self.n_dimensions == 3:
+                printf("[QuadTree] Checking point (%f, %f, %f) in cell %li "
+                       "([%f/%f, %f/%f, %f/%f], size %li)\n",
+                       point[0], point[1], point[2], cell.cell_id,
+                       cell.min_bounds[0], cell.max_bounds[0], cell.min_bounds[1],
+                       cell.max_bounds[1], cell.min_bounds[2], cell.max_bounds[2],
+                       cell.cumulative_size)
+            else:
+                printf("[QuadTree] Checking point (%f, %f) in cell %li "
+                       "([%f/%f, %f/%f], size %li)\n",
+                       point[0], point[1], cell.cell_id, cell.min_bounds[0],
+                       cell.max_bounds[0], cell.min_bounds[1],
+                       cell.max_bounds[1], cell.cumulative_size)
+
+        for i in range(self.n_dimensions):
+            if (cell.min_bounds[i] > point[i] or
+                    cell.max_bounds[i] <= point[i]):
+                with gil:
+                    msg = "[QuadTree] InsertionError: point out of cell "
+                    msg += "boundary.\nAxis %li: cell [%f, %f]; point %f\n"
+
+                    msg %= i, cell.min_bounds[i],  cell.max_bounds[i], point[i]
+                    raise ValueError(msg)
+
+    def _check_coherence(self):
+        """Check the coherence of the cells of the tree.
+
+        Check that the info stored in each cell is compatible with the info
+        stored in descendent and sibling cells. Raise a ValueError if this
+        fails.
+        """
+        for cell in self.cells[:self.cell_count]:
+            # Check that the barycenter of inserted point is within the cell
+            # boundaries
+            self._check_point_in_cell(cell.barycenter, &cell)
+
+            if not cell.is_leaf:
+                # Compute the number of point in children and compare with
+                # its cummulative_size.
+                n_points = 0
+                for idx in range(self.n_cells_per_cell):
+                    child_id = cell.children[idx]
+                    if child_id != -1:
+                        child = self.cells[child_id]
+                        n_points += child.cumulative_size
+                        assert child.cell_id == child_id, (
+                            "Cell id not correctly initialized.")
+                if n_points != cell.cumulative_size:
+                    raise ValueError(
+                        "Cell {} is incoherent. Size={} but found {} points "
+                        "in children. ({})"
+                        .format(cell.cell_id, cell.cumulative_size,
+                                n_points, cell.children))
+
+        # Make sure that the number of point in the tree correspond to the
+        # cumulative size in root cell.
+        if self.n_points != self.cells[0].cumulative_size:
+            raise ValueError(
+                "QuadTree is incoherent. Size={} but found {} points "
+                "in children."
+                .format(self.n_points, self.cells[0].cumulative_size))
+
+    cdef long summarize(self, float32_t[3] point, float32_t* results,
+                        float squared_theta=.5, intp_t cell_id=0, long idx=0
+                        ) noexcept nogil:
+        """Summarize the tree compared to a query point.
+
+        Input arguments
+        ---------------
+        point : array (n_dimensions)
+             query point to construct the summary.
+        cell_id : integer, optional (default: 0)
+            current cell of the tree summarized. This should be set to 0 for
+            external calls.
+        idx : integer, optional (default: 0)
+            current index in the result array. This should be set to 0 for
+            external calls
+        squared_theta: float, optional (default: .5)
+            threshold to decide whether the node is sufficiently far
+            from the query point to be a good summary. The formula is such that
+            the node is a summary if
+                node_width^2 / dist_node_point^2 < squared_theta.
+            Note that the argument should be passed as theta^2 to avoid
+            computing square roots of the distances.
+
+        Output arguments
+        ----------------
+        results : array (n_samples * (n_dimensions+2))
+            result will contain a summary of the tree information compared to
+            the query point:
+            - results[idx:idx+n_dimensions] contains the coordinate-wise
+                difference between the query point and the summary cell idx.
+                This is useful in t-SNE to compute the negative forces.
+            - result[idx+n_dimensions+1] contains the squared euclidean
+                distance to the summary cell idx.
+            - result[idx+n_dimensions+2] contains the number of point of the
+                tree contained in the summary cell idx.
+
+        Return
+        ------
+        idx : integer
+            number of elements in the results array.
+        """
+        cdef:
+            int i, idx_d = idx + self.n_dimensions
+            bint duplicate = True
+            Cell* cell = &self.cells[cell_id]
+
+        results[idx_d] = 0.
+        for i in range(self.n_dimensions):
+            results[idx + i] = point[i] - cell.barycenter[i]
+            results[idx_d] += results[idx + i] * results[idx + i]
+            duplicate &= fabsf(results[idx + i]) <= EPSILON
+
+        # Do not compute self interactions
+        if duplicate and cell.is_leaf:
+            return idx
+
+        # Check whether we can use this node as a summary
+        # It's a summary node if the angular size as measured from the point
+        # is relatively small (w.r.t. theta) or if it is a leaf node.
+        # If it can be summarized, we use the cell center of mass
+        # Otherwise, we go a higher level of resolution and into the leaves.
+        if cell.is_leaf or (
+                (cell.squared_max_width / results[idx_d]) < squared_theta):
+            results[idx_d + 1] =  cell.cumulative_size
+            return idx + self.n_dimensions + 2
+
+        else:
+            # Recursively compute the summary in nodes
+            for c in range(self.n_cells_per_cell):
+                child_id = cell.children[c]
+                if child_id != -1:
+                    idx = self.summarize(point, results, squared_theta,
+                                         child_id, idx)
+
+        return idx
+
+    def get_cell(self, point):
+        """return the id of the cell containing the query point or raise
+        ValueError if the point is not in the tree
+        """
+        cdef float32_t[3] query_pt
+        cdef int i
+
+        assert len(point) == self.n_dimensions, (
+            "Query point should be a point in dimension {}."
+            .format(self.n_dimensions))
+
+        for i in range(self.n_dimensions):
+            query_pt[i] = point[i]
+
+        return self._get_cell(query_pt, 0)
+
+    cdef int _get_cell(self, float32_t[3] point, intp_t cell_id=0
+                       ) except -1 nogil:
+        """guts of get_cell.
+
+        Return the id of the cell containing the query point or raise ValueError
+        if the point is not in the tree"""
+        cdef:
+            intp_t selected_child
+            Cell* cell = &self.cells[cell_id]
+
+        if cell.is_leaf:
+            if self._is_duplicate(cell.barycenter, point):
+                if self.verbose > 99:
+                    printf("[QuadTree] Found point in cell: %li\n",
+                           cell.cell_id)
+                return cell_id
+            with gil:
+                raise ValueError("Query point not in the Tree.")
+
+        selected_child = self._select_child(point, cell)
+        if selected_child > 0:
+            if self.verbose > 99:
+                printf("[QuadTree] Selected_child: %li\n", selected_child)
+            return self._get_cell(point, selected_child)
+        with gil:
+            raise ValueError("Query point not in the Tree.")
+
+    # Pickling primitives
+
+    def __reduce__(self):
+        """Reduce re-implementation, for pickling."""
+        return (_QuadTree, (self.n_dimensions, self.verbose), self.__getstate__())
+
+    def __getstate__(self):
+        """Getstate re-implementation, for pickling."""
+        d = {}
+        # capacity is inferred during the __setstate__ using nodes
+        d["max_depth"] = self.max_depth
+        d["cell_count"] = self.cell_count
+        d["capacity"] = self.capacity
+        d["n_points"] = self.n_points
+        d["cells"] = self._get_cell_ndarray().base
+        return d
+
+    def __setstate__(self, d):
+        """Setstate re-implementation, for unpickling."""
+        self.max_depth = d["max_depth"]
+        self.cell_count = d["cell_count"]
+        self.capacity = d["capacity"]
+        self.n_points = d["n_points"]
+
+        if 'cells' not in d:
+            raise ValueError('You have loaded Tree version which '
+                             'cannot be imported')
+
+        cell_ndarray = d['cells']
+
+        if (cell_ndarray.ndim != 1 or
+                cell_ndarray.dtype != CELL_DTYPE or
+                not cell_ndarray.flags.c_contiguous):
+            raise ValueError('Did not recognise loaded array layout')
+
+        self.capacity = cell_ndarray.shape[0]
+        if self._resize_c(self.capacity) != 0:
+            raise MemoryError("resizing tree to %d" % self.capacity)
+
+        cdef Cell[:] cell_mem_view = cell_ndarray
+        memcpy(
+            pto=self.cells,
+            pfrom=&cell_mem_view[0],
+            size=self.capacity * sizeof(Cell),
+        )
+
+    # Array manipulation methods, to convert it to numpy or to resize
+    # self.cells array
+
+    cdef Cell[:] _get_cell_ndarray(self):
+        """Wraps nodes as a NumPy struct array.
+
+        The array keeps a reference to this Tree, which manages the underlying
+        memory. Individual fields are publicly accessible as properties of the
+        Tree.
+        """
+        cdef cnp.npy_intp shape[1]
+        shape[0] =  self.cell_count
+        cdef cnp.npy_intp strides[1]
+        strides[0] = sizeof(Cell)
+        cdef Cell[:] arr
+        Py_INCREF(CELL_DTYPE)
+        arr = PyArray_NewFromDescr(
+            subtype= np.ndarray,
+            descr=CELL_DTYPE,
+            nd=1,
+            dims=shape,
+            strides=strides,
+            data= self.cells,
+            flags=cnp.NPY_ARRAY_DEFAULT,
+            obj=None,
+        )
+        Py_INCREF(self)
+        if PyArray_SetBaseObject(arr.base,  self) < 0:
+            raise ValueError("Can't initialize array!")
+        return arr
+
+    cdef int _resize(self, intp_t capacity) except -1 nogil:
+        """Resize all inner arrays to `capacity`, if `capacity` == -1, then
+           double the size of the inner arrays.
+
+        Returns -1 in case of failure to allocate memory (and raise MemoryError)
+        or 0 otherwise.
+        """
+        if self._resize_c(capacity) != 0:
+            # Acquire gil only if we need to raise
+            with gil:
+                raise MemoryError()
+
+    cdef int _resize_c(self, intp_t capacity=SIZE_MAX) except -1 nogil:
+        """Guts of _resize
+
+        Returns -1 in case of failure to allocate memory (and raise MemoryError)
+        or 0 otherwise.
+        """
+        if capacity == self.capacity and self.cells != NULL:
+            return 0
+
+        if  capacity == SIZE_MAX:
+            if self.capacity == 0:
+                capacity = 9  # default initial value to min
+            else:
+                capacity = 2 * self.capacity
+
+        safe_realloc(&self.cells, capacity)
+
+        # if capacity smaller than cell_count, adjust the counter
+        if capacity < self.cell_count:
+            self.cell_count = capacity
+
+        self.capacity = capacity
+        return 0
+
+    def _py_summarize(self, float32_t[:] query_pt, float32_t[:, :] X, float angle):
+        # Used for testing summarize
+        cdef:
+            float32_t[:] summary
+            int n_samples
+
+        n_samples = X.shape[0]
+        summary = np.empty(4 * n_samples, dtype=np.float32)
+
+        idx = self.summarize(&query_pt[0], &summary[0], angle * angle)
+        return idx, summary
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_regression.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_regression.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ee0a340b8153b632fb8174785d53d018545f8ce
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_regression.py
@@ -0,0 +1,513 @@
+"""Nearest Neighbor Regression."""
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+import warnings
+
+import numpy as np
+
+from ..base import RegressorMixin, _fit_context
+from ..metrics import DistanceMetric
+from ..utils._param_validation import StrOptions
+from ._base import KNeighborsMixin, NeighborsBase, RadiusNeighborsMixin, _get_weights
+
+
+class KNeighborsRegressor(KNeighborsMixin, RegressorMixin, NeighborsBase):
+    """Regression based on k-nearest neighbors.
+
+    The target is predicted by local interpolation of the targets
+    associated of the nearest neighbors in the training set.
+
+    Read more in the :ref:`User Guide `.
+
+    .. versionadded:: 0.9
+
+    Parameters
+    ----------
+    n_neighbors : int, default=5
+        Number of neighbors to use by default for :meth:`kneighbors` queries.
+
+    weights : {'uniform', 'distance'}, callable or None, default='uniform'
+        Weight function used in prediction.  Possible values:
+
+        - 'uniform' : uniform weights.  All points in each neighborhood
+          are weighted equally.
+        - 'distance' : weight points by the inverse of their distance.
+          in this case, closer neighbors of a query point will have a
+          greater influence than neighbors which are further away.
+        - [callable] : a user-defined function which accepts an
+          array of distances, and returns an array of the same shape
+          containing the weights.
+
+        Uniform weights are used by default.
+
+        See the following example for a demonstration of the impact of
+        different weighting schemes on predictions:
+        :ref:`sphx_glr_auto_examples_neighbors_plot_regression.py`.
+
+    algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto'
+        Algorithm used to compute the nearest neighbors:
+
+        - 'ball_tree' will use :class:`BallTree`
+        - 'kd_tree' will use :class:`KDTree`
+        - 'brute' will use a brute-force search.
+        - 'auto' will attempt to decide the most appropriate algorithm
+          based on the values passed to :meth:`fit` method.
+
+        Note: fitting on sparse input will override the setting of
+        this parameter, using brute force.
+
+    leaf_size : int, default=30
+        Leaf size passed to BallTree or KDTree.  This can affect the
+        speed of the construction and query, as well as the memory
+        required to store the tree.  The optimal value depends on the
+        nature of the problem.
+
+    p : float, default=2
+        Power parameter for the Minkowski metric. When p = 1, this is
+        equivalent to using manhattan_distance (l1), and euclidean_distance
+        (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.
+
+    metric : str, DistanceMetric object or callable, default='minkowski'
+        Metric to use for distance computation. Default is "minkowski", which
+        results in the standard Euclidean distance when p = 2. See the
+        documentation of `scipy.spatial.distance
+        `_ and
+        the metrics listed in
+        :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric
+        values.
+
+        If metric is "precomputed", X is assumed to be a distance matrix and
+        must be square during fit. X may be a :term:`sparse graph`, in which
+        case only "nonzero" elements may be considered neighbors.
+
+        If metric is a callable function, it takes two arrays representing 1D
+        vectors as inputs and must return one value indicating the distance
+        between those vectors. This works for Scipy's metrics, but is less
+        efficient than passing the metric name as a string.
+
+        If metric is a DistanceMetric object, it will be passed directly to
+        the underlying computation routines.
+
+    metric_params : dict, default=None
+        Additional keyword arguments for the metric function.
+
+    n_jobs : int, default=None
+        The number of parallel jobs to run for neighbors search.
+        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+        ``-1`` means using all processors. See :term:`Glossary `
+        for more details.
+        Doesn't affect :meth:`fit` method.
+
+    Attributes
+    ----------
+    effective_metric_ : str or callable
+        The distance metric to use. It will be same as the `metric` parameter
+        or a synonym of it, e.g. 'euclidean' if the `metric` parameter set to
+        'minkowski' and `p` parameter set to 2.
+
+    effective_metric_params_ : dict
+        Additional keyword arguments for the metric function. For most metrics
+        will be same with `metric_params` parameter, but may also contain the
+        `p` parameter value if the `effective_metric_` attribute is set to
+        'minkowski'.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    n_samples_fit_ : int
+        Number of samples in the fitted data.
+
+    See Also
+    --------
+    NearestNeighbors : Unsupervised learner for implementing neighbor searches.
+    RadiusNeighborsRegressor : Regression based on neighbors within a fixed radius.
+    KNeighborsClassifier : Classifier implementing the k-nearest neighbors vote.
+    RadiusNeighborsClassifier : Classifier implementing
+        a vote among neighbors within a given radius.
+
+    Notes
+    -----
+    See :ref:`Nearest Neighbors ` in the online documentation
+    for a discussion of the choice of ``algorithm`` and ``leaf_size``.
+
+    .. warning::
+
+       Regarding the Nearest Neighbors algorithms, if it is found that two
+       neighbors, neighbor `k+1` and `k`, have identical distances but
+       different labels, the results will depend on the ordering of the
+       training data.
+
+    https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm
+
+    Examples
+    --------
+    >>> X = [[0], [1], [2], [3]]
+    >>> y = [0, 0, 1, 1]
+    >>> from sklearn.neighbors import KNeighborsRegressor
+    >>> neigh = KNeighborsRegressor(n_neighbors=2)
+    >>> neigh.fit(X, y)
+    KNeighborsRegressor(...)
+    >>> print(neigh.predict([[1.5]]))
+    [0.5]
+    """
+
+    _parameter_constraints: dict = {
+        **NeighborsBase._parameter_constraints,
+        "weights": [StrOptions({"uniform", "distance"}), callable, None],
+    }
+    _parameter_constraints["metric"].append(DistanceMetric)
+    _parameter_constraints.pop("radius")
+
+    def __init__(
+        self,
+        n_neighbors=5,
+        *,
+        weights="uniform",
+        algorithm="auto",
+        leaf_size=30,
+        p=2,
+        metric="minkowski",
+        metric_params=None,
+        n_jobs=None,
+    ):
+        super().__init__(
+            n_neighbors=n_neighbors,
+            algorithm=algorithm,
+            leaf_size=leaf_size,
+            metric=metric,
+            p=p,
+            metric_params=metric_params,
+            n_jobs=n_jobs,
+        )
+        self.weights = weights
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        # For cross-validation routines to split data correctly
+        tags.input_tags.pairwise = self.metric == "precomputed"
+        return tags
+
+    @_fit_context(
+        # KNeighborsRegressor.metric is not validated yet
+        prefer_skip_nested_validation=False
+    )
+    def fit(self, X, y):
+        """Fit the k-nearest neighbors regressor from the training dataset.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
+                (n_samples, n_samples) if metric='precomputed'
+            Training data.
+
+        y : {array-like, sparse matrix} of shape (n_samples,) or \
+                (n_samples, n_outputs)
+            Target values.
+
+        Returns
+        -------
+        self : KNeighborsRegressor
+            The fitted k-nearest neighbors regressor.
+        """
+        return self._fit(X, y)
+
+    def predict(self, X):
+        """Predict the target for the provided data.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_queries, n_features), \
+                or (n_queries, n_indexed) if metric == 'precomputed', or None
+            Test samples. If `None`, predictions for all indexed points are
+            returned; in this case, points are not considered their own
+            neighbors.
+
+        Returns
+        -------
+        y : ndarray of shape (n_queries,) or (n_queries, n_outputs), dtype=int
+            Target values.
+        """
+        if self.weights == "uniform":
+            # In that case, we do not need the distances to perform
+            # the weighting so we do not compute them.
+            neigh_ind = self.kneighbors(X, return_distance=False)
+            neigh_dist = None
+        else:
+            neigh_dist, neigh_ind = self.kneighbors(X)
+
+        weights = _get_weights(neigh_dist, self.weights)
+
+        _y = self._y
+        if _y.ndim == 1:
+            _y = _y.reshape((-1, 1))
+
+        if weights is None:
+            y_pred = np.mean(_y[neigh_ind], axis=1)
+        else:
+            y_pred = np.empty((neigh_dist.shape[0], _y.shape[1]), dtype=np.float64)
+            denom = np.sum(weights, axis=1)
+
+            for j in range(_y.shape[1]):
+                num = np.sum(_y[neigh_ind, j] * weights, axis=1)
+                y_pred[:, j] = num / denom
+
+        if self._y.ndim == 1:
+            y_pred = y_pred.ravel()
+
+        return y_pred
+
+
+class RadiusNeighborsRegressor(RadiusNeighborsMixin, RegressorMixin, NeighborsBase):
+    """Regression based on neighbors within a fixed radius.
+
+    The target is predicted by local interpolation of the targets
+    associated of the nearest neighbors in the training set.
+
+    Read more in the :ref:`User Guide `.
+
+    .. versionadded:: 0.9
+
+    Parameters
+    ----------
+    radius : float, default=1.0
+        Range of parameter space to use by default for :meth:`radius_neighbors`
+        queries.
+
+    weights : {'uniform', 'distance'}, callable or None, default='uniform'
+        Weight function used in prediction.  Possible values:
+
+        - 'uniform' : uniform weights.  All points in each neighborhood
+          are weighted equally.
+        - 'distance' : weight points by the inverse of their distance.
+          in this case, closer neighbors of a query point will have a
+          greater influence than neighbors which are further away.
+        - [callable] : a user-defined function which accepts an
+          array of distances, and returns an array of the same shape
+          containing the weights.
+
+        Uniform weights are used by default.
+
+    algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto'
+        Algorithm used to compute the nearest neighbors:
+
+        - 'ball_tree' will use :class:`BallTree`
+        - 'kd_tree' will use :class:`KDTree`
+        - 'brute' will use a brute-force search.
+        - 'auto' will attempt to decide the most appropriate algorithm
+          based on the values passed to :meth:`fit` method.
+
+        Note: fitting on sparse input will override the setting of
+        this parameter, using brute force.
+
+    leaf_size : int, default=30
+        Leaf size passed to BallTree or KDTree.  This can affect the
+        speed of the construction and query, as well as the memory
+        required to store the tree.  The optimal value depends on the
+        nature of the problem.
+
+    p : float, default=2
+        Power parameter for the Minkowski metric. When p = 1, this is
+        equivalent to using manhattan_distance (l1), and euclidean_distance
+        (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.
+
+    metric : str or callable, default='minkowski'
+        Metric to use for distance computation. Default is "minkowski", which
+        results in the standard Euclidean distance when p = 2. See the
+        documentation of `scipy.spatial.distance
+        `_ and
+        the metrics listed in
+        :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric
+        values.
+
+        If metric is "precomputed", X is assumed to be a distance matrix and
+        must be square during fit. X may be a :term:`sparse graph`, in which
+        case only "nonzero" elements may be considered neighbors.
+
+        If metric is a callable function, it takes two arrays representing 1D
+        vectors as inputs and must return one value indicating the distance
+        between those vectors. This works for Scipy's metrics, but is less
+        efficient than passing the metric name as a string.
+
+    metric_params : dict, default=None
+        Additional keyword arguments for the metric function.
+
+    n_jobs : int, default=None
+        The number of parallel jobs to run for neighbors search.
+        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+        ``-1`` means using all processors. See :term:`Glossary `
+        for more details.
+
+    Attributes
+    ----------
+    effective_metric_ : str or callable
+        The distance metric to use. It will be same as the `metric` parameter
+        or a synonym of it, e.g. 'euclidean' if the `metric` parameter set to
+        'minkowski' and `p` parameter set to 2.
+
+    effective_metric_params_ : dict
+        Additional keyword arguments for the metric function. For most metrics
+        will be same with `metric_params` parameter, but may also contain the
+        `p` parameter value if the `effective_metric_` attribute is set to
+        'minkowski'.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    n_samples_fit_ : int
+        Number of samples in the fitted data.
+
+    See Also
+    --------
+    NearestNeighbors : Unsupervised learner for implementing neighbor searches.
+    KNeighborsRegressor : Regression based on k-nearest neighbors.
+    KNeighborsClassifier : Classifier based on the k-nearest neighbors.
+    RadiusNeighborsClassifier : Classifier based on neighbors within a given radius.
+
+    Notes
+    -----
+    See :ref:`Nearest Neighbors ` in the online documentation
+    for a discussion of the choice of ``algorithm`` and ``leaf_size``.
+
+    https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm
+
+    Examples
+    --------
+    >>> X = [[0], [1], [2], [3]]
+    >>> y = [0, 0, 1, 1]
+    >>> from sklearn.neighbors import RadiusNeighborsRegressor
+    >>> neigh = RadiusNeighborsRegressor(radius=1.0)
+    >>> neigh.fit(X, y)
+    RadiusNeighborsRegressor(...)
+    >>> print(neigh.predict([[1.5]]))
+    [0.5]
+    """
+
+    _parameter_constraints: dict = {
+        **NeighborsBase._parameter_constraints,
+        "weights": [StrOptions({"uniform", "distance"}), callable, None],
+    }
+    _parameter_constraints.pop("n_neighbors")
+
+    def __init__(
+        self,
+        radius=1.0,
+        *,
+        weights="uniform",
+        algorithm="auto",
+        leaf_size=30,
+        p=2,
+        metric="minkowski",
+        metric_params=None,
+        n_jobs=None,
+    ):
+        super().__init__(
+            radius=radius,
+            algorithm=algorithm,
+            leaf_size=leaf_size,
+            p=p,
+            metric=metric,
+            metric_params=metric_params,
+            n_jobs=n_jobs,
+        )
+        self.weights = weights
+
+    @_fit_context(
+        # RadiusNeighborsRegressor.metric is not validated yet
+        prefer_skip_nested_validation=False
+    )
+    def fit(self, X, y):
+        """Fit the radius neighbors regressor from the training dataset.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
+                (n_samples, n_samples) if metric='precomputed'
+            Training data.
+
+        y : {array-like, sparse matrix} of shape (n_samples,) or \
+                (n_samples, n_outputs)
+            Target values.
+
+        Returns
+        -------
+        self : RadiusNeighborsRegressor
+            The fitted radius neighbors regressor.
+        """
+        return self._fit(X, y)
+
+    def predict(self, X):
+        """Predict the target for the provided data.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_queries, n_features), \
+                or (n_queries, n_indexed) if metric == 'precomputed', or None
+            Test samples. If `None`, predictions for all indexed points are
+            returned; in this case, points are not considered their own
+            neighbors.
+
+        Returns
+        -------
+        y : ndarray of shape (n_queries,) or (n_queries, n_outputs), \
+                dtype=double
+            Target values.
+        """
+        neigh_dist, neigh_ind = self.radius_neighbors(X)
+
+        weights = _get_weights(neigh_dist, self.weights)
+
+        _y = self._y
+        if _y.ndim == 1:
+            _y = _y.reshape((-1, 1))
+
+        empty_obs = np.full_like(_y[0], np.nan)
+
+        if weights is None:
+            y_pred = np.array(
+                [
+                    np.mean(_y[ind, :], axis=0) if len(ind) else empty_obs
+                    for (i, ind) in enumerate(neigh_ind)
+                ]
+            )
+
+        else:
+            y_pred = np.array(
+                [
+                    (
+                        np.average(_y[ind, :], axis=0, weights=weights[i])
+                        if len(ind)
+                        else empty_obs
+                    )
+                    for (i, ind) in enumerate(neigh_ind)
+                ]
+            )
+
+        if np.any(np.isnan(y_pred)):
+            empty_warning_msg = (
+                "One or more samples have no neighbors "
+                "within specified radius; predicting NaN."
+            )
+            warnings.warn(empty_warning_msg)
+
+        if self._y.ndim == 1:
+            y_pred = y_pred.ravel()
+
+        return y_pred
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_unsupervised.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_unsupervised.py
new file mode 100644
index 0000000000000000000000000000000000000000..8888fe18483c6ae5f7008d78b0d6ff97d096a419
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/_unsupervised.py
@@ -0,0 +1,179 @@
+"""Unsupervised nearest neighbors learner"""
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+from ..base import _fit_context
+from ._base import KNeighborsMixin, NeighborsBase, RadiusNeighborsMixin
+
+
+class NearestNeighbors(KNeighborsMixin, RadiusNeighborsMixin, NeighborsBase):
+    """Unsupervised learner for implementing neighbor searches.
+
+    Read more in the :ref:`User Guide `.
+
+    .. versionadded:: 0.9
+
+    Parameters
+    ----------
+    n_neighbors : int, default=5
+        Number of neighbors to use by default for :meth:`kneighbors` queries.
+
+    radius : float, default=1.0
+        Range of parameter space to use by default for :meth:`radius_neighbors`
+        queries.
+
+    algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto'
+        Algorithm used to compute the nearest neighbors:
+
+        - 'ball_tree' will use :class:`BallTree`
+        - 'kd_tree' will use :class:`KDTree`
+        - 'brute' will use a brute-force search.
+        - 'auto' will attempt to decide the most appropriate algorithm
+          based on the values passed to :meth:`fit` method.
+
+        Note: fitting on sparse input will override the setting of
+        this parameter, using brute force.
+
+    leaf_size : int, default=30
+        Leaf size passed to BallTree or KDTree.  This can affect the
+        speed of the construction and query, as well as the memory
+        required to store the tree.  The optimal value depends on the
+        nature of the problem.
+
+    metric : str or callable, default='minkowski'
+        Metric to use for distance computation. Default is "minkowski", which
+        results in the standard Euclidean distance when p = 2. See the
+        documentation of `scipy.spatial.distance
+        `_ and
+        the metrics listed in
+        :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric
+        values.
+
+        If metric is "precomputed", X is assumed to be a distance matrix and
+        must be square during fit. X may be a :term:`sparse graph`, in which
+        case only "nonzero" elements may be considered neighbors.
+
+        If metric is a callable function, it takes two arrays representing 1D
+        vectors as inputs and must return one value indicating the distance
+        between those vectors. This works for Scipy's metrics, but is less
+        efficient than passing the metric name as a string.
+
+    p : float (positive), default=2
+        Parameter for the Minkowski metric from
+        sklearn.metrics.pairwise.pairwise_distances. When p = 1, this is
+        equivalent to using manhattan_distance (l1), and euclidean_distance
+        (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.
+
+    metric_params : dict, default=None
+        Additional keyword arguments for the metric function.
+
+    n_jobs : int, default=None
+        The number of parallel jobs to run for neighbors search.
+        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+        ``-1`` means using all processors. See :term:`Glossary `
+        for more details.
+
+    Attributes
+    ----------
+    effective_metric_ : str
+        Metric used to compute distances to neighbors.
+
+    effective_metric_params_ : dict
+        Parameters for the metric used to compute distances to neighbors.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    n_samples_fit_ : int
+        Number of samples in the fitted data.
+
+    See Also
+    --------
+    KNeighborsClassifier : Classifier implementing the k-nearest neighbors
+        vote.
+    RadiusNeighborsClassifier : Classifier implementing a vote among neighbors
+        within a given radius.
+    KNeighborsRegressor : Regression based on k-nearest neighbors.
+    RadiusNeighborsRegressor : Regression based on neighbors within a fixed
+        radius.
+    BallTree : Space partitioning data structure for organizing points in a
+        multi-dimensional space, used for nearest neighbor search.
+
+    Notes
+    -----
+    See :ref:`Nearest Neighbors ` in the online documentation
+    for a discussion of the choice of ``algorithm`` and ``leaf_size``.
+
+    https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from sklearn.neighbors import NearestNeighbors
+    >>> samples = [[0, 0, 2], [1, 0, 0], [0, 0, 1]]
+    >>> neigh = NearestNeighbors(n_neighbors=2, radius=0.4)
+    >>> neigh.fit(samples)
+    NearestNeighbors(...)
+    >>> neigh.kneighbors([[0, 0, 1.3]], 2, return_distance=False)
+    array([[2, 0]]...)
+    >>> nbrs = neigh.radius_neighbors(
+    ...    [[0, 0, 1.3]], 0.4, return_distance=False
+    ... )
+    >>> np.asarray(nbrs[0][0])
+    array(2)
+    """
+
+    def __init__(
+        self,
+        *,
+        n_neighbors=5,
+        radius=1.0,
+        algorithm="auto",
+        leaf_size=30,
+        metric="minkowski",
+        p=2,
+        metric_params=None,
+        n_jobs=None,
+    ):
+        super().__init__(
+            n_neighbors=n_neighbors,
+            radius=radius,
+            algorithm=algorithm,
+            leaf_size=leaf_size,
+            metric=metric,
+            p=p,
+            metric_params=metric_params,
+            n_jobs=n_jobs,
+        )
+
+    @_fit_context(
+        # NearestNeighbors.metric is not validated yet
+        prefer_skip_nested_validation=False
+    )
+    def fit(self, X, y=None):
+        """Fit the nearest neighbors estimator from the training dataset.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
+                (n_samples, n_samples) if metric='precomputed'
+            Training data.
+
+        y : Ignored
+            Not used, present for API consistency by convention.
+
+        Returns
+        -------
+        self : NearestNeighbors
+            The fitted nearest neighbors estimator.
+        """
+        return self._fit(X)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/meson.build b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/meson.build
new file mode 100644
index 0000000000000000000000000000000000000000..7993421896218d3a4c9db8055d2dfd9528ac3746
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/meson.build
@@ -0,0 +1,53 @@
+_binary_tree_pxi = custom_target(
+  '_binary_tree_pxi',
+  output: '_binary_tree.pxi',
+  input: '_binary_tree.pxi.tp',
+  command: [tempita, '@INPUT@', '-o', '@OUTDIR@'],
+)
+
+# .pyx is generated so this is needed to make Cython compilation work. The pxi
+# file is included avoid "missing dependency paths" with ninja -t missindeps
+neighbors_cython_tree = [
+  fs.copyfile('__init__.py'),
+  fs.copyfile('_partition_nodes.pxd'),
+  _binary_tree_pxi,
+]
+
+name_list = ['_ball_tree', '_kd_tree']
+
+foreach name: name_list
+  pyx = custom_target(
+    name + '_pyx',
+    output: name + '.pyx',
+    input: name + '.pyx.tp',
+    command: [tempita, '@INPUT@', '-o', '@OUTDIR@'],
+    # TODO in principle this should go in py.exension_module below. This is
+    # temporary work-around for dependency issue with .pyx.tp files. For more
+    # details, see https://github.com/mesonbuild/meson/issues/13212
+    depends: [neighbors_cython_tree, utils_cython_tree, metrics_cython_tree],
+  )
+  py.extension_module(
+    name,
+    cython_gen.process(pyx),
+    dependencies: [np_dep],
+    subdir: 'sklearn/neighbors',
+    install: true
+)
+endforeach
+
+neighbors_extension_metadata = {
+  '_partition_nodes':
+      {'sources': [cython_gen_cpp.process('_partition_nodes.pyx')],
+       'dependencies': [np_dep]},
+  '_quad_tree': {'sources': [cython_gen.process('_quad_tree.pyx')], 'dependencies': [np_dep]},
+}
+
+foreach ext_name, ext_dict : neighbors_extension_metadata
+  py.extension_module(
+    ext_name,
+    [ext_dict.get('sources'), utils_cython_tree],
+    dependencies: ext_dict.get('dependencies'),
+    subdir: 'sklearn/neighbors',
+    install: true
+  )
+endforeach
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_ball_tree.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_ball_tree.py
new file mode 100644
index 0000000000000000000000000000000000000000..5263f201f320b17ced98fb223e7aaaf624d9271d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_ball_tree.py
@@ -0,0 +1,200 @@
+import itertools
+
+import numpy as np
+import pytest
+from numpy.testing import assert_allclose, assert_array_almost_equal, assert_equal
+
+from sklearn.neighbors._ball_tree import BallTree, BallTree32, BallTree64
+from sklearn.utils import check_random_state
+from sklearn.utils._testing import _convert_container
+from sklearn.utils.validation import check_array
+
+rng = np.random.RandomState(10)
+V_mahalanobis = rng.rand(3, 3)
+V_mahalanobis = np.dot(V_mahalanobis, V_mahalanobis.T)
+
+DIMENSION = 3
+
+METRICS = {
+    "euclidean": {},
+    "manhattan": {},
+    "minkowski": dict(p=3),
+    "chebyshev": {},
+}
+
+DISCRETE_METRICS = ["hamming", "canberra", "braycurtis"]
+
+BOOLEAN_METRICS = [
+    "jaccard",
+    "dice",
+    "rogerstanimoto",
+    "russellrao",
+    "sokalmichener",
+    "sokalsneath",
+]
+
+BALL_TREE_CLASSES = [
+    BallTree64,
+    BallTree32,
+]
+
+
+def brute_force_neighbors(X, Y, k, metric, **kwargs):
+    from sklearn.metrics import DistanceMetric
+
+    X, Y = check_array(X), check_array(Y)
+    D = DistanceMetric.get_metric(metric, **kwargs).pairwise(Y, X)
+    ind = np.argsort(D, axis=1)[:, :k]
+    dist = D[np.arange(Y.shape[0])[:, None], ind]
+    return dist, ind
+
+
+def test_BallTree_is_BallTree64_subclass():
+    assert issubclass(BallTree, BallTree64)
+
+
+@pytest.mark.parametrize("metric", itertools.chain(BOOLEAN_METRICS, DISCRETE_METRICS))
+@pytest.mark.parametrize("array_type", ["list", "array"])
+@pytest.mark.parametrize("BallTreeImplementation", BALL_TREE_CLASSES)
+def test_ball_tree_query_metrics(metric, array_type, BallTreeImplementation):
+    rng = check_random_state(0)
+    if metric in BOOLEAN_METRICS:
+        X = rng.random_sample((40, 10)).round(0)
+        Y = rng.random_sample((10, 10)).round(0)
+    elif metric in DISCRETE_METRICS:
+        X = (4 * rng.random_sample((40, 10))).round(0)
+        Y = (4 * rng.random_sample((10, 10))).round(0)
+    X = _convert_container(X, array_type)
+    Y = _convert_container(Y, array_type)
+
+    k = 5
+
+    bt = BallTreeImplementation(X, leaf_size=1, metric=metric)
+    dist1, ind1 = bt.query(Y, k)
+    dist2, ind2 = brute_force_neighbors(X, Y, k, metric)
+    assert_array_almost_equal(dist1, dist2)
+
+
+@pytest.mark.parametrize(
+    "BallTreeImplementation, decimal_tol", zip(BALL_TREE_CLASSES, [6, 5])
+)
+def test_query_haversine(BallTreeImplementation, decimal_tol):
+    rng = check_random_state(0)
+    X = 2 * np.pi * rng.random_sample((40, 2))
+    bt = BallTreeImplementation(X, leaf_size=1, metric="haversine")
+    dist1, ind1 = bt.query(X, k=5)
+    dist2, ind2 = brute_force_neighbors(X, X, k=5, metric="haversine")
+
+    assert_array_almost_equal(dist1, dist2, decimal=decimal_tol)
+    assert_array_almost_equal(ind1, ind2)
+
+
+@pytest.mark.parametrize("BallTreeImplementation", BALL_TREE_CLASSES)
+def test_array_object_type(BallTreeImplementation):
+    """Check that we do not accept object dtype array."""
+    X = np.array([(1, 2, 3), (2, 5), (5, 5, 1, 2)], dtype=object)
+    with pytest.raises(ValueError, match="setting an array element with a sequence"):
+        BallTreeImplementation(X)
+
+
+@pytest.mark.parametrize("BallTreeImplementation", BALL_TREE_CLASSES)
+def test_bad_pyfunc_metric(BallTreeImplementation):
+    def wrong_returned_value(x, y):
+        return "1"
+
+    def one_arg_func(x):
+        return 1.0  # pragma: no cover
+
+    X = np.ones((5, 2))
+    msg = "Custom distance function must accept two vectors and return a float."
+    with pytest.raises(TypeError, match=msg):
+        BallTreeImplementation(X, metric=wrong_returned_value)
+
+    msg = "takes 1 positional argument but 2 were given"
+    with pytest.raises(TypeError, match=msg):
+        BallTreeImplementation(X, metric=one_arg_func)
+
+
+@pytest.mark.parametrize("metric", itertools.chain(METRICS, BOOLEAN_METRICS))
+def test_ball_tree_numerical_consistency(global_random_seed, metric):
+    # Results on float64 and float32 versions of a dataset must be
+    # numerically close.
+    X_64, X_32, Y_64, Y_32 = get_dataset_for_binary_tree(
+        random_seed=global_random_seed, features=50
+    )
+
+    metric_params = METRICS.get(metric, {})
+    bt_64 = BallTree64(X_64, leaf_size=1, metric=metric, **metric_params)
+    bt_32 = BallTree32(X_32, leaf_size=1, metric=metric, **metric_params)
+
+    # Test consistency with respect to the `query` method
+    k = 5
+    dist_64, ind_64 = bt_64.query(Y_64, k=k)
+    dist_32, ind_32 = bt_32.query(Y_32, k=k)
+    assert_allclose(dist_64, dist_32, rtol=1e-5)
+    assert_equal(ind_64, ind_32)
+    assert dist_64.dtype == np.float64
+    assert dist_32.dtype == np.float32
+
+    # Test consistency with respect to the `query_radius` method
+    r = 2.38
+    ind_64 = bt_64.query_radius(Y_64, r=r)
+    ind_32 = bt_32.query_radius(Y_32, r=r)
+    for _ind64, _ind32 in zip(ind_64, ind_32):
+        assert_equal(_ind64, _ind32)
+
+    # Test consistency with respect to the `query_radius` method
+    # with return distances being true
+    ind_64, dist_64 = bt_64.query_radius(Y_64, r=r, return_distance=True)
+    ind_32, dist_32 = bt_32.query_radius(Y_32, r=r, return_distance=True)
+    for _ind64, _ind32, _dist_64, _dist_32 in zip(ind_64, ind_32, dist_64, dist_32):
+        assert_equal(_ind64, _ind32)
+        assert_allclose(_dist_64, _dist_32, rtol=1e-5)
+        assert _dist_64.dtype == np.float64
+        assert _dist_32.dtype == np.float32
+
+
+@pytest.mark.parametrize("metric", itertools.chain(METRICS, BOOLEAN_METRICS))
+def test_kernel_density_numerical_consistency(global_random_seed, metric):
+    # Test consistency with respect to the `kernel_density` method
+    X_64, X_32, Y_64, Y_32 = get_dataset_for_binary_tree(random_seed=global_random_seed)
+
+    metric_params = METRICS.get(metric, {})
+    bt_64 = BallTree64(X_64, leaf_size=1, metric=metric, **metric_params)
+    bt_32 = BallTree32(X_32, leaf_size=1, metric=metric, **metric_params)
+
+    kernel = "gaussian"
+    h = 0.1
+    density64 = bt_64.kernel_density(Y_64, h=h, kernel=kernel, breadth_first=True)
+    density32 = bt_32.kernel_density(Y_32, h=h, kernel=kernel, breadth_first=True)
+    assert_allclose(density64, density32, rtol=1e-5)
+    assert density64.dtype == np.float64
+    assert density32.dtype == np.float32
+
+
+def test_two_point_correlation_numerical_consistency(global_random_seed):
+    # Test consistency with respect to the `two_point_correlation` method
+    X_64, X_32, Y_64, Y_32 = get_dataset_for_binary_tree(random_seed=global_random_seed)
+
+    bt_64 = BallTree64(X_64, leaf_size=10)
+    bt_32 = BallTree32(X_32, leaf_size=10)
+
+    r = np.linspace(0, 1, 10)
+
+    counts_64 = bt_64.two_point_correlation(Y_64, r=r, dualtree=True)
+    counts_32 = bt_32.two_point_correlation(Y_32, r=r, dualtree=True)
+    assert_allclose(counts_64, counts_32)
+
+
+def get_dataset_for_binary_tree(random_seed, features=3):
+    rng = np.random.RandomState(random_seed)
+    _X = rng.rand(100, features)
+    _Y = rng.rand(5, features)
+
+    X_64 = _X.astype(dtype=np.float64, copy=False)
+    Y_64 = _Y.astype(dtype=np.float64, copy=False)
+
+    X_32 = _X.astype(dtype=np.float32, copy=False)
+    Y_32 = _Y.astype(dtype=np.float32, copy=False)
+
+    return X_64, X_32, Y_64, Y_32
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_graph.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_graph.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb593485d17a8155f784ef881b3868338348e1a8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_graph.py
@@ -0,0 +1,101 @@
+import numpy as np
+import pytest
+
+from sklearn.metrics import euclidean_distances
+from sklearn.neighbors import KNeighborsTransformer, RadiusNeighborsTransformer
+from sklearn.neighbors._base import _is_sorted_by_data
+from sklearn.utils._testing import assert_array_equal
+
+
+def test_transformer_result():
+    # Test the number of neighbors returned
+    n_neighbors = 5
+    n_samples_fit = 20
+    n_queries = 18
+    n_features = 10
+
+    rng = np.random.RandomState(42)
+    X = rng.randn(n_samples_fit, n_features)
+    X2 = rng.randn(n_queries, n_features)
+    radius = np.percentile(euclidean_distances(X), 10)
+
+    # with n_neighbors
+    for mode in ["distance", "connectivity"]:
+        add_one = mode == "distance"
+        nnt = KNeighborsTransformer(n_neighbors=n_neighbors, mode=mode)
+        Xt = nnt.fit_transform(X)
+        assert Xt.shape == (n_samples_fit, n_samples_fit)
+        assert Xt.data.shape == (n_samples_fit * (n_neighbors + add_one),)
+        assert Xt.format == "csr"
+        assert _is_sorted_by_data(Xt)
+
+        X2t = nnt.transform(X2)
+        assert X2t.shape == (n_queries, n_samples_fit)
+        assert X2t.data.shape == (n_queries * (n_neighbors + add_one),)
+        assert X2t.format == "csr"
+        assert _is_sorted_by_data(X2t)
+
+    # with radius
+    for mode in ["distance", "connectivity"]:
+        add_one = mode == "distance"
+        nnt = RadiusNeighborsTransformer(radius=radius, mode=mode)
+        Xt = nnt.fit_transform(X)
+        assert Xt.shape == (n_samples_fit, n_samples_fit)
+        assert not Xt.data.shape == (n_samples_fit * (n_neighbors + add_one),)
+        assert Xt.format == "csr"
+        assert _is_sorted_by_data(Xt)
+
+        X2t = nnt.transform(X2)
+        assert X2t.shape == (n_queries, n_samples_fit)
+        assert not X2t.data.shape == (n_queries * (n_neighbors + add_one),)
+        assert X2t.format == "csr"
+        assert _is_sorted_by_data(X2t)
+
+
+def _has_explicit_diagonal(X):
+    """Return True if the diagonal is explicitly stored"""
+    X = X.tocoo()
+    explicit = X.row[X.row == X.col]
+    return len(explicit) == X.shape[0]
+
+
+def test_explicit_diagonal():
+    # Test that the diagonal is explicitly stored in the sparse graph
+    n_neighbors = 5
+    n_samples_fit, n_samples_transform, n_features = 20, 18, 10
+    rng = np.random.RandomState(42)
+    X = rng.randn(n_samples_fit, n_features)
+    X2 = rng.randn(n_samples_transform, n_features)
+
+    nnt = KNeighborsTransformer(n_neighbors=n_neighbors)
+    Xt = nnt.fit_transform(X)
+    assert _has_explicit_diagonal(Xt)
+    assert np.all(Xt.data.reshape(n_samples_fit, n_neighbors + 1)[:, 0] == 0)
+
+    Xt = nnt.transform(X)
+    assert _has_explicit_diagonal(Xt)
+    assert np.all(Xt.data.reshape(n_samples_fit, n_neighbors + 1)[:, 0] == 0)
+
+    # Using transform on new data should not always have zero diagonal
+    X2t = nnt.transform(X2)
+    assert not _has_explicit_diagonal(X2t)
+
+
+@pytest.mark.parametrize("Klass", [KNeighborsTransformer, RadiusNeighborsTransformer])
+def test_graph_feature_names_out(Klass):
+    """Check `get_feature_names_out` for transformers defined in `_graph.py`."""
+
+    n_samples_fit = 20
+    n_features = 10
+    rng = np.random.RandomState(42)
+    X = rng.randn(n_samples_fit, n_features)
+
+    est = Klass().fit(X)
+    names_out = est.get_feature_names_out()
+
+    class_name_lower = Klass.__name__.lower()
+    expected_names_out = np.array(
+        [f"{class_name_lower}{i}" for i in range(est.n_samples_fit_)],
+        dtype=object,
+    )
+    assert_array_equal(names_out, expected_names_out)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_kd_tree.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_kd_tree.py
new file mode 100644
index 0000000000000000000000000000000000000000..749601baaf66fdbf96e8396ca1df45c5bdab4a1e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_kd_tree.py
@@ -0,0 +1,100 @@
+import numpy as np
+import pytest
+from numpy.testing import assert_allclose, assert_equal
+
+from sklearn.neighbors._kd_tree import KDTree, KDTree32, KDTree64
+from sklearn.neighbors.tests.test_ball_tree import get_dataset_for_binary_tree
+from sklearn.utils.parallel import Parallel, delayed
+
+DIMENSION = 3
+
+METRICS = {"euclidean": {}, "manhattan": {}, "chebyshev": {}, "minkowski": dict(p=3)}
+
+KD_TREE_CLASSES = [
+    KDTree64,
+    KDTree32,
+]
+
+
+def test_KDTree_is_KDTree64_subclass():
+    assert issubclass(KDTree, KDTree64)
+
+
+@pytest.mark.parametrize("BinarySearchTree", KD_TREE_CLASSES)
+def test_array_object_type(BinarySearchTree):
+    """Check that we do not accept object dtype array."""
+    X = np.array([(1, 2, 3), (2, 5), (5, 5, 1, 2)], dtype=object)
+    with pytest.raises(ValueError, match="setting an array element with a sequence"):
+        BinarySearchTree(X)
+
+
+@pytest.mark.parametrize("BinarySearchTree", KD_TREE_CLASSES)
+def test_kdtree_picklable_with_joblib(BinarySearchTree):
+    """Make sure that KDTree queries work when joblib memmaps.
+
+    Non-regression test for #21685 and #21228."""
+    rng = np.random.RandomState(0)
+    X = rng.random_sample((10, 3))
+    tree = BinarySearchTree(X, leaf_size=2)
+
+    # Call Parallel with max_nbytes=1 to trigger readonly memory mapping that
+    # use to raise "ValueError: buffer source array is read-only" in a previous
+    # version of the Cython code.
+    Parallel(n_jobs=2, max_nbytes=1)(delayed(tree.query)(data) for data in 2 * [X])
+
+
+@pytest.mark.parametrize("metric", METRICS)
+def test_kd_tree_numerical_consistency(global_random_seed, metric):
+    # Results on float64 and float32 versions of a dataset must be
+    # numerically close.
+    X_64, X_32, Y_64, Y_32 = get_dataset_for_binary_tree(
+        random_seed=global_random_seed, features=50
+    )
+
+    metric_params = METRICS.get(metric, {})
+    kd_64 = KDTree64(X_64, leaf_size=2, metric=metric, **metric_params)
+    kd_32 = KDTree32(X_32, leaf_size=2, metric=metric, **metric_params)
+
+    # Test consistency with respect to the `query` method
+    k = 4
+    dist_64, ind_64 = kd_64.query(Y_64, k=k)
+    dist_32, ind_32 = kd_32.query(Y_32, k=k)
+    assert_allclose(dist_64, dist_32, rtol=1e-5)
+    assert_equal(ind_64, ind_32)
+    assert dist_64.dtype == np.float64
+    assert dist_32.dtype == np.float32
+
+    # Test consistency with respect to the `query_radius` method
+    r = 2.38
+    ind_64 = kd_64.query_radius(Y_64, r=r)
+    ind_32 = kd_32.query_radius(Y_32, r=r)
+    for _ind64, _ind32 in zip(ind_64, ind_32):
+        assert_equal(_ind64, _ind32)
+
+    # Test consistency with respect to the `query_radius` method
+    # with return distances being true
+    ind_64, dist_64 = kd_64.query_radius(Y_64, r=r, return_distance=True)
+    ind_32, dist_32 = kd_32.query_radius(Y_32, r=r, return_distance=True)
+    for _ind64, _ind32, _dist_64, _dist_32 in zip(ind_64, ind_32, dist_64, dist_32):
+        assert_equal(_ind64, _ind32)
+        assert_allclose(_dist_64, _dist_32, rtol=1e-5)
+        assert _dist_64.dtype == np.float64
+        assert _dist_32.dtype == np.float32
+
+
+@pytest.mark.parametrize("metric", METRICS)
+def test_kernel_density_numerical_consistency(global_random_seed, metric):
+    # Test consistency with respect to the `kernel_density` method
+    X_64, X_32, Y_64, Y_32 = get_dataset_for_binary_tree(random_seed=global_random_seed)
+
+    metric_params = METRICS.get(metric, {})
+    kd_64 = KDTree64(X_64, leaf_size=2, metric=metric, **metric_params)
+    kd_32 = KDTree32(X_32, leaf_size=2, metric=metric, **metric_params)
+
+    kernel = "gaussian"
+    h = 0.1
+    density64 = kd_64.kernel_density(Y_64, h=h, kernel=kernel, breadth_first=True)
+    density32 = kd_32.kernel_density(Y_32, h=h, kernel=kernel, breadth_first=True)
+    assert_allclose(density64, density32, rtol=1e-5)
+    assert density64.dtype == np.float64
+    assert density32.dtype == np.float32
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_kde.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_kde.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6bf09d01b672b7ad5a3abf3506443b0ac620915
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_kde.py
@@ -0,0 +1,252 @@
+import joblib
+import numpy as np
+import pytest
+
+from sklearn.datasets import make_blobs
+from sklearn.exceptions import NotFittedError
+from sklearn.model_selection import GridSearchCV
+from sklearn.neighbors import KDTree, KernelDensity, NearestNeighbors
+from sklearn.neighbors._ball_tree import kernel_norm
+from sklearn.pipeline import make_pipeline
+from sklearn.preprocessing import StandardScaler
+from sklearn.utils._testing import assert_allclose
+
+
+# XXX Duplicated in test_neighbors_tree, test_kde
+def compute_kernel_slow(Y, X, kernel, h):
+    if h == "scott":
+        h = X.shape[0] ** (-1 / (X.shape[1] + 4))
+    elif h == "silverman":
+        h = (X.shape[0] * (X.shape[1] + 2) / 4) ** (-1 / (X.shape[1] + 4))
+
+    d = np.sqrt(((Y[:, None, :] - X) ** 2).sum(-1))
+    norm = kernel_norm(h, X.shape[1], kernel) / X.shape[0]
+
+    if kernel == "gaussian":
+        return norm * np.exp(-0.5 * (d * d) / (h * h)).sum(-1)
+    elif kernel == "tophat":
+        return norm * (d < h).sum(-1)
+    elif kernel == "epanechnikov":
+        return norm * ((1.0 - (d * d) / (h * h)) * (d < h)).sum(-1)
+    elif kernel == "exponential":
+        return norm * (np.exp(-d / h)).sum(-1)
+    elif kernel == "linear":
+        return norm * ((1 - d / h) * (d < h)).sum(-1)
+    elif kernel == "cosine":
+        return norm * (np.cos(0.5 * np.pi * d / h) * (d < h)).sum(-1)
+    else:
+        raise ValueError("kernel not recognized")
+
+
+def check_results(kernel, bandwidth, atol, rtol, X, Y, dens_true):
+    kde = KernelDensity(kernel=kernel, bandwidth=bandwidth, atol=atol, rtol=rtol)
+    log_dens = kde.fit(X).score_samples(Y)
+    assert_allclose(np.exp(log_dens), dens_true, atol=atol, rtol=max(1e-7, rtol))
+    assert_allclose(
+        np.exp(kde.score(Y)), np.prod(dens_true), atol=atol, rtol=max(1e-7, rtol)
+    )
+
+
+@pytest.mark.parametrize(
+    "kernel", ["gaussian", "tophat", "epanechnikov", "exponential", "linear", "cosine"]
+)
+@pytest.mark.parametrize("bandwidth", [0.01, 0.1, 1, "scott", "silverman"])
+def test_kernel_density(kernel, bandwidth):
+    n_samples, n_features = (100, 3)
+
+    rng = np.random.RandomState(0)
+    X = rng.randn(n_samples, n_features)
+    Y = rng.randn(n_samples, n_features)
+
+    dens_true = compute_kernel_slow(Y, X, kernel, bandwidth)
+
+    for rtol in [0, 1e-5]:
+        for atol in [1e-6, 1e-2]:
+            for breadth_first in (True, False):
+                check_results(kernel, bandwidth, atol, rtol, X, Y, dens_true)
+
+
+def test_kernel_density_sampling(n_samples=100, n_features=3):
+    rng = np.random.RandomState(0)
+    X = rng.randn(n_samples, n_features)
+
+    bandwidth = 0.2
+
+    for kernel in ["gaussian", "tophat"]:
+        # draw a tophat sample
+        kde = KernelDensity(bandwidth=bandwidth, kernel=kernel).fit(X)
+        samp = kde.sample(100)
+        assert X.shape == samp.shape
+
+        # check that samples are in the right range
+        nbrs = NearestNeighbors(n_neighbors=1).fit(X)
+        dist, ind = nbrs.kneighbors(X, return_distance=True)
+
+        if kernel == "tophat":
+            assert np.all(dist < bandwidth)
+        elif kernel == "gaussian":
+            # 5 standard deviations is safe for 100 samples, but there's a
+            # very small chance this test could fail.
+            assert np.all(dist < 5 * bandwidth)
+
+    # check unsupported kernels
+    for kernel in ["epanechnikov", "exponential", "linear", "cosine"]:
+        kde = KernelDensity(bandwidth=bandwidth, kernel=kernel).fit(X)
+        with pytest.raises(NotImplementedError):
+            kde.sample(100)
+
+    # non-regression test: used to return a scalar
+    X = rng.randn(4, 1)
+    kde = KernelDensity(kernel="gaussian").fit(X)
+    assert kde.sample().shape == (1, 1)
+
+
+@pytest.mark.parametrize("algorithm", ["auto", "ball_tree", "kd_tree"])
+@pytest.mark.parametrize(
+    "metric", ["euclidean", "minkowski", "manhattan", "chebyshev", "haversine"]
+)
+def test_kde_algorithm_metric_choice(algorithm, metric):
+    # Smoke test for various metrics and algorithms
+    rng = np.random.RandomState(0)
+    X = rng.randn(10, 2)  # 2 features required for haversine dist.
+    Y = rng.randn(10, 2)
+
+    kde = KernelDensity(algorithm=algorithm, metric=metric)
+
+    if algorithm == "kd_tree" and metric not in KDTree.valid_metrics:
+        with pytest.raises(ValueError, match="invalid metric"):
+            kde.fit(X)
+    else:
+        kde.fit(X)
+        y_dens = kde.score_samples(Y)
+        assert y_dens.shape == Y.shape[:1]
+
+
+def test_kde_score(n_samples=100, n_features=3):
+    pass
+    # FIXME
+    # rng = np.random.RandomState(0)
+    # X = rng.random_sample((n_samples, n_features))
+    # Y = rng.random_sample((n_samples, n_features))
+
+
+def test_kde_sample_weights_error():
+    kde = KernelDensity()
+    with pytest.raises(ValueError):
+        kde.fit(np.random.random((200, 10)), sample_weight=np.random.random((200, 10)))
+    with pytest.raises(ValueError):
+        kde.fit(np.random.random((200, 10)), sample_weight=-np.random.random(200))
+
+
+def test_kde_pipeline_gridsearch():
+    # test that kde plays nice in pipelines and grid-searches
+    X, _ = make_blobs(cluster_std=0.1, random_state=1, centers=[[0, 1], [1, 0], [0, 0]])
+    pipe1 = make_pipeline(
+        StandardScaler(with_mean=False, with_std=False),
+        KernelDensity(kernel="gaussian"),
+    )
+    params = dict(kerneldensity__bandwidth=[0.001, 0.01, 0.1, 1, 10])
+    search = GridSearchCV(pipe1, param_grid=params)
+    search.fit(X)
+    assert search.best_params_["kerneldensity__bandwidth"] == 0.1
+
+
+def test_kde_sample_weights():
+    n_samples = 400
+    size_test = 20
+    weights_neutral = np.full(n_samples, 3.0)
+    for d in [1, 2, 10]:
+        rng = np.random.RandomState(0)
+        X = rng.rand(n_samples, d)
+        weights = 1 + (10 * X.sum(axis=1)).astype(np.int8)
+        X_repetitions = np.repeat(X, weights, axis=0)
+        n_samples_test = size_test // d
+        test_points = rng.rand(n_samples_test, d)
+        for algorithm in ["auto", "ball_tree", "kd_tree"]:
+            for metric in ["euclidean", "minkowski", "manhattan", "chebyshev"]:
+                if algorithm != "kd_tree" or metric in KDTree.valid_metrics:
+                    kde = KernelDensity(algorithm=algorithm, metric=metric)
+
+                    # Test that adding a constant sample weight has no effect
+                    kde.fit(X, sample_weight=weights_neutral)
+                    scores_const_weight = kde.score_samples(test_points)
+                    sample_const_weight = kde.sample(random_state=1234)
+                    kde.fit(X)
+                    scores_no_weight = kde.score_samples(test_points)
+                    sample_no_weight = kde.sample(random_state=1234)
+                    assert_allclose(scores_const_weight, scores_no_weight)
+                    assert_allclose(sample_const_weight, sample_no_weight)
+
+                    # Test equivalence between sampling and (integer) weights
+                    kde.fit(X, sample_weight=weights)
+                    scores_weight = kde.score_samples(test_points)
+                    sample_weight = kde.sample(random_state=1234)
+                    kde.fit(X_repetitions)
+                    scores_ref_sampling = kde.score_samples(test_points)
+                    sample_ref_sampling = kde.sample(random_state=1234)
+                    assert_allclose(scores_weight, scores_ref_sampling)
+                    assert_allclose(sample_weight, sample_ref_sampling)
+
+                    # Test that sample weights has a non-trivial effect
+                    diff = np.max(np.abs(scores_no_weight - scores_weight))
+                    assert diff > 0.001
+
+                    # Test invariance with respect to arbitrary scaling
+                    scale_factor = rng.rand()
+                    kde.fit(X, sample_weight=(scale_factor * weights))
+                    scores_scaled_weight = kde.score_samples(test_points)
+                    assert_allclose(scores_scaled_weight, scores_weight)
+
+
+@pytest.mark.parametrize("sample_weight", [None, [0.1, 0.2, 0.3]])
+def test_pickling(tmpdir, sample_weight):
+    # Make sure that predictions are the same before and after pickling. Used
+    # to be a bug because sample_weights wasn't pickled and the resulting tree
+    # would miss some info.
+
+    kde = KernelDensity()
+    data = np.reshape([1.0, 2.0, 3.0], (-1, 1))
+    kde.fit(data, sample_weight=sample_weight)
+
+    X = np.reshape([1.1, 2.1], (-1, 1))
+    scores = kde.score_samples(X)
+
+    file_path = str(tmpdir.join("dump.pkl"))
+    joblib.dump(kde, file_path)
+    kde = joblib.load(file_path)
+    scores_pickled = kde.score_samples(X)
+
+    assert_allclose(scores, scores_pickled)
+
+
+@pytest.mark.parametrize("method", ["score_samples", "sample"])
+def test_check_is_fitted(method):
+    # Check that predict raises an exception in an unfitted estimator.
+    # Unfitted estimators should raise a NotFittedError.
+    rng = np.random.RandomState(0)
+    X = rng.randn(10, 2)
+    kde = KernelDensity()
+
+    with pytest.raises(NotFittedError):
+        getattr(kde, method)(X)
+
+
+@pytest.mark.parametrize("bandwidth", ["scott", "silverman", 0.1])
+def test_bandwidth(bandwidth):
+    n_samples, n_features = (100, 3)
+    rng = np.random.RandomState(0)
+    X = rng.randn(n_samples, n_features)
+    kde = KernelDensity(bandwidth=bandwidth).fit(X)
+    samp = kde.sample(100)
+    kde_sc = kde.score_samples(X)
+    assert X.shape == samp.shape
+    assert kde_sc.shape == (n_samples,)
+
+    # Test that the attribute self.bandwidth_ has the expected value
+    if bandwidth == "scott":
+        h = X.shape[0] ** (-1 / (X.shape[1] + 4))
+    elif bandwidth == "silverman":
+        h = (X.shape[0] * (X.shape[1] + 2) / 4) ** (-1 / (X.shape[1] + 4))
+    else:
+        h = bandwidth
+    assert kde.bandwidth_ == pytest.approx(h)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_lof.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_lof.py
new file mode 100644
index 0000000000000000000000000000000000000000..140d0d9ba6dff1ba15acf54fe769cd526e832c3d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_lof.py
@@ -0,0 +1,394 @@
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+import re
+from math import sqrt
+
+import numpy as np
+import pytest
+
+from sklearn import metrics, neighbors
+from sklearn.datasets import load_iris
+from sklearn.metrics import roc_auc_score
+from sklearn.utils import check_random_state
+from sklearn.utils._testing import assert_allclose, assert_array_equal
+from sklearn.utils.estimator_checks import (
+    check_outlier_corruption,
+    parametrize_with_checks,
+)
+from sklearn.utils.fixes import CSR_CONTAINERS
+
+# load the iris dataset
+# and randomly permute it
+rng = check_random_state(0)
+iris = load_iris()
+perm = rng.permutation(iris.target.size)
+iris.data = iris.data[perm]
+iris.target = iris.target[perm]
+
+
+def test_lof(global_dtype):
+    # Toy sample (the last two samples are outliers):
+    X = np.asarray(
+        [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1], [5, 3], [-4, 2]],
+        dtype=global_dtype,
+    )
+
+    # Test LocalOutlierFactor:
+    clf = neighbors.LocalOutlierFactor(n_neighbors=5)
+    score = clf.fit(X).negative_outlier_factor_
+    assert_array_equal(clf._fit_X, X)
+
+    # Assert largest outlier score is smaller than smallest inlier score:
+    assert np.min(score[:-2]) > np.max(score[-2:])
+
+    # Assert predict() works:
+    clf = neighbors.LocalOutlierFactor(contamination=0.25, n_neighbors=5).fit(X)
+    expected_predictions = 6 * [1] + 2 * [-1]
+    assert_array_equal(clf._predict(), expected_predictions)
+    assert_array_equal(clf.fit_predict(X), expected_predictions)
+
+
+def test_lof_performance(global_dtype):
+    # Generate train/test data
+    rng = check_random_state(2)
+    X = 0.3 * rng.randn(120, 2).astype(global_dtype, copy=False)
+    X_train = X[:100]
+
+    # Generate some abnormal novel observations
+    X_outliers = rng.uniform(low=-4, high=4, size=(20, 2)).astype(
+        global_dtype, copy=False
+    )
+    X_test = np.r_[X[100:], X_outliers]
+    y_test = np.array([0] * 20 + [1] * 20)
+
+    # fit the model for novelty detection
+    clf = neighbors.LocalOutlierFactor(novelty=True).fit(X_train)
+
+    # predict scores (the lower, the more normal)
+    y_pred = -clf.decision_function(X_test)
+
+    # check that roc_auc is good
+    assert roc_auc_score(y_test, y_pred) > 0.99
+
+
+def test_lof_values(global_dtype):
+    # toy samples:
+    X_train = np.asarray([[1, 1], [1, 2], [2, 1]], dtype=global_dtype)
+    clf1 = neighbors.LocalOutlierFactor(
+        n_neighbors=2, contamination=0.1, novelty=True
+    ).fit(X_train)
+    clf2 = neighbors.LocalOutlierFactor(n_neighbors=2, novelty=True).fit(X_train)
+    s_0 = 2.0 * sqrt(2.0) / (1.0 + sqrt(2.0))
+    s_1 = (1.0 + sqrt(2)) * (1.0 / (4.0 * sqrt(2.0)) + 1.0 / (2.0 + 2.0 * sqrt(2)))
+    # check predict()
+    assert_allclose(-clf1.negative_outlier_factor_, [s_0, s_1, s_1])
+    assert_allclose(-clf2.negative_outlier_factor_, [s_0, s_1, s_1])
+    # check predict(one sample not in train)
+    assert_allclose(-clf1.score_samples([[2.0, 2.0]]), [s_0])
+    assert_allclose(-clf2.score_samples([[2.0, 2.0]]), [s_0])
+    # check predict(one sample already in train)
+    assert_allclose(-clf1.score_samples([[1.0, 1.0]]), [s_1])
+    assert_allclose(-clf2.score_samples([[1.0, 1.0]]), [s_1])
+
+
+def test_lof_precomputed(global_dtype, random_state=42):
+    """Tests LOF with a distance matrix."""
+    # Note: smaller samples may result in spurious test success
+    rng = np.random.RandomState(random_state)
+    X = rng.random_sample((10, 4)).astype(global_dtype, copy=False)
+    Y = rng.random_sample((3, 4)).astype(global_dtype, copy=False)
+    DXX = metrics.pairwise_distances(X, metric="euclidean")
+    DYX = metrics.pairwise_distances(Y, X, metric="euclidean")
+    # As a feature matrix (n_samples by n_features)
+    lof_X = neighbors.LocalOutlierFactor(n_neighbors=3, novelty=True)
+    lof_X.fit(X)
+    pred_X_X = lof_X._predict()
+    pred_X_Y = lof_X.predict(Y)
+
+    # As a dense distance matrix (n_samples by n_samples)
+    lof_D = neighbors.LocalOutlierFactor(
+        n_neighbors=3, algorithm="brute", metric="precomputed", novelty=True
+    )
+    lof_D.fit(DXX)
+    pred_D_X = lof_D._predict()
+    pred_D_Y = lof_D.predict(DYX)
+
+    assert_allclose(pred_X_X, pred_D_X)
+    assert_allclose(pred_X_Y, pred_D_Y)
+
+
+def test_n_neighbors_attribute():
+    X = iris.data
+    clf = neighbors.LocalOutlierFactor(n_neighbors=500).fit(X)
+    assert clf.n_neighbors_ == X.shape[0] - 1
+
+    clf = neighbors.LocalOutlierFactor(n_neighbors=500)
+    msg = "n_neighbors will be set to (n_samples - 1)"
+    with pytest.warns(UserWarning, match=re.escape(msg)):
+        clf.fit(X)
+    assert clf.n_neighbors_ == X.shape[0] - 1
+
+
+def test_score_samples(global_dtype):
+    X_train = np.asarray([[1, 1], [1, 2], [2, 1]], dtype=global_dtype)
+    X_test = np.asarray([[2.0, 2.0]], dtype=global_dtype)
+    clf1 = neighbors.LocalOutlierFactor(
+        n_neighbors=2, contamination=0.1, novelty=True
+    ).fit(X_train)
+    clf2 = neighbors.LocalOutlierFactor(n_neighbors=2, novelty=True).fit(X_train)
+
+    clf1_scores = clf1.score_samples(X_test)
+    clf1_decisions = clf1.decision_function(X_test)
+
+    clf2_scores = clf2.score_samples(X_test)
+    clf2_decisions = clf2.decision_function(X_test)
+
+    assert_allclose(
+        clf1_scores,
+        clf1_decisions + clf1.offset_,
+    )
+    assert_allclose(
+        clf2_scores,
+        clf2_decisions + clf2.offset_,
+    )
+    assert_allclose(clf1_scores, clf2_scores)
+
+
+def test_novelty_errors():
+    X = iris.data
+
+    # check errors for novelty=False
+    clf = neighbors.LocalOutlierFactor()
+    clf.fit(X)
+    # predict, decision_function and score_samples raise ValueError
+    for method in ["predict", "decision_function", "score_samples"]:
+        outer_msg = f"'LocalOutlierFactor' has no attribute '{method}'"
+        inner_msg = "{} is not available when novelty=False".format(method)
+        with pytest.raises(AttributeError, match=outer_msg) as exec_info:
+            getattr(clf, method)
+
+        assert isinstance(exec_info.value.__cause__, AttributeError)
+        assert inner_msg in str(exec_info.value.__cause__)
+
+    # check errors for novelty=True
+    clf = neighbors.LocalOutlierFactor(novelty=True)
+
+    outer_msg = "'LocalOutlierFactor' has no attribute 'fit_predict'"
+    inner_msg = "fit_predict is not available when novelty=True"
+    with pytest.raises(AttributeError, match=outer_msg) as exec_info:
+        getattr(clf, "fit_predict")
+
+    assert isinstance(exec_info.value.__cause__, AttributeError)
+    assert inner_msg in str(exec_info.value.__cause__)
+
+
+def test_novelty_training_scores(global_dtype):
+    # check that the scores of the training samples are still accessible
+    # when novelty=True through the negative_outlier_factor_ attribute
+    X = iris.data.astype(global_dtype)
+
+    # fit with novelty=False
+    clf_1 = neighbors.LocalOutlierFactor()
+    clf_1.fit(X)
+    scores_1 = clf_1.negative_outlier_factor_
+
+    # fit with novelty=True
+    clf_2 = neighbors.LocalOutlierFactor(novelty=True)
+    clf_2.fit(X)
+    scores_2 = clf_2.negative_outlier_factor_
+
+    assert_allclose(scores_1, scores_2)
+
+
+def test_hasattr_prediction():
+    # check availability of prediction methods depending on novelty value.
+    X = [[1, 1], [1, 2], [2, 1]]
+
+    # when novelty=True
+    clf = neighbors.LocalOutlierFactor(novelty=True)
+    clf.fit(X)
+    assert hasattr(clf, "predict")
+    assert hasattr(clf, "decision_function")
+    assert hasattr(clf, "score_samples")
+    assert not hasattr(clf, "fit_predict")
+
+    # when novelty=False
+    clf = neighbors.LocalOutlierFactor(novelty=False)
+    clf.fit(X)
+    assert hasattr(clf, "fit_predict")
+    assert not hasattr(clf, "predict")
+    assert not hasattr(clf, "decision_function")
+    assert not hasattr(clf, "score_samples")
+
+
+@parametrize_with_checks([neighbors.LocalOutlierFactor(novelty=True)])
+def test_novelty_true_common_tests(estimator, check):
+    # the common tests are run for the default LOF (novelty=False).
+    # here we run these common tests for LOF when novelty=True
+    check(estimator)
+
+
+@pytest.mark.parametrize("expected_outliers", [30, 53])
+def test_predicted_outlier_number(expected_outliers):
+    # the number of predicted outliers should be equal to the number of
+    # expected outliers unless there are ties in the abnormality scores.
+    X = iris.data
+    n_samples = X.shape[0]
+    contamination = float(expected_outliers) / n_samples
+
+    clf = neighbors.LocalOutlierFactor(contamination=contamination)
+    y_pred = clf.fit_predict(X)
+
+    num_outliers = np.sum(y_pred != 1)
+    if num_outliers != expected_outliers:
+        y_dec = clf.negative_outlier_factor_
+        check_outlier_corruption(num_outliers, expected_outliers, y_dec)
+
+
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_sparse(csr_container):
+    # LocalOutlierFactor must support CSR inputs
+    # TODO: compare results on dense and sparse data as proposed in:
+    # https://github.com/scikit-learn/scikit-learn/pull/23585#discussion_r968388186
+    X = csr_container(iris.data)
+
+    lof = neighbors.LocalOutlierFactor(novelty=True)
+    lof.fit(X)
+    lof.predict(X)
+    lof.score_samples(X)
+    lof.decision_function(X)
+
+    lof = neighbors.LocalOutlierFactor(novelty=False)
+    lof.fit_predict(X)
+
+
+def test_lof_error_n_neighbors_too_large():
+    """Check that we raise a proper error message when n_neighbors == n_samples.
+
+    Non-regression test for:
+    https://github.com/scikit-learn/scikit-learn/issues/17207
+    """
+    X = np.ones((7, 7))
+
+    msg = (
+        "Expected n_neighbors < n_samples_fit, but n_neighbors = 1, "
+        "n_samples_fit = 1, n_samples = 1"
+    )
+    with pytest.raises(ValueError, match=msg):
+        lof = neighbors.LocalOutlierFactor(n_neighbors=1).fit(X[:1])
+
+    lof = neighbors.LocalOutlierFactor(n_neighbors=2).fit(X[:2])
+    assert lof.n_samples_fit_ == 2
+
+    msg = (
+        "Expected n_neighbors < n_samples_fit, but n_neighbors = 2, "
+        "n_samples_fit = 2, n_samples = 2"
+    )
+    with pytest.raises(ValueError, match=msg):
+        lof.kneighbors(None, n_neighbors=2)
+
+    distances, indices = lof.kneighbors(None, n_neighbors=1)
+    assert distances.shape == (2, 1)
+    assert indices.shape == (2, 1)
+
+    msg = (
+        "Expected n_neighbors <= n_samples_fit, but n_neighbors = 3, "
+        "n_samples_fit = 2, n_samples = 7"
+    )
+    with pytest.raises(ValueError, match=msg):
+        lof.kneighbors(X, n_neighbors=3)
+
+    (
+        distances,
+        indices,
+    ) = lof.kneighbors(X, n_neighbors=2)
+    assert distances.shape == (7, 2)
+    assert indices.shape == (7, 2)
+
+
+@pytest.mark.parametrize("algorithm", ["auto", "ball_tree", "kd_tree", "brute"])
+@pytest.mark.parametrize("novelty", [True, False])
+@pytest.mark.parametrize("contamination", [0.5, "auto"])
+def test_lof_input_dtype_preservation(global_dtype, algorithm, contamination, novelty):
+    """Check that the fitted attributes are stored using the data type of X."""
+    X = iris.data.astype(global_dtype, copy=False)
+
+    iso = neighbors.LocalOutlierFactor(
+        n_neighbors=5, algorithm=algorithm, contamination=contamination, novelty=novelty
+    )
+    iso.fit(X)
+
+    assert iso.negative_outlier_factor_.dtype == global_dtype
+
+    for method in ("score_samples", "decision_function"):
+        if hasattr(iso, method):
+            y_pred = getattr(iso, method)(X)
+            assert y_pred.dtype == global_dtype
+
+
+@pytest.mark.parametrize("algorithm", ["auto", "ball_tree", "kd_tree", "brute"])
+@pytest.mark.parametrize("novelty", [True, False])
+@pytest.mark.parametrize("contamination", [0.5, "auto"])
+def test_lof_dtype_equivalence(algorithm, novelty, contamination):
+    """Check the equivalence of the results with 32 and 64 bits input."""
+
+    inliers = iris.data[:50]  # setosa iris are really distinct from others
+    outliers = iris.data[-5:]  # virginica will be considered as outliers
+    # lower the precision of the input data to check that we have an equivalence when
+    # making the computation in 32 and 64 bits.
+    X = np.concatenate([inliers, outliers], axis=0).astype(np.float32)
+
+    lof_32 = neighbors.LocalOutlierFactor(
+        algorithm=algorithm, novelty=novelty, contamination=contamination
+    )
+    X_32 = X.astype(np.float32, copy=True)
+    lof_32.fit(X_32)
+
+    lof_64 = neighbors.LocalOutlierFactor(
+        algorithm=algorithm, novelty=novelty, contamination=contamination
+    )
+    X_64 = X.astype(np.float64, copy=True)
+    lof_64.fit(X_64)
+
+    assert_allclose(lof_32.negative_outlier_factor_, lof_64.negative_outlier_factor_)
+
+    for method in ("score_samples", "decision_function", "predict", "fit_predict"):
+        if hasattr(lof_32, method):
+            y_pred_32 = getattr(lof_32, method)(X_32)
+            y_pred_64 = getattr(lof_64, method)(X_64)
+            assert_allclose(y_pred_32, y_pred_64, atol=0.0002)
+
+
+def test_lof_duplicate_samples():
+    """
+    Check that LocalOutlierFactor raises a warning when duplicate values
+    in the training data cause inaccurate results.
+
+    Non-regression test for:
+    https://github.com/scikit-learn/scikit-learn/issues/27839
+    """
+
+    rng = np.random.default_rng(0)
+
+    x = rng.permutation(
+        np.hstack(
+            [
+                [0.1] * 1000,  # constant values
+                np.linspace(0.1, 0.3, num=3000),
+                rng.random(500) * 100,  # the clear outliers
+            ]
+        )
+    )
+    X = x.reshape(-1, 1)
+
+    error_msg = (
+        "Duplicate values are leading to incorrect results. "
+        "Increase the number of neighbors for more accurate results."
+    )
+
+    lof = neighbors.LocalOutlierFactor(n_neighbors=5, contamination=0.1)
+
+    # Catch the warning
+    with pytest.warns(UserWarning, match=re.escape(error_msg)):
+        lof.fit_predict(X)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_nca.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_nca.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebfb01d12e3acbbb31d79a3a0573f39884cac6bb
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_nca.py
@@ -0,0 +1,563 @@
+"""
+Testing for Neighborhood Component Analysis module (sklearn.neighbors.nca)
+"""
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+import re
+
+import numpy as np
+import pytest
+from numpy.testing import assert_array_almost_equal, assert_array_equal
+from scipy.optimize import check_grad
+
+from sklearn import clone
+from sklearn.datasets import load_iris, make_blobs, make_classification
+from sklearn.exceptions import ConvergenceWarning
+from sklearn.metrics import pairwise_distances
+from sklearn.neighbors import NeighborhoodComponentsAnalysis
+from sklearn.preprocessing import LabelEncoder
+from sklearn.utils import check_random_state
+from sklearn.utils.validation import validate_data
+
+rng = check_random_state(0)
+# Load and shuffle the iris dataset.
+iris = load_iris()
+perm = rng.permutation(iris.target.size)
+iris_data = iris.data[perm]
+iris_target = iris.target[perm]
+# Avoid having test data introducing dependencies between tests.
+iris_data.flags.writeable = False
+iris_target.flags.writeable = False
+EPS = np.finfo(float).eps
+
+
+def test_simple_example():
+    """Test on a simple example.
+
+    Puts four points in the input space where the opposite labels points are
+    next to each other. After transform the samples from the same class
+    should be next to each other.
+
+    """
+    X = np.array([[0, 0], [0, 1], [2, 0], [2, 1]])
+    y = np.array([1, 0, 1, 0])
+    nca = NeighborhoodComponentsAnalysis(
+        n_components=2, init="identity", random_state=42
+    )
+    nca.fit(X, y)
+    X_t = nca.transform(X)
+    assert_array_equal(pairwise_distances(X_t).argsort()[:, 1], np.array([2, 3, 0, 1]))
+
+
+def test_toy_example_collapse_points():
+    """Test on a toy example of three points that should collapse
+
+    We build a simple example: two points from the same class and a point from
+    a different class in the middle of them. On this simple example, the new
+    (transformed) points should all collapse into one single point. Indeed, the
+    objective is 2/(1 + exp(d/2)), with d the euclidean distance between the
+    two samples from the same class. This is maximized for d=0 (because d>=0),
+    with an objective equal to 1 (loss=-1.).
+
+    """
+    rng = np.random.RandomState(42)
+    input_dim = 5
+    two_points = rng.randn(2, input_dim)
+    X = np.vstack([two_points, two_points.mean(axis=0)[np.newaxis, :]])
+    y = [0, 0, 1]
+
+    class LossStorer:
+        def __init__(self, X, y):
+            self.loss = np.inf  # initialize the loss to very high
+            # Initialize a fake NCA and variables needed to compute the loss:
+            self.fake_nca = NeighborhoodComponentsAnalysis()
+            self.fake_nca.n_iter_ = np.inf
+            self.X, y = validate_data(self.fake_nca, X, y, ensure_min_samples=2)
+            y = LabelEncoder().fit_transform(y)
+            self.same_class_mask = y[:, np.newaxis] == y[np.newaxis, :]
+
+        def callback(self, transformation, n_iter):
+            """Stores the last value of the loss function"""
+            self.loss, _ = self.fake_nca._loss_grad_lbfgs(
+                transformation, self.X, self.same_class_mask, -1.0
+            )
+
+    loss_storer = LossStorer(X, y)
+    nca = NeighborhoodComponentsAnalysis(random_state=42, callback=loss_storer.callback)
+    X_t = nca.fit_transform(X, y)
+    print(X_t)
+    # test that points are collapsed into one point
+    assert_array_almost_equal(X_t - X_t[0], 0.0)
+    assert abs(loss_storer.loss + 1) < 1e-10
+
+
+def test_finite_differences(global_random_seed):
+    """Test gradient of loss function
+
+    Assert that the gradient is almost equal to its finite differences
+    approximation.
+    """
+    # Initialize the transformation `M`, as well as `X` and `y` and `NCA`
+    rng = np.random.RandomState(global_random_seed)
+    X, y = make_classification(random_state=global_random_seed)
+    M = rng.randn(rng.randint(1, X.shape[1] + 1), X.shape[1])
+    nca = NeighborhoodComponentsAnalysis()
+    nca.n_iter_ = 0
+    mask = y[:, np.newaxis] == y[np.newaxis, :]
+
+    def fun(M):
+        return nca._loss_grad_lbfgs(M, X, mask)[0]
+
+    def grad(M):
+        return nca._loss_grad_lbfgs(M, X, mask)[1]
+
+    # compare the gradient to a finite difference approximation
+    diff = check_grad(fun, grad, M.ravel())
+    assert diff == pytest.approx(0.0, abs=1e-4)
+
+
+def test_params_validation():
+    # Test that invalid parameters raise value error
+    X = np.arange(12).reshape(4, 3)
+    y = [1, 1, 2, 2]
+    NCA = NeighborhoodComponentsAnalysis
+    rng = np.random.RandomState(42)
+
+    init = rng.rand(5, 3)
+    msg = (
+        f"The output dimensionality ({init.shape[0]}) "
+        "of the given linear transformation `init` cannot be "
+        f"greater than its input dimensionality ({init.shape[1]})."
+    )
+    with pytest.raises(ValueError, match=re.escape(msg)):
+        NCA(init=init).fit(X, y)
+    n_components = 10
+    msg = (
+        "The preferred dimensionality of the projected space "
+        f"`n_components` ({n_components}) cannot be greater "
+        f"than the given data dimensionality ({X.shape[1]})!"
+    )
+    with pytest.raises(ValueError, match=re.escape(msg)):
+        NCA(n_components=n_components).fit(X, y)
+
+
+def test_transformation_dimensions():
+    X = np.arange(12).reshape(4, 3)
+    y = [1, 1, 2, 2]
+
+    # Fail if transformation input dimension does not match inputs dimensions
+    transformation = np.array([[1, 2], [3, 4]])
+    with pytest.raises(ValueError):
+        NeighborhoodComponentsAnalysis(init=transformation).fit(X, y)
+
+    # Fail if transformation output dimension is larger than
+    # transformation input dimension
+    transformation = np.array([[1, 2], [3, 4], [5, 6]])
+    # len(transformation) > len(transformation[0])
+    with pytest.raises(ValueError):
+        NeighborhoodComponentsAnalysis(init=transformation).fit(X, y)
+
+    # Pass otherwise
+    transformation = np.arange(9).reshape(3, 3)
+    NeighborhoodComponentsAnalysis(init=transformation).fit(X, y)
+
+
+def test_n_components():
+    rng = np.random.RandomState(42)
+    X = np.arange(12).reshape(4, 3)
+    y = [1, 1, 2, 2]
+
+    init = rng.rand(X.shape[1] - 1, 3)
+
+    # n_components = X.shape[1] != transformation.shape[0]
+    n_components = X.shape[1]
+    nca = NeighborhoodComponentsAnalysis(init=init, n_components=n_components)
+    msg = (
+        "The preferred dimensionality of the projected space "
+        f"`n_components` ({n_components}) does not match the output "
+        "dimensionality of the given linear transformation "
+        f"`init` ({init.shape[0]})!"
+    )
+    with pytest.raises(ValueError, match=re.escape(msg)):
+        nca.fit(X, y)
+
+    # n_components > X.shape[1]
+    n_components = X.shape[1] + 2
+    nca = NeighborhoodComponentsAnalysis(init=init, n_components=n_components)
+    msg = (
+        "The preferred dimensionality of the projected space "
+        f"`n_components` ({n_components}) cannot be greater than "
+        f"the given data dimensionality ({X.shape[1]})!"
+    )
+    with pytest.raises(ValueError, match=re.escape(msg)):
+        nca.fit(X, y)
+
+    # n_components < X.shape[1]
+    nca = NeighborhoodComponentsAnalysis(n_components=2, init="identity")
+    nca.fit(X, y)
+
+
+def test_init_transformation():
+    rng = np.random.RandomState(42)
+    X, y = make_blobs(n_samples=30, centers=6, n_features=5, random_state=0)
+
+    # Start learning from scratch
+    nca = NeighborhoodComponentsAnalysis(init="identity")
+    nca.fit(X, y)
+
+    # Initialize with random
+    nca_random = NeighborhoodComponentsAnalysis(init="random")
+    nca_random.fit(X, y)
+
+    # Initialize with auto
+    nca_auto = NeighborhoodComponentsAnalysis(init="auto")
+    nca_auto.fit(X, y)
+
+    # Initialize with PCA
+    nca_pca = NeighborhoodComponentsAnalysis(init="pca")
+    nca_pca.fit(X, y)
+
+    # Initialize with LDA
+    nca_lda = NeighborhoodComponentsAnalysis(init="lda")
+    nca_lda.fit(X, y)
+
+    init = rng.rand(X.shape[1], X.shape[1])
+    nca = NeighborhoodComponentsAnalysis(init=init)
+    nca.fit(X, y)
+
+    # init.shape[1] must match X.shape[1]
+    init = rng.rand(X.shape[1], X.shape[1] + 1)
+    nca = NeighborhoodComponentsAnalysis(init=init)
+    msg = (
+        f"The input dimensionality ({init.shape[1]}) of the given "
+        "linear transformation `init` must match the "
+        f"dimensionality of the given inputs `X` ({X.shape[1]})."
+    )
+    with pytest.raises(ValueError, match=re.escape(msg)):
+        nca.fit(X, y)
+
+    # init.shape[0] must be <= init.shape[1]
+    init = rng.rand(X.shape[1] + 1, X.shape[1])
+    nca = NeighborhoodComponentsAnalysis(init=init)
+    msg = (
+        f"The output dimensionality ({init.shape[0]}) of the given "
+        "linear transformation `init` cannot be "
+        f"greater than its input dimensionality ({init.shape[1]})."
+    )
+    with pytest.raises(ValueError, match=re.escape(msg)):
+        nca.fit(X, y)
+
+    # init.shape[0] must match n_components
+    init = rng.rand(X.shape[1], X.shape[1])
+    n_components = X.shape[1] - 2
+    nca = NeighborhoodComponentsAnalysis(init=init, n_components=n_components)
+    msg = (
+        "The preferred dimensionality of the "
+        f"projected space `n_components` ({n_components}) "
+        "does not match the output dimensionality of the given "
+        f"linear transformation `init` ({init.shape[0]})!"
+    )
+    with pytest.raises(ValueError, match=re.escape(msg)):
+        nca.fit(X, y)
+
+
+@pytest.mark.parametrize("n_samples", [3, 5, 7, 11])
+@pytest.mark.parametrize("n_features", [3, 5, 7, 11])
+@pytest.mark.parametrize("n_classes", [5, 7, 11])
+@pytest.mark.parametrize("n_components", [3, 5, 7, 11])
+def test_auto_init(n_samples, n_features, n_classes, n_components):
+    # Test that auto choose the init as expected with every configuration
+    # of order of n_samples, n_features, n_classes and n_components.
+    rng = np.random.RandomState(42)
+    nca_base = NeighborhoodComponentsAnalysis(
+        init="auto", n_components=n_components, max_iter=1, random_state=rng
+    )
+    if n_classes >= n_samples:
+        pass
+        # n_classes > n_samples is impossible, and n_classes == n_samples
+        # throws an error from lda but is an absurd case
+    else:
+        X = rng.randn(n_samples, n_features)
+        y = np.tile(range(n_classes), n_samples // n_classes + 1)[:n_samples]
+        if n_components > n_features:
+            # this would return a ValueError, which is already tested in
+            # test_params_validation
+            pass
+        else:
+            nca = clone(nca_base)
+            nca.fit(X, y)
+            if n_components <= min(n_classes - 1, n_features):
+                nca_other = clone(nca_base).set_params(init="lda")
+            elif n_components < min(n_features, n_samples):
+                nca_other = clone(nca_base).set_params(init="pca")
+            else:
+                nca_other = clone(nca_base).set_params(init="identity")
+            nca_other.fit(X, y)
+            assert_array_almost_equal(nca.components_, nca_other.components_)
+
+
+def test_warm_start_validation():
+    X, y = make_classification(
+        n_samples=30,
+        n_features=5,
+        n_classes=4,
+        n_redundant=0,
+        n_informative=5,
+        random_state=0,
+    )
+
+    nca = NeighborhoodComponentsAnalysis(warm_start=True, max_iter=5)
+    nca.fit(X, y)
+
+    X_less_features, y = make_classification(
+        n_samples=30,
+        n_features=4,
+        n_classes=4,
+        n_redundant=0,
+        n_informative=4,
+        random_state=0,
+    )
+    msg = (
+        f"The new inputs dimensionality ({X_less_features.shape[1]}) "
+        "does not match the input dimensionality of the previously learned "
+        f"transformation ({nca.components_.shape[1]})."
+    )
+    with pytest.raises(ValueError, match=re.escape(msg)):
+        nca.fit(X_less_features, y)
+
+
+def test_warm_start_effectiveness():
+    # A 1-iteration second fit on same data should give almost same result
+    # with warm starting, and quite different result without warm starting.
+
+    nca_warm = NeighborhoodComponentsAnalysis(warm_start=True, random_state=0)
+    nca_warm.fit(iris_data, iris_target)
+    transformation_warm = nca_warm.components_
+    nca_warm.max_iter = 1
+    nca_warm.fit(iris_data, iris_target)
+    transformation_warm_plus_one = nca_warm.components_
+
+    nca_cold = NeighborhoodComponentsAnalysis(warm_start=False, random_state=0)
+    nca_cold.fit(iris_data, iris_target)
+    transformation_cold = nca_cold.components_
+    nca_cold.max_iter = 1
+    nca_cold.fit(iris_data, iris_target)
+    transformation_cold_plus_one = nca_cold.components_
+
+    diff_warm = np.sum(np.abs(transformation_warm_plus_one - transformation_warm))
+    diff_cold = np.sum(np.abs(transformation_cold_plus_one - transformation_cold))
+    assert diff_warm < 3.0, (
+        "Transformer changed significantly after one "
+        "iteration even though it was warm-started."
+    )
+
+    assert diff_cold > diff_warm, (
+        "Cold-started transformer changed less "
+        "significantly than warm-started "
+        "transformer after one iteration."
+    )
+
+
+@pytest.mark.parametrize(
+    "init_name", ["pca", "lda", "identity", "random", "precomputed"]
+)
+def test_verbose(init_name, capsys):
+    # assert there is proper output when verbose = 1, for every initialization
+    # except auto because auto will call one of the others
+    rng = np.random.RandomState(42)
+    X, y = make_blobs(n_samples=30, centers=6, n_features=5, random_state=0)
+    regexp_init = r"... done in \ *\d+\.\d{2}s"
+    msgs = {
+        "pca": "Finding principal components" + regexp_init,
+        "lda": "Finding most discriminative components" + regexp_init,
+    }
+    if init_name == "precomputed":
+        init = rng.randn(X.shape[1], X.shape[1])
+    else:
+        init = init_name
+    nca = NeighborhoodComponentsAnalysis(verbose=1, init=init)
+    nca.fit(X, y)
+    out, _ = capsys.readouterr()
+
+    # check output
+    lines = re.split("\n+", out)
+    # if pca or lda init, an additional line is printed, so we test
+    # it and remove it to test the rest equally among initializations
+    if init_name in ["pca", "lda"]:
+        assert re.match(msgs[init_name], lines[0])
+        lines = lines[1:]
+    assert lines[0] == "[NeighborhoodComponentsAnalysis]"
+    header = "{:>10} {:>20} {:>10}".format("Iteration", "Objective Value", "Time(s)")
+    assert lines[1] == "[NeighborhoodComponentsAnalysis] {}".format(header)
+    assert lines[2] == "[NeighborhoodComponentsAnalysis] {}".format("-" * len(header))
+    for line in lines[3:-2]:
+        # The following regex will match for instance:
+        # '[NeighborhoodComponentsAnalysis]  0    6.988936e+01   0.01'
+        assert re.match(
+            r"\[NeighborhoodComponentsAnalysis\] *\d+ *\d\.\d{6}e"
+            r"[+|-]\d+\ *\d+\.\d{2}",
+            line,
+        )
+    assert re.match(
+        r"\[NeighborhoodComponentsAnalysis\] Training took\ *\d+\.\d{2}s\.",
+        lines[-2],
+    )
+    assert lines[-1] == ""
+
+
+def test_no_verbose(capsys):
+    # assert by default there is no output (verbose=0)
+    nca = NeighborhoodComponentsAnalysis()
+    nca.fit(iris_data, iris_target)
+    out, _ = capsys.readouterr()
+    # check output
+    assert out == ""
+
+
+def test_singleton_class():
+    X = iris_data.copy()
+    y = iris_target.copy()
+
+    # one singleton class
+    singleton_class = 1
+    (ind_singleton,) = np.where(y == singleton_class)
+    y[ind_singleton] = 2
+    y[ind_singleton[0]] = singleton_class
+
+    nca = NeighborhoodComponentsAnalysis(max_iter=30)
+    nca.fit(X, y)
+
+    # One non-singleton class
+    (ind_1,) = np.where(y == 1)
+    (ind_2,) = np.where(y == 2)
+    y[ind_1] = 0
+    y[ind_1[0]] = 1
+    y[ind_2] = 0
+    y[ind_2[0]] = 2
+
+    nca = NeighborhoodComponentsAnalysis(max_iter=30)
+    nca.fit(X, y)
+
+    # Only singleton classes
+    (ind_0,) = np.where(y == 0)
+    (ind_1,) = np.where(y == 1)
+    (ind_2,) = np.where(y == 2)
+    X = X[[ind_0[0], ind_1[0], ind_2[0]]]
+    y = y[[ind_0[0], ind_1[0], ind_2[0]]]
+
+    nca = NeighborhoodComponentsAnalysis(init="identity", max_iter=30)
+    nca.fit(X, y)
+    assert_array_equal(X, nca.transform(X))
+
+
+def test_one_class():
+    X = iris_data[iris_target == 0]
+    y = iris_target[iris_target == 0]
+
+    nca = NeighborhoodComponentsAnalysis(
+        max_iter=30, n_components=X.shape[1], init="identity"
+    )
+    nca.fit(X, y)
+    assert_array_equal(X, nca.transform(X))
+
+
+def test_callback(capsys):
+    max_iter = 10
+
+    def my_cb(transformation, n_iter):
+        assert transformation.shape == (iris_data.shape[1] ** 2,)
+        rem_iter = max_iter - n_iter
+        print("{} iterations remaining...".format(rem_iter))
+
+    # assert that my_cb is called
+    nca = NeighborhoodComponentsAnalysis(max_iter=max_iter, callback=my_cb, verbose=1)
+    nca.fit(iris_data, iris_target)
+    out, _ = capsys.readouterr()
+
+    # check output
+    assert "{} iterations remaining...".format(max_iter - 1) in out
+
+
+def test_expected_transformation_shape():
+    """Test that the transformation has the expected shape."""
+    X = iris_data
+    y = iris_target
+
+    class TransformationStorer:
+        def __init__(self, X, y):
+            # Initialize a fake NCA and variables needed to call the loss
+            # function:
+            self.fake_nca = NeighborhoodComponentsAnalysis()
+            self.fake_nca.n_iter_ = np.inf
+            self.X, y = validate_data(self.fake_nca, X, y, ensure_min_samples=2)
+            y = LabelEncoder().fit_transform(y)
+            self.same_class_mask = y[:, np.newaxis] == y[np.newaxis, :]
+
+        def callback(self, transformation, n_iter):
+            """Stores the last value of the transformation taken as input by
+            the optimizer"""
+            self.transformation = transformation
+
+    transformation_storer = TransformationStorer(X, y)
+    cb = transformation_storer.callback
+    nca = NeighborhoodComponentsAnalysis(max_iter=5, callback=cb)
+    nca.fit(X, y)
+    assert transformation_storer.transformation.size == X.shape[1] ** 2
+
+
+def test_convergence_warning():
+    nca = NeighborhoodComponentsAnalysis(max_iter=2, verbose=1)
+    cls_name = nca.__class__.__name__
+    msg = "[{}] NCA did not converge".format(cls_name)
+    with pytest.warns(ConvergenceWarning, match=re.escape(msg)):
+        nca.fit(iris_data, iris_target)
+
+
+@pytest.mark.parametrize(
+    "param, value",
+    [
+        ("n_components", np.int32(3)),
+        ("max_iter", np.int32(100)),
+        ("tol", np.float32(0.0001)),
+    ],
+)
+def test_parameters_valid_types(param, value):
+    # check that no error is raised when parameters have numpy integer or
+    # floating types.
+    nca = NeighborhoodComponentsAnalysis(**{param: value})
+
+    X = iris_data
+    y = iris_target
+
+    nca.fit(X, y)
+
+
+@pytest.mark.parametrize("n_components", [None, 2])
+def test_nca_feature_names_out(n_components):
+    """Check `get_feature_names_out` for `NeighborhoodComponentsAnalysis`.
+
+    Non-regression test for:
+    https://github.com/scikit-learn/scikit-learn/issues/28293
+    """
+
+    X = iris_data
+    y = iris_target
+
+    est = NeighborhoodComponentsAnalysis(n_components=n_components).fit(X, y)
+    names_out = est.get_feature_names_out()
+
+    class_name_lower = est.__class__.__name__.lower()
+
+    if n_components is not None:
+        expected_n_features = n_components
+    else:
+        expected_n_features = X.shape[1]
+
+    expected_names_out = np.array(
+        [f"{class_name_lower}{i}" for i in range(expected_n_features)],
+        dtype=object,
+    )
+
+    assert_array_equal(names_out, expected_names_out)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_nearest_centroid.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_nearest_centroid.py
new file mode 100644
index 0000000000000000000000000000000000000000..1aa9274cd28a89be3744f56b6c3f31b80c2252ed
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_nearest_centroid.py
@@ -0,0 +1,237 @@
+"""
+Testing for the nearest centroid module.
+"""
+
+import numpy as np
+import pytest
+
+from sklearn import datasets
+from sklearn.neighbors import NearestCentroid
+from sklearn.utils._testing import (
+    assert_allclose,
+    assert_array_almost_equal,
+    assert_array_equal,
+)
+from sklearn.utils.fixes import CSR_CONTAINERS
+
+# toy sample
+X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]
+y = [-1, -1, -1, 1, 1, 1]
+T = [[-1, -1], [2, 2], [3, 2]]
+true_result = [-1, 1, 1]
+true_result_prior1 = [-1, 1, 1]
+
+true_discriminant_scores = [-32, 64, 80]
+true_proba = [[1, 1.26642e-14], [1.60381e-28, 1], [1.80485e-35, 1]]
+
+
+# also load the iris dataset
+# and randomly permute it
+iris = datasets.load_iris()
+rng = np.random.RandomState(1)
+perm = rng.permutation(iris.target.size)
+iris.data = iris.data[perm]
+iris.target = iris.target[perm]
+
+
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_classification_toy(csr_container):
+    # Check classification on a toy dataset, including sparse versions.
+    X_csr = csr_container(X)
+    T_csr = csr_container(T)
+
+    # Check classification on a toy dataset, including sparse versions.
+    clf = NearestCentroid()
+    clf.fit(X, y)
+    assert_array_equal(clf.predict(T), true_result)
+    assert_array_almost_equal(clf.decision_function(T), true_discriminant_scores)
+    assert_array_almost_equal(clf.predict_proba(T), true_proba)
+
+    # Test uniform priors
+    clf = NearestCentroid(priors="uniform")
+    clf.fit(X, y)
+    assert_array_equal(clf.predict(T), true_result)
+    assert_array_almost_equal(clf.decision_function(T), true_discriminant_scores)
+    assert_array_almost_equal(clf.predict_proba(T), true_proba)
+
+    clf = NearestCentroid(priors="empirical")
+    clf.fit(X, y)
+    assert_array_equal(clf.predict(T), true_result)
+    assert_array_almost_equal(clf.decision_function(T), true_discriminant_scores)
+    assert_array_almost_equal(clf.predict_proba(T), true_proba)
+
+    # Test custom priors
+    clf = NearestCentroid(priors=[0.25, 0.75])
+    clf.fit(X, y)
+    assert_array_equal(clf.predict(T), true_result_prior1)
+
+    # Same test, but with a sparse matrix to fit and test.
+    clf = NearestCentroid()
+    clf.fit(X_csr, y)
+    assert_array_equal(clf.predict(T_csr), true_result)
+
+    # Fit with sparse, test with non-sparse
+    clf = NearestCentroid()
+    clf.fit(X_csr, y)
+    assert_array_equal(clf.predict(T), true_result)
+
+    # Fit with non-sparse, test with sparse
+    clf = NearestCentroid()
+    clf.fit(X, y)
+    assert_array_equal(clf.predict(T_csr), true_result)
+
+    # Fit and predict with non-CSR sparse matrices
+    clf = NearestCentroid()
+    clf.fit(X_csr.tocoo(), y)
+    assert_array_equal(clf.predict(T_csr.tolil()), true_result)
+
+
+def test_iris():
+    # Check consistency on dataset iris.
+    for metric in ("euclidean", "manhattan"):
+        clf = NearestCentroid(metric=metric).fit(iris.data, iris.target)
+        score = np.mean(clf.predict(iris.data) == iris.target)
+        assert score > 0.9, "Failed with score = " + str(score)
+
+
+def test_iris_shrinkage():
+    # Check consistency on dataset iris, when using shrinkage.
+    for metric in ("euclidean", "manhattan"):
+        for shrink_threshold in [None, 0.1, 0.5]:
+            clf = NearestCentroid(metric=metric, shrink_threshold=shrink_threshold)
+            clf = clf.fit(iris.data, iris.target)
+            score = np.mean(clf.predict(iris.data) == iris.target)
+            assert score > 0.8, "Failed with score = " + str(score)
+
+
+def test_pickle():
+    import pickle
+
+    # classification
+    obj = NearestCentroid()
+    obj.fit(iris.data, iris.target)
+    score = obj.score(iris.data, iris.target)
+    s = pickle.dumps(obj)
+
+    obj2 = pickle.loads(s)
+    assert type(obj2) == obj.__class__
+    score2 = obj2.score(iris.data, iris.target)
+    assert_array_equal(
+        score,
+        score2,
+        "Failed to generate same score after pickling (classification).",
+    )
+
+
+def test_shrinkage_correct():
+    # Ensure that the shrinking is correct.
+    # The expected result is calculated by R (pamr),
+    # which is implemented by the author of the original paper.
+    # (One need to modify the code to output the new centroid in pamr.predict)
+
+    X = np.array([[0, 1], [1, 0], [1, 1], [2, 0], [6, 8]])
+    y = np.array([1, 1, 2, 2, 2])
+    clf = NearestCentroid(shrink_threshold=0.1)
+    clf.fit(X, y)
+    expected_result = np.array([[0.7787310, 0.8545292], [2.814179, 2.763647]])
+    np.testing.assert_array_almost_equal(clf.centroids_, expected_result)
+
+
+def test_shrinkage_threshold_decoded_y():
+    clf = NearestCentroid(shrink_threshold=0.01)
+    y_ind = np.asarray(y)
+    y_ind[y_ind == -1] = 0
+    clf.fit(X, y_ind)
+    centroid_encoded = clf.centroids_
+    clf.fit(X, y)
+    assert_array_equal(centroid_encoded, clf.centroids_)
+
+
+def test_predict_translated_data():
+    # Test that NearestCentroid gives same results on translated data
+
+    rng = np.random.RandomState(0)
+    X = rng.rand(50, 50)
+    y = rng.randint(0, 3, 50)
+    noise = rng.rand(50)
+    clf = NearestCentroid(shrink_threshold=0.1)
+    clf.fit(X, y)
+    y_init = clf.predict(X)
+    clf = NearestCentroid(shrink_threshold=0.1)
+    X_noise = X + noise
+    clf.fit(X_noise, y)
+    y_translate = clf.predict(X_noise)
+    assert_array_equal(y_init, y_translate)
+
+
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_manhattan_metric(csr_container):
+    # Test the manhattan metric.
+    X_csr = csr_container(X)
+
+    clf = NearestCentroid(metric="manhattan")
+    clf.fit(X, y)
+    dense_centroid = clf.centroids_
+    clf.fit(X_csr, y)
+    assert_array_equal(clf.centroids_, dense_centroid)
+    assert_array_equal(dense_centroid, [[-1, -1], [1, 1]])
+
+
+def test_features_zero_var():
+    # Test that features with 0 variance throw error
+
+    X = np.empty((10, 2))
+    X[:, 0] = -0.13725701
+    X[:, 1] = -0.9853293
+    y = np.zeros((10))
+    y[0] = 1
+
+    clf = NearestCentroid(shrink_threshold=0.1)
+    with pytest.raises(ValueError):
+        clf.fit(X, y)
+
+
+def test_negative_priors_error():
+    """Check that we raise an error when the user-defined priors are negative."""
+    clf = NearestCentroid(priors=[-2, 4])
+    with pytest.raises(ValueError, match="priors must be non-negative"):
+        clf.fit(X, y)
+
+
+def test_warn_non_normalized_priors():
+    """Check that we raise a warning and normalize the user-defined priors when they
+    don't sum to 1.
+    """
+    priors = [2, 4]
+    clf = NearestCentroid(priors=priors)
+    with pytest.warns(
+        UserWarning,
+        match="The priors do not sum to 1. Normalizing such that it sums to one.",
+    ):
+        clf.fit(X, y)
+
+    assert_allclose(clf.class_prior_, np.asarray(priors) / np.asarray(priors).sum())
+
+
+@pytest.mark.parametrize(
+    "response_method", ["decision_function", "predict_proba", "predict_log_proba"]
+)
+def test_method_not_available_with_manhattan(response_method):
+    """Check that we raise an AttributeError with Manhattan metric when trying
+    to call a non-thresholded response method.
+    """
+    clf = NearestCentroid(metric="manhattan").fit(X, y)
+    with pytest.raises(AttributeError):
+        getattr(clf, response_method)(T)
+
+
+@pytest.mark.parametrize("array_constructor", [np.array] + CSR_CONTAINERS)
+def test_error_zero_variances(array_constructor):
+    """Check that we raise an error when the variance for all features is zero."""
+    X = np.ones((len(y), 2))
+    X[:, 1] *= 2
+    X = array_constructor(X)
+
+    clf = NearestCentroid()
+    with pytest.raises(ValueError, match="All features have zero variance"):
+        clf.fit(X, y)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_neighbors.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_neighbors.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae589b30dd74369cb8ef242fb86a11e0c75a09a2
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_neighbors.py
@@ -0,0 +1,2503 @@
+import re
+import warnings
+from itertools import product
+
+import joblib
+import numpy as np
+import pytest
+from scipy.sparse import issparse
+
+from sklearn import (
+    config_context,
+    datasets,
+    metrics,
+    neighbors,
+)
+from sklearn.base import clone
+from sklearn.exceptions import EfficiencyWarning, NotFittedError
+from sklearn.metrics._dist_metrics import (
+    DistanceMetric,
+)
+from sklearn.metrics.pairwise import PAIRWISE_BOOLEAN_FUNCTIONS, pairwise_distances
+from sklearn.metrics.tests.test_dist_metrics import BOOL_METRICS
+from sklearn.metrics.tests.test_pairwise_distances_reduction import (
+    assert_compatible_argkmin_results,
+    assert_compatible_radius_results,
+)
+from sklearn.model_selection import (
+    LeaveOneOut,
+    cross_val_predict,
+    cross_val_score,
+    train_test_split,
+)
+from sklearn.neighbors import (
+    VALID_METRICS_SPARSE,
+    KNeighborsRegressor,
+)
+from sklearn.neighbors._base import (
+    KNeighborsMixin,
+    _check_precomputed,
+    _is_sorted_by_data,
+    sort_graph_by_row_values,
+)
+from sklearn.pipeline import make_pipeline
+from sklearn.utils._testing import (
+    assert_allclose,
+    assert_array_equal,
+    ignore_warnings,
+)
+from sklearn.utils.fixes import (
+    BSR_CONTAINERS,
+    COO_CONTAINERS,
+    CSC_CONTAINERS,
+    CSR_CONTAINERS,
+    DIA_CONTAINERS,
+    DOK_CONTAINERS,
+    LIL_CONTAINERS,
+)
+from sklearn.utils.validation import check_random_state
+
+rng = np.random.RandomState(0)
+# load and shuffle iris dataset
+iris = datasets.load_iris()
+perm = rng.permutation(iris.target.size)
+iris.data = iris.data[perm]
+iris.target = iris.target[perm]
+
+# load and shuffle digits
+digits = datasets.load_digits()
+perm = rng.permutation(digits.target.size)
+digits.data = digits.data[perm]
+digits.target = digits.target[perm]
+
+SPARSE_TYPES = tuple(
+    BSR_CONTAINERS
+    + COO_CONTAINERS
+    + CSC_CONTAINERS
+    + CSR_CONTAINERS
+    + DOK_CONTAINERS
+    + LIL_CONTAINERS
+)
+SPARSE_OR_DENSE = SPARSE_TYPES + (np.asarray,)
+
+ALGORITHMS = ("ball_tree", "brute", "kd_tree", "auto")
+COMMON_VALID_METRICS = sorted(
+    set.intersection(*map(set, neighbors.VALID_METRICS.values()))
+)
+
+P = (1, 2, 3, 4, np.inf)
+
+# Filter deprecation warnings.
+neighbors.kneighbors_graph = ignore_warnings(neighbors.kneighbors_graph)
+neighbors.radius_neighbors_graph = ignore_warnings(neighbors.radius_neighbors_graph)
+
+# A list containing metrics where the string specifies the use of the
+# DistanceMetric object directly (as resolved in _parse_metric)
+DISTANCE_METRIC_OBJS = ["DM_euclidean"]
+
+
+def _parse_metric(metric: str, dtype=None):
+    """
+    Helper function for properly building a type-specialized DistanceMetric instances.
+
+    Constructs a type-specialized DistanceMetric instance from a string
+    beginning with "DM_" while allowing a pass-through for other metric-specifying
+    strings. This is necessary since we wish to parameterize dtype independent of
+    metric, yet DistanceMetric requires it for construction.
+
+    """
+    if metric[:3] == "DM_":
+        return DistanceMetric.get_metric(metric[3:], dtype=dtype)
+    return metric
+
+
+def _generate_test_params_for(metric: str, n_features: int):
+    """Return list of DistanceMetric kwargs for tests."""
+
+    # Distinguishing on cases not to compute unneeded datastructures.
+    rng = np.random.RandomState(1)
+
+    if metric == "minkowski":
+        return [
+            dict(p=1.5),
+            dict(p=2),
+            dict(p=3),
+            dict(p=np.inf),
+            dict(p=3, w=rng.rand(n_features)),
+        ]
+
+    if metric == "seuclidean":
+        return [dict(V=rng.rand(n_features))]
+
+    if metric == "mahalanobis":
+        A = rng.rand(n_features, n_features)
+        # Make the matrix symmetric positive definite
+        VI = A + A.T + 3 * np.eye(n_features)
+        return [dict(VI=VI)]
+
+    # Case of: "euclidean", "manhattan", "chebyshev", "haversine" or any other metric.
+    # In those cases, no kwargs are needed.
+    return [{}]
+
+
+def _weight_func(dist):
+    """Weight function to replace lambda d: d ** -2.
+    The lambda function is not valid because:
+    if d==0 then 0^-2 is not valid."""
+
+    # Dist could be multidimensional, flatten it so all values
+    # can be looped
+    with np.errstate(divide="ignore"):
+        retval = 1.0 / dist
+    return retval**2
+
+
+WEIGHTS = ["uniform", "distance", _weight_func]
+
+
+@pytest.mark.parametrize(
+    "n_samples, n_features, n_query_pts, n_neighbors",
+    [
+        (100, 100, 10, 100),
+        (1000, 5, 100, 1),
+    ],
+)
+@pytest.mark.parametrize("query_is_train", [False, True])
+@pytest.mark.parametrize("metric", COMMON_VALID_METRICS + DISTANCE_METRIC_OBJS)
+def test_unsupervised_kneighbors(
+    global_dtype,
+    n_samples,
+    n_features,
+    n_query_pts,
+    n_neighbors,
+    query_is_train,
+    metric,
+):
+    # The different algorithms must return identical results
+    # on their common metrics, with and without returning
+    # distances
+
+    metric = _parse_metric(metric, global_dtype)
+
+    # Redefining the rng locally to use the same generated X
+    local_rng = np.random.RandomState(0)
+    X = local_rng.rand(n_samples, n_features).astype(global_dtype, copy=False)
+
+    query = (
+        X
+        if query_is_train
+        else local_rng.rand(n_query_pts, n_features).astype(global_dtype, copy=False)
+    )
+
+    results_nodist = []
+    results = []
+
+    for algorithm in ALGORITHMS:
+        if isinstance(metric, DistanceMetric) and global_dtype == np.float32:
+            if "tree" in algorithm:  # pragma: nocover
+                pytest.skip(
+                    "Neither KDTree nor BallTree support 32-bit distance metric"
+                    " objects."
+                )
+        neigh = neighbors.NearestNeighbors(
+            n_neighbors=n_neighbors, algorithm=algorithm, metric=metric
+        )
+        neigh.fit(X)
+
+        results_nodist.append(neigh.kneighbors(query, return_distance=False))
+        results.append(neigh.kneighbors(query, return_distance=True))
+
+    for i in range(len(results) - 1):
+        algorithm = ALGORITHMS[i]
+        next_algorithm = ALGORITHMS[i + 1]
+
+        indices_no_dist = results_nodist[i]
+        distances, next_distances = results[i][0], results[i + 1][0]
+        indices, next_indices = results[i][1], results[i + 1][1]
+        assert_array_equal(
+            indices_no_dist,
+            indices,
+            err_msg=(
+                f"The '{algorithm}' algorithm returns different"
+                "indices depending on 'return_distances'."
+            ),
+        )
+        assert_array_equal(
+            indices,
+            next_indices,
+            err_msg=(
+                f"The '{algorithm}' and '{next_algorithm}' "
+                "algorithms return different indices."
+            ),
+        )
+        assert_allclose(
+            distances,
+            next_distances,
+            err_msg=(
+                f"The '{algorithm}' and '{next_algorithm}' "
+                "algorithms return different distances."
+            ),
+            atol=1e-6,
+        )
+
+
+@pytest.mark.parametrize(
+    "n_samples, n_features, n_query_pts",
+    [
+        (100, 100, 10),
+        (1000, 5, 100),
+    ],
+)
+@pytest.mark.parametrize("metric", COMMON_VALID_METRICS + DISTANCE_METRIC_OBJS)
+@pytest.mark.parametrize("n_neighbors, radius", [(1, 100), (50, 500), (100, 1000)])
+@pytest.mark.parametrize(
+    "NeighborsMixinSubclass",
+    [
+        neighbors.KNeighborsClassifier,
+        neighbors.KNeighborsRegressor,
+        neighbors.RadiusNeighborsClassifier,
+        neighbors.RadiusNeighborsRegressor,
+    ],
+)
+def test_neigh_predictions_algorithm_agnosticity(
+    global_dtype,
+    n_samples,
+    n_features,
+    n_query_pts,
+    metric,
+    n_neighbors,
+    radius,
+    NeighborsMixinSubclass,
+):
+    # The different algorithms must return identical predictions results
+    # on their common metrics.
+
+    metric = _parse_metric(metric, global_dtype)
+    if isinstance(metric, DistanceMetric):
+        if "Classifier" in NeighborsMixinSubclass.__name__:
+            pytest.skip(
+                "Metrics of type `DistanceMetric` are not yet supported for"
+                " classifiers."
+            )
+        if "Radius" in NeighborsMixinSubclass.__name__:
+            pytest.skip(
+                "Metrics of type `DistanceMetric` are not yet supported for"
+                " radius-neighbor estimators."
+            )
+
+    # Redefining the rng locally to use the same generated X
+    local_rng = np.random.RandomState(0)
+    X = local_rng.rand(n_samples, n_features).astype(global_dtype, copy=False)
+    y = local_rng.randint(3, size=n_samples)
+
+    query = local_rng.rand(n_query_pts, n_features).astype(global_dtype, copy=False)
+
+    predict_results = []
+
+    parameter = (
+        n_neighbors if issubclass(NeighborsMixinSubclass, KNeighborsMixin) else radius
+    )
+
+    for algorithm in ALGORITHMS:
+        if isinstance(metric, DistanceMetric) and global_dtype == np.float32:
+            if "tree" in algorithm:  # pragma: nocover
+                pytest.skip(
+                    "Neither KDTree nor BallTree support 32-bit distance metric"
+                    " objects."
+                )
+        neigh = NeighborsMixinSubclass(parameter, algorithm=algorithm, metric=metric)
+        neigh.fit(X, y)
+
+        predict_results.append(neigh.predict(query))
+
+    for i in range(len(predict_results) - 1):
+        algorithm = ALGORITHMS[i]
+        next_algorithm = ALGORITHMS[i + 1]
+
+        predictions, next_predictions = predict_results[i], predict_results[i + 1]
+
+        assert_allclose(
+            predictions,
+            next_predictions,
+            err_msg=(
+                f"The '{algorithm}' and '{next_algorithm}' "
+                "algorithms return different predictions."
+            ),
+        )
+
+
+@pytest.mark.parametrize(
+    "KNeighborsMixinSubclass",
+    [
+        neighbors.KNeighborsClassifier,
+        neighbors.KNeighborsRegressor,
+        neighbors.NearestNeighbors,
+    ],
+)
+def test_unsupervised_inputs(global_dtype, KNeighborsMixinSubclass):
+    # Test unsupervised inputs for neighbors estimators
+
+    X = rng.random_sample((10, 3)).astype(global_dtype, copy=False)
+    y = rng.randint(3, size=10)
+    nbrs_fid = neighbors.NearestNeighbors(n_neighbors=1)
+    nbrs_fid.fit(X)
+
+    dist1, ind1 = nbrs_fid.kneighbors(X)
+
+    nbrs = KNeighborsMixinSubclass(n_neighbors=1)
+
+    for data in (nbrs_fid, neighbors.BallTree(X), neighbors.KDTree(X)):
+        nbrs.fit(data, y)
+
+        dist2, ind2 = nbrs.kneighbors(X)
+
+        assert_allclose(dist1, dist2)
+        assert_array_equal(ind1, ind2)
+
+
+def test_not_fitted_error_gets_raised():
+    X = [[1]]
+    neighbors_ = neighbors.NearestNeighbors()
+    with pytest.raises(NotFittedError):
+        neighbors_.kneighbors_graph(X)
+    with pytest.raises(NotFittedError):
+        neighbors_.radius_neighbors_graph(X)
+
+
+@pytest.mark.filterwarnings("ignore:EfficiencyWarning")
+def check_precomputed(make_train_test, estimators):
+    """Tests unsupervised NearestNeighbors with a distance matrix."""
+    # Note: smaller samples may result in spurious test success
+    rng = np.random.RandomState(42)
+    X = rng.random_sample((10, 4))
+    Y = rng.random_sample((3, 4))
+    DXX, DYX = make_train_test(X, Y)
+    for method in [
+        "kneighbors",
+    ]:
+        # TODO: also test radius_neighbors, but requires different assertion
+
+        # As a feature matrix (n_samples by n_features)
+        nbrs_X = neighbors.NearestNeighbors(n_neighbors=3)
+        nbrs_X.fit(X)
+        dist_X, ind_X = getattr(nbrs_X, method)(Y)
+
+        # As a dense distance matrix (n_samples by n_samples)
+        nbrs_D = neighbors.NearestNeighbors(
+            n_neighbors=3, algorithm="brute", metric="precomputed"
+        )
+        nbrs_D.fit(DXX)
+        dist_D, ind_D = getattr(nbrs_D, method)(DYX)
+        assert_allclose(dist_X, dist_D)
+        assert_array_equal(ind_X, ind_D)
+
+        # Check auto works too
+        nbrs_D = neighbors.NearestNeighbors(
+            n_neighbors=3, algorithm="auto", metric="precomputed"
+        )
+        nbrs_D.fit(DXX)
+        dist_D, ind_D = getattr(nbrs_D, method)(DYX)
+        assert_allclose(dist_X, dist_D)
+        assert_array_equal(ind_X, ind_D)
+
+        # Check X=None in prediction
+        dist_X, ind_X = getattr(nbrs_X, method)(None)
+        dist_D, ind_D = getattr(nbrs_D, method)(None)
+        assert_allclose(dist_X, dist_D)
+        assert_array_equal(ind_X, ind_D)
+
+        # Must raise a ValueError if the matrix is not of correct shape
+        with pytest.raises(ValueError):
+            getattr(nbrs_D, method)(X)
+
+    target = np.arange(X.shape[0])
+    for Est in estimators:
+        est = Est(metric="euclidean")
+        est.radius = est.n_neighbors = 1
+        pred_X = est.fit(X, target).predict(Y)
+        est.metric = "precomputed"
+        pred_D = est.fit(DXX, target).predict(DYX)
+        assert_allclose(pred_X, pred_D)
+
+
+def test_precomputed_dense():
+    def make_train_test(X_train, X_test):
+        return (
+            metrics.pairwise_distances(X_train),
+            metrics.pairwise_distances(X_test, X_train),
+        )
+
+    estimators = [
+        neighbors.KNeighborsClassifier,
+        neighbors.KNeighborsRegressor,
+        neighbors.RadiusNeighborsClassifier,
+        neighbors.RadiusNeighborsRegressor,
+    ]
+    check_precomputed(make_train_test, estimators)
+
+
+@pytest.mark.parametrize("fmt", ["csr", "lil"])
+def test_precomputed_sparse_knn(fmt):
+    def make_train_test(X_train, X_test):
+        nn = neighbors.NearestNeighbors(n_neighbors=3 + 1).fit(X_train)
+        return (
+            nn.kneighbors_graph(X_train, mode="distance").asformat(fmt),
+            nn.kneighbors_graph(X_test, mode="distance").asformat(fmt),
+        )
+
+    # We do not test RadiusNeighborsClassifier and RadiusNeighborsRegressor
+    # since the precomputed neighbors graph is built with k neighbors only.
+    estimators = [
+        neighbors.KNeighborsClassifier,
+        neighbors.KNeighborsRegressor,
+    ]
+    check_precomputed(make_train_test, estimators)
+
+
+@pytest.mark.parametrize("fmt", ["csr", "lil"])
+def test_precomputed_sparse_radius(fmt):
+    def make_train_test(X_train, X_test):
+        nn = neighbors.NearestNeighbors(radius=1).fit(X_train)
+        return (
+            nn.radius_neighbors_graph(X_train, mode="distance").asformat(fmt),
+            nn.radius_neighbors_graph(X_test, mode="distance").asformat(fmt),
+        )
+
+    # We do not test KNeighborsClassifier and KNeighborsRegressor
+    # since the precomputed neighbors graph is built with a radius.
+    estimators = [
+        neighbors.RadiusNeighborsClassifier,
+        neighbors.RadiusNeighborsRegressor,
+    ]
+    check_precomputed(make_train_test, estimators)
+
+
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_is_sorted_by_data(csr_container):
+    # Test that _is_sorted_by_data works as expected. In CSR sparse matrix,
+    # entries in each row can be sorted by indices, by data, or unsorted.
+    # _is_sorted_by_data should return True when entries are sorted by data,
+    # and False in all other cases.
+
+    # Test with sorted single row sparse array
+    X = csr_container(np.arange(10).reshape(1, 10))
+    assert _is_sorted_by_data(X)
+    # Test with unsorted 1D array
+    X[0, 2] = 5
+    assert not _is_sorted_by_data(X)
+
+    # Test when the data is sorted in each sample, but not necessarily
+    # between samples
+    X = csr_container([[0, 1, 2], [3, 0, 0], [3, 4, 0], [1, 0, 2]])
+    assert _is_sorted_by_data(X)
+
+    # Test with duplicates entries in X.indptr
+    data, indices, indptr = [0, 4, 2, 2], [0, 1, 1, 1], [0, 2, 2, 4]
+    X = csr_container((data, indices, indptr), shape=(3, 3))
+    assert _is_sorted_by_data(X)
+
+
+@pytest.mark.filterwarnings("ignore:EfficiencyWarning")
+@pytest.mark.parametrize("function", [sort_graph_by_row_values, _check_precomputed])
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_sort_graph_by_row_values(function, csr_container):
+    # Test that sort_graph_by_row_values returns a graph sorted by row values
+    X = csr_container(np.abs(np.random.RandomState(42).randn(10, 10)))
+    assert not _is_sorted_by_data(X)
+    Xt = function(X)
+    assert _is_sorted_by_data(Xt)
+
+    # test with a different number of nonzero entries for each sample
+    mask = np.random.RandomState(42).randint(2, size=(10, 10))
+    X = X.toarray()
+    X[mask == 1] = 0
+    X = csr_container(X)
+    assert not _is_sorted_by_data(X)
+    Xt = function(X)
+    assert _is_sorted_by_data(Xt)
+
+
+@pytest.mark.filterwarnings("ignore:EfficiencyWarning")
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_sort_graph_by_row_values_copy(csr_container):
+    # Test if the sorting is done inplace if X is CSR, so that Xt is X.
+    X_ = csr_container(np.abs(np.random.RandomState(42).randn(10, 10)))
+    assert not _is_sorted_by_data(X_)
+
+    # sort_graph_by_row_values is done inplace if copy=False
+    X = X_.copy()
+    assert sort_graph_by_row_values(X).data is X.data
+
+    X = X_.copy()
+    assert sort_graph_by_row_values(X, copy=False).data is X.data
+
+    X = X_.copy()
+    assert sort_graph_by_row_values(X, copy=True).data is not X.data
+
+    # _check_precomputed is never done inplace
+    X = X_.copy()
+    assert _check_precomputed(X).data is not X.data
+
+    # do not raise if X is not CSR and copy=True
+    sort_graph_by_row_values(X.tocsc(), copy=True)
+
+    # raise if X is not CSR and copy=False
+    with pytest.raises(ValueError, match="Use copy=True to allow the conversion"):
+        sort_graph_by_row_values(X.tocsc(), copy=False)
+
+
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_sort_graph_by_row_values_warning(csr_container):
+    # Test that the parameter warn_when_not_sorted works as expected.
+    X = csr_container(np.abs(np.random.RandomState(42).randn(10, 10)))
+    assert not _is_sorted_by_data(X)
+
+    # warning
+    with pytest.warns(EfficiencyWarning, match="was not sorted by row values"):
+        sort_graph_by_row_values(X, copy=True)
+    with pytest.warns(EfficiencyWarning, match="was not sorted by row values"):
+        sort_graph_by_row_values(X, copy=True, warn_when_not_sorted=True)
+    with pytest.warns(EfficiencyWarning, match="was not sorted by row values"):
+        _check_precomputed(X)
+
+    # no warning
+    with warnings.catch_warnings():
+        warnings.simplefilter("error")
+        sort_graph_by_row_values(X, copy=True, warn_when_not_sorted=False)
+
+
+@pytest.mark.parametrize(
+    "sparse_container", DOK_CONTAINERS + BSR_CONTAINERS + DIA_CONTAINERS
+)
+def test_sort_graph_by_row_values_bad_sparse_format(sparse_container):
+    # Test that sort_graph_by_row_values and _check_precomputed error on bad formats
+    X = sparse_container(np.abs(np.random.RandomState(42).randn(10, 10)))
+    with pytest.raises(TypeError, match="format is not supported"):
+        sort_graph_by_row_values(X)
+    with pytest.raises(TypeError, match="format is not supported"):
+        _check_precomputed(X)
+
+
+@pytest.mark.filterwarnings("ignore:EfficiencyWarning")
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_precomputed_sparse_invalid(csr_container):
+    dist = np.array([[0.0, 2.0, 1.0], [2.0, 0.0, 3.0], [1.0, 3.0, 0.0]])
+    dist_csr = csr_container(dist)
+    neigh = neighbors.NearestNeighbors(n_neighbors=1, metric="precomputed")
+    neigh.fit(dist_csr)
+    neigh.kneighbors(None, n_neighbors=1)
+    neigh.kneighbors(np.array([[0.0, 0.0, 0.0]]), n_neighbors=2)
+
+    # Ensures enough number of nearest neighbors
+    dist = np.array([[0.0, 2.0, 0.0], [2.0, 0.0, 3.0], [0.0, 3.0, 0.0]])
+    dist_csr = csr_container(dist)
+    neigh.fit(dist_csr)
+    msg = "2 neighbors per samples are required, but some samples have only 1"
+    with pytest.raises(ValueError, match=msg):
+        neigh.kneighbors(None, n_neighbors=1)
+
+    # Checks error with inconsistent distance matrix
+    dist = np.array([[5.0, 2.0, 1.0], [-2.0, 0.0, 3.0], [1.0, 3.0, 0.0]])
+    dist_csr = csr_container(dist)
+    msg = "Negative values in data passed to precomputed distance matrix."
+    with pytest.raises(ValueError, match=msg):
+        neigh.kneighbors(dist_csr, n_neighbors=1)
+
+
+def test_precomputed_cross_validation():
+    # Ensure array is split correctly
+    rng = np.random.RandomState(0)
+    X = rng.rand(20, 2)
+    D = pairwise_distances(X, metric="euclidean")
+    y = rng.randint(3, size=20)
+    for Est in (
+        neighbors.KNeighborsClassifier,
+        neighbors.RadiusNeighborsClassifier,
+        neighbors.KNeighborsRegressor,
+        neighbors.RadiusNeighborsRegressor,
+    ):
+        metric_score = cross_val_score(Est(), X, y)
+        precomp_score = cross_val_score(Est(metric="precomputed"), D, y)
+        assert_array_equal(metric_score, precomp_score)
+
+
+def test_unsupervised_radius_neighbors(
+    global_dtype, n_samples=20, n_features=5, n_query_pts=2, radius=0.5, random_state=0
+):
+    # Test unsupervised radius-based query
+    rng = np.random.RandomState(random_state)
+
+    X = rng.rand(n_samples, n_features).astype(global_dtype, copy=False)
+
+    test = rng.rand(n_query_pts, n_features).astype(global_dtype, copy=False)
+
+    for p in P:
+        results = []
+
+        for algorithm in ALGORITHMS:
+            neigh = neighbors.NearestNeighbors(radius=radius, algorithm=algorithm, p=p)
+            neigh.fit(X)
+
+            ind1 = neigh.radius_neighbors(test, return_distance=False)
+
+            # sort the results: this is not done automatically for
+            # radius searches
+            dist, ind = neigh.radius_neighbors(test, return_distance=True)
+            for d, i, i1 in zip(dist, ind, ind1):
+                j = d.argsort()
+                d[:] = d[j]
+                i[:] = i[j]
+                i1[:] = i1[j]
+            results.append((dist, ind))
+
+            assert_allclose(np.concatenate(list(ind)), np.concatenate(list(ind1)))
+
+        for i in range(len(results) - 1):
+            assert_allclose(
+                np.concatenate(list(results[i][0])),
+                np.concatenate(list(results[i + 1][0])),
+            )
+            assert_allclose(
+                np.concatenate(list(results[i][1])),
+                np.concatenate(list(results[i + 1][1])),
+            )
+
+
+@pytest.mark.parametrize("algorithm", ALGORITHMS)
+@pytest.mark.parametrize("weights", WEIGHTS)
+def test_kneighbors_classifier(
+    global_dtype,
+    algorithm,
+    weights,
+    n_samples=40,
+    n_features=5,
+    n_test_pts=10,
+    n_neighbors=5,
+    random_state=0,
+):
+    # Test k-neighbors classification
+    rng = np.random.RandomState(random_state)
+    X = 2 * rng.rand(n_samples, n_features).astype(global_dtype, copy=False) - 1
+    y = ((X**2).sum(axis=1) < 0.5).astype(int)
+    y_str = y.astype(str)
+
+    knn = neighbors.KNeighborsClassifier(
+        n_neighbors=n_neighbors, weights=weights, algorithm=algorithm
+    )
+    knn.fit(X, y)
+    epsilon = 1e-5 * (2 * rng.rand(1, n_features) - 1)
+    y_pred = knn.predict(X[:n_test_pts] + epsilon)
+    assert_array_equal(y_pred, y[:n_test_pts])
+    # Test prediction with y_str
+    knn.fit(X, y_str)
+    y_pred = knn.predict(X[:n_test_pts] + epsilon)
+    assert_array_equal(y_pred, y_str[:n_test_pts])
+
+
+def test_kneighbors_classifier_float_labels(
+    global_dtype,
+    n_samples=40,
+    n_features=5,
+    n_test_pts=10,
+    n_neighbors=5,
+    random_state=0,
+):
+    # Test k-neighbors classification
+    rng = np.random.RandomState(random_state)
+    X = 2 * rng.rand(n_samples, n_features).astype(global_dtype, copy=False) - 1
+    y = ((X**2).sum(axis=1) < 0.5).astype(int)
+
+    knn = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors)
+    knn.fit(X, y.astype(float))
+    epsilon = 1e-5 * (2 * rng.rand(1, n_features) - 1)
+    y_pred = knn.predict(X[:n_test_pts] + epsilon)
+    assert_array_equal(y_pred, y[:n_test_pts])
+
+
+def test_kneighbors_classifier_predict_proba(global_dtype):
+    # Test KNeighborsClassifier.predict_proba() method
+    X = np.array(
+        [[0, 2, 0], [0, 2, 1], [2, 0, 0], [2, 2, 0], [0, 0, 2], [0, 0, 1]]
+    ).astype(global_dtype, copy=False)
+    y = np.array([4, 4, 5, 5, 1, 1])
+    cls = neighbors.KNeighborsClassifier(n_neighbors=3, p=1)  # cityblock dist
+    cls.fit(X, y)
+    y_prob = cls.predict_proba(X)
+    real_prob = (
+        np.array(
+            [
+                [0, 2, 1],
+                [1, 2, 0],
+                [1, 0, 2],
+                [0, 1, 2],
+                [2, 1, 0],
+                [2, 1, 0],
+            ]
+        )
+        / 3.0
+    )
+    assert_array_equal(real_prob, y_prob)
+    # Check that it also works with non integer labels
+    cls.fit(X, y.astype(str))
+    y_prob = cls.predict_proba(X)
+    assert_array_equal(real_prob, y_prob)
+    # Check that it works with weights='distance'
+    cls = neighbors.KNeighborsClassifier(n_neighbors=2, p=1, weights="distance")
+    cls.fit(X, y)
+    y_prob = cls.predict_proba(np.array([[0, 2, 0], [2, 2, 2]]))
+    real_prob = np.array([[0, 1, 0], [0, 0.4, 0.6]])
+    assert_allclose(real_prob, y_prob)
+
+
+@pytest.mark.parametrize("algorithm", ALGORITHMS)
+@pytest.mark.parametrize("weights", WEIGHTS)
+def test_radius_neighbors_classifier(
+    global_dtype,
+    algorithm,
+    weights,
+    n_samples=40,
+    n_features=5,
+    n_test_pts=10,
+    radius=0.5,
+    random_state=0,
+):
+    # Test radius-based classification
+    rng = np.random.RandomState(random_state)
+    X = 2 * rng.rand(n_samples, n_features).astype(global_dtype, copy=False) - 1
+    y = ((X**2).sum(axis=1) < radius).astype(int)
+    y_str = y.astype(str)
+
+    neigh = neighbors.RadiusNeighborsClassifier(
+        radius=radius, weights=weights, algorithm=algorithm
+    )
+    neigh.fit(X, y)
+    epsilon = 1e-5 * (2 * rng.rand(1, n_features) - 1)
+    y_pred = neigh.predict(X[:n_test_pts] + epsilon)
+    assert_array_equal(y_pred, y[:n_test_pts])
+    neigh.fit(X, y_str)
+    y_pred = neigh.predict(X[:n_test_pts] + epsilon)
+    assert_array_equal(y_pred, y_str[:n_test_pts])
+
+
+@pytest.mark.parametrize("algorithm", ALGORITHMS)
+@pytest.mark.parametrize("weights", WEIGHTS)
+@pytest.mark.parametrize("outlier_label", [0, -1, None])
+def test_radius_neighbors_classifier_when_no_neighbors(
+    global_dtype, algorithm, weights, outlier_label
+):
+    # Test radius-based classifier when no neighbors found.
+    # In this case it should rise an informative exception
+
+    X = np.array([[1.0, 1.0], [2.0, 2.0]], dtype=global_dtype)
+    y = np.array([1, 2])
+    radius = 0.1
+
+    # no outliers
+    z1 = np.array([[1.01, 1.01], [2.01, 2.01]], dtype=global_dtype)
+
+    # one outlier
+    z2 = np.array([[1.01, 1.01], [1.4, 1.4]], dtype=global_dtype)
+
+    rnc = neighbors.RadiusNeighborsClassifier
+    clf = rnc(
+        radius=radius,
+        weights=weights,
+        algorithm=algorithm,
+        outlier_label=outlier_label,
+    )
+    clf.fit(X, y)
+    assert_array_equal(np.array([1, 2]), clf.predict(z1))
+    if outlier_label is None:
+        with pytest.raises(ValueError):
+            clf.predict(z2)
+
+
+@pytest.mark.parametrize("algorithm", ALGORITHMS)
+@pytest.mark.parametrize("weights", WEIGHTS)
+def test_radius_neighbors_classifier_outlier_labeling(global_dtype, algorithm, weights):
+    # Test radius-based classifier when no neighbors found and outliers
+    # are labeled.
+
+    X = np.array(
+        [[1.0, 1.0], [2.0, 2.0], [0.99, 0.99], [0.98, 0.98], [2.01, 2.01]],
+        dtype=global_dtype,
+    )
+    y = np.array([1, 2, 1, 1, 2])
+    radius = 0.1
+
+    # no outliers
+    z1 = np.array([[1.01, 1.01], [2.01, 2.01]], dtype=global_dtype)
+
+    # one outlier
+    z2 = np.array([[1.4, 1.4], [1.01, 1.01], [2.01, 2.01]], dtype=global_dtype)
+
+    correct_labels1 = np.array([1, 2])
+    correct_labels2 = np.array([-1, 1, 2])
+    outlier_proba = np.array([0, 0])
+
+    clf = neighbors.RadiusNeighborsClassifier(
+        radius=radius, weights=weights, algorithm=algorithm, outlier_label=-1
+    )
+    clf.fit(X, y)
+    assert_array_equal(correct_labels1, clf.predict(z1))
+    with pytest.warns(UserWarning, match="Outlier label -1 is not in training classes"):
+        assert_array_equal(correct_labels2, clf.predict(z2))
+    with pytest.warns(UserWarning, match="Outlier label -1 is not in training classes"):
+        assert_allclose(outlier_proba, clf.predict_proba(z2)[0])
+
+    # test outlier_labeling of using predict_proba()
+    RNC = neighbors.RadiusNeighborsClassifier
+    X = np.array([[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]], dtype=global_dtype)
+    y = np.array([0, 2, 2, 1, 1, 1, 3, 3, 3, 3])
+
+    # test outlier_label scalar verification
+    def check_array_exception():
+        clf = RNC(radius=1, outlier_label=[[5]])
+        clf.fit(X, y)
+
+    with pytest.raises(TypeError):
+        check_array_exception()
+
+    # test invalid outlier_label dtype
+    def check_dtype_exception():
+        clf = RNC(radius=1, outlier_label="a")
+        clf.fit(X, y)
+
+    with pytest.raises(TypeError):
+        check_dtype_exception()
+
+    # test most frequent
+    clf = RNC(radius=1, outlier_label="most_frequent")
+    clf.fit(X, y)
+    proba = clf.predict_proba([[1], [15]])
+    assert_array_equal(proba[1, :], [0, 0, 0, 1])
+
+    # test manual label in y
+    clf = RNC(radius=1, outlier_label=1)
+    clf.fit(X, y)
+    proba = clf.predict_proba([[1], [15]])
+    assert_array_equal(proba[1, :], [0, 1, 0, 0])
+    pred = clf.predict([[1], [15]])
+    assert_array_equal(pred, [2, 1])
+
+    # test manual label out of y warning
+    def check_warning():
+        clf = RNC(radius=1, outlier_label=4)
+        clf.fit(X, y)
+        clf.predict_proba([[1], [15]])
+
+    with pytest.warns(UserWarning):
+        check_warning()
+
+    # test multi output same outlier label
+    y_multi = [
+        [0, 1],
+        [2, 1],
+        [2, 2],
+        [1, 2],
+        [1, 2],
+        [1, 3],
+        [3, 3],
+        [3, 3],
+        [3, 0],
+        [3, 0],
+    ]
+    clf = RNC(radius=1, outlier_label=1)
+    clf.fit(X, y_multi)
+    proba = clf.predict_proba([[7], [15]])
+    assert_array_equal(proba[1][1, :], [0, 1, 0, 0])
+    pred = clf.predict([[7], [15]])
+    assert_array_equal(pred[1, :], [1, 1])
+
+    # test multi output different outlier label
+    y_multi = [
+        [0, 0],
+        [2, 2],
+        [2, 2],
+        [1, 1],
+        [1, 1],
+        [1, 1],
+        [3, 3],
+        [3, 3],
+        [3, 3],
+        [3, 3],
+    ]
+    clf = RNC(radius=1, outlier_label=[0, 1])
+    clf.fit(X, y_multi)
+    proba = clf.predict_proba([[7], [15]])
+    assert_array_equal(proba[0][1, :], [1, 0, 0, 0])
+    assert_array_equal(proba[1][1, :], [0, 1, 0, 0])
+    pred = clf.predict([[7], [15]])
+    assert_array_equal(pred[1, :], [0, 1])
+
+    # test inconsistent outlier label list length
+    def check_exception():
+        clf = RNC(radius=1, outlier_label=[0, 1, 2])
+        clf.fit(X, y_multi)
+
+    with pytest.raises(ValueError):
+        check_exception()
+
+
+def test_radius_neighbors_classifier_zero_distance():
+    # Test radius-based classifier, when distance to a sample is zero.
+
+    X = np.array([[1.0, 1.0], [2.0, 2.0]])
+    y = np.array([1, 2])
+    radius = 0.1
+
+    z1 = np.array([[1.01, 1.01], [2.0, 2.0]])
+    correct_labels1 = np.array([1, 2])
+
+    weight_func = _weight_func
+
+    for algorithm in ALGORITHMS:
+        for weights in ["uniform", "distance", weight_func]:
+            clf = neighbors.RadiusNeighborsClassifier(
+                radius=radius, weights=weights, algorithm=algorithm
+            )
+            clf.fit(X, y)
+            with np.errstate(invalid="ignore"):
+                # Ignore the warning raised in _weight_func when making
+                # predictions with null distances resulting in np.inf values.
+                assert_array_equal(correct_labels1, clf.predict(z1))
+
+
+def test_neighbors_regressors_zero_distance():
+    # Test radius-based regressor, when distance to a sample is zero.
+
+    X = np.array([[1.0, 1.0], [1.0, 1.0], [2.0, 2.0], [2.5, 2.5]])
+    y = np.array([1.0, 1.5, 2.0, 0.0])
+    radius = 0.2
+    z = np.array([[1.1, 1.1], [2.0, 2.0]])
+
+    rnn_correct_labels = np.array([1.25, 2.0])
+
+    knn_correct_unif = np.array([1.25, 1.0])
+    knn_correct_dist = np.array([1.25, 2.0])
+
+    for algorithm in ALGORITHMS:
+        # we don't test for weights=_weight_func since user will be expected
+        # to handle zero distances themselves in the function.
+        for weights in ["uniform", "distance"]:
+            rnn = neighbors.RadiusNeighborsRegressor(
+                radius=radius, weights=weights, algorithm=algorithm
+            )
+            rnn.fit(X, y)
+            assert_allclose(rnn_correct_labels, rnn.predict(z))
+
+        for weights, corr_labels in zip(
+            ["uniform", "distance"], [knn_correct_unif, knn_correct_dist]
+        ):
+            knn = neighbors.KNeighborsRegressor(
+                n_neighbors=2, weights=weights, algorithm=algorithm
+            )
+            knn.fit(X, y)
+            assert_allclose(corr_labels, knn.predict(z))
+
+
+def test_radius_neighbors_boundary_handling():
+    """Test whether points lying on boundary are handled consistently
+
+    Also ensures that even with only one query point, an object array
+    is returned rather than a 2d array.
+    """
+
+    X = np.array([[1.5], [3.0], [3.01]])
+    radius = 3.0
+
+    for algorithm in ALGORITHMS:
+        nbrs = neighbors.NearestNeighbors(radius=radius, algorithm=algorithm).fit(X)
+        results = nbrs.radius_neighbors([[0.0]], return_distance=False)
+        assert results.shape == (1,)
+        assert results.dtype == object
+        assert_array_equal(results[0], [0, 1])
+
+
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_radius_neighbors_returns_array_of_objects(csr_container):
+    # check that we can pass precomputed distances to
+    # NearestNeighbors.radius_neighbors()
+    # non-regression test for
+    # https://github.com/scikit-learn/scikit-learn/issues/16036
+    X = csr_container(np.ones((4, 4)))
+    X.setdiag([0, 0, 0, 0])
+
+    nbrs = neighbors.NearestNeighbors(
+        radius=0.5, algorithm="auto", leaf_size=30, metric="precomputed"
+    ).fit(X)
+    neigh_dist, neigh_ind = nbrs.radius_neighbors(X, return_distance=True)
+
+    expected_dist = np.empty(X.shape[0], dtype=object)
+    expected_dist[:] = [np.array([0]), np.array([0]), np.array([0]), np.array([0])]
+    expected_ind = np.empty(X.shape[0], dtype=object)
+    expected_ind[:] = [np.array([0]), np.array([1]), np.array([2]), np.array([3])]
+
+    assert_array_equal(neigh_dist, expected_dist)
+    assert_array_equal(neigh_ind, expected_ind)
+
+
+@pytest.mark.parametrize("algorithm", ["ball_tree", "kd_tree", "brute"])
+def test_query_equidistant_kth_nn(algorithm):
+    # For several candidates for the k-th nearest neighbor position,
+    # the first candidate should be chosen
+    query_point = np.array([[0, 0]])
+    equidistant_points = np.array([[1, 0], [0, 1], [-1, 0], [0, -1]])
+    # The 3rd and 4th points should not replace the 2nd point
+    # for the 2th nearest neighbor position
+    k = 2
+    knn_indices = np.array([[0, 1]])
+    nn = neighbors.NearestNeighbors(algorithm=algorithm).fit(equidistant_points)
+    indices = np.sort(nn.kneighbors(query_point, n_neighbors=k, return_distance=False))
+    assert_array_equal(indices, knn_indices)
+
+
+@pytest.mark.parametrize(
+    ["algorithm", "metric"],
+    list(
+        product(
+            ("kd_tree", "ball_tree", "brute"),
+            ("euclidean", *DISTANCE_METRIC_OBJS),
+        )
+    )
+    + [
+        ("brute", "euclidean"),
+        ("brute", "precomputed"),
+    ],
+)
+def test_radius_neighbors_sort_results(algorithm, metric):
+    # Test radius_neighbors[_graph] output when sort_result is True
+
+    metric = _parse_metric(metric, np.float64)
+    if isinstance(metric, DistanceMetric):
+        pytest.skip(
+            "Metrics of type `DistanceMetric` are not yet supported for radius-neighbor"
+            " estimators."
+        )
+    n_samples = 10
+    rng = np.random.RandomState(42)
+    X = rng.random_sample((n_samples, 4))
+
+    if metric == "precomputed":
+        X = neighbors.radius_neighbors_graph(X, radius=np.inf, mode="distance")
+    model = neighbors.NearestNeighbors(algorithm=algorithm, metric=metric)
+    model.fit(X)
+
+    # self.radius_neighbors
+    distances, indices = model.radius_neighbors(X=X, radius=np.inf, sort_results=True)
+    for ii in range(n_samples):
+        assert_array_equal(distances[ii], np.sort(distances[ii]))
+
+    # sort_results=True and return_distance=False
+    if metric != "precomputed":  # no need to raise with precomputed graph
+        with pytest.raises(ValueError, match="return_distance must be True"):
+            model.radius_neighbors(
+                X=X, radius=np.inf, sort_results=True, return_distance=False
+            )
+
+    # self.radius_neighbors_graph
+    graph = model.radius_neighbors_graph(
+        X=X, radius=np.inf, mode="distance", sort_results=True
+    )
+    assert _is_sorted_by_data(graph)
+
+
+def test_RadiusNeighborsClassifier_multioutput():
+    # Test k-NN classifier on multioutput data
+    rng = check_random_state(0)
+    n_features = 2
+    n_samples = 40
+    n_output = 3
+
+    X = rng.rand(n_samples, n_features)
+    y = rng.randint(0, 3, (n_samples, n_output))
+
+    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
+
+    weights = [None, "uniform", "distance", _weight_func]
+
+    for algorithm, weights in product(ALGORITHMS, weights):
+        # Stack single output prediction
+        y_pred_so = []
+        for o in range(n_output):
+            rnn = neighbors.RadiusNeighborsClassifier(
+                weights=weights, algorithm=algorithm
+            )
+            rnn.fit(X_train, y_train[:, o])
+            y_pred_so.append(rnn.predict(X_test))
+
+        y_pred_so = np.vstack(y_pred_so).T
+        assert y_pred_so.shape == y_test.shape
+
+        # Multioutput prediction
+        rnn_mo = neighbors.RadiusNeighborsClassifier(
+            weights=weights, algorithm=algorithm
+        )
+        rnn_mo.fit(X_train, y_train)
+        y_pred_mo = rnn_mo.predict(X_test)
+
+        assert y_pred_mo.shape == y_test.shape
+        assert_array_equal(y_pred_mo, y_pred_so)
+
+
+def test_kneighbors_classifier_sparse(
+    n_samples=40, n_features=5, n_test_pts=10, n_neighbors=5, random_state=0
+):
+    # Test k-NN classifier on sparse matrices
+    # Like the above, but with various types of sparse matrices
+    rng = np.random.RandomState(random_state)
+    X = 2 * rng.rand(n_samples, n_features) - 1
+    X *= X > 0.2
+    y = ((X**2).sum(axis=1) < 0.5).astype(int)
+
+    for sparsemat in SPARSE_TYPES:
+        knn = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm="auto")
+        knn.fit(sparsemat(X), y)
+        epsilon = 1e-5 * (2 * rng.rand(1, n_features) - 1)
+        for sparsev in SPARSE_TYPES + (np.asarray,):
+            X_eps = sparsev(X[:n_test_pts] + epsilon)
+            y_pred = knn.predict(X_eps)
+            assert_array_equal(y_pred, y[:n_test_pts])
+
+
+def test_KNeighborsClassifier_multioutput():
+    # Test k-NN classifier on multioutput data
+    rng = check_random_state(0)
+    n_features = 5
+    n_samples = 50
+    n_output = 3
+
+    X = rng.rand(n_samples, n_features)
+    y = rng.randint(0, 3, (n_samples, n_output))
+
+    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
+
+    weights = [None, "uniform", "distance", _weight_func]
+
+    for algorithm, weights in product(ALGORITHMS, weights):
+        # Stack single output prediction
+        y_pred_so = []
+        y_pred_proba_so = []
+        for o in range(n_output):
+            knn = neighbors.KNeighborsClassifier(weights=weights, algorithm=algorithm)
+            knn.fit(X_train, y_train[:, o])
+            y_pred_so.append(knn.predict(X_test))
+            y_pred_proba_so.append(knn.predict_proba(X_test))
+
+        y_pred_so = np.vstack(y_pred_so).T
+        assert y_pred_so.shape == y_test.shape
+        assert len(y_pred_proba_so) == n_output
+
+        # Multioutput prediction
+        knn_mo = neighbors.KNeighborsClassifier(weights=weights, algorithm=algorithm)
+        knn_mo.fit(X_train, y_train)
+        y_pred_mo = knn_mo.predict(X_test)
+
+        assert y_pred_mo.shape == y_test.shape
+        assert_array_equal(y_pred_mo, y_pred_so)
+
+        # Check proba
+        y_pred_proba_mo = knn_mo.predict_proba(X_test)
+        assert len(y_pred_proba_mo) == n_output
+
+        for proba_mo, proba_so in zip(y_pred_proba_mo, y_pred_proba_so):
+            assert_array_equal(proba_mo, proba_so)
+
+
+def test_kneighbors_regressor(
+    n_samples=40, n_features=5, n_test_pts=10, n_neighbors=3, random_state=0
+):
+    # Test k-neighbors regression
+    rng = np.random.RandomState(random_state)
+    X = 2 * rng.rand(n_samples, n_features) - 1
+    y = np.sqrt((X**2).sum(1))
+    y /= y.max()
+
+    y_target = y[:n_test_pts]
+
+    weight_func = _weight_func
+
+    for algorithm in ALGORITHMS:
+        for weights in ["uniform", "distance", weight_func]:
+            knn = neighbors.KNeighborsRegressor(
+                n_neighbors=n_neighbors, weights=weights, algorithm=algorithm
+            )
+            knn.fit(X, y)
+            epsilon = 1e-5 * (2 * rng.rand(1, n_features) - 1)
+            y_pred = knn.predict(X[:n_test_pts] + epsilon)
+            assert np.all(abs(y_pred - y_target) < 0.3)
+
+
+def test_KNeighborsRegressor_multioutput_uniform_weight():
+    # Test k-neighbors in multi-output regression with uniform weight
+    rng = check_random_state(0)
+    n_features = 5
+    n_samples = 40
+    n_output = 4
+
+    X = rng.rand(n_samples, n_features)
+    y = rng.rand(n_samples, n_output)
+
+    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
+    for algorithm, weights in product(ALGORITHMS, [None, "uniform"]):
+        knn = neighbors.KNeighborsRegressor(weights=weights, algorithm=algorithm)
+        knn.fit(X_train, y_train)
+
+        neigh_idx = knn.kneighbors(X_test, return_distance=False)
+        y_pred_idx = np.array([np.mean(y_train[idx], axis=0) for idx in neigh_idx])
+
+        y_pred = knn.predict(X_test)
+
+        assert y_pred.shape == y_test.shape
+        assert y_pred_idx.shape == y_test.shape
+        assert_allclose(y_pred, y_pred_idx)
+
+
+def test_kneighbors_regressor_multioutput(
+    n_samples=40, n_features=5, n_test_pts=10, n_neighbors=3, random_state=0
+):
+    # Test k-neighbors in multi-output regression
+    rng = np.random.RandomState(random_state)
+    X = 2 * rng.rand(n_samples, n_features) - 1
+    y = np.sqrt((X**2).sum(1))
+    y /= y.max()
+    y = np.vstack([y, y]).T
+
+    y_target = y[:n_test_pts]
+
+    weights = ["uniform", "distance", _weight_func]
+    for algorithm, weights in product(ALGORITHMS, weights):
+        knn = neighbors.KNeighborsRegressor(
+            n_neighbors=n_neighbors, weights=weights, algorithm=algorithm
+        )
+        knn.fit(X, y)
+        epsilon = 1e-5 * (2 * rng.rand(1, n_features) - 1)
+        y_pred = knn.predict(X[:n_test_pts] + epsilon)
+        assert y_pred.shape == y_target.shape
+
+        assert np.all(np.abs(y_pred - y_target) < 0.3)
+
+
+def test_radius_neighbors_regressor(
+    n_samples=40, n_features=3, n_test_pts=10, radius=0.5, random_state=0
+):
+    # Test radius-based neighbors regression
+    rng = np.random.RandomState(random_state)
+    X = 2 * rng.rand(n_samples, n_features) - 1
+    y = np.sqrt((X**2).sum(1))
+    y /= y.max()
+
+    y_target = y[:n_test_pts]
+
+    weight_func = _weight_func
+
+    for algorithm in ALGORITHMS:
+        for weights in ["uniform", "distance", weight_func]:
+            neigh = neighbors.RadiusNeighborsRegressor(
+                radius=radius, weights=weights, algorithm=algorithm
+            )
+            neigh.fit(X, y)
+            epsilon = 1e-5 * (2 * rng.rand(1, n_features) - 1)
+            y_pred = neigh.predict(X[:n_test_pts] + epsilon)
+            assert np.all(abs(y_pred - y_target) < radius / 2)
+
+    # test that nan is returned when no nearby observations
+    for weights in ["uniform", "distance"]:
+        neigh = neighbors.RadiusNeighborsRegressor(
+            radius=radius, weights=weights, algorithm="auto"
+        )
+        neigh.fit(X, y)
+        X_test_nan = np.full((1, n_features), -1.0)
+        empty_warning_msg = (
+            "One or more samples have no neighbors "
+            "within specified radius; predicting NaN."
+        )
+        with pytest.warns(UserWarning, match=re.escape(empty_warning_msg)):
+            pred = neigh.predict(X_test_nan)
+        assert np.all(np.isnan(pred))
+
+
+def test_RadiusNeighborsRegressor_multioutput_with_uniform_weight():
+    # Test radius neighbors in multi-output regression (uniform weight)
+
+    rng = check_random_state(0)
+    n_features = 5
+    n_samples = 40
+    n_output = 4
+
+    X = rng.rand(n_samples, n_features)
+    y = rng.rand(n_samples, n_output)
+    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
+
+    for algorithm, weights in product(ALGORITHMS, [None, "uniform"]):
+        rnn = neighbors.RadiusNeighborsRegressor(weights=weights, algorithm=algorithm)
+        rnn.fit(X_train, y_train)
+
+        neigh_idx = rnn.radius_neighbors(X_test, return_distance=False)
+        y_pred_idx = np.array([np.mean(y_train[idx], axis=0) for idx in neigh_idx])
+
+        y_pred_idx = np.array(y_pred_idx)
+        y_pred = rnn.predict(X_test)
+
+        assert y_pred_idx.shape == y_test.shape
+        assert y_pred.shape == y_test.shape
+        assert_allclose(y_pred, y_pred_idx)
+
+
+def test_RadiusNeighborsRegressor_multioutput(
+    n_samples=40, n_features=5, n_test_pts=10, random_state=0
+):
+    # Test k-neighbors in multi-output regression with various weight
+    rng = np.random.RandomState(random_state)
+    X = 2 * rng.rand(n_samples, n_features) - 1
+    y = np.sqrt((X**2).sum(1))
+    y /= y.max()
+    y = np.vstack([y, y]).T
+
+    y_target = y[:n_test_pts]
+    weights = ["uniform", "distance", _weight_func]
+
+    for algorithm, weights in product(ALGORITHMS, weights):
+        rnn = neighbors.RadiusNeighborsRegressor(weights=weights, algorithm=algorithm)
+        rnn.fit(X, y)
+        epsilon = 1e-5 * (2 * rng.rand(1, n_features) - 1)
+        y_pred = rnn.predict(X[:n_test_pts] + epsilon)
+
+        assert y_pred.shape == y_target.shape
+        assert np.all(np.abs(y_pred - y_target) < 0.3)
+
+
+@pytest.mark.filterwarnings("ignore:EfficiencyWarning")
+def test_kneighbors_regressor_sparse(
+    n_samples=40, n_features=5, n_test_pts=10, n_neighbors=5, random_state=0
+):
+    # Test radius-based regression on sparse matrices
+    # Like the above, but with various types of sparse matrices
+    rng = np.random.RandomState(random_state)
+    X = 2 * rng.rand(n_samples, n_features) - 1
+    y = ((X**2).sum(axis=1) < 0.25).astype(int)
+
+    for sparsemat in SPARSE_TYPES:
+        knn = neighbors.KNeighborsRegressor(n_neighbors=n_neighbors, algorithm="auto")
+        knn.fit(sparsemat(X), y)
+
+        knn_pre = neighbors.KNeighborsRegressor(
+            n_neighbors=n_neighbors, metric="precomputed"
+        )
+        knn_pre.fit(pairwise_distances(X, metric="euclidean"), y)
+
+        for sparsev in SPARSE_OR_DENSE:
+            X2 = sparsev(X)
+            assert np.mean(knn.predict(X2).round() == y) > 0.95
+
+            X2_pre = sparsev(pairwise_distances(X, metric="euclidean"))
+            if sparsev in DOK_CONTAINERS + BSR_CONTAINERS:
+                msg = "not supported due to its handling of explicit zeros"
+                with pytest.raises(TypeError, match=msg):
+                    knn_pre.predict(X2_pre)
+            else:
+                assert np.mean(knn_pre.predict(X2_pre).round() == y) > 0.95
+
+
+def test_neighbors_iris():
+    # Sanity checks on the iris dataset
+    # Puts three points of each label in the plane and performs a
+    # nearest neighbor query on points near the decision boundary.
+
+    for algorithm in ALGORITHMS:
+        clf = neighbors.KNeighborsClassifier(n_neighbors=1, algorithm=algorithm)
+        clf.fit(iris.data, iris.target)
+        assert_array_equal(clf.predict(iris.data), iris.target)
+
+        clf.set_params(n_neighbors=9, algorithm=algorithm)
+        clf.fit(iris.data, iris.target)
+        assert np.mean(clf.predict(iris.data) == iris.target) > 0.95
+
+        rgs = neighbors.KNeighborsRegressor(n_neighbors=5, algorithm=algorithm)
+        rgs.fit(iris.data, iris.target)
+        assert np.mean(rgs.predict(iris.data).round() == iris.target) > 0.95
+
+
+def test_neighbors_digits():
+    # Sanity check on the digits dataset
+    # the 'brute' algorithm has been observed to fail if the input
+    # dtype is uint8 due to overflow in distance calculations.
+
+    X = digits.data.astype("uint8")
+    Y = digits.target
+    (n_samples, n_features) = X.shape
+    train_test_boundary = int(n_samples * 0.8)
+    train = np.arange(0, train_test_boundary)
+    test = np.arange(train_test_boundary, n_samples)
+    (X_train, Y_train, X_test, Y_test) = X[train], Y[train], X[test], Y[test]
+
+    clf = neighbors.KNeighborsClassifier(n_neighbors=1, algorithm="brute")
+    score_uint8 = clf.fit(X_train, Y_train).score(X_test, Y_test)
+    score_float = clf.fit(X_train.astype(float, copy=False), Y_train).score(
+        X_test.astype(float, copy=False), Y_test
+    )
+    assert score_uint8 == score_float
+
+
+def test_kneighbors_graph():
+    # Test kneighbors_graph to build the k-Nearest Neighbor graph.
+    X = np.array([[0, 1], [1.01, 1.0], [2, 0]])
+
+    # n_neighbors = 1
+    A = neighbors.kneighbors_graph(X, 1, mode="connectivity", include_self=True)
+    assert_array_equal(A.toarray(), np.eye(A.shape[0]))
+
+    A = neighbors.kneighbors_graph(X, 1, mode="distance")
+    assert_allclose(
+        A.toarray(), [[0.00, 1.01, 0.0], [1.01, 0.0, 0.0], [0.00, 1.40716026, 0.0]]
+    )
+
+    # n_neighbors = 2
+    A = neighbors.kneighbors_graph(X, 2, mode="connectivity", include_self=True)
+    assert_array_equal(A.toarray(), [[1.0, 1.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 1.0]])
+
+    A = neighbors.kneighbors_graph(X, 2, mode="distance")
+    assert_allclose(
+        A.toarray(),
+        [
+            [0.0, 1.01, 2.23606798],
+            [1.01, 0.0, 1.40716026],
+            [2.23606798, 1.40716026, 0.0],
+        ],
+    )
+
+    # n_neighbors = 3
+    A = neighbors.kneighbors_graph(X, 3, mode="connectivity", include_self=True)
+    assert_allclose(A.toarray(), [[1, 1, 1], [1, 1, 1], [1, 1, 1]])
+
+
+@pytest.mark.parametrize("n_neighbors", [1, 2, 3])
+@pytest.mark.parametrize("mode", ["connectivity", "distance"])
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_kneighbors_graph_sparse(n_neighbors, mode, csr_container, seed=36):
+    # Test kneighbors_graph to build the k-Nearest Neighbor graph
+    # for sparse input.
+    rng = np.random.RandomState(seed)
+    X = rng.randn(10, 10)
+    Xcsr = csr_container(X)
+
+    assert_allclose(
+        neighbors.kneighbors_graph(X, n_neighbors, mode=mode).toarray(),
+        neighbors.kneighbors_graph(Xcsr, n_neighbors, mode=mode).toarray(),
+    )
+
+
+def test_radius_neighbors_graph():
+    # Test radius_neighbors_graph to build the Nearest Neighbor graph.
+    X = np.array([[0, 1], [1.01, 1.0], [2, 0]])
+
+    A = neighbors.radius_neighbors_graph(X, 1.5, mode="connectivity", include_self=True)
+    assert_array_equal(A.toarray(), [[1.0, 1.0, 0.0], [1.0, 1.0, 1.0], [0.0, 1.0, 1.0]])
+
+    A = neighbors.radius_neighbors_graph(X, 1.5, mode="distance")
+    assert_allclose(
+        A.toarray(), [[0.0, 1.01, 0.0], [1.01, 0.0, 1.40716026], [0.0, 1.40716026, 0.0]]
+    )
+
+
+@pytest.mark.parametrize("n_neighbors", [1, 2, 3])
+@pytest.mark.parametrize("mode", ["connectivity", "distance"])
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_radius_neighbors_graph_sparse(n_neighbors, mode, csr_container, seed=36):
+    # Test radius_neighbors_graph to build the Nearest Neighbor graph
+    # for sparse input.
+    rng = np.random.RandomState(seed)
+    X = rng.randn(10, 10)
+    Xcsr = csr_container(X)
+
+    assert_allclose(
+        neighbors.radius_neighbors_graph(X, n_neighbors, mode=mode).toarray(),
+        neighbors.radius_neighbors_graph(Xcsr, n_neighbors, mode=mode).toarray(),
+    )
+
+
+@pytest.mark.parametrize(
+    "Estimator",
+    [
+        neighbors.KNeighborsClassifier,
+        neighbors.RadiusNeighborsClassifier,
+        neighbors.KNeighborsRegressor,
+        neighbors.RadiusNeighborsRegressor,
+    ],
+)
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_neighbors_validate_parameters(Estimator, csr_container):
+    """Additional parameter validation for *Neighbors* estimators not covered by common
+    validation."""
+    X = rng.random_sample((10, 2))
+    Xsparse = csr_container(X)
+    X3 = rng.random_sample((10, 3))
+    y = np.ones(10)
+
+    nbrs = Estimator(algorithm="ball_tree", metric="haversine")
+    msg = "instance is not fitted yet"
+    with pytest.raises(ValueError, match=msg):
+        nbrs.predict(X)
+    msg = "Metric 'haversine' not valid for sparse input."
+    with pytest.raises(ValueError, match=msg):
+        ignore_warnings(nbrs.fit(Xsparse, y))
+
+    nbrs = Estimator(metric="haversine", algorithm="brute")
+    nbrs.fit(X3, y)
+    msg = "Haversine distance only valid in 2 dimensions"
+    with pytest.raises(ValueError, match=msg):
+        nbrs.predict(X3)
+
+    nbrs = Estimator()
+    msg = re.escape("Found array with 0 sample(s)")
+    with pytest.raises(ValueError, match=msg):
+        nbrs.fit(np.ones((0, 2)), np.ones(0))
+
+    msg = "Found array with dim 3"
+    with pytest.raises(ValueError, match=msg):
+        nbrs.fit(X[:, :, None], y)
+    nbrs.fit(X, y)
+
+    msg = re.escape("Found array with 0 feature(s)")
+    with pytest.raises(ValueError, match=msg):
+        nbrs.predict([[]])
+
+
+@pytest.mark.parametrize(
+    "Estimator",
+    [
+        neighbors.KNeighborsClassifier,
+        neighbors.RadiusNeighborsClassifier,
+        neighbors.KNeighborsRegressor,
+        neighbors.RadiusNeighborsRegressor,
+    ],
+)
+@pytest.mark.parametrize("n_features", [2, 100])
+@pytest.mark.parametrize("algorithm", ["auto", "brute"])
+def test_neighbors_minkowski_semimetric_algo_warn(Estimator, n_features, algorithm):
+    """
+    Validation of all classes extending NeighborsBase with
+    Minkowski semi-metrics (i.e. when 0 < p < 1). That proper
+    Warning is raised for `algorithm="auto"` and "brute".
+    """
+    X = rng.random_sample((10, n_features))
+    y = np.ones(10)
+
+    model = Estimator(p=0.1, algorithm=algorithm)
+    msg = (
+        "Mind that for 0 < p < 1, Minkowski metrics are not distance"
+        " metrics. Continuing the execution with `algorithm='brute'`."
+    )
+    with pytest.warns(UserWarning, match=msg):
+        model.fit(X, y)
+
+    assert model._fit_method == "brute"
+
+
+@pytest.mark.parametrize(
+    "Estimator",
+    [
+        neighbors.KNeighborsClassifier,
+        neighbors.RadiusNeighborsClassifier,
+        neighbors.KNeighborsRegressor,
+        neighbors.RadiusNeighborsRegressor,
+    ],
+)
+@pytest.mark.parametrize("n_features", [2, 100])
+@pytest.mark.parametrize("algorithm", ["kd_tree", "ball_tree"])
+def test_neighbors_minkowski_semimetric_algo_error(Estimator, n_features, algorithm):
+    """Check that we raise a proper error if `algorithm!='brute'` and `p<1`."""
+    X = rng.random_sample((10, 2))
+    y = np.ones(10)
+
+    model = Estimator(algorithm=algorithm, p=0.1)
+    msg = (
+        f'algorithm="{algorithm}" does not support 0 < p < 1 for '
+        "the Minkowski metric. To resolve this problem either "
+        'set p >= 1 or algorithm="brute".'
+    )
+    with pytest.raises(ValueError, match=msg):
+        model.fit(X, y)
+
+
+# TODO: remove when NearestNeighbors methods uses parameter validation mechanism
+def test_nearest_neighbors_validate_params():
+    """Validate parameter of NearestNeighbors."""
+    X = rng.random_sample((10, 2))
+
+    nbrs = neighbors.NearestNeighbors().fit(X)
+    msg = (
+        'Unsupported mode, must be one of "connectivity", or "distance" but got "blah"'
+        " instead"
+    )
+    with pytest.raises(ValueError, match=msg):
+        nbrs.kneighbors_graph(X, mode="blah")
+    with pytest.raises(ValueError, match=msg):
+        nbrs.radius_neighbors_graph(X, mode="blah")
+
+
+@pytest.mark.parametrize(
+    "metric",
+    sorted(
+        set(neighbors.VALID_METRICS["ball_tree"]).intersection(
+            neighbors.VALID_METRICS["brute"]
+        )
+        - set(["pyfunc", *BOOL_METRICS])
+    )
+    + DISTANCE_METRIC_OBJS,
+)
+def test_neighbors_metrics(
+    global_dtype,
+    global_random_seed,
+    metric,
+    n_samples=20,
+    n_features=3,
+    n_query_pts=2,
+    n_neighbors=5,
+):
+    rng = np.random.RandomState(global_random_seed)
+
+    metric = _parse_metric(metric, global_dtype)
+
+    # Test computing the neighbors for various metrics
+    algorithms = ["brute", "ball_tree", "kd_tree"]
+    X_train = rng.rand(n_samples, n_features).astype(global_dtype, copy=False)
+    X_test = rng.rand(n_query_pts, n_features).astype(global_dtype, copy=False)
+
+    metric_params_list = _generate_test_params_for(metric, n_features)
+
+    for metric_params in metric_params_list:
+        # Some metric (e.g. Weighted minkowski) are not supported by KDTree
+        exclude_kd_tree = (
+            False
+            if isinstance(metric, DistanceMetric)
+            else metric not in neighbors.VALID_METRICS["kd_tree"]
+            or ("minkowski" in metric and "w" in metric_params)
+        )
+        results = {}
+        p = metric_params.pop("p", 2)
+        for algorithm in algorithms:
+            if isinstance(metric, DistanceMetric) and global_dtype == np.float32:
+                if "tree" in algorithm:  # pragma: nocover
+                    pytest.skip(
+                        "Neither KDTree nor BallTree support 32-bit distance metric"
+                        " objects."
+                    )
+            neigh = neighbors.NearestNeighbors(
+                n_neighbors=n_neighbors,
+                algorithm=algorithm,
+                metric=metric,
+                p=p,
+                metric_params=metric_params,
+            )
+
+            if exclude_kd_tree and algorithm == "kd_tree":
+                with pytest.raises(ValueError):
+                    neigh.fit(X_train)
+                continue
+
+            # Haversine distance only accepts 2D data
+            if metric == "haversine":
+                feature_sl = slice(None, 2)
+                X_train = np.ascontiguousarray(X_train[:, feature_sl])
+                X_test = np.ascontiguousarray(X_test[:, feature_sl])
+
+            neigh.fit(X_train)
+            results[algorithm] = neigh.kneighbors(X_test, return_distance=True)
+
+        brute_dst, brute_idx = results["brute"]
+        ball_tree_dst, ball_tree_idx = results["ball_tree"]
+
+        # The returned distances are always in float64 regardless of the input dtype
+        # We need to adjust the tolerance w.r.t the input dtype
+        rtol = 1e-7 if global_dtype == np.float64 else 1e-4
+
+        assert_allclose(brute_dst, ball_tree_dst, rtol=rtol)
+        assert_array_equal(brute_idx, ball_tree_idx)
+
+        if not exclude_kd_tree:
+            kd_tree_dst, kd_tree_idx = results["kd_tree"]
+            assert_allclose(brute_dst, kd_tree_dst, rtol=rtol)
+            assert_array_equal(brute_idx, kd_tree_idx)
+
+            assert_allclose(ball_tree_dst, kd_tree_dst, rtol=rtol)
+            assert_array_equal(ball_tree_idx, kd_tree_idx)
+
+
+# TODO: Remove ignore_warnings when minimum supported SciPy version is 1.17
+# Some scipy metrics are deprecated (depending on the scipy version) but we
+# still want to test them.
+@ignore_warnings(category=DeprecationWarning)
+@pytest.mark.parametrize(
+    "metric", sorted(set(neighbors.VALID_METRICS["brute"]) - set(["precomputed"]))
+)
+def test_kneighbors_brute_backend(
+    metric,
+    global_dtype,
+    global_random_seed,
+    n_samples=2000,
+    n_features=30,
+    n_query_pts=5,
+    n_neighbors=5,
+):
+    rng = np.random.RandomState(global_random_seed)
+    # Both backend for the 'brute' algorithm of kneighbors must give identical results.
+    X_train = rng.rand(n_samples, n_features).astype(global_dtype, copy=False)
+    X_test = rng.rand(n_query_pts, n_features).astype(global_dtype, copy=False)
+
+    # Haversine distance only accepts 2D data
+    if metric == "haversine":
+        feature_sl = slice(None, 2)
+        X_train = np.ascontiguousarray(X_train[:, feature_sl])
+        X_test = np.ascontiguousarray(X_test[:, feature_sl])
+
+    if metric in PAIRWISE_BOOLEAN_FUNCTIONS:
+        X_train = X_train > 0.5
+        X_test = X_test > 0.5
+
+    metric_params_list = _generate_test_params_for(metric, n_features)
+
+    for metric_params in metric_params_list:
+        p = metric_params.pop("p", 2)
+
+        neigh = neighbors.NearestNeighbors(
+            n_neighbors=n_neighbors,
+            algorithm="brute",
+            metric=metric,
+            p=p,
+            metric_params=metric_params,
+        )
+
+        neigh.fit(X_train)
+
+        with config_context(enable_cython_pairwise_dist=False):
+            # Use the legacy backend for brute
+            legacy_brute_dst, legacy_brute_idx = neigh.kneighbors(
+                X_test, return_distance=True
+            )
+        with config_context(enable_cython_pairwise_dist=True):
+            # Use the pairwise-distances reduction backend for brute
+            pdr_brute_dst, pdr_brute_idx = neigh.kneighbors(
+                X_test, return_distance=True
+            )
+
+        assert_compatible_argkmin_results(
+            legacy_brute_dst, pdr_brute_dst, legacy_brute_idx, pdr_brute_idx
+        )
+
+
+def test_callable_metric():
+    def custom_metric(x1, x2):
+        return np.sqrt(np.sum(x1**2 + x2**2))
+
+    X = np.random.RandomState(42).rand(20, 2)
+    nbrs1 = neighbors.NearestNeighbors(
+        n_neighbors=3, algorithm="auto", metric=custom_metric
+    )
+    nbrs2 = neighbors.NearestNeighbors(
+        n_neighbors=3, algorithm="brute", metric=custom_metric
+    )
+
+    nbrs1.fit(X)
+    nbrs2.fit(X)
+
+    dist1, ind1 = nbrs1.kneighbors(X)
+    dist2, ind2 = nbrs2.kneighbors(X)
+
+    assert_allclose(dist1, dist2)
+
+
+@pytest.mark.parametrize(
+    "metric", neighbors.VALID_METRICS["brute"] + DISTANCE_METRIC_OBJS
+)
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_valid_brute_metric_for_auto_algorithm(
+    global_dtype, metric, csr_container, n_samples=20, n_features=12
+):
+    metric = _parse_metric(metric, global_dtype)
+
+    X = rng.rand(n_samples, n_features).astype(global_dtype, copy=False)
+    Xcsr = csr_container(X)
+
+    metric_params_list = _generate_test_params_for(metric, n_features)
+
+    if metric == "precomputed":
+        X_precomputed = rng.random_sample((10, 4))
+        Y_precomputed = rng.random_sample((3, 4))
+        DXX = metrics.pairwise_distances(X_precomputed, metric="euclidean")
+        DYX = metrics.pairwise_distances(
+            Y_precomputed, X_precomputed, metric="euclidean"
+        )
+        nb_p = neighbors.NearestNeighbors(n_neighbors=3, metric="precomputed")
+        nb_p.fit(DXX)
+        nb_p.kneighbors(DYX)
+
+    else:
+        for metric_params in metric_params_list:
+            nn = neighbors.NearestNeighbors(
+                n_neighbors=3,
+                algorithm="auto",
+                metric=metric,
+                metric_params=metric_params,
+            )
+            # Haversine distance only accepts 2D data
+            if metric == "haversine":
+                feature_sl = slice(None, 2)
+                X = np.ascontiguousarray(X[:, feature_sl])
+
+            nn.fit(X)
+            nn.kneighbors(X)
+
+            if metric in VALID_METRICS_SPARSE["brute"]:
+                nn = neighbors.NearestNeighbors(
+                    n_neighbors=3, algorithm="auto", metric=metric
+                ).fit(Xcsr)
+                nn.kneighbors(Xcsr)
+
+
+def test_metric_params_interface():
+    X = rng.rand(5, 5)
+    y = rng.randint(0, 2, 5)
+    est = neighbors.KNeighborsClassifier(metric_params={"p": 3})
+    with pytest.warns(SyntaxWarning):
+        est.fit(X, y)
+
+
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_predict_sparse_ball_kd_tree(csr_container):
+    rng = np.random.RandomState(0)
+    X = rng.rand(5, 5)
+    y = rng.randint(0, 2, 5)
+    nbrs1 = neighbors.KNeighborsClassifier(1, algorithm="kd_tree")
+    nbrs2 = neighbors.KNeighborsRegressor(1, algorithm="ball_tree")
+    for model in [nbrs1, nbrs2]:
+        model.fit(X, y)
+        with pytest.raises(ValueError):
+            model.predict(csr_container(X))
+
+
+def test_non_euclidean_kneighbors():
+    rng = np.random.RandomState(0)
+    X = rng.rand(5, 5)
+
+    # Find a reasonable radius.
+    dist_array = pairwise_distances(X).flatten()
+    np.sort(dist_array)
+    radius = dist_array[15]
+
+    # Test kneighbors_graph
+    for metric in ["manhattan", "chebyshev"]:
+        nbrs_graph = neighbors.kneighbors_graph(
+            X, 3, metric=metric, mode="connectivity", include_self=True
+        ).toarray()
+        nbrs1 = neighbors.NearestNeighbors(n_neighbors=3, metric=metric).fit(X)
+        assert_array_equal(nbrs_graph, nbrs1.kneighbors_graph(X).toarray())
+
+    # Test radiusneighbors_graph
+    for metric in ["manhattan", "chebyshev"]:
+        nbrs_graph = neighbors.radius_neighbors_graph(
+            X, radius, metric=metric, mode="connectivity", include_self=True
+        ).toarray()
+        nbrs1 = neighbors.NearestNeighbors(metric=metric, radius=radius).fit(X)
+        assert_array_equal(nbrs_graph, nbrs1.radius_neighbors_graph(X).toarray())
+
+    # Raise error when wrong parameters are supplied,
+    X_nbrs = neighbors.NearestNeighbors(n_neighbors=3, metric="manhattan")
+    X_nbrs.fit(X)
+    with pytest.raises(ValueError):
+        neighbors.kneighbors_graph(X_nbrs, 3, metric="euclidean")
+    X_nbrs = neighbors.NearestNeighbors(radius=radius, metric="manhattan")
+    X_nbrs.fit(X)
+    with pytest.raises(ValueError):
+        neighbors.radius_neighbors_graph(X_nbrs, radius, metric="euclidean")
+
+
+def check_object_arrays(nparray, list_check):
+    for ind, ele in enumerate(nparray):
+        assert_array_equal(ele, list_check[ind])
+
+
+def test_k_and_radius_neighbors_train_is_not_query():
+    # Test kneighbors et.al when query is not training data
+
+    for algorithm in ALGORITHMS:
+        nn = neighbors.NearestNeighbors(n_neighbors=1, algorithm=algorithm)
+
+        X = [[0], [1]]
+        nn.fit(X)
+        test_data = [[2], [1]]
+
+        # Test neighbors.
+        dist, ind = nn.kneighbors(test_data)
+        assert_array_equal(dist, [[1], [0]])
+        assert_array_equal(ind, [[1], [1]])
+        dist, ind = nn.radius_neighbors([[2], [1]], radius=1.5)
+        check_object_arrays(dist, [[1], [1, 0]])
+        check_object_arrays(ind, [[1], [0, 1]])
+
+        # Test the graph variants.
+        assert_array_equal(
+            nn.kneighbors_graph(test_data).toarray(), [[0.0, 1.0], [0.0, 1.0]]
+        )
+        assert_array_equal(
+            nn.kneighbors_graph([[2], [1]], mode="distance").toarray(),
+            np.array([[0.0, 1.0], [0.0, 0.0]]),
+        )
+        rng = nn.radius_neighbors_graph([[2], [1]], radius=1.5)
+        assert_array_equal(rng.toarray(), [[0, 1], [1, 1]])
+
+
+@pytest.mark.parametrize("algorithm", ALGORITHMS)
+def test_k_and_radius_neighbors_X_None(algorithm):
+    # Test kneighbors et.al when query is None
+    nn = neighbors.NearestNeighbors(n_neighbors=1, algorithm=algorithm)
+
+    X = [[0], [1]]
+    nn.fit(X)
+
+    dist, ind = nn.kneighbors()
+    assert_array_equal(dist, [[1], [1]])
+    assert_array_equal(ind, [[1], [0]])
+    dist, ind = nn.radius_neighbors(None, radius=1.5)
+    check_object_arrays(dist, [[1], [1]])
+    check_object_arrays(ind, [[1], [0]])
+
+    # Test the graph variants.
+    rng = nn.radius_neighbors_graph(None, radius=1.5)
+    kng = nn.kneighbors_graph(None)
+    for graph in [rng, kng]:
+        assert_array_equal(graph.toarray(), [[0, 1], [1, 0]])
+        assert_array_equal(graph.data, [1, 1])
+        assert_array_equal(graph.indices, [1, 0])
+
+    X = [[0, 1], [0, 1], [1, 1]]
+    nn = neighbors.NearestNeighbors(n_neighbors=2, algorithm=algorithm)
+    nn.fit(X)
+    assert_array_equal(
+        nn.kneighbors_graph().toarray(),
+        np.array([[0.0, 1.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 0]]),
+    )
+
+
+@pytest.mark.parametrize("algorithm", ALGORITHMS)
+def test_k_and_radius_neighbors_duplicates(algorithm):
+    # Test behavior of kneighbors when duplicates are present in query
+    nn = neighbors.NearestNeighbors(n_neighbors=1, algorithm=algorithm)
+    duplicates = [[0], [1], [3]]
+
+    nn.fit(duplicates)
+
+    # Do not do anything special to duplicates.
+    kng = nn.kneighbors_graph(duplicates, mode="distance")
+    assert_allclose(
+        kng.toarray(), np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
+    )
+    assert_allclose(kng.data, [0.0, 0.0, 0.0])
+    assert_allclose(kng.indices, [0, 1, 2])
+
+    dist, ind = nn.radius_neighbors([[0], [1]], radius=1.5)
+    check_object_arrays(dist, [[0, 1], [1, 0]])
+    check_object_arrays(ind, [[0, 1], [0, 1]])
+
+    rng = nn.radius_neighbors_graph(duplicates, radius=1.5)
+    assert_allclose(
+        rng.toarray(), np.array([[1.0, 1.0, 0.0], [1.0, 1.0, 0.0], [0.0, 0.0, 1.0]])
+    )
+
+    rng = nn.radius_neighbors_graph([[0], [1]], radius=1.5, mode="distance")
+    rng.sort_indices()
+    assert_allclose(rng.toarray(), [[0, 1, 0], [1, 0, 0]])
+    assert_allclose(rng.indices, [0, 1, 0, 1])
+    assert_allclose(rng.data, [0, 1, 1, 0])
+
+    # Mask the first duplicates when n_duplicates > n_neighbors.
+    X = np.ones((3, 1))
+    nn = neighbors.NearestNeighbors(n_neighbors=1, algorithm="brute")
+    nn.fit(X)
+    dist, ind = nn.kneighbors()
+    assert_allclose(dist, np.zeros((3, 1)))
+    assert_allclose(ind, [[1], [0], [1]])
+
+    # Test that zeros are explicitly marked in kneighbors_graph.
+    kng = nn.kneighbors_graph(mode="distance")
+    assert_allclose(kng.toarray(), np.zeros((3, 3)))
+    assert_allclose(kng.data, np.zeros(3))
+    assert_allclose(kng.indices, [1, 0, 1])
+    assert_allclose(
+        nn.kneighbors_graph().toarray(),
+        np.array([[0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]),
+    )
+
+
+def test_include_self_neighbors_graph():
+    # Test include_self parameter in neighbors_graph
+    X = [[2, 3], [4, 5]]
+    kng = neighbors.kneighbors_graph(X, 1, include_self=True).toarray()
+    kng_not_self = neighbors.kneighbors_graph(X, 1, include_self=False).toarray()
+    assert_array_equal(kng, [[1.0, 0.0], [0.0, 1.0]])
+    assert_array_equal(kng_not_self, [[0.0, 1.0], [1.0, 0.0]])
+
+    rng = neighbors.radius_neighbors_graph(X, 5.0, include_self=True).toarray()
+    rng_not_self = neighbors.radius_neighbors_graph(
+        X, 5.0, include_self=False
+    ).toarray()
+    assert_array_equal(rng, [[1.0, 1.0], [1.0, 1.0]])
+    assert_array_equal(rng_not_self, [[0.0, 1.0], [1.0, 0.0]])
+
+
+@pytest.mark.parametrize("algorithm", ALGORITHMS)
+def test_same_knn_parallel(algorithm):
+    X, y = datasets.make_classification(
+        n_samples=30, n_features=5, n_redundant=0, random_state=0
+    )
+    X_train, X_test, y_train, y_test = train_test_split(X, y)
+
+    clf = neighbors.KNeighborsClassifier(n_neighbors=3, algorithm=algorithm)
+    clf.fit(X_train, y_train)
+    y = clf.predict(X_test)
+    dist, ind = clf.kneighbors(X_test)
+    graph = clf.kneighbors_graph(X_test, mode="distance").toarray()
+
+    clf.set_params(n_jobs=3)
+    clf.fit(X_train, y_train)
+    y_parallel = clf.predict(X_test)
+    dist_parallel, ind_parallel = clf.kneighbors(X_test)
+    graph_parallel = clf.kneighbors_graph(X_test, mode="distance").toarray()
+
+    assert_array_equal(y, y_parallel)
+    assert_allclose(dist, dist_parallel)
+    assert_array_equal(ind, ind_parallel)
+    assert_allclose(graph, graph_parallel)
+
+
+@pytest.mark.parametrize("algorithm", ALGORITHMS)
+def test_same_radius_neighbors_parallel(algorithm):
+    X, y = datasets.make_classification(
+        n_samples=30, n_features=5, n_redundant=0, random_state=0
+    )
+    X_train, X_test, y_train, y_test = train_test_split(X, y)
+
+    clf = neighbors.RadiusNeighborsClassifier(radius=10, algorithm=algorithm)
+    clf.fit(X_train, y_train)
+    y = clf.predict(X_test)
+    dist, ind = clf.radius_neighbors(X_test)
+    graph = clf.radius_neighbors_graph(X_test, mode="distance").toarray()
+
+    clf.set_params(n_jobs=3)
+    clf.fit(X_train, y_train)
+    y_parallel = clf.predict(X_test)
+    dist_parallel, ind_parallel = clf.radius_neighbors(X_test)
+    graph_parallel = clf.radius_neighbors_graph(X_test, mode="distance").toarray()
+
+    assert_array_equal(y, y_parallel)
+    for i in range(len(dist)):
+        assert_allclose(dist[i], dist_parallel[i])
+        assert_array_equal(ind[i], ind_parallel[i])
+    assert_allclose(graph, graph_parallel)
+
+
+@pytest.mark.parametrize("backend", ["threading", "loky"])
+@pytest.mark.parametrize("algorithm", ALGORITHMS)
+def test_knn_forcing_backend(backend, algorithm):
+    # Non-regression test which ensures the knn methods are properly working
+    # even when forcing the global joblib backend.
+    with joblib.parallel_backend(backend):
+        X, y = datasets.make_classification(
+            n_samples=30, n_features=5, n_redundant=0, random_state=0
+        )
+        X_train, X_test, y_train, y_test = train_test_split(X, y)
+
+        clf = neighbors.KNeighborsClassifier(
+            n_neighbors=3, algorithm=algorithm, n_jobs=2
+        )
+        clf.fit(X_train, y_train)
+        clf.predict(X_test)
+        clf.kneighbors(X_test)
+        clf.kneighbors_graph(X_test, mode="distance")
+
+
+def test_dtype_convert():
+    classifier = neighbors.KNeighborsClassifier(n_neighbors=1)
+    CLASSES = 15
+    X = np.eye(CLASSES)
+    y = [ch for ch in "ABCDEFGHIJKLMNOPQRSTU"[:CLASSES]]
+
+    result = classifier.fit(X, y).predict(X)
+    assert_array_equal(result, y)
+
+
+@pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
+def test_sparse_metric_callable(csr_container):
+    def sparse_metric(x, y):  # Metric accepting sparse matrix input (only)
+        assert issparse(x) and issparse(y)
+        return x.dot(y.T).toarray().item()
+
+    X = csr_container(
+        [[1, 1, 1, 1, 1], [1, 0, 1, 0, 1], [0, 0, 1, 0, 0]]  # Population matrix
+    )
+
+    Y = csr_container([[1, 1, 0, 1, 1], [1, 0, 0, 1, 1]])  # Query matrix
+
+    nn = neighbors.NearestNeighbors(
+        algorithm="brute", n_neighbors=2, metric=sparse_metric
+    ).fit(X)
+    N = nn.kneighbors(Y, return_distance=False)
+
+    # GS indices of nearest neighbours in `X` for `sparse_metric`
+    gold_standard_nn = np.array([[2, 1], [2, 1]])
+
+    assert_array_equal(N, gold_standard_nn)
+
+
+# ignore conversion to boolean in pairwise_distances
+@pytest.mark.filterwarnings("ignore::sklearn.exceptions.DataConversionWarning")
+def test_pairwise_boolean_distance():
+    # Non-regression test for #4523
+    # 'brute': uses scipy.spatial.distance through pairwise_distances
+    # 'ball_tree': uses sklearn.neighbors._dist_metrics
+    rng = np.random.RandomState(0)
+    X = rng.uniform(size=(6, 5))
+    NN = neighbors.NearestNeighbors
+
+    nn1 = NN(metric="jaccard", algorithm="brute").fit(X)
+    nn2 = NN(metric="jaccard", algorithm="ball_tree").fit(X)
+    assert_array_equal(nn1.kneighbors(X)[0], nn2.kneighbors(X)[0])
+
+
+def test_radius_neighbors_predict_proba():
+    for seed in range(5):
+        X, y = datasets.make_classification(
+            n_samples=50,
+            n_features=5,
+            n_informative=3,
+            n_redundant=0,
+            n_classes=3,
+            random_state=seed,
+        )
+        X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)
+        outlier_label = int(2 - seed)
+        clf = neighbors.RadiusNeighborsClassifier(radius=2, outlier_label=outlier_label)
+        clf.fit(X_tr, y_tr)
+        pred = clf.predict(X_te)
+        proba = clf.predict_proba(X_te)
+        proba_label = proba.argmax(axis=1)
+        proba_label = np.where(proba.sum(axis=1) == 0, outlier_label, proba_label)
+        assert_array_equal(pred, proba_label)
+
+
+def test_pipeline_with_nearest_neighbors_transformer():
+    # Test chaining KNeighborsTransformer and classifiers/regressors
+    rng = np.random.RandomState(0)
+    X = 2 * rng.rand(40, 5) - 1
+    X2 = 2 * rng.rand(40, 5) - 1
+    y = rng.rand(40, 1)
+
+    n_neighbors = 12
+    radius = 1.5
+    # We precompute more neighbors than necessary, to have equivalence between
+    # k-neighbors estimator after radius-neighbors transformer, and vice-versa.
+    factor = 2
+
+    k_trans = neighbors.KNeighborsTransformer(n_neighbors=n_neighbors, mode="distance")
+    k_trans_factor = neighbors.KNeighborsTransformer(
+        n_neighbors=int(n_neighbors * factor), mode="distance"
+    )
+
+    r_trans = neighbors.RadiusNeighborsTransformer(radius=radius, mode="distance")
+    r_trans_factor = neighbors.RadiusNeighborsTransformer(
+        radius=int(radius * factor), mode="distance"
+    )
+
+    k_reg = neighbors.KNeighborsRegressor(n_neighbors=n_neighbors)
+    r_reg = neighbors.RadiusNeighborsRegressor(radius=radius)
+
+    test_list = [
+        (k_trans, k_reg),
+        (k_trans_factor, r_reg),
+        (r_trans, r_reg),
+        (r_trans_factor, k_reg),
+    ]
+
+    for trans, reg in test_list:
+        # compare the chained version and the compact version
+        reg_compact = clone(reg)
+        reg_precomp = clone(reg)
+        reg_precomp.set_params(metric="precomputed")
+
+        reg_chain = make_pipeline(clone(trans), reg_precomp)
+
+        y_pred_chain = reg_chain.fit(X, y).predict(X2)
+        y_pred_compact = reg_compact.fit(X, y).predict(X2)
+        assert_allclose(y_pred_chain, y_pred_compact)
+
+
+@pytest.mark.parametrize(
+    "X, metric, metric_params, expected_algo",
+    [
+        (np.random.randint(10, size=(10, 10)), "precomputed", None, "brute"),
+        (np.random.randn(10, 20), "euclidean", None, "brute"),
+        (np.random.randn(8, 5), "euclidean", None, "brute"),
+        (np.random.randn(10, 5), "euclidean", None, "kd_tree"),
+        (np.random.randn(10, 5), "seuclidean", {"V": [2] * 5}, "ball_tree"),
+        (np.random.randn(10, 5), "correlation", None, "brute"),
+    ],
+)
+def test_auto_algorithm(X, metric, metric_params, expected_algo):
+    model = neighbors.NearestNeighbors(
+        n_neighbors=4, algorithm="auto", metric=metric, metric_params=metric_params
+    )
+    model.fit(X)
+    assert model._fit_method == expected_algo
+
+
+# TODO: Remove ignore_warnings when minimum supported SciPy version is 1.17
+# Some scipy metrics are deprecated (depending on the scipy version) but we
+# still want to test them.
+@ignore_warnings(category=DeprecationWarning)
+@pytest.mark.parametrize(
+    "metric", sorted(set(neighbors.VALID_METRICS["brute"]) - set(["precomputed"]))
+)
+def test_radius_neighbors_brute_backend(
+    metric,
+    global_random_seed,
+    global_dtype,
+    n_samples=2000,
+    n_features=30,
+    n_query_pts=5,
+    radius=1.0,
+):
+    rng = np.random.RandomState(global_random_seed)
+    # Both backends for the 'brute' algorithm of radius_neighbors
+    # must give identical results.
+    X_train = rng.rand(n_samples, n_features).astype(global_dtype, copy=False)
+    X_test = rng.rand(n_query_pts, n_features).astype(global_dtype, copy=False)
+
+    # Haversine distance only accepts 2D data
+    if metric == "haversine":
+        feature_sl = slice(None, 2)
+        X_train = np.ascontiguousarray(X_train[:, feature_sl])
+        X_test = np.ascontiguousarray(X_test[:, feature_sl])
+
+    metric_params_list = _generate_test_params_for(metric, n_features)
+
+    for metric_params in metric_params_list:
+        p = metric_params.pop("p", 2)
+
+        neigh = neighbors.NearestNeighbors(
+            radius=radius,
+            algorithm="brute",
+            metric=metric,
+            p=p,
+            metric_params=metric_params,
+        )
+
+        neigh.fit(X_train)
+
+        with config_context(enable_cython_pairwise_dist=False):
+            # Use the legacy backend for brute
+            legacy_brute_dst, legacy_brute_idx = neigh.radius_neighbors(
+                X_test, return_distance=True
+            )
+        with config_context(enable_cython_pairwise_dist=True):
+            # Use the pairwise-distances reduction backend for brute
+            pdr_brute_dst, pdr_brute_idx = neigh.radius_neighbors(
+                X_test, return_distance=True
+            )
+
+        assert_compatible_radius_results(
+            legacy_brute_dst,
+            pdr_brute_dst,
+            legacy_brute_idx,
+            pdr_brute_idx,
+            radius=radius,
+            check_sorted=False,
+        )
+
+
+def test_valid_metrics_has_no_duplicate():
+    for val in neighbors.VALID_METRICS.values():
+        assert len(val) == len(set(val))
+
+
+def test_regressor_predict_on_arraylikes():
+    """Ensures that `predict` works for array-likes when `weights` is a callable.
+
+    Non-regression test for #22687.
+    """
+    X = [[5, 1], [3, 1], [4, 3], [0, 3]]
+    y = [2, 3, 5, 6]
+
+    def _weights(dist):
+        return np.ones_like(dist)
+
+    est = KNeighborsRegressor(n_neighbors=1, algorithm="brute", weights=_weights)
+    est.fit(X, y)
+    assert_allclose(est.predict([[0, 2.5]]), [6])
+
+
+@pytest.mark.parametrize(
+    "Estimator, params",
+    [
+        (neighbors.KNeighborsClassifier, {"n_neighbors": 2}),
+        (neighbors.KNeighborsRegressor, {"n_neighbors": 2}),
+        (neighbors.RadiusNeighborsRegressor, {}),
+        (neighbors.RadiusNeighborsClassifier, {}),
+        (neighbors.KNeighborsTransformer, {"n_neighbors": 2}),
+        (neighbors.RadiusNeighborsTransformer, {"radius": 1.5}),
+        (neighbors.LocalOutlierFactor, {"n_neighbors": 1}),
+    ],
+)
+def test_nan_euclidean_support(Estimator, params):
+    """Check that the different neighbor estimators are lenient towards `nan`
+    values if using `metric="nan_euclidean"`.
+    """
+
+    X = [[0, 1], [1, np.nan], [2, 3], [3, 5]]
+    y = [0, 0, 1, 1]
+
+    params.update({"metric": "nan_euclidean"})
+    estimator = Estimator().set_params(**params).fit(X, y)
+
+    for response_method in ("kneighbors", "predict", "transform", "fit_predict"):
+        if hasattr(estimator, response_method):
+            output = getattr(estimator, response_method)(X)
+            if hasattr(output, "toarray"):
+                assert not np.isnan(output.data).any()
+            else:
+                assert not np.isnan(output).any()
+
+
+def test_predict_dataframe():
+    """Check that KNN predict works with dataframes
+
+    non-regression test for issue #26768
+    """
+    pd = pytest.importorskip("pandas")
+
+    X = pd.DataFrame(np.array([[1, 2], [3, 4], [5, 6], [7, 8]]), columns=["a", "b"])
+    y = np.array([1, 2, 3, 4])
+
+    knn = neighbors.KNeighborsClassifier(n_neighbors=2).fit(X, y)
+    knn.predict(X)
+
+
+def test_nearest_neighbours_works_with_p_less_than_1():
+    """Check that NearestNeighbors works with :math:`p \\in (0,1)` when `algorithm`
+    is `"auto"` or `"brute"` regardless of the dtype of X.
+
+    Non-regression test for issue #26548
+    """
+    X = np.array([[1.0, 0.0], [0.0, 0.0], [0.0, 1.0]])
+    neigh = neighbors.NearestNeighbors(
+        n_neighbors=3, algorithm="brute", metric_params={"p": 0.5}
+    )
+    neigh.fit(X)
+
+    y = neigh.radius_neighbors(X[0].reshape(1, -1), radius=4, return_distance=False)
+    assert_allclose(y[0], [0, 1, 2])
+
+    y = neigh.kneighbors(X[0].reshape(1, -1), return_distance=False)
+    assert_allclose(y[0], [0, 1, 2])
+
+
+def test_KNeighborsClassifier_raise_on_all_zero_weights():
+    """Check that `predict` and `predict_proba` raises on sample of all zeros weights.
+
+    Related to Issue #25854.
+    """
+    X = [[0, 1], [1, 2], [2, 3], [3, 4]]
+    y = [0, 0, 1, 1]
+
+    def _weights(dist):
+        return np.vectorize(lambda x: 0 if x > 0.5 else 1)(dist)
+
+    est = neighbors.KNeighborsClassifier(n_neighbors=3, weights=_weights)
+    est.fit(X, y)
+
+    msg = (
+        "All neighbors of some sample is getting zero weights. "
+        "Please modify 'weights' to avoid this case if you are "
+        "using a user-defined function."
+    )
+
+    with pytest.raises(ValueError, match=msg):
+        est.predict([[1.1, 1.1]])
+
+    with pytest.raises(ValueError, match=msg):
+        est.predict_proba([[1.1, 1.1]])
+
+
+@pytest.mark.parametrize(
+    "nn_model",
+    [
+        neighbors.KNeighborsClassifier(n_neighbors=10),
+        neighbors.RadiusNeighborsClassifier(),
+    ],
+)
+@pytest.mark.parametrize("algorithm", ALGORITHMS)
+def test_neighbor_classifiers_loocv(nn_model, algorithm):
+    """Check that `predict` and related functions work fine with X=None
+
+    Calling predict with X=None computes a prediction for each training point
+    from the labels of its neighbors (without the label of the data point being
+    predicted upon). This is therefore mathematically equivalent to
+    leave-one-out cross-validation without having do any retraining (rebuilding
+    a KD-tree or Ball-tree index) or any data reshuffling.
+    """
+    X, y = datasets.make_blobs(n_samples=15, centers=5, n_features=2, random_state=0)
+
+    nn_model = clone(nn_model).set_params(algorithm=algorithm)
+
+    # Set the radius for RadiusNeighborsRegressor to some percentile of the
+    # empirical pairwise distances to avoid trivial test cases and warnings for
+    # predictions with no neighbors within the radius.
+    if "radius" in nn_model.get_params():
+        dists = pairwise_distances(X).ravel()
+        dists = dists[dists > 0]
+        nn_model.set_params(radius=np.percentile(dists, 80))
+
+    loocv = cross_val_score(nn_model, X, y, cv=LeaveOneOut())
+    nn_model.fit(X, y)
+
+    assert_allclose(loocv, nn_model.predict(None) == y)
+    assert np.mean(loocv) == pytest.approx(nn_model.score(None, y))
+
+    # Evaluating `nn_model` on its "training" set should lead to a higher
+    # accuracy value than leaving out each data point in turn because the
+    # former can overfit while the latter cannot by construction.
+    assert nn_model.score(None, y) < nn_model.score(X, y)
+
+
+@pytest.mark.parametrize(
+    "nn_model",
+    [
+        neighbors.KNeighborsRegressor(n_neighbors=10),
+        neighbors.RadiusNeighborsRegressor(),
+    ],
+)
+@pytest.mark.parametrize("algorithm", ALGORITHMS)
+def test_neighbor_regressors_loocv(nn_model, algorithm):
+    """Check that `predict` and related functions work fine with X=None"""
+    X, y = datasets.make_regression(n_samples=15, n_features=2, random_state=0)
+
+    # Only checking cross_val_predict and not cross_val_score because
+    # cross_val_score does not work with LeaveOneOut() for a regressor: the
+    # default score method implements R2 score which is not well defined for a
+    # single data point.
+    #
+    # TODO: if score is refactored to evaluate models for other scoring
+    # functions, then this test can be extended to check cross_val_score as
+    # well.
+    nn_model = clone(nn_model).set_params(algorithm=algorithm)
+
+    # Set the radius for RadiusNeighborsRegressor to some percentile of the
+    # empirical pairwise distances to avoid trivial test cases and warnings for
+    # predictions with no neighbors within the radius.
+    if "radius" in nn_model.get_params():
+        dists = pairwise_distances(X).ravel()
+        dists = dists[dists > 0]
+        nn_model.set_params(radius=np.percentile(dists, 80))
+
+    loocv = cross_val_predict(nn_model, X, y, cv=LeaveOneOut())
+    nn_model.fit(X, y)
+    assert_allclose(loocv, nn_model.predict(None))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_neighbors_pipeline.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_neighbors_pipeline.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ad78824489cada3ad56ccff34d806ba6cf1278a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_neighbors_pipeline.py
@@ -0,0 +1,256 @@
+"""
+This is testing the equivalence between some estimators with internal nearest
+neighbors computations, and the corresponding pipeline versions with
+KNeighborsTransformer or RadiusNeighborsTransformer to precompute the
+neighbors.
+"""
+
+import numpy as np
+
+from sklearn.base import clone
+from sklearn.cluster import DBSCAN, SpectralClustering
+from sklearn.cluster.tests.common import generate_clustered_data
+from sklearn.datasets import make_blobs
+from sklearn.manifold import TSNE, Isomap, SpectralEmbedding
+from sklearn.neighbors import (
+    KNeighborsRegressor,
+    KNeighborsTransformer,
+    LocalOutlierFactor,
+    RadiusNeighborsRegressor,
+    RadiusNeighborsTransformer,
+)
+from sklearn.pipeline import make_pipeline
+from sklearn.utils._testing import assert_array_almost_equal
+
+
+def test_spectral_clustering():
+    # Test chaining KNeighborsTransformer and SpectralClustering
+    n_neighbors = 5
+    X, _ = make_blobs(random_state=0)
+
+    # compare the chained version and the compact version
+    est_chain = make_pipeline(
+        KNeighborsTransformer(n_neighbors=n_neighbors, mode="connectivity"),
+        SpectralClustering(
+            n_neighbors=n_neighbors, affinity="precomputed", random_state=42
+        ),
+    )
+    est_compact = SpectralClustering(
+        n_neighbors=n_neighbors, affinity="nearest_neighbors", random_state=42
+    )
+    labels_compact = est_compact.fit_predict(X)
+    labels_chain = est_chain.fit_predict(X)
+    assert_array_almost_equal(labels_chain, labels_compact)
+
+
+def test_spectral_embedding():
+    # Test chaining KNeighborsTransformer and SpectralEmbedding
+    n_neighbors = 5
+
+    n_samples = 1000
+    centers = np.array(
+        [
+            [0.0, 5.0, 0.0, 0.0, 0.0],
+            [0.0, 0.0, 4.0, 0.0, 0.0],
+            [1.0, 0.0, 0.0, 5.0, 1.0],
+        ]
+    )
+    S, true_labels = make_blobs(
+        n_samples=n_samples, centers=centers, cluster_std=1.0, random_state=42
+    )
+
+    # compare the chained version and the compact version
+    est_chain = make_pipeline(
+        KNeighborsTransformer(n_neighbors=n_neighbors, mode="connectivity"),
+        SpectralEmbedding(
+            n_neighbors=n_neighbors, affinity="precomputed", random_state=42
+        ),
+    )
+    est_compact = SpectralEmbedding(
+        n_neighbors=n_neighbors, affinity="nearest_neighbors", random_state=42
+    )
+    St_compact = est_compact.fit_transform(S)
+    St_chain = est_chain.fit_transform(S)
+    assert_array_almost_equal(St_chain, St_compact)
+
+
+def test_dbscan():
+    # Test chaining RadiusNeighborsTransformer and DBSCAN
+    radius = 0.3
+    n_clusters = 3
+    X = generate_clustered_data(n_clusters=n_clusters)
+
+    # compare the chained version and the compact version
+    est_chain = make_pipeline(
+        RadiusNeighborsTransformer(radius=radius, mode="distance"),
+        DBSCAN(metric="precomputed", eps=radius),
+    )
+    est_compact = DBSCAN(eps=radius)
+
+    labels_chain = est_chain.fit_predict(X)
+    labels_compact = est_compact.fit_predict(X)
+    assert_array_almost_equal(labels_chain, labels_compact)
+
+
+def test_isomap():
+    # Test chaining KNeighborsTransformer and Isomap with
+    # neighbors_algorithm='precomputed'
+    algorithm = "auto"
+    n_neighbors = 10
+
+    X, _ = make_blobs(random_state=0)
+    X2, _ = make_blobs(random_state=1)
+
+    # compare the chained version and the compact version
+    est_chain = make_pipeline(
+        KNeighborsTransformer(
+            n_neighbors=n_neighbors, algorithm=algorithm, mode="distance"
+        ),
+        Isomap(n_neighbors=n_neighbors, metric="precomputed"),
+    )
+    est_compact = Isomap(n_neighbors=n_neighbors, neighbors_algorithm=algorithm)
+
+    Xt_chain = est_chain.fit_transform(X)
+    Xt_compact = est_compact.fit_transform(X)
+    assert_array_almost_equal(Xt_chain, Xt_compact)
+
+    Xt_chain = est_chain.transform(X2)
+    Xt_compact = est_compact.transform(X2)
+    assert_array_almost_equal(Xt_chain, Xt_compact)
+
+
+def test_tsne():
+    # Test chaining KNeighborsTransformer and TSNE
+    max_iter = 250
+    perplexity = 5
+    n_neighbors = int(3.0 * perplexity + 1)
+
+    rng = np.random.RandomState(0)
+    X = rng.randn(20, 2)
+
+    for metric in ["minkowski", "sqeuclidean"]:
+        # compare the chained version and the compact version
+        est_chain = make_pipeline(
+            KNeighborsTransformer(
+                n_neighbors=n_neighbors, mode="distance", metric=metric
+            ),
+            TSNE(
+                init="random",
+                metric="precomputed",
+                perplexity=perplexity,
+                method="barnes_hut",
+                random_state=42,
+                max_iter=max_iter,
+            ),
+        )
+        est_compact = TSNE(
+            init="random",
+            metric=metric,
+            perplexity=perplexity,
+            max_iter=max_iter,
+            method="barnes_hut",
+            random_state=42,
+        )
+
+        Xt_chain = est_chain.fit_transform(X)
+        Xt_compact = est_compact.fit_transform(X)
+        assert_array_almost_equal(Xt_chain, Xt_compact)
+
+
+def test_lof_novelty_false():
+    # Test chaining KNeighborsTransformer and LocalOutlierFactor
+    n_neighbors = 4
+
+    rng = np.random.RandomState(0)
+    X = rng.randn(40, 2)
+
+    # compare the chained version and the compact version
+    est_chain = make_pipeline(
+        KNeighborsTransformer(n_neighbors=n_neighbors, mode="distance"),
+        LocalOutlierFactor(
+            metric="precomputed",
+            n_neighbors=n_neighbors,
+            novelty=False,
+            contamination="auto",
+        ),
+    )
+    est_compact = LocalOutlierFactor(
+        n_neighbors=n_neighbors, novelty=False, contamination="auto"
+    )
+
+    pred_chain = est_chain.fit_predict(X)
+    pred_compact = est_compact.fit_predict(X)
+    assert_array_almost_equal(pred_chain, pred_compact)
+
+
+def test_lof_novelty_true():
+    # Test chaining KNeighborsTransformer and LocalOutlierFactor
+    n_neighbors = 4
+
+    rng = np.random.RandomState(0)
+    X1 = rng.randn(40, 2)
+    X2 = rng.randn(40, 2)
+
+    # compare the chained version and the compact version
+    est_chain = make_pipeline(
+        KNeighborsTransformer(n_neighbors=n_neighbors, mode="distance"),
+        LocalOutlierFactor(
+            metric="precomputed",
+            n_neighbors=n_neighbors,
+            novelty=True,
+            contamination="auto",
+        ),
+    )
+    est_compact = LocalOutlierFactor(
+        n_neighbors=n_neighbors, novelty=True, contamination="auto"
+    )
+
+    pred_chain = est_chain.fit(X1).predict(X2)
+    pred_compact = est_compact.fit(X1).predict(X2)
+    assert_array_almost_equal(pred_chain, pred_compact)
+
+
+def test_kneighbors_regressor():
+    # Test chaining KNeighborsTransformer and classifiers/regressors
+    rng = np.random.RandomState(0)
+    X = 2 * rng.rand(40, 5) - 1
+    X2 = 2 * rng.rand(40, 5) - 1
+    y = rng.rand(40, 1)
+
+    n_neighbors = 12
+    radius = 1.5
+    # We precompute more neighbors than necessary, to have equivalence between
+    # k-neighbors estimator after radius-neighbors transformer, and vice-versa.
+    factor = 2
+
+    k_trans = KNeighborsTransformer(n_neighbors=n_neighbors, mode="distance")
+    k_trans_factor = KNeighborsTransformer(
+        n_neighbors=int(n_neighbors * factor), mode="distance"
+    )
+
+    r_trans = RadiusNeighborsTransformer(radius=radius, mode="distance")
+    r_trans_factor = RadiusNeighborsTransformer(
+        radius=int(radius * factor), mode="distance"
+    )
+
+    k_reg = KNeighborsRegressor(n_neighbors=n_neighbors)
+    r_reg = RadiusNeighborsRegressor(radius=radius)
+
+    test_list = [
+        (k_trans, k_reg),
+        (k_trans_factor, r_reg),
+        (r_trans, r_reg),
+        (r_trans_factor, k_reg),
+    ]
+
+    for trans, reg in test_list:
+        # compare the chained version and the compact version
+        reg_compact = clone(reg)
+        reg_precomp = clone(reg)
+        reg_precomp.set_params(metric="precomputed")
+
+        reg_chain = make_pipeline(clone(trans), reg_precomp)
+
+        y_pred_chain = reg_chain.fit(X, y).predict(X2)
+        y_pred_compact = reg_compact.fit(X, y).predict(X2)
+        assert_array_almost_equal(y_pred_chain, y_pred_compact)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_neighbors_tree.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_neighbors_tree.py
new file mode 100644
index 0000000000000000000000000000000000000000..de19152e8b7f236d0a524f756ca9c40d48023edb
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_neighbors_tree.py
@@ -0,0 +1,296 @@
+# SPDX-License-Identifier: BSD-3-Clause
+
+import itertools
+import pickle
+
+import numpy as np
+import pytest
+from numpy.testing import assert_allclose, assert_array_almost_equal
+
+from sklearn.metrics import DistanceMetric
+from sklearn.neighbors._ball_tree import (
+    BallTree,
+    kernel_norm,
+)
+from sklearn.neighbors._ball_tree import (
+    NeighborsHeap64 as NeighborsHeapBT,
+)
+from sklearn.neighbors._ball_tree import (
+    nodeheap_sort as nodeheap_sort_bt,
+)
+from sklearn.neighbors._ball_tree import (
+    simultaneous_sort as simultaneous_sort_bt,
+)
+from sklearn.neighbors._kd_tree import (
+    KDTree,
+)
+from sklearn.neighbors._kd_tree import (
+    NeighborsHeap64 as NeighborsHeapKDT,
+)
+from sklearn.neighbors._kd_tree import (
+    nodeheap_sort as nodeheap_sort_kdt,
+)
+from sklearn.neighbors._kd_tree import (
+    simultaneous_sort as simultaneous_sort_kdt,
+)
+from sklearn.utils import check_random_state
+
+rng = np.random.RandomState(42)
+V_mahalanobis = rng.rand(3, 3)
+V_mahalanobis = np.dot(V_mahalanobis, V_mahalanobis.T)
+
+DIMENSION = 3
+
+METRICS = {
+    "euclidean": {},
+    "manhattan": {},
+    "minkowski": dict(p=3),
+    "chebyshev": {},
+    "seuclidean": dict(V=rng.random_sample(DIMENSION)),
+    "mahalanobis": dict(V=V_mahalanobis),
+}
+
+KD_TREE_METRICS = ["euclidean", "manhattan", "chebyshev", "minkowski"]
+BALL_TREE_METRICS = list(METRICS)
+
+
+def dist_func(x1, x2, p):
+    return np.sum((x1 - x2) ** p) ** (1.0 / p)
+
+
+def compute_kernel_slow(Y, X, kernel, h):
+    d = np.sqrt(((Y[:, None, :] - X) ** 2).sum(-1))
+    norm = kernel_norm(h, X.shape[1], kernel)
+
+    if kernel == "gaussian":
+        return norm * np.exp(-0.5 * (d * d) / (h * h)).sum(-1)
+    elif kernel == "tophat":
+        return norm * (d < h).sum(-1)
+    elif kernel == "epanechnikov":
+        return norm * ((1.0 - (d * d) / (h * h)) * (d < h)).sum(-1)
+    elif kernel == "exponential":
+        return norm * (np.exp(-d / h)).sum(-1)
+    elif kernel == "linear":
+        return norm * ((1 - d / h) * (d < h)).sum(-1)
+    elif kernel == "cosine":
+        return norm * (np.cos(0.5 * np.pi * d / h) * (d < h)).sum(-1)
+    else:
+        raise ValueError("kernel not recognized")
+
+
+def brute_force_neighbors(X, Y, k, metric, **kwargs):
+    D = DistanceMetric.get_metric(metric, **kwargs).pairwise(Y, X)
+    ind = np.argsort(D, axis=1)[:, :k]
+    dist = D[np.arange(Y.shape[0])[:, None], ind]
+    return dist, ind
+
+
+@pytest.mark.parametrize("Cls", [KDTree, BallTree])
+@pytest.mark.parametrize(
+    "kernel", ["gaussian", "tophat", "epanechnikov", "exponential", "linear", "cosine"]
+)
+@pytest.mark.parametrize("h", [0.01, 0.1, 1])
+@pytest.mark.parametrize("rtol", [0, 1e-5])
+@pytest.mark.parametrize("atol", [1e-6, 1e-2])
+@pytest.mark.parametrize("breadth_first", [True, False])
+def test_kernel_density(
+    Cls, kernel, h, rtol, atol, breadth_first, n_samples=100, n_features=3
+):
+    rng = check_random_state(1)
+    X = rng.random_sample((n_samples, n_features))
+    Y = rng.random_sample((n_samples, n_features))
+    dens_true = compute_kernel_slow(Y, X, kernel, h)
+
+    tree = Cls(X, leaf_size=10)
+    dens = tree.kernel_density(
+        Y, h, atol=atol, rtol=rtol, kernel=kernel, breadth_first=breadth_first
+    )
+    assert_allclose(dens, dens_true, atol=atol, rtol=max(rtol, 1e-7))
+
+
+@pytest.mark.parametrize("Cls", [KDTree, BallTree])
+def test_neighbor_tree_query_radius(Cls, n_samples=100, n_features=10):
+    rng = check_random_state(0)
+    X = 2 * rng.random_sample(size=(n_samples, n_features)) - 1
+    query_pt = np.zeros(n_features, dtype=float)
+
+    eps = 1e-15  # roundoff error can cause test to fail
+    tree = Cls(X, leaf_size=5)
+    rad = np.sqrt(((X - query_pt) ** 2).sum(1))
+
+    for r in np.linspace(rad[0], rad[-1], 100):
+        ind = tree.query_radius([query_pt], r + eps)[0]
+        i = np.where(rad <= r + eps)[0]
+
+        ind.sort()
+        i.sort()
+
+        assert_array_almost_equal(i, ind)
+
+
+@pytest.mark.parametrize("Cls", [KDTree, BallTree])
+def test_neighbor_tree_query_radius_distance(Cls, n_samples=100, n_features=10):
+    rng = check_random_state(0)
+    X = 2 * rng.random_sample(size=(n_samples, n_features)) - 1
+    query_pt = np.zeros(n_features, dtype=float)
+
+    eps = 1e-15  # roundoff error can cause test to fail
+    tree = Cls(X, leaf_size=5)
+    rad = np.sqrt(((X - query_pt) ** 2).sum(1))
+
+    for r in np.linspace(rad[0], rad[-1], 100):
+        ind, dist = tree.query_radius([query_pt], r + eps, return_distance=True)
+
+        ind = ind[0]
+        dist = dist[0]
+
+        d = np.sqrt(((query_pt - X[ind]) ** 2).sum(1))
+
+        assert_array_almost_equal(d, dist)
+
+
+@pytest.mark.parametrize("Cls", [KDTree, BallTree])
+@pytest.mark.parametrize("dualtree", (True, False))
+def test_neighbor_tree_two_point(Cls, dualtree, n_samples=100, n_features=3):
+    rng = check_random_state(0)
+    X = rng.random_sample((n_samples, n_features))
+    Y = rng.random_sample((n_samples, n_features))
+    r = np.linspace(0, 1, 10)
+    tree = Cls(X, leaf_size=10)
+
+    D = DistanceMetric.get_metric("euclidean").pairwise(Y, X)
+    counts_true = [(D <= ri).sum() for ri in r]
+
+    counts = tree.two_point_correlation(Y, r=r, dualtree=dualtree)
+    assert_array_almost_equal(counts, counts_true)
+
+
+@pytest.mark.parametrize("NeighborsHeap", [NeighborsHeapBT, NeighborsHeapKDT])
+def test_neighbors_heap(NeighborsHeap, n_pts=5, n_nbrs=10):
+    heap = NeighborsHeap(n_pts, n_nbrs)
+    rng = check_random_state(0)
+
+    for row in range(n_pts):
+        d_in = rng.random_sample(2 * n_nbrs).astype(np.float64, copy=False)
+        i_in = np.arange(2 * n_nbrs, dtype=np.intp)
+        for d, i in zip(d_in, i_in):
+            heap.push(row, d, i)
+
+        ind = np.argsort(d_in)
+        d_in = d_in[ind]
+        i_in = i_in[ind]
+
+        d_heap, i_heap = heap.get_arrays(sort=True)
+
+        assert_array_almost_equal(d_in[:n_nbrs], d_heap[row])
+        assert_array_almost_equal(i_in[:n_nbrs], i_heap[row])
+
+
+@pytest.mark.parametrize("nodeheap_sort", [nodeheap_sort_bt, nodeheap_sort_kdt])
+def test_node_heap(nodeheap_sort, n_nodes=50):
+    rng = check_random_state(0)
+    vals = rng.random_sample(n_nodes).astype(np.float64, copy=False)
+
+    i1 = np.argsort(vals)
+    vals2, i2 = nodeheap_sort(vals)
+
+    assert_array_almost_equal(i1, i2)
+    assert_array_almost_equal(vals[i1], vals2)
+
+
+@pytest.mark.parametrize(
+    "simultaneous_sort", [simultaneous_sort_bt, simultaneous_sort_kdt]
+)
+def test_simultaneous_sort(simultaneous_sort, n_rows=10, n_pts=201):
+    rng = check_random_state(0)
+    dist = rng.random_sample((n_rows, n_pts)).astype(np.float64, copy=False)
+    ind = (np.arange(n_pts) + np.zeros((n_rows, 1))).astype(np.intp, copy=False)
+
+    dist2 = dist.copy()
+    ind2 = ind.copy()
+
+    # simultaneous sort rows using function
+    simultaneous_sort(dist, ind)
+
+    # simultaneous sort rows using numpy
+    i = np.argsort(dist2, axis=1)
+    row_ind = np.arange(n_rows)[:, None]
+    dist2 = dist2[row_ind, i]
+    ind2 = ind2[row_ind, i]
+
+    assert_array_almost_equal(dist, dist2)
+    assert_array_almost_equal(ind, ind2)
+
+
+@pytest.mark.parametrize("Cls", [KDTree, BallTree])
+def test_gaussian_kde(Cls, n_samples=1000):
+    # Compare gaussian KDE results to scipy.stats.gaussian_kde
+    from scipy.stats import gaussian_kde
+
+    rng = check_random_state(0)
+    x_in = rng.normal(0, 1, n_samples)
+    x_out = np.linspace(-5, 5, 30)
+
+    for h in [0.01, 0.1, 1]:
+        tree = Cls(x_in[:, None])
+        gkde = gaussian_kde(x_in, bw_method=h / np.std(x_in))
+
+        dens_tree = tree.kernel_density(x_out[:, None], h) / n_samples
+        dens_gkde = gkde.evaluate(x_out)
+
+        assert_array_almost_equal(dens_tree, dens_gkde, decimal=3)
+
+
+@pytest.mark.parametrize(
+    "Cls, metric",
+    itertools.chain(
+        [(KDTree, metric) for metric in KD_TREE_METRICS],
+        [(BallTree, metric) for metric in BALL_TREE_METRICS],
+    ),
+)
+@pytest.mark.parametrize("k", (1, 3, 5))
+@pytest.mark.parametrize("dualtree", (True, False))
+@pytest.mark.parametrize("breadth_first", (True, False))
+def test_nn_tree_query(Cls, metric, k, dualtree, breadth_first):
+    rng = check_random_state(0)
+    X = rng.random_sample((40, DIMENSION))
+    Y = rng.random_sample((10, DIMENSION))
+
+    kwargs = METRICS[metric]
+
+    kdt = Cls(X, leaf_size=1, metric=metric, **kwargs)
+    dist1, ind1 = kdt.query(Y, k, dualtree=dualtree, breadth_first=breadth_first)
+    dist2, ind2 = brute_force_neighbors(X, Y, k, metric, **kwargs)
+
+    # don't check indices here: if there are any duplicate distances,
+    # the indices may not match.  Distances should not have this problem.
+    assert_array_almost_equal(dist1, dist2)
+
+
+@pytest.mark.parametrize(
+    "Cls, metric",
+    [(KDTree, "euclidean"), (BallTree, "euclidean"), (BallTree, dist_func)],
+)
+@pytest.mark.parametrize("protocol", (0, 1, 2))
+def test_pickle(Cls, metric, protocol):
+    rng = check_random_state(0)
+    X = rng.random_sample((10, 3))
+
+    if hasattr(metric, "__call__"):
+        kwargs = {"p": 2}
+    else:
+        kwargs = {}
+
+    tree1 = Cls(X, leaf_size=1, metric=metric, **kwargs)
+
+    ind1, dist1 = tree1.query(X)
+
+    s = pickle.dumps(tree1, protocol=protocol)
+    tree2 = pickle.loads(s)
+
+    ind2, dist2 = tree2.query(X)
+
+    assert_array_almost_equal(ind1, ind2)
+    assert_array_almost_equal(dist1, dist2)
+
+    assert isinstance(tree2, Cls)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_quad_tree.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_quad_tree.py
new file mode 100644
index 0000000000000000000000000000000000000000..be9a4c5fe549d32a130f9c6a55f6675fa0e42f20
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/neighbors/tests/test_quad_tree.py
@@ -0,0 +1,144 @@
+import pickle
+
+import numpy as np
+import pytest
+
+from sklearn.neighbors._quad_tree import _QuadTree
+from sklearn.utils import check_random_state
+
+
+def test_quadtree_boundary_computation():
+    # Introduce a point into a quad tree with boundaries not easy to compute.
+    Xs = []
+
+    # check a random case
+    Xs.append(np.array([[-1, 1], [-4, -1]], dtype=np.float32))
+    # check the case where only 0 are inserted
+    Xs.append(np.array([[0, 0], [0, 0]], dtype=np.float32))
+    # check the case where only negative are inserted
+    Xs.append(np.array([[-1, -2], [-4, 0]], dtype=np.float32))
+    # check the case where only small numbers are inserted
+    Xs.append(np.array([[-1e-6, 1e-6], [-4e-6, -1e-6]], dtype=np.float32))
+
+    for X in Xs:
+        tree = _QuadTree(n_dimensions=2, verbose=0)
+        tree.build_tree(X)
+        tree._check_coherence()
+
+
+def test_quadtree_similar_point():
+    # Introduce a point into a quad tree where a similar point already exists.
+    # Test will hang if it doesn't complete.
+    Xs = []
+
+    # check the case where points are actually different
+    Xs.append(np.array([[1, 2], [3, 4]], dtype=np.float32))
+    # check the case where points are the same on X axis
+    Xs.append(np.array([[1.0, 2.0], [1.0, 3.0]], dtype=np.float32))
+    # check the case where points are arbitrarily close on X axis
+    Xs.append(np.array([[1.00001, 2.0], [1.00002, 3.0]], dtype=np.float32))
+    # check the case where points are the same on Y axis
+    Xs.append(np.array([[1.0, 2.0], [3.0, 2.0]], dtype=np.float32))
+    # check the case where points are arbitrarily close on Y axis
+    Xs.append(np.array([[1.0, 2.00001], [3.0, 2.00002]], dtype=np.float32))
+    # check the case where points are arbitrarily close on both axes
+    Xs.append(np.array([[1.00001, 2.00001], [1.00002, 2.00002]], dtype=np.float32))
+
+    # check the case where points are arbitrarily close on both axes
+    # close to machine epsilon - x axis
+    Xs.append(np.array([[1, 0.0003817754041], [2, 0.0003817753750]], dtype=np.float32))
+
+    # check the case where points are arbitrarily close on both axes
+    # close to machine epsilon - y axis
+    Xs.append(
+        np.array([[0.0003817754041, 1.0], [0.0003817753750, 2.0]], dtype=np.float32)
+    )
+
+    for X in Xs:
+        tree = _QuadTree(n_dimensions=2, verbose=0)
+        tree.build_tree(X)
+        tree._check_coherence()
+
+
+@pytest.mark.parametrize("n_dimensions", (2, 3))
+@pytest.mark.parametrize("protocol", (0, 1, 2))
+def test_quad_tree_pickle(n_dimensions, protocol):
+    rng = check_random_state(0)
+
+    X = rng.random_sample((10, n_dimensions))
+
+    tree = _QuadTree(n_dimensions=n_dimensions, verbose=0)
+    tree.build_tree(X)
+
+    s = pickle.dumps(tree, protocol=protocol)
+    bt2 = pickle.loads(s)
+
+    for x in X:
+        cell_x_tree = tree.get_cell(x)
+        cell_x_bt2 = bt2.get_cell(x)
+        assert cell_x_tree == cell_x_bt2
+
+
+@pytest.mark.parametrize("n_dimensions", (2, 3))
+def test_qt_insert_duplicate(n_dimensions):
+    rng = check_random_state(0)
+
+    X = rng.random_sample((10, n_dimensions))
+    Xd = np.r_[X, X[:5]]
+    tree = _QuadTree(n_dimensions=n_dimensions, verbose=0)
+    tree.build_tree(Xd)
+
+    cumulative_size = tree.cumulative_size
+    leafs = tree.leafs
+
+    # Assert that the first 5 are indeed duplicated and that the next
+    # ones are single point leaf
+    for i, x in enumerate(X):
+        cell_id = tree.get_cell(x)
+        assert leafs[cell_id]
+        assert cumulative_size[cell_id] == 1 + (i < 5)
+
+
+def test_summarize():
+    # Simple check for quad tree's summarize
+
+    angle = 0.9
+    X = np.array(
+        [[-10.0, -10.0], [9.0, 10.0], [10.0, 9.0], [10.0, 10.0]], dtype=np.float32
+    )
+    query_pt = X[0, :]
+    n_dimensions = X.shape[1]
+    offset = n_dimensions + 2
+
+    qt = _QuadTree(n_dimensions, verbose=0)
+    qt.build_tree(X)
+
+    idx, summary = qt._py_summarize(query_pt, X, angle)
+
+    node_dist = summary[n_dimensions]
+    node_size = summary[n_dimensions + 1]
+
+    # Summary should contain only 1 node with size 3 and distance to
+    # X[1:] barycenter
+    barycenter = X[1:].mean(axis=0)
+    ds2c = ((X[0] - barycenter) ** 2).sum()
+
+    assert idx == offset
+    assert node_size == 3, "summary size = {}".format(node_size)
+    assert np.isclose(node_dist, ds2c)
+
+    # Summary should contain all 3 node with size 1 and distance to
+    # each point in X[1:] for ``angle=0``
+    idx, summary = qt._py_summarize(query_pt, X, 0.0)
+    barycenter = X[1:].mean(axis=0)
+    ds2c = ((X[0] - barycenter) ** 2).sum()
+
+    assert idx == 3 * (offset)
+    for i in range(3):
+        node_dist = summary[i * offset + n_dimensions]
+        node_size = summary[i * offset + n_dimensions + 1]
+
+        ds2c = ((X[0] - X[i + 1]) ** 2).sum()
+
+        assert node_size == 1, "summary size = {}".format(node_size)
+        assert np.isclose(node_dist, ds2c)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/semi_supervised/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/semi_supervised/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..453cd5edc348bf1a0d957e011cd2fa85fee9b34a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/semi_supervised/__init__.py
@@ -0,0 +1,13 @@
+"""Semi-supervised learning algorithms.
+
+These algorithms utilize small amounts of labeled data and large amounts of unlabeled
+data for classification tasks.
+"""
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+from ._label_propagation import LabelPropagation, LabelSpreading
+from ._self_training import SelfTrainingClassifier
+
+__all__ = ["LabelPropagation", "LabelSpreading", "SelfTrainingClassifier"]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/semi_supervised/_label_propagation.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/semi_supervised/_label_propagation.py
new file mode 100644
index 0000000000000000000000000000000000000000..559a17a13d6ae35f4a97a008d6e4c07e4dc77923
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/semi_supervised/_label_propagation.py
@@ -0,0 +1,630 @@
+# coding=utf8
+"""
+Label propagation in the context of this module refers to a set of
+semi-supervised classification algorithms. At a high level, these algorithms
+work by forming a fully-connected graph between all points given and solving
+for the steady-state distribution of labels at each point.
+
+These algorithms perform very well in practice. The cost of running can be very
+expensive, at approximately O(N^3) where N is the number of (labeled and
+unlabeled) points. The theory (why they perform so well) is motivated by
+intuitions from random walk algorithms and geometric relationships in the data.
+For more information see the references below.
+
+Model Features
+--------------
+Label clamping:
+  The algorithm tries to learn distributions of labels over the dataset given
+  label assignments over an initial subset. In one variant, the algorithm does
+  not allow for any errors in the initial assignment (hard-clamping) while
+  in another variant, the algorithm allows for some wiggle room for the initial
+  assignments, allowing them to change by a fraction alpha in each iteration
+  (soft-clamping).
+
+Kernel:
+  A function which projects a vector into some higher dimensional space. This
+  implementation supports RBF and KNN kernels. Using the RBF kernel generates
+  a dense matrix of size O(N^2). KNN kernel will generate a sparse matrix of
+  size O(k*N) which will run much faster. See the documentation for SVMs for
+  more info on kernels.
+
+Examples
+--------
+>>> import numpy as np
+>>> from sklearn import datasets
+>>> from sklearn.semi_supervised import LabelPropagation
+>>> label_prop_model = LabelPropagation()
+>>> iris = datasets.load_iris()
+>>> rng = np.random.RandomState(42)
+>>> random_unlabeled_points = rng.rand(len(iris.target)) < 0.3
+>>> labels = np.copy(iris.target)
+>>> labels[random_unlabeled_points] = -1
+>>> label_prop_model.fit(iris.data, labels)
+LabelPropagation(...)
+
+Notes
+-----
+References:
+[1] Yoshua Bengio, Olivier Delalleau, Nicolas Le Roux. In Semi-Supervised
+Learning (2006), pp. 193-216
+
+[2] Olivier Delalleau, Yoshua Bengio, Nicolas Le Roux. Efficient
+Non-Parametric Function Induction in Semi-Supervised Learning. AISTAT 2005
+"""
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+import warnings
+from abc import ABCMeta, abstractmethod
+from numbers import Integral, Real
+
+import numpy as np
+from scipy import sparse
+
+from ..base import BaseEstimator, ClassifierMixin, _fit_context
+from ..exceptions import ConvergenceWarning
+from ..metrics.pairwise import rbf_kernel
+from ..neighbors import NearestNeighbors
+from ..utils._param_validation import Interval, StrOptions
+from ..utils.extmath import safe_sparse_dot
+from ..utils.fixes import laplacian as csgraph_laplacian
+from ..utils.multiclass import check_classification_targets
+from ..utils.validation import check_is_fitted, validate_data
+
+
+class BaseLabelPropagation(ClassifierMixin, BaseEstimator, metaclass=ABCMeta):
+    """Base class for label propagation module.
+
+     Parameters
+     ----------
+     kernel : {'knn', 'rbf'} or callable, default='rbf'
+         String identifier for kernel function to use or the kernel function
+         itself. Only 'rbf' and 'knn' strings are valid inputs. The function
+         passed should take two inputs, each of shape (n_samples, n_features),
+         and return a (n_samples, n_samples) shaped weight matrix.
+
+     gamma : float, default=20
+         Parameter for rbf kernel.
+
+     n_neighbors : int, default=7
+         Parameter for knn kernel. Need to be strictly positive.
+
+     alpha : float, default=1.0
+         Clamping factor.
+
+     max_iter : int, default=30
+         Change maximum number of iterations allowed.
+
+     tol : float, default=1e-3
+         Convergence tolerance: threshold to consider the system at steady
+         state.
+
+    n_jobs : int, default=None
+         The number of parallel jobs to run.
+         ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+         ``-1`` means using all processors. See :term:`Glossary `
+         for more details.
+    """
+
+    _parameter_constraints: dict = {
+        "kernel": [StrOptions({"knn", "rbf"}), callable],
+        "gamma": [Interval(Real, 0, None, closed="left")],
+        "n_neighbors": [Interval(Integral, 0, None, closed="neither")],
+        "alpha": [None, Interval(Real, 0, 1, closed="neither")],
+        "max_iter": [Interval(Integral, 0, None, closed="neither")],
+        "tol": [Interval(Real, 0, None, closed="left")],
+        "n_jobs": [None, Integral],
+    }
+
+    def __init__(
+        self,
+        kernel="rbf",
+        *,
+        gamma=20,
+        n_neighbors=7,
+        alpha=1,
+        max_iter=30,
+        tol=1e-3,
+        n_jobs=None,
+    ):
+        self.max_iter = max_iter
+        self.tol = tol
+
+        # kernel parameters
+        self.kernel = kernel
+        self.gamma = gamma
+        self.n_neighbors = n_neighbors
+
+        # clamping factor
+        self.alpha = alpha
+
+        self.n_jobs = n_jobs
+
+    def _get_kernel(self, X, y=None):
+        if self.kernel == "rbf":
+            if y is None:
+                return rbf_kernel(X, X, gamma=self.gamma)
+            else:
+                return rbf_kernel(X, y, gamma=self.gamma)
+        elif self.kernel == "knn":
+            if self.nn_fit is None:
+                self.nn_fit = NearestNeighbors(
+                    n_neighbors=self.n_neighbors, n_jobs=self.n_jobs
+                ).fit(X)
+            if y is None:
+                return self.nn_fit.kneighbors_graph(
+                    self.nn_fit._fit_X, self.n_neighbors, mode="connectivity"
+                )
+            else:
+                return self.nn_fit.kneighbors(y, return_distance=False)
+        elif callable(self.kernel):
+            if y is None:
+                return self.kernel(X, X)
+            else:
+                return self.kernel(X, y)
+
+    @abstractmethod
+    def _build_graph(self):
+        raise NotImplementedError(
+            "Graph construction must be implemented to fit a label propagation model."
+        )
+
+    def predict(self, X):
+        """Perform inductive inference across the model.
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            The data matrix.
+
+        Returns
+        -------
+        y : ndarray of shape (n_samples,)
+            Predictions for input data.
+        """
+        # Note: since `predict` does not accept semi-supervised labels as input,
+        # `fit(X, y).predict(X) != fit(X, y).transduction_`.
+        # Hence, `fit_predict` is not implemented.
+        # See https://github.com/scikit-learn/scikit-learn/pull/24898
+        probas = self.predict_proba(X)
+        return self.classes_[np.argmax(probas, axis=1)].ravel()
+
+    def predict_proba(self, X):
+        """Predict probability for each possible outcome.
+
+        Compute the probability estimates for each single sample in X
+        and each possible outcome seen during training (categorical
+        distribution).
+
+        Parameters
+        ----------
+        X : array-like of shape (n_samples, n_features)
+            The data matrix.
+
+        Returns
+        -------
+        probabilities : ndarray of shape (n_samples, n_classes)
+            Normalized probability distributions across
+            class labels.
+        """
+        check_is_fitted(self)
+
+        X_2d = validate_data(
+            self,
+            X,
+            accept_sparse=["csc", "csr", "coo", "dok", "bsr", "lil", "dia"],
+            reset=False,
+        )
+        weight_matrices = self._get_kernel(self.X_, X_2d)
+        if self.kernel == "knn":
+            probabilities = np.array(
+                [
+                    np.sum(self.label_distributions_[weight_matrix], axis=0)
+                    for weight_matrix in weight_matrices
+                ]
+            )
+        else:
+            weight_matrices = weight_matrices.T
+            probabilities = safe_sparse_dot(weight_matrices, self.label_distributions_)
+        normalizer = np.atleast_2d(np.sum(probabilities, axis=1)).T
+        probabilities /= normalizer
+        return probabilities
+
+    @_fit_context(prefer_skip_nested_validation=True)
+    def fit(self, X, y):
+        """Fit a semi-supervised label propagation model to X.
+
+        The input samples (labeled and unlabeled) are provided by matrix X,
+        and target labels are provided by matrix y. We conventionally apply the
+        label -1 to unlabeled samples in matrix y in a semi-supervised
+        classification.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            Training data, where `n_samples` is the number of samples
+            and `n_features` is the number of features.
+
+        y : array-like of shape (n_samples,)
+            Target class values with unlabeled points marked as -1.
+            All unlabeled samples will be transductively assigned labels
+            internally, which are stored in `transduction_`.
+
+        Returns
+        -------
+        self : object
+            Returns the instance itself.
+        """
+        X, y = validate_data(
+            self,
+            X,
+            y,
+            accept_sparse=["csr", "csc"],
+            reset=True,
+        )
+        self.X_ = X
+        check_classification_targets(y)
+
+        # actual graph construction (implementations should override this)
+        graph_matrix = self._build_graph()
+
+        # label construction
+        # construct a categorical distribution for classification only
+        classes = np.unique(y)
+        classes = classes[classes != -1]
+        self.classes_ = classes
+
+        n_samples, n_classes = len(y), len(classes)
+
+        y = np.asarray(y)
+        unlabeled = y == -1
+
+        # initialize distributions
+        self.label_distributions_ = np.zeros((n_samples, n_classes))
+        for label in classes:
+            self.label_distributions_[y == label, classes == label] = 1
+
+        y_static = np.copy(self.label_distributions_)
+        if self._variant == "propagation":
+            # LabelPropagation
+            y_static[unlabeled] = 0
+        else:
+            # LabelSpreading
+            y_static *= 1 - self.alpha
+
+        l_previous = np.zeros((self.X_.shape[0], n_classes))
+
+        unlabeled = unlabeled[:, np.newaxis]
+        if sparse.issparse(graph_matrix):
+            graph_matrix = graph_matrix.tocsr()
+
+        for self.n_iter_ in range(self.max_iter):
+            if np.abs(self.label_distributions_ - l_previous).sum() < self.tol:
+                break
+
+            l_previous = self.label_distributions_
+            self.label_distributions_ = safe_sparse_dot(
+                graph_matrix, self.label_distributions_
+            )
+
+            if self._variant == "propagation":
+                normalizer = np.sum(self.label_distributions_, axis=1)[:, np.newaxis]
+                normalizer[normalizer == 0] = 1
+                self.label_distributions_ /= normalizer
+                self.label_distributions_ = np.where(
+                    unlabeled, self.label_distributions_, y_static
+                )
+            else:
+                # clamp
+                self.label_distributions_ = (
+                    np.multiply(self.alpha, self.label_distributions_) + y_static
+                )
+        else:
+            warnings.warn(
+                "max_iter=%d was reached without convergence." % self.max_iter,
+                category=ConvergenceWarning,
+            )
+            self.n_iter_ += 1
+
+        normalizer = np.sum(self.label_distributions_, axis=1)[:, np.newaxis]
+        normalizer[normalizer == 0] = 1
+        self.label_distributions_ /= normalizer
+
+        # set the transduction item
+        transduction = self.classes_[np.argmax(self.label_distributions_, axis=1)]
+        self.transduction_ = transduction.ravel()
+        return self
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        tags.input_tags.sparse = True
+        return tags
+
+
+class LabelPropagation(BaseLabelPropagation):
+    """Label Propagation classifier.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    kernel : {'knn', 'rbf'} or callable, default='rbf'
+        String identifier for kernel function to use or the kernel function
+        itself. Only 'rbf' and 'knn' strings are valid inputs. The function
+        passed should take two inputs, each of shape (n_samples, n_features),
+        and return a (n_samples, n_samples) shaped weight matrix.
+
+    gamma : float, default=20
+        Parameter for rbf kernel.
+
+    n_neighbors : int, default=7
+        Parameter for knn kernel which need to be strictly positive.
+
+    max_iter : int, default=1000
+        Change maximum number of iterations allowed.
+
+    tol : float, default=1e-3
+        Convergence tolerance: threshold to consider the system at steady
+        state.
+
+    n_jobs : int, default=None
+        The number of parallel jobs to run.
+        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+        ``-1`` means using all processors. See :term:`Glossary `
+        for more details.
+
+    Attributes
+    ----------
+    X_ : {array-like, sparse matrix} of shape (n_samples, n_features)
+        Input array.
+
+    classes_ : ndarray of shape (n_classes,)
+        The distinct labels used in classifying instances.
+
+    label_distributions_ : ndarray of shape (n_samples, n_classes)
+        Categorical distribution for each item.
+
+    transduction_ : ndarray of shape (n_samples)
+        Label assigned to each item during :term:`fit`.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    n_iter_ : int
+        Number of iterations run.
+
+    See Also
+    --------
+    LabelSpreading : Alternate label propagation strategy more robust to noise.
+
+    References
+    ----------
+    Xiaojin Zhu and Zoubin Ghahramani. Learning from labeled and unlabeled data
+    with label propagation. Technical Report CMU-CALD-02-107, Carnegie Mellon
+    University, 2002 http://pages.cs.wisc.edu/~jerryzhu/pub/CMU-CALD-02-107.pdf
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from sklearn import datasets
+    >>> from sklearn.semi_supervised import LabelPropagation
+    >>> label_prop_model = LabelPropagation()
+    >>> iris = datasets.load_iris()
+    >>> rng = np.random.RandomState(42)
+    >>> random_unlabeled_points = rng.rand(len(iris.target)) < 0.3
+    >>> labels = np.copy(iris.target)
+    >>> labels[random_unlabeled_points] = -1
+    >>> label_prop_model.fit(iris.data, labels)
+    LabelPropagation(...)
+    """
+
+    _variant = "propagation"
+
+    _parameter_constraints: dict = {**BaseLabelPropagation._parameter_constraints}
+    _parameter_constraints.pop("alpha")
+
+    def __init__(
+        self,
+        kernel="rbf",
+        *,
+        gamma=20,
+        n_neighbors=7,
+        max_iter=1000,
+        tol=1e-3,
+        n_jobs=None,
+    ):
+        super().__init__(
+            kernel=kernel,
+            gamma=gamma,
+            n_neighbors=n_neighbors,
+            max_iter=max_iter,
+            tol=tol,
+            n_jobs=n_jobs,
+            alpha=None,
+        )
+
+    def _build_graph(self):
+        """Matrix representing a fully connected graph between each sample
+
+        This basic implementation creates a non-stochastic affinity matrix, so
+        class distributions will exceed 1 (normalization may be desired).
+        """
+        if self.kernel == "knn":
+            self.nn_fit = None
+        affinity_matrix = self._get_kernel(self.X_)
+        normalizer = affinity_matrix.sum(axis=0)
+        if sparse.issparse(affinity_matrix):
+            affinity_matrix.data /= np.diag(np.array(normalizer))
+        else:
+            affinity_matrix /= normalizer[:, np.newaxis]
+        return affinity_matrix
+
+    def fit(self, X, y):
+        """Fit a semi-supervised label propagation model to X.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            Training data, where `n_samples` is the number of samples
+            and `n_features` is the number of features.
+
+        y : array-like of shape (n_samples,)
+            Target class values with unlabeled points marked as -1.
+            All unlabeled samples will be transductively assigned labels
+            internally, which are stored in `transduction_`.
+
+        Returns
+        -------
+        self : object
+            Returns the instance itself.
+        """
+        return super().fit(X, y)
+
+
+class LabelSpreading(BaseLabelPropagation):
+    """LabelSpreading model for semi-supervised learning.
+
+    This model is similar to the basic Label Propagation algorithm,
+    but uses affinity matrix based on the normalized graph Laplacian
+    and soft clamping across the labels.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    kernel : {'knn', 'rbf'} or callable, default='rbf'
+        String identifier for kernel function to use or the kernel function
+        itself. Only 'rbf' and 'knn' strings are valid inputs. The function
+        passed should take two inputs, each of shape (n_samples, n_features),
+        and return a (n_samples, n_samples) shaped weight matrix.
+
+    gamma : float, default=20
+      Parameter for rbf kernel.
+
+    n_neighbors : int, default=7
+      Parameter for knn kernel which is a strictly positive integer.
+
+    alpha : float, default=0.2
+      Clamping factor. A value in (0, 1) that specifies the relative amount
+      that an instance should adopt the information from its neighbors as
+      opposed to its initial label.
+      alpha=0 means keeping the initial label information; alpha=1 means
+      replacing all initial information.
+
+    max_iter : int, default=30
+      Maximum number of iterations allowed.
+
+    tol : float, default=1e-3
+      Convergence tolerance: threshold to consider the system at steady
+      state.
+
+    n_jobs : int, default=None
+        The number of parallel jobs to run.
+        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
+        ``-1`` means using all processors. See :term:`Glossary `
+        for more details.
+
+    Attributes
+    ----------
+    X_ : ndarray of shape (n_samples, n_features)
+        Input array.
+
+    classes_ : ndarray of shape (n_classes,)
+        The distinct labels used in classifying instances.
+
+    label_distributions_ : ndarray of shape (n_samples, n_classes)
+        Categorical distribution for each item.
+
+    transduction_ : ndarray of shape (n_samples,)
+        Label assigned to each item during :term:`fit`.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    n_iter_ : int
+        Number of iterations run.
+
+    See Also
+    --------
+    LabelPropagation : Unregularized graph based semi-supervised learning.
+
+    References
+    ----------
+    `Dengyong Zhou, Olivier Bousquet, Thomas Navin Lal, Jason Weston,
+    Bernhard Schoelkopf. Learning with local and global consistency (2004)
+    `_
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from sklearn import datasets
+    >>> from sklearn.semi_supervised import LabelSpreading
+    >>> label_prop_model = LabelSpreading()
+    >>> iris = datasets.load_iris()
+    >>> rng = np.random.RandomState(42)
+    >>> random_unlabeled_points = rng.rand(len(iris.target)) < 0.3
+    >>> labels = np.copy(iris.target)
+    >>> labels[random_unlabeled_points] = -1
+    >>> label_prop_model.fit(iris.data, labels)
+    LabelSpreading(...)
+    """
+
+    _variant = "spreading"
+
+    _parameter_constraints: dict = {**BaseLabelPropagation._parameter_constraints}
+    _parameter_constraints["alpha"] = [Interval(Real, 0, 1, closed="neither")]
+
+    def __init__(
+        self,
+        kernel="rbf",
+        *,
+        gamma=20,
+        n_neighbors=7,
+        alpha=0.2,
+        max_iter=30,
+        tol=1e-3,
+        n_jobs=None,
+    ):
+        # this one has different base parameters
+        super().__init__(
+            kernel=kernel,
+            gamma=gamma,
+            n_neighbors=n_neighbors,
+            alpha=alpha,
+            max_iter=max_iter,
+            tol=tol,
+            n_jobs=n_jobs,
+        )
+
+    def _build_graph(self):
+        """Graph matrix for Label Spreading computes the graph laplacian"""
+        # compute affinity matrix (or gram matrix)
+        if self.kernel == "knn":
+            self.nn_fit = None
+        n_samples = self.X_.shape[0]
+        affinity_matrix = self._get_kernel(self.X_)
+        laplacian = csgraph_laplacian(affinity_matrix, normed=True)
+        laplacian = -laplacian
+        if sparse.issparse(laplacian):
+            diag_mask = laplacian.row == laplacian.col
+            laplacian.data[diag_mask] = 0.0
+        else:
+            laplacian.flat[:: n_samples + 1] = 0.0  # set diag to 0.0
+        return laplacian
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/semi_supervised/_self_training.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/semi_supervised/_self_training.py
new file mode 100644
index 0000000000000000000000000000000000000000..0fe6f57d6c1ed281748e7223554a103a52a01334
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/semi_supervised/_self_training.py
@@ -0,0 +1,625 @@
+import warnings
+from numbers import Integral, Real
+from warnings import warn
+
+import numpy as np
+
+from ..base import (
+    BaseEstimator,
+    ClassifierMixin,
+    MetaEstimatorMixin,
+    _fit_context,
+    clone,
+)
+from ..utils import Bunch, get_tags, safe_mask
+from ..utils._param_validation import HasMethods, Hidden, Interval, StrOptions
+from ..utils.metadata_routing import (
+    MetadataRouter,
+    MethodMapping,
+    _raise_for_params,
+    _routing_enabled,
+    process_routing,
+)
+from ..utils.metaestimators import available_if
+from ..utils.validation import _estimator_has, check_is_fitted, validate_data
+
+__all__ = ["SelfTrainingClassifier"]
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+
+class SelfTrainingClassifier(ClassifierMixin, MetaEstimatorMixin, BaseEstimator):
+    """Self-training classifier.
+
+    This :term:`metaestimator` allows a given supervised classifier to function as a
+    semi-supervised classifier, allowing it to learn from unlabeled data. It
+    does this by iteratively predicting pseudo-labels for the unlabeled data
+    and adding them to the training set.
+
+    The classifier will continue iterating until either max_iter is reached, or
+    no pseudo-labels were added to the training set in the previous iteration.
+
+    Read more in the :ref:`User Guide `.
+
+    Parameters
+    ----------
+    estimator : estimator object
+        An estimator object implementing `fit` and `predict_proba`.
+        Invoking the `fit` method will fit a clone of the passed estimator,
+        which will be stored in the `estimator_` attribute.
+
+        .. versionadded:: 1.6
+            `estimator` was added to replace `base_estimator`.
+
+    base_estimator : estimator object
+        An estimator object implementing `fit` and `predict_proba`.
+        Invoking the `fit` method will fit a clone of the passed estimator,
+        which will be stored in the `estimator_` attribute.
+
+        .. deprecated:: 1.6
+            `base_estimator` was deprecated in 1.6 and will be removed in 1.8.
+            Use `estimator` instead.
+
+    threshold : float, default=0.75
+        The decision threshold for use with `criterion='threshold'`.
+        Should be in [0, 1). When using the `'threshold'` criterion, a
+        :ref:`well calibrated classifier ` should be used.
+
+    criterion : {'threshold', 'k_best'}, default='threshold'
+        The selection criterion used to select which labels to add to the
+        training set. If `'threshold'`, pseudo-labels with prediction
+        probabilities above `threshold` are added to the dataset. If `'k_best'`,
+        the `k_best` pseudo-labels with highest prediction probabilities are
+        added to the dataset. When using the 'threshold' criterion, a
+        :ref:`well calibrated classifier ` should be used.
+
+    k_best : int, default=10
+        The amount of samples to add in each iteration. Only used when
+        `criterion='k_best'`.
+
+    max_iter : int or None, default=10
+        Maximum number of iterations allowed. Should be greater than or equal
+        to 0. If it is `None`, the classifier will continue to predict labels
+        until no new pseudo-labels are added, or all unlabeled samples have
+        been labeled.
+
+    verbose : bool, default=False
+        Enable verbose output.
+
+    Attributes
+    ----------
+    estimator_ : estimator object
+        The fitted estimator.
+
+    classes_ : ndarray or list of ndarray of shape (n_classes,)
+        Class labels for each output. (Taken from the trained
+        `estimator_`).
+
+    transduction_ : ndarray of shape (n_samples,)
+        The labels used for the final fit of the classifier, including
+        pseudo-labels added during fit.
+
+    labeled_iter_ : ndarray of shape (n_samples,)
+        The iteration in which each sample was labeled. When a sample has
+        iteration 0, the sample was already labeled in the original dataset.
+        When a sample has iteration -1, the sample was not labeled in any
+        iteration.
+
+    n_features_in_ : int
+        Number of features seen during :term:`fit`.
+
+        .. versionadded:: 0.24
+
+    feature_names_in_ : ndarray of shape (`n_features_in_`,)
+        Names of features seen during :term:`fit`. Defined only when `X`
+        has feature names that are all strings.
+
+        .. versionadded:: 1.0
+
+    n_iter_ : int
+        The number of rounds of self-training, that is the number of times the
+        base estimator is fitted on relabeled variants of the training set.
+
+    termination_condition_ : {'max_iter', 'no_change', 'all_labeled'}
+        The reason that fitting was stopped.
+
+        - `'max_iter'`: `n_iter_` reached `max_iter`.
+        - `'no_change'`: no new labels were predicted.
+        - `'all_labeled'`: all unlabeled samples were labeled before `max_iter`
+          was reached.
+
+    See Also
+    --------
+    LabelPropagation : Label propagation classifier.
+    LabelSpreading : Label spreading model for semi-supervised learning.
+
+    References
+    ----------
+    :doi:`David Yarowsky. 1995. Unsupervised word sense disambiguation rivaling
+    supervised methods. In Proceedings of the 33rd annual meeting on
+    Association for Computational Linguistics (ACL '95). Association for
+    Computational Linguistics, Stroudsburg, PA, USA, 189-196.
+    <10.3115/981658.981684>`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from sklearn import datasets
+    >>> from sklearn.semi_supervised import SelfTrainingClassifier
+    >>> from sklearn.svm import SVC
+    >>> rng = np.random.RandomState(42)
+    >>> iris = datasets.load_iris()
+    >>> random_unlabeled_points = rng.rand(iris.target.shape[0]) < 0.3
+    >>> iris.target[random_unlabeled_points] = -1
+    >>> svc = SVC(probability=True, gamma="auto")
+    >>> self_training_model = SelfTrainingClassifier(svc)
+    >>> self_training_model.fit(iris.data, iris.target)
+    SelfTrainingClassifier(...)
+    """
+
+    _parameter_constraints: dict = {
+        # We don't require `predic_proba` here to allow passing a meta-estimator
+        # that only exposes `predict_proba` after fitting.
+        # TODO(1.8) remove None option
+        "estimator": [None, HasMethods(["fit"])],
+        # TODO(1.8) remove
+        "base_estimator": [
+            HasMethods(["fit"]),
+            Hidden(StrOptions({"deprecated"})),
+        ],
+        "threshold": [Interval(Real, 0.0, 1.0, closed="left")],
+        "criterion": [StrOptions({"threshold", "k_best"})],
+        "k_best": [Interval(Integral, 1, None, closed="left")],
+        "max_iter": [Interval(Integral, 0, None, closed="left"), None],
+        "verbose": ["verbose"],
+    }
+
+    def __init__(
+        self,
+        estimator=None,
+        base_estimator="deprecated",
+        threshold=0.75,
+        criterion="threshold",
+        k_best=10,
+        max_iter=10,
+        verbose=False,
+    ):
+        self.estimator = estimator
+        self.threshold = threshold
+        self.criterion = criterion
+        self.k_best = k_best
+        self.max_iter = max_iter
+        self.verbose = verbose
+
+        # TODO(1.8) remove
+        self.base_estimator = base_estimator
+
+    def _get_estimator(self):
+        """Get the estimator.
+
+        Returns
+        -------
+        estimator_ : estimator object
+            The cloned estimator object.
+        """
+        # TODO(1.8): remove and only keep clone(self.estimator)
+        if self.estimator is None and self.base_estimator != "deprecated":
+            estimator_ = clone(self.base_estimator)
+
+            warn(
+                (
+                    "`base_estimator` has been deprecated in 1.6 and will be removed"
+                    " in 1.8. Please use `estimator` instead."
+                ),
+                FutureWarning,
+            )
+        # TODO(1.8) remove
+        elif self.estimator is None and self.base_estimator == "deprecated":
+            raise ValueError(
+                "You must pass an estimator to SelfTrainingClassifier. Use `estimator`."
+            )
+        elif self.estimator is not None and self.base_estimator != "deprecated":
+            raise ValueError(
+                "You must pass only one estimator to SelfTrainingClassifier."
+                " Use `estimator`."
+            )
+        else:
+            estimator_ = clone(self.estimator)
+        return estimator_
+
+    @_fit_context(
+        # SelfTrainingClassifier.estimator is not validated yet
+        prefer_skip_nested_validation=False
+    )
+    def fit(self, X, y, **params):
+        """
+        Fit self-training classifier using `X`, `y` as training data.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            Array representing the data.
+
+        y : {array-like, sparse matrix} of shape (n_samples,)
+            Array representing the labels. Unlabeled samples should have the
+            label -1.
+
+        **params : dict
+            Parameters to pass to the underlying estimators.
+
+            .. versionadded:: 1.6
+                Only available if `enable_metadata_routing=True`,
+                which can be set by using
+                ``sklearn.set_config(enable_metadata_routing=True)``.
+                See :ref:`Metadata Routing User Guide ` for
+                more details.
+
+        Returns
+        -------
+        self : object
+            Fitted estimator.
+        """
+        _raise_for_params(params, self, "fit")
+
+        self.estimator_ = self._get_estimator()
+
+        # we need row slicing support for sparse matrices, but costly finiteness check
+        # can be delegated to the base estimator.
+        X, y = validate_data(
+            self,
+            X,
+            y,
+            accept_sparse=["csr", "csc", "lil", "dok"],
+            ensure_all_finite=False,
+        )
+
+        if y.dtype.kind in ["U", "S"]:
+            raise ValueError(
+                "y has dtype string. If you wish to predict on "
+                "string targets, use dtype object, and use -1"
+                " as the label for unlabeled samples."
+            )
+
+        has_label = y != -1
+
+        if np.all(has_label):
+            warnings.warn("y contains no unlabeled samples", UserWarning)
+
+        if self.criterion == "k_best" and (
+            self.k_best > X.shape[0] - np.sum(has_label)
+        ):
+            warnings.warn(
+                (
+                    "k_best is larger than the amount of unlabeled "
+                    "samples. All unlabeled samples will be labeled in "
+                    "the first iteration"
+                ),
+                UserWarning,
+            )
+
+        if _routing_enabled():
+            routed_params = process_routing(self, "fit", **params)
+        else:
+            routed_params = Bunch(estimator=Bunch(fit={}))
+
+        self.transduction_ = np.copy(y)
+        self.labeled_iter_ = np.full_like(y, -1)
+        self.labeled_iter_[has_label] = 0
+
+        self.n_iter_ = 0
+
+        while not np.all(has_label) and (
+            self.max_iter is None or self.n_iter_ < self.max_iter
+        ):
+            self.n_iter_ += 1
+            self.estimator_.fit(
+                X[safe_mask(X, has_label)],
+                self.transduction_[has_label],
+                **routed_params.estimator.fit,
+            )
+
+            # Predict on the unlabeled samples
+            prob = self.estimator_.predict_proba(X[safe_mask(X, ~has_label)])
+            pred = self.estimator_.classes_[np.argmax(prob, axis=1)]
+            max_proba = np.max(prob, axis=1)
+
+            # Select new labeled samples
+            if self.criterion == "threshold":
+                selected = max_proba > self.threshold
+            else:
+                n_to_select = min(self.k_best, max_proba.shape[0])
+                if n_to_select == max_proba.shape[0]:
+                    selected = np.ones_like(max_proba, dtype=bool)
+                else:
+                    # NB these are indices, not a mask
+                    selected = np.argpartition(-max_proba, n_to_select)[:n_to_select]
+
+            # Map selected indices into original array
+            selected_full = np.nonzero(~has_label)[0][selected]
+
+            # Add newly labeled confident predictions to the dataset
+            self.transduction_[selected_full] = pred[selected]
+            has_label[selected_full] = True
+            self.labeled_iter_[selected_full] = self.n_iter_
+
+            if selected_full.shape[0] == 0:
+                # no changed labels
+                self.termination_condition_ = "no_change"
+                break
+
+            if self.verbose:
+                print(
+                    f"End of iteration {self.n_iter_},"
+                    f" added {selected_full.shape[0]} new labels."
+                )
+
+        if self.n_iter_ == self.max_iter:
+            self.termination_condition_ = "max_iter"
+        if np.all(has_label):
+            self.termination_condition_ = "all_labeled"
+
+        self.estimator_.fit(
+            X[safe_mask(X, has_label)],
+            self.transduction_[has_label],
+            **routed_params.estimator.fit,
+        )
+        self.classes_ = self.estimator_.classes_
+        return self
+
+    @available_if(_estimator_has("predict"))
+    def predict(self, X, **params):
+        """Predict the classes of `X`.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            Array representing the data.
+
+        **params : dict of str -> object
+            Parameters to pass to the underlying estimator's ``predict`` method.
+
+            .. versionadded:: 1.6
+                Only available if `enable_metadata_routing=True`,
+                which can be set by using
+                ``sklearn.set_config(enable_metadata_routing=True)``.
+                See :ref:`Metadata Routing User Guide ` for
+                more details.
+
+        Returns
+        -------
+        y : ndarray of shape (n_samples,)
+            Array with predicted labels.
+        """
+        check_is_fitted(self)
+        _raise_for_params(params, self, "predict")
+
+        if _routing_enabled():
+            # metadata routing is enabled.
+            routed_params = process_routing(self, "predict", **params)
+        else:
+            routed_params = Bunch(estimator=Bunch(predict={}))
+
+        X = validate_data(
+            self,
+            X,
+            accept_sparse=True,
+            ensure_all_finite=False,
+            reset=False,
+        )
+        return self.estimator_.predict(X, **routed_params.estimator.predict)
+
+    @available_if(_estimator_has("predict_proba"))
+    def predict_proba(self, X, **params):
+        """Predict probability for each possible outcome.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            Array representing the data.
+
+        **params : dict of str -> object
+            Parameters to pass to the underlying estimator's
+            ``predict_proba`` method.
+
+            .. versionadded:: 1.6
+                Only available if `enable_metadata_routing=True`,
+                which can be set by using
+                ``sklearn.set_config(enable_metadata_routing=True)``.
+                See :ref:`Metadata Routing User Guide ` for
+                more details.
+
+        Returns
+        -------
+        y : ndarray of shape (n_samples, n_features)
+            Array with prediction probabilities.
+        """
+        check_is_fitted(self)
+        _raise_for_params(params, self, "predict_proba")
+
+        if _routing_enabled():
+            # metadata routing is enabled.
+            routed_params = process_routing(self, "predict_proba", **params)
+        else:
+            routed_params = Bunch(estimator=Bunch(predict_proba={}))
+
+        X = validate_data(
+            self,
+            X,
+            accept_sparse=True,
+            ensure_all_finite=False,
+            reset=False,
+        )
+        return self.estimator_.predict_proba(X, **routed_params.estimator.predict_proba)
+
+    @available_if(_estimator_has("decision_function"))
+    def decision_function(self, X, **params):
+        """Call decision function of the `estimator`.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            Array representing the data.
+
+        **params : dict of str -> object
+            Parameters to pass to the underlying estimator's
+            ``decision_function`` method.
+
+            .. versionadded:: 1.6
+                Only available if `enable_metadata_routing=True`,
+                which can be set by using
+                ``sklearn.set_config(enable_metadata_routing=True)``.
+                See :ref:`Metadata Routing User Guide ` for
+                more details.
+
+        Returns
+        -------
+        y : ndarray of shape (n_samples, n_features)
+            Result of the decision function of the `estimator`.
+        """
+        check_is_fitted(self)
+        _raise_for_params(params, self, "decision_function")
+
+        if _routing_enabled():
+            # metadata routing is enabled.
+            routed_params = process_routing(self, "decision_function", **params)
+        else:
+            routed_params = Bunch(estimator=Bunch(decision_function={}))
+
+        X = validate_data(
+            self,
+            X,
+            accept_sparse=True,
+            ensure_all_finite=False,
+            reset=False,
+        )
+        return self.estimator_.decision_function(
+            X, **routed_params.estimator.decision_function
+        )
+
+    @available_if(_estimator_has("predict_log_proba"))
+    def predict_log_proba(self, X, **params):
+        """Predict log probability for each possible outcome.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            Array representing the data.
+
+        **params : dict of str -> object
+            Parameters to pass to the underlying estimator's
+            ``predict_log_proba`` method.
+
+            .. versionadded:: 1.6
+                Only available if `enable_metadata_routing=True`,
+                which can be set by using
+                ``sklearn.set_config(enable_metadata_routing=True)``.
+                See :ref:`Metadata Routing User Guide ` for
+                more details.
+
+        Returns
+        -------
+        y : ndarray of shape (n_samples, n_features)
+            Array with log prediction probabilities.
+        """
+        check_is_fitted(self)
+        _raise_for_params(params, self, "predict_log_proba")
+
+        if _routing_enabled():
+            # metadata routing is enabled.
+            routed_params = process_routing(self, "predict_log_proba", **params)
+        else:
+            routed_params = Bunch(estimator=Bunch(predict_log_proba={}))
+
+        X = validate_data(
+            self,
+            X,
+            accept_sparse=True,
+            ensure_all_finite=False,
+            reset=False,
+        )
+        return self.estimator_.predict_log_proba(
+            X, **routed_params.estimator.predict_log_proba
+        )
+
+    @available_if(_estimator_has("score"))
+    def score(self, X, y, **params):
+        """Call score on the `estimator`.
+
+        Parameters
+        ----------
+        X : {array-like, sparse matrix} of shape (n_samples, n_features)
+            Array representing the data.
+
+        y : array-like of shape (n_samples,)
+            Array representing the labels.
+
+        **params : dict of str -> object
+            Parameters to pass to the underlying estimator's ``score`` method.
+
+            .. versionadded:: 1.6
+                Only available if `enable_metadata_routing=True`,
+                which can be set by using
+                ``sklearn.set_config(enable_metadata_routing=True)``.
+                See :ref:`Metadata Routing User Guide ` for
+                more details.
+
+        Returns
+        -------
+        score : float
+            Result of calling score on the `estimator`.
+        """
+        check_is_fitted(self)
+        _raise_for_params(params, self, "score")
+
+        if _routing_enabled():
+            # metadata routing is enabled.
+            routed_params = process_routing(self, "score", **params)
+        else:
+            routed_params = Bunch(estimator=Bunch(score={}))
+
+        X = validate_data(
+            self,
+            X,
+            accept_sparse=True,
+            ensure_all_finite=False,
+            reset=False,
+        )
+        return self.estimator_.score(X, y, **routed_params.estimator.score)
+
+    def get_metadata_routing(self):
+        """Get metadata routing of this object.
+
+        Please check :ref:`User Guide ` on how the routing
+        mechanism works.
+
+        .. versionadded:: 1.6
+
+        Returns
+        -------
+        routing : MetadataRouter
+            A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
+            routing information.
+        """
+        router = MetadataRouter(owner=self.__class__.__name__)
+        router.add(
+            estimator=self.estimator,
+            method_mapping=(
+                MethodMapping()
+                .add(callee="fit", caller="fit")
+                .add(callee="score", caller="fit")
+                .add(callee="predict", caller="predict")
+                .add(callee="predict_proba", caller="predict_proba")
+                .add(callee="decision_function", caller="decision_function")
+                .add(callee="predict_log_proba", caller="predict_log_proba")
+                .add(callee="score", caller="score")
+            ),
+        )
+        return router
+
+    def __sklearn_tags__(self):
+        tags = super().__sklearn_tags__()
+        # TODO(1.8): remove the condition check together with base_estimator
+        if self.estimator is not None:
+            tags.input_tags.sparse = get_tags(self.estimator).input_tags.sparse
+        return tags
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/semi_supervised/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/semi_supervised/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/semi_supervised/tests/test_label_propagation.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/semi_supervised/tests/test_label_propagation.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b046aa11125032a706b5c984c5dec5caba72594
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/semi_supervised/tests/test_label_propagation.py
@@ -0,0 +1,238 @@
+"""test the label propagation module"""
+
+import warnings
+
+import numpy as np
+import pytest
+from scipy.sparse import issparse
+
+from sklearn.datasets import make_classification
+from sklearn.exceptions import ConvergenceWarning
+from sklearn.metrics.pairwise import rbf_kernel
+from sklearn.model_selection import train_test_split
+from sklearn.neighbors import NearestNeighbors
+from sklearn.semi_supervised import _label_propagation as label_propagation
+from sklearn.utils._testing import (
+    _convert_container,
+    assert_allclose,
+    assert_array_equal,
+)
+
+CONSTRUCTOR_TYPES = ("array", "sparse_csr", "sparse_csc")
+
+ESTIMATORS = [
+    (label_propagation.LabelPropagation, {"kernel": "rbf"}),
+    (label_propagation.LabelPropagation, {"kernel": "knn", "n_neighbors": 2}),
+    (
+        label_propagation.LabelPropagation,
+        {"kernel": lambda x, y: rbf_kernel(x, y, gamma=20)},
+    ),
+    (label_propagation.LabelSpreading, {"kernel": "rbf"}),
+    (label_propagation.LabelSpreading, {"kernel": "knn", "n_neighbors": 2}),
+    (
+        label_propagation.LabelSpreading,
+        {"kernel": lambda x, y: rbf_kernel(x, y, gamma=20)},
+    ),
+]
+
+
+@pytest.mark.parametrize("Estimator, parameters", ESTIMATORS)
+def test_fit_transduction(global_dtype, Estimator, parameters):
+    samples = np.asarray([[1.0, 0.0], [0.0, 2.0], [1.0, 3.0]], dtype=global_dtype)
+    labels = [0, 1, -1]
+    clf = Estimator(**parameters).fit(samples, labels)
+    assert clf.transduction_[2] == 1
+
+
+@pytest.mark.parametrize("Estimator, parameters", ESTIMATORS)
+def test_distribution(global_dtype, Estimator, parameters):
+    if parameters["kernel"] == "knn":
+        pytest.skip(
+            "Unstable test for this configuration: changes in k-NN ordering break it."
+        )
+    samples = np.asarray([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]], dtype=global_dtype)
+    labels = [0, 1, -1]
+    clf = Estimator(**parameters).fit(samples, labels)
+    assert_allclose(clf.label_distributions_[2], [0.5, 0.5], atol=1e-2)
+
+
+@pytest.mark.parametrize("Estimator, parameters", ESTIMATORS)
+def test_predict(global_dtype, Estimator, parameters):
+    samples = np.asarray([[1.0, 0.0], [0.0, 2.0], [1.0, 3.0]], dtype=global_dtype)
+    labels = [0, 1, -1]
+    clf = Estimator(**parameters).fit(samples, labels)
+    assert_array_equal(clf.predict([[0.5, 2.5]]), np.array([1]))
+
+
+@pytest.mark.parametrize("Estimator, parameters", ESTIMATORS)
+def test_predict_proba(global_dtype, Estimator, parameters):
+    samples = np.asarray([[1.0, 0.0], [0.0, 1.0], [1.0, 2.5]], dtype=global_dtype)
+    labels = [0, 1, -1]
+    clf = Estimator(**parameters).fit(samples, labels)
+    assert_allclose(clf.predict_proba([[1.0, 1.0]]), np.array([[0.5, 0.5]]))
+
+
+@pytest.mark.parametrize("alpha", [0.1, 0.3, 0.5, 0.7, 0.9])
+@pytest.mark.parametrize("Estimator, parameters", ESTIMATORS)
+def test_label_spreading_closed_form(global_dtype, Estimator, parameters, alpha):
+    n_classes = 2
+    X, y = make_classification(n_classes=n_classes, n_samples=200, random_state=0)
+    X = X.astype(global_dtype, copy=False)
+    y[::3] = -1
+
+    gamma = 0.1
+    clf = label_propagation.LabelSpreading(gamma=gamma).fit(X, y)
+    # adopting notation from Zhou et al (2004):
+    S = clf._build_graph()
+    Y = np.zeros((len(y), n_classes + 1), dtype=X.dtype)
+    Y[np.arange(len(y)), y] = 1
+    Y = Y[:, :-1]
+
+    expected = np.dot(np.linalg.inv(np.eye(len(S), dtype=S.dtype) - alpha * S), Y)
+    expected /= expected.sum(axis=1)[:, np.newaxis]
+
+    clf = label_propagation.LabelSpreading(
+        max_iter=100, alpha=alpha, tol=1e-10, gamma=gamma
+    )
+    clf.fit(X, y)
+
+    assert_allclose(expected, clf.label_distributions_)
+
+
+def test_label_propagation_closed_form(global_dtype):
+    n_classes = 2
+    X, y = make_classification(n_classes=n_classes, n_samples=200, random_state=0)
+    X = X.astype(global_dtype, copy=False)
+    y[::3] = -1
+    Y = np.zeros((len(y), n_classes + 1))
+    Y[np.arange(len(y)), y] = 1
+    unlabelled_idx = Y[:, (-1,)].nonzero()[0]
+    labelled_idx = (Y[:, (-1,)] == 0).nonzero()[0]
+
+    clf = label_propagation.LabelPropagation(max_iter=100, tol=1e-10, gamma=0.1)
+    clf.fit(X, y)
+    # adopting notation from Zhu et al 2002
+    T_bar = clf._build_graph()
+    Tuu = T_bar[tuple(np.meshgrid(unlabelled_idx, unlabelled_idx, indexing="ij"))]
+    Tul = T_bar[tuple(np.meshgrid(unlabelled_idx, labelled_idx, indexing="ij"))]
+    Y = Y[:, :-1]
+    Y_l = Y[labelled_idx, :]
+    Y_u = np.dot(np.dot(np.linalg.inv(np.eye(Tuu.shape[0]) - Tuu), Tul), Y_l)
+
+    expected = Y.copy()
+    expected[unlabelled_idx, :] = Y_u
+    expected /= expected.sum(axis=1)[:, np.newaxis]
+
+    assert_allclose(expected, clf.label_distributions_, atol=1e-4)
+
+
+@pytest.mark.parametrize("accepted_sparse_type", ["sparse_csr", "sparse_csc"])
+@pytest.mark.parametrize("index_dtype", [np.int32, np.int64])
+@pytest.mark.parametrize("dtype", [np.float32, np.float64])
+@pytest.mark.parametrize("Estimator, parameters", ESTIMATORS)
+def test_sparse_input_types(
+    accepted_sparse_type, index_dtype, dtype, Estimator, parameters
+):
+    # This is non-regression test for #17085
+    X = _convert_container([[1.0, 0.0], [0.0, 2.0], [1.0, 3.0]], accepted_sparse_type)
+    X.data = X.data.astype(dtype, copy=False)
+    X.indices = X.indices.astype(index_dtype, copy=False)
+    X.indptr = X.indptr.astype(index_dtype, copy=False)
+    labels = [0, 1, -1]
+    clf = Estimator(**parameters).fit(X, labels)
+    assert_array_equal(clf.predict([[0.5, 2.5]]), np.array([1]))
+
+
+@pytest.mark.parametrize("constructor_type", CONSTRUCTOR_TYPES)
+def test_convergence_speed(constructor_type):
+    # This is a non-regression test for #5774
+    X = _convert_container([[1.0, 0.0], [0.0, 1.0], [1.0, 2.5]], constructor_type)
+    y = np.array([0, 1, -1])
+    mdl = label_propagation.LabelSpreading(kernel="rbf", max_iter=5000)
+    mdl.fit(X, y)
+
+    # this should converge quickly:
+    assert mdl.n_iter_ < 10
+    assert_array_equal(mdl.predict(X), [0, 1, 1])
+
+
+def test_convergence_warning():
+    # This is a non-regression test for #5774
+    X = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 2.5]])
+    y = np.array([0, 1, -1])
+    mdl = label_propagation.LabelSpreading(kernel="rbf", max_iter=1)
+    warn_msg = "max_iter=1 was reached without convergence."
+    with pytest.warns(ConvergenceWarning, match=warn_msg):
+        mdl.fit(X, y)
+    assert mdl.n_iter_ == mdl.max_iter
+
+    mdl = label_propagation.LabelPropagation(kernel="rbf", max_iter=1)
+    with pytest.warns(ConvergenceWarning, match=warn_msg):
+        mdl.fit(X, y)
+    assert mdl.n_iter_ == mdl.max_iter
+
+    mdl = label_propagation.LabelSpreading(kernel="rbf", max_iter=500)
+    with warnings.catch_warnings():
+        warnings.simplefilter("error", ConvergenceWarning)
+        mdl.fit(X, y)
+
+    mdl = label_propagation.LabelPropagation(kernel="rbf", max_iter=500)
+    with warnings.catch_warnings():
+        warnings.simplefilter("error", ConvergenceWarning)
+        mdl.fit(X, y)
+
+
+@pytest.mark.parametrize(
+    "LabelPropagationCls",
+    [label_propagation.LabelSpreading, label_propagation.LabelPropagation],
+)
+def test_label_propagation_non_zero_normalizer(LabelPropagationCls):
+    # check that we don't divide by zero in case of null normalizer
+    # non-regression test for
+    # https://github.com/scikit-learn/scikit-learn/pull/15946
+    # https://github.com/scikit-learn/scikit-learn/issues/9292
+    X = np.array([[100.0, 100.0], [100.0, 100.0], [0.0, 0.0], [0.0, 0.0]])
+    y = np.array([0, 1, -1, -1])
+    mdl = LabelPropagationCls(kernel="knn", max_iter=100, n_neighbors=1)
+    with warnings.catch_warnings():
+        warnings.simplefilter("error", RuntimeWarning)
+        mdl.fit(X, y)
+
+
+def test_predict_sparse_callable_kernel(global_dtype):
+    # This is a non-regression test for #15866
+
+    # Custom sparse kernel (top-K RBF)
+    def topk_rbf(X, Y=None, n_neighbors=10, gamma=1e-5):
+        nn = NearestNeighbors(n_neighbors=10, metric="euclidean", n_jobs=2)
+        nn.fit(X)
+        W = -1 * nn.kneighbors_graph(Y, mode="distance").power(2) * gamma
+        np.exp(W.data, out=W.data)
+        assert issparse(W)
+        return W.T
+
+    n_classes = 4
+    n_samples = 500
+    n_test = 10
+    X, y = make_classification(
+        n_classes=n_classes,
+        n_samples=n_samples,
+        n_features=20,
+        n_informative=20,
+        n_redundant=0,
+        n_repeated=0,
+        random_state=0,
+    )
+    X = X.astype(global_dtype)
+
+    X_train, X_test, y_train, y_test = train_test_split(
+        X, y, test_size=n_test, random_state=0
+    )
+
+    model = label_propagation.LabelSpreading(kernel=topk_rbf)
+    model.fit(X_train, y_train)
+    assert model.score(X_test, y_test) >= 0.9
+
+    model = label_propagation.LabelPropagation(kernel=topk_rbf)
+    model.fit(X_train, y_train)
+    assert model.score(X_test, y_test) >= 0.9
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/semi_supervised/tests/test_self_training.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/semi_supervised/tests/test_self_training.py
new file mode 100644
index 0000000000000000000000000000000000000000..02244063994d573537d7194c2837f8e80ffad0c6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sklearn/semi_supervised/tests/test_self_training.py
@@ -0,0 +1,395 @@
+from math import ceil
+
+import numpy as np
+import pytest
+from numpy.testing import assert_array_equal
+
+from sklearn.datasets import load_iris, make_blobs
+from sklearn.ensemble import StackingClassifier
+from sklearn.exceptions import NotFittedError
+from sklearn.metrics import accuracy_score
+from sklearn.model_selection import train_test_split
+from sklearn.neighbors import KNeighborsClassifier
+from sklearn.semi_supervised import SelfTrainingClassifier
+from sklearn.svm import SVC
+from sklearn.tests.test_pipeline import SimpleEstimator
+from sklearn.tree import DecisionTreeClassifier
+
+# Authors: The scikit-learn developers
+# SPDX-License-Identifier: BSD-3-Clause
+
+# load the iris dataset and randomly permute it
+iris = load_iris()
+X_train, X_test, y_train, y_test = train_test_split(
+    iris.data, iris.target, random_state=0
+)
+
+n_labeled_samples = 50
+
+y_train_missing_labels = y_train.copy()
+y_train_missing_labels[n_labeled_samples:] = -1
+mapping = {0: "A", 1: "B", 2: "C", -1: "-1"}
+y_train_missing_strings = np.vectorize(mapping.get)(y_train_missing_labels).astype(
+    object
+)
+y_train_missing_strings[y_train_missing_labels == -1] = -1
+
+
+def test_warns_k_best():
+    st = SelfTrainingClassifier(KNeighborsClassifier(), criterion="k_best", k_best=1000)
+    with pytest.warns(UserWarning, match="k_best is larger than"):
+        st.fit(X_train, y_train_missing_labels)
+
+    assert st.termination_condition_ == "all_labeled"
+
+
+@pytest.mark.parametrize(
+    "estimator",
+    [KNeighborsClassifier(), SVC(gamma="scale", probability=True, random_state=0)],
+)
+@pytest.mark.parametrize("selection_crit", ["threshold", "k_best"])
+def test_classification(estimator, selection_crit):
+    # Check classification for various parameter settings.
+    # Also assert that predictions for strings and numerical labels are equal.
+    # Also test for multioutput classification
+    threshold = 0.75
+    max_iter = 10
+    st = SelfTrainingClassifier(
+        estimator, max_iter=max_iter, threshold=threshold, criterion=selection_crit
+    )
+    st.fit(X_train, y_train_missing_labels)
+    pred = st.predict(X_test)
+    proba = st.predict_proba(X_test)
+
+    st_string = SelfTrainingClassifier(
+        estimator, max_iter=max_iter, criterion=selection_crit, threshold=threshold
+    )
+    st_string.fit(X_train, y_train_missing_strings)
+    pred_string = st_string.predict(X_test)
+    proba_string = st_string.predict_proba(X_test)
+
+    assert_array_equal(np.vectorize(mapping.get)(pred), pred_string)
+    assert_array_equal(proba, proba_string)
+
+    assert st.termination_condition_ == st_string.termination_condition_
+    # Check consistency between labeled_iter, n_iter and max_iter
+    labeled = y_train_missing_labels != -1
+    # assert that labeled samples have labeled_iter = 0
+    assert_array_equal(st.labeled_iter_ == 0, labeled)
+    # assert that labeled samples do not change label during training
+    assert_array_equal(y_train_missing_labels[labeled], st.transduction_[labeled])
+
+    # assert that the max of the iterations is less than the total amount of
+    # iterations
+    assert np.max(st.labeled_iter_) <= st.n_iter_ <= max_iter
+    assert np.max(st_string.labeled_iter_) <= st_string.n_iter_ <= max_iter
+
+    # check shapes
+    assert st.labeled_iter_.shape == st.transduction_.shape
+    assert st_string.labeled_iter_.shape == st_string.transduction_.shape
+
+
+def test_k_best():
+    st = SelfTrainingClassifier(
+        KNeighborsClassifier(n_neighbors=1),
+        criterion="k_best",
+        k_best=10,
+        max_iter=None,
+    )
+    y_train_only_one_label = np.copy(y_train)
+    y_train_only_one_label[1:] = -1
+    n_samples = y_train.shape[0]
+
+    n_expected_iter = ceil((n_samples - 1) / 10)
+    st.fit(X_train, y_train_only_one_label)
+    assert st.n_iter_ == n_expected_iter
+
+    # Check labeled_iter_
+    assert np.sum(st.labeled_iter_ == 0) == 1
+    for i in range(1, n_expected_iter):
+        assert np.sum(st.labeled_iter_ == i) == 10
+    assert np.sum(st.labeled_iter_ == n_expected_iter) == (n_samples - 1) % 10
+    assert st.termination_condition_ == "all_labeled"
+
+
+def test_sanity_classification():
+    estimator = SVC(gamma="scale", probability=True)
+    estimator.fit(X_train[n_labeled_samples:], y_train[n_labeled_samples:])
+
+    st = SelfTrainingClassifier(estimator)
+    st.fit(X_train, y_train_missing_labels)
+
+    pred1, pred2 = estimator.predict(X_test), st.predict(X_test)
+    assert not np.array_equal(pred1, pred2)
+    score_supervised = accuracy_score(estimator.predict(X_test), y_test)
+    score_self_training = accuracy_score(st.predict(X_test), y_test)
+
+    assert score_self_training > score_supervised
+
+
+def test_none_iter():
+    # Check that the all samples were labeled after a 'reasonable' number of
+    # iterations.
+    st = SelfTrainingClassifier(KNeighborsClassifier(), threshold=0.55, max_iter=None)
+    st.fit(X_train, y_train_missing_labels)
+
+    assert st.n_iter_ < 10
+    assert st.termination_condition_ == "all_labeled"
+
+
+@pytest.mark.parametrize(
+    "estimator",
+    [KNeighborsClassifier(), SVC(gamma="scale", probability=True, random_state=0)],
+)
+@pytest.mark.parametrize("y", [y_train_missing_labels, y_train_missing_strings])
+def test_zero_iterations(estimator, y):
+    # Check classification for zero iterations.
+    # Fitting a SelfTrainingClassifier with zero iterations should give the
+    # same results as fitting a supervised classifier.
+    # This also asserts that string arrays work as expected.
+
+    clf1 = SelfTrainingClassifier(estimator, max_iter=0)
+
+    clf1.fit(X_train, y)
+
+    clf2 = estimator.fit(X_train[:n_labeled_samples], y[:n_labeled_samples])
+
+    assert_array_equal(clf1.predict(X_test), clf2.predict(X_test))
+    assert clf1.termination_condition_ == "max_iter"
+
+
+def test_prefitted_throws_error():
+    # Test that passing a pre-fitted classifier and calling predict throws an
+    # error
+    knn = KNeighborsClassifier()
+    knn.fit(X_train, y_train)
+    st = SelfTrainingClassifier(knn)
+    with pytest.raises(
+        NotFittedError,
+        match="This SelfTrainingClassifier instance is not fitted yet",
+    ):
+        st.predict(X_train)
+
+
+@pytest.mark.parametrize("max_iter", range(1, 5))
+def test_labeled_iter(max_iter):
+    # Check that the amount of datapoints labeled in iteration 0 is equal to
+    # the amount of labeled datapoints we passed.
+    st = SelfTrainingClassifier(KNeighborsClassifier(), max_iter=max_iter)
+
+    st.fit(X_train, y_train_missing_labels)
+    amount_iter_0 = len(st.labeled_iter_[st.labeled_iter_ == 0])
+    assert amount_iter_0 == n_labeled_samples
+    # Check that the max of the iterations is less than the total amount of
+    # iterations
+    assert np.max(st.labeled_iter_) <= st.n_iter_ <= max_iter
+
+
+def test_no_unlabeled():
+    # Test that training on a fully labeled dataset produces the same results
+    # as training the classifier by itself.
+    knn = KNeighborsClassifier()
+    knn.fit(X_train, y_train)
+    st = SelfTrainingClassifier(knn)
+    with pytest.warns(UserWarning, match="y contains no unlabeled samples"):
+        st.fit(X_train, y_train)
+    assert_array_equal(knn.predict(X_test), st.predict(X_test))
+    # Assert that all samples were labeled in iteration 0 (since there were no
+    # unlabeled samples).
+    assert np.all(st.labeled_iter_ == 0)
+    assert st.termination_condition_ == "all_labeled"
+
+
+def test_early_stopping():
+    svc = SVC(gamma="scale", probability=True)
+    st = SelfTrainingClassifier(svc)
+    X_train_easy = [[1], [0], [1], [0.5]]
+    y_train_easy = [1, 0, -1, -1]
+    # X = [[0.5]] cannot be predicted on with a high confidence, so training
+    # stops early
+    st.fit(X_train_easy, y_train_easy)
+    assert st.n_iter_ == 1
+    assert st.termination_condition_ == "no_change"
+
+
+def test_strings_dtype():
+    clf = SelfTrainingClassifier(KNeighborsClassifier())
+    X, y = make_blobs(n_samples=30, random_state=0, cluster_std=0.1)
+    labels_multiclass = ["one", "two", "three"]
+
+    y_strings = np.take(labels_multiclass, y)
+
+    with pytest.raises(ValueError, match="dtype"):
+        clf.fit(X, y_strings)
+
+
+@pytest.mark.parametrize("verbose", [True, False])
+def test_verbose(capsys, verbose):
+    clf = SelfTrainingClassifier(KNeighborsClassifier(), verbose=verbose)
+    clf.fit(X_train, y_train_missing_labels)
+
+    captured = capsys.readouterr()
+
+    if verbose:
+        assert "iteration" in captured.out
+    else:
+        assert "iteration" not in captured.out
+
+
+def test_verbose_k_best(capsys):
+    st = SelfTrainingClassifier(
+        KNeighborsClassifier(n_neighbors=1),
+        criterion="k_best",
+        k_best=10,
+        verbose=True,
+        max_iter=None,
+    )
+
+    y_train_only_one_label = np.copy(y_train)
+    y_train_only_one_label[1:] = -1
+    n_samples = y_train.shape[0]
+
+    n_expected_iter = ceil((n_samples - 1) / 10)
+    st.fit(X_train, y_train_only_one_label)
+
+    captured = capsys.readouterr()
+
+    msg = "End of iteration {}, added {} new labels."
+    for i in range(1, n_expected_iter):
+        assert msg.format(i, 10) in captured.out
+
+    assert msg.format(n_expected_iter, (n_samples - 1) % 10) in captured.out
+
+
+def test_k_best_selects_best():
+    # Tests that the labels added by st really are the 10 best labels.
+    svc = SVC(gamma="scale", probability=True, random_state=0)
+    st = SelfTrainingClassifier(svc, criterion="k_best", max_iter=1, k_best=10)
+    has_label = y_train_missing_labels != -1
+    st.fit(X_train, y_train_missing_labels)
+
+    got_label = ~has_label & (st.transduction_ != -1)
+
+    svc.fit(X_train[has_label], y_train_missing_labels[has_label])
+    pred = svc.predict_proba(X_train[~has_label])
+    max_proba = np.max(pred, axis=1)
+
+    most_confident_svc = X_train[~has_label][np.argsort(max_proba)[-10:]]
+    added_by_st = X_train[np.where(got_label)].tolist()
+
+    for row in most_confident_svc.tolist():
+        assert row in added_by_st
+
+
+def test_estimator_meta_estimator():
+    # Check that a meta-estimator relying on an estimator implementing
+    # `predict_proba` will work even if it does not expose this method before being
+    # fitted.
+    # Non-regression test for:
+    # https://github.com/scikit-learn/scikit-learn/issues/19119
+
+    estimator = StackingClassifier(
+        estimators=[
+            ("svc_1", SVC(probability=True)),
+            ("svc_2", SVC(probability=True)),
+        ],
+        final_estimator=SVC(probability=True),
+        cv=2,
+    )
+
+    assert hasattr(estimator, "predict_proba")
+    clf = SelfTrainingClassifier(estimator=estimator)
+    clf.fit(X_train, y_train_missing_labels)
+    clf.predict_proba(X_test)
+
+    estimator = StackingClassifier(
+        estimators=[
+            ("svc_1", SVC(probability=False)),
+            ("svc_2", SVC(probability=False)),
+        ],
+        final_estimator=SVC(probability=False),
+        cv=2,
+    )
+
+    assert not hasattr(estimator, "predict_proba")
+    clf = SelfTrainingClassifier(estimator=estimator)
+    with pytest.raises(AttributeError):
+        clf.fit(X_train, y_train_missing_labels)
+
+
+def test_self_training_estimator_attribute_error():
+    """Check that we raise the proper AttributeErrors when the `estimator`
+    does not implement the `predict_proba` method, which is called from within
+    `fit`, or `decision_function`, which is decorated with `available_if`.
+
+    Non-regression test for:
+    https://github.com/scikit-learn/scikit-learn/issues/28108
+    """
+    # `SVC` with `probability=False` does not implement 'predict_proba' that
+    # is required internally in `fit` of `SelfTrainingClassifier`. We expect
+    # an AttributeError to be raised.
+    estimator = SVC(probability=False, gamma="scale")
+    self_training = SelfTrainingClassifier(estimator)
+
+    with pytest.raises(AttributeError, match="has no attribute 'predict_proba'"):
+        self_training.fit(X_train, y_train_missing_labels)
+
+    # `DecisionTreeClassifier` does not implement 'decision_function' and
+    # should raise an AttributeError
+    self_training = SelfTrainingClassifier(estimator=DecisionTreeClassifier())
+
+    outer_msg = "This 'SelfTrainingClassifier' has no attribute 'decision_function'"
+    inner_msg = "'DecisionTreeClassifier' object has no attribute 'decision_function'"
+    with pytest.raises(AttributeError, match=outer_msg) as exec_info:
+        self_training.fit(X_train, y_train_missing_labels).decision_function(X_train)
+    assert isinstance(exec_info.value.__cause__, AttributeError)
+    assert inner_msg in str(exec_info.value.__cause__)
+
+
+# TODO(1.8): remove in 1.8
+def test_deprecation_warning_base_estimator():
+    warn_msg = "`base_estimator` has been deprecated in 1.6 and will be removed"
+    with pytest.warns(FutureWarning, match=warn_msg):
+        SelfTrainingClassifier(base_estimator=DecisionTreeClassifier()).fit(
+            X_train, y_train_missing_labels
+        )
+
+    error_msg = "You must pass an estimator to SelfTrainingClassifier"
+    with pytest.raises(ValueError, match=error_msg):
+        SelfTrainingClassifier().fit(X_train, y_train_missing_labels)
+
+    error_msg = "You must pass only one estimator to SelfTrainingClassifier."
+    with pytest.raises(ValueError, match=error_msg):
+        SelfTrainingClassifier(
+            base_estimator=DecisionTreeClassifier(), estimator=DecisionTreeClassifier()
+        ).fit(X_train, y_train_missing_labels)
+
+
+# Metadata routing tests
+# =================================================================
+
+
+@pytest.mark.filterwarnings("ignore:y contains no unlabeled samples:UserWarning")
+@pytest.mark.parametrize(
+    "method", ["decision_function", "predict_log_proba", "predict_proba", "predict"]
+)
+def test_routing_passed_metadata_not_supported(method):
+    """Test that the right error message is raised when metadata is passed while
+    not supported when `enable_metadata_routing=False`."""
+    est = SelfTrainingClassifier(estimator=SimpleEstimator())
+    with pytest.raises(
+        ValueError, match="is only supported if enable_metadata_routing=True"
+    ):
+        est.fit([[1], [1]], [1, 1], sample_weight=[1], prop="a")
+
+    est = SelfTrainingClassifier(estimator=SimpleEstimator())
+    with pytest.raises(
+        ValueError, match="is only supported if enable_metadata_routing=True"
+    ):
+        # make sure that the estimator thinks it is already fitted
+        est.fitted_params_ = True
+        getattr(est, method)([[1]], sample_weight=[1], prop="a")
+
+
+# End of routing tests
+# ====================
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/INSTALLER b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+uv
\ No newline at end of file
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/METADATA b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..5883009e816c08a2672bc24096295aa8b3252a51
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/METADATA
@@ -0,0 +1,319 @@
+Metadata-Version: 2.4
+Name: sympy
+Version: 1.14.0
+Summary: Computer algebra system (CAS) in Python
+Home-page: https://sympy.org
+Author: SymPy development team
+Author-email: sympy@googlegroups.com
+License: BSD
+Project-URL: Source, https://github.com/sympy/sympy
+Keywords: Math CAS
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Topic :: Scientific/Engineering
+Classifier: Topic :: Scientific/Engineering :: Mathematics
+Classifier: Topic :: Scientific/Engineering :: Physics
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Requires-Python: >=3.9
+Description-Content-Type: text/markdown
+License-File: LICENSE
+License-File: AUTHORS
+Requires-Dist: mpmath<1.4,>=1.1.0
+Provides-Extra: dev
+Requires-Dist: pytest>=7.1.0; extra == "dev"
+Requires-Dist: hypothesis>=6.70.0; extra == "dev"
+Dynamic: author
+Dynamic: author-email
+Dynamic: classifier
+Dynamic: description
+Dynamic: description-content-type
+Dynamic: home-page
+Dynamic: keywords
+Dynamic: license
+Dynamic: license-file
+Dynamic: project-url
+Dynamic: provides-extra
+Dynamic: requires-dist
+Dynamic: requires-python
+Dynamic: summary
+
+# SymPy
+
+[![pypi version](https://img.shields.io/pypi/v/sympy.svg)](https://pypi.python.org/pypi/sympy)
+[![Join the chat at https://gitter.im/sympy/sympy](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/sympy/sympy?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
+[![Zenodo Badge](https://zenodo.org/badge/18918/sympy/sympy.svg)](https://zenodo.org/badge/latestdoi/18918/sympy/sympy)
+[![Downloads](https://pepy.tech/badge/sympy/month)](https://pepy.tech/project/sympy)
+[![GitHub Issues](https://img.shields.io/badge/issue_tracking-github-blue.svg)](https://github.com/sympy/sympy/issues)
+[![Git Tutorial](https://img.shields.io/badge/PR-Welcome-%23FF8300.svg?)](https://git-scm.com/book/en/v2/GitHub-Contributing-to-a-Project)
+[![Powered by NumFocus](https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A)](https://numfocus.org)
+[![Commits since last release](https://img.shields.io/github/commits-since/sympy/sympy/latest.svg?longCache=true&style=flat-square&logo=git&logoColor=fff)](https://github.com/sympy/sympy/releases)
+
+[![SymPy Banner](https://github.com/sympy/sympy/raw/master/banner.svg)](https://sympy.org/)
+
+
+See the [AUTHORS](AUTHORS) file for the list of authors.
+
+And many more people helped on the SymPy mailing list, reported bugs,
+helped organize SymPy's participation in the Google Summer of Code, the
+Google Highly Open Participation Contest, Google Code-In, wrote and
+blogged about SymPy...
+
+License: New BSD License (see the [LICENSE](LICENSE) file for details) covers all
+files in the sympy repository unless stated otherwise.
+
+Our mailing list is at
+.
+
+We have a community chat at [Gitter](https://gitter.im/sympy/sympy). Feel
+free to ask us anything there. We have a very welcoming and helpful
+community.
+
+## Download
+
+The recommended installation method is through Anaconda,
+
+
+You can also get the latest version of SymPy from
+
+
+To get the git version do
+
+    $ git clone https://github.com/sympy/sympy.git
+
+For other options (tarballs, debs, etc.), see
+.
+
+## Documentation and Usage
+
+For in-depth instructions on installation and building the
+documentation, see the [SymPy Documentation Style Guide](https://docs.sympy.org/dev/documentation-style-guide.html).
+
+Everything is at:
+
+
+
+You can generate everything at the above site in your local copy of
+SymPy by:
+
+    $ cd doc
+    $ make html
+
+Then the docs will be in \_build/html. If
+you don't want to read that, here is a short usage:
+
+From this directory, start Python and:
+
+``` python
+>>> from sympy import Symbol, cos
+>>> x = Symbol('x')
+>>> e = 1/cos(x)
+>>> print(e.series(x, 0, 10))
+1 + x**2/2 + 5*x**4/24 + 61*x**6/720 + 277*x**8/8064 + O(x**10)
+```
+
+SymPy also comes with a console that is a simple wrapper around the
+classic python console (or IPython when available) that loads the SymPy
+namespace and executes some common commands for you.
+
+To start it, issue:
+
+    $ bin/isympy
+
+from this directory, if SymPy is not installed or simply:
+
+    $ isympy
+
+if SymPy is installed.
+
+## Installation
+
+To install SymPy using PyPI, run the following command:
+
+    $ pip install sympy
+
+To install SymPy using Anaconda, run the following command:
+
+    $ conda install -c anaconda sympy
+
+To install SymPy from GitHub source, first clone SymPy using `git`:
+
+    $ git clone https://github.com/sympy/sympy.git
+
+Then, in the `sympy` repository that you cloned, simply run:
+
+    $ pip install .
+
+See  for more information.
+
+## Contributing
+
+We welcome contributions from anyone, even if you are new to open
+source. Please read our [Introduction to Contributing](https://docs.sympy.org/dev/contributing/introduction-to-contributing.html)
+page and the [SymPy Documentation Style Guide](https://docs.sympy.org/dev/documentation-style-guide.html). If you
+are new and looking for some way to contribute, a good place to start is
+to look at the issues tagged [Easy to Fix](https://github.com/sympy/sympy/issues?q=is%3Aopen+is%3Aissue+label%3A%22Easy+to+Fix%22).
+
+Please note that all participants in this project are expected to follow
+our Code of Conduct. By participating in this project you agree to abide
+by its terms. See [CODE\_OF\_CONDUCT.md](CODE_OF_CONDUCT.md).
+
+## Tests
+
+To execute all tests, run:
+
+    $./setup.py test
+
+in the current directory.
+
+For the more fine-grained running of tests or doctests, use `bin/test`
+or respectively `bin/doctest`. The master branch is automatically tested
+by GitHub Actions.
+
+To test pull requests, use
+[sympy-bot](https://github.com/sympy/sympy-bot).
+
+## Regenerate Experimental LaTeX Parser/Lexer
+
+The parser and lexer were generated with the [ANTLR4](http://antlr4.org)
+toolchain in `sympy/parsing/latex/_antlr` and checked into the repo.
+Presently, most users should not need to regenerate these files, but
+if you plan to work on this feature, you will need the `antlr4`
+command-line tool (and you must ensure that it is in your `PATH`).
+One way to get it is:
+
+    $ conda install -c conda-forge antlr=4.11.1
+
+Alternatively, follow the instructions on the ANTLR website and download
+the `antlr-4.11.1-complete.jar`. Then export the `CLASSPATH` as instructed
+and instead of creating `antlr4` as an alias, make it an executable file
+with the following contents:
+``` bash
+#!/bin/bash
+java -jar /usr/local/lib/antlr-4.11.1-complete.jar "$@"
+```
+
+After making changes to `sympy/parsing/latex/LaTeX.g4`, run:
+
+    $ ./setup.py antlr
+
+## Clean
+
+To clean everything (thus getting the same tree as in the repository):
+
+    $ git clean -Xdf
+
+which will clear everything ignored by `.gitignore`, and:
+
+    $ git clean -df
+
+to clear all untracked files. You can revert the most recent changes in
+git with:
+
+    $ git reset --hard
+
+WARNING: The above commands will all clear changes you may have made,
+and you will lose them forever. Be sure to check things with `git
+status`, `git diff`, `git clean -Xn`, and `git clean -n` before doing any
+of those.
+
+## Bugs
+
+Our issue tracker is at . Please
+report any bugs that you find. Or, even better, fork the repository on
+GitHub and create a pull request. We welcome all changes, big or small,
+and we will help you make the pull request if you are new to git (just
+ask on our mailing list or Gitter Channel). If you further have any queries, you can find answers
+on Stack Overflow using the [sympy](https://stackoverflow.com/questions/tagged/sympy) tag.
+
+## Brief History
+
+SymPy was started by Ondřej Čertík in 2005, he wrote some code during
+the summer, then he wrote some more code during summer 2006. In February
+2007, Fabian Pedregosa joined the project and helped fix many things,
+contributed documentation, and made it alive again. 5 students (Mateusz
+Paprocki, Brian Jorgensen, Jason Gedge, Robert Schwarz, and Chris Wu)
+improved SymPy incredibly during summer 2007 as part of the Google
+Summer of Code. Pearu Peterson joined the development during the summer
+2007 and he has made SymPy much more competitive by rewriting the core
+from scratch, which has made it from 10x to 100x faster. Jurjen N.E. Bos
+has contributed pretty-printing and other patches. Fredrik Johansson has
+written mpmath and contributed a lot of patches.
+
+SymPy has participated in every Google Summer of Code since 2007. You
+can see  for
+full details. Each year has improved SymPy by bounds. Most of SymPy's
+development has come from Google Summer of Code students.
+
+In 2011, Ondřej Čertík stepped down as lead developer, with Aaron
+Meurer, who also started as a Google Summer of Code student, taking his
+place. Ondřej Čertík is still active in the community but is too busy
+with work and family to play a lead development role.
+
+Since then, a lot more people have joined the development and some
+people have also left. You can see the full list in doc/src/aboutus.rst,
+or online at:
+
+
+
+The git history goes back to 2007 when development moved from svn to hg.
+To see the history before that point, look at
+.
+
+You can use git to see the biggest developers. The command:
+
+    $ git shortlog -ns
+
+will show each developer, sorted by commits to the project. The command:
+
+    $ git shortlog -ns --since="1 year"
+
+will show the top developers from the last year.
+
+## Citation
+
+To cite SymPy in publications use
+
+> Meurer A, Smith CP, Paprocki M, Čertík O, Kirpichev SB, Rocklin M,
+> Kumar A, Ivanov S, Moore JK, Singh S, Rathnayake T, Vig S, Granger BE,
+> Muller RP, Bonazzi F, Gupta H, Vats S, Johansson F, Pedregosa F, Curry
+> MJ, Terrel AR, Roučka Š, Saboo A, Fernando I, Kulal S, Cimrman R,
+> Scopatz A. (2017) SymPy: symbolic computing in Python. *PeerJ Computer
+> Science* 3:e103 
+
+A BibTeX entry for LaTeX users is
+
+``` bibtex
+@article{10.7717/peerj-cs.103,
+ title = {SymPy: symbolic computing in Python},
+ author = {Meurer, Aaron and Smith, Christopher P. and Paprocki, Mateusz and \v{C}ert\'{i}k, Ond\v{r}ej and Kirpichev, Sergey B. and Rocklin, Matthew and Kumar, Amit and Ivanov, Sergiu and Moore, Jason K. and Singh, Sartaj and Rathnayake, Thilina and Vig, Sean and Granger, Brian E. and Muller, Richard P. and Bonazzi, Francesco and Gupta, Harsh and Vats, Shivam and Johansson, Fredrik and Pedregosa, Fabian and Curry, Matthew J. and Terrel, Andy R. and Rou\v{c}ka, \v{S}t\v{e}p\'{a}n and Saboo, Ashutosh and Fernando, Isuru and Kulal, Sumith and Cimrman, Robert and Scopatz, Anthony},
+ year = 2017,
+ month = Jan,
+ keywords = {Python, Computer algebra system, Symbolics},
+ abstract = {
+            SymPy is an open-source computer algebra system written in pure Python. It is built with a focus on extensibility and ease of use, through both interactive and programmatic applications. These characteristics have led SymPy to become a popular symbolic library for the scientific Python ecosystem. This paper presents the architecture of SymPy, a description of its features, and a discussion of select submodules. The supplementary material provides additional examples and further outlines details of the architecture and features of SymPy.
+         },
+ volume = 3,
+ pages = {e103},
+ journal = {PeerJ Computer Science},
+ issn = {2376-5992},
+ url = {https://doi.org/10.7717/peerj-cs.103},
+ doi = {10.7717/peerj-cs.103}
+}
+```
+
+SymPy is BSD licensed, so you are free to use it whatever you like, be
+it academic, commercial, creating forks or derivatives, as long as you
+copy the BSD statement if you redistribute it (see the LICENSE file for
+details). That said, although not required by the SymPy license, if it
+is convenient for you, please cite SymPy when using it in your work and
+also consider contributing all your changes back, so that we can
+incorporate it and all of us will benefit in the end.
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/RECORD b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..ea17ba584d9ee542c2096beb896e182f4dce0350
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/RECORD
@@ -0,0 +1,1573 @@
+../../../bin/isympy,sha256=ANyiYI4JjO3xcTueMNQNUS9u8Qo4oZMZ2QWdFhWvwKo,363
+../../../share/man/man1/isympy.1,sha256=9DZdSOIQLikrATHlbkdDZ04LBQigZDUE0_oCXBDvdBs,6659
+isympy.py,sha256=haEArczb_Ny-LyjOCwx2FNGal_S0Mo4d0deiWL2g_Gc,11220
+sympy-1.14.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
+sympy-1.14.0.dist-info/METADATA,sha256=t1bC-_1b4FrFvbDrymH1VhjzD2M-2S2IpWh0KTE6dZU,12816
+sympy-1.14.0.dist-info/RECORD,,
+sympy-1.14.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy-1.14.0.dist-info/WHEEL,sha256=SmOxYU7pzNKBqASvQJ7DjX3XGUF92lrGhMb3R6_iiqI,91
+sympy-1.14.0.dist-info/entry_points.txt,sha256=Sp-vLJom4PRlhGfY6RpUre7SjYm33JNq9NCwCGeW-fQ,39
+sympy-1.14.0.dist-info/licenses/AUTHORS,sha256=grEDhSGwaWxjyQsx7UoKLJxMFoccZIsVewfKRLbxj40,55779
+sympy-1.14.0.dist-info/licenses/LICENSE,sha256=B6XpgZ9ye0mGrSgpx6KaYyDUJXX3IOsk1xt_71c6AoY,7885
+sympy-1.14.0.dist-info/top_level.txt,sha256=elXb5xfjLdjgSSoQFk4_2Qu3lp2CIaglF9MQtfIoH7o,13
+sympy/__init__.py,sha256=TpR2NIuhBf6rKNgvW89s26Lj6E3m4Fm7_noTcowKSrA,29422
+sympy/abc.py,sha256=-RYLRKQ6SZMJGXDIAOP9UWPDAyvYH0zPbp9ZFg0YKBY,3764
+sympy/algebras/__init__.py,sha256=7PRGOW30nlMOTeUPR7iy8l5xGoE2yCBEfRbjqDKWOgU,62
+sympy/algebras/quaternion.py,sha256=i2Fkvjj14vA6GtXgcSkpDwVmIYc7T5zT1hw49sb__tM,47483
+sympy/algebras/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/algebras/tests/test_quaternion.py,sha256=un4I6IKE2v6YEfUsFBSY5N6qaZ0agn1puX0LElb1k4E,16809
+sympy/assumptions/__init__.py,sha256=PFS8djTqiNbGVMjg7PaPjEfwmjyZVfioXiRVzqqA3E0,550
+sympy/assumptions/ask.py,sha256=B2W8CW-9ynvYqfBX9_4qCLhCSwE0g_gUGqq7lM50wUk,19376
+sympy/assumptions/ask_generated.py,sha256=whNIU5tj2UkEGHPAfk-_89ahvVERs4npOB0JYVbIQJc,23558
+sympy/assumptions/assume.py,sha256=_gcFc4h_YGs9-tshoD0gmLl_RtPivDQWMWhWWLX9seo,14606
+sympy/assumptions/cnf.py,sha256=mfthFXL8Jhpn7Vgj1IfG5acFzfBgaV02xztQ7KpoLmg,12509
+sympy/assumptions/facts.py,sha256=fimPoHEyusSUr0uI4kiDb4mzxHjEBglvLQW0DGdNFAs,8391
+sympy/assumptions/handlers/__init__.py,sha256=lvjAfPdz0MDjTxjuzbBSGBco2OmpZRiGixSG0oaiZi0,330
+sympy/assumptions/handlers/calculus.py,sha256=WF3gysxZa2frvd1kHxdDN7xd0PwYemER8dWutfDN-w8,7799
+sympy/assumptions/handlers/common.py,sha256=xgUR3xHPNgGFkLGyMqLV_nUIfMsQJLP8p6boy8Rc6JI,4314
+sympy/assumptions/handlers/matrices.py,sha256=Gdauk2xk1hKPRr4i6RpvOMHtDnyVD34x1OyhL-Oh8Hc,22321
+sympy/assumptions/handlers/ntheory.py,sha256=lRhW2ceJPK0gNqR00NAwkEq1FBjtRrxz1u6WevjRvjc,7660
+sympy/assumptions/handlers/order.py,sha256=-NCLn8ab7Fo_UzZLZi7m3UwtYGN-XiU1qvJDhi5z7ZQ,12280
+sympy/assumptions/handlers/sets.py,sha256=9P8X6ucARJIJA3jG_gj736L71ZQi5hfLCKL--0_ifrw,25841
+sympy/assumptions/lra_satask.py,sha256=FlmiLERsj6J9w6vygwEEEn7pyGPnD0JkPEFEdoE7bfM,9563
+sympy/assumptions/predicates/__init__.py,sha256=q1C7iWpvdDymEUZNyzJvZLsLtgwSkYtCixME-fYyIDw,110
+sympy/assumptions/predicates/calculus.py,sha256=vFnlYVYZVd6D9OwA7-3bDK_Q0jf2iCZCZiMlWenw0Vg,1889
+sympy/assumptions/predicates/common.py,sha256=zpByACpa_tF0nVNB0J_rJehnXkHtkxhchn1DvkVVS-s,2279
+sympy/assumptions/predicates/matrices.py,sha256=X3vbkEf3zwJLyanEjf6ijYXuRfFfSv-yatl1tJ25wDk,12142
+sympy/assumptions/predicates/ntheory.py,sha256=wvFNFSf0S4egbY7REw0V0ANC03CuiRU9PLmdi16VfHo,2546
+sympy/assumptions/predicates/order.py,sha256=ez1UZ824KDtimLssUASCZHD_KEQmo8Pv-qofVLhZUrk,9511
+sympy/assumptions/predicates/sets.py,sha256=-bTVXa-X1-yfXlIKzMBW_JxIqueS5PdEwEzChzIne38,9238
+sympy/assumptions/refine.py,sha256=FNv5neAYJh-MgvnHDZ8-tjC9RIKcIxarVj5WiE4EnYg,11946
+sympy/assumptions/relation/__init__.py,sha256=t2tZNEIK7w-xXshRQIRL8tIyiNe1W5fMhN7QNRPnQFo,261
+sympy/assumptions/relation/binrel.py,sha256=3iwnSEE53-vRsPv-bOnjydgOkCpbB12FTFR_sQ3CwvE,6313
+sympy/assumptions/relation/equality.py,sha256=ZBnSFpctNeroYy1nvam0kzSJCNpsUR3SlBeqFcAMM0U,7148
+sympy/assumptions/satask.py,sha256=P3iprPjuOyhT5Fwr0hX61xTOcD98M_bzXSAV-pXYhN4,11745
+sympy/assumptions/sathandlers.py,sha256=jx8B0u_N73fMoVoLKIfmXMdtSLz7-ZIKhJrxYl84AJk,9418
+sympy/assumptions/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/assumptions/tests/test_assumptions_2.py,sha256=oNgIDOoW-GpBbXxbtw05SWnE8I7sGislYmB3MDogwB4,1070
+sympy/assumptions/tests/test_context.py,sha256=I5gES7AY9_vz1-CEaCchy4MXABtX85ncNkvoRuLskG8,1153
+sympy/assumptions/tests/test_matrices.py,sha256=nzSofuawc18hNe9Nj0dN_lTeDwa2KbPjt4K2rvb3xmw,12258
+sympy/assumptions/tests/test_query.py,sha256=ENB3XoNNi7j0p1_-j9Xd9C5YYpRbu1dcAQe46foV8cU,104495
+sympy/assumptions/tests/test_refine.py,sha256=bHxYUnCOEIzA1yPU3B2xbU9JZfhDv6RkmPm8esetisQ,8834
+sympy/assumptions/tests/test_rel_queries.py,sha256=fRn_IMMb942GfEH8CNk6z50YCyDlA_GMXv2xOVFdSdk,6677
+sympy/assumptions/tests/test_satask.py,sha256=IIqqIxzkLfANpTNBKEsCGCp3Bm8zmDnYd23woqKh9EE,15741
+sympy/assumptions/tests/test_sathandlers.py,sha256=jMCZQb3G6pVQ5MHaSTWV_0eULHaCF8Mowu12Ll72rgs,1842
+sympy/assumptions/tests/test_wrapper.py,sha256=iE32j83rrerCz85HHt2hTolgJkqb44KddfEpI3H1Fb8,1159
+sympy/assumptions/wrapper.py,sha256=7GXR39zPCCfV-pcs8ph9KRRwZF3i_T5Lzv156vKFf_I,5434
+sympy/benchmarks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/benchmarks/bench_discrete_log.py,sha256=CNchIJ5HFMPpNlVZh2vOU0GgQ3bse6hqyqDovpDHlKE,2473
+sympy/benchmarks/bench_meijerint.py,sha256=dSNdZhoc8a4h50wRtbOxLwpmgUiuMFpe6ytTLURcplY,11610
+sympy/benchmarks/bench_symbench.py,sha256=UMD3eYf_Poht0qxjdH2_axGwwON6cZo1Sp700Ci1M1M,2997
+sympy/calculus/__init__.py,sha256=IWDc6qPbEcWyTm9QM6V8vSAs-5OtGNijimykoWz3Clc,828
+sympy/calculus/accumulationbounds.py,sha256=4nJD5JzBarlB5l6yPpVADX3iDamnHVwsor_nQJw9CAM,28682
+sympy/calculus/euler.py,sha256=0QrHD9TYKlSZuO8drnU3bUFJrSu8v5SncqtkRSWLjGM,3436
+sympy/calculus/finite_diff.py,sha256=X7qZJ5GmHlHKokUUMFoaQqrqX2jLRq4b7W2G5aWntzM,17053
+sympy/calculus/singularities.py,sha256=wBQ7WiJ1amuZStBJ-iMTiIHJexjzJHHwrc0tU2XVT10,12184
+sympy/calculus/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/calculus/tests/test_accumulationbounds.py,sha256=a_Ry2nKX5WbhSe1Bk2k0W6-VWOpVTg0FnA9u8rNSIV4,11195
+sympy/calculus/tests/test_euler.py,sha256=YWpts4pWSiYEwRsi5DLQ16JgC9109-9NKZIL_IO6_Aw,2683
+sympy/calculus/tests/test_finite_diff.py,sha256=9mIvXB8DaxJh2gzmhwi5eE3eBRYTFxyqYG5uIUpYg2w,7670
+sympy/calculus/tests/test_singularities.py,sha256=Zj4WPkT-KlXo7TF3Ir3ug3IkS_qhnFBS7VXAMnIuCso,5272
+sympy/calculus/tests/test_util.py,sha256=IJIhgudR9dym1VRAdu33G2tfSDoexNdWdz-Pgf-kh4o,18557
+sympy/calculus/util.py,sha256=qBDTlb5VP-xJPfh2Ndz37zNMVpseXW4d77hxBCLX5AA,28880
+sympy/categories/__init__.py,sha256=XiKBVC6pbDED-OVtNlSH-fGB8dB_jWLqwCEO7wBTAyA,984
+sympy/categories/baseclasses.py,sha256=1Kn7PIegQCbF78s0rhf1Bx1mbxwfQcfQi6v-QqloSoE,31360
+sympy/categories/diagram_drawing.py,sha256=lfR29f6QX-rK-cCAom-2mRJ4xLyhi55ch91CyEPCXAQ,95173
+sympy/categories/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/categories/tests/test_baseclasses.py,sha256=SwD6QsfSlrEdpD2dbkcN62CPVIRP5SadjCplLrMAoa8,5767
+sympy/categories/tests/test_drawing.py,sha256=IELPpadmnQyQ2x5a5qHC8ioq5kfT1UnAl4h1vO3gbqg,27848
+sympy/codegen/__init__.py,sha256=sQcJsyLyoRh9ccOPhv2eZ-wHjQrArByOON9ndj-MYgQ,974
+sympy/codegen/abstract_nodes.py,sha256=TY4ecftqnym5viYInnb59zGPPFXdeSGQwi--xTz6Pvo,490
+sympy/codegen/algorithms.py,sha256=GEvnadOTZ3afVrbN5WE52OhCP8gzMII_AN4oHQxvEpo,6383
+sympy/codegen/approximations.py,sha256=r7zyShIWp40QngshFQwqKVKWcA5KmHmQcJarXVtOATQ,6448
+sympy/codegen/ast.py,sha256=R_JhC-uryx9NoJ1ISQU6fb3aV4aRL1SModmV_Dc2z2U,56788
+sympy/codegen/cfunctions.py,sha256=jrFWaRjrQnpHzu6-mwFtd6cRspK8Jo7B3RDo1AOoTLo,12331
+sympy/codegen/cnodes.py,sha256=lsqy-JeRvr9WCk2fwDiRqPhAMFk0snInF7WlAlk9-Zg,3409
+sympy/codegen/cutils.py,sha256=vlzMs8OkC5Bu4sIP-AF2mYf_tIo7Uo4r2DAI_LNhZzM,383
+sympy/codegen/cxxnodes.py,sha256=Om-EBfYduFF97tgXOF68rr8zYbngem9kBRm9SJiKLSM,342
+sympy/codegen/fnodes.py,sha256=mdOPkMVmjjNp22XfHscvx8uMtUxbUqTl66Wki7ORMa8,18936
+sympy/codegen/futils.py,sha256=k-mxMJKr_Q_afTy6NrKNl_N2XQLBmSdZAssO5hBonNY,1792
+sympy/codegen/matrix_nodes.py,sha256=0d3qXy2zaq3isyklE48lP7NP5LTF7SkLXMHMbweVGXU,2284
+sympy/codegen/numpy_nodes.py,sha256=H6FoBnarEuO7R1sbX8Qa9hK4jCju90R2qN66_-1N6Ug,4543
+sympy/codegen/pynodes.py,sha256=Neo1gFQ9kC31T-gH8TeeCaDDNaDe5deIP97MRZFgMHk,243
+sympy/codegen/pyutils.py,sha256=HfF6SP710Y7yExZcSesI0usVaDiWdEPEmMtyMD3JtOY,838
+sympy/codegen/rewriting.py,sha256=8JtiMFgv0sA7uGu2MUU7L3uzldGw5xG1ksuk4zh2ZDE,11585
+sympy/codegen/scipy_nodes.py,sha256=hYlxtGyTM0Z64Nazm1TeMZ3Y8dMsiD_HNhNvbU9eiQY,2508
+sympy/codegen/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/codegen/tests/test_abstract_nodes.py,sha256=a_GKf3FpeNN8zfMc-V8AaSrQtEI1oiLfJOco2VKiSKI,451
+sympy/codegen/tests/test_algorithms.py,sha256=lgl6w3d7WaT8LJrp716wWicxbgnR4hQk4alzBCdDrIw,6919
+sympy/codegen/tests/test_applications.py,sha256=RFWS7EoE3DytUrr4HzkPaXbOtnaStpzJalVKrY1rVRE,2277
+sympy/codegen/tests/test_approximations.py,sha256=SZpOUzahb_bJOceD0DLdmeiw-jN37OPmf5TRp1dyRgM,2035
+sympy/codegen/tests/test_ast.py,sha256=aAWk-yAVVNAmFMkyUlYBbVA8mPlTFqULOtmXMEi3LO8,21688
+sympy/codegen/tests/test_cfunctions.py,sha256=4jJM7dCLPbfEU3CB1ZUKGC1pRuRvjqZfDkFfYSkrzsY,5119
+sympy/codegen/tests/test_cnodes.py,sha256=FlI5XP39K3kC1QWKQ-QKkzNQw8TROjj5mKXJhK1UU2c,3039
+sympy/codegen/tests/test_cxxnodes.py,sha256=5OwN8D_ZtKN9z5uNeUwbUkyAGzNLrTgIKUlcRWmOSpE,366
+sympy/codegen/tests/test_fnodes.py,sha256=dKSw6w7i4Z8NHVDu_ug4V9Fa49CfnSX1FVahDIdNPgI,6650
+sympy/codegen/tests/test_matrix_nodes.py,sha256=CTMSwQkW0JHaMgHR9Lys8kDk5UgQidTl4VQhWI8gw7s,1896
+sympy/codegen/tests/test_numpy_nodes.py,sha256=tEeyF9vDmw-EyKnHV2dYM6MWGfA2I2fmf3kBsYxqad0,2199
+sympy/codegen/tests/test_pynodes.py,sha256=Gso18KKzSwA-1AHC55SgHPAfH1GrGUCGaN6QR7iuEO0,432
+sympy/codegen/tests/test_pyutils.py,sha256=yvqif7d6EpsnaBjP8XXjVo3wEENBxI6Vm01I1Wow-js,299
+sympy/codegen/tests/test_rewriting.py,sha256=ELPziNI3CsJ4VS7mUbk4QWyG_94FbgZCdBKieMN20Vc,15852
+sympy/codegen/tests/test_scipy_nodes.py,sha256=LBWpjTRfgWN5NLTchLZEp6m7IMtu7HbiKoztLc6KNGY,1495
+sympy/combinatorics/__init__.py,sha256=Dx9xakpHuTIgy4G8zVjAY6pTu8J9_K3d_jKPizRMdVo,1500
+sympy/combinatorics/coset_table.py,sha256=soppBd8i6UV-sppdOzykfNE8evMeclU4l1TwfL5UlXI,43296
+sympy/combinatorics/fp_groups.py,sha256=0iLx7mtwxn1kjYFysgAzILAdtlS9e1VWPtWnszubhd8,47779
+sympy/combinatorics/free_groups.py,sha256=gt33RoIByKDZNaf661ay4pQMilPPMPY4hFNGIKi2ho0,39740
+sympy/combinatorics/galois.py,sha256=cpd2iHaSdim5-3-cqvk58YP-AuS6CvJeCdUWpiOdIZI,17867
+sympy/combinatorics/generators.py,sha256=UAdv0bvqtN6i9bfFgB873g-A-zssc0ZoiHckDOEI0M0,7479
+sympy/combinatorics/graycode.py,sha256=xbtr8AaFYb4SMmwUi7mf7913U87jH-XEYF_3pGZfj0o,11207
+sympy/combinatorics/group_constructs.py,sha256=IKx12_yWJqEQ7g-oBuAWd5VRLbCOWyL0LG4PQu43BS8,2021
+sympy/combinatorics/group_numbers.py,sha256=eOiK0RyVHewiGiPXHihfM7MIKlAlg7AhGnBL4f1D54M,9163
+sympy/combinatorics/homomorphisms.py,sha256=dCpmPM3V2ReRuYDdXDfdMTU3pt7zkjKBkYSF6X2MfE8,18844
+sympy/combinatorics/named_groups.py,sha256=zd_C9epKDrMG0drafGUcHuuJJkcMaDt1Nf2ik4NXNq8,8378
+sympy/combinatorics/partitions.py,sha256=ZXqVmVNjmauhMeiTWtCCqOP38b9MJg7UlBdZa-7aICQ,20841
+sympy/combinatorics/pc_groups.py,sha256=5AwEeYQCMdYcybhlEykvJZqEYtJQLgYbRxAnNQeajfE,21414
+sympy/combinatorics/perm_groups.py,sha256=sf0FfxmJ5uWCwlvzRD5m5HHduG5qqHzh3Y0n1Dax5Yo,184825
+sympy/combinatorics/permutations.py,sha256=nQoc4YgTeoT80eHkqetTBUxwAQQW40US2AnR2u4-E_k,87737
+sympy/combinatorics/polyhedron.py,sha256=-1y5GhorUK62_gJpn4tXTLye7BcG0hAup74waDQ8y2I,35928
+sympy/combinatorics/prufer.py,sha256=yN6d4w_ZVXNFhBoevA84gor4Xb5ttG529xbVgHxzKDo,12061
+sympy/combinatorics/rewritingsystem.py,sha256=cT1JrAuKj9rWI3IhaHekYYt0rdG56pwFLg32pcGC9aI,17095
+sympy/combinatorics/rewritingsystem_fsm.py,sha256=CKGhLqyvxY0mlmy8_Hb4WzkSdWYPUaU2yZYhz-0iZ5w,2433
+sympy/combinatorics/schur_number.py,sha256=YdsyA7n_z9tyfRTSRfIjEjtnGo5EuDGBMUS09AQ2MxU,4437
+sympy/combinatorics/subsets.py,sha256=oxuExuGyFnvunkmktl-vBYiLbiN66A2Q2MyzwWfy46A,16047
+sympy/combinatorics/tensor_can.py,sha256=JywytVypkN6aWdCpeEYletMW4vxyUvU29RfKq9-Lu0c,40738
+sympy/combinatorics/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/combinatorics/tests/test_coset_table.py,sha256=cEUF0OH6SNhN_kh069wMsq6h4eSVqbDLghrg2r9Ht48,28474
+sympy/combinatorics/tests/test_fp_groups.py,sha256=C4rWnSJyk7L6uZnI-kAYvtbfFXxba0o1XjpOTkWr97s,10203
+sympy/combinatorics/tests/test_free_groups.py,sha256=g47dnRsNXVG9lFcqppJyrGryGIUCw9dRASkcMa4QujA,6411
+sympy/combinatorics/tests/test_galois.py,sha256=w35JRx8lmlXCdzUBNdocgATPYWBOEZ6LH-tAxOPwCQ8,2763
+sympy/combinatorics/tests/test_generators.py,sha256=6YpOp0i5PRGtySPNZseQ8mjSXbwpfGfz0hDB4kfk40Q,3567
+sympy/combinatorics/tests/test_graycode.py,sha256=pI4e7Y615d5Bmmxui6fdEeyca6j6KSD0YmeychV6ORk,2800
+sympy/combinatorics/tests/test_group_constructs.py,sha256=jJLwMdhuUalKv4Aql9SzV2utK8Ex-IYdMecggr95pi8,450
+sympy/combinatorics/tests/test_group_numbers.py,sha256=spHwsvjzEDXsdAFxkrQYOnioTgtWoVF5K7k7FbgMvfg,4149
+sympy/combinatorics/tests/test_homomorphisms.py,sha256=UwBj5loCuZAiuvmqy5VAbwhCQTph8o6BzTaGrH0rzB4,3745
+sympy/combinatorics/tests/test_named_groups.py,sha256=tsuDVGv4iHGEZ0BVR87_ENhyAfZvFIl0M6Dv_HX1VoY,1931
+sympy/combinatorics/tests/test_partitions.py,sha256=oppszKJLLSpcEzHgespIveSmEC3fDZ0qkus1k7MBt4E,4097
+sympy/combinatorics/tests/test_pc_groups.py,sha256=wfkY_ilpG0XWrhaWMVK6r7yWMeXfM8WNTyti5oE9bdk,2728
+sympy/combinatorics/tests/test_perm_groups.py,sha256=70_AedMpr-YxiYDHHjw6fjvmYW7-YoznEGwUeGtJo0E,41195
+sympy/combinatorics/tests/test_permutations.py,sha256=E8J-WLCW2z9hTyTJcm1dsFgFXh8YAesIppYsXRu5pAs,20189
+sympy/combinatorics/tests/test_polyhedron.py,sha256=3SWkFQKeF-p1QWP4Iu9NIA1oTxAFo1BLRrrLerBFAhw,4180
+sympy/combinatorics/tests/test_prufer.py,sha256=OTJp0NxjiVswWkOuCIlnGFU2Gw4noRsrPpUJtp2XhEs,2649
+sympy/combinatorics/tests/test_rewriting.py,sha256=3COHq74k6knt2rqE7hfd4ZP_6whf0Kg14tYxFmTtYrI,1787
+sympy/combinatorics/tests/test_schur_number.py,sha256=wg13uTumFltWIGbVg_PEr6nhXIru19UWitsEZiakoRI,1727
+sympy/combinatorics/tests/test_subsets.py,sha256=6pyhLYV5HuXvx63r-gGVHr8LSrGRXcpDudhFn9fBqX8,2635
+sympy/combinatorics/tests/test_tensor_can.py,sha256=olH5D5wwTBOkZXjtqvLO6RKbvCG9KoMVK4__wDe95N4,24676
+sympy/combinatorics/tests/test_testutil.py,sha256=NYEI8X2qLWf7Gv1O7UthOHUSyWpbNCRrGmG_vdyEgF8,1733
+sympy/combinatorics/tests/test_util.py,sha256=sOYMWHxlbM0mqalqA7jNrYMm8DKcf_GwL5YBjs96_C4,4499
+sympy/combinatorics/testutil.py,sha256=GNnqy0mb6yPMa3zpGEzz2p6uxY7VtobPtwUialhfYEQ,11142
+sympy/combinatorics/util.py,sha256=lkOaITBImqB9yyLvN8DU0G-vraw27cSx2XaPdAPVBhg,16296
+sympy/concrete/__init__.py,sha256=2HDmg3VyLgM_ZPw3XsGpkOClGiQnyTlUNHSwVTtizA0,144
+sympy/concrete/delta.py,sha256=38M0E24b6V-dn706WXnylM4DAvvyb6tFy7eRE4oR5Bo,9870
+sympy/concrete/expr_with_intlimits.py,sha256=vj4PjttB9xE5aUYu37R1A4_KtGgxcPa65jzjv8-krsc,11352
+sympy/concrete/expr_with_limits.py,sha256=dL5u-b_CzwghTWIhNsGc4md8jPWfhXOvna5Lig6XVr0,21834
+sympy/concrete/gosper.py,sha256=JUFbnOWSls8Xo0Zj198Xm4adopE-rAJjXv6M2q9x7us,5499
+sympy/concrete/guess.py,sha256=6EejdhNgqjMK7lVTXms8-_xGmmpI3vtliLW7-L2eaDM,17474
+sympy/concrete/products.py,sha256=I_aGMeKtSuFU07PGfZPHHTwS1WxDRNbnjedNC_m1k24,18456
+sympy/concrete/summations.py,sha256=D5n4x-fzqhgRwTIWpdN3Xun4I8u847tB7Dcex7lh7lI,55998
+sympy/concrete/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/concrete/tests/test_delta.py,sha256=uI7xjMx7JuVb3kkN7cLR6_pGsKS4Ulq22p-Z9oti5Jc,23869
+sympy/concrete/tests/test_gosper.py,sha256=ZHiZfYGCeCS9I-0oqN6sFbiYa-284GeFoGsNbhIWq4I,7987
+sympy/concrete/tests/test_guess.py,sha256=TPW6Hy11Po6VLZG_dx95x3sMBYl5kcQH8wjJ6TOtu-k,3370
+sympy/concrete/tests/test_products.py,sha256=caYc-xlEIrX9I_A-KPQdwp5oDprVJSbfcOaKg_qUnsM,14521
+sympy/concrete/tests/test_sums_products.py,sha256=rg0cSziPNgkvyehA0wCf-3jj8fSmNT7ECOOkiXWN64o,66390
+sympy/conftest.py,sha256=wvibr2FiWTlUcLTYAFEL8tSAKWPnv_Q6Cj4lARBCM0U,2775
+sympy/core/__init__.py,sha256=0L72TGngrIg2JknW3elaPSIDmkpPjWGNVfNk33wKXJ0,3123
+sympy/core/_print_helpers.py,sha256=GQo9dI_BvAJtYHVFFfmroNr0L8d71UeI-tU7SGJgctk,2388
+sympy/core/add.py,sha256=TddwsicZFR4yEtVTkZmkzFtn9ndAlhfad7vJiECr6o4,43407
+sympy/core/alphabets.py,sha256=vWBs2atOvfRK6Xfg6hc5IKiB7s_0sZIiVJpcCUJL0N4,266
+sympy/core/assumptions.py,sha256=8K9rhYtT-kqS7hmc9ltkYC-wujYT3pe0BaUJNrOr8fg,23595
+sympy/core/assumptions_generated.py,sha256=0TJKYIHSIFyQcVHZdIHZ19b7tqst_sY7iZwjKzcvZBM,42817
+sympy/core/backend.py,sha256=hF9cftjzB92QEcwimekj0gQ9CEMXTH-leH3l8QcguGo,5273
+sympy/core/basic.py,sha256=IzZvs7iIcMvV8_athdOBnIvBYJg38khuO2fAJtd7uTE,76789
+sympy/core/benchmarks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/core/benchmarks/bench_arit.py,sha256=gfrnvKSXLCaUoFFxMgJhnLUp7rG9Pa_YT7OKgOrPP8E,412
+sympy/core/benchmarks/bench_assumptions.py,sha256=evfZzTgOUUvvvlK0DRdDZQRqxIlGLfJYzKu8QDMxSks,177
+sympy/core/benchmarks/bench_basic.py,sha256=YF0tTJ_AN_Wz11qidzM4bIhlwEhEqVc-IGVGrUx6SaA,210
+sympy/core/benchmarks/bench_expand.py,sha256=xgQYQMwqgXJtKajM4JVhuL-7AW8TLY-vdBpO6uyMDoQ,427
+sympy/core/benchmarks/bench_numbers.py,sha256=_1yHSbYmxriiTTzKtxFh7kJm-rXPL6roGs8MW1E5-sg,1135
+sympy/core/benchmarks/bench_sympify.py,sha256=G5iGInhhbkkxSY2pS08BNG945m9m4eZlNT1aJutGt5M,138
+sympy/core/cache.py,sha256=AyG7kganyV0jVx-aNBEUFogqRLHQqqFn8xU3ZSfJoaM,6172
+sympy/core/compatibility.py,sha256=XQH7ezmRi6l3R23qMHN2wfA-YMRWbh2YYjPY7LRo3lo,1145
+sympy/core/containers.py,sha256=IA8PWQeCl78Pn_1WczoYUzOhBoT9X2hM3_hJ232gyKc,11411
+sympy/core/core.py,sha256=lX3Af31Qyff-gwPiAH-vijjuOzBFSuQtN06nUqIcSTQ,547
+sympy/core/coreerrors.py,sha256=imD9TCL-UEM5hrHcqGQbbfLeyZCSJMx6vB1NBQITQIQ,642
+sympy/core/decorators.py,sha256=NO3oe7yIO4q-6Vvy2vTpIAS8GGI-JHjEOEGeAv97voY,8759
+sympy/core/evalf.py,sha256=X0BinrUYeCKyHPHJQnu3FGASTUB8iz5dweVvqeArBrU,62089
+sympy/core/expr.py,sha256=HR_xzh6273FBmdfNbogGzkWoqaI_k_CeIOnpmyzwCrQ,143770
+sympy/core/exprtools.py,sha256=Ft7C1K2kD4_EdpRrGxii_WDub4pK_rYnLTdeVhlBoeo,51544
+sympy/core/facts.py,sha256=54pFKhJwEzU8LkO7rL25TwGjIb5y5CvZleHEy_TpD68,19546
+sympy/core/function.py,sha256=y0vEdXaUD8thP3XasZVkkogqXOGB0cs2JnfHEa4DNjQ,117102
+sympy/core/intfunc.py,sha256=TigJI9bvsb4aN0aZJgCzxIHlv_eh0rElWeTurier3yI,14219
+sympy/core/kind.py,sha256=9kQvtDxm-SSRGi-155XsBl_rs-oN_7dw7fNNT3mDu2Q,11540
+sympy/core/logic.py,sha256=Qbj2WUh5lS0GjxvtPaNmcQXz7mbWXuWj5ZNFZ-N-YPg,10827
+sympy/core/mod.py,sha256=XDfpth2r4AWc04oLqtDWwFuYRLzI0l0MhLMwGSMu99g,8363
+sympy/core/mul.py,sha256=rjCiyOqxMgUTWR8sAcmilRfQLup9wv8Ij7s7JIfUkVM,79201
+sympy/core/multidimensional.py,sha256=NWX1okybO_nZCl9IhIOE8QYalY1WoC0zlzsvBg_E1eE,4233
+sympy/core/numbers.py,sha256=WEkS1JJ9ov-n4hXvxwrH1NPikNlyBCjLN5v-jOZxvsw,136741
+sympy/core/operations.py,sha256=_wjhMX-MD6cyUNKCc9K_QxyxpeG4WQehdypo0Fp76GM,25828
+sympy/core/parameters.py,sha256=EoT2S3W1dS2-HoV6WN7szBexXvn5_w43e2JFouKuvkU,3854
+sympy/core/power.py,sha256=FJSYRf0S3pk1JGkVy3kdWWQENhmpVme-Pf9SS2Rc6SE,73244
+sympy/core/random.py,sha256=miFdVpNKfutbkpYiIOzG9kVNUm5GTk-_nnmQqUhVDZs,6647
+sympy/core/relational.py,sha256=htbGT0uvzoYD07Q6_hdT0iDDsns0NDI2aml0W8mtAgM,51896
+sympy/core/rules.py,sha256=AJuZztmYKZ_yUITLZB6rhZjDy6ROBCtajcYqPa50sjc,1496
+sympy/core/singleton.py,sha256=2Ueja8GJ-0-cvBzlqPwL9hB9eOtjrJFXV6mkDZO1Bp4,7115
+sympy/core/sorting.py,sha256=PoL2-MtVeuYTu-DISGlbvqW2mt787BmWfzrwV1ibavE,10827
+sympy/core/symbol.py,sha256=0xwgxT7ZfhPjq87glw2CQq5MtIEO-DOrAoXu7bHwWFo,29820
+sympy/core/sympify.py,sha256=1vWheH469HqICHrADMY_k4T4eDQlGORNjEh7Re4WbmE,20546
+sympy/core/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/core/tests/test_args.py,sha256=gsvYkFoqSWM0G8sjwBkwwNpT_9jc-io1SyDcchI3fA4,184252
+sympy/core/tests/test_arit.py,sha256=TH4b9Z_sMGWlYqiU5MqpY5LmhzYRJSTHWtTNIrYv7fk,78611
+sympy/core/tests/test_assumptions.py,sha256=MjJdF_ymVL6mtgQx-aSr_rsNNxaTi2pHFLjyaPCBq5Q,41573
+sympy/core/tests/test_basic.py,sha256=skFOWZRNqDujmQ8GAskWH7OYcsrO0miBdM92Gy01k0U,10230
+sympy/core/tests/test_cache.py,sha256=p6Ci75a_T-bBXE_5HVxRKla62uSay_0Vuf57gUuH6sI,2001
+sympy/core/tests/test_compatibility.py,sha256=7pvNUEGIcRrfWl3doqHlm3AdNkGlcChO69gos3Fk09A,240
+sympy/core/tests/test_complex.py,sha256=koNGFMt6UMmzahJADSja_eD24gr-GG5gGCtyDgCRtPI,21906
+sympy/core/tests/test_constructor_postprocessor.py,sha256=0d7vbVuKi3GCm3PKLtiNqv_Au7v6RYt1rzRdHiD08tM,2441
+sympy/core/tests/test_containers.py,sha256=ijteBC6cjqzejfxXZZIELZJfMrgTQa1n6AlxHGCEQJs,7432
+sympy/core/tests/test_count_ops.py,sha256=eIA2WvCuWKXVBJEGfWoJrn6WfUshX_NXttrrfyLbNnI,5665
+sympy/core/tests/test_diff.py,sha256=6j4Vk9UCNRv8Oyx_4iv1ePjocwBg7_-3ftrSJ8u0cPo,5421
+sympy/core/tests/test_equal.py,sha256=RoOJuu4kMe4Rkk7eNyVOJov5S1770YHiVAiziNIKd2o,1678
+sympy/core/tests/test_eval.py,sha256=o0kZn3oaMidVYdNjeZYtx4uUKBoE3A2tWn2NS4hu72Q,2366
+sympy/core/tests/test_evalf.py,sha256=aIf2xMuFomr828s4qv6Q16xLHWNmBnDfC4FUv9g619M,28574
+sympy/core/tests/test_expand.py,sha256=jbIjBEmdsPPArsxJ9206YzMS7mPUVZo7j-7alM795eU,13886
+sympy/core/tests/test_expr.py,sha256=249jMUV5GnkjmVVcgPSkwWvzrT00ppWeygkK_9RO6kc,78428
+sympy/core/tests/test_exprtools.py,sha256=L7fi319z1EeFag6pH8myqDQYQ32H193QLKMdqlxACsY,19021
+sympy/core/tests/test_facts.py,sha256=YEZMZ-116VFnFqJ48h9bQsF2flhiB65trnZvJsRSh_o,11579
+sympy/core/tests/test_function.py,sha256=_YRRGTDthS85Bq4zoLo8bHMHNESPLUZW-4_VQaClCLs,51450
+sympy/core/tests/test_kind.py,sha256=NLJbwCpugzlNbaSyUlbb6NHoT_9dHuoXj023EDQMrNI,2048
+sympy/core/tests/test_logic.py,sha256=_YKSIod6Q0oIz9lDs78UQQrv9LU-uKaztd7w8LWwuwY,5634
+sympy/core/tests/test_match.py,sha256=yjVNccCLutvov8Ru_p38Hl_HDS0ltdsWierSi54m5Ts,22714
+sympy/core/tests/test_multidimensional.py,sha256=Fr-lagme3lwLrBpdaWP7O7oPezhIatn5X8fYYs-8bN8,848
+sympy/core/tests/test_noncommutative.py,sha256=IkGPcvLO4ACVj5LMT2IUgyj68F1RBvMKbm01iqTOK04,4436
+sympy/core/tests/test_numbers.py,sha256=SvTVZUpMWfeGvaqyJUp4e9FYIO8lFJLcbRcmBNWO8m0,78001
+sympy/core/tests/test_operations.py,sha256=mRxftKlrxxrn3zS3UPwqkF6Nr15l5Cv6j3c2RJX46s4,2859
+sympy/core/tests/test_parameters.py,sha256=wO9D-LcMMEyf5u5-EmDwVeQ02YzYbYwtFFR_o-M4ybQ,3560
+sympy/core/tests/test_power.py,sha256=H7SFxpWVnF4vgpF95ad-Fo5xHhIvKhtZJuGBg0J2SAk,24862
+sympy/core/tests/test_priority.py,sha256=6QlWz52qWwOU0CknBb4KErs4R87jp4wH3hVSQNAgdVI,3252
+sympy/core/tests/test_random.py,sha256=H58NfH5BYeQ3RIscbDct6SZkHQVRJjichVUSuSrhvAU,1233
+sympy/core/tests/test_relational.py,sha256=7ne7GIG_i0uVT8FfpCJ4ixnuIyQoVy-PwJm3kYNWbKI,43525
+sympy/core/tests/test_rules.py,sha256=iwmMX7hxC_73CuX9BizeAci-cO4JDq-y1sicKBXEGA4,349
+sympy/core/tests/test_singleton.py,sha256=xLJJgXwmkbKhsot_qTs-o4dniMjHUh3_va0xsA5h-KA,3036
+sympy/core/tests/test_sorting.py,sha256=6BZKYqUedAR-jeHcIgsJelJHFWuougml2c1NNilxGZg,902
+sympy/core/tests/test_subs.py,sha256=7ITJFDplgWBRImkcHfjRdnHqaKgjTxWb4j4WoRysvR8,30106
+sympy/core/tests/test_symbol.py,sha256=zYhPWsdyQp7_NiLVthpoCB1RyP9pmJcNlTdTN2kMdfY,13043
+sympy/core/tests/test_sympify.py,sha256=FEOsRduYX3EqE9EhMILwE9wu6jDj_o2WU9XEZHsXFUo,28195
+sympy/core/tests/test_traversal.py,sha256=cmgvMW8G-LZ20ZXy-wg5Vz5ogI_oq2p2bJSwMy9IMF0,4311
+sympy/core/tests/test_truediv.py,sha256=RYfJX39-mNhekRE3sj5TGFZXKra4ML9vGvObsRYuD3k,854
+sympy/core/tests/test_var.py,sha256=hexP-0q2nN9h_dyhKLCuvqFXgLC9e_Hroni8Ldb16Ko,1594
+sympy/core/trace.py,sha256=9WC8p3OpBL6TdHmZWMDK9jaCG-16f4uZV2VptduVH98,348
+sympy/core/traversal.py,sha256=PP4HUp-2gtsoCtGZwqxpbqZ33vtoRX-yYTbIqOQiaR0,8860
+sympy/crypto/__init__.py,sha256=i8GcbScXhIPbMEe7uuMgXqh_cU2mZm2f6hspIgmW5uM,2158
+sympy/crypto/crypto.py,sha256=iAERU5Qf9GizEUMUyxTgTUBI0U9QpSkbRir2nvKIKUA,89685
+sympy/crypto/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/crypto/tests/test_crypto.py,sha256=gPsRBNNHwc4QDBjgT5tvWTCuC5IA5d4aZRTblxXjngk,19758
+sympy/diffgeom/__init__.py,sha256=cWj4N7AfNgrYcGIBexX-UrWxfd1bP9DTNqUmLWUJ9nA,991
+sympy/diffgeom/diffgeom.py,sha256=DgxgxP9B7NT-M1Hb1-1AwHYHBvXZk_Y6_MqZcGPsmOg,72274
+sympy/diffgeom/rn.py,sha256=kvgth6rNJWt94kzVospZwiH53C-s4VSiorktQNmMobQ,6264
+sympy/diffgeom/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/diffgeom/tests/test_class_structure.py,sha256=LbRyxhhp-NnnfJ2gTn1SdlgCBQn2rhyB7xApOgcd_rM,1048
+sympy/diffgeom/tests/test_diffgeom.py,sha256=3BepCr6ned-4C_3me4zScu06HXG9Qx_dBBxIpiXAvy4,14145
+sympy/diffgeom/tests/test_function_diffgeom_book.py,sha256=GwhUAiAPtUv5I9oghdElMhtc6KX184tySgLSpVHhT0Q,5254
+sympy/diffgeom/tests/test_hyperbolic_space.py,sha256=c4xQJ_bBS4xrMj3pfx1Ms3oC2_LwuJuNYXNZxs-cVG8,2598
+sympy/discrete/__init__.py,sha256=A_Seud0IRr2gPYlz6JMQZa3sBhRL3O7gVqhIvMRRvE0,772
+sympy/discrete/convolutions.py,sha256=9L2d2Rrn6jqGfV2lBxCV6LmcTNBZUuOIqP_fuMIzPzk,18341
+sympy/discrete/recurrences.py,sha256=FqU5QG4qNNLSVBqcpL7HtKa7rQOlmHMXDQRzHZ_P_s0,5124
+sympy/discrete/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/discrete/tests/test_convolutions.py,sha256=K4S9bA1E2tg0VcFQ8SYtlxjL6HB666RxD5rriTuAK4k,17856
+sympy/discrete/tests/test_recurrences.py,sha256=s5ZEZQ262gcnBLpCjJVmeKlTKQByRTQBrc-N9p_4W8c,3019
+sympy/discrete/tests/test_transforms.py,sha256=vEORFaPvxmPSsw0f4Z2hLEN1wD0FdyQOYHDEY9aVm5A,5546
+sympy/discrete/transforms.py,sha256=lf-n6IN881uCfTUAxPNjdUaSguiRbYW0omuR96vKNlE,11681
+sympy/external/__init__.py,sha256=C6s4654Elc_X-D9UgI2cUQWiQyGDt9LG3IKUc8qqzuo,578
+sympy/external/gmpy.py,sha256=89vXc1KD5TiQCTwlL-98r01KdqsOsJpzc8XN1R7TwM4,9768
+sympy/external/importtools.py,sha256=Q7tS2cdGZ9a4NI_1sgGuoVcSDv_rIk-Av0BpFTa6EzA,7671
+sympy/external/ntheory.py,sha256=jnm13KGII1p6X42T-u2jVoBxiOCXZ8XGxjzhCuWXthE,16555
+sympy/external/pythonmpq.py,sha256=DBQYdZsCUajqIjV5ECYpzpCSbe4RR9qr4D1x_ZTuZaY,11259
+sympy/external/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/external/tests/test_autowrap.py,sha256=nUWYeQd1QF-Ou4A63iWypsn6pJMi0uMLyba8aRCOhnM,9759
+sympy/external/tests/test_codegen.py,sha256=t991vYFfQC6loodk7Vp1oKTCklBn8SwY7qLshVVou4w,12598
+sympy/external/tests/test_gmpy.py,sha256=8ITpuWYeitCymWwuQLpOOVBmRb3CJsO5sbqiZcVDulE,397
+sympy/external/tests/test_importtools.py,sha256=KrfontKYv11UvpazQ0vS1qyhxIvgZrCOXh1JFeACjeo,1394
+sympy/external/tests/test_ntheory.py,sha256=BJWirDnX7Y7McBoXreMomGQx33YlAjiuBTYQQLhobLU,8881
+sympy/external/tests/test_numpy.py,sha256=tuEji5l6GqbNjv74T6a3e8LDzI2zKUaLzvfluNXOFE0,10291
+sympy/external/tests/test_pythonmpq.py,sha256=L_FdZmmk5N-VEivE_O_qZa98BZhT1WSxRfdmG817bA0,5797
+sympy/external/tests/test_scipy.py,sha256=CVaw7D0-6DORgg78Q6b35SNKn05PlKwWJuqXOuU-qdY,1172
+sympy/functions/__init__.py,sha256=-u5IzcQAPk9emytXfMK22EVXqpXUtSau3pQtevZYmFo,5565
+sympy/functions/combinatorial/__init__.py,sha256=WqXI3qU_TTJ7nJA8m3Z-7ZAYKoApT8f9Xs0u2bTwy_c,53
+sympy/functions/combinatorial/factorials.py,sha256=cYMN1Bz76XninzSxzdLYxTN7-Mt1mzfUcSWIU-qpYAw,39184
+sympy/functions/combinatorial/numbers.py,sha256=PcW4rvWQ66POd1FcL8SJav2iUmGv2Ip_Vbbp_3qYIAY,101088
+sympy/functions/combinatorial/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/functions/combinatorial/tests/test_comb_factorials.py,sha256=B59sfZxTUmKtnG62LW9sPn7HnRxFBP6x_rnbKqbaaZ0,26317
+sympy/functions/combinatorial/tests/test_comb_numbers.py,sha256=GWeIeb9zJo3WJr9NGW7VD-PmCIt13ce-VufICHs1-A8,47593
+sympy/functions/elementary/__init__.py,sha256=Fj8p5qE-Rr1lqAyHI0aSgC3RYX56O-gWwo6wu-eUQYA,50
+sympy/functions/elementary/_trigonometric_special.py,sha256=FvrgSXisxjXjyBC4-NLLya6q2YyTMNMAUqqYzuYl34g,7271
+sympy/functions/elementary/benchmarks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/functions/elementary/benchmarks/bench_exp.py,sha256=PFBYa9eMovH5XOFN5XTxWr1VDj1EBoKwn4mAtj-_DdM,185
+sympy/functions/elementary/complexes.py,sha256=HQm4ViBWN5OkCtJZQPdLdChTnmzbk4Cb2A--MUzTgUs,44168
+sympy/functions/elementary/exponential.py,sha256=GoDlUBPcmpRjYehRZOooF0bISSK_oxpJlkqaE_KNTeQ,42610
+sympy/functions/elementary/hyperbolic.py,sha256=zewRSHNzxyvSFD9sP9XBKX-evG6Rds4k9jAAcfmDbIk,69329
+sympy/functions/elementary/integers.py,sha256=Dc5Bq6ds85NJYWkfHJPJccUeVTxbhzVloTeMo5HGG98,22394
+sympy/functions/elementary/miscellaneous.py,sha256=cPpv71po3HCQGsWIHgcQEql6RNb4Y3RrL24ujgtdTIQ,27944
+sympy/functions/elementary/piecewise.py,sha256=Nv32I9lktMPHF3k0JpifbcgCgIz7CyQ8KwI_t1BaVsI,58285
+sympy/functions/elementary/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/functions/elementary/tests/test_complexes.py,sha256=BaPIrUSkoguP74x7uLSt9bA9kxmB58fJ4wgNtx5RnCg,34016
+sympy/functions/elementary/tests/test_exponential.py,sha256=ojjC0aafWaQegZVYV7bgxyvWAES_erpeYTb3R0m9V5I,29733
+sympy/functions/elementary/tests/test_hyperbolic.py,sha256=TBJZbiV-o9c2uVUqnkaRuHr5FdSGBOpqKK5_2bWg92s,56898
+sympy/functions/elementary/tests/test_integers.py,sha256=_QaECu3JQRQa9uPi10jXlu9AohvtLTKB4rSe920g0tY,23266
+sympy/functions/elementary/tests/test_interface.py,sha256=dW0aHvLR5UPyyXzBS-tgKrQIp-H6Vu8sKjlQrBQgtZ4,2513
+sympy/functions/elementary/tests/test_miscellaneous.py,sha256=eCL30UmsusBhjvqICQNmToa1aJTML8fXav1L1J6b7FU,17148
+sympy/functions/elementary/tests/test_piecewise.py,sha256=b1c0IMbXHDLjbi_ESs7fQhJiMaEro30GEu9XYreicYA,62876
+sympy/functions/elementary/tests/test_trigonometric.py,sha256=ebRorj-WThNp56qvZOAGkvgpvWFnIlB6kFZyV1gCii4,90340
+sympy/functions/elementary/trigonometric.py,sha256=b2mE2SpNj0LZM3AcipW0FrjturAi9ozijK3PhqyfCbM,115945
+sympy/functions/special/__init__.py,sha256=5pjIq_RVCMsuCe1b-FlwIty30KxoUowZYKLmpIT9KHQ,59
+sympy/functions/special/benchmarks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/functions/special/benchmarks/bench_special.py,sha256=wzAoKTccuEaG4xrEYTlYfIJuLi3kUTMTEJ9iA113Wog,164
+sympy/functions/special/bessel.py,sha256=r-jJETBLp8a4JOKV9dW5EWr_yvERL0HMn0su328bug8,68656
+sympy/functions/special/beta_functions.py,sha256=de-ypTWZEjvFkq9RgPq3ghGOvFOfPmb9JfUDAPKQoXk,12777
+sympy/functions/special/bsplines.py,sha256=q7iZSeEMlRrx5gpXOzlk4uSTPIollduNZuGwMHB6fRM,10060
+sympy/functions/special/delta_functions.py,sha256=jopb1BX803pZtDAtLmKfFqRVjo3mySekyC80Lu-sJkM,19887
+sympy/functions/special/elliptic_integrals.py,sha256=YpCU-xyTvrmBxdO7Rj2pNYDbS2-bGfCvCaOHon9nSq0,14921
+sympy/functions/special/error_functions.py,sha256=GvKrm5fVMpat0Iierh9UsxsTeQknJyiHgMrWS-e7fhw,79556
+sympy/functions/special/gamma_functions.py,sha256=gkPQdMNR7k5uY1vSUu6zzyoJKMoQZfC90YjLRcyft5c,42943
+sympy/functions/special/hyper.py,sha256=oqeAhFALAN_H6eS0Fs_axdfL9jIYQ-aRFGGgQky2HYk,38829
+sympy/functions/special/mathieu_functions.py,sha256=kFmt0RUA70vhGphI7lhwUsOQ7KIy8Y95DU6gGkVQU5Y,6620
+sympy/functions/special/polynomials.py,sha256=IdxRf8D1iFA-oYfLyTcUmsSCeuWja4h2ExNb8UShwxg,46753
+sympy/functions/special/singularity_functions.py,sha256=ounzMgFQiOW-e1Rb5y_dCSopJGegXMdkj-EpjrP8tzU,8346
+sympy/functions/special/spherical_harmonics.py,sha256=MNAJ4ABTy_EIZe2XSK_MZ1SPnk1OeDnJAtrICAst4yw,11018
+sympy/functions/special/tensor_functions.py,sha256=UNoDpLu1EBR-2tX_dLoRpKhN0Yhm-z_hh8EtW50dNSE,12303
+sympy/functions/special/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/functions/special/tests/test_bessel.py,sha256=c6OKhj4MCjv4kpDG7udueaCOLykblsKHMOyP4CdFToA,37373
+sympy/functions/special/tests/test_beta_functions.py,sha256=yxfgu-wmNEeMfaFABiDHYmuZpZup9FTp0ZYerlc6hhc,3786
+sympy/functions/special/tests/test_bsplines.py,sha256=6UYg7IqXTi8fcSOut8TEzNVkxIA4ff-CyG22qJnbIYA,7145
+sympy/functions/special/tests/test_delta_functions.py,sha256=8xhSWG4SLL86z1QKFfLk_3b--bCrxjvCaxHlODBVToE,7138
+sympy/functions/special/tests/test_elliptic_integrals.py,sha256=scu7KemJ7Q2nsRcZtckQNruuthI-vla9M1sDVkLcbKM,6991
+sympy/functions/special/tests/test_error_functions.py,sha256=TkhkIKiuRZS78-F4ZTt5rvr3hfknp654IEhmHhRXT48,33565
+sympy/functions/special/tests/test_gamma_functions.py,sha256=aveGPdG1X9OdlC6xpdZbSsJ3S4M4DaG2osyOhm1fAYo,29908
+sympy/functions/special/tests/test_hyper.py,sha256=SEnQ9TtyO_dSQRc94AHrbQai6Q7-tmRfDIh40gNE3FE,16694
+sympy/functions/special/tests/test_mathieu.py,sha256=pqoFbnC84NDL6EQkigFtx5OQ1RFYppckTjzsm9XT0PY,1282
+sympy/functions/special/tests/test_singularity_functions.py,sha256=GEXzHHeR5F0swrZzhF7pEGR0tk9Vp3Ve2c-sE4WSpsY,6249
+sympy/functions/special/tests/test_spec_polynomials.py,sha256=wuiZaR_LwaM8SlNuGl3B1p4eOHC_-zZVSXMPNfzKRB4,19561
+sympy/functions/special/tests/test_spherical_harmonics.py,sha256=pUFtFpNPBnJTdnqou0jniSchijyh1rdzKv8H24RT9FU,3850
+sympy/functions/special/tests/test_tensor_functions.py,sha256=bblSDkPABZ6N1j1Rb2Bb5TZIzZoK1D8ks3fHizi69ZI,5546
+sympy/functions/special/tests/test_zeta_functions.py,sha256=2r59_aC0QOXQsBNXqxsHPr2PkJExusI6qvSydZBPbfw,10474
+sympy/functions/special/zeta_functions.py,sha256=QPRYVp0-WKs02CUSQiRIJUWD4N_3PmqrOsk1MGzBUfU,24091
+sympy/galgebra.py,sha256=yEosUPSnhLp9a1NWXvpCLoU20J6TQ58XNIvw07POkVk,123
+sympy/geometry/__init__.py,sha256=BU2MiKm8qJyZJ_hz1qC-3nFJTPEcuvx4hYd02jHjqSM,1240
+sympy/geometry/curve.py,sha256=F7b6XrlhUZ0QWLDoZJVojWfC5LeyOU-69OTFnYAREg8,10170
+sympy/geometry/ellipse.py,sha256=So0gH9e-1Oh3HGzrXoLqANyP4lTTBfGHHVo5vCdbfdk,50305
+sympy/geometry/entity.py,sha256=fvHhtSb6RvE6v-8yMyCNvm0ekLPoO7EO9J8TEsGyQGU,20668
+sympy/geometry/exceptions.py,sha256=XtUMA44UTdrBWt771jegFC-TXsobhDiI-10TDH_WNFM,131
+sympy/geometry/line.py,sha256=Yw8ns_w8rn6FEak6MmfsdccgNNjMQHhodDik2UX7jJM,80397
+sympy/geometry/parabola.py,sha256=YhtQ9C5Yco_iSQ6ZYRs0lZBWHmDkcvKUr-Y8RghY3M8,10716
+sympy/geometry/plane.py,sha256=z3hjEf3ibO735DV0Mb4DVjvthYlDyiPfekCeePSCDMM,26770
+sympy/geometry/point.py,sha256=vQB40V1fvhZze3D_D54HlMSS8gXeMIWerd2hBozmPFA,36661
+sympy/geometry/polygon.py,sha256=aooJyJVwf6ZPuxStYgTc-2jNjVaM2YHSvpVY3XRjAuo,82027
+sympy/geometry/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/geometry/tests/test_curve.py,sha256=xL4uRWAal4mXZxuQhcs9QOhs6MheCbFNyH1asq_a2IQ,4479
+sympy/geometry/tests/test_ellipse.py,sha256=f-EorUkNl_cg63bDvm4Qrbe1PWrBaCCRg8jAmdIYBuU,26509
+sympy/geometry/tests/test_entity.py,sha256=KSsncs7afLpqUAYTs9b0VH1dt6FhPrX5rrj2rdLpBUo,3896
+sympy/geometry/tests/test_geometrysets.py,sha256=vvOWrFrJuNAFgbrVh1wPY94o-H-85FWlnIyyo2Kst9c,1911
+sympy/geometry/tests/test_line.py,sha256=fLWGfHQNC3YqjxtT7zQbP--Cu0mjcPwSBfji4DA7BP0,38054
+sympy/geometry/tests/test_parabola.py,sha256=kd0RU5sGOcfp6jgwgXMtvT2B6kG1-M3-iGOLnUJfZOw,6150
+sympy/geometry/tests/test_plane.py,sha256=QRcfoDsJtCtcvjFb18hBEHupycLgAT2OohF6GpNShyQ,12525
+sympy/geometry/tests/test_point.py,sha256=YKXQdlBTQWsIVf9l3G6iPMq0OqMTo8nZlibhJDsq_Ic,16410
+sympy/geometry/tests/test_polygon.py,sha256=4D0t98SELQF42dYR-CbFqDU5yJds0LAE2RE8xqEdqag,27602
+sympy/geometry/tests/test_util.py,sha256=sbh1QvkQG1OqvE-kt4fNNIkMWnOFi5EpaBmnZS3pzNc,7044
+sympy/geometry/util.py,sha256=zF6Xx0ciab6Rxm4ekK5RawWXPWAk5oug8eDvgfNKoRc,20671
+sympy/holonomic/__init__.py,sha256=BgHIokaSOo3nwJlGO_caJHz37n6yoA8GeM9Xjn4zMpc,784
+sympy/holonomic/holonomic.py,sha256=vP5XabVIezsAURbK65p8P_QfPINQwhol0d62B7Br3s0,91887
+sympy/holonomic/holonomicerrors.py,sha256=qDyUoGbrRjPtVax4SeEEf_o6-264mASEZO_rZETXH5o,1193
+sympy/holonomic/numerical.py,sha256=MlP8xTBqjVQqM1-jwviS_yPICKj6tEVsa9f6wyMCSfo,2625
+sympy/holonomic/recurrence.py,sha256=HWSMokhjcdGTLW_oku0Xi8W8RHxWYS28bv8V7eubC58,10377
+sympy/holonomic/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/holonomic/tests/test_holonomic.py,sha256=NuoJtJi3RlpMYhMU_bGH1tuFuFoOZZrrSdMpgdHGhf0,35333
+sympy/holonomic/tests/test_recurrence.py,sha256=qHv0kn1Q4-aCD7XmbDK2xIdkjF0XkeZUKD2yeLajiq0,1342
+sympy/integrals/__init__.py,sha256=pZ-C3tDP_8woKActNoS7IwyW-9AuB5PMHB5B0ohlpw8,1970
+sympy/integrals/benchmarks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/integrals/benchmarks/bench_integrate.py,sha256=vk6wAO1bqzFT9oW4qsW7nKGfc_gP0XaB5PMYKx5339Q,396
+sympy/integrals/benchmarks/bench_trigintegrate.py,sha256=8XU3uB3mcavigvzHQZA7H1sHI32zgT-9RkSnLa-Y3Vc,305
+sympy/integrals/deltafunctions.py,sha256=ysIQLdRBcG_YR-bVDoxt-sxEVU8TG77oSgM-J0gI0mE,7435
+sympy/integrals/heurisch.py,sha256=Huq3dBJEXvYGzkBboXnG6xFCGorc5Uftf5ssbiltyIs,26706
+sympy/integrals/integrals.py,sha256=DV_ditazAyVBpUCzsUFNiYvvQRqJfx3UGjnSEB2HKcg,64887
+sympy/integrals/intpoly.py,sha256=SXjd_f295YrYsvoQpzE2EQM5xaQnnj0zvHdYW5KEdn0,43266
+sympy/integrals/laplace.py,sha256=y5NxZ3_nNtc-NETYWw4iha7LTVM9Ok9NWPtmMUXtZwg,87038
+sympy/integrals/manualintegrate.py,sha256=sO_5-9pbeRKhZSuEwXm6okxpvRsbpQZerbLBdRdDtp4,75721
+sympy/integrals/meijerint.py,sha256=yOsrHJA7doo1uDsmsiTqK2Tly4JF30sA5RElT92lfec,80775
+sympy/integrals/meijerint_doc.py,sha256=Sis9bZvwciU2_BZzr3GCvXLkBcXVUhP9ycqGIDu99xU,1204
+sympy/integrals/prde.py,sha256=3VqBQOX7SZv_lETmhoVgb9gRjb1z8hiZAJ6vv5AgNEo,52073
+sympy/integrals/quadrature.py,sha256=6Bg3JmlIjIduIfaGfNVcwNfSrgEiLOszcN8WPzsXNqE,17064
+sympy/integrals/rationaltools.py,sha256=ZAizq9unSt-_wQkCIAhl_FaemzbQcfBcE9A3mDiU788,11694
+sympy/integrals/rde.py,sha256=EKXK6bf4m-2O0NZ-rtHq0Ye2a_o9LmUrkoV8gNxZKVk,27393
+sympy/integrals/risch.py,sha256=4UsTHizZtAMe3VUmRHugdOuPMilw8sKiVOlSUMWj9oE,67352
+sympy/integrals/singularityfunctions.py,sha256=ONI8x-ed-IcqOF4K2l0LVUvEUN2_dHztvL4auRsi67U,2235
+sympy/integrals/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/integrals/tests/test_deltafunctions.py,sha256=ivFjS-WlLQ4aMqjVS7ZzMChP2Mmw_JUPnwI9otiLnvs,3709
+sympy/integrals/tests/test_failing_integrals.py,sha256=HKMA6O26exCIRWQ43KyKugOvJL3gOei3r9JObcKo8p0,7438
+sympy/integrals/tests/test_heurisch.py,sha256=-btpZS_LI9EO-2EmA0eHV6l7xykQjkHIcpDU_GziTlo,14299
+sympy/integrals/tests/test_integrals.py,sha256=8bVIN4ztTwOvpLrlDIk1SURQMtiNXoqu-LLMkZp-Wrk,81192
+sympy/integrals/tests/test_intpoly.py,sha256=NzGhkR2pUMfd8lIU2cFR9bFa0J89RzpHs3zDggAWtXo,37445
+sympy/integrals/tests/test_laplace.py,sha256=pWn5UEm15gJv_hD35lvJh03Uuw4o79rbCQYvbXQS2xk,38186
+sympy/integrals/tests/test_lineintegrals.py,sha256=zcPJ2n7DYt9KsgAe38t0gq3ARApUlb-kBahLThuRcq8,450
+sympy/integrals/tests/test_manual.py,sha256=unQ6Ew81SCHvVMva_aAOndh7hWpLeDwBtXs6W-yC0jE,34551
+sympy/integrals/tests/test_meijerint.py,sha256=G22dppQGMFU3JGexHZs65nce8UAK9wTilZn0D1XvZu0,32594
+sympy/integrals/tests/test_prde.py,sha256=2BZmEDasdx_3l64-9hioArysDj6Nl520GpQN2xnEE_A,16360
+sympy/integrals/tests/test_quadrature.py,sha256=iFMdqck36gkL-yksLflawIOYmw-0PzO2tFj_qdK6Hjg,19919
+sympy/integrals/tests/test_rationaltools.py,sha256=7QiPnpBXl7lo32RmhXo7ED6FYj5I1gjEFOziJYlqPtI,5669
+sympy/integrals/tests/test_rde.py,sha256=4d3vJupa-hRN4yNDISY8IC3rSI_cZW5BbtxoZm14y-Y,9571
+sympy/integrals/tests/test_risch.py,sha256=HaWg0JnErdrNzNmVfyz2Zz4XAgZPVVpZPt6Map3sQ58,38630
+sympy/integrals/tests/test_singularityfunctions.py,sha256=CSrHie59_NjNZ9B2GaHzKPNsMzxm5Kh6GuxlYk8zTuI,1266
+sympy/integrals/tests/test_transforms.py,sha256=mLl5RfuENf11oenV1OXgg6TfWdQTEY23txiGl7grCyo,27152
+sympy/integrals/tests/test_trigonometry.py,sha256=moMYr_Prc7gaYPjBK0McLjRpTEes2veUlN0vGv9UyEA,3869
+sympy/integrals/transforms.py,sha256=_rwRkrOnV4zby27MZJ9dpJrtQFG4gTbL7naLpFLXKDo,51750
+sympy/integrals/trigonometry.py,sha256=iOoBDGFDZx8PNbgL3XeZEd80I8ro0WAizNuC4P-u8x0,11083
+sympy/interactive/__init__.py,sha256=yokwEO2HF3eN2Xu65JSpUUsN4iYmPvvU4m_64f3Q33o,251
+sympy/interactive/printing.py,sha256=EZBO3YCga2dXBI1EfFHVDmUKBkF9UmrLMgwI76B0nyE,21562
+sympy/interactive/session.py,sha256=sG546e0mAtT0OrFkYNVM7QGvkWrDhAQZ5E1hfx03iBQ,15329
+sympy/interactive/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/interactive/tests/test_interactive.py,sha256=Pbopy9lODrd_P46_xxlWxLwqPfG6_4J3CWWC4IqfDL4,485
+sympy/interactive/tests/test_ipython.py,sha256=QZUvr77TxJHjdgQVNpihAuoglg1ghVHOTDFOVXJ9pcE,11797
+sympy/interactive/traversal.py,sha256=XbccdO6msNAvrG6FFJl2n4XmIiRISnvda4QflfEPg7U,3189
+sympy/liealgebras/__init__.py,sha256=K8tw7JqG33_y6mYl1LTr8ZNtKH5L21BqkjCHfLhP4aA,79
+sympy/liealgebras/cartan_matrix.py,sha256=yr2LoZi_Gxmu-EMKgFuPOPNMYPOsxucLAS6oRpSYi2U,524
+sympy/liealgebras/cartan_type.py,sha256=xLklg8Y5s40je6sXwmLmG9iyYi9YEk9KoxTSFz1GtdI,1790
+sympy/liealgebras/dynkin_diagram.py,sha256=ZzGuBGNOJ3lPDdJDs4n8hvGbz6wLhC5mwb8zFkDmyPw,535
+sympy/liealgebras/root_system.py,sha256=n1TKAZyWDPSlUDmjAga9Sa2Cm9qeRXddYPbl2XKyFq4,6673
+sympy/liealgebras/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/liealgebras/tests/test_cartan_matrix.py,sha256=KCsakn0fHKHRbIUcrUkHBIKkudl3_ISUdHrfJy-UOd4,303
+sympy/liealgebras/tests/test_cartan_type.py,sha256=t5PvYYDXbNIFL3CV59Je7SBIAeLLf-W3mOINPUoHK6E,339
+sympy/liealgebras/tests/test_dynkin_diagram.py,sha256=DSixbnt_yd0zrhKzXW_XqkXWXYe1Dk2MmXN-Rjb1dGg,260
+sympy/liealgebras/tests/test_root_system.py,sha256=YmGBdUeJ4PkLSfAfRgTF7GW62RCEd5nH27FSX9UaG5Q,927
+sympy/liealgebras/tests/test_type_A.py,sha256=x7QmpjxsGmXol-IYVtN1lmIOmM3HLYwpX1tSG5h6FMM,657
+sympy/liealgebras/tests/test_type_B.py,sha256=Gw0GP24wP2rPn38Wwla9W7BwWH4JtCGpaprZb5W6JVY,642
+sympy/liealgebras/tests/test_type_C.py,sha256=ysSy-vzE9lNwzAunrmvnFkLBoJwF7W2On7QpqS6RI1s,927
+sympy/liealgebras/tests/test_type_D.py,sha256=qrO4oCjrjkp1uDvrNtbgANVyaOExqOLNtIpIxD1uH0U,764
+sympy/liealgebras/tests/test_type_E.py,sha256=IQ46Bo75Kivz0O45mNKNvDO8jen7X2NwxVBTwvr5lQo,987
+sympy/liealgebras/tests/test_type_F.py,sha256=yUQJ7LzTemv4Cd1XW_dr3x7KEI07BahsWAyJfXLS1eA,1378
+sympy/liealgebras/tests/test_type_G.py,sha256=wVa6qcAHbdrc9dA63samexHL35cWWJS606pom-6mH2Q,548
+sympy/liealgebras/tests/test_weyl_group.py,sha256=HrzojRECbhNUsdLFQAXYnJEt8LfktOSJZuqVE45aRnc,1501
+sympy/liealgebras/type_a.py,sha256=Etn_aeyE5FdYrUXrGnjNiTL5k4r5-O_CysaO-_UKASA,4294
+sympy/liealgebras/type_b.py,sha256=ERH1aM38eHZUuTJYRsWLKFDm74G4y1MQtweSfkDFQYc,4547
+sympy/liealgebras/type_c.py,sha256=Al1pA5cw5IKjvBzx9LdMORd5-JZXgA0kaMv8aHhnYJ0,4426
+sympy/liealgebras/type_d.py,sha256=Cagn4GXrYuUP32W6jauIPnEv8IcD3H88sbn0fKS7pmU,4681
+sympy/liealgebras/type_e.py,sha256=KR84bp4Ga7d9itKRCsD3AYrarVewGiNNe7AHWNUfTAM,8280
+sympy/liealgebras/type_f.py,sha256=gIyk4zA04uIpwizcYdvKsZ_xkcpPLId6LIHR6tp38dk,4423
+sympy/liealgebras/type_g.py,sha256=Ife98dGPtarGd-ii8hJbXdB0SMsct4okDkSX2wLN8XI,2965
+sympy/liealgebras/weyl_group.py,sha256=5YFA8qC4GWDM0WLNR_6VgpuNFZDfyDA7fBFjBcZaLgA,14557
+sympy/logic/__init__.py,sha256=RfoXrq9MESnXdL7PkwpYEfWeaxH6wBPHiE4zCgLKvk0,456
+sympy/logic/algorithms/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/logic/algorithms/dpll.py,sha256=zqiZDm1oD5sNxFqm_0Hen6NjfILIDp5uRgEOad1vYXI,9188
+sympy/logic/algorithms/dpll2.py,sha256=PEVvFUrEf-IwTwfnTYtAFLPLPjjqA1nmm39nASgsM1I,21497
+sympy/logic/algorithms/lra_theory.py,sha256=6JZAZMJhhHSbUXZuc0ddYwp_x7efVuthIYV7Dc9eUyc,31769
+sympy/logic/algorithms/minisat22_wrapper.py,sha256=uINcvkIHGWYJb8u-Q0OgnSgaHfVUd9tYYFbBAVNiASo,1317
+sympy/logic/algorithms/pycosat_wrapper.py,sha256=0vNFTbu9-YhSfjwYTsZsP_Z4HM8WpL11-xujLBS1kYg,1207
+sympy/logic/algorithms/z3_wrapper.py,sha256=mFmf7DWDV0Zu7006EdFK4qEDTP7sfmcXrfGZkMK97vo,3747
+sympy/logic/boolalg.py,sha256=GqxLtqUangGoSjsncKDzlLEE7iYVe5qsMtPhztniI9c,114972
+sympy/logic/inference.py,sha256=J2D8t9iHCSdotzS9iq6g3EvLPsI2B10kiNbmHsIz_oY,8983
+sympy/logic/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/logic/tests/test_boolalg.py,sha256=0ZjG56WpIhIwFLedUzg5IC-c0VF_g9qoU9aAbFydPYU,49748
+sympy/logic/tests/test_dimacs.py,sha256=EK_mA_k9zBLcQLTOKTZVrGhnGuQNza5mwXDQD_f-X1c,3886
+sympy/logic/tests/test_inference.py,sha256=9BXfPbJs6sBEgx1nwkmg2HcLl82lcfFXngKJL_ByzUI,16116
+sympy/logic/tests/test_lra_theory.py,sha256=hNCH66hP_32x5ioyqM6ltd0DbEl72kdctCBu-H6egG0,16834
+sympy/logic/utilities/__init__.py,sha256=WTn2vBgHcmhONRWI79PdMYNk8UxYDzsxRlZWuc-wtNI,55
+sympy/logic/utilities/dimacs.py,sha256=gfrGWQpn4F7gLJH1zHAnLB8-CMGa1XtXl9NCGhwAW9k,1671
+sympy/matrices/__init__.py,sha256=i2a37WlcCj8-AKG_Yy8BBdOHFgAuWois_2IcD_Ih00s,2634
+sympy/matrices/benchmarks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/matrices/benchmarks/bench_matrix.py,sha256=vGMlg-2il2cFeAWrf0NJ6pzPX3Yd3ZQMxFgQ4q5ILQE,306
+sympy/matrices/common.py,sha256=v_jMjH9t6mrHl7Z5QluhO-G07QUaJSdiioF2YC1xlhY,95395
+sympy/matrices/decompositions.py,sha256=5OjwFe5Z_eM2XoZPqrNFY9-Esq3cO_8yqFxT9QBPHgQ,47865
+sympy/matrices/dense.py,sha256=HTPNMKbi2M0W0nHImNtHib9JM5VC8si99ldL_FylKwQ,30461
+sympy/matrices/determinant.py,sha256=pDTDYCLBSWJov_j_B-ZZHdqH3-WQ_uwhZawrX3EDE9k,34550
+sympy/matrices/eigen.py,sha256=v09mqb2hZ0HqGbGzYpELOatIHnGTP5XADE-1RGcua-g,39811
+sympy/matrices/exceptions.py,sha256=8diN_ojMGC93XpqvZeS5ow4crlFxSkm6WqtnIK5j81E,503
+sympy/matrices/expressions/__init__.py,sha256=IMqXCSsPh0Vp_MC9HZTudA5DGM4WBq_yB-Bst0azyM8,1692
+sympy/matrices/expressions/_shape.py,sha256=TyQSwGx41aaMyAYs5Q7Er6atKVAdWK7DJ6YIVsiEAZg,3062
+sympy/matrices/expressions/adjoint.py,sha256=HV4OIWgmS2f_1_4PHRhQpgNmKJVCoX0eyHmrM6gfN5g,1515
+sympy/matrices/expressions/applyfunc.py,sha256=8scpWjZp7yzuvUNr0mxN03KgyTzLRa5NkGl9s81YPgY,6751
+sympy/matrices/expressions/blockmatrix.py,sha256=TPR1ZDTSzVGtT-Qo23XNzjnDVl1Js8NCi_2qV3fQA9U,31643
+sympy/matrices/expressions/companion.py,sha256=lXUJRbjQR6e1mdHQdJwNIJXMW80XmKbOVqNvUXjB57U,1705
+sympy/matrices/expressions/determinant.py,sha256=RyQXgUgqJkv_rvUPrn1_rOY45wzp5zYH6ZOf9S8NK8s,3281
+sympy/matrices/expressions/diagonal.py,sha256=XHWoT-Jv5QwJVsGNbfxHnNG2sygPy1CeR_t6zr8oUoM,6328
+sympy/matrices/expressions/dotproduct.py,sha256=sKdUhwVKTB3LEvd8xMwCDexNoQ1Dz43DCYsmm3UwFWw,1911
+sympy/matrices/expressions/factorizations.py,sha256=zFNjMBsJqhsIcDD8Me4W8-Q-TV89WptfG3Dd9yK_tPE,1456
+sympy/matrices/expressions/fourier.py,sha256=dvaftgB9jgkR_8ETyhzyVLtf1ZJu_wQC-ZbpTYMXZGE,2094
+sympy/matrices/expressions/funcmatrix.py,sha256=q6R75wLn0UdV4xJdVJUrNaofV1k1egXLLQdBeZcPtiY,3520
+sympy/matrices/expressions/hadamard.py,sha256=feXSZy0vbqxTzg0JeLmkSegiF4T2v5dOdcv0UQczK38,13920
+sympy/matrices/expressions/inverse.py,sha256=4UwgHWSIHgEoKOniObkClMYN9DrO2xNyvOSVToXSpj8,2963
+sympy/matrices/expressions/kronecker.py,sha256=kzCHqXDtcZGVQPln521lfN5redNwj6IjXJwjbv_Dkhg,13404
+sympy/matrices/expressions/matadd.py,sha256=0MSanal1HKVEuCBEpehKwfUX4fuM9UMy6Fg2H5noA0s,4773
+sympy/matrices/expressions/matexpr.py,sha256=nfV9MhDNBR9HkOP7zoXOtv9wWR4OFxNczprik4S3Uh8,27549
+sympy/matrices/expressions/matmul.py,sha256=n9LcrgYoEhEQuq2htALHuboIWN0p8P_3lZdKNo92Rf0,15509
+sympy/matrices/expressions/matpow.py,sha256=puuYB49wr1WzFxhT9DcTWtF2bGDFWcbJ7oh14ATQARs,5140
+sympy/matrices/expressions/permutation.py,sha256=Xe7yOx-EgeD6JrqWc4L-ApdN-3ZiV8XS_LQPmc1lhGw,8050
+sympy/matrices/expressions/sets.py,sha256=3zase_rDn2QdaXETX78BgkfKiWcRC7FmwVjjIU-WmdY,2033
+sympy/matrices/expressions/slice.py,sha256=aNdY1Ey4VJR-UCvoORX2kh2DmA6QjOp-waENvWg8WVE,3355
+sympy/matrices/expressions/special.py,sha256=hywkygOQjcJEGQn2fG4dF8oUqXL3N42U1TxbdJr4-6E,7499
+sympy/matrices/expressions/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/matrices/expressions/tests/test_adjoint.py,sha256=cxOc334yNSI9MazhG9HT8s1OCXjkDWr3Zj2JnyHS3Z4,1065
+sympy/matrices/expressions/tests/test_applyfunc.py,sha256=mxTJaoB4Ze50lk-2TgVopmrrbuQbEqUsZwc3K1H8w-Q,3522
+sympy/matrices/expressions/tests/test_blockmatrix.py,sha256=ANNR7e2eiGIvabMNezxRVzipmA8oUwmDTrBTz5ALMzU,16541
+sympy/matrices/expressions/tests/test_companion.py,sha256=Lam6r-cSOokjhSlJws55Kq-gL5_pHfeV_Xuvmn5PkRU,1657
+sympy/matrices/expressions/tests/test_derivatives.py,sha256=9mBeaAZDX7-JbYs6tMClNuGDygETVN_dCXSlHmyAhwg,15991
+sympy/matrices/expressions/tests/test_determinant.py,sha256=JSgptLz9KNC4_X27qnuFq-rscgHk6144s5TEUQpLxr0,2067
+sympy/matrices/expressions/tests/test_diagonal.py,sha256=3L6Vs_Yr36a8dgIqAeIcNEf0xcVyeyGhANNu0dlIpwI,4516
+sympy/matrices/expressions/tests/test_dotproduct.py,sha256=Zkv2N6oRPm0-sN4PFwsVFrM5Y_qv4x2gWqQQQD86hBY,1171
+sympy/matrices/expressions/tests/test_factorizations.py,sha256=6UPA_UhCL5JPbaQCOatMnxhGnQ-aIHmb3lXqbwrSoIE,786
+sympy/matrices/expressions/tests/test_fourier.py,sha256=0eD69faoHXBcuQ7g2Q31fqs-gyR_Xfe-gv-7DXhJh_c,1638
+sympy/matrices/expressions/tests/test_funcmatrix.py,sha256=uN9r0ECMIBqsIzOezg_n9uDYNs6ebYS8Yf5yexUjmAM,2230
+sympy/matrices/expressions/tests/test_hadamard.py,sha256=rR0l1howrI8SaJOnLb0fsCXS5cIx1rzahwFTfGldp3Y,4614
+sympy/matrices/expressions/tests/test_indexing.py,sha256=wwYQa7LNlzhBA5fU50gPyE8cqaJf0s3O70PUx4eNCEA,12038
+sympy/matrices/expressions/tests/test_inverse.py,sha256=n4gwv-GH0LPXZDVgzEB0lA_fk8MmNFK_BVNJb0FEUfY,2320
+sympy/matrices/expressions/tests/test_kronecker.py,sha256=e5H6av3ioOn8jkjyDBrT3NEmCkyHbN6ZEHOlyB9OYLk,5366
+sympy/matrices/expressions/tests/test_matadd.py,sha256=U1fL5YLP_cYEOsdi2uaGGrzm8qOsKcXn69BC1UV6RMM,1866
+sympy/matrices/expressions/tests/test_matexpr.py,sha256=pQkxhi8okFDbF6Uea-dbeRrjNfmlc6nzJdIXOJxAqUI,18441
+sympy/matrices/expressions/tests/test_matmul.py,sha256=2ofS4YHHIcI9DamZNU-8RhBQTnNogqGknKxqkyKXO8U,6187
+sympy/matrices/expressions/tests/test_matpow.py,sha256=dRbwvZ3vxwnqw09lnRqOu475f46xDPNo7V3oc1d_P2U,7308
+sympy/matrices/expressions/tests/test_permutation.py,sha256=93Cqjj2k3aoR3ayMJLdJUa5h1u87bRRxT3I8B4FQsvU,5607
+sympy/matrices/expressions/tests/test_sets.py,sha256=DfFGe6W1ppUs6bgo3vB3DSJvFemrT68s0F3QbyoIJiE,1408
+sympy/matrices/expressions/tests/test_slice.py,sha256=C7OGAQQTz0YZxZCa7g0m8_0Bqq8jaPRa22JHVSqK7tY,2027
+sympy/matrices/expressions/tests/test_special.py,sha256=Mhg71vnjjb4fm0jZgjDoWW8rAJMBeh8aDCM75gjEpKQ,6496
+sympy/matrices/expressions/tests/test_trace.py,sha256=fRlrw9CfdO3z3SI4TQb1fCUb_zVAndbtyOErEeCTCQ0,3383
+sympy/matrices/expressions/tests/test_transpose.py,sha256=P3wPPRywKnrAppX6gssgD66v0RIcolxqDkCaKGGPVcM,1987
+sympy/matrices/expressions/trace.py,sha256=skr53LvstLV5Yg9hkaRb0yWrTdxC9u95G-YzIc80aTs,5362
+sympy/matrices/expressions/transpose.py,sha256=QGQ1bgqvYmRNs6QiVolhtFlbluPYpwW3UNvkRZUqUHU,2645
+sympy/matrices/graph.py,sha256=4UBv9SI5Z8Xjc5jPJVOoPVGQDtfbyOmS8f0ENrPOuU8,9080
+sympy/matrices/immutable.py,sha256=okpJZ41FnaHp1PpwnPNCnB_o3afAU7DgRsr2NqBKtvg,5530
+sympy/matrices/inverse.py,sha256=aVjDn_SjZUfi-jdM_1uJ6u6lVItuvbnb3CppayHQ-Gs,13166
+sympy/matrices/kind.py,sha256=EJxDdD4gFgvVfC3lRex-bczhcGjwBhglf1hPDk2WzXE,2843
+sympy/matrices/matrices.py,sha256=iqgi7x7cjnLT6OuRp6TYjoObJtUtbcPpeGTOC-Enh9Q,23536
+sympy/matrices/matrixbase.py,sha256=snpv-ZBFi-CRtfMwY9lukSTPpELVXmJF16Gn8xPV3yI,165154
+sympy/matrices/normalforms.py,sha256=mX19wvJqQAirRiPY-WdSfEdljFOhst18LcDX4MvPM8A,4636
+sympy/matrices/reductions.py,sha256=MZ8LtryawSm1jXsWzRPsYBmir867lRUWX4LFNGVIHwI,12500
+sympy/matrices/repmatrix.py,sha256=d2vne9qNn1cu7dQbCdkftMPadA87evGMaoE7LkxaYXE,29914
+sympy/matrices/solvers.py,sha256=kWkUdy0XoWbn7RY4S1N0qNgxKAcUrHiTlicb25rR9z4,25163
+sympy/matrices/sparse.py,sha256=ER4tfnpvAMeockzWi10mKdKZJSYJNPISyoUL_m29UJ8,14673
+sympy/matrices/sparsetools.py,sha256=tzI541P8QW_v1eVJAXgOlo_KK1Xp6u1geawX_tdlBxY,9182
+sympy/matrices/subspaces.py,sha256=uLo4qnP0xvFcFo5hhf6g7pHSHiRbcQ1ATDKwGBxW7CE,3761
+sympy/matrices/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/matrices/tests/test_commonmatrix.py,sha256=CEYYa5frGDGPAVz78uYVTBC3IHoQLG18VRnq289XtBQ,40772
+sympy/matrices/tests/test_decompositions.py,sha256=LTm3KjUHh0QkGmR8UA1CwGWzpFu8o-qcl4sv2VKBi8g,14419
+sympy/matrices/tests/test_determinant.py,sha256=FxbLYbiO1wj12YYfsbQPoEOcgWpRGVu1CzVKLx4e8oQ,9560
+sympy/matrices/tests/test_domains.py,sha256=gUnMLr_LeEsN5unFjIwHCZje0URC9uVBN_Q76JbX9f4,3276
+sympy/matrices/tests/test_eigen.py,sha256=Xm-Xe7qGACLpqwOx5W2mDjve2KyJf-q8PyEi40jMgAk,22722
+sympy/matrices/tests/test_graph.py,sha256=ckfGDCg2M6gluv9XFnfURga8gxd2HTL7aX281s6wy6c,3213
+sympy/matrices/tests/test_immutable.py,sha256=JSu6YlGtPP-5iialCeatCKbZ4ScLDUzhQ-TMGhsalp8,4616
+sympy/matrices/tests/test_interactions.py,sha256=6T6wkHyTW5v2fwg0rz2HULoDElfA_NttApU2t-pZFKI,2070
+sympy/matrices/tests/test_matrices.py,sha256=YrwrczVsTuLoPAAkh4dlZYbfUcVEUe88wyM53fmUOtw,163196
+sympy/matrices/tests/test_matrixbase.py,sha256=2EUoz0Dl3hPFNvWU--ls6RPGfllZJbVvZSsDA9D6jPo,168868
+sympy/matrices/tests/test_normalforms.py,sha256=leFZ2rJGrWKv8Zz8aMaHQiNrCEQWOG1RqQ87omvlqIk,3730
+sympy/matrices/tests/test_reductions.py,sha256=tKv_KufpVc6qwH-MDz8XLpgVS4z6snnlNdd1ECAQSXM,13385
+sympy/matrices/tests/test_repmatrix.py,sha256=enu29IYEPzvKvGFeN6Bi9KYKqcXdy0EucifN9fV420Q,2084
+sympy/matrices/tests/test_solvers.py,sha256=55Zmvp2KC6OpdXFHBkXZRBRls_8wHfYNWO2UOQh9AoE,22311
+sympy/matrices/tests/test_sparse.py,sha256=GvXN6kBVldjqoR8WN8I_PjblKhRmyRWvVuLUgZEgugY,23281
+sympy/matrices/tests/test_sparsetools.py,sha256=pjQR6UaEMR92NolB_IGZ9Umk6FPZjvI0vk1Fd4H_C5I,4877
+sympy/matrices/tests/test_subspaces.py,sha256=poY6k6l2LSL7OCixQNGzrauLZIYbrjDul7J-yEE02S8,3465
+sympy/matrices/utilities.py,sha256=mMnNsDTxGKqiG0JATsM4W9b5jglhacy-vmRw2aZojgY,2117
+sympy/multipledispatch/__init__.py,sha256=aV2NC2cO_KmD6QFiwy4oC1D8fm3pFuPbaiTMeWmNWak,259
+sympy/multipledispatch/conflict.py,sha256=rR6tKn58MfhMMKZ4ZrhVduylXd9f5PjT2TpzM9LMB6o,2117
+sympy/multipledispatch/core.py,sha256=I4WOnmu1VtlaCnn2oD9R2-xckkYLRZPNFEWtCOTAYfM,2261
+sympy/multipledispatch/dispatcher.py,sha256=A2I4upt4qNollXGpwzrqg7M0oKHJhZx1BUMIBnjRIow,12226
+sympy/multipledispatch/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/multipledispatch/tests/test_conflict.py,sha256=msNVSiikuPOqsEm_MMGmjsNbA2CAR0F1FZaHskzzo04,1786
+sympy/multipledispatch/tests/test_core.py,sha256=UfH_7cyvZ6PHjdH8vmLG49CG7E30W8uxm3FthuMc1Jk,4048
+sympy/multipledispatch/tests/test_dispatcher.py,sha256=saJPpGXLpLOuRfw-ekzZGzY-Rys0NsS5ke0n33i9j0U,6228
+sympy/multipledispatch/utils.py,sha256=39wB9i8jNhlLFZyCTFnioLx5N_CNWv4r5VZwKrxswIE,3097
+sympy/ntheory/__init__.py,sha256=WpYPsusKb9OQ1xmXxZFla7kXacIWv4lNIpFIEVVzTLA,2810
+sympy/ntheory/bbp_pi.py,sha256=ILur1c9Ja-1F_blgnInUx-WopQ_WSvK-2OvNLEe2Zx8,5998
+sympy/ntheory/continued_fraction.py,sha256=bQW7PvdgDtWnbpCmkOwyz3mNYPOXh9_ehq3_ZpJO8Rw,10717
+sympy/ntheory/digits.py,sha256=ea3xSLy8RMaMHsekg8nq2gnVTug7SOvaDjw0lmB6NMU,3831
+sympy/ntheory/ecm.py,sha256=zg_GhL0XSyG5ZVSdGv3YceCguPZrFaS-hC-vXqOVOGQ,11793
+sympy/ntheory/egyptian_fraction.py,sha256=hW886hPWJtARqgZIrH1WjZFC0uvf9CHxMIn0X9MWZro,6923
+sympy/ntheory/elliptic_curve.py,sha256=ZT677EHi26BkZdRTLs1Tf4VSyMxDzJrwk1xECoMT7Qg,11544
+sympy/ntheory/factor_.py,sha256=MQQJSnjSpz-B9ex9fqMCnrrNTfqFOlhJV9RAWy3gJTw,83551
+sympy/ntheory/generate.py,sha256=B6LVkK627xWzQ1UE5XoeMxNM7Q1O8EwcP7fwKs5vkZk,33376
+sympy/ntheory/modular.py,sha256=wYNfNr5S8DqipQNBLVMR7cPUNg7twM25xcLhXBD14I4,8474
+sympy/ntheory/multinomial.py,sha256=rbm3STjgfRbNVbcPeH69qtWktthSCk0sC373NuDM6fU,5073
+sympy/ntheory/partitions_.py,sha256=S81zrWeTVHmYAphcP6yUGLz5CrlUwW_JFtkQRoeLlV4,8995
+sympy/ntheory/primetest.py,sha256=9EVL1yeBkOHDfa2phHiDwUnmidSJJrTl6Wzo0y1Sck0,25423
+sympy/ntheory/qs.py,sha256=8ZKxvqc-oGPqZNbEH-XcPsjXLy5-5aygVB5rR1BkSO8,14938
+sympy/ntheory/residue_ntheory.py,sha256=dDBaogSqroJHlyXRqnLmuzNVyXfy4rWB_hlhOCNQHpk,54359
+sympy/ntheory/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/ntheory/tests/test_bbp_pi.py,sha256=TgNpZOtKAfU-IVzO62Ko7Oy3LLNfdzEo9gWMTTDZL6c,9486
+sympy/ntheory/tests/test_continued_fraction.py,sha256=JJsyEXatgjNxYZTKkKubvymyVs0WDpLfbEiAY5SYk8g,3583
+sympy/ntheory/tests/test_digits.py,sha256=mrTfwboMCQkiOEpMgYg8Nrk12WE5pEtpmbQthRVt4Xc,1968
+sympy/ntheory/tests/test_ecm.py,sha256=yco77gknWe6co4VKTCoRNKHzd3jdqGKQWQFwuziYNWI,2290
+sympy/ntheory/tests/test_egyptian_fraction.py,sha256=tpHcwteuuQAahcPqvgBm4Mwq-efzcHOn8mldijynjlE,2378
+sympy/ntheory/tests/test_elliptic_curve.py,sha256=wc0EOsGo-qGpdevRq1o64htwTOT_YSUzUfyhJC-JVbg,624
+sympy/ntheory/tests/test_factor_.py,sha256=Z4B33C0blhcG9KuQzmJcDw7TtrTYJ6jAsWQd8Oi3YZw,26382
+sympy/ntheory/tests/test_generate.py,sha256=lhnJPjlz1TYrDHJ4Jq0F64P4KV8C7ngKmm3Jxtz7Wsk,9868
+sympy/ntheory/tests/test_hypothesis.py,sha256=Ztg-QoiBxpUp6euPy1RcPbF6yaLK_ij-Jcl637GGhNY,728
+sympy/ntheory/tests/test_modular.py,sha256=g73sUXtYNxzbDcq5UnMWT8NodAU8unwRj_E-PpvJqDs,1425
+sympy/ntheory/tests/test_multinomial.py,sha256=8uuj6XlatNyIILOpjJap13CMZmDwrCyGKn9LiIUiLV0,2344
+sympy/ntheory/tests/test_partitions.py,sha256=qkd-84AO0rpJv-MQW0lnXtIPtGTAfplFbu2ezKSfEQI,1088
+sympy/ntheory/tests/test_primetest.py,sha256=Lp4elAnnBDYSIPfVXENOUjZYuwAynsNQrE_CEiYDErU,9495
+sympy/ntheory/tests/test_qs.py,sha256=zbwQ1k5ywsUVNZzPewWul_yUnoqWxxvsSWOBAU5Albc,3956
+sympy/ntheory/tests/test_residue.py,sha256=7VGXsslZWVd3R7tAtIcLjYyh0TjZpb5BtG2GQehlAUY,16809
+sympy/parsing/__init__.py,sha256=KHuyDeHY1ifpVxT4aTOhomazCBYVIrKWd28jqp6YNJ8,125
+sympy/parsing/ast_parser.py,sha256=iJvr6bhm1RjM5rhWzZA4c4LGTH5lAFazN5zu8y8q-aY,2734
+sympy/parsing/autolev/Autolev.g4,sha256=980mo25mLWrQFmhRIg-aqIalUuwktYYaBGTXZ5_XZwA,4195
+sympy/parsing/autolev/__init__.py,sha256=sp5hzv5siVW3xUmhkp0S0iaA0Cz-PVB0HO1zC04pxYs,3611
+sympy/parsing/autolev/_antlr/__init__.py,sha256=MQ4ZacpTuP-NmruFXKdWLQatoeVJQ8SaBQ2DnYvtyE8,203
+sympy/parsing/autolev/_antlr/autolevlexer.py,sha256=K7HF_-5dUyAIv1_7GkhTmxqSCanEhCpzJG8fayAEB3Q,13609
+sympy/parsing/autolev/_antlr/autolevlistener.py,sha256=EDb3XkH9Y7CLzxGM-tY-nGqxMGfBHVkqKdVCPxABgRE,12821
+sympy/parsing/autolev/_antlr/autolevparser.py,sha256=BZYJ7IkurRmm44S50pYp_9JHCjT8fr1w5HeksAEPjtg,106291
+sympy/parsing/autolev/_build_autolev_antlr.py,sha256=0oIrC3sWUDe18zydeNyRmQrGGwPtRYQzIul8YcmMpk4,2578
+sympy/parsing/autolev/_listener_autolev_antlr.py,sha256=jv1jYvmrGmom6F3fhYTHG1sqLK6FFCO1-jrvDW-nPEM,104760
+sympy/parsing/autolev/_parse_autolev_antlr.py,sha256=b9hIaluJUd1V2XIAp1erak6U-c-CwKyDLH1UkYQuvKE,1736
+sympy/parsing/autolev/test-examples/README.txt,sha256=0C4m_nLROeV5J8nMfm3RYEfYgQJqmlHZaCpVD24boQY,528
+sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.al,sha256=HpTcX2wXzLqmgpp8fcSqNweKjxljk43iYK0wQmBbCDI,690
+sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py,sha256=FSu4TP2BDTQjzYhMkcpRhXbb3kAD27XCyO_EoL55Ack,2274
+sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.al,sha256=wjeeRdCS3Es6ldX9Ug5Du1uaijUTyoXpfTqmhL0uYfk,427
+sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.py,sha256=uU9azTUGrY15BSDtw5T_V-7gmjyhHbXslzkmwBvFjGk,1583
+sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.al,sha256=Gf7OhgRlwqUEXq7rkfbf89yWA23u4uIUJ-buXTyOuXM,505
+sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.py,sha256=9ReCAqcUH5HYBgHmop9h5Zx54mfScWZN5L5F6rCHk4w,1366
+sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.al,sha256=p5v40h1nVFrWNqnB0K7GiNQT0b-MqwayYjZxXOY4M8M,362
+sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.py,sha256=DdxcWrm3HMQuyyY3Pk6sKHb4RXhQEM_EKY3HYZCP8ec,1503
+sympy/parsing/autolev/test-examples/ruletest1.al,sha256=mDJ02Q1Qm-ShVmGoyjzSfgDJHUOuDrsUg3YMnkpKdUw,176
+sympy/parsing/autolev/test-examples/ruletest1.py,sha256=eIKEFzEwkCFhPF0GTmf6SLuxXT384GqdCJnhiL2U0BQ,555
+sympy/parsing/autolev/test-examples/ruletest10.al,sha256=jKpV8BgX91iQsQDLFOJyaS396AyE5YQlUMxih5o9RK0,781
+sympy/parsing/autolev/test-examples/ruletest10.py,sha256=I1tsQcSAW6wqIguF-7lwlj9D4YZ8kCZqPqTKPUHR9oI,2726
+sympy/parsing/autolev/test-examples/ruletest11.al,sha256=j_q7giq2KIuXVRLWwNlwIlpbhNO6SqBMnLGLcxIkzwk,188
+sympy/parsing/autolev/test-examples/ruletest11.py,sha256=dYTRtXvMDXHiKzXHD2Sh0fcEukob3wr_GbSeqaZrrO8,475
+sympy/parsing/autolev/test-examples/ruletest12.al,sha256=drr2NLrK1ewn4FjMppXycpAUNbZEQ0IAMsdVx8nxk6I,185
+sympy/parsing/autolev/test-examples/ruletest12.py,sha256=ZG36s3PnkT0aKBM9Nx6H0sdJrtoLwaebU9386YSUql8,472
+sympy/parsing/autolev/test-examples/ruletest2.al,sha256=d-QjPpW0lzugaGBg8F6pDl_5sZHOR_EDJ8EvWLcz4FY,237
+sympy/parsing/autolev/test-examples/ruletest2.py,sha256=jrJfb0Jk2FP4GS5pDa0UB5ph0ijEVd1X8meKeZrTVng,820
+sympy/parsing/autolev/test-examples/ruletest3.al,sha256=1TAaOe8GI8-yBWJddfIxwnvScHNmOjSzSaQn0RS_v5k,308
+sympy/parsing/autolev/test-examples/ruletest3.py,sha256=O3K3IQo-HCjAIOSkfz3bDlst7dVUiRwhOZ0q_3jb5LU,1574
+sympy/parsing/autolev/test-examples/ruletest4.al,sha256=qPGlPbdDRrzTDUBeWydAIa7mbjs2o3uX938QAsWJ7Qk,302
+sympy/parsing/autolev/test-examples/ruletest4.py,sha256=WHod5yzKF4TNbEf4Yfxmx9WnimA7NOXqtTjZXR8FsP0,682
+sympy/parsing/autolev/test-examples/ruletest5.al,sha256=VuiKjiFmLK3uEdho0m3pk-n0qm4SNLoLPMRJqjMJ4GY,516
+sympy/parsing/autolev/test-examples/ruletest5.py,sha256=WvUtno1D3BrmFNPYYIBKR_gOA-PaHoxLlSTNDX67dcQ,1991
+sympy/parsing/autolev/test-examples/ruletest6.al,sha256=-HwgTmh_6X3wHjo3PQi7378t8YdizRJClc5Eb5DmjhE,703
+sympy/parsing/autolev/test-examples/ruletest6.py,sha256=vEO0jMOD-KIevAcVexmpvac0MGjN7O_dNipOBJJNzF0,1473
+sympy/parsing/autolev/test-examples/ruletest7.al,sha256=wR9S9rTzO9fyKL6Ofgwzw8XCFCV_p2hBpYotC8TvADI,773
+sympy/parsing/autolev/test-examples/ruletest7.py,sha256=_XvMrMe5r9RLopTrIqMGLhaYvHL1qjteWz9CKcotCL8,1696
+sympy/parsing/autolev/test-examples/ruletest8.al,sha256=P7Nu3Pq2R1mKcuFRc9dRO5jJ1_e5fwWdtqYG8NHVVds,682
+sympy/parsing/autolev/test-examples/ruletest8.py,sha256=8tgbwJ-ir0wiOCsgIFCAu4uD8SieYRrLoLzEfae5YQY,2690
+sympy/parsing/autolev/test-examples/ruletest9.al,sha256=txtZ5RH2p1FvAe6etwetSCH8rLktnpk5z0W72sCOdAA,755
+sympy/parsing/autolev/test-examples/ruletest9.py,sha256=GtqV-Wq2GGJzfblMscAz-KXCzs0P_4XqvA3FIdlPe04,1965
+sympy/parsing/c/__init__.py,sha256=J9CvkNRY-qy6CA06GZYuwTuxdnqas6oUP2g0qLztGro,65
+sympy/parsing/c/c_parser.py,sha256=fM1GGRIbjzrVQ7ErfkWz6Xzfjvym030BOoWlQLx37Oc,38124
+sympy/parsing/fortran/__init__.py,sha256=KraiVw2qxIgYeMRTFjs1vkMi-hqqDkxUBv8Rc2gwkCI,73
+sympy/parsing/fortran/fortran_parser.py,sha256=RpNQR3eNx5vgfzdt0nEZDCB56kF__SnYMaqWN3zla00,11483
+sympy/parsing/latex/LICENSE.txt,sha256=AHvDClj6QKmW53IEcSDeTq8x9REOT5w7X5P8374urKE,1075
+sympy/parsing/latex/LaTeX.g4,sha256=fG0ZUQPwYQOIbcyaPDAkGvcfGs3ZwwMB8ZnKW5yHUDY,5821
+sympy/parsing/latex/__init__.py,sha256=CfRRwZZo2qMF2HksyjGer8qSwhx0T4wnXsa2HKxCvUE,8968
+sympy/parsing/latex/_antlr/__init__.py,sha256=TAb79senorEsoYLCLwUa8wg8AUCHzmmZ7tLdi0XGNaE,384
+sympy/parsing/latex/_antlr/latexlexer.py,sha256=Y1hmY1VGL5FTSSlToTRQydPnyaLLNy1mDSWx76HaYwM,30502
+sympy/parsing/latex/_antlr/latexparser.py,sha256=ZvonpvTS3vLSOVpas88M3CfNnUhPUDsCCPPk4wBYUGE,123655
+sympy/parsing/latex/_build_latex_antlr.py,sha256=3Mwip9f_yXUNhiwwUTCG5Nk8l2uzAw8oZHU0HSl5gkE,2765
+sympy/parsing/latex/_parse_latex_antlr.py,sha256=sVaO04oSeHe_TaMeM-6toheCR88G_RmJYpUIx-Sef1g,20712
+sympy/parsing/latex/errors.py,sha256=adSpvQyWjTLsbN_2KHJ4HuXpY7_U9noeWiG0lskYLgE,45
+sympy/parsing/latex/lark/__init__.py,sha256=hhhvfKRGP3ON36wRJwVfxMWw_GA6rl0JKsIzjuaUX38,120
+sympy/parsing/latex/lark/grammar/greek_symbols.lark,sha256=-G8JGrBredhWAzCaurr1UmqgRMRrAJfs_pANub8kXyA,937
+sympy/parsing/latex/lark/grammar/latex.lark,sha256=yz3DXIHllvRDGHeBmpz49PzDCU92pKexg2RTKX4KhTE,13221
+sympy/parsing/latex/lark/latex_parser.py,sha256=lGFEo_RxSKXYmjVEb_E3DiZ-aXl5tAZyfHklzEuJ9VA,4430
+sympy/parsing/latex/lark/transformer.py,sha256=RuXe8enUnLrzUFC9ZfKQyQ1_IlgA-qPINNng6UnY1x4,25754
+sympy/parsing/mathematica.py,sha256=P2vWEgx_HXv4I_C-6vPE3RXtbpXNT2iIJQBrA6QfqkU,39614
+sympy/parsing/maxima.py,sha256=DhTnXRSAceijyA1OAm86c6TyW9-aeUVoZEELGu0oZtY,1835
+sympy/parsing/sym_expr.py,sha256=-hxarp961eyLtuwUhbg3D3qzy06HrEPZEYpGVcJzAv0,8895
+sympy/parsing/sympy_parser.py,sha256=PRRhNS_0LKBVcHFmg7LGygzxRyQt6-vyCSMisXkRhVE,43832
+sympy/parsing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/parsing/tests/test_ast_parser.py,sha256=lcT8w7mn6UEZ8T-xfA4TqG4Mt7JxY00oHhOW7JtHQfY,803
+sympy/parsing/tests/test_autolev.py,sha256=tQuUFa8YqVdsHPOcUhAwlMKB8Uk08HejDhDCda8lXs0,6647
+sympy/parsing/tests/test_c_parser.py,sha256=VYl3K4if_23iIS-Be8MBSG0OKZo-6xgxHiN22laeAyo,155354
+sympy/parsing/tests/test_custom_latex.py,sha256=vX5uVHw9-UgEcRl0XVNOMgrjBbb1sXDlPLL4D8AeOiQ,2060
+sympy/parsing/tests/test_fortran_parser.py,sha256=SGbawrJ4a780TJAFVMONc7Y3Y8VYgVqsIHxVGaicbxE,11828
+sympy/parsing/tests/test_implicit_multiplication_application.py,sha256=xUlc9TKH4HjimhnvWMwCtTabHAJcHCupFdsuiOsZhUs,7389
+sympy/parsing/tests/test_latex.py,sha256=WvKNJ5mtxfzl-rBiE9hc2aEz81b5BmI3SKO7sRZiNbI,11765
+sympy/parsing/tests/test_latex_deps.py,sha256=oe5vm2eIKn05ZiCcXUaO8X6HCcRmN1qCuTsz6tB7Qrk,426
+sympy/parsing/tests/test_latex_lark.py,sha256=kXmZP-gMLwa5XAcNsd-rF_zrPok0RZuJsa6Ny6zfoLw,36059
+sympy/parsing/tests/test_mathematica.py,sha256=vAxwquc8ArTQE9UNbsO21FqSa6J17sCF-A4vhTPXLY0,13395
+sympy/parsing/tests/test_maxima.py,sha256=iIwnFm0lYD0-JcraUIymogqEMN3ji0c-0JeNFFGTEDs,1987
+sympy/parsing/tests/test_sym_expr.py,sha256=-wNR7GwvJHVmPSZxSuAuoX1_FJk83O0tcDi09qYY6Jk,5668
+sympy/parsing/tests/test_sympy_parser.py,sha256=H_dDL89ASex3sI8F92ceXIJy5Qd137rxTa20Rj-9l2A,12946
+sympy/physics/__init__.py,sha256=F_yvUMCuBq3HR-3Ai6W4oktBsXRg8KdutFLwT9FFJlY,220
+sympy/physics/biomechanics/__init__.py,sha256=dG1IoRAnmfXvSyPciqJVrPn5LLnuvbVnBt78hBG0maQ,1520
+sympy/physics/biomechanics/_mixin.py,sha256=0D3iBqlCRmR4HXKMxyC2LvYpKGHreOuZY5dXMJioQ4A,1493
+sympy/physics/biomechanics/activation.py,sha256=rUJegXrdO1LPHnzJpVRAYnA6DsvF46ndctkBt1JHDwI,25522
+sympy/physics/biomechanics/curve.py,sha256=PezKOUytiC15oLV11GC4M6u7ndXHpwtbilqdbIiqvgw,63154
+sympy/physics/biomechanics/musculotendon.py,sha256=LrYwFnwkShDWWZQtCgtSUqvc1H5IlTj_BNVKxfFNhE0,58274
+sympy/physics/biomechanics/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/physics/biomechanics/tests/test_activation.py,sha256=hdnMsFBLjloJylu8-cLZ44oamORG3kSsI0q2-eLQ_-I,13395
+sympy/physics/biomechanics/tests/test_curve.py,sha256=3jbWEHr8ieZYCfVlwJ1KTA1WJ9dcTCyQ1p3r8G2jp1I,75800
+sympy/physics/biomechanics/tests/test_mixin.py,sha256=ds-EoUCvfiSjVGnC_mBwjn5mI7z5W5wi2UTZZ4-pIIQ,1322
+sympy/physics/biomechanics/tests/test_musculotendon.py,sha256=Ls59mtJQ83W0fdpDGFGNeTgtxL8yAZ6ODW96N9mvFtM,32906
+sympy/physics/continuum_mechanics/__init__.py,sha256=GzYypKq3so15xfvY4qFerHYCNGFzZthfQ1aOcgu8yCM,191
+sympy/physics/continuum_mechanics/arch.py,sha256=TKaoHk7-ToNP0n6ZGFF_cW6x965C-D3iENiqFo74ZJU,39243
+sympy/physics/continuum_mechanics/beam.py,sha256=Vq1xJHrjatQEUigMsxlAk8qoZSyp_Z_0GiJ5y5AIMIg,159946
+sympy/physics/continuum_mechanics/cable.py,sha256=1IOpa_eLYwdyixNkDhLXJQSg4fQhwOH7Ybm1jWR4aQA,31420
+sympy/physics/continuum_mechanics/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/physics/continuum_mechanics/tests/test_arch.py,sha256=t_V-Pt0fxoPqYDZl5LB6ehQ4hBBVlveRWLsEXdyo_3k,2571
+sympy/physics/continuum_mechanics/tests/test_beam.py,sha256=Wmi8BCju21H1RaomKDqFATvCUqsrca_43o5IyA5s4ok,42085
+sympy/physics/continuum_mechanics/tests/test_cable.py,sha256=aANZVJxfihRkjAauCvFPGkXKD_zxMcJFb7vXU443dsQ,3832
+sympy/physics/continuum_mechanics/tests/test_truss.py,sha256=wgtF1GbQX5hzx20UrBg2ZyEvplVpsio3DiU8CS_bAk8,3269
+sympy/physics/continuum_mechanics/truss.py,sha256=hkLLnXA9aRaE2YvA0ods7T40zJQXUc_jLI108NjhtTI,44962
+sympy/physics/control/__init__.py,sha256=U0BeOmFRXOw-cpZ_F-RzNuEh78Tqzx31nuvZMZW2Fo8,1334
+sympy/physics/control/control_plots.py,sha256=lYa42ATTrSXMV44Q3POfEyYQCFSTV1W5Rb4UejYFdT8,37515
+sympy/physics/control/lti.py,sha256=o6n-qFXriBeETr4anCgOuYViUpQXDtBejckIdYdlxx0,177322
+sympy/physics/control/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/physics/control/tests/test_control_plots.py,sha256=dsXkabVUMzU6b1FmptRz2sGgXfe6y_lu3Mm0KN8is90,16899
+sympy/physics/control/tests/test_lti.py,sha256=YAvwA11zSKRcHmgLPuCJhBJXbFrPfjUNytaQsnEsEr8,104043
+sympy/physics/hep/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/physics/hep/gamma_matrices.py,sha256=WlSHLUtMU7NrgLyKEvTntMSYxMZq1r_6o2kqUEAdPaA,24253
+sympy/physics/hep/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/physics/hep/tests/test_gamma_matrices.py,sha256=iKqICj0bP7EK0sSuYFsPdPkDTbHGa6J_LMPZAzv1j4o,14722
+sympy/physics/hydrogen.py,sha256=R2wnNi1xB-WTQ8Z9aPUhX9Z8mQ8TdhCM1JAZIkyXgjw,7594
+sympy/physics/matrices.py,sha256=jHfbWkzL2myFt-39kodQo5wPubBxNZKXlljuSxZL4bE,3836
+sympy/physics/mechanics/__init__.py,sha256=7rgPJp1YItAMOc29gWqkRp68AKCdZLu4tFQG-CWgjOQ,2874
+sympy/physics/mechanics/actuator.py,sha256=d7Ffb9vo1Tmrcfiy71_g0r1btscfvvabE-vznku3Auk,43633
+sympy/physics/mechanics/body.py,sha256=Z9ZOReEab9FHEDsyv2RfIBQM4_ripXhFXmQtu1OmN_Y,24617
+sympy/physics/mechanics/body_base.py,sha256=bwP04lWmD0iY_T0Vsn6NWMbnWyzUMFFqkAoAyKsow_c,2491
+sympy/physics/mechanics/functions.py,sha256=KsX3z33rZdMCifwyVlyKIHVJh0Fve--zs5wd1rkGMl0,25190
+sympy/physics/mechanics/inertia.py,sha256=FKcEbpYPx_26LS9sSp8lcsJ83spqwSYIyxM5q_z1mYA,6172
+sympy/physics/mechanics/joint.py,sha256=o9SWJ9pXDO-sVh0gJ6VTI0LgY019gFB5w5FP1PN--UI,84621
+sympy/physics/mechanics/jointsmethod.py,sha256=nqkXawtuxeyP0D8DEAYURCJlDYS4Eka_vXx6UZP7y74,10415
+sympy/physics/mechanics/kane.py,sha256=XyvEDNF09i5DnHf-YlCecEHDdKK9j486N2P5YD8_XaM,37118
+sympy/physics/mechanics/lagrange.py,sha256=UTmClOP-PkY8S-LcPlcOAUmshndlq6mpmZailbvy4E4,20202
+sympy/physics/mechanics/linearize.py,sha256=YtAap6TzsZJd794cdDCEDJVlMOXd_wFAMaCZZacHwbE,17242
+sympy/physics/mechanics/loads.py,sha256=jnajZOg631Aqtd0-BplehohUL991C3Cji2OZZ3MVHdk,5406
+sympy/physics/mechanics/method.py,sha256=2vFRhA79ra4HR6AzVBHMr3oNncrcqgLLMRqdyif0DrI,660
+sympy/physics/mechanics/models.py,sha256=9q1g3I2xYpuTMi-v9geswEqxJWTP3RjcOquRfzMhHzM,6463
+sympy/physics/mechanics/particle.py,sha256=YKiEBkPLVRI9foXlEe8eu8Ys5W1GyQO1oOBf0T8fHFg,5985
+sympy/physics/mechanics/pathway.py,sha256=2T71x06X8CZ20NUyXkMnP83gKsx2wJJEbPJS-1gMXFA,26555
+sympy/physics/mechanics/rigidbody.py,sha256=s5b7ynsdcMsq9PN2nM1yozNcZd08RA-MgzMjcs7jnBI,10287
+sympy/physics/mechanics/system.py,sha256=VsPPQfJs0gBLKJYNQ2ZLmD98JWLd1IZy0QGRwI21_TM,59457
+sympy/physics/mechanics/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/physics/mechanics/tests/test_actuator.py,sha256=WoTnD_IGhewVOzcL7ybJXf_mrK0_E71gDcnon-3Mayg,41081
+sympy/physics/mechanics/tests/test_body.py,sha256=ygHfWeL6-3LW9gqXHfzdvqQhJWxg2-U2KQIHKqGNqKQ,12067
+sympy/physics/mechanics/tests/test_functions.py,sha256=Cl1aT3qT-0Ik6vJgS6at6PUaeWRQfpEG88QvEIxz1Bk,10447
+sympy/physics/mechanics/tests/test_inertia.py,sha256=On4K78tmq4tyr_QFs3Uo01efdlVj5R6yfn6CVs7ksnE,2726
+sympy/physics/mechanics/tests/test_joint.py,sha256=ojhQdBsWN6nR7egEhpw-LAyDRdFIPfSEsDoFL1bhzqs,57922
+sympy/physics/mechanics/tests/test_jointsmethod.py,sha256=8IUO7ntLPsydDT4YgA1FPyO5TXNpo4CIWC7O_JdWg9Q,10226
+sympy/physics/mechanics/tests/test_kane.py,sha256=K1HOm7cuPzXeO9ZmW7oAHgu-jxOg1IFqyKB3YheAbus,21545
+sympy/physics/mechanics/tests/test_kane2.py,sha256=qNLkbSV6UYclQzMDoRi_TJrJEz0-MUi7yf1e7XW4ba4,19256
+sympy/physics/mechanics/tests/test_kane3.py,sha256=-9MbXLfYUDhA_9D2o4NrNLgDTOnKDLLsgryQW3AHacs,14959
+sympy/physics/mechanics/tests/test_kane4.py,sha256=qJYUfvnq1F5UN_AQqTu_3BT5XqGceqxnCyP3d2gE04A,4709
+sympy/physics/mechanics/tests/test_kane5.py,sha256=gZvAyxJ8fkkLtH60xHlb_Gxrbt9d7VmJTckXSGmF0j4,5693
+sympy/physics/mechanics/tests/test_lagrange.py,sha256=iuHomulBF8MafLeorKGaLHUEF8CvFhXcxEtN0hk1akM,10119
+sympy/physics/mechanics/tests/test_lagrange2.py,sha256=VBonbWg0uLduE4AwNUWCsGGa_2KmaDbg9jROZL3DTWE,1402
+sympy/physics/mechanics/tests/test_linearity_of_velocity_constraints.py,sha256=Y9JYoaob8yyL7PS-VN7g-DC8YEfCxBGdFSSkQAKlOBI,1341
+sympy/physics/mechanics/tests/test_linearize.py,sha256=6yFFGEhJW60fx9Ny1duc6eyvGDg6rtmJVo_V1mgHgGk,13273
+sympy/physics/mechanics/tests/test_loads.py,sha256=Kw94kP0tfwKsV-jCDHGTQsyc-1dKQl3ABJfqJtR8AJg,2698
+sympy/physics/mechanics/tests/test_method.py,sha256=L7CnsvbQC-U7ijbSZdu7DEr03p88OLj4IPvFJ_3kCDo,154
+sympy/physics/mechanics/tests/test_models.py,sha256=GcsfCm5G4PPYQXsHCiAKI1dEW42RaZOh-x6aEouTYo4,5078
+sympy/physics/mechanics/tests/test_particle.py,sha256=JL6QAA6T3POQkSutUnungrVkR3xt6ZVX-hp75-EufQw,2682
+sympy/physics/mechanics/tests/test_pathway.py,sha256=oGCxlUOviyNc1GBMvhk5sYVZfu8C4o7lJMbqatBie3A,24944
+sympy/physics/mechanics/tests/test_rigidbody.py,sha256=ezMW5BWt9cWdNeY1B9aYcL4NsPcVkaKZuUS1C7S1qPk,6188
+sympy/physics/mechanics/tests/test_system.py,sha256=Dihu77qM5_QkDQg-zavHbVhh_nvaGEVztXgPNl2_enk,8700
+sympy/physics/mechanics/tests/test_system_class.py,sha256=Xe4VLrxWaYL3oRwP2SBaanWf5DY46d2yPlwf9H1XJ4M,38219
+sympy/physics/mechanics/tests/test_wrapping_geometry.py,sha256=aXwuEaprstnSW7BwLr3OKUyxSagRPO58L-tUMaq3I9s,10502
+sympy/physics/mechanics/wrapping_geometry.py,sha256=XkI331oQcBme4jDmH0RqQDWh_pq49o38nbRsXwT9O5E,21599
+sympy/physics/optics/__init__.py,sha256=0UmqIt2-u8WwNkAqsnOVt9VlkB9K0CRIJYiQaltJ73w,1647
+sympy/physics/optics/gaussopt.py,sha256=mVQ-JX7xmAp9XbNOYIlwsPAxkUukTw_QjbjIxuKWZW8,20898
+sympy/physics/optics/medium.py,sha256=cys0tWGi1VCPWMTZuKadcN_bToz_bqKsDHSEVzuV3CE,7124
+sympy/physics/optics/polarization.py,sha256=mIrZiOVXetGtKkLxl8Llaf2Z9coWenf6JKrClh4W8yU,21434
+sympy/physics/optics/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/physics/optics/tests/test_gaussopt.py,sha256=QMXJw_6mFCC3918b-pc_4b_zgO8Hsk7_SBvMupbEi5I,4222
+sympy/physics/optics/tests/test_medium.py,sha256=RxG7N3lzmCO_8hIoKyPnDKffmk8QFzA9yamu1_mr_dE,2194
+sympy/physics/optics/tests/test_polarization.py,sha256=81MzyA29HZckg_Ss-88-5o0g9augDqCr_LwcJIiXuA0,2605
+sympy/physics/optics/tests/test_utils.py,sha256=SjicjAptcZGwuX-ib_Lq7PlGONotvo2XJ4p3JA9iNVI,8553
+sympy/physics/optics/tests/test_waves.py,sha256=PeFfrl7MBkWBHdc796sDDYDuhGepat3DQk7PmyTXVnw,3397
+sympy/physics/optics/utils.py,sha256=BqfuvtrjO3PEcDQ1DecNyt2Th9Yps6xued1tEY4ysvk,22172
+sympy/physics/optics/waves.py,sha256=Iw-9gGksvWhPmQ_VepmI90ekKyzHdPlq6U41wdM4ikI,10042
+sympy/physics/paulialgebra.py,sha256=1r_qDBbVyl836qIXlVDdoF89Z9wedGvWIkHAbwQaK-4,6002
+sympy/physics/pring.py,sha256=SCMGGIcEhVoD7dwhY7_NWL1iKwo7OfgKdmm2Ok_9Xl0,2240
+sympy/physics/qho_1d.py,sha256=ZXemUsa_b0rLtPVTUkgAkZQ1Ecu2eIZxaiNSSXW0PDk,2005
+sympy/physics/quantum/__init__.py,sha256=vzWc2d2aXbMdZGJRx4tyS6FDCtjbtl7SqCJE7nSXN9A,1952
+sympy/physics/quantum/anticommutator.py,sha256=kXr7DWZZy0Sqcnxx-QEeA58mUCRXTL_VHDzQBjNV0DI,5072
+sympy/physics/quantum/boson.py,sha256=Nn4TN917TQv4tdFNZddlT1eEGg7O1uybnU9K5NI6AyM,5834
+sympy/physics/quantum/cartesian.py,sha256=9R9VDYLV1Xe-GkA9TQbj8PVlBLaD0fF6KXfHJ1ze5as,9092
+sympy/physics/quantum/cg.py,sha256=WK7HkAIRFejQQLjRsCC7rH0L--0fmXAoeL1JdTHb3GA,23319
+sympy/physics/quantum/circuitplot.py,sha256=SacQMhPyDhizKmGRNEs1vtXph8lR6bMn5bVJI4rJiXg,11799
+sympy/physics/quantum/circuitutils.py,sha256=mrQNUDbwM3LV1NZ1EqVpXyOY2mOXCBVZW7cQTiCxUaM,13882
+sympy/physics/quantum/commutator.py,sha256=MKk8OqwIi8LCzxkD8URmKCFM9OthAAxS8xFNgP_i09U,8139
+sympy/physics/quantum/constants.py,sha256=20VRATCkSprSnGFR5ejvMEYlWwEcv1B-dE3RPqPTQ9k,1420
+sympy/physics/quantum/dagger.py,sha256=P58FL8fLFfMhtu79jGsG69oEMjLjutRDrXsLwBat-9U,2484
+sympy/physics/quantum/density.py,sha256=ie_NJO-YNJ3PydAMp3jlmhC5H8bN3ldhn2SiCKY5N0s,9546
+sympy/physics/quantum/fermion.py,sha256=1ipn3FItUJ_ruLnflpp9MN_6t5w8CgHAJRJCOsukGGI,4983
+sympy/physics/quantum/gate.py,sha256=Iv7-qhSCe_An9qaJcYRDgwr8ClNraP47E75UlS5fCoQ,42588
+sympy/physics/quantum/grover.py,sha256=17KC5MJR3cCavmzqRqi9dB5OFTOpsYjfrTZuv03HiuE,10452
+sympy/physics/quantum/hilbert.py,sha256=qrja92vF7BUeSyHOLKVX8-XKcPGT7QaQMWrqWXjRNus,19632
+sympy/physics/quantum/identitysearch.py,sha256=Zh_ji5J0YeAy2AezsQcHV9W2icWoaa3ZwTbfjCCQmJo,27607
+sympy/physics/quantum/innerproduct.py,sha256=NKlJufh068C3MeKBORJG8k7zdH_vGJeo7jlH67PqU7E,4303
+sympy/physics/quantum/kind.py,sha256=odJyriPZKyievddvlY-kks8iBCSi1yZ7JEsaLANHoe4,2831
+sympy/physics/quantum/matrixcache.py,sha256=S6fPkkYmfX8ELBOc9EST-8XnQ1gtpSOBfd2KwLGKdYo,3587
+sympy/physics/quantum/matrixutils.py,sha256=53VGeUNYNpU1eA1sNcYFaX1_45I9SVabCfpTyHUDFog,8214
+sympy/physics/quantum/operator.py,sha256=Q-uiUjAZgMOXHKoBFe2oW_qJsJSjC8fM246yzxMmZ0A,19657
+sympy/physics/quantum/operatorordering.py,sha256=byAyZCNKTCeFWIFThmNx0NgdI4u32O4ydodYSa6Wrr8,10296
+sympy/physics/quantum/operatorset.py,sha256=h8nkScpQcUzCO3zemqKpgQfJDWiBbfj33IJzcl4J2_4,9563
+sympy/physics/quantum/pauli.py,sha256=lzxWFHXqxKWRiYK99QCo9zuVG9eVXiB8vFya7TvrVxQ,17250
+sympy/physics/quantum/piab.py,sha256=Zjb2cRGniVDV6e35gjP4uEpI4w0C7YGQIEXReaq_z-E,1912
+sympy/physics/quantum/qapply.py,sha256=5vqWe__WRvJuD6sWC2NTDe1qEcToBGTGaye9lzirgf4,9494
+sympy/physics/quantum/qasm.py,sha256=UWpcUIBgkK55SmEBZlpmz-1KGHZvW7dNeSVG8tHr44A,6288
+sympy/physics/quantum/qexpr.py,sha256=N87sU5AqFbGEXgHJof-B7ua46rk4SeysK16abU1GfYI,13940
+sympy/physics/quantum/qft.py,sha256=ua4qBQAm-gi923lRRxOgAebTsTCoR93pz8ZHPXBdcus,6425
+sympy/physics/quantum/qubit.py,sha256=mE0xebz8zqeKEc4xww9-Iv7tZzxHjm9Klsr2WgUQcVM,25997
+sympy/physics/quantum/represent.py,sha256=dBY9RLD21V0WuIBbigagjaLSUCiloDzitv8Wl6fU9dE,18729
+sympy/physics/quantum/sho1d.py,sha256=ZroR_FjxmjOmDcd0Fm04vWKTGCpvLaEu4NiuplKm708,20867
+sympy/physics/quantum/shor.py,sha256=DVwPxLAPSr8t3F3aXJIPe4o5XSuQiE6a6eA6OYmdZFw,5504
+sympy/physics/quantum/spin.py,sha256=l6168fTEZEC4FeaMS8iLqo3b4YMvUlPTZvq9N8iSV08,72986
+sympy/physics/quantum/state.py,sha256=618YaDGAtpUeuWCVYs6lDuO3mD87_f8KIUGUXaN9L4s,29971
+sympy/physics/quantum/tensorproduct.py,sha256=PvpDSuLku1IdIV3T2dK3fVv6AdMNVcc5eR8n34AB3OQ,12599
+sympy/physics/quantum/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/physics/quantum/tests/test_anticommutator.py,sha256=ckWHKwQFiAMWcDaYSa_26vi_GIsvs32_0O62I5lGsr8,1304
+sympy/physics/quantum/tests/test_boson.py,sha256=BZjdrZ-F1QhyhDqfK4Zc1VEFBJi1PeiPjMpfBcHekfo,1676
+sympy/physics/quantum/tests/test_cartesian.py,sha256=4szaB4w555oDUkhaRtBF8mOfIxiODNCqOlDHEVcUFOo,4417
+sympy/physics/quantum/tests/test_cg.py,sha256=BF-2ybLhoAYOb0wfWFlgnobMzH20zTYJvW5Z7v46SYI,9159
+sympy/physics/quantum/tests/test_circuitplot.py,sha256=c3v9wUzLHUH-eBVGj6_broVhHkioNwpaaApTDAJEflU,2096
+sympy/physics/quantum/tests/test_circuitutils.py,sha256=GrJAWRQVH_l8EIHrj1ve2jtxske72IriQ3lo94fqrVQ,13187
+sympy/physics/quantum/tests/test_commutator.py,sha256=keBstGDpNITFRr06uVFrka_Lje56g6oFoJQEpZXmnYw,2727
+sympy/physics/quantum/tests/test_constants.py,sha256=KBmYPIF49Sq34lbzbFCZRYWSyIdhnR3AK3q-VbU6grU,338
+sympy/physics/quantum/tests/test_dagger.py,sha256=pi2lhL5EaE8FuIuwM9gOce2NpDCP4S1JptqI-mx8FGM,2632
+sympy/physics/quantum/tests/test_density.py,sha256=EyxiEgyc0nDSweJwI0JUwta7gZ81TVHCl7YDEosTrvI,9718
+sympy/physics/quantum/tests/test_fermion.py,sha256=RK-J3nV1UO_9R5UyrBIp_qfWX-5iZ152aoyEllKWSIc,1636
+sympy/physics/quantum/tests/test_gate.py,sha256=7oBX1HoWnrYtHjABRoqv_wQDB9B829E99fdcJzaqawM,12496
+sympy/physics/quantum/tests/test_grover.py,sha256=uze62AG6H4x2MYJJA-EY3NtkqwvrDIQ2kONuvIRQiZ4,3640
+sympy/physics/quantum/tests/test_hilbert.py,sha256=IGP6rc2-b3we9dRDbpRniFAhQwp_TYtMfFzxusAprx0,2643
+sympy/physics/quantum/tests/test_identitysearch.py,sha256=3YGrXCsFLhLtN5MRyT5ZF8ELrSdkvDKTv6xKM4i2ims,17745
+sympy/physics/quantum/tests/test_innerproduct.py,sha256=37tT8p6MhHjAYeoay1Zyv7gCs-DeZQi4VdwUH2IffDE,1483
+sympy/physics/quantum/tests/test_kind.py,sha256=MCc0jobaf-fZmi99ir2VpZM1Lah5w9ZMxqygVQZfleU,2515
+sympy/physics/quantum/tests/test_matrixutils.py,sha256=wXc2jYLYaR07MgbVBpUU0cEsy2YQhQygbHV6M55u_ss,4115
+sympy/physics/quantum/tests/test_operator.py,sha256=kmNGQzjtdsko6PlUNcTT0kjOYX73LOMzHGuncS2SjSw,8417
+sympy/physics/quantum/tests/test_operatorordering.py,sha256=SFvJfrBxreMgMB3PEpXGcTvO_113Pi1O-Jco-A9_aVI,2003
+sympy/physics/quantum/tests/test_operatorset.py,sha256=DNfBeYBa_58kSG7PM5Ilo6xnzek8lSiAGX01uMFRYqI,2628
+sympy/physics/quantum/tests/test_pauli.py,sha256=Bhsx_gj5cpYv4BhVJRQohxlKk_rcp4jHtSRlTP-m_xs,4940
+sympy/physics/quantum/tests/test_piab.py,sha256=8ndnzyIsjF4AOu_9k6Yqap_1XUDTbiGnv7onJdrZBWA,1086
+sympy/physics/quantum/tests/test_printing.py,sha256=Qg34sHUAgKeh7DhHNp3KQX0_bhfdkMPCKJUvL08ufz8,30332
+sympy/physics/quantum/tests/test_qapply.py,sha256=ol5IJuuPand4r-P2cBv_Wycv2wnkMsW3dlJxDAp_PSs,6086
+sympy/physics/quantum/tests/test_qasm.py,sha256=ZvMjiheWBceSmIM9LHOL5fiFUl6HsUo8puqdzywrhkc,2976
+sympy/physics/quantum/tests/test_qexpr.py,sha256=0a80r2d31yxuJn11CcemrMn855o2ge5CH8j73ZCwuKI,1830
+sympy/physics/quantum/tests/test_qft.py,sha256=v-sGTaW9S-gcGTDAUPvjwd1kINF6rlI_u5Sf-Gso0r8,1931
+sympy/physics/quantum/tests/test_qubit.py,sha256=rj5RNjLWjZ8514fQwEsVp0wuUlI1SKAIomL0wZ-9PqA,9271
+sympy/physics/quantum/tests/test_represent.py,sha256=lEwzpL0fGxDGkojZ4_WoBAtCcA7aq2-S-i0Z0QrnTXg,5177
+sympy/physics/quantum/tests/test_sho1d.py,sha256=1QCoRXwhcK-P1oUrREgAroPHJPzPgWEBSrHomjS3meA,6893
+sympy/physics/quantum/tests/test_shor.py,sha256=3a3GCg6V5_mlJ2bltoXinGMGvlSxpq7GluapD_3SZaQ,666
+sympy/physics/quantum/tests/test_spin.py,sha256=p6F0cfQkPYwXlzE29mTL-dpsEYZmFU0EfAwm2MUA9xE,345698
+sympy/physics/quantum/tests/test_state.py,sha256=pjNwjEQN1zMXzC6NbL60ZLzpqBfZD5RscjuyiFuhTaE,6748
+sympy/physics/quantum/tests/test_tensorproduct.py,sha256=CL8xJyUl7plFU7TYsHHkLDYt9PtS4SM_H-SG4lKM5aE,5314
+sympy/physics/quantum/tests/test_trace.py,sha256=dbpTXcJArWRR_Hh5JTuy2GJIfgjVo6zS20o5mdVEGH4,3057
+sympy/physics/quantum/tests/test_transforms.py,sha256=w1fLTJO07CWPOQp5jFVU83MatsaoNBkxOI_YbM6I1w8,2346
+sympy/physics/quantum/trace.py,sha256=2ZqN9IEsz3LKHTLV8ZDwTK0sM5PfwL0p2sYet0N7Gis,6397
+sympy/physics/quantum/transforms.py,sha256=XLnWmyoWW8oXJ8I7dUIF7cMxFt9xr736HfNstD_tnK0,10929
+sympy/physics/secondquant.py,sha256=1XDsbnUpFC7zmJ4VC9DXEsK_smSqNMaDfsi6slIkws0,90974
+sympy/physics/sho.py,sha256=K8P9FAdZr6UfQKYZO9TlhDUqUd3YsMekXCsKy2HhaY0,2480
+sympy/physics/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/physics/tests/test_clebsch_gordan.py,sha256=gHMZnYkigoVWeDV7bwD4YARplb_L1AOMppzcLxSmWnI,9921
+sympy/physics/tests/test_hydrogen.py,sha256=kohRIR6JojE_GWYnlzLsMMgdhoKd8whazs0mq7cCTQc,4987
+sympy/physics/tests/test_paulialgebra.py,sha256=tyshEMsLNPR4iYzoAbPGZRZ-e_8t7GDP_xyjRyhepeQ,1477
+sympy/physics/tests/test_physics_matrices.py,sha256=Dha8iQRhzxLcl7TKSA6QP0pnEcBoqtj_Ob6tx01SMwI,2948
+sympy/physics/tests/test_pring.py,sha256=XScQQO9RhRrlqSII_ZyyOUpE-zs-7wphSFCZq2OuFnE,1261
+sympy/physics/tests/test_qho_1d.py,sha256=LD9WU-Y5lW7bVM7MyCkSGW9MU2FZhVjMB5Zk848_q1M,1775
+sympy/physics/tests/test_secondquant.py,sha256=vI9EuCMd1PMYNbZH2bHW9xHPYS5DS92QOmAk1kC12cQ,49401
+sympy/physics/tests/test_sho.py,sha256=aIs1f3eo6hb4ErRU8xrr_h_yhTmRx-fQgv9n27SfsLM,693
+sympy/physics/units/__init__.py,sha256=DVvWy9qNRm742NFGcBpybFY20ZK3BU7DWNbLMTXYiFo,12386
+sympy/physics/units/definitions/__init__.py,sha256=F3RyZc1AjM2Ch5b27Tt-VYdZ1HAIWvhgtQQQTfMiN6w,7470
+sympy/physics/units/definitions/dimension_definitions.py,sha256=QmPLCy7GvLx1z_YEZ5KFl8QUXg4rcuu3PuNI5wLpPdY,1633
+sympy/physics/units/definitions/unit_definitions.py,sha256=05wpHmAtyQvuJBeuzWm3cDQ6UYviNtsi4kVc0hv8VHw,14680
+sympy/physics/units/dimensions.py,sha256=GMuoSF1vqKDs_e3JJ7Y0lpFrneXMZLZk_qIC5d6Q5UU,20899
+sympy/physics/units/prefixes.py,sha256=_q2f8gA-kckBG7TutTFQazTf15PCZqNnaTR1gKXRfsk,6260
+sympy/physics/units/quantities.py,sha256=r5E231CULmsSEM7Rh7zfcTPuR85_X0CwRCVU_nDsek0,4671
+sympy/physics/units/systems/__init__.py,sha256=jJuvdc15c83yl11IuvhyjijwOZ9m1JGgZOgKwKv2e2o,244
+sympy/physics/units/systems/cgs.py,sha256=gXbX8uuZo7lcYIENA-CpAnyS9WVQy-vRisxlQm-198A,3702
+sympy/physics/units/systems/length_weight_time.py,sha256=DXIDSWdhjfxGLA0ldOziWhwQjzTAs7-VQTNCHzDvCgY,7004
+sympy/physics/units/systems/mks.py,sha256=Z3eX9yWK9BdvEosCROK2qRKtKFYOjtQ50Jk6vFT7AQY,1546
+sympy/physics/units/systems/mksa.py,sha256=U8cSI-maIuLJRvpKLBuZA8V19LDRYVc2I40Rao-wvjk,2002
+sympy/physics/units/systems/natural.py,sha256=43Odvmtxdpbz8UcW_xoRE9ArJVVdF7dgdAN2ByDAXx4,909
+sympy/physics/units/systems/si.py,sha256=YBPUuovW3-JBDZYuStXXRaC8cfzE3En3K5MjNy5pLJk,14478
+sympy/physics/units/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/physics/units/tests/test_dimensions.py,sha256=lzkgGfEXMHxB8Izv7nRTN2uOEPh65LXPYaG8Kr5H05o,6122
+sympy/physics/units/tests/test_dimensionsystem.py,sha256=s2_2RAJwOaPOTvyIiAO9SYap374ytZqWbatWkLCnbSU,2717
+sympy/physics/units/tests/test_prefixes.py,sha256=Y3vlIReWGu8bwwZTrNGZSVoWYjhzgUZC33CDeyIvw48,2238
+sympy/physics/units/tests/test_quantities.py,sha256=XPuM6ul7XrUHvQE7F8rvpoCaxT9N6TM2gX99qUM4gTA,19758
+sympy/physics/units/tests/test_unit_system_cgs_gauss.py,sha256=JepTWt8yGdtv5dQ2AKUKb9fxpuYqLWOp0oOmzov9vfY,3173
+sympy/physics/units/tests/test_unitsystem.py,sha256=1Xh78_8hbv-yP4ICWI_dUrOnk3cimlvP_VhO-EXOa7Q,3254
+sympy/physics/units/tests/test_util.py,sha256=76PaLp_Cd9BAiry6VcWUD4Hrr68D6lTOkScWcLyhmL0,9355
+sympy/physics/units/unitsystem.py,sha256=mLuXftt3003OLk3knUGdYb1XfGbQa6vp-pHcenL11-o,7593
+sympy/physics/units/util.py,sha256=GU43MjXBRl5fm0CrU1fhFsZi9Q7wPG0NSJVJb1Oc_Y8,9885
+sympy/physics/vector/__init__.py,sha256=jZmrNB6ZfY7NOP8nx8GWcfI2Ixb2mv7lXuGHn63kyOw,985
+sympy/physics/vector/dyadic.py,sha256=CuAkSBgnatfnZQ2gBazZQC1DBVXbksiFWWqxu2w3C2U,18042
+sympy/physics/vector/fieldfunctions.py,sha256=H3S7oeLHaInZns9ko04BPOcSSOK2M5hBK71jB813ExY,8610
+sympy/physics/vector/frame.py,sha256=J1sY-qaAamcZFKP26x54Q9TWITXBgjmE3v5PiEaFri4,57260
+sympy/physics/vector/functions.py,sha256=b4dHZOxbvS77SMcSlCV2GTaOzWj0TQiUtDaO_dhj3Uw,24810
+sympy/physics/vector/point.py,sha256=W1H6Jd-ZAIHY8yKO3YWj-vdEp7qI2yoglzk5HuT-y2E,20569
+sympy/physics/vector/printing.py,sha256=a1N-wziCnt4gHtY9luqe-CDW9aAtpZ0FcvWwQ0hMEEo,11790
+sympy/physics/vector/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/physics/vector/tests/test_dyadic.py,sha256=vCSLxo0pynrHrCCo7S4925lgRhoSm_Mr5YhIh_1bYcw,4265
+sympy/physics/vector/tests/test_fieldfunctions.py,sha256=FUjh18QzB6dXSau9iHutb36o28faSa7T9sB0icpja-M,5825
+sympy/physics/vector/tests/test_frame.py,sha256=S5xn5Q9dMj_ACIS9ff7ACTBS7sFFovi9DIov-crUsko,29683
+sympy/physics/vector/tests/test_functions.py,sha256=qHGT0RR-vkAp1oF30TFNgaeuOGvXdZnK2aKZuRgrZHg,21127
+sympy/physics/vector/tests/test_output.py,sha256=hgqlE-_zN_EPE_gIZ_v2uXB1y2auo39hReWpvFUm2QQ,2612
+sympy/physics/vector/tests/test_point.py,sha256=5CTzT3a-igd33auAra4uusm0PYUc_whPtV7KAoZ4g5w,12373
+sympy/physics/vector/tests/test_printing.py,sha256=qVBjz4f3TtDrduUYLNDrvlrzBVMBDqLo27JWsFHdX18,10967
+sympy/physics/vector/tests/test_vector.py,sha256=bqU1ltS6UGbSo74KXMtvP1mOpqKQ6XSV19Wjw2QoNFc,10259
+sympy/physics/vector/vector.py,sha256=R7P63QPZee0lfHHVDU7Uq91ZJs5ewjVK5HVj9HHNeQo,24874
+sympy/physics/wigner.py,sha256=L5QyzD4yH4SyTk7-WCCd07XK0_Pd9nz7sHwo2zOWV7I,39588
+sympy/plotting/__init__.py,sha256=hAdOjai8-laj79rLJ2HZbiW1okXlz0p1ck-CoeNU6m8,526
+sympy/plotting/backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/plotting/backends/base_backend.py,sha256=aof5cs8mWG6fl87DadR5sZBjY8ssMelOwKFWi27-FO0,14911
+sympy/plotting/backends/matplotlibbackend/__init__.py,sha256=Mzsz43gkanid12G8qnOcwJNbbvqf6eGppn-IZyJCMto,162
+sympy/plotting/backends/matplotlibbackend/matplotlib.py,sha256=9efu7ST_D3M-_fepZCPTcy8TdYEIX0PCkyocDGVfbPE,12548
+sympy/plotting/backends/textbackend/__init__.py,sha256=nnV_C7JJ_kwGcQe2C-tpnK635W8vTuIf5Grvvmur0rQ,92
+sympy/plotting/backends/textbackend/text.py,sha256=1ukArjwwQWUED9SB-1dmkB6YL5EcJ2rUosUf_NcBpXs,803
+sympy/plotting/experimental_lambdify.py,sha256=xcBhlvZ2h20aI1MpUN6qAEpO075Dv132AWbQJ7l3Wzg,22828
+sympy/plotting/intervalmath/__init__.py,sha256=fQV7sLZ9NHpZO5XGl2ZfqX56x-mdq-sYhtWEKLngHlU,479
+sympy/plotting/intervalmath/interval_arithmetic.py,sha256=jv5YolNs6pOawIhuSsTBVwgkgmdOFwPrGN_1KtjfcIs,15570
+sympy/plotting/intervalmath/interval_membership.py,sha256=1VpO1T7UjvPxcMySC5GhZl8-VM_DxIirSWC3ZGmxIAY,2385
+sympy/plotting/intervalmath/lib_interval.py,sha256=WY1qRtyub4MDJaZizw6cXQI5NMEIXBO9UEWPEI80aW8,14809
+sympy/plotting/intervalmath/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/plotting/intervalmath/tests/test_interval_functions.py,sha256=gdIo5z54tIbG8hDaGd3I8rBDP67oetMZWWdM-uvt1ec,9862
+sympy/plotting/intervalmath/tests/test_interval_membership.py,sha256=D1KjcrLxAwOmDEUqA-8TCqkFWGtmeerR9KwmzS7tyjk,4216
+sympy/plotting/intervalmath/tests/test_intervalmath.py,sha256=ndBMczrs6xYMN5RGnyCL9yq7pNUxrXHTSU1mdUsp5tU,9034
+sympy/plotting/plot.py,sha256=umvG47eIqOdEUo5qki3jDkS6LYKnTWFTZ5qzxZZBgAw,40882
+sympy/plotting/plot_implicit.py,sha256=1xIIr4eV1gIU4SkQ2k54PBZGUgYMCgsPttY-9uZ2eZM,7330
+sympy/plotting/plotgrid.py,sha256=QZmbxY-fcgPuseYLnKVDFsoH6m57Cosvy4W7l4jIqWw,6115
+sympy/plotting/pygletplot/__init__.py,sha256=DM7GURQbdSfcddHz23MxOShatBFc26tP_sd3G8pGCQE,3732
+sympy/plotting/pygletplot/color_scheme.py,sha256=NgPUamkldygfrIPj0LvC_1AzhscVtg18FSudElvFYB8,12522
+sympy/plotting/pygletplot/managed_window.py,sha256=N7AKtM7ELfIJLie6zvI-J6-OQRBnMZu6AL1USz7hFEk,3072
+sympy/plotting/pygletplot/plot.py,sha256=s-5AJB0KelHs9WGoFIVIdYrOoMXfdpnM5-G2cF8xzDQ,13352
+sympy/plotting/pygletplot/plot_axes.py,sha256=Q9YN8W0Hd1PeflHLvOvSZ-hxeLU4Kq3nUFLYDC0x0E8,8655
+sympy/plotting/pygletplot/plot_camera.py,sha256=myYtKbv1ov_ltgR34hf8BR76t3AwTSu4QFUY5YY-e1E,3928
+sympy/plotting/pygletplot/plot_controller.py,sha256=MroJJSPCbBDT8gGs_GdqpV_KHsllMNJpxx0MU3vKJV8,6941
+sympy/plotting/pygletplot/plot_curve.py,sha256=YwKA2lYC7IwCOQJaOVnww8AAG4P36cArgbC1iLV9OFI,2838
+sympy/plotting/pygletplot/plot_interval.py,sha256=doqr2wxnrED4MJDlkxQ07GFvaagX36HUb77ly_vIuKQ,5431
+sympy/plotting/pygletplot/plot_mode.py,sha256=Djq-ewVms_JoSriDpolDhhtttBJQdJO8BD4E0nyOWcQ,14156
+sympy/plotting/pygletplot/plot_mode_base.py,sha256=3z3WjeN7TTslHJevhr3X_7HRHPgUleYSngu6285lR6k,11502
+sympy/plotting/pygletplot/plot_modes.py,sha256=gKzJShz6OXa6EHKar8SuHWrELVznxg_s2d5IBQkkeYE,5352
+sympy/plotting/pygletplot/plot_object.py,sha256=qGtzcKup4It1CqZ2jxA7FnorCua4S9I-B_7I3SHBjcQ,330
+sympy/plotting/pygletplot/plot_rotation.py,sha256=KGMCTyaSh5_UQD9FKGCIpoI3-CbbOhXxTcjAc1o5-PU,1445
+sympy/plotting/pygletplot/plot_surface.py,sha256=C0q9tzDmxzC1IpWiNKY4llzcopx6dhotGOLpK1N9m3s,3803
+sympy/plotting/pygletplot/plot_window.py,sha256=5boC2Fkmk46-gWGqWzdTkPmTMNHHOpA0CnB9q946Hwc,4643
+sympy/plotting/pygletplot/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/plotting/pygletplot/tests/test_plotting.py,sha256=NisjR-yuBRJfQvjcb20skTR3yid2U3MhKHW6sy8RE10,2720
+sympy/plotting/pygletplot/util.py,sha256=mzQQgDDbp04B03KyJrossLp8Yq72RJzjp-3ArfjbMH8,4621
+sympy/plotting/series.py,sha256=hPkMicAi29RjoJkFpMCt1CRn0xdBVYU1wLniigHgCaM,96568
+sympy/plotting/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/plotting/tests/test_experimental_lambdify.py,sha256=EYshdXA5tAGWolaDX-nHAolp7xIJN4Oqb1Uc1C1IhJI,3127
+sympy/plotting/tests/test_plot.py,sha256=mXiNdG-dHkK1iJ_moNlehZQU3i8mCtUKhVJdTxSxjdA,48217
+sympy/plotting/tests/test_plot_implicit.py,sha256=wurrO7ntsHb4tWYPVs5VogRrtcylevu0EceCSEwiWQg,5799
+sympy/plotting/tests/test_region_and.png,sha256=EV0Lm4HtQPk_6eIWtPY4TPcQk-O7tkpdZIuLmFjGRaA,6864
+sympy/plotting/tests/test_region_not.png,sha256=3O_9_nPW149FMULEcT5RqI2-k2H3nHELbfJADt2cO8k,7939
+sympy/plotting/tests/test_region_or.png,sha256=5Bug09vyog-Cu3mky7pbtFjew5bMvbpe0ZXWsgDKfy4,8809
+sympy/plotting/tests/test_region_xor.png,sha256=kucVWBA9A98OpcR4did5aLXUyoq4z0O4C3PM6dliBSw,10002
+sympy/plotting/tests/test_series.py,sha256=Nwa6__YMoWCiY0mYSlvJPPnlvtfOYLACHR1RbkopMc0,65638
+sympy/plotting/tests/test_textplot.py,sha256=VurTGeMjUfBLpLdoMqzJK9gbcShNb7f1OrAcRNyrtag,12761
+sympy/plotting/tests/test_utils.py,sha256=FkcYZAFT8TnHRIbkknx9NvA3-LgR0ua7WFyzQEPsVIE,3602
+sympy/plotting/textplot.py,sha256=Xc-bWvzVOq8QUn_BxDlJv9bryCpgzsgV73XoQQwVj0Q,5075
+sympy/plotting/utils.py,sha256=Cimno9MQGjcbe4rQ6TN86r4rM2t62CgARqPtgF0mhR8,12259
+sympy/polys/__init__.py,sha256=qXmDNr7noCUAtIs0rJJRHHFbHjy3uHIvXZDajcSePc4,5577
+sympy/polys/agca/__init__.py,sha256=fahpWoG_0LgoqOXBnDBJS16Jj1fE1_VKG7edM3qZ2HE,130
+sympy/polys/agca/extensions.py,sha256=YmtFs9C0s-4DNMXFtdX1hYVNlby18mAJzhJ5Aqickrw,9388
+sympy/polys/agca/homomorphisms.py,sha256=gaMNV96pKUuYHZ8Bd7QOs27J1IbbJgkEjyWcTLe8GFI,21937
+sympy/polys/agca/ideals.py,sha256=S6rBl3H-hdeI44ZbELwjjt1rKlrhK11AKb8Aas-OtCE,11073
+sympy/polys/agca/modules.py,sha256=PeA138FHsCfUn8vkdrjPa92xmzq7Qqk0PrdYwVoNqf0,47240
+sympy/polys/agca/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/polys/agca/tests/test_extensions.py,sha256=i3IHQNXQByFMCvjjyd_hwwJSCiUj0z1rRwS9WFK2AFc,6455
+sympy/polys/agca/tests/test_homomorphisms.py,sha256=m0hFmcTzvZ8sZbbnWeENwzKyufpE9zWwZR-WCI4kdpU,4224
+sympy/polys/agca/tests/test_ideals.py,sha256=w76qXO-_HN6LQbV7l3h7gJZsM-DZ2io2X-kPWiHYRNw,3788
+sympy/polys/agca/tests/test_modules.py,sha256=HdfmcxdEVucEbtfmzVq8i_1wGojT5b5DE5VIfbTMx3k,13552
+sympy/polys/appellseqs.py,sha256=hWeDKsKnJuAuPN_5IU6m1okurAq9xMt3LQgMehcvBKQ,8305
+sympy/polys/benchmarks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/polys/benchmarks/bench_galoispolys.py,sha256=8RtN9ZQga2oxscVPPkMGB29Dz8UbskMS2szYtqZ69u0,1502
+sympy/polys/benchmarks/bench_groebnertools.py,sha256=YqGDCzewRszCye_GnneDXMRNB38ORSpVu_Jn0ELIySo,803
+sympy/polys/benchmarks/bench_solvers.py,sha256=gLrZguh6pE0E4_vM2GeOS5bHnrcSUQXqD0Qz9tItfmo,446778
+sympy/polys/compatibility.py,sha256=ti_gJSz8zB1sf-oIyfXAw4xkDGkQaZs_34RSC-6HldY,58373
+sympy/polys/constructor.py,sha256=rv8hQgE8-P9QXUtOQmlEiyA4XD-fb1Qzd8bvH3UHQls,11373
+sympy/polys/densearith.py,sha256=6wB6DJWKNB0RA7Tdg7jMgRIERjZdtAp32OQhIQ6wmV4,34114
+sympy/polys/densebasic.py,sha256=Kag6cqlxHhHUMYUXpr9GHLWh4E1Mnw2Esoh6zx9r14E,35954
+sympy/polys/densetools.py,sha256=A0Z1E16eVx577zw84m8KZgT5o6dbDXXonW8TqfISJZY,29746
+sympy/polys/dispersion.py,sha256=s6GIYnGA6U9jhGP7YXQQS8G3byG4-kPbr55BR6p-iz4,5740
+sympy/polys/distributedmodules.py,sha256=t8pLIgDQs_dMecGXwybVYoLavofEy2DXhFS8N5gj5SU,21827
+sympy/polys/domainmatrix.py,sha256=FmNqklNFQR1WrQYtP2r7jypw2IQadNKGP14EaUaxUqI,310
+sympy/polys/domains/__init__.py,sha256=T6qPNkU1EJ6D5BnvyJSXJv4zeJ5MUT5RLsovMkkXS9E,1872
+sympy/polys/domains/algebraicfield.py,sha256=JXK_o6BdQbYT_0gOLALNOLsmqgfV46DRFJb7cANJgAM,23051
+sympy/polys/domains/characteristiczero.py,sha256=vHYRUXPrfJzDF8wrd1KSFqG8WzwfITP_eweA-SHPVYA,382
+sympy/polys/domains/complexfield.py,sha256=VbhX6yigmU2OLhof8qEpPp1XZhzzkfXfcuZevx1LZsk,6159
+sympy/polys/domains/compositedomain.py,sha256=DAo2ISA9XdOnYzFu8azuPIQAT9fyVwSM8Pe425vmvww,1642
+sympy/polys/domains/domain.py,sha256=aj9HOp98G2m25wRzSDj4lWzoRLGyXDsuevzScdHjV6o,40850
+sympy/polys/domains/domainelement.py,sha256=IrG-Mzv_VlCAmE-hmJVH_d77TrsfyaGGfJVmU8FFvlY,860
+sympy/polys/domains/expressiondomain.py,sha256=AB7Mnd6kOLaS_yG4lMXZTpVPUuAHGcrd6RAjjFSVxNc,7593
+sympy/polys/domains/expressionrawdomain.py,sha256=cXarD2jXi97FGNiqNiDqQlX0g764EW2M1PEbrveImnY,1448
+sympy/polys/domains/field.py,sha256=fR0l6wZIv02UMJ5rioEP910jGUViVx38EdwtJuJX5vg,2959
+sympy/polys/domains/finitefield.py,sha256=1DHkfrCz08KXLEz7in4IK71B8udHPZZAWv50-jV5_vQ,10654
+sympy/polys/domains/fractionfield.py,sha256=BoqUCbVggwaoqGCVy_r42MIVHuAV-P3gONFVZIlWojU,5848
+sympy/polys/domains/gaussiandomains.py,sha256=YrcHg4QSPgIRW-Ft8J84q1zwmU-DVJuAscWXnVCQ9CI,19598
+sympy/polys/domains/gmpyfinitefield.py,sha256=WgSLnALNOVVKH931WpVT28ZWDilsrTDG8DyMee2xR94,437
+sympy/polys/domains/gmpyintegerring.py,sha256=qJ7w8K40cfzhztZtOuWlIL2DXa642xJcKIIxoAOlcSs,3037
+sympy/polys/domains/gmpyrationalfield.py,sha256=dZjrfcWaUA-BHUtutzLOWPlOSNLYzBqSFeukER6L_bA,3178
+sympy/polys/domains/groundtypes.py,sha256=hAla27w5ekoJR_8c-1Yo8vrEgIIggPc615tfe1udc9A,2102
+sympy/polys/domains/integerring.py,sha256=4oy49xTi8hV6qh8CWUAoBcgn2aJqgqwyh7bZBsjGfwI,7442
+sympy/polys/domains/modularinteger.py,sha256=k6gskb0eypXdrKJRxR3l_75mVjmICGnaOy7FdRMwG8E,6042
+sympy/polys/domains/mpelements.py,sha256=PREDWq_WA5er2zzftt5Lg0opnWzyFBsIkLKcyGXUVz0,5042
+sympy/polys/domains/old_fractionfield.py,sha256=TUVxyL2fS4QF3kgyW5EGfkl91ir3S1klu08UfZr3GuI,6226
+sympy/polys/domains/old_polynomialring.py,sha256=KQcH58oHnHzOpDdWojZiLlHDqrAiUd4OAaBIZigqpyc,15982
+sympy/polys/domains/polynomialring.py,sha256=OLPcwkyrbkt5pNZ342o3Ziv9TCrlpU3h18s9R-cxqXI,6223
+sympy/polys/domains/pythonfinitefield.py,sha256=lWp266ErnuUPuo7k8ju3z2S5IresFInpJAl4Ihsq0pI,453
+sympy/polys/domains/pythonintegerring.py,sha256=EH5s6nwaxmeaScLER_FfqPdhyuJnbjtBslHmgyOyEPs,2962
+sympy/polys/domains/pythonrational.py,sha256=M3VUGODh3MLElePjYtjt9b02ReMThw-XXpuQTkohgNs,548
+sympy/polys/domains/pythonrationalfield.py,sha256=x8BPkGKj0WPuwJzN2py5l9aAjHaY4djv65c4tzUTr3Y,2295
+sympy/polys/domains/quotientring.py,sha256=2NOUkkbFj4514qkDUszl6hl1EQuPikn3QEoQ1sDobGI,5911
+sympy/polys/domains/rationalfield.py,sha256=D-pA-iHDHbOi6fivqSrJnfmH2JTrheKJQ9ZFXXN5ftM,5982
+sympy/polys/domains/realfield.py,sha256=OdLfE_9OVxvQlnQiT4faJxuB6dZwnXdIt-o-5wGYroA,6456
+sympy/polys/domains/ring.py,sha256=p66U2X58acSHLHxOTU6aJZ0Umdcu1qiGIUDtV8iJCD0,3236
+sympy/polys/domains/simpledomain.py,sha256=_K-Zz8Opf505r3eHSrbPAlnGiGSjY_O4Cwa4OTeOSoY,369
+sympy/polys/domains/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/polys/domains/tests/test_domains.py,sha256=XJwTGPM-8W4Rn76-cec99rpUIDDjP-7HTFs7AKGNrEw,51028
+sympy/polys/domains/tests/test_polynomialring.py,sha256=8nNFKuQeicwiBk6pnqPLNk0cnI61iK8Dpl-TZifvORc,2895
+sympy/polys/domains/tests/test_quotientring.py,sha256=BYoq1CqI76RDSm0xQdp1v7Dv1n5sdcmes-b_y_AfW-0,1459
+sympy/polys/euclidtools.py,sha256=hAsNupzfR-07fTwFvTF2yDabyKMm_PLgFC8KX9c2CAo,41808
+sympy/polys/factortools.py,sha256=CupycipegP1IGCYPY9eY2T8f_6h4gmr6qId1A4UDJvk,43034
+sympy/polys/fglmtools.py,sha256=Z3VS_IKsZu1o3g22KPTIH1feNL8cTpieaNWvLuILmK4,4298
+sympy/polys/fields.py,sha256=RdSDkOls6n87yvHG1KXFnGng0JS3SAcUAlz4tTb1RZE,21250
+sympy/polys/galoistools.py,sha256=Z3ed_A0Nohj9RzuM3kom7-ay4MnzIHppwgV2QpONuTo,57238
+sympy/polys/groebnertools.py,sha256=NhK-XcFR9e4chDDJJ-diXb7XYuw9zcixFA_riomThPM,23342
+sympy/polys/heuristicgcd.py,sha256=rD3intgKCtAAMH3sqlgqbJL1XSq9QjfeG_MYzwCOek0,3732
+sympy/polys/matrices/__init__.py,sha256=ZaPJMi8l22d3F3rudS4NqzSt0xwxbs3uwnQwlhhR91o,397
+sympy/polys/matrices/_dfm.py,sha256=_3p5Hb9e86uBG_r__Ee6BAZxj4KiRhcf2uN3XnjHxwQ,32971
+sympy/polys/matrices/_typing.py,sha256=Egp2nMOaq-oJCW0bgNDxy1Bx6evTl8eMTpf4mzIw1s4,407
+sympy/polys/matrices/ddm.py,sha256=eMKUy8X1kQTEG1l7Fx_L4LG9Jqs9l0KEwlYQwlcl6Do,32362
+sympy/polys/matrices/dense.py,sha256=RYdogVHeWZoeO94Oal1mf1sJvj-JmyS_baRi8-d9Rms,23217
+sympy/polys/matrices/dfm.py,sha256=Fj_uF4FskrwcBDNuRSV--AozCP2cYkUz-BMitcMlkRE,1241
+sympy/polys/matrices/domainmatrix.py,sha256=MvjWRzQ4lKzX2rCl8mRtpiIXSe641_x6OMrTr8iscPA,115928
+sympy/polys/matrices/domainscalar.py,sha256=sPXC-it46yun2r_tJkun4MIuVQQyQMQTVsTedId8Rj4,3778
+sympy/polys/matrices/eigen.py,sha256=glArxs9_rTrE_ssz2fd2gKCTsguSyEHwoeQP82tmIcM,3015
+sympy/polys/matrices/exceptions.py,sha256=ay3Lv21X3QqszysBN71xdr9KGQuC5kDBl90a2Sjx6pM,1351
+sympy/polys/matrices/linsolve.py,sha256=p86jlJP9h3CxZX92xk2sh1WAvKBkB5_YD55k1oYpmGI,7534
+sympy/polys/matrices/lll.py,sha256=p5q_rb5QvAuHsGRZAzP2Jf_h2vdC_Be4Q62lkaYxW-c,3550
+sympy/polys/matrices/normalforms.py,sha256=6MJfVbiwlZuCk-0fYiyOMuqkPdVpyzTNdDP2s6jkRw0,17122
+sympy/polys/matrices/rref.py,sha256=5YK_phB382K9JFVIydlH2IYpziirEDUnKzyl5BfS2_o,15532
+sympy/polys/matrices/sdm.py,sha256=bb2fIO42KjyJuEuMBkiDFn_qLJVjD4gsRgWZ6GOmTHw,64293
+sympy/polys/matrices/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/polys/matrices/tests/test_ddm.py,sha256=BcnUntz3XR2Xyff02l4Mk2EsxwYlIBzM4lFSRo9oZT8,16699
+sympy/polys/matrices/tests/test_dense.py,sha256=ETC2h5yLKsPJ5GAgx_RUcWyR63iZx81pbtOZiWty1r0,9516
+sympy/polys/matrices/tests/test_domainmatrix.py,sha256=4QttFR5PYJg6Xn37VXdxmv1w9Xkm82fF-M-KRQIe0RU,50006
+sympy/polys/matrices/tests/test_domainscalar.py,sha256=HEFEKX5tP6SZ83_91nvLmFqgHxbVdpqOP4ZwzfFbHnc,3740
+sympy/polys/matrices/tests/test_eigen.py,sha256=T1lYZeW-0NwDxDOG6ZJLr-OICfxY2wa0fVHV2V6EXSk,3200
+sympy/polys/matrices/tests/test_fflu.py,sha256=7En_75QemdtHvR7lUyZrcHiV9Dv2rswBuuKVOPWi1pk,8542
+sympy/polys/matrices/tests/test_inverse.py,sha256=5DT5qvfS3MlrgNgeHnG8GLjgLnmhsxj94yR3cbtmEO8,5247
+sympy/polys/matrices/tests/test_linsolve.py,sha256=ur1BFzlIQyBrO_-aL71lXsLC67nfec9G5o-mzW_TFY4,3373
+sympy/polys/matrices/tests/test_lll.py,sha256=RGYTDGbLfFvAMTESv-S1kqSWzwtOIjmguqXO3yGCjH4,6624
+sympy/polys/matrices/tests/test_normalforms.py,sha256=x1-vkjXq3LGblUSJFz7z73IVmaxqZbVzWoGj9XS-yXw,5106
+sympy/polys/matrices/tests/test_nullspace.py,sha256=eAEDPlnVkKfFM9jn1gztOUQTos1Sm9qwH10C-t9uLUE,5418
+sympy/polys/matrices/tests/test_rref.py,sha256=mWTIfKAUP3vkGKhffCrPHuC_0DdF-iH41cchlSN8Pqc,25982
+sympy/polys/matrices/tests/test_sdm.py,sha256=fSE3bQlDU-atzTFTgp4AgAS3QL-7rvb_61stj3QGBnU,13415
+sympy/polys/matrices/tests/test_xxm.py,sha256=X9sP_VfPi4bUR7V1ZLq6ZHXPOBUA7tE5-gQULang_Ag,29778
+sympy/polys/modulargcd.py,sha256=gOwojISiV8IncaEHZJZMHOC1odN7xRKN5L1Ls4szROI,58729
+sympy/polys/monomials.py,sha256=6cDCTVNNPDeee5bt0RQnGuYnsO_fefioHA5mEDKHSuA,18458
+sympy/polys/multivariate_resultants.py,sha256=6bwdF-lcUqtKoVDrnOKhm_PyPfo8w0Yyy_GtESatQFw,15248
+sympy/polys/numberfields/__init__.py,sha256=ZfhC9MyfGfGUz_DT_rXasB-M_P2zUiZXOJUNh_Gtm8c,538
+sympy/polys/numberfields/basis.py,sha256=IPA6cSwz-53ClQwo-wkmRzfx9pRX4iBhiggdLMVSgJ0,8261
+sympy/polys/numberfields/exceptions.py,sha256=kHb-aB4eBzG3SsIpYtL5wLExDSb8lIOpNq0tk3guFIA,1594
+sympy/polys/numberfields/galois_resolvents.py,sha256=OL3u-G6sCwvZuBuuYQO0QpL-wWxtjxFaBjVQhtiQ_Z8,25006
+sympy/polys/numberfields/galoisgroups.py,sha256=c4s6z_mEUkoWKezFrfjKiU2tZnEnxR4m1LYaagicVno,20671
+sympy/polys/numberfields/minpoly.py,sha256=0F7QVSOk8WqViD50jKtT-94C6kQyuXPBCyNZPTf0ScA,27791
+sympy/polys/numberfields/modules.py,sha256=4MJykT6gtT_LC033LWsHT_CM7nEydLISAdQ0yA_bhkQ,69243
+sympy/polys/numberfields/primes.py,sha256=UXOkuMdnamVvHPQZxwilCbhdwNNNS7zQ4bwSFc5xGgk,23984
+sympy/polys/numberfields/resolvent_lookup.py,sha256=qfLNKOz_WjtXwpVlfzy8EkD4gw12epx9npE9HsjyIdg,40411
+sympy/polys/numberfields/subfield.py,sha256=Huh9iq2CDQN8p0fs2bSe-yEoB_V1OVr8rH58rJT4crk,16668
+sympy/polys/numberfields/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/polys/numberfields/tests/test_basis.py,sha256=96BJ7e4oPDKXyvlRrUkiQxmHyjRGpOkAC7R3ln-jgNE,4580
+sympy/polys/numberfields/tests/test_galoisgroups.py,sha256=3LFuMbV92VBFlqqEqjh37oQvmG8cgZ0pFxDCXUoYRL4,5036
+sympy/polys/numberfields/tests/test_minpoly.py,sha256=HjlmPWX90Cb-XK5G1H0-uirOiHdgTu7R8qpcG5ZI5iw,23115
+sympy/polys/numberfields/tests/test_modules.py,sha256=GU4166j_hMlB22uWxxIjV_ON8RsyvpaN7Ly3eK8_m8Y,22926
+sympy/polys/numberfields/tests/test_numbers.py,sha256=M0vZIBnjPBHV4vFUnPBILaqiR_cgSuU50kFB-v7l1gA,5988
+sympy/polys/numberfields/tests/test_primes.py,sha256=JhcAkaQMgjkOSziQ2jZApJ8b8oviil5cUy0hfFqNmZg,9779
+sympy/polys/numberfields/tests/test_subfield.py,sha256=EpBexToc17YwLB4-n6nE_HaleU8AcFGi5OpDReW7q0k,12776
+sympy/polys/numberfields/tests/test_utilities.py,sha256=rQGEJWctcfzjUtMwRuyCHerSqEsoP5C3z1bnddJA17o,3661
+sympy/polys/numberfields/utilities.py,sha256=IHKmfafE9tMGammfdtkyR4_IHb0mON-OBwitE0Ss1R0,13087
+sympy/polys/orderings.py,sha256=IFieyj4LkFa7NDiGTZD3VwUY7mSN3GEjThKk0z5WJ1s,8500
+sympy/polys/orthopolys.py,sha256=PIJg_Kml8MxmJs5QPCjGmRLjjlE_4QKhsWhU7-an7x0,10181
+sympy/polys/partfrac.py,sha256=ptYpXsp8dYyyeiPnLU-rdQ-uv3-GAvDnN79E81C68y8,14695
+sympy/polys/polyclasses.py,sha256=Zc9sjiwVxsM6wM8h9KCFP2Pjlfl4XA3MjC6NlguQzqM,96529
+sympy/polys/polyconfig.py,sha256=mgfFpp9SU159tA_PM2o04WZyzMoWfOtWZugRcHnP42c,1598
+sympy/polys/polyerrors.py,sha256=xByI-fqIHVYsYRm63NmHXlSSRCwSI9vZUoO-1Mf5Wlk,4744
+sympy/polys/polyfuncs.py,sha256=OEZpdYeHQADBJYqMw8JAyN4sw-jsJ6lzVH6m-CCoK8g,8547
+sympy/polys/polymatrix.py,sha256=iNa-EyIrzv7ZeXMaP_PjojgNd29AnIotZE3NeF2te44,9771
+sympy/polys/polyoptions.py,sha256=yG1k4ZPN2ufwpZ4lI4Sn8DSIHvd7EwDUHUaz64HxlUM,21806
+sympy/polys/polyquinticconst.py,sha256=mYLFWSBq3H3Y0I8cx76Z_xauLx1YeViC4xF6yWsSTPQ,96035
+sympy/polys/polyroots.py,sha256=bJToZlR6WZNl9fNxkIJxiPt3XoDQ_K6Pb3UOCBPfsKM,37025
+sympy/polys/polytools.py,sha256=BUwK8wJApazWeKQ3t27yg-HTMnwiv9ScPiavk2n02Rk,212876
+sympy/polys/polyutils.py,sha256=M8V-D4NkfMlsJe4LeAZzljrM4BKp10Qvuuutd8kmp3E,17248
+sympy/polys/puiseux.py,sha256=wc_5w5RyXHfAwC9Dde-6ecPm9y1z5DAmfthtSZ53CqA,26518
+sympy/polys/rationaltools.py,sha256=8vbkg3nuBxbd4ztR7lOj2jTF9taKUKTPah_fD38Ex6c,2838
+sympy/polys/ring_series.py,sha256=7DijmljyAaQrupWB0JmaNwGm3wNTstnEsBln-o1uX1M,59877
+sympy/polys/rings.py,sha256=KVdA3C04G2H3YN81rM-8ORsUHqmktIrz0S0tfwLwN4g,86080
+sympy/polys/rootisolation.py,sha256=QKCYgD4kMNBtSLYkUim8MXHa7louMtlO0riwKTiXRRI,64341
+sympy/polys/rootoftools.py,sha256=bMcVUcIwqaM643UU1WTCNmPmDFRepZEq9Xfdr9mm63Q,43092
+sympy/polys/solvers.py,sha256=FareKqDVVC6P2I4yjudi_3CS3kx0SbmAz3k7zHkETgE,13520
+sympy/polys/specialpolys.py,sha256=B2vijl75zgUKUTY1HCqjB9BTDFf3FM8ugwkKGTB83XA,11038
+sympy/polys/sqfreetools.py,sha256=oRFlOLhcXz5OKjc9SQtOuEhMvacvkHyTSEqhk6Snh1Y,19876
+sympy/polys/subresultants_qq_zz.py,sha256=VFKTAe3iGMCimLkc9GeuwG5o4SB0x2T5kRwxe4A5BDo,88241
+sympy/polys/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/polys/tests/test_appellseqs.py,sha256=YTERuRr30QtfxYR0erXvJG8D-INe9RaMFAF0ZM-H4Ks,3820
+sympy/polys/tests/test_constructor.py,sha256=t6JpLbIdy2hcHF4_s_Xiav0kVc4OOsH5EFg6IXOiwmI,7220
+sympy/polys/tests/test_densearith.py,sha256=ptFGN7ovPH3dqT5khr6Wm8CR6a1WOR7Fi8dj8SuBvJs,40827
+sympy/polys/tests/test_densebasic.py,sha256=FcjAfZngYRQSWJ__BrBPITAUYjMNkS_pOtGyuJv_Bs0,21590
+sympy/polys/tests/test_densetools.py,sha256=o7HZfOw4Xn71RpCDhk98srNipA3zXfikAP_lV0gShlM,26241
+sympy/polys/tests/test_dispersion.py,sha256=S3diTgz7WKH88ulGNT3ijiQ8Y53Rpul6jATBJMGyQdw,3182
+sympy/polys/tests/test_distributedmodules.py,sha256=dXmjhozX5Yzb7DsrtbdFTqAxi9Z1UZNJvGxj-vHM7cM,7639
+sympy/polys/tests/test_euclidtools.py,sha256=vEyj48eIjm6-KRQtThNfI4ic_VDNB6l7jMouxJAF9HE,19482
+sympy/polys/tests/test_factortools.py,sha256=K5_R-01Muc_45XOtolk_tQswE2l6tGrlOJ9zA_aNVYE,24903
+sympy/polys/tests/test_fields.py,sha256=DUvcax7WGtydkLDXq0aQ9Ksc6PkdV67NPZCvqTYN2w8,9869
+sympy/polys/tests/test_galoistools.py,sha256=0oN3eSWvV99juZSXco6Ek9n6s6BFOmOE4UIEhyZnQQs,28532
+sympy/polys/tests/test_groebnertools.py,sha256=ZWHBcCCOVNwDxuJWg1WPo0krTHx1m1wTPi2cOYPsAT4,18584
+sympy/polys/tests/test_heuristicgcd.py,sha256=87Yc0on955VExFyOgJuxBZhsIMFz1Vq4vclIVkQ--cE,4297
+sympy/polys/tests/test_hypothesis.py,sha256=LdokFa3JrQ59_umY15x21QSScPjJoCl8RxHRfn1NUOc,1109
+sympy/polys/tests/test_injections.py,sha256=EONGggBUNWaVSwi817CzLBYJgkTehFq8-m-Qdqes984,1286
+sympy/polys/tests/test_modulargcd.py,sha256=2SjCEjCPkf1-u-Co5vuVg5sJmfBLSY3gkFLicLl4g6E,9043
+sympy/polys/tests/test_monomials.py,sha256=YcMBU1qe6g7EJojtV89dfJZmdXsXVTSly2J5cF6SD6o,11083
+sympy/polys/tests/test_multivariate_resultants.py,sha256=DJu8CcZ3xwx8njpjDeSOyhyxeqZYmhfb7dkSCU-ll7Y,9501
+sympy/polys/tests/test_orderings.py,sha256=bdsIsqJTFJCVyZNRMAGVDXVk79ldw9rmAGejS_lwKP0,4254
+sympy/polys/tests/test_orthopolys.py,sha256=Ob5Osxd8hwebEjK3dDMarZ2VDXzl3pdsEdz_-kMa80M,6560
+sympy/polys/tests/test_partfrac.py,sha256=VfWOx30fZu_avMbWqxtbLDcLi-9x6iuQmLfyatnFc3Y,7838
+sympy/polys/tests/test_polyclasses.py,sha256=EuoT3b9a9KRTQFe95MjGrQIqAhRgLG5qUo42FtkM-Js,14765
+sympy/polys/tests/test_polyfuncs.py,sha256=VbgCgCRE06dtSY9I9GSdPH9T52ETYYoxk4J3N1WBtd4,4520
+sympy/polys/tests/test_polymatrix.py,sha256=pl2VrN_d2XGOVHvvAnaNQzkdFTdQgjt9ePgo41soBRs,7353
+sympy/polys/tests/test_polyoptions.py,sha256=z9DUdt8K3lYkm4IyLH1Cv-TKe76HP-EyaRkZVsfWb6U,12416
+sympy/polys/tests/test_polyroots.py,sha256=m0rnjXMqX59XdFn9X4rRtZJjI39vBN-MAt9cpQszq-I,26803
+sympy/polys/tests/test_polytools.py,sha256=JfaZlcguRIh6ZVNpkIUc2sSRJX_Hq6aluW7HxjCDWO4,139212
+sympy/polys/tests/test_polyutils.py,sha256=Qs3QQl0WYmTnkYE2ovTxdLeu6DYnWO_OoUmLwNDZzSw,11547
+sympy/polys/tests/test_puiseux.py,sha256=4PnBdJuYDWku8l6Jg2Dsn7umg14ldYBdvHqtVaaELbE,7304
+sympy/polys/tests/test_pythonrational.py,sha256=vYMlOTuYvf-15P0nKTFm-uRrhUc-nCFEkqYFAPLxg08,4143
+sympy/polys/tests/test_rationaltools.py,sha256=wkvjzNP1IH-SdubNk5JJ7OWcY-zNF6z3t32kfp9Ncs0,2397
+sympy/polys/tests/test_ring_series.py,sha256=j88HGfiJ9ZL114UezdJtC5aWtox8RG0I2Qyq9gLnkCE,31697
+sympy/polys/tests/test_rings.py,sha256=q8A_CeerrzGqVf1Ol-O-Jc-R7q-2X119YSNMnds3Ccs,48735
+sympy/polys/tests/test_rootisolation.py,sha256=x-n-T-Con-8phelNa05BPszkC_UCW1C0yAOwz658I60,32724
+sympy/polys/tests/test_rootoftools.py,sha256=1cv7M6EQ3mK7NhcwKqbIvour1l_QYtW_zr6vyZ3rzs0,23414
+sympy/polys/tests/test_solvers.py,sha256=kKyEvmqt91HHuAV42DS26B8fPDFQ2Ghtb_Nf3-1eWyI,13644
+sympy/polys/tests/test_specialpolys.py,sha256=v1i0RMNlixxe2EbwqoE-UlV7a2KY-md4T7thhUhWSx0,5031
+sympy/polys/tests/test_sqfreetools.py,sha256=m8ipJE28YC9eOrsVVAqxduCsw4iOW-s_nw76y0E8wUs,4886
+sympy/polys/tests/test_subresultants_qq_zz.py,sha256=bSFOjbtyIClbJHLDvvzgmOgoZyC_5Vdpe7vtW9VGU_s,13219
+sympy/printing/__init__.py,sha256=Hh-z1idh92pk17XjdXkjYwb8cJ5coEr4ZJQGcpE3d9I,2215
+sympy/printing/aesaracode.py,sha256=_iHvF9avR9MGiOnxLIwog2M5rUwhLRt-bdsbcJHeO_s,18921
+sympy/printing/c.py,sha256=qX8EkxVT5Z2Hncz8DJh8iar_jBuVcRDEiIt1d6jcerE,27011
+sympy/printing/codeprinter.py,sha256=QUAWM6H45YBkd7fX6jXXO3j-tfVaHhzxbXn7OnSm0Es,42371
+sympy/printing/conventions.py,sha256=hvN1VMZE5krMj8FL4AAuxAO0xCwhAugBFWrFQ0355AY,2586
+sympy/printing/cxx.py,sha256=vCQyzT-1eNLLDJy4NBwCp5X5OCoPOZ9icsx8YifaPsc,6123
+sympy/printing/defaults.py,sha256=YitLfIRfFH8ltNd18Y6YtBgq5H2te0wFKlHuIO4cvo8,135
+sympy/printing/dot.py,sha256=W0J798ZxBdlJercffBGnNDTp7J2tMdIYQkE_KIiyi3s,8274
+sympy/printing/fortran.py,sha256=zHVQMphFeeIGl-1x29Hw5Lekxi5NWou-V3Kn4O0oHQQ,28635
+sympy/printing/glsl.py,sha256=wsjPcpyzk92m4I2_re0cn3JwEjPmRlmlVWX9owhzM5w,20310
+sympy/printing/gtk.py,sha256=ptnwYxJr5ox3LG4TCDbRIgxsCikaVvEzWBaqIpITUXc,466
+sympy/printing/jscode.py,sha256=BORODo9Aio62FKh1HYlluG-IxtJC26_-IWrxAiEtmr8,11981
+sympy/printing/julia.py,sha256=V_Qbld0MOebIkT4VnmyP6VdIbgrPaqllgjkv7eSq8bk,23541
+sympy/printing/lambdarepr.py,sha256=BCx4eSdG8MQ8ZSUV1lWEd3CzbZ4IiMid-TTxPoV6FHU,8305
+sympy/printing/latex.py,sha256=jCqXe1XOWLNUcRNzsHOY3CMvbkPBKjf8tD4ii6PVKxU,123669
+sympy/printing/llvmjitcode.py,sha256=NjjHbgheH4j6SboFIDfrrIogkcrJRkW_kjlzM8DpDmQ,17127
+sympy/printing/maple.py,sha256=aG7t4RUEVojSFBVA14GDBzU702KtTcolTCelXozNiN0,10571
+sympy/printing/mathematica.py,sha256=to8LmNkhiP0ACh-Vun-hfaMnLFSEc0mF2OmZnQmihE8,12720
+sympy/printing/mathml.py,sha256=UT7g45oLTqvnrC1IUZeqywHTV6-LUClfuOF_U4AMlaI,76634
+sympy/printing/numpy.py,sha256=Kpq-ySkQSRKYCxtgQZEi_4lj3EmK7FgvbDJTzvB77Tc,21049
+sympy/printing/octave.py,sha256=1ofeBaIcoJfgzImezfPed9Z4dZ6Tk5gVbEQbr02TcLI,25469
+sympy/printing/precedence.py,sha256=hKIin20F4LJp2l5yhSQ-WAegTRHYQLhccABC1_ciI-U,5522
+sympy/printing/pretty/__init__.py,sha256=pJTe-DO4ctTlnjg1UvqyoeBY50B5znFjcGvivXRhM2U,344
+sympy/printing/pretty/pretty.py,sha256=KmEXRb6XEtI5tiQYssueibKKrJVF1F1mwrF1uHGxmpM,105024
+sympy/printing/pretty/pretty_symbology.py,sha256=v4FyDz_03mbSGX7tGni8Zw2L2qKTRGvmCIL85ttXg0s,24112
+sympy/printing/pretty/stringpict.py,sha256=UbG55kC4ve8-Dby_v0cm8AXUdLcu4YDLXVnA8F_iV8Y,19158
+sympy/printing/pretty/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/printing/pretty/tests/test_pretty.py,sha256=K2Xt--ptdxWLuUmtYJnuyh81ZrGIDRqNM_iOUADAdjA,187716
+sympy/printing/preview.py,sha256=3KacgHEch3KKJZeKc7kvD-L4pfftI8Gm62fx9-Vipak,14089
+sympy/printing/printer.py,sha256=z1phdIHrrcU2cyD-1GaBXREmhkcVl8bxeIWZrGAlczg,15868
+sympy/printing/pycode.py,sha256=LsDnREZEJVw0zsy_AjRSkYER-acomwQiDicrWBmnoW8,27048
+sympy/printing/python.py,sha256=oxGJhNQUXRKjHSEgqroGAyB-A4ZgJQqA_o7C8uXA1U8,3347
+sympy/printing/pytorch.py,sha256=HXEAoLbgbuE-SYj0hvDHeJ0zgzOVDBkK5qWErLCJhNo,10620
+sympy/printing/rcode.py,sha256=uBazXZwSRd95UUQjNoD6qLlpun7Xwlm8cfLG4qYhy3Y,14101
+sympy/printing/repr.py,sha256=GLO6WFOunZ8k0Om0g1VbGW2Y5uOP0IVEo_pIGO8HoNw,11545
+sympy/printing/rust.py,sha256=5Dh_zFxXZRVzbfHGowRQd9moUjzJZ7G2PXjxqsmBBw0,20831
+sympy/printing/smtlib.py,sha256=u2rVmprPITJdLq79FTYm7Fl-osteadr1JyXeQXlZW68,21752
+sympy/printing/str.py,sha256=dTK_CdT-Mm_zRoOL-Mwb4ocBA__h2wBFAAg6VvAiebQ,33239
+sympy/printing/tableform.py,sha256=pz4hXDLZ1IlqU8eOo0XBX1xaALYMqe4qHPUnEVq0mAE,11797
+sympy/printing/tensorflow.py,sha256=QmWoLUKpefBYJZ-J0Ei0NHHrU7Livp8Td4trWTDFzy8,8161
+sympy/printing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/printing/tests/test_aesaracode.py,sha256=dX-SKJHfx9m91NSlt7pQ5Gul0x7fig3XZsHCt2kvtRc,21340
+sympy/printing/tests/test_c.py,sha256=etIEgJwlGWxtH6VRYg3Zkjyw_ktYRYj_-mvEMQehmjI,31227
+sympy/printing/tests/test_codeprinter.py,sha256=rVimgQTdJchy7PsjdZupQmXfqi6FBme2BPwnz7Z5WeQ,2142
+sympy/printing/tests/test_conventions.py,sha256=yqPpU3F0WcbxImPBBAHd3YEZpkFGfcq_TLK4WN_gtP4,5257
+sympy/printing/tests/test_cupy.py,sha256=E2T4a82XITbWAssmRZD4zCQdMCrpaZFCAjGXthUp8cY,1882
+sympy/printing/tests/test_cxx.py,sha256=0XQPQdtDCgEKVfpuelEB-79f7d2fe9QPgEKCCYVAI_w,3183
+sympy/printing/tests/test_dot.py,sha256=TSAtgGIgK_JbY-RMbQgUvnAI87SJqeJOqzcLjAobhKM,4648
+sympy/printing/tests/test_fortran.py,sha256=d5uy1zp0IgaBPupzXpNuk169YZYygnodPWhNRcvUtAQ,35456
+sympy/printing/tests/test_glsl.py,sha256=cfog9fp_EOFm_piJwqUcSvAIJ78bRwkFjecwr3ocCak,28421
+sympy/printing/tests/test_gtk.py,sha256=94gp1xRlPrFiALQGuqHnmh9xKrMxR52RQVkN0MXbUdA,500
+sympy/printing/tests/test_jax.py,sha256=5sOhmFNadFAKT2FumDuk5UqgOc0e0cYkRnJTczClnG8,11062
+sympy/printing/tests/test_jscode.py,sha256=ObahZne9lQbBiXyJZLohjQGdHsG2CnWCFOB8KbFOAqQ,11369
+sympy/printing/tests/test_julia.py,sha256=7KSmbPi_0J2ZSL2fI_xLWqoR9Gy73LfNtzFANHS8EiM,14014
+sympy/printing/tests/test_lambdarepr.py,sha256=DMoIfRNmUkF0KUXoNnJ_skNPU42tJ2xlEvqCT2GxwaA,6947
+sympy/printing/tests/test_latex.py,sha256=xHG_gSlEsD-QkOIiHUyWE4zb0brJxwgwGs1jJBvvOA0,138061
+sympy/printing/tests/test_llvmjit.py,sha256=EGPeRisM60_TIVgnk7PTLSm5F-Aod_88zLjHPZwfyZ8,5344
+sympy/printing/tests/test_maple.py,sha256=dhcz2bqapB_qMyBLMgsgnvVRIcHQ-HmxvAxC_Y0Z3q8,13078
+sympy/printing/tests/test_mathematica.py,sha256=oNNTHZzHviNi_ckua2issBb05IS7GaYyluBJiCjhGoM,10954
+sympy/printing/tests/test_mathml.py,sha256=yVIJYHlFNLbt1qtbKrqjxB2P88dsD6AtS9EVsDi_vEw,99434
+sympy/printing/tests/test_numpy.py,sha256=JZwyiFUS7Vfiwn3j1ogF31PJLJRzH57dtEHq_ujV9wQ,11715
+sympy/printing/tests/test_octave.py,sha256=WOJpsuGhMYLw2ikjwdTV6kVac6-I3xkjZ7qvUVheFbU,18545
+sympy/printing/tests/test_precedence.py,sha256=Za6JCTVvRGZhNY2dqiA8XpUpR5YGck7Op2cXiV78dZA,4067
+sympy/printing/tests/test_preview.py,sha256=dSVxiGqdNR6gbF40V4J2tGhQ-T4RDvSyGypHvYcPDYM,988
+sympy/printing/tests/test_pycode.py,sha256=txwQ1jKkQNZSOXoKw9w2n-_IeIdd-QUjh7WYvOgi1rA,18363
+sympy/printing/tests/test_python.py,sha256=HN7JkzQcKSnB6718i7kaEJZ5pYMqu56z1mSmHQGzY4k,8128
+sympy/printing/tests/test_rcode.py,sha256=TXyl449eCO4J-P3DQb3w9FWvMqOdXmfuiXgyBg_inQQ,13781
+sympy/printing/tests/test_repr.py,sha256=5XmDdIDlQlCWckWq8H95Fw82h-oDxrRpMWZePb6hHa4,12980
+sympy/printing/tests/test_rust.py,sha256=ClZ30PUmZj1ZoBWL2zSt4SsWQS0WB8FrFSQE-w3bxjU,11988
+sympy/printing/tests/test_smtlib.py,sha256=S-42OTOUGkZ-k17qCQ36DYgT-tyOeYqDCvtXzrL2Kzo,22553
+sympy/printing/tests/test_str.py,sha256=QhRuH-hwpXRcPTmKClxqBv8HQdlpNjR4dMXf_XJ3jCs,43523
+sympy/printing/tests/test_tableform.py,sha256=Ff5l1QL2HxN32WS_TdFhUAVqzop8YoWY3Uz1TThvVIM,5692
+sympy/printing/tests/test_tensorflow.py,sha256=-56L5IdYszZy9CGNxS8Ix8UaFStZudFuKQlyyz6Rzzs,17100
+sympy/printing/tests/test_theanocode.py,sha256=E36Fj72HxMK0e1pKTkoTpv9wI4UvwHdVufo-JA6dYq0,21394
+sympy/printing/tests/test_torch.py,sha256=yOtB4yl1DjbTbb8I_t2bdW8fAafVC5G8ubeIJpVLPus,16842
+sympy/printing/tests/test_tree.py,sha256=_8PGAhWMQ_A0f2DQLdDeMrpxY19889P5Ih9H41RZn8s,6080
+sympy/printing/theanocode.py,sha256=d1Aznwfqz6lFR680RGrIf5ht2AH0Ei7pz-7yGZt-CLY,19094
+sympy/printing/tree.py,sha256=tQNjLV3_c3QUUce068AbzAuCiUIJb47l_7F_TYxxFUQ,3868
+sympy/release.py,sha256=oitamisYLp3lrFI3uGv-5ZCJIeYOT9gZLcszUmVNhw8,23
+sympy/sandbox/__init__.py,sha256=IaEVOYHaZ97OHEuto1UGthFuO35c0uvAZFZU23YyEaU,189
+sympy/sandbox/indexed_integrals.py,sha256=svh4xDIa8nGpDeH4TeRb49gG8miMvXpCzEarbor58EE,2141
+sympy/sandbox/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/sandbox/tests/test_indexed_integrals.py,sha256=UK2E2wg9EMwda4Vwpzyj3rmXs6ni33HqcbyaqAww6ww,1179
+sympy/series/__init__.py,sha256=DYG9oisjzYeS55dIUpQpbAFcoDz7Q81fZJw36PRGu14,766
+sympy/series/acceleration.py,sha256=Phe8jpZ4uiS4vYAzh8PiUoHKVUjyu5K9MoAnZX3pV_w,3365
+sympy/series/approximants.py,sha256=tE-hHuoW62QJHDA3WhRlXaTkokCAODs1vXgjirhOYiQ,3181
+sympy/series/aseries.py,sha256=cHVGRQaza4ayqI6ji6OHNkdQEMV7Bko4f4vug2buEQY,255
+sympy/series/benchmarks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/series/benchmarks/bench_limit.py,sha256=2PtdeeJtD6qyEvt9HFNvyTnMM8phFZRjscgnb4fHndU,173
+sympy/series/benchmarks/bench_order.py,sha256=iC8sQJ0lLlTgiXltAyLzSCQ-3490cf-c6NFiIU44JSk,207
+sympy/series/formal.py,sha256=9HJp9fcNX-MxcIfTtMptdKEyAw6cQQ3LyyzMyEt-9aw,51668
+sympy/series/fourier.py,sha256=H3zDg_S5D0Qeewp-o87_t_30TIg3rad83bzAoz9yp_E,22941
+sympy/series/gruntz.py,sha256=fhHr8w8SeMd-6GKjHmlwajd4FUmzeYo97AA3C_q0lKg,23497
+sympy/series/kauers.py,sha256=PzD0MATMNjLjPi9GW5GQGL6Uqc2UT-uPwnzhi7TkJH8,1720
+sympy/series/limits.py,sha256=hoSFWORWR-DodSf6Po93uK_09JUePhNvI60YsH6V4CI,13307
+sympy/series/limitseq.py,sha256=WM1Lh3RXhSZM1gQaJrhWnUtYEgJunLujIEw1gmtVhYw,7752
+sympy/series/order.py,sha256=1JjdsH2zvP8X1rf75qpfIB-iI70fkcH9CmJsXsRqSxY,19558
+sympy/series/residues.py,sha256=k46s_fFfIHdJZqfst-B_-X1R-SAWs_rR9MQH7a9JLtg,2213
+sympy/series/sequences.py,sha256=WLubAZr5AevpllgI4b6WmIfXRX88QNVCpMGBofGkcqo,35543
+sympy/series/series.py,sha256=PveJ6LibsrDX-mymTbV7teNggnsX0cfaoGMLAP0KAIo,1863
+sympy/series/series_class.py,sha256=033NJ5Re8AS4eq-chmfct3-Lz2vBqdFqXtnrbxswTx0,2918
+sympy/series/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/series/tests/test_approximants.py,sha256=KViHMW1dPXn7xaPYhtTQ9L_WtLLkoIic6yfFnwZ8Q70,1012
+sympy/series/tests/test_aseries.py,sha256=5yWntog5ogRZrmjF3ZhY4e-d2mHYC1Ocs7IXRRFQrtI,2377
+sympy/series/tests/test_demidovich.py,sha256=JGYacqJMEqHS6oT2AYs9d7iutIEb32PkJs9EJqOHxcQ,4947
+sympy/series/tests/test_formal.py,sha256=TpMws7tgQHaokLrzEKZdlOcn6f04WIZhUqreaOOJ0kU,22496
+sympy/series/tests/test_fourier.py,sha256=-RnlhZUZJuctdE3pEtVMeGzCfyWzR1TFeojDhpJqyWo,5908
+sympy/series/tests/test_gruntz.py,sha256=3yPq8ksMGM7x4VQIfsFkk3JIgHlj-g1kJJBwIL76uPg,16445
+sympy/series/tests/test_kauers.py,sha256=Z85FhfXOOVki0HNGeK5BEBZOpkuB6SnKK3FqfK1-aLQ,1102
+sympy/series/tests/test_limits.py,sha256=YuwcBy8Atf-UGP8Li2sFU0guV_ZsjHqx-IdPwI6M3EA,48638
+sympy/series/tests/test_limitseq.py,sha256=QjEF99sYEDqfY7ULz1qjQTo6e0lIRUCflEOBgiDYRVA,5691
+sympy/series/tests/test_lseries.py,sha256=GlQvlBlD9wh02PPBP6zU83wmhurvGUFTuCRp44B4uI4,1875
+sympy/series/tests/test_nseries.py,sha256=uzhzYswSOe9Gh_nWKeO69tvGPMLd-9tqk4HBYX8JIm4,18284
+sympy/series/tests/test_order.py,sha256=AUlRkYKCUIs4DyT6g94ZGmjzT2fqHutPXOUGhpz4mb0,17901
+sympy/series/tests/test_residues.py,sha256=pT9xzPqtmfKGSbLLAxgDVZLTSy3TOxyfq3thTJs2VLw,3178
+sympy/series/tests/test_sequences.py,sha256=Oyq32yQZnGNQDS2uJ3by3bZ-y4G9c9BFfdQTcVuW2RM,11161
+sympy/series/tests/test_series.py,sha256=yPqSIfTytdiIYlYR9yvK7uS4IwF1fctpDiiktEnwvec,17006
+sympy/sets/__init__.py,sha256=3vjCm4v2esbpsVPY0ROwTXMETxns_66bG4FCIFZ96oM,1026
+sympy/sets/conditionset.py,sha256=mhodBVrMqJ6W5H8CuaFhO3FO9VdJifOEPjjFmV9lT2I,7792
+sympy/sets/contains.py,sha256=AlsfOc_6V0TH_6G7XTPIXhDywgtg3ECdjCTfSOmPC-E,1829
+sympy/sets/fancysets.py,sha256=tZ4wVasc937Yr0VkQuLVHe75Falcr72Nrkhk89178QQ,48187
+sympy/sets/handlers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/sets/handlers/add.py,sha256=_ucFvxuDv9wsmKxGkCDUERtYk3I_tQxjZjY3ZkroWs0,1863
+sympy/sets/handlers/comparison.py,sha256=WfT_vLrOkvPqRg2mf7gziVs_6cLg0kOTEFv-Nb1zIvo,1601
+sympy/sets/handlers/functions.py,sha256=jYSFqFNH6mXbKFPgvIAIGY8BhbLPo1dAvcNg4MxmCaI,8381
+sympy/sets/handlers/intersection.py,sha256=oYPmrx3FAkGLVWT3EjSimeMfsGqPsqVnpJm5UxQzuCM,17514
+sympy/sets/handlers/issubset.py,sha256=azka_5eOaUro3r3v72PmET0oY8-aaoJkzVEK7kuqXCA,4739
+sympy/sets/handlers/mul.py,sha256=XFbkOw4PDQumaOEUlHeQLvjhIom0f3iniSYv_Kau-xw,1842
+sympy/sets/handlers/power.py,sha256=84N3dIus7r09XV7PF_RiEpFRw1y5tOGD34WKzSM9F-4,3186
+sympy/sets/handlers/union.py,sha256=lrAdydqExnALUjM0dnoM-7JAZqtbgLb46Y2GGmFtQdw,4225
+sympy/sets/ordinals.py,sha256=GSyaBq7BHJC3pvgoCDoUKZQ0IE2VXyHtx6_g5OS64W4,7641
+sympy/sets/powerset.py,sha256=vIGnSYKngEPEt6V-6beDOXAOY9ugDLJ8fXOx5H9JJck,2913
+sympy/sets/setexpr.py,sha256=jMOQigDscLTrFPXvHqo1ODVRG9BqC4yn38Ej4m6WPa0,3019
+sympy/sets/sets.py,sha256=-iuLnPWLunCa0oOErHELO9EkLZXs6L2AFWQgkCFbJcA,81202
+sympy/sets/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/sets/tests/test_conditionset.py,sha256=UeutWuBCT5PZicNkkl9E94pREnU5CvLGWUfmRS29PcU,11370
+sympy/sets/tests/test_contains.py,sha256=ec6WRzriwV9nurz3jS9IXEqtfL1pZedtJFp--fSsBvY,1561
+sympy/sets/tests/test_fancysets.py,sha256=oiuu5PKNrDeDO-NtgsE4CpkwQaS7JNgCYuSyc1ykKKE,51938
+sympy/sets/tests/test_ordinals.py,sha256=L4DYc6ByQMDwJGFzJC3YhfSrVk5auW7pf4QYpJ5xY7w,2637
+sympy/sets/tests/test_powerset.py,sha256=nFvDGlhAf0wG-pZnPkgJjfwDHrTwdro3MYIinwyxn94,4805
+sympy/sets/tests/test_setexpr.py,sha256=E--SjYVzrmau0EbD8g4NTqp6aLD8qHzIuI7sAfuWxpY,14797
+sympy/sets/tests/test_sets.py,sha256=oMtqcr9gr68itfWH4j18POID8tD0hAZUV8HCz7-KKj0,68544
+sympy/simplify/__init__.py,sha256=MH1vkwHq0J5tNm7ss8V6v-mjrDGUXwfOsariIwfi38c,1274
+sympy/simplify/_cse_diff.py,sha256=Nq1gXn27o1v83t__SQUuacnOohhywa39ucPaR2jD518,10479
+sympy/simplify/combsimp.py,sha256=UzgG6eC_eIzieMS3j0oQFJnS5XkZ1gxNqOSzBqJcIFQ,3604
+sympy/simplify/cse_main.py,sha256=tcUmXXFGIZyoX4PvBEmZ-YYm-CBLXoAyGLHverxP23o,31310
+sympy/simplify/cse_opts.py,sha256=ZTCaOdOrgtifWxQmFzyngrLq9uwzByBdiSS5mE-DDoE,1618
+sympy/simplify/epathtools.py,sha256=fV3oeD2J3LJRQ4YoTV6gq3yFT_NSZi-7xxKnrX-2KJA,10122
+sympy/simplify/fu.py,sha256=exevmk1p4YgEAO-MmTgh7cG7cyVMMF8p7vZ1ymwwKiI,62208
+sympy/simplify/gammasimp.py,sha256=yzfkD_q1Zxu1eMCZuprmA3VzZXhecX3K0xdZlUdYlcY,18485
+sympy/simplify/hyperexpand.py,sha256=sTWd1-VeLr0NTr-cm6nftjmO_gVPqa1P9ud_rvSZS54,84420
+sympy/simplify/hyperexpand_doc.py,sha256=E8AD0mj8ULtelDSUkmJKJY7kYm5fVfCL4QH_DX65qEw,521
+sympy/simplify/powsimp.py,sha256=aCkX2zxgOm1S9oWc260KrzhSwcJw8p3JEMZ-vkmUapM,26754
+sympy/simplify/radsimp.py,sha256=VP83Ufl_9DUtmeHCRXSmOHqdg9zDsPoQJ_7eUyCiwpI,41649
+sympy/simplify/ratsimp.py,sha256=vTu0t0k1FDFTofl4mwcK9NuTMNZ20IsL8fIyFJRFNkg,7682
+sympy/simplify/simplify.py,sha256=3rK7cCfkh1svliMVsCuTv9_aQDz3nmZvA_HRAvmNkSo,73330
+sympy/simplify/sqrtdenest.py,sha256=MsTyPUcEhiMf51fpk6e5grlqudU-LMAHOuatPCxo5uA,21600
+sympy/simplify/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/simplify/tests/test_combsimp.py,sha256=O95WSxCvo2fDQs-UlarAcSf0_8M3PuTR76lhREDoNA8,2958
+sympy/simplify/tests/test_cse.py,sha256=JOjH5G6GPfeaKpKdeeKL1vvHgbt8TGxTkqmH2e1ovY8,25516
+sympy/simplify/tests/test_cse_diff.py,sha256=Y_zYZpldwjUoWiTTpFMlw4PXkqNp9r9Zwrw46gkmNoY,7275
+sympy/simplify/tests/test_epathtools.py,sha256=ugsQlfuK6POiixdeit63QovsVAlG5JyCaPlPp0j35LE,3525
+sympy/simplify/tests/test_fu.py,sha256=X2NNsynwefg2aH5GhyxQItL80fKPZ9md6nydMEedWbQ,19410
+sympy/simplify/tests/test_function.py,sha256=gzdcSFObuDzVFJDdAgmERtZJvG38WNSmclPAdG8OaPQ,2199
+sympy/simplify/tests/test_gammasimp.py,sha256=32cPRmtG-_Mz9g02lmmn-PWDD3J_Ku6sxLxIUU7WqxE,5320
+sympy/simplify/tests/test_hyperexpand.py,sha256=y3lxd97UZ1BkrrZe0r2l6MM8zNABTE_L4KtxFwmdzeQ,41043
+sympy/simplify/tests/test_powsimp.py,sha256=FWI_K8nozwYzhrhY1Q0CZkf6n88hFR0jjuYRvQnMius,14375
+sympy/simplify/tests/test_radsimp.py,sha256=Gf6Tf7-lb5G8gqF6hJA6kPrZNFES6fCz7_-ls7TFUfY,19128
+sympy/simplify/tests/test_ratsimp.py,sha256=bv-K60A7m2on-U9szzaeYO7Hlp1EK5P0HvBBO59oyas,2198
+sympy/simplify/tests/test_rewrite.py,sha256=LZj4V6a95GJj1o3NlKRoHMk7sWGPASFlw24nsm4z43k,1127
+sympy/simplify/tests/test_simplify.py,sha256=QkiaVVj0nqHXvu1lUUYZfYZ6_Ods6DfiBwFiqAJKSoo,41928
+sympy/simplify/tests/test_sqrtdenest.py,sha256=4zRtDQVGpKRRBYSAnEF5pSM0AR_fAMumONu2Ocb3tqg,7470
+sympy/simplify/tests/test_trigsimp.py,sha256=vG5PDTDNOuFypT7H9DSMjIollPqkKdNhWv5FBj6vFnE,19949
+sympy/simplify/traversaltools.py,sha256=pn_t9Yrk_SL1X0vl-zVR6yZaxkY25D4MwTBv4ywnD1Y,409
+sympy/simplify/trigsimp.py,sha256=t36QKVf_0yqVCNo1hUBlBp5locL0sMH1AlsAwQCzpLQ,46857
+sympy/solvers/__init__.py,sha256=nb1LceF2MwvULXsCN8VUq7X2tVgZOPsmWYHGFszIdW4,2333
+sympy/solvers/benchmarks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/solvers/benchmarks/bench_solvers.py,sha256=ZVK2TIW0XjWRDBex054ymmVlSBQw-RIBhEL1wS2ZAmU,288
+sympy/solvers/bivariate.py,sha256=Ku4Ttid3yU3CIc4IPfJ7bedLtXVaGKvFOonEIlZrXXw,17870
+sympy/solvers/decompogen.py,sha256=dWQla7hp7A4RqI2a0qRNQLWNPEuur68lD3dVTyktdBU,3757
+sympy/solvers/deutils.py,sha256=jukqDw6JGZfl36HRFjZIX_A0_iarmTawI0Up7z5tQDc,10315
+sympy/solvers/diophantine/__init__.py,sha256=I1p3uj3kFQv20cbsZ34K5rNCx1_pDS7JwHUCFstpBgs,128
+sympy/solvers/diophantine/diophantine.py,sha256=n74XrMIW6ZwrAfaVVks7nwB01GClI0SYdvTe5K90Jnc,122482
+sympy/solvers/diophantine/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/solvers/diophantine/tests/test_diophantine.py,sha256=N7ZCyNVfSV0JzAKbnc_8YbUFq5ZkiDLnO6MxxMxCG90,43335
+sympy/solvers/inequalities.py,sha256=kz6HzAytg4V2eqSKwGzbJuYyFfgj6bFSUgk1i15zVp0,33189
+sympy/solvers/ode/__init__.py,sha256=I7RKwCcaoerflUm5i3ZDJgBIOnkhBjb83BCHcVcFqfM,468
+sympy/solvers/ode/hypergeometric.py,sha256=t9KN5AdB7yF-rRoatEBzUYBcrwvIrKm83KBDa5BJYqY,10048
+sympy/solvers/ode/lie_group.py,sha256=C2HoOVtDbIT2ryx4TzEvQU46Yqc8LurTBBtjv5m2-BQ,39175
+sympy/solvers/ode/nonhomogeneous.py,sha256=Wi6UxjYNAPcfJsEzKHNvIJ8zhJ7-ZOkqccCR93MpUuM,17875
+sympy/solvers/ode/ode.py,sha256=9UQ0bqcrFOsGuSxGfRJpd2CllIWfiUYZPC2-A7Crefo,145379
+sympy/solvers/ode/riccati.py,sha256=3ZrkCy3ufXCyCx8gJfAuxyCOgbOLEHtvTh2VgJhA7Mk,30736
+sympy/solvers/ode/single.py,sha256=yBpPVFK3LsCf07dDb9_x6tzhp5d4ln_xIpMZpP2Ryrc,109465
+sympy/solvers/ode/subscheck.py,sha256=CIPca_qTxL9z5oaD2e2NrgME0eVQgF9PabZndcVqHZM,16130
+sympy/solvers/ode/systems.py,sha256=Kok2AMO4YEKX38fi2LrxLm5zpTcNXz398b7OBvrUezU,71467
+sympy/solvers/ode/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/solvers/ode/tests/test_lie_group.py,sha256=vg1yy_-a5x1Xm2IcVkEi5cD2uA5wE5gjqpfBwkV1vZc,5319
+sympy/solvers/ode/tests/test_ode.py,sha256=bEcTi9zA5TooKOE9duFtd6TAVRvLPrO92arX7fF85-Q,48508
+sympy/solvers/ode/tests/test_riccati.py,sha256=a2_pXzCFb9WDtT_kdxYkfLd-PG5xvs4rQn_vpFk-O9s,29348
+sympy/solvers/ode/tests/test_single.py,sha256=sEvhXws920Oe_IuvmBIYM5iPViR6I3njZNgJlc8sMC4,100200
+sympy/solvers/ode/tests/test_subscheck.py,sha256=Gzwc9h9n6zlNOhJ8Qh6fQDeB8ghaRmgv3ktBAfPJx-U,12468
+sympy/solvers/ode/tests/test_systems.py,sha256=PeIEHOx8-eZQNuqOfhjTvGEeFSVriLlHShPmy84mde4,129087
+sympy/solvers/pde.py,sha256=V2jxgmmepng2ofFFDVOsBHWqf-IUQCgIz4lXzhBUeyg,34913
+sympy/solvers/polysys.py,sha256=4CCK3FNhl-K6B4bYF_goSrAq1JOMubl6KsmaB_5R2f4,27168
+sympy/solvers/recurr.py,sha256=DyssZuOyemoC6J1cWq635O7zkg1WLHrR7KGoM-gNy0g,25389
+sympy/solvers/simplex.py,sha256=peRv44aDM30U_0wk8xZv3t6M_cpm_a9hBALiyr7zndY,35276
+sympy/solvers/solvers.py,sha256=xsSlQaj0XaunexmhfQZZI_uiRXHETmaUab9hgZrmmbU,138454
+sympy/solvers/solveset.py,sha256=6VxsiKcn4fwdJGYXA8k1si5zvYs6vNrSTtLcmSKpjMk,151683
+sympy/solvers/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/solvers/tests/test_constantsimp.py,sha256=9Feugsg9jD2BwQiG4EFpb9fORyst6JdBmZqq2GaOgH8,8707
+sympy/solvers/tests/test_decompogen.py,sha256=7GUsDQQZtYbZIK0p0UxsOuNEJxEt4IHeOSsem_k-k0U,2943
+sympy/solvers/tests/test_inequalities.py,sha256=whg3vGXEYxeIHNQS4yBeB9VQpoYWnfw5NBS4xLiqDJ8,21025
+sympy/solvers/tests/test_numeric.py,sha256=pKLBJuf4lGCewf5DgBjvH5T9phf6ilkyW1gB2R-5SzA,4734
+sympy/solvers/tests/test_pde.py,sha256=UGP3uWjF8pKQgfPifmdfvS5URVmzSg6m2NkS7LGzmio,9257
+sympy/solvers/tests/test_polysys.py,sha256=bK2ckIhQvbJCc6_qsUOAuAEyTc5CR8J2yiqN4MFOgpM,15266
+sympy/solvers/tests/test_recurr.py,sha256=-OeghSg16GFN70y_RUXC6CF6VU_b7NXaKDbejtRSocg,11418
+sympy/solvers/tests/test_simplex.py,sha256=pG7j7KxXrlK8K_fF04XH_mvMzwEOopSBpJZiagKjyNs,9037
+sympy/solvers/tests/test_solvers.py,sha256=eXM6AT2upxlRC7S2l1YxUSS6jJNM42PxzYCTz4C4vmc,107765
+sympy/solvers/tests/test_solveset.py,sha256=lOQ4hG7Dg6yuDgFriKIlvWdzEumehgL08Srsh4JwDHY,148480
+sympy/stats/__init__.py,sha256=9pY3OMdvAIeJ_Q1ZqynOZ8hHWFFrrxOx0qBHKkGfHCg,8487
+sympy/stats/compound_rv.py,sha256=SO1KXJ0aHGbD5y9QA8o6qOHbio3ua8wyO2Rsh0Hnw48,7965
+sympy/stats/crv.py,sha256=jd8iemE41aW-byXgFDYKaMv2VOOUnyUtiMx_QAXI-n4,21028
+sympy/stats/crv_types.py,sha256=qXYxtvJPg4ORJI7AxIkRhwnJ6lcz3sVBWf4toQy9vvA,122371
+sympy/stats/drv.py,sha256=Zu8IK9yt69XJFKt-ShoJfZbvZ-CGMwvrKNiXvi6q_n4,11994
+sympy/stats/drv_types.py,sha256=2jL6QYa9lAlbvTxvx9BXdfwU6PRt0uzV3CVXRIeZ5k0,19865
+sympy/stats/error_prop.py,sha256=a-H6GZEidsiP_4-iNw7nSD99AMyN6DNHsSl0IUZGIAs,3315
+sympy/stats/frv.py,sha256=vZROeD6DSVGX0kfOL_yOds3pZgjSiXFX-bMZtSUkVMA,16874
+sympy/stats/frv_types.py,sha256=Xkc3MU5dFLajPajIStW_lV4qiuiHg86rBo45zX_oGLk,23348
+sympy/stats/joint_rv.py,sha256=DcixlO2Ml4gnwMmZk2VTegiHVq88DkLdQlOTQ57SQtc,15963
+sympy/stats/joint_rv_types.py,sha256=PUatR4WcPHmAHadt8iRh5xYh5NJigzYh-EoAMR5blDw,30575
+sympy/stats/matrix_distributions.py,sha256=3OricwEMM_NU8b2lJxoiSTml7kvqrNQ6IUIn9Xy_DsY,21953
+sympy/stats/random_matrix.py,sha256=NmzLC5JMDWI2TvH8tY6go8lYyHmqcZ-B7sSIO7z7oAk,1028
+sympy/stats/random_matrix_models.py,sha256=7i5XAUYxt-ekmP5KDMaytUlmCvxglEspoWbswSf82tE,15328
+sympy/stats/rv.py,sha256=rmjdVpsvJrqtMgnreuT_7lU5S_V2nkvlrpUvA7zCWLM,54579
+sympy/stats/rv_interface.py,sha256=0ZSplwmkEtio_UTlh7bqSK_1aILgvk2JTfZ-CkOcfAc,13935
+sympy/stats/sampling/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/stats/sampling/sample_numpy.py,sha256=B4ZC7ZBrSD6ICQT468rOy-xrOgQDuecsHa0zJesAeYE,4229
+sympy/stats/sampling/sample_pymc.py,sha256=9g-n04aXSFc6F7FJ5zTYtHHL6W8-26g1nrgtamJc3Hw,2995
+sympy/stats/sampling/sample_scipy.py,sha256=ysqpDy8bp1RMH0g5FFgMmp2SQuXGFkcSH7JDZEpiZ8w,6329
+sympy/stats/sampling/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/stats/sampling/tests/test_sample_continuous_rv.py,sha256=Gh8hFN1hFFsthEv9wP2ZdgghQfaEnE8n7HlmyXXhN1E,5708
+sympy/stats/sampling/tests/test_sample_discrete_rv.py,sha256=Z3hqjHEFaIoB0hrhpy7YYL_7Dtqzmy5YMWAYrlqPu38,3360
+sympy/stats/sampling/tests/test_sample_finite_rv.py,sha256=dWwrFePw8eX2rBheAXi1AVxr_gqBD63VZKfW81hNoQc,3061
+sympy/stats/stochastic_process.py,sha256=pDz0rbKXTiaNmMmmz70dP3F_KWL_XhoCKFHYBNt1QeU,2312
+sympy/stats/stochastic_process_types.py,sha256=YEUA-saTh8WF6Pn7GcgrcyclRCb_SC13YnpgOIpu7-Q,88553
+sympy/stats/symbolic_multivariate_probability.py,sha256=R6Co7XCcxLoOtTqC6ZSnGuylZNUBrC5AD0DrJr2jE1A,10450
+sympy/stats/symbolic_probability.py,sha256=HkWUiH9EM_DQ1aM1FxNmBm_8xtqeviIsyUpqFl2RYnI,23266
+sympy/stats/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/stats/tests/test_compound_rv.py,sha256=2927chbHTThA34Ki-ji319QT7ajQ1ueC640Mga-18ZA,6263
+sympy/stats/tests/test_continuous_rv.py,sha256=BcBkiyX7e1QiwS6xnD-qLzXnijvqbsebTzXEn3IfGyE,56140
+sympy/stats/tests/test_discrete_rv.py,sha256=bLqMtKpH5fDjuP7uuRAtAjakbahuFz9x3dY-PPKFsGk,11230
+sympy/stats/tests/test_error_prop.py,sha256=xKAkw3F5XJ72xiDREI7PkyReWNVW_89CD_mjOY_diDY,1933
+sympy/stats/tests/test_finite_rv.py,sha256=JHYgY4snFF5t9qcnQfKaN5zaGsO7_SuNR7Tq234W4No,20413
+sympy/stats/tests/test_joint_rv.py,sha256=W28rCRYczv5Jax7k-bj7OveT-y-AP4q-kRR0-LNaWX0,18653
+sympy/stats/tests/test_matrix_distributions.py,sha256=9daJUiSGaLq34TeZfB-xPqC8xz6vECGrm0DdBZaQPyY,8857
+sympy/stats/tests/test_mix.py,sha256=Cplnw06Ki96Y_4fx6Bu7lUXjxoIfX7tNJasm9SOz5wQ,3991
+sympy/stats/tests/test_random_matrix.py,sha256=CiD1hV25MGHwTfHGaoaehGD3iJ4lqNYi-ZiwReO6CVk,5842
+sympy/stats/tests/test_rv.py,sha256=Bp7UwffIMO7oc8UnFV11yYGcXUjSa0NhsuOgQaNRMt8,12959
+sympy/stats/tests/test_stochastic_process.py,sha256=i-VCOZrjpJtvyTBm9xgniTCkk_iUYIuFnkiyxzkn6Ig,39323
+sympy/stats/tests/test_symbolic_multivariate.py,sha256=G3AgbRbt0DQ-p0DYXYDjbx4e4f5FIgd31F34e0NO2n8,5580
+sympy/stats/tests/test_symbolic_probability.py,sha256=k5trScMiwSgl9dzJt30BV-t0KuYcyD-s9HtT2-hVhQ0,9398
+sympy/strategies/__init__.py,sha256=XaTAPqDoi6527juvR8LLN1mv6ZcslDrGloTTBMjJzxA,1402
+sympy/strategies/branch/__init__.py,sha256=xxbMwR2LzLcQWsH9ss8ddE99VHFJTY-cYiR6xhO3tj0,356
+sympy/strategies/branch/core.py,sha256=QiXSa7uhvmUBTLyUwBQHrYkWlOceKh5p4kVD90VnCKM,2759
+sympy/strategies/branch/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/strategies/branch/tests/test_core.py,sha256=23KQWJxC_2T1arwMAkt9pY1ZtG59avlxTZcVTn81UPI,2246
+sympy/strategies/branch/tests/test_tools.py,sha256=4BDkqVqrTlsivQ0PldQr6PjVZsAikc39tSxGAQA3ir8,942
+sympy/strategies/branch/tests/test_traverse.py,sha256=6rikMnZdamSzww1sSiM-aQwqa4lQrpM-DpOU9XCbiOQ,1322
+sympy/strategies/branch/tools.py,sha256=tvv3IjmQGNYbo-slCbbDf_rylZd537wvLcpdBtT-bbY,357
+sympy/strategies/branch/traverse.py,sha256=7iBViQdNpKu-AHoFED7_C9KBSyYcQBfLGopEJQbNtvk,799
+sympy/strategies/core.py,sha256=nsH6LZgyc_aslv4Na5XvJMEizC6uSzscRlVW91k1pu4,3956
+sympy/strategies/rl.py,sha256=-M5lfrtcREkvbW4YfoiB19wfYyMLKz6SmL887ymKeoI,4404
+sympy/strategies/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/strategies/tests/test_core.py,sha256=42XHlv1hN1S1QPEf2r9pddZ2EQL6o4FEPQvfo-UmXcw,2152
+sympy/strategies/tests/test_rl.py,sha256=wm0L6pdvddBgRcwhpiSk-nCgyzVGickfnOCkmHWS0j4,1949
+sympy/strategies/tests/test_tools.py,sha256=UdMojFIn3f1b2x2iRGv1Wfnwdso-Kl57GTyjCU_DjzQ,875
+sympy/strategies/tests/test_traverse.py,sha256=jWuZhYEt-F18_rxEMhn6OgGQ1GNs-dM_GFZ2F5nHs2I,2082
+sympy/strategies/tests/test_tree.py,sha256=9NL948rt6i9tYU6CQz9VNxE6l1begQs-MxP2euzE3Sc,2400
+sympy/strategies/tools.py,sha256=ERASzEP2SP-EcJ8p-4XyREYB15q3t81x1cyamJ-M880,1368
+sympy/strategies/traverse.py,sha256=DhPnBJ5Rw_xzhGiBtSciTyV-H2zhlxgjYVjrNH-gLyk,1183
+sympy/strategies/tree.py,sha256=ggnP9l3NIpJsssBMVKr4-yM_m8uCkrkm191ZC6MfZjc,3770
+sympy/strategies/util.py,sha256=2fbR813IY4IYco5mBoGJLu5z88OhXmwuIxgOO9IvZO4,361
+sympy/tensor/__init__.py,sha256=VMNXCRSayigQT6a3cvf5M_M-wdV-KSil_JbAmHcuUQc,870
+sympy/tensor/array/__init__.py,sha256=lTT1EwV5tb3WAvmmS_mIjhCSWSLiB0NNPW4n9_3fu0k,8244
+sympy/tensor/array/array_comprehension.py,sha256=01PTIbkAGaq0CDcaI_2KsaMnYm1nxQ8sFAiHHcc__gw,12262
+sympy/tensor/array/array_derivatives.py,sha256=c-gYeA_qpXOY3aexyz7psSqmTVIGVBrcGDvSkW5dZV0,4796
+sympy/tensor/array/arrayop.py,sha256=KvFGYWcYvChWkThtVAotlaSrcfjHogAxvpxWvp6dSgo,18397
+sympy/tensor/array/dense_ndim_array.py,sha256=Ie8qVMJyp2Tsq7aVhmZpPX8X-KTlF9uaxkQfTzCZ9z8,6433
+sympy/tensor/array/expressions/__init__.py,sha256=OUMJjZY7HtWJL0ygqkdWC8LdCqibJZhHCfYeXu-eB4E,7045
+sympy/tensor/array/expressions/array_expressions.py,sha256=28TI8cwwQ4Q-QCI9X_j6X-lG0kR6amjAe9-h9JKb5EU,76961
+sympy/tensor/array/expressions/arrayexpr_derivatives.py,sha256=W9-bY2LL83lLSNHXItzqjOgvf-HIDbUXPoVw8uOymcg,6249
+sympy/tensor/array/expressions/conv_array_to_indexed.py,sha256=BIwlQr7RKC8bZN3mR8ICC5TYOC9uasYcV0Zc1VNKmiE,445
+sympy/tensor/array/expressions/conv_array_to_matrix.py,sha256=85YZBTZI4o9dJtKDJXXug_lJVLG8dT_22AT7l7DKoyE,416
+sympy/tensor/array/expressions/conv_indexed_to_array.py,sha256=EyW52TplBxIx25mUDvI_5Tzc8LD6Mnp6XNW9wIw9pH4,254
+sympy/tensor/array/expressions/conv_matrix_to_array.py,sha256=XYyqt0NsQSrgNpEkr8xTGeUhR7ZYeNljVFfVEF1K7vA,250
+sympy/tensor/array/expressions/from_array_to_indexed.py,sha256=3YIcsAzWVWQRJYQS90uPvSl2dM7ZqLV_qt7E9-uYU28,3936
+sympy/tensor/array/expressions/from_array_to_matrix.py,sha256=4HUbCfR2BHd54Ijws9DCcSs6aAJ-k8RwT195NTQImis,41435
+sympy/tensor/array/expressions/from_indexed_to_array.py,sha256=RUcKemmrwuK5RFRr19YSPVMCOkZfLAWlbbB56u8Wi0g,11187
+sympy/tensor/array/expressions/from_matrix_to_array.py,sha256=yIY1RupF9-FVV3jZLsqWxZ1ckoE1-HkQyM8cQIm4_Gs,3929
+sympy/tensor/array/expressions/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/tensor/array/expressions/tests/test_array_expressions.py,sha256=QUAdxQ9TvBpDEAZoJpLSWwbqjmuflPe3xBRP30lFZr0,31262
+sympy/tensor/array/expressions/tests/test_arrayexpr_derivatives.py,sha256=lpC4ly6MJLDRBcVt3GcP3H6ke9bI-o3VULw0xyF5QbY,2470
+sympy/tensor/array/expressions/tests/test_as_explicit.py,sha256=nOjFKXCqYNu2O7Szc1TD1x1bsUchPRAG3nGlNGEd1Yg,2568
+sympy/tensor/array/expressions/tests/test_convert_array_to_indexed.py,sha256=6yNxGXH6BX5607FTjMkwR2t9wNVlEhV8JMSh4UIWux8,2500
+sympy/tensor/array/expressions/tests/test_convert_array_to_matrix.py,sha256=2vkSep9CPKYrQQS0u8Ayn_sc7yek1zwzjjCWK5cfYe8,29311
+sympy/tensor/array/expressions/tests/test_convert_indexed_to_array.py,sha256=RVEG_qUsXiBH9gHtWp2-9pMC4J2aLc4iUdzBFM0QyTw,8615
+sympy/tensor/array/expressions/tests/test_convert_matrix_to_array.py,sha256=G2g5E0l-FABwYyQowbKKvLcEI8NViJXaYLW3eUEcvjw,4595
+sympy/tensor/array/expressions/tests/test_deprecated_conv_modules.py,sha256=DG8IoUtxCy2acWjUHUUKu4bRsTxXbeFLFjKMLA2GdLY,1216
+sympy/tensor/array/expressions/utils.py,sha256=Rn58boHHUEoBZFtinDpruLWFBkNBwgkVQ4c9m7Nym1o,3939
+sympy/tensor/array/mutable_ndim_array.py,sha256=M0PTt8IOIcVXqQPWe2N50sm4Eq2bodRXV4Vkd08crXk,277
+sympy/tensor/array/ndim_array.py,sha256=bZvA21fSTMc2sQLJN4AovQspddzmnINBWFPr-TeGmm0,19138
+sympy/tensor/array/sparse_ndim_array.py,sha256=4nD_Hg-JdC_1mYQTohmKFfL5M1Ugdq0fpnDUILkTtq8,6387
+sympy/tensor/array/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/tensor/array/tests/test_array_comprehension.py,sha256=e8MsWbvwmr-HxTfaM7i8HoIVofa8InLzF9PTCIVvzjU,4529
+sympy/tensor/array/tests/test_array_derivatives.py,sha256=hS10Bkb3F2kWoFoxk2ucr21p0r5DfwHDYPI8HcmAl0o,1601
+sympy/tensor/array/tests/test_arrayop.py,sha256=WahGcUnArsAo9eaMqGT7_AjKons0WgFzLOWTtNvnSEI,25844
+sympy/tensor/array/tests/test_immutable_ndim_array.py,sha256=9ji_14szn-qoL6DQ5muzIFNaXefT7n55PFigXoFwk50,15823
+sympy/tensor/array/tests/test_mutable_ndim_array.py,sha256=rFFa0o0AJYgPNnpqijl91Vb9EW2kgHGQc6cu9f1fIvY,13070
+sympy/tensor/array/tests/test_ndim_array.py,sha256=KH-9LAME3ldVIu5n7Vd_Xr36dN4frCdiF9qZdBWETu0,2232
+sympy/tensor/array/tests/test_ndim_array_conversions.py,sha256=CUGDCbCcslACy3Ngq-zoig9JnO4yHTw3IPcKy0FnRpw,648
+sympy/tensor/functions.py,sha256=FNZ2M0HGVaASJ_1AkPu1vF5NHNLmBXKLsj0Q5wKMX90,4168
+sympy/tensor/index_methods.py,sha256=dcX9kNKLHi_XXkFHBPS-fcM-PaeYKkX80jmzxC0siiQ,15434
+sympy/tensor/indexed.py,sha256=3qiQehMvXSDbr_RDXg6l_aEu6dHZXEfXrMoXCJj7Cqo,24515
+sympy/tensor/tensor.py,sha256=EQ9qJjtvij4gG101jB1eOuTtaSmvm1Da3IHVCBn1Flo,181094
+sympy/tensor/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/tensor/tests/test_functions.py,sha256=rBBHjJIUA2oR83UgEJ_GIASDWfTZXDzOllmcO90XYDU,1552
+sympy/tensor/tests/test_index_methods.py,sha256=Pu951z4yYYMOXBKcNteH63hTAxmNX8702nSQH_pciFE,7112
+sympy/tensor/tests/test_indexed.py,sha256=EB2-t0gYkaTOvrCkhyW2cEL_MVi4xBUZxbf35NA-puI,16376
+sympy/tensor/tests/test_printing.py,sha256=sUx_rChNTWFKPNwVl296QXO-d4-yemDJnkEHFislsmc,424
+sympy/tensor/tests/test_tensor.py,sha256=XQiLkOtyLLFKX_lWEqpCr2lXxQ6LK_hShj0rz7RrWpk,81236
+sympy/tensor/tests/test_tensor_element.py,sha256=1dF96FtqUGaJzethw23vJIj3H5KdxsU1Xyd4DU54EB4,908
+sympy/tensor/tests/test_tensor_operators.py,sha256=n4md5Dv7QoVSMR4cHbkEKSFDxgTTpEyxMiCAqoqyJyk,17966
+sympy/tensor/toperators.py,sha256=fniTUpdYz0OvtNnFgrHINedX86FxVcxfKj9l_l1p9Rw,8840
+sympy/testing/__init__.py,sha256=IN9aHvoksdZywonAYE0cExFnuPQs9z1E4P742aYZNnE,169
+sympy/testing/matrices.py,sha256=VWBPdjIUYNHE7fdbYcmQwQTYcIWpOP9tFn9A0rGCBmE,216
+sympy/testing/pytest.py,sha256=xiKL67rD4sKYVZ1Xqci4arPJQzrm3xWfg-m6I7eWNBM,13363
+sympy/testing/quality_unicode.py,sha256=quKFUpEUPftVGNpsj71WpRoeKZUzc8sgLjODRmHPf-w,3482
+sympy/testing/randtest.py,sha256=IKDFAm8b72Z1OkT7vpgnZjaW5LsSU_wf6g35sCkq9I0,562
+sympy/testing/runtests.py,sha256=dD9_0xtvG0wMgQtdvxDi7ePc2CL2ybNRqHKgHjJomzE,89921
+sympy/testing/runtests_pytest.py,sha256=KSqhzaRis7sx2AwctWsP6VjCbDcg6C5UCApp_LUNRuc,17801
+sympy/testing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/testing/tests/diagnose_imports.py,sha256=VQAc0WLHgQgksu6kcQLmEVW4O98v7YgjLMzCLNZ6JfE,9508
+sympy/testing/tests/test_code_quality.py,sha256=Yzb1CAIAGTO29Ay2fsPn0-OqstAoy9FMiAMIed6iVZE,19214
+sympy/testing/tests/test_deprecated.py,sha256=wQZHs4wDNuK4flaKKLsJW6XRMtrVjMv_5rUP3WspgPA,183
+sympy/testing/tests/test_module_imports.py,sha256=5w6F6JW6K7lgpbB4X9Tj0Vw8AcNVlfaSuvbwKXJKD6c,1459
+sympy/testing/tests/test_pytest.py,sha256=iKO10Tvua1Xem6a22IWH4SDrpFfr-bM-rXx039Ua7YA,6778
+sympy/testing/tests/test_runtests_pytest.py,sha256=C4bo-SOx8BsxvT4M_0OPUiwSEXShaMqpYRoedMmbR1g,6083
+sympy/testing/tmpfiles.py,sha256=bF8ktKC9lDhS65gahB9hOewsZ378UkhLgq3QHiqWYXU,1042
+sympy/this.py,sha256=XfOkN5EIM2RuDxSm_q6k_R_WtkIoSy6PXWKp3aAXvoc,550
+sympy/unify/__init__.py,sha256=Upa9h7SSr9W1PXo0WkNESsGsMZ85rcWkeruBtkAi3Fg,293
+sympy/unify/core.py,sha256=-BCNPPMdfZuhhIWqyn9pYJoO8yFPGDX78Hn2551ABuE,7037
+sympy/unify/rewrite.py,sha256=Emr8Uoum3gxKpMDqFHJIjx3xChArUIN6XIy6NPfCS8I,1798
+sympy/unify/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/unify/tests/test_rewrite.py,sha256=BgA8zmdz9Nw-Xbu4-w3UABeWypqLvmy9VzL744EmYtE,2002
+sympy/unify/tests/test_sympy.py,sha256=UCItZJNAx9dG5F7O27pyXUF1-e6aOwkZ-cVdB6SZFZc,5922
+sympy/unify/tests/test_unify.py,sha256=4TlgchV6NWuBekJx9RGlMjx3-UwonzgIYXDytb7sBRU,3029
+sympy/unify/usympy.py,sha256=6Kxx96FXSdqXimLseVK_FkYwy2vqWhNnxMVPMRShvy4,3964
+sympy/utilities/__init__.py,sha256=nbQhzII8dw5zd4hQJ2SUyriK5dOrqf-bbjy10XKQXPw,840
+sympy/utilities/_compilation/__init__.py,sha256=uYUDPbwrMTbGEMVuago32EN_ix8fsi5M0SvcLOtwMOk,751
+sympy/utilities/_compilation/availability.py,sha256=ybxp3mboH5772JHTWKBN1D-cs6QxATQiaL4zJVV4RE0,2884
+sympy/utilities/_compilation/compilation.py,sha256=qkfDtSgSeRJ-97E5hN1asUqoDXS4nnNgYoHCA8WAmHA,22156
+sympy/utilities/_compilation/runners.py,sha256=KAinYF0m55dRdDFO5pvHBlvTxDY0ldoImqTOwX7VmL4,10237
+sympy/utilities/_compilation/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/utilities/_compilation/tests/test_compilation.py,sha256=DmdxCPlWaqgtNZPWzMVPwqRuqqJcgWBWxXfOEMZ21D0,3189
+sympy/utilities/_compilation/util.py,sha256=otSIKhM5YSYzbUNYycagG2xSj6owlQVrwIVl0rv7Owc,8611
+sympy/utilities/autowrap.py,sha256=l8noWRKmA-B814S92RK3O64YWAkARnMfqY1AQqi2S8g,42561
+sympy/utilities/codegen.py,sha256=1ieFSlxGgd9utMSPzN5NraTfoSSzlUM9V_BnGYMuMc8,81670
+sympy/utilities/decorator.py,sha256=NaZBNCDdMhG4_3esEOLZCbVQcjltvi3lrMIRCqewfR4,11184
+sympy/utilities/enumerative.py,sha256=ah4Td5KhqGdPR7EQHcUDOsYLDH64Sh2z6xm5gDpJSFg,43585
+sympy/utilities/exceptions.py,sha256=RoKY7jDIq6OsZbNSCyneWbVQb1Cw2MtOuioJlCKmBec,10570
+sympy/utilities/iterables.py,sha256=noIMRQmdSPfbg1LorRPHreozS265u4IHUmDkOvMB2po,91103
+sympy/utilities/lambdify.py,sha256=lepieExI19QvZYPrGl_WZaFwta8YZBo6AgxDnwq01ow,57816
+sympy/utilities/magic.py,sha256=ofrwi1-xwMWb4VCQOEIwe4J1QAwxOscigDq26uSn3iY,400
+sympy/utilities/matchpy_connector.py,sha256=7dSDOPbN5Y_XW6bIGVNK3dJ-gVdTB_liJ8O5rIqd28c,11948
+sympy/utilities/mathml/__init__.py,sha256=74VhxNJlvCZTm2Jh3t69N8QZRklTQjqMvqFMLVwCKQk,3388
+sympy/utilities/mathml/data/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/utilities/mathml/data/mmlctop.xsl,sha256=fi3CTNyg-mSscOGYBXLJv8veE_ItR_YTFMJ4jmjp6aE,114444
+sympy/utilities/mathml/data/mmltex.xsl,sha256=haX7emZOfD6_nbn5BjK93F-C85mSS8KogAbIBsW1aBA,137304
+sympy/utilities/mathml/data/simple_mmlctop.xsl,sha256=OM-Vge1satH-MAYwWhraeXcorn1KGtuqBK-PDddaOrk,114433
+sympy/utilities/memoization.py,sha256=jD6RjVMZkGpNZYaJ9481vTiqvmwyu1IKDpsF5PYIvf4,1838
+sympy/utilities/misc.py,sha256=C6C3Em9YUjqg4gUhVdu97K0Wt_gRxuhNHS0TW6MlrxQ,16000
+sympy/utilities/pkgdata.py,sha256=BiBonyObCsS6EnLUII_1kDtchDN7Tur0T4GMzoUo06M,935
+sympy/utilities/pytest.py,sha256=ifo5fkOQ94HKXjy_U__mLFSohNRGP2ft8Z4P5gAi4yw,440
+sympy/utilities/randtest.py,sha256=Qlr4MMe0ade6jUH6pIEE0-v4g4qGswJhKpdaQFS_GDw,435
+sympy/utilities/runtests.py,sha256=Js3GGuzxQDZw5Tr5Kge0DCYx9gi3eya4DZxfwib6e3Y,451
+sympy/utilities/source.py,sha256=ShIXRNtplSEfZNi5VDYD3yi6305eRz4TmchEOEvcicw,1127
+sympy/utilities/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/utilities/tests/test_autowrap.py,sha256=PA6zaRVrIWyQHq6bGKezqNB6YWTfcnnB9VH2vzaEfaQ,14865
+sympy/utilities/tests/test_codegen.py,sha256=pjfhZTa5LI9gdrakDfLtBBrIxgWjWORR_NBDW9J8Cq8,56130
+sympy/utilities/tests/test_codegen_julia.py,sha256=QYqSluVhmxq_BAagEKBb6eJIseFFAweMjpuLgNPMUWI,18540
+sympy/utilities/tests/test_codegen_octave.py,sha256=GUQIj6YjsMsj8ZLmVngWa9ovoyqfwvikWXdeS7m_c7I,17830
+sympy/utilities/tests/test_codegen_rust.py,sha256=seq9o51dsa09MmcqwKRkGiurbWLs1uAIjaz7xGOKNE4,12326
+sympy/utilities/tests/test_decorator.py,sha256=VYUvzUrVI7I7MK0YZxLLEmEu4pV5dqaB1CLEJ8Ocav4,3705
+sympy/utilities/tests/test_deprecated.py,sha256=LRrZ2UxuXnK6Jwxl8vT0EdLT-q-7jLkTC69U9JjuYYU,489
+sympy/utilities/tests/test_enumerative.py,sha256=nw-1r0MgxbzYkScmxv7HUAIAQycg8pUVOH_slDRLg7E,6097
+sympy/utilities/tests/test_exceptions.py,sha256=OKRa2yuHMtnVcnisu-xcaedi2RKsH9QrgU9exgoOK30,716
+sympy/utilities/tests/test_iterables.py,sha256=xYWyoDtVkYfnIOdA-5yUYZsxo4iTsExaNpVmjMuwpTc,35288
+sympy/utilities/tests/test_lambdify.py,sha256=emTSDwHdGprENO3ugK86k1L6m8Y3IamPj1oUNIKaYrQ,73531
+sympy/utilities/tests/test_matchpy_connector.py,sha256=mBrAev2Hxe4jg_1ny3ZaGIfh2xvWbr6BDRVjB9owJFM,4850
+sympy/utilities/tests/test_mathml.py,sha256=-6z1MRYEH4eYQi2_wt8zmdjwtt5Cn483zqsvD-o_r70,836
+sympy/utilities/tests/test_misc.py,sha256=xZh6ux9o2iZpWvfX_ivp4lD3WgJVeP5k6ipppNGHDsw,4643
+sympy/utilities/tests/test_pickling.py,sha256=ZXGzB_gQ9juws_N_n2vf6QPVojdfP4Mbl7uqdtkPb0E,23600
+sympy/utilities/tests/test_source.py,sha256=ObjrJxZFVhLgXjVmFHUy7bti9UPPgOh5Cptw8lHW9mM,289
+sympy/utilities/tests/test_timeutils.py,sha256=sCRC6BCSho1e9n4clke3QXHx4a3qYLru-bddS_sEmFA,337
+sympy/utilities/tests/test_wester.py,sha256=S79UNsGhEW5z6hDriQB8OY_Vhaz1j0Q7yv31HynyDfk,94866
+sympy/utilities/tests/test_xxe.py,sha256=xk1j0Dd96wsGYKRNDzXTW0hTQejGCfiZcEhYcYiqojg,66
+sympy/utilities/timeutils.py,sha256=PNHyvuEM66UEXLF8ye6PMilcEDK75B9wab3ai8a9cyo,1941
+sympy/utilities/tmpfiles.py,sha256=tQP3g7LTrnXTGqUgGNoIZtjug6O6lq6EYLrKPJcUGEU,450
+sympy/vector/__init__.py,sha256=bgKutVqUPWuvHWBpiEm6XWE6iGfAPJw3pt19NRn2n10,1969
+sympy/vector/basisdependent.py,sha256=P7LogUck6NWjEzAOH3dYr4A8M5QCOPaCW75lmiQpBqU,11857
+sympy/vector/coordsysrect.py,sha256=0BKdr8AG8BUJnShIIyyCvkU5OVdjtZsKcBuGgdbvdHw,36833
+sympy/vector/deloperator.py,sha256=4BJNjmI342HkVRmeQkqauqvibKsf2HOuzknQTfQMkpg,3191
+sympy/vector/dyadic.py,sha256=IOyrgONyGDHPtG0RINcMgetAVMSOmYI5a99s-OwXBTA,8571
+sympy/vector/functions.py,sha256=rmEBaV0XpZLkCPcJFojHS9CNHirV55v5sDwNqTPwqGM,15454
+sympy/vector/implicitregion.py,sha256=4-M_-shL4EJ9nfjAZ_xg00IXZVQghcCZ3bv8QGbkopI,16158
+sympy/vector/integrals.py,sha256=x8DrvKXPznE05JgnZ7I3IWLWrvFl9SEghGaFmHrBaE4,6837
+sympy/vector/kind.py,sha256=U6qxciZY7-ACzBSpGM0iSTI5tqflpPBvm4_J9ujyxyE,1812
+sympy/vector/operators.py,sha256=dNC7mNXZb3KxX5GyjFNDTLTkzSnYjOohZtBXuQ1keZE,9579
+sympy/vector/orienters.py,sha256=EtWNWfOvAuy_wipam9SA7_muKSrsP-43UPRCCz56sb0,11798
+sympy/vector/parametricregion.py,sha256=gAarunY8q3D8WVvryZEbJQ4g-nlXo4FnO-CbyEpVUXc,5932
+sympy/vector/point.py,sha256=-JFOibsQclOKC2m2qZRiGGB4oK9ieVZRd2ll5g4k3bE,4488
+sympy/vector/scalar.py,sha256=WAb25BC0TEOZ-_bEtL1gdySuM1adJzK47kJYTrC4Y4w,2024
+sympy/vector/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+sympy/vector/tests/test_coordsysrect.py,sha256=q9n9OIG_CpD4KQN20dzwRZIXoMv7VSgp8fHmVnkZfr0,19595
+sympy/vector/tests/test_dyadic.py,sha256=f1R-BL_63VBbc0XgEX_LYzV_3OupYd4hp5RzRk6dAbI,4949
+sympy/vector/tests/test_field_functions.py,sha256=v9l8Ex8K2MsPGxqAPhpEgu6WAo6wS6qvdWLKQMxgE4A,14094
+sympy/vector/tests/test_functions.py,sha256=Bs2sekdDJyw_wrUpG7vZQGH0y0S4C4AbxGSpeU_8C2s,8050
+sympy/vector/tests/test_implicitregion.py,sha256=wVilD5H-MhHiW58QT6P5U7uT79JdKHm9D7JgZoi6BE4,4028
+sympy/vector/tests/test_integrals.py,sha256=iDq3Wpr8I8EXAGkXqMpA-P9i1zEnV7lU8WR6xBOhEK0,5087
+sympy/vector/tests/test_operators.py,sha256=KexUWvc_Nwp2HWrEbhxiO7MeaFxYlckrp__Tkwg-wmU,1613
+sympy/vector/tests/test_parametricregion.py,sha256=OfKapF9A_g9X6JxgYc0UfxIhwXzRERzaj-EijQCJONw,4009
+sympy/vector/tests/test_printing.py,sha256=3BeW55iQ4qXdfDTFqptE2ufJPJIBOzdfIYVx84n_EwA,7708
+sympy/vector/tests/test_vector.py,sha256=rJpMlUWiezrY6drHUNdJc8_FDYMwGCG4lBy8zS4XSZk,10238
+sympy/vector/vector.py,sha256=aOSfyfRvkatzWHWuulY6n0_iqElI5mntAUjNPptpBiM,20322
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/REQUESTED b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/WHEEL b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..8acb95590701b87bf84eec079cf4e3989f63b098
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (79.0.1)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/entry_points.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/entry_points.txt
new file mode 100644
index 0000000000000000000000000000000000000000..42a12f960335556fcee728e5754c346447d4e89c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/entry_points.txt
@@ -0,0 +1,2 @@
+[console_scripts]
+isympy = isympy:main
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/licenses/AUTHORS b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/licenses/AUTHORS
new file mode 100644
index 0000000000000000000000000000000000000000..1062f3bf743c0a37bcde05b1afc1ba5e98a95822
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/licenses/AUTHORS
@@ -0,0 +1,1379 @@
+All people who contributed to SymPy by sending at least a patch or
+more (in the order of the date of their first contribution), except
+those who explicitly didn't want to be mentioned. People with a * next
+to their names are not found in the metadata of the git history. This
+file is generated automatically by running `./bin/authors_update.py`.
+
+There are a total of 1371 authors.
+
+Ondřej Čertík 
+Fabian Pedregosa 
+Jurjen N.E. Bos 
+Mateusz Paprocki 
+*Marc-Etienne M.Leveille 
+Brian Jorgensen 
+Jason Gedge 
+Robert Schwarz 
+Pearu Peterson 
+Fredrik Johansson 
+Chris Wu 
+*Ulrich Hecht 
+Goutham Lakshminarayan 
+David Lawrence 
+Jaroslaw Tworek 
+David Marek 
+Bernhard R. Link 
+Andrej Tokarčík 
+Or Dvory 
+Saroj Adhikari 
+Pauli Virtanen 
+Robert Kern 
+James Aspnes 
+Nimish Telang 
+Abderrahim Kitouni 
+Pan Peng 
+Friedrich Hagedorn 
+Elrond der Elbenfuerst 
+Rizgar Mella 
+Felix Kaiser 
+Roberto Nobrega 
+David Roberts 
+Sebastian Krämer 
+Vinzent Steinberg 
+Riccardo Gori 
+Case Van Horsen 
+Stepan Roucka 
+Ali Raza Syed 
+Stefano Maggiolo 
+Robert Cimrman 
+Bastian Weber 
+Sebastian Krause 
+Sebastian Kreft 
+*Dan 
+Alan Bromborsky 
+Boris Timokhin 
+Robert 
+Andy R. Terrel 
+Hubert Tsang 
+Konrad Meyer 
+Henrik Johansson 
+Priit Laes 
+Freddie Witherden 
+Brian E. Granger 
+Andrew Straw 
+Kaifeng Zhu 
+Ted Horst 
+Andrew Docherty 
+Akshay Srinivasan 
+Aaron Meurer 
+Barry Wardell 
+Tomasz Buchert 
+Vinay Kumar 
+Johann Cohen-Tanugi 
+Jochen Voss 
+Luke Peterson 
+Chris Smith 
+Thomas Sidoti 
+Florian Mickler 
+Nicolas Pourcelot 
+Ben Goodrich 
+Toon Verstraelen 
+Ronan Lamy 
+James Abbatiello 
+Ryan Krauss 
+Bill Flynn 
+Kevin Goodsell 
+Jorn Baayen 
+Eh Tan 
+Renato Coutinho 
+Oscar Benjamin 
+Øyvind Jensen 
+Julio Idichekop Filho 
+Łukasz Pankowski 
+*Chu-Ching Huang 
+Fernando Perez 
+Raffaele De Feo 
+Christian Muise 
+Matt Curry 
+Kazuo Thow 
+Christian Schubert 
+Jezreel Ng 
+James Pearson 
+Matthew Brett 
+Addison Cugini 
+Nicholas J.S. Kinar 
+Harold Erbin 
+Thomas Dixon 
+Cristóvão Sousa 
+Andre de Fortier Smit 
+Mark Dewing 
+Alexey U. Gudchenko 
+Gary Kerr 
+Sherjil Ozair 
+Oleksandr Gituliar 
+Sean Vig 
+Prafullkumar P. Tale 
+Vladimir Perić 
+Tom Bachmann 
+Yuri Karadzhov 
+Vladimir Lagunov 
+Matthew Rocklin 
+Saptarshi Mandal 
+Gilbert Gede 
+Anatolii Koval 
+Tomo Lazovich 
+Pavel Fedotov 
+Jack McCaffery 
+Jeremias Yehdegho 
+Kibeom Kim 
+Gregory Ksionda 
+Tomáš Bambas 
+Raymond Wong 
+Luca Weihs 
+Shai 'Deshe' Wyborski 
+Thomas Wiecki 
+Óscar Nájera 
+Mario Pernici 
+Benjamin McDonald 
+Sam Magura 
+Stefan Krastanov 
+Bradley Froehle 
+Min Ragan-Kelley 
+Emma Hogan 
+Nikhil Sarda 
+Julien Rioux 
+Roberto Colistete, Jr. 
+Raoul Bourquin 
+Gert-Ludwig Ingold 
+Srinivas Vasudevan 
+Jason Moore 
+Miha Marolt 
+Tim Lahey 
+Luis Garcia 
+Matt Rajca 
+David Li 
+Alexandr Gudulin 
+Bilal Akhtar 
+Grzegorz Świrski 
+Matt Habel 
+David Ju 
+Nichita Utiu 
+Nikolay Lazarov 
+Steve Anton 
+Imran Ahmed Manzoor 
+Ljubiša Moćić <3rdslasher@gmail.com>
+Piotr Korgul 
+Jim Zhang 
+Sam Sleight 
+tborisova 
+Chancellor Arkantos 
+Stepan Simsa 
+Tobias Lenz 
+Siddhanathan Shanmugam 
+Tiffany Zhu 
+Tristan Hume 
+Alexey Subach 
+Joan Creus 
+Geoffry Song 
+Puneeth Chaganti 
+Marcin Kostrzewa <>
+Natalia Nawara 
+vishal 
+Shruti Mangipudi 
+Davy Mao 
+Swapnil Agarwal 
+Dhia Kennouche 
+jerryma1121 
+Joachim Durchholz 
+Martin Povišer 
+Siddhant Jain 
+Kevin Hunter 
+Michael Mayorov 
+Nathan Alison 
+Christian Bühler 
+Carsten Knoll 
+Bharath M R 
+Matthias Toews 
+Sergiu Ivanov 
+Jorge E. Cardona 
+Sanket Agarwal 
+Manoj Babu K. 
+Sai Nikhil 
+Aleksandar Makelov 
+Sachin Irukula 
+Raphael Michel 
+Ashwini Oruganti 
+Andreas Klöckner 
+Prateek Papriwal 
+Arpit Goyal 
+Angadh Nanjangud 
+Comer Duncan 
+Jens H. Nielsen 
+Joseph Dougherty 
+Elliot Marshall 
+Guru Devanla 
+George Waksman 
+Alexandr Popov 
+Tarun Gaba 
+Takafumi Arakaki 
+Saurabh Jha 
+Rom le Clair 
+Angus Griffith <16sn6uv@gmail.com>
+Timothy Reluga 
+Brian Stephanik 
+Alexander Eberspächer 
+Sachin Joglekar 
+Tyler Pirtle 
+Vasily Povalyaev 
+Colleen Lee 
+Matthew Hoff 
+Niklas Thörne 
+Huijun Mai 
+Marek Šuppa 
+Ramana Venkata 
+Prasoon Shukla 
+Stefen Yin 
+Thomas Hisch 
+Madeleine Ball 
+Mary Clark 
+Rishabh Dixit 
+Manoj Kumar 
+Akshit Agarwal 
+CJ Carey 
+Patrick Lacasse 
+Ananya H 
+Tarang Patel 
+Christopher Dembia 
+Benjamin Fishbein 
+Sean Ge 
+Amit Jamadagni 
+Ankit Agrawal 
+Björn Dahlgren 
+Christophe Saint-Jean 
+Demian Wassermann 
+Khagesh Patel 
+Stephen Loo 
+hm 
+Patrick Poitras 
+Katja Sophie Hotz 
+Varun Joshi 
+Chetna Gupta 
+Thilina Rathnayake 
+Max Hutchinson 
+Shravas K Rao 
+Matthew Tadd 
+Alexander Hirzel 
+Randy Heydon 
+Oliver Lee 
+Seshagiri Prabhu 
+Pradyumna 
+Erik Welch 
+Eric Nelson 
+Roland Puntaier 
+Chris Conley 
+Tim Swast 
+Dmitry Batkovich 
+Francesco Bonazzi 
+Yuriy Demidov 
+Rick Muller 
+Manish Gill 
+Markus Müller 
+Amit Saha 
+Jeremy 
+QuaBoo 
+Stefan van der Walt 
+David Joyner 
+Lars Buitinck 
+Alkiviadis G. Akritas 
+Vinit Ravishankar 
+Michael Boyle 
+Heiner Kirchhoffer 
+Pablo Puente 
+James Fiedler 
+Harsh Gupta 
+Tuomas Airaksinen 
+Paul Strickland 
+James Goppert 
+rathmann 
+Avichal Dayal 
+Paul Scott 
+Shipra Banga 
+Pramod Ch 
+Akshay 
+Buck Shlegeris 
+Jonathan Miller 
+Edward Schembor 
+Rajath Shashidhara 
+Zamrath Nizam 
+Aditya Shah 
+Rajat Aggarwal 
+Sambuddha Basu 
+Zeel Shah 
+Abhinav Chanda 
+Jim Crist 
+Sudhanshu Mishra 
+Anurag Sharma 
+Soumya Dipta Biswas 
+Sushant Hiray 
+Ben Lucato 
+Kunal Arora 
+Henry Gebhardt 
+Dammina Sahabandu 
+Manish Shukla 
+Ralph Bean 
+richierichrawr 
+John Connor 
+Juan Luis Cano Rodríguez 
+Sahil Shekhawat 
+Kundan Kumar 
+Stas Kelvich 
+sevaader 
+Dhruvesh Vijay Parikh 
+Venkatesh Halli 
+Lennart Fricke 
+Vlad Seghete 
+Shashank Agarwal 
+carstimon 
+Pierre Haessig 
+Maciej Baranski 
+Benjamin Gudehus 
+Faisal Anees 
+Mark Shoulson 
+Robert Johansson 
+Kalevi Suominen 
+Kaushik Varanasi 
+Fawaz Alazemi 
+Ambar Mehrotra 
+David P. Sanders 
+Peter Brady 
+John V. Siratt 
+Sarwar Chahal 
+Nathan Woods 
+Colin B. Macdonald 
+Marcus Näslund 
+Clemens Novak 
+Mridul Seth 
+Craig A. Stoudt 
+Raj 
+Mihai A. Ionescu 
+immerrr 
+Chai Wah Wu 
+Leonid Blouvshtein 
+Peleg Michaeli 
+ck Lux 
+zsc347 
+Hamish Dickson 
+Michael Gallaspy 
+Roman Inflianskas 
+Duane Nykamp 
+Ted Dokos 
+Sunny Aggarwal 
+Victor Brebenar 
+Akshat Jain 
+Shivam Vats 
+Longqi Wang 
+Juan Felipe Osorio 
+Ray Cathcart 
+Lukas Zorich 
+Eric Miller 
+Cody Herbst 
+Nishith Shah 
+Amit Kumar 
+Yury G. Kudryashov 
+Guillaume Gay 
+Mihir Wadwekar 
+Tuan Manh Lai 
+Asish Panda 
+Darshan Chaudhary 
+Alec Kalinin 
+Ralf Stephan 
+Aaditya Nair 
+Jayesh Lahori 
+Harshil Goel 
+Luv Agarwal 
+Jason Ly 
+Lokesh Sharma 
+Sartaj Singh 
+Chris Swierczewski 
+Konstantin Togoi 
+Param Singh 
+Sumith Kulal 
+Juha Remes 
+Philippe Bouafia 
+Peter Schmidt 
+Jiaxing Liang 
+Lucas Jones 
+Gregory Ashton 
+Jennifer White 
+Renato Orsino 
+Alistair Lynn 
+Govind Sahai 
+Adam Bloomston 
+Kyle McDaniel 
+Nguyen Truong Duy 
+Alex Lindsay 
+Mathew Chong 
+Jason Siefken 
+Gaurav Dhingra 
+Gao, Xiang 
+Kevin Ventullo 
+mao8 
+Isuru Fernando 
+Shivam Tyagi 
+Richard Otis 
+Rich LaSota 
+dustyrockpyle 
+Anton Akhmerov 
+Michael Zingale 
+Chak-Pong Chung 
+David T 
+Phil Ruffwind 
+Sebastian Koslowski 
+Kumar Krishna Agrawal 
+Dustin Gadal 
+João Moura 
+Yu Kobayashi 
+Shashank Kumar 
+Timothy Cyrus 
+Devyani Kota 
+Keval Shah 
+Dzhelil Rufat 
+Pastafarianist 
+Sourav Singh 
+Jacob Garber 
+Vinay Singh 
+GolimarOurHero 
+Prashant Tyagi 
+Matthew Davis 
+Tschijnmo TSCHAU 
+Alexander Bentkamp 
+Jack Kemp 
+Kshitij Saraogi 
+Thomas Baruchel 
+Nicolás Guarín-Zapata 
+Jens Jørgen Mortensen 
+Sampad Kumar Saha 
+Eva Charlotte Mayer 
+Laura Domine 
+Justin Blythe 
+Meghana Madhyastha 
+Tanu Hari Dixit 
+Shekhar Prasad Rajak 
+Aqnouch Mohammed 
+Arafat Dad Khan 
+Boris Atamanovskiy 
+Sam Tygier 
+Jai Luthra 
+Guo Xingjian 
+Sandeep Veethu 
+Archit Verma 
+Shubham Tibra 
+Ashutosh Saboo 
+Michael S. Hansen 
+Anish Shah 
+Guillaume Jacquenot 
+Bhautik Mavani 
+Michał Radwański 
+Jerry Li 
+Pablo Zubieta 
+Shivam Agarwal 
+Chaitanya Sai Alaparthi 
+Arihant Parsoya 
+Ruslan Pisarev 
+Akash Trehan 
+Nishant Nikhil 
+Vladimir Poluhsin 
+Akshay Nagar 
+James Brandon Milam 
+Abhinav Agarwal 
+Rishabh Daal 
+Sanya Khurana 
+Aman Deep 
+Aravind Reddy 
+Abhishek Verma 
+Matthew Parnell 
+Thomas Hickman 
+Akshay Siramdas 
+YiDing Jiang 
+Jatin Yadav 
+Matthew Thomas 
+Rehas Sachdeva 
+Michael Mueller 
+Srajan Garg 
+Prabhjot Singh 
+Haruki Moriguchi 
+Tom Gijselinck 
+Nitin Chaudhary 
+Alex Argunov 
+Nathan Musoke 
+Abhishek Garg 
+Dana Jacobsen 
+Vasiliy Dommes 
+Phillip Berndt 
+Haimo Zhang 
+Anthony Scopatz 
+bluebrook 
+Leonid Kovalev 
+Josh Burkart 
+Dimitra Konomi 
+Christina Zografou 
+Fiach Antaw 
+Langston Barrett 
+Krit Karan 
+G. D. McBain 
+Prempal Singh 
+Gabriel Orisaka 
+Matthias Bussonnier 
+rahuldan 
+Colin Marquardt 
+Andrew Taber 
+Yash Reddy 
+Peter Stangl 
+elvis-sik 
+Nikos Karagiannakis 
+Jainul Vaghasia 
+Dennis Meckel 
+Harshil Meena 
+Micky 
+Nick Curtis 
+Michele Zaffalon 
+Martha Giannoudovardi 
+Devang Kulshreshtha 
+Steph Papanik 
+Mohammad Sadeq Dousti 
+Arif Ahmed 
+Abdullah Javed Nesar 
+Lakshya Agrawal 
+shruti 
+Rohit Rango 
+Hong Xu 
+Ivan Petuhov 
+Alsheh 
+Marcel Stimberg 
+Alexey Pakhocmhik 
+Tommy Olofsson 
+Zulfikar 
+Blair Azzopardi 
+Danny Hermes 
+Sergey Pestov 
+Mohit Chandra 
+Karthik Chintapalli 
+Marcin Briański 
+andreo 
+Flamy Owl 
+Yicong Guo 
+Varun Garg 
+Rishabh Madan 
+Aditya Kapoor 
+Karan Sharma 
+Vedant Rathore 
+Johan Blåbäck 
+Pranjal Tale 
+Jason Tokayer 
+Raghav Jajodia 
+Rajat Thakur 
+Dhruv Bhanushali 
+Anjul Kumar Tyagi 
+Barun Parruck 
+Bao Chau 
+Tanay Agrawal 
+Ranjith Kumar 
+Shikhar Makhija 
+Yathartha Joshi 
+Valeriia Gladkova 
+Sagar Bharadwaj 
+Daniel Mahler 
+Ka Yi 
+Rishat Iskhakov 
+Szymon Mieszczak 
+Sachin Agarwal 
+Priyank Patel 
+Satya Prakash Dwibedi 
+tools4origins 
+Nico Schlömer 
+Fermi Paradox 
+Ekansh Purohit 
+Vedarth Sharma 
+Peeyush Kushwaha 
+Jayjayyy 
+Christopher J. Wright 
+Jakub Wilk 
+Mauro Garavello 
+Chris Tefer 
+Shikhar Jaiswal 
+Chiu-Hsiang Hsu 
+Carlos Cordoba 
+Fabian Ball 
+Yerniyaz 
+Christiano Anderson 
+Robin Neatherway 
+Thomas Hunt 
+Theodore Han 
+Duc-Minh Phan 
+Lejla Metohajrova 
+Samyak Jain 
+Aditya Rohan 
+Vincent Delecroix 
+Michael Sparapany 
+Harsh Jain 
+Nathan Goldbaum 
+latot 
+Kenneth Lyons 
+Stan Schymanski 
+David Daly 
+Ayush Shridhar 
+Javed Nissar 
+Jiri Kuncar 
+vedantc98 
+Rupesh Harode 
+Rob Zinkov 
+James Harrop 
+James Taylor 
+Ishan Joshi 
+Marco Mancini 
+Boris Ettinger 
+Micah Fitch 
+Daniel Wennberg 
+ylemkimon 
+Akash Vaish 
+Peter Enenkel 
+Waldir Pimenta 
+Jithin D. George 
+Lev Chelyadinov 
+Lucas Wiman 
+Rhea Parekh 
+James Cotton 
+Robert Pollak 
+anca-mc 
+Sourav Ghosh 
+Jonathan Allan 
+Nikhil Pappu 
+Ethan Ward 
+Cezary Marczak 
+dps7ud 
+Nilabja Bhattacharya 
+Itay4 <31018228+Itay4@users.noreply.github.com>
+Poom Chiarawongse 
+Yang Yang 
+Cavendish McKay 
+Bradley Gannon 
+B McG 
+Rob Drynkin 
+Seth Ebner 
+Akash Kundu 
+Mark Jeromin 
+Roberto Díaz Pérez 
+Gleb Siroki 
+Segev Finer 
+Alex Lubbock 
+Ayodeji Ige 
+Matthew Wardrop 
+Hugo van Kemenade 
+Austin Palmer 
+der-blaue-elefant 
+Filip Gokstorp 
+Yuki Matsuda 
+Aaron Miller 
+Salil Vishnu Kapur 
+Atharva Khare 
+Shubham Maheshwari 
+Pavel Tkachenko 
+Ashish Kumar Gaurav 
+Rajeev Singh 
+Keno Goertz 
+Lucas Gallindo 
+Himanshu 
+David Menéndez Hurtado 
+Amit Manchanda 
+Rohit Jain 
+Jonathan A. Gross 
+Unknown 
+Sayan Goswami 
+Subhash Saurabh 
+Rastislav Rabatin 
+Vishal 
+Jeremey Gluck 
+Akshat Maheshwari 
+symbolique 
+Saloni Jain 
+Arighna Chakrabarty 
+Abhigyan Khaund 
+Jashanpreet Singh 
+Saurabh Agarwal 
+luzpaz 
+P. Sai Prasanth 
+Nirmal Sarswat 
+Cristian Di Pietrantonio 
+Ravi charan 
+Nityananda Gohain 
+Cédric Travelletti 
+Nicholas Bollweg 
+Himanshu Ladia 
+Adwait Baokar 
+Mihail Tarigradschi 
+Saketh 
+rushyam 
+sfoo 
+Rahil Hastu 
+Zach Raines 
+Sidhant Nagpal 
+Gagandeep Singh 
+Rishav Chakraborty 
+Malkhan Singh 
+Joaquim Monserrat 
+Mayank Singh 
+Rémy Léone 
+Maxence Mayrand <35958639+maxencemayrand@users.noreply.github.com>
+Nikoleta Glynatsi 
+helo9 
+Ken Wakita 
+Carl Sandrock 
+Fredrik Eriksson 
+Ian Swire 
+Bulat 
+Ehren Metcalfe 
+Dmitry Savransky 
+Kiyohito Yamazaki 
+Caley Finn 
+Zhi-Qiang Zhou 
+Alexander Pozdneev 
+Wes Turner <50891+westurner@users.noreply.github.com>
+JMSS-Unknown <31131631+JMSS-Unknown@users.noreply.github.com>
+Arshdeep Singh 
+cym1 <16437732+cym1@users.noreply.github.com>
+Stewart Wadsworth 
+Jared Lumpe 
+Avi Shrivastava 
+ramvenkat98 
+Bilal Ahmed 
+Dimas Abreu Archanjo Dutra 
+Yatna Verma 
+S.Y. Lee 
+Miro Hrončok 
+Sudarshan Kamath 
+Ayushman Koul 
+Robert Dougherty-Bliss 
+Andrey Grozin 
+Bavish Kulur 
+Arun Singh 
+sirnicolaf <43586954+sirnicolaf@users.noreply.github.com>
+Zachariah Etienne 
+Prayush Dawda <35144226+iamprayush@users.noreply.github.com>
+2torus 
+Faisal Riyaz 
+Martin Roelfs 
+SirJohnFranklin 
+Anthony Sottile 
+ViacheslavP 
+Safiya03 
+Alexander Dunlap 
+Rohit Sharma <31184621+rohitx007@users.noreply.github.com>
+Jonathan Warner 
+Mohit Balwani 
+Marduk Bolaños 
+amsuhane 
+Matthias Geier 
+klaasvanaarsen <44929042+klaasvanaarsen@users.noreply.github.com>
+Shubham Kumar Jha 
+rationa-kunal 
+Animesh Sinha 
+Gaurang Tandon <1gaurangtandon@gmail.com>
+Matthew Craven 
+Daniel Ingram 
+Jogi Miglani 
+Takumasa Nakamura 
+Ritu Raj Singh 
+Rajiv Ranjan Singh 
+Vera Lozhkina 
+adhoc-king <46354827+adhoc-king@users.noreply.github.com>
+Mikel Rouco 
+Oscar Gustafsson 
+damianos 
+Supreet Agrawal 
+shiksha11 
+Martin Ueding 
+sharma-kunal 
+Divyanshu Thakur 
+Susumu Ishizuka 
+Samnan Rahee 
+Fredrik Andersson 
+Bhavya Srivastava 
+Alpesh Jamgade 
+Shubham Abhang 
+Vishesh Mangla 
+Nicko van Someren 
+dandiez <47832466+dandiez@users.noreply.github.com>
+Frédéric Chapoton 
+jhanwar 
+Noumbissi valere Gille Geovan 
+Salmista-94 
+Shivani Kohli 
+Parker Berry 
+Pragyan Mehrotra 
+Nabanita Dash 
+Gaetano Guerriero 
+Ankit Raj Pandey 
+Ritesh Kumar 
+kangzhiq <709563092@qq.com>
+Jun Lin 
+Petr Kungurtsev 
+Anway De 
+znxftw 
+Denis Ivanenko 
+Orestis Vaggelis 
+Nikhil Maan 
+Abhinav Anand 
+Qingsha Shi 
+Juan Barbosa 
+Prionti Nasir 
+Bharat Raghunathan 
+arooshiverma 
+Christoph Gohle 
+Charalampos Tsiagkalis 
+Daniel Sears 
+Megan Ly 
+Sean P. Cornelius 
+Erik R. Gomez 
+Riccardo Magliocchetti 
+Henry Metlov 
+pekochun 
+Bendik Samseth 
+Vighnesh Shenoy 
+Versus Void 
+Denys Rybalka 
+Mark Dickinson 
+Rimi 
+rimibis <33387803+rimibis@users.noreply.github.com>
+Steven Lee 
+Gilles Schintgen 
+Abhi58 
+Tomasz Pytel 
+Aadit Kamat 
+Samesh 
+Velibor Zeli 
+Gabriel Bernardino 
+Joseph Redfern 
+Evelyn King 
+Miguel Marco 
+David Hagen 
+Hannah Kari 
+Soniya Nayak 
+Harsh Agarwal 
+Enric Florit 
+Yogesh Mishra 
+Denis Rykov 
+Ivan Tkachenko 
+Kenneth Emeka Odoh 
+Stephan Seitz 
+Yeshwanth N 
+Oscar Gerardo Lazo Arjona 
+Srinivasa Arun Yeragudipati 
+Kirtan Mali 
+TitanSnow 
+Pengning Chao <8857165+PengningChao@users.noreply.github.com>
+Louis Abraham 
+Morten Olsen Lysgaard 
+Akash Nagaraj (akasnaga) 
+Akash Nagaraj 
+Lauren Glattly 
+Hou-Rui 
+George Korepanov 
+dranknight09 
+aditisingh2362 
+Gina 
+gregmedlock 
+Georgios Giapitzakis Tzintanos 
+Eric Wieser 
+Bradley Dowling <34559056+btdow@users.noreply.github.com>
+Maria Marginean <33810762+mmargin@users.noreply.github.com>
+Akash Agrawall 
+jgulian 
+Sourav Goyal 
+Zlatan Vasović 
+Alex Meiburg 
+Smit Lunagariya 
+Naman Gera 
+Julien Palard 
+Dhruv Mendiratta 
+erdOne <36414270+erdOne@users.noreply.github.com>
+risubaba 
+abhinav28071999 <41710346+abhinav28071999@users.noreply.github.com>
+Jisoo Song 
+Jaime R <38530589+Jaime02@users.noreply.github.com>
+Vikrant Malik 
+Hardik Saini <43683678+Guardianofgotham@users.noreply.github.com>
+Abhishek 
+Johannes Hartung 
+Milan Jolly 
+faizan2700 
+mohit <39158356+mohitacecode@users.noreply.github.com>
+Mohit Gupta 
+Psycho-Pirate 
+Chanakya-Ekbote 
+Rashmi Shehana 
+Jonty16117 
+Anubhav Gupta 
+Michal Grňo 
+vezeli <37907135+vezeli@users.noreply.github.com>
+Tim Gates 
+Sandeep Murthy 
+Neil 
+V1krant <46847915+V1krant@users.noreply.github.com>
+alejandro 
+Riyan Dhiman 
+sbt4104 
+Seth Troisi 
+Bhaskar Gupta 
+Smit Gajjar 
+rbl 
+Ilya Pchelintsev 
+Omar Wagih 
+prshnt19 
+Johan Guzman 
+Vasileios Kalos 
+BasileiosKal <61801875+BasileiosKal@users.noreply.github.com>
+Shubham Thorat <37049710+sbt4104@users.noreply.github.com>
+Arpan Chattopadhyay 
+Ashutosh Hathidara 
+Moses Paul R 
+Saanidhya vats 
+tnzl 
+Vatsal Srivastava 
+Jean-Luc Herren 
+Dhruv Kothari 
+seadavis <45022599+seadavis@users.noreply.github.com>
+kamimura 
+slacker404 
+Jaime Resano 
+Ebrahim Byagowi 
+wuyudi 
+Akira Kyle 
+Calvin Jay Ross 
+Martin Thoma 
+Thomas A Caswell 
+Lagaras Stelios 
+Jerry James 
+Jan Kruse 
+Nathan Taylor 
+Vaishnav Damani 
+Mohit Shah 
+Mathias Louboutin 
+Marijan Smetko 
+Dave Witte Morris 
+soumi7 
+Zhongshi 
+Wes Galbraith 
+KaustubhDamania 
+w495 
+Akhil Rajput 
+Markus Mohrhard 
+Benjamin Wolba 
+彭于斌 <1931127624@qq.com>
+Rudr Tiwari 
+Aaryan Dewan 
+Benedikt Placke 
+Sneha Goddu 
+goddus <39923708+goddus@users.noreply.github.com>
+Shivang Dubey 
+Michael Greminger 
+Peter Cock 
+Willem Melching 
+Elias Basler 
+Brandon David 
+Abhay_Dhiman 
+Tasha Kim 
+Ayush Malik 
+Devesh Sawant 
+Wolfgang Stöcher 
+Sudeep Sidhu 
+foice 
+Ben Payne 
+Muskan Kumar <31043527+muskanvk@users.noreply.github.com>
+noam simcha finkelstein 
+Garrett Folbe 
+Islam Mansour 
+Sayandip Halder 
+Shubham Agrawal 
+numbermaniac <5206120+numbermaniac@users.noreply.github.com>
+Sakirul Alam 
+Mohammed Bilal 
+Chris du Plessis 
+Coder-RG 
+Ansh Mishra 
+Alex Malins 
+Lorenzo Contento 
+Naveen Sai 
+Shital Mule 
+Amanda Dsouza 
+Nijso Beishuizen 
+Harry Zheng 
+Felix Yan 
+Constantin Mateescu 
+Eva Tiwari 
+Aditya Kumar Sinha 
+Soumi Bardhan <51290447+Soumi7@users.noreply.github.com>
+Kaustubh Chaudhari 
+Kristian Brünn 
+Neel Gorasiya 
+Akshat Sood <68052998+akshatsood2249@users.noreply.github.com>
+Jose M. Gomez 
+Stefan Petrea 
+Praveen Sahu 
+Mark Bell 
+AlexCQY 
+Fabian Froehlich 
+Nikhil Gopalam 
+Kartik Sethi 
+Muhammed Abdul Quadir Owais 
+Harshit Yadav 
+Sidharth Mundhra 
+Suryam Arnav Kalra 
+Prince Gupta 
+Kunal Singh 
+Mayank Raj 
+Achal Jain <2achaljain@gmail.com>
+Mario Maio 
+Aaron Stiff <69512633+AaronStiff@users.noreply.github.com>
+Wyatt Peak 
+Bhaskar Joshi 
+Aditya Jindal 
+Vaibhav Bhat 
+Priyansh Rathi 
+Saket Kumar Singh 
+Yukai Chou 
+Qijia Liu 
+Paul Mandel 
+Nisarg Chaudhari <54911392+Nisarg-Chaudhari@users.noreply.github.com>
+Dominik Stańczak 
+Rodrigo Luger 
+Marco Antônio Habitzreuter 
+Ayush Bisht 
+Akshansh Bhatt 
+Brandon T. Willard 
+Thomas Aarholt 
+Hiren Chalodiya 
+Roland Dixon 
+dimasvq 
+Sagar231 
+Michael Chu 
+Abby Ng 
+Angad Sandhu <55819847+angadsinghsandhu@users.noreply.github.com>
+Alexander Cockburn 
+Yaser AlOsh 
+Davide Sandonà 
+Jonathan Gutow 
+Nihir Agarwal 
+Lee Johnston 
+Zach Carmichael <20629897+craymichael@users.noreply.github.com>
+Vijairam Ganesh Moorthy 
+Hanspeter Schmid 
+Ben Oostendorp 
+Nikita 
+Aman 
+Shashank KS 
+Aman Sharma 
+Anup Parikh 
+Lucy Mountain 
+Miguel Torres Costa 
+Rikard Nordgren 
+Arun sanganal <74652697+ArunSanganal@users.noreply.github.com>
+Kamlesh Joshi <72374645+kamleshjoshi8102@users.noreply.github.com>
+Joseph Rance <56409230+Joseph-Rance@users.noreply.github.com>
+Huangduirong 
+Nils Schulte <47043622+Schnilz@users.noreply.github.com>
+Matt Bogosian 
+Elisha Hollander 
+Aditya Ravuri 
+Mamidi Ratna Praneeth 
+Jeffrey Ryan 
+Jonathan Daniel <36337649+jond01@users.noreply.github.com>
+Robin Richard 
+Gautam Menghani 
+Remco de Boer <29308176+redeboer@users.noreply.github.com>
+Sebastian East 
+Evani Balasubramanyam 
+Rahil Parikh 
+Jason Ross 
+Joannah Nanjekye 
+Ayush Kumar 
+Kshitij 
+Daniel Hyams 
+alijosephine 
+Matthias Köppe 
+mohajain 
+Anibal M. Medina-Mardones 
+Travis Ens 
+Evgenia Karunus 
+Risiraj Dey 
+lastcodestanding 
+Andrey Lekar 
+Abbas Mohammed <42001049+iam-abbas@users.noreply.github.com>
+Anutosh Bhat 
+Steve Kieffer 
+Paul Spiering 
+Pieter Gijsbers 
+Wang Ran (汪然) 
+naelsondouglas 
+Aman Thakur 
+S. Hanko 
+Dennis Sweeney 
+Gurpartap Singh 
+Hampus Malmberg 
+scimax 
+Nikhil Date 
+Kuldeep Borkar Jr 
+AkuBrain <76952313+Franck2111@users.noreply.github.com>
+Leo Battle 
+Advait Pote 
+Anurag Bhat 
+Jeremy Monat 
+Diane Tchuindjo 
+Tom Fryers <61272761+TomFryers@users.noreply.github.com>
+Zouhair 
+zzj <29055749+zjzh@users.noreply.github.com>
+shubhayu09 
+Siddhant Jain 
+Tirthankar Mazumder <63574588+wermos@users.noreply.github.com>
+Sumit Kumar 
+Shivam Sagar 
+Gaurav Jain 
+Andrii Oriekhov 
+Luis Talavera 
+Arie Bovenberg 
+Carson McManus 
+Jack Schmidt <1107865+jackschmidt@users.noreply.github.com>
+Riley Britten 
+Georges Khaznadar 
+Donald Wilson 
+Timo Stienstra 
+dispasha 
+Saksham Alok 
+Varenyam Bhardwaj 
+oittaa <8972248+oittaa@users.noreply.github.com>
+Omkaar <79257339+Pysics@users.noreply.github.com>
+Islem BOUZENIA 
+extraymond 
+Alexander Behrens 
+user202729 <25191436+user202729@users.noreply.github.com>
+Pieter Eendebak 
+Zaz Brown 
+ritikBhandari 
+viocha <66580331+viocha@users.noreply.github.com>
+Arthur Ryman 
+Xiang Wu 
+tttc3 
+Seth Poulsen 
+cocolato 
+Anton Golovanov 
+Gareth Ma 
+Clément M.T. Robert 
+Glenn Horton-Smith 
+Karan 
+Stefan Behnle <84378403+behnle@users.noreply.github.com>
+Shreyash Mishra <72146041+Shreyash-cyber@users.noreply.github.com>
+Arthur Milchior 
+NotWearingPants <26556598+NotWearingPants@users.noreply.github.com>
+Ishan Pandhare 
+Carlos García Montoro 
+Parcly Taxel 
+Saicharan 
+Kunal Sheth 
+Biswadeep Purkayastha <98874428+metabiswadeep@users.noreply.github.com>
+Jyn Spring 琴春 
+Phil LeMaitre 
+Chris Kerr 
+José Senart 
+Uwe L. Korn 
+ForeverHaibara <69423537+ForeverHaibara@users.noreply.github.com>
+Yves Tumushimire 
+wookie184 
+Costor 
+Klaus Rettinghaus 
+Sam Brockie 
+Abhishek Patidar <1e9abhi1e10@gmail.com>
+Eric Demer 
+Pontus von Brömssen 
+Victor Immanuel 
+Evandro Bernardes 
+Michele Ceccacci 
+Ayush Aryan 
+Kishore Gopalakrishnan 
+Jan-Philipp Hoffmann 
+Daiki Takahashi 
+Sayan Mitra 
+Aman Kumar Shukla 
+Zoufiné Lauer-Baré 
+Charles Harris 
+Tejaswini Sanapathi 
+Devansh 
+Aaron Gokaslan 
+Daan Koning (he/him) 
+Steven Burns 
+Jay Patankar 
+Vivek Soni 
+Le Cong Minh Hieu 
+Sam Ritchie 
+Maciej Skórski 
+Tilo Reneau-Cardoso 
+Laurence Warne 
+Lukas Molleman 
+Konstantinos Riganas 
+Grace Su 
+Pedro Rosa 
+Abhinav Cillanki 
+Baiyuan Qiu <1061688677@qq.com>
+Liwei Cai 
+Daniel Weindl 
+Isidora Araya 
+Seb Tiburzio 
+Victory Omole 
+Abhishek Chaudhary 
+Alexander Zhura 
+Shuai Zhou 
+Martin Manns 
+John Möller 
+zzc <1378113190@qq.com>
+Pablo Galindo Salgado 
+Johannes Kasimir 
+Theodore Dias 
+Kaustubh <90597818+kaustubh-765@users.noreply.github.com>
+Idan Pazi 
+Bobby Palmer 
+Saikat Das 
+Suman mondal 
+Taylan Sahin 
+Fabio Luporini 
+Oriel Malihi 
+Geetika Vadali 
+Matthias Rettl 
+Mikhail Remnev 
+philwillnyc <56197213+philwillnyc@users.noreply.github.com>
+Raphael Lehner 
+Harry Mountain 
+Bhavik Sachdev 
+袁野 (Yuan Ye) 
+fazledyn-or 
+mohammedouahman 
+K. Kraus 
+Zac Hatfield-Dodds 
+platypus 
+codecruisader 
+James Whitehead 
+atharvParlikar 
+Ivan Petukhov 
+Augusto Borges 
+Han Wei Ang 
+Congxu Yang 
+Saicharan <62512681+saicharan2804@users.noreply.github.com>
+Arnab Nandi 
+Harrison Oates <48871176+HarrisonOates@users.noreply.github.com>
+Corey Cerovsek 
+Harsh Kasat 
+omahs <73983677+omahs@users.noreply.github.com>
+Pascal Gitz 
+Ravindu-Hirimuthugoda 
+Sophia Pustova 
+George Pittock 
+Warren Jacinto 
+Sachin Singh 
+Zedmat <104870914+harshkasat@users.noreply.github.com>
+Soumendra Ganguly 
+Samith Karunathilake <55777141+samithkavishke@users.noreply.github.com>
+Viraj Vekaria 
+Shishir Kushwaha 
+Ankit Kumar Singh 
+Abhishek Kumar 
+Mohak Malviya 
+Matthias Liesenfeld <116307294+maliesen@users.noreply.github.com>
+dodo 
+Mohamed Rezk 
+Tommaso Vaccari <05-gesto-follemente@icloud.com>
+Alexis Schotte 
+Lauren Yim <31467609+cherryblossom000@users.noreply.github.com>
+Prey Patel 
+Riccardo Di Girolamo 
+Abhishek kumar 
+Sam Lubelsky 
+Henrique Soares 
+Vladimir Sereda 
+Hwayeon Kang 
+Raj Sapale 
+Gerald Teschl 
+Richard Samuel <98638849+samuelard7@users.noreply.github.com>
+HeeJae Chang 
+Nick Harder 
+Ethan DeGuire 
+Lorenz Winkler 
+Richard Rodenbusch 
+Zhenxu Zhu 
+Mark van Gelder 
+Mark van Gelder 
+Ishan Pandhare <91841626+Ishanned@users.noreply.github.com>
+James A. Preiss 
+Emile Fourcini 
+Alberto Jiménez Ruiz 
+João Bravo 
+Dean Price 
+Edward Z. Yang 
+James Titus 
+Zhuoyuan Li 
+Hugo Kerstens 
+Jan Jancar 
+Andrew Mosson 
+Marek Madejski 
+Gonzalo Tornaría 
+Peter Stahlecker 
+Jean-François B <2589111+jfbu@users.noreply.github.com>
+Zexuan Zhou (Bruce) 
+George Frolov 
+Corbet Elkins 
+Håkon Kvernmoen 
+Muhammad Maaz 
+Shishir Kushwaha <138311586+shishir-11@users.noreply.github.com>
+Matt Wang 
+bharatAmeria <21001019007@jcboseust.ac.in>
+Amir Ebrahimi 
+Steven Esquea 
+Rishabh Kamboj <111004091+VectorNd@users.noreply.github.com>
+Aasim Ali 
+Ivan A. Melnikov 
+Borek Saheli 
+Guido Roncarolo 
+Quek Zi Yao 
+Roelof Rietbroek 
+MostafaGalal1 
+Au Huishan 
+Kris Katterjohn 
+Shiyao Guo 
+Rushabh Mehta 
+Temiloluwa Yusuf ytemiloluwa@gmail.com ytemiloluwa 
+Davi Laerte 
+Agriya Khetarpal <74401230+agriyakhetarpal@users.noreply.github.com>
+Harshit Gupta 
+Praveen Perumal 
+Kevin McWhirter 
+Prayag V 
+Lucas Kletzander 
+Pratyksh Gupta 
+Leonardo Mangani 
+Karan Anand 
+Gagan Mishra 
+Krishnav Bajoria 
+Matt Ord 
+Jatin Bhardwaj 
+Prashant Tandon 
+Paramjit Singh 
+João Rodrigues 
+Alejandro García Prada <114813960+AlexGarciaPrada@users.noreply.github.com>
+Matthew Treinish 
+Clayton Rabideau 
+Victoria Koval 
+Voaides Negustor Robert <134785947+voaidesr@users.noreply.github.com>
+Ovsk Mendov 
+David Brooks 
+Nicholas Laustrup <124007393+nicklaustrup@users.noreply.github.com>
+Harikrishna Srinivasan 
+Mathis Cros 
+Arnav Mummineni <45217840+RCoder01@users.noreply.github.com>
+Thangaraju Sibiraj <85477603+t-sibiraj@users.noreply.github.com>
+KJaybhaye 
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/licenses/LICENSE b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..0744f229d697ca3ed1b1b257bfdb70e3eecf0b9e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/licenses/LICENSE
@@ -0,0 +1,153 @@
+Copyright (c) 2006-2023 SymPy Development Team
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+  a. Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+  b. 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.
+  c. Neither the name of SymPy 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGE.
+
+--------------------------------------------------------------------------------
+
+Patches that were taken from the Diofant project (https://github.com/diofant/diofant)
+are licensed as:
+
+Copyright (c) 2006-2018 SymPy Development Team,
+              2013-2023 Sergey B Kirpichev
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+  a. Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+  b. 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.
+  c. Neither the name of Diofant or SymPy 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGE.
+
+--------------------------------------------------------------------------------
+
+Submodules taken from the multipledispatch project (https://github.com/mrocklin/multipledispatch)
+are licensed as:
+
+Copyright (c) 2014 Matthew Rocklin
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+  a. Redistributions of source code must retain the above copyright notice,
+     this list of conditions and the following disclaimer.
+  b. 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.
+  c. Neither the name of multipledispatch 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGE.
+
+--------------------------------------------------------------------------------
+
+The files under the directory sympy/parsing/autolev/tests/pydy-example-repo
+are directly copied from PyDy project and are licensed as:
+
+Copyright (c) 2009-2023, PyDy Authors
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* 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 this 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 PYDY AUTHORS 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.
+
+--------------------------------------------------------------------------------
+
+The files under the directory sympy/parsing/latex 
+are directly copied from latex2sympy project and are licensed as:
+
+Copyright 2016, latex2sympy
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/top_level.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..0aa85c253508b68bb075f556be3c3f76dc4467ad
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy-1.14.0.dist-info/top_level.txt
@@ -0,0 +1,2 @@
+isympy
+sympy
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d038f07f69191b1e2e12ea462f4bfd9e3b568bd9
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/__pycache__/release.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/__pycache__/release.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..13c855ea379262b750b002912b22829fb152cf51
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/__pycache__/release.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..865c0556769e35ca7e8a09a4c208a1cfbd17369c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__init__.py
@@ -0,0 +1,25 @@
+"""Calculus-related methods."""
+
+from .euler import euler_equations
+from .singularities import (singularities, is_increasing,
+                            is_strictly_increasing, is_decreasing,
+                            is_strictly_decreasing, is_monotonic)
+from .finite_diff import finite_diff_weights, apply_finite_diff, differentiate_finite
+from .util import (periodicity, not_empty_in, is_convex,
+                   stationary_points, minimum, maximum)
+from .accumulationbounds import AccumBounds
+
+__all__ = [
+'euler_equations',
+
+'singularities', 'is_increasing',
+'is_strictly_increasing', 'is_decreasing',
+'is_strictly_decreasing', 'is_monotonic',
+
+'finite_diff_weights', 'apply_finite_diff', 'differentiate_finite',
+
+'periodicity', 'not_empty_in', 'is_convex', 'stationary_points',
+'minimum', 'maximum',
+
+'AccumBounds'
+]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fed4c1e8a816e753f341a97825986e83c5da6d7d
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__pycache__/accumulationbounds.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__pycache__/accumulationbounds.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..91db04150aa3a95ac0986cd2d410ec478f13df18
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__pycache__/accumulationbounds.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__pycache__/euler.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__pycache__/euler.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a6310bf2409be2602bebaeb7f444adc16ed0a78f
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__pycache__/euler.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__pycache__/finite_diff.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__pycache__/finite_diff.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b2b6c7d40b7f92a68da60eb2806547678a7a2f48
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__pycache__/finite_diff.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__pycache__/singularities.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__pycache__/singularities.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9728b01a62c7c2b23711976ebb99c2e4c3a6801b
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__pycache__/singularities.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__pycache__/util.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__pycache__/util.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dd3318042e89d9bdb60c187f57b6531cf4030b97
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/__pycache__/util.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/accumulationbounds.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/accumulationbounds.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a2b0e634da1028c25399c8b03884865d981a56e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/accumulationbounds.py
@@ -0,0 +1,804 @@
+from sympy.core import Add, Mul, Pow, S
+from sympy.core.basic import Basic
+from sympy.core.expr import Expr
+from sympy.core.numbers import _sympifyit, oo, zoo
+from sympy.core.relational import is_le, is_lt, is_ge, is_gt
+from sympy.core.sympify import _sympify
+from sympy.functions.elementary.miscellaneous import Min, Max
+from sympy.logic.boolalg import And
+from sympy.multipledispatch import dispatch
+from sympy.series.order import Order
+from sympy.sets.sets import FiniteSet
+
+
+class AccumulationBounds(Expr):
+    r"""An accumulation bounds.
+
+    # Note AccumulationBounds has an alias: AccumBounds
+
+    AccumulationBounds represent an interval `[a, b]`, which is always closed
+    at the ends. Here `a` and `b` can be any value from extended real numbers.
+
+    The intended meaning of AccummulationBounds is to give an approximate
+    location of the accumulation points of a real function at a limit point.
+
+    Let `a` and `b` be reals such that `a \le b`.
+
+    `\left\langle a, b\right\rangle = \{x \in \mathbb{R} \mid a \le x \le b\}`
+
+    `\left\langle -\infty, b\right\rangle = \{x \in \mathbb{R} \mid x \le b\} \cup \{-\infty, \infty\}`
+
+    `\left\langle a, \infty \right\rangle = \{x \in \mathbb{R} \mid a \le x\} \cup \{-\infty, \infty\}`
+
+    `\left\langle -\infty, \infty \right\rangle = \mathbb{R} \cup \{-\infty, \infty\}`
+
+    ``oo`` and ``-oo`` are added to the second and third definition respectively,
+    since if either ``-oo`` or ``oo`` is an argument, then the other one should
+    be included (though not as an end point). This is forced, since we have,
+    for example, ``1/AccumBounds(0, 1) = AccumBounds(1, oo)``, and the limit at
+    `0` is not one-sided. As `x` tends to `0-`, then `1/x \rightarrow -\infty`, so `-\infty`
+    should be interpreted as belonging to ``AccumBounds(1, oo)`` though it need
+    not appear explicitly.
+
+    In many cases it suffices to know that the limit set is bounded.
+    However, in some other cases more exact information could be useful.
+    For example, all accumulation values of `\cos(x) + 1` are non-negative.
+    (``AccumBounds(-1, 1) + 1 = AccumBounds(0, 2)``)
+
+    A AccumulationBounds object is defined to be real AccumulationBounds,
+    if its end points are finite reals.
+
+    Let `X`, `Y` be real AccumulationBounds, then their sum, difference,
+    product are defined to be the following sets:
+
+    `X + Y = \{ x+y \mid x \in X \cap y \in Y\}`
+
+    `X - Y = \{ x-y \mid x \in X \cap y \in Y\}`
+
+    `X \times Y = \{ x \times y \mid x \in X \cap y \in Y\}`
+
+    When an AccumBounds is raised to a negative power, if 0 is contained
+    between the bounds then an infinite range is returned, otherwise if an
+    endpoint is 0 then a semi-infinite range with consistent sign will be returned.
+
+    AccumBounds in expressions behave a lot like Intervals but the
+    semantics are not necessarily the same. Division (or exponentiation
+    to a negative integer power) could be handled with *intervals* by
+    returning a union of the results obtained after splitting the
+    bounds between negatives and positives, but that is not done with
+    AccumBounds. In addition, bounds are assumed to be independent of
+    each other; if the same bound is used in more than one place in an
+    expression, the result may not be the supremum or infimum of the
+    expression (see below). Finally, when a boundary is ``1``,
+    exponentiation to the power of ``oo`` yields ``oo``, neither
+    ``1`` nor ``nan``.
+
+    Examples
+    ========
+
+    >>> from sympy import AccumBounds, sin, exp, log, pi, E, S, oo
+    >>> from sympy.abc import x
+
+    >>> AccumBounds(0, 1) + AccumBounds(1, 2)
+    AccumBounds(1, 3)
+
+    >>> AccumBounds(0, 1) - AccumBounds(0, 2)
+    AccumBounds(-2, 1)
+
+    >>> AccumBounds(-2, 3)*AccumBounds(-1, 1)
+    AccumBounds(-3, 3)
+
+    >>> AccumBounds(1, 2)*AccumBounds(3, 5)
+    AccumBounds(3, 10)
+
+    The exponentiation of AccumulationBounds is defined
+    as follows:
+
+    If 0 does not belong to `X` or `n > 0` then
+
+    `X^n = \{ x^n \mid x \in X\}`
+
+    >>> AccumBounds(1, 4)**(S(1)/2)
+    AccumBounds(1, 2)
+
+    otherwise, an infinite or semi-infinite result is obtained:
+
+    >>> 1/AccumBounds(-1, 1)
+    AccumBounds(-oo, oo)
+    >>> 1/AccumBounds(0, 2)
+    AccumBounds(1/2, oo)
+    >>> 1/AccumBounds(-oo, 0)
+    AccumBounds(-oo, 0)
+
+    A boundary of 1 will always generate all nonnegatives:
+
+    >>> AccumBounds(1, 2)**oo
+    AccumBounds(0, oo)
+    >>> AccumBounds(0, 1)**oo
+    AccumBounds(0, oo)
+
+    If the exponent is itself an AccumulationBounds or is not an
+    integer then unevaluated results will be returned unless the base
+    values are positive:
+
+    >>> AccumBounds(2, 3)**AccumBounds(-1, 2)
+    AccumBounds(1/3, 9)
+    >>> AccumBounds(-2, 3)**AccumBounds(-1, 2)
+    AccumBounds(-2, 3)**AccumBounds(-1, 2)
+
+    >>> AccumBounds(-2, -1)**(S(1)/2)
+    sqrt(AccumBounds(-2, -1))
+
+    Note: `\left\langle a, b\right\rangle^2` is not same as `\left\langle a, b\right\rangle \times \left\langle a, b\right\rangle`
+
+    >>> AccumBounds(-1, 1)**2
+    AccumBounds(0, 1)
+
+    >>> AccumBounds(1, 3) < 4
+    True
+
+    >>> AccumBounds(1, 3) < -1
+    False
+
+    Some elementary functions can also take AccumulationBounds as input.
+    A function `f` evaluated for some real AccumulationBounds `\left\langle a, b \right\rangle`
+    is defined as `f(\left\langle a, b\right\rangle) = \{ f(x) \mid a \le x \le b \}`
+
+    >>> sin(AccumBounds(pi/6, pi/3))
+    AccumBounds(1/2, sqrt(3)/2)
+
+    >>> exp(AccumBounds(0, 1))
+    AccumBounds(1, E)
+
+    >>> log(AccumBounds(1, E))
+    AccumBounds(0, 1)
+
+    Some symbol in an expression can be substituted for a AccumulationBounds
+    object. But it does not necessarily evaluate the AccumulationBounds for
+    that expression.
+
+    The same expression can be evaluated to different values depending upon
+    the form it is used for substitution since each instance of an
+    AccumulationBounds is considered independent. For example:
+
+    >>> (x**2 + 2*x + 1).subs(x, AccumBounds(-1, 1))
+    AccumBounds(-1, 4)
+
+    >>> ((x + 1)**2).subs(x, AccumBounds(-1, 1))
+    AccumBounds(0, 4)
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Interval_arithmetic
+
+    .. [2] https://fab.cba.mit.edu/classes/S62.12/docs/Hickey_interval.pdf
+
+    Notes
+    =====
+
+    Do not use ``AccumulationBounds`` for floating point interval arithmetic
+    calculations, use ``mpmath.iv`` instead.
+    """
+
+    is_extended_real = True
+    is_number = False
+
+    def __new__(cls, min, max) -> Expr: # type: ignore
+
+        min = _sympify(min)
+        max = _sympify(max)
+
+        # Only allow real intervals (use symbols with 'is_extended_real=True').
+        if not min.is_extended_real or not max.is_extended_real:
+            raise ValueError("Only real AccumulationBounds are supported")
+
+        if max == min:
+            return max
+
+        # Make sure that the created AccumBounds object will be valid.
+        if max.is_number and min.is_number:
+            bad = max.is_comparable and min.is_comparable and max < min
+        else:
+            bad = (max - min).is_extended_negative
+        if bad:
+            raise ValueError(
+                "Lower limit should be smaller than upper limit")
+
+        return Basic.__new__(cls, min, max)
+
+    # setting the operation priority
+    _op_priority = 11.0
+
+    def _eval_is_real(self):
+        if self.min.is_real and self.max.is_real:
+            return True
+
+    @property
+    def min(self):
+        """
+        Returns the minimum possible value attained by AccumulationBounds
+        object.
+
+        Examples
+        ========
+
+        >>> from sympy import AccumBounds
+        >>> AccumBounds(1, 3).min
+        1
+
+        """
+        return self.args[0]
+
+    @property
+    def max(self):
+        """
+        Returns the maximum possible value attained by AccumulationBounds
+        object.
+
+        Examples
+        ========
+
+        >>> from sympy import AccumBounds
+        >>> AccumBounds(1, 3).max
+        3
+
+        """
+        return self.args[1]
+
+    @property
+    def delta(self):
+        """
+        Returns the difference of maximum possible value attained by
+        AccumulationBounds object and minimum possible value attained
+        by AccumulationBounds object.
+
+        Examples
+        ========
+
+        >>> from sympy import AccumBounds
+        >>> AccumBounds(1, 3).delta
+        2
+
+        """
+        return self.max - self.min
+
+    @property
+    def mid(self):
+        """
+        Returns the mean of maximum possible value attained by
+        AccumulationBounds object and minimum possible value
+        attained by AccumulationBounds object.
+
+        Examples
+        ========
+
+        >>> from sympy import AccumBounds
+        >>> AccumBounds(1, 3).mid
+        2
+
+        """
+        return (self.min + self.max) / 2
+
+    @_sympifyit('other', NotImplemented)
+    def _eval_power(self, other):
+        return self.__pow__(other)
+
+    @_sympifyit('other', NotImplemented)
+    def __add__(self, other):
+        if isinstance(other, Expr):
+            if isinstance(other, AccumBounds):
+                return AccumBounds(
+                    Add(self.min, other.min),
+                    Add(self.max, other.max))
+            if other is S.Infinity and self.min is S.NegativeInfinity or \
+                    other is S.NegativeInfinity and self.max is S.Infinity:
+                return AccumBounds(-oo, oo)
+            elif other.is_extended_real:
+                if self.min is S.NegativeInfinity and self.max is S.Infinity:
+                    return AccumBounds(-oo, oo)
+                elif self.min is S.NegativeInfinity:
+                    return AccumBounds(-oo, self.max + other)
+                elif self.max is S.Infinity:
+                    return AccumBounds(self.min + other, oo)
+                else:
+                    return AccumBounds(Add(self.min, other), Add(self.max, other))
+            return Add(self, other, evaluate=False)
+        return NotImplemented
+
+    __radd__ = __add__
+
+    def __neg__(self):
+        return AccumBounds(-self.max, -self.min)
+
+    @_sympifyit('other', NotImplemented)
+    def __sub__(self, other):
+        if isinstance(other, Expr):
+            if isinstance(other, AccumBounds):
+                return AccumBounds(
+                    Add(self.min, -other.max),
+                    Add(self.max, -other.min))
+            if other is S.NegativeInfinity and self.min is S.NegativeInfinity or \
+                    other is S.Infinity and self.max is S.Infinity:
+                return AccumBounds(-oo, oo)
+            elif other.is_extended_real:
+                if self.min is S.NegativeInfinity and self.max is S.Infinity:
+                    return AccumBounds(-oo, oo)
+                elif self.min is S.NegativeInfinity:
+                    return AccumBounds(-oo, self.max - other)
+                elif self.max is S.Infinity:
+                    return AccumBounds(self.min - other, oo)
+                else:
+                    return AccumBounds(
+                        Add(self.min, -other),
+                        Add(self.max, -other))
+            return Add(self, -other, evaluate=False)
+        return NotImplemented
+
+    @_sympifyit('other', NotImplemented)
+    def __rsub__(self, other):
+        return self.__neg__() + other
+
+    @_sympifyit('other', NotImplemented)
+    def __mul__(self, other):
+        if self.args == (-oo, oo):
+            return self
+        if isinstance(other, Expr):
+            if isinstance(other, AccumBounds):
+                if other.args == (-oo, oo):
+                    return other
+                v = set()
+                for a in self.args:
+                    vi = other*a
+                    v.update(vi.args or (vi,))
+                return AccumBounds(Min(*v), Max(*v))
+            if other is S.Infinity:
+                if self.min.is_zero:
+                    return AccumBounds(0, oo)
+                if self.max.is_zero:
+                    return AccumBounds(-oo, 0)
+            if other is S.NegativeInfinity:
+                if self.min.is_zero:
+                    return AccumBounds(-oo, 0)
+                if self.max.is_zero:
+                    return AccumBounds(0, oo)
+            if other.is_extended_real:
+                if other.is_zero:
+                    if self.max is S.Infinity:
+                        return AccumBounds(0, oo)
+                    if self.min is S.NegativeInfinity:
+                        return AccumBounds(-oo, 0)
+                    return S.Zero
+                if other.is_extended_positive:
+                    return AccumBounds(
+                        Mul(self.min, other),
+                        Mul(self.max, other))
+                elif other.is_extended_negative:
+                    return AccumBounds(
+                        Mul(self.max, other),
+                        Mul(self.min, other))
+            if isinstance(other, Order):
+                return other
+            return Mul(self, other, evaluate=False)
+        return NotImplemented
+
+    __rmul__ = __mul__
+
+    @_sympifyit('other', NotImplemented)
+    def __truediv__(self, other):
+        if isinstance(other, Expr):
+            if isinstance(other, AccumBounds):
+                if other.min.is_positive or other.max.is_negative:
+                    return self * AccumBounds(1/other.max, 1/other.min)
+
+                if (self.min.is_extended_nonpositive and self.max.is_extended_nonnegative and
+                    other.min.is_extended_nonpositive and other.max.is_extended_nonnegative):
+                    if self.min.is_zero and other.min.is_zero:
+                        return AccumBounds(0, oo)
+                    if self.max.is_zero and other.min.is_zero:
+                        return AccumBounds(-oo, 0)
+                    return AccumBounds(-oo, oo)
+
+                if self.max.is_extended_negative:
+                    if other.min.is_extended_negative:
+                        if other.max.is_zero:
+                            return AccumBounds(self.max / other.min, oo)
+                        if other.max.is_extended_positive:
+                            # if we were dealing with intervals we would return
+                            # Union(Interval(-oo, self.max/other.max),
+                            #       Interval(self.max/other.min, oo))
+                            return AccumBounds(-oo, oo)
+
+                    if other.min.is_zero and other.max.is_extended_positive:
+                        return AccumBounds(-oo, self.max / other.max)
+
+                if self.min.is_extended_positive:
+                    if other.min.is_extended_negative:
+                        if other.max.is_zero:
+                            return AccumBounds(-oo, self.min / other.min)
+                        if other.max.is_extended_positive:
+                            # if we were dealing with intervals we would return
+                            # Union(Interval(-oo, self.min/other.min),
+                            #       Interval(self.min/other.max, oo))
+                            return AccumBounds(-oo, oo)
+
+                    if other.min.is_zero and other.max.is_extended_positive:
+                        return AccumBounds(self.min / other.max, oo)
+
+            elif other.is_extended_real:
+                if other in (S.Infinity, S.NegativeInfinity):
+                    if self == AccumBounds(-oo, oo):
+                        return AccumBounds(-oo, oo)
+                    if self.max is S.Infinity:
+                        return AccumBounds(Min(0, other), Max(0, other))
+                    if self.min is S.NegativeInfinity:
+                        return AccumBounds(Min(0, -other), Max(0, -other))
+                if other.is_extended_positive:
+                    return AccumBounds(self.min / other, self.max / other)
+                elif other.is_extended_negative:
+                    return AccumBounds(self.max / other, self.min / other)
+            if (1 / other) is S.ComplexInfinity:
+                return Mul(self, 1 / other, evaluate=False)
+            else:
+                return Mul(self, 1 / other)
+
+        return NotImplemented
+
+    @_sympifyit('other', NotImplemented)
+    def __rtruediv__(self, other):
+        if isinstance(other, Expr):
+            if other.is_extended_real:
+                if other.is_zero:
+                    return S.Zero
+                if (self.min.is_extended_nonpositive and self.max.is_extended_nonnegative):
+                    if self.min.is_zero:
+                        if other.is_extended_positive:
+                            return AccumBounds(Mul(other, 1 / self.max), oo)
+                        if other.is_extended_negative:
+                            return AccumBounds(-oo, Mul(other, 1 / self.max))
+                    if self.max.is_zero:
+                        if other.is_extended_positive:
+                            return AccumBounds(-oo, Mul(other, 1 / self.min))
+                        if other.is_extended_negative:
+                            return AccumBounds(Mul(other, 1 / self.min), oo)
+                    return AccumBounds(-oo, oo)
+                else:
+                    return AccumBounds(Min(other / self.min, other / self.max),
+                                       Max(other / self.min, other / self.max))
+            return Mul(other, 1 / self, evaluate=False)
+        else:
+            return NotImplemented
+
+    @_sympifyit('other', NotImplemented)
+    def __pow__(self, other):
+        if isinstance(other, Expr):
+            if other is S.Infinity:
+                if self.min.is_extended_nonnegative:
+                    if self.max < 1:
+                        return S.Zero
+                    if self.min > 1:
+                        return S.Infinity
+                    return AccumBounds(0, oo)
+                elif self.max.is_extended_negative:
+                    if self.min > -1:
+                        return S.Zero
+                    if self.max < -1:
+                        return zoo
+                    return S.NaN
+                else:
+                    if self.min > -1:
+                        if self.max < 1:
+                            return S.Zero
+                        return AccumBounds(0, oo)
+                    return AccumBounds(-oo, oo)
+
+            if other is S.NegativeInfinity:
+                return (1/self)**oo
+
+            # generically true
+            if (self.max - self.min).is_nonnegative:
+                # well defined
+                if self.min.is_nonnegative:
+                    # no 0 to worry about
+                    if other.is_nonnegative:
+                        # no infinity to worry about
+                        return self.func(self.min**other, self.max**other)
+
+            if other.is_zero:
+                return S.One  # x**0 = 1
+
+            if other.is_Integer or other.is_integer:
+                if self.min.is_extended_positive:
+                    return AccumBounds(
+                        Min(self.min**other, self.max**other),
+                        Max(self.min**other, self.max**other))
+                elif self.max.is_extended_negative:
+                    return AccumBounds(
+                        Min(self.max**other, self.min**other),
+                        Max(self.max**other, self.min**other))
+
+                if other % 2 == 0:
+                    if other.is_extended_negative:
+                        if self.min.is_zero:
+                            return AccumBounds(self.max**other, oo)
+                        if self.max.is_zero:
+                            return AccumBounds(self.min**other, oo)
+                        return (1/self)**(-other)
+                    return AccumBounds(
+                        S.Zero, Max(self.min**other, self.max**other))
+                elif other % 2 == 1:
+                    if other.is_extended_negative:
+                        if self.min.is_zero:
+                            return AccumBounds(self.max**other, oo)
+                        if self.max.is_zero:
+                            return AccumBounds(-oo, self.min**other)
+                        return (1/self)**(-other)
+                    return AccumBounds(self.min**other, self.max**other)
+
+            # non-integer exponent
+            # 0**neg or neg**frac yields complex
+            if (other.is_number or other.is_rational) and (
+                    self.min.is_extended_nonnegative or (
+                    other.is_extended_nonnegative and
+                    self.min.is_extended_nonnegative)):
+                num, den = other.as_numer_denom()
+                if num is S.One:
+                    return AccumBounds(*[i**(1/den) for i in self.args])
+
+                elif den is not S.One:  # e.g. if other is not Float
+                    return (self**num)**(1/den)  # ok for non-negative base
+
+            if isinstance(other, AccumBounds):
+                if (self.min.is_extended_positive or
+                        self.min.is_extended_nonnegative and
+                        other.min.is_extended_nonnegative):
+                    p = [self**i for i in other.args]
+                    if not any(i.is_Pow for i in p):
+                        a = [j for i in p for j in i.args or (i,)]
+                        try:
+                            return self.func(min(a), max(a))
+                        except TypeError:  # can't sort
+                            pass
+
+            return Pow(self, other, evaluate=False)
+
+        return NotImplemented
+
+    @_sympifyit('other', NotImplemented)
+    def __rpow__(self, other):
+        if other.is_real and other.is_extended_nonnegative and (
+                self.max - self.min).is_extended_positive:
+            if other is S.One:
+                return S.One
+            if other.is_extended_positive:
+                a, b = [other**i for i in self.args]
+                if min(a, b) != a:
+                    a, b = b, a
+                return self.func(a, b)
+            if other.is_zero:
+                if self.min.is_zero:
+                    return self.func(0, 1)
+                if self.min.is_extended_positive:
+                    return S.Zero
+
+        return Pow(other, self, evaluate=False)
+
+    def __abs__(self):
+        if self.max.is_extended_negative:
+            return self.__neg__()
+        elif self.min.is_extended_negative:
+            return AccumBounds(S.Zero, Max(abs(self.min), self.max))
+        else:
+            return self
+
+
+    def __contains__(self, other):
+        """
+        Returns ``True`` if other is contained in self, where other
+        belongs to extended real numbers, ``False`` if not contained,
+        otherwise TypeError is raised.
+
+        Examples
+        ========
+
+        >>> from sympy import AccumBounds, oo
+        >>> 1 in AccumBounds(-1, 3)
+        True
+
+        -oo and oo go together as limits (in AccumulationBounds).
+
+        >>> -oo in AccumBounds(1, oo)
+        True
+
+        >>> oo in AccumBounds(-oo, 0)
+        True
+
+        """
+        other = _sympify(other)
+
+        if other in (S.Infinity, S.NegativeInfinity):
+            if self.min is S.NegativeInfinity or self.max is S.Infinity:
+                return True
+            return False
+
+        rv = And(self.min <= other, self.max >= other)
+        if rv not in (True, False):
+            raise TypeError("input failed to evaluate")
+        return rv
+
+    def intersection(self, other):
+        """
+        Returns the intersection of 'self' and 'other'.
+        Here other can be an instance of :py:class:`~.FiniteSet` or AccumulationBounds.
+
+        Parameters
+        ==========
+
+        other : AccumulationBounds
+            Another AccumulationBounds object with which the intersection
+            has to be computed.
+
+        Returns
+        =======
+
+        AccumulationBounds
+            Intersection of ``self`` and ``other``.
+
+        Examples
+        ========
+
+        >>> from sympy import AccumBounds, FiniteSet
+        >>> AccumBounds(1, 3).intersection(AccumBounds(2, 4))
+        AccumBounds(2, 3)
+
+        >>> AccumBounds(1, 3).intersection(AccumBounds(4, 6))
+        EmptySet
+
+        >>> AccumBounds(1, 4).intersection(FiniteSet(1, 2, 5))
+        {1, 2}
+
+        """
+        if not isinstance(other, (AccumBounds, FiniteSet)):
+            raise TypeError(
+                "Input must be AccumulationBounds or FiniteSet object")
+
+        if isinstance(other, FiniteSet):
+            fin_set = S.EmptySet
+            for i in other:
+                if i in self:
+                    fin_set = fin_set + FiniteSet(i)
+            return fin_set
+
+        if self.max < other.min or self.min > other.max:
+            return S.EmptySet
+
+        if self.min <= other.min:
+            if self.max <= other.max:
+                return AccumBounds(other.min, self.max)
+            if self.max > other.max:
+                return other
+
+        if other.min <= self.min:
+            if other.max < self.max:
+                return AccumBounds(self.min, other.max)
+            if other.max > self.max:
+                return self
+
+    def union(self, other):
+        # TODO : Devise a better method for Union of AccumBounds
+        # this method is not actually correct and
+        # can be made better
+        if not isinstance(other, AccumBounds):
+            raise TypeError(
+                "Input must be AccumulationBounds or FiniteSet object")
+
+        if self.min <= other.min and self.max >= other.min:
+            return AccumBounds(self.min, Max(self.max, other.max))
+
+        if other.min <= self.min and other.max >= self.min:
+            return AccumBounds(other.min, Max(self.max, other.max))
+
+
+@dispatch(AccumulationBounds, AccumulationBounds) # type: ignore # noqa:F811
+def _eval_is_le(lhs, rhs): # noqa:F811
+    if is_le(lhs.max, rhs.min):
+        return True
+    if is_gt(lhs.min, rhs.max):
+        return False
+
+
+@dispatch(AccumulationBounds, Basic) # type: ignore # noqa:F811
+def _eval_is_le(lhs, rhs): # noqa: F811
+
+    """
+    Returns ``True `` if range of values attained by ``lhs`` AccumulationBounds
+    object is greater than the range of values attained by ``rhs``,
+    where ``rhs`` may be any value of type AccumulationBounds object or
+    extended real number value, ``False`` if ``rhs`` satisfies
+    the same property, else an unevaluated :py:class:`~.Relational`.
+
+    Examples
+    ========
+
+    >>> from sympy import AccumBounds, oo
+    >>> AccumBounds(1, 3) > AccumBounds(4, oo)
+    False
+    >>> AccumBounds(1, 4) > AccumBounds(3, 4)
+    AccumBounds(1, 4) > AccumBounds(3, 4)
+    >>> AccumBounds(1, oo) > -1
+    True
+
+    """
+    if not rhs.is_extended_real:
+            raise TypeError(
+                "Invalid comparison of %s %s" %
+                (type(rhs), rhs))
+    elif rhs.is_comparable:
+        if is_le(lhs.max, rhs):
+            return True
+        if is_gt(lhs.min, rhs):
+            return False
+
+
+@dispatch(AccumulationBounds, AccumulationBounds)
+def _eval_is_ge(lhs, rhs): # noqa:F811
+    if is_ge(lhs.min, rhs.max):
+        return True
+    if is_lt(lhs.max, rhs.min):
+        return False
+
+
+@dispatch(AccumulationBounds, Expr)  # type:ignore
+def _eval_is_ge(lhs, rhs): # noqa: F811
+    """
+    Returns ``True`` if range of values attained by ``lhs`` AccumulationBounds
+    object is less that the range of values attained by ``rhs``, where
+    other may be any value of type AccumulationBounds object or extended
+    real number value, ``False`` if ``rhs`` satisfies the same
+    property, else an unevaluated :py:class:`~.Relational`.
+
+    Examples
+    ========
+
+    >>> from sympy import AccumBounds, oo
+    >>> AccumBounds(1, 3) >= AccumBounds(4, oo)
+    False
+    >>> AccumBounds(1, 4) >= AccumBounds(3, 4)
+    AccumBounds(1, 4) >= AccumBounds(3, 4)
+    >>> AccumBounds(1, oo) >= 1
+    True
+    """
+
+    if not rhs.is_extended_real:
+        raise TypeError(
+            "Invalid comparison of %s %s" %
+            (type(rhs), rhs))
+    elif rhs.is_comparable:
+        if is_ge(lhs.min, rhs):
+            return True
+        if is_lt(lhs.max, rhs):
+            return False
+
+
+@dispatch(Expr, AccumulationBounds)  # type:ignore
+def _eval_is_ge(lhs, rhs): # noqa:F811
+    if not lhs.is_extended_real:
+        raise TypeError(
+            "Invalid comparison of %s %s" %
+            (type(lhs), lhs))
+    elif lhs.is_comparable:
+        if is_le(rhs.max, lhs):
+            return True
+        if is_gt(rhs.min, lhs):
+            return False
+
+
+@dispatch(AccumulationBounds, AccumulationBounds)  # type:ignore
+def _eval_is_ge(lhs, rhs): # noqa:F811
+    if is_ge(lhs.min, rhs.max):
+        return True
+    if is_lt(lhs.max, rhs.min):
+        return False
+
+# setting an alias for AccumulationBounds
+AccumBounds = AccumulationBounds
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/euler.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/euler.py
new file mode 100644
index 0000000000000000000000000000000000000000..817acf76091dfba2dba40487ca7735e307c0fc15
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/euler.py
@@ -0,0 +1,108 @@
+"""
+This module implements a method to find
+Euler-Lagrange Equations for given Lagrangian.
+"""
+from itertools import combinations_with_replacement
+from sympy.core.function import (Derivative, Function, diff)
+from sympy.core.relational import Eq
+from sympy.core.singleton import S
+from sympy.core.symbol import Symbol
+from sympy.core.sympify import sympify
+from sympy.utilities.iterables import iterable
+
+
+def euler_equations(L, funcs=(), vars=()):
+    r"""
+    Find the Euler-Lagrange equations [1]_ for a given Lagrangian.
+
+    Parameters
+    ==========
+
+    L : Expr
+        The Lagrangian that should be a function of the functions listed
+        in the second argument and their derivatives.
+
+        For example, in the case of two functions $f(x,y)$, $g(x,y)$ and
+        two independent variables $x$, $y$ the Lagrangian has the form:
+
+            .. math:: L\left(f(x,y),g(x,y),\frac{\partial f(x,y)}{\partial x},
+                      \frac{\partial f(x,y)}{\partial y},
+                      \frac{\partial g(x,y)}{\partial x},
+                      \frac{\partial g(x,y)}{\partial y},x,y\right)
+
+        In many cases it is not necessary to provide anything, except the
+        Lagrangian, it will be auto-detected (and an error raised if this
+        cannot be done).
+
+    funcs : Function or an iterable of Functions
+        The functions that the Lagrangian depends on. The Euler equations
+        are differential equations for each of these functions.
+
+    vars : Symbol or an iterable of Symbols
+        The Symbols that are the independent variables of the functions.
+
+    Returns
+    =======
+
+    eqns : list of Eq
+        The list of differential equations, one for each function.
+
+    Examples
+    ========
+
+    >>> from sympy import euler_equations, Symbol, Function
+    >>> x = Function('x')
+    >>> t = Symbol('t')
+    >>> L = (x(t).diff(t))**2/2 - x(t)**2/2
+    >>> euler_equations(L, x(t), t)
+    [Eq(-x(t) - Derivative(x(t), (t, 2)), 0)]
+    >>> u = Function('u')
+    >>> x = Symbol('x')
+    >>> L = (u(t, x).diff(t))**2/2 - (u(t, x).diff(x))**2/2
+    >>> euler_equations(L, u(t, x), [t, x])
+    [Eq(-Derivative(u(t, x), (t, 2)) + Derivative(u(t, x), (x, 2)), 0)]
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Lagrange_equation
+
+    """
+
+    funcs = tuple(funcs) if iterable(funcs) else (funcs,)
+
+    if not funcs:
+        funcs = tuple(L.atoms(Function))
+    else:
+        for f in funcs:
+            if not isinstance(f, Function):
+                raise TypeError('Function expected, got: %s' % f)
+
+    vars = tuple(vars) if iterable(vars) else (vars,)
+
+    if not vars:
+        vars = funcs[0].args
+    else:
+        vars = tuple(sympify(var) for var in vars)
+
+    if not all(isinstance(v, Symbol) for v in vars):
+        raise TypeError('Variables are not symbols, got %s' % vars)
+
+    for f in funcs:
+        if not vars == f.args:
+            raise ValueError("Variables %s do not match args: %s" % (vars, f))
+
+    order = max([len(d.variables) for d in L.atoms(Derivative)
+                        if d.expr in funcs] + [0])
+
+    eqns = []
+    for f in funcs:
+        eq = diff(L, f)
+        for i in range(1, order + 1):
+            for p in combinations_with_replacement(vars, i):
+                eq = eq + S.NegativeOne**i*diff(L, diff(f, *p), *p)
+        new_eq = Eq(eq, 0)
+        if isinstance(new_eq, Eq):
+            eqns.append(new_eq)
+
+    return eqns
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/finite_diff.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/finite_diff.py
new file mode 100644
index 0000000000000000000000000000000000000000..17eece149aadad236cefeb350e1ef4a383c84f01
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/finite_diff.py
@@ -0,0 +1,476 @@
+"""
+Finite difference weights
+=========================
+
+This module implements an algorithm for efficient generation of finite
+difference weights for ordinary differentials of functions for
+derivatives from 0 (interpolation) up to arbitrary order.
+
+The core algorithm is provided in the finite difference weight generating
+function (``finite_diff_weights``), and two convenience functions are provided
+for:
+
+- estimating a derivative (or interpolate) directly from a series of points
+    is also provided (``apply_finite_diff``).
+- differentiating by using finite difference approximations
+    (``differentiate_finite``).
+
+"""
+
+from sympy.core.function import Derivative
+from sympy.core.singleton import S
+from sympy.core.function import Subs
+from sympy.core.traversal import preorder_traversal
+from sympy.utilities.exceptions import sympy_deprecation_warning
+from sympy.utilities.iterables import iterable
+
+
+
+def finite_diff_weights(order, x_list, x0=S.One):
+    """
+    Calculates the finite difference weights for an arbitrarily spaced
+    one-dimensional grid (``x_list``) for derivatives at ``x0`` of order
+    0, 1, ..., up to ``order`` using a recursive formula. Order of accuracy
+    is at least ``len(x_list) - order``, if ``x_list`` is defined correctly.
+
+    Parameters
+    ==========
+
+    order: int
+        Up to what derivative order weights should be calculated.
+        0 corresponds to interpolation.
+    x_list: sequence
+        Sequence of (unique) values for the independent variable.
+        It is useful (but not necessary) to order ``x_list`` from
+        nearest to furthest from ``x0``; see examples below.
+    x0: Number or Symbol
+        Root or value of the independent variable for which the finite
+        difference weights should be generated. Default is ``S.One``.
+
+    Returns
+    =======
+
+    list
+        A list of sublists, each corresponding to coefficients for
+        increasing derivative order, and each containing lists of
+        coefficients for increasing subsets of x_list.
+
+    Examples
+    ========
+
+    >>> from sympy import finite_diff_weights, S
+    >>> res = finite_diff_weights(1, [-S(1)/2, S(1)/2, S(3)/2, S(5)/2], 0)
+    >>> res
+    [[[1, 0, 0, 0],
+      [1/2, 1/2, 0, 0],
+      [3/8, 3/4, -1/8, 0],
+      [5/16, 15/16, -5/16, 1/16]],
+     [[0, 0, 0, 0],
+      [-1, 1, 0, 0],
+      [-1, 1, 0, 0],
+      [-23/24, 7/8, 1/8, -1/24]]]
+    >>> res[0][-1]  # FD weights for 0th derivative, using full x_list
+    [5/16, 15/16, -5/16, 1/16]
+    >>> res[1][-1]  # FD weights for 1st derivative
+    [-23/24, 7/8, 1/8, -1/24]
+    >>> res[1][-2]  # FD weights for 1st derivative, using x_list[:-1]
+    [-1, 1, 0, 0]
+    >>> res[1][-1][0]  # FD weight for 1st deriv. for x_list[0]
+    -23/24
+    >>> res[1][-1][1]  # FD weight for 1st deriv. for x_list[1], etc.
+    7/8
+
+    Each sublist contains the most accurate formula at the end.
+    Note, that in the above example ``res[1][1]`` is the same as ``res[1][2]``.
+    Since res[1][2] has an order of accuracy of
+    ``len(x_list[:3]) - order = 3 - 1 = 2``, the same is true for ``res[1][1]``!
+
+    >>> res = finite_diff_weights(1, [S(0), S(1), -S(1), S(2), -S(2)], 0)[1]
+    >>> res
+    [[0, 0, 0, 0, 0],
+     [-1, 1, 0, 0, 0],
+     [0, 1/2, -1/2, 0, 0],
+     [-1/2, 1, -1/3, -1/6, 0],
+     [0, 2/3, -2/3, -1/12, 1/12]]
+    >>> res[0]  # no approximation possible, using x_list[0] only
+    [0, 0, 0, 0, 0]
+    >>> res[1]  # classic forward step approximation
+    [-1, 1, 0, 0, 0]
+    >>> res[2]  # classic centered approximation
+    [0, 1/2, -1/2, 0, 0]
+    >>> res[3:]  # higher order approximations
+    [[-1/2, 1, -1/3, -1/6, 0], [0, 2/3, -2/3, -1/12, 1/12]]
+
+    Let us compare this to a differently defined ``x_list``. Pay attention to
+    ``foo[i][k]`` corresponding to the gridpoint defined by ``x_list[k]``.
+
+    >>> foo = finite_diff_weights(1, [-S(2), -S(1), S(0), S(1), S(2)], 0)[1]
+    >>> foo
+    [[0, 0, 0, 0, 0],
+     [-1, 1, 0, 0, 0],
+     [1/2, -2, 3/2, 0, 0],
+     [1/6, -1, 1/2, 1/3, 0],
+     [1/12, -2/3, 0, 2/3, -1/12]]
+    >>> foo[1]  # not the same and of lower accuracy as res[1]!
+    [-1, 1, 0, 0, 0]
+    >>> foo[2]  # classic double backward step approximation
+    [1/2, -2, 3/2, 0, 0]
+    >>> foo[4]  # the same as res[4]
+    [1/12, -2/3, 0, 2/3, -1/12]
+
+    Note that, unless you plan on using approximations based on subsets of
+    ``x_list``, the order of gridpoints does not matter.
+
+    The capability to generate weights at arbitrary points can be
+    used e.g. to minimize Runge's phenomenon by using Chebyshev nodes:
+
+    >>> from sympy import cos, symbols, pi, simplify
+    >>> N, (h, x) = 4, symbols('h x')
+    >>> x_list = [x+h*cos(i*pi/(N)) for i in range(N,-1,-1)] # chebyshev nodes
+    >>> print(x_list)
+    [-h + x, -sqrt(2)*h/2 + x, x, sqrt(2)*h/2 + x, h + x]
+    >>> mycoeffs = finite_diff_weights(1, x_list, 0)[1][4]
+    >>> [simplify(c) for c in  mycoeffs] #doctest: +NORMALIZE_WHITESPACE
+    [(h**3/2 + h**2*x - 3*h*x**2 - 4*x**3)/h**4,
+    (-sqrt(2)*h**3 - 4*h**2*x + 3*sqrt(2)*h*x**2 + 8*x**3)/h**4,
+    (6*h**2*x - 8*x**3)/h**4,
+    (sqrt(2)*h**3 - 4*h**2*x - 3*sqrt(2)*h*x**2 + 8*x**3)/h**4,
+    (-h**3/2 + h**2*x + 3*h*x**2 - 4*x**3)/h**4]
+
+    Notes
+    =====
+
+    If weights for a finite difference approximation of 3rd order
+    derivative is wanted, weights for 0th, 1st and 2nd order are
+    calculated "for free", so are formulae using subsets of ``x_list``.
+    This is something one can take advantage of to save computational cost.
+    Be aware that one should define ``x_list`` from nearest to furthest from
+    ``x0``. If not, subsets of ``x_list`` will yield poorer approximations,
+    which might not grand an order of accuracy of ``len(x_list) - order``.
+
+    See also
+    ========
+
+    sympy.calculus.finite_diff.apply_finite_diff
+
+    References
+    ==========
+
+    .. [1] Generation of Finite Difference Formulas on Arbitrarily Spaced
+            Grids, Bengt Fornberg; Mathematics of computation; 51; 184;
+            (1988); 699-706; doi:10.1090/S0025-5718-1988-0935077-0
+
+    """
+    # The notation below closely corresponds to the one used in the paper.
+    order = S(order)
+    if not order.is_number:
+        raise ValueError("Cannot handle symbolic order.")
+    if order < 0:
+        raise ValueError("Negative derivative order illegal.")
+    if int(order) != order:
+        raise ValueError("Non-integer order illegal")
+    M = order
+    N = len(x_list) - 1
+    delta = [[[0 for nu in range(N+1)] for n in range(N+1)] for
+             m in range(M+1)]
+    delta[0][0][0] = S.One
+    c1 = S.One
+    for n in range(1, N+1):
+        c2 = S.One
+        for nu in range(n):
+            c3 = x_list[n] - x_list[nu]
+            c2 = c2 * c3
+            if n <= M:
+                delta[n][n-1][nu] = 0
+            for m in range(min(n, M)+1):
+                delta[m][n][nu] = (x_list[n]-x0)*delta[m][n-1][nu] -\
+                    m*delta[m-1][n-1][nu]
+                delta[m][n][nu] /= c3
+        for m in range(min(n, M)+1):
+            delta[m][n][n] = c1/c2*(m*delta[m-1][n-1][n-1] -
+                                    (x_list[n-1]-x0)*delta[m][n-1][n-1])
+        c1 = c2
+    return delta
+
+
+def apply_finite_diff(order, x_list, y_list, x0=S.Zero):
+    """
+    Calculates the finite difference approximation of
+    the derivative of requested order at ``x0`` from points
+    provided in ``x_list`` and ``y_list``.
+
+    Parameters
+    ==========
+
+    order: int
+        order of derivative to approximate. 0 corresponds to interpolation.
+    x_list: sequence
+        Sequence of (unique) values for the independent variable.
+    y_list: sequence
+        The function value at corresponding values for the independent
+        variable in x_list.
+    x0: Number or Symbol
+        At what value of the independent variable the derivative should be
+        evaluated. Defaults to 0.
+
+    Returns
+    =======
+
+    sympy.core.add.Add or sympy.core.numbers.Number
+        The finite difference expression approximating the requested
+        derivative order at ``x0``.
+
+    Examples
+    ========
+
+    >>> from sympy import apply_finite_diff
+    >>> cube = lambda arg: (1.0*arg)**3
+    >>> xlist = range(-3,3+1)
+    >>> apply_finite_diff(2, xlist, map(cube, xlist), 2) - 12 # doctest: +SKIP
+    -3.55271367880050e-15
+
+    we see that the example above only contain rounding errors.
+    apply_finite_diff can also be used on more abstract objects:
+
+    >>> from sympy import IndexedBase, Idx
+    >>> x, y = map(IndexedBase, 'xy')
+    >>> i = Idx('i')
+    >>> x_list, y_list = zip(*[(x[i+j], y[i+j]) for j in range(-1,2)])
+    >>> apply_finite_diff(1, x_list, y_list, x[i])
+    ((x[i + 1] - x[i])/(-x[i - 1] + x[i]) - 1)*y[i]/(x[i + 1] - x[i]) -
+    (x[i + 1] - x[i])*y[i - 1]/((x[i + 1] - x[i - 1])*(-x[i - 1] + x[i])) +
+    (-x[i - 1] + x[i])*y[i + 1]/((x[i + 1] - x[i - 1])*(x[i + 1] - x[i]))
+
+    Notes
+    =====
+
+    Order = 0 corresponds to interpolation.
+    Only supply so many points you think makes sense
+    to around x0 when extracting the derivative (the function
+    need to be well behaved within that region). Also beware
+    of Runge's phenomenon.
+
+    See also
+    ========
+
+    sympy.calculus.finite_diff.finite_diff_weights
+
+    References
+    ==========
+
+    Fortran 90 implementation with Python interface for numerics: finitediff_
+
+    .. _finitediff: https://github.com/bjodah/finitediff
+
+    """
+
+    # In the original paper the following holds for the notation:
+    # M = order
+    # N = len(x_list) - 1
+
+    N = len(x_list) - 1
+    if len(x_list) != len(y_list):
+        raise ValueError("x_list and y_list not equal in length.")
+
+    delta = finite_diff_weights(order, x_list, x0)
+
+    derivative = 0
+    for nu in range(len(x_list)):
+        derivative += delta[order][N][nu]*y_list[nu]
+    return derivative
+
+
+def _as_finite_diff(derivative, points=1, x0=None, wrt=None):
+    """
+    Returns an approximation of a derivative of a function in
+    the form of a finite difference formula. The expression is a
+    weighted sum of the function at a number of discrete values of
+    (one of) the independent variable(s).
+
+    Parameters
+    ==========
+
+    derivative: a Derivative instance
+
+    points: sequence or coefficient, optional
+        If sequence: discrete values (length >= order+1) of the
+        independent variable used for generating the finite
+        difference weights.
+        If it is a coefficient, it will be used as the step-size
+        for generating an equidistant sequence of length order+1
+        centered around ``x0``. default: 1 (step-size 1)
+
+    x0: number or Symbol, optional
+        the value of the independent variable (``wrt``) at which the
+        derivative is to be approximated. Default: same as ``wrt``.
+
+    wrt: Symbol, optional
+        "with respect to" the variable for which the (partial)
+        derivative is to be approximated for. If not provided it
+        is required that the Derivative is ordinary. Default: ``None``.
+
+    Examples
+    ========
+
+    >>> from sympy import symbols, Function, exp, sqrt, Symbol
+    >>> from sympy.calculus.finite_diff import _as_finite_diff
+    >>> x, h = symbols('x h')
+    >>> f = Function('f')
+    >>> _as_finite_diff(f(x).diff(x))
+    -f(x - 1/2) + f(x + 1/2)
+
+    The default step size and number of points are 1 and ``order + 1``
+    respectively. We can change the step size by passing a symbol
+    as a parameter:
+
+    >>> _as_finite_diff(f(x).diff(x), h)
+    -f(-h/2 + x)/h + f(h/2 + x)/h
+
+    We can also specify the discretized values to be used in a sequence:
+
+    >>> _as_finite_diff(f(x).diff(x), [x, x+h, x+2*h])
+    -3*f(x)/(2*h) + 2*f(h + x)/h - f(2*h + x)/(2*h)
+
+    The algorithm is not restricted to use equidistant spacing, nor
+    do we need to make the approximation around ``x0``, but we can get
+    an expression estimating the derivative at an offset:
+
+    >>> e, sq2 = exp(1), sqrt(2)
+    >>> xl = [x-h, x+h, x+e*h]
+    >>> _as_finite_diff(f(x).diff(x, 1), xl, x+h*sq2)
+    2*h*((h + sqrt(2)*h)/(2*h) - (-sqrt(2)*h + h)/(2*h))*f(E*h + x)/((-h + E*h)*(h + E*h)) +
+    (-(-sqrt(2)*h + h)/(2*h) - (-sqrt(2)*h + E*h)/(2*h))*f(-h + x)/(h + E*h) +
+    (-(h + sqrt(2)*h)/(2*h) + (-sqrt(2)*h + E*h)/(2*h))*f(h + x)/(-h + E*h)
+
+    Partial derivatives are also supported:
+
+    >>> y = Symbol('y')
+    >>> d2fdxdy=f(x,y).diff(x,y)
+    >>> _as_finite_diff(d2fdxdy, wrt=x)
+    -Derivative(f(x - 1/2, y), y) + Derivative(f(x + 1/2, y), y)
+
+    See also
+    ========
+
+    sympy.calculus.finite_diff.apply_finite_diff
+    sympy.calculus.finite_diff.finite_diff_weights
+
+    """
+    if derivative.is_Derivative:
+        pass
+    elif derivative.is_Atom:
+        return derivative
+    else:
+        return derivative.fromiter(
+            [_as_finite_diff(ar, points, x0, wrt) for ar
+             in derivative.args], **derivative.assumptions0)
+
+    if wrt is None:
+        old = None
+        for v in derivative.variables:
+            if old is v:
+                continue
+            derivative = _as_finite_diff(derivative, points, x0, v)
+            old = v
+        return derivative
+
+    order = derivative.variables.count(wrt)
+
+    if x0 is None:
+        x0 = wrt
+
+    if not iterable(points):
+        if getattr(points, 'is_Function', False) and wrt in points.args:
+            points = points.subs(wrt, x0)
+        # points is simply the step-size, let's make it a
+        # equidistant sequence centered around x0
+        if order % 2 == 0:
+            # even order => odd number of points, grid point included
+            points = [x0 + points*i for i
+                      in range(-order//2, order//2 + 1)]
+        else:
+            # odd order => even number of points, half-way wrt grid point
+            points = [x0 + points*S(i)/2 for i
+                      in range(-order, order + 1, 2)]
+    others = [wrt, 0]
+    for v in set(derivative.variables):
+        if v == wrt:
+            continue
+        others += [v, derivative.variables.count(v)]
+    if len(points) < order+1:
+        raise ValueError("Too few points for order %d" % order)
+    return apply_finite_diff(order, points, [
+        Derivative(derivative.expr.subs({wrt: x}), *others) for
+        x in points], x0)
+
+
+def differentiate_finite(expr, *symbols,
+                         points=1, x0=None, wrt=None, evaluate=False):
+    r""" Differentiate expr and replace Derivatives with finite differences.
+
+    Parameters
+    ==========
+
+    expr : expression
+    \*symbols : differentiate with respect to symbols
+    points: sequence, coefficient or undefined function, optional
+        see ``Derivative.as_finite_difference``
+    x0: number or Symbol, optional
+        see ``Derivative.as_finite_difference``
+    wrt: Symbol, optional
+        see ``Derivative.as_finite_difference``
+
+    Examples
+    ========
+
+    >>> from sympy import sin, Function, differentiate_finite
+    >>> from sympy.abc import x, y, h
+    >>> f, g = Function('f'), Function('g')
+    >>> differentiate_finite(f(x)*g(x), x, points=[x-h, x+h])
+    -f(-h + x)*g(-h + x)/(2*h) + f(h + x)*g(h + x)/(2*h)
+
+    ``differentiate_finite`` works on any expression, including the expressions
+    with embedded derivatives:
+
+    >>> differentiate_finite(f(x) + sin(x), x, 2)
+    -2*f(x) + f(x - 1) + f(x + 1) - 2*sin(x) + sin(x - 1) + sin(x + 1)
+    >>> differentiate_finite(f(x, y), x, y)
+    f(x - 1/2, y - 1/2) - f(x - 1/2, y + 1/2) - f(x + 1/2, y - 1/2) + f(x + 1/2, y + 1/2)
+    >>> differentiate_finite(f(x)*g(x).diff(x), x)
+    (-g(x) + g(x + 1))*f(x + 1/2) - (g(x) - g(x - 1))*f(x - 1/2)
+
+    To make finite difference with non-constant discretization step use
+    undefined functions:
+
+    >>> dx = Function('dx')
+    >>> differentiate_finite(f(x)*g(x).diff(x), points=dx(x))
+    -(-g(x - dx(x)/2 - dx(x - dx(x)/2)/2)/dx(x - dx(x)/2) +
+    g(x - dx(x)/2 + dx(x - dx(x)/2)/2)/dx(x - dx(x)/2))*f(x - dx(x)/2)/dx(x) +
+    (-g(x + dx(x)/2 - dx(x + dx(x)/2)/2)/dx(x + dx(x)/2) +
+    g(x + dx(x)/2 + dx(x + dx(x)/2)/2)/dx(x + dx(x)/2))*f(x + dx(x)/2)/dx(x)
+
+    """
+    if any(term.is_Derivative for term in list(preorder_traversal(expr))):
+        evaluate = False
+
+    Dexpr = expr.diff(*symbols, evaluate=evaluate)
+    if evaluate:
+        sympy_deprecation_warning("""
+        The evaluate flag to differentiate_finite() is deprecated.
+
+        evaluate=True expands the intermediate derivatives before computing
+        differences, but this usually not what you want, as it does not
+        satisfy the product rule.
+        """,
+            deprecated_since_version="1.5",
+             active_deprecations_target="deprecated-differentiate_finite-evaluate",
+        )
+        return Dexpr.replace(
+            lambda arg: arg.is_Derivative,
+            lambda arg: arg.as_finite_difference(points=points, x0=x0, wrt=wrt))
+    else:
+        DFexpr = Dexpr.as_finite_difference(points=points, x0=x0, wrt=wrt)
+        return DFexpr.replace(
+            lambda arg: isinstance(arg, Subs),
+            lambda arg: arg.expr.as_finite_difference(
+                    points=points, x0=arg.point[0], wrt=arg.variables[0]))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/singularities.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/singularities.py
new file mode 100644
index 0000000000000000000000000000000000000000..5adafc59efaf0bff44707f6b5e3f074be6bc1f32
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/singularities.py
@@ -0,0 +1,406 @@
+"""
+Singularities
+=============
+
+This module implements algorithms for finding singularities for a function
+and identifying types of functions.
+
+The differential calculus methods in this module include methods to identify
+the following function types in the given ``Interval``:
+- Increasing
+- Strictly Increasing
+- Decreasing
+- Strictly Decreasing
+- Monotonic
+
+"""
+
+from sympy.core.power import Pow
+from sympy.core.singleton import S
+from sympy.core.symbol import Symbol
+from sympy.core.sympify import sympify
+from sympy.functions.elementary.exponential import log
+from sympy.functions.elementary.trigonometric import sec, csc, cot, tan, cos
+from sympy.functions.elementary.hyperbolic import (
+    sech, csch, coth, tanh, cosh, asech, acsch, atanh, acoth)
+from sympy.utilities.misc import filldedent
+
+
+def singularities(expression, symbol, domain=None):
+    """
+    Find singularities of a given function.
+
+    Parameters
+    ==========
+
+    expression : Expr
+        The target function in which singularities need to be found.
+    symbol : Symbol
+        The symbol over the values of which the singularity in
+        expression in being searched for.
+
+    Returns
+    =======
+
+    Set
+        A set of values for ``symbol`` for which ``expression`` has a
+        singularity. An ``EmptySet`` is returned if ``expression`` has no
+        singularities for any given value of ``Symbol``.
+
+    Raises
+    ======
+
+    NotImplementedError
+        Methods for determining the singularities of this function have
+        not been developed.
+
+    Notes
+    =====
+
+    This function does not find non-isolated singularities
+    nor does it find branch points of the expression.
+
+    Currently supported functions are:
+        - univariate continuous (real or complex) functions
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Mathematical_singularity
+
+    Examples
+    ========
+
+    >>> from sympy import singularities, Symbol, log
+    >>> x = Symbol('x', real=True)
+    >>> y = Symbol('y', real=False)
+    >>> singularities(x**2 + x + 1, x)
+    EmptySet
+    >>> singularities(1/(x + 1), x)
+    {-1}
+    >>> singularities(1/(y**2 + 1), y)
+    {-I, I}
+    >>> singularities(1/(y**3 + 1), y)
+    {-1, 1/2 - sqrt(3)*I/2, 1/2 + sqrt(3)*I/2}
+    >>> singularities(log(x), x)
+    {0}
+
+    """
+    from sympy.solvers.solveset import solveset
+
+    if domain is None:
+        domain = S.Reals if symbol.is_real else S.Complexes
+    try:
+        sings = S.EmptySet
+        e = expression.rewrite([sec, csc, cot, tan], cos)
+        e = e.rewrite([sech, csch, coth, tanh], cosh)
+        for i in e.atoms(Pow):
+            if i.exp.is_infinite:
+                raise NotImplementedError
+            if i.exp.is_negative:
+                # XXX: exponent of varying sign not handled
+                sings += solveset(i.base, symbol, domain)
+        for i in expression.atoms(log, asech, acsch):
+            sings += solveset(i.args[0], symbol, domain)
+        for i in expression.atoms(atanh, acoth):
+            sings += solveset(i.args[0] - 1, symbol, domain)
+            sings += solveset(i.args[0] + 1, symbol, domain)
+        return sings
+    except NotImplementedError:
+        raise NotImplementedError(filldedent('''
+            Methods for determining the singularities
+            of this function have not been developed.'''))
+
+
+###########################################################################
+#                      DIFFERENTIAL CALCULUS METHODS                      #
+###########################################################################
+
+
+def monotonicity_helper(expression, predicate, interval=S.Reals, symbol=None):
+    """
+    Helper function for functions checking function monotonicity.
+
+    Parameters
+    ==========
+
+    expression : Expr
+        The target function which is being checked
+    predicate : function
+        The property being tested for. The function takes in an integer
+        and returns a boolean. The integer input is the derivative and
+        the boolean result should be true if the property is being held,
+        and false otherwise.
+    interval : Set, optional
+        The range of values in which we are testing, defaults to all reals.
+    symbol : Symbol, optional
+        The symbol present in expression which gets varied over the given range.
+
+    It returns a boolean indicating whether the interval in which
+    the function's derivative satisfies given predicate is a superset
+    of the given interval.
+
+    Returns
+    =======
+
+    Boolean
+        True if ``predicate`` is true for all the derivatives when ``symbol``
+        is varied in ``range``, False otherwise.
+
+    """
+    from sympy.solvers.solveset import solveset
+
+    expression = sympify(expression)
+    free = expression.free_symbols
+
+    if symbol is None:
+        if len(free) > 1:
+            raise NotImplementedError(
+                'The function has not yet been implemented'
+                ' for all multivariate expressions.'
+            )
+
+    variable = symbol or (free.pop() if free else Symbol('x'))
+    derivative = expression.diff(variable)
+    predicate_interval = solveset(predicate(derivative), variable, S.Reals)
+    return interval.is_subset(predicate_interval)
+
+
+def is_increasing(expression, interval=S.Reals, symbol=None):
+    """
+    Return whether the function is increasing in the given interval.
+
+    Parameters
+    ==========
+
+    expression : Expr
+        The target function which is being checked.
+    interval : Set, optional
+        The range of values in which we are testing (defaults to set of
+        all real numbers).
+    symbol : Symbol, optional
+        The symbol present in expression which gets varied over the given range.
+
+    Returns
+    =======
+
+    Boolean
+        True if ``expression`` is increasing (either strictly increasing or
+        constant) in the given ``interval``, False otherwise.
+
+    Examples
+    ========
+
+    >>> from sympy import is_increasing
+    >>> from sympy.abc import x, y
+    >>> from sympy import S, Interval, oo
+    >>> is_increasing(x**3 - 3*x**2 + 4*x, S.Reals)
+    True
+    >>> is_increasing(-x**2, Interval(-oo, 0))
+    True
+    >>> is_increasing(-x**2, Interval(0, oo))
+    False
+    >>> is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3))
+    False
+    >>> is_increasing(x**2 + y, Interval(1, 2), x)
+    True
+
+    """
+    return monotonicity_helper(expression, lambda x: x >= 0, interval, symbol)
+
+
+def is_strictly_increasing(expression, interval=S.Reals, symbol=None):
+    """
+    Return whether the function is strictly increasing in the given interval.
+
+    Parameters
+    ==========
+
+    expression : Expr
+        The target function which is being checked.
+    interval : Set, optional
+        The range of values in which we are testing (defaults to set of
+        all real numbers).
+    symbol : Symbol, optional
+        The symbol present in expression which gets varied over the given range.
+
+    Returns
+    =======
+
+    Boolean
+        True if ``expression`` is strictly increasing in the given ``interval``,
+        False otherwise.
+
+    Examples
+    ========
+
+    >>> from sympy import is_strictly_increasing
+    >>> from sympy.abc import x, y
+    >>> from sympy import Interval, oo
+    >>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.Ropen(-oo, -2))
+    True
+    >>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.Lopen(3, oo))
+    True
+    >>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3))
+    False
+    >>> is_strictly_increasing(-x**2, Interval(0, oo))
+    False
+    >>> is_strictly_increasing(-x**2 + y, Interval(-oo, 0), x)
+    False
+
+    """
+    return monotonicity_helper(expression, lambda x: x > 0, interval, symbol)
+
+
+def is_decreasing(expression, interval=S.Reals, symbol=None):
+    """
+    Return whether the function is decreasing in the given interval.
+
+    Parameters
+    ==========
+
+    expression : Expr
+        The target function which is being checked.
+    interval : Set, optional
+        The range of values in which we are testing (defaults to set of
+        all real numbers).
+    symbol : Symbol, optional
+        The symbol present in expression which gets varied over the given range.
+
+    Returns
+    =======
+
+    Boolean
+        True if ``expression`` is decreasing (either strictly decreasing or
+        constant) in the given ``interval``, False otherwise.
+
+    Examples
+    ========
+
+    >>> from sympy import is_decreasing
+    >>> from sympy.abc import x, y
+    >>> from sympy import S, Interval, oo
+    >>> is_decreasing(1/(x**2 - 3*x), Interval.open(S(3)/2, 3))
+    True
+    >>> is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
+    True
+    >>> is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
+    True
+    >>> is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2))
+    False
+    >>> is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, 1.5))
+    False
+    >>> is_decreasing(-x**2, Interval(-oo, 0))
+    False
+    >>> is_decreasing(-x**2 + y, Interval(-oo, 0), x)
+    False
+
+    """
+    return monotonicity_helper(expression, lambda x: x <= 0, interval, symbol)
+
+
+def is_strictly_decreasing(expression, interval=S.Reals, symbol=None):
+    """
+    Return whether the function is strictly decreasing in the given interval.
+
+    Parameters
+    ==========
+
+    expression : Expr
+        The target function which is being checked.
+    interval : Set, optional
+        The range of values in which we are testing (defaults to set of
+        all real numbers).
+    symbol : Symbol, optional
+        The symbol present in expression which gets varied over the given range.
+
+    Returns
+    =======
+
+    Boolean
+        True if ``expression`` is strictly decreasing in the given ``interval``,
+        False otherwise.
+
+    Examples
+    ========
+
+    >>> from sympy import is_strictly_decreasing
+    >>> from sympy.abc import x, y
+    >>> from sympy import S, Interval, oo
+    >>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
+    True
+    >>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2))
+    False
+    >>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, 1.5))
+    False
+    >>> is_strictly_decreasing(-x**2, Interval(-oo, 0))
+    False
+    >>> is_strictly_decreasing(-x**2 + y, Interval(-oo, 0), x)
+    False
+
+    """
+    return monotonicity_helper(expression, lambda x: x < 0, interval, symbol)
+
+
+def is_monotonic(expression, interval=S.Reals, symbol=None):
+    """
+    Return whether the function is monotonic in the given interval.
+
+    Parameters
+    ==========
+
+    expression : Expr
+        The target function which is being checked.
+    interval : Set, optional
+        The range of values in which we are testing (defaults to set of
+        all real numbers).
+    symbol : Symbol, optional
+        The symbol present in expression which gets varied over the given range.
+
+    Returns
+    =======
+
+    Boolean
+        True if ``expression`` is monotonic in the given ``interval``,
+        False otherwise.
+
+    Raises
+    ======
+
+    NotImplementedError
+        Monotonicity check has not been implemented for the queried function.
+
+    Examples
+    ========
+
+    >>> from sympy import is_monotonic
+    >>> from sympy.abc import x, y
+    >>> from sympy import S, Interval, oo
+    >>> is_monotonic(1/(x**2 - 3*x), Interval.open(S(3)/2, 3))
+    True
+    >>> is_monotonic(1/(x**2 - 3*x), Interval.open(1.5, 3))
+    True
+    >>> is_monotonic(1/(x**2 - 3*x), Interval.Lopen(3, oo))
+    True
+    >>> is_monotonic(x**3 - 3*x**2 + 4*x, S.Reals)
+    True
+    >>> is_monotonic(-x**2, S.Reals)
+    False
+    >>> is_monotonic(x**2 + y + 1, Interval(1, 2), x)
+    True
+
+    """
+    from sympy.solvers.solveset import solveset
+
+    expression = sympify(expression)
+
+    free = expression.free_symbols
+    if symbol is None and len(free) > 1:
+        raise NotImplementedError(
+            'is_monotonic has not yet been implemented'
+            ' for all multivariate expressions.'
+        )
+
+    variable = symbol or (free.pop() if free else Symbol('x'))
+    turning_points = solveset(expression.diff(variable), variable, interval)
+    return interval.intersection(turning_points) is S.EmptySet
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/tests/test_accumulationbounds.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/tests/test_accumulationbounds.py
new file mode 100644
index 0000000000000000000000000000000000000000..bcc47c66327fe21ddca3a6b73ca5914e0441b38e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/tests/test_accumulationbounds.py
@@ -0,0 +1,336 @@
+from sympy.core.numbers import (E, Rational, oo, pi, zoo)
+from sympy.core.singleton import S
+from sympy.core.symbol import Symbol
+from sympy.functions.elementary.exponential import (exp, log)
+from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
+from sympy.functions.elementary.trigonometric import (cos, sin, tan)
+from sympy.calculus.accumulationbounds import AccumBounds
+from sympy.core import Add, Mul, Pow
+from sympy.core.expr import unchanged
+from sympy.testing.pytest import raises, XFAIL
+from sympy.abc import x
+
+a = Symbol('a', real=True)
+B = AccumBounds
+
+
+def test_AccumBounds():
+    assert B(1, 2).args == (1, 2)
+    assert B(1, 2).delta is S.One
+    assert B(1, 2).mid == Rational(3, 2)
+    assert B(1, 3).is_real == True
+
+    assert B(1, 1) is S.One
+
+    assert B(1, 2) + 1 == B(2, 3)
+    assert 1 + B(1, 2) == B(2, 3)
+    assert B(1, 2) + B(2, 3) == B(3, 5)
+
+    assert -B(1, 2) == B(-2, -1)
+
+    assert B(1, 2) - 1 == B(0, 1)
+    assert 1 - B(1, 2) == B(-1, 0)
+    assert B(2, 3) - B(1, 2) == B(0, 2)
+
+    assert x + B(1, 2) == Add(B(1, 2), x)
+    assert a + B(1, 2) == B(1 + a, 2 + a)
+    assert B(1, 2) - x == Add(B(1, 2), -x)
+
+    assert B(-oo, 1) + oo == B(-oo, oo)
+    assert B(1, oo) + oo is oo
+    assert B(1, oo) - oo == B(-oo, oo)
+    assert (-oo - B(-1, oo)) is -oo
+    assert B(-oo, 1) - oo is -oo
+
+    assert B(1, oo) - oo == B(-oo, oo)
+    assert B(-oo, 1) - (-oo) == B(-oo, oo)
+    assert (oo - B(1, oo)) == B(-oo, oo)
+    assert (-oo - B(1, oo)) is -oo
+
+    assert B(1, 2)/2 == B(S.Half, 1)
+    assert 2/B(2, 3) == B(Rational(2, 3), 1)
+    assert 1/B(-1, 1) == B(-oo, oo)
+
+    assert abs(B(1, 2)) == B(1, 2)
+    assert abs(B(-2, -1)) == B(1, 2)
+    assert abs(B(-2, 1)) == B(0, 2)
+    assert abs(B(-1, 2)) == B(0, 2)
+    c = Symbol('c')
+    raises(ValueError, lambda: B(0, c))
+    raises(ValueError, lambda: B(1, -1))
+    r = Symbol('r', real=True)
+    raises(ValueError, lambda: B(r, r - 1))
+
+
+def test_AccumBounds_mul():
+    assert B(1, 2)*2 == B(2, 4)
+    assert 2*B(1, 2) == B(2, 4)
+    assert B(1, 2)*B(2, 3) == B(2, 6)
+    assert B(0, 2)*B(2, oo) == B(0, oo)
+    l, r = B(-oo, oo), B(-a, a)
+    assert l*r == B(-oo, oo)
+    assert r*l == B(-oo, oo)
+    l, r = B(1, oo), B(-3, -2)
+    assert l*r == B(-oo, -2)
+    assert r*l == B(-oo, -2)
+    assert B(1, 2)*0 == 0
+    assert B(1, oo)*0 == B(0, oo)
+    assert B(-oo, 1)*0 == B(-oo, 0)
+    assert B(-oo, oo)*0 == B(-oo, oo)
+
+    assert B(1, 2)*x == Mul(B(1, 2), x, evaluate=False)
+
+    assert B(0, 2)*oo == B(0, oo)
+    assert B(-2, 0)*oo == B(-oo, 0)
+    assert B(0, 2)*(-oo) == B(-oo, 0)
+    assert B(-2, 0)*(-oo) == B(0, oo)
+    assert B(-1, 1)*oo == B(-oo, oo)
+    assert B(-1, 1)*(-oo) == B(-oo, oo)
+    assert B(-oo, oo)*oo == B(-oo, oo)
+
+
+def test_AccumBounds_div():
+    assert B(-1, 3)/B(3, 4) == B(Rational(-1, 3), 1)
+    assert B(-2, 4)/B(-3, 4) == B(-oo, oo)
+    assert B(-3, -2)/B(-4, 0) == B(S.Half, oo)
+
+    # these two tests can have a better answer
+    # after Union of B is improved
+    assert B(-3, -2)/B(-2, 1) == B(-oo, oo)
+    assert B(2, 3)/B(-2, 2) == B(-oo, oo)
+
+    assert B(-3, -2)/B(0, 4) == B(-oo, Rational(-1, 2))
+    assert B(2, 4)/B(-3, 0) == B(-oo, Rational(-2, 3))
+    assert B(2, 4)/B(0, 3) == B(Rational(2, 3), oo)
+
+    assert B(0, 1)/B(0, 1) == B(0, oo)
+    assert B(-1, 0)/B(0, 1) == B(-oo, 0)
+    assert B(-1, 2)/B(-2, 2) == B(-oo, oo)
+
+    assert 1/B(-1, 2) == B(-oo, oo)
+    assert 1/B(0, 2) == B(S.Half, oo)
+    assert (-1)/B(0, 2) == B(-oo, Rational(-1, 2))
+    assert 1/B(-oo, 0) == B(-oo, 0)
+    assert 1/B(-1, 0) == B(-oo, -1)
+    assert (-2)/B(-oo, 0) == B(0, oo)
+    assert 1/B(-oo, -1) == B(-1, 0)
+
+    assert B(1, 2)/a == Mul(B(1, 2), 1/a, evaluate=False)
+
+    assert B(1, 2)/0 == B(1, 2)*zoo
+    assert B(1, oo)/oo == B(0, oo)
+    assert B(1, oo)/(-oo) == B(-oo, 0)
+    assert B(-oo, -1)/oo == B(-oo, 0)
+    assert B(-oo, -1)/(-oo) == B(0, oo)
+    assert B(-oo, oo)/oo == B(-oo, oo)
+    assert B(-oo, oo)/(-oo) == B(-oo, oo)
+    assert B(-1, oo)/oo == B(0, oo)
+    assert B(-1, oo)/(-oo) == B(-oo, 0)
+    assert B(-oo, 1)/oo == B(-oo, 0)
+    assert B(-oo, 1)/(-oo) == B(0, oo)
+
+
+def test_issue_18795():
+    r = Symbol('r', real=True)
+    a = B(-1,1)
+    c = B(7, oo)
+    b = B(-oo, oo)
+    assert c - tan(r) == B(7-tan(r), oo)
+    assert b + tan(r) == B(-oo, oo)
+    assert (a + r)/a == B(-oo, oo)*B(r - 1, r + 1)
+    assert (b + a)/a == B(-oo, oo)
+
+
+def test_AccumBounds_func():
+    assert (x**2 + 2*x + 1).subs(x, B(-1, 1)) == B(-1, 4)
+    assert exp(B(0, 1)) == B(1, E)
+    assert exp(B(-oo, oo)) == B(0, oo)
+    assert log(B(3, 6)) == B(log(3), log(6))
+
+
+@XFAIL
+def test_AccumBounds_powf():
+    nn = Symbol('nn', nonnegative=True)
+    assert B(1 + nn, 2 + nn)**B(1, 2) == B(1 + nn, (2 + nn)**2)
+    i = Symbol('i', integer=True, negative=True)
+    assert B(1, 2)**i == B(2**i, 1)
+
+
+def test_AccumBounds_pow():
+    assert B(0, 2)**2 == B(0, 4)
+    assert B(-1, 1)**2 == B(0, 1)
+    assert B(1, 2)**2 == B(1, 4)
+    assert B(-1, 2)**3 == B(-1, 8)
+    assert B(-1, 1)**0 == 1
+
+    assert B(1, 2)**Rational(5, 2) == B(1, 4*sqrt(2))
+    assert B(0, 2)**S.Half == B(0, sqrt(2))
+
+    neg = Symbol('neg', negative=True)
+    assert unchanged(Pow, B(neg, 1), S.Half)
+    nn = Symbol('nn', nonnegative=True)
+    assert B(nn, nn + 1)**S.Half == B(sqrt(nn), sqrt(nn + 1))
+    assert B(nn, nn + 1)**nn == B(nn**nn, (nn + 1)**nn)
+    assert unchanged(Pow, B(nn, nn + 1), x)
+    i = Symbol('i', integer=True)
+    assert B(1, 2)**i == B(Min(1, 2**i), Max(1, 2**i))
+    i = Symbol('i', integer=True, nonnegative=True)
+    assert B(1, 2)**i == B(1, 2**i)
+    assert B(0, 1)**i == B(0**i, 1)
+
+    assert B(1, 5)**(-2) == B(Rational(1, 25), 1)
+    assert B(-1, 3)**(-2) == B(0, oo)
+    assert B(0, 2)**(-3) == B(Rational(1, 8), oo)
+    assert B(-2, 0)**(-3) == B(-oo, -Rational(1, 8))
+    assert B(0, 2)**(-2) == B(Rational(1, 4), oo)
+    assert B(-1, 2)**(-3) == B(-oo, oo)
+    assert B(-3, -2)**(-3) == B(Rational(-1, 8), Rational(-1, 27))
+    assert B(-3, -2)**(-2) == B(Rational(1, 9), Rational(1, 4))
+    assert B(0, oo)**S.Half == B(0, oo)
+    assert B(-oo, 0)**(-2) == B(0, oo)
+    assert B(-2, 0)**(-2) == B(Rational(1, 4), oo)
+
+    assert B(Rational(1, 3), S.Half)**oo is S.Zero
+    assert B(0, S.Half)**oo is S.Zero
+    assert B(S.Half, 1)**oo == B(0, oo)
+    assert B(0, 1)**oo == B(0, oo)
+    assert B(2, 3)**oo is oo
+    assert B(1, 2)**oo == B(0, oo)
+    assert B(S.Half, 3)**oo == B(0, oo)
+    assert B(Rational(-1, 3), Rational(-1, 4))**oo is S.Zero
+    assert B(-1, Rational(-1, 2))**oo is S.NaN
+    assert B(-3, -2)**oo is zoo
+    assert B(-2, -1)**oo is S.NaN
+    assert B(-2, Rational(-1, 2))**oo is S.NaN
+    assert B(Rational(-1, 2), S.Half)**oo is S.Zero
+    assert B(Rational(-1, 2), 1)**oo == B(0, oo)
+    assert B(Rational(-2, 3), 2)**oo == B(0, oo)
+    assert B(-1, 1)**oo == B(-oo, oo)
+    assert B(-1, S.Half)**oo == B(-oo, oo)
+    assert B(-1, 2)**oo == B(-oo, oo)
+    assert B(-2, S.Half)**oo == B(-oo, oo)
+
+    assert B(1, 2)**x == Pow(B(1, 2), x, evaluate=False)
+
+    assert B(2, 3)**(-oo) is S.Zero
+    assert B(0, 2)**(-oo) == B(0, oo)
+    assert B(-1, 2)**(-oo) == B(-oo, oo)
+
+    assert (tan(x)**sin(2*x)).subs(x, B(0, pi/2)) == \
+        Pow(B(-oo, oo), B(0, 1))
+
+
+def test_AccumBounds_exponent():
+    # base is 0
+    z = 0**B(a, a + S.Half)
+    assert z.subs(a, 0) == B(0, 1)
+    assert z.subs(a, 1) == 0
+    p = z.subs(a, -1)
+    assert p.is_Pow and p.args == (0, B(-1, -S.Half))
+    # base > 0
+    #   when base is 1 the type of bounds does not matter
+    assert 1**B(a, a + 1) == 1
+    #  otherwise we need to know if 0 is in the bounds
+    assert S.Half**B(-2, 2) == B(S(1)/4, 4)
+    assert 2**B(-2, 2) == B(S(1)/4, 4)
+
+    # +eps may introduce +oo
+    # if there is a negative integer exponent
+    assert B(0, 1)**B(S(1)/2, 1) == B(0, 1)
+    assert B(0, 1)**B(0, 1) == B(0, 1)
+
+    # positive bases have positive bounds
+    assert B(2, 3)**B(-3, -2) == B(S(1)/27, S(1)/4)
+    assert B(2, 3)**B(-3, 2) == B(S(1)/27, 9)
+
+    # bounds generating imaginary parts unevaluated
+    assert unchanged(Pow, B(-1, 1), B(1, 2))
+    assert B(0, S(1)/2)**B(1, oo) == B(0, S(1)/2)
+    assert B(0, 1)**B(1, oo) == B(0, oo)
+    assert B(0, 2)**B(1, oo) == B(0, oo)
+    assert B(0, oo)**B(1, oo) == B(0, oo)
+    assert B(S(1)/2, 1)**B(1, oo) == B(0, oo)
+    assert B(S(1)/2, 1)**B(-oo, -1) == B(0, oo)
+    assert B(S(1)/2, 1)**B(-oo, oo) == B(0, oo)
+    assert B(S(1)/2, 2)**B(1, oo) == B(0, oo)
+    assert B(S(1)/2, 2)**B(-oo, -1) == B(0, oo)
+    assert B(S(1)/2, 2)**B(-oo, oo) == B(0, oo)
+    assert B(S(1)/2, oo)**B(1, oo) == B(0, oo)
+    assert B(S(1)/2, oo)**B(-oo, -1) == B(0, oo)
+    assert B(S(1)/2, oo)**B(-oo, oo) == B(0, oo)
+    assert B(1, 2)**B(1, oo) == B(0, oo)
+    assert B(1, 2)**B(-oo, -1) == B(0, oo)
+    assert B(1, 2)**B(-oo, oo) == B(0, oo)
+    assert B(1, oo)**B(1, oo) == B(0, oo)
+    assert B(1, oo)**B(-oo, -1) == B(0, oo)
+    assert B(1, oo)**B(-oo, oo) == B(0, oo)
+    assert B(2, oo)**B(1, oo) == B(2, oo)
+    assert B(2, oo)**B(-oo, -1) == B(0, S(1)/2)
+    assert B(2, oo)**B(-oo, oo) == B(0, oo)
+
+
+def test_comparison_AccumBounds():
+    assert (B(1, 3) < 4) == S.true
+    assert (B(1, 3) < -1) == S.false
+    assert (B(1, 3) < 2).rel_op == '<'
+    assert (B(1, 3) <= 2).rel_op == '<='
+
+    assert (B(1, 3) > 4) == S.false
+    assert (B(1, 3) > -1) == S.true
+    assert (B(1, 3) > 2).rel_op == '>'
+    assert (B(1, 3) >= 2).rel_op == '>='
+
+    assert (B(1, 3) < B(4, 6)) == S.true
+    assert (B(1, 3) < B(2, 4)).rel_op == '<'
+    assert (B(1, 3) < B(-2, 0)) == S.false
+
+    assert (B(1, 3) <= B(4, 6)) == S.true
+    assert (B(1, 3) <= B(-2, 0)) == S.false
+
+    assert (B(1, 3) > B(4, 6)) == S.false
+    assert (B(1, 3) > B(-2, 0)) == S.true
+
+    assert (B(1, 3) >= B(4, 6)) == S.false
+    assert (B(1, 3) >= B(-2, 0)) == S.true
+
+    # issue 13499
+    assert (cos(x) > 0).subs(x, oo) == (B(-1, 1) > 0)
+
+    c = Symbol('c')
+    raises(TypeError, lambda: (B(0, 1) < c))
+    raises(TypeError, lambda: (B(0, 1) <= c))
+    raises(TypeError, lambda: (B(0, 1) > c))
+    raises(TypeError, lambda: (B(0, 1) >= c))
+
+
+def test_contains_AccumBounds():
+    assert (1 in B(1, 2)) == S.true
+    raises(TypeError, lambda: a in B(1, 2))
+    assert 0 in B(-1, 0)
+    raises(TypeError, lambda:
+        (cos(1)**2 + sin(1)**2 - 1) in B(-1, 0))
+    assert (-oo in B(1, oo)) == S.true
+    assert (oo in B(-oo, 0)) == S.true
+
+    # issue 13159
+    assert Mul(0, B(-1, 1)) == Mul(B(-1, 1), 0) == 0
+    import itertools
+    for perm in itertools.permutations([0, B(-1, 1), x]):
+        assert Mul(*perm) == 0
+
+
+def test_intersection_AccumBounds():
+    assert B(0, 3).intersection(B(1, 2)) == B(1, 2)
+    assert B(0, 3).intersection(B(1, 4)) == B(1, 3)
+    assert B(0, 3).intersection(B(-1, 2)) == B(0, 2)
+    assert B(0, 3).intersection(B(-1, 4)) == B(0, 3)
+    assert B(0, 1).intersection(B(2, 3)) == S.EmptySet
+    raises(TypeError, lambda: B(0, 3).intersection(1))
+
+
+def test_union_AccumBounds():
+    assert B(0, 3).union(B(1, 2)) == B(0, 3)
+    assert B(0, 3).union(B(1, 4)) == B(0, 4)
+    assert B(0, 3).union(B(-1, 2)) == B(-1, 3)
+    assert B(0, 3).union(B(-1, 4)) == B(-1, 4)
+    raises(TypeError, lambda: B(0, 3).union(1))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/tests/test_euler.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/tests/test_euler.py
new file mode 100644
index 0000000000000000000000000000000000000000..56371c8c787d9459d1390e18c306fddde94d2745
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/tests/test_euler.py
@@ -0,0 +1,74 @@
+from sympy.core.function import (Derivative as D, Function)
+from sympy.core.relational import Eq
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.functions.elementary.trigonometric import (cos, sin)
+from sympy.testing.pytest import raises
+from sympy.calculus.euler import euler_equations as euler
+
+
+def test_euler_interface():
+    x = Function('x')
+    y = Symbol('y')
+    t = Symbol('t')
+    raises(TypeError, lambda: euler())
+    raises(TypeError, lambda: euler(D(x(t), t)*y(t), [x(t), y]))
+    raises(ValueError, lambda: euler(D(x(t), t)*x(y), [x(t), x(y)]))
+    raises(TypeError, lambda: euler(D(x(t), t)**2, x(0)))
+    raises(TypeError, lambda: euler(D(x(t), t)*y(t), [t]))
+    assert euler(D(x(t), t)**2/2, {x(t)}) == [Eq(-D(x(t), t, t), 0)]
+    assert euler(D(x(t), t)**2/2, x(t), {t}) == [Eq(-D(x(t), t, t), 0)]
+
+
+def test_euler_pendulum():
+    x = Function('x')
+    t = Symbol('t')
+    L = D(x(t), t)**2/2 + cos(x(t))
+    assert euler(L, x(t), t) == [Eq(-sin(x(t)) - D(x(t), t, t), 0)]
+
+
+def test_euler_henonheiles():
+    x = Function('x')
+    y = Function('y')
+    t = Symbol('t')
+    L = sum(D(z(t), t)**2/2 - z(t)**2/2 for z in [x, y])
+    L += -x(t)**2*y(t) + y(t)**3/3
+    assert euler(L, [x(t), y(t)], t) == [Eq(-2*x(t)*y(t) - x(t) -
+                                            D(x(t), t, t), 0),
+                                         Eq(-x(t)**2 + y(t)**2 -
+                                            y(t) - D(y(t), t, t), 0)]
+
+
+def test_euler_sineg():
+    psi = Function('psi')
+    t = Symbol('t')
+    x = Symbol('x')
+    L = D(psi(t, x), t)**2/2 - D(psi(t, x), x)**2/2 + cos(psi(t, x))
+    assert euler(L, psi(t, x), [t, x]) == [Eq(-sin(psi(t, x)) -
+                                              D(psi(t, x), t, t) +
+                                              D(psi(t, x), x, x), 0)]
+
+
+def test_euler_high_order():
+    # an example from hep-th/0309038
+    m = Symbol('m')
+    k = Symbol('k')
+    x = Function('x')
+    y = Function('y')
+    t = Symbol('t')
+    L = (m*D(x(t), t)**2/2 + m*D(y(t), t)**2/2 -
+         k*D(x(t), t)*D(y(t), t, t) + k*D(y(t), t)*D(x(t), t, t))
+    assert euler(L, [x(t), y(t)]) == [Eq(2*k*D(y(t), t, t, t) -
+                                         m*D(x(t), t, t), 0),
+                                      Eq(-2*k*D(x(t), t, t, t) -
+                                         m*D(y(t), t, t), 0)]
+
+    w = Symbol('w')
+    L = D(x(t, w), t, w)**2/2
+    assert euler(L) == [Eq(D(x(t, w), t, t, w, w), 0)]
+
+def test_issue_18653():
+    x, y, z = symbols("x y z")
+    f, g, h = symbols("f g h", cls=Function, args=(x, y))
+    f, g, h = f(), g(), h()
+    expr2 = f.diff(x)*h.diff(z)
+    assert euler(expr2, (f,), (x, y)) == []
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/tests/test_finite_diff.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/tests/test_finite_diff.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9ecfbdd61b15f516c54bd6d716ba1f264ee2ca0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/tests/test_finite_diff.py
@@ -0,0 +1,164 @@
+from itertools import product
+
+from sympy.core.function import (Function, diff)
+from sympy.core.numbers import Rational
+from sympy.core.singleton import S
+from sympy.core.symbol import symbols
+from sympy.functions.elementary.exponential import exp
+from sympy.calculus.finite_diff import (
+    apply_finite_diff, differentiate_finite, finite_diff_weights,
+    _as_finite_diff
+)
+from sympy.testing.pytest import raises, warns_deprecated_sympy
+
+
+def test_apply_finite_diff():
+    x, h = symbols('x h')
+    f = Function('f')
+    assert (apply_finite_diff(1, [x-h, x+h], [f(x-h), f(x+h)], x) -
+            (f(x+h)-f(x-h))/(2*h)).simplify() == 0
+
+    assert (apply_finite_diff(1, [5, 6, 7], [f(5), f(6), f(7)], 5) -
+            (Rational(-3, 2)*f(5) + 2*f(6) - S.Half*f(7))).simplify() == 0
+    raises(ValueError, lambda: apply_finite_diff(1, [x, h], [f(x)]))
+
+
+def test_finite_diff_weights():
+
+    d = finite_diff_weights(1, [5, 6, 7], 5)
+    assert d[1][2] == [Rational(-3, 2), 2, Rational(-1, 2)]
+
+    # Table 1, p. 702 in doi:10.1090/S0025-5718-1988-0935077-0
+    # --------------------------------------------------------
+    xl = [0, 1, -1, 2, -2, 3, -3, 4, -4]
+
+    # d holds all coefficients
+    d = finite_diff_weights(4, xl, S.Zero)
+
+    # Zeroeth derivative
+    for i in range(5):
+        assert d[0][i] == [S.One] + [S.Zero]*8
+
+    # First derivative
+    assert d[1][0] == [S.Zero]*9
+    assert d[1][2] == [S.Zero, S.Half, Rational(-1, 2)] + [S.Zero]*6
+    assert d[1][4] == [S.Zero, Rational(2, 3), Rational(-2, 3), Rational(-1, 12), Rational(1, 12)] + [S.Zero]*4
+    assert d[1][6] == [S.Zero, Rational(3, 4), Rational(-3, 4), Rational(-3, 20), Rational(3, 20),
+                       Rational(1, 60), Rational(-1, 60)] + [S.Zero]*2
+    assert d[1][8] == [S.Zero, Rational(4, 5), Rational(-4, 5), Rational(-1, 5), Rational(1, 5),
+                       Rational(4, 105), Rational(-4, 105), Rational(-1, 280), Rational(1, 280)]
+
+    # Second derivative
+    for i in range(2):
+        assert d[2][i] == [S.Zero]*9
+    assert d[2][2] == [-S(2), S.One, S.One] + [S.Zero]*6
+    assert d[2][4] == [Rational(-5, 2), Rational(4, 3), Rational(4, 3), Rational(-1, 12), Rational(-1, 12)] + [S.Zero]*4
+    assert d[2][6] == [Rational(-49, 18), Rational(3, 2), Rational(3, 2), Rational(-3, 20), Rational(-3, 20),
+                       Rational(1, 90), Rational(1, 90)] + [S.Zero]*2
+    assert d[2][8] == [Rational(-205, 72), Rational(8, 5), Rational(8, 5), Rational(-1, 5), Rational(-1, 5),
+                       Rational(8, 315), Rational(8, 315), Rational(-1, 560), Rational(-1, 560)]
+
+    # Third derivative
+    for i in range(3):
+        assert d[3][i] == [S.Zero]*9
+    assert d[3][4] == [S.Zero, -S.One, S.One, S.Half, Rational(-1, 2)] + [S.Zero]*4
+    assert d[3][6] == [S.Zero, Rational(-13, 8), Rational(13, 8), S.One, -S.One,
+                       Rational(-1, 8), Rational(1, 8)] + [S.Zero]*2
+    assert d[3][8] == [S.Zero, Rational(-61, 30), Rational(61, 30), Rational(169, 120), Rational(-169, 120),
+                       Rational(-3, 10), Rational(3, 10), Rational(7, 240), Rational(-7, 240)]
+
+    # Fourth derivative
+    for i in range(4):
+        assert d[4][i] == [S.Zero]*9
+    assert d[4][4] == [S(6), -S(4), -S(4), S.One, S.One] + [S.Zero]*4
+    assert d[4][6] == [Rational(28, 3), Rational(-13, 2), Rational(-13, 2), S(2), S(2),
+                       Rational(-1, 6), Rational(-1, 6)] + [S.Zero]*2
+    assert d[4][8] == [Rational(91, 8), Rational(-122, 15), Rational(-122, 15), Rational(169, 60), Rational(169, 60),
+                       Rational(-2, 5), Rational(-2, 5), Rational(7, 240), Rational(7, 240)]
+
+    # Table 2, p. 703 in doi:10.1090/S0025-5718-1988-0935077-0
+    # --------------------------------------------------------
+    xl = [[j/S(2) for j in list(range(-i*2+1, 0, 2))+list(range(1, i*2+1, 2))]
+          for i in range(1, 5)]
+
+    # d holds all coefficients
+    d = [finite_diff_weights({0: 1, 1: 2, 2: 4, 3: 4}[i], xl[i], 0) for
+         i in range(4)]
+
+    # Zeroth derivative
+    assert d[0][0][1] == [S.Half, S.Half]
+    assert d[1][0][3] == [Rational(-1, 16), Rational(9, 16), Rational(9, 16), Rational(-1, 16)]
+    assert d[2][0][5] == [Rational(3, 256), Rational(-25, 256), Rational(75, 128), Rational(75, 128),
+                          Rational(-25, 256), Rational(3, 256)]
+    assert d[3][0][7] == [Rational(-5, 2048), Rational(49, 2048), Rational(-245, 2048), Rational(1225, 2048),
+                          Rational(1225, 2048), Rational(-245, 2048), Rational(49, 2048), Rational(-5, 2048)]
+
+    # First derivative
+    assert d[0][1][1] == [-S.One, S.One]
+    assert d[1][1][3] == [Rational(1, 24), Rational(-9, 8), Rational(9, 8), Rational(-1, 24)]
+    assert d[2][1][5] == [Rational(-3, 640), Rational(25, 384), Rational(-75, 64),
+                          Rational(75, 64), Rational(-25, 384), Rational(3, 640)]
+    assert d[3][1][7] == [Rational(5, 7168), Rational(-49, 5120),
+                          Rational(245, 3072), Rational(-1225, 1024),
+                          Rational(1225, 1024), Rational(-245, 3072),
+                          Rational(49, 5120), Rational(-5, 7168)]
+
+    # Reasonably the rest of the table is also correct... (testing of that
+    # deemed excessive at the moment)
+    raises(ValueError, lambda: finite_diff_weights(-1, [1, 2]))
+    raises(ValueError, lambda: finite_diff_weights(1.2, [1, 2]))
+    x = symbols('x')
+    raises(ValueError, lambda: finite_diff_weights(x, [1, 2]))
+
+
+def test_as_finite_diff():
+    x = symbols('x')
+    f = Function('f')
+    dx = Function('dx')
+
+    _as_finite_diff(f(x).diff(x), [x-2, x-1, x, x+1, x+2])
+
+    # Use of undefined functions in ``points``
+    df_true = -f(x+dx(x)/2-dx(x+dx(x)/2)/2) / dx(x+dx(x)/2) \
+              + f(x+dx(x)/2+dx(x+dx(x)/2)/2) / dx(x+dx(x)/2)
+    df_test = diff(f(x), x).as_finite_difference(points=dx(x), x0=x+dx(x)/2)
+    assert (df_test - df_true).simplify() == 0
+
+
+def test_differentiate_finite():
+    x, y, h = symbols('x y h')
+    f = Function('f')
+    with warns_deprecated_sympy():
+        res0 = differentiate_finite(f(x, y) + exp(42), x, y, evaluate=True)
+    xm, xp, ym, yp = [v + sign*S.Half for v, sign in product([x, y], [-1, 1])]
+    ref0 = f(xm, ym) + f(xp, yp) - f(xm, yp) - f(xp, ym)
+    assert (res0 - ref0).simplify() == 0
+
+    g = Function('g')
+    with warns_deprecated_sympy():
+        res1 = differentiate_finite(f(x)*g(x) + 42, x, evaluate=True)
+    ref1 = (-f(x - S.Half) + f(x + S.Half))*g(x) + \
+           (-g(x - S.Half) + g(x + S.Half))*f(x)
+    assert (res1 - ref1).simplify() == 0
+
+    res2 = differentiate_finite(f(x) + x**3 + 42, x, points=[x-1, x+1])
+    ref2 = (f(x + 1) + (x + 1)**3 - f(x - 1) - (x - 1)**3)/2
+    assert (res2 - ref2).simplify() == 0
+    raises(TypeError, lambda: differentiate_finite(f(x)*g(x), x,
+                                                   pints=[x-1, x+1]))
+
+    res3 = differentiate_finite(f(x)*g(x).diff(x), x)
+    ref3 = (-g(x) + g(x + 1))*f(x + S.Half) - (g(x) - g(x - 1))*f(x - S.Half)
+    assert res3 == ref3
+
+    res4 = differentiate_finite(f(x)*g(x).diff(x).diff(x), x)
+    ref4 = -((g(x - Rational(3, 2)) - 2*g(x - S.Half) + g(x + S.Half))*f(x - S.Half)) \
+           + (g(x - S.Half) - 2*g(x + S.Half) + g(x + Rational(3, 2)))*f(x + S.Half)
+    assert res4 == ref4
+
+    res5_expr = f(x).diff(x)*g(x).diff(x)
+    res5 = differentiate_finite(res5_expr, points=[x-h, x, x+h])
+    ref5 = (-2*f(x)/h + f(-h + x)/(2*h) + 3*f(h + x)/(2*h))*(-2*g(x)/h + g(-h + x)/(2*h) \
+           + 3*g(h + x)/(2*h))/(2*h) - (2*f(x)/h - 3*f(-h + x)/(2*h) - \
+           f(h + x)/(2*h))*(2*g(x)/h - 3*g(-h + x)/(2*h) - g(h + x)/(2*h))/(2*h)
+    assert res5 == ref5
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/tests/test_singularities.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/tests/test_singularities.py
new file mode 100644
index 0000000000000000000000000000000000000000..19a042332326658021ce12a38f4e058f55903869
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/tests/test_singularities.py
@@ -0,0 +1,122 @@
+from sympy.core.numbers import (I, Rational, pi, oo)
+from sympy.core.singleton import S
+from sympy.core.symbol import Symbol, Dummy
+from sympy.core.function import Lambda
+from sympy.functions.elementary.exponential import (exp, log)
+from sympy.functions.elementary.trigonometric import sec, csc
+from sympy.functions.elementary.hyperbolic import (coth, sech,
+                                                   atanh, asech, acoth, acsch)
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.calculus.singularities import (
+    singularities,
+    is_increasing,
+    is_strictly_increasing,
+    is_decreasing,
+    is_strictly_decreasing,
+    is_monotonic
+)
+from sympy.sets import Interval, FiniteSet, Union, ImageSet
+from sympy.testing.pytest import raises
+from sympy.abc import x, y
+
+
+def test_singularities():
+    x = Symbol('x')
+    assert singularities(x**2, x) == S.EmptySet
+    assert singularities(x/(x**2 + 3*x + 2), x) == FiniteSet(-2, -1)
+    assert singularities(1/(x**2 + 1), x) == FiniteSet(I, -I)
+    assert singularities(x/(x**3 + 1), x) == \
+        FiniteSet(-1, (1 - sqrt(3) * I) / 2, (1 + sqrt(3) * I) / 2)
+    assert singularities(1/(y**2 + 2*I*y + 1), y) == \
+        FiniteSet(-I + sqrt(2)*I, -I - sqrt(2)*I)
+    _n = Dummy('n')
+    assert singularities(sech(x), x).dummy_eq(Union(
+        ImageSet(Lambda(_n, 2*_n*I*pi + I*pi/2), S.Integers),
+        ImageSet(Lambda(_n, 2*_n*I*pi + 3*I*pi/2), S.Integers)))
+    assert singularities(coth(x), x).dummy_eq(Union(
+        ImageSet(Lambda(_n, 2*_n*I*pi + I*pi), S.Integers),
+        ImageSet(Lambda(_n, 2*_n*I*pi), S.Integers)))
+    assert singularities(atanh(x), x) == FiniteSet(-1, 1)
+    assert singularities(acoth(x), x) == FiniteSet(-1, 1)
+    assert singularities(asech(x), x) == FiniteSet(0)
+    assert singularities(acsch(x), x) == FiniteSet(0)
+
+    x = Symbol('x', real=True)
+    assert singularities(1/(x**2 + 1), x) == S.EmptySet
+    assert singularities(exp(1/x), x, S.Reals) == FiniteSet(0)
+    assert singularities(exp(1/x), x, Interval(1, 2)) == S.EmptySet
+    assert singularities(log((x - 2)**2), x, Interval(1, 3)) == FiniteSet(2)
+    raises(NotImplementedError, lambda: singularities(x**-oo, x))
+    assert singularities(sec(x), x, Interval(0, 3*pi)) == FiniteSet(
+        pi/2, 3*pi/2, 5*pi/2)
+    assert singularities(csc(x), x, Interval(0, 3*pi)) == FiniteSet(
+        0, pi, 2*pi, 3*pi)
+
+
+def test_is_increasing():
+    """Test whether is_increasing returns correct value."""
+    a = Symbol('a', negative=True)
+
+    assert is_increasing(x**3 - 3*x**2 + 4*x, S.Reals)
+    assert is_increasing(-x**2, Interval(-oo, 0))
+    assert not is_increasing(-x**2, Interval(0, oo))
+    assert not is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3))
+    assert is_increasing(x**2 + y, Interval(1, oo), x)
+    assert is_increasing(-x**2*a, Interval(1, oo), x)
+    assert is_increasing(1)
+
+    assert is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3)) is False
+
+
+def test_is_strictly_increasing():
+    """Test whether is_strictly_increasing returns correct value."""
+    assert is_strictly_increasing(
+        4*x**3 - 6*x**2 - 72*x + 30, Interval.Ropen(-oo, -2))
+    assert is_strictly_increasing(
+        4*x**3 - 6*x**2 - 72*x + 30, Interval.Lopen(3, oo))
+    assert not is_strictly_increasing(
+        4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3))
+    assert not is_strictly_increasing(-x**2, Interval(0, oo))
+    assert not is_strictly_decreasing(1)
+
+    assert is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3)) is False
+
+
+def test_is_decreasing():
+    """Test whether is_decreasing returns correct value."""
+    b = Symbol('b', positive=True)
+
+    assert is_decreasing(1/(x**2 - 3*x), Interval.open(Rational(3,2), 3))
+    assert is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
+    assert is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
+    assert not is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, Rational(3, 2)))
+    assert not is_decreasing(-x**2, Interval(-oo, 0))
+    assert not is_decreasing(-x**2*b, Interval(-oo, 0), x)
+
+
+def test_is_strictly_decreasing():
+    """Test whether is_strictly_decreasing returns correct value."""
+    assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
+    assert not is_strictly_decreasing(
+        1/(x**2 - 3*x), Interval.Ropen(-oo, Rational(3, 2)))
+    assert not is_strictly_decreasing(-x**2, Interval(-oo, 0))
+    assert not is_strictly_decreasing(1)
+    assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.open(Rational(3,2), 3))
+    assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
+
+
+def test_is_monotonic():
+    """Test whether is_monotonic returns correct value."""
+    assert is_monotonic(1/(x**2 - 3*x), Interval.open(Rational(3,2), 3))
+    assert is_monotonic(1/(x**2 - 3*x), Interval.open(1.5, 3))
+    assert is_monotonic(1/(x**2 - 3*x), Interval.Lopen(3, oo))
+    assert is_monotonic(x**3 - 3*x**2 + 4*x, S.Reals)
+    assert not is_monotonic(-x**2, S.Reals)
+    assert is_monotonic(x**2 + y + 1, Interval(1, 2), x)
+    raises(NotImplementedError, lambda: is_monotonic(x**2 + y + 1))
+
+
+def test_issue_23401():
+    x = Symbol('x')
+    expr = (x + 1)/(-1.0e-3*x**2 + 0.1*x + 0.1)
+    assert is_increasing(expr, Interval(1,2), x)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/tests/test_util.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/tests/test_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..c18b7a79fd54fdb2638cc746d43ab26753fc72a9
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/tests/test_util.py
@@ -0,0 +1,392 @@
+from sympy.core.function import Lambda
+from sympy.core.numbers import (E, I, Rational, oo, pi)
+from sympy.core.relational import Eq
+from sympy.core.singleton import S
+from sympy.core.symbol import (Dummy, Symbol)
+from sympy.functions.elementary.complexes import (Abs, re)
+from sympy.functions.elementary.exponential import (exp, log)
+from sympy.functions.elementary.integers import frac
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.functions.elementary.trigonometric import (
+    cos, cot, csc, sec, sin, tan, asin, acos, atan, acot, asec, acsc)
+from sympy.functions.elementary.hyperbolic import (sinh, cosh, tanh, coth,
+    sech, csch, asinh, acosh, atanh, acoth, asech, acsch)
+from sympy.functions.special.gamma_functions import gamma
+from sympy.functions.special.error_functions import expint
+from sympy.matrices.expressions.matexpr import MatrixSymbol
+from sympy.simplify.simplify import simplify
+from sympy.calculus.util import (function_range, continuous_domain, not_empty_in,
+                                 periodicity, lcim, is_convex,
+                                 stationary_points, minimum, maximum)
+from sympy.sets.sets import (Interval, FiniteSet, Complement, Union)
+from sympy.sets.fancysets import ImageSet
+from sympy.sets.conditionset import ConditionSet
+from sympy.testing.pytest import XFAIL, raises, _both_exp_pow, slow
+from sympy.abc import x, y
+
+a = Symbol('a', real=True)
+
+def test_function_range():
+    assert function_range(sin(x), x, Interval(-pi/2, pi/2)
+        ) == Interval(-1, 1)
+    assert function_range(sin(x), x, Interval(0, pi)
+        ) == Interval(0, 1)
+    assert function_range(tan(x), x, Interval(0, pi)
+        ) == Interval(-oo, oo)
+    assert function_range(tan(x), x, Interval(pi/2, pi)
+        ) == Interval(-oo, 0)
+    assert function_range((x + 3)/(x - 2), x, Interval(-5, 5)
+        ) == Union(Interval(-oo, Rational(2, 7)), Interval(Rational(8, 3), oo))
+    assert function_range(1/(x**2), x, Interval(-1, 1)
+        ) == Interval(1, oo)
+    assert function_range(exp(x), x, Interval(-1, 1)
+        ) == Interval(exp(-1), exp(1))
+    assert function_range(log(x) - x, x, S.Reals
+        ) == Interval(-oo, -1)
+    assert function_range(sqrt(3*x - 1), x, Interval(0, 2)
+        ) == Interval(0, sqrt(5))
+    assert function_range(x*(x - 1) - (x**2 - x), x, S.Reals
+        ) == FiniteSet(0)
+    assert function_range(x*(x - 1) - (x**2 - x) + y, x, S.Reals
+        ) == FiniteSet(y)
+    assert function_range(sin(x), x, Union(Interval(-5, -3), FiniteSet(4))
+        ) == Union(Interval(-sin(3), 1), FiniteSet(sin(4)))
+    assert function_range(cos(x), x, Interval(-oo, -4)
+        ) == Interval(-1, 1)
+    assert function_range(cos(x), x, S.EmptySet) == S.EmptySet
+    assert function_range(x/sqrt(x**2+1), x, S.Reals) == Interval.open(-1,1)
+    raises(NotImplementedError, lambda : function_range(
+        exp(x)*(sin(x) - cos(x))/2 - x, x, S.Reals))
+    raises(NotImplementedError, lambda : function_range(
+        sin(x) + x, x, S.Reals)) # issue 13273
+    raises(NotImplementedError, lambda : function_range(
+        log(x), x, S.Integers))
+    raises(NotImplementedError, lambda : function_range(
+        sin(x)/2, x, S.Naturals))
+
+
+@slow
+def test_function_range1():
+    assert function_range(tan(x)**2 + tan(3*x)**2 + 1, x, S.Reals) == Interval(1,oo)
+
+
+def test_continuous_domain():
+    assert continuous_domain(sin(x), x, Interval(0, 2*pi)) == Interval(0, 2*pi)
+    assert continuous_domain(tan(x), x, Interval(0, 2*pi)) == \
+        Union(Interval(0, pi/2, False, True), Interval(pi/2, pi*Rational(3, 2), True, True),
+              Interval(pi*Rational(3, 2), 2*pi, True, False))
+    assert continuous_domain(cot(x), x, Interval(0, 2*pi)) == Union(
+        Interval.open(0, pi), Interval.open(pi, 2*pi))
+    assert continuous_domain((x - 1)/((x - 1)**2), x, S.Reals) == \
+        Union(Interval(-oo, 1, True, True), Interval(1, oo, True, True))
+    assert continuous_domain(log(x) + log(4*x - 1), x, S.Reals) == \
+        Interval(Rational(1, 4), oo, True, True)
+    assert continuous_domain(1/sqrt(x - 3), x, S.Reals) == Interval(3, oo, True, True)
+    assert continuous_domain(1/x - 2, x, S.Reals) == \
+        Union(Interval.open(-oo, 0), Interval.open(0, oo))
+    assert continuous_domain(1/(x**2 - 4) + 2, x, S.Reals) == \
+        Union(Interval.open(-oo, -2), Interval.open(-2, 2), Interval.open(2, oo))
+    assert continuous_domain((x+1)**pi, x, S.Reals) == Interval(-1, oo)
+    assert continuous_domain((x+1)**(pi/2), x, S.Reals) == Interval(-1, oo)
+    assert continuous_domain(x**x, x, S.Reals) == Interval(0, oo)
+    assert continuous_domain((x+1)**log(x**2), x, S.Reals) == Union(
+        Interval.Ropen(-1, 0), Interval.open(0, oo))
+    domain = continuous_domain(log(tan(x)**2 + 1), x, S.Reals)
+    assert not domain.contains(3*pi/2)
+    assert domain.contains(5)
+    d = Symbol('d', even=True, zero=False)
+    assert continuous_domain(x**(1/d), x, S.Reals) == Interval(0, oo)
+    n = Dummy('n')
+    assert continuous_domain(1/sin(x), x, S.Reals).dummy_eq(Complement(
+        S.Reals, Union(ImageSet(Lambda(n, 2*n*pi + pi), S.Integers),
+                       ImageSet(Lambda(n, 2*n*pi), S.Integers))))
+    assert continuous_domain(sin(x) + cos(x), x, S.Reals) == S.Reals
+    assert continuous_domain(asin(x), x, S.Reals) == Interval(-1, 1) # issue #21786
+    assert continuous_domain(1/acos(log(x)), x, S.Reals) == Interval.Ropen(exp(-1), E)
+    assert continuous_domain(sinh(x)+cosh(x), x, S.Reals) == S.Reals
+    assert continuous_domain(tanh(x)+sech(x), x, S.Reals) == S.Reals
+    assert continuous_domain(atan(x)+asinh(x), x, S.Reals) == S.Reals
+    assert continuous_domain(acosh(x), x, S.Reals) == Interval(1, oo)
+    assert continuous_domain(atanh(x), x, S.Reals) == Interval.open(-1, 1)
+    assert continuous_domain(atanh(x)+acosh(x), x, S.Reals) == S.EmptySet
+    assert continuous_domain(asech(x), x, S.Reals) == Interval.Lopen(0, 1)
+    assert continuous_domain(acoth(x), x, S.Reals) == Union(
+        Interval.open(-oo, -1), Interval.open(1, oo))
+    assert continuous_domain(asec(x), x, S.Reals) == Union(
+        Interval(-oo, -1), Interval(1, oo))
+    assert continuous_domain(acsc(x), x, S.Reals) == Union(
+        Interval(-oo, -1), Interval(1, oo))
+    for f in (coth, acsch, csch):
+        assert continuous_domain(f(x), x, S.Reals) == Union(
+            Interval.open(-oo, 0), Interval.open(0, oo))
+    assert continuous_domain(acot(x), x, S.Reals).contains(0) == False
+    assert continuous_domain(1/(exp(x) - x), x, S.Reals) == Complement(
+        S.Reals, ConditionSet(x, Eq(-x + exp(x), 0), S.Reals))
+    assert continuous_domain(frac(x**2), x, Interval(-2,-1)) == Union(
+        Interval.open(-2, -sqrt(3)), Interval.open(-sqrt(2), -1),
+        Interval.open(-sqrt(3), -sqrt(2)))
+    assert continuous_domain(frac(x), x, S.Reals) == Complement(
+        S.Reals, S.Integers)
+    raises(NotImplementedError, lambda : continuous_domain(
+        1/(x**2+1), x, S.Complexes))
+    raises(NotImplementedError, lambda : continuous_domain(
+        gamma(x), x, Interval(-5,0)))
+    assert continuous_domain(x + gamma(pi), x, S.Reals) == S.Reals
+
+
+@XFAIL
+def test_continuous_domain_acot():
+    acot_cont = Piecewise((pi+acot(x), x<0), (acot(x), True))
+    assert continuous_domain(acot_cont, x, S.Reals) == S.Reals
+
+@XFAIL
+def test_continuous_domain_gamma():
+    assert continuous_domain(gamma(x), x, S.Reals).contains(-1) == False
+
+@XFAIL
+def test_continuous_domain_neg_power():
+    assert continuous_domain((x-2)**(1-x), x, S.Reals) == Interval.open(2, oo)
+
+
+def test_not_empty_in():
+    assert not_empty_in(FiniteSet(x, 2*x).intersect(Interval(1, 2, True, False)), x) == \
+        Interval(S.Half, 2, True, False)
+    assert not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x) == \
+        Union(Interval(-sqrt(2), -1), Interval(1, 2))
+    assert not_empty_in(FiniteSet(x**2 + x, x).intersect(Interval(2, 4)), x) == \
+        Union(Interval(-sqrt(17)/2 - S.Half, -2),
+              Interval(1, Rational(-1, 2) + sqrt(17)/2), Interval(2, 4))
+    assert not_empty_in(FiniteSet(x/(x - 1)).intersect(S.Reals), x) == \
+        Complement(S.Reals, FiniteSet(1))
+    assert not_empty_in(FiniteSet(a/(a - 1)).intersect(S.Reals), a) == \
+        Complement(S.Reals, FiniteSet(1))
+    assert not_empty_in(FiniteSet((x**2 - 3*x + 2)/(x - 1)).intersect(S.Reals), x) == \
+        Complement(S.Reals, FiniteSet(1))
+    assert not_empty_in(FiniteSet(3, 4, x/(x - 1)).intersect(Interval(2, 3)), x) == \
+        Interval(-oo, oo)
+    assert not_empty_in(FiniteSet(4, x/(x - 1)).intersect(Interval(2, 3)), x) == \
+        Interval(S(3)/2, 2)
+    assert not_empty_in(FiniteSet(x/(x**2 - 1)).intersect(S.Reals), x) == \
+        Complement(S.Reals, FiniteSet(-1, 1))
+    assert not_empty_in(FiniteSet(x, x**2).intersect(Union(Interval(1, 3, True, True),
+                                                           Interval(4, 5))), x) == \
+        Union(Interval(-sqrt(5), -2), Interval(-sqrt(3), -1, True, True),
+              Interval(1, 3, True, True), Interval(4, 5))
+    assert not_empty_in(FiniteSet(1).intersect(Interval(3, 4)), x) == S.EmptySet
+    assert not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x) == \
+        Union(Interval(-2, -1, True, False), Interval(2, oo))
+    raises(ValueError, lambda: not_empty_in(x))
+    raises(ValueError, lambda: not_empty_in(Interval(0, 1), x))
+    raises(NotImplementedError,
+           lambda: not_empty_in(FiniteSet(x).intersect(S.Reals), x, a))
+
+
+@_both_exp_pow
+def test_periodicity():
+    assert periodicity(sin(2*x), x) == pi
+    assert periodicity((-2)*tan(4*x), x) == pi/4
+    assert periodicity(sin(x)**2, x) == 2*pi
+    assert periodicity(3**tan(3*x), x) == pi/3
+    assert periodicity(tan(x)*cos(x), x) == 2*pi
+    assert periodicity(sin(x)**(tan(x)), x) == 2*pi
+    assert periodicity(tan(x)*sec(x), x) == 2*pi
+    assert periodicity(sin(2*x)*cos(2*x) - y, x) == pi/2
+    assert periodicity(tan(x) + cot(x), x) == pi
+    assert periodicity(sin(x) - cos(2*x), x) == 2*pi
+    assert periodicity(sin(x) - 1, x) == 2*pi
+    assert periodicity(sin(4*x) + sin(x)*cos(x), x) == pi
+    assert periodicity(exp(sin(x)), x) == 2*pi
+    assert periodicity(log(cot(2*x)) - sin(cos(2*x)), x) == pi
+    assert periodicity(sin(2*x)*exp(tan(x) - csc(2*x)), x) == pi
+    assert periodicity(cos(sec(x) - csc(2*x)), x) == 2*pi
+    assert periodicity(tan(sin(2*x)), x) == pi
+    assert periodicity(2*tan(x)**2, x) == pi
+    assert periodicity(sin(x%4), x) == 4
+    assert periodicity(sin(x)%4, x) == 2*pi
+    assert periodicity(tan((3*x-2)%4), x) == Rational(4, 3)
+    assert periodicity((sqrt(2)*(x+1)+x) % 3, x) == 3 / (sqrt(2)+1)
+    assert periodicity((x**2+1) % x, x) is None
+    assert periodicity(sin(re(x)), x) == 2*pi
+    assert periodicity(sin(x)**2 + cos(x)**2, x) is S.Zero
+    assert periodicity(tan(x), y) is S.Zero
+    assert periodicity(sin(x) + I*cos(x), x) == 2*pi
+    assert periodicity(x - sin(2*y), y) == pi
+
+    assert periodicity(exp(x), x) is None
+    assert periodicity(exp(I*x), x) == 2*pi
+    assert periodicity(exp(I*a), a) == 2*pi
+    assert periodicity(exp(a), a) is None
+    assert periodicity(exp(log(sin(a) + I*cos(2*a)), evaluate=False), a) == 2*pi
+    assert periodicity(exp(log(sin(2*a) + I*cos(a)), evaluate=False), a) == 2*pi
+    assert periodicity(exp(sin(a)), a) == 2*pi
+    assert periodicity(exp(2*I*a), a) == pi
+    assert periodicity(exp(a + I*sin(a)), a) is None
+    assert periodicity(exp(cos(a/2) + sin(a)), a) == 4*pi
+    assert periodicity(log(x), x) is None
+    assert periodicity(exp(x)**sin(x), x) is None
+    assert periodicity(sin(x)**y, y) is None
+
+    assert periodicity(Abs(sin(Abs(sin(x)))), x) == pi
+    assert all(periodicity(Abs(f(x)), x) == pi for f in (
+        cos, sin, sec, csc, tan, cot))
+    assert periodicity(Abs(sin(tan(x))), x) == pi
+    assert periodicity(Abs(sin(sin(x) + tan(x))), x) == 2*pi
+    assert periodicity(sin(x) > S.Half, x) == 2*pi
+
+    assert periodicity(x > 2, x) is None
+    assert periodicity(x**3 - x**2 + 1, x) is None
+    assert periodicity(Abs(x), x) is None
+    assert periodicity(Abs(x**2 - 1), x) is None
+
+    assert periodicity((x**2 + 4)%2, x) is None
+    assert periodicity((E**x)%3, x) is None
+
+    assert periodicity(sin(expint(1, x))/expint(1, x), x) is None
+    # returning `None` for any Piecewise
+    p = Piecewise((0, x < -1), (x**2, x <= 1), (log(x), True))
+    assert periodicity(p, x) is None
+
+    m = MatrixSymbol('m', 3, 3)
+    raises(NotImplementedError, lambda: periodicity(sin(m), m))
+    raises(NotImplementedError, lambda: periodicity(sin(m[0, 0]), m))
+    raises(NotImplementedError, lambda: periodicity(sin(m), m[0, 0]))
+    raises(NotImplementedError, lambda: periodicity(sin(m[0, 0]), m[0, 0]))
+
+
+def test_periodicity_check():
+    assert periodicity(tan(x), x, check=True) == pi
+    assert periodicity(sin(x) + cos(x), x, check=True) == 2*pi
+    assert periodicity(sec(x), x) == 2*pi
+    assert periodicity(sin(x*y), x) == 2*pi/abs(y)
+    assert periodicity(Abs(sec(sec(x))), x) == pi
+
+
+def test_lcim():
+    assert lcim([S.Half, S(2), S(3)]) == 6
+    assert lcim([pi/2, pi/4, pi]) == pi
+    assert lcim([2*pi, pi/2]) == 2*pi
+    assert lcim([S.One, 2*pi]) is None
+    assert lcim([S(2) + 2*E, E/3 + Rational(1, 3), S.One + E]) == S(2) + 2*E
+
+
+def test_is_convex():
+    assert is_convex(1/x, x, domain=Interval.open(0, oo)) == True
+    assert is_convex(1/x, x, domain=Interval(-oo, 0)) == False
+    assert is_convex(x**2, x, domain=Interval(0, oo)) == True
+    assert is_convex(1/x**3, x, domain=Interval.Lopen(0, oo)) == True
+    assert is_convex(-1/x**3, x, domain=Interval.Ropen(-oo, 0)) == True
+    assert is_convex(log(x) ,x) == False
+    assert is_convex(x**2+y**2, x, y) == True
+    assert is_convex(cos(x) + cos(y), x) == False
+    assert is_convex(8*x**2 - 2*y**2, x, y) == False
+
+
+def test_stationary_points():
+    assert stationary_points(sin(x), x, Interval(-pi/2, pi/2)
+        ) == {-pi/2, pi/2}
+    assert  stationary_points(sin(x), x, Interval.Ropen(0, pi/4)
+        ) is S.EmptySet
+    assert stationary_points(tan(x), x,
+        ) is S.EmptySet
+    assert stationary_points(sin(x)*cos(x), x, Interval(0, pi)
+        ) == {pi/4, pi*Rational(3, 4)}
+    assert stationary_points(sec(x), x, Interval(0, pi)
+        ) == {0, pi}
+    assert stationary_points((x+3)*(x-2), x
+        ) == FiniteSet(Rational(-1, 2))
+    assert stationary_points((x + 3)/(x - 2), x, Interval(-5, 5)
+        ) is S.EmptySet
+    assert stationary_points((x**2+3)/(x-2), x
+        ) == {2 - sqrt(7), 2 + sqrt(7)}
+    assert stationary_points((x**2+3)/(x-2), x, Interval(0, 5)
+        ) == {2 + sqrt(7)}
+    assert stationary_points(x**4 + x**3 - 5*x**2, x, S.Reals
+        ) == FiniteSet(-2, 0, Rational(5, 4))
+    assert stationary_points(exp(x), x
+        ) is S.EmptySet
+    assert stationary_points(log(x) - x, x, S.Reals
+        ) == {1}
+    assert stationary_points(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
+        ) == {0, -pi, pi}
+    assert stationary_points(y, x, S.Reals
+        ) == S.Reals
+    assert stationary_points(y, x, S.EmptySet) == S.EmptySet
+
+
+def test_maximum():
+    assert maximum(sin(x), x) is S.One
+    assert maximum(sin(x), x, Interval(0, 1)) == sin(1)
+    assert maximum(tan(x), x) is oo
+    assert maximum(tan(x), x, Interval(-pi/4, pi/4)) is S.One
+    assert maximum(sin(x)*cos(x), x, S.Reals) == S.Half
+    assert simplify(maximum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8)))
+        ) == sqrt(2)/4
+    assert maximum((x+3)*(x-2), x) is oo
+    assert maximum((x+3)*(x-2), x, Interval(-5, 0)) == S(14)
+    assert maximum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(2, 7)
+    assert simplify(maximum(-x**4-x**3+x**2+10, x)
+        ) == 41*sqrt(41)/512 + Rational(5419, 512)
+    assert maximum(exp(x), x, Interval(-oo, 2)) == exp(2)
+    assert maximum(log(x) - x, x, S.Reals) is S.NegativeOne
+    assert maximum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
+        ) is S.One
+    assert maximum(cos(x)-sin(x), x, S.Reals) == sqrt(2)
+    assert maximum(y, x, S.Reals) == y
+    assert maximum(abs(a**3 + a), a, Interval(0, 2)) == 10
+    assert maximum(abs(60*a**3 + 24*a), a, Interval(0, 2)) == 528
+    assert maximum(abs(12*a*(5*a**2 + 2)), a, Interval(0, 2)) == 528
+    assert maximum(x/sqrt(x**2+1), x, S.Reals) == 1
+
+    raises(ValueError, lambda : maximum(sin(x), x, S.EmptySet))
+    raises(ValueError, lambda : maximum(log(cos(x)), x, S.EmptySet))
+    raises(ValueError, lambda : maximum(1/(x**2 + y**2 + 1), x, S.EmptySet))
+    raises(ValueError, lambda : maximum(sin(x), sin(x)))
+    raises(ValueError, lambda : maximum(sin(x), x*y, S.EmptySet))
+    raises(ValueError, lambda : maximum(sin(x), S.One))
+
+
+def test_minimum():
+    assert minimum(sin(x), x) is S.NegativeOne
+    assert minimum(sin(x), x, Interval(1, 4)) == sin(4)
+    assert minimum(tan(x), x) is -oo
+    assert minimum(tan(x), x, Interval(-pi/4, pi/4)) is S.NegativeOne
+    assert minimum(sin(x)*cos(x), x, S.Reals) == Rational(-1, 2)
+    assert simplify(minimum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8)))
+        ) == -sqrt(2)/4
+    assert minimum((x+3)*(x-2), x) == Rational(-25, 4)
+    assert minimum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(-3, 2)
+    assert minimum(x**4-x**3+x**2+10, x) == S(10)
+    assert minimum(exp(x), x, Interval(-2, oo)) == exp(-2)
+    assert minimum(log(x) - x, x, S.Reals) is -oo
+    assert minimum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
+        ) is S.NegativeOne
+    assert minimum(cos(x)-sin(x), x, S.Reals) == -sqrt(2)
+    assert minimum(y, x, S.Reals) == y
+    assert minimum(x/sqrt(x**2+1), x, S.Reals) == -1
+
+    raises(ValueError, lambda : minimum(sin(x), x, S.EmptySet))
+    raises(ValueError, lambda : minimum(log(cos(x)), x, S.EmptySet))
+    raises(ValueError, lambda : minimum(1/(x**2 + y**2 + 1), x, S.EmptySet))
+    raises(ValueError, lambda : minimum(sin(x), sin(x)))
+    raises(ValueError, lambda : minimum(sin(x), x*y, S.EmptySet))
+    raises(ValueError, lambda : minimum(sin(x), S.One))
+
+
+def test_issue_19869():
+    assert (maximum(sqrt(3)*(x - 1)/(3*sqrt(x**2 + 1)), x)
+        ) == sqrt(3)/3
+
+
+def test_issue_16469():
+    f = abs(a)
+    assert function_range(f, a, S.Reals) == Interval(0, oo, False, True)
+
+
+@_both_exp_pow
+def test_issue_18747():
+    assert periodicity(exp(pi*I*(x/4 + S.Half/2)), x) == 8
+
+
+def test_issue_25942():
+    assert (acos(x) > pi/3).as_set() == Interval.Ropen(-1, S(1)/2)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/util.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..dac316358873de2418dd8ab56445823f07a37b1b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/calculus/util.py
@@ -0,0 +1,895 @@
+from .accumulationbounds import AccumBounds, AccumulationBounds # noqa: F401
+from .singularities import singularities
+from sympy.core import Pow, S
+from sympy.core.function import diff, expand_mul, Function
+from sympy.core.kind import NumberKind
+from sympy.core.mod import Mod
+from sympy.core.numbers import equal_valued
+from sympy.core.relational import Relational
+from sympy.core.symbol import Symbol, Dummy
+from sympy.core.sympify import _sympify
+from sympy.functions.elementary.complexes import Abs, im, re
+from sympy.functions.elementary.exponential import exp, log
+from sympy.functions.elementary.integers import frac
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.functions.elementary.trigonometric import (
+    TrigonometricFunction, sin, cos, tan, cot, csc, sec,
+    asin, acos, acot, atan, asec, acsc)
+from sympy.functions.elementary.hyperbolic import (sinh, cosh, tanh, coth,
+    sech, csch, asinh, acosh, atanh, acoth, asech, acsch)
+from sympy.polys.polytools import degree, lcm_list
+from sympy.sets.sets import (Interval, Intersection, FiniteSet, Union,
+                             Complement)
+from sympy.sets.fancysets import ImageSet
+from sympy.sets.conditionset import ConditionSet
+from sympy.utilities import filldedent
+from sympy.utilities.iterables import iterable
+from sympy.matrices.dense import hessian
+
+
+def continuous_domain(f, symbol, domain):
+    """
+    Returns the domain on which the function expression f is continuous.
+
+    This function is limited by the ability to determine the various
+    singularities and discontinuities of the given function.
+    The result is either given as a union of intervals or constructed using
+    other set operations.
+
+    Parameters
+    ==========
+
+    f : :py:class:`~.Expr`
+        The concerned function.
+    symbol : :py:class:`~.Symbol`
+        The variable for which the intervals are to be determined.
+    domain : :py:class:`~.Interval`
+        The domain over which the continuity of the symbol has to be checked.
+
+    Examples
+    ========
+
+    >>> from sympy import Interval, Symbol, S, tan, log, pi, sqrt
+    >>> from sympy.calculus.util import continuous_domain
+    >>> x = Symbol('x')
+    >>> continuous_domain(1/x, x, S.Reals)
+    Union(Interval.open(-oo, 0), Interval.open(0, oo))
+    >>> continuous_domain(tan(x), x, Interval(0, pi))
+    Union(Interval.Ropen(0, pi/2), Interval.Lopen(pi/2, pi))
+    >>> continuous_domain(sqrt(x - 2), x, Interval(-5, 5))
+    Interval(2, 5)
+    >>> continuous_domain(log(2*x - 1), x, S.Reals)
+    Interval.open(1/2, oo)
+
+    Returns
+    =======
+
+    :py:class:`~.Interval`
+        Union of all intervals where the function is continuous.
+
+    Raises
+    ======
+
+    NotImplementedError
+        If the method to determine continuity of such a function
+        has not yet been developed.
+
+    """
+    from sympy.solvers.inequalities import solve_univariate_inequality
+
+    if not domain.is_subset(S.Reals):
+        raise NotImplementedError(filldedent('''
+            Domain must be a subset of S.Reals.
+            '''))
+    implemented = [Pow, exp, log, Abs, frac,
+                   sin, cos, tan, cot, sec, csc,
+                   asin, acos, atan, acot, asec, acsc,
+                   sinh, cosh, tanh, coth, sech, csch,
+                   asinh, acosh, atanh, acoth, asech, acsch]
+    used = [fct.func for fct in f.atoms(Function) if fct.has(symbol)]
+    if any(func not in implemented for func in used):
+        raise NotImplementedError(filldedent('''
+            Unable to determine the domain of the given function.
+            '''))
+
+    x = Symbol('x')
+    constraints = {
+        log: (x > 0,),
+        asin: (x >= -1, x <= 1),
+        acos: (x >= -1, x <= 1),
+        acosh: (x >= 1,),
+        atanh: (x > -1, x < 1),
+        asech: (x > 0, x <= 1)
+    }
+    constraints_union = {
+        asec: (x <= -1, x >= 1),
+        acsc: (x <= -1, x >= 1),
+        acoth: (x < -1, x > 1)
+    }
+
+    cont_domain = domain
+    for atom in f.atoms(Pow):
+        den = atom.exp.as_numer_denom()[1]
+        if atom.exp.is_rational and den.is_odd:
+            pass    # 0**negative handled by singularities()
+        else:
+            constraint = solve_univariate_inequality(atom.base >= 0,
+                                                        symbol).as_set()
+            cont_domain = Intersection(constraint, cont_domain)
+
+    for atom in f.atoms(Function):
+        if atom.func in constraints:
+            for c in constraints[atom.func]:
+                constraint_relational = c.subs(x, atom.args[0])
+                constraint_set = solve_univariate_inequality(
+                    constraint_relational, symbol).as_set()
+                cont_domain = Intersection(constraint_set, cont_domain)
+        elif atom.func in constraints_union:
+            constraint_set = S.EmptySet
+            for c in constraints_union[atom.func]:
+                constraint_relational = c.subs(x, atom.args[0])
+                constraint_set += solve_univariate_inequality(
+                    constraint_relational, symbol).as_set()
+            cont_domain = Intersection(constraint_set, cont_domain)
+        # XXX: the discontinuities below could be factored out in
+        # a new "discontinuities()".
+        elif atom.func == acot:
+            from sympy.solvers.solveset import solveset_real
+            # Sympy's acot() has a step discontinuity at 0. Since it's
+            # neither an essential singularity nor a pole, singularities()
+            # will not report it. But it's still relevant for determining
+            # the continuity of the function f.
+            cont_domain -= solveset_real(atom.args[0], symbol)
+            # Note that the above may introduce spurious discontinuities, e.g.
+            # for abs(acot(x)) at 0.
+        elif atom.func == frac:
+            from sympy.solvers.solveset import solveset_real
+            r = function_range(atom.args[0], symbol, domain)
+            r = Intersection(r, S.Integers)
+            if r.is_finite_set:
+                discont = S.EmptySet
+                for n in r:
+                    discont += solveset_real(atom.args[0]-n, symbol)
+            else:
+                discont = ConditionSet(
+                    symbol, S.Integers.contains(atom.args[0]), cont_domain)
+            cont_domain -= discont
+
+    return cont_domain - singularities(f, symbol, domain)
+
+
+def function_range(f, symbol, domain):
+    """
+    Finds the range of a function in a given domain.
+    This method is limited by the ability to determine the singularities and
+    determine limits.
+
+    Parameters
+    ==========
+
+    f : :py:class:`~.Expr`
+        The concerned function.
+    symbol : :py:class:`~.Symbol`
+        The variable for which the range of function is to be determined.
+    domain : :py:class:`~.Interval`
+        The domain under which the range of the function has to be found.
+
+    Examples
+    ========
+
+    >>> from sympy import Interval, Symbol, S, exp, log, pi, sqrt, sin, tan
+    >>> from sympy.calculus.util import function_range
+    >>> x = Symbol('x')
+    >>> function_range(sin(x), x, Interval(0, 2*pi))
+    Interval(-1, 1)
+    >>> function_range(tan(x), x, Interval(-pi/2, pi/2))
+    Interval(-oo, oo)
+    >>> function_range(1/x, x, S.Reals)
+    Union(Interval.open(-oo, 0), Interval.open(0, oo))
+    >>> function_range(exp(x), x, S.Reals)
+    Interval.open(0, oo)
+    >>> function_range(log(x), x, S.Reals)
+    Interval(-oo, oo)
+    >>> function_range(sqrt(x), x, Interval(-5, 9))
+    Interval(0, 3)
+
+    Returns
+    =======
+
+    :py:class:`~.Interval`
+        Union of all ranges for all intervals under domain where function is
+        continuous.
+
+    Raises
+    ======
+
+    NotImplementedError
+        If any of the intervals, in the given domain, for which function
+        is continuous are not finite or real,
+        OR if the critical points of the function on the domain cannot be found.
+    """
+
+    if domain is S.EmptySet:
+        return S.EmptySet
+
+    period = periodicity(f, symbol)
+    if period == S.Zero:
+        # the expression is constant wrt symbol
+        return FiniteSet(f.expand())
+
+    from sympy.series.limits import limit
+    from sympy.solvers.solveset import solveset
+
+    if period is not None:
+        if isinstance(domain, Interval):
+            if (domain.inf - domain.sup).is_infinite:
+                domain = Interval(0, period)
+        elif isinstance(domain, Union):
+            for sub_dom in domain.args:
+                if isinstance(sub_dom, Interval) and \
+                ((sub_dom.inf - sub_dom.sup).is_infinite):
+                    domain = Interval(0, period)
+
+    intervals = continuous_domain(f, symbol, domain)
+    range_int = S.EmptySet
+    if isinstance(intervals,(Interval, FiniteSet)):
+        interval_iter = (intervals,)
+    elif isinstance(intervals, Union):
+        interval_iter = intervals.args
+    else:
+        raise NotImplementedError("Unable to find range for the given domain.")
+
+    for interval in interval_iter:
+        if isinstance(interval, FiniteSet):
+            for singleton in interval:
+                if singleton in domain:
+                    range_int += FiniteSet(f.subs(symbol, singleton))
+        elif isinstance(interval, Interval):
+            vals = S.EmptySet
+            critical_values = S.EmptySet
+            bounds = ((interval.left_open, interval.inf, '+'),
+                   (interval.right_open, interval.sup, '-'))
+
+            for is_open, limit_point, direction in bounds:
+                if is_open:
+                    critical_values += FiniteSet(limit(f, symbol, limit_point, direction))
+                    vals += critical_values
+                else:
+                    vals += FiniteSet(f.subs(symbol, limit_point))
+
+            critical_points = solveset(f.diff(symbol), symbol, interval)
+
+            if not iterable(critical_points):
+                raise NotImplementedError(
+                        'Unable to find critical points for {}'.format(f))
+            if isinstance(critical_points, ImageSet):
+                raise NotImplementedError(
+                        'Infinite number of critical points for {}'.format(f))
+
+            for critical_point in critical_points:
+                vals += FiniteSet(f.subs(symbol, critical_point))
+
+            left_open, right_open = False, False
+
+            if critical_values is not S.EmptySet:
+                if critical_values.inf == vals.inf:
+                    left_open = True
+
+                if critical_values.sup == vals.sup:
+                    right_open = True
+
+            range_int += Interval(vals.inf, vals.sup, left_open, right_open)
+        else:
+            raise NotImplementedError("Unable to find range for the given domain.")
+
+    return range_int
+
+
+def not_empty_in(finset_intersection, *syms):
+    """
+    Finds the domain of the functions in ``finset_intersection`` in which the
+    ``finite_set`` is not-empty.
+
+    Parameters
+    ==========
+
+    finset_intersection : Intersection of FiniteSet
+        The unevaluated intersection of FiniteSet containing
+        real-valued functions with Union of Sets
+    syms : Tuple of symbols
+        Symbol for which domain is to be found
+
+    Raises
+    ======
+
+    NotImplementedError
+        The algorithms to find the non-emptiness of the given FiniteSet are
+        not yet implemented.
+    ValueError
+        The input is not valid.
+    RuntimeError
+        It is a bug, please report it to the github issue tracker
+        (https://github.com/sympy/sympy/issues).
+
+    Examples
+    ========
+
+    >>> from sympy import FiniteSet, Interval, not_empty_in, oo
+    >>> from sympy.abc import x
+    >>> not_empty_in(FiniteSet(x/2).intersect(Interval(0, 1)), x)
+    Interval(0, 2)
+    >>> not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x)
+    Union(Interval(1, 2), Interval(-sqrt(2), -1))
+    >>> not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x)
+    Union(Interval.Lopen(-2, -1), Interval(2, oo))
+    """
+
+    # TODO: handle piecewise defined functions
+    # TODO: handle transcendental functions
+    # TODO: handle multivariate functions
+    if len(syms) == 0:
+        raise ValueError("One or more symbols must be given in syms.")
+
+    if finset_intersection is S.EmptySet:
+        return S.EmptySet
+
+    if isinstance(finset_intersection, Union):
+        elm_in_sets = finset_intersection.args[0]
+        return Union(not_empty_in(finset_intersection.args[1], *syms),
+                     elm_in_sets)
+
+    if isinstance(finset_intersection, FiniteSet):
+        finite_set = finset_intersection
+        _sets = S.Reals
+    else:
+        finite_set = finset_intersection.args[1]
+        _sets = finset_intersection.args[0]
+
+    if not isinstance(finite_set, FiniteSet):
+        raise ValueError('A FiniteSet must be given, not %s: %s' %
+                         (type(finite_set), finite_set))
+
+    if len(syms) == 1:
+        symb = syms[0]
+    else:
+        raise NotImplementedError('more than one variables %s not handled' %
+                                  (syms,))
+
+    def elm_domain(expr, intrvl):
+        """ Finds the domain of an expression in any given interval """
+        from sympy.solvers.solveset import solveset
+
+        _start = intrvl.start
+        _end = intrvl.end
+        _singularities = solveset(expr.as_numer_denom()[1], symb,
+                                  domain=S.Reals)
+
+        if intrvl.right_open:
+            if _end is S.Infinity:
+                _domain1 = S.Reals
+            else:
+                _domain1 = solveset(expr < _end, symb, domain=S.Reals)
+        else:
+            _domain1 = solveset(expr <= _end, symb, domain=S.Reals)
+
+        if intrvl.left_open:
+            if _start is S.NegativeInfinity:
+                _domain2 = S.Reals
+            else:
+                _domain2 = solveset(expr > _start, symb, domain=S.Reals)
+        else:
+            _domain2 = solveset(expr >= _start, symb, domain=S.Reals)
+
+        # domain in the interval
+        expr_with_sing = Intersection(_domain1, _domain2)
+        expr_domain = Complement(expr_with_sing, _singularities)
+        return expr_domain
+
+    if isinstance(_sets, Interval):
+        return Union(*[elm_domain(element, _sets) for element in finite_set])
+
+    if isinstance(_sets, Union):
+        _domain = S.EmptySet
+        for intrvl in _sets.args:
+            _domain_element = Union(*[elm_domain(element, intrvl)
+                                      for element in finite_set])
+            _domain = Union(_domain, _domain_element)
+        return _domain
+
+
+def periodicity(f, symbol, check=False):
+    """
+    Tests the given function for periodicity in the given symbol.
+
+    Parameters
+    ==========
+
+    f : :py:class:`~.Expr`
+        The concerned function.
+    symbol : :py:class:`~.Symbol`
+        The variable for which the period is to be determined.
+    check : bool, optional
+        The flag to verify whether the value being returned is a period or not.
+
+    Returns
+    =======
+
+    period
+        The period of the function is returned.
+        ``None`` is returned when the function is aperiodic or has a complex period.
+        The value of $0$ is returned as the period of a constant function.
+
+    Raises
+    ======
+
+    NotImplementedError
+        The value of the period computed cannot be verified.
+
+
+    Notes
+    =====
+
+    Currently, we do not support functions with a complex period.
+    The period of functions having complex periodic values such
+    as ``exp``, ``sinh`` is evaluated to ``None``.
+
+    The value returned might not be the "fundamental" period of the given
+    function i.e. it may not be the smallest periodic value of the function.
+
+    The verification of the period through the ``check`` flag is not reliable
+    due to internal simplification of the given expression. Hence, it is set
+    to ``False`` by default.
+
+    Examples
+    ========
+    >>> from sympy import periodicity, Symbol, sin, cos, tan, exp
+    >>> x = Symbol('x')
+    >>> f = sin(x) + sin(2*x) + sin(3*x)
+    >>> periodicity(f, x)
+    2*pi
+    >>> periodicity(sin(x)*cos(x), x)
+    pi
+    >>> periodicity(exp(tan(2*x) - 1), x)
+    pi/2
+    >>> periodicity(sin(4*x)**cos(2*x), x)
+    pi
+    >>> periodicity(exp(x), x)
+    """
+    if symbol.kind is not NumberKind:
+        raise NotImplementedError("Cannot use symbol of kind %s" % symbol.kind)
+    temp = Dummy('x', real=True)
+    f = f.subs(symbol, temp)
+    symbol = temp
+
+    def _check(orig_f, period):
+        '''Return the checked period or raise an error.'''
+        new_f = orig_f.subs(symbol, symbol + period)
+        if new_f.equals(orig_f):
+            return period
+        else:
+            raise NotImplementedError(filldedent('''
+                The period of the given function cannot be verified.
+                When `%s` was replaced with `%s + %s` in `%s`, the result
+                was `%s` which was not recognized as being the same as
+                the original function.
+                So either the period was wrong or the two forms were
+                not recognized as being equal.
+                Set check=False to obtain the value.''' %
+                (symbol, symbol, period, orig_f, new_f)))
+
+    orig_f = f
+    period = None
+
+    if isinstance(f, Relational):
+        f = f.lhs - f.rhs
+
+    f = f.simplify()
+
+    if symbol not in f.free_symbols:
+        return S.Zero
+
+    if isinstance(f, TrigonometricFunction):
+        try:
+            period = f.period(symbol)
+        except NotImplementedError:
+            pass
+
+    if isinstance(f, Abs):
+        arg = f.args[0]
+        if isinstance(arg, (sec, csc, cos)):
+            # all but tan and cot might have a
+            # a period that is half as large
+            # so recast as sin
+            arg = sin(arg.args[0])
+        period = periodicity(arg, symbol)
+        if period is not None and isinstance(arg, sin):
+            # the argument of Abs was a trigonometric other than
+            # cot or tan; test to see if the half-period
+            # is valid. Abs(arg) has behaviour equivalent to
+            # orig_f, so use that for test:
+            orig_f = Abs(arg)
+            try:
+                return _check(orig_f, period/2)
+            except NotImplementedError as err:
+                if check:
+                    raise NotImplementedError(err)
+            # else let new orig_f and period be
+            # checked below
+
+    if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1):
+        f = Pow(S.Exp1, expand_mul(f.exp))
+        if im(f) != 0:
+            period_real = periodicity(re(f), symbol)
+            period_imag = periodicity(im(f), symbol)
+            if period_real is not None and period_imag is not None:
+                period = lcim([period_real, period_imag])
+
+    if f.is_Pow and f.base != S.Exp1:
+        base, expo = f.args
+        base_has_sym = base.has(symbol)
+        expo_has_sym = expo.has(symbol)
+
+        if base_has_sym and not expo_has_sym:
+            period = periodicity(base, symbol)
+
+        elif expo_has_sym and not base_has_sym:
+            period = periodicity(expo, symbol)
+
+        else:
+            period = _periodicity(f.args, symbol)
+
+    elif f.is_Mul:
+        coeff, g = f.as_independent(symbol, as_Add=False)
+        if isinstance(g, TrigonometricFunction) or not equal_valued(coeff, 1):
+            period = periodicity(g, symbol)
+        else:
+            period = _periodicity(g.args, symbol)
+
+    elif f.is_Add:
+        k, g = f.as_independent(symbol)
+        if k is not S.Zero:
+            return periodicity(g, symbol)
+
+        period = _periodicity(g.args, symbol)
+
+    elif isinstance(f, Mod):
+        a, n = f.args
+
+        if a == symbol:
+            period = n
+        elif isinstance(a, TrigonometricFunction):
+            period = periodicity(a, symbol)
+        #check if 'f' is linear in 'symbol'
+        elif (a.is_polynomial(symbol) and degree(a, symbol) == 1 and
+            symbol not in n.free_symbols):
+                period = Abs(n / a.diff(symbol))
+
+    elif isinstance(f, Piecewise):
+        pass  # not handling Piecewise yet as the return type is not favorable
+
+    elif period is None:
+        from sympy.solvers.decompogen import compogen, decompogen
+        g_s = decompogen(f, symbol)
+        num_of_gs = len(g_s)
+        if num_of_gs > 1:
+            for index, g in enumerate(reversed(g_s)):
+                start_index = num_of_gs - 1 - index
+                g = compogen(g_s[start_index:], symbol)
+                if g not in (orig_f, f): # Fix for issue 12620
+                    period = periodicity(g, symbol)
+                    if period is not None:
+                        break
+
+    if period is not None:
+        if check:
+            return _check(orig_f, period)
+        return period
+
+    return None
+
+
+def _periodicity(args, symbol):
+    """
+    Helper for `periodicity` to find the period of a list of simpler
+    functions.
+    It uses the `lcim` method to find the least common period of
+    all the functions.
+
+    Parameters
+    ==========
+
+    args : Tuple of :py:class:`~.Symbol`
+        All the symbols present in a function.
+
+    symbol : :py:class:`~.Symbol`
+        The symbol over which the function is to be evaluated.
+
+    Returns
+    =======
+
+    period
+        The least common period of the function for all the symbols
+        of the function.
+        ``None`` if for at least one of the symbols the function is aperiodic.
+
+    """
+    periods = []
+    for f in args:
+        period = periodicity(f, symbol)
+        if period is None:
+            return None
+
+        if period is not S.Zero:
+            periods.append(period)
+
+    if len(periods) > 1:
+        return lcim(periods)
+
+    if periods:
+        return periods[0]
+
+
+def lcim(numbers):
+    """Returns the least common integral multiple of a list of numbers.
+
+    The numbers can be rational or irrational or a mixture of both.
+    `None` is returned for incommensurable numbers.
+
+    Parameters
+    ==========
+
+    numbers : list
+        Numbers (rational and/or irrational) for which lcim is to be found.
+
+    Returns
+    =======
+
+    number
+        lcim if it exists, otherwise ``None`` for incommensurable numbers.
+
+    Examples
+    ========
+
+    >>> from sympy.calculus.util import lcim
+    >>> from sympy import S, pi
+    >>> lcim([S(1)/2, S(3)/4, S(5)/6])
+    15/2
+    >>> lcim([2*pi, 3*pi, pi, pi/2])
+    6*pi
+    >>> lcim([S(1), 2*pi])
+    """
+    result = None
+    if all(num.is_irrational for num in numbers):
+        factorized_nums = [num.factor() for num in numbers]
+        factors_num = [num.as_coeff_Mul() for num in factorized_nums]
+        term = factors_num[0][1]
+        if all(factor == term for coeff, factor in factors_num):
+            common_term = term
+            coeffs = [coeff for coeff, factor in factors_num]
+            result = lcm_list(coeffs) * common_term
+
+    elif all(num.is_rational for num in numbers):
+        result = lcm_list(numbers)
+
+    else:
+        pass
+
+    return result
+
+def is_convex(f, *syms, domain=S.Reals):
+    r"""Determines the  convexity of the function passed in the argument.
+
+    Parameters
+    ==========
+
+    f : :py:class:`~.Expr`
+        The concerned function.
+    syms : Tuple of :py:class:`~.Symbol`
+        The variables with respect to which the convexity is to be determined.
+    domain : :py:class:`~.Interval`, optional
+        The domain over which the convexity of the function has to be checked.
+        If unspecified, S.Reals will be the default domain.
+
+    Returns
+    =======
+
+    bool
+        The method returns ``True`` if the function is convex otherwise it
+        returns ``False``.
+
+    Raises
+    ======
+
+    NotImplementedError
+        The check for the convexity of multivariate functions is not implemented yet.
+
+    Notes
+    =====
+
+    To determine concavity of a function pass `-f` as the concerned function.
+    To determine logarithmic convexity of a function pass `\log(f)` as
+    concerned function.
+    To determine logarithmic concavity of a function pass `-\log(f)` as
+    concerned function.
+
+    Currently, convexity check of multivariate functions is not handled.
+
+    Examples
+    ========
+
+    >>> from sympy import is_convex, symbols, exp, oo, Interval
+    >>> x = symbols('x')
+    >>> is_convex(exp(x), x)
+    True
+    >>> is_convex(x**3, x, domain = Interval(-1, oo))
+    False
+    >>> is_convex(1/x**2, x, domain=Interval.open(0, oo))
+    True
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Convex_function
+    .. [2] http://www.ifp.illinois.edu/~angelia/L3_convfunc.pdf
+    .. [3] https://en.wikipedia.org/wiki/Logarithmically_convex_function
+    .. [4] https://en.wikipedia.org/wiki/Logarithmically_concave_function
+    .. [5] https://en.wikipedia.org/wiki/Concave_function
+
+    """
+    if len(syms) > 1 :
+        return hessian(f, syms).is_positive_semidefinite
+    from sympy.solvers.inequalities import solve_univariate_inequality
+    f = _sympify(f)
+    var = syms[0]
+    if any(s in domain for s in singularities(f, var)):
+        return False
+    condition = f.diff(var, 2) < 0
+    if solve_univariate_inequality(condition, var, False, domain):
+        return False
+    return True
+
+
+def stationary_points(f, symbol, domain=S.Reals):
+    """
+    Returns the stationary points of a function (where derivative of the
+    function is 0) in the given domain.
+
+    Parameters
+    ==========
+
+    f : :py:class:`~.Expr`
+        The concerned function.
+    symbol : :py:class:`~.Symbol`
+        The variable for which the stationary points are to be determined.
+    domain : :py:class:`~.Interval`
+        The domain over which the stationary points have to be checked.
+        If unspecified, ``S.Reals`` will be the default domain.
+
+    Returns
+    =======
+
+    Set
+        A set of stationary points for the function. If there are no
+        stationary point, an :py:class:`~.EmptySet` is returned.
+
+    Examples
+    ========
+
+    >>> from sympy import Interval, Symbol, S, sin, pi, pprint, stationary_points
+    >>> x = Symbol('x')
+
+    >>> stationary_points(1/x, x, S.Reals)
+    EmptySet
+
+    >>> pprint(stationary_points(sin(x), x), use_unicode=False)
+              pi                              3*pi
+    {2*n*pi + -- | n in Integers} U {2*n*pi + ---- | n in Integers}
+              2                                2
+
+    >>> stationary_points(sin(x),x, Interval(0, 4*pi))
+    {pi/2, 3*pi/2, 5*pi/2, 7*pi/2}
+
+    """
+    from sympy.solvers.solveset import solveset
+
+    if domain is S.EmptySet:
+        return S.EmptySet
+
+    domain = continuous_domain(f, symbol, domain)
+    set = solveset(diff(f, symbol), symbol, domain)
+
+    return set
+
+
+def maximum(f, symbol, domain=S.Reals):
+    """
+    Returns the maximum value of a function in the given domain.
+
+    Parameters
+    ==========
+
+    f : :py:class:`~.Expr`
+        The concerned function.
+    symbol : :py:class:`~.Symbol`
+        The variable for maximum value needs to be determined.
+    domain : :py:class:`~.Interval`
+        The domain over which the maximum have to be checked.
+        If unspecified, then the global maximum is returned.
+
+    Returns
+    =======
+
+    number
+        Maximum value of the function in given domain.
+
+    Examples
+    ========
+
+    >>> from sympy import Interval, Symbol, S, sin, cos, pi, maximum
+    >>> x = Symbol('x')
+
+    >>> f = -x**2 + 2*x + 5
+    >>> maximum(f, x, S.Reals)
+    6
+
+    >>> maximum(sin(x), x, Interval(-pi, pi/4))
+    sqrt(2)/2
+
+    >>> maximum(sin(x)*cos(x), x)
+    1/2
+
+    """
+    if isinstance(symbol, Symbol):
+        if domain is S.EmptySet:
+            raise ValueError("Maximum value not defined for empty domain.")
+
+        return function_range(f, symbol, domain).sup
+    else:
+        raise ValueError("%s is not a valid symbol." % symbol)
+
+
+def minimum(f, symbol, domain=S.Reals):
+    """
+    Returns the minimum value of a function in the given domain.
+
+    Parameters
+    ==========
+
+    f : :py:class:`~.Expr`
+        The concerned function.
+    symbol : :py:class:`~.Symbol`
+        The variable for minimum value needs to be determined.
+    domain : :py:class:`~.Interval`
+        The domain over which the minimum have to be checked.
+        If unspecified, then the global minimum is returned.
+
+    Returns
+    =======
+
+    number
+        Minimum value of the function in the given domain.
+
+    Examples
+    ========
+
+    >>> from sympy import Interval, Symbol, S, sin, cos, minimum
+    >>> x = Symbol('x')
+
+    >>> f = x**2 + 2*x + 5
+    >>> minimum(f, x, S.Reals)
+    4
+
+    >>> minimum(sin(x), x, Interval(2, 3))
+    sin(3)
+
+    >>> minimum(sin(x)*cos(x), x)
+    -1/2
+
+    """
+    if isinstance(symbol, Symbol):
+        if domain is S.EmptySet:
+            raise ValueError("Minimum value not defined for empty domain.")
+
+        return function_range(f, symbol, domain).inf
+    else:
+        raise ValueError("%s is not a valid symbol." % symbol)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/concrete/tests/test_sums_products.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/concrete/tests/test_sums_products.py
new file mode 100644
index 0000000000000000000000000000000000000000..b190afe0bd403819d3525453879d7d5d39e20a56
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/concrete/tests/test_sums_products.py
@@ -0,0 +1,1676 @@
+from math import prod
+
+from sympy.concrete.expr_with_intlimits import ReorderError
+from sympy.concrete.products import (Product, product)
+from sympy.concrete.summations import (Sum, summation, telescopic,
+     eval_sum_residue, _dummy_with_inherited_properties_concrete)
+from sympy.core.function import (Derivative, Function)
+from sympy.core import (Catalan, EulerGamma)
+from sympy.core.facts import InconsistentAssumptions
+from sympy.core.mod import Mod
+from sympy.core.numbers import (E, I, Rational, nan, oo, pi)
+from sympy.core.relational import Eq, Ne
+from sympy.core.numbers import Float
+from sympy.core.singleton import S
+from sympy.core.symbol import (Dummy, Symbol, symbols)
+from sympy.core.sympify import sympify
+from sympy.functions.combinatorial.factorials import (rf, binomial, factorial)
+from sympy.functions.combinatorial.numbers import harmonic
+from sympy.functions.elementary.complexes import Abs, re
+from sympy.functions.elementary.exponential import (exp, log)
+from sympy.functions.elementary.hyperbolic import (sinh, tanh)
+from sympy.functions.elementary.integers import floor
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.functions.elementary.trigonometric import (cos, sin, atan)
+from sympy.functions.special.gamma_functions import (gamma, lowergamma)
+from sympy.functions.special.tensor_functions import KroneckerDelta
+from sympy.functions.special.zeta_functions import zeta
+from sympy.integrals.integrals import Integral
+from sympy.logic.boolalg import And, Or
+from sympy.matrices.expressions.matexpr import MatrixSymbol
+from sympy.matrices.expressions.special import Identity
+from sympy.matrices import (Matrix, SparseMatrix,
+    ImmutableDenseMatrix, ImmutableSparseMatrix, diag)
+from sympy.sets.contains import Contains
+from sympy.sets.fancysets import Range
+from sympy.sets.sets import Interval
+from sympy.simplify.combsimp import combsimp
+from sympy.simplify.simplify import simplify
+from sympy.tensor.indexed import (Idx, Indexed, IndexedBase)
+from sympy.testing.pytest import XFAIL, raises, slow
+from sympy.abc import a, b, c, d, k, m, x, y, z
+
+n = Symbol('n', integer=True)
+f, g = symbols('f g', cls=Function)
+
+def test_karr_convention():
+    # Test the Karr summation convention that we want to hold.
+    # See his paper "Summation in Finite Terms" for a detailed
+    # reasoning why we really want exactly this definition.
+    # The convention is described on page 309 and essentially
+    # in section 1.4, definition 3:
+    #
+    # \sum_{m <= i < n} f(i) 'has the obvious meaning'   for m < n
+    # \sum_{m <= i < n} f(i) = 0                         for m = n
+    # \sum_{m <= i < n} f(i) = - \sum_{n <= i < m} f(i)  for m > n
+    #
+    # It is important to note that he defines all sums with
+    # the upper limit being *exclusive*.
+    # In contrast, SymPy and the usual mathematical notation has:
+    #
+    # sum_{i = a}^b f(i) = f(a) + f(a+1) + ... + f(b-1) + f(b)
+    #
+    # with the upper limit *inclusive*. So translating between
+    # the two we find that:
+    #
+    # \sum_{m <= i < n} f(i) = \sum_{i = m}^{n-1} f(i)
+    #
+    # where we intentionally used two different ways to typeset the
+    # sum and its limits.
+
+    i = Symbol("i", integer=True)
+    k = Symbol("k", integer=True)
+    j = Symbol("j", integer=True)
+
+    # A simple example with a concrete summand and symbolic limits.
+
+    # The normal sum: m = k and n = k + j and therefore m < n:
+    m = k
+    n = k + j
+
+    a = m
+    b = n - 1
+    S1 = Sum(i**2, (i, a, b)).doit()
+
+    # The reversed sum: m = k + j and n = k and therefore m > n:
+    m = k + j
+    n = k
+
+    a = m
+    b = n - 1
+    S2 = Sum(i**2, (i, a, b)).doit()
+
+    assert simplify(S1 + S2) == 0
+
+    # Test the empty sum: m = k and n = k and therefore m = n:
+    m = k
+    n = k
+
+    a = m
+    b = n - 1
+    Sz = Sum(i**2, (i, a, b)).doit()
+
+    assert Sz == 0
+
+    # Another example this time with an unspecified summand and
+    # numeric limits. (We can not do both tests in the same example.)
+
+    # The normal sum with m < n:
+    m = 2
+    n = 11
+
+    a = m
+    b = n - 1
+    S1 = Sum(f(i), (i, a, b)).doit()
+
+    # The reversed sum with m > n:
+    m = 11
+    n = 2
+
+    a = m
+    b = n - 1
+    S2 = Sum(f(i), (i, a, b)).doit()
+
+    assert simplify(S1 + S2) == 0
+
+    # Test the empty sum with m = n:
+    m = 5
+    n = 5
+
+    a = m
+    b = n - 1
+    Sz = Sum(f(i), (i, a, b)).doit()
+
+    assert Sz == 0
+
+    e = Piecewise((exp(-i), Mod(i, 2) > 0), (0, True))
+    s = Sum(e, (i, 0, 11))
+    assert s.n(3) == s.doit().n(3)
+
+    # issue #27893
+    n = Symbol('n', integer=True)
+    assert Sum(1/(x**2 + 1), (x, oo, 0)).doit(deep=False) == Rational(-1, 2) + pi / (2 * tanh(pi))
+    assert Sum(c**x/factorial(x), (x, oo, 0)).doit(deep=False).simplify() == exp(c) - 1 # exponential series
+    assert Sum((-1)**x/x, (x, oo,0)).doit() == -log(2) # alternating harmnic series
+    assert Sum((1/2)**x,(x, oo, -1)).doit() == S(2) # geometric series
+    assert Sum(1/x, (x, oo, 0)).doit() == oo # harmonic series, divergent
+    assert Sum((-1)**x/(2*x+1), (x, oo, -1)).doit() == pi/4 # leibniz series
+    assert Sum((((-1)**x) * c**(2*x+1)) / factorial(2*x+1), (x, oo, -1)).doit() == sin(c) # sinusoidal series
+    assert Sum((((-1)**x) * c**(2*x+1)) / (2*x+1), (x, 0, oo)).doit() \
+        == Piecewise((atan(c), Ne(c**2, -1) & (Abs(c**2) <= 1)), \
+                     (Sum((-1)**x*c**(2*x + 1)/(2*x + 1), (x, 0, oo)), True)) # arctangent series
+    assert Sum(binomial(n, x) * c**x, (x, 0, oo)).doit() \
+        == Piecewise(((c + 1)**n, \
+                     ((n <= -1) & (Abs(c) < 1)) \
+                        | ((n > 0) & (Abs(c) <= 1)) \
+                        | ((n <= 0) & (n > -1) & Ne(c, -1) & (Abs(c) <= 1))), \
+                     (Sum(c**x*binomial(n, x), (x, 0, oo)), True)) # binomial series
+    assert Sum(1/x**n, (x, oo, 0)).doit() \
+        == Piecewise((zeta(n), n > 1), (Sum(x**(-n), (x, oo, 0)), True)) # Euler's zeta function
+
+def test_karr_proposition_2a():
+    # Test Karr, page 309, proposition 2, part a
+    i = Symbol("i", integer=True)
+    u = Symbol("u", integer=True)
+    v = Symbol("v", integer=True)
+
+    def test_the_sum(m, n):
+        # g
+        g = i**3 + 2*i**2 - 3*i
+        # f = Delta g
+        f = simplify(g.subs(i, i+1) - g)
+        # The sum
+        a = m
+        b = n - 1
+        S = Sum(f, (i, a, b)).doit()
+        # Test if Sum_{m <= i < n} f(i) = g(n) - g(m)
+        assert simplify(S - (g.subs(i, n) - g.subs(i, m))) == 0
+
+    # m < n
+    test_the_sum(u,   u+v)
+    # m = n
+    test_the_sum(u,   u  )
+    # m > n
+    test_the_sum(u+v, u  )
+
+
+def test_karr_proposition_2b():
+    # Test Karr, page 309, proposition 2, part b
+    i = Symbol("i", integer=True)
+    u = Symbol("u", integer=True)
+    v = Symbol("v", integer=True)
+    w = Symbol("w", integer=True)
+
+    def test_the_sum(l, n, m):
+        # Summand
+        s = i**3
+        # First sum
+        a = l
+        b = n - 1
+        S1 = Sum(s, (i, a, b)).doit()
+        # Second sum
+        a = l
+        b = m - 1
+        S2 = Sum(s, (i, a, b)).doit()
+        # Third sum
+        a = m
+        b = n - 1
+        S3 = Sum(s, (i, a, b)).doit()
+        # Test if S1 = S2 + S3 as required
+        assert S1 - (S2 + S3) == 0
+
+    # l < m < n
+    test_the_sum(u,     u+v,   u+v+w)
+    # l < m = n
+    test_the_sum(u,     u+v,   u+v  )
+    # l < m > n
+    test_the_sum(u,     u+v+w, v    )
+    # l = m < n
+    test_the_sum(u,     u,     u+v  )
+    # l = m = n
+    test_the_sum(u,     u,     u    )
+    # l = m > n
+    test_the_sum(u+v,   u+v,   u    )
+    # l > m < n
+    test_the_sum(u+v,   u,     u+w  )
+    # l > m = n
+    test_the_sum(u+v,   u,     u    )
+    # l > m > n
+    test_the_sum(u+v+w, u+v,   u    )
+
+
+def test_arithmetic_sums():
+    assert summation(1, (n, a, b)) == b - a + 1
+    assert Sum(S.NaN, (n, a, b)) is S.NaN
+    assert Sum(x, (n, a, a)).doit() == x
+    assert Sum(x, (x, a, a)).doit() == a
+    assert Sum(x, (n, 1, a)).doit() == a*x
+    assert Sum(x, (x, Range(1, 11))).doit() == 55
+    assert Sum(x, (x, Range(1, 11, 2))).doit() == 25
+    assert Sum(x, (x, Range(1, 10, 2))) == Sum(x, (x, Range(9, 0, -2)))
+    lo, hi = 1, 2
+    s1 = Sum(n, (n, lo, hi))
+    s2 = Sum(n, (n, hi, lo))
+    assert s1 != s2
+    assert s1.doit() == 3 and s2.doit() == 0
+    lo, hi = x, x + 1
+    s1 = Sum(n, (n, lo, hi))
+    s2 = Sum(n, (n, hi, lo))
+    assert s1 != s2
+    assert s1.doit() == 2*x + 1 and s2.doit() == 0
+    assert Sum(Integral(x, (x, 1, y)) + x, (x, 1, 2)).doit() == \
+        y**2 + 2
+    assert summation(1, (n, 1, 10)) == 10
+    assert summation(2*n, (n, 0, 10**10)) == 100000000010000000000
+    assert summation(4*n*m, (n, a, 1), (m, 1, d)).expand() == \
+        2*d + 2*d**2 + a*d + a*d**2 - d*a**2 - a**2*d**2
+    assert summation(cos(n), (n, -2, 1)) == cos(-2) + cos(-1) + cos(0) + cos(1)
+    assert summation(cos(n), (n, x, x + 2)) == cos(x) + cos(x + 1) + cos(x + 2)
+    assert isinstance(summation(cos(n), (n, x, x + S.Half)), Sum)
+    assert summation(k, (k, 0, oo)) is oo
+    assert summation(k, (k, Range(1, 11))) == 55
+
+
+def test_polynomial_sums():
+    assert summation(n**2, (n, 3, 8)) == 199
+    assert summation(n, (n, a, b)) == \
+        ((a + b)*(b - a + 1)/2).expand()
+    assert summation(n**2, (n, 1, b)) == \
+        ((2*b**3 + 3*b**2 + b)/6).expand()
+    assert summation(n**3, (n, 1, b)) == \
+        ((b**4 + 2*b**3 + b**2)/4).expand()
+    assert summation(n**6, (n, 1, b)) == \
+        ((6*b**7 + 21*b**6 + 21*b**5 - 7*b**3 + b)/42).expand()
+
+
+def test_geometric_sums():
+    assert summation(pi**n, (n, 0, b)) == (1 - pi**(b + 1)) / (1 - pi)
+    assert summation(2 * 3**n, (n, 0, b)) == 3**(b + 1) - 1
+    assert summation(S.Half**n, (n, 1, oo)) == 1
+    assert summation(2**n, (n, 0, b)) == 2**(b + 1) - 1
+    assert summation(2**n, (n, 1, oo)) is oo
+    assert summation(2**(-n), (n, 1, oo)) == 1
+    assert summation(3**(-n), (n, 4, oo)) == Rational(1, 54)
+    assert summation(2**(-4*n + 3), (n, 1, oo)) == Rational(8, 15)
+    assert summation(2**(n + 1), (n, 1, b)).expand() == 4*(2**b - 1)
+
+    # issue 6664:
+    assert summation(x**n, (n, 0, oo)) == \
+        Piecewise((1/(-x + 1), Abs(x) < 1), (Sum(x**n, (n, 0, oo)), True))
+
+    assert summation(-2**n, (n, 0, oo)) is -oo
+    assert summation(I**n, (n, 0, oo)) == Sum(I**n, (n, 0, oo))
+
+    # issue 6802:
+    assert summation((-1)**(2*x + 2), (x, 0, n)) == n + 1
+    assert summation((-2)**(2*x + 2), (x, 0, n)) == 4*4**(n + 1)/S(3) - Rational(4, 3)
+    assert summation((-1)**x, (x, 0, n)) == -(-1)**(n + 1)/S(2) + S.Half
+    assert summation(y**x, (x, a, b)) == \
+        Piecewise((-a + b + 1, Eq(y, 1)), ((y**a - y**(b + 1))/(-y + 1), True))
+    assert summation((-2)**(y*x + 2), (x, 0, n)) == \
+        4*Piecewise((n + 1, Eq((-2)**y, 1)),
+                    ((-(-2)**(y*(n + 1)) + 1)/(-(-2)**y + 1), True))
+
+    # issue 8251:
+    assert summation((1/(n + 1)**2)*n**2, (n, 0, oo)) is oo
+
+    #issue 9908:
+    assert Sum(1/(n**3 - 1), (n, -oo, -2)).doit() == summation(1/(n**3 - 1), (n, -oo, -2))
+
+    #issue 11642:
+    result = Sum(0.5**n, (n, 1, oo)).doit()
+    assert result == 1.0
+    assert result.is_Float
+
+    result = Sum(0.25**n, (n, 1, oo)).doit()
+    assert result == 1/3.
+    assert result.is_Float
+
+    result = Sum(0.99999**n, (n, 1, oo)).doit()
+    assert result == 99999.0
+    assert result.is_Float
+
+    result = Sum(S.Half**n, (n, 1, oo)).doit()
+    assert result == 1
+    assert not result.is_Float
+
+    result = Sum(Rational(3, 5)**n, (n, 1, oo)).doit()
+    assert result == Rational(3, 2)
+    assert not result.is_Float
+
+    assert Sum(1.0**n, (n, 1, oo)).doit() is oo
+    assert Sum(2.43**n, (n, 1, oo)).doit() is oo
+
+    # Issue 13979
+    i, k, q = symbols('i k q', integer=True)
+    result = summation(
+        exp(-2*I*pi*k*i/n) * exp(2*I*pi*q*i/n) / n, (i, 0, n - 1)
+    )
+    assert result.simplify() == Piecewise(
+            (1, Eq(exp(-2*I*pi*(k - q)/n), 1)), (0, True)
+    )
+
+    #Issue 23491
+    assert Sum(1/(n**2 + 1), (n, 1, oo)).doit() == S(-1)/2 + pi/(2*tanh(pi))
+
+def test_harmonic_sums():
+    assert summation(1/k, (k, 0, n)) == Sum(1/k, (k, 0, n))
+    assert summation(1/k, (k, 1, n)) == harmonic(n)
+    assert summation(n/k, (k, 1, n)) == n*harmonic(n)
+    assert summation(1/k, (k, 5, n)) == harmonic(n) - harmonic(4)
+
+
+def test_composite_sums():
+    f = S.Half*(7 - 6*n + Rational(1, 7)*n**3)
+    s = summation(f, (n, a, b))
+    assert not isinstance(s, Sum)
+    A = 0
+    for i in range(-3, 5):
+        A += f.subs(n, i)
+    B = s.subs(a, -3).subs(b, 4)
+    assert A == B
+
+
+def test_hypergeometric_sums():
+    assert summation(
+        binomial(2*k, k)/4**k, (k, 0, n)) == (1 + 2*n)*binomial(2*n, n)/4**n
+    assert summation(binomial(2*k, k)/5**k, (k, -oo, oo)) == sqrt(5)
+
+
+def test_other_sums():
+    f = m**2 + m*exp(m)
+    g = 3*exp(Rational(3, 2))/2 + exp(S.Half)/2 - exp(Rational(-1, 2))/2 - 3*exp(Rational(-3, 2))/2 + 5
+
+    assert summation(f, (m, Rational(-3, 2), Rational(3, 2))) == g
+    assert summation(f, (m, -1.5, 1.5)).evalf().epsilon_eq(g.evalf(), 1e-10)
+
+fac = factorial
+
+
+def NS(e, n=15, **options):
+    return str(sympify(e).evalf(n, **options))
+
+
+def test_evalf_fast_series():
+    # Euler transformed series for sqrt(1+x)
+    assert NS(Sum(
+        fac(2*n + 1)/fac(n)**2/2**(3*n + 1), (n, 0, oo)), 100) == NS(sqrt(2), 100)
+
+    # Some series for exp(1)
+    estr = NS(E, 100)
+    assert NS(Sum(1/fac(n), (n, 0, oo)), 100) == estr
+    assert NS(1/Sum((1 - 2*n)/fac(2*n), (n, 0, oo)), 100) == estr
+    assert NS(Sum((2*n + 1)/fac(2*n), (n, 0, oo)), 100) == estr
+    assert NS(Sum((4*n + 3)/2**(2*n + 1)/fac(2*n + 1), (n, 0, oo))**2, 100) == estr
+
+    pistr = NS(pi, 100)
+    # Ramanujan series for pi
+    assert NS(9801/sqrt(8)/Sum(fac(
+        4*n)*(1103 + 26390*n)/fac(n)**4/396**(4*n), (n, 0, oo)), 100) == pistr
+    assert NS(1/Sum(
+        binomial(2*n, n)**3 * (42*n + 5)/2**(12*n + 4), (n, 0, oo)), 100) == pistr
+    # Machin's formula for pi
+    assert NS(16*Sum((-1)**n/(2*n + 1)/5**(2*n + 1), (n, 0, oo)) -
+        4*Sum((-1)**n/(2*n + 1)/239**(2*n + 1), (n, 0, oo)), 100) == pistr
+
+    # Apery's constant
+    astr = NS(zeta(3), 100)
+    P = 126392*n**5 + 412708*n**4 + 531578*n**3 + 336367*n**2 + 104000* \
+        n + 12463
+    assert NS(Sum((-1)**n * P / 24 * (fac(2*n + 1)*fac(2*n)*fac(
+        n))**3 / fac(3*n + 2) / fac(4*n + 3)**3, (n, 0, oo)), 100) == astr
+    assert NS(Sum((-1)**n * (205*n**2 + 250*n + 77)/64 * fac(n)**10 /
+              fac(2*n + 1)**5, (n, 0, oo)), 100) == astr
+
+
+def test_evalf_fast_series_issue_4021():
+    # Catalan's constant
+    assert NS(Sum((-1)**(n - 1)*2**(8*n)*(40*n**2 - 24*n + 3)*fac(2*n)**3*
+        fac(n)**2/n**3/(2*n - 1)/fac(4*n)**2, (n, 1, oo))/64, 100) == \
+        NS(Catalan, 100)
+    astr = NS(zeta(3), 100)
+    assert NS(5*Sum(
+        (-1)**(n - 1)*fac(n)**2 / n**3 / fac(2*n), (n, 1, oo))/2, 100) == astr
+    assert NS(Sum((-1)**(n - 1)*(56*n**2 - 32*n + 5) / (2*n - 1)**2 * fac(n - 1)
+              **3 / fac(3*n), (n, 1, oo))/4, 100) == astr
+
+
+def test_evalf_slow_series():
+    assert NS(Sum((-1)**n / n, (n, 1, oo)), 15) == NS(-log(2), 15)
+    assert NS(Sum((-1)**n / n, (n, 1, oo)), 50) == NS(-log(2), 50)
+    assert NS(Sum(1/n**2, (n, 1, oo)), 15) == NS(pi**2/6, 15)
+    assert NS(Sum(1/n**2, (n, 1, oo)), 100) == NS(pi**2/6, 100)
+    assert NS(Sum(1/n**2, (n, 1, oo)), 500) == NS(pi**2/6, 500)
+    assert NS(Sum((-1)**n / (2*n + 1)**3, (n, 0, oo)), 15) == NS(pi**3/32, 15)
+    assert NS(Sum((-1)**n / (2*n + 1)**3, (n, 0, oo)), 50) == NS(pi**3/32, 50)
+
+
+def test_evalf_oo_to_oo():
+    # There used to be an error in certain cases
+    # Does not evaluate, but at least do not throw an error
+    # Evaluates symbolically to 0, which is not correct
+    assert Sum(1/(n**2+1), (n, -oo, oo)).evalf() == Sum(1/(n**2+1), (n, -oo, oo))
+    # This evaluates if from 1 to oo and symbolically
+    assert Sum(1/(factorial(abs(n))), (n, -oo, -1)).evalf() == Sum(1/(factorial(abs(n))), (n, -oo, -1))
+
+
+def test_euler_maclaurin():
+    # Exact polynomial sums with E-M
+    def check_exact(f, a, b, m, n):
+        A = Sum(f, (k, a, b))
+        s, e = A.euler_maclaurin(m, n)
+        assert (e == 0) and (s.expand() == A.doit())
+    check_exact(k**4, a, b, 0, 2)
+    check_exact(k**4 + 2*k, a, b, 1, 2)
+    check_exact(k**4 + k**2, a, b, 1, 5)
+    check_exact(k**5, 2, 6, 1, 2)
+    check_exact(k**5, 2, 6, 1, 3)
+    assert Sum(x-1, (x, 0, 2)).euler_maclaurin(m=30, n=30, eps=2**-15) == (0, 0)
+    # Not exact
+    assert Sum(k**6, (k, a, b)).euler_maclaurin(0, 2)[1] != 0
+    # Numerical test
+    for mi, ni in [(2, 4), (2, 20), (10, 20), (18, 20)]:
+        A = Sum(1/k**3, (k, 1, oo))
+        s, e = A.euler_maclaurin(mi, ni)
+        assert abs((s - zeta(3)).evalf()) < e.evalf()
+
+    raises(ValueError, lambda: Sum(1, (x, 0, 1), (k, 0, 1)).euler_maclaurin())
+
+
+@slow
+def test_evalf_euler_maclaurin():
+    assert NS(Sum(1/k**k, (k, 1, oo)), 15) == '1.29128599706266'
+    assert NS(Sum(1/k**k, (k, 1, oo)),
+              50) == '1.2912859970626635404072825905956005414986193682745'
+    assert NS(Sum(1/k - log(1 + 1/k), (k, 1, oo)), 15) == NS(EulerGamma, 15)
+    assert NS(Sum(1/k - log(1 + 1/k), (k, 1, oo)), 50) == NS(EulerGamma, 50)
+    assert NS(Sum(log(k)/k**2, (k, 1, oo)), 15) == '0.937548254315844'
+    assert NS(Sum(log(k)/k**2, (k, 1, oo)),
+              50) == '0.93754825431584375370257409456786497789786028861483'
+    assert NS(Sum(1/k, (k, 1000000, 2000000)), 15) == '0.693147930560008'
+    assert NS(Sum(1/k, (k, 1000000, 2000000)),
+              50) == '0.69314793056000780941723211364567656807940638436025'
+
+
+def test_evalf_symbolic():
+    # issue 6328
+    expr = Sum(f(x), (x, 1, 3)) + Sum(g(x), (x, 1, 3))
+    assert expr.evalf() == expr
+
+
+def test_evalf_issue_3273():
+    assert Sum(0, (k, 1, oo)).evalf() == 0
+
+
+def test_simple_products():
+    assert Product(S.NaN, (x, 1, 3)) is S.NaN
+    assert product(S.NaN, (x, 1, 3)) is S.NaN
+    assert Product(x, (n, a, a)).doit() == x
+    assert Product(x, (x, a, a)).doit() == a
+    assert Product(x, (y, 1, a)).doit() == x**a
+
+    lo, hi = 1, 2
+    s1 = Product(n, (n, lo, hi))
+    s2 = Product(n, (n, hi, lo))
+    assert s1 != s2
+    # This IS correct according to Karr product convention
+    assert s1.doit() == 2
+    assert s2.doit() == 1
+
+    lo, hi = x, x + 1
+    s1 = Product(n, (n, lo, hi))
+    s2 = Product(n, (n, hi, lo))
+    s3 = 1 / Product(n, (n, hi + 1, lo - 1))
+    assert s1 != s2
+    # This IS correct according to Karr product convention
+    assert s1.doit() == x*(x + 1)
+    assert s2.doit() == 1
+    assert s3.doit() == x*(x + 1)
+
+    assert Product(Integral(2*x, (x, 1, y)) + 2*x, (x, 1, 2)).doit() == \
+        (y**2 + 1)*(y**2 + 3)
+    assert product(2, (n, a, b)) == 2**(b - a + 1)
+    assert product(n, (n, 1, b)) == factorial(b)
+    assert product(n**3, (n, 1, b)) == factorial(b)**3
+    assert product(3**(2 + n), (n, a, b)) \
+        == 3**(2*(1 - a + b) + b/2 + (b**2)/2 + a/2 - (a**2)/2)
+    assert product(cos(n), (n, 3, 5)) == cos(3)*cos(4)*cos(5)
+    assert product(cos(n), (n, x, x + 2)) == cos(x)*cos(x + 1)*cos(x + 2)
+    assert isinstance(product(cos(n), (n, x, x + S.Half)), Product)
+    # If Product managed to evaluate this one, it most likely got it wrong!
+    assert isinstance(Product(n**n, (n, 1, b)), Product)
+
+
+def test_rational_products():
+    assert combsimp(product(1 + 1/n, (n, a, b))) == (1 + b)/a
+    assert combsimp(product(n + 1, (n, a, b))) == gamma(2 + b)/gamma(1 + a)
+    assert combsimp(product((n + 1)/(n - 1), (n, a, b))) == b*(1 + b)/(a*(a - 1))
+    assert combsimp(product(n/(n + 1)/(n + 2), (n, a, b))) == \
+        a*gamma(a + 2)/(b + 1)/gamma(b + 3)
+    assert combsimp(product(n*(n + 1)/(n - 1)/(n - 2), (n, a, b))) == \
+        b**2*(b - 1)*(1 + b)/(a - 1)**2/(a*(a - 2))
+
+
+def test_wallis_product():
+    # Wallis product, given in two different forms to ensure that Product
+    # can factor simple rational expressions
+    A = Product(4*n**2 / (4*n**2 - 1), (n, 1, b))
+    B = Product((2*n)*(2*n)/(2*n - 1)/(2*n + 1), (n, 1, b))
+    R = pi*gamma(b + 1)**2/(2*gamma(b + S.Half)*gamma(b + Rational(3, 2)))
+    assert simplify(A.doit()) == R
+    assert simplify(B.doit()) == R
+    # This one should eventually also be doable (Euler's product formula for sin)
+    # assert Product(1+x/n**2, (n, 1, b)) == ...
+
+
+def test_telescopic_sums():
+    #checks also input 2 of comment 1 issue 4127
+    assert Sum(1/k - 1/(k + 1), (k, 1, n)).doit() == 1 - 1/(1 + n)
+    assert Sum(
+        f(k) - f(k + 2), (k, m, n)).doit() == -f(1 + n) - f(2 + n) + f(m) + f(1 + m)
+    assert Sum(cos(k) - cos(k + 3), (k, 1, n)).doit() == -cos(1 + n) - \
+        cos(2 + n) - cos(3 + n) + cos(1) + cos(2) + cos(3)
+
+    # dummy variable shouldn't matter
+    assert telescopic(1/m, -m/(1 + m), (m, n - 1, n)) == \
+        telescopic(1/k, -k/(1 + k), (k, n - 1, n))
+
+    assert Sum(1/x/(x - 1), (x, a, b)).doit() == 1/(a - 1) - 1/b
+    eq = 1/((5*n + 2)*(5*(n + 1) + 2))
+    assert Sum(eq, (n, 0, oo)).doit() == S(1)/10
+    nz = symbols('nz', nonzero=True)
+    v = Sum(eq.subs(5, nz), (n, 0, oo)).doit()
+    assert v.subs(nz, 5).simplify() == S(1)/10
+    # check that apart is being used in non-symbolic case
+    s = Sum(eq, (n, 0, k)).doit()
+    v = Sum(eq, (n, 0, 10**100)).doit()
+    assert v == s.subs(k, 10**100)
+
+
+def test_sum_reconstruct():
+    s = Sum(n**2, (n, -1, 1))
+    assert s == Sum(*s.args)
+    raises(ValueError, lambda: Sum(x, x))
+    raises(ValueError, lambda: Sum(x, (x, 1)))
+
+
+def test_limit_subs():
+    for F in (Sum, Product, Integral):
+        assert F(a*exp(a), (a, -2, 2)) == F(a*exp(a), (a, -b, b)).subs(b, 2)
+        assert F(a, (a, F(b, (b, 1, 2)), 4)).subs(F(b, (b, 1, 2)), c) == \
+            F(a, (a, c, 4))
+        assert F(x, (x, 1, x + y)).subs(x, 1) == F(x, (x, 1, y + 1))
+
+
+def test_function_subs():
+    S = Sum(x*f(y),(x,0,oo),(y,0,oo))
+    assert S.subs(f(y),y) == Sum(x*y,(x,0,oo),(y,0,oo))
+    assert S.subs(f(x),x) == S
+    raises(ValueError, lambda: S.subs(f(y),x+y) )
+    S = Sum(x*log(y),(x,0,oo),(y,0,oo))
+    assert S.subs(log(y),y) == S
+    S = Sum(x*f(y),(x,0,oo),(y,0,oo))
+    assert S.subs(f(y),y) == Sum(x*y,(x,0,oo),(y,0,oo))
+
+
+def test_equality():
+    # if this fails remove special handling below
+    raises(ValueError, lambda: Sum(x, x))
+    r = symbols('x', real=True)
+    for F in (Sum, Product, Integral):
+        try:
+            assert F(x, x) != F(y, y)
+            assert F(x, (x, 1, 2)) != F(x, x)
+            assert F(x, (x, x)) != F(x, x)  # or else they print the same
+            assert F(1, x) != F(1, y)
+        except ValueError:
+            pass
+        assert F(a, (x, 1, 2)) != F(a, (x, 1, 3))  # diff limit
+        assert F(a, (x, 1, x)) != F(a, (y, 1, y))
+        assert F(a, (x, 1, 2)) != F(b, (x, 1, 2))  # diff expression
+        assert F(x, (x, 1, 2)) != F(r, (r, 1, 2))  # diff assumptions
+        assert F(1, (x, 1, x)) != F(1, (y, 1, x))  # only dummy is diff
+        assert F(1, (x, 1, x)).dummy_eq(F(1, (y, 1, x)))
+
+    # issue 5265
+    assert Sum(x, (x, 1, x)).subs(x, a) == Sum(x, (x, 1, a))
+
+
+def test_Sum_doit():
+    assert Sum(n*Integral(a**2), (n, 0, 2)).doit() == a**3
+    assert Sum(n*Integral(a**2), (n, 0, 2)).doit(deep=False) == \
+        3*Integral(a**2)
+    assert summation(n*Integral(a**2), (n, 0, 2)) == 3*Integral(a**2)
+
+    # test nested sum evaluation
+    s = Sum( Sum( Sum(2,(z,1,n+1)), (y,x+1,n)), (x,1,n))
+    assert 0 == (s.doit() - n*(n+1)*(n-1)).factor()
+
+    # Integer assumes finite
+    assert Sum(KroneckerDelta(x, y), (x, -oo, oo)).doit() == Piecewise((1, And(-oo < y, y < oo)), (0, True))
+    assert Sum(KroneckerDelta(m, n), (m, -oo, oo)).doit() == 1
+    assert Sum(m*KroneckerDelta(x, y), (x, -oo, oo)).doit() == Piecewise((m, And(-oo < y, y < oo)), (0, True))
+    assert Sum(x*KroneckerDelta(m, n), (m, -oo, oo)).doit() == x
+    assert Sum(Sum(KroneckerDelta(m, n), (m, 1, 3)), (n, 1, 3)).doit() == 3
+    assert Sum(Sum(KroneckerDelta(k, m), (m, 1, 3)), (n, 1, 3)).doit() == \
+           3 * Piecewise((1, And(1 <= k, k <= 3)), (0, True))
+    assert Sum(f(n) * Sum(KroneckerDelta(m, n), (m, 0, oo)), (n, 1, 3)).doit() == \
+           f(1) + f(2) + f(3)
+    assert Sum(f(n) * Sum(KroneckerDelta(m, n), (m, 0, oo)), (n, 1, oo)).doit() == \
+           Sum(f(n), (n, 1, oo))
+
+    # issue 2597
+    nmax = symbols('N', integer=True, positive=True)
+    pw = Piecewise((1, And(1 <= n, n <= nmax)), (0, True))
+    assert Sum(pw, (n, 1, nmax)).doit() == Sum(Piecewise((1, nmax >= n),
+                    (0, True)), (n, 1, nmax))
+
+    q, s = symbols('q, s')
+    assert summation(1/n**(2*s), (n, 1, oo)) == Piecewise((zeta(2*s), 2*re(s) > 1),
+        (Sum(n**(-2*s), (n, 1, oo)), True))
+    assert summation(1/(n+1)**s, (n, 0, oo)) == Piecewise((zeta(s), re(s) > 1),
+        (Sum((n + 1)**(-s), (n, 0, oo)), True))
+    assert summation(1/(n+q)**s, (n, 0, oo)) == Piecewise(
+        (zeta(s, q), And(~Contains(-q, S.Naturals0), re(s) > 1)),
+        (Sum((n + q)**(-s), (n, 0, oo)), True))
+    assert summation(1/(n+q)**s, (n, q, oo)) == Piecewise(
+        (zeta(s, 2*q), And(~Contains(-2*q, S.Naturals0), re(s) > 1)),
+        (Sum((n + q)**(-s), (n, q, oo)), True))
+    assert summation(1/n**2, (n, 1, oo)) == zeta(2)
+    assert summation(1/n**s, (n, 0, oo)) == Sum(n**(-s), (n, 0, oo))
+    assert summation(1/(n+1)**(2+I), (n, 0, oo)) == zeta(2+I)
+    t = symbols('t', real=True, positive=True)
+    assert summation(1/(n+I)**(t+1), (n, 0, oo)) == zeta(t+1, I)
+
+
+def test_Product_doit():
+    assert Product(n*Integral(a**2), (n, 1, 3)).doit() == 2 * a**9 / 9
+    assert Product(n*Integral(a**2), (n, 1, 3)).doit(deep=False) == \
+        6*Integral(a**2)**3
+    assert product(n*Integral(a**2), (n, 1, 3)) == 6*Integral(a**2)**3
+
+
+def test_Sum_interface():
+    assert isinstance(Sum(0, (n, 0, 2)), Sum)
+    assert Sum(nan, (n, 0, 2)) is nan
+    assert Sum(nan, (n, 0, oo)) is nan
+    assert Sum(0, (n, 0, 2)).doit() == 0
+    assert isinstance(Sum(0, (n, 0, oo)), Sum)
+    assert Sum(0, (n, 0, oo)).doit() == 0
+    raises(ValueError, lambda: Sum(1))
+    raises(ValueError, lambda: summation(1))
+
+
+def test_diff():
+    assert Sum(x, (x, 1, 2)).diff(x) == 0
+    assert Sum(x*y, (x, 1, 2)).diff(x) == 0
+    assert Sum(x*y, (y, 1, 2)).diff(x) == Sum(y, (y, 1, 2))
+    e = Sum(x*y, (x, 1, a))
+    assert e.diff(a) == Derivative(e, a)
+    assert Sum(x*y, (x, 1, 3), (a, 2, 5)).diff(y).doit() == \
+        Sum(x*y, (x, 1, 3), (a, 2, 5)).doit().diff(y) == 24
+    assert Sum(x, (x, 1, 2)).diff(y) == 0
+
+
+def test_hypersum():
+    assert simplify(summation(x**n/fac(n), (n, 1, oo))) == -1 + exp(x)
+    assert summation((-1)**n * x**(2*n) / fac(2*n), (n, 0, oo)) == cos(x)
+    assert simplify(summation((-1)**n*x**(2*n + 1) /
+        factorial(2*n + 1), (n, 3, oo))) == -x + sin(x) + x**3/6 - x**5/120
+
+    assert summation(1/(n + 2)**3, (n, 1, oo)) == Rational(-9, 8) + zeta(3)
+    assert summation(1/n**4, (n, 1, oo)) == pi**4/90
+
+    s = summation(x**n*n, (n, -oo, 0))
+    assert s.is_Piecewise
+    assert s.args[0].args[0] == -1/(x*(1 - 1/x)**2)
+    assert s.args[0].args[1] == (abs(1/x) < 1)
+
+    m = Symbol('n', integer=True, positive=True)
+    assert summation(binomial(m, k), (k, 0, m)) == 2**m
+
+
+def test_issue_4170():
+    assert summation(1/factorial(k), (k, 0, oo)) == E
+
+
+def test_is_commutative():
+    from sympy.physics.secondquant import NO, F, Fd
+    m = Symbol('m', commutative=False)
+    for f in (Sum, Product, Integral):
+        assert f(z, (z, 1, 1)).is_commutative is True
+        assert f(z*y, (z, 1, 6)).is_commutative is True
+        assert f(m*x, (x, 1, 2)).is_commutative is False
+
+        assert f(NO(Fd(x)*F(y))*z, (z, 1, 2)).is_commutative is False
+
+
+def test_is_zero():
+    for func in [Sum, Product]:
+        assert func(0, (x, 1, 1)).is_zero is True
+        assert func(x, (x, 1, 1)).is_zero is None
+
+    assert Sum(0, (x, 1, 0)).is_zero is True
+    assert Product(0, (x, 1, 0)).is_zero is False
+
+
+def test_is_number():
+    # is number should not rely on evaluation or assumptions,
+    # it should be equivalent to `not foo.free_symbols`
+    assert Sum(1, (x, 1, 1)).is_number is True
+    assert Sum(1, (x, 1, x)).is_number is False
+    assert Sum(0, (x, y, z)).is_number is False
+    assert Sum(x, (y, 1, 2)).is_number is False
+    assert Sum(x, (y, 1, 1)).is_number is False
+    assert Sum(x, (x, 1, 2)).is_number is True
+    assert Sum(x*y, (x, 1, 2), (y, 1, 3)).is_number is True
+
+    assert Product(2, (x, 1, 1)).is_number is True
+    assert Product(2, (x, 1, y)).is_number is False
+    assert Product(0, (x, y, z)).is_number is False
+    assert Product(1, (x, y, z)).is_number is False
+    assert Product(x, (y, 1, x)).is_number is False
+    assert Product(x, (y, 1, 2)).is_number is False
+    assert Product(x, (y, 1, 1)).is_number is False
+    assert Product(x, (x, 1, 2)).is_number is True
+
+
+def test_free_symbols():
+    for func in [Sum, Product]:
+        assert func(1, (x, 1, 2)).free_symbols == set()
+        assert func(0, (x, 1, y)).free_symbols == {y}
+        assert func(2, (x, 1, y)).free_symbols == {y}
+        assert func(x, (x, 1, 2)).free_symbols == set()
+        assert func(x, (x, 1, y)).free_symbols == {y}
+        assert func(x, (y, 1, y)).free_symbols == {x, y}
+        assert func(x, (y, 1, 2)).free_symbols == {x}
+        assert func(x, (y, 1, 1)).free_symbols == {x}
+        assert func(x, (y, 1, z)).free_symbols == {x, z}
+        assert func(x, (x, 1, y), (y, 1, 2)).free_symbols == set()
+        assert func(x, (x, 1, y), (y, 1, z)).free_symbols == {z}
+        assert func(x, (x, 1, y), (y, 1, y)).free_symbols == {y}
+        assert func(x, (y, 1, y), (y, 1, z)).free_symbols == {x, z}
+    assert Sum(1, (x, 1, y)).free_symbols == {y}
+    # free_symbols answers whether the object *as written* has free symbols,
+    # not whether the evaluated expression has free symbols
+    assert Product(1, (x, 1, y)).free_symbols == {y}
+    # don't count free symbols that are not independent of integration
+    # variable(s)
+    assert func(f(x), (f(x), 1, 2)).free_symbols == set()
+    assert func(f(x), (f(x), 1, x)).free_symbols == {x}
+    assert func(f(x), (f(x), 1, y)).free_symbols == {y}
+    assert func(f(x), (z, 1, y)).free_symbols == {x, y}
+
+
+def test_conjugate_transpose():
+    A, B = symbols("A B", commutative=False)
+    p = Sum(A*B**n, (n, 1, 3))
+    assert p.adjoint().doit() == p.doit().adjoint()
+    assert p.conjugate().doit() == p.doit().conjugate()
+    assert p.transpose().doit() == p.doit().transpose()
+
+    p = Sum(B**n*A, (n, 1, 3))
+    assert p.adjoint().doit() == p.doit().adjoint()
+    assert p.conjugate().doit() == p.doit().conjugate()
+    assert p.transpose().doit() == p.doit().transpose()
+
+
+def test_noncommutativity_honoured():
+    A, B = symbols("A B", commutative=False)
+    M = symbols('M', integer=True, positive=True)
+    p = Sum(A*B**n, (n, 1, M))
+    assert p.doit() == A*Piecewise((M, Eq(B, 1)),
+                                   ((B - B**(M + 1))*(1 - B)**(-1), True))
+
+    p = Sum(B**n*A, (n, 1, M))
+    assert p.doit() == Piecewise((M, Eq(B, 1)),
+                                 ((B - B**(M + 1))*(1 - B)**(-1), True))*A
+
+    p = Sum(B**n*A*B**n, (n, 1, M))
+    assert p.doit() == p
+
+
+def test_issue_4171():
+    assert summation(factorial(2*k + 1)/factorial(2*k), (k, 0, oo)) is oo
+    assert summation(2*k + 1, (k, 0, oo)) is oo
+
+
+def test_issue_6273():
+    assert Sum(x, (x, 1, n)).n(2, subs={n: 1}) == Float(1, 2)
+
+
+def test_issue_6274():
+    assert Sum(x, (x, 1, 0)).doit() == 0
+    assert NS(Sum(x, (x, 1, 0))) == '0'
+    assert Sum(n, (n, 10, 5)).doit() == -30
+    assert NS(Sum(n, (n, 10, 5))) == '-30.0000000000000'
+
+
+def test_simplify_sum():
+    y, t, v = symbols('y, t, v')
+
+    _simplify = lambda e: simplify(e, doit=False)
+    assert _simplify(Sum(x*y, (x, n, m), (y, a, k)) + \
+        Sum(y, (x, n, m), (y, a, k))) == Sum(y * (x + 1), (x, n, m), (y, a, k))
+    assert _simplify(Sum(x, (x, n, m)) + Sum(x, (x, m + 1, a))) == \
+        Sum(x, (x, n, a))
+    assert _simplify(Sum(x, (x, k + 1, a)) + Sum(x, (x, n, k))) == \
+        Sum(x, (x, n, a))
+    assert _simplify(Sum(x, (x, k + 1, a)) + Sum(x + 1, (x, n, k))) == \
+        Sum(x, (x, n, a)) + Sum(1, (x, n, k))
+    assert _simplify(Sum(x, (x, 0, 3)) * 3 + 3 * Sum(x, (x, 4, 6)) + \
+        4 * Sum(z, (z, 0, 1))) == 4*Sum(z, (z, 0, 1)) + 3*Sum(x, (x, 0, 6))
+    assert _simplify(3*Sum(x**2, (x, a, b)) + Sum(x, (x, a, b))) == \
+        Sum(x*(3*x + 1), (x, a, b))
+    assert _simplify(Sum(x**3, (x, n, k)) * 3 + 3 * Sum(x, (x, n, k)) + \
+        4 * y * Sum(z, (z, n, k))) + 1 == \
+            4*y*Sum(z, (z, n, k)) + 3*Sum(x**3 + x, (x, n, k)) + 1
+    assert _simplify(Sum(x, (x, a, b)) + 1 + Sum(x, (x, b + 1, c))) == \
+        1 + Sum(x, (x, a, c))
+    assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + \
+        Sum(x, (t, b+1, c))) == x * Sum(1, (t, a, c)) + y * Sum(1, (t, a, b))
+    assert _simplify(Sum(x, (t, a, b)) + Sum(x, (t, b+1, c)) + \
+        Sum(y, (t, a, b))) == x * Sum(1, (t, a, c)) + y * Sum(1, (t, a, b))
+    assert _simplify(Sum(x, (t, a, b)) + 2 * Sum(x, (t, b+1, c))) == \
+        _simplify(Sum(x, (t, a, b)) + Sum(x, (t, b+1, c)) + Sum(x, (t, b+1, c)))
+    assert _simplify(Sum(x, (x, a, b))*Sum(x**2, (x, a, b))) == \
+        Sum(x, (x, a, b)) * Sum(x**2, (x, a, b))
+    assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + Sum(z, (t, a, b))) \
+        == (x + y + z) * Sum(1, (t, a, b))          # issue 8596
+    assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + Sum(z, (t, a, b)) + \
+        Sum(v, (t, a, b))) == (x + y + z + v) * Sum(1, (t, a, b))  # issue 8596
+    assert _simplify(Sum(x * y, (x, a, b)) / (3 * y)) == \
+        (Sum(x, (x, a, b)) / 3)
+    assert _simplify(Sum(f(x) * y * z, (x, a, b)) / (y * z)) \
+        == Sum(f(x), (x, a, b))
+    assert _simplify(Sum(c * x, (x, a, b)) - c * Sum(x, (x, a, b))) == 0
+    assert _simplify(c * (Sum(x, (x, a, b))  + y)) == c * (y + Sum(x, (x, a, b)))
+    assert _simplify(c * (Sum(x, (x, a, b)) + y * Sum(x, (x, a, b)))) == \
+        c * (y + 1) * Sum(x, (x, a, b))
+    assert _simplify(Sum(Sum(c * x, (x, a, b)), (y, a, b))) == \
+                c * Sum(x, (x, a, b), (y, a, b))
+    assert _simplify(Sum((3 + y) * Sum(c * x, (x, a, b)), (y, a, b))) == \
+                c * Sum((3 + y), (y, a, b)) * Sum(x, (x, a, b))
+    assert _simplify(Sum((3 + t) * Sum(c * t, (x, a, b)), (y, a, b))) == \
+                c*t*(t + 3)*Sum(1, (x, a, b))*Sum(1, (y, a, b))
+    assert _simplify(Sum(Sum(d * t, (x, a, b - 1)) + \
+                Sum(d * t, (x, b, c)), (t, a, b))) == \
+                    d * Sum(1, (x, a, c)) * Sum(t, (t, a, b))
+    assert _simplify(Sum(sin(t)**2 + cos(t)**2 + 1, (t, a, b))) == \
+        2 * Sum(1, (t, a, b))
+
+
+def test_change_index():
+    b, v, w = symbols('b, v, w', integer = True)
+
+    assert Sum(x, (x, a, b)).change_index(x, x + 1, y) == \
+        Sum(y - 1, (y, a + 1, b + 1))
+    assert Sum(x**2, (x, a, b)).change_index( x, x - 1) == \
+        Sum((x+1)**2, (x, a - 1, b - 1))
+    assert Sum(x**2, (x, a, b)).change_index( x, -x, y) == \
+        Sum((-y)**2, (y, -b, -a))
+    assert Sum(x, (x, a, b)).change_index( x, -x - 1) == \
+        Sum(-x - 1, (x, -b - 1, -a - 1))
+    assert Sum(x*y, (x, a, b), (y, c, d)).change_index( x, x - 1, z) == \
+        Sum((z + 1)*y, (z, a - 1, b - 1), (y, c, d))
+    assert Sum(x, (x, a, b)).change_index( x, x + v) == \
+        Sum(-v + x, (x, a + v, b + v))
+    assert Sum(x, (x, a, b)).change_index( x, -x - v) == \
+        Sum(-v - x, (x, -b - v, -a - v))
+    assert Sum(x, (x, a, b)).change_index(x, w*x, v) == \
+        Sum(v/w, (v, b*w, a*w))
+    raises(ValueError, lambda: Sum(x, (x, a, b)).change_index(x, 2*x))
+
+
+def test_reorder():
+    b, y, c, d, z = symbols('b, y, c, d, z', integer = True)
+
+    assert Sum(x*y, (x, a, b), (y, c, d)).reorder((0, 1)) == \
+        Sum(x*y, (y, c, d), (x, a, b))
+    assert Sum(x, (x, a, b), (x, c, d)).reorder((0, 1)) == \
+        Sum(x, (x, c, d), (x, a, b))
+    assert Sum(x*y + z, (x, a, b), (z, m, n), (y, c, d)).reorder(\
+        (2, 0), (0, 1)) == Sum(x*y + z, (z, m, n), (y, c, d), (x, a, b))
+    assert Sum(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\
+        (0, 1), (1, 2), (0, 2)) == Sum(x*y*z, (x, a, b), (z, m, n), (y, c, d))
+    assert Sum(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\
+        (x, y), (y, z), (x, z)) == Sum(x*y*z, (x, a, b), (z, m, n), (y, c, d))
+    assert Sum(x*y, (x, a, b), (y, c, d)).reorder((x, 1)) == \
+        Sum(x*y, (y, c, d), (x, a, b))
+    assert Sum(x*y, (x, a, b), (y, c, d)).reorder((y, x)) == \
+        Sum(x*y, (y, c, d), (x, a, b))
+
+
+def test_reverse_order():
+    assert Sum(x, (x, 0, 3)).reverse_order(0) == Sum(-x, (x, 4, -1))
+    assert Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(0, 1) == \
+           Sum(x*y, (x, 6, 0), (y, 7, -1))
+    assert Sum(x, (x, 1, 2)).reverse_order(0) == Sum(-x, (x, 3, 0))
+    assert Sum(x, (x, 1, 3)).reverse_order(0) == Sum(-x, (x, 4, 0))
+    assert Sum(x, (x, 1, a)).reverse_order(0) == Sum(-x, (x, a + 1, 0))
+    assert Sum(x, (x, a, 5)).reverse_order(0) == Sum(-x, (x, 6, a - 1))
+    assert Sum(x, (x, a + 1, a + 5)).reverse_order(0) == \
+                         Sum(-x, (x, a + 6, a))
+    assert Sum(x, (x, a + 1, a + 2)).reverse_order(0) == \
+           Sum(-x, (x, a + 3, a))
+    assert Sum(x, (x, a + 1, a + 1)).reverse_order(0) == \
+           Sum(-x, (x, a + 2, a))
+    assert Sum(x, (x, a, b)).reverse_order(0) == Sum(-x, (x, b + 1, a - 1))
+    assert Sum(x, (x, a, b)).reverse_order(x) == Sum(-x, (x, b + 1, a - 1))
+    assert Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1) == \
+        Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
+    assert Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x) == \
+        Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
+
+
+def test_issue_7097():
+    assert sum(x**n/n for n in range(1, 401)) == summation(x**n/n, (n, 1, 400))
+
+
+def test_factor_expand_subs():
+    # test factoring
+    assert Sum(4 * x, (x, 1, y)).factor() == 4 * Sum(x, (x, 1, y))
+    assert Sum(x * a, (x, 1, y)).factor() == a * Sum(x, (x, 1, y))
+    assert Sum(4 * x * a, (x, 1, y)).factor() == 4 * a * Sum(x, (x, 1, y))
+    assert Sum(4 * x * y, (x, 1, y)).factor() == 4 * y * Sum(x, (x, 1, y))
+
+    # test expand
+    _x = Symbol('x', zero=False)
+    assert Sum(x+1,(x,1,y)).expand() == Sum(x,(x,1,y)) + Sum(1,(x,1,y))
+    assert Sum(x+a*x**2,(x,1,y)).expand() == Sum(x,(x,1,y)) + Sum(a*x**2,(x,1,y))
+    assert Sum(_x**(n + 1)*(n + 1), (n, -1, oo)).expand() \
+        == Sum(n*_x*_x**n + _x*_x**n, (n, -1, oo))
+    assert Sum(x**(n + 1)*(n + 1), (n, -1, oo)).expand(power_exp=False) \
+        == Sum(n*x**(n + 1) + x**(n + 1), (n, -1, oo))
+    assert Sum(x**(n + 1)*(n + 1), (n, -1, oo)).expand(force=True) \
+           == Sum(x*x**n, (n, -1, oo)) + Sum(n*x*x**n, (n, -1, oo))
+    assert Sum(a*n+a*n**2,(n,0,4)).expand() \
+        == Sum(a*n,(n,0,4)) + Sum(a*n**2,(n,0,4))
+    assert Sum(_x**a*_x**n,(x,0,3)) \
+        == Sum(_x**(a+n),(x,0,3)).expand(power_exp=True)
+    _a, _n = symbols('a n', positive=True)
+    assert Sum(x**(_a+_n),(x,0,3)).expand(power_exp=True) \
+        == Sum(x**_a*x**_n, (x, 0, 3))
+    assert Sum(x**(_a-_n),(x,0,3)).expand(power_exp=True) \
+        == Sum(x**(_a-_n),(x,0,3)).expand(power_exp=False)
+
+    # test subs
+    assert Sum(1/(1+a*x**2),(x,0,3)).subs([(a,3)]) == Sum(1/(1+3*x**2),(x,0,3))
+    assert Sum(x*y,(x,0,y),(y,0,x)).subs([(x,3)]) == Sum(x*y,(x,0,y),(y,0,3))
+    assert Sum(x,(x,1,10)).subs([(x,y-2)]) == Sum(x,(x,1,10))
+    assert Sum(1/x,(x,1,10)).subs([(x,(3+n)**3)]) == Sum(1/x,(x,1,10))
+    assert Sum(1/x,(x,1,10)).subs([(x,3*x-2)]) == Sum(1/x,(x,1,10))
+
+
+def test_distribution_over_equality():
+    assert Product(Eq(x*2, f(x)), (x, 1, 3)).doit() == Eq(48, f(1)*f(2)*f(3))
+    assert Sum(Eq(f(x), x**2), (x, 0, y)) == \
+        Eq(Sum(f(x), (x, 0, y)), Sum(x**2, (x, 0, y)))
+
+
+def test_issue_2787():
+    n, k = symbols('n k', positive=True, integer=True)
+    p = symbols('p', positive=True)
+    binomial_dist = binomial(n, k)*p**k*(1 - p)**(n - k)
+    s = Sum(binomial_dist*k, (k, 0, n))
+    res = s.doit().simplify()
+    ans = Piecewise(
+        (n*p, x),
+        (Sum(k*p**k*binomial(n, k)*(1 - p)**(n - k), (k, 0, n)),
+        True)).subs(x, (Eq(n, 1) | (n > 1)) & (p/Abs(p - 1) <= 1))
+    ans2 = Piecewise(
+        (n*p, x),
+        (factorial(n)*Sum(p**k*(1 - p)**(-k + n)/
+        (factorial(-k + n)*factorial(k - 1)), (k, 0, n)),
+        True)).subs(x, (Eq(n, 1) | (n > 1)) & (p/Abs(p - 1) <= 1))
+    assert res in [ans, ans2]  # XXX system dependent
+    # Issue #17165: make sure that another simplify does not complicate
+    # the result by much. Why didn't first simplify replace
+    # Eq(n, 1) | (n > 1) with True?
+    assert res.simplify().count_ops() <= res.count_ops() + 2
+
+
+def test_issue_4668():
+    assert summation(1/n, (n, 2, oo)) is oo
+
+
+def test_matrix_sum():
+    A = Matrix([[0, 1], [n, 0]])
+
+    result = Sum(A, (n, 0, 3)).doit()
+    assert result == Matrix([[0, 4], [6, 0]])
+    assert result.__class__ == ImmutableDenseMatrix
+
+    A = SparseMatrix([[0, 1], [n, 0]])
+
+    result = Sum(A, (n, 0, 3)).doit()
+    assert result.__class__ == ImmutableSparseMatrix
+
+
+def test_failing_matrix_sum():
+    n = Symbol('n')
+    # TODO Implement matrix geometric series summation.
+    A = Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 0]])
+    assert Sum(A ** n, (n, 1, 4)).doit() == \
+        Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
+    # issue sympy/sympy#16989
+    assert summation(A**n, (n, 1, 1)) == A
+
+
+def test_indexed_idx_sum():
+    i = symbols('i', cls=Idx)
+    r = Indexed('r', i)
+    assert Sum(r, (i, 0, 3)).doit() == sum(r.xreplace({i: j}) for j in range(4))
+    assert Product(r, (i, 0, 3)).doit() == prod([r.xreplace({i: j}) for j in range(4)])
+
+    j = symbols('j', integer=True)
+    assert Sum(r, (i, j, j+2)).doit() == sum(r.xreplace({i: j+k}) for k in range(3))
+    assert Product(r, (i, j, j+2)).doit() == prod([r.xreplace({i: j+k}) for k in range(3)])
+
+    k = Idx('k', range=(1, 3))
+    A = IndexedBase('A')
+    assert Sum(A[k], k).doit() == sum(A[Idx(j, (1, 3))] for j in range(1, 4))
+    assert Product(A[k], k).doit() == prod([A[Idx(j, (1, 3))] for j in range(1, 4)])
+
+    raises(ValueError, lambda: Sum(A[k], (k, 1, 4)))
+    raises(ValueError, lambda: Sum(A[k], (k, 0, 3)))
+    raises(ValueError, lambda: Sum(A[k], (k, 2, oo)))
+
+    raises(ValueError, lambda: Product(A[k], (k, 1, 4)))
+    raises(ValueError, lambda: Product(A[k], (k, 0, 3)))
+    raises(ValueError, lambda: Product(A[k], (k, 2, oo)))
+
+
+@slow
+def test_is_convergent():
+    # divergence tests --
+    assert Sum(n/(2*n + 1), (n, 1, oo)).is_convergent() is S.false
+    assert Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent() is S.false
+    assert Sum(3**(-2*n - 1)*n**n, (n, 1, oo)).is_convergent() is S.false
+    assert Sum((-1)**n*n, (n, 3, oo)).is_convergent() is S.false
+    assert Sum((-1)**n, (n, 1, oo)).is_convergent() is S.false
+    assert Sum(log(1/n), (n, 2, oo)).is_convergent() is S.false
+    assert Sum(sin(n), (n, 1, oo)).is_convergent() is S.false
+
+    # Raabe's test --
+    assert Sum(Product((3*m),(m,1,n))/Product((3*m+4),(m,1,n)),(n,1,oo)).is_convergent() is S.true
+
+    # root test --
+    assert Sum((-12)**n/n, (n, 1, oo)).is_convergent() is S.false
+
+    # integral test --
+
+    # p-series test --
+    assert Sum(1/(n**2 + 1), (n, 1, oo)).is_convergent() is S.true
+    assert Sum(1/n**Rational(6, 5), (n, 1, oo)).is_convergent() is S.true
+    assert Sum(2/(n*sqrt(n - 1)), (n, 2, oo)).is_convergent() is S.true
+    assert Sum(1/(sqrt(n)*sqrt(n)), (n, 2, oo)).is_convergent() is S.false
+    assert Sum(factorial(n) / factorial(n+2), (n, 1, oo)).is_convergent() is S.true
+    assert Sum(rf(5,n)/rf(7,n),(n,1,oo)).is_convergent() is S.true
+    assert Sum((rf(1, n)*rf(2, n))/(rf(3, n)*factorial(n)),(n,1,oo)).is_convergent() is S.false
+
+    # comparison test --
+    assert Sum(1/(n + log(n)), (n, 1, oo)).is_convergent() is S.false
+    assert Sum(1/(n**2*log(n)), (n, 2, oo)).is_convergent() is S.true
+    assert Sum(1/(n*log(n)), (n, 2, oo)).is_convergent() is S.false
+    assert Sum(2/(n*log(n)*log(log(n))**2), (n, 5, oo)).is_convergent() is S.true
+    assert Sum(2/(n*log(n)**2), (n, 2, oo)).is_convergent() is S.true
+    assert Sum((n - 1)/(n**2*log(n)**3), (n, 2, oo)).is_convergent() is S.true
+    assert Sum(1/(n*log(n)*log(log(n))), (n, 5, oo)).is_convergent() is S.false
+    assert Sum((n - 1)/(n*log(n)**3), (n, 3, oo)).is_convergent() is S.false
+    assert Sum(2/(n**2*log(n)), (n, 2, oo)).is_convergent() is S.true
+    assert Sum(1/(n*sqrt(log(n))*log(log(n))), (n, 100, oo)).is_convergent() is S.false
+    assert Sum(log(log(n))/(n*log(n)**2), (n, 100, oo)).is_convergent() is S.true
+    assert Sum(log(n)/n**2, (n, 5, oo)).is_convergent() is S.true
+
+    # alternating series tests --
+    assert Sum((-1)**(n - 1)/(n**2 - 1), (n, 3, oo)).is_convergent() is S.true
+
+    # with -negativeInfinite Limits
+    assert Sum(1/(n**2 + 1), (n, -oo, 1)).is_convergent() is S.true
+    assert Sum(1/(n - 1), (n, -oo, -1)).is_convergent() is S.false
+    assert Sum(1/(n**2 - 1), (n, -oo, -5)).is_convergent() is S.true
+    assert Sum(1/(n**2 - 1), (n, -oo, 2)).is_convergent() is S.true
+    assert Sum(1/(n**2 - 1), (n, -oo, oo)).is_convergent() is S.true
+
+    # piecewise functions
+    f = Piecewise((n**(-2), n <= 1), (n**2, n > 1))
+    assert Sum(f, (n, 1, oo)).is_convergent() is S.false
+    assert Sum(f, (n, -oo, oo)).is_convergent() is S.false
+    assert Sum(f, (n, 1, 100)).is_convergent() is S.true
+    #assert Sum(f, (n, -oo, 1)).is_convergent() is S.true
+
+    # integral test
+
+    assert Sum(log(n)/n**3, (n, 1, oo)).is_convergent() is S.true
+    assert Sum(-log(n)/n**3, (n, 1, oo)).is_convergent() is S.true
+    # the following function has maxima located at (x, y) =
+    # (1.2, 0.43), (3.0, -0.25) and (6.8, 0.050)
+    eq = (x - 2)*(x**2 - 6*x + 4)*exp(-x)
+    assert Sum(eq, (x, 1, oo)).is_convergent() is S.true
+    assert Sum(eq, (x, 1, 2)).is_convergent() is S.true
+    assert Sum(1/(x**3), (x, 1, oo)).is_convergent() is S.true
+    assert Sum(1/(x**S.Half), (x, 1, oo)).is_convergent() is S.false
+
+    # issue 19545
+    assert Sum(1/n - 3/(3*n +2), (n, 1, oo)).is_convergent() is S.true
+
+    # issue 19836
+    assert Sum(4/(n + 2) - 5/(n + 1) + 1/n,(n, 7, oo)).is_convergent() is S.true
+
+
+def test_is_absolutely_convergent():
+    assert Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent() is S.false
+    assert Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent() is S.true
+
+
+@XFAIL
+def test_convergent_failing():
+    # dirichlet tests
+    assert Sum(sin(n)/n, (n, 1, oo)).is_convergent() is S.true
+    assert Sum(sin(2*n)/n, (n, 1, oo)).is_convergent() is S.true
+
+
+def test_issue_6966():
+    i, k, m = symbols('i k m', integer=True)
+    z_i, q_i = symbols('z_i q_i')
+    a_k = Sum(-q_i*z_i/k,(i,1,m))
+    b_k = a_k.diff(z_i)
+    assert isinstance(b_k, Sum)
+    assert b_k == Sum(-q_i/k,(i,1,m))
+
+
+def test_issue_10156():
+    cx = Sum(2*y**2*x, (x, 1,3))
+    e = 2*y*Sum(2*cx*x**2, (x, 1, 9))
+    assert e.factor() == \
+        8*y**3*Sum(x, (x, 1, 3))*Sum(x**2, (x, 1, 9))
+
+
+def test_issue_10973():
+    assert Sum((-n + (n**3 + 1)**(S(1)/3))/log(n), (n, 1, oo)).is_convergent() is S.true
+
+
+def test_issue_14103():
+    assert Sum(sin(n)**2 + cos(n)**2 - 1, (n, 1, oo)).is_convergent() is S.true
+    assert Sum(sin(pi*n), (n, 1, oo)).is_convergent() is S.true
+
+
+def test_issue_14129():
+    x = Symbol('x', zero=False)
+    assert Sum( k*x**k, (k, 0, n-1)).doit() == \
+        Piecewise((n**2/2 - n/2, Eq(x, 1)), ((n*x*x**n -
+            n*x**n - x*x**n + x)/(x - 1)**2, True))
+    assert Sum( x**k, (k, 0, n-1)).doit() == \
+        Piecewise((n, Eq(x, 1)), ((-x**n + 1)/(-x + 1), True))
+    assert Sum( k*(x/y+x)**k, (k, 0, n-1)).doit() == \
+        Piecewise((n*(n - 1)/2, Eq(x, y/(y + 1))),
+        (x*(y + 1)*(n*x*y*(x + x/y)**(n - 1) +
+        n*x*(x + x/y)**(n - 1) - n*y*(x + x/y)**(n - 1) -
+        x*y*(x + x/y)**(n - 1) - x*(x + x/y)**(n - 1) + y)/
+        (x*y + x - y)**2, True))
+
+
+def test_issue_14112():
+    assert Sum((-1)**n/sqrt(n), (n, 1, oo)).is_absolutely_convergent() is S.false
+    assert Sum((-1)**(2*n)/n, (n, 1, oo)).is_convergent() is S.false
+    assert Sum((-2)**n + (-3)**n, (n, 1, oo)).is_convergent() is S.false
+
+
+def test_issue_14219():
+    A = diag(0, 2, -3)
+    res = diag(1, 15, -20)
+    assert Sum(A**n, (n, 0, 3)).doit() == res
+
+
+def test_sin_times_absolutely_convergent():
+    assert Sum(sin(n) / n**3, (n, 1, oo)).is_convergent() is S.true
+    assert Sum(sin(n) * log(n) / n**3, (n, 1, oo)).is_convergent() is S.true
+
+
+def test_issue_14111():
+    assert Sum(1/log(log(n)), (n, 22, oo)).is_convergent() is S.false
+
+
+def test_issue_14484():
+    assert Sum(sin(n)/log(log(n)), (n, 22, oo)).is_convergent() is S.false
+
+
+def test_issue_14640():
+    i, n = symbols("i n", integer=True)
+    a, b, c = symbols("a b c", zero=False)
+
+    assert Sum(a**-i/(a - b), (i, 0, n)).doit() == Sum(
+        1/(a*a**i - a**i*b), (i, 0, n)).doit() == Piecewise(
+            (n + 1, Eq(1/a, 1)),
+            ((-a**(-n - 1) + 1)/(1 - 1/a), True))/(a - b)
+
+    assert Sum((b*a**i - c*a**i)**-2, (i, 0, n)).doit() == Piecewise(
+        (n + 1, Eq(a**(-2), 1)),
+        ((-a**(-2*n - 2) + 1)/(1 - 1/a**2), True))/(b - c)**2
+
+    s = Sum(i*(a**(n - i) - b**(n - i))/(a - b), (i, 0, n)).doit()
+    assert not s.has(Sum)
+    assert s.subs({a: 2, b: 3, n: 5}) == 122
+
+
+def test_issue_15943():
+    s = Sum(binomial(n, k)*factorial(n - k), (k, 0, n)).doit().rewrite(gamma)
+    assert s == -E*(n + 1)*gamma(n + 1)*lowergamma(n + 1, 1)/gamma(n + 2
+        ) + E*gamma(n + 1)
+    assert s.simplify() == E*(factorial(n) - lowergamma(n + 1, 1))
+
+
+def test_Sum_dummy_eq():
+    assert not Sum(x, (x, a, b)).dummy_eq(1)
+    assert not Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, b), (a, 1, 2)))
+    assert not Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, c)))
+    assert Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, b)))
+    d = Dummy()
+    assert Sum(x, (x, a, d)).dummy_eq(Sum(x, (x, a, c)), c)
+    assert not Sum(x, (x, a, d)).dummy_eq(Sum(x, (x, a, c)))
+    assert Sum(x, (x, a, c)).dummy_eq(Sum(y, (y, a, c)))
+    assert Sum(x, (x, a, d)).dummy_eq(Sum(y, (y, a, c)), c)
+    assert not Sum(x, (x, a, d)).dummy_eq(Sum(y, (y, a, c)))
+
+
+def test_issue_15852():
+    assert summation(x**y*y, (y, -oo, oo)).doit() == Sum(x**y*y, (y, -oo, oo))
+
+
+def test_exceptions():
+    S = Sum(x, (x, a, b))
+    raises(ValueError, lambda: S.change_index(x, x**2, y))
+    S = Sum(x, (x, a, b), (x, 1, 4))
+    raises(ValueError, lambda: S.index(x))
+    S = Sum(x, (x, a, b), (y, 1, 4))
+    raises(ValueError, lambda: S.reorder([x]))
+    S = Sum(x, (x, y, b), (y, 1, 4))
+    raises(ReorderError, lambda: S.reorder_limit(0, 1))
+    S = Sum(x*y, (x, a, b), (y, 1, 4))
+    raises(NotImplementedError, lambda: S.is_convergent())
+
+
+def test_sumproducts_assumptions():
+    M = Symbol('M', integer=True, positive=True)
+
+    m = Symbol('m', integer=True)
+    for func in [Sum, Product]:
+        assert func(m, (m, -M, M)).is_positive is None
+        assert func(m, (m, -M, M)).is_nonpositive is None
+        assert func(m, (m, -M, M)).is_negative is None
+        assert func(m, (m, -M, M)).is_nonnegative is None
+        assert func(m, (m, -M, M)).is_finite is True
+
+    m = Symbol('m', integer=True, nonnegative=True)
+    for func in [Sum, Product]:
+        assert func(m, (m, 0, M)).is_positive is None
+        assert func(m, (m, 0, M)).is_nonpositive is None
+        assert func(m, (m, 0, M)).is_negative is False
+        assert func(m, (m, 0, M)).is_nonnegative is True
+        assert func(m, (m, 0, M)).is_finite is True
+
+    m = Symbol('m', integer=True, positive=True)
+    for func in [Sum, Product]:
+        assert func(m, (m, 1, M)).is_positive is True
+        assert func(m, (m, 1, M)).is_nonpositive is False
+        assert func(m, (m, 1, M)).is_negative is False
+        assert func(m, (m, 1, M)).is_nonnegative is True
+        assert func(m, (m, 1, M)).is_finite is True
+
+    m = Symbol('m', integer=True, negative=True)
+    assert Sum(m, (m, -M, -1)).is_positive is False
+    assert Sum(m, (m, -M, -1)).is_nonpositive is True
+    assert Sum(m, (m, -M, -1)).is_negative is True
+    assert Sum(m, (m, -M, -1)).is_nonnegative is False
+    assert Sum(m, (m, -M, -1)).is_finite is True
+    assert Product(m, (m, -M, -1)).is_positive is None
+    assert Product(m, (m, -M, -1)).is_nonpositive is None
+    assert Product(m, (m, -M, -1)).is_negative is None
+    assert Product(m, (m, -M, -1)).is_nonnegative is None
+    assert Product(m, (m, -M, -1)).is_finite is True
+
+    m = Symbol('m', integer=True, nonpositive=True)
+    assert Sum(m, (m, -M, 0)).is_positive is False
+    assert Sum(m, (m, -M, 0)).is_nonpositive is True
+    assert Sum(m, (m, -M, 0)).is_negative is None
+    assert Sum(m, (m, -M, 0)).is_nonnegative is None
+    assert Sum(m, (m, -M, 0)).is_finite is True
+    assert Product(m, (m, -M, 0)).is_positive is None
+    assert Product(m, (m, -M, 0)).is_nonpositive is None
+    assert Product(m, (m, -M, 0)).is_negative is None
+    assert Product(m, (m, -M, 0)).is_nonnegative is None
+    assert Product(m, (m, -M, 0)).is_finite is True
+
+    m = Symbol('m', integer=True)
+    assert Sum(2, (m, 0, oo)).is_positive is None
+    assert Sum(2, (m, 0, oo)).is_nonpositive is None
+    assert Sum(2, (m, 0, oo)).is_negative is None
+    assert Sum(2, (m, 0, oo)).is_nonnegative is None
+    assert Sum(2, (m, 0, oo)).is_finite is None
+
+    assert Product(2, (m, 0, oo)).is_positive is None
+    assert Product(2, (m, 0, oo)).is_nonpositive is None
+    assert Product(2, (m, 0, oo)).is_negative is False
+    assert Product(2, (m, 0, oo)).is_nonnegative is None
+    assert Product(2, (m, 0, oo)).is_finite is None
+
+    assert Product(0, (x, M, M-1)).is_positive is True
+    assert Product(0, (x, M, M-1)).is_finite is True
+
+
+def test_expand_with_assumptions():
+    M = Symbol('M', integer=True, positive=True)
+    x = Symbol('x', positive=True)
+    m = Symbol('m', nonnegative=True)
+    assert log(Product(x**m, (m, 0, M))).expand() == Sum(m*log(x), (m, 0, M))
+    assert log(Product(exp(x**m), (m, 0, M))).expand() == Sum(x**m, (m, 0, M))
+    assert log(Product(x**m, (m, 0, M))).rewrite(Sum).expand() == Sum(m*log(x), (m, 0, M))
+    assert log(Product(exp(x**m), (m, 0, M))).rewrite(Sum).expand() == Sum(x**m, (m, 0, M))
+
+    n = Symbol('n', nonnegative=True)
+    i, j = symbols('i,j', positive=True, integer=True)
+    x, y = symbols('x,y', positive=True)
+    assert log(Product(x**i*y**j, (i, 1, n), (j, 1, m))).expand() \
+        == Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m))
+
+    m = Symbol('m', nonnegative=True, integer=True)
+    s = Sum(x**m, (m, 0, M))
+    s_as_product = s.rewrite(Product)
+    assert s_as_product.has(Product)
+    assert s_as_product == log(Product(exp(x**m), (m, 0, M)))
+    assert s_as_product.expand() == s
+    s5 = s.subs(M, 5)
+    s5_as_product = s5.rewrite(Product)
+    assert s5_as_product.has(Product)
+    assert s5_as_product.doit().expand() == s5.doit()
+
+
+def test_has_finite_limits():
+    x = Symbol('x')
+    assert Sum(1, (x, 1, 9)).has_finite_limits is True
+    assert Sum(1, (x, 1, oo)).has_finite_limits is False
+    M = Symbol('M')
+    assert Sum(1, (x, 1, M)).has_finite_limits is None
+    M = Symbol('M', positive=True)
+    assert Sum(1, (x, 1, M)).has_finite_limits is True
+    x = Symbol('x', positive=True)
+    M = Symbol('M')
+    assert Sum(1, (x, 1, M)).has_finite_limits is True
+
+    assert Sum(1, (x, 1, M), (y, -oo, oo)).has_finite_limits is False
+
+def test_has_reversed_limits():
+    assert Sum(1, (x, 1, 1)).has_reversed_limits is False
+    assert Sum(1, (x, 1, 9)).has_reversed_limits is False
+    assert Sum(1, (x, 1, -9)).has_reversed_limits is True
+    assert Sum(1, (x, 1, 0)).has_reversed_limits is True
+    assert Sum(1, (x, 1, oo)).has_reversed_limits is False
+    M = Symbol('M')
+    assert Sum(1, (x, 1, M)).has_reversed_limits is None
+    M = Symbol('M', positive=True, integer=True)
+    assert Sum(1, (x, 1, M)).has_reversed_limits is False
+    assert Sum(1, (x, 1, M), (y, -oo, oo)).has_reversed_limits is False
+    M = Symbol('M', negative=True)
+    assert Sum(1, (x, 1, M)).has_reversed_limits is True
+
+    assert Sum(1, (x, 1, M), (y, -oo, oo)).has_reversed_limits is True
+    assert Sum(1, (x, oo, oo)).has_reversed_limits is None
+
+
+def test_has_empty_sequence():
+    assert Sum(1, (x, 1, 1)).has_empty_sequence is False
+    assert Sum(1, (x, 1, 9)).has_empty_sequence is False
+    assert Sum(1, (x, 1, -9)).has_empty_sequence is False
+    assert Sum(1, (x, 1, 0)).has_empty_sequence is True
+    assert Sum(1, (x, y, y - 1)).has_empty_sequence is True
+    assert Sum(1, (x, 3, 2), (y, -oo, oo)).has_empty_sequence is True
+    assert Sum(1, (y, -oo, oo), (x, 3, 2)).has_empty_sequence is True
+    assert Sum(1, (x, oo, oo)).has_empty_sequence is False
+
+
+def test_empty_sequence():
+    assert Product(x*y, (x, -oo, oo), (y, 1, 0)).doit() == 1
+    assert Product(x*y, (y, 1, 0), (x, -oo, oo)).doit() == 1
+    assert Sum(x, (x, -oo, oo), (y, 1, 0)).doit() == 0
+    assert Sum(x, (y, 1, 0), (x, -oo, oo)).doit() == 0
+
+
+def test_issue_8016():
+    k = Symbol('k', integer=True)
+    n, m = symbols('n, m', integer=True, positive=True)
+    s = Sum(binomial(m, k)*binomial(m, n - k)*(-1)**k, (k, 0, n))
+    assert s.doit().simplify() == \
+        cos(pi*n/2)*gamma(m + 1)/gamma(n/2 + 1)/gamma(m - n/2 + 1)
+
+
+def test_issue_14313():
+    assert Sum(S.Half**floor(n/2), (n, 1, oo)).is_convergent()
+
+
+def test_issue_14563():
+    # The assertion was failing due to no assumptions methods in Sums and Product
+    assert 1 % Sum(1, (x, 0, 1)) == 1
+
+
+def test_issue_16735():
+    assert Sum(5**n/gamma(n+1), (n, 1, oo)).is_convergent() is S.true
+
+
+def test_issue_14871():
+    assert Sum((Rational(1, 10))**n*rf(0, n)/factorial(n), (n, 0, oo)).rewrite(factorial).doit() == 1
+
+
+def test_issue_17165():
+    n = symbols("n", integer=True)
+    x = symbols('x')
+    s = (x*Sum(x**n, (n, -1, oo)))
+    ssimp = s.doit().simplify()
+
+    assert ssimp == Piecewise((-1/(x - 1), (x > -1) & (x < 1)),
+                              (x*Sum(x**n, (n, -1, oo)), True)), ssimp
+    assert ssimp.simplify() == ssimp
+
+
+def test_issue_19379():
+    assert Sum(factorial(n)/factorial(n + 2), (n, 1, oo)).is_convergent() is S.true
+
+
+def test_issue_20777():
+    assert Sum(exp(x*sin(n/m)), (n, 1, m)).doit() == Sum(exp(x*sin(n/m)), (n, 1, m))
+
+
+def test__dummy_with_inherited_properties_concrete():
+    x = Symbol('x')
+
+    from sympy.core.containers import Tuple
+    d = _dummy_with_inherited_properties_concrete(Tuple(x, 0, 5))
+    assert d.is_real
+    assert d.is_integer
+    assert d.is_nonnegative
+    assert d.is_extended_nonnegative
+
+    d = _dummy_with_inherited_properties_concrete(Tuple(x, 1, 9))
+    assert d.is_real
+    assert d.is_integer
+    assert d.is_positive
+    assert d.is_odd is None
+
+    d = _dummy_with_inherited_properties_concrete(Tuple(x, -5, 5))
+    assert d.is_real
+    assert d.is_integer
+    assert d.is_positive is None
+    assert d.is_extended_nonnegative is None
+    assert d.is_odd is None
+
+    d = _dummy_with_inherited_properties_concrete(Tuple(x, -1.5, 1.5))
+    assert d.is_real
+    assert d.is_integer is None
+    assert d.is_positive is None
+    assert d.is_extended_nonnegative is None
+
+    N = Symbol('N', integer=True, positive=True)
+    d = _dummy_with_inherited_properties_concrete(Tuple(x, 2, N))
+    assert d.is_real
+    assert d.is_positive
+    assert d.is_integer
+
+    # Return None if no assumptions are added
+    N = Symbol('N', integer=True, positive=True)
+    d = _dummy_with_inherited_properties_concrete(Tuple(N, 2, 4))
+    assert d is None
+
+    x = Symbol('x', negative=True)
+    raises(InconsistentAssumptions,
+           lambda: _dummy_with_inherited_properties_concrete(Tuple(x, 1, 5)))
+
+
+def test_matrixsymbol_summation_numerical_limits():
+    A = MatrixSymbol('A', 3, 3)
+    n = Symbol('n', integer=True)
+
+    assert Sum(A**n, (n, 0, 2)).doit() == Identity(3) + A + A**2
+    assert Sum(A, (n, 0, 2)).doit() == 3*A
+    assert Sum(n*A, (n, 0, 2)).doit() == 3*A
+
+    B = Matrix([[0, n, 0], [-1, 0, 0], [0, 0, 2]])
+    ans = Matrix([[0, 6, 0], [-4, 0, 0], [0, 0, 8]]) + 4*A
+    assert Sum(A+B, (n, 0, 3)).doit() == ans
+    ans = A*Matrix([[0, 6, 0], [-4, 0, 0], [0, 0, 8]])
+    assert Sum(A*B, (n, 0, 3)).doit() == ans
+
+    ans = (A**2*Matrix([[-2, 0, 0], [0,-2, 0], [0, 0, 4]]) +
+           A**3*Matrix([[0, -9, 0], [3, 0, 0], [0, 0, 8]]) +
+           A*Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 2]]))
+    assert Sum(A**n*B**n, (n, 1, 3)).doit() == ans
+
+
+def test_issue_21651():
+    i = Symbol('i')
+    a = Sum(floor(2*2**(-i)), (i, S.One, 2))
+    assert a.doit() == S.One
+
+
+@XFAIL
+def test_matrixsymbol_summation_symbolic_limits():
+    N = Symbol('N', integer=True, positive=True)
+
+    A = MatrixSymbol('A', 3, 3)
+    n = Symbol('n', integer=True)
+    assert Sum(A, (n, 0, N)).doit() == (N+1)*A
+    assert Sum(n*A, (n, 0, N)).doit() == (N**2/2+N/2)*A
+
+
+def test_summation_by_residues():
+    x = Symbol('x')
+
+    # Examples from Nakhle H. Asmar, Loukas Grafakos,
+    # Complex Analysis with Applications
+    assert eval_sum_residue(1 / (x**2 + 1), (x, -oo, oo)) == pi/tanh(pi)
+    assert eval_sum_residue(1 / x**6, (x, S(1), oo)) == pi**6/945
+    assert eval_sum_residue(1 / (x**2 + 9), (x, -oo, oo)) == pi/(3*tanh(3*pi))
+    assert eval_sum_residue(1 / (x**2 + 1)**2, (x, -oo, oo)).cancel() == \
+        (-pi**2*tanh(pi)**2 + pi*tanh(pi) + pi**2)/(2*tanh(pi)**2)
+    assert eval_sum_residue(x**2 / (x**2 + 1)**2, (x, -oo, oo)).cancel() == \
+        (-pi**2 + pi*tanh(pi) + pi**2*tanh(pi)**2)/(2*tanh(pi)**2)
+    assert eval_sum_residue(1 / (4*x**2 - 1), (x, -oo, oo)) == 0
+    assert eval_sum_residue(x**2 / (x**2 - S(1)/4)**2, (x, -oo, oo)) == pi**2/2
+    assert eval_sum_residue(1 / (4*x**2 - 1)**2, (x, -oo, oo)) == pi**2/8
+    assert eval_sum_residue(1 / ((x - S(1)/2)**2 + 1), (x, -oo, oo)) == pi*tanh(pi)
+    assert eval_sum_residue(1 / x**2, (x, S(1), oo)) == pi**2/6
+    assert eval_sum_residue(1 / x**4, (x, S(1), oo)) == pi**4/90
+    assert eval_sum_residue(1 / x**2 / (x**2 + 4), (x, S(1), oo)) == \
+        -pi*(-pi/12 - 1/(16*pi) + 1/(8*tanh(2*pi)))/2
+
+    # Some examples made from 1 / (x**2 + 1)
+    assert eval_sum_residue(1 / (x**2 + 1), (x, S(0), oo)) == \
+        S(1)/2 + pi/(2*tanh(pi))
+    assert eval_sum_residue(1 / (x**2 + 1), (x, S(1), oo)) == \
+        -S(1)/2 + pi/(2*tanh(pi))
+    assert eval_sum_residue(1 / (x**2 + 1), (x, S(-1), oo)) == \
+        1 + pi/(2*tanh(pi))
+    assert eval_sum_residue((-1)**x / (x**2 + 1), (x, -oo, oo)) == \
+        pi/sinh(pi)
+    assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(0), oo)) == \
+        pi/(2*sinh(pi)) + S(1)/2
+    assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(1), oo)) == \
+        -S(1)/2 + pi/(2*sinh(pi))
+    assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(-1), oo)) == \
+        pi/(2*sinh(pi))
+
+    # Some examples made from shifting of 1 / (x**2 + 1)
+    assert eval_sum_residue(1 / (x**2 + 2*x + 2), (x, S(-1), oo)) == S(1)/2 + pi/(2*tanh(pi))
+    assert eval_sum_residue(1 / (x**2 + 4*x + 5), (x, S(-2), oo)) == S(1)/2 + pi/(2*tanh(pi))
+    assert eval_sum_residue(1 / (x**2 - 2*x + 2), (x, S(1), oo)) == S(1)/2 + pi/(2*tanh(pi))
+    assert eval_sum_residue(1 / (x**2 - 4*x + 5), (x, S(2), oo)) == S(1)/2 + pi/(2*tanh(pi))
+    assert eval_sum_residue((-1)**x * -1 / (x**2 + 2*x + 2), (x, S(-1), oo)) ==  S(1)/2 + pi/(2*sinh(pi))
+    assert eval_sum_residue((-1)**x * -1 / (x**2 -2*x + 2), (x, S(1), oo)) == S(1)/2 + pi/(2*sinh(pi))
+
+    # Some examples made from 1 / x**2
+    assert eval_sum_residue(1 / x**2, (x, S(2), oo)) == -1 + pi**2/6
+    assert eval_sum_residue(1 / x**2, (x, S(3), oo)) == -S(5)/4 + pi**2/6
+    assert eval_sum_residue((-1)**x / x**2, (x, S(1), oo)) == -pi**2/12
+    assert eval_sum_residue((-1)**x / x**2, (x, S(2), oo)) == 1 - pi**2/12
+
+
+@slow
+def test_summation_by_residues_failing():
+    x = Symbol('x')
+
+    # Failing because of the bug in residue computation
+    assert eval_sum_residue(x**2 / (x**4 + 1), (x, S(1), oo))
+    assert eval_sum_residue(1 / ((x - 1)*(x - 2) + 1), (x, -oo, oo)) != 0
+
+
+def test_process_limits():
+    from sympy.concrete.expr_with_limits import _process_limits
+
+    # these should be (x, Range(3)) not Range(3)
+    raises(ValueError, lambda: _process_limits(
+        Range(3), discrete=True))
+    raises(ValueError, lambda: _process_limits(
+        Range(3), discrete=False))
+    # these should be (x, union) not union
+    # (but then we would get a TypeError because we don't
+    # handle non-contiguous sets: see below use of `union`)
+    union = Or(x < 1, x > 3).as_set()
+    raises(ValueError, lambda: _process_limits(
+        union, discrete=True))
+    raises(ValueError, lambda: _process_limits(
+        union, discrete=False))
+
+    # error not triggered if not needed
+    assert _process_limits((x, 1, 2)) == ([(x, 1, 2)], 1)
+
+    # this equivalence is used to detect Reals in _process_limits
+    assert isinstance(S.Reals, Interval)
+
+    C = Integral  # continuous limits
+    assert C(x, x >= 5) == C(x, (x, 5, oo))
+    assert C(x, x < 3) == C(x, (x, -oo, 3))
+    ans = C(x, (x, 0, 3))
+    assert C(x, And(x >= 0, x < 3)) == ans
+    assert C(x, (x, Interval.Ropen(0, 3))) == ans
+    raises(TypeError, lambda: C(x, (x, Range(3))))
+
+    # discrete limits
+    for D in (Sum, Product):
+        r, ans = Range(3, 10, 2), D(2*x + 3, (x, 0, 3))
+        assert D(x, (x, r)) == ans
+        assert D(x, (x, r.reversed)) == ans
+        r, ans = Range(3, oo, 2), D(2*x + 3, (x, 0, oo))
+        assert D(x, (x, r)) == ans
+        assert D(x, (x, r.reversed)) == ans
+        r, ans = Range(-oo, 5, 2), D(3 - 2*x, (x, 0, oo))
+        assert D(x, (x, r)) == ans
+        assert D(x, (x, r.reversed)) == ans
+        raises(TypeError, lambda: D(x, x > 0))
+        raises(ValueError, lambda: D(x, Interval(1, 3)))
+        raises(NotImplementedError, lambda: D(x, (x, union)))
+
+
+def test_pr_22677():
+    b = Symbol('b', integer=True, positive=True)
+    assert Sum(1/x**2,(x, 0, b)).doit() == Sum(x**(-2), (x, 0, b))
+    assert Sum(1/(x - b)**2,(x, 0, b-1)).doit() == Sum(
+        (-b + x)**(-2), (x, 0, b - 1))
+
+
+def test_issue_23952():
+    p, q = symbols("p q", real=True, nonnegative=True)
+    k1, k2 = symbols("k1 k2", integer=True, nonnegative=True)
+    n = Symbol("n", integer=True, positive=True)
+    expr = Sum(abs(k1 - k2)*p**k1 *(1 - q)**(n - k2),
+        (k1, 0, n), (k2, 0, n))
+    assert expr.subs(p,0).subs(q,1).subs(n, 3).doit() == 3
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/crypto/crypto.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/crypto/crypto.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c298e4ac08616dbe7d607a9d56d33b7fe9d5e2d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/crypto/crypto.py
@@ -0,0 +1,3368 @@
+"""
+This file contains some classical ciphers and routines
+implementing a linear-feedback shift register (LFSR)
+and the Diffie-Hellman key exchange.
+
+.. warning::
+
+   This module is intended for educational purposes only. Do not use the
+   functions in this module for real cryptographic applications. If you wish
+   to encrypt real data, we recommend using something like the `cryptography
+   `_ module.
+
+"""
+
+from string import whitespace, ascii_uppercase as uppercase, printable
+from functools import reduce
+import string
+import warnings
+
+from itertools import cycle
+
+from sympy.external.gmpy import GROUND_TYPES
+from sympy.core import Symbol
+from sympy.core.numbers import Rational
+from sympy.core.random import _randrange, _randint
+from sympy.external.gmpy import gcd, invert
+from sympy.functions.combinatorial.numbers import (totient as _euler,
+                                                   reduced_totient as _carmichael)
+from sympy.matrices import Matrix
+from sympy.ntheory import isprime, primitive_root, factorint
+from sympy.ntheory.generate import nextprime
+from sympy.ntheory.modular import crt
+from sympy.polys.domains import FF
+from sympy.polys.polytools import Poly
+from sympy.utilities.misc import as_int, filldedent, translate
+from sympy.utilities.iterables import uniq, multiset
+from sympy.utilities.decorator import doctest_depends_on
+
+
+if GROUND_TYPES == 'flint':
+    __doctest_skip__ = ['lfsr_sequence']
+
+
+class NonInvertibleCipherWarning(RuntimeWarning):
+    """A warning raised if the cipher is not invertible."""
+    def __init__(self, msg):
+        self.fullMessage = msg
+
+    def __str__(self):
+        return '\n\t' + self.fullMessage
+
+    def warn(self, stacklevel=3):
+        warnings.warn(self, stacklevel=stacklevel)
+
+
+def AZ(s=None):
+    """Return the letters of ``s`` in uppercase. In case more than
+    one string is passed, each of them will be processed and a list
+    of upper case strings will be returned.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import AZ
+    >>> AZ('Hello, world!')
+    'HELLOWORLD'
+    >>> AZ('Hello, world!'.split())
+    ['HELLO', 'WORLD']
+
+    See Also
+    ========
+
+    check_and_join
+
+    """
+    if not s:
+        return uppercase
+    t = isinstance(s, str)
+    if t:
+        s = [s]
+    rv = [check_and_join(i.upper().split(), uppercase, filter=True)
+        for i in s]
+    if t:
+        return rv[0]
+    return rv
+
+bifid5 = AZ().replace('J', '')
+bifid6 = AZ() + string.digits
+bifid10 = printable
+
+
+def padded_key(key, symbols):
+    """Return a string of the distinct characters of ``symbols`` with
+    those of ``key`` appearing first. A ValueError is raised if
+    a) there are duplicate characters in ``symbols`` or
+    b) there are characters in ``key`` that are  not in ``symbols``.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import padded_key
+    >>> padded_key('PUPPY', 'OPQRSTUVWXY')
+    'PUYOQRSTVWX'
+    >>> padded_key('RSA', 'ARTIST')
+    Traceback (most recent call last):
+    ...
+    ValueError: duplicate characters in symbols: T
+
+    """
+    syms = list(uniq(symbols))
+    if len(syms) != len(symbols):
+        extra = ''.join(sorted({
+            i for i in symbols if symbols.count(i) > 1}))
+        raise ValueError('duplicate characters in symbols: %s' % extra)
+    extra = set(key) - set(syms)
+    if extra:
+        raise ValueError(
+            'characters in key but not symbols: %s' % ''.join(
+            sorted(extra)))
+    key0 = ''.join(list(uniq(key)))
+    # remove from syms characters in key0
+    return key0 + translate(''.join(syms), None, key0)
+
+
+def check_and_join(phrase, symbols=None, filter=None):
+    """
+    Joins characters of ``phrase`` and if ``symbols`` is given, raises
+    an error if any character in ``phrase`` is not in ``symbols``.
+
+    Parameters
+    ==========
+
+    phrase
+        String or list of strings to be returned as a string.
+
+    symbols
+        Iterable of characters allowed in ``phrase``.
+
+        If ``symbols`` is ``None``, no checking is performed.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import check_and_join
+    >>> check_and_join('a phrase')
+    'a phrase'
+    >>> check_and_join('a phrase'.upper().split())
+    'APHRASE'
+    >>> check_and_join('a phrase!'.upper().split(), 'ARE', filter=True)
+    'ARAE'
+    >>> check_and_join('a phrase!'.upper().split(), 'ARE')
+    Traceback (most recent call last):
+    ...
+    ValueError: characters in phrase but not symbols: "!HPS"
+
+    """
+    rv = ''.join(''.join(phrase))
+    if symbols is not None:
+        symbols = check_and_join(symbols)
+        missing = ''.join(sorted(set(rv) - set(symbols)))
+        if missing:
+            if not filter:
+                raise ValueError(
+                    'characters in phrase but not symbols: "%s"' % missing)
+            rv = translate(rv, None, missing)
+    return rv
+
+
+def _prep(msg, key, alp, default=None):
+    if not alp:
+        if not default:
+            alp = AZ()
+            msg = AZ(msg)
+            key = AZ(key)
+        else:
+            alp = default
+    else:
+        alp = ''.join(alp)
+    key = check_and_join(key, alp, filter=True)
+    msg = check_and_join(msg, alp, filter=True)
+    return msg, key, alp
+
+
+def cycle_list(k, n):
+    """
+    Returns the elements of the list ``range(n)`` shifted to the
+    left by ``k`` (so the list starts with ``k`` (mod ``n``)).
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import cycle_list
+    >>> cycle_list(3, 10)
+    [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]
+
+    """
+    k = k % n
+    return list(range(k, n)) + list(range(k))
+
+
+######## shift cipher examples ############
+
+
+def encipher_shift(msg, key, symbols=None):
+    """
+    Performs shift cipher encryption on plaintext msg, and returns the
+    ciphertext.
+
+    Parameters
+    ==========
+
+    key : int
+        The secret key.
+
+    msg : str
+        Plaintext of upper-case letters.
+
+    Returns
+    =======
+
+    str
+        Ciphertext of upper-case letters.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import encipher_shift, decipher_shift
+    >>> msg = "GONAVYBEATARMY"
+    >>> ct = encipher_shift(msg, 1); ct
+    'HPOBWZCFBUBSNZ'
+
+    To decipher the shifted text, change the sign of the key:
+
+    >>> encipher_shift(ct, -1)
+    'GONAVYBEATARMY'
+
+    There is also a convenience function that does this with the
+    original key:
+
+    >>> decipher_shift(ct, 1)
+    'GONAVYBEATARMY'
+
+    Notes
+    =====
+
+    ALGORITHM:
+
+        STEPS:
+            0. Number the letters of the alphabet from 0, ..., N
+            1. Compute from the string ``msg`` a list ``L1`` of
+               corresponding integers.
+            2. Compute from the list ``L1`` a new list ``L2``, given by
+               adding ``(k mod 26)`` to each element in ``L1``.
+            3. Compute from the list ``L2`` a string ``ct`` of
+               corresponding letters.
+
+    The shift cipher is also called the Caesar cipher, after
+    Julius Caesar, who, according to Suetonius, used it with a
+    shift of three to protect messages of military significance.
+    Caesar's nephew Augustus reportedly used a similar cipher, but
+    with a right shift of 1.
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Caesar_cipher
+    .. [2] https://mathworld.wolfram.com/CaesarsMethod.html
+
+    See Also
+    ========
+
+    decipher_shift
+
+    """
+    msg, _, A = _prep(msg, '', symbols)
+    shift = len(A) - key % len(A)
+    key = A[shift:] + A[:shift]
+    return translate(msg, key, A)
+
+
+def decipher_shift(msg, key, symbols=None):
+    """
+    Return the text by shifting the characters of ``msg`` to the
+    left by the amount given by ``key``.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import encipher_shift, decipher_shift
+    >>> msg = "GONAVYBEATARMY"
+    >>> ct = encipher_shift(msg, 1); ct
+    'HPOBWZCFBUBSNZ'
+
+    To decipher the shifted text, change the sign of the key:
+
+    >>> encipher_shift(ct, -1)
+    'GONAVYBEATARMY'
+
+    Or use this function with the original key:
+
+    >>> decipher_shift(ct, 1)
+    'GONAVYBEATARMY'
+
+    """
+    return encipher_shift(msg, -key, symbols)
+
+def encipher_rot13(msg, symbols=None):
+    """
+    Performs the ROT13 encryption on a given plaintext ``msg``.
+
+    Explanation
+    ===========
+
+    ROT13 is a substitution cipher which substitutes each letter
+    in the plaintext message for the letter furthest away from it
+    in the English alphabet.
+
+    Equivalently, it is just a Caeser (shift) cipher with a shift
+    key of 13 (midway point of the alphabet).
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/ROT13
+
+    See Also
+    ========
+
+    decipher_rot13
+    encipher_shift
+
+    """
+    return encipher_shift(msg, 13, symbols)
+
+def decipher_rot13(msg, symbols=None):
+    """
+    Performs the ROT13 decryption on a given plaintext ``msg``.
+
+    Explanation
+    ============
+
+    ``decipher_rot13`` is equivalent to ``encipher_rot13`` as both
+    ``decipher_shift`` with a key of 13 and ``encipher_shift`` key with a
+    key of 13 will return the same results. Nonetheless,
+    ``decipher_rot13`` has nonetheless been explicitly defined here for
+    consistency.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import encipher_rot13, decipher_rot13
+    >>> msg = 'GONAVYBEATARMY'
+    >>> ciphertext = encipher_rot13(msg);ciphertext
+    'TBANILORNGNEZL'
+    >>> decipher_rot13(ciphertext)
+    'GONAVYBEATARMY'
+    >>> encipher_rot13(msg) == decipher_rot13(msg)
+    True
+    >>> msg == decipher_rot13(ciphertext)
+    True
+
+    """
+    return decipher_shift(msg, 13, symbols)
+
+######## affine cipher examples ############
+
+
+def encipher_affine(msg, key, symbols=None, _inverse=False):
+    r"""
+    Performs the affine cipher encryption on plaintext ``msg``, and
+    returns the ciphertext.
+
+    Explanation
+    ===========
+
+    Encryption is based on the map `x \rightarrow ax+b` (mod `N`)
+    where ``N`` is the number of characters in the alphabet.
+    Decryption is based on the map `x \rightarrow cx+d` (mod `N`),
+    where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`).
+    In particular, for the map to be invertible, we need
+    `\mathrm{gcd}(a, N) = 1` and an error will be raised if this is
+    not true.
+
+    Parameters
+    ==========
+
+    msg : str
+        Characters that appear in ``symbols``.
+
+    a, b : int, int
+        A pair integers, with ``gcd(a, N) = 1`` (the secret key).
+
+    symbols
+        String of characters (default = uppercase letters).
+
+        When no symbols are given, ``msg`` is converted to upper case
+        letters and all other characters are ignored.
+
+    Returns
+    =======
+
+    ct
+        String of characters (the ciphertext message)
+
+    Notes
+    =====
+
+    ALGORITHM:
+
+        STEPS:
+            0. Number the letters of the alphabet from 0, ..., N
+            1. Compute from the string ``msg`` a list ``L1`` of
+               corresponding integers.
+            2. Compute from the list ``L1`` a new list ``L2``, given by
+               replacing ``x`` by ``a*x + b (mod N)``, for each element
+               ``x`` in ``L1``.
+            3. Compute from the list ``L2`` a string ``ct`` of
+               corresponding letters.
+
+    This is a straightforward generalization of the shift cipher with
+    the added complexity of requiring 2 characters to be deciphered in
+    order to recover the key.
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Affine_cipher
+
+    See Also
+    ========
+
+    decipher_affine
+
+    """
+    msg, _, A = _prep(msg, '', symbols)
+    N = len(A)
+    a, b = key
+    assert gcd(a, N) == 1
+    if _inverse:
+        c = invert(a, N)
+        d = -b*c
+        a, b = c, d
+    B = ''.join([A[(a*i + b) % N] for i in range(N)])
+    return translate(msg, A, B)
+
+
+def decipher_affine(msg, key, symbols=None):
+    r"""
+    Return the deciphered text that was made from the mapping,
+    `x \rightarrow ax+b` (mod `N`), where ``N`` is the
+    number of characters in the alphabet. Deciphering is done by
+    reciphering with a new key: `x \rightarrow cx+d` (mod `N`),
+    where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`).
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import encipher_affine, decipher_affine
+    >>> msg = "GO NAVY BEAT ARMY"
+    >>> key = (3, 1)
+    >>> encipher_affine(msg, key)
+    'TROBMVENBGBALV'
+    >>> decipher_affine(_, key)
+    'GONAVYBEATARMY'
+
+    See Also
+    ========
+
+    encipher_affine
+
+    """
+    return encipher_affine(msg, key, symbols, _inverse=True)
+
+
+def encipher_atbash(msg, symbols=None):
+    r"""
+    Enciphers a given ``msg`` into its Atbash ciphertext and returns it.
+
+    Explanation
+    ===========
+
+    Atbash is a substitution cipher originally used to encrypt the Hebrew
+    alphabet. Atbash works on the principle of mapping each alphabet to its
+    reverse / counterpart (i.e. a would map to z, b to y etc.)
+
+    Atbash is functionally equivalent to the affine cipher with ``a = 25``
+    and ``b = 25``
+
+    See Also
+    ========
+
+    decipher_atbash
+
+    """
+    return encipher_affine(msg, (25, 25), symbols)
+
+
+def decipher_atbash(msg, symbols=None):
+    r"""
+    Deciphers a given ``msg`` using Atbash cipher and returns it.
+
+    Explanation
+    ===========
+
+    ``decipher_atbash`` is functionally equivalent to ``encipher_atbash``.
+    However, it has still been added as a separate function to maintain
+    consistency.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import encipher_atbash, decipher_atbash
+    >>> msg = 'GONAVYBEATARMY'
+    >>> encipher_atbash(msg)
+    'TLMZEBYVZGZINB'
+    >>> decipher_atbash(msg)
+    'TLMZEBYVZGZINB'
+    >>> encipher_atbash(msg) == decipher_atbash(msg)
+    True
+    >>> msg == encipher_atbash(encipher_atbash(msg))
+    True
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Atbash
+
+    See Also
+    ========
+
+    encipher_atbash
+
+    """
+    return decipher_affine(msg, (25, 25), symbols)
+
+#################### substitution cipher ###########################
+
+
+def encipher_substitution(msg, old, new=None):
+    r"""
+    Returns the ciphertext obtained by replacing each character that
+    appears in ``old`` with the corresponding character in ``new``.
+    If ``old`` is a mapping, then new is ignored and the replacements
+    defined by ``old`` are used.
+
+    Explanation
+    ===========
+
+    This is a more general than the affine cipher in that the key can
+    only be recovered by determining the mapping for each symbol.
+    Though in practice, once a few symbols are recognized the mappings
+    for other characters can be quickly guessed.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import encipher_substitution, AZ
+    >>> old = 'OEYAG'
+    >>> new = '034^6'
+    >>> msg = AZ("go navy! beat army!")
+    >>> ct = encipher_substitution(msg, old, new); ct
+    '60N^V4B3^T^RM4'
+
+    To decrypt a substitution, reverse the last two arguments:
+
+    >>> encipher_substitution(ct, new, old)
+    'GONAVYBEATARMY'
+
+    In the special case where ``old`` and ``new`` are a permutation of
+    order 2 (representing a transposition of characters) their order
+    is immaterial:
+
+    >>> old = 'NAVY'
+    >>> new = 'ANYV'
+    >>> encipher = lambda x: encipher_substitution(x, old, new)
+    >>> encipher('NAVY')
+    'ANYV'
+    >>> encipher(_)
+    'NAVY'
+
+    The substitution cipher, in general, is a method
+    whereby "units" (not necessarily single characters) of plaintext
+    are replaced with ciphertext according to a regular system.
+
+    >>> ords = dict(zip('abc', ['\\%i' % ord(i) for i in 'abc']))
+    >>> print(encipher_substitution('abc', ords))
+    \97\98\99
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Substitution_cipher
+
+    """
+    return translate(msg, old, new)
+
+
+######################################################################
+#################### Vigenere cipher examples ########################
+######################################################################
+
+def encipher_vigenere(msg, key, symbols=None):
+    """
+    Performs the Vigenere cipher encryption on plaintext ``msg``, and
+    returns the ciphertext.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import encipher_vigenere, AZ
+    >>> key = "encrypt"
+    >>> msg = "meet me on monday"
+    >>> encipher_vigenere(msg, key)
+    'QRGKKTHRZQEBPR'
+
+    Section 1 of the Kryptos sculpture at the CIA headquarters
+    uses this cipher and also changes the order of the
+    alphabet [2]_. Here is the first line of that section of
+    the sculpture:
+
+    >>> from sympy.crypto.crypto import decipher_vigenere, padded_key
+    >>> alp = padded_key('KRYPTOS', AZ())
+    >>> key = 'PALIMPSEST'
+    >>> msg = 'EMUFPHZLRFAXYUSDJKZLDKRNSHGNFIVJ'
+    >>> decipher_vigenere(msg, key, alp)
+    'BETWEENSUBTLESHADINGANDTHEABSENC'
+
+    Explanation
+    ===========
+
+    The Vigenere cipher is named after Blaise de Vigenere, a sixteenth
+    century diplomat and cryptographer, by a historical accident.
+    Vigenere actually invented a different and more complicated cipher.
+    The so-called *Vigenere cipher* was actually invented
+    by Giovan Batista Belaso in 1553.
+
+    This cipher was used in the 1800's, for example, during the American
+    Civil War. The Confederacy used a brass cipher disk to implement the
+    Vigenere cipher (now on display in the NSA Museum in Fort
+    Meade) [1]_.
+
+    The Vigenere cipher is a generalization of the shift cipher.
+    Whereas the shift cipher shifts each letter by the same amount
+    (that amount being the key of the shift cipher) the Vigenere
+    cipher shifts a letter by an amount determined by the key (which is
+    a word or phrase known only to the sender and receiver).
+
+    For example, if the key was a single letter, such as "C", then the
+    so-called Vigenere cipher is actually a shift cipher with a
+    shift of `2` (since "C" is the 2nd letter of the alphabet, if
+    you start counting at `0`). If the key was a word with two
+    letters, such as "CA", then the so-called Vigenere cipher will
+    shift letters in even positions by `2` and letters in odd positions
+    are left alone (shifted by `0`, since "A" is the 0th letter, if
+    you start counting at `0`).
+
+
+    ALGORITHM:
+
+        INPUT:
+
+            ``msg``: string of characters that appear in ``symbols``
+            (the plaintext)
+
+            ``key``: a string of characters that appear in ``symbols``
+            (the secret key)
+
+            ``symbols``: a string of letters defining the alphabet
+
+
+        OUTPUT:
+
+            ``ct``: string of characters (the ciphertext message)
+
+        STEPS:
+            0. Number the letters of the alphabet from 0, ..., N
+            1. Compute from the string ``key`` a list ``L1`` of
+               corresponding integers. Let ``n1 = len(L1)``.
+            2. Compute from the string ``msg`` a list ``L2`` of
+               corresponding integers. Let ``n2 = len(L2)``.
+            3. Break ``L2`` up sequentially into sublists of size
+               ``n1``; the last sublist may be smaller than ``n1``
+            4. For each of these sublists ``L`` of ``L2``, compute a
+               new list ``C`` given by ``C[i] = L[i] + L1[i] (mod N)``
+               to the ``i``-th element in the sublist, for each ``i``.
+            5. Assemble these lists ``C`` by concatenation into a new
+               list of length ``n2``.
+            6. Compute from the new list a string ``ct`` of
+               corresponding letters.
+
+    Once it is known that the key is, say, `n` characters long,
+    frequency analysis can be applied to every `n`-th letter of
+    the ciphertext to determine the plaintext. This method is
+    called *Kasiski examination* (although it was first discovered
+    by Babbage). If they key is as long as the message and is
+    comprised of randomly selected characters -- a one-time pad -- the
+    message is theoretically unbreakable.
+
+    The cipher Vigenere actually discovered is an "auto-key" cipher
+    described as follows.
+
+    ALGORITHM:
+
+        INPUT:
+
+          ``key``: a string of letters (the secret key)
+
+          ``msg``: string of letters (the plaintext message)
+
+        OUTPUT:
+
+          ``ct``: string of upper-case letters (the ciphertext message)
+
+        STEPS:
+            0. Number the letters of the alphabet from 0, ..., N
+            1. Compute from the string ``msg`` a list ``L2`` of
+               corresponding integers. Let ``n2 = len(L2)``.
+            2. Let ``n1`` be the length of the key. Append to the
+               string ``key`` the first ``n2 - n1`` characters of
+               the plaintext message. Compute from this string (also of
+               length ``n2``) a list ``L1`` of integers corresponding
+               to the letter numbers in the first step.
+            3. Compute a new list ``C`` given by
+               ``C[i] = L1[i] + L2[i] (mod N)``.
+            4. Compute from the new list a string ``ct`` of letters
+               corresponding to the new integers.
+
+    To decipher the auto-key ciphertext, the key is used to decipher
+    the first ``n1`` characters and then those characters become the
+    key to  decipher the next ``n1`` characters, etc...:
+
+    >>> m = AZ('go navy, beat army! yes you can'); m
+    'GONAVYBEATARMYYESYOUCAN'
+    >>> key = AZ('gold bug'); n1 = len(key); n2 = len(m)
+    >>> auto_key = key + m[:n2 - n1]; auto_key
+    'GOLDBUGGONAVYBEATARMYYE'
+    >>> ct = encipher_vigenere(m, auto_key); ct
+    'MCYDWSHKOGAMKZCELYFGAYR'
+    >>> n1 = len(key)
+    >>> pt = []
+    >>> while ct:
+    ...     part, ct = ct[:n1], ct[n1:]
+    ...     pt.append(decipher_vigenere(part, key))
+    ...     key = pt[-1]
+    ...
+    >>> ''.join(pt) == m
+    True
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Vigenere_cipher
+    .. [2] https://web.archive.org/web/20071116100808/https://filebox.vt.edu/users/batman/kryptos.html
+       (short URL: https://goo.gl/ijr22d)
+
+    """
+    msg, key, A = _prep(msg, key, symbols)
+    map = {c: i for i, c in enumerate(A)}
+    key = [map[c] for c in key]
+    N = len(map)
+    k = len(key)
+    rv = []
+    for i, m in enumerate(msg):
+        rv.append(A[(map[m] + key[i % k]) % N])
+    rv = ''.join(rv)
+    return rv
+
+
+def decipher_vigenere(msg, key, symbols=None):
+    """
+    Decode using the Vigenere cipher.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import decipher_vigenere
+    >>> key = "encrypt"
+    >>> ct = "QRGK kt HRZQE BPR"
+    >>> decipher_vigenere(ct, key)
+    'MEETMEONMONDAY'
+
+    """
+    msg, key, A = _prep(msg, key, symbols)
+    map = {c: i for i, c in enumerate(A)}
+    N = len(A)   # normally, 26
+    K = [map[c] for c in key]
+    n = len(K)
+    C = [map[c] for c in msg]
+    rv = ''.join([A[(-K[i % n] + c) % N] for i, c in enumerate(C)])
+    return rv
+
+
+#################### Hill cipher  ########################
+
+
+def encipher_hill(msg, key, symbols=None, pad="Q"):
+    r"""
+    Return the Hill cipher encryption of ``msg``.
+
+    Explanation
+    ===========
+
+    The Hill cipher [1]_, invented by Lester S. Hill in the 1920's [2]_,
+    was the first polygraphic cipher in which it was practical
+    (though barely) to operate on more than three symbols at once.
+    The following discussion assumes an elementary knowledge of
+    matrices.
+
+    First, each letter is first encoded as a number starting with 0.
+    Suppose your message `msg` consists of `n` capital letters, with no
+    spaces. This may be regarded an `n`-tuple M of elements of
+    `Z_{26}` (if the letters are those of the English alphabet). A key
+    in the Hill cipher is a `k x k` matrix `K`, all of whose entries
+    are in `Z_{26}`, such that the matrix `K` is invertible (i.e., the
+    linear transformation `K: Z_{N}^k \rightarrow Z_{N}^k`
+    is one-to-one).
+
+
+    Parameters
+    ==========
+
+    msg
+        Plaintext message of `n` upper-case letters.
+
+    key
+        A `k \times k` invertible matrix `K`, all of whose entries are
+        in `Z_{26}` (or whatever number of symbols are being used).
+
+    pad
+        Character (default "Q") to use to make length of text be a
+        multiple of ``k``.
+
+    Returns
+    =======
+
+    ct
+        Ciphertext of upper-case letters.
+
+    Notes
+    =====
+
+    ALGORITHM:
+
+        STEPS:
+            0. Number the letters of the alphabet from 0, ..., N
+            1. Compute from the string ``msg`` a list ``L`` of
+               corresponding integers. Let ``n = len(L)``.
+            2. Break the list ``L`` up into ``t = ceiling(n/k)``
+               sublists ``L_1``, ..., ``L_t`` of size ``k`` (with
+               the last list "padded" to ensure its size is
+               ``k``).
+            3. Compute new list ``C_1``, ..., ``C_t`` given by
+               ``C[i] = K*L_i`` (arithmetic is done mod N), for each
+               ``i``.
+            4. Concatenate these into a list ``C = C_1 + ... + C_t``.
+            5. Compute from ``C`` a string ``ct`` of corresponding
+               letters. This has length ``k*t``.
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Hill_cipher
+    .. [2] Lester S. Hill, Cryptography in an Algebraic Alphabet,
+       The American Mathematical Monthly Vol.36, June-July 1929,
+       pp.306-312.
+
+    See Also
+    ========
+
+    decipher_hill
+
+    """
+    assert key.is_square
+    assert len(pad) == 1
+    msg, pad, A = _prep(msg, pad, symbols)
+    map = {c: i for i, c in enumerate(A)}
+    P = [map[c] for c in msg]
+    N = len(A)
+    k = key.cols
+    n = len(P)
+    m, r = divmod(n, k)
+    if r:
+        P = P + [map[pad]]*(k - r)
+        m += 1
+    rv = ''.join([A[c % N] for j in range(m) for c in
+        list(key*Matrix(k, 1, [P[i]
+        for i in range(k*j, k*(j + 1))]))])
+    return rv
+
+
+def decipher_hill(msg, key, symbols=None):
+    """
+    Deciphering is the same as enciphering but using the inverse of the
+    key matrix.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import encipher_hill, decipher_hill
+    >>> from sympy import Matrix
+
+    >>> key = Matrix([[1, 2], [3, 5]])
+    >>> encipher_hill("meet me on monday", key)
+    'UEQDUEODOCTCWQ'
+    >>> decipher_hill(_, key)
+    'MEETMEONMONDAY'
+
+    When the length of the plaintext (stripped of invalid characters)
+    is not a multiple of the key dimension, extra characters will
+    appear at the end of the enciphered and deciphered text. In order to
+    decipher the text, those characters must be included in the text to
+    be deciphered. In the following, the key has a dimension of 4 but
+    the text is 2 short of being a multiple of 4 so two characters will
+    be added.
+
+    >>> key = Matrix([[1, 1, 1, 2], [0, 1, 1, 0],
+    ...               [2, 2, 3, 4], [1, 1, 0, 1]])
+    >>> msg = "ST"
+    >>> encipher_hill(msg, key)
+    'HJEB'
+    >>> decipher_hill(_, key)
+    'STQQ'
+    >>> encipher_hill(msg, key, pad="Z")
+    'ISPK'
+    >>> decipher_hill(_, key)
+    'STZZ'
+
+    If the last two characters of the ciphertext were ignored in
+    either case, the wrong plaintext would be recovered:
+
+    >>> decipher_hill("HD", key)
+    'ORMV'
+    >>> decipher_hill("IS", key)
+    'UIKY'
+
+    See Also
+    ========
+
+    encipher_hill
+
+    """
+    assert key.is_square
+    msg, _, A = _prep(msg, '', symbols)
+    map = {c: i for i, c in enumerate(A)}
+    C = [map[c] for c in msg]
+    N = len(A)
+    k = key.cols
+    n = len(C)
+    m, r = divmod(n, k)
+    if r:
+        C = C + [0]*(k - r)
+        m += 1
+    key_inv = key.inv_mod(N)
+    rv = ''.join([A[p % N] for j in range(m) for p in
+        list(key_inv*Matrix(
+        k, 1, [C[i] for i in range(k*j, k*(j + 1))]))])
+    return rv
+
+
+#################### Bifid cipher  ########################
+
+
+def encipher_bifid(msg, key, symbols=None):
+    r"""
+    Performs the Bifid cipher encryption on plaintext ``msg``, and
+    returns the ciphertext.
+
+    This is the version of the Bifid cipher that uses an `n \times n`
+    Polybius square.
+
+    Parameters
+    ==========
+
+    msg
+        Plaintext string.
+
+    key
+        Short string for key.
+
+        Duplicate characters are ignored and then it is padded with the
+        characters in ``symbols`` that were not in the short key.
+
+    symbols
+        `n \times n` characters defining the alphabet.
+
+        (default is string.printable)
+
+    Returns
+    =======
+
+    ciphertext
+        Ciphertext using Bifid5 cipher without spaces.
+
+    See Also
+    ========
+
+    decipher_bifid, encipher_bifid5, encipher_bifid6
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Bifid_cipher
+
+    """
+    msg, key, A = _prep(msg, key, symbols, bifid10)
+    long_key = ''.join(uniq(key)) or A
+
+    n = len(A)**.5
+    if n != int(n):
+        raise ValueError(
+            'Length of alphabet (%s) is not a square number.' % len(A))
+    N = int(n)
+    if len(long_key) < N**2:
+        long_key = list(long_key) + [x for x in A if x not in long_key]
+
+    # the fractionalization
+    row_col = {ch: divmod(i, N) for i, ch in enumerate(long_key)}
+    r, c = zip(*[row_col[x] for x in msg])
+    rc = r + c
+    ch = {i: ch for ch, i in row_col.items()}
+    rv = ''.join(ch[i] for i in zip(rc[::2], rc[1::2]))
+    return rv
+
+
+def decipher_bifid(msg, key, symbols=None):
+    r"""
+    Performs the Bifid cipher decryption on ciphertext ``msg``, and
+    returns the plaintext.
+
+    This is the version of the Bifid cipher that uses the `n \times n`
+    Polybius square.
+
+    Parameters
+    ==========
+
+    msg
+        Ciphertext string.
+
+    key
+        Short string for key.
+
+        Duplicate characters are ignored and then it is padded with the
+        characters in symbols that were not in the short key.
+
+    symbols
+        `n \times n` characters defining the alphabet.
+
+        (default=string.printable, a `10 \times 10` matrix)
+
+    Returns
+    =======
+
+    deciphered
+        Deciphered text.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import (
+    ...     encipher_bifid, decipher_bifid, AZ)
+
+    Do an encryption using the bifid5 alphabet:
+
+    >>> alp = AZ().replace('J', '')
+    >>> ct = AZ("meet me on monday!")
+    >>> key = AZ("gold bug")
+    >>> encipher_bifid(ct, key, alp)
+    'IEILHHFSTSFQYE'
+
+    When entering the text or ciphertext, spaces are ignored so it
+    can be formatted as desired. Re-entering the ciphertext from the
+    preceding, putting 4 characters per line and padding with an extra
+    J, does not cause problems for the deciphering:
+
+    >>> decipher_bifid('''
+    ... IEILH
+    ... HFSTS
+    ... FQYEJ''', key, alp)
+    'MEETMEONMONDAY'
+
+    When no alphabet is given, all 100 printable characters will be
+    used:
+
+    >>> key = ''
+    >>> encipher_bifid('hello world!', key)
+    'bmtwmg-bIo*w'
+    >>> decipher_bifid(_, key)
+    'hello world!'
+
+    If the key is changed, a different encryption is obtained:
+
+    >>> key = 'gold bug'
+    >>> encipher_bifid('hello world!', 'gold_bug')
+    'hg2sfuei7t}w'
+
+    And if the key used to decrypt the message is not exact, the
+    original text will not be perfectly obtained:
+
+    >>> decipher_bifid(_, 'gold pug')
+    'heldo~wor6d!'
+
+    """
+    msg, _, A = _prep(msg, '', symbols, bifid10)
+    long_key = ''.join(uniq(key)) or A
+
+    n = len(A)**.5
+    if n != int(n):
+        raise ValueError(
+            'Length of alphabet (%s) is not a square number.' % len(A))
+    N = int(n)
+    if len(long_key) < N**2:
+        long_key = list(long_key) + [x for x in A if x not in long_key]
+
+    # the reverse fractionalization
+    row_col = {
+        ch: divmod(i, N) for i, ch in enumerate(long_key)}
+    rc = [i for c in msg for i in row_col[c]]
+    n = len(msg)
+    rc = zip(*(rc[:n], rc[n:]))
+    ch = {i: ch for ch, i in row_col.items()}
+    rv = ''.join(ch[i] for i in rc)
+    return rv
+
+
+def bifid_square(key):
+    """Return characters of ``key`` arranged in a square.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import (
+    ...    bifid_square, AZ, padded_key, bifid5)
+    >>> bifid_square(AZ().replace('J', ''))
+    Matrix([
+    [A, B, C, D, E],
+    [F, G, H, I, K],
+    [L, M, N, O, P],
+    [Q, R, S, T, U],
+    [V, W, X, Y, Z]])
+
+    >>> bifid_square(padded_key(AZ('gold bug!'), bifid5))
+    Matrix([
+    [G, O, L, D, B],
+    [U, A, C, E, F],
+    [H, I, K, M, N],
+    [P, Q, R, S, T],
+    [V, W, X, Y, Z]])
+
+    See Also
+    ========
+
+    padded_key
+
+    """
+    A = ''.join(uniq(''.join(key)))
+    n = len(A)**.5
+    if n != int(n):
+        raise ValueError(
+            'Length of alphabet (%s) is not a square number.' % len(A))
+    n = int(n)
+    f = lambda i, j: Symbol(A[n*i + j])
+    rv = Matrix(n, n, f)
+    return rv
+
+
+def encipher_bifid5(msg, key):
+    r"""
+    Performs the Bifid cipher encryption on plaintext ``msg``, and
+    returns the ciphertext.
+
+    Explanation
+    ===========
+
+    This is the version of the Bifid cipher that uses the `5 \times 5`
+    Polybius square. The letter "J" is ignored so it must be replaced
+    with something else (traditionally an "I") before encryption.
+
+    ALGORITHM: (5x5 case)
+
+        STEPS:
+            0. Create the `5 \times 5` Polybius square ``S`` associated
+               to ``key`` as follows:
+
+                a) moving from left-to-right, top-to-bottom,
+                   place the letters of the key into a `5 \times 5`
+                   matrix,
+                b) if the key has less than 25 letters, add the
+                   letters of the alphabet not in the key until the
+                   `5 \times 5` square is filled.
+
+            1. Create a list ``P`` of pairs of numbers which are the
+               coordinates in the Polybius square of the letters in
+               ``msg``.
+            2. Let ``L1`` be the list of all first coordinates of ``P``
+               (length of ``L1 = n``), let ``L2`` be the list of all
+               second coordinates of ``P`` (so the length of ``L2``
+               is also ``n``).
+            3. Let ``L`` be the concatenation of ``L1`` and ``L2``
+               (length ``L = 2*n``), except that consecutive numbers
+               are paired ``(L[2*i], L[2*i + 1])``. You can regard
+               ``L`` as a list of pairs of length ``n``.
+            4. Let ``C`` be the list of all letters which are of the
+               form ``S[i, j]``, for all ``(i, j)`` in ``L``. As a
+               string, this is the ciphertext of ``msg``.
+
+    Parameters
+    ==========
+
+    msg : str
+        Plaintext string.
+
+        Converted to upper case and filtered of anything but all letters
+        except J.
+
+    key
+        Short string for key; non-alphabetic letters, J and duplicated
+        characters are ignored and then, if the length is less than 25
+        characters, it is padded with other letters of the alphabet
+        (in alphabetical order).
+
+    Returns
+    =======
+
+    ct
+        Ciphertext (all caps, no spaces).
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import (
+    ...     encipher_bifid5, decipher_bifid5)
+
+    "J" will be omitted unless it is replaced with something else:
+
+    >>> round_trip = lambda m, k: \
+    ...     decipher_bifid5(encipher_bifid5(m, k), k)
+    >>> key = 'a'
+    >>> msg = "JOSIE"
+    >>> round_trip(msg, key)
+    'OSIE'
+    >>> round_trip(msg.replace("J", "I"), key)
+    'IOSIE'
+    >>> j = "QIQ"
+    >>> round_trip(msg.replace("J", j), key).replace(j, "J")
+    'JOSIE'
+
+
+    Notes
+    =====
+
+    The Bifid cipher was invented around 1901 by Felix Delastelle.
+    It is a *fractional substitution* cipher, where letters are
+    replaced by pairs of symbols from a smaller alphabet. The
+    cipher uses a `5 \times 5` square filled with some ordering of the
+    alphabet, except that "J" is replaced with "I" (this is a so-called
+    Polybius square; there is a `6 \times 6` analog if you add back in
+    "J" and also append onto the usual 26 letter alphabet, the digits
+    0, 1, ..., 9).
+    According to Helen Gaines' book *Cryptanalysis*, this type of cipher
+    was used in the field by the German Army during World War I.
+
+    See Also
+    ========
+
+    decipher_bifid5, encipher_bifid
+
+    """
+    msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5)
+    key = padded_key(key, bifid5)
+    return encipher_bifid(msg, '', key)
+
+
+def decipher_bifid5(msg, key):
+    r"""
+    Return the Bifid cipher decryption of ``msg``.
+
+    Explanation
+    ===========
+
+    This is the version of the Bifid cipher that uses the `5 \times 5`
+    Polybius square; the letter "J" is ignored unless a ``key`` of
+    length 25 is used.
+
+    Parameters
+    ==========
+
+    msg
+        Ciphertext string.
+
+    key
+        Short string for key; duplicated characters are ignored and if
+        the length is less then 25 characters, it will be padded with
+        other letters from the alphabet omitting "J".
+        Non-alphabetic characters are ignored.
+
+    Returns
+    =======
+
+    plaintext
+        Plaintext from Bifid5 cipher (all caps, no spaces).
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import encipher_bifid5, decipher_bifid5
+    >>> key = "gold bug"
+    >>> encipher_bifid5('meet me on friday', key)
+    'IEILEHFSTSFXEE'
+    >>> encipher_bifid5('meet me on monday', key)
+    'IEILHHFSTSFQYE'
+    >>> decipher_bifid5(_, key)
+    'MEETMEONMONDAY'
+
+    """
+    msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5)
+    key = padded_key(key, bifid5)
+    return decipher_bifid(msg, '', key)
+
+
+def bifid5_square(key=None):
+    r"""
+    5x5 Polybius square.
+
+    Produce the Polybius square for the `5 \times 5` Bifid cipher.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import bifid5_square
+    >>> bifid5_square("gold bug")
+    Matrix([
+    [G, O, L, D, B],
+    [U, A, C, E, F],
+    [H, I, K, M, N],
+    [P, Q, R, S, T],
+    [V, W, X, Y, Z]])
+
+    """
+    if not key:
+        key = bifid5
+    else:
+        _, key, _ = _prep('', key.upper(), None, bifid5)
+        key = padded_key(key, bifid5)
+    return bifid_square(key)
+
+
+def encipher_bifid6(msg, key):
+    r"""
+    Performs the Bifid cipher encryption on plaintext ``msg``, and
+    returns the ciphertext.
+
+    This is the version of the Bifid cipher that uses the `6 \times 6`
+    Polybius square.
+
+    Parameters
+    ==========
+
+    msg
+        Plaintext string (digits okay).
+
+    key
+        Short string for key (digits okay).
+
+        If ``key`` is less than 36 characters long, the square will be
+        filled with letters A through Z and digits 0 through 9.
+
+    Returns
+    =======
+
+    ciphertext
+        Ciphertext from Bifid cipher (all caps, no spaces).
+
+    See Also
+    ========
+
+    decipher_bifid6, encipher_bifid
+
+    """
+    msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6)
+    key = padded_key(key, bifid6)
+    return encipher_bifid(msg, '', key)
+
+
+def decipher_bifid6(msg, key):
+    r"""
+    Performs the Bifid cipher decryption on ciphertext ``msg``, and
+    returns the plaintext.
+
+    This is the version of the Bifid cipher that uses the `6 \times 6`
+    Polybius square.
+
+    Parameters
+    ==========
+
+    msg
+        Ciphertext string (digits okay); converted to upper case
+
+    key
+        Short string for key (digits okay).
+
+        If ``key`` is less than 36 characters long, the square will be
+        filled with letters A through Z and digits 0 through 9.
+        All letters are converted to uppercase.
+
+    Returns
+    =======
+
+    plaintext
+        Plaintext from Bifid cipher (all caps, no spaces).
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import encipher_bifid6, decipher_bifid6
+    >>> key = "gold bug"
+    >>> encipher_bifid6('meet me on monday at 8am', key)
+    'KFKLJJHF5MMMKTFRGPL'
+    >>> decipher_bifid6(_, key)
+    'MEETMEONMONDAYAT8AM'
+
+    """
+    msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6)
+    key = padded_key(key, bifid6)
+    return decipher_bifid(msg, '', key)
+
+
+def bifid6_square(key=None):
+    r"""
+    6x6 Polybius square.
+
+    Produces the Polybius square for the `6 \times 6` Bifid cipher.
+    Assumes alphabet of symbols is "A", ..., "Z", "0", ..., "9".
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import bifid6_square
+    >>> key = "gold bug"
+    >>> bifid6_square(key)
+    Matrix([
+    [G, O, L, D, B, U],
+    [A, C, E, F, H, I],
+    [J, K, M, N, P, Q],
+    [R, S, T, V, W, X],
+    [Y, Z, 0, 1, 2, 3],
+    [4, 5, 6, 7, 8, 9]])
+
+    """
+    if not key:
+        key = bifid6
+    else:
+        _, key, _ = _prep('', key.upper(), None, bifid6)
+        key = padded_key(key, bifid6)
+    return bifid_square(key)
+
+
+#################### RSA  #############################
+
+def _decipher_rsa_crt(i, d, factors):
+    """Decipher RSA using chinese remainder theorem from the information
+    of the relatively-prime factors of the modulus.
+
+    Parameters
+    ==========
+
+    i : integer
+        Ciphertext
+
+    d : integer
+        The exponent component.
+
+    factors : list of relatively-prime integers
+        The integers given must be coprime and the product must equal
+        the modulus component of the original RSA key.
+
+    Examples
+    ========
+
+    How to decrypt RSA with CRT:
+
+    >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
+    >>> primes = [61, 53]
+    >>> e = 17
+    >>> args = primes + [e]
+    >>> puk = rsa_public_key(*args)
+    >>> prk = rsa_private_key(*args)
+
+    >>> from sympy.crypto.crypto import encipher_rsa, _decipher_rsa_crt
+    >>> msg = 65
+    >>> crt_primes = primes
+    >>> encrypted = encipher_rsa(msg, puk)
+    >>> decrypted = _decipher_rsa_crt(encrypted, prk[1], primes)
+    >>> decrypted
+    65
+    """
+    moduluses = [pow(i, d, p) for p in factors]
+
+    result = crt(factors, moduluses)
+    if not result:
+        raise ValueError("CRT failed")
+    return result[0]
+
+
+def _rsa_key(*args, public=True, private=True, totient='Euler', index=None, multipower=None):
+    r"""A private subroutine to generate RSA key
+
+    Parameters
+    ==========
+
+    public, private : bool, optional
+        Flag to generate either a public key, a private key.
+
+    totient : 'Euler' or 'Carmichael'
+        Different notation used for totient.
+
+    multipower : bool, optional
+        Flag to bypass warning for multipower RSA.
+    """
+
+    if len(args) < 2:
+        return False
+
+    if totient not in ('Euler', 'Carmichael'):
+        raise ValueError(
+            "The argument totient={} should either be " \
+            "'Euler', 'Carmichalel'." \
+            .format(totient))
+
+    if totient == 'Euler':
+        _totient = _euler
+    else:
+        _totient = _carmichael
+
+    if index is not None:
+        index = as_int(index)
+        if totient != 'Carmichael':
+            raise ValueError(
+                "Setting the 'index' keyword argument requires totient"
+                "notation to be specified as 'Carmichael'.")
+
+    primes, e = args[:-1], args[-1]
+
+    if not all(isprime(p) for p in primes):
+        new_primes = []
+        for i in primes:
+            new_primes.extend(factorint(i, multiple=True))
+        primes = new_primes
+
+    n = reduce(lambda i, j: i*j, primes)
+
+    tally = multiset(primes)
+    if all(v == 1 for v in tally.values()):
+        phi = int(_totient(tally))
+
+    else:
+        if not multipower:
+            NonInvertibleCipherWarning(
+                'Non-distinctive primes found in the factors {}. '
+                'The cipher may not be decryptable for some numbers '
+                'in the complete residue system Z[{}], but the cipher '
+                'can still be valid if you restrict the domain to be '
+                'the reduced residue system Z*[{}]. You can pass '
+                'the flag multipower=True if you want to suppress this '
+                'warning.'
+                .format(primes, n, n)
+                # stacklevel=4 because most users will call a function that
+                # calls this function
+                ).warn(stacklevel=4)
+        phi = int(_totient(tally))
+
+    if gcd(e, phi) == 1:
+        if public and not private:
+            if isinstance(index, int):
+                e = e % phi
+                e += index * phi
+            return n, e
+
+        if private and not public:
+            d = invert(e, phi)
+            if isinstance(index, int):
+                d += index * phi
+            return n, d
+
+    return False
+
+
+def rsa_public_key(*args, **kwargs):
+    r"""Return the RSA *public key* pair, `(n, e)`
+
+    Parameters
+    ==========
+
+    args : naturals
+        If specified as `p, q, e` where `p` and `q` are distinct primes
+        and `e` is a desired public exponent of the RSA, `n = p q` and
+        `e` will be verified against the totient
+        `\phi(n)` (Euler totient) or `\lambda(n)` (Carmichael totient)
+        to be `\gcd(e, \phi(n)) = 1` or `\gcd(e, \lambda(n)) = 1`.
+
+        If specified as `p_1, p_2, \dots, p_n, e` where
+        `p_1, p_2, \dots, p_n` are specified as primes,
+        and `e` is specified as a desired public exponent of the RSA,
+        it will be able to form a multi-prime RSA, which is a more
+        generalized form of the popular 2-prime RSA.
+
+        It can also be possible to form a single-prime RSA by specifying
+        the argument as `p, e`, which can be considered a trivial case
+        of a multiprime RSA.
+
+        Furthermore, it can be possible to form a multi-power RSA by
+        specifying two or more pairs of the primes to be same.
+        However, unlike the two-distinct prime RSA or multi-prime
+        RSA, not every numbers in the complete residue system
+        (`\mathbb{Z}_n`) will be decryptable since the mapping
+        `\mathbb{Z}_{n} \rightarrow \mathbb{Z}_{n}`
+        will not be bijective.
+        (Only except for the trivial case when
+        `e = 1`
+        or more generally,
+
+        .. math::
+            e \in \left \{ 1 + k \lambda(n)
+            \mid k \in \mathbb{Z} \land k \geq 0 \right \}
+
+        when RSA reduces to the identity.)
+        However, the RSA can still be decryptable for the numbers in the
+        reduced residue system (`\mathbb{Z}_n^{\times}`), since the
+        mapping
+        `\mathbb{Z}_{n}^{\times} \rightarrow \mathbb{Z}_{n}^{\times}`
+        can still be bijective.
+
+        If you pass a non-prime integer to the arguments
+        `p_1, p_2, \dots, p_n`, the particular number will be
+        prime-factored and it will become either a multi-prime RSA or a
+        multi-power RSA in its canonical form, depending on whether the
+        product equals its radical or not.
+        `p_1 p_2 \dots p_n = \text{rad}(p_1 p_2 \dots p_n)`
+
+    totient : bool, optional
+        If ``'Euler'``, it uses Euler's totient `\phi(n)` which is
+        :meth:`sympy.functions.combinatorial.numbers.totient` in SymPy.
+
+        If ``'Carmichael'``, it uses Carmichael's totient `\lambda(n)`
+        which is :meth:`sympy.functions.combinatorial.numbers.reduced_totient` in SymPy.
+
+        Unlike private key generation, this is a trivial keyword for
+        public key generation because
+        `\gcd(e, \phi(n)) = 1 \iff \gcd(e, \lambda(n)) = 1`.
+
+    index : nonnegative integer, optional
+        Returns an arbitrary solution of a RSA public key at the index
+        specified at `0, 1, 2, \dots`. This parameter needs to be
+        specified along with ``totient='Carmichael'``.
+
+        Similarly to the non-uniquenss of a RSA private key as described
+        in the ``index`` parameter documentation in
+        :meth:`rsa_private_key`, RSA public key is also not unique and
+        there is an infinite number of RSA public exponents which
+        can behave in the same manner.
+
+        From any given RSA public exponent `e`, there are can be an
+        another RSA public exponent `e + k \lambda(n)` where `k` is an
+        integer, `\lambda` is a Carmichael's totient function.
+
+        However, considering only the positive cases, there can be
+        a principal solution of a RSA public exponent `e_0` in
+        `0 < e_0 < \lambda(n)`, and all the other solutions
+        can be canonicalzed in a form of `e_0 + k \lambda(n)`.
+
+        ``index`` specifies the `k` notation to yield any possible value
+        an RSA public key can have.
+
+        An example of computing any arbitrary RSA public key:
+
+        >>> from sympy.crypto.crypto import rsa_public_key
+        >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=0)
+        (3233, 17)
+        >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=1)
+        (3233, 797)
+        >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=2)
+        (3233, 1577)
+
+    multipower : bool, optional
+        Any pair of non-distinct primes found in the RSA specification
+        will restrict the domain of the cryptosystem, as noted in the
+        explanation of the parameter ``args``.
+
+        SymPy RSA key generator may give a warning before dispatching it
+        as a multi-power RSA, however, you can disable the warning if
+        you pass ``True`` to this keyword.
+
+    Returns
+    =======
+
+    (n, e) : int, int
+        `n` is a product of any arbitrary number of primes given as
+        the argument.
+
+        `e` is relatively prime (coprime) to the Euler totient
+        `\phi(n)`.
+
+    False
+        Returned if less than two arguments are given, or `e` is
+        not relatively prime to the modulus.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import rsa_public_key
+
+    A public key of a two-prime RSA:
+
+    >>> p, q, e = 3, 5, 7
+    >>> rsa_public_key(p, q, e)
+    (15, 7)
+    >>> rsa_public_key(p, q, 30)
+    False
+
+    A public key of a multiprime RSA:
+
+    >>> primes = [2, 3, 5, 7, 11, 13]
+    >>> e = 7
+    >>> args = primes + [e]
+    >>> rsa_public_key(*args)
+    (30030, 7)
+
+    Notes
+    =====
+
+    Although the RSA can be generalized over any modulus `n`, using
+    two large primes had became the most popular specification because a
+    product of two large primes is usually the hardest to factor
+    relatively to the digits of `n` can have.
+
+    However, it may need further understanding of the time complexities
+    of each prime-factoring algorithms to verify the claim.
+
+    See Also
+    ========
+
+    rsa_private_key
+    encipher_rsa
+    decipher_rsa
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29
+
+    .. [2] https://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
+
+    .. [3] https://link.springer.com/content/pdf/10.1007/BFb0055738.pdf
+
+    .. [4] https://www.itiis.org/digital-library/manuscript/1381
+    """
+    return _rsa_key(*args, public=True, private=False, **kwargs)
+
+
+def rsa_private_key(*args, **kwargs):
+    r"""Return the RSA *private key* pair, `(n, d)`
+
+    Parameters
+    ==========
+
+    args : naturals
+        The keyword is identical to the ``args`` in
+        :meth:`rsa_public_key`.
+
+    totient : bool, optional
+        If ``'Euler'``, it uses Euler's totient convention `\phi(n)`
+        which is :meth:`sympy.functions.combinatorial.numbers.totient` in SymPy.
+
+        If ``'Carmichael'``, it uses Carmichael's totient convention
+        `\lambda(n)` which is
+        :meth:`sympy.functions.combinatorial.numbers.reduced_totient` in SymPy.
+
+        There can be some output differences for private key generation
+        as examples below.
+
+        Example using Euler's totient:
+
+        >>> from sympy.crypto.crypto import rsa_private_key
+        >>> rsa_private_key(61, 53, 17, totient='Euler')
+        (3233, 2753)
+
+        Example using Carmichael's totient:
+
+        >>> from sympy.crypto.crypto import rsa_private_key
+        >>> rsa_private_key(61, 53, 17, totient='Carmichael')
+        (3233, 413)
+
+    index : nonnegative integer, optional
+        Returns an arbitrary solution of a RSA private key at the index
+        specified at `0, 1, 2, \dots`. This parameter needs to be
+        specified along with ``totient='Carmichael'``.
+
+        RSA private exponent is a non-unique solution of
+        `e d \mod \lambda(n) = 1` and it is possible in any form of
+        `d + k \lambda(n)`, where `d` is an another
+        already-computed private exponent, and `\lambda` is a
+        Carmichael's totient function, and `k` is any integer.
+
+        However, considering only the positive cases, there can be
+        a principal solution of a RSA private exponent `d_0` in
+        `0 < d_0 < \lambda(n)`, and all the other solutions
+        can be canonicalzed in a form of `d_0 + k \lambda(n)`.
+
+        ``index`` specifies the `k` notation to yield any possible value
+        an RSA private key can have.
+
+        An example of computing any arbitrary RSA private key:
+
+        >>> from sympy.crypto.crypto import rsa_private_key
+        >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=0)
+        (3233, 413)
+        >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=1)
+        (3233, 1193)
+        >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=2)
+        (3233, 1973)
+
+    multipower : bool, optional
+        The keyword is identical to the ``multipower`` in
+        :meth:`rsa_public_key`.
+
+    Returns
+    =======
+
+    (n, d) : int, int
+        `n` is a product of any arbitrary number of primes given as
+        the argument.
+
+        `d` is the inverse of `e` (mod `\phi(n)`) where `e` is the
+        exponent given, and `\phi` is a Euler totient.
+
+    False
+        Returned if less than two arguments are given, or `e` is
+        not relatively prime to the totient of the modulus.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import rsa_private_key
+
+    A private key of a two-prime RSA:
+
+    >>> p, q, e = 3, 5, 7
+    >>> rsa_private_key(p, q, e)
+    (15, 7)
+    >>> rsa_private_key(p, q, 30)
+    False
+
+    A private key of a multiprime RSA:
+
+    >>> primes = [2, 3, 5, 7, 11, 13]
+    >>> e = 7
+    >>> args = primes + [e]
+    >>> rsa_private_key(*args)
+    (30030, 823)
+
+    See Also
+    ========
+
+    rsa_public_key
+    encipher_rsa
+    decipher_rsa
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29
+
+    .. [2] https://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
+
+    .. [3] https://link.springer.com/content/pdf/10.1007/BFb0055738.pdf
+
+    .. [4] https://www.itiis.org/digital-library/manuscript/1381
+    """
+    return _rsa_key(*args, public=False, private=True, **kwargs)
+
+
+def _encipher_decipher_rsa(i, key, factors=None):
+    n, d = key
+    if not factors:
+        return pow(i, d, n)
+
+    def _is_coprime_set(l):
+        is_coprime_set = True
+        for i in range(len(l)):
+            for j in range(i+1, len(l)):
+                if gcd(l[i], l[j]) != 1:
+                    is_coprime_set = False
+                    break
+        return is_coprime_set
+
+    prod = reduce(lambda i, j: i*j, factors)
+    if prod == n and _is_coprime_set(factors):
+        return _decipher_rsa_crt(i, d, factors)
+    return _encipher_decipher_rsa(i, key, factors=None)
+
+
+def encipher_rsa(i, key, factors=None):
+    r"""Encrypt the plaintext with RSA.
+
+    Parameters
+    ==========
+
+    i : integer
+        The plaintext to be encrypted for.
+
+    key : (n, e) where n, e are integers
+        `n` is the modulus of the key and `e` is the exponent of the
+        key. The encryption is computed by `i^e \bmod n`.
+
+        The key can either be a public key or a private key, however,
+        the message encrypted by a public key can only be decrypted by
+        a private key, and vice versa, as RSA is an asymmetric
+        cryptography system.
+
+    factors : list of coprime integers
+        This is identical to the keyword ``factors`` in
+        :meth:`decipher_rsa`.
+
+    Notes
+    =====
+
+    Some specifications may make the RSA not cryptographically
+    meaningful.
+
+    For example, `0`, `1` will remain always same after taking any
+    number of exponentiation, thus, should be avoided.
+
+    Furthermore, if `i^e < n`, `i` may easily be figured out by taking
+    `e` th root.
+
+    And also, specifying the exponent as `1` or in more generalized form
+    as `1 + k \lambda(n)` where `k` is an nonnegative integer,
+    `\lambda` is a carmichael totient, the RSA becomes an identity
+    mapping.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import encipher_rsa
+    >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
+
+    Public Key Encryption:
+
+    >>> p, q, e = 3, 5, 7
+    >>> puk = rsa_public_key(p, q, e)
+    >>> msg = 12
+    >>> encipher_rsa(msg, puk)
+    3
+
+    Private Key Encryption:
+
+    >>> p, q, e = 3, 5, 7
+    >>> prk = rsa_private_key(p, q, e)
+    >>> msg = 12
+    >>> encipher_rsa(msg, prk)
+    3
+
+    Encryption using chinese remainder theorem:
+
+    >>> encipher_rsa(msg, prk, factors=[p, q])
+    3
+    """
+    return _encipher_decipher_rsa(i, key, factors=factors)
+
+
+def decipher_rsa(i, key, factors=None):
+    r"""Decrypt the ciphertext with RSA.
+
+    Parameters
+    ==========
+
+    i : integer
+        The ciphertext to be decrypted for.
+
+    key : (n, d) where n, d are integers
+        `n` is the modulus of the key and `d` is the exponent of the
+        key. The decryption is computed by `i^d \bmod n`.
+
+        The key can either be a public key or a private key, however,
+        the message encrypted by a public key can only be decrypted by
+        a private key, and vice versa, as RSA is an asymmetric
+        cryptography system.
+
+    factors : list of coprime integers
+        As the modulus `n` created from RSA key generation is composed
+        of arbitrary prime factors
+        `n = {p_1}^{k_1}{p_2}^{k_2}\dots{p_n}^{k_n}` where
+        `p_1, p_2, \dots, p_n` are distinct primes and
+        `k_1, k_2, \dots, k_n` are positive integers, chinese remainder
+        theorem can be used to compute `i^d \bmod n` from the
+        fragmented modulo operations like
+
+        .. math::
+            i^d \bmod {p_1}^{k_1}, i^d \bmod {p_2}^{k_2}, \dots,
+            i^d \bmod {p_n}^{k_n}
+
+        or like
+
+        .. math::
+            i^d \bmod {p_1}^{k_1}{p_2}^{k_2},
+            i^d \bmod {p_3}^{k_3}, \dots ,
+            i^d \bmod {p_n}^{k_n}
+
+        as long as every moduli does not share any common divisor each
+        other.
+
+        The raw primes used in generating the RSA key pair can be a good
+        option.
+
+        Note that the speed advantage of using this is only viable for
+        very large cases (Like 2048-bit RSA keys) since the
+        overhead of using pure Python implementation of
+        :meth:`sympy.ntheory.modular.crt` may overcompensate the
+        theoretical speed advantage.
+
+    Notes
+    =====
+
+    See the ``Notes`` section in the documentation of
+    :meth:`encipher_rsa`
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import decipher_rsa, encipher_rsa
+    >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
+
+    Public Key Encryption and Decryption:
+
+    >>> p, q, e = 3, 5, 7
+    >>> prk = rsa_private_key(p, q, e)
+    >>> puk = rsa_public_key(p, q, e)
+    >>> msg = 12
+    >>> new_msg = encipher_rsa(msg, prk)
+    >>> new_msg
+    3
+    >>> decipher_rsa(new_msg, puk)
+    12
+
+    Private Key Encryption and Decryption:
+
+    >>> p, q, e = 3, 5, 7
+    >>> prk = rsa_private_key(p, q, e)
+    >>> puk = rsa_public_key(p, q, e)
+    >>> msg = 12
+    >>> new_msg = encipher_rsa(msg, puk)
+    >>> new_msg
+    3
+    >>> decipher_rsa(new_msg, prk)
+    12
+
+    Decryption using chinese remainder theorem:
+
+    >>> decipher_rsa(new_msg, prk, factors=[p, q])
+    12
+
+    See Also
+    ========
+
+    encipher_rsa
+    """
+    return _encipher_decipher_rsa(i, key, factors=factors)
+
+
+#################### kid krypto (kid RSA) #############################
+
+
+def kid_rsa_public_key(a, b, A, B):
+    r"""
+    Kid RSA is a version of RSA useful to teach grade school children
+    since it does not involve exponentiation.
+
+    Explanation
+    ===========
+
+    Alice wants to talk to Bob. Bob generates keys as follows.
+    Key generation:
+
+    * Select positive integers `a, b, A, B` at random.
+    * Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`,
+      `n = (e d - 1)//M`.
+    * The *public key* is `(n, e)`. Bob sends these to Alice.
+    * The *private key* is `(n, d)`, which Bob keeps secret.
+
+    Encryption: If `p` is the plaintext message then the
+    ciphertext is `c = p e \pmod n`.
+
+    Decryption: If `c` is the ciphertext message then the
+    plaintext is `p = c d \pmod n`.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import kid_rsa_public_key
+    >>> a, b, A, B = 3, 4, 5, 6
+    >>> kid_rsa_public_key(a, b, A, B)
+    (369, 58)
+
+    """
+    M = a*b - 1
+    e = A*M + a
+    d = B*M + b
+    n = (e*d - 1)//M
+    return n, e
+
+
+def kid_rsa_private_key(a, b, A, B):
+    """
+    Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`,
+    `n = (e d - 1) / M`. The *private key* is `d`, which Bob
+    keeps secret.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import kid_rsa_private_key
+    >>> a, b, A, B = 3, 4, 5, 6
+    >>> kid_rsa_private_key(a, b, A, B)
+    (369, 70)
+
+    """
+    M = a*b - 1
+    e = A*M + a
+    d = B*M + b
+    n = (e*d - 1)//M
+    return n, d
+
+
+def encipher_kid_rsa(msg, key):
+    """
+    Here ``msg`` is the plaintext and ``key`` is the public key.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import (
+    ...     encipher_kid_rsa, kid_rsa_public_key)
+    >>> msg = 200
+    >>> a, b, A, B = 3, 4, 5, 6
+    >>> key = kid_rsa_public_key(a, b, A, B)
+    >>> encipher_kid_rsa(msg, key)
+    161
+
+    """
+    n, e = key
+    return (msg*e) % n
+
+
+def decipher_kid_rsa(msg, key):
+    """
+    Here ``msg`` is the plaintext and ``key`` is the private key.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import (
+    ...     kid_rsa_public_key, kid_rsa_private_key,
+    ...     decipher_kid_rsa, encipher_kid_rsa)
+    >>> a, b, A, B = 3, 4, 5, 6
+    >>> d = kid_rsa_private_key(a, b, A, B)
+    >>> msg = 200
+    >>> pub = kid_rsa_public_key(a, b, A, B)
+    >>> pri = kid_rsa_private_key(a, b, A, B)
+    >>> ct = encipher_kid_rsa(msg, pub)
+    >>> decipher_kid_rsa(ct, pri)
+    200
+
+    """
+    n, d = key
+    return (msg*d) % n
+
+
+#################### Morse Code ######################################
+
+morse_char = {
+    ".-": "A", "-...": "B",
+    "-.-.": "C", "-..": "D",
+    ".": "E", "..-.": "F",
+    "--.": "G", "....": "H",
+    "..": "I", ".---": "J",
+    "-.-": "K", ".-..": "L",
+    "--": "M", "-.": "N",
+    "---": "O", ".--.": "P",
+    "--.-": "Q", ".-.": "R",
+    "...": "S", "-": "T",
+    "..-": "U", "...-": "V",
+    ".--": "W", "-..-": "X",
+    "-.--": "Y", "--..": "Z",
+    "-----": "0", ".----": "1",
+    "..---": "2", "...--": "3",
+    "....-": "4", ".....": "5",
+    "-....": "6", "--...": "7",
+    "---..": "8", "----.": "9",
+    ".-.-.-": ".", "--..--": ",",
+    "---...": ":", "-.-.-.": ";",
+    "..--..": "?", "-....-": "-",
+    "..--.-": "_", "-.--.": "(",
+    "-.--.-": ")", ".----.": "'",
+    "-...-": "=", ".-.-.": "+",
+    "-..-.": "/", ".--.-.": "@",
+    "...-..-": "$", "-.-.--": "!"}
+char_morse = {v: k for k, v in morse_char.items()}
+
+
+def encode_morse(msg, sep='|', mapping=None):
+    """
+    Encodes a plaintext into popular Morse Code with letters
+    separated by ``sep`` and words by a double ``sep``.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import encode_morse
+    >>> msg = 'ATTACK RIGHT FLANK'
+    >>> encode_morse(msg)
+    '.-|-|-|.-|-.-.|-.-||.-.|..|--.|....|-||..-.|.-..|.-|-.|-.-'
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Morse_code
+
+    """
+
+    mapping = mapping or char_morse
+    assert sep not in mapping
+    word_sep = 2*sep
+    mapping[" "] = word_sep
+    suffix = msg and msg[-1] in whitespace
+
+    # normalize whitespace
+    msg = (' ' if word_sep else '').join(msg.split())
+    # omit unmapped chars
+    chars = set(''.join(msg.split()))
+    ok = set(mapping.keys())
+    msg = translate(msg, None, ''.join(chars - ok))
+
+    morsestring = []
+    words = msg.split()
+    for word in words:
+        morseword = []
+        for letter in word:
+            morseletter = mapping[letter]
+            morseword.append(morseletter)
+
+        word = sep.join(morseword)
+        morsestring.append(word)
+
+    return word_sep.join(morsestring) + (word_sep if suffix else '')
+
+
+def decode_morse(msg, sep='|', mapping=None):
+    """
+    Decodes a Morse Code with letters separated by ``sep``
+    (default is '|') and words by `word_sep` (default is '||)
+    into plaintext.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import decode_morse
+    >>> mc = '--|---|...-|.||.|.-|...|-'
+    >>> decode_morse(mc)
+    'MOVE EAST'
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Morse_code
+
+    """
+
+    mapping = mapping or morse_char
+    word_sep = 2*sep
+    characterstring = []
+    words = msg.strip(word_sep).split(word_sep)
+    for word in words:
+        letters = word.split(sep)
+        chars = [mapping[c] for c in letters]
+        word = ''.join(chars)
+        characterstring.append(word)
+    rv = " ".join(characterstring)
+    return rv
+
+
+#################### LFSRs  ##########################################
+
+
+@doctest_depends_on(ground_types=['python', 'gmpy'])
+def lfsr_sequence(key, fill, n):
+    r"""
+    This function creates an LFSR sequence.
+
+    Parameters
+    ==========
+
+    key : list
+        A list of finite field elements, `[c_0, c_1, \ldots, c_k].`
+
+    fill : list
+        The list of the initial terms of the LFSR sequence,
+        `[x_0, x_1, \ldots, x_k].`
+
+    n
+        Number of terms of the sequence that the function returns.
+
+    Returns
+    =======
+
+    L
+        The LFSR sequence defined by
+        `x_{n+1} = c_k x_n + \ldots + c_0 x_{n-k}`, for
+        `n \leq k`.
+
+    Notes
+    =====
+
+    S. Golomb [G]_ gives a list of three statistical properties a
+    sequence of numbers `a = \{a_n\}_{n=1}^\infty`,
+    `a_n \in \{0,1\}`, should display to be considered
+    "random". Define the autocorrelation of `a` to be
+
+    .. math::
+
+        C(k) = C(k,a) = \lim_{N\rightarrow \infty} {1\over N}\sum_{n=1}^N (-1)^{a_n + a_{n+k}}.
+
+    In the case where `a` is periodic with period
+    `P` then this reduces to
+
+    .. math::
+
+        C(k) = {1\over P}\sum_{n=1}^P (-1)^{a_n + a_{n+k}}.
+
+    Assume `a` is periodic with period `P`.
+
+    - balance:
+
+      .. math::
+
+        \left|\sum_{n=1}^P(-1)^{a_n}\right| \leq 1.
+
+    - low autocorrelation:
+
+       .. math::
+
+         C(k) = \left\{ \begin{array}{cc} 1,& k = 0,\\ \epsilon, & k \ne 0. \end{array} \right.
+
+      (For sequences satisfying these first two properties, it is known
+      that `\epsilon = -1/P` must hold.)
+
+    - proportional runs property: In each period, half the runs have
+      length `1`, one-fourth have length `2`, etc.
+      Moreover, there are as many runs of `1`'s as there are of
+      `0`'s.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import lfsr_sequence
+    >>> from sympy.polys.domains import FF
+    >>> F = FF(2)
+    >>> fill = [F(1), F(1), F(0), F(1)]
+    >>> key = [F(1), F(0), F(0), F(1)]
+    >>> lfsr_sequence(key, fill, 10)
+    [1 mod 2, 1 mod 2, 0 mod 2, 1 mod 2, 0 mod 2,
+    1 mod 2, 1 mod 2, 0 mod 2, 0 mod 2, 1 mod 2]
+
+    References
+    ==========
+
+    .. [G] Solomon Golomb, Shift register sequences, Aegean Park Press,
+       Laguna Hills, Ca, 1967
+
+    """
+    if not isinstance(key, list):
+        raise TypeError("key must be a list")
+    if not isinstance(fill, list):
+        raise TypeError("fill must be a list")
+    p = key[0].modulus()
+    F = FF(p)
+    s = fill
+    k = len(fill)
+    L = []
+    for i in range(n):
+        s0 = s[:]
+        L.append(s[0])
+        s = s[1:k]
+        x = sum(int(key[i]*s0[i]) for i in range(k))
+        s.append(F(x))
+    return L       # use [int(x) for x in L] for int version
+
+
+def lfsr_autocorrelation(L, P, k):
+    """
+    This function computes the LFSR autocorrelation function.
+
+    Parameters
+    ==========
+
+    L
+        A periodic sequence of elements of `GF(2)`.
+        L must have length larger than P.
+
+    P
+        The period of L.
+
+    k : int
+        An integer `k` (`0 < k < P`).
+
+    Returns
+    =======
+
+    autocorrelation
+        The k-th value of the autocorrelation of the LFSR L.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import (
+    ...     lfsr_sequence, lfsr_autocorrelation)
+    >>> from sympy.polys.domains import FF
+    >>> F = FF(2)
+    >>> fill = [F(1), F(1), F(0), F(1)]
+    >>> key = [F(1), F(0), F(0), F(1)]
+    >>> s = lfsr_sequence(key, fill, 20)
+    >>> lfsr_autocorrelation(s, 15, 7)
+    -1/15
+    >>> lfsr_autocorrelation(s, 15, 0)
+    1
+
+    """
+    if not isinstance(L, list):
+        raise TypeError("L (=%s) must be a list" % L)
+    P = int(P)
+    k = int(k)
+    L0 = L[:P]     # slices makes a copy
+    L1 = L0 + L0[:k]
+    L2 = [(-1)**(int(L1[i]) + int(L1[i + k])) for i in range(P)]
+    tot = sum(L2)
+    return Rational(tot, P)
+
+
+def lfsr_connection_polynomial(s):
+    """
+    This function computes the LFSR connection polynomial.
+
+    Parameters
+    ==========
+
+    s
+        A sequence of elements of even length, with entries in a finite
+        field.
+
+    Returns
+    =======
+
+    C(x)
+        The connection polynomial of a minimal LFSR yielding s.
+
+        This implements the algorithm in section 3 of J. L. Massey's
+        article [M]_.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import (
+    ...     lfsr_sequence, lfsr_connection_polynomial)
+    >>> from sympy.polys.domains import FF
+    >>> F = FF(2)
+    >>> fill = [F(1), F(1), F(0), F(1)]
+    >>> key = [F(1), F(0), F(0), F(1)]
+    >>> s = lfsr_sequence(key, fill, 20)
+    >>> lfsr_connection_polynomial(s)
+    x**4 + x + 1
+    >>> fill = [F(1), F(0), F(0), F(1)]
+    >>> key = [F(1), F(1), F(0), F(1)]
+    >>> s = lfsr_sequence(key, fill, 20)
+    >>> lfsr_connection_polynomial(s)
+    x**3 + 1
+    >>> fill = [F(1), F(0), F(1)]
+    >>> key = [F(1), F(1), F(0)]
+    >>> s = lfsr_sequence(key, fill, 20)
+    >>> lfsr_connection_polynomial(s)
+    x**3 + x**2 + 1
+    >>> fill = [F(1), F(0), F(1)]
+    >>> key = [F(1), F(0), F(1)]
+    >>> s = lfsr_sequence(key, fill, 20)
+    >>> lfsr_connection_polynomial(s)
+    x**3 + x + 1
+
+    References
+    ==========
+
+    .. [M] James L. Massey, "Shift-Register Synthesis and BCH Decoding."
+        IEEE Trans. on Information Theory, vol. 15(1), pp. 122-127,
+        Jan 1969.
+
+    """
+    # Initialization:
+    p = s[0].modulus()
+    x = Symbol("x")
+    C = 1*x**0
+    B = 1*x**0
+    m = 1
+    b = 1*x**0
+    L = 0
+    N = 0
+    while N < len(s):
+        if L > 0:
+            dC = Poly(C).degree()
+            r = min(L + 1, dC + 1)
+            coeffsC = [C.subs(x, 0)] + [C.coeff(x**i)
+                for i in range(1, dC + 1)]
+            d = (int(s[N]) + sum(coeffsC[i]*int(s[N - i])
+                for i in range(1, r))) % p
+        if L == 0:
+            d = int(s[N])*x**0
+        if d == 0:
+            m += 1
+            N += 1
+        if d > 0:
+            if 2*L > N:
+                C = (C - d*((b**(p - 2)) % p)*x**m*B).expand()
+                m += 1
+                N += 1
+            else:
+                T = C
+                C = (C - d*((b**(p - 2)) % p)*x**m*B).expand()
+                L = N + 1 - L
+                m = 1
+                b = d
+                B = T
+                N += 1
+    dC = Poly(C).degree()
+    coeffsC = [C.subs(x, 0)] + [C.coeff(x**i) for i in range(1, dC + 1)]
+    return sum(coeffsC[i] % p*x**i for i in range(dC + 1)
+        if coeffsC[i] is not None)
+
+
+#################### ElGamal  #############################
+
+
+def elgamal_private_key(digit=10, seed=None):
+    r"""
+    Return three number tuple as private key.
+
+    Explanation
+    ===========
+
+    Elgamal encryption is based on the mathematical problem
+    called the Discrete Logarithm Problem (DLP). For example,
+
+    `a^{b} \equiv c \pmod p`
+
+    In general, if ``a`` and ``b`` are known, ``ct`` is easily
+    calculated. If ``b`` is unknown, it is hard to use
+    ``a`` and ``ct`` to get ``b``.
+
+    Parameters
+    ==========
+
+    digit : int
+        Minimum number of binary digits for key.
+
+    Returns
+    =======
+
+    tuple : (p, r, d)
+        p = prime number.
+
+        r = primitive root.
+
+        d = random number.
+
+    Notes
+    =====
+
+    For testing purposes, the ``seed`` parameter may be set to control
+    the output of this routine. See sympy.core.random._randrange.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import elgamal_private_key
+    >>> from sympy.ntheory import is_primitive_root, isprime
+    >>> a, b, _ = elgamal_private_key()
+    >>> isprime(a)
+    True
+    >>> is_primitive_root(b, a)
+    True
+
+    """
+    randrange = _randrange(seed)
+    p = nextprime(2**digit)
+    return p, primitive_root(p), randrange(2, p)
+
+
+def elgamal_public_key(key):
+    r"""
+    Return three number tuple as public key.
+
+    Parameters
+    ==========
+
+    key : (p, r, e)
+        Tuple generated by ``elgamal_private_key``.
+
+    Returns
+    =======
+
+    tuple : (p, r, e)
+        `e = r**d \bmod p`
+
+        `d` is a random number in private key.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import elgamal_public_key
+    >>> elgamal_public_key((1031, 14, 636))
+    (1031, 14, 212)
+
+    """
+    p, r, e = key
+    return p, r, pow(r, e, p)
+
+
+def encipher_elgamal(i, key, seed=None):
+    r"""
+    Encrypt message with public key.
+
+    Explanation
+    ===========
+
+    ``i`` is a plaintext message expressed as an integer.
+    ``key`` is public key (p, r, e). In order to encrypt
+    a message, a random number ``a`` in ``range(2, p)``
+    is generated and the encrypted message is returned as
+    `c_{1}` and `c_{2}` where:
+
+    `c_{1} \equiv r^{a} \pmod p`
+
+    `c_{2} \equiv m e^{a} \pmod p`
+
+    Parameters
+    ==========
+
+    msg
+        int of encoded message.
+
+    key
+        Public key.
+
+    Returns
+    =======
+
+    tuple : (c1, c2)
+        Encipher into two number.
+
+    Notes
+    =====
+
+    For testing purposes, the ``seed`` parameter may be set to control
+    the output of this routine. See sympy.core.random._randrange.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import encipher_elgamal, elgamal_private_key, elgamal_public_key
+    >>> pri = elgamal_private_key(5, seed=[3]); pri
+    (37, 2, 3)
+    >>> pub = elgamal_public_key(pri); pub
+    (37, 2, 8)
+    >>> msg = 36
+    >>> encipher_elgamal(msg, pub, seed=[3])
+    (8, 6)
+
+    """
+    p, r, e = key
+    if i < 0 or i >= p:
+        raise ValueError(
+            'Message (%s) should be in range(%s)' % (i, p))
+    randrange = _randrange(seed)
+    a = randrange(2, p)
+    return pow(r, a, p), i*pow(e, a, p) % p
+
+
+def decipher_elgamal(msg, key):
+    r"""
+    Decrypt message with private key.
+
+    `msg = (c_{1}, c_{2})`
+
+    `key = (p, r, d)`
+
+    According to extended Eucliden theorem,
+    `u c_{1}^{d} + p n = 1`
+
+    `u \equiv 1/{{c_{1}}^d} \pmod p`
+
+    `u c_{2} \equiv \frac{1}{c_{1}^d} c_{2} \equiv \frac{1}{r^{ad}} c_{2} \pmod p`
+
+    `\frac{1}{r^{ad}} m e^a \equiv \frac{1}{r^{ad}} m {r^{d a}} \equiv m \pmod p`
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import decipher_elgamal
+    >>> from sympy.crypto.crypto import encipher_elgamal
+    >>> from sympy.crypto.crypto import elgamal_private_key
+    >>> from sympy.crypto.crypto import elgamal_public_key
+
+    >>> pri = elgamal_private_key(5, seed=[3])
+    >>> pub = elgamal_public_key(pri); pub
+    (37, 2, 8)
+    >>> msg = 17
+    >>> decipher_elgamal(encipher_elgamal(msg, pub), pri) == msg
+    True
+
+    """
+    p, _, d = key
+    c1, c2 = msg
+    u = pow(c1, -d, p)
+    return u * c2 % p
+
+
+################ Diffie-Hellman Key Exchange  #########################
+
+def dh_private_key(digit=10, seed=None):
+    r"""
+    Return three integer tuple as private key.
+
+    Explanation
+    ===========
+
+    Diffie-Hellman key exchange is based on the mathematical problem
+    called the Discrete Logarithm Problem (see ElGamal).
+
+    Diffie-Hellman key exchange is divided into the following steps:
+
+    *   Alice and Bob agree on a base that consist of a prime ``p``
+        and a primitive root of ``p`` called ``g``
+    *   Alice choses a number ``a`` and Bob choses a number ``b`` where
+        ``a`` and ``b`` are random numbers in range `[2, p)`. These are
+        their private keys.
+    *   Alice then publicly sends Bob `g^{a} \pmod p` while Bob sends
+        Alice `g^{b} \pmod p`
+    *   They both raise the received value to their secretly chosen
+        number (``a`` or ``b``) and now have both as their shared key
+        `g^{ab} \pmod p`
+
+    Parameters
+    ==========
+
+    digit
+        Minimum number of binary digits required in key.
+
+    Returns
+    =======
+
+    tuple : (p, g, a)
+        p = prime number.
+
+        g = primitive root of p.
+
+        a = random number from 2 through p - 1.
+
+    Notes
+    =====
+
+    For testing purposes, the ``seed`` parameter may be set to control
+    the output of this routine. See sympy.core.random._randrange.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import dh_private_key
+    >>> from sympy.ntheory import isprime, is_primitive_root
+    >>> p, g, _ = dh_private_key()
+    >>> isprime(p)
+    True
+    >>> is_primitive_root(g, p)
+    True
+    >>> p, g, _ = dh_private_key(5)
+    >>> isprime(p)
+    True
+    >>> is_primitive_root(g, p)
+    True
+
+    """
+    p = nextprime(2**digit)
+    g = primitive_root(p)
+    randrange = _randrange(seed)
+    a = randrange(2, p)
+    return p, g, a
+
+
+def dh_public_key(key):
+    r"""
+    Return three number tuple as public key.
+
+    This is the tuple that Alice sends to Bob.
+
+    Parameters
+    ==========
+
+    key : (p, g, a)
+        A tuple generated by ``dh_private_key``.
+
+    Returns
+    =======
+
+    tuple : int, int, int
+        A tuple of `(p, g, g^a \mod p)` with `p`, `g` and `a` given as
+        parameters.s
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import dh_private_key, dh_public_key
+    >>> p, g, a = dh_private_key();
+    >>> _p, _g, x = dh_public_key((p, g, a))
+    >>> p == _p and g == _g
+    True
+    >>> x == pow(g, a, p)
+    True
+
+    """
+    p, g, a = key
+    return p, g, pow(g, a, p)
+
+
+def dh_shared_key(key, b):
+    """
+    Return an integer that is the shared key.
+
+    This is what Bob and Alice can both calculate using the public
+    keys they received from each other and their private keys.
+
+    Parameters
+    ==========
+
+    key : (p, g, x)
+        Tuple `(p, g, x)` generated by ``dh_public_key``.
+
+    b
+        Random number in the range of `2` to `p - 1`
+        (Chosen by second key exchange member (Bob)).
+
+    Returns
+    =======
+
+    int
+        A shared key.
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import (
+    ...     dh_private_key, dh_public_key, dh_shared_key)
+    >>> prk = dh_private_key();
+    >>> p, g, x = dh_public_key(prk);
+    >>> sk = dh_shared_key((p, g, x), 1000)
+    >>> sk == pow(x, 1000, p)
+    True
+
+    """
+    p, _, x = key
+    if 1 >= b or b >= p:
+        raise ValueError(filldedent('''
+            Value of b should be greater 1 and less
+            than prime %s.''' % p))
+
+    return pow(x, b, p)
+
+
+################ Goldwasser-Micali Encryption  #########################
+
+
+def _legendre(a, p):
+    """
+    Returns the legendre symbol of a and p
+    assuming that p is a prime.
+
+    i.e. 1 if a is a quadratic residue mod p
+        -1 if a is not a quadratic residue mod p
+         0 if a is divisible by p
+
+    Parameters
+    ==========
+
+    a : int
+        The number to test.
+
+    p : prime
+        The prime to test ``a`` against.
+
+    Returns
+    =======
+
+    int
+        Legendre symbol (a / p).
+
+    """
+    sig = pow(a, (p - 1)//2, p)
+    if sig == 1:
+        return 1
+    elif sig == 0:
+        return 0
+    else:
+        return -1
+
+
+def _random_coprime_stream(n, seed=None):
+    randrange = _randrange(seed)
+    while True:
+        y = randrange(n)
+        if gcd(y, n) == 1:
+            yield y
+
+
+def gm_private_key(p, q, a=None):
+    r"""
+    Check if ``p`` and ``q`` can be used as private keys for
+    the Goldwasser-Micali encryption. The method works
+    roughly as follows.
+
+    Explanation
+    ===========
+
+    #. Pick two large primes $p$ and $q$.
+    #. Call their product $N$.
+    #. Given a message as an integer $i$, write $i$ in its bit representation $b_0, \dots, b_n$.
+    #. For each $k$,
+
+     if $b_k = 0$:
+        let $a_k$ be a random square
+        (quadratic residue) modulo $p q$
+        such that ``jacobi_symbol(a, p*q) = 1``
+     if $b_k = 1$:
+        let $a_k$ be a random non-square
+        (non-quadratic residue) modulo $p q$
+        such that ``jacobi_symbol(a, p*q) = 1``
+
+    returns $\left[a_1, a_2, \dots\right]$
+
+    $b_k$ can be recovered by checking whether or not
+    $a_k$ is a residue. And from the $b_k$'s, the message
+    can be reconstructed.
+
+    The idea is that, while ``jacobi_symbol(a, p*q)``
+    can be easily computed (and when it is equal to $-1$ will
+    tell you that $a$ is not a square mod $p q$), quadratic
+    residuosity modulo a composite number is hard to compute
+    without knowing its factorization.
+
+    Moreover, approximately half the numbers coprime to $p q$ have
+    :func:`~.jacobi_symbol` equal to $1$ . And among those, approximately half
+    are residues and approximately half are not. This maximizes the
+    entropy of the code.
+
+    Parameters
+    ==========
+
+    p, q, a
+        Initialization variables.
+
+    Returns
+    =======
+
+    tuple : (p, q)
+        The input value ``p`` and ``q``.
+
+    Raises
+    ======
+
+    ValueError
+        If ``p`` and ``q`` are not distinct odd primes.
+
+    """
+    if p == q:
+        raise ValueError("expected distinct primes, "
+                         "got two copies of %i" % p)
+    elif not isprime(p) or not isprime(q):
+        raise ValueError("first two arguments must be prime, "
+                         "got %i of %i" % (p, q))
+    elif p == 2 or q == 2:
+        raise ValueError("first two arguments must not be even, "
+                         "got %i of %i" % (p, q))
+    return p, q
+
+
+def gm_public_key(p, q, a=None, seed=None):
+    """
+    Compute public keys for ``p`` and ``q``.
+    Note that in Goldwasser-Micali Encryption,
+    public keys are randomly selected.
+
+    Parameters
+    ==========
+
+    p, q, a : int, int, int
+        Initialization variables.
+
+    Returns
+    =======
+
+    tuple : (a, N)
+        ``a`` is the input ``a`` if it is not ``None`` otherwise
+        some random integer coprime to ``p`` and ``q``.
+
+        ``N`` is the product of ``p`` and ``q``.
+
+    """
+
+    p, q = gm_private_key(p, q)
+    N = p * q
+
+    if a is None:
+        randrange = _randrange(seed)
+        while True:
+            a = randrange(N)
+            if _legendre(a, p) == _legendre(a, q) == -1:
+                break
+    else:
+        if _legendre(a, p) != -1 or _legendre(a, q) != -1:
+            return False
+    return (a, N)
+
+
+def encipher_gm(i, key, seed=None):
+    """
+    Encrypt integer 'i' using public_key 'key'
+    Note that gm uses random encryption.
+
+    Parameters
+    ==========
+
+    i : int
+        The message to encrypt.
+
+    key : (a, N)
+        The public key.
+
+    Returns
+    =======
+
+    list : list of int
+        The randomized encrypted message.
+
+    """
+    if i < 0:
+        raise ValueError(
+            "message must be a non-negative "
+            "integer: got %d instead" % i)
+    a, N = key
+    bits = []
+    while i > 0:
+        bits.append(i % 2)
+        i //= 2
+
+    gen = _random_coprime_stream(N, seed)
+    rev = reversed(bits)
+    encode = lambda b: next(gen)**2*pow(a, b) % N
+    return [ encode(b) for b in rev ]
+
+
+
+def decipher_gm(message, key):
+    """
+    Decrypt message 'message' using public_key 'key'.
+
+    Parameters
+    ==========
+
+    message : list of int
+        The randomized encrypted message.
+
+    key : (p, q)
+        The private key.
+
+    Returns
+    =======
+
+    int
+        The encrypted message.
+
+    """
+    p, q = key
+    res = lambda m, p: _legendre(m, p) > 0
+    bits = [res(m, p) * res(m, q) for m in message]
+    m = 0
+    for b in bits:
+        m <<= 1
+        m += not b
+    return m
+
+
+
+########### RailFence Cipher #############
+
+def encipher_railfence(message,rails):
+    """
+    Performs Railfence Encryption on plaintext and returns ciphertext
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import encipher_railfence
+    >>> message = "hello world"
+    >>> encipher_railfence(message,3)
+    'horel ollwd'
+
+    Parameters
+    ==========
+
+    message : string, the message to encrypt.
+    rails : int, the number of rails.
+
+    Returns
+    =======
+
+    The Encrypted string message.
+
+    References
+    ==========
+    .. [1] https://en.wikipedia.org/wiki/Rail_fence_cipher
+
+    """
+    r = list(range(rails))
+    p = cycle(r + r[-2:0:-1])
+    return ''.join(sorted(message, key=lambda i: next(p)))
+
+
+def decipher_railfence(ciphertext,rails):
+    """
+    Decrypt the message using the given rails
+
+    Examples
+    ========
+
+    >>> from sympy.crypto.crypto import decipher_railfence
+    >>> decipher_railfence("horel ollwd",3)
+    'hello world'
+
+    Parameters
+    ==========
+
+    message : string, the message to encrypt.
+    rails : int, the number of rails.
+
+    Returns
+    =======
+
+    The Decrypted string message.
+
+    """
+    r = list(range(rails))
+    p = cycle(r + r[-2:0:-1])
+
+    idx = sorted(range(len(ciphertext)), key=lambda i: next(p))
+    res = [''] * len(ciphertext)
+    for i, c in zip(idx, ciphertext):
+        res[i] = c
+    return ''.join(res)
+
+
+################ Blum-Goldwasser cryptosystem  #########################
+
+def bg_private_key(p, q):
+    """
+    Check if p and q can be used as private keys for
+    the Blum-Goldwasser cryptosystem.
+
+    Explanation
+    ===========
+
+    The three necessary checks for p and q to pass
+    so that they can be used as private keys:
+
+        1. p and q must both be prime
+        2. p and q must be distinct
+        3. p and q must be congruent to 3 mod 4
+
+    Parameters
+    ==========
+
+    p, q
+        The keys to be checked.
+
+    Returns
+    =======
+
+    p, q
+        Input values.
+
+    Raises
+    ======
+
+    ValueError
+        If p and q do not pass the above conditions.
+
+    """
+
+    if not isprime(p) or not isprime(q):
+        raise ValueError("the two arguments must be prime, "
+                         "got %i and %i" %(p, q))
+    elif p == q:
+        raise ValueError("the two arguments must be distinct, "
+                         "got two copies of %i. " %p)
+    elif (p - 3) % 4 != 0 or (q - 3) % 4 != 0:
+        raise ValueError("the two arguments must be congruent to 3 mod 4, "
+                         "got %i and %i" %(p, q))
+    return p, q
+
+def bg_public_key(p, q):
+    """
+    Calculates public keys from private keys.
+
+    Explanation
+    ===========
+
+    The function first checks the validity of
+    private keys passed as arguments and
+    then returns their product.
+
+    Parameters
+    ==========
+
+    p, q
+        The private keys.
+
+    Returns
+    =======
+
+    N
+        The public key.
+
+    """
+    p, q = bg_private_key(p, q)
+    N = p * q
+    return N
+
+def encipher_bg(i, key, seed=None):
+    """
+    Encrypts the message using public key and seed.
+
+    Explanation
+    ===========
+
+    ALGORITHM:
+        1. Encodes i as a string of L bits, m.
+        2. Select a random element r, where 1 < r < key, and computes
+           x = r^2 mod key.
+        3. Use BBS pseudo-random number generator to generate L random bits, b,
+        using the initial seed as x.
+        4. Encrypted message, c_i = m_i XOR b_i, 1 <= i <= L.
+        5. x_L = x^(2^L) mod key.
+        6. Return (c, x_L)
+
+    Parameters
+    ==========
+
+    i
+        Message, a non-negative integer
+
+    key
+        The public key
+
+    Returns
+    =======
+
+    Tuple
+        (encrypted_message, x_L)
+
+    Raises
+    ======
+
+    ValueError
+        If i is negative.
+
+    """
+
+    if i < 0:
+        raise ValueError(
+            "message must be a non-negative "
+            "integer: got %d instead" % i)
+
+    enc_msg = []
+    while i > 0:
+        enc_msg.append(i % 2)
+        i //= 2
+    enc_msg.reverse()
+    L = len(enc_msg)
+
+    r = _randint(seed)(2, key - 1)
+    x = r**2 % key
+    x_L = pow(int(x), int(2**L), int(key))
+
+    rand_bits = []
+    for _ in range(L):
+        rand_bits.append(x % 2)
+        x = x**2 % key
+
+    encrypt_msg = [m ^ b for (m, b) in zip(enc_msg, rand_bits)]
+
+    return (encrypt_msg, x_L)
+
+def decipher_bg(message, key):
+    """
+    Decrypts the message using private keys.
+
+    Explanation
+    ===========
+
+    ALGORITHM:
+        1. Let, c be the encrypted message, y the second number received,
+        and p and q be the private keys.
+        2. Compute, r_p = y^((p+1)/4 ^ L) mod p and
+        r_q = y^((q+1)/4 ^ L) mod q.
+        3. Compute x_0 = (q(q^-1 mod p)r_p + p(p^-1 mod q)r_q) mod N.
+        4. From, recompute the bits using the BBS generator, as in the
+        encryption algorithm.
+        5. Compute original message by XORing c and b.
+
+    Parameters
+    ==========
+
+    message
+        Tuple of encrypted message and a non-negative integer.
+
+    key
+        Tuple of private keys.
+
+    Returns
+    =======
+
+    orig_msg
+        The original message
+
+    """
+
+    p, q = key
+    encrypt_msg, y = message
+    public_key = p * q
+    L = len(encrypt_msg)
+    p_t = ((p + 1)/4)**L
+    q_t = ((q + 1)/4)**L
+    r_p = pow(int(y), int(p_t), int(p))
+    r_q = pow(int(y), int(q_t), int(q))
+
+    x = (q * invert(q, p) * r_p + p * invert(p, q) * r_q) % public_key
+
+    orig_bits = []
+    for _ in range(L):
+        orig_bits.append(x % 2)
+        x = x**2 % public_key
+
+    orig_msg = 0
+    for (m, b) in zip(encrypt_msg, orig_bits):
+        orig_msg = orig_msg * 2
+        orig_msg += (m ^ b)
+
+    return orig_msg
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/crypto/tests/test_crypto.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/crypto/tests/test_crypto.py
new file mode 100644
index 0000000000000000000000000000000000000000..c671138f9a61325f6e65cc7cafddc7cd46f19229
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/crypto/tests/test_crypto.py
@@ -0,0 +1,562 @@
+from sympy.core import symbols
+from sympy.crypto.crypto import (cycle_list,
+      encipher_shift, encipher_affine, encipher_substitution,
+      check_and_join, encipher_vigenere, decipher_vigenere,
+      encipher_hill, decipher_hill, encipher_bifid5, encipher_bifid6,
+      bifid5_square, bifid6_square, bifid5, bifid6,
+      decipher_bifid5, decipher_bifid6, encipher_kid_rsa,
+      decipher_kid_rsa, kid_rsa_private_key, kid_rsa_public_key,
+      decipher_rsa, rsa_private_key, rsa_public_key, encipher_rsa,
+      lfsr_connection_polynomial, lfsr_autocorrelation, lfsr_sequence,
+      encode_morse, decode_morse, elgamal_private_key, elgamal_public_key,
+      encipher_elgamal, decipher_elgamal, dh_private_key, dh_public_key,
+      dh_shared_key, decipher_shift, decipher_affine, encipher_bifid,
+      decipher_bifid, bifid_square, padded_key, uniq, decipher_gm,
+      encipher_gm, gm_public_key, gm_private_key, encipher_bg, decipher_bg,
+      bg_private_key, bg_public_key, encipher_rot13, decipher_rot13,
+      encipher_atbash, decipher_atbash, NonInvertibleCipherWarning,
+      encipher_railfence, decipher_railfence)
+from sympy.external.gmpy import gcd
+from sympy.matrices import Matrix
+from sympy.ntheory import isprime, is_primitive_root
+from sympy.polys.domains import FF
+
+from sympy.testing.pytest import raises, warns
+
+from sympy.core.random import randrange
+
+def test_encipher_railfence():
+    assert encipher_railfence("hello world",2) == "hlowrdel ol"
+    assert encipher_railfence("hello world",3) == "horel ollwd"
+    assert encipher_railfence("hello world",4) == "hwe olordll"
+
+def test_decipher_railfence():
+    assert decipher_railfence("hlowrdel ol",2) == "hello world"
+    assert decipher_railfence("horel ollwd",3) == "hello world"
+    assert decipher_railfence("hwe olordll",4) == "hello world"
+
+
+def test_cycle_list():
+    assert cycle_list(3, 4) == [3, 0, 1, 2]
+    assert cycle_list(-1, 4) == [3, 0, 1, 2]
+    assert cycle_list(1, 4) == [1, 2, 3, 0]
+
+
+def test_encipher_shift():
+    assert encipher_shift("ABC", 0) == "ABC"
+    assert encipher_shift("ABC", 1) == "BCD"
+    assert encipher_shift("ABC", -1) == "ZAB"
+    assert decipher_shift("ZAB", -1) == "ABC"
+
+def test_encipher_rot13():
+    assert encipher_rot13("ABC") == "NOP"
+    assert encipher_rot13("NOP") == "ABC"
+    assert decipher_rot13("ABC") == "NOP"
+    assert decipher_rot13("NOP") == "ABC"
+
+
+def test_encipher_affine():
+    assert encipher_affine("ABC", (1, 0)) == "ABC"
+    assert encipher_affine("ABC", (1, 1)) == "BCD"
+    assert encipher_affine("ABC", (-1, 0)) == "AZY"
+    assert encipher_affine("ABC", (-1, 1), symbols="ABCD") == "BAD"
+    assert encipher_affine("123", (-1, 1), symbols="1234") == "214"
+    assert encipher_affine("ABC", (3, 16)) == "QTW"
+    assert decipher_affine("QTW", (3, 16)) == "ABC"
+
+def test_encipher_atbash():
+    assert encipher_atbash("ABC") == "ZYX"
+    assert encipher_atbash("ZYX") == "ABC"
+    assert decipher_atbash("ABC") == "ZYX"
+    assert decipher_atbash("ZYX") == "ABC"
+
+def test_encipher_substitution():
+    assert encipher_substitution("ABC", "BAC", "ABC") == "BAC"
+    assert encipher_substitution("123", "1243", "1234") == "124"
+
+
+def test_check_and_join():
+    assert check_and_join("abc") == "abc"
+    assert check_and_join(uniq("aaabc")) == "abc"
+    assert check_and_join("ab c".split()) == "abc"
+    assert check_and_join("abc", "a", filter=True) == "a"
+    raises(ValueError, lambda: check_and_join('ab', 'a'))
+
+
+def test_encipher_vigenere():
+    assert encipher_vigenere("ABC", "ABC") == "ACE"
+    assert encipher_vigenere("ABC", "ABC", symbols="ABCD") == "ACA"
+    assert encipher_vigenere("ABC", "AB", symbols="ABCD") == "ACC"
+    assert encipher_vigenere("AB", "ABC", symbols="ABCD") == "AC"
+    assert encipher_vigenere("A", "ABC", symbols="ABCD") == "A"
+
+
+def test_decipher_vigenere():
+    assert decipher_vigenere("ABC", "ABC") == "AAA"
+    assert decipher_vigenere("ABC", "ABC", symbols="ABCD") == "AAA"
+    assert decipher_vigenere("ABC", "AB", symbols="ABCD") == "AAC"
+    assert decipher_vigenere("AB", "ABC", symbols="ABCD") == "AA"
+    assert decipher_vigenere("A", "ABC", symbols="ABCD") == "A"
+
+
+def test_encipher_hill():
+    A = Matrix(2, 2, [1, 2, 3, 5])
+    assert encipher_hill("ABCD", A) == "CFIV"
+    A = Matrix(2, 2, [1, 0, 0, 1])
+    assert encipher_hill("ABCD", A) == "ABCD"
+    assert encipher_hill("ABCD", A, symbols="ABCD") == "ABCD"
+    A = Matrix(2, 2, [1, 2, 3, 5])
+    assert encipher_hill("ABCD", A, symbols="ABCD") == "CBAB"
+    assert encipher_hill("AB", A, symbols="ABCD") == "CB"
+    # message length, n, does not need to be a multiple of k;
+    # it is padded
+    assert encipher_hill("ABA", A) == "CFGC"
+    assert encipher_hill("ABA", A, pad="Z") == "CFYV"
+
+
+def test_decipher_hill():
+    A = Matrix(2, 2, [1, 2, 3, 5])
+    assert decipher_hill("CFIV", A) == "ABCD"
+    A = Matrix(2, 2, [1, 0, 0, 1])
+    assert decipher_hill("ABCD", A) == "ABCD"
+    assert decipher_hill("ABCD", A, symbols="ABCD") == "ABCD"
+    A = Matrix(2, 2, [1, 2, 3, 5])
+    assert decipher_hill("CBAB", A, symbols="ABCD") == "ABCD"
+    assert decipher_hill("CB", A, symbols="ABCD") == "AB"
+    # n does not need to be a multiple of k
+    assert decipher_hill("CFA", A) == "ABAA"
+
+
+def test_encipher_bifid5():
+    assert encipher_bifid5("AB", "AB") == "AB"
+    assert encipher_bifid5("AB", "CD") == "CO"
+    assert encipher_bifid5("ab", "c") == "CH"
+    assert encipher_bifid5("a bc", "b") == "BAC"
+
+
+def test_bifid5_square():
+    A = bifid5
+    f = lambda i, j: symbols(A[5*i + j])
+    M = Matrix(5, 5, f)
+    assert bifid5_square("") == M
+
+
+def test_decipher_bifid5():
+    assert decipher_bifid5("AB", "AB") == "AB"
+    assert decipher_bifid5("CO", "CD") == "AB"
+    assert decipher_bifid5("ch", "c") == "AB"
+    assert decipher_bifid5("b ac", "b") == "ABC"
+
+
+def test_encipher_bifid6():
+    assert encipher_bifid6("AB", "AB") == "AB"
+    assert encipher_bifid6("AB", "CD") == "CP"
+    assert encipher_bifid6("ab", "c") == "CI"
+    assert encipher_bifid6("a bc", "b") == "BAC"
+
+
+def test_decipher_bifid6():
+    assert decipher_bifid6("AB", "AB") == "AB"
+    assert decipher_bifid6("CP", "CD") == "AB"
+    assert decipher_bifid6("ci", "c") == "AB"
+    assert decipher_bifid6("b ac", "b") == "ABC"
+
+
+def test_bifid6_square():
+    A = bifid6
+    f = lambda i, j: symbols(A[6*i + j])
+    M = Matrix(6, 6, f)
+    assert bifid6_square("") == M
+
+
+def test_rsa_public_key():
+    assert rsa_public_key(2, 3, 1) == (6, 1)
+    assert rsa_public_key(5, 3, 3) == (15, 3)
+
+    with warns(NonInvertibleCipherWarning):
+        assert rsa_public_key(2, 2, 1) == (4, 1)
+        assert rsa_public_key(8, 8, 8) is False
+
+
+def test_rsa_private_key():
+    assert rsa_private_key(2, 3, 1) == (6, 1)
+    assert rsa_private_key(5, 3, 3) == (15, 3)
+    assert rsa_private_key(23,29,5) == (667,493)
+
+    with warns(NonInvertibleCipherWarning):
+        assert rsa_private_key(2, 2, 1) == (4, 1)
+        assert rsa_private_key(8, 8, 8) is False
+
+
+def test_rsa_large_key():
+    # Sample from
+    # http://www.herongyang.com/Cryptography/JCE-Public-Key-RSA-Private-Public-Key-Pair-Sample.html
+    p = int('101565610013301240713207239558950144682174355406589305284428666'\
+        '903702505233009')
+    q = int('894687191887545488935455605955948413812376003053143521429242133'\
+        '12069293984003')
+    e = int('65537')
+    d = int('893650581832704239530398858744759129594796235440844479456143566'\
+        '6999402846577625762582824202269399672579058991442587406384754958587'\
+        '400493169361356902030209')
+    assert rsa_public_key(p, q, e) == (p*q, e)
+    assert rsa_private_key(p, q, e) == (p*q, d)
+
+
+def test_encipher_rsa():
+    puk = rsa_public_key(2, 3, 1)
+    assert encipher_rsa(2, puk) == 2
+    puk = rsa_public_key(5, 3, 3)
+    assert encipher_rsa(2, puk) == 8
+
+    with warns(NonInvertibleCipherWarning):
+        puk = rsa_public_key(2, 2, 1)
+        assert encipher_rsa(2, puk) == 2
+
+
+def test_decipher_rsa():
+    prk = rsa_private_key(2, 3, 1)
+    assert decipher_rsa(2, prk) == 2
+    prk = rsa_private_key(5, 3, 3)
+    assert decipher_rsa(8, prk) == 2
+
+    with warns(NonInvertibleCipherWarning):
+        prk = rsa_private_key(2, 2, 1)
+        assert decipher_rsa(2, prk) == 2
+
+
+def test_mutltiprime_rsa_full_example():
+    # Test example from
+    # https://iopscience.iop.org/article/10.1088/1742-6596/995/1/012030
+    puk = rsa_public_key(2, 3, 5, 7, 11, 13, 7)
+    prk = rsa_private_key(2, 3, 5, 7, 11, 13, 7)
+    assert puk == (30030, 7)
+    assert prk == (30030, 823)
+
+    msg = 10
+    encrypted = encipher_rsa(2 * msg - 15, puk)
+    assert encrypted == 18065
+    decrypted = (decipher_rsa(encrypted, prk) + 15) / 2
+    assert decrypted == msg
+
+    # Test example from
+    # https://www.scirp.org/pdf/JCC_2018032215502008.pdf
+    puk1 = rsa_public_key(53, 41, 43, 47, 41)
+    prk1 = rsa_private_key(53, 41, 43, 47, 41)
+    puk2 = rsa_public_key(53, 41, 43, 47, 97)
+    prk2 = rsa_private_key(53, 41, 43, 47, 97)
+
+    assert puk1 == (4391633, 41)
+    assert prk1 == (4391633, 294041)
+    assert puk2 == (4391633, 97)
+    assert prk2 == (4391633, 455713)
+
+    msg = 12321
+    encrypted = encipher_rsa(encipher_rsa(msg, puk1), puk2)
+    assert encrypted == 1081588
+    decrypted = decipher_rsa(decipher_rsa(encrypted, prk2), prk1)
+    assert decrypted == msg
+
+
+def test_rsa_crt_extreme():
+    p = int(
+        '10177157607154245068023861503693082120906487143725062283406501' \
+        '54082258226204046999838297167140821364638180697194879500245557' \
+        '65445186962893346463841419427008800341257468600224049986260471' \
+        '92257248163014468841725476918639415726709736077813632961290911' \
+        '0256421232977833028677441206049309220354796014376698325101693')
+
+    q = int(
+        '28752342353095132872290181526607275886182793241660805077850801' \
+        '75689512797754286972952273553128181861830576836289738668745250' \
+        '34028199691128870676414118458442900035778874482624765513861643' \
+        '27966696316822188398336199002306588703902894100476186823849595' \
+        '103239410527279605442148285816149368667083114802852804976893')
+
+    r = int(
+        '17698229259868825776879500736350186838850961935956310134378261' \
+        '89771862186717463067541369694816245225291921138038800171125596' \
+        '07315449521981157084370187887650624061033066022458512942411841' \
+        '18747893789972315277160085086164119879536041875335384844820566' \
+        '0287479617671726408053319619892052000850883994343378882717849')
+
+    s = int(
+        '68925428438585431029269182233502611027091755064643742383515623' \
+        '64321310582896893395529367074942808353187138794422745718419645' \
+        '28291231865157212604266903677599180789896916456120289112752835' \
+        '98502265889669730331688206825220074713977607415178738015831030' \
+        '364290585369150502819743827343552098197095520550865360159439'
+    )
+
+    t = int(
+        '69035483433453632820551311892368908779778144568711455301541094' \
+        '31487047642322695357696860925747923189635033183069823820910521' \
+        '71172909106797748883261493224162414050106920442445896819806600' \
+        '15448444826108008217972129130625571421904893252804729877353352' \
+        '739420480574842850202181462656251626522910618936534699566291'
+    )
+
+    e = 65537
+    puk = rsa_public_key(p, q, r, s, t, e)
+    prk = rsa_private_key(p, q, r, s, t, e)
+
+    plaintext = 1000
+    ciphertext_1 = encipher_rsa(plaintext, puk)
+    ciphertext_2 = encipher_rsa(plaintext, puk, [p, q, r, s, t])
+    assert ciphertext_1 == ciphertext_2
+    assert decipher_rsa(ciphertext_1, prk) == \
+        decipher_rsa(ciphertext_1, prk, [p, q, r, s, t])
+
+
+def test_rsa_exhaustive():
+    p, q = 61, 53
+    e = 17
+    puk = rsa_public_key(p, q, e, totient='Carmichael')
+    prk = rsa_private_key(p, q, e, totient='Carmichael')
+
+    for msg in range(puk[0]):
+        encrypted = encipher_rsa(msg, puk)
+        decrypted = decipher_rsa(encrypted, prk)
+        try:
+            assert decrypted == msg
+        except AssertionError:
+            raise AssertionError(
+                "The RSA is not correctly decrypted " \
+                "(Original : {}, Encrypted : {}, Decrypted : {})" \
+                .format(msg, encrypted, decrypted)
+                )
+
+
+def test_rsa_multiprime_exhanstive():
+    primes = [3, 5, 7, 11]
+    e = 7
+    args = primes + [e]
+    puk = rsa_public_key(*args, totient='Carmichael')
+    prk = rsa_private_key(*args, totient='Carmichael')
+    n = puk[0]
+
+    for msg in range(n):
+        encrypted = encipher_rsa(msg, puk)
+        decrypted = decipher_rsa(encrypted, prk)
+        try:
+            assert decrypted == msg
+        except AssertionError:
+            raise AssertionError(
+                "The RSA is not correctly decrypted " \
+                "(Original : {}, Encrypted : {}, Decrypted : {})" \
+                .format(msg, encrypted, decrypted)
+                )
+
+
+def test_rsa_multipower_exhanstive():
+    primes = [5, 5, 7]
+    e = 7
+    args = primes + [e]
+    puk = rsa_public_key(*args, multipower=True)
+    prk = rsa_private_key(*args, multipower=True)
+    n = puk[0]
+
+    for msg in range(n):
+        if gcd(msg, n) != 1:
+            continue
+
+        encrypted = encipher_rsa(msg, puk)
+        decrypted = decipher_rsa(encrypted, prk)
+        try:
+            assert decrypted == msg
+        except AssertionError:
+            raise AssertionError(
+                "The RSA is not correctly decrypted " \
+                "(Original : {}, Encrypted : {}, Decrypted : {})" \
+                .format(msg, encrypted, decrypted)
+                )
+
+
+def test_kid_rsa_public_key():
+    assert kid_rsa_public_key(1, 2, 1, 1) == (5, 2)
+    assert kid_rsa_public_key(1, 2, 2, 1) == (8, 3)
+    assert kid_rsa_public_key(1, 2, 1, 2) == (7, 2)
+
+
+def test_kid_rsa_private_key():
+    assert kid_rsa_private_key(1, 2, 1, 1) == (5, 3)
+    assert kid_rsa_private_key(1, 2, 2, 1) == (8, 3)
+    assert kid_rsa_private_key(1, 2, 1, 2) == (7, 4)
+
+
+def test_encipher_kid_rsa():
+    assert encipher_kid_rsa(1, (5, 2)) == 2
+    assert encipher_kid_rsa(1, (8, 3)) == 3
+    assert encipher_kid_rsa(1, (7, 2)) == 2
+
+
+def test_decipher_kid_rsa():
+    assert decipher_kid_rsa(2, (5, 3)) == 1
+    assert decipher_kid_rsa(3, (8, 3)) == 1
+    assert decipher_kid_rsa(2, (7, 4)) == 1
+
+
+def test_encode_morse():
+    assert encode_morse('ABC') == '.-|-...|-.-.'
+    assert encode_morse('SMS ') == '...|--|...||'
+    assert encode_morse('SMS\n') == '...|--|...||'
+    assert encode_morse('') == ''
+    assert encode_morse(' ') == '||'
+    assert encode_morse(' ', sep='`') == '``'
+    assert encode_morse(' ', sep='``') == '````'
+    assert encode_morse('!@#$%^&*()_+') == '-.-.--|.--.-.|...-..-|-.--.|-.--.-|..--.-|.-.-.'
+    assert encode_morse('12345') == '.----|..---|...--|....-|.....'
+    assert encode_morse('67890') == '-....|--...|---..|----.|-----'
+
+
+def test_decode_morse():
+    assert decode_morse('-.-|.|-.--') == 'KEY'
+    assert decode_morse('.-.|..-|-.||') == 'RUN'
+    raises(KeyError, lambda: decode_morse('.....----'))
+
+
+def test_lfsr_sequence():
+    raises(TypeError, lambda: lfsr_sequence(1, [1], 1))
+    raises(TypeError, lambda: lfsr_sequence([1], 1, 1))
+    F = FF(2)
+    assert lfsr_sequence([F(1)], [F(1)], 2) == [F(1), F(1)]
+    assert lfsr_sequence([F(0)], [F(1)], 2) == [F(1), F(0)]
+    F = FF(3)
+    assert lfsr_sequence([F(1)], [F(1)], 2) == [F(1), F(1)]
+    assert lfsr_sequence([F(0)], [F(2)], 2) == [F(2), F(0)]
+    assert lfsr_sequence([F(1)], [F(2)], 2) == [F(2), F(2)]
+
+
+def test_lfsr_autocorrelation():
+    raises(TypeError, lambda: lfsr_autocorrelation(1, 2, 3))
+    F = FF(2)
+    s = lfsr_sequence([F(1), F(0)], [F(0), F(1)], 5)
+    assert lfsr_autocorrelation(s, 2, 0) == 1
+    assert lfsr_autocorrelation(s, 2, 1) == -1
+
+
+def test_lfsr_connection_polynomial():
+    F = FF(2)
+    x = symbols("x")
+    s = lfsr_sequence([F(1), F(0)], [F(0), F(1)], 5)
+    assert lfsr_connection_polynomial(s) == x**2 + 1
+    s = lfsr_sequence([F(1), F(1)], [F(0), F(1)], 5)
+    assert lfsr_connection_polynomial(s) == x**2 + x + 1
+
+
+def test_elgamal_private_key():
+    a, b, _ = elgamal_private_key(digit=100)
+    assert isprime(a)
+    assert is_primitive_root(b, a)
+    assert len(bin(a)) >= 102
+
+
+def test_elgamal():
+    dk = elgamal_private_key(5)
+    ek = elgamal_public_key(dk)
+    P = ek[0]
+    assert P - 1 == decipher_elgamal(encipher_elgamal(P - 1, ek), dk)
+    raises(ValueError, lambda: encipher_elgamal(P, dk))
+    raises(ValueError, lambda: encipher_elgamal(-1, dk))
+
+
+def test_dh_private_key():
+    p, g, _ = dh_private_key(digit = 100)
+    assert isprime(p)
+    assert is_primitive_root(g, p)
+    assert len(bin(p)) >= 102
+
+
+def test_dh_public_key():
+    p1, g1, a = dh_private_key(digit = 100)
+    p2, g2, ga = dh_public_key((p1, g1, a))
+    assert p1 == p2
+    assert g1 == g2
+    assert ga == pow(g1, a, p1)
+
+
+def test_dh_shared_key():
+    prk = dh_private_key(digit = 100)
+    p, _, ga = dh_public_key(prk)
+    b = randrange(2, p)
+    sk = dh_shared_key((p, _, ga), b)
+    assert sk == pow(ga, b, p)
+    raises(ValueError, lambda: dh_shared_key((1031, 14, 565), 2000))
+
+
+def test_padded_key():
+    assert padded_key('b', 'ab') == 'ba'
+    raises(ValueError, lambda: padded_key('ab', 'ace'))
+    raises(ValueError, lambda: padded_key('ab', 'abba'))
+
+
+def test_bifid():
+    raises(ValueError, lambda: encipher_bifid('abc', 'b', 'abcde'))
+    assert encipher_bifid('abc', 'b', 'abcd') == 'bdb'
+    raises(ValueError, lambda: decipher_bifid('bdb', 'b', 'abcde'))
+    assert encipher_bifid('bdb', 'b', 'abcd') == 'abc'
+    raises(ValueError, lambda: bifid_square('abcde'))
+    assert bifid5_square("B") == \
+        bifid5_square('BACDEFGHIKLMNOPQRSTUVWXYZ')
+    assert bifid6_square('B0') == \
+        bifid6_square('B0ACDEFGHIJKLMNOPQRSTUVWXYZ123456789')
+
+
+def test_encipher_decipher_gm():
+    ps = [131, 137, 139, 149, 151, 157, 163, 167,
+          173, 179, 181, 191, 193, 197, 199]
+    qs = [89, 97, 101, 103, 107, 109, 113, 127,
+          131, 137, 139, 149, 151, 157, 47]
+    messages = [
+        0, 32855, 34303, 14805, 1280, 75859, 38368,
+        724, 60356, 51675, 76697, 61854, 18661,
+    ]
+    for p, q in zip(ps, qs):
+        pri = gm_private_key(p, q)
+        for msg in messages:
+            pub = gm_public_key(p, q)
+            enc = encipher_gm(msg, pub)
+            dec = decipher_gm(enc, pri)
+            assert dec == msg
+
+
+def test_gm_private_key():
+    raises(ValueError, lambda: gm_public_key(13, 15))
+    raises(ValueError, lambda: gm_public_key(0, 0))
+    raises(ValueError, lambda: gm_public_key(0, 5))
+    assert 17, 19 == gm_public_key(17, 19)
+
+
+def test_gm_public_key():
+    assert 323 == gm_public_key(17, 19)[1]
+    assert 15  == gm_public_key(3, 5)[1]
+    raises(ValueError, lambda: gm_public_key(15, 19))
+
+def test_encipher_decipher_bg():
+    ps = [67, 7, 71, 103, 11, 43, 107, 47,
+          79, 19, 83, 23, 59, 127, 31]
+    qs = qs = [7, 71, 103, 11, 43, 107, 47,
+               79, 19, 83, 23, 59, 127, 31, 67]
+    messages = [
+        0, 328, 343, 148, 1280, 758, 383,
+        724, 603, 516, 766, 618, 186,
+    ]
+
+    for p, q in zip(ps, qs):
+        pri = bg_private_key(p, q)
+        for msg in messages:
+            pub = bg_public_key(p, q)
+            enc = encipher_bg(msg, pub)
+            dec = decipher_bg(enc, pri)
+            assert dec == msg
+
+def test_bg_private_key():
+    raises(ValueError, lambda: bg_private_key(8, 16))
+    raises(ValueError, lambda: bg_private_key(8, 8))
+    raises(ValueError, lambda: bg_private_key(13, 17))
+    assert 23, 31 == bg_private_key(23, 31)
+
+def test_bg_public_key():
+    assert 5293 == bg_public_key(67, 79)
+    assert 713 == bg_public_key(23, 31)
+    raises(ValueError, lambda: bg_private_key(13, 17))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..968c4caa0d4562b71285f414bfb70f43d0b35111
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/__init__.py
@@ -0,0 +1,20 @@
+"""This module contains functions which operate on discrete sequences.
+
+Transforms - ``fft``, ``ifft``, ``ntt``, ``intt``, ``fwht``, ``ifwht``,
+            ``mobius_transform``, ``inverse_mobius_transform``
+
+Convolutions - ``convolution``, ``convolution_fft``, ``convolution_ntt``,
+            ``convolution_fwht``, ``convolution_subset``,
+            ``covering_product``, ``intersecting_product``
+"""
+
+from .transforms import (fft, ifft, ntt, intt, fwht, ifwht,
+    mobius_transform, inverse_mobius_transform)
+from .convolutions import convolution, covering_product, intersecting_product
+
+__all__ = [
+    'fft', 'ifft', 'ntt', 'intt', 'fwht', 'ifwht', 'mobius_transform',
+    'inverse_mobius_transform',
+
+    'convolution', 'covering_product', 'intersecting_product',
+]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b656c16e55d8f2e08f288fceaa5bc42b9358beb2
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/convolutions.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/convolutions.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..554ec31f8d72eb92fbba6042d5a1ad5dfb036752
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/convolutions.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/transforms.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/transforms.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5f4575aa6803102602c323ad5f613778a7098533
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/__pycache__/transforms.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/convolutions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/convolutions.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac9a3dbbb26b8b117ea1ee99cf7ebabbd21322cc
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/convolutions.py
@@ -0,0 +1,597 @@
+"""
+Convolution (using **FFT**, **NTT**, **FWHT**), Subset Convolution,
+Covering Product, Intersecting Product
+"""
+
+from sympy.core import S, sympify, Rational
+from sympy.core.function import expand_mul
+from sympy.discrete.transforms import (
+    fft, ifft, ntt, intt, fwht, ifwht,
+    mobius_transform, inverse_mobius_transform)
+from sympy.external.gmpy import MPZ, lcm
+from sympy.utilities.iterables import iterable
+from sympy.utilities.misc import as_int
+
+
+def convolution(a, b, cycle=0, dps=None, prime=None, dyadic=None, subset=None):
+    """
+    Performs convolution by determining the type of desired
+    convolution using hints.
+
+    Exactly one of ``dps``, ``prime``, ``dyadic``, ``subset`` arguments
+    should be specified explicitly for identifying the type of convolution,
+    and the argument ``cycle`` can be specified optionally.
+
+    For the default arguments, linear convolution is performed using **FFT**.
+
+    Parameters
+    ==========
+
+    a, b : iterables
+        The sequences for which convolution is performed.
+    cycle : Integer
+        Specifies the length for doing cyclic convolution.
+    dps : Integer
+        Specifies the number of decimal digits for precision for
+        performing **FFT** on the sequence.
+    prime : Integer
+        Prime modulus of the form `(m 2^k + 1)` to be used for
+        performing **NTT** on the sequence.
+    dyadic : bool
+        Identifies the convolution type as dyadic (*bitwise-XOR*)
+        convolution, which is performed using **FWHT**.
+    subset : bool
+        Identifies the convolution type as subset convolution.
+
+    Examples
+    ========
+
+    >>> from sympy import convolution, symbols, S, I
+    >>> u, v, w, x, y, z = symbols('u v w x y z')
+
+    >>> convolution([1 + 2*I, 4 + 3*I], [S(5)/4, 6], dps=3)
+    [1.25 + 2.5*I, 11.0 + 15.8*I, 24.0 + 18.0*I]
+    >>> convolution([1, 2, 3], [4, 5, 6], cycle=3)
+    [31, 31, 28]
+
+    >>> convolution([111, 777], [888, 444], prime=19*2**10 + 1)
+    [1283, 19351, 14219]
+    >>> convolution([111, 777], [888, 444], prime=19*2**10 + 1, cycle=2)
+    [15502, 19351]
+
+    >>> convolution([u, v], [x, y, z], dyadic=True)
+    [u*x + v*y, u*y + v*x, u*z, v*z]
+    >>> convolution([u, v], [x, y, z], dyadic=True, cycle=2)
+    [u*x + u*z + v*y, u*y + v*x + v*z]
+
+    >>> convolution([u, v, w], [x, y, z], subset=True)
+    [u*x, u*y + v*x, u*z + w*x, v*z + w*y]
+    >>> convolution([u, v, w], [x, y, z], subset=True, cycle=3)
+    [u*x + v*z + w*y, u*y + v*x, u*z + w*x]
+
+    """
+
+    c = as_int(cycle)
+    if c < 0:
+        raise ValueError("The length for cyclic convolution "
+                        "must be non-negative")
+
+    dyadic = True if dyadic else None
+    subset = True if subset else None
+    if sum(x is not None for x in (prime, dps, dyadic, subset)) > 1:
+        raise TypeError("Ambiguity in determining the type of convolution")
+
+    if prime is not None:
+        ls = convolution_ntt(a, b, prime=prime)
+        return ls if not c else [sum(ls[i::c]) % prime for i in range(c)]
+
+    if dyadic:
+        ls = convolution_fwht(a, b)
+    elif subset:
+        ls = convolution_subset(a, b)
+    else:
+        def loop(a):
+            dens = []
+            for i in a:
+                if isinstance(i, Rational) and i.q - 1:
+                    dens.append(i.q)
+                elif not isinstance(i, int):
+                    return
+            if dens:
+                l = lcm(*dens)
+                return [i*l if type(i) is int else i.p*(l//i.q) for i in a], l
+            # no lcm of den to deal with
+            return a, 1
+        ls = None
+        da = loop(a)
+        if da is not None:
+            db = loop(b)
+            if db is not None:
+                (ia, ma), (ib, mb) = da, db
+                den = ma*mb
+                ls = convolution_int(ia, ib)
+                if den != 1:
+                    ls = [Rational(i, den) for i in ls]
+        if ls is None:
+            ls = convolution_fft(a, b, dps)
+
+    return ls if not c else [sum(ls[i::c]) for i in range(c)]
+
+
+#----------------------------------------------------------------------------#
+#                                                                            #
+#                       Convolution for Complex domain                       #
+#                                                                            #
+#----------------------------------------------------------------------------#
+
+def convolution_fft(a, b, dps=None):
+    """
+    Performs linear convolution using Fast Fourier Transform.
+
+    Parameters
+    ==========
+
+    a, b : iterables
+        The sequences for which convolution is performed.
+    dps : Integer
+        Specifies the number of decimal digits for precision.
+
+    Examples
+    ========
+
+    >>> from sympy import S, I
+    >>> from sympy.discrete.convolutions import convolution_fft
+
+    >>> convolution_fft([2, 3], [4, 5])
+    [8, 22, 15]
+    >>> convolution_fft([2, 5], [6, 7, 3])
+    [12, 44, 41, 15]
+    >>> convolution_fft([1 + 2*I, 4 + 3*I], [S(5)/4, 6])
+    [5/4 + 5*I/2, 11 + 63*I/4, 24 + 18*I]
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Convolution_theorem
+    .. [2] https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general%29
+
+    """
+
+    a, b = a[:], b[:]
+    n = m = len(a) + len(b) - 1 # convolution size
+
+    if n > 0 and n&(n - 1): # not a power of 2
+        n = 2**n.bit_length()
+
+    # padding with zeros
+    a += [S.Zero]*(n - len(a))
+    b += [S.Zero]*(n - len(b))
+
+    a, b = fft(a, dps), fft(b, dps)
+    a = [expand_mul(x*y) for x, y in zip(a, b)]
+    a = ifft(a, dps)[:m]
+
+    return a
+
+
+#----------------------------------------------------------------------------#
+#                                                                            #
+#                           Convolution for GF(p)                            #
+#                                                                            #
+#----------------------------------------------------------------------------#
+
+def convolution_ntt(a, b, prime):
+    """
+    Performs linear convolution using Number Theoretic Transform.
+
+    Parameters
+    ==========
+
+    a, b : iterables
+        The sequences for which convolution is performed.
+    prime : Integer
+        Prime modulus of the form `(m 2^k + 1)` to be used for performing
+        **NTT** on the sequence.
+
+    Examples
+    ========
+
+    >>> from sympy.discrete.convolutions import convolution_ntt
+    >>> convolution_ntt([2, 3], [4, 5], prime=19*2**10 + 1)
+    [8, 22, 15]
+    >>> convolution_ntt([2, 5], [6, 7, 3], prime=19*2**10 + 1)
+    [12, 44, 41, 15]
+    >>> convolution_ntt([333, 555], [222, 666], prime=19*2**10 + 1)
+    [15555, 14219, 19404]
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Convolution_theorem
+    .. [2] https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general%29
+
+    """
+
+    a, b, p = a[:], b[:], as_int(prime)
+    n = m = len(a) + len(b) - 1 # convolution size
+
+    if n > 0 and n&(n - 1): # not a power of 2
+        n = 2**n.bit_length()
+
+    # padding with zeros
+    a += [0]*(n - len(a))
+    b += [0]*(n - len(b))
+
+    a, b = ntt(a, p), ntt(b, p)
+    a = [x*y % p for x, y in zip(a, b)]
+    a = intt(a, p)[:m]
+
+    return a
+
+
+#----------------------------------------------------------------------------#
+#                                                                            #
+#                         Convolution for 2**n-group                         #
+#                                                                            #
+#----------------------------------------------------------------------------#
+
+def convolution_fwht(a, b):
+    """
+    Performs dyadic (*bitwise-XOR*) convolution using Fast Walsh Hadamard
+    Transform.
+
+    The convolution is automatically padded to the right with zeros, as the
+    *radix-2 FWHT* requires the number of sample points to be a power of 2.
+
+    Parameters
+    ==========
+
+    a, b : iterables
+        The sequences for which convolution is performed.
+
+    Examples
+    ========
+
+    >>> from sympy import symbols, S, I
+    >>> from sympy.discrete.convolutions import convolution_fwht
+
+    >>> u, v, x, y = symbols('u v x y')
+    >>> convolution_fwht([u, v], [x, y])
+    [u*x + v*y, u*y + v*x]
+
+    >>> convolution_fwht([2, 3], [4, 5])
+    [23, 22]
+    >>> convolution_fwht([2, 5 + 4*I, 7], [6*I, 7, 3 + 4*I])
+    [56 + 68*I, -10 + 30*I, 6 + 50*I, 48 + 32*I]
+
+    >>> convolution_fwht([S(33)/7, S(55)/6, S(7)/4], [S(2)/3, 5])
+    [2057/42, 1870/63, 7/6, 35/4]
+
+    References
+    ==========
+
+    .. [1] https://www.radioeng.cz/fulltexts/2002/02_03_40_42.pdf
+    .. [2] https://en.wikipedia.org/wiki/Hadamard_transform
+
+    """
+
+    if not a or not b:
+        return []
+
+    a, b = a[:], b[:]
+    n = max(len(a), len(b))
+
+    if n&(n - 1): # not a power of 2
+        n = 2**n.bit_length()
+
+    # padding with zeros
+    a += [S.Zero]*(n - len(a))
+    b += [S.Zero]*(n - len(b))
+
+    a, b = fwht(a), fwht(b)
+    a = [expand_mul(x*y) for x, y in zip(a, b)]
+    a = ifwht(a)
+
+    return a
+
+
+#----------------------------------------------------------------------------#
+#                                                                            #
+#                            Subset Convolution                              #
+#                                                                            #
+#----------------------------------------------------------------------------#
+
+def convolution_subset(a, b):
+    """
+    Performs Subset Convolution of given sequences.
+
+    The indices of each argument, considered as bit strings, correspond to
+    subsets of a finite set.
+
+    The sequence is automatically padded to the right with zeros, as the
+    definition of subset based on bitmasks (indices) requires the size of
+    sequence to be a power of 2.
+
+    Parameters
+    ==========
+
+    a, b : iterables
+        The sequences for which convolution is performed.
+
+    Examples
+    ========
+
+    >>> from sympy import symbols, S
+    >>> from sympy.discrete.convolutions import convolution_subset
+    >>> u, v, x, y, z = symbols('u v x y z')
+
+    >>> convolution_subset([u, v], [x, y])
+    [u*x, u*y + v*x]
+    >>> convolution_subset([u, v, x], [y, z])
+    [u*y, u*z + v*y, x*y, x*z]
+
+    >>> convolution_subset([1, S(2)/3], [3, 4])
+    [3, 6]
+    >>> convolution_subset([1, 3, S(5)/7], [7])
+    [7, 21, 5, 0]
+
+    References
+    ==========
+
+    .. [1] https://people.csail.mit.edu/rrw/presentations/subset-conv.pdf
+
+    """
+
+    if not a or not b:
+        return []
+
+    if not iterable(a) or not iterable(b):
+        raise TypeError("Expected a sequence of coefficients for convolution")
+
+    a = [sympify(arg) for arg in a]
+    b = [sympify(arg) for arg in b]
+    n = max(len(a), len(b))
+
+    if n&(n - 1): # not a power of 2
+        n = 2**n.bit_length()
+
+    # padding with zeros
+    a += [S.Zero]*(n - len(a))
+    b += [S.Zero]*(n - len(b))
+
+    c = [S.Zero]*n
+
+    for mask in range(n):
+        smask = mask
+        while smask > 0:
+            c[mask] += expand_mul(a[smask] * b[mask^smask])
+            smask = (smask - 1)&mask
+
+        c[mask] += expand_mul(a[smask] * b[mask^smask])
+
+    return c
+
+
+#----------------------------------------------------------------------------#
+#                                                                            #
+#                              Covering Product                              #
+#                                                                            #
+#----------------------------------------------------------------------------#
+
+def covering_product(a, b):
+    """
+    Returns the covering product of given sequences.
+
+    The indices of each argument, considered as bit strings, correspond to
+    subsets of a finite set.
+
+    The covering product of given sequences is a sequence which contains
+    the sum of products of the elements of the given sequences grouped by
+    the *bitwise-OR* of the corresponding indices.
+
+    The sequence is automatically padded to the right with zeros, as the
+    definition of subset based on bitmasks (indices) requires the size of
+    sequence to be a power of 2.
+
+    Parameters
+    ==========
+
+    a, b : iterables
+        The sequences for which covering product is to be obtained.
+
+    Examples
+    ========
+
+    >>> from sympy import symbols, S, I, covering_product
+    >>> u, v, x, y, z = symbols('u v x y z')
+
+    >>> covering_product([u, v], [x, y])
+    [u*x, u*y + v*x + v*y]
+    >>> covering_product([u, v, x], [y, z])
+    [u*y, u*z + v*y + v*z, x*y, x*z]
+
+    >>> covering_product([1, S(2)/3], [3, 4 + 5*I])
+    [3, 26/3 + 25*I/3]
+    >>> covering_product([1, 3, S(5)/7], [7, 8])
+    [7, 53, 5, 40/7]
+
+    References
+    ==========
+
+    .. [1] https://people.csail.mit.edu/rrw/presentations/subset-conv.pdf
+
+    """
+
+    if not a or not b:
+        return []
+
+    a, b = a[:], b[:]
+    n = max(len(a), len(b))
+
+    if n&(n - 1): # not a power of 2
+        n = 2**n.bit_length()
+
+    # padding with zeros
+    a += [S.Zero]*(n - len(a))
+    b += [S.Zero]*(n - len(b))
+
+    a, b = mobius_transform(a), mobius_transform(b)
+    a = [expand_mul(x*y) for x, y in zip(a, b)]
+    a = inverse_mobius_transform(a)
+
+    return a
+
+
+#----------------------------------------------------------------------------#
+#                                                                            #
+#                            Intersecting Product                            #
+#                                                                            #
+#----------------------------------------------------------------------------#
+
+def intersecting_product(a, b):
+    """
+    Returns the intersecting product of given sequences.
+
+    The indices of each argument, considered as bit strings, correspond to
+    subsets of a finite set.
+
+    The intersecting product of given sequences is the sequence which
+    contains the sum of products of the elements of the given sequences
+    grouped by the *bitwise-AND* of the corresponding indices.
+
+    The sequence is automatically padded to the right with zeros, as the
+    definition of subset based on bitmasks (indices) requires the size of
+    sequence to be a power of 2.
+
+    Parameters
+    ==========
+
+    a, b : iterables
+        The sequences for which intersecting product is to be obtained.
+
+    Examples
+    ========
+
+    >>> from sympy import symbols, S, I, intersecting_product
+    >>> u, v, x, y, z = symbols('u v x y z')
+
+    >>> intersecting_product([u, v], [x, y])
+    [u*x + u*y + v*x, v*y]
+    >>> intersecting_product([u, v, x], [y, z])
+    [u*y + u*z + v*y + x*y + x*z, v*z, 0, 0]
+
+    >>> intersecting_product([1, S(2)/3], [3, 4 + 5*I])
+    [9 + 5*I, 8/3 + 10*I/3]
+    >>> intersecting_product([1, 3, S(5)/7], [7, 8])
+    [327/7, 24, 0, 0]
+
+    References
+    ==========
+
+    .. [1] https://people.csail.mit.edu/rrw/presentations/subset-conv.pdf
+
+    """
+
+    if not a or not b:
+        return []
+
+    a, b = a[:], b[:]
+    n = max(len(a), len(b))
+
+    if n&(n - 1): # not a power of 2
+        n = 2**n.bit_length()
+
+    # padding with zeros
+    a += [S.Zero]*(n - len(a))
+    b += [S.Zero]*(n - len(b))
+
+    a, b = mobius_transform(a, subset=False), mobius_transform(b, subset=False)
+    a = [expand_mul(x*y) for x, y in zip(a, b)]
+    a = inverse_mobius_transform(a, subset=False)
+
+    return a
+
+
+#----------------------------------------------------------------------------#
+#                                                                            #
+#                            Integer Convolutions                            #
+#                                                                            #
+#----------------------------------------------------------------------------#
+
+def convolution_int(a, b):
+    """Return the convolution of two sequences as a list.
+
+    The iterables must consist solely of integers.
+
+    Parameters
+    ==========
+
+    a, b : Sequence
+        The sequences for which convolution is performed.
+
+    Explanation
+    ===========
+
+    This function performs the convolution of ``a`` and ``b`` by packing
+    each into a single integer, multiplying them together, and then
+    unpacking the result from the product.  The intuition behind this is
+    that if we evaluate some polynomial [1]:
+
+    .. math ::
+        1156x^6 + 3808x^5 + 8440x^4 + 14856x^3 + 16164x^2 + 14040x + 8100
+
+    at say $x = 10^5$ we obtain $1156038080844014856161641404008100$.
+    Note we can read of the coefficients for each term every five digits.
+    If the $x$ we chose to evaluate at is large enough, the same will hold
+    for the product.
+
+    The idea now is since big integer multiplication in libraries such
+    as GMP is highly optimised, this will be reasonably fast.
+
+    Examples
+    ========
+
+    >>> from sympy.discrete.convolutions import convolution_int
+
+    >>> convolution_int([2, 3], [4, 5])
+    [8, 22, 15]
+    >>> convolution_int([1, 1, -1], [1, 1])
+    [1, 2, 0, -1]
+
+    References
+    ==========
+
+    .. [1] Fateman, Richard J.
+           Can you save time in multiplying polynomials by encoding them as integers?
+           University of California, Berkeley, California (2004).
+           https://people.eecs.berkeley.edu/~fateman/papers/polysbyGMP.pdf
+    """
+    # An upper bound on the largest coefficient in p(x)q(x) is given by (1 + min(dp, dq))N(p)N(q)
+    # where dp = deg(p), dq = deg(q), N(f) denotes the coefficient of largest modulus in f [1]
+    B = max(abs(c) for c in a)*max(abs(c) for c in b)*(1 + min(len(a) - 1, len(b) - 1))
+    x, power = MPZ(1), 0
+    while x <= (2*B):  # multiply by two for negative coefficients, see [1]
+        x <<= 1
+        power += 1
+
+    def to_integer(poly):
+        n, mul = MPZ(0), 0
+        for c in reversed(poly):
+            if c and not mul: mul = -1 if c < 0 else 1
+            n <<= power
+            n += mul*int(c)
+        return mul, n
+
+    # Perform packing and multiplication
+    (a_mul, a_packed), (b_mul, b_packed) = to_integer(a), to_integer(b)
+    result = a_packed * b_packed
+
+    # Perform unpacking
+    mul = a_mul * b_mul
+    mask, half, borrow, poly = x - 1, x >> 1, 0, []
+    while result or borrow:
+        coeff = (result & mask) + borrow
+        result >>= power
+        borrow = coeff >= half
+        poly.append(mul * int(coeff if coeff < half else coeff - x))
+    return poly or [0]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/recurrences.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/recurrences.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b0ed80d304161cf9ca298321aedc094c8cae1b3
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/recurrences.py
@@ -0,0 +1,166 @@
+"""
+Recurrences
+"""
+
+from sympy.core import S, sympify
+from sympy.utilities.iterables import iterable
+from sympy.utilities.misc import as_int
+
+
+def linrec(coeffs, init, n):
+    r"""
+    Evaluation of univariate linear recurrences of homogeneous type
+    having coefficients independent of the recurrence variable.
+
+    Parameters
+    ==========
+
+    coeffs : iterable
+        Coefficients of the recurrence
+    init : iterable
+        Initial values of the recurrence
+    n : Integer
+        Point of evaluation for the recurrence
+
+    Notes
+    =====
+
+    Let `y(n)` be the recurrence of given type, ``c`` be the sequence
+    of coefficients, ``b`` be the sequence of initial/base values of the
+    recurrence and ``k`` (equal to ``len(c)``) be the order of recurrence.
+    Then,
+
+    .. math :: y(n) = \begin{cases} b_n & 0 \le n < k \\
+        c_0 y(n-1) + c_1 y(n-2) + \cdots + c_{k-1} y(n-k) & n \ge k
+        \end{cases}
+
+    Let `x_0, x_1, \ldots, x_n` be a sequence and consider the transformation
+    that maps each polynomial `f(x)` to `T(f(x))` where each power `x^i` is
+    replaced by the corresponding value `x_i`. The sequence is then a solution
+    of the recurrence if and only if `T(x^i p(x)) = 0` for each `i \ge 0` where
+    `p(x) = x^k - c_0 x^(k-1) - \cdots - c_{k-1}` is the characteristic
+    polynomial.
+
+    Then `T(f(x)p(x)) = 0` for each polynomial `f(x)` (as it is a linear
+    combination of powers `x^i`). Now, if `x^n` is congruent to
+    `g(x) = a_0 x^0 + a_1 x^1 + \cdots + a_{k-1} x^{k-1}` modulo `p(x)`, then
+    `T(x^n) = x_n` is equal to
+    `T(g(x)) = a_0 x_0 + a_1 x_1 + \cdots + a_{k-1} x_{k-1}`.
+
+    Computation of `x^n`,
+    given `x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}`
+    is performed using exponentiation by squaring (refer to [1_]) with
+    an additional reduction step performed to retain only first `k` powers
+    of `x` in the representation of `x^n`.
+
+    Examples
+    ========
+
+    >>> from sympy.discrete.recurrences import linrec
+    >>> from sympy.abc import x, y, z
+
+    >>> linrec(coeffs=[1, 1], init=[0, 1], n=10)
+    55
+
+    >>> linrec(coeffs=[1, 1], init=[x, y], n=10)
+    34*x + 55*y
+
+    >>> linrec(coeffs=[x, y], init=[0, 1], n=5)
+    x**2*y + x*(x**3 + 2*x*y) + y**2
+
+    >>> linrec(coeffs=[1, 2, 3, 0, 0, 4], init=[x, y, z], n=16)
+    13576*x + 5676*y + 2356*z
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Exponentiation_by_squaring
+    .. [2] https://en.wikipedia.org/w/index.php?title=Modular_exponentiation§ion=6#Matrices
+
+    See Also
+    ========
+
+    sympy.polys.agca.extensions.ExtensionElement.__pow__
+
+    """
+
+    if not coeffs:
+        return S.Zero
+
+    if not iterable(coeffs):
+        raise TypeError("Expected a sequence of coefficients for"
+                        " the recurrence")
+
+    if not iterable(init):
+        raise TypeError("Expected a sequence of values for the initialization"
+                        " of the recurrence")
+
+    n = as_int(n)
+    if n < 0:
+        raise ValueError("Point of evaluation of recurrence must be a "
+                        "non-negative integer")
+
+    c = [sympify(arg) for arg in coeffs]
+    b = [sympify(arg) for arg in init]
+    k = len(c)
+
+    if len(b) > k:
+        raise TypeError("Count of initial values should not exceed the "
+                        "order of the recurrence")
+    else:
+        b += [S.Zero]*(k - len(b)) # remaining initial values default to zero
+
+    if n < k:
+        return b[n]
+    terms = [u*v for u, v in zip(linrec_coeffs(c, n), b)]
+    return sum(terms[:-1], terms[-1])
+
+
+def linrec_coeffs(c, n):
+    r"""
+    Compute the coefficients of n'th term in linear recursion
+    sequence defined by c.
+
+    `x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}`.
+
+    It computes the coefficients by using binary exponentiation.
+    This function is used by `linrec` and `_eval_pow_by_cayley`.
+
+    Parameters
+    ==========
+
+    c = coefficients of the divisor polynomial
+    n = exponent of x, so dividend is x^n
+
+    """
+
+    k = len(c)
+
+    def _square_and_reduce(u, offset):
+        # squares `(u_0 + u_1 x + u_2 x^2 + \cdots + u_{k-1} x^k)` (and
+        # multiplies by `x` if offset is 1) and reduces the above result of
+        # length upto `2k` to `k` using the characteristic equation of the
+        # recurrence given by, `x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}`
+
+        w = [S.Zero]*(2*len(u) - 1 + offset)
+        for i, p in enumerate(u):
+            for j, q in enumerate(u):
+                w[offset + i + j] += p*q
+
+        for j in range(len(w) - 1, k - 1, -1):
+            for i in range(k):
+                w[j - i - 1] += w[j]*c[i]
+
+        return w[:k]
+
+    def _final_coeffs(n):
+        # computes the final coefficient list - `cf` corresponding to the
+        # point at which recurrence is to be evalauted - `n`, such that,
+        # `y(n) = cf_0 y(k-1) + cf_1 y(k-2) + \cdots + cf_{k-1} y(0)`
+
+        if n < k:
+            return [S.Zero]*n + [S.One] + [S.Zero]*(k - n - 1)
+        else:
+            return _square_and_reduce(_final_coeffs(n // 2), n % 2)
+
+    return _final_coeffs(n)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/tests/test_convolutions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/tests/test_convolutions.py
new file mode 100644
index 0000000000000000000000000000000000000000..96e5fc801ac63f95c01eb18d48143ae3a1ac6222
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/tests/test_convolutions.py
@@ -0,0 +1,392 @@
+from sympy.core.numbers import (E, Rational, pi)
+from sympy.functions.elementary.exponential import exp
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.core import S, symbols, I
+from sympy.discrete.convolutions import (
+    convolution, convolution_fft, convolution_ntt, convolution_fwht,
+    convolution_subset, covering_product, intersecting_product,
+    convolution_int)
+from sympy.testing.pytest import raises
+from sympy.abc import x, y
+
+def test_convolution():
+    # fft
+    a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)]
+    b = [9, 5, 5, 4, 3, 2]
+    c = [3, 5, 3, 7, 8]
+    d = [1422, 6572, 3213, 5552]
+    e = [-1, Rational(5, 3), Rational(7, 5)]
+
+    assert convolution(a, b) == convolution_fft(a, b)
+    assert convolution(a, b, dps=9) == convolution_fft(a, b, dps=9)
+    assert convolution(a, d, dps=7) == convolution_fft(d, a, dps=7)
+    assert convolution(a, d[1:], dps=3) == convolution_fft(d[1:], a, dps=3)
+
+    # prime moduli of the form (m*2**k + 1), sequence length
+    # should be a divisor of 2**k
+    p = 7*17*2**23 + 1
+    q = 19*2**10 + 1
+
+    # ntt
+    assert convolution(d, b, prime=q) == convolution_ntt(b, d, prime=q)
+    assert convolution(c, b, prime=p) == convolution_ntt(b, c, prime=p)
+    assert convolution(d, c, prime=p) == convolution_ntt(c, d, prime=p)
+    raises(TypeError, lambda: convolution(b, d, dps=5, prime=q))
+    raises(TypeError, lambda: convolution(b, d, dps=6, prime=q))
+
+    # fwht
+    assert convolution(a, b, dyadic=True) == convolution_fwht(a, b)
+    assert convolution(a, b, dyadic=False) == convolution(a, b)
+    raises(TypeError, lambda: convolution(b, d, dps=2, dyadic=True))
+    raises(TypeError, lambda: convolution(b, d, prime=p, dyadic=True))
+    raises(TypeError, lambda: convolution(a, b, dps=2, dyadic=True))
+    raises(TypeError, lambda: convolution(b, c, prime=p, dyadic=True))
+
+    # subset
+    assert convolution(a, b, subset=True) == convolution_subset(a, b) == \
+            convolution(a, b, subset=True, dyadic=False) == \
+                convolution(a, b, subset=True)
+    assert convolution(a, b, subset=False) == convolution(a, b)
+    raises(TypeError, lambda: convolution(a, b, subset=True, dyadic=True))
+    raises(TypeError, lambda: convolution(c, d, subset=True, dps=6))
+    raises(TypeError, lambda: convolution(a, c, subset=True, prime=q))
+
+    # integer
+    assert convolution([0], [0]) == convolution_int([0], [0])
+    assert convolution(b, c) == convolution_int(b, c)
+
+    # rational
+    assert convolution([Rational(1,2)], [Rational(1,2)]) == [Rational(1, 4)]
+    assert convolution(b, e) == [-9, 10, Rational(239, 15), Rational(34, 3),
+                                 Rational(32, 3), Rational(43, 5), Rational(113, 15),
+                                 Rational(14, 5)]
+
+
+def test_cyclic_convolution():
+    # fft
+    a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)]
+    b = [9, 5, 5, 4, 3, 2]
+
+    assert convolution([1, 2, 3], [4, 5, 6], cycle=0) == \
+            convolution([1, 2, 3], [4, 5, 6], cycle=5) == \
+                convolution([1, 2, 3], [4, 5, 6])
+
+    assert convolution([1, 2, 3], [4, 5, 6], cycle=3) == [31, 31, 28]
+
+    a = [Rational(1, 3), Rational(7, 3), Rational(5, 9), Rational(2, 7), Rational(5, 8)]
+    b = [Rational(3, 5), Rational(4, 7), Rational(7, 8), Rational(8, 9)]
+
+    assert convolution(a, b, cycle=0) == \
+            convolution(a, b, cycle=len(a) + len(b) - 1)
+
+    assert convolution(a, b, cycle=4) == [Rational(87277, 26460), Rational(30521, 11340),
+                            Rational(11125, 4032), Rational(3653, 1080)]
+
+    assert convolution(a, b, cycle=6) == [Rational(20177, 20160), Rational(676, 315), Rational(47, 24),
+                            Rational(3053, 1080), Rational(16397, 5292), Rational(2497, 2268)]
+
+    assert convolution(a, b, cycle=9) == \
+                convolution(a, b, cycle=0) + [S.Zero]
+
+    # ntt
+    a = [2313, 5323532, S(3232), 42142, 42242421]
+    b = [S(33456), 56757, 45754, 432423]
+
+    assert convolution(a, b, prime=19*2**10 + 1, cycle=0) == \
+            convolution(a, b, prime=19*2**10 + 1, cycle=8) == \
+                convolution(a, b, prime=19*2**10 + 1)
+
+    assert convolution(a, b, prime=19*2**10 + 1, cycle=5) == [96, 17146, 2664,
+                                                                    15534, 3517]
+
+    assert convolution(a, b, prime=19*2**10 + 1, cycle=7) == [4643, 3458, 1260,
+                                                        15534, 3517, 16314, 13688]
+
+    assert convolution(a, b, prime=19*2**10 + 1, cycle=9) == \
+            convolution(a, b, prime=19*2**10 + 1) + [0]
+
+    # fwht
+    u, v, w, x, y = symbols('u v w x y')
+    p, q, r, s, t = symbols('p q r s t')
+    c = [u, v, w, x, y]
+    d = [p, q, r, s, t]
+
+    assert convolution(a, b, dyadic=True, cycle=3) == \
+                        [2499522285783, 19861417974796, 4702176579021]
+
+    assert convolution(a, b, dyadic=True, cycle=5) == [2718149225143,
+            2114320852171, 20571217906407, 246166418903, 1413262436976]
+
+    assert convolution(c, d, dyadic=True, cycle=4) == \
+            [p*u + p*y + q*v + r*w + s*x + t*u + t*y,
+             p*v + q*u + q*y + r*x + s*w + t*v,
+             p*w + q*x + r*u + r*y + s*v + t*w,
+             p*x + q*w + r*v + s*u + s*y + t*x]
+
+    assert convolution(c, d, dyadic=True, cycle=6) == \
+            [p*u + q*v + r*w + r*y + s*x + t*w + t*y,
+             p*v + q*u + r*x + s*w + s*y + t*x,
+             p*w + q*x + r*u + s*v,
+             p*x + q*w + r*v + s*u,
+             p*y + t*u,
+             q*y + t*v]
+
+    # subset
+    assert convolution(a, b, subset=True, cycle=7) == [18266671799811,
+                    178235365533, 213958794, 246166418903, 1413262436976,
+                    2397553088697, 1932759730434]
+
+    assert convolution(a[1:], b, subset=True, cycle=4) == \
+            [178104086592, 302255835516, 244982785880, 3717819845434]
+
+    assert convolution(a, b[:-1], subset=True, cycle=6) == [1932837114162,
+            178235365533, 213958794, 245166224504, 1413262436976, 2397553088697]
+
+    assert convolution(c, d, subset=True, cycle=3) == \
+            [p*u + p*x + q*w + r*v + r*y + s*u + t*w,
+             p*v + p*y + q*u + s*y + t*u + t*x,
+             p*w + q*y + r*u + t*v]
+
+    assert convolution(c, d, subset=True, cycle=5) == \
+            [p*u + q*y + t*v,
+             p*v + q*u + r*y + t*w,
+             p*w + r*u + s*y + t*x,
+             p*x + q*w + r*v + s*u,
+             p*y + t*u]
+
+    raises(ValueError, lambda: convolution([1, 2, 3], [4, 5, 6], cycle=-1))
+
+
+def test_convolution_fft():
+    assert all(convolution_fft([], x, dps=y) == [] for x in ([], [1]) for y in (None, 3))
+    assert convolution_fft([1, 2, 3], [4, 5, 6]) == [4, 13, 28, 27, 18]
+    assert convolution_fft([1], [5, 6, 7]) == [5, 6, 7]
+    assert convolution_fft([1, 3], [5, 6, 7]) == [5, 21, 25, 21]
+
+    assert convolution_fft([1 + 2*I], [2 + 3*I]) == [-4 + 7*I]
+    assert convolution_fft([1 + 2*I, 3 + 4*I, 5 + 3*I/5], [Rational(2, 5) + 4*I/7]) == \
+            [Rational(-26, 35) + I*48/35, Rational(-38, 35) + I*116/35, Rational(58, 35) + I*542/175]
+
+    assert convolution_fft([Rational(3, 4), Rational(5, 6)], [Rational(7, 8), Rational(1, 3), Rational(2, 5)]) == \
+                                    [Rational(21, 32), Rational(47, 48), Rational(26, 45), Rational(1, 3)]
+
+    assert convolution_fft([Rational(1, 9), Rational(2, 3), Rational(3, 5)], [Rational(2, 5), Rational(3, 7), Rational(4, 9)]) == \
+                                [Rational(2, 45), Rational(11, 35), Rational(8152, 14175), Rational(523, 945), Rational(4, 15)]
+
+    assert convolution_fft([pi, E, sqrt(2)], [sqrt(3), 1/pi, 1/E]) == \
+                    [sqrt(3)*pi, 1 + sqrt(3)*E, E/pi + pi*exp(-1) + sqrt(6),
+                                            sqrt(2)/pi + 1, sqrt(2)*exp(-1)]
+
+    assert convolution_fft([2321, 33123], [5321, 6321, 71323]) == \
+                        [12350041, 190918524, 374911166, 2362431729]
+
+    assert convolution_fft([312313, 31278232], [32139631, 319631]) == \
+                        [10037624576503, 1005370659728895, 9997492572392]
+
+    raises(TypeError, lambda: convolution_fft(x, y))
+    raises(ValueError, lambda: convolution_fft([x, y], [y, x]))
+
+
+def test_convolution_ntt():
+    # prime moduli of the form (m*2**k + 1), sequence length
+    # should be a divisor of 2**k
+    p = 7*17*2**23 + 1
+    q = 19*2**10 + 1
+    r = 2*500000003 + 1 # only for sequences of length 1 or 2
+    # s = 2*3*5*7 # composite modulus
+
+    assert all(convolution_ntt([], x, prime=y) == [] for x in ([], [1]) for y in (p, q, r))
+    assert convolution_ntt([2], [3], r) == [6]
+    assert convolution_ntt([2, 3], [4], r) == [8, 12]
+
+    assert convolution_ntt([32121, 42144, 4214, 4241], [32132, 3232, 87242], p) == [33867619,
+                                    459741727, 79180879, 831885249, 381344700, 369993322]
+    assert convolution_ntt([121913, 3171831, 31888131, 12], [17882, 21292, 29921, 312], q) == \
+                                                [8158, 3065, 3682, 7090, 1239, 2232, 3744]
+
+    assert convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], p) == \
+                    convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], q)
+    assert convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], p) == \
+                    convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], q)
+
+    raises(ValueError, lambda: convolution_ntt([2, 3], [4, 5], r))
+    raises(ValueError, lambda: convolution_ntt([x, y], [y, x], q))
+    raises(TypeError, lambda: convolution_ntt(x, y, p))
+
+
+def test_convolution_fwht():
+    assert convolution_fwht([], []) == []
+    assert convolution_fwht([], [1]) == []
+    assert convolution_fwht([1, 2, 3], [4, 5, 6]) == [32, 13, 18, 27]
+
+    assert convolution_fwht([Rational(5, 7), Rational(6, 8), Rational(7, 3)], [2, 4, Rational(6, 7)]) == \
+                                    [Rational(45, 7), Rational(61, 14), Rational(776, 147), Rational(419, 42)]
+
+    a = [1, Rational(5, 3), sqrt(3), Rational(7, 5), 4 + 5*I]
+    b = [94, 51, 53, 45, 31, 27, 13]
+    c = [3 + 4*I, 5 + 7*I, 3, Rational(7, 6), 8]
+
+    assert convolution_fwht(a, b) == [53*sqrt(3) + 366 + 155*I,
+                                    45*sqrt(3) + Rational(5848, 15) + 135*I,
+                                    94*sqrt(3) + Rational(1257, 5) + 65*I,
+                                    51*sqrt(3) + Rational(3974, 15),
+                                    13*sqrt(3) + 452 + 470*I,
+                                    Rational(4513, 15) + 255*I,
+                                    31*sqrt(3) + Rational(1314, 5) + 265*I,
+                                    27*sqrt(3) + Rational(3676, 15) + 225*I]
+
+    assert convolution_fwht(b, c) == [Rational(1993, 2) + 733*I, Rational(6215, 6) + 862*I,
+        Rational(1659, 2) + 527*I, Rational(1988, 3) + 551*I, 1019 + 313*I, Rational(3955, 6) + 325*I,
+        Rational(1175, 2) + 52*I, Rational(3253, 6) + 91*I]
+
+    assert convolution_fwht(a[3:], c) == [Rational(-54, 5) + I*293/5, -1 + I*204/5,
+            Rational(133, 15) + I*35/6, Rational(409, 30) + 15*I, Rational(56, 5), 32 + 40*I, 0, 0]
+
+    u, v, w, x, y, z = symbols('u v w x y z')
+
+    assert convolution_fwht([u, v], [x, y]) == [u*x + v*y, u*y + v*x]
+
+    assert convolution_fwht([u, v, w], [x, y]) == \
+        [u*x + v*y, u*y + v*x, w*x, w*y]
+
+    assert convolution_fwht([u, v, w], [x, y, z]) == \
+        [u*x + v*y + w*z, u*y + v*x, u*z + w*x, v*z + w*y]
+
+    raises(TypeError, lambda: convolution_fwht(x, y))
+    raises(TypeError, lambda: convolution_fwht(x*y, u + v))
+
+
+def test_convolution_subset():
+    assert convolution_subset([], []) == []
+    assert convolution_subset([], [Rational(1, 3)]) == []
+    assert convolution_subset([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7]
+
+    a = [1, Rational(5, 3), sqrt(3), 4 + 5*I]
+    b = [64, 71, 55, 47, 33, 29, 15]
+    c = [3 + I*2/3, 5 + 7*I, 7, Rational(7, 5), 9]
+
+    assert convolution_subset(a, b) == [64, Rational(533, 3), 55 + 64*sqrt(3),
+                                        71*sqrt(3) + Rational(1184, 3) + 320*I, 33, 84,
+                                        15 + 33*sqrt(3), 29*sqrt(3) + 157 + 165*I]
+
+    assert convolution_subset(b, c) == [192 + I*128/3, 533 + I*1486/3,
+                                        613 + I*110/3, Rational(5013, 5) + I*1249/3,
+                                        675 + 22*I, 891 + I*751/3,
+                                        771 + 10*I, Rational(3736, 5) + 105*I]
+
+    assert convolution_subset(a, c) == convolution_subset(c, a)
+    assert convolution_subset(a[:2], b) == \
+            [64, Rational(533, 3), 55, Rational(416, 3), 33, 84, 15, 25]
+
+    assert convolution_subset(a[:2], c) == \
+            [3 + I*2/3, 10 + I*73/9, 7, Rational(196, 15), 9, 15, 0, 0]
+
+    u, v, w, x, y, z = symbols('u v w x y z')
+
+    assert convolution_subset([u, v, w], [x, y]) == [u*x, u*y + v*x, w*x, w*y]
+    assert convolution_subset([u, v, w, x], [y, z]) == \
+                            [u*y, u*z + v*y, w*y, w*z + x*y]
+
+    assert convolution_subset([u, v], [x, y, z]) == \
+                    convolution_subset([x, y, z], [u, v])
+
+    raises(TypeError, lambda: convolution_subset(x, z))
+    raises(TypeError, lambda: convolution_subset(Rational(7, 3), u))
+
+
+def test_covering_product():
+    assert covering_product([], []) == []
+    assert covering_product([], [Rational(1, 3)]) == []
+    assert covering_product([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7]
+
+    a = [1, Rational(5, 8), sqrt(7), 4 + 9*I]
+    b = [66, 81, 95, 49, 37, 89, 17]
+    c = [3 + I*2/3, 51 + 72*I, 7, Rational(7, 15), 91]
+
+    assert covering_product(a, b) == [66, Rational(1383, 8), 95 + 161*sqrt(7),
+                                        130*sqrt(7) + 1303 + 2619*I, 37,
+                                        Rational(671, 4), 17 + 54*sqrt(7),
+                                        89*sqrt(7) + Rational(4661, 8) + 1287*I]
+
+    assert covering_product(b, c) == [198 + 44*I, 7740 + 10638*I,
+                                        1412 + I*190/3, Rational(42684, 5) + I*31202/3,
+                                        9484 + I*74/3, 22163 + I*27394/3,
+                                        10621 + I*34/3, Rational(90236, 15) + 1224*I]
+
+    assert covering_product(a, c) == covering_product(c, a)
+    assert covering_product(b, c[:-1]) == [198 + 44*I, 7740 + 10638*I,
+                                         1412 + I*190/3, Rational(42684, 5) + I*31202/3,
+                                         111 + I*74/3, 6693 + I*27394/3,
+                                         429 + I*34/3, Rational(23351, 15) + 1224*I]
+
+    assert covering_product(a, c[:-1]) == [3 + I*2/3,
+                            Rational(339, 4) + I*1409/12, 7 + 10*sqrt(7) + 2*sqrt(7)*I/3,
+                            -403 + 772*sqrt(7)/15 + 72*sqrt(7)*I + I*12658/15]
+
+    u, v, w, x, y, z = symbols('u v w x y z')
+
+    assert covering_product([u, v, w], [x, y]) == \
+                            [u*x, u*y + v*x + v*y, w*x, w*y]
+
+    assert covering_product([u, v, w, x], [y, z]) == \
+                            [u*y, u*z + v*y + v*z, w*y, w*z + x*y + x*z]
+
+    assert covering_product([u, v], [x, y, z]) == \
+                    covering_product([x, y, z], [u, v])
+
+    raises(TypeError, lambda: covering_product(x, z))
+    raises(TypeError, lambda: covering_product(Rational(7, 3), u))
+
+
+def test_intersecting_product():
+    assert intersecting_product([], []) == []
+    assert intersecting_product([], [Rational(1, 3)]) == []
+    assert intersecting_product([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7]
+
+    a = [1, sqrt(5), Rational(3, 8) + 5*I, 4 + 7*I]
+    b = [67, 51, 65, 48, 36, 79, 27]
+    c = [3 + I*2/5, 5 + 9*I, 7, Rational(7, 19), 13]
+
+    assert intersecting_product(a, b) == [195*sqrt(5) + Rational(6979, 8) + 1886*I,
+                                178*sqrt(5) + 520 + 910*I, Rational(841, 2) + 1344*I,
+                                192 + 336*I, 0, 0, 0, 0]
+
+    assert intersecting_product(b, c) == [Rational(128553, 19) + I*9521/5,
+                Rational(17820, 19) + 1602*I, Rational(19264, 19), Rational(336, 19), 1846, 0, 0, 0]
+
+    assert intersecting_product(a, c) == intersecting_product(c, a)
+    assert intersecting_product(b[1:], c[:-1]) == [Rational(64788, 19) + I*8622/5,
+                    Rational(12804, 19) + 1152*I, Rational(11508, 19), Rational(252, 19), 0, 0, 0, 0]
+
+    assert intersecting_product(a, c[:-2]) == \
+                    [Rational(-99, 5) + 10*sqrt(5) + 2*sqrt(5)*I/5 + I*3021/40,
+                    -43 + 5*sqrt(5) + 9*sqrt(5)*I + 71*I, Rational(245, 8) + 84*I, 0]
+
+    u, v, w, x, y, z = symbols('u v w x y z')
+
+    assert intersecting_product([u, v, w], [x, y]) == \
+                            [u*x + u*y + v*x + w*x + w*y, v*y, 0, 0]
+
+    assert intersecting_product([u, v, w, x], [y, z]) == \
+                        [u*y + u*z + v*y + w*y + w*z + x*y, v*z + x*z, 0, 0]
+
+    assert intersecting_product([u, v], [x, y, z]) == \
+                    intersecting_product([x, y, z], [u, v])
+
+    raises(TypeError, lambda: intersecting_product(x, z))
+    raises(TypeError, lambda: intersecting_product(u, Rational(8, 3)))
+
+
+def test_convolution_int():
+    assert convolution_int([1], [1]) == [1]
+    assert convolution_int([1, 1], [0]) == [0]
+    assert convolution_int([1, 2, 3], [4, 5, 6]) == [4, 13, 28, 27, 18]
+    assert convolution_int([1], [5, 6, 7]) == [5, 6, 7]
+    assert convolution_int([1, 3], [5, 6, 7]) == [5, 21, 25, 21]
+    assert convolution_int([10, -5, 1, 3], [-5, 6, 7]) == [-50, 85, 35, -44, 25, 21]
+    assert convolution_int([0, 1, 0, -1], [1, 0, -1, 0]) == [0, 1, 0, -2, 0, 1]
+    assert convolution_int(
+        [-341, -5, 1, 3, -71, -99, 43, 87],
+        [5, 6, 7, 12, 345, 21, -78, -7, -89]
+    ) == [-1705, -2071, -2412, -4106, -118035, -9774, 25998, 2981, 5509,
+          -34317, 19228, 38870, 5485, 1724, -4436, -7743]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/tests/test_recurrences.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/tests/test_recurrences.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c2186ca525b6680350a03edbe44ca88f8f95c3c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/tests/test_recurrences.py
@@ -0,0 +1,59 @@
+from sympy.core.numbers import Rational
+from sympy.functions.combinatorial.numbers import fibonacci
+from sympy.core import S, symbols
+from sympy.testing.pytest import raises
+from sympy.discrete.recurrences import linrec
+
+def test_linrec():
+    assert linrec(coeffs=[1, 1], init=[1, 1], n=20) == 10946
+    assert linrec(coeffs=[1, 2, 3, 4, 5], init=[1, 1, 0, 2], n=10) == 1040
+    assert linrec(coeffs=[0, 0, 11, 13], init=[23, 27], n=25) == 59628567384
+    assert linrec(coeffs=[0, 0, 1, 1, 2], init=[1, 5, 3], n=15) == 165
+    assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=70) == \
+        56889923441670659718376223533331214868804815612050381493741233489928913241
+    assert linrec(coeffs=[0]*55 + [1, 1, 2, 3], init=[0]*50 + [1, 2, 3], n=4000) == \
+        702633573874937994980598979769135096432444135301118916539
+
+    assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=10**4)
+    assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=10**5)
+
+    assert all(linrec(coeffs=[1, 1], init=[0, 1], n=n) == fibonacci(n)
+                                                    for n in range(95, 115))
+
+    assert all(linrec(coeffs=[1, 1], init=[1, 1], n=n) == fibonacci(n + 1)
+                                                    for n in range(595, 615))
+
+    a = [S.Half, Rational(3, 4), Rational(5, 6), 7, Rational(8, 9), Rational(3, 5)]
+    b = [1, 2, 8, Rational(5, 7), Rational(3, 7), Rational(2, 9), 6]
+    x, y, z = symbols('x y z')
+
+    assert linrec(coeffs=a[:5], init=b[:4], n=80) == \
+        Rational(1726244235456268979436592226626304376013002142588105090705187189,
+            1960143456748895967474334873705475211264)
+
+    assert linrec(coeffs=a[:4], init=b[:4], n=50) == \
+        Rational(368949940033050147080268092104304441, 504857282956046106624)
+
+    assert linrec(coeffs=a[3:], init=b[:3], n=35) == \
+        Rational(97409272177295731943657945116791049305244422833125109,
+            814315512679031689453125)
+
+    assert linrec(coeffs=[0]*60 + [Rational(2, 3), Rational(4, 5)], init=b, n=3000) == \
+        Rational(26777668739896791448594650497024, 48084516708184142230517578125)
+
+    raises(TypeError, lambda: linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4, 5], n=1))
+    raises(TypeError, lambda: linrec(coeffs=a[:4], init=b[:5], n=10000))
+    raises(ValueError, lambda: linrec(coeffs=a[:4], init=b[:4], n=-10000))
+    raises(TypeError, lambda: linrec(x, b, n=10000))
+    raises(TypeError, lambda: linrec(a, y, n=10000))
+
+    assert linrec(coeffs=[x, y, z], init=[1, 1, 1], n=4) == \
+        x**2  + x*y + x*z + y + z
+    assert linrec(coeffs=[1, 2, 1], init=[x, y, z], n=20) == \
+        269542*x + 664575*y + 578949*z
+    assert linrec(coeffs=[0, 3, 1, 2], init=[x, y], n=30) == \
+        58516436*x + 56372788*y
+    assert linrec(coeffs=[0]*50 + [1, 2, 3], init=[x, y, z], n=1000) == \
+        11477135884896*x + 25999077948732*y + 41975630244216*z
+    assert linrec(coeffs=[], init=[1, 1], n=20) == 0
+    assert linrec(coeffs=[x, y, z], init=[1, 2, 3], n=2) == 3
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/tests/test_transforms.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/tests/test_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..385514be4cdec2f19cf3a750bdbe0f4f6e21cc6e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/tests/test_transforms.py
@@ -0,0 +1,154 @@
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.core import S, Symbol, symbols, I, Rational
+from sympy.discrete import (fft, ifft, ntt, intt, fwht, ifwht,
+    mobius_transform, inverse_mobius_transform)
+from sympy.testing.pytest import raises
+
+
+def test_fft_ifft():
+    assert all(tf(ls) == ls for tf in (fft, ifft)
+                            for ls in ([], [Rational(5, 3)]))
+
+    ls = list(range(6))
+    fls = [15, -7*sqrt(2)/2 - 4 - sqrt(2)*I/2 + 2*I, 2 + 3*I,
+             -4 + 7*sqrt(2)/2 - 2*I - sqrt(2)*I/2, -3,
+             -4 + 7*sqrt(2)/2 + sqrt(2)*I/2 + 2*I,
+              2 - 3*I, -7*sqrt(2)/2 - 4 - 2*I + sqrt(2)*I/2]
+
+    assert fft(ls) == fls
+    assert ifft(fls) == ls + [S.Zero]*2
+
+    ls = [1 + 2*I, 3 + 4*I, 5 + 6*I]
+    ifls = [Rational(9, 4) + 3*I, I*Rational(-7, 4), Rational(3, 4) + I, -2 - I/4]
+
+    assert ifft(ls) == ifls
+    assert fft(ifls) == ls + [S.Zero]
+
+    x = Symbol('x', real=True)
+    raises(TypeError, lambda: fft(x))
+    raises(ValueError, lambda: ifft([x, 2*x, 3*x**2, 4*x**3]))
+
+
+def test_ntt_intt():
+    # prime moduli of the form (m*2**k + 1), sequence length
+    # should be a divisor of 2**k
+    p = 7*17*2**23 + 1
+    q = 2*500000003 + 1 # only for sequences of length 1 or 2
+    r = 2*3*5*7 # composite modulus
+
+    assert all(tf(ls, p) == ls for tf in (ntt, intt)
+                                for ls in ([], [5]))
+
+    ls = list(range(6))
+    nls = [15, 801133602, 738493201, 334102277, 998244350, 849020224,
+            259751156, 12232587]
+
+    assert ntt(ls, p) == nls
+    assert intt(nls, p) == ls + [0]*2
+
+    ls = [1 + 2*I, 3 + 4*I, 5 + 6*I]
+    x = Symbol('x', integer=True)
+
+    raises(TypeError, lambda: ntt(x, p))
+    raises(ValueError, lambda: intt([x, 2*x, 3*x**2, 4*x**3], p))
+    raises(ValueError, lambda: intt(ls, p))
+    raises(ValueError, lambda: ntt([1.2, 2.1, 3.5], p))
+    raises(ValueError, lambda: ntt([3, 5, 6], q))
+    raises(ValueError, lambda: ntt([4, 5, 7], r))
+    raises(ValueError, lambda: ntt([1.0, 2.0, 3.0], p))
+
+
+def test_fwht_ifwht():
+    assert all(tf(ls) == ls for tf in (fwht, ifwht) \
+                        for ls in ([], [Rational(7, 4)]))
+
+    ls = [213, 321, 43235, 5325, 312, 53]
+    fls = [49459, 38061, -47661, -37759, 48729, 37543, -48391, -38277]
+
+    assert fwht(ls) == fls
+    assert ifwht(fls) == ls + [S.Zero]*2
+
+    ls = [S.Half + 2*I, Rational(3, 7) + 4*I, Rational(5, 6) + 6*I, Rational(7, 3), Rational(9, 4)]
+    ifls = [Rational(533, 672) + I*3/2, Rational(23, 224) + I/2, Rational(1, 672), Rational(107, 224) - I,
+        Rational(155, 672) + I*3/2, Rational(-103, 224) + I/2, Rational(-377, 672), Rational(-19, 224) - I]
+
+    assert ifwht(ls) == ifls
+    assert fwht(ifls) == ls + [S.Zero]*3
+
+    x, y = symbols('x y')
+
+    raises(TypeError, lambda: fwht(x))
+
+    ls = [x, 2*x, 3*x**2, 4*x**3]
+    ifls = [x**3 + 3*x**2/4 + x*Rational(3, 4),
+        -x**3 + 3*x**2/4 - x/4,
+        -x**3 - 3*x**2/4 + x*Rational(3, 4),
+        x**3 - 3*x**2/4 - x/4]
+
+    assert ifwht(ls) == ifls
+    assert fwht(ifls) == ls
+
+    ls = [x, y, x**2, y**2, x*y]
+    fls = [x**2 + x*y + x + y**2 + y,
+        x**2 + x*y + x - y**2 - y,
+        -x**2 + x*y + x - y**2 + y,
+        -x**2 + x*y + x + y**2 - y,
+        x**2 - x*y + x + y**2 + y,
+        x**2 - x*y + x - y**2 - y,
+        -x**2 - x*y + x - y**2 + y,
+        -x**2 - x*y + x + y**2 - y]
+
+    assert fwht(ls) == fls
+    assert ifwht(fls) == ls + [S.Zero]*3
+
+    ls = list(range(6))
+
+    assert fwht(ls) == [x*8 for x in ifwht(ls)]
+
+
+def test_mobius_transform():
+    assert all(tf(ls, subset=subset) == ls
+                for ls in ([], [Rational(7, 4)]) for subset in (True, False)
+                for tf in (mobius_transform, inverse_mobius_transform))
+
+    w, x, y, z = symbols('w x y z')
+
+    assert mobius_transform([x, y]) == [x, x + y]
+    assert inverse_mobius_transform([x, x + y]) == [x, y]
+    assert mobius_transform([x, y], subset=False) == [x + y, y]
+    assert inverse_mobius_transform([x + y, y], subset=False) == [x, y]
+
+    assert mobius_transform([w, x, y, z]) == [w, w + x, w + y, w + x + y + z]
+    assert inverse_mobius_transform([w, w + x, w + y, w + x + y + z]) == \
+            [w, x, y, z]
+    assert mobius_transform([w, x, y, z], subset=False) == \
+            [w + x + y + z, x + z, y + z, z]
+    assert inverse_mobius_transform([w + x + y + z, x + z, y + z, z], subset=False) == \
+            [w, x, y, z]
+
+    ls = [Rational(2, 3), Rational(6, 7), Rational(5, 8), 9, Rational(5, 3) + 7*I]
+    mls = [Rational(2, 3), Rational(32, 21), Rational(31, 24), Rational(1873, 168),
+            Rational(7, 3) + 7*I, Rational(67, 21) + 7*I, Rational(71, 24) + 7*I,
+            Rational(2153, 168) + 7*I]
+
+    assert mobius_transform(ls) == mls
+    assert inverse_mobius_transform(mls) == ls + [S.Zero]*3
+
+    mls = [Rational(2153, 168) + 7*I, Rational(69, 7), Rational(77, 8), 9, Rational(5, 3) + 7*I, 0, 0, 0]
+
+    assert mobius_transform(ls, subset=False) == mls
+    assert inverse_mobius_transform(mls, subset=False) == ls + [S.Zero]*3
+
+    ls = ls[:-1]
+    mls = [Rational(2, 3), Rational(32, 21), Rational(31, 24), Rational(1873, 168)]
+
+    assert mobius_transform(ls) == mls
+    assert inverse_mobius_transform(mls) == ls
+
+    mls = [Rational(1873, 168), Rational(69, 7), Rational(77, 8), 9]
+
+    assert mobius_transform(ls, subset=False) == mls
+    assert inverse_mobius_transform(mls, subset=False) == ls
+
+    raises(TypeError, lambda: mobius_transform(x, subset=True))
+    raises(TypeError, lambda: inverse_mobius_transform(y, subset=False))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/transforms.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb3550837021a4cf99e38c6b15f89ce8bb69b25a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/discrete/transforms.py
@@ -0,0 +1,425 @@
+"""
+Discrete Fourier Transform, Number Theoretic Transform,
+Walsh Hadamard Transform, Mobius Transform
+"""
+
+from sympy.core import S, Symbol, sympify
+from sympy.core.function import expand_mul
+from sympy.core.numbers import pi, I
+from sympy.functions.elementary.trigonometric import sin, cos
+from sympy.ntheory import isprime, primitive_root
+from sympy.utilities.iterables import ibin, iterable
+from sympy.utilities.misc import as_int
+
+
+#----------------------------------------------------------------------------#
+#                                                                            #
+#                         Discrete Fourier Transform                         #
+#                                                                            #
+#----------------------------------------------------------------------------#
+
+def _fourier_transform(seq, dps, inverse=False):
+    """Utility function for the Discrete Fourier Transform"""
+
+    if not iterable(seq):
+        raise TypeError("Expected a sequence of numeric coefficients "
+                        "for Fourier Transform")
+
+    a = [sympify(arg) for arg in seq]
+    if any(x.has(Symbol) for x in a):
+        raise ValueError("Expected non-symbolic coefficients")
+
+    n = len(a)
+    if n < 2:
+        return a
+
+    b = n.bit_length() - 1
+    if n&(n - 1): # not a power of 2
+        b += 1
+        n = 2**b
+
+    a += [S.Zero]*(n - len(a))
+    for i in range(1, n):
+        j = int(ibin(i, b, str=True)[::-1], 2)
+        if i < j:
+            a[i], a[j] = a[j], a[i]
+
+    ang = -2*pi/n if inverse else 2*pi/n
+
+    if dps is not None:
+        ang = ang.evalf(dps + 2)
+
+    w = [cos(ang*i) + I*sin(ang*i) for i in range(n // 2)]
+
+    h = 2
+    while h <= n:
+        hf, ut = h // 2, n // h
+        for i in range(0, n, h):
+            for j in range(hf):
+                u, v = a[i + j], expand_mul(a[i + j + hf]*w[ut * j])
+                a[i + j], a[i + j + hf] = u + v, u - v
+        h *= 2
+
+    if inverse:
+        a = [(x/n).evalf(dps) for x in a] if dps is not None \
+                            else [x/n for x in a]
+
+    return a
+
+
+def fft(seq, dps=None):
+    r"""
+    Performs the Discrete Fourier Transform (**DFT**) in the complex domain.
+
+    The sequence is automatically padded to the right with zeros, as the
+    *radix-2 FFT* requires the number of sample points to be a power of 2.
+
+    This method should be used with default arguments only for short sequences
+    as the complexity of expressions increases with the size of the sequence.
+
+    Parameters
+    ==========
+
+    seq : iterable
+        The sequence on which **DFT** is to be applied.
+    dps : Integer
+        Specifies the number of decimal digits for precision.
+
+    Examples
+    ========
+
+    >>> from sympy import fft, ifft
+
+    >>> fft([1, 2, 3, 4])
+    [10, -2 - 2*I, -2, -2 + 2*I]
+    >>> ifft(_)
+    [1, 2, 3, 4]
+
+    >>> ifft([1, 2, 3, 4])
+    [5/2, -1/2 + I/2, -1/2, -1/2 - I/2]
+    >>> fft(_)
+    [1, 2, 3, 4]
+
+    >>> ifft([1, 7, 3, 4], dps=15)
+    [3.75, -0.5 - 0.75*I, -1.75, -0.5 + 0.75*I]
+    >>> fft(_)
+    [1.0, 7.0, 3.0, 4.0]
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm
+    .. [2] https://mathworld.wolfram.com/FastFourierTransform.html
+
+    """
+
+    return _fourier_transform(seq, dps=dps)
+
+
+def ifft(seq, dps=None):
+    return _fourier_transform(seq, dps=dps, inverse=True)
+
+ifft.__doc__ = fft.__doc__
+
+
+#----------------------------------------------------------------------------#
+#                                                                            #
+#                         Number Theoretic Transform                         #
+#                                                                            #
+#----------------------------------------------------------------------------#
+
+def _number_theoretic_transform(seq, prime, inverse=False):
+    """Utility function for the Number Theoretic Transform"""
+
+    if not iterable(seq):
+        raise TypeError("Expected a sequence of integer coefficients "
+                        "for Number Theoretic Transform")
+
+    p = as_int(prime)
+    if not isprime(p):
+        raise ValueError("Expected prime modulus for "
+                        "Number Theoretic Transform")
+
+    a = [as_int(x) % p for x in seq]
+
+    n = len(a)
+    if n < 1:
+        return a
+
+    b = n.bit_length() - 1
+    if n&(n - 1):
+        b += 1
+        n = 2**b
+
+    if (p - 1) % n:
+        raise ValueError("Expected prime modulus of the form (m*2**k + 1)")
+
+    a += [0]*(n - len(a))
+    for i in range(1, n):
+        j = int(ibin(i, b, str=True)[::-1], 2)
+        if i < j:
+            a[i], a[j] = a[j], a[i]
+
+    pr = primitive_root(p)
+
+    rt = pow(pr, (p - 1) // n, p)
+    if inverse:
+        rt = pow(rt, p - 2, p)
+
+    w = [1]*(n // 2)
+    for i in range(1, n // 2):
+        w[i] = w[i - 1]*rt % p
+
+    h = 2
+    while h <= n:
+        hf, ut = h // 2, n // h
+        for i in range(0, n, h):
+            for j in range(hf):
+                u, v = a[i + j], a[i + j + hf]*w[ut * j]
+                a[i + j], a[i + j + hf] = (u + v) % p, (u - v) % p
+        h *= 2
+
+    if inverse:
+        rv = pow(n, p - 2, p)
+        a = [x*rv % p for x in a]
+
+    return a
+
+
+def ntt(seq, prime):
+    r"""
+    Performs the Number Theoretic Transform (**NTT**), which specializes the
+    Discrete Fourier Transform (**DFT**) over quotient ring `Z/pZ` for prime
+    `p` instead of complex numbers `C`.
+
+    The sequence is automatically padded to the right with zeros, as the
+    *radix-2 NTT* requires the number of sample points to be a power of 2.
+
+    Parameters
+    ==========
+
+    seq : iterable
+        The sequence on which **DFT** is to be applied.
+    prime : Integer
+        Prime modulus of the form `(m 2^k + 1)` to be used for performing
+        **NTT** on the sequence.
+
+    Examples
+    ========
+
+    >>> from sympy import ntt, intt
+    >>> ntt([1, 2, 3, 4], prime=3*2**8 + 1)
+    [10, 643, 767, 122]
+    >>> intt(_, 3*2**8 + 1)
+    [1, 2, 3, 4]
+    >>> intt([1, 2, 3, 4], prime=3*2**8 + 1)
+    [387, 415, 384, 353]
+    >>> ntt(_, prime=3*2**8 + 1)
+    [1, 2, 3, 4]
+
+    References
+    ==========
+
+    .. [1] http://www.apfloat.org/ntt.html
+    .. [2] https://mathworld.wolfram.com/NumberTheoreticTransform.html
+    .. [3] https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general%29
+
+    """
+
+    return _number_theoretic_transform(seq, prime=prime)
+
+
+def intt(seq, prime):
+    return _number_theoretic_transform(seq, prime=prime, inverse=True)
+
+intt.__doc__ = ntt.__doc__
+
+
+#----------------------------------------------------------------------------#
+#                                                                            #
+#                          Walsh Hadamard Transform                          #
+#                                                                            #
+#----------------------------------------------------------------------------#
+
+def _walsh_hadamard_transform(seq, inverse=False):
+    """Utility function for the Walsh Hadamard Transform"""
+
+    if not iterable(seq):
+        raise TypeError("Expected a sequence of coefficients "
+                        "for Walsh Hadamard Transform")
+
+    a = [sympify(arg) for arg in seq]
+    n = len(a)
+    if n < 2:
+        return a
+
+    if n&(n - 1):
+        n = 2**n.bit_length()
+
+    a += [S.Zero]*(n - len(a))
+    h = 2
+    while h <= n:
+        hf = h // 2
+        for i in range(0, n, h):
+            for j in range(hf):
+                u, v = a[i + j], a[i + j + hf]
+                a[i + j], a[i + j + hf] = u + v, u - v
+        h *= 2
+
+    if inverse:
+        a = [x/n for x in a]
+
+    return a
+
+
+def fwht(seq):
+    r"""
+    Performs the Walsh Hadamard Transform (**WHT**), and uses Hadamard
+    ordering for the sequence.
+
+    The sequence is automatically padded to the right with zeros, as the
+    *radix-2 FWHT* requires the number of sample points to be a power of 2.
+
+    Parameters
+    ==========
+
+    seq : iterable
+        The sequence on which WHT is to be applied.
+
+    Examples
+    ========
+
+    >>> from sympy import fwht, ifwht
+    >>> fwht([4, 2, 2, 0, 0, 2, -2, 0])
+    [8, 0, 8, 0, 8, 8, 0, 0]
+    >>> ifwht(_)
+    [4, 2, 2, 0, 0, 2, -2, 0]
+
+    >>> ifwht([19, -1, 11, -9, -7, 13, -15, 5])
+    [2, 0, 4, 0, 3, 10, 0, 0]
+    >>> fwht(_)
+    [19, -1, 11, -9, -7, 13, -15, 5]
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Hadamard_transform
+    .. [2] https://en.wikipedia.org/wiki/Fast_Walsh%E2%80%93Hadamard_transform
+
+    """
+
+    return _walsh_hadamard_transform(seq)
+
+
+def ifwht(seq):
+    return _walsh_hadamard_transform(seq, inverse=True)
+
+ifwht.__doc__ = fwht.__doc__
+
+
+#----------------------------------------------------------------------------#
+#                                                                            #
+#                    Mobius Transform for Subset Lattice                     #
+#                                                                            #
+#----------------------------------------------------------------------------#
+
+def _mobius_transform(seq, sgn, subset):
+    r"""Utility function for performing Mobius Transform using
+    Yate's Dynamic Programming method"""
+
+    if not iterable(seq):
+        raise TypeError("Expected a sequence of coefficients")
+
+    a = [sympify(arg) for arg in seq]
+
+    n = len(a)
+    if n < 2:
+        return a
+
+    if n&(n - 1):
+        n = 2**n.bit_length()
+
+    a += [S.Zero]*(n - len(a))
+
+    if subset:
+        i = 1
+        while i < n:
+            for j in range(n):
+                if j & i:
+                    a[j] += sgn*a[j ^ i]
+            i *= 2
+
+    else:
+        i = 1
+        while i < n:
+            for j in range(n):
+                if j & i:
+                    continue
+                a[j] += sgn*a[j ^ i]
+            i *= 2
+
+    return a
+
+
+def mobius_transform(seq, subset=True):
+    r"""
+    Performs the Mobius Transform for subset lattice with indices of
+    sequence as bitmasks.
+
+    The indices of each argument, considered as bit strings, correspond
+    to subsets of a finite set.
+
+    The sequence is automatically padded to the right with zeros, as the
+    definition of subset/superset based on bitmasks (indices) requires
+    the size of sequence to be a power of 2.
+
+    Parameters
+    ==========
+
+    seq : iterable
+        The sequence on which Mobius Transform is to be applied.
+    subset : bool
+        Specifies if Mobius Transform is applied by enumerating subsets
+        or supersets of the given set.
+
+    Examples
+    ========
+
+    >>> from sympy import symbols
+    >>> from sympy import mobius_transform, inverse_mobius_transform
+    >>> x, y, z = symbols('x y z')
+
+    >>> mobius_transform([x, y, z])
+    [x, x + y, x + z, x + y + z]
+    >>> inverse_mobius_transform(_)
+    [x, y, z, 0]
+
+    >>> mobius_transform([x, y, z], subset=False)
+    [x + y + z, y, z, 0]
+    >>> inverse_mobius_transform(_, subset=False)
+    [x, y, z, 0]
+
+    >>> mobius_transform([1, 2, 3, 4])
+    [1, 3, 4, 10]
+    >>> inverse_mobius_transform(_)
+    [1, 2, 3, 4]
+    >>> mobius_transform([1, 2, 3, 4], subset=False)
+    [10, 6, 7, 4]
+    >>> inverse_mobius_transform(_, subset=False)
+    [1, 2, 3, 4]
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/M%C3%B6bius_inversion_formula
+    .. [2] https://people.csail.mit.edu/rrw/presentations/subset-conv.pdf
+    .. [3] https://arxiv.org/pdf/1211.0189.pdf
+
+    """
+
+    return _mobius_transform(seq, sgn=+1, subset=subset)
+
+def inverse_mobius_transform(seq, subset=True):
+    return _mobius_transform(seq, sgn=-1, subset=subset)
+
+inverse_mobius_transform.__doc__ = mobius_transform.__doc__
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..549b4b96cdce0ee4d31960e89cb9dc26af0e105d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/__init__.py
@@ -0,0 +1,20 @@
+"""
+Unified place for determining if external dependencies are installed or not.
+
+You should import all external modules using the import_module() function.
+
+For example
+
+>>> from sympy.external import import_module
+>>> numpy = import_module('numpy')
+
+If the resulting library is not installed, or if the installed version
+is less than a given minimum version, the function will return None.
+Otherwise, it will return the library. See the docstring of
+import_module() for more information.
+
+"""
+
+from sympy.external.importtools import import_module
+
+__all__ = ['import_module']
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4d612606dd3ebe4893c2f05c59e9594c2316cc76
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/__pycache__/gmpy.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/__pycache__/gmpy.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..377c160537fea3589d89c2669151dd63633488bd
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/__pycache__/gmpy.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/__pycache__/importtools.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/__pycache__/importtools.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..67a144b4ab7f6e154a4c321d432ae653f9c03e4d
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/__pycache__/importtools.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/__pycache__/ntheory.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/__pycache__/ntheory.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..577a4cb9381eed22690e130125cdc06548b4c17f
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/__pycache__/ntheory.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/__pycache__/pythonmpq.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/__pycache__/pythonmpq.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..faba70e09242b50af48e6f6ab45f862b18ea082d
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/__pycache__/pythonmpq.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/gmpy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/gmpy.py
new file mode 100644
index 0000000000000000000000000000000000000000..d26942864bf4786e72198d3640d488857b3313f4
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/gmpy.py
@@ -0,0 +1,342 @@
+from __future__ import annotations
+import os
+from ctypes import c_long, sizeof
+from functools import reduce
+from typing import Type
+from warnings import warn
+
+from sympy.external import import_module
+
+from .pythonmpq import PythonMPQ
+
+from .ntheory import (
+    bit_scan1 as python_bit_scan1,
+    bit_scan0 as python_bit_scan0,
+    remove as python_remove,
+    factorial as python_factorial,
+    sqrt as python_sqrt,
+    sqrtrem as python_sqrtrem,
+    gcd as python_gcd,
+    lcm as python_lcm,
+    gcdext as python_gcdext,
+    is_square as python_is_square,
+    invert as python_invert,
+    legendre as python_legendre,
+    jacobi as python_jacobi,
+    kronecker as python_kronecker,
+    iroot as python_iroot,
+    is_fermat_prp as python_is_fermat_prp,
+    is_euler_prp as python_is_euler_prp,
+    is_strong_prp as python_is_strong_prp,
+    is_fibonacci_prp as python_is_fibonacci_prp,
+    is_lucas_prp as python_is_lucas_prp,
+    is_selfridge_prp as python_is_selfridge_prp,
+    is_strong_lucas_prp as python_is_strong_lucas_prp,
+    is_strong_selfridge_prp as python_is_strong_selfridge_prp,
+    is_bpsw_prp as python_is_bpsw_prp,
+    is_strong_bpsw_prp as python_is_strong_bpsw_prp,
+)
+
+
+__all__ = [
+    # GROUND_TYPES is either 'gmpy' or 'python' depending on which is used. If
+    # gmpy is installed then it will be used unless the environment variable
+    # SYMPY_GROUND_TYPES is set to something other than 'auto', 'gmpy', or
+    # 'gmpy2'.
+    'GROUND_TYPES',
+
+    # If HAS_GMPY is 0, no supported version of gmpy is available. Otherwise,
+    # HAS_GMPY will be 2 for gmpy2 if GROUND_TYPES is 'gmpy'. It used to be
+    # possible for HAS_GMPY to be 1 for gmpy but gmpy is no longer supported.
+    'HAS_GMPY',
+
+    # SYMPY_INTS is a tuple containing the base types for valid integer types.
+    # This is either (int,) or (int, type(mpz(0))) depending on GROUND_TYPES.
+    'SYMPY_INTS',
+
+    # MPQ is either gmpy.mpq or the Python equivalent from
+    # sympy.external.pythonmpq
+    'MPQ',
+
+    # MPZ is either gmpy.mpz or int.
+    'MPZ',
+
+    'bit_scan1',
+    'bit_scan0',
+    'remove',
+    'factorial',
+    'sqrt',
+    'is_square',
+    'sqrtrem',
+    'gcd',
+    'lcm',
+    'gcdext',
+    'invert',
+    'legendre',
+    'jacobi',
+    'kronecker',
+    'iroot',
+    'is_fermat_prp',
+    'is_euler_prp',
+    'is_strong_prp',
+    'is_fibonacci_prp',
+    'is_lucas_prp',
+    'is_selfridge_prp',
+    'is_strong_lucas_prp',
+    'is_strong_selfridge_prp',
+    'is_bpsw_prp',
+    'is_strong_bpsw_prp',
+]
+
+
+#
+# Tested python-flint version. Future versions might work but we will only use
+# them if explicitly requested by SYMPY_GROUND_TYPES=flint.
+#
+_PYTHON_FLINT_VERSION_NEEDED = ["0.6", "0.7", "0.8", "0.9", "0.10"]
+
+
+def _flint_version_okay(flint_version):
+    major, minor = flint_version.split('.')[:2]
+    flint_ver = f'{major}.{minor}'
+    return flint_ver in _PYTHON_FLINT_VERSION_NEEDED
+
+#
+# We will only use gmpy2 >= 2.0.0
+#
+_GMPY2_MIN_VERSION = '2.0.0'
+
+
+def _get_flint(sympy_ground_types):
+    if sympy_ground_types not in ('auto', 'flint'):
+        return None
+
+    try:
+        import flint
+        # Earlier versions of python-flint may not have __version__.
+        from flint import __version__ as _flint_version
+    except ImportError:
+        if sympy_ground_types == 'flint':
+            warn("SYMPY_GROUND_TYPES was set to flint but python-flint is not "
+                 "installed. Falling back to other ground types.")
+        return None
+
+    if _flint_version_okay(_flint_version):
+        return flint
+    elif sympy_ground_types == 'auto':
+        return None
+    else:
+        warn(f"Using python-flint {_flint_version} because SYMPY_GROUND_TYPES "
+             f"is set to flint but this version of SymPy is only tested "
+             f"with python-flint versions {_PYTHON_FLINT_VERSION_NEEDED}.")
+        return flint
+
+
+def _get_gmpy2(sympy_ground_types):
+    if sympy_ground_types not in ('auto', 'gmpy', 'gmpy2'):
+        return None
+
+    gmpy = import_module('gmpy2', min_module_version=_GMPY2_MIN_VERSION,
+            module_version_attr='version', module_version_attr_call_args=())
+
+    if sympy_ground_types != 'auto' and gmpy is None:
+        warn("gmpy2 library is not installed, switching to 'python' ground types")
+
+    return gmpy
+
+
+#
+# SYMPY_GROUND_TYPES can be flint, gmpy, gmpy2, python or auto (default)
+#
+_SYMPY_GROUND_TYPES = os.environ.get('SYMPY_GROUND_TYPES', 'auto').lower()
+_flint = None
+_gmpy = None
+
+#
+# First handle auto-detection of flint/gmpy2. We will prefer flint if available
+# or otherwise gmpy2 if available and then lastly the python types.
+#
+if _SYMPY_GROUND_TYPES in ('auto', 'flint'):
+    _flint = _get_flint(_SYMPY_GROUND_TYPES)
+    if _flint is not None:
+        _SYMPY_GROUND_TYPES = 'flint'
+    else:
+        _SYMPY_GROUND_TYPES = 'auto'
+
+if _SYMPY_GROUND_TYPES in ('auto', 'gmpy', 'gmpy2'):
+    _gmpy = _get_gmpy2(_SYMPY_GROUND_TYPES)
+    if _gmpy is not None:
+        _SYMPY_GROUND_TYPES = 'gmpy'
+    else:
+        _SYMPY_GROUND_TYPES = 'python'
+
+if _SYMPY_GROUND_TYPES not in ('flint', 'gmpy', 'python'):
+    warn("SYMPY_GROUND_TYPES environment variable unrecognised. "
+         "Should be 'auto', 'flint', 'gmpy', 'gmpy2' or 'python'.")
+    _SYMPY_GROUND_TYPES = 'python'
+
+#
+# At this point _SYMPY_GROUND_TYPES is either flint, gmpy or python. The blocks
+# below define the values exported by this module in each case.
+#
+
+#
+# In gmpy2 and flint, there are functions that take a long (or unsigned long)
+# argument. That is, it is not possible to input a value larger than that.
+#
+LONG_MAX = (1 << (8*sizeof(c_long) - 1)) - 1
+
+#
+# Type checkers are confused by what SYMPY_INTS is. There may be a better type
+# hint for this like Type[Integral] or something.
+#
+SYMPY_INTS: tuple[Type, ...]
+
+if _SYMPY_GROUND_TYPES == 'gmpy':
+
+    assert _gmpy is not None
+
+    flint = None
+    gmpy = _gmpy
+
+    HAS_GMPY = 2
+    GROUND_TYPES = 'gmpy'
+    SYMPY_INTS = (int, type(gmpy.mpz(0)))
+    MPZ = gmpy.mpz
+    MPQ = gmpy.mpq
+
+    bit_scan1 = gmpy.bit_scan1
+    bit_scan0 = gmpy.bit_scan0
+    remove = gmpy.remove
+    factorial = gmpy.fac
+    sqrt = gmpy.isqrt
+    is_square = gmpy.is_square
+    sqrtrem = gmpy.isqrt_rem
+    gcd = gmpy.gcd
+    lcm = gmpy.lcm
+    gcdext = gmpy.gcdext
+    invert = gmpy.invert
+    legendre = gmpy.legendre
+    jacobi = gmpy.jacobi
+    kronecker = gmpy.kronecker
+
+    def iroot(x, n):
+        # In the latest gmpy2, the threshold for n is ULONG_MAX,
+        # but adjust to the older one.
+        if n <= LONG_MAX:
+            return gmpy.iroot(x, n)
+        return python_iroot(x, n)
+
+    is_fermat_prp = gmpy.is_fermat_prp
+    is_euler_prp = gmpy.is_euler_prp
+    is_strong_prp = gmpy.is_strong_prp
+    is_fibonacci_prp = gmpy.is_fibonacci_prp
+    is_lucas_prp = gmpy.is_lucas_prp
+    is_selfridge_prp = gmpy.is_selfridge_prp
+    is_strong_lucas_prp = gmpy.is_strong_lucas_prp
+    is_strong_selfridge_prp = gmpy.is_strong_selfridge_prp
+    is_bpsw_prp = gmpy.is_bpsw_prp
+    is_strong_bpsw_prp = gmpy.is_strong_bpsw_prp
+
+elif _SYMPY_GROUND_TYPES == 'flint':
+
+    assert _flint is not None
+
+    flint = _flint
+    gmpy = None
+
+    HAS_GMPY = 0
+    GROUND_TYPES = 'flint'
+    SYMPY_INTS = (int, flint.fmpz) # type: ignore
+    MPZ = flint.fmpz # type: ignore
+    MPQ = flint.fmpq # type: ignore
+
+    bit_scan1 = python_bit_scan1
+    bit_scan0 = python_bit_scan0
+    remove = python_remove
+    factorial = python_factorial
+
+    def sqrt(x):
+        return flint.fmpz(x).isqrt()
+
+    def is_square(x):
+        if x < 0:
+            return False
+        return flint.fmpz(x).sqrtrem()[1] == 0
+
+    def sqrtrem(x):
+        return flint.fmpz(x).sqrtrem()
+
+    def gcd(*args):
+        return reduce(flint.fmpz.gcd, args, flint.fmpz(0))
+
+    def lcm(*args):
+        return reduce(flint.fmpz.lcm, args, flint.fmpz(1))
+
+    gcdext = python_gcdext
+    invert = python_invert
+    legendre = python_legendre
+
+    def jacobi(x, y):
+        if y <= 0 or not y % 2:
+            raise ValueError("y should be an odd positive integer")
+        return flint.fmpz(x).jacobi(y)
+
+    kronecker = python_kronecker
+
+    def iroot(x, n):
+        if n <= LONG_MAX:
+            y = flint.fmpz(x).root(n)
+            return y, y**n == x
+        return python_iroot(x, n)
+
+    is_fermat_prp = python_is_fermat_prp
+    is_euler_prp = python_is_euler_prp
+    is_strong_prp = python_is_strong_prp
+    is_fibonacci_prp = python_is_fibonacci_prp
+    is_lucas_prp = python_is_lucas_prp
+    is_selfridge_prp = python_is_selfridge_prp
+    is_strong_lucas_prp = python_is_strong_lucas_prp
+    is_strong_selfridge_prp = python_is_strong_selfridge_prp
+    is_bpsw_prp = python_is_bpsw_prp
+    is_strong_bpsw_prp = python_is_strong_bpsw_prp
+
+elif _SYMPY_GROUND_TYPES == 'python':
+
+    flint = None
+    gmpy = None
+
+    HAS_GMPY = 0
+    GROUND_TYPES = 'python'
+    SYMPY_INTS = (int,)
+    MPZ = int
+    MPQ = PythonMPQ
+
+    bit_scan1 = python_bit_scan1
+    bit_scan0 = python_bit_scan0
+    remove = python_remove
+    factorial = python_factorial
+    sqrt = python_sqrt
+    is_square = python_is_square
+    sqrtrem = python_sqrtrem
+    gcd = python_gcd
+    lcm = python_lcm
+    gcdext = python_gcdext
+    invert = python_invert
+    legendre = python_legendre
+    jacobi = python_jacobi
+    kronecker = python_kronecker
+    iroot = python_iroot
+    is_fermat_prp = python_is_fermat_prp
+    is_euler_prp = python_is_euler_prp
+    is_strong_prp = python_is_strong_prp
+    is_fibonacci_prp = python_is_fibonacci_prp
+    is_lucas_prp = python_is_lucas_prp
+    is_selfridge_prp = python_is_selfridge_prp
+    is_strong_lucas_prp = python_is_strong_lucas_prp
+    is_strong_selfridge_prp = python_is_strong_selfridge_prp
+    is_bpsw_prp = python_is_bpsw_prp
+    is_strong_bpsw_prp = python_is_strong_bpsw_prp
+
+else:
+    assert False
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/importtools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/importtools.py
new file mode 100644
index 0000000000000000000000000000000000000000..5008b3dd4634d3cee10744a0a92b1204051f07cc
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/importtools.py
@@ -0,0 +1,187 @@
+"""Tools to assist importing optional external modules."""
+
+import sys
+import re
+
+# Override these in the module to change the default warning behavior.
+# For example, you might set both to False before running the tests so that
+# warnings are not printed to the console, or set both to True for debugging.
+
+WARN_NOT_INSTALLED = None  # Default is False
+WARN_OLD_VERSION = None  # Default is True
+
+
+def __sympy_debug():
+    # helper function from sympy/__init__.py
+    # We don't just import SYMPY_DEBUG from that file because we don't want to
+    # import all of SymPy just to use this module.
+    import os
+    debug_str = os.getenv('SYMPY_DEBUG', 'False')
+    if debug_str in ('True', 'False'):
+        return eval(debug_str)
+    else:
+        raise RuntimeError("unrecognized value for SYMPY_DEBUG: %s" %
+                           debug_str)
+
+if __sympy_debug():
+    WARN_OLD_VERSION = True
+    WARN_NOT_INSTALLED = True
+
+
+_component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE)
+
+def version_tuple(vstring):
+    # Parse a version string to a tuple e.g. '1.2' -> (1, 2)
+    # Simplified from distutils.version.LooseVersion which was deprecated in
+    # Python 3.10.
+    components = []
+    for x in _component_re.split(vstring):
+        if x and x != '.':
+            try:
+                x = int(x)
+            except ValueError:
+                pass
+            components.append(x)
+    return tuple(components)
+
+
+def import_module(module, min_module_version=None, min_python_version=None,
+        warn_not_installed=None, warn_old_version=None,
+        module_version_attr='__version__', module_version_attr_call_args=None,
+        import_kwargs={}, catch=()):
+    """
+    Import and return a module if it is installed.
+
+    If the module is not installed, it returns None.
+
+    A minimum version for the module can be given as the keyword argument
+    min_module_version.  This should be comparable against the module version.
+    By default, module.__version__ is used to get the module version.  To
+    override this, set the module_version_attr keyword argument.  If the
+    attribute of the module to get the version should be called (e.g.,
+    module.version()), then set module_version_attr_call_args to the args such
+    that module.module_version_attr(*module_version_attr_call_args) returns the
+    module's version.
+
+    If the module version is less than min_module_version using the Python <
+    comparison, None will be returned, even if the module is installed. You can
+    use this to keep from importing an incompatible older version of a module.
+
+    You can also specify a minimum Python version by using the
+    min_python_version keyword argument.  This should be comparable against
+    sys.version_info.
+
+    If the keyword argument warn_not_installed is set to True, the function will
+    emit a UserWarning when the module is not installed.
+
+    If the keyword argument warn_old_version is set to True, the function will
+    emit a UserWarning when the library is installed, but cannot be imported
+    because of the min_module_version or min_python_version options.
+
+    Note that because of the way warnings are handled, a warning will be
+    emitted for each module only once.  You can change the default warning
+    behavior by overriding the values of WARN_NOT_INSTALLED and WARN_OLD_VERSION
+    in sympy.external.importtools.  By default, WARN_NOT_INSTALLED is False and
+    WARN_OLD_VERSION is True.
+
+    This function uses __import__() to import the module.  To pass additional
+    options to __import__(), use the import_kwargs keyword argument.  For
+    example, to import a submodule A.B, you must pass a nonempty fromlist option
+    to __import__.  See the docstring of __import__().
+
+    This catches ImportError to determine if the module is not installed.  To
+    catch additional errors, pass them as a tuple to the catch keyword
+    argument.
+
+    Examples
+    ========
+
+    >>> from sympy.external import import_module
+
+    >>> numpy = import_module('numpy')
+
+    >>> numpy = import_module('numpy', min_python_version=(2, 7),
+    ... warn_old_version=False)
+
+    >>> numpy = import_module('numpy', min_module_version='1.5',
+    ... warn_old_version=False) # numpy.__version__ is a string
+
+    >>> # gmpy does not have __version__, but it does have gmpy.version()
+
+    >>> gmpy = import_module('gmpy', min_module_version='1.14',
+    ... module_version_attr='version', module_version_attr_call_args=(),
+    ... warn_old_version=False)
+
+    >>> # To import a submodule, you must pass a nonempty fromlist to
+    >>> # __import__().  The values do not matter.
+    >>> p3 = import_module('mpl_toolkits.mplot3d',
+    ... import_kwargs={'fromlist':['something']})
+
+    >>> # matplotlib.pyplot can raise RuntimeError when the display cannot be opened
+    >>> matplotlib = import_module('matplotlib',
+    ... import_kwargs={'fromlist':['pyplot']}, catch=(RuntimeError,))
+
+    """
+    # keyword argument overrides default, and global variable overrides
+    # keyword argument.
+    warn_old_version = (WARN_OLD_VERSION if WARN_OLD_VERSION is not None
+        else warn_old_version or True)
+    warn_not_installed = (WARN_NOT_INSTALLED if WARN_NOT_INSTALLED is not None
+        else warn_not_installed or False)
+
+    import warnings
+
+    # Check Python first so we don't waste time importing a module we can't use
+    if min_python_version:
+        if sys.version_info < min_python_version:
+            if warn_old_version:
+                warnings.warn("Python version is too old to use %s "
+                    "(%s or newer required)" % (
+                        module, '.'.join(map(str, min_python_version))),
+                    UserWarning, stacklevel=2)
+            return
+
+    try:
+        mod = __import__(module, **import_kwargs)
+
+        ## there's something funny about imports with matplotlib and py3k. doing
+        ##    from matplotlib import collections
+        ## gives python's stdlib collections module. explicitly re-importing
+        ## the module fixes this.
+        from_list = import_kwargs.get('fromlist', ())
+        for submod in from_list:
+            if submod == 'collections' and mod.__name__ == 'matplotlib':
+                __import__(module + '.' + submod)
+    except ImportError:
+        if warn_not_installed:
+            warnings.warn("%s module is not installed" % module, UserWarning,
+                    stacklevel=2)
+        return
+    except catch as e:
+        if warn_not_installed:
+            warnings.warn(
+                "%s module could not be used (%s)" % (module, repr(e)),
+                stacklevel=2)
+        return
+
+    if min_module_version:
+        modversion = getattr(mod, module_version_attr)
+        if module_version_attr_call_args is not None:
+            modversion = modversion(*module_version_attr_call_args)
+        if version_tuple(modversion) < version_tuple(min_module_version):
+            if warn_old_version:
+                # Attempt to create a pretty string version of the version
+                if isinstance(min_module_version, str):
+                    verstr = min_module_version
+                elif isinstance(min_module_version, (tuple, list)):
+                    verstr = '.'.join(map(str, min_module_version))
+                else:
+                    # Either don't know what this is.  Hopefully
+                    # it's something that has a nice str version, like an int.
+                    verstr = str(min_module_version)
+                warnings.warn("%s version is too old to use "
+                    "(%s or newer required)" % (module, verstr),
+                    UserWarning, stacklevel=2)
+            return
+
+    return mod
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/ntheory.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/ntheory.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0c9bf813cf02b311f9a12ee7fbc4932ed551f3b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/ntheory.py
@@ -0,0 +1,618 @@
+# sympy.external.ntheory
+#
+# This module provides pure Python implementations of some number theory
+# functions that are alternately used from gmpy2 if it is installed.
+
+import math
+
+import mpmath.libmp as mlib
+
+
+_small_trailing = [0] * 256
+for j in range(1, 8):
+    _small_trailing[1 << j :: 1 << (j + 1)] = [j] * (1 << (7 - j))
+
+
+def bit_scan1(x, n=0):
+    if not x:
+        return
+    x = abs(x >> n)
+    low_byte = x & 0xFF
+    if low_byte:
+        return _small_trailing[low_byte] + n
+
+    t = 8 + n
+    x >>= 8
+    # 2**m is quick for z up through 2**30
+    z = x.bit_length() - 1
+    if x == 1 << z:
+        return z + t
+
+    if z < 300:
+        # fixed 8-byte reduction
+        while not x & 0xFF:
+            x >>= 8
+            t += 8
+    else:
+        # binary reduction important when there might be a large
+        # number of trailing 0s
+        p = z >> 1
+        while not x & 0xFF:
+            while x & ((1 << p) - 1):
+                p >>= 1
+            x >>= p
+            t += p
+    return t + _small_trailing[x & 0xFF]
+
+
+def bit_scan0(x, n=0):
+    return bit_scan1(x + (1 << n), n)
+
+
+def remove(x, f):
+    if f < 2:
+        raise ValueError("factor must be > 1")
+    if x == 0:
+        return 0, 0
+    if f == 2:
+        b = bit_scan1(x)
+        return x >> b, b
+    m = 0
+    y, rem = divmod(x, f)
+    while not rem:
+        x = y
+        m += 1
+        if m > 5:
+            pow_list = [f**2]
+            while pow_list:
+                _f = pow_list[-1]
+                y, rem = divmod(x, _f)
+                if not rem:
+                    m += 1 << len(pow_list)
+                    x = y
+                    pow_list.append(_f**2)
+                else:
+                    pow_list.pop()
+        y, rem = divmod(x, f)
+    return x, m
+
+
+def factorial(x):
+    """Return x!."""
+    return int(mlib.ifac(int(x)))
+
+
+def sqrt(x):
+    """Integer square root of x."""
+    return int(mlib.isqrt(int(x)))
+
+
+def sqrtrem(x):
+    """Integer square root of x and remainder."""
+    s, r = mlib.sqrtrem(int(x))
+    return (int(s), int(r))
+
+
+gcd = math.gcd
+lcm = math.lcm
+
+
+def _sign(n):
+    if n < 0:
+        return -1, -n
+    return 1, n
+
+
+def gcdext(a, b):
+    if not a or not b:
+        g = abs(a) or abs(b)
+        if not g:
+            return (0, 0, 0)
+        return (g, a // g, b // g)
+
+    x_sign, a = _sign(a)
+    y_sign, b = _sign(b)
+    x, r = 1, 0
+    y, s = 0, 1
+
+    while b:
+        q, c = divmod(a, b)
+        a, b = b, c
+        x, r = r, x - q*r
+        y, s = s, y - q*s
+
+    return (a, x * x_sign, y * y_sign)
+
+
+def is_square(x):
+    """Return True if x is a square number."""
+    if x < 0:
+        return False
+
+    # Note that the possible values of y**2 % n for a given n are limited.
+    # For example, when n=4, y**2 % n can only take 0 or 1.
+    # In other words, if x % 4 is 2 or 3, then x is not a square number.
+    # Mathematically, it determines if it belongs to the set {y**2 % n},
+    # but implementationally, it can be realized as a logical conjunction
+    # with an n-bit integer.
+    # see https://mersenneforum.org/showpost.php?p=110896
+    # def magic(n):
+    #     s = {y**2 % n for y in range(n)}
+    #     s = set(range(n)) - s
+    #     return sum(1 << bit for bit in s)
+    # >>> print(hex(magic(128)))
+    # 0xfdfdfdedfdfdfdecfdfdfdedfdfcfdec
+    # >>> print(hex(magic(99)))
+    # 0x5f6f9ffb6fb7ddfcb75befdec
+    # >>> print(hex(magic(91)))
+    # 0x6fd1bfcfed5f3679d3ebdec
+    # >>> print(hex(magic(85)))
+    # 0xdef9ae771ffe3b9d67dec
+    if 0xfdfdfdedfdfdfdecfdfdfdedfdfcfdec & (1 << (x & 127)):
+        return False  # e.g. 2, 3
+    m = x % 765765 # 765765 = 99 * 91 * 85
+    if 0x5f6f9ffb6fb7ddfcb75befdec & (1 << (m % 99)):
+        return False  # e.g. 17, 68
+    if 0x6fd1bfcfed5f3679d3ebdec & (1 << (m % 91)):
+        return False  # e.g. 97, 388
+    if 0xdef9ae771ffe3b9d67dec & (1 << (m % 85)):
+        return False  # e.g. 793, 1408
+    return mlib.sqrtrem(int(x))[1] == 0
+
+
+def invert(x, m):
+    """Modular inverse of x modulo m.
+
+    Returns y such that x*y == 1 mod m.
+
+    Uses ``math.pow`` but reproduces the behaviour of ``gmpy2.invert``
+    which raises ZeroDivisionError if no inverse exists.
+    """
+    try:
+        return pow(x, -1, m)
+    except ValueError:
+        raise ZeroDivisionError("invert() no inverse exists")
+
+
+def legendre(x, y):
+    """Legendre symbol (x / y).
+
+    Following the implementation of gmpy2,
+    the error is raised only when y is an even number.
+    """
+    if y <= 0 or not y % 2:
+        raise ValueError("y should be an odd prime")
+    x %= y
+    if not x:
+        return 0
+    if pow(x, (y - 1) // 2, y) == 1:
+        return 1
+    return -1
+
+
+def jacobi(x, y):
+    """Jacobi symbol (x / y)."""
+    if y <= 0 or not y % 2:
+        raise ValueError("y should be an odd positive integer")
+    x %= y
+    if not x:
+        return int(y == 1)
+    if y == 1 or x == 1:
+        return 1
+    if gcd(x, y) != 1:
+        return 0
+    j = 1
+    while x != 0:
+        while x % 2 == 0 and x > 0:
+            x >>= 1
+            if y % 8 in [3, 5]:
+                j = -j
+        x, y = y, x
+        if x % 4 == y % 4 == 3:
+            j = -j
+        x %= y
+    return j
+
+
+def kronecker(x, y):
+    """Kronecker symbol (x / y)."""
+    if gcd(x, y) != 1:
+        return 0
+    if y == 0:
+        return 1
+    sign = -1 if y < 0 and x < 0 else 1
+    y = abs(y)
+    s = bit_scan1(y)
+    y >>= s
+    if s % 2 and x % 8 in [3, 5]:
+        sign = -sign
+    return sign * jacobi(x, y)
+
+
+def iroot(y, n):
+    if y < 0:
+        raise ValueError("y must be nonnegative")
+    if n < 1:
+        raise ValueError("n must be positive")
+    if y in (0, 1):
+        return y, True
+    if n == 1:
+        return y, True
+    if n == 2:
+        x, rem = mlib.sqrtrem(y)
+        return int(x), not rem
+    if n >= y.bit_length():
+        return 1, False
+    # Get initial estimate for Newton's method. Care must be taken to
+    # avoid overflow
+    try:
+        guess = int(y**(1./n) + 0.5)
+    except OverflowError:
+        exp = math.log2(y)/n
+        if exp > 53:
+            shift = int(exp - 53)
+            guess = int(2.0**(exp - shift) + 1) << shift
+        else:
+            guess = int(2.0**exp)
+    if guess > 2**50:
+        # Newton iteration
+        xprev, x = -1, guess
+        while 1:
+            t = x**(n - 1)
+            xprev, x = x, ((n - 1)*x + y//t)//n
+            if abs(x - xprev) < 2:
+                break
+    else:
+        x = guess
+    # Compensate
+    t = x**n
+    while t < y:
+        x += 1
+        t = x**n
+    while t > y:
+        x -= 1
+        t = x**n
+    return x, t == y
+
+
+def is_fermat_prp(n, a):
+    if a < 2:
+        raise ValueError("is_fermat_prp() requires 'a' greater than or equal to 2")
+    if n < 1:
+        raise ValueError("is_fermat_prp() requires 'n' be greater than 0")
+    if n == 1:
+        return False
+    if n % 2 == 0:
+        return n == 2
+    a %= n
+    if gcd(n, a) != 1:
+        raise ValueError("is_fermat_prp() requires gcd(n,a) == 1")
+    return pow(a, n - 1, n) == 1
+
+
+def is_euler_prp(n, a):
+    if a < 2:
+        raise ValueError("is_euler_prp() requires 'a' greater than or equal to 2")
+    if n < 1:
+        raise ValueError("is_euler_prp() requires 'n' be greater than 0")
+    if n == 1:
+        return False
+    if n % 2 == 0:
+        return n == 2
+    a %= n
+    if gcd(n, a) != 1:
+        raise ValueError("is_euler_prp() requires gcd(n,a) == 1")
+    return pow(a, n >> 1, n) == jacobi(a, n) % n
+
+
+def _is_strong_prp(n, a):
+    s = bit_scan1(n - 1)
+    a = pow(a, n >> s, n)
+    if a == 1 or a == n - 1:
+        return True
+    for _ in range(s - 1):
+        a = pow(a, 2, n)
+        if a == n - 1:
+            return True
+        if a == 1:
+            return False
+    return False
+
+
+def is_strong_prp(n, a):
+    if a < 2:
+        raise ValueError("is_strong_prp() requires 'a' greater than or equal to 2")
+    if n < 1:
+        raise ValueError("is_strong_prp() requires 'n' be greater than 0")
+    if n == 1:
+        return False
+    if n % 2 == 0:
+        return n == 2
+    a %= n
+    if gcd(n, a) != 1:
+        raise ValueError("is_strong_prp() requires gcd(n,a) == 1")
+    return _is_strong_prp(n, a)
+
+
+def _lucas_sequence(n, P, Q, k):
+    r"""Return the modular Lucas sequence (U_k, V_k, Q_k).
+
+    Explanation
+    ===========
+
+    Given a Lucas sequence defined by P, Q, returns the kth values for
+    U and V, along with Q^k, all modulo n. This is intended for use with
+    possibly very large values of n and k, where the combinatorial functions
+    would be completely unusable.
+
+    .. math ::
+        U_k = \begin{cases}
+             0 & \text{if } k = 0\\
+             1 & \text{if } k = 1\\
+             PU_{k-1} - QU_{k-2} & \text{if } k > 1
+        \end{cases}\\
+        V_k = \begin{cases}
+             2 & \text{if } k = 0\\
+             P & \text{if } k = 1\\
+             PV_{k-1} - QV_{k-2} & \text{if } k > 1
+        \end{cases}
+
+    The modular Lucas sequences are used in numerous places in number theory,
+    especially in the Lucas compositeness tests and the various n + 1 proofs.
+
+    Parameters
+    ==========
+
+    n : int
+        n is an odd number greater than or equal to 3
+    P : int
+    Q : int
+        D determined by D = P**2 - 4*Q is non-zero
+    k : int
+        k is a nonnegative integer
+
+    Returns
+    =======
+
+    U, V, Qk : (int, int, int)
+        `(U_k \bmod{n}, V_k \bmod{n}, Q^k \bmod{n})`
+
+    Examples
+    ========
+
+    >>> from sympy.external.ntheory import _lucas_sequence
+    >>> N = 10**2000 + 4561
+    >>> sol = U, V, Qk = _lucas_sequence(N, 3, 1, N//2); sol
+    (0, 2, 1)
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Lucas_sequence
+
+    """
+    if k == 0:
+        return (0, 2, 1)
+    D = P**2 - 4*Q
+    U = 1
+    V = P
+    Qk = Q % n
+    if Q == 1:
+        # Optimization for extra strong tests.
+        for b in bin(k)[3:]:
+            U = (U*V) % n
+            V = (V*V - 2) % n
+            if b == "1":
+                U, V = U*P + V, V*P + U*D
+                if U & 1:
+                    U += n
+                if V & 1:
+                    V += n
+                U, V = U >> 1, V >> 1
+    elif P == 1 and Q == -1:
+        # Small optimization for 50% of Selfridge parameters.
+        for b in bin(k)[3:]:
+            U = (U*V) % n
+            if Qk == 1:
+                V = (V*V - 2) % n
+            else:
+                V = (V*V + 2) % n
+                Qk = 1
+            if b == "1":
+                # new_U = (U + V) // 2
+                # new_V = (5*U + V) // 2 = 2*U + new_U
+                U, V  = U + V, U << 1
+                if U & 1:
+                    U += n
+                U >>= 1
+                V += U
+                Qk = -1
+        Qk %= n
+    elif P == 1:
+        for b in bin(k)[3:]:
+            U = (U*V) % n
+            V = (V*V - 2*Qk) % n
+            Qk *= Qk
+            if b == "1":
+                # new_U = (U + V) // 2
+                # new_V = new_U - 2*Q*U
+                U, V  = U + V, (Q*U) << 1
+                if U & 1:
+                    U += n
+                U >>= 1
+                V = U - V
+                Qk *= Q
+            Qk %= n
+    else:
+        # The general case with any P and Q.
+        for b in bin(k)[3:]:
+            U = (U*V) % n
+            V = (V*V - 2*Qk) % n
+            Qk *= Qk
+            if b == "1":
+                U, V = U*P + V, V*P + U*D
+                if U & 1:
+                    U += n
+                if V & 1:
+                    V += n
+                U, V = U >> 1, V >> 1
+                Qk *= Q
+            Qk %= n
+    return (U % n, V % n, Qk)
+
+
+def is_fibonacci_prp(n, p, q):
+    d = p**2 - 4*q
+    if d == 0 or p <= 0 or q not in [1, -1]:
+        raise ValueError("invalid values for p,q in is_fibonacci_prp()")
+    if n < 1:
+        raise ValueError("is_fibonacci_prp() requires 'n' be greater than 0")
+    if n == 1:
+        return False
+    if n % 2 == 0:
+        return n == 2
+    return _lucas_sequence(n, p, q, n)[1] == p % n
+
+
+def is_lucas_prp(n, p, q):
+    d = p**2 - 4*q
+    if d == 0:
+        raise ValueError("invalid values for p,q in is_lucas_prp()")
+    if n < 1:
+        raise ValueError("is_lucas_prp() requires 'n' be greater than 0")
+    if n == 1:
+        return False
+    if n % 2 == 0:
+        return n == 2
+    if gcd(n, q*d) not in [1, n]:
+        raise ValueError("is_lucas_prp() requires gcd(n,2*q*D) == 1")
+    return _lucas_sequence(n, p, q, n - jacobi(d, n))[0] == 0
+
+
+def _is_selfridge_prp(n):
+    """Lucas compositeness test with the Selfridge parameters for n.
+
+    Explanation
+    ===========
+
+    The Lucas compositeness test checks whether n is a prime number.
+    The test can be run with arbitrary parameters ``P`` and ``Q``, which also change the performance of the test.
+    So, which parameters are most effective for running the Lucas compositeness test?
+    As an algorithm for determining ``P`` and ``Q``, Selfridge proposed method A [1]_ page 1401
+    (Since two methods were proposed, referred to simply as A and B in the paper,
+    we will refer to one of them as "method A").
+
+    method A fixes ``P = 1``. Then, ``D`` defined by ``D = P**2 - 4Q`` is varied from 5, -7, 9, -11, 13, and so on,
+    with the first ``D`` being ``jacobi(D, n) == -1``. Once ``D`` is determined,
+    ``Q`` is determined to be ``(P**2 - D)//4``.
+
+    References
+    ==========
+
+    .. [1] Robert Baillie, Samuel S. Wagstaff, Lucas Pseudoprimes,
+           Math. Comp. Vol 35, Number 152 (1980), pp. 1391-1417,
+           https://doi.org/10.1090%2FS0025-5718-1980-0583518-6
+           http://mpqs.free.fr/LucasPseudoprimes.pdf
+
+    """
+    for D in range(5, 1_000_000, 2):
+        if D & 2: # if D % 4 == 3
+            D = -D
+        j = jacobi(D, n)
+        if j == -1:
+            return _lucas_sequence(n, 1, (1-D) // 4, n + 1)[0] == 0
+        if j == 0 and D % n:
+            return False
+        # When j == -1 is hard to find, suspect a square number
+        if D == 13 and is_square(n):
+            return False
+    raise ValueError("appropriate value for D cannot be found in is_selfridge_prp()")
+
+
+def is_selfridge_prp(n):
+    if n < 1:
+        raise ValueError("is_selfridge_prp() requires 'n' be greater than 0")
+    if n == 1:
+        return False
+    if n % 2 == 0:
+        return n == 2
+    return _is_selfridge_prp(n)
+
+
+def is_strong_lucas_prp(n, p, q):
+    D = p**2 - 4*q
+    if D == 0:
+        raise ValueError("invalid values for p,q in is_strong_lucas_prp()")
+    if n < 1:
+        raise ValueError("is_selfridge_prp() requires 'n' be greater than 0")
+    if n == 1:
+        return False
+    if n % 2 == 0:
+        return n == 2
+    if gcd(n, q*D) not in [1, n]:
+        raise ValueError("is_strong_lucas_prp() requires gcd(n,2*q*D) == 1")
+    j = jacobi(D, n)
+    s = bit_scan1(n - j)
+    U, V, Qk = _lucas_sequence(n, p, q, (n - j) >> s)
+    if U == 0 or V == 0:
+        return True
+    for _ in range(s - 1):
+        V = (V*V - 2*Qk) % n
+        if V == 0:
+            return True
+        Qk = pow(Qk, 2, n)
+    return False
+
+
+def _is_strong_selfridge_prp(n):
+    for D in range(5, 1_000_000, 2):
+        if D & 2: # if D % 4 == 3
+            D = -D
+        j = jacobi(D, n)
+        if j == -1:
+            s = bit_scan1(n + 1)
+            U, V, Qk = _lucas_sequence(n, 1, (1-D) // 4, (n + 1) >> s)
+            if U == 0 or V == 0:
+                return True
+            for _ in range(s - 1):
+                V = (V*V - 2*Qk) % n
+                if V == 0:
+                    return True
+                Qk = pow(Qk, 2, n)
+            return False
+        if j == 0 and D % n:
+            return False
+        # When j == -1 is hard to find, suspect a square number
+        if D == 13 and is_square(n):
+            return False
+    raise ValueError("appropriate value for D cannot be found in is_strong_selfridge_prp()")
+
+
+def is_strong_selfridge_prp(n):
+    if n < 1:
+        raise ValueError("is_strong_selfridge_prp() requires 'n' be greater than 0")
+    if n == 1:
+        return False
+    if n % 2 == 0:
+        return n == 2
+    return _is_strong_selfridge_prp(n)
+
+
+def is_bpsw_prp(n):
+    if n < 1:
+        raise ValueError("is_bpsw_prp() requires 'n' be greater than 0")
+    if n == 1:
+        return False
+    if n % 2 == 0:
+        return n == 2
+    return _is_strong_prp(n, 2) and _is_selfridge_prp(n)
+
+
+def is_strong_bpsw_prp(n):
+    if n < 1:
+        raise ValueError("is_strong_bpsw_prp() requires 'n' be greater than 0")
+    if n == 1:
+        return False
+    if n % 2 == 0:
+        return n == 2
+    return _is_strong_prp(n, 2) and _is_strong_selfridge_prp(n)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/pythonmpq.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/pythonmpq.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f2d102974e04e139c00a39057976b5a5bf90776
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/pythonmpq.py
@@ -0,0 +1,341 @@
+"""
+PythonMPQ: Rational number type based on Python integers.
+
+This class is intended as a pure Python fallback for when gmpy2 is not
+installed. If gmpy2 is installed then its mpq type will be used instead. The
+mpq type is around 20x faster. We could just use the stdlib Fraction class
+here but that is slower:
+
+    from fractions import Fraction
+    from sympy.external.pythonmpq import PythonMPQ
+    nums = range(1000)
+    dens = range(5, 1005)
+    rats = [Fraction(n, d) for n, d in zip(nums, dens)]
+    sum(rats) # <--- 24 milliseconds
+    rats = [PythonMPQ(n, d) for n, d in zip(nums, dens)]
+    sum(rats) # <---  7 milliseconds
+
+Both mpq and Fraction have some awkward features like the behaviour of
+division with // and %:
+
+    >>> from fractions import Fraction
+    >>> Fraction(2, 3) % Fraction(1, 4)
+    1/6
+
+For the QQ domain we do not want this behaviour because there should be no
+remainder when dividing rational numbers. SymPy does not make use of this
+aspect of mpq when gmpy2 is installed. Since this class is a fallback for that
+case we do not bother implementing e.g. __mod__ so that we can be sure we
+are not using it when gmpy2 is installed either.
+"""
+
+from __future__ import annotations
+import operator
+from math import gcd
+from decimal import Decimal
+from fractions import Fraction
+import sys
+from typing import Type
+
+
+# Used for __hash__
+_PyHASH_MODULUS = sys.hash_info.modulus
+_PyHASH_INF = sys.hash_info.inf
+
+
+class PythonMPQ:
+    """Rational number implementation that is intended to be compatible with
+    gmpy2's mpq.
+
+    Also slightly faster than fractions.Fraction.
+
+    PythonMPQ should be treated as immutable although no effort is made to
+    prevent mutation (since that might slow down calculations).
+    """
+    __slots__ = ('numerator', 'denominator')
+
+    def __new__(cls, numerator, denominator=None):
+        """Construct PythonMPQ with gcd computation and checks"""
+        if denominator is not None:
+            #
+            # PythonMPQ(n, d): require n and d to be int and d != 0
+            #
+            if isinstance(numerator, int) and isinstance(denominator, int):
+                # This is the slow part:
+                divisor = gcd(numerator, denominator)
+                numerator //= divisor
+                denominator //= divisor
+                return cls._new_check(numerator, denominator)
+        else:
+            #
+            # PythonMPQ(q)
+            #
+            # Here q can be PythonMPQ, int, Decimal, float, Fraction or str
+            #
+            if isinstance(numerator, int):
+                return cls._new(numerator, 1)
+            elif isinstance(numerator, PythonMPQ):
+                return cls._new(numerator.numerator, numerator.denominator)
+
+            # Let Fraction handle Decimal/float conversion and str parsing
+            if isinstance(numerator, (Decimal, float, str)):
+                numerator = Fraction(numerator)
+            if isinstance(numerator, Fraction):
+                return cls._new(numerator.numerator, numerator.denominator)
+        #
+        # Reject everything else. This is more strict than mpq which allows
+        # things like mpq(Fraction, Fraction) or mpq(Decimal, any). The mpq
+        # behaviour is somewhat inconsistent so we choose to accept only a
+        # more strict subset of what mpq allows.
+        #
+        raise TypeError("PythonMPQ() requires numeric or string argument")
+
+    @classmethod
+    def _new_check(cls, numerator, denominator):
+        """Construct PythonMPQ, check divide by zero and canonicalize signs"""
+        if not denominator:
+            raise ZeroDivisionError(f'Zero divisor {numerator}/{denominator}')
+        elif denominator < 0:
+            numerator = -numerator
+            denominator = -denominator
+        return cls._new(numerator, denominator)
+
+    @classmethod
+    def _new(cls, numerator, denominator):
+        """Construct PythonMPQ efficiently (no checks)"""
+        obj = super().__new__(cls)
+        obj.numerator = numerator
+        obj.denominator = denominator
+        return obj
+
+    def __int__(self):
+        """Convert to int (truncates towards zero)"""
+        p, q = self.numerator, self.denominator
+        if p < 0:
+            return -(-p//q)
+        return p//q
+
+    def __float__(self):
+        """Convert to float (approximately)"""
+        return self.numerator / self.denominator
+
+    def __bool__(self):
+        """True/False if nonzero/zero"""
+        return bool(self.numerator)
+
+    def __eq__(self, other):
+        """Compare equal with PythonMPQ, int, float, Decimal or Fraction"""
+        if isinstance(other, PythonMPQ):
+            return (self.numerator == other.numerator
+                and self.denominator == other.denominator)
+        elif isinstance(other, self._compatible_types):
+            return self.__eq__(PythonMPQ(other))
+        else:
+            return NotImplemented
+
+    def __hash__(self):
+        """hash - same as mpq/Fraction"""
+        try:
+            dinv = pow(self.denominator, -1, _PyHASH_MODULUS)
+        except ValueError:
+            hash_ = _PyHASH_INF
+        else:
+            hash_ = hash(hash(abs(self.numerator)) * dinv)
+        result = hash_ if self.numerator >= 0 else -hash_
+        return -2 if result == -1 else result
+
+    def __reduce__(self):
+        """Deconstruct for pickling"""
+        return type(self), (self.numerator, self.denominator)
+
+    def __str__(self):
+        """Convert to string"""
+        if self.denominator != 1:
+            return f"{self.numerator}/{self.denominator}"
+        else:
+            return f"{self.numerator}"
+
+    def __repr__(self):
+        """Convert to string"""
+        return f"MPQ({self.numerator},{self.denominator})"
+
+    def _cmp(self, other, op):
+        """Helper for lt/le/gt/ge"""
+        if not isinstance(other, self._compatible_types):
+            return NotImplemented
+        lhs = self.numerator * other.denominator
+        rhs = other.numerator * self.denominator
+        return op(lhs, rhs)
+
+    def __lt__(self, other):
+        """self < other"""
+        return self._cmp(other, operator.lt)
+
+    def __le__(self, other):
+        """self <= other"""
+        return self._cmp(other, operator.le)
+
+    def __gt__(self, other):
+        """self > other"""
+        return self._cmp(other, operator.gt)
+
+    def __ge__(self, other):
+        """self >= other"""
+        return self._cmp(other, operator.ge)
+
+    def __abs__(self):
+        """abs(q)"""
+        return self._new(abs(self.numerator), self.denominator)
+
+    def __pos__(self):
+        """+q"""
+        return self
+
+    def __neg__(self):
+        """-q"""
+        return self._new(-self.numerator, self.denominator)
+
+    def __add__(self, other):
+        """q1 + q2"""
+        if isinstance(other, PythonMPQ):
+            #
+            # This is much faster than the naive method used in the stdlib
+            # fractions module. Not sure where this method comes from
+            # though...
+            #
+            # Compare timings for something like:
+            #   nums = range(1000)
+            #   rats = [PythonMPQ(n, d) for n, d in zip(nums[:-5], nums[5:])]
+            #   sum(rats) # <-- time this
+            #
+            ap, aq = self.numerator, self.denominator
+            bp, bq = other.numerator, other.denominator
+            g = gcd(aq, bq)
+            if g == 1:
+                p = ap*bq + aq*bp
+                q = bq*aq
+            else:
+                q1, q2 = aq//g, bq//g
+                p, q = ap*q2 + bp*q1, q1*q2
+                g2 = gcd(p, g)
+                p, q = (p // g2), q * (g // g2)
+
+        elif isinstance(other, int):
+            p = self.numerator + self.denominator * other
+            q = self.denominator
+        else:
+            return NotImplemented
+
+        return self._new(p, q)
+
+    def __radd__(self, other):
+        """z1 + q2"""
+        if isinstance(other, int):
+            p = self.numerator + self.denominator * other
+            q = self.denominator
+            return self._new(p, q)
+        else:
+            return NotImplemented
+
+    def __sub__(self ,other):
+        """q1 - q2"""
+        if isinstance(other, PythonMPQ):
+            ap, aq = self.numerator, self.denominator
+            bp, bq = other.numerator, other.denominator
+            g = gcd(aq, bq)
+            if g == 1:
+                p = ap*bq - aq*bp
+                q = bq*aq
+            else:
+                q1, q2 = aq//g, bq//g
+                p, q = ap*q2 - bp*q1, q1*q2
+                g2 = gcd(p, g)
+                p, q = (p // g2), q * (g // g2)
+        elif isinstance(other, int):
+            p = self.numerator - self.denominator*other
+            q = self.denominator
+        else:
+            return NotImplemented
+
+        return self._new(p, q)
+
+    def __rsub__(self, other):
+        """z1 - q2"""
+        if isinstance(other, int):
+            p = self.denominator * other - self.numerator
+            q = self.denominator
+            return self._new(p, q)
+        else:
+            return NotImplemented
+
+    def __mul__(self, other):
+        """q1 * q2"""
+        if isinstance(other, PythonMPQ):
+            ap, aq = self.numerator, self.denominator
+            bp, bq = other.numerator, other.denominator
+            x1 = gcd(ap, bq)
+            x2 = gcd(bp, aq)
+            p, q = ((ap//x1)*(bp//x2), (aq//x2)*(bq//x1))
+        elif isinstance(other, int):
+            x = gcd(other, self.denominator)
+            p = self.numerator*(other//x)
+            q = self.denominator//x
+        else:
+            return NotImplemented
+
+        return self._new(p, q)
+
+    def __rmul__(self, other):
+        """z1 * q2"""
+        if isinstance(other, int):
+            x = gcd(self.denominator, other)
+            p = self.numerator*(other//x)
+            q = self.denominator//x
+            return self._new(p, q)
+        else:
+            return NotImplemented
+
+    def __pow__(self, exp):
+        """q ** z"""
+        p, q = self.numerator, self.denominator
+
+        if exp < 0:
+            p, q, exp = q, p, -exp
+
+        return self._new_check(p**exp, q**exp)
+
+    def __truediv__(self, other):
+        """q1 / q2"""
+        if isinstance(other, PythonMPQ):
+            ap, aq = self.numerator, self.denominator
+            bp, bq = other.numerator, other.denominator
+            x1 = gcd(ap, bp)
+            x2 = gcd(bq, aq)
+            p, q = ((ap//x1)*(bq//x2), (aq//x2)*(bp//x1))
+        elif isinstance(other, int):
+            x = gcd(other, self.numerator)
+            p = self.numerator//x
+            q = self.denominator*(other//x)
+        else:
+            return NotImplemented
+
+        return self._new_check(p, q)
+
+    def __rtruediv__(self, other):
+        """z / q"""
+        if isinstance(other, int):
+            x = gcd(self.numerator, other)
+            p = self.denominator*(other//x)
+            q = self.numerator//x
+            return self._new_check(p, q)
+        else:
+            return NotImplemented
+
+    _compatible_types: tuple[Type, ...] = ()
+
+#
+# These are the types that PythonMPQ will interoperate with for operations
+# and comparisons such as ==, + etc. We define this down here so that we can
+# include PythonMPQ in the list as well.
+#
+PythonMPQ._compatible_types = (PythonMPQ, int, Decimal, Fraction)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_autowrap.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_autowrap.py
new file mode 100644
index 0000000000000000000000000000000000000000..d469b552995b7625f786f3296089e41f42da75cb
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_autowrap.py
@@ -0,0 +1,313 @@
+import sympy
+import tempfile
+import os
+from pathlib import Path
+from sympy.core.mod import Mod
+from sympy.core.relational import Eq
+from sympy.core.symbol import symbols
+from sympy.external import import_module
+from sympy.tensor import IndexedBase, Idx
+from sympy.utilities.autowrap import autowrap, ufuncify, CodeWrapError
+from sympy.testing.pytest import skip
+
+numpy = import_module('numpy', min_module_version='1.6.1')
+Cython = import_module('Cython', min_module_version='0.15.1')
+f2py = import_module('numpy.f2py', import_kwargs={'fromlist': ['f2py']})
+
+f2pyworks = False
+if f2py:
+    try:
+        autowrap(symbols('x'), 'f95', 'f2py')
+    except (CodeWrapError, ImportError, OSError):
+        f2pyworks = False
+    else:
+        f2pyworks = True
+
+a, b, c = symbols('a b c')
+n, m, d = symbols('n m d', integer=True)
+A, B, C = symbols('A B C', cls=IndexedBase)
+i = Idx('i', m)
+j = Idx('j', n)
+k = Idx('k', d)
+
+
+def has_module(module):
+    """
+    Return True if module exists, otherwise run skip().
+
+    module should be a string.
+    """
+    # To give a string of the module name to skip(), this function takes a
+    # string.  So we don't waste time running import_module() more than once,
+    # just map the three modules tested here in this dict.
+    modnames = {'numpy': numpy, 'Cython': Cython, 'f2py': f2py}
+
+    if modnames[module]:
+        if module == 'f2py' and not f2pyworks:
+            skip("Couldn't run f2py.")
+        return True
+    skip("Couldn't import %s." % module)
+
+#
+# test runners used by several language-backend combinations
+#
+
+def runtest_autowrap_twice(language, backend):
+    f = autowrap((((a + b)/c)**5).expand(), language, backend)
+    g = autowrap((((a + b)/c)**4).expand(), language, backend)
+
+    # check that autowrap updates the module name.  Else, g gives the same as f
+    assert f(1, -2, 1) == -1.0
+    assert g(1, -2, 1) == 1.0
+
+
+def runtest_autowrap_trace(language, backend):
+    has_module('numpy')
+    trace = autowrap(A[i, i], language, backend)
+    assert trace(numpy.eye(100)) == 100
+
+
+def runtest_autowrap_matrix_vector(language, backend):
+    has_module('numpy')
+    x, y = symbols('x y', cls=IndexedBase)
+    expr = Eq(y[i], A[i, j]*x[j])
+    mv = autowrap(expr, language, backend)
+
+    # compare with numpy's dot product
+    M = numpy.random.rand(10, 20)
+    x = numpy.random.rand(20)
+    y = numpy.dot(M, x)
+    assert numpy.sum(numpy.abs(y - mv(M, x))) < 1e-13
+
+
+def runtest_autowrap_matrix_matrix(language, backend):
+    has_module('numpy')
+    expr = Eq(C[i, j], A[i, k]*B[k, j])
+    matmat = autowrap(expr, language, backend)
+
+    # compare with numpy's dot product
+    M1 = numpy.random.rand(10, 20)
+    M2 = numpy.random.rand(20, 15)
+    M3 = numpy.dot(M1, M2)
+    assert numpy.sum(numpy.abs(M3 - matmat(M1, M2))) < 1e-13
+
+
+def runtest_ufuncify(language, backend):
+    has_module('numpy')
+    a, b, c = symbols('a b c')
+    fabc = ufuncify([a, b, c], a*b + c, backend=backend)
+    facb = ufuncify([a, c, b], a*b + c, backend=backend)
+    grid = numpy.linspace(-2, 2, 50)
+    b = numpy.linspace(-5, 4, 50)
+    c = numpy.linspace(-1, 1, 50)
+    expected = grid*b + c
+    numpy.testing.assert_allclose(fabc(grid, b, c), expected)
+    numpy.testing.assert_allclose(facb(grid, c, b), expected)
+
+
+def runtest_issue_10274(language, backend):
+    expr = (a - b + c)**(13)
+    tmp = tempfile.mkdtemp()
+    f = autowrap(expr, language, backend, tempdir=tmp,
+                 helpers=('helper', a - b + c, (a, b, c)))
+    assert f(1, 1, 1) == 1
+
+    for file in os.listdir(tmp):
+        if not (file.startswith("wrapped_code_") and file.endswith(".c")):
+            continue
+
+        with open(tmp + '/' + file) as fil:
+            lines = fil.readlines()
+            assert lines[0] == "/******************************************************************************\n"
+            assert "Code generated with SymPy " + sympy.__version__ in lines[1]
+            assert lines[2:] == [
+                " *                                                                            *\n",
+                " *              See http://www.sympy.org/ for more information.               *\n",
+                " *                                                                            *\n",
+                " *                      This file is part of 'autowrap'                       *\n",
+                " ******************************************************************************/\n",
+                "#include " + '"' + file[:-1]+ 'h"' + "\n",
+                "#include \n",
+                "\n",
+                "double helper(double a, double b, double c) {\n",
+                "\n",
+                "   double helper_result;\n",
+                "   helper_result = a - b + c;\n",
+                "   return helper_result;\n",
+                "\n",
+                "}\n",
+                "\n",
+                "double autofunc(double a, double b, double c) {\n",
+                "\n",
+                "   double autofunc_result;\n",
+                "   autofunc_result = pow(helper(a, b, c), 13);\n",
+                "   return autofunc_result;\n",
+                "\n",
+                "}\n",
+                ]
+
+
+def runtest_issue_15337(language, backend):
+    has_module('numpy')
+    # NOTE : autowrap was originally designed to only accept an iterable for
+    # the kwarg "helpers", but in issue 10274 the user mistakenly thought that
+    # if there was only a single helper it did not need to be passed via an
+    # iterable that wrapped the helper tuple. There were no tests for this
+    # behavior so when the code was changed to accept a single tuple it broke
+    # the original behavior. These tests below ensure that both now work.
+    a, b, c, d, e = symbols('a, b, c, d, e')
+    expr = (a - b + c - d + e)**13
+    exp_res = (1. - 2. + 3. - 4. + 5.)**13
+
+    f = autowrap(expr, language, backend, args=(a, b, c, d, e),
+                 helpers=('f1', a - b + c, (a, b, c)))
+    numpy.testing.assert_allclose(f(1, 2, 3, 4, 5), exp_res)
+
+    f = autowrap(expr, language, backend, args=(a, b, c, d, e),
+                 helpers=(('f1', a - b, (a, b)), ('f2', c - d, (c, d))))
+    numpy.testing.assert_allclose(f(1, 2, 3, 4, 5), exp_res)
+
+
+def test_issue_15230():
+    has_module('f2py')
+
+    x, y = symbols('x, y')
+    expr = Mod(x, 3.0) - Mod(y, -2.0)
+    f = autowrap(expr, args=[x, y], language='F95')
+    exp_res = float(expr.xreplace({x: 3.5, y: 2.7}).evalf())
+    assert abs(f(3.5, 2.7) - exp_res) < 1e-14
+
+    x, y = symbols('x, y', integer=True)
+    expr = Mod(x, 3) - Mod(y, -2)
+    f = autowrap(expr, args=[x, y], language='F95')
+    assert f(3, 2) == expr.xreplace({x: 3, y: 2})
+
+#
+# tests of language-backend combinations
+#
+
+# f2py
+
+
+def test_wrap_twice_f95_f2py():
+    has_module('f2py')
+    runtest_autowrap_twice('f95', 'f2py')
+
+
+def test_autowrap_trace_f95_f2py():
+    has_module('f2py')
+    runtest_autowrap_trace('f95', 'f2py')
+
+
+def test_autowrap_matrix_vector_f95_f2py():
+    has_module('f2py')
+    runtest_autowrap_matrix_vector('f95', 'f2py')
+
+
+def test_autowrap_matrix_matrix_f95_f2py():
+    has_module('f2py')
+    runtest_autowrap_matrix_matrix('f95', 'f2py')
+
+
+def test_ufuncify_f95_f2py():
+    has_module('f2py')
+    runtest_ufuncify('f95', 'f2py')
+
+
+def test_issue_15337_f95_f2py():
+    has_module('f2py')
+    runtest_issue_15337('f95', 'f2py')
+
+# Cython
+
+
+def test_wrap_twice_c_cython():
+    has_module('Cython')
+    runtest_autowrap_twice('C', 'cython')
+
+
+def test_autowrap_trace_C_Cython():
+    has_module('Cython')
+    runtest_autowrap_trace('C99', 'cython')
+
+
+def test_autowrap_matrix_vector_C_cython():
+    has_module('Cython')
+    runtest_autowrap_matrix_vector('C99', 'cython')
+
+
+def test_autowrap_matrix_matrix_C_cython():
+    has_module('Cython')
+    runtest_autowrap_matrix_matrix('C99', 'cython')
+
+
+def test_ufuncify_C_Cython():
+    has_module('Cython')
+    runtest_ufuncify('C99', 'cython')
+
+
+def test_issue_10274_C_cython():
+    has_module('Cython')
+    runtest_issue_10274('C89', 'cython')
+
+
+def test_issue_15337_C_cython():
+    has_module('Cython')
+    runtest_issue_15337('C89', 'cython')
+
+
+def test_autowrap_custom_printer():
+    has_module('Cython')
+
+    from sympy.core.numbers import pi
+    from sympy.utilities.codegen import C99CodeGen
+    from sympy.printing.c import C99CodePrinter
+
+    class PiPrinter(C99CodePrinter):
+        def _print_Pi(self, expr):
+            return "S_PI"
+
+    printer = PiPrinter()
+    gen = C99CodeGen(printer=printer)
+    gen.preprocessor_statements.append('#include "shortpi.h"')
+
+    expr = pi * a
+
+    expected = (
+        '#include "%s"\n'
+        '#include \n'
+        '#include "shortpi.h"\n'
+        '\n'
+        'double autofunc(double a) {\n'
+        '\n'
+        '   double autofunc_result;\n'
+        '   autofunc_result = S_PI*a;\n'
+        '   return autofunc_result;\n'
+        '\n'
+        '}\n'
+    )
+
+    tmpdir = tempfile.mkdtemp()
+    # write a trivial header file to use in the generated code
+    Path(os.path.join(tmpdir, 'shortpi.h')).write_text('#define S_PI 3.14')
+
+    func = autowrap(expr, backend='cython', tempdir=tmpdir, code_gen=gen)
+
+    assert func(4.2) == 3.14 * 4.2
+
+    # check that the generated code is correct
+    for filename in os.listdir(tmpdir):
+        if filename.startswith('wrapped_code') and filename.endswith('.c'):
+            with open(os.path.join(tmpdir, filename)) as f:
+                lines = f.readlines()
+                expected = expected % filename.replace('.c', '.h')
+                assert ''.join(lines[7:]) == expected
+
+
+# Numpy
+
+def test_ufuncify_numpy():
+    # This test doesn't use Cython, but if Cython works, then there is a valid
+    # C compiler, which is needed.
+    has_module('Cython')
+    runtest_ufuncify('C99', 'numpy')
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_codegen.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_codegen.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a4fe28300b86fb0b38d98fcf2fcbbe514cf720f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_codegen.py
@@ -0,0 +1,375 @@
+# This tests the compilation and execution of the source code generated with
+# utilities.codegen. The compilation takes place in a temporary directory that
+# is removed after the test. By default the test directory is always removed,
+# but this behavior can be changed by setting the environment variable
+# SYMPY_TEST_CLEAN_TEMP to:
+#   export SYMPY_TEST_CLEAN_TEMP=always   : the default behavior.
+#   export SYMPY_TEST_CLEAN_TEMP=success  : only remove the directories of working tests.
+#   export SYMPY_TEST_CLEAN_TEMP=never    : never remove the directories with the test code.
+# When a directory is not removed, the necessary information is printed on
+# screen to find the files that belong to the (failed) tests. If a test does
+# not fail, py.test captures all the output and you will not see the directories
+# corresponding to the successful tests. Use the --nocapture option to see all
+# the output.
+
+# All tests below have a counterpart in utilities/test/test_codegen.py. In the
+# latter file, the resulting code is compared with predefined strings, without
+# compilation or execution.
+
+# All the generated Fortran code should conform with the Fortran 95 standard,
+# and all the generated C code should be ANSI C, which facilitates the
+# incorporation in various projects. The tests below assume that the binary cc
+# is somewhere in the path and that it can compile ANSI C code.
+
+from sympy.abc import x, y, z
+from sympy.testing.pytest import IS_WASM, skip
+from sympy.utilities.codegen import codegen, make_routine, get_code_generator
+import sys
+import os
+import tempfile
+import subprocess
+from pathlib import Path
+
+
+# templates for the main program that will test the generated code.
+
+main_template = {}
+main_template['F95'] = """
+program main
+  include "codegen.h"
+  integer :: result;
+  result = 0
+
+  %(statements)s
+
+  call exit(result)
+end program
+"""
+
+main_template['C89'] = """
+#include "codegen.h"
+#include 
+#include 
+
+int main() {
+  int result = 0;
+
+  %(statements)s
+
+  return result;
+}
+"""
+main_template['C99'] = main_template['C89']
+# templates for the numerical tests
+
+numerical_test_template = {}
+numerical_test_template['C89'] = """
+  if (fabs(%(call)s)>%(threshold)s) {
+    printf("Numerical validation failed: %(call)s=%%e threshold=%(threshold)s\\n", %(call)s);
+    result = -1;
+  }
+"""
+numerical_test_template['C99'] = numerical_test_template['C89']
+
+numerical_test_template['F95'] = """
+  if (abs(%(call)s)>%(threshold)s) then
+    write(6,"('Numerical validation failed:')")
+    write(6,"('%(call)s=',e15.5,'threshold=',e15.5)") %(call)s, %(threshold)s
+    result = -1;
+  end if
+"""
+# command sequences for supported compilers
+
+compile_commands = {}
+compile_commands['cc'] = [
+    "cc -c codegen.c -o codegen.o",
+    "cc -c main.c -o main.o",
+    "cc main.o codegen.o -lm -o test.exe"
+]
+
+compile_commands['gfortran'] = [
+    "gfortran -c codegen.f90 -o codegen.o",
+    "gfortran -ffree-line-length-none -c main.f90 -o main.o",
+    "gfortran main.o codegen.o -o test.exe"
+]
+
+compile_commands['g95'] = [
+    "g95 -c codegen.f90 -o codegen.o",
+    "g95 -ffree-line-length-huge -c main.f90 -o main.o",
+    "g95 main.o codegen.o -o test.exe"
+]
+
+compile_commands['ifort'] = [
+    "ifort -c codegen.f90 -o codegen.o",
+    "ifort -c main.f90 -o main.o",
+    "ifort main.o codegen.o -o test.exe"
+]
+
+combinations_lang_compiler = [
+    ('C89', 'cc'),
+    ('C99', 'cc'),
+    ('F95', 'ifort'),
+    ('F95', 'gfortran'),
+    ('F95', 'g95')
+]
+
+def try_run(commands):
+    """Run a series of commands and only return True if all ran fine."""
+    if IS_WASM:
+        return False
+    with open(os.devnull, 'w') as null:
+        for command in commands:
+            retcode = subprocess.call(command, stdout=null, shell=True,
+                    stderr=subprocess.STDOUT)
+            if retcode != 0:
+                return False
+    return True
+
+
+def run_test(label, routines, numerical_tests, language, commands, friendly=True):
+    """A driver for the codegen tests.
+
+       This driver assumes that a compiler ifort is present in the PATH and that
+       ifort is (at least) a Fortran 90 compiler. The generated code is written in
+       a temporary directory, together with a main program that validates the
+       generated code. The test passes when the compilation and the validation
+       run correctly.
+    """
+
+    # Check input arguments before touching the file system
+    language = language.upper()
+    assert language in main_template
+    assert language in numerical_test_template
+
+    # Check that environment variable makes sense
+    clean = os.getenv('SYMPY_TEST_CLEAN_TEMP', 'always').lower()
+    if clean not in ('always', 'success', 'never'):
+        raise ValueError("SYMPY_TEST_CLEAN_TEMP must be one of the following: 'always', 'success' or 'never'.")
+
+    # Do all the magic to compile, run and validate the test code
+    # 1) prepare the temporary working directory, switch to that dir
+    work = tempfile.mkdtemp("_sympy_%s_test" % language, "%s_" % label)
+    oldwork = os.getcwd()
+    os.chdir(work)
+
+    # 2) write the generated code
+    if friendly:
+        # interpret the routines as a name_expr list and call the friendly
+        # function codegen
+        codegen(routines, language, "codegen", to_files=True)
+    else:
+        code_gen = get_code_generator(language, "codegen")
+        code_gen.write(routines, "codegen", to_files=True)
+
+    # 3) write a simple main program that links to the generated code, and that
+    #    includes the numerical tests
+    test_strings = []
+    for fn_name, args, expected, threshold in numerical_tests:
+        call_string = "%s(%s)-(%s)" % (
+            fn_name, ",".join(str(arg) for arg in args), expected)
+        if language == "F95":
+            call_string = fortranize_double_constants(call_string)
+            threshold = fortranize_double_constants(str(threshold))
+        test_strings.append(numerical_test_template[language] % {
+            "call": call_string,
+            "threshold": threshold,
+        })
+
+    if language == "F95":
+        f_name = "main.f90"
+    elif language.startswith("C"):
+        f_name = "main.c"
+    else:
+        raise NotImplementedError(
+            "FIXME: filename extension unknown for language: %s" % language)
+
+    Path(f_name).write_text(
+        main_template[language] % {'statements': "".join(test_strings)})
+
+    # 4) Compile and link
+    compiled = try_run(commands)
+
+    # 5) Run if compiled
+    if compiled:
+        executed = try_run(["./test.exe"])
+    else:
+        executed = False
+
+    # 6) Clean up stuff
+    if clean == 'always' or (clean == 'success' and compiled and executed):
+        def safe_remove(filename):
+            if os.path.isfile(filename):
+                os.remove(filename)
+        safe_remove("codegen.f90")
+        safe_remove("codegen.c")
+        safe_remove("codegen.h")
+        safe_remove("codegen.o")
+        safe_remove("main.f90")
+        safe_remove("main.c")
+        safe_remove("main.o")
+        safe_remove("test.exe")
+        os.chdir(oldwork)
+        os.rmdir(work)
+    else:
+        print("TEST NOT REMOVED: %s" % work, file=sys.stderr)
+        os.chdir(oldwork)
+
+    # 7) Do the assertions in the end
+    assert compiled, "failed to compile %s code with:\n%s" % (
+        language, "\n".join(commands))
+    assert executed, "failed to execute %s code from:\n%s" % (
+        language, "\n".join(commands))
+
+
+def fortranize_double_constants(code_string):
+    """
+    Replaces every literal float with literal doubles
+    """
+    import re
+    pattern_exp = re.compile(r'\d+(\.)?\d*[eE]-?\d+')
+    pattern_float = re.compile(r'\d+\.\d*(?!\d*d)')
+
+    def subs_exp(matchobj):
+        return re.sub('[eE]', 'd', matchobj.group(0))
+
+    def subs_float(matchobj):
+        return "%sd0" % matchobj.group(0)
+
+    code_string = pattern_exp.sub(subs_exp, code_string)
+    code_string = pattern_float.sub(subs_float, code_string)
+
+    return code_string
+
+
+def is_feasible(language, commands):
+    # This test should always work, otherwise the compiler is not present.
+    routine = make_routine("test", x)
+    numerical_tests = [
+        ("test", ( 1.0,), 1.0, 1e-15),
+        ("test", (-1.0,), -1.0, 1e-15),
+    ]
+    try:
+        run_test("is_feasible", [routine], numerical_tests, language, commands,
+                 friendly=False)
+        return True
+    except AssertionError:
+        return False
+
+valid_lang_commands = []
+invalid_lang_compilers = []
+for lang, compiler in combinations_lang_compiler:
+    commands = compile_commands[compiler]
+    if is_feasible(lang, commands):
+        valid_lang_commands.append((lang, commands))
+    else:
+        invalid_lang_compilers.append((lang, compiler))
+
+# We test all language-compiler combinations, just to report what is skipped
+
+def test_C89_cc():
+    if ("C89", 'cc') in invalid_lang_compilers:
+        skip("`cc' command didn't work as expected (C89)")
+
+
+def test_C99_cc():
+    if ("C99", 'cc') in invalid_lang_compilers:
+        skip("`cc' command didn't work as expected (C99)")
+
+
+def test_F95_ifort():
+    if ("F95", 'ifort') in invalid_lang_compilers:
+        skip("`ifort' command didn't work as expected")
+
+
+def test_F95_gfortran():
+    if ("F95", 'gfortran') in invalid_lang_compilers:
+        skip("`gfortran' command didn't work as expected")
+
+
+def test_F95_g95():
+    if ("F95", 'g95') in invalid_lang_compilers:
+        skip("`g95' command didn't work as expected")
+
+# Here comes the actual tests
+
+
+def test_basic_codegen():
+    numerical_tests = [
+        ("test", (1.0, 6.0, 3.0), 21.0, 1e-15),
+        ("test", (-1.0, 2.0, -2.5), -2.5, 1e-15),
+    ]
+    name_expr = [("test", (x + y)*z)]
+    for lang, commands in valid_lang_commands:
+        run_test("basic_codegen", name_expr, numerical_tests, lang, commands)
+
+
+def test_intrinsic_math1_codegen():
+    # not included: log10
+    from sympy.core.evalf import N
+    from sympy.functions import ln
+    from sympy.functions.elementary.exponential import log
+    from sympy.functions.elementary.hyperbolic import (cosh, sinh, tanh)
+    from sympy.functions.elementary.integers import (ceiling, floor)
+    from sympy.functions.elementary.miscellaneous import sqrt
+    from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, tan)
+    name_expr = [
+        ("test_fabs", abs(x)),
+        ("test_acos", acos(x)),
+        ("test_asin", asin(x)),
+        ("test_atan", atan(x)),
+        ("test_cos", cos(x)),
+        ("test_cosh", cosh(x)),
+        ("test_log", log(x)),
+        ("test_ln", ln(x)),
+        ("test_sin", sin(x)),
+        ("test_sinh", sinh(x)),
+        ("test_sqrt", sqrt(x)),
+        ("test_tan", tan(x)),
+        ("test_tanh", tanh(x)),
+    ]
+    numerical_tests = []
+    for name, expr in name_expr:
+        for xval in 0.2, 0.5, 0.8:
+            expected = N(expr.subs(x, xval))
+            numerical_tests.append((name, (xval,), expected, 1e-14))
+    for lang, commands in valid_lang_commands:
+        if lang.startswith("C"):
+            name_expr_C = [("test_floor", floor(x)), ("test_ceil", ceiling(x))]
+        else:
+            name_expr_C = []
+        run_test("intrinsic_math1", name_expr + name_expr_C,
+                 numerical_tests, lang, commands)
+
+
+def test_instrinsic_math2_codegen():
+    # not included: frexp, ldexp, modf, fmod
+    from sympy.core.evalf import N
+    from sympy.functions.elementary.trigonometric import atan2
+    name_expr = [
+        ("test_atan2", atan2(x, y)),
+        ("test_pow", x**y),
+    ]
+    numerical_tests = []
+    for name, expr in name_expr:
+        for xval, yval in (0.2, 1.3), (0.5, -0.2), (0.8, 0.8):
+            expected = N(expr.subs(x, xval).subs(y, yval))
+            numerical_tests.append((name, (xval, yval), expected, 1e-14))
+    for lang, commands in valid_lang_commands:
+        run_test("intrinsic_math2", name_expr, numerical_tests, lang, commands)
+
+
+def test_complicated_codegen():
+    from sympy.core.evalf import N
+    from sympy.functions.elementary.trigonometric import (cos, sin, tan)
+    name_expr = [
+        ("test1", ((sin(x) + cos(y) + tan(z))**7).expand()),
+        ("test2", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))),
+    ]
+    numerical_tests = []
+    for name, expr in name_expr:
+        for xval, yval, zval in (0.2, 1.3, -0.3), (0.5, -0.2, 0.0), (0.8, 2.1, 0.8):
+            expected = N(expr.subs(x, xval).subs(y, yval).subs(z, zval))
+            numerical_tests.append((name, (xval, yval, zval), expected, 1e-12))
+    for lang, commands in valid_lang_commands:
+        run_test(
+            "complicated_codegen", name_expr, numerical_tests, lang, commands)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_gmpy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_gmpy.py
new file mode 100644
index 0000000000000000000000000000000000000000..d88f9da0c6c26c15f529ce485fff5b72342170ea
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_gmpy.py
@@ -0,0 +1,12 @@
+from sympy.external.gmpy import LONG_MAX, iroot
+from sympy.testing.pytest import raises
+
+
+def test_iroot():
+    assert iroot(2, LONG_MAX) == (1, False)
+    assert iroot(2, LONG_MAX + 1) == (1, False)
+    for x in range(3):
+        assert iroot(x, 1) == (x, True)
+    raises(ValueError, lambda: iroot(-1, 1))
+    raises(ValueError, lambda: iroot(0, 0))
+    raises(ValueError, lambda: iroot(0, -1))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_importtools.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_importtools.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b954070c179282ed2bcf5735d802c5f22a3a261
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_importtools.py
@@ -0,0 +1,40 @@
+from sympy.external import import_module
+from sympy.testing.pytest import warns
+
+# fixes issue that arose in addressing issue 6533
+def test_no_stdlib_collections():
+    '''
+    make sure we get the right collections when it is not part of a
+    larger list
+    '''
+    import collections
+    matplotlib = import_module('matplotlib',
+        import_kwargs={'fromlist': ['cm', 'collections']},
+        min_module_version='1.1.0', catch=(RuntimeError,))
+    if matplotlib:
+        assert collections != matplotlib.collections
+
+def test_no_stdlib_collections2():
+    '''
+    make sure we get the right collections when it is not part of a
+    larger list
+    '''
+    import collections
+    matplotlib = import_module('matplotlib',
+        import_kwargs={'fromlist': ['collections']},
+        min_module_version='1.1.0', catch=(RuntimeError,))
+    if matplotlib:
+        assert collections != matplotlib.collections
+
+def test_no_stdlib_collections3():
+    '''make sure we get the right collections with no catch'''
+    import collections
+    matplotlib = import_module('matplotlib',
+        import_kwargs={'fromlist': ['cm', 'collections']},
+        min_module_version='1.1.0')
+    if matplotlib:
+        assert collections != matplotlib.collections
+
+def test_min_module_version_python3_basestring_error():
+    with warns(UserWarning):
+        import_module('mpmath', min_module_version='1000.0.1')
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_ntheory.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_ntheory.py
new file mode 100644
index 0000000000000000000000000000000000000000..00824481ad27aa9071ea5801fb3bde75cacbc3c8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_ntheory.py
@@ -0,0 +1,307 @@
+from itertools import permutations
+
+from sympy.external.ntheory import (bit_scan1, remove, bit_scan0, is_fermat_prp,
+                                    is_euler_prp, is_strong_prp, gcdext, _lucas_sequence,
+                                    is_fibonacci_prp, is_lucas_prp, is_selfridge_prp,
+                                    is_strong_lucas_prp, is_strong_selfridge_prp,
+                                    is_bpsw_prp, is_strong_bpsw_prp)
+from sympy.testing.pytest import raises
+
+
+def test_bit_scan1():
+    assert bit_scan1(0) is None
+    assert bit_scan1(1) == 0
+    assert bit_scan1(-1) == 0
+    assert bit_scan1(2) == 1
+    assert bit_scan1(7) == 0
+    assert bit_scan1(-7) == 0
+    for i in range(100):
+        assert bit_scan1(1 << i) == i
+        assert bit_scan1((1 << i) * 31337) == i
+    for i in range(500):
+        n = (1 << 500) + (1 << i)
+        assert bit_scan1(n) == i
+    assert bit_scan1(1 << 1000001) == 1000001
+    assert bit_scan1((1 << 273956)*7**37) == 273956
+    # issue 12709
+    for i in range(1, 10):
+        big = 1 << i
+        assert bit_scan1(-big) == bit_scan1(big)
+
+
+def test_bit_scan0():
+    assert bit_scan0(-1) is None
+    assert bit_scan0(0) == 0
+    assert bit_scan0(1) == 1
+    assert bit_scan0(-2) == 0
+
+
+def test_remove():
+    raises(ValueError, lambda: remove(1, 1))
+    assert remove(0, 3) == (0, 0)
+    for f in range(2, 10):
+        for y in range(2, 1000):
+            for z in [1, 17, 101, 1009]:
+                assert remove(z*f**y, f) == (z, y)
+
+
+def test_gcdext():
+    assert gcdext(0, 0) == (0, 0, 0)
+    assert gcdext(3, 0) == (3, 1, 0)
+    assert gcdext(0, 4) == (4, 0, 1)
+
+    for n in range(1, 10):
+        assert gcdext(n, 1) == gcdext(-n, 1) == (1, 0, 1)
+        assert gcdext(n, -1) == gcdext(-n, -1) == (1, 0, -1)
+        assert gcdext(n, n) == gcdext(-n, n) == (n, 0, 1)
+        assert gcdext(n, -n) == gcdext(-n, -n) == (n, 0, -1)
+
+    for n in range(2, 10):
+        assert gcdext(1, n) == gcdext(1, -n) == (1, 1, 0)
+        assert gcdext(-1, n) == gcdext(-1, -n) == (1, -1, 0)
+
+    for a, b in permutations([2**5, 3, 5, 7**2, 11], 2):
+        g, x, y = gcdext(a, b)
+        assert g == a*x + b*y == 1
+
+
+def test_is_fermat_prp():
+    # invalid input
+    raises(ValueError, lambda: is_fermat_prp(0, 10))
+    raises(ValueError, lambda: is_fermat_prp(5, 1))
+
+    # n = 1
+    assert not is_fermat_prp(1, 3)
+
+    # n is prime
+    assert is_fermat_prp(2, 4)
+    assert is_fermat_prp(3, 2)
+    assert is_fermat_prp(11, 3)
+    assert is_fermat_prp(2**31-1, 5)
+
+    # A001567
+    pseudorpime = [341, 561, 645, 1105, 1387, 1729, 1905, 2047,
+                   2465, 2701, 2821, 3277, 4033, 4369, 4371, 4681]
+    for n in pseudorpime:
+        assert is_fermat_prp(n, 2)
+
+    # A020136
+    pseudorpime = [15, 85, 91, 341, 435, 451, 561, 645, 703, 1105,
+                   1247, 1271, 1387, 1581, 1695, 1729, 1891, 1905]
+    for n in pseudorpime:
+        assert is_fermat_prp(n, 4)
+
+
+def test_is_euler_prp():
+    # invalid input
+    raises(ValueError, lambda: is_euler_prp(0, 10))
+    raises(ValueError, lambda: is_euler_prp(5, 1))
+
+    # n = 1
+    assert not is_euler_prp(1, 3)
+
+    # n is prime
+    assert is_euler_prp(2, 4)
+    assert is_euler_prp(3, 2)
+    assert is_euler_prp(11, 3)
+    assert is_euler_prp(2**31-1, 5)
+
+    # A047713
+    pseudorpime = [561, 1105, 1729, 1905, 2047, 2465, 3277, 4033,
+                   4681, 6601, 8321, 8481, 10585, 12801, 15841]
+    for n in pseudorpime:
+        assert is_euler_prp(n, 2)
+
+    # A048950
+    pseudorpime = [121, 703, 1729, 1891, 2821, 3281, 7381, 8401,
+                   8911, 10585, 12403, 15457, 15841, 16531, 18721]
+    for n in pseudorpime:
+        assert is_euler_prp(n, 3)
+
+
+def test_is_strong_prp():
+    # invalid input
+    raises(ValueError, lambda: is_strong_prp(0, 10))
+    raises(ValueError, lambda: is_strong_prp(5, 1))
+
+    # n = 1
+    assert not is_strong_prp(1, 3)
+
+    # n is prime
+    assert is_strong_prp(2, 4)
+    assert is_strong_prp(3, 2)
+    assert is_strong_prp(11, 3)
+    assert is_strong_prp(2**31-1, 5)
+
+    # A001262
+    pseudorpime = [2047, 3277, 4033, 4681, 8321, 15841, 29341,
+                   42799, 49141, 52633, 65281, 74665, 80581]
+    for n in pseudorpime:
+        assert is_strong_prp(n, 2)
+
+    # A020229
+    pseudorpime = [121, 703, 1891, 3281, 8401, 8911, 10585, 12403,
+                   16531, 18721, 19345, 23521, 31621, 44287, 47197]
+    for n in pseudorpime:
+        assert is_strong_prp(n, 3)
+
+
+def test_lucas_sequence():
+    def lucas_u(P, Q, length):
+        array = [0] * length
+        array[1] = 1
+        for k in range(2, length):
+            array[k] = P * array[k - 1] - Q * array[k - 2]
+        return array
+
+    def lucas_v(P, Q, length):
+        array = [0] * length
+        array[0] = 2
+        array[1] = P
+        for k in range(2, length):
+            array[k] = P * array[k - 1] - Q * array[k - 2]
+        return array
+
+    length = 20
+    for P in range(-10, 10):
+        for Q in range(-10, 10):
+            D = P**2 - 4*Q
+            if D == 0:
+                continue
+            us = lucas_u(P, Q, length)
+            vs = lucas_v(P, Q, length)
+            for n in range(3, 100, 2):
+                for k in range(length):
+                    U, V, Qk = _lucas_sequence(n, P, Q, k)
+                    assert U == us[k] % n
+                    assert V == vs[k] % n
+                    assert pow(Q, k, n) == Qk
+
+
+def test_is_fibonacci_prp():
+    # invalid input
+    raises(ValueError, lambda: is_fibonacci_prp(3, 2, 1))
+    raises(ValueError, lambda: is_fibonacci_prp(3, -5, 1))
+    raises(ValueError, lambda: is_fibonacci_prp(3, 5, 2))
+    raises(ValueError, lambda: is_fibonacci_prp(0, 5, -1))
+
+    # n = 1
+    assert not is_fibonacci_prp(1, 3, 1)
+
+    # n is prime
+    assert is_fibonacci_prp(2, 5, 1)
+    assert is_fibonacci_prp(3, 6, -1)
+    assert is_fibonacci_prp(11, 7, 1)
+    assert is_fibonacci_prp(2**31-1, 8, -1)
+
+    # A005845
+    pseudorpime = [705, 2465, 2737, 3745, 4181, 5777, 6721,
+                   10877, 13201, 15251, 24465, 29281, 34561]
+    for n in pseudorpime:
+        assert is_fibonacci_prp(n, 1, -1)
+
+
+def test_is_lucas_prp():
+    # invalid input
+    raises(ValueError, lambda: is_lucas_prp(3, 2, 1))
+    raises(ValueError, lambda: is_lucas_prp(0, 5, -1))
+    raises(ValueError, lambda: is_lucas_prp(15, 3, 1))
+
+    # n = 1
+    assert not is_lucas_prp(1, 3, 1)
+
+    # n is prime
+    assert is_lucas_prp(2, 5, 2)
+    assert is_lucas_prp(3, 6, -1)
+    assert is_lucas_prp(11, 7, 5)
+    assert is_lucas_prp(2**31-1, 8, -3)
+
+    # A081264
+    pseudorpime = [323, 377, 1891, 3827, 4181, 5777, 6601, 6721,
+                   8149, 10877, 11663, 13201, 13981, 15251, 17119]
+    for n in pseudorpime:
+        assert is_lucas_prp(n, 1, -1)
+
+
+def test_is_selfridge_prp():
+    # invalid input
+    raises(ValueError, lambda: is_selfridge_prp(0))
+
+    # n = 1
+    assert not is_selfridge_prp(1)
+
+    # n is prime
+    assert is_selfridge_prp(2)
+    assert is_selfridge_prp(3)
+    assert is_selfridge_prp(11)
+    assert is_selfridge_prp(2**31-1)
+
+    # A217120
+    pseudorpime = [323, 377, 1159, 1829, 3827, 5459, 5777, 9071,
+                   9179, 10877, 11419, 11663, 13919, 14839, 16109]
+    for n in pseudorpime:
+        assert is_selfridge_prp(n)
+
+
+def test_is_strong_lucas_prp():
+    # invalid input
+    raises(ValueError, lambda: is_strong_lucas_prp(3, 2, 1))
+    raises(ValueError, lambda: is_strong_lucas_prp(0, 5, -1))
+    raises(ValueError, lambda: is_strong_lucas_prp(15, 3, 1))
+
+    # n = 1
+    assert not is_strong_lucas_prp(1, 3, 1)
+
+    # n is prime
+    assert is_strong_lucas_prp(2, 5, 2)
+    assert is_strong_lucas_prp(3, 6, -1)
+    assert is_strong_lucas_prp(11, 7, 5)
+    assert is_strong_lucas_prp(2**31-1, 8, -3)
+
+
+def test_is_strong_selfridge_prp():
+    # invalid input
+    raises(ValueError, lambda: is_strong_selfridge_prp(0))
+
+    # n = 1
+    assert not is_strong_selfridge_prp(1)
+
+    # n is prime
+    assert is_strong_selfridge_prp(2)
+    assert is_strong_selfridge_prp(3)
+    assert is_strong_selfridge_prp(11)
+    assert is_strong_selfridge_prp(2**31-1)
+
+    # A217255
+    pseudorpime = [5459, 5777, 10877, 16109, 18971, 22499, 24569,
+                   25199, 40309, 58519, 75077, 97439, 100127, 113573]
+    for n in pseudorpime:
+        assert is_strong_selfridge_prp(n)
+
+
+def test_is_bpsw_prp():
+    # invalid input
+    raises(ValueError, lambda: is_bpsw_prp(0))
+
+    # n = 1
+    assert not is_bpsw_prp(1)
+
+    # n is prime
+    assert is_bpsw_prp(2)
+    assert is_bpsw_prp(3)
+    assert is_bpsw_prp(11)
+    assert is_bpsw_prp(2**31-1)
+
+
+def test_is_strong_bpsw_prp():
+    # invalid input
+    raises(ValueError, lambda: is_strong_bpsw_prp(0))
+
+    # n = 1
+    assert not is_strong_bpsw_prp(1)
+
+    # n is prime
+    assert is_strong_bpsw_prp(2)
+    assert is_strong_bpsw_prp(3)
+    assert is_strong_bpsw_prp(11)
+    assert is_strong_bpsw_prp(2**31-1)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_numpy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_numpy.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd456d0d6cc49138c29d7ab28ee02694448d578f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_numpy.py
@@ -0,0 +1,335 @@
+# This testfile tests SymPy <-> NumPy compatibility
+
+# Don't test any SymPy features here. Just pure interaction with NumPy.
+# Always write regular SymPy tests for anything, that can be tested in pure
+# Python (without numpy). Here we test everything, that a user may need when
+# using SymPy with NumPy
+from sympy.external.importtools import version_tuple
+from sympy.external import import_module
+
+numpy = import_module('numpy')
+if numpy:
+    array, matrix, ndarray = numpy.array, numpy.matrix, numpy.ndarray
+else:
+    #bin/test will not execute any tests now
+    disabled = True
+
+
+from sympy.core.numbers import (Float, Integer, Rational)
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.functions.elementary.trigonometric import sin
+from sympy.matrices.dense import (Matrix, list2numpy, matrix2numpy, symarray)
+from sympy.utilities.lambdify import lambdify
+import sympy
+
+import mpmath
+from sympy.abc import x, y, z
+from sympy.utilities.decorator import conserve_mpmath_dps
+from sympy.utilities.exceptions import ignore_warnings
+from sympy.testing.pytest import raises
+
+
+# first, systematically check, that all operations are implemented and don't
+# raise an exception
+
+
+def test_systematic_basic():
+    def s(sympy_object, numpy_array):
+        _ = [sympy_object + numpy_array,
+        numpy_array + sympy_object,
+        sympy_object - numpy_array,
+        numpy_array - sympy_object,
+        sympy_object * numpy_array,
+        numpy_array * sympy_object,
+        sympy_object / numpy_array,
+        numpy_array / sympy_object,
+        sympy_object ** numpy_array,
+        numpy_array ** sympy_object]
+    x = Symbol("x")
+    y = Symbol("y")
+    sympy_objs = [
+        Rational(2, 3),
+        Float("1.3"),
+        x,
+        y,
+        pow(x, y)*y,
+        Integer(5),
+        Float(5.5),
+    ]
+    numpy_objs = [
+        array([1]),
+        array([3, 8, -1]),
+        array([x, x**2, Rational(5)]),
+        array([x/y*sin(y), 5, Rational(5)]),
+    ]
+    for x in sympy_objs:
+        for y in numpy_objs:
+            s(x, y)
+
+
+# now some random tests, that test particular problems and that also
+# check that the results of the operations are correct
+
+def test_basics():
+    one = Rational(1)
+    zero = Rational(0)
+    assert array(1) == array(one)
+    assert array([one]) == array([one])
+    assert array([x]) == array([x])
+    assert array(x) == array(Symbol("x"))
+    assert array(one + x) == array(1 + x)
+
+    X = array([one, zero, zero])
+    assert (X == array([one, zero, zero])).all()
+    assert (X == array([one, 0, 0])).all()
+
+
+def test_arrays():
+    one = Rational(1)
+    zero = Rational(0)
+    X = array([one, zero, zero])
+    Y = one*X
+    X = array([Symbol("a") + Rational(1, 2)])
+    Y = X + X
+    assert Y == array([1 + 2*Symbol("a")])
+    Y = Y + 1
+    assert Y == array([2 + 2*Symbol("a")])
+    Y = X - X
+    assert Y == array([0])
+
+
+def test_conversion1():
+    a = list2numpy([x**2, x])
+    #looks like an array?
+    assert isinstance(a, ndarray)
+    assert a[0] == x**2
+    assert a[1] == x
+    assert len(a) == 2
+    #yes, it's the array
+
+
+def test_conversion2():
+    a = 2*list2numpy([x**2, x])
+    b = list2numpy([2*x**2, 2*x])
+    assert (a == b).all()
+
+    one = Rational(1)
+    zero = Rational(0)
+    X = list2numpy([one, zero, zero])
+    Y = one*X
+    X = list2numpy([Symbol("a") + Rational(1, 2)])
+    Y = X + X
+    assert Y == array([1 + 2*Symbol("a")])
+    Y = Y + 1
+    assert Y == array([2 + 2*Symbol("a")])
+    Y = X - X
+    assert Y == array([0])
+
+
+def test_list2numpy():
+    assert (array([x**2, x]) == list2numpy([x**2, x])).all()
+
+
+def test_Matrix1():
+    m = Matrix([[x, x**2], [5, 2/x]])
+    assert (array(m.subs(x, 2)) == array([[2, 4], [5, 1]])).all()
+    m = Matrix([[sin(x), x**2], [5, 2/x]])
+    assert (array(m.subs(x, 2)) == array([[sin(2), 4], [5, 1]])).all()
+
+
+def test_Matrix2():
+    m = Matrix([[x, x**2], [5, 2/x]])
+    with ignore_warnings(PendingDeprecationWarning):
+        assert (matrix(m.subs(x, 2)) == matrix([[2, 4], [5, 1]])).all()
+    m = Matrix([[sin(x), x**2], [5, 2/x]])
+    with ignore_warnings(PendingDeprecationWarning):
+        assert (matrix(m.subs(x, 2)) == matrix([[sin(2), 4], [5, 1]])).all()
+
+
+def test_Matrix3():
+    a = array([[2, 4], [5, 1]])
+    assert Matrix(a) == Matrix([[2, 4], [5, 1]])
+    assert Matrix(a) != Matrix([[2, 4], [5, 2]])
+    a = array([[sin(2), 4], [5, 1]])
+    assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]])
+    assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]])
+
+
+def test_Matrix4():
+    with ignore_warnings(PendingDeprecationWarning):
+        a = matrix([[2, 4], [5, 1]])
+    assert Matrix(a) == Matrix([[2, 4], [5, 1]])
+    assert Matrix(a) != Matrix([[2, 4], [5, 2]])
+    with ignore_warnings(PendingDeprecationWarning):
+        a = matrix([[sin(2), 4], [5, 1]])
+    assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]])
+    assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]])
+
+
+def test_Matrix_sum():
+    M = Matrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]])
+    with ignore_warnings(PendingDeprecationWarning):
+        m = matrix([[2, 3, 4], [x, 5, 6], [x, y, z**2]])
+    assert M + m == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]])
+    assert m + M == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]])
+    assert M + m == M.add(m)
+
+
+def test_Matrix_mul():
+    M = Matrix([[1, 2, 3], [x, y, x]])
+    with ignore_warnings(PendingDeprecationWarning):
+        m = matrix([[2, 4], [x, 6], [x, z**2]])
+    assert M*m == Matrix([
+        [         2 + 5*x,        16 + 3*z**2],
+        [2*x + x*y + x**2, 4*x + 6*y + x*z**2],
+    ])
+
+    assert m*M == Matrix([
+        [   2 + 4*x,      4 + 4*y,      6 + 4*x],
+        [       7*x,    2*x + 6*y,          9*x],
+        [x + x*z**2, 2*x + y*z**2, 3*x + x*z**2],
+    ])
+    a = array([2])
+    assert a[0] * M == 2 * M
+    assert M * a[0] == 2 * M
+
+
+def test_Matrix_array():
+    class matarray:
+        def __array__(self, dtype=object, copy=None):
+            if copy is not None and not copy:
+                raise TypeError("Cannot implement copy=False when converting Matrix to ndarray")
+            from numpy import array
+            return array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+    matarr = matarray()
+    assert Matrix(matarr) == Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+
+
+def test_matrix2numpy():
+    a = matrix2numpy(Matrix([[1, x**2], [3*sin(x), 0]]))
+    assert isinstance(a, ndarray)
+    assert a.shape == (2, 2)
+    assert a[0, 0] == 1
+    assert a[0, 1] == x**2
+    assert a[1, 0] == 3*sin(x)
+    assert a[1, 1] == 0
+
+
+def test_matrix2numpy_conversion():
+    a = Matrix([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]])
+    b = array([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]])
+    assert (matrix2numpy(a) == b).all()
+    assert matrix2numpy(a).dtype == numpy.dtype('object')
+
+    c = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='int8')
+    d = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='float64')
+    assert c.dtype == numpy.dtype('int8')
+    assert d.dtype == numpy.dtype('float64')
+
+
+def test_issue_3728():
+    assert (Rational(1, 2)*array([2*x, 0]) == array([x, 0])).all()
+    assert (Rational(1, 2) + array(
+        [2*x, 0]) == array([2*x + Rational(1, 2), Rational(1, 2)])).all()
+    assert (Float("0.5")*array([2*x, 0]) == array([Float("1.0")*x, 0])).all()
+    assert (Float("0.5") + array(
+        [2*x, 0]) == array([2*x + Float("0.5"), Float("0.5")])).all()
+
+
+@conserve_mpmath_dps
+def test_lambdify():
+    mpmath.mp.dps = 16
+    sin02 = mpmath.mpf("0.198669330795061215459412627")
+    f = lambdify(x, sin(x), "numpy")
+    prec = 1e-15
+    assert -prec < f(0.2) - sin02 < prec
+
+    # if this succeeds, it can't be a numpy function
+
+    if version_tuple(numpy.__version__) >= version_tuple('1.17'):
+        with raises(TypeError):
+            f(x)
+    else:
+        with raises(AttributeError):
+            f(x)
+
+
+def test_lambdify_matrix():
+    f = lambdify(x, Matrix([[x, 2*x], [1, 2]]), [{'ImmutableMatrix': numpy.array}, "numpy"])
+    assert (f(1) == array([[1, 2], [1, 2]])).all()
+
+
+def test_lambdify_matrix_multi_input():
+    M = sympy.Matrix([[x**2, x*y, x*z],
+                      [y*x, y**2, y*z],
+                      [z*x, z*y, z**2]])
+    f = lambdify((x, y, z), M, [{'ImmutableMatrix': numpy.array}, "numpy"])
+
+    xh, yh, zh = 1.0, 2.0, 3.0
+    expected = array([[xh**2, xh*yh, xh*zh],
+                      [yh*xh, yh**2, yh*zh],
+                      [zh*xh, zh*yh, zh**2]])
+    actual = f(xh, yh, zh)
+    assert numpy.allclose(actual, expected)
+
+
+def test_lambdify_matrix_vec_input():
+    X = sympy.DeferredVector('X')
+    M = Matrix([
+        [X[0]**2, X[0]*X[1], X[0]*X[2]],
+        [X[1]*X[0], X[1]**2, X[1]*X[2]],
+        [X[2]*X[0], X[2]*X[1], X[2]**2]])
+    f = lambdify(X, M, [{'ImmutableMatrix': numpy.array}, "numpy"])
+
+    Xh = array([1.0, 2.0, 3.0])
+    expected = array([[Xh[0]**2, Xh[0]*Xh[1], Xh[0]*Xh[2]],
+                      [Xh[1]*Xh[0], Xh[1]**2, Xh[1]*Xh[2]],
+                      [Xh[2]*Xh[0], Xh[2]*Xh[1], Xh[2]**2]])
+    actual = f(Xh)
+    assert numpy.allclose(actual, expected)
+
+
+def test_lambdify_transl():
+    from sympy.utilities.lambdify import NUMPY_TRANSLATIONS
+    for sym, mat in NUMPY_TRANSLATIONS.items():
+        assert sym in sympy.__dict__
+        assert mat in numpy.__dict__
+
+
+def test_symarray():
+    """Test creation of numpy arrays of SymPy symbols."""
+
+    import numpy as np
+    import numpy.testing as npt
+
+    syms = symbols('_0,_1,_2')
+    s1 = symarray("", 3)
+    s2 = symarray("", 3)
+    npt.assert_array_equal(s1, np.array(syms, dtype=object))
+    assert s1[0] == s2[0]
+
+    a = symarray('a', 3)
+    b = symarray('b', 3)
+    assert not(a[0] == b[0])
+
+    asyms = symbols('a_0,a_1,a_2')
+    npt.assert_array_equal(a, np.array(asyms, dtype=object))
+
+    # Multidimensional checks
+    a2d = symarray('a', (2, 3))
+    assert a2d.shape == (2, 3)
+    a00, a12 = symbols('a_0_0,a_1_2')
+    assert a2d[0, 0] == a00
+    assert a2d[1, 2] == a12
+
+    a3d = symarray('a', (2, 3, 2))
+    assert a3d.shape == (2, 3, 2)
+    a000, a120, a121 = symbols('a_0_0_0,a_1_2_0,a_1_2_1')
+    assert a3d[0, 0, 0] == a000
+    assert a3d[1, 2, 0] == a120
+    assert a3d[1, 2, 1] == a121
+
+
+def test_vectorize():
+    assert (numpy.vectorize(
+        sin)([1, 2, 3]) == numpy.array([sin(1), sin(2), sin(3)])).all()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_pythonmpq.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_pythonmpq.py
new file mode 100644
index 0000000000000000000000000000000000000000..137cfdf5c858544f0811ae666f000cfb368787a0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_pythonmpq.py
@@ -0,0 +1,176 @@
+"""
+test_pythonmpq.py
+
+Test the PythonMPQ class for consistency with gmpy2's mpq type. If gmpy2 is
+installed run the same tests for both.
+"""
+from fractions import Fraction
+from decimal import Decimal
+import pickle
+from typing import Callable, List, Tuple, Type
+
+from sympy.testing.pytest import raises
+
+from sympy.external.pythonmpq import PythonMPQ
+
+#
+# If gmpy2 is installed then run the tests for both mpq and PythonMPQ.
+# That should ensure consistency between the implementation here and mpq.
+#
+rational_types: List[Tuple[Callable, Type, Callable, Type]]
+rational_types = [(PythonMPQ, PythonMPQ, int, int)]
+try:
+    from gmpy2 import mpq, mpz
+    rational_types.append((mpq, type(mpq(1)), mpz, type(mpz(1))))
+except ImportError:
+    pass
+
+
+def test_PythonMPQ():
+    #
+    # Test PythonMPQ and also mpq if gmpy/gmpy2 is installed.
+    #
+    for Q, TQ, Z, TZ in rational_types:
+
+        def check_Q(q):
+            assert isinstance(q, TQ)
+            assert isinstance(q.numerator, TZ)
+            assert isinstance(q.denominator, TZ)
+            return q.numerator, q.denominator
+
+        # Check construction from different types
+        assert check_Q(Q(3)) == (3, 1)
+        assert check_Q(Q(3, 5)) == (3, 5)
+        assert check_Q(Q(Q(3, 5))) == (3, 5)
+        assert check_Q(Q(0.5)) == (1, 2)
+        assert check_Q(Q('0.5')) == (1, 2)
+        assert check_Q(Q(Fraction(3, 5))) == (3, 5)
+
+        # https://github.com/aleaxit/gmpy/issues/327
+        if Q is PythonMPQ:
+            assert check_Q(Q(Decimal('0.6'))) == (3, 5)
+
+        # Invalid types
+        raises(TypeError, lambda: Q([]))
+        raises(TypeError, lambda: Q([], []))
+
+        # Check normalisation of signs
+        assert check_Q(Q(2, 3)) == (2, 3)
+        assert check_Q(Q(-2, 3)) == (-2, 3)
+        assert check_Q(Q(2, -3)) == (-2, 3)
+        assert check_Q(Q(-2, -3)) == (2, 3)
+
+        # Check gcd calculation
+        assert check_Q(Q(12, 8)) == (3, 2)
+
+        # __int__/__float__
+        assert int(Q(5, 3)) == 1
+        assert int(Q(-5, 3)) == -1
+        assert float(Q(5, 2)) == 2.5
+        assert float(Q(-5, 2)) == -2.5
+
+        # __str__/__repr__
+        assert str(Q(2, 1)) == "2"
+        assert str(Q(1, 2)) == "1/2"
+        if Q is PythonMPQ:
+            assert repr(Q(2, 1)) == "MPQ(2,1)"
+            assert repr(Q(1, 2)) == "MPQ(1,2)"
+        else:
+            assert repr(Q(2, 1)) == "mpq(2,1)"
+            assert repr(Q(1, 2)) == "mpq(1,2)"
+
+        # __bool__
+        assert bool(Q(1, 2)) is True
+        assert bool(Q(0)) is False
+
+        # __eq__/__ne__
+        assert (Q(2, 3) == Q(2, 3)) is True
+        assert (Q(2, 3) == Q(2, 5)) is False
+        assert (Q(2, 3) != Q(2, 3)) is False
+        assert (Q(2, 3) != Q(2, 5)) is True
+
+        # __hash__
+        assert hash(Q(3, 5)) == hash(Fraction(3, 5))
+
+        # __reduce__
+        q = Q(2, 3)
+        assert pickle.loads(pickle.dumps(q)) == q
+
+        # __ge__/__gt__/__le__/__lt__
+        assert (Q(1, 3) < Q(2, 3)) is True
+        assert (Q(2, 3) < Q(2, 3)) is False
+        assert (Q(2, 3) < Q(1, 3)) is False
+        assert (Q(-2, 3) < Q(1, 3)) is True
+        assert (Q(1, 3) < Q(-2, 3)) is False
+
+        assert (Q(1, 3) <= Q(2, 3)) is True
+        assert (Q(2, 3) <= Q(2, 3)) is True
+        assert (Q(2, 3) <= Q(1, 3)) is False
+        assert (Q(-2, 3) <= Q(1, 3)) is True
+        assert (Q(1, 3) <= Q(-2, 3)) is False
+
+        assert (Q(1, 3) > Q(2, 3)) is False
+        assert (Q(2, 3) > Q(2, 3)) is False
+        assert (Q(2, 3) > Q(1, 3)) is True
+        assert (Q(-2, 3) > Q(1, 3)) is False
+        assert (Q(1, 3) > Q(-2, 3)) is True
+
+        assert (Q(1, 3) >= Q(2, 3)) is False
+        assert (Q(2, 3) >= Q(2, 3)) is True
+        assert (Q(2, 3) >= Q(1, 3)) is True
+        assert (Q(-2, 3) >= Q(1, 3)) is False
+        assert (Q(1, 3) >= Q(-2, 3)) is True
+
+        # __abs__/__pos__/__neg__
+        assert abs(Q(2, 3)) == abs(Q(-2, 3)) == Q(2, 3)
+        assert +Q(2, 3) == Q(2, 3)
+        assert -Q(2, 3) == Q(-2, 3)
+
+        # __add__/__radd__
+        assert Q(2, 3) + Q(5, 7) == Q(29, 21)
+        assert Q(2, 3) + 1 == Q(5, 3)
+        assert 1 + Q(2, 3) == Q(5, 3)
+        raises(TypeError, lambda: [] + Q(1))
+        raises(TypeError, lambda: Q(1) + [])
+
+        # __sub__/__rsub__
+        assert Q(2, 3) - Q(5, 7) == Q(-1, 21)
+        assert Q(2, 3) - 1 == Q(-1, 3)
+        assert 1 - Q(2, 3) == Q(1, 3)
+        raises(TypeError, lambda: [] - Q(1))
+        raises(TypeError, lambda: Q(1) - [])
+
+        # __mul__/__rmul__
+        assert Q(2, 3) * Q(5, 7) == Q(10, 21)
+        assert Q(2, 3) * 1 == Q(2, 3)
+        assert 1 * Q(2, 3) == Q(2, 3)
+        raises(TypeError, lambda: [] * Q(1))
+        raises(TypeError, lambda: Q(1) * [])
+
+        # __pow__/__rpow__
+        assert Q(2, 3) ** 2 == Q(4, 9)
+        assert Q(2, 3) ** 1 == Q(2, 3)
+        assert Q(-2, 3) ** 2 == Q(4, 9)
+        assert Q(-2, 3) ** -1 == Q(-3, 2)
+        if Q is PythonMPQ:
+            raises(TypeError, lambda: 1 ** Q(2, 3))
+            raises(TypeError, lambda: Q(1, 4) ** Q(1, 2))
+        raises(TypeError, lambda: [] ** Q(1))
+        raises(TypeError, lambda: Q(1) ** [])
+
+        # __div__/__rdiv__
+        assert Q(2, 3) / Q(5, 7) == Q(14, 15)
+        assert Q(2, 3) / 1 == Q(2, 3)
+        assert 1 / Q(2, 3) == Q(3, 2)
+        raises(TypeError, lambda: [] / Q(1))
+        raises(TypeError, lambda: Q(1) / [])
+        raises(ZeroDivisionError, lambda: Q(1, 2) / Q(0))
+
+        # __divmod__
+        if Q is PythonMPQ:
+            raises(TypeError, lambda: Q(2, 3) // Q(1, 3))
+            raises(TypeError, lambda: Q(2, 3) % Q(1, 3))
+            raises(TypeError, lambda: 1 // Q(1, 3))
+            raises(TypeError, lambda: 1 % Q(1, 3))
+            raises(TypeError, lambda: Q(2, 3) // 1)
+            raises(TypeError, lambda: Q(2, 3) % 1)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_scipy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_scipy.py
new file mode 100644
index 0000000000000000000000000000000000000000..3746d1a311eb68bb1af16e18ab152c7236b42bb5
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/external/tests/test_scipy.py
@@ -0,0 +1,35 @@
+# This testfile tests SymPy <-> SciPy compatibility
+
+# Don't test any SymPy features here. Just pure interaction with SciPy.
+# Always write regular SymPy tests for anything, that can be tested in pure
+# Python (without scipy). Here we test everything, that a user may need when
+# using SymPy with SciPy
+
+from sympy.external import import_module
+
+scipy = import_module('scipy')
+if not scipy:
+    #bin/test will not execute any tests now
+    disabled = True
+
+from sympy.functions.special.bessel import jn_zeros
+
+
+def eq(a, b, tol=1e-6):
+    for x, y in zip(a, b):
+        if not (abs(x - y) < tol):
+            return False
+    return True
+
+
+def test_jn_zeros():
+    assert eq(jn_zeros(0, 4, method="scipy"),
+            [3.141592, 6.283185, 9.424777, 12.566370])
+    assert eq(jn_zeros(1, 4, method="scipy"),
+            [4.493409, 7.725251, 10.904121, 14.066193])
+    assert eq(jn_zeros(2, 4, method="scipy"),
+            [5.763459, 9.095011, 12.322940, 15.514603])
+    assert eq(jn_zeros(3, 4, method="scipy"),
+            [6.987932, 10.417118, 13.698023, 16.923621])
+    assert eq(jn_zeros(4, 4, method="scipy"),
+            [8.182561, 11.704907, 15.039664, 18.301255])
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb85d4ff5d53eb44a039a95cfc2fff687322cc76
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__init__.py
@@ -0,0 +1,45 @@
+"""
+A geometry module for the SymPy library. This module contains all of the
+entities and functions needed to construct basic geometrical data and to
+perform simple informational queries.
+
+Usage:
+======
+
+Examples
+========
+
+"""
+from sympy.geometry.point import Point, Point2D, Point3D
+from sympy.geometry.line import Line, Ray, Segment, Line2D, Segment2D, Ray2D, \
+    Line3D, Segment3D, Ray3D
+from sympy.geometry.plane import Plane
+from sympy.geometry.ellipse import Ellipse, Circle
+from sympy.geometry.polygon import Polygon, RegularPolygon, Triangle, rad, deg
+from sympy.geometry.util import are_similar, centroid, convex_hull, idiff, \
+    intersection, closest_points, farthest_points
+from sympy.geometry.exceptions import GeometryError
+from sympy.geometry.curve import Curve
+from sympy.geometry.parabola import Parabola
+
+__all__ = [
+    'Point', 'Point2D', 'Point3D',
+
+    'Line', 'Ray', 'Segment', 'Line2D', 'Segment2D', 'Ray2D', 'Line3D',
+    'Segment3D', 'Ray3D',
+
+    'Plane',
+
+    'Ellipse', 'Circle',
+
+    'Polygon', 'RegularPolygon', 'Triangle', 'rad', 'deg',
+
+    'are_similar', 'centroid', 'convex_hull', 'idiff', 'intersection',
+    'closest_points', 'farthest_points',
+
+    'GeometryError',
+
+    'Curve',
+
+    'Parabola',
+]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7fa4998afc41c883ed337ca25ba6db89a9facac4
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/curve.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/curve.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..044940ac88d1b543d4203745ba0050cd4f94f3dd
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/curve.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/ellipse.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/ellipse.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9b75eb3155fcd2de8d6b7192bd56a96eab169439
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/ellipse.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/entity.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/entity.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4adceb77555498ca9b63c12b9a41b3a68165c0ca
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/entity.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/exceptions.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/exceptions.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..55ecdf8334277343ae9879b423bb5ffc9313d741
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/exceptions.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/line.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/line.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5a71d7b706d33395e4866e0a3ac0a50a8f45829a
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/line.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/parabola.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/parabola.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..78b529a397614d8739e047beea86dc7967c74dc0
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/parabola.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/plane.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/plane.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7fe8f2d6e632acb125df2ef1321d785ed448bacb
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/plane.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/point.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/point.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8eab8ad599a83bf5832822ef4e2e12921f971a1c
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/point.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/polygon.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/polygon.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..54f3151c35e78f8dbdb94effd02f5088dfaf5029
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/polygon.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/util.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/util.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ab41171fc0dc861858681ed1761c4cbf96177cb
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/__pycache__/util.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/curve.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/curve.py
new file mode 100644
index 0000000000000000000000000000000000000000..c074f22cad79b1261ad44be4ccface972cdd3b82
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/curve.py
@@ -0,0 +1,424 @@
+"""Curves in 2-dimensional Euclidean space.
+
+Contains
+========
+Curve
+
+"""
+
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.core import diff
+from sympy.core.containers import Tuple
+from sympy.core.symbol import _symbol
+from sympy.geometry.entity import GeometryEntity, GeometrySet
+from sympy.geometry.point import Point
+from sympy.integrals import integrate
+from sympy.matrices import Matrix, rot_axis3
+from sympy.utilities.iterables import is_sequence
+
+from mpmath.libmp.libmpf import prec_to_dps
+
+
+class Curve(GeometrySet):
+    """A curve in space.
+
+    A curve is defined by parametric functions for the coordinates, a
+    parameter and the lower and upper bounds for the parameter value.
+
+    Parameters
+    ==========
+
+    function : list of functions
+    limits : 3-tuple
+        Function parameter and lower and upper bounds.
+
+    Attributes
+    ==========
+
+    functions
+    parameter
+    limits
+
+    Raises
+    ======
+
+    ValueError
+        When `functions` are specified incorrectly.
+        When `limits` are specified incorrectly.
+
+    Examples
+    ========
+
+    >>> from sympy import Curve, sin, cos, interpolate
+    >>> from sympy.abc import t, a
+    >>> C = Curve((sin(t), cos(t)), (t, 0, 2))
+    >>> C.functions
+    (sin(t), cos(t))
+    >>> C.limits
+    (t, 0, 2)
+    >>> C.parameter
+    t
+    >>> C = Curve((t, interpolate([1, 4, 9, 16], t)), (t, 0, 1)); C
+    Curve((t, t**2), (t, 0, 1))
+    >>> C.subs(t, 4)
+    Point2D(4, 16)
+    >>> C.arbitrary_point(a)
+    Point2D(a, a**2)
+
+    See Also
+    ========
+
+    sympy.core.function.Function
+    sympy.polys.polyfuncs.interpolate
+
+    """
+
+    def __new__(cls, function, limits):
+        if not is_sequence(function) or len(function) != 2:
+            raise ValueError("Function argument should be (x(t), y(t)) "
+                "but got %s" % str(function))
+        if not is_sequence(limits) or len(limits) != 3:
+            raise ValueError("Limit argument should be (t, tmin, tmax) "
+                "but got %s" % str(limits))
+
+        return GeometryEntity.__new__(cls, Tuple(*function), Tuple(*limits))
+
+    def __call__(self, f):
+        return self.subs(self.parameter, f)
+
+    def _eval_subs(self, old, new):
+        if old == self.parameter:
+            return Point(*[f.subs(old, new) for f in self.functions])
+
+    def _eval_evalf(self, prec=15, **options):
+        f, (t, a, b) = self.args
+        dps = prec_to_dps(prec)
+        f = tuple([i.evalf(n=dps, **options) for i in f])
+        a, b = [i.evalf(n=dps, **options) for i in (a, b)]
+        return self.func(f, (t, a, b))
+
+    def arbitrary_point(self, parameter='t'):
+        """A parameterized point on the curve.
+
+        Parameters
+        ==========
+
+        parameter : str or Symbol, optional
+            Default value is 't'.
+            The Curve's parameter is selected with None or self.parameter
+            otherwise the provided symbol is used.
+
+        Returns
+        =======
+
+        Point :
+            Returns a point in parametric form.
+
+        Raises
+        ======
+
+        ValueError
+            When `parameter` already appears in the functions.
+
+        Examples
+        ========
+
+        >>> from sympy import Curve, Symbol
+        >>> from sympy.abc import s
+        >>> C = Curve([2*s, s**2], (s, 0, 2))
+        >>> C.arbitrary_point()
+        Point2D(2*t, t**2)
+        >>> C.arbitrary_point(C.parameter)
+        Point2D(2*s, s**2)
+        >>> C.arbitrary_point(None)
+        Point2D(2*s, s**2)
+        >>> C.arbitrary_point(Symbol('a'))
+        Point2D(2*a, a**2)
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point
+
+        """
+        if parameter is None:
+            return Point(*self.functions)
+
+        tnew = _symbol(parameter, self.parameter, real=True)
+        t = self.parameter
+        if (tnew.name != t.name and
+                tnew.name in (f.name for f in self.free_symbols)):
+            raise ValueError('Symbol %s already appears in object '
+                'and cannot be used as a parameter.' % tnew.name)
+        return Point(*[w.subs(t, tnew) for w in self.functions])
+
+    @property
+    def free_symbols(self):
+        """Return a set of symbols other than the bound symbols used to
+        parametrically define the Curve.
+
+        Returns
+        =======
+
+        set :
+            Set of all non-parameterized symbols.
+
+        Examples
+        ========
+
+        >>> from sympy.abc import t, a
+        >>> from sympy import Curve
+        >>> Curve((t, t**2), (t, 0, 2)).free_symbols
+        set()
+        >>> Curve((t, t**2), (t, a, 2)).free_symbols
+        {a}
+
+        """
+        free = set()
+        for a in self.functions + self.limits[1:]:
+            free |= a.free_symbols
+        free = free.difference({self.parameter})
+        return free
+
+    @property
+    def ambient_dimension(self):
+        """The dimension of the curve.
+
+        Returns
+        =======
+
+        int :
+            the dimension of curve.
+
+        Examples
+        ========
+
+        >>> from sympy.abc import t
+        >>> from sympy import Curve
+        >>> C = Curve((t, t**2), (t, 0, 2))
+        >>> C.ambient_dimension
+        2
+
+        """
+
+        return len(self.args[0])
+
+    @property
+    def functions(self):
+        """The functions specifying the curve.
+
+        Returns
+        =======
+
+        functions :
+            list of parameterized coordinate functions.
+
+        Examples
+        ========
+
+        >>> from sympy.abc import t
+        >>> from sympy import Curve
+        >>> C = Curve((t, t**2), (t, 0, 2))
+        >>> C.functions
+        (t, t**2)
+
+        See Also
+        ========
+
+        parameter
+
+        """
+        return self.args[0]
+
+    @property
+    def limits(self):
+        """The limits for the curve.
+
+        Returns
+        =======
+
+        limits : tuple
+            Contains parameter and lower and upper limits.
+
+        Examples
+        ========
+
+        >>> from sympy.abc import t
+        >>> from sympy import Curve
+        >>> C = Curve([t, t**3], (t, -2, 2))
+        >>> C.limits
+        (t, -2, 2)
+
+        See Also
+        ========
+
+        plot_interval
+
+        """
+        return self.args[1]
+
+    @property
+    def parameter(self):
+        """The curve function variable.
+
+        Returns
+        =======
+
+        Symbol :
+            returns a bound symbol.
+
+        Examples
+        ========
+
+        >>> from sympy.abc import t
+        >>> from sympy import Curve
+        >>> C = Curve([t, t**2], (t, 0, 2))
+        >>> C.parameter
+        t
+
+        See Also
+        ========
+
+        functions
+
+        """
+        return self.args[1][0]
+
+    @property
+    def length(self):
+        """The curve length.
+
+        Examples
+        ========
+
+        >>> from sympy import Curve
+        >>> from sympy.abc import t
+        >>> Curve((t, t), (t, 0, 1)).length
+        sqrt(2)
+
+        """
+        integrand = sqrt(sum(diff(func, self.limits[0])**2 for func in self.functions))
+        return integrate(integrand, self.limits)
+
+    def plot_interval(self, parameter='t'):
+        """The plot interval for the default geometric plot of the curve.
+
+        Parameters
+        ==========
+
+        parameter : str or Symbol, optional
+            Default value is 't';
+            otherwise the provided symbol is used.
+
+        Returns
+        =======
+
+        List :
+            the plot interval as below:
+                [parameter, lower_bound, upper_bound]
+
+        Examples
+        ========
+
+        >>> from sympy import Curve, sin
+        >>> from sympy.abc import x, s
+        >>> Curve((x, sin(x)), (x, 1, 2)).plot_interval()
+        [t, 1, 2]
+        >>> Curve((x, sin(x)), (x, 1, 2)).plot_interval(s)
+        [s, 1, 2]
+
+        See Also
+        ========
+
+        limits : Returns limits of the parameter interval
+
+        """
+        t = _symbol(parameter, self.parameter, real=True)
+        return [t] + list(self.limits[1:])
+
+    def rotate(self, angle=0, pt=None):
+        """This function is used to rotate a curve along given point ``pt`` at given angle(in radian).
+
+        Parameters
+        ==========
+
+        angle :
+            the angle at which the curve will be rotated(in radian) in counterclockwise direction.
+            default value of angle is 0.
+
+        pt : Point
+            the point along which the curve will be rotated.
+            If no point given, the curve will be rotated around origin.
+
+        Returns
+        =======
+
+        Curve :
+            returns a curve rotated at given angle along given point.
+
+        Examples
+        ========
+
+        >>> from sympy import Curve, pi
+        >>> from sympy.abc import x
+        >>> Curve((x, x), (x, 0, 1)).rotate(pi/2)
+        Curve((-x, x), (x, 0, 1))
+
+        """
+        if pt:
+            pt = -Point(pt, dim=2)
+        else:
+            pt = Point(0,0)
+        rv = self.translate(*pt.args)
+        f = list(rv.functions)
+        f.append(0)
+        f = Matrix(1, 3, f)
+        f *= rot_axis3(angle)
+        rv = self.func(f[0, :2].tolist()[0], self.limits)
+        pt = -pt
+        return rv.translate(*pt.args)
+
+    def scale(self, x=1, y=1, pt=None):
+        """Override GeometryEntity.scale since Curve is not made up of Points.
+
+        Returns
+        =======
+
+        Curve :
+            returns scaled curve.
+
+        Examples
+        ========
+
+        >>> from sympy import Curve
+        >>> from sympy.abc import x
+        >>> Curve((x, x), (x, 0, 1)).scale(2)
+        Curve((2*x, x), (x, 0, 1))
+
+        """
+        if pt:
+            pt = Point(pt, dim=2)
+            return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
+        fx, fy = self.functions
+        return self.func((fx*x, fy*y), self.limits)
+
+    def translate(self, x=0, y=0):
+        """Translate the Curve by (x, y).
+
+        Returns
+        =======
+
+        Curve :
+            returns a translated curve.
+
+        Examples
+        ========
+
+        >>> from sympy import Curve
+        >>> from sympy.abc import x
+        >>> Curve((x, x), (x, 0, 1)).translate(1, 2)
+        Curve((x + 1, x + 2), (x, 0, 1))
+
+        """
+        fx, fy = self.functions
+        return self.func((fx + x, fy + y), self.limits)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/ellipse.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/ellipse.py
new file mode 100644
index 0000000000000000000000000000000000000000..199db25fde9b019893a275d69959154990e8a4a7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/ellipse.py
@@ -0,0 +1,1768 @@
+"""Elliptical geometrical entities.
+
+Contains
+* Ellipse
+* Circle
+
+"""
+
+from sympy.core.expr import Expr
+from sympy.core.relational import Eq
+from sympy.core import S, pi, sympify
+from sympy.core.evalf import N
+from sympy.core.parameters import global_parameters
+from sympy.core.logic import fuzzy_bool
+from sympy.core.numbers import Rational, oo
+from sympy.core.sorting import ordered
+from sympy.core.symbol import Dummy, uniquely_named_symbol, _symbol
+from sympy.simplify.simplify import simplify
+from sympy.simplify.trigsimp import trigsimp
+from sympy.functions.elementary.miscellaneous import sqrt, Max
+from sympy.functions.elementary.trigonometric import cos, sin
+from sympy.functions.special.elliptic_integrals import elliptic_e
+from .entity import GeometryEntity, GeometrySet
+from .exceptions import GeometryError
+from .line import Line, Segment, Ray2D, Segment2D, Line2D, LinearEntity3D
+from .point import Point, Point2D, Point3D
+from .util import idiff, find
+from sympy.polys import DomainError, Poly, PolynomialError
+from sympy.polys.polyutils import _not_a_coeff, _nsort
+from sympy.solvers import solve
+from sympy.solvers.solveset import linear_coeffs
+from sympy.utilities.misc import filldedent, func_name
+
+from mpmath.libmp.libmpf import prec_to_dps
+
+import random
+
+x, y = [Dummy('ellipse_dummy', real=True) for i in range(2)]
+
+
+class Ellipse(GeometrySet):
+    """An elliptical GeometryEntity.
+
+    Parameters
+    ==========
+
+    center : Point, optional
+        Default value is Point(0, 0)
+    hradius : number or SymPy expression, optional
+    vradius : number or SymPy expression, optional
+    eccentricity : number or SymPy expression, optional
+        Two of `hradius`, `vradius` and `eccentricity` must be supplied to
+        create an Ellipse. The third is derived from the two supplied.
+
+    Attributes
+    ==========
+
+    center
+    hradius
+    vradius
+    area
+    circumference
+    eccentricity
+    periapsis
+    apoapsis
+    focus_distance
+    foci
+
+    Raises
+    ======
+
+    GeometryError
+        When `hradius`, `vradius` and `eccentricity` are incorrectly supplied
+        as parameters.
+    TypeError
+        When `center` is not a Point.
+
+    See Also
+    ========
+
+    Circle
+
+    Notes
+    -----
+    Constructed from a center and two radii, the first being the horizontal
+    radius (along the x-axis) and the second being the vertical radius (along
+    the y-axis).
+
+    When symbolic value for hradius and vradius are used, any calculation that
+    refers to the foci or the major or minor axis will assume that the ellipse
+    has its major radius on the x-axis. If this is not true then a manual
+    rotation is necessary.
+
+    Examples
+    ========
+
+    >>> from sympy import Ellipse, Point, Rational
+    >>> e1 = Ellipse(Point(0, 0), 5, 1)
+    >>> e1.hradius, e1.vradius
+    (5, 1)
+    >>> e2 = Ellipse(Point(3, 1), hradius=3, eccentricity=Rational(4, 5))
+    >>> e2
+    Ellipse(Point2D(3, 1), 3, 9/5)
+
+    """
+
+    def __contains__(self, o):
+        if isinstance(o, Point):
+            res = self.equation(x, y).subs({x: o.x, y: o.y})
+            return trigsimp(simplify(res)) is S.Zero
+        elif isinstance(o, Ellipse):
+            return self == o
+        return False
+
+    def __eq__(self, o):
+        """Is the other GeometryEntity the same as this ellipse?"""
+        return isinstance(o, Ellipse) and (self.center == o.center and
+                                           self.hradius == o.hradius and
+                                           self.vradius == o.vradius)
+
+    def __hash__(self):
+        return super().__hash__()
+
+    def __new__(
+        cls, center=None, hradius=None, vradius=None, eccentricity=None, **kwargs):
+
+        hradius = sympify(hradius)
+        vradius = sympify(vradius)
+
+        if center is None:
+            center = Point(0, 0)
+        else:
+            if len(center) != 2:
+                raise ValueError('The center of "{}" must be a two dimensional point'.format(cls))
+            center = Point(center, dim=2)
+
+        if len(list(filter(lambda x: x is not None, (hradius, vradius, eccentricity)))) != 2:
+            raise ValueError(filldedent('''
+                Exactly two arguments of "hradius", "vradius", and
+                "eccentricity" must not be None.'''))
+
+        if eccentricity is not None:
+            eccentricity = sympify(eccentricity)
+            if eccentricity.is_negative:
+                raise GeometryError("Eccentricity of ellipse/circle should lie between [0, 1)")
+            elif hradius is None:
+                hradius = vradius / sqrt(1 - eccentricity**2)
+            elif vradius is None:
+                vradius = hradius * sqrt(1 - eccentricity**2)
+
+        if hradius == vradius:
+            return Circle(center, hradius, **kwargs)
+
+        if S.Zero in (hradius, vradius):
+            return Segment(Point(center[0] - hradius, center[1] - vradius), Point(center[0] + hradius, center[1] + vradius))
+
+        if hradius.is_real is False or vradius.is_real is False:
+            raise GeometryError("Invalid value encountered when computing hradius / vradius.")
+
+        return GeometryEntity.__new__(cls, center, hradius, vradius, **kwargs)
+
+    def _svg(self, scale_factor=1., fill_color="#66cc99"):
+        """Returns SVG ellipse element for the Ellipse.
+
+        Parameters
+        ==========
+
+        scale_factor : float
+            Multiplication factor for the SVG stroke-width.  Default is 1.
+        fill_color : str, optional
+            Hex string for fill color. Default is "#66cc99".
+        """
+
+        c = N(self.center)
+        h, v = N(self.hradius), N(self.vradius)
+        return (
+            ''
+        ).format(2. * scale_factor, fill_color, c.x, c.y, h, v)
+
+    @property
+    def ambient_dimension(self):
+        return 2
+
+    @property
+    def apoapsis(self):
+        """The apoapsis of the ellipse.
+
+        The greatest distance between the focus and the contour.
+
+        Returns
+        =======
+
+        apoapsis : number
+
+        See Also
+        ========
+
+        periapsis : Returns shortest distance between foci and contour
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse
+        >>> p1 = Point(0, 0)
+        >>> e1 = Ellipse(p1, 3, 1)
+        >>> e1.apoapsis
+        2*sqrt(2) + 3
+
+        """
+        return self.major * (1 + self.eccentricity)
+
+    def arbitrary_point(self, parameter='t'):
+        """A parameterized point on the ellipse.
+
+        Parameters
+        ==========
+
+        parameter : str, optional
+            Default value is 't'.
+
+        Returns
+        =======
+
+        arbitrary_point : Point
+
+        Raises
+        ======
+
+        ValueError
+            When `parameter` already appears in the functions.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse
+        >>> e1 = Ellipse(Point(0, 0), 3, 2)
+        >>> e1.arbitrary_point()
+        Point2D(3*cos(t), 2*sin(t))
+
+        """
+        t = _symbol(parameter, real=True)
+        if t.name in (f.name for f in self.free_symbols):
+            raise ValueError(filldedent('Symbol %s already appears in object '
+                                        'and cannot be used as a parameter.' % t.name))
+        return Point(self.center.x + self.hradius*cos(t),
+                     self.center.y + self.vradius*sin(t))
+
+    @property
+    def area(self):
+        """The area of the ellipse.
+
+        Returns
+        =======
+
+        area : number
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse
+        >>> p1 = Point(0, 0)
+        >>> e1 = Ellipse(p1, 3, 1)
+        >>> e1.area
+        3*pi
+
+        """
+        return simplify(S.Pi * self.hradius * self.vradius)
+
+    @property
+    def bounds(self):
+        """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding
+        rectangle for the geometric figure.
+
+        """
+
+        h, v = self.hradius, self.vradius
+        return (self.center.x - h, self.center.y - v, self.center.x + h, self.center.y + v)
+
+    @property
+    def center(self):
+        """The center of the ellipse.
+
+        Returns
+        =======
+
+        center : number
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse
+        >>> p1 = Point(0, 0)
+        >>> e1 = Ellipse(p1, 3, 1)
+        >>> e1.center
+        Point2D(0, 0)
+
+        """
+        return self.args[0]
+
+    @property
+    def circumference(self):
+        """The circumference of the ellipse.
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse
+        >>> p1 = Point(0, 0)
+        >>> e1 = Ellipse(p1, 3, 1)
+        >>> e1.circumference
+        12*elliptic_e(8/9)
+
+        """
+        if self.eccentricity == 1:
+            # degenerate
+            return 4*self.major
+        elif self.eccentricity == 0:
+            # circle
+            return 2*pi*self.hradius
+        else:
+            return 4*self.major*elliptic_e(self.eccentricity**2)
+
+    @property
+    def eccentricity(self):
+        """The eccentricity of the ellipse.
+
+        Returns
+        =======
+
+        eccentricity : number
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse, sqrt
+        >>> p1 = Point(0, 0)
+        >>> e1 = Ellipse(p1, 3, sqrt(2))
+        >>> e1.eccentricity
+        sqrt(7)/3
+
+        """
+        return self.focus_distance / self.major
+
+    def encloses_point(self, p):
+        """
+        Return True if p is enclosed by (is inside of) self.
+
+        Notes
+        -----
+        Being on the border of self is considered False.
+
+        Parameters
+        ==========
+
+        p : Point
+
+        Returns
+        =======
+
+        encloses_point : True, False or None
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point
+
+        Examples
+        ========
+
+        >>> from sympy import Ellipse, S
+        >>> from sympy.abc import t
+        >>> e = Ellipse((0, 0), 3, 2)
+        >>> e.encloses_point((0, 0))
+        True
+        >>> e.encloses_point(e.arbitrary_point(t).subs(t, S.Half))
+        False
+        >>> e.encloses_point((4, 0))
+        False
+
+        """
+        p = Point(p, dim=2)
+        if p in self:
+            return False
+
+        if len(self.foci) == 2:
+            # if the combined distance from the foci to p (h1 + h2) is less
+            # than the combined distance from the foci to the minor axis
+            # (which is the same as the major axis length) then p is inside
+            # the ellipse
+            h1, h2 = [f.distance(p) for f in self.foci]
+            test = 2*self.major - (h1 + h2)
+        else:
+            test = self.radius - self.center.distance(p)
+
+        return fuzzy_bool(test.is_positive)
+
+    def equation(self, x='x', y='y', _slope=None):
+        """
+        Returns the equation of an ellipse aligned with the x and y axes;
+        when slope is given, the equation returned corresponds to an ellipse
+        with a major axis having that slope.
+
+        Parameters
+        ==========
+
+        x : str, optional
+            Label for the x-axis. Default value is 'x'.
+        y : str, optional
+            Label for the y-axis. Default value is 'y'.
+        _slope : Expr, optional
+                The slope of the major axis. Ignored when 'None'.
+
+        Returns
+        =======
+
+        equation : SymPy expression
+
+        See Also
+        ========
+
+        arbitrary_point : Returns parameterized point on ellipse
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse, pi
+        >>> from sympy.abc import x, y
+        >>> e1 = Ellipse(Point(1, 0), 3, 2)
+        >>> eq1 = e1.equation(x, y); eq1
+        y**2/4 + (x/3 - 1/3)**2 - 1
+        >>> eq2 = e1.equation(x, y, _slope=1); eq2
+        (-x + y + 1)**2/8 + (x + y - 1)**2/18 - 1
+
+        A point on e1 satisfies eq1. Let's use one on the x-axis:
+
+        >>> p1 = e1.center + Point(e1.major, 0)
+        >>> assert eq1.subs(x, p1.x).subs(y, p1.y) == 0
+
+        When rotated the same as the rotated ellipse, about the center
+        point of the ellipse, it will satisfy the rotated ellipse's
+        equation, too:
+
+        >>> r1 = p1.rotate(pi/4, e1.center)
+        >>> assert eq2.subs(x, r1.x).subs(y, r1.y) == 0
+
+        References
+        ==========
+
+        .. [1] https://math.stackexchange.com/questions/108270/what-is-the-equation-of-an-ellipse-that-is-not-aligned-with-the-axis
+        .. [2] https://en.wikipedia.org/wiki/Ellipse#Shifted_ellipse
+
+        """
+
+        x = _symbol(x, real=True)
+        y = _symbol(y, real=True)
+
+        dx = x - self.center.x
+        dy = y - self.center.y
+
+        if _slope is not None:
+            L = (dy - _slope*dx)**2
+            l = (_slope*dy + dx)**2
+            h = 1 + _slope**2
+            b = h*self.major**2
+            a = h*self.minor**2
+            return l/b + L/a - 1
+
+        else:
+            t1 = (dx/self.hradius)**2
+            t2 = (dy/self.vradius)**2
+            return t1 + t2 - 1
+
+    def evolute(self, x='x', y='y'):
+        """The equation of evolute of the ellipse.
+
+        Parameters
+        ==========
+
+        x : str, optional
+            Label for the x-axis. Default value is 'x'.
+        y : str, optional
+            Label for the y-axis. Default value is 'y'.
+
+        Returns
+        =======
+
+        equation : SymPy expression
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse
+        >>> e1 = Ellipse(Point(1, 0), 3, 2)
+        >>> e1.evolute()
+        2**(2/3)*y**(2/3) + (3*x - 3)**(2/3) - 5**(2/3)
+        """
+        if len(self.args) != 3:
+            raise NotImplementedError('Evolute of arbitrary Ellipse is not supported.')
+        x = _symbol(x, real=True)
+        y = _symbol(y, real=True)
+        t1 = (self.hradius*(x - self.center.x))**Rational(2, 3)
+        t2 = (self.vradius*(y - self.center.y))**Rational(2, 3)
+        return t1 + t2 - (self.hradius**2 - self.vradius**2)**Rational(2, 3)
+
+    @property
+    def foci(self):
+        """The foci of the ellipse.
+
+        Notes
+        -----
+        The foci can only be calculated if the major/minor axes are known.
+
+        Raises
+        ======
+
+        ValueError
+            When the major and minor axis cannot be determined.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point
+        focus_distance : Returns the distance between focus and center
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse
+        >>> p1 = Point(0, 0)
+        >>> e1 = Ellipse(p1, 3, 1)
+        >>> e1.foci
+        (Point2D(-2*sqrt(2), 0), Point2D(2*sqrt(2), 0))
+
+        """
+        c = self.center
+        hr, vr = self.hradius, self.vradius
+        if hr == vr:
+            return (c, c)
+
+        # calculate focus distance manually, since focus_distance calls this
+        # routine
+        fd = sqrt(self.major**2 - self.minor**2)
+        if hr == self.minor:
+            # foci on the y-axis
+            return (c + Point(0, -fd), c + Point(0, fd))
+        elif hr == self.major:
+            # foci on the x-axis
+            return (c + Point(-fd, 0), c + Point(fd, 0))
+
+    @property
+    def focus_distance(self):
+        """The focal distance of the ellipse.
+
+        The distance between the center and one focus.
+
+        Returns
+        =======
+
+        focus_distance : number
+
+        See Also
+        ========
+
+        foci
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse
+        >>> p1 = Point(0, 0)
+        >>> e1 = Ellipse(p1, 3, 1)
+        >>> e1.focus_distance
+        2*sqrt(2)
+
+        """
+        return Point.distance(self.center, self.foci[0])
+
+    @property
+    def hradius(self):
+        """The horizontal radius of the ellipse.
+
+        Returns
+        =======
+
+        hradius : number
+
+        See Also
+        ========
+
+        vradius, major, minor
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse
+        >>> p1 = Point(0, 0)
+        >>> e1 = Ellipse(p1, 3, 1)
+        >>> e1.hradius
+        3
+
+        """
+        return self.args[1]
+
+    def intersection(self, o):
+        """The intersection of this ellipse and another geometrical entity
+        `o`.
+
+        Parameters
+        ==========
+
+        o : GeometryEntity
+
+        Returns
+        =======
+
+        intersection : list of GeometryEntity objects
+
+        Notes
+        -----
+        Currently supports intersections with Point, Line, Segment, Ray,
+        Circle and Ellipse types.
+
+        See Also
+        ========
+
+        sympy.geometry.entity.GeometryEntity
+
+        Examples
+        ========
+
+        >>> from sympy import Ellipse, Point, Line
+        >>> e = Ellipse(Point(0, 0), 5, 7)
+        >>> e.intersection(Point(0, 0))
+        []
+        >>> e.intersection(Point(5, 0))
+        [Point2D(5, 0)]
+        >>> e.intersection(Line(Point(0,0), Point(0, 1)))
+        [Point2D(0, -7), Point2D(0, 7)]
+        >>> e.intersection(Line(Point(5,0), Point(5, 1)))
+        [Point2D(5, 0)]
+        >>> e.intersection(Line(Point(6,0), Point(6, 1)))
+        []
+        >>> e = Ellipse(Point(-1, 0), 4, 3)
+        >>> e.intersection(Ellipse(Point(1, 0), 4, 3))
+        [Point2D(0, -3*sqrt(15)/4), Point2D(0, 3*sqrt(15)/4)]
+        >>> e.intersection(Ellipse(Point(5, 0), 4, 3))
+        [Point2D(2, -3*sqrt(7)/4), Point2D(2, 3*sqrt(7)/4)]
+        >>> e.intersection(Ellipse(Point(100500, 0), 4, 3))
+        []
+        >>> e.intersection(Ellipse(Point(0, 0), 3, 4))
+        [Point2D(3, 0), Point2D(-363/175, -48*sqrt(111)/175), Point2D(-363/175, 48*sqrt(111)/175)]
+        >>> e.intersection(Ellipse(Point(-1, 0), 3, 4))
+        [Point2D(-17/5, -12/5), Point2D(-17/5, 12/5), Point2D(7/5, -12/5), Point2D(7/5, 12/5)]
+        """
+        # TODO: Replace solve with nonlinsolve, when nonlinsolve will be able to solve in real domain
+
+        if isinstance(o, Point):
+            if o in self:
+                return [o]
+            else:
+                return []
+
+        elif isinstance(o, (Segment2D, Ray2D)):
+            ellipse_equation = self.equation(x, y)
+            result = solve([ellipse_equation, Line(
+                o.points[0], o.points[1]).equation(x, y)], [x, y],
+                set=True)[1]
+            return list(ordered([Point(i) for i in result if i in o]))
+
+        elif isinstance(o, Polygon):
+            return o.intersection(self)
+
+        elif isinstance(o, (Ellipse, Line2D)):
+            if o == self:
+                return self
+            else:
+                ellipse_equation = self.equation(x, y)
+                return list(ordered([Point(i) for i in solve(
+                    [ellipse_equation, o.equation(x, y)], [x, y],
+                    set=True)[1]]))
+        elif isinstance(o, LinearEntity3D):
+            raise TypeError('Entity must be two dimensional, not three dimensional')
+        else:
+            raise TypeError('Intersection not handled for %s' % func_name(o))
+
+    def is_tangent(self, o):
+        """Is `o` tangent to the ellipse?
+
+        Parameters
+        ==========
+
+        o : GeometryEntity
+            An Ellipse, LinearEntity or Polygon
+
+        Raises
+        ======
+
+        NotImplementedError
+            When the wrong type of argument is supplied.
+
+        Returns
+        =======
+
+        is_tangent: boolean
+            True if o is tangent to the ellipse, False otherwise.
+
+        See Also
+        ========
+
+        tangent_lines
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse, Line
+        >>> p0, p1, p2 = Point(0, 0), Point(3, 0), Point(3, 3)
+        >>> e1 = Ellipse(p0, 3, 2)
+        >>> l1 = Line(p1, p2)
+        >>> e1.is_tangent(l1)
+        True
+
+        """
+        if isinstance(o, Point2D):
+            return False
+        elif isinstance(o, Ellipse):
+            intersect = self.intersection(o)
+            if isinstance(intersect, Ellipse):
+                return True
+            elif intersect:
+                return all((self.tangent_lines(i)[0]).equals(o.tangent_lines(i)[0]) for i in intersect)
+            else:
+                return False
+        elif isinstance(o, Line2D):
+            hit = self.intersection(o)
+            if not hit:
+                return False
+            if len(hit) == 1:
+                return True
+            # might return None if it can't decide
+            return hit[0].equals(hit[1])
+        elif isinstance(o, (Segment2D, Ray2D)):
+            intersect = self.intersection(o)
+            if len(intersect) == 1:
+                return o in self.tangent_lines(intersect[0])[0]
+            else:
+                return False
+        elif isinstance(o, Polygon):
+            return all(self.is_tangent(s) for s in o.sides)
+        elif isinstance(o, (LinearEntity3D, Point3D)):
+            raise TypeError('Entity must be two dimensional, not three dimensional')
+        else:
+            raise TypeError('Is_tangent not handled for %s' % func_name(o))
+
+    @property
+    def major(self):
+        """Longer axis of the ellipse (if it can be determined) else hradius.
+
+        Returns
+        =======
+
+        major : number or expression
+
+        See Also
+        ========
+
+        hradius, vradius, minor
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse, Symbol
+        >>> p1 = Point(0, 0)
+        >>> e1 = Ellipse(p1, 3, 1)
+        >>> e1.major
+        3
+
+        >>> a = Symbol('a')
+        >>> b = Symbol('b')
+        >>> Ellipse(p1, a, b).major
+        a
+        >>> Ellipse(p1, b, a).major
+        b
+
+        >>> m = Symbol('m')
+        >>> M = m + 1
+        >>> Ellipse(p1, m, M).major
+        m + 1
+
+        """
+        ab = self.args[1:3]
+        if len(ab) == 1:
+            return ab[0]
+        a, b = ab
+        o = b - a < 0
+        if o == True:
+            return a
+        elif o == False:
+            return b
+        return self.hradius
+
+    @property
+    def minor(self):
+        """Shorter axis of the ellipse (if it can be determined) else vradius.
+
+        Returns
+        =======
+
+        minor : number or expression
+
+        See Also
+        ========
+
+        hradius, vradius, major
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse, Symbol
+        >>> p1 = Point(0, 0)
+        >>> e1 = Ellipse(p1, 3, 1)
+        >>> e1.minor
+        1
+
+        >>> a = Symbol('a')
+        >>> b = Symbol('b')
+        >>> Ellipse(p1, a, b).minor
+        b
+        >>> Ellipse(p1, b, a).minor
+        a
+
+        >>> m = Symbol('m')
+        >>> M = m + 1
+        >>> Ellipse(p1, m, M).minor
+        m
+
+        """
+        ab = self.args[1:3]
+        if len(ab) == 1:
+            return ab[0]
+        a, b = ab
+        o = a - b < 0
+        if o == True:
+            return a
+        elif o == False:
+            return b
+        return self.vradius
+
+    def normal_lines(self, p, prec=None):
+        """Normal lines between `p` and the ellipse.
+
+        Parameters
+        ==========
+
+        p : Point
+
+        Returns
+        =======
+
+        normal_lines : list with 1, 2 or 4 Lines
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse
+        >>> e = Ellipse((0, 0), 2, 3)
+        >>> c = e.center
+        >>> e.normal_lines(c + Point(1, 0))
+        [Line2D(Point2D(0, 0), Point2D(1, 0))]
+        >>> e.normal_lines(c)
+        [Line2D(Point2D(0, 0), Point2D(0, 1)), Line2D(Point2D(0, 0), Point2D(1, 0))]
+
+        Off-axis points require the solution of a quartic equation. This
+        often leads to very large expressions that may be of little practical
+        use. An approximate solution of `prec` digits can be obtained by
+        passing in the desired value:
+
+        >>> e.normal_lines((3, 3), prec=2)
+        [Line2D(Point2D(-0.81, -2.7), Point2D(0.19, -1.2)),
+        Line2D(Point2D(1.5, -2.0), Point2D(2.5, -2.7))]
+
+        Whereas the above solution has an operation count of 12, the exact
+        solution has an operation count of 2020.
+        """
+        p = Point(p, dim=2)
+
+        # XXX change True to something like self.angle == 0 if the arbitrarily
+        # rotated ellipse is introduced.
+        # https://github.com/sympy/sympy/issues/2815)
+        if True:
+            rv = []
+            if p.x == self.center.x:
+                rv.append(Line(self.center, slope=oo))
+            if p.y == self.center.y:
+                rv.append(Line(self.center, slope=0))
+            if rv:
+                # at these special orientations of p either 1 or 2 normals
+                # exist and we are done
+                return rv
+
+        # find the 4 normal points and construct lines through them with
+        # the corresponding slope
+        eq = self.equation(x, y)
+        dydx = idiff(eq, y, x)
+        norm = -1/dydx
+        slope = Line(p, (x, y)).slope
+        seq = slope - norm
+
+        # TODO: Replace solve with solveset, when this line is tested
+        yis = solve(seq, y)[0]
+        xeq = eq.subs(y, yis).as_numer_denom()[0].expand()
+        if len(xeq.free_symbols) == 1:
+            try:
+                # this is so much faster, it's worth a try
+                xsol = Poly(xeq, x).real_roots()
+            except (DomainError, PolynomialError, NotImplementedError):
+                # TODO: Replace solve with solveset, when these lines are tested
+                xsol = _nsort(solve(xeq, x), separated=True)[0]
+            points = [Point(i, solve(eq.subs(x, i), y)[0]) for i in xsol]
+        else:
+            raise NotImplementedError(
+                'intersections for the general ellipse are not supported')
+        slopes = [norm.subs(zip((x, y), pt.args)) for pt in points]
+        if prec is not None:
+            points = [pt.n(prec) for pt in points]
+            slopes = [i if _not_a_coeff(i) else i.n(prec) for i in slopes]
+        return [Line(pt, slope=s) for pt, s in zip(points, slopes)]
+
+    @property
+    def periapsis(self):
+        """The periapsis of the ellipse.
+
+        The shortest distance between the focus and the contour.
+
+        Returns
+        =======
+
+        periapsis : number
+
+        See Also
+        ========
+
+        apoapsis : Returns greatest distance between focus and contour
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse
+        >>> p1 = Point(0, 0)
+        >>> e1 = Ellipse(p1, 3, 1)
+        >>> e1.periapsis
+        3 - 2*sqrt(2)
+
+        """
+        return self.major * (1 - self.eccentricity)
+
+    @property
+    def semilatus_rectum(self):
+        """
+        Calculates the semi-latus rectum of the Ellipse.
+
+        Semi-latus rectum is defined as one half of the chord through a
+        focus parallel to the conic section directrix of a conic section.
+
+        Returns
+        =======
+
+        semilatus_rectum : number
+
+        See Also
+        ========
+
+        apoapsis : Returns greatest distance between focus and contour
+
+        periapsis : The shortest distance between the focus and the contour
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse
+        >>> p1 = Point(0, 0)
+        >>> e1 = Ellipse(p1, 3, 1)
+        >>> e1.semilatus_rectum
+        1/3
+
+        References
+        ==========
+
+        .. [1] https://mathworld.wolfram.com/SemilatusRectum.html
+        .. [2] https://en.wikipedia.org/wiki/Ellipse#Semi-latus_rectum
+
+        """
+        return self.major * (1 - self.eccentricity ** 2)
+
+    def auxiliary_circle(self):
+        """Returns a Circle whose diameter is the major axis of the ellipse.
+
+        Examples
+        ========
+
+        >>> from sympy import Ellipse, Point, symbols
+        >>> c = Point(1, 2)
+        >>> Ellipse(c, 8, 7).auxiliary_circle()
+        Circle(Point2D(1, 2), 8)
+        >>> a, b = symbols('a b')
+        >>> Ellipse(c, a, b).auxiliary_circle()
+        Circle(Point2D(1, 2), Max(a, b))
+        """
+        return Circle(self.center, Max(self.hradius, self.vradius))
+
+    def director_circle(self):
+        """
+        Returns a Circle consisting of all points where two perpendicular
+        tangent lines to the ellipse cross each other.
+
+        Returns
+        =======
+
+        Circle
+            A director circle returned as a geometric object.
+
+        Examples
+        ========
+
+        >>> from sympy import Ellipse, Point, symbols
+        >>> c = Point(3,8)
+        >>> Ellipse(c, 7, 9).director_circle()
+        Circle(Point2D(3, 8), sqrt(130))
+        >>> a, b = symbols('a b')
+        >>> Ellipse(c, a, b).director_circle()
+        Circle(Point2D(3, 8), sqrt(a**2 + b**2))
+
+        References
+        ==========
+
+        .. [1] https://en.wikipedia.org/wiki/Director_circle
+
+        """
+        return Circle(self.center, sqrt(self.hradius**2 + self.vradius**2))
+
+    def plot_interval(self, parameter='t'):
+        """The plot interval for the default geometric plot of the Ellipse.
+
+        Parameters
+        ==========
+
+        parameter : str, optional
+            Default value is 't'.
+
+        Returns
+        =======
+
+        plot_interval : list
+            [parameter, lower_bound, upper_bound]
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse
+        >>> e1 = Ellipse(Point(0, 0), 3, 2)
+        >>> e1.plot_interval()
+        [t, -pi, pi]
+
+        """
+        t = _symbol(parameter, real=True)
+        return [t, -S.Pi, S.Pi]
+
+    def random_point(self, seed=None):
+        """A random point on the ellipse.
+
+        Returns
+        =======
+
+        point : Point
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse
+        >>> e1 = Ellipse(Point(0, 0), 3, 2)
+        >>> e1.random_point() # gives some random point
+        Point2D(...)
+        >>> p1 = e1.random_point(seed=0); p1.n(2)
+        Point2D(2.1, 1.4)
+
+        Notes
+        =====
+
+        When creating a random point, one may simply replace the
+        parameter with a random number. When doing so, however, the
+        random number should be made a Rational or else the point
+        may not test as being in the ellipse:
+
+        >>> from sympy.abc import t
+        >>> from sympy import Rational
+        >>> arb = e1.arbitrary_point(t); arb
+        Point2D(3*cos(t), 2*sin(t))
+        >>> arb.subs(t, .1) in e1
+        False
+        >>> arb.subs(t, Rational(.1)) in e1
+        True
+        >>> arb.subs(t, Rational('.1')) in e1
+        True
+
+        See Also
+        ========
+        sympy.geometry.point.Point
+        arbitrary_point : Returns parameterized point on ellipse
+        """
+        t = _symbol('t', real=True)
+        x, y = self.arbitrary_point(t).args
+        # get a random value in [-1, 1) corresponding to cos(t)
+        # and confirm that it will test as being in the ellipse
+        if seed is not None:
+            rng = random.Random(seed)
+        else:
+            rng = random
+        # simplify this now or else the Float will turn s into a Float
+        r = Rational(rng.random())
+        c = 2*r - 1
+        s = sqrt(1 - c**2)
+        return Point(x.subs(cos(t), c), y.subs(sin(t), s))
+
+    def reflect(self, line):
+        """Override GeometryEntity.reflect since the radius
+        is not a GeometryEntity.
+
+        Examples
+        ========
+
+        >>> from sympy import Circle, Line
+        >>> Circle((0, 1), 1).reflect(Line((0, 0), (1, 1)))
+        Circle(Point2D(1, 0), -1)
+        >>> from sympy import Ellipse, Line, Point
+        >>> Ellipse(Point(3, 4), 1, 3).reflect(Line(Point(0, -4), Point(5, 0)))
+        Traceback (most recent call last):
+        ...
+        NotImplementedError:
+        General Ellipse is not supported but the equation of the reflected
+        Ellipse is given by the zeros of: f(x, y) = (9*x/41 + 40*y/41 +
+        37/41)**2 + (40*x/123 - 3*y/41 - 364/123)**2 - 1
+
+        Notes
+        =====
+
+        Until the general ellipse (with no axis parallel to the x-axis) is
+        supported a NotImplemented error is raised and the equation whose
+        zeros define the rotated ellipse is given.
+
+        """
+
+        if line.slope in (0, oo):
+            c = self.center
+            c = c.reflect(line)
+            return self.func(c, -self.hradius, self.vradius)
+        else:
+            x, y = [uniquely_named_symbol(
+                name, (self, line), modify=lambda s: '_' + s, real=True)
+                for name in 'xy']
+            expr = self.equation(x, y)
+            p = Point(x, y).reflect(line)
+            result = expr.subs(zip((x, y), p.args
+                                   ), simultaneous=True)
+            raise NotImplementedError(filldedent(
+                'General Ellipse is not supported but the equation '
+                'of the reflected Ellipse is given by the zeros of: ' +
+                "f(%s, %s) = %s" % (str(x), str(y), str(result))))
+
+    def rotate(self, angle=0, pt=None):
+        """Rotate ``angle`` radians counterclockwise about Point ``pt``.
+
+        Note: since the general ellipse is not supported, only rotations that
+        are integer multiples of pi/2 are allowed.
+
+        Examples
+        ========
+
+        >>> from sympy import Ellipse, pi
+        >>> Ellipse((1, 0), 2, 1).rotate(pi/2)
+        Ellipse(Point2D(0, 1), 1, 2)
+        >>> Ellipse((1, 0), 2, 1).rotate(pi)
+        Ellipse(Point2D(-1, 0), 2, 1)
+        """
+        if self.hradius == self.vradius:
+            return self.func(self.center.rotate(angle, pt), self.hradius)
+        if (angle/S.Pi).is_integer:
+            return super().rotate(angle, pt)
+        if (2*angle/S.Pi).is_integer:
+            return self.func(self.center.rotate(angle, pt), self.vradius, self.hradius)
+        # XXX see https://github.com/sympy/sympy/issues/2815 for general ellipes
+        raise NotImplementedError('Only rotations of pi/2 are currently supported for Ellipse.')
+
+    def scale(self, x=1, y=1, pt=None):
+        """Override GeometryEntity.scale since it is the major and minor
+        axes which must be scaled and they are not GeometryEntities.
+
+        Examples
+        ========
+
+        >>> from sympy import Ellipse
+        >>> Ellipse((0, 0), 2, 1).scale(2, 4)
+        Circle(Point2D(0, 0), 4)
+        >>> Ellipse((0, 0), 2, 1).scale(2)
+        Ellipse(Point2D(0, 0), 4, 1)
+        """
+        c = self.center
+        if pt:
+            pt = Point(pt, dim=2)
+            return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
+        h = self.hradius
+        v = self.vradius
+        return self.func(c.scale(x, y), hradius=h*x, vradius=v*y)
+
+    def tangent_lines(self, p):
+        """Tangent lines between `p` and the ellipse.
+
+        If `p` is on the ellipse, returns the tangent line through point `p`.
+        Otherwise, returns the tangent line(s) from `p` to the ellipse, or
+        None if no tangent line is possible (e.g., `p` inside ellipse).
+
+        Parameters
+        ==========
+
+        p : Point
+
+        Returns
+        =======
+
+        tangent_lines : list with 1 or 2 Lines
+
+        Raises
+        ======
+
+        NotImplementedError
+            Can only find tangent lines for a point, `p`, on the ellipse.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point, sympy.geometry.line.Line
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse
+        >>> e1 = Ellipse(Point(0, 0), 3, 2)
+        >>> e1.tangent_lines(Point(3, 0))
+        [Line2D(Point2D(3, 0), Point2D(3, -12))]
+
+        """
+        p = Point(p, dim=2)
+        if self.encloses_point(p):
+            return []
+
+        if p in self:
+            delta = self.center - p
+            rise = (self.vradius**2)*delta.x
+            run = -(self.hradius**2)*delta.y
+            p2 = Point(simplify(p.x + run),
+                       simplify(p.y + rise))
+            return [Line(p, p2)]
+        else:
+            if len(self.foci) == 2:
+                f1, f2 = self.foci
+                maj = self.hradius
+                test = (2*maj -
+                        Point.distance(f1, p) -
+                        Point.distance(f2, p))
+            else:
+                test = self.radius - Point.distance(self.center, p)
+            if test.is_number and test.is_positive:
+                return []
+            # else p is outside the ellipse or we can't tell. In case of the
+            # latter, the solutions returned will only be valid if
+            # the point is not inside the ellipse; if it is, nan will result.
+            eq = self.equation(x, y)
+            dydx = idiff(eq, y, x)
+            slope = Line(p, Point(x, y)).slope
+
+            # TODO: Replace solve with solveset, when this line is tested
+            tangent_points = solve([slope - dydx, eq], [x, y])
+
+            # handle horizontal and vertical tangent lines
+            if len(tangent_points) == 1:
+                if tangent_points[0][
+                           0] == p.x or tangent_points[0][1] == p.y:
+                    return [Line(p, p + Point(1, 0)), Line(p, p + Point(0, 1))]
+                else:
+                    return [Line(p, p + Point(0, 1)), Line(p, tangent_points[0])]
+
+            # others
+            return [Line(p, tangent_points[0]), Line(p, tangent_points[1])]
+
+    @property
+    def vradius(self):
+        """The vertical radius of the ellipse.
+
+        Returns
+        =======
+
+        vradius : number
+
+        See Also
+        ========
+
+        hradius, major, minor
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse
+        >>> p1 = Point(0, 0)
+        >>> e1 = Ellipse(p1, 3, 1)
+        >>> e1.vradius
+        1
+
+        """
+        return self.args[2]
+
+
+    def second_moment_of_area(self, point=None):
+        """Returns the second moment and product moment area of an ellipse.
+
+        Parameters
+        ==========
+
+        point : Point, two-tuple of sympifiable objects, or None(default=None)
+            point is the point about which second moment of area is to be found.
+            If "point=None" it will be calculated about the axis passing through the
+            centroid of the ellipse.
+
+        Returns
+        =======
+
+        I_xx, I_yy, I_xy : number or SymPy expression
+            I_xx, I_yy are second moment of area of an ellise.
+            I_xy is product moment of area of an ellipse.
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ellipse
+        >>> p1 = Point(0, 0)
+        >>> e1 = Ellipse(p1, 3, 1)
+        >>> e1.second_moment_of_area()
+        (3*pi/4, 27*pi/4, 0)
+
+        References
+        ==========
+
+        .. [1] https://en.wikipedia.org/wiki/List_of_second_moments_of_area
+
+        """
+
+        I_xx = (S.Pi*(self.hradius)*(self.vradius**3))/4
+        I_yy = (S.Pi*(self.hradius**3)*(self.vradius))/4
+        I_xy = 0
+
+        if point is None:
+            return I_xx, I_yy, I_xy
+
+        # parallel axis theorem
+        I_xx = I_xx + self.area*((point[1] - self.center.y)**2)
+        I_yy = I_yy + self.area*((point[0] - self.center.x)**2)
+        I_xy = I_xy + self.area*(point[0] - self.center.x)*(point[1] - self.center.y)
+
+        return I_xx, I_yy, I_xy
+
+
+    def polar_second_moment_of_area(self):
+        """Returns the polar second moment of area of an Ellipse
+
+        It is a constituent of the second moment of area, linked through
+        the perpendicular axis theorem. While the planar second moment of
+        area describes an object's resistance to deflection (bending) when
+        subjected to a force applied to a plane parallel to the central
+        axis, the polar second moment of area describes an object's
+        resistance to deflection when subjected to a moment applied in a
+        plane perpendicular to the object's central axis (i.e. parallel to
+        the cross-section)
+
+        Examples
+        ========
+
+        >>> from sympy import symbols, Circle, Ellipse
+        >>> c = Circle((5, 5), 4)
+        >>> c.polar_second_moment_of_area()
+        128*pi
+        >>> a, b = symbols('a, b')
+        >>> e = Ellipse((0, 0), a, b)
+        >>> e.polar_second_moment_of_area()
+        pi*a**3*b/4 + pi*a*b**3/4
+
+        References
+        ==========
+
+        .. [1] https://en.wikipedia.org/wiki/Polar_moment_of_inertia
+
+        """
+        second_moment = self.second_moment_of_area()
+        return second_moment[0] + second_moment[1]
+
+
+    def section_modulus(self, point=None):
+        """Returns a tuple with the section modulus of an ellipse
+
+        Section modulus is a geometric property of an ellipse defined as the
+        ratio of second moment of area to the distance of the extreme end of
+        the ellipse from the centroidal axis.
+
+        Parameters
+        ==========
+
+        point : Point, two-tuple of sympifyable objects, or None(default=None)
+            point is the point at which section modulus is to be found.
+            If "point=None" section modulus will be calculated for the
+            point farthest from the centroidal axis of the ellipse.
+
+        Returns
+        =======
+
+        S_x, S_y: numbers or SymPy expressions
+                  S_x is the section modulus with respect to the x-axis
+                  S_y is the section modulus with respect to the y-axis
+                  A negative sign indicates that the section modulus is
+                  determined for a point below the centroidal axis.
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol, Ellipse, Circle, Point2D
+        >>> d = Symbol('d', positive=True)
+        >>> c = Circle((0, 0), d/2)
+        >>> c.section_modulus()
+        (pi*d**3/32, pi*d**3/32)
+        >>> e = Ellipse(Point2D(0, 0), 2, 4)
+        >>> e.section_modulus()
+        (8*pi, 4*pi)
+        >>> e.section_modulus((2, 2))
+        (16*pi, 4*pi)
+
+        References
+        ==========
+
+        .. [1] https://en.wikipedia.org/wiki/Section_modulus
+
+        """
+        x_c, y_c = self.center
+        if point is None:
+            # taking x and y as maximum distances from centroid
+            x_min, y_min, x_max, y_max = self.bounds
+            y = max(y_c - y_min, y_max - y_c)
+            x = max(x_c - x_min, x_max - x_c)
+        else:
+            # taking x and y as distances of the given point from the center
+            point = Point2D(point)
+            y = point.y - y_c
+            x = point.x - x_c
+
+        second_moment = self.second_moment_of_area()
+        S_x = second_moment[0]/y
+        S_y = second_moment[1]/x
+
+        return S_x, S_y
+
+
+class Circle(Ellipse):
+    r"""A circle in space.
+
+    Constructed simply from a center and a radius, from three
+    non-collinear points, or the equation of a circle.
+
+    Parameters
+    ==========
+
+    center : Point
+    radius : number or SymPy expression
+    points : sequence of three Points
+    equation : equation of a circle
+
+    Attributes
+    ==========
+
+    radius (synonymous with hradius, vradius, major and minor)
+    circumference
+    equation
+
+    Raises
+    ======
+
+    GeometryError
+        When the given equation is not that of a circle.
+        When trying to construct circle from incorrect parameters.
+
+    See Also
+    ========
+
+    Ellipse, sympy.geometry.point.Point
+
+    Examples
+    ========
+
+    >>> from sympy import Point, Circle, Eq
+    >>> from sympy.abc import x, y, a, b
+
+    A circle constructed from a center and radius:
+
+    >>> c1 = Circle(Point(0, 0), 5)
+    >>> c1.hradius, c1.vradius, c1.radius
+    (5, 5, 5)
+
+    A circle constructed from three points:
+
+    >>> c2 = Circle(Point(0, 0), Point(1, 1), Point(1, 0))
+    >>> c2.hradius, c2.vradius, c2.radius, c2.center
+    (sqrt(2)/2, sqrt(2)/2, sqrt(2)/2, Point2D(1/2, 1/2))
+
+    A circle can be constructed from an equation in the form
+    `ax^2 + by^2 + gx + hy + c = 0`, too:
+
+    >>> Circle(x**2 + y**2 - 25)
+    Circle(Point2D(0, 0), 5)
+
+    If the variables corresponding to x and y are named something
+    else, their name or symbol can be supplied:
+
+    >>> Circle(Eq(a**2 + b**2, 25), x='a', y=b)
+    Circle(Point2D(0, 0), 5)
+    """
+
+    def __new__(cls, *args, **kwargs):
+        evaluate = kwargs.get('evaluate', global_parameters.evaluate)
+        if len(args) == 1 and isinstance(args[0], (Expr, Eq)):
+            x = kwargs.get('x', 'x')
+            y = kwargs.get('y', 'y')
+            equation = args[0].expand()
+            if isinstance(equation, Eq):
+                equation = equation.lhs - equation.rhs
+            x = find(x, equation)
+            y = find(y, equation)
+
+            try:
+                a, b, c, d, e = linear_coeffs(equation, x**2, y**2, x, y)
+            except ValueError:
+                raise GeometryError("The given equation is not that of a circle.")
+
+            if S.Zero in (a, b) or a != b:
+                raise GeometryError("The given equation is not that of a circle.")
+
+            center_x = -c/a/2
+            center_y = -d/b/2
+            r2 = (center_x**2) + (center_y**2) - e/a
+
+            return Circle((center_x, center_y), sqrt(r2), evaluate=evaluate)
+
+        else:
+            c, r = None, None
+            if len(args) == 3:
+                args = [Point(a, dim=2, evaluate=evaluate) for a in args]
+                t = Triangle(*args)
+                if not isinstance(t, Triangle):
+                    return t
+                c = t.circumcenter
+                r = t.circumradius
+            elif len(args) == 2:
+                # Assume (center, radius) pair
+                c = Point(args[0], dim=2, evaluate=evaluate)
+                r = args[1]
+                # this will prohibit imaginary radius
+                try:
+                    r = Point(r, 0, evaluate=evaluate).x
+                except ValueError:
+                    raise GeometryError("Circle with imaginary radius is not permitted")
+
+            if not (c is None or r is None):
+                if r == 0:
+                    return c
+                return GeometryEntity.__new__(cls, c, r, **kwargs)
+
+            raise GeometryError("Circle.__new__ received unknown arguments")
+
+    def _eval_evalf(self, prec=15, **options):
+        pt, r = self.args
+        dps = prec_to_dps(prec)
+        pt = pt.evalf(n=dps, **options)
+        r = r.evalf(n=dps, **options)
+        return self.func(pt, r, evaluate=False)
+
+    @property
+    def circumference(self):
+        """The circumference of the circle.
+
+        Returns
+        =======
+
+        circumference : number or SymPy expression
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Circle
+        >>> c1 = Circle(Point(3, 4), 6)
+        >>> c1.circumference
+        12*pi
+
+        """
+        return 2 * S.Pi * self.radius
+
+    def equation(self, x='x', y='y'):
+        """The equation of the circle.
+
+        Parameters
+        ==========
+
+        x : str or Symbol, optional
+            Default value is 'x'.
+        y : str or Symbol, optional
+            Default value is 'y'.
+
+        Returns
+        =======
+
+        equation : SymPy expression
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Circle
+        >>> c1 = Circle(Point(0, 0), 5)
+        >>> c1.equation()
+        x**2 + y**2 - 25
+
+        """
+        x = _symbol(x, real=True)
+        y = _symbol(y, real=True)
+        t1 = (x - self.center.x)**2
+        t2 = (y - self.center.y)**2
+        return t1 + t2 - self.major**2
+
+    def intersection(self, o):
+        """The intersection of this circle with another geometrical entity.
+
+        Parameters
+        ==========
+
+        o : GeometryEntity
+
+        Returns
+        =======
+
+        intersection : list of GeometryEntities
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Circle, Line, Ray
+        >>> p1, p2, p3 = Point(0, 0), Point(5, 5), Point(6, 0)
+        >>> p4 = Point(5, 0)
+        >>> c1 = Circle(p1, 5)
+        >>> c1.intersection(p2)
+        []
+        >>> c1.intersection(p4)
+        [Point2D(5, 0)]
+        >>> c1.intersection(Ray(p1, p2))
+        [Point2D(5*sqrt(2)/2, 5*sqrt(2)/2)]
+        >>> c1.intersection(Line(p2, p3))
+        []
+
+        """
+        return Ellipse.intersection(self, o)
+
+    @property
+    def radius(self):
+        """The radius of the circle.
+
+        Returns
+        =======
+
+        radius : number or SymPy expression
+
+        See Also
+        ========
+
+        Ellipse.major, Ellipse.minor, Ellipse.hradius, Ellipse.vradius
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Circle
+        >>> c1 = Circle(Point(3, 4), 6)
+        >>> c1.radius
+        6
+
+        """
+        return self.args[1]
+
+    def reflect(self, line):
+        """Override GeometryEntity.reflect since the radius
+        is not a GeometryEntity.
+
+        Examples
+        ========
+
+        >>> from sympy import Circle, Line
+        >>> Circle((0, 1), 1).reflect(Line((0, 0), (1, 1)))
+        Circle(Point2D(1, 0), -1)
+        """
+        c = self.center
+        c = c.reflect(line)
+        return self.func(c, -self.radius)
+
+    def scale(self, x=1, y=1, pt=None):
+        """Override GeometryEntity.scale since the radius
+        is not a GeometryEntity.
+
+        Examples
+        ========
+
+        >>> from sympy import Circle
+        >>> Circle((0, 0), 1).scale(2, 2)
+        Circle(Point2D(0, 0), 2)
+        >>> Circle((0, 0), 1).scale(2, 4)
+        Ellipse(Point2D(0, 0), 2, 4)
+        """
+        c = self.center
+        if pt:
+            pt = Point(pt, dim=2)
+            return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
+        c = c.scale(x, y)
+        x, y = [abs(i) for i in (x, y)]
+        if x == y:
+            return self.func(c, x*self.radius)
+        h = v = self.radius
+        return Ellipse(c, hradius=h*x, vradius=v*y)
+
+    @property
+    def vradius(self):
+        """
+        This Ellipse property is an alias for the Circle's radius.
+
+        Whereas hradius, major and minor can use Ellipse's conventions,
+        the vradius does not exist for a circle. It is always a positive
+        value in order that the Circle, like Polygons, will have an
+        area that can be positive or negative as determined by the sign
+        of the hradius.
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Circle
+        >>> c1 = Circle(Point(3, 4), 6)
+        >>> c1.vradius
+        6
+        """
+        return abs(self.radius)
+
+
+from .polygon import Polygon, Triangle
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/entity.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/entity.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ea1e807542c43eb955c2d778cec0f101d78bdce
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/entity.py
@@ -0,0 +1,641 @@
+"""The definition of the base geometrical entity with attributes common to
+all derived geometrical entities.
+
+Contains
+========
+
+GeometryEntity
+GeometricSet
+
+Notes
+=====
+
+A GeometryEntity is any object that has special geometric properties.
+A GeometrySet is a superclass of any GeometryEntity that can also
+be viewed as a sympy.sets.Set.  In particular, points are the only
+GeometryEntity not considered a Set.
+
+Rn is a GeometrySet representing n-dimensional Euclidean space. R2 and
+R3 are currently the only ambient spaces implemented.
+
+"""
+from __future__ import annotations
+
+from sympy.core.basic import Basic
+from sympy.core.containers import Tuple
+from sympy.core.evalf import EvalfMixin, N
+from sympy.core.numbers import oo
+from sympy.core.symbol import Dummy
+from sympy.core.sympify import sympify
+from sympy.functions.elementary.trigonometric import cos, sin, atan
+from sympy.matrices import eye
+from sympy.multipledispatch import dispatch
+from sympy.printing import sstr
+from sympy.sets import Set, Union, FiniteSet
+from sympy.sets.handlers.intersection import intersection_sets
+from sympy.sets.handlers.union import union_sets
+from sympy.solvers.solvers import solve
+from sympy.utilities.misc import func_name
+from sympy.utilities.iterables import is_sequence
+
+
+# How entities are ordered; used by __cmp__ in GeometryEntity
+ordering_of_classes = [
+    "Point2D",
+    "Point3D",
+    "Point",
+    "Segment2D",
+    "Ray2D",
+    "Line2D",
+    "Segment3D",
+    "Line3D",
+    "Ray3D",
+    "Segment",
+    "Ray",
+    "Line",
+    "Plane",
+    "Triangle",
+    "RegularPolygon",
+    "Polygon",
+    "Circle",
+    "Ellipse",
+    "Curve",
+    "Parabola"
+]
+
+
+x, y = [Dummy('entity_dummy') for i in range(2)]
+T = Dummy('entity_dummy', real=True)
+
+
+class GeometryEntity(Basic, EvalfMixin):
+    """The base class for all geometrical entities.
+
+    This class does not represent any particular geometric entity, it only
+    provides the implementation of some methods common to all subclasses.
+
+    """
+
+    __slots__: tuple[str, ...] = ()
+
+    def __cmp__(self, other):
+        """Comparison of two GeometryEntities."""
+        n1 = self.__class__.__name__
+        n2 = other.__class__.__name__
+        c = (n1 > n2) - (n1 < n2)
+        if not c:
+            return 0
+
+        i1 = -1
+        for cls in self.__class__.__mro__:
+            try:
+                i1 = ordering_of_classes.index(cls.__name__)
+                break
+            except ValueError:
+                i1 = -1
+        if i1 == -1:
+            return c
+
+        i2 = -1
+        for cls in other.__class__.__mro__:
+            try:
+                i2 = ordering_of_classes.index(cls.__name__)
+                break
+            except ValueError:
+                i2 = -1
+        if i2 == -1:
+            return c
+
+        return (i1 > i2) - (i1 < i2)
+
+    def __contains__(self, other):
+        """Subclasses should implement this method for anything more complex than equality."""
+        if type(self) is type(other):
+            return self == other
+        raise NotImplementedError()
+
+    def __getnewargs__(self):
+        """Returns a tuple that will be passed to __new__ on unpickling."""
+        return tuple(self.args)
+
+    def __ne__(self, o):
+        """Test inequality of two geometrical entities."""
+        return not self == o
+
+    def __new__(cls, *args, **kwargs):
+        # Points are sequences, but they should not
+        # be converted to Tuples, so use this detection function instead.
+        def is_seq_and_not_point(a):
+            # we cannot use isinstance(a, Point) since we cannot import Point
+            if hasattr(a, 'is_Point') and a.is_Point:
+                return False
+            return is_sequence(a)
+
+        args = [Tuple(*a) if is_seq_and_not_point(a) else sympify(a) for a in args]
+        return Basic.__new__(cls, *args)
+
+    def __radd__(self, a):
+        """Implementation of reverse add method."""
+        return a.__add__(self)
+
+    def __rtruediv__(self, a):
+        """Implementation of reverse division method."""
+        return a.__truediv__(self)
+
+    def __repr__(self):
+        """String representation of a GeometryEntity that can be evaluated
+        by sympy."""
+        return type(self).__name__ + repr(self.args)
+
+    def __rmul__(self, a):
+        """Implementation of reverse multiplication method."""
+        return a.__mul__(self)
+
+    def __rsub__(self, a):
+        """Implementation of reverse subtraction method."""
+        return a.__sub__(self)
+
+    def __str__(self):
+        """String representation of a GeometryEntity."""
+        return type(self).__name__ + sstr(self.args)
+
+    def _eval_subs(self, old, new):
+        from sympy.geometry.point import Point, Point3D
+        if is_sequence(old) or is_sequence(new):
+            if isinstance(self, Point3D):
+                old = Point3D(old)
+                new = Point3D(new)
+            else:
+                old = Point(old)
+                new = Point(new)
+            return  self._subs(old, new)
+
+    def _repr_svg_(self):
+        """SVG representation of a GeometryEntity suitable for IPython"""
+
+        try:
+            bounds = self.bounds
+        except (NotImplementedError, TypeError):
+            # if we have no SVG representation, return None so IPython
+            # will fall back to the next representation
+            return None
+
+        if not all(x.is_number and x.is_finite for x in bounds):
+            return None
+
+        svg_top = '''
+            
+                
+                    
+                
+                
+                    
+                
+                
+                    
+                
+            '''
+
+        # Establish SVG canvas that will fit all the data + small space
+        xmin, ymin, xmax, ymax = map(N, bounds)
+        if xmin == xmax and ymin == ymax:
+            # This is a point; buffer using an arbitrary size
+            xmin, ymin, xmax, ymax = xmin - .5, ymin -.5, xmax + .5, ymax + .5
+        else:
+            # Expand bounds by a fraction of the data ranges
+            expand = 0.1  # or 10%; this keeps arrowheads in view (R plots use 4%)
+            widest_part = max([xmax - xmin, ymax - ymin])
+            expand_amount = widest_part * expand
+            xmin -= expand_amount
+            ymin -= expand_amount
+            xmax += expand_amount
+            ymax += expand_amount
+        dx = xmax - xmin
+        dy = ymax - ymin
+        width = min([max([100., dx]), 300])
+        height = min([max([100., dy]), 300])
+
+        scale_factor = 1. if max(width, height) == 0 else max(dx, dy) / max(width, height)
+        try:
+            svg = self._svg(scale_factor)
+        except (NotImplementedError, TypeError):
+            # if we have no SVG representation, return None so IPython
+            # will fall back to the next representation
+            return None
+
+        view_box = "{} {} {} {}".format(xmin, ymin, dx, dy)
+        transform = "matrix(1,0,0,-1,0,{})".format(ymax + ymin)
+        svg_top = svg_top.format(view_box, width, height)
+
+        return svg_top + (
+            '{}'
+            ).format(transform, svg)
+
+    def _svg(self, scale_factor=1., fill_color="#66cc99"):
+        """Returns SVG path element for the GeometryEntity.
+
+        Parameters
+        ==========
+
+        scale_factor : float
+            Multiplication factor for the SVG stroke-width.  Default is 1.
+        fill_color : str, optional
+            Hex string for fill color. Default is "#66cc99".
+        """
+        raise NotImplementedError()
+
+    def _sympy_(self):
+        return self
+
+    @property
+    def ambient_dimension(self):
+        """What is the dimension of the space that the object is contained in?"""
+        raise NotImplementedError()
+
+    @property
+    def bounds(self):
+        """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding
+        rectangle for the geometric figure.
+
+        """
+
+        raise NotImplementedError()
+
+    def encloses(self, o):
+        """
+        Return True if o is inside (not on or outside) the boundaries of self.
+
+        The object will be decomposed into Points and individual Entities need
+        only define an encloses_point method for their class.
+
+        See Also
+        ========
+
+        sympy.geometry.ellipse.Ellipse.encloses_point
+        sympy.geometry.polygon.Polygon.encloses_point
+
+        Examples
+        ========
+
+        >>> from sympy import RegularPolygon, Point, Polygon
+        >>> t  = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
+        >>> t2 = Polygon(*RegularPolygon(Point(0, 0), 2, 3).vertices)
+        >>> t2.encloses(t)
+        True
+        >>> t.encloses(t2)
+        False
+
+        """
+
+        from sympy.geometry.point import Point
+        from sympy.geometry.line import Segment, Ray, Line
+        from sympy.geometry.ellipse import Ellipse
+        from sympy.geometry.polygon import Polygon, RegularPolygon
+
+        if isinstance(o, Point):
+            return self.encloses_point(o)
+        elif isinstance(o, Segment):
+            return all(self.encloses_point(x) for x in o.points)
+        elif isinstance(o, (Ray, Line)):
+            return False
+        elif isinstance(o, Ellipse):
+            return self.encloses_point(o.center) and \
+                self.encloses_point(
+                Point(o.center.x + o.hradius, o.center.y)) and \
+                not self.intersection(o)
+        elif isinstance(o, Polygon):
+            if isinstance(o, RegularPolygon):
+                if not self.encloses_point(o.center):
+                    return False
+            return all(self.encloses_point(v) for v in o.vertices)
+        raise NotImplementedError()
+
+    def equals(self, o):
+        return self == o
+
+    def intersection(self, o):
+        """
+        Returns a list of all of the intersections of self with o.
+
+        Notes
+        =====
+
+        An entity is not required to implement this method.
+
+        If two different types of entities can intersect, the item with
+        higher index in ordering_of_classes should implement
+        intersections with anything having a lower index.
+
+        See Also
+        ========
+
+        sympy.geometry.util.intersection
+
+        """
+        raise NotImplementedError()
+
+    def is_similar(self, other):
+        """Is this geometrical entity similar to another geometrical entity?
+
+        Two entities are similar if a uniform scaling (enlarging or
+        shrinking) of one of the entities will allow one to obtain the other.
+
+        Notes
+        =====
+
+        This method is not intended to be used directly but rather
+        through the `are_similar` function found in util.py.
+        An entity is not required to implement this method.
+        If two different types of entities can be similar, it is only
+        required that one of them be able to determine this.
+
+        See Also
+        ========
+
+        scale
+
+        """
+        raise NotImplementedError()
+
+    def reflect(self, line):
+        """
+        Reflects an object across a line.
+
+        Parameters
+        ==========
+
+        line: Line
+
+        Examples
+        ========
+
+        >>> from sympy import pi, sqrt, Line, RegularPolygon
+        >>> l = Line((0, pi), slope=sqrt(2))
+        >>> pent = RegularPolygon((1, 2), 1, 5)
+        >>> rpent = pent.reflect(l)
+        >>> rpent
+        RegularPolygon(Point2D(-2*sqrt(2)*pi/3 - 1/3 + 4*sqrt(2)/3, 2/3 + 2*sqrt(2)/3 + 2*pi/3), -1, 5, -atan(2*sqrt(2)) + 3*pi/5)
+
+        >>> from sympy import pi, Line, Circle, Point
+        >>> l = Line((0, pi), slope=1)
+        >>> circ = Circle(Point(0, 0), 5)
+        >>> rcirc = circ.reflect(l)
+        >>> rcirc
+        Circle(Point2D(-pi, pi), -5)
+
+        """
+        from sympy.geometry.point import Point
+
+        g = self
+        l = line
+        o = Point(0, 0)
+        if l.slope.is_zero:
+            v = l.args[0].y
+            if not v:  # x-axis
+                return g.scale(y=-1)
+            reps = [(p, p.translate(y=2*(v - p.y))) for p in g.atoms(Point)]
+        elif l.slope is oo:
+            v = l.args[0].x
+            if not v:  # y-axis
+                return g.scale(x=-1)
+            reps = [(p, p.translate(x=2*(v - p.x))) for p in g.atoms(Point)]
+        else:
+            if not hasattr(g, 'reflect') and not all(
+                    isinstance(arg, Point) for arg in g.args):
+                raise NotImplementedError(
+                    'reflect undefined or non-Point args in %s' % g)
+            a = atan(l.slope)
+            c = l.coefficients
+            d = -c[-1]/c[1]  # y-intercept
+            # apply the transform to a single point
+            xf = Point(x, y)
+            xf = xf.translate(y=-d).rotate(-a, o).scale(y=-1
+                ).rotate(a, o).translate(y=d)
+            # replace every point using that transform
+            reps = [(p, xf.xreplace({x: p.x, y: p.y})) for p in g.atoms(Point)]
+        return g.xreplace(dict(reps))
+
+    def rotate(self, angle, pt=None):
+        """Rotate ``angle`` radians counterclockwise about Point ``pt``.
+
+        The default pt is the origin, Point(0, 0)
+
+        See Also
+        ========
+
+        scale, translate
+
+        Examples
+        ========
+
+        >>> from sympy import Point, RegularPolygon, Polygon, pi
+        >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
+        >>> t # vertex on x axis
+        Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2))
+        >>> t.rotate(pi/2) # vertex on y axis now
+        Triangle(Point2D(0, 1), Point2D(-sqrt(3)/2, -1/2), Point2D(sqrt(3)/2, -1/2))
+
+        """
+        newargs = []
+        for a in self.args:
+            if isinstance(a, GeometryEntity):
+                newargs.append(a.rotate(angle, pt))
+            else:
+                newargs.append(a)
+        return type(self)(*newargs)
+
+    def scale(self, x=1, y=1, pt=None):
+        """Scale the object by multiplying the x,y-coordinates by x and y.
+
+        If pt is given, the scaling is done relative to that point; the
+        object is shifted by -pt, scaled, and shifted by pt.
+
+        See Also
+        ========
+
+        rotate, translate
+
+        Examples
+        ========
+
+        >>> from sympy import RegularPolygon, Point, Polygon
+        >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
+        >>> t
+        Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2))
+        >>> t.scale(2)
+        Triangle(Point2D(2, 0), Point2D(-1, sqrt(3)/2), Point2D(-1, -sqrt(3)/2))
+        >>> t.scale(2, 2)
+        Triangle(Point2D(2, 0), Point2D(-1, sqrt(3)), Point2D(-1, -sqrt(3)))
+
+        """
+        from sympy.geometry.point import Point
+        if pt:
+            pt = Point(pt, dim=2)
+            return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
+        return type(self)(*[a.scale(x, y) for a in self.args])  # if this fails, override this class
+
+    def translate(self, x=0, y=0):
+        """Shift the object by adding to the x,y-coordinates the values x and y.
+
+        See Also
+        ========
+
+        rotate, scale
+
+        Examples
+        ========
+
+        >>> from sympy import RegularPolygon, Point, Polygon
+        >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
+        >>> t
+        Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2))
+        >>> t.translate(2)
+        Triangle(Point2D(3, 0), Point2D(3/2, sqrt(3)/2), Point2D(3/2, -sqrt(3)/2))
+        >>> t.translate(2, 2)
+        Triangle(Point2D(3, 2), Point2D(3/2, sqrt(3)/2 + 2), Point2D(3/2, 2 - sqrt(3)/2))
+
+        """
+        newargs = []
+        for a in self.args:
+            if isinstance(a, GeometryEntity):
+                newargs.append(a.translate(x, y))
+            else:
+                newargs.append(a)
+        return self.func(*newargs)
+
+    def parameter_value(self, other, t):
+        """Return the parameter corresponding to the given point.
+        Evaluating an arbitrary point of the entity at this parameter
+        value will return the given point.
+
+        Examples
+        ========
+
+        >>> from sympy import Line, Point
+        >>> from sympy.abc import t
+        >>> a = Point(0, 0)
+        >>> b = Point(2, 2)
+        >>> Line(a, b).parameter_value((1, 1), t)
+        {t: 1/2}
+        >>> Line(a, b).arbitrary_point(t).subs(_)
+        Point2D(1, 1)
+        """
+        from sympy.geometry.point import Point
+        if not isinstance(other, GeometryEntity):
+            other = Point(other, dim=self.ambient_dimension)
+        if not isinstance(other, Point):
+            raise ValueError("other must be a point")
+        sol = solve(self.arbitrary_point(T) - other, T, dict=True)
+        if not sol:
+            raise ValueError("Given point is not on %s" % func_name(self))
+        return {t: sol[0][T]}
+
+
+class GeometrySet(GeometryEntity, Set):
+    """Parent class of all GeometryEntity that are also Sets
+    (compatible with sympy.sets)
+    """
+    __slots__ = ()
+
+    def _contains(self, other):
+        """sympy.sets uses the _contains method, so include it for compatibility."""
+
+        if isinstance(other, Set) and other.is_FiniteSet:
+            return all(self.__contains__(i) for i in other)
+
+        return self.__contains__(other)
+
+@dispatch(GeometrySet, Set)  # type:ignore # noqa:F811
+def union_sets(self, o): # noqa:F811
+    """ Returns the union of self and o
+    for use with sympy.sets.Set, if possible. """
+
+
+    # if its a FiniteSet, merge any points
+    # we contain and return a union with the rest
+    if o.is_FiniteSet:
+        other_points = [p for p in o if not self._contains(p)]
+        if len(other_points) == len(o):
+            return None
+        return Union(self, FiniteSet(*other_points))
+    if self._contains(o):
+        return self
+    return None
+
+
+@dispatch(GeometrySet, Set)  # type: ignore # noqa:F811
+def intersection_sets(self, o): # noqa:F811
+    """ Returns a sympy.sets.Set of intersection objects,
+    if possible. """
+
+    from sympy.geometry.point import Point
+
+    try:
+        # if o is a FiniteSet, find the intersection directly
+        # to avoid infinite recursion
+        if o.is_FiniteSet:
+            inter = FiniteSet(*(p for p in o if self.contains(p)))
+        else:
+            inter = self.intersection(o)
+    except NotImplementedError:
+        # sympy.sets.Set.reduce expects None if an object
+        # doesn't know how to simplify
+        return None
+
+    # put the points in a FiniteSet
+    points = FiniteSet(*[p for p in inter if isinstance(p, Point)])
+    non_points = [p for p in inter if not isinstance(p, Point)]
+
+    return Union(*(non_points + [points]))
+
+def translate(x, y):
+    """Return the matrix to translate a 2-D point by x and y."""
+    rv = eye(3)
+    rv[2, 0] = x
+    rv[2, 1] = y
+    return rv
+
+
+def scale(x, y, pt=None):
+    """Return the matrix to multiply a 2-D point's coordinates by x and y.
+
+    If pt is given, the scaling is done relative to that point."""
+    rv = eye(3)
+    rv[0, 0] = x
+    rv[1, 1] = y
+    if pt:
+        from sympy.geometry.point import Point
+        pt = Point(pt, dim=2)
+        tr1 = translate(*(-pt).args)
+        tr2 = translate(*pt.args)
+        return tr1*rv*tr2
+    return rv
+
+
+def rotate(th):
+    """Return the matrix to rotate a 2-D point about the origin by ``angle``.
+
+    The angle is measured in radians. To Point a point about a point other
+    then the origin, translate the Point, do the rotation, and
+    translate it back:
+
+    >>> from sympy.geometry.entity import rotate, translate
+    >>> from sympy import Point, pi
+    >>> rot_about_11 = translate(-1, -1)*rotate(pi/2)*translate(1, 1)
+    >>> Point(1, 1).transform(rot_about_11)
+    Point2D(1, 1)
+    >>> Point(0, 0).transform(rot_about_11)
+    Point2D(2, 0)
+    """
+    s = sin(th)
+    rv = eye(3)*cos(th)
+    rv[0, 1] = s
+    rv[1, 0] = -s
+    rv[2, 2] = 1
+    return rv
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/exceptions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..41d97af718de2cebad3accefcd60e43ccf74a3f6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/exceptions.py
@@ -0,0 +1,5 @@
+"""Geometry Errors."""
+
+class GeometryError(ValueError):
+    """An exception raised by classes in the geometry module."""
+    pass
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/line.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/line.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed73d43d0c9581f9d51f299cf4425acb11958e57
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/line.py
@@ -0,0 +1,2877 @@
+"""Line-like geometrical entities.
+
+Contains
+========
+LinearEntity
+Line
+Ray
+Segment
+LinearEntity2D
+Line2D
+Ray2D
+Segment2D
+LinearEntity3D
+Line3D
+Ray3D
+Segment3D
+
+"""
+
+from sympy.core.containers import Tuple
+from sympy.core.evalf import N
+from sympy.core.expr import Expr
+from sympy.core.numbers import Rational, oo, Float
+from sympy.core.relational import Eq
+from sympy.core.singleton import S
+from sympy.core.sorting import ordered
+from sympy.core.symbol import _symbol, Dummy, uniquely_named_symbol
+from sympy.core.sympify import sympify
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.functions.elementary.trigonometric import (_pi_coeff, acos, tan, atan2)
+from .entity import GeometryEntity, GeometrySet
+from .exceptions import GeometryError
+from .point import Point, Point3D
+from .util import find, intersection
+from sympy.logic.boolalg import And
+from sympy.matrices import Matrix
+from sympy.sets.sets import Intersection
+from sympy.simplify.simplify import simplify
+from sympy.solvers.solvers import solve
+from sympy.solvers.solveset import linear_coeffs
+from sympy.utilities.misc import Undecidable, filldedent
+
+
+import random
+
+
+t, u = [Dummy('line_dummy') for i in range(2)]
+
+
+class LinearEntity(GeometrySet):
+    """A base class for all linear entities (Line, Ray and Segment)
+    in n-dimensional Euclidean space.
+
+    Attributes
+    ==========
+
+    ambient_dimension
+    direction
+    length
+    p1
+    p2
+    points
+
+    Notes
+    =====
+
+    This is an abstract class and is not meant to be instantiated.
+
+    See Also
+    ========
+
+    sympy.geometry.entity.GeometryEntity
+
+    """
+    def __new__(cls, p1, p2=None, **kwargs):
+        p1, p2 = Point._normalize_dimension(p1, p2)
+        if p1 == p2:
+            # sometimes we return a single point if we are not given two unique
+            # points. This is done in the specific subclass
+            raise ValueError(
+                "%s.__new__ requires two unique Points." % cls.__name__)
+        if len(p1) != len(p2):
+            raise ValueError(
+                "%s.__new__ requires two Points of equal dimension." % cls.__name__)
+
+        return GeometryEntity.__new__(cls, p1, p2, **kwargs)
+
+    def __contains__(self, other):
+        """Return a definitive answer or else raise an error if it cannot
+        be determined that other is on the boundaries of self."""
+        result = self.contains(other)
+
+        if result is not None:
+            return result
+        else:
+            raise Undecidable(
+                "Cannot decide whether '%s' contains '%s'" % (self, other))
+
+    def _span_test(self, other):
+        """Test whether the point `other` lies in the positive span of `self`.
+        A point x is 'in front' of a point y if x.dot(y) >= 0.  Return
+        -1 if `other` is behind `self.p1`, 0 if `other` is `self.p1` and
+        and 1 if `other` is in front of `self.p1`."""
+        if self.p1 == other:
+            return 0
+
+        rel_pos = other - self.p1
+        d = self.direction
+        if d.dot(rel_pos) > 0:
+            return 1
+        return -1
+
+    @property
+    def ambient_dimension(self):
+        """A property method that returns the dimension of LinearEntity
+        object.
+
+        Parameters
+        ==========
+
+        p1 : LinearEntity
+
+        Returns
+        =======
+
+        dimension : integer
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line
+        >>> p1, p2 = Point(0, 0), Point(1, 1)
+        >>> l1 = Line(p1, p2)
+        >>> l1.ambient_dimension
+        2
+
+        >>> from sympy import Point, Line
+        >>> p1, p2 = Point(0, 0, 0), Point(1, 1, 1)
+        >>> l1 = Line(p1, p2)
+        >>> l1.ambient_dimension
+        3
+
+        """
+        return len(self.p1)
+
+    def angle_between(l1, l2):
+        """Return the non-reflex angle formed by rays emanating from
+        the origin with directions the same as the direction vectors
+        of the linear entities.
+
+        Parameters
+        ==========
+
+        l1 : LinearEntity
+        l2 : LinearEntity
+
+        Returns
+        =======
+
+        angle : angle in radians
+
+        Notes
+        =====
+
+        From the dot product of vectors v1 and v2 it is known that:
+
+            ``dot(v1, v2) = |v1|*|v2|*cos(A)``
+
+        where A is the angle formed between the two vectors. We can
+        get the directional vectors of the two lines and readily
+        find the angle between the two using the above formula.
+
+        See Also
+        ========
+
+        is_perpendicular, Ray2D.closing_angle
+
+        Examples
+        ========
+
+        >>> from sympy import Line
+        >>> e = Line((0, 0), (1, 0))
+        >>> ne = Line((0, 0), (1, 1))
+        >>> sw = Line((1, 1), (0, 0))
+        >>> ne.angle_between(e)
+        pi/4
+        >>> sw.angle_between(e)
+        3*pi/4
+
+        To obtain the non-obtuse angle at the intersection of lines, use
+        the ``smallest_angle_between`` method:
+
+        >>> sw.smallest_angle_between(e)
+        pi/4
+
+        >>> from sympy import Point3D, Line3D
+        >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(-1, 2, 0)
+        >>> l1, l2 = Line3D(p1, p2), Line3D(p2, p3)
+        >>> l1.angle_between(l2)
+        acos(-sqrt(2)/3)
+        >>> l1.smallest_angle_between(l2)
+        acos(sqrt(2)/3)
+        """
+        if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity):
+            raise TypeError('Must pass only LinearEntity objects')
+
+        v1, v2 = l1.direction, l2.direction
+        return acos(v1.dot(v2)/(abs(v1)*abs(v2)))
+
+    def smallest_angle_between(l1, l2):
+        """Return the smallest angle formed at the intersection of the
+        lines containing the linear entities.
+
+        Parameters
+        ==========
+
+        l1 : LinearEntity
+        l2 : LinearEntity
+
+        Returns
+        =======
+
+        angle : angle in radians
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line
+        >>> p1, p2, p3 = Point(0, 0), Point(0, 4), Point(2, -2)
+        >>> l1, l2 = Line(p1, p2), Line(p1, p3)
+        >>> l1.smallest_angle_between(l2)
+        pi/4
+
+        See Also
+        ========
+
+        angle_between, is_perpendicular, Ray2D.closing_angle
+        """
+        if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity):
+            raise TypeError('Must pass only LinearEntity objects')
+
+        v1, v2 = l1.direction, l2.direction
+        return acos(abs(v1.dot(v2))/(abs(v1)*abs(v2)))
+
+    def arbitrary_point(self, parameter='t'):
+        """A parameterized point on the Line.
+
+        Parameters
+        ==========
+
+        parameter : str, optional
+            The name of the parameter which will be used for the parametric
+            point. The default value is 't'. When this parameter is 0, the
+            first point used to define the line will be returned, and when
+            it is 1 the second point will be returned.
+
+        Returns
+        =======
+
+        point : Point
+
+        Raises
+        ======
+
+        ValueError
+            When ``parameter`` already appears in the Line's definition.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line
+        >>> p1, p2 = Point(1, 0), Point(5, 3)
+        >>> l1 = Line(p1, p2)
+        >>> l1.arbitrary_point()
+        Point2D(4*t + 1, 3*t)
+        >>> from sympy import Point3D, Line3D
+        >>> p1, p2 = Point3D(1, 0, 0), Point3D(5, 3, 1)
+        >>> l1 = Line3D(p1, p2)
+        >>> l1.arbitrary_point()
+        Point3D(4*t + 1, 3*t, t)
+
+        """
+        t = _symbol(parameter, real=True)
+        if t.name in (f.name for f in self.free_symbols):
+            raise ValueError(filldedent('''
+                Symbol %s already appears in object
+                and cannot be used as a parameter.
+                ''' % t.name))
+        # multiply on the right so the variable gets
+        # combined with the coordinates of the point
+        return self.p1 + (self.p2 - self.p1)*t
+
+    @staticmethod
+    def are_concurrent(*lines):
+        """Is a sequence of linear entities concurrent?
+
+        Two or more linear entities are concurrent if they all
+        intersect at a single point.
+
+        Parameters
+        ==========
+
+        lines
+            A sequence of linear entities.
+
+        Returns
+        =======
+
+        True : if the set of linear entities intersect in one point
+        False : otherwise.
+
+        See Also
+        ========
+
+        sympy.geometry.util.intersection
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line
+        >>> p1, p2 = Point(0, 0), Point(3, 5)
+        >>> p3, p4 = Point(-2, -2), Point(0, 2)
+        >>> l1, l2, l3 = Line(p1, p2), Line(p1, p3), Line(p1, p4)
+        >>> Line.are_concurrent(l1, l2, l3)
+        True
+        >>> l4 = Line(p2, p3)
+        >>> Line.are_concurrent(l2, l3, l4)
+        False
+        >>> from sympy import Point3D, Line3D
+        >>> p1, p2 = Point3D(0, 0, 0), Point3D(3, 5, 2)
+        >>> p3, p4 = Point3D(-2, -2, -2), Point3D(0, 2, 1)
+        >>> l1, l2, l3 = Line3D(p1, p2), Line3D(p1, p3), Line3D(p1, p4)
+        >>> Line3D.are_concurrent(l1, l2, l3)
+        True
+        >>> l4 = Line3D(p2, p3)
+        >>> Line3D.are_concurrent(l2, l3, l4)
+        False
+
+        """
+        common_points = Intersection(*lines)
+        if common_points.is_FiniteSet and len(common_points) == 1:
+            return True
+        return False
+
+    def contains(self, other):
+        """Subclasses should implement this method and should return
+            True if other is on the boundaries of self;
+            False if not on the boundaries of self;
+            None if a determination cannot be made."""
+        raise NotImplementedError()
+
+    @property
+    def direction(self):
+        """The direction vector of the LinearEntity.
+
+        Returns
+        =======
+
+        p : a Point; the ray from the origin to this point is the
+            direction of `self`
+
+        Examples
+        ========
+
+        >>> from sympy import Line
+        >>> a, b = (1, 1), (1, 3)
+        >>> Line(a, b).direction
+        Point2D(0, 2)
+        >>> Line(b, a).direction
+        Point2D(0, -2)
+
+        This can be reported so the distance from the origin is 1:
+
+        >>> Line(b, a).direction.unit
+        Point2D(0, -1)
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point.unit
+
+        """
+        return self.p2 - self.p1
+
+    def intersection(self, other):
+        """The intersection with another geometrical entity.
+
+        Parameters
+        ==========
+
+        o : Point or LinearEntity
+
+        Returns
+        =======
+
+        intersection : list of geometrical entities
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line, Segment
+        >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(7, 7)
+        >>> l1 = Line(p1, p2)
+        >>> l1.intersection(p3)
+        [Point2D(7, 7)]
+        >>> p4, p5 = Point(5, 0), Point(0, 3)
+        >>> l2 = Line(p4, p5)
+        >>> l1.intersection(l2)
+        [Point2D(15/8, 15/8)]
+        >>> p6, p7 = Point(0, 5), Point(2, 6)
+        >>> s1 = Segment(p6, p7)
+        >>> l1.intersection(s1)
+        []
+        >>> from sympy import Point3D, Line3D, Segment3D
+        >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(7, 7, 7)
+        >>> l1 = Line3D(p1, p2)
+        >>> l1.intersection(p3)
+        [Point3D(7, 7, 7)]
+        >>> l1 = Line3D(Point3D(4,19,12), Point3D(5,25,17))
+        >>> l2 = Line3D(Point3D(-3, -15, -19), direction_ratio=[2,8,8])
+        >>> l1.intersection(l2)
+        [Point3D(1, 1, -3)]
+        >>> p6, p7 = Point3D(0, 5, 2), Point3D(2, 6, 3)
+        >>> s1 = Segment3D(p6, p7)
+        >>> l1.intersection(s1)
+        []
+
+        """
+        def intersect_parallel_rays(ray1, ray2):
+            if ray1.direction.dot(ray2.direction) > 0:
+                # rays point in the same direction
+                # so return the one that is "in front"
+                return [ray2] if ray1._span_test(ray2.p1) >= 0 else [ray1]
+            else:
+                # rays point in opposite directions
+                st = ray1._span_test(ray2.p1)
+                if st < 0:
+                    return []
+                elif st == 0:
+                    return [ray2.p1]
+                return [Segment(ray1.p1, ray2.p1)]
+
+        def intersect_parallel_ray_and_segment(ray, seg):
+            st1, st2 = ray._span_test(seg.p1), ray._span_test(seg.p2)
+            if st1 < 0 and st2 < 0:
+                return []
+            elif st1 >= 0 and st2 >= 0:
+                return [seg]
+            elif st1 >= 0:  # st2 < 0:
+                return [Segment(ray.p1, seg.p1)]
+            else:  # st1 < 0 and st2 >= 0:
+                return [Segment(ray.p1, seg.p2)]
+
+        def intersect_parallel_segments(seg1, seg2):
+            if seg1.contains(seg2):
+                return [seg2]
+            if seg2.contains(seg1):
+                return [seg1]
+
+            # direct the segments so they're oriented the same way
+            if seg1.direction.dot(seg2.direction) < 0:
+                seg2 = Segment(seg2.p2, seg2.p1)
+            # order the segments so seg1 is "behind" seg2
+            if seg1._span_test(seg2.p1) < 0:
+                seg1, seg2 = seg2, seg1
+            if seg2._span_test(seg1.p2) < 0:
+                return []
+            return [Segment(seg2.p1, seg1.p2)]
+
+        if not isinstance(other, GeometryEntity):
+            other = Point(other, dim=self.ambient_dimension)
+        if other.is_Point:
+            if self.contains(other):
+                return [other]
+            else:
+                return []
+        elif isinstance(other, LinearEntity):
+            # break into cases based on whether
+            # the lines are parallel, non-parallel intersecting, or skew
+            pts = Point._normalize_dimension(self.p1, self.p2, other.p1, other.p2)
+            rank = Point.affine_rank(*pts)
+
+            if rank == 1:
+                # we're collinear
+                if isinstance(self, Line):
+                    return [other]
+                if isinstance(other, Line):
+                    return [self]
+
+                if isinstance(self, Ray) and isinstance(other, Ray):
+                    return intersect_parallel_rays(self, other)
+                if isinstance(self, Ray) and isinstance(other, Segment):
+                    return intersect_parallel_ray_and_segment(self, other)
+                if isinstance(self, Segment) and isinstance(other, Ray):
+                    return intersect_parallel_ray_and_segment(other, self)
+                if isinstance(self, Segment) and isinstance(other, Segment):
+                    return intersect_parallel_segments(self, other)
+            elif rank == 2:
+                # we're in the same plane
+                l1 = Line(*pts[:2])
+                l2 = Line(*pts[2:])
+
+                # check to see if we're parallel.  If we are, we can't
+                # be intersecting, since the collinear case was already
+                # handled
+                if l1.direction.is_scalar_multiple(l2.direction):
+                    return []
+
+                # find the intersection as if everything were lines
+                # by solving the equation t*d + p1 == s*d' + p1'
+                m = Matrix([l1.direction, -l2.direction]).transpose()
+                v = Matrix([l2.p1 - l1.p1]).transpose()
+
+                # we cannot use m.solve(v) because that only works for square matrices
+                m_rref, pivots = m.col_insert(2, v).rref(simplify=True)
+                # rank == 2 ensures we have 2 pivots, but let's check anyway
+                if len(pivots) != 2:
+                    raise GeometryError("Failed when solving Mx=b when M={} and b={}".format(m, v))
+                coeff = m_rref[0, 2]
+                line_intersection = l1.direction*coeff + self.p1
+
+                # if both are lines, skip a containment check
+                if isinstance(self, Line) and isinstance(other, Line):
+                    return [line_intersection]
+
+                if ((isinstance(self, Line) or
+                     self.contains(line_intersection)) and
+                        other.contains(line_intersection)):
+                    return [line_intersection]
+                if not self.atoms(Float) and not other.atoms(Float):
+                    # if it can fail when there are no Floats then
+                    # maybe the following parametric check should be
+                    # done
+                    return []
+                # floats may fail exact containment so check that the
+                # arbitrary points, when  equal, both give a
+                # non-negative parameter when the arbitrary point
+                # coordinates are equated
+                tu = solve(self.arbitrary_point(t) - other.arbitrary_point(u),
+                    t, u, dict=True)[0]
+                def ok(p, l):
+                    if isinstance(l, Line):
+                        # p > -oo
+                        return True
+                    if isinstance(l, Ray):
+                        # p >= 0
+                        return p.is_nonnegative
+                    if isinstance(l, Segment):
+                        # 0 <= p <= 1
+                        return p.is_nonnegative and (1 - p).is_nonnegative
+                    raise ValueError("unexpected line type")
+                if ok(tu[t], self) and ok(tu[u], other):
+                    return [line_intersection]
+                return []
+            else:
+                # we're skew
+                return []
+
+        return other.intersection(self)
+
+    def is_parallel(l1, l2):
+        """Are two linear entities parallel?
+
+        Parameters
+        ==========
+
+        l1 : LinearEntity
+        l2 : LinearEntity
+
+        Returns
+        =======
+
+        True : if l1 and l2 are parallel,
+        False : otherwise.
+
+        See Also
+        ========
+
+        coefficients
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line
+        >>> p1, p2 = Point(0, 0), Point(1, 1)
+        >>> p3, p4 = Point(3, 4), Point(6, 7)
+        >>> l1, l2 = Line(p1, p2), Line(p3, p4)
+        >>> Line.is_parallel(l1, l2)
+        True
+        >>> p5 = Point(6, 6)
+        >>> l3 = Line(p3, p5)
+        >>> Line.is_parallel(l1, l3)
+        False
+        >>> from sympy import Point3D, Line3D
+        >>> p1, p2 = Point3D(0, 0, 0), Point3D(3, 4, 5)
+        >>> p3, p4 = Point3D(2, 1, 1), Point3D(8, 9, 11)
+        >>> l1, l2 = Line3D(p1, p2), Line3D(p3, p4)
+        >>> Line3D.is_parallel(l1, l2)
+        True
+        >>> p5 = Point3D(6, 6, 6)
+        >>> l3 = Line3D(p3, p5)
+        >>> Line3D.is_parallel(l1, l3)
+        False
+
+        """
+        if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity):
+            raise TypeError('Must pass only LinearEntity objects')
+
+        return l1.direction.is_scalar_multiple(l2.direction)
+
+    def is_perpendicular(l1, l2):
+        """Are two linear entities perpendicular?
+
+        Parameters
+        ==========
+
+        l1 : LinearEntity
+        l2 : LinearEntity
+
+        Returns
+        =======
+
+        True : if l1 and l2 are perpendicular,
+        False : otherwise.
+
+        See Also
+        ========
+
+        coefficients
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line
+        >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(-1, 1)
+        >>> l1, l2 = Line(p1, p2), Line(p1, p3)
+        >>> l1.is_perpendicular(l2)
+        True
+        >>> p4 = Point(5, 3)
+        >>> l3 = Line(p1, p4)
+        >>> l1.is_perpendicular(l3)
+        False
+        >>> from sympy import Point3D, Line3D
+        >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(-1, 2, 0)
+        >>> l1, l2 = Line3D(p1, p2), Line3D(p2, p3)
+        >>> l1.is_perpendicular(l2)
+        False
+        >>> p4 = Point3D(5, 3, 7)
+        >>> l3 = Line3D(p1, p4)
+        >>> l1.is_perpendicular(l3)
+        False
+
+        """
+        if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity):
+            raise TypeError('Must pass only LinearEntity objects')
+
+        return S.Zero.equals(l1.direction.dot(l2.direction))
+
+    def is_similar(self, other):
+        """
+        Return True if self and other are contained in the same line.
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line
+        >>> p1, p2, p3 = Point(0, 1), Point(3, 4), Point(2, 3)
+        >>> l1 = Line(p1, p2)
+        >>> l2 = Line(p1, p3)
+        >>> l1.is_similar(l2)
+        True
+        """
+        l = Line(self.p1, self.p2)
+        return l.contains(other)
+
+    @property
+    def length(self):
+        """
+        The length of the line.
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line
+        >>> p1, p2 = Point(0, 0), Point(3, 5)
+        >>> l1 = Line(p1, p2)
+        >>> l1.length
+        oo
+        """
+        return S.Infinity
+
+    @property
+    def p1(self):
+        """The first defining point of a linear entity.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line
+        >>> p1, p2 = Point(0, 0), Point(5, 3)
+        >>> l = Line(p1, p2)
+        >>> l.p1
+        Point2D(0, 0)
+
+        """
+        return self.args[0]
+
+    @property
+    def p2(self):
+        """The second defining point of a linear entity.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line
+        >>> p1, p2 = Point(0, 0), Point(5, 3)
+        >>> l = Line(p1, p2)
+        >>> l.p2
+        Point2D(5, 3)
+
+        """
+        return self.args[1]
+
+    def parallel_line(self, p):
+        """Create a new Line parallel to this linear entity which passes
+        through the point `p`.
+
+        Parameters
+        ==========
+
+        p : Point
+
+        Returns
+        =======
+
+        line : Line
+
+        See Also
+        ========
+
+        is_parallel
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line
+        >>> p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2)
+        >>> l1 = Line(p1, p2)
+        >>> l2 = l1.parallel_line(p3)
+        >>> p3 in l2
+        True
+        >>> l1.is_parallel(l2)
+        True
+        >>> from sympy import Point3D, Line3D
+        >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(2, 3, 4), Point3D(-2, 2, 0)
+        >>> l1 = Line3D(p1, p2)
+        >>> l2 = l1.parallel_line(p3)
+        >>> p3 in l2
+        True
+        >>> l1.is_parallel(l2)
+        True
+
+        """
+        p = Point(p, dim=self.ambient_dimension)
+        return Line(p, p + self.direction)
+
+    def perpendicular_line(self, p):
+        """Create a new Line perpendicular to this linear entity which passes
+        through the point `p`.
+
+        Parameters
+        ==========
+
+        p : Point
+
+        Returns
+        =======
+
+        line : Line
+
+        See Also
+        ========
+
+        sympy.geometry.line.LinearEntity.is_perpendicular, perpendicular_segment
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D, Line3D
+        >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(2, 3, 4), Point3D(-2, 2, 0)
+        >>> L = Line3D(p1, p2)
+        >>> P = L.perpendicular_line(p3); P
+        Line3D(Point3D(-2, 2, 0), Point3D(4/29, 6/29, 8/29))
+        >>> L.is_perpendicular(P)
+        True
+
+        In 3D the, the first point used to define the line is the point
+        through which the perpendicular was required to pass; the
+        second point is (arbitrarily) contained in the given line:
+
+        >>> P.p2 in L
+        True
+        """
+        p = Point(p, dim=self.ambient_dimension)
+        if p in self:
+            p = p + self.direction.orthogonal_direction
+        return Line(p, self.projection(p))
+
+    def perpendicular_segment(self, p):
+        """Create a perpendicular line segment from `p` to this line.
+
+        The endpoints of the segment are ``p`` and the closest point in
+        the line containing self. (If self is not a line, the point might
+        not be in self.)
+
+        Parameters
+        ==========
+
+        p : Point
+
+        Returns
+        =======
+
+        segment : Segment
+
+        Notes
+        =====
+
+        Returns `p` itself if `p` is on this linear entity.
+
+        See Also
+        ========
+
+        perpendicular_line
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line
+        >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(0, 2)
+        >>> l1 = Line(p1, p2)
+        >>> s1 = l1.perpendicular_segment(p3)
+        >>> l1.is_perpendicular(s1)
+        True
+        >>> p3 in s1
+        True
+        >>> l1.perpendicular_segment(Point(4, 0))
+        Segment2D(Point2D(4, 0), Point2D(2, 2))
+        >>> from sympy import Point3D, Line3D
+        >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, 2, 0)
+        >>> l1 = Line3D(p1, p2)
+        >>> s1 = l1.perpendicular_segment(p3)
+        >>> l1.is_perpendicular(s1)
+        True
+        >>> p3 in s1
+        True
+        >>> l1.perpendicular_segment(Point3D(4, 0, 0))
+        Segment3D(Point3D(4, 0, 0), Point3D(4/3, 4/3, 4/3))
+
+        """
+        p = Point(p, dim=self.ambient_dimension)
+        if p in self:
+            return p
+        l = self.perpendicular_line(p)
+        # The intersection should be unique, so unpack the singleton
+        p2, = Intersection(Line(self.p1, self.p2), l)
+
+        return Segment(p, p2)
+
+    @property
+    def points(self):
+        """The two points used to define this linear entity.
+
+        Returns
+        =======
+
+        points : tuple of Points
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line
+        >>> p1, p2 = Point(0, 0), Point(5, 11)
+        >>> l1 = Line(p1, p2)
+        >>> l1.points
+        (Point2D(0, 0), Point2D(5, 11))
+
+        """
+        return (self.p1, self.p2)
+
+    def projection(self, other):
+        """Project a point, line, ray, or segment onto this linear entity.
+
+        Parameters
+        ==========
+
+        other : Point or LinearEntity (Line, Ray, Segment)
+
+        Returns
+        =======
+
+        projection : Point or LinearEntity (Line, Ray, Segment)
+            The return type matches the type of the parameter ``other``.
+
+        Raises
+        ======
+
+        GeometryError
+            When method is unable to perform projection.
+
+        Notes
+        =====
+
+        A projection involves taking the two points that define
+        the linear entity and projecting those points onto a
+        Line and then reforming the linear entity using these
+        projections.
+        A point P is projected onto a line L by finding the point
+        on L that is closest to P. This point is the intersection
+        of L and the line perpendicular to L that passes through P.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point, perpendicular_line
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line, Segment, Rational
+        >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(Rational(1, 2), 0)
+        >>> l1 = Line(p1, p2)
+        >>> l1.projection(p3)
+        Point2D(1/4, 1/4)
+        >>> p4, p5 = Point(10, 0), Point(12, 1)
+        >>> s1 = Segment(p4, p5)
+        >>> l1.projection(s1)
+        Segment2D(Point2D(5, 5), Point2D(13/2, 13/2))
+        >>> p1, p2, p3 = Point(0, 0, 1), Point(1, 1, 2), Point(2, 0, 1)
+        >>> l1 = Line(p1, p2)
+        >>> l1.projection(p3)
+        Point3D(2/3, 2/3, 5/3)
+        >>> p4, p5 = Point(10, 0, 1), Point(12, 1, 3)
+        >>> s1 = Segment(p4, p5)
+        >>> l1.projection(s1)
+        Segment3D(Point3D(10/3, 10/3, 13/3), Point3D(5, 5, 6))
+
+        """
+        if not isinstance(other, GeometryEntity):
+            other = Point(other, dim=self.ambient_dimension)
+
+        def proj_point(p):
+            return Point.project(p - self.p1, self.direction) + self.p1
+
+        if isinstance(other, Point):
+            return proj_point(other)
+        elif isinstance(other, LinearEntity):
+            p1, p2 = proj_point(other.p1), proj_point(other.p2)
+            # test to see if we're degenerate
+            if p1 == p2:
+                return p1
+            projected = other.__class__(p1, p2)
+            projected = Intersection(self, projected)
+            if projected.is_empty:
+                return projected
+            # if we happen to have intersected in only a point, return that
+            if projected.is_FiniteSet and len(projected) == 1:
+                # projected is a set of size 1, so unpack it in `a`
+                a, = projected
+                return a
+            # order args so projection is in the same direction as self
+            if self.direction.dot(projected.direction) < 0:
+                p1, p2 = projected.args
+                projected = projected.func(p2, p1)
+            return projected
+
+        raise GeometryError(
+            "Do not know how to project %s onto %s" % (other, self))
+
+    def random_point(self, seed=None):
+        """A random point on a LinearEntity.
+
+        Returns
+        =======
+
+        point : Point
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line, Ray, Segment
+        >>> p1, p2 = Point(0, 0), Point(5, 3)
+        >>> line = Line(p1, p2)
+        >>> r = line.random_point(seed=42)  # seed value is optional
+        >>> r.n(3)
+        Point2D(-0.72, -0.432)
+        >>> r in line
+        True
+        >>> Ray(p1, p2).random_point(seed=42).n(3)
+        Point2D(0.72, 0.432)
+        >>> Segment(p1, p2).random_point(seed=42).n(3)
+        Point2D(3.2, 1.92)
+
+        """
+        if seed is not None:
+            rng = random.Random(seed)
+        else:
+            rng = random
+        pt = self.arbitrary_point(t)
+        if isinstance(self, Ray):
+            v = abs(rng.gauss(0, 1))
+        elif isinstance(self, Segment):
+            v = rng.random()
+        elif isinstance(self, Line):
+            v = rng.gauss(0, 1)
+        else:
+            raise NotImplementedError('unhandled line type')
+        return pt.subs(t, Rational(v))
+
+    def bisectors(self, other):
+        """Returns the perpendicular lines which pass through the intersections
+        of self and other that are in the same plane.
+
+        Parameters
+        ==========
+
+        line : Line3D
+
+        Returns
+        =======
+
+        list: two Line instances
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D, Line3D
+        >>> r1 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0))
+        >>> r2 = Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0))
+        >>> r1.bisectors(r2)
+        [Line3D(Point3D(0, 0, 0), Point3D(1, 1, 0)), Line3D(Point3D(0, 0, 0), Point3D(1, -1, 0))]
+
+        """
+        if not isinstance(other, LinearEntity):
+            raise GeometryError("Expecting LinearEntity, not %s" % other)
+
+        l1, l2 = self, other
+
+        # make sure dimensions match or else a warning will rise from
+        # intersection calculation
+        if l1.p1.ambient_dimension != l2.p1.ambient_dimension:
+            if isinstance(l1, Line2D):
+                l1, l2 = l2, l1
+            _, p1 = Point._normalize_dimension(l1.p1, l2.p1, on_morph='ignore')
+            _, p2 = Point._normalize_dimension(l1.p2, l2.p2, on_morph='ignore')
+            l2 = Line(p1, p2)
+
+        point = intersection(l1, l2)
+
+        # Three cases: Lines may intersect in a point, may be equal or may not intersect.
+        if not point:
+            raise GeometryError("The lines do not intersect")
+        else:
+            pt = point[0]
+            if isinstance(pt, Line):
+                # Intersection is a line because both lines are coincident
+                return [self]
+
+
+        d1 = l1.direction.unit
+        d2 = l2.direction.unit
+
+        bis1 = Line(pt, pt + d1 + d2)
+        bis2 = Line(pt, pt + d1 - d2)
+
+        return [bis1, bis2]
+
+
+class Line(LinearEntity):
+    """An infinite line in space.
+
+    A 2D line is declared with two distinct points, point and slope, or
+    an equation. A 3D line may be defined with a point and a direction ratio.
+
+    Parameters
+    ==========
+
+    p1 : Point
+    p2 : Point
+    slope : SymPy expression
+    direction_ratio : list
+    equation : equation of a line
+
+    Notes
+    =====
+
+    `Line` will automatically subclass to `Line2D` or `Line3D` based
+    on the dimension of `p1`.  The `slope` argument is only relevant
+    for `Line2D` and the `direction_ratio` argument is only relevant
+    for `Line3D`.
+
+    The order of the points will define the direction of the line
+    which is used when calculating the angle between lines.
+
+    See Also
+    ========
+
+    sympy.geometry.point.Point
+    sympy.geometry.line.Line2D
+    sympy.geometry.line.Line3D
+
+    Examples
+    ========
+
+    >>> from sympy import Line, Segment, Point, Eq
+    >>> from sympy.abc import x, y, a, b
+
+    >>> L = Line(Point(2,3), Point(3,5))
+    >>> L
+    Line2D(Point2D(2, 3), Point2D(3, 5))
+    >>> L.points
+    (Point2D(2, 3), Point2D(3, 5))
+    >>> L.equation()
+    -2*x + y + 1
+    >>> L.coefficients
+    (-2, 1, 1)
+
+    Instantiate with keyword ``slope``:
+
+    >>> Line(Point(0, 0), slope=0)
+    Line2D(Point2D(0, 0), Point2D(1, 0))
+
+    Instantiate with another linear object
+
+    >>> s = Segment((0, 0), (0, 1))
+    >>> Line(s).equation()
+    x
+
+    The line corresponding to an equation in the for `ax + by + c = 0`,
+    can be entered:
+
+    >>> Line(3*x + y + 18)
+    Line2D(Point2D(0, -18), Point2D(1, -21))
+
+    If `x` or `y` has a different name, then they can be specified, too,
+    as a string (to match the name) or symbol:
+
+    >>> Line(Eq(3*a + b, -18), x='a', y=b)
+    Line2D(Point2D(0, -18), Point2D(1, -21))
+    """
+    def __new__(cls, *args, **kwargs):
+        if len(args) == 1 and isinstance(args[0], (Expr, Eq)):
+            missing = uniquely_named_symbol('?', args)
+            if not kwargs:
+                x = 'x'
+                y = 'y'
+            else:
+                x = kwargs.pop('x', missing)
+                y = kwargs.pop('y', missing)
+            if kwargs:
+                raise ValueError('expecting only x and y as keywords')
+
+            equation = args[0]
+            if isinstance(equation, Eq):
+                equation = equation.lhs - equation.rhs
+
+            def find_or_missing(x):
+                try:
+                    return find(x, equation)
+                except ValueError:
+                    return missing
+            x = find_or_missing(x)
+            y = find_or_missing(y)
+
+            a, b, c = linear_coeffs(equation, x, y)
+
+            if b:
+                return Line((0, -c/b), slope=-a/b)
+            if a:
+                return Line((-c/a, 0), slope=oo)
+
+            raise ValueError('not found in equation: %s' % (set('xy') - {x, y}))
+
+        else:
+            if len(args) > 0:
+                p1 = args[0]
+                if len(args) > 1:
+                    p2 = args[1]
+                else:
+                    p2 = None
+
+                if isinstance(p1, LinearEntity):
+                    if p2:
+                        raise ValueError('If p1 is a LinearEntity, p2 must be None.')
+                    dim = len(p1.p1)
+                else:
+                    p1 = Point(p1)
+                    dim = len(p1)
+                    if p2 is not None or isinstance(p2, Point) and p2.ambient_dimension != dim:
+                        p2 = Point(p2)
+
+                if dim == 2:
+                    return Line2D(p1, p2, **kwargs)
+                elif dim == 3:
+                    return Line3D(p1, p2, **kwargs)
+                return LinearEntity.__new__(cls, p1, p2, **kwargs)
+
+    def contains(self, other):
+        """
+        Return True if `other` is on this Line, or False otherwise.
+
+        Examples
+        ========
+
+        >>> from sympy import Line,Point
+        >>> p1, p2 = Point(0, 1), Point(3, 4)
+        >>> l = Line(p1, p2)
+        >>> l.contains(p1)
+        True
+        >>> l.contains((0, 1))
+        True
+        >>> l.contains((0, 0))
+        False
+        >>> a = (0, 0, 0)
+        >>> b = (1, 1, 1)
+        >>> c = (2, 2, 2)
+        >>> l1 = Line(a, b)
+        >>> l2 = Line(b, a)
+        >>> l1 == l2
+        False
+        >>> l1 in l2
+        True
+
+        """
+        if not isinstance(other, GeometryEntity):
+            other = Point(other, dim=self.ambient_dimension)
+        if isinstance(other, Point):
+            return Point.is_collinear(other, self.p1, self.p2)
+        if isinstance(other, LinearEntity):
+            return Point.is_collinear(self.p1, self.p2, other.p1, other.p2)
+        return False
+
+    def distance(self, other):
+        """
+        Finds the shortest distance between a line and a point.
+
+        Raises
+        ======
+
+        NotImplementedError is raised if `other` is not a Point
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line
+        >>> p1, p2 = Point(0, 0), Point(1, 1)
+        >>> s = Line(p1, p2)
+        >>> s.distance(Point(-1, 1))
+        sqrt(2)
+        >>> s.distance((-1, 2))
+        3*sqrt(2)/2
+        >>> p1, p2 = Point(0, 0, 0), Point(1, 1, 1)
+        >>> s = Line(p1, p2)
+        >>> s.distance(Point(-1, 1, 1))
+        2*sqrt(6)/3
+        >>> s.distance((-1, 1, 1))
+        2*sqrt(6)/3
+
+        """
+        if not isinstance(other, GeometryEntity):
+            other = Point(other, dim=self.ambient_dimension)
+        if self.contains(other):
+            return S.Zero
+        return self.perpendicular_segment(other).length
+
+    def equals(self, other):
+        """Returns True if self and other are the same mathematical entities"""
+        if not isinstance(other, Line):
+            return False
+        return Point.is_collinear(self.p1, other.p1, self.p2, other.p2)
+
+    def plot_interval(self, parameter='t'):
+        """The plot interval for the default geometric plot of line. Gives
+        values that will produce a line that is +/- 5 units long (where a
+        unit is the distance between the two points that define the line).
+
+        Parameters
+        ==========
+
+        parameter : str, optional
+            Default value is 't'.
+
+        Returns
+        =======
+
+        plot_interval : list (plot interval)
+            [parameter, lower_bound, upper_bound]
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line
+        >>> p1, p2 = Point(0, 0), Point(5, 3)
+        >>> l1 = Line(p1, p2)
+        >>> l1.plot_interval()
+        [t, -5, 5]
+
+        """
+        t = _symbol(parameter, real=True)
+        return [t, -5, 5]
+
+
+class Ray(LinearEntity):
+    """A Ray is a semi-line in the space with a source point and a direction.
+
+    Parameters
+    ==========
+
+    p1 : Point
+        The source of the Ray
+    p2 : Point or radian value
+        This point determines the direction in which the Ray propagates.
+        If given as an angle it is interpreted in radians with the positive
+        direction being ccw.
+
+    Attributes
+    ==========
+
+    source
+
+    See Also
+    ========
+
+    sympy.geometry.line.Ray2D
+    sympy.geometry.line.Ray3D
+    sympy.geometry.point.Point
+    sympy.geometry.line.Line
+
+    Notes
+    =====
+
+    `Ray` will automatically subclass to `Ray2D` or `Ray3D` based on the
+    dimension of `p1`.
+
+    Examples
+    ========
+
+    >>> from sympy import Ray, Point, pi
+    >>> r = Ray(Point(2, 3), Point(3, 5))
+    >>> r
+    Ray2D(Point2D(2, 3), Point2D(3, 5))
+    >>> r.points
+    (Point2D(2, 3), Point2D(3, 5))
+    >>> r.source
+    Point2D(2, 3)
+    >>> r.xdirection
+    oo
+    >>> r.ydirection
+    oo
+    >>> r.slope
+    2
+    >>> Ray(Point(0, 0), angle=pi/4).slope
+    1
+
+    """
+    def __new__(cls, p1, p2=None, **kwargs):
+        p1 = Point(p1)
+        if p2 is not None:
+            p1, p2 = Point._normalize_dimension(p1, Point(p2))
+        dim = len(p1)
+
+        if dim == 2:
+            return Ray2D(p1, p2, **kwargs)
+        elif dim == 3:
+            return Ray3D(p1, p2, **kwargs)
+        return LinearEntity.__new__(cls, p1, p2, **kwargs)
+
+    def _svg(self, scale_factor=1., fill_color="#66cc99"):
+        """Returns SVG path element for the LinearEntity.
+
+        Parameters
+        ==========
+
+        scale_factor : float
+            Multiplication factor for the SVG stroke-width.  Default is 1.
+        fill_color : str, optional
+            Hex string for fill color. Default is "#66cc99".
+        """
+        verts = (N(self.p1), N(self.p2))
+        coords = ["{},{}".format(p.x, p.y) for p in verts]
+        path = "M {} L {}".format(coords[0], " L ".join(coords[1:]))
+
+        return (
+            ''
+        ).format(2.*scale_factor, path, fill_color)
+
+    def contains(self, other):
+        """
+        Is other GeometryEntity contained in this Ray?
+
+        Examples
+        ========
+
+        >>> from sympy import Ray,Point,Segment
+        >>> p1, p2 = Point(0, 0), Point(4, 4)
+        >>> r = Ray(p1, p2)
+        >>> r.contains(p1)
+        True
+        >>> r.contains((1, 1))
+        True
+        >>> r.contains((1, 3))
+        False
+        >>> s = Segment((1, 1), (2, 2))
+        >>> r.contains(s)
+        True
+        >>> s = Segment((1, 2), (2, 5))
+        >>> r.contains(s)
+        False
+        >>> r1 = Ray((2, 2), (3, 3))
+        >>> r.contains(r1)
+        True
+        >>> r1 = Ray((2, 2), (3, 5))
+        >>> r.contains(r1)
+        False
+        """
+        if not isinstance(other, GeometryEntity):
+            other = Point(other, dim=self.ambient_dimension)
+        if isinstance(other, Point):
+            if Point.is_collinear(self.p1, self.p2, other):
+                # if we're in the direction of the ray, our
+                # direction vector dot the ray's direction vector
+                # should be non-negative
+                return bool((self.p2 - self.p1).dot(other - self.p1) >= S.Zero)
+            return False
+        elif isinstance(other, Ray):
+            if Point.is_collinear(self.p1, self.p2, other.p1, other.p2):
+                return bool((self.p2 - self.p1).dot(other.p2 - other.p1) > S.Zero)
+            return False
+        elif isinstance(other, Segment):
+            return other.p1 in self and other.p2 in self
+
+        # No other known entity can be contained in a Ray
+        return False
+
+    def distance(self, other):
+        """
+        Finds the shortest distance between the ray and a point.
+
+        Raises
+        ======
+
+        NotImplementedError is raised if `other` is not a Point
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ray
+        >>> p1, p2 = Point(0, 0), Point(1, 1)
+        >>> s = Ray(p1, p2)
+        >>> s.distance(Point(-1, -1))
+        sqrt(2)
+        >>> s.distance((-1, 2))
+        3*sqrt(2)/2
+        >>> p1, p2 = Point(0, 0, 0), Point(1, 1, 2)
+        >>> s = Ray(p1, p2)
+        >>> s
+        Ray3D(Point3D(0, 0, 0), Point3D(1, 1, 2))
+        >>> s.distance(Point(-1, -1, 2))
+        4*sqrt(3)/3
+        >>> s.distance((-1, -1, 2))
+        4*sqrt(3)/3
+
+        """
+        if not isinstance(other, GeometryEntity):
+            other = Point(other, dim=self.ambient_dimension)
+        if self.contains(other):
+            return S.Zero
+
+        proj = Line(self.p1, self.p2).projection(other)
+        if self.contains(proj):
+            return abs(other - proj)
+        else:
+            return abs(other - self.source)
+
+    def equals(self, other):
+        """Returns True if self and other are the same mathematical entities"""
+        if not isinstance(other, Ray):
+            return False
+        return self.source == other.source and other.p2 in self
+
+    def plot_interval(self, parameter='t'):
+        """The plot interval for the default geometric plot of the Ray. Gives
+        values that will produce a ray that is 10 units long (where a unit is
+        the distance between the two points that define the ray).
+
+        Parameters
+        ==========
+
+        parameter : str, optional
+            Default value is 't'.
+
+        Returns
+        =======
+
+        plot_interval : list
+            [parameter, lower_bound, upper_bound]
+
+        Examples
+        ========
+
+        >>> from sympy import Ray, pi
+        >>> r = Ray((0, 0), angle=pi/4)
+        >>> r.plot_interval()
+        [t, 0, 10]
+
+        """
+        t = _symbol(parameter, real=True)
+        return [t, 0, 10]
+
+    @property
+    def source(self):
+        """The point from which the ray emanates.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ray
+        >>> p1, p2 = Point(0, 0), Point(4, 1)
+        >>> r1 = Ray(p1, p2)
+        >>> r1.source
+        Point2D(0, 0)
+        >>> p1, p2 = Point(0, 0, 0), Point(4, 1, 5)
+        >>> r1 = Ray(p2, p1)
+        >>> r1.source
+        Point3D(4, 1, 5)
+
+        """
+        return self.p1
+
+
+class Segment(LinearEntity):
+    """A line segment in space.
+
+    Parameters
+    ==========
+
+    p1 : Point
+    p2 : Point
+
+    Attributes
+    ==========
+
+    length : number or SymPy expression
+    midpoint : Point
+
+    See Also
+    ========
+
+    sympy.geometry.line.Segment2D
+    sympy.geometry.line.Segment3D
+    sympy.geometry.point.Point
+    sympy.geometry.line.Line
+
+    Notes
+    =====
+
+    If 2D or 3D points are used to define `Segment`, it will
+    be automatically subclassed to `Segment2D` or `Segment3D`.
+
+    Examples
+    ========
+
+    >>> from sympy import Point, Segment
+    >>> Segment((1, 0), (1, 1)) # tuples are interpreted as pts
+    Segment2D(Point2D(1, 0), Point2D(1, 1))
+    >>> s = Segment(Point(4, 3), Point(1, 1))
+    >>> s.points
+    (Point2D(4, 3), Point2D(1, 1))
+    >>> s.slope
+    2/3
+    >>> s.length
+    sqrt(13)
+    >>> s.midpoint
+    Point2D(5/2, 2)
+    >>> Segment((1, 0, 0), (1, 1, 1)) # tuples are interpreted as pts
+    Segment3D(Point3D(1, 0, 0), Point3D(1, 1, 1))
+    >>> s = Segment(Point(4, 3, 9), Point(1, 1, 7)); s
+    Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7))
+    >>> s.points
+    (Point3D(4, 3, 9), Point3D(1, 1, 7))
+    >>> s.length
+    sqrt(17)
+    >>> s.midpoint
+    Point3D(5/2, 2, 8)
+
+    """
+    def __new__(cls, p1, p2, **kwargs):
+        p1, p2 = Point._normalize_dimension(Point(p1), Point(p2))
+        dim = len(p1)
+
+        if dim == 2:
+            return Segment2D(p1, p2, **kwargs)
+        elif dim == 3:
+            return Segment3D(p1, p2, **kwargs)
+        return LinearEntity.__new__(cls, p1, p2, **kwargs)
+
+    def contains(self, other):
+        """
+        Is the other GeometryEntity contained within this Segment?
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Segment
+        >>> p1, p2 = Point(0, 1), Point(3, 4)
+        >>> s = Segment(p1, p2)
+        >>> s2 = Segment(p2, p1)
+        >>> s.contains(s2)
+        True
+        >>> from sympy import Point3D, Segment3D
+        >>> p1, p2 = Point3D(0, 1, 1), Point3D(3, 4, 5)
+        >>> s = Segment3D(p1, p2)
+        >>> s2 = Segment3D(p2, p1)
+        >>> s.contains(s2)
+        True
+        >>> s.contains((p1 + p2)/2)
+        True
+        """
+        if not isinstance(other, GeometryEntity):
+            other = Point(other, dim=self.ambient_dimension)
+        if isinstance(other, Point):
+            if Point.is_collinear(other, self.p1, self.p2):
+                if isinstance(self, Segment2D):
+                    # if it is collinear and is in the bounding box of the
+                    # segment then it must be on the segment
+                    vert = (1/self.slope).equals(0)
+                    if vert is False:
+                        isin = (self.p1.x - other.x)*(self.p2.x - other.x) <= 0
+                        if isin in (True, False):
+                            return isin
+                    if vert is True:
+                        isin = (self.p1.y - other.y)*(self.p2.y - other.y) <= 0
+                        if isin in (True, False):
+                            return isin
+                # use the triangle inequality
+                d1, d2 = other - self.p1, other - self.p2
+                d = self.p2 - self.p1
+                # without the call to simplify, SymPy cannot tell that an expression
+                # like (a+b)*(a/2+b/2) is always non-negative.  If it cannot be
+                # determined, raise an Undecidable error
+                try:
+                    # the triangle inequality says that |d1|+|d2| >= |d| and is strict
+                    # only if other lies in the line segment
+                    return bool(simplify(Eq(abs(d1) + abs(d2) - abs(d), 0)))
+                except TypeError:
+                    raise Undecidable("Cannot determine if {} is in {}".format(other, self))
+        if isinstance(other, Segment):
+            return other.p1 in self and other.p2 in self
+
+        return False
+
+    def equals(self, other):
+        """Returns True if self and other are the same mathematical entities"""
+        return isinstance(other, self.func) and list(
+            ordered(self.args)) == list(ordered(other.args))
+
+    def distance(self, other):
+        """
+        Finds the shortest distance between a line segment and a point.
+
+        Raises
+        ======
+
+        NotImplementedError is raised if `other` is not a Point
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Segment
+        >>> p1, p2 = Point(0, 1), Point(3, 4)
+        >>> s = Segment(p1, p2)
+        >>> s.distance(Point(10, 15))
+        sqrt(170)
+        >>> s.distance((0, 12))
+        sqrt(73)
+        >>> from sympy import Point3D, Segment3D
+        >>> p1, p2 = Point3D(0, 0, 3), Point3D(1, 1, 4)
+        >>> s = Segment3D(p1, p2)
+        >>> s.distance(Point3D(10, 15, 12))
+        sqrt(341)
+        >>> s.distance((10, 15, 12))
+        sqrt(341)
+        """
+        if not isinstance(other, GeometryEntity):
+            other = Point(other, dim=self.ambient_dimension)
+        if isinstance(other, Point):
+            vp1 = other - self.p1
+            vp2 = other - self.p2
+
+            dot_prod_sign_1 = self.direction.dot(vp1) >= 0
+            dot_prod_sign_2 = self.direction.dot(vp2) <= 0
+            if dot_prod_sign_1 and dot_prod_sign_2:
+                return Line(self.p1, self.p2).distance(other)
+            if dot_prod_sign_1 and not dot_prod_sign_2:
+                return abs(vp2)
+            if not dot_prod_sign_1 and dot_prod_sign_2:
+                return abs(vp1)
+        raise NotImplementedError()
+
+    @property
+    def length(self):
+        """The length of the line segment.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point.distance
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Segment
+        >>> p1, p2 = Point(0, 0), Point(4, 3)
+        >>> s1 = Segment(p1, p2)
+        >>> s1.length
+        5
+        >>> from sympy import Point3D, Segment3D
+        >>> p1, p2 = Point3D(0, 0, 0), Point3D(4, 3, 3)
+        >>> s1 = Segment3D(p1, p2)
+        >>> s1.length
+        sqrt(34)
+
+        """
+        return Point.distance(self.p1, self.p2)
+
+    @property
+    def midpoint(self):
+        """The midpoint of the line segment.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point.midpoint
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Segment
+        >>> p1, p2 = Point(0, 0), Point(4, 3)
+        >>> s1 = Segment(p1, p2)
+        >>> s1.midpoint
+        Point2D(2, 3/2)
+        >>> from sympy import Point3D, Segment3D
+        >>> p1, p2 = Point3D(0, 0, 0), Point3D(4, 3, 3)
+        >>> s1 = Segment3D(p1, p2)
+        >>> s1.midpoint
+        Point3D(2, 3/2, 3/2)
+
+        """
+        return Point.midpoint(self.p1, self.p2)
+
+    def perpendicular_bisector(self, p=None):
+        """The perpendicular bisector of this segment.
+
+        If no point is specified or the point specified is not on the
+        bisector then the bisector is returned as a Line. Otherwise a
+        Segment is returned that joins the point specified and the
+        intersection of the bisector and the segment.
+
+        Parameters
+        ==========
+
+        p : Point
+
+        Returns
+        =======
+
+        bisector : Line or Segment
+
+        See Also
+        ========
+
+        LinearEntity.perpendicular_segment
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Segment
+        >>> p1, p2, p3 = Point(0, 0), Point(6, 6), Point(5, 1)
+        >>> s1 = Segment(p1, p2)
+        >>> s1.perpendicular_bisector()
+        Line2D(Point2D(3, 3), Point2D(-3, 9))
+
+        >>> s1.perpendicular_bisector(p3)
+        Segment2D(Point2D(5, 1), Point2D(3, 3))
+
+        """
+        l = self.perpendicular_line(self.midpoint)
+        if p is not None:
+            p2 = Point(p, dim=self.ambient_dimension)
+            if p2 in l:
+                return Segment(p2, self.midpoint)
+        return l
+
+    def plot_interval(self, parameter='t'):
+        """The plot interval for the default geometric plot of the Segment gives
+        values that will produce the full segment in a plot.
+
+        Parameters
+        ==========
+
+        parameter : str, optional
+            Default value is 't'.
+
+        Returns
+        =======
+
+        plot_interval : list
+            [parameter, lower_bound, upper_bound]
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Segment
+        >>> p1, p2 = Point(0, 0), Point(5, 3)
+        >>> s1 = Segment(p1, p2)
+        >>> s1.plot_interval()
+        [t, 0, 1]
+
+        """
+        t = _symbol(parameter, real=True)
+        return [t, 0, 1]
+
+
+class LinearEntity2D(LinearEntity):
+    """A base class for all linear entities (line, ray and segment)
+    in a 2-dimensional Euclidean space.
+
+    Attributes
+    ==========
+
+    p1
+    p2
+    coefficients
+    slope
+    points
+
+    Notes
+    =====
+
+    This is an abstract class and is not meant to be instantiated.
+
+    See Also
+    ========
+
+    sympy.geometry.entity.GeometryEntity
+
+    """
+    @property
+    def bounds(self):
+        """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding
+        rectangle for the geometric figure.
+
+        """
+        verts = self.points
+        xs = [p.x for p in verts]
+        ys = [p.y for p in verts]
+        return (min(xs), min(ys), max(xs), max(ys))
+
+    def perpendicular_line(self, p):
+        """Create a new Line perpendicular to this linear entity which passes
+        through the point `p`.
+
+        Parameters
+        ==========
+
+        p : Point
+
+        Returns
+        =======
+
+        line : Line
+
+        See Also
+        ========
+
+        sympy.geometry.line.LinearEntity.is_perpendicular, perpendicular_segment
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line
+        >>> p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2)
+        >>> L = Line(p1, p2)
+        >>> P = L.perpendicular_line(p3); P
+        Line2D(Point2D(-2, 2), Point2D(-5, 4))
+        >>> L.is_perpendicular(P)
+        True
+
+        In 2D, the first point of the perpendicular line is the
+        point through which was required to pass; the second
+        point is arbitrarily chosen. To get a line that explicitly
+        uses a point in the line, create a line from the perpendicular
+        segment from the line to the point:
+
+        >>> Line(L.perpendicular_segment(p3))
+        Line2D(Point2D(-2, 2), Point2D(4/13, 6/13))
+        """
+        p = Point(p, dim=self.ambient_dimension)
+        # any two lines in R^2 intersect, so blindly making
+        # a line through p in an orthogonal direction will work
+        # and is faster than finding the projection point as in 3D
+        return Line(p, p + self.direction.orthogonal_direction)
+
+    @property
+    def slope(self):
+        """The slope of this linear entity, or infinity if vertical.
+
+        Returns
+        =======
+
+        slope : number or SymPy expression
+
+        See Also
+        ========
+
+        coefficients
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line
+        >>> p1, p2 = Point(0, 0), Point(3, 5)
+        >>> l1 = Line(p1, p2)
+        >>> l1.slope
+        5/3
+
+        >>> p3 = Point(0, 4)
+        >>> l2 = Line(p1, p3)
+        >>> l2.slope
+        oo
+
+        """
+        d1, d2 = (self.p1 - self.p2).args
+        if d1 == 0:
+            return S.Infinity
+        return simplify(d2/d1)
+
+
+class Line2D(LinearEntity2D, Line):
+    """An infinite line in space 2D.
+
+    A line is declared with two distinct points or a point and slope
+    as defined using keyword `slope`.
+
+    Parameters
+    ==========
+
+    p1 : Point
+    pt : Point
+    slope : SymPy expression
+
+    See Also
+    ========
+
+    sympy.geometry.point.Point
+
+    Examples
+    ========
+
+    >>> from sympy import Line, Segment, Point
+    >>> L = Line(Point(2,3), Point(3,5))
+    >>> L
+    Line2D(Point2D(2, 3), Point2D(3, 5))
+    >>> L.points
+    (Point2D(2, 3), Point2D(3, 5))
+    >>> L.equation()
+    -2*x + y + 1
+    >>> L.coefficients
+    (-2, 1, 1)
+
+    Instantiate with keyword ``slope``:
+
+    >>> Line(Point(0, 0), slope=0)
+    Line2D(Point2D(0, 0), Point2D(1, 0))
+
+    Instantiate with another linear object
+
+    >>> s = Segment((0, 0), (0, 1))
+    >>> Line(s).equation()
+    x
+    """
+    def __new__(cls, p1, pt=None, slope=None, **kwargs):
+        if isinstance(p1, LinearEntity):
+            if pt is not None:
+                raise ValueError('When p1 is a LinearEntity, pt should be None')
+            p1, pt = Point._normalize_dimension(*p1.args, dim=2)
+        else:
+            p1 = Point(p1, dim=2)
+        if pt is not None and slope is None:
+            try:
+                p2 = Point(pt, dim=2)
+            except (NotImplementedError, TypeError, ValueError):
+                raise ValueError(filldedent('''
+                    The 2nd argument was not a valid Point.
+                    If it was a slope, enter it with keyword "slope".
+                    '''))
+        elif slope is not None and pt is None:
+            slope = sympify(slope)
+            if slope.is_finite is False:
+                # when infinite slope, don't change x
+                dx = 0
+                dy = 1
+            else:
+                # go over 1 up slope
+                dx = 1
+                dy = slope
+            # XXX avoiding simplification by adding to coords directly
+            p2 = Point(p1.x + dx, p1.y + dy, evaluate=False)
+        else:
+            raise ValueError('A 2nd Point or keyword "slope" must be used.')
+        return LinearEntity2D.__new__(cls, p1, p2, **kwargs)
+
+    def _svg(self, scale_factor=1., fill_color="#66cc99"):
+        """Returns SVG path element for the LinearEntity.
+
+        Parameters
+        ==========
+
+        scale_factor : float
+            Multiplication factor for the SVG stroke-width.  Default is 1.
+        fill_color : str, optional
+            Hex string for fill color. Default is "#66cc99".
+        """
+        verts = (N(self.p1), N(self.p2))
+        coords = ["{},{}".format(p.x, p.y) for p in verts]
+        path = "M {} L {}".format(coords[0], " L ".join(coords[1:]))
+
+        return (
+            ''
+        ).format(2.*scale_factor, path, fill_color)
+
+    @property
+    def coefficients(self):
+        """The coefficients (`a`, `b`, `c`) for `ax + by + c = 0`.
+
+        See Also
+        ========
+
+        sympy.geometry.line.Line2D.equation
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line
+        >>> from sympy.abc import x, y
+        >>> p1, p2 = Point(0, 0), Point(5, 3)
+        >>> l = Line(p1, p2)
+        >>> l.coefficients
+        (-3, 5, 0)
+
+        >>> p3 = Point(x, y)
+        >>> l2 = Line(p1, p3)
+        >>> l2.coefficients
+        (-y, x, 0)
+
+        """
+        p1, p2 = self.points
+        if p1.x == p2.x:
+            return (S.One, S.Zero, -p1.x)
+        elif p1.y == p2.y:
+            return (S.Zero, S.One, -p1.y)
+        return tuple([simplify(i) for i in
+                      (self.p1.y - self.p2.y,
+                       self.p2.x - self.p1.x,
+                       self.p1.x*self.p2.y - self.p1.y*self.p2.x)])
+
+    def equation(self, x='x', y='y'):
+        """The equation of the line: ax + by + c.
+
+        Parameters
+        ==========
+
+        x : str, optional
+            The name to use for the x-axis, default value is 'x'.
+        y : str, optional
+            The name to use for the y-axis, default value is 'y'.
+
+        Returns
+        =======
+
+        equation : SymPy expression
+
+        See Also
+        ========
+
+        sympy.geometry.line.Line2D.coefficients
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line
+        >>> p1, p2 = Point(1, 0), Point(5, 3)
+        >>> l1 = Line(p1, p2)
+        >>> l1.equation()
+        -3*x + 4*y + 3
+
+        """
+        x = _symbol(x, real=True)
+        y = _symbol(y, real=True)
+        p1, p2 = self.points
+        if p1.x == p2.x:
+            return x - p1.x
+        elif p1.y == p2.y:
+            return y - p1.y
+
+        a, b, c = self.coefficients
+        return a*x + b*y + c
+
+
+class Ray2D(LinearEntity2D, Ray):
+    """
+    A Ray is a semi-line in the space with a source point and a direction.
+
+    Parameters
+    ==========
+
+    p1 : Point
+        The source of the Ray
+    p2 : Point or radian value
+        This point determines the direction in which the Ray propagates.
+        If given as an angle it is interpreted in radians with the positive
+        direction being ccw.
+
+    Attributes
+    ==========
+
+    source
+    xdirection
+    ydirection
+
+    See Also
+    ========
+
+    sympy.geometry.point.Point, Line
+
+    Examples
+    ========
+
+    >>> from sympy import Point, pi, Ray
+    >>> r = Ray(Point(2, 3), Point(3, 5))
+    >>> r
+    Ray2D(Point2D(2, 3), Point2D(3, 5))
+    >>> r.points
+    (Point2D(2, 3), Point2D(3, 5))
+    >>> r.source
+    Point2D(2, 3)
+    >>> r.xdirection
+    oo
+    >>> r.ydirection
+    oo
+    >>> r.slope
+    2
+    >>> Ray(Point(0, 0), angle=pi/4).slope
+    1
+
+    """
+    def __new__(cls, p1, pt=None, angle=None, **kwargs):
+        p1 = Point(p1, dim=2)
+        if pt is not None and angle is None:
+            try:
+                p2 = Point(pt, dim=2)
+            except (NotImplementedError, TypeError, ValueError):
+                raise ValueError(filldedent('''
+                    The 2nd argument was not a valid Point; if
+                    it was meant to be an angle it should be
+                    given with keyword "angle".'''))
+            if p1 == p2:
+                raise ValueError('A Ray requires two distinct points.')
+        elif angle is not None and pt is None:
+            # we need to know if the angle is an odd multiple of pi/2
+            angle = sympify(angle)
+            c = _pi_coeff(angle)
+            p2 = None
+            if c is not None:
+                if c.is_Rational:
+                    if c.q == 2:
+                        if c.p == 1:
+                            p2 = p1 + Point(0, 1)
+                        elif c.p == 3:
+                            p2 = p1 + Point(0, -1)
+                    elif c.q == 1:
+                        if c.p == 0:
+                            p2 = p1 + Point(1, 0)
+                        elif c.p == 1:
+                            p2 = p1 + Point(-1, 0)
+                if p2 is None:
+                    c *= S.Pi
+            else:
+                c = angle % (2*S.Pi)
+            if not p2:
+                m = 2*c/S.Pi
+                left = And(1 < m, m < 3)  # is it in quadrant 2 or 3?
+                x = Piecewise((-1, left), (Piecewise((0, Eq(m % 1, 0)), (1, True)), True))
+                y = Piecewise((-tan(c), left), (Piecewise((1, Eq(m, 1)), (-1, Eq(m, 3)), (tan(c), True)), True))
+                p2 = p1 + Point(x, y)
+        else:
+            raise ValueError('A 2nd point or keyword "angle" must be used.')
+
+        return LinearEntity2D.__new__(cls, p1, p2, **kwargs)
+
+    @property
+    def xdirection(self):
+        """The x direction of the ray.
+
+        Positive infinity if the ray points in the positive x direction,
+        negative infinity if the ray points in the negative x direction,
+        or 0 if the ray is vertical.
+
+        See Also
+        ========
+
+        ydirection
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ray
+        >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(0, -1)
+        >>> r1, r2 = Ray(p1, p2), Ray(p1, p3)
+        >>> r1.xdirection
+        oo
+        >>> r2.xdirection
+        0
+
+        """
+        if self.p1.x < self.p2.x:
+            return S.Infinity
+        elif self.p1.x == self.p2.x:
+            return S.Zero
+        else:
+            return S.NegativeInfinity
+
+    @property
+    def ydirection(self):
+        """The y direction of the ray.
+
+        Positive infinity if the ray points in the positive y direction,
+        negative infinity if the ray points in the negative y direction,
+        or 0 if the ray is horizontal.
+
+        See Also
+        ========
+
+        xdirection
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Ray
+        >>> p1, p2, p3 = Point(0, 0), Point(-1, -1), Point(-1, 0)
+        >>> r1, r2 = Ray(p1, p2), Ray(p1, p3)
+        >>> r1.ydirection
+        -oo
+        >>> r2.ydirection
+        0
+
+        """
+        if self.p1.y < self.p2.y:
+            return S.Infinity
+        elif self.p1.y == self.p2.y:
+            return S.Zero
+        else:
+            return S.NegativeInfinity
+
+    def closing_angle(r1, r2):
+        """Return the angle by which r2 must be rotated so it faces the same
+        direction as r1.
+
+        Parameters
+        ==========
+
+        r1 : Ray2D
+        r2 : Ray2D
+
+        Returns
+        =======
+
+        angle : angle in radians (ccw angle is positive)
+
+        See Also
+        ========
+
+        LinearEntity.angle_between
+
+        Examples
+        ========
+
+        >>> from sympy import Ray, pi
+        >>> r1 = Ray((0, 0), (1, 0))
+        >>> r2 = r1.rotate(-pi/2)
+        >>> angle = r1.closing_angle(r2); angle
+        pi/2
+        >>> r2.rotate(angle).direction.unit == r1.direction.unit
+        True
+        >>> r2.closing_angle(r1)
+        -pi/2
+        """
+        if not all(isinstance(r, Ray2D) for r in (r1, r2)):
+            # although the direction property is defined for
+            # all linear entities, only the Ray is truly a
+            # directed object
+            raise TypeError('Both arguments must be Ray2D objects.')
+
+        a1 = atan2(*list(reversed(r1.direction.args)))
+        a2 = atan2(*list(reversed(r2.direction.args)))
+        if a1*a2 < 0:
+            a1 = 2*S.Pi + a1 if a1 < 0 else a1
+            a2 = 2*S.Pi + a2 if a2 < 0 else a2
+        return a1 - a2
+
+
+class Segment2D(LinearEntity2D, Segment):
+    """A line segment in 2D space.
+
+    Parameters
+    ==========
+
+    p1 : Point
+    p2 : Point
+
+    Attributes
+    ==========
+
+    length : number or SymPy expression
+    midpoint : Point
+
+    See Also
+    ========
+
+    sympy.geometry.point.Point, Line
+
+    Examples
+    ========
+
+    >>> from sympy import Point, Segment
+    >>> Segment((1, 0), (1, 1)) # tuples are interpreted as pts
+    Segment2D(Point2D(1, 0), Point2D(1, 1))
+    >>> s = Segment(Point(4, 3), Point(1, 1)); s
+    Segment2D(Point2D(4, 3), Point2D(1, 1))
+    >>> s.points
+    (Point2D(4, 3), Point2D(1, 1))
+    >>> s.slope
+    2/3
+    >>> s.length
+    sqrt(13)
+    >>> s.midpoint
+    Point2D(5/2, 2)
+
+    """
+    def __new__(cls, p1, p2, **kwargs):
+        p1 = Point(p1, dim=2)
+        p2 = Point(p2, dim=2)
+
+        if p1 == p2:
+            return p1
+
+        return LinearEntity2D.__new__(cls, p1, p2, **kwargs)
+
+    def _svg(self, scale_factor=1., fill_color="#66cc99"):
+        """Returns SVG path element for the LinearEntity.
+
+        Parameters
+        ==========
+
+        scale_factor : float
+            Multiplication factor for the SVG stroke-width.  Default is 1.
+        fill_color : str, optional
+            Hex string for fill color. Default is "#66cc99".
+        """
+        verts = (N(self.p1), N(self.p2))
+        coords = ["{},{}".format(p.x, p.y) for p in verts]
+        path = "M {} L {}".format(coords[0], " L ".join(coords[1:]))
+        return (
+            ''
+        ).format(2.*scale_factor, path, fill_color)
+
+
+class LinearEntity3D(LinearEntity):
+    """An base class for all linear entities (line, ray and segment)
+    in a 3-dimensional Euclidean space.
+
+    Attributes
+    ==========
+
+    p1
+    p2
+    direction_ratio
+    direction_cosine
+    points
+
+    Notes
+    =====
+
+    This is a base class and is not meant to be instantiated.
+    """
+    def __new__(cls, p1, p2, **kwargs):
+        p1 = Point3D(p1, dim=3)
+        p2 = Point3D(p2, dim=3)
+        if p1 == p2:
+            # if it makes sense to return a Point, handle in subclass
+            raise ValueError(
+                "%s.__new__ requires two unique Points." % cls.__name__)
+
+        return GeometryEntity.__new__(cls, p1, p2, **kwargs)
+
+    ambient_dimension = 3
+
+    @property
+    def direction_ratio(self):
+        """The direction ratio of a given line in 3D.
+
+        See Also
+        ========
+
+        sympy.geometry.line.Line3D.equation
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D, Line3D
+        >>> p1, p2 = Point3D(0, 0, 0), Point3D(5, 3, 1)
+        >>> l = Line3D(p1, p2)
+        >>> l.direction_ratio
+        [5, 3, 1]
+        """
+        p1, p2 = self.points
+        return p1.direction_ratio(p2)
+
+    @property
+    def direction_cosine(self):
+        """The normalized direction ratio of a given line in 3D.
+
+        See Also
+        ========
+
+        sympy.geometry.line.Line3D.equation
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D, Line3D
+        >>> p1, p2 = Point3D(0, 0, 0), Point3D(5, 3, 1)
+        >>> l = Line3D(p1, p2)
+        >>> l.direction_cosine
+        [sqrt(35)/7, 3*sqrt(35)/35, sqrt(35)/35]
+        >>> sum(i**2 for i in _)
+        1
+        """
+        p1, p2 = self.points
+        return p1.direction_cosine(p2)
+
+
+class Line3D(LinearEntity3D, Line):
+    """An infinite 3D line in space.
+
+    A line is declared with two distinct points or a point and direction_ratio
+    as defined using keyword `direction_ratio`.
+
+    Parameters
+    ==========
+
+    p1 : Point3D
+    pt : Point3D
+    direction_ratio : list
+
+    See Also
+    ========
+
+    sympy.geometry.point.Point3D
+    sympy.geometry.line.Line
+    sympy.geometry.line.Line2D
+
+    Examples
+    ========
+
+    >>> from sympy import Line3D, Point3D
+    >>> L = Line3D(Point3D(2, 3, 4), Point3D(3, 5, 1))
+    >>> L
+    Line3D(Point3D(2, 3, 4), Point3D(3, 5, 1))
+    >>> L.points
+    (Point3D(2, 3, 4), Point3D(3, 5, 1))
+    """
+    def __new__(cls, p1, pt=None, direction_ratio=(), **kwargs):
+        if isinstance(p1, LinearEntity3D):
+            if pt is not None:
+                raise ValueError('if p1 is a LinearEntity, pt must be None.')
+            p1, pt = p1.args
+        else:
+            p1 = Point(p1, dim=3)
+        if pt is not None and len(direction_ratio) == 0:
+            pt = Point(pt, dim=3)
+        elif len(direction_ratio) == 3 and pt is None:
+            pt = Point3D(p1.x + direction_ratio[0], p1.y + direction_ratio[1],
+                         p1.z + direction_ratio[2])
+        else:
+            raise ValueError('A 2nd Point or keyword "direction_ratio" must '
+                             'be used.')
+
+        return LinearEntity3D.__new__(cls, p1, pt, **kwargs)
+
+    def equation(self, x='x', y='y', z='z'):
+        """Return the equations that define the line in 3D.
+
+        Parameters
+        ==========
+
+        x : str, optional
+            The name to use for the x-axis, default value is 'x'.
+        y : str, optional
+            The name to use for the y-axis, default value is 'y'.
+        z : str, optional
+            The name to use for the z-axis, default value is 'z'.
+
+        Returns
+        =======
+
+        equation : Tuple of simultaneous equations
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D, Line3D, solve
+        >>> from sympy.abc import x, y, z
+        >>> p1, p2 = Point3D(1, 0, 0), Point3D(5, 3, 0)
+        >>> l1 = Line3D(p1, p2)
+        >>> eq = l1.equation(x, y, z); eq
+        (-3*x + 4*y + 3, z)
+        >>> solve(eq.subs(z, 0), (x, y, z))
+        {x: 4*y/3 + 1}
+        """
+        x, y, z, k = [_symbol(i, real=True) for i in (x, y, z, 'k')]
+        p1, p2 = self.points
+        d1, d2, d3 = p1.direction_ratio(p2)
+        x1, y1, z1 = p1
+        eqs = [-d1*k + x - x1, -d2*k + y - y1, -d3*k + z - z1]
+        # eliminate k from equations by solving first eq with k for k
+        for i, e in enumerate(eqs):
+            if e.has(k):
+                kk = solve(e, k)[0]
+                eqs.pop(i)
+                break
+        return Tuple(*[i.subs(k, kk).as_numer_denom()[0] for i in eqs])
+
+    def distance(self, other):
+        """
+        Finds the shortest distance between a line and another object.
+
+        Parameters
+        ==========
+
+        Point3D, Line3D, Plane, tuple, list
+
+        Returns
+        =======
+
+        distance
+
+        Notes
+        =====
+
+        This method accepts only 3D entities as it's parameter
+
+        Tuples and lists are converted to Point3D and therefore must be of
+        length 3, 2 or 1.
+
+        NotImplementedError is raised if `other` is not an instance of one
+        of the specified classes: Point3D, Line3D, or Plane.
+
+        Examples
+        ========
+
+        >>> from sympy.geometry import Line3D
+        >>> l1 = Line3D((0, 0, 0), (0, 0, 1))
+        >>> l2 = Line3D((0, 1, 0), (1, 1, 1))
+        >>> l1.distance(l2)
+        1
+
+        The computed distance may be symbolic, too:
+
+        >>> from sympy.abc import x, y
+        >>> l1 = Line3D((0, 0, 0), (0, 0, 1))
+        >>> l2 = Line3D((0, x, 0), (y, x, 1))
+        >>> l1.distance(l2)
+        Abs(x*y)/Abs(sqrt(y**2))
+
+        """
+
+        from .plane import Plane  # Avoid circular import
+
+        if isinstance(other, (tuple, list)):
+            try:
+                other = Point3D(other)
+            except ValueError:
+                pass
+
+        if isinstance(other, Point3D):
+            return super().distance(other)
+
+        if isinstance(other, Line3D):
+            if self == other:
+                return S.Zero
+            if self.is_parallel(other):
+                return super().distance(other.p1)
+
+            # Skew lines
+            self_direction = Matrix(self.direction_ratio)
+            other_direction = Matrix(other.direction_ratio)
+            normal = self_direction.cross(other_direction)
+            plane_through_self = Plane(p1=self.p1, normal_vector=normal)
+            return other.p1.distance(plane_through_self)
+
+        if isinstance(other, Plane):
+            return other.distance(self)
+
+        msg = f"{other} has type {type(other)}, which is unsupported"
+        raise NotImplementedError(msg)
+
+
+class Ray3D(LinearEntity3D, Ray):
+    """
+    A Ray is a semi-line in the space with a source point and a direction.
+
+    Parameters
+    ==========
+
+    p1 : Point3D
+        The source of the Ray
+    p2 : Point or a direction vector
+    direction_ratio: Determines the direction in which the Ray propagates.
+
+
+    Attributes
+    ==========
+
+    source
+    xdirection
+    ydirection
+    zdirection
+
+    See Also
+    ========
+
+    sympy.geometry.point.Point3D, Line3D
+
+
+    Examples
+    ========
+
+    >>> from sympy import Point3D, Ray3D
+    >>> r = Ray3D(Point3D(2, 3, 4), Point3D(3, 5, 0))
+    >>> r
+    Ray3D(Point3D(2, 3, 4), Point3D(3, 5, 0))
+    >>> r.points
+    (Point3D(2, 3, 4), Point3D(3, 5, 0))
+    >>> r.source
+    Point3D(2, 3, 4)
+    >>> r.xdirection
+    oo
+    >>> r.ydirection
+    oo
+    >>> r.direction_ratio
+    [1, 2, -4]
+
+    """
+    def __new__(cls, p1, pt=None, direction_ratio=(), **kwargs):
+        if isinstance(p1, LinearEntity3D):
+            if pt is not None:
+                raise ValueError('If p1 is a LinearEntity, pt must be None')
+            p1, pt = p1.args
+        else:
+            p1 = Point(p1, dim=3)
+        if pt is not None and len(direction_ratio) == 0:
+            pt = Point(pt, dim=3)
+        elif len(direction_ratio) == 3 and pt is None:
+            pt = Point3D(p1.x + direction_ratio[0], p1.y + direction_ratio[1],
+                         p1.z + direction_ratio[2])
+        else:
+            raise ValueError(filldedent('''
+                A 2nd Point or keyword "direction_ratio" must be used.
+            '''))
+
+        return LinearEntity3D.__new__(cls, p1, pt, **kwargs)
+
+    @property
+    def xdirection(self):
+        """The x direction of the ray.
+
+        Positive infinity if the ray points in the positive x direction,
+        negative infinity if the ray points in the negative x direction,
+        or 0 if the ray is vertical.
+
+        See Also
+        ========
+
+        ydirection
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D, Ray3D
+        >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, -1, 0)
+        >>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3)
+        >>> r1.xdirection
+        oo
+        >>> r2.xdirection
+        0
+
+        """
+        if self.p1.x < self.p2.x:
+            return S.Infinity
+        elif self.p1.x == self.p2.x:
+            return S.Zero
+        else:
+            return S.NegativeInfinity
+
+    @property
+    def ydirection(self):
+        """The y direction of the ray.
+
+        Positive infinity if the ray points in the positive y direction,
+        negative infinity if the ray points in the negative y direction,
+        or 0 if the ray is horizontal.
+
+        See Also
+        ========
+
+        xdirection
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D, Ray3D
+        >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(-1, -1, -1), Point3D(-1, 0, 0)
+        >>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3)
+        >>> r1.ydirection
+        -oo
+        >>> r2.ydirection
+        0
+
+        """
+        if self.p1.y < self.p2.y:
+            return S.Infinity
+        elif self.p1.y == self.p2.y:
+            return S.Zero
+        else:
+            return S.NegativeInfinity
+
+    @property
+    def zdirection(self):
+        """The z direction of the ray.
+
+        Positive infinity if the ray points in the positive z direction,
+        negative infinity if the ray points in the negative z direction,
+        or 0 if the ray is horizontal.
+
+        See Also
+        ========
+
+        xdirection
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D, Ray3D
+        >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(-1, -1, -1), Point3D(-1, 0, 0)
+        >>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3)
+        >>> r1.ydirection
+        -oo
+        >>> r2.ydirection
+        0
+        >>> r2.zdirection
+        0
+
+        """
+        if self.p1.z < self.p2.z:
+            return S.Infinity
+        elif self.p1.z == self.p2.z:
+            return S.Zero
+        else:
+            return S.NegativeInfinity
+
+
+class Segment3D(LinearEntity3D, Segment):
+    """A line segment in a 3D space.
+
+    Parameters
+    ==========
+
+    p1 : Point3D
+    p2 : Point3D
+
+    Attributes
+    ==========
+
+    length : number or SymPy expression
+    midpoint : Point3D
+
+    See Also
+    ========
+
+    sympy.geometry.point.Point3D, Line3D
+
+    Examples
+    ========
+
+    >>> from sympy import Point3D, Segment3D
+    >>> Segment3D((1, 0, 0), (1, 1, 1)) # tuples are interpreted as pts
+    Segment3D(Point3D(1, 0, 0), Point3D(1, 1, 1))
+    >>> s = Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7)); s
+    Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7))
+    >>> s.points
+    (Point3D(4, 3, 9), Point3D(1, 1, 7))
+    >>> s.length
+    sqrt(17)
+    >>> s.midpoint
+    Point3D(5/2, 2, 8)
+
+    """
+    def __new__(cls, p1, p2, **kwargs):
+        p1 = Point(p1, dim=3)
+        p2 = Point(p2, dim=3)
+
+        if p1 == p2:
+            return p1
+
+        return LinearEntity3D.__new__(cls, p1, p2, **kwargs)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/parabola.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/parabola.py
new file mode 100644
index 0000000000000000000000000000000000000000..183c593785bb610e6f451a0c87abb2aa34d22494
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/parabola.py
@@ -0,0 +1,422 @@
+"""Parabolic geometrical entity.
+
+Contains
+* Parabola
+
+"""
+
+from sympy.core import S
+from sympy.core.sorting import ordered
+from sympy.core.symbol import _symbol, symbols
+from sympy.geometry.entity import GeometryEntity, GeometrySet
+from sympy.geometry.point import Point, Point2D
+from sympy.geometry.line import Line, Line2D, Ray2D, Segment2D, LinearEntity3D
+from sympy.geometry.ellipse import Ellipse
+from sympy.functions import sign
+from sympy.simplify.simplify import simplify
+from sympy.solvers.solvers import solve
+
+
+class Parabola(GeometrySet):
+    """A parabolic GeometryEntity.
+
+    A parabola is declared with a point, that is called 'focus', and
+    a line, that is called 'directrix'.
+    Only vertical or horizontal parabolas are currently supported.
+
+    Parameters
+    ==========
+
+    focus : Point
+        Default value is Point(0, 0)
+    directrix : Line
+
+    Attributes
+    ==========
+
+    focus
+    directrix
+    axis of symmetry
+    focal length
+    p parameter
+    vertex
+    eccentricity
+
+    Raises
+    ======
+    ValueError
+        When `focus` is not a two dimensional point.
+        When `focus` is a point of directrix.
+    NotImplementedError
+        When `directrix` is neither horizontal nor vertical.
+
+    Examples
+    ========
+
+    >>> from sympy import Parabola, Point, Line
+    >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7,8)))
+    >>> p1.focus
+    Point2D(0, 0)
+    >>> p1.directrix
+    Line2D(Point2D(5, 8), Point2D(7, 8))
+
+    """
+
+    def __new__(cls, focus=None, directrix=None, **kwargs):
+
+        if focus:
+            focus = Point(focus, dim=2)
+        else:
+            focus = Point(0, 0)
+
+        directrix = Line(directrix)
+
+        if directrix.contains(focus):
+            raise ValueError('The focus must not be a point of directrix')
+
+        return GeometryEntity.__new__(cls, focus, directrix, **kwargs)
+
+    @property
+    def ambient_dimension(self):
+        """Returns the ambient dimension of parabola.
+
+        Returns
+        =======
+
+        ambient_dimension : integer
+
+        Examples
+        ========
+
+        >>> from sympy import Parabola, Point, Line
+        >>> f1 = Point(0, 0)
+        >>> p1 = Parabola(f1, Line(Point(5, 8), Point(7, 8)))
+        >>> p1.ambient_dimension
+        2
+
+        """
+        return 2
+
+    @property
+    def axis_of_symmetry(self):
+        """Return the axis of symmetry of the parabola: a line
+        perpendicular to the directrix passing through the focus.
+
+        Returns
+        =======
+
+        axis_of_symmetry : Line
+
+        See Also
+        ========
+
+        sympy.geometry.line.Line
+
+        Examples
+        ========
+
+        >>> from sympy import Parabola, Point, Line
+        >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
+        >>> p1.axis_of_symmetry
+        Line2D(Point2D(0, 0), Point2D(0, 1))
+
+        """
+        return self.directrix.perpendicular_line(self.focus)
+
+    @property
+    def directrix(self):
+        """The directrix of the parabola.
+
+        Returns
+        =======
+
+        directrix : Line
+
+        See Also
+        ========
+
+        sympy.geometry.line.Line
+
+        Examples
+        ========
+
+        >>> from sympy import Parabola, Point, Line
+        >>> l1 = Line(Point(5, 8), Point(7, 8))
+        >>> p1 = Parabola(Point(0, 0), l1)
+        >>> p1.directrix
+        Line2D(Point2D(5, 8), Point2D(7, 8))
+
+        """
+        return self.args[1]
+
+    @property
+    def eccentricity(self):
+        """The eccentricity of the parabola.
+
+        Returns
+        =======
+
+        eccentricity : number
+
+        A parabola may also be characterized as a conic section with an
+        eccentricity of 1. As a consequence of this, all parabolas are
+        similar, meaning that while they can be different sizes,
+        they are all the same shape.
+
+        See Also
+        ========
+
+        https://en.wikipedia.org/wiki/Parabola
+
+
+        Examples
+        ========
+
+        >>> from sympy import Parabola, Point, Line
+        >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
+        >>> p1.eccentricity
+        1
+
+        Notes
+        -----
+        The eccentricity for every Parabola is 1 by definition.
+
+        """
+        return S.One
+
+    def equation(self, x='x', y='y'):
+        """The equation of the parabola.
+
+        Parameters
+        ==========
+        x : str, optional
+            Label for the x-axis. Default value is 'x'.
+        y : str, optional
+            Label for the y-axis. Default value is 'y'.
+
+        Returns
+        =======
+        equation : SymPy expression
+
+        Examples
+        ========
+
+        >>> from sympy import Parabola, Point, Line
+        >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
+        >>> p1.equation()
+        -x**2 - 16*y + 64
+        >>> p1.equation('f')
+        -f**2 - 16*y + 64
+        >>> p1.equation(y='z')
+        -x**2 - 16*z + 64
+
+        """
+        x = _symbol(x, real=True)
+        y = _symbol(y, real=True)
+
+        m = self.directrix.slope
+        if m is S.Infinity:
+            t1 = 4 * (self.p_parameter) * (x - self.vertex.x)
+            t2 = (y - self.vertex.y)**2
+        elif m == 0:
+            t1 = 4 * (self.p_parameter) * (y - self.vertex.y)
+            t2 = (x - self.vertex.x)**2
+        else:
+            a, b = self.focus
+            c, d = self.directrix.coefficients[:2]
+            t1 = (x - a)**2 + (y - b)**2
+            t2 = self.directrix.equation(x, y)**2/(c**2 + d**2)
+        return t1 - t2
+
+    @property
+    def focal_length(self):
+        """The focal length of the parabola.
+
+        Returns
+        =======
+
+        focal_lenght : number or symbolic expression
+
+        Notes
+        =====
+
+        The distance between the vertex and the focus
+        (or the vertex and directrix), measured along the axis
+        of symmetry, is the "focal length".
+
+        See Also
+        ========
+
+        https://en.wikipedia.org/wiki/Parabola
+
+        Examples
+        ========
+
+        >>> from sympy import Parabola, Point, Line
+        >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
+        >>> p1.focal_length
+        4
+
+        """
+        distance = self.directrix.distance(self.focus)
+        focal_length = distance/2
+
+        return focal_length
+
+    @property
+    def focus(self):
+        """The focus of the parabola.
+
+        Returns
+        =======
+
+        focus : Point
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point
+
+        Examples
+        ========
+
+        >>> from sympy import Parabola, Point, Line
+        >>> f1 = Point(0, 0)
+        >>> p1 = Parabola(f1, Line(Point(5, 8), Point(7, 8)))
+        >>> p1.focus
+        Point2D(0, 0)
+
+        """
+        return self.args[0]
+
+    def intersection(self, o):
+        """The intersection of the parabola and another geometrical entity `o`.
+
+        Parameters
+        ==========
+
+        o : GeometryEntity, LinearEntity
+
+        Returns
+        =======
+
+        intersection : list of GeometryEntity objects
+
+        Examples
+        ========
+
+        >>> from sympy import Parabola, Point, Ellipse, Line, Segment
+        >>> p1 = Point(0,0)
+        >>> l1 = Line(Point(1, -2), Point(-1,-2))
+        >>> parabola1 = Parabola(p1, l1)
+        >>> parabola1.intersection(Ellipse(Point(0, 0), 2, 5))
+        [Point2D(-2, 0), Point2D(2, 0)]
+        >>> parabola1.intersection(Line(Point(-7, 3), Point(12, 3)))
+        [Point2D(-4, 3), Point2D(4, 3)]
+        >>> parabola1.intersection(Segment((-12, -65), (14, -68)))
+        []
+
+        """
+        x, y = symbols('x y', real=True)
+        parabola_eq = self.equation()
+        if isinstance(o, Parabola):
+            if o in self:
+                return [o]
+            else:
+                return list(ordered([Point(i) for i in solve(
+                    [parabola_eq, o.equation()], [x, y], set=True)[1]]))
+        elif isinstance(o, Point2D):
+            if simplify(parabola_eq.subs([(x, o._args[0]), (y, o._args[1])])) == 0:
+                return [o]
+            else:
+                return []
+        elif isinstance(o, (Segment2D, Ray2D)):
+            result = solve([parabola_eq,
+                Line2D(o.points[0], o.points[1]).equation()],
+                [x, y], set=True)[1]
+            return list(ordered([Point2D(i) for i in result if i in o]))
+        elif isinstance(o, (Line2D, Ellipse)):
+            return list(ordered([Point2D(i) for i in solve(
+                [parabola_eq, o.equation()], [x, y], set=True)[1]]))
+        elif isinstance(o, LinearEntity3D):
+            raise TypeError('Entity must be two dimensional, not three dimensional')
+        else:
+            raise TypeError('Wrong type of argument were put')
+
+    @property
+    def p_parameter(self):
+        """P is a parameter of parabola.
+
+        Returns
+        =======
+
+        p : number or symbolic expression
+
+        Notes
+        =====
+
+        The absolute value of p is the focal length. The sign on p tells
+        which way the parabola faces. Vertical parabolas that open up
+        and horizontal that open right, give a positive value for p.
+        Vertical parabolas that open down and horizontal that open left,
+        give a negative value for p.
+
+
+        See Also
+        ========
+
+        https://www.sparknotes.com/math/precalc/conicsections/section2/
+
+        Examples
+        ========
+
+        >>> from sympy import Parabola, Point, Line
+        >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
+        >>> p1.p_parameter
+        -4
+
+        """
+        m = self.directrix.slope
+        if m is S.Infinity:
+            x = self.directrix.coefficients[2]
+            p = sign(self.focus.args[0] + x)
+        elif m == 0:
+            y = self.directrix.coefficients[2]
+            p = sign(self.focus.args[1] + y)
+        else:
+            d = self.directrix.projection(self.focus)
+            p = sign(self.focus.x - d.x)
+        return p * self.focal_length
+
+    @property
+    def vertex(self):
+        """The vertex of the parabola.
+
+        Returns
+        =======
+
+        vertex : Point
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point
+
+        Examples
+        ========
+
+        >>> from sympy import Parabola, Point, Line
+        >>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
+        >>> p1.vertex
+        Point2D(0, 4)
+
+        """
+        focus = self.focus
+        m = self.directrix.slope
+        if m is S.Infinity:
+            vertex = Point(focus.args[0] - self.p_parameter, focus.args[1])
+        elif m == 0:
+            vertex = Point(focus.args[0], focus.args[1] - self.p_parameter)
+        else:
+            vertex = self.axis_of_symmetry.intersection(self)[0]
+        return vertex
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/plane.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/plane.py
new file mode 100644
index 0000000000000000000000000000000000000000..509dc4be5dc41c5df7c33561fdbe5bb0b6620352
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/plane.py
@@ -0,0 +1,878 @@
+"""Geometrical Planes.
+
+Contains
+========
+Plane
+
+"""
+
+from sympy.core import Dummy, Rational, S, Symbol
+from sympy.core.symbol import _symbol
+from sympy.functions.elementary.trigonometric import cos, sin, acos, asin, sqrt
+from .entity import GeometryEntity
+from .line import (Line, Ray, Segment, Line3D, LinearEntity, LinearEntity3D,
+                   Ray3D, Segment3D)
+from .point import Point, Point3D
+from sympy.matrices import Matrix
+from sympy.polys.polytools import cancel
+from sympy.solvers import solve, linsolve
+from sympy.utilities.iterables import uniq, is_sequence
+from sympy.utilities.misc import filldedent, func_name, Undecidable
+
+from mpmath.libmp.libmpf import prec_to_dps
+
+import random
+
+
+x, y, z, t = [Dummy('plane_dummy') for i in range(4)]
+
+
+class Plane(GeometryEntity):
+    """
+    A plane is a flat, two-dimensional surface. A plane is the two-dimensional
+    analogue of a point (zero-dimensions), a line (one-dimension) and a solid
+    (three-dimensions). A plane can generally be constructed by two types of
+    inputs. They are:
+    - three non-collinear points
+    - a point and the plane's normal vector
+
+    Attributes
+    ==========
+
+    p1
+    normal_vector
+
+    Examples
+    ========
+
+    >>> from sympy import Plane, Point3D
+    >>> Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2))
+    Plane(Point3D(1, 1, 1), (-1, 2, -1))
+    >>> Plane((1, 1, 1), (2, 3, 4), (2, 2, 2))
+    Plane(Point3D(1, 1, 1), (-1, 2, -1))
+    >>> Plane(Point3D(1, 1, 1), normal_vector=(1,4,7))
+    Plane(Point3D(1, 1, 1), (1, 4, 7))
+
+    """
+    def __new__(cls, p1, a=None, b=None, **kwargs):
+        p1 = Point3D(p1, dim=3)
+        if a and b:
+            p2 = Point(a, dim=3)
+            p3 = Point(b, dim=3)
+            if Point3D.are_collinear(p1, p2, p3):
+                raise ValueError('Enter three non-collinear points')
+            a = p1.direction_ratio(p2)
+            b = p1.direction_ratio(p3)
+            normal_vector = tuple(Matrix(a).cross(Matrix(b)))
+        else:
+            a = kwargs.pop('normal_vector', a)
+            evaluate = kwargs.get('evaluate', True)
+            if is_sequence(a) and len(a) == 3:
+                normal_vector = Point3D(a).args if evaluate else a
+            else:
+                raise ValueError(filldedent('''
+                    Either provide 3 3D points or a point with a
+                    normal vector expressed as a sequence of length 3'''))
+            if all(coord.is_zero for coord in normal_vector):
+                raise ValueError('Normal vector cannot be zero vector')
+        return GeometryEntity.__new__(cls, p1, normal_vector, **kwargs)
+
+    def __contains__(self, o):
+        k = self.equation(x, y, z)
+        if isinstance(o, (LinearEntity, LinearEntity3D)):
+            d = Point3D(o.arbitrary_point(t))
+            e = k.subs([(x, d.x), (y, d.y), (z, d.z)])
+            return e.equals(0)
+        try:
+            o = Point(o, dim=3, strict=True)
+            d = k.xreplace(dict(zip((x, y, z), o.args)))
+            return d.equals(0)
+        except TypeError:
+            return False
+
+    def _eval_evalf(self, prec=15, **options):
+        pt, tup = self.args
+        dps = prec_to_dps(prec)
+        pt = pt.evalf(n=dps, **options)
+        tup = tuple([i.evalf(n=dps, **options) for i in tup])
+        return self.func(pt, normal_vector=tup, evaluate=False)
+
+    def angle_between(self, o):
+        """Angle between the plane and other geometric entity.
+
+        Parameters
+        ==========
+
+        LinearEntity3D, Plane.
+
+        Returns
+        =======
+
+        angle : angle in radians
+
+        Notes
+        =====
+
+        This method accepts only 3D entities as it's parameter, but if you want
+        to calculate the angle between a 2D entity and a plane you should
+        first convert to a 3D entity by projecting onto a desired plane and
+        then proceed to calculate the angle.
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D, Line3D, Plane
+        >>> a = Plane(Point3D(1, 2, 2), normal_vector=(1, 2, 3))
+        >>> b = Line3D(Point3D(1, 3, 4), Point3D(2, 2, 2))
+        >>> a.angle_between(b)
+        -asin(sqrt(21)/6)
+
+        """
+        if isinstance(o, LinearEntity3D):
+            a = Matrix(self.normal_vector)
+            b = Matrix(o.direction_ratio)
+            c = a.dot(b)
+            d = sqrt(sum(i**2 for i in self.normal_vector))
+            e = sqrt(sum(i**2 for i in o.direction_ratio))
+            return asin(c/(d*e))
+        if isinstance(o, Plane):
+            a = Matrix(self.normal_vector)
+            b = Matrix(o.normal_vector)
+            c = a.dot(b)
+            d = sqrt(sum(i**2 for i in self.normal_vector))
+            e = sqrt(sum(i**2 for i in o.normal_vector))
+            return acos(c/(d*e))
+
+
+    def arbitrary_point(self, u=None, v=None):
+        """ Returns an arbitrary point on the Plane. If given two
+        parameters, the point ranges over the entire plane. If given 1
+        or no parameters, returns a point with one parameter which,
+        when varying from 0 to 2*pi, moves the point in a circle of
+        radius 1 about p1 of the Plane.
+
+        Examples
+        ========
+
+        >>> from sympy import Plane, Ray
+        >>> from sympy.abc import u, v, t, r
+        >>> p = Plane((1, 1, 1), normal_vector=(1, 0, 0))
+        >>> p.arbitrary_point(u, v)
+        Point3D(1, u + 1, v + 1)
+        >>> p.arbitrary_point(t)
+        Point3D(1, cos(t) + 1, sin(t) + 1)
+
+        While arbitrary values of u and v can move the point anywhere in
+        the plane, the single-parameter point can be used to construct a
+        ray whose arbitrary point can be located at angle t and radius
+        r from p.p1:
+
+        >>> Ray(p.p1, _).arbitrary_point(r)
+        Point3D(1, r*cos(t) + 1, r*sin(t) + 1)
+
+        Returns
+        =======
+
+        Point3D
+
+        """
+        circle = v is None
+        if circle:
+            u = _symbol(u or 't', real=True)
+        else:
+            u = _symbol(u or 'u', real=True)
+            v = _symbol(v or 'v', real=True)
+        x, y, z = self.normal_vector
+        a, b, c = self.p1.args
+        # x1, y1, z1 is a nonzero vector parallel to the plane
+        if x.is_zero and y.is_zero:
+            x1, y1, z1 = S.One, S.Zero, S.Zero
+        else:
+            x1, y1, z1 = -y, x, S.Zero
+        # x2, y2, z2 is also parallel to the plane, and orthogonal to x1, y1, z1
+        x2, y2, z2 = tuple(Matrix((x, y, z)).cross(Matrix((x1, y1, z1))))
+        if circle:
+            x1, y1, z1 = (w/sqrt(x1**2 + y1**2 + z1**2) for w in (x1, y1, z1))
+            x2, y2, z2 = (w/sqrt(x2**2 + y2**2 + z2**2) for w in (x2, y2, z2))
+            p = Point3D(a + x1*cos(u) + x2*sin(u), \
+                        b + y1*cos(u) + y2*sin(u), \
+                        c + z1*cos(u) + z2*sin(u))
+        else:
+            p = Point3D(a + x1*u + x2*v, b + y1*u + y2*v, c + z1*u + z2*v)
+        return p
+
+
+    @staticmethod
+    def are_concurrent(*planes):
+        """Is a sequence of Planes concurrent?
+
+        Two or more Planes are concurrent if their intersections
+        are a common line.
+
+        Parameters
+        ==========
+
+        planes: list
+
+        Returns
+        =======
+
+        Boolean
+
+        Examples
+        ========
+
+        >>> from sympy import Plane, Point3D
+        >>> a = Plane(Point3D(5, 0, 0), normal_vector=(1, -1, 1))
+        >>> b = Plane(Point3D(0, -2, 0), normal_vector=(3, 1, 1))
+        >>> c = Plane(Point3D(0, -1, 0), normal_vector=(5, -1, 9))
+        >>> Plane.are_concurrent(a, b)
+        True
+        >>> Plane.are_concurrent(a, b, c)
+        False
+
+        """
+        planes = list(uniq(planes))
+        for i in planes:
+            if not isinstance(i, Plane):
+                raise ValueError('All objects should be Planes but got %s' % i.func)
+        if len(planes) < 2:
+            return False
+        planes = list(planes)
+        first = planes.pop(0)
+        sol = first.intersection(planes[0])
+        if sol == []:
+            return False
+        else:
+            line = sol[0]
+            for i in planes[1:]:
+                l = first.intersection(i)
+                if not l or l[0] not in line:
+                    return False
+            return True
+
+
+    def distance(self, o):
+        """Distance between the plane and another geometric entity.
+
+        Parameters
+        ==========
+
+        Point3D, LinearEntity3D, Plane.
+
+        Returns
+        =======
+
+        distance
+
+        Notes
+        =====
+
+        This method accepts only 3D entities as it's parameter, but if you want
+        to calculate the distance between a 2D entity and a plane you should
+        first convert to a 3D entity by projecting onto a desired plane and
+        then proceed to calculate the distance.
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D, Line3D, Plane
+        >>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 1, 1))
+        >>> b = Point3D(1, 2, 3)
+        >>> a.distance(b)
+        sqrt(3)
+        >>> c = Line3D(Point3D(2, 3, 1), Point3D(1, 2, 2))
+        >>> a.distance(c)
+        0
+
+        """
+        if self.intersection(o) != []:
+            return S.Zero
+
+        if isinstance(o, (Segment3D, Ray3D)):
+            a, b = o.p1, o.p2
+            pi, = self.intersection(Line3D(a, b))
+            if pi in o:
+                return self.distance(pi)
+            elif a in Segment3D(pi, b):
+                return self.distance(a)
+            else:
+                assert isinstance(o, Segment3D) is True
+                return self.distance(b)
+
+        # following code handles `Point3D`, `LinearEntity3D`, `Plane`
+        a = o if isinstance(o, Point3D) else o.p1
+        n = Point3D(self.normal_vector).unit
+        d = (a - self.p1).dot(n)
+        return abs(d)
+
+
+    def equals(self, o):
+        """
+        Returns True if self and o are the same mathematical entities.
+
+        Examples
+        ========
+
+        >>> from sympy import Plane, Point3D
+        >>> a = Plane(Point3D(1, 2, 3), normal_vector=(1, 1, 1))
+        >>> b = Plane(Point3D(1, 2, 3), normal_vector=(2, 2, 2))
+        >>> c = Plane(Point3D(1, 2, 3), normal_vector=(-1, 4, 6))
+        >>> a.equals(a)
+        True
+        >>> a.equals(b)
+        True
+        >>> a.equals(c)
+        False
+        """
+        if isinstance(o, Plane):
+            a = self.equation()
+            b = o.equation()
+            return cancel(a/b).is_constant()
+        else:
+            return False
+
+
+    def equation(self, x=None, y=None, z=None):
+        """The equation of the Plane.
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D, Plane
+        >>> a = Plane(Point3D(1, 1, 2), Point3D(2, 4, 7), Point3D(3, 5, 1))
+        >>> a.equation()
+        -23*x + 11*y - 2*z + 16
+        >>> a = Plane(Point3D(1, 4, 2), normal_vector=(6, 6, 6))
+        >>> a.equation()
+        6*x + 6*y + 6*z - 42
+
+        """
+        x, y, z = [i if i else Symbol(j, real=True) for i, j in zip((x, y, z), 'xyz')]
+        a = Point3D(x, y, z)
+        b = self.p1.direction_ratio(a)
+        c = self.normal_vector
+        return (sum(i*j for i, j in zip(b, c)))
+
+
+    def intersection(self, o):
+        """ The intersection with other geometrical entity.
+
+        Parameters
+        ==========
+
+        Point, Point3D, LinearEntity, LinearEntity3D, Plane
+
+        Returns
+        =======
+
+        List
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D, Line3D, Plane
+        >>> a = Plane(Point3D(1, 2, 3), normal_vector=(1, 1, 1))
+        >>> b = Point3D(1, 2, 3)
+        >>> a.intersection(b)
+        [Point3D(1, 2, 3)]
+        >>> c = Line3D(Point3D(1, 4, 7), Point3D(2, 2, 2))
+        >>> a.intersection(c)
+        [Point3D(2, 2, 2)]
+        >>> d = Plane(Point3D(6, 0, 0), normal_vector=(2, -5, 3))
+        >>> e = Plane(Point3D(2, 0, 0), normal_vector=(3, 4, -3))
+        >>> d.intersection(e)
+        [Line3D(Point3D(78/23, -24/23, 0), Point3D(147/23, 321/23, 23))]
+
+        """
+        if not isinstance(o, GeometryEntity):
+            o = Point(o, dim=3)
+        if isinstance(o, Point):
+            if o in self:
+                return [o]
+            else:
+                return []
+        if isinstance(o, (LinearEntity, LinearEntity3D)):
+            # recast to 3D
+            p1, p2 = o.p1, o.p2
+            if isinstance(o, Segment):
+                o = Segment3D(p1, p2)
+            elif isinstance(o, Ray):
+                o = Ray3D(p1, p2)
+            elif isinstance(o, Line):
+                o = Line3D(p1, p2)
+            else:
+                raise ValueError('unhandled linear entity: %s' % o.func)
+            if o in self:
+                return [o]
+            else:
+                a = Point3D(o.arbitrary_point(t))
+                p1, n = self.p1, Point3D(self.normal_vector)
+
+                # TODO: Replace solve with solveset, when this line is tested
+                c = solve((a - p1).dot(n), t)
+                if not c:
+                    return []
+                else:
+                    c = [i for i in c if i.is_real is not False]
+                    if len(c) > 1:
+                        c = [i for i in c if i.is_real]
+                    if len(c) != 1:
+                        raise Undecidable("not sure which point is real")
+                    p = a.subs(t, c[0])
+                    if p not in o:
+                        return []  # e.g. a segment might not intersect a plane
+                    return [p]
+        if isinstance(o, Plane):
+            if self.equals(o):
+                return [self]
+            if self.is_parallel(o):
+                return []
+            else:
+                x, y, z = map(Dummy, 'xyz')
+                a, b = Matrix([self.normal_vector]), Matrix([o.normal_vector])
+                c = list(a.cross(b))
+                d = self.equation(x, y, z)
+                e = o.equation(x, y, z)
+                result = list(linsolve([d, e], x, y, z))[0]
+                for i in (x, y, z): result = result.subs(i, 0)
+                return [Line3D(Point3D(result), direction_ratio=c)]
+
+
+    def is_coplanar(self, o):
+        """ Returns True if `o` is coplanar with self, else False.
+
+        Examples
+        ========
+
+        >>> from sympy import Plane
+        >>> o = (0, 0, 0)
+        >>> p = Plane(o, (1, 1, 1))
+        >>> p2 = Plane(o, (2, 2, 2))
+        >>> p == p2
+        False
+        >>> p.is_coplanar(p2)
+        True
+        """
+        if isinstance(o, Plane):
+            return not cancel(self.equation(x, y, z)/o.equation(x, y, z)).has(x, y, z)
+        if isinstance(o, Point3D):
+            return o in self
+        elif isinstance(o, LinearEntity3D):
+            return all(i in self for i in self)
+        elif isinstance(o, GeometryEntity):  # XXX should only be handling 2D objects now
+            return all(i == 0 for i in self.normal_vector[:2])
+
+
+    def is_parallel(self, l):
+        """Is the given geometric entity parallel to the plane?
+
+        Parameters
+        ==========
+
+        LinearEntity3D or Plane
+
+        Returns
+        =======
+
+        Boolean
+
+        Examples
+        ========
+
+        >>> from sympy import Plane, Point3D
+        >>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6))
+        >>> b = Plane(Point3D(3,1,3), normal_vector=(4, 8, 12))
+        >>> a.is_parallel(b)
+        True
+
+        """
+        if isinstance(l, LinearEntity3D):
+            a = l.direction_ratio
+            b = self.normal_vector
+            return sum(i*j for i, j in zip(a, b)) == 0
+        if isinstance(l, Plane):
+            a = Matrix(l.normal_vector)
+            b = Matrix(self.normal_vector)
+            return bool(a.cross(b).is_zero_matrix)
+
+
+    def is_perpendicular(self, l):
+        """Is the given geometric entity perpendicualar to the given plane?
+
+        Parameters
+        ==========
+
+        LinearEntity3D or Plane
+
+        Returns
+        =======
+
+        Boolean
+
+        Examples
+        ========
+
+        >>> from sympy import Plane, Point3D
+        >>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6))
+        >>> b = Plane(Point3D(2, 2, 2), normal_vector=(-1, 2, -1))
+        >>> a.is_perpendicular(b)
+        True
+
+        """
+        if isinstance(l, LinearEntity3D):
+            a = Matrix(l.direction_ratio)
+            b = Matrix(self.normal_vector)
+            if a.cross(b).is_zero_matrix:
+                return True
+            else:
+                return False
+        elif isinstance(l, Plane):
+            a = Matrix(l.normal_vector)
+            b = Matrix(self.normal_vector)
+            if a.dot(b) == 0:
+                return True
+            else:
+                return False
+        else:
+            return False
+
+    @property
+    def normal_vector(self):
+        """Normal vector of the given plane.
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D, Plane
+        >>> a = Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2))
+        >>> a.normal_vector
+        (-1, 2, -1)
+        >>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 4, 7))
+        >>> a.normal_vector
+        (1, 4, 7)
+
+        """
+        return self.args[1]
+
+    @property
+    def p1(self):
+        """The only defining point of the plane. Others can be obtained from the
+        arbitrary_point method.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point3D
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D, Plane
+        >>> a = Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2))
+        >>> a.p1
+        Point3D(1, 1, 1)
+
+        """
+        return self.args[0]
+
+    def parallel_plane(self, pt):
+        """
+        Plane parallel to the given plane and passing through the point pt.
+
+        Parameters
+        ==========
+
+        pt: Point3D
+
+        Returns
+        =======
+
+        Plane
+
+        Examples
+        ========
+
+        >>> from sympy import Plane, Point3D
+        >>> a = Plane(Point3D(1, 4, 6), normal_vector=(2, 4, 6))
+        >>> a.parallel_plane(Point3D(2, 3, 5))
+        Plane(Point3D(2, 3, 5), (2, 4, 6))
+
+        """
+        a = self.normal_vector
+        return Plane(pt, normal_vector=a)
+
+    def perpendicular_line(self, pt):
+        """A line perpendicular to the given plane.
+
+        Parameters
+        ==========
+
+        pt: Point3D
+
+        Returns
+        =======
+
+        Line3D
+
+        Examples
+        ========
+
+        >>> from sympy import Plane, Point3D
+        >>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6))
+        >>> a.perpendicular_line(Point3D(9, 8, 7))
+        Line3D(Point3D(9, 8, 7), Point3D(11, 12, 13))
+
+        """
+        a = self.normal_vector
+        return Line3D(pt, direction_ratio=a)
+
+    def perpendicular_plane(self, *pts):
+        """
+        Return a perpendicular passing through the given points. If the
+        direction ratio between the points is the same as the Plane's normal
+        vector then, to select from the infinite number of possible planes,
+        a third point will be chosen on the z-axis (or the y-axis
+        if the normal vector is already parallel to the z-axis). If less than
+        two points are given they will be supplied as follows: if no point is
+        given then pt1 will be self.p1; if a second point is not given it will
+        be a point through pt1 on a line parallel to the z-axis (if the normal
+        is not already the z-axis, otherwise on the line parallel to the
+        y-axis).
+
+        Parameters
+        ==========
+
+        pts: 0, 1 or 2 Point3D
+
+        Returns
+        =======
+
+        Plane
+
+        Examples
+        ========
+
+        >>> from sympy import Plane, Point3D
+        >>> a, b = Point3D(0, 0, 0), Point3D(0, 1, 0)
+        >>> Z = (0, 0, 1)
+        >>> p = Plane(a, normal_vector=Z)
+        >>> p.perpendicular_plane(a, b)
+        Plane(Point3D(0, 0, 0), (1, 0, 0))
+        """
+        if len(pts) > 2:
+            raise ValueError('No more than 2 pts should be provided.')
+
+        pts = list(pts)
+        if len(pts) == 0:
+            pts.append(self.p1)
+        if len(pts) == 1:
+            x, y, z = self.normal_vector
+            if x == y == 0:
+                dir = (0, 1, 0)
+            else:
+                dir = (0, 0, 1)
+            pts.append(pts[0] + Point3D(*dir))
+
+        p1, p2 = [Point(i, dim=3) for i in pts]
+        l = Line3D(p1, p2)
+        n = Line3D(p1, direction_ratio=self.normal_vector)
+        if l in n:  # XXX should an error be raised instead?
+            # there are infinitely many perpendicular planes;
+            x, y, z = self.normal_vector
+            if x == y == 0:
+                # the z axis is the normal so pick a pt on the y-axis
+                p3 = Point3D(0, 1, 0)  # case 1
+            else:
+                # else pick a pt on the z axis
+                p3 = Point3D(0, 0, 1)  # case 2
+            # in case that point is already given, move it a bit
+            if p3 in l:
+                p3 *= 2  # case 3
+        else:
+            p3 = p1 + Point3D(*self.normal_vector)  # case 4
+        return Plane(p1, p2, p3)
+
+    def projection_line(self, line):
+        """Project the given line onto the plane through the normal plane
+        containing the line.
+
+        Parameters
+        ==========
+
+        LinearEntity or LinearEntity3D
+
+        Returns
+        =======
+
+        Point3D, Line3D, Ray3D or Segment3D
+
+        Notes
+        =====
+
+        For the interaction between 2D and 3D lines(segments, rays), you should
+        convert the line to 3D by using this method. For example for finding the
+        intersection between a 2D and a 3D line, convert the 2D line to a 3D line
+        by projecting it on a required plane and then proceed to find the
+        intersection between those lines.
+
+        Examples
+        ========
+
+        >>> from sympy import Plane, Line, Line3D, Point3D
+        >>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 1, 1))
+        >>> b = Line(Point3D(1, 1), Point3D(2, 2))
+        >>> a.projection_line(b)
+        Line3D(Point3D(4/3, 4/3, 1/3), Point3D(5/3, 5/3, -1/3))
+        >>> c = Line3D(Point3D(1, 1, 1), Point3D(2, 2, 2))
+        >>> a.projection_line(c)
+        Point3D(1, 1, 1)
+
+        """
+        if not isinstance(line, (LinearEntity, LinearEntity3D)):
+            raise NotImplementedError('Enter a linear entity only')
+        a, b = self.projection(line.p1), self.projection(line.p2)
+        if a == b:
+            # projection does not imply intersection so for
+            # this case (line parallel to plane's normal) we
+            # return the projection point
+            return a
+        if isinstance(line, (Line, Line3D)):
+            return Line3D(a, b)
+        if isinstance(line, (Ray, Ray3D)):
+            return Ray3D(a, b)
+        if isinstance(line, (Segment, Segment3D)):
+            return Segment3D(a, b)
+
+    def projection(self, pt):
+        """Project the given point onto the plane along the plane normal.
+
+        Parameters
+        ==========
+
+        Point or Point3D
+
+        Returns
+        =======
+
+        Point3D
+
+        Examples
+        ========
+
+        >>> from sympy import Plane, Point3D
+        >>> A = Plane(Point3D(1, 1, 2), normal_vector=(1, 1, 1))
+
+        The projection is along the normal vector direction, not the z
+        axis, so (1, 1) does not project to (1, 1, 2) on the plane A:
+
+        >>> b = Point3D(1, 1)
+        >>> A.projection(b)
+        Point3D(5/3, 5/3, 2/3)
+        >>> _ in A
+        True
+
+        But the point (1, 1, 2) projects to (1, 1) on the XY-plane:
+
+        >>> XY = Plane((0, 0, 0), (0, 0, 1))
+        >>> XY.projection((1, 1, 2))
+        Point3D(1, 1, 0)
+        """
+        rv = Point(pt, dim=3)
+        if rv in self:
+            return rv
+        return self.intersection(Line3D(rv, rv + Point3D(self.normal_vector)))[0]
+
+    def random_point(self, seed=None):
+        """ Returns a random point on the Plane.
+
+        Returns
+        =======
+
+        Point3D
+
+        Examples
+        ========
+
+        >>> from sympy import Plane
+        >>> p = Plane((1, 0, 0), normal_vector=(0, 1, 0))
+        >>> r = p.random_point(seed=42)  # seed value is optional
+        >>> r.n(3)
+        Point3D(2.29, 0, -1.35)
+
+        The random point can be moved to lie on the circle of radius
+        1 centered on p1:
+
+        >>> c = p.p1 + (r - p.p1).unit
+        >>> c.distance(p.p1).equals(1)
+        True
+        """
+        if seed is not None:
+            rng = random.Random(seed)
+        else:
+            rng = random
+        params = {
+            x: 2*Rational(rng.gauss(0, 1)) - 1,
+            y: 2*Rational(rng.gauss(0, 1)) - 1}
+        return self.arbitrary_point(x, y).subs(params)
+
+    def parameter_value(self, other, u, v=None):
+        """Return the parameter(s) corresponding to the given point.
+
+        Examples
+        ========
+
+        >>> from sympy import pi, Plane
+        >>> from sympy.abc import t, u, v
+        >>> p = Plane((2, 0, 0), (0, 0, 1), (0, 1, 0))
+
+        By default, the parameter value returned defines a point
+        that is a distance of 1 from the Plane's p1 value and
+        in line with the given point:
+
+        >>> on_circle = p.arbitrary_point(t).subs(t, pi/4)
+        >>> on_circle.distance(p.p1)
+        1
+        >>> p.parameter_value(on_circle, t)
+        {t: pi/4}
+
+        Moving the point twice as far from p1 does not change
+        the parameter value:
+
+        >>> off_circle = p.p1 + (on_circle - p.p1)*2
+        >>> off_circle.distance(p.p1)
+        2
+        >>> p.parameter_value(off_circle, t)
+        {t: pi/4}
+
+        If the 2-value parameter is desired, supply the two
+        parameter symbols and a replacement dictionary will
+        be returned:
+
+        >>> p.parameter_value(on_circle, u, v)
+        {u: sqrt(10)/10, v: sqrt(10)/30}
+        >>> p.parameter_value(off_circle, u, v)
+        {u: sqrt(10)/5, v: sqrt(10)/15}
+        """
+        if not isinstance(other, GeometryEntity):
+            other = Point(other, dim=self.ambient_dimension)
+        if not isinstance(other, Point):
+            raise ValueError("other must be a point")
+        if other == self.p1:
+            return other
+        if isinstance(u, Symbol) and v is None:
+            delta = self.arbitrary_point(u) - self.p1
+            eq = delta - (other - self.p1).unit
+            sol = solve(eq, u, dict=True)
+        elif isinstance(u, Symbol) and isinstance(v, Symbol):
+            pt = self.arbitrary_point(u, v)
+            sol = solve(pt - other, (u, v), dict=True)
+        else:
+            raise ValueError('expecting 1 or 2 symbols')
+        if not sol:
+            raise ValueError("Given point is not on %s" % func_name(self))
+        return sol[0]  # {t: tval} or {u: uval, v: vval}
+
+    @property
+    def ambient_dimension(self):
+        return self.p1.ambient_dimension
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/point.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/point.py
new file mode 100644
index 0000000000000000000000000000000000000000..19e6c566f06de4df086912470dc35d0f4af3bd38
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/point.py
@@ -0,0 +1,1378 @@
+"""Geometrical Points.
+
+Contains
+========
+Point
+Point2D
+Point3D
+
+When methods of Point require 1 or more points as arguments, they
+can be passed as a sequence of coordinates or Points:
+
+>>> from sympy import Point
+>>> Point(1, 1).is_collinear((2, 2), (3, 4))
+False
+>>> Point(1, 1).is_collinear(Point(2, 2), Point(3, 4))
+False
+
+"""
+
+import warnings
+
+from sympy.core import S, sympify, Expr
+from sympy.core.add import Add
+from sympy.core.containers import Tuple
+from sympy.core.numbers import Float
+from sympy.core.parameters import global_parameters
+from sympy.simplify.simplify import nsimplify, simplify
+from sympy.geometry.exceptions import GeometryError
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.complexes import im
+from sympy.functions.elementary.trigonometric import cos, sin
+from sympy.matrices import Matrix
+from sympy.matrices.expressions import Transpose
+from sympy.utilities.iterables import uniq, is_sequence
+from sympy.utilities.misc import filldedent, func_name, Undecidable
+
+from .entity import GeometryEntity
+
+from mpmath.libmp.libmpf import prec_to_dps
+
+
+class Point(GeometryEntity):
+    """A point in a n-dimensional Euclidean space.
+
+    Parameters
+    ==========
+
+    coords : sequence of n-coordinate values. In the special
+        case where n=2 or 3, a Point2D or Point3D will be created
+        as appropriate.
+    evaluate : if `True` (default), all floats are turn into
+        exact types.
+    dim : number of coordinates the point should have.  If coordinates
+        are unspecified, they are padded with zeros.
+    on_morph : indicates what should happen when the number of
+        coordinates of a point need to be changed by adding or
+        removing zeros.  Possible values are `'warn'`, `'error'`, or
+        `ignore` (default).  No warning or error is given when `*args`
+        is empty and `dim` is given. An error is always raised when
+        trying to remove nonzero coordinates.
+
+
+    Attributes
+    ==========
+
+    length
+    origin: A `Point` representing the origin of the
+        appropriately-dimensioned space.
+
+    Raises
+    ======
+
+    TypeError : When instantiating with anything but a Point or sequence
+    ValueError : when instantiating with a sequence with length < 2 or
+        when trying to reduce dimensions if keyword `on_morph='error'` is
+        set.
+
+    See Also
+    ========
+
+    sympy.geometry.line.Segment : Connects two Points
+
+    Examples
+    ========
+
+    >>> from sympy import Point
+    >>> from sympy.abc import x
+    >>> Point(1, 2, 3)
+    Point3D(1, 2, 3)
+    >>> Point([1, 2])
+    Point2D(1, 2)
+    >>> Point(0, x)
+    Point2D(0, x)
+    >>> Point(dim=4)
+    Point(0, 0, 0, 0)
+
+    Floats are automatically converted to Rational unless the
+    evaluate flag is False:
+
+    >>> Point(0.5, 0.25)
+    Point2D(1/2, 1/4)
+    >>> Point(0.5, 0.25, evaluate=False)
+    Point2D(0.5, 0.25)
+
+    """
+
+    is_Point = True
+
+    def __new__(cls, *args, **kwargs):
+        evaluate = kwargs.get('evaluate', global_parameters.evaluate)
+        on_morph = kwargs.get('on_morph', 'ignore')
+
+        # unpack into coords
+        coords = args[0] if len(args) == 1 else args
+
+        # check args and handle quickly handle Point instances
+        if isinstance(coords, Point):
+            # even if we're mutating the dimension of a point, we
+            # don't reevaluate its coordinates
+            evaluate = False
+            if len(coords) == kwargs.get('dim', len(coords)):
+                return coords
+
+        if not is_sequence(coords):
+            raise TypeError(filldedent('''
+                Expecting sequence of coordinates, not `{}`'''
+                                       .format(func_name(coords))))
+        # A point where only `dim` is specified is initialized
+        # to zeros.
+        if len(coords) == 0 and kwargs.get('dim', None):
+            coords = (S.Zero,)*kwargs.get('dim')
+
+        coords = Tuple(*coords)
+        dim = kwargs.get('dim', len(coords))
+
+        if len(coords) < 2:
+            raise ValueError(filldedent('''
+                Point requires 2 or more coordinates or
+                keyword `dim` > 1.'''))
+        if len(coords) != dim:
+            message = ("Dimension of {} needs to be changed "
+                       "from {} to {}.").format(coords, len(coords), dim)
+            if on_morph == 'ignore':
+                pass
+            elif on_morph == "error":
+                raise ValueError(message)
+            elif on_morph == 'warn':
+                warnings.warn(message, stacklevel=2)
+            else:
+                raise ValueError(filldedent('''
+                        on_morph value should be 'error',
+                        'warn' or 'ignore'.'''))
+        if any(coords[dim:]):
+            raise ValueError('Nonzero coordinates cannot be removed.')
+        if any(a.is_number and im(a).is_zero is False for a in coords):
+            raise ValueError('Imaginary coordinates are not permitted.')
+        if not all(isinstance(a, Expr) for a in coords):
+            raise TypeError('Coordinates must be valid SymPy expressions.')
+
+        # pad with zeros appropriately
+        coords = coords[:dim] + (S.Zero,)*(dim - len(coords))
+
+        # Turn any Floats into rationals and simplify
+        # any expressions before we instantiate
+        if evaluate:
+            coords = coords.xreplace({
+                f: simplify(nsimplify(f, rational=True))
+                 for f in coords.atoms(Float)})
+
+        # return 2D or 3D instances
+        if len(coords) == 2:
+            kwargs['_nocheck'] = True
+            return Point2D(*coords, **kwargs)
+        elif len(coords) == 3:
+            kwargs['_nocheck'] = True
+            return Point3D(*coords, **kwargs)
+
+        # the general Point
+        return GeometryEntity.__new__(cls, *coords)
+
+    def __abs__(self):
+        """Returns the distance between this point and the origin."""
+        origin = Point([0]*len(self))
+        return Point.distance(origin, self)
+
+    def __add__(self, other):
+        """Add other to self by incrementing self's coordinates by
+        those of other.
+
+        Notes
+        =====
+
+        >>> from sympy import Point
+
+        When sequences of coordinates are passed to Point methods, they
+        are converted to a Point internally. This __add__ method does
+        not do that so if floating point values are used, a floating
+        point result (in terms of SymPy Floats) will be returned.
+
+        >>> Point(1, 2) + (.1, .2)
+        Point2D(1.1, 2.2)
+
+        If this is not desired, the `translate` method can be used or
+        another Point can be added:
+
+        >>> Point(1, 2).translate(.1, .2)
+        Point2D(11/10, 11/5)
+        >>> Point(1, 2) + Point(.1, .2)
+        Point2D(11/10, 11/5)
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point.translate
+
+        """
+        try:
+            s, o = Point._normalize_dimension(self, Point(other, evaluate=False))
+        except TypeError:
+            raise GeometryError("Don't know how to add {} and a Point object".format(other))
+
+        coords = [simplify(a + b) for a, b in zip(s, o)]
+        return Point(coords, evaluate=False)
+
+    def __contains__(self, item):
+        return item in self.args
+
+    def __truediv__(self, divisor):
+        """Divide point's coordinates by a factor."""
+        divisor = sympify(divisor)
+        coords = [simplify(x/divisor) for x in self.args]
+        return Point(coords, evaluate=False)
+
+    def __eq__(self, other):
+        if not isinstance(other, Point) or len(self.args) != len(other.args):
+            return False
+        return self.args == other.args
+
+    def __getitem__(self, key):
+        return self.args[key]
+
+    def __hash__(self):
+        return hash(self.args)
+
+    def __iter__(self):
+        return self.args.__iter__()
+
+    def __len__(self):
+        return len(self.args)
+
+    def __mul__(self, factor):
+        """Multiply point's coordinates by a factor.
+
+        Notes
+        =====
+
+        >>> from sympy import Point
+
+        When multiplying a Point by a floating point number,
+        the coordinates of the Point will be changed to Floats:
+
+        >>> Point(1, 2)*0.1
+        Point2D(0.1, 0.2)
+
+        If this is not desired, the `scale` method can be used or
+        else only multiply or divide by integers:
+
+        >>> Point(1, 2).scale(1.1, 1.1)
+        Point2D(11/10, 11/5)
+        >>> Point(1, 2)*11/10
+        Point2D(11/10, 11/5)
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point.scale
+        """
+        factor = sympify(factor)
+        coords = [simplify(x*factor) for x in self.args]
+        return Point(coords, evaluate=False)
+
+    def __rmul__(self, factor):
+        """Multiply a factor by point's coordinates."""
+        return self.__mul__(factor)
+
+    def __neg__(self):
+        """Negate the point."""
+        coords = [-x for x in self.args]
+        return Point(coords, evaluate=False)
+
+    def __sub__(self, other):
+        """Subtract two points, or subtract a factor from this point's
+        coordinates."""
+        return self + [-x for x in other]
+
+    @classmethod
+    def _normalize_dimension(cls, *points, **kwargs):
+        """Ensure that points have the same dimension.
+        By default `on_morph='warn'` is passed to the
+        `Point` constructor."""
+        # if we have a built-in ambient dimension, use it
+        dim = getattr(cls, '_ambient_dimension', None)
+        # override if we specified it
+        dim = kwargs.get('dim', dim)
+        # if no dim was given, use the highest dimensional point
+        if dim is None:
+            dim = max(i.ambient_dimension for i in points)
+        if all(i.ambient_dimension == dim for i in points):
+            return list(points)
+        kwargs['dim'] = dim
+        kwargs['on_morph'] = kwargs.get('on_morph', 'warn')
+        return [Point(i, **kwargs) for i in points]
+
+    @staticmethod
+    def affine_rank(*args):
+        """The affine rank of a set of points is the dimension
+        of the smallest affine space containing all the points.
+        For example, if the points lie on a line (and are not all
+        the same) their affine rank is 1.  If the points lie on a plane
+        but not a line, their affine rank is 2.  By convention, the empty
+        set has affine rank -1."""
+
+        if len(args) == 0:
+            return -1
+        # make sure we're genuinely points
+        # and translate every point to the origin
+        points = Point._normalize_dimension(*[Point(i) for i in args])
+        origin = points[0]
+        points = [i - origin for i in points[1:]]
+
+        m = Matrix([i.args for i in points])
+        # XXX fragile -- what is a better way?
+        return m.rank(iszerofunc = lambda x:
+            abs(x.n(2)) < 1e-12 if x.is_number else x.is_zero)
+
+    @property
+    def ambient_dimension(self):
+        """Number of components this point has."""
+        return getattr(self, '_ambient_dimension', len(self))
+
+    @classmethod
+    def are_coplanar(cls, *points):
+        """Return True if there exists a plane in which all the points
+        lie.  A trivial True value is returned if `len(points) < 3` or
+        all Points are 2-dimensional.
+
+        Parameters
+        ==========
+
+        A set of points
+
+        Raises
+        ======
+
+        ValueError : if less than 3 unique points are given
+
+        Returns
+        =======
+
+        boolean
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D
+        >>> p1 = Point3D(1, 2, 2)
+        >>> p2 = Point3D(2, 7, 2)
+        >>> p3 = Point3D(0, 0, 2)
+        >>> p4 = Point3D(1, 1, 2)
+        >>> Point3D.are_coplanar(p1, p2, p3, p4)
+        True
+        >>> p5 = Point3D(0, 1, 3)
+        >>> Point3D.are_coplanar(p1, p2, p3, p5)
+        False
+
+        """
+        if len(points) <= 1:
+            return True
+
+        points = cls._normalize_dimension(*[Point(i) for i in points])
+        # quick exit if we are in 2D
+        if points[0].ambient_dimension == 2:
+            return True
+        points = list(uniq(points))
+        return Point.affine_rank(*points) <= 2
+
+    def distance(self, other):
+        """The Euclidean distance between self and another GeometricEntity.
+
+        Returns
+        =======
+
+        distance : number or symbolic expression.
+
+        Raises
+        ======
+
+        TypeError : if other is not recognized as a GeometricEntity or is a
+                    GeometricEntity for which distance is not defined.
+
+        See Also
+        ========
+
+        sympy.geometry.line.Segment.length
+        sympy.geometry.point.Point.taxicab_distance
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Line
+        >>> p1, p2 = Point(1, 1), Point(4, 5)
+        >>> l = Line((3, 1), (2, 2))
+        >>> p1.distance(p2)
+        5
+        >>> p1.distance(l)
+        sqrt(2)
+
+        The computed distance may be symbolic, too:
+
+        >>> from sympy.abc import x, y
+        >>> p3 = Point(x, y)
+        >>> p3.distance((0, 0))
+        sqrt(x**2 + y**2)
+
+        """
+        if not isinstance(other, GeometryEntity):
+            try:
+                other = Point(other, dim=self.ambient_dimension)
+            except TypeError:
+                raise TypeError("not recognized as a GeometricEntity: %s" % type(other))
+        if isinstance(other, Point):
+            s, p = Point._normalize_dimension(self, Point(other))
+            return sqrt(Add(*((a - b)**2 for a, b in zip(s, p))))
+        distance = getattr(other, 'distance', None)
+        if distance is None:
+            raise TypeError("distance between Point and %s is not defined" % type(other))
+        return distance(self)
+
+    def dot(self, p):
+        """Return dot product of self with another Point."""
+        if not is_sequence(p):
+            p = Point(p)  # raise the error via Point
+        return Add(*(a*b for a, b in zip(self, p)))
+
+    def equals(self, other):
+        """Returns whether the coordinates of self and other agree."""
+        # a point is equal to another point if all its components are equal
+        if not isinstance(other, Point) or len(self) != len(other):
+            return False
+        return all(a.equals(b) for a, b in zip(self, other))
+
+    def _eval_evalf(self, prec=15, **options):
+        """Evaluate the coordinates of the point.
+
+        This method will, where possible, create and return a new Point
+        where the coordinates are evaluated as floating point numbers to
+        the precision indicated (default=15).
+
+        Parameters
+        ==========
+
+        prec : int
+
+        Returns
+        =======
+
+        point : Point
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Rational
+        >>> p1 = Point(Rational(1, 2), Rational(3, 2))
+        >>> p1
+        Point2D(1/2, 3/2)
+        >>> p1.evalf()
+        Point2D(0.5, 1.5)
+
+        """
+        dps = prec_to_dps(prec)
+        coords = [x.evalf(n=dps, **options) for x in self.args]
+        return Point(*coords, evaluate=False)
+
+    def intersection(self, other):
+        """The intersection between this point and another GeometryEntity.
+
+        Parameters
+        ==========
+
+        other : GeometryEntity or sequence of coordinates
+
+        Returns
+        =======
+
+        intersection : list of Points
+
+        Notes
+        =====
+
+        The return value will either be an empty list if there is no
+        intersection, otherwise it will contain this point.
+
+        Examples
+        ========
+
+        >>> from sympy import Point
+        >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(0, 0)
+        >>> p1.intersection(p2)
+        []
+        >>> p1.intersection(p3)
+        [Point2D(0, 0)]
+
+        """
+        if not isinstance(other, GeometryEntity):
+            other = Point(other)
+        if isinstance(other, Point):
+            if self == other:
+                return [self]
+            p1, p2 = Point._normalize_dimension(self, other)
+            if p1 == self and p1 == p2:
+                return [self]
+            return []
+        return other.intersection(self)
+
+    def is_collinear(self, *args):
+        """Returns `True` if there exists a line
+        that contains `self` and `points`.  Returns `False` otherwise.
+        A trivially True value is returned if no points are given.
+
+        Parameters
+        ==========
+
+        args : sequence of Points
+
+        Returns
+        =======
+
+        is_collinear : boolean
+
+        See Also
+        ========
+
+        sympy.geometry.line.Line
+
+        Examples
+        ========
+
+        >>> from sympy import Point
+        >>> from sympy.abc import x
+        >>> p1, p2 = Point(0, 0), Point(1, 1)
+        >>> p3, p4, p5 = Point(2, 2), Point(x, x), Point(1, 2)
+        >>> Point.is_collinear(p1, p2, p3, p4)
+        True
+        >>> Point.is_collinear(p1, p2, p3, p5)
+        False
+
+        """
+        points = (self,) + args
+        points = Point._normalize_dimension(*[Point(i) for i in points])
+        points = list(uniq(points))
+        return Point.affine_rank(*points) <= 1
+
+    def is_concyclic(self, *args):
+        """Do `self` and the given sequence of points lie in a circle?
+
+        Returns True if the set of points are concyclic and
+        False otherwise. A trivial value of True is returned
+        if there are fewer than 2 other points.
+
+        Parameters
+        ==========
+
+        args : sequence of Points
+
+        Returns
+        =======
+
+        is_concyclic : boolean
+
+
+        Examples
+        ========
+
+        >>> from sympy import Point
+
+        Define 4 points that are on the unit circle:
+
+        >>> p1, p2, p3, p4 = Point(1, 0), (0, 1), (-1, 0), (0, -1)
+
+        >>> p1.is_concyclic() == p1.is_concyclic(p2, p3, p4) == True
+        True
+
+        Define a point not on that circle:
+
+        >>> p = Point(1, 1)
+
+        >>> p.is_concyclic(p1, p2, p3)
+        False
+
+        """
+        points = (self,) + args
+        points = Point._normalize_dimension(*[Point(i) for i in points])
+        points = list(uniq(points))
+        if not Point.affine_rank(*points) <= 2:
+            return False
+        origin = points[0]
+        points = [p - origin for p in points]
+        # points are concyclic if they are coplanar and
+        # there is a point c so that ||p_i-c|| == ||p_j-c|| for all
+        # i and j.  Rearranging this equation gives us the following
+        # condition: the matrix `mat` must not a pivot in the last
+        # column.
+        mat = Matrix([list(i) + [i.dot(i)] for i in points])
+        rref, pivots = mat.rref()
+        if len(origin) not in pivots:
+            return True
+        return False
+
+    @property
+    def is_nonzero(self):
+        """True if any coordinate is nonzero, False if every coordinate is zero,
+        and None if it cannot be determined."""
+        is_zero = self.is_zero
+        if is_zero is None:
+            return None
+        return not is_zero
+
+    def is_scalar_multiple(self, p):
+        """Returns whether each coordinate of `self` is a scalar
+        multiple of the corresponding coordinate in point p.
+        """
+        s, o = Point._normalize_dimension(self, Point(p))
+        # 2d points happen a lot, so optimize this function call
+        if s.ambient_dimension == 2:
+            (x1, y1), (x2, y2) = s.args, o.args
+            rv = (x1*y2 - x2*y1).equals(0)
+            if rv is None:
+                raise Undecidable(filldedent(
+                    '''Cannot determine if %s is a scalar multiple of
+                    %s''' % (s, o)))
+
+        # if the vectors p1 and p2 are linearly dependent, then they must
+        # be scalar multiples of each other
+        m = Matrix([s.args, o.args])
+        return m.rank() < 2
+
+    @property
+    def is_zero(self):
+        """True if every coordinate is zero, False if any coordinate is not zero,
+        and None if it cannot be determined."""
+        nonzero = [x.is_nonzero for x in self.args]
+        if any(nonzero):
+            return False
+        if any(x is None for x in nonzero):
+            return None
+        return True
+
+    @property
+    def length(self):
+        """
+        Treating a Point as a Line, this returns 0 for the length of a Point.
+
+        Examples
+        ========
+
+        >>> from sympy import Point
+        >>> p = Point(0, 1)
+        >>> p.length
+        0
+        """
+        return S.Zero
+
+    def midpoint(self, p):
+        """The midpoint between self and point p.
+
+        Parameters
+        ==========
+
+        p : Point
+
+        Returns
+        =======
+
+        midpoint : Point
+
+        See Also
+        ========
+
+        sympy.geometry.line.Segment.midpoint
+
+        Examples
+        ========
+
+        >>> from sympy import Point
+        >>> p1, p2 = Point(1, 1), Point(13, 5)
+        >>> p1.midpoint(p2)
+        Point2D(7, 3)
+
+        """
+        s, p = Point._normalize_dimension(self, Point(p))
+        return Point([simplify((a + b)*S.Half) for a, b in zip(s, p)])
+
+    @property
+    def origin(self):
+        """A point of all zeros of the same ambient dimension
+        as the current point"""
+        return Point([0]*len(self), evaluate=False)
+
+    @property
+    def orthogonal_direction(self):
+        """Returns a non-zero point that is orthogonal to the
+        line containing `self` and the origin.
+
+        Examples
+        ========
+
+        >>> from sympy import Line, Point
+        >>> a = Point(1, 2, 3)
+        >>> a.orthogonal_direction
+        Point3D(-2, 1, 0)
+        >>> b = _
+        >>> Line(b, b.origin).is_perpendicular(Line(a, a.origin))
+        True
+        """
+        dim = self.ambient_dimension
+        # if a coordinate is zero, we can put a 1 there and zeros elsewhere
+        if self[0].is_zero:
+            return Point([1] + (dim - 1)*[0])
+        if self[1].is_zero:
+            return Point([0,1] + (dim - 2)*[0])
+        # if the first two coordinates aren't zero, we can create a non-zero
+        # orthogonal vector by swapping them, negating one, and padding with zeros
+        return Point([-self[1], self[0]] + (dim - 2)*[0])
+
+    @staticmethod
+    def project(a, b):
+        """Project the point `a` onto the line between the origin
+        and point `b` along the normal direction.
+
+        Parameters
+        ==========
+
+        a : Point
+        b : Point
+
+        Returns
+        =======
+
+        p : Point
+
+        See Also
+        ========
+
+        sympy.geometry.line.LinearEntity.projection
+
+        Examples
+        ========
+
+        >>> from sympy import Line, Point
+        >>> a = Point(1, 2)
+        >>> b = Point(2, 5)
+        >>> z = a.origin
+        >>> p = Point.project(a, b)
+        >>> Line(p, a).is_perpendicular(Line(p, b))
+        True
+        >>> Point.is_collinear(z, p, b)
+        True
+        """
+        a, b = Point._normalize_dimension(Point(a), Point(b))
+        if b.is_zero:
+            raise ValueError("Cannot project to the zero vector.")
+        return b*(a.dot(b) / b.dot(b))
+
+    def taxicab_distance(self, p):
+        """The Taxicab Distance from self to point p.
+
+        Returns the sum of the horizontal and vertical distances to point p.
+
+        Parameters
+        ==========
+
+        p : Point
+
+        Returns
+        =======
+
+        taxicab_distance : The sum of the horizontal
+        and vertical distances to point p.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point.distance
+
+        Examples
+        ========
+
+        >>> from sympy import Point
+        >>> p1, p2 = Point(1, 1), Point(4, 5)
+        >>> p1.taxicab_distance(p2)
+        7
+
+        """
+        s, p = Point._normalize_dimension(self, Point(p))
+        return Add(*(abs(a - b) for a, b in zip(s, p)))
+
+    def canberra_distance(self, p):
+        """The Canberra Distance from self to point p.
+
+        Returns the weighted sum of horizontal and vertical distances to
+        point p.
+
+        Parameters
+        ==========
+
+        p : Point
+
+        Returns
+        =======
+
+        canberra_distance : The weighted sum of horizontal and vertical
+        distances to point p. The weight used is the sum of absolute values
+        of the coordinates.
+
+        Examples
+        ========
+
+        >>> from sympy import Point
+        >>> p1, p2 = Point(1, 1), Point(3, 3)
+        >>> p1.canberra_distance(p2)
+        1
+        >>> p1, p2 = Point(0, 0), Point(3, 3)
+        >>> p1.canberra_distance(p2)
+        2
+
+        Raises
+        ======
+
+        ValueError when both vectors are zero.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point.distance
+
+        """
+
+        s, p = Point._normalize_dimension(self, Point(p))
+        if self.is_zero and p.is_zero:
+            raise ValueError("Cannot project to the zero vector.")
+        return Add(*((abs(a - b)/(abs(a) + abs(b))) for a, b in zip(s, p)))
+
+    @property
+    def unit(self):
+        """Return the Point that is in the same direction as `self`
+        and a distance of 1 from the origin"""
+        return self / abs(self)
+
+
+class Point2D(Point):
+    """A point in a 2-dimensional Euclidean space.
+
+    Parameters
+    ==========
+
+    coords
+        A sequence of 2 coordinate values.
+
+    Attributes
+    ==========
+
+    x
+    y
+    length
+
+    Raises
+    ======
+
+    TypeError
+        When trying to add or subtract points with different dimensions.
+        When trying to create a point with more than two dimensions.
+        When `intersection` is called with object other than a Point.
+
+    See Also
+    ========
+
+    sympy.geometry.line.Segment : Connects two Points
+
+    Examples
+    ========
+
+    >>> from sympy import Point2D
+    >>> from sympy.abc import x
+    >>> Point2D(1, 2)
+    Point2D(1, 2)
+    >>> Point2D([1, 2])
+    Point2D(1, 2)
+    >>> Point2D(0, x)
+    Point2D(0, x)
+
+    Floats are automatically converted to Rational unless the
+    evaluate flag is False:
+
+    >>> Point2D(0.5, 0.25)
+    Point2D(1/2, 1/4)
+    >>> Point2D(0.5, 0.25, evaluate=False)
+    Point2D(0.5, 0.25)
+
+    """
+
+    _ambient_dimension = 2
+
+    def __new__(cls, *args, _nocheck=False, **kwargs):
+        if not _nocheck:
+            kwargs['dim'] = 2
+            args = Point(*args, **kwargs)
+        return GeometryEntity.__new__(cls, *args)
+
+    def __contains__(self, item):
+        return item == self
+
+    @property
+    def bounds(self):
+        """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding
+        rectangle for the geometric figure.
+
+        """
+
+        return (self.x, self.y, self.x, self.y)
+
+    def rotate(self, angle, pt=None):
+        """Rotate ``angle`` radians counterclockwise about Point ``pt``.
+
+        See Also
+        ========
+
+        translate, scale
+
+        Examples
+        ========
+
+        >>> from sympy import Point2D, pi
+        >>> t = Point2D(1, 0)
+        >>> t.rotate(pi/2)
+        Point2D(0, 1)
+        >>> t.rotate(pi/2, (2, 0))
+        Point2D(2, -1)
+
+        """
+        c = cos(angle)
+        s = sin(angle)
+
+        rv = self
+        if pt is not None:
+            pt = Point(pt, dim=2)
+            rv -= pt
+        x, y = rv.args
+        rv = Point(c*x - s*y, s*x + c*y)
+        if pt is not None:
+            rv += pt
+        return rv
+
+    def scale(self, x=1, y=1, pt=None):
+        """Scale the coordinates of the Point by multiplying by
+        ``x`` and ``y`` after subtracting ``pt`` -- default is (0, 0) --
+        and then adding ``pt`` back again (i.e. ``pt`` is the point of
+        reference for the scaling).
+
+        See Also
+        ========
+
+        rotate, translate
+
+        Examples
+        ========
+
+        >>> from sympy import Point2D
+        >>> t = Point2D(1, 1)
+        >>> t.scale(2)
+        Point2D(2, 1)
+        >>> t.scale(2, 2)
+        Point2D(2, 2)
+
+        """
+        if pt:
+            pt = Point(pt, dim=2)
+            return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
+        return Point(self.x*x, self.y*y)
+
+    def transform(self, matrix):
+        """Return the point after applying the transformation described
+        by the 3x3 Matrix, ``matrix``.
+
+        See Also
+        ========
+        sympy.geometry.point.Point2D.rotate
+        sympy.geometry.point.Point2D.scale
+        sympy.geometry.point.Point2D.translate
+        """
+        if not (matrix.is_Matrix and matrix.shape == (3, 3)):
+            raise ValueError("matrix must be a 3x3 matrix")
+        x, y = self.args
+        return Point(*(Matrix(1, 3, [x, y, 1])*matrix).tolist()[0][:2])
+
+    def translate(self, x=0, y=0):
+        """Shift the Point by adding x and y to the coordinates of the Point.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point2D.rotate, scale
+
+        Examples
+        ========
+
+        >>> from sympy import Point2D
+        >>> t = Point2D(0, 1)
+        >>> t.translate(2)
+        Point2D(2, 1)
+        >>> t.translate(2, 2)
+        Point2D(2, 3)
+        >>> t + Point2D(2, 2)
+        Point2D(2, 3)
+
+        """
+        return Point(self.x + x, self.y + y)
+
+    @property
+    def coordinates(self):
+        """
+        Returns the two coordinates of the Point.
+
+        Examples
+        ========
+
+        >>> from sympy import Point2D
+        >>> p = Point2D(0, 1)
+        >>> p.coordinates
+        (0, 1)
+        """
+        return self.args
+
+    @property
+    def x(self):
+        """
+        Returns the X coordinate of the Point.
+
+        Examples
+        ========
+
+        >>> from sympy import Point2D
+        >>> p = Point2D(0, 1)
+        >>> p.x
+        0
+        """
+        return self.args[0]
+
+    @property
+    def y(self):
+        """
+        Returns the Y coordinate of the Point.
+
+        Examples
+        ========
+
+        >>> from sympy import Point2D
+        >>> p = Point2D(0, 1)
+        >>> p.y
+        1
+        """
+        return self.args[1]
+
+class Point3D(Point):
+    """A point in a 3-dimensional Euclidean space.
+
+    Parameters
+    ==========
+
+    coords
+        A sequence of 3 coordinate values.
+
+    Attributes
+    ==========
+
+    x
+    y
+    z
+    length
+
+    Raises
+    ======
+
+    TypeError
+        When trying to add or subtract points with different dimensions.
+        When `intersection` is called with object other than a Point.
+
+    Examples
+    ========
+
+    >>> from sympy import Point3D
+    >>> from sympy.abc import x
+    >>> Point3D(1, 2, 3)
+    Point3D(1, 2, 3)
+    >>> Point3D([1, 2, 3])
+    Point3D(1, 2, 3)
+    >>> Point3D(0, x, 3)
+    Point3D(0, x, 3)
+
+    Floats are automatically converted to Rational unless the
+    evaluate flag is False:
+
+    >>> Point3D(0.5, 0.25, 2)
+    Point3D(1/2, 1/4, 2)
+    >>> Point3D(0.5, 0.25, 3, evaluate=False)
+    Point3D(0.5, 0.25, 3)
+
+    """
+
+    _ambient_dimension = 3
+
+    def __new__(cls, *args, _nocheck=False, **kwargs):
+        if not _nocheck:
+            kwargs['dim'] = 3
+            args = Point(*args, **kwargs)
+        return GeometryEntity.__new__(cls, *args)
+
+    def __contains__(self, item):
+        return item == self
+
+    @staticmethod
+    def are_collinear(*points):
+        """Is a sequence of points collinear?
+
+        Test whether or not a set of points are collinear. Returns True if
+        the set of points are collinear, or False otherwise.
+
+        Parameters
+        ==========
+
+        points : sequence of Point
+
+        Returns
+        =======
+
+        are_collinear : boolean
+
+        See Also
+        ========
+
+        sympy.geometry.line.Line3D
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D
+        >>> from sympy.abc import x
+        >>> p1, p2 = Point3D(0, 0, 0), Point3D(1, 1, 1)
+        >>> p3, p4, p5 = Point3D(2, 2, 2), Point3D(x, x, x), Point3D(1, 2, 6)
+        >>> Point3D.are_collinear(p1, p2, p3, p4)
+        True
+        >>> Point3D.are_collinear(p1, p2, p3, p5)
+        False
+        """
+        return Point.is_collinear(*points)
+
+    def direction_cosine(self, point):
+        """
+        Gives the direction cosine between 2 points
+
+        Parameters
+        ==========
+
+        p : Point3D
+
+        Returns
+        =======
+
+        list
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D
+        >>> p1 = Point3D(1, 2, 3)
+        >>> p1.direction_cosine(Point3D(2, 3, 5))
+        [sqrt(6)/6, sqrt(6)/6, sqrt(6)/3]
+        """
+        a = self.direction_ratio(point)
+        b = sqrt(Add(*(i**2 for i in a)))
+        return [(point.x - self.x) / b,(point.y - self.y) / b,
+                (point.z - self.z) / b]
+
+    def direction_ratio(self, point):
+        """
+        Gives the direction ratio between 2 points
+
+        Parameters
+        ==========
+
+        p : Point3D
+
+        Returns
+        =======
+
+        list
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D
+        >>> p1 = Point3D(1, 2, 3)
+        >>> p1.direction_ratio(Point3D(2, 3, 5))
+        [1, 1, 2]
+        """
+        return [(point.x - self.x),(point.y - self.y),(point.z - self.z)]
+
+    def intersection(self, other):
+        """The intersection between this point and another GeometryEntity.
+
+        Parameters
+        ==========
+
+        other : GeometryEntity or sequence of coordinates
+
+        Returns
+        =======
+
+        intersection : list of Points
+
+        Notes
+        =====
+
+        The return value will either be an empty list if there is no
+        intersection, otherwise it will contain this point.
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D
+        >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, 0, 0)
+        >>> p1.intersection(p2)
+        []
+        >>> p1.intersection(p3)
+        [Point3D(0, 0, 0)]
+
+        """
+        if not isinstance(other, GeometryEntity):
+            other = Point(other, dim=3)
+        if isinstance(other, Point3D):
+            if self == other:
+                return [self]
+            return []
+        return other.intersection(self)
+
+    def scale(self, x=1, y=1, z=1, pt=None):
+        """Scale the coordinates of the Point by multiplying by
+        ``x`` and ``y`` after subtracting ``pt`` -- default is (0, 0) --
+        and then adding ``pt`` back again (i.e. ``pt`` is the point of
+        reference for the scaling).
+
+        See Also
+        ========
+
+        translate
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D
+        >>> t = Point3D(1, 1, 1)
+        >>> t.scale(2)
+        Point3D(2, 1, 1)
+        >>> t.scale(2, 2)
+        Point3D(2, 2, 1)
+
+        """
+        if pt:
+            pt = Point3D(pt)
+            return self.translate(*(-pt).args).scale(x, y, z).translate(*pt.args)
+        return Point3D(self.x*x, self.y*y, self.z*z)
+
+    def transform(self, matrix):
+        """Return the point after applying the transformation described
+        by the 4x4 Matrix, ``matrix``.
+
+        See Also
+        ========
+        sympy.geometry.point.Point3D.scale
+        sympy.geometry.point.Point3D.translate
+        """
+        if not (matrix.is_Matrix and matrix.shape == (4, 4)):
+            raise ValueError("matrix must be a 4x4 matrix")
+        x, y, z = self.args
+        m = Transpose(matrix)
+        return Point3D(*(Matrix(1, 4, [x, y, z, 1])*m).tolist()[0][:3])
+
+    def translate(self, x=0, y=0, z=0):
+        """Shift the Point by adding x and y to the coordinates of the Point.
+
+        See Also
+        ========
+
+        scale
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D
+        >>> t = Point3D(0, 1, 1)
+        >>> t.translate(2)
+        Point3D(2, 1, 1)
+        >>> t.translate(2, 2)
+        Point3D(2, 3, 1)
+        >>> t + Point3D(2, 2, 2)
+        Point3D(2, 3, 3)
+
+        """
+        return Point3D(self.x + x, self.y + y, self.z + z)
+
+    @property
+    def coordinates(self):
+        """
+        Returns the three coordinates of the Point.
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D
+        >>> p = Point3D(0, 1, 2)
+        >>> p.coordinates
+        (0, 1, 2)
+        """
+        return self.args
+
+    @property
+    def x(self):
+        """
+        Returns the X coordinate of the Point.
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D
+        >>> p = Point3D(0, 1, 3)
+        >>> p.x
+        0
+        """
+        return self.args[0]
+
+    @property
+    def y(self):
+        """
+        Returns the Y coordinate of the Point.
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D
+        >>> p = Point3D(0, 1, 2)
+        >>> p.y
+        1
+        """
+        return self.args[1]
+
+    @property
+    def z(self):
+        """
+        Returns the Z coordinate of the Point.
+
+        Examples
+        ========
+
+        >>> from sympy import Point3D
+        >>> p = Point3D(0, 1, 1)
+        >>> p.z
+        1
+        """
+        return self.args[2]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/polygon.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/polygon.py
new file mode 100644
index 0000000000000000000000000000000000000000..63031183438e2d228f881fd82e1b0ecca04ec534
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/polygon.py
@@ -0,0 +1,2891 @@
+from sympy.core import Expr, S, oo, pi, sympify
+from sympy.core.evalf import N
+from sympy.core.sorting import default_sort_key, ordered
+from sympy.core.symbol import _symbol, Dummy, Symbol
+from sympy.functions.elementary.complexes import sign
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.functions.elementary.trigonometric import cos, sin, tan
+from .ellipse import Circle
+from .entity import GeometryEntity, GeometrySet
+from .exceptions import GeometryError
+from .line import Line, Segment, Ray
+from .point import Point
+from sympy.logic import And
+from sympy.matrices import Matrix
+from sympy.simplify.simplify import simplify
+from sympy.solvers.solvers import solve
+from sympy.utilities.iterables import has_dups, has_variety, uniq, rotate_left, least_rotation
+from sympy.utilities.misc import as_int, func_name
+
+from mpmath.libmp.libmpf import prec_to_dps
+
+import warnings
+
+
+x, y, T = [Dummy('polygon_dummy', real=True) for i in range(3)]
+
+
+class Polygon(GeometrySet):
+    """A two-dimensional polygon.
+
+    A simple polygon in space. Can be constructed from a sequence of points
+    or from a center, radius, number of sides and rotation angle.
+
+    Parameters
+    ==========
+
+    vertices
+        A sequence of points.
+
+    n : int, optional
+        If $> 0$, an n-sided RegularPolygon is created.
+        Default value is $0$.
+
+    Attributes
+    ==========
+
+    area
+    angles
+    perimeter
+    vertices
+    centroid
+    sides
+
+    Raises
+    ======
+
+    GeometryError
+        If all parameters are not Points.
+
+    See Also
+    ========
+
+    sympy.geometry.point.Point, sympy.geometry.line.Segment, Triangle
+
+    Notes
+    =====
+
+    Polygons are treated as closed paths rather than 2D areas so
+    some calculations can be be negative or positive (e.g., area)
+    based on the orientation of the points.
+
+    Any consecutive identical points are reduced to a single point
+    and any points collinear and between two points will be removed
+    unless they are needed to define an explicit intersection (see examples).
+
+    A Triangle, Segment or Point will be returned when there are 3 or
+    fewer points provided.
+
+    Examples
+    ========
+
+    >>> from sympy import Polygon, pi
+    >>> p1, p2, p3, p4, p5 = [(0, 0), (1, 0), (5, 1), (0, 1), (3, 0)]
+    >>> Polygon(p1, p2, p3, p4)
+    Polygon(Point2D(0, 0), Point2D(1, 0), Point2D(5, 1), Point2D(0, 1))
+    >>> Polygon(p1, p2)
+    Segment2D(Point2D(0, 0), Point2D(1, 0))
+    >>> Polygon(p1, p2, p5)
+    Segment2D(Point2D(0, 0), Point2D(3, 0))
+
+    The area of a polygon is calculated as positive when vertices are
+    traversed in a ccw direction. When the sides of a polygon cross the
+    area will have positive and negative contributions. The following
+    defines a Z shape where the bottom right connects back to the top
+    left.
+
+    >>> Polygon((0, 2), (2, 2), (0, 0), (2, 0)).area
+    0
+
+    When the keyword `n` is used to define the number of sides of the
+    Polygon then a RegularPolygon is created and the other arguments are
+    interpreted as center, radius and rotation. The unrotated RegularPolygon
+    will always have a vertex at Point(r, 0) where `r` is the radius of the
+    circle that circumscribes the RegularPolygon. Its method `spin` can be
+    used to increment that angle.
+
+    >>> p = Polygon((0,0), 1, n=3)
+    >>> p
+    RegularPolygon(Point2D(0, 0), 1, 3, 0)
+    >>> p.vertices[0]
+    Point2D(1, 0)
+    >>> p.args[0]
+    Point2D(0, 0)
+    >>> p.spin(pi/2)
+    >>> p.vertices[0]
+    Point2D(0, 1)
+
+    """
+
+    __slots__ = ()
+
+    def __new__(cls, *args, n = 0, **kwargs):
+        if n:
+            args = list(args)
+            # return a virtual polygon with n sides
+            if len(args) == 2:  # center, radius
+                args.append(n)
+            elif len(args) == 3:  # center, radius, rotation
+                args.insert(2, n)
+            return RegularPolygon(*args, **kwargs)
+
+        vertices = [Point(a, dim=2, **kwargs) for a in args]
+
+        # remove consecutive duplicates
+        nodup = []
+        for p in vertices:
+            if nodup and p == nodup[-1]:
+                continue
+            nodup.append(p)
+        if len(nodup) > 1 and nodup[-1] == nodup[0]:
+            nodup.pop()  # last point was same as first
+
+        # remove collinear points
+        i = -3
+        while i < len(nodup) - 3 and len(nodup) > 2:
+            a, b, c = nodup[i], nodup[i + 1], nodup[i + 2]
+            if Point.is_collinear(a, b, c):
+                nodup.pop(i + 1)
+                if a == c:
+                    nodup.pop(i)
+            else:
+                i += 1
+
+        vertices = list(nodup)
+
+        if len(vertices) > 3:
+            return GeometryEntity.__new__(cls, *vertices, **kwargs)
+        elif len(vertices) == 3:
+            return Triangle(*vertices, **kwargs)
+        elif len(vertices) == 2:
+            return Segment(*vertices, **kwargs)
+        else:
+            return Point(*vertices, **kwargs)
+
+    @property
+    def area(self):
+        """
+        The area of the polygon.
+
+        Notes
+        =====
+
+        The area calculation can be positive or negative based on the
+        orientation of the points. If any side of the polygon crosses
+        any other side, there will be areas having opposite signs.
+
+        See Also
+        ========
+
+        sympy.geometry.ellipse.Ellipse.area
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Polygon
+        >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
+        >>> poly = Polygon(p1, p2, p3, p4)
+        >>> poly.area
+        3
+
+        In the Z shaped polygon (with the lower right connecting back
+        to the upper left) the areas cancel out:
+
+        >>> Z = Polygon((0, 1), (1, 1), (0, 0), (1, 0))
+        >>> Z.area
+        0
+
+        In the M shaped polygon, areas do not cancel because no side
+        crosses any other (though there is a point of contact).
+
+        >>> M = Polygon((0, 0), (0, 1), (2, 0), (3, 1), (3, 0))
+        >>> M.area
+        -3/2
+
+        """
+        area = 0
+        args = self.args
+        for i in range(len(args)):
+            x1, y1 = args[i - 1].args
+            x2, y2 = args[i].args
+            area += x1*y2 - x2*y1
+        return simplify(area) / 2
+
+    @staticmethod
+    def _is_clockwise(a, b, c):
+        """Return True/False for cw/ccw orientation.
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Polygon
+        >>> a, b, c = [Point(i) for i in [(0, 0), (1, 1), (1, 0)]]
+        >>> Polygon._is_clockwise(a, b, c)
+        True
+        >>> Polygon._is_clockwise(a, c, b)
+        False
+        """
+        ba = b - a
+        ca = c - a
+        t_area = simplify(ba.x*ca.y - ca.x*ba.y)
+        res = t_area.is_nonpositive
+        if res is None:
+            raise ValueError("Can't determine orientation")
+        return res
+
+    @property
+    def angles(self):
+        """The internal angle at each vertex.
+
+        Returns
+        =======
+
+        angles : dict
+            A dictionary where each key is a vertex and each value is the
+            internal angle at that vertex. The vertices are represented as
+            Points.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point, sympy.geometry.line.LinearEntity.angle_between
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Polygon
+        >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
+        >>> poly = Polygon(p1, p2, p3, p4)
+        >>> poly.angles[p1]
+        pi/2
+        >>> poly.angles[p2]
+        acos(-4*sqrt(17)/17)
+
+        """
+
+        args = self.vertices
+        n = len(args)
+        ret = {}
+        for i in range(n):
+            a, b, c = args[i - 2], args[i - 1], args[i]
+            reflex_ang = Ray(b, a).angle_between(Ray(b, c))
+            if self._is_clockwise(a, b, c):
+                ret[b] = 2*S.Pi - reflex_ang
+            else:
+                ret[b] = reflex_ang
+
+        # internal sum should be pi*(n - 2), not pi*(n+2)
+        # so if ratio is (n+2)/(n-2) > 1 it is wrong
+        wrong = ((sum(ret.values())/S.Pi-1)/(n - 2) - 1).is_positive
+        if wrong:
+            two_pi = 2*S.Pi
+            for b in ret:
+                ret[b] = two_pi - ret[b]
+        elif wrong is None:
+            raise ValueError("could not determine Polygon orientation.")
+        return ret
+
+    @property
+    def ambient_dimension(self):
+        return self.vertices[0].ambient_dimension
+
+    @property
+    def perimeter(self):
+        """The perimeter of the polygon.
+
+        Returns
+        =======
+
+        perimeter : number or Basic instance
+
+        See Also
+        ========
+
+        sympy.geometry.line.Segment.length
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Polygon
+        >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
+        >>> poly = Polygon(p1, p2, p3, p4)
+        >>> poly.perimeter
+        sqrt(17) + 7
+        """
+        p = 0
+        args = self.vertices
+        for i in range(len(args)):
+            p += args[i - 1].distance(args[i])
+        return simplify(p)
+
+    @property
+    def vertices(self):
+        """The vertices of the polygon.
+
+        Returns
+        =======
+
+        vertices : list of Points
+
+        Notes
+        =====
+
+        When iterating over the vertices, it is more efficient to index self
+        rather than to request the vertices and index them. Only use the
+        vertices when you want to process all of them at once. This is even
+        more important with RegularPolygons that calculate each vertex.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Polygon
+        >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
+        >>> poly = Polygon(p1, p2, p3, p4)
+        >>> poly.vertices
+        [Point2D(0, 0), Point2D(1, 0), Point2D(5, 1), Point2D(0, 1)]
+        >>> poly.vertices[0]
+        Point2D(0, 0)
+
+        """
+        return list(self.args)
+
+    @property
+    def centroid(self):
+        """The centroid of the polygon.
+
+        Returns
+        =======
+
+        centroid : Point
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point, sympy.geometry.util.centroid
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Polygon
+        >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
+        >>> poly = Polygon(p1, p2, p3, p4)
+        >>> poly.centroid
+        Point2D(31/18, 11/18)
+
+        """
+        A = 1/(6*self.area)
+        cx, cy = 0, 0
+        args = self.args
+        for i in range(len(args)):
+            x1, y1 = args[i - 1].args
+            x2, y2 = args[i].args
+            v = x1*y2 - x2*y1
+            cx += v*(x1 + x2)
+            cy += v*(y1 + y2)
+        return Point(simplify(A*cx), simplify(A*cy))
+
+
+    def second_moment_of_area(self, point=None):
+        """Returns the second moment and product moment of area of a two dimensional polygon.
+
+        Parameters
+        ==========
+
+        point : Point, two-tuple of sympifyable objects, or None(default=None)
+            point is the point about which second moment of area is to be found.
+            If "point=None" it will be calculated about the axis passing through the
+            centroid of the polygon.
+
+        Returns
+        =======
+
+        I_xx, I_yy, I_xy : number or SymPy expression
+                           I_xx, I_yy are second moment of area of a two dimensional polygon.
+                           I_xy is product moment of area of a two dimensional polygon.
+
+        Examples
+        ========
+
+        >>> from sympy import Polygon, symbols
+        >>> a, b = symbols('a, b')
+        >>> p1, p2, p3, p4, p5 = [(0, 0), (a, 0), (a, b), (0, b), (a/3, b/3)]
+        >>> rectangle = Polygon(p1, p2, p3, p4)
+        >>> rectangle.second_moment_of_area()
+        (a*b**3/12, a**3*b/12, 0)
+        >>> rectangle.second_moment_of_area(p5)
+        (a*b**3/9, a**3*b/9, a**2*b**2/36)
+
+        References
+        ==========
+
+        .. [1] https://en.wikipedia.org/wiki/Second_moment_of_area
+
+        """
+
+        I_xx, I_yy, I_xy = 0, 0, 0
+        args = self.vertices
+        for i in range(len(args)):
+            x1, y1 = args[i-1].args
+            x2, y2 = args[i].args
+            v = x1*y2 - x2*y1
+            I_xx += (y1**2 + y1*y2 + y2**2)*v
+            I_yy += (x1**2 + x1*x2 + x2**2)*v
+            I_xy += (x1*y2 + 2*x1*y1 + 2*x2*y2 + x2*y1)*v
+        A = self.area
+        c_x = self.centroid[0]
+        c_y = self.centroid[1]
+        # parallel axis theorem
+        I_xx_c = (I_xx/12) - (A*(c_y**2))
+        I_yy_c = (I_yy/12) - (A*(c_x**2))
+        I_xy_c = (I_xy/24) - (A*(c_x*c_y))
+        if point is None:
+            return I_xx_c, I_yy_c, I_xy_c
+
+        I_xx = (I_xx_c + A*((point[1]-c_y)**2))
+        I_yy = (I_yy_c + A*((point[0]-c_x)**2))
+        I_xy = (I_xy_c + A*((point[0]-c_x)*(point[1]-c_y)))
+
+        return I_xx, I_yy, I_xy
+
+
+    def first_moment_of_area(self, point=None):
+        """
+        Returns the first moment of area of a two-dimensional polygon with
+        respect to a certain point of interest.
+
+        First moment of area is a measure of the distribution of the area
+        of a polygon in relation to an axis. The first moment of area of
+        the entire polygon about its own centroid is always zero. Therefore,
+        here it is calculated for an area, above or below a certain point
+        of interest, that makes up a smaller portion of the polygon. This
+        area is bounded by the point of interest and the extreme end
+        (top or bottom) of the polygon. The first moment for this area is
+        is then determined about the centroidal axis of the initial polygon.
+
+        References
+        ==========
+
+        .. [1] https://skyciv.com/docs/tutorials/section-tutorials/calculating-the-statical-or-first-moment-of-area-of-beam-sections/?cc=BMD
+        .. [2] https://mechanicalc.com/reference/cross-sections
+
+        Parameters
+        ==========
+
+        point: Point, two-tuple of sympifyable objects, or None (default=None)
+            point is the point above or below which the area of interest lies
+            If ``point=None`` then the centroid acts as the point of interest.
+
+        Returns
+        =======
+
+        Q_x, Q_y: number or SymPy expressions
+            Q_x is the first moment of area about the x-axis
+            Q_y is the first moment of area about the y-axis
+            A negative sign indicates that the section modulus is
+            determined for a section below (or left of) the centroidal axis
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Polygon
+        >>> a, b = 50, 10
+        >>> p1, p2, p3, p4 = [(0, b), (0, 0), (a, 0), (a, b)]
+        >>> p = Polygon(p1, p2, p3, p4)
+        >>> p.first_moment_of_area()
+        (625, 3125)
+        >>> p.first_moment_of_area(point=Point(30, 7))
+        (525, 3000)
+        """
+        if point:
+            xc, yc = self.centroid
+        else:
+            point = self.centroid
+            xc, yc = point
+
+        h_line = Line(point, slope=0)
+        v_line = Line(point, slope=S.Infinity)
+
+        h_poly = self.cut_section(h_line)
+        v_poly = self.cut_section(v_line)
+
+        poly_1 = h_poly[0] if h_poly[0].area <= h_poly[1].area else h_poly[1]
+        poly_2 = v_poly[0] if v_poly[0].area <= v_poly[1].area else v_poly[1]
+
+        Q_x = (poly_1.centroid.y - yc)*poly_1.area
+        Q_y = (poly_2.centroid.x - xc)*poly_2.area
+
+        return Q_x, Q_y
+
+
+    def polar_second_moment_of_area(self):
+        """Returns the polar modulus of a two-dimensional polygon
+
+        It is a constituent of the second moment of area, linked through
+        the perpendicular axis theorem. While the planar second moment of
+        area describes an object's resistance to deflection (bending) when
+        subjected to a force applied to a plane parallel to the central
+        axis, the polar second moment of area describes an object's
+        resistance to deflection when subjected to a moment applied in a
+        plane perpendicular to the object's central axis (i.e. parallel to
+        the cross-section)
+
+        Examples
+        ========
+
+        >>> from sympy import Polygon, symbols
+        >>> a, b = symbols('a, b')
+        >>> rectangle = Polygon((0, 0), (a, 0), (a, b), (0, b))
+        >>> rectangle.polar_second_moment_of_area()
+        a**3*b/12 + a*b**3/12
+
+        References
+        ==========
+
+        .. [1] https://en.wikipedia.org/wiki/Polar_moment_of_inertia
+
+        """
+        second_moment = self.second_moment_of_area()
+        return second_moment[0] + second_moment[1]
+
+
+    def section_modulus(self, point=None):
+        """Returns a tuple with the section modulus of a two-dimensional
+        polygon.
+
+        Section modulus is a geometric property of a polygon defined as the
+        ratio of second moment of area to the distance of the extreme end of
+        the polygon from the centroidal axis.
+
+        Parameters
+        ==========
+
+        point : Point, two-tuple of sympifyable objects, or None(default=None)
+            point is the point at which section modulus is to be found.
+            If "point=None" it will be calculated for the point farthest from the
+            centroidal axis of the polygon.
+
+        Returns
+        =======
+
+        S_x, S_y: numbers or SymPy expressions
+                  S_x is the section modulus with respect to the x-axis
+                  S_y is the section modulus with respect to the y-axis
+                  A negative sign indicates that the section modulus is
+                  determined for a point below the centroidal axis
+
+        Examples
+        ========
+
+        >>> from sympy import symbols, Polygon, Point
+        >>> a, b = symbols('a, b', positive=True)
+        >>> rectangle = Polygon((0, 0), (a, 0), (a, b), (0, b))
+        >>> rectangle.section_modulus()
+        (a*b**2/6, a**2*b/6)
+        >>> rectangle.section_modulus(Point(a/4, b/4))
+        (-a*b**2/3, -a**2*b/3)
+
+        References
+        ==========
+
+        .. [1] https://en.wikipedia.org/wiki/Section_modulus
+
+        """
+        x_c, y_c = self.centroid
+        if point is None:
+            # taking x and y as maximum distances from centroid
+            x_min, y_min, x_max, y_max = self.bounds
+            y = max(y_c - y_min, y_max - y_c)
+            x = max(x_c - x_min, x_max - x_c)
+        else:
+            # taking x and y as distances of the given point from the centroid
+            y = point.y - y_c
+            x = point.x - x_c
+
+        second_moment= self.second_moment_of_area()
+        S_x = second_moment[0]/y
+        S_y = second_moment[1]/x
+
+        return S_x, S_y
+
+
+    @property
+    def sides(self):
+        """The directed line segments that form the sides of the polygon.
+
+        Returns
+        =======
+
+        sides : list of sides
+            Each side is a directed Segment.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point, sympy.geometry.line.Segment
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Polygon
+        >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
+        >>> poly = Polygon(p1, p2, p3, p4)
+        >>> poly.sides
+        [Segment2D(Point2D(0, 0), Point2D(1, 0)),
+        Segment2D(Point2D(1, 0), Point2D(5, 1)),
+        Segment2D(Point2D(5, 1), Point2D(0, 1)), Segment2D(Point2D(0, 1), Point2D(0, 0))]
+
+        """
+        res = []
+        args = self.vertices
+        for i in range(-len(args), 0):
+            res.append(Segment(args[i], args[i + 1]))
+        return res
+
+    @property
+    def bounds(self):
+        """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding
+        rectangle for the geometric figure.
+
+        """
+
+        verts = self.vertices
+        xs = [p.x for p in verts]
+        ys = [p.y for p in verts]
+        return (min(xs), min(ys), max(xs), max(ys))
+
+    def is_convex(self):
+        """Is the polygon convex?
+
+        A polygon is convex if all its interior angles are less than 180
+        degrees and there are no intersections between sides.
+
+        Returns
+        =======
+
+        is_convex : boolean
+            True if this polygon is convex, False otherwise.
+
+        See Also
+        ========
+
+        sympy.geometry.util.convex_hull
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Polygon
+        >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
+        >>> poly = Polygon(p1, p2, p3, p4)
+        >>> poly.is_convex()
+        True
+
+        """
+        # Determine orientation of points
+        args = self.vertices
+        cw = self._is_clockwise(args[-2], args[-1], args[0])
+        for i in range(1, len(args)):
+            if cw ^ self._is_clockwise(args[i - 2], args[i - 1], args[i]):
+                return False
+        # check for intersecting sides
+        sides = self.sides
+        for i, si in enumerate(sides):
+            pts = si.args
+            # exclude the sides connected to si
+            for j in range(1 if i == len(sides) - 1 else 0, i - 1):
+                sj = sides[j]
+                if sj.p1 not in pts and sj.p2 not in pts:
+                    hit = si.intersection(sj)
+                    if hit:
+                        return False
+        return True
+
+    def encloses_point(self, p):
+        """
+        Return True if p is enclosed by (is inside of) self.
+
+        Notes
+        =====
+
+        Being on the border of self is considered False.
+
+        Parameters
+        ==========
+
+        p : Point
+
+        Returns
+        =======
+
+        encloses_point : True, False or None
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point, sympy.geometry.ellipse.Ellipse.encloses_point
+
+        Examples
+        ========
+
+        >>> from sympy import Polygon, Point
+        >>> p = Polygon((0, 0), (4, 0), (4, 4))
+        >>> p.encloses_point(Point(2, 1))
+        True
+        >>> p.encloses_point(Point(2, 2))
+        False
+        >>> p.encloses_point(Point(5, 5))
+        False
+
+        References
+        ==========
+
+        .. [1] https://paulbourke.net/geometry/polygonmesh/#insidepoly
+
+        """
+        p = Point(p, dim=2)
+        if p in self.vertices or any(p in s for s in self.sides):
+            return False
+
+        # move to p, checking that the result is numeric
+        lit = []
+        for v in self.vertices:
+            lit.append(v - p)  # the difference is simplified
+            if lit[-1].free_symbols:
+                return None
+
+        poly = Polygon(*lit)
+
+        # polygon closure is assumed in the following test but Polygon removes duplicate pts so
+        # the last point has to be added so all sides are computed. Using Polygon.sides is
+        # not good since Segments are unordered.
+        args = poly.args
+        indices = list(range(-len(args), 1))
+
+        if poly.is_convex():
+            orientation = None
+            for i in indices:
+                a = args[i]
+                b = args[i + 1]
+                test = ((-a.y)*(b.x - a.x) - (-a.x)*(b.y - a.y)).is_negative
+                if orientation is None:
+                    orientation = test
+                elif test is not orientation:
+                    return False
+            return True
+
+        hit_odd = False
+        p1x, p1y = args[0].args
+        for i in indices[1:]:
+            p2x, p2y = args[i].args
+            if 0 > min(p1y, p2y):
+                if 0 <= max(p1y, p2y):
+                    if 0 <= max(p1x, p2x):
+                        if p1y != p2y:
+                            xinters = (-p1y)*(p2x - p1x)/(p2y - p1y) + p1x
+                            if p1x == p2x or 0 <= xinters:
+                                hit_odd = not hit_odd
+            p1x, p1y = p2x, p2y
+        return hit_odd
+
+    def arbitrary_point(self, parameter='t'):
+        """A parameterized point on the polygon.
+
+        The parameter, varying from 0 to 1, assigns points to the position on
+        the perimeter that is that fraction of the total perimeter. So the
+        point evaluated at t=1/2 would return the point from the first vertex
+        that is 1/2 way around the polygon.
+
+        Parameters
+        ==========
+
+        parameter : str, optional
+            Default value is 't'.
+
+        Returns
+        =======
+
+        arbitrary_point : Point
+
+        Raises
+        ======
+
+        ValueError
+            When `parameter` already appears in the Polygon's definition.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point
+
+        Examples
+        ========
+
+        >>> from sympy import Polygon, Symbol
+        >>> t = Symbol('t', real=True)
+        >>> tri = Polygon((0, 0), (1, 0), (1, 1))
+        >>> p = tri.arbitrary_point('t')
+        >>> perimeter = tri.perimeter
+        >>> s1, s2 = [s.length for s in tri.sides[:2]]
+        >>> p.subs(t, (s1 + s2/2)/perimeter)
+        Point2D(1, 1/2)
+
+        """
+        t = _symbol(parameter, real=True)
+        if t.name in (f.name for f in self.free_symbols):
+            raise ValueError('Symbol %s already appears in object and cannot be used as a parameter.' % t.name)
+        sides = []
+        perimeter = self.perimeter
+        perim_fraction_start = 0
+        for s in self.sides:
+            side_perim_fraction = s.length/perimeter
+            perim_fraction_end = perim_fraction_start + side_perim_fraction
+            pt = s.arbitrary_point(parameter).subs(
+                t, (t - perim_fraction_start)/side_perim_fraction)
+            sides.append(
+                (pt, (And(perim_fraction_start <= t, t < perim_fraction_end))))
+            perim_fraction_start = perim_fraction_end
+        return Piecewise(*sides)
+
+    def parameter_value(self, other, t):
+        if not isinstance(other,GeometryEntity):
+            other = Point(other, dim=self.ambient_dimension)
+        if not isinstance(other,Point):
+            raise ValueError("other must be a point")
+        if other.free_symbols:
+            raise NotImplementedError('non-numeric coordinates')
+        unknown = False
+        p = self.arbitrary_point(T)
+        for pt, cond in p.args:
+            sol = solve(pt - other, T, dict=True)
+            if not sol:
+                continue
+            value = sol[0][T]
+            if simplify(cond.subs(T, value)) == True:
+                return {t: value}
+            unknown = True
+        if unknown:
+            raise ValueError("Given point may not be on %s" % func_name(self))
+        raise ValueError("Given point is not on %s" % func_name(self))
+
+    def plot_interval(self, parameter='t'):
+        """The plot interval for the default geometric plot of the polygon.
+
+        Parameters
+        ==========
+
+        parameter : str, optional
+            Default value is 't'.
+
+        Returns
+        =======
+
+        plot_interval : list (plot interval)
+            [parameter, lower_bound, upper_bound]
+
+        Examples
+        ========
+
+        >>> from sympy import Polygon
+        >>> p = Polygon((0, 0), (1, 0), (1, 1))
+        >>> p.plot_interval()
+        [t, 0, 1]
+
+        """
+        t = Symbol(parameter, real=True)
+        return [t, 0, 1]
+
+    def intersection(self, o):
+        """The intersection of polygon and geometry entity.
+
+        The intersection may be empty and can contain individual Points and
+        complete Line Segments.
+
+        Parameters
+        ==========
+
+        other: GeometryEntity
+
+        Returns
+        =======
+
+        intersection : list
+            The list of Segments and Points
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point, sympy.geometry.line.Segment
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Polygon, Line
+        >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
+        >>> poly1 = Polygon(p1, p2, p3, p4)
+        >>> p5, p6, p7 = map(Point, [(3, 2), (1, -1), (0, 2)])
+        >>> poly2 = Polygon(p5, p6, p7)
+        >>> poly1.intersection(poly2)
+        [Point2D(1/3, 1), Point2D(2/3, 0), Point2D(9/5, 1/5), Point2D(7/3, 1)]
+        >>> poly1.intersection(Line(p1, p2))
+        [Segment2D(Point2D(0, 0), Point2D(1, 0))]
+        >>> poly1.intersection(p1)
+        [Point2D(0, 0)]
+        """
+        intersection_result = []
+        k = o.sides if isinstance(o, Polygon) else [o]
+        for side in self.sides:
+            for side1 in k:
+                intersection_result.extend(side.intersection(side1))
+
+        intersection_result = list(uniq(intersection_result))
+        points = [entity for entity in intersection_result if isinstance(entity, Point)]
+        segments = [entity for entity in intersection_result if isinstance(entity, Segment)]
+
+        if points and segments:
+            points_in_segments = list(uniq([point for point in points for segment in segments if point in segment]))
+            if points_in_segments:
+                for i in points_in_segments:
+                    points.remove(i)
+            return list(ordered(segments + points))
+        else:
+            return list(ordered(intersection_result))
+
+
+    def cut_section(self, line):
+        """
+        Returns a tuple of two polygon segments that lie above and below
+        the intersecting line respectively.
+
+        Parameters
+        ==========
+
+        line: Line object of geometry module
+            line which cuts the Polygon. The part of the Polygon that lies
+            above and below this line is returned.
+
+        Returns
+        =======
+
+        upper_polygon, lower_polygon: Polygon objects or None
+            upper_polygon is the polygon that lies above the given line.
+            lower_polygon is the polygon that lies below the given line.
+            upper_polygon and lower polygon are ``None`` when no polygon
+            exists above the line or below the line.
+
+        Raises
+        ======
+
+        ValueError: When the line does not intersect the polygon
+
+        Examples
+        ========
+
+        >>> from sympy import Polygon, Line
+        >>> a, b = 20, 10
+        >>> p1, p2, p3, p4 = [(0, b), (0, 0), (a, 0), (a, b)]
+        >>> rectangle = Polygon(p1, p2, p3, p4)
+        >>> t = rectangle.cut_section(Line((0, 5), slope=0))
+        >>> t
+        (Polygon(Point2D(0, 10), Point2D(0, 5), Point2D(20, 5), Point2D(20, 10)),
+        Polygon(Point2D(0, 5), Point2D(0, 0), Point2D(20, 0), Point2D(20, 5)))
+        >>> upper_segment, lower_segment = t
+        >>> upper_segment.area
+        100
+        >>> upper_segment.centroid
+        Point2D(10, 15/2)
+        >>> lower_segment.centroid
+        Point2D(10, 5/2)
+
+        References
+        ==========
+
+        .. [1] https://github.com/sympy/sympy/wiki/A-method-to-return-a-cut-section-of-any-polygon-geometry
+
+        """
+        intersection_points = self.intersection(line)
+        if not intersection_points:
+            raise ValueError("This line does not intersect the polygon")
+
+        points = list(self.vertices)
+        points.append(points[0])
+
+        eq = line.equation(x, y)
+
+        # considering equation of line to be `ax +by + c`
+        a = eq.coeff(x)
+        b = eq.coeff(y)
+
+        upper_vertices = []
+        lower_vertices = []
+        # prev is true when previous point is above the line
+        prev = True
+        prev_point = None
+        for point in points:
+            # when coefficient of y is 0, right side of the line is
+            # considered
+            compare = eq.subs({x: point.x, y: point.y})/b if b \
+                    else eq.subs(x, point.x)/a
+
+            # if point lies above line
+            if compare > 0:
+                if not prev:
+                    # if previous point lies below the line, the intersection
+                    # point of the polygon edge and the line has to be included
+                    edge = Line(point, prev_point)
+                    new_point = edge.intersection(line)
+                    upper_vertices.append(new_point[0])
+                    lower_vertices.append(new_point[0])
+
+                upper_vertices.append(point)
+                prev = True
+            else:
+                if prev and prev_point:
+                    edge = Line(point, prev_point)
+                    new_point = edge.intersection(line)
+                    upper_vertices.append(new_point[0])
+                    lower_vertices.append(new_point[0])
+                lower_vertices.append(point)
+                prev = False
+            prev_point = point
+
+        upper_polygon, lower_polygon = None, None
+        if upper_vertices and isinstance(Polygon(*upper_vertices), Polygon):
+            upper_polygon = Polygon(*upper_vertices)
+        if lower_vertices and isinstance(Polygon(*lower_vertices), Polygon):
+            lower_polygon = Polygon(*lower_vertices)
+
+        return upper_polygon, lower_polygon
+
+
+    def distance(self, o):
+        """
+        Returns the shortest distance between self and o.
+
+        If o is a point, then self does not need to be convex.
+        If o is another polygon self and o must be convex.
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Polygon, RegularPolygon
+        >>> p1, p2 = map(Point, [(0, 0), (7, 5)])
+        >>> poly = Polygon(*RegularPolygon(p1, 1, 3).vertices)
+        >>> poly.distance(p2)
+        sqrt(61)
+        """
+        if isinstance(o, Point):
+            dist = oo
+            for side in self.sides:
+                current = side.distance(o)
+                if current == 0:
+                    return S.Zero
+                elif current < dist:
+                    dist = current
+            return dist
+        elif isinstance(o, Polygon) and self.is_convex() and o.is_convex():
+            return self._do_poly_distance(o)
+        raise NotImplementedError()
+
+    def _do_poly_distance(self, e2):
+        """
+        Calculates the least distance between the exteriors of two
+        convex polygons e1 and e2. Does not check for the convexity
+        of the polygons as this is checked by Polygon.distance.
+
+        Notes
+        =====
+
+            - Prints a warning if the two polygons possibly intersect as the return
+              value will not be valid in such a case. For a more through test of
+              intersection use intersection().
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point.distance
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Polygon
+        >>> square = Polygon(Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0))
+        >>> triangle = Polygon(Point(1, 2), Point(2, 2), Point(2, 1))
+        >>> square._do_poly_distance(triangle)
+        sqrt(2)/2
+
+        Description of method used
+        ==========================
+
+        Method:
+        [1] https://web.archive.org/web/20150509035744/http://cgm.cs.mcgill.ca/~orm/mind2p.html
+        Uses rotating calipers:
+        [2] https://en.wikipedia.org/wiki/Rotating_calipers
+        and antipodal points:
+        [3] https://en.wikipedia.org/wiki/Antipodal_point
+        """
+        e1 = self
+
+        '''Tests for a possible intersection between the polygons and outputs a warning'''
+        e1_center = e1.centroid
+        e2_center = e2.centroid
+        e1_max_radius = S.Zero
+        e2_max_radius = S.Zero
+        for vertex in e1.vertices:
+            r = Point.distance(e1_center, vertex)
+            if e1_max_radius < r:
+                e1_max_radius = r
+        for vertex in e2.vertices:
+            r = Point.distance(e2_center, vertex)
+            if e2_max_radius < r:
+                e2_max_radius = r
+        center_dist = Point.distance(e1_center, e2_center)
+        if center_dist <= e1_max_radius + e2_max_radius:
+            warnings.warn("Polygons may intersect producing erroneous output",
+                          stacklevel=3)
+
+        '''
+        Find the upper rightmost vertex of e1 and the lowest leftmost vertex of e2
+        '''
+        e1_ymax = Point(0, -oo)
+        e2_ymin = Point(0, oo)
+
+        for vertex in e1.vertices:
+            if vertex.y > e1_ymax.y or (vertex.y == e1_ymax.y and vertex.x > e1_ymax.x):
+                e1_ymax = vertex
+        for vertex in e2.vertices:
+            if vertex.y < e2_ymin.y or (vertex.y == e2_ymin.y and vertex.x < e2_ymin.x):
+                e2_ymin = vertex
+        min_dist = Point.distance(e1_ymax, e2_ymin)
+
+        '''
+        Produce a dictionary with vertices of e1 as the keys and, for each vertex, the points
+        to which the vertex is connected as its value. The same is then done for e2.
+        '''
+        e1_connections = {}
+        e2_connections = {}
+
+        for side in e1.sides:
+            if side.p1 in e1_connections:
+                e1_connections[side.p1].append(side.p2)
+            else:
+                e1_connections[side.p1] = [side.p2]
+
+            if side.p2 in e1_connections:
+                e1_connections[side.p2].append(side.p1)
+            else:
+                e1_connections[side.p2] = [side.p1]
+
+        for side in e2.sides:
+            if side.p1 in e2_connections:
+                e2_connections[side.p1].append(side.p2)
+            else:
+                e2_connections[side.p1] = [side.p2]
+
+            if side.p2 in e2_connections:
+                e2_connections[side.p2].append(side.p1)
+            else:
+                e2_connections[side.p2] = [side.p1]
+
+        e1_current = e1_ymax
+        e2_current = e2_ymin
+        support_line = Line(Point(S.Zero, S.Zero), Point(S.One, S.Zero))
+
+        '''
+        Determine which point in e1 and e2 will be selected after e2_ymin and e1_ymax,
+        this information combined with the above produced dictionaries determines the
+        path that will be taken around the polygons
+        '''
+        point1 = e1_connections[e1_ymax][0]
+        point2 = e1_connections[e1_ymax][1]
+        angle1 = support_line.angle_between(Line(e1_ymax, point1))
+        angle2 = support_line.angle_between(Line(e1_ymax, point2))
+        if angle1 < angle2:
+            e1_next = point1
+        elif angle2 < angle1:
+            e1_next = point2
+        elif Point.distance(e1_ymax, point1) > Point.distance(e1_ymax, point2):
+            e1_next = point2
+        else:
+            e1_next = point1
+
+        point1 = e2_connections[e2_ymin][0]
+        point2 = e2_connections[e2_ymin][1]
+        angle1 = support_line.angle_between(Line(e2_ymin, point1))
+        angle2 = support_line.angle_between(Line(e2_ymin, point2))
+        if angle1 > angle2:
+            e2_next = point1
+        elif angle2 > angle1:
+            e2_next = point2
+        elif Point.distance(e2_ymin, point1) > Point.distance(e2_ymin, point2):
+            e2_next = point2
+        else:
+            e2_next = point1
+
+        '''
+        Loop which determines the distance between anti-podal pairs and updates the
+        minimum distance accordingly. It repeats until it reaches the starting position.
+        '''
+        while True:
+            e1_angle = support_line.angle_between(Line(e1_current, e1_next))
+            e2_angle = pi - support_line.angle_between(Line(
+                e2_current, e2_next))
+
+            if (e1_angle < e2_angle) is True:
+                support_line = Line(e1_current, e1_next)
+                e1_segment = Segment(e1_current, e1_next)
+                min_dist_current = e1_segment.distance(e2_current)
+
+                if min_dist_current.evalf() < min_dist.evalf():
+                    min_dist = min_dist_current
+
+                if e1_connections[e1_next][0] != e1_current:
+                    e1_current = e1_next
+                    e1_next = e1_connections[e1_next][0]
+                else:
+                    e1_current = e1_next
+                    e1_next = e1_connections[e1_next][1]
+            elif (e1_angle > e2_angle) is True:
+                support_line = Line(e2_next, e2_current)
+                e2_segment = Segment(e2_current, e2_next)
+                min_dist_current = e2_segment.distance(e1_current)
+
+                if min_dist_current.evalf() < min_dist.evalf():
+                    min_dist = min_dist_current
+
+                if e2_connections[e2_next][0] != e2_current:
+                    e2_current = e2_next
+                    e2_next = e2_connections[e2_next][0]
+                else:
+                    e2_current = e2_next
+                    e2_next = e2_connections[e2_next][1]
+            else:
+                support_line = Line(e1_current, e1_next)
+                e1_segment = Segment(e1_current, e1_next)
+                e2_segment = Segment(e2_current, e2_next)
+                min1 = e1_segment.distance(e2_next)
+                min2 = e2_segment.distance(e1_next)
+
+                min_dist_current = min(min1, min2)
+                if min_dist_current.evalf() < min_dist.evalf():
+                    min_dist = min_dist_current
+
+                if e1_connections[e1_next][0] != e1_current:
+                    e1_current = e1_next
+                    e1_next = e1_connections[e1_next][0]
+                else:
+                    e1_current = e1_next
+                    e1_next = e1_connections[e1_next][1]
+
+                if e2_connections[e2_next][0] != e2_current:
+                    e2_current = e2_next
+                    e2_next = e2_connections[e2_next][0]
+                else:
+                    e2_current = e2_next
+                    e2_next = e2_connections[e2_next][1]
+            if e1_current == e1_ymax and e2_current == e2_ymin:
+                break
+        return min_dist
+
+    def _svg(self, scale_factor=1., fill_color="#66cc99"):
+        """Returns SVG path element for the Polygon.
+
+        Parameters
+        ==========
+
+        scale_factor : float
+            Multiplication factor for the SVG stroke-width.  Default is 1.
+        fill_color : str, optional
+            Hex string for fill color. Default is "#66cc99".
+        """
+        verts = map(N, self.vertices)
+        coords = ["{},{}".format(p.x, p.y) for p in verts]
+        path = "M {} L {} z".format(coords[0], " L ".join(coords[1:]))
+        return (
+            ''
+            ).format(2. * scale_factor, path, fill_color)
+
+    def _hashable_content(self):
+
+        D = {}
+        def ref_list(point_list):
+            kee = {}
+            for i, p in enumerate(ordered(set(point_list))):
+                kee[p] = i
+                D[i] = p
+            return [kee[p] for p in point_list]
+
+        S1 = ref_list(self.args)
+        r_nor = rotate_left(S1, least_rotation(S1))
+        S2 = ref_list(list(reversed(self.args)))
+        r_rev = rotate_left(S2, least_rotation(S2))
+        if r_nor < r_rev:
+            r = r_nor
+        else:
+            r = r_rev
+        canonical_args = [ D[order] for order in r ]
+        return tuple(canonical_args)
+
+    def __contains__(self, o):
+        """
+        Return True if o is contained within the boundary lines of self.altitudes
+
+        Parameters
+        ==========
+
+        other : GeometryEntity
+
+        Returns
+        =======
+
+        contained in : bool
+            The points (and sides, if applicable) are contained in self.
+
+        See Also
+        ========
+
+        sympy.geometry.entity.GeometryEntity.encloses
+
+        Examples
+        ========
+
+        >>> from sympy import Line, Segment, Point
+        >>> p = Point(0, 0)
+        >>> q = Point(1, 1)
+        >>> s = Segment(p, q*2)
+        >>> l = Line(p, q)
+        >>> p in q
+        False
+        >>> p in s
+        True
+        >>> q*3 in s
+        False
+        >>> s in l
+        True
+
+        """
+
+        if isinstance(o, Polygon):
+            return self == o
+        elif isinstance(o, Segment):
+            return any(o in s for s in self.sides)
+        elif isinstance(o, Point):
+            if o in self.vertices:
+                return True
+            for side in self.sides:
+                if o in side:
+                    return True
+
+        return False
+
+    def bisectors(p, prec=None):
+        """Returns angle bisectors of a polygon. If prec is given
+        then approximate the point defining the ray to that precision.
+
+        The distance between the points defining the bisector ray is 1.
+
+        Examples
+        ========
+
+        >>> from sympy import Polygon, Point
+        >>> p = Polygon(Point(0, 0), Point(2, 0), Point(1, 1), Point(0, 3))
+        >>> p.bisectors(2)
+        {Point2D(0, 0): Ray2D(Point2D(0, 0), Point2D(0.71, 0.71)),
+         Point2D(0, 3): Ray2D(Point2D(0, 3), Point2D(0.23, 2.0)),
+         Point2D(1, 1): Ray2D(Point2D(1, 1), Point2D(0.19, 0.42)),
+         Point2D(2, 0): Ray2D(Point2D(2, 0), Point2D(1.1, 0.38))}
+        """
+        b = {}
+        pts = list(p.args)
+        pts.append(pts[0])  # close it
+        cw = Polygon._is_clockwise(*pts[:3])
+        if cw:
+            pts = list(reversed(pts))
+        for v, a in p.angles.items():
+            i = pts.index(v)
+            p1, p2 = Point._normalize_dimension(pts[i], pts[i + 1])
+            ray = Ray(p1, p2).rotate(a/2, v)
+            dir = ray.direction
+            ray = Ray(ray.p1, ray.p1 + dir/dir.distance((0, 0)))
+            if prec is not None:
+                ray = Ray(ray.p1, ray.p2.n(prec))
+            b[v] = ray
+        return b
+
+
+class RegularPolygon(Polygon):
+    """
+    A regular polygon.
+
+    Such a polygon has all internal angles equal and all sides the same length.
+
+    Parameters
+    ==========
+
+    center : Point
+    radius : number or Basic instance
+        The distance from the center to a vertex
+    n : int
+        The number of sides
+
+    Attributes
+    ==========
+
+    vertices
+    center
+    radius
+    rotation
+    apothem
+    interior_angle
+    exterior_angle
+    circumcircle
+    incircle
+    angles
+
+    Raises
+    ======
+
+    GeometryError
+        If the `center` is not a Point, or the `radius` is not a number or Basic
+        instance, or the number of sides, `n`, is less than three.
+
+    Notes
+    =====
+
+    A RegularPolygon can be instantiated with Polygon with the kwarg n.
+
+    Regular polygons are instantiated with a center, radius, number of sides
+    and a rotation angle. Whereas the arguments of a Polygon are vertices, the
+    vertices of the RegularPolygon must be obtained with the vertices method.
+
+    See Also
+    ========
+
+    sympy.geometry.point.Point, Polygon
+
+    Examples
+    ========
+
+    >>> from sympy import RegularPolygon, Point
+    >>> r = RegularPolygon(Point(0, 0), 5, 3)
+    >>> r
+    RegularPolygon(Point2D(0, 0), 5, 3, 0)
+    >>> r.vertices[0]
+    Point2D(5, 0)
+
+    """
+
+    __slots__ = ('_n', '_center', '_radius', '_rot')
+
+    def __new__(self, c, r, n, rot=0, **kwargs):
+        r, n, rot = map(sympify, (r, n, rot))
+        c = Point(c, dim=2, **kwargs)
+        if not isinstance(r, Expr):
+            raise GeometryError("r must be an Expr object, not %s" % r)
+        if n.is_Number:
+            as_int(n)  # let an error raise if necessary
+            if n < 3:
+                raise GeometryError("n must be a >= 3, not %s" % n)
+
+        obj = GeometryEntity.__new__(self, c, r, n, **kwargs)
+        obj._n = n
+        obj._center = c
+        obj._radius = r
+        obj._rot = rot % (2*S.Pi/n) if rot.is_number else rot
+        return obj
+
+    def _eval_evalf(self, prec=15, **options):
+        c, r, n, a = self.args
+        dps = prec_to_dps(prec)
+        c, r, a = [i.evalf(n=dps, **options) for i in (c, r, a)]
+        return self.func(c, r, n, a)
+
+    @property
+    def args(self):
+        """
+        Returns the center point, the radius,
+        the number of sides, and the orientation angle.
+
+        Examples
+        ========
+
+        >>> from sympy import RegularPolygon, Point
+        >>> r = RegularPolygon(Point(0, 0), 5, 3)
+        >>> r.args
+        (Point2D(0, 0), 5, 3, 0)
+        """
+        return self._center, self._radius, self._n, self._rot
+
+    def __str__(self):
+        return 'RegularPolygon(%s, %s, %s, %s)' % tuple(self.args)
+
+    def __repr__(self):
+        return 'RegularPolygon(%s, %s, %s, %s)' % tuple(self.args)
+
+    @property
+    def area(self):
+        """Returns the area.
+
+        Examples
+        ========
+
+        >>> from sympy import RegularPolygon
+        >>> square = RegularPolygon((0, 0), 1, 4)
+        >>> square.area
+        2
+        >>> _ == square.length**2
+        True
+        """
+        c, r, n, rot = self.args
+        return sign(r)*n*self.length**2/(4*tan(pi/n))
+
+    @property
+    def length(self):
+        """Returns the length of the sides.
+
+        The half-length of the side and the apothem form two legs
+        of a right triangle whose hypotenuse is the radius of the
+        regular polygon.
+
+        Examples
+        ========
+
+        >>> from sympy import RegularPolygon
+        >>> from sympy import sqrt
+        >>> s = square_in_unit_circle = RegularPolygon((0, 0), 1, 4)
+        >>> s.length
+        sqrt(2)
+        >>> sqrt((_/2)**2 + s.apothem**2) == s.radius
+        True
+
+        """
+        return self.radius*2*sin(pi/self._n)
+
+    @property
+    def center(self):
+        """The center of the RegularPolygon
+
+        This is also the center of the circumscribing circle.
+
+        Returns
+        =======
+
+        center : Point
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point, sympy.geometry.ellipse.Ellipse.center
+
+        Examples
+        ========
+
+        >>> from sympy import RegularPolygon, Point
+        >>> rp = RegularPolygon(Point(0, 0), 5, 4)
+        >>> rp.center
+        Point2D(0, 0)
+        """
+        return self._center
+
+    centroid = center
+
+    @property
+    def circumcenter(self):
+        """
+        Alias for center.
+
+        Examples
+        ========
+
+        >>> from sympy import RegularPolygon, Point
+        >>> rp = RegularPolygon(Point(0, 0), 5, 4)
+        >>> rp.circumcenter
+        Point2D(0, 0)
+        """
+        return self.center
+
+    @property
+    def radius(self):
+        """Radius of the RegularPolygon
+
+        This is also the radius of the circumscribing circle.
+
+        Returns
+        =======
+
+        radius : number or instance of Basic
+
+        See Also
+        ========
+
+        sympy.geometry.line.Segment.length, sympy.geometry.ellipse.Circle.radius
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy import RegularPolygon, Point
+        >>> radius = Symbol('r')
+        >>> rp = RegularPolygon(Point(0, 0), radius, 4)
+        >>> rp.radius
+        r
+
+        """
+        return self._radius
+
+    @property
+    def circumradius(self):
+        """
+        Alias for radius.
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy import RegularPolygon, Point
+        >>> radius = Symbol('r')
+        >>> rp = RegularPolygon(Point(0, 0), radius, 4)
+        >>> rp.circumradius
+        r
+        """
+        return self.radius
+
+    @property
+    def rotation(self):
+        """CCW angle by which the RegularPolygon is rotated
+
+        Returns
+        =======
+
+        rotation : number or instance of Basic
+
+        Examples
+        ========
+
+        >>> from sympy import pi
+        >>> from sympy.abc import a
+        >>> from sympy import RegularPolygon, Point
+        >>> RegularPolygon(Point(0, 0), 3, 4, pi/4).rotation
+        pi/4
+
+        Numerical rotation angles are made canonical:
+
+        >>> RegularPolygon(Point(0, 0), 3, 4, a).rotation
+        a
+        >>> RegularPolygon(Point(0, 0), 3, 4, pi).rotation
+        0
+
+        """
+        return self._rot
+
+    @property
+    def apothem(self):
+        """The inradius of the RegularPolygon.
+
+        The apothem/inradius is the radius of the inscribed circle.
+
+        Returns
+        =======
+
+        apothem : number or instance of Basic
+
+        See Also
+        ========
+
+        sympy.geometry.line.Segment.length, sympy.geometry.ellipse.Circle.radius
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy import RegularPolygon, Point
+        >>> radius = Symbol('r')
+        >>> rp = RegularPolygon(Point(0, 0), radius, 4)
+        >>> rp.apothem
+        sqrt(2)*r/2
+
+        """
+        return self.radius * cos(S.Pi/self._n)
+
+    @property
+    def inradius(self):
+        """
+        Alias for apothem.
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy import RegularPolygon, Point
+        >>> radius = Symbol('r')
+        >>> rp = RegularPolygon(Point(0, 0), radius, 4)
+        >>> rp.inradius
+        sqrt(2)*r/2
+        """
+        return self.apothem
+
+    @property
+    def interior_angle(self):
+        """Measure of the interior angles.
+
+        Returns
+        =======
+
+        interior_angle : number
+
+        See Also
+        ========
+
+        sympy.geometry.line.LinearEntity.angle_between
+
+        Examples
+        ========
+
+        >>> from sympy import RegularPolygon, Point
+        >>> rp = RegularPolygon(Point(0, 0), 4, 8)
+        >>> rp.interior_angle
+        3*pi/4
+
+        """
+        return (self._n - 2)*S.Pi/self._n
+
+    @property
+    def exterior_angle(self):
+        """Measure of the exterior angles.
+
+        Returns
+        =======
+
+        exterior_angle : number
+
+        See Also
+        ========
+
+        sympy.geometry.line.LinearEntity.angle_between
+
+        Examples
+        ========
+
+        >>> from sympy import RegularPolygon, Point
+        >>> rp = RegularPolygon(Point(0, 0), 4, 8)
+        >>> rp.exterior_angle
+        pi/4
+
+        """
+        return 2*S.Pi/self._n
+
+    @property
+    def circumcircle(self):
+        """The circumcircle of the RegularPolygon.
+
+        Returns
+        =======
+
+        circumcircle : Circle
+
+        See Also
+        ========
+
+        circumcenter, sympy.geometry.ellipse.Circle
+
+        Examples
+        ========
+
+        >>> from sympy import RegularPolygon, Point
+        >>> rp = RegularPolygon(Point(0, 0), 4, 8)
+        >>> rp.circumcircle
+        Circle(Point2D(0, 0), 4)
+
+        """
+        return Circle(self.center, self.radius)
+
+    @property
+    def incircle(self):
+        """The incircle of the RegularPolygon.
+
+        Returns
+        =======
+
+        incircle : Circle
+
+        See Also
+        ========
+
+        inradius, sympy.geometry.ellipse.Circle
+
+        Examples
+        ========
+
+        >>> from sympy import RegularPolygon, Point
+        >>> rp = RegularPolygon(Point(0, 0), 4, 7)
+        >>> rp.incircle
+        Circle(Point2D(0, 0), 4*cos(pi/7))
+
+        """
+        return Circle(self.center, self.apothem)
+
+    @property
+    def angles(self):
+        """
+        Returns a dictionary with keys, the vertices of the Polygon,
+        and values, the interior angle at each vertex.
+
+        Examples
+        ========
+
+        >>> from sympy import RegularPolygon, Point
+        >>> r = RegularPolygon(Point(0, 0), 5, 3)
+        >>> r.angles
+        {Point2D(-5/2, -5*sqrt(3)/2): pi/3,
+         Point2D(-5/2, 5*sqrt(3)/2): pi/3,
+         Point2D(5, 0): pi/3}
+        """
+        ret = {}
+        ang = self.interior_angle
+        for v in self.vertices:
+            ret[v] = ang
+        return ret
+
+    def encloses_point(self, p):
+        """
+        Return True if p is enclosed by (is inside of) self.
+
+        Notes
+        =====
+
+        Being on the border of self is considered False.
+
+        The general Polygon.encloses_point method is called only if
+        a point is not within or beyond the incircle or circumcircle,
+        respectively.
+
+        Parameters
+        ==========
+
+        p : Point
+
+        Returns
+        =======
+
+        encloses_point : True, False or None
+
+        See Also
+        ========
+
+        sympy.geometry.ellipse.Ellipse.encloses_point
+
+        Examples
+        ========
+
+        >>> from sympy import RegularPolygon, S, Point, Symbol
+        >>> p = RegularPolygon((0, 0), 3, 4)
+        >>> p.encloses_point(Point(0, 0))
+        True
+        >>> r, R = p.inradius, p.circumradius
+        >>> p.encloses_point(Point((r + R)/2, 0))
+        True
+        >>> p.encloses_point(Point(R/2, R/2 + (R - r)/10))
+        False
+        >>> t = Symbol('t', real=True)
+        >>> p.encloses_point(p.arbitrary_point().subs(t, S.Half))
+        False
+        >>> p.encloses_point(Point(5, 5))
+        False
+
+        """
+
+        c = self.center
+        d = Segment(c, p).length
+        if d >= self.radius:
+            return False
+        elif d < self.inradius:
+            return True
+        else:
+            # now enumerate the RegularPolygon like a general polygon.
+            return Polygon.encloses_point(self, p)
+
+    def spin(self, angle):
+        """Increment *in place* the virtual Polygon's rotation by ccw angle.
+
+        See also: rotate method which moves the center.
+
+        >>> from sympy import Polygon, Point, pi
+        >>> r = Polygon(Point(0,0), 1, n=3)
+        >>> r.vertices[0]
+        Point2D(1, 0)
+        >>> r.spin(pi/6)
+        >>> r.vertices[0]
+        Point2D(sqrt(3)/2, 1/2)
+
+        See Also
+        ========
+
+        rotation
+        rotate : Creates a copy of the RegularPolygon rotated about a Point
+
+        """
+        self._rot += angle
+
+    def rotate(self, angle, pt=None):
+        """Override GeometryEntity.rotate to first rotate the RegularPolygon
+        about its center.
+
+        >>> from sympy import Point, RegularPolygon, pi
+        >>> t = RegularPolygon(Point(1, 0), 1, 3)
+        >>> t.vertices[0] # vertex on x-axis
+        Point2D(2, 0)
+        >>> t.rotate(pi/2).vertices[0] # vertex on y axis now
+        Point2D(0, 2)
+
+        See Also
+        ========
+
+        rotation
+        spin : Rotates a RegularPolygon in place
+
+        """
+
+        r = type(self)(*self.args)  # need a copy or else changes are in-place
+        r._rot += angle
+        return GeometryEntity.rotate(r, angle, pt)
+
+    def scale(self, x=1, y=1, pt=None):
+        """Override GeometryEntity.scale since it is the radius that must be
+        scaled (if x == y) or else a new Polygon must be returned.
+
+        >>> from sympy import RegularPolygon
+
+        Symmetric scaling returns a RegularPolygon:
+
+        >>> RegularPolygon((0, 0), 1, 4).scale(2, 2)
+        RegularPolygon(Point2D(0, 0), 2, 4, 0)
+
+        Asymmetric scaling returns a kite as a Polygon:
+
+        >>> RegularPolygon((0, 0), 1, 4).scale(2, 1)
+        Polygon(Point2D(2, 0), Point2D(0, 1), Point2D(-2, 0), Point2D(0, -1))
+
+        """
+        if pt:
+            pt = Point(pt, dim=2)
+            return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
+        if x != y:
+            return Polygon(*self.vertices).scale(x, y)
+        c, r, n, rot = self.args
+        r *= x
+        return self.func(c, r, n, rot)
+
+    def reflect(self, line):
+        """Override GeometryEntity.reflect since this is not made of only
+        points.
+
+        Examples
+        ========
+
+        >>> from sympy import RegularPolygon, Line
+
+        >>> RegularPolygon((0, 0), 1, 4).reflect(Line((0, 1), slope=-2))
+        RegularPolygon(Point2D(4/5, 2/5), -1, 4, atan(4/3))
+
+        """
+        c, r, n, rot = self.args
+        v = self.vertices[0]
+        d = v - c
+        cc = c.reflect(line)
+        vv = v.reflect(line)
+        dd = vv - cc
+        # calculate rotation about the new center
+        # which will align the vertices
+        l1 = Ray((0, 0), dd)
+        l2 = Ray((0, 0), d)
+        ang = l1.closing_angle(l2)
+        rot += ang
+        # change sign of radius as point traversal is reversed
+        return self.func(cc, -r, n, rot)
+
+    @property
+    def vertices(self):
+        """The vertices of the RegularPolygon.
+
+        Returns
+        =======
+
+        vertices : list
+            Each vertex is a Point.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point
+
+        Examples
+        ========
+
+        >>> from sympy import RegularPolygon, Point
+        >>> rp = RegularPolygon(Point(0, 0), 5, 4)
+        >>> rp.vertices
+        [Point2D(5, 0), Point2D(0, 5), Point2D(-5, 0), Point2D(0, -5)]
+
+        """
+        c = self._center
+        r = abs(self._radius)
+        rot = self._rot
+        v = 2*S.Pi/self._n
+
+        return [Point(c.x + r*cos(k*v + rot), c.y + r*sin(k*v + rot))
+                for k in range(self._n)]
+
+    def __eq__(self, o):
+        if not isinstance(o, Polygon):
+            return False
+        elif not isinstance(o, RegularPolygon):
+            return Polygon.__eq__(o, self)
+        return self.args == o.args
+
+    def __hash__(self):
+        return super().__hash__()
+
+
+class Triangle(Polygon):
+    """
+    A polygon with three vertices and three sides.
+
+    Parameters
+    ==========
+
+    points : sequence of Points
+    keyword: asa, sas, or sss to specify sides/angles of the triangle
+
+    Attributes
+    ==========
+
+    vertices
+    altitudes
+    orthocenter
+    circumcenter
+    circumradius
+    circumcircle
+    inradius
+    incircle
+    exradii
+    medians
+    medial
+    nine_point_circle
+
+    Raises
+    ======
+
+    GeometryError
+        If the number of vertices is not equal to three, or one of the vertices
+        is not a Point, or a valid keyword is not given.
+
+    See Also
+    ========
+
+    sympy.geometry.point.Point, Polygon
+
+    Examples
+    ========
+
+    >>> from sympy import Triangle, Point
+    >>> Triangle(Point(0, 0), Point(4, 0), Point(4, 3))
+    Triangle(Point2D(0, 0), Point2D(4, 0), Point2D(4, 3))
+
+    Keywords sss, sas, or asa can be used to give the desired
+    side lengths (in order) and interior angles (in degrees) that
+    define the triangle:
+
+    >>> Triangle(sss=(3, 4, 5))
+    Triangle(Point2D(0, 0), Point2D(3, 0), Point2D(3, 4))
+    >>> Triangle(asa=(30, 1, 30))
+    Triangle(Point2D(0, 0), Point2D(1, 0), Point2D(1/2, sqrt(3)/6))
+    >>> Triangle(sas=(1, 45, 2))
+    Triangle(Point2D(0, 0), Point2D(2, 0), Point2D(sqrt(2)/2, sqrt(2)/2))
+
+    """
+
+    def __new__(cls, *args, **kwargs):
+        if len(args) != 3:
+            if 'sss' in kwargs:
+                return _sss(*[simplify(a) for a in kwargs['sss']])
+            if 'asa' in kwargs:
+                return _asa(*[simplify(a) for a in kwargs['asa']])
+            if 'sas' in kwargs:
+                return _sas(*[simplify(a) for a in kwargs['sas']])
+            msg = "Triangle instantiates with three points or a valid keyword."
+            raise GeometryError(msg)
+
+        vertices = [Point(a, dim=2, **kwargs) for a in args]
+
+        # remove consecutive duplicates
+        nodup = []
+        for p in vertices:
+            if nodup and p == nodup[-1]:
+                continue
+            nodup.append(p)
+        if len(nodup) > 1 and nodup[-1] == nodup[0]:
+            nodup.pop()  # last point was same as first
+
+        # remove collinear points
+        i = -3
+        while i < len(nodup) - 3 and len(nodup) > 2:
+            a, b, c = sorted(
+                [nodup[i], nodup[i + 1], nodup[i + 2]], key=default_sort_key)
+            if Point.is_collinear(a, b, c):
+                nodup[i] = a
+                nodup[i + 1] = None
+                nodup.pop(i + 1)
+            i += 1
+
+        vertices = list(filter(lambda x: x is not None, nodup))
+
+        if len(vertices) == 3:
+            return GeometryEntity.__new__(cls, *vertices, **kwargs)
+        elif len(vertices) == 2:
+            return Segment(*vertices, **kwargs)
+        else:
+            return Point(*vertices, **kwargs)
+
+    @property
+    def vertices(self):
+        """The triangle's vertices
+
+        Returns
+        =======
+
+        vertices : tuple
+            Each element in the tuple is a Point
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point
+
+        Examples
+        ========
+
+        >>> from sympy import Triangle, Point
+        >>> t = Triangle(Point(0, 0), Point(4, 0), Point(4, 3))
+        >>> t.vertices
+        (Point2D(0, 0), Point2D(4, 0), Point2D(4, 3))
+
+        """
+        return self.args
+
+    def is_similar(t1, t2):
+        """Is another triangle similar to this one.
+
+        Two triangles are similar if one can be uniformly scaled to the other.
+
+        Parameters
+        ==========
+
+        other: Triangle
+
+        Returns
+        =======
+
+        is_similar : boolean
+
+        See Also
+        ========
+
+        sympy.geometry.entity.GeometryEntity.is_similar
+
+        Examples
+        ========
+
+        >>> from sympy import Triangle, Point
+        >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(4, 3))
+        >>> t2 = Triangle(Point(0, 0), Point(-4, 0), Point(-4, -3))
+        >>> t1.is_similar(t2)
+        True
+
+        >>> t2 = Triangle(Point(0, 0), Point(-4, 0), Point(-4, -4))
+        >>> t1.is_similar(t2)
+        False
+
+        """
+        if not isinstance(t2, Polygon):
+            return False
+
+        s1_1, s1_2, s1_3 = [side.length for side in t1.sides]
+        s2 = [side.length for side in t2.sides]
+
+        def _are_similar(u1, u2, u3, v1, v2, v3):
+            e1 = simplify(u1/v1)
+            e2 = simplify(u2/v2)
+            e3 = simplify(u3/v3)
+            return bool(e1 == e2) and bool(e2 == e3)
+
+        # There's only 6 permutations, so write them out
+        return _are_similar(s1_1, s1_2, s1_3, *s2) or \
+            _are_similar(s1_1, s1_3, s1_2, *s2) or \
+            _are_similar(s1_2, s1_1, s1_3, *s2) or \
+            _are_similar(s1_2, s1_3, s1_1, *s2) or \
+            _are_similar(s1_3, s1_1, s1_2, *s2) or \
+            _are_similar(s1_3, s1_2, s1_1, *s2)
+
+    def is_equilateral(self):
+        """Are all the sides the same length?
+
+        Returns
+        =======
+
+        is_equilateral : boolean
+
+        See Also
+        ========
+
+        sympy.geometry.entity.GeometryEntity.is_similar, RegularPolygon
+        is_isosceles, is_right, is_scalene
+
+        Examples
+        ========
+
+        >>> from sympy import Triangle, Point
+        >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(4, 3))
+        >>> t1.is_equilateral()
+        False
+
+        >>> from sympy import sqrt
+        >>> t2 = Triangle(Point(0, 0), Point(10, 0), Point(5, 5*sqrt(3)))
+        >>> t2.is_equilateral()
+        True
+
+        """
+        return not has_variety(s.length for s in self.sides)
+
+    def is_isosceles(self):
+        """Are two or more of the sides the same length?
+
+        Returns
+        =======
+
+        is_isosceles : boolean
+
+        See Also
+        ========
+
+        is_equilateral, is_right, is_scalene
+
+        Examples
+        ========
+
+        >>> from sympy import Triangle, Point
+        >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(2, 4))
+        >>> t1.is_isosceles()
+        True
+
+        """
+        return has_dups(s.length for s in self.sides)
+
+    def is_scalene(self):
+        """Are all the sides of the triangle of different lengths?
+
+        Returns
+        =======
+
+        is_scalene : boolean
+
+        See Also
+        ========
+
+        is_equilateral, is_isosceles, is_right
+
+        Examples
+        ========
+
+        >>> from sympy import Triangle, Point
+        >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(1, 4))
+        >>> t1.is_scalene()
+        True
+
+        """
+        return not has_dups(s.length for s in self.sides)
+
+    def is_right(self):
+        """Is the triangle right-angled.
+
+        Returns
+        =======
+
+        is_right : boolean
+
+        See Also
+        ========
+
+        sympy.geometry.line.LinearEntity.is_perpendicular
+        is_equilateral, is_isosceles, is_scalene
+
+        Examples
+        ========
+
+        >>> from sympy import Triangle, Point
+        >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(4, 3))
+        >>> t1.is_right()
+        True
+
+        """
+        s = self.sides
+        return Segment.is_perpendicular(s[0], s[1]) or \
+            Segment.is_perpendicular(s[1], s[2]) or \
+            Segment.is_perpendicular(s[0], s[2])
+
+    @property
+    def altitudes(self):
+        """The altitudes of the triangle.
+
+        An altitude of a triangle is a segment through a vertex,
+        perpendicular to the opposite side, with length being the
+        height of the vertex measured from the line containing the side.
+
+        Returns
+        =======
+
+        altitudes : dict
+            The dictionary consists of keys which are vertices and values
+            which are Segments.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point, sympy.geometry.line.Segment.length
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Triangle
+        >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
+        >>> t = Triangle(p1, p2, p3)
+        >>> t.altitudes[p1]
+        Segment2D(Point2D(0, 0), Point2D(1/2, 1/2))
+
+        """
+        s = self.sides
+        v = self.vertices
+        return {v[0]: s[1].perpendicular_segment(v[0]),
+                v[1]: s[2].perpendicular_segment(v[1]),
+                v[2]: s[0].perpendicular_segment(v[2])}
+
+    @property
+    def orthocenter(self):
+        """The orthocenter of the triangle.
+
+        The orthocenter is the intersection of the altitudes of a triangle.
+        It may lie inside, outside or on the triangle.
+
+        Returns
+        =======
+
+        orthocenter : Point
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Triangle
+        >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
+        >>> t = Triangle(p1, p2, p3)
+        >>> t.orthocenter
+        Point2D(0, 0)
+
+        """
+        a = self.altitudes
+        v = self.vertices
+        return Line(a[v[0]]).intersection(Line(a[v[1]]))[0]
+
+    @property
+    def circumcenter(self):
+        """The circumcenter of the triangle
+
+        The circumcenter is the center of the circumcircle.
+
+        Returns
+        =======
+
+        circumcenter : Point
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Triangle
+        >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
+        >>> t = Triangle(p1, p2, p3)
+        >>> t.circumcenter
+        Point2D(1/2, 1/2)
+        """
+        a, b, c = [x.perpendicular_bisector() for x in self.sides]
+        return a.intersection(b)[0]
+
+    @property
+    def circumradius(self):
+        """The radius of the circumcircle of the triangle.
+
+        Returns
+        =======
+
+        circumradius : number of Basic instance
+
+        See Also
+        ========
+
+        sympy.geometry.ellipse.Circle.radius
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy import Point, Triangle
+        >>> a = Symbol('a')
+        >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, a)
+        >>> t = Triangle(p1, p2, p3)
+        >>> t.circumradius
+        sqrt(a**2/4 + 1/4)
+        """
+        return Point.distance(self.circumcenter, self.vertices[0])
+
+    @property
+    def circumcircle(self):
+        """The circle which passes through the three vertices of the triangle.
+
+        Returns
+        =======
+
+        circumcircle : Circle
+
+        See Also
+        ========
+
+        sympy.geometry.ellipse.Circle
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Triangle
+        >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
+        >>> t = Triangle(p1, p2, p3)
+        >>> t.circumcircle
+        Circle(Point2D(1/2, 1/2), sqrt(2)/2)
+
+        """
+        return Circle(self.circumcenter, self.circumradius)
+
+    def bisectors(self):
+        """The angle bisectors of the triangle.
+
+        An angle bisector of a triangle is a straight line through a vertex
+        which cuts the corresponding angle in half.
+
+        Returns
+        =======
+
+        bisectors : dict
+            Each key is a vertex (Point) and each value is the corresponding
+            bisector (Segment).
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point, sympy.geometry.line.Segment
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Triangle, Segment
+        >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
+        >>> t = Triangle(p1, p2, p3)
+        >>> from sympy import sqrt
+        >>> t.bisectors()[p2] == Segment(Point(1, 0), Point(0, sqrt(2) - 1))
+        True
+
+        """
+        # use lines containing sides so containment check during
+        # intersection calculation can be avoided, thus reducing
+        # the processing time for calculating the bisectors
+        s = [Line(l) for l in self.sides]
+        v = self.vertices
+        c = self.incenter
+        l1 = Segment(v[0], Line(v[0], c).intersection(s[1])[0])
+        l2 = Segment(v[1], Line(v[1], c).intersection(s[2])[0])
+        l3 = Segment(v[2], Line(v[2], c).intersection(s[0])[0])
+        return {v[0]: l1, v[1]: l2, v[2]: l3}
+
+    @property
+    def incenter(self):
+        """The center of the incircle.
+
+        The incircle is the circle which lies inside the triangle and touches
+        all three sides.
+
+        Returns
+        =======
+
+        incenter : Point
+
+        See Also
+        ========
+
+        incircle, sympy.geometry.point.Point
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Triangle
+        >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
+        >>> t = Triangle(p1, p2, p3)
+        >>> t.incenter
+        Point2D(1 - sqrt(2)/2, 1 - sqrt(2)/2)
+
+        """
+        s = self.sides
+        l = Matrix([s[i].length for i in [1, 2, 0]])
+        p = sum(l)
+        v = self.vertices
+        x = simplify(l.dot(Matrix([vi.x for vi in v]))/p)
+        y = simplify(l.dot(Matrix([vi.y for vi in v]))/p)
+        return Point(x, y)
+
+    @property
+    def inradius(self):
+        """The radius of the incircle.
+
+        Returns
+        =======
+
+        inradius : number of Basic instance
+
+        See Also
+        ========
+
+        incircle, sympy.geometry.ellipse.Circle.radius
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Triangle
+        >>> p1, p2, p3 = Point(0, 0), Point(4, 0), Point(0, 3)
+        >>> t = Triangle(p1, p2, p3)
+        >>> t.inradius
+        1
+
+        """
+        return simplify(2 * self.area / self.perimeter)
+
+    @property
+    def incircle(self):
+        """The incircle of the triangle.
+
+        The incircle is the circle which lies inside the triangle and touches
+        all three sides.
+
+        Returns
+        =======
+
+        incircle : Circle
+
+        See Also
+        ========
+
+        sympy.geometry.ellipse.Circle
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Triangle
+        >>> p1, p2, p3 = Point(0, 0), Point(2, 0), Point(0, 2)
+        >>> t = Triangle(p1, p2, p3)
+        >>> t.incircle
+        Circle(Point2D(2 - sqrt(2), 2 - sqrt(2)), 2 - sqrt(2))
+
+        """
+        return Circle(self.incenter, self.inradius)
+
+    @property
+    def exradii(self):
+        """The radius of excircles of a triangle.
+
+        An excircle of the triangle is a circle lying outside the triangle,
+        tangent to one of its sides and tangent to the extensions of the
+        other two.
+
+        Returns
+        =======
+
+        exradii : dict
+
+        See Also
+        ========
+
+        sympy.geometry.polygon.Triangle.inradius
+
+        Examples
+        ========
+
+        The exradius touches the side of the triangle to which it is keyed, e.g.
+        the exradius touching side 2 is:
+
+        >>> from sympy import Point, Triangle
+        >>> p1, p2, p3 = Point(0, 0), Point(6, 0), Point(0, 2)
+        >>> t = Triangle(p1, p2, p3)
+        >>> t.exradii[t.sides[2]]
+        -2 + sqrt(10)
+
+        References
+        ==========
+
+        .. [1] https://mathworld.wolfram.com/Exradius.html
+        .. [2] https://mathworld.wolfram.com/Excircles.html
+
+        """
+
+        side = self.sides
+        a = side[0].length
+        b = side[1].length
+        c = side[2].length
+        s = (a+b+c)/2
+        area = self.area
+        exradii = {self.sides[0]: simplify(area/(s-a)),
+                   self.sides[1]: simplify(area/(s-b)),
+                   self.sides[2]: simplify(area/(s-c))}
+
+        return exradii
+
+    @property
+    def excenters(self):
+        """Excenters of the triangle.
+
+        An excenter is the center of a circle that is tangent to a side of the
+        triangle and the extensions of the other two sides.
+
+        Returns
+        =======
+
+        excenters : dict
+
+
+        Examples
+        ========
+
+        The excenters are keyed to the side of the triangle to which their corresponding
+        excircle is tangent: The center is keyed, e.g. the excenter of a circle touching
+        side 0 is:
+
+        >>> from sympy import Point, Triangle
+        >>> p1, p2, p3 = Point(0, 0), Point(6, 0), Point(0, 2)
+        >>> t = Triangle(p1, p2, p3)
+        >>> t.excenters[t.sides[0]]
+        Point2D(12*sqrt(10), 2/3 + sqrt(10)/3)
+
+        See Also
+        ========
+
+        sympy.geometry.polygon.Triangle.exradii
+
+        References
+        ==========
+
+        .. [1] https://mathworld.wolfram.com/Excircles.html
+
+        """
+
+        s = self.sides
+        v = self.vertices
+        a = s[0].length
+        b = s[1].length
+        c = s[2].length
+        x = [v[0].x, v[1].x, v[2].x]
+        y = [v[0].y, v[1].y, v[2].y]
+
+        exc_coords = {
+            "x1": simplify(-a*x[0]+b*x[1]+c*x[2]/(-a+b+c)),
+            "x2": simplify(a*x[0]-b*x[1]+c*x[2]/(a-b+c)),
+            "x3": simplify(a*x[0]+b*x[1]-c*x[2]/(a+b-c)),
+            "y1": simplify(-a*y[0]+b*y[1]+c*y[2]/(-a+b+c)),
+            "y2": simplify(a*y[0]-b*y[1]+c*y[2]/(a-b+c)),
+            "y3": simplify(a*y[0]+b*y[1]-c*y[2]/(a+b-c))
+        }
+
+        excenters = {
+            s[0]: Point(exc_coords["x1"], exc_coords["y1"]),
+            s[1]: Point(exc_coords["x2"], exc_coords["y2"]),
+            s[2]: Point(exc_coords["x3"], exc_coords["y3"])
+        }
+
+        return excenters
+
+    @property
+    def medians(self):
+        """The medians of the triangle.
+
+        A median of a triangle is a straight line through a vertex and the
+        midpoint of the opposite side, and divides the triangle into two
+        equal areas.
+
+        Returns
+        =======
+
+        medians : dict
+            Each key is a vertex (Point) and each value is the median (Segment)
+            at that point.
+
+        See Also
+        ========
+
+        sympy.geometry.point.Point.midpoint, sympy.geometry.line.Segment.midpoint
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Triangle
+        >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
+        >>> t = Triangle(p1, p2, p3)
+        >>> t.medians[p1]
+        Segment2D(Point2D(0, 0), Point2D(1/2, 1/2))
+
+        """
+        s = self.sides
+        v = self.vertices
+        return {v[0]: Segment(v[0], s[1].midpoint),
+                v[1]: Segment(v[1], s[2].midpoint),
+                v[2]: Segment(v[2], s[0].midpoint)}
+
+    @property
+    def medial(self):
+        """The medial triangle of the triangle.
+
+        The triangle which is formed from the midpoints of the three sides.
+
+        Returns
+        =======
+
+        medial : Triangle
+
+        See Also
+        ========
+
+        sympy.geometry.line.Segment.midpoint
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Triangle
+        >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
+        >>> t = Triangle(p1, p2, p3)
+        >>> t.medial
+        Triangle(Point2D(1/2, 0), Point2D(1/2, 1/2), Point2D(0, 1/2))
+
+        """
+        s = self.sides
+        return Triangle(s[0].midpoint, s[1].midpoint, s[2].midpoint)
+
+    @property
+    def nine_point_circle(self):
+        """The nine-point circle of the triangle.
+
+        Nine-point circle is the circumcircle of the medial triangle, which
+        passes through the feet of altitudes and the middle points of segments
+        connecting the vertices and the orthocenter.
+
+        Returns
+        =======
+
+        nine_point_circle : Circle
+
+        See also
+        ========
+
+        sympy.geometry.line.Segment.midpoint
+        sympy.geometry.polygon.Triangle.medial
+        sympy.geometry.polygon.Triangle.orthocenter
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Triangle
+        >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
+        >>> t = Triangle(p1, p2, p3)
+        >>> t.nine_point_circle
+        Circle(Point2D(1/4, 1/4), sqrt(2)/4)
+
+        """
+        return Circle(*self.medial.vertices)
+
+    @property
+    def eulerline(self):
+        """The Euler line of the triangle.
+
+        The line which passes through circumcenter, centroid and orthocenter.
+
+        Returns
+        =======
+
+        eulerline : Line (or Point for equilateral triangles in which case all
+                    centers coincide)
+
+        Examples
+        ========
+
+        >>> from sympy import Point, Triangle
+        >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
+        >>> t = Triangle(p1, p2, p3)
+        >>> t.eulerline
+        Line2D(Point2D(0, 0), Point2D(1/2, 1/2))
+
+        """
+        if self.is_equilateral():
+            return self.orthocenter
+        return Line(self.orthocenter, self.circumcenter)
+
+def rad(d):
+    """Return the radian value for the given degrees (pi = 180 degrees)."""
+    return d*pi/180
+
+
+def deg(r):
+    """Return the degree value for the given radians (pi = 180 degrees)."""
+    return r/pi*180
+
+
+def _slope(d):
+    rv = tan(rad(d))
+    return rv
+
+
+def _asa(d1, l, d2):
+    """Return triangle having side with length l on the x-axis."""
+    xy = Line((0, 0), slope=_slope(d1)).intersection(
+        Line((l, 0), slope=_slope(180 - d2)))[0]
+    return Triangle((0, 0), (l, 0), xy)
+
+
+def _sss(l1, l2, l3):
+    """Return triangle having side of length l1 on the x-axis."""
+    c1 = Circle((0, 0), l3)
+    c2 = Circle((l1, 0), l2)
+    inter = [a for a in c1.intersection(c2) if a.y.is_nonnegative]
+    if not inter:
+        return None
+    pt = inter[0]
+    return Triangle((0, 0), (l1, 0), pt)
+
+
+def _sas(l1, d, l2):
+    """Return triangle having side with length l2 on the x-axis."""
+    p1 = Point(0, 0)
+    p2 = Point(l2, 0)
+    p3 = Point(cos(rad(d))*l1, sin(rad(d))*l1)
+    return Triangle(p1, p2, p3)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_curve.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_curve.py
new file mode 100644
index 0000000000000000000000000000000000000000..50aa80273a1d8eb9e414a8d591571f3127352dad
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_curve.py
@@ -0,0 +1,120 @@
+from sympy.core.containers import Tuple
+from sympy.core.numbers import (Rational, pi)
+from sympy.core.singleton import S
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.functions.elementary.hyperbolic import asinh
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.geometry import Curve, Line, Point, Ellipse, Ray, Segment, Circle, Polygon, RegularPolygon
+from sympy.testing.pytest import raises, slow
+
+
+def test_curve():
+    x = Symbol('x', real=True)
+    s = Symbol('s')
+    z = Symbol('z')
+
+    # this curve is independent of the indicated parameter
+    c = Curve([2*s, s**2], (z, 0, 2))
+
+    assert c.parameter == z
+    assert c.functions == (2*s, s**2)
+    assert c.arbitrary_point() == Point(2*s, s**2)
+    assert c.arbitrary_point(z) == Point(2*s, s**2)
+
+    # this is how it is normally used
+    c = Curve([2*s, s**2], (s, 0, 2))
+
+    assert c.parameter == s
+    assert c.functions == (2*s, s**2)
+    t = Symbol('t')
+    # the t returned as assumptions
+    assert c.arbitrary_point() != Point(2*t, t**2)
+    t = Symbol('t', real=True)
+    # now t has the same assumptions so the test passes
+    assert c.arbitrary_point() == Point(2*t, t**2)
+    assert c.arbitrary_point(z) == Point(2*z, z**2)
+    assert c.arbitrary_point(c.parameter) == Point(2*s, s**2)
+    assert c.arbitrary_point(None) == Point(2*s, s**2)
+    assert c.plot_interval() == [t, 0, 2]
+    assert c.plot_interval(z) == [z, 0, 2]
+
+    assert Curve([x, x], (x, 0, 1)).rotate(pi/2) == Curve([-x, x], (x, 0, 1))
+    assert Curve([x, x], (x, 0, 1)).rotate(pi/2, (1, 2)).scale(2, 3).translate(
+        1, 3).arbitrary_point(s) == \
+        Line((0, 0), (1, 1)).rotate(pi/2, (1, 2)).scale(2, 3).translate(
+            1, 3).arbitrary_point(s) == \
+        Point(-2*s + 7, 3*s + 6)
+
+    raises(ValueError, lambda: Curve((s), (s, 1, 2)))
+    raises(ValueError, lambda: Curve((x, x * 2), (1, x)))
+
+    raises(ValueError, lambda: Curve((s, s + t), (s, 1, 2)).arbitrary_point())
+    raises(ValueError, lambda: Curve((s, s + t), (t, 1, 2)).arbitrary_point(s))
+
+
+@slow
+def test_free_symbols():
+    a, b, c, d, e, f, s = symbols('a:f,s')
+    assert Point(a, b).free_symbols == {a, b}
+    assert Line((a, b), (c, d)).free_symbols == {a, b, c, d}
+    assert Ray((a, b), (c, d)).free_symbols == {a, b, c, d}
+    assert Ray((a, b), angle=c).free_symbols == {a, b, c}
+    assert Segment((a, b), (c, d)).free_symbols == {a, b, c, d}
+    assert Line((a, b), slope=c).free_symbols == {a, b, c}
+    assert Curve((a*s, b*s), (s, c, d)).free_symbols == {a, b, c, d}
+    assert Ellipse((a, b), c, d).free_symbols == {a, b, c, d}
+    assert Ellipse((a, b), c, eccentricity=d).free_symbols == \
+        {a, b, c, d}
+    assert Ellipse((a, b), vradius=c, eccentricity=d).free_symbols == \
+        {a, b, c, d}
+    assert Circle((a, b), c).free_symbols == {a, b, c}
+    assert Circle((a, b), (c, d), (e, f)).free_symbols == \
+        {e, d, c, b, f, a}
+    assert Polygon((a, b), (c, d), (e, f)).free_symbols == \
+        {e, b, d, f, a, c}
+    assert RegularPolygon((a, b), c, d, e).free_symbols == {e, a, b, c, d}
+
+
+def test_transform():
+    x = Symbol('x', real=True)
+    y = Symbol('y', real=True)
+    c = Curve((x, x**2), (x, 0, 1))
+    cout = Curve((2*x - 4, 3*x**2 - 10), (x, 0, 1))
+    pts = [Point(0, 0), Point(S.Half, Rational(1, 4)), Point(1, 1)]
+    pts_out = [Point(-4, -10), Point(-3, Rational(-37, 4)), Point(-2, -7)]
+
+    assert c.scale(2, 3, (4, 5)) == cout
+    assert [c.subs(x, xi/2) for xi in Tuple(0, 1, 2)] == pts
+    assert [cout.subs(x, xi/2) for xi in Tuple(0, 1, 2)] == pts_out
+    assert Curve((x + y, 3*x), (x, 0, 1)).subs(y, S.Half) == \
+        Curve((x + S.Half, 3*x), (x, 0, 1))
+    assert Curve((x, 3*x), (x, 0, 1)).translate(4, 5) == \
+        Curve((x + 4, 3*x + 5), (x, 0, 1))
+
+
+def test_length():
+    t = Symbol('t', real=True)
+
+    c1 = Curve((t, 0), (t, 0, 1))
+    assert c1.length == 1
+
+    c2 = Curve((t, t), (t, 0, 1))
+    assert c2.length == sqrt(2)
+
+    c3 = Curve((t ** 2, t), (t, 2, 5))
+    assert c3.length == -sqrt(17) - asinh(4) / 4 + asinh(10) / 4 + 5 * sqrt(101) / 2
+
+
+def test_parameter_value():
+    t = Symbol('t')
+    C = Curve([2*t, t**2], (t, 0, 2))
+    assert C.parameter_value((2, 1), t) == {t: 1}
+    raises(ValueError, lambda: C.parameter_value((2, 0), t))
+
+
+def test_issue_17997():
+    t, s = symbols('t s')
+    c = Curve((t, t**2), (t, 0, 10))
+    p = Curve([2*s, s**2], (s, 0, 2))
+    assert c(2) == Point(2, 4)
+    assert p(1) == Point(2, 1)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_ellipse.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_ellipse.py
new file mode 100644
index 0000000000000000000000000000000000000000..a79eba8c35771bda9f0980aca68d937f8e625c0a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_ellipse.py
@@ -0,0 +1,613 @@
+from sympy.core import expand
+from sympy.core.numbers import (Rational, oo, pi)
+from sympy.core.relational import Eq
+from sympy.core.singleton import S
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.functions.elementary.complexes import Abs
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import sec
+from sympy.geometry.line import Segment2D
+from sympy.geometry.point import Point2D
+from sympy.geometry import (Circle, Ellipse, GeometryError, Line, Point,
+                            Polygon, Ray, RegularPolygon, Segment,
+                            Triangle, intersection)
+from sympy.testing.pytest import raises, slow
+from sympy.integrals.integrals import integrate
+from sympy.functions.special.elliptic_integrals import elliptic_e
+from sympy.functions.elementary.miscellaneous import Max
+
+
+def test_ellipse_equation_using_slope():
+    from sympy.abc import x, y
+
+    e1 = Ellipse(Point(1, 0), 3, 2)
+    assert str(e1.equation(_slope=1)) == str((-x + y + 1)**2/8 + (x + y - 1)**2/18 - 1)
+
+    e2 = Ellipse(Point(0, 0), 4, 1)
+    assert str(e2.equation(_slope=1)) == str((-x + y)**2/2 + (x + y)**2/32 - 1)
+
+    e3 = Ellipse(Point(1, 5), 6, 2)
+    assert str(e3.equation(_slope=2)) == str((-2*x + y - 3)**2/20 + (x + 2*y - 11)**2/180 - 1)
+
+
+def test_object_from_equation():
+    from sympy.abc import x, y, a, b, c, d, e
+    assert Circle(x**2 + y**2 + 3*x + 4*y - 8) == Circle(Point2D(S(-3) / 2, -2), sqrt(57) / 2)
+    assert Circle(x**2 + y**2 + 6*x + 8*y + 25) == Circle(Point2D(-3, -4), 0)
+    assert Circle(a**2 + b**2 + 6*a + 8*b + 25, x='a', y='b') == Circle(Point2D(-3, -4), 0)
+    assert Circle(x**2 + y**2 - 25) == Circle(Point2D(0, 0), 5)
+    assert Circle(x**2 + y**2) == Circle(Point2D(0, 0), 0)
+    assert Circle(a**2 + b**2, x='a', y='b') == Circle(Point2D(0, 0), 0)
+    assert Circle(x**2 + y**2 + 6*x + 8) == Circle(Point2D(-3, 0), 1)
+    assert Circle(x**2 + y**2 + 6*y + 8) == Circle(Point2D(0, -3), 1)
+    assert Circle((x - 1)**2 + y**2 - 9) == Circle(Point2D(1, 0), 3)
+    assert Circle(6*(x**2) + 6*(y**2) + 6*x + 8*y - 25) == Circle(Point2D(Rational(-1, 2), Rational(-2, 3)), 5*sqrt(7)/6)
+    assert Circle(Eq(a**2 + b**2, 25), x='a', y=b) == Circle(Point2D(0, 0), 5)
+    raises(GeometryError, lambda: Circle(x**2 + y**2 + 3*x + 4*y + 26))
+    raises(GeometryError, lambda: Circle(x**2 + y**2 + 25))
+    raises(GeometryError, lambda: Circle(a**2 + b**2 + 25, x='a', y='b'))
+    raises(GeometryError, lambda: Circle(x**2 + 6*y + 8))
+    raises(GeometryError, lambda: Circle(6*(x ** 2) + 4*(y**2) + 6*x + 8*y + 25))
+    raises(ValueError, lambda: Circle(a**2 + b**2 + 3*a + 4*b - 8))
+    # .equation() adds 'real=True' assumption; '==' would fail if assumptions differed
+    x, y = symbols('x y', real=True)
+    eq = a*x**2 + a*y**2 + c*x + d*y + e
+    assert expand(Circle(eq).equation()*a) == eq
+
+
+@slow
+def test_ellipse_geom():
+    x = Symbol('x', real=True)
+    y = Symbol('y', real=True)
+    t = Symbol('t', real=True)
+    y1 = Symbol('y1', real=True)
+    half = S.Half
+    p1 = Point(0, 0)
+    p2 = Point(1, 1)
+    p4 = Point(0, 1)
+
+    e1 = Ellipse(p1, 1, 1)
+    e2 = Ellipse(p2, half, 1)
+    e3 = Ellipse(p1, y1, y1)
+    c1 = Circle(p1, 1)
+    c2 = Circle(p2, 1)
+    c3 = Circle(Point(sqrt(2), sqrt(2)), 1)
+    l1 = Line(p1, p2)
+
+    # Test creation with three points
+    cen, rad = Point(3*half, 2), 5*half
+    assert Circle(Point(0, 0), Point(3, 0), Point(0, 4)) == Circle(cen, rad)
+    assert Circle(Point(0, 0), Point(1, 1), Point(2, 2)) == Segment2D(Point2D(0, 0), Point2D(2, 2))
+
+    raises(ValueError, lambda: Ellipse(None, None, None, 1))
+    raises(ValueError, lambda: Ellipse())
+    raises(GeometryError, lambda: Circle(Point(0, 0)))
+    raises(GeometryError, lambda: Circle(Symbol('x')*Symbol('y')))
+
+    # Basic Stuff
+    assert Ellipse(None, 1, 1).center == Point(0, 0)
+    assert e1 == c1
+    assert e1 != e2
+    assert e1 != l1
+    assert p4 in e1
+    assert e1 in e1
+    assert e2 in e2
+    assert 1 not in e2
+    assert p2 not in e2
+    assert e1.area == pi
+    assert e2.area == pi/2
+    assert e3.area == pi*y1*abs(y1)
+    assert c1.area == e1.area
+    assert c1.circumference == e1.circumference
+    assert e3.circumference == 2*pi*y1
+    assert e1.plot_interval() == e2.plot_interval() == [t, -pi, pi]
+    assert e1.plot_interval(x) == e2.plot_interval(x) == [x, -pi, pi]
+
+    assert c1.minor == 1
+    assert c1.major == 1
+    assert c1.hradius == 1
+    assert c1.vradius == 1
+
+    assert Ellipse((1, 1), 0, 0) == Point(1, 1)
+    assert Ellipse((1, 1), 1, 0) == Segment(Point(0, 1), Point(2, 1))
+    assert Ellipse((1, 1), 0, 1) == Segment(Point(1, 0), Point(1, 2))
+
+    # Private Functions
+    assert hash(c1) == hash(Circle(Point(1, 0), Point(0, 1), Point(0, -1)))
+    assert c1 in e1
+    assert (Line(p1, p2) in e1) is False
+    assert e1.__cmp__(e1) == 0
+    assert e1.__cmp__(Point(0, 0)) > 0
+
+    # Encloses
+    assert e1.encloses(Segment(Point(-0.5, -0.5), Point(0.5, 0.5))) is True
+    assert e1.encloses(Line(p1, p2)) is False
+    assert e1.encloses(Ray(p1, p2)) is False
+    assert e1.encloses(e1) is False
+    assert e1.encloses(
+        Polygon(Point(-0.5, -0.5), Point(-0.5, 0.5), Point(0.5, 0.5))) is True
+    assert e1.encloses(RegularPolygon(p1, 0.5, 3)) is True
+    assert e1.encloses(RegularPolygon(p1, 5, 3)) is False
+    assert e1.encloses(RegularPolygon(p2, 5, 3)) is False
+
+    assert e2.arbitrary_point() in e2
+    raises(ValueError, lambda: Ellipse(Point(x, y), 1, 1).arbitrary_point(parameter='x'))
+
+    # Foci
+    f1, f2 = Point(sqrt(12), 0), Point(-sqrt(12), 0)
+    ef = Ellipse(Point(0, 0), 4, 2)
+    assert ef.foci in [(f1, f2), (f2, f1)]
+
+    # Tangents
+    v = sqrt(2) / 2
+    p1_1 = Point(v, v)
+    p1_2 = p2 + Point(half, 0)
+    p1_3 = p2 + Point(0, 1)
+    assert e1.tangent_lines(p4) == c1.tangent_lines(p4)
+    assert e2.tangent_lines(p1_2) == [Line(Point(Rational(3, 2), 1), Point(Rational(3, 2), S.Half))]
+    assert e2.tangent_lines(p1_3) == [Line(Point(1, 2), Point(Rational(5, 4), 2))]
+    assert c1.tangent_lines(p1_1) != [Line(p1_1, Point(0, sqrt(2)))]
+    assert c1.tangent_lines(p1) == []
+    assert e2.is_tangent(Line(p1_2, p2 + Point(half, 1)))
+    assert e2.is_tangent(Line(p1_3, p2 + Point(half, 1)))
+    assert c1.is_tangent(Line(p1_1, Point(0, sqrt(2))))
+    assert e1.is_tangent(Line(Point(0, 0), Point(1, 1))) is False
+    assert c1.is_tangent(e1) is True
+    assert c1.is_tangent(Ellipse(Point(2, 0), 1, 1)) is True
+    assert c1.is_tangent(
+        Polygon(Point(1, 1), Point(1, -1), Point(2, 0))) is False
+    assert c1.is_tangent(
+        Polygon(Point(1, 1), Point(1, 0), Point(2, 0))) is False
+    assert Circle(Point(5, 5), 3).is_tangent(Circle(Point(0, 5), 1)) is False
+
+    assert Ellipse(Point(5, 5), 2, 1).tangent_lines(Point(0, 0)) == \
+        [Line(Point(0, 0), Point(Rational(77, 25), Rational(132, 25))),
+     Line(Point(0, 0), Point(Rational(33, 5), Rational(22, 5)))]
+    assert Ellipse(Point(5, 5), 2, 1).tangent_lines(Point(3, 4)) == \
+        [Line(Point(3, 4), Point(4, 4)), Line(Point(3, 4), Point(3, 5))]
+    assert Circle(Point(5, 5), 2).tangent_lines(Point(3, 3)) == \
+        [Line(Point(3, 3), Point(4, 3)), Line(Point(3, 3), Point(3, 4))]
+    assert Circle(Point(5, 5), 2).tangent_lines(Point(5 - 2*sqrt(2), 5)) == \
+        [Line(Point(5 - 2*sqrt(2), 5), Point(5 - sqrt(2), 5 - sqrt(2))),
+     Line(Point(5 - 2*sqrt(2), 5), Point(5 - sqrt(2), 5 + sqrt(2))), ]
+    assert Circle(Point(5, 5), 5).tangent_lines(Point(4, 0)) == \
+        [Line(Point(4, 0), Point(Rational(40, 13), Rational(5, 13))),
+     Line(Point(4, 0), Point(5, 0))]
+    assert Circle(Point(5, 5), 5).tangent_lines(Point(0, 6)) == \
+        [Line(Point(0, 6), Point(0, 7)),
+        Line(Point(0, 6), Point(Rational(5, 13), Rational(90, 13)))]
+
+    # for numerical calculations, we shouldn't demand exact equality,
+    # so only test up to the desired precision
+    def lines_close(l1, l2, prec):
+        """ tests whether l1 and 12 are within 10**(-prec)
+        of each other """
+        return abs(l1.p1 - l2.p1) < 10**(-prec) and abs(l1.p2 - l2.p2) < 10**(-prec)
+    def line_list_close(ll1, ll2, prec):
+        return all(lines_close(l1, l2, prec) for l1, l2 in zip(ll1, ll2))
+
+    e = Ellipse(Point(0, 0), 2, 1)
+    assert e.normal_lines(Point(0, 0)) == \
+        [Line(Point(0, 0), Point(0, 1)), Line(Point(0, 0), Point(1, 0))]
+    assert e.normal_lines(Point(1, 0)) == \
+        [Line(Point(0, 0), Point(1, 0))]
+    assert e.normal_lines((0, 1)) == \
+        [Line(Point(0, 0), Point(0, 1))]
+    assert line_list_close(e.normal_lines(Point(1, 1), 2), [
+        Line(Point(Rational(-51, 26), Rational(-1, 5)), Point(Rational(-25, 26), Rational(17, 83))),
+        Line(Point(Rational(28, 29), Rational(-7, 8)), Point(Rational(57, 29), Rational(-9, 2)))], 2)
+    # test the failure of Poly.intervals and checks a point on the boundary
+    p = Point(sqrt(3), S.Half)
+    assert p in e
+    assert line_list_close(e.normal_lines(p, 2), [
+        Line(Point(Rational(-341, 171), Rational(-1, 13)), Point(Rational(-170, 171), Rational(5, 64))),
+        Line(Point(Rational(26, 15), Rational(-1, 2)), Point(Rational(41, 15), Rational(-43, 26)))], 2)
+    # be sure to use the slope that isn't undefined on boundary
+    e = Ellipse((0, 0), 2, 2*sqrt(3)/3)
+    assert line_list_close(e.normal_lines((1, 1), 2), [
+        Line(Point(Rational(-64, 33), Rational(-20, 71)), Point(Rational(-31, 33), Rational(2, 13))),
+        Line(Point(1, -1), Point(2, -4))], 2)
+    # general ellipse fails except under certain conditions
+    e = Ellipse((0, 0), x, 1)
+    assert e.normal_lines((x + 1, 0)) == [Line(Point(0, 0), Point(1, 0))]
+    raises(NotImplementedError, lambda: e.normal_lines((x + 1, 1)))
+    # Properties
+    major = 3
+    minor = 1
+    e4 = Ellipse(p2, minor, major)
+    assert e4.focus_distance == sqrt(major**2 - minor**2)
+    ecc = e4.focus_distance / major
+    assert e4.eccentricity == ecc
+    assert e4.periapsis == major*(1 - ecc)
+    assert e4.apoapsis == major*(1 + ecc)
+    assert e4.semilatus_rectum == major*(1 - ecc ** 2)
+    # independent of orientation
+    e4 = Ellipse(p2, major, minor)
+    assert e4.focus_distance == sqrt(major**2 - minor**2)
+    ecc = e4.focus_distance / major
+    assert e4.eccentricity == ecc
+    assert e4.periapsis == major*(1 - ecc)
+    assert e4.apoapsis == major*(1 + ecc)
+
+    # Intersection
+    l1 = Line(Point(1, -5), Point(1, 5))
+    l2 = Line(Point(-5, -1), Point(5, -1))
+    l3 = Line(Point(-1, -1), Point(1, 1))
+    l4 = Line(Point(-10, 0), Point(0, 10))
+    pts_c1_l3 = [Point(sqrt(2)/2, sqrt(2)/2), Point(-sqrt(2)/2, -sqrt(2)/2)]
+
+    assert intersection(e2, l4) == []
+    assert intersection(c1, Point(1, 0)) == [Point(1, 0)]
+    assert intersection(c1, l1) == [Point(1, 0)]
+    assert intersection(c1, l2) == [Point(0, -1)]
+    assert intersection(c1, l3) in [pts_c1_l3, [pts_c1_l3[1], pts_c1_l3[0]]]
+    assert intersection(c1, c2) == [Point(0, 1), Point(1, 0)]
+    assert intersection(c1, c3) == [Point(sqrt(2)/2, sqrt(2)/2)]
+    assert e1.intersection(l1) == [Point(1, 0)]
+    assert e2.intersection(l4) == []
+    assert e1.intersection(Circle(Point(0, 2), 1)) == [Point(0, 1)]
+    assert e1.intersection(Circle(Point(5, 0), 1)) == []
+    assert e1.intersection(Ellipse(Point(2, 0), 1, 1)) == [Point(1, 0)]
+    assert e1.intersection(Ellipse(Point(5, 0), 1, 1)) == []
+    assert e1.intersection(Point(2, 0)) == []
+    assert e1.intersection(e1) == e1
+    assert intersection(Ellipse(Point(0, 0), 2, 1), Ellipse(Point(3, 0), 1, 2)) == [Point(2, 0)]
+    assert intersection(Circle(Point(0, 0), 2), Circle(Point(3, 0), 1)) == [Point(2, 0)]
+    assert intersection(Circle(Point(0, 0), 2), Circle(Point(7, 0), 1)) == []
+    assert intersection(Ellipse(Point(0, 0), 5, 17), Ellipse(Point(4, 0), 1, 0.2)
+        ) == [Point(5.0, 0, evaluate=False)]
+    assert intersection(Ellipse(Point(0, 0), 5, 17), Ellipse(Point(4, 0), 0.999, 0.2)) == []
+    assert Circle((0, 0), S.Half).intersection(
+        Triangle((-1, 0), (1, 0), (0, 1))) == [
+        Point(Rational(-1, 2), 0), Point(S.Half, 0)]
+    raises(TypeError, lambda: intersection(e2, Line((0, 0, 0), (0, 0, 1))))
+    raises(TypeError, lambda: intersection(e2, Rational(12)))
+    raises(TypeError, lambda: Ellipse.intersection(e2, 1))
+    # some special case intersections
+    csmall = Circle(p1, 3)
+    cbig = Circle(p1, 5)
+    cout = Circle(Point(5, 5), 1)
+    # one circle inside of another
+    assert csmall.intersection(cbig) == []
+    # separate circles
+    assert csmall.intersection(cout) == []
+    # coincident circles
+    assert csmall.intersection(csmall) == csmall
+
+    v = sqrt(2)
+    t1 = Triangle(Point(0, v), Point(0, -v), Point(v, 0))
+    points = intersection(t1, c1)
+    assert len(points) == 4
+    assert Point(0, 1) in points
+    assert Point(0, -1) in points
+    assert Point(v/2, v/2) in points
+    assert Point(v/2, -v/2) in points
+
+    circ = Circle(Point(0, 0), 5)
+    elip = Ellipse(Point(0, 0), 5, 20)
+    assert intersection(circ, elip) in \
+        [[Point(5, 0), Point(-5, 0)], [Point(-5, 0), Point(5, 0)]]
+    assert elip.tangent_lines(Point(0, 0)) == []
+    elip = Ellipse(Point(0, 0), 3, 2)
+    assert elip.tangent_lines(Point(3, 0)) == \
+        [Line(Point(3, 0), Point(3, -12))]
+
+    e1 = Ellipse(Point(0, 0), 5, 10)
+    e2 = Ellipse(Point(2, 1), 4, 8)
+    a = Rational(53, 17)
+    c = 2*sqrt(3991)/17
+    ans = [Point(a - c/8, a/2 + c), Point(a + c/8, a/2 - c)]
+    assert e1.intersection(e2) == ans
+    e2 = Ellipse(Point(x, y), 4, 8)
+    c = sqrt(3991)
+    ans = [Point(-c/68 + a, c*Rational(2, 17) + a/2), Point(c/68 + a, c*Rational(-2, 17) + a/2)]
+    assert [p.subs({x: 2, y:1}) for p in e1.intersection(e2)] == ans
+
+    # Combinations of above
+    assert e3.is_tangent(e3.tangent_lines(p1 + Point(y1, 0))[0])
+
+    e = Ellipse((1, 2), 3, 2)
+    assert e.tangent_lines(Point(10, 0)) == \
+        [Line(Point(10, 0), Point(1, 0)),
+        Line(Point(10, 0), Point(Rational(14, 5), Rational(18, 5)))]
+
+    # encloses_point
+    e = Ellipse((0, 0), 1, 2)
+    assert e.encloses_point(e.center)
+    assert e.encloses_point(e.center + Point(0, e.vradius - Rational(1, 10)))
+    assert e.encloses_point(e.center + Point(e.hradius - Rational(1, 10), 0))
+    assert e.encloses_point(e.center + Point(e.hradius, 0)) is False
+    assert e.encloses_point(
+        e.center + Point(e.hradius + Rational(1, 10), 0)) is False
+    e = Ellipse((0, 0), 2, 1)
+    assert e.encloses_point(e.center)
+    assert e.encloses_point(e.center + Point(0, e.vradius - Rational(1, 10)))
+    assert e.encloses_point(e.center + Point(e.hradius - Rational(1, 10), 0))
+    assert e.encloses_point(e.center + Point(e.hradius, 0)) is False
+    assert e.encloses_point(
+        e.center + Point(e.hradius + Rational(1, 10), 0)) is False
+    assert c1.encloses_point(Point(1, 0)) is False
+    assert c1.encloses_point(Point(0.3, 0.4)) is True
+
+    assert e.scale(2, 3) == Ellipse((0, 0), 4, 3)
+    assert e.scale(3, 6) == Ellipse((0, 0), 6, 6)
+    assert e.rotate(pi) == e
+    assert e.rotate(pi, (1, 2)) == Ellipse(Point(2, 4), 2, 1)
+    raises(NotImplementedError, lambda: e.rotate(pi/3))
+
+    # Circle rotation tests (Issue #11743)
+    # Link - https://github.com/sympy/sympy/issues/11743
+    cir = Circle(Point(1, 0), 1)
+    assert cir.rotate(pi/2) == Circle(Point(0, 1), 1)
+    assert cir.rotate(pi/3) == Circle(Point(S.Half, sqrt(3)/2), 1)
+    assert cir.rotate(pi/3, Point(1, 0)) == Circle(Point(1, 0), 1)
+    assert cir.rotate(pi/3, Point(0, 1)) == Circle(Point(S.Half + sqrt(3)/2, S.Half + sqrt(3)/2), 1)
+
+
+def test_construction():
+    e1 = Ellipse(hradius=2, vradius=1, eccentricity=None)
+    assert e1.eccentricity == sqrt(3)/2
+
+    e2 = Ellipse(hradius=2, vradius=None, eccentricity=sqrt(3)/2)
+    assert e2.vradius == 1
+
+    e3 = Ellipse(hradius=None, vradius=1, eccentricity=sqrt(3)/2)
+    assert e3.hradius == 2
+
+    # filter(None, iterator) filters out anything falsey, including 0
+    # eccentricity would be filtered out in this case and the constructor would throw an error
+    e4 = Ellipse(Point(0, 0), hradius=1, eccentricity=0)
+    assert e4.vradius == 1
+
+    #tests for eccentricity > 1
+    raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity = S(3)/2))
+    raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity=sec(5)))
+    raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity=S.Pi-S(2)))
+
+    #tests for eccentricity = 1
+    #if vradius is not defined
+    assert Ellipse(None, 1, None, 1).length == 2
+    #if hradius is not defined
+    raises(GeometryError, lambda: Ellipse(None, None, 1, eccentricity = 1))
+
+    #tests for eccentricity < 0
+    raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity = -3))
+    raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity = -0.5))
+
+def test_ellipse_random_point():
+    y1 = Symbol('y1', real=True)
+    e3 = Ellipse(Point(0, 0), y1, y1)
+    rx, ry = Symbol('rx'), Symbol('ry')
+    for ind in range(0, 5):
+        r = e3.random_point()
+        # substitution should give zero*y1**2
+        assert e3.equation(rx, ry).subs(zip((rx, ry), r.args)).equals(0)
+    # test for the case with seed
+    r = e3.random_point(seed=1)
+    assert e3.equation(rx, ry).subs(zip((rx, ry), r.args)).equals(0)
+
+
+def test_repr():
+    assert repr(Circle((0, 1), 2)) == 'Circle(Point2D(0, 1), 2)'
+
+
+def test_transform():
+    c = Circle((1, 1), 2)
+    assert c.scale(-1) == Circle((-1, 1), 2)
+    assert c.scale(y=-1) == Circle((1, -1), 2)
+    assert c.scale(2) == Ellipse((2, 1), 4, 2)
+
+    assert Ellipse((0, 0), 2, 3).scale(2, 3, (4, 5)) == \
+        Ellipse(Point(-4, -10), 4, 9)
+    assert Circle((0, 0), 2).scale(2, 3, (4, 5)) == \
+        Ellipse(Point(-4, -10), 4, 6)
+    assert Ellipse((0, 0), 2, 3).scale(3, 3, (4, 5)) == \
+        Ellipse(Point(-8, -10), 6, 9)
+    assert Circle((0, 0), 2).scale(3, 3, (4, 5)) == \
+        Circle(Point(-8, -10), 6)
+    assert Circle(Point(-8, -10), 6).scale(Rational(1, 3), Rational(1, 3), (4, 5)) == \
+        Circle((0, 0), 2)
+    assert Circle((0, 0), 2).translate(4, 5) == \
+        Circle((4, 5), 2)
+    assert Circle((0, 0), 2).scale(3, 3) == \
+        Circle((0, 0), 6)
+
+
+def test_bounds():
+    e1 = Ellipse(Point(0, 0), 3, 5)
+    e2 = Ellipse(Point(2, -2), 7, 7)
+    c1 = Circle(Point(2, -2), 7)
+    c2 = Circle(Point(-2, 0), Point(0, 2), Point(2, 0))
+    assert e1.bounds == (-3, -5, 3, 5)
+    assert e2.bounds == (-5, -9, 9, 5)
+    assert c1.bounds == (-5, -9, 9, 5)
+    assert c2.bounds == (-2, -2, 2, 2)
+
+
+def test_reflect():
+    b = Symbol('b')
+    m = Symbol('m')
+    l = Line((0, b), slope=m)
+    t1 = Triangle((0, 0), (1, 0), (2, 3))
+    assert t1.area == -t1.reflect(l).area
+    e = Ellipse((1, 0), 1, 2)
+    assert e.area == -e.reflect(Line((1, 0), slope=0)).area
+    assert e.area == -e.reflect(Line((1, 0), slope=oo)).area
+    raises(NotImplementedError, lambda: e.reflect(Line((1, 0), slope=m)))
+    assert Circle((0, 1), 1).reflect(Line((0, 0), (1, 1))) == Circle(Point2D(1, 0), -1)
+
+
+def test_is_tangent():
+    e1 = Ellipse(Point(0, 0), 3, 5)
+    c1 = Circle(Point(2, -2), 7)
+    assert e1.is_tangent(Point(0, 0)) is False
+    assert e1.is_tangent(Point(3, 0)) is False
+    assert e1.is_tangent(e1) is True
+    assert e1.is_tangent(Ellipse((0, 0), 1, 2)) is False
+    assert e1.is_tangent(Ellipse((0, 0), 3, 2)) is True
+    assert c1.is_tangent(Ellipse((2, -2), 7, 1)) is True
+    assert c1.is_tangent(Circle((11, -2), 2)) is True
+    assert c1.is_tangent(Circle((7, -2), 2)) is True
+    assert c1.is_tangent(Ray((-5, -2), (-15, -20))) is False
+    assert c1.is_tangent(Ray((-3, -2), (-15, -20))) is False
+    assert c1.is_tangent(Ray((-3, -22), (15, 20))) is False
+    assert c1.is_tangent(Ray((9, 20), (9, -20))) is True
+    assert c1.is_tangent(Ray((2, 5), (9, 5))) is True
+    assert c1.is_tangent(Segment((2, 5), (9, 5))) is True
+    assert e1.is_tangent(Segment((2, 2), (-7, 7))) is False
+    assert e1.is_tangent(Segment((0, 0), (1, 2))) is False
+    assert c1.is_tangent(Segment((0, 0), (-5, -2))) is False
+    assert e1.is_tangent(Segment((3, 0), (12, 12))) is False
+    assert e1.is_tangent(Segment((12, 12), (3, 0))) is False
+    assert e1.is_tangent(Segment((-3, 0), (3, 0))) is False
+    assert e1.is_tangent(Segment((-3, 5), (3, 5))) is True
+    assert e1.is_tangent(Line((10, 0), (10, 10))) is False
+    assert e1.is_tangent(Line((0, 0), (1, 1))) is False
+    assert e1.is_tangent(Line((-3, 0), (-2.99, -0.001))) is False
+    assert e1.is_tangent(Line((-3, 0), (-3, 1))) is True
+    assert e1.is_tangent(Polygon((0, 0), (5, 5), (5, -5))) is False
+    assert e1.is_tangent(Polygon((-100, -50), (-40, -334), (-70, -52))) is False
+    assert e1.is_tangent(Polygon((-3, 0), (3, 0), (0, 1))) is False
+    assert e1.is_tangent(Polygon((-3, 0), (3, 0), (0, 5))) is False
+    assert e1.is_tangent(Polygon((-3, 0), (0, -5), (3, 0), (0, 5))) is False
+    assert e1.is_tangent(Polygon((-3, -5), (-3, 5), (3, 5), (3, -5))) is True
+    assert c1.is_tangent(Polygon((-3, -5), (-3, 5), (3, 5), (3, -5))) is False
+    assert e1.is_tangent(Polygon((0, 0), (3, 0), (7, 7), (0, 5))) is False
+    assert e1.is_tangent(Polygon((3, 12), (3, -12), (6, 5))) is False
+    assert e1.is_tangent(Polygon((3, 12), (3, -12), (0, -5), (0, 5))) is False
+    assert e1.is_tangent(Polygon((3, 0), (5, 7), (6, -5))) is False
+    assert c1.is_tangent(Segment((0, 0), (-5, -2))) is False
+    assert e1.is_tangent(Segment((-3, 0), (3, 0))) is False
+    assert e1.is_tangent(Segment((-3, 5), (3, 5))) is True
+    assert e1.is_tangent(Polygon((0, 0), (5, 5), (5, -5))) is False
+    assert e1.is_tangent(Polygon((-100, -50), (-40, -334), (-70, -52))) is False
+    assert e1.is_tangent(Polygon((-3, -5), (-3, 5), (3, 5), (3, -5))) is True
+    assert c1.is_tangent(Polygon((-3, -5), (-3, 5), (3, 5), (3, -5))) is False
+    assert e1.is_tangent(Polygon((3, 12), (3, -12), (0, -5), (0, 5))) is False
+    assert e1.is_tangent(Polygon((3, 0), (5, 7), (6, -5))) is False
+    raises(TypeError, lambda: e1.is_tangent(Point(0, 0, 0)))
+    raises(TypeError, lambda: e1.is_tangent(Rational(5)))
+
+
+def test_parameter_value():
+    t = Symbol('t')
+    e = Ellipse(Point(0, 0), 3, 5)
+    assert e.parameter_value((3, 0), t) == {t: 0}
+    raises(ValueError, lambda: e.parameter_value((4, 0), t))
+
+
+@slow
+def test_second_moment_of_area():
+    x, y = symbols('x, y')
+    e = Ellipse(Point(0, 0), 5, 4)
+    I_yy = 2*4*integrate(sqrt(25 - x**2)*x**2, (x, -5, 5))/5
+    I_xx = 2*5*integrate(sqrt(16 - y**2)*y**2, (y, -4, 4))/4
+    Y = 3*sqrt(1 - x**2/5**2)
+    I_xy = integrate(integrate(y, (y, -Y, Y))*x, (x, -5, 5))
+    assert I_yy == e.second_moment_of_area()[1]
+    assert I_xx == e.second_moment_of_area()[0]
+    assert I_xy == e.second_moment_of_area()[2]
+    #checking for other point
+    t1 = e.second_moment_of_area(Point(6,5))
+    t2 = (580*pi, 845*pi, 600*pi)
+    assert t1==t2
+
+
+def test_section_modulus_and_polar_second_moment_of_area():
+    d = Symbol('d', positive=True)
+    c = Circle((3, 7), 8)
+    assert c.polar_second_moment_of_area() == 2048*pi
+    assert c.section_modulus() == (128*pi, 128*pi)
+    c = Circle((2, 9), d/2)
+    assert c.polar_second_moment_of_area() == pi*d**3*Abs(d)/64 + pi*d*Abs(d)**3/64
+    assert c.section_modulus() == (pi*d**3/S(32), pi*d**3/S(32))
+
+    a, b = symbols('a, b', positive=True)
+    e = Ellipse((4, 6), a, b)
+    assert e.section_modulus() == (pi*a*b**2/S(4), pi*a**2*b/S(4))
+    assert e.polar_second_moment_of_area() == pi*a**3*b/S(4) + pi*a*b**3/S(4)
+    e = e.rotate(pi/2) # no change in polar and section modulus
+    assert e.section_modulus() == (pi*a**2*b/S(4), pi*a*b**2/S(4))
+    assert e.polar_second_moment_of_area() == pi*a**3*b/S(4) + pi*a*b**3/S(4)
+
+    e = Ellipse((a, b), 2, 6)
+    assert e.section_modulus() == (18*pi, 6*pi)
+    assert e.polar_second_moment_of_area() == 120*pi
+
+    e = Ellipse(Point(0, 0), 2, 2)
+    assert e.section_modulus() == (2*pi, 2*pi)
+    assert e.section_modulus(Point(2, 2)) == (2*pi, 2*pi)
+    assert e.section_modulus((2, 2)) == (2*pi, 2*pi)
+
+
+def test_circumference():
+    M = Symbol('M')
+    m = Symbol('m')
+    assert Ellipse(Point(0, 0), M, m).circumference == 4 * M * elliptic_e((M ** 2 - m ** 2) / M**2)
+
+    assert Ellipse(Point(0, 0), 5, 4).circumference == 20 * elliptic_e(S(9) / 25)
+
+    # circle
+    assert Ellipse(None, 1, None, 0).circumference == 2*pi
+
+    # test numerically
+    assert abs(Ellipse(None, hradius=5, vradius=3).circumference.evalf(16) - 25.52699886339813) < 1e-10
+
+
+def test_issue_15259():
+    assert Circle((1, 2), 0) == Point(1, 2)
+
+
+def test_issue_15797_equals():
+    Ri = 0.024127189424130748
+    Ci = (0.0864931002830291, 0.0819863295239654)
+    A = Point(0, 0.0578591400998346)
+    c = Circle(Ci, Ri)  # evaluated
+    assert c.is_tangent(c.tangent_lines(A)[0]) == True
+    assert c.center.x.is_Rational
+    assert c.center.y.is_Rational
+    assert c.radius.is_Rational
+    u = Circle(Ci, Ri, evaluate=False)  # unevaluated
+    assert u.center.x.is_Float
+    assert u.center.y.is_Float
+    assert u.radius.is_Float
+
+
+def test_auxiliary_circle():
+    x, y, a, b = symbols('x y a b')
+    e = Ellipse((x, y), a, b)
+    # the general result
+    assert e.auxiliary_circle() == Circle((x, y), Max(a, b))
+    # a special case where Ellipse is a Circle
+    assert Circle((3, 4), 8).auxiliary_circle() == Circle((3, 4), 8)
+
+
+def test_director_circle():
+    x, y, a, b = symbols('x y a b')
+    e = Ellipse((x, y), a, b)
+    # the general result
+    assert e.director_circle() == Circle((x, y), sqrt(a**2 + b**2))
+    # a special case where Ellipse is a Circle
+    assert Circle((3, 4), 8).director_circle() == Circle((3, 4), 8*sqrt(2))
+
+
+def test_evolute():
+    #ellipse centered at h,k
+    x, y, h, k = symbols('x y h k',real = True)
+    a, b = symbols('a b')
+    e = Ellipse(Point(h, k), a, b)
+    t1 = (e.hradius*(x - e.center.x))**Rational(2, 3)
+    t2 = (e.vradius*(y - e.center.y))**Rational(2, 3)
+    E = t1 + t2 - (e.hradius**2 - e.vradius**2)**Rational(2, 3)
+    assert e.evolute() == E
+    #Numerical Example
+    e = Ellipse(Point(1, 1), 6, 3)
+    t1 = (6*(x - 1))**Rational(2, 3)
+    t2 = (3*(y - 1))**Rational(2, 3)
+    E = t1 + t2 - (27)**Rational(2, 3)
+    assert e.evolute() == E
+
+
+def test_svg():
+    e1 = Ellipse(Point(1, 0), 3, 2)
+    assert e1._svg(2, "#FFAAFF") == ''
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_entity.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_entity.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d440fd5dbd193c7c490b45a706fab2703e247ec
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_entity.py
@@ -0,0 +1,120 @@
+from sympy.core.numbers import (Rational, pi)
+from sympy.core.singleton import S
+from sympy.core.symbol import Symbol
+from sympy.geometry import (Circle, Ellipse, Point, Line, Parabola,
+    Polygon, Ray, RegularPolygon, Segment, Triangle, Plane, Curve)
+from sympy.geometry.entity import scale, GeometryEntity
+from sympy.testing.pytest import raises
+
+
+def test_entity():
+    x = Symbol('x', real=True)
+    y = Symbol('y', real=True)
+
+    assert GeometryEntity(x, y) in GeometryEntity(x, y)
+    raises(NotImplementedError, lambda: Point(0, 0) in GeometryEntity(x, y))
+
+    assert GeometryEntity(x, y) == GeometryEntity(x, y)
+    assert GeometryEntity(x, y).equals(GeometryEntity(x, y))
+
+    c = Circle((0, 0), 5)
+    assert GeometryEntity.encloses(c, Point(0, 0))
+    assert GeometryEntity.encloses(c, Segment((0, 0), (1, 1)))
+    assert GeometryEntity.encloses(c, Line((0, 0), (1, 1))) is False
+    assert GeometryEntity.encloses(c, Circle((0, 0), 4))
+    assert GeometryEntity.encloses(c, Polygon(Point(0, 0), Point(1, 0), Point(0, 1)))
+    assert GeometryEntity.encloses(c, RegularPolygon(Point(8, 8), 1, 3)) is False
+
+
+def test_svg():
+    a = Symbol('a')
+    b = Symbol('b')
+    d = Symbol('d')
+
+    entity = Circle(Point(a, b), d)
+    assert entity._repr_svg_() is None
+
+    entity = Circle(Point(0, 0), S.Infinity)
+    assert entity._repr_svg_() is None
+
+
+def test_subs():
+    x = Symbol('x', real=True)
+    y = Symbol('y', real=True)
+    p = Point(x, 2)
+    q = Point(1, 1)
+    r = Point(3, 4)
+    for o in [p,
+              Segment(p, q),
+              Ray(p, q),
+              Line(p, q),
+              Triangle(p, q, r),
+              RegularPolygon(p, 3, 6),
+              Polygon(p, q, r, Point(5, 4)),
+              Circle(p, 3),
+              Ellipse(p, 3, 4)]:
+        assert 'y' in str(o.subs(x, y))
+    assert p.subs({x: 1}) == Point(1, 2)
+    assert Point(1, 2).subs(Point(1, 2), Point(3, 4)) == Point(3, 4)
+    assert Point(1, 2).subs((1, 2), Point(3, 4)) == Point(3, 4)
+    assert Point(1, 2).subs(Point(1, 2), Point(3, 4)) == Point(3, 4)
+    assert Point(1, 2).subs({(1, 2)}) == Point(2, 2)
+    raises(ValueError, lambda: Point(1, 2).subs(1))
+    raises(TypeError, lambda: Point(1, 1).subs((Point(1, 1), Point(1,
+           2)), 1, 2))
+
+
+def test_transform():
+    assert scale(1, 2, (3, 4)).tolist() == \
+        [[1, 0, 0], [0, 2, 0], [0, -4, 1]]
+
+
+def test_reflect_entity_overrides():
+    x = Symbol('x', real=True)
+    y = Symbol('y', real=True)
+    b = Symbol('b')
+    m = Symbol('m')
+    l = Line((0, b), slope=m)
+    p = Point(x, y)
+    r = p.reflect(l)
+    c = Circle((x, y), 3)
+    cr = c.reflect(l)
+    assert cr == Circle(r, -3)
+    assert c.area == -cr.area
+
+    pent = RegularPolygon((1, 2), 1, 5)
+    slope = S.ComplexInfinity
+    while slope is S.ComplexInfinity:
+        slope = Rational(*(x._random()/2).as_real_imag())
+    l = Line(pent.vertices[1], slope=slope)
+    rpent = pent.reflect(l)
+    assert rpent.center == pent.center.reflect(l)
+    rvert = [i.reflect(l) for i in pent.vertices]
+    for v in rpent.vertices:
+        for i in range(len(rvert)):
+            ri = rvert[i]
+            if ri.equals(v):
+                rvert.remove(ri)
+                break
+    assert not rvert
+    assert pent.area.equals(-rpent.area)
+
+
+def test_geometry_EvalfMixin():
+    x = pi
+    t = Symbol('t')
+    for g in [
+            Point(x, x),
+            Plane(Point(0, x, 0), (0, 0, x)),
+            Curve((x*t, x), (t, 0, x)),
+            Ellipse((x, x), x, -x),
+            Circle((x, x), x),
+            Line((0, x), (x, 0)),
+            Segment((0, x), (x, 0)),
+            Ray((0, x), (x, 0)),
+            Parabola((0, x), Line((-x, 0), (x, 0))),
+            Polygon((0, 0), (0, x), (x, 0), (x, x)),
+            RegularPolygon((0, x), x, 4, x),
+            Triangle((0, 0), (x, 0), (x, x)),
+            ]:
+        assert str(g).replace('pi', '3.1') == str(g.n(2))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_geometrysets.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_geometrysets.py
new file mode 100644
index 0000000000000000000000000000000000000000..c52898b3c9ba4e9db80c244db3aebf88db2cc8b4
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_geometrysets.py
@@ -0,0 +1,38 @@
+from sympy.core.numbers import Rational
+from sympy.core.singleton import S
+from sympy.geometry import Circle, Line, Point, Polygon, Segment
+from sympy.sets import FiniteSet, Union, Intersection, EmptySet
+
+
+def test_booleans():
+    """ test basic unions and intersections """
+    half = S.Half
+
+    p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)])
+    p5, p6, p7 = map(Point, [(3, 2), (1, -1), (0, 2)])
+    l1 = Line(Point(0,0), Point(1,1))
+    l2 = Line(Point(half, half), Point(5,5))
+    l3 = Line(p2, p3)
+    l4 = Line(p3, p4)
+    poly1 = Polygon(p1, p2, p3, p4)
+    poly2 = Polygon(p5, p6, p7)
+    poly3 = Polygon(p1, p2, p5)
+    assert Union(l1, l2).equals(l1)
+    assert Intersection(l1, l2).equals(l1)
+    assert Intersection(l1, l4) == FiniteSet(Point(1,1))
+    assert Intersection(Union(l1, l4), l3) == FiniteSet(Point(Rational(-1, 3), Rational(-1, 3)), Point(5, 1))
+    assert Intersection(l1, FiniteSet(Point(7,-7))) == EmptySet
+    assert Intersection(Circle(Point(0,0), 3), Line(p1,p2)) == FiniteSet(Point(-3,0), Point(3,0))
+    assert Intersection(l1, FiniteSet(p1)) == FiniteSet(p1)
+    assert Union(l1, FiniteSet(p1)) == l1
+
+    fs = FiniteSet(Point(Rational(1, 3), 1), Point(Rational(2, 3), 0), Point(Rational(9, 5), Rational(1, 5)), Point(Rational(7, 3), 1))
+    # test the intersection of polygons
+    assert Intersection(poly1, poly2) == fs
+    # make sure if we union polygons with subsets, the subsets go away
+    assert Union(poly1, poly2, fs) == Union(poly1, poly2)
+    # make sure that if we union with a FiniteSet that isn't a subset,
+    # that the points in the intersection stop being listed
+    assert Union(poly1, FiniteSet(Point(0,0), Point(3,5))) == Union(poly1, FiniteSet(Point(3,5)))
+    # intersect two polygons that share an edge
+    assert Intersection(poly1, poly3) == Union(FiniteSet(Point(Rational(3, 2), 1), Point(2, 1)), Segment(Point(0, 0), Point(1, 0)))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_line.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_line.py
new file mode 100644
index 0000000000000000000000000000000000000000..5158ec05ab414020fbbe2681a2658454dd15b6eb
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_line.py
@@ -0,0 +1,861 @@
+from sympy.core.numbers import (Float, Rational, oo, pi)
+from sympy.core.relational import Eq
+from sympy.core.singleton import S
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import (acos, cos, sin)
+from sympy.sets import EmptySet
+from sympy.simplify.simplify import simplify
+from sympy.functions.elementary.trigonometric import tan
+from sympy.geometry import (Circle, GeometryError, Line, Point, Ray,
+    Segment, Triangle, intersection, Point3D, Line3D, Ray3D, Segment3D,
+    Point2D, Line2D, Plane)
+from sympy.geometry.line import Undecidable
+from sympy.geometry.polygon import _asa as asa
+from sympy.utilities.iterables import cartes
+from sympy.testing.pytest import raises, warns
+
+
+x = Symbol('x', real=True)
+y = Symbol('y', real=True)
+z = Symbol('z', real=True)
+k = Symbol('k', real=True)
+x1 = Symbol('x1', real=True)
+y1 = Symbol('y1', real=True)
+t = Symbol('t', real=True)
+a, b = symbols('a,b', real=True)
+m = symbols('m', real=True)
+
+
+def test_object_from_equation():
+    from sympy.abc import x, y, a, b
+    assert Line(3*x + y + 18) == Line2D(Point2D(0, -18), Point2D(1, -21))
+    assert Line(3*x + 5 * y + 1) == Line2D(
+        Point2D(0, Rational(-1, 5)), Point2D(1, Rational(-4, 5)))
+    assert Line(3*a + b + 18, x="a", y="b") == Line2D(
+        Point2D(0, -18), Point2D(1, -21))
+    assert Line(3*x + y) == Line2D(Point2D(0, 0), Point2D(1, -3))
+    assert Line(x + y) == Line2D(Point2D(0, 0), Point2D(1, -1))
+    assert Line(Eq(3*a + b, -18), x="a", y=b) == Line2D(
+        Point2D(0, -18), Point2D(1, -21))
+    # issue 22361
+    assert Line(x - 1) == Line2D(Point2D(1, 0), Point2D(1, 1))
+    assert Line(2*x - 2, y=x) == Line2D(Point2D(0, 1), Point2D(1, 1))
+    assert Line(y) == Line2D(Point2D(0, 0), Point2D(1, 0))
+    assert Line(2*y, x=y) == Line2D(Point2D(0, 0), Point2D(0, 1))
+    assert Line(y, x=y) == Line2D(Point2D(0, 0), Point2D(0, 1))
+    raises(ValueError, lambda: Line(x / y))
+    raises(ValueError, lambda: Line(a / b, x='a', y='b'))
+    raises(ValueError, lambda: Line(y / x))
+    raises(ValueError, lambda: Line(b / a, x='a', y='b'))
+    raises(ValueError, lambda: Line((x + 1)**2 + y))
+
+
+def feq(a, b):
+    """Test if two floating point values are 'equal'."""
+    t_float = Float("1.0E-10")
+    return -t_float < a - b < t_float
+
+
+def test_angle_between():
+    a = Point(1, 2, 3, 4)
+    b = a.orthogonal_direction
+    o = a.origin
+    assert feq(Line.angle_between(Line(Point(0, 0), Point(1, 1)),
+                                  Line(Point(0, 0), Point(5, 0))).evalf(), pi.evalf() / 4)
+    assert Line(a, o).angle_between(Line(b, o)) == pi / 2
+    z = Point3D(0, 0, 0)
+    assert Line3D.angle_between(Line3D(z, Point3D(1, 1, 1)),
+                                Line3D(z, Point3D(5, 0, 0))) == acos(sqrt(3) / 3)
+    # direction of points is used to determine angle
+    assert Line3D.angle_between(Line3D(z, Point3D(1, 1, 1)),
+                                Line3D(Point3D(5, 0, 0), z)) == acos(-sqrt(3) / 3)
+
+
+def test_closing_angle():
+    a = Ray((0, 0), angle=0)
+    b = Ray((1, 2), angle=pi/2)
+    assert a.closing_angle(b) == -pi/2
+    assert b.closing_angle(a) == pi/2
+    assert a.closing_angle(a) == 0
+
+
+def test_smallest_angle():
+    a = Line(Point(1, 1), Point(1, 2))
+    b = Line(Point(1, 1),Point(2, 3))
+    assert a.smallest_angle_between(b) == acos(2*sqrt(5)/5)
+
+
+def test_svg():
+    a = Line(Point(1, 1),Point(1, 2))
+    assert a._svg() == ''
+    a = Segment(Point(1, 0),Point(1, 1))
+    assert a._svg() == ''
+    a = Ray(Point(2, 3), Point(3, 5))
+    assert a._svg() == ''
+
+
+def test_arbitrary_point():
+    l1 = Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1))
+    l2 = Line(Point(x1, x1), Point(y1, y1))
+    assert l2.arbitrary_point() in l2
+    assert Ray((1, 1), angle=pi / 4).arbitrary_point() == \
+           Point(t + 1, t + 1)
+    assert Segment((1, 1), (2, 3)).arbitrary_point() == Point(1 + t, 1 + 2 * t)
+    assert l1.perpendicular_segment(l1.arbitrary_point()) == l1.arbitrary_point()
+    assert Ray3D((1, 1, 1), direction_ratio=[1, 2, 3]).arbitrary_point() == \
+           Point3D(t + 1, 2 * t + 1, 3 * t + 1)
+    assert Segment3D(Point3D(0, 0, 0), Point3D(1, 1, 1)).midpoint == \
+           Point3D(S.Half, S.Half, S.Half)
+    assert Segment3D(Point3D(x1, x1, x1), Point3D(y1, y1, y1)).length == sqrt(3) * sqrt((x1 - y1) ** 2)
+    assert Segment3D((1, 1, 1), (2, 3, 4)).arbitrary_point() == \
+           Point3D(t + 1, 2 * t + 1, 3 * t + 1)
+    raises(ValueError, (lambda: Line((x, 1), (2, 3)).arbitrary_point(x)))
+
+
+def test_are_concurrent_2d():
+    l1 = Line(Point(0, 0), Point(1, 1))
+    l2 = Line(Point(x1, x1), Point(x1, 1 + x1))
+    assert Line.are_concurrent(l1) is False
+    assert Line.are_concurrent(l1, l2)
+    assert Line.are_concurrent(l1, l1, l1, l2)
+    assert Line.are_concurrent(l1, l2, Line(Point(5, x1), Point(Rational(-3, 5), x1)))
+    assert Line.are_concurrent(l1, Line(Point(0, 0), Point(-x1, x1)), l2) is False
+
+
+def test_are_concurrent_3d():
+    p1 = Point3D(0, 0, 0)
+    l1 = Line(p1, Point3D(1, 1, 1))
+    parallel_1 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0))
+    parallel_2 = Line3D(Point3D(0, 1, 0), Point3D(1, 1, 0))
+    assert Line3D.are_concurrent(l1) is False
+    assert Line3D.are_concurrent(l1, Line(Point3D(x1, x1, x1), Point3D(y1, y1, y1))) is False
+    assert Line3D.are_concurrent(l1, Line3D(p1, Point3D(x1, x1, x1)),
+                                 Line(Point3D(x1, x1, x1), Point3D(x1, 1 + x1, 1))) is True
+    assert Line3D.are_concurrent(parallel_1, parallel_2) is False
+
+
+def test_arguments():
+    """Functions accepting `Point` objects in `geometry`
+    should also accept tuples, lists, and generators and
+    automatically convert them to points."""
+    from sympy.utilities.iterables import subsets
+
+    singles2d = ((1, 2), [1, 3], Point(1, 5))
+    doubles2d = subsets(singles2d, 2)
+    l2d = Line(Point2D(1, 2), Point2D(2, 3))
+    singles3d = ((1, 2, 3), [1, 2, 4], Point(1, 2, 6))
+    doubles3d = subsets(singles3d, 2)
+    l3d = Line(Point3D(1, 2, 3), Point3D(1, 1, 2))
+    singles4d = ((1, 2, 3, 4), [1, 2, 3, 5], Point(1, 2, 3, 7))
+    doubles4d = subsets(singles4d, 2)
+    l4d = Line(Point(1, 2, 3, 4), Point(2, 2, 2, 2))
+    # test 2D
+    test_single = ['contains', 'distance', 'equals', 'parallel_line', 'perpendicular_line', 'perpendicular_segment',
+                   'projection', 'intersection']
+    for p in doubles2d:
+        Line2D(*p)
+    for func in test_single:
+        for p in singles2d:
+            getattr(l2d, func)(p)
+    # test 3D
+    for p in doubles3d:
+        Line3D(*p)
+    for func in test_single:
+        for p in singles3d:
+            getattr(l3d, func)(p)
+    # test 4D
+    for p in doubles4d:
+        Line(*p)
+    for func in test_single:
+        for p in singles4d:
+            getattr(l4d, func)(p)
+
+
+def test_basic_properties_2d():
+    p1 = Point(0, 0)
+    p2 = Point(1, 1)
+    p10 = Point(2000, 2000)
+    p_r3 = Ray(p1, p2).random_point()
+    p_r4 = Ray(p2, p1).random_point()
+
+    l1 = Line(p1, p2)
+    l3 = Line(Point(x1, x1), Point(x1, 1 + x1))
+    l4 = Line(p1, Point(1, 0))
+
+    r1 = Ray(p1, Point(0, 1))
+    r2 = Ray(Point(0, 1), p1)
+
+    s1 = Segment(p1, p10)
+    p_s1 = s1.random_point()
+
+    assert Line((1, 1), slope=1) == Line((1, 1), (2, 2))
+    assert Line((1, 1), slope=oo) == Line((1, 1), (1, 2))
+    assert Line((1, 1), slope=oo).bounds == (1, 1, 1, 2)
+    assert Line((1, 1), slope=-oo) == Line((1, 1), (1, 2))
+    assert Line(p1, p2).scale(2, 1) == Line(p1, Point(2, 1))
+    assert Line(p1, p2) == Line(p1, p2)
+    assert Line(p1, p2) != Line(p2, p1)
+    assert l1 != Line(Point(x1, x1), Point(y1, y1))
+    assert l1 != l3
+    assert Line(p1, p10) != Line(p10, p1)
+    assert Line(p1, p10) != p1
+    assert p1 in l1  # is p1 on the line l1?
+    assert p1 not in l3
+    assert s1 in Line(p1, p10)
+    assert Ray(Point(0, 0), Point(0, 1)) in Ray(Point(0, 0), Point(0, 2))
+    assert Ray(Point(0, 0), Point(0, 2)) in Ray(Point(0, 0), Point(0, 1))
+    assert Ray(Point(0, 0), Point(0, 2)).xdirection == S.Zero
+    assert Ray(Point(0, 0), Point(1, 2)).xdirection == S.Infinity
+    assert Ray(Point(0, 0), Point(-1, 2)).xdirection == S.NegativeInfinity
+    assert Ray(Point(0, 0), Point(2, 0)).ydirection == S.Zero
+    assert Ray(Point(0, 0), Point(2, 2)).ydirection == S.Infinity
+    assert Ray(Point(0, 0), Point(2, -2)).ydirection == S.NegativeInfinity
+    assert (r1 in s1) is False
+    assert Segment(p1, p2) in s1
+    assert Ray(Point(x1, x1), Point(x1, 1 + x1)) != Ray(p1, Point(-1, 5))
+    assert Segment(p1, p2).midpoint == Point(S.Half, S.Half)
+    assert Segment(p1, Point(-x1, x1)).length == sqrt(2 * (x1 ** 2))
+
+    assert l1.slope == 1
+    assert l3.slope is oo
+    assert l4.slope == 0
+    assert Line(p1, Point(0, 1)).slope is oo
+    assert Line(r1.source, r1.random_point()).slope == r1.slope
+    assert Line(r2.source, r2.random_point()).slope == r2.slope
+    assert Segment(Point(0, -1), Segment(p1, Point(0, 1)).random_point()).slope == Segment(p1, Point(0, 1)).slope
+
+    assert l4.coefficients == (0, 1, 0)
+    assert Line((-x, x), (-x + 1, x - 1)).coefficients == (1, 1, 0)
+    assert Line(p1, Point(0, 1)).coefficients == (1, 0, 0)
+    # issue 7963
+    r = Ray((0, 0), angle=x)
+    assert r.subs(x, 3 * pi / 4) == Ray((0, 0), (-1, 1))
+    assert r.subs(x, 5 * pi / 4) == Ray((0, 0), (-1, -1))
+    assert r.subs(x, -pi / 4) == Ray((0, 0), (1, -1))
+    assert r.subs(x, pi / 2) == Ray((0, 0), (0, 1))
+    assert r.subs(x, -pi / 2) == Ray((0, 0), (0, -1))
+
+    for ind in range(0, 5):
+        assert l3.random_point() in l3
+
+    assert p_r3.x >= p1.x and p_r3.y >= p1.y
+    assert p_r4.x <= p2.x and p_r4.y <= p2.y
+    assert p1.x <= p_s1.x <= p10.x and p1.y <= p_s1.y <= p10.y
+    assert hash(s1) != hash(Segment(p10, p1))
+
+    assert s1.plot_interval() == [t, 0, 1]
+    assert Line(p1, p10).plot_interval() == [t, -5, 5]
+    assert Ray((0, 0), angle=pi / 4).plot_interval() == [t, 0, 10]
+
+
+def test_basic_properties_3d():
+    p1 = Point3D(0, 0, 0)
+    p2 = Point3D(1, 1, 1)
+    p3 = Point3D(x1, x1, x1)
+    p5 = Point3D(x1, 1 + x1, 1)
+
+    l1 = Line3D(p1, p2)
+    l3 = Line3D(p3, p5)
+
+    r1 = Ray3D(p1, Point3D(-1, 5, 0))
+    r3 = Ray3D(p1, p2)
+
+    s1 = Segment3D(p1, p2)
+
+    assert Line3D((1, 1, 1), direction_ratio=[2, 3, 4]) == Line3D(Point3D(1, 1, 1), Point3D(3, 4, 5))
+    assert Line3D((1, 1, 1), direction_ratio=[1, 5, 7]) == Line3D(Point3D(1, 1, 1), Point3D(2, 6, 8))
+    assert Line3D((1, 1, 1), direction_ratio=[1, 2, 3]) == Line3D(Point3D(1, 1, 1), Point3D(2, 3, 4))
+    assert Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).direction_cosine == [1, 0, 0]
+    assert Line3D(Line3D(p1, Point3D(0, 1, 0))) == Line3D(p1, Point3D(0, 1, 0))
+    assert Ray3D(Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0))) == Ray3D(p1, Point3D(1, 0, 0))
+    assert Line3D(p1, p2) != Line3D(p2, p1)
+    assert l1 != l3
+    assert l1 != Line3D(p3, Point3D(y1, y1, y1))
+    assert r3 != r1
+    assert Ray3D(Point3D(0, 0, 0), Point3D(1, 1, 1)) in Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2))
+    assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)) in Ray3D(Point3D(0, 0, 0), Point3D(1, 1, 1))
+    assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)).xdirection == S.Infinity
+    assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)).ydirection == S.Infinity
+    assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)).zdirection == S.Infinity
+    assert Ray3D(Point3D(0, 0, 0), Point3D(-2, 2, 2)).xdirection == S.NegativeInfinity
+    assert Ray3D(Point3D(0, 0, 0), Point3D(2, -2, 2)).ydirection == S.NegativeInfinity
+    assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, -2)).zdirection == S.NegativeInfinity
+    assert Ray3D(Point3D(0, 0, 0), Point3D(0, 2, 2)).xdirection == S.Zero
+    assert Ray3D(Point3D(0, 0, 0), Point3D(2, 0, 2)).ydirection == S.Zero
+    assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 0)).zdirection == S.Zero
+    assert p1 in l1
+    assert p1 not in l3
+
+    assert l1.direction_ratio == [1, 1, 1]
+
+    assert s1.midpoint == Point3D(S.Half, S.Half, S.Half)
+    # Test zdirection
+    assert Ray3D(p1, Point3D(0, 0, -1)).zdirection is S.NegativeInfinity
+
+
+def test_contains():
+    p1 = Point(0, 0)
+
+    r = Ray(p1, Point(4, 4))
+    r1 = Ray3D(p1, Point3D(0, 0, -1))
+    r2 = Ray3D(p1, Point3D(0, 1, 0))
+    r3 = Ray3D(p1, Point3D(0, 0, 1))
+
+    l = Line(Point(0, 1), Point(3, 4))
+    # Segment contains
+    assert Point(0, (a + b) / 2) in Segment((0, a), (0, b))
+    assert Point((a + b) / 2, 0) in Segment((a, 0), (b, 0))
+    assert Point3D(0, 1, 0) in Segment3D((0, 1, 0), (0, 1, 0))
+    assert Point3D(1, 0, 0) in Segment3D((1, 0, 0), (1, 0, 0))
+    assert Segment3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).contains([]) is True
+    assert Segment3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).contains(
+        Segment3D(Point3D(2, 2, 2), Point3D(3, 2, 2))) is False
+    # Line contains
+    assert l.contains(Point(0, 1)) is True
+    assert l.contains((0, 1)) is True
+    assert l.contains((0, 0)) is False
+    # Ray contains
+    assert r.contains(p1) is True
+    assert r.contains((1, 1)) is True
+    assert r.contains((1, 3)) is False
+    assert r.contains(Segment((1, 1), (2, 2))) is True
+    assert r.contains(Segment((1, 2), (2, 5))) is False
+    assert r.contains(Ray((2, 2), (3, 3))) is True
+    assert r.contains(Ray((2, 2), (3, 5))) is False
+    assert r1.contains(Segment3D(p1, Point3D(0, 0, -10))) is True
+    assert r1.contains(Segment3D(Point3D(1, 1, 1), Point3D(2, 2, 2))) is False
+    assert r2.contains(Point3D(0, 0, 0)) is True
+    assert r3.contains(Point3D(0, 0, 0)) is True
+    assert Ray3D(Point3D(1, 1, 1), Point3D(1, 0, 0)).contains([]) is False
+    assert Line3D((0, 0, 0), (x, y, z)).contains((2 * x, 2 * y, 2 * z))
+    with warns(UserWarning, test_stacklevel=False):
+        assert Line3D(p1, Point3D(0, 1, 0)).contains(Point(1.0, 1.0)) is False
+
+    with warns(UserWarning, test_stacklevel=False):
+        assert r3.contains(Point(1.0, 1.0)) is False
+
+
+def test_contains_nonreal_symbols():
+    u, v, w, z = symbols('u, v, w, z')
+    l = Segment(Point(u, w), Point(v, z))
+    p = Point(u*Rational(2, 3) + v/3, w*Rational(2, 3) + z/3)
+    assert l.contains(p)
+
+
+def test_distance_2d():
+    p1 = Point(0, 0)
+    p2 = Point(1, 1)
+    half = S.Half
+
+    s1 = Segment(Point(0, 0), Point(1, 1))
+    s2 = Segment(Point(half, half), Point(1, 0))
+
+    r = Ray(p1, p2)
+
+    assert s1.distance(Point(0, 0)) == 0
+    assert s1.distance((0, 0)) == 0
+    assert s2.distance(Point(0, 0)) == 2 ** half / 2
+    assert s2.distance(Point(Rational(3) / 2, Rational(3) / 2)) == 2 ** half
+    assert Line(p1, p2).distance(Point(-1, 1)) == sqrt(2)
+    assert Line(p1, p2).distance(Point(1, -1)) == sqrt(2)
+    assert Line(p1, p2).distance(Point(2, 2)) == 0
+    assert Line(p1, p2).distance((-1, 1)) == sqrt(2)
+    assert Line((0, 0), (0, 1)).distance(p1) == 0
+    assert Line((0, 0), (0, 1)).distance(p2) == 1
+    assert Line((0, 0), (1, 0)).distance(p1) == 0
+    assert Line((0, 0), (1, 0)).distance(p2) == 1
+    assert r.distance(Point(-1, -1)) == sqrt(2)
+    assert r.distance(Point(1, 1)) == 0
+    assert r.distance(Point(-1, 1)) == sqrt(2)
+    assert Ray((1, 1), (2, 2)).distance(Point(1.5, 3)) == 3 * sqrt(2) / 4
+    assert r.distance((1, 1)) == 0
+
+
+def test_dimension_normalization():
+    with warns(UserWarning, test_stacklevel=False):
+        assert Ray((1, 1), (2, 1, 2)) == Ray((1, 1, 0), (2, 1, 2))
+
+
+def test_distance_3d():
+    p1, p2 = Point3D(0, 0, 0), Point3D(1, 1, 1)
+    p3 = Point3D(Rational(3) / 2, Rational(3) / 2, Rational(3) / 2)
+
+    s1 = Segment3D(Point3D(0, 0, 0), Point3D(1, 1, 1))
+    s2 = Segment3D(Point3D(S.Half, S.Half, S.Half), Point3D(1, 0, 1))
+
+    r = Ray3D(p1, p2)
+
+    assert s1.distance(p1) == 0
+    assert s2.distance(p1) == sqrt(3) / 2
+    assert s2.distance(p3) == 2 * sqrt(6) / 3
+    assert s1.distance((0, 0, 0)) == 0
+    assert s2.distance((0, 0, 0)) == sqrt(3) / 2
+    assert s1.distance(p1) == 0
+    assert s2.distance(p1) == sqrt(3) / 2
+    assert s2.distance(p3) == 2 * sqrt(6) / 3
+    assert s1.distance((0, 0, 0)) == 0
+    assert s2.distance((0, 0, 0)) == sqrt(3) / 2
+    # Line to point
+    assert Line3D(p1, p2).distance(Point3D(-1, 1, 1)) == 2 * sqrt(6) / 3
+    assert Line3D(p1, p2).distance(Point3D(1, -1, 1)) == 2 * sqrt(6) / 3
+    assert Line3D(p1, p2).distance(Point3D(2, 2, 2)) == 0
+    assert Line3D(p1, p2).distance((2, 2, 2)) == 0
+    assert Line3D(p1, p2).distance((1, -1, 1)) == 2 * sqrt(6) / 3
+    assert Line3D((0, 0, 0), (0, 1, 0)).distance(p1) == 0
+    assert Line3D((0, 0, 0), (0, 1, 0)).distance(p2) == sqrt(2)
+    assert Line3D((0, 0, 0), (1, 0, 0)).distance(p1) == 0
+    assert Line3D((0, 0, 0), (1, 0, 0)).distance(p2) == sqrt(2)
+    # Line to line
+    assert Line3D((0, 0, 0), (1, 0, 0)).distance(Line3D((0, 0, 0), (0, 1, 2))) == 0
+    assert Line3D((0, 0, 0), (1, 0, 0)).distance(Line3D((0, 0, 0), (1, 0, 0))) == 0
+    assert Line3D((0, 0, 0), (1, 0, 0)).distance(Line3D((10, 0, 0), (10, 1, 2))) == 0
+    assert Line3D((0, 0, 0), (1, 0, 0)).distance(Line3D((0, 1, 0), (0, 1, 1))) == 1
+    # Line to plane
+    assert Line3D((0, 0, 0), (1, 0, 0)).distance(Plane((2, 0, 0), (0, 0, 1))) == 0
+    assert Line3D((0, 0, 0), (1, 0, 0)).distance(Plane((0, 1, 0), (0, 1, 0))) == 1
+    assert Line3D((0, 0, 0), (1, 0, 0)).distance(Plane((1, 1, 3), (1, 0, 0))) == 0
+    # Ray to point
+    assert r.distance(Point3D(-1, -1, -1)) == sqrt(3)
+    assert r.distance(Point3D(1, 1, 1)) == 0
+    assert r.distance((-1, -1, -1)) == sqrt(3)
+    assert r.distance((1, 1, 1)) == 0
+    assert Ray3D((0, 0, 0), (1, 1, 2)).distance((-1, -1, 2)) == 4 * sqrt(3) / 3
+    assert Ray3D((1, 1, 1), (2, 2, 2)).distance(Point3D(1.5, -3, -1)) == Rational(9) / 2
+    assert Ray3D((1, 1, 1), (2, 2, 2)).distance(Point3D(1.5, 3, 1)) == sqrt(78) / 6
+
+
+def test_equals():
+    p1 = Point(0, 0)
+    p2 = Point(1, 1)
+
+    l1 = Line(p1, p2)
+    l2 = Line((0, 5), slope=m)
+    l3 = Line(Point(x1, x1), Point(x1, 1 + x1))
+
+    assert l1.perpendicular_line(p1.args).equals(Line(Point(0, 0), Point(1, -1)))
+    assert l1.perpendicular_line(p1).equals(Line(Point(0, 0), Point(1, -1)))
+    assert Line(Point(x1, x1), Point(y1, y1)).parallel_line(Point(-x1, x1)). \
+        equals(Line(Point(-x1, x1), Point(-y1, 2 * x1 - y1)))
+    assert l3.parallel_line(p1.args).equals(Line(Point(0, 0), Point(0, -1)))
+    assert l3.parallel_line(p1).equals(Line(Point(0, 0), Point(0, -1)))
+    assert (l2.distance(Point(2, 3)) - 2 * abs(m + 1) / sqrt(m ** 2 + 1)).equals(0)
+    assert Line3D(p1, Point3D(0, 1, 0)).equals(Point(1.0, 1.0)) is False
+    assert Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).equals(Line3D(Point3D(-5, 0, 0), Point3D(-1, 0, 0))) is True
+    assert Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).equals(Line3D(p1, Point3D(0, 1, 0))) is False
+    assert Ray3D(p1, Point3D(0, 0, -1)).equals(Point(1.0, 1.0)) is False
+    assert Ray3D(p1, Point3D(0, 0, -1)).equals(Ray3D(p1, Point3D(0, 0, -1))) is True
+    assert Line3D((0, 0), (t, t)).perpendicular_line(Point(0, 1, 0)).equals(
+        Line3D(Point3D(0, 1, 0), Point3D(S.Half, S.Half, 0)))
+    assert Line3D((0, 0), (t, t)).perpendicular_segment(Point(0, 1, 0)).equals(Segment3D((0, 1), (S.Half, S.Half)))
+    assert Line3D(p1, Point3D(0, 1, 0)).equals(Point(1.0, 1.0)) is False
+
+
+def test_equation():
+    p1 = Point(0, 0)
+    p2 = Point(1, 1)
+    l1 = Line(p1, p2)
+    l3 = Line(Point(x1, x1), Point(x1, 1 + x1))
+
+    assert simplify(l1.equation()) in (x - y, y - x)
+    assert simplify(l3.equation()) in (x - x1, x1 - x)
+    assert simplify(l1.equation()) in (x - y, y - x)
+    assert simplify(l3.equation()) in (x - x1, x1 - x)
+
+    assert Line(p1, Point(1, 0)).equation(x=x, y=y) == y
+    assert Line(p1, Point(0, 1)).equation() == x
+    assert Line(Point(2, 0), Point(2, 1)).equation() == x - 2
+    assert Line(p2, Point(2, 1)).equation() == y - 1
+
+    assert Line3D(Point(x1, x1, x1), Point(y1, y1, y1)
+        ).equation() == (-x + y, -x + z)
+    assert Line3D(Point(1, 2, 3), Point(2, 3, 4)
+        ).equation() == (-x + y - 1, -x + z - 2)
+    assert Line3D(Point(1, 2, 3), Point(1, 3, 4)
+        ).equation() == (x - 1, -y + z - 1)
+    assert Line3D(Point(1, 2, 3), Point(2, 2, 4)
+        ).equation() == (y - 2, -x + z - 2)
+    assert Line3D(Point(1, 2, 3), Point(2, 3, 3)
+        ).equation() == (-x + y - 1, z - 3)
+    assert Line3D(Point(1, 2, 3), Point(1, 2, 4)
+        ).equation() == (x - 1, y - 2)
+    assert Line3D(Point(1, 2, 3), Point(1, 3, 3)
+        ).equation() == (x - 1, z - 3)
+    assert Line3D(Point(1, 2, 3), Point(2, 2, 3)
+        ).equation() == (y - 2, z - 3)
+
+
+def test_intersection_2d():
+    p1 = Point(0, 0)
+    p2 = Point(1, 1)
+    p3 = Point(x1, x1)
+    p4 = Point(y1, y1)
+
+    l1 = Line(p1, p2)
+    l3 = Line(Point(0, 0), Point(3, 4))
+
+    r1 = Ray(Point(1, 1), Point(2, 2))
+    r2 = Ray(Point(0, 0), Point(3, 4))
+    r4 = Ray(p1, p2)
+    r6 = Ray(Point(0, 1), Point(1, 2))
+    r7 = Ray(Point(0.5, 0.5), Point(1, 1))
+
+    s1 = Segment(p1, p2)
+    s2 = Segment(Point(0.25, 0.25), Point(0.5, 0.5))
+    s3 = Segment(Point(0, 0), Point(3, 4))
+
+    assert intersection(l1, p1) == [p1]
+    assert intersection(l1, Point(x1, 1 + x1)) == []
+    assert intersection(l1, Line(p3, p4)) in [[l1], [Line(p3, p4)]]
+    assert intersection(l1, l1.parallel_line(Point(x1, 1 + x1))) == []
+    assert intersection(l3, l3) == [l3]
+    assert intersection(l3, r2) == [r2]
+    assert intersection(l3, s3) == [s3]
+    assert intersection(s3, l3) == [s3]
+    assert intersection(Segment(Point(-10, 10), Point(10, 10)), Segment(Point(-5, -5), Point(-5, 5))) == []
+    assert intersection(r2, l3) == [r2]
+    assert intersection(r1, Ray(Point(2, 2), Point(0, 0))) == [Segment(Point(1, 1), Point(2, 2))]
+    assert intersection(r1, Ray(Point(1, 1), Point(-1, -1))) == [Point(1, 1)]
+    assert intersection(r1, Segment(Point(0, 0), Point(2, 2))) == [Segment(Point(1, 1), Point(2, 2))]
+
+    assert r4.intersection(s2) == [s2]
+    assert r4.intersection(Segment(Point(2, 3), Point(3, 4))) == []
+    assert r4.intersection(Segment(Point(-1, -1), Point(0.5, 0.5))) == [Segment(p1, Point(0.5, 0.5))]
+    assert r4.intersection(Ray(p2, p1)) == [s1]
+    assert Ray(p2, p1).intersection(r6) == []
+    assert r4.intersection(r7) == r7.intersection(r4) == [r7]
+    assert Ray3D((0, 0), (3, 0)).intersection(Ray3D((1, 0), (3, 0))) == [Ray3D((1, 0), (3, 0))]
+    assert Ray3D((1, 0), (3, 0)).intersection(Ray3D((0, 0), (3, 0))) == [Ray3D((1, 0), (3, 0))]
+    assert Ray(Point(0, 0), Point(0, 4)).intersection(Ray(Point(0, 1), Point(0, -1))) == \
+           [Segment(Point(0, 0), Point(0, 1))]
+
+    assert Segment3D((0, 0), (3, 0)).intersection(
+        Segment3D((1, 0), (2, 0))) == [Segment3D((1, 0), (2, 0))]
+    assert Segment3D((1, 0), (2, 0)).intersection(
+        Segment3D((0, 0), (3, 0))) == [Segment3D((1, 0), (2, 0))]
+    assert Segment3D((0, 0), (3, 0)).intersection(
+        Segment3D((3, 0), (4, 0))) == [Point3D((3, 0))]
+    assert Segment3D((0, 0), (3, 0)).intersection(
+        Segment3D((2, 0), (5, 0))) == [Segment3D((2, 0), (3, 0))]
+    assert Segment3D((0, 0), (3, 0)).intersection(
+        Segment3D((-2, 0), (1, 0))) == [Segment3D((0, 0), (1, 0))]
+    assert Segment3D((0, 0), (3, 0)).intersection(
+        Segment3D((-2, 0), (0, 0))) == [Point3D(0, 0)]
+    assert s1.intersection(Segment(Point(1, 1), Point(2, 2))) == [Point(1, 1)]
+    assert s1.intersection(Segment(Point(0.5, 0.5), Point(1.5, 1.5))) == [Segment(Point(0.5, 0.5), p2)]
+    assert s1.intersection(Segment(Point(4, 4), Point(5, 5))) == []
+    assert s1.intersection(Segment(Point(-1, -1), p1)) == [p1]
+    assert s1.intersection(Segment(Point(-1, -1), Point(0.5, 0.5))) == [Segment(p1, Point(0.5, 0.5))]
+    assert s1.intersection(Line(Point(1, 0), Point(2, 1))) == []
+    assert s1.intersection(s2) == [s2]
+    assert s2.intersection(s1) == [s2]
+
+    assert asa(120, 8, 52) == \
+           Triangle(
+               Point(0, 0),
+               Point(8, 0),
+               Point(-4 * cos(19 * pi / 90) / sin(2 * pi / 45),
+                     4 * sqrt(3) * cos(19 * pi / 90) / sin(2 * pi / 45)))
+    assert Line((0, 0), (1, 1)).intersection(Ray((1, 0), (1, 2))) == [Point(1, 1)]
+    assert Line((0, 0), (1, 1)).intersection(Segment((1, 0), (1, 2))) == [Point(1, 1)]
+    assert Ray((0, 0), (1, 1)).intersection(Ray((1, 0), (1, 2))) == [Point(1, 1)]
+    assert Ray((0, 0), (1, 1)).intersection(Segment((1, 0), (1, 2))) == [Point(1, 1)]
+    assert Ray((0, 0), (10, 10)).contains(Segment((1, 1), (2, 2))) is True
+    assert Segment((1, 1), (2, 2)) in Line((0, 0), (10, 10))
+    assert s1.intersection(Ray((1, 1), (4, 4))) == [Point(1, 1)]
+
+    # This test is disabled because it hangs after rref changes which simplify
+    # intermediate results and return a different representation from when the
+    # test was written.
+    # # 16628 - this should be fast
+    # p0 = Point2D(Rational(249, 5), Rational(497999, 10000))
+    # p1 = Point2D((-58977084786*sqrt(405639795226) + 2030690077184193 +
+    #     20112207807*sqrt(630547164901) + 99600*sqrt(255775022850776494562626))
+    #     /(2000*sqrt(255775022850776494562626) + 1991998000*sqrt(405639795226)
+    #     + 1991998000*sqrt(630547164901) + 1622561172902000),
+    #     (-498000*sqrt(255775022850776494562626) - 995999*sqrt(630547164901) +
+    #     90004251917891999 +
+    #     496005510002*sqrt(405639795226))/(10000*sqrt(255775022850776494562626)
+    #     + 9959990000*sqrt(405639795226) + 9959990000*sqrt(630547164901) +
+    #     8112805864510000))
+    # p2 = Point2D(Rational(497, 10), Rational(-497, 10))
+    # p3 = Point2D(Rational(-497, 10), Rational(-497, 10))
+    # l = Line(p0, p1)
+    # s = Segment(p2, p3)
+    # n = (-52673223862*sqrt(405639795226) - 15764156209307469 -
+    #     9803028531*sqrt(630547164901) +
+    #     33200*sqrt(255775022850776494562626))
+    # d = sqrt(405639795226) + 315274080450 + 498000*sqrt(
+    #     630547164901) + sqrt(255775022850776494562626)
+    # assert intersection(l, s) == [
+    #     Point2D(n/d*Rational(3, 2000), Rational(-497, 10))]
+
+
+def test_line_intersection():
+    # see also test_issue_11238 in test_matrices.py
+    x0 = tan(pi*Rational(13, 45))
+    x1 = sqrt(3)
+    x2 = x0**2
+    x, y = [8*x0/(x0 + x1), (24*x0 - 8*x1*x2)/(x2 - 3)]
+    assert Line(Point(0, 0), Point(1, -sqrt(3))).contains(Point(x, y)) is True
+
+
+def test_intersection_3d():
+    p1 = Point3D(0, 0, 0)
+    p2 = Point3D(1, 1, 1)
+
+    l1 = Line3D(p1, p2)
+    l2 = Line3D(Point3D(0, 0, 0), Point3D(3, 4, 0))
+
+    r1 = Ray3D(Point3D(1, 1, 1), Point3D(2, 2, 2))
+    r2 = Ray3D(Point3D(0, 0, 0), Point3D(3, 4, 0))
+
+    s1 = Segment3D(Point3D(0, 0, 0), Point3D(3, 4, 0))
+
+    assert intersection(l1, p1) == [p1]
+    assert intersection(l1, Point3D(x1, 1 + x1, 1)) == []
+    assert intersection(l1, l1.parallel_line(p1)) == [Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1))]
+    assert intersection(l2, r2) == [r2]
+    assert intersection(l2, s1) == [s1]
+    assert intersection(r2, l2) == [r2]
+    assert intersection(r1, Ray3D(Point3D(1, 1, 1), Point3D(-1, -1, -1))) == [Point3D(1, 1, 1)]
+    assert intersection(r1, Segment3D(Point3D(0, 0, 0), Point3D(2, 2, 2))) == [
+        Segment3D(Point3D(1, 1, 1), Point3D(2, 2, 2))]
+    assert intersection(Ray3D(Point3D(1, 0, 0), Point3D(-1, 0, 0)), Ray3D(Point3D(0, 1, 0), Point3D(0, -1, 0))) \
+           == [Point3D(0, 0, 0)]
+    assert intersection(r1, Ray3D(Point3D(2, 2, 2), Point3D(0, 0, 0))) == \
+           [Segment3D(Point3D(1, 1, 1), Point3D(2, 2, 2))]
+    assert intersection(s1, r2) == [s1]
+
+    assert Line3D(Point3D(4, 0, 1), Point3D(0, 4, 1)).intersection(Line3D(Point3D(0, 0, 1), Point3D(4, 4, 1))) == \
+           [Point3D(2, 2, 1)]
+    assert Line3D((0, 1, 2), (0, 2, 3)).intersection(Line3D((0, 1, 2), (0, 1, 1))) == [Point3D(0, 1, 2)]
+    assert Line3D((0, 0), (t, t)).intersection(Line3D((0, 1), (t, t))) == \
+           [Point3D(t, t)]
+
+    assert Ray3D(Point3D(0, 0, 0), Point3D(0, 4, 0)).intersection(Ray3D(Point3D(0, 1, 1), Point3D(0, -1, 1))) == []
+
+
+def test_is_parallel():
+    p1 = Point3D(0, 0, 0)
+    p2 = Point3D(1, 1, 1)
+    p3 = Point3D(x1, x1, x1)
+
+    l2 = Line(Point(x1, x1), Point(y1, y1))
+    l2_1 = Line(Point(x1, x1), Point(x1, 1 + x1))
+
+    assert Line.is_parallel(Line(Point(0, 0), Point(1, 1)), l2)
+    assert Line.is_parallel(l2, Line(Point(x1, x1), Point(x1, 1 + x1))) is False
+    assert Line.is_parallel(l2, l2.parallel_line(Point(-x1, x1)))
+    assert Line.is_parallel(l2_1, l2_1.parallel_line(Point(0, 0)))
+    assert Line3D(p1, p2).is_parallel(Line3D(p1, p2))  # same as in 2D
+    assert Line3D(Point3D(4, 0, 1), Point3D(0, 4, 1)).is_parallel(Line3D(Point3D(0, 0, 1), Point3D(4, 4, 1))) is False
+    assert Line3D(p1, p2).parallel_line(p3) == Line3D(Point3D(x1, x1, x1),
+                                                      Point3D(x1 + 1, x1 + 1, x1 + 1))
+    assert Line3D(p1, p2).parallel_line(p3.args) == \
+           Line3D(Point3D(x1, x1, x1), Point3D(x1 + 1, x1 + 1, x1 + 1))
+    assert Line3D(Point3D(4, 0, 1), Point3D(0, 4, 1)).is_parallel(Line3D(Point3D(0, 0, 1), Point3D(4, 4, 1))) is False
+
+
+def test_is_perpendicular():
+    p1 = Point(0, 0)
+    p2 = Point(1, 1)
+
+    l1 = Line(p1, p2)
+    l2 = Line(Point(x1, x1), Point(y1, y1))
+    l1_1 = Line(p1, Point(-x1, x1))
+    # 2D
+    assert Line.is_perpendicular(l1, l1_1)
+    assert Line.is_perpendicular(l1, l2) is False
+    p = l1.random_point()
+    assert l1.perpendicular_segment(p) == p
+    # 3D
+    assert Line3D.is_perpendicular(Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)),
+                                   Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0))) is True
+    assert Line3D.is_perpendicular(Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)),
+                                   Line3D(Point3D(0, 1, 0), Point3D(1, 1, 0))) is False
+    assert Line3D.is_perpendicular(Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1)),
+                                   Line3D(Point3D(x1, x1, x1), Point3D(y1, y1, y1))) is False
+
+
+def test_is_similar():
+    p1 = Point(2000, 2000)
+    p2 = p1.scale(2, 2)
+
+    r1 = Ray3D(Point3D(1, 1, 1), Point3D(1, 0, 0))
+    r2 = Ray(Point(0, 0), Point(0, 1))
+
+    s1 = Segment(Point(0, 0), p1)
+
+    assert s1.is_similar(Segment(p1, p2))
+    assert s1.is_similar(r2) is False
+    assert r1.is_similar(Line3D(Point3D(1, 1, 1), Point3D(1, 0, 0))) is True
+    assert r1.is_similar(Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0))) is False
+
+
+def test_length():
+    s2 = Segment3D(Point3D(x1, x1, x1), Point3D(y1, y1, y1))
+    assert Line(Point(0, 0), Point(1, 1)).length is oo
+    assert s2.length == sqrt(3) * sqrt((x1 - y1) ** 2)
+    assert Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1)).length is oo
+
+
+def test_projection():
+    p1 = Point(0, 0)
+    p2 = Point3D(0, 0, 0)
+    p3 = Point(-x1, x1)
+
+    l1 = Line(p1, Point(1, 1))
+    l2 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0))
+    l3 = Line3D(p2, Point3D(1, 1, 1))
+
+    r1 = Ray(Point(1, 1), Point(2, 2))
+
+    s1 = Segment(Point2D(0, 0), Point2D(0, 1))
+    s2 = Segment(Point2D(1, 0), Point2D(2, 1/2))
+
+    assert Line(Point(x1, x1), Point(y1, y1)).projection(Point(y1, y1)) == Point(y1, y1)
+    assert Line(Point(x1, x1), Point(x1, 1 + x1)).projection(Point(1, 1)) == Point(x1, 1)
+    assert Segment(Point(-2, 2), Point(0, 4)).projection(r1) == Segment(Point(-1, 3), Point(0, 4))
+    assert Segment(Point(0, 4), Point(-2, 2)).projection(r1) == Segment(Point(0, 4), Point(-1, 3))
+    assert s2.projection(s1) == EmptySet
+    assert l1.projection(p3) == p1
+    assert l1.projection(Ray(p1, Point(-1, 5))) == Ray(Point(0, 0), Point(2, 2))
+    assert l1.projection(Ray(p1, Point(-1, 1))) == p1
+    assert r1.projection(Ray(Point(1, 1), Point(-1, -1))) == Point(1, 1)
+    assert r1.projection(Ray(Point(0, 4), Point(-1, -5))) == Segment(Point(1, 1), Point(2, 2))
+    assert r1.projection(Segment(Point(-1, 5), Point(-5, -10))) == Segment(Point(1, 1), Point(2, 2))
+    assert r1.projection(Ray(Point(1, 1), Point(-1, -1))) == Point(1, 1)
+    assert r1.projection(Ray(Point(0, 4), Point(-1, -5))) == Segment(Point(1, 1), Point(2, 2))
+    assert r1.projection(Segment(Point(-1, 5), Point(-5, -10))) == Segment(Point(1, 1), Point(2, 2))
+
+    assert l3.projection(Ray3D(p2, Point3D(-1, 5, 0))) == Ray3D(Point3D(0, 0, 0), Point3D(Rational(4, 3), Rational(4, 3), Rational(4, 3)))
+    assert l3.projection(Ray3D(p2, Point3D(-1, 1, 1))) == Ray3D(Point3D(0, 0, 0), Point3D(Rational(1, 3), Rational(1, 3), Rational(1, 3)))
+    assert l2.projection(Point3D(5, 5, 0)) == Point3D(5, 0)
+    assert l2.projection(Line3D(Point3D(0, 1, 0), Point3D(1, 1, 0))).equals(l2)
+
+
+def test_perpendicular_line():
+    # 3d - requires a particular orthogonal to be selected
+    p1, p2, p3 = Point(0, 0, 0), Point(2, 3, 4), Point(-2, 2, 0)
+    l = Line(p1, p2)
+    p = l.perpendicular_line(p3)
+    assert p.p1 == p3
+    assert p.p2 in l
+    # 2d - does not require special selection
+    p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2)
+    l = Line(p1, p2)
+    p = l.perpendicular_line(p3)
+    assert p.p1 == p3
+    # p is directed from l to p3
+    assert p.direction.unit == (p3 - l.projection(p3)).unit
+
+
+def test_perpendicular_bisector():
+    s1 = Segment(Point(0, 0), Point(1, 1))
+    aline = Line(Point(S.Half, S.Half), Point(Rational(3, 2), Rational(-1, 2)))
+    on_line = Segment(Point(S.Half, S.Half), Point(Rational(3, 2), Rational(-1, 2))).midpoint
+
+    assert s1.perpendicular_bisector().equals(aline)
+    assert s1.perpendicular_bisector(on_line).equals(Segment(s1.midpoint, on_line))
+    assert s1.perpendicular_bisector(on_line + (1, 0)).equals(aline)
+
+
+def test_raises():
+    d, e = symbols('a,b', real=True)
+    s = Segment((d, 0), (e, 0))
+
+    raises(TypeError, lambda: Line((1, 1), 1))
+    raises(ValueError, lambda: Line(Point(0, 0), Point(0, 0)))
+    raises(Undecidable, lambda: Point(2 * d, 0) in s)
+    raises(ValueError, lambda: Ray3D(Point(1.0, 1.0)))
+    raises(ValueError, lambda: Line3D(Point3D(0, 0, 0), Point3D(0, 0, 0)))
+    raises(TypeError, lambda: Line3D((1, 1), 1))
+    raises(ValueError, lambda: Line3D(Point3D(0, 0, 0)))
+    raises(TypeError, lambda: Ray((1, 1), 1))
+    raises(GeometryError, lambda: Line(Point(0, 0), Point(1, 0))
+           .projection(Circle(Point(0, 0), 1)))
+
+
+def test_ray_generation():
+    assert Ray((1, 1), angle=pi / 4) == Ray((1, 1), (2, 2))
+    assert Ray((1, 1), angle=pi / 2) == Ray((1, 1), (1, 2))
+    assert Ray((1, 1), angle=-pi / 2) == Ray((1, 1), (1, 0))
+    assert Ray((1, 1), angle=-3 * pi / 2) == Ray((1, 1), (1, 2))
+    assert Ray((1, 1), angle=5 * pi / 2) == Ray((1, 1), (1, 2))
+    assert Ray((1, 1), angle=5.0 * pi / 2) == Ray((1, 1), (1, 2))
+    assert Ray((1, 1), angle=pi) == Ray((1, 1), (0, 1))
+    assert Ray((1, 1), angle=3.0 * pi) == Ray((1, 1), (0, 1))
+    assert Ray((1, 1), angle=4.0 * pi) == Ray((1, 1), (2, 1))
+    assert Ray((1, 1), angle=0) == Ray((1, 1), (2, 1))
+    assert Ray((1, 1), angle=4.05 * pi) == Ray(Point(1, 1),
+                                               Point(2, -sqrt(5) * sqrt(2 * sqrt(5) + 10) / 4 - sqrt(
+                                                   2 * sqrt(5) + 10) / 4 + 2 + sqrt(5)))
+    assert Ray((1, 1), angle=4.02 * pi) == Ray(Point(1, 1),
+                                               Point(2, 1 + tan(4.02 * pi)))
+    assert Ray((1, 1), angle=5) == Ray((1, 1), (2, 1 + tan(5)))
+
+    assert Ray3D((1, 1, 1), direction_ratio=[4, 4, 4]) == Ray3D(Point3D(1, 1, 1), Point3D(5, 5, 5))
+    assert Ray3D((1, 1, 1), direction_ratio=[1, 2, 3]) == Ray3D(Point3D(1, 1, 1), Point3D(2, 3, 4))
+    assert Ray3D((1, 1, 1), direction_ratio=[1, 1, 1]) == Ray3D(Point3D(1, 1, 1), Point3D(2, 2, 2))
+
+
+def test_issue_7814():
+    circle = Circle(Point(x, 0), y)
+    line = Line(Point(k, z), slope=0)
+    _s = sqrt((y - z)*(y + z))
+    assert line.intersection(circle) == [Point2D(x + _s, z), Point2D(x - _s, z)]
+
+
+def test_issue_2941():
+    def _check():
+        for f, g in cartes(*[(Line, Ray, Segment)] * 2):
+            l1 = f(a, b)
+            l2 = g(c, d)
+            assert l1.intersection(l2) == l2.intersection(l1)
+    # intersect at end point
+    c, d = (-2, -2), (-2, 0)
+    a, b = (0, 0), (1, 1)
+    _check()
+    # midline intersection
+    c, d = (-2, -3), (-2, 0)
+    _check()
+
+
+def test_parameter_value():
+    t = Symbol('t')
+    p1, p2 = Point(0, 1), Point(5, 6)
+    l = Line(p1, p2)
+    assert l.parameter_value((5, 6), t) == {t: 1}
+    raises(ValueError, lambda: l.parameter_value((0, 0), t))
+
+
+def test_bisectors():
+    r1 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0))
+    r2 = Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0))
+    bisections = r1.bisectors(r2)
+    assert bisections == [Line3D(Point3D(0, 0, 0), Point3D(1, 1, 0)),
+        Line3D(Point3D(0, 0, 0), Point3D(1, -1, 0))]
+    ans = [Line3D(Point3D(0, 0, 0), Point3D(1, 0, 1)),
+        Line3D(Point3D(0, 0, 0), Point3D(-1, 0, 1))]
+    l1 = (0, 0, 0), (0, 0, 1)
+    l2 = (0, 0), (1, 0)
+    for a, b in cartes((Line, Segment, Ray), repeat=2):
+        assert a(*l1).bisectors(b(*l2)) == ans
+
+
+def test_issue_8615():
+    a = Line3D(Point3D(6, 5, 0), Point3D(6, -6, 0))
+    b = Line3D(Point3D(6, -1, 19/10), Point3D(6, -1, 0))
+    assert a.intersection(b) == [Point3D(6, -1, 0)]
+
+
+def test_issue_12598():
+    r1 = Ray(Point(0, 1), Point(0.98, 0.79).n(2))
+    r2 = Ray(Point(0, 0), Point(0.71, 0.71).n(2))
+    assert str(r1.intersection(r2)[0]) == 'Point2D(0.82, 0.82)'
+    l1 = Line((0, 0), (1, 1))
+    l2 = Segment((-1, 1), (0, -1)).n(2)
+    assert str(l1.intersection(l2)[0]) == 'Point2D(-0.33, -0.33)'
+    l2 = Segment((-1, 1), (-1/2, 1/2)).n(2)
+    assert not l1.intersection(l2)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_parabola.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_parabola.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a683f26619952d93475aca9ebd3d47cfb3657a6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_parabola.py
@@ -0,0 +1,143 @@
+from sympy.core.numbers import (Rational, oo)
+from sympy.core.singleton import S
+from sympy.core.symbol import symbols
+from sympy.functions.elementary.complexes import sign
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.geometry.ellipse import (Circle, Ellipse)
+from sympy.geometry.line import (Line, Ray2D, Segment2D)
+from sympy.geometry.parabola import Parabola
+from sympy.geometry.point import (Point, Point2D)
+from sympy.testing.pytest import raises
+
+from sympy.abc import x, y
+
+def test_parabola_geom():
+    a, b = symbols('a b')
+    p1 = Point(0, 0)
+    p2 = Point(3, 7)
+    p3 = Point(0, 4)
+    p4 = Point(6, 0)
+    p5 = Point(a, a)
+    d1 = Line(Point(4, 0), Point(4, 9))
+    d2 = Line(Point(7, 6), Point(3, 6))
+    d3 = Line(Point(4, 0), slope=oo)
+    d4 = Line(Point(7, 6), slope=0)
+    d5 = Line(Point(b, a), slope=oo)
+    d6 = Line(Point(a, b), slope=0)
+
+    half = S.Half
+
+    pa1 = Parabola(None, d2)
+    pa2 = Parabola(directrix=d1)
+    pa3 = Parabola(p1, d1)
+    pa4 = Parabola(p2, d2)
+    pa5 = Parabola(p2, d4)
+    pa6 = Parabola(p3, d2)
+    pa7 = Parabola(p2, d1)
+    pa8 = Parabola(p4, d1)
+    pa9 = Parabola(p4, d3)
+    pa10 = Parabola(p5, d5)
+    pa11 = Parabola(p5, d6)
+    d = Line(Point(3, 7), Point(2, 9))
+    pa12 = Parabola(Point(7, 8), d)
+    pa12r = Parabola(Point(7, 8).reflect(d), d)
+
+    raises(ValueError, lambda:
+           Parabola(Point(7, 8, 9), Line(Point(6, 7), Point(7, 7))))
+    raises(ValueError, lambda:
+           Parabola(Point(0, 2), Line(Point(7, 2), Point(6, 2))))
+    raises(ValueError, lambda: Parabola(Point(7, 8), Point(3, 8)))
+
+    # Basic Stuff
+    assert pa1.focus == Point(0, 0)
+    assert pa1.ambient_dimension == S(2)
+    assert pa2 == pa3
+    assert pa4 != pa7
+    assert pa6 != pa7
+    assert pa6.focus == Point2D(0, 4)
+    assert pa6.focal_length == 1
+    assert pa6.p_parameter == -1
+    assert pa6.vertex == Point2D(0, 5)
+    assert pa6.eccentricity == 1
+    assert pa7.focus == Point2D(3, 7)
+    assert pa7.focal_length == half
+    assert pa7.p_parameter == -half
+    assert pa7.vertex == Point2D(7*half, 7)
+    assert pa4.focal_length == half
+    assert pa4.p_parameter == half
+    assert pa4.vertex == Point2D(3, 13*half)
+    assert pa8.focal_length == 1
+    assert pa8.p_parameter == 1
+    assert pa8.vertex == Point2D(5, 0)
+    assert pa4.focal_length == pa5.focal_length
+    assert pa4.p_parameter == pa5.p_parameter
+    assert pa4.vertex == pa5.vertex
+    assert pa4.equation() == pa5.equation()
+    assert pa8.focal_length == pa9.focal_length
+    assert pa8.p_parameter == pa9.p_parameter
+    assert pa8.vertex == pa9.vertex
+    assert pa8.equation() == pa9.equation()
+    assert pa10.focal_length == pa11.focal_length == sqrt((a - b) ** 2) / 2 # if a, b real == abs(a - b)/2
+    assert pa11.vertex == Point(*pa10.vertex[::-1]) == Point(a,
+                            a - sqrt((a - b)**2)*sign(a - b)/2) # change axis x->y, y->x on pa10
+    aos = pa12.axis_of_symmetry
+    assert aos == Line(Point(7, 8), Point(5, 7))
+    assert pa12.directrix == Line(Point(3, 7), Point(2, 9))
+    assert pa12.directrix.angle_between(aos) == S.Pi/2
+    assert pa12.eccentricity == 1
+    assert pa12.equation(x, y) == (x - 7)**2 + (y - 8)**2 - (-2*x - y + 13)**2/5
+    assert pa12.focal_length == 9*sqrt(5)/10
+    assert pa12.focus == Point(7, 8)
+    assert pa12.p_parameter == 9*sqrt(5)/10
+    assert pa12.vertex == Point2D(S(26)/5, S(71)/10)
+    assert pa12r.focal_length == 9*sqrt(5)/10
+    assert pa12r.focus == Point(-S(1)/5, S(22)/5)
+    assert pa12r.p_parameter == -9*sqrt(5)/10
+    assert pa12r.vertex == Point(S(8)/5, S(53)/10)
+
+
+def test_parabola_intersection():
+    l1 = Line(Point(1, -2), Point(-1,-2))
+    l2 = Line(Point(1, 2), Point(-1,2))
+    l3 = Line(Point(1, 0), Point(-1,0))
+
+    p1 = Point(0,0)
+    p2 = Point(0, -2)
+    p3 = Point(120, -12)
+    parabola1 = Parabola(p1, l1)
+
+    # parabola with parabola
+    assert parabola1.intersection(parabola1) == [parabola1]
+    assert parabola1.intersection(Parabola(p1, l2)) == [Point2D(-2, 0), Point2D(2, 0)]
+    assert parabola1.intersection(Parabola(p2, l3)) == [Point2D(0, -1)]
+    assert parabola1.intersection(Parabola(Point(16, 0), l1)) == [Point2D(8, 15)]
+    assert parabola1.intersection(Parabola(Point(0, 16), l1)) == [Point2D(-6, 8), Point2D(6, 8)]
+    assert parabola1.intersection(Parabola(p3, l3)) == []
+    # parabola with point
+    assert parabola1.intersection(p1) == []
+    assert parabola1.intersection(Point2D(0, -1)) == [Point2D(0, -1)]
+    assert parabola1.intersection(Point2D(4, 3)) == [Point2D(4, 3)]
+    # parabola with line
+    assert parabola1.intersection(Line(Point2D(-7, 3), Point(12, 3))) == [Point2D(-4, 3), Point2D(4, 3)]
+    assert parabola1.intersection(Line(Point(-4, -1), Point(4, -1))) == [Point(0, -1)]
+    assert parabola1.intersection(Line(Point(2, 0), Point(0, -2))) == [Point2D(2, 0)]
+    raises(TypeError, lambda: parabola1.intersection(Line(Point(0, 0, 0), Point(1, 1, 1))))
+    # parabola with segment
+    assert parabola1.intersection(Segment2D((-4, -5), (4, 3))) == [Point2D(0, -1), Point2D(4, 3)]
+    assert parabola1.intersection(Segment2D((0, -5), (0, 6))) == [Point2D(0, -1)]
+    assert parabola1.intersection(Segment2D((-12, -65), (14, -68))) == []
+    # parabola with ray
+    assert parabola1.intersection(Ray2D((-4, -5), (4, 3))) == [Point2D(0, -1), Point2D(4, 3)]
+    assert parabola1.intersection(Ray2D((0, 7), (1, 14))) == [Point2D(14 + 2*sqrt(57), 105 + 14*sqrt(57))]
+    assert parabola1.intersection(Ray2D((0, 7), (0, 14))) == []
+    # parabola with ellipse/circle
+    assert parabola1.intersection(Circle(p1, 2)) == [Point2D(-2, 0), Point2D(2, 0)]
+    assert parabola1.intersection(Circle(p2, 1)) == [Point2D(0, -1)]
+    assert parabola1.intersection(Ellipse(p2, 2, 1)) == [Point2D(0, -1)]
+    assert parabola1.intersection(Ellipse(Point(0, 19), 5, 7)) == []
+    assert parabola1.intersection(Ellipse((0, 3), 12, 4)) == [
+           Point2D(0, -1),
+           Point2D(-4*sqrt(17)/3, Rational(59, 9)),
+           Point2D(4*sqrt(17)/3, Rational(59, 9))]
+    # parabola with unsupported type
+    raises(TypeError, lambda: parabola1.intersection(2))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_plane.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_plane.py
new file mode 100644
index 0000000000000000000000000000000000000000..1010fce5c3bc68348eacee13f29c1d7588f17e39
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_plane.py
@@ -0,0 +1,268 @@
+from sympy.core.numbers import (Rational, pi)
+from sympy.core.singleton import S
+from sympy.core.symbol import (Dummy, symbols)
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import (asin, cos, sin)
+from sympy.geometry import Line, Point, Ray, Segment, Point3D, Line3D, Ray3D, Segment3D, Plane, Circle
+from sympy.geometry.util import are_coplanar
+from sympy.testing.pytest import raises
+
+
+def test_plane():
+    x, y, z, u, v = symbols('x y z u v', real=True)
+    p1 = Point3D(0, 0, 0)
+    p2 = Point3D(1, 1, 1)
+    p3 = Point3D(1, 2, 3)
+    pl3 = Plane(p1, p2, p3)
+    pl4 = Plane(p1, normal_vector=(1, 1, 1))
+    pl4b = Plane(p1, p2)
+    pl5 = Plane(p3, normal_vector=(1, 2, 3))
+    pl6 = Plane(Point3D(2, 3, 7), normal_vector=(2, 2, 2))
+    pl7 = Plane(Point3D(1, -5, -6), normal_vector=(1, -2, 1))
+    pl8 = Plane(p1, normal_vector=(0, 0, 1))
+    pl9 = Plane(p1, normal_vector=(0, 12, 0))
+    pl10 = Plane(p1, normal_vector=(-2, 0, 0))
+    pl11 = Plane(p2, normal_vector=(0, 0, 1))
+    l1 = Line3D(Point3D(5, 0, 0), Point3D(1, -1, 1))
+    l2 = Line3D(Point3D(0, -2, 0), Point3D(3, 1, 1))
+    l3 = Line3D(Point3D(0, -1, 0), Point3D(5, -1, 9))
+
+    raises(ValueError, lambda: Plane(p1, p1, p1))
+
+    assert Plane(p1, p2, p3) != Plane(p1, p3, p2)
+    assert Plane(p1, p2, p3).is_coplanar(Plane(p1, p3, p2))
+    assert Plane(p1, p2, p3).is_coplanar(p1)
+    assert Plane(p1, p2, p3).is_coplanar(Circle(p1, 1)) is False
+    assert Plane(p1, normal_vector=(0, 0, 1)).is_coplanar(Circle(p1, 1))
+
+    assert pl3 == Plane(Point3D(0, 0, 0), normal_vector=(1, -2, 1))
+    assert pl3 != pl4
+    assert pl4 == pl4b
+    assert pl5 == Plane(Point3D(1, 2, 3), normal_vector=(1, 2, 3))
+
+    assert pl5.equation(x, y, z) == x + 2*y + 3*z - 14
+    assert pl3.equation(x, y, z) == x - 2*y + z
+
+    assert pl3.p1 == p1
+    assert pl4.p1 == p1
+    assert pl5.p1 == p3
+
+    assert pl4.normal_vector == (1, 1, 1)
+    assert pl5.normal_vector == (1, 2, 3)
+
+    assert p1 in pl3
+    assert p1 in pl4
+    assert p3 in pl5
+
+    assert pl3.projection(Point(0, 0)) == p1
+    p = pl3.projection(Point3D(1, 1, 0))
+    assert p == Point3D(Rational(7, 6), Rational(2, 3), Rational(1, 6))
+    assert p in pl3
+
+    l = pl3.projection_line(Line(Point(0, 0), Point(1, 1)))
+    assert l == Line3D(Point3D(0, 0, 0), Point3D(Rational(7, 6), Rational(2, 3), Rational(1, 6)))
+    assert l in pl3
+    # get a segment that does not intersect the plane which is also
+    # parallel to pl3's normal veector
+    t = Dummy()
+    r = pl3.random_point()
+    a = pl3.perpendicular_line(r).arbitrary_point(t)
+    s = Segment3D(a.subs(t, 1), a.subs(t, 2))
+    assert s.p1 not in pl3 and s.p2 not in pl3
+    assert pl3.projection_line(s).equals(r)
+    assert pl3.projection_line(Segment(Point(1, 0), Point(1, 1))) == \
+               Segment3D(Point3D(Rational(5, 6), Rational(1, 3), Rational(-1, 6)), Point3D(Rational(7, 6), Rational(2, 3), Rational(1, 6)))
+    assert pl6.projection_line(Ray(Point(1, 0), Point(1, 1))) == \
+               Ray3D(Point3D(Rational(14, 3), Rational(11, 3), Rational(11, 3)), Point3D(Rational(13, 3), Rational(13, 3), Rational(10, 3)))
+    assert pl3.perpendicular_line(r.args) == pl3.perpendicular_line(r)
+
+    assert pl3.is_parallel(pl6) is False
+    assert pl4.is_parallel(pl6)
+    assert pl3.is_parallel(Line(p1, p2))
+    assert pl6.is_parallel(l1) is False
+
+    assert pl3.is_perpendicular(pl6)
+    assert pl4.is_perpendicular(pl7)
+    assert pl6.is_perpendicular(pl7)
+    assert pl6.is_perpendicular(pl4) is False
+    assert pl6.is_perpendicular(l1) is False
+    assert pl6.is_perpendicular(Line((0, 0, 0), (1, 1, 1)))
+    assert pl6.is_perpendicular((1, 1)) is False
+
+    assert pl6.distance(pl6.arbitrary_point(u, v)) == 0
+    assert pl7.distance(pl7.arbitrary_point(u, v)) == 0
+    assert pl6.distance(pl6.arbitrary_point(t)) == 0
+    assert pl7.distance(pl7.arbitrary_point(t)) == 0
+    assert pl6.p1.distance(pl6.arbitrary_point(t)).simplify() == 1
+    assert pl7.p1.distance(pl7.arbitrary_point(t)).simplify() == 1
+    assert pl3.arbitrary_point(t) == Point3D(-sqrt(30)*sin(t)/30 + \
+        2*sqrt(5)*cos(t)/5, sqrt(30)*sin(t)/15 + sqrt(5)*cos(t)/5, sqrt(30)*sin(t)/6)
+    assert pl3.arbitrary_point(u, v) == Point3D(2*u - v, u + 2*v, 5*v)
+
+    assert pl7.distance(Point3D(1, 3, 5)) == 5*sqrt(6)/6
+    assert pl6.distance(Point3D(0, 0, 0)) == 4*sqrt(3)
+    assert pl6.distance(pl6.p1) == 0
+    assert pl7.distance(pl6) == 0
+    assert pl7.distance(l1) == 0
+    assert pl6.distance(Segment3D(Point3D(2, 3, 1), Point3D(1, 3, 4))) == \
+        pl6.distance(Point3D(1, 3, 4)) == 4*sqrt(3)/3
+    assert pl6.distance(Segment3D(Point3D(1, 3, 4), Point3D(0, 3, 7))) == \
+        pl6.distance(Point3D(0, 3, 7)) == 2*sqrt(3)/3
+    assert pl6.distance(Segment3D(Point3D(0, 3, 7), Point3D(-1, 3, 10))) == 0
+    assert pl6.distance(Segment3D(Point3D(-1, 3, 10), Point3D(-2, 3, 13))) == 0
+    assert pl6.distance(Segment3D(Point3D(-2, 3, 13), Point3D(-3, 3, 16))) == \
+        pl6.distance(Point3D(-2, 3, 13)) == 2*sqrt(3)/3
+    assert pl6.distance(Plane(Point3D(5, 5, 5), normal_vector=(8, 8, 8))) == sqrt(3)
+    assert pl6.distance(Ray3D(Point3D(1, 3, 4), direction_ratio=[1, 0, -3])) == 4*sqrt(3)/3
+    assert pl6.distance(Ray3D(Point3D(2, 3, 1), direction_ratio=[-1, 0, 3])) == 0
+
+
+    assert pl6.angle_between(pl3) == pi/2
+    assert pl6.angle_between(pl6) == 0
+    assert pl6.angle_between(pl4) == 0
+    assert pl7.angle_between(Line3D(Point3D(2, 3, 5), Point3D(2, 4, 6))) == \
+        -asin(sqrt(3)/6)
+    assert pl6.angle_between(Ray3D(Point3D(2, 4, 1), Point3D(6, 5, 3))) == \
+        asin(sqrt(7)/3)
+    assert pl7.angle_between(Segment3D(Point3D(5, 6, 1), Point3D(1, 2, 4))) == \
+        asin(7*sqrt(246)/246)
+
+    assert are_coplanar(l1, l2, l3) is False
+    assert are_coplanar(l1) is False
+    assert are_coplanar(Point3D(2, 7, 2), Point3D(0, 0, 2),
+        Point3D(1, 1, 2), Point3D(1, 2, 2))
+    assert are_coplanar(Plane(p1, p2, p3), Plane(p1, p3, p2))
+    assert Plane.are_concurrent(pl3, pl4, pl5) is False
+    assert Plane.are_concurrent(pl6) is False
+    raises(ValueError, lambda: Plane.are_concurrent(Point3D(0, 0, 0)))
+    raises(ValueError, lambda: Plane((1, 2, 3), normal_vector=(0, 0, 0)))
+
+    assert pl3.parallel_plane(Point3D(1, 2, 5)) == Plane(Point3D(1, 2, 5), \
+                                                      normal_vector=(1, -2, 1))
+
+    # perpendicular_plane
+    p = Plane((0, 0, 0), (1, 0, 0))
+    # default
+    assert p.perpendicular_plane() == Plane(Point3D(0, 0, 0), (0, 1, 0))
+    # 1 pt
+    assert p.perpendicular_plane(Point3D(1, 0, 1)) == \
+        Plane(Point3D(1, 0, 1), (0, 1, 0))
+    # pts as tuples
+    assert p.perpendicular_plane((1, 0, 1), (1, 1, 1)) == \
+        Plane(Point3D(1, 0, 1), (0, 0, -1))
+    # more than two planes
+    raises(ValueError, lambda: p.perpendicular_plane((1, 0, 1), (1, 1, 1), (1, 1, 0)))
+
+    a, b = Point3D(0, 0, 0), Point3D(0, 1, 0)
+    Z = (0, 0, 1)
+    p = Plane(a, normal_vector=Z)
+    # case 4
+    assert p.perpendicular_plane(a, b) == Plane(a, (1, 0, 0))
+    n = Point3D(*Z)
+    # case 1
+    assert p.perpendicular_plane(a, n) == Plane(a, (-1, 0, 0))
+    # case 2
+    assert Plane(a, normal_vector=b.args).perpendicular_plane(a, a + b) == \
+        Plane(Point3D(0, 0, 0), (1, 0, 0))
+    # case 1&3
+    assert Plane(b, normal_vector=Z).perpendicular_plane(b, b + n) == \
+        Plane(Point3D(0, 1, 0), (-1, 0, 0))
+    # case 2&3
+    assert Plane(b, normal_vector=b.args).perpendicular_plane(n, n + b) == \
+        Plane(Point3D(0, 0, 1), (1, 0, 0))
+
+    p = Plane(a, normal_vector=(0, 0, 1))
+    assert p.perpendicular_plane() == Plane(a, normal_vector=(1, 0, 0))
+
+    assert pl6.intersection(pl6) == [pl6]
+    assert pl4.intersection(pl4.p1) == [pl4.p1]
+    assert pl3.intersection(pl6) == [
+        Line3D(Point3D(8, 4, 0), Point3D(2, 4, 6))]
+    assert pl3.intersection(Line3D(Point3D(1,2,4), Point3D(4,4,2))) == [
+        Point3D(2, Rational(8, 3), Rational(10, 3))]
+    assert pl3.intersection(Plane(Point3D(6, 0, 0), normal_vector=(2, -5, 3))
+        ) == [Line3D(Point3D(-24, -12, 0), Point3D(-25, -13, -1))]
+    assert pl6.intersection(Ray3D(Point3D(2, 3, 1), Point3D(1, 3, 4))) == [
+        Point3D(-1, 3, 10)]
+    assert pl6.intersection(Segment3D(Point3D(2, 3, 1), Point3D(1, 3, 4))) == []
+    assert pl7.intersection(Line(Point(2, 3), Point(4, 2))) == [
+        Point3D(Rational(13, 2), Rational(3, 4), 0)]
+    r = Ray(Point(2, 3), Point(4, 2))
+    assert Plane((1,2,0), normal_vector=(0,0,1)).intersection(r) == [
+        Ray3D(Point(2, 3), Point(4, 2))]
+    assert pl9.intersection(pl8) == [Line3D(Point3D(0, 0, 0), Point3D(12, 0, 0))]
+    assert pl10.intersection(pl11) == [Line3D(Point3D(0, 0, 1), Point3D(0, 2, 1))]
+    assert pl4.intersection(pl8) == [Line3D(Point3D(0, 0, 0), Point3D(1, -1, 0))]
+    assert pl11.intersection(pl8) == []
+    assert pl9.intersection(pl11) == [Line3D(Point3D(0, 0, 1), Point3D(12, 0, 1))]
+    assert pl9.intersection(pl4) == [Line3D(Point3D(0, 0, 0), Point3D(12, 0, -12))]
+    assert pl3.random_point() in pl3
+    assert pl3.random_point(seed=1) in pl3
+
+    # test geometrical entity using equals
+    assert pl4.intersection(pl4.p1)[0].equals(pl4.p1)
+    assert pl3.intersection(pl6)[0].equals(Line3D(Point3D(8, 4, 0), Point3D(2, 4, 6)))
+    pl8 = Plane((1, 2, 0), normal_vector=(0, 0, 1))
+    assert pl8.intersection(Line3D(p1, (1, 12, 0)))[0].equals(Line((0, 0, 0), (0.1, 1.2, 0)))
+    assert pl8.intersection(Ray3D(p1, (1, 12, 0)))[0].equals(Ray((0, 0, 0), (1, 12, 0)))
+    assert pl8.intersection(Segment3D(p1, (21, 1, 0)))[0].equals(Segment3D(p1, (21, 1, 0)))
+    assert pl8.intersection(Plane(p1, normal_vector=(0, 0, 112)))[0].equals(pl8)
+    assert pl8.intersection(Plane(p1, normal_vector=(0, 12, 0)))[0].equals(
+        Line3D(p1, direction_ratio=(112 * pi, 0, 0)))
+    assert pl8.intersection(Plane(p1, normal_vector=(11, 0, 1)))[0].equals(
+        Line3D(p1, direction_ratio=(0, -11, 0)))
+    assert pl8.intersection(Plane(p1, normal_vector=(1, 0, 11)))[0].equals(
+        Line3D(p1, direction_ratio=(0, 11, 0)))
+    assert pl8.intersection(Plane(p1, normal_vector=(-1, -1, -11)))[0].equals(
+        Line3D(p1, direction_ratio=(1, -1, 0)))
+    assert pl3.random_point() in pl3
+    assert len(pl8.intersection(Ray3D(Point3D(0, 2, 3), Point3D(1, 0, 3)))) == 0
+    # check if two plane are equals
+    assert pl6.intersection(pl6)[0].equals(pl6)
+    assert pl8.equals(Plane(p1, normal_vector=(0, 12, 0))) is False
+    assert pl8.equals(pl8)
+    assert pl8.equals(Plane(p1, normal_vector=(0, 0, -12)))
+    assert pl8.equals(Plane(p1, normal_vector=(0, 0, -12*sqrt(3))))
+    assert pl8.equals(p1) is False
+
+    # issue 8570
+    l2 = Line3D(Point3D(Rational(50000004459633, 5000000000000),
+                        Rational(-891926590718643, 1000000000000000),
+                        Rational(231800966893633, 100000000000000)),
+                Point3D(Rational(50000004459633, 50000000000000),
+                        Rational(-222981647679771, 250000000000000),
+                        Rational(231800966893633, 100000000000000)))
+
+    p2 = Plane(Point3D(Rational(402775636372767, 100000000000000),
+                       Rational(-97224357654973, 100000000000000),
+                       Rational(216793600814789, 100000000000000)),
+               (-S('9.00000087501922'), -S('4.81170658872543e-13'),
+                S('0.0')))
+
+    assert str([i.n(2) for i in p2.intersection(l2)]) == \
+           '[Point3D(4.0, -0.89, 2.3)]'
+
+
+def test_dimension_normalization():
+    A = Plane(Point3D(1, 1, 2), normal_vector=(1, 1, 1))
+    b = Point(1, 1)
+    assert A.projection(b) == Point(Rational(5, 3), Rational(5, 3), Rational(2, 3))
+
+    a, b = Point(0, 0), Point3D(0, 1)
+    Z = (0, 0, 1)
+    p = Plane(a, normal_vector=Z)
+    assert p.perpendicular_plane(a, b) == Plane(Point3D(0, 0, 0), (1, 0, 0))
+    assert Plane((1, 2, 1), (2, 1, 0), (3, 1, 2)
+        ).intersection((2, 1)) == [Point(2, 1, 0)]
+
+
+def test_parameter_value():
+    t, u, v = symbols("t, u v")
+    p1, p2, p3 = Point(0, 0, 0), Point(0, 0, 1), Point(0, 1, 0)
+    p = Plane(p1, p2, p3)
+    assert p.parameter_value((0, -3, 2), t) == {t: asin(2*sqrt(13)/13)}
+    assert p.parameter_value((0, -3, 2), u, v) == {u: 3, v: 2}
+    assert p.parameter_value(p1, t) == p1
+    raises(ValueError, lambda: p.parameter_value((1, 0, 0), t))
+    raises(ValueError, lambda: p.parameter_value(Line(Point(0, 0), Point(1, 1)), t))
+    raises(ValueError, lambda: p.parameter_value((0, -3, 2), t, 1))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_point.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_point.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f2b2768eb3fba2009f702351de1aac3ed6e71d4
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_point.py
@@ -0,0 +1,481 @@
+from sympy.core.basic import Basic
+from sympy.core.numbers import (I, Rational, pi)
+from sympy.core.parameters import evaluate
+from sympy.core.singleton import S
+from sympy.core.symbol import Symbol
+from sympy.core.sympify import sympify
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.geometry import Line, Point, Point2D, Point3D, Line3D, Plane
+from sympy.geometry.entity import rotate, scale, translate, GeometryEntity
+from sympy.matrices import Matrix
+from sympy.utilities.iterables import subsets, permutations, cartes
+from sympy.utilities.misc import Undecidable
+from sympy.testing.pytest import raises, warns
+
+
+def test_point():
+    x = Symbol('x', real=True)
+    y = Symbol('y', real=True)
+    x1 = Symbol('x1', real=True)
+    x2 = Symbol('x2', real=True)
+    y1 = Symbol('y1', real=True)
+    y2 = Symbol('y2', real=True)
+    half = S.Half
+    p1 = Point(x1, x2)
+    p2 = Point(y1, y2)
+    p3 = Point(0, 0)
+    p4 = Point(1, 1)
+    p5 = Point(0, 1)
+    line = Line(Point(1, 0), slope=1)
+
+    assert p1 in p1
+    assert p1 not in p2
+    assert p2.y == y2
+    assert (p3 + p4) == p4
+    assert (p2 - p1) == Point(y1 - x1, y2 - x2)
+    assert -p2 == Point(-y1, -y2)
+    raises(TypeError, lambda: Point(1))
+    raises(ValueError, lambda: Point([1]))
+    raises(ValueError, lambda: Point(3, I))
+    raises(ValueError, lambda: Point(2*I, I))
+    raises(ValueError, lambda: Point(3 + I, I))
+
+    assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3))
+    assert Point.midpoint(p3, p4) == Point(half, half)
+    assert Point.midpoint(p1, p4) == Point(half + half*x1, half + half*x2)
+    assert Point.midpoint(p2, p2) == p2
+    assert p2.midpoint(p2) == p2
+    assert p1.origin == Point(0, 0)
+
+    assert Point.distance(p3, p4) == sqrt(2)
+    assert Point.distance(p1, p1) == 0
+    assert Point.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2)
+    raises(TypeError, lambda: Point.distance(p1, 0))
+    raises(TypeError, lambda: Point.distance(p1, GeometryEntity()))
+
+    # distance should be symmetric
+    assert p1.distance(line) == line.distance(p1)
+    assert p4.distance(line) == line.distance(p4)
+
+    assert Point.taxicab_distance(p4, p3) == 2
+
+    assert Point.canberra_distance(p4, p5) == 1
+    raises(ValueError, lambda: Point.canberra_distance(p3, p3))
+
+    p1_1 = Point(x1, x1)
+    p1_2 = Point(y2, y2)
+    p1_3 = Point(x1 + 1, x1)
+    assert Point.is_collinear(p3)
+
+    with warns(UserWarning, test_stacklevel=False):
+        assert Point.is_collinear(p3, Point(p3, dim=4))
+    assert p3.is_collinear()
+    assert Point.is_collinear(p3, p4)
+    assert Point.is_collinear(p3, p4, p1_1, p1_2)
+    assert Point.is_collinear(p3, p4, p1_1, p1_3) is False
+    assert Point.is_collinear(p3, p3, p4, p5) is False
+
+    raises(TypeError, lambda: Point.is_collinear(line))
+    raises(TypeError, lambda: p1_1.is_collinear(line))
+
+    assert p3.intersection(Point(0, 0)) == [p3]
+    assert p3.intersection(p4) == []
+    assert p3.intersection(line) == []
+    with warns(UserWarning, test_stacklevel=False):
+        assert Point.intersection(Point(0, 0, 0), Point(0, 0)) == [Point(0, 0, 0)]
+
+    x_pos = Symbol('x', positive=True)
+    p2_1 = Point(x_pos, 0)
+    p2_2 = Point(0, x_pos)
+    p2_3 = Point(-x_pos, 0)
+    p2_4 = Point(0, -x_pos)
+    p2_5 = Point(x_pos, 5)
+    assert Point.is_concyclic(p2_1)
+    assert Point.is_concyclic(p2_1, p2_2)
+    assert Point.is_concyclic(p2_1, p2_2, p2_3, p2_4)
+    for pts in permutations((p2_1, p2_2, p2_3, p2_5)):
+        assert Point.is_concyclic(*pts) is False
+    assert Point.is_concyclic(p4, p4 * 2, p4 * 3) is False
+    assert Point(0, 0).is_concyclic((1, 1), (2, 2), (2, 1)) is False
+    assert Point.is_concyclic(Point(0, 0, 0, 0), Point(1, 0, 0, 0), Point(1, 1, 0, 0), Point(1, 1, 1, 0)) is False
+
+    assert p1.is_scalar_multiple(p1)
+    assert p1.is_scalar_multiple(2*p1)
+    assert not p1.is_scalar_multiple(p2)
+    assert Point.is_scalar_multiple(Point(1, 1), (-1, -1))
+    assert Point.is_scalar_multiple(Point(0, 0), (0, -1))
+    # test when is_scalar_multiple can't be determined
+    raises(Undecidable, lambda: Point.is_scalar_multiple(Point(sympify("x1%y1"), sympify("x2%y2")), Point(0, 1)))
+
+    assert Point(0, 1).orthogonal_direction == Point(1, 0)
+    assert Point(1, 0).orthogonal_direction == Point(0, 1)
+
+    assert p1.is_zero is None
+    assert p3.is_zero
+    assert p4.is_zero is False
+    assert p1.is_nonzero is None
+    assert p3.is_nonzero is False
+    assert p4.is_nonzero
+
+    assert p4.scale(2, 3) == Point(2, 3)
+    assert p3.scale(2, 3) == p3
+
+    assert p4.rotate(pi, Point(0.5, 0.5)) == p3
+    assert p1.__radd__(p2) == p1.midpoint(p2).scale(2, 2)
+    assert (-p3).__rsub__(p4) == p3.midpoint(p4).scale(2, 2)
+
+    assert p4 * 5 == Point(5, 5)
+    assert p4 / 5 == Point(0.2, 0.2)
+    assert 5 * p4 == Point(5, 5)
+
+    raises(ValueError, lambda: Point(0, 0) + 10)
+
+    # Point differences should be simplified
+    assert Point(x*(x - 1), y) - Point(x**2 - x, y + 1) == Point(0, -1)
+
+    a, b = S.Half, Rational(1, 3)
+    assert Point(a, b).evalf(2) == \
+        Point(a.n(2), b.n(2), evaluate=False)
+    raises(ValueError, lambda: Point(1, 2) + 1)
+
+    # test project
+    assert Point.project((0, 1), (1, 0)) == Point(0, 0)
+    assert Point.project((1, 1), (1, 0)) == Point(1, 0)
+    raises(ValueError, lambda: Point.project(p1, Point(0, 0)))
+
+    # test transformations
+    p = Point(1, 0)
+    assert p.rotate(pi/2) == Point(0, 1)
+    assert p.rotate(pi/2, p) == p
+    p = Point(1, 1)
+    assert p.scale(2, 3) == Point(2, 3)
+    assert p.translate(1, 2) == Point(2, 3)
+    assert p.translate(1) == Point(2, 1)
+    assert p.translate(y=1) == Point(1, 2)
+    assert p.translate(*p.args) == Point(2, 2)
+
+    # Check invalid input for transform
+    raises(ValueError, lambda: p3.transform(p3))
+    raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]])))
+
+    # test __contains__
+    assert 0 in Point(0, 0, 0, 0)
+    assert 1 not in Point(0, 0, 0, 0)
+
+    # test affine_rank
+    assert Point.affine_rank() == -1
+
+
+def test_point3D():
+    x = Symbol('x', real=True)
+    y = Symbol('y', real=True)
+    x1 = Symbol('x1', real=True)
+    x2 = Symbol('x2', real=True)
+    x3 = Symbol('x3', real=True)
+    y1 = Symbol('y1', real=True)
+    y2 = Symbol('y2', real=True)
+    y3 = Symbol('y3', real=True)
+    half = S.Half
+    p1 = Point3D(x1, x2, x3)
+    p2 = Point3D(y1, y2, y3)
+    p3 = Point3D(0, 0, 0)
+    p4 = Point3D(1, 1, 1)
+    p5 = Point3D(0, 1, 2)
+
+    assert p1 in p1
+    assert p1 not in p2
+    assert p2.y == y2
+    assert (p3 + p4) == p4
+    assert (p2 - p1) == Point3D(y1 - x1, y2 - x2, y3 - x3)
+    assert -p2 == Point3D(-y1, -y2, -y3)
+
+    assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3))
+    assert Point3D.midpoint(p3, p4) == Point3D(half, half, half)
+    assert Point3D.midpoint(p1, p4) == Point3D(half + half*x1, half + half*x2,
+                                         half + half*x3)
+    assert Point3D.midpoint(p2, p2) == p2
+    assert p2.midpoint(p2) == p2
+
+    assert Point3D.distance(p3, p4) == sqrt(3)
+    assert Point3D.distance(p1, p1) == 0
+    assert Point3D.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2 + p2.z**2)
+
+    p1_1 = Point3D(x1, x1, x1)
+    p1_2 = Point3D(y2, y2, y2)
+    p1_3 = Point3D(x1 + 1, x1, x1)
+    Point3D.are_collinear(p3)
+    assert Point3D.are_collinear(p3, p4)
+    assert Point3D.are_collinear(p3, p4, p1_1, p1_2)
+    assert Point3D.are_collinear(p3, p4, p1_1, p1_3) is False
+    assert Point3D.are_collinear(p3, p3, p4, p5) is False
+
+    assert p3.intersection(Point3D(0, 0, 0)) == [p3]
+    assert p3.intersection(p4) == []
+
+
+    assert p4 * 5 == Point3D(5, 5, 5)
+    assert p4 / 5 == Point3D(0.2, 0.2, 0.2)
+    assert 5 * p4 == Point3D(5, 5, 5)
+
+    raises(ValueError, lambda: Point3D(0, 0, 0) + 10)
+
+    # Test coordinate properties
+    assert p1.coordinates == (x1, x2, x3)
+    assert p2.coordinates == (y1, y2, y3)
+    assert p3.coordinates == (0, 0, 0)
+    assert p4.coordinates == (1, 1, 1)
+    assert p5.coordinates == (0, 1, 2)
+    assert p5.x == 0
+    assert p5.y == 1
+    assert p5.z == 2
+
+    # Point differences should be simplified
+    assert Point3D(x*(x - 1), y, 2) - Point3D(x**2 - x, y + 1, 1) == \
+        Point3D(0, -1, 1)
+
+    a, b, c = S.Half, Rational(1, 3), Rational(1, 4)
+    assert Point3D(a, b, c).evalf(2) == \
+        Point(a.n(2), b.n(2), c.n(2), evaluate=False)
+    raises(ValueError, lambda: Point3D(1, 2, 3) + 1)
+
+    # test transformations
+    p = Point3D(1, 1, 1)
+    assert p.scale(2, 3) == Point3D(2, 3, 1)
+    assert p.translate(1, 2) == Point3D(2, 3, 1)
+    assert p.translate(1) == Point3D(2, 1, 1)
+    assert p.translate(z=1) == Point3D(1, 1, 2)
+    assert p.translate(*p.args) == Point3D(2, 2, 2)
+
+    # Test __new__
+    assert Point3D(0.1, 0.2, evaluate=False, on_morph='ignore').args[0].is_Float
+
+    # Test length property returns correctly
+    assert p.length == 0
+    assert p1_1.length == 0
+    assert p1_2.length == 0
+
+    # Test are_colinear type error
+    raises(TypeError, lambda: Point3D.are_collinear(p, x))
+
+    # Test are_coplanar
+    assert Point.are_coplanar()
+    assert Point.are_coplanar((1, 2, 0), (1, 2, 0), (1, 3, 0))
+    assert Point.are_coplanar((1, 2, 0), (1, 2, 3))
+    with warns(UserWarning, test_stacklevel=False):
+        raises(ValueError, lambda: Point2D.are_coplanar((1, 2), (1, 2, 3)))
+    assert Point3D.are_coplanar((1, 2, 0), (1, 2, 3))
+    assert Point.are_coplanar((0, 0, 0), (1, 1, 0), (1, 1, 1), (1, 2, 1)) is False
+    planar2 = Point3D(1, -1, 1)
+    planar3 = Point3D(-1, 1, 1)
+    assert Point3D.are_coplanar(p, planar2, planar3) == True
+    assert Point3D.are_coplanar(p, planar2, planar3, p3) == False
+    assert Point.are_coplanar(p, planar2)
+    planar2 = Point3D(1, 1, 2)
+    planar3 = Point3D(1, 1, 3)
+    assert Point3D.are_coplanar(p, planar2, planar3)  # line, not plane
+    plane = Plane((1, 2, 1), (2, 1, 0), (3, 1, 2))
+    assert Point.are_coplanar(*[plane.projection(((-1)**i, i)) for i in range(4)])
+
+    # all 2D points are coplanar
+    assert Point.are_coplanar(Point(x, y), Point(x, x + y), Point(y, x + 2)) is True
+
+    # Test Intersection
+    assert planar2.intersection(Line3D(p, planar3)) == [Point3D(1, 1, 2)]
+
+    # Test Scale
+    assert planar2.scale(1, 1, 1) == planar2
+    assert planar2.scale(2, 2, 2, planar3) == Point3D(1, 1, 1)
+    assert planar2.scale(1, 1, 1, p3) == planar2
+
+    # Test Transform
+    identity = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
+    assert p.transform(identity) == p
+    trans = Matrix([[1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1], [0, 0, 0, 1]])
+    assert p.transform(trans) == Point3D(2, 2, 2)
+    raises(ValueError, lambda: p.transform(p))
+    raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]])))
+
+    # Test Equals
+    assert p.equals(x1) == False
+
+    # Test __sub__
+    p_4d = Point(0, 0, 0, 1)
+    with warns(UserWarning, test_stacklevel=False):
+        assert p - p_4d == Point(1, 1, 1, -1)
+    p_4d3d = Point(0, 0, 1, 0)
+    with warns(UserWarning, test_stacklevel=False):
+        assert p - p_4d3d == Point(1, 1, 0, 0)
+
+
+def test_Point2D():
+
+    # Test Distance
+    p1 = Point2D(1, 5)
+    p2 = Point2D(4, 2.5)
+    p3 = (6, 3)
+    assert p1.distance(p2) == sqrt(61)/2
+    assert p2.distance(p3) == sqrt(17)/2
+
+    # Test coordinates
+    assert p1.x == 1
+    assert p1.y == 5
+    assert p2.x == 4
+    assert p2.y == S(5)/2
+    assert p1.coordinates == (1, 5)
+    assert p2.coordinates == (4, S(5)/2)
+
+    # test bounds
+    assert p1.bounds == (1, 5, 1, 5)
+
+def test_issue_9214():
+    p1 = Point3D(4, -2, 6)
+    p2 = Point3D(1, 2, 3)
+    p3 = Point3D(7, 2, 3)
+
+    assert Point3D.are_collinear(p1, p2, p3) is False
+
+
+def test_issue_11617():
+    p1 = Point3D(1,0,2)
+    p2 = Point2D(2,0)
+
+    with warns(UserWarning, test_stacklevel=False):
+        assert p1.distance(p2) == sqrt(5)
+
+
+def test_transform():
+    p = Point(1, 1)
+    assert p.transform(rotate(pi/2)) == Point(-1, 1)
+    assert p.transform(scale(3, 2)) == Point(3, 2)
+    assert p.transform(translate(1, 2)) == Point(2, 3)
+    assert Point(1, 1).scale(2, 3, (4, 5)) == \
+        Point(-2, -7)
+    assert Point(1, 1).translate(4, 5) == \
+        Point(5, 6)
+
+
+def test_concyclic_doctest_bug():
+    p1, p2 = Point(-1, 0), Point(1, 0)
+    p3, p4 = Point(0, 1), Point(-1, 2)
+    assert Point.is_concyclic(p1, p2, p3)
+    assert not Point.is_concyclic(p1, p2, p3, p4)
+
+
+def test_arguments():
+    """Functions accepting `Point` objects in `geometry`
+    should also accept tuples and lists and
+    automatically convert them to points."""
+
+    singles2d = ((1,2), [1,2], Point(1,2))
+    singles2d2 = ((1,3), [1,3], Point(1,3))
+    doubles2d = cartes(singles2d, singles2d2)
+    p2d = Point2D(1,2)
+    singles3d = ((1,2,3), [1,2,3], Point(1,2,3))
+    doubles3d = subsets(singles3d, 2)
+    p3d = Point3D(1,2,3)
+    singles4d = ((1,2,3,4), [1,2,3,4], Point(1,2,3,4))
+    doubles4d = subsets(singles4d, 2)
+    p4d = Point(1,2,3,4)
+
+    # test 2D
+    test_single = ['distance', 'is_scalar_multiple', 'taxicab_distance', 'midpoint', 'intersection', 'dot', 'equals', '__add__', '__sub__']
+    test_double = ['is_concyclic', 'is_collinear']
+    for p in singles2d:
+        Point2D(p)
+    for func in test_single:
+        for p in singles2d:
+            getattr(p2d, func)(p)
+    for func in test_double:
+        for p in doubles2d:
+            getattr(p2d, func)(*p)
+
+    # test 3D
+    test_double = ['is_collinear']
+    for p in singles3d:
+        Point3D(p)
+    for func in test_single:
+        for p in singles3d:
+            getattr(p3d, func)(p)
+    for func in test_double:
+        for p in doubles3d:
+            getattr(p3d, func)(*p)
+
+    # test 4D
+    test_double = ['is_collinear']
+    for p in singles4d:
+        Point(p)
+    for func in test_single:
+        for p in singles4d:
+            getattr(p4d, func)(p)
+    for func in test_double:
+        for p in doubles4d:
+            getattr(p4d, func)(*p)
+
+    # test evaluate=False for ops
+    x = Symbol('x')
+    a = Point(0, 1)
+    assert a + (0.1, x) == Point(0.1, 1 + x, evaluate=False)
+    a = Point(0, 1)
+    assert a/10.0 == Point(0, 0.1, evaluate=False)
+    a = Point(0, 1)
+    assert a*10.0 == Point(0, 10.0, evaluate=False)
+
+    # test evaluate=False when changing dimensions
+    u = Point(.1, .2, evaluate=False)
+    u4 = Point(u, dim=4, on_morph='ignore')
+    assert u4.args == (.1, .2, 0, 0)
+    assert all(i.is_Float for i in u4.args[:2])
+    # and even when *not* changing dimensions
+    assert all(i.is_Float for i in Point(u).args)
+
+    # never raise error if creating an origin
+    assert Point(dim=3, on_morph='error')
+
+    # raise error with unmatched dimension
+    raises(ValueError, lambda: Point(1, 1, dim=3, on_morph='error'))
+    # test unknown on_morph
+    raises(ValueError, lambda: Point(1, 1, dim=3, on_morph='unknown'))
+    # test invalid expressions
+    raises(TypeError, lambda: Point(Basic(), Basic()))
+
+def test_unit():
+    assert Point(1, 1).unit == Point(sqrt(2)/2, sqrt(2)/2)
+
+
+def test_dot():
+    raises(TypeError, lambda: Point(1, 2).dot(Line((0, 0), (1, 1))))
+
+
+def test__normalize_dimension():
+    assert Point._normalize_dimension(Point(1, 2), Point(3, 4)) == [
+        Point(1, 2), Point(3, 4)]
+    assert Point._normalize_dimension(
+        Point(1, 2), Point(3, 4, 0), on_morph='ignore') == [
+        Point(1, 2, 0), Point(3, 4, 0)]
+
+
+def test_issue_22684():
+    # Used to give an error
+    with evaluate(False):
+        Point(1, 2)
+
+
+def test_direction_cosine():
+    p1 = Point3D(0, 0, 0)
+    p2 = Point3D(1, 1, 1)
+
+    assert p1.direction_cosine(Point3D(1, 0, 0)) == [1, 0, 0]
+    assert p1.direction_cosine(Point3D(0, 1, 0)) == [0, 1, 0]
+    assert p1.direction_cosine(Point3D(0, 0, pi)) == [0, 0, 1]
+
+    assert p1.direction_cosine(Point3D(5, 0, 0)) == [1, 0, 0]
+    assert p1.direction_cosine(Point3D(0, sqrt(3), 0)) == [0, 1, 0]
+    assert p1.direction_cosine(Point3D(0, 0, 5)) == [0, 0, 1]
+
+    assert p1.direction_cosine(Point3D(2.4, 2.4, 0)) == [sqrt(2)/2, sqrt(2)/2, 0]
+    assert p1.direction_cosine(Point3D(1, 1, 1)) == [sqrt(3) / 3, sqrt(3) / 3, sqrt(3) / 3]
+    assert p1.direction_cosine(Point3D(-12, 0 -15)) == [-4*sqrt(41)/41, -5*sqrt(41)/41, 0]
+
+    assert p2.direction_cosine(Point3D(0, 0, 0)) == [-sqrt(3) / 3, -sqrt(3) / 3, -sqrt(3) / 3]
+    assert p2.direction_cosine(Point3D(1, 1, 12)) == [0, 0, 1]
+    assert p2.direction_cosine(Point3D(12, 1, 12)) == [sqrt(2) / 2, 0, sqrt(2) / 2]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_polygon.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_polygon.py
new file mode 100644
index 0000000000000000000000000000000000000000..520023349f363bdb12146465305c2a5650c80934
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_polygon.py
@@ -0,0 +1,676 @@
+from sympy.core.numbers import (Float, Rational, oo, pi)
+from sympy.core.singleton import S
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.functions.elementary.complexes import Abs
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import (acos, cos, sin)
+from sympy.functions.elementary.trigonometric import tan
+from sympy.geometry import (Circle, Ellipse, GeometryError, Point, Point2D,
+                            Polygon, Ray, RegularPolygon, Segment, Triangle,
+                            are_similar, convex_hull, intersection, Line, Ray2D)
+from sympy.testing.pytest import raises, slow, warns
+from sympy.core.random import verify_numerically
+from sympy.geometry.polygon import rad, deg
+from sympy.integrals.integrals import integrate
+from sympy.utilities.iterables import rotate_left
+
+
+def feq(a, b):
+    """Test if two floating point values are 'equal'."""
+    t_float = Float("1.0E-10")
+    return -t_float < a - b < t_float
+
+@slow
+def test_polygon():
+    x = Symbol('x', real=True)
+    y = Symbol('y', real=True)
+    q = Symbol('q', real=True)
+    u = Symbol('u', real=True)
+    v = Symbol('v', real=True)
+    w = Symbol('w', real=True)
+    x1 = Symbol('x1', real=True)
+    half = S.Half
+    a, b, c = Point(0, 0), Point(2, 0), Point(3, 3)
+    t = Triangle(a, b, c)
+    assert Polygon(Point(0, 0)) == Point(0, 0)
+    assert Polygon(a, Point(1, 0), b, c) == t
+    assert Polygon(Point(1, 0), b, c, a) == t
+    assert Polygon(b, c, a, Point(1, 0)) == t
+    # 2 "remove folded" tests
+    assert Polygon(a, Point(3, 0), b, c) == t
+    assert Polygon(a, b, Point(3, -1), b, c) == t
+    # remove multiple collinear points
+    assert Polygon(Point(-4, 15), Point(-11, 15), Point(-15, 15),
+        Point(-15, 33/5), Point(-15, -87/10), Point(-15, -15),
+        Point(-42/5, -15), Point(-2, -15), Point(7, -15), Point(15, -15),
+        Point(15, -3), Point(15, 10), Point(15, 15)) == \
+        Polygon(Point(-15, -15), Point(15, -15), Point(15, 15), Point(-15, 15))
+
+    p1 = Polygon(
+        Point(0, 0), Point(3, -1),
+        Point(6, 0), Point(4, 5),
+        Point(2, 3), Point(0, 3))
+    p2 = Polygon(
+        Point(6, 0), Point(3, -1),
+        Point(0, 0), Point(0, 3),
+        Point(2, 3), Point(4, 5))
+    p3 = Polygon(
+        Point(0, 0), Point(3, 0),
+        Point(5, 2), Point(4, 4))
+    p4 = Polygon(
+        Point(0, 0), Point(4, 4),
+        Point(5, 2), Point(3, 0))
+    p5 = Polygon(
+        Point(0, 0), Point(4, 4),
+        Point(0, 4))
+    p6 = Polygon(
+        Point(-11, 1), Point(-9, 6.6),
+        Point(-4, -3), Point(-8.4, -8.7))
+    p7 = Polygon(
+        Point(x, y), Point(q, u),
+        Point(v, w))
+    p8 = Polygon(
+        Point(x, y), Point(v, w),
+        Point(q, u))
+    p9 = Polygon(
+        Point(0, 0), Point(4, 4),
+        Point(3, 0), Point(5, 2))
+    p10 = Polygon(
+        Point(0, 2), Point(2, 2),
+        Point(0, 0), Point(2, 0))
+    p11 = Polygon(Point(0, 0), 1, n=3)
+    p12 = Polygon(Point(0, 0), 1, 0, n=3)
+    p13 = Polygon(
+        Point(0, 0),Point(8, 8),
+        Point(23, 20),Point(0, 20))
+    p14 = Polygon(*rotate_left(p13.args, 1))
+
+
+    r = Ray(Point(-9, 6.6), Point(-9, 5.5))
+    #
+    # General polygon
+    #
+    assert p1 == p2
+    assert len(p1.args) == 6
+    assert len(p1.sides) == 6
+    assert p1.perimeter == 5 + 2*sqrt(10) + sqrt(29) + sqrt(8)
+    assert p1.area == 22
+    assert not p1.is_convex()
+    assert Polygon((-1, 1), (2, -1), (2, 1), (-1, -1), (3, 0)
+        ).is_convex() is False
+    # ensure convex for both CW and CCW point specification
+    assert p3.is_convex()
+    assert p4.is_convex()
+    dict5 = p5.angles
+    assert dict5[Point(0, 0)] == pi / 4
+    assert dict5[Point(0, 4)] == pi / 2
+    assert p5.encloses_point(Point(x, y)) is None
+    assert p5.encloses_point(Point(1, 3))
+    assert p5.encloses_point(Point(0, 0)) is False
+    assert p5.encloses_point(Point(4, 0)) is False
+    assert p1.encloses(Circle(Point(2.5, 2.5), 5)) is False
+    assert p1.encloses(Ellipse(Point(2.5, 2), 5, 6)) is False
+    assert p5.plot_interval('x') == [x, 0, 1]
+    assert p5.distance(
+        Polygon(Point(10, 10), Point(14, 14), Point(10, 14))) == 6 * sqrt(2)
+    assert p5.distance(
+        Polygon(Point(1, 8), Point(5, 8), Point(8, 12), Point(1, 12))) == 4
+    with warns(UserWarning, \
+               match="Polygons may intersect producing erroneous output"):
+        Polygon(Point(0, 0), Point(1, 0), Point(1, 1)).distance(
+                Polygon(Point(0, 0), Point(0, 1), Point(1, 1)))
+    assert hash(p5) == hash(Polygon(Point(0, 0), Point(4, 4), Point(0, 4)))
+    assert hash(p1) == hash(p2)
+    assert hash(p7) == hash(p8)
+    assert hash(p3) != hash(p9)
+    assert p5 == Polygon(Point(4, 4), Point(0, 4), Point(0, 0))
+    assert Polygon(Point(4, 4), Point(0, 4), Point(0, 0)) in p5
+    assert p5 != Point(0, 4)
+    assert Point(0, 1) in p5
+    assert p5.arbitrary_point('t').subs(Symbol('t', real=True), 0) == \
+        Point(0, 0)
+    raises(ValueError, lambda: Polygon(
+        Point(x, 0), Point(0, y), Point(x, y)).arbitrary_point('x'))
+    assert p6.intersection(r) == [Point(-9, Rational(-84, 13)), Point(-9, Rational(33, 5))]
+    assert p10.area == 0
+    assert p11 == RegularPolygon(Point(0, 0), 1, 3, 0)
+    assert p11 == p12
+    assert p11.vertices[0] == Point(1, 0)
+    assert p11.args[0] == Point(0, 0)
+    p11.spin(pi/2)
+    assert p11.vertices[0] == Point(0, 1)
+    #
+    # Regular polygon
+    #
+    p1 = RegularPolygon(Point(0, 0), 10, 5)
+    p2 = RegularPolygon(Point(0, 0), 5, 5)
+    raises(GeometryError, lambda: RegularPolygon(Point(0, 0), Point(0,
+           1), Point(1, 1)))
+    raises(GeometryError, lambda: RegularPolygon(Point(0, 0), 1, 2))
+    raises(ValueError, lambda: RegularPolygon(Point(0, 0), 1, 2.5))
+
+    assert p1 != p2
+    assert p1.interior_angle == pi*Rational(3, 5)
+    assert p1.exterior_angle == pi*Rational(2, 5)
+    assert p2.apothem == 5*cos(pi/5)
+    assert p2.circumcenter == p1.circumcenter == Point(0, 0)
+    assert p1.circumradius == p1.radius == 10
+    assert p2.circumcircle == Circle(Point(0, 0), 5)
+    assert p2.incircle == Circle(Point(0, 0), p2.apothem)
+    assert p2.inradius == p2.apothem == (5 * (1 + sqrt(5)) / 4)
+    p2.spin(pi / 10)
+    dict1 = p2.angles
+    assert dict1[Point(0, 5)] == 3 * pi / 5
+    assert p1.is_convex()
+    assert p1.rotation == 0
+    assert p1.encloses_point(Point(0, 0))
+    assert p1.encloses_point(Point(11, 0)) is False
+    assert p2.encloses_point(Point(0, 4.9))
+    p1.spin(pi/3)
+    assert p1.rotation == pi/3
+    assert p1.vertices[0] == Point(5, 5*sqrt(3))
+    for var in p1.args:
+        if isinstance(var, Point):
+            assert var == Point(0, 0)
+        else:
+            assert var in (5, 10, pi / 3)
+    assert p1 != Point(0, 0)
+    assert p1 != p5
+
+    # while spin works in place (notice that rotation is 2pi/3 below)
+    # rotate returns a new object
+    p1_old = p1
+    assert p1.rotate(pi/3) == RegularPolygon(Point(0, 0), 10, 5, pi*Rational(2, 3))
+    assert p1 == p1_old
+
+    assert p1.area == (-250*sqrt(5) + 1250)/(4*tan(pi/5))
+    assert p1.length == 20*sqrt(-sqrt(5)/8 + Rational(5, 8))
+    assert p1.scale(2, 2) == \
+        RegularPolygon(p1.center, p1.radius*2, p1._n, p1.rotation)
+    assert RegularPolygon((0, 0), 1, 4).scale(2, 3) == \
+        Polygon(Point(2, 0), Point(0, 3), Point(-2, 0), Point(0, -3))
+
+    assert repr(p1) == str(p1)
+
+    #
+    # Angles
+    #
+    angles = p4.angles
+    assert feq(angles[Point(0, 0)].evalf(), Float("0.7853981633974483"))
+    assert feq(angles[Point(4, 4)].evalf(), Float("1.2490457723982544"))
+    assert feq(angles[Point(5, 2)].evalf(), Float("1.8925468811915388"))
+    assert feq(angles[Point(3, 0)].evalf(), Float("2.3561944901923449"))
+
+    angles = p3.angles
+    assert feq(angles[Point(0, 0)].evalf(), Float("0.7853981633974483"))
+    assert feq(angles[Point(4, 4)].evalf(), Float("1.2490457723982544"))
+    assert feq(angles[Point(5, 2)].evalf(), Float("1.8925468811915388"))
+    assert feq(angles[Point(3, 0)].evalf(), Float("2.3561944901923449"))
+
+    # https://github.com/sympy/sympy/issues/24885
+    interior_angles_sum = sum(p13.angles.values())
+    assert feq(interior_angles_sum, (len(p13.angles) - 2)*pi )
+    interior_angles_sum = sum(p14.angles.values())
+    assert feq(interior_angles_sum, (len(p14.angles) - 2)*pi )
+
+    #
+    # Triangle
+    #
+    p1 = Point(0, 0)
+    p2 = Point(5, 0)
+    p3 = Point(0, 5)
+    t1 = Triangle(p1, p2, p3)
+    t2 = Triangle(p1, p2, Point(Rational(5, 2), sqrt(Rational(75, 4))))
+    t3 = Triangle(p1, Point(x1, 0), Point(0, x1))
+    s1 = t1.sides
+    assert Triangle(p1, p2, p1) == Polygon(p1, p2, p1) == Segment(p1, p2)
+    raises(GeometryError, lambda: Triangle(Point(0, 0)))
+
+    # Basic stuff
+    assert Triangle(p1, p1, p1) == p1
+    assert Triangle(p2, p2*2, p2*3) == Segment(p2, p2*3)
+    assert t1.area == Rational(25, 2)
+    assert t1.is_right()
+    assert t2.is_right() is False
+    assert t3.is_right()
+    assert p1 in t1
+    assert t1.sides[0] in t1
+    assert Segment((0, 0), (1, 0)) in t1
+    assert Point(5, 5) not in t2
+    assert t1.is_convex()
+    assert feq(t1.angles[p1].evalf(), pi.evalf()/2)
+
+    assert t1.is_equilateral() is False
+    assert t2.is_equilateral()
+    assert t3.is_equilateral() is False
+    assert are_similar(t1, t2) is False
+    assert are_similar(t1, t3)
+    assert are_similar(t2, t3) is False
+    assert t1.is_similar(Point(0, 0)) is False
+    assert t1.is_similar(t2) is False
+
+    # Bisectors
+    bisectors = t1.bisectors()
+    assert bisectors[p1] == Segment(
+        p1, Point(Rational(5, 2), Rational(5, 2)))
+    assert t2.bisectors()[p2] == Segment(
+        Point(5, 0), Point(Rational(5, 4), 5*sqrt(3)/4))
+    p4 = Point(0, x1)
+    assert t3.bisectors()[p4] == Segment(p4, Point(x1*(sqrt(2) - 1), 0))
+    ic = (250 - 125*sqrt(2))/50
+    assert t1.incenter == Point(ic, ic)
+
+    # Inradius
+    assert t1.inradius == t1.incircle.radius == 5 - 5*sqrt(2)/2
+    assert t2.inradius == t2.incircle.radius == 5*sqrt(3)/6
+    assert t3.inradius == t3.incircle.radius == x1**2/((2 + sqrt(2))*Abs(x1))
+
+    # Exradius
+    assert t1.exradii[t1.sides[2]] == 5*sqrt(2)/2
+
+    # Excenters
+    assert t1.excenters[t1.sides[2]] == Point2D(25*sqrt(2), -5*sqrt(2)/2)
+
+    # Circumcircle
+    assert t1.circumcircle.center == Point(2.5, 2.5)
+
+    # Medians + Centroid
+    m = t1.medians
+    assert t1.centroid == Point(Rational(5, 3), Rational(5, 3))
+    assert m[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2)))
+    assert t3.medians[p1] == Segment(p1, Point(x1/2, x1/2))
+    assert intersection(m[p1], m[p2], m[p3]) == [t1.centroid]
+    assert t1.medial == Triangle(Point(2.5, 0), Point(0, 2.5), Point(2.5, 2.5))
+
+    # Nine-point circle
+    assert t1.nine_point_circle == Circle(Point(2.5, 0),
+                                          Point(0, 2.5), Point(2.5, 2.5))
+    assert t1.nine_point_circle == Circle(Point(0, 0),
+                                          Point(0, 2.5), Point(2.5, 2.5))
+
+    # Perpendicular
+    altitudes = t1.altitudes
+    assert altitudes[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2)))
+    assert altitudes[p2].equals(s1[0])
+    assert altitudes[p3] == s1[2]
+    assert t1.orthocenter == p1
+    t = S('''Triangle(
+    Point(100080156402737/5000000000000, 79782624633431/500000000000),
+    Point(39223884078253/2000000000000, 156345163124289/1000000000000),
+    Point(31241359188437/1250000000000, 338338270939941/1000000000000000))''')
+    assert t.orthocenter == S('''Point(-780660869050599840216997'''
+    '''79471538701955848721853/80368430960602242240789074233100000000000000,'''
+    '''20151573611150265741278060334545897615974257/16073686192120448448157'''
+    '''8148466200000000000)''')
+
+    # Ensure
+    assert len(intersection(*bisectors.values())) == 1
+    assert len(intersection(*altitudes.values())) == 1
+    assert len(intersection(*m.values())) == 1
+
+    # Distance
+    p1 = Polygon(
+        Point(0, 0), Point(1, 0),
+        Point(1, 1), Point(0, 1))
+    p2 = Polygon(
+        Point(0, Rational(5)/4), Point(1, Rational(5)/4),
+        Point(1, Rational(9)/4), Point(0, Rational(9)/4))
+    p3 = Polygon(
+        Point(1, 2), Point(2, 2),
+        Point(2, 1))
+    p4 = Polygon(
+        Point(1, 1), Point(Rational(6)/5, 1),
+        Point(1, Rational(6)/5))
+    pt1 = Point(half, half)
+    pt2 = Point(1, 1)
+
+    '''Polygon to Point'''
+    assert p1.distance(pt1) == half
+    assert p1.distance(pt2) == 0
+    assert p2.distance(pt1) == Rational(3)/4
+    assert p3.distance(pt2) == sqrt(2)/2
+
+    '''Polygon to Polygon'''
+    # p1.distance(p2) emits a warning
+    with warns(UserWarning, \
+               match="Polygons may intersect producing erroneous output"):
+        assert p1.distance(p2) == half/2
+
+    assert p1.distance(p3) == sqrt(2)/2
+
+    # p3.distance(p4) emits a warning
+    with warns(UserWarning, \
+               match="Polygons may intersect producing erroneous output"):
+        assert p3.distance(p4) == (sqrt(2)/2 - sqrt(Rational(2)/25)/2)
+
+
+def test_convex_hull():
+    p = [Point(-5, -1), Point(-2, 1), Point(-2, -1), Point(-1, -3), \
+         Point(0, 0), Point(1, 1), Point(2, 2), Point(2, -1), Point(3, 1), \
+         Point(4, -1), Point(6, 2)]
+    ch = Polygon(p[0], p[3], p[9], p[10], p[6], p[1])
+    #test handling of duplicate points
+    p.append(p[3])
+
+    #more than 3 collinear points
+    another_p = [Point(-45, -85), Point(-45, 85), Point(-45, 26), \
+                 Point(-45, -24)]
+    ch2 = Segment(another_p[0], another_p[1])
+
+    assert convex_hull(*another_p) == ch2
+    assert convex_hull(*p) == ch
+    assert convex_hull(p[0]) == p[0]
+    assert convex_hull(p[0], p[1]) == Segment(p[0], p[1])
+
+    # no unique points
+    assert convex_hull(*[p[-1]]*3) == p[-1]
+
+    # collection of items
+    assert convex_hull(*[Point(0, 0), \
+                        Segment(Point(1, 0), Point(1, 1)), \
+                        RegularPolygon(Point(2, 0), 2, 4)]) == \
+        Polygon(Point(0, 0), Point(2, -2), Point(4, 0), Point(2, 2))
+
+
+def test_encloses():
+    # square with a dimpled left side
+    s = Polygon(Point(0, 0), Point(1, 0), Point(1, 1), Point(0, 1), \
+        Point(S.Half, S.Half))
+    # the following is True if the polygon isn't treated as closing on itself
+    assert s.encloses(Point(0, S.Half)) is False
+    assert s.encloses(Point(S.Half, S.Half)) is False  # it's a vertex
+    assert s.encloses(Point(Rational(3, 4), S.Half)) is True
+
+
+def test_triangle_kwargs():
+    assert Triangle(sss=(3, 4, 5)) == \
+        Triangle(Point(0, 0), Point(3, 0), Point(3, 4))
+    assert Triangle(asa=(30, 2, 30)) == \
+        Triangle(Point(0, 0), Point(2, 0), Point(1, sqrt(3)/3))
+    assert Triangle(sas=(1, 45, 2)) == \
+        Triangle(Point(0, 0), Point(2, 0), Point(sqrt(2)/2, sqrt(2)/2))
+    assert Triangle(sss=(1, 2, 5)) is None
+    assert deg(rad(180)) == 180
+
+
+def test_transform():
+    pts = [Point(0, 0), Point(S.Half, Rational(1, 4)), Point(1, 1)]
+    pts_out = [Point(-4, -10), Point(-3, Rational(-37, 4)), Point(-2, -7)]
+    assert Triangle(*pts).scale(2, 3, (4, 5)) == Triangle(*pts_out)
+    assert RegularPolygon((0, 0), 1, 4).scale(2, 3, (4, 5)) == \
+        Polygon(Point(-2, -10), Point(-4, -7), Point(-6, -10), Point(-4, -13))
+    # Checks for symmetric scaling
+    assert RegularPolygon((0, 0), 1, 4).scale(2, 2) == \
+        RegularPolygon(Point2D(0, 0), 2, 4, 0)
+
+def test_reflect():
+    x = Symbol('x', real=True)
+    y = Symbol('y', real=True)
+    b = Symbol('b')
+    m = Symbol('m')
+    l = Line((0, b), slope=m)
+    p = Point(x, y)
+    r = p.reflect(l)
+    dp = l.perpendicular_segment(p).length
+    dr = l.perpendicular_segment(r).length
+
+    assert verify_numerically(dp, dr)
+
+    assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((3, 0), slope=oo)) \
+        == Triangle(Point(5, 0), Point(4, 0), Point(4, 2))
+    assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((0, 3), slope=oo)) \
+        == Triangle(Point(-1, 0), Point(-2, 0), Point(-2, 2))
+    assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((0, 3), slope=0)) \
+        == Triangle(Point(1, 6), Point(2, 6), Point(2, 4))
+    assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((3, 0), slope=0)) \
+        == Triangle(Point(1, 0), Point(2, 0), Point(2, -2))
+
+def test_bisectors():
+    p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1)
+    p = Polygon(Point(0, 0), Point(2, 0), Point(1, 1), Point(0, 3))
+    q = Polygon(Point(1, 0), Point(2, 0), Point(3, 3), Point(-1, 5))
+    poly = Polygon(Point(3, 4), Point(0, 0), Point(8, 7), Point(-1, 1), Point(19, -19))
+    t = Triangle(p1, p2, p3)
+    assert t.bisectors()[p2] == Segment(Point(1, 0), Point(0, sqrt(2) - 1))
+    assert p.bisectors()[Point2D(0, 3)] == Ray2D(Point2D(0, 3), \
+        Point2D(sin(acos(2*sqrt(5)/5)/2), 3 - cos(acos(2*sqrt(5)/5)/2)))
+    assert q.bisectors()[Point2D(-1, 5)] == \
+        Ray2D(Point2D(-1, 5), Point2D(-1 + sqrt(29)*(5*sin(acos(9*sqrt(145)/145)/2) + \
+        2*cos(acos(9*sqrt(145)/145)/2))/29, sqrt(29)*(-5*cos(acos(9*sqrt(145)/145)/2) + \
+        2*sin(acos(9*sqrt(145)/145)/2))/29 + 5))
+    assert poly.bisectors()[Point2D(-1, 1)] == Ray2D(Point2D(-1, 1), \
+        Point2D(-1 + sin(acos(sqrt(26)/26)/2 + pi/4), 1 - sin(-acos(sqrt(26)/26)/2 + pi/4)))
+
+def test_incenter():
+    assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).incenter \
+        == Point(1 - sqrt(2)/2, 1 - sqrt(2)/2)
+
+def test_inradius():
+    assert Triangle(Point(0, 0), Point(4, 0), Point(0, 3)).inradius == 1
+
+def test_incircle():
+    assert Triangle(Point(0, 0), Point(2, 0), Point(0, 2)).incircle \
+        == Circle(Point(2 - sqrt(2), 2 - sqrt(2)), 2 - sqrt(2))
+
+def test_exradii():
+    t = Triangle(Point(0, 0), Point(6, 0), Point(0, 2))
+    assert t.exradii[t.sides[2]] == (-2 + sqrt(10))
+
+def test_medians():
+    t = Triangle(Point(0, 0), Point(1, 0), Point(0, 1))
+    assert t.medians[Point(0, 0)] == Segment(Point(0, 0), Point(S.Half, S.Half))
+
+def test_medial():
+    assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).medial \
+        == Triangle(Point(S.Half, 0), Point(S.Half, S.Half), Point(0, S.Half))
+
+def test_nine_point_circle():
+    assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).nine_point_circle \
+        == Circle(Point2D(Rational(1, 4), Rational(1, 4)), sqrt(2)/4)
+
+def test_eulerline():
+    assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).eulerline \
+        == Line(Point2D(0, 0), Point2D(S.Half, S.Half))
+    assert Triangle(Point(0, 0), Point(10, 0), Point(5, 5*sqrt(3))).eulerline \
+        == Point2D(5, 5*sqrt(3)/3)
+    assert Triangle(Point(4, -6), Point(4, -1), Point(-3, 3)).eulerline \
+        == Line(Point2D(Rational(64, 7), 3), Point2D(Rational(-29, 14), Rational(-7, 2)))
+
+def test_intersection():
+    poly1 = Triangle(Point(0, 0), Point(1, 0), Point(0, 1))
+    poly2 = Polygon(Point(0, 1), Point(-5, 0),
+                    Point(0, -4), Point(0, Rational(1, 5)),
+                    Point(S.Half, -0.1), Point(1, 0), Point(0, 1))
+
+    assert poly1.intersection(poly2) == [Point2D(Rational(1, 3), 0),
+        Segment(Point(0, Rational(1, 5)), Point(0, 0)),
+        Segment(Point(1, 0), Point(0, 1))]
+    assert poly2.intersection(poly1) == [Point(Rational(1, 3), 0),
+        Segment(Point(0, 0), Point(0, Rational(1, 5))),
+        Segment(Point(1, 0), Point(0, 1))]
+    assert poly1.intersection(Point(0, 0)) == [Point(0, 0)]
+    assert poly1.intersection(Point(-12,  -43)) == []
+    assert poly2.intersection(Line((-12, 0), (12, 0))) == [Point(-5, 0),
+        Point(0, 0), Point(Rational(1, 3), 0), Point(1, 0)]
+    assert poly2.intersection(Line((-12, 12), (12, 12))) == []
+    assert poly2.intersection(Ray((-3, 4), (1, 0))) == [Segment(Point(1, 0),
+        Point(0, 1))]
+    assert poly2.intersection(Circle((0, -1), 1)) == [Point(0, -2),
+        Point(0, 0)]
+    assert poly1.intersection(poly1) == [Segment(Point(0, 0), Point(1, 0)),
+        Segment(Point(0, 1), Point(0, 0)), Segment(Point(1, 0), Point(0, 1))]
+    assert poly2.intersection(poly2) == [Segment(Point(-5, 0), Point(0, -4)),
+        Segment(Point(0, -4), Point(0, Rational(1, 5))),
+        Segment(Point(0, Rational(1, 5)), Point(S.Half, Rational(-1, 10))),
+        Segment(Point(0, 1), Point(-5, 0)),
+        Segment(Point(S.Half, Rational(-1, 10)), Point(1, 0)),
+        Segment(Point(1, 0), Point(0, 1))]
+    assert poly2.intersection(Triangle(Point(0, 1), Point(1, 0), Point(-1, 1))) \
+        == [Point(Rational(-5, 7), Rational(6, 7)), Segment(Point2D(0, 1), Point(1, 0))]
+    assert poly1.intersection(RegularPolygon((-12, -15), 3, 3)) == []
+
+
+def test_parameter_value():
+    t = Symbol('t')
+    sq = Polygon((0, 0), (0, 1), (1, 1), (1, 0))
+    assert sq.parameter_value((0.5, 1), t) == {t: Rational(3, 8)}
+    q = Polygon((0, 0), (2, 1), (2, 4), (4, 0))
+    assert q.parameter_value((4, 0), t) == {t: -6 + 3*sqrt(5)} # ~= 0.708
+
+    raises(ValueError, lambda: sq.parameter_value((5, 6), t))
+    raises(ValueError, lambda: sq.parameter_value(Circle(Point(0, 0), 1), t))
+
+
+def test_issue_12966():
+    poly = Polygon(Point(0, 0), Point(0, 10), Point(5, 10), Point(5, 5),
+        Point(10, 5), Point(10, 0))
+    t = Symbol('t')
+    pt = poly.arbitrary_point(t)
+    DELTA = 5/poly.perimeter
+    assert [pt.subs(t, DELTA*i) for i in range(int(1/DELTA))] == [
+        Point(0, 0), Point(0, 5), Point(0, 10), Point(5, 10),
+        Point(5, 5), Point(10, 5), Point(10, 0), Point(5, 0)]
+
+
+def test_second_moment_of_area():
+    x, y = symbols('x, y')
+    # triangle
+    p1, p2, p3 = [(0, 0), (4, 0), (0, 2)]
+    p = (0, 0)
+    # equation of hypotenuse
+    eq_y = (1-x/4)*2
+    I_yy = integrate((x**2) * (integrate(1, (y, 0, eq_y))), (x, 0, 4))
+    I_xx = integrate(1 * (integrate(y**2, (y, 0, eq_y))), (x, 0, 4))
+    I_xy = integrate(x * (integrate(y, (y, 0, eq_y))), (x, 0, 4))
+
+    triangle = Polygon(p1, p2, p3)
+
+    assert (I_xx - triangle.second_moment_of_area(p)[0]) == 0
+    assert (I_yy - triangle.second_moment_of_area(p)[1]) == 0
+    assert (I_xy - triangle.second_moment_of_area(p)[2]) == 0
+
+    # rectangle
+    p1, p2, p3, p4=[(0, 0), (4, 0), (4, 2), (0, 2)]
+    I_yy = integrate((x**2) * integrate(1, (y, 0, 2)), (x, 0, 4))
+    I_xx = integrate(1 * integrate(y**2, (y, 0, 2)), (x, 0, 4))
+    I_xy = integrate(x * integrate(y, (y, 0, 2)), (x, 0, 4))
+
+    rectangle = Polygon(p1, p2, p3, p4)
+
+    assert (I_xx - rectangle.second_moment_of_area(p)[0]) == 0
+    assert (I_yy - rectangle.second_moment_of_area(p)[1]) == 0
+    assert (I_xy - rectangle.second_moment_of_area(p)[2]) == 0
+
+
+    r = RegularPolygon(Point(0, 0), 5, 3)
+    assert r.second_moment_of_area() == (1875*sqrt(3)/S(32), 1875*sqrt(3)/S(32), 0)
+
+
+def test_first_moment():
+    a, b  = symbols('a, b', positive=True)
+    # rectangle
+    p1 = Polygon((0, 0), (a, 0), (a, b), (0, b))
+    assert p1.first_moment_of_area() == (a*b**2/8, a**2*b/8)
+    assert p1.first_moment_of_area((a/3, b/4)) == (-3*a*b**2/32, -a**2*b/9)
+
+    p1 = Polygon((0, 0), (40, 0), (40, 30), (0, 30))
+    assert p1.first_moment_of_area() == (4500, 6000)
+
+    # triangle
+    p2 = Polygon((0, 0), (a, 0), (a/2, b))
+    assert p2.first_moment_of_area() == (4*a*b**2/81, a**2*b/24)
+    assert p2.first_moment_of_area((a/8, b/6)) == (-25*a*b**2/648, -5*a**2*b/768)
+
+    p2 = Polygon((0, 0), (12, 0), (12, 30))
+    assert p2.first_moment_of_area() == (S(1600)/3, -S(640)/3)
+
+
+def test_section_modulus_and_polar_second_moment_of_area():
+    a, b = symbols('a, b', positive=True)
+    x, y = symbols('x, y')
+    rectangle = Polygon((0, b), (0, 0), (a, 0), (a, b))
+    assert rectangle.section_modulus(Point(x, y)) == (a*b**3/12/(-b/2 + y), a**3*b/12/(-a/2 + x))
+    assert rectangle.polar_second_moment_of_area() == a**3*b/12 + a*b**3/12
+
+    convex = RegularPolygon((0, 0), 1, 6)
+    assert convex.section_modulus() == (Rational(5, 8), sqrt(3)*Rational(5, 16))
+    assert convex.polar_second_moment_of_area() == 5*sqrt(3)/S(8)
+
+    concave = Polygon((0, 0), (1, 8), (3, 4), (4, 6), (7, 1))
+    assert concave.section_modulus() == (Rational(-6371, 429), Rational(-9778, 519))
+    assert concave.polar_second_moment_of_area() == Rational(-38669, 252)
+
+
+def test_cut_section():
+    # concave polygon
+    p = Polygon((-1, -1), (1, Rational(5, 2)), (2, 1), (3, Rational(5, 2)), (4, 2), (5, 3), (-1, 3))
+    l = Line((0, 0), (Rational(9, 2), 3))
+    p1 = p.cut_section(l)[0]
+    p2 = p.cut_section(l)[1]
+    assert p1 == Polygon(
+        Point2D(Rational(-9, 13), Rational(-6, 13)), Point2D(1, Rational(5, 2)), Point2D(Rational(24, 13), Rational(16, 13)),
+        Point2D(Rational(12, 5), Rational(8, 5)), Point2D(3, Rational(5, 2)), Point2D(Rational(24, 7), Rational(16, 7)),
+        Point2D(Rational(9, 2), 3), Point2D(-1, 3), Point2D(-1, Rational(-2, 3)))
+    assert p2 == Polygon(Point2D(-1, -1), Point2D(Rational(-9, 13), Rational(-6, 13)), Point2D(Rational(24, 13), Rational(16, 13)),
+        Point2D(2, 1), Point2D(Rational(12, 5), Rational(8, 5)), Point2D(Rational(24, 7), Rational(16, 7)), Point2D(4, 2), Point2D(5, 3),
+        Point2D(Rational(9, 2), 3), Point2D(-1, Rational(-2, 3)))
+
+    # convex polygon
+    p = RegularPolygon(Point2D(0, 0), 6, 6)
+    s = p.cut_section(Line((0, 0), slope=1))
+    assert s[0] == Polygon(Point2D(-3*sqrt(3) + 9, -3*sqrt(3) + 9), Point2D(3, 3*sqrt(3)),
+        Point2D(-3, 3*sqrt(3)), Point2D(-6, 0), Point2D(-9 + 3*sqrt(3), -9 + 3*sqrt(3)))
+    assert s[1] == Polygon(Point2D(6, 0), Point2D(-3*sqrt(3) + 9, -3*sqrt(3) + 9),
+        Point2D(-9 + 3*sqrt(3), -9 + 3*sqrt(3)), Point2D(-3, -3*sqrt(3)), Point2D(3, -3*sqrt(3)))
+
+    # case where line does not intersects but coincides with the edge of polygon
+    a, b = 20, 10
+    t1, t2, t3, t4 = [(0, b), (0, 0), (a, 0), (a, b)]
+    p = Polygon(t1, t2, t3, t4)
+    p1, p2 = p.cut_section(Line((0, b), slope=0))
+    assert p1 == None
+    assert p2 == Polygon(Point2D(0, 10), Point2D(0, 0), Point2D(20, 0), Point2D(20, 10))
+
+    p3, p4 = p.cut_section(Line((0, 0), slope=0))
+    assert p3 == Polygon(Point2D(0, 10), Point2D(0, 0), Point2D(20, 0), Point2D(20, 10))
+    assert p4 == None
+
+    # case where the line does not intersect with a polygon at all
+    raises(ValueError, lambda: p.cut_section(Line((0, a), slope=0)))
+
+def test_type_of_triangle():
+    # Isoceles triangle
+    p1 = Polygon(Point(0, 0), Point(5, 0), Point(2, 4))
+    assert p1.is_isosceles() == True
+    assert p1.is_scalene() == False
+    assert p1.is_equilateral() == False
+
+    # Scalene triangle
+    p2 = Polygon (Point(0, 0), Point(0, 2), Point(4, 0))
+    assert p2.is_isosceles() == False
+    assert p2.is_scalene() == True
+    assert p2.is_equilateral() == False
+
+    # Equilateral triangle
+    p3 = Polygon(Point(0, 0), Point(6, 0), Point(3, sqrt(27)))
+    assert p3.is_isosceles() == True
+    assert p3.is_scalene() == False
+    assert p3.is_equilateral() == True
+
+def test_do_poly_distance():
+    # Non-intersecting polygons
+    square1 = Polygon (Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0))
+    triangle1 = Polygon(Point(1, 2), Point(2, 2), Point(2, 1))
+    assert square1._do_poly_distance(triangle1) == sqrt(2)/2
+
+    # Polygons which sides intersect
+    square2 = Polygon(Point(1, 0), Point(2, 0), Point(2, 1), Point(1, 1))
+    with warns(UserWarning, \
+               match="Polygons may intersect producing erroneous output", test_stacklevel=False):
+        assert square1._do_poly_distance(square2) == 0
+
+    # Polygons which bodies intersect
+    triangle2 = Polygon(Point(0, -1), Point(2, -1), Point(S.Half, S.Half))
+    with warns(UserWarning, \
+               match="Polygons may intersect producing erroneous output", test_stacklevel=False):
+        assert triangle2._do_poly_distance(square1) == 0
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_util.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..da52a795a9383c6438ca06303e8ae6506dccdc65
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/tests/test_util.py
@@ -0,0 +1,170 @@
+import pytest
+from sympy.core.numbers import Float
+from sympy.core.function import (Derivative, Function)
+from sympy.core.singleton import S
+from sympy.core.symbol import Symbol
+from sympy.functions import exp, cos, sin, tan, cosh, sinh
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.geometry import Point, Point2D, Line, Polygon, Segment, convex_hull,\
+    intersection, centroid, Point3D, Line3D, Ray, Ellipse
+from sympy.geometry.util import idiff, closest_points, farthest_points, _ordered_points, are_coplanar
+from sympy.solvers.solvers import solve
+from sympy.testing.pytest import raises
+
+
+def test_idiff():
+    x = Symbol('x', real=True)
+    y = Symbol('y', real=True)
+    t = Symbol('t', real=True)
+    f = Function('f')
+    g = Function('g')
+    # the use of idiff in ellipse also provides coverage
+    circ = x**2 + y**2 - 4
+    ans = -3*x*(x**2/y**2 + 1)/y**3
+    assert ans == idiff(circ, y, x, 3), idiff(circ, y, x, 3)
+    assert ans == idiff(circ, [y], x, 3)
+    assert idiff(circ, y, x, 3) == ans
+    explicit  = 12*x/sqrt(-x**2 + 4)**5
+    assert ans.subs(y, solve(circ, y)[0]).equals(explicit)
+    assert True in [sol.diff(x, 3).equals(explicit) for sol in solve(circ, y)]
+    assert idiff(x + t + y, [y, t], x) == -Derivative(t, x) - 1
+    assert idiff(f(x) * exp(f(x)) - x * exp(x), f(x), x) == (x + 1)*exp(x)*exp(-f(x))/(f(x) + 1)
+    assert idiff(f(x) - y * exp(x), [f(x), y], x) == (y + Derivative(y, x))*exp(x)
+    assert idiff(f(x) - y * exp(x), [y, f(x)], x) == -y + Derivative(f(x), x)*exp(-x)
+    assert idiff(f(x) - g(x), [f(x), g(x)], x) == Derivative(g(x), x)
+    # this should be fast
+    fxy = y - (-10*(-sin(x) + 1/x)**2 + tan(x)**2 + 2*cosh(x/10))
+    assert idiff(fxy, y, x) == -20*sin(x)*cos(x) + 2*tan(x)**3 + \
+        2*tan(x) + sinh(x/10)/5 + 20*cos(x)/x - 20*sin(x)/x**2 + 20/x**3
+
+
+def test_intersection():
+    assert intersection(Point(0, 0)) == []
+    raises(TypeError, lambda: intersection(Point(0, 0), 3))
+    assert intersection(
+            Segment((0, 0), (2, 0)),
+            Segment((-1, 0), (1, 0)),
+            Line((0, 0), (0, 1)), pairwise=True) == [
+        Point(0, 0), Segment((0, 0), (1, 0))]
+    assert intersection(
+            Line((0, 0), (0, 1)),
+            Segment((0, 0), (2, 0)),
+            Segment((-1, 0), (1, 0)), pairwise=True) == [
+        Point(0, 0), Segment((0, 0), (1, 0))]
+    assert intersection(
+            Line((0, 0), (0, 1)),
+            Segment((0, 0), (2, 0)),
+            Segment((-1, 0), (1, 0)),
+            Line((0, 0), slope=1), pairwise=True) == [
+        Point(0, 0), Segment((0, 0), (1, 0))]
+    R = 4.0
+    c = intersection(
+            Ray(Point2D(0.001, -1),
+            Point2D(0.0008, -1.7)),
+            Ellipse(center=Point2D(0, 0), hradius=R, vradius=2.0), pairwise=True)[0].coordinates
+    assert c == pytest.approx(
+            Point2D(0.000714285723396502, -1.99999996811224, evaluate=False).coordinates)
+    # check this is responds to a lower precision parameter
+    R = Float(4, 5)
+    c2 = intersection(
+            Ray(Point2D(0.001, -1),
+            Point2D(0.0008, -1.7)),
+            Ellipse(center=Point2D(0, 0), hradius=R, vradius=2.0), pairwise=True)[0].coordinates
+    assert c2 == pytest.approx(
+            Point2D(0.000714285723396502, -1.99999996811224, evaluate=False).coordinates)
+    assert c[0]._prec == 53
+    assert c2[0]._prec == 20
+
+
+def test_convex_hull():
+    raises(TypeError, lambda: convex_hull(Point(0, 0), 3))
+    points = [(1, -1), (1, -2), (3, -1), (-5, -2), (15, -4)]
+    assert convex_hull(*points, **{"polygon": False}) == (
+        [Point2D(-5, -2), Point2D(1, -1), Point2D(3, -1), Point2D(15, -4)],
+        [Point2D(-5, -2), Point2D(15, -4)])
+
+
+def test_centroid():
+    p = Polygon((0, 0), (10, 0), (10, 10))
+    q = p.translate(0, 20)
+    assert centroid(p, q) == Point(20, 40)/3
+    p = Segment((0, 0), (2, 0))
+    q = Segment((0, 0), (2, 2))
+    assert centroid(p, q) == Point(1, -sqrt(2) + 2)
+    assert centroid(Point(0, 0), Point(2, 0)) == Point(2, 0)/2
+    assert centroid(Point(0, 0), Point(0, 0), Point(2, 0)) == Point(2, 0)/3
+
+
+def test_farthest_points_closest_points():
+    from sympy.core.random import randint
+    from sympy.utilities.iterables import subsets
+
+    for how in (min, max):
+        if how == min:
+            func = closest_points
+        else:
+            func = farthest_points
+
+        raises(ValueError, lambda: func(Point2D(0, 0), Point2D(0, 0)))
+
+        # 3rd pt dx is close and pt is closer to 1st pt
+        p1 = [Point2D(0, 0), Point2D(3, 0), Point2D(1, 1)]
+        # 3rd pt dx is close and pt is closer to 2nd pt
+        p2 = [Point2D(0, 0), Point2D(3, 0), Point2D(2, 1)]
+        # 3rd pt dx is close and but pt is not closer
+        p3 = [Point2D(0, 0), Point2D(3, 0), Point2D(1, 10)]
+        # 3rd pt dx is not closer and it's closer to 2nd pt
+        p4 = [Point2D(0, 0), Point2D(3, 0), Point2D(4, 0)]
+        # 3rd pt dx is not closer and it's closer to 1st pt
+        p5 = [Point2D(0, 0), Point2D(3, 0), Point2D(-1, 0)]
+        # duplicate point doesn't affect outcome
+        dup = [Point2D(0, 0), Point2D(3, 0), Point2D(3, 0), Point2D(-1, 0)]
+        # symbolic
+        x = Symbol('x', positive=True)
+        s = [Point2D(a) for a in ((x, 1), (x + 3, 2), (x + 2, 2))]
+
+        for points in (p1, p2, p3, p4, p5, dup, s):
+            d = how(i.distance(j) for i, j in subsets(set(points), 2))
+            ans = a, b = list(func(*points))[0]
+            assert a.distance(b) == d
+            assert ans == _ordered_points(ans)
+
+        # if the following ever fails, the above tests were not sufficient
+        # and the logical error in the routine should be fixed
+        points = set()
+        while len(points) != 7:
+            points.add(Point2D(randint(1, 100), randint(1, 100)))
+        points = list(points)
+        d = how(i.distance(j) for i, j in subsets(points, 2))
+        ans = a, b = list(func(*points))[0]
+        assert a.distance(b) == d
+        assert ans == _ordered_points(ans)
+
+    # equidistant points
+    a, b, c = (
+        Point2D(0, 0), Point2D(1, 0), Point2D(S.Half, sqrt(3)/2))
+    ans = {_ordered_points((i, j))
+        for i, j in subsets((a, b, c), 2)}
+    assert closest_points(b, c, a) == ans
+    assert farthest_points(b, c, a) == ans
+
+    # unique to farthest
+    points = [(1, 1), (1, 2), (3, 1), (-5, 2), (15, 4)]
+    assert farthest_points(*points) == {
+        (Point2D(-5, 2), Point2D(15, 4))}
+    points = [(1, -1), (1, -2), (3, -1), (-5, -2), (15, -4)]
+    assert farthest_points(*points) == {
+        (Point2D(-5, -2), Point2D(15, -4))}
+    assert farthest_points((1, 1), (0, 0)) == {
+        (Point2D(0, 0), Point2D(1, 1))}
+    raises(ValueError, lambda: farthest_points((1, 1)))
+
+
+def test_are_coplanar():
+    a = Line3D(Point3D(5, 0, 0), Point3D(1, -1, 1))
+    b = Line3D(Point3D(0, -2, 0), Point3D(3, 1, 1))
+    c = Line3D(Point3D(0, -1, 0), Point3D(5, -1, 9))
+    d = Line(Point2D(0, 3), Point2D(1, 5))
+
+    assert are_coplanar(a, b, c) == False
+    assert are_coplanar(a, d) == False
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/util.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d8fb77550f2faea8185ff0c373b5f1680e623ec
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/geometry/util.py
@@ -0,0 +1,731 @@
+"""Utility functions for geometrical entities.
+
+Contains
+========
+intersection
+convex_hull
+closest_points
+farthest_points
+are_coplanar
+are_similar
+
+"""
+
+from collections import deque
+from math import sqrt as _sqrt
+
+from sympy import nsimplify
+from .entity import GeometryEntity
+from .exceptions import GeometryError
+from .point import Point, Point2D, Point3D
+from sympy.core.containers import OrderedSet
+from sympy.core.exprtools import factor_terms
+from sympy.core.function import Function, expand_mul
+from sympy.core.numbers import Float
+from sympy.core.sorting import ordered
+from sympy.core.symbol import Symbol
+from sympy.core.singleton import S
+from sympy.polys.polytools import cancel
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.utilities.iterables import is_sequence
+
+from mpmath.libmp.libmpf import prec_to_dps
+
+
+def find(x, equation):
+    """
+    Checks whether a Symbol matching ``x`` is present in ``equation``
+    or not. If present, the matching symbol is returned, else a
+    ValueError is raised. If ``x`` is a string the matching symbol
+    will have the same name; if ``x`` is a Symbol then it will be
+    returned if found.
+
+    Examples
+    ========
+
+    >>> from sympy.geometry.util import find
+    >>> from sympy import Dummy
+    >>> from sympy.abc import x
+    >>> find('x', x)
+    x
+    >>> find('x', Dummy('x'))
+    _x
+
+    The dummy symbol is returned since it has a matching name:
+
+    >>> _.name == 'x'
+    True
+    >>> find(x, Dummy('x'))
+    Traceback (most recent call last):
+    ...
+    ValueError: could not find x
+    """
+
+    free = equation.free_symbols
+    xs = [i for i in free if (i.name if isinstance(x, str) else i) == x]
+    if not xs:
+        raise ValueError('could not find %s' % x)
+    if len(xs) != 1:
+        raise ValueError('ambiguous %s' % x)
+    return xs[0]
+
+
+def _ordered_points(p):
+    """Return the tuple of points sorted numerically according to args"""
+    return tuple(sorted(p, key=lambda x: x.args))
+
+
+def are_coplanar(*e):
+    """ Returns True if the given entities are coplanar otherwise False
+
+    Parameters
+    ==========
+
+    e: entities to be checked for being coplanar
+
+    Returns
+    =======
+
+    Boolean
+
+    Examples
+    ========
+
+    >>> from sympy import Point3D, Line3D
+    >>> from sympy.geometry.util import are_coplanar
+    >>> a = Line3D(Point3D(5, 0, 0), Point3D(1, -1, 1))
+    >>> b = Line3D(Point3D(0, -2, 0), Point3D(3, 1, 1))
+    >>> c = Line3D(Point3D(0, -1, 0), Point3D(5, -1, 9))
+    >>> are_coplanar(a, b, c)
+    False
+
+    """
+    from .line import LinearEntity3D
+    from .plane import Plane
+    # XXX update tests for coverage
+
+    e = set(e)
+    # first work with a Plane if present
+    for i in list(e):
+        if isinstance(i, Plane):
+            e.remove(i)
+            return all(p.is_coplanar(i) for p in e)
+
+    if all(isinstance(i, Point3D) for i in e):
+        if len(e) < 3:
+            return False
+
+        # remove pts that are collinear with 2 pts
+        a, b = e.pop(), e.pop()
+        for i in list(e):
+            if Point3D.are_collinear(a, b, i):
+                e.remove(i)
+
+        if not e:
+            return False
+        else:
+            # define a plane
+            p = Plane(a, b, e.pop())
+            for i in e:
+                if i not in p:
+                    return False
+            return True
+    else:
+        pt3d = []
+        for i in e:
+            if isinstance(i, Point3D):
+                pt3d.append(i)
+            elif isinstance(i, LinearEntity3D):
+                pt3d.extend(i.args)
+            elif isinstance(i, GeometryEntity):  # XXX we should have a GeometryEntity3D class so we can tell the difference between 2D and 3D -- here we just want to deal with 2D objects; if new 3D objects are encountered that we didn't handle above, an error should be raised
+                # all 2D objects have some Point that defines them; so convert those points to 3D pts by making z=0
+                for p in i.args:
+                    if isinstance(p, Point):
+                        pt3d.append(Point3D(*(p.args + (0,))))
+        return are_coplanar(*pt3d)
+
+
+def are_similar(e1, e2):
+    """Are two geometrical entities similar.
+
+    Can one geometrical entity be uniformly scaled to the other?
+
+    Parameters
+    ==========
+
+    e1 : GeometryEntity
+    e2 : GeometryEntity
+
+    Returns
+    =======
+
+    are_similar : boolean
+
+    Raises
+    ======
+
+    GeometryError
+        When `e1` and `e2` cannot be compared.
+
+    Notes
+    =====
+
+    If the two objects are equal then they are similar.
+
+    See Also
+    ========
+
+    sympy.geometry.entity.GeometryEntity.is_similar
+
+    Examples
+    ========
+
+    >>> from sympy import Point, Circle, Triangle, are_similar
+    >>> c1, c2 = Circle(Point(0, 0), 4), Circle(Point(1, 4), 3)
+    >>> t1 = Triangle(Point(0, 0), Point(1, 0), Point(0, 1))
+    >>> t2 = Triangle(Point(0, 0), Point(2, 0), Point(0, 2))
+    >>> t3 = Triangle(Point(0, 0), Point(3, 0), Point(0, 1))
+    >>> are_similar(t1, t2)
+    True
+    >>> are_similar(t1, t3)
+    False
+
+    """
+    if e1 == e2:
+        return True
+    is_similar1 = getattr(e1, 'is_similar', None)
+    if is_similar1:
+        return is_similar1(e2)
+    is_similar2 = getattr(e2, 'is_similar', None)
+    if is_similar2:
+        return is_similar2(e1)
+    n1 = e1.__class__.__name__
+    n2 = e2.__class__.__name__
+    raise GeometryError(
+        "Cannot test similarity between %s and %s" % (n1, n2))
+
+
+def centroid(*args):
+    """Find the centroid (center of mass) of the collection containing only Points,
+    Segments or Polygons. The centroid is the weighted average of the individual centroid
+    where the weights are the lengths (of segments) or areas (of polygons).
+    Overlapping regions will add to the weight of that region.
+
+    If there are no objects (or a mixture of objects) then None is returned.
+
+    See Also
+    ========
+
+    sympy.geometry.point.Point, sympy.geometry.line.Segment,
+    sympy.geometry.polygon.Polygon
+
+    Examples
+    ========
+
+    >>> from sympy import Point, Segment, Polygon
+    >>> from sympy.geometry.util import centroid
+    >>> p = Polygon((0, 0), (10, 0), (10, 10))
+    >>> q = p.translate(0, 20)
+    >>> p.centroid, q.centroid
+    (Point2D(20/3, 10/3), Point2D(20/3, 70/3))
+    >>> centroid(p, q)
+    Point2D(20/3, 40/3)
+    >>> p, q = Segment((0, 0), (2, 0)), Segment((0, 0), (2, 2))
+    >>> centroid(p, q)
+    Point2D(1, 2 - sqrt(2))
+    >>> centroid(Point(0, 0), Point(2, 0))
+    Point2D(1, 0)
+
+    Stacking 3 polygons on top of each other effectively triples the
+    weight of that polygon:
+
+    >>> p = Polygon((0, 0), (1, 0), (1, 1), (0, 1))
+    >>> q = Polygon((1, 0), (3, 0), (3, 1), (1, 1))
+    >>> centroid(p, q)
+    Point2D(3/2, 1/2)
+    >>> centroid(p, p, p, q) # centroid x-coord shifts left
+    Point2D(11/10, 1/2)
+
+    Stacking the squares vertically above and below p has the same
+    effect:
+
+    >>> centroid(p, p.translate(0, 1), p.translate(0, -1), q)
+    Point2D(11/10, 1/2)
+
+    """
+    from .line import Segment
+    from .polygon import Polygon
+    if args:
+        if all(isinstance(g, Point) for g in args):
+            c = Point(0, 0)
+            for g in args:
+                c += g
+            den = len(args)
+        elif all(isinstance(g, Segment) for g in args):
+            c = Point(0, 0)
+            L = 0
+            for g in args:
+                l = g.length
+                c += g.midpoint*l
+                L += l
+            den = L
+        elif all(isinstance(g, Polygon) for g in args):
+            c = Point(0, 0)
+            A = 0
+            for g in args:
+                a = g.area
+                c += g.centroid*a
+                A += a
+            den = A
+        c /= den
+        return c.func(*[i.simplify() for i in c.args])
+
+
+def closest_points(*args):
+    """Return the subset of points from a set of points that were
+    the closest to each other in the 2D plane.
+
+    Parameters
+    ==========
+
+    args
+        A collection of Points on 2D plane.
+
+    Notes
+    =====
+
+    This can only be performed on a set of points whose coordinates can
+    be ordered on the number line. If there are no ties then a single
+    pair of Points will be in the set.
+
+    Examples
+    ========
+
+    >>> from sympy import closest_points, Triangle
+    >>> Triangle(sss=(3, 4, 5)).args
+    (Point2D(0, 0), Point2D(3, 0), Point2D(3, 4))
+    >>> closest_points(*_)
+    {(Point2D(0, 0), Point2D(3, 0))}
+
+    References
+    ==========
+
+    .. [1] https://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairPS.html
+
+    .. [2] Sweep line algorithm
+        https://en.wikipedia.org/wiki/Sweep_line_algorithm
+
+    """
+    p = [Point2D(i) for i in set(args)]
+    if len(p) < 2:
+        raise ValueError('At least 2 distinct points must be given.')
+
+    try:
+        p.sort(key=lambda x: x.args)
+    except TypeError:
+        raise ValueError("The points could not be sorted.")
+
+    if not all(i.is_Rational for j in p for i in j.args):
+        def hypot(x, y):
+            arg = x*x + y*y
+            if arg.is_Rational:
+                return _sqrt(arg)
+            return sqrt(arg)
+    else:
+        from math import hypot
+
+    rv = [(0, 1)]
+    best_dist = hypot(p[1].x - p[0].x, p[1].y - p[0].y)
+    left = 0
+    box = deque([0, 1])
+    for i in range(2, len(p)):
+        while left < i and p[i][0] - p[left][0] > best_dist:
+            box.popleft()
+            left += 1
+
+        for j in box:
+            d = hypot(p[i].x - p[j].x, p[i].y - p[j].y)
+            if d < best_dist:
+                rv = [(j, i)]
+            elif d == best_dist:
+                rv.append((j, i))
+            else:
+                continue
+            best_dist = d
+        box.append(i)
+
+    return {tuple([p[i] for i in pair]) for pair in rv}
+
+
+def convex_hull(*args, polygon=True):
+    """The convex hull surrounding the Points contained in the list of entities.
+
+    Parameters
+    ==========
+
+    args : a collection of Points, Segments and/or Polygons
+
+    Optional parameters
+    ===================
+
+    polygon : Boolean. If True, returns a Polygon, if false a tuple, see below.
+              Default is True.
+
+    Returns
+    =======
+
+    convex_hull : Polygon if ``polygon`` is True else as a tuple `(U, L)` where
+                  ``L`` and ``U`` are the lower and upper hulls, respectively.
+
+    Notes
+    =====
+
+    This can only be performed on a set of points whose coordinates can
+    be ordered on the number line.
+
+    See Also
+    ========
+
+    sympy.geometry.point.Point, sympy.geometry.polygon.Polygon
+
+    Examples
+    ========
+
+    >>> from sympy import convex_hull
+    >>> points = [(1, 1), (1, 2), (3, 1), (-5, 2), (15, 4)]
+    >>> convex_hull(*points)
+    Polygon(Point2D(-5, 2), Point2D(1, 1), Point2D(3, 1), Point2D(15, 4))
+    >>> convex_hull(*points, **dict(polygon=False))
+    ([Point2D(-5, 2), Point2D(15, 4)],
+     [Point2D(-5, 2), Point2D(1, 1), Point2D(3, 1), Point2D(15, 4)])
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Graham_scan
+
+    .. [2] Andrew's Monotone Chain Algorithm
+      (A.M. Andrew,
+      "Another Efficient Algorithm for Convex Hulls in Two Dimensions", 1979)
+      https://web.archive.org/web/20210511015444/http://geomalgorithms.com/a10-_hull-1.html
+
+    """
+    from .line import Segment
+    from .polygon import Polygon
+    p = OrderedSet()
+    for e in args:
+        if not isinstance(e, GeometryEntity):
+            try:
+                e = Point(e)
+            except NotImplementedError:
+                raise ValueError('%s is not a GeometryEntity and cannot be made into Point' % str(e))
+        if isinstance(e, Point):
+            p.add(e)
+        elif isinstance(e, Segment):
+            p.update(e.points)
+        elif isinstance(e, Polygon):
+            p.update(e.vertices)
+        else:
+            raise NotImplementedError(
+                'Convex hull for %s not implemented.' % type(e))
+
+    # make sure all our points are of the same dimension
+    if any(len(x) != 2 for x in p):
+        raise ValueError('Can only compute the convex hull in two dimensions')
+
+    p = list(p)
+    if len(p) == 1:
+        return p[0] if polygon else (p[0], None)
+    elif len(p) == 2:
+        s = Segment(p[0], p[1])
+        return s if polygon else (s, None)
+
+    def _orientation(p, q, r):
+        '''Return positive if p-q-r are clockwise, neg if ccw, zero if
+        collinear.'''
+        return (q.y - p.y)*(r.x - p.x) - (q.x - p.x)*(r.y - p.y)
+
+    # scan to find upper and lower convex hulls of a set of 2d points.
+    U = []
+    L = []
+    try:
+        p.sort(key=lambda x: x.args)
+    except TypeError:
+        raise ValueError("The points could not be sorted.")
+    for p_i in p:
+        while len(U) > 1 and _orientation(U[-2], U[-1], p_i) <= 0:
+            U.pop()
+        while len(L) > 1 and _orientation(L[-2], L[-1], p_i) >= 0:
+            L.pop()
+        U.append(p_i)
+        L.append(p_i)
+    U.reverse()
+    convexHull = tuple(L + U[1:-1])
+
+    if len(convexHull) == 2:
+        s = Segment(convexHull[0], convexHull[1])
+        return s if polygon else (s, None)
+    if polygon:
+        return Polygon(*convexHull)
+    else:
+        U.reverse()
+        return (U, L)
+
+def farthest_points(*args):
+    """Return the subset of points from a set of points that were
+    the furthest apart from each other in the 2D plane.
+
+    Parameters
+    ==========
+
+    args
+        A collection of Points on 2D plane.
+
+    Notes
+    =====
+
+    This can only be performed on a set of points whose coordinates can
+    be ordered on the number line. If there are no ties then a single
+    pair of Points will be in the set.
+
+    Examples
+    ========
+
+    >>> from sympy.geometry import farthest_points, Triangle
+    >>> Triangle(sss=(3, 4, 5)).args
+    (Point2D(0, 0), Point2D(3, 0), Point2D(3, 4))
+    >>> farthest_points(*_)
+    {(Point2D(0, 0), Point2D(3, 4))}
+
+    References
+    ==========
+
+    .. [1] https://code.activestate.com/recipes/117225-convex-hull-and-diameter-of-2d-point-sets/
+
+    .. [2] Rotating Callipers Technique
+        https://en.wikipedia.org/wiki/Rotating_calipers
+
+    """
+
+    def rotatingCalipers(Points):
+        U, L = convex_hull(*Points, **{"polygon": False})
+
+        if L is None:
+            if isinstance(U, Point):
+                raise ValueError('At least two distinct points must be given.')
+            yield U.args
+        else:
+            i = 0
+            j = len(L) - 1
+            while i < len(U) - 1 or j > 0:
+                yield U[i], L[j]
+                # if all the way through one side of hull, advance the other side
+                if i == len(U) - 1:
+                    j -= 1
+                elif j == 0:
+                    i += 1
+                # still points left on both lists, compare slopes of next hull edges
+                # being careful to avoid divide-by-zero in slope calculation
+                elif (U[i+1].y - U[i].y) * (L[j].x - L[j-1].x) > \
+                        (L[j].y - L[j-1].y) * (U[i+1].x - U[i].x):
+                    i += 1
+                else:
+                    j -= 1
+
+    p = [Point2D(i) for i in set(args)]
+
+    if not all(i.is_Rational for j in p for i in j.args):
+        def hypot(x, y):
+            arg = x*x + y*y
+            if arg.is_Rational:
+                return _sqrt(arg)
+            return sqrt(arg)
+    else:
+        from math import hypot
+
+    rv = []
+    diam = 0
+    for pair in rotatingCalipers(args):
+        h, q = _ordered_points(pair)
+        d = hypot(h.x - q.x, h.y - q.y)
+        if d > diam:
+            rv = [(h, q)]
+        elif d == diam:
+            rv.append((h, q))
+        else:
+            continue
+        diam = d
+
+    return set(rv)
+
+
+def idiff(eq, y, x, n=1):
+    """Return ``dy/dx`` assuming that ``eq == 0``.
+
+    Parameters
+    ==========
+
+    y : the dependent variable or a list of dependent variables (with y first)
+    x : the variable that the derivative is being taken with respect to
+    n : the order of the derivative (default is 1)
+
+    Examples
+    ========
+
+    >>> from sympy.abc import x, y, a
+    >>> from sympy.geometry.util import idiff
+
+    >>> circ = x**2 + y**2 - 4
+    >>> idiff(circ, y, x)
+    -x/y
+    >>> idiff(circ, y, x, 2).simplify()
+    (-x**2 - y**2)/y**3
+
+    Here, ``a`` is assumed to be independent of ``x``:
+
+    >>> idiff(x + a + y, y, x)
+    -1
+
+    Now the x-dependence of ``a`` is made explicit by listing ``a`` after
+    ``y`` in a list.
+
+    >>> idiff(x + a + y, [y, a], x)
+    -Derivative(a, x) - 1
+
+    See Also
+    ========
+
+    sympy.core.function.Derivative: represents unevaluated derivatives
+    sympy.core.function.diff: explicitly differentiates wrt symbols
+
+    """
+    if is_sequence(y):
+        dep = set(y)
+        y = y[0]
+    elif isinstance(y, Symbol):
+        dep = {y}
+    elif isinstance(y, Function):
+        pass
+    else:
+        raise ValueError("expecting x-dependent symbol(s) or function(s) but got: %s" % y)
+
+    f = {s: Function(s.name)(x) for s in eq.free_symbols
+        if s != x and s in dep}
+
+    if isinstance(y, Symbol):
+        dydx = Function(y.name)(x).diff(x)
+    else:
+        dydx = y.diff(x)
+
+    eq = eq.subs(f)
+    derivs = {}
+    for i in range(n):
+        # equation will be linear in dydx, a*dydx + b, so dydx = -b/a
+        deq = eq.diff(x)
+        b = deq.xreplace({dydx: S.Zero})
+        a = (deq - b).xreplace({dydx: S.One})
+        yp = factor_terms(expand_mul(cancel((-b/a).subs(derivs)), deep=False))
+        if i == n - 1:
+            return yp.subs([(v, k) for k, v in f.items()])
+        derivs[dydx] = yp
+        eq = dydx - yp
+        dydx = dydx.diff(x)
+
+
+def intersection(*entities, pairwise=False, **kwargs):
+    """The intersection of a collection of GeometryEntity instances.
+
+    Parameters
+    ==========
+    entities : sequence of GeometryEntity
+    pairwise (keyword argument) : Can be either True or False
+
+    Returns
+    =======
+    intersection : list of GeometryEntity
+
+    Raises
+    ======
+    NotImplementedError
+        When unable to calculate intersection.
+
+    Notes
+    =====
+    The intersection of any geometrical entity with itself should return
+    a list with one item: the entity in question.
+    An intersection requires two or more entities. If only a single
+    entity is given then the function will return an empty list.
+    It is possible for `intersection` to miss intersections that one
+    knows exists because the required quantities were not fully
+    simplified internally.
+    Reals should be converted to Rationals, e.g. Rational(str(real_num))
+    or else failures due to floating point issues may result.
+
+    Case 1: When the keyword argument 'pairwise' is False (default value):
+    In this case, the function returns a list of intersections common to
+    all entities.
+
+    Case 2: When the keyword argument 'pairwise' is True:
+    In this case, the functions returns a list intersections that occur
+    between any pair of entities.
+
+    See Also
+    ========
+
+    sympy.geometry.entity.GeometryEntity.intersection
+
+    Examples
+    ========
+
+    >>> from sympy import Ray, Circle, intersection
+    >>> c = Circle((0, 1), 1)
+    >>> intersection(c, c.center)
+    []
+    >>> right = Ray((0, 0), (1, 0))
+    >>> up = Ray((0, 0), (0, 1))
+    >>> intersection(c, right, up)
+    [Point2D(0, 0)]
+    >>> intersection(c, right, up, pairwise=True)
+    [Point2D(0, 0), Point2D(0, 2)]
+    >>> left = Ray((1, 0), (0, 0))
+    >>> intersection(right, left)
+    [Segment2D(Point2D(0, 0), Point2D(1, 0))]
+
+    """
+    if len(entities) <= 1:
+        return []
+
+    entities = list(entities)
+    prec = None
+    for i, e in enumerate(entities):
+        if not isinstance(e, GeometryEntity):
+            # entities may be an immutable tuple
+            e = Point(e)
+        # convert to exact Rationals
+        d = {}
+        for f in e.atoms(Float):
+            prec = f._prec if prec is None else min(f._prec, prec)
+            d.setdefault(f, nsimplify(f, rational=True))
+        entities[i] = e.xreplace(d)
+
+    if not pairwise:
+        # find the intersection common to all objects
+        res = entities[0].intersection(entities[1])
+        for entity in entities[2:]:
+            newres = []
+            for x in res:
+                newres.extend(x.intersection(entity))
+            res = newres
+    else:
+        # find all pairwise intersections
+        ans = []
+        for j in range(len(entities)):
+            for k in range(j + 1, len(entities)):
+                ans.extend(intersection(entities[j], entities[k]))
+        res = list(ordered(set(ans)))
+
+    # convert back to Floats
+    if prec is not None:
+        p = prec_to_dps(prec)
+        res = [i.n(p) for i in res]
+    return res
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b3f043ada6222d79dd52fd28b035e2ea45c5683
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/__init__.py
@@ -0,0 +1,8 @@
+"""Helper module for setting up interactive SymPy sessions. """
+
+from .printing import init_printing
+from .session import init_session
+from .traversal import interactive_traversal
+
+
+__all__ = ['init_printing', 'init_session', 'interactive_traversal']
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ef9195ff1aafcf291855f9cbfd44a79092f34a1
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/__pycache__/printing.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/__pycache__/printing.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9947c843b8392b725f1153a6065ae07b2270386d
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/__pycache__/printing.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/__pycache__/session.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/__pycache__/session.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..41fbc8b2672711fc06ac7760c0f1e65720dd914d
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/__pycache__/session.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/__pycache__/traversal.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/__pycache__/traversal.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a0c8000408ff2ac769eff0c12f741b0935c58563
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/__pycache__/traversal.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/printing.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/printing.py
new file mode 100644
index 0000000000000000000000000000000000000000..2fcc73e3e96a5b7e25f7fc7ebf54a5781c3b15b9
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/printing.py
@@ -0,0 +1,532 @@
+"""Tools for setting up printing in interactive sessions. """
+
+from io import BytesIO
+
+from sympy.printing.latex import latex as default_latex
+from sympy.printing.preview import preview
+from sympy.utilities.misc import debug
+from sympy.printing.defaults import Printable
+from sympy.external import import_module
+
+
+def _init_python_printing(stringify_func, **settings):
+    """Setup printing in Python interactive session. """
+    import sys
+    import builtins
+
+    def _displayhook(arg):
+        """Python's pretty-printer display hook.
+
+           This function was adapted from:
+
+            https://www.python.org/dev/peps/pep-0217/
+
+        """
+        if arg is not None:
+            builtins._ = None
+            print(stringify_func(arg, **settings))
+            builtins._ = arg
+
+    sys.displayhook = _displayhook
+
+
+def _init_ipython_printing(ip, stringify_func, use_latex, euler, forecolor,
+                           backcolor, fontsize, latex_mode, print_builtin,
+                           latex_printer, scale, **settings):
+    """Setup printing in IPython interactive session. """
+    IPython = import_module("IPython", min_module_version="1.0")
+    try:
+        from IPython.lib.latextools import latex_to_png
+    except ImportError:
+        pass
+
+    # Guess best font color if none was given based on the ip.colors string.
+    # From the IPython documentation:
+    #   It has four case-insensitive values: 'nocolor', 'neutral', 'linux',
+    #   'lightbg'. The default is neutral, which should be legible on either
+    #   dark or light terminal backgrounds. linux is optimised for dark
+    #   backgrounds and lightbg for light ones.
+    if forecolor is None:
+        color = ip.colors.lower()
+        if color == 'lightbg':
+            forecolor = 'Black'
+        elif color == 'linux':
+            forecolor = 'White'
+        else:
+            # No idea, go with gray.
+            forecolor = 'Gray'
+        debug("init_printing: Automatic foreground color:", forecolor)
+
+    if use_latex == "svg":
+        extra_preamble = "\n\\special{color %s}" % forecolor
+    else:
+        extra_preamble = ""
+
+    imagesize = 'tight'
+    offset = "0cm,0cm"
+    resolution = round(150*scale)
+    dvi = r"-T %s -D %d -bg %s -fg %s -O %s" % (
+        imagesize, resolution, backcolor, forecolor, offset)
+    dvioptions = dvi.split()
+
+    svg_scale = 150/72*scale
+    dvioptions_svg = ["--no-fonts", "--scale={}".format(svg_scale)]
+
+    debug("init_printing: DVIOPTIONS:", dvioptions)
+    debug("init_printing: DVIOPTIONS_SVG:", dvioptions_svg)
+
+    latex = latex_printer or default_latex
+
+    def _print_plain(arg, p, cycle):
+        """caller for pretty, for use in IPython 0.11"""
+        if _can_print(arg):
+            p.text(stringify_func(arg))
+        else:
+            p.text(IPython.lib.pretty.pretty(arg))
+
+    def _preview_wrapper(o):
+        exprbuffer = BytesIO()
+        try:
+            preview(o, output='png', viewer='BytesIO', euler=euler,
+                    outputbuffer=exprbuffer, extra_preamble=extra_preamble,
+                    dvioptions=dvioptions, fontsize=fontsize)
+        except Exception as e:
+            # IPython swallows exceptions
+            debug("png printing:", "_preview_wrapper exception raised:",
+                  repr(e))
+            raise
+        return exprbuffer.getvalue()
+
+    def _svg_wrapper(o):
+        exprbuffer = BytesIO()
+        try:
+            preview(o, output='svg', viewer='BytesIO', euler=euler,
+                    outputbuffer=exprbuffer, extra_preamble=extra_preamble,
+                    dvioptions=dvioptions_svg, fontsize=fontsize)
+        except Exception as e:
+            # IPython swallows exceptions
+            debug("svg printing:", "_preview_wrapper exception raised:",
+                  repr(e))
+            raise
+        return exprbuffer.getvalue().decode('utf-8')
+
+    def _matplotlib_wrapper(o):
+        # mathtext can't render some LaTeX commands. For example, it can't
+        # render any LaTeX environments such as array or matrix. So here we
+        # ensure that if mathtext fails to render, we return None.
+        try:
+            try:
+                return latex_to_png(o, color=forecolor, scale=scale)
+            except TypeError: #  Old IPython version without color and scale
+                return latex_to_png(o)
+        except ValueError as e:
+            debug('matplotlib exception caught:', repr(e))
+            return None
+
+
+    # Hook methods for builtin SymPy printers
+    printing_hooks = ('_latex', '_sympystr', '_pretty', '_sympyrepr')
+
+
+    def _can_print(o):
+        """Return True if type o can be printed with one of the SymPy printers.
+
+        If o is a container type, this is True if and only if every element of
+        o can be printed in this way.
+        """
+
+        try:
+            # If you're adding another type, make sure you add it to printable_types
+            # later in this file as well
+
+            builtin_types = (list, tuple, set, frozenset)
+            if isinstance(o, builtin_types):
+                # If the object is a custom subclass with a custom str or
+                # repr, use that instead.
+                if (type(o).__str__ not in (i.__str__ for i in builtin_types) or
+                    type(o).__repr__ not in (i.__repr__ for i in builtin_types)):
+                    return False
+                return all(_can_print(i) for i in o)
+            elif isinstance(o, dict):
+                return all(_can_print(i) and _can_print(o[i]) for i in o)
+            elif isinstance(o, bool):
+                return False
+            elif isinstance(o, Printable):
+                # types known to SymPy
+                return True
+            elif any(hasattr(o, hook) for hook in printing_hooks):
+                # types which add support themselves
+                return True
+            elif isinstance(o, (float, int)) and print_builtin:
+                return True
+            return False
+        except RuntimeError:
+            return False
+            # This is in case maximum recursion depth is reached.
+            # Since RecursionError is for versions of Python 3.5+
+            # so this is to guard against RecursionError for older versions.
+
+    def _print_latex_png(o):
+        """
+        A function that returns a png rendered by an external latex
+        distribution, falling back to matplotlib rendering
+        """
+        if _can_print(o):
+            s = latex(o, mode=latex_mode, **settings)
+            if latex_mode == 'plain':
+                s = '$\\displaystyle %s$' % s
+            try:
+                return _preview_wrapper(s)
+            except RuntimeError as e:
+                debug('preview failed with:', repr(e),
+                      ' Falling back to matplotlib backend')
+                if latex_mode != 'inline':
+                    s = latex(o, mode='inline', **settings)
+                return _matplotlib_wrapper(s)
+
+    def _print_latex_svg(o):
+        """
+        A function that returns a svg rendered by an external latex
+        distribution, no fallback available.
+        """
+        if _can_print(o):
+            s = latex(o, mode=latex_mode, **settings)
+            if latex_mode == 'plain':
+                s = '$\\displaystyle %s$' % s
+            try:
+                return _svg_wrapper(s)
+            except RuntimeError as e:
+                debug('preview failed with:', repr(e),
+                      ' No fallback available.')
+
+    def _print_latex_matplotlib(o):
+        """
+        A function that returns a png rendered by mathtext
+        """
+        if _can_print(o):
+            s = latex(o, mode='inline', **settings)
+            return _matplotlib_wrapper(s)
+
+    def _print_latex_text(o):
+        """
+        A function to generate the latex representation of SymPy expressions.
+        """
+        if _can_print(o):
+            s = latex(o, mode=latex_mode, **settings)
+            if latex_mode == 'plain':
+                return '$\\displaystyle %s$' % s
+            return s
+
+    # Printable is our own type, so we handle it with methods instead of
+    # the approach required by builtin types. This allows downstream
+    # packages to override the methods in their own subclasses of Printable,
+    # which avoids the effects of gh-16002.
+    printable_types = [float, tuple, list, set, frozenset, dict, int]
+
+    plaintext_formatter = ip.display_formatter.formatters['text/plain']
+
+    # Exception to the rule above: IPython has better dispatching rules
+    # for plaintext printing (xref ipython/ipython#8938), and we can't
+    # use `_repr_pretty_` without hitting a recursion error in _print_plain.
+    for cls in printable_types + [Printable]:
+        plaintext_formatter.for_type(cls, _print_plain)
+
+    svg_formatter = ip.display_formatter.formatters['image/svg+xml']
+    if use_latex in ('svg', ):
+        debug("init_printing: using svg formatter")
+        for cls in printable_types:
+            svg_formatter.for_type(cls, _print_latex_svg)
+        Printable._repr_svg_ = _print_latex_svg
+    else:
+        debug("init_printing: not using any svg formatter")
+        for cls in printable_types:
+            # Better way to set this, but currently does not work in IPython
+            #png_formatter.for_type(cls, None)
+            if cls in svg_formatter.type_printers:
+                svg_formatter.type_printers.pop(cls)
+        Printable._repr_svg_ = Printable._repr_disabled
+
+    png_formatter = ip.display_formatter.formatters['image/png']
+    if use_latex in (True, 'png'):
+        debug("init_printing: using png formatter")
+        for cls in printable_types:
+            png_formatter.for_type(cls, _print_latex_png)
+        Printable._repr_png_ = _print_latex_png
+    elif use_latex == 'matplotlib':
+        debug("init_printing: using matplotlib formatter")
+        for cls in printable_types:
+            png_formatter.for_type(cls, _print_latex_matplotlib)
+        Printable._repr_png_ = _print_latex_matplotlib
+    else:
+        debug("init_printing: not using any png formatter")
+        for cls in printable_types:
+            # Better way to set this, but currently does not work in IPython
+            #png_formatter.for_type(cls, None)
+            if cls in png_formatter.type_printers:
+                png_formatter.type_printers.pop(cls)
+        Printable._repr_png_ = Printable._repr_disabled
+
+    latex_formatter = ip.display_formatter.formatters['text/latex']
+    if use_latex in (True, 'mathjax'):
+        debug("init_printing: using mathjax formatter")
+        for cls in printable_types:
+            latex_formatter.for_type(cls, _print_latex_text)
+        Printable._repr_latex_ = _print_latex_text
+    else:
+        debug("init_printing: not using text/latex formatter")
+        for cls in printable_types:
+            # Better way to set this, but currently does not work in IPython
+            #latex_formatter.for_type(cls, None)
+            if cls in latex_formatter.type_printers:
+                latex_formatter.type_printers.pop(cls)
+        Printable._repr_latex_ = Printable._repr_disabled
+
+def _is_ipython(shell):
+    """Is a shell instance an IPython shell?"""
+    # shortcut, so we don't import IPython if we don't have to
+    from sys import modules
+    if 'IPython' not in modules:
+        return False
+    try:
+        from IPython.core.interactiveshell import InteractiveShell
+    except ImportError:
+        # IPython < 0.11
+        try:
+            from IPython.iplib import InteractiveShell
+        except ImportError:
+            # Reaching this points means IPython has changed in a backward-incompatible way
+            # that we don't know about. Warn?
+            return False
+    return isinstance(shell, InteractiveShell)
+
+# Used by the doctester to override the default for no_global
+NO_GLOBAL = False
+
+def init_printing(pretty_print=True, order=None, use_unicode=None,
+                  use_latex=None, wrap_line=None, num_columns=None,
+                  no_global=False, ip=None, euler=False, forecolor=None,
+                  backcolor='Transparent', fontsize='10pt',
+                  latex_mode='plain', print_builtin=True,
+                  str_printer=None, pretty_printer=None,
+                  latex_printer=None, scale=1.0, **settings):
+    r"""
+    Initializes pretty-printer depending on the environment.
+
+    Parameters
+    ==========
+
+    pretty_print : bool, default=True
+        If ``True``, use :func:`~.pretty_print` to stringify or the provided pretty
+        printer; if ``False``, use :func:`~.sstrrepr` to stringify or the provided string
+        printer.
+    order : string or None, default='lex'
+        There are a few different settings for this parameter:
+        ``'lex'`` (default), which is lexographic order;
+        ``'grlex'``, which is graded lexographic order;
+        ``'grevlex'``, which is reversed graded lexographic order;
+        ``'old'``, which is used for compatibility reasons and for long expressions;
+        ``None``, which sets it to lex.
+    use_unicode : bool or None, default=None
+        If ``True``, use unicode characters;
+        if ``False``, do not use unicode characters;
+        if ``None``, make a guess based on the environment.
+    use_latex : string, bool, or None, default=None
+        If ``True``, use default LaTeX rendering in GUI interfaces (png and
+        mathjax);
+        if ``False``, do not use LaTeX rendering;
+        if ``None``, make a guess based on the environment;
+        if ``'png'``, enable LaTeX rendering with an external LaTeX compiler,
+        falling back to matplotlib if external compilation fails;
+        if ``'matplotlib'``, enable LaTeX rendering with matplotlib;
+        if ``'mathjax'``, enable LaTeX text generation, for example MathJax
+        rendering in IPython notebook or text rendering in LaTeX documents;
+        if ``'svg'``, enable LaTeX rendering with an external latex compiler,
+        no fallback
+    wrap_line : bool
+        If True, lines will wrap at the end; if False, they will not wrap
+        but continue as one line. This is only relevant if ``pretty_print`` is
+        True.
+    num_columns : int or None, default=None
+        If ``int``, number of columns before wrapping is set to num_columns; if
+        ``None``, number of columns before wrapping is set to terminal width.
+        This is only relevant if ``pretty_print`` is ``True``.
+    no_global : bool, default=False
+        If ``True``, the settings become system wide;
+        if ``False``, use just for this console/session.
+    ip : An interactive console
+        This can either be an instance of IPython,
+        or a class that derives from code.InteractiveConsole.
+    euler : bool, optional, default=False
+        Loads the euler package in the LaTeX preamble for handwritten style
+        fonts (https://www.ctan.org/pkg/euler).
+    forecolor : string or None, optional, default=None
+        DVI setting for foreground color. ``None`` means that either ``'Black'``,
+        ``'White'``, or ``'Gray'`` will be selected based on a guess of the IPython
+        terminal color setting. See notes.
+    backcolor : string, optional, default='Transparent'
+        DVI setting for background color. See notes.
+    fontsize : string or int, optional, default='10pt'
+        A font size to pass to the LaTeX documentclass function in the
+        preamble. Note that the options are limited by the documentclass.
+        Consider using scale instead.
+    latex_mode : string, optional, default='plain'
+        The mode used in the LaTeX printer. Can be one of:
+        ``{'inline'|'plain'|'equation'|'equation*'}``.
+    print_builtin : boolean, optional, default=True
+        If ``True`` then floats and integers will be printed. If ``False`` the
+        printer will only print SymPy types.
+    str_printer : function, optional, default=None
+        A custom string printer function. This should mimic
+        :func:`~.sstrrepr`.
+    pretty_printer : function, optional, default=None
+        A custom pretty printer. This should mimic :func:`~.pretty`.
+    latex_printer : function, optional, default=None
+        A custom LaTeX printer. This should mimic :func:`~.latex`.
+    scale : float, optional, default=1.0
+        Scale the LaTeX output when using the ``'png'`` or ``'svg'`` backends.
+        Useful for high dpi screens.
+    settings :
+        Any additional settings for the ``latex`` and ``pretty`` commands can
+        be used to fine-tune the output.
+
+    Examples
+    ========
+
+    >>> from sympy.interactive import init_printing
+    >>> from sympy import Symbol, sqrt
+    >>> from sympy.abc import x, y
+    >>> sqrt(5)
+    sqrt(5)
+    >>> init_printing(pretty_print=True) # doctest: +SKIP
+    >>> sqrt(5) # doctest: +SKIP
+      ___
+    \/ 5
+    >>> theta = Symbol('theta') # doctest: +SKIP
+    >>> init_printing(use_unicode=True) # doctest: +SKIP
+    >>> theta # doctest: +SKIP
+    \u03b8
+    >>> init_printing(use_unicode=False) # doctest: +SKIP
+    >>> theta # doctest: +SKIP
+    theta
+    >>> init_printing(order='lex') # doctest: +SKIP
+    >>> str(y + x + y**2 + x**2) # doctest: +SKIP
+    x**2 + x + y**2 + y
+    >>> init_printing(order='grlex') # doctest: +SKIP
+    >>> str(y + x + y**2 + x**2) # doctest: +SKIP
+    x**2 + x + y**2 + y
+    >>> init_printing(order='grevlex') # doctest: +SKIP
+    >>> str(y * x**2 + x * y**2) # doctest: +SKIP
+    x**2*y + x*y**2
+    >>> init_printing(order='old') # doctest: +SKIP
+    >>> str(x**2 + y**2 + x + y) # doctest: +SKIP
+    x**2 + x + y**2 + y
+    >>> init_printing(num_columns=10) # doctest: +SKIP
+    >>> x**2 + x + y**2 + y # doctest: +SKIP
+    x + y +
+    x**2 + y**2
+
+    Notes
+    =====
+
+    The foreground and background colors can be selected when using ``'png'`` or
+    ``'svg'`` LaTeX rendering. Note that before the ``init_printing`` command is
+    executed, the LaTeX rendering is handled by the IPython console and not SymPy.
+
+    The colors can be selected among the 68 standard colors known to ``dvips``,
+    for a list see [1]_. In addition, the background color can be
+    set to  ``'Transparent'`` (which is the default value).
+
+    When using the ``'Auto'`` foreground color, the guess is based on the
+    ``colors`` variable in the IPython console, see [2]_. Hence, if
+    that variable is set correctly in your IPython console, there is a high
+    chance that the output will be readable, although manual settings may be
+    needed.
+
+
+    References
+    ==========
+
+    .. [1] https://en.wikibooks.org/wiki/LaTeX/Colors#The_68_standard_colors_known_to_dvips
+
+    .. [2] https://ipython.readthedocs.io/en/stable/config/details.html#terminal-colors
+
+    See Also
+    ========
+
+    sympy.printing.latex
+    sympy.printing.pretty
+
+    """
+    import sys
+    from sympy.printing.printer import Printer
+
+    if pretty_print:
+        if pretty_printer is not None:
+            stringify_func = pretty_printer
+        else:
+            from sympy.printing import pretty as stringify_func
+    else:
+        if str_printer is not None:
+            stringify_func = str_printer
+        else:
+            from sympy.printing import sstrrepr as stringify_func
+
+    # Even if ip is not passed, double check that not in IPython shell
+    in_ipython = False
+    if ip is None:
+        try:
+            ip = get_ipython()
+        except NameError:
+            pass
+        else:
+            in_ipython = (ip is not None)
+
+    if ip and not in_ipython:
+        in_ipython = _is_ipython(ip)
+
+    if in_ipython and pretty_print:
+        try:
+            from IPython.terminal.interactiveshell import TerminalInteractiveShell
+            from code import InteractiveConsole
+        except ImportError:
+            pass
+        else:
+            # This will be True if we are in the qtconsole or notebook
+            if not isinstance(ip, (InteractiveConsole, TerminalInteractiveShell)) \
+                    and 'ipython-console' not in ''.join(sys.argv):
+                if use_unicode is None:
+                    debug("init_printing: Setting use_unicode to True")
+                    use_unicode = True
+                if use_latex is None:
+                    debug("init_printing: Setting use_latex to True")
+                    use_latex = True
+
+    if not NO_GLOBAL and not no_global:
+        Printer.set_global_settings(order=order, use_unicode=use_unicode,
+                                    wrap_line=wrap_line, num_columns=num_columns)
+    else:
+        _stringify_func = stringify_func
+
+        if pretty_print:
+            stringify_func = lambda expr, **settings: \
+                             _stringify_func(expr, order=order,
+                                             use_unicode=use_unicode,
+                                             wrap_line=wrap_line,
+                                             num_columns=num_columns,
+                                             **settings)
+        else:
+            stringify_func = \
+                lambda expr, **settings: _stringify_func(
+                    expr, order=order, **settings)
+
+    if in_ipython:
+        mode_in_settings = settings.pop("mode", None)
+        if mode_in_settings:
+            debug("init_printing: Mode is not able to be set due to internals"
+                  "of IPython printing")
+        _init_ipython_printing(ip, stringify_func, use_latex, euler,
+                               forecolor, backcolor, fontsize, latex_mode,
+                               print_builtin, latex_printer, scale,
+                               **settings)
+    else:
+        _init_python_printing(stringify_func, **settings)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/session.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/session.py
new file mode 100644
index 0000000000000000000000000000000000000000..348b0938d69e5e7ffa9510f7d9ac759eb6683b8f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/session.py
@@ -0,0 +1,463 @@
+"""Tools for setting up interactive sessions. """
+
+from sympy.external.gmpy import GROUND_TYPES
+from sympy.external.importtools import version_tuple
+
+from sympy.interactive.printing import init_printing
+
+from sympy.utilities.misc import ARCH
+
+preexec_source = """\
+from sympy import *
+x, y, z, t = symbols('x y z t')
+k, m, n = symbols('k m n', integer=True)
+f, g, h = symbols('f g h', cls=Function)
+init_printing()
+"""
+
+verbose_message = """\
+These commands were executed:
+%(source)s
+Documentation can be found at https://docs.sympy.org/%(version)s
+"""
+
+no_ipython = """\
+Could not locate IPython. Having IPython installed is greatly recommended.
+See http://ipython.scipy.org for more details. If you use Debian/Ubuntu,
+just install the 'ipython' package and start isympy again.
+"""
+
+
+def _make_message(ipython=True, quiet=False, source=None):
+    """Create a banner for an interactive session. """
+    from sympy import __version__ as sympy_version
+    from sympy import SYMPY_DEBUG
+
+    import sys
+    import os
+
+    if quiet:
+        return ""
+
+    python_version = "%d.%d.%d" % sys.version_info[:3]
+
+    if ipython:
+        shell_name = "IPython"
+    else:
+        shell_name = "Python"
+
+    info = ['ground types: %s' % GROUND_TYPES]
+
+    cache = os.getenv('SYMPY_USE_CACHE')
+
+    if cache is not None and cache.lower() == 'no':
+        info.append('cache: off')
+
+    if SYMPY_DEBUG:
+        info.append('debugging: on')
+
+    args = shell_name, sympy_version, python_version, ARCH, ', '.join(info)
+    message = "%s console for SymPy %s (Python %s-%s) (%s)\n" % args
+
+    if source is None:
+        source = preexec_source
+
+    _source = ""
+
+    for line in source.split('\n')[:-1]:
+        if not line:
+            _source += '\n'
+        else:
+            _source += '>>> ' + line + '\n'
+
+    doc_version = sympy_version
+    if 'dev' in doc_version:
+        doc_version = "dev"
+    else:
+        doc_version = "%s/" % doc_version
+
+    message += '\n' + verbose_message % {'source': _source,
+                                         'version': doc_version}
+
+    return message
+
+
+def int_to_Integer(s):
+    """
+    Wrap integer literals with Integer.
+
+    This is based on the decistmt example from
+    https://docs.python.org/3/library/tokenize.html.
+
+    Only integer literals are converted.  Float literals are left alone.
+
+    Examples
+    ========
+
+    >>> from sympy import Integer # noqa: F401
+    >>> from sympy.interactive.session import int_to_Integer
+    >>> s = '1.2 + 1/2 - 0x12 + a1'
+    >>> int_to_Integer(s)
+    '1.2 +Integer (1 )/Integer (2 )-Integer (0x12 )+a1 '
+    >>> s = 'print (1/2)'
+    >>> int_to_Integer(s)
+    'print (Integer (1 )/Integer (2 ))'
+    >>> exec(s)
+    0.5
+    >>> exec(int_to_Integer(s))
+    1/2
+    """
+    from tokenize import generate_tokens, untokenize, NUMBER, NAME, OP
+    from io import StringIO
+
+    def _is_int(num):
+        """
+        Returns true if string value num (with token NUMBER) represents an integer.
+        """
+        # XXX: Is there something in the standard library that will do this?
+        if '.' in num or 'j' in num.lower() or 'e' in num.lower():
+            return False
+        return True
+
+    result = []
+    g = generate_tokens(StringIO(s).readline)  # tokenize the string
+    for toknum, tokval, _, _, _ in g:
+        if toknum == NUMBER and _is_int(tokval):  # replace NUMBER tokens
+            result.extend([
+                (NAME, 'Integer'),
+                (OP, '('),
+                (NUMBER, tokval),
+                (OP, ')')
+            ])
+        else:
+            result.append((toknum, tokval))
+    return untokenize(result)
+
+
+def enable_automatic_int_sympification(shell):
+    """
+    Allow IPython to automatically convert integer literals to Integer.
+    """
+    import ast
+    old_run_cell = shell.run_cell
+
+    def my_run_cell(cell, *args, **kwargs):
+        try:
+            # Check the cell for syntax errors.  This way, the syntax error
+            # will show the original input, not the transformed input.  The
+            # downside here is that IPython magic like %timeit will not work
+            # with transformed input (but on the other hand, IPython magic
+            # that doesn't expect transformed input will continue to work).
+            ast.parse(cell)
+        except SyntaxError:
+            pass
+        else:
+            cell = int_to_Integer(cell)
+        return old_run_cell(cell, *args, **kwargs)
+
+    shell.run_cell = my_run_cell
+
+
+def enable_automatic_symbols(shell):
+    """Allow IPython to automatically create symbols (``isympy -a``). """
+    # XXX: This should perhaps use tokenize, like int_to_Integer() above.
+    # This would avoid re-executing the code, which can lead to subtle
+    # issues.  For example:
+    #
+    # In [1]: a = 1
+    #
+    # In [2]: for i in range(10):
+    #    ...:     a += 1
+    #    ...:
+    #
+    # In [3]: a
+    # Out[3]: 11
+    #
+    # In [4]: a = 1
+    #
+    # In [5]: for i in range(10):
+    #    ...:     a += 1
+    #    ...:     print b
+    #    ...:
+    # b
+    # b
+    # b
+    # b
+    # b
+    # b
+    # b
+    # b
+    # b
+    # b
+    #
+    # In [6]: a
+    # Out[6]: 12
+    #
+    # Note how the for loop is executed again because `b` was not defined, but `a`
+    # was already incremented once, so the result is that it is incremented
+    # multiple times.
+
+    import re
+    re_nameerror = re.compile(
+        "name '(?P[A-Za-z_][A-Za-z0-9_]*)' is not defined")
+
+    def _handler(self, etype, value, tb, tb_offset=None):
+        """Handle :exc:`NameError` exception and allow injection of missing symbols. """
+        if etype is NameError and tb.tb_next and not tb.tb_next.tb_next:
+            match = re_nameerror.match(str(value))
+
+            if match is not None:
+                # XXX: Make sure Symbol is in scope. Otherwise you'll get infinite recursion.
+                self.run_cell("%(symbol)s = Symbol('%(symbol)s')" %
+                              {'symbol': match.group("symbol")}, store_history=False)
+
+                try:
+                    code = self.user_ns['In'][-1]
+                except (KeyError, IndexError):
+                    pass
+                else:
+                    self.run_cell(code, store_history=False)
+                    return None
+                finally:
+                    self.run_cell("del %s" % match.group("symbol"),
+                                  store_history=False)
+
+        stb = self.InteractiveTB.structured_traceback(
+            etype, value, tb, tb_offset=tb_offset)
+        self._showtraceback(etype, value, stb)
+
+    shell.set_custom_exc((NameError,), _handler)
+
+
+def init_ipython_session(shell=None, argv=[], auto_symbols=False, auto_int_to_Integer=False):
+    """Construct new IPython session. """
+    import IPython
+
+    if version_tuple(IPython.__version__) >= version_tuple('0.11'):
+        if not shell:
+            # use an app to parse the command line, and init config
+            # IPython 1.0 deprecates the frontend module, so we import directly
+            # from the terminal module to prevent a deprecation message from being
+            # shown.
+            if version_tuple(IPython.__version__) >= version_tuple('1.0'):
+                from IPython.terminal import ipapp
+            else:
+                from IPython.frontend.terminal import ipapp
+            app = ipapp.TerminalIPythonApp()
+
+            # don't draw IPython banner during initialization:
+            app.display_banner = False
+            app.initialize(argv)
+
+            shell = app.shell
+
+        if auto_symbols:
+            enable_automatic_symbols(shell)
+        if auto_int_to_Integer:
+            enable_automatic_int_sympification(shell)
+
+        return shell
+    else:
+        from IPython.Shell import make_IPython
+        return make_IPython(argv)
+
+
+def init_python_session():
+    """Construct new Python session. """
+    from code import InteractiveConsole
+
+    class SymPyConsole(InteractiveConsole):
+        """An interactive console with readline support. """
+
+        def __init__(self):
+            ns_locals = {}
+            InteractiveConsole.__init__(self, locals=ns_locals)
+            try:
+                import rlcompleter
+                import readline
+            except ImportError:
+                pass
+            else:
+                import os
+                import atexit
+
+                readline.set_completer(rlcompleter.Completer(ns_locals).complete)
+                readline.parse_and_bind('tab: complete')
+
+                if hasattr(readline, 'read_history_file'):
+                    history = os.path.expanduser('~/.sympy-history')
+
+                    try:
+                        readline.read_history_file(history)
+                    except OSError:
+                        pass
+
+                    atexit.register(readline.write_history_file, history)
+
+    return SymPyConsole()
+
+
+def init_session(ipython=None, pretty_print=True, order=None,
+                 use_unicode=None, use_latex=None, quiet=False, auto_symbols=False,
+                 auto_int_to_Integer=False, str_printer=None, pretty_printer=None,
+                 latex_printer=None, argv=[]):
+    """
+    Initialize an embedded IPython or Python session. The IPython session is
+    initiated with the --pylab option, without the numpy imports, so that
+    matplotlib plotting can be interactive.
+
+    Parameters
+    ==========
+
+    pretty_print: boolean
+        If True, use pretty_print to stringify;
+        if False, use sstrrepr to stringify.
+    order: string or None
+        There are a few different settings for this parameter:
+        lex (default), which is lexographic order;
+        grlex, which is graded lexographic order;
+        grevlex, which is reversed graded lexographic order;
+        old, which is used for compatibility reasons and for long expressions;
+        None, which sets it to lex.
+    use_unicode: boolean or None
+        If True, use unicode characters;
+        if False, do not use unicode characters.
+    use_latex: boolean or None
+        If True, use latex rendering if IPython GUI's;
+        if False, do not use latex rendering.
+    quiet: boolean
+        If True, init_session will not print messages regarding its status;
+        if False, init_session will print messages regarding its status.
+    auto_symbols: boolean
+        If True, IPython will automatically create symbols for you.
+        If False, it will not.
+        The default is False.
+    auto_int_to_Integer: boolean
+        If True, IPython will automatically wrap int literals with Integer, so
+        that things like 1/2 give Rational(1, 2).
+        If False, it will not.
+        The default is False.
+    ipython: boolean or None
+        If True, printing will initialize for an IPython console;
+        if False, printing will initialize for a normal console;
+        The default is None, which automatically determines whether we are in
+        an ipython instance or not.
+    str_printer: function, optional, default=None
+        A custom string printer function. This should mimic
+        sympy.printing.sstrrepr().
+    pretty_printer: function, optional, default=None
+        A custom pretty printer. This should mimic sympy.printing.pretty().
+    latex_printer: function, optional, default=None
+        A custom LaTeX printer. This should mimic sympy.printing.latex()
+        This should mimic sympy.printing.latex().
+    argv: list of arguments for IPython
+        See sympy.bin.isympy for options that can be used to initialize IPython.
+
+    See Also
+    ========
+
+    sympy.interactive.printing.init_printing: for examples and the rest of the parameters.
+
+
+    Examples
+    ========
+
+    >>> from sympy import init_session, Symbol, sin, sqrt
+    >>> sin(x) #doctest: +SKIP
+    NameError: name 'x' is not defined
+    >>> init_session() #doctest: +SKIP
+    >>> sin(x) #doctest: +SKIP
+    sin(x)
+    >>> sqrt(5) #doctest: +SKIP
+      ___
+    \\/ 5
+    >>> init_session(pretty_print=False) #doctest: +SKIP
+    >>> sqrt(5) #doctest: +SKIP
+    sqrt(5)
+    >>> y + x + y**2 + x**2 #doctest: +SKIP
+    x**2 + x + y**2 + y
+    >>> init_session(order='grlex') #doctest: +SKIP
+    >>> y + x + y**2 + x**2 #doctest: +SKIP
+    x**2 + y**2 + x + y
+    >>> init_session(order='grevlex') #doctest: +SKIP
+    >>> y * x**2 + x * y**2 #doctest: +SKIP
+    x**2*y + x*y**2
+    >>> init_session(order='old') #doctest: +SKIP
+    >>> x**2 + y**2 + x + y #doctest: +SKIP
+    x + y + x**2 + y**2
+    >>> theta = Symbol('theta') #doctest: +SKIP
+    >>> theta #doctest: +SKIP
+    theta
+    >>> init_session(use_unicode=True) #doctest: +SKIP
+    >>> theta # doctest: +SKIP
+    \u03b8
+    """
+    import sys
+
+    in_ipython = False
+
+    if ipython is not False:
+        try:
+            import IPython
+        except ImportError:
+            if ipython is True:
+                raise RuntimeError("IPython is not available on this system")
+            ip = None
+        else:
+            try:
+                from IPython import get_ipython
+                ip = get_ipython()
+            except ImportError:
+                ip = None
+        in_ipython = bool(ip)
+        if ipython is None:
+            ipython = in_ipython
+
+    if ipython is False:
+        ip = init_python_session()
+        mainloop = ip.interact
+    else:
+        ip = init_ipython_session(ip, argv=argv, auto_symbols=auto_symbols,
+                                  auto_int_to_Integer=auto_int_to_Integer)
+
+        if version_tuple(IPython.__version__) >= version_tuple('0.11'):
+            # runsource is gone, use run_cell instead, which doesn't
+            # take a symbol arg.  The second arg is `store_history`,
+            # and False means don't add the line to IPython's history.
+            ip.runsource = lambda src, symbol='exec': ip.run_cell(src, False)
+
+            # Enable interactive plotting using pylab.
+            try:
+                ip.enable_pylab(import_all=False)
+            except Exception:
+                # Causes an import error if matplotlib is not installed.
+                # Causes other errors (depending on the backend) if there
+                # is no display, or if there is some problem in the
+                # backend, so we have a bare "except Exception" here
+                pass
+        if not in_ipython:
+            mainloop = ip.mainloop
+
+    if auto_symbols and (not ipython or version_tuple(IPython.__version__) < version_tuple('0.11')):
+        raise RuntimeError("automatic construction of symbols is possible only in IPython 0.11 or above")
+    if auto_int_to_Integer and (not ipython or version_tuple(IPython.__version__) < version_tuple('0.11')):
+        raise RuntimeError("automatic int to Integer transformation is possible only in IPython 0.11 or above")
+
+    _preexec_source = preexec_source
+
+    ip.runsource(_preexec_source, symbol='exec')
+    init_printing(pretty_print=pretty_print, order=order,
+                  use_unicode=use_unicode, use_latex=use_latex, ip=ip,
+                  str_printer=str_printer, pretty_printer=pretty_printer,
+                  latex_printer=latex_printer)
+
+    message = _make_message(ipython, quiet, _preexec_source)
+
+    if not in_ipython:
+        print(message)
+        mainloop()
+        sys.exit('Exiting ...')
+    else:
+        print(message)
+        import atexit
+        atexit.register(lambda: print("Exiting ...\n"))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/tests/test_interactive.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/tests/test_interactive.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e088c42fd872c13849e593b04734158f5d1e5bc
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/tests/test_interactive.py
@@ -0,0 +1,10 @@
+from sympy.interactive.session import int_to_Integer
+
+
+def test_int_to_Integer():
+    assert int_to_Integer("1 + 2.2 + 0x3 + 40") == \
+        'Integer (1 )+2.2 +Integer (0x3 )+Integer (40 )'
+    assert int_to_Integer("0b101") == 'Integer (0b101 )'
+    assert int_to_Integer("ab1 + 1 + '1 + 2'") == "ab1 +Integer (1 )+'1 + 2'"
+    assert int_to_Integer("(2 + \n3)") == '(Integer (2 )+\nInteger (3 ))'
+    assert int_to_Integer("2 + 2.0 + 2j + 2e-10") == 'Integer (2 )+2.0 +2j +2e-10 '
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/tests/test_ipython.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/tests/test_ipython.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac4734406d2f1197732a9dcbdd94b2b34e9fe170
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/tests/test_ipython.py
@@ -0,0 +1,278 @@
+"""Tests of tools for setting up interactive IPython sessions. """
+
+from sympy.interactive.session import (init_ipython_session,
+    enable_automatic_symbols, enable_automatic_int_sympification)
+
+from sympy.core import Symbol, Rational, Integer
+from sympy.external import import_module
+from sympy.testing.pytest import raises
+
+# TODO: The code below could be made more granular with something like:
+#
+# @requires('IPython', version=">=1.0")
+# def test_automatic_symbols(ipython):
+
+ipython = import_module("IPython", min_module_version="1.0")
+
+if not ipython:
+    #bin/test will not execute any tests now
+    disabled = True
+
+# WARNING: These tests will modify the existing IPython environment. IPython
+# uses a single instance for its interpreter, so there is no way to isolate
+# the test from another IPython session. It also means that if this test is
+# run twice in the same Python session it will fail. This isn't usually a
+# problem because the test suite is run in a subprocess by default, but if the
+# tests are run with subprocess=False it can pollute the current IPython
+# session. See the discussion in issue #15149.
+
+def test_automatic_symbols():
+    # NOTE: Because of the way the hook works, you have to use run_cell(code,
+    # True).  This means that the code must have no Out, or it will be printed
+    # during the tests.
+    app = init_ipython_session()
+    app.run_cell("from sympy import *")
+
+    enable_automatic_symbols(app)
+
+    symbol = "verylongsymbolname"
+    assert symbol not in app.user_ns
+    app.run_cell("a = %s" % symbol, True)
+    assert symbol not in app.user_ns
+    app.run_cell("a = type(%s)" % symbol, True)
+    assert app.user_ns['a'] == Symbol
+    app.run_cell("%s = Symbol('%s')" % (symbol, symbol), True)
+    assert symbol in app.user_ns
+
+    # Check that built-in names aren't overridden
+    app.run_cell("a = all == __builtin__.all", True)
+    assert "all" not in app.user_ns
+    assert app.user_ns['a'] is True
+
+    # Check that SymPy names aren't overridden
+    app.run_cell("import sympy")
+    app.run_cell("a = factorial == sympy.factorial", True)
+    assert app.user_ns['a'] is True
+
+
+def test_int_to_Integer():
+    # XXX: Warning, don't test with == here.  0.5 == Rational(1, 2) is True!
+    app = init_ipython_session()
+    app.run_cell("from sympy import Integer")
+    app.run_cell("a = 1")
+    assert isinstance(app.user_ns['a'], int)
+
+    enable_automatic_int_sympification(app)
+    app.run_cell("a = 1/2")
+    assert isinstance(app.user_ns['a'], Rational)
+    app.run_cell("a = 1")
+    assert isinstance(app.user_ns['a'], Integer)
+    app.run_cell("a = int(1)")
+    assert isinstance(app.user_ns['a'], int)
+    app.run_cell("a = (1/\n2)")
+    assert app.user_ns['a'] == Rational(1, 2)
+    # TODO: How can we test that the output of a SyntaxError is the original
+    # input, not the transformed input?
+
+
+def test_ipythonprinting():
+    # Initialize and setup IPython session
+    app = init_ipython_session()
+    app.run_cell("ip = get_ipython()")
+    app.run_cell("inst = ip.instance()")
+    app.run_cell("format = inst.display_formatter.format")
+    app.run_cell("from sympy import Symbol")
+
+    # Printing without printing extension
+    app.run_cell("a = format(Symbol('pi'))")
+    app.run_cell("a2 = format(Symbol('pi')**2)")
+    # Deal with API change starting at IPython 1.0
+    if int(ipython.__version__.split(".")[0]) < 1:
+        assert app.user_ns['a']['text/plain'] == "pi"
+        assert app.user_ns['a2']['text/plain'] == "pi**2"
+    else:
+        assert app.user_ns['a'][0]['text/plain'] == "pi"
+        assert app.user_ns['a2'][0]['text/plain'] == "pi**2"
+
+    # Load printing extension
+    app.run_cell("from sympy import init_printing")
+    app.run_cell("init_printing()")
+    # Printing with printing extension
+    app.run_cell("a = format(Symbol('pi'))")
+    app.run_cell("a2 = format(Symbol('pi')**2)")
+    # Deal with API change starting at IPython 1.0
+    if int(ipython.__version__.split(".")[0]) < 1:
+        assert app.user_ns['a']['text/plain'] in ('\N{GREEK SMALL LETTER PI}', 'pi')
+        assert app.user_ns['a2']['text/plain'] in (' 2\n\N{GREEK SMALL LETTER PI} ', '  2\npi ')
+    else:
+        assert app.user_ns['a'][0]['text/plain'] in ('\N{GREEK SMALL LETTER PI}', 'pi')
+        assert app.user_ns['a2'][0]['text/plain'] in (' 2\n\N{GREEK SMALL LETTER PI} ', '  2\npi ')
+
+
+def test_print_builtin_option():
+    # Initialize and setup IPython session
+    app = init_ipython_session()
+    app.run_cell("ip = get_ipython()")
+    app.run_cell("inst = ip.instance()")
+    app.run_cell("format = inst.display_formatter.format")
+    app.run_cell("from sympy import Symbol")
+    app.run_cell("from sympy import init_printing")
+
+    app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
+    # Deal with API change starting at IPython 1.0
+    if int(ipython.__version__.split(".")[0]) < 1:
+        text = app.user_ns['a']['text/plain']
+        raises(KeyError, lambda: app.user_ns['a']['text/latex'])
+    else:
+        text = app.user_ns['a'][0]['text/plain']
+        raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])
+    # XXX: How can we make this ignore the terminal width? This test fails if
+    # the terminal is too narrow.
+    assert text in ("{pi: 3.14, n_i: 3}",
+                    '{n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3, \N{GREEK SMALL LETTER PI}: 3.14}',
+                    "{n_i: 3, pi: 3.14}",
+                    '{\N{GREEK SMALL LETTER PI}: 3.14, n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3}')
+
+    # If we enable the default printing, then the dictionary's should render
+    # as a LaTeX version of the whole dict: ${\pi: 3.14, n_i: 3}$
+    app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
+    app.run_cell("init_printing(use_latex=True)")
+    app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
+    # Deal with API change starting at IPython 1.0
+    if int(ipython.__version__.split(".")[0]) < 1:
+        text = app.user_ns['a']['text/plain']
+        latex = app.user_ns['a']['text/latex']
+    else:
+        text = app.user_ns['a'][0]['text/plain']
+        latex = app.user_ns['a'][0]['text/latex']
+    assert text in ("{pi: 3.14, n_i: 3}",
+                    '{n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3, \N{GREEK SMALL LETTER PI}: 3.14}',
+                    "{n_i: 3, pi: 3.14}",
+                    '{\N{GREEK SMALL LETTER PI}: 3.14, n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3}')
+    assert latex == r'$\displaystyle \left\{ n_{i} : 3, \  \pi : 3.14\right\}$'
+
+    # Objects with an _latex overload should also be handled by our tuple
+    # printer.
+    app.run_cell("""\
+    class WithOverload:
+        def _latex(self, printer):
+            return r"\\LaTeX"
+    """)
+    app.run_cell("a = format((WithOverload(),))")
+    # Deal with API change starting at IPython 1.0
+    if int(ipython.__version__.split(".")[0]) < 1:
+        latex = app.user_ns['a']['text/latex']
+    else:
+        latex = app.user_ns['a'][0]['text/latex']
+    assert latex == r'$\displaystyle \left( \LaTeX,\right)$'
+
+    app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
+    app.run_cell("init_printing(use_latex=True, print_builtin=False)")
+    app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
+    # Deal with API change starting at IPython 1.0
+    if int(ipython.__version__.split(".")[0]) < 1:
+        text = app.user_ns['a']['text/plain']
+        raises(KeyError, lambda: app.user_ns['a']['text/latex'])
+    else:
+        text = app.user_ns['a'][0]['text/plain']
+        raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])
+    # Note : In Python 3 we have one text type: str which holds Unicode data
+    # and two byte types bytes and bytearray.
+    # Python 3.3.3 + IPython 0.13.2 gives: '{n_i: 3, pi: 3.14}'
+    # Python 3.3.3 + IPython 1.1.0 gives: '{n_i: 3, pi: 3.14}'
+    assert text in ("{pi: 3.14, n_i: 3}", "{n_i: 3, pi: 3.14}")
+
+
+def test_builtin_containers():
+    # Initialize and setup IPython session
+    app = init_ipython_session()
+    app.run_cell("ip = get_ipython()")
+    app.run_cell("inst = ip.instance()")
+    app.run_cell("format = inst.display_formatter.format")
+    app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
+    app.run_cell("from sympy import init_printing, Matrix")
+    app.run_cell('init_printing(use_latex=True, use_unicode=False)')
+
+    # Make sure containers that shouldn't pretty print don't.
+    app.run_cell('a = format((True, False))')
+    app.run_cell('import sys')
+    app.run_cell('b = format(sys.flags)')
+    app.run_cell('c = format((Matrix([1, 2]),))')
+    # Deal with API change starting at IPython 1.0
+    if int(ipython.__version__.split(".")[0]) < 1:
+        assert app.user_ns['a']['text/plain'] ==  '(True, False)'
+        assert 'text/latex' not in app.user_ns['a']
+        assert app.user_ns['b']['text/plain'][:10] == 'sys.flags('
+        assert 'text/latex' not in app.user_ns['b']
+        assert app.user_ns['c']['text/plain'] == \
+"""\
+ [1]  \n\
+([ ],)
+ [2]  \
+"""
+        assert app.user_ns['c']['text/latex'] == '$\\displaystyle \\left( \\left[\\begin{matrix}1\\\\2\\end{matrix}\\right],\\right)$'
+    else:
+        assert app.user_ns['a'][0]['text/plain'] ==  '(True, False)'
+        assert 'text/latex' not in app.user_ns['a'][0]
+        assert app.user_ns['b'][0]['text/plain'][:10] == 'sys.flags('
+        assert 'text/latex' not in app.user_ns['b'][0]
+        assert app.user_ns['c'][0]['text/plain'] == \
+"""\
+ [1]  \n\
+([ ],)
+ [2]  \
+"""
+        assert app.user_ns['c'][0]['text/latex'] == '$\\displaystyle \\left( \\left[\\begin{matrix}1\\\\2\\end{matrix}\\right],\\right)$'
+
+def test_matplotlib_bad_latex():
+    # Initialize and setup IPython session
+    app = init_ipython_session()
+    app.run_cell("import IPython")
+    app.run_cell("ip = get_ipython()")
+    app.run_cell("inst = ip.instance()")
+    app.run_cell("format = inst.display_formatter.format")
+    app.run_cell("from sympy import init_printing, Matrix")
+    app.run_cell("init_printing(use_latex='matplotlib')")
+
+    # The png formatter is not enabled by default in this context
+    app.run_cell("inst.display_formatter.formatters['image/png'].enabled = True")
+
+    # Make sure no warnings are raised by IPython
+    app.run_cell("import warnings")
+    # IPython.core.formatters.FormatterWarning was introduced in IPython 2.0
+    if int(ipython.__version__.split(".")[0]) < 2:
+        app.run_cell("warnings.simplefilter('error')")
+    else:
+        app.run_cell("warnings.simplefilter('error', IPython.core.formatters.FormatterWarning)")
+
+    # This should not raise an exception
+    app.run_cell("a = format(Matrix([1, 2, 3]))")
+
+    # issue 9799
+    app.run_cell("from sympy import Piecewise, Symbol, Eq")
+    app.run_cell("x = Symbol('x'); pw = format(Piecewise((1, Eq(x, 0)), (0, True)))")
+
+
+def test_override_repr_latex():
+    # Initialize and setup IPython session
+    app = init_ipython_session()
+    app.run_cell("import IPython")
+    app.run_cell("ip = get_ipython()")
+    app.run_cell("inst = ip.instance()")
+    app.run_cell("format = inst.display_formatter.format")
+    app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
+    app.run_cell("from sympy import init_printing")
+    app.run_cell("from sympy import Symbol")
+    app.run_cell("init_printing(use_latex=True)")
+    app.run_cell("""\
+    class SymbolWithOverload(Symbol):
+        def _repr_latex_(self):
+            return r"Hello " + super()._repr_latex_() + " world"
+    """)
+    app.run_cell("a = format(SymbolWithOverload('s'))")
+
+    if int(ipython.__version__.split(".")[0]) < 1:
+        latex = app.user_ns['a']['text/latex']
+    else:
+        latex = app.user_ns['a'][0]['text/latex']
+    assert latex == r'Hello $\displaystyle s$ world'
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/traversal.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/traversal.py
new file mode 100644
index 0000000000000000000000000000000000000000..1315ec4ef7868b666bb6b978b3d8b20442d100b0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/interactive/traversal.py
@@ -0,0 +1,95 @@
+from sympy.core.basic import Basic
+from sympy.printing import pprint
+
+import random
+
+def interactive_traversal(expr):
+    """Traverse a tree asking a user which branch to choose. """
+
+    RED, BRED = '\033[0;31m', '\033[1;31m'
+    GREEN, BGREEN = '\033[0;32m', '\033[1;32m'
+    YELLOW, BYELLOW = '\033[0;33m', '\033[1;33m'  # noqa
+    BLUE, BBLUE = '\033[0;34m', '\033[1;34m'      # noqa
+    MAGENTA, BMAGENTA = '\033[0;35m', '\033[1;35m'# noqa
+    CYAN, BCYAN = '\033[0;36m', '\033[1;36m'      # noqa
+    END = '\033[0m'
+
+    def cprint(*args):
+        print("".join(map(str, args)) + END)
+
+    def _interactive_traversal(expr, stage):
+        if stage > 0:
+            print()
+
+        cprint("Current expression (stage ", BYELLOW, stage, END, "):")
+        print(BCYAN)
+        pprint(expr)
+        print(END)
+
+        if isinstance(expr, Basic):
+            if expr.is_Add:
+                args = expr.as_ordered_terms()
+            elif expr.is_Mul:
+                args = expr.as_ordered_factors()
+            else:
+                args = expr.args
+        elif hasattr(expr, "__iter__"):
+            args = list(expr)
+        else:
+            return expr
+
+        n_args = len(args)
+
+        if not n_args:
+            return expr
+
+        for i, arg in enumerate(args):
+            cprint(GREEN, "[", BGREEN, i, GREEN, "] ", BLUE, type(arg), END)
+            pprint(arg)
+            print()
+
+        if n_args == 1:
+            choices = '0'
+        else:
+            choices = '0-%d' % (n_args - 1)
+
+        try:
+            choice = input("Your choice [%s,f,l,r,d,?]: " % choices)
+        except EOFError:
+            result = expr
+            print()
+        else:
+            if choice == '?':
+                cprint(RED, "%s - select subexpression with the given index" %
+                       choices)
+                cprint(RED, "f - select the first subexpression")
+                cprint(RED, "l - select the last subexpression")
+                cprint(RED, "r - select a random subexpression")
+                cprint(RED, "d - done\n")
+
+                result = _interactive_traversal(expr, stage)
+            elif choice in ('d', ''):
+                result = expr
+            elif choice == 'f':
+                result = _interactive_traversal(args[0], stage + 1)
+            elif choice == 'l':
+                result = _interactive_traversal(args[-1], stage + 1)
+            elif choice == 'r':
+                result = _interactive_traversal(random.choice(args), stage + 1)
+            else:
+                try:
+                    choice = int(choice)
+                except ValueError:
+                    cprint(BRED,
+                           "Choice must be a number in %s range\n" % choices)
+                    result = _interactive_traversal(expr, stage)
+                else:
+                    if choice < 0 or choice >= n_args:
+                        cprint(BRED, "Choice must be in %s range\n" % choices)
+                        result = _interactive_traversal(expr, stage)
+                    else:
+                        result = _interactive_traversal(args[choice], stage + 1)
+
+        return result
+
+    return _interactive_traversal(expr, 0)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d023d86f2c6f0c64d7ac460c50eedc355e78b21f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/__init__.py
@@ -0,0 +1,3 @@
+from sympy.liealgebras.cartan_type import CartanType
+
+__all__ = ['CartanType']
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/cartan_matrix.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/cartan_matrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d29b37bc9a1a26790ee88b5902951afe4fc4560
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/cartan_matrix.py
@@ -0,0 +1,25 @@
+from .cartan_type import CartanType
+
+def CartanMatrix(ct):
+    """Access the Cartan matrix of a specific Lie algebra
+
+    Examples
+    ========
+
+    >>> from sympy.liealgebras.cartan_matrix import CartanMatrix
+    >>> CartanMatrix("A2")
+    Matrix([
+    [ 2, -1],
+    [-1,  2]])
+
+    >>> CartanMatrix(['C', 3])
+    Matrix([
+    [ 2, -1,  0],
+    [-1,  2, -1],
+    [ 0, -2,  2]])
+
+    This method works by returning the Cartan matrix
+    which corresponds to Cartan type t.
+    """
+
+    return CartanType(ct).cartan_matrix()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/cartan_type.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/cartan_type.py
new file mode 100644
index 0000000000000000000000000000000000000000..16bb152469238ea912a30c2d0f8210d6f729bdb1
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/cartan_type.py
@@ -0,0 +1,73 @@
+from sympy.core import Atom, Basic
+
+
+class CartanType_generator():
+    """
+    Constructor for actually creating things
+    """
+    def __call__(self, *args):
+        c = args[0]
+        if isinstance(c, list):
+            letter, n = c[0], int(c[1])
+        elif isinstance(c, str):
+            letter, n = c[0], int(c[1:])
+        else:
+            raise TypeError("Argument must be a string (e.g. 'A3') or a list (e.g. ['A', 3])")
+
+        if n < 0:
+            raise ValueError("Lie algebra rank cannot be negative")
+        if letter == "A":
+            from . import type_a
+            return type_a.TypeA(n)
+        if letter == "B":
+            from . import type_b
+            return type_b.TypeB(n)
+
+        if letter == "C":
+            from . import type_c
+            return type_c.TypeC(n)
+
+        if letter == "D":
+            from . import type_d
+            return type_d.TypeD(n)
+
+        if letter == "E":
+            if n >= 6 and n <= 8:
+                from . import type_e
+                return type_e.TypeE(n)
+
+        if letter == "F":
+            if n == 4:
+                from . import type_f
+                return type_f.TypeF(n)
+
+        if letter == "G":
+            if n == 2:
+                from . import type_g
+                return type_g.TypeG(n)
+
+CartanType = CartanType_generator()
+
+
+class Standard_Cartan(Atom):
+    """
+    Concrete base class for Cartan types such as A4, etc
+    """
+
+    def __new__(cls, series, n):
+        obj = Basic.__new__(cls)
+        obj.n = n
+        obj.series = series
+        return obj
+
+    def rank(self):
+        """
+        Returns the rank of the Lie algebra
+        """
+        return self.n
+
+    def series(self):
+        """
+        Returns the type of the Lie algebra
+        """
+        return self.series
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/dynkin_diagram.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/dynkin_diagram.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc9e2dac4d54490b803eeaf9637cb9b66b01f058
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/dynkin_diagram.py
@@ -0,0 +1,24 @@
+from .cartan_type import CartanType
+
+
+def DynkinDiagram(t):
+    """Display the Dynkin diagram of a given Lie algebra
+
+    Works by generating the CartanType for the input, t, and then returning the
+    Dynkin diagram method from the individual classes.
+
+    Examples
+    ========
+
+    >>> from sympy.liealgebras.dynkin_diagram import DynkinDiagram
+    >>> print(DynkinDiagram("A3"))
+    0---0---0
+    1   2   3
+
+    >>> print(DynkinDiagram("B4"))
+    0---0---0=>=0
+    1   2   3   4
+
+    """
+
+    return CartanType(t).dynkin_diagram()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/root_system.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/root_system.py
new file mode 100644
index 0000000000000000000000000000000000000000..36eb24605e78bbdc669736910d89be5606df1389
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/root_system.py
@@ -0,0 +1,196 @@
+from .cartan_type import CartanType
+from sympy.core.basic import Atom
+
+class RootSystem(Atom):
+    """Represent the root system of a simple Lie algebra
+
+    Every simple Lie algebra has a unique root system.  To find the root
+    system, we first consider the Cartan subalgebra of g, which is the maximal
+    abelian subalgebra, and consider the adjoint action of g on this
+    subalgebra.  There is a root system associated with this action. Now, a
+    root system over a vector space V is a set of finite vectors Phi (called
+    roots), which satisfy:
+
+    1.  The roots span V
+    2.  The only scalar multiples of x in Phi are x and -x
+    3.  For every x in Phi, the set Phi is closed under reflection
+        through the hyperplane perpendicular to x.
+    4.  If x and y are roots in Phi, then the projection of y onto
+        the line through x is a half-integral multiple of x.
+
+    Now, there is a subset of Phi, which we will call Delta, such that:
+    1.  Delta is a basis of V
+    2.  Each root x in Phi can be written x = sum k_y y for y in Delta
+
+    The elements of Delta are called the simple roots.
+    Therefore, we see that the simple roots span the root space of a given
+    simple Lie algebra.
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Root_system
+    .. [2] Lie Algebras and Representation Theory - Humphreys
+
+    """
+
+    def __new__(cls, cartantype):
+        """Create a new RootSystem object
+
+        This method assigns an attribute called cartan_type to each instance of
+        a RootSystem object.  When an instance of RootSystem is called, it
+        needs an argument, which should be an instance of a simple Lie algebra.
+        We then take the CartanType of this argument and set it as the
+        cartan_type attribute of the RootSystem instance.
+
+        """
+        obj = Atom.__new__(cls)
+        obj.cartan_type = CartanType(cartantype)
+        return obj
+
+    def simple_roots(self):
+        """Generate the simple roots of the Lie algebra
+
+        The rank of the Lie algebra determines the number of simple roots that
+        it has.  This method obtains the rank of the Lie algebra, and then uses
+        the simple_root method from the Lie algebra classes to generate all the
+        simple roots.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.root_system import RootSystem
+        >>> c = RootSystem("A3")
+        >>> roots = c.simple_roots()
+        >>> roots
+        {1: [1, -1, 0, 0], 2: [0, 1, -1, 0], 3: [0, 0, 1, -1]}
+
+        """
+        n = self.cartan_type.rank()
+        roots = {i: self.cartan_type.simple_root(i) for i in range(1, n+1)}
+        return roots
+
+
+    def all_roots(self):
+        """Generate all the roots of a given root system
+
+        The result is a dictionary where the keys are integer numbers.  It
+        generates the roots by getting the dictionary of all positive roots
+        from the bases classes, and then taking each root, and multiplying it
+        by -1 and adding it to the dictionary.  In this way all the negative
+        roots are generated.
+
+        """
+        alpha = self.cartan_type.positive_roots()
+        keys = list(alpha.keys())
+        k = max(keys)
+        for val in keys:
+            k += 1
+            root = alpha[val]
+            newroot = [-x for x in root]
+            alpha[k] = newroot
+        return alpha
+
+    def root_space(self):
+        """Return the span of the simple roots
+
+        The root space is the vector space spanned by the simple roots, i.e. it
+        is a vector space with a distinguished basis, the simple roots.  This
+        method returns a string that represents the root space as the span of
+        the simple roots, alpha[1],...., alpha[n].
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.root_system import RootSystem
+        >>> c = RootSystem("A3")
+        >>> c.root_space()
+        'alpha[1] + alpha[2] + alpha[3]'
+
+        """
+        n = self.cartan_type.rank()
+        rs = " + ".join("alpha["+str(i) +"]" for i in range(1, n+1))
+        return rs
+
+    def add_simple_roots(self, root1, root2):
+        """Add two simple roots together
+
+        The function takes as input two integers, root1 and root2.  It then
+        uses these integers as keys in the dictionary of simple roots, and gets
+        the corresponding simple roots, and then adds them together.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.root_system import RootSystem
+        >>> c = RootSystem("A3")
+        >>> newroot = c.add_simple_roots(1, 2)
+        >>> newroot
+        [1, 0, -1, 0]
+
+        """
+
+        alpha = self.simple_roots()
+        if root1 > len(alpha) or root2 > len(alpha):
+            raise ValueError("You've used a root that doesn't exist!")
+        a1 = alpha[root1]
+        a2 = alpha[root2]
+        newroot = [_a1 + _a2 for _a1, _a2 in zip(a1, a2)]
+        return newroot
+
+    def add_as_roots(self, root1, root2):
+        """Add two roots together if and only if their sum is also a root
+
+        It takes as input two vectors which should be roots.  It then computes
+        their sum and checks if it is in the list of all possible roots.  If it
+        is, it returns the sum.  Otherwise it returns a string saying that the
+        sum is not a root.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.root_system import RootSystem
+        >>> c = RootSystem("A3")
+        >>> c.add_as_roots([1, 0, -1, 0], [0, 0, 1, -1])
+        [1, 0, 0, -1]
+        >>> c.add_as_roots([1, -1, 0, 0], [0, 0, -1, 1])
+        'The sum of these two roots is not a root'
+
+        """
+        alpha = self.all_roots()
+        newroot = [r1 + r2 for r1, r2 in zip(root1, root2)]
+        if newroot in alpha.values():
+            return newroot
+        else:
+            return "The sum of these two roots is not a root"
+
+
+    def cartan_matrix(self):
+        """Cartan matrix of Lie algebra associated with this root system
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.root_system import RootSystem
+        >>> c = RootSystem("A3")
+        >>> c.cartan_matrix()
+        Matrix([
+            [ 2, -1,  0],
+            [-1,  2, -1],
+            [ 0, -1,  2]])
+        """
+        return self.cartan_type.cartan_matrix()
+
+    def dynkin_diagram(self):
+        """Dynkin diagram of the Lie algebra associated with this root system
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.root_system import RootSystem
+        >>> c = RootSystem("A3")
+        >>> print(c.dynkin_diagram())
+        0---0---0
+        1   2   3
+        """
+        return self.cartan_type.dynkin_diagram()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_cartan_matrix.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_cartan_matrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..98b1793dee63e0e87c610768554a8388dfd641a1
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_cartan_matrix.py
@@ -0,0 +1,10 @@
+from sympy.liealgebras.cartan_matrix import CartanMatrix
+from sympy.matrices import Matrix
+
+def test_CartanMatrix():
+    c = CartanMatrix("A3")
+    m = Matrix(3, 3, [2, -1, 0, -1, 2, -1, 0, -1, 2])
+    assert c == m
+    a = CartanMatrix(["G",2])
+    mt = Matrix(2, 2, [2, -1, -3, 2])
+    assert a == mt
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_cartan_type.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_cartan_type.py
new file mode 100644
index 0000000000000000000000000000000000000000..257eeca41d0f5f2eb240cc270f76d452848ed405
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_cartan_type.py
@@ -0,0 +1,12 @@
+from sympy.liealgebras.cartan_type import CartanType, Standard_Cartan
+
+def test_Standard_Cartan():
+    c = CartanType("A4")
+    assert c.rank() == 4
+    assert c.series == "A"
+    m = Standard_Cartan("A", 2)
+    assert m.rank() == 2
+    assert m.series == "A"
+    b = CartanType("B12")
+    assert b.rank() == 12
+    assert b.series == "B"
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_dynkin_diagram.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_dynkin_diagram.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad2ee4c162945c437ecf83d75c7fef9455c9464a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_dynkin_diagram.py
@@ -0,0 +1,9 @@
+from sympy.liealgebras.dynkin_diagram import DynkinDiagram
+
+def test_DynkinDiagram():
+    c = DynkinDiagram("A3")
+    diag = "0---0---0\n1   2   3"
+    assert c == diag
+    ct = DynkinDiagram(["B", 3])
+    diag2 = "0---0=>=0\n1   2   3"
+    assert ct == diag2
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_root_system.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_root_system.py
new file mode 100644
index 0000000000000000000000000000000000000000..42110da5a1c59a7e6b2e537ee13746bfce361579
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_root_system.py
@@ -0,0 +1,18 @@
+from sympy.liealgebras.root_system import RootSystem
+from sympy.liealgebras.type_a import TypeA
+from sympy.matrices import Matrix
+
+def test_root_system():
+    c = RootSystem("A3")
+    assert c.cartan_type == TypeA(3)
+    assert c.simple_roots() ==  {1: [1, -1, 0, 0], 2: [0, 1, -1, 0], 3: [0, 0, 1, -1]}
+    assert c.root_space() == "alpha[1] + alpha[2] + alpha[3]"
+    assert c.cartan_matrix() == Matrix([[ 2, -1,  0], [-1,  2, -1], [ 0, -1,  2]])
+    assert c.dynkin_diagram() == "0---0---0\n1   2   3"
+    assert c.add_simple_roots(1, 2) == [1, 0, -1, 0]
+    assert c.all_roots() == {1: [1, -1, 0, 0], 2: [1, 0, -1, 0],
+            3: [1, 0, 0, -1], 4: [0, 1, -1, 0], 5: [0, 1, 0, -1],
+            6: [0, 0, 1, -1], 7: [-1, 1, 0, 0], 8: [-1, 0, 1, 0],
+            9: [-1, 0, 0, 1], 10: [0, -1, 1, 0],
+            11: [0, -1, 0, 1], 12: [0, 0, -1, 1]}
+    assert c.add_as_roots([1, 0, -1, 0], [0, 0, 1, -1]) == [1, 0, 0, -1]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_A.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_A.py
new file mode 100644
index 0000000000000000000000000000000000000000..85d6f451ee167cf6db17ab20e59efab86ac0b691
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_A.py
@@ -0,0 +1,17 @@
+from sympy.liealgebras.cartan_type import CartanType
+from sympy.matrices import Matrix
+
+def test_type_A():
+    c = CartanType("A3")
+    m = Matrix(3, 3, [2, -1, 0, -1, 2, -1, 0, -1, 2])
+    assert m == c.cartan_matrix()
+    assert c.basis() == 8
+    assert c.roots() == 12
+    assert c.dimension() == 4
+    assert c.simple_root(1) == [1, -1, 0, 0]
+    assert c.highest_root() == [1, 0, 0, -1]
+    assert c.lie_algebra() == "su(4)"
+    diag = "0---0---0\n1   2   3"
+    assert c.dynkin_diagram() == diag
+    assert c.positive_roots() == {1: [1, -1, 0, 0], 2: [1, 0, -1, 0],
+            3: [1, 0, 0, -1], 4: [0, 1, -1, 0], 5: [0, 1, 0, -1], 6: [0, 0, 1, -1]}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_B.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_B.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f2a9011f96bc647e48d39e16cf10703a99d86b3
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_B.py
@@ -0,0 +1,17 @@
+from sympy.liealgebras.cartan_type import CartanType
+from sympy.matrices import Matrix
+
+def test_type_B():
+    c = CartanType("B3")
+    m = Matrix(3, 3, [2, -1, 0, -1, 2, -2, 0, -1, 2])
+    assert m == c.cartan_matrix()
+    assert c.dimension() == 3
+    assert c.roots() == 18
+    assert c.simple_root(3) == [0, 0, 1]
+    assert c.basis() == 3
+    assert c.lie_algebra() == "so(6)"
+    diag = "0---0=>=0\n1   2   3"
+    assert c.dynkin_diagram() == diag
+    assert c.positive_roots() ==  {1: [1, -1, 0], 2: [1, 1, 0], 3: [1, 0, -1],
+            4: [1, 0, 1], 5: [0, 1, -1], 6: [0, 1, 1], 7: [1, 0, 0],
+            8: [0, 1, 0], 9: [0, 0, 1]}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_C.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_C.py
new file mode 100644
index 0000000000000000000000000000000000000000..8154c201e6c50adb7c74458b240ed98b9a0dd123
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_C.py
@@ -0,0 +1,22 @@
+from sympy.liealgebras.cartan_type import CartanType
+from sympy.matrices import Matrix
+
+def test_type_C():
+    c = CartanType("C4")
+    m = Matrix(4, 4, [2, -1, 0, 0, -1, 2, -1, 0, 0, -1, 2, -1, 0, 0, -2, 2])
+    assert c.cartan_matrix() == m
+    assert c.dimension() == 4
+    assert c.simple_root(4) == [0, 0, 0, 2]
+    assert c.roots() == 32
+    assert c.basis() == 36
+    assert c.lie_algebra() == "sp(8)"
+    t = CartanType(['C', 3])
+    assert t.dimension() == 3
+    diag = "0---0---0=<=0\n1   2   3   4"
+    assert c.dynkin_diagram() == diag
+    assert c.positive_roots() == {1: [1, -1, 0, 0], 2: [1, 1, 0, 0],
+            3: [1, 0, -1, 0], 4: [1, 0, 1, 0], 5: [1, 0, 0, -1],
+            6: [1, 0, 0, 1], 7: [0, 1, -1, 0], 8: [0, 1, 1, 0],
+            9: [0, 1, 0, -1], 10: [0, 1, 0, 1], 11: [0, 0, 1, -1],
+            12: [0, 0, 1, 1], 13: [2, 0, 0, 0], 14: [0, 2, 0, 0], 15: [0, 0, 2, 0],
+            16: [0, 0, 0, 2]}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_D.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_D.py
new file mode 100644
index 0000000000000000000000000000000000000000..ddf6a34cb5be475cc30042e95bf8eae2376a2223
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_D.py
@@ -0,0 +1,19 @@
+from sympy.liealgebras.cartan_type import CartanType
+from sympy.matrices import Matrix
+
+
+
+def test_type_D():
+    c = CartanType("D4")
+    m = Matrix(4, 4, [2, -1, 0, 0, -1, 2, -1, -1, 0, -1, 2, 0, 0, -1, 0, 2])
+    assert c.cartan_matrix() == m
+    assert c.basis() == 6
+    assert c.lie_algebra() == "so(8)"
+    assert c.roots() == 24
+    assert c.simple_root(3) == [0, 0, 1, -1]
+    diag = "    3\n    0\n    |\n    |\n0---0---0\n1   2   4"
+    assert diag == c.dynkin_diagram()
+    assert c.positive_roots() == {1: [1, -1, 0, 0], 2: [1, 1, 0, 0],
+            3: [1, 0, -1, 0], 4: [1, 0, 1, 0], 5: [1, 0, 0, -1], 6: [1, 0, 0, 1],
+            7: [0, 1, -1, 0], 8: [0, 1, 1, 0], 9: [0, 1, 0, -1], 10: [0, 1, 0, 1],
+            11: [0, 0, 1, -1], 12: [0, 0, 1, 1]}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_E.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_E.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdb08342f41ede3390f34e9b297864eda16bedc7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_E.py
@@ -0,0 +1,22 @@
+from sympy.liealgebras.cartan_type import CartanType
+from sympy.matrices import Matrix
+from sympy.core.backend import Rational
+
+def test_type_E():
+    c = CartanType("E6")
+    m = Matrix(6, 6, [2, 0, -1, 0, 0, 0, 0, 2, 0, -1, 0, 0,
+        -1, 0, 2, -1, 0, 0, 0, -1, -1, 2, -1, 0, 0, 0, 0,
+        -1, 2, -1, 0, 0, 0, 0, -1, 2])
+    assert c.cartan_matrix() == m
+    assert c.dimension() == 8
+    assert c.simple_root(6) == [0, 0, 0, -1, 1, 0, 0, 0]
+    assert c.roots() == 72
+    assert c.basis() == 78
+    diag = " "*8 + "2\n" + " "*8 + "0\n" + " "*8 + "|\n" + " "*8 + "|\n"
+    diag += "---".join("0" for i in range(1, 6))+"\n"
+    diag += "1   " + "   ".join(str(i) for i in range(3, 7))
+    assert c.dynkin_diagram() == diag
+    posroots = c.positive_roots()
+    assert posroots[8] == [1, 0, 0, 0, 1, 0, 0, 0]
+    assert posroots[21] == [Rational(1,2),Rational(1,2),Rational(1,2),Rational(1,2),
+                            Rational(1,2),Rational(-1,2),Rational(-1,2),Rational(1,2)]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_F.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_F.py
new file mode 100644
index 0000000000000000000000000000000000000000..fbb58223d0b5886e6044108c9c5cc3bbf371dd14
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_F.py
@@ -0,0 +1,24 @@
+from sympy.liealgebras.cartan_type import CartanType
+from sympy.matrices import Matrix
+from sympy.core.backend import S
+
+def test_type_F():
+    c = CartanType("F4")
+    m = Matrix(4, 4, [2, -1, 0, 0, -1, 2, -2, 0, 0, -1, 2, -1, 0, 0, -1, 2])
+    assert c.cartan_matrix() == m
+    assert c.dimension() == 4
+    assert c.simple_root(1) == [1, -1, 0, 0]
+    assert c.simple_root(2) == [0, 1, -1, 0]
+    assert c.simple_root(3) == [0, 0, 0, 1]
+    assert c.simple_root(4) == [-S.Half, -S.Half, -S.Half, -S.Half]
+    assert c.roots() == 48
+    assert c.basis() == 52
+    diag = "0---0=>=0---0\n" + "   ".join(str(i) for i in range(1, 5))
+    assert c.dynkin_diagram() == diag
+    assert c.positive_roots() == {1: [1, -1, 0, 0], 2: [1, 1, 0, 0], 3: [1, 0, -1, 0],
+            4: [1, 0, 1, 0], 5: [1, 0, 0, -1], 6: [1, 0, 0, 1], 7: [0, 1, -1, 0],
+            8: [0, 1, 1, 0], 9: [0, 1, 0, -1], 10: [0, 1, 0, 1], 11: [0, 0, 1, -1],
+            12: [0, 0, 1, 1], 13: [1, 0, 0, 0], 14: [0, 1, 0, 0], 15: [0, 0, 1, 0],
+            16: [0, 0, 0, 1], 17: [S.Half, S.Half, S.Half, S.Half], 18: [S.Half, -S.Half, S.Half, S.Half],
+            19: [S.Half, S.Half, -S.Half, S.Half], 20: [S.Half, S.Half, S.Half, -S.Half], 21: [S.Half, S.Half, -S.Half, -S.Half],
+            22: [S.Half, -S.Half, S.Half, -S.Half], 23: [S.Half, -S.Half, -S.Half, S.Half], 24: [S.Half, -S.Half, -S.Half, -S.Half]}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_G.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_G.py
new file mode 100644
index 0000000000000000000000000000000000000000..c427eeb85bad8fc77d17a1563a7b796d4e0f217f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_type_G.py
@@ -0,0 +1,16 @@
+# coding=utf-8
+from sympy.liealgebras.cartan_type import CartanType
+from sympy.matrices import Matrix
+
+def test_type_G():
+    c = CartanType("G2")
+    m = Matrix(2, 2, [2, -1, -3, 2])
+    assert c.cartan_matrix() == m
+    assert c.simple_root(2) == [1, -2, 1]
+    assert c.basis() == 14
+    assert c.roots() == 12
+    assert c.dimension() == 3
+    diag = "0≡<≡0\n1   2"
+    assert diag == c.dynkin_diagram()
+    assert c.positive_roots() == {1: [0, 1, -1], 2: [1, -2, 1], 3: [1, -1, 0],
+            4: [1, 0, 1], 5: [1, 1, -2], 6: [2, -1, -1]}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_weyl_group.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_weyl_group.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4e57246fdcb5a431d8bbd65f1f60e0254a9cdf0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/tests/test_weyl_group.py
@@ -0,0 +1,35 @@
+from sympy.liealgebras.weyl_group import WeylGroup
+from sympy.matrices import Matrix
+
+def test_weyl_group():
+    c = WeylGroup("A3")
+    assert c.matrix_form('r1*r2') == Matrix([[0, 0, 1, 0], [1, 0, 0, 0],
+        [0, 1, 0, 0], [0, 0, 0, 1]])
+    assert c.generators() == ['r1', 'r2', 'r3']
+    assert c.group_order() == 24.0
+    assert c.group_name() == "S4: the symmetric group acting on 4 elements."
+    assert c.coxeter_diagram() == "0---0---0\n1   2   3"
+    assert c.element_order('r1*r2*r3') == 4
+    assert c.element_order('r1*r3*r2*r3') == 3
+    d = WeylGroup("B5")
+    assert d.group_order() == 3840
+    assert d.element_order('r1*r2*r4*r5') == 12
+    assert d.matrix_form('r2*r3') ==  Matrix([[0, 0, 1, 0, 0], [1, 0, 0, 0, 0],
+        [0, 1, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]])
+    assert d.element_order('r1*r2*r1*r3*r5') == 6
+    e = WeylGroup("D5")
+    assert e.element_order('r2*r3*r5') == 4
+    assert e.matrix_form('r2*r3*r5') == Matrix([[1, 0, 0, 0, 0], [0, 0, 0, 0, -1],
+        [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, -1, 0]])
+    f = WeylGroup("G2")
+    assert f.element_order('r1*r2*r1*r2') == 3
+    assert f.element_order('r2*r1*r1*r2') == 1
+
+    assert f.matrix_form('r1*r2*r1*r2') == Matrix([[0, 1, 0], [0, 0, 1], [1, 0, 0]])
+    g = WeylGroup("F4")
+    assert g.matrix_form('r2*r3') == Matrix([[1, 0, 0, 0], [0, 1, 0, 0],
+        [0, 0, 0, -1], [0, 0, 1, 0]])
+
+    assert g.element_order('r2*r3') == 4
+    h = WeylGroup("E6")
+    assert h.group_order() == 51840
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_a.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_a.py
new file mode 100644
index 0000000000000000000000000000000000000000..96dc615366ae20d668d651620ac088f15751c50e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_a.py
@@ -0,0 +1,164 @@
+from sympy.liealgebras.cartan_type import Standard_Cartan
+from sympy.core.backend import eye
+
+
+class TypeA(Standard_Cartan):
+    """
+    This class contains the information about
+    the A series of simple Lie algebras.
+    ====
+    """
+
+    def __new__(cls, n):
+        if n < 1:
+            raise ValueError("n cannot be less than 1")
+        return Standard_Cartan.__new__(cls, "A", n)
+
+
+    def dimension(self):
+        """Dimension of the vector space V underlying the Lie algebra
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("A4")
+        >>> c.dimension()
+        5
+        """
+        return self.n+1
+
+
+    def basic_root(self, i, j):
+        """
+        This is a method just to generate roots
+        with a 1 iin the ith position and a -1
+        in the jth position.
+
+        """
+
+        n = self.n
+        root = [0]*(n+1)
+        root[i] = 1
+        root[j] = -1
+        return root
+
+    def simple_root(self, i):
+        """
+        Every lie algebra has a unique root system.
+        Given a root system Q, there is a subset of the
+        roots such that an element of Q is called a
+        simple root if it cannot be written as the sum
+        of two elements in Q.  If we let D denote the
+        set of simple roots, then it is clear that every
+        element of Q can be written as a linear combination
+        of elements of D with all coefficients non-negative.
+
+        In A_n the ith simple root is the root which has a 1
+        in the ith position, a -1 in the (i+1)th position,
+        and zeroes elsewhere.
+
+        This method returns the ith simple root for the A series.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("A4")
+        >>> c.simple_root(1)
+        [1, -1, 0, 0, 0]
+
+        """
+
+        return self.basic_root(i-1, i)
+
+    def positive_roots(self):
+        """
+        This method generates all the positive roots of
+        A_n.  This is half of all of the roots of A_n;
+        by multiplying all the positive roots by -1 we
+        get the negative roots.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("A3")
+        >>> c.positive_roots()
+        {1: [1, -1, 0, 0], 2: [1, 0, -1, 0], 3: [1, 0, 0, -1], 4: [0, 1, -1, 0],
+                5: [0, 1, 0, -1], 6: [0, 0, 1, -1]}
+        """
+
+        n = self.n
+        posroots = {}
+        k = 0
+        for i in range(0, n):
+            for j in range(i+1, n+1):
+                k += 1
+                posroots[k] = self.basic_root(i, j)
+        return posroots
+
+    def highest_root(self):
+        """
+        Returns the highest weight root for A_n
+        """
+
+        return self.basic_root(0, self.n)
+
+    def roots(self):
+        """
+        Returns the total number of roots for A_n
+        """
+        n = self.n
+        return n*(n+1)
+
+    def cartan_matrix(self):
+        """
+        Returns the Cartan matrix for A_n.
+        The Cartan matrix matrix for a Lie algebra is
+        generated by assigning an ordering to the simple
+        roots, (alpha[1], ...., alpha[l]).  Then the ijth
+        entry of the Cartan matrix is ().
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType('A4')
+        >>> c.cartan_matrix()
+        Matrix([
+        [ 2, -1,  0,  0],
+        [-1,  2, -1,  0],
+        [ 0, -1,  2, -1],
+        [ 0,  0, -1,  2]])
+
+        """
+
+        n = self.n
+        m = 2 * eye(n)
+        for i in range(1, n - 1):
+            m[i, i+1] = -1
+            m[i, i-1] = -1
+        m[0,1] = -1
+        m[n-1, n-2] = -1
+        return m
+
+    def basis(self):
+        """
+        Returns the number of independent generators of A_n
+        """
+        n = self.n
+        return n**2 - 1
+
+    def lie_algebra(self):
+        """
+        Returns the Lie algebra associated with A_n
+        """
+        n = self.n
+        return "su(" + str(n + 1) + ")"
+
+    def dynkin_diagram(self):
+        n = self.n
+        diag = "---".join("0" for i in range(1, n+1)) + "\n"
+        diag += "   ".join(str(i) for i in range(1, n+1))
+        return diag
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_b.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_b.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6ee85502261f4702769067c64021521a2bc1725
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_b.py
@@ -0,0 +1,170 @@
+from .cartan_type import Standard_Cartan
+from sympy.core.backend import eye
+
+class TypeB(Standard_Cartan):
+
+    def __new__(cls, n):
+        if n < 2:
+            raise ValueError("n cannot be less than 2")
+        return Standard_Cartan.__new__(cls, "B", n)
+
+    def dimension(self):
+        """Dimension of the vector space V underlying the Lie algebra
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("B3")
+        >>> c.dimension()
+        3
+        """
+
+        return self.n
+
+    def basic_root(self, i, j):
+        """
+        This is a method just to generate roots
+        with a 1 iin the ith position and a -1
+        in the jth position.
+
+        """
+        root = [0]*self.n
+        root[i] = 1
+        root[j] = -1
+        return root
+
+    def simple_root(self, i):
+        """
+        Every lie algebra has a unique root system.
+        Given a root system Q, there is a subset of the
+        roots such that an element of Q is called a
+        simple root if it cannot be written as the sum
+        of two elements in Q.  If we let D denote the
+        set of simple roots, then it is clear that every
+        element of Q can be written as a linear combination
+        of elements of D with all coefficients non-negative.
+
+        In B_n the first n-1 simple roots are the same as the
+        roots in A_(n-1) (a 1 in the ith position, a -1 in
+        the (i+1)th position, and zeroes elsewhere).  The n-th
+        simple root is the root with a 1 in the nth position
+        and zeroes elsewhere.
+
+        This method returns the ith simple root for the B series.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("B3")
+        >>> c.simple_root(2)
+        [0, 1, -1]
+
+        """
+        n = self.n
+        if i < n:
+            return self.basic_root(i-1, i)
+        else:
+            root = [0]*self.n
+            root[n-1] = 1
+            return root
+
+    def positive_roots(self):
+        """
+        This method generates all the positive roots of
+        A_n.  This is half of all of the roots of B_n;
+        by multiplying all the positive roots by -1 we
+        get the negative roots.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("A3")
+        >>> c.positive_roots()
+        {1: [1, -1, 0, 0], 2: [1, 0, -1, 0], 3: [1, 0, 0, -1], 4: [0, 1, -1, 0],
+                5: [0, 1, 0, -1], 6: [0, 0, 1, -1]}
+        """
+
+        n = self.n
+        posroots = {}
+        k = 0
+        for i in range(0, n-1):
+            for j in range(i+1, n):
+                k += 1
+                posroots[k] = self.basic_root(i, j)
+                k += 1
+                root = self.basic_root(i, j)
+                root[j] = 1
+                posroots[k] = root
+
+        for i in range(0, n):
+            k += 1
+            root = [0]*n
+            root[i] = 1
+            posroots[k] = root
+
+        return posroots
+
+    def roots(self):
+        """
+        Returns the total number of roots for B_n"
+        """
+
+        n = self.n
+        return 2*(n**2)
+
+    def cartan_matrix(self):
+        """
+        Returns the Cartan matrix for B_n.
+        The Cartan matrix matrix for a Lie algebra is
+        generated by assigning an ordering to the simple
+        roots, (alpha[1], ...., alpha[l]).  Then the ijth
+        entry of the Cartan matrix is ().
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType('B4')
+        >>> c.cartan_matrix()
+        Matrix([
+        [ 2, -1,  0,  0],
+        [-1,  2, -1,  0],
+        [ 0, -1,  2, -2],
+        [ 0,  0, -1,  2]])
+
+        """
+
+        n = self.n
+        m = 2* eye(n)
+        for i in range(1, n - 1):
+            m[i, i+1] = -1
+            m[i, i-1] = -1
+        m[0, 1] = -1
+        m[n-2, n-1] = -2
+        m[n-1, n-2] = -1
+        return m
+
+    def basis(self):
+        """
+        Returns the number of independent generators of B_n
+        """
+
+        n = self.n
+        return (n**2 - n)/2
+
+    def lie_algebra(self):
+        """
+        Returns the Lie algebra associated with B_n
+        """
+
+        n = self.n
+        return "so(" + str(2*n) + ")"
+
+    def dynkin_diagram(self):
+        n = self.n
+        diag = "---".join("0" for i in range(1, n)) + "=>=0\n"
+        diag += "   ".join(str(i) for i in range(1, n+1))
+        return diag
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_c.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_c.py
new file mode 100644
index 0000000000000000000000000000000000000000..615bb900b5ba9613fd02e43f476d34eef0d5d35c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_c.py
@@ -0,0 +1,169 @@
+from .cartan_type import Standard_Cartan
+from sympy.core.backend import eye
+
+class TypeC(Standard_Cartan):
+
+    def __new__(cls, n):
+        if n < 3:
+            raise ValueError("n cannot be less than 3")
+        return Standard_Cartan.__new__(cls, "C", n)
+
+
+    def dimension(self):
+        """Dimension of the vector space V underlying the Lie algebra
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("C3")
+        >>> c.dimension()
+        3
+        """
+        n = self.n
+        return n
+
+    def basic_root(self, i, j):
+        """Generate roots with 1 in ith position and a -1 in jth position
+        """
+        n = self.n
+        root = [0]*n
+        root[i] = 1
+        root[j] = -1
+        return root
+
+    def simple_root(self, i):
+        """The ith simple root for the C series
+
+        Every lie algebra has a unique root system.
+        Given a root system Q, there is a subset of the
+        roots such that an element of Q is called a
+        simple root if it cannot be written as the sum
+        of two elements in Q.  If we let D denote the
+        set of simple roots, then it is clear that every
+        element of Q can be written as a linear combination
+        of elements of D with all coefficients non-negative.
+
+        In C_n, the first n-1 simple roots are the same as
+        the roots in A_(n-1) (a 1 in the ith position, a -1
+        in the (i+1)th position, and zeroes elsewhere).  The
+        nth simple root is the root in which there is a 2 in
+        the nth position and zeroes elsewhere.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("C3")
+        >>> c.simple_root(2)
+        [0, 1, -1]
+
+        """
+
+        n = self.n
+        if i < n:
+            return self.basic_root(i-1,i)
+        else:
+            root = [0]*self.n
+            root[n-1] = 2
+            return root
+
+
+    def positive_roots(self):
+        """Generates all the positive roots of A_n
+
+        This is half of all of the roots of C_n; by multiplying all the
+        positive roots by -1 we get the negative roots.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("A3")
+        >>> c.positive_roots()
+        {1: [1, -1, 0, 0], 2: [1, 0, -1, 0], 3: [1, 0, 0, -1], 4: [0, 1, -1, 0],
+                5: [0, 1, 0, -1], 6: [0, 0, 1, -1]}
+
+        """
+
+        n = self.n
+        posroots = {}
+        k = 0
+        for i in range(0, n-1):
+            for j in range(i+1, n):
+                k += 1
+                posroots[k] = self.basic_root(i, j)
+                k += 1
+                root = self.basic_root(i, j)
+                root[j] = 1
+                posroots[k] = root
+
+        for i in range(0, n):
+            k += 1
+            root = [0]*n
+            root[i] = 2
+            posroots[k] = root
+
+        return posroots
+
+    def roots(self):
+        """
+        Returns the total number of roots for C_n"
+        """
+
+        n = self.n
+        return 2*(n**2)
+
+    def cartan_matrix(self):
+        """The Cartan matrix for C_n
+
+        The Cartan matrix matrix for a Lie algebra is
+        generated by assigning an ordering to the simple
+        roots, (alpha[1], ...., alpha[l]).  Then the ijth
+        entry of the Cartan matrix is ().
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType('C4')
+        >>> c.cartan_matrix()
+        Matrix([
+        [ 2, -1,  0,  0],
+        [-1,  2, -1,  0],
+        [ 0, -1,  2, -1],
+        [ 0,  0, -2,  2]])
+
+        """
+
+        n = self.n
+        m = 2 * eye(n)
+        for i in range(1, n - 1):
+            m[i, i+1] = -1
+            m[i, i-1] = -1
+        m[0,1] = -1
+        m[n-1, n-2] = -2
+        return m
+
+
+    def basis(self):
+        """
+        Returns the number of independent generators of C_n
+        """
+
+        n = self.n
+        return n*(2*n + 1)
+
+    def lie_algebra(self):
+        """
+        Returns the Lie algebra associated with C_n"
+        """
+
+        n = self.n
+        return "sp(" + str(2*n) + ")"
+
+    def dynkin_diagram(self):
+        n = self.n
+        diag = "---".join("0" for i in range(1, n)) + "=<=0\n"
+        diag += "   ".join(str(i) for i in range(1, n+1))
+        return diag
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_d.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_d.py
new file mode 100644
index 0000000000000000000000000000000000000000..9450d76e906c79e23db0ce223ed0de03d71c1199
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_d.py
@@ -0,0 +1,173 @@
+from .cartan_type import Standard_Cartan
+from sympy.core.backend import eye
+
+class TypeD(Standard_Cartan):
+
+    def __new__(cls, n):
+        if n < 3:
+            raise ValueError("n cannot be less than 3")
+        return Standard_Cartan.__new__(cls, "D", n)
+
+
+    def dimension(self):
+        """Dmension of the vector space V underlying the Lie algebra
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("D4")
+        >>> c.dimension()
+        4
+        """
+
+        return self.n
+
+    def basic_root(self, i, j):
+        """
+        This is a method just to generate roots
+        with a 1 iin the ith position and a -1
+        in the jth position.
+
+        """
+
+        n = self.n
+        root = [0]*n
+        root[i] = 1
+        root[j] = -1
+        return root
+
+    def simple_root(self, i):
+        """
+        Every lie algebra has a unique root system.
+        Given a root system Q, there is a subset of the
+        roots such that an element of Q is called a
+        simple root if it cannot be written as the sum
+        of two elements in Q.  If we let D denote the
+        set of simple roots, then it is clear that every
+        element of Q can be written as a linear combination
+        of elements of D with all coefficients non-negative.
+
+        In D_n, the first n-1 simple roots are the same as
+        the roots in A_(n-1) (a 1 in the ith position, a -1
+        in the (i+1)th position, and zeroes elsewhere).
+        The nth simple root is the root in which there 1s in
+        the nth and (n-1)th positions, and zeroes elsewhere.
+
+        This method returns the ith simple root for the D series.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("D4")
+        >>> c.simple_root(2)
+        [0, 1, -1, 0]
+
+        """
+
+        n = self.n
+        if i < n:
+            return self.basic_root(i-1, i)
+        else:
+            root = [0]*n
+            root[n-2] = 1
+            root[n-1] = 1
+            return root
+
+
+    def positive_roots(self):
+        """
+        This method generates all the positive roots of
+        A_n.  This is half of all of the roots of D_n
+        by multiplying all the positive roots by -1 we
+        get the negative roots.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("A3")
+        >>> c.positive_roots()
+        {1: [1, -1, 0, 0], 2: [1, 0, -1, 0], 3: [1, 0, 0, -1], 4: [0, 1, -1, 0],
+                5: [0, 1, 0, -1], 6: [0, 0, 1, -1]}
+        """
+
+        n = self.n
+        posroots = {}
+        k = 0
+        for i in range(0, n-1):
+            for j in range(i+1, n):
+                k += 1
+                posroots[k] = self.basic_root(i, j)
+                k += 1
+                root = self.basic_root(i, j)
+                root[j] = 1
+                posroots[k] = root
+        return posroots
+
+    def roots(self):
+        """
+        Returns the total number of roots for D_n"
+        """
+
+        n = self.n
+        return 2*n*(n-1)
+
+    def cartan_matrix(self):
+        """
+        Returns the Cartan matrix for D_n.
+        The Cartan matrix matrix for a Lie algebra is
+        generated by assigning an ordering to the simple
+        roots, (alpha[1], ...., alpha[l]).  Then the ijth
+        entry of the Cartan matrix is ().
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType('D4')
+        >>> c.cartan_matrix()
+            Matrix([
+            [ 2, -1,  0,  0],
+            [-1,  2, -1, -1],
+            [ 0, -1,  2,  0],
+            [ 0, -1,  0,  2]])
+
+        """
+
+        n = self.n
+        m = 2*eye(n)
+        for i in range(1, n - 2):
+            m[i,i+1] = -1
+            m[i,i-1] = -1
+        m[n-2, n-3] = -1
+        m[n-3, n-1] = -1
+        m[n-1, n-3] = -1
+        m[0, 1] = -1
+        return m
+
+    def basis(self):
+        """
+        Returns the number of independent generators of D_n
+        """
+        n = self.n
+        return n*(n-1)/2
+
+    def lie_algebra(self):
+        """
+        Returns the Lie algebra associated with D_n"
+        """
+
+        n = self.n
+        return "so(" + str(2*n) + ")"
+
+    def dynkin_diagram(self):
+        n = self.n
+        diag = " "*4*(n-3) + str(n-1) + "\n"
+        diag += " "*4*(n-3) + "0\n"
+        diag += " "*4*(n-3) +"|\n"
+        diag += " "*4*(n-3) + "|\n"
+        diag += "---".join("0" for i in range(1,n)) + "\n"
+        diag += "   ".join(str(i) for i in range(1, n-1)) + "   "+str(n)
+        return diag
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_e.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_e.py
new file mode 100644
index 0000000000000000000000000000000000000000..3db9a820d31bff31acc58ba1592a1b10f8be53db
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_e.py
@@ -0,0 +1,275 @@
+import itertools
+
+from .cartan_type import Standard_Cartan
+from sympy.core.backend import eye, Rational
+from sympy.core.singleton import S
+
+class TypeE(Standard_Cartan):
+
+    def __new__(cls, n):
+        if n < 6 or n > 8:
+            raise ValueError("Invalid value of n")
+        return Standard_Cartan.__new__(cls, "E", n)
+
+    def dimension(self):
+        """Dimension of the vector space V underlying the Lie algebra
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("E6")
+        >>> c.dimension()
+        8
+        """
+
+        return 8
+
+    def basic_root(self, i, j):
+        """
+        This is a method just to generate roots
+        with a -1 in the ith position and a 1
+        in the jth position.
+
+        """
+
+        root = [0]*8
+        root[i] = -1
+        root[j] = 1
+        return root
+
+    def simple_root(self, i):
+        """
+        Every Lie algebra has a unique root system.
+        Given a root system Q, there is a subset of the
+        roots such that an element of Q is called a
+        simple root if it cannot be written as the sum
+        of two elements in Q.  If we let D denote the
+        set of simple roots, then it is clear that every
+        element of Q can be written as a linear combination
+        of elements of D with all coefficients non-negative.
+
+        This method returns the ith simple root for E_n.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("E6")
+        >>> c.simple_root(2)
+        [1, 1, 0, 0, 0, 0, 0, 0]
+        """
+        n = self.n
+        if i == 1:
+            root = [-0.5]*8
+            root[0] = 0.5
+            root[7] = 0.5
+            return root
+        elif i == 2:
+            root = [0]*8
+            root[1] = 1
+            root[0] = 1
+            return root
+        else:
+            if i in (7, 8) and n == 6:
+                raise ValueError("E6 only has six simple roots!")
+            if i == 8 and n == 7:
+                raise ValueError("E7 only has seven simple roots!")
+
+            return self.basic_root(i - 3, i - 2)
+
+    def positive_roots(self):
+        """
+        This method generates all the positive roots of
+        A_n.  This is half of all of the roots of E_n;
+        by multiplying all the positive roots by -1 we
+        get the negative roots.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("A3")
+        >>> c.positive_roots()
+        {1: [1, -1, 0, 0], 2: [1, 0, -1, 0], 3: [1, 0, 0, -1], 4: [0, 1, -1, 0],
+                5: [0, 1, 0, -1], 6: [0, 0, 1, -1]}
+        """
+        n = self.n
+        neghalf = Rational(-1, 2)
+        poshalf = S.Half
+        if n == 6:
+            posroots = {}
+            k = 0
+            for i in range(n-1):
+                for j in range(i+1, n-1):
+                    k += 1
+                    root = self.basic_root(i, j)
+                    posroots[k] = root
+                    k += 1
+                    root = self.basic_root(i, j)
+                    root[i] = 1
+                    posroots[k] = root
+
+            root = [poshalf, poshalf, poshalf, poshalf, poshalf,
+                    neghalf, neghalf, poshalf]
+            for a, b, c, d, e in itertools.product(
+                    range(2), range(2), range(2), range(2), range(2)):
+                if (a + b + c + d + e)%2 == 0:
+                    k += 1
+                    if a == 1:
+                        root[0] = neghalf
+                    if b == 1:
+                        root[1] = neghalf
+                    if c == 1:
+                        root[2] = neghalf
+                    if d == 1:
+                        root[3] = neghalf
+                    if e == 1:
+                        root[4] = neghalf
+                    posroots[k] = root[:]
+            return posroots
+        if n == 7:
+            posroots = {}
+            k = 0
+            for i in range(n-1):
+                for j in range(i+1, n-1):
+                    k += 1
+                    root = self.basic_root(i, j)
+                    posroots[k] = root
+                    k += 1
+                    root = self.basic_root(i, j)
+                    root[i] = 1
+                    posroots[k] = root
+
+            k += 1
+            posroots[k] = [0, 0, 0, 0, 0, 1, 1, 0]
+            root = [poshalf, poshalf, poshalf, poshalf, poshalf,
+                    neghalf, neghalf, poshalf]
+            for a, b, c, d, e, f in itertools.product(
+                    range(2), range(2), range(2), range(2), range(2), range(2)):
+                if (a + b + c + d + e + f)%2 == 0:
+                    k += 1
+                    if a == 1:
+                        root[0] = neghalf
+                    if b == 1:
+                        root[1] = neghalf
+                    if c == 1:
+                        root[2] = neghalf
+                    if d == 1:
+                        root[3] = neghalf
+                    if e == 1:
+                        root[4] = neghalf
+                    if f == 1:
+                        root[5] = poshalf
+                    posroots[k] = root[:]
+            return posroots
+        if n == 8:
+            posroots = {}
+            k = 0
+            for i in range(n):
+                for j in range(i+1, n):
+                    k += 1
+                    root = self.basic_root(i, j)
+                    posroots[k] = root
+                    k += 1
+                    root = self.basic_root(i, j)
+                    root[i] = 1
+                    posroots[k] = root
+
+            root = [poshalf, poshalf, poshalf, poshalf, poshalf,
+                    neghalf, neghalf, poshalf]
+            for a, b, c, d, e, f, g in itertools.product(
+                    range(2), range(2), range(2), range(2), range(2),
+                    range(2), range(2)):
+                if (a + b + c + d + e + f + g)%2 == 0:
+                    k += 1
+                    if a == 1:
+                        root[0] = neghalf
+                    if b == 1:
+                        root[1] = neghalf
+                    if c == 1:
+                        root[2] = neghalf
+                    if d == 1:
+                        root[3] = neghalf
+                    if e == 1:
+                        root[4] = neghalf
+                    if f == 1:
+                        root[5] = poshalf
+                    if g == 1:
+                        root[6] = poshalf
+                    posroots[k] = root[:]
+            return posroots
+
+
+
+    def roots(self):
+        """
+        Returns the total number of roots of E_n
+        """
+
+        n = self.n
+        if n == 6:
+            return 72
+        if n == 7:
+            return 126
+        if n == 8:
+            return 240
+
+
+    def cartan_matrix(self):
+        """
+        Returns the Cartan matrix for G_2
+        The Cartan matrix matrix for a Lie algebra is
+        generated by assigning an ordering to the simple
+        roots, (alpha[1], ...., alpha[l]).  Then the ijth
+        entry of the Cartan matrix is ().
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType('A4')
+        >>> c.cartan_matrix()
+        Matrix([
+        [ 2, -1,  0,  0],
+        [-1,  2, -1,  0],
+        [ 0, -1,  2, -1],
+        [ 0,  0, -1,  2]])
+
+
+        """
+
+        n = self.n
+        m = 2*eye(n)
+        for i in range(3, n - 1):
+            m[i, i+1] = -1
+            m[i, i-1] = -1
+        m[0, 2] = m[2, 0] = -1
+        m[1, 3] = m[3, 1] = -1
+        m[2, 3] = -1
+        m[n-1, n-2] = -1
+        return m
+
+
+    def basis(self):
+        """
+        Returns the number of independent generators of E_n
+        """
+
+        n = self.n
+        if n == 6:
+            return 78
+        if n == 7:
+            return 133
+        if n == 8:
+            return 248
+
+    def dynkin_diagram(self):
+        n = self.n
+        diag = " "*8 + str(2) + "\n"
+        diag += " "*8 + "0\n"
+        diag += " "*8 + "|\n"
+        diag += " "*8 + "|\n"
+        diag += "---".join("0" for i in range(1, n)) + "\n"
+        diag += "1   " + "   ".join(str(i) for i in range(3, n+1))
+        return diag
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_f.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_f.py
new file mode 100644
index 0000000000000000000000000000000000000000..f04da557870f2cd21818cf69c454ef598e2ab65a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_f.py
@@ -0,0 +1,162 @@
+from .cartan_type import Standard_Cartan
+from sympy.core.backend import Matrix, Rational
+
+
+class TypeF(Standard_Cartan):
+
+    def __new__(cls, n):
+        if n != 4:
+            raise ValueError("n should be 4")
+        return Standard_Cartan.__new__(cls, "F", 4)
+
+    def dimension(self):
+        """Dimension of the vector space V underlying the Lie algebra
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("F4")
+        >>> c.dimension()
+        4
+        """
+
+        return 4
+
+
+    def basic_root(self, i, j):
+        """Generate roots with 1 in ith position and -1 in jth position
+
+        """
+
+        n = self.n
+        root = [0]*n
+        root[i] = 1
+        root[j] = -1
+        return root
+
+    def simple_root(self, i):
+        """The ith simple root of F_4
+
+        Every lie algebra has a unique root system.
+        Given a root system Q, there is a subset of the
+        roots such that an element of Q is called a
+        simple root if it cannot be written as the sum
+        of two elements in Q.  If we let D denote the
+        set of simple roots, then it is clear that every
+        element of Q can be written as a linear combination
+        of elements of D with all coefficients non-negative.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("F4")
+        >>> c.simple_root(3)
+        [0, 0, 0, 1]
+
+        """
+
+        if i < 3:
+            return self.basic_root(i-1, i)
+        if i == 3:
+            root = [0]*4
+            root[3] = 1
+            return root
+        if i == 4:
+            root = [Rational(-1, 2)]*4
+            return root
+
+    def positive_roots(self):
+        """Generate all the positive roots of A_n
+
+        This is half of all of the roots of F_4; by multiplying all the
+        positive roots by -1 we get the negative roots.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("A3")
+        >>> c.positive_roots()
+        {1: [1, -1, 0, 0], 2: [1, 0, -1, 0], 3: [1, 0, 0, -1], 4: [0, 1, -1, 0],
+                5: [0, 1, 0, -1], 6: [0, 0, 1, -1]}
+
+        """
+
+        n = self.n
+        posroots = {}
+        k = 0
+        for i in range(0, n-1):
+            for j in range(i+1, n):
+                k += 1
+                posroots[k] = self.basic_root(i, j)
+                k += 1
+                root = self.basic_root(i, j)
+                root[j] = 1
+                posroots[k] = root
+
+        for i in range(0, n):
+            k += 1
+            root = [0]*n
+            root[i] = 1
+            posroots[k] = root
+
+        k += 1
+        root = [Rational(1, 2)]*n
+        posroots[k] = root
+        for i in range(1, 4):
+            k += 1
+            root = [Rational(1, 2)]*n
+            root[i] = Rational(-1, 2)
+            posroots[k] = root
+
+        posroots[k+1] = [Rational(1, 2), Rational(1, 2), Rational(-1, 2), Rational(-1, 2)]
+        posroots[k+2] = [Rational(1, 2), Rational(-1, 2), Rational(1, 2), Rational(-1, 2)]
+        posroots[k+3] = [Rational(1, 2), Rational(-1, 2), Rational(-1, 2), Rational(1, 2)]
+        posroots[k+4] = [Rational(1, 2), Rational(-1, 2), Rational(-1, 2), Rational(-1, 2)]
+
+        return posroots
+
+
+    def roots(self):
+        """
+        Returns the total number of roots for F_4
+        """
+        return 48
+
+    def cartan_matrix(self):
+        """The Cartan matrix for F_4
+
+        The Cartan matrix matrix for a Lie algebra is
+        generated by assigning an ordering to the simple
+        roots, (alpha[1], ...., alpha[l]).  Then the ijth
+        entry of the Cartan matrix is ().
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType('A4')
+        >>> c.cartan_matrix()
+        Matrix([
+        [ 2, -1,  0,  0],
+        [-1,  2, -1,  0],
+        [ 0, -1,  2, -1],
+        [ 0,  0, -1,  2]])
+        """
+
+        m = Matrix( 4, 4, [2, -1, 0, 0, -1, 2, -2, 0, 0,
+            -1, 2, -1, 0, 0, -1, 2])
+        return m
+
+    def basis(self):
+        """
+        Returns the number of independent generators of F_4
+        """
+        return 52
+
+    def dynkin_diagram(self):
+        diag = "0---0=>=0---0\n"
+        diag += "   ".join(str(i) for i in range(1, 5))
+        return diag
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_g.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_g.py
new file mode 100644
index 0000000000000000000000000000000000000000..014409cf5ed966b53c596b14e0073e89ceee05b6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/type_g.py
@@ -0,0 +1,111 @@
+# -*- coding: utf-8 -*-
+
+from .cartan_type import Standard_Cartan
+from sympy.core.backend import Matrix
+
+class TypeG(Standard_Cartan):
+
+    def __new__(cls, n):
+        if n != 2:
+            raise ValueError("n should be 2")
+        return Standard_Cartan.__new__(cls, "G", 2)
+
+
+    def dimension(self):
+        """Dimension of the vector space V underlying the Lie algebra
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("G2")
+        >>> c.dimension()
+        3
+        """
+        return 3
+
+    def simple_root(self, i):
+        """The ith simple root of G_2
+
+        Every lie algebra has a unique root system.
+        Given a root system Q, there is a subset of the
+        roots such that an element of Q is called a
+        simple root if it cannot be written as the sum
+        of two elements in Q.  If we let D denote the
+        set of simple roots, then it is clear that every
+        element of Q can be written as a linear combination
+        of elements of D with all coefficients non-negative.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("G2")
+        >>> c.simple_root(1)
+        [0, 1, -1]
+
+        """
+        if i == 1:
+            return [0, 1, -1]
+        else:
+            return [1, -2, 1]
+
+    def positive_roots(self):
+        """Generate all the positive roots of A_n
+
+        This is half of all of the roots of A_n; by multiplying all the
+        positive roots by -1 we get the negative roots.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("A3")
+        >>> c.positive_roots()
+        {1: [1, -1, 0, 0], 2: [1, 0, -1, 0], 3: [1, 0, 0, -1], 4: [0, 1, -1, 0],
+                5: [0, 1, 0, -1], 6: [0, 0, 1, -1]}
+
+        """
+
+        roots = {1: [0, 1, -1], 2: [1, -2, 1], 3: [1, -1, 0], 4: [1, 0, 1],
+                5: [1, 1, -2], 6: [2, -1, -1]}
+        return roots
+
+    def roots(self):
+        """
+        Returns the total number of roots of G_2"
+        """
+        return 12
+
+    def cartan_matrix(self):
+        """The Cartan matrix for G_2
+
+        The Cartan matrix matrix for a Lie algebra is
+        generated by assigning an ordering to the simple
+        roots, (alpha[1], ...., alpha[l]).  Then the ijth
+        entry of the Cartan matrix is ().
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.cartan_type import CartanType
+        >>> c = CartanType("G2")
+        >>> c.cartan_matrix()
+        Matrix([
+            [ 2, -1],
+            [-3,  2]])
+
+        """
+
+        m = Matrix( 2, 2, [2, -1, -3, 2])
+        return m
+
+    def basis(self):
+        """
+        Returns the number of independent generators of G_2
+        """
+        return 14
+
+    def dynkin_diagram(self):
+        diag = "0≡<≡0\n1   2"
+        return diag
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/weyl_group.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/weyl_group.py
new file mode 100644
index 0000000000000000000000000000000000000000..15ff70b6f1fc4649268a38ee13e1f717a1c9f5fa
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/liealgebras/weyl_group.py
@@ -0,0 +1,403 @@
+# -*- coding: utf-8 -*-
+
+from .cartan_type import CartanType
+from mpmath import fac
+from sympy.core.backend import Matrix, eye, Rational, igcd
+from sympy.core.basic import Atom
+
+class WeylGroup(Atom):
+
+    """
+    For each semisimple Lie group, we have a Weyl group.  It is a subgroup of
+    the isometry group of the root system.  Specifically, it's the subgroup
+    that is generated by reflections through the hyperplanes orthogonal to
+    the roots.  Therefore, Weyl groups are reflection groups, and so a Weyl
+    group is a finite Coxeter group.
+
+    """
+
+    def __new__(cls, cartantype):
+        obj = Atom.__new__(cls)
+        obj.cartan_type = CartanType(cartantype)
+        return obj
+
+    def generators(self):
+        """
+        This method creates the generating reflections of the Weyl group for
+        a given Lie algebra.  For a Lie algebra of rank n, there are n
+        different generating reflections.  This function returns them as
+        a list.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.weyl_group import WeylGroup
+        >>> c = WeylGroup("F4")
+        >>> c.generators()
+        ['r1', 'r2', 'r3', 'r4']
+        """
+        n = self.cartan_type.rank()
+        generators = []
+        for i in range(1, n+1):
+            reflection = "r"+str(i)
+            generators.append(reflection)
+        return generators
+
+    def group_order(self):
+        """
+        This method returns the order of the Weyl group.
+        For types A, B, C, D, and E the order depends on
+        the rank of the Lie algebra.  For types F and G,
+        the order is fixed.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.weyl_group import WeylGroup
+        >>> c = WeylGroup("D4")
+        >>> c.group_order()
+        192.0
+        """
+        n = self.cartan_type.rank()
+        if self.cartan_type.series == "A":
+            return fac(n+1)
+
+        if self.cartan_type.series in ("B", "C"):
+            return fac(n)*(2**n)
+
+        if self.cartan_type.series == "D":
+            return fac(n)*(2**(n-1))
+
+        if self.cartan_type.series == "E":
+            if n == 6:
+                return 51840
+            if n == 7:
+                return 2903040
+            if n == 8:
+                return 696729600
+        if self.cartan_type.series == "F":
+            return 1152
+
+        if self.cartan_type.series == "G":
+            return 12
+
+    def group_name(self):
+        """
+        This method returns some general information about the Weyl group for
+        a given Lie algebra.  It returns the name of the group and the elements
+        it acts on, if relevant.
+        """
+        n = self.cartan_type.rank()
+        if self.cartan_type.series == "A":
+            return "S"+str(n+1) + ": the symmetric group acting on " + str(n+1) + " elements."
+
+        if self.cartan_type.series in ("B", "C"):
+            return "The hyperoctahedral group acting on " + str(2*n) + " elements."
+
+        if self.cartan_type.series == "D":
+            return "The symmetry group of the " + str(n) + "-dimensional demihypercube."
+
+        if self.cartan_type.series == "E":
+            if n == 6:
+                return "The symmetry group of the 6-polytope."
+
+            if n == 7:
+                return "The symmetry group of the 7-polytope."
+
+            if n == 8:
+                return "The symmetry group of the 8-polytope."
+
+        if self.cartan_type.series == "F":
+            return "The symmetry group of the 24-cell, or icositetrachoron."
+
+        if self.cartan_type.series == "G":
+            return "D6, the dihedral group of order 12, and symmetry group of the hexagon."
+
+    def element_order(self, weylelt):
+        """
+        This method returns the order of a given Weyl group element, which should
+        be specified by the user in the form of products of the generating
+        reflections, i.e. of the form r1*r2 etc.
+
+        For types A-F, this method current works by taking the matrix form of
+        the specified element, and then finding what power of the matrix is the
+        identity.  It then returns this power.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.weyl_group import WeylGroup
+        >>> b = WeylGroup("B4")
+        >>> b.element_order('r1*r4*r2')
+        4
+        """
+        n = self.cartan_type.rank()
+        if self.cartan_type.series == "A":
+            a = self.matrix_form(weylelt)
+            order = 1
+            while a != eye(n+1):
+                a *= self.matrix_form(weylelt)
+                order += 1
+            return order
+
+        if self.cartan_type.series == "D":
+            a = self.matrix_form(weylelt)
+            order = 1
+            while a != eye(n):
+                a *= self.matrix_form(weylelt)
+                order += 1
+            return order
+
+        if self.cartan_type.series == "E":
+            a = self.matrix_form(weylelt)
+            order = 1
+            while a != eye(8):
+                a *= self.matrix_form(weylelt)
+                order += 1
+            return order
+
+        if self.cartan_type.series == "G":
+            elts = list(weylelt)
+            reflections = elts[1::3]
+            m = self.delete_doubles(reflections)
+            while self.delete_doubles(m) != m:
+                m = self.delete_doubles(m)
+                reflections = m
+            if len(reflections) % 2 == 1:
+                return 2
+
+            elif len(reflections) == 0:
+                return 1
+
+            else:
+                if len(reflections) == 1:
+                    return 2
+                else:
+                    m = len(reflections) // 2
+                    lcm = (6 * m)/ igcd(m, 6)
+                order = lcm / m
+                return order
+
+
+        if self.cartan_type.series == 'F':
+            a = self.matrix_form(weylelt)
+            order = 1
+            while a != eye(4):
+                a *= self.matrix_form(weylelt)
+                order += 1
+            return order
+
+
+        if self.cartan_type.series in ("B", "C"):
+            a = self.matrix_form(weylelt)
+            order = 1
+            while a != eye(n):
+                a *= self.matrix_form(weylelt)
+                order += 1
+            return order
+
+    def delete_doubles(self, reflections):
+        """
+        This is a helper method for determining the order of an element in the
+        Weyl group of G2.  It takes a Weyl element and if repeated simple reflections
+        in it, it deletes them.
+        """
+        counter = 0
+        copy = list(reflections)
+        for elt in copy:
+            if counter < len(copy)-1:
+                if copy[counter + 1] == elt:
+                    del copy[counter]
+                    del copy[counter]
+            counter += 1
+
+
+        return copy
+
+
+    def matrix_form(self, weylelt):
+        """
+        This method takes input from the user in the form of products of the
+        generating reflections, and returns the matrix corresponding to the
+        element of the Weyl group.  Since each element of the Weyl group is
+        a reflection of some type, there is a corresponding matrix representation.
+        This method uses the standard representation for all the generating
+        reflections.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.weyl_group import WeylGroup
+        >>> f = WeylGroup("F4")
+        >>> f.matrix_form('r2*r3')
+        Matrix([
+        [1, 0, 0,  0],
+        [0, 1, 0,  0],
+        [0, 0, 0, -1],
+        [0, 0, 1,  0]])
+
+        """
+        elts = list(weylelt)
+        reflections = elts[1::3]
+        n = self.cartan_type.rank()
+        if self.cartan_type.series == 'A':
+            matrixform = eye(n+1)
+            for elt in reflections:
+                a = int(elt)
+                mat = eye(n+1)
+                mat[a-1, a-1] = 0
+                mat[a-1, a] = 1
+                mat[a, a-1] = 1
+                mat[a, a] = 0
+                matrixform *= mat
+            return matrixform
+
+        if self.cartan_type.series == 'D':
+            matrixform = eye(n)
+            for elt in reflections:
+                a = int(elt)
+                mat = eye(n)
+                if a < n:
+                    mat[a-1, a-1] = 0
+                    mat[a-1, a] = 1
+                    mat[a, a-1] = 1
+                    mat[a, a] = 0
+                    matrixform *= mat
+                else:
+                    mat[n-2, n-1] = -1
+                    mat[n-2, n-2] = 0
+                    mat[n-1, n-2] = -1
+                    mat[n-1, n-1] = 0
+                    matrixform *= mat
+            return matrixform
+
+        if self.cartan_type.series == 'G':
+            matrixform = eye(3)
+            for elt in reflections:
+                a = int(elt)
+                if a == 1:
+                    gen1 = Matrix([[1, 0, 0], [0, 0, 1], [0, 1, 0]])
+                    matrixform *= gen1
+                else:
+                    gen2 = Matrix([[Rational(2, 3), Rational(2, 3), Rational(-1, 3)],
+                                   [Rational(2, 3), Rational(-1, 3), Rational(2, 3)],
+                                   [Rational(-1, 3), Rational(2, 3), Rational(2, 3)]])
+                    matrixform *= gen2
+            return matrixform
+
+        if self.cartan_type.series == 'F':
+            matrixform = eye(4)
+            for elt in reflections:
+                a = int(elt)
+                if a == 1:
+                    mat = Matrix([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]])
+                    matrixform *= mat
+                elif a == 2:
+                    mat = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
+                    matrixform *= mat
+                elif a == 3:
+                    mat = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]])
+                    matrixform *= mat
+                else:
+
+                    mat = Matrix([[Rational(1, 2), Rational(1, 2), Rational(1, 2), Rational(1, 2)],
+                        [Rational(1, 2), Rational(1, 2), Rational(-1, 2), Rational(-1, 2)],
+                        [Rational(1, 2), Rational(-1, 2), Rational(1, 2), Rational(-1, 2)],
+                        [Rational(1, 2), Rational(-1, 2), Rational(-1, 2), Rational(1, 2)]])
+                    matrixform *= mat
+            return matrixform
+
+        if self.cartan_type.series == 'E':
+            matrixform = eye(8)
+            for elt in reflections:
+                a = int(elt)
+                if a == 1:
+                    mat = Matrix([[Rational(3, 4), Rational(1, 4), Rational(1, 4), Rational(1, 4),
+                        Rational(1, 4), Rational(1, 4), Rational(1, 4), Rational(-1, 4)],
+                        [Rational(1, 4), Rational(3, 4), Rational(-1, 4), Rational(-1, 4),
+                            Rational(-1, 4), Rational(-1, 4), Rational(1, 4), Rational(-1, 4)],
+                        [Rational(1, 4), Rational(-1, 4), Rational(3, 4), Rational(-1, 4),
+                        Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(1, 4)],
+                        [Rational(1, 4), Rational(-1, 4), Rational(-1, 4), Rational(3, 4),
+                        Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(1, 4)],
+                        [Rational(1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4),
+                        Rational(3, 4), Rational(-1, 4), Rational(-1, 4), Rational(1, 4)],
+                        [Rational(1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4),
+                        Rational(-1, 4), Rational(3, 4), Rational(-1, 4), Rational(1, 4)],
+                        [Rational(1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4),
+                        Rational(-1, 4), Rational(-1, 4), Rational(-3, 4), Rational(1, 4)],
+                        [Rational(1, 4), Rational(-1, 4), Rational(-1, 4), Rational(-1, 4),
+                        Rational(-1, 4), Rational(-1, 4), Rational(-1, 4), Rational(3, 4)]])
+                    matrixform *= mat
+                elif a == 2:
+                    mat = eye(8)
+                    mat[0, 0] = 0
+                    mat[0, 1] = -1
+                    mat[1, 0] = -1
+                    mat[1, 1] = 0
+                    matrixform *= mat
+                else:
+                    mat = eye(8)
+                    mat[a-3, a-3] = 0
+                    mat[a-3, a-2] = 1
+                    mat[a-2, a-3] = 1
+                    mat[a-2, a-2] = 0
+                    matrixform *= mat
+            return matrixform
+
+
+        if self.cartan_type.series in ("B", "C"):
+            matrixform = eye(n)
+            for elt in reflections:
+                a = int(elt)
+                mat = eye(n)
+                if a == 1:
+                    mat[0, 0] = -1
+                    matrixform *= mat
+                else:
+                    mat[a - 2, a - 2] = 0
+                    mat[a-2, a-1] = 1
+                    mat[a - 1, a - 2] = 1
+                    mat[a -1, a - 1] = 0
+                    matrixform *= mat
+            return matrixform
+
+
+
+    def coxeter_diagram(self):
+        """
+        This method returns the Coxeter diagram corresponding to a Weyl group.
+        The Coxeter diagram can be obtained from a Lie algebra's Dynkin diagram
+        by deleting all arrows; the Coxeter diagram is the undirected graph.
+        The vertices of the Coxeter diagram represent the generating reflections
+        of the Weyl group, $s_i$.  An edge is drawn between $s_i$ and $s_j$ if the order
+        $m(i, j)$ of $s_is_j$ is greater than two.  If there is one edge, the order
+        $m(i, j)$ is 3.  If there are two edges, the order $m(i, j)$ is 4, and if there
+        are three edges, the order $m(i, j)$ is 6.
+
+        Examples
+        ========
+
+        >>> from sympy.liealgebras.weyl_group import WeylGroup
+        >>> c = WeylGroup("B3")
+        >>> print(c.coxeter_diagram())
+        0---0===0
+        1   2   3
+        """
+        n = self.cartan_type.rank()
+        if self.cartan_type.series in ("A", "D", "E"):
+            return self.cartan_type.dynkin_diagram()
+
+        if self.cartan_type.series in ("B", "C"):
+            diag = "---".join("0" for i in range(1, n)) + "===0\n"
+            diag += "   ".join(str(i) for i in range(1, n+1))
+            return diag
+
+        if self.cartan_type.series == "F":
+            diag = "0---0===0---0\n"
+            diag += "   ".join(str(i) for i in range(1, 5))
+            return diag
+
+        if self.cartan_type.series == "G":
+            diag = "0≡≡≡0\n1   2"
+            return diag
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb26903a384e9df3a0f02a92c488c5442cee1486
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/__init__.py
@@ -0,0 +1,12 @@
+from .boolalg import (to_cnf, to_dnf, to_nnf, And, Or, Not, Xor, Nand, Nor, Implies,
+    Equivalent, ITE, POSform, SOPform, simplify_logic, bool_map, true, false,
+    gateinputcount)
+from .inference import satisfiable
+
+__all__ = [
+    'to_cnf', 'to_dnf', 'to_nnf', 'And', 'Or', 'Not', 'Xor', 'Nand', 'Nor',
+    'Implies', 'Equivalent', 'ITE', 'POSform', 'SOPform', 'simplify_logic',
+    'bool_map', 'true', 'false', 'gateinputcount',
+
+    'satisfiable',
+]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d10499c3d563276599a5b3e03abec7d29d27567f
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/__pycache__/inference.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/__pycache__/inference.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f842d24a2cca7f158502d0db63615dfc0cc02466
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/__pycache__/inference.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/algorithms/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/algorithms/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/algorithms/dpll.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/algorithms/dpll.py
new file mode 100644
index 0000000000000000000000000000000000000000..40e6802f7626c982a9a6cd7146baea3ac6b8b6e0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/algorithms/dpll.py
@@ -0,0 +1,308 @@
+"""Implementation of DPLL algorithm
+
+Further improvements: eliminate calls to pl_true, implement branching rules,
+efficient unit propagation.
+
+References:
+  - https://en.wikipedia.org/wiki/DPLL_algorithm
+  - https://www.researchgate.net/publication/242384772_Implementations_of_the_DPLL_Algorithm
+"""
+
+from sympy.core.sorting import default_sort_key
+from sympy.logic.boolalg import Or, Not, conjuncts, disjuncts, to_cnf, \
+    to_int_repr, _find_predicates
+from sympy.assumptions.cnf import CNF
+from sympy.logic.inference import pl_true, literal_symbol
+
+
+def dpll_satisfiable(expr):
+    """
+    Check satisfiability of a propositional sentence.
+    It returns a model rather than True when it succeeds
+
+    >>> from sympy.abc import A, B
+    >>> from sympy.logic.algorithms.dpll import dpll_satisfiable
+    >>> dpll_satisfiable(A & ~B)
+    {A: True, B: False}
+    >>> dpll_satisfiable(A & ~A)
+    False
+
+    """
+    if not isinstance(expr, CNF):
+        clauses = conjuncts(to_cnf(expr))
+    else:
+        clauses = expr.clauses
+    if False in clauses:
+        return False
+    symbols = sorted(_find_predicates(expr), key=default_sort_key)
+    symbols_int_repr = set(range(1, len(symbols) + 1))
+    clauses_int_repr = to_int_repr(clauses, symbols)
+    result = dpll_int_repr(clauses_int_repr, symbols_int_repr, {})
+    if not result:
+        return result
+    output = {}
+    for key in result:
+        output.update({symbols[key - 1]: result[key]})
+    return output
+
+
+def dpll(clauses, symbols, model):
+    """
+    Compute satisfiability in a partial model.
+    Clauses is an array of conjuncts.
+
+    >>> from sympy.abc import A, B, D
+    >>> from sympy.logic.algorithms.dpll import dpll
+    >>> dpll([A, B, D], [A, B], {D: False})
+    False
+
+    """
+    # compute DP kernel
+    P, value = find_unit_clause(clauses, model)
+    while P:
+        model.update({P: value})
+        symbols.remove(P)
+        if not value:
+            P = ~P
+        clauses = unit_propagate(clauses, P)
+        P, value = find_unit_clause(clauses, model)
+    P, value = find_pure_symbol(symbols, clauses)
+    while P:
+        model.update({P: value})
+        symbols.remove(P)
+        if not value:
+            P = ~P
+        clauses = unit_propagate(clauses, P)
+        P, value = find_pure_symbol(symbols, clauses)
+    # end DP kernel
+    unknown_clauses = []
+    for c in clauses:
+        val = pl_true(c, model)
+        if val is False:
+            return False
+        if val is not True:
+            unknown_clauses.append(c)
+    if not unknown_clauses:
+        return model
+    if not clauses:
+        return model
+    P = symbols.pop()
+    model_copy = model.copy()
+    model.update({P: True})
+    model_copy.update({P: False})
+    symbols_copy = symbols[:]
+    return (dpll(unit_propagate(unknown_clauses, P), symbols, model) or
+            dpll(unit_propagate(unknown_clauses, Not(P)), symbols_copy, model_copy))
+
+
+def dpll_int_repr(clauses, symbols, model):
+    """
+    Compute satisfiability in a partial model.
+    Arguments are expected to be in integer representation
+
+    >>> from sympy.logic.algorithms.dpll import dpll_int_repr
+    >>> dpll_int_repr([{1}, {2}, {3}], {1, 2}, {3: False})
+    False
+
+    """
+    # compute DP kernel
+    P, value = find_unit_clause_int_repr(clauses, model)
+    while P:
+        model.update({P: value})
+        symbols.remove(P)
+        if not value:
+            P = -P
+        clauses = unit_propagate_int_repr(clauses, P)
+        P, value = find_unit_clause_int_repr(clauses, model)
+    P, value = find_pure_symbol_int_repr(symbols, clauses)
+    while P:
+        model.update({P: value})
+        symbols.remove(P)
+        if not value:
+            P = -P
+        clauses = unit_propagate_int_repr(clauses, P)
+        P, value = find_pure_symbol_int_repr(symbols, clauses)
+    # end DP kernel
+    unknown_clauses = []
+    for c in clauses:
+        val = pl_true_int_repr(c, model)
+        if val is False:
+            return False
+        if val is not True:
+            unknown_clauses.append(c)
+    if not unknown_clauses:
+        return model
+    P = symbols.pop()
+    model_copy = model.copy()
+    model.update({P: True})
+    model_copy.update({P: False})
+    symbols_copy = symbols.copy()
+    return (dpll_int_repr(unit_propagate_int_repr(unknown_clauses, P), symbols, model) or
+            dpll_int_repr(unit_propagate_int_repr(unknown_clauses, -P), symbols_copy, model_copy))
+
+### helper methods for DPLL
+
+
+def pl_true_int_repr(clause, model={}):
+    """
+    Lightweight version of pl_true.
+    Argument clause represents the set of args of an Or clause. This is used
+    inside dpll_int_repr, it is not meant to be used directly.
+
+    >>> from sympy.logic.algorithms.dpll import pl_true_int_repr
+    >>> pl_true_int_repr({1, 2}, {1: False})
+    >>> pl_true_int_repr({1, 2}, {1: False, 2: False})
+    False
+
+    """
+    result = False
+    for lit in clause:
+        if lit < 0:
+            p = model.get(-lit)
+            if p is not None:
+                p = not p
+        else:
+            p = model.get(lit)
+        if p is True:
+            return True
+        elif p is None:
+            result = None
+    return result
+
+
+def unit_propagate(clauses, symbol):
+    """
+    Returns an equivalent set of clauses
+    If a set of clauses contains the unit clause l, the other clauses are
+    simplified by the application of the two following rules:
+
+      1. every clause containing l is removed
+      2. in every clause that contains ~l this literal is deleted
+
+    Arguments are expected to be in CNF.
+
+    >>> from sympy.abc import A, B, D
+    >>> from sympy.logic.algorithms.dpll import unit_propagate
+    >>> unit_propagate([A | B, D | ~B, B], B)
+    [D, B]
+
+    """
+    output = []
+    for c in clauses:
+        if c.func != Or:
+            output.append(c)
+            continue
+        for arg in c.args:
+            if arg == ~symbol:
+                output.append(Or(*[x for x in c.args if x != ~symbol]))
+                break
+            if arg == symbol:
+                break
+        else:
+            output.append(c)
+    return output
+
+
+def unit_propagate_int_repr(clauses, s):
+    """
+    Same as unit_propagate, but arguments are expected to be in integer
+    representation
+
+    >>> from sympy.logic.algorithms.dpll import unit_propagate_int_repr
+    >>> unit_propagate_int_repr([{1, 2}, {3, -2}, {2}], 2)
+    [{3}]
+
+    """
+    negated = {-s}
+    return [clause - negated for clause in clauses if s not in clause]
+
+
+def find_pure_symbol(symbols, unknown_clauses):
+    """
+    Find a symbol and its value if it appears only as a positive literal
+    (or only as a negative) in clauses.
+
+    >>> from sympy.abc import A, B, D
+    >>> from sympy.logic.algorithms.dpll import find_pure_symbol
+    >>> find_pure_symbol([A, B, D], [A|~B,~B|~D,D|A])
+    (A, True)
+
+    """
+    for sym in symbols:
+        found_pos, found_neg = False, False
+        for c in unknown_clauses:
+            if not found_pos and sym in disjuncts(c):
+                found_pos = True
+            if not found_neg and Not(sym) in disjuncts(c):
+                found_neg = True
+        if found_pos != found_neg:
+            return sym, found_pos
+    return None, None
+
+
+def find_pure_symbol_int_repr(symbols, unknown_clauses):
+    """
+    Same as find_pure_symbol, but arguments are expected
+    to be in integer representation
+
+    >>> from sympy.logic.algorithms.dpll import find_pure_symbol_int_repr
+    >>> find_pure_symbol_int_repr({1,2,3},
+    ...     [{1, -2}, {-2, -3}, {3, 1}])
+    (1, True)
+
+    """
+    all_symbols = set().union(*unknown_clauses)
+    found_pos = all_symbols.intersection(symbols)
+    found_neg = all_symbols.intersection([-s for s in symbols])
+    for p in found_pos:
+        if -p not in found_neg:
+            return p, True
+    for p in found_neg:
+        if -p not in found_pos:
+            return -p, False
+    return None, None
+
+
+def find_unit_clause(clauses, model):
+    """
+    A unit clause has only 1 variable that is not bound in the model.
+
+    >>> from sympy.abc import A, B, D
+    >>> from sympy.logic.algorithms.dpll import find_unit_clause
+    >>> find_unit_clause([A | B | D, B | ~D, A | ~B], {A:True})
+    (B, False)
+
+    """
+    for clause in clauses:
+        num_not_in_model = 0
+        for literal in disjuncts(clause):
+            sym = literal_symbol(literal)
+            if sym not in model:
+                num_not_in_model += 1
+                P, value = sym, not isinstance(literal, Not)
+        if num_not_in_model == 1:
+            return P, value
+    return None, None
+
+
+def find_unit_clause_int_repr(clauses, model):
+    """
+    Same as find_unit_clause, but arguments are expected to be in
+    integer representation.
+
+    >>> from sympy.logic.algorithms.dpll import find_unit_clause_int_repr
+    >>> find_unit_clause_int_repr([{1, 2, 3},
+    ...     {2, -3}, {1, -2}], {1: True})
+    (2, False)
+
+    """
+    bound = set(model) | {-sym for sym in model}
+    for clause in clauses:
+        unbound = clause - bound
+        if len(unbound) == 1:
+            p = unbound.pop()
+            if p < 0:
+                return -p, False
+            else:
+                return p, True
+    return None, None
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/algorithms/dpll2.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/algorithms/dpll2.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f18c81189d6be565dc9b7caa3f0bf48e978bb56
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/algorithms/dpll2.py
@@ -0,0 +1,688 @@
+"""Implementation of DPLL algorithm
+
+Features:
+  - Clause learning
+  - Watch literal scheme
+  - VSIDS heuristic
+
+References:
+  - https://en.wikipedia.org/wiki/DPLL_algorithm
+"""
+
+from collections import defaultdict
+from heapq import heappush, heappop
+
+from sympy.core.sorting import ordered
+from sympy.assumptions.cnf import EncodedCNF
+
+from sympy.logic.algorithms.lra_theory import LRASolver
+
+
+def dpll_satisfiable(expr, all_models=False, use_lra_theory=False):
+    """
+    Check satisfiability of a propositional sentence.
+    It returns a model rather than True when it succeeds.
+    Returns a generator of all models if all_models is True.
+
+    Examples
+    ========
+
+    >>> from sympy.abc import A, B
+    >>> from sympy.logic.algorithms.dpll2 import dpll_satisfiable
+    >>> dpll_satisfiable(A & ~B)
+    {A: True, B: False}
+    >>> dpll_satisfiable(A & ~A)
+    False
+
+    """
+    if not isinstance(expr, EncodedCNF):
+        exprs = EncodedCNF()
+        exprs.add_prop(expr)
+        expr = exprs
+
+    # Return UNSAT when False (encoded as 0) is present in the CNF
+    if {0} in expr.data:
+        if all_models:
+            return (f for f in [False])
+        return False
+
+    if use_lra_theory:
+        lra, immediate_conflicts = LRASolver.from_encoded_cnf(expr)
+    else:
+        lra = None
+        immediate_conflicts = []
+    solver = SATSolver(expr.data + immediate_conflicts, expr.variables, set(), expr.symbols, lra_theory=lra)
+    models = solver._find_model()
+
+    if all_models:
+        return _all_models(models)
+
+    try:
+        return next(models)
+    except StopIteration:
+        return False
+
+    # Uncomment to confirm the solution is valid (hitting set for the clauses)
+    #else:
+        #for cls in clauses_int_repr:
+            #assert solver.var_settings.intersection(cls)
+
+
+def _all_models(models):
+    satisfiable = False
+    try:
+        while True:
+            yield next(models)
+            satisfiable = True
+    except StopIteration:
+        if not satisfiable:
+            yield False
+
+
+class SATSolver:
+    """
+    Class for representing a SAT solver capable of
+     finding a model to a boolean theory in conjunctive
+     normal form.
+    """
+
+    def __init__(self, clauses, variables, var_settings, symbols=None,
+                heuristic='vsids', clause_learning='none', INTERVAL=500,
+                 lra_theory = None):
+
+        self.var_settings = var_settings
+        self.heuristic = heuristic
+        self.is_unsatisfied = False
+        self._unit_prop_queue = []
+        self.update_functions = []
+        self.INTERVAL = INTERVAL
+
+        if symbols is None:
+            self.symbols = list(ordered(variables))
+        else:
+            self.symbols = symbols
+
+        self._initialize_variables(variables)
+        self._initialize_clauses(clauses)
+
+        if 'vsids' == heuristic:
+            self._vsids_init()
+            self.heur_calculate = self._vsids_calculate
+            self.heur_lit_assigned = self._vsids_lit_assigned
+            self.heur_lit_unset = self._vsids_lit_unset
+            self.heur_clause_added = self._vsids_clause_added
+
+            # Note: Uncomment this if/when clause learning is enabled
+            #self.update_functions.append(self._vsids_decay)
+
+        else:
+            raise NotImplementedError
+
+        if 'simple' == clause_learning:
+            self.add_learned_clause = self._simple_add_learned_clause
+            self.compute_conflict = self._simple_compute_conflict
+            self.update_functions.append(self._simple_clean_clauses)
+        elif 'none' == clause_learning:
+            self.add_learned_clause = lambda x: None
+            self.compute_conflict = lambda: None
+        else:
+            raise NotImplementedError
+
+        # Create the base level
+        self.levels = [Level(0)]
+        self._current_level.varsettings = var_settings
+
+        # Keep stats
+        self.num_decisions = 0
+        self.num_learned_clauses = 0
+        self.original_num_clauses = len(self.clauses)
+
+        self.lra = lra_theory
+
+    def _initialize_variables(self, variables):
+        """Set up the variable data structures needed."""
+        self.sentinels = defaultdict(set)
+        self.occurrence_count = defaultdict(int)
+        self.variable_set = [False] * (len(variables) + 1)
+
+    def _initialize_clauses(self, clauses):
+        """Set up the clause data structures needed.
+
+        For each clause, the following changes are made:
+        - Unit clauses are queued for propagation right away.
+        - Non-unit clauses have their first and last literals set as sentinels.
+        - The number of clauses a literal appears in is computed.
+        """
+        self.clauses = [list(clause) for clause in clauses]
+
+        for i, clause in enumerate(self.clauses):
+
+            # Handle the unit clauses
+            if 1 == len(clause):
+                self._unit_prop_queue.append(clause[0])
+                continue
+
+            self.sentinels[clause[0]].add(i)
+            self.sentinels[clause[-1]].add(i)
+
+            for lit in clause:
+                self.occurrence_count[lit] += 1
+
+    def _find_model(self):
+        """
+        Main DPLL loop. Returns a generator of models.
+
+        Variables are chosen successively, and assigned to be either
+        True or False. If a solution is not found with this setting,
+        the opposite is chosen and the search continues. The solver
+        halts when every variable has a setting.
+
+        Examples
+        ========
+
+        >>> from sympy.logic.algorithms.dpll2 import SATSolver
+        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
+        ... {3, -2}], {1, 2, 3}, set())
+        >>> list(l._find_model())
+        [{1: True, 2: False, 3: False}, {1: True, 2: True, 3: True}]
+
+        >>> from sympy.abc import A, B, C
+        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
+        ... {3, -2}], {1, 2, 3}, set(), [A, B, C])
+        >>> list(l._find_model())
+        [{A: True, B: False, C: False}, {A: True, B: True, C: True}]
+
+        """
+
+        # We use this variable to keep track of if we should flip a
+        #  variable setting in successive rounds
+        flip_var = False
+
+        # Check if unit prop says the theory is unsat right off the bat
+        self._simplify()
+        if self.is_unsatisfied:
+            return
+
+        # While the theory still has clauses remaining
+        while True:
+            # Perform cleanup / fixup at regular intervals
+            if self.num_decisions % self.INTERVAL == 0:
+                for func in self.update_functions:
+                    func()
+
+            if flip_var:
+                # We have just backtracked and we are trying to opposite literal
+                flip_var = False
+                lit = self._current_level.decision
+
+            else:
+                # Pick a literal to set
+                lit = self.heur_calculate()
+                self.num_decisions += 1
+
+                # Stopping condition for a satisfying theory
+                if 0 == lit:
+
+                    # check if assignment satisfies lra theory
+                    if self.lra:
+                        for enc_var in self.var_settings:
+                            res = self.lra.assert_lit(enc_var)
+                            if res is not None:
+                                break
+                        res = self.lra.check()
+                        self.lra.reset_bounds()
+                    else:
+                        res = None
+                    if res is None or res[0]:
+                        yield {self.symbols[abs(lit) - 1]:
+                                    lit > 0 for lit in self.var_settings}
+                    else:
+                        self._simple_add_learned_clause(res[1])
+
+                        # backtrack until we unassign one of the literals causing the conflict
+                        while not any(-lit in res[1] for lit in self._current_level.var_settings):
+                            self._undo()
+
+                    while self._current_level.flipped:
+                        self._undo()
+                    if len(self.levels) == 1:
+                        return
+                    flip_lit = -self._current_level.decision
+                    self._undo()
+                    self.levels.append(Level(flip_lit, flipped=True))
+                    flip_var = True
+                    continue
+
+                # Start the new decision level
+                self.levels.append(Level(lit))
+
+            # Assign the literal, updating the clauses it satisfies
+            self._assign_literal(lit)
+
+            # _simplify the theory
+            self._simplify()
+
+            # Check if we've made the theory unsat
+            if self.is_unsatisfied:
+
+                self.is_unsatisfied = False
+
+                # We unroll all of the decisions until we can flip a literal
+                while self._current_level.flipped:
+                    self._undo()
+
+                    # If we've unrolled all the way, the theory is unsat
+                    if 1 == len(self.levels):
+                        return
+
+                # Detect and add a learned clause
+                self.add_learned_clause(self.compute_conflict())
+
+                # Try the opposite setting of the most recent decision
+                flip_lit = -self._current_level.decision
+                self._undo()
+                self.levels.append(Level(flip_lit, flipped=True))
+                flip_var = True
+
+    ########################
+    #    Helper Methods    #
+    ########################
+    @property
+    def _current_level(self):
+        """The current decision level data structure
+
+        Examples
+        ========
+
+        >>> from sympy.logic.algorithms.dpll2 import SATSolver
+        >>> l = SATSolver([{1}, {2}], {1, 2}, set())
+        >>> next(l._find_model())
+        {1: True, 2: True}
+        >>> l._current_level.decision
+        0
+        >>> l._current_level.flipped
+        False
+        >>> l._current_level.var_settings
+        {1, 2}
+
+        """
+        return self.levels[-1]
+
+    def _clause_sat(self, cls):
+        """Check if a clause is satisfied by the current variable setting.
+
+        Examples
+        ========
+
+        >>> from sympy.logic.algorithms.dpll2 import SATSolver
+        >>> l = SATSolver([{1}, {-1}], {1}, set())
+        >>> try:
+        ...     next(l._find_model())
+        ... except StopIteration:
+        ...     pass
+        >>> l._clause_sat(0)
+        False
+        >>> l._clause_sat(1)
+        True
+
+        """
+        for lit in self.clauses[cls]:
+            if lit in self.var_settings:
+                return True
+        return False
+
+    def _is_sentinel(self, lit, cls):
+        """Check if a literal is a sentinel of a given clause.
+
+        Examples
+        ========
+
+        >>> from sympy.logic.algorithms.dpll2 import SATSolver
+        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
+        ... {3, -2}], {1, 2, 3}, set())
+        >>> next(l._find_model())
+        {1: True, 2: False, 3: False}
+        >>> l._is_sentinel(2, 3)
+        True
+        >>> l._is_sentinel(-3, 1)
+        False
+
+        """
+        return cls in self.sentinels[lit]
+
+    def _assign_literal(self, lit):
+        """Make a literal assignment.
+
+        The literal assignment must be recorded as part of the current
+        decision level. Additionally, if the literal is marked as a
+        sentinel of any clause, then a new sentinel must be chosen. If
+        this is not possible, then unit propagation is triggered and
+        another literal is added to the queue to be set in the future.
+
+        Examples
+        ========
+
+        >>> from sympy.logic.algorithms.dpll2 import SATSolver
+        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
+        ... {3, -2}], {1, 2, 3}, set())
+        >>> next(l._find_model())
+        {1: True, 2: False, 3: False}
+        >>> l.var_settings
+        {-3, -2, 1}
+
+        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
+        ... {3, -2}], {1, 2, 3}, set())
+        >>> l._assign_literal(-1)
+        >>> try:
+        ...     next(l._find_model())
+        ... except StopIteration:
+        ...     pass
+        >>> l.var_settings
+        {-1}
+
+        """
+        self.var_settings.add(lit)
+        self._current_level.var_settings.add(lit)
+        self.variable_set[abs(lit)] = True
+        self.heur_lit_assigned(lit)
+
+        sentinel_list = list(self.sentinels[-lit])
+
+        for cls in sentinel_list:
+            if not self._clause_sat(cls):
+                other_sentinel = None
+                for newlit in self.clauses[cls]:
+                    if newlit != -lit:
+                        if self._is_sentinel(newlit, cls):
+                            other_sentinel = newlit
+                        elif not self.variable_set[abs(newlit)]:
+                            self.sentinels[-lit].remove(cls)
+                            self.sentinels[newlit].add(cls)
+                            other_sentinel = None
+                            break
+
+                # Check if no sentinel update exists
+                if other_sentinel:
+                    self._unit_prop_queue.append(other_sentinel)
+
+    def _undo(self):
+        """
+        _undo the changes of the most recent decision level.
+
+        Examples
+        ========
+
+        >>> from sympy.logic.algorithms.dpll2 import SATSolver
+        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
+        ... {3, -2}], {1, 2, 3}, set())
+        >>> next(l._find_model())
+        {1: True, 2: False, 3: False}
+        >>> level = l._current_level
+        >>> level.decision, level.var_settings, level.flipped
+        (-3, {-3, -2}, False)
+        >>> l._undo()
+        >>> level = l._current_level
+        >>> level.decision, level.var_settings, level.flipped
+        (0, {1}, False)
+
+        """
+        # Undo the variable settings
+        for lit in self._current_level.var_settings:
+            self.var_settings.remove(lit)
+            self.heur_lit_unset(lit)
+            self.variable_set[abs(lit)] = False
+
+        # Pop the level off the stack
+        self.levels.pop()
+
+    #########################
+    #      Propagation      #
+    #########################
+    """
+    Propagation methods should attempt to soundly simplify the boolean
+      theory, and return True if any simplification occurred and False
+      otherwise.
+    """
+    def _simplify(self):
+        """Iterate over the various forms of propagation to simplify the theory.
+
+        Examples
+        ========
+
+        >>> from sympy.logic.algorithms.dpll2 import SATSolver
+        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
+        ... {3, -2}], {1, 2, 3}, set())
+        >>> l.variable_set
+        [False, False, False, False]
+        >>> l.sentinels
+        {-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4}}
+
+        >>> l._simplify()
+
+        >>> l.variable_set
+        [False, True, False, False]
+        >>> l.sentinels
+        {-3: {0, 2}, -2: {3, 4}, -1: set(), 2: {0, 3},
+        ...3: {2, 4}}
+
+        """
+        changed = True
+        while changed:
+            changed = False
+            changed |= self._unit_prop()
+            changed |= self._pure_literal()
+
+    def _unit_prop(self):
+        """Perform unit propagation on the current theory."""
+        result = len(self._unit_prop_queue) > 0
+        while self._unit_prop_queue:
+            next_lit = self._unit_prop_queue.pop()
+            if -next_lit in self.var_settings:
+                self.is_unsatisfied = True
+                self._unit_prop_queue = []
+                return False
+            else:
+                self._assign_literal(next_lit)
+
+        return result
+
+    def _pure_literal(self):
+        """Look for pure literals and assign them when found."""
+        return False
+
+    #########################
+    #      Heuristics       #
+    #########################
+    def _vsids_init(self):
+        """Initialize the data structures needed for the VSIDS heuristic."""
+        self.lit_heap = []
+        self.lit_scores = {}
+
+        for var in range(1, len(self.variable_set)):
+            self.lit_scores[var] = float(-self.occurrence_count[var])
+            self.lit_scores[-var] = float(-self.occurrence_count[-var])
+            heappush(self.lit_heap, (self.lit_scores[var], var))
+            heappush(self.lit_heap, (self.lit_scores[-var], -var))
+
+    def _vsids_decay(self):
+        """Decay the VSIDS scores for every literal.
+
+        Examples
+        ========
+
+        >>> from sympy.logic.algorithms.dpll2 import SATSolver
+        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
+        ... {3, -2}], {1, 2, 3}, set())
+
+        >>> l.lit_scores
+        {-3: -2.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -2.0, 3: -2.0}
+
+        >>> l._vsids_decay()
+
+        >>> l.lit_scores
+        {-3: -1.0, -2: -1.0, -1: 0.0, 1: 0.0, 2: -1.0, 3: -1.0}
+
+        """
+        # We divide every literal score by 2 for a decay factor
+        #  Note: This doesn't change the heap property
+        for lit in self.lit_scores.keys():
+            self.lit_scores[lit] /= 2.0
+
+    def _vsids_calculate(self):
+        """
+            VSIDS Heuristic Calculation
+
+        Examples
+        ========
+
+        >>> from sympy.logic.algorithms.dpll2 import SATSolver
+        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
+        ... {3, -2}], {1, 2, 3}, set())
+
+        >>> l.lit_heap
+        [(-2.0, -3), (-2.0, 2), (-2.0, -2), (0.0, 1), (-2.0, 3), (0.0, -1)]
+
+        >>> l._vsids_calculate()
+        -3
+
+        >>> l.lit_heap
+        [(-2.0, -2), (-2.0, 2), (0.0, -1), (0.0, 1), (-2.0, 3)]
+
+        """
+        if len(self.lit_heap) == 0:
+            return 0
+
+        # Clean out the front of the heap as long the variables are set
+        while self.variable_set[abs(self.lit_heap[0][1])]:
+            heappop(self.lit_heap)
+            if len(self.lit_heap) == 0:
+                return 0
+
+        return heappop(self.lit_heap)[1]
+
+    def _vsids_lit_assigned(self, lit):
+        """Handle the assignment of a literal for the VSIDS heuristic."""
+        pass
+
+    def _vsids_lit_unset(self, lit):
+        """Handle the unsetting of a literal for the VSIDS heuristic.
+
+        Examples
+        ========
+
+        >>> from sympy.logic.algorithms.dpll2 import SATSolver
+        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
+        ... {3, -2}], {1, 2, 3}, set())
+        >>> l.lit_heap
+        [(-2.0, -3), (-2.0, 2), (-2.0, -2), (0.0, 1), (-2.0, 3), (0.0, -1)]
+
+        >>> l._vsids_lit_unset(2)
+
+        >>> l.lit_heap
+        [(-2.0, -3), (-2.0, -2), (-2.0, -2), (-2.0, 2), (-2.0, 3), (0.0, -1),
+        ...(-2.0, 2), (0.0, 1)]
+
+        """
+        var = abs(lit)
+        heappush(self.lit_heap, (self.lit_scores[var], var))
+        heappush(self.lit_heap, (self.lit_scores[-var], -var))
+
+    def _vsids_clause_added(self, cls):
+        """Handle the addition of a new clause for the VSIDS heuristic.
+
+        Examples
+        ========
+
+        >>> from sympy.logic.algorithms.dpll2 import SATSolver
+        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
+        ... {3, -2}], {1, 2, 3}, set())
+
+        >>> l.num_learned_clauses
+        0
+        >>> l.lit_scores
+        {-3: -2.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -2.0, 3: -2.0}
+
+        >>> l._vsids_clause_added({2, -3})
+
+        >>> l.num_learned_clauses
+        1
+        >>> l.lit_scores
+        {-3: -1.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -1.0, 3: -2.0}
+
+        """
+        self.num_learned_clauses += 1
+        for lit in cls:
+            self.lit_scores[lit] += 1
+
+    ########################
+    #   Clause Learning    #
+    ########################
+    def _simple_add_learned_clause(self, cls):
+        """Add a new clause to the theory.
+
+        Examples
+        ========
+
+        >>> from sympy.logic.algorithms.dpll2 import SATSolver
+        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
+        ... {3, -2}], {1, 2, 3}, set())
+
+        >>> l.num_learned_clauses
+        0
+        >>> l.clauses
+        [[2, -3], [1], [3, -3], [2, -2], [3, -2]]
+        >>> l.sentinels
+        {-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4}}
+
+        >>> l._simple_add_learned_clause([3])
+
+        >>> l.clauses
+        [[2, -3], [1], [3, -3], [2, -2], [3, -2], [3]]
+        >>> l.sentinels
+        {-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4, 5}}
+
+        """
+        cls_num = len(self.clauses)
+        self.clauses.append(cls)
+
+        for lit in cls:
+            self.occurrence_count[lit] += 1
+
+        self.sentinels[cls[0]].add(cls_num)
+        self.sentinels[cls[-1]].add(cls_num)
+
+        self.heur_clause_added(cls)
+
+    def _simple_compute_conflict(self):
+        """ Build a clause representing the fact that at least one decision made
+        so far is wrong.
+
+        Examples
+        ========
+
+        >>> from sympy.logic.algorithms.dpll2 import SATSolver
+        >>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
+        ... {3, -2}], {1, 2, 3}, set())
+        >>> next(l._find_model())
+        {1: True, 2: False, 3: False}
+        >>> l._simple_compute_conflict()
+        [3]
+
+        """
+        return [-(level.decision) for level in self.levels[1:]]
+
+    def _simple_clean_clauses(self):
+        """Clean up learned clauses."""
+        pass
+
+
+class Level:
+    """
+    Represents a single level in the DPLL algorithm, and contains
+    enough information for a sound backtracking procedure.
+    """
+
+    def __init__(self, decision, flipped=False):
+        self.decision = decision
+        self.var_settings = set()
+        self.flipped = flipped
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/algorithms/lra_theory.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/algorithms/lra_theory.py
new file mode 100644
index 0000000000000000000000000000000000000000..1690760d36003aed6866f593120c05a5b8f92c83
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/algorithms/lra_theory.py
@@ -0,0 +1,912 @@
+"""Implements "A Fast Linear-Arithmetic Solver for DPLL(T)"
+
+The LRASolver class defined in this file can be used
+in conjunction with a SAT solver to check the
+satisfiability of formulas involving inequalities.
+
+Here's an example of how that would work:
+
+    Suppose you want to check the satisfiability of
+    the following formula:
+
+    >>> from sympy.core.relational import Eq
+    >>> from sympy.abc import x, y
+    >>> f = ((x > 0) | (x < 0)) & (Eq(x, 0) | Eq(y, 1)) & (~Eq(y, 1) | Eq(1, 2))
+
+    First a preprocessing step should be done on f. During preprocessing,
+    f should be checked for any predicates such as `Q.prime` that can't be
+    handled. Also unequality like `~Eq(y, 1)` should be split.
+
+    I should mention that the paper says to split both equalities and
+    unequality, but this implementation only requires that unequality
+    be split.
+
+    >>> f = ((x > 0) | (x < 0)) & (Eq(x, 0) | Eq(y, 1)) & ((y < 1) | (y > 1) | Eq(1, 2))
+
+    Then an LRASolver instance needs to be initialized with this formula.
+
+    >>> from sympy.assumptions.cnf import CNF, EncodedCNF
+    >>> from sympy.assumptions.ask import Q
+    >>> from sympy.logic.algorithms.lra_theory import LRASolver
+    >>> cnf = CNF.from_prop(f)
+    >>> enc = EncodedCNF()
+    >>> enc.add_from_cnf(cnf)
+    >>> lra, conflicts = LRASolver.from_encoded_cnf(enc)
+
+    Any immediate one-lital conflicts clauses will be detected here.
+    In this example, `~Eq(1, 2)` is one such conflict clause. We'll
+    want to add it to `f` so that the SAT solver is forced to
+    assign Eq(1, 2) to False.
+
+    >>> f = f & ~Eq(1, 2)
+
+    Now that the one-literal conflict clauses have been added
+    and an lra object has been initialized, we can pass `f`
+    to a SAT solver. The SAT solver will give us a satisfying
+    assignment such as:
+
+    (1 = 2): False
+    (y = 1): True
+    (y < 1): True
+    (y > 1): True
+    (x = 0): True
+    (x < 0): True
+    (x > 0): True
+
+    Next you would pass this assignment to the LRASolver
+    which will be able to determine that this particular
+    assignment is satisfiable or not.
+
+    Note that since EncodedCNF is inherently non-deterministic,
+    the int each predicate is encoded as is not consistent. As a
+    result, the code below likely does not reflect the assignment
+    given above.
+
+    >>> lra.assert_lit(-1) #doctest: +SKIP
+    >>> lra.assert_lit(2) #doctest: +SKIP
+    >>> lra.assert_lit(3) #doctest: +SKIP
+    >>> lra.assert_lit(4) #doctest: +SKIP
+    >>> lra.assert_lit(5) #doctest: +SKIP
+    >>> lra.assert_lit(6) #doctest: +SKIP
+    >>> lra.assert_lit(7) #doctest: +SKIP
+    >>> is_sat, conflict_or_assignment = lra.check()
+
+    As the particular assignment suggested is not satisfiable,
+    the LRASolver will return unsat and a conflict clause when
+    given that assignment. The conflict clause will always be
+    minimal, but there can be multiple minimal conflict clauses.
+    One possible conflict clause could be `~(x < 0) | ~(x > 0)`.
+
+    We would then add whatever conflict clause is given to
+    `f` to prevent the SAT solver from coming up with an
+    assignment with the same conflicting literals. In this case,
+    the conflict clause `~(x < 0) | ~(x > 0)` would prevent
+    any assignment where both (x < 0) and (x > 0) were both
+    true.
+
+    The SAT solver would then find another assignment
+    and we would check that assignment with the LRASolver
+    and so on. Eventually either a satisfying assignment
+    that the SAT solver and LRASolver agreed on would be found
+    or enough conflict clauses would be added so that the
+    boolean formula was unsatisfiable.
+
+
+This implementation is based on [1]_, which includes a
+detailed explanation of the algorithm and pseudocode
+for the most important functions.
+
+[1]_ also explains how backtracking and theory propagation
+could be implemented to speed up the current implementation,
+but these are not currently implemented.
+
+TODO:
+ - Handle non-rational real numbers
+ - Handle positive and negative infinity
+ - Implement backtracking and theory proposition
+ - Simplify matrix by removing unused variables using Gaussian elimination
+
+References
+==========
+
+.. [1] Dutertre, B., de Moura, L.:
+       A Fast Linear-Arithmetic Solver for DPLL(T)
+       https://link.springer.com/chapter/10.1007/11817963_11
+"""
+from sympy.solvers.solveset import linear_eq_to_matrix
+from sympy.matrices.dense import eye
+from sympy.assumptions import Predicate
+from sympy.assumptions.assume import AppliedPredicate
+from sympy.assumptions.ask import Q
+from sympy.core import Dummy
+from sympy.core.mul import Mul
+from sympy.core.add import Add
+from sympy.core.relational import Eq, Ne
+from sympy.core.sympify import sympify
+from sympy.core.singleton import S
+from sympy.core.numbers import Rational, oo
+from sympy.matrices.dense import Matrix
+
+class UnhandledInput(Exception):
+    """
+    Raised while creating an LRASolver if non-linearity
+    or non-rational numbers are present.
+    """
+
+# predicates that LRASolver understands and makes use of
+ALLOWED_PRED = {Q.eq, Q.gt, Q.lt, Q.le, Q.ge}
+
+# if true ~Q.gt(x, y) implies Q.le(x, y)
+HANDLE_NEGATION = True
+
+class LRASolver():
+    """
+    Linear Arithmetic Solver for DPLL(T) implemented with an algorithm based on
+    the Dual Simplex method. Uses Bland's pivoting rule to avoid cycling.
+
+    References
+    ==========
+
+    .. [1] Dutertre, B., de Moura, L.:
+           A Fast Linear-Arithmetic Solver for DPLL(T)
+           https://link.springer.com/chapter/10.1007/11817963_11
+    """
+
+    def __init__(self, A, slack_variables, nonslack_variables, enc_to_boundary, s_subs, testing_mode):
+        """
+        Use the "from_encoded_cnf" method to create a new LRASolver.
+        """
+        self.run_checks = testing_mode
+        self.s_subs = s_subs  # used only for test_lra_theory.test_random_problems
+
+        if any(not isinstance(a, Rational) for a in A):
+            raise UnhandledInput("Non-rational numbers are not handled")
+        if any(not isinstance(b.bound, Rational) for b in enc_to_boundary.values()):
+            raise UnhandledInput("Non-rational numbers are not handled")
+        m, n = len(slack_variables), len(slack_variables)+len(nonslack_variables)
+        if m != 0:
+            assert A.shape == (m, n)
+        if self.run_checks:
+            assert A[:, n-m:] == -eye(m)
+
+        self.enc_to_boundary = enc_to_boundary  # mapping of int to Boundary objects
+        self.boundary_to_enc = {value: key for key, value in enc_to_boundary.items()}
+        self.A = A
+        self.slack = slack_variables
+        self.nonslack = nonslack_variables
+        self.all_var = nonslack_variables + slack_variables
+
+        self.slack_set = set(slack_variables)
+
+        self.is_sat = True  # While True, all constraints asserted so far are satisfiable
+        self.result = None  # always one of: (True, assignment), (False, conflict clause), None
+
+    @staticmethod
+    def from_encoded_cnf(encoded_cnf, testing_mode=False):
+        """
+        Creates an LRASolver from an EncodedCNF object
+        and a list of conflict clauses for propositions
+        that can be simplified to True or False.
+
+        Parameters
+        ==========
+
+        encoded_cnf : EncodedCNF
+
+        testing_mode : bool
+            Setting testing_mode to True enables some slow assert statements
+            and sorting to reduce nonterministic behavior.
+
+        Returns
+        =======
+
+        (lra, conflicts)
+
+        lra : LRASolver
+
+        conflicts : list
+            Contains a one-literal conflict clause for each proposition
+            that can be simplified to True or False.
+
+        Example
+        =======
+
+        >>> from sympy.core.relational import Eq
+        >>> from sympy.assumptions.cnf import CNF, EncodedCNF
+        >>> from sympy.assumptions.ask import Q
+        >>> from sympy.logic.algorithms.lra_theory import LRASolver
+        >>> from sympy.abc import x, y, z
+        >>> phi = (x >= 0) & ((x + y <= 2) | (x + 2 * y - z >= 6))
+        >>> phi = phi & (Eq(x + y, 2) | (x + 2 * y - z > 4))
+        >>> phi = phi & Q.gt(2, 1)
+        >>> cnf = CNF.from_prop(phi)
+        >>> enc = EncodedCNF()
+        >>> enc.from_cnf(cnf)
+        >>> lra, conflicts = LRASolver.from_encoded_cnf(enc, testing_mode=True)
+        >>> lra #doctest: +SKIP
+        
+        >>> conflicts #doctest: +SKIP
+        [[4]]
+        """
+        # This function has three main jobs:
+        # - raise errors if the input formula is not handled
+        # - preprocesses the formula into a matrix and single variable constraints
+        # - create one-literal conflict clauses from predicates that are always True
+        #   or always False such as Q.gt(3, 2)
+        #
+        # See the preprocessing section of "A Fast Linear-Arithmetic Solver for DPLL(T)"
+        # for an explanation of how the formula is converted into a matrix
+        # and a set of single variable constraints.
+
+        encoding = {}  # maps int to boundary
+        A = []
+
+        basic = []
+        s_count = 0
+        s_subs = {}
+        nonbasic = []
+
+        if testing_mode:
+            # sort to reduce nondeterminism
+            encoded_cnf_items = sorted(encoded_cnf.encoding.items(), key=lambda x: str(x))
+        else:
+            encoded_cnf_items = encoded_cnf.encoding.items()
+
+        empty_var = Dummy()
+        var_to_lra_var = {}
+        conflicts = []
+
+        for prop, enc in encoded_cnf_items:
+            if isinstance(prop, Predicate):
+                prop = prop(empty_var)
+            if not isinstance(prop, AppliedPredicate):
+                if prop == True:
+                    conflicts.append([enc])
+                    continue
+                if prop == False:
+                    conflicts.append([-enc])
+                    continue
+
+                raise ValueError(f"Unhandled Predicate: {prop}")
+
+            assert prop.function in ALLOWED_PRED
+            if prop.lhs == S.NaN or prop.rhs == S.NaN:
+                raise ValueError(f"{prop} contains nan")
+            if prop.lhs.is_imaginary or prop.rhs.is_imaginary:
+                raise UnhandledInput(f"{prop} contains an imaginary component")
+            if prop.lhs == oo or prop.rhs == oo:
+                raise UnhandledInput(f"{prop} contains infinity")
+
+            prop = _eval_binrel(prop)  # simplify variable-less quantities to True / False if possible
+            if prop == True:
+                conflicts.append([enc])
+                continue
+            elif prop == False:
+                conflicts.append([-enc])
+                continue
+            elif prop is None:
+                raise UnhandledInput(f"{prop} could not be simplified")
+
+            expr = prop.lhs - prop.rhs
+            if prop.function in [Q.ge, Q.gt]:
+                expr = -expr
+
+            # expr should be less than (or equal to) 0
+            # otherwise prop is False
+            if prop.function in [Q.le, Q.ge]:
+                bool = (expr <= 0)
+            elif prop.function in [Q.lt, Q.gt]:
+                bool = (expr < 0)
+            else:
+                assert prop.function == Q.eq
+                bool = Eq(expr, 0)
+
+            if bool == True:
+                conflicts.append([enc])
+                continue
+            elif bool == False:
+                conflicts.append([-enc])
+                continue
+
+
+            vars, const = _sep_const_terms(expr)  # example: (2x + 3y + 2) --> (2x + 3y), (2)
+            vars, var_coeff = _sep_const_coeff(vars)  # examples: (2x) --> (x, 2); (2x + 3y) --> (2x + 3y), (1)
+            const = const / var_coeff
+
+            terms = _list_terms(vars)  # example: (2x + 3y) --> [2x, 3y]
+            for term in terms:
+                term, _ = _sep_const_coeff(term)
+                assert len(term.free_symbols) > 0
+                if term not in var_to_lra_var:
+                    var_to_lra_var[term] = LRAVariable(term)
+                    nonbasic.append(term)
+
+            if len(terms) > 1:
+                if vars not in s_subs:
+                    s_count += 1
+                    d = Dummy(f"s{s_count}")
+                    var_to_lra_var[d] = LRAVariable(d)
+                    basic.append(d)
+                    s_subs[vars] = d
+                    A.append(vars - d)
+                var = s_subs[vars]
+            else:
+                var = terms[0]
+
+            assert var_coeff != 0
+
+            equality = prop.function == Q.eq
+            upper = var_coeff > 0 if not equality else None
+            strict = prop.function in [Q.gt, Q.lt]
+            b = Boundary(var_to_lra_var[var], -const, upper, equality, strict)
+            encoding[enc] = b
+
+        fs = [v.free_symbols for v in nonbasic + basic]
+        assert all(len(syms) > 0 for syms in fs)
+        fs_count = sum(len(syms) for syms in fs)
+        if len(fs) > 0 and  len(set.union(*fs)) < fs_count:
+            raise UnhandledInput("Nonlinearity is not handled")
+
+        A, _ = linear_eq_to_matrix(A, nonbasic + basic)
+        nonbasic = [var_to_lra_var[nb] for nb in nonbasic]
+        basic = [var_to_lra_var[b] for b in basic]
+        for idx, var in enumerate(nonbasic + basic):
+            var.col_idx = idx
+
+        return LRASolver(A, basic, nonbasic, encoding, s_subs, testing_mode), conflicts
+
+    def reset_bounds(self):
+        """
+        Resets the state of the LRASolver to before
+        anything was asserted.
+        """
+        self.result = None
+        for var in self.all_var:
+            var.lower = LRARational(-float("inf"), 0)
+            var.lower_from_eq = False
+            var.lower_from_neg = False
+            var.upper = LRARational(float("inf"), 0)
+            var.upper_from_eq= False
+            var.lower_from_neg = False
+            var.assign = LRARational(0, 0)
+
+    def assert_lit(self, enc_constraint):
+        """
+        Assert a literal representing a constraint
+        and update the internal state accordingly.
+
+        Note that due to peculiarities of this implementation
+        asserting ~(x > 0) will assert (x <= 0) but asserting
+        ~Eq(x, 0) will not do anything.
+
+        Parameters
+        ==========
+
+        enc_constraint : int
+            A mapping of encodings to constraints
+            can be found in `self.enc_to_boundary`.
+
+        Returns
+        =======
+
+        None or (False, explanation)
+
+        explanation : set of ints
+            A conflict clause that "explains" why
+            the literals asserted so far are unsatisfiable.
+        """
+        if abs(enc_constraint) not in self.enc_to_boundary:
+            return None
+
+        if not HANDLE_NEGATION and enc_constraint < 0:
+            return None
+
+        boundary = self.enc_to_boundary[abs(enc_constraint)]
+        sym, c, negated = boundary.var, boundary.bound, enc_constraint < 0
+
+        if boundary.equality and negated:
+            return None # negated equality is not handled and should only appear in conflict clauses
+
+        upper = boundary.upper != negated
+        if boundary.strict != negated:
+            delta = -1 if upper else 1
+            c = LRARational(c, delta)
+        else:
+            c = LRARational(c, 0)
+
+        if boundary.equality:
+            res1 = self._assert_lower(sym, c, from_equality=True, from_neg=negated)
+            if res1 and res1[0] == False:
+                res = res1
+            else:
+                res2 = self._assert_upper(sym, c, from_equality=True, from_neg=negated)
+                res =  res2
+        elif upper:
+            res = self._assert_upper(sym, c, from_neg=negated)
+        else:
+            res = self._assert_lower(sym, c, from_neg=negated)
+
+        if self.is_sat and sym not in self.slack_set:
+            self.is_sat = res is None
+        else:
+            self.is_sat = False
+
+        return res
+
+    def _assert_upper(self, xi, ci, from_equality=False, from_neg=False):
+        """
+        Adjusts the upper bound on variable xi if the new upper bound is
+        more limiting. The assignment of variable xi is adjusted to be
+        within the new bound if needed.
+
+        Also calls `self._update` to update the assignment for slack variables
+        to keep all equalities satisfied.
+        """
+        if self.result:
+            assert self.result[0] != False
+        self.result = None
+        if ci >= xi.upper:
+            return None
+        if ci < xi.lower:
+            assert (xi.lower[1] >= 0) is True
+            assert (ci[1] <= 0) is True
+
+            lit1, neg1 = Boundary.from_lower(xi)
+
+            lit2 = Boundary(var=xi, const=ci[0], strict=ci[1] != 0, upper=True, equality=from_equality)
+            if from_neg:
+                lit2 = lit2.get_negated()
+            neg2 = -1 if from_neg else 1
+
+            conflict = [-neg1*self.boundary_to_enc[lit1], -neg2*self.boundary_to_enc[lit2]]
+            self.result = False, conflict
+            return self.result
+        xi.upper = ci
+        xi.upper_from_eq = from_equality
+        xi.upper_from_neg = from_neg
+        if xi in self.nonslack and xi.assign > ci:
+            self._update(xi, ci)
+
+        if self.run_checks and all(v.assign[0] != float("inf") and v.assign[0] != -float("inf")
+                                   for v in self.all_var):
+            M = self.A
+            X = Matrix([v.assign[0] for v in self.all_var])
+            assert all(abs(val) < 10 ** (-10) for val in M * X)
+
+        return None
+
+    def _assert_lower(self, xi, ci, from_equality=False, from_neg=False):
+        """
+        Adjusts the lower bound on variable xi if the new lower bound is
+        more limiting. The assignment of variable xi is adjusted to be
+        within the new bound if needed.
+
+        Also calls `self._update` to update the assignment for slack variables
+        to keep all equalities satisfied.
+        """
+        if self.result:
+            assert self.result[0] != False
+        self.result = None
+        if ci <= xi.lower:
+            return None
+        if ci > xi.upper:
+            assert (xi.upper[1] <= 0) is True
+            assert (ci[1] >= 0) is True
+
+            lit1, neg1 = Boundary.from_upper(xi)
+
+            lit2 = Boundary(var=xi, const=ci[0], strict=ci[1] != 0, upper=False, equality=from_equality)
+            if from_neg:
+                lit2 = lit2.get_negated()
+            neg2 = -1 if from_neg else 1
+
+            conflict = [-neg1*self.boundary_to_enc[lit1],-neg2*self.boundary_to_enc[lit2]]
+            self.result = False, conflict
+            return self.result
+        xi.lower = ci
+        xi.lower_from_eq = from_equality
+        xi.lower_from_neg = from_neg
+        if xi in self.nonslack and xi.assign < ci:
+            self._update(xi, ci)
+
+        if self.run_checks and all(v.assign[0] != float("inf") and v.assign[0] != -float("inf")
+                                   for v in self.all_var):
+            M = self.A
+            X = Matrix([v.assign[0] for v in self.all_var])
+            assert all(abs(val) < 10 ** (-10) for val in M * X)
+
+        return None
+
+    def _update(self, xi, v):
+        """
+        Updates all slack variables that have equations that contain
+        variable xi so that they stay satisfied given xi is equal to v.
+        """
+        i = xi.col_idx
+        for j, b in enumerate(self.slack):
+            aji = self.A[j, i]
+            b.assign = b.assign + (v - xi.assign)*aji
+        xi.assign = v
+
+    def check(self):
+        """
+        Searches for an assignment that satisfies all constraints
+        or determines that no such assignment exists and gives
+        a minimal conflict clause that "explains" why the
+        constraints are unsatisfiable.
+
+        Returns
+        =======
+
+        (True, assignment) or (False, explanation)
+
+        assignment : dict of LRAVariables to values
+            Assigned values are tuples that represent a rational number
+            plus some infinatesimal delta.
+
+        explanation : set of ints
+        """
+        if self.is_sat:
+            return True, {var: var.assign for var in self.all_var}
+        if self.result:
+            return self.result
+
+        from sympy.matrices.dense import Matrix
+        M = self.A.copy()
+        basic = {s: i for i, s in enumerate(self.slack)}  # contains the row index associated with each basic variable
+        nonbasic = set(self.nonslack)
+        while True:
+            if self.run_checks:
+                # nonbasic variables must always be within bounds
+                assert all(((nb.assign >= nb.lower) == True) and ((nb.assign <= nb.upper) == True) for nb in nonbasic)
+
+                # assignments for x must always satisfy Ax = 0
+                # probably have to turn this off when dealing with strict ineq
+                if all(v.assign[0] != float("inf") and v.assign[0] != -float("inf")
+                                   for v in self.all_var):
+                    X = Matrix([v.assign[0] for v in self.all_var])
+                    assert all(abs(val) < 10**(-10) for val in M*X)
+
+                # check upper and lower match this format:
+                # x <= rat + delta iff x < rat
+                # x >= rat - delta iff x > rat
+                # this wouldn't make sense:
+                # x <= rat - delta
+                # x >= rat + delta
+                assert all(x.upper[1] <= 0 for x in self.all_var)
+                assert all(x.lower[1] >= 0 for x in self.all_var)
+
+            cand = [b for b in basic if b.assign < b.lower or b.assign > b.upper]
+
+            if len(cand) == 0:
+                return True, {var: var.assign for var in self.all_var}
+
+            xi = min(cand, key=lambda v: v.col_idx) # Bland's rule
+            i = basic[xi]
+
+            if xi.assign < xi.lower:
+                cand = [nb for nb in nonbasic
+                        if (M[i, nb.col_idx] > 0 and nb.assign < nb.upper)
+                        or (M[i, nb.col_idx] < 0 and nb.assign > nb.lower)]
+                if len(cand) == 0:
+                    N_plus = [nb for nb in nonbasic if M[i, nb.col_idx] > 0]
+                    N_minus = [nb for nb in nonbasic if M[i, nb.col_idx] < 0]
+
+                    conflict = []
+                    conflict += [Boundary.from_upper(nb) for nb in N_plus]
+                    conflict += [Boundary.from_lower(nb) for nb in N_minus]
+                    conflict.append(Boundary.from_lower(xi))
+                    conflict = [-neg*self.boundary_to_enc[c] for c, neg in conflict]
+                    return False, conflict
+                xj = min(cand, key=str)
+                M = self._pivot_and_update(M, basic, nonbasic, xi, xj, xi.lower)
+
+            if xi.assign > xi.upper:
+                cand = [nb for nb in nonbasic
+                        if (M[i, nb.col_idx] < 0 and nb.assign < nb.upper)
+                        or (M[i, nb.col_idx] > 0 and nb.assign > nb.lower)]
+
+                if len(cand) == 0:
+                    N_plus = [nb for nb in nonbasic if M[i, nb.col_idx] > 0]
+                    N_minus = [nb for nb in nonbasic if M[i, nb.col_idx] < 0]
+
+                    conflict = []
+                    conflict += [Boundary.from_upper(nb) for nb in N_minus]
+                    conflict += [Boundary.from_lower(nb) for nb in N_plus]
+                    conflict.append(Boundary.from_upper(xi))
+
+                    conflict = [-neg*self.boundary_to_enc[c] for c, neg in conflict]
+                    return False, conflict
+                xj = min(cand, key=lambda v: v.col_idx)
+                M = self._pivot_and_update(M, basic, nonbasic, xi, xj, xi.upper)
+
+    def _pivot_and_update(self, M, basic, nonbasic, xi, xj, v):
+        """
+        Pivots basic variable xi with nonbasic variable xj,
+        and sets value of xi to v and adjusts the values of all basic variables
+        to keep equations satisfied.
+        """
+        i, j = basic[xi], xj.col_idx
+        assert M[i, j] != 0
+        theta = (v - xi.assign)*(1/M[i, j])
+        xi.assign = v
+        xj.assign = xj.assign + theta
+        for xk in basic:
+            if xk != xi:
+                k = basic[xk]
+                akj = M[k, j]
+                xk.assign = xk.assign + theta*akj
+        # pivot
+        basic[xj] = basic[xi]
+        del basic[xi]
+        nonbasic.add(xi)
+        nonbasic.remove(xj)
+        return self._pivot(M, i, j)
+
+    @staticmethod
+    def _pivot(M, i, j):
+        """
+        Performs a pivot operation about entry i, j of M by performing
+        a series of row operations on a copy of M and returning the result.
+        The original M is left unmodified.
+
+        Conceptually, M represents a system of equations and pivoting
+        can be thought of as rearranging equation i to be in terms of
+        variable j and then substituting in the rest of the equations
+        to get rid of other occurances of variable j.
+
+        Example
+        =======
+
+        >>> from sympy.matrices.dense import Matrix
+        >>> from sympy.logic.algorithms.lra_theory import LRASolver
+        >>> from sympy import var
+        >>> Matrix(3, 3, var('a:i'))
+        Matrix([
+        [a, b, c],
+        [d, e, f],
+        [g, h, i]])
+
+        This matrix is equivalent to:
+        0 = a*x + b*y + c*z
+        0 = d*x + e*y + f*z
+        0 = g*x + h*y + i*z
+
+        >>> LRASolver._pivot(_, 1, 0)
+        Matrix([
+        [ 0, -a*e/d + b, -a*f/d + c],
+        [-1,       -e/d,       -f/d],
+        [ 0,  h - e*g/d,  i - f*g/d]])
+
+        We rearrange equation 1 in terms of variable 0 (x)
+        and substitute to remove x from the other equations.
+
+        0 = 0 + (-a*e/d + b)*y + (-a*f/d + c)*z
+        0 = -x + (-e/d)*y + (-f/d)*z
+        0 = 0 + (h - e*g/d)*y + (i - f*g/d)*z
+        """
+        _, _, Mij = M[i, :], M[:, j], M[i, j]
+        if Mij == 0:
+            raise ZeroDivisionError("Tried to pivot about zero-valued entry.")
+        A = M.copy()
+        A[i, :] = -A[i, :]/Mij
+        for row in range(M.shape[0]):
+            if row != i:
+                A[row, :] = A[row, :] + A[row, j] * A[i, :]
+
+        return A
+
+
+def _sep_const_coeff(expr):
+    """
+    Example
+    =======
+
+    >>> from sympy.logic.algorithms.lra_theory import _sep_const_coeff
+    >>> from sympy.abc import x, y
+    >>> _sep_const_coeff(2*x)
+    (x, 2)
+    >>> _sep_const_coeff(2*x + 3*y)
+    (2*x + 3*y, 1)
+    """
+    if isinstance(expr, Add):
+        return expr, sympify(1)
+
+    if isinstance(expr, Mul):
+        coeffs = expr.args
+    else:
+        coeffs = [expr]
+
+    var, const = [], []
+    for c in coeffs:
+        c = sympify(c)
+        if len(c.free_symbols)==0:
+            const.append(c)
+        else:
+            var.append(c)
+    return Mul(*var), Mul(*const)
+
+
+def _list_terms(expr):
+    if not isinstance(expr, Add):
+        return [expr]
+
+    return expr.args
+
+
+def _sep_const_terms(expr):
+    """
+    Example
+    =======
+
+    >>> from sympy.logic.algorithms.lra_theory import _sep_const_terms
+    >>> from sympy.abc import x, y
+    >>> _sep_const_terms(2*x + 3*y + 2)
+    (2*x + 3*y, 2)
+    """
+    if isinstance(expr, Add):
+        terms = expr.args
+    else:
+        terms = [expr]
+
+    var, const = [], []
+    for t in terms:
+        if len(t.free_symbols) == 0:
+            const.append(t)
+        else:
+            var.append(t)
+    return sum(var), sum(const)
+
+
+def _eval_binrel(binrel):
+    """
+    Simplify binary relation to True / False if possible.
+    """
+    if not (len(binrel.lhs.free_symbols) == 0 and len(binrel.rhs.free_symbols) == 0):
+        return binrel
+    if binrel.function == Q.lt:
+        res = binrel.lhs < binrel.rhs
+    elif binrel.function == Q.gt:
+        res = binrel.lhs > binrel.rhs
+    elif binrel.function == Q.le:
+        res = binrel.lhs <= binrel.rhs
+    elif binrel.function == Q.ge:
+        res = binrel.lhs >= binrel.rhs
+    elif binrel.function == Q.eq:
+        res = Eq(binrel.lhs, binrel.rhs)
+    elif binrel.function == Q.ne:
+        res = Ne(binrel.lhs, binrel.rhs)
+
+    if res == True or res == False:
+        return res
+    else:
+        return None
+
+
+class Boundary:
+    """
+    Represents an upper or lower bound or an equality between a symbol
+    and some constant.
+    """
+    def __init__(self, var, const, upper, equality, strict=None):
+        if not equality in [True, False]:
+            assert equality in [True, False]
+
+
+        self.var = var
+        if isinstance(const, tuple):
+            s = const[1] != 0
+            if strict:
+                assert s == strict
+            self.bound = const[0]
+            self.strict = s
+        else:
+            self.bound = const
+            self.strict = strict
+        self.upper = upper if not equality else None
+        self.equality = equality
+        self.strict = strict
+        assert self.strict is not None
+
+    @staticmethod
+    def from_upper(var):
+        neg = -1 if var.upper_from_neg else 1
+        b = Boundary(var, var.upper[0], True, var.upper_from_eq, var.upper[1] != 0)
+        if neg < 0:
+            b = b.get_negated()
+        return b, neg
+
+    @staticmethod
+    def from_lower(var):
+        neg = -1 if var.lower_from_neg else 1
+        b = Boundary(var, var.lower[0], False, var.lower_from_eq, var.lower[1] != 0)
+        if neg < 0:
+            b = b.get_negated()
+        return b, neg
+
+    def get_negated(self):
+        return Boundary(self.var, self.bound, not self.upper, self.equality, not self.strict)
+
+    def get_inequality(self):
+        if self.equality:
+            return Eq(self.var.var, self.bound)
+        elif self.upper and self.strict:
+            return self.var.var < self.bound
+        elif not self.upper and self.strict:
+            return self.var.var > self.bound
+        elif self.upper:
+            return self.var.var <= self.bound
+        else:
+            return self.var.var >= self.bound
+
+    def __repr__(self):
+        return repr("Boundary(" + repr(self.get_inequality()) + ")")
+
+    def __eq__(self, other):
+        other = (other.var, other.bound, other.strict, other.upper, other.equality)
+        return (self.var, self.bound, self.strict, self.upper, self.equality) == other
+
+    def __hash__(self):
+        return hash((self.var, self.bound, self.strict, self.upper, self.equality))
+
+
+class LRARational():
+    """
+    Represents a rational plus or minus some amount
+    of arbitrary small deltas.
+    """
+    def __init__(self, rational, delta):
+        self.value = (rational, delta)
+
+    def __lt__(self, other):
+        return self.value < other.value
+
+    def __le__(self, other):
+        return self.value <= other.value
+
+    def __eq__(self, other):
+        return self.value == other.value
+
+    def __add__(self, other):
+        return LRARational(self.value[0] + other.value[0], self.value[1] + other.value[1])
+
+    def __sub__(self, other):
+        return LRARational(self.value[0] - other.value[0], self.value[1] - other.value[1])
+
+    def __mul__(self, other):
+        assert not isinstance(other, LRARational)
+        return LRARational(self.value[0] * other, self.value[1] * other)
+
+    def __getitem__(self, index):
+        return self.value[index]
+
+    def __repr__(self):
+        return repr(self.value)
+
+
+class LRAVariable():
+    """
+    Object to keep track of upper and lower bounds
+    on `self.var`.
+    """
+    def __init__(self, var):
+        self.upper = LRARational(float("inf"), 0)
+        self.upper_from_eq = False
+        self.upper_from_neg = False
+        self.lower = LRARational(-float("inf"), 0)
+        self.lower_from_eq = False
+        self.lower_from_neg = False
+        self.assign = LRARational(0,0)
+        self.var = var
+        self.col_idx = None
+
+    def __repr__(self):
+        return repr(self.var)
+
+    def __eq__(self, other):
+        if not isinstance(other, LRAVariable):
+            return False
+        return other.var == self.var
+
+    def __hash__(self):
+        return hash(self.var)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/algorithms/minisat22_wrapper.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/algorithms/minisat22_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d5c1f8f14f04309f7cb8197cc05d01a3c108545
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/algorithms/minisat22_wrapper.py
@@ -0,0 +1,46 @@
+from sympy.assumptions.cnf import EncodedCNF
+
+def minisat22_satisfiable(expr, all_models=False, minimal=False):
+
+    if not isinstance(expr, EncodedCNF):
+        exprs = EncodedCNF()
+        exprs.add_prop(expr)
+        expr = exprs
+
+    from pysat.solvers import Minisat22
+
+    # Return UNSAT when False (encoded as 0) is present in the CNF
+    if {0} in expr.data:
+        if all_models:
+            return (f for f in [False])
+        return False
+
+    r = Minisat22(expr.data)
+
+    if minimal:
+        r.set_phases([-(i+1) for i in range(r.nof_vars())])
+
+    if not r.solve():
+        return False
+
+    if not all_models:
+        return {expr.symbols[abs(lit) - 1]: lit > 0 for lit in r.get_model()}
+
+    else:
+        # Make solutions SymPy compatible by creating a generator
+        def _gen(results):
+            satisfiable = False
+            while results.solve():
+                sol = results.get_model()
+                yield {expr.symbols[abs(lit) - 1]: lit > 0 for lit in sol}
+                if minimal:
+                    results.add_clause([-i for i in sol if i>0])
+                else:
+                    results.add_clause([-i for i in sol])
+                satisfiable = True
+            if not satisfiable:
+                yield False
+            raise StopIteration
+
+
+        return _gen(r)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/algorithms/pycosat_wrapper.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/algorithms/pycosat_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ff498b7e3f6b73d95e9b949598ef32df4ecf226
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/algorithms/pycosat_wrapper.py
@@ -0,0 +1,41 @@
+from sympy.assumptions.cnf import EncodedCNF
+
+
+def pycosat_satisfiable(expr, all_models=False):
+    import pycosat
+    if not isinstance(expr, EncodedCNF):
+        exprs = EncodedCNF()
+        exprs.add_prop(expr)
+        expr = exprs
+
+    # Return UNSAT when False (encoded as 0) is present in the CNF
+    if {0} in expr.data:
+        if all_models:
+            return (f for f in [False])
+        return False
+
+    if not all_models:
+        r = pycosat.solve(expr.data)
+        result = (r != "UNSAT")
+        if not result:
+            return result
+        return {expr.symbols[abs(lit) - 1]: lit > 0 for lit in r}
+    else:
+        r = pycosat.itersolve(expr.data)
+        result = (r != "UNSAT")
+        if not result:
+            return result
+
+        # Make solutions SymPy compatible by creating a generator
+        def _gen(results):
+            satisfiable = False
+            try:
+                while True:
+                    sol = next(results)
+                    yield {expr.symbols[abs(lit) - 1]: lit > 0 for lit in sol}
+                    satisfiable = True
+            except StopIteration:
+                if not satisfiable:
+                    yield False
+
+        return _gen(r)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/algorithms/z3_wrapper.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/algorithms/z3_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe44f713a2edfd5286c0f81b737212146766b11b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/algorithms/z3_wrapper.py
@@ -0,0 +1,115 @@
+from sympy.printing.smtlib import smtlib_code
+from sympy.assumptions.assume import AppliedPredicate
+from sympy.assumptions.cnf import EncodedCNF
+from sympy.assumptions.ask import Q
+
+from sympy.core import Add, Mul
+from sympy.core.relational import Equality, LessThan, GreaterThan, StrictLessThan, StrictGreaterThan
+from sympy.functions.elementary.complexes import Abs
+from sympy.functions.elementary.exponential import Pow
+from sympy.functions.elementary.miscellaneous import Min, Max
+from sympy.logic.boolalg import And, Or, Xor, Implies
+from sympy.logic.boolalg import Not, ITE
+from sympy.assumptions.relation.equality import StrictGreaterThanPredicate, StrictLessThanPredicate, GreaterThanPredicate, LessThanPredicate, EqualityPredicate
+from sympy.external import import_module
+
+def z3_satisfiable(expr, all_models=False):
+    if not isinstance(expr, EncodedCNF):
+        exprs = EncodedCNF()
+        exprs.add_prop(expr)
+        expr = exprs
+
+    z3 = import_module("z3")
+    if z3 is None:
+        raise ImportError("z3 is not installed")
+
+    s = encoded_cnf_to_z3_solver(expr, z3)
+
+    res = str(s.check())
+    if res == "unsat":
+        return False
+    elif res == "sat":
+        return z3_model_to_sympy_model(s.model(), expr)
+    else:
+        return None
+
+
+def z3_model_to_sympy_model(z3_model, enc_cnf):
+    rev_enc = {value : key for key, value in enc_cnf.encoding.items()}
+    return {rev_enc[int(var.name()[1:])] : bool(z3_model[var]) for var in z3_model}
+
+
+def clause_to_assertion(clause):
+    clause_strings = [f"d{abs(lit)}" if lit > 0 else f"(not d{abs(lit)})" for lit in clause]
+    return "(assert (or " + " ".join(clause_strings) + "))"
+
+
+def encoded_cnf_to_z3_solver(enc_cnf, z3):
+    def dummify_bool(pred):
+        return False
+        assert isinstance(pred, AppliedPredicate)
+
+        if pred.function in [Q.positive, Q.negative, Q.zero]:
+            return pred
+        else:
+            return False
+
+    s = z3.Solver()
+
+    declarations = [f"(declare-const d{var} Bool)" for var in enc_cnf.variables]
+    assertions = [clause_to_assertion(clause) for clause in enc_cnf.data]
+
+    symbols = set()
+    for pred, enc in enc_cnf.encoding.items():
+        if not isinstance(pred, AppliedPredicate):
+            continue
+        if pred.function not in (Q.gt, Q.lt, Q.ge, Q.le, Q.ne, Q.eq, Q.positive, Q.negative, Q.extended_negative, Q.extended_positive, Q.zero, Q.nonzero, Q.nonnegative, Q.nonpositive, Q.extended_nonzero, Q.extended_nonnegative, Q.extended_nonpositive):
+            continue
+
+        pred_str = smtlib_code(pred, auto_declare=False, auto_assert=False, known_functions=known_functions)
+
+        symbols |= pred.free_symbols
+        pred = pred_str
+        clause = f"(implies d{enc} {pred})"
+        assertion = "(assert " + clause + ")"
+        assertions.append(assertion)
+
+    for sym in symbols:
+        declarations.append(f"(declare-const {sym} Real)")
+
+    declarations = "\n".join(declarations)
+    assertions = "\n".join(assertions)
+    s.from_string(declarations)
+    s.from_string(assertions)
+
+    return s
+
+
+known_functions = {
+            Add: '+',
+            Mul: '*',
+
+            Equality: '=',
+            LessThan: '<=',
+            GreaterThan: '>=',
+            StrictLessThan: '<',
+            StrictGreaterThan: '>',
+
+            EqualityPredicate(): '=',
+            LessThanPredicate(): '<=',
+            GreaterThanPredicate(): '>=',
+            StrictLessThanPredicate(): '<',
+            StrictGreaterThanPredicate(): '>',
+
+            Abs: 'abs',
+            Min: 'min',
+            Max: 'max',
+            Pow: '^',
+
+            And: 'and',
+            Or: 'or',
+            Xor: 'xor',
+            Not: 'not',
+            ITE: 'ite',
+            Implies: '=>',
+        }
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/boolalg.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/boolalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e11a9b6361ac5d7e355d5d4fb176d8df443e07e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/boolalg.py
@@ -0,0 +1,3587 @@
+"""
+Boolean algebra module for SymPy
+"""
+
+from __future__ import annotations
+from typing import TYPE_CHECKING, overload, Any
+from collections.abc import Iterable, Mapping
+
+from collections import defaultdict
+from itertools import chain, combinations, product, permutations
+from sympy.core.add import Add
+from sympy.core.basic import Basic
+from sympy.core.cache import cacheit
+from sympy.core.containers import Tuple
+from sympy.core.decorators import sympify_method_args, sympify_return
+from sympy.core.function import Application, Derivative
+from sympy.core.kind import BooleanKind, NumberKind
+from sympy.core.numbers import Number
+from sympy.core.operations import LatticeOp
+from sympy.core.singleton import Singleton, S
+from sympy.core.sorting import ordered
+from sympy.core.sympify import _sympy_converter, _sympify, sympify
+from sympy.utilities.iterables import sift, ibin
+from sympy.utilities.misc import filldedent
+
+
+def as_Boolean(e):
+    """Like ``bool``, return the Boolean value of an expression, e,
+    which can be any instance of :py:class:`~.Boolean` or ``bool``.
+
+    Examples
+    ========
+
+    >>> from sympy import true, false, nan
+    >>> from sympy.logic.boolalg import as_Boolean
+    >>> from sympy.abc import x
+    >>> as_Boolean(0) is false
+    True
+    >>> as_Boolean(1) is true
+    True
+    >>> as_Boolean(x)
+    x
+    >>> as_Boolean(2)
+    Traceback (most recent call last):
+    ...
+    TypeError: expecting bool or Boolean, not `2`.
+    >>> as_Boolean(nan)
+    Traceback (most recent call last):
+    ...
+    TypeError: expecting bool or Boolean, not `nan`.
+
+    """
+    from sympy.core.symbol import Symbol
+    if e == True:
+        return true
+    if e == False:
+        return false
+    if isinstance(e, Symbol):
+        z = e.is_zero
+        if z is None:
+            return e
+        return false if z else true
+    if isinstance(e, Boolean):
+        return e
+    raise TypeError('expecting bool or Boolean, not `%s`.' % e)
+
+
+@sympify_method_args
+class Boolean(Basic):
+    """A Boolean object is an object for which logic operations make sense."""
+
+    __slots__ = ()
+
+    kind = BooleanKind
+
+    if TYPE_CHECKING:
+
+        def __new__(cls, *args: Basic | complex) -> Boolean:
+            ...
+
+        @overload # type: ignore
+        def subs(self, arg1: Mapping[Basic | complex, Boolean | complex], arg2: None=None) -> Boolean: ...
+        @overload
+        def subs(self, arg1: Iterable[tuple[Basic | complex, Boolean | complex]], arg2: None=None, **kwargs: Any) -> Boolean: ...
+        @overload
+        def subs(self, arg1: Boolean | complex, arg2: Boolean | complex) -> Boolean: ...
+        @overload
+        def subs(self, arg1: Mapping[Basic | complex, Basic | complex], arg2: None=None, **kwargs: Any) -> Basic: ...
+        @overload
+        def subs(self, arg1: Iterable[tuple[Basic | complex, Basic | complex]], arg2: None=None, **kwargs: Any) -> Basic: ...
+        @overload
+        def subs(self, arg1: Basic | complex, arg2: Basic | complex, **kwargs: Any) -> Basic: ...
+
+        def subs(self, arg1: Mapping[Basic | complex, Basic | complex] | Basic | complex, # type: ignore
+                 arg2: Basic | complex | None = None, **kwargs: Any) -> Basic:
+            ...
+
+        def simplify(self, **kwargs) -> Boolean:
+            ...
+
+    @sympify_return([('other', 'Boolean')], NotImplemented)
+    def __and__(self, other):
+        return And(self, other)
+
+    __rand__ = __and__
+
+    @sympify_return([('other', 'Boolean')], NotImplemented)
+    def __or__(self, other):
+        return Or(self, other)
+
+    __ror__ = __or__
+
+    def __invert__(self):
+        """Overloading for ~"""
+        return Not(self)
+
+    @sympify_return([('other', 'Boolean')], NotImplemented)
+    def __rshift__(self, other):
+        return Implies(self, other)
+
+    @sympify_return([('other', 'Boolean')], NotImplemented)
+    def __lshift__(self, other):
+        return Implies(other, self)
+
+    __rrshift__ = __lshift__
+    __rlshift__ = __rshift__
+
+    @sympify_return([('other', 'Boolean')], NotImplemented)
+    def __xor__(self, other):
+        return Xor(self, other)
+
+    __rxor__ = __xor__
+
+    def equals(self, other):
+        """
+        Returns ``True`` if the given formulas have the same truth table.
+        For two formulas to be equal they must have the same literals.
+
+        Examples
+        ========
+
+        >>> from sympy.abc import A, B, C
+        >>> from sympy import And, Or, Not
+        >>> (A >> B).equals(~B >> ~A)
+        True
+        >>> Not(And(A, B, C)).equals(And(Not(A), Not(B), Not(C)))
+        False
+        >>> Not(And(A, Not(A))).equals(Or(B, Not(B)))
+        False
+
+        """
+        from sympy.logic.inference import satisfiable
+        from sympy.core.relational import Relational
+
+        if self.has(Relational) or other.has(Relational):
+            raise NotImplementedError('handling of relationals')
+        return self.atoms() == other.atoms() and \
+            not satisfiable(Not(Equivalent(self, other)))
+
+    def to_nnf(self, simplify=True):
+        # override where necessary
+        return self
+
+    def as_set(self):
+        """
+        Rewrites Boolean expression in terms of real sets.
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol, Eq, Or, And
+        >>> x = Symbol('x', real=True)
+        >>> Eq(x, 0).as_set()
+        {0}
+        >>> (x > 0).as_set()
+        Interval.open(0, oo)
+        >>> And(-2 < x, x < 2).as_set()
+        Interval.open(-2, 2)
+        >>> Or(x < -2, 2 < x).as_set()
+        Union(Interval.open(-oo, -2), Interval.open(2, oo))
+
+        """
+        from sympy.calculus.util import periodicity
+        from sympy.core.relational import Relational
+
+        free = self.free_symbols
+        if len(free) == 1:
+            x = free.pop()
+            if x.kind is NumberKind:
+                reps = {}
+                for r in self.atoms(Relational):
+                    if periodicity(r, x) not in (0, None):
+                        s = r._eval_as_set()
+                        if s in (S.EmptySet, S.UniversalSet, S.Reals):
+                            reps[r] = s.as_relational(x)
+                            continue
+                        raise NotImplementedError(filldedent('''
+                            as_set is not implemented for relationals
+                            with periodic solutions
+                            '''))
+                new = self.subs(reps)
+                if new.func != self.func:
+                    return new.as_set()  # restart with new obj
+                else:
+                    return new._eval_as_set()
+
+            return self._eval_as_set()
+        else:
+            raise NotImplementedError("Sorry, as_set has not yet been"
+                                      " implemented for multivariate"
+                                      " expressions")
+
+    @property
+    def binary_symbols(self):
+        from sympy.core.relational import Eq, Ne
+        return set().union(*[i.binary_symbols for i in self.args
+                           if i.is_Boolean or i.is_Symbol
+                           or isinstance(i, (Eq, Ne))])
+
+    def _eval_refine(self, assumptions):
+        from sympy.assumptions import ask
+        ret = ask(self, assumptions)
+        if ret is True:
+            return true
+        elif ret is False:
+            return false
+        return None
+
+
+class BooleanAtom(Boolean):
+    """
+    Base class of :py:class:`~.BooleanTrue` and :py:class:`~.BooleanFalse`.
+    """
+    is_Boolean = True
+    is_Atom = True
+    _op_priority = 11  # higher than Expr
+
+    def simplify(self, *a, **kw):
+        return self
+
+    def expand(self, *a, **kw):
+        return self
+
+    @property
+    def canonical(self):
+        return self
+
+    def _noop(self, other=None):
+        raise TypeError('BooleanAtom not allowed in this context.')
+
+    __add__ = _noop
+    __radd__ = _noop
+    __sub__ = _noop
+    __rsub__ = _noop
+    __mul__ = _noop
+    __rmul__ = _noop
+    __pow__ = _noop
+    __rpow__ = _noop
+    __truediv__ = _noop
+    __rtruediv__ = _noop
+    __mod__ = _noop
+    __rmod__ = _noop
+    _eval_power = _noop
+
+    def __lt__(self, other):
+        raise TypeError(filldedent('''
+            A Boolean argument can only be used in
+            Eq and Ne; all other relationals expect
+            real expressions.
+        '''))
+
+    __le__ = __lt__
+    __gt__ = __lt__
+    __ge__ = __lt__
+    # \\\
+
+    def _eval_simplify(self, **kwargs):
+        return self
+
+
+class BooleanTrue(BooleanAtom, metaclass=Singleton):
+    """
+    SymPy version of ``True``, a singleton that can be accessed via ``S.true``.
+
+    This is the SymPy version of ``True``, for use in the logic module. The
+    primary advantage of using ``true`` instead of ``True`` is that shorthand Boolean
+    operations like ``~`` and ``>>`` will work as expected on this class, whereas with
+    True they act bitwise on 1. Functions in the logic module will return this
+    class when they evaluate to true.
+
+    Notes
+    =====
+
+    There is liable to be some confusion as to when ``True`` should
+    be used and when ``S.true`` should be used in various contexts
+    throughout SymPy. An important thing to remember is that
+    ``sympify(True)`` returns ``S.true``. This means that for the most
+    part, you can just use ``True`` and it will automatically be converted
+    to ``S.true`` when necessary, similar to how you can generally use 1
+    instead of ``S.One``.
+
+    The rule of thumb is:
+
+    "If the boolean in question can be replaced by an arbitrary symbolic
+    ``Boolean``, like ``Or(x, y)`` or ``x > 1``, use ``S.true``.
+    Otherwise, use ``True``"
+
+    In other words, use ``S.true`` only on those contexts where the
+    boolean is being used as a symbolic representation of truth.
+    For example, if the object ends up in the ``.args`` of any expression,
+    then it must necessarily be ``S.true`` instead of ``True``, as
+    elements of ``.args`` must be ``Basic``. On the other hand,
+    ``==`` is not a symbolic operation in SymPy, since it always returns
+    ``True`` or ``False``, and does so in terms of structural equality
+    rather than mathematical, so it should return ``True``. The assumptions
+    system should use ``True`` and ``False``. Aside from not satisfying
+    the above rule of thumb, the assumptions system uses a three-valued logic
+    (``True``, ``False``, ``None``), whereas ``S.true`` and ``S.false``
+    represent a two-valued logic. When in doubt, use ``True``.
+
+    "``S.true == True is True``."
+
+    While "``S.true is True``" is ``False``, "``S.true == True``"
+    is ``True``, so if there is any doubt over whether a function or
+    expression will return ``S.true`` or ``True``, just use ``==``
+    instead of ``is`` to do the comparison, and it will work in either
+    case.  Finally, for boolean flags, it's better to just use ``if x``
+    instead of ``if x is True``. To quote PEP 8:
+
+    Do not compare boolean values to ``True`` or ``False``
+    using ``==``.
+
+    * Yes:   ``if greeting:``
+    * No:    ``if greeting == True:``
+    * Worse: ``if greeting is True:``
+
+    Examples
+    ========
+
+    >>> from sympy import sympify, true, false, Or
+    >>> sympify(True)
+    True
+    >>> _ is True, _ is true
+    (False, True)
+
+    >>> Or(true, false)
+    True
+    >>> _ is true
+    True
+
+    Python operators give a boolean result for true but a
+    bitwise result for True
+
+    >>> ~true, ~True  # doctest: +SKIP
+    (False, -2)
+    >>> true >> true, True >> True
+    (True, 0)
+
+    See Also
+    ========
+
+    sympy.logic.boolalg.BooleanFalse
+
+    """
+    def __bool__(self):
+        return True
+
+    def __hash__(self):
+        return hash(True)
+
+    def __eq__(self, other):
+        if other is True:
+            return True
+        if other is False:
+            return False
+        return super().__eq__(other)
+
+    @property
+    def negated(self):
+        return false
+
+    def as_set(self):
+        """
+        Rewrite logic operators and relationals in terms of real sets.
+
+        Examples
+        ========
+
+        >>> from sympy import true
+        >>> true.as_set()
+        UniversalSet
+
+        """
+        return S.UniversalSet
+
+
+class BooleanFalse(BooleanAtom, metaclass=Singleton):
+    """
+    SymPy version of ``False``, a singleton that can be accessed via ``S.false``.
+
+    This is the SymPy version of ``False``, for use in the logic module. The
+    primary advantage of using ``false`` instead of ``False`` is that shorthand
+    Boolean operations like ``~`` and ``>>`` will work as expected on this class,
+    whereas with ``False`` they act bitwise on 0. Functions in the logic module
+    will return this class when they evaluate to false.
+
+    Notes
+    ======
+
+    See the notes section in :py:class:`sympy.logic.boolalg.BooleanTrue`
+
+    Examples
+    ========
+
+    >>> from sympy import sympify, true, false, Or
+    >>> sympify(False)
+    False
+    >>> _ is False, _ is false
+    (False, True)
+
+    >>> Or(true, false)
+    True
+    >>> _ is true
+    True
+
+    Python operators give a boolean result for false but a
+    bitwise result for False
+
+    >>> ~false, ~False  # doctest: +SKIP
+    (True, -1)
+    >>> false >> false, False >> False
+    (True, 0)
+
+    See Also
+    ========
+
+    sympy.logic.boolalg.BooleanTrue
+
+    """
+    def __bool__(self):
+        return False
+
+    def __hash__(self):
+        return hash(False)
+
+    def __eq__(self, other):
+        if other is True:
+            return False
+        if other is False:
+            return True
+        return super().__eq__(other)
+
+    @property
+    def negated(self):
+        return true
+
+    def as_set(self):
+        """
+        Rewrite logic operators and relationals in terms of real sets.
+
+        Examples
+        ========
+
+        >>> from sympy import false
+        >>> false.as_set()
+        EmptySet
+        """
+        return S.EmptySet
+
+
+true = BooleanTrue()
+false = BooleanFalse()
+# We want S.true and S.false to work, rather than S.BooleanTrue and
+# S.BooleanFalse, but making the class and instance names the same causes some
+# major issues (like the inability to import the class directly from this
+# file).
+S.true = true
+S.false = false
+
+_sympy_converter[bool] = lambda x: true if x else false
+
+
+class BooleanFunction(Application, Boolean):
+    """Boolean function is a function that lives in a boolean space
+    It is used as base class for :py:class:`~.And`, :py:class:`~.Or`,
+    :py:class:`~.Not`, etc.
+    """
+    is_Boolean = True
+
+    def _eval_simplify(self, **kwargs):
+        rv = simplify_univariate(self)
+        if not isinstance(rv, BooleanFunction):
+            return rv.simplify(**kwargs)
+        rv = rv.func(*[a.simplify(**kwargs) for a in rv.args])
+        return simplify_logic(rv)
+
+    def simplify(self, **kwargs):
+        from sympy.simplify.simplify import simplify
+        return simplify(self, **kwargs)
+
+    def __lt__(self, other):
+        raise TypeError(filldedent('''
+            A Boolean argument can only be used in
+            Eq and Ne; all other relationals expect
+            real expressions.
+        '''))
+    __le__ = __lt__
+    __ge__ = __lt__
+    __gt__ = __lt__
+
+    @classmethod
+    def binary_check_and_simplify(self, *args):
+        return [as_Boolean(i) for i in args]
+
+    def to_nnf(self, simplify=True):
+        return self._to_nnf(*self.args, simplify=simplify)
+
+    def to_anf(self, deep=True):
+        return self._to_anf(*self.args, deep=deep)
+
+    @classmethod
+    def _to_nnf(cls, *args, **kwargs):
+        simplify = kwargs.get('simplify', True)
+        argset = set()
+        for arg in args:
+            if not is_literal(arg):
+                arg = arg.to_nnf(simplify)
+            if simplify:
+                if isinstance(arg, cls):
+                    arg = arg.args
+                else:
+                    arg = (arg,)
+                for a in arg:
+                    if Not(a) in argset:
+                        return cls.zero
+                    argset.add(a)
+            else:
+                argset.add(arg)
+        return cls(*argset)
+
+    @classmethod
+    def _to_anf(cls, *args, **kwargs):
+        deep = kwargs.get('deep', True)
+        new_args = []
+        for arg in args:
+            if deep:
+                if not is_literal(arg) or isinstance(arg, Not):
+                    arg = arg.to_anf(deep=deep)
+            new_args.append(arg)
+        return cls(*new_args, remove_true=False)
+
+    # the diff method below is copied from Expr class
+    def diff(self, *symbols, **assumptions):
+        assumptions.setdefault("evaluate", True)
+        return Derivative(self, *symbols, **assumptions)
+
+    def _eval_derivative(self, x):
+        if x in self.binary_symbols:
+            from sympy.core.relational import Eq
+            from sympy.functions.elementary.piecewise import Piecewise
+            return Piecewise(
+                (0, Eq(self.subs(x, 0), self.subs(x, 1))),
+                (1, True))
+        elif x in self.free_symbols:
+            # not implemented, see https://www.encyclopediaofmath.org/
+            # index.php/Boolean_differential_calculus
+            pass
+        else:
+            return S.Zero
+
+
+class And(LatticeOp, BooleanFunction):
+    """
+    Logical AND function.
+
+    It evaluates its arguments in order, returning false immediately
+    when an argument is false and true if they are all true.
+
+    Examples
+    ========
+
+    >>> from sympy.abc import x, y
+    >>> from sympy import And
+    >>> x & y
+    x & y
+
+    Notes
+    =====
+
+    The ``&`` operator is provided as a convenience, but note that its use
+    here is different from its normal use in Python, which is bitwise
+    and. Hence, ``And(a, b)`` and ``a & b`` will produce different results if
+    ``a`` and ``b`` are integers.
+
+    >>> And(x, y).subs(x, 1)
+    y
+
+    """
+    zero = false
+    identity = true
+
+    nargs = None
+
+    if TYPE_CHECKING:
+
+        def __new__(cls, *args: Boolean | bool) -> Boolean: # type: ignore
+            ...
+
+        @property
+        def args(self) -> tuple[Boolean, ...]:
+            ...
+
+    @classmethod
+    def _new_args_filter(cls, args):
+        args = BooleanFunction.binary_check_and_simplify(*args)
+        args = LatticeOp._new_args_filter(args, And)
+        newargs = []
+        rel = set()
+        for x in ordered(args):
+            if x.is_Relational:
+                c = x.canonical
+                if c in rel:
+                    continue
+                elif c.negated.canonical in rel:
+                    return [false]
+                else:
+                    rel.add(c)
+            newargs.append(x)
+        return newargs
+
+    def _eval_subs(self, old, new):
+        args = []
+        bad = None
+        for i in self.args:
+            try:
+                i = i.subs(old, new)
+            except TypeError:
+                # store TypeError
+                if bad is None:
+                    bad = i
+                continue
+            if i == False:
+                return false
+            elif i != True:
+                args.append(i)
+        if bad is not None:
+            # let it raise
+            bad.subs(old, new)
+        # If old is And, replace the parts of the arguments with new if all
+        # are there
+        if isinstance(old, And):
+            old_set = set(old.args)
+            if old_set.issubset(args):
+                args = set(args) - old_set
+                args.add(new)
+
+        return self.func(*args)
+
+    def _eval_simplify(self, **kwargs):
+        from sympy.core.relational import Equality, Relational
+        from sympy.solvers.solveset import linear_coeffs
+        # standard simplify
+        rv = super()._eval_simplify(**kwargs)
+        if not isinstance(rv, And):
+            return rv
+
+        # simplify args that are equalities involving
+        # symbols so x == 0 & x == y -> x==0 & y == 0
+        Rel, nonRel = sift(rv.args, lambda i: isinstance(i, Relational),
+                           binary=True)
+        if not Rel:
+            return rv
+        eqs, other = sift(Rel, lambda i: isinstance(i, Equality), binary=True)
+
+        measure = kwargs['measure']
+        if eqs:
+            ratio = kwargs['ratio']
+            reps = {}
+            sifted = {}
+            # group by length of free symbols
+            sifted = sift(ordered([
+                (i.free_symbols, i) for i in eqs]),
+                lambda x: len(x[0]))
+            eqs = []
+            nonlineqs = []
+            while 1 in sifted:
+                for free, e in sifted.pop(1):
+                    x = free.pop()
+                    if (e.lhs != x or x in e.rhs.free_symbols) and x not in reps:
+                        try:
+                            m, b = linear_coeffs(
+                                Add(e.lhs, -e.rhs, evaluate=False), x)
+                            enew = e.func(x, -b/m)
+                            if measure(enew) <= ratio*measure(e):
+                                e = enew
+                            else:
+                                eqs.append(e)
+                                continue
+                        except ValueError:
+                            pass
+                    if x in reps:
+                        eqs.append(e.subs(x, reps[x]))
+                    elif e.lhs == x and x not in e.rhs.free_symbols:
+                        reps[x] = e.rhs
+                        eqs.append(e)
+                    else:
+                        # x is not yet identified, but may be later
+                        nonlineqs.append(e)
+                resifted = defaultdict(list)
+                for k in sifted:
+                    for f, e in sifted[k]:
+                        e = e.xreplace(reps)
+                        f = e.free_symbols
+                        resifted[len(f)].append((f, e))
+                sifted = resifted
+            for k in sifted:
+                eqs.extend([e for f, e in sifted[k]])
+            nonlineqs = [ei.subs(reps) for ei in nonlineqs]
+            other = [ei.subs(reps) for ei in other]
+            rv = rv.func(*([i.canonical for i in (eqs + nonlineqs + other)] + nonRel))
+        patterns = _simplify_patterns_and()
+        threeterm_patterns = _simplify_patterns_and3()
+        return _apply_patternbased_simplification(rv, patterns,
+                                                  measure, false,
+                                                  threeterm_patterns=threeterm_patterns)
+
+    def _eval_as_set(self):
+        from sympy.sets.sets import Intersection
+        return Intersection(*[arg.as_set() for arg in self.args])
+
+    def _eval_rewrite_as_Nor(self, *args, **kwargs):
+        return Nor(*[Not(arg) for arg in self.args])
+
+    def to_anf(self, deep=True):
+        if deep:
+            result = And._to_anf(*self.args, deep=deep)
+            return distribute_xor_over_and(result)
+        return self
+
+
+class Or(LatticeOp, BooleanFunction):
+    """
+    Logical OR function
+
+    It evaluates its arguments in order, returning true immediately
+    when an  argument is true, and false if they are all false.
+
+    Examples
+    ========
+
+    >>> from sympy.abc import x, y
+    >>> from sympy import Or
+    >>> x | y
+    x | y
+
+    Notes
+    =====
+
+    The ``|`` operator is provided as a convenience, but note that its use
+    here is different from its normal use in Python, which is bitwise
+    or. Hence, ``Or(a, b)`` and ``a | b`` will return different things if
+    ``a`` and ``b`` are integers.
+
+    >>> Or(x, y).subs(x, 0)
+    y
+
+    """
+    zero = true
+    identity = false
+
+    if TYPE_CHECKING:
+
+        def __new__(cls, *args: Boolean | bool) -> Boolean: # type: ignore
+            ...
+
+        @property
+        def args(self) -> tuple[Boolean, ...]:
+            ...
+
+    @classmethod
+    def _new_args_filter(cls, args):
+        newargs = []
+        rel = []
+        args = BooleanFunction.binary_check_and_simplify(*args)
+        for x in args:
+            if x.is_Relational:
+                c = x.canonical
+                if c in rel:
+                    continue
+                nc = c.negated.canonical
+                if any(r == nc for r in rel):
+                    return [true]
+                rel.append(c)
+            newargs.append(x)
+        return LatticeOp._new_args_filter(newargs, Or)
+
+    def _eval_subs(self, old, new):
+        args = []
+        bad = None
+        for i in self.args:
+            try:
+                i = i.subs(old, new)
+            except TypeError:
+                # store TypeError
+                if bad is None:
+                    bad = i
+                continue
+            if i == True:
+                return true
+            elif i != False:
+                args.append(i)
+        if bad is not None:
+            # let it raise
+            bad.subs(old, new)
+        # If old is Or, replace the parts of the arguments with new if all
+        # are there
+        if isinstance(old, Or):
+            old_set = set(old.args)
+            if old_set.issubset(args):
+                args = set(args) - old_set
+                args.add(new)
+
+        return self.func(*args)
+
+    def _eval_as_set(self):
+        from sympy.sets.sets import Union
+        return Union(*[arg.as_set() for arg in self.args])
+
+    def _eval_rewrite_as_Nand(self, *args, **kwargs):
+        return Nand(*[Not(arg) for arg in self.args])
+
+    def _eval_simplify(self, **kwargs):
+        from sympy.core.relational import Le, Ge, Eq
+        lege = self.atoms(Le, Ge)
+        if lege:
+            reps = {i: self.func(
+                Eq(i.lhs, i.rhs), i.strict) for i in lege}
+            return self.xreplace(reps)._eval_simplify(**kwargs)
+        # standard simplify
+        rv = super()._eval_simplify(**kwargs)
+        if not isinstance(rv, Or):
+            return rv
+        patterns = _simplify_patterns_or()
+        return _apply_patternbased_simplification(rv, patterns,
+                                                  kwargs['measure'], true)
+
+    def to_anf(self, deep=True):
+        args = range(1, len(self.args) + 1)
+        args = (combinations(self.args, j) for j in args)
+        args = chain.from_iterable(args)  # powerset
+        args = (And(*arg) for arg in args)
+        args = (to_anf(x, deep=deep) if deep else x for x in args)
+        return Xor(*list(args), remove_true=False)
+
+
+class Not(BooleanFunction):
+    """
+    Logical Not function (negation)
+
+
+    Returns ``true`` if the statement is ``false`` or ``False``.
+    Returns ``false`` if the statement is ``true`` or ``True``.
+
+    Examples
+    ========
+
+    >>> from sympy import Not, And, Or
+    >>> from sympy.abc import x, A, B
+    >>> Not(True)
+    False
+    >>> Not(False)
+    True
+    >>> Not(And(True, False))
+    True
+    >>> Not(Or(True, False))
+    False
+    >>> Not(And(And(True, x), Or(x, False)))
+    ~x
+    >>> ~x
+    ~x
+    >>> Not(And(Or(A, B), Or(~A, ~B)))
+    ~((A | B) & (~A | ~B))
+
+    Notes
+    =====
+
+    - The ``~`` operator is provided as a convenience, but note that its use
+      here is different from its normal use in Python, which is bitwise
+      not. In particular, ``~a`` and ``Not(a)`` will be different if ``a`` is
+      an integer. Furthermore, since bools in Python subclass from ``int``,
+      ``~True`` is the same as ``~1`` which is ``-2``, which has a boolean
+      value of True.  To avoid this issue, use the SymPy boolean types
+      ``true`` and ``false``.
+
+    - As of Python 3.12, the bitwise not operator ``~`` used on a
+      Python ``bool`` is deprecated and will emit a warning.
+
+    >>> from sympy import true
+    >>> ~True  # doctest: +SKIP
+    -2
+    >>> ~true
+    False
+
+    """
+
+    is_Not = True
+
+    @classmethod
+    def eval(cls, arg):
+        if isinstance(arg, Number) or arg in (True, False):
+            return false if arg else true
+        if arg.is_Not:
+            return arg.args[0]
+        # Simplify Relational objects.
+        if arg.is_Relational:
+            return arg.negated
+
+    def _eval_as_set(self):
+        """
+        Rewrite logic operators and relationals in terms of real sets.
+
+        Examples
+        ========
+
+        >>> from sympy import Not, Symbol
+        >>> x = Symbol('x')
+        >>> Not(x > 0).as_set()
+        Interval(-oo, 0)
+        """
+        return self.args[0].as_set().complement(S.Reals)
+
+    def to_nnf(self, simplify=True):
+        if is_literal(self):
+            return self
+
+        expr = self.args[0]
+
+        func, args = expr.func, expr.args
+
+        if func == And:
+            return Or._to_nnf(*[Not(arg) for arg in args], simplify=simplify)
+
+        if func == Or:
+            return And._to_nnf(*[Not(arg) for arg in args], simplify=simplify)
+
+        if func == Implies:
+            a, b = args
+            return And._to_nnf(a, Not(b), simplify=simplify)
+
+        if func == Equivalent:
+            return And._to_nnf(Or(*args), Or(*[Not(arg) for arg in args]),
+                               simplify=simplify)
+
+        if func == Xor:
+            result = []
+            for i in range(1, len(args)+1, 2):
+                for neg in combinations(args, i):
+                    clause = [Not(s) if s in neg else s for s in args]
+                    result.append(Or(*clause))
+            return And._to_nnf(*result, simplify=simplify)
+
+        if func == ITE:
+            a, b, c = args
+            return And._to_nnf(Or(a, Not(c)), Or(Not(a), Not(b)), simplify=simplify)
+
+        raise ValueError("Illegal operator %s in expression" % func)
+
+    def to_anf(self, deep=True):
+        return Xor._to_anf(true, self.args[0], deep=deep)
+
+
+class Xor(BooleanFunction):
+    """
+    Logical XOR (exclusive OR) function.
+
+
+    Returns True if an odd number of the arguments are True and the rest are
+    False.
+
+    Returns False if an even number of the arguments are True and the rest are
+    False.
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import Xor
+    >>> from sympy import symbols
+    >>> x, y = symbols('x y')
+    >>> Xor(True, False)
+    True
+    >>> Xor(True, True)
+    False
+    >>> Xor(True, False, True, True, False)
+    True
+    >>> Xor(True, False, True, False)
+    False
+    >>> x ^ y
+    x ^ y
+
+    Notes
+    =====
+
+    The ``^`` operator is provided as a convenience, but note that its use
+    here is different from its normal use in Python, which is bitwise xor. In
+    particular, ``a ^ b`` and ``Xor(a, b)`` will be different if ``a`` and
+    ``b`` are integers.
+
+    >>> Xor(x, y).subs(y, 0)
+    x
+
+    """
+    def __new__(cls, *args, remove_true=True, **kwargs):
+        argset = set()
+        obj = super().__new__(cls, *args, **kwargs)
+        for arg in obj._args:
+            if isinstance(arg, Number) or arg in (True, False):
+                if arg:
+                    arg = true
+                else:
+                    continue
+            if isinstance(arg, Xor):
+                for a in arg.args:
+                    argset.remove(a) if a in argset else argset.add(a)
+            elif arg in argset:
+                argset.remove(arg)
+            else:
+                argset.add(arg)
+        rel = [(r, r.canonical, r.negated.canonical)
+               for r in argset if r.is_Relational]
+        odd = False  # is number of complimentary pairs odd? start 0 -> False
+        remove = []
+        for i, (r, c, nc) in enumerate(rel):
+            for j in range(i + 1, len(rel)):
+                rj, cj = rel[j][:2]
+                if cj == nc:
+                    odd = not odd
+                    break
+                elif cj == c:
+                    break
+            else:
+                continue
+            remove.append((r, rj))
+        if odd:
+            argset.remove(true) if true in argset else argset.add(true)
+        for a, b in remove:
+            argset.remove(a)
+            argset.remove(b)
+        if len(argset) == 0:
+            return false
+        elif len(argset) == 1:
+            return argset.pop()
+        elif True in argset and remove_true:
+            argset.remove(True)
+            return Not(Xor(*argset))
+        else:
+            obj._args = tuple(ordered(argset))
+            obj._argset = frozenset(argset)
+            return obj
+
+    # XXX: This should be cached on the object rather than using cacheit
+    # Maybe it can be computed in __new__?
+    @property  # type: ignore
+    @cacheit
+    def args(self):
+        return tuple(ordered(self._argset))
+
+    def to_nnf(self, simplify=True):
+        args = []
+        for i in range(0, len(self.args)+1, 2):
+            for neg in combinations(self.args, i):
+                clause = [Not(s) if s in neg else s for s in self.args]
+                args.append(Or(*clause))
+        return And._to_nnf(*args, simplify=simplify)
+
+    def _eval_rewrite_as_Or(self, *args, **kwargs):
+        a = self.args
+        return Or(*[_convert_to_varsSOP(x, self.args)
+                    for x in _get_odd_parity_terms(len(a))])
+
+    def _eval_rewrite_as_And(self, *args, **kwargs):
+        a = self.args
+        return And(*[_convert_to_varsPOS(x, self.args)
+                     for x in _get_even_parity_terms(len(a))])
+
+    def _eval_simplify(self, **kwargs):
+        # as standard simplify uses simplify_logic which writes things as
+        # And and Or, we only simplify the partial expressions before using
+        # patterns
+        rv = self.func(*[a.simplify(**kwargs) for a in self.args])
+        rv = rv.to_anf()
+        if not isinstance(rv, Xor):  # This shouldn't really happen here
+            return rv
+        patterns = _simplify_patterns_xor()
+        return _apply_patternbased_simplification(rv, patterns,
+                                                  kwargs['measure'], None)
+
+    def _eval_subs(self, old, new):
+        # If old is Xor, replace the parts of the arguments with new if all
+        # are there
+        if isinstance(old, Xor):
+            old_set = set(old.args)
+            if old_set.issubset(self.args):
+                args = set(self.args) - old_set
+                args.add(new)
+                return self.func(*args)
+
+
+class Nand(BooleanFunction):
+    """
+    Logical NAND function.
+
+    It evaluates its arguments in order, giving True immediately if any
+    of them are False, and False if they are all True.
+
+    Returns True if any of the arguments are False
+    Returns False if all arguments are True
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import Nand
+    >>> from sympy import symbols
+    >>> x, y = symbols('x y')
+    >>> Nand(False, True)
+    True
+    >>> Nand(True, True)
+    False
+    >>> Nand(x, y)
+    ~(x & y)
+
+    """
+    @classmethod
+    def eval(cls, *args):
+        return Not(And(*args))
+
+
+class Nor(BooleanFunction):
+    """
+    Logical NOR function.
+
+    It evaluates its arguments in order, giving False immediately if any
+    of them are True, and True if they are all False.
+
+    Returns False if any argument is True
+    Returns True if all arguments are False
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import Nor
+    >>> from sympy import symbols
+    >>> x, y = symbols('x y')
+
+    >>> Nor(True, False)
+    False
+    >>> Nor(True, True)
+    False
+    >>> Nor(False, True)
+    False
+    >>> Nor(False, False)
+    True
+    >>> Nor(x, y)
+    ~(x | y)
+
+    """
+    @classmethod
+    def eval(cls, *args):
+        return Not(Or(*args))
+
+
+class Xnor(BooleanFunction):
+    """
+    Logical XNOR function.
+
+    Returns False if an odd number of the arguments are True and the rest are
+    False.
+
+    Returns True if an even number of the arguments are True and the rest are
+    False.
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import Xnor
+    >>> from sympy import symbols
+    >>> x, y = symbols('x y')
+    >>> Xnor(True, False)
+    False
+    >>> Xnor(True, True)
+    True
+    >>> Xnor(True, False, True, True, False)
+    False
+    >>> Xnor(True, False, True, False)
+    True
+
+    """
+    @classmethod
+    def eval(cls, *args):
+        return Not(Xor(*args))
+
+
+class Implies(BooleanFunction):
+    r"""
+    Logical implication.
+
+    A implies B is equivalent to if A then B. Mathematically, it is written
+    as `A \Rightarrow B` and is equivalent to `\neg A \vee B` or ``~A | B``.
+
+    Accepts two Boolean arguments; A and B.
+    Returns False if A is True and B is False
+    Returns True otherwise.
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import Implies
+    >>> from sympy import symbols
+    >>> x, y = symbols('x y')
+
+    >>> Implies(True, False)
+    False
+    >>> Implies(False, False)
+    True
+    >>> Implies(True, True)
+    True
+    >>> Implies(False, True)
+    True
+    >>> x >> y
+    Implies(x, y)
+    >>> y << x
+    Implies(x, y)
+
+    Notes
+    =====
+
+    The ``>>`` and ``<<`` operators are provided as a convenience, but note
+    that their use here is different from their normal use in Python, which is
+    bit shifts. Hence, ``Implies(a, b)`` and ``a >> b`` will return different
+    things if ``a`` and ``b`` are integers.  In particular, since Python
+    considers ``True`` and ``False`` to be integers, ``True >> True`` will be
+    the same as ``1 >> 1``, i.e., 0, which has a truth value of False.  To
+    avoid this issue, use the SymPy objects ``true`` and ``false``.
+
+    >>> from sympy import true, false
+    >>> True >> False
+    1
+    >>> true >> false
+    False
+
+    """
+    @classmethod
+    def eval(cls, *args):
+        try:
+            newargs = []
+            for x in args:
+                if isinstance(x, Number) or x in (0, 1):
+                    newargs.append(bool(x))
+                else:
+                    newargs.append(x)
+            A, B = newargs
+        except ValueError:
+            raise ValueError(
+                "%d operand(s) used for an Implies "
+                "(pairs are required): %s" % (len(args), str(args)))
+        if A in (True, False) or B in (True, False):
+            return Or(Not(A), B)
+        elif A == B:
+            return true
+        elif A.is_Relational and B.is_Relational:
+            if A.canonical == B.canonical:
+                return true
+            if A.negated.canonical == B.canonical:
+                return B
+        else:
+            return Basic.__new__(cls, *args)
+
+    def to_nnf(self, simplify=True):
+        a, b = self.args
+        return Or._to_nnf(Not(a), b, simplify=simplify)
+
+    def to_anf(self, deep=True):
+        a, b = self.args
+        return Xor._to_anf(true, a, And(a, b), deep=deep)
+
+
+class Equivalent(BooleanFunction):
+    """
+    Equivalence relation.
+
+    ``Equivalent(A, B)`` is True iff A and B are both True or both False.
+
+    Returns True if all of the arguments are logically equivalent.
+    Returns False otherwise.
+
+    For two arguments, this is equivalent to :py:class:`~.Xnor`.
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import Equivalent, And
+    >>> from sympy.abc import x
+    >>> Equivalent(False, False, False)
+    True
+    >>> Equivalent(True, False, False)
+    False
+    >>> Equivalent(x, And(x, True))
+    True
+
+    """
+    def __new__(cls, *args, **options):
+        from sympy.core.relational import Relational
+        args = [_sympify(arg) for arg in args]
+
+        argset = set(args)
+        for x in args:
+            if isinstance(x, Number) or x in [True, False]:  # Includes 0, 1
+                argset.discard(x)
+                argset.add(bool(x))
+        rel = []
+        for r in argset:
+            if isinstance(r, Relational):
+                rel.append((r, r.canonical, r.negated.canonical))
+        remove = []
+        for i, (r, c, nc) in enumerate(rel):
+            for j in range(i + 1, len(rel)):
+                rj, cj = rel[j][:2]
+                if cj == nc:
+                    return false
+                elif cj == c:
+                    remove.append((r, rj))
+                    break
+        for a, b in remove:
+            argset.remove(a)
+            argset.remove(b)
+            argset.add(True)
+        if len(argset) <= 1:
+            return true
+        if True in argset:
+            argset.discard(True)
+            return And(*argset)
+        if False in argset:
+            argset.discard(False)
+            return And(*[Not(arg) for arg in argset])
+        _args = frozenset(argset)
+        obj = super().__new__(cls, _args)
+        obj._argset = _args
+        return obj
+
+    # XXX: This should be cached on the object rather than using cacheit
+    # Maybe it can be computed in __new__?
+    @property  # type: ignore
+    @cacheit
+    def args(self):
+        return tuple(ordered(self._argset))
+
+    def to_nnf(self, simplify=True):
+        args = []
+        for a, b in zip(self.args, self.args[1:]):
+            args.append(Or(Not(a), b))
+        args.append(Or(Not(self.args[-1]), self.args[0]))
+        return And._to_nnf(*args, simplify=simplify)
+
+    def to_anf(self, deep=True):
+        a = And(*self.args)
+        b = And(*[to_anf(Not(arg), deep=False) for arg in self.args])
+        b = distribute_xor_over_and(b)
+        return Xor._to_anf(a, b, deep=deep)
+
+
+class ITE(BooleanFunction):
+    """
+    If-then-else clause.
+
+    ``ITE(A, B, C)`` evaluates and returns the result of B if A is true
+    else it returns the result of C. All args must be Booleans.
+
+    From a logic gate perspective, ITE corresponds to a 2-to-1 multiplexer,
+    where A is the select signal.
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import ITE, And, Xor, Or
+    >>> from sympy.abc import x, y, z
+    >>> ITE(True, False, True)
+    False
+    >>> ITE(Or(True, False), And(True, True), Xor(True, True))
+    True
+    >>> ITE(x, y, z)
+    ITE(x, y, z)
+    >>> ITE(True, x, y)
+    x
+    >>> ITE(False, x, y)
+    y
+    >>> ITE(x, y, y)
+    y
+
+    Trying to use non-Boolean args will generate a TypeError:
+
+    >>> ITE(True, [], ())
+    Traceback (most recent call last):
+    ...
+    TypeError: expecting bool, Boolean or ITE, not `[]`
+
+    """
+    def __new__(cls, *args, **kwargs):
+        from sympy.core.relational import Eq, Ne
+        if len(args) != 3:
+            raise ValueError('expecting exactly 3 args')
+        a, b, c = args
+        # check use of binary symbols
+        if isinstance(a, (Eq, Ne)):
+            # in this context, we can evaluate the Eq/Ne
+            # if one arg is a binary symbol and the other
+            # is true/false
+            b, c = map(as_Boolean, (b, c))
+            bin_syms = set().union(*[i.binary_symbols for i in (b, c)])
+            if len(set(a.args) - bin_syms) == 1:
+                # one arg is a binary_symbols
+                _a = a
+                if a.lhs is true:
+                    a = a.rhs
+                elif a.rhs is true:
+                    a = a.lhs
+                elif a.lhs is false:
+                    a = Not(a.rhs)
+                elif a.rhs is false:
+                    a = Not(a.lhs)
+                else:
+                    # binary can only equal True or False
+                    a = false
+                if isinstance(_a, Ne):
+                    a = Not(a)
+        else:
+            a, b, c = BooleanFunction.binary_check_and_simplify(
+                a, b, c)
+        rv = None
+        if kwargs.get('evaluate', True):
+            rv = cls.eval(a, b, c)
+        if rv is None:
+            rv = BooleanFunction.__new__(cls, a, b, c, evaluate=False)
+        return rv
+
+    @classmethod
+    def eval(cls, *args):
+        from sympy.core.relational import Eq, Ne
+        # do the args give a singular result?
+        a, b, c = args
+        if isinstance(a, (Ne, Eq)):
+            _a = a
+            if true in a.args:
+                a = a.lhs if a.rhs is true else a.rhs
+            elif false in a.args:
+                a = Not(a.lhs) if a.rhs is false else Not(a.rhs)
+            else:
+                _a = None
+            if _a is not None and isinstance(_a, Ne):
+                a = Not(a)
+        if a is true:
+            return b
+        if a is false:
+            return c
+        if b == c:
+            return b
+        else:
+            # or maybe the results allow the answer to be expressed
+            # in terms of the condition
+            if b is true and c is false:
+                return a
+            if b is false and c is true:
+                return Not(a)
+        if [a, b, c] != args:
+            return cls(a, b, c, evaluate=False)
+
+    def to_nnf(self, simplify=True):
+        a, b, c = self.args
+        return And._to_nnf(Or(Not(a), b), Or(a, c), simplify=simplify)
+
+    def _eval_as_set(self):
+        return self.to_nnf().as_set()
+
+    def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
+        from sympy.functions.elementary.piecewise import Piecewise
+        return Piecewise((args[1], args[0]), (args[2], True))
+
+
+class Exclusive(BooleanFunction):
+    """
+    True if only one or no argument is true.
+
+    ``Exclusive(A, B, C)`` is equivalent to ``~(A & B) & ~(A & C) & ~(B & C)``.
+
+    For two arguments, this is equivalent to :py:class:`~.Xor`.
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import Exclusive
+    >>> Exclusive(False, False, False)
+    True
+    >>> Exclusive(False, True, False)
+    True
+    >>> Exclusive(False, True, True)
+    False
+
+    """
+    @classmethod
+    def eval(cls, *args):
+        and_args = []
+        for a, b in combinations(args, 2):
+            and_args.append(Not(And(a, b)))
+        return And(*and_args)
+
+
+# end class definitions. Some useful methods
+
+
+def conjuncts(expr):
+    """Return a list of the conjuncts in ``expr``.
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import conjuncts
+    >>> from sympy.abc import A, B
+    >>> conjuncts(A & B)
+    frozenset({A, B})
+    >>> conjuncts(A | B)
+    frozenset({A | B})
+
+    """
+    return And.make_args(expr)
+
+
+def disjuncts(expr):
+    """Return a list of the disjuncts in ``expr``.
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import disjuncts
+    >>> from sympy.abc import A, B
+    >>> disjuncts(A | B)
+    frozenset({A, B})
+    >>> disjuncts(A & B)
+    frozenset({A & B})
+
+    """
+    return Or.make_args(expr)
+
+
+def distribute_and_over_or(expr):
+    """
+    Given a sentence ``expr`` consisting of conjunctions and disjunctions
+    of literals, return an equivalent sentence in CNF.
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import distribute_and_over_or, And, Or, Not
+    >>> from sympy.abc import A, B, C
+    >>> distribute_and_over_or(Or(A, And(Not(B), Not(C))))
+    (A | ~B) & (A | ~C)
+
+    """
+    return _distribute((expr, And, Or))
+
+
+def distribute_or_over_and(expr):
+    """
+    Given a sentence ``expr`` consisting of conjunctions and disjunctions
+    of literals, return an equivalent sentence in DNF.
+
+    Note that the output is NOT simplified.
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import distribute_or_over_and, And, Or, Not
+    >>> from sympy.abc import A, B, C
+    >>> distribute_or_over_and(And(Or(Not(A), B), C))
+    (B & C) | (C & ~A)
+
+    """
+    return _distribute((expr, Or, And))
+
+
+def distribute_xor_over_and(expr):
+    """
+    Given a sentence ``expr`` consisting of conjunction and
+    exclusive disjunctions of literals, return an
+    equivalent exclusive disjunction.
+
+    Note that the output is NOT simplified.
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import distribute_xor_over_and, And, Xor, Not
+    >>> from sympy.abc import A, B, C
+    >>> distribute_xor_over_and(And(Xor(Not(A), B), C))
+    (B & C) ^ (C & ~A)
+    """
+    return _distribute((expr, Xor, And))
+
+
+def _distribute(info):
+    """
+    Distributes ``info[1]`` over ``info[2]`` with respect to ``info[0]``.
+    """
+    if isinstance(info[0], info[2]):
+        for arg in info[0].args:
+            if isinstance(arg, info[1]):
+                conj = arg
+                break
+        else:
+            return info[0]
+        rest = info[2](*[a for a in info[0].args if a is not conj])
+        return info[1](*list(map(_distribute,
+                                 [(info[2](c, rest), info[1], info[2])
+                                  for c in conj.args])), remove_true=False)
+    elif isinstance(info[0], info[1]):
+        return info[1](*list(map(_distribute,
+                                 [(x, info[1], info[2])
+                                  for x in info[0].args])),
+                       remove_true=False)
+    else:
+        return info[0]
+
+
+def to_anf(expr, deep=True):
+    r"""
+    Converts expr to Algebraic Normal Form (ANF).
+
+    ANF is a canonical normal form, which means that two
+    equivalent formulas will convert to the same ANF.
+
+    A logical expression is in ANF if it has the form
+
+    .. math:: 1 \oplus a \oplus b \oplus ab \oplus abc
+
+    i.e. it can be:
+        - purely true,
+        - purely false,
+        - conjunction of variables,
+        - exclusive disjunction.
+
+    The exclusive disjunction can only contain true, variables
+    or conjunction of variables. No negations are permitted.
+
+    If ``deep`` is ``False``, arguments of the boolean
+    expression are considered variables, i.e. only the
+    top-level expression is converted to ANF.
+
+    Examples
+    ========
+    >>> from sympy.logic.boolalg import And, Or, Not, Implies, Equivalent
+    >>> from sympy.logic.boolalg import to_anf
+    >>> from sympy.abc import A, B, C
+    >>> to_anf(Not(A))
+    A ^ True
+    >>> to_anf(And(Or(A, B), Not(C)))
+    A ^ B ^ (A & B) ^ (A & C) ^ (B & C) ^ (A & B & C)
+    >>> to_anf(Implies(Not(A), Equivalent(B, C)), deep=False)
+    True ^ ~A ^ (~A & (Equivalent(B, C)))
+
+    """
+    expr = sympify(expr)
+
+    if is_anf(expr):
+        return expr
+    return expr.to_anf(deep=deep)
+
+
+def to_nnf(expr, simplify=True):
+    """
+    Converts ``expr`` to Negation Normal Form (NNF).
+
+    A logical expression is in NNF if it
+    contains only :py:class:`~.And`, :py:class:`~.Or` and :py:class:`~.Not`,
+    and :py:class:`~.Not` is applied only to literals.
+    If ``simplify`` is ``True``, the result contains no redundant clauses.
+
+    Examples
+    ========
+
+    >>> from sympy.abc import A, B, C, D
+    >>> from sympy.logic.boolalg import Not, Equivalent, to_nnf
+    >>> to_nnf(Not((~A & ~B) | (C & D)))
+    (A | B) & (~C | ~D)
+    >>> to_nnf(Equivalent(A >> B, B >> A))
+    (A | ~B | (A & ~B)) & (B | ~A | (B & ~A))
+
+    """
+    if is_nnf(expr, simplify):
+        return expr
+    return expr.to_nnf(simplify)
+
+
+def to_cnf(expr, simplify=False, force=False):
+    """
+    Convert a propositional logical sentence ``expr`` to conjunctive normal
+    form: ``((A | ~B | ...) & (B | C | ...) & ...)``.
+    If ``simplify`` is ``True``, ``expr`` is evaluated to its simplest CNF
+    form using the Quine-McCluskey algorithm; this may take a long
+    time. If there are more than 8 variables the ``force`` flag must be set
+    to ``True`` to simplify (default is ``False``).
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import to_cnf
+    >>> from sympy.abc import A, B, D
+    >>> to_cnf(~(A | B) | D)
+    (D | ~A) & (D | ~B)
+    >>> to_cnf((A | B) & (A | ~A), True)
+    A | B
+
+    """
+    expr = sympify(expr)
+    if not isinstance(expr, BooleanFunction):
+        return expr
+
+    if simplify:
+        if not force and len(_find_predicates(expr)) > 8:
+            raise ValueError(filldedent('''
+            To simplify a logical expression with more
+            than 8 variables may take a long time and requires
+            the use of `force=True`.'''))
+        return simplify_logic(expr, 'cnf', True, force=force)
+
+    # Don't convert unless we have to
+    if is_cnf(expr):
+        return expr
+
+    expr = eliminate_implications(expr)
+    res = distribute_and_over_or(expr)
+
+    return res
+
+
+def to_dnf(expr, simplify=False, force=False):
+    """
+    Convert a propositional logical sentence ``expr`` to disjunctive normal
+    form: ``((A & ~B & ...) | (B & C & ...) | ...)``.
+    If ``simplify`` is ``True``, ``expr`` is evaluated to its simplest DNF form using
+    the Quine-McCluskey algorithm; this may take a long
+    time. If there are more than 8 variables, the ``force`` flag must be set to
+    ``True`` to simplify (default is ``False``).
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import to_dnf
+    >>> from sympy.abc import A, B, C
+    >>> to_dnf(B & (A | C))
+    (A & B) | (B & C)
+    >>> to_dnf((A & B) | (A & ~B) | (B & C) | (~B & C), True)
+    A | C
+
+    """
+    expr = sympify(expr)
+    if not isinstance(expr, BooleanFunction):
+        return expr
+
+    if simplify:
+        if not force and len(_find_predicates(expr)) > 8:
+            raise ValueError(filldedent('''
+            To simplify a logical expression with more
+            than 8 variables may take a long time and requires
+            the use of `force=True`.'''))
+        return simplify_logic(expr, 'dnf', True, force=force)
+
+    # Don't convert unless we have to
+    if is_dnf(expr):
+        return expr
+
+    expr = eliminate_implications(expr)
+    return distribute_or_over_and(expr)
+
+
+def is_anf(expr):
+    r"""
+    Checks if ``expr``  is in Algebraic Normal Form (ANF).
+
+    A logical expression is in ANF if it has the form
+
+    .. math:: 1 \oplus a \oplus b \oplus ab \oplus abc
+
+    i.e. it is purely true, purely false, conjunction of
+    variables or exclusive disjunction. The exclusive
+    disjunction can only contain true, variables or
+    conjunction of variables. No negations are permitted.
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import And, Not, Xor, true, is_anf
+    >>> from sympy.abc import A, B, C
+    >>> is_anf(true)
+    True
+    >>> is_anf(A)
+    True
+    >>> is_anf(And(A, B, C))
+    True
+    >>> is_anf(Xor(A, Not(B)))
+    False
+
+    """
+    expr = sympify(expr)
+
+    if is_literal(expr) and not isinstance(expr, Not):
+        return True
+
+    if isinstance(expr, And):
+        for arg in expr.args:
+            if not arg.is_Symbol:
+                return False
+        return True
+
+    elif isinstance(expr, Xor):
+        for arg in expr.args:
+            if isinstance(arg, And):
+                for a in arg.args:
+                    if not a.is_Symbol:
+                        return False
+            elif is_literal(arg):
+                if isinstance(arg, Not):
+                    return False
+            else:
+                return False
+        return True
+
+    else:
+        return False
+
+
+def is_nnf(expr, simplified=True):
+    """
+    Checks if ``expr`` is in Negation Normal Form (NNF).
+
+    A logical expression is in NNF if it
+    contains only :py:class:`~.And`, :py:class:`~.Or` and :py:class:`~.Not`,
+    and :py:class:`~.Not` is applied only to literals.
+    If ``simplified`` is ``True``, checks if result contains no redundant clauses.
+
+    Examples
+    ========
+
+    >>> from sympy.abc import A, B, C
+    >>> from sympy.logic.boolalg import Not, is_nnf
+    >>> is_nnf(A & B | ~C)
+    True
+    >>> is_nnf((A | ~A) & (B | C))
+    False
+    >>> is_nnf((A | ~A) & (B | C), False)
+    True
+    >>> is_nnf(Not(A & B) | C)
+    False
+    >>> is_nnf((A >> B) & (B >> A))
+    False
+
+    """
+
+    expr = sympify(expr)
+    if is_literal(expr):
+        return True
+
+    stack = [expr]
+
+    while stack:
+        expr = stack.pop()
+        if expr.func in (And, Or):
+            if simplified:
+                args = expr.args
+                for arg in args:
+                    if Not(arg) in args:
+                        return False
+            stack.extend(expr.args)
+
+        elif not is_literal(expr):
+            return False
+
+    return True
+
+
+def is_cnf(expr):
+    """
+    Test whether or not an expression is in conjunctive normal form.
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import is_cnf
+    >>> from sympy.abc import A, B, C
+    >>> is_cnf(A | B | C)
+    True
+    >>> is_cnf(A & B & C)
+    True
+    >>> is_cnf((A & B) | C)
+    False
+
+    """
+    return _is_form(expr, And, Or)
+
+
+def is_dnf(expr):
+    """
+    Test whether or not an expression is in disjunctive normal form.
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import is_dnf
+    >>> from sympy.abc import A, B, C
+    >>> is_dnf(A | B | C)
+    True
+    >>> is_dnf(A & B & C)
+    True
+    >>> is_dnf((A & B) | C)
+    True
+    >>> is_dnf(A & (B | C))
+    False
+
+    """
+    return _is_form(expr, Or, And)
+
+
+def _is_form(expr, function1, function2):
+    """
+    Test whether or not an expression is of the required form.
+
+    """
+    expr = sympify(expr)
+
+    vals = function1.make_args(expr) if isinstance(expr, function1) else [expr]
+    for lit in vals:
+        if isinstance(lit, function2):
+            vals2 = function2.make_args(lit) if isinstance(lit, function2) else [lit]
+            for l in vals2:
+                if is_literal(l) is False:
+                    return False
+        elif is_literal(lit) is False:
+            return False
+
+    return True
+
+
+def eliminate_implications(expr):
+    """
+    Change :py:class:`~.Implies` and :py:class:`~.Equivalent` into
+    :py:class:`~.And`, :py:class:`~.Or`, and :py:class:`~.Not`.
+    That is, return an expression that is equivalent to ``expr``, but has only
+    ``&``, ``|``, and ``~`` as logical
+    operators.
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import Implies, Equivalent, \
+         eliminate_implications
+    >>> from sympy.abc import A, B, C
+    >>> eliminate_implications(Implies(A, B))
+    B | ~A
+    >>> eliminate_implications(Equivalent(A, B))
+    (A | ~B) & (B | ~A)
+    >>> eliminate_implications(Equivalent(A, B, C))
+    (A | ~C) & (B | ~A) & (C | ~B)
+
+    """
+    return to_nnf(expr, simplify=False)
+
+
+def is_literal(expr):
+    """
+    Returns True if expr is a literal, else False.
+
+    Examples
+    ========
+
+    >>> from sympy import Or, Q
+    >>> from sympy.abc import A, B
+    >>> from sympy.logic.boolalg import is_literal
+    >>> is_literal(A)
+    True
+    >>> is_literal(~A)
+    True
+    >>> is_literal(Q.zero(A))
+    True
+    >>> is_literal(A + B)
+    True
+    >>> is_literal(Or(A, B))
+    False
+
+    """
+    from sympy.assumptions import AppliedPredicate
+
+    if isinstance(expr, Not):
+        return is_literal(expr.args[0])
+    elif expr in (True, False) or isinstance(expr, AppliedPredicate) or expr.is_Atom:
+        return True
+    elif not isinstance(expr, BooleanFunction) and all(
+            (isinstance(expr, AppliedPredicate) or a.is_Atom) for a in expr.args):
+        return True
+    return False
+
+
+def to_int_repr(clauses, symbols):
+    """
+    Takes clauses in CNF format and puts them into an integer representation.
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import to_int_repr
+    >>> from sympy.abc import x, y
+    >>> to_int_repr([x | y, y], [x, y]) == [{1, 2}, {2}]
+    True
+
+    """
+
+    # Convert the symbol list into a dict
+    symbols = dict(zip(symbols, range(1, len(symbols) + 1)))
+
+    def append_symbol(arg, symbols):
+        if isinstance(arg, Not):
+            return -symbols[arg.args[0]]
+        else:
+            return symbols[arg]
+
+    return [{append_symbol(arg, symbols) for arg in Or.make_args(c)}
+            for c in clauses]
+
+
+def term_to_integer(term):
+    """
+    Return an integer corresponding to the base-2 digits given by *term*.
+
+    Parameters
+    ==========
+
+    term : a string or list of ones and zeros
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import term_to_integer
+    >>> term_to_integer([1, 0, 0])
+    4
+    >>> term_to_integer('100')
+    4
+
+    """
+
+    return int(''.join(list(map(str, list(term)))), 2)
+
+
+integer_to_term = ibin  # XXX could delete?
+
+
+def truth_table(expr, variables, input=True):
+    """
+    Return a generator of all possible configurations of the input variables,
+    and the result of the boolean expression for those values.
+
+    Parameters
+    ==========
+
+    expr : Boolean expression
+
+    variables : list of variables
+
+    input : bool (default ``True``)
+        Indicates whether to return the input combinations.
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import truth_table
+    >>> from sympy.abc import x,y
+    >>> table = truth_table(x >> y, [x, y])
+    >>> for t in table:
+    ...     print('{0} -> {1}'.format(*t))
+    [0, 0] -> True
+    [0, 1] -> True
+    [1, 0] -> False
+    [1, 1] -> True
+
+    >>> table = truth_table(x | y, [x, y])
+    >>> list(table)
+    [([0, 0], False), ([0, 1], True), ([1, 0], True), ([1, 1], True)]
+
+    If ``input`` is ``False``, ``truth_table`` returns only a list of truth values.
+    In this case, the corresponding input values of variables can be
+    deduced from the index of a given output.
+
+    >>> from sympy.utilities.iterables import ibin
+    >>> vars = [y, x]
+    >>> values = truth_table(x >> y, vars, input=False)
+    >>> values = list(values)
+    >>> values
+    [True, False, True, True]
+
+    >>> for i, value in enumerate(values):
+    ...     print('{0} -> {1}'.format(list(zip(
+    ...     vars, ibin(i, len(vars)))), value))
+    [(y, 0), (x, 0)] -> True
+    [(y, 0), (x, 1)] -> False
+    [(y, 1), (x, 0)] -> True
+    [(y, 1), (x, 1)] -> True
+
+    """
+    variables = [sympify(v) for v in variables]
+
+    expr = sympify(expr)
+    if not isinstance(expr, BooleanFunction) and not is_literal(expr):
+        return
+
+    table = product((0, 1), repeat=len(variables))
+    for term in table:
+        value = expr.xreplace(dict(zip(variables, term)))
+
+        if input:
+            yield list(term), value
+        else:
+            yield value
+
+
+def _check_pair(minterm1, minterm2):
+    """
+    Checks if a pair of minterms differs by only one bit. If yes, returns
+    index, else returns `-1`.
+    """
+    # Early termination seems to be faster than list comprehension,
+    # at least for large examples.
+    index = -1
+    for x, i in enumerate(minterm1):  # zip(minterm1, minterm2) is slower
+        if i != minterm2[x]:
+            if index == -1:
+                index = x
+            else:
+                return -1
+    return index
+
+
+def _convert_to_varsSOP(minterm, variables):
+    """
+    Converts a term in the expansion of a function from binary to its
+    variable form (for SOP).
+    """
+    temp = [variables[n] if val == 1 else Not(variables[n])
+            for n, val in enumerate(minterm) if val != 3]
+    return And(*temp)
+
+
+def _convert_to_varsPOS(maxterm, variables):
+    """
+    Converts a term in the expansion of a function from binary to its
+    variable form (for POS).
+    """
+    temp = [variables[n] if val == 0 else Not(variables[n])
+            for n, val in enumerate(maxterm) if val != 3]
+    return Or(*temp)
+
+
+def _convert_to_varsANF(term, variables):
+    """
+    Converts a term in the expansion of a function from binary to its
+    variable form (for ANF).
+
+    Parameters
+    ==========
+
+    term : list of 1's and 0's (complementation pattern)
+    variables : list of variables
+
+    """
+    temp = [variables[n] for n, t in enumerate(term) if t == 1]
+
+    if not temp:
+        return true
+
+    return And(*temp)
+
+
+def _get_odd_parity_terms(n):
+    """
+    Returns a list of lists, with all possible combinations of n zeros and ones
+    with an odd number of ones.
+    """
+    return [e for e in [ibin(i, n) for i in range(2**n)] if sum(e) % 2 == 1]
+
+
+def _get_even_parity_terms(n):
+    """
+    Returns a list of lists, with all possible combinations of n zeros and ones
+    with an even number of ones.
+    """
+    return [e for e in [ibin(i, n) for i in range(2**n)] if sum(e) % 2 == 0]
+
+
+def _simplified_pairs(terms):
+    """
+    Reduces a set of minterms, if possible, to a simplified set of minterms
+    with one less variable in the terms using QM method.
+    """
+    if not terms:
+        return []
+
+    simplified_terms = []
+    todo = list(range(len(terms)))
+
+    # Count number of ones as _check_pair can only potentially match if there
+    # is at most a difference of a single one
+    termdict = defaultdict(list)
+    for n, term in enumerate(terms):
+        ones = sum(1 for t in term if t == 1)
+        termdict[ones].append(n)
+
+    variables = len(terms[0])
+    for k in range(variables):
+        for i in termdict[k]:
+            for j in termdict[k+1]:
+                index = _check_pair(terms[i], terms[j])
+                if index != -1:
+                    # Mark terms handled
+                    todo[i] = todo[j] = None
+                    # Copy old term
+                    newterm = terms[i][:]
+                    # Set differing position to don't care
+                    newterm[index] = 3
+                    # Add if not already there
+                    if newterm not in simplified_terms:
+                        simplified_terms.append(newterm)
+
+    if simplified_terms:
+        # Further simplifications only among the new terms
+        simplified_terms = _simplified_pairs(simplified_terms)
+
+    # Add remaining, non-simplified, terms
+    simplified_terms.extend([terms[i] for i in todo if i is not None])
+    return simplified_terms
+
+
+def _rem_redundancy(l1, terms):
+    """
+    After the truth table has been sufficiently simplified, use the prime
+    implicant table method to recognize and eliminate redundant pairs,
+    and return the essential arguments.
+    """
+
+    if not terms:
+        return []
+
+    nterms = len(terms)
+    nl1 = len(l1)
+
+    # Create dominating matrix
+    dommatrix = [[0]*nl1 for n in range(nterms)]
+    colcount = [0]*nl1
+    rowcount = [0]*nterms
+    for primei, prime in enumerate(l1):
+        for termi, term in enumerate(terms):
+            # Check prime implicant covering term
+            if all(t == 3 or t == mt for t, mt in zip(prime, term)):
+                dommatrix[termi][primei] = 1
+                colcount[primei] += 1
+                rowcount[termi] += 1
+
+    # Keep track if anything changed
+    anythingchanged = True
+    # Then, go again
+    while anythingchanged:
+        anythingchanged = False
+
+        for rowi in range(nterms):
+            # Still non-dominated?
+            if rowcount[rowi]:
+                row = dommatrix[rowi]
+                for row2i in range(nterms):
+                    # Still non-dominated?
+                    if rowi != row2i and rowcount[rowi] and (rowcount[rowi] <= rowcount[row2i]):
+                        row2 = dommatrix[row2i]
+                        if all(row2[n] >= row[n] for n in range(nl1)):
+                            # row2 dominating row, remove row2
+                            rowcount[row2i] = 0
+                            anythingchanged = True
+                            for primei, prime in enumerate(row2):
+                                if prime:
+                                    # Make corresponding entry 0
+                                    dommatrix[row2i][primei] = 0
+                                    colcount[primei] -= 1
+
+        colcache = {}
+
+        for coli in range(nl1):
+            # Still non-dominated?
+            if colcount[coli]:
+                if coli in colcache:
+                    col = colcache[coli]
+                else:
+                    col = [dommatrix[i][coli] for i in range(nterms)]
+                    colcache[coli] = col
+                for col2i in range(nl1):
+                    # Still non-dominated?
+                    if coli != col2i and colcount[col2i] and (colcount[coli] >= colcount[col2i]):
+                        if col2i in colcache:
+                            col2 = colcache[col2i]
+                        else:
+                            col2 = [dommatrix[i][col2i] for i in range(nterms)]
+                            colcache[col2i] = col2
+                        if all(col[n] >= col2[n] for n in range(nterms)):
+                            # col dominating col2, remove col2
+                            colcount[col2i] = 0
+                            anythingchanged = True
+                            for termi, term in enumerate(col2):
+                                if term and dommatrix[termi][col2i]:
+                                    # Make corresponding entry 0
+                                    dommatrix[termi][col2i] = 0
+                                    rowcount[termi] -= 1
+
+        if not anythingchanged:
+            # Heuristically select the prime implicant covering most terms
+            maxterms = 0
+            bestcolidx = -1
+            for coli in range(nl1):
+                s = colcount[coli]
+                if s > maxterms:
+                    bestcolidx = coli
+                    maxterms = s
+
+            # In case we found a prime implicant covering at least two terms
+            if bestcolidx != -1 and maxterms > 1:
+                for primei, prime in enumerate(l1):
+                    if primei != bestcolidx:
+                        for termi, term in enumerate(colcache[bestcolidx]):
+                            if term and dommatrix[termi][primei]:
+                                # Make corresponding entry 0
+                                dommatrix[termi][primei] = 0
+                                anythingchanged = True
+                                rowcount[termi] -= 1
+                                colcount[primei] -= 1
+
+    return [l1[i] for i in range(nl1) if colcount[i]]
+
+
+def _input_to_binlist(inputlist, variables):
+    binlist = []
+    bits = len(variables)
+    for val in inputlist:
+        if isinstance(val, int):
+            binlist.append(ibin(val, bits))
+        elif isinstance(val, dict):
+            nonspecvars = list(variables)
+            for key in val.keys():
+                nonspecvars.remove(key)
+            for t in product((0, 1), repeat=len(nonspecvars)):
+                d = dict(zip(nonspecvars, t))
+                d.update(val)
+                binlist.append([d[v] for v in variables])
+        elif isinstance(val, (list, tuple)):
+            if len(val) != bits:
+                raise ValueError("Each term must contain {bits} bits as there are"
+                                 "\n{bits} variables (or be an integer)."
+                                 "".format(bits=bits))
+            binlist.append(list(val))
+        else:
+            raise TypeError("A term list can only contain lists,"
+                            " ints or dicts.")
+    return binlist
+
+
+def SOPform(variables, minterms, dontcares=None):
+    """
+    The SOPform function uses simplified_pairs and a redundant group-
+    eliminating algorithm to convert the list of all input combos that
+    generate '1' (the minterms) into the smallest sum-of-products form.
+
+    The variables must be given as the first argument.
+
+    Return a logical :py:class:`~.Or` function (i.e., the "sum of products" or
+    "SOP" form) that gives the desired outcome. If there are inputs that can
+    be ignored, pass them as a list, too.
+
+    The result will be one of the (perhaps many) functions that satisfy
+    the conditions.
+
+    Examples
+    ========
+
+    >>> from sympy.logic import SOPform
+    >>> from sympy import symbols
+    >>> w, x, y, z = symbols('w x y z')
+    >>> minterms = [[0, 0, 0, 1], [0, 0, 1, 1],
+    ...             [0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 1, 1]]
+    >>> dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]]
+    >>> SOPform([w, x, y, z], minterms, dontcares)
+    (y & z) | (~w & ~x)
+
+    The terms can also be represented as integers:
+
+    >>> minterms = [1, 3, 7, 11, 15]
+    >>> dontcares = [0, 2, 5]
+    >>> SOPform([w, x, y, z], minterms, dontcares)
+    (y & z) | (~w & ~x)
+
+    They can also be specified using dicts, which does not have to be fully
+    specified:
+
+    >>> minterms = [{w: 0, x: 1}, {y: 1, z: 1, x: 0}]
+    >>> SOPform([w, x, y, z], minterms)
+    (x & ~w) | (y & z & ~x)
+
+    Or a combination:
+
+    >>> minterms = [4, 7, 11, [1, 1, 1, 1]]
+    >>> dontcares = [{w : 0, x : 0, y: 0}, 5]
+    >>> SOPform([w, x, y, z], minterms, dontcares)
+    (w & y & z) | (~w & ~y) | (x & z & ~w)
+
+    See also
+    ========
+
+    POSform
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Quine-McCluskey_algorithm
+    .. [2] https://en.wikipedia.org/wiki/Don%27t-care_term
+
+    """
+    if not minterms:
+        return false
+
+    variables = tuple(map(sympify, variables))
+
+
+    minterms = _input_to_binlist(minterms, variables)
+    dontcares = _input_to_binlist((dontcares or []), variables)
+    for d in dontcares:
+        if d in minterms:
+            raise ValueError('%s in minterms is also in dontcares' % d)
+
+    return _sop_form(variables, minterms, dontcares)
+
+
+def _sop_form(variables, minterms, dontcares):
+    new = _simplified_pairs(minterms + dontcares)
+    essential = _rem_redundancy(new, minterms)
+    return Or(*[_convert_to_varsSOP(x, variables) for x in essential])
+
+
+def POSform(variables, minterms, dontcares=None):
+    """
+    The POSform function uses simplified_pairs and a redundant-group
+    eliminating algorithm to convert the list of all input combinations
+    that generate '1' (the minterms) into the smallest product-of-sums form.
+
+    The variables must be given as the first argument.
+
+    Return a logical :py:class:`~.And` function (i.e., the "product of sums"
+    or "POS" form) that gives the desired outcome. If there are inputs that can
+    be ignored, pass them as a list, too.
+
+    The result will be one of the (perhaps many) functions that satisfy
+    the conditions.
+
+    Examples
+    ========
+
+    >>> from sympy.logic import POSform
+    >>> from sympy import symbols
+    >>> w, x, y, z = symbols('w x y z')
+    >>> minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1],
+    ...             [1, 0, 1, 1], [1, 1, 1, 1]]
+    >>> dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]]
+    >>> POSform([w, x, y, z], minterms, dontcares)
+    z & (y | ~w)
+
+    The terms can also be represented as integers:
+
+    >>> minterms = [1, 3, 7, 11, 15]
+    >>> dontcares = [0, 2, 5]
+    >>> POSform([w, x, y, z], minterms, dontcares)
+    z & (y | ~w)
+
+    They can also be specified using dicts, which does not have to be fully
+    specified:
+
+    >>> minterms = [{w: 0, x: 1}, {y: 1, z: 1, x: 0}]
+    >>> POSform([w, x, y, z], minterms)
+    (x | y) & (x | z) & (~w | ~x)
+
+    Or a combination:
+
+    >>> minterms = [4, 7, 11, [1, 1, 1, 1]]
+    >>> dontcares = [{w : 0, x : 0, y: 0}, 5]
+    >>> POSform([w, x, y, z], minterms, dontcares)
+    (w | x) & (y | ~w) & (z | ~y)
+
+    See also
+    ========
+
+    SOPform
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Quine-McCluskey_algorithm
+    .. [2] https://en.wikipedia.org/wiki/Don%27t-care_term
+
+    """
+    if not minterms:
+        return false
+
+    variables = tuple(map(sympify, variables))
+    minterms = _input_to_binlist(minterms, variables)
+    dontcares = _input_to_binlist((dontcares or []), variables)
+    for d in dontcares:
+        if d in minterms:
+            raise ValueError('%s in minterms is also in dontcares' % d)
+
+    maxterms = []
+    for t in product((0, 1), repeat=len(variables)):
+        t = list(t)
+        if (t not in minterms) and (t not in dontcares):
+            maxterms.append(t)
+
+    new = _simplified_pairs(maxterms + dontcares)
+    essential = _rem_redundancy(new, maxterms)
+    return And(*[_convert_to_varsPOS(x, variables) for x in essential])
+
+
+def ANFform(variables, truthvalues):
+    """
+    The ANFform function converts the list of truth values to
+    Algebraic Normal Form (ANF).
+
+    The variables must be given as the first argument.
+
+    Return True, False, logical :py:class:`~.And` function (i.e., the
+    "Zhegalkin monomial") or logical :py:class:`~.Xor` function (i.e.,
+    the "Zhegalkin polynomial"). When True and False
+    are represented by 1 and 0, respectively, then
+    :py:class:`~.And` is multiplication and :py:class:`~.Xor` is addition.
+
+    Formally a "Zhegalkin monomial" is the product (logical
+    And) of a finite set of distinct variables, including
+    the empty set whose product is denoted 1 (True).
+    A "Zhegalkin polynomial" is the sum (logical Xor) of a
+    set of Zhegalkin monomials, with the empty set denoted
+    by 0 (False).
+
+    Parameters
+    ==========
+
+    variables : list of variables
+    truthvalues : list of 1's and 0's (result column of truth table)
+
+    Examples
+    ========
+    >>> from sympy.logic.boolalg import ANFform
+    >>> from sympy.abc import x, y
+    >>> ANFform([x], [1, 0])
+    x ^ True
+    >>> ANFform([x, y], [0, 1, 1, 1])
+    x ^ y ^ (x & y)
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Zhegalkin_polynomial
+
+    """
+
+    n_vars = len(variables)
+    n_values = len(truthvalues)
+
+    if n_values != 2 ** n_vars:
+        raise ValueError("The number of truth values must be equal to 2^%d, "
+                         "got %d" % (n_vars, n_values))
+
+    variables = tuple(map(sympify, variables))
+
+    coeffs = anf_coeffs(truthvalues)
+    terms = []
+
+    for i, t in enumerate(product((0, 1), repeat=n_vars)):
+        if coeffs[i] == 1:
+            terms.append(t)
+
+    return Xor(*[_convert_to_varsANF(x, variables) for x in terms],
+               remove_true=False)
+
+
+def anf_coeffs(truthvalues):
+    """
+    Convert a list of truth values of some boolean expression
+    to the list of coefficients of the polynomial mod 2 (exclusive
+    disjunction) representing the boolean expression in ANF
+    (i.e., the "Zhegalkin polynomial").
+
+    There are `2^n` possible Zhegalkin monomials in `n` variables, since
+    each monomial is fully specified by the presence or absence of
+    each variable.
+
+    We can enumerate all the monomials. For example, boolean
+    function with four variables ``(a, b, c, d)`` can contain
+    up to `2^4 = 16` monomials. The 13-th monomial is the
+    product ``a & b & d``, because 13 in binary is 1, 1, 0, 1.
+
+    A given monomial's presence or absence in a polynomial corresponds
+    to that monomial's coefficient being 1 or 0 respectively.
+
+    Examples
+    ========
+    >>> from sympy.logic.boolalg import anf_coeffs, bool_monomial, Xor
+    >>> from sympy.abc import a, b, c
+    >>> truthvalues = [0, 1, 1, 0, 0, 1, 0, 1]
+    >>> coeffs = anf_coeffs(truthvalues)
+    >>> coeffs
+    [0, 1, 1, 0, 0, 0, 1, 0]
+    >>> polynomial = Xor(*[
+    ...     bool_monomial(k, [a, b, c])
+    ...     for k, coeff in enumerate(coeffs) if coeff == 1
+    ... ])
+    >>> polynomial
+    b ^ c ^ (a & b)
+
+    """
+
+    s = '{:b}'.format(len(truthvalues))
+    n = len(s) - 1
+
+    if len(truthvalues) != 2**n:
+        raise ValueError("The number of truth values must be a power of two, "
+                         "got %d" % len(truthvalues))
+
+    coeffs = [[v] for v in truthvalues]
+
+    for i in range(n):
+        tmp = []
+        for j in range(2 ** (n-i-1)):
+            tmp.append(coeffs[2*j] +
+                list(map(lambda x, y: x^y, coeffs[2*j], coeffs[2*j+1])))
+        coeffs = tmp
+
+    return coeffs[0]
+
+
+def bool_minterm(k, variables):
+    """
+    Return the k-th minterm.
+
+    Minterms are numbered by a binary encoding of the complementation
+    pattern of the variables. This convention assigns the value 1 to
+    the direct form and 0 to the complemented form.
+
+    Parameters
+    ==========
+
+    k : int or list of 1's and 0's (complementation pattern)
+    variables : list of variables
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import bool_minterm
+    >>> from sympy.abc import x, y, z
+    >>> bool_minterm([1, 0, 1], [x, y, z])
+    x & z & ~y
+    >>> bool_minterm(6, [x, y, z])
+    x & y & ~z
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Canonical_normal_form#Indexing_minterms
+
+    """
+    if isinstance(k, int):
+        k = ibin(k, len(variables))
+    variables = tuple(map(sympify, variables))
+    return _convert_to_varsSOP(k, variables)
+
+
+def bool_maxterm(k, variables):
+    """
+    Return the k-th maxterm.
+
+    Each maxterm is assigned an index based on the opposite
+    conventional binary encoding used for minterms. The maxterm
+    convention assigns the value 0 to the direct form and 1 to
+    the complemented form.
+
+    Parameters
+    ==========
+
+    k : int or list of 1's and 0's (complementation pattern)
+    variables : list of variables
+
+    Examples
+    ========
+    >>> from sympy.logic.boolalg import bool_maxterm
+    >>> from sympy.abc import x, y, z
+    >>> bool_maxterm([1, 0, 1], [x, y, z])
+    y | ~x | ~z
+    >>> bool_maxterm(6, [x, y, z])
+    z | ~x | ~y
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Canonical_normal_form#Indexing_maxterms
+
+    """
+    if isinstance(k, int):
+        k = ibin(k, len(variables))
+    variables = tuple(map(sympify, variables))
+    return _convert_to_varsPOS(k, variables)
+
+
+def bool_monomial(k, variables):
+    """
+    Return the k-th monomial.
+
+    Monomials are numbered by a binary encoding of the presence and
+    absences of the variables. This convention assigns the value
+    1 to the presence of variable and 0 to the absence of variable.
+
+    Each boolean function can be uniquely represented by a
+    Zhegalkin Polynomial (Algebraic Normal Form). The Zhegalkin
+    Polynomial of the boolean function with `n` variables can contain
+    up to `2^n` monomials. We can enumerate all the monomials.
+    Each monomial is fully specified by the presence or absence
+    of each variable.
+
+    For example, boolean function with four variables ``(a, b, c, d)``
+    can contain up to `2^4 = 16` monomials. The 13-th monomial is the
+    product ``a & b & d``, because 13 in binary is 1, 1, 0, 1.
+
+    Parameters
+    ==========
+
+    k : int or list of 1's and 0's
+    variables : list of variables
+
+    Examples
+    ========
+    >>> from sympy.logic.boolalg import bool_monomial
+    >>> from sympy.abc import x, y, z
+    >>> bool_monomial([1, 0, 1], [x, y, z])
+    x & z
+    >>> bool_monomial(6, [x, y, z])
+    x & y
+
+    """
+    if isinstance(k, int):
+        k = ibin(k, len(variables))
+    variables = tuple(map(sympify, variables))
+    return _convert_to_varsANF(k, variables)
+
+
+def _find_predicates(expr):
+    """Helper to find logical predicates in BooleanFunctions.
+
+    A logical predicate is defined here as anything within a BooleanFunction
+    that is not a BooleanFunction itself.
+
+    """
+    if not isinstance(expr, BooleanFunction):
+        return {expr}
+    return set().union(*(map(_find_predicates, expr.args)))
+
+
+def simplify_logic(expr, form=None, deep=True, force=False, dontcare=None):
+    """
+    This function simplifies a boolean function to its simplified version
+    in SOP or POS form. The return type is an :py:class:`~.Or` or
+    :py:class:`~.And` object in SymPy.
+
+    Parameters
+    ==========
+
+    expr : Boolean
+
+    form : string (``'cnf'`` or ``'dnf'``) or ``None`` (default).
+        If ``'cnf'`` or ``'dnf'``, the simplest expression in the corresponding
+        normal form is returned; if ``None``, the answer is returned
+        according to the form with fewest args (in CNF by default).
+
+    deep : bool (default ``True``)
+        Indicates whether to recursively simplify any
+        non-boolean functions contained within the input.
+
+    force : bool (default ``False``)
+        As the simplifications require exponential time in the number
+        of variables, there is by default a limit on expressions with
+        8 variables. When the expression has more than 8 variables
+        only symbolical simplification (controlled by ``deep``) is
+        made. By setting ``force`` to ``True``, this limit is removed. Be
+        aware that this can lead to very long simplification times.
+
+    dontcare : Boolean
+        Optimize expression under the assumption that inputs where this
+        expression is true are don't care. This is useful in e.g. Piecewise
+        conditions, where later conditions do not need to consider inputs that
+        are converted by previous conditions. For example, if a previous
+        condition is ``And(A, B)``, the simplification of expr can be made
+        with don't cares for ``And(A, B)``.
+
+    Examples
+    ========
+
+    >>> from sympy.logic import simplify_logic
+    >>> from sympy.abc import x, y, z
+    >>> b = (~x & ~y & ~z) | ( ~x & ~y & z)
+    >>> simplify_logic(b)
+    ~x & ~y
+    >>> simplify_logic(x | y, dontcare=y)
+    x
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Don%27t-care_term
+
+    """
+
+    if form not in (None, 'cnf', 'dnf'):
+        raise ValueError("form can be cnf or dnf only")
+    expr = sympify(expr)
+    # check for quick exit if form is given: right form and all args are
+    # literal and do not involve Not
+    if form:
+        form_ok = False
+        if form == 'cnf':
+            form_ok = is_cnf(expr)
+        elif form == 'dnf':
+            form_ok = is_dnf(expr)
+
+        if form_ok and all(is_literal(a)
+                for a in expr.args):
+            return expr
+    from sympy.core.relational import Relational
+    if deep:
+        variables = expr.atoms(Relational)
+        from sympy.simplify.simplify import simplify
+        s = tuple(map(simplify, variables))
+        expr = expr.xreplace(dict(zip(variables, s)))
+    if not isinstance(expr, BooleanFunction):
+        return expr
+    # Replace Relationals with Dummys to possibly
+    # reduce the number of variables
+    repl = {}
+    undo = {}
+    from sympy.core.symbol import Dummy
+    variables = expr.atoms(Relational)
+    if dontcare is not None:
+        dontcare = sympify(dontcare)
+        variables.update(dontcare.atoms(Relational))
+    while variables:
+        var = variables.pop()
+        if var.is_Relational:
+            d = Dummy()
+            undo[d] = var
+            repl[var] = d
+            nvar = var.negated
+            if nvar in variables:
+                repl[nvar] = Not(d)
+                variables.remove(nvar)
+
+    expr = expr.xreplace(repl)
+
+    if dontcare is not None:
+        dontcare = dontcare.xreplace(repl)
+
+    # Get new variables after replacing
+    variables = _find_predicates(expr)
+    if not force and len(variables) > 8:
+        return expr.xreplace(undo)
+    if dontcare is not None:
+        # Add variables from dontcare
+        dcvariables = _find_predicates(dontcare)
+        variables.update(dcvariables)
+        # if too many restore to variables only
+        if not force and len(variables) > 8:
+            variables = _find_predicates(expr)
+            dontcare = None
+    # group into constants and variable values
+    c, v = sift(ordered(variables), lambda x: x in (True, False), binary=True)
+    variables = c + v
+    # standardize constants to be 1 or 0 in keeping with truthtable
+    c = [1 if i == True else 0 for i in c]
+    truthtable = _get_truthtable(v, expr, c)
+    if dontcare is not None:
+        dctruthtable = _get_truthtable(v, dontcare, c)
+        truthtable = [t for t in truthtable if t not in dctruthtable]
+    else:
+        dctruthtable = []
+    big = len(truthtable) >= (2 ** (len(variables) - 1))
+    if form == 'dnf' or form is None and big:
+        return _sop_form(variables, truthtable, dctruthtable).xreplace(undo)
+    return POSform(variables, truthtable, dctruthtable).xreplace(undo)
+
+
+def _get_truthtable(variables, expr, const):
+    """ Return a list of all combinations leading to a True result for ``expr``.
+    """
+    _variables = variables.copy()
+    def _get_tt(inputs):
+        if _variables:
+            v = _variables.pop()
+            tab = [[i[0].xreplace({v: false}), [0] + i[1]] for i in inputs if i[0] is not false]
+            tab.extend([[i[0].xreplace({v: true}), [1] + i[1]] for i in inputs if i[0] is not false])
+            return _get_tt(tab)
+        return inputs
+    res = [const + k[1] for k in _get_tt([[expr, []]]) if k[0]]
+    if res == [[]]:
+        return []
+    else:
+        return res
+
+
+def _finger(eq):
+    """
+    Assign a 5-item fingerprint to each symbol in the equation:
+    [
+    # of times it appeared as a Symbol;
+    # of times it appeared as a Not(symbol);
+    # of times it appeared as a Symbol in an And or Or;
+    # of times it appeared as a Not(Symbol) in an And or Or;
+    a sorted tuple of tuples, (i, j, k), where i is the number of arguments
+    in an And or Or with which it appeared as a Symbol, and j is
+    the number of arguments that were Not(Symbol); k is the number
+    of times that (i, j) was seen.
+    ]
+
+    Examples
+    ========
+
+    >>> from sympy.logic.boolalg import _finger as finger
+    >>> from sympy import And, Or, Not, Xor, to_cnf, symbols
+    >>> from sympy.abc import a, b, x, y
+    >>> eq = Or(And(Not(y), a), And(Not(y), b), And(x, y))
+    >>> dict(finger(eq))
+    {(0, 0, 1, 0, ((2, 0, 1),)): [x],
+    (0, 0, 1, 0, ((2, 1, 1),)): [a, b],
+    (0, 0, 1, 2, ((2, 0, 1),)): [y]}
+    >>> dict(finger(x & ~y))
+    {(0, 1, 0, 0, ()): [y], (1, 0, 0, 0, ()): [x]}
+
+    In the following, the (5, 2, 6) means that there were 6 Or
+    functions in which a symbol appeared as itself amongst 5 arguments in
+    which there were also 2 negated symbols, e.g. ``(a0 | a1 | a2 | ~a3 | ~a4)``
+    is counted once for a0, a1 and a2.
+
+    >>> dict(finger(to_cnf(Xor(*symbols('a:5')))))
+    {(0, 0, 8, 8, ((5, 0, 1), (5, 2, 6), (5, 4, 1))): [a0, a1, a2, a3, a4]}
+
+    The equation must not have more than one level of nesting:
+
+    >>> dict(finger(And(Or(x, y), y)))
+    {(0, 0, 1, 0, ((2, 0, 1),)): [x], (1, 0, 1, 0, ((2, 0, 1),)): [y]}
+    >>> dict(finger(And(Or(x, And(a, x)), y)))
+    Traceback (most recent call last):
+    ...
+    NotImplementedError: unexpected level of nesting
+
+    So y and x have unique fingerprints, but a and b do not.
+    """
+    f = eq.free_symbols
+    d = dict(list(zip(f, [[0]*4 + [defaultdict(int)] for fi in f])))
+    for a in eq.args:
+        if a.is_Symbol:
+            d[a][0] += 1
+        elif a.is_Not:
+            d[a.args[0]][1] += 1
+        else:
+            o = len(a.args), sum(isinstance(ai, Not) for ai in a.args)
+            for ai in a.args:
+                if ai.is_Symbol:
+                    d[ai][2] += 1
+                    d[ai][-1][o] += 1
+                elif ai.is_Not:
+                    d[ai.args[0]][3] += 1
+                else:
+                    raise NotImplementedError('unexpected level of nesting')
+    inv = defaultdict(list)
+    for k, v in ordered(iter(d.items())):
+        v[-1] = tuple(sorted([i + (j,) for i, j in v[-1].items()]))
+        inv[tuple(v)].append(k)
+    return inv
+
+
+def bool_map(bool1, bool2):
+    """
+    Return the simplified version of *bool1*, and the mapping of variables
+    that makes the two expressions *bool1* and *bool2* represent the same
+    logical behaviour for some correspondence between the variables
+    of each.
+    If more than one mappings of this sort exist, one of them
+    is returned.
+
+    For example, ``And(x, y)`` is logically equivalent to ``And(a, b)`` for
+    the mapping ``{x: a, y: b}`` or ``{x: b, y: a}``.
+    If no such mapping exists, return ``False``.
+
+    Examples
+    ========
+
+    >>> from sympy import SOPform, bool_map, Or, And, Not, Xor
+    >>> from sympy.abc import w, x, y, z, a, b, c, d
+    >>> function1 = SOPform([x, z, y],[[1, 0, 1], [0, 0, 1]])
+    >>> function2 = SOPform([a, b, c],[[1, 0, 1], [1, 0, 0]])
+    >>> bool_map(function1, function2)
+    (y & ~z, {y: a, z: b})
+
+    The results are not necessarily unique, but they are canonical. Here,
+    ``(w, z)`` could be ``(a, d)`` or ``(d, a)``:
+
+    >>> eq =  Or(And(Not(y), w), And(Not(y), z), And(x, y))
+    >>> eq2 = Or(And(Not(c), a), And(Not(c), d), And(b, c))
+    >>> bool_map(eq, eq2)
+    ((x & y) | (w & ~y) | (z & ~y), {w: a, x: b, y: c, z: d})
+    >>> eq = And(Xor(a, b), c, And(c,d))
+    >>> bool_map(eq, eq.subs(c, x))
+    (c & d & (a | b) & (~a | ~b), {a: a, b: b, c: d, d: x})
+
+    """
+
+    def match(function1, function2):
+        """Return the mapping that equates variables between two
+        simplified boolean expressions if possible.
+
+        By "simplified" we mean that a function has been denested
+        and is either an And (or an Or) whose arguments are either
+        symbols (x), negated symbols (Not(x)), or Or (or an And) whose
+        arguments are only symbols or negated symbols. For example,
+        ``And(x, Not(y), Or(w, Not(z)))``.
+
+        Basic.match is not robust enough (see issue 4835) so this is
+        a workaround that is valid for simplified boolean expressions
+        """
+
+        # do some quick checks
+        if function1.__class__ != function2.__class__:
+            return None  # maybe simplification makes them the same?
+        if len(function1.args) != len(function2.args):
+            return None  # maybe simplification makes them the same?
+        if function1.is_Symbol:
+            return {function1: function2}
+
+        # get the fingerprint dictionaries
+        f1 = _finger(function1)
+        f2 = _finger(function2)
+
+        # more quick checks
+        if len(f1) != len(f2):
+            return False
+
+        # assemble the match dictionary if possible
+        matchdict = {}
+        for k in f1.keys():
+            if k not in f2:
+                return False
+            if len(f1[k]) != len(f2[k]):
+                return False
+            for i, x in enumerate(f1[k]):
+                matchdict[x] = f2[k][i]
+        return matchdict
+
+    a = simplify_logic(bool1)
+    b = simplify_logic(bool2)
+    m = match(a, b)
+    if m:
+        return a, m
+    return m
+
+
+def _apply_patternbased_simplification(rv, patterns, measure,
+                                       dominatingvalue,
+                                       replacementvalue=None,
+                                       threeterm_patterns=None):
+    """
+    Replace patterns of Relational
+
+    Parameters
+    ==========
+
+    rv : Expr
+        Boolean expression
+
+    patterns : tuple
+        Tuple of tuples, with (pattern to simplify, simplified pattern) with
+        two terms.
+
+    measure : function
+        Simplification measure.
+
+    dominatingvalue : Boolean or ``None``
+        The dominating value for the function of consideration.
+        For example, for :py:class:`~.And` ``S.false`` is dominating.
+        As soon as one expression is ``S.false`` in :py:class:`~.And`,
+        the whole expression is ``S.false``.
+
+    replacementvalue : Boolean or ``None``, optional
+        The resulting value for the whole expression if one argument
+        evaluates to ``dominatingvalue``.
+        For example, for :py:class:`~.Nand` ``S.false`` is dominating, but
+        in this case the resulting value is ``S.true``. Default is ``None``.
+        If ``replacementvalue`` is ``None`` and ``dominatingvalue`` is not
+        ``None``, ``replacementvalue = dominatingvalue``.
+
+    threeterm_patterns : tuple, optional
+        Tuple of tuples, with (pattern to simplify, simplified pattern) with
+        three terms.
+
+    """
+    from sympy.core.relational import Relational, _canonical
+
+    if replacementvalue is None and dominatingvalue is not None:
+        replacementvalue = dominatingvalue
+    # Use replacement patterns for Relationals
+    Rel, nonRel = sift(rv.args, lambda i: isinstance(i, Relational),
+                       binary=True)
+    if len(Rel) <= 1:
+        return rv
+    Rel, nonRealRel = sift(Rel, lambda i: not any(s.is_real is False
+                                                  for s in i.free_symbols),
+                           binary=True)
+    Rel = [i.canonical for i in Rel]
+
+    if threeterm_patterns and len(Rel) >= 3:
+        Rel = _apply_patternbased_threeterm_simplification(Rel,
+                            threeterm_patterns, rv.func, dominatingvalue,
+                            replacementvalue, measure)
+
+    Rel = _apply_patternbased_twoterm_simplification(Rel, patterns,
+                    rv.func, dominatingvalue, replacementvalue, measure)
+
+    rv = rv.func(*([_canonical(i) for i in ordered(Rel)]
+                 + nonRel + nonRealRel))
+    return rv
+
+
+def _apply_patternbased_twoterm_simplification(Rel, patterns, func,
+                                               dominatingvalue,
+                                               replacementvalue,
+                                               measure):
+    """ Apply pattern-based two-term simplification."""
+    from sympy.functions.elementary.miscellaneous import Min, Max
+    from sympy.core.relational import Ge, Gt, _Inequality
+    changed = True
+    while changed and len(Rel) >= 2:
+        changed = False
+        # Use only < or <=
+        Rel = [r.reversed if isinstance(r, (Ge, Gt)) else r for r in Rel]
+        # Sort based on ordered
+        Rel = list(ordered(Rel))
+        # Eq and Ne must be tested reversed as well
+        rtmp = [(r, ) if isinstance(r, _Inequality) else (r, r.reversed) for r in Rel]
+        # Create a list of possible replacements
+        results = []
+        # Try all combinations of possibly reversed relational
+        for ((i, pi), (j, pj)) in combinations(enumerate(rtmp), 2):
+            for pattern, simp in patterns:
+                res = []
+                for p1, p2 in product(pi, pj):
+                    # use SymPy matching
+                    oldexpr = Tuple(p1, p2)
+                    tmpres = oldexpr.match(pattern)
+                    if tmpres:
+                        res.append((tmpres, oldexpr))
+
+                if res:
+                    for tmpres, oldexpr in res:
+                        # we have a matching, compute replacement
+                        np = simp.xreplace(tmpres)
+                        if np == dominatingvalue:
+                            # if dominatingvalue, the whole expression
+                            # will be replacementvalue
+                            return [replacementvalue]
+                        # add replacement
+                        if not isinstance(np, ITE) and not np.has(Min, Max):
+                            # We only want to use ITE and Min/Max replacements if
+                            # they simplify to a relational
+                            costsaving = measure(func(*oldexpr.args)) - measure(np)
+                            if costsaving > 0:
+                                results.append((costsaving, ([i, j], np)))
+        if results:
+            # Sort results based on complexity
+            results = sorted(results,
+                                           key=lambda pair: pair[0], reverse=True)
+            # Replace the one providing most simplification
+            replacement = results[0][1]
+            idx, newrel = replacement
+            idx.sort()
+            # Remove the old relationals
+            for index in reversed(idx):
+                del Rel[index]
+            if dominatingvalue is None or newrel != Not(dominatingvalue):
+                # Insert the new one (no need to insert a value that will
+                # not affect the result)
+                if newrel.func == func:
+                    for a in newrel.args:
+                        Rel.append(a)
+                else:
+                    Rel.append(newrel)
+            # We did change something so try again
+            changed = True
+    return Rel
+
+
+def _apply_patternbased_threeterm_simplification(Rel, patterns, func,
+                                                 dominatingvalue,
+                                                 replacementvalue,
+                                                 measure):
+    """ Apply pattern-based three-term simplification."""
+    from sympy.functions.elementary.miscellaneous import Min, Max
+    from sympy.core.relational import Le, Lt, _Inequality
+    changed = True
+    while changed and len(Rel) >= 3:
+        changed = False
+        # Use only > or >=
+        Rel = [r.reversed if isinstance(r, (Le, Lt)) else r for r in Rel]
+        # Sort based on ordered
+        Rel = list(ordered(Rel))
+        # Create a list of possible replacements
+        results = []
+        # Eq and Ne must be tested reversed as well
+        rtmp = [(r, ) if isinstance(r, _Inequality) else (r, r.reversed) for r in Rel]
+        # Try all combinations of possibly reversed relational
+        for ((i, pi), (j, pj), (k, pk)) in permutations(enumerate(rtmp), 3):
+            for pattern, simp in patterns:
+                res = []
+                for p1, p2, p3 in product(pi, pj, pk):
+                    # use SymPy matching
+                    oldexpr = Tuple(p1, p2, p3)
+                    tmpres = oldexpr.match(pattern)
+                    if tmpres:
+                        res.append((tmpres, oldexpr))
+
+                if res:
+                    for tmpres, oldexpr in res:
+                        # we have a matching, compute replacement
+                        np = simp.xreplace(tmpres)
+                        if np == dominatingvalue:
+                            # if dominatingvalue, the whole expression
+                            # will be replacementvalue
+                            return [replacementvalue]
+                        # add replacement
+                        if not isinstance(np, ITE) and not np.has(Min, Max):
+                            # We only want to use ITE and Min/Max replacements if
+                            # they simplify to a relational
+                            costsaving = measure(func(*oldexpr.args)) - measure(np)
+                            if costsaving > 0:
+                                results.append((costsaving, ([i, j, k], np)))
+        if results:
+            # Sort results based on complexity
+            results = sorted(results,
+                                           key=lambda pair: pair[0], reverse=True)
+            # Replace the one providing most simplification
+            replacement = results[0][1]
+            idx, newrel = replacement
+            idx.sort()
+            # Remove the old relationals
+            for index in reversed(idx):
+                del Rel[index]
+            if dominatingvalue is None or newrel != Not(dominatingvalue):
+                # Insert the new one (no need to insert a value that will
+                # not affect the result)
+                if newrel.func == func:
+                    for a in newrel.args:
+                        Rel.append(a)
+                else:
+                    Rel.append(newrel)
+            # We did change something so try again
+            changed = True
+    return Rel
+
+
+@cacheit
+def _simplify_patterns_and():
+    """ Two-term patterns for And."""
+
+    from sympy.core import Wild
+    from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt
+    from sympy.functions.elementary.complexes import Abs
+    from sympy.functions.elementary.miscellaneous import Min, Max
+    a = Wild('a')
+    b = Wild('b')
+    c = Wild('c')
+    # Relationals patterns should be in alphabetical order
+    # (pattern1, pattern2, simplified)
+    # Do not use Ge, Gt
+    _matchers_and = ((Tuple(Eq(a, b), Lt(a, b)), false),
+                     #(Tuple(Eq(a, b), Lt(b, a)), S.false),
+                     #(Tuple(Le(b, a), Lt(a, b)), S.false),
+                     #(Tuple(Lt(b, a), Le(a, b)), S.false),
+                     (Tuple(Lt(b, a), Lt(a, b)), false),
+                     (Tuple(Eq(a, b), Le(b, a)), Eq(a, b)),
+                     #(Tuple(Eq(a, b), Le(a, b)), Eq(a, b)),
+                     #(Tuple(Le(b, a), Lt(b, a)), Gt(a, b)),
+                     (Tuple(Le(b, a), Le(a, b)), Eq(a, b)),
+                     #(Tuple(Le(b, a), Ne(a, b)), Gt(a, b)),
+                     #(Tuple(Lt(b, a), Ne(a, b)), Gt(a, b)),
+                     (Tuple(Le(a, b), Lt(a, b)), Lt(a, b)),
+                     (Tuple(Le(a, b), Ne(a, b)), Lt(a, b)),
+                     (Tuple(Lt(a, b), Ne(a, b)), Lt(a, b)),
+                     # Sign
+                     (Tuple(Eq(a, b), Eq(a, -b)), And(Eq(a, S.Zero), Eq(b, S.Zero))),
+                     # Min/Max/ITE
+                     (Tuple(Le(b, a), Le(c, a)), Ge(a, Max(b, c))),
+                     (Tuple(Le(b, a), Lt(c, a)), ITE(b > c, Ge(a, b), Gt(a, c))),
+                     (Tuple(Lt(b, a), Lt(c, a)), Gt(a, Max(b, c))),
+                     (Tuple(Le(a, b), Le(a, c)), Le(a, Min(b, c))),
+                     (Tuple(Le(a, b), Lt(a, c)), ITE(b < c, Le(a, b), Lt(a, c))),
+                     (Tuple(Lt(a, b), Lt(a, c)), Lt(a, Min(b, c))),
+                     (Tuple(Le(a, b), Le(c, a)), ITE(Eq(b, c), Eq(a, b), ITE(b < c, false, And(Le(a, b), Ge(a, c))))),
+                     (Tuple(Le(c, a), Le(a, b)), ITE(Eq(b, c), Eq(a, b), ITE(b < c, false, And(Le(a, b), Ge(a, c))))),
+                     (Tuple(Lt(a, b), Lt(c, a)), ITE(b < c, false, And(Lt(a, b), Gt(a, c)))),
+                     (Tuple(Lt(c, a), Lt(a, b)), ITE(b < c, false, And(Lt(a, b), Gt(a, c)))),
+                     (Tuple(Le(a, b), Lt(c, a)), ITE(b <= c, false, And(Le(a, b), Gt(a, c)))),
+                     (Tuple(Le(c, a), Lt(a, b)), ITE(b <= c, false, And(Lt(a, b), Ge(a, c)))),
+                     (Tuple(Eq(a, b), Eq(a, c)), ITE(Eq(b, c), Eq(a, b), false)),
+                     (Tuple(Lt(a, b), Lt(-b, a)), ITE(b > 0, Lt(Abs(a), b), false)),
+                     (Tuple(Le(a, b), Le(-b, a)), ITE(b >= 0, Le(Abs(a), b), false)),
+                     )
+    return _matchers_and
+
+
+@cacheit
+def _simplify_patterns_and3():
+    """ Three-term patterns for And."""
+
+    from sympy.core import Wild
+    from sympy.core.relational import Eq, Ge, Gt
+
+    a = Wild('a')
+    b = Wild('b')
+    c = Wild('c')
+    # Relationals patterns should be in alphabetical order
+    # (pattern1, pattern2, pattern3, simplified)
+    # Do not use Le, Lt
+    _matchers_and = ((Tuple(Ge(a, b), Ge(b, c), Gt(c, a)), false),
+                     (Tuple(Ge(a, b), Gt(b, c), Gt(c, a)), false),
+                     (Tuple(Gt(a, b), Gt(b, c), Gt(c, a)), false),
+                     # (Tuple(Ge(c, a), Gt(a, b), Gt(b, c)), S.false),
+                     # Lower bound relations
+                     # Commented out combinations that does not simplify
+                     (Tuple(Ge(a, b), Ge(a, c), Ge(b, c)), And(Ge(a, b), Ge(b, c))),
+                     (Tuple(Ge(a, b), Ge(a, c), Gt(b, c)), And(Ge(a, b), Gt(b, c))),
+                     # (Tuple(Ge(a, b), Gt(a, c), Ge(b, c)), And(Ge(a, b), Ge(b, c))),
+                     (Tuple(Ge(a, b), Gt(a, c), Gt(b, c)), And(Ge(a, b), Gt(b, c))),
+                     # (Tuple(Gt(a, b), Ge(a, c), Ge(b, c)), And(Gt(a, b), Ge(b, c))),
+                     (Tuple(Ge(a, c), Gt(a, b), Gt(b, c)), And(Gt(a, b), Gt(b, c))),
+                     (Tuple(Ge(b, c), Gt(a, b), Gt(a, c)), And(Gt(a, b), Ge(b, c))),
+                     (Tuple(Gt(a, b), Gt(a, c), Gt(b, c)), And(Gt(a, b), Gt(b, c))),
+                     # Upper bound relations
+                     # Commented out combinations that does not simplify
+                     (Tuple(Ge(b, a), Ge(c, a), Ge(b, c)), And(Ge(c, a), Ge(b, c))),
+                     (Tuple(Ge(b, a), Ge(c, a), Gt(b, c)), And(Ge(c, a), Gt(b, c))),
+                     # (Tuple(Ge(b, a), Gt(c, a), Ge(b, c)), And(Gt(c, a), Ge(b, c))),
+                     (Tuple(Ge(b, a), Gt(c, a), Gt(b, c)), And(Gt(c, a), Gt(b, c))),
+                     # (Tuple(Gt(b, a), Ge(c, a), Ge(b, c)), And(Ge(c, a), Ge(b, c))),
+                     (Tuple(Ge(c, a), Gt(b, a), Gt(b, c)), And(Ge(c, a), Gt(b, c))),
+                     (Tuple(Ge(b, c), Gt(b, a), Gt(c, a)), And(Gt(c, a), Ge(b, c))),
+                     (Tuple(Gt(b, a), Gt(c, a), Gt(b, c)), And(Gt(c, a), Gt(b, c))),
+                     # Circular relation
+                     (Tuple(Ge(a, b), Ge(b, c), Ge(c, a)), And(Eq(a, b), Eq(b, c))),
+                     )
+    return _matchers_and
+
+
+@cacheit
+def _simplify_patterns_or():
+    """ Two-term patterns for Or."""
+
+    from sympy.core import Wild
+    from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt
+    from sympy.functions.elementary.complexes import Abs
+    from sympy.functions.elementary.miscellaneous import Min, Max
+    a = Wild('a')
+    b = Wild('b')
+    c = Wild('c')
+    # Relationals patterns should be in alphabetical order
+    # (pattern1, pattern2, simplified)
+    # Do not use Ge, Gt
+    _matchers_or = ((Tuple(Le(b, a), Le(a, b)), true),
+                    #(Tuple(Le(b, a), Lt(a, b)), true),
+                    (Tuple(Le(b, a), Ne(a, b)), true),
+                    #(Tuple(Le(a, b), Lt(b, a)), true),
+                    #(Tuple(Le(a, b), Ne(a, b)), true),
+                    #(Tuple(Eq(a, b), Le(b, a)), Ge(a, b)),
+                    #(Tuple(Eq(a, b), Lt(b, a)), Ge(a, b)),
+                    (Tuple(Eq(a, b), Le(a, b)), Le(a, b)),
+                    (Tuple(Eq(a, b), Lt(a, b)), Le(a, b)),
+                    #(Tuple(Le(b, a), Lt(b, a)), Ge(a, b)),
+                    (Tuple(Lt(b, a), Lt(a, b)), Ne(a, b)),
+                    (Tuple(Lt(b, a), Ne(a, b)), Ne(a, b)),
+                    (Tuple(Le(a, b), Lt(a, b)), Le(a, b)),
+                    #(Tuple(Lt(a, b), Ne(a, b)), Ne(a, b)),
+                    (Tuple(Eq(a, b), Ne(a, c)), ITE(Eq(b, c), true, Ne(a, c))),
+                    (Tuple(Ne(a, b), Ne(a, c)), ITE(Eq(b, c), Ne(a, b), true)),
+                    # Min/Max/ITE
+                    (Tuple(Le(b, a), Le(c, a)), Ge(a, Min(b, c))),
+                    #(Tuple(Ge(b, a), Ge(c, a)), Ge(Min(b, c), a)),
+                    (Tuple(Le(b, a), Lt(c, a)), ITE(b > c, Lt(c, a), Le(b, a))),
+                    (Tuple(Lt(b, a), Lt(c, a)), Gt(a, Min(b, c))),
+                    #(Tuple(Gt(b, a), Gt(c, a)), Gt(Min(b, c), a)),
+                    (Tuple(Le(a, b), Le(a, c)), Le(a, Max(b, c))),
+                    #(Tuple(Le(b, a), Le(c, a)), Le(Max(b, c), a)),
+                    (Tuple(Le(a, b), Lt(a, c)), ITE(b >= c, Le(a, b), Lt(a, c))),
+                    (Tuple(Lt(a, b), Lt(a, c)), Lt(a, Max(b, c))),
+                    #(Tuple(Lt(b, a), Lt(c, a)), Lt(Max(b, c), a)),
+                    (Tuple(Le(a, b), Le(c, a)), ITE(b >= c, true, Or(Le(a, b), Ge(a, c)))),
+                    (Tuple(Le(c, a), Le(a, b)), ITE(b >= c, true, Or(Le(a, b), Ge(a, c)))),
+                    (Tuple(Lt(a, b), Lt(c, a)), ITE(b > c, true, Or(Lt(a, b), Gt(a, c)))),
+                    (Tuple(Lt(c, a), Lt(a, b)), ITE(b > c, true, Or(Lt(a, b), Gt(a, c)))),
+                    (Tuple(Le(a, b), Lt(c, a)), ITE(b >= c, true, Or(Le(a, b), Gt(a, c)))),
+                    (Tuple(Le(c, a), Lt(a, b)), ITE(b >= c, true, Or(Lt(a, b), Ge(a, c)))),
+                    (Tuple(Lt(b, a), Lt(a, -b)), ITE(b >= 0, Gt(Abs(a), b), true)),
+                    (Tuple(Le(b, a), Le(a, -b)), ITE(b > 0, Ge(Abs(a), b), true)),
+                    )
+    return _matchers_or
+
+
+@cacheit
+def _simplify_patterns_xor():
+    """ Two-term patterns for Xor."""
+
+    from sympy.functions.elementary.miscellaneous import Min, Max
+    from sympy.core import Wild
+    from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt
+    a = Wild('a')
+    b = Wild('b')
+    c = Wild('c')
+    # Relationals patterns should be in alphabetical order
+    # (pattern1, pattern2, simplified)
+    # Do not use Ge, Gt
+    _matchers_xor = (#(Tuple(Le(b, a), Lt(a, b)), true),
+                     #(Tuple(Lt(b, a), Le(a, b)), true),
+                     #(Tuple(Eq(a, b), Le(b, a)), Gt(a, b)),
+                     #(Tuple(Eq(a, b), Lt(b, a)), Ge(a, b)),
+                     (Tuple(Eq(a, b), Le(a, b)), Lt(a, b)),
+                     (Tuple(Eq(a, b), Lt(a, b)), Le(a, b)),
+                     (Tuple(Le(a, b), Lt(a, b)), Eq(a, b)),
+                     (Tuple(Le(a, b), Le(b, a)), Ne(a, b)),
+                     (Tuple(Le(b, a), Ne(a, b)), Le(a, b)),
+                     # (Tuple(Lt(b, a), Lt(a, b)), Ne(a, b)),
+                     (Tuple(Lt(b, a), Ne(a, b)), Lt(a, b)),
+                     # (Tuple(Le(a, b), Lt(a, b)), Eq(a, b)),
+                     # (Tuple(Le(a, b), Ne(a, b)), Ge(a, b)),
+                     # (Tuple(Lt(a, b), Ne(a, b)), Gt(a, b)),
+                     # Min/Max/ITE
+                     (Tuple(Le(b, a), Le(c, a)),
+                      And(Ge(a, Min(b, c)), Lt(a, Max(b, c)))),
+                     (Tuple(Le(b, a), Lt(c, a)),
+                      ITE(b > c, And(Gt(a, c), Lt(a, b)),
+                          And(Ge(a, b), Le(a, c)))),
+                     (Tuple(Lt(b, a), Lt(c, a)),
+                      And(Gt(a, Min(b, c)), Le(a, Max(b, c)))),
+                     (Tuple(Le(a, b), Le(a, c)),
+                      And(Le(a, Max(b, c)), Gt(a, Min(b, c)))),
+                     (Tuple(Le(a, b), Lt(a, c)),
+                      ITE(b < c, And(Lt(a, c), Gt(a, b)),
+                          And(Le(a, b), Ge(a, c)))),
+                     (Tuple(Lt(a, b), Lt(a, c)),
+                      And(Lt(a, Max(b, c)), Ge(a, Min(b, c)))),
+                     )
+    return _matchers_xor
+
+
+def simplify_univariate(expr):
+    """return a simplified version of univariate boolean expression, else ``expr``"""
+    from sympy.functions.elementary.piecewise import Piecewise
+    from sympy.core.relational import Eq, Ne
+    if not isinstance(expr, BooleanFunction):
+        return expr
+    if expr.atoms(Eq, Ne):
+        return expr
+    c = expr
+    free = c.free_symbols
+    if len(free) != 1:
+        return c
+    x = free.pop()
+    ok, i = Piecewise((0, c), evaluate=False
+            )._intervals(x, err_on_Eq=True)
+    if not ok:
+        return c
+    if not i:
+        return false
+    args = []
+    for a, b, _, _ in i:
+        if a is S.NegativeInfinity:
+            if b is S.Infinity:
+                c = true
+            else:
+                if c.subs(x, b) == True:
+                    c = (x <= b)
+                else:
+                    c = (x < b)
+        else:
+            incl_a = (c.subs(x, a) == True)
+            incl_b = (c.subs(x, b) == True)
+            if incl_a and incl_b:
+                if b.is_infinite:
+                    c = (x >= a)
+                else:
+                    c = And(a <= x, x <= b)
+            elif incl_a:
+                c = And(a <= x, x < b)
+            elif incl_b:
+                if b.is_infinite:
+                    c = (x > a)
+                else:
+                    c = And(a < x, x <= b)
+            else:
+                c = And(a < x, x < b)
+        args.append(c)
+    return Or(*args)
+
+
+# Classes corresponding to logic gates
+# Used in gateinputcount method
+BooleanGates = (And, Or, Xor, Nand, Nor, Not, Xnor, ITE)
+
+def gateinputcount(expr):
+    """
+    Return the total number of inputs for the logic gates realizing the
+    Boolean expression.
+
+    Returns
+    =======
+
+    int
+        Number of gate inputs
+
+    Note
+    ====
+
+    Not all Boolean functions count as gate here, only those that are
+    considered to be standard gates. These are: :py:class:`~.And`,
+    :py:class:`~.Or`, :py:class:`~.Xor`, :py:class:`~.Not`, and
+    :py:class:`~.ITE` (multiplexer). :py:class:`~.Nand`, :py:class:`~.Nor`,
+    and :py:class:`~.Xnor` will be evaluated to ``Not(And())`` etc.
+
+    Examples
+    ========
+
+    >>> from sympy.logic import And, Or, Nand, Not, gateinputcount
+    >>> from sympy.abc import x, y, z
+    >>> expr = And(x, y)
+    >>> gateinputcount(expr)
+    2
+    >>> gateinputcount(Or(expr, z))
+    4
+
+    Note that ``Nand`` is automatically evaluated to ``Not(And())`` so
+
+    >>> gateinputcount(Nand(x, y, z))
+    4
+    >>> gateinputcount(Not(And(x, y, z)))
+    4
+
+    Although this can be avoided by using ``evaluate=False``
+
+    >>> gateinputcount(Nand(x, y, z, evaluate=False))
+    3
+
+    Also note that a comparison will count as a Boolean variable:
+
+    >>> gateinputcount(And(x > z, y >= 2))
+    2
+
+    As will a symbol:
+    >>> gateinputcount(x)
+    0
+
+    """
+    if not isinstance(expr, Boolean):
+        raise TypeError("Expression must be Boolean")
+    if isinstance(expr, BooleanGates):
+        return len(expr.args) + sum(gateinputcount(x) for x in expr.args)
+    return 0
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/inference.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/inference.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3798231c09ae351ea7e7026d622b834fea3e3fa
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/inference.py
@@ -0,0 +1,340 @@
+"""Inference in propositional logic"""
+
+from sympy.logic.boolalg import And, Not, conjuncts, to_cnf, BooleanFunction
+from sympy.core.sorting import ordered
+from sympy.core.sympify import sympify
+from sympy.external.importtools import import_module
+
+
+def literal_symbol(literal):
+    """
+    The symbol in this literal (without the negation).
+
+    Examples
+    ========
+
+    >>> from sympy.abc import A
+    >>> from sympy.logic.inference import literal_symbol
+    >>> literal_symbol(A)
+    A
+    >>> literal_symbol(~A)
+    A
+
+    """
+
+    if literal is True or literal is False:
+        return literal
+    elif literal.is_Symbol:
+        return literal
+    elif literal.is_Not:
+        return literal_symbol(literal.args[0])
+    else:
+        raise ValueError("Argument must be a boolean literal.")
+
+
+def satisfiable(expr, algorithm=None, all_models=False, minimal=False, use_lra_theory=False):
+    """
+    Check satisfiability of a propositional sentence.
+    Returns a model when it succeeds.
+    Returns {true: true} for trivially true expressions.
+
+    On setting all_models to True, if given expr is satisfiable then
+    returns a generator of models. However, if expr is unsatisfiable
+    then returns a generator containing the single element False.
+
+    Examples
+    ========
+
+    >>> from sympy.abc import A, B
+    >>> from sympy.logic.inference import satisfiable
+    >>> satisfiable(A & ~B)
+    {A: True, B: False}
+    >>> satisfiable(A & ~A)
+    False
+    >>> satisfiable(True)
+    {True: True}
+    >>> next(satisfiable(A & ~A, all_models=True))
+    False
+    >>> models = satisfiable((A >> B) & B, all_models=True)
+    >>> next(models)
+    {A: False, B: True}
+    >>> next(models)
+    {A: True, B: True}
+    >>> def use_models(models):
+    ...     for model in models:
+    ...         if model:
+    ...             # Do something with the model.
+    ...             print(model)
+    ...         else:
+    ...             # Given expr is unsatisfiable.
+    ...             print("UNSAT")
+    >>> use_models(satisfiable(A >> ~A, all_models=True))
+    {A: False}
+    >>> use_models(satisfiable(A ^ A, all_models=True))
+    UNSAT
+
+    """
+    if use_lra_theory:
+        if algorithm is not None and algorithm != "dpll2":
+            raise ValueError(f"Currently only dpll2 can handle using lra theory. {algorithm} is not handled.")
+        algorithm = "dpll2"
+
+    if algorithm is None or algorithm == "pycosat":
+        pycosat = import_module('pycosat')
+        if pycosat is not None:
+            algorithm = "pycosat"
+        else:
+            if algorithm == "pycosat":
+                raise ImportError("pycosat module is not present")
+            # Silently fall back to dpll2 if pycosat
+            # is not installed
+            algorithm = "dpll2"
+
+    if algorithm=="minisat22":
+        pysat = import_module('pysat')
+        if pysat is None:
+            algorithm = "dpll2"
+
+    if algorithm=="z3":
+        z3 = import_module('z3')
+        if z3 is None:
+            algorithm = "dpll2"
+
+    if algorithm == "dpll":
+        from sympy.logic.algorithms.dpll import dpll_satisfiable
+        return dpll_satisfiable(expr)
+    elif algorithm == "dpll2":
+        from sympy.logic.algorithms.dpll2 import dpll_satisfiable
+        return dpll_satisfiable(expr, all_models, use_lra_theory=use_lra_theory)
+    elif algorithm == "pycosat":
+        from sympy.logic.algorithms.pycosat_wrapper import pycosat_satisfiable
+        return pycosat_satisfiable(expr, all_models)
+    elif algorithm == "minisat22":
+        from sympy.logic.algorithms.minisat22_wrapper import minisat22_satisfiable
+        return minisat22_satisfiable(expr, all_models, minimal)
+    elif algorithm == "z3":
+        from sympy.logic.algorithms.z3_wrapper import z3_satisfiable
+        return z3_satisfiable(expr, all_models)
+
+    raise NotImplementedError
+
+
+def valid(expr):
+    """
+    Check validity of a propositional sentence.
+    A valid propositional sentence is True under every assignment.
+
+    Examples
+    ========
+
+    >>> from sympy.abc import A, B
+    >>> from sympy.logic.inference import valid
+    >>> valid(A | ~A)
+    True
+    >>> valid(A | B)
+    False
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Validity
+
+    """
+    return not satisfiable(Not(expr))
+
+
+def pl_true(expr, model=None, deep=False):
+    """
+    Returns whether the given assignment is a model or not.
+
+    If the assignment does not specify the value for every proposition,
+    this may return None to indicate 'not obvious'.
+
+    Parameters
+    ==========
+
+    model : dict, optional, default: {}
+        Mapping of symbols to boolean values to indicate assignment.
+    deep: boolean, optional, default: False
+        Gives the value of the expression under partial assignments
+        correctly. May still return None to indicate 'not obvious'.
+
+
+    Examples
+    ========
+
+    >>> from sympy.abc import A, B
+    >>> from sympy.logic.inference import pl_true
+    >>> pl_true( A & B, {A: True, B: True})
+    True
+    >>> pl_true(A & B, {A: False})
+    False
+    >>> pl_true(A & B, {A: True})
+    >>> pl_true(A & B, {A: True}, deep=True)
+    >>> pl_true(A >> (B >> A))
+    >>> pl_true(A >> (B >> A), deep=True)
+    True
+    >>> pl_true(A & ~A)
+    >>> pl_true(A & ~A, deep=True)
+    False
+    >>> pl_true(A & B & (~A | ~B), {A: True})
+    >>> pl_true(A & B & (~A | ~B), {A: True}, deep=True)
+    False
+
+    """
+
+    from sympy.core.symbol import Symbol
+
+    boolean = (True, False)
+
+    def _validate(expr):
+        if isinstance(expr, Symbol) or expr in boolean:
+            return True
+        if not isinstance(expr, BooleanFunction):
+            return False
+        return all(_validate(arg) for arg in expr.args)
+
+    if expr in boolean:
+        return expr
+    expr = sympify(expr)
+    if not _validate(expr):
+        raise ValueError("%s is not a valid boolean expression" % expr)
+    if not model:
+        model = {}
+    model = {k: v for k, v in model.items() if v in boolean}
+    result = expr.subs(model)
+    if result in boolean:
+        return bool(result)
+    if deep:
+        model = dict.fromkeys(result.atoms(), True)
+        if pl_true(result, model):
+            if valid(result):
+                return True
+        else:
+            if not satisfiable(result):
+                return False
+    return None
+
+
+def entails(expr, formula_set=None):
+    """
+    Check whether the given expr_set entail an expr.
+    If formula_set is empty then it returns the validity of expr.
+
+    Examples
+    ========
+
+    >>> from sympy.abc import A, B, C
+    >>> from sympy.logic.inference import entails
+    >>> entails(A, [A >> B, B >> C])
+    False
+    >>> entails(C, [A >> B, B >> C, A])
+    True
+    >>> entails(A >> B)
+    False
+    >>> entails(A >> (B >> A))
+    True
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Logical_consequence
+
+    """
+    if formula_set:
+        formula_set = list(formula_set)
+    else:
+        formula_set = []
+    formula_set.append(Not(expr))
+    return not satisfiable(And(*formula_set))
+
+
+class KB:
+    """Base class for all knowledge bases"""
+    def __init__(self, sentence=None):
+        self.clauses_ = set()
+        if sentence:
+            self.tell(sentence)
+
+    def tell(self, sentence):
+        raise NotImplementedError
+
+    def ask(self, query):
+        raise NotImplementedError
+
+    def retract(self, sentence):
+        raise NotImplementedError
+
+    @property
+    def clauses(self):
+        return list(ordered(self.clauses_))
+
+
+class PropKB(KB):
+    """A KB for Propositional Logic.  Inefficient, with no indexing."""
+
+    def tell(self, sentence):
+        """Add the sentence's clauses to the KB
+
+        Examples
+        ========
+
+        >>> from sympy.logic.inference import PropKB
+        >>> from sympy.abc import x, y
+        >>> l = PropKB()
+        >>> l.clauses
+        []
+
+        >>> l.tell(x | y)
+        >>> l.clauses
+        [x | y]
+
+        >>> l.tell(y)
+        >>> l.clauses
+        [y, x | y]
+
+        """
+        for c in conjuncts(to_cnf(sentence)):
+            self.clauses_.add(c)
+
+    def ask(self, query):
+        """Checks if the query is true given the set of clauses.
+
+        Examples
+        ========
+
+        >>> from sympy.logic.inference import PropKB
+        >>> from sympy.abc import x, y
+        >>> l = PropKB()
+        >>> l.tell(x & ~y)
+        >>> l.ask(x)
+        True
+        >>> l.ask(y)
+        False
+
+        """
+        return entails(query, self.clauses_)
+
+    def retract(self, sentence):
+        """Remove the sentence's clauses from the KB
+
+        Examples
+        ========
+
+        >>> from sympy.logic.inference import PropKB
+        >>> from sympy.abc import x, y
+        >>> l = PropKB()
+        >>> l.clauses
+        []
+
+        >>> l.tell(x | y)
+        >>> l.clauses
+        [x | y]
+
+        >>> l.retract(x | y)
+        >>> l.clauses
+        []
+
+        """
+        for c in conjuncts(to_cnf(sentence)):
+            self.clauses_.discard(c)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/tests/test_boolalg.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/tests/test_boolalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..88cdd647fdcc723faee328f71df96030841a3edb
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/tests/test_boolalg.py
@@ -0,0 +1,1367 @@
+from sympy.assumptions.ask import Q
+from sympy.assumptions.refine import refine
+from sympy.core.numbers import oo
+from sympy.core.relational import Equality, Eq, Ne
+from sympy.core.singleton import S
+from sympy.core.symbol import (Dummy, symbols)
+from sympy.functions import Piecewise
+from sympy.functions.elementary.trigonometric import cos, sin
+from sympy.sets.sets import Interval, Union
+from sympy.sets.contains import Contains
+from sympy.simplify.simplify import simplify
+from sympy.logic.boolalg import (
+    And, Boolean, Equivalent, ITE, Implies, Nand, Nor, Not, Or,
+    POSform, SOPform, Xor, Xnor, conjuncts, disjuncts,
+    distribute_or_over_and, distribute_and_over_or,
+    eliminate_implications, is_nnf, is_cnf, is_dnf, simplify_logic,
+    to_nnf, to_cnf, to_dnf, to_int_repr, bool_map, true, false,
+    BooleanAtom, is_literal, term_to_integer,
+    truth_table, as_Boolean, to_anf, is_anf, distribute_xor_over_and,
+    anf_coeffs, ANFform, bool_minterm, bool_maxterm, bool_monomial,
+    _check_pair, _convert_to_varsSOP, _convert_to_varsPOS, Exclusive,
+    gateinputcount)
+from sympy.assumptions.cnf import CNF
+
+from sympy.testing.pytest import raises, XFAIL, slow
+
+from itertools import combinations, permutations, product
+
+A, B, C, D = symbols('A:D')
+a, b, c, d, e, w, x, y, z = symbols('a:e w:z')
+
+
+def test_overloading():
+    """Test that |, & are overloaded as expected"""
+
+    assert A & B == And(A, B)
+    assert A | B == Or(A, B)
+    assert (A & B) | C == Or(And(A, B), C)
+    assert A >> B == Implies(A, B)
+    assert A << B == Implies(B, A)
+    assert ~A == Not(A)
+    assert A ^ B == Xor(A, B)
+
+
+def test_And():
+    assert And() is true
+    assert And(A) == A
+    assert And(True) is true
+    assert And(False) is false
+    assert And(True, True) is true
+    assert And(True, False) is false
+    assert And(False, False) is false
+    assert And(True, A) == A
+    assert And(False, A) is false
+    assert And(True, True, True) is true
+    assert And(True, True, A) == A
+    assert And(True, False, A) is false
+    assert And(1, A) == A
+    raises(TypeError, lambda: And(2, A))
+    assert And(A < 1, A >= 1) is false
+    e = A > 1
+    assert And(e, e.canonical) == e.canonical
+    g, l, ge, le = A > B, B < A, A >= B, B <= A
+    assert And(g, l, ge, le) == And(ge, g)
+    assert {And(*i) for i in permutations((l, g, le, ge))} == {And(ge, g)}
+    assert And(And(Eq(a, 0), Eq(b, 0)), And(Ne(a, 0), Eq(c, 0))) is false
+
+
+def test_Or():
+    assert Or() is false
+    assert Or(A) == A
+    assert Or(True) is true
+    assert Or(False) is false
+    assert Or(True, True) is true
+    assert Or(True, False) is true
+    assert Or(False, False) is false
+    assert Or(True, A) is true
+    assert Or(False, A) == A
+    assert Or(True, False, False) is true
+    assert Or(True, False, A) is true
+    assert Or(False, False, A) == A
+    assert Or(1, A) is true
+    raises(TypeError, lambda: Or(2, A))
+    assert Or(A < 1, A >= 1) is true
+    e = A > 1
+    assert Or(e, e.canonical) == e
+    g, l, ge, le = A > B, B < A, A >= B, B <= A
+    assert Or(g, l, ge, le) == Or(g, ge)
+
+
+def test_Xor():
+    assert Xor() is false
+    assert Xor(A) == A
+    assert Xor(A, A) is false
+    assert Xor(True, A, A) is true
+    assert Xor(A, A, A, A, A) == A
+    assert Xor(True, False, False, A, B) == ~Xor(A, B)
+    assert Xor(True) is true
+    assert Xor(False) is false
+    assert Xor(True, True) is false
+    assert Xor(True, False) is true
+    assert Xor(False, False) is false
+    assert Xor(True, A) == ~A
+    assert Xor(False, A) == A
+    assert Xor(True, False, False) is true
+    assert Xor(True, False, A) == ~A
+    assert Xor(False, False, A) == A
+    assert isinstance(Xor(A, B), Xor)
+    assert Xor(A, B, Xor(C, D)) == Xor(A, B, C, D)
+    assert Xor(A, B, Xor(B, C)) == Xor(A, C)
+    assert Xor(A < 1, A >= 1, B) == Xor(0, 1, B) == Xor(1, 0, B)
+    e = A > 1
+    assert Xor(e, e.canonical) == Xor(0, 0) == Xor(1, 1)
+
+
+def test_rewrite_as_And():
+    expr = x ^ y
+    assert expr.rewrite(And) == (x | y) & (~x | ~y)
+
+
+def test_rewrite_as_Or():
+    expr = x ^ y
+    assert expr.rewrite(Or) == (x & ~y) | (y & ~x)
+
+
+def test_rewrite_as_Nand():
+    expr = (y & z) | (z & ~w)
+    assert expr.rewrite(Nand) == ~(~(y & z) & ~(z & ~w))
+
+
+def test_rewrite_as_Nor():
+    expr = z & (y | ~w)
+    assert expr.rewrite(Nor) == ~(~z | ~(y | ~w))
+
+
+def test_Not():
+    raises(TypeError, lambda: Not(True, False))
+    assert Not(True) is false
+    assert Not(False) is true
+    assert Not(0) is true
+    assert Not(1) is false
+    assert Not(2) is false
+
+
+def test_Nand():
+    assert Nand() is false
+    assert Nand(A) == ~A
+    assert Nand(True) is false
+    assert Nand(False) is true
+    assert Nand(True, True) is false
+    assert Nand(True, False) is true
+    assert Nand(False, False) is true
+    assert Nand(True, A) == ~A
+    assert Nand(False, A) is true
+    assert Nand(True, True, True) is false
+    assert Nand(True, True, A) == ~A
+    assert Nand(True, False, A) is true
+
+
+def test_Nor():
+    assert Nor() is true
+    assert Nor(A) == ~A
+    assert Nor(True) is false
+    assert Nor(False) is true
+    assert Nor(True, True) is false
+    assert Nor(True, False) is false
+    assert Nor(False, False) is true
+    assert Nor(True, A) is false
+    assert Nor(False, A) == ~A
+    assert Nor(True, True, True) is false
+    assert Nor(True, True, A) is false
+    assert Nor(True, False, A) is false
+
+
+def test_Xnor():
+    assert Xnor() is true
+    assert Xnor(A) == ~A
+    assert Xnor(A, A) is true
+    assert Xnor(True, A, A) is false
+    assert Xnor(A, A, A, A, A) == ~A
+    assert Xnor(True) is false
+    assert Xnor(False) is true
+    assert Xnor(True, True) is true
+    assert Xnor(True, False) is false
+    assert Xnor(False, False) is true
+    assert Xnor(True, A) == A
+    assert Xnor(False, A) == ~A
+    assert Xnor(True, False, False) is false
+    assert Xnor(True, False, A) == A
+    assert Xnor(False, False, A) == ~A
+
+
+def test_Implies():
+    raises(ValueError, lambda: Implies(A, B, C))
+    assert Implies(True, True) is true
+    assert Implies(True, False) is false
+    assert Implies(False, True) is true
+    assert Implies(False, False) is true
+    assert Implies(0, A) is true
+    assert Implies(1, 1) is true
+    assert Implies(1, 0) is false
+    assert A >> B == B << A
+    assert (A < 1) >> (A >= 1) == (A >= 1)
+    assert (A < 1) >> (S.One > A) is true
+    assert A >> A is true
+
+
+def test_Equivalent():
+    assert Equivalent(A, B) == Equivalent(B, A) == Equivalent(A, B, A)
+    assert Equivalent() is true
+    assert Equivalent(A, A) == Equivalent(A) is true
+    assert Equivalent(True, True) == Equivalent(False, False) is true
+    assert Equivalent(True, False) == Equivalent(False, True) is false
+    assert Equivalent(A, True) == A
+    assert Equivalent(A, False) == Not(A)
+    assert Equivalent(A, B, True) == A & B
+    assert Equivalent(A, B, False) == ~A & ~B
+    assert Equivalent(1, A) == A
+    assert Equivalent(0, A) == Not(A)
+    assert Equivalent(A, Equivalent(B, C)) != Equivalent(Equivalent(A, B), C)
+    assert Equivalent(A < 1, A >= 1) is false
+    assert Equivalent(A < 1, A >= 1, 0) is false
+    assert Equivalent(A < 1, A >= 1, 1) is false
+    assert Equivalent(A < 1, S.One > A) == Equivalent(1, 1) == Equivalent(0, 0)
+    assert Equivalent(Equality(A, B), Equality(B, A)) is true
+
+
+def test_Exclusive():
+    assert Exclusive(False, False, False) is true
+    assert Exclusive(True, False, False) is true
+    assert Exclusive(True, True, False) is false
+    assert Exclusive(True, True, True) is false
+
+
+def test_equals():
+    assert Not(Or(A, B)).equals(And(Not(A), Not(B))) is True
+    assert Equivalent(A, B).equals((A >> B) & (B >> A)) is True
+    assert ((A | ~B) & (~A | B)).equals((~A & ~B) | (A & B)) is True
+    assert (A >> B).equals(~A >> ~B) is False
+    assert (A >> (B >> A)).equals(A >> (C >> A)) is False
+    raises(NotImplementedError, lambda: (A & B).equals(A > B))
+
+
+def test_simplification_boolalg():
+    """
+    Test working of simplification methods.
+    """
+    set1 = [[0, 0, 1], [0, 1, 1], [1, 0, 0], [1, 1, 0]]
+    set2 = [[0, 0, 0], [0, 1, 0], [1, 0, 1], [1, 1, 1]]
+    assert SOPform([x, y, z], set1) == Or(And(Not(x), z), And(Not(z), x))
+    assert Not(SOPform([x, y, z], set2)) == \
+           Not(Or(And(Not(x), Not(z)), And(x, z)))
+    assert POSform([x, y, z], set1 + set2) is true
+    assert SOPform([x, y, z], set1 + set2) is true
+    assert SOPform([Dummy(), Dummy(), Dummy()], set1 + set2) is true
+
+    minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1],
+                [1, 1, 1, 1]]
+    dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]]
+    assert (
+        SOPform([w, x, y, z], minterms, dontcares) ==
+        Or(And(y, z), And(Not(w), Not(x))))
+    assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)
+
+    minterms = [1, 3, 7, 11, 15]
+    dontcares = [0, 2, 5]
+    assert (
+        SOPform([w, x, y, z], minterms, dontcares) ==
+        Or(And(y, z), And(Not(w), Not(x))))
+    assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)
+
+    minterms = [1, [0, 0, 1, 1], 7, [1, 0, 1, 1],
+                [1, 1, 1, 1]]
+    dontcares = [0, [0, 0, 1, 0], 5]
+    assert (
+        SOPform([w, x, y, z], minterms, dontcares) ==
+        Or(And(y, z), And(Not(w), Not(x))))
+    assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)
+
+    minterms = [1, {y: 1, z: 1}]
+    dontcares = [0, [0, 0, 1, 0], 5]
+    assert (
+        SOPform([w, x, y, z], minterms, dontcares) ==
+        Or(And(y, z), And(Not(w), Not(x))))
+    assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)
+
+    minterms = [{y: 1, z: 1}, 1]
+    dontcares = [[0, 0, 0, 0]]
+
+    minterms = [[0, 0, 0]]
+    raises(ValueError, lambda: SOPform([w, x, y, z], minterms))
+    raises(ValueError, lambda: POSform([w, x, y, z], minterms))
+
+    raises(TypeError, lambda: POSform([w, x, y, z], ["abcdefg"]))
+
+    # test simplification
+    ans = And(A, Or(B, C))
+    assert simplify_logic(A & (B | C)) == ans
+    assert simplify_logic((A & B) | (A & C)) == ans
+    assert simplify_logic(Implies(A, B)) == Or(Not(A), B)
+    assert simplify_logic(Equivalent(A, B)) == \
+           Or(And(A, B), And(Not(A), Not(B)))
+    assert simplify_logic(And(Equality(A, 2), C)) == And(Equality(A, 2), C)
+    assert simplify_logic(And(Equality(A, 2), A)) == And(Equality(A, 2), A)
+    assert simplify_logic(And(Equality(A, B), C)) == And(Equality(A, B), C)
+    assert simplify_logic(Or(And(Equality(A, 3), B), And(Equality(A, 3), C))) \
+           == And(Equality(A, 3), Or(B, C))
+    b = (~x & ~y & ~z) | (~x & ~y & z)
+    e = And(A, b)
+    assert simplify_logic(e) == A & ~x & ~y
+    raises(ValueError, lambda: simplify_logic(A & (B | C), form='blabla'))
+    assert simplify(Or(x <= y, And(x < y, z))) == (x <= y)
+    assert simplify(Or(x <= y, And(y > x, z))) == (x <= y)
+    assert simplify(Or(x >= y, And(y < x, z))) == (x >= y)
+
+    # Check that expressions with nine variables or more are not simplified
+    # (without the force-flag)
+    a, b, c, d, e, f, g, h, j = symbols('a b c d e f g h j')
+    expr = a & b & c & d & e & f & g & h & j | \
+           a & b & c & d & e & f & g & h & ~j
+    # This expression can be simplified to get rid of the j variables
+    assert simplify_logic(expr) == expr
+
+    # Test dontcare
+    assert simplify_logic((a & b) | c | d, dontcare=(a & b)) == c | d
+
+    # check input
+    ans = SOPform([x, y], [[1, 0]])
+    assert SOPform([x, y], [[1, 0]]) == ans
+    assert POSform([x, y], [[1, 0]]) == ans
+
+    raises(ValueError, lambda: SOPform([x], [[1]], [[1]]))
+    assert SOPform([x], [[1]], [[0]]) is true
+    assert SOPform([x], [[0]], [[1]]) is true
+    assert SOPform([x], [], []) is false
+
+    raises(ValueError, lambda: POSform([x], [[1]], [[1]]))
+    assert POSform([x], [[1]], [[0]]) is true
+    assert POSform([x], [[0]], [[1]]) is true
+    assert POSform([x], [], []) is false
+
+    # check working of simplify
+    assert simplify((A & B) | (A & C)) == And(A, Or(B, C))
+    assert simplify(And(x, Not(x))) == False
+    assert simplify(Or(x, Not(x))) == True
+    assert simplify(And(Eq(x, 0), Eq(x, y))) == And(Eq(x, 0), Eq(y, 0))
+    assert And(Eq(x - 1, 0), Eq(x, y)).simplify() == And(Eq(x, 1), Eq(y, 1))
+    assert And(Ne(x - 1, 0), Ne(x, y)).simplify() == And(Ne(x, 1), Ne(x, y))
+    assert And(Eq(x - 1, 0), Ne(x, y)).simplify() == And(Eq(x, 1), Ne(y, 1))
+    assert And(Eq(x - 1, 0), Eq(x, z + y), Eq(y + x, 0)).simplify(
+    ) == And(Eq(x, 1), Eq(y, -1), Eq(z, 2))
+    assert And(Eq(x - 1, 0), Eq(x + 2, 3)).simplify() == Eq(x, 1)
+    assert And(Ne(x - 1, 0), Ne(x + 2, 3)).simplify() == Ne(x, 1)
+    assert And(Eq(x - 1, 0), Eq(x + 2, 2)).simplify() == False
+    assert And(Ne(x - 1, 0), Ne(x + 2, 2)).simplify(
+    ) == And(Ne(x, 1), Ne(x, 0))
+    assert simplify(Xor(x, ~x)) == True
+
+
+def test_bool_map():
+    """
+    Test working of bool_map function.
+    """
+
+    minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1],
+                [1, 1, 1, 1]]
+    assert bool_map(Not(Not(a)), a) == (a, {a: a})
+    assert bool_map(SOPform([w, x, y, z], minterms),
+                    POSform([w, x, y, z], minterms)) == \
+           (And(Or(Not(w), y), Or(Not(x), y), z), {x: x, w: w, z: z, y: y})
+    assert bool_map(SOPform([x, z, y], [[1, 0, 1]]),
+                    SOPform([a, b, c], [[1, 0, 1]])) != False
+    function1 = SOPform([x, z, y], [[1, 0, 1], [0, 0, 1]])
+    function2 = SOPform([a, b, c], [[1, 0, 1], [1, 0, 0]])
+    assert bool_map(function1, function2) == \
+           (function1, {y: a, z: b})
+    assert bool_map(Xor(x, y), ~Xor(x, y)) == False
+    assert bool_map(And(x, y), Or(x, y)) is None
+    assert bool_map(And(x, y), And(x, y, z)) is None
+    # issue 16179
+    assert bool_map(Xor(x, y, z), ~Xor(x, y, z)) == False
+    assert bool_map(Xor(a, x, y, z), ~Xor(a, x, y, z)) == False
+
+
+def test_bool_symbol():
+    """Test that mixing symbols with boolean values
+    works as expected"""
+
+    assert And(A, True) == A
+    assert And(A, True, True) == A
+    assert And(A, False) is false
+    assert And(A, True, False) is false
+    assert Or(A, True) is true
+    assert Or(A, False) == A
+
+
+def test_is_boolean():
+    assert isinstance(True, Boolean) is False
+    assert isinstance(true, Boolean) is True
+    assert 1 == True
+    assert 1 != true
+    assert (1 == true) is False
+    assert 0 == False
+    assert 0 != false
+    assert (0 == false) is False
+    assert true.is_Boolean is True
+    assert (A & B).is_Boolean
+    assert (A | B).is_Boolean
+    assert (~A).is_Boolean
+    assert (A ^ B).is_Boolean
+    assert A.is_Boolean != isinstance(A, Boolean)
+    assert isinstance(A, Boolean)
+
+
+def test_subs():
+    assert (A & B).subs(A, True) == B
+    assert (A & B).subs(A, False) is false
+    assert (A & B).subs(B, True) == A
+    assert (A & B).subs(B, False) is false
+    assert (A & B).subs({A: True, B: True}) is true
+    assert (A | B).subs(A, True) is true
+    assert (A | B).subs(A, False) == B
+    assert (A | B).subs(B, True) is true
+    assert (A | B).subs(B, False) == A
+    assert (A | B).subs({A: True, B: True}) is true
+
+
+"""
+we test for axioms of boolean algebra
+see https://en.wikipedia.org/wiki/Boolean_algebra_(structure)
+"""
+
+
+def test_commutative():
+    """Test for commutativity of And and Or"""
+    A, B = map(Boolean, symbols('A,B'))
+
+    assert A & B == B & A
+    assert A | B == B | A
+
+
+def test_and_associativity():
+    """Test for associativity of And"""
+
+    assert (A & B) & C == A & (B & C)
+
+
+def test_or_assicativity():
+    assert ((A | B) | C) == (A | (B | C))
+
+
+def test_double_negation():
+    a = Boolean()
+    assert ~(~a) == a
+
+
+# test methods
+
+def test_eliminate_implications():
+    assert eliminate_implications(Implies(A, B, evaluate=False)) == (~A) | B
+    assert eliminate_implications(
+        A >> (C >> Not(B))) == Or(Or(Not(B), Not(C)), Not(A))
+    assert eliminate_implications(Equivalent(A, B, C, D)) == \
+           (~A | B) & (~B | C) & (~C | D) & (~D | A)
+
+
+def test_conjuncts():
+    assert conjuncts(A & B & C) == {A, B, C}
+    assert conjuncts((A | B) & C) == {A | B, C}
+    assert conjuncts(A) == {A}
+    assert conjuncts(True) == {True}
+    assert conjuncts(False) == {False}
+
+
+def test_disjuncts():
+    assert disjuncts(A | B | C) == {A, B, C}
+    assert disjuncts((A | B) & C) == {(A | B) & C}
+    assert disjuncts(A) == {A}
+    assert disjuncts(True) == {True}
+    assert disjuncts(False) == {False}
+
+
+def test_distribute():
+    assert distribute_and_over_or(Or(And(A, B), C)) == And(Or(A, C), Or(B, C))
+    assert distribute_or_over_and(And(A, Or(B, C))) == Or(And(A, B), And(A, C))
+    assert distribute_xor_over_and(And(A, Xor(B, C))) == Xor(And(A, B), And(A, C))
+
+
+def test_to_anf():
+    x, y, z = symbols('x,y,z')
+    assert to_anf(And(x, y)) == And(x, y)
+    assert to_anf(Or(x, y)) == Xor(x, y, And(x, y))
+    assert to_anf(Or(Implies(x, y), And(x, y), y)) == \
+           Xor(x, True, x & y, remove_true=False)
+    assert to_anf(Or(Nand(x, y), Nor(x, y), Xnor(x, y), Implies(x, y))) == True
+    assert to_anf(Or(x, Not(y), Nor(x, z), And(x, y), Nand(y, z))) == \
+           Xor(True, And(y, z), And(x, y, z), remove_true=False)
+    assert to_anf(Xor(x, y)) == Xor(x, y)
+    assert to_anf(Not(x)) == Xor(x, True, remove_true=False)
+    assert to_anf(Nand(x, y)) == Xor(True, And(x, y), remove_true=False)
+    assert to_anf(Nor(x, y)) == Xor(x, y, True, And(x, y), remove_true=False)
+    assert to_anf(Implies(x, y)) == Xor(x, True, And(x, y), remove_true=False)
+    assert to_anf(Equivalent(x, y)) == Xor(x, y, True, remove_true=False)
+    assert to_anf(Nand(x | y, x >> y), deep=False) == \
+           Xor(True, And(Or(x, y), Implies(x, y)), remove_true=False)
+    assert to_anf(Nor(x ^ y, x & y), deep=False) == \
+           Xor(True, Or(Xor(x, y), And(x, y)), remove_true=False)
+    # issue 25218
+    assert to_anf(x ^ ~(x ^ y ^ ~y)) == False
+
+
+def test_to_nnf():
+    assert to_nnf(true) is true
+    assert to_nnf(false) is false
+    assert to_nnf(A) == A
+    assert to_nnf(A | ~A | B) is true
+    assert to_nnf(A & ~A & B) is false
+    assert to_nnf(A >> B) == ~A | B
+    assert to_nnf(Equivalent(A, B, C)) == (~A | B) & (~B | C) & (~C | A)
+    assert to_nnf(A ^ B ^ C) == \
+           (A | B | C) & (~A | ~B | C) & (A | ~B | ~C) & (~A | B | ~C)
+    assert to_nnf(ITE(A, B, C)) == (~A | B) & (A | C)
+    assert to_nnf(Not(A | B | C)) == ~A & ~B & ~C
+    assert to_nnf(Not(A & B & C)) == ~A | ~B | ~C
+    assert to_nnf(Not(A >> B)) == A & ~B
+    assert to_nnf(Not(Equivalent(A, B, C))) == And(Or(A, B, C), Or(~A, ~B, ~C))
+    assert to_nnf(Not(A ^ B ^ C)) == \
+           (~A | B | C) & (A | ~B | C) & (A | B | ~C) & (~A | ~B | ~C)
+    assert to_nnf(Not(ITE(A, B, C))) == (~A | ~B) & (A | ~C)
+    assert to_nnf((A >> B) ^ (B >> A)) == (A & ~B) | (~A & B)
+    assert to_nnf((A >> B) ^ (B >> A), False) == \
+           (~A | ~B | A | B) & ((A & ~B) | (~A & B))
+    assert ITE(A, 1, 0).to_nnf() == A
+    assert ITE(A, 0, 1).to_nnf() == ~A
+    # although ITE can hold non-Boolean, it will complain if
+    # an attempt is made to convert the ITE to Boolean nnf
+    raises(TypeError, lambda: ITE(A < 1, [1], B).to_nnf())
+
+
+def test_to_cnf():
+    assert to_cnf(~(B | C)) == And(Not(B), Not(C))
+    assert to_cnf((A & B) | C) == And(Or(A, C), Or(B, C))
+    assert to_cnf(A >> B) == (~A) | B
+    assert to_cnf(A >> (B & C)) == (~A | B) & (~A | C)
+    assert to_cnf(A & (B | C) | ~A & (B | C), True) == B | C
+    assert to_cnf(A & B) == And(A, B)
+
+    assert to_cnf(Equivalent(A, B)) == And(Or(A, Not(B)), Or(B, Not(A)))
+    assert to_cnf(Equivalent(A, B & C)) == \
+           (~A | B) & (~A | C) & (~B | ~C | A)
+    assert to_cnf(Equivalent(A, B | C), True) == \
+           And(Or(Not(B), A), Or(Not(C), A), Or(B, C, Not(A)))
+    assert to_cnf(A + 1) == A + 1
+
+
+def test_issue_18904():
+    x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15 = symbols('x1:16')
+    eq = ((x1 & x2 & x3 & x4 & x5 & x6 & x7 & x8 & x9) |
+          (x1 & x2 & x3 & x4 & x5 & x6 & x7 & x10 & x9) |
+          (x1 & x11 & x3 & x12 & x5 & x13 & x14 & x15 & x9))
+    assert is_cnf(to_cnf(eq))
+    raises(ValueError, lambda: to_cnf(eq, simplify=True))
+    for f, t in zip((And, Or), (to_cnf, to_dnf)):
+        eq = f(x1, x2, x3, x4, x5, x6, x7, x8, x9)
+        raises(ValueError, lambda: to_cnf(eq, simplify=True))
+        assert t(eq, simplify=True, force=True) == eq
+
+
+def test_issue_9949():
+    assert is_cnf(to_cnf((b > -5) | (a > 2) & (a < 4)))
+
+
+def test_to_CNF():
+    assert CNF.CNF_to_cnf(CNF.to_CNF(~(B | C))) == to_cnf(~(B | C))
+    assert CNF.CNF_to_cnf(CNF.to_CNF((A & B) | C)) == to_cnf((A & B) | C)
+    assert CNF.CNF_to_cnf(CNF.to_CNF(A >> B)) == to_cnf(A >> B)
+    assert CNF.CNF_to_cnf(CNF.to_CNF(A >> (B & C))) == to_cnf(A >> (B & C))
+    assert CNF.CNF_to_cnf(CNF.to_CNF(A & (B | C) | ~A & (B | C))) == to_cnf(A & (B | C) | ~A & (B | C))
+    assert CNF.CNF_to_cnf(CNF.to_CNF(A & B)) == to_cnf(A & B)
+
+
+def test_to_dnf():
+    assert to_dnf(~(B | C)) == And(Not(B), Not(C))
+    assert to_dnf(A & (B | C)) == Or(And(A, B), And(A, C))
+    assert to_dnf(A >> B) == (~A) | B
+    assert to_dnf(A >> (B & C)) == (~A) | (B & C)
+    assert to_dnf(A | B) == A | B
+
+    assert to_dnf(Equivalent(A, B), True) == \
+           Or(And(A, B), And(Not(A), Not(B)))
+    assert to_dnf(Equivalent(A, B & C), True) == \
+           Or(And(A, B, C), And(Not(A), Not(B)), And(Not(A), Not(C)))
+    assert to_dnf(A + 1) == A + 1
+
+
+def test_to_int_repr():
+    x, y, z = map(Boolean, symbols('x,y,z'))
+
+    def sorted_recursive(arg):
+        try:
+            return sorted(sorted_recursive(x) for x in arg)
+        except TypeError:  # arg is not a sequence
+            return arg
+
+    assert sorted_recursive(to_int_repr([x | y, z | x], [x, y, z])) == \
+           sorted_recursive([[1, 2], [1, 3]])
+    assert sorted_recursive(to_int_repr([x | y, z | ~x], [x, y, z])) == \
+           sorted_recursive([[1, 2], [3, -1]])
+
+
+def test_is_anf():
+    x, y = symbols('x,y')
+    assert is_anf(true) is True
+    assert is_anf(false) is True
+    assert is_anf(x) is True
+    assert is_anf(And(x, y)) is True
+    assert is_anf(Xor(x, y, And(x, y))) is True
+    assert is_anf(Xor(x, y, Or(x, y))) is False
+    assert is_anf(Xor(Not(x), y)) is False
+
+
+def test_is_nnf():
+    assert is_nnf(true) is True
+    assert is_nnf(A) is True
+    assert is_nnf(~A) is True
+    assert is_nnf(A & B) is True
+    assert is_nnf((A & B) | (~A & A) | (~B & B) | (~A & ~B), False) is True
+    assert is_nnf((A | B) & (~A | ~B)) is True
+    assert is_nnf(Not(Or(A, B))) is False
+    assert is_nnf(A ^ B) is False
+    assert is_nnf((A & B) | (~A & A) | (~B & B) | (~A & ~B), True) is False
+
+
+def test_is_cnf():
+    assert is_cnf(x) is True
+    assert is_cnf(x | y | z) is True
+    assert is_cnf(x & y & z) is True
+    assert is_cnf((x | y) & z) is True
+    assert is_cnf((x & y) | z) is False
+    assert is_cnf(~(x & y) | z) is False
+
+
+def test_is_dnf():
+    assert is_dnf(x) is True
+    assert is_dnf(x | y | z) is True
+    assert is_dnf(x & y & z) is True
+    assert is_dnf((x & y) | z) is True
+    assert is_dnf((x | y) & z) is False
+    assert is_dnf(~(x | y) & z) is False
+
+
+def test_ITE():
+    A, B, C = symbols('A:C')
+    assert ITE(True, False, True) is false
+    assert ITE(True, True, False) is true
+    assert ITE(False, True, False) is false
+    assert ITE(False, False, True) is true
+    assert isinstance(ITE(A, B, C), ITE)
+
+    A = True
+    assert ITE(A, B, C) == B
+    A = False
+    assert ITE(A, B, C) == C
+    B = True
+    assert ITE(And(A, B), B, C) == C
+    assert ITE(Or(A, False), And(B, True), False) is false
+    assert ITE(x, A, B) == Not(x)
+    assert ITE(x, B, A) == x
+    assert ITE(1, x, y) == x
+    assert ITE(0, x, y) == y
+    raises(TypeError, lambda: ITE(2, x, y))
+    raises(TypeError, lambda: ITE(1, [], y))
+    raises(TypeError, lambda: ITE(1, (), y))
+    raises(TypeError, lambda: ITE(1, y, []))
+    assert ITE(1, 1, 1) is S.true
+    assert isinstance(ITE(1, 1, 1, evaluate=False), ITE)
+
+    assert ITE(Eq(x, True), y, x) == ITE(x, y, x)
+    assert ITE(Eq(x, False), y, x) == ITE(~x, y, x)
+    assert ITE(Ne(x, True), y, x) == ITE(~x, y, x)
+    assert ITE(Ne(x, False), y, x) == ITE(x, y, x)
+    assert ITE(Eq(S.true, x), y, x) == ITE(x, y, x)
+    assert ITE(Eq(S.false, x), y, x) == ITE(~x, y, x)
+    assert ITE(Ne(S.true, x), y, x) == ITE(~x, y, x)
+    assert ITE(Ne(S.false, x), y, x) == ITE(x, y, x)
+    # 0 and 1 in the context are not treated as True/False
+    # so the equality must always be False since dissimilar
+    # objects cannot be equal
+    assert ITE(Eq(x, 0), y, x) == x
+    assert ITE(Eq(x, 1), y, x) == x
+    assert ITE(Ne(x, 0), y, x) == y
+    assert ITE(Ne(x, 1), y, x) == y
+    assert ITE(Eq(x, 0), y, z).subs(x, 0) == y
+    assert ITE(Eq(x, 0), y, z).subs(x, 1) == z
+    raises(ValueError, lambda: ITE(x > 1, y, x, z))
+
+
+def test_is_literal():
+    assert is_literal(True) is True
+    assert is_literal(False) is True
+    assert is_literal(A) is True
+    assert is_literal(~A) is True
+    assert is_literal(Or(A, B)) is False
+    assert is_literal(Q.zero(A)) is True
+    assert is_literal(Not(Q.zero(A))) is True
+    assert is_literal(Or(A, B)) is False
+    assert is_literal(And(Q.zero(A), Q.zero(B))) is False
+    assert is_literal(x < 3)
+    assert not is_literal(x + y < 3)
+
+
+def test_operators():
+    # Mostly test __and__, __rand__, and so on
+    assert True & A == A & True == A
+    assert False & A == A & False == False
+    assert A & B == And(A, B)
+    assert True | A == A | True == True
+    assert False | A == A | False == A
+    assert A | B == Or(A, B)
+    assert ~A == Not(A)
+    assert True >> A == A << True == A
+    assert False >> A == A << False == True
+    assert A >> True == True << A == True
+    assert A >> False == False << A == ~A
+    assert A >> B == B << A == Implies(A, B)
+    assert True ^ A == A ^ True == ~A
+    assert False ^ A == A ^ False == A
+    assert A ^ B == Xor(A, B)
+
+
+def test_true_false():
+    assert true is S.true
+    assert false is S.false
+    assert true is not True
+    assert false is not False
+    assert true
+    assert not false
+    assert true == True
+    assert false == False
+    assert not (true == False)
+    assert not (false == True)
+    assert not (true == false)
+
+    assert hash(true) == hash(True)
+    assert hash(false) == hash(False)
+    assert len({true, True}) == len({false, False}) == 1
+
+    assert isinstance(true, BooleanAtom)
+    assert isinstance(false, BooleanAtom)
+    # We don't want to subclass from bool, because bool subclasses from
+    # int. But operators like &, |, ^, <<, >>, and ~ act differently on 0 and
+    # 1 then we want them to on true and false.  See the docstrings of the
+    # various And, Or, etc. functions for examples.
+    assert not isinstance(true, bool)
+    assert not isinstance(false, bool)
+
+    # Note: using 'is' comparison is important here. We want these to return
+    # true and false, not True and False
+
+    assert Not(true) is false
+    assert Not(True) is false
+    assert Not(false) is true
+    assert Not(False) is true
+    assert ~true is false
+    assert ~false is true
+
+    for T, F in product((True, true), (False, false)):
+        assert And(T, F) is false
+        assert And(F, T) is false
+        assert And(F, F) is false
+        assert And(T, T) is true
+        assert And(T, x) == x
+        assert And(F, x) is false
+        if not (T is True and F is False):
+            assert T & F is false
+            assert F & T is false
+        if F is not False:
+            assert F & F is false
+        if T is not True:
+            assert T & T is true
+
+        assert Or(T, F) is true
+        assert Or(F, T) is true
+        assert Or(F, F) is false
+        assert Or(T, T) is true
+        assert Or(T, x) is true
+        assert Or(F, x) == x
+        if not (T is True and F is False):
+            assert T | F is true
+            assert F | T is true
+        if F is not False:
+            assert F | F is false
+        if T is not True:
+            assert T | T is true
+
+        assert Xor(T, F) is true
+        assert Xor(F, T) is true
+        assert Xor(F, F) is false
+        assert Xor(T, T) is false
+        assert Xor(T, x) == ~x
+        assert Xor(F, x) == x
+        if not (T is True and F is False):
+            assert T ^ F is true
+            assert F ^ T is true
+        if F is not False:
+            assert F ^ F is false
+        if T is not True:
+            assert T ^ T is false
+
+        assert Nand(T, F) is true
+        assert Nand(F, T) is true
+        assert Nand(F, F) is true
+        assert Nand(T, T) is false
+        assert Nand(T, x) == ~x
+        assert Nand(F, x) is true
+
+        assert Nor(T, F) is false
+        assert Nor(F, T) is false
+        assert Nor(F, F) is true
+        assert Nor(T, T) is false
+        assert Nor(T, x) is false
+        assert Nor(F, x) == ~x
+
+        assert Implies(T, F) is false
+        assert Implies(F, T) is true
+        assert Implies(F, F) is true
+        assert Implies(T, T) is true
+        assert Implies(T, x) == x
+        assert Implies(F, x) is true
+        assert Implies(x, T) is true
+        assert Implies(x, F) == ~x
+        if not (T is True and F is False):
+            assert T >> F is false
+            assert F << T is false
+            assert F >> T is true
+            assert T << F is true
+        if F is not False:
+            assert F >> F is true
+            assert F << F is true
+        if T is not True:
+            assert T >> T is true
+            assert T << T is true
+
+        assert Equivalent(T, F) is false
+        assert Equivalent(F, T) is false
+        assert Equivalent(F, F) is true
+        assert Equivalent(T, T) is true
+        assert Equivalent(T, x) == x
+        assert Equivalent(F, x) == ~x
+        assert Equivalent(x, T) == x
+        assert Equivalent(x, F) == ~x
+
+        assert ITE(T, T, T) is true
+        assert ITE(T, T, F) is true
+        assert ITE(T, F, T) is false
+        assert ITE(T, F, F) is false
+        assert ITE(F, T, T) is true
+        assert ITE(F, T, F) is false
+        assert ITE(F, F, T) is true
+        assert ITE(F, F, F) is false
+
+    assert all(i.simplify(1, 2) is i for i in (S.true, S.false))
+
+
+def test_bool_as_set():
+    assert ITE(y <= 0, False, y >= 1).as_set() == Interval(1, oo)
+    assert And(x <= 2, x >= -2).as_set() == Interval(-2, 2)
+    assert Or(x >= 2, x <= -2).as_set() == Interval(-oo, -2) + Interval(2, oo)
+    assert Not(x > 2).as_set() == Interval(-oo, 2)
+    # issue 10240
+    assert Not(And(x > 2, x < 3)).as_set() == \
+           Union(Interval(-oo, 2), Interval(3, oo))
+    assert true.as_set() == S.UniversalSet
+    assert false.as_set() is S.EmptySet
+    assert x.as_set() == S.UniversalSet
+    assert And(Or(x < 1, x > 3), x < 2).as_set() == Interval.open(-oo, 1)
+    assert And(x < 1, sin(x) < 3).as_set() == (x < 1).as_set()
+    raises(NotImplementedError, lambda: (sin(x) < 1).as_set())
+    # watch for object morph in as_set
+    assert Eq(-1, cos(2 * x) ** 2 / sin(2 * x) ** 2).as_set() is S.EmptySet
+
+
+@XFAIL
+def test_multivariate_bool_as_set():
+    x, y = symbols('x,y')
+
+    assert And(x >= 0, y >= 0).as_set() == Interval(0, oo) * Interval(0, oo)
+    assert Or(x >= 0, y >= 0).as_set() == S.Reals * S.Reals - \
+           Interval(-oo, 0, True, True) * Interval(-oo, 0, True, True)
+
+
+def test_all_or_nothing():
+    x = symbols('x', extended_real=True)
+    args = x >= -oo, x <= oo
+    v = And(*args)
+    if v.func is And:
+        assert len(v.args) == len(args) - args.count(S.true)
+    else:
+        assert v == True
+    v = Or(*args)
+    if v.func is Or:
+        assert len(v.args) == 2
+    else:
+        assert v == True
+
+
+def test_canonical_atoms():
+    assert true.canonical == true
+    assert false.canonical == false
+
+
+def test_negated_atoms():
+    assert true.negated == false
+    assert false.negated == true
+
+
+def test_issue_8777():
+    assert And(x > 2, x < oo).as_set() == Interval(2, oo, left_open=True)
+    assert And(x >= 1, x < oo).as_set() == Interval(1, oo)
+    assert (x < oo).as_set() == Interval(-oo, oo)
+    assert (x > -oo).as_set() == Interval(-oo, oo)
+
+
+def test_issue_8975():
+    assert Or(And(-oo < x, x <= -2), And(2 <= x, x < oo)).as_set() == \
+           Interval(-oo, -2) + Interval(2, oo)
+
+
+def test_term_to_integer():
+    assert term_to_integer([1, 0, 1, 0, 0, 1, 0]) == 82
+    assert term_to_integer('0010101000111001') == 10809
+
+
+def test_issue_21971():
+    a, b, c, d = symbols('a b c d')
+    f = a & b & c | a & c
+    assert f.subs(a & c, d) == b & d | d
+    assert f.subs(a & b & c, d) == a & c | d
+
+    f = (a | b | c) & (a | c)
+    assert f.subs(a | c, d) == (b | d) & d
+    assert f.subs(a | b | c, d) == (a | c) & d
+
+    f = (a ^ b ^ c) & (a ^ c)
+    assert f.subs(a ^ c, d) == (b ^ d) & d
+    assert f.subs(a ^ b ^ c, d) == (a ^ c) & d
+
+
+def test_truth_table():
+    assert list(truth_table(And(x, y), [x, y], input=False)) == \
+           [False, False, False, True]
+    assert list(truth_table(x | y, [x, y], input=False)) == \
+           [False, True, True, True]
+    assert list(truth_table(x >> y, [x, y], input=False)) == \
+           [True, True, False, True]
+    assert list(truth_table(And(x, y), [x, y])) == \
+           [([0, 0], False), ([0, 1], False), ([1, 0], False), ([1, 1], True)]
+
+
+def test_issue_8571():
+    for t in (S.true, S.false):
+        raises(TypeError, lambda: +t)
+        raises(TypeError, lambda: -t)
+        raises(TypeError, lambda: abs(t))
+        # use int(bool(t)) to get 0 or 1
+        raises(TypeError, lambda: int(t))
+
+        for o in [S.Zero, S.One, x]:
+            for _ in range(2):
+                raises(TypeError, lambda: o + t)
+                raises(TypeError, lambda: o - t)
+                raises(TypeError, lambda: o % t)
+                raises(TypeError, lambda: o * t)
+                raises(TypeError, lambda: o / t)
+                raises(TypeError, lambda: o ** t)
+                o, t = t, o  # do again in reversed order
+
+
+def test_expand_relational():
+    n = symbols('n', negative=True)
+    p, q = symbols('p q', positive=True)
+    r = ((n + q * (-n / q + 1)) / (q * (-n / q + 1)) < 0)
+    assert r is not S.false
+    assert r.expand() is S.false
+    assert (q > 0).expand() is S.true
+
+
+def test_issue_12717():
+    assert S.true.is_Atom == True
+    assert S.false.is_Atom == True
+
+
+def test_as_Boolean():
+    nz = symbols('nz', nonzero=True)
+    assert all(as_Boolean(i) is S.true for i in (True, S.true, 1, nz))
+    z = symbols('z', zero=True)
+    assert all(as_Boolean(i) is S.false for i in (False, S.false, 0, z))
+    assert all(as_Boolean(i) == i for i in (x, x < 0))
+    for i in (2, S(2), x + 1, []):
+        raises(TypeError, lambda: as_Boolean(i))
+
+
+def test_binary_symbols():
+    assert ITE(x < 1, y, z).binary_symbols == {y, z}
+    for f in (Eq, Ne):
+        assert f(x, 1).binary_symbols == set()
+        assert f(x, True).binary_symbols == {x}
+        assert f(x, False).binary_symbols == {x}
+    assert S.true.binary_symbols == set()
+    assert S.false.binary_symbols == set()
+    assert x.binary_symbols == {x}
+    assert And(x, Eq(y, False), Eq(z, 1)).binary_symbols == {x, y}
+    assert Q.prime(x).binary_symbols == set()
+    assert Q.lt(x, 1).binary_symbols == set()
+    assert Q.is_true(x).binary_symbols == {x}
+    assert Q.eq(x, True).binary_symbols == {x}
+    assert Q.prime(x).binary_symbols == set()
+
+
+def test_BooleanFunction_diff():
+    assert And(x, y).diff(x) == Piecewise((0, Eq(y, False)), (1, True))
+
+
+def test_issue_14700():
+    A, B, C, D, E, F, G, H = symbols('A B C D E F G H')
+    q = ((B & D & H & ~F) | (B & H & ~C & ~D) | (B & H & ~C & ~F) |
+         (B & H & ~D & ~G) | (B & H & ~F & ~G) | (C & G & ~B & ~D) |
+         (C & G & ~D & ~H) | (C & G & ~F & ~H) | (D & F & H & ~B) |
+         (D & F & ~G & ~H) | (B & D & F & ~C & ~H) | (D & E & F & ~B & ~C) |
+         (D & F & ~A & ~B & ~C) | (D & F & ~A & ~C & ~H) |
+         (A & B & D & F & ~E & ~H))
+    soldnf = ((B & D & H & ~F) | (D & F & H & ~B) | (B & H & ~C & ~D) |
+              (B & H & ~D & ~G) | (C & G & ~B & ~D) | (C & G & ~D & ~H) |
+              (C & G & ~F & ~H) | (D & F & ~G & ~H) | (D & E & F & ~C & ~H) |
+              (D & F & ~A & ~C & ~H) | (A & B & D & F & ~E & ~H))
+    solcnf = ((B | C | D) & (B | D | G) & (C | D | H) & (C | F | H) &
+              (D | G | H) & (F | G | H) & (B | F | ~D | ~H) &
+              (~B | ~D | ~F | ~H) & (D | ~B | ~C | ~G | ~H) &
+              (A | H | ~C | ~D | ~F | ~G) & (H | ~C | ~D | ~E | ~F | ~G) &
+              (B | E | H | ~A | ~D | ~F | ~G))
+    assert simplify_logic(q, "dnf") == soldnf
+    assert simplify_logic(q, "cnf") == solcnf
+
+    minterms = [[0, 1, 0, 0], [0, 1, 0, 1], [0, 1, 1, 0], [0, 1, 1, 1],
+                [0, 0, 1, 1], [1, 0, 1, 1]]
+    dontcares = [[1, 0, 0, 0], [1, 0, 0, 1], [1, 1, 0, 0], [1, 1, 0, 1]]
+    assert SOPform([w, x, y, z], minterms) == (x & ~w) | (y & z & ~x)
+    # Should not be more complicated with don't cares
+    assert SOPform([w, x, y, z], minterms, dontcares) == \
+           (x & ~w) | (y & z & ~x)
+
+
+def test_issue_25115():
+    cond = Contains(x, S.Integers)
+    # Previously this raised an exception:
+    assert simplify_logic(cond) == cond
+
+
+def test_relational_simplification():
+    w, x, y, z = symbols('w x y z', real=True)
+    d, e = symbols('d e', real=False)
+    # Test all combinations or sign and order
+    assert Or(x >= y, x < y).simplify() == S.true
+    assert Or(x >= y, y > x).simplify() == S.true
+    assert Or(x >= y, -x > -y).simplify() == S.true
+    assert Or(x >= y, -y < -x).simplify() == S.true
+    assert Or(-x <= -y, x < y).simplify() == S.true
+    assert Or(-x <= -y, -x > -y).simplify() == S.true
+    assert Or(-x <= -y, y > x).simplify() == S.true
+    assert Or(-x <= -y, -y < -x).simplify() == S.true
+    assert Or(y <= x, x < y).simplify() == S.true
+    assert Or(y <= x, y > x).simplify() == S.true
+    assert Or(y <= x, -x > -y).simplify() == S.true
+    assert Or(y <= x, -y < -x).simplify() == S.true
+    assert Or(-y >= -x, x < y).simplify() == S.true
+    assert Or(-y >= -x, y > x).simplify() == S.true
+    assert Or(-y >= -x, -x > -y).simplify() == S.true
+    assert Or(-y >= -x, -y < -x).simplify() == S.true
+
+    assert Or(x < y, x >= y).simplify() == S.true
+    assert Or(y > x, x >= y).simplify() == S.true
+    assert Or(-x > -y, x >= y).simplify() == S.true
+    assert Or(-y < -x, x >= y).simplify() == S.true
+    assert Or(x < y, -x <= -y).simplify() == S.true
+    assert Or(-x > -y, -x <= -y).simplify() == S.true
+    assert Or(y > x, -x <= -y).simplify() == S.true
+    assert Or(-y < -x, -x <= -y).simplify() == S.true
+    assert Or(x < y, y <= x).simplify() == S.true
+    assert Or(y > x, y <= x).simplify() == S.true
+    assert Or(-x > -y, y <= x).simplify() == S.true
+    assert Or(-y < -x, y <= x).simplify() == S.true
+    assert Or(x < y, -y >= -x).simplify() == S.true
+    assert Or(y > x, -y >= -x).simplify() == S.true
+    assert Or(-x > -y, -y >= -x).simplify() == S.true
+    assert Or(-y < -x, -y >= -x).simplify() == S.true
+
+    # Some other tests
+    assert Or(x >= y, w < z, x <= y).simplify() == S.true
+    assert And(x >= y, x < y).simplify() == S.false
+    assert Or(x >= y, Eq(y, x)).simplify() == (x >= y)
+    assert And(x >= y, Eq(y, x)).simplify() == Eq(x, y)
+    assert And(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y).simplify() == \
+           (Eq(x, y) & (x >= 1) & (y >= 5) & (y > z))
+    assert Or(Eq(x, y), x >= y, w < y, z < y).simplify() == \
+           (x >= y) | (y > z) | (w < y)
+    assert And(Eq(x, y), x >= y, w < y, y >= z, z < y).simplify() == \
+           Eq(x, y) & (y > z) & (w < y)
+    # assert And(Eq(x, y), x >= y, w < y, y >= z, z < y).simplify(relational_minmax=True) == \
+    #    And(Eq(x, y), y > Max(w, z))
+    # assert Or(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y).simplify(relational_minmax=True) == \
+    #    (Eq(x, y) | (x >= 1) | (y > Min(2, z)))
+    assert And(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y).simplify() == \
+           (Eq(x, y) & (x >= 1) & (y >= 5) & (y > z))
+    assert (Eq(x, y) & Eq(d, e) & (x >= y) & (d >= e)).simplify() == \
+           (Eq(x, y) & Eq(d, e) & (d >= e))
+    assert And(Eq(x, y), Eq(x, -y)).simplify() == And(Eq(x, 0), Eq(y, 0))
+    assert Xor(x >= y, x <= y).simplify() == Ne(x, y)
+    assert And(x > 1, x < -1, Eq(x, y)).simplify() == S.false
+    # From #16690
+    assert And(x >= y, Eq(y, 0)).simplify() == And(x >= 0, Eq(y, 0))
+    assert Or(Ne(x, 1), Ne(x, 2)).simplify() == S.true
+    assert And(Eq(x, 1), Ne(2, x)).simplify() == Eq(x, 1)
+    assert Or(Eq(x, 1), Ne(2, x)).simplify() == Ne(x, 2)
+
+
+def test_issue_8373():
+    x = symbols('x', real=True)
+    assert Or(x < 1, x > -1).simplify() == S.true
+    assert Or(x < 1, x >= 1).simplify() == S.true
+    assert And(x < 1, x >= 1).simplify() == S.false
+    assert Or(x <= 1, x >= 1).simplify() == S.true
+
+
+def test_issue_7950():
+    x = symbols('x', real=True)
+    assert And(Eq(x, 1), Eq(x, 2)).simplify() == S.false
+
+
+@slow
+def test_relational_simplification_numerically():
+    def test_simplification_numerically_function(original, simplified):
+        symb = original.free_symbols
+        n = len(symb)
+        valuelist = list(set(combinations(list(range(-(n - 1), n)) * n, n)))
+        for values in valuelist:
+            sublist = dict(zip(symb, values))
+            originalvalue = original.subs(sublist)
+            simplifiedvalue = simplified.subs(sublist)
+            assert originalvalue == simplifiedvalue, "Original: {}\nand" \
+                                                     " simplified: {}\ndo not evaluate to the same value for {}" \
+                                                     "".format(original, simplified, sublist)
+
+    w, x, y, z = symbols('w x y z', real=True)
+    d, e = symbols('d e', real=False)
+
+    expressions = (And(Eq(x, y), x >= y, w < y, y >= z, z < y),
+                   And(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y),
+                   Or(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y),
+                   And(x >= y, Eq(y, x)),
+                   Or(And(Eq(x, y), x >= y, w < y, Or(y >= z, z < y)),
+                      And(Eq(x, y), x >= 1, 2 < y, y >= -1, z < y)),
+                   (Eq(x, y) & Eq(d, e) & (x >= y) & (d >= e)),
+                   )
+
+    for expression in expressions:
+        test_simplification_numerically_function(expression,
+                                                 expression.simplify())
+
+
+def test_relational_simplification_patterns_numerically():
+    from sympy.core import Wild
+    from sympy.logic.boolalg import _simplify_patterns_and, \
+        _simplify_patterns_or, _simplify_patterns_xor
+    a = Wild('a')
+    b = Wild('b')
+    c = Wild('c')
+    symb = [a, b, c]
+    patternlists = [[And, _simplify_patterns_and()],
+                    [Or, _simplify_patterns_or()],
+                    [Xor, _simplify_patterns_xor()]]
+    valuelist = list(set(combinations(list(range(-2, 3)) * 3, 3)))
+    # Skip combinations of +/-2 and 0, except for all 0
+    valuelist = [v for v in valuelist if any(w % 2 for w in v) or not any(v)]
+    for func, patternlist in patternlists:
+        for pattern in patternlist:
+            original = func(*pattern[0].args)
+            simplified = pattern[1]
+            for values in valuelist:
+                sublist = dict(zip(symb, values))
+                originalvalue = original.xreplace(sublist)
+                simplifiedvalue = simplified.xreplace(sublist)
+                assert originalvalue == simplifiedvalue, "Original: {}\nand" \
+                                                         " simplified: {}\ndo not evaluate to the same value for" \
+                                                         "{}".format(pattern[0], simplified, sublist)
+
+
+def test_issue_16803():
+    n = symbols('n')
+    # No simplification done, but should not raise an exception
+    assert ((n > 3) | (n < 0) | ((n > 0) & (n < 3))).simplify() == \
+           (n > 3) | (n < 0) | ((n > 0) & (n < 3))
+
+
+def test_issue_17530():
+    r = {x: oo, y: oo}
+    assert Or(x + y > 0, x - y < 0).subs(r)
+    assert not And(x + y < 0, x - y < 0).subs(r)
+    raises(TypeError, lambda: Or(x + y < 0, x - y < 0).subs(r))
+    raises(TypeError, lambda: And(x + y > 0, x - y < 0).subs(r))
+    raises(TypeError, lambda: And(x + y > 0, x - y < 0).subs(r))
+
+
+def test_anf_coeffs():
+    assert anf_coeffs([1, 0]) == [1, 1]
+    assert anf_coeffs([0, 0, 0, 1]) == [0, 0, 0, 1]
+    assert anf_coeffs([0, 1, 1, 1]) == [0, 1, 1, 1]
+    assert anf_coeffs([1, 1, 1, 0]) == [1, 0, 0, 1]
+    assert anf_coeffs([1, 0, 0, 0]) == [1, 1, 1, 1]
+    assert anf_coeffs([1, 0, 0, 1]) == [1, 1, 1, 0]
+    assert anf_coeffs([1, 1, 0, 1]) == [1, 0, 1, 1]
+
+
+def test_ANFform():
+    x, y = symbols('x,y')
+    assert ANFform([x], [1, 1]) == True
+    assert ANFform([x], [0, 0]) == False
+    assert ANFform([x], [1, 0]) == Xor(x, True, remove_true=False)
+    assert ANFform([x, y], [1, 1, 1, 0]) == \
+           Xor(True, And(x, y), remove_true=False)
+
+
+def test_bool_minterm():
+    x, y = symbols('x,y')
+    assert bool_minterm(3, [x, y]) == And(x, y)
+    assert bool_minterm([1, 0], [x, y]) == And(Not(y), x)
+
+
+def test_bool_maxterm():
+    x, y = symbols('x,y')
+    assert bool_maxterm(2, [x, y]) == Or(Not(x), y)
+    assert bool_maxterm([0, 1], [x, y]) == Or(Not(y), x)
+
+
+def test_bool_monomial():
+    x, y = symbols('x,y')
+    assert bool_monomial(1, [x, y]) == y
+    assert bool_monomial([1, 1], [x, y]) == And(x, y)
+
+
+def test_check_pair():
+    assert _check_pair([0, 1, 0], [0, 1, 1]) == 2
+    assert _check_pair([0, 1, 0], [1, 1, 1]) == -1
+
+
+def test_issue_19114():
+    expr = (B & C) | (A & ~C) | (~A & ~B)
+    # Expression is minimal, but there are multiple minimal forms possible
+    res1 = (A & B) | (C & ~A) | (~B & ~C)
+    result = to_dnf(expr, simplify=True)
+    assert result in (expr, res1)
+
+
+def test_issue_20870():
+    result = SOPform([a, b, c, d], [1, 2, 3, 4, 5, 6, 8, 9, 11, 12, 14, 15])
+    expected = ((d & ~b) | (a & b & c) | (a & ~c & ~d) |
+                (b & ~a & ~c) | (c & ~a & ~d))
+    assert result == expected
+
+
+def test_convert_to_varsSOP():
+    assert _convert_to_varsSOP([0, 1, 0], [x, y, z]) == And(Not(x), y, Not(z))
+    assert _convert_to_varsSOP([3, 1, 0], [x, y, z]) == And(y, Not(z))
+
+
+def test_convert_to_varsPOS():
+    assert _convert_to_varsPOS([0, 1, 0], [x, y, z]) == Or(x, Not(y), z)
+    assert _convert_to_varsPOS([3, 1, 0], [x, y, z]) == Or(Not(y), z)
+
+
+def test_gateinputcount():
+    a, b, c, d, e = symbols('a:e')
+    assert gateinputcount(And(a, b)) == 2
+    assert gateinputcount(a | b & c & d ^ (e | a)) == 9
+    assert gateinputcount(And(a, True)) == 0
+    raises(TypeError, lambda: gateinputcount(a * b))
+
+
+def test_refine():
+    # relational
+    assert not refine(x < 0, ~(x < 0))
+    assert refine(x < 0, (x < 0))
+    assert refine(x < 0, (0 > x)) is S.true
+    assert refine(x < 0, (y < 0)) == (x < 0)
+    assert not refine(x <= 0, ~(x <= 0))
+    assert refine(x <= 0, (x <= 0))
+    assert refine(x <= 0, (0 >= x)) is S.true
+    assert refine(x <= 0, (y <= 0)) == (x <= 0)
+    assert not refine(x > 0, ~(x > 0))
+    assert refine(x > 0, (x > 0))
+    assert refine(x > 0, (0 < x)) is S.true
+    assert refine(x > 0, (y > 0)) == (x > 0)
+    assert not refine(x >= 0, ~(x >= 0))
+    assert refine(x >= 0, (x >= 0))
+    assert refine(x >= 0, (0 <= x)) is S.true
+    assert refine(x >= 0, (y >= 0)) == (x >= 0)
+    assert not refine(Eq(x, 0), ~(Eq(x, 0)))
+    assert refine(Eq(x, 0), (Eq(x, 0)))
+    assert refine(Eq(x, 0), (Eq(0, x))) is S.true
+    assert refine(Eq(x, 0), (Eq(y, 0))) == Eq(x, 0)
+    assert not refine(Ne(x, 0), ~(Ne(x, 0)))
+    assert refine(Ne(x, 0), (Ne(0, x))) is S.true
+    assert refine(Ne(x, 0), (Ne(x, 0)))
+    assert refine(Ne(x, 0), (Ne(y, 0))) == (Ne(x, 0))
+
+    # boolean functions
+    assert refine(And(x > 0, y > 0), (x > 0)) == (y > 0)
+    assert refine(And(x > 0, y > 0), (x > 0) & (y > 0)) is S.true
+
+    # predicates
+    assert refine(Q.positive(x), Q.positive(x)) is S.true
+    assert refine(Q.positive(x), Q.negative(x)) is S.false
+    assert refine(Q.positive(x), Q.real(x)) == Q.positive(x)
+
+
+def test_relational_threeterm_simplification_patterns_numerically():
+    from sympy.core import Wild
+    from sympy.logic.boolalg import _simplify_patterns_and3
+    a = Wild('a')
+    b = Wild('b')
+    c = Wild('c')
+    symb = [a, b, c]
+    patternlists = [[And, _simplify_patterns_and3()]]
+    valuelist = list(set(combinations(list(range(-2, 3)) * 3, 3)))
+    # Skip combinations of +/-2 and 0, except for all 0
+    valuelist = [v for v in valuelist if any(w % 2 for w in v) or not any(v)]
+    for func, patternlist in patternlists:
+        for pattern in patternlist:
+            original = func(*pattern[0].args)
+            simplified = pattern[1]
+            for values in valuelist:
+                sublist = dict(zip(symb, values))
+                originalvalue = original.xreplace(sublist)
+                simplifiedvalue = simplified.xreplace(sublist)
+                assert originalvalue == simplifiedvalue, "Original: {}\nand" \
+                                                         " simplified: {}\ndo not evaluate to the same value for" \
+                                                         "{}".format(pattern[0], simplified, sublist)
+
+
+def test_issue_25451():
+    x = Or(And(a, c), Eq(a, b))
+    assert isinstance(x, Or)
+    assert set(x.args) == {And(a, c), Eq(a, b)}
+
+
+def test_issue_26985():
+    a, b, c, d = symbols('a b c d')
+
+    # Expression before applying to_anf
+    x = Xor(c, And(a, b), And(a, c))
+    y = Xor(a, b, And(a, c))
+
+    # Applying to_anf
+    result = Xor(Xor(d, And(x, y)), And(x, y))
+    result_anf = to_anf(Xor(to_anf(Xor(d, And(x, y))), And(x, y)))
+
+    assert result_anf == d
+    assert result == d
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/tests/test_dimacs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/tests/test_dimacs.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a9a51a39d33fb807688614cb5809b621ce21a2c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/tests/test_dimacs.py
@@ -0,0 +1,234 @@
+"""Various tests on satisfiability using dimacs cnf file syntax
+You can find lots of cnf files in
+ftp://dimacs.rutgers.edu/pub/challenge/satisfiability/benchmarks/cnf/
+"""
+
+from sympy.logic.utilities.dimacs import load
+from sympy.logic.algorithms.dpll import dpll_satisfiable
+
+
+def test_f1():
+    assert bool(dpll_satisfiable(load(f1)))
+
+
+def test_f2():
+    assert bool(dpll_satisfiable(load(f2)))
+
+
+def test_f3():
+    assert bool(dpll_satisfiable(load(f3)))
+
+
+def test_f4():
+    assert not bool(dpll_satisfiable(load(f4)))
+
+
+def test_f5():
+    assert bool(dpll_satisfiable(load(f5)))
+
+f1 = """c  simple example
+c Resolution: SATISFIABLE
+c
+p cnf 3 2
+1 -3 0
+2 3 -1 0
+"""
+
+
+f2 = """c  an example from Quinn's text, 16 variables and 18 clauses.
+c Resolution: SATISFIABLE
+c
+p cnf 16 18
+  1    2  0
+ -2   -4  0
+  3    4  0
+ -4   -5  0
+  5   -6  0
+  6   -7  0
+  6    7  0
+  7  -16  0
+  8   -9  0
+ -8  -14  0
+  9   10  0
+  9  -10  0
+-10  -11  0
+ 10   12  0
+ 11   12  0
+ 13   14  0
+ 14  -15  0
+ 15   16  0
+"""
+
+f3 = """c
+p cnf 6 9
+-1 0
+-3 0
+2 -1 0
+2 -4 0
+5 -4 0
+-1 -3 0
+-4 -6 0
+1 3 -2 0
+4 6 -2 -5 0
+"""
+
+f4 = """c
+c file:   hole6.cnf [http://people.sc.fsu.edu/~jburkardt/data/cnf/hole6.cnf]
+c
+c SOURCE: John Hooker (jh38+@andrew.cmu.edu)
+c
+c DESCRIPTION: Pigeon hole problem of placing n (for file 'holen.cnf') pigeons
+c              in n+1 holes without placing 2 pigeons in the same hole
+c
+c NOTE: Part of the collection at the Forschungsinstitut fuer
+c       anwendungsorientierte Wissensverarbeitung in Ulm Germany.
+c
+c NOTE: Not satisfiable
+c
+p cnf 42 133
+-1     -7    0
+-1     -13   0
+-1     -19   0
+-1     -25   0
+-1     -31   0
+-1     -37   0
+-7     -13   0
+-7     -19   0
+-7     -25   0
+-7     -31   0
+-7     -37   0
+-13    -19   0
+-13    -25   0
+-13    -31   0
+-13    -37   0
+-19    -25   0
+-19    -31   0
+-19    -37   0
+-25    -31   0
+-25    -37   0
+-31    -37   0
+-2     -8    0
+-2     -14   0
+-2     -20   0
+-2     -26   0
+-2     -32   0
+-2     -38   0
+-8     -14   0
+-8     -20   0
+-8     -26   0
+-8     -32   0
+-8     -38   0
+-14    -20   0
+-14    -26   0
+-14    -32   0
+-14    -38   0
+-20    -26   0
+-20    -32   0
+-20    -38   0
+-26    -32   0
+-26    -38   0
+-32    -38   0
+-3     -9    0
+-3     -15   0
+-3     -21   0
+-3     -27   0
+-3     -33   0
+-3     -39   0
+-9     -15   0
+-9     -21   0
+-9     -27   0
+-9     -33   0
+-9     -39   0
+-15    -21   0
+-15    -27   0
+-15    -33   0
+-15    -39   0
+-21    -27   0
+-21    -33   0
+-21    -39   0
+-27    -33   0
+-27    -39   0
+-33    -39   0
+-4     -10   0
+-4     -16   0
+-4     -22   0
+-4     -28   0
+-4     -34   0
+-4     -40   0
+-10    -16   0
+-10    -22   0
+-10    -28   0
+-10    -34   0
+-10    -40   0
+-16    -22   0
+-16    -28   0
+-16    -34   0
+-16    -40   0
+-22    -28   0
+-22    -34   0
+-22    -40   0
+-28    -34   0
+-28    -40   0
+-34    -40   0
+-5     -11   0
+-5     -17   0
+-5     -23   0
+-5     -29   0
+-5     -35   0
+-5     -41   0
+-11    -17   0
+-11    -23   0
+-11    -29   0
+-11    -35   0
+-11    -41   0
+-17    -23   0
+-17    -29   0
+-17    -35   0
+-17    -41   0
+-23    -29   0
+-23    -35   0
+-23    -41   0
+-29    -35   0
+-29    -41   0
+-35    -41   0
+-6     -12   0
+-6     -18   0
+-6     -24   0
+-6     -30   0
+-6     -36   0
+-6     -42   0
+-12    -18   0
+-12    -24   0
+-12    -30   0
+-12    -36   0
+-12    -42   0
+-18    -24   0
+-18    -30   0
+-18    -36   0
+-18    -42   0
+-24    -30   0
+-24    -36   0
+-24    -42   0
+-30    -36   0
+-30    -42   0
+-36    -42   0
+ 6      5      4      3      2      1    0
+ 12     11     10     9      8      7    0
+ 18     17     16     15     14     13   0
+ 24     23     22     21     20     19   0
+ 30     29     28     27     26     25   0
+ 36     35     34     33     32     31   0
+ 42     41     40     39     38     37   0
+"""
+
+f5 = """c  simple example requiring variable selection
+c
+c NOTE: Satisfiable
+c
+p cnf 5 5
+1 2 3 0
+1 -2 3 0
+4 5 -3 0
+1 -4 -3 0
+-1 -5 0
+"""
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/tests/test_inference.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/tests/test_inference.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff37b1b104f6f106ec5df7809fd34959bce35917
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/tests/test_inference.py
@@ -0,0 +1,396 @@
+"""For more tests on satisfiability, see test_dimacs"""
+
+from sympy.assumptions.ask import Q
+from sympy.core.symbol import symbols
+from sympy.core.relational import Unequality
+from sympy.logic.boolalg import And, Or, Implies, Equivalent, true, false
+from sympy.logic.inference import literal_symbol, \
+     pl_true, satisfiable, valid, entails, PropKB
+from sympy.logic.algorithms.dpll import dpll, dpll_satisfiable, \
+    find_pure_symbol, find_unit_clause, unit_propagate, \
+    find_pure_symbol_int_repr, find_unit_clause_int_repr, \
+    unit_propagate_int_repr
+from sympy.logic.algorithms.dpll2 import dpll_satisfiable as dpll2_satisfiable
+
+from sympy.logic.algorithms.z3_wrapper import z3_satisfiable
+from sympy.assumptions.cnf import CNF, EncodedCNF
+from sympy.logic.tests.test_lra_theory import make_random_problem
+from sympy.core.random import randint
+
+from sympy.testing.pytest import raises, skip
+from sympy.external import import_module
+
+
+def test_literal():
+    A, B = symbols('A,B')
+    assert literal_symbol(True) is True
+    assert literal_symbol(False) is False
+    assert literal_symbol(A) is A
+    assert literal_symbol(~A) is A
+
+
+def test_find_pure_symbol():
+    A, B, C = symbols('A,B,C')
+    assert find_pure_symbol([A], [A]) == (A, True)
+    assert find_pure_symbol([A, B], [~A | B, ~B | A]) == (None, None)
+    assert find_pure_symbol([A, B, C], [ A | ~B, ~B | ~C, C | A]) == (A, True)
+    assert find_pure_symbol([A, B, C], [~A | B, B | ~C, C | A]) == (B, True)
+    assert find_pure_symbol([A, B, C], [~A | ~B, ~B | ~C, C | A]) == (B, False)
+    assert find_pure_symbol(
+        [A, B, C], [~A | B, ~B | ~C, C | A]) == (None, None)
+
+
+def test_find_pure_symbol_int_repr():
+    assert find_pure_symbol_int_repr([1], [{1}]) == (1, True)
+    assert find_pure_symbol_int_repr([1, 2],
+                [{-1, 2}, {-2, 1}]) == (None, None)
+    assert find_pure_symbol_int_repr([1, 2, 3],
+                [{1, -2}, {-2, -3}, {3, 1}]) == (1, True)
+    assert find_pure_symbol_int_repr([1, 2, 3],
+                [{-1, 2}, {2, -3}, {3, 1}]) == (2, True)
+    assert find_pure_symbol_int_repr([1, 2, 3],
+                [{-1, -2}, {-2, -3}, {3, 1}]) == (2, False)
+    assert find_pure_symbol_int_repr([1, 2, 3],
+                [{-1, 2}, {-2, -3}, {3, 1}]) == (None, None)
+
+
+def test_unit_clause():
+    A, B, C = symbols('A,B,C')
+    assert find_unit_clause([A], {}) == (A, True)
+    assert find_unit_clause([A, ~A], {}) == (A, True)  # Wrong ??
+    assert find_unit_clause([A | B], {A: True}) == (B, True)
+    assert find_unit_clause([A | B], {B: True}) == (A, True)
+    assert find_unit_clause(
+        [A | B | C, B | ~C, A | ~B], {A: True}) == (B, False)
+    assert find_unit_clause([A | B | C, B | ~C, A | B], {A: True}) == (B, True)
+    assert find_unit_clause([A | B | C, B | ~C, A ], {}) == (A, True)
+
+
+def test_unit_clause_int_repr():
+    assert find_unit_clause_int_repr(map(set, [[1]]), {}) == (1, True)
+    assert find_unit_clause_int_repr(map(set, [[1], [-1]]), {}) == (1, True)
+    assert find_unit_clause_int_repr([{1, 2}], {1: True}) == (2, True)
+    assert find_unit_clause_int_repr([{1, 2}], {2: True}) == (1, True)
+    assert find_unit_clause_int_repr(map(set,
+        [[1, 2, 3], [2, -3], [1, -2]]), {1: True}) == (2, False)
+    assert find_unit_clause_int_repr(map(set,
+        [[1, 2, 3], [3, -3], [1, 2]]), {1: True}) == (2, True)
+
+    A, B, C = symbols('A,B,C')
+    assert find_unit_clause([A | B | C, B | ~C, A ], {}) == (A, True)
+
+
+def test_unit_propagate():
+    A, B, C = symbols('A,B,C')
+    assert unit_propagate([A | B], A) == []
+    assert unit_propagate([A | B, ~A | C, ~C | B, A], A) == [C, ~C | B, A]
+
+
+def test_unit_propagate_int_repr():
+    assert unit_propagate_int_repr([{1, 2}], 1) == []
+    assert unit_propagate_int_repr(map(set,
+        [[1, 2], [-1, 3], [-3, 2], [1]]), 1) == [{3}, {-3, 2}]
+
+
+def test_dpll():
+    """This is also tested in test_dimacs"""
+    A, B, C = symbols('A,B,C')
+    assert dpll([A | B], [A, B], {A: True, B: True}) == {A: True, B: True}
+
+
+def test_dpll_satisfiable():
+    A, B, C = symbols('A,B,C')
+    assert dpll_satisfiable( A & ~A ) is False
+    assert dpll_satisfiable( A & ~B ) == {A: True, B: False}
+    assert dpll_satisfiable(
+        A | B ) in ({A: True}, {B: True}, {A: True, B: True})
+    assert dpll_satisfiable(
+        (~A | B) & (~B | A) ) in ({A: True, B: True}, {A: False, B: False})
+    assert dpll_satisfiable( (A | B) & (~B | C) ) in ({A: True, B: False},
+            {A: True, C: True}, {B: True, C: True})
+    assert dpll_satisfiable( A & B & C  ) == {A: True, B: True, C: True}
+    assert dpll_satisfiable( (A | B) & (A >> B) ) == {B: True}
+    assert dpll_satisfiable( Equivalent(A, B) & A ) == {A: True, B: True}
+    assert dpll_satisfiable( Equivalent(A, B) & ~A ) == {A: False, B: False}
+
+
+def test_dpll2_satisfiable():
+    A, B, C = symbols('A,B,C')
+    assert dpll2_satisfiable( A & ~A ) is False
+    assert dpll2_satisfiable( A & ~B ) == {A: True, B: False}
+    assert dpll2_satisfiable(
+        A | B ) in ({A: True}, {B: True}, {A: True, B: True})
+    assert dpll2_satisfiable(
+        (~A | B) & (~B | A) ) in ({A: True, B: True}, {A: False, B: False})
+    assert dpll2_satisfiable( (A | B) & (~B | C) ) in ({A: True, B: False, C: True},
+        {A: True, B: True, C: True})
+    assert dpll2_satisfiable( A & B & C  ) == {A: True, B: True, C: True}
+    assert dpll2_satisfiable( (A | B) & (A >> B) ) in ({B: True, A: False},
+        {B: True, A: True})
+    assert dpll2_satisfiable( Equivalent(A, B) & A ) == {A: True, B: True}
+    assert dpll2_satisfiable( Equivalent(A, B) & ~A ) == {A: False, B: False}
+
+
+def test_minisat22_satisfiable():
+    A, B, C = symbols('A,B,C')
+    minisat22_satisfiable = lambda expr: satisfiable(expr, algorithm="minisat22")
+    assert minisat22_satisfiable( A & ~A ) is False
+    assert minisat22_satisfiable( A & ~B ) == {A: True, B: False}
+    assert minisat22_satisfiable(
+        A | B ) in ({A: True}, {B: False}, {A: False, B: True}, {A: True, B: True}, {A: True, B: False})
+    assert minisat22_satisfiable(
+        (~A | B) & (~B | A) ) in ({A: True, B: True}, {A: False, B: False})
+    assert minisat22_satisfiable( (A | B) & (~B | C) ) in ({A: True, B: False, C: True},
+        {A: True, B: True, C: True}, {A: False, B: True, C: True}, {A: True, B: False, C: False})
+    assert minisat22_satisfiable( A & B & C  ) == {A: True, B: True, C: True}
+    assert minisat22_satisfiable( (A | B) & (A >> B) ) in ({B: True, A: False},
+        {B: True, A: True})
+    assert minisat22_satisfiable( Equivalent(A, B) & A ) == {A: True, B: True}
+    assert minisat22_satisfiable( Equivalent(A, B) & ~A ) == {A: False, B: False}
+
+def test_minisat22_minimal_satisfiable():
+    A, B, C = symbols('A,B,C')
+    minisat22_satisfiable = lambda expr, minimal=True: satisfiable(expr, algorithm="minisat22", minimal=True)
+    assert minisat22_satisfiable( A & ~A ) is False
+    assert minisat22_satisfiable( A & ~B ) == {A: True, B: False}
+    assert minisat22_satisfiable(
+        A | B ) in ({A: True}, {B: False}, {A: False, B: True}, {A: True, B: True}, {A: True, B: False})
+    assert minisat22_satisfiable(
+        (~A | B) & (~B | A) ) in ({A: True, B: True}, {A: False, B: False})
+    assert minisat22_satisfiable( (A | B) & (~B | C) ) in ({A: True, B: False, C: True},
+        {A: True, B: True, C: True}, {A: False, B: True, C: True}, {A: True, B: False, C: False})
+    assert minisat22_satisfiable( A & B & C  ) == {A: True, B: True, C: True}
+    assert minisat22_satisfiable( (A | B) & (A >> B) ) in ({B: True, A: False},
+        {B: True, A: True})
+    assert minisat22_satisfiable( Equivalent(A, B) & A ) == {A: True, B: True}
+    assert minisat22_satisfiable( Equivalent(A, B) & ~A ) == {A: False, B: False}
+    g = satisfiable((A | B | C),algorithm="minisat22",minimal=True,all_models=True)
+    sol = next(g)
+    first_solution = {key for key, value in sol.items() if value}
+    sol=next(g)
+    second_solution = {key for key, value in sol.items() if value}
+    sol=next(g)
+    third_solution = {key for key, value in sol.items() if value}
+    assert not first_solution <= second_solution
+    assert not second_solution <= third_solution
+    assert not first_solution <= third_solution
+
+def test_satisfiable():
+    A, B, C = symbols('A,B,C')
+    assert satisfiable(A & (A >> B) & ~B) is False
+
+
+def test_valid():
+    A, B, C = symbols('A,B,C')
+    assert valid(A >> (B >> A)) is True
+    assert valid((A >> (B >> C)) >> ((A >> B) >> (A >> C))) is True
+    assert valid((~B >> ~A) >> (A >> B)) is True
+    assert valid(A | B | C) is False
+    assert valid(A >> B) is False
+
+
+def test_pl_true():
+    A, B, C = symbols('A,B,C')
+    assert pl_true(True) is True
+    assert pl_true( A & B, {A: True, B: True}) is True
+    assert pl_true( A | B, {A: True}) is True
+    assert pl_true( A | B, {B: True}) is True
+    assert pl_true( A | B, {A: None, B: True}) is True
+    assert pl_true( A >> B, {A: False}) is True
+    assert pl_true( A | B | ~C, {A: False, B: True, C: True}) is True
+    assert pl_true(Equivalent(A, B), {A: False, B: False}) is True
+
+    # test for false
+    assert pl_true(False) is False
+    assert pl_true( A & B, {A: False, B: False}) is False
+    assert pl_true( A & B, {A: False}) is False
+    assert pl_true( A & B, {B: False}) is False
+    assert pl_true( A | B, {A: False, B: False}) is False
+
+    #test for None
+    assert pl_true(B, {B: None}) is None
+    assert pl_true( A & B, {A: True, B: None}) is None
+    assert pl_true( A >> B, {A: True, B: None}) is None
+    assert pl_true(Equivalent(A, B), {A: None}) is None
+    assert pl_true(Equivalent(A, B), {A: True, B: None}) is None
+
+    # Test for deep
+    assert pl_true(A | B, {A: False}, deep=True) is None
+    assert pl_true(~A & ~B, {A: False}, deep=True) is None
+    assert pl_true(A | B, {A: False, B: False}, deep=True) is False
+    assert pl_true(A & B & (~A | ~B), {A: True}, deep=True) is False
+    assert pl_true((C >> A) >> (B >> A), {C: True}, deep=True) is True
+
+
+def test_pl_true_wrong_input():
+    from sympy.core.numbers import pi
+    raises(ValueError, lambda: pl_true('John Cleese'))
+    raises(ValueError, lambda: pl_true(42 + pi + pi ** 2))
+    raises(ValueError, lambda: pl_true(42))
+
+
+def test_entails():
+    A, B, C = symbols('A, B, C')
+    assert entails(A, [A >> B, ~B]) is False
+    assert entails(B, [Equivalent(A, B), A]) is True
+    assert entails((A >> B) >> (~A >> ~B)) is False
+    assert entails((A >> B) >> (~B >> ~A)) is True
+
+
+def test_PropKB():
+    A, B, C = symbols('A,B,C')
+    kb = PropKB()
+    assert kb.ask(A >> B) is False
+    assert kb.ask(A >> (B >> A)) is True
+    kb.tell(A >> B)
+    kb.tell(B >> C)
+    assert kb.ask(A) is False
+    assert kb.ask(B) is False
+    assert kb.ask(C) is False
+    assert kb.ask(~A) is False
+    assert kb.ask(~B) is False
+    assert kb.ask(~C) is False
+    assert kb.ask(A >> C) is True
+    kb.tell(A)
+    assert kb.ask(A) is True
+    assert kb.ask(B) is True
+    assert kb.ask(C) is True
+    assert kb.ask(~C) is False
+    kb.retract(A)
+    assert kb.ask(C) is False
+
+
+def test_propKB_tolerant():
+    """"tolerant to bad input"""
+    kb = PropKB()
+    A, B, C = symbols('A,B,C')
+    assert kb.ask(B) is False
+
+def test_satisfiable_non_symbols():
+    x, y = symbols('x y')
+    assumptions = Q.zero(x*y)
+    facts = Implies(Q.zero(x*y), Q.zero(x) | Q.zero(y))
+    query = ~Q.zero(x) & ~Q.zero(y)
+    refutations = [
+        {Q.zero(x): True, Q.zero(x*y): True},
+        {Q.zero(y): True, Q.zero(x*y): True},
+        {Q.zero(x): True, Q.zero(y): True, Q.zero(x*y): True},
+        {Q.zero(x): True, Q.zero(y): False, Q.zero(x*y): True},
+        {Q.zero(x): False, Q.zero(y): True, Q.zero(x*y): True}]
+    assert not satisfiable(And(assumptions, facts, query), algorithm='dpll')
+    assert satisfiable(And(assumptions, facts, ~query), algorithm='dpll') in refutations
+    assert not satisfiable(And(assumptions, facts, query), algorithm='dpll2')
+    assert satisfiable(And(assumptions, facts, ~query), algorithm='dpll2') in refutations
+
+def test_satisfiable_bool():
+    from sympy.core.singleton import S
+    assert satisfiable(true) == {true: true}
+    assert satisfiable(S.true) == {true: true}
+    assert satisfiable(false) is False
+    assert satisfiable(S.false) is False
+
+
+def test_satisfiable_all_models():
+    from sympy.abc import A, B
+    assert next(satisfiable(False, all_models=True)) is False
+    assert list(satisfiable((A >> ~A) & A, all_models=True)) == [False]
+    assert list(satisfiable(True, all_models=True)) == [{true: true}]
+
+    models = [{A: True, B: False}, {A: False, B: True}]
+    result = satisfiable(A ^ B, all_models=True)
+    models.remove(next(result))
+    models.remove(next(result))
+    raises(StopIteration, lambda: next(result))
+    assert not models
+
+    assert list(satisfiable(Equivalent(A, B), all_models=True)) == \
+    [{A: False, B: False}, {A: True, B: True}]
+
+    models = [{A: False, B: False}, {A: False, B: True}, {A: True, B: True}]
+    for model in satisfiable(A >> B, all_models=True):
+        models.remove(model)
+    assert not models
+
+    # This is a santiy test to check that only the required number
+    # of solutions are generated. The expr below has 2**100 - 1 models
+    # which would time out the test if all are generated at once.
+    from sympy.utilities.iterables import numbered_symbols
+    from sympy.logic.boolalg import Or
+    sym = numbered_symbols()
+    X = [next(sym) for i in range(100)]
+    result = satisfiable(Or(*X), all_models=True)
+    for i in range(10):
+        assert next(result)
+
+
+def test_z3():
+    z3 = import_module("z3")
+
+    if not z3:
+        skip("z3 not installed.")
+    A, B, C = symbols('A,B,C')
+    x, y, z = symbols('x,y,z')
+    assert z3_satisfiable((x >= 2) & (x < 1)) is False
+    assert z3_satisfiable( A & ~A ) is False
+
+    model = z3_satisfiable(A & (~A | B | C))
+    assert bool(model) is True
+    assert model[A] is True
+
+    # test nonlinear function
+    assert z3_satisfiable((x ** 2 >= 2) & (x < 1) & (x > -1)) is False
+
+
+def test_z3_vs_lra_dpll2():
+    z3 = import_module("z3")
+    if z3 is None:
+        skip("z3 not installed.")
+
+    def boolean_formula_to_encoded_cnf(bf):
+        cnf = CNF.from_prop(bf)
+        enc = EncodedCNF()
+        enc.from_cnf(cnf)
+        return enc
+
+    def make_random_cnf(num_clauses=5, num_constraints=10, num_var=2):
+        assert num_clauses <= num_constraints
+        constraints = make_random_problem(num_variables=num_var, num_constraints=num_constraints, rational=False)
+        clauses = [[cons] for cons in constraints[:num_clauses]]
+        for cons in constraints[num_clauses:]:
+            if isinstance(cons, Unequality):
+                cons = ~cons
+            i = randint(0, num_clauses-1)
+            clauses[i].append(cons)
+
+        clauses = [Or(*clause) for clause in clauses]
+        cnf = And(*clauses)
+        return boolean_formula_to_encoded_cnf(cnf)
+
+    lra_dpll2_satisfiable = lambda x: dpll2_satisfiable(x, use_lra_theory=True)
+
+    for _ in range(50):
+        cnf = make_random_cnf(num_clauses=10, num_constraints=15, num_var=2)
+
+        try:
+            z3_sat = z3_satisfiable(cnf)
+        except z3.z3types.Z3Exception:
+            continue
+
+        lra_dpll2_sat = lra_dpll2_satisfiable(cnf) is not False
+
+        assert z3_sat == lra_dpll2_sat
+
+def test_issue_27733():
+    x, y = symbols('x,y')
+    clauses = [[1, -3, -2], [5, 7, -8, -6, -4], [-10, -9, 10, 11, -4], [-12, 13, 14], [-10, 9, -6, 11, -4],
+               [16, -15, 18, -19, -17], [11, -6, 10, -9], [9, 11, -10, -9], [2, -3, -1], [-13, 12], [-15, 3, -17],
+               [-16, -15, 19, -17], [-6, -9, 10, 11, -4], [20, -1, -2], [-23, -22, -21], [10, 11, -10, -9],
+               [9, 11, -4, -10], [24, -6, -4], [-14, 12], [-10, -9, 9, -6, 11], [25, -27, -26], [-15, 19, -18, -17],
+               [5, 8, -7, -6, -4], [-30, -29, 28], [12], [14]]
+
+    encoding = {Q.gt(y, i): i for i in range(1, 31) if i != 11 and i != 12}
+    encoding[Q.gt(x, 0)] = 11
+    encoding[Q.lt(x, 0)] = 12
+
+    cnf = EncodedCNF(clauses, encoding)
+    assert satisfiable(cnf, use_lra_theory=True) is False
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/tests/test_lra_theory.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/tests/test_lra_theory.py
new file mode 100644
index 0000000000000000000000000000000000000000..207a3c5ba2c1b16ee5323382deee0863a5dfb595
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/tests/test_lra_theory.py
@@ -0,0 +1,440 @@
+from sympy.core.numbers import Rational, I, oo
+from sympy.core.relational import Eq
+from sympy.core.symbol import symbols
+from sympy.core.singleton import S
+from sympy.matrices.dense import Matrix
+from sympy.matrices.dense import randMatrix
+from sympy.assumptions.ask import Q
+from sympy.logic.boolalg import And
+from sympy.abc import x, y, z
+from sympy.assumptions.cnf import CNF, EncodedCNF
+from sympy.functions.elementary.trigonometric import cos
+from sympy.external import import_module
+
+from sympy.logic.algorithms.lra_theory import LRASolver, UnhandledInput, LRARational, HANDLE_NEGATION
+from sympy.core.random import random, choice, randint
+from sympy.core.sympify import sympify
+from sympy.ntheory.generate import randprime
+from sympy.core.relational import StrictLessThan, StrictGreaterThan
+import itertools
+
+from sympy.testing.pytest import raises, XFAIL, skip
+
+def make_random_problem(num_variables=2, num_constraints=2, sparsity=.1, rational=True,
+                        disable_strict = False, disable_nonstrict=False, disable_equality=False):
+    def rand(sparsity=sparsity):
+        if random() < sparsity:
+            return sympify(0)
+        if rational:
+            int1, int2 = [randprime(0, 50) for _ in range(2)]
+            return Rational(int1, int2) * choice([-1, 1])
+        else:
+            return randint(1, 10) * choice([-1, 1])
+
+    variables = symbols('x1:%s' % (num_variables + 1))
+    constraints = []
+    for _ in range(num_constraints):
+        lhs, rhs = sum(rand() * x for x in variables), rand(sparsity=0) # sparsity=0  bc of bug with smtlib_code
+        options = []
+        if not disable_equality:
+            options += [Eq(lhs, rhs)]
+        if not disable_nonstrict:
+            options += [lhs <= rhs, lhs >= rhs]
+        if not disable_strict:
+            options += [lhs < rhs, lhs > rhs]
+
+        constraints.append(choice(options))
+
+    return constraints
+
+def check_if_satisfiable_with_z3(constraints):
+    from sympy.external.importtools import import_module
+    from sympy.printing.smtlib import smtlib_code
+    from sympy.logic.boolalg import And
+    boolean_formula = And(*constraints)
+    z3 = import_module("z3")
+    if z3:
+        smtlib_string = smtlib_code(boolean_formula)
+        s = z3.Solver()
+        s.from_string(smtlib_string)
+        res = str(s.check())
+        if res == 'sat':
+            return True
+        elif res == 'unsat':
+            return False
+        else:
+            raise ValueError(f"z3 was not able to check the satisfiability of {boolean_formula}")
+
+def find_rational_assignment(constr, assignment, iter=20):
+    eps = sympify(1)
+
+    for _ in range(iter):
+        assign = {key: val[0] + val[1]*eps for key, val in assignment.items()}
+        try:
+            for cons in constr:
+                assert cons.subs(assign) == True
+            return assign
+        except AssertionError:
+            eps = eps/2
+
+    return None
+
+def boolean_formula_to_encoded_cnf(bf):
+    cnf = CNF.from_prop(bf)
+    enc = EncodedCNF()
+    enc.from_cnf(cnf)
+    return enc
+
+
+def test_from_encoded_cnf():
+    s1, s2 = symbols("s1 s2")
+
+    # Test preprocessing
+    # Example is from section 3 of paper.
+    phi = (x >= 0) & ((x + y <= 2) | (x + 2 * y - z >= 6)) & (Eq(x + y, 2) | (x + 2 * y - z > 4))
+    enc = boolean_formula_to_encoded_cnf(phi)
+    lra, _ = LRASolver.from_encoded_cnf(enc, testing_mode=True)
+    assert lra.A.shape == (2, 5)
+    assert str(lra.slack) == '[_s1, _s2]'
+    assert str(lra.nonslack) == '[x, y, z]'
+    assert lra.A == Matrix([[ 1,  1, 0, -1,  0],
+                            [-1, -2, 1,  0, -1]])
+    assert {(str(b.var), b.bound, b.upper, b.equality, b.strict) for b in lra.enc_to_boundary.values()} == {('_s1', 2, None, True, False),
+    ('_s1', 2, True, False, False),
+    ('_s2', -4, True, False, True),
+    ('_s2', -6, True, False, False),
+    ('x', 0, False, False, False)}
+
+
+def test_problem():
+    from sympy.logic.algorithms.lra_theory import LRASolver
+    from sympy.assumptions.cnf import CNF, EncodedCNF
+    cons = [-2 * x - 2 * y >= 7, -9 * y >= 7, -6 * y >= 5]
+    cnf = CNF().from_prop(And(*cons))
+    enc = EncodedCNF()
+    enc.from_cnf(cnf)
+    lra, _ = LRASolver.from_encoded_cnf(enc)
+    lra.assert_lit(1)
+    lra.assert_lit(2)
+    lra.assert_lit(3)
+    is_sat, assignment = lra.check()
+    assert is_sat is True
+
+
+def test_random_problems():
+    z3 = import_module("z3")
+    if z3 is None:
+        skip("z3 is not installed")
+
+    special_cases = []; x1, x2, x3 = symbols("x1 x2 x3")
+    special_cases.append([x1 - 3 * x2 <= -5, 6 * x1 + 4 * x2 <= 0, -7 * x1 + 3 * x2 <= 3])
+    special_cases.append([-3 * x1 >= 3, Eq(4 * x1, -1)])
+    special_cases.append([-4 * x1 < 4, 6 * x1 <= -6])
+    special_cases.append([-3 * x2 >= 7, 6 * x1 <= -5, -3 * x2 <= -4])
+    special_cases.append([x + y >= 2, x + y <= 1])
+    special_cases.append([x >= 0, x + y <= 2, x + 2 * y - z >= 6])  # from paper example
+    special_cases.append([-2 * x1 - 2 * x2 >= 7, -9 * x1 >= 7, -6 * x1 >= 5])
+    special_cases.append([2 * x1 > -3, -9 * x1 < -6, 9 * x1 <= 6])
+    special_cases.append([-2*x1 < -4, 9*x1 > -9])
+    special_cases.append([-6*x1 >= -1, -8*x1 + x2 >= 5, -8*x1 + 7*x2 < 4, x1 > 7])
+    special_cases.append([Eq(x1, 2), Eq(5*x1, -2), Eq(-7*x2, -6), Eq(9*x1 + 10*x2, 9)])
+    special_cases.append([Eq(3*x1, 6), Eq(x1 - 8*x2, -9), Eq(-7*x1 + 5*x2, 3), Eq(3*x2, 7)])
+    special_cases.append([-4*x1 < 4, 6*x1 <= -6])
+    special_cases.append([-3*x1 + 8*x2 >= -8, -10*x2 > 9, 8*x1 - 4*x2 < 8, 10*x1 - 9*x2 >= -9])
+    special_cases.append([x1 + 5*x2 >= -6, 9*x1 - 3*x2 >= -9, 6*x1 + 6*x2 < -10, -3*x1 + 3*x2 < -7])
+    special_cases.append([-9*x1 < 7, -5*x1 - 7*x2 < -1, 3*x1 + 7*x2 > 1, -6*x1 - 6*x2 > 9])
+    special_cases.append([9*x1 - 6*x2 >= -7, 9*x1 + 4*x2 < -8, -7*x2 <= 1, 10*x2 <= -7])
+
+    feasible_count = 0
+    for i in range(50):
+        if i % 8 == 0:
+            constraints = make_random_problem(num_variables=1, num_constraints=2, rational=False)
+        elif i % 8 == 1:
+            constraints = make_random_problem(num_variables=2, num_constraints=4, rational=False, disable_equality=True,
+                                              disable_nonstrict=True)
+        elif i % 8 == 2:
+            constraints = make_random_problem(num_variables=2, num_constraints=4, rational=False, disable_strict=True)
+        elif i % 8 == 3:
+            constraints = make_random_problem(num_variables=3, num_constraints=12, rational=False)
+        else:
+            constraints = make_random_problem(num_variables=3, num_constraints=6, rational=False)
+
+        if i < len(special_cases):
+            constraints = special_cases[i]
+
+        if False in constraints or True in constraints:
+            continue
+
+        phi = And(*constraints)
+        if phi == False:
+            continue
+        cnf = CNF.from_prop(phi); enc = EncodedCNF()
+        enc.from_cnf(cnf)
+        assert all(0 not in clause for clause in enc.data)
+
+        lra, _ = LRASolver.from_encoded_cnf(enc, testing_mode=True)
+        s_subs = lra.s_subs
+
+        lra.run_checks = True
+        s_subs_rev = {value: key for key, value in s_subs.items()}
+        lits = {lit for clause in enc.data for lit in clause}
+
+        bounds = [(lra.enc_to_boundary[l], l) for l in lits if l in lra.enc_to_boundary]
+        bounds = sorted(bounds, key=lambda x: (str(x[0].var), x[0].bound, str(x[0].upper))) # to remove nondeterminism
+
+        for b, l in bounds:
+            if lra.result and lra.result[0] == False:
+                break
+            lra.assert_lit(l)
+
+        feasible = lra.check()
+
+        if feasible[0] == True:
+            feasible_count += 1
+            assert check_if_satisfiable_with_z3(constraints) is True
+            cons_funcs = [cons.func for cons in constraints]
+            assignment = feasible[1]
+            assignment = {key.var : value for key, value in assignment.items()}
+            if not (StrictLessThan in cons_funcs or StrictGreaterThan in cons_funcs):
+                assignment = {key: value[0] for key, value in assignment.items()}
+                for cons in constraints:
+                    assert cons.subs(assignment) == True
+
+            else:
+                rat_assignment = find_rational_assignment(constraints, assignment)
+                assert rat_assignment is not None
+        else:
+            assert check_if_satisfiable_with_z3(constraints) is False
+
+            conflict = feasible[1]
+            assert len(conflict) >= 2
+            conflict = {lra.enc_to_boundary[-l].get_inequality() for l in conflict}
+            conflict = {clause.subs(s_subs_rev) for clause in conflict}
+            assert check_if_satisfiable_with_z3(conflict) is False
+
+            # check that conflict clause is probably minimal
+            for subset in itertools.combinations(conflict, len(conflict)-1):
+                assert check_if_satisfiable_with_z3(subset) is True
+
+
+@XFAIL
+def test_pos_neg_zero():
+    bf = Q.positive(x) & Q.negative(x) & Q.zero(y)
+    enc = boolean_formula_to_encoded_cnf(bf)
+    lra, _ = LRASolver.from_encoded_cnf(enc, testing_mode=True)
+    for lit in enc.encoding.values():
+        if lra.assert_lit(lit) is not None:
+            break
+    assert len(lra.enc_to_boundary) == 3
+    assert lra.check()[0] == False
+
+    bf = Q.positive(x) & Q.lt(x, -1)
+    enc = boolean_formula_to_encoded_cnf(bf)
+    lra, _ = LRASolver.from_encoded_cnf(enc, testing_mode=True)
+    for lit in enc.encoding.values():
+        if lra.assert_lit(lit) is not None:
+            break
+    assert len(lra.enc_to_boundary) == 2
+    assert lra.check()[0] == False
+
+    bf = Q.positive(x) & Q.zero(x)
+    enc = boolean_formula_to_encoded_cnf(bf)
+    lra, _ = LRASolver.from_encoded_cnf(enc, testing_mode=True)
+    for lit in enc.encoding.values():
+        if lra.assert_lit(lit) is not None:
+            break
+    assert len(lra.enc_to_boundary) == 2
+    assert lra.check()[0] == False
+
+    bf = Q.positive(x) & Q.zero(y)
+    enc = boolean_formula_to_encoded_cnf(bf)
+    lra, _ = LRASolver.from_encoded_cnf(enc, testing_mode=True)
+    for lit in enc.encoding.values():
+        if lra.assert_lit(lit) is not None:
+            break
+    assert len(lra.enc_to_boundary) == 2
+    assert lra.check()[0] == True
+
+
+@XFAIL
+def test_pos_neg_infinite():
+    bf = Q.positive_infinite(x) & Q.lt(x, 10000000) & Q.positive_infinite(y)
+    enc = boolean_formula_to_encoded_cnf(bf)
+    lra, _ = LRASolver.from_encoded_cnf(enc, testing_mode=True)
+    for lit in enc.encoding.values():
+        if lra.assert_lit(lit) is not None:
+            break
+    assert len(lra.enc_to_boundary) == 3
+    assert lra.check()[0] == False
+
+    bf = Q.positive_infinite(x) & Q.gt(x, 10000000) & Q.positive_infinite(y)
+    enc = boolean_formula_to_encoded_cnf(bf)
+    lra, _ = LRASolver.from_encoded_cnf(enc, testing_mode=True)
+    for lit in enc.encoding.values():
+        if lra.assert_lit(lit) is not None:
+            break
+    assert len(lra.enc_to_boundary) == 3
+    assert lra.check()[0] == True
+
+    bf = Q.positive_infinite(x) & Q.negative_infinite(x)
+    enc = boolean_formula_to_encoded_cnf(bf)
+    lra, _ = LRASolver.from_encoded_cnf(enc, testing_mode=True)
+    for lit in enc.encoding.values():
+        if lra.assert_lit(lit) is not None:
+            break
+    assert len(lra.enc_to_boundary) == 2
+    assert lra.check()[0] == False
+
+
+def test_binrel_evaluation():
+    bf = Q.gt(3, 2)
+    enc = boolean_formula_to_encoded_cnf(bf)
+    lra, conflicts = LRASolver.from_encoded_cnf(enc, testing_mode=True)
+    assert len(lra.enc_to_boundary) == 0
+    assert conflicts == [[1]]
+
+    bf = Q.lt(3, 2)
+    enc = boolean_formula_to_encoded_cnf(bf)
+    lra, conflicts = LRASolver.from_encoded_cnf(enc, testing_mode=True)
+    assert len(lra.enc_to_boundary) == 0
+    assert conflicts == [[-1]]
+
+
+def test_negation():
+    assert HANDLE_NEGATION is True
+    bf = Q.gt(x, 1) & ~Q.gt(x, 0)
+    enc = boolean_formula_to_encoded_cnf(bf)
+    lra, _ = LRASolver.from_encoded_cnf(enc, testing_mode=True)
+    for clause in enc.data:
+        for lit in clause:
+            lra.assert_lit(lit)
+    assert len(lra.enc_to_boundary) == 2
+    assert lra.check()[0] == False
+    assert sorted(lra.check()[1]) in [[-1, 2], [-2, 1]]
+
+    bf = ~Q.gt(x, 1) & ~Q.lt(x, 0)
+    enc = boolean_formula_to_encoded_cnf(bf)
+    lra, _ = LRASolver.from_encoded_cnf(enc, testing_mode=True)
+    for clause in enc.data:
+        for lit in clause:
+            lra.assert_lit(lit)
+    assert len(lra.enc_to_boundary) == 2
+    assert lra.check()[0] == True
+
+    bf = ~Q.gt(x, 0) & ~Q.lt(x, 1)
+    enc = boolean_formula_to_encoded_cnf(bf)
+    lra, _ = LRASolver.from_encoded_cnf(enc, testing_mode=True)
+    for clause in enc.data:
+        for lit in clause:
+            lra.assert_lit(lit)
+    assert len(lra.enc_to_boundary) == 2
+    assert lra.check()[0] == False
+
+    bf = ~Q.gt(x, 0) & ~Q.le(x, 0)
+    enc = boolean_formula_to_encoded_cnf(bf)
+    lra, _ = LRASolver.from_encoded_cnf(enc, testing_mode=True)
+    for clause in enc.data:
+        for lit in clause:
+            lra.assert_lit(lit)
+    assert len(lra.enc_to_boundary) == 2
+    assert lra.check()[0] == False
+
+    bf = ~Q.le(x+y, 2) & ~Q.ge(x-y, 2) & ~Q.ge(y, 0)
+    enc = boolean_formula_to_encoded_cnf(bf)
+    lra, _ = LRASolver.from_encoded_cnf(enc, testing_mode=True)
+    for clause in enc.data:
+        for lit in clause:
+            lra.assert_lit(lit)
+    assert len(lra.enc_to_boundary) == 3
+    assert lra.check()[0] == False
+    assert len(lra.check()[1]) == 3
+    assert all(i > 0 for i in lra.check()[1])
+
+
+def test_unhandled_input():
+    nan = S.NaN
+    bf = Q.gt(3, nan) & Q.gt(x, nan)
+    enc = boolean_formula_to_encoded_cnf(bf)
+    raises(ValueError, lambda: LRASolver.from_encoded_cnf(enc, testing_mode=True))
+
+    bf = Q.gt(3, I) & Q.gt(x, I)
+    enc = boolean_formula_to_encoded_cnf(bf)
+    raises(UnhandledInput, lambda: LRASolver.from_encoded_cnf(enc, testing_mode=True))
+
+    bf = Q.gt(3, float("inf")) & Q.gt(x, float("inf"))
+    enc = boolean_formula_to_encoded_cnf(bf)
+    raises(UnhandledInput, lambda: LRASolver.from_encoded_cnf(enc, testing_mode=True))
+
+    bf = Q.gt(3, oo) & Q.gt(x, oo)
+    enc = boolean_formula_to_encoded_cnf(bf)
+    raises(UnhandledInput, lambda: LRASolver.from_encoded_cnf(enc, testing_mode=True))
+
+    # test non-linearity
+    bf = Q.gt(x**2 + x, 2)
+    enc = boolean_formula_to_encoded_cnf(bf)
+    raises(UnhandledInput, lambda: LRASolver.from_encoded_cnf(enc, testing_mode=True))
+
+    bf = Q.gt(cos(x) + x, 2)
+    enc = boolean_formula_to_encoded_cnf(bf)
+    raises(UnhandledInput, lambda: LRASolver.from_encoded_cnf(enc, testing_mode=True))
+
+@XFAIL
+def test_infinite_strict_inequalities():
+    # Extensive testing of the interaction between strict inequalities
+    # and constraints containing infinity is needed because
+    # the paper's rule for strict inequalities don't work when
+    # infinite numbers are allowed. Using the paper's rules you
+    # can end up with situations where oo + delta > oo is considered
+    # True when oo + delta should be equal to oo.
+    # See https://math.stackexchange.com/questions/4757069/can-this-method-of-converting-strict-inequalities-to-equisatisfiable-nonstrict-i
+    bf = (-x - y >= -float("inf")) & (x > 0) & (y >= float("inf"))
+    enc = boolean_formula_to_encoded_cnf(bf)
+    lra, _ = LRASolver.from_encoded_cnf(enc, testing_mode=True)
+    for lit in sorted(enc.encoding.values()):
+        if lra.assert_lit(lit) is not None:
+            break
+    assert len(lra.enc_to_boundary) == 3
+    assert lra.check()[0] == True
+
+
+def test_pivot():
+    for _ in range(10):
+        m = randMatrix(5)
+        rref = m.rref()
+        for _ in range(5):
+            i, j = randint(0, 4), randint(0, 4)
+            if m[i, j] != 0:
+                assert LRASolver._pivot(m, i, j).rref() == rref
+
+
+def test_reset_bounds():
+    bf = Q.ge(x, 1) & Q.lt(x, 1)
+    enc = boolean_formula_to_encoded_cnf(bf)
+    lra, _ = LRASolver.from_encoded_cnf(enc, testing_mode=True)
+    for clause in enc.data:
+        for lit in clause:
+            lra.assert_lit(lit)
+    assert len(lra.enc_to_boundary) == 2
+    assert lra.check()[0] == False
+
+    lra.reset_bounds()
+    assert lra.check()[0] == True
+    for var in lra.all_var:
+        assert var.upper == LRARational(float("inf"), 0)
+        assert var.upper_from_eq == False
+        assert var.upper_from_neg == False
+        assert var.lower == LRARational(-float("inf"), 0)
+        assert var.lower_from_eq == False
+        assert var.lower_from_neg == False
+        assert var.assign == LRARational(0, 0)
+        assert var.var is not None
+        assert var.col_idx is not None
+
+
+def test_empty_cnf():
+    cnf = CNF()
+    enc = EncodedCNF()
+    enc.from_cnf(cnf)
+    lra, conflict = LRASolver.from_encoded_cnf(enc)
+    assert len(conflict) == 0
+    assert lra.check() == (True, {})
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/utilities/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/utilities/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3526c3e53d624bc70afe2df05f123c835781364c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/utilities/__init__.py
@@ -0,0 +1,3 @@
+from .dimacs import load_file
+
+__all__ = ['load_file']
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/utilities/dimacs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/utilities/dimacs.py
new file mode 100644
index 0000000000000000000000000000000000000000..51302d8052c8ed8443239c1e21a2f063cf34e4ab
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/logic/utilities/dimacs.py
@@ -0,0 +1,69 @@
+"""For reading in DIMACS file format
+
+www.cs.ubc.ca/~hoos/SATLIB/Benchmarks/SAT/satformat.ps
+
+"""
+
+from sympy.core import Symbol
+from sympy.logic.boolalg import And, Or
+import re
+from pathlib import Path
+
+
+def load(s):
+    """Loads a boolean expression from a string.
+
+    Examples
+    ========
+
+    >>> from sympy.logic.utilities.dimacs import load
+    >>> load('1')
+    cnf_1
+    >>> load('1 2')
+    cnf_1 | cnf_2
+    >>> load('1 \\n 2')
+    cnf_1 & cnf_2
+    >>> load('1 2 \\n 3')
+    cnf_3 & (cnf_1 | cnf_2)
+    """
+    clauses = []
+
+    lines = s.split('\n')
+
+    pComment = re.compile(r'c.*')
+    pStats = re.compile(r'p\s*cnf\s*(\d*)\s*(\d*)')
+
+    while len(lines) > 0:
+        line = lines.pop(0)
+
+        # Only deal with lines that aren't comments
+        if not pComment.match(line):
+            m = pStats.match(line)
+
+            if not m:
+                nums = line.rstrip('\n').split(' ')
+                list = []
+                for lit in nums:
+                    if lit != '':
+                        if int(lit) == 0:
+                            continue
+                        num = abs(int(lit))
+                        sign = True
+                        if int(lit) < 0:
+                            sign = False
+
+                        if sign:
+                            list.append(Symbol("cnf_%s" % num))
+                        else:
+                            list.append(~Symbol("cnf_%s" % num))
+
+                if len(list) > 0:
+                    clauses.append(Or(*list))
+
+    return And(*clauses)
+
+
+def load_file(location):
+    """Loads a boolean expression from a file."""
+    s = Path(location).read_text()
+    return load(s)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..19576c8935da455743d27f0a263caecca94f59f8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__init__.py
@@ -0,0 +1,67 @@
+"""
+Number theory module (primes, etc)
+"""
+
+from .generate import nextprime, prevprime, prime, primepi, primerange, \
+    randprime, Sieve, sieve, primorial, cycle_length, composite, compositepi
+from .primetest import isprime, is_gaussian_prime, is_mersenne_prime
+from .factor_ import divisors, proper_divisors, factorint, multiplicity, \
+    multiplicity_in_factorial, perfect_power, factor_cache, pollard_pm1, \
+    pollard_rho, primefactors, totient, \
+    divisor_count, proper_divisor_count, divisor_sigma, factorrat, \
+    reduced_totient, primenu, primeomega, mersenne_prime_exponent, \
+    is_perfect, is_abundant, is_deficient, is_amicable, is_carmichael, \
+    abundance, dra, drm
+
+from .partitions_ import npartitions
+from .residue_ntheory import is_primitive_root, is_quad_residue, \
+    legendre_symbol, jacobi_symbol, n_order, sqrt_mod, quadratic_residues, \
+    primitive_root, nthroot_mod, is_nthpow_residue, sqrt_mod_iter, mobius, \
+    discrete_log, quadratic_congruence, polynomial_congruence
+from .multinomial import binomial_coefficients, binomial_coefficients_list, \
+    multinomial_coefficients
+from .continued_fraction import continued_fraction_periodic, \
+    continued_fraction_iterator, continued_fraction_reduce, \
+    continued_fraction_convergents, continued_fraction
+from .digits import count_digits, digits, is_palindromic
+from .egyptian_fraction import egyptian_fraction
+from .ecm import ecm
+from .qs import qs, qs_factor
+__all__ = [
+    'nextprime', 'prevprime', 'prime', 'primepi', 'primerange', 'randprime',
+    'Sieve', 'sieve', 'primorial', 'cycle_length', 'composite', 'compositepi',
+
+    'isprime', 'is_gaussian_prime', 'is_mersenne_prime',
+
+
+    'divisors', 'proper_divisors', 'factorint', 'multiplicity', 'perfect_power',
+    'pollard_pm1', 'factor_cache', 'pollard_rho', 'primefactors', 'totient',
+    'divisor_count', 'proper_divisor_count', 'divisor_sigma', 'factorrat',
+    'reduced_totient', 'primenu', 'primeomega', 'mersenne_prime_exponent',
+    'is_perfect', 'is_abundant', 'is_deficient', 'is_amicable',
+    'is_carmichael', 'abundance', 'dra', 'drm', 'multiplicity_in_factorial',
+
+    'npartitions',
+
+    'is_primitive_root', 'is_quad_residue', 'legendre_symbol',
+    'jacobi_symbol', 'n_order', 'sqrt_mod', 'quadratic_residues',
+    'primitive_root', 'nthroot_mod', 'is_nthpow_residue', 'sqrt_mod_iter',
+    'mobius', 'discrete_log', 'quadratic_congruence', 'polynomial_congruence',
+
+    'binomial_coefficients', 'binomial_coefficients_list',
+    'multinomial_coefficients',
+
+    'continued_fraction_periodic', 'continued_fraction_iterator',
+    'continued_fraction_reduce', 'continued_fraction_convergents',
+    'continued_fraction',
+
+    'digits',
+    'count_digits',
+    'is_palindromic',
+
+    'egyptian_fraction',
+
+    'ecm',
+
+    'qs', 'qs_factor',
+]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..57985b43cc60cae5734f6cd21ce761b351de1705
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/continued_fraction.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/continued_fraction.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..03b87e2d9cd390a1719e5cdaf6a8c3ffa60aa344
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/continued_fraction.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/digits.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/digits.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a0a7f0f3fdf76be2d8f894338e52f452a7cbc0ba
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/digits.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/ecm.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/ecm.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36887f78f2e4d338b9d3589a19dff5d46f97ae05
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/ecm.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/egyptian_fraction.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/egyptian_fraction.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d2e0fbca07a9d743f523165469e5469c766202e4
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/egyptian_fraction.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/factor_.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/factor_.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fb695eeb35acb14d8182530781eeaaed14dfc0c6
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/factor_.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/generate.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/generate.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0190c38ae393f5b65c4a234bc5a6b0b6b048fea8
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/generate.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/modular.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/modular.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d61c9ef548e77a2ebc982752eafc638823588ea5
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/modular.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/multinomial.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/multinomial.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c3381536651e2179e80e462547ede0b575e0949b
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/multinomial.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/partitions_.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/partitions_.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b32010a997c0c344d3af76240684c9f189946d8a
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/partitions_.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/primetest.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/primetest.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8180ecdbe83a41c09357d5db8bd0983d2eb04ff3
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/primetest.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/qs.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/qs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f919aa15c8a4c79fca5aa344015d1abab3b04aa9
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/qs.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/residue_ntheory.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/residue_ntheory.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4cd780caedc61dd63b834b0491f319c1451cd644
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/__pycache__/residue_ntheory.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/bbp_pi.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/bbp_pi.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2ff4b755d74d4e075ac7195f991c8182d175693
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/bbp_pi.py
@@ -0,0 +1,190 @@
+'''
+This implementation is a heavily modified fixed point implementation of
+BBP_formula for calculating the nth position of pi. The original hosted
+at: https://web.archive.org/web/20151116045029/http://en.literateprograms.org/Pi_with_the_BBP_formula_(Python)
+
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sub-license, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+Modifications:
+
+1.Once the nth digit and desired number of digits is selected, the
+number of digits of working precision is calculated to ensure that
+the hexadecimal digits returned are accurate. This is calculated as
+
+    int(math.log(start + prec)/math.log(16) + prec + 3)
+    ---------------------------------------   --------
+                      /                          /
+    number of hex digits           additional digits
+
+This was checked by the following code which completed without
+errors (and dig are the digits included in the test_bbp.py file):
+
+    for i in range(0,1000):
+     for j in range(1,1000):
+      a, b = pi_hex_digits(i, j), dig[i:i+j]
+      if a != b:
+        print('%s\n%s'%(a,b))
+
+Deceasing the additional digits by 1 generated errors, so '3' is
+the smallest additional precision needed to calculate the above
+loop without errors. The following trailing 10 digits were also
+checked to be accurate (and the times were slightly faster with
+some of the constant modifications that were made):
+
+    >> from time import time
+    >> t=time();pi_hex_digits(10**2-10 + 1, 10), time()-t
+    ('e90c6cc0ac', 0.0)
+    >> t=time();pi_hex_digits(10**4-10 + 1, 10), time()-t
+    ('26aab49ec6', 0.17100000381469727)
+    >> t=time();pi_hex_digits(10**5-10 + 1, 10), time()-t
+    ('a22673c1a5', 4.7109999656677246)
+    >> t=time();pi_hex_digits(10**6-10 + 1, 10), time()-t
+    ('9ffd342362', 59.985999822616577)
+    >> t=time();pi_hex_digits(10**7-10 + 1, 10), time()-t
+    ('c1a42e06a1', 689.51800012588501)
+
+2. The while loop to evaluate whether the series has converged quits
+when the addition amount `dt` has dropped to zero.
+
+3. the formatting string to convert the decimal to hexadecimal is
+calculated for the given precision.
+
+4. pi_hex_digits(n) changed to have coefficient to the formula in an
+array (perhaps just a matter of preference).
+
+'''
+
+from sympy.utilities.misc import as_int
+
+
+def _series(j, n, prec=14):
+
+    # Left sum from the bbp algorithm
+    s = 0
+    D = _dn(n, prec)
+    D4 = 4 * D
+    d = j
+    for k in range(n + 1):
+        s += (pow(16, n - k, d) << D4) // d
+        d += 8
+
+    # Right sum iterates to infinity for full precision, but we
+    # stop at the point where one iteration is beyond the precision
+    # specified.
+
+    t = 0
+    k = n + 1
+    e = D4 - 4 # 4*(D + n - k)
+    d = 8 * k + j
+    while True:
+        dt = (1 << e) // d
+        if not dt:
+            break
+        t += dt
+        # k += 1
+        e -= 4
+        d += 8
+    total = s + t
+
+    return total
+
+
+def pi_hex_digits(n, prec=14):
+    """Returns a string containing ``prec`` (default 14) digits
+    starting at the nth digit of pi in hex. Counting of digits
+    starts at 0 and the decimal is not counted, so for n = 0 the
+    returned value starts with 3; n = 1 corresponds to the first
+    digit past the decimal point (which in hex is 2).
+
+    Parameters
+    ==========
+
+    n : non-negative integer
+    prec : non-negative integer. default = 14
+
+    Returns
+    =======
+
+    str : Returns a string containing ``prec`` digits
+          starting at the nth digit of pi in hex.
+          If ``prec`` = 0, returns empty string.
+
+    Raises
+    ======
+
+    ValueError
+        If ``n`` < 0 or ``prec`` < 0.
+        Or ``n`` or ``prec`` is not an integer.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.bbp_pi import pi_hex_digits
+    >>> pi_hex_digits(0)
+    '3243f6a8885a30'
+    >>> pi_hex_digits(0, 3)
+    '324'
+
+    These are consistent with the following results
+
+    >>> import math
+    >>> hex(int(math.pi * 2**((14-1)*4)))
+    '0x3243f6a8885a30'
+    >>> hex(int(math.pi * 2**((3-1)*4)))
+    '0x324'
+
+    References
+    ==========
+
+    .. [1] http://www.numberworld.org/digits/Pi/
+    """
+    n, prec = as_int(n), as_int(prec)
+    if n < 0:
+        raise ValueError('n cannot be negative')
+    if prec < 0:
+        raise ValueError('prec cannot be negative')
+    if prec == 0:
+        return ''
+
+    # main of implementation arrays holding formulae coefficients
+    n -= 1
+    a = [4, 2, 1, 1]
+    j = [1, 4, 5, 6]
+
+    #formulae
+    D = _dn(n, prec)
+    x = + (a[0]*_series(j[0], n, prec)
+         - a[1]*_series(j[1], n, prec)
+         - a[2]*_series(j[2], n, prec)
+         - a[3]*_series(j[3], n, prec)) & (16**D - 1)
+
+    s = ("%0" + "%ix" % prec) % (x // 16**(D - prec))
+    return s
+
+
+def _dn(n, prec):
+    # controller for n dependence on precision
+    # n = starting digit index
+    # prec = the number of total digits to compute
+    n += 1  # because we subtract 1 for _series
+
+    # assert int(math.log(n + prec)/math.log(16)) ==\
+    #  ((n + prec).bit_length() - 1) // 4
+    return ((n + prec).bit_length() - 1) // 4 + prec + 3
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/continued_fraction.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/continued_fraction.py
new file mode 100644
index 0000000000000000000000000000000000000000..62f8e2d729ada3414a87d6f0583e06bee2a2b220
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/continued_fraction.py
@@ -0,0 +1,369 @@
+from __future__ import annotations
+import itertools
+from sympy.core.exprtools import factor_terms
+from sympy.core.numbers import Integer, Rational
+from sympy.core.singleton import S
+from sympy.core.symbol import Dummy
+from sympy.core.sympify import _sympify
+from sympy.utilities.misc import as_int
+
+
+def continued_fraction(a) -> list:
+    """Return the continued fraction representation of a Rational or
+    quadratic irrational.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.continued_fraction import continued_fraction
+    >>> from sympy import sqrt
+    >>> continued_fraction((1 + 2*sqrt(3))/5)
+    [0, 1, [8, 3, 34, 3]]
+
+    See Also
+    ========
+    continued_fraction_periodic, continued_fraction_reduce, continued_fraction_convergents
+    """
+    e = _sympify(a)
+    if all(i.is_Rational for i in e.atoms()):
+        if e.is_Integer:
+            return continued_fraction_periodic(e, 1, 0)
+        elif e.is_Rational:
+            return continued_fraction_periodic(e.p, e.q, 0)
+        elif e.is_Pow and e.exp is S.Half and e.base.is_Integer:
+            return continued_fraction_periodic(0, 1, e.base)
+        elif e.is_Mul and len(e.args) == 2 and (
+                e.args[0].is_Rational and
+                e.args[1].is_Pow and
+                e.args[1].base.is_Integer and
+                e.args[1].exp is S.Half):
+            a, b = e.args
+            return continued_fraction_periodic(0, a.q, b.base, a.p)
+        else:
+            # this should not have to work very hard- no
+            # simplification, cancel, etc... which should be
+            # done by the user.  e.g. This is a fancy 1 but
+            # the user should simplify it first:
+            # sqrt(2)*(1 + sqrt(2))/(sqrt(2) + 2)
+            p, d = e.expand().as_numer_denom()
+            if d.is_Integer:
+                if p.is_Rational:
+                    return continued_fraction_periodic(p, d)
+                # look for a + b*c
+                # with c = sqrt(s)
+                if p.is_Add and len(p.args) == 2:
+                    a, bc = p.args
+                else:
+                    a = S.Zero
+                    bc = p
+                if a.is_Integer:
+                    b = S.NaN
+                    if bc.is_Mul and len(bc.args) == 2:
+                        b, c = bc.args
+                    elif bc.is_Pow:
+                        b = Integer(1)
+                        c = bc
+                    if b.is_Integer and (
+                            c.is_Pow and c.exp is S.Half and
+                            c.base.is_Integer):
+                        # (a + b*sqrt(c))/d
+                        c = c.base
+                        return continued_fraction_periodic(a, d, c, b)
+    raise ValueError(
+        'expecting a rational or quadratic irrational, not %s' % e)
+
+
+def continued_fraction_periodic(p, q, d=0, s=1) -> list:
+    r"""
+    Find the periodic continued fraction expansion of a quadratic irrational.
+
+    Compute the continued fraction expansion of a rational or a
+    quadratic irrational number, i.e. `\frac{p + s\sqrt{d}}{q}`, where
+    `p`, `q \ne 0` and `d \ge 0` are integers.
+
+    Returns the continued fraction representation (canonical form) as
+    a list of integers, optionally ending (for quadratic irrationals)
+    with list of integers representing the repeating digits.
+
+    Parameters
+    ==========
+
+    p : int
+        the rational part of the number's numerator
+    q : int
+        the denominator of the number
+    d : int, optional
+        the irrational part (discriminator) of the number's numerator
+    s : int, optional
+        the coefficient of the irrational part
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.continued_fraction import continued_fraction_periodic
+    >>> continued_fraction_periodic(3, 2, 7)
+    [2, [1, 4, 1, 1]]
+
+    Golden ratio has the simplest continued fraction expansion:
+
+    >>> continued_fraction_periodic(1, 2, 5)
+    [[1]]
+
+    If the discriminator is zero or a perfect square then the number will be a
+    rational number:
+
+    >>> continued_fraction_periodic(4, 3, 0)
+    [1, 3]
+    >>> continued_fraction_periodic(4, 3, 49)
+    [3, 1, 2]
+
+    See Also
+    ========
+
+    continued_fraction_iterator, continued_fraction_reduce
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Periodic_continued_fraction
+    .. [2] K. Rosen. Elementary Number theory and its applications.
+           Addison-Wesley, 3 Sub edition, pages 379-381, January 1992.
+
+    """
+    from sympy.functions import sqrt, floor
+
+    p, q, d, s = list(map(as_int, [p, q, d, s]))
+
+    if d < 0:
+        raise ValueError("expected non-negative for `d` but got %s" % d)
+
+    if q == 0:
+        raise ValueError("The denominator cannot be 0.")
+
+    if not s:
+        d = 0
+
+    # check for rational case
+    sd = sqrt(d)
+    if sd.is_Integer:
+        return list(continued_fraction_iterator(Rational(p + s*sd, q)))
+
+    # irrational case with sd != Integer
+    if q < 0:
+        p, q, s = -p, -q, -s
+
+    n = (p + s*sd)/q
+    if n < 0:
+        w = floor(-n)
+        f = -n - w
+        one_f = continued_fraction(1 - f)  # 1-f < 1 so cf is [0 ... [...]]
+        one_f[0] -= w + 1
+        return one_f
+
+    d *= s**2
+    sd *= s
+
+    if (d - p**2)%q:
+        d *= q**2
+        sd *= q
+        p *= q
+        q *= q
+
+    terms: list[int] = []
+    pq = {}
+
+    while (p, q) not in pq:
+        pq[(p, q)] = len(terms)
+        terms.append((p + sd)//q)
+        p = terms[-1]*q - p
+        q = (d - p**2)//q
+
+    i = pq[(p, q)]
+    return terms[:i] + [terms[i:]]  # type: ignore
+
+
+def continued_fraction_reduce(cf):
+    """
+    Reduce a continued fraction to a rational or quadratic irrational.
+
+    Compute the rational or quadratic irrational number from its
+    terminating or periodic continued fraction expansion.  The
+    continued fraction expansion (cf) should be supplied as a
+    terminating iterator supplying the terms of the expansion.  For
+    terminating continued fractions, this is equivalent to
+    ``list(continued_fraction_convergents(cf))[-1]``, only a little more
+    efficient.  If the expansion has a repeating part, a list of the
+    repeating terms should be returned as the last element from the
+    iterator.  This is the format returned by
+    continued_fraction_periodic.
+
+    For quadratic irrationals, returns the largest solution found,
+    which is generally the one sought, if the fraction is in canonical
+    form (all terms positive except possibly the first).
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.continued_fraction import continued_fraction_reduce
+    >>> continued_fraction_reduce([1, 2, 3, 4, 5])
+    225/157
+    >>> continued_fraction_reduce([-2, 1, 9, 7, 1, 2])
+    -256/233
+    >>> continued_fraction_reduce([2, 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8]).n(10)
+    2.718281835
+    >>> continued_fraction_reduce([1, 4, 2, [3, 1]])
+    (sqrt(21) + 287)/238
+    >>> continued_fraction_reduce([[1]])
+    (1 + sqrt(5))/2
+    >>> from sympy.ntheory.continued_fraction import continued_fraction_periodic
+    >>> continued_fraction_reduce(continued_fraction_periodic(8, 5, 13))
+    (sqrt(13) + 8)/5
+
+    See Also
+    ========
+
+    continued_fraction_periodic
+
+    """
+    from sympy.solvers import solve
+
+    period = []
+    x = Dummy('x')
+
+    def untillist(cf):
+        for nxt in cf:
+            if isinstance(nxt, list):
+                period.extend(nxt)
+                yield x
+                break
+            yield nxt
+
+    a = S.Zero
+    for a in continued_fraction_convergents(untillist(cf)):
+        pass
+
+    if period:
+        y = Dummy('y')
+        solns = solve(continued_fraction_reduce(period + [y]) - y, y)
+        solns.sort()
+        pure = solns[-1]
+        rv = a.subs(x, pure).radsimp()
+    else:
+        rv = a
+    if rv.is_Add:
+        rv = factor_terms(rv)
+        if rv.is_Mul and rv.args[0] == -1:
+            rv = rv.func(*rv.args)
+    return rv
+
+
+def continued_fraction_iterator(x):
+    """
+    Return continued fraction expansion of x as iterator.
+
+    Examples
+    ========
+
+    >>> from sympy import Rational, pi
+    >>> from sympy.ntheory.continued_fraction import continued_fraction_iterator
+
+    >>> list(continued_fraction_iterator(Rational(3, 8)))
+    [0, 2, 1, 2]
+    >>> list(continued_fraction_iterator(Rational(-3, 8)))
+    [-1, 1, 1, 1, 2]
+
+    >>> for i, v in enumerate(continued_fraction_iterator(pi)):
+    ...     if i > 7:
+    ...         break
+    ...     print(v)
+    3
+    7
+    15
+    1
+    292
+    1
+    1
+    1
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Continued_fraction
+
+    """
+    from sympy.functions import floor
+    while True:
+        i = floor(x)
+        yield i
+        x -= i
+        if not x:
+            break
+        x = 1/x
+
+
+def continued_fraction_convergents(cf):
+    """
+    Return an iterator over the convergents of a continued fraction (cf).
+
+    The parameter should be in either of the following to forms:
+    - A list of partial quotients, possibly with the last element being a list
+    of repeating partial quotients, such as might be returned by
+    continued_fraction and continued_fraction_periodic.
+    - An iterable returning successive partial quotients of the continued
+    fraction, such as might be returned by continued_fraction_iterator.
+
+    In computing the convergents, the continued fraction need not be strictly
+    in canonical form (all integers, all but the first positive).
+    Rational and negative elements may be present in the expansion.
+
+    Examples
+    ========
+
+    >>> from sympy.core import pi
+    >>> from sympy import S
+    >>> from sympy.ntheory.continued_fraction import \
+            continued_fraction_convergents, continued_fraction_iterator
+
+    >>> list(continued_fraction_convergents([0, 2, 1, 2]))
+    [0, 1/2, 1/3, 3/8]
+
+    >>> list(continued_fraction_convergents([1, S('1/2'), -7, S('1/4')]))
+    [1, 3, 19/5, 7]
+
+    >>> it = continued_fraction_convergents(continued_fraction_iterator(pi))
+    >>> for n in range(7):
+    ...     print(next(it))
+    3
+    22/7
+    333/106
+    355/113
+    103993/33102
+    104348/33215
+    208341/66317
+
+    >>> it = continued_fraction_convergents([1, [1, 2]])  # sqrt(3)
+    >>> for n in range(7):
+    ...     print(next(it))
+    1
+    2
+    5/3
+    7/4
+    19/11
+    26/15
+    71/41
+
+    See Also
+    ========
+
+    continued_fraction_iterator, continued_fraction, continued_fraction_periodic
+
+    """
+    if isinstance(cf, list) and isinstance(cf[-1], list):
+        cf = itertools.chain(cf[:-1], itertools.cycle(cf[-1]))
+    p_2, q_2 = S.Zero, S.One
+    p_1, q_1 = S.One, S.Zero
+    for a in cf:
+        p, q = a*p_1 + p_2, a*q_1 + q_2
+        p_2, q_2 = p_1, q_1
+        p_1, q_1 = p, q
+        yield p/q
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/digits.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/digits.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0414815871f6f888ccd2823546ab2b0c2c9f515
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/digits.py
@@ -0,0 +1,150 @@
+from collections import defaultdict
+
+from sympy.utilities.iterables import multiset, is_palindromic as _palindromic
+from sympy.utilities.misc import as_int
+
+
+def digits(n, b=10, digits=None):
+    """
+    Return a list of the digits of ``n`` in base ``b``. The first
+    element in the list is ``b`` (or ``-b`` if ``n`` is negative).
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.digits import digits
+    >>> digits(35)
+    [10, 3, 5]
+
+    If the number is negative, the negative sign will be placed on the
+    base (which is the first element in the returned list):
+
+    >>> digits(-35)
+    [-10, 3, 5]
+
+    Bases other than 10 (and greater than 1) can be selected with ``b``:
+
+    >>> digits(27, b=2)
+    [2, 1, 1, 0, 1, 1]
+
+    Use the ``digits`` keyword if a certain number of digits is desired:
+
+    >>> digits(35, digits=4)
+    [10, 0, 0, 3, 5]
+
+    Parameters
+    ==========
+
+    n: integer
+        The number whose digits are returned.
+
+    b: integer
+        The base in which digits are computed.
+
+    digits: integer (or None for all digits)
+        The number of digits to be returned (padded with zeros, if
+        necessary).
+
+    See Also
+    ========
+    sympy.core.intfunc.num_digits, count_digits
+    """
+
+    b = as_int(b)
+    n = as_int(n)
+    if b < 2:
+        raise ValueError("b must be greater than 1")
+    else:
+        x, y = abs(n), []
+        while x >= b:
+            x, r = divmod(x, b)
+            y.append(r)
+        y.append(x)
+        y.append(-b if n < 0 else b)
+        y.reverse()
+        ndig = len(y) - 1
+        if digits is not None:
+            if ndig > digits:
+                raise ValueError(
+                    "For %s, at least %s digits are needed." % (n, ndig))
+            elif ndig < digits:
+                y[1:1] = [0]*(digits - ndig)
+        return y
+
+
+def count_digits(n, b=10):
+    """
+    Return a dictionary whose keys are the digits of ``n`` in the
+    given base, ``b``, with keys indicating the digits appearing in the
+    number and values indicating how many times that digit appeared.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory import count_digits
+
+    >>> count_digits(1111339)
+    {1: 4, 3: 2, 9: 1}
+
+    The digits returned are always represented in base-10
+    but the number itself can be entered in any format that is
+    understood by Python; the base of the number can also be
+    given if it is different than 10:
+
+    >>> n = 0xFA; n
+    250
+    >>> count_digits(_)
+    {0: 1, 2: 1, 5: 1}
+    >>> count_digits(n, 16)
+    {10: 1, 15: 1}
+
+    The default dictionary will return a 0 for any digit that did
+    not appear in the number. For example, which digits appear 7
+    times in ``77!``:
+
+    >>> from sympy import factorial
+    >>> c77 = count_digits(factorial(77))
+    >>> [i for i in range(10) if c77[i] == 7]
+    [1, 3, 7, 9]
+
+    See Also
+    ========
+    sympy.core.intfunc.num_digits, digits
+    """
+    rv = defaultdict(int, multiset(digits(n, b)).items())
+    rv.pop(b) if b in rv else rv.pop(-b)  # b or -b is there
+    return rv
+
+
+def is_palindromic(n, b=10):
+    """return True if ``n`` is the same when read from left to right
+    or right to left in the given base, ``b``.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory import is_palindromic
+
+    >>> all(is_palindromic(i) for i in (-11, 1, 22, 121))
+    True
+
+    The second argument allows you to test numbers in other
+    bases. For example, 88 is palindromic in base-10 but not
+    in base-8:
+
+    >>> is_palindromic(88, 8)
+    False
+
+    On the other hand, a number can be palindromic in base-8 but
+    not in base-10:
+
+    >>> 0o121, is_palindromic(0o121)
+    (81, False)
+
+    Or it might be palindromic in both bases:
+
+    >>> oct(121), is_palindromic(121, 8) and is_palindromic(121)
+    ('0o171', True)
+
+    """
+    return _palindromic(digits(n, b), 1)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/ecm.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/ecm.py
new file mode 100644
index 0000000000000000000000000000000000000000..498c0c8fdf8478688465c4bae307818e9685b686
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/ecm.py
@@ -0,0 +1,348 @@
+from math import log
+
+from sympy.core.random import _randint
+from sympy.external.gmpy import gcd, invert, sqrt
+from sympy.utilities.misc import as_int
+from .generate import sieve, primerange
+from .primetest import isprime
+
+
+#----------------------------------------------------------------------------#
+#                                                                            #
+#                   Lenstra's Elliptic Curve Factorization                   #
+#                                                                            #
+#----------------------------------------------------------------------------#
+
+
+class Point:
+    """Montgomery form of Points in an elliptic curve.
+    In this form, the addition and doubling of points
+    does not need any y-coordinate information thus
+    decreasing the number of operations.
+    Using Montgomery form we try to perform point addition
+    and doubling in least amount of multiplications.
+
+    The elliptic curve used here is of the form
+    (E : b*y**2*z = x**3 + a*x**2*z + x*z**2).
+    The a_24 parameter is equal to (a + 2)/4.
+
+    References
+    ==========
+
+    .. [1] Kris Gaj, Soonhak Kwon, Patrick Baier, Paul Kohlbrenner, Hoang Le, Mohammed Khaleeluddin, Ramakrishna Bachimanchi,
+           Implementing the Elliptic Curve Method of Factoring in Reconfigurable Hardware,
+           Cryptographic Hardware and Embedded Systems - CHES 2006 (2006), pp. 119-133,
+           https://doi.org/10.1007/11894063_10
+           https://www.hyperelliptic.org/tanja/SHARCS/talks06/Gaj.pdf
+
+    """
+
+    def __init__(self, x_cord, z_cord, a_24, mod):
+        """
+        Initial parameters for the Point class.
+
+        Parameters
+        ==========
+
+        x_cord : X coordinate of the Point
+        z_cord : Z coordinate of the Point
+        a_24 : Parameter of the elliptic curve in Montgomery form
+        mod : modulus
+        """
+        self.x_cord = x_cord
+        self.z_cord = z_cord
+        self.a_24 = a_24
+        self.mod = mod
+
+    def __eq__(self, other):
+        """Two points are equal if X/Z of both points are equal
+        """
+        if self.a_24 != other.a_24 or self.mod != other.mod:
+            return False
+        return self.x_cord * other.z_cord % self.mod ==\
+            other.x_cord * self.z_cord % self.mod
+
+    def add(self, Q, diff):
+        """
+        Add two points self and Q where diff = self - Q. Moreover the assumption
+        is self.x_cord*Q.x_cord*(self.x_cord - Q.x_cord) != 0. This algorithm
+        requires 6 multiplications. Here the difference between the points
+        is already known and using this algorithm speeds up the addition
+        by reducing the number of multiplication required. Also in the
+        mont_ladder algorithm is constructed in a way so that the difference
+        between intermediate points is always equal to the initial point.
+        So, we always know what the difference between the point is.
+
+
+        Parameters
+        ==========
+
+        Q : point on the curve in Montgomery form
+        diff : self - Q
+
+        Examples
+        ========
+
+        >>> from sympy.ntheory.ecm import Point
+        >>> p1 = Point(11, 16, 7, 29)
+        >>> p2 = Point(13, 10, 7, 29)
+        >>> p3 = p2.add(p1, p1)
+        >>> p3.x_cord
+        23
+        >>> p3.z_cord
+        17
+        """
+        u = (self.x_cord - self.z_cord)*(Q.x_cord + Q.z_cord)
+        v = (self.x_cord + self.z_cord)*(Q.x_cord - Q.z_cord)
+        add, subt = u + v, u - v
+        x_cord = diff.z_cord * add * add % self.mod
+        z_cord = diff.x_cord * subt * subt % self.mod
+        return Point(x_cord, z_cord, self.a_24, self.mod)
+
+    def double(self):
+        """
+        Doubles a point in an elliptic curve in Montgomery form.
+        This algorithm requires 5 multiplications.
+
+        Examples
+        ========
+
+        >>> from sympy.ntheory.ecm import Point
+        >>> p1 = Point(11, 16, 7, 29)
+        >>> p2 = p1.double()
+        >>> p2.x_cord
+        13
+        >>> p2.z_cord
+        10
+        """
+        u = pow(self.x_cord + self.z_cord, 2, self.mod)
+        v = pow(self.x_cord - self.z_cord, 2, self.mod)
+        diff = u - v
+        x_cord = u*v % self.mod
+        z_cord = diff*(v + self.a_24*diff) % self.mod
+        return Point(x_cord, z_cord, self.a_24, self.mod)
+
+    def mont_ladder(self, k):
+        """
+        Scalar multiplication of a point in Montgomery form
+        using Montgomery Ladder Algorithm.
+        A total of 11 multiplications are required in each step of this
+        algorithm.
+
+        Parameters
+        ==========
+
+        k : The positive integer multiplier
+
+        Examples
+        ========
+
+        >>> from sympy.ntheory.ecm import Point
+        >>> p1 = Point(11, 16, 7, 29)
+        >>> p3 = p1.mont_ladder(3)
+        >>> p3.x_cord
+        23
+        >>> p3.z_cord
+        17
+        """
+        Q = self
+        R = self.double()
+        for i in bin(k)[3:]:
+            if  i  == '1':
+                Q = R.add(Q, self)
+                R = R.double()
+            else:
+                R = Q.add(R, self)
+                Q = Q.double()
+        return Q
+
+
+def _ecm_one_factor(n, B1=10000, B2=100000, max_curve=200, seed=None):
+    """Returns one factor of n using
+    Lenstra's 2 Stage Elliptic curve Factorization
+    with Suyama's Parameterization. Here Montgomery
+    arithmetic is used for fast computation of addition
+    and doubling of points in elliptic curve.
+
+    Explanation
+    ===========
+
+    This ECM method considers elliptic curves in Montgomery
+    form (E : b*y**2*z = x**3 + a*x**2*z + x*z**2) and involves
+    elliptic curve operations (mod N), where the elements in
+    Z are reduced (mod N). Since N is not a prime, E over FF(N)
+    is not really an elliptic curve but we can still do point additions
+    and doubling as if FF(N) was a field.
+
+    Stage 1 : The basic algorithm involves taking a random point (P) on an
+    elliptic curve in FF(N). The compute k*P using Montgomery ladder algorithm.
+    Let q be an unknown factor of N. Then the order of the curve E, |E(FF(q))|,
+    might be a smooth number that divides k. Then we have k = l * |E(FF(q))|
+    for some l. For any point belonging to the curve E, |E(FF(q))|*P = O,
+    hence k*P = l*|E(FF(q))|*P. Thus kP.z_cord = 0 (mod q), and the unknownn
+    factor of N (q) can be recovered by taking gcd(kP.z_cord, N).
+
+    Stage 2 : This is a continuation of Stage 1 if k*P != O. The idea utilize
+    the fact that even if kP != 0, the value of k might miss just one large
+    prime divisor of |E(FF(q))|. In this case we only need to compute the
+    scalar multiplication by p to get p*k*P = O. Here a second bound B2
+    restrict the size of possible values of p.
+
+    Parameters
+    ==========
+
+    n : Number to be Factored. Assume that it is a composite number.
+    B1 : Stage 1 Bound. Must be an even number.
+    B2 : Stage 2 Bound. Must be an even number.
+    max_curve : Maximum number of curves generated
+
+    Returns
+    =======
+
+    integer | None : a non-trivial divisor of ``n``. ``None`` if not found
+
+    References
+    ==========
+
+    .. [1] Carl Pomerance, Richard Crandall, Prime Numbers: A Computational Perspective,
+           2nd Edition (2005), page 344, ISBN:978-0387252827
+    """
+    randint = _randint(seed)
+
+    # When calculating T, if (B1 - 2*D) is negative, it cannot be calculated.
+    D = min(sqrt(B2), B1 // 2 - 1)
+    sieve.extend(D)
+    beta = [0] * D
+    S = [0] * D
+    k = 1
+    for p in primerange(2, B1 + 1):
+        k *= pow(p, int(log(B1, p)))
+
+    # Pre-calculate the prime numbers to be used in stage 2.
+    # Using the fact that the x-coordinates of point P and its
+    # inverse -P coincide, the number of primes to be checked
+    # in stage 2 can be reduced.
+    deltas_list = []
+    for r in range(B1 + 2*D, B2 + 2*D, 4*D):
+        # d in deltas iff r+(2d+1) and/or r-(2d+1) is prime
+        deltas = {abs(q - r) >> 1 for q in primerange(r - 2*D, r + 2*D)}
+        deltas_list.append(list(deltas))
+
+    for _ in range(max_curve):
+        #Suyama's Parametrization
+        sigma = randint(6, n - 1)
+        u = (sigma**2 - 5) % n
+        v = (4*sigma) % n
+        u_3 = pow(u, 3, n)
+
+        try:
+            # We use the elliptic curve y**2 = x**3 + a*x**2 + x
+            # where a = pow(v - u, 3, n)*(3*u + v)*invert(4*u_3*v, n) - 2
+            # However, we do not declare a because it is more convenient
+            # to use a24 = (a + 2)*invert(4, n) in the calculation.
+            a24 = pow(v - u, 3, n)*(3*u + v)*invert(16*u_3*v, n) % n
+        except ZeroDivisionError:
+            #If the invert(16*u_3*v, n) doesn't exist (i.e., g != 1)
+            g = gcd(2*u_3*v, n)
+            #If g = n, try another curve
+            if g == n:
+                continue
+            return g
+
+        Q = Point(u_3, pow(v, 3, n), a24, n)
+        Q = Q.mont_ladder(k)
+        g = gcd(Q.z_cord, n)
+
+        #Stage 1 factor
+        if g != 1 and g != n:
+            return g
+        #Stage 1 failure. Q.z = 0, Try another curve
+        elif g == n:
+            continue
+
+        #Stage 2 - Improved Standard Continuation
+        S[0] = Q
+        Q2 = Q.double()
+        S[1] = Q2.add(Q, Q)
+        beta[0] = (S[0].x_cord*S[0].z_cord) % n
+        beta[1] = (S[1].x_cord*S[1].z_cord) % n
+        for d in range(2, D):
+            S[d] = S[d - 1].add(Q2, S[d - 2])
+            beta[d] = (S[d].x_cord*S[d].z_cord) % n
+        # i.e., S[i] = Q.mont_ladder(2*i + 1)
+
+        g = 1
+        W = Q.mont_ladder(4*D)
+        T = Q.mont_ladder(B1 - 2*D)
+        R = Q.mont_ladder(B1 + 2*D)
+        for deltas in deltas_list:
+            # R = Q.mont_ladder(r) where r in range(B1 + 2*D, B2 + 2*D, 4*D)
+            alpha = (R.x_cord*R.z_cord) % n
+            for delta in deltas:
+                # We want to calculate
+                # f = R.x_cord * S[delta].z_cord - S[delta].x_cord * R.z_cord
+                f = (R.x_cord - S[delta].x_cord)*\
+                    (R.z_cord + S[delta].z_cord) - alpha + beta[delta]
+                g = (g*f) % n
+            T, R = R, R.add(W, T)
+        g = gcd(n, g)
+
+        #Stage 2 Factor found
+        if g != 1 and g != n:
+            return g
+
+
+def ecm(n, B1=10000, B2=100000, max_curve=200, seed=1234):
+    """Performs factorization using Lenstra's Elliptic curve method.
+
+    This function repeatedly calls ``_ecm_one_factor`` to compute the factors
+    of n. First all the small factors are taken out using trial division.
+    Then ``_ecm_one_factor`` is used to compute one factor at a time.
+
+    Parameters
+    ==========
+
+    n : Number to be Factored
+    B1 : Stage 1 Bound. Must be an even number.
+    B2 : Stage 2 Bound. Must be an even number.
+    max_curve : Maximum number of curves generated
+    seed : Initialize pseudorandom generator
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory import ecm
+    >>> ecm(25645121643901801)
+    {5394769, 4753701529}
+    >>> ecm(9804659461513846513)
+    {4641991, 2112166839943}
+    """
+    from .factor_ import _perfect_power
+    n = as_int(n)
+    if B1 % 2 != 0 or B2 % 2 != 0:
+        raise ValueError("both bounds must be even")
+    TF_LIMIT = 100000
+    factors = set()
+    for prime in sieve.primerange(2, TF_LIMIT):
+        if n % prime == 0:
+            factors.add(prime)
+            while(n % prime == 0):
+                n //= prime
+
+    queue = []
+    def check(m):
+        if isprime(m):
+            factors.add(m)
+            return
+        if result := _perfect_power(m, TF_LIMIT):
+            return check(result[0])
+        queue.append(m)
+    check(n)
+    while queue:
+        n = queue.pop()
+        factor = _ecm_one_factor(n, B1, B2, max_curve, seed)
+        if factor is None:
+            raise ValueError("Increase the bounds")
+        check(factor)
+        check(n // factor)
+    return factors
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/egyptian_fraction.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/egyptian_fraction.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a42540b372042f596808684fef8e3fc57935b74
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/egyptian_fraction.py
@@ -0,0 +1,223 @@
+from sympy.core.containers import Tuple
+from sympy.core.numbers import (Integer, Rational)
+from sympy.core.singleton import S
+import sympy.polys
+
+from math import gcd
+
+
+def egyptian_fraction(r, algorithm="Greedy"):
+    """
+    Return the list of denominators of an Egyptian fraction
+    expansion [1]_ of the said rational `r`.
+
+    Parameters
+    ==========
+
+    r : Rational or (p, q)
+        a positive rational number, ``p/q``.
+    algorithm : { "Greedy", "Graham Jewett", "Takenouchi", "Golomb" }, optional
+        Denotes the algorithm to be used (the default is "Greedy").
+
+    Examples
+    ========
+
+    >>> from sympy import Rational
+    >>> from sympy.ntheory.egyptian_fraction import egyptian_fraction
+    >>> egyptian_fraction(Rational(3, 7))
+    [3, 11, 231]
+    >>> egyptian_fraction((3, 7), "Graham Jewett")
+    [7, 8, 9, 56, 57, 72, 3192]
+    >>> egyptian_fraction((3, 7), "Takenouchi")
+    [4, 7, 28]
+    >>> egyptian_fraction((3, 7), "Golomb")
+    [3, 15, 35]
+    >>> egyptian_fraction((11, 5), "Golomb")
+    [1, 2, 3, 4, 9, 234, 1118, 2580]
+
+    See Also
+    ========
+
+    sympy.core.numbers.Rational
+
+    Notes
+    =====
+
+    Currently the following algorithms are supported:
+
+    1) Greedy Algorithm
+
+       Also called the Fibonacci-Sylvester algorithm [2]_.
+       At each step, extract the largest unit fraction less
+       than the target and replace the target with the remainder.
+
+       It has some distinct properties:
+
+       a) Given `p/q` in lowest terms, generates an expansion of maximum
+          length `p`. Even as the numerators get large, the number of
+          terms is seldom more than a handful.
+
+       b) Uses minimal memory.
+
+       c) The terms can blow up (standard examples of this are 5/121 and
+          31/311).  The denominator is at most squared at each step
+          (doubly-exponential growth) and typically exhibits
+          singly-exponential growth.
+
+    2) Graham Jewett Algorithm
+
+       The algorithm suggested by the result of Graham and Jewett.
+       Note that this has a tendency to blow up: the length of the
+       resulting expansion is always ``2**(x/gcd(x, y)) - 1``.  See [3]_.
+
+    3) Takenouchi Algorithm
+
+       The algorithm suggested by Takenouchi (1921).
+       Differs from the Graham-Jewett algorithm only in the handling
+       of duplicates.  See [3]_.
+
+    4) Golomb's Algorithm
+
+       A method given by Golumb (1962), using modular arithmetic and
+       inverses.  It yields the same results as a method using continued
+       fractions proposed by Bleicher (1972).  See [4]_.
+
+    If the given rational is greater than or equal to 1, a greedy algorithm
+    of summing the harmonic sequence 1/1 + 1/2 + 1/3 + ... is used, taking
+    all the unit fractions of this sequence until adding one more would be
+    greater than the given number.  This list of denominators is prefixed
+    to the result from the requested algorithm used on the remainder.  For
+    example, if r is 8/3, using the Greedy algorithm, we get [1, 2, 3, 4,
+    5, 6, 7, 14, 420], where the beginning of the sequence, [1, 2, 3, 4, 5,
+    6, 7] is part of the harmonic sequence summing to 363/140, leaving a
+    remainder of 31/420, which yields [14, 420] by the Greedy algorithm.
+    The result of egyptian_fraction(Rational(8, 3), "Golomb") is [1, 2, 3,
+    4, 5, 6, 7, 14, 574, 2788, 6460, 11590, 33062, 113820], and so on.
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Egyptian_fraction
+    .. [2] https://en.wikipedia.org/wiki/Greedy_algorithm_for_Egyptian_fractions
+    .. [3] https://www.ics.uci.edu/~eppstein/numth/egypt/conflict.html
+    .. [4] https://web.archive.org/web/20180413004012/https://ami.ektf.hu/uploads/papers/finalpdf/AMI_42_from129to134.pdf
+
+    """
+
+    if not isinstance(r, Rational):
+        if isinstance(r, (Tuple, tuple)) and len(r) == 2:
+            r = Rational(*r)
+        else:
+            raise ValueError("Value must be a Rational or tuple of ints")
+    if r <= 0:
+        raise ValueError("Value must be positive")
+
+    # common cases that all methods agree on
+    x, y = r.as_numer_denom()
+    if y == 1 and x == 2:
+        return [Integer(i) for i in [1, 2, 3, 6]]
+    if x == y + 1:
+        return [S.One, y]
+
+    prefix, rem = egypt_harmonic(r)
+    if rem == 0:
+        return prefix
+    # work in Python ints
+    x, y = rem.p, rem.q
+    # assert x < y and gcd(x, y) = 1
+
+    if algorithm == "Greedy":
+        postfix = egypt_greedy(x, y)
+    elif algorithm == "Graham Jewett":
+        postfix = egypt_graham_jewett(x, y)
+    elif algorithm == "Takenouchi":
+        postfix = egypt_takenouchi(x, y)
+    elif algorithm == "Golomb":
+        postfix = egypt_golomb(x, y)
+    else:
+        raise ValueError("Entered invalid algorithm")
+    return prefix + [Integer(i) for i in postfix]
+
+
+def egypt_greedy(x, y):
+    # assumes gcd(x, y) == 1
+    if x == 1:
+        return [y]
+    else:
+        a = (-y) % x
+        b = y*(y//x + 1)
+        c = gcd(a, b)
+        if c > 1:
+            num, denom = a//c, b//c
+        else:
+            num, denom = a, b
+        return [y//x + 1] + egypt_greedy(num, denom)
+
+
+def egypt_graham_jewett(x, y):
+    # assumes gcd(x, y) == 1
+    l = [y] * x
+
+    # l is now a list of integers whose reciprocals sum to x/y.
+    # we shall now proceed to manipulate the elements of l without
+    # changing the reciprocated sum until all elements are unique.
+
+    while len(l) != len(set(l)):
+        l.sort()  # so the list has duplicates. find a smallest pair
+        for i in range(len(l) - 1):
+            if l[i] == l[i + 1]:
+                break
+        # we have now identified a pair of identical
+        # elements: l[i] and l[i + 1].
+        # now comes the application of the result of graham and jewett:
+        l[i + 1] = l[i] + 1
+        # and we just iterate that until the list has no duplicates.
+        l.append(l[i]*(l[i] + 1))
+    return sorted(l)
+
+
+def egypt_takenouchi(x, y):
+    # assumes gcd(x, y) == 1
+    # special cases for 3/y
+    if x == 3:
+        if y % 2 == 0:
+            return [y//2, y]
+        i = (y - 1)//2
+        j = i + 1
+        k = j + i
+        return [j, k, j*k]
+    l = [y] * x
+    while len(l) != len(set(l)):
+        l.sort()
+        for i in range(len(l) - 1):
+            if l[i] == l[i + 1]:
+                break
+        k = l[i]
+        if k % 2 == 0:
+            l[i] = l[i] // 2
+            del l[i + 1]
+        else:
+            l[i], l[i + 1] = (k + 1)//2, k*(k + 1)//2
+    return sorted(l)
+
+
+def egypt_golomb(x, y):
+    # assumes x < y and gcd(x, y) == 1
+    if x == 1:
+        return [y]
+    xp = sympy.polys.ZZ.invert(int(x), int(y))
+    rv = [xp*y]
+    rv.extend(egypt_golomb((x*xp - 1)//y, xp))
+    return sorted(rv)
+
+
+def egypt_harmonic(r):
+    # assumes r is Rational
+    rv = []
+    d = S.One
+    acc = S.Zero
+    while acc + 1/d <= r:
+        acc += 1/d
+        rv.append(d)
+        d += 1
+    return (rv, r - acc)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/elliptic_curve.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/elliptic_curve.py
new file mode 100644
index 0000000000000000000000000000000000000000..c969470a6c19a3d17e637529b6615eeba326e84a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/elliptic_curve.py
@@ -0,0 +1,397 @@
+from sympy.core.numbers import oo
+from sympy.core.symbol import symbols
+from sympy.polys.domains import FiniteField, QQ, RationalField, FF
+from sympy.polys.polytools import Poly
+from sympy.solvers.solvers import solve
+from sympy.utilities.iterables import is_sequence
+from sympy.utilities.misc import as_int
+from .factor_ import divisors
+from .residue_ntheory import polynomial_congruence
+
+
+class EllipticCurve:
+    """
+    Create the following Elliptic Curve over domain.
+
+    `y^{2} + a_{1} x y + a_{3} y = x^{3} + a_{2} x^{2} + a_{4} x + a_{6}`
+
+    The default domain is ``QQ``. If no coefficient ``a1``, ``a2``, ``a3``,
+    is given then it creates a curve with the following form:
+
+    `y^{2} = x^{3} + a_{4} x + a_{6}`
+
+    Examples
+    ========
+
+    References
+    ==========
+
+    .. [1] J. Silverman "A Friendly Introduction to Number Theory" Third Edition
+    .. [2] https://mathworld.wolfram.com/EllipticDiscriminant.html
+    .. [3] G. Hardy, E. Wright "An Introduction to the Theory of Numbers" Sixth Edition
+
+    """
+
+    def __init__(self, a4, a6, a1=0, a2=0, a3=0, modulus=0):
+        if modulus == 0:
+            domain = QQ
+        else:
+            domain = FF(modulus)
+        a1, a2, a3, a4, a6 = map(domain.convert, (a1, a2, a3, a4, a6))
+        self._domain = domain
+        self.modulus = modulus
+        # Calculate discriminant
+        b2 = a1**2 + 4 * a2
+        b4 = 2 * a4 + a1 * a3
+        b6 = a3**2 + 4 * a6
+        b8 = a1**2 * a6 + 4 * a2 * a6 - a1 * a3 * a4 + a2 * a3**2 - a4**2
+        self._b2, self._b4, self._b6, self._b8 = b2, b4, b6, b8
+        self._discrim = -b2**2 * b8 - 8 * b4**3 - 27 * b6**2 + 9 * b2 * b4 * b6
+        self._a1 = a1
+        self._a2 = a2
+        self._a3 = a3
+        self._a4 = a4
+        self._a6 = a6
+        x, y, z = symbols('x y z')
+        self.x, self.y, self.z = x, y, z
+        self._poly = Poly(y**2*z + a1*x*y*z + a3*y*z**2 - x**3 - a2*x**2*z - a4*x*z**2 - a6*z**3, domain=domain)
+        if isinstance(self._domain, FiniteField):
+            self._rank = 0
+        elif isinstance(self._domain, RationalField):
+            self._rank = None
+
+    def __call__(self, x, y, z=1):
+        return EllipticCurvePoint(x, y, z, self)
+
+    def __contains__(self, point):
+        if is_sequence(point):
+            if len(point) == 2:
+                z1 = 1
+            else:
+                z1 = point[2]
+            x1, y1 = point[:2]
+        elif isinstance(point, EllipticCurvePoint):
+            x1, y1, z1 = point.x, point.y, point.z
+        else:
+            raise ValueError('Invalid point.')
+        if self.characteristic == 0 and z1 == 0:
+            return True
+        return self._poly.subs({self.x: x1, self.y: y1, self.z: z1}) == 0
+
+    def __repr__(self):
+        return self._poly.__repr__()
+
+    def minimal(self):
+        """
+        Return minimal Weierstrass equation.
+
+        Examples
+        ========
+
+        >>> from sympy.ntheory.elliptic_curve import EllipticCurve
+
+        >>> e1 = EllipticCurve(-10, -20, 0, -1, 1)
+        >>> e1.minimal()
+        Poly(-x**3 + 13392*x*z**2 + y**2*z + 1080432*z**3, x, y, z, domain='QQ')
+
+        """
+        char = self.characteristic
+        if char == 2:
+            return self
+        if char == 3:
+            return EllipticCurve(self._b4/2, self._b6/4, a2=self._b2/4, modulus=self.modulus)
+        c4 = self._b2**2 - 24*self._b4
+        c6 = -self._b2**3 + 36*self._b2*self._b4 - 216*self._b6
+        return EllipticCurve(-27*c4, -54*c6, modulus=self.modulus)
+
+    def points(self):
+        """
+        Return points of curve over Finite Field.
+
+        Examples
+        ========
+
+        >>> from sympy.ntheory.elliptic_curve import EllipticCurve
+        >>> e2 = EllipticCurve(1, 1, 1, 1, 1, modulus=5)
+        >>> e2.points()
+        {(0, 2), (1, 4), (2, 0), (2, 2), (3, 0), (3, 1), (4, 0)}
+
+        """
+
+        char = self.characteristic
+        all_pt = set()
+        if char >= 1:
+            for i in range(char):
+                congruence_eq = self._poly.subs({self.x: i, self.z: 1}).expr
+                sol = polynomial_congruence(congruence_eq, char)
+                all_pt.update((i, num) for num in sol)
+            return all_pt
+        else:
+            raise ValueError("Infinitely many points")
+
+    def points_x(self, x):
+        """Returns points on the curve for the given x-coordinate."""
+        pt = []
+        if self._domain == QQ:
+            for y in solve(self._poly.subs(self.x, x)):
+                pt.append((x, y))
+        else:
+            congruence_eq = self._poly.subs({self.x: x, self.z: 1}).expr
+            for y in polynomial_congruence(congruence_eq, self.characteristic):
+                pt.append((x, y))
+        return pt
+
+    def torsion_points(self):
+        """
+        Return torsion points of curve over Rational number.
+
+        Return point objects those are finite order.
+        According to Nagell-Lutz theorem, torsion point p(x, y)
+        x and y are integers, either y = 0 or y**2 is divisor
+        of discriminent. According to Mazur's theorem, there are
+        at most 15 points in torsion collection.
+
+        Examples
+        ========
+
+        >>> from sympy.ntheory.elliptic_curve import EllipticCurve
+        >>> e2 = EllipticCurve(-43, 166)
+        >>> sorted(e2.torsion_points())
+        [(-5, -16), (-5, 16), O, (3, -8), (3, 8), (11, -32), (11, 32)]
+
+        """
+        if self.characteristic > 0:
+            raise ValueError("No torsion point for Finite Field.")
+        l = [EllipticCurvePoint.point_at_infinity(self)]
+        for xx in solve(self._poly.subs({self.y: 0, self.z: 1})):
+            if xx.is_rational:
+                l.append(self(xx, 0))
+        for i in divisors(self.discriminant, generator=True):
+            j = int(i**.5)
+            if j**2 == i:
+                for xx in solve(self._poly.subs({self.y: j, self.z: 1})):
+                    if not xx.is_rational:
+                        continue
+                    p = self(xx, j)
+                    if p.order() != oo:
+                        l.extend([p, -p])
+        return l
+
+    @property
+    def characteristic(self):
+        """
+        Return domain characteristic.
+
+        Examples
+        ========
+
+        >>> from sympy.ntheory.elliptic_curve import EllipticCurve
+        >>> e2 = EllipticCurve(-43, 166)
+        >>> e2.characteristic
+        0
+
+        """
+        return self._domain.characteristic()
+
+    @property
+    def discriminant(self):
+        """
+        Return curve discriminant.
+
+        Examples
+        ========
+
+        >>> from sympy.ntheory.elliptic_curve import EllipticCurve
+        >>> e2 = EllipticCurve(0, 17)
+        >>> e2.discriminant
+        -124848
+
+        """
+        return int(self._discrim)
+
+    @property
+    def is_singular(self):
+        """
+        Return True if curve discriminant is equal to zero.
+        """
+        return self.discriminant == 0
+
+    @property
+    def j_invariant(self):
+        """
+        Return curve j-invariant.
+
+        Examples
+        ========
+
+        >>> from sympy.ntheory.elliptic_curve import EllipticCurve
+        >>> e1 = EllipticCurve(-2, 0, 0, 1, 1)
+        >>> e1.j_invariant
+        1404928/389
+
+        """
+        c4 = self._b2**2 - 24*self._b4
+        return self._domain.to_sympy(c4**3 / self._discrim)
+
+    @property
+    def order(self):
+        """
+        Number of points in Finite field.
+
+        Examples
+        ========
+
+        >>> from sympy.ntheory.elliptic_curve import EllipticCurve
+        >>> e2 = EllipticCurve(1, 0, modulus=19)
+        >>> e2.order
+        19
+
+        """
+        if self.characteristic == 0:
+            raise NotImplementedError("Still not implemented")
+        return len(self.points())
+
+    @property
+    def rank(self):
+        """
+        Number of independent points of infinite order.
+
+        For Finite field, it must be 0.
+        """
+        if self._rank is not None:
+            return self._rank
+        raise NotImplementedError("Still not implemented")
+
+
+class EllipticCurvePoint:
+    """
+    Point of Elliptic Curve
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.elliptic_curve import EllipticCurve
+    >>> e1 = EllipticCurve(-17, 16)
+    >>> p1 = e1(0, -4, 1)
+    >>> p2 = e1(1, 0)
+    >>> p1 + p2
+    (15, -56)
+    >>> e3 = EllipticCurve(-1, 9)
+    >>> e3(1, -3) * 3
+    (664/169, 17811/2197)
+    >>> (e3(1, -3) * 3).order()
+    oo
+    >>> e2 = EllipticCurve(-2, 0, 0, 1, 1)
+    >>> p = e2(-1,1)
+    >>> q = e2(0, -1)
+    >>> p+q
+    (4, 8)
+    >>> p-q
+    (1, 0)
+    >>> 3*p-5*q
+    (328/361, -2800/6859)
+    """
+
+    @staticmethod
+    def point_at_infinity(curve):
+        return EllipticCurvePoint(0, 1, 0, curve)
+
+    def __init__(self, x, y, z, curve):
+        dom = curve._domain.convert
+        self.x = dom(x)
+        self.y = dom(y)
+        self.z = dom(z)
+        self._curve = curve
+        self._domain = self._curve._domain
+        if not self._curve.__contains__(self):
+            raise ValueError("The curve does not contain this point")
+
+    def __add__(self, p):
+        if self.z == 0:
+            return p
+        if p.z == 0:
+            return self
+        x1, y1 = self.x/self.z, self.y/self.z
+        x2, y2 = p.x/p.z, p.y/p.z
+        a1 = self._curve._a1
+        a2 = self._curve._a2
+        a3 = self._curve._a3
+        a4 = self._curve._a4
+        a6 = self._curve._a6
+        if x1 != x2:
+            slope = (y1 - y2) / (x1 - x2)
+            yint = (y1 * x2 - y2 * x1) / (x2 - x1)
+        else:
+            if (y1 + y2) == 0:
+                return self.point_at_infinity(self._curve)
+            slope = (3 * x1**2 + 2*a2*x1 + a4 - a1*y1) / (a1 * x1 + a3 + 2 * y1)
+            yint = (-x1**3 + a4*x1 + 2*a6 - a3*y1) / (a1*x1 + a3 + 2*y1)
+        x3 = slope**2 + a1*slope - a2 - x1 - x2
+        y3 = -(slope + a1) * x3 - yint - a3
+        return self._curve(x3, y3, 1)
+
+    def __lt__(self, other):
+        return (self.x, self.y, self.z) < (other.x, other.y, other.z)
+
+    def __mul__(self, n):
+        n = as_int(n)
+        r = self.point_at_infinity(self._curve)
+        if n == 0:
+            return r
+        if n < 0:
+            return -self * -n
+        p = self
+        while n:
+            if n & 1:
+                r = r + p
+            n >>= 1
+            p = p + p
+        return r
+
+    def __rmul__(self, n):
+        return self * n
+
+    def __neg__(self):
+        return EllipticCurvePoint(self.x, -self.y - self._curve._a1*self.x - self._curve._a3, self.z, self._curve)
+
+    def __repr__(self):
+        if self.z == 0:
+            return 'O'
+        dom = self._curve._domain
+        try:
+            return '({}, {})'.format(dom.to_sympy(self.x), dom.to_sympy(self.y))
+        except TypeError:
+            pass
+        return '({}, {})'.format(self.x, self.y)
+
+    def __sub__(self, other):
+        return self.__add__(-other)
+
+    def order(self):
+        """
+        Return point order n where nP = 0.
+
+        """
+        if self.z == 0:
+            return 1
+        if self.y == 0:  # P = -P
+            return 2
+        p = self * 2
+        if p.y == -self.y:  # 2P = -P
+            return 3
+        i = 2
+        if self._domain != QQ:
+            while int(p.x) == p.x and int(p.y) == p.y:
+                p = self + p
+                i += 1
+                if p.z == 0:
+                    return i
+            return oo
+        while p.x.numerator == p.x and p.y.numerator == p.y:
+            p = self + p
+            i += 1
+            if i > 12:
+                return oo
+            if p.z == 0:
+                return i
+        return oo
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/factor_.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/factor_.py
new file mode 100644
index 0000000000000000000000000000000000000000..2dc6ac81c237f000e55014f5e170b27b41335786
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/factor_.py
@@ -0,0 +1,2841 @@
+"""
+Integer factorization
+"""
+from __future__ import annotations
+
+from bisect import bisect_left
+from collections import defaultdict, OrderedDict
+from collections.abc import MutableMapping
+import math
+
+from sympy.core.containers import Dict
+from sympy.core.mul import Mul
+from sympy.core.numbers import Rational, Integer
+from sympy.core.intfunc import num_digits
+from sympy.core.power import Pow
+from sympy.core.random import _randint
+from sympy.core.singleton import S
+from sympy.external.gmpy import (SYMPY_INTS, gcd, sqrt as isqrt,
+                                 sqrtrem, iroot, bit_scan1, remove)
+from .primetest import isprime, MERSENNE_PRIME_EXPONENTS, is_mersenne_prime
+from .generate import sieve, primerange, nextprime
+from .digits import digits
+from sympy.utilities.decorator import deprecated
+from sympy.utilities.iterables import flatten
+from sympy.utilities.misc import as_int, filldedent
+from .ecm import _ecm_one_factor
+
+
+def smoothness(n):
+    """
+    Return the B-smooth and B-power smooth values of n.
+
+    The smoothness of n is the largest prime factor of n; the power-
+    smoothness is the largest divisor raised to its multiplicity.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.factor_ import smoothness
+    >>> smoothness(2**7*3**2)
+    (3, 128)
+    >>> smoothness(2**4*13)
+    (13, 16)
+    >>> smoothness(2)
+    (2, 2)
+
+    See Also
+    ========
+
+    factorint, smoothness_p
+    """
+
+    if n == 1:
+        return (1, 1)  # not prime, but otherwise this causes headaches
+    facs = factorint(n)
+    return max(facs), max(m**facs[m] for m in facs)
+
+
+def smoothness_p(n, m=-1, power=0, visual=None):
+    """
+    Return a list of [m, (p, (M, sm(p + m), psm(p + m)))...]
+    where:
+
+    1. p**M is the base-p divisor of n
+    2. sm(p + m) is the smoothness of p + m (m = -1 by default)
+    3. psm(p + m) is the power smoothness of p + m
+
+    The list is sorted according to smoothness (default) or by power smoothness
+    if power=1.
+
+    The smoothness of the numbers to the left (m = -1) or right (m = 1) of a
+    factor govern the results that are obtained from the p +/- 1 type factoring
+    methods.
+
+        >>> from sympy.ntheory.factor_ import smoothness_p, factorint
+        >>> smoothness_p(10431, m=1)
+        (1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))])
+        >>> smoothness_p(10431)
+        (-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))])
+        >>> smoothness_p(10431, power=1)
+        (-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))])
+
+    If visual=True then an annotated string will be returned:
+
+        >>> print(smoothness_p(21477639576571, visual=1))
+        p**i=4410317**1 has p-1 B=1787, B-pow=1787
+        p**i=4869863**1 has p-1 B=2434931, B-pow=2434931
+
+    This string can also be generated directly from a factorization dictionary
+    and vice versa:
+
+        >>> factorint(17*9)
+        {3: 2, 17: 1}
+        >>> smoothness_p(_)
+        'p**i=3**2 has p-1 B=2, B-pow=2\\np**i=17**1 has p-1 B=2, B-pow=16'
+        >>> smoothness_p(_)
+        {3: 2, 17: 1}
+
+    The table of the output logic is:
+
+        ====== ====== ======= =======
+        |              Visual
+        ------ ----------------------
+        Input  True   False   other
+        ====== ====== ======= =======
+        dict    str    tuple   str
+        str     str    tuple   dict
+        tuple   str    tuple   str
+        n       str    tuple   tuple
+        mul     str    tuple   tuple
+        ====== ====== ======= =======
+
+    See Also
+    ========
+
+    factorint, smoothness
+    """
+
+    # visual must be True, False or other (stored as None)
+    if visual in (1, 0):
+        visual = bool(visual)
+    elif visual not in (True, False):
+        visual = None
+
+    if isinstance(n, str):
+        if visual:
+            return n
+        d = {}
+        for li in n.splitlines():
+            k, v = [int(i) for i in
+                    li.split('has')[0].split('=')[1].split('**')]
+            d[k] = v
+        if visual is not True and visual is not False:
+            return d
+        return smoothness_p(d, visual=False)
+    elif not isinstance(n, tuple):
+        facs = factorint(n, visual=False)
+
+    if power:
+        k = -1
+    else:
+        k = 1
+    if isinstance(n, tuple):
+        rv = n
+    else:
+        rv = (m, sorted([(f,
+                          tuple([M] + list(smoothness(f + m))))
+                         for f, M in list(facs.items())],
+                        key=lambda x: (x[1][k], x[0])))
+
+    if visual is False or (visual is not True) and (type(n) in [int, Mul]):
+        return rv
+    lines = []
+    for dat in rv[1]:
+        dat = flatten(dat)
+        dat.insert(2, m)
+        lines.append('p**i=%i**%i has p%+i B=%i, B-pow=%i' % tuple(dat))
+    return '\n'.join(lines)
+
+
+def multiplicity(p, n):
+    """
+    Find the greatest integer m such that p**m divides n.
+
+    Examples
+    ========
+
+    >>> from sympy import multiplicity, Rational
+    >>> [multiplicity(5, n) for n in [8, 5, 25, 125, 250]]
+    [0, 1, 2, 3, 3]
+    >>> multiplicity(3, Rational(1, 9))
+    -2
+
+    Note: when checking for the multiplicity of a number in a
+    large factorial it is most efficient to send it as an unevaluated
+    factorial or to call ``multiplicity_in_factorial`` directly:
+
+    >>> from sympy.ntheory import multiplicity_in_factorial
+    >>> from sympy import factorial
+    >>> p = factorial(25)
+    >>> n = 2**100
+    >>> nfac = factorial(n, evaluate=False)
+    >>> multiplicity(p, nfac)
+    52818775009509558395695966887
+    >>> _ == multiplicity_in_factorial(p, n)
+    True
+
+    See Also
+    ========
+
+    trailing
+
+    """
+    try:
+        p, n = as_int(p), as_int(n)
+    except ValueError:
+        from sympy.functions.combinatorial.factorials import factorial
+        if all(isinstance(i, (SYMPY_INTS, Rational)) for i in (p, n)):
+            p = Rational(p)
+            n = Rational(n)
+            if p.q == 1:
+                if n.p == 1:
+                    return -multiplicity(p.p, n.q)
+                return multiplicity(p.p, n.p) - multiplicity(p.p, n.q)
+            elif p.p == 1:
+                return multiplicity(p.q, n.q)
+            else:
+                like = min(
+                    multiplicity(p.p, n.p),
+                    multiplicity(p.q, n.q))
+                cross = min(
+                    multiplicity(p.q, n.p),
+                    multiplicity(p.p, n.q))
+                return like - cross
+        elif (isinstance(p, (SYMPY_INTS, Integer)) and
+                isinstance(n, factorial) and
+                isinstance(n.args[0], Integer) and
+                n.args[0] >= 0):
+            return multiplicity_in_factorial(p, n.args[0])
+        raise ValueError('expecting ints or fractions, got %s and %s' % (p, n))
+
+    if n == 0:
+        raise ValueError('no such integer exists: multiplicity of %s is not-defined' %(n))
+    return remove(n, p)[1]
+
+
+def multiplicity_in_factorial(p, n):
+    """return the largest integer ``m`` such that ``p**m`` divides ``n!``
+    without calculating the factorial of ``n``.
+
+    Parameters
+    ==========
+
+    p : Integer
+        positive integer
+    n : Integer
+        non-negative integer
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory import multiplicity_in_factorial
+    >>> from sympy import factorial
+
+    >>> multiplicity_in_factorial(2, 3)
+    1
+
+    An instructive use of this is to tell how many trailing zeros
+    a given factorial has. For example, there are 6 in 25!:
+
+    >>> factorial(25)
+    15511210043330985984000000
+    >>> multiplicity_in_factorial(10, 25)
+    6
+
+    For large factorials, it is much faster/feasible to use
+    this function rather than computing the actual factorial:
+
+    >>> multiplicity_in_factorial(factorial(25), 2**100)
+    52818775009509558395695966887
+
+    See Also
+    ========
+
+    multiplicity
+
+    """
+
+    p, n = as_int(p), as_int(n)
+
+    if p <= 0:
+        raise ValueError('expecting positive integer got %s' % p )
+
+    if n < 0:
+        raise ValueError('expecting non-negative integer got %s' % n )
+
+    # keep only the largest of a given multiplicity since those
+    # of a given multiplicity will be goverened by the behavior
+    # of the largest factor
+    f = defaultdict(int)
+    for k, v in factorint(p).items():
+        f[v] = max(k, f[v])
+    # multiplicity of p in n! depends on multiplicity
+    # of prime `k` in p, so we floor divide by `v`
+    # and keep it if smaller than the multiplicity of p
+    # seen so far
+    return min((n + k - sum(digits(n, k)))//(k - 1)//v for v, k in f.items())
+
+
+def _perfect_power(n, next_p=2):
+    """ Return integers ``(b, e)`` such that ``n == b**e`` if ``n`` is a unique
+    perfect power with ``e > 1``, else ``False`` (e.g. 1 is not a perfect power).
+
+    Explanation
+    ===========
+
+    This is a low-level helper for ``perfect_power``, for internal use.
+
+    Parameters
+    ==========
+
+    n : int
+        assume that n is a nonnegative integer
+    next_p : int
+        Assume that n has no factor less than next_p.
+        i.e., all(n % p for p in range(2, next_p)) is True
+
+    Examples
+    ========
+    >>> from sympy.ntheory.factor_ import _perfect_power
+    >>> _perfect_power(16)
+    (2, 4)
+    >>> _perfect_power(17)
+    False
+
+    """
+    if n <= 3:
+        return False
+
+    factors = {}
+    g = 0
+    multi = 1
+
+    def done(n, factors, g, multi):
+        g = gcd(g, multi)
+        if g == 1:
+            return False
+        factors[n] = multi
+        return math.prod(p**(e//g) for p, e in factors.items()), g
+
+    # If n is small, only trial factoring is faster
+    if n <= 1_000_000:
+        n = _factorint_small(factors, n, 1_000, 1_000, next_p)[0]
+        if n > 1:
+            return False
+        g = gcd(*factors.values())
+        if g == 1:
+            return False
+        return math.prod(p**(e//g) for p, e in factors.items()), g
+
+    # divide by 2
+    if next_p < 3:
+        g = bit_scan1(n)
+        if g:
+            if g == 1:
+                return False
+            n >>= g
+            factors[2] = g
+            if n == 1:
+                return 2, g
+            else:
+                # If `m**g`, then we have found perfect power.
+                # Otherwise, there is no possibility of perfect power, especially if `g` is prime.
+                m, _exact = iroot(n, g)
+                if _exact:
+                    return 2*m, g
+                elif isprime(g):
+                    return False
+        next_p = 3
+
+    # square number?
+    while n & 7 == 1: # n % 8 == 1:
+        m, _exact = iroot(n, 2)
+        if _exact:
+            n = m
+            multi <<= 1
+        else:
+            break
+    if n < next_p**3:
+        return done(n, factors, g, multi)
+
+    # trial factoring
+    # Since the maximum value an exponent can take is `log_{next_p}(n)`,
+    # the number of exponents to be checked can be reduced by performing a trial factoring.
+    # The value of `tf_max` needs more consideration.
+    tf_max = n.bit_length()//27 + 24
+    if next_p < tf_max:
+        for p in primerange(next_p, tf_max):
+            m, t = remove(n, p)
+            if t:
+                n = m
+                t *= multi
+                _g = gcd(g, t)
+                if _g == 1:
+                    return False
+                factors[p] = t
+                if n == 1:
+                    return math.prod(p**(e//_g)
+                                        for p, e in factors.items()), _g
+                elif g == 0 or _g < g: # If g is updated
+                    g = _g
+                    m, _exact = iroot(n**multi, g)
+                    if _exact:
+                        return m * math.prod(p**(e//g)
+                                            for p, e in factors.items()), g
+                    elif isprime(g):
+                        return False
+        next_p = tf_max
+    if n < next_p**3:
+        return done(n, factors, g, multi)
+
+    # check iroot
+    if g:
+        # If g is non-zero, the exponent is a divisor of g.
+        # 2 can be omitted since it has already been checked.
+        prime_iter = sorted(factorint(g >> bit_scan1(g)).keys())
+    else:
+        # The maximum possible value of the exponent is `log_{next_p}(n)`.
+        # To compensate for the presence of computational error, 2 is added.
+        prime_iter = primerange(3, int(math.log(n, next_p)) + 2)
+    logn = math.log2(n)
+    threshold = logn / 40 # Threshold for direct calculation
+    for p in prime_iter:
+        if threshold < p:
+            # If p is large, find the power root p directly without `iroot`.
+            while True:
+                b = pow(2, logn / p)
+                rb = int(b + 0.5)
+                if abs(rb - b) < 0.01 and rb**p == n:
+                    n = rb
+                    multi *= p
+                    logn = math.log2(n)
+                else:
+                    break
+        else:
+            while True:
+                m, _exact = iroot(n, p)
+                if _exact:
+                    n = m
+                    multi *= p
+                    logn = math.log2(n)
+                else:
+                    break
+        if n < next_p**(p + 2):
+            break
+    return done(n, factors, g, multi)
+
+
+def perfect_power(n, candidates=None, big=True, factor=True):
+    """
+    Return ``(b, e)`` such that ``n`` == ``b**e`` if ``n`` is a unique
+    perfect power with ``e > 1``, else ``False`` (e.g. 1 is not a
+    perfect power). A ValueError is raised if ``n`` is not Rational.
+
+    By default, the base is recursively decomposed and the exponents
+    collected so the largest possible ``e`` is sought. If ``big=False``
+    then the smallest possible ``e`` (thus prime) will be chosen.
+
+    If ``factor=True`` then simultaneous factorization of ``n`` is
+    attempted since finding a factor indicates the only possible root
+    for ``n``. This is True by default since only a few small factors will
+    be tested in the course of searching for the perfect power.
+
+    The use of ``candidates`` is primarily for internal use; if provided,
+    False will be returned if ``n`` cannot be written as a power with one
+    of the candidates as an exponent and factoring (beyond testing for
+    a factor of 2) will not be attempted.
+
+    Examples
+    ========
+
+    >>> from sympy import perfect_power, Rational
+    >>> perfect_power(16)
+    (2, 4)
+    >>> perfect_power(16, big=False)
+    (4, 2)
+
+    Negative numbers can only have odd perfect powers:
+
+    >>> perfect_power(-4)
+    False
+    >>> perfect_power(-8)
+    (-2, 3)
+
+    Rationals are also recognized:
+
+    >>> perfect_power(Rational(1, 2)**3)
+    (1/2, 3)
+    >>> perfect_power(Rational(-3, 2)**3)
+    (-3/2, 3)
+
+    Notes
+    =====
+
+    To know whether an integer is a perfect power of 2 use
+
+        >>> is2pow = lambda n: bool(n and not n & (n - 1))
+        >>> [(i, is2pow(i)) for i in range(5)]
+        [(0, False), (1, True), (2, True), (3, False), (4, True)]
+
+    It is not necessary to provide ``candidates``. When provided
+    it will be assumed that they are ints. The first one that is
+    larger than the computed maximum possible exponent will signal
+    failure for the routine.
+
+        >>> perfect_power(3**8, [9])
+        False
+        >>> perfect_power(3**8, [2, 4, 8])
+        (3, 8)
+        >>> perfect_power(3**8, [4, 8], big=False)
+        (9, 4)
+
+    See Also
+    ========
+    sympy.core.intfunc.integer_nthroot
+    sympy.ntheory.primetest.is_square
+    """
+    # negative handling
+    if n < 0:
+        if candidates is None:
+            pp = perfect_power(-n, big=True, factor=factor)
+            if not pp:
+                return False
+
+            b, e = pp
+            e2 = e & (-e)
+            b, e = b ** e2, e // e2
+
+            if e <= 1:
+                return False
+
+            if big or isprime(e):
+                return -b, e
+
+            for p in primerange(3, e + 1):
+                if e % p == 0:
+                    return - b ** (e // p), p
+
+        odd_candidates = {i for i in candidates if i % 2}
+        if not odd_candidates:
+            return False
+
+        pp = perfect_power(-n, odd_candidates, big, factor)
+        if pp:
+            return -pp[0], pp[1]
+
+        return False
+
+    # non-integer handling
+    if isinstance(n, Rational) and not isinstance(n, Integer):
+        p, q = n.p, n.q
+
+        if p == 1:
+            qq = perfect_power(q, candidates, big, factor)
+            return (S.One / qq[0], qq[1]) if qq is not False else False
+
+        if not (pp:=perfect_power(p, factor=factor)):
+            return False
+        if not (qq:=perfect_power(q, factor=factor)):
+            return False
+        (num_base, num_exp), (den_base, den_exp) = pp, qq
+
+        def compute_tuple(exponent):
+            """Helper to compute final result given an exponent"""
+            new_num = num_base ** (num_exp // exponent)
+            new_den = den_base ** (den_exp // exponent)
+            return n.func(new_num, new_den), exponent
+
+        if candidates:
+            valid_candidates = [i for i in candidates
+                                if num_exp % i == 0 and den_exp % i == 0]
+            if not valid_candidates:
+                return False
+
+            e = max(valid_candidates) if big else min(valid_candidates)
+            return compute_tuple(e)
+
+        g = math.gcd(num_exp, den_exp)
+        if g == 1:
+            return False
+
+        if big:
+            return compute_tuple(g)
+
+        e = next(p for p in primerange(2, g + 1) if g % p == 0)
+        return compute_tuple(e)
+
+    if candidates is not None:
+        candidates = set(candidates)
+
+    # positive integer handling
+    n = as_int(n)
+
+    if candidates is None and big:
+        return _perfect_power(n)
+
+    if n <= 3:
+        # no unique exponent for 0, 1
+        # 2 and 3 have exponents of 1
+        return False
+    logn = math.log2(n)
+    max_possible = int(logn) + 2  # only check values less than this
+    not_square = n % 10 in [2, 3, 7, 8]  # squares cannot end in 2, 3, 7, 8
+    min_possible = 2 + not_square
+    if not candidates:
+        candidates = primerange(min_possible, max_possible)
+    else:
+        candidates = sorted([i for i in candidates
+            if min_possible <= i < max_possible])
+        if n%2 == 0:
+            e = bit_scan1(n)
+            candidates = [i for i in candidates if e%i == 0]
+        if big:
+            candidates = reversed(candidates)
+        for e in candidates:
+            r, ok = iroot(n, e)
+            if ok:
+                return int(r), e
+        return False
+
+    def _factors():
+        rv = 2 + n % 2
+        while True:
+            yield rv
+            rv = nextprime(rv)
+
+    for fac, e in zip(_factors(), candidates):
+        # see if there is a factor present
+        if factor and n % fac == 0:
+            # find what the potential power is
+            e = remove(n, fac)[1]
+            # if it's a trivial power we are done
+            if e == 1:
+                return False
+
+            # maybe the e-th root of n is exact
+            r, exact = iroot(n, e)
+            if not exact:
+                # Having a factor, we know that e is the maximal
+                # possible value for a root of n.
+                # If n = fac**e*m can be written as a perfect
+                # power then see if m can be written as r**E where
+                # gcd(e, E) != 1 so n = (fac**(e//E)*r)**E
+                m = n//fac**e
+                rE = perfect_power(m, candidates=divisors(e, generator=True))
+                if not rE:
+                    return False
+                else:
+                    r, E = rE
+                    r, e = fac**(e//E)*r, E
+            if not big:
+                e0 = primefactors(e)
+                if e0[0] != e:
+                    r, e = r**(e//e0[0]), e0[0]
+            return int(r), e
+
+        # Weed out downright impossible candidates
+        if logn/e < 40:
+            b = 2.0**(logn/e)
+            if abs(int(b + 0.5) - b) > 0.01:
+                continue
+
+        # now see if the plausible e makes a perfect power
+        r, exact = iroot(n, e)
+        if exact:
+            if big:
+                m = perfect_power(r, big=big, factor=factor)
+                if m:
+                    r, e = m[0], e*m[1]
+            return int(r), e
+
+    return False
+
+
+class FactorCache(MutableMapping):
+    """ Provides a cache for prime factors.
+    ``factor_cache`` is pre-prepared as an instance of ``FactorCache``,
+    and ``factorint`` internally references it to speed up
+    the factorization of prime factors.
+
+    While cache is automatically added during the execution of ``factorint``,
+    users can also manually add prime factors independently.
+
+    >>> from sympy import factor_cache
+    >>> factor_cache[15] = 5
+
+    Furthermore, by customizing ``get_external``,
+    it is also possible to use external databases.
+    The following is an example using http://factordb.com .
+
+    .. code-block:: python
+
+        import requests
+        from sympy import factor_cache
+
+        def get_external(self, n: int) -> list[int] | None:
+            res = requests.get("http://factordb.com/api", params={"query": str(n)})
+            if res.status_code != requests.codes.ok:
+                return None
+            j = res.json()
+            if j.get("status") in ["FF", "P"]:
+                return list(int(p) for p, _ in j.get("factors"))
+
+        factor_cache.get_external = get_external
+
+    Be aware that writing this code will trigger internet access
+    to factordb.com when calling ``factorint``.
+
+    """
+    def __init__(self, maxsize: int | None = None):
+        self._cache: OrderedDict[int, int] = OrderedDict()
+        self.maxsize = maxsize
+
+    def __len__(self) -> int:
+        return len(self._cache)
+
+    def __contains__(self, n) -> bool:
+        return n in self._cache
+
+    def __getitem__(self, n: int) -> int:
+        factor = self.get(n)
+        if factor is None:
+            raise KeyError(f"{n} does not exist.")
+        return factor
+
+    def __setitem__(self, n: int, factor: int):
+        if not (1 < factor <= n and n % factor == 0 and isprime(factor)):
+            raise ValueError(f"{factor} is not a prime factor of {n}")
+        self._cache[n] = max(self._cache.get(n, 0), factor)
+        if self.maxsize is not None and len(self._cache) > self.maxsize:
+            self._cache.popitem(False)
+
+    def __delitem__(self, n: int):
+        if n not in self._cache:
+            raise KeyError(f"{n} does not exist.")
+        del self._cache[n]
+
+    def __iter__(self):
+        return self._cache.__iter__()
+
+    def cache_clear(self) -> None:
+        """ Clear the cache """
+        self._cache = OrderedDict()
+
+    @property
+    def maxsize(self) -> int | None:
+        """ Returns the maximum cache size; if ``None``, it is unlimited. """
+        return self._maxsize
+
+    @maxsize.setter
+    def maxsize(self, value: int | None) -> None:
+        if value is not None and value <= 0:
+            raise ValueError("maxsize must be None or a non-negative integer.")
+        self._maxsize = value
+        if value is not None:
+            while len(self._cache) > value:
+                self._cache.popitem(False)
+
+    def get(self, n: int, default=None):
+        """ Return the prime factor of ``n``.
+        If it does not exist in the cache, return the value of ``default``.
+        """
+        if n <= sieve._list[-1]:
+            if sieve._list[bisect_left(sieve._list, n)] == n:
+                return n
+        if n in self._cache:
+            self._cache.move_to_end(n)
+            return self._cache[n]
+        if factors := self.get_external(n):
+            self.add(n, factors)
+            return self._cache[n]
+        return default
+
+    def add(self, n: int, factors: list[int]) -> None:
+        for p in sorted(factors, reverse=True):
+            self[n] = p
+            n, _ = remove(n, p)
+
+    def get_external(self, n: int) -> list[int] | None:
+        return None
+
+
+factor_cache = FactorCache(maxsize=1000)
+
+
+def pollard_rho(n, s=2, a=1, retries=5, seed=1234, max_steps=None, F=None):
+    r"""
+    Use Pollard's rho method to try to extract a nontrivial factor
+    of ``n``. The returned factor may be a composite number. If no
+    factor is found, ``None`` is returned.
+
+    The algorithm generates pseudo-random values of x with a generator
+    function, replacing x with F(x). If F is not supplied then the
+    function x**2 + ``a`` is used. The first value supplied to F(x) is ``s``.
+    Upon failure (if ``retries`` is > 0) a new ``a`` and ``s`` will be
+    supplied; the ``a`` will be ignored if F was supplied.
+
+    The sequence of numbers generated by such functions generally have a
+    a lead-up to some number and then loop around back to that number and
+    begin to repeat the sequence, e.g. 1, 2, 3, 4, 5, 3, 4, 5 -- this leader
+    and loop look a bit like the Greek letter rho, and thus the name, 'rho'.
+
+    For a given function, very different leader-loop values can be obtained
+    so it is a good idea to allow for retries:
+
+    >>> from sympy.ntheory.generate import cycle_length
+    >>> n = 16843009
+    >>> F = lambda x:(2048*pow(x, 2, n) + 32767) % n
+    >>> for s in range(5):
+    ...     print('loop length = %4i; leader length = %3i' % next(cycle_length(F, s)))
+    ...
+    loop length = 2489; leader length =  43
+    loop length =   78; leader length = 121
+    loop length = 1482; leader length = 100
+    loop length = 1482; leader length = 286
+    loop length = 1482; leader length = 101
+
+    Here is an explicit example where there is a three element leadup to
+    a sequence of 3 numbers (11, 14, 4) that then repeat:
+
+    >>> x=2
+    >>> for i in range(9):
+    ...     print(x)
+    ...     x=(x**2+12)%17
+    ...
+    2
+    16
+    13
+    11
+    14
+    4
+    11
+    14
+    4
+    >>> next(cycle_length(lambda x: (x**2+12)%17, 2))
+    (3, 3)
+    >>> list(cycle_length(lambda x: (x**2+12)%17, 2, values=True))
+    [2, 16, 13, 11, 14, 4]
+
+    Instead of checking the differences of all generated values for a gcd
+    with n, only the kth and 2*kth numbers are checked, e.g. 1st and 2nd,
+    2nd and 4th, 3rd and 6th until it has been detected that the loop has been
+    traversed. Loops may be many thousands of steps long before rho finds a
+    factor or reports failure. If ``max_steps`` is specified, the iteration
+    is cancelled with a failure after the specified number of steps.
+
+    Examples
+    ========
+
+    >>> from sympy import pollard_rho
+    >>> n=16843009
+    >>> F=lambda x:(2048*pow(x,2,n) + 32767) % n
+    >>> pollard_rho(n, F=F)
+    257
+
+    Use the default setting with a bad value of ``a`` and no retries:
+
+    >>> pollard_rho(n, a=n-2, retries=0)
+
+    If retries is > 0 then perhaps the problem will correct itself when
+    new values are generated for a:
+
+    >>> pollard_rho(n, a=n-2, retries=1)
+    257
+
+    References
+    ==========
+
+    .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
+           A Computational Perspective", Springer, 2nd edition, 229-231
+
+    """
+    n = int(n)
+    if n < 5:
+        raise ValueError('pollard_rho should receive n > 4')
+    randint = _randint(seed + retries)
+    V = s
+    for i in range(retries + 1):
+        U = V
+        if not F:
+            F = lambda x: (pow(x, 2, n) + a) % n
+        j = 0
+        while 1:
+            if max_steps and (j > max_steps):
+                break
+            j += 1
+            U = F(U)
+            V = F(F(V))  # V is 2x further along than U
+            g = gcd(U - V, n)
+            if g == 1:
+                continue
+            if g == n:
+                break
+            return int(g)
+        V = randint(0, n - 1)
+        a = randint(1, n - 3)  # for x**2 + a, a%n should not be 0 or -2
+        F = None
+    return None
+
+
+def pollard_pm1(n, B=10, a=2, retries=0, seed=1234):
+    """
+    Use Pollard's p-1 method to try to extract a nontrivial factor
+    of ``n``. Either a divisor (perhaps composite) or ``None`` is returned.
+
+    The value of ``a`` is the base that is used in the test gcd(a**M - 1, n).
+    The default is 2.  If ``retries`` > 0 then if no factor is found after the
+    first attempt, a new ``a`` will be generated randomly (using the ``seed``)
+    and the process repeated.
+
+    Note: the value of M is lcm(1..B) = reduce(ilcm, range(2, B + 1)).
+
+    A search is made for factors next to even numbers having a power smoothness
+    less than ``B``. Choosing a larger B increases the likelihood of finding a
+    larger factor but takes longer. Whether a factor of n is found or not
+    depends on ``a`` and the power smoothness of the even number just less than
+    the factor p (hence the name p - 1).
+
+    Although some discussion of what constitutes a good ``a`` some
+    descriptions are hard to interpret. At the modular.math site referenced
+    below it is stated that if gcd(a**M - 1, n) = N then a**M % q**r is 1
+    for every prime power divisor of N. But consider the following:
+
+        >>> from sympy.ntheory.factor_ import smoothness_p, pollard_pm1
+        >>> n=257*1009
+        >>> smoothness_p(n)
+        (-1, [(257, (1, 2, 256)), (1009, (1, 7, 16))])
+
+    So we should (and can) find a root with B=16:
+
+        >>> pollard_pm1(n, B=16, a=3)
+        1009
+
+    If we attempt to increase B to 256 we find that it does not work:
+
+        >>> pollard_pm1(n, B=256)
+        >>>
+
+    But if the value of ``a`` is changed we find that only multiples of
+    257 work, e.g.:
+
+        >>> pollard_pm1(n, B=256, a=257)
+        1009
+
+    Checking different ``a`` values shows that all the ones that did not
+    work had a gcd value not equal to ``n`` but equal to one of the
+    factors:
+
+        >>> from sympy import ilcm, igcd, factorint, Pow
+        >>> M = 1
+        >>> for i in range(2, 256):
+        ...     M = ilcm(M, i)
+        ...
+        >>> set([igcd(pow(a, M, n) - 1, n) for a in range(2, 256) if
+        ...      igcd(pow(a, M, n) - 1, n) != n])
+        {1009}
+
+    But does aM % d for every divisor of n give 1?
+
+        >>> aM = pow(255, M, n)
+        >>> [(d, aM%Pow(*d.args)) for d in factorint(n, visual=True).args]
+        [(257**1, 1), (1009**1, 1)]
+
+    No, only one of them. So perhaps the principle is that a root will
+    be found for a given value of B provided that:
+
+    1) the power smoothness of the p - 1 value next to the root
+       does not exceed B
+    2) a**M % p != 1 for any of the divisors of n.
+
+    By trying more than one ``a`` it is possible that one of them
+    will yield a factor.
+
+    Examples
+    ========
+
+    With the default smoothness bound, this number cannot be cracked:
+
+        >>> from sympy.ntheory import pollard_pm1
+        >>> pollard_pm1(21477639576571)
+
+    Increasing the smoothness bound helps:
+
+        >>> pollard_pm1(21477639576571, B=2000)
+        4410317
+
+    Looking at the smoothness of the factors of this number we find:
+
+        >>> from sympy.ntheory.factor_ import smoothness_p, factorint
+        >>> print(smoothness_p(21477639576571, visual=1))
+        p**i=4410317**1 has p-1 B=1787, B-pow=1787
+        p**i=4869863**1 has p-1 B=2434931, B-pow=2434931
+
+    The B and B-pow are the same for the p - 1 factorizations of the divisors
+    because those factorizations had a very large prime factor:
+
+        >>> factorint(4410317 - 1)
+        {2: 2, 617: 1, 1787: 1}
+        >>> factorint(4869863-1)
+        {2: 1, 2434931: 1}
+
+    Note that until B reaches the B-pow value of 1787, the number is not cracked;
+
+        >>> pollard_pm1(21477639576571, B=1786)
+        >>> pollard_pm1(21477639576571, B=1787)
+        4410317
+
+    The B value has to do with the factors of the number next to the divisor,
+    not the divisors themselves. A worst case scenario is that the number next
+    to the factor p has a large prime divisisor or is a perfect power. If these
+    conditions apply then the power-smoothness will be about p/2 or p. The more
+    realistic is that there will be a large prime factor next to p requiring
+    a B value on the order of p/2. Although primes may have been searched for
+    up to this level, the p/2 is a factor of p - 1, something that we do not
+    know. The modular.math reference below states that 15% of numbers in the
+    range of 10**15 to 15**15 + 10**4 are 10**6 power smooth so a B of 10**6
+    will fail 85% of the time in that range. From 10**8 to 10**8 + 10**3 the
+    percentages are nearly reversed...but in that range the simple trial
+    division is quite fast.
+
+    References
+    ==========
+
+    .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
+           A Computational Perspective", Springer, 2nd edition, 236-238
+    .. [2] https://web.archive.org/web/20150716201437/http://modular.math.washington.edu/edu/2007/spring/ent/ent-html/node81.html
+    .. [3] https://www.cs.toronto.edu/~yuvalf/Factorization.pdf
+    """
+
+    n = int(n)
+    if n < 4 or B < 3:
+        raise ValueError('pollard_pm1 should receive n > 3 and B > 2')
+    randint = _randint(seed + B)
+
+    # computing a**lcm(1,2,3,..B) % n for B > 2
+    # it looks weird, but it's right: primes run [2, B]
+    # and the answer's not right until the loop is done.
+    for i in range(retries + 1):
+        aM = a
+        for p in sieve.primerange(2, B + 1):
+            e = int(math.log(B, p))
+            aM = pow(aM, pow(p, e), n)
+        g = gcd(aM - 1, n)
+        if 1 < g < n:
+            return int(g)
+
+        # get a new a:
+        # since the exponent, lcm(1..B), is even, if we allow 'a' to be 'n-1'
+        # then (n - 1)**even % n will be 1 which will give a g of 0 and 1 will
+        # give a zero, too, so we set the range as [2, n-2]. Some references
+        # say 'a' should be coprime to n, but either will detect factors.
+        a = randint(2, n - 2)
+
+
+def _trial(factors, n, candidates, verbose=False):
+    """
+    Helper function for integer factorization. Trial factors ``n`
+    against all integers given in the sequence ``candidates``
+    and updates the dict ``factors`` in-place. Returns the reduced
+    value of ``n`` and a flag indicating whether any factors were found.
+    """
+    if verbose:
+        factors0 = list(factors.keys())
+    nfactors = len(factors)
+    for d in candidates:
+        if n % d == 0:
+            if n != d:
+                factor_cache[n] = d
+            n, m = remove(n // d, d)
+            factors[d] = m + 1
+    if verbose:
+        for k in sorted(set(factors).difference(set(factors0))):
+            print(factor_msg % (k, factors[k]))
+    return int(n), len(factors) != nfactors
+
+
+def _check_termination(factors, n, limit, use_trial, use_rho, use_pm1,
+                       verbose, next_p):
+    """
+    Helper function for integer factorization. Checks if ``n``
+    is a prime or a perfect power, and in those cases updates the factorization.
+    """
+    if verbose:
+        print('Check for termination')
+    if n == 1:
+        if verbose:
+            print(complete_msg)
+        return True
+    if n < next_p**2 or isprime(n):
+        factor_cache[n] = n
+        factors[int(n)] = 1
+        if verbose:
+            print(complete_msg)
+        return True
+
+    # since we've already been factoring there is no need to do
+    # simultaneous factoring with the power check
+    p = _perfect_power(n, next_p)
+    if not p:
+        return False
+    base, exp = p
+    if base < next_p**2 or isprime(base):
+        factor_cache[n] = base
+        factors[base] = exp
+    else:
+        facs = factorint(base, limit, use_trial, use_rho, use_pm1,
+                         verbose=False)
+        for b, e in facs.items():
+            if verbose:
+                print(factor_msg % (b, e))
+            factors[b] = exp*e
+    if verbose:
+        print(complete_msg)
+    return True
+
+
+trial_int_msg = "Trial division with ints [%i ... %i] and fail_max=%i"
+trial_msg = "Trial division with primes [%i ... %i]"
+rho_msg = "Pollard's rho with retries %i, max_steps %i and seed %i"
+pm1_msg = "Pollard's p-1 with smoothness bound %i and seed %i"
+ecm_msg = "Elliptic Curve with B1 bound %i, B2 bound %i, num_curves %i"
+factor_msg = '\t%i ** %i'
+fermat_msg = 'Close factors satisfying Fermat condition found.'
+complete_msg = 'Factorization is complete.'
+
+
+def _factorint_small(factors, n, limit, fail_max, next_p=2):
+    """
+    Return the value of n and either a 0 (indicating that factorization up
+    to the limit was complete) or else the next near-prime that would have
+    been tested.
+
+    Factoring stops if there are fail_max unsuccessful tests in a row.
+
+    If factors of n were found they will be in the factors dictionary as
+    {factor: multiplicity} and the returned value of n will have had those
+    factors removed. The factors dictionary is modified in-place.
+
+    """
+
+    def done(n, d):
+        """return n, d if the sqrt(n) was not reached yet, else
+           n, 0 indicating that factoring is done.
+        """
+        if d*d <= n:
+            return n, d
+        return n, 0
+
+    limit2 = limit**2
+    threshold2 = min(n, limit2)
+
+    if next_p < 3:
+        if not n & 1:
+            m = bit_scan1(n)
+            factors[2] = m
+            n >>= m
+            threshold2 = min(n, limit2)
+        next_p = 3
+        if threshold2 < 9: # next_p**2 = 9
+            return done(n, next_p)
+
+    if next_p < 5:
+        if not n % 3:
+            n //= 3
+            m = 1
+            while not n % 3:
+                n //= 3
+                m += 1
+                if m == 20:
+                    n, mm = remove(n, 3)
+                    m += mm
+                    break
+            factors[3] = m
+            threshold2 = min(n, limit2)
+        next_p = 5
+        if threshold2 < 25: # next_p**2 = 25
+            return done(n, next_p)
+
+    # Because of the order of checks, starting from `min_p = 6k+5`,
+    # useless checks are caused.
+    # We want to calculate
+    # next_p += [-1, -2, 3, 2, 1, 0][next_p % 6]
+    p6 = next_p % 6
+    next_p += (-1 if p6 < 2 else 5) - p6
+
+    fails = 0
+    while fails < fail_max:
+        # next_p % 6 == 5
+        if n % next_p:
+            fails += 1
+        else:
+            n //= next_p
+            m = 1
+            while not n % next_p:
+                n //= next_p
+                m += 1
+                if m == 20:
+                    n, mm = remove(n, next_p)
+                    m += mm
+                    break
+            factors[next_p] = m
+            fails = 0
+            threshold2 = min(n, limit2)
+        next_p += 2
+        if threshold2 < next_p**2:
+            return done(n, next_p)
+
+        # next_p % 6 == 1
+        if n % next_p:
+            fails += 1
+        else:
+            n //= next_p
+            m = 1
+            while not n % next_p:
+                n //= next_p
+                m += 1
+                if m == 20:
+                    n, mm = remove(n, next_p)
+                    m += mm
+                    break
+            factors[next_p] = m
+            fails = 0
+            threshold2 = min(n, limit2)
+        next_p += 4
+        if threshold2 < next_p**2:
+            return done(n, next_p)
+    return done(n, next_p)
+
+
+def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True,
+              use_ecm=True, verbose=False, visual=None, multiple=False):
+    r"""
+    Given a positive integer ``n``, ``factorint(n)`` returns a dict containing
+    the prime factors of ``n`` as keys and their respective multiplicities
+    as values. For example:
+
+    >>> from sympy.ntheory import factorint
+    >>> factorint(2000)    # 2000 = (2**4) * (5**3)
+    {2: 4, 5: 3}
+    >>> factorint(65537)   # This number is prime
+    {65537: 1}
+
+    For input less than 2, factorint behaves as follows:
+
+        - ``factorint(1)`` returns the empty factorization, ``{}``
+        - ``factorint(0)`` returns ``{0:1}``
+        - ``factorint(-n)`` adds ``-1:1`` to the factors and then factors ``n``
+
+    Partial Factorization:
+
+    If ``limit`` (> 3) is specified, the search is stopped after performing
+    trial division up to (and including) the limit (or taking a
+    corresponding number of rho/p-1 steps). This is useful if one has
+    a large number and only is interested in finding small factors (if
+    any). Note that setting a limit does not prevent larger factors
+    from being found early; it simply means that the largest factor may
+    be composite. Since checking for perfect power is relatively cheap, it is
+    done regardless of the limit setting.
+
+    This number, for example, has two small factors and a huge
+    semi-prime factor that cannot be reduced easily:
+
+    >>> from sympy.ntheory import isprime
+    >>> a = 1407633717262338957430697921446883
+    >>> f = factorint(a, limit=10000)
+    >>> f == {991: 1, int(202916782076162456022877024859): 1, 7: 1}
+    True
+    >>> isprime(max(f))
+    False
+
+    This number has a small factor and a residual perfect power whose
+    base is greater than the limit:
+
+    >>> factorint(3*101**7, limit=5)
+    {3: 1, 101: 7}
+
+    List of Factors:
+
+    If ``multiple`` is set to ``True`` then a list containing the
+    prime factors including multiplicities is returned.
+
+    >>> factorint(24, multiple=True)
+    [2, 2, 2, 3]
+
+    Visual Factorization:
+
+    If ``visual`` is set to ``True``, then it will return a visual
+    factorization of the integer.  For example:
+
+    >>> from sympy import pprint
+    >>> pprint(factorint(4200, visual=True))
+     3  1  2  1
+    2 *3 *5 *7
+
+    Note that this is achieved by using the evaluate=False flag in Mul
+    and Pow. If you do other manipulations with an expression where
+    evaluate=False, it may evaluate.  Therefore, you should use the
+    visual option only for visualization, and use the normal dictionary
+    returned by visual=False if you want to perform operations on the
+    factors.
+
+    You can easily switch between the two forms by sending them back to
+    factorint:
+
+    >>> from sympy import Mul
+    >>> regular = factorint(1764); regular
+    {2: 2, 3: 2, 7: 2}
+    >>> pprint(factorint(regular))
+     2  2  2
+    2 *3 *7
+
+    >>> visual = factorint(1764, visual=True); pprint(visual)
+     2  2  2
+    2 *3 *7
+    >>> print(factorint(visual))
+    {2: 2, 3: 2, 7: 2}
+
+    If you want to send a number to be factored in a partially factored form
+    you can do so with a dictionary or unevaluated expression:
+
+    >>> factorint(factorint({4: 2, 12: 3})) # twice to toggle to dict form
+    {2: 10, 3: 3}
+    >>> factorint(Mul(4, 12, evaluate=False))
+    {2: 4, 3: 1}
+
+    The table of the output logic is:
+
+        ====== ====== ======= =======
+                       Visual
+        ------ ----------------------
+        Input  True   False   other
+        ====== ====== ======= =======
+        dict    mul    dict    mul
+        n       mul    dict    dict
+        mul     mul    dict    dict
+        ====== ====== ======= =======
+
+    Notes
+    =====
+
+    Algorithm:
+
+    The function switches between multiple algorithms. Trial division
+    quickly finds small factors (of the order 1-5 digits), and finds
+    all large factors if given enough time. The Pollard rho and p-1
+    algorithms are used to find large factors ahead of time; they
+    will often find factors of the order of 10 digits within a few
+    seconds:
+
+    >>> factors = factorint(12345678910111213141516)
+    >>> for base, exp in sorted(factors.items()):
+    ...     print('%s %s' % (base, exp))
+    ...
+    2 2
+    2507191691 1
+    1231026625769 1
+
+    Any of these methods can optionally be disabled with the following
+    boolean parameters:
+
+        - ``use_trial``: Toggle use of trial division
+        - ``use_rho``: Toggle use of Pollard's rho method
+        - ``use_pm1``: Toggle use of Pollard's p-1 method
+
+    ``factorint`` also periodically checks if the remaining part is
+    a prime number or a perfect power, and in those cases stops.
+
+    For unevaluated factorial, it uses Legendre's formula(theorem).
+
+
+    If ``verbose`` is set to ``True``, detailed progress is printed.
+
+    See Also
+    ========
+
+    smoothness, smoothness_p, divisors
+
+    """
+    if isinstance(n, Dict):
+        n = dict(n)
+    if multiple:
+        fac = factorint(n, limit=limit, use_trial=use_trial,
+                           use_rho=use_rho, use_pm1=use_pm1,
+                           verbose=verbose, visual=False, multiple=False)
+        factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S.One/p]*(-fac[p])
+                               for p in sorted(fac)), [])
+        return factorlist
+
+    factordict = {}
+    if visual and not isinstance(n, (Mul, dict)):
+        factordict = factorint(n, limit=limit, use_trial=use_trial,
+                               use_rho=use_rho, use_pm1=use_pm1,
+                               verbose=verbose, visual=False)
+    elif isinstance(n, Mul):
+        factordict = {int(k): int(v) for k, v in
+            n.as_powers_dict().items()}
+    elif isinstance(n, dict):
+        factordict = n
+    if factordict and isinstance(n, (Mul, dict)):
+        # check it
+        for key in list(factordict.keys()):
+            if isprime(key):
+                continue
+            e = factordict.pop(key)
+            d = factorint(key, limit=limit, use_trial=use_trial, use_rho=use_rho,
+                          use_pm1=use_pm1, verbose=verbose, visual=False)
+            for k, v in d.items():
+                if k in factordict:
+                    factordict[k] += v*e
+                else:
+                    factordict[k] = v*e
+    if visual or (type(n) is dict and
+                  visual is not True and
+                  visual is not False):
+        if factordict == {}:
+            return S.One
+        if -1 in factordict:
+            factordict.pop(-1)
+            args = [S.NegativeOne]
+        else:
+            args = []
+        args.extend([Pow(*i, evaluate=False)
+                     for i in sorted(factordict.items())])
+        return Mul(*args, evaluate=False)
+    elif isinstance(n, (dict, Mul)):
+        return factordict
+
+    assert use_trial or use_rho or use_pm1 or use_ecm
+
+    from sympy.functions.combinatorial.factorials import factorial
+    if isinstance(n, factorial):
+        x = as_int(n.args[0])
+        if x >= 20:
+            factors = {}
+            m = 2 # to initialize the if condition below
+            for p in sieve.primerange(2, x + 1):
+                if m > 1:
+                    m, q = 0, x // p
+                    while q != 0:
+                        m += q
+                        q //= p
+                factors[p] = m
+            if factors and verbose:
+                for k in sorted(factors):
+                    print(factor_msg % (k, factors[k]))
+            if verbose:
+                print(complete_msg)
+            return factors
+        else:
+            # if n < 20!, direct computation is faster
+            # since it uses a lookup table
+            n = n.func(x)
+
+    n = as_int(n)
+    if limit:
+        limit = int(limit)
+        use_ecm = False
+
+    # special cases
+    if n < 0:
+        factors = factorint(
+            -n, limit=limit, use_trial=use_trial, use_rho=use_rho,
+            use_pm1=use_pm1, verbose=verbose, visual=False)
+        factors[-1] = 1
+        return factors
+
+    if limit and limit < 2:
+        if n == 1:
+            return {}
+        return {n: 1}
+    elif n < 10:
+        # doing this we are assured of getting a limit > 2
+        # when we have to compute it later
+        return [{0: 1}, {}, {2: 1}, {3: 1}, {2: 2}, {5: 1},
+                {2: 1, 3: 1}, {7: 1}, {2: 3}, {3: 2}][n]
+
+    factors = {}
+
+    # do simplistic factorization
+    if verbose:
+        sn = str(n)
+        if len(sn) > 50:
+            print('Factoring %s' % sn[:5] + \
+                  '..(%i other digits)..' % (len(sn) - 10) + sn[-5:])
+        else:
+            print('Factoring', n)
+
+    # this is the preliminary factorization for small factors
+    # We want to guarantee that there are no small prime factors,
+    # so we run even if `use_trial` is False.
+    small = 2**15
+    fail_max = 600
+    small = min(small, limit or small)
+    if verbose:
+        print(trial_int_msg % (2, small, fail_max))
+    n, next_p = _factorint_small(factors, n, small, fail_max)
+    if factors and verbose:
+        for k in sorted(factors):
+            print(factor_msg % (k, factors[k]))
+    if next_p == 0:
+        if n > 1:
+            factors[int(n)] = 1
+        if verbose:
+            print(complete_msg)
+        return factors
+    # Check if it exists in the cache
+    while p := factor_cache.get(n):
+        n, e = remove(n, p)
+        factors[int(p)] = int(e)
+    # first check if the simplistic run didn't finish
+    # because of the limit and check for a perfect
+    # power before exiting
+    if limit and next_p > limit:
+        if verbose:
+            print('Exceeded limit:', limit)
+        if _check_termination(factors, n, limit, use_trial,
+                              use_rho, use_pm1, verbose, next_p):
+            return factors
+        if n > 1:
+            factors[int(n)] = 1
+        return factors
+    if _check_termination(factors, n, limit, use_trial,
+                          use_rho, use_pm1, verbose, next_p):
+        return factors
+
+    # continue with more advanced factorization methods
+    # ...do a Fermat test since it's so easy and we need the
+    # square root anyway. Finding 2 factors is easy if they are
+    # "close enough." This is the big root equivalent of dividing by
+    # 2, 3, 5.
+    sqrt_n = isqrt(n)
+    a = sqrt_n + 1
+    # If `n % 4 == 1`, `a` must be odd for `a**2 - n` to be a square number.
+    if (n % 4 == 1) ^ (a & 1):
+        a += 1
+    a2 = a**2
+    b2 = a2 - n
+    for _ in range(3):
+        b, fermat = sqrtrem(b2)
+        if not fermat:
+            if verbose:
+                print(fermat_msg)
+            for r in [a - b, a + b]:
+                facs = factorint(r, limit=limit, use_trial=use_trial,
+                                 use_rho=use_rho, use_pm1=use_pm1,
+                                 verbose=verbose)
+                for k, v in facs.items():
+                    factors[k] = factors.get(k, 0) + v
+                factor_cache.add(n, facs)
+            if verbose:
+                print(complete_msg)
+            return factors
+        b2 += (a + 1) << 2  # equiv to (a + 2)**2 - n
+        a += 2
+
+    # these are the limits for trial division which will
+    # be attempted in parallel with pollard methods
+    low, high = next_p, 2*next_p
+
+    # add 1 to make sure limit is reached in primerange calls
+    _limit = (limit or sqrt_n) + 1
+    iteration = 0
+    while 1:
+        high_ = min(high, _limit)
+
+        # Trial division
+        if use_trial:
+            if verbose:
+                print(trial_msg % (low, high_))
+            ps = sieve.primerange(low, high_)
+            n, found_trial = _trial(factors, n, ps, verbose)
+            next_p = high_
+            if found_trial and _check_termination(factors, n, limit, use_trial,
+                                                  use_rho, use_pm1, verbose, next_p):
+                return factors
+        else:
+            found_trial = False
+
+        if high > _limit:
+            if verbose:
+                print('Exceeded limit:', _limit)
+            if n > 1:
+                factors[int(n)] = 1
+            if verbose:
+                print(complete_msg)
+            return factors
+
+        # Only used advanced methods when no small factors were found
+        if not found_trial:
+            # Pollard p-1
+            if use_pm1:
+                if verbose:
+                    print(pm1_msg % (low, high_))
+                c = pollard_pm1(n, B=low, seed=high_)
+                if c:
+                    if c < next_p**2 or isprime(c):
+                        ps = [c]
+                    else:
+                        ps = factorint(c, limit=limit,
+                                       use_trial=use_trial,
+                                       use_rho=use_rho,
+                                       use_pm1=use_pm1,
+                                       use_ecm=use_ecm,
+                                       verbose=verbose)
+                    n, _ = _trial(factors, n, ps, verbose=False)
+                    if _check_termination(factors, n, limit, use_trial,
+                                          use_rho, use_pm1, verbose, next_p):
+                        return factors
+
+            # Pollard rho
+            if use_rho:
+                if verbose:
+                    print(rho_msg % (1, low, high_))
+                c = pollard_rho(n, retries=1, max_steps=low, seed=high_)
+                if c:
+                    if c < next_p**2 or isprime(c):
+                        ps = [c]
+                    else:
+                        ps = factorint(c, limit=limit,
+                                       use_trial=use_trial,
+                                       use_rho=use_rho,
+                                       use_pm1=use_pm1,
+                                       use_ecm=use_ecm,
+                                       verbose=verbose)
+                    n, _ = _trial(factors, n, ps, verbose=False)
+                    if _check_termination(factors, n, limit, use_trial,
+                                          use_rho, use_pm1, verbose, next_p):
+                        return factors
+        # Use subexponential algorithms if use_ecm
+        # Use pollard algorithms for finding small factors for 3 iterations
+        # if after small factors the number of digits of n >= 25 then use ecm
+        iteration += 1
+        if use_ecm and iteration >= 3 and num_digits(n) >= 24:
+            break
+        low, high = high, high*2
+
+    B1 = 10000
+    B2 = 100*B1
+    num_curves = 50
+    while(1):
+        if verbose:
+            print(ecm_msg % (B1, B2, num_curves))
+        factor = _ecm_one_factor(n, B1, B2, num_curves, seed=B1)
+        if factor:
+            if factor < next_p**2 or isprime(factor):
+                ps = [factor]
+            else:
+                ps = factorint(factor, limit=limit,
+                           use_trial=use_trial,
+                           use_rho=use_rho,
+                           use_pm1=use_pm1,
+                           use_ecm=use_ecm,
+                           verbose=verbose)
+            n, _ = _trial(factors, n, ps, verbose=False)
+            if _check_termination(factors, n, limit, use_trial,
+                                  use_rho, use_pm1, verbose, next_p):
+                return factors
+        B1 *= 5
+        B2 = 100*B1
+        num_curves *= 4
+
+
+def factorrat(rat, limit=None, use_trial=True, use_rho=True, use_pm1=True,
+              verbose=False, visual=None, multiple=False):
+    r"""
+    Given a Rational ``r``, ``factorrat(r)`` returns a dict containing
+    the prime factors of ``r`` as keys and their respective multiplicities
+    as values. For example:
+
+    >>> from sympy import factorrat, S
+    >>> factorrat(S(8)/9)    # 8/9 = (2**3) * (3**-2)
+    {2: 3, 3: -2}
+    >>> factorrat(S(-1)/987)    # -1/789 = -1 * (3**-1) * (7**-1) * (47**-1)
+    {-1: 1, 3: -1, 7: -1, 47: -1}
+
+    Please see the docstring for ``factorint`` for detailed explanations
+    and examples of the following keywords:
+
+        - ``limit``: Integer limit up to which trial division is done
+        - ``use_trial``: Toggle use of trial division
+        - ``use_rho``: Toggle use of Pollard's rho method
+        - ``use_pm1``: Toggle use of Pollard's p-1 method
+        - ``verbose``: Toggle detailed printing of progress
+        - ``multiple``: Toggle returning a list of factors or dict
+        - ``visual``: Toggle product form of output
+    """
+    if multiple:
+        fac = factorrat(rat, limit=limit, use_trial=use_trial,
+                  use_rho=use_rho, use_pm1=use_pm1,
+                  verbose=verbose, visual=False, multiple=False)
+        factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S.One/p]*(-fac[p])
+                               for p, _ in sorted(fac.items(),
+                                                        key=lambda elem: elem[0]
+                                                        if elem[1] > 0
+                                                        else 1/elem[0])), [])
+        return factorlist
+
+    f = factorint(rat.p, limit=limit, use_trial=use_trial,
+                  use_rho=use_rho, use_pm1=use_pm1,
+                  verbose=verbose).copy()
+    f = defaultdict(int, f)
+    for p, e in factorint(rat.q, limit=limit,
+                          use_trial=use_trial,
+                          use_rho=use_rho,
+                          use_pm1=use_pm1,
+                          verbose=verbose).items():
+        f[p] += -e
+
+    if len(f) > 1 and 1 in f:
+        del f[1]
+    if not visual:
+        return dict(f)
+    else:
+        if -1 in f:
+            f.pop(-1)
+            args = [S.NegativeOne]
+        else:
+            args = []
+        args.extend([Pow(*i, evaluate=False)
+                     for i in sorted(f.items())])
+        return Mul(*args, evaluate=False)
+
+
+def primefactors(n, limit=None, verbose=False, **kwargs):
+    """Return a sorted list of n's prime factors, ignoring multiplicity
+    and any composite factor that remains if the limit was set too low
+    for complete factorization. Unlike factorint(), primefactors() does
+    not return -1 or 0.
+
+    Parameters
+    ==========
+
+    n : integer
+    limit, verbose, **kwargs :
+        Additional keyword arguments to be passed to ``factorint``.
+        Since ``kwargs`` is new in version 1.13,
+        ``limit`` and ``verbose`` are retained for compatibility purposes.
+
+    Returns
+    =======
+
+    list(int) : List of prime numbers dividing ``n``
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory import primefactors, factorint, isprime
+    >>> primefactors(6)
+    [2, 3]
+    >>> primefactors(-5)
+    [5]
+
+    >>> sorted(factorint(123456).items())
+    [(2, 6), (3, 1), (643, 1)]
+    >>> primefactors(123456)
+    [2, 3, 643]
+
+    >>> sorted(factorint(10000000001, limit=200).items())
+    [(101, 1), (99009901, 1)]
+    >>> isprime(99009901)
+    False
+    >>> primefactors(10000000001, limit=300)
+    [101]
+
+    See Also
+    ========
+
+    factorint, divisors
+
+    """
+    n = int(n)
+    kwargs.update({"visual": None, "multiple": False,
+                   "limit": limit, "verbose": verbose})
+    factors = sorted(factorint(n=n, **kwargs).keys())
+    # We want to calculate
+    # s = [f for f in factors if isprime(f)]
+    s = [f for f in factors[:-1:] if f not in [-1, 0, 1]]
+    if factors and isprime(factors[-1]):
+        s += [factors[-1]]
+    return s
+
+
+def _divisors(n, proper=False):
+    """Helper function for divisors which generates the divisors.
+
+    Parameters
+    ==========
+
+    n : int
+        a nonnegative integer
+    proper: bool
+        If `True`, returns the generator that outputs only the proper divisor (i.e., excluding n).
+
+    """
+    if n <= 1:
+        if not proper and n:
+            yield 1
+        return
+
+    factordict = factorint(n)
+    ps = sorted(factordict.keys())
+
+    def rec_gen(n=0):
+        if n == len(ps):
+            yield 1
+        else:
+            pows = [1]
+            for _ in range(factordict[ps[n]]):
+                pows.append(pows[-1] * ps[n])
+            yield from (p * q for q in rec_gen(n + 1) for p in pows)
+
+    if proper:
+        yield from (p for p in rec_gen() if p != n)
+    else:
+        yield from rec_gen()
+
+
+def divisors(n, generator=False, proper=False):
+    r"""
+    Return all divisors of n sorted from 1..n by default.
+    If generator is ``True`` an unordered generator is returned.
+
+    The number of divisors of n can be quite large if there are many
+    prime factors (counting repeated factors). If only the number of
+    factors is desired use divisor_count(n).
+
+    Examples
+    ========
+
+    >>> from sympy import divisors, divisor_count
+    >>> divisors(24)
+    [1, 2, 3, 4, 6, 8, 12, 24]
+    >>> divisor_count(24)
+    8
+
+    >>> list(divisors(120, generator=True))
+    [1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60, 120]
+
+    Notes
+    =====
+
+    This is a slightly modified version of Tim Peters referenced at:
+    https://stackoverflow.com/questions/1010381/python-factorization
+
+    See Also
+    ========
+
+    primefactors, factorint, divisor_count
+    """
+    rv = _divisors(as_int(abs(n)), proper)
+    return rv if generator else sorted(rv)
+
+
+def divisor_count(n, modulus=1, proper=False):
+    """
+    Return the number of divisors of ``n``. If ``modulus`` is not 1 then only
+    those that are divisible by ``modulus`` are counted. If ``proper`` is True
+    then the divisor of ``n`` will not be counted.
+
+    Examples
+    ========
+
+    >>> from sympy import divisor_count
+    >>> divisor_count(6)
+    4
+    >>> divisor_count(6, 2)
+    2
+    >>> divisor_count(6, proper=True)
+    3
+
+    See Also
+    ========
+
+    factorint, divisors, totient, proper_divisor_count
+
+    """
+
+    if not modulus:
+        return 0
+    elif modulus != 1:
+        n, r = divmod(n, modulus)
+        if r:
+            return 0
+    if n == 0:
+        return 0
+    n = Mul(*[v + 1 for k, v in factorint(n).items() if k > 1])
+    if n and proper:
+        n -= 1
+    return n
+
+
+def proper_divisors(n, generator=False):
+    """
+    Return all divisors of n except n, sorted by default.
+    If generator is ``True`` an unordered generator is returned.
+
+    Examples
+    ========
+
+    >>> from sympy import proper_divisors, proper_divisor_count
+    >>> proper_divisors(24)
+    [1, 2, 3, 4, 6, 8, 12]
+    >>> proper_divisor_count(24)
+    7
+    >>> list(proper_divisors(120, generator=True))
+    [1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60]
+
+    See Also
+    ========
+
+    factorint, divisors, proper_divisor_count
+
+    """
+    return divisors(n, generator=generator, proper=True)
+
+
+def proper_divisor_count(n, modulus=1):
+    """
+    Return the number of proper divisors of ``n``.
+
+    Examples
+    ========
+
+    >>> from sympy import proper_divisor_count
+    >>> proper_divisor_count(6)
+    3
+    >>> proper_divisor_count(6, modulus=2)
+    1
+
+    See Also
+    ========
+
+    divisors, proper_divisors, divisor_count
+
+    """
+    return divisor_count(n, modulus=modulus, proper=True)
+
+
+def _udivisors(n):
+    """Helper function for udivisors which generates the unitary divisors.
+
+    Parameters
+    ==========
+
+    n : int
+        a nonnegative integer
+
+    """
+    if n <= 1:
+        if n == 1:
+            yield 1
+        return
+
+    factorpows = [p**e for p, e in factorint(n).items()]
+    # We want to calculate
+    # yield from (math.prod(s) for s in powersets(factorpows))
+    for i in range(2**len(factorpows)):
+        d = 1
+        for k in range(i.bit_length()):
+            if i & 1:
+                d *= factorpows[k]
+            i >>= 1
+        yield d
+
+
+def udivisors(n, generator=False):
+    r"""
+    Return all unitary divisors of n sorted from 1..n by default.
+    If generator is ``True`` an unordered generator is returned.
+
+    The number of unitary divisors of n can be quite large if there are many
+    prime factors. If only the number of unitary divisors is desired use
+    udivisor_count(n).
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.factor_ import udivisors, udivisor_count
+    >>> udivisors(15)
+    [1, 3, 5, 15]
+    >>> udivisor_count(15)
+    4
+
+    >>> sorted(udivisors(120, generator=True))
+    [1, 3, 5, 8, 15, 24, 40, 120]
+
+    See Also
+    ========
+
+    primefactors, factorint, divisors, divisor_count, udivisor_count
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Unitary_divisor
+    .. [2] https://mathworld.wolfram.com/UnitaryDivisor.html
+
+    """
+    rv = _udivisors(as_int(abs(n)))
+    return rv if generator else sorted(rv)
+
+
+def udivisor_count(n):
+    """
+    Return the number of unitary divisors of ``n``.
+
+    Parameters
+    ==========
+
+    n : integer
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.factor_ import udivisor_count
+    >>> udivisor_count(120)
+    8
+
+    See Also
+    ========
+
+    factorint, divisors, udivisors, divisor_count, totient
+
+    References
+    ==========
+
+    .. [1] https://mathworld.wolfram.com/UnitaryDivisorFunction.html
+
+    """
+
+    if n == 0:
+        return 0
+    return 2**len([p for p in factorint(n) if p > 1])
+
+
+def _antidivisors(n):
+    """Helper function for antidivisors which generates the antidivisors.
+
+    Parameters
+    ==========
+
+    n : int
+        a nonnegative integer
+
+    """
+    if n <= 2:
+        return
+    for d in _divisors(n):
+        y = 2*d
+        if n > y and n % y:
+            yield y
+    for d in _divisors(2*n-1):
+        if n > d >= 2 and n % d:
+            yield d
+    for d in _divisors(2*n+1):
+        if n > d >= 2 and n % d:
+            yield d
+
+
+def antidivisors(n, generator=False):
+    r"""
+    Return all antidivisors of n sorted from 1..n by default.
+
+    Antidivisors [1]_ of n are numbers that do not divide n by the largest
+    possible margin.  If generator is True an unordered generator is returned.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.factor_ import antidivisors
+    >>> antidivisors(24)
+    [7, 16]
+
+    >>> sorted(antidivisors(128, generator=True))
+    [3, 5, 15, 17, 51, 85]
+
+    See Also
+    ========
+
+    primefactors, factorint, divisors, divisor_count, antidivisor_count
+
+    References
+    ==========
+
+    .. [1] definition is described in https://oeis.org/A066272/a066272a.html
+
+    """
+    rv = _antidivisors(as_int(abs(n)))
+    return rv if generator else sorted(rv)
+
+
+def antidivisor_count(n):
+    """
+    Return the number of antidivisors [1]_ of ``n``.
+
+    Parameters
+    ==========
+
+    n : integer
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.factor_ import antidivisor_count
+    >>> antidivisor_count(13)
+    4
+    >>> antidivisor_count(27)
+    5
+
+    See Also
+    ========
+
+    factorint, divisors, antidivisors, divisor_count, totient
+
+    References
+    ==========
+
+    .. [1] formula from https://oeis.org/A066272
+
+    """
+
+    n = as_int(abs(n))
+    if n <= 2:
+        return 0
+    return divisor_count(2*n - 1) + divisor_count(2*n + 1) + \
+        divisor_count(n) - divisor_count(n, 2) - 5
+
+@deprecated("""\
+The `sympy.ntheory.factor_.totient` has been moved to `sympy.functions.combinatorial.numbers.totient`.""",
+deprecated_since_version="1.13",
+active_deprecations_target='deprecated-ntheory-symbolic-functions')
+def totient(n):
+    r"""
+    Calculate the Euler totient function phi(n)
+
+    .. deprecated:: 1.13
+
+        The ``totient`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.totient`
+        instead. See its documentation for more information. See
+        :ref:`deprecated-ntheory-symbolic-functions` for details.
+
+    ``totient(n)`` or `\phi(n)` is the number of positive integers `\leq` n
+    that are relatively prime to n.
+
+    Parameters
+    ==========
+
+    n : integer
+
+    Examples
+    ========
+
+    >>> from sympy.functions.combinatorial.numbers import totient
+    >>> totient(1)
+    1
+    >>> totient(25)
+    20
+    >>> totient(45) == totient(5)*totient(9)
+    True
+
+    See Also
+    ========
+
+    divisor_count
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Euler%27s_totient_function
+    .. [2] https://mathworld.wolfram.com/TotientFunction.html
+
+    """
+    from sympy.functions.combinatorial.numbers import totient as _totient
+    return _totient(n)
+
+
+@deprecated("""\
+The `sympy.ntheory.factor_.reduced_totient` has been moved to `sympy.functions.combinatorial.numbers.reduced_totient`.""",
+deprecated_since_version="1.13",
+active_deprecations_target='deprecated-ntheory-symbolic-functions')
+def reduced_totient(n):
+    r"""
+    Calculate the Carmichael reduced totient function lambda(n)
+
+    .. deprecated:: 1.13
+
+        The ``reduced_totient`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.reduced_totient`
+        instead. See its documentation for more information. See
+        :ref:`deprecated-ntheory-symbolic-functions` for details.
+
+    ``reduced_totient(n)`` or `\lambda(n)` is the smallest m > 0 such that
+    `k^m \equiv 1 \mod n` for all k relatively prime to n.
+
+    Examples
+    ========
+
+    >>> from sympy.functions.combinatorial.numbers import reduced_totient
+    >>> reduced_totient(1)
+    1
+    >>> reduced_totient(8)
+    2
+    >>> reduced_totient(30)
+    4
+
+    See Also
+    ========
+
+    totient
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Carmichael_function
+    .. [2] https://mathworld.wolfram.com/CarmichaelFunction.html
+
+    """
+    from sympy.functions.combinatorial.numbers import reduced_totient as _reduced_totient
+    return _reduced_totient(n)
+
+
+@deprecated("""\
+The `sympy.ntheory.factor_.divisor_sigma` has been moved to `sympy.functions.combinatorial.numbers.divisor_sigma`.""",
+deprecated_since_version="1.13",
+active_deprecations_target='deprecated-ntheory-symbolic-functions')
+def divisor_sigma(n, k=1):
+    r"""
+    Calculate the divisor function `\sigma_k(n)` for positive integer n
+
+    .. deprecated:: 1.13
+
+        The ``divisor_sigma`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.divisor_sigma`
+        instead. See its documentation for more information. See
+        :ref:`deprecated-ntheory-symbolic-functions` for details.
+
+    ``divisor_sigma(n, k)`` is equal to ``sum([x**k for x in divisors(n)])``
+
+    If n's prime factorization is:
+
+    .. math ::
+        n = \prod_{i=1}^\omega p_i^{m_i},
+
+    then
+
+    .. math ::
+        \sigma_k(n) = \prod_{i=1}^\omega (1+p_i^k+p_i^{2k}+\cdots
+        + p_i^{m_ik}).
+
+    Parameters
+    ==========
+
+    n : integer
+
+    k : integer, optional
+        power of divisors in the sum
+
+        for k = 0, 1:
+        ``divisor_sigma(n, 0)`` is equal to ``divisor_count(n)``
+        ``divisor_sigma(n, 1)`` is equal to ``sum(divisors(n))``
+
+        Default for k is 1.
+
+    Examples
+    ========
+
+    >>> from sympy.functions.combinatorial.numbers import divisor_sigma
+    >>> divisor_sigma(18, 0)
+    6
+    >>> divisor_sigma(39, 1)
+    56
+    >>> divisor_sigma(12, 2)
+    210
+    >>> divisor_sigma(37)
+    38
+
+    See Also
+    ========
+
+    divisor_count, totient, divisors, factorint
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Divisor_function
+
+    """
+    from sympy.functions.combinatorial.numbers import divisor_sigma as func_divisor_sigma
+    return func_divisor_sigma(n, k)
+
+
+def _divisor_sigma(n:int, k:int=1) -> int:
+    r""" Calculate the divisor function `\sigma_k(n)` for positive integer n
+
+    Parameters
+    ==========
+
+    n : int
+        positive integer
+    k : int
+        nonnegative integer
+
+    See Also
+    ========
+
+    sympy.functions.combinatorial.numbers.divisor_sigma
+
+    """
+    if k == 0:
+        return math.prod(e + 1 for e in factorint(n).values())
+    return math.prod((p**(k*(e + 1)) - 1)//(p**k - 1) for p, e in factorint(n).items())
+
+
+def core(n, t=2):
+    r"""
+    Calculate core(n, t) = `core_t(n)` of a positive integer n
+
+    ``core_2(n)`` is equal to the squarefree part of n
+
+    If n's prime factorization is:
+
+    .. math ::
+        n = \prod_{i=1}^\omega p_i^{m_i},
+
+    then
+
+    .. math ::
+        core_t(n) = \prod_{i=1}^\omega p_i^{m_i \mod t}.
+
+    Parameters
+    ==========
+
+    n : integer
+
+    t : integer
+        core(n, t) calculates the t-th power free part of n
+
+        ``core(n, 2)`` is the squarefree part of ``n``
+        ``core(n, 3)`` is the cubefree part of ``n``
+
+        Default for t is 2.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.factor_ import core
+    >>> core(24, 2)
+    6
+    >>> core(9424, 3)
+    1178
+    >>> core(379238)
+    379238
+    >>> core(15**11, 10)
+    15
+
+    See Also
+    ========
+
+    factorint, sympy.solvers.diophantine.diophantine.square_factor
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Square-free_integer#Squarefree_core
+
+    """
+
+    n = as_int(n)
+    t = as_int(t)
+    if n <= 0:
+        raise ValueError("n must be a positive integer")
+    elif t <= 1:
+        raise ValueError("t must be >= 2")
+    else:
+        y = 1
+        for p, e in factorint(n).items():
+            y *= p**(e % t)
+        return y
+
+
+@deprecated("""\
+The `sympy.ntheory.factor_.udivisor_sigma` has been moved to `sympy.functions.combinatorial.numbers.udivisor_sigma`.""",
+deprecated_since_version="1.13",
+active_deprecations_target='deprecated-ntheory-symbolic-functions')
+def udivisor_sigma(n, k=1):
+    r"""
+    Calculate the unitary divisor function `\sigma_k^*(n)` for positive integer n
+
+    .. deprecated:: 1.13
+
+        The ``udivisor_sigma`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.udivisor_sigma`
+        instead. See its documentation for more information. See
+        :ref:`deprecated-ntheory-symbolic-functions` for details.
+
+    ``udivisor_sigma(n, k)`` is equal to ``sum([x**k for x in udivisors(n)])``
+
+    If n's prime factorization is:
+
+    .. math ::
+        n = \prod_{i=1}^\omega p_i^{m_i},
+
+    then
+
+    .. math ::
+        \sigma_k^*(n) = \prod_{i=1}^\omega (1+ p_i^{m_ik}).
+
+    Parameters
+    ==========
+
+    k : power of divisors in the sum
+
+        for k = 0, 1:
+        ``udivisor_sigma(n, 0)`` is equal to ``udivisor_count(n)``
+        ``udivisor_sigma(n, 1)`` is equal to ``sum(udivisors(n))``
+
+        Default for k is 1.
+
+    Examples
+    ========
+
+    >>> from sympy.functions.combinatorial.numbers import udivisor_sigma
+    >>> udivisor_sigma(18, 0)
+    4
+    >>> udivisor_sigma(74, 1)
+    114
+    >>> udivisor_sigma(36, 3)
+    47450
+    >>> udivisor_sigma(111)
+    152
+
+    See Also
+    ========
+
+    divisor_count, totient, divisors, udivisors, udivisor_count, divisor_sigma,
+    factorint
+
+    References
+    ==========
+
+    .. [1] https://mathworld.wolfram.com/UnitaryDivisorFunction.html
+
+    """
+    from sympy.functions.combinatorial.numbers import udivisor_sigma as _udivisor_sigma
+    return _udivisor_sigma(n, k)
+
+
+@deprecated("""\
+The `sympy.ntheory.factor_.primenu` has been moved to `sympy.functions.combinatorial.numbers.primenu`.""",
+deprecated_since_version="1.13",
+active_deprecations_target='deprecated-ntheory-symbolic-functions')
+def primenu(n):
+    r"""
+    Calculate the number of distinct prime factors for a positive integer n.
+
+    .. deprecated:: 1.13
+
+        The ``primenu`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.primenu`
+        instead. See its documentation for more information. See
+        :ref:`deprecated-ntheory-symbolic-functions` for details.
+
+    If n's prime factorization is:
+
+    .. math ::
+        n = \prod_{i=1}^k p_i^{m_i},
+
+    then ``primenu(n)`` or `\nu(n)` is:
+
+    .. math ::
+        \nu(n) = k.
+
+    Examples
+    ========
+
+    >>> from sympy.functions.combinatorial.numbers import primenu
+    >>> primenu(1)
+    0
+    >>> primenu(30)
+    3
+
+    See Also
+    ========
+
+    factorint
+
+    References
+    ==========
+
+    .. [1] https://mathworld.wolfram.com/PrimeFactor.html
+
+    """
+    from sympy.functions.combinatorial.numbers import primenu as _primenu
+    return _primenu(n)
+
+
+@deprecated("""\
+The `sympy.ntheory.factor_.primeomega` has been moved to `sympy.functions.combinatorial.numbers.primeomega`.""",
+deprecated_since_version="1.13",
+active_deprecations_target='deprecated-ntheory-symbolic-functions')
+def primeomega(n):
+    r"""
+    Calculate the number of prime factors counting multiplicities for a
+    positive integer n.
+
+    .. deprecated:: 1.13
+
+        The ``primeomega`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.primeomega`
+        instead. See its documentation for more information. See
+        :ref:`deprecated-ntheory-symbolic-functions` for details.
+
+    If n's prime factorization is:
+
+    .. math ::
+        n = \prod_{i=1}^k p_i^{m_i},
+
+    then ``primeomega(n)``  or `\Omega(n)` is:
+
+    .. math ::
+        \Omega(n) = \sum_{i=1}^k m_i.
+
+    Examples
+    ========
+
+    >>> from sympy.functions.combinatorial.numbers import primeomega
+    >>> primeomega(1)
+    0
+    >>> primeomega(20)
+    3
+
+    See Also
+    ========
+
+    factorint
+
+    References
+    ==========
+
+    .. [1] https://mathworld.wolfram.com/PrimeFactor.html
+
+    """
+    from sympy.functions.combinatorial.numbers import primeomega as _primeomega
+    return _primeomega(n)
+
+
+def mersenne_prime_exponent(nth):
+    """Returns the exponent ``i`` for the nth Mersenne prime (which
+    has the form `2^i - 1`).
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.factor_ import mersenne_prime_exponent
+    >>> mersenne_prime_exponent(1)
+    2
+    >>> mersenne_prime_exponent(20)
+    4423
+    """
+    n = as_int(nth)
+    if n < 1:
+        raise ValueError("nth must be a positive integer; mersenne_prime_exponent(1) == 2")
+    if n > 51:
+        raise ValueError("There are only 51 perfect numbers; nth must be less than or equal to 51")
+    return MERSENNE_PRIME_EXPONENTS[n - 1]
+
+
+def is_perfect(n):
+    """Returns True if ``n`` is a perfect number, else False.
+
+    A perfect number is equal to the sum of its positive, proper divisors.
+
+    Examples
+    ========
+
+    >>> from sympy.functions.combinatorial.numbers import divisor_sigma
+    >>> from sympy.ntheory.factor_ import is_perfect, divisors
+    >>> is_perfect(20)
+    False
+    >>> is_perfect(6)
+    True
+    >>> 6 == divisor_sigma(6) - 6 == sum(divisors(6)[:-1])
+    True
+
+    References
+    ==========
+
+    .. [1] https://mathworld.wolfram.com/PerfectNumber.html
+    .. [2] https://en.wikipedia.org/wiki/Perfect_number
+
+    """
+    n = as_int(n)
+    if n < 1:
+        return False
+    if n % 2 == 0:
+        m = (n.bit_length() + 1) >> 1
+        if (1 << (m - 1)) * ((1 << m) - 1) != n:
+            # Even perfect numbers must be of the form `2^{m-1}(2^m-1)`
+            return False
+        return m in MERSENNE_PRIME_EXPONENTS or is_mersenne_prime(2**m - 1)
+
+    # n is an odd integer
+    if n < 10**2000:  # https://www.lirmm.fr/~ochem/opn/
+        return False
+    if n % 105 == 0:  # not divis by 105
+        return False
+    if all(n % m != r for m, r in [(12, 1), (468, 117), (324, 81)]):
+        return False
+    # there are many criteria that the factor structure of n
+    # must meet; since we will have to factor it to test the
+    # structure we will have the factors and can then check
+    # to see whether it is a perfect number or not. So we
+    # skip the structure checks and go straight to the final
+    # test below.
+    result = abundance(n) == 0
+    if result:
+        raise ValueError(filldedent('''In 1888, Sylvester stated: "
+            ...a prolonged meditation on the subject has satisfied
+            me that the existence of any one such [odd perfect number]
+            -- its escape, so to say, from the complex web of conditions
+            which hem it in on all sides -- would be little short of a
+            miracle." I guess SymPy just found that miracle and it
+            factors like this: %s''' % factorint(n)))
+    return result
+
+
+def abundance(n):
+    """Returns the difference between the sum of the positive
+    proper divisors of a number and the number.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory import abundance, is_perfect, is_abundant
+    >>> abundance(6)
+    0
+    >>> is_perfect(6)
+    True
+    >>> abundance(10)
+    -2
+    >>> is_abundant(10)
+    False
+    """
+    return _divisor_sigma(n) - 2 * n
+
+
+def is_abundant(n):
+    """Returns True if ``n`` is an abundant number, else False.
+
+    A abundant number is smaller than the sum of its positive proper divisors.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.factor_ import is_abundant
+    >>> is_abundant(20)
+    True
+    >>> is_abundant(15)
+    False
+
+    References
+    ==========
+
+    .. [1] https://mathworld.wolfram.com/AbundantNumber.html
+
+    """
+    n = as_int(n)
+    if is_perfect(n):
+        return False
+    return n % 6 == 0 or bool(abundance(n) > 0)
+
+
+def is_deficient(n):
+    """Returns True if ``n`` is a deficient number, else False.
+
+    A deficient number is greater than the sum of its positive proper divisors.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.factor_ import is_deficient
+    >>> is_deficient(20)
+    False
+    >>> is_deficient(15)
+    True
+
+    References
+    ==========
+
+    .. [1] https://mathworld.wolfram.com/DeficientNumber.html
+
+    """
+    n = as_int(n)
+    if is_perfect(n):
+        return False
+    return bool(abundance(n) < 0)
+
+
+def is_amicable(m, n):
+    """Returns True if the numbers `m` and `n` are "amicable", else False.
+
+    Amicable numbers are two different numbers so related that the sum
+    of the proper divisors of each is equal to that of the other.
+
+    Examples
+    ========
+
+    >>> from sympy.functions.combinatorial.numbers import divisor_sigma
+    >>> from sympy.ntheory.factor_ import is_amicable
+    >>> is_amicable(220, 284)
+    True
+    >>> divisor_sigma(220) == divisor_sigma(284)
+    True
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Amicable_numbers
+
+    """
+    return m != n and m + n == _divisor_sigma(m) == _divisor_sigma(n)
+
+
+def is_carmichael(n):
+    """ Returns True if the numbers `n` is Carmichael number, else False.
+
+    Parameters
+    ==========
+
+    n : Integer
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Carmichael_number
+    .. [2] https://oeis.org/A002997
+
+    """
+    if n < 561:
+        return False
+    return n % 2 and not isprime(n) and \
+           all(e == 1 and (n - 1) % (p - 1) == 0 for p, e in factorint(n).items())
+
+
+def find_carmichael_numbers_in_range(x, y):
+    """ Returns a list of the number of Carmichael in the range
+
+    See Also
+    ========
+
+    is_carmichael
+
+    """
+    if 0 <= x <= y:
+        if x % 2 == 0:
+            return [i for i in range(x + 1, y, 2) if is_carmichael(i)]
+        else:
+            return [i for i in range(x, y, 2) if is_carmichael(i)]
+    else:
+        raise ValueError('The provided range is not valid. x and y must be non-negative integers and x <= y')
+
+
+def find_first_n_carmichaels(n):
+    """ Returns the first n Carmichael numbers.
+
+    Parameters
+    ==========
+
+    n : Integer
+
+    See Also
+    ========
+
+    is_carmichael
+
+    """
+    i = 561
+    carmichaels = []
+
+    while len(carmichaels) < n:
+        if is_carmichael(i):
+            carmichaels.append(i)
+        i += 2
+
+    return carmichaels
+
+
+def dra(n, b):
+    """
+    Returns the additive digital root of a natural number ``n`` in base ``b``
+    which is a single digit value obtained by an iterative process of summing
+    digits, on each iteration using the result from the previous iteration to
+    compute a digit sum.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.factor_ import dra
+    >>> dra(3110, 12)
+    8
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Digital_root
+
+    """
+
+    num = abs(as_int(n))
+    b = as_int(b)
+    if b <= 1:
+        raise ValueError("Base should be an integer greater than 1")
+
+    if num == 0:
+        return 0
+
+    return (1 + (num - 1) % (b - 1))
+
+
+def drm(n, b):
+    """
+    Returns the multiplicative digital root of a natural number ``n`` in a given
+    base ``b`` which is a single digit value obtained by an iterative process of
+    multiplying digits, on each iteration using the result from the previous
+    iteration to compute the digit multiplication.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.factor_ import drm
+    >>> drm(9876, 10)
+    0
+
+    >>> drm(49, 10)
+    8
+
+    References
+    ==========
+
+    .. [1] https://mathworld.wolfram.com/MultiplicativeDigitalRoot.html
+
+    """
+
+    n = abs(as_int(n))
+    b = as_int(b)
+    if b <= 1:
+        raise ValueError("Base should be an integer greater than 1")
+    while n > b:
+        mul = 1
+        while n > 1:
+            n, r = divmod(n, b)
+            if r == 0:
+                return 0
+            mul *= r
+        n = mul
+    return n
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/generate.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/generate.py
new file mode 100644
index 0000000000000000000000000000000000000000..855bb44acfcb6241e6b0bcb81e7a2cfc8ced861f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/generate.py
@@ -0,0 +1,1157 @@
+"""
+Generating and counting primes.
+
+"""
+
+from bisect import bisect, bisect_left
+from itertools import count
+# Using arrays for sieving instead of lists greatly reduces
+# memory consumption
+from array import array as _array
+
+from sympy.core.random import randint
+from sympy.external.gmpy import sqrt
+from .primetest import isprime
+from sympy.utilities.decorator import deprecated
+from sympy.utilities.misc import as_int
+
+
+def _as_int_ceiling(a):
+    """ Wrapping ceiling in as_int will raise an error if there was a problem
+        determining whether the expression was exactly an integer or not."""
+    from sympy.functions.elementary.integers import ceiling
+    return as_int(ceiling(a))
+
+
+class Sieve:
+    """A list of prime numbers, implemented as a dynamically
+    growing sieve of Eratosthenes. When a lookup is requested involving
+    an odd number that has not been sieved, the sieve is automatically
+    extended up to that number. Implementation details limit the number of
+    primes to ``2^32-1``.
+
+    Examples
+    ========
+
+    >>> from sympy import sieve
+    >>> sieve._reset() # this line for doctest only
+    >>> 25 in sieve
+    False
+    >>> sieve._list
+    array('L', [2, 3, 5, 7, 11, 13, 17, 19, 23])
+    """
+
+    # data shared (and updated) by all Sieve instances
+    def __init__(self, sieve_interval=1_000_000):
+        """ Initial parameters for the Sieve class.
+
+        Parameters
+        ==========
+
+        sieve_interval (int): Amount of memory to be used
+
+        Raises
+        ======
+
+        ValueError
+            If ``sieve_interval`` is not positive.
+
+        """
+        self._n = 6
+        self._list = _array('L', [2, 3, 5, 7, 11, 13]) # primes
+        self._tlist = _array('L', [0, 1, 1, 2, 2, 4]) # totient
+        self._mlist = _array('i', [0, 1, -1, -1, 0, -1]) # mobius
+        if sieve_interval <= 0:
+            raise ValueError("sieve_interval should be a positive integer")
+        self.sieve_interval = sieve_interval
+        assert all(len(i) == self._n for i in (self._list, self._tlist, self._mlist))
+
+    def __repr__(self):
+        return ("<%s sieve (%i): %i, %i, %i, ... %i, %i\n"
+             "%s sieve (%i): %i, %i, %i, ... %i, %i\n"
+             "%s sieve (%i): %i, %i, %i, ... %i, %i>") % (
+             'prime', len(self._list),
+                 self._list[0], self._list[1], self._list[2],
+                 self._list[-2], self._list[-1],
+             'totient', len(self._tlist),
+                 self._tlist[0], self._tlist[1],
+                 self._tlist[2], self._tlist[-2], self._tlist[-1],
+             'mobius', len(self._mlist),
+                 self._mlist[0], self._mlist[1],
+                 self._mlist[2], self._mlist[-2], self._mlist[-1])
+
+    def _reset(self, prime=None, totient=None, mobius=None):
+        """Reset all caches (default). To reset one or more set the
+            desired keyword to True."""
+        if all(i is None for i in (prime, totient, mobius)):
+            prime = totient = mobius = True
+        if prime:
+            self._list = self._list[:self._n]
+        if totient:
+            self._tlist = self._tlist[:self._n]
+        if mobius:
+            self._mlist = self._mlist[:self._n]
+
+    def extend(self, n):
+        """Grow the sieve to cover all primes <= n.
+
+        Examples
+        ========
+
+        >>> from sympy import sieve
+        >>> sieve._reset() # this line for doctest only
+        >>> sieve.extend(30)
+        >>> sieve[10] == 29
+        True
+        """
+        n = int(n)
+        # `num` is even at any point in the function.
+        # This satisfies the condition required by `self._primerange`.
+        num = self._list[-1] + 1
+        if n < num:
+            return
+        num2 = num**2
+        while num2 <= n:
+            self._list += _array('L', self._primerange(num, num2))
+            num, num2 = num2, num2**2
+        # Merge the sieves
+        self._list += _array('L', self._primerange(num, n + 1))
+
+    def _primerange(self, a, b):
+        """ Generate all prime numbers in the range (a, b).
+
+        Parameters
+        ==========
+
+        a, b : positive integers assuming the following conditions
+                * a is an even number
+                * 2 < self._list[-1] < a < b < nextprime(self._list[-1])**2
+
+        Yields
+        ======
+
+        p (int): prime numbers such that ``a < p < b``
+
+        Examples
+        ========
+
+        >>> from sympy.ntheory.generate import Sieve
+        >>> s = Sieve()
+        >>> s._list[-1]
+        13
+        >>> list(s._primerange(18, 31))
+        [19, 23, 29]
+
+        """
+        if b % 2:
+            b -= 1
+        while a < b:
+            block_size = min(self.sieve_interval, (b - a) // 2)
+            # Create the list such that block[x] iff (a + 2x + 1) is prime.
+            # Note that even numbers are not considered here.
+            block = [True] * block_size
+            for p in self._list[1:bisect(self._list, sqrt(a + 2 * block_size + 1))]:
+                for t in range((-(a + 1 + p) // 2) % p, block_size, p):
+                    block[t] = False
+            for idx, p in enumerate(block):
+                if p:
+                    yield a + 2 * idx + 1
+            a += 2 * block_size
+
+    def extend_to_no(self, i):
+        """Extend to include the ith prime number.
+
+        Parameters
+        ==========
+
+        i : integer
+
+        Examples
+        ========
+
+        >>> from sympy import sieve
+        >>> sieve._reset() # this line for doctest only
+        >>> sieve.extend_to_no(9)
+        >>> sieve._list
+        array('L', [2, 3, 5, 7, 11, 13, 17, 19, 23])
+
+        Notes
+        =====
+
+        The list is extended by 50% if it is too short, so it is
+        likely that it will be longer than requested.
+        """
+        i = as_int(i)
+        while len(self._list) < i:
+            self.extend(int(self._list[-1] * 1.5))
+
+    def primerange(self, a, b=None):
+        """Generate all prime numbers in the range [2, a) or [a, b).
+
+        Examples
+        ========
+
+        >>> from sympy import sieve, prime
+
+        All primes less than 19:
+
+        >>> print([i for i in sieve.primerange(19)])
+        [2, 3, 5, 7, 11, 13, 17]
+
+        All primes greater than or equal to 7 and less than 19:
+
+        >>> print([i for i in sieve.primerange(7, 19)])
+        [7, 11, 13, 17]
+
+        All primes through the 10th prime
+
+        >>> list(sieve.primerange(prime(10) + 1))
+        [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
+
+        """
+        if b is None:
+            b = _as_int_ceiling(a)
+            a = 2
+        else:
+            a = max(2, _as_int_ceiling(a))
+            b = _as_int_ceiling(b)
+        if a >= b:
+            return
+        self.extend(b)
+        yield from self._list[bisect_left(self._list, a):
+                              bisect_left(self._list, b)]
+
+    def totientrange(self, a, b):
+        """Generate all totient numbers for the range [a, b).
+
+        Examples
+        ========
+
+        >>> from sympy import sieve
+        >>> print([i for i in sieve.totientrange(7, 18)])
+        [6, 4, 6, 4, 10, 4, 12, 6, 8, 8, 16]
+        """
+        a = max(1, _as_int_ceiling(a))
+        b = _as_int_ceiling(b)
+        n = len(self._tlist)
+        if a >= b:
+            return
+        elif b <= n:
+            for i in range(a, b):
+                yield self._tlist[i]
+        else:
+            self._tlist += _array('L', range(n, b))
+            for i in range(1, n):
+                ti = self._tlist[i]
+                if ti == i - 1:
+                    startindex = (n + i - 1) // i * i
+                    for j in range(startindex, b, i):
+                        self._tlist[j] -= self._tlist[j] // i
+                if i >= a:
+                    yield ti
+
+            for i in range(n, b):
+                ti = self._tlist[i]
+                if ti == i:
+                    for j in range(i, b, i):
+                        self._tlist[j] -= self._tlist[j] // i
+                if i >= a:
+                    yield self._tlist[i]
+
+    def mobiusrange(self, a, b):
+        """Generate all mobius numbers for the range [a, b).
+
+        Parameters
+        ==========
+
+        a : integer
+            First number in range
+
+        b : integer
+            First number outside of range
+
+        Examples
+        ========
+
+        >>> from sympy import sieve
+        >>> print([i for i in sieve.mobiusrange(7, 18)])
+        [-1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1]
+        """
+        a = max(1, _as_int_ceiling(a))
+        b = _as_int_ceiling(b)
+        n = len(self._mlist)
+        if a >= b:
+            return
+        elif b <= n:
+            for i in range(a, b):
+                yield self._mlist[i]
+        else:
+            self._mlist += _array('i', [0]*(b - n))
+            for i in range(1, n):
+                mi = self._mlist[i]
+                startindex = (n + i - 1) // i * i
+                for j in range(startindex, b, i):
+                    self._mlist[j] -= mi
+                if i >= a:
+                    yield mi
+
+            for i in range(n, b):
+                mi = self._mlist[i]
+                for j in range(2 * i, b, i):
+                    self._mlist[j] -= mi
+                if i >= a:
+                    yield mi
+
+    def search(self, n):
+        """Return the indices i, j of the primes that bound n.
+
+        If n is prime then i == j.
+
+        Although n can be an expression, if ceiling cannot convert
+        it to an integer then an n error will be raised.
+
+        Examples
+        ========
+
+        >>> from sympy import sieve
+        >>> sieve.search(25)
+        (9, 10)
+        >>> sieve.search(23)
+        (9, 9)
+        """
+        test = _as_int_ceiling(n)
+        n = as_int(n)
+        if n < 2:
+            raise ValueError("n should be >= 2 but got: %s" % n)
+        if n > self._list[-1]:
+            self.extend(n)
+        b = bisect(self._list, n)
+        if self._list[b - 1] == test:
+            return b, b
+        else:
+            return b, b + 1
+
+    def __contains__(self, n):
+        try:
+            n = as_int(n)
+            assert n >= 2
+        except (ValueError, AssertionError):
+            return False
+        if n % 2 == 0:
+            return n == 2
+        a, b = self.search(n)
+        return a == b
+
+    def __iter__(self):
+        for n in count(1):
+            yield self[n]
+
+    def __getitem__(self, n):
+        """Return the nth prime number"""
+        if isinstance(n, slice):
+            self.extend_to_no(n.stop)
+            start = n.start if n.start is not None else 0
+            if start < 1:
+                # sieve[:5] would be empty (starting at -1), let's
+                # just be explicit and raise.
+                raise IndexError("Sieve indices start at 1.")
+            return self._list[start - 1:n.stop - 1:n.step]
+        else:
+            if n < 1:
+                # offset is one, so forbid explicit access to sieve[0]
+                # (would surprisingly return the last one).
+                raise IndexError("Sieve indices start at 1.")
+            n = as_int(n)
+            self.extend_to_no(n)
+            return self._list[n - 1]
+
+# Generate a global object for repeated use in trial division etc
+sieve = Sieve()
+
+def prime(nth):
+    r"""
+    Return the nth prime number, where primes are indexed starting from 1:
+    prime(1) = 2, prime(2) = 3, etc.
+
+    Parameters
+    ==========
+
+    nth : int
+        The position of the prime number to return (must be a positive integer).
+
+    Returns
+    =======
+
+    int
+        The nth prime number.
+
+    Examples
+    ========
+
+    >>> from sympy import prime
+    >>> prime(10)
+    29
+    >>> prime(1)
+    2
+    >>> prime(100000)
+    1299709
+
+    See Also
+    ========
+
+    sympy.ntheory.primetest.isprime : Test if a number is prime.
+    primerange : Generate all primes in a given range.
+    primepi : Return the number of primes less than or equal to a given number.
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Prime_number_theorem
+    .. [2] https://en.wikipedia.org/wiki/Logarithmic_integral_function
+    .. [3] https://en.wikipedia.org/wiki/Skewes%27_number
+    """
+    n = as_int(nth)
+    if n < 1:
+        raise ValueError("nth must be a positive integer; prime(1) == 2")
+
+    # Check if n is within the sieve range
+    if n <= len(sieve._list):
+        return sieve[n]
+
+    from sympy.functions.elementary.exponential import log
+    from sympy.functions.special.error_functions import li
+
+    if n < 1000:
+        # Extend sieve up to 8*n as this is empirically sufficient
+        sieve.extend(8 * n)
+        return sieve[n]
+
+    a = 2
+    # Estimate an upper bound for the nth prime using the prime number theorem
+    b = int(n * (log(n).evalf() + log(log(n)).evalf()))
+
+    # Binary search for the least m such that li(m) > n
+    while a < b:
+        mid = (a + b) >> 1
+        if li(mid).evalf() > n:
+            b = mid
+        else:
+            a = mid + 1
+
+    return nextprime(a - 1, n - _primepi(a - 1))
+
+
+@deprecated("""\
+The `sympy.ntheory.generate.primepi` has been moved to `sympy.functions.combinatorial.numbers.primepi`.""",
+deprecated_since_version="1.13",
+active_deprecations_target='deprecated-ntheory-symbolic-functions')
+def primepi(n):
+    r""" Represents the prime counting function pi(n) = the number
+        of prime numbers less than or equal to n.
+
+        .. deprecated:: 1.13
+
+            The ``primepi`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.primepi`
+            instead. See its documentation for more information. See
+            :ref:`deprecated-ntheory-symbolic-functions` for details.
+
+        Algorithm Description:
+
+        In sieve method, we remove all multiples of prime p
+        except p itself.
+
+        Let phi(i,j) be the number of integers 2 <= k <= i
+        which remain after sieving from primes less than
+        or equal to j.
+        Clearly, pi(n) = phi(n, sqrt(n))
+
+        If j is not a prime,
+        phi(i,j) = phi(i, j - 1)
+
+        if j is a prime,
+        We remove all numbers(except j) whose
+        smallest prime factor is j.
+
+        Let $x= j \times a$ be such a number, where $2 \le a \le i / j$
+        Now, after sieving from primes $\le j - 1$,
+        a must remain
+        (because x, and hence a has no prime factor $\le j - 1$)
+        Clearly, there are phi(i / j, j - 1) such a
+        which remain on sieving from primes $\le j - 1$
+
+        Now, if a is a prime less than equal to j - 1,
+        $x= j \times a$ has smallest prime factor = a, and
+        has already been removed(by sieving from a).
+        So, we do not need to remove it again.
+        (Note: there will be pi(j - 1) such x)
+
+        Thus, number of x, that will be removed are:
+        phi(i / j, j - 1) - phi(j - 1, j - 1)
+        (Note that pi(j - 1) = phi(j - 1, j - 1))
+
+        $\Rightarrow$ phi(i,j) = phi(i, j - 1) - phi(i / j, j - 1) + phi(j - 1, j - 1)
+
+        So,following recursion is used and implemented as dp:
+
+        phi(a, b) = phi(a, b - 1), if b is not a prime
+        phi(a, b) = phi(a, b-1)-phi(a / b, b-1) + phi(b-1, b-1), if b is prime
+
+        Clearly a is always of the form floor(n / k),
+        which can take at most $2\sqrt{n}$ values.
+        Two arrays arr1,arr2 are maintained
+        arr1[i] = phi(i, j),
+        arr2[i] = phi(n // i, j)
+
+        Finally the answer is arr2[1]
+
+        Examples
+        ========
+
+        >>> from sympy import primepi, prime, prevprime, isprime
+        >>> primepi(25)
+        9
+
+        So there are 9 primes less than or equal to 25. Is 25 prime?
+
+        >>> isprime(25)
+        False
+
+        It is not. So the first prime less than 25 must be the
+        9th prime:
+
+        >>> prevprime(25) == prime(9)
+        True
+
+        See Also
+        ========
+
+        sympy.ntheory.primetest.isprime : Test if n is prime
+        primerange : Generate all primes in a given range
+        prime : Return the nth prime
+    """
+    from sympy.functions.combinatorial.numbers import primepi as func_primepi
+    return func_primepi(n)
+
+
+def _primepi(n:int) -> int:
+    r""" Represents the prime counting function pi(n) = the number
+    of prime numbers less than or equal to n.
+
+    Explanation
+    ===========
+
+    In sieve method, we remove all multiples of prime p
+    except p itself.
+
+    Let phi(i,j) be the number of integers 2 <= k <= i
+    which remain after sieving from primes less than
+    or equal to j.
+    Clearly, pi(n) = phi(n, sqrt(n))
+
+    If j is not a prime,
+    phi(i,j) = phi(i, j - 1)
+
+    if j is a prime,
+    We remove all numbers(except j) whose
+    smallest prime factor is j.
+
+    Let $x= j \times a$ be such a number, where $2 \le a \le i / j$
+    Now, after sieving from primes $\le j - 1$,
+    a must remain
+    (because x, and hence a has no prime factor $\le j - 1$)
+    Clearly, there are phi(i / j, j - 1) such a
+    which remain on sieving from primes $\le j - 1$
+
+    Now, if a is a prime less than equal to j - 1,
+    $x= j \times a$ has smallest prime factor = a, and
+    has already been removed(by sieving from a).
+    So, we do not need to remove it again.
+    (Note: there will be pi(j - 1) such x)
+
+    Thus, number of x, that will be removed are:
+    phi(i / j, j - 1) - phi(j - 1, j - 1)
+    (Note that pi(j - 1) = phi(j - 1, j - 1))
+
+    $\Rightarrow$ phi(i,j) = phi(i, j - 1) - phi(i / j, j - 1) + phi(j - 1, j - 1)
+
+    So,following recursion is used and implemented as dp:
+
+    phi(a, b) = phi(a, b - 1), if b is not a prime
+    phi(a, b) = phi(a, b-1)-phi(a / b, b-1) + phi(b-1, b-1), if b is prime
+
+    Clearly a is always of the form floor(n / k),
+    which can take at most $2\sqrt{n}$ values.
+    Two arrays arr1,arr2 are maintained
+    arr1[i] = phi(i, j),
+    arr2[i] = phi(n // i, j)
+
+    Finally the answer is arr2[1]
+
+    Parameters
+    ==========
+
+    n : int
+
+    """
+    if n < 2:
+        return 0
+    if n <= sieve._list[-1]:
+        return sieve.search(n)[0]
+    lim = sqrt(n)
+    arr1 = [(i + 1) >> 1 for i in range(lim + 1)]
+    arr2 = [0] + [(n//i + 1) >> 1 for i in range(1, lim + 1)]
+    skip = [False] * (lim + 1)
+    for i in range(3, lim + 1, 2):
+        # Presently, arr1[k]=phi(k,i - 1),
+        # arr2[k] = phi(n // k,i - 1) # not all k's do this
+        if skip[i]:
+            # skip if i is a composite number
+            continue
+        p = arr1[i - 1]
+        for j in range(i, lim + 1, i):
+            skip[j] = True
+        # update arr2
+        # phi(n/j, i) = phi(n/j, i-1) - phi(n/(i*j), i-1) + phi(i-1, i-1)
+        for j in range(1, min(n // (i * i), lim) + 1, 2):
+            # No need for arr2[j] in j such that skip[j] is True to
+            # compute the final required arr2[1].
+            if skip[j]:
+                continue
+            st = i * j
+            if st <= lim:
+                arr2[j] -= arr2[st] - p
+            else:
+                arr2[j] -= arr1[n // st] - p
+        # update arr1
+        # phi(j, i) = phi(j, i-1) - phi(j/i, i-1) + phi(i-1, i-1)
+        # where the range below i**2 is fixed and
+        # does not need to be calculated.
+        for j in range(lim, min(lim, i*i - 1), -1):
+            arr1[j] -= arr1[j // i] - p
+    return arr2[1]
+
+
+def nextprime(n, ith=1):
+    """ Return the ith prime greater than n.
+
+        Parameters
+        ==========
+
+        n : integer
+        ith : positive integer
+
+        Returns
+        =======
+
+        int : Return the ith prime greater than n
+
+        Raises
+        ======
+
+        ValueError
+            If ``ith <= 0``.
+            If ``n`` or ``ith`` is not an integer.
+
+        Notes
+        =====
+
+        Potential primes are located at 6*j +/- 1. This
+        property is used during searching.
+
+        >>> from sympy import nextprime
+        >>> [(i, nextprime(i)) for i in range(10, 15)]
+        [(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)]
+        >>> nextprime(2, ith=2) # the 2nd prime after 2
+        5
+
+        See Also
+        ========
+
+        prevprime : Return the largest prime smaller than n
+        primerange : Generate all primes in a given range
+
+    """
+    n = int(n)
+    i = as_int(ith)
+    if i <= 0:
+        raise ValueError("ith should be positive")
+    if n < 2:
+        n = 2
+        i -= 1
+    if n <= sieve._list[-2]:
+        l, _ = sieve.search(n)
+        if l + i - 1 < len(sieve._list):
+            return sieve._list[l + i - 1]
+        n = sieve._list[-1]
+        i += l - len(sieve._list)
+    nn = 6*(n//6)
+    if nn == n:
+        n += 1
+        if isprime(n):
+            i -= 1
+            if not i:
+                return n
+        n += 4
+    elif n - nn == 5:
+        n += 2
+        if isprime(n):
+            i -= 1
+            if not i:
+                return n
+        n += 4
+    else:
+        n = nn + 5
+    while 1:
+        if isprime(n):
+            i -= 1
+            if not i:
+                return n
+        n += 2
+        if isprime(n):
+            i -= 1
+            if not i:
+                return n
+        n += 4
+
+
+def prevprime(n):
+    """ Return the largest prime smaller than n.
+
+        Notes
+        =====
+
+        Potential primes are located at 6*j +/- 1. This
+        property is used during searching.
+
+        >>> from sympy import prevprime
+        >>> [(i, prevprime(i)) for i in range(10, 15)]
+        [(10, 7), (11, 7), (12, 11), (13, 11), (14, 13)]
+
+        See Also
+        ========
+
+        nextprime : Return the ith prime greater than n
+        primerange : Generates all primes in a given range
+    """
+    n = _as_int_ceiling(n)
+    if n < 3:
+        raise ValueError("no preceding primes")
+    if n < 8:
+        return {3: 2, 4: 3, 5: 3, 6: 5, 7: 5}[n]
+    if n <= sieve._list[-1]:
+        l, u = sieve.search(n)
+        if l == u:
+            return sieve[l-1]
+        else:
+            return sieve[l]
+    nn = 6*(n//6)
+    if n - nn <= 1:
+        n = nn - 1
+        if isprime(n):
+            return n
+        n -= 4
+    else:
+        n = nn + 1
+    while 1:
+        if isprime(n):
+            return n
+        n -= 2
+        if isprime(n):
+            return n
+        n -= 4
+
+
+def primerange(a, b=None):
+    """ Generate a list of all prime numbers in the range [2, a),
+        or [a, b).
+
+        If the range exists in the default sieve, the values will
+        be returned from there; otherwise values will be returned
+        but will not modify the sieve.
+
+        Examples
+        ========
+
+        >>> from sympy import primerange, prime
+
+        All primes less than 19:
+
+        >>> list(primerange(19))
+        [2, 3, 5, 7, 11, 13, 17]
+
+        All primes greater than or equal to 7 and less than 19:
+
+        >>> list(primerange(7, 19))
+        [7, 11, 13, 17]
+
+        All primes through the 10th prime
+
+        >>> list(primerange(prime(10) + 1))
+        [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
+
+        The Sieve method, primerange, is generally faster but it will
+        occupy more memory as the sieve stores values. The default
+        instance of Sieve, named sieve, can be used:
+
+        >>> from sympy import sieve
+        >>> list(sieve.primerange(1, 30))
+        [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
+
+        Notes
+        =====
+
+        Some famous conjectures about the occurrence of primes in a given
+        range are [1]:
+
+        - Twin primes: though often not, the following will give 2 primes
+                    an infinite number of times:
+                        primerange(6*n - 1, 6*n + 2)
+        - Legendre's: the following always yields at least one prime
+                        primerange(n**2, (n+1)**2+1)
+        - Bertrand's (proven): there is always a prime in the range
+                        primerange(n, 2*n)
+        - Brocard's: there are at least four primes in the range
+                        primerange(prime(n)**2, prime(n+1)**2)
+
+        The average gap between primes is log(n) [2]; the gap between
+        primes can be arbitrarily large since sequences of composite
+        numbers are arbitrarily large, e.g. the numbers in the sequence
+        n! + 2, n! + 3 ... n! + n are all composite.
+
+        See Also
+        ========
+
+        prime : Return the nth prime
+        nextprime : Return the ith prime greater than n
+        prevprime : Return the largest prime smaller than n
+        randprime : Returns a random prime in a given range
+        primorial : Returns the product of primes based on condition
+        Sieve.primerange : return range from already computed primes
+                           or extend the sieve to contain the requested
+                           range.
+
+        References
+        ==========
+
+        .. [1] https://en.wikipedia.org/wiki/Prime_number
+        .. [2] https://primes.utm.edu/notes/gaps.html
+    """
+    if b is None:
+        a, b = 2, a
+    if a >= b:
+        return
+    # If we already have the range, return it.
+    largest_known_prime = sieve._list[-1]
+    if b <= largest_known_prime:
+        yield from sieve.primerange(a, b)
+        return
+    # If we know some of it, return it.
+    if a <= largest_known_prime:
+        yield from sieve._list[bisect_left(sieve._list, a):]
+        a = largest_known_prime + 1
+    elif a % 2:
+        a -= 1
+    tail = min(b, (largest_known_prime)**2)
+    if a < tail:
+        yield from sieve._primerange(a, tail)
+        a = tail
+    if b <= a:
+        return
+    # otherwise compute, without storing, the desired range.
+    while 1:
+        a = nextprime(a)
+        if a < b:
+            yield a
+        else:
+            return
+
+
+def randprime(a, b):
+    """ Return a random prime number in the range [a, b).
+
+        Bertrand's postulate assures that
+        randprime(a, 2*a) will always succeed for a > 1.
+
+        Note that due to implementation difficulties,
+        the prime numbers chosen are not uniformly random.
+        For example, there are two primes in the range [112, 128),
+        ``113`` and ``127``, but ``randprime(112, 128)`` returns ``127``
+        with a probability of 15/17.
+
+        Examples
+        ========
+
+        >>> from sympy import randprime, isprime
+        >>> randprime(1, 30) #doctest: +SKIP
+        13
+        >>> isprime(randprime(1, 30))
+        True
+
+        See Also
+        ========
+
+        primerange : Generate all primes in a given range
+
+        References
+        ==========
+
+        .. [1] https://en.wikipedia.org/wiki/Bertrand's_postulate
+
+    """
+    if a >= b:
+        return
+    a, b = map(int, (a, b))
+    n = randint(a - 1, b)
+    p = nextprime(n)
+    if p >= b:
+        p = prevprime(b)
+    if p < a:
+        raise ValueError("no primes exist in the specified range")
+    return p
+
+
+def primorial(n, nth=True):
+    """
+    Returns the product of the first n primes (default) or
+    the primes less than or equal to n (when ``nth=False``).
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.generate import primorial, primerange
+    >>> from sympy import factorint, Mul, primefactors, sqrt
+    >>> primorial(4) # the first 4 primes are 2, 3, 5, 7
+    210
+    >>> primorial(4, nth=False) # primes <= 4 are 2 and 3
+    6
+    >>> primorial(1)
+    2
+    >>> primorial(1, nth=False)
+    1
+    >>> primorial(sqrt(101), nth=False)
+    210
+
+    One can argue that the primes are infinite since if you take
+    a set of primes and multiply them together (e.g. the primorial) and
+    then add or subtract 1, the result cannot be divided by any of the
+    original factors, hence either 1 or more new primes must divide this
+    product of primes.
+
+    In this case, the number itself is a new prime:
+
+    >>> factorint(primorial(4) + 1)
+    {211: 1}
+
+    In this case two new primes are the factors:
+
+    >>> factorint(primorial(4) - 1)
+    {11: 1, 19: 1}
+
+    Here, some primes smaller and larger than the primes multiplied together
+    are obtained:
+
+    >>> p = list(primerange(10, 20))
+    >>> sorted(set(primefactors(Mul(*p) + 1)).difference(set(p)))
+    [2, 5, 31, 149]
+
+    See Also
+    ========
+
+    primerange : Generate all primes in a given range
+
+    """
+    if nth:
+        n = as_int(n)
+    else:
+        n = int(n)
+    if n < 1:
+        raise ValueError("primorial argument must be >= 1")
+    p = 1
+    if nth:
+        for i in range(1, n + 1):
+            p *= prime(i)
+    else:
+        for i in primerange(2, n + 1):
+            p *= i
+    return p
+
+
+def cycle_length(f, x0, nmax=None, values=False):
+    """For a given iterated sequence, return a generator that gives
+    the length of the iterated cycle (lambda) and the length of terms
+    before the cycle begins (mu); if ``values`` is True then the
+    terms of the sequence will be returned instead. The sequence is
+    started with value ``x0``.
+
+    Note: more than the first lambda + mu terms may be returned and this
+    is the cost of cycle detection with Brent's method; there are, however,
+    generally less terms calculated than would have been calculated if the
+    proper ending point were determined, e.g. by using Floyd's method.
+
+    >>> from sympy.ntheory.generate import cycle_length
+
+    This will yield successive values of i <-- func(i):
+
+        >>> def gen(func, i):
+        ...     while 1:
+        ...         yield i
+        ...         i = func(i)
+        ...
+
+    A function is defined:
+
+        >>> func = lambda i: (i**2 + 1) % 51
+
+    and given a seed of 4 and the mu and lambda terms calculated:
+
+        >>> next(cycle_length(func, 4))
+        (6, 3)
+
+    We can see what is meant by looking at the output:
+
+        >>> iter = cycle_length(func, 4, values=True)
+        >>> list(iter)
+        [4, 17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]
+
+    There are 6 repeating values after the first 3.
+
+    If a sequence is suspected of being longer than you might wish, ``nmax``
+    can be used to exit early (and mu will be returned as None):
+
+        >>> next(cycle_length(func, 4, nmax = 4))
+        (4, None)
+        >>> list(cycle_length(func, 4, nmax = 4, values=True))
+        [4, 17, 35, 2]
+
+    Code modified from:
+        https://en.wikipedia.org/wiki/Cycle_detection.
+    """
+
+    nmax = int(nmax or 0)
+
+    # main phase: search successive powers of two
+    power = lam = 1
+    tortoise, hare = x0, f(x0)  # f(x0) is the element/node next to x0.
+    i = 1
+    if values:
+        yield tortoise
+    while tortoise != hare and (not nmax or i < nmax):
+        i += 1
+        if power == lam:   # time to start a new power of two?
+            tortoise = hare
+            power *= 2
+            lam = 0
+        if values:
+            yield hare
+        hare = f(hare)
+        lam += 1
+    if nmax and i == nmax:
+        if values:
+            return
+        else:
+            yield nmax, None
+            return
+    if not values:
+        # Find the position of the first repetition of length lambda
+        mu = 0
+        tortoise = hare = x0
+        for i in range(lam):
+            hare = f(hare)
+        while tortoise != hare:
+            tortoise = f(tortoise)
+            hare = f(hare)
+            mu += 1
+        yield lam, mu
+
+
+def composite(nth):
+    """ Return the nth composite number, with the composite numbers indexed as
+        composite(1) = 4, composite(2) = 6, etc....
+
+        Examples
+        ========
+
+        >>> from sympy import composite
+        >>> composite(36)
+        52
+        >>> composite(1)
+        4
+        >>> composite(17737)
+        20000
+
+        See Also
+        ========
+
+        sympy.ntheory.primetest.isprime : Test if n is prime
+        primerange : Generate all primes in a given range
+        primepi : Return the number of primes less than or equal to n
+        prime : Return the nth prime
+        compositepi : Return the number of positive composite numbers less than or equal to n
+    """
+    n = as_int(nth)
+    if n < 1:
+        raise ValueError("nth must be a positive integer; composite(1) == 4")
+    composite_arr = [4, 6, 8, 9, 10, 12, 14, 15, 16, 18]
+    if n <= 10:
+        return composite_arr[n - 1]
+
+    a, b = 4, sieve._list[-1]
+    if n <= b - _primepi(b) - 1:
+        while a < b - 1:
+            mid = (a + b) >> 1
+            if mid - _primepi(mid) - 1 > n:
+                b = mid
+            else:
+                a = mid
+        if isprime(a):
+            a -= 1
+        return a
+
+    from sympy.functions.elementary.exponential import log
+    from sympy.functions.special.error_functions import li
+    a = 4 # Lower bound for binary search
+    b = int(n*(log(n) + log(log(n)))) # Upper bound for the search.
+
+    while a < b:
+        mid = (a + b) >> 1
+        if mid - li(mid) - 1 > n:
+            b = mid
+        else:
+            a = mid + 1
+
+    n_composites = a - _primepi(a) - 1
+    while n_composites > n:
+        if not isprime(a):
+            n_composites -= 1
+        a -= 1
+    if isprime(a):
+        a -= 1
+    return a
+
+
+def compositepi(n):
+    """ Return the number of positive composite numbers less than or equal to n.
+        The first positive composite is 4, i.e. compositepi(4) = 1.
+
+        Examples
+        ========
+
+        >>> from sympy import compositepi
+        >>> compositepi(25)
+        15
+        >>> compositepi(1000)
+        831
+
+        See Also
+        ========
+
+        sympy.ntheory.primetest.isprime : Test if n is prime
+        primerange : Generate all primes in a given range
+        prime : Return the nth prime
+        primepi : Return the number of primes less than or equal to n
+        composite : Return the nth composite number
+    """
+    n = int(n)
+    if n < 4:
+        return 0
+    return n - _primepi(n) - 1
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/modular.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/modular.py
new file mode 100644
index 0000000000000000000000000000000000000000..628a3d8c5a7fb4b6c51ad337df66d74f90282496
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/modular.py
@@ -0,0 +1,291 @@
+from math import prod
+
+from sympy.external.gmpy import gcd, gcdext
+from sympy.ntheory.primetest import isprime
+from sympy.polys.domains import ZZ
+from sympy.polys.galoistools import gf_crt, gf_crt1, gf_crt2
+from sympy.utilities.misc import as_int
+
+
+def symmetric_residue(a, m):
+    """Return the residual mod m such that it is within half of the modulus.
+
+    >>> from sympy.ntheory.modular import symmetric_residue
+    >>> symmetric_residue(1, 6)
+    1
+    >>> symmetric_residue(4, 6)
+    -2
+    """
+    if a <= m // 2:
+        return a
+    return a - m
+
+
+def crt(m, v, symmetric=False, check=True):
+    r"""Chinese Remainder Theorem.
+
+    The moduli in m are assumed to be pairwise coprime.  The output
+    is then an integer f, such that f = v_i mod m_i for each pair out
+    of v and m. If ``symmetric`` is False a positive integer will be
+    returned, else \|f\| will be less than or equal to the LCM of the
+    moduli, and thus f may be negative.
+
+    If the moduli are not co-prime the correct result will be returned
+    if/when the test of the result is found to be incorrect. This result
+    will be None if there is no solution.
+
+    The keyword ``check`` can be set to False if it is known that the moduli
+    are coprime.
+
+    Examples
+    ========
+
+    As an example consider a set of residues ``U = [49, 76, 65]``
+    and a set of moduli ``M = [99, 97, 95]``. Then we have::
+
+       >>> from sympy.ntheory.modular import crt
+
+       >>> crt([99, 97, 95], [49, 76, 65])
+       (639985, 912285)
+
+    This is the correct result because::
+
+       >>> [639985 % m for m in [99, 97, 95]]
+       [49, 76, 65]
+
+    If the moduli are not co-prime, you may receive an incorrect result
+    if you use ``check=False``:
+
+       >>> crt([12, 6, 17], [3, 4, 2], check=False)
+       (954, 1224)
+       >>> [954 % m for m in [12, 6, 17]]
+       [6, 0, 2]
+       >>> crt([12, 6, 17], [3, 4, 2]) is None
+       True
+       >>> crt([3, 6], [2, 5])
+       (5, 6)
+
+    Note: the order of gf_crt's arguments is reversed relative to crt,
+    and that solve_congruence takes residue, modulus pairs.
+
+    Programmer's note: rather than checking that all pairs of moduli share
+    no GCD (an O(n**2) test) and rather than factoring all moduli and seeing
+    that there is no factor in common, a check that the result gives the
+    indicated residuals is performed -- an O(n) operation.
+
+    See Also
+    ========
+
+    solve_congruence
+    sympy.polys.galoistools.gf_crt : low level crt routine used by this routine
+    """
+    if check:
+        m = list(map(as_int, m))
+        v = list(map(as_int, v))
+
+    result = gf_crt(v, m, ZZ)
+    mm = prod(m)
+
+    if check:
+        if not all(v % m == result % m for v, m in zip(v, m)):
+            result = solve_congruence(*list(zip(v, m)),
+                    check=False, symmetric=symmetric)
+            if result is None:
+                return result
+            result, mm = result
+
+    if symmetric:
+        return int(symmetric_residue(result, mm)), int(mm)
+    return int(result), int(mm)
+
+
+def crt1(m):
+    """First part of Chinese Remainder Theorem, for multiple application.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.modular import crt, crt1, crt2
+    >>> m = [99, 97, 95]
+    >>> v = [49, 76, 65]
+
+    The following two codes have the same result.
+
+    >>> crt(m, v)
+    (639985, 912285)
+
+    >>> mm, e, s = crt1(m)
+    >>> crt2(m, v, mm, e, s)
+    (639985, 912285)
+
+    However, it is faster when we want to fix ``m`` and
+    compute for multiple ``v``, i.e. the following cases:
+
+    >>> mm, e, s = crt1(m)
+    >>> vs = [[52, 21, 37], [19, 46, 76]]
+    >>> for v in vs:
+    ...     print(crt2(m, v, mm, e, s))
+    (397042, 912285)
+    (803206, 912285)
+
+    See Also
+    ========
+
+    sympy.polys.galoistools.gf_crt1 : low level crt routine used by this routine
+    sympy.ntheory.modular.crt
+    sympy.ntheory.modular.crt2
+
+    """
+
+    return gf_crt1(m, ZZ)
+
+
+def crt2(m, v, mm, e, s, symmetric=False):
+    """Second part of Chinese Remainder Theorem, for multiple application.
+
+    See ``crt1`` for usage.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.modular import crt1, crt2
+    >>> mm, e, s = crt1([18, 42, 6])
+    >>> crt2([18, 42, 6], [0, 0, 0], mm, e, s)
+    (0, 4536)
+
+    See Also
+    ========
+
+    sympy.polys.galoistools.gf_crt2 : low level crt routine used by this routine
+    sympy.ntheory.modular.crt
+    sympy.ntheory.modular.crt1
+
+    """
+
+    result = gf_crt2(v, m, mm, e, s, ZZ)
+
+    if symmetric:
+        return int(symmetric_residue(result, mm)), int(mm)
+    return int(result), int(mm)
+
+
+def solve_congruence(*remainder_modulus_pairs, **hint):
+    """Compute the integer ``n`` that has the residual ``ai`` when it is
+    divided by ``mi`` where the ``ai`` and ``mi`` are given as pairs to
+    this function: ((a1, m1), (a2, m2), ...). If there is no solution,
+    return None. Otherwise return ``n`` and its modulus.
+
+    The ``mi`` values need not be co-prime. If it is known that the moduli are
+    not co-prime then the hint ``check`` can be set to False (default=True) and
+    the check for a quicker solution via crt() (valid when the moduli are
+    co-prime) will be skipped.
+
+    If the hint ``symmetric`` is True (default is False), the value of ``n``
+    will be within 1/2 of the modulus, possibly negative.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.modular import solve_congruence
+
+    What number is 2 mod 3, 3 mod 5 and 2 mod 7?
+
+    >>> solve_congruence((2, 3), (3, 5), (2, 7))
+    (23, 105)
+    >>> [23 % m for m in [3, 5, 7]]
+    [2, 3, 2]
+
+    If you prefer to work with all remainder in one list and
+    all moduli in another, send the arguments like this:
+
+    >>> solve_congruence(*zip((2, 3, 2), (3, 5, 7)))
+    (23, 105)
+
+    The moduli need not be co-prime; in this case there may or
+    may not be a solution:
+
+    >>> solve_congruence((2, 3), (4, 6)) is None
+    True
+
+    >>> solve_congruence((2, 3), (5, 6))
+    (5, 6)
+
+    The symmetric flag will make the result be within 1/2 of the modulus:
+
+    >>> solve_congruence((2, 3), (5, 6), symmetric=True)
+    (-1, 6)
+
+    See Also
+    ========
+
+    crt : high level routine implementing the Chinese Remainder Theorem
+
+    """
+    def combine(c1, c2):
+        """Return the tuple (a, m) which satisfies the requirement
+        that n = a + i*m satisfy n = a1 + j*m1 and n = a2 = k*m2.
+
+        References
+        ==========
+
+        .. [1] https://en.wikipedia.org/wiki/Method_of_successive_substitution
+        """
+        a1, m1 = c1
+        a2, m2 = c2
+        a, b, c = m1, a2 - a1, m2
+        g = gcd(a, b, c)
+        a, b, c = [i//g for i in [a, b, c]]
+        if a != 1:
+            g, inv_a, _ = gcdext(a, c)
+            if g != 1:
+                return None
+            b *= inv_a
+        a, m = a1 + m1*b, m1*c
+        return a, m
+
+    rm = remainder_modulus_pairs
+    symmetric = hint.get('symmetric', False)
+
+    if hint.get('check', True):
+        rm = [(as_int(r), as_int(m)) for r, m in rm]
+
+        # ignore redundant pairs but raise an error otherwise; also
+        # make sure that a unique set of bases is sent to gf_crt if
+        # they are all prime.
+        #
+        # The routine will work out less-trivial violations and
+        # return None, e.g. for the pairs (1,3) and (14,42) there
+        # is no answer because 14 mod 42 (having a gcd of 14) implies
+        # (14/2) mod (42/2), (14/7) mod (42/7) and (14/14) mod (42/14)
+        # which, being 0 mod 3, is inconsistent with 1 mod 3. But to
+        # preprocess the input beyond checking of another pair with 42
+        # or 3 as the modulus (for this example) is not necessary.
+        uniq = {}
+        for r, m in rm:
+            r %= m
+            if m in uniq:
+                if r != uniq[m]:
+                    return None
+                continue
+            uniq[m] = r
+        rm = [(r, m) for m, r in uniq.items()]
+        del uniq
+
+        # if the moduli are co-prime, the crt will be significantly faster;
+        # checking all pairs for being co-prime gets to be slow but a prime
+        # test is a good trade-off
+        if all(isprime(m) for r, m in rm):
+            r, m = list(zip(*rm))
+            return crt(m, r, symmetric=symmetric, check=False)
+
+    rv = (0, 1)
+    for rmi in rm:
+        rv = combine(rv, rmi)
+        if rv is None:
+            break
+        n, m = rv
+        n = n % m
+    else:
+        if symmetric:
+            return symmetric_residue(n, m), m
+        return n, m
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/multinomial.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/multinomial.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ec50fdb533be547b9a8e60dc47568965bf89436
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/multinomial.py
@@ -0,0 +1,188 @@
+from sympy.utilities.misc import as_int
+
+
+def binomial_coefficients(n):
+    """Return a dictionary containing pairs :math:`{(k1,k2) : C_kn}` where
+    :math:`C_kn` are binomial coefficients and :math:`n=k1+k2`.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory import binomial_coefficients
+    >>> binomial_coefficients(9)
+    {(0, 9): 1, (1, 8): 9, (2, 7): 36, (3, 6): 84,
+     (4, 5): 126, (5, 4): 126, (6, 3): 84, (7, 2): 36, (8, 1): 9, (9, 0): 1}
+
+    See Also
+    ========
+
+    binomial_coefficients_list, multinomial_coefficients
+    """
+    n = as_int(n)
+    d = {(0, n): 1, (n, 0): 1}
+    a = 1
+    for k in range(1, n//2 + 1):
+        a = (a * (n - k + 1))//k
+        d[k, n - k] = d[n - k, k] = a
+    return d
+
+
+def binomial_coefficients_list(n):
+    """ Return a list of binomial coefficients as rows of the Pascal's
+    triangle.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory import binomial_coefficients_list
+    >>> binomial_coefficients_list(9)
+    [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
+
+    See Also
+    ========
+
+    binomial_coefficients, multinomial_coefficients
+    """
+    n = as_int(n)
+    d = [1] * (n + 1)
+    a = 1
+    for k in range(1, n//2 + 1):
+        a = (a * (n - k + 1))//k
+        d[k] = d[n - k] = a
+    return d
+
+
+def multinomial_coefficients(m, n):
+    r"""Return a dictionary containing pairs ``{(k1,k2,..,km) : C_kn}``
+    where ``C_kn`` are multinomial coefficients such that
+    ``n=k1+k2+..+km``.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory import multinomial_coefficients
+    >>> multinomial_coefficients(2, 5) # indirect doctest
+    {(0, 5): 1, (1, 4): 5, (2, 3): 10, (3, 2): 10, (4, 1): 5, (5, 0): 1}
+
+    Notes
+    =====
+
+    The algorithm is based on the following result:
+
+    .. math::
+        \binom{n}{k_1, \ldots, k_m} =
+        \frac{k_1 + 1}{n - k_1} \sum_{i=2}^m \binom{n}{k_1 + 1, \ldots, k_i - 1, \ldots}
+
+    Code contributed to Sage by Yann Laigle-Chapuy, copied with permission
+    of the author.
+
+    See Also
+    ========
+
+    binomial_coefficients_list, binomial_coefficients
+    """
+    m = as_int(m)
+    n = as_int(n)
+    if not m:
+        if n:
+            return {}
+        return {(): 1}
+    if m == 2:
+        return binomial_coefficients(n)
+    if m >= 2*n and n > 1:
+        return dict(multinomial_coefficients_iterator(m, n))
+    t = [n] + [0] * (m - 1)
+    r = {tuple(t): 1}
+    if n:
+        j = 0  # j will be the leftmost nonzero position
+    else:
+        j = m
+    # enumerate tuples in co-lex order
+    while j < m - 1:
+        # compute next tuple
+        tj = t[j]
+        if j:
+            t[j] = 0
+            t[0] = tj
+        if tj > 1:
+            t[j + 1] += 1
+            j = 0
+            start = 1
+            v = 0
+        else:
+            j += 1
+            start = j + 1
+            v = r[tuple(t)]
+            t[j] += 1
+        # compute the value
+        # NB: the initialization of v was done above
+        for k in range(start, m):
+            if t[k]:
+                t[k] -= 1
+                v += r[tuple(t)]
+                t[k] += 1
+        t[0] -= 1
+        r[tuple(t)] = (v * tj) // (n - t[0])
+    return r
+
+
+def multinomial_coefficients_iterator(m, n, _tuple=tuple):
+    """multinomial coefficient iterator
+
+    This routine has been optimized for `m` large with respect to `n` by taking
+    advantage of the fact that when the monomial tuples `t` are stripped of
+    zeros, their coefficient is the same as that of the monomial tuples from
+    ``multinomial_coefficients(n, n)``. Therefore, the latter coefficients are
+    precomputed to save memory and time.
+
+    >>> from sympy.ntheory.multinomial import multinomial_coefficients
+    >>> m53, m33 = multinomial_coefficients(5,3), multinomial_coefficients(3,3)
+    >>> m53[(0,0,0,1,2)] == m53[(0,0,1,0,2)] == m53[(1,0,2,0,0)] == m33[(0,1,2)]
+    True
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.multinomial import multinomial_coefficients_iterator
+    >>> it = multinomial_coefficients_iterator(20,3)
+    >>> next(it)
+    ((3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), 1)
+    """
+    m = as_int(m)
+    n = as_int(n)
+    if m < 2*n or n == 1:
+        mc = multinomial_coefficients(m, n)
+        yield from mc.items()
+    else:
+        mc = multinomial_coefficients(n, n)
+        mc1 = {}
+        for k, v in mc.items():
+            mc1[_tuple(filter(None, k))] = v
+        mc = mc1
+
+        t = [n] + [0] * (m - 1)
+        t1 = _tuple(t)
+        b = _tuple(filter(None, t1))
+        yield (t1, mc[b])
+        if n:
+            j = 0  # j will be the leftmost nonzero position
+        else:
+            j = m
+        # enumerate tuples in co-lex order
+        while j < m - 1:
+            # compute next tuple
+            tj = t[j]
+            if j:
+                t[j] = 0
+                t[0] = tj
+            if tj > 1:
+                t[j + 1] += 1
+                j = 0
+            else:
+                j += 1
+                t[j] += 1
+
+            t[0] -= 1
+            t1 = _tuple(t)
+            b = _tuple(filter(None, t1))
+            yield (t1, mc[b])
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/partitions_.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/partitions_.py
new file mode 100644
index 0000000000000000000000000000000000000000..953fa9e2fef146b0d3a9baad0ec5e1353ad6f237
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/partitions_.py
@@ -0,0 +1,277 @@
+from mpmath.libmp import (fzero, from_int, from_rational,
+    fone, fhalf, bitcount, to_int, mpf_mul, mpf_div, mpf_sub,
+    mpf_add, mpf_sqrt, mpf_pi, mpf_cosh_sinh, mpf_cos, mpf_sin)
+from .residue_ntheory import _sqrt_mod_prime_power, is_quad_residue
+from sympy.utilities.decorator import deprecated
+from sympy.utilities.memoization import recurrence_memo
+
+import math
+from itertools import count
+
+def _pre():
+    maxn = 10**5
+    global _factor, _totient
+    _factor = [0]*maxn
+    _totient = [1]*maxn
+    lim = int(maxn**0.5) + 5
+    for i in range(2, lim):
+        if _factor[i] == 0:
+            for j in range(i*i, maxn, i):
+                if _factor[j] == 0:
+                    _factor[j] = i
+    for i in range(2, maxn):
+        if _factor[i] == 0:
+            _factor[i] = i
+            _totient[i] = i-1
+            continue
+        x = _factor[i]
+        y = i//x
+        if y % x == 0:
+            _totient[i] = _totient[y]*x
+        else:
+            _totient[i] = _totient[y]*(x - 1)
+
+def _a(n, k, prec):
+    """ Compute the inner sum in HRR formula [1]_
+
+    References
+    ==========
+
+    .. [1] https://msp.org/pjm/1956/6-1/pjm-v6-n1-p18-p.pdf
+
+    """
+    if k == 1:
+        return fone
+
+    k1 = k
+    e = 0
+    p = _factor[k]
+    while k1 % p == 0:
+        k1 //= p
+        e += 1
+    k2 = k//k1 # k2 = p^e
+    v = 1 - 24*n
+    pi = mpf_pi(prec)
+
+    if k1 == 1:
+        # k  = p^e
+        if p == 2:
+            mod = 8*k
+            v = mod + v % mod
+            v = (v*pow(9, k - 1, mod)) % mod
+            m = _sqrt_mod_prime_power(v, 2, e + 3)[0]
+            arg = mpf_div(mpf_mul(
+                from_int(4*m), pi, prec), from_int(mod), prec)
+            return mpf_mul(mpf_mul(
+                from_int((-1)**e*(2 - (m % 4))),
+                mpf_sqrt(from_int(k), prec), prec),
+                mpf_sin(arg, prec), prec)
+        if p == 3:
+            mod = 3*k
+            v = mod + v % mod
+            if e > 1:
+                v = (v*pow(64, k//3 - 1, mod)) % mod
+            m = _sqrt_mod_prime_power(v, 3, e + 1)[0]
+            arg = mpf_div(mpf_mul(from_int(4*m), pi, prec),
+                from_int(mod), prec)
+            return mpf_mul(mpf_mul(
+                from_int(2*(-1)**(e + 1)*(3 - 2*(m % 3))),
+                mpf_sqrt(from_int(k//3), prec), prec),
+                mpf_sin(arg, prec), prec)
+        v = k + v % k
+        jacobi3 = -1 if k % 12 in [5, 7] else 1
+        if v % p == 0:
+            if e == 1:
+                return mpf_mul(
+                    from_int(jacobi3),
+                    mpf_sqrt(from_int(k), prec), prec)
+            return fzero
+        if not is_quad_residue(v, p):
+            return fzero
+        _phi = p**(e - 1)*(p - 1)
+        v = (v*pow(576, _phi - 1, k))
+        m = _sqrt_mod_prime_power(v, p, e)[0]
+        arg = mpf_div(
+            mpf_mul(from_int(4*m), pi, prec),
+            from_int(k), prec)
+        return mpf_mul(mpf_mul(
+            from_int(2*jacobi3),
+            mpf_sqrt(from_int(k), prec), prec),
+            mpf_cos(arg, prec), prec)
+
+    if p != 2 or e >= 3:
+        d1, d2 = math.gcd(k1, 24), math.gcd(k2, 24)
+        e = 24//(d1*d2)
+        n1 = ((d2*e*n + (k2**2 - 1)//d1)*
+            pow(e*k2*k2*d2, _totient[k1] - 1, k1)) % k1
+        n2 = ((d1*e*n + (k1**2 - 1)//d2)*
+            pow(e*k1*k1*d1, _totient[k2] - 1, k2)) % k2
+        return mpf_mul(_a(n1, k1, prec), _a(n2, k2, prec), prec)
+    if e == 2:
+        n1 = ((8*n + 5)*pow(128, _totient[k1] - 1, k1)) % k1
+        n2 = (4 + ((n - 2 - (k1**2 - 1)//8)*(k1**2)) % 4) % 4
+        return mpf_mul(mpf_mul(
+            from_int(-1),
+            _a(n1, k1, prec), prec),
+            _a(n2, k2, prec))
+    n1 = ((8*n + 1)*pow(32, _totient[k1] - 1, k1)) % k1
+    n2 = (2 + (n - (k1**2 - 1)//8) % 2) % 2
+    return mpf_mul(_a(n1, k1, prec), _a(n2, k2, prec), prec)
+
+def _d(n, j, prec, sq23pi, sqrt8):
+    """
+    Compute the sinh term in the outer sum of the HRR formula.
+    The constants sqrt(2/3*pi) and sqrt(8) must be precomputed.
+    """
+    j = from_int(j)
+    pi = mpf_pi(prec)
+    a = mpf_div(sq23pi, j, prec)
+    b = mpf_sub(from_int(n), from_rational(1, 24, prec), prec)
+    c = mpf_sqrt(b, prec)
+    ch, sh = mpf_cosh_sinh(mpf_mul(a, c), prec)
+    D = mpf_div(
+        mpf_sqrt(j, prec),
+        mpf_mul(mpf_mul(sqrt8, b), pi), prec)
+    E = mpf_sub(mpf_mul(a, ch), mpf_div(sh, c, prec), prec)
+    return mpf_mul(D, E)
+
+
+@recurrence_memo([1, 1])
+def _partition_rec(n: int, prev) -> int:
+    """ Calculate the partition function P(n)
+
+    Parameters
+    ==========
+
+    n : int
+        nonnegative integer
+
+    """
+    v = 0
+    penta = 0 # pentagonal number: 1, 5, 12, ...
+    for i in count():
+        penta += 3*i + 1
+        np = n - penta
+        if np < 0:
+            break
+        s = prev[np]
+        np -= i + 1
+        # np = n - gp where gp = generalized pentagonal: 2, 7, 15, ...
+        if 0 <= np:
+            s += prev[np]
+        v += -s if i % 2 else s
+    return v
+
+
+def _partition(n: int) -> int:
+    """ Calculate the partition function P(n)
+
+    Parameters
+    ==========
+
+    n : int
+
+    """
+    if n < 0:
+        return 0
+    if (n <= 200_000 and n - _partition_rec.cache_length() < 70 or
+            _partition_rec.cache_length() == 2 and n < 14_400):
+        # There will be 2*10**5 elements created here
+        # and n elements created by partition, so in case we
+        # are going to be working with small n, we just
+        # use partition to calculate (and cache) the values
+        # since lookup is used there while summation, using
+        # _factor and _totient, will be used below. But we
+        # only do so if n is relatively close to the length
+        # of the cache since doing 1 calculation here is about
+        # the same as adding 70 elements to the cache. In addition,
+        # the startup here costs about the same as calculating the first
+        # 14,400 values via partition, so we delay startup here unless n
+        # is smaller than that.
+        return _partition_rec(n)
+    if '_factor' not in globals():
+        _pre()
+    # Estimate number of bits in p(n). This formula could be tidied
+    pbits = int((
+        math.pi*(2*n/3.)**0.5 -
+        math.log(4*n))/math.log(10) + 1) * \
+        math.log2(10)
+    prec = p = int(pbits*1.1 + 100)
+
+    # find the number of terms needed so rounded sum will be accurate
+    # using Rademacher's bound M(n, N) for the remainder after a partial
+    # sum of N terms (https://arxiv.org/pdf/1205.5991.pdf, (1.8))
+    c1 = 44*math.pi**2/(225*math.sqrt(3))
+    c2 = math.pi*math.sqrt(2)/75
+    c3 = math.pi*math.sqrt(2/3)
+    def _M(n, N):
+        sqrt = math.sqrt
+        return c1/sqrt(N) + c2*sqrt(N/(n - 1))*math.sinh(c3*sqrt(n)/N)
+    big = max(9, math.ceil(n**0.5))  # should be too large (for n > 65, ceil should work)
+    assert _M(n, big) < 0.5  # else double big until too large
+    while big > 40 and _M(n, big) < 0.5:
+        big //= 2
+    small = big
+    big = small*2
+    while big - small > 1:
+        N = (big + small)//2
+        if (er := _M(n, N)) < 0.5:
+            big = N
+        elif er >= 0.5:
+            small = N
+    M = big  # done with function M; now have value
+
+    # sanity check for expected size of answer
+    if M > 10**5:  # i.e. M > maxn
+        raise ValueError("Input too big")  # i.e. n > 149832547102
+
+    # calculate it
+    s = fzero
+    sq23pi = mpf_mul(mpf_sqrt(from_rational(2, 3, p), p), mpf_pi(p), p)
+    sqrt8 = mpf_sqrt(from_int(8), p)
+    for q in range(1, M):
+        a = _a(n, q, p)
+        d = _d(n, q, p, sq23pi, sqrt8)
+        s = mpf_add(s, mpf_mul(a, d), prec)
+        # On average, the terms decrease rapidly in magnitude.
+        # Dynamically reducing the precision greatly improves
+        # performance.
+        p = bitcount(abs(to_int(d))) + 50
+    return int(to_int(mpf_add(s, fhalf, prec)))
+
+
+@deprecated("""\
+The `sympy.ntheory.partitions_.npartitions` has been moved to `sympy.functions.combinatorial.numbers.partition`.""",
+deprecated_since_version="1.13",
+active_deprecations_target='deprecated-ntheory-symbolic-functions')
+def npartitions(n, verbose=False):
+    """
+    Calculate the partition function P(n), i.e. the number of ways that
+    n can be written as a sum of positive integers.
+
+    .. deprecated:: 1.13
+
+        The ``npartitions`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.partition`
+        instead. See its documentation for more information. See
+        :ref:`deprecated-ntheory-symbolic-functions` for details.
+
+    P(n) is computed using the Hardy-Ramanujan-Rademacher formula [1]_.
+
+
+    The correctness of this implementation has been tested through $10^{10}$.
+
+    Examples
+    ========
+
+    >>> from sympy.functions.combinatorial.numbers import partition
+    >>> partition(25)
+    1958
+
+    References
+    ==========
+
+    .. [1] https://mathworld.wolfram.com/PartitionFunctionP.html
+
+    """
+    from sympy.functions.combinatorial.numbers import partition as func_partition
+    return func_partition(n)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/primetest.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/primetest.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff3cb82cc51bf57ca345a7d72ee715c861f62e2a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/primetest.py
@@ -0,0 +1,830 @@
+"""
+Primality testing
+
+"""
+
+from itertools import count
+
+from sympy.core.sympify import sympify
+from sympy.external.gmpy import (gmpy as _gmpy, gcd, jacobi,
+                                 is_square as gmpy_is_square,
+                                 bit_scan1, is_fermat_prp, is_euler_prp,
+                                 is_selfridge_prp, is_strong_selfridge_prp,
+                                 is_strong_bpsw_prp)
+from sympy.external.ntheory import _lucas_sequence
+from sympy.utilities.misc import as_int, filldedent
+
+# Note: This list should be updated whenever new Mersenne primes are found.
+# Refer: https://www.mersenne.org/
+MERSENNE_PRIME_EXPONENTS = (2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203,
+ 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049,
+ 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583,
+ 25964951, 30402457, 32582657, 37156667, 42643801, 43112609, 57885161, 74207281, 77232917, 82589933,
+ 136279841)
+
+
+def is_fermat_pseudoprime(n, a):
+    r"""Returns True if ``n`` is prime or is an odd composite integer that
+    is coprime to ``a`` and satisfy the modular arithmetic congruence relation:
+
+    .. math ::
+        a^{n-1} \equiv 1 \pmod{n}
+
+    (where mod refers to the modulo operation).
+
+    Parameters
+    ==========
+
+    n : Integer
+        ``n`` is a positive integer.
+    a : Integer
+        ``a`` is a positive integer.
+        ``a`` and ``n`` should be relatively prime.
+
+    Returns
+    =======
+
+    bool : If ``n`` is prime, it always returns ``True``.
+           The composite number that returns ``True`` is called an Fermat pseudoprime.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.primetest import is_fermat_pseudoprime
+    >>> from sympy.ntheory.factor_ import isprime
+    >>> for n in range(1, 1000):
+    ...     if is_fermat_pseudoprime(n, 2) and not isprime(n):
+    ...         print(n)
+    341
+    561
+    645
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Fermat_pseudoprime
+    """
+    n, a = as_int(n), as_int(a)
+    if a == 1:
+        return n == 2 or bool(n % 2)
+    return is_fermat_prp(n, a)
+
+
+def is_euler_pseudoprime(n, a):
+    r"""Returns True if ``n`` is prime or is an odd composite integer that
+    is coprime to ``a`` and satisfy the modular arithmetic congruence relation:
+
+    .. math ::
+        a^{(n-1)/2} \equiv \pm 1 \pmod{n}
+
+    (where mod refers to the modulo operation).
+
+    Parameters
+    ==========
+
+    n : Integer
+        ``n`` is a positive integer.
+    a : Integer
+        ``a`` is a positive integer.
+        ``a`` and ``n`` should be relatively prime.
+
+    Returns
+    =======
+
+    bool : If ``n`` is prime, it always returns ``True``.
+           The composite number that returns ``True`` is called an Euler pseudoprime.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.primetest import is_euler_pseudoprime
+    >>> from sympy.ntheory.factor_ import isprime
+    >>> for n in range(1, 1000):
+    ...     if is_euler_pseudoprime(n, 2) and not isprime(n):
+    ...         print(n)
+    341
+    561
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Euler_pseudoprime
+    """
+    n, a = as_int(n), as_int(a)
+    if a < 1:
+        raise ValueError("a should be an integer greater than 0")
+    if n < 1:
+        raise ValueError("n should be an integer greater than 0")
+    if n == 1:
+        return False
+    if a == 1:
+        return n == 2 or bool(n % 2)  # (prime or odd composite)
+    if n % 2 == 0:
+        return n == 2
+    if gcd(n, a) != 1:
+        raise ValueError("The two numbers should be relatively prime")
+    return pow(a, (n - 1) // 2, n) in [1, n - 1]
+
+
+def is_euler_jacobi_pseudoprime(n, a):
+    r"""Returns True if ``n`` is prime or is an odd composite integer that
+    is coprime to ``a`` and satisfy the modular arithmetic congruence relation:
+
+    .. math ::
+        a^{(n-1)/2} \equiv \left(\frac{a}{n}\right) \pmod{n}
+
+    (where mod refers to the modulo operation).
+
+    Parameters
+    ==========
+
+    n : Integer
+        ``n`` is a positive integer.
+    a : Integer
+        ``a`` is a positive integer.
+        ``a`` and ``n`` should be relatively prime.
+
+    Returns
+    =======
+
+    bool : If ``n`` is prime, it always returns ``True``.
+           The composite number that returns ``True`` is called an Euler-Jacobi pseudoprime.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.primetest import is_euler_jacobi_pseudoprime
+    >>> from sympy.ntheory.factor_ import isprime
+    >>> for n in range(1, 1000):
+    ...     if is_euler_jacobi_pseudoprime(n, 2) and not isprime(n):
+    ...         print(n)
+    561
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Jacobi_pseudoprime
+    """
+    n, a = as_int(n), as_int(a)
+    if a == 1:
+        return n == 2 or bool(n % 2)
+    return is_euler_prp(n, a)
+
+
+def is_square(n, prep=True):
+    """Return True if n == a * a for some integer a, else False.
+    If n is suspected of *not* being a square then this is a
+    quick method of confirming that it is not.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.primetest import is_square
+    >>> is_square(25)
+    True
+    >>> is_square(2)
+    False
+
+    References
+    ==========
+
+    .. [1]  https://mersenneforum.org/showpost.php?p=110896
+
+    See Also
+    ========
+    sympy.core.intfunc.isqrt
+    """
+    if prep:
+        n = as_int(n)
+        if n < 0:
+            return False
+        if n in (0, 1):
+            return True
+    return gmpy_is_square(n)
+
+
+def _test(n, base, s, t):
+    """Miller-Rabin strong pseudoprime test for one base.
+    Return False if n is definitely composite, True if n is
+    probably prime, with a probability greater than 3/4.
+
+    """
+    # do the Fermat test
+    b = pow(base, t, n)
+    if b == 1 or b == n - 1:
+        return True
+    for _ in range(s - 1):
+        b = pow(b, 2, n)
+        if b == n - 1:
+            return True
+        # see I. Niven et al. "An Introduction to Theory of Numbers", page 78
+        if b == 1:
+            return False
+    return False
+
+
+def mr(n, bases):
+    """Perform a Miller-Rabin strong pseudoprime test on n using a
+    given list of bases/witnesses.
+
+    References
+    ==========
+
+    .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
+           A Computational Perspective", Springer, 2nd edition, 135-138
+
+    A list of thresholds and the bases they require are here:
+    https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Deterministic_variants
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.primetest import mr
+    >>> mr(1373651, [2, 3])
+    False
+    >>> mr(479001599, [31, 73])
+    True
+
+    """
+    from sympy.polys.domains import ZZ
+
+    n = as_int(n)
+    if n < 2 or (n > 2 and n % 2 == 0):
+        return False
+    # remove powers of 2 from n-1 (= t * 2**s)
+    s = bit_scan1(n - 1)
+    t = n >> s
+    for base in bases:
+        # Bases >= n are wrapped, bases < 2 are invalid
+        if base >= n:
+            base %= n
+        if base >= 2:
+            base = ZZ(base)
+            if not _test(n, base, s, t):
+                return False
+    return True
+
+
+def _lucas_extrastrong_params(n):
+    """Calculates the "extra strong" parameters (D, P, Q) for n.
+
+    Parameters
+    ==========
+
+    n : int
+        positive odd integer
+
+    Returns
+    =======
+
+    D, P, Q: "extra strong" parameters.
+             ``(0, 0, 0)`` if we find a nontrivial divisor of ``n``.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.primetest import _lucas_extrastrong_params
+    >>> _lucas_extrastrong_params(101)
+    (12, 4, 1)
+    >>> _lucas_extrastrong_params(15)
+    (0, 0, 0)
+
+    References
+    ==========
+    .. [1] OEIS A217719: Extra Strong Lucas Pseudoprimes
+           https://oeis.org/A217719
+    .. [2] https://en.wikipedia.org/wiki/Lucas_pseudoprime
+
+    """
+    for P in count(3):
+        D = P**2 - 4
+        j = jacobi(D, n)
+        if j == -1:
+            return (D, P, 1)
+        elif j == 0 and D % n:
+            return (0, 0, 0)
+
+
+def is_lucas_prp(n):
+    """Standard Lucas compositeness test with Selfridge parameters.  Returns
+    False if n is definitely composite, and True if n is a Lucas probable
+    prime.
+
+    This is typically used in combination with the Miller-Rabin test.
+
+    References
+    ==========
+    .. [1] Robert Baillie, Samuel S. Wagstaff, Lucas Pseudoprimes,
+           Math. Comp. Vol 35, Number 152 (1980), pp. 1391-1417,
+           https://doi.org/10.1090%2FS0025-5718-1980-0583518-6
+           http://mpqs.free.fr/LucasPseudoprimes.pdf
+    .. [2] OEIS A217120: Lucas Pseudoprimes
+           https://oeis.org/A217120
+    .. [3] https://en.wikipedia.org/wiki/Lucas_pseudoprime
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.primetest import isprime, is_lucas_prp
+    >>> for i in range(10000):
+    ...     if is_lucas_prp(i) and not isprime(i):
+    ...         print(i)
+    323
+    377
+    1159
+    1829
+    3827
+    5459
+    5777
+    9071
+    9179
+    """
+    n = as_int(n)
+    if n < 2:
+        return False
+    return is_selfridge_prp(n)
+
+
+def is_strong_lucas_prp(n):
+    """Strong Lucas compositeness test with Selfridge parameters.  Returns
+    False if n is definitely composite, and True if n is a strong Lucas
+    probable prime.
+
+    This is often used in combination with the Miller-Rabin test, and
+    in particular, when combined with M-R base 2 creates the strong BPSW test.
+
+    References
+    ==========
+    .. [1] Robert Baillie, Samuel S. Wagstaff, Lucas Pseudoprimes,
+           Math. Comp. Vol 35, Number 152 (1980), pp. 1391-1417,
+           https://doi.org/10.1090%2FS0025-5718-1980-0583518-6
+           http://mpqs.free.fr/LucasPseudoprimes.pdf
+    .. [2] OEIS A217255: Strong Lucas Pseudoprimes
+           https://oeis.org/A217255
+    .. [3] https://en.wikipedia.org/wiki/Lucas_pseudoprime
+    .. [4] https://en.wikipedia.org/wiki/Baillie-PSW_primality_test
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.primetest import isprime, is_strong_lucas_prp
+    >>> for i in range(20000):
+    ...     if is_strong_lucas_prp(i) and not isprime(i):
+    ...        print(i)
+    5459
+    5777
+    10877
+    16109
+    18971
+    """
+    n = as_int(n)
+    if n < 2:
+        return False
+    return is_strong_selfridge_prp(n)
+
+
+def is_extra_strong_lucas_prp(n):
+    """Extra Strong Lucas compositeness test.  Returns False if n is
+    definitely composite, and True if n is an "extra strong" Lucas probable
+    prime.
+
+    The parameters are selected using P = 3, Q = 1, then incrementing P until
+    (D|n) == -1.  The test itself is as defined in [1]_, from the
+    Mo and Jones preprint.  The parameter selection and test are the same as
+    used in OEIS A217719, Perl's Math::Prime::Util, and the Lucas pseudoprime
+    page on Wikipedia.
+
+    It is 20-50% faster than the strong test.
+
+    Because of the different parameters selected, there is no relationship
+    between the strong Lucas pseudoprimes and extra strong Lucas pseudoprimes.
+    In particular, one is not a subset of the other.
+
+    References
+    ==========
+    .. [1] Jon Grantham, Frobenius Pseudoprimes,
+           Math. Comp. Vol 70, Number 234 (2001), pp. 873-891,
+           https://doi.org/10.1090%2FS0025-5718-00-01197-2
+    .. [2] OEIS A217719: Extra Strong Lucas Pseudoprimes
+           https://oeis.org/A217719
+    .. [3] https://en.wikipedia.org/wiki/Lucas_pseudoprime
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.primetest import isprime, is_extra_strong_lucas_prp
+    >>> for i in range(20000):
+    ...     if is_extra_strong_lucas_prp(i) and not isprime(i):
+    ...        print(i)
+    989
+    3239
+    5777
+    10877
+    """
+    # Implementation notes:
+    #   1) the parameters differ from Thomas R. Nicely's.  His parameter
+    #      selection leads to pseudoprimes that overlap M-R tests, and
+    #      contradict Baillie and Wagstaff's suggestion of (D|n) = -1.
+    #   2) The MathWorld page as of June 2013 specifies Q=-1.  The Lucas
+    #      sequence must have Q=1.  See Grantham theorem 2.3, any of the
+    #      references on the MathWorld page, or run it and see Q=-1 is wrong.
+    n = as_int(n)
+    if n == 2:
+        return True
+    if n < 2 or (n % 2) == 0:
+        return False
+    if gmpy_is_square(n):
+        return False
+
+    D, P, Q = _lucas_extrastrong_params(n)
+    if D == 0:
+        return False
+
+    # remove powers of 2 from n+1 (= k * 2**s)
+    s = bit_scan1(n + 1)
+    k = (n + 1) >> s
+
+    U, V, _ = _lucas_sequence(n, P, Q, k)
+
+    if U == 0 and (V == 2 or V == n - 2):
+        return True
+    for _ in range(1, s):
+        if V == 0:
+            return True
+        V = (V*V - 2) % n
+    return False
+
+
+def proth_test(n):
+    r""" Test if the Proth number `n = k2^m + 1` is prime. where k is a positive odd number and `2^m > k`.
+
+    Parameters
+    ==========
+
+    n : Integer
+        ``n`` is Proth number
+
+    Returns
+    =======
+
+    bool : If ``True``, then ``n`` is the Proth prime
+
+    Raises
+    ======
+
+    ValueError
+        If ``n`` is not Proth number.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.primetest import proth_test
+    >>> proth_test(41)
+    True
+    >>> proth_test(57)
+    False
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Proth_prime
+
+    """
+    n = as_int(n)
+    if n < 3:
+        raise ValueError("n is not Proth number")
+    m = bit_scan1(n - 1)
+    k = n >> m
+    if m < k.bit_length():
+        raise ValueError("n is not Proth number")
+    if n % 3 == 0:
+        return n == 3
+    if k % 3: # n % 12 == 5
+        return pow(3, n >> 1, n) == n - 1
+    # If `n` is a square number, then `jacobi(a, n) = 1` for any `a`
+    if gmpy_is_square(n):
+        return False
+    # `a` may be chosen at random.
+    # In any case, we want to find `a` such that `jacobi(a, n) = -1`.
+    for a in range(5, n):
+        j = jacobi(a, n)
+        if j == -1:
+            return pow(a, n >> 1, n) == n - 1
+        if j == 0:
+            return False
+
+
+def _lucas_lehmer_primality_test(p):
+    r""" Test if the Mersenne number `M_p = 2^p-1` is prime.
+
+    Parameters
+    ==========
+
+    p : int
+        ``p`` is an odd prime number
+
+    Returns
+    =======
+
+    bool : If ``True``, then `M_p` is the Mersenne prime
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.primetest import _lucas_lehmer_primality_test
+    >>> _lucas_lehmer_primality_test(5) # 2**5 - 1 = 31 is prime
+    True
+    >>> _lucas_lehmer_primality_test(11) # 2**11 - 1 = 2047 is not prime
+    False
+
+    See Also
+    ========
+
+    is_mersenne_prime
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test
+
+    """
+    v = 4
+    m = 2**p - 1
+    for _ in range(p - 2):
+        v = pow(v, 2, m) - 2
+    return v == 0
+
+
+def is_mersenne_prime(n):
+    """Returns True if  ``n`` is a Mersenne prime, else False.
+
+    A Mersenne prime is a prime number having the form `2^i - 1`.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.factor_ import is_mersenne_prime
+    >>> is_mersenne_prime(6)
+    False
+    >>> is_mersenne_prime(127)
+    True
+
+    References
+    ==========
+
+    .. [1] https://mathworld.wolfram.com/MersennePrime.html
+
+    """
+    n = as_int(n)
+    if n < 1:
+        return False
+    if n & (n + 1):
+        # n is not Mersenne number
+        return False
+    p = n.bit_length()
+    if p in MERSENNE_PRIME_EXPONENTS:
+        return True
+    if p < 65_000_000 or not isprime(p):
+        # According to GIMPS, verification was completed on September 19, 2023 for p less than 65 million.
+        # https://www.mersenne.org/report_milestones/
+        # If p is composite number, then n=2**p-1 is composite number.
+        return False
+    result = _lucas_lehmer_primality_test(p)
+    if result:
+        raise ValueError(filldedent('''
+            This Mersenne Prime, 2^%s - 1, should
+            be added to SymPy's known values.''' % p))
+    return result
+
+
+_MR_BASES_32 = [15591, 2018, 166, 7429, 8064, 16045, 10503, 4399, 1949, 1295,
+                2776, 3620, 560, 3128, 5212, 2657, 2300, 2021, 4652, 1471,
+                9336, 4018, 2398, 20462, 10277, 8028, 2213, 6219, 620, 3763,
+                4852, 5012, 3185, 1333, 6227,5298, 1074, 2391, 5113, 7061,
+                803, 1269, 3875, 422, 751, 580, 4729, 10239, 746, 2951, 556,
+                2206, 3778, 481, 1522, 3476, 481, 2487, 3266, 5633, 488, 3373,
+                6441, 3344, 17, 15105, 1490, 4154, 2036, 1882, 1813, 467,
+                3307, 14042, 6371, 658, 1005, 903, 737, 1887, 7447, 1888,
+                2848, 1784, 7559, 3400, 951, 13969, 4304, 177, 41, 19875,
+                3110, 13221, 8726, 571, 7043, 6943, 1199, 352, 6435, 165,
+                1169, 3315, 978, 233, 3003, 2562, 2994, 10587, 10030, 2377,
+                1902, 5354, 4447, 1555, 263, 27027, 2283, 305, 669, 1912, 601,
+                6186, 429, 1930, 14873, 1784, 1661, 524, 3577, 236, 2360,
+                6146, 2850, 55637, 1753, 4178, 8466, 222, 2579, 2743, 2031,
+                2226, 2276, 374, 2132, 813, 23788, 1610, 4422, 5159, 1725,
+                3597, 3366, 14336, 579, 165, 1375, 10018, 12616, 9816, 1371,
+                536, 1867, 10864, 857, 2206, 5788, 434, 8085, 17618, 727,
+                3639, 1595, 4944, 2129, 2029, 8195, 8344, 6232, 9183, 8126,
+                1870, 3296, 7455, 8947, 25017, 541, 19115, 368, 566, 5674,
+                411, 522, 1027, 8215, 2050, 6544, 10049, 614, 774, 2333, 3007,
+                35201, 4706, 1152, 1785, 1028, 1540, 3743, 493, 4474, 2521,
+                26845, 8354, 864, 18915, 5465, 2447, 42, 4511, 1660, 166,
+                1249, 6259, 2553, 304, 272, 7286, 73, 6554, 899, 2816, 5197,
+                13330, 7054, 2818, 3199, 811, 922, 350, 7514, 4452, 3449,
+                2663, 4708, 418, 1621, 1171, 3471, 88, 11345, 412, 1559, 194]
+
+
+def isprime(n):
+    """
+    Test if n is a prime number (True) or not (False). For n < 2^64 the
+    answer is definitive; larger n values have a small probability of actually
+    being pseudoprimes.
+
+    Negative numbers (e.g. -2) are not considered prime.
+
+    The first step is looking for trivial factors, which if found enables
+    a quick return.  Next, if the sieve is large enough, use bisection search
+    on the sieve.  For small numbers, a set of deterministic Miller-Rabin
+    tests are performed with bases that are known to have no counterexamples
+    in their range.  Finally if the number is larger than 2^64, a strong
+    BPSW test is performed.  While this is a probable prime test and we
+    believe counterexamples exist, there are no known counterexamples.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory import isprime
+    >>> isprime(13)
+    True
+    >>> isprime(15)
+    False
+
+    Notes
+    =====
+
+    This routine is intended only for integer input, not numerical
+    expressions which may represent numbers. Floats are also
+    rejected as input because they represent numbers of limited
+    precision. While it is tempting to permit 7.0 to represent an
+    integer there are errors that may "pass silently" if this is
+    allowed:
+
+    >>> from sympy import Float, S
+    >>> int(1e3) == 1e3 == 10**3
+    True
+    >>> int(1e23) == 1e23
+    True
+    >>> int(1e23) == 10**23
+    False
+
+    >>> near_int = 1 + S(1)/10**19
+    >>> near_int == int(near_int)
+    False
+    >>> n = Float(near_int, 10)  # truncated by precision
+    >>> n % 1 == 0
+    True
+    >>> n = Float(near_int, 20)
+    >>> n % 1 == 0
+    False
+
+    See Also
+    ========
+
+    sympy.ntheory.generate.primerange : Generates all primes in a given range
+    sympy.functions.combinatorial.numbers.primepi : Return the number of primes less than or equal to n
+    sympy.ntheory.generate.prime : Return the nth prime
+
+    References
+    ==========
+    .. [1] https://en.wikipedia.org/wiki/Strong_pseudoprime
+    .. [2] Robert Baillie, Samuel S. Wagstaff, Lucas Pseudoprimes,
+           Math. Comp. Vol 35, Number 152 (1980), pp. 1391-1417,
+           https://doi.org/10.1090%2FS0025-5718-1980-0583518-6
+           http://mpqs.free.fr/LucasPseudoprimes.pdf
+    .. [3] https://en.wikipedia.org/wiki/Baillie-PSW_primality_test
+    """
+    n = as_int(n)
+
+    # Step 1, do quick composite testing via trial division.  The individual
+    # modulo tests benchmark faster than one or two primorial igcds for me.
+    # The point here is just to speedily handle small numbers and many
+    # composites.  Step 2 only requires that n <= 2 get handled here.
+    if n in [2, 3, 5]:
+        return True
+    if n < 2 or (n % 2) == 0 or (n % 3) == 0 or (n % 5) == 0:
+        return False
+    if n < 49:
+        return True
+    if (n %  7) == 0 or (n % 11) == 0 or (n % 13) == 0 or (n % 17) == 0 or \
+       (n % 19) == 0 or (n % 23) == 0 or (n % 29) == 0 or (n % 31) == 0 or \
+       (n % 37) == 0 or (n % 41) == 0 or (n % 43) == 0 or (n % 47) == 0:
+        return False
+    if n < 2809:
+        return True
+    if n < 65077:
+        # There are only five Euler pseudoprimes with a least prime factor greater than 47
+        return pow(2, n >> 1, n) in [1, n - 1] and n not in [8321, 31621, 42799, 49141, 49981]
+
+    # bisection search on the sieve if the sieve is large enough
+    from sympy.ntheory.generate import sieve as s
+    if n <= s._list[-1]:
+        l, u = s.search(n)
+        return l == u
+    from sympy.ntheory.factor_ import factor_cache
+    if (ret := factor_cache.get(n)) is not None:
+        return ret == n
+
+    # If we have GMPY2, skip straight to step 3 and do a strong BPSW test.
+    # This should be a bit faster than our step 2, and for large values will
+    # be a lot faster than our step 3 (C+GMP vs. Python).
+    if _gmpy is not None:
+        return is_strong_bpsw_prp(n)
+
+
+    # Step 2: deterministic Miller-Rabin testing for numbers < 2^64.  See:
+    #    https://miller-rabin.appspot.com/
+    # for lists.  We have made sure the M-R routine will successfully handle
+    # bases larger than n, so we can use the minimal set.
+    # In September 2015 deterministic numbers were extended to over 2^81.
+    #    https://arxiv.org/pdf/1509.00864.pdf
+    #    https://oeis.org/A014233
+    if n < 341531:
+        return mr(n, [9345883071009581737])
+    if n < 4296595241:
+        # Michal Forisek and Jakub Jancina,
+        # Fast Primality Testing for Integers That Fit into a Machine Word
+        # https://ceur-ws.org/Vol-1326/020-Forisek.pdf
+        h = ((n >> 16) ^ n) * 0x45d9f3b
+        h = ((h >> 16) ^ h) * 0x45d9f3b
+        h = ((h >> 16) ^ h) & 255
+        return mr(n, [_MR_BASES_32[h]])
+    if n < 350269456337:
+        return mr(n, [4230279247111683200, 14694767155120705706, 16641139526367750375])
+    if n < 55245642489451:
+        return mr(n, [2, 141889084524735, 1199124725622454117, 11096072698276303650])
+    if n < 7999252175582851:
+        return mr(n, [2, 4130806001517, 149795463772692060, 186635894390467037, 3967304179347715805])
+    if n < 585226005592931977:
+        return mr(n, [2, 123635709730000, 9233062284813009, 43835965440333360, 761179012939631437, 1263739024124850375])
+    if n < 18446744073709551616:
+        return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])
+    if n < 318665857834031151167461:
+        return mr(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37])
+    if n < 3317044064679887385961981:
+        return mr(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41])
+
+    # We could do this instead at any point:
+    #if n < 18446744073709551616:
+    #   return mr(n, [2]) and is_extra_strong_lucas_prp(n)
+
+    # Here are tests that are safe for MR routines that don't understand
+    # large bases.
+    #if n < 9080191:
+    #    return mr(n, [31, 73])
+    #if n < 19471033:
+    #    return mr(n, [2, 299417])
+    #if n < 38010307:
+    #    return mr(n, [2, 9332593])
+    #if n < 316349281:
+    #    return mr(n, [11000544, 31481107])
+    #if n < 4759123141:
+    #    return mr(n, [2, 7, 61])
+    #if n < 105936894253:
+    #    return mr(n, [2, 1005905886, 1340600841])
+    #if n < 31858317218647:
+    #    return mr(n, [2, 642735, 553174392, 3046413974])
+    #if n < 3071837692357849:
+    #    return mr(n, [2, 75088, 642735, 203659041, 3613982119])
+    #if n < 18446744073709551616:
+    #    return mr(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022])
+
+    # Step 3: BPSW.
+    #
+    #  Time for isprime(10**2000 + 4561), no gmpy or gmpy2 installed
+    #     44.0s   old isprime using 46 bases
+    #      5.3s   strong BPSW + one random base
+    #      4.3s   extra strong BPSW + one random base
+    #      4.1s   strong BPSW
+    #      3.2s   extra strong BPSW
+
+    # Classic BPSW from page 1401 of the paper.  See alternate ideas below.
+    return is_strong_bpsw_prp(n)
+
+    # Using extra strong test, which is somewhat faster
+    #return mr(n, [2]) and is_extra_strong_lucas_prp(n)
+
+    # Add a random M-R base
+    #import random
+    #return mr(n, [2, random.randint(3, n-1)]) and is_strong_lucas_prp(n)
+
+
+def is_gaussian_prime(num):
+    r"""Test if num is a Gaussian prime number.
+
+    References
+    ==========
+
+    .. [1] https://oeis.org/wiki/Gaussian_primes
+    """
+
+    num = sympify(num)
+    a, b = num.as_real_imag()
+    a = as_int(a, strict=False)
+    b = as_int(b, strict=False)
+    if a == 0:
+        b = abs(b)
+        return isprime(b) and b % 4 == 3
+    elif b == 0:
+        a = abs(a)
+        return isprime(a) and a % 4 == 3
+    return isprime(a**2 + b**2)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/qs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/qs.py
new file mode 100644
index 0000000000000000000000000000000000000000..acc9a7b6e0151695538a99a738ef397166497ba5
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/qs.py
@@ -0,0 +1,451 @@
+from math import exp, log
+from sympy.core.random import _randint
+from sympy.external.gmpy import bit_scan1, gcd, invert, sqrt as isqrt
+from sympy.ntheory.factor_ import _perfect_power
+from sympy.ntheory.primetest import isprime
+from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power
+
+
+class SievePolynomial:
+    def __init__(self, a, b, N):
+        """This class denotes the sieve polynomial.
+        Provide methods to compute `(a*x + b)**2 - N` and
+        `a*x + b` when given `x`.
+
+        Parameters
+        ==========
+
+        a : parameter of the sieve polynomial
+        b : parameter of the sieve polynomial
+        N : number to be factored
+
+        """
+        self.a = a
+        self.b = b
+        self.a2 = a**2
+        self.ab = 2*a*b
+        self.b2 = b**2 - N
+
+    def eval_u(self, x):
+        return self.a*x + self.b
+
+    def eval_v(self, x):
+        return (self.a2*x + self.ab)*x + self.b2
+
+
+class FactorBaseElem:
+    """This class stores an element of the `factor_base`.
+    """
+    def __init__(self, prime, tmem_p, log_p):
+        """
+        Initialization of factor_base_elem.
+
+        Parameters
+        ==========
+
+        prime : prime number of the factor_base
+        tmem_p : Integer square root of x**2 = n mod prime
+        log_p : Compute Natural Logarithm of the prime
+        """
+        self.prime = prime
+        self.tmem_p = tmem_p
+        self.log_p = log_p
+        # `soln1` and `soln2` are solutions to
+        # the equation `(a*x + b)**2 - N = 0 (mod p)`.
+        self.soln1 = None
+        self.soln2 = None
+        self.b_ainv = None
+
+
+def _generate_factor_base(prime_bound, n):
+    """Generate `factor_base` for Quadratic Sieve. The `factor_base`
+    consists of all the points whose ``legendre_symbol(n, p) == 1``
+    and ``p < num_primes``. Along with the prime `factor_base` also stores
+    natural logarithm of prime and the residue n modulo p.
+    It also returns the of primes numbers in the `factor_base` which are
+    close to 1000 and 5000.
+
+    Parameters
+    ==========
+
+    prime_bound : upper prime bound of the factor_base
+    n : integer to be factored
+    """
+    from sympy.ntheory.generate import sieve
+    factor_base = []
+    idx_1000, idx_5000 = None, None
+    for prime in sieve.primerange(1, prime_bound):
+        if pow(n, (prime - 1) // 2, prime) == 1:
+            if prime > 1000 and idx_1000 is None:
+                idx_1000 = len(factor_base) - 1
+            if prime > 5000 and idx_5000 is None:
+                idx_5000 = len(factor_base) - 1
+            residue = _sqrt_mod_prime_power(n, prime, 1)[0]
+            log_p = round(log(prime)*2**10)
+            factor_base.append(FactorBaseElem(prime, residue, log_p))
+    return idx_1000, idx_5000, factor_base
+
+
+def _generate_polynomial(N, M, factor_base, idx_1000, idx_5000, randint):
+    """ Generate sieve polynomials indefinitely.
+    Information such as `soln1` in the `factor_base` associated with
+    the polynomial is modified in place.
+
+    Parameters
+    ==========
+
+    N : Number to be factored
+    M : sieve interval
+    factor_base : factor_base primes
+    idx_1000 : index of prime number in the factor_base near 1000
+    idx_5000 : index of prime number in the factor_base near to 5000
+    randint : A callable that takes two integers (a, b) and returns a random integer
+              n such that a <= n <= b, similar to `random.randint`.
+    """
+    approx_val = log(2*N)/2 - log(M)
+    start = idx_1000 or 0
+    end = idx_5000 or (len(factor_base) - 1)
+    while True:
+        # Choose `a` that is close to `sqrt(2*N) / M`
+        best_a, best_q, best_ratio = None, None, None
+        for _ in range(50):
+            a = 1
+            q = []
+            while log(a) < approx_val:
+                rand_p = 0
+                while(rand_p == 0 or rand_p in q):
+                    rand_p = randint(start, end)
+                p = factor_base[rand_p].prime
+                a *= p
+                q.append(rand_p)
+            ratio = exp(log(a) - approx_val)
+            if best_ratio is None or abs(ratio - 1) < abs(best_ratio - 1):
+                best_q = q
+                best_a = a
+                best_ratio = ratio
+
+        # Set `b` using the Chinese remainder theorem
+        a = best_a
+        q = best_q
+        B = []
+        for val in q:
+            q_l = factor_base[val].prime
+            gamma = factor_base[val].tmem_p * invert(a // q_l, q_l) % q_l
+            if 2*gamma > q_l:
+                gamma = q_l - gamma
+            B.append(a//q_l*gamma)
+        b = sum(B)
+        g = SievePolynomial(a, b, N)
+        for fb in factor_base:
+            if a % fb.prime == 0:
+                fb.soln1 = None
+                continue
+            a_inv = invert(a, fb.prime)
+            fb.b_ainv = [2*b_elem*a_inv % fb.prime for b_elem in B]
+            fb.soln1 = (a_inv*(fb.tmem_p - b)) % fb.prime
+            fb.soln2 = (a_inv*(-fb.tmem_p - b)) % fb.prime
+        yield g
+
+        # Update `b` with Gray code
+        for i in range(1, 2**(len(B)-1)):
+            v = bit_scan1(i)
+            neg_pow = 2*((i >> (v + 1)) % 2) - 1
+            b = g.b + 2*neg_pow*B[v]
+            a = g.a
+            g = SievePolynomial(a, b, N)
+            for fb in factor_base:
+                if fb.soln1 is None:
+                    continue
+                fb.soln1 = (fb.soln1 - neg_pow*fb.b_ainv[v]) % fb.prime
+                fb.soln2 = (fb.soln2 - neg_pow*fb.b_ainv[v]) % fb.prime
+            yield g
+
+
+def _gen_sieve_array(M, factor_base):
+    """Sieve Stage of the Quadratic Sieve. For every prime in the factor_base
+    that does not divide the coefficient `a` we add log_p over the sieve_array
+    such that ``-M <= soln1 + i*p <=  M`` and ``-M <= soln2 + i*p <=  M`` where `i`
+    is an integer. When p = 2 then log_p is only added using
+    ``-M <= soln1 + i*p <=  M``.
+
+    Parameters
+    ==========
+
+    M : sieve interval
+    factor_base : factor_base primes
+    """
+    sieve_array = [0]*(2*M + 1)
+    for factor in factor_base:
+        if factor.soln1 is None: #The prime does not divides a
+            continue
+        for idx in range((M + factor.soln1) % factor.prime, 2*M, factor.prime):
+            sieve_array[idx] += factor.log_p
+        if factor.prime == 2:
+            continue
+        #if prime is 2 then sieve only with soln_1_p
+        for idx in range((M + factor.soln2) % factor.prime, 2*M, factor.prime):
+            sieve_array[idx] += factor.log_p
+    return sieve_array
+
+
+def _check_smoothness(num, factor_base):
+    r""" Check if `num` is smooth with respect to the given `factor_base`
+    and compute its factorization vector.
+
+    Parameters
+    ==========
+
+    num : integer whose smootheness is to be checked
+    factor_base : factor_base primes
+    """
+    if num < 0:
+        num *= -1
+        vec = 1
+    else:
+        vec = 0
+    for i, fb in enumerate(factor_base, 1):
+        if num % fb.prime:
+            continue
+        e = 1
+        num //= fb.prime
+        while num % fb.prime == 0:
+            e += 1
+            num //= fb.prime
+        if e % 2:
+            vec += 1 << i
+    return vec, num
+
+
+def _trial_division_stage(N, M, factor_base, sieve_array, sieve_poly, partial_relations, ERROR_TERM):
+    """Trial division stage. Here we trial divide the values generetated
+    by sieve_poly in the sieve interval and if it is a smooth number then
+    it is stored in `smooth_relations`. Moreover, if we find two partial relations
+    with same large prime then they are combined to form a smooth relation.
+    First we iterate over sieve array and look for values which are greater
+    than accumulated_val, as these values have a high chance of being smooth
+    number. Then using these values we find smooth relations.
+    In general, let ``t**2 = u*p modN`` and ``r**2 = v*p modN`` be two partial relations
+    with the same large prime p. Then they can be combined ``(t*r/p)**2 = u*v modN``
+    to form a smooth relation.
+
+    Parameters
+    ==========
+
+    N : Number to be factored
+    M : sieve interval
+    factor_base : factor_base primes
+    sieve_array : stores log_p values
+    sieve_poly : polynomial from which we find smooth relations
+    partial_relations : stores partial relations with one large prime
+    ERROR_TERM : error term for accumulated_val
+    """
+    accumulated_val = (log(M) + log(N)/2 - ERROR_TERM) * 2**10
+    smooth_relations = []
+    proper_factor = set()
+    partial_relation_upper_bound = 128*factor_base[-1].prime
+    for x, val in enumerate(sieve_array, -M):
+        if val < accumulated_val:
+            continue
+        v = sieve_poly.eval_v(x)
+        vec, num = _check_smoothness(v, factor_base)
+        if num == 1:
+            smooth_relations.append((sieve_poly.eval_u(x), v, vec))
+        elif num < partial_relation_upper_bound and isprime(num):
+            if N % num == 0:
+                proper_factor.add(num)
+                continue
+            u = sieve_poly.eval_u(x)
+            if num in partial_relations:
+                u_prev, v_prev, vec_prev = partial_relations.pop(num)
+                u = u*u_prev*invert(num, N) % N
+                v = v*v_prev // num**2
+                vec ^= vec_prev
+                smooth_relations.append((u, v, vec))
+            else:
+                partial_relations[num] = (u, v, vec)
+    return smooth_relations, proper_factor
+
+
+def _find_factor(N, smooth_relations, col):
+    """ Finds proper factor of N using fast gaussian reduction for modulo 2 matrix.
+
+    Parameters
+    ==========
+
+    N : Number to be factored
+    smooth_relations : Smooth relations vectors matrix
+    col : Number of columns in the matrix
+
+    Reference
+    ==========
+
+    .. [1] A fast algorithm for gaussian elimination over GF(2) and
+    its implementation on the GAPP. Cetin K.Koc, Sarath N.Arachchige
+    """
+    matrix = [s_relation[2] for s_relation in smooth_relations]
+    row = len(matrix)
+    mark = [False] * row
+    for pos in range(col):
+        m = 1 << pos
+        for i in range(row):
+            if p := matrix[i] & m:
+                add_col = p ^ matrix[i]
+                matrix[i] = m
+                mark[i] = True
+                for j in range(i + 1, row):
+                    if matrix[j] & m:
+                        matrix[j] ^= add_col
+                break
+
+    for m, mat, rel in zip(mark, matrix, smooth_relations):
+        if m:
+            continue
+        u, v = rel[0], rel[1]
+        for m1, mat1, rel1 in zip(mark, matrix, smooth_relations):
+            if m1 and mat & mat1:
+                u *= rel1[0]
+                v *= rel1[1]
+        # assert is_square(v)
+        v = isqrt(v)
+        if 1 < (g := gcd(u - v, N)) < N:
+            yield g
+
+
+def qs(N, prime_bound, M, ERROR_TERM=25, seed=1234):
+    """Performs factorization using Self-Initializing Quadratic Sieve.
+    In SIQS, let N be a number to be factored, and this N should not be a
+    perfect power. If we find two integers such that ``X**2 = Y**2 modN`` and
+    ``X != +-Y modN``, then `gcd(X + Y, N)` will reveal a proper factor of N.
+    In order to find these integers X and Y we try to find relations of form
+    t**2 = u modN where u is a product of small primes. If we have enough of
+    these relations then we can form ``(t1*t2...ti)**2 = u1*u2...ui modN`` such that
+    the right hand side is a square, thus we found a relation of ``X**2 = Y**2 modN``.
+
+    Here, several optimizations are done like using multiple polynomials for
+    sieving, fast changing between polynomials and using partial relations.
+    The use of partial relations can speeds up the factoring by 2 times.
+
+    Parameters
+    ==========
+
+    N : Number to be Factored
+    prime_bound : upper bound for primes in the factor base
+    M : Sieve Interval
+    ERROR_TERM : Error term for checking smoothness
+    seed : seed of random number generator
+
+    Returns
+    =======
+
+    set(int) : A set of factors of N without considering multiplicity.
+               Returns ``{N}`` if factorization fails.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory import qs
+    >>> qs(25645121643901801, 2000, 10000)
+    {5394769, 4753701529}
+    >>> qs(9804659461513846513, 2000, 10000)
+    {4641991, 2112166839943}
+
+    See Also
+    ========
+
+    qs_factor
+
+    References
+    ==========
+
+    .. [1] https://pdfs.semanticscholar.org/5c52/8a975c1405bd35c65993abf5a4edb667c1db.pdf
+    .. [2] https://www.rieselprime.de/ziki/Self-initializing_quadratic_sieve
+    """
+    return set(qs_factor(N, prime_bound, M, ERROR_TERM, seed))
+
+
+def qs_factor(N, prime_bound, M, ERROR_TERM=25, seed=1234):
+    """ Performs factorization using Self-Initializing Quadratic Sieve.
+
+    Parameters
+    ==========
+
+    N : Number to be Factored
+    prime_bound : upper bound for primes in the factor base
+    M : Sieve Interval
+    ERROR_TERM : Error term for checking smoothness
+    seed : seed of random number generator
+
+    Returns
+    =======
+
+    dict[int, int] : Factors of N.
+                     Returns ``{N: 1}`` if factorization fails.
+                     Note that the key is not always a prime number.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory import qs_factor
+    >>> qs_factor(1009 * 100003, 2000, 10000)
+    {1009: 1, 100003: 1}
+
+    See Also
+    ========
+
+    qs
+
+    """
+    if N < 2:
+        raise ValueError("N should be greater than 1")
+    factors = {}
+    smooth_relations = []
+    partial_relations = {}
+    # Eliminate the possibility of even numbers,
+    # prime numbers, and perfect powers.
+    if N % 2 == 0:
+        e = 1
+        N //= 2
+        while N % 2 == 0:
+            N //= 2
+            e += 1
+        factors[2] = e
+    if isprime(N):
+        factors[N] = 1
+        return factors
+    if result := _perfect_power(N, 3):
+        n, e = result
+        factors[n] = e
+        return factors
+    N_copy = N
+    randint = _randint(seed)
+    idx_1000, idx_5000, factor_base = _generate_factor_base(prime_bound, N)
+    threshold = len(factor_base) * 105//100
+    for g in _generate_polynomial(N, M, factor_base, idx_1000, idx_5000, randint):
+        sieve_array = _gen_sieve_array(M, factor_base)
+        s_rel, p_f = _trial_division_stage(N, M, factor_base, sieve_array, g, partial_relations, ERROR_TERM)
+        smooth_relations += s_rel
+        for p in p_f:
+            if N_copy % p:
+                continue
+            e = 1
+            N_copy //= p
+            while N_copy % p == 0:
+                N_copy //= p
+                e += 1
+            factors[p] = e
+        if threshold <= len(smooth_relations):
+            break
+
+    for factor in _find_factor(N, smooth_relations, len(factor_base) + 1):
+        if N_copy % factor == 0:
+            e = 1
+            N_copy //= factor
+            while N_copy % factor == 0:
+                N_copy //= factor
+                e += 1
+            factors[factor] = e
+            if N_copy == 1 or isprime(N_copy):
+                break
+    if N_copy != 1:
+        factors[N_copy] = 1
+    return factors
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/residue_ntheory.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/residue_ntheory.py
new file mode 100644
index 0000000000000000000000000000000000000000..eba024161194605aabebd10ee30bf09acb90270b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/residue_ntheory.py
@@ -0,0 +1,1963 @@
+from __future__ import annotations
+
+from sympy.external.gmpy import (gcd, lcm, invert, sqrt, jacobi,
+                                 bit_scan1, remove)
+from sympy.polys import Poly
+from sympy.polys.domains import ZZ
+from sympy.polys.galoistools import gf_crt1, gf_crt2, linear_congruence, gf_csolve
+from .primetest import isprime
+from .generate import primerange
+from .factor_ import factorint, _perfect_power
+from .modular import crt
+from sympy.utilities.decorator import deprecated
+from sympy.utilities.memoization import recurrence_memo
+from sympy.utilities.misc import as_int
+from sympy.utilities.iterables import iproduct
+from sympy.core.random import _randint, randint
+
+from itertools import product
+
+
+def n_order(a, n):
+    r""" Returns the order of ``a`` modulo ``n``.
+
+    Explanation
+    ===========
+
+    The order of ``a`` modulo ``n`` is the smallest integer
+    ``k`` such that `a^k` leaves a remainder of 1 with ``n``.
+
+    Parameters
+    ==========
+
+    a : integer
+    n : integer, n > 1. a and n should be relatively prime
+
+    Returns
+    =======
+
+    int : the order of ``a`` modulo ``n``
+
+    Raises
+    ======
+
+    ValueError
+        If `n \le 1` or `\gcd(a, n) \neq 1`.
+        If ``a`` or ``n`` is not an integer.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory import n_order
+    >>> n_order(3, 7)
+    6
+    >>> n_order(4, 7)
+    3
+
+    See Also
+    ========
+
+    is_primitive_root
+        We say that ``a`` is a primitive root of ``n``
+        when the order of ``a`` modulo ``n`` equals ``totient(n)``
+
+    """
+    a, n = as_int(a), as_int(n)
+    if n <= 1:
+        raise ValueError("n should be an integer greater than 1")
+    a = a % n
+    # Trivial
+    if a == 1:
+        return 1
+    if gcd(a, n) != 1:
+        raise ValueError("The two numbers should be relatively prime")
+    a_order = 1
+    for p, e in factorint(n).items():
+        pe = p**e
+        pe_order = (p - 1) * p**(e - 1)
+        factors = factorint(p - 1)
+        if e > 1:
+            factors[p] = e - 1
+        order = 1
+        for px, ex in factors.items():
+            x = pow(a, pe_order // px**ex, pe)
+            while x != 1:
+                x = pow(x, px, pe)
+                order *= px
+        a_order = lcm(a_order, order)
+    return int(a_order)
+
+
+def _primitive_root_prime_iter(p):
+    r""" Generates the primitive roots for a prime ``p``.
+
+    Explanation
+    ===========
+
+    The primitive roots generated are not necessarily sorted.
+    However, the first one is the smallest primitive root.
+
+    Find the element whose order is ``p-1`` from the smaller one.
+    If we can find the first primitive root ``g``, we can use the following theorem.
+
+    .. math ::
+        \operatorname{ord}(g^k) = \frac{\operatorname{ord}(g)}{\gcd(\operatorname{ord}(g), k)}
+
+    From the assumption that `\operatorname{ord}(g)=p-1`,
+    it is a necessary and sufficient condition for
+    `\operatorname{ord}(g^k)=p-1` that `\gcd(p-1, k)=1`.
+
+    Parameters
+    ==========
+
+    p : odd prime
+
+    Yields
+    ======
+
+    int
+        the primitive roots of ``p``
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.residue_ntheory import _primitive_root_prime_iter
+    >>> sorted(_primitive_root_prime_iter(19))
+    [2, 3, 10, 13, 14, 15]
+
+    References
+    ==========
+
+    .. [1] W. Stein "Elementary Number Theory" (2011), page 44
+
+    """
+    if p == 3:
+        yield 2
+        return
+    # Let p = +-1 (mod 4a). Legendre symbol (a/p) = 1, so `a` is not the primitive root.
+    # Corollary : If p = +-1 (mod 8), then 2 is not the primitive root of p.
+    g_min = 3 if p % 8 in [1, 7] else 2
+    if p < 41:
+        # small case
+        g = 5 if p == 23 else g_min
+    else:
+        v = [(p - 1) // i for i in factorint(p - 1).keys()]
+        for g in range(g_min, p):
+            if all(pow(g, pw, p) != 1 for pw in v):
+                break
+    yield g
+    # g**k is the primitive root of p iff gcd(p - 1, k) = 1
+    for k in range(3, p, 2):
+        if gcd(p - 1, k) == 1:
+            yield pow(g, k, p)
+
+
+def _primitive_root_prime_power_iter(p, e):
+    r""" Generates the primitive roots of `p^e`.
+
+    Explanation
+    ===========
+
+    Let ``g`` be the primitive root of ``p``.
+    If `g^{p-1} \not\equiv 1 \pmod{p^2}`, then ``g`` is primitive root of `p^e`.
+    Thus, if we find a primitive root ``g`` of ``p``,
+    then `g, g+p, g+2p, \ldots, g+(p-1)p` are primitive roots of `p^2` except one.
+    That one satisfies `\hat{g}^{p-1} \equiv 1 \pmod{p^2}`.
+    If ``h`` is the primitive root of `p^2`,
+    then `h, h+p^2, h+2p^2, \ldots, h+(p^{e-2}-1)p^e` are primitive roots of `p^e`.
+
+    Parameters
+    ==========
+
+    p : odd prime
+    e : positive integer
+
+    Yields
+    ======
+
+    int
+        the primitive roots of `p^e`
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.residue_ntheory import _primitive_root_prime_power_iter
+    >>> sorted(_primitive_root_prime_power_iter(5, 2))
+    [2, 3, 8, 12, 13, 17, 22, 23]
+
+    """
+    if e == 1:
+        yield from _primitive_root_prime_iter(p)
+    else:
+        p2 = p**2
+        for g in _primitive_root_prime_iter(p):
+            t = (g - pow(g, 2 - p, p2)) % p2
+            for k in range(0, p2, p):
+                if k != t:
+                    yield from (g + k + m for m in range(0, p**e, p2))
+
+
+def _primitive_root_prime_power2_iter(p, e):
+    r""" Generates the primitive roots of `2p^e`.
+
+    Explanation
+    ===========
+
+    If ``g`` is the primitive root of ``p**e``,
+    then the odd one of ``g`` and ``g+p**e`` is the primitive root of ``2*p**e``.
+
+    Parameters
+    ==========
+
+    p : odd prime
+    e : positive integer
+
+    Yields
+    ======
+
+    int
+        the primitive roots of `2p^e`
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.residue_ntheory import _primitive_root_prime_power2_iter
+    >>> sorted(_primitive_root_prime_power2_iter(5, 2))
+    [3, 13, 17, 23, 27, 33, 37, 47]
+
+    """
+    for g in _primitive_root_prime_power_iter(p, e):
+        if g % 2 == 1:
+            yield g
+        else:
+            yield g + p**e
+
+
+def primitive_root(p, smallest=True):
+    r""" Returns a primitive root of ``p`` or None.
+
+    Explanation
+    ===========
+
+    For the definition of primitive root,
+    see the explanation of ``is_primitive_root``.
+
+    The primitive root of ``p`` exist only for
+    `p = 2, 4, q^e, 2q^e` (``q`` is an odd prime).
+    Now, if we know the primitive root of ``q``,
+    we can calculate the primitive root of `q^e`,
+    and if we know the primitive root of `q^e`,
+    we can calculate the primitive root of `2q^e`.
+    When there is no need to find the smallest primitive root,
+    this property can be used to obtain a fast primitive root.
+    On the other hand, when we want the smallest primitive root,
+    we naively determine whether it is a primitive root or not.
+
+    Parameters
+    ==========
+
+    p : integer, p > 1
+    smallest : if True the smallest primitive root is returned or None
+
+    Returns
+    =======
+
+    int | None :
+        If the primitive root exists, return the primitive root of ``p``.
+        If not, return None.
+
+    Raises
+    ======
+
+    ValueError
+        If `p \le 1` or ``p`` is not an integer.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.residue_ntheory import primitive_root
+    >>> primitive_root(19)
+    2
+    >>> primitive_root(21) is None
+    True
+    >>> primitive_root(50, smallest=False)
+    27
+
+    See Also
+    ========
+
+    is_primitive_root
+
+    References
+    ==========
+
+    .. [1] W. Stein "Elementary Number Theory" (2011), page 44
+    .. [2] P. Hackman "Elementary Number Theory" (2009), Chapter C
+
+    """
+    p = as_int(p)
+    if p <= 1:
+        raise ValueError("p should be an integer greater than 1")
+    if p <= 4:
+        return p - 1
+    p_even = p % 2 == 0
+    if not p_even:
+        q = p  # p is odd
+    elif p % 4:
+        q = p//2  # p had 1 factor of 2
+    else:
+        return None  # p had more than one factor of 2
+    if isprime(q):
+        e = 1
+    else:
+        m = _perfect_power(q, 3)
+        if not m:
+            return None
+        q, e = m
+        if not isprime(q):
+            return None
+    if not smallest:
+        if p_even:
+            return next(_primitive_root_prime_power2_iter(q, e))
+        return next(_primitive_root_prime_power_iter(q, e))
+    if p_even:
+        for i in range(3, p, 2):
+            if i % q and is_primitive_root(i, p):
+                return i
+    g = next(_primitive_root_prime_iter(q))
+    if e == 1 or pow(g, q - 1, q**2) != 1:
+        return g
+    for i in range(g + 1, p):
+        if i % q and is_primitive_root(i, p):
+            return i
+
+
+def is_primitive_root(a, p):
+    r""" Returns True if ``a`` is a primitive root of ``p``.
+
+    Explanation
+    ===========
+
+    ``a`` is said to be the primitive root of ``p`` if `\gcd(a, p) = 1` and
+    `\phi(p)` is the smallest positive number s.t.
+
+        `a^{\phi(p)} \equiv 1 \pmod{p}`.
+
+    where `\phi(p)` is Euler's totient function.
+
+    The primitive root of ``p`` exist only for
+    `p = 2, 4, q^e, 2q^e` (``q`` is an odd prime).
+    Hence, if it is not such a ``p``, it returns False.
+    To determine the primitive root, we need to know
+    the prime factorization of ``q-1``.
+    The hardness of the determination depends on this complexity.
+
+    Parameters
+    ==========
+
+    a : integer
+    p : integer, ``p`` > 1. ``a`` and ``p`` should be relatively prime
+
+    Returns
+    =======
+
+    bool : If True, ``a`` is the primitive root of ``p``.
+
+    Raises
+    ======
+
+    ValueError
+        If `p \le 1` or `\gcd(a, p) \neq 1`.
+        If ``a`` or ``p`` is not an integer.
+
+    Examples
+    ========
+
+    >>> from sympy.functions.combinatorial.numbers import totient
+    >>> from sympy.ntheory import is_primitive_root, n_order
+    >>> is_primitive_root(3, 10)
+    True
+    >>> is_primitive_root(9, 10)
+    False
+    >>> n_order(3, 10) == totient(10)
+    True
+    >>> n_order(9, 10) == totient(10)
+    False
+
+    See Also
+    ========
+
+    primitive_root
+
+    """
+    a, p = as_int(a), as_int(p)
+    if p <= 1:
+        raise ValueError("p should be an integer greater than 1")
+    a = a % p
+    if gcd(a, p) != 1:
+        raise ValueError("The two numbers should be relatively prime")
+    # Primitive root of p exist only for
+    # p = 2, 4, q**e, 2*q**e (q is odd prime)
+    if p <= 4:
+        # The primitive root is only p-1.
+        return a == p - 1
+    if p % 2:
+        q = p  # p is odd
+    elif p % 4:
+        q = p//2  # p had 1 factor of 2
+    else:
+        return False  # p had more than one factor of 2
+    if isprime(q):
+        group_order = q - 1
+        factors = factorint(q - 1).keys()
+    else:
+        m = _perfect_power(q, 3)
+        if not m:
+            return False
+        q, e = m
+        if not isprime(q):
+            return False
+        group_order = q**(e - 1)*(q - 1)
+        factors = set(factorint(q - 1).keys())
+        factors.add(q)
+    return all(pow(a, group_order // prime, p) != 1 for prime in factors)
+
+
+def _sqrt_mod_tonelli_shanks(a, p):
+    """
+    Returns the square root in the case of ``p`` prime with ``p == 1 (mod 8)``
+
+    Assume that the root exists.
+
+    Parameters
+    ==========
+
+    a : int
+    p : int
+        prime number. should be ``p % 8 == 1``
+
+    Returns
+    =======
+
+    int : Generally, there are two roots, but only one is returned.
+          Which one is returned is random.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.residue_ntheory import _sqrt_mod_tonelli_shanks
+    >>> _sqrt_mod_tonelli_shanks(2, 17) in [6, 11]
+    True
+
+    References
+    ==========
+
+    .. [1] Carl Pomerance, Richard Crandall, Prime Numbers: A Computational Perspective,
+           2nd Edition (2005), page 101, ISBN:978-0387252827
+
+    """
+    s = bit_scan1(p - 1)
+    t = p >> s
+    # find a non-quadratic residue
+    if p % 12 == 5:
+        # Legendre symbol (3/p) == -1 if p % 12 in [5, 7]
+        d = 3
+    elif p % 5 in [2, 3]:
+        # Legendre symbol (5/p) == -1 if p % 5 in [2, 3]
+        d = 5
+    else:
+        while 1:
+            d = randint(6, p - 1)
+            if jacobi(d, p) == -1:
+                break
+    #assert legendre_symbol(d, p) == -1
+    A = pow(a, t, p)
+    D = pow(d, t, p)
+    m = 0
+    for i in range(s):
+        adm = A*pow(D, m, p) % p
+        adm = pow(adm, 2**(s - 1 - i), p)
+        if adm % p == p - 1:
+            m += 2**i
+    #assert A*pow(D, m, p) % p == 1
+    x = pow(a, (t + 1)//2, p)*pow(D, m//2, p) % p
+    return x
+
+
+def sqrt_mod(a, p, all_roots=False):
+    """
+    Find a root of ``x**2 = a mod p``.
+
+    Parameters
+    ==========
+
+    a : integer
+    p : positive integer
+    all_roots : if True the list of roots is returned or None
+
+    Notes
+    =====
+
+    If there is no root it is returned None; else the returned root
+    is less or equal to ``p // 2``; in general is not the smallest one.
+    It is returned ``p // 2`` only if it is the only root.
+
+    Use ``all_roots`` only when it is expected that all the roots fit
+    in memory; otherwise use ``sqrt_mod_iter``.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory import sqrt_mod
+    >>> sqrt_mod(11, 43)
+    21
+    >>> sqrt_mod(17, 32, True)
+    [7, 9, 23, 25]
+    """
+    if all_roots:
+        return sorted(sqrt_mod_iter(a, p))
+    p = abs(as_int(p))
+    halfp = p // 2
+    x = None
+    for r in sqrt_mod_iter(a, p):
+        if r < halfp:
+            return r
+        elif r > halfp:
+            return p - r
+        else:
+            x = r
+    return x
+
+
+def sqrt_mod_iter(a, p, domain=int):
+    """
+    Iterate over solutions to ``x**2 = a mod p``.
+
+    Parameters
+    ==========
+
+    a : integer
+    p : positive integer
+    domain : integer domain, ``int``, ``ZZ`` or ``Integer``
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.residue_ntheory import sqrt_mod_iter
+    >>> list(sqrt_mod_iter(11, 43))
+    [21, 22]
+
+    See Also
+    ========
+
+    sqrt_mod : Same functionality, but you want a sorted list or only one solution.
+
+    """
+    a, p = as_int(a), abs(as_int(p))
+    v = []
+    pv = []
+    _product = product
+    for px, ex in factorint(p).items():
+        if a % px:
+            # `len(rx)` is at most 4
+            rx = _sqrt_mod_prime_power(a, px, ex)
+        else:
+            # `len(list(rx))` can be assumed to be large.
+            # The `itertools.product` is disadvantageous in terms of memory usage.
+            # It is also inferior to iproduct in speed if not all Cartesian products are needed.
+            rx = _sqrt_mod1(a, px, ex)
+            _product = iproduct
+        if not rx:
+            return
+        v.append(rx)
+        pv.append(px**ex)
+    if len(v) == 1:
+        yield from map(domain, v[0])
+    else:
+        mm, e, s = gf_crt1(pv, ZZ)
+        for vx in _product(*v):
+            yield domain(gf_crt2(vx, pv, mm, e, s, ZZ))
+
+
+def _sqrt_mod_prime_power(a, p, k):
+    """
+    Find the solutions to ``x**2 = a mod p**k`` when ``a % p != 0``.
+    If no solution exists, return ``None``.
+    Solutions are returned in an ascending list.
+
+    Parameters
+    ==========
+
+    a : integer
+    p : prime number
+    k : positive integer
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power
+    >>> _sqrt_mod_prime_power(11, 43, 1)
+    [21, 22]
+
+    References
+    ==========
+
+    .. [1] P. Hackman "Elementary Number Theory" (2009), page 160
+    .. [2] http://www.numbertheory.org/php/squareroot.html
+    .. [3] [Gathen99]_
+    """
+    pk = p**k
+    a = a % pk
+
+    if p == 2:
+        # see Ref.[2]
+        if a % 8 != 1:
+            return None
+        # Trivial
+        if k <= 3:
+            return list(range(1, pk, 2))
+        r = 1
+        # r is one of the solutions to x**2 - a = 0 (mod 2**3).
+        # Hensel lift them to solutions of x**2 - a = 0 (mod 2**k)
+        # if r**2 - a = 0 mod 2**nx but not mod 2**(nx+1)
+        # then r + 2**(nx - 1) is a root mod 2**(nx+1)
+        for nx in range(3, k):
+            if ((r**2 - a) >> nx) % 2:
+                r += 1 << (nx - 1)
+        # r is a solution of x**2 - a = 0 (mod 2**k), and
+        # there exist other solutions -r, r+h, -(r+h), and these are all solutions.
+        h = 1 << (k - 1)
+        return sorted([r, pk - r, (r + h) % pk, -(r + h) % pk])
+
+    # If the Legendre symbol (a/p) is not 1, no solution exists.
+    if jacobi(a, p) != 1:
+        return None
+    if p % 4 == 3:
+        res = pow(a, (p + 1) // 4, p)
+    elif p % 8 == 5:
+        res = pow(a, (p + 3) // 8, p)
+        if pow(res, 2, p) != a % p:
+            res = res * pow(2, (p - 1) // 4, p) % p
+    else:
+        res = _sqrt_mod_tonelli_shanks(a, p)
+    if k > 1:
+        # Hensel lifting with Newton iteration, see Ref.[3] chapter 9
+        # with f(x) = x**2 - a; one has f'(a) != 0 (mod p) for p != 2
+        px = p
+        for _ in range(k.bit_length() - 1):
+            px = px**2
+            frinv = invert(2*res, px)
+            res = (res - (res**2 - a)*frinv) % px
+        if k & (k - 1): # If k is not a power of 2
+            frinv = invert(2*res, pk)
+            res = (res - (res**2 - a)*frinv) % pk
+    return sorted([res, pk - res])
+
+
+def _sqrt_mod1(a, p, n):
+    """
+    Find solution to ``x**2 == a mod p**n`` when ``a % p == 0``.
+    If no solution exists, return ``None``.
+
+    Parameters
+    ==========
+
+    a : integer
+    p : prime number, p must divide a
+    n : positive integer
+
+    References
+    ==========
+
+    .. [1] http://www.numbertheory.org/php/squareroot.html
+    """
+    pn = p**n
+    a = a % pn
+    if a == 0:
+        # case gcd(a, p**k) = p**n
+        return range(0, pn, p**((n + 1) // 2))
+    # case gcd(a, p**k) = p**r, r < n
+    a, r = remove(a, p)
+    if r % 2 == 1:
+        return None
+    res = _sqrt_mod_prime_power(a, p, n - r)
+    if res is None:
+        return None
+    m = r // 2
+    return (x for rx in res for x in range(rx*p**m, pn, p**(n - m)))
+
+
+def is_quad_residue(a, p):
+    """
+    Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``,
+    i.e a % p in set([i**2 % p for i in range(p)]).
+
+    Parameters
+    ==========
+
+    a : integer
+    p : positive integer
+
+    Returns
+    =======
+
+    bool : If True, ``x**2 == a (mod p)`` has solution.
+
+    Raises
+    ======
+
+    ValueError
+        If ``a``, ``p`` is not integer.
+        If ``p`` is not positive.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory import is_quad_residue
+    >>> is_quad_residue(21, 100)
+    True
+
+    Indeed, ``pow(39, 2, 100)`` would be 21.
+
+    >>> is_quad_residue(21, 120)
+    False
+
+    That is, for any integer ``x``, ``pow(x, 2, 120)`` is not 21.
+
+    If ``p`` is an odd
+    prime, an iterative method is used to make the determination:
+
+    >>> from sympy.ntheory import is_quad_residue
+    >>> sorted(set([i**2 % 7 for i in range(7)]))
+    [0, 1, 2, 4]
+    >>> [j for j in range(7) if is_quad_residue(j, 7)]
+    [0, 1, 2, 4]
+
+    See Also
+    ========
+
+    legendre_symbol, jacobi_symbol, sqrt_mod
+    """
+    a, p = as_int(a), as_int(p)
+    if p < 1:
+        raise ValueError('p must be > 0')
+    a %= p
+    if a < 2 or p < 3:
+        return True
+    # Since we want to compute the Jacobi symbol,
+    # we separate p into the odd part and the rest.
+    t = bit_scan1(p)
+    if t:
+        # The existence of a solution to a power of 2 is determined
+        # using the logic of `p==2` in `_sqrt_mod_prime_power` and `_sqrt_mod1`.
+        a_ = a % (1 << t)
+        if a_:
+            r = bit_scan1(a_)
+            if r % 2 or (a_ >> r) & 6:
+                return False
+        p >>= t
+        a %= p
+        if a < 2 or p < 3:
+            return True
+    # If Jacobi symbol is -1 or p is prime, can be determined by Jacobi symbol only
+    j = jacobi(a, p)
+    if j == -1 or isprime(p):
+        return j == 1
+    # Checks if `x**2 = a (mod p)` has a solution
+    for px, ex in factorint(p).items():
+        if a % px:
+            if jacobi(a, px) != 1:
+                return False
+        else:
+            a_ = a % px**ex
+            if a_ == 0:
+                continue
+            a_, r = remove(a_, px)
+            if r % 2 or jacobi(a_, px) != 1:
+                return False
+    return True
+
+
+def is_nthpow_residue(a, n, m):
+    """
+    Returns True if ``x**n == a (mod m)`` has solutions.
+
+    References
+    ==========
+
+    .. [1] P. Hackman "Elementary Number Theory" (2009), page 76
+
+    """
+    a = a % m
+    a, n, m = as_int(a), as_int(n), as_int(m)
+    if m <= 0:
+        raise ValueError('m must be > 0')
+    if n < 0:
+        raise ValueError('n must be >= 0')
+    if n == 0:
+        if m == 1:
+            return False
+        return a == 1
+    if a == 0:
+        return True
+    if n == 1:
+        return True
+    if n == 2:
+        return is_quad_residue(a, m)
+    return all(_is_nthpow_residue_bign_prime_power(a, n, p, e)
+               for p, e in factorint(m).items())
+
+
+def _is_nthpow_residue_bign_prime_power(a, n, p, k):
+    r"""
+    Returns True if `x^n = a \pmod{p^k}` has solutions for `n > 2`.
+
+    Parameters
+    ==========
+
+    a : positive integer
+    n : integer, n > 2
+    p : prime number
+    k : positive integer
+
+    """
+    while a % p == 0:
+        a %= pow(p, k)
+        if not a:
+            return True
+        a, mu = remove(a, p)
+        if mu % n:
+            return False
+        k -= mu
+    if p != 2:
+        f = p**(k - 1)*(p - 1) # f = totient(p**k)
+        return pow(a, f // gcd(f, n), pow(p, k)) == 1
+    if n & 1:
+        return True
+    c = min(bit_scan1(n) + 2, k)
+    return a % pow(2, c) == 1
+
+
+def _nthroot_mod1(s, q, p, all_roots):
+    """
+    Root of ``x**q = s mod p``, ``p`` prime and ``q`` divides ``p - 1``.
+    Assume that the root exists.
+
+    Parameters
+    ==========
+
+    s : integer
+    q : integer, n > 2. ``q`` divides ``p - 1``.
+    p : prime number
+    all_roots : if False returns the smallest root, else the list of roots
+
+    Returns
+    =======
+
+    list[int] | int :
+        Root of ``x**q = s mod p``. If ``all_roots == True``,
+        returned ascending list. otherwise, returned an int.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.residue_ntheory import _nthroot_mod1
+    >>> _nthroot_mod1(5, 3, 13, False)
+    7
+    >>> _nthroot_mod1(13, 4, 17, True)
+    [3, 5, 12, 14]
+
+    References
+    ==========
+
+    .. [1] A. M. Johnston, A Generalized qth Root Algorithm,
+           ACM-SIAM Symposium on Discrete Algorithms (1999), pp. 929-930
+
+    """
+    g = next(_primitive_root_prime_iter(p))
+    r = s
+    for qx, ex in factorint(q).items():
+        f = (p - 1) // qx**ex
+        while f % qx == 0:
+            f //= qx
+        z = f*invert(-f, qx)
+        x = (1 + z) // qx
+        t = discrete_log(p, pow(r, f, p), pow(g, f*qx, p))
+        for _ in range(ex):
+            # assert t == discrete_log(p, pow(r, f, p), pow(g, f*qx, p))
+            r = pow(r, x, p)*pow(g, -z*t % (p - 1), p) % p
+            t //= qx
+    res = [r]
+    h = pow(g, (p - 1) // q, p)
+    #assert pow(h, q, p) == 1
+    hx = r
+    for _ in range(q - 1):
+        hx = (hx*h) % p
+        res.append(hx)
+    if all_roots:
+        res.sort()
+        return res
+    return min(res)
+
+
+def _nthroot_mod_prime_power(a, n, p, k):
+    """ Root of ``x**n = a mod p**k``.
+
+    Parameters
+    ==========
+
+    a : integer
+    n : integer, n > 2
+    p : prime number
+    k : positive integer
+
+    Returns
+    =======
+
+    list[int] :
+        Ascending list of roots of ``x**n = a mod p**k``.
+        If no solution exists, return ``[]``.
+
+    """
+    if not _is_nthpow_residue_bign_prime_power(a, n, p, k):
+        return []
+    a_mod_p = a % p
+    if a_mod_p == 0:
+        base_roots = [0]
+    elif (p - 1) % n == 0:
+        base_roots = _nthroot_mod1(a_mod_p, n, p, all_roots=True)
+    else:
+        # The roots of ``x**n - a = 0 (mod p)`` are roots of
+        # ``gcd(x**n - a, x**(p - 1) - 1) = 0 (mod p)``
+        pa = n
+        pb = p - 1
+        b = 1
+        if pa < pb:
+            a_mod_p, pa, b, pb = b, pb, a_mod_p, pa
+        # gcd(x**pa - a, x**pb - b) = gcd(x**pb - b, x**pc - c)
+        # where pc = pa % pb; c = b**-q * a mod p
+        while pb:
+            q, pc = divmod(pa, pb)
+            c = pow(b, -q, p) * a_mod_p % p
+            pa, pb = pb, pc
+            a_mod_p, b = b, c
+        if pa == 1:
+            base_roots = [a_mod_p]
+        elif pa == 2:
+            base_roots = sqrt_mod(a_mod_p, p, all_roots=True)
+        else:
+            base_roots = _nthroot_mod1(a_mod_p, pa, p, all_roots=True)
+    if k == 1:
+        return base_roots
+    a %= p**k
+    tot_roots = set()
+    for root in base_roots:
+        diff = pow(root, n - 1, p)*n % p
+        new_base = p
+        if diff != 0:
+            m_inv = invert(diff, p)
+            for _ in range(k - 1):
+                new_base *= p
+                tmp = pow(root, n, new_base) - a
+                tmp *= m_inv
+                root = (root - tmp) % new_base
+            tot_roots.add(root)
+        else:
+            roots_in_base = {root}
+            for _ in range(k - 1):
+                new_base *= p
+                new_roots = set()
+                for k_ in roots_in_base:
+                    if pow(k_, n, new_base) != a % new_base:
+                        continue
+                    while k_ not in new_roots:
+                        new_roots.add(k_)
+                        k_ = (k_ + (new_base // p)) % new_base
+                roots_in_base = new_roots
+            tot_roots = tot_roots | roots_in_base
+    return sorted(tot_roots)
+
+
+def nthroot_mod(a, n, p, all_roots=False):
+    """
+    Find the solutions to ``x**n = a mod p``.
+
+    Parameters
+    ==========
+
+    a : integer
+    n : positive integer
+    p : positive integer
+    all_roots : if False returns the smallest root, else the list of roots
+
+    Returns
+    =======
+
+        list[int] | int | None :
+            solutions to ``x**n = a mod p``.
+            The table of the output type is:
+
+            ========== ========== ==========
+            all_roots  has roots  Returns
+            ========== ========== ==========
+            True       Yes        list[int]
+            True       No         []
+            False      Yes        int
+            False      No         None
+            ========== ========== ==========
+
+    Raises
+    ======
+
+        ValueError
+            If ``a``, ``n`` or ``p`` is not integer.
+            If ``n`` or ``p`` is not positive.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.residue_ntheory import nthroot_mod
+    >>> nthroot_mod(11, 4, 19)
+    8
+    >>> nthroot_mod(11, 4, 19, True)
+    [8, 11]
+    >>> nthroot_mod(68, 3, 109)
+    23
+
+    References
+    ==========
+
+    .. [1] P. Hackman "Elementary Number Theory" (2009), page 76
+
+    """
+    a = a % p
+    a, n, p = as_int(a), as_int(n), as_int(p)
+
+    if n < 1:
+        raise ValueError("n should be positive")
+    if p < 1:
+        raise ValueError("p should be positive")
+    if n == 1:
+        return [a] if all_roots else a
+    if n == 2:
+        return sqrt_mod(a, p, all_roots)
+    base = []
+    prime_power = []
+    for q, e in factorint(p).items():
+        tot_roots = _nthroot_mod_prime_power(a, n, q, e)
+        if not tot_roots:
+            return [] if all_roots else None
+        prime_power.append(q**e)
+        base.append(sorted(tot_roots))
+    P, E, S = gf_crt1(prime_power, ZZ)
+    ret = sorted(map(int, {gf_crt2(c, prime_power, P, E, S, ZZ)
+                           for c in product(*base)}))
+    if all_roots:
+        return ret
+    if ret:
+        return ret[0]
+
+
+def quadratic_residues(p) -> list[int]:
+    """
+    Returns the list of quadratic residues.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.residue_ntheory import quadratic_residues
+    >>> quadratic_residues(7)
+    [0, 1, 2, 4]
+    """
+    p = as_int(p)
+    r = {pow(i, 2, p) for i in range(p // 2 + 1)}
+    return sorted(r)
+
+
+@deprecated("""\
+The `sympy.ntheory.residue_ntheory.legendre_symbol` has been moved to `sympy.functions.combinatorial.numbers.legendre_symbol`.""",
+deprecated_since_version="1.13",
+active_deprecations_target='deprecated-ntheory-symbolic-functions')
+def legendre_symbol(a, p):
+    r"""
+    Returns the Legendre symbol `(a / p)`.
+
+    .. deprecated:: 1.13
+
+        The ``legendre_symbol`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.legendre_symbol`
+        instead. See its documentation for more information. See
+        :ref:`deprecated-ntheory-symbolic-functions` for details.
+
+    For an integer ``a`` and an odd prime ``p``, the Legendre symbol is
+    defined as
+
+    .. math ::
+        \genfrac(){}{}{a}{p} = \begin{cases}
+             0 & \text{if } p \text{ divides } a\\
+             1 & \text{if } a \text{ is a quadratic residue modulo } p\\
+            -1 & \text{if } a \text{ is a quadratic nonresidue modulo } p
+        \end{cases}
+
+    Parameters
+    ==========
+
+    a : integer
+    p : odd prime
+
+    Examples
+    ========
+
+    >>> from sympy.functions.combinatorial.numbers import legendre_symbol
+    >>> [legendre_symbol(i, 7) for i in range(7)]
+    [0, 1, 1, -1, 1, -1, -1]
+    >>> sorted(set([i**2 % 7 for i in range(7)]))
+    [0, 1, 2, 4]
+
+    See Also
+    ========
+
+    is_quad_residue, jacobi_symbol
+
+    """
+    from sympy.functions.combinatorial.numbers import legendre_symbol as _legendre_symbol
+    return _legendre_symbol(a, p)
+
+
+@deprecated("""\
+The `sympy.ntheory.residue_ntheory.jacobi_symbol` has been moved to `sympy.functions.combinatorial.numbers.jacobi_symbol`.""",
+deprecated_since_version="1.13",
+active_deprecations_target='deprecated-ntheory-symbolic-functions')
+def jacobi_symbol(m, n):
+    r"""
+    Returns the Jacobi symbol `(m / n)`.
+
+    .. deprecated:: 1.13
+
+        The ``jacobi_symbol`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.jacobi_symbol`
+        instead. See its documentation for more information. See
+        :ref:`deprecated-ntheory-symbolic-functions` for details.
+
+    For any integer ``m`` and any positive odd integer ``n`` the Jacobi symbol
+    is defined as the product of the Legendre symbols corresponding to the
+    prime factors of ``n``:
+
+    .. math ::
+        \genfrac(){}{}{m}{n} =
+            \genfrac(){}{}{m}{p^{1}}^{\alpha_1}
+            \genfrac(){}{}{m}{p^{2}}^{\alpha_2}
+            ...
+            \genfrac(){}{}{m}{p^{k}}^{\alpha_k}
+            \text{ where } n =
+                p_1^{\alpha_1}
+                p_2^{\alpha_2}
+                ...
+                p_k^{\alpha_k}
+
+    Like the Legendre symbol, if the Jacobi symbol `\genfrac(){}{}{m}{n} = -1`
+    then ``m`` is a quadratic nonresidue modulo ``n``.
+
+    But, unlike the Legendre symbol, if the Jacobi symbol
+    `\genfrac(){}{}{m}{n} = 1` then ``m`` may or may not be a quadratic residue
+    modulo ``n``.
+
+    Parameters
+    ==========
+
+    m : integer
+    n : odd positive integer
+
+    Examples
+    ========
+
+    >>> from sympy.functions.combinatorial.numbers import jacobi_symbol, legendre_symbol
+    >>> from sympy import S
+    >>> jacobi_symbol(45, 77)
+    -1
+    >>> jacobi_symbol(60, 121)
+    1
+
+    The relationship between the ``jacobi_symbol`` and ``legendre_symbol`` can
+    be demonstrated as follows:
+
+    >>> L = legendre_symbol
+    >>> S(45).factors()
+    {3: 2, 5: 1}
+    >>> jacobi_symbol(7, 45) == L(7, 3)**2 * L(7, 5)**1
+    True
+
+    See Also
+    ========
+
+    is_quad_residue, legendre_symbol
+    """
+    from sympy.functions.combinatorial.numbers import jacobi_symbol as _jacobi_symbol
+    return _jacobi_symbol(m, n)
+
+
+@deprecated("""\
+The `sympy.ntheory.residue_ntheory.mobius` has been moved to `sympy.functions.combinatorial.numbers.mobius`.""",
+deprecated_since_version="1.13",
+active_deprecations_target='deprecated-ntheory-symbolic-functions')
+def mobius(n):
+    """
+    Mobius function maps natural number to {-1, 0, 1}
+
+    .. deprecated:: 1.13
+
+        The ``mobius`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.mobius`
+        instead. See its documentation for more information. See
+        :ref:`deprecated-ntheory-symbolic-functions` for details.
+
+    It is defined as follows:
+        1) `1` if `n = 1`.
+        2) `0` if `n` has a squared prime factor.
+        3) `(-1)^k` if `n` is a square-free positive integer with `k`
+           number of prime factors.
+
+    It is an important multiplicative function in number theory
+    and combinatorics.  It has applications in mathematical series,
+    algebraic number theory and also physics (Fermion operator has very
+    concrete realization with Mobius Function model).
+
+    Parameters
+    ==========
+
+    n : positive integer
+
+    Examples
+    ========
+
+    >>> from sympy.functions.combinatorial.numbers import mobius
+    >>> mobius(13*7)
+    1
+    >>> mobius(1)
+    1
+    >>> mobius(13*7*5)
+    -1
+    >>> mobius(13**2)
+    0
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/M%C3%B6bius_function
+    .. [2] Thomas Koshy "Elementary Number Theory with Applications"
+
+    """
+    from sympy.functions.combinatorial.numbers import mobius as _mobius
+    return _mobius(n)
+
+
+def _discrete_log_trial_mul(n, a, b, order=None):
+    """
+    Trial multiplication algorithm for computing the discrete logarithm of
+    ``a`` to the base ``b`` modulo ``n``.
+
+    The algorithm finds the discrete logarithm using exhaustive search. This
+    naive method is used as fallback algorithm of ``discrete_log`` when the
+    group order is very small. The value ``n`` must be greater than 1.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.residue_ntheory import _discrete_log_trial_mul
+    >>> _discrete_log_trial_mul(41, 15, 7)
+    3
+
+    See Also
+    ========
+
+    discrete_log
+
+    References
+    ==========
+
+    .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
+        Vanstone, S. A. (1997).
+    """
+    a %= n
+    b %= n
+    if order is None:
+        order = n
+    x = 1
+    for i in range(order):
+        if x == a:
+            return i
+        x = x * b % n
+    raise ValueError("Log does not exist")
+
+
+def _discrete_log_shanks_steps(n, a, b, order=None):
+    """
+    Baby-step giant-step algorithm for computing the discrete logarithm of
+    ``a`` to the base ``b`` modulo ``n``.
+
+    The algorithm is a time-memory trade-off of the method of exhaustive
+    search. It uses `O(sqrt(m))` memory, where `m` is the group order.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.residue_ntheory import _discrete_log_shanks_steps
+    >>> _discrete_log_shanks_steps(41, 15, 7)
+    3
+
+    See Also
+    ========
+
+    discrete_log
+
+    References
+    ==========
+
+    .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
+        Vanstone, S. A. (1997).
+    """
+    a %= n
+    b %= n
+    if order is None:
+        order = n_order(b, n)
+    m = sqrt(order) + 1
+    T = {}
+    x = 1
+    for i in range(m):
+        T[x] = i
+        x = x * b % n
+    z = pow(b, -m, n)
+    x = a
+    for i in range(m):
+        if x in T:
+            return i * m + T[x]
+        x = x * z % n
+    raise ValueError("Log does not exist")
+
+
+def _discrete_log_pollard_rho(n, a, b, order=None, retries=10, rseed=None):
+    """
+    Pollard's Rho algorithm for computing the discrete logarithm of ``a`` to
+    the base ``b`` modulo ``n``.
+
+    It is a randomized algorithm with the same expected running time as
+    ``_discrete_log_shanks_steps``, but requires a negligible amount of memory.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.residue_ntheory import _discrete_log_pollard_rho
+    >>> _discrete_log_pollard_rho(227, 3**7, 3)
+    7
+
+    See Also
+    ========
+
+    discrete_log
+
+    References
+    ==========
+
+    .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
+        Vanstone, S. A. (1997).
+    """
+    a %= n
+    b %= n
+
+    if order is None:
+        order = n_order(b, n)
+    randint = _randint(rseed)
+
+    for i in range(retries):
+        aa = randint(1, order - 1)
+        ba = randint(1, order - 1)
+        xa = pow(b, aa, n) * pow(a, ba, n) % n
+
+        c = xa % 3
+        if c == 0:
+            xb = a * xa % n
+            ab = aa
+            bb = (ba + 1) % order
+        elif c == 1:
+            xb = xa * xa % n
+            ab = (aa + aa) % order
+            bb = (ba + ba) % order
+        else:
+            xb = b * xa % n
+            ab = (aa + 1) % order
+            bb = ba
+
+        for j in range(order):
+            c = xa % 3
+            if c == 0:
+                xa = a * xa % n
+                ba = (ba + 1) % order
+            elif c == 1:
+                xa = xa * xa % n
+                aa = (aa + aa) % order
+                ba = (ba + ba) % order
+            else:
+                xa = b * xa % n
+                aa = (aa + 1) % order
+
+            c = xb % 3
+            if c == 0:
+                xb = a * xb % n
+                bb = (bb + 1) % order
+            elif c == 1:
+                xb = xb * xb % n
+                ab = (ab + ab) % order
+                bb = (bb + bb) % order
+            else:
+                xb = b * xb % n
+                ab = (ab + 1) % order
+
+            c = xb % 3
+            if c == 0:
+                xb = a * xb % n
+                bb = (bb + 1) % order
+            elif c == 1:
+                xb = xb * xb % n
+                ab = (ab + ab) % order
+                bb = (bb + bb) % order
+            else:
+                xb = b * xb % n
+                ab = (ab + 1) % order
+
+            if xa == xb:
+                r = (ba - bb) % order
+                try:
+                    e = invert(r, order) * (ab - aa) % order
+                    if (pow(b, e, n) - a) % n == 0:
+                        return e
+                except ZeroDivisionError:
+                    pass
+                break
+    raise ValueError("Pollard's Rho failed to find logarithm")
+
+
+def _discrete_log_is_smooth(n: int, factorbase: list):
+    """Try to factor n with respect to a given factorbase.
+    Upon success a list of exponents with respect to the factorbase is returned.
+    Otherwise None."""
+    factors = [0]*len(factorbase)
+    for i, p in enumerate(factorbase):
+        while n % p == 0: # divide by p as many times as possible
+            factors[i] += 1
+            n = n // p
+    if n != 1:
+        return None # the number factors if at the end nothing is left
+    return factors
+
+
+def _discrete_log_index_calculus(n, a, b, order, rseed=None):
+    """
+    Index Calculus algorithm for computing the discrete logarithm of ``a`` to
+    the base ``b`` modulo ``n``.
+
+    The group order must be given and prime. It is not suitable for small orders
+    and the algorithm might fail to find a solution in such situations.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.residue_ntheory import _discrete_log_index_calculus
+    >>> _discrete_log_index_calculus(24570203447, 23859756228, 2, 12285101723)
+    4519867240
+
+    See Also
+    ========
+
+    discrete_log
+
+    References
+    ==========
+
+    .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
+        Vanstone, S. A. (1997).
+    """
+    randint = _randint(rseed)
+    from math import sqrt, exp, log
+    a %= n
+    b %= n
+    # assert isprime(order), "The order of the base must be prime."
+    # First choose a heuristic the bound B for the factorbase.
+    # We have added an extra term to the asymptotic value which
+    # is closer to the theoretical optimum for n up to 2^70.
+    B = int(exp(0.5 * sqrt( log(n) * log(log(n)) )*( 1 + 1/log(log(n)) )))
+    max = 5 * B * B  # expected number of tries to find a relation
+    factorbase = list(primerange(B)) # compute the factorbase
+    lf = len(factorbase) # length of the factorbase
+    ordermo = order-1
+    abx = a
+    for x in range(order):
+        if abx == 1:
+            return (order - x) % order
+        relationa = _discrete_log_is_smooth(abx, factorbase)
+        if relationa:
+            relationa = [r % order for r in relationa] + [x]
+            break
+        abx = abx * b % n # abx = a*pow(b, x, n) % n
+
+    else:
+        raise ValueError("Index Calculus failed")
+
+    relations = [None] * lf
+    k = 1  # number of relations found
+    kk = 0
+    while k < 3 * lf and kk < max:  # find relations for all primes in our factor base
+        x = randint(1,ordermo)
+        relation = _discrete_log_is_smooth(pow(b,x,n), factorbase)
+        if relation is None:
+            kk += 1
+            continue
+        k += 1
+        kk = 0
+        relation += [ x ]
+        index = lf  # determine the index of the first nonzero entry
+        for i in range(lf):
+            ri = relation[i] % order
+            if ri> 0 and relations[i] is not None:  # make this entry zero if we can
+                for j in range(lf+1):
+                    relation[j] = (relation[j] - ri*relations[i][j]) % order
+            else:
+                relation[i] = ri
+            if relation[i] > 0 and index == lf:  # is this the index of the first nonzero entry?
+                index = i
+        if index == lf or relations[index] is not None:  # the relation contains no new information
+            continue
+        # the relation contains new information
+        rinv = pow(relation[index],-1,order)  # normalize the first nonzero entry
+        for j in range(index,lf+1):
+            relation[j] = rinv * relation[j] % order
+        relations[index] = relation
+        for i in range(lf):  # subtract the new relation from the one for a
+            if relationa[i] > 0 and relations[i] is not None:
+                rbi = relationa[i]
+                for j in range(lf+1):
+                    relationa[j] = (relationa[j] - rbi*relations[i][j]) % order
+            if relationa[i] > 0:  # the index of the first nonzero entry
+                break  # we do not need to reduce further at this point
+        else:  # all unknowns are gone
+            #print(f"Success after {k} relations out of {lf}")
+            x = (order -relationa[lf]) % order
+            if pow(b,x,n) == a:
+                return x
+            raise ValueError("Index Calculus failed")
+    raise ValueError("Index Calculus failed")
+
+
+def _discrete_log_pohlig_hellman(n, a, b, order=None, order_factors=None):
+    """
+    Pohlig-Hellman algorithm for computing the discrete logarithm of ``a`` to
+    the base ``b`` modulo ``n``.
+
+    In order to compute the discrete logarithm, the algorithm takes advantage
+    of the factorization of the group order. It is more efficient when the
+    group order factors into many small primes.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.residue_ntheory import _discrete_log_pohlig_hellman
+    >>> _discrete_log_pohlig_hellman(251, 210, 71)
+    197
+
+    See Also
+    ========
+
+    discrete_log
+
+    References
+    ==========
+
+    .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
+        Vanstone, S. A. (1997).
+    """
+    from .modular import crt
+    a %= n
+    b %= n
+
+    if order is None:
+        order = n_order(b, n)
+    if order_factors is None:
+        order_factors = factorint(order)
+    l = [0] * len(order_factors)
+
+    for i, (pi, ri) in enumerate(order_factors.items()):
+        for j in range(ri):
+            aj = pow(a * pow(b, -l[i], n), order // pi**(j + 1), n)
+            bj = pow(b, order // pi, n)
+            cj = discrete_log(n, aj, bj, pi, True)
+            l[i] += cj * pi**j
+
+    d, _ = crt([pi**ri for pi, ri in order_factors.items()], l)
+    return d
+
+
+def discrete_log(n, a, b, order=None, prime_order=None):
+    """
+    Compute the discrete logarithm of ``a`` to the base ``b`` modulo ``n``.
+
+    This is a recursive function to reduce the discrete logarithm problem in
+    cyclic groups of composite order to the problem in cyclic groups of prime
+    order.
+
+    It employs different algorithms depending on the problem (subgroup order
+    size, prime order or not):
+
+        * Trial multiplication
+        * Baby-step giant-step
+        * Pollard's Rho
+        * Index Calculus
+        * Pohlig-Hellman
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory import discrete_log
+    >>> discrete_log(41, 15, 7)
+    3
+
+    References
+    ==========
+
+    .. [1] https://mathworld.wolfram.com/DiscreteLogarithm.html
+    .. [2] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., &
+        Vanstone, S. A. (1997).
+
+    """
+    from math import sqrt, log
+    n, a, b = as_int(n), as_int(a), as_int(b)
+
+    if n < 1:
+        raise ValueError("n should be positive")
+    if n == 1:
+        return 0
+
+    if order is None:
+        # Compute the order and its factoring in one pass
+        # order = totient(n), factors = factorint(order)
+        factors = {}
+        for px, kx in factorint(n).items():
+            if kx > 1:
+                if px in factors:
+                    factors[px] += kx - 1
+                else:
+                    factors[px] = kx - 1
+            for py, ky in factorint(px - 1).items():
+                if py in factors:
+                    factors[py] += ky
+                else:
+                    factors[py] = ky
+        order = 1
+        for px, kx in factors.items():
+            order *= px**kx
+        # Now the `order` is the order of the group and factors = factorint(order)
+        # The order of `b` divides the order of the group.
+        order_factors = {}
+        for p, e in factors.items():
+            i = 0
+            for _ in range(e):
+                if pow(b, order // p, n) == 1:
+                    order //= p
+                    i += 1
+                else:
+                    break
+            if i < e:
+                order_factors[p] = e - i
+
+    if prime_order is None:
+        prime_order = isprime(order)
+
+    if order < 1000:
+        return _discrete_log_trial_mul(n, a, b, order)
+    elif prime_order:
+        # Shanks and Pollard rho are O(sqrt(order)) while index calculus is O(exp(2*sqrt(log(n)log(log(n)))))
+        # we compare the expected running times to determine the algorithm which is expected to be faster
+        if 4*sqrt(log(n)*log(log(n))) < log(order) - 10:  # the number 10 was determined experimental
+            return _discrete_log_index_calculus(n, a, b, order)
+        elif order < 1000000000000:
+            # Shanks seems typically faster, but uses O(sqrt(order)) memory
+            return _discrete_log_shanks_steps(n, a, b, order)
+        return _discrete_log_pollard_rho(n, a, b, order)
+
+    return _discrete_log_pohlig_hellman(n, a, b, order, order_factors)
+
+
+
+def quadratic_congruence(a, b, c, n):
+    r"""
+    Find the solutions to `a x^2 + b x + c \equiv 0 \pmod{n}`.
+
+    Parameters
+    ==========
+
+    a : int
+    b : int
+    c : int
+    n : int
+        A positive integer.
+
+    Returns
+    =======
+
+    list[int] :
+        A sorted list of solutions. If no solution exists, ``[]``.
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.residue_ntheory import quadratic_congruence
+    >>> quadratic_congruence(2, 5, 3, 7) # 2x^2 + 5x + 3 = 0 (mod 7)
+    [2, 6]
+    >>> quadratic_congruence(8, 6, 4, 15) # No solution
+    []
+
+    See Also
+    ========
+
+    polynomial_congruence : Solve the polynomial congruence
+
+    """
+    a = as_int(a)
+    b = as_int(b)
+    c = as_int(c)
+    n = as_int(n)
+    if n <= 1:
+        raise ValueError("n should be an integer greater than 1")
+    a %= n
+    b %= n
+    c %= n
+
+    if a == 0:
+        return linear_congruence(b, -c, n)
+    if n == 2:
+        # assert a == 1
+        roots = []
+        if c == 0:
+            roots.append(0)
+        if (b + c) % 2:
+            roots.append(1)
+        return roots
+    if gcd(2*a, n) == 1:
+        inv_a = invert(a, n)
+        b *= inv_a
+        c *= inv_a
+        if b % 2:
+            b += n
+        b >>= 1
+        return sorted((i - b) % n for i in sqrt_mod_iter(b**2 - c, n))
+    res = set()
+    for i in sqrt_mod_iter(b**2 - 4*a*c, 4*a*n):
+        q, rem = divmod(i - b, 2*a)
+        if rem == 0:
+            res.add(q % n)
+
+    return sorted(res)
+
+
+def _valid_expr(expr):
+    """
+    return coefficients of expr if it is a univariate polynomial
+    with integer coefficients else raise a ValueError.
+    """
+
+    if not expr.is_polynomial():
+        raise ValueError("The expression should be a polynomial")
+    polynomial = Poly(expr)
+    if not polynomial.is_univariate:
+        raise ValueError("The expression should be univariate")
+    if not polynomial.domain == ZZ:
+        raise ValueError("The expression should should have integer coefficients")
+    return polynomial.all_coeffs()
+
+
+def polynomial_congruence(expr, m):
+    """
+    Find the solutions to a polynomial congruence equation modulo m.
+
+    Parameters
+    ==========
+
+    expr : integer coefficient polynomial
+    m : positive integer
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory import polynomial_congruence
+    >>> from sympy.abc import x
+    >>> expr = x**6 - 2*x**5 -35
+    >>> polynomial_congruence(expr, 6125)
+    [3257]
+
+    See Also
+    ========
+
+    sympy.polys.galoistools.gf_csolve : low level solving routine used by this routine
+
+    """
+    coefficients = _valid_expr(expr)
+    coefficients = [num % m for num in coefficients]
+    rank = len(coefficients)
+    if rank == 3:
+        return quadratic_congruence(*coefficients, m)
+    if rank == 2:
+        return quadratic_congruence(0, *coefficients, m)
+    if coefficients[0] == 1 and 1 + coefficients[-1] == sum(coefficients):
+        return nthroot_mod(-coefficients[-1], rank - 1, m, True)
+    return gf_csolve(coefficients, m)
+
+
+def binomial_mod(n, m, k):
+    """Compute ``binomial(n, m) % k``.
+
+    Explanation
+    ===========
+
+    Returns ``binomial(n, m) % k`` using a generalization of Lucas'
+    Theorem for prime powers given by Granville [1]_, in conjunction with
+    the Chinese Remainder Theorem.  The residue for each prime power
+    is calculated in time O(log^2(n) + q^4*log(n)log(p) + q^4*p*log^3(p)).
+
+    Parameters
+    ==========
+
+    n : an integer
+    m : an integer
+    k : a positive integer
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.residue_ntheory import binomial_mod
+    >>> binomial_mod(10, 2, 6)  # binomial(10, 2) = 45
+    3
+    >>> binomial_mod(17, 9, 10)  # binomial(17, 9) = 24310
+    0
+
+    References
+    ==========
+
+    .. [1] Binomial coefficients modulo prime powers, Andrew Granville,
+        Available: https://web.archive.org/web/20170202003812/http://www.dms.umontreal.ca/~andrew/PDF/BinCoeff.pdf
+    """
+    if k < 1: raise ValueError('k is required to be positive')
+    # We decompose q into a product of prime powers and apply
+    # the generalization of Lucas' Theorem given by Granville
+    # to obtain binomial(n, k) mod p^e, and then use the Chinese
+    # Remainder Theorem to obtain the result mod q
+    if n < 0 or m < 0 or m > n: return 0
+    factorisation = factorint(k)
+    residues = [_binomial_mod_prime_power(n, m, p, e) for p, e in factorisation.items()]
+    return crt([p**pw for p, pw in factorisation.items()], residues, check=False)[0]
+
+
+def _binomial_mod_prime_power(n, m, p, q):
+    """Compute ``binomial(n, m) % p**q`` for a prime ``p``.
+
+    Parameters
+    ==========
+
+    n : positive integer
+    m : a nonnegative integer
+    p : a prime
+    q : a positive integer (the prime exponent)
+
+    Examples
+    ========
+
+    >>> from sympy.ntheory.residue_ntheory import _binomial_mod_prime_power
+    >>> _binomial_mod_prime_power(10, 2, 3, 2)  # binomial(10, 2) = 45
+    0
+    >>> _binomial_mod_prime_power(17, 9, 2, 4)  # binomial(17, 9) = 24310
+    6
+
+    References
+    ==========
+
+    .. [1] Binomial coefficients modulo prime powers, Andrew Granville,
+        Available: https://web.archive.org/web/20170202003812/http://www.dms.umontreal.ca/~andrew/PDF/BinCoeff.pdf
+    """
+    # Function/variable naming within this function follows Ref.[1]
+    # n!_p will be used to denote the product of integers <= n not divisible by
+    # p, with binomial(n, m)_p the same as binomial(n, m), but defined using
+    # n!_p in place of n!
+    modulo = pow(p, q)
+
+    def up_factorial(u):
+        """Compute (u*p)!_p modulo p^q."""
+        r = q // 2
+        fac = prod = 1
+        if r == 1 and p == 2 or 2*r + 1 in (p, p*p):
+            if q % 2 == 1: r += 1
+            modulo, div = pow(p, 2*r), pow(p, 2*r - q)
+        else:
+            modulo, div = pow(p, 2*r + 1), pow(p, (2*r + 1) - q)
+        for j in range(1, r + 1):
+            for mul in range((j - 1)*p + 1, j*p):  # ignore jp itself
+                fac *= mul
+                fac %= modulo
+            bj_ = bj(u, j, r)
+            prod *= pow(fac, bj_, modulo)
+            prod %= modulo
+        if p == 2:
+            sm = u // 2
+            for j in range(1, r + 1): sm += j//2 * bj(u, j, r)
+            if sm % 2 == 1: prod *= -1
+        prod %= modulo//div
+        return prod % modulo
+
+    def bj(u, j, r):
+        """Compute the exponent of (j*p)!_p in the calculation of (u*p)!_p."""
+        prod = u
+        for i in range(1, r + 1):
+            if i != j: prod *= u*u - i*i
+        for i in range(1, r + 1):
+            if i != j: prod //= j*j - i*i
+        return prod // j
+
+    def up_plus_v_binom(u, v):
+        """Compute binomial(u*p + v, v)_p modulo p^q."""
+        prod = 1
+        div = invert(factorial(v), modulo)
+        for j in range(1, q):
+            b = div
+            for v_ in range(j*p + 1, j*p + v + 1):
+                b *= v_
+                b %= modulo
+            aj = u
+            for i in range(1, q):
+                if i != j: aj *= u - i
+            for i in range(1, q):
+                if i != j: aj //= j - i
+            aj //= j
+            prod *= pow(b, aj, modulo)
+            prod %= modulo
+        return prod
+
+    @recurrence_memo([1])
+    def factorial(v, prev):
+        """Compute v! modulo p^q."""
+        return v*prev[-1] % modulo
+
+    def factorial_p(n):
+        """Compute n!_p modulo p^q."""
+        u, v = divmod(n, p)
+        return (factorial(v) * up_factorial(u) * up_plus_v_binom(u, v)) % modulo
+
+    prod = 1
+    Nj, Mj, Rj = n, m, n - m
+    # e0 will be the p-adic valuation of binomial(n, m) at p
+    e0 = carry = eq_1 = j = 0
+    while Nj:
+        numerator = factorial_p(Nj % modulo)
+        denominator = factorial_p(Mj % modulo) * factorial_p(Rj % modulo) % modulo
+        Nj, (Mj, mj), (Rj, rj) = Nj//p, divmod(Mj, p), divmod(Rj, p)
+        carry = (mj + rj + carry) // p
+        e0 += carry
+        if j >= q - 1: eq_1 += carry
+        prod *= numerator * invert(denominator, modulo)
+        prod %= modulo
+        j += 1
+
+    mul = pow(1 if p == 2 and q >= 3 else -1, eq_1, modulo)
+    return (pow(p, e0, modulo) * mul * prod) % modulo
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_bbp_pi.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_bbp_pi.py
new file mode 100644
index 0000000000000000000000000000000000000000..69c24970239cc45eef4140bf19dfd7d4f6a7e150
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_bbp_pi.py
@@ -0,0 +1,134 @@
+from sympy.core.random import randint
+
+from sympy.ntheory.bbp_pi import pi_hex_digits
+from sympy.testing.pytest import raises
+
+
+# http://www.herongyang.com/Cryptography/Blowfish-First-8366-Hex-Digits-of-PI.html
+# There are actually 8336 listed there; with the prepended 3 there are 8337
+# below
+dig=''.join('''
+3243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89452821e638d013
+77be5466cf34e90c6cc0ac29b7c97c50dd3f84d5b5b54709179216d5d98979fb1bd1310ba698dfb5
+ac2ffd72dbd01adfb7b8e1afed6a267e96ba7c9045f12c7f9924a19947b3916cf70801f2e2858efc
+16636920d871574e69a458fea3f4933d7e0d95748f728eb658718bcd5882154aee7b54a41dc25a59
+b59c30d5392af26013c5d1b023286085f0ca417918b8db38ef8e79dcb0603a180e6c9e0e8bb01e8a
+3ed71577c1bd314b2778af2fda55605c60e65525f3aa55ab945748986263e8144055ca396a2aab10
+b6b4cc5c341141e8cea15486af7c72e993b3ee1411636fbc2a2ba9c55d741831f6ce5c3e169b8793
+1eafd6ba336c24cf5c7a325381289586773b8f48986b4bb9afc4bfe81b6628219361d809ccfb21a9
+91487cac605dec8032ef845d5de98575b1dc262302eb651b8823893e81d396acc50f6d6ff383f442
+392e0b4482a484200469c8f04a9e1f9b5e21c66842f6e96c9a670c9c61abd388f06a51a0d2d8542f
+68960fa728ab5133a36eef0b6c137a3be4ba3bf0507efb2a98a1f1651d39af017666ca593e82430e
+888cee8619456f9fb47d84a5c33b8b5ebee06f75d885c12073401a449f56c16aa64ed3aa62363f77
+061bfedf72429b023d37d0d724d00a1248db0fead349f1c09b075372c980991b7b25d479d8f6e8de
+f7e3fe501ab6794c3b976ce0bd04c006bac1a94fb6409f60c45e5c9ec2196a246368fb6faf3e6c53
+b51339b2eb3b52ec6f6dfc511f9b30952ccc814544af5ebd09bee3d004de334afd660f2807192e4b
+b3c0cba85745c8740fd20b5f39b9d3fbdb5579c0bd1a60320ad6a100c6402c7279679f25fefb1fa3
+cc8ea5e9f8db3222f83c7516dffd616b152f501ec8ad0552ab323db5fafd23876053317b483e00df
+829e5c57bbca6f8ca01a87562edf1769dbd542a8f6287effc3ac6732c68c4f5573695b27b0bbca58
+c8e1ffa35db8f011a010fa3d98fd2183b84afcb56c2dd1d35b9a53e479b6f84565d28e49bc4bfb97
+90e1ddf2daa4cb7e3362fb1341cee4c6e8ef20cada36774c01d07e9efe2bf11fb495dbda4dae9091
+98eaad8e716b93d5a0d08ed1d0afc725e08e3c5b2f8e7594b78ff6e2fbf2122b648888b812900df0
+1c4fad5ea0688fc31cd1cff191b3a8c1ad2f2f2218be0e1777ea752dfe8b021fa1e5a0cc0fb56f74
+e818acf3d6ce89e299b4a84fe0fd13e0b77cc43b81d2ada8d9165fa2668095770593cc7314211a14
+77e6ad206577b5fa86c75442f5fb9d35cfebcdaf0c7b3e89a0d6411bd3ae1e7e4900250e2d2071b3
+5e226800bb57b8e0af2464369bf009b91e5563911d59dfa6aa78c14389d95a537f207d5ba202e5b9
+c5832603766295cfa911c819684e734a41b3472dca7b14a94a1b5100529a532915d60f573fbc9bc6
+e42b60a47681e6740008ba6fb5571be91ff296ec6b2a0dd915b6636521e7b9f9b6ff34052ec58556
+6453b02d5da99f8fa108ba47996e85076a4b7a70e9b5b32944db75092ec4192623ad6ea6b049a7df
+7d9cee60b88fedb266ecaa8c71699a17ff5664526cc2b19ee1193602a575094c29a0591340e4183a
+3e3f54989a5b429d656b8fe4d699f73fd6a1d29c07efe830f54d2d38e6f0255dc14cdd20868470eb
+266382e9c6021ecc5e09686b3f3ebaefc93c9718146b6a70a1687f358452a0e286b79c5305aa5007
+373e07841c7fdeae5c8e7d44ec5716f2b8b03ada37f0500c0df01c1f040200b3ffae0cf51a3cb574
+b225837a58dc0921bdd19113f97ca92ff69432477322f547013ae5e58137c2dadcc8b576349af3dd
+a7a94461460fd0030eecc8c73ea4751e41e238cd993bea0e2f3280bba1183eb3314e548b384f6db9
+086f420d03f60a04bf2cb8129024977c795679b072bcaf89afde9a771fd9930810b38bae12dccf3f
+2e5512721f2e6b7124501adde69f84cd877a5847187408da17bc9f9abce94b7d8cec7aec3adb851d
+fa63094366c464c3d2ef1c18473215d908dd433b3724c2ba1612a14d432a65c45150940002133ae4
+dd71dff89e10314e5581ac77d65f11199b043556f1d7a3c76b3c11183b5924a509f28fe6ed97f1fb
+fa9ebabf2c1e153c6e86e34570eae96fb1860e5e0a5a3e2ab3771fe71c4e3d06fa2965dcb999e71d
+0f803e89d65266c8252e4cc9789c10b36ac6150eba94e2ea78a5fc3c531e0a2df4f2f74ea7361d2b
+3d1939260f19c279605223a708f71312b6ebadfe6eeac31f66e3bc4595a67bc883b17f37d1018cff
+28c332ddefbe6c5aa56558218568ab9802eecea50fdb2f953b2aef7dad5b6e2f841521b628290761
+70ecdd4775619f151013cca830eb61bd960334fe1eaa0363cfb5735c904c70a239d59e9e0bcbaade
+14eecc86bc60622ca79cab5cabb2f3846e648b1eaf19bdf0caa02369b9655abb5040685a323c2ab4
+b3319ee9d5c021b8f79b540b19875fa09995f7997e623d7da8f837889a97e32d7711ed935f166812
+810e358829c7e61fd696dedfa17858ba9957f584a51b2272639b83c3ff1ac24696cdb30aeb532e30
+548fd948e46dbc312858ebf2ef34c6ffeafe28ed61ee7c3c735d4a14d9e864b7e342105d14203e13
+e045eee2b6a3aaabeadb6c4f15facb4fd0c742f442ef6abbb5654f3b1d41cd2105d81e799e86854d
+c7e44b476a3d816250cf62a1f25b8d2646fc8883a0c1c7b6a37f1524c369cb749247848a0b5692b2
+85095bbf00ad19489d1462b17423820e0058428d2a0c55f5ea1dadf43e233f70613372f0928d937e
+41d65fecf16c223bdb7cde3759cbee74604085f2a7ce77326ea607808419f8509ee8efd85561d997
+35a969a7aac50c06c25a04abfc800bcadc9e447a2ec3453484fdd567050e1e9ec9db73dbd3105588
+cd675fda79e3674340c5c43465713e38d83d28f89ef16dff20153e21e78fb03d4ae6e39f2bdb83ad
+f7e93d5a68948140f7f64c261c94692934411520f77602d4f7bcf46b2ed4a20068d40824713320f4
+6a43b7d4b7500061af1e39f62e9724454614214f74bf8b88404d95fc1d96b591af70f4ddd366a02f
+45bfbc09ec03bd97857fac6dd031cb850496eb27b355fd3941da2547e6abca0a9a28507825530429
+f40a2c86dae9b66dfb68dc1462d7486900680ec0a427a18dee4f3ffea2e887ad8cb58ce0067af4d6
+b6aace1e7cd3375fecce78a399406b2a4220fe9e35d9f385b9ee39d7ab3b124e8b1dc9faf74b6d18
+5626a36631eae397b23a6efa74dd5b43326841e7f7ca7820fbfb0af54ed8feb397454056acba4895
+2755533a3a20838d87fe6ba9b7d096954b55a867bca1159a58cca9296399e1db33a62a4a563f3125
+f95ef47e1c9029317cfdf8e80204272f7080bb155c05282ce395c11548e4c66d2248c1133fc70f86
+dc07f9c9ee41041f0f404779a45d886e17325f51ebd59bc0d1f2bcc18f41113564257b7834602a9c
+60dff8e8a31f636c1b0e12b4c202e1329eaf664fd1cad181156b2395e0333e92e13b240b62eebeb9
+2285b2a20ee6ba0d99de720c8c2da2f728d012784595b794fd647d0862e7ccf5f05449a36f877d48
+fac39dfd27f33e8d1e0a476341992eff743a6f6eabf4f8fd37a812dc60a1ebddf8991be14cdb6e6b
+0dc67b55106d672c372765d43bdcd0e804f1290dc7cc00ffa3b5390f92690fed0b667b9ffbcedb7d
+9ca091cf0bd9155ea3bb132f88515bad247b9479bf763bd6eb37392eb3cc1159798026e297f42e31
+2d6842ada7c66a2b3b12754ccc782ef11c6a124237b79251e706a1bbe64bfb63501a6b101811caed
+fa3d25bdd8e2e1c3c9444216590a121386d90cec6ed5abea2a64af674eda86a85fbebfe98864e4c3
+fe9dbc8057f0f7c08660787bf86003604dd1fd8346f6381fb07745ae04d736fccc83426b33f01eab
+71b08041873c005e5f77a057bebde8ae2455464299bf582e614e58f48ff2ddfda2f474ef388789bd
+c25366f9c3c8b38e74b475f25546fcd9b97aeb26618b1ddf84846a0e79915f95e2466e598e20b457
+708cd55591c902de4cb90bace1bb8205d011a862487574a99eb77f19b6e0a9dc09662d09a1c43246
+33e85a1f0209f0be8c4a99a0251d6efe101ab93d1d0ba5a4dfa186f20f2868f169dcb7da83573906
+fea1e2ce9b4fcd7f5250115e01a70683faa002b5c40de6d0279af88c27773f8641c3604c0661a806
+b5f0177a28c0f586e0006058aa30dc7d6211e69ed72338ea6353c2dd94c2c21634bbcbee5690bcb6
+deebfc7da1ce591d766f05e4094b7c018839720a3d7c927c2486e3725f724d9db91ac15bb4d39eb8
+fced54557808fca5b5d83d7cd34dad0fc41e50ef5eb161e6f8a28514d96c51133c6fd5c7e756e14e
+c4362abfceddc6c837d79a323492638212670efa8e406000e03a39ce37d3faf5cfabc277375ac52d
+1b5cb0679e4fa33742d382274099bc9bbed5118e9dbf0f7315d62d1c7ec700c47bb78c1b6b21a190
+45b26eb1be6a366eb45748ab2fbc946e79c6a376d26549c2c8530ff8ee468dde7dd5730a1d4cd04d
+c62939bbdba9ba4650ac9526e8be5ee304a1fad5f06a2d519a63ef8ce29a86ee22c089c2b843242e
+f6a51e03aa9cf2d0a483c061ba9be96a4d8fe51550ba645bd62826a2f9a73a3ae14ba99586ef5562
+e9c72fefd3f752f7da3f046f6977fa0a5980e4a91587b086019b09e6ad3b3ee593e990fd5a9e34d7
+972cf0b7d9022b8b5196d5ac3a017da67dd1cf3ed67c7d2d281f9f25cfadf2b89b5ad6b4725a88f5
+4ce029ac71e019a5e647b0acfded93fa9be8d3c48d283b57ccf8d5662979132e28785f0191ed7560
+55f7960e44e3d35e8c15056dd488f46dba03a161250564f0bdc3eb9e153c9057a297271aeca93a07
+2a1b3f6d9b1e6321f5f59c66fb26dcf3197533d928b155fdf5035634828aba3cbb28517711c20ad9
+f8abcc5167ccad925f4de817513830dc8e379d58629320f991ea7a90c2fb3e7bce5121ce64774fbe
+32a8b6e37ec3293d4648de53696413e680a2ae0810dd6db22469852dfd09072166b39a460a6445c0
+dd586cdecf1c20c8ae5bbef7dd1b588d40ccd2017f6bb4e3bbdda26a7e3a59ff453e350a44bcb4cd
+d572eacea8fa6484bb8d6612aebf3c6f47d29be463542f5d9eaec2771bf64e6370740e0d8de75b13
+57f8721671af537d5d4040cb084eb4e2cc34d2466a0115af84e1b0042895983a1d06b89fb4ce6ea0
+486f3f3b823520ab82011a1d4b277227f8611560b1e7933fdcbb3a792b344525bda08839e151ce79
+4b2f32c9b7a01fbac9e01cc87ebcc7d1f6cf0111c3a1e8aac71a908749d44fbd9ad0dadecbd50ada
+380339c32ac69136678df9317ce0b12b4ff79e59b743f5bb3af2d519ff27d9459cbf97222c15e6fc
+2a0f91fc719b941525fae59361ceb69cebc2a8645912baa8d1b6c1075ee3056a0c10d25065cb03a4
+42e0ec6e0e1698db3b4c98a0be3278e9649f1f9532e0d392dfd3a0342b8971f21e1b0a74414ba334
+8cc5be7120c37632d8df359f8d9b992f2ee60b6f470fe3f11de54cda541edad891ce6279cfcd3e7e
+6f1618b166fd2c1d05848fd2c5f6fb2299f523f357a632762393a8353156cccd02acf081625a75eb
+b56e16369788d273ccde96629281b949d04c50901b71c65614e6c6c7bd327a140a45e1d006c3f27b
+9ac9aa53fd62a80f00bb25bfe235bdd2f671126905b2040222b6cbcf7ccd769c2b53113ec01640e3
+d338abbd602547adf0ba38209cf746ce7677afa1c52075606085cbfe4e8ae88dd87aaaf9b04cf9aa
+7e1948c25c02fb8a8c01c36ae4d6ebe1f990d4f869a65cdea03f09252dc208e69fb74e6132ce77e2
+5b578fdfe33ac372e6'''.split())
+
+
+def test_hex_pi_nth_digits():
+    assert pi_hex_digits(0) == '3243f6a8885a30'
+    assert pi_hex_digits(1) ==  '243f6a8885a308'
+    assert pi_hex_digits(10000) == '68ac8fcfb8016c'
+    assert pi_hex_digits(13) == '08d313198a2e03'
+    assert pi_hex_digits(0, 3) == '324'
+    assert pi_hex_digits(0, 0) == ''
+    raises(ValueError, lambda: pi_hex_digits(-1))
+    raises(ValueError, lambda: pi_hex_digits(0, -1))
+    raises(ValueError, lambda: pi_hex_digits(3.14))
+
+    # this will pick a random segment to compute every time
+    # it is run. If it ever fails, there is an error in the
+    # computation.
+    n = randint(0, len(dig))
+    prec = randint(0, len(dig) - n)
+    assert pi_hex_digits(n, prec) == dig[n: n + prec]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_continued_fraction.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_continued_fraction.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ca6088507f1d112e9146cd5249b1143f375c2cf
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_continued_fraction.py
@@ -0,0 +1,77 @@
+import itertools
+from sympy.core import GoldenRatio as phi
+from sympy.core.numbers import (Rational, pi)
+from sympy.core.singleton import S
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.ntheory.continued_fraction import \
+    (continued_fraction_periodic as cf_p,
+     continued_fraction_iterator as cf_i,
+     continued_fraction_convergents as cf_c,
+     continued_fraction_reduce as cf_r,
+     continued_fraction as cf)
+from sympy.testing.pytest import raises
+
+
+def test_continued_fraction():
+    assert cf_p(1, 1, 10, 0) == cf_p(1, 1, 0, 1)
+    assert cf_p(1, -1, 10, 1) == cf_p(-1, 1, 10, -1)
+    t = sqrt(2)
+    assert cf((1 + t)*(1 - t)) == cf(-1)
+    for n in [0, 2, Rational(2, 3), sqrt(2), 3*sqrt(2), 1 + 2*sqrt(3)/5,
+            (2 - 3*sqrt(5))/7, 1 + sqrt(2), (-5 + sqrt(17))/4]:
+        assert (cf_r(cf(n)) - n).expand() == 0
+        assert (cf_r(cf(-n)) + n).expand() == 0
+    raises(ValueError, lambda: cf(sqrt(2 + sqrt(3))))
+    raises(ValueError, lambda: cf(sqrt(2) + sqrt(3)))
+    raises(ValueError, lambda: cf(pi))
+    raises(ValueError, lambda: cf(.1))
+
+    raises(ValueError, lambda: cf_p(1, 0, 0))
+    raises(ValueError, lambda: cf_p(1, 1, -1))
+    assert cf_p(4, 3, 0) == [1, 3]
+    assert cf_p(0, 3, 5) == [0, 1, [2, 1, 12, 1, 2, 2]]
+    assert cf_p(1, 1, 0) == [1]
+    assert cf_p(3, 4, 0) == [0, 1, 3]
+    assert cf_p(4, 5, 0) == [0, 1, 4]
+    assert cf_p(5, 6, 0) == [0, 1, 5]
+    assert cf_p(11, 13, 0) == [0, 1, 5, 2]
+    assert cf_p(16, 19, 0) == [0, 1, 5, 3]
+    assert cf_p(27, 32, 0) == [0, 1, 5, 2, 2]
+    assert cf_p(1, 2, 5) == [[1]]
+    assert cf_p(0, 1, 2) == [1, [2]]
+    assert cf_p(6, 7, 49) == [1, 1, 6]
+    assert cf_p(3796, 1387, 0) == [2, 1, 2, 1, 4]
+    assert cf_p(3245, 10000) == [0, 3, 12, 4, 13]
+    assert cf_p(1932, 2568) == [0, 1, 3, 26, 2]
+    assert cf_p(6589, 2569) == [2, 1, 1, 3, 2, 1, 3, 1, 23]
+
+    def take(iterator, n=7):
+        return list(itertools.islice(iterator, n))
+
+    assert take(cf_i(phi)) == [1, 1, 1, 1, 1, 1, 1]
+    assert take(cf_i(pi)) == [3, 7, 15, 1, 292, 1, 1]
+
+    assert list(cf_i(Rational(17, 12))) == [1, 2, 2, 2]
+    assert list(cf_i(Rational(-17, 12))) == [-2, 1, 1, 2, 2]
+
+    assert list(cf_c([1, 6, 1, 8])) == [S.One, Rational(7, 6), Rational(8, 7), Rational(71, 62)]
+    assert list(cf_c([2])) == [S(2)]
+    assert list(cf_c([1, 1, 1, 1, 1, 1, 1])) == [S.One, S(2), Rational(3, 2), Rational(5, 3),
+                                                 Rational(8, 5), Rational(13, 8), Rational(21, 13)]
+    assert list(cf_c([1, 6, Rational(-1, 2), 4])) == [S.One, Rational(7, 6), Rational(5, 4), Rational(3, 2)]
+    assert take(cf_c([[1]])) == [S.One, S(2), Rational(3, 2), Rational(5, 3), Rational(8, 5),
+                                 Rational(13, 8), Rational(21, 13)]
+    assert take(cf_c([1, [1, 2]])) == [S.One, S(2), Rational(5, 3), Rational(7, 4), Rational(19, 11),
+                                    Rational(26, 15), Rational(71, 41)]
+
+    cf_iter_e = (2 if i == 1 else i // 3 * 2 if i % 3 == 0 else 1 for i in itertools.count(1))
+    assert take(cf_c(cf_iter_e)) == [S(2), S(3), Rational(8, 3), Rational(11, 4), Rational(19, 7),
+                                     Rational(87, 32), Rational(106, 39)]
+
+    assert cf_r([1, 6, 1, 8]) == Rational(71, 62)
+    assert cf_r([3]) == S(3)
+    assert cf_r([-1, 5, 1, 4]) == Rational(-24, 29)
+    assert (cf_r([0, 1, 1, 7, [24, 8]]) - (sqrt(3) + 2)/7).expand() == 0
+    assert cf_r([1, 5, 9]) == Rational(55, 46)
+    assert (cf_r([[1]]) - (sqrt(5) + 1)/2).expand() == 0
+    assert cf_r([-3, 1, 1, [2]]) == -1 - sqrt(2)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_digits.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_digits.py
new file mode 100644
index 0000000000000000000000000000000000000000..4284805f4ffe5b9095eacb2e83f2cd8076db3ee4
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_digits.py
@@ -0,0 +1,55 @@
+from sympy.ntheory import count_digits, digits, is_palindromic
+from sympy.core.intfunc import num_digits
+
+from sympy.testing.pytest import raises
+
+
+def test_num_digits():
+    # depending on whether one rounds up or down or uses log or log10,
+    # one or more of these will fail if you don't check for the off-by
+    # one condition
+    assert num_digits(2, 2) == 2
+    assert num_digits(2**48 - 1, 2) == 48
+    assert num_digits(1000, 10) == 4
+    assert num_digits(125, 5) == 4
+    assert num_digits(100, 16) == 2
+    assert num_digits(-1000, 10) == 4
+    # if changes are made to the function, this structured test over
+    # this range will expose problems
+    for base in range(2, 100):
+        for e in range(1, 100):
+            n = base**e
+            assert num_digits(n, base) == e + 1
+            assert num_digits(n + 1, base) == e + 1
+            assert num_digits(n - 1, base) == e
+
+
+def test_digits():
+    assert all(digits(n, 2)[1:] == [int(d) for d in format(n, 'b')]
+                for n in range(20))
+    assert all(digits(n, 8)[1:] == [int(d) for d in format(n, 'o')]
+                for n in range(20))
+    assert all(digits(n, 16)[1:] == [int(d, 16) for d in format(n, 'x')]
+                for n in range(20))
+    assert digits(2345, 34) == [34, 2, 0, 33]
+    assert digits(384753, 71) == [71, 1, 5, 23, 4]
+    assert digits(93409, 10) == [10, 9, 3, 4, 0, 9]
+    assert digits(-92838, 11) == [-11, 6, 3, 8, 2, 9]
+    assert digits(35, 10) == [10, 3, 5]
+    assert digits(35, 10, 3) == [10, 0, 3, 5]
+    assert digits(-35, 10, 4) == [-10, 0, 0, 3, 5]
+    raises(ValueError, lambda: digits(2, 2, 1))
+
+
+def test_count_digits():
+    assert count_digits(55, 2) == {1: 5, 0: 1}
+    assert count_digits(55, 10) == {5: 2}
+    n = count_digits(123)
+    assert n[4] == 0 and type(n[4]) is int
+
+
+def test_is_palindromic():
+    assert is_palindromic(-11)
+    assert is_palindromic(11)
+    assert is_palindromic(0o121, 8)
+    assert not is_palindromic(123)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_ecm.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_ecm.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f134e4e1cf68231e9f89242d2b8476b9edeabb8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_ecm.py
@@ -0,0 +1,63 @@
+from sympy.external.gmpy import invert
+from sympy.ntheory.ecm import ecm, Point
+from sympy.testing.pytest import slow
+
+@slow
+def test_ecm():
+    assert ecm(3146531246531241245132451321) == {3, 100327907731, 10454157497791297}
+    assert ecm(46167045131415113) == {43, 2634823, 407485517}
+    assert ecm(631211032315670776841) == {9312934919, 67777885039}
+    assert ecm(398883434337287) == {99476569, 4009823}
+    assert ecm(64211816600515193) == {281719, 359641, 633767}
+    assert ecm(4269021180054189416198169786894227) == {184039, 241603, 333331, 477973, 618619, 974123}
+    assert ecm(4516511326451341281684513) == {3, 39869, 131743543, 95542348571}
+    assert ecm(4132846513818654136451) == {47, 160343, 2802377, 195692803}
+    assert ecm(168541512131094651323) == {79, 113, 11011069, 1714635721}
+    #This takes ~10secs while factorint is not able to factorize this even in ~10mins
+    assert ecm(7060005655815754299976961394452809, B1=100000, B2=1000000) == {6988699669998001, 1010203040506070809}
+
+
+def test_Point():
+    #The curve is of the form y**2 = x**3 + a*x**2 + x
+    mod = 101
+    a = 10
+    a_24 = (a + 2)*invert(4, mod)
+    p1 = Point(10, 17, a_24, mod)
+    p2 = p1.double()
+    assert p2 == Point(68, 56, a_24, mod)
+    p4 = p2.double()
+    assert p4 == Point(22, 64, a_24, mod)
+    p8 = p4.double()
+    assert p8 == Point(71, 95, a_24, mod)
+    p16 = p8.double()
+    assert p16 == Point(5, 16, a_24, mod)
+    p32 = p16.double()
+    assert p32 == Point(33, 96, a_24, mod)
+
+    # p3 = p2 + p1
+    p3 = p2.add(p1, p1)
+    assert p3 == Point(1, 61, a_24, mod)
+    # p5 = p3 + p2 or p4 + p1
+    p5 = p3.add(p2, p1)
+    assert p5 == Point(49, 90, a_24, mod)
+    assert p5 == p4.add(p1, p3)
+    # p6 = 2*p3
+    p6 = p3.double()
+    assert p6 == Point(87, 43, a_24, mod)
+    assert p6 == p4.add(p2, p2)
+    # p7 = p5 + p2
+    p7 = p5.add(p2, p3)
+    assert p7 == Point(69, 23, a_24, mod)
+    assert p7 == p4.add(p3, p1)
+    assert p7 == p6.add(p1, p5)
+    # p9 = p5 + p4
+    p9 = p5.add(p4, p1)
+    assert p9 == Point(56, 99, a_24, mod)
+    assert p9 == p6.add(p3, p3)
+    assert p9 == p7.add(p2, p5)
+    assert p9 == p8.add(p1, p7)
+
+    assert p5 == p1.mont_ladder(5)
+    assert p9 == p1.mont_ladder(9)
+    assert p16 == p1.mont_ladder(16)
+    assert p9 == p3.mont_ladder(3)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_egyptian_fraction.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_egyptian_fraction.py
new file mode 100644
index 0000000000000000000000000000000000000000..a9a9fac578d93a88a648bdcf8dc34550cf4a7573
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_egyptian_fraction.py
@@ -0,0 +1,49 @@
+from sympy.core.numbers import Rational
+from sympy.ntheory.egyptian_fraction import egyptian_fraction
+from sympy.core.add import Add
+from sympy.testing.pytest import raises
+from sympy.core.random import random_complex_number
+
+
+def test_egyptian_fraction():
+    def test_equality(r, alg="Greedy"):
+        return r == Add(*[Rational(1, i) for i in egyptian_fraction(r, alg)])
+
+    r = random_complex_number(a=0, c=1, b=0, d=0, rational=True)
+    assert test_equality(r)
+
+    assert egyptian_fraction(Rational(4, 17)) == [5, 29, 1233, 3039345]
+    assert egyptian_fraction(Rational(7, 13), "Greedy") == [2, 26]
+    assert egyptian_fraction(Rational(23, 101), "Greedy") == \
+        [5, 37, 1438, 2985448, 40108045937720]
+    assert egyptian_fraction(Rational(18, 23), "Takenouchi") == \
+        [2, 6, 12, 35, 276, 2415]
+    assert egyptian_fraction(Rational(5, 6), "Graham Jewett") == \
+        [6, 7, 8, 9, 10, 42, 43, 44, 45, 56, 57, 58, 72, 73, 90, 1806, 1807,
+         1808, 1892, 1893, 1980, 3192, 3193, 3306, 5256, 3263442, 3263443,
+         3267056, 3581556, 10192056, 10650056950806]
+    assert egyptian_fraction(Rational(5, 6), "Golomb") == [2, 6, 12, 20, 30]
+    assert egyptian_fraction(Rational(5, 121), "Golomb") == [25, 1225, 3577, 7081, 11737]
+    raises(ValueError, lambda: egyptian_fraction(Rational(-4, 9)))
+    assert egyptian_fraction(Rational(8, 3), "Golomb") == [1, 2, 3, 4, 5, 6, 7,
+                                                           14, 574, 2788, 6460,
+                                                           11590, 33062, 113820]
+    assert egyptian_fraction(Rational(355, 113)) == [1, 2, 3, 4, 5, 6, 7, 8, 9,
+                                                     10, 11, 12, 27, 744, 893588,
+                                                     1251493536607,
+                                                     20361068938197002344405230]
+
+
+def test_input():
+    r = (2,3), Rational(2, 3), (Rational(2), Rational(3))
+    for m in ["Greedy", "Graham Jewett", "Takenouchi", "Golomb"]:
+        for i in r:
+            d = egyptian_fraction(i, m)
+            assert all(i.is_Integer for i in d)
+            if m == "Graham Jewett":
+                assert d == [3, 4, 12]
+            else:
+                assert d == [2, 6]
+    # check prefix
+    d = egyptian_fraction(Rational(5, 3))
+    assert d == [1, 2, 6] and all(i.is_Integer for i in d)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_elliptic_curve.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_elliptic_curve.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d49d8eac72cc622fb92dfca8c54e5cc6c8dfb8f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_elliptic_curve.py
@@ -0,0 +1,20 @@
+from sympy.ntheory.elliptic_curve import EllipticCurve
+
+
+def test_elliptic_curve():
+    # Point addition and multiplication
+    e3 = EllipticCurve(-1, 9)
+    p = e3(0, 3)
+    q = e3(-1, 3)
+    r = p + q
+    assert r.x == 1 and r.y == -3
+    r = 2*p + q
+    assert r.x == 35 and r.y == 207
+    r = -p + q
+    assert r.x == 37 and r.y == 225
+    # Verify result in http://www.lmfdb.org/EllipticCurve/Q
+    # Discriminant
+    assert EllipticCurve(-1, 9).discriminant == -34928
+    assert EllipticCurve(-2731, -55146, 1, 0, 1).discriminant == 25088
+    # Torsion points
+    assert len(EllipticCurve(0, 1).torsion_points()) == 6
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_factor_.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_factor_.py
new file mode 100644
index 0000000000000000000000000000000000000000..5174b842c49ef0e14c1ad38d2d9ad550c2a2a388
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_factor_.py
@@ -0,0 +1,702 @@
+from sympy.core.containers import Dict
+from sympy.core.mul import Mul
+from sympy.core.power import Pow
+from sympy.core.singleton import S
+from sympy.functions.combinatorial.factorials import factorial as fac
+from sympy.core.numbers import Integer, Rational
+from sympy.external.gmpy import gcd
+
+from sympy.ntheory import (totient,
+    factorint, primefactors, divisors, nextprime,
+    pollard_rho, perfect_power, multiplicity, multiplicity_in_factorial,
+    divisor_count, primorial, pollard_pm1, divisor_sigma,
+    factorrat, reduced_totient)
+from sympy.ntheory.factor_ import (smoothness, smoothness_p, proper_divisors,
+    antidivisors, antidivisor_count, _divisor_sigma, core, udivisors, udivisor_sigma,
+    udivisor_count, proper_divisor_count, primenu, primeomega,
+    mersenne_prime_exponent, is_perfect, is_abundant,
+    is_deficient, is_amicable, is_carmichael, find_carmichael_numbers_in_range,
+    find_first_n_carmichaels, dra, drm, _perfect_power, factor_cache)
+
+from sympy.testing.pytest import raises, slow
+
+from sympy.utilities.iterables import capture
+
+
+def fac_multiplicity(n, p):
+    """Return the power of the prime number p in the
+    factorization of n!"""
+    if p > n:
+        return 0
+    if p > n//2:
+        return 1
+    q, m = n, 0
+    while q >= p:
+        q //= p
+        m += q
+    return m
+
+
+def multiproduct(seq=(), start=1):
+    """
+    Return the product of a sequence of factors with multiplicities,
+    times the value of the parameter ``start``. The input may be a
+    sequence of (factor, exponent) pairs or a dict of such pairs.
+
+        >>> multiproduct({3:7, 2:5}, 4) # = 3**7 * 2**5 * 4
+        279936
+
+    """
+    if not seq:
+        return start
+    if isinstance(seq, dict):
+        seq = iter(seq.items())
+    units = start
+    multi = []
+    for base, exp in seq:
+        if not exp:
+            continue
+        elif exp == 1:
+            units *= base
+        else:
+            if exp % 2:
+                units *= base
+            multi.append((base, exp//2))
+    return units * multiproduct(multi)**2
+
+
+def test_multiplicity():
+    for b in range(2, 20):
+        for i in range(100):
+            assert multiplicity(b, b**i) == i
+            assert multiplicity(b, (b**i) * 23) == i
+            assert multiplicity(b, (b**i) * 1000249) == i
+    # Should be fast
+    assert multiplicity(10, 10**10023) == 10023
+    # Should exit quickly
+    assert multiplicity(10**10, 10**10) == 1
+    # Should raise errors for bad input
+    raises(ValueError, lambda: multiplicity(1, 1))
+    raises(ValueError, lambda: multiplicity(1, 2))
+    raises(ValueError, lambda: multiplicity(1.3, 2))
+    raises(ValueError, lambda: multiplicity(2, 0))
+    raises(ValueError, lambda: multiplicity(1.3, 0))
+
+    # handles Rationals
+    assert multiplicity(10, Rational(30, 7)) == 1
+    assert multiplicity(Rational(2, 7), Rational(4, 7)) == 1
+    assert multiplicity(Rational(1, 7), Rational(3, 49)) == 2
+    assert multiplicity(Rational(2, 7), Rational(7, 2)) == -1
+    assert multiplicity(3, Rational(1, 9)) == -2
+
+
+def test_multiplicity_in_factorial():
+    n = fac(1000)
+    for i in (2, 4, 6, 12, 30, 36, 48, 60, 72, 96):
+        assert multiplicity(i, n) == multiplicity_in_factorial(i, 1000)
+
+
+def test_private_perfect_power():
+    assert _perfect_power(0) is False
+    assert _perfect_power(1) is False
+    assert _perfect_power(2) is False
+    assert _perfect_power(3) is False
+    for x in [2, 3, 5, 6, 7, 12, 15, 105, 100003]:
+        for y in range(2, 100):
+            assert _perfect_power(x**y) == (x, y)
+            if x & 1:
+                assert _perfect_power(x**y, next_p=3) == (x, y)
+            if x == 100003:
+                assert _perfect_power(x**y, next_p=100003) == (x, y)
+            assert _perfect_power(101*x**y) == False
+            # Catalan's conjecture
+            if x**y not in [8, 9]:
+                assert _perfect_power(x**y + 1) == False
+                assert _perfect_power(x**y - 1) == False
+    for x in range(1, 10):
+        for y in range(1, 10):
+            g = gcd(x, y)
+            if g == 1:
+                assert _perfect_power(5**x * 101**y) == False
+            else:
+                assert _perfect_power(5**x * 101**y) == (5**(x//g) * 101**(y//g), g)
+
+
+def test_perfect_power():
+    raises(ValueError, lambda: perfect_power(0.1))
+    assert perfect_power(0) is False
+    assert perfect_power(1) is False
+    assert perfect_power(2) is False
+    assert perfect_power(3) is False
+    assert perfect_power(4) == (2, 2)
+    assert perfect_power(14) is False
+    assert perfect_power(25) == (5, 2)
+    assert perfect_power(22) is False
+    assert perfect_power(22, [2]) is False
+    assert perfect_power(137**(3*5*13)) == (137, 3*5*13)
+    assert perfect_power(137**(3*5*13) + 1) is False
+    assert perfect_power(137**(3*5*13) - 1) is False
+    assert perfect_power(103005006004**7) == (103005006004, 7)
+    assert perfect_power(103005006004**7 + 1) is False
+    assert perfect_power(103005006004**7 - 1) is False
+    assert perfect_power(103005006004**12) == (103005006004, 12)
+    assert perfect_power(103005006004**12 + 1) is False
+    assert perfect_power(103005006004**12 - 1) is False
+    assert perfect_power(2**10007) == (2, 10007)
+    assert perfect_power(2**10007 + 1) is False
+    assert perfect_power(2**10007 - 1) is False
+    assert perfect_power((9**99 + 1)**60) == (9**99 + 1, 60)
+    assert perfect_power((9**99 + 1)**60 + 1) is False
+    assert perfect_power((9**99 + 1)**60 - 1) is False
+    assert perfect_power((10**40000)**2, big=False) == (10**40000, 2)
+    assert perfect_power(10**100000) == (10, 100000)
+    assert perfect_power(10**100001) == (10, 100001)
+    assert perfect_power(13**4, [3, 5]) is False
+    assert perfect_power(3**4, [3, 10], factor=0) is False
+    assert perfect_power(3**3*5**3) == (15, 3)
+    assert perfect_power(2**3*5**5) is False
+    assert perfect_power(2*13**4) is False
+    assert perfect_power(2**5*3**3) is False
+    t = 2**24
+    for d in divisors(24):
+        m = perfect_power(t*3**d)
+        assert m and m[1] == d or d == 1
+        m = perfect_power(t*3**d, big=False)
+        assert m and m[1] == 2 or d == 1 or d == 3, (d, m)
+
+    # negatives and non-integer rationals
+    assert perfect_power(-4) is False
+    assert perfect_power(-8) == (-2, 3)
+    assert perfect_power(-S(1)/8) == (-S(1)/2, 3)
+    assert perfect_power(S(1)/3) == False
+    assert perfect_power(-5**15) == (-5, 15)
+    assert perfect_power(-5**15, big=False) == (-3125, 3)
+    assert perfect_power(-5**15, [15]) == (-5, 15)
+
+    n = -3 ** 60
+    assert perfect_power(n) == (-81, 15)
+    assert perfect_power(n, big=False) == (-3486784401, 3)
+    assert perfect_power(n, [3, 5], big=True) == (-531441, 5)
+    assert perfect_power(n, [3, 5], big=False) == (-3486784401, 3)
+    assert perfect_power(n, [2]) == False
+    assert perfect_power(n, [2, 15]) == (-81, 15)
+    assert perfect_power(n, [2, 13]) == False
+    assert perfect_power(n, [17]) == False
+    assert perfect_power(n, [3]) == (-3486784401, 3)
+    assert perfect_power(n + 1) == False
+
+    r = S(2) ** (2 * 5 * 7) / S(3) ** (2 * 7)
+    assert perfect_power(r) == (S(32) / 3, 14)
+    assert perfect_power(-r) == (-S(1024) / 9, 7)
+    assert perfect_power(r, big=False) == (S(34359738368) / 2187, 2)
+    assert perfect_power(r, [2, 5]) == (S(34359738368) / 2187, 2)
+    assert perfect_power(r, [5, 7]) == (S(1024) / 9, 7)
+    assert perfect_power(r, [5, 7], big=False) == (S(1024) / 9, 7)
+    assert perfect_power(r, [2, 5, 7], big=False) == (S(34359738368) / 2187, 2)
+    assert perfect_power(-r, [5, 7], big=False) == (-S(1024) / 9, 7)
+
+    assert perfect_power(-S(1) / 8) == (-S(1) / 2, 3)
+
+    assert perfect_power((-3)**60) == (3, 60)
+    assert perfect_power((-3)**61) == (-3, 61)
+
+    assert perfect_power(S(2 ** 9) / 3 ** 12) == (S(8)/81, 3)
+    assert perfect_power(Rational(1, 2)**3) == (S.Half, 3)
+    assert perfect_power(Rational(-3, 2)**3) == (-3*S.Half, 3)
+
+
+def test_factor_cache():
+    factor_cache.cache_clear()
+    raises(ValueError, lambda: factor_cache.__setitem__(1, 5))
+    raises(ValueError, lambda: factor_cache.__setitem__(10, 1))
+    raises(ValueError, lambda: factor_cache.__setitem__(10, 10))
+    raises(ValueError, lambda: factor_cache.__setitem__(10, 3))
+    raises(ValueError, lambda: factor_cache.__setitem__(20, 4))
+    factor_cache.maxsize = 3
+    for i in range(2, 10):
+        factor_cache[5*i] = 5
+    assert len(factor_cache) == 3
+    factor_cache.maxsize = 5
+    for i in range(2, 10):
+        factor_cache[5*i] = 5
+    assert len(factor_cache) == 5
+    factor_cache.maxsize = 2
+    assert len(factor_cache) == 2
+    factor_cache.maxsize =1000
+
+    factor_cache.cache_clear()
+    factor_cache[40] = 5
+    assert factor_cache.get(40) == 5
+    assert factor_cache.get(20) is None
+    assert factor_cache[40] == 5
+    raises(KeyError, lambda: factor_cache[10])
+    del factor_cache[40]
+    assert len(factor_cache) == 0
+    raises(KeyError, lambda: factor_cache.__delitem__(40))
+    factor_cache.add(100, [5, 2])
+    assert len(factor_cache) == 2
+    assert factor_cache[100] == 5
+
+    for n in [1000000007, 10000019*20000003]:
+        factorint(n)
+        assert n in factor_cache
+
+    # Restore the initial state
+    factor_cache.cache_clear()
+    factor_cache.maxsize = 1000
+
+
+@slow
+def test_factorint():
+    assert primefactors(123456) == [2, 3, 643]
+    assert factorint(0) == {0: 1}
+    assert factorint(1) == {}
+    assert factorint(-1) == {-1: 1}
+    assert factorint(-2) == {-1: 1, 2: 1}
+    assert factorint(-16) == {-1: 1, 2: 4}
+    assert factorint(2) == {2: 1}
+    assert factorint(126) == {2: 1, 3: 2, 7: 1}
+    assert factorint(123456) == {2: 6, 3: 1, 643: 1}
+    assert factorint(5951757) == {3: 1, 7: 1, 29: 2, 337: 1}
+    assert factorint(64015937) == {7993: 1, 8009: 1}
+    assert factorint(2**(2**6) + 1) == {274177: 1, 67280421310721: 1}
+    #issue 19683
+    assert factorint(10**38 - 1) == {3: 2, 11: 1, 909090909090909091: 1, 1111111111111111111: 1}
+    #issue 17676
+    assert factorint(28300421052393658575) == {3: 1, 5: 2, 11: 2, 43: 1, 2063: 2, 4127: 1, 4129: 1}
+    assert factorint(2063**2 * 4127**1 * 4129**1) == {2063: 2, 4127: 1, 4129: 1}
+    assert factorint(2347**2 * 7039**1 * 7043**1) == {2347: 2, 7039: 1, 7043: 1}
+
+    assert factorint(0, multiple=True) == [0]
+    assert factorint(1, multiple=True) == []
+    assert factorint(-1, multiple=True) == [-1]
+    assert factorint(-2, multiple=True) == [-1, 2]
+    assert factorint(-16, multiple=True) == [-1, 2, 2, 2, 2]
+    assert factorint(2, multiple=True) == [2]
+    assert factorint(24, multiple=True) == [2, 2, 2, 3]
+    assert factorint(126, multiple=True) == [2, 3, 3, 7]
+    assert factorint(123456, multiple=True) == [2, 2, 2, 2, 2, 2, 3, 643]
+    assert factorint(5951757, multiple=True) == [3, 7, 29, 29, 337]
+    assert factorint(64015937, multiple=True) == [7993, 8009]
+    assert factorint(2**(2**6) + 1, multiple=True) == [274177, 67280421310721]
+
+    assert factorint(fac(1, evaluate=False)) == {}
+    assert factorint(fac(7, evaluate=False)) == {2: 4, 3: 2, 5: 1, 7: 1}
+    assert factorint(fac(15, evaluate=False)) == \
+        {2: 11, 3: 6, 5: 3, 7: 2, 11: 1, 13: 1}
+    assert factorint(fac(20, evaluate=False)) == \
+        {2: 18, 3: 8, 5: 4, 7: 2, 11: 1, 13: 1, 17: 1, 19: 1}
+    assert factorint(fac(23, evaluate=False)) == \
+        {2: 19, 3: 9, 5: 4, 7: 3, 11: 2, 13: 1, 17: 1, 19: 1, 23: 1}
+
+    assert multiproduct(factorint(fac(200))) == fac(200)
+    assert multiproduct(factorint(fac(200, evaluate=False))) == fac(200)
+    for b, e in factorint(fac(150)).items():
+        assert e == fac_multiplicity(150, b)
+    for b, e in factorint(fac(150, evaluate=False)).items():
+        assert e == fac_multiplicity(150, b)
+    assert factorint(103005006059**7) == {103005006059: 7}
+    assert factorint(31337**191) == {31337: 191}
+    assert factorint(2**1000 * 3**500 * 257**127 * 383**60) == \
+        {2: 1000, 3: 500, 257: 127, 383: 60}
+    assert len(factorint(fac(10000))) == 1229
+    assert len(factorint(fac(10000, evaluate=False))) == 1229
+    assert factorint(12932983746293756928584532764589230) == \
+        {2: 1, 5: 1, 73: 1, 727719592270351: 1, 63564265087747: 1, 383: 1}
+    assert factorint(727719592270351) == {727719592270351: 1}
+    assert factorint(2**64 + 1, use_trial=False) == factorint(2**64 + 1)
+    for n in range(60000):
+        assert multiproduct(factorint(n)) == n
+    assert pollard_rho(2**64 + 1, seed=1) == 274177
+    assert pollard_rho(19, seed=1) is None
+    assert factorint(3, limit=2) == {3: 1}
+    assert factorint(12345) == {3: 1, 5: 1, 823: 1}
+    assert factorint(
+        12345, limit=3) == {4115: 1, 3: 1}  # the 5 is greater than the limit
+    assert factorint(1, limit=1) == {}
+    assert factorint(0, 3) == {0: 1}
+    assert factorint(12, limit=1) == {12: 1}
+    assert factorint(30, limit=2) == {2: 1, 15: 1}
+    assert factorint(16, limit=2) == {2: 4}
+    assert factorint(124, limit=3) == {2: 2, 31: 1}
+    assert factorint(4*31**2, limit=3) == {2: 2, 31: 2}
+    p1 = nextprime(2**32)
+    p2 = nextprime(2**16)
+    p3 = nextprime(p2)
+    assert factorint(p1*p2*p3) == {p1: 1, p2: 1, p3: 1}
+    assert factorint(13*17*19, limit=15) == {13: 1, 17*19: 1}
+    assert factorint(1951*15013*15053, limit=2000) == {225990689: 1, 1951: 1}
+    assert factorint(primorial(17) + 1, use_pm1=0) == \
+        {int(19026377261): 1, 3467: 1, 277: 1, 105229: 1}
+    # when prime b is closer than approx sqrt(8*p) to prime p then they are
+    # "close" and have a trivial factorization
+    a = nextprime(2**2**8)  # 78 digits
+    b = nextprime(a + 2**2**4)
+    assert 'Fermat' in capture(lambda: factorint(a*b, verbose=1))
+
+    raises(ValueError, lambda: pollard_rho(4))
+    raises(ValueError, lambda: pollard_pm1(3))
+    raises(ValueError, lambda: pollard_pm1(10, B=2))
+    # verbose coverage
+    n = nextprime(2**16)*nextprime(2**17)*nextprime(1901)
+    assert 'with primes' in capture(lambda: factorint(n, verbose=1))
+    capture(lambda: factorint(nextprime(2**16)*1012, verbose=1))
+
+    n = nextprime(2**17)
+    capture(lambda: factorint(n**3, verbose=1))  # perfect power termination
+    capture(lambda: factorint(2*n, verbose=1))  # factoring complete msg
+
+    # exceed 1st
+    n = nextprime(2**17)
+    n *= nextprime(n)
+    assert '1000' in capture(lambda: factorint(n, limit=1000, verbose=1))
+    n *= nextprime(n)
+    assert len(factorint(n)) == 3
+    assert len(factorint(n, limit=p1)) == 3
+    n *= nextprime(2*n)
+    # exceed 2nd
+    assert '2001' in capture(lambda: factorint(n, limit=2000, verbose=1))
+    assert capture(
+        lambda: factorint(n, limit=4000, verbose=1)).count('Pollard') == 2
+    # non-prime pm1 result
+    n = nextprime(8069)
+    n *= nextprime(2*n)*nextprime(2*n, 2)
+    capture(lambda: factorint(n, verbose=1))  # non-prime pm1 result
+    # factor fermat composite
+    p1 = nextprime(2**17)
+    p2 = nextprime(2*p1)
+    assert factorint((p1*p2**2)**3) == {p1: 3, p2: 6}
+    # Test for non integer input
+    raises(ValueError, lambda: factorint(4.5))
+    # test dict/Dict input
+    sans = '2**10*3**3'
+    n = {4: 2, 12: 3}
+    assert str(factorint(n)) == sans
+    assert str(factorint(Dict(n))) == sans
+
+
+def test_divisors_and_divisor_count():
+    assert divisors(-1) == [1]
+    assert divisors(0) == []
+    assert divisors(1) == [1]
+    assert divisors(2) == [1, 2]
+    assert divisors(3) == [1, 3]
+    assert divisors(17) == [1, 17]
+    assert divisors(10) == [1, 2, 5, 10]
+    assert divisors(100) == [1, 2, 4, 5, 10, 20, 25, 50, 100]
+    assert divisors(101) == [1, 101]
+    assert type(divisors(2, generator=True)) is not list
+
+    assert divisor_count(0) == 0
+    assert divisor_count(-1) == 1
+    assert divisor_count(1) == 1
+    assert divisor_count(6) == 4
+    assert divisor_count(12) == 6
+
+    assert divisor_count(180, 3) == divisor_count(180//3)
+    assert divisor_count(2*3*5, 7) == 0
+
+
+def test_proper_divisors_and_proper_divisor_count():
+    assert proper_divisors(-1) == []
+    assert proper_divisors(0) == []
+    assert proper_divisors(1) == []
+    assert proper_divisors(2) == [1]
+    assert proper_divisors(3) == [1]
+    assert proper_divisors(17) == [1]
+    assert proper_divisors(10) == [1, 2, 5]
+    assert proper_divisors(100) == [1, 2, 4, 5, 10, 20, 25, 50]
+    assert proper_divisors(1000000007) == [1]
+    assert type(proper_divisors(2, generator=True)) is not list
+
+    assert proper_divisor_count(0) == 0
+    assert proper_divisor_count(-1) == 0
+    assert proper_divisor_count(1) == 0
+    assert proper_divisor_count(36) == 8
+    assert proper_divisor_count(2*3*5) == 7
+
+
+def test_udivisors_and_udivisor_count():
+    assert udivisors(-1) == [1]
+    assert udivisors(0) == []
+    assert udivisors(1) == [1]
+    assert udivisors(2) == [1, 2]
+    assert udivisors(3) == [1, 3]
+    assert udivisors(17) == [1, 17]
+    assert udivisors(10) == [1, 2, 5, 10]
+    assert udivisors(100) == [1, 4, 25, 100]
+    assert udivisors(101) == [1, 101]
+    assert udivisors(1000) == [1, 8, 125, 1000]
+    assert type(udivisors(2, generator=True)) is not list
+
+    assert udivisor_count(0) == 0
+    assert udivisor_count(-1) == 1
+    assert udivisor_count(1) == 1
+    assert udivisor_count(6) == 4
+    assert udivisor_count(12) == 4
+
+    assert udivisor_count(180) == 8
+    assert udivisor_count(2*3*5*7) == 16
+
+
+def test_issue_6981():
+    S = set(divisors(4)).union(set(divisors(Integer(2))))
+    assert S == {1,2,4}
+
+
+def test_issue_4356():
+    assert factorint(1030903) == {53: 2, 367: 1}
+
+
+def test_divisors():
+    assert divisors(28) == [1, 2, 4, 7, 14, 28]
+    assert list(divisors(3*5*7, 1)) == [1, 3, 5, 15, 7, 21, 35, 105]
+    assert divisors(0) == []
+
+
+def test_divisor_count():
+    assert divisor_count(0) == 0
+    assert divisor_count(6) == 4
+
+
+def test_proper_divisors():
+    assert proper_divisors(-1) == []
+    assert proper_divisors(28) == [1, 2, 4, 7, 14]
+    assert list(proper_divisors(3*5*7, True)) == [1, 3, 5, 15, 7, 21, 35]
+
+
+def test_proper_divisor_count():
+    assert proper_divisor_count(6) == 3
+    assert proper_divisor_count(108) == 11
+
+
+def test_antidivisors():
+    assert antidivisors(-1) == []
+    assert antidivisors(-3) == [2]
+    assert antidivisors(14) == [3, 4, 9]
+    assert antidivisors(237) == [2, 5, 6, 11, 19, 25, 43, 95, 158]
+    assert antidivisors(12345) == [2, 6, 7, 10, 30, 1646, 3527, 4938, 8230]
+    assert antidivisors(393216) == [262144]
+    assert sorted(x for x in antidivisors(3*5*7, 1)) == \
+        [2, 6, 10, 11, 14, 19, 30, 42, 70]
+    assert antidivisors(1) == []
+    assert type(antidivisors(2, generator=True)) is not list
+
+def test_antidivisor_count():
+    assert antidivisor_count(0) == 0
+    assert antidivisor_count(-1) == 0
+    assert antidivisor_count(-4) == 1
+    assert antidivisor_count(20) == 3
+    assert antidivisor_count(25) == 5
+    assert antidivisor_count(38) == 7
+    assert antidivisor_count(180) == 6
+    assert antidivisor_count(2*3*5) == 3
+
+
+def test_smoothness_and_smoothness_p():
+    assert smoothness(1) == (1, 1)
+    assert smoothness(2**4*3**2) == (3, 16)
+
+    assert smoothness_p(10431, m=1) == \
+        (1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))])
+    assert smoothness_p(10431) == \
+        (-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))])
+    assert smoothness_p(10431, power=1) == \
+        (-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))])
+    assert smoothness_p(21477639576571, visual=1) == \
+        'p**i=4410317**1 has p-1 B=1787, B-pow=1787\n' + \
+        'p**i=4869863**1 has p-1 B=2434931, B-pow=2434931'
+
+
+def test_visual_factorint():
+    assert factorint(1, visual=1) == 1
+    forty2 = factorint(42, visual=True)
+    assert type(forty2) == Mul
+    assert str(forty2) == '2**1*3**1*7**1'
+    assert factorint(1, visual=True) is S.One
+    no = {"evaluate": False}
+    assert factorint(42**2, visual=True) == Mul(Pow(2, 2, **no),
+                                                Pow(3, 2, **no),
+                                                Pow(7, 2, **no), **no)
+    assert -1 in factorint(-42, visual=True).args
+
+
+def test_factorrat():
+    assert str(factorrat(S(12)/1, visual=True)) == '2**2*3**1'
+    assert str(factorrat(Rational(1, 1), visual=True)) == '1'
+    assert str(factorrat(S(25)/14, visual=True)) == '5**2/(2*7)'
+    assert str(factorrat(Rational(25, 14), visual=True)) == '5**2/(2*7)'
+    assert str(factorrat(S(-25)/14/9, visual=True)) == '-1*5**2/(2*3**2*7)'
+
+    assert factorrat(S(12)/1, multiple=True) == [2, 2, 3]
+    assert factorrat(Rational(1, 1), multiple=True) == []
+    assert factorrat(S(25)/14, multiple=True) == [Rational(1, 7), S.Half, 5, 5]
+    assert factorrat(Rational(25, 14), multiple=True) == [Rational(1, 7), S.Half, 5, 5]
+    assert factorrat(Rational(12, 1), multiple=True) == [2, 2, 3]
+    assert factorrat(S(-25)/14/9, multiple=True) == \
+        [-1, Rational(1, 7), Rational(1, 3), Rational(1, 3), S.Half, 5, 5]
+
+
+def test_visual_io():
+    sm = smoothness_p
+    fi = factorint
+    # with smoothness_p
+    n = 124
+    d = fi(n)
+    m = fi(d, visual=True)
+    t = sm(n)
+    s = sm(t)
+    for th in [d, s, t, n, m]:
+        assert sm(th, visual=True) == s
+        assert sm(th, visual=1) == s
+    for th in [d, s, t, n, m]:
+        assert sm(th, visual=False) == t
+    assert [sm(th, visual=None) for th in [d, s, t, n, m]] == [s, d, s, t, t]
+    assert [sm(th, visual=2) for th in [d, s, t, n, m]] == [s, d, s, t, t]
+
+    # with factorint
+    for th in [d, m, n]:
+        assert fi(th, visual=True) == m
+        assert fi(th, visual=1) == m
+    for th in [d, m, n]:
+        assert fi(th, visual=False) == d
+    assert [fi(th, visual=None) for th in [d, m, n]] == [m, d, d]
+    assert [fi(th, visual=0) for th in [d, m, n]] == [m, d, d]
+
+    # test reevaluation
+    no = {"evaluate": False}
+    assert sm({4: 2}, visual=False) == sm(16)
+    assert sm(Mul(*[Pow(k, v, **no) for k, v in {4: 2, 2: 6}.items()], **no),
+              visual=False) == sm(2**10)
+
+    assert fi({4: 2}, visual=False) == fi(16)
+    assert fi(Mul(*[Pow(k, v, **no) for k, v in {4: 2, 2: 6}.items()], **no),
+              visual=False) == fi(2**10)
+
+
+def test_core():
+    assert core(35**13, 10) == 42875
+    assert core(210**2) == 1
+    assert core(7776, 3) == 36
+    assert core(10**27, 22) == 10**5
+    assert core(537824) == 14
+    assert core(1, 6) == 1
+
+
+def test__divisor_sigma():
+    assert _divisor_sigma(23450) == 50592
+    assert _divisor_sigma(23450, 0) == 24
+    assert _divisor_sigma(23450, 1) == 50592
+    assert _divisor_sigma(23450, 2) == 730747500
+    assert _divisor_sigma(23450, 3) == 14666785333344
+    A000005 = [1, 2, 2, 3, 2, 4, 2, 4, 3, 4, 2, 6, 2, 4, 4, 5, 2, 6, 2, 6, 4,
+               4, 2, 8, 3, 4, 4, 6, 2, 8, 2, 6, 4, 4, 4, 9, 2, 4, 4, 8, 2, 8]
+    for n, val in enumerate(A000005, 1):
+        assert _divisor_sigma(n, 0) == val
+    A000203 = [1, 3, 4, 7, 6, 12, 8, 15, 13, 18, 12, 28, 14, 24, 24, 31, 18,
+               39, 20, 42, 32, 36, 24, 60, 31, 42, 40, 56, 30, 72, 32, 63, 48]
+    for n, val in enumerate(A000203, 1):
+        assert _divisor_sigma(n, 1) == val
+    A001157 = [1, 5, 10, 21, 26, 50, 50, 85, 91, 130, 122, 210, 170, 250, 260,
+               341, 290, 455, 362, 546, 500, 610, 530, 850, 651, 850, 820, 1050]
+    for n, val in enumerate(A001157, 1):
+        assert _divisor_sigma(n, 2) == val
+
+
+def test_mersenne_prime_exponent():
+    assert mersenne_prime_exponent(1) == 2
+    assert mersenne_prime_exponent(4) == 7
+    assert mersenne_prime_exponent(10) == 89
+    assert mersenne_prime_exponent(25) == 21701
+    raises(ValueError, lambda: mersenne_prime_exponent(52))
+    raises(ValueError, lambda: mersenne_prime_exponent(0))
+
+
+def test_is_perfect():
+    assert is_perfect(-6) is False
+    assert is_perfect(6) is True
+    assert is_perfect(15) is False
+    assert is_perfect(28) is True
+    assert is_perfect(400) is False
+    assert is_perfect(496) is True
+    assert is_perfect(8128) is True
+    assert is_perfect(10000) is False
+
+
+def test_is_abundant():
+    assert is_abundant(10) is False
+    assert is_abundant(12) is True
+    assert is_abundant(18) is True
+    assert is_abundant(21) is False
+    assert is_abundant(945) is True
+
+
+def test_is_deficient():
+    assert is_deficient(10) is True
+    assert is_deficient(22) is True
+    assert is_deficient(56) is False
+    assert is_deficient(20) is False
+    assert is_deficient(36) is False
+
+
+def test_is_amicable():
+    assert is_amicable(173, 129) is False
+    assert is_amicable(220, 284) is True
+    assert is_amicable(8756, 8756) is False
+
+
+def test_is_carmichael():
+    A002997 = [561, 1105, 1729, 2465, 2821, 6601, 8911, 10585, 15841,
+               29341, 41041, 46657, 52633, 62745, 63973, 75361, 101101]
+    for n in range(1, 5000):
+        assert is_carmichael(n) == (n in A002997)
+    for n in A002997:
+        assert is_carmichael(n)
+
+
+def test_find_carmichael_numbers_in_range():
+    assert find_carmichael_numbers_in_range(0, 561) == []
+    assert find_carmichael_numbers_in_range(561, 562) == [561]
+    assert find_carmichael_numbers_in_range(561, 1105) == find_carmichael_numbers_in_range(561, 562)
+    raises(ValueError, lambda: find_carmichael_numbers_in_range(-2, 2))
+    raises(ValueError, lambda: find_carmichael_numbers_in_range(22, 2))
+
+
+def test_find_first_n_carmichaels():
+    assert find_first_n_carmichaels(0) == []
+    assert find_first_n_carmichaels(1) == [561]
+    assert find_first_n_carmichaels(2) == [561, 1105]
+
+
+def test_dra():
+    assert dra(19, 12) == 8
+    assert dra(2718, 10) == 9
+    assert dra(0, 22) == 0
+    assert dra(23456789, 10) == 8
+    raises(ValueError, lambda: dra(24, -2))
+    raises(ValueError, lambda: dra(24.2, 5))
+
+def test_drm():
+    assert drm(19, 12) == 7
+    assert drm(2718, 10) == 2
+    assert drm(0, 15) == 0
+    assert drm(234161, 10) == 6
+    raises(ValueError, lambda: drm(24, -2))
+    raises(ValueError, lambda: drm(11.6, 9))
+
+
+def test_deprecated_ntheory_symbolic_functions():
+    from sympy.testing.pytest import warns_deprecated_sympy
+
+    with warns_deprecated_sympy():
+        assert primenu(3) == 1
+    with warns_deprecated_sympy():
+        assert primeomega(3) == 1
+    with warns_deprecated_sympy():
+        assert totient(3) == 2
+    with warns_deprecated_sympy():
+        assert reduced_totient(3) == 2
+    with warns_deprecated_sympy():
+        assert divisor_sigma(3) == 4
+    with warns_deprecated_sympy():
+        assert udivisor_sigma(3) == 4
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_generate.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_generate.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0e5918ffefede2e86f3be2b07d6c3a01c02e6e0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_generate.py
@@ -0,0 +1,285 @@
+from bisect import bisect, bisect_left
+
+from sympy.functions.combinatorial.numbers import mobius, totient
+from sympy.ntheory.generate import (sieve, Sieve)
+
+from sympy.ntheory import isprime, randprime, nextprime, prevprime, \
+    primerange, primepi, prime, primorial, composite, compositepi
+from sympy.ntheory.generate import cycle_length, _primepi
+from sympy.ntheory.primetest import mr
+from sympy.testing.pytest import raises
+
+def test_prime():
+    assert prime(1) == 2
+    assert prime(2) == 3
+    assert prime(5) == 11
+    assert prime(11) == 31
+    assert prime(57) == 269
+    assert prime(296) == 1949
+    assert prime(559) == 4051
+    assert prime(3000) == 27449
+    assert prime(4096) == 38873
+    assert prime(9096) == 94321
+    assert prime(25023) == 287341
+    assert prime(10000000) == 179424673 # issue #20951
+    assert prime(99999999) == 2038074739
+    raises(ValueError, lambda: prime(0))
+    sieve.extend(3000)
+    assert prime(401) == 2749
+    raises(ValueError, lambda: prime(-1))
+
+
+def test__primepi():
+    assert _primepi(-1) == 0
+    assert _primepi(1) == 0
+    assert _primepi(2) == 1
+    assert _primepi(5) == 3
+    assert _primepi(11) == 5
+    assert _primepi(57) == 16
+    assert _primepi(296) == 62
+    assert _primepi(559) == 102
+    assert _primepi(3000) == 430
+    assert _primepi(4096) == 564
+    assert _primepi(9096) == 1128
+    assert _primepi(25023) == 2763
+    assert _primepi(10**8) == 5761455
+    assert _primepi(253425253) == 13856396
+    assert _primepi(8769575643) == 401464322
+    sieve.extend(3000)
+    assert _primepi(2000) == 303
+
+
+def test_composite():
+    from sympy.ntheory.generate import sieve
+    sieve._reset()
+    assert composite(1) == 4
+    assert composite(2) == 6
+    assert composite(5) == 10
+    assert composite(11) == 20
+    assert composite(41) == 58
+    assert composite(57) == 80
+    assert composite(296) == 370
+    assert composite(559) == 684
+    assert composite(3000) == 3488
+    assert composite(4096) == 4736
+    assert composite(9096) == 10368
+    assert composite(25023) == 28088
+    sieve.extend(3000)
+    assert composite(1957) == 2300
+    assert composite(2568) == 2998
+    raises(ValueError, lambda: composite(0))
+
+
+def test_compositepi():
+    assert compositepi(1) == 0
+    assert compositepi(2) == 0
+    assert compositepi(5) == 1
+    assert compositepi(11) == 5
+    assert compositepi(57) == 40
+    assert compositepi(296) == 233
+    assert compositepi(559) == 456
+    assert compositepi(3000) == 2569
+    assert compositepi(4096) == 3531
+    assert compositepi(9096) == 7967
+    assert compositepi(25023) == 22259
+    assert compositepi(10**8) == 94238544
+    assert compositepi(253425253) == 239568856
+    assert compositepi(8769575643) == 8368111320
+    sieve.extend(3000)
+    assert compositepi(2321) == 1976
+
+
+def test_generate():
+    from sympy.ntheory.generate import sieve
+    sieve._reset()
+    assert nextprime(-4) == 2
+    assert nextprime(2) == 3
+    assert nextprime(5) == 7
+    assert nextprime(12) == 13
+    assert prevprime(3) == 2
+    assert prevprime(7) == 5
+    assert prevprime(13) == 11
+    assert prevprime(19) == 17
+    assert prevprime(20) == 19
+
+    sieve.extend_to_no(9)
+    assert sieve._list[-1] == 23
+
+    assert sieve._list[-1] < 31
+    assert 31 in sieve
+
+    assert nextprime(90) == 97
+    assert nextprime(10**40) == (10**40 + 121)
+    primelist = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31,
+                 37, 41, 43, 47, 53, 59, 61, 67, 71, 73,
+                 79, 83, 89, 97, 101, 103, 107, 109, 113,
+                 127, 131, 137, 139, 149, 151, 157, 163,
+                 167, 173, 179, 181, 191, 193, 197, 199,
+                 211, 223, 227, 229, 233, 239, 241, 251,
+                 257, 263, 269, 271, 277, 281, 283, 293]
+    for i in range(len(primelist) - 2):
+        for j in range(2, len(primelist) - i):
+            assert nextprime(primelist[i], j) == primelist[i + j]
+            if 3 < i:
+                assert nextprime(primelist[i] - 1, j) == primelist[i + j - 1]
+    raises(ValueError, lambda: nextprime(2, 0))
+    raises(ValueError, lambda: nextprime(2, -1))
+    assert prevprime(97) == 89
+    assert prevprime(10**40) == (10**40 - 17)
+
+    raises(ValueError, lambda: Sieve(0))
+    raises(ValueError, lambda: Sieve(-1))
+    for sieve_interval in [1, 10, 11, 1_000_000]:
+        s = Sieve(sieve_interval=sieve_interval)
+        for head in range(s._list[-1] + 1, (s._list[-1] + 1)**2, 2):
+            for tail in range(head + 1, (s._list[-1] + 1)**2):
+                A = list(s._primerange(head, tail))
+                B = primelist[bisect(primelist, head):bisect_left(primelist, tail)]
+                assert A == B
+        for k in range(s._list[-1], primelist[-1] - 1, 2):
+            s = Sieve(sieve_interval=sieve_interval)
+            s.extend(k)
+            assert list(s._list) == primelist[:bisect(primelist, k)]
+            s.extend(primelist[-1])
+            assert list(s._list) == primelist
+
+    assert list(sieve.primerange(10, 1)) == []
+    assert list(sieve.primerange(5, 9)) == [5, 7]
+    sieve._reset(prime=True)
+    assert list(sieve.primerange(2, 13)) == [2, 3, 5, 7, 11]
+    assert list(sieve.primerange(13)) == [2, 3, 5, 7, 11]
+    assert list(sieve.primerange(8)) == [2, 3, 5, 7]
+    assert list(sieve.primerange(-2)) == []
+    assert list(sieve.primerange(29)) == [2, 3, 5, 7, 11, 13, 17, 19, 23]
+    assert list(sieve.primerange(34)) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
+
+    assert list(sieve.totientrange(5, 15)) == [4, 2, 6, 4, 6, 4, 10, 4, 12, 6]
+    sieve._reset(totient=True)
+    assert list(sieve.totientrange(3, 13)) == [2, 2, 4, 2, 6, 4, 6, 4, 10, 4]
+    assert list(sieve.totientrange(900, 1000)) == [totient(x) for x in range(900, 1000)]
+    assert list(sieve.totientrange(0, 1)) == []
+    assert list(sieve.totientrange(1, 2)) == [1]
+
+    assert list(sieve.mobiusrange(5, 15)) == [-1, 1, -1, 0, 0, 1, -1, 0, -1, 1]
+    sieve._reset(mobius=True)
+    assert list(sieve.mobiusrange(3, 13)) == [-1, 0, -1, 1, -1, 0, 0, 1, -1, 0]
+    assert list(sieve.mobiusrange(1050, 1100)) == [mobius(x) for x in range(1050, 1100)]
+    assert list(sieve.mobiusrange(0, 1)) == []
+    assert list(sieve.mobiusrange(1, 2)) == [1]
+
+    assert list(primerange(10, 1)) == []
+    assert list(primerange(2, 7)) == [2, 3, 5]
+    assert list(primerange(2, 10)) == [2, 3, 5, 7]
+    assert list(primerange(1050, 1100)) == [1051, 1061,
+        1063, 1069, 1087, 1091, 1093, 1097]
+    s = Sieve()
+    for i in range(30, 2350, 376):
+        for j in range(2, 5096, 1139):
+            A = list(s.primerange(i, i + j))
+            B = list(primerange(i, i + j))
+            assert A == B
+    s = Sieve()
+    sieve._reset(prime=True)
+    sieve.extend(13)
+    for i in range(200):
+        for j in range(i, 200):
+            A = list(s.primerange(i, j))
+            B = list(primerange(i, j))
+            assert A == B
+    sieve.extend(1000)
+    for a, b in [(901, 1103), # a < 1000 < b < 1000**2
+                 (806, 1002007), # a < 1000 < 1000**2 < b
+                 (2000, 30001), # 1000 < a < b < 1000**2
+                 (100005, 1010001), # 1000 < a < 1000**2 < b
+                 (1003003, 1005000), # 1000**2 < a < b
+                 ]:
+        assert list(primerange(a, b)) == list(s.primerange(a, b))
+    sieve._reset(prime=True)
+    sieve.extend(100000)
+    assert len(sieve._list) == len(set(sieve._list))
+    s = Sieve()
+    assert s[10] == 29
+
+    assert nextprime(2, 2) == 5
+
+    raises(ValueError, lambda: totient(0))
+
+    raises(ValueError, lambda: primorial(0))
+
+    assert mr(1, [2]) is False
+
+    func = lambda i: (i**2 + 1) % 51
+    assert next(cycle_length(func, 4)) == (6, 3)
+    assert list(cycle_length(func, 4, values=True)) == \
+        [4, 17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]
+    assert next(cycle_length(func, 4, nmax=5)) == (5, None)
+    assert list(cycle_length(func, 4, nmax=5, values=True)) == \
+        [4, 17, 35, 2, 5]
+    sieve.extend(3000)
+    assert nextprime(2968) == 2969
+    assert prevprime(2930) == 2927
+    raises(ValueError, lambda: prevprime(1))
+    raises(ValueError, lambda: prevprime(-4))
+
+
+def test_randprime():
+    assert randprime(10, 1) is None
+    assert randprime(3, -3) is None
+    assert randprime(2, 3) == 2
+    assert randprime(1, 3) == 2
+    assert randprime(3, 5) == 3
+    raises(ValueError, lambda: randprime(-12, -2))
+    raises(ValueError, lambda: randprime(-10, 0))
+    raises(ValueError, lambda: randprime(20, 22))
+    raises(ValueError, lambda: randprime(0, 2))
+    raises(ValueError, lambda: randprime(1, 2))
+    for a in [100, 300, 500, 250000]:
+        for b in [100, 300, 500, 250000]:
+            p = randprime(a, a + b)
+            assert a <= p < (a + b) and isprime(p)
+
+
+def test_primorial():
+    assert primorial(1) == 2
+    assert primorial(1, nth=0) == 1
+    assert primorial(2) == 6
+    assert primorial(2, nth=0) == 2
+    assert primorial(4, nth=0) == 6
+
+
+def test_search():
+    assert 2 in sieve
+    assert 2.1 not in sieve
+    assert 1 not in sieve
+    assert 2**1000 not in sieve
+    raises(ValueError, lambda: sieve.search(1))
+
+
+def test_sieve_slice():
+    assert sieve[5] == 11
+    assert list(sieve[5:10]) == [sieve[x] for x in range(5, 10)]
+    assert list(sieve[5:10:2]) == [sieve[x] for x in range(5, 10, 2)]
+    assert list(sieve[1:5]) == [2, 3, 5, 7]
+    raises(IndexError, lambda: sieve[:5])
+    raises(IndexError, lambda: sieve[0])
+    raises(IndexError, lambda: sieve[0:5])
+
+def test_sieve_iter():
+    values = []
+    for value in sieve:
+        if value > 7:
+            break
+        values.append(value)
+    assert values == list(sieve[1:5])
+
+
+def test_sieve_repr():
+    assert "sieve" in repr(sieve)
+    assert "prime" in repr(sieve)
+
+
+def test_deprecated_ntheory_symbolic_functions():
+    from sympy.testing.pytest import warns_deprecated_sympy
+
+    with warns_deprecated_sympy():
+        assert primepi(0) == 0
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_hypothesis.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_hypothesis.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8f4cbecdbb7a6b15b0e323700cda11039c968fb
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_hypothesis.py
@@ -0,0 +1,24 @@
+from hypothesis import given
+from hypothesis import strategies as st
+from sympy import divisors
+from sympy.functions.combinatorial.numbers import divisor_sigma, totient
+from sympy.ntheory.primetest import is_square
+
+
+@given(n=st.integers(1, 10**10))
+def test_tau_hypothesis(n):
+    div = divisors(n)
+    tau_n = len(div)
+    assert is_square(n) == (tau_n % 2 == 1)
+    sigmas = [divisor_sigma(i) for i in div]
+    totients = [totient(n // i) for i in div]
+    mul = [a * b for a, b in zip(sigmas, totients)]
+    assert n * tau_n == sum(mul)
+
+
+@given(n=st.integers(1, 10**10))
+def test_totient_hypothesis(n):
+    assert totient(n) <= n
+    div = divisors(n)
+    totients = [totient(i) for i in div]
+    assert n == sum(totients)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_modular.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_modular.py
new file mode 100644
index 0000000000000000000000000000000000000000..10ebb1d3d3bdf5f736a6229579ae4c42a805745e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_modular.py
@@ -0,0 +1,34 @@
+from sympy.ntheory.modular import crt, crt1, crt2, solve_congruence
+from sympy.testing.pytest import raises
+
+
+def test_crt():
+    def mcrt(m, v, r, symmetric=False):
+        assert crt(m, v, symmetric)[0] == r
+        mm, e, s = crt1(m)
+        assert crt2(m, v, mm, e, s, symmetric) == (r, mm)
+
+    mcrt([2, 3, 5], [0, 0, 0], 0)
+    mcrt([2, 3, 5], [1, 1, 1], 1)
+
+    mcrt([2, 3, 5], [-1, -1, -1], -1, True)
+    mcrt([2, 3, 5], [-1, -1, -1], 2*3*5 - 1, False)
+
+    assert crt([656, 350], [811, 133], symmetric=True) == (-56917, 114800)
+
+
+def test_modular():
+    assert solve_congruence(*list(zip([3, 4, 2], [12, 35, 17]))) == (1719, 7140)
+    assert solve_congruence(*list(zip([3, 4, 2], [12, 6, 17]))) is None
+    assert solve_congruence(*list(zip([3, 4, 2], [13, 7, 17]))) == (172, 1547)
+    assert solve_congruence(*list(zip([-10, -3, -15], [13, 7, 17]))) == (172, 1547)
+    assert solve_congruence(*list(zip([-10, -3, 1, -15], [13, 7, 7, 17]))) is None
+    assert solve_congruence(
+        *list(zip([-10, -5, 2, -15], [13, 7, 7, 17]))) == (835, 1547)
+    assert solve_congruence(
+        *list(zip([-10, -5, 2, -15], [13, 7, 14, 17]))) == (2382, 3094)
+    assert solve_congruence(
+        *list(zip([-10, 2, 2, -15], [13, 7, 14, 17]))) == (2382, 3094)
+    assert solve_congruence(*list(zip((1, 1, 2), (3, 2, 4)))) is None
+    raises(
+        ValueError, lambda: solve_congruence(*list(zip([3, 4, 2], [12.1, 35, 17]))))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_multinomial.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_multinomial.py
new file mode 100644
index 0000000000000000000000000000000000000000..b455c5cc979b9ba9756c9da88c1694471115cd5d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_multinomial.py
@@ -0,0 +1,48 @@
+from sympy.ntheory.multinomial import (binomial_coefficients, binomial_coefficients_list, multinomial_coefficients)
+from sympy.ntheory.multinomial import multinomial_coefficients_iterator
+
+
+def test_binomial_coefficients_list():
+    assert binomial_coefficients_list(0) == [1]
+    assert binomial_coefficients_list(1) == [1, 1]
+    assert binomial_coefficients_list(2) == [1, 2, 1]
+    assert binomial_coefficients_list(3) == [1, 3, 3, 1]
+    assert binomial_coefficients_list(4) == [1, 4, 6, 4, 1]
+    assert binomial_coefficients_list(5) == [1, 5, 10, 10, 5, 1]
+    assert binomial_coefficients_list(6) == [1, 6, 15, 20, 15, 6, 1]
+
+
+def test_binomial_coefficients():
+    for n in range(15):
+        c = binomial_coefficients(n)
+        l = [c[k] for k in sorted(c)]
+        assert l == binomial_coefficients_list(n)
+
+
+def test_multinomial_coefficients():
+    assert multinomial_coefficients(1, 1) == {(1,): 1}
+    assert multinomial_coefficients(1, 2) == {(2,): 1}
+    assert multinomial_coefficients(1, 3) == {(3,): 1}
+    assert multinomial_coefficients(2, 0) == {(0, 0): 1}
+    assert multinomial_coefficients(2, 1) == {(0, 1): 1, (1, 0): 1}
+    assert multinomial_coefficients(2, 2) == {(2, 0): 1, (0, 2): 1, (1, 1): 2}
+    assert multinomial_coefficients(2, 3) == {(3, 0): 1, (1, 2): 3, (0, 3): 1,
+            (2, 1): 3}
+    assert multinomial_coefficients(3, 1) == {(1, 0, 0): 1, (0, 1, 0): 1,
+            (0, 0, 1): 1}
+    assert multinomial_coefficients(3, 2) == {(0, 1, 1): 2, (0, 0, 2): 1,
+            (1, 1, 0): 2, (0, 2, 0): 1, (1, 0, 1): 2, (2, 0, 0): 1}
+    mc = multinomial_coefficients(3, 3)
+    assert mc == {(2, 1, 0): 3, (0, 3, 0): 1,
+            (1, 0, 2): 3, (0, 2, 1): 3, (0, 1, 2): 3, (3, 0, 0): 1,
+            (2, 0, 1): 3, (1, 2, 0): 3, (1, 1, 1): 6, (0, 0, 3): 1}
+    assert dict(multinomial_coefficients_iterator(2, 0)) == {(0, 0): 1}
+    assert dict(
+        multinomial_coefficients_iterator(2, 1)) == {(0, 1): 1, (1, 0): 1}
+    assert dict(multinomial_coefficients_iterator(2, 2)) == \
+        {(2, 0): 1, (0, 2): 1, (1, 1): 2}
+    assert dict(multinomial_coefficients_iterator(3, 3)) == mc
+    it = multinomial_coefficients_iterator(7, 2)
+    assert [next(it) for i in range(4)] == \
+        [((2, 0, 0, 0, 0, 0, 0), 1), ((1, 1, 0, 0, 0, 0, 0), 2),
+      ((0, 2, 0, 0, 0, 0, 0), 1), ((1, 0, 1, 0, 0, 0, 0), 2)]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_partitions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_partitions.py
new file mode 100644
index 0000000000000000000000000000000000000000..8eb7fad3445068ae7ae4033c76c808e3c87347b6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_partitions.py
@@ -0,0 +1,28 @@
+from sympy.ntheory.partitions_ import npartitions, _partition_rec, _partition
+
+
+def test__partition_rec():
+    A000041 = [1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56, 77, 101, 135,
+               176, 231, 297, 385, 490, 627, 792, 1002, 1255, 1575]
+    for n, val in enumerate(A000041):
+        assert _partition_rec(n) == val
+
+
+def test__partition():
+    assert [_partition(k) for k in range(13)] == \
+        [1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56, 77]
+    assert _partition(100) == 190569292
+    assert _partition(200) == 3972999029388
+    assert _partition(1000) == 24061467864032622473692149727991
+    assert _partition(1001) == 25032297938763929621013218349796
+    assert _partition(2000) == 4720819175619413888601432406799959512200344166
+    assert _partition(10000) % 10**10 == 6916435144
+    assert _partition(100000) % 10**10 == 9421098519
+    assert _partition(10000000) % 10**10 == 7677288980
+
+
+def test_deprecated_ntheory_symbolic_functions():
+    from sympy.testing.pytest import warns_deprecated_sympy
+
+    with warns_deprecated_sympy():
+        assert npartitions(0) == 1
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_primetest.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_primetest.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a56332941d9421bda4d6acc1e4b3406617cee2b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_primetest.py
@@ -0,0 +1,235 @@
+from math import gcd
+
+from sympy.ntheory.generate import Sieve, sieve
+from sympy.ntheory.primetest import (mr, _lucas_extrastrong_params, is_lucas_prp, is_square,
+                                     is_strong_lucas_prp, is_extra_strong_lucas_prp,
+                                     proth_test, isprime, is_euler_pseudoprime,
+                                     is_gaussian_prime, is_fermat_pseudoprime, is_euler_jacobi_pseudoprime,
+                                     MERSENNE_PRIME_EXPONENTS, _lucas_lehmer_primality_test,
+                                     is_mersenne_prime)
+
+from sympy.testing.pytest import slow, raises
+from sympy.core.numbers import I, Float
+
+
+def test_is_fermat_pseudoprime():
+    assert is_fermat_pseudoprime(5, 1)
+    assert is_fermat_pseudoprime(9, 1)
+
+
+def test_euler_pseudoprimes():
+    assert is_euler_pseudoprime(13, 1)
+    assert is_euler_pseudoprime(15, 1)
+    assert is_euler_pseudoprime(17, 6)
+    assert is_euler_pseudoprime(101, 7)
+    assert is_euler_pseudoprime(1009, 10)
+    assert is_euler_pseudoprime(11287, 41)
+
+    raises(ValueError, lambda: is_euler_pseudoprime(0, 4))
+    raises(ValueError, lambda: is_euler_pseudoprime(3, 0))
+    raises(ValueError, lambda: is_euler_pseudoprime(15, 6))
+
+    # A006970
+    euler_prp = [341, 561, 1105, 1729, 1905, 2047, 2465, 3277,
+                 4033, 4681, 5461, 6601, 8321, 8481, 10261, 10585]
+    for p in euler_prp:
+        assert is_euler_pseudoprime(p, 2)
+
+    # A048950
+    euler_prp = [121, 703, 1729, 1891, 2821, 3281, 7381, 8401, 8911, 10585,
+                 12403, 15457, 15841, 16531, 18721, 19345, 23521, 24661, 28009]
+    for p in euler_prp:
+        assert is_euler_pseudoprime(p, 3)
+
+    # A033181
+    absolute_euler_prp = [1729, 2465, 15841, 41041, 46657, 75361,
+                          162401, 172081, 399001, 449065, 488881]
+    for p in absolute_euler_prp:
+        for a in range(2, p):
+            if gcd(a, p) != 1:
+                continue
+            assert is_euler_pseudoprime(p, a)
+
+
+def test_is_euler_jacobi_pseudoprime():
+    assert is_euler_jacobi_pseudoprime(11, 1)
+    assert is_euler_jacobi_pseudoprime(15, 1)
+
+
+def test_lucas_extrastrong_params():
+    assert _lucas_extrastrong_params(3) == (5, 3, 1)
+    assert _lucas_extrastrong_params(5) == (12, 4, 1)
+    assert _lucas_extrastrong_params(7) == (5, 3, 1)
+    assert _lucas_extrastrong_params(9) == (0, 0, 0)
+    assert _lucas_extrastrong_params(11) == (21, 5, 1)
+    assert _lucas_extrastrong_params(59) == (32, 6, 1)
+    assert _lucas_extrastrong_params(479) == (117, 11, 1)
+
+
+def test_is_extra_strong_lucas_prp():
+    assert is_extra_strong_lucas_prp(4) == False
+    assert is_extra_strong_lucas_prp(989) == True
+    assert is_extra_strong_lucas_prp(10877) == True
+    assert is_extra_strong_lucas_prp(9) == False
+    assert is_extra_strong_lucas_prp(16) == False
+    assert is_extra_strong_lucas_prp(169) == False
+
+@slow
+def test_prps():
+    oddcomposites = [n for n in range(1, 10**5) if
+        n % 2 and not isprime(n)]
+    # A checksum would be better.
+    assert sum(oddcomposites) == 2045603465
+    assert [n for n in oddcomposites if mr(n, [2])] == [
+        2047, 3277, 4033, 4681, 8321, 15841, 29341, 42799, 49141,
+        52633, 65281, 74665, 80581, 85489, 88357, 90751]
+    assert [n for n in oddcomposites if mr(n, [3])] == [
+        121, 703, 1891, 3281, 8401, 8911, 10585, 12403, 16531,
+        18721, 19345, 23521, 31621, 44287, 47197, 55969, 63139,
+        74593, 79003, 82513, 87913, 88573, 97567]
+    assert [n for n in oddcomposites if mr(n, [325])] == [
+        9, 25, 27, 49, 65, 81, 325, 341, 343, 697, 1141, 2059,
+        2149, 3097, 3537, 4033, 4681, 4941, 5833, 6517, 7987, 8911,
+        12403, 12913, 15043, 16021, 20017, 22261, 23221, 24649,
+        24929, 31841, 35371, 38503, 43213, 44173, 47197, 50041,
+        55909, 56033, 58969, 59089, 61337, 65441, 68823, 72641,
+        76793, 78409, 85879]
+    assert not any(mr(n, [9345883071009581737]) for n in oddcomposites)
+    assert [n for n in oddcomposites if is_lucas_prp(n)] == [
+        323, 377, 1159, 1829, 3827, 5459, 5777, 9071, 9179, 10877,
+        11419, 11663, 13919, 14839, 16109, 16211, 18407, 18971,
+        19043, 22499, 23407, 24569, 25199, 25877, 26069, 27323,
+        32759, 34943, 35207, 39059, 39203, 39689, 40309, 44099,
+        46979, 47879, 50183, 51983, 53663, 56279, 58519, 60377,
+        63881, 69509, 72389, 73919, 75077, 77219, 79547, 79799,
+        82983, 84419, 86063, 90287, 94667, 97019, 97439]
+    assert [n for n in oddcomposites if is_strong_lucas_prp(n)] == [
+        5459, 5777, 10877, 16109, 18971, 22499, 24569, 25199, 40309,
+        58519, 75077, 97439]
+    assert [n for n in oddcomposites if is_extra_strong_lucas_prp(n)
+            ] == [
+        989, 3239, 5777, 10877, 27971, 29681, 30739, 31631, 39059,
+        72389, 73919, 75077]
+
+
+def test_proth_test():
+    # Proth number
+    A080075 = [3, 5, 9, 13, 17, 25, 33, 41, 49, 57, 65,
+               81, 97, 113, 129, 145, 161, 177, 193]
+    # Proth prime
+    A080076 = [3, 5, 13, 17, 41, 97, 113, 193]
+
+    for n in range(200):
+        if n in A080075:
+            assert proth_test(n) == (n in A080076)
+        else:
+            raises(ValueError, lambda: proth_test(n))
+
+
+def test_lucas_lehmer_primality_test():
+    for p in sieve.primerange(3, 100):
+        assert _lucas_lehmer_primality_test(p) == (p in MERSENNE_PRIME_EXPONENTS)
+
+
+def test_is_mersenne_prime():
+    assert is_mersenne_prime(-3) is False
+    assert is_mersenne_prime(3) is True
+    assert is_mersenne_prime(10) is False
+    assert is_mersenne_prime(127) is True
+    assert is_mersenne_prime(511) is False
+    assert is_mersenne_prime(131071) is True
+    assert is_mersenne_prime(2147483647) is True
+
+
+def test_isprime():
+    s = Sieve()
+    s.extend(100000)
+    ps = set(s.primerange(2, 100001))
+    for n in range(100001):
+        # if (n in ps) != isprime(n): print n
+        assert (n in ps) == isprime(n)
+    assert isprime(179424673)
+    assert isprime(20678048681)
+    assert isprime(1968188556461)
+    assert isprime(2614941710599)
+    assert isprime(65635624165761929287)
+    assert isprime(1162566711635022452267983)
+    assert isprime(77123077103005189615466924501)
+    assert isprime(3991617775553178702574451996736229)
+    assert isprime(273952953553395851092382714516720001799)
+    assert isprime(int('''
+531137992816767098689588206552468627329593117727031923199444138200403\
+559860852242739162502265229285668889329486246501015346579337652707239\
+409519978766587351943831270835393219031728127'''))
+
+    # Some Mersenne primes
+    assert isprime(2**61 - 1)
+    assert isprime(2**89 - 1)
+    assert isprime(2**607 - 1)
+    # (but not all Mersenne's are primes
+    assert not isprime(2**601 - 1)
+
+    # pseudoprimes
+    #-------------
+    # to some small bases
+    assert not isprime(2152302898747)
+    assert not isprime(3474749660383)
+    assert not isprime(341550071728321)
+    assert not isprime(3825123056546413051)
+    # passes the base set [2, 3, 7, 61, 24251]
+    assert not isprime(9188353522314541)
+    # large examples
+    assert not isprime(877777777777777777777777)
+    # conjectured psi_12 given at http://mathworld.wolfram.com/StrongPseudoprime.html
+    assert not isprime(318665857834031151167461)
+    # conjectured psi_17 given at http://mathworld.wolfram.com/StrongPseudoprime.html
+    assert not isprime(564132928021909221014087501701)
+    # Arnault's 1993 number; a factor of it is
+    # 400958216639499605418306452084546853005188166041132508774506\
+    # 204738003217070119624271622319159721973358216316508535816696\
+    # 9145233813917169287527980445796800452592031836601
+    assert not isprime(int('''
+803837457453639491257079614341942108138837688287558145837488917522297\
+427376533365218650233616396004545791504202360320876656996676098728404\
+396540823292873879185086916685732826776177102938969773947016708230428\
+687109997439976544144845341155872450633409279022275296229414984230688\
+1685404326457534018329786111298960644845216191652872597534901'''))
+    # Arnault's 1995 number; can be factored as
+    # p1*(313*(p1 - 1) + 1)*(353*(p1 - 1) + 1) where p1 is
+    # 296744956686855105501541746429053327307719917998530433509950\
+    # 755312768387531717701995942385964281211880336647542183455624\
+    # 93168782883
+    assert not isprime(int('''
+288714823805077121267142959713039399197760945927972270092651602419743\
+230379915273311632898314463922594197780311092934965557841894944174093\
+380561511397999942154241693397290542371100275104208013496673175515285\
+922696291677532547504444585610194940420003990443211677661994962953925\
+045269871932907037356403227370127845389912612030924484149472897688540\
+6024976768122077071687938121709811322297802059565867'''))
+    sieve.extend(3000)
+    assert isprime(2819)
+    assert not isprime(2931)
+    raises(ValueError, lambda: isprime(2.0))
+    raises(ValueError, lambda: isprime(Float(2)))
+
+
+def test_is_square():
+    assert [i for i in range(25) if is_square(i)] == [0, 1, 4, 9, 16]
+
+    # issue #17044
+    assert not is_square(60 ** 3)
+    assert not is_square(60 ** 5)
+    assert not is_square(84 ** 7)
+    assert not is_square(105 ** 9)
+    assert not is_square(120 ** 3)
+
+def test_is_gaussianprime():
+    assert is_gaussian_prime(7*I)
+    assert is_gaussian_prime(7)
+    assert is_gaussian_prime(2 + 3*I)
+    assert not is_gaussian_prime(2 + 2*I)
+
+
+def test_issue_27145():
+    #https://github.com/sympy/sympy/issues/27145
+    assert [mr(i,[2,3,5,7]) for i in (1, 2, 6)] == [False, True, False]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_qs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_qs.py
new file mode 100644
index 0000000000000000000000000000000000000000..16932dd61badf4a467e67fa52e0f473594fd057b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_qs.py
@@ -0,0 +1,110 @@
+from __future__ import annotations
+
+import math
+from sympy.core.random import _randint
+from sympy.ntheory import qs, qs_factor
+from sympy.ntheory.qs import SievePolynomial, _generate_factor_base, \
+    _generate_polynomial, \
+    _gen_sieve_array, _check_smoothness, _trial_division_stage, _find_factor
+from sympy.testing.pytest import slow
+
+
+@slow
+def test_qs_1():
+    assert qs(10009202107, 100, 10000) == {100043, 100049}
+    assert qs(211107295182713951054568361, 1000, 10000) == \
+        {13791315212531, 15307263442931}
+    assert qs(980835832582657*990377764891511, 2000, 10000) == \
+        {980835832582657, 990377764891511}
+    assert qs(18640889198609*20991129234731, 1000, 50000) == \
+        {18640889198609, 20991129234731}
+
+
+def test_qs_2() -> None:
+    n = 10009202107
+    M = 50
+    sieve_poly = SievePolynomial(10, 80, n)
+    assert sieve_poly.eval_v(10) == sieve_poly.eval_u(10)**2 - n == -10009169707
+    assert sieve_poly.eval_v(5) == sieve_poly.eval_u(5)**2 - n == -10009185207
+
+    idx_1000, idx_5000, factor_base = _generate_factor_base(2000, n)
+    assert idx_1000 == 82
+    assert [factor_base[i].prime for i in range(15)] == \
+        [2, 3, 7, 11, 17, 19, 29, 31, 43, 59, 61, 67, 71, 73, 79]
+    assert [factor_base[i].tmem_p for i in range(15)] == \
+        [1, 1, 3, 5, 3, 6, 6, 14, 1, 16, 24, 22, 18, 22, 15]
+    assert [factor_base[i].log_p for i in range(5)] == \
+        [710, 1125, 1993, 2455, 2901]
+
+    it = _generate_polynomial(
+        n, M, factor_base, idx_1000, idx_5000, _randint(0))
+    g = next(it)
+    assert g.a == 1133107
+    assert g.b == 682543
+    assert [factor_base[i].soln1 for i in range(15)] == \
+        [0, 0, 3, 7, 13, 0, 8, 19, 9, 43, 27, 25, 63, 29, 19]
+    assert [factor_base[i].soln2 for i in range(15)] == \
+        [0, 1, 1, 3, 12, 16, 15, 6, 15, 1, 56, 55, 61, 58, 16]
+    assert [factor_base[i].b_ainv for i in range(5)] == \
+        [[0, 0], [0, 2], [3, 0], [3, 9], [13, 13]]
+
+    g_1 = next(it)
+    assert g_1.a == 1133107
+    assert g_1.b == 136765
+
+    sieve_array = _gen_sieve_array(M, factor_base)
+    assert sieve_array[0:5] == [8424, 13603, 1835, 5335, 710]
+
+    assert _check_smoothness(9645, factor_base) == (36028797018963972, 5)
+    assert _check_smoothness(210313, factor_base) == (20992, 1)
+
+    partial_relations: dict[int, tuple[int, int]] = {}
+    smooth_relation, proper_factor = _trial_division_stage(
+        n, M, factor_base, sieve_array, sieve_poly, partial_relations,
+        ERROR_TERM=25*2**10)
+
+    assert partial_relations == {
+        8699: (440, -10009008507, 75557863761098695507973),
+        166741: (490, -10008962007, 524341),
+        131449: (530, -10008921207, 664613997892457936451903530140172325),
+        6653: (550, -10008899607, 19342813113834066795307021)
+    }
+    assert [smooth_relation[i][0] for i in range(5)] == [
+        -250, 1064469, 72819, 231957, 44167]
+    assert [smooth_relation[i][1] for i in range(5)] == [
+        -10009139607, 1133094251961, 5302606761, 53804049849, 1950723889]
+    assert smooth_relation[0][2] == 89213869829863962596973701078031812362502145
+    assert proper_factor == set()
+
+
+def test_qs_3():
+    N = 1817
+    smooth_relations = [
+        (2455024, 637, 8),
+        (-27993000, 81536, 10),
+        (11461840, 12544, 0),
+        (149, 20384, 10),
+        (-31138074, 19208, 2)
+    ]
+    assert next(_find_factor(N, smooth_relations, 4)) == 23
+
+
+def test_qs_4():
+    N = 10007**2 * 10009 * 10037**3 * 10039
+    for factor in qs(N, 1000, 2000):
+        assert N % factor == 0
+        N //= factor
+
+
+def test_qs_factor():
+    assert qs_factor(1009 * 100003, 2000, 10000) == {1009: 1, 100003: 1}
+    n = 1009**2 * 2003**2*30011*400009
+    factors = qs_factor(n, 2000, 10000)
+    assert len(factors) > 1
+    assert math.prod(p**e for p, e in factors.items()) == n
+
+
+def test_issue_27616():
+    #https://github.com/sympy/sympy/issues/27616
+    N = 9804659461513846513 + 1
+    assert qs(N, 5000, 20000) is not None
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_residue.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_residue.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d530905f39b88d8d7cc0e861ac6eadb2fa6f98a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/ntheory/tests/test_residue.py
@@ -0,0 +1,349 @@
+from collections import defaultdict
+from sympy.core.containers import Tuple
+from sympy.core.singleton import S
+from sympy.core.symbol import (Dummy, Symbol)
+from sympy.functions.combinatorial.numbers import totient
+from sympy.ntheory import n_order, is_primitive_root, is_quad_residue, \
+    legendre_symbol, jacobi_symbol, primerange, sqrt_mod, \
+    primitive_root, quadratic_residues, is_nthpow_residue, nthroot_mod, \
+    sqrt_mod_iter, mobius, discrete_log, quadratic_congruence, \
+    polynomial_congruence, sieve
+from sympy.ntheory.residue_ntheory import _primitive_root_prime_iter, \
+    _primitive_root_prime_power_iter, _primitive_root_prime_power2_iter, \
+    _nthroot_mod_prime_power, _discrete_log_trial_mul, _discrete_log_shanks_steps, \
+    _discrete_log_pollard_rho, _discrete_log_index_calculus, _discrete_log_pohlig_hellman, \
+    _binomial_mod_prime_power, binomial_mod
+from sympy.polys.domains import ZZ
+from sympy.testing.pytest import raises
+from sympy.core.random import randint, choice
+
+
+def test_residue():
+    assert n_order(2, 13) == 12
+    assert [n_order(a, 7) for a in range(1, 7)] == \
+           [1, 3, 6, 3, 6, 2]
+    assert n_order(5, 17) == 16
+    assert n_order(17, 11) == n_order(6, 11)
+    assert n_order(101, 119) == 6
+    assert n_order(11, (10**50 + 151)**2) == 10000000000000000000000000000000000000000000000030100000000000000000000000000000000000000000000022650
+    raises(ValueError, lambda: n_order(6, 9))
+
+    assert is_primitive_root(2, 7) is False
+    assert is_primitive_root(3, 8) is False
+    assert is_primitive_root(11, 14) is False
+    assert is_primitive_root(12, 17) == is_primitive_root(29, 17)
+    raises(ValueError, lambda: is_primitive_root(3, 6))
+
+    for p in primerange(3, 100):
+        li = list(_primitive_root_prime_iter(p))
+        assert li[0] == min(li)
+        for g in li:
+            assert n_order(g, p) == p - 1
+        assert len(li) == totient(totient(p))
+        for e in range(1, 4):
+            li_power = list(_primitive_root_prime_power_iter(p, e))
+            li_power2 = list(_primitive_root_prime_power2_iter(p, e))
+            assert len(li_power) == len(li_power2) == totient(totient(p**e))
+    assert primitive_root(97) == 5
+    assert n_order(primitive_root(97, False), 97) == totient(97)
+    assert primitive_root(97**2) == 5
+    assert n_order(primitive_root(97**2, False), 97**2) == totient(97**2)
+    assert primitive_root(40487) == 5
+    assert n_order(primitive_root(40487, False), 40487) == totient(40487)
+    # note that primitive_root(40487) + 40487 = 40492 is a primitive root
+    # of 40487**2, but it is not the smallest
+    assert primitive_root(40487**2) == 10
+    assert n_order(primitive_root(40487**2, False), 40487**2) == totient(40487**2)
+    assert primitive_root(82) == 7
+    assert n_order(primitive_root(82, False), 82) == totient(82)
+    p = 10**50 + 151
+    assert primitive_root(p) == 11
+    assert n_order(primitive_root(p, False), p) == totient(p)
+    assert primitive_root(2*p) == 11
+    assert n_order(primitive_root(2*p, False), 2*p) == totient(2*p)
+    assert primitive_root(p**2) == 11
+    assert n_order(primitive_root(p**2, False), p**2) == totient(p**2)
+    assert primitive_root(4 * 11) is None and primitive_root(4 * 11, False) is None
+    assert primitive_root(15) is None and primitive_root(15, False) is None
+    raises(ValueError, lambda: primitive_root(-3))
+
+    assert is_quad_residue(3, 7) is False
+    assert is_quad_residue(10, 13) is True
+    assert is_quad_residue(12364, 139) == is_quad_residue(12364 % 139, 139)
+    assert is_quad_residue(207, 251) is True
+    assert is_quad_residue(0, 1) is True
+    assert is_quad_residue(1, 1) is True
+    assert is_quad_residue(0, 2) == is_quad_residue(1, 2) is True
+    assert is_quad_residue(1, 4) is True
+    assert is_quad_residue(2, 27) is False
+    assert is_quad_residue(13122380800, 13604889600) is True
+    assert [j for j in range(14) if is_quad_residue(j, 14)] == \
+           [0, 1, 2, 4, 7, 8, 9, 11]
+    raises(ValueError, lambda: is_quad_residue(1.1, 2))
+    raises(ValueError, lambda: is_quad_residue(2, 0))
+
+    assert quadratic_residues(S.One) == [0]
+    assert quadratic_residues(1) == [0]
+    assert quadratic_residues(12) == [0, 1, 4, 9]
+    assert quadratic_residues(13) == [0, 1, 3, 4, 9, 10, 12]
+    assert [len(quadratic_residues(i)) for i in range(1, 20)] == \
+      [1, 2, 2, 2, 3, 4, 4, 3, 4, 6, 6, 4, 7, 8, 6, 4, 9, 8, 10]
+
+    assert list(sqrt_mod_iter(6, 2)) == [0]
+    assert sqrt_mod(3, 13) == 4
+    assert sqrt_mod(3, -13) == 4
+    assert sqrt_mod(6, 23) == 11
+    assert sqrt_mod(345, 690) == 345
+    assert sqrt_mod(67, 101) == None
+    assert sqrt_mod(1020, 104729) == None
+
+    for p in range(3, 100):
+        d = defaultdict(list)
+        for i in range(p):
+            d[pow(i, 2, p)].append(i)
+        for i in range(1, p):
+            it = sqrt_mod_iter(i, p)
+            v = sqrt_mod(i, p, True)
+            if v:
+                v = sorted(v)
+                assert d[i] == v
+            else:
+                assert not d[i]
+
+    assert sqrt_mod(9, 27, True) == [3, 6, 12, 15, 21, 24]
+    assert sqrt_mod(9, 81, True) == [3, 24, 30, 51, 57, 78]
+    assert sqrt_mod(9, 3**5, True) == [3, 78, 84, 159, 165, 240]
+    assert sqrt_mod(81, 3**4, True) == [0, 9, 18, 27, 36, 45, 54, 63, 72]
+    assert sqrt_mod(81, 3**5, True) == [9, 18, 36, 45, 63, 72, 90, 99, 117,\
+            126, 144, 153, 171, 180, 198, 207, 225, 234]
+    assert sqrt_mod(81, 3**6, True) == [9, 72, 90, 153, 171, 234, 252, 315,\
+            333, 396, 414, 477, 495, 558, 576, 639, 657, 720]
+    assert sqrt_mod(81, 3**7, True) == [9, 234, 252, 477, 495, 720, 738, 963,\
+            981, 1206, 1224, 1449, 1467, 1692, 1710, 1935, 1953, 2178]
+
+    for a, p in [(26214400, 32768000000), (26214400, 16384000000),
+        (262144, 1048576), (87169610025, 163443018796875),
+        (22315420166400, 167365651248000000)]:
+        assert pow(sqrt_mod(a, p), 2, p) == a
+
+    n = 70
+    a, p = 5**2*3**n*2**n, 5**6*3**(n+1)*2**(n+2)
+    it = sqrt_mod_iter(a, p)
+    for i in range(10):
+        assert pow(next(it), 2, p) == a
+    a, p = 5**2*3**n*2**n, 5**6*3**(n+1)*2**(n+3)
+    it = sqrt_mod_iter(a, p)
+    for i in range(2):
+        assert pow(next(it), 2, p) == a
+    n = 100
+    a, p = 5**2*3**n*2**n, 5**6*3**(n+1)*2**(n+1)
+    it = sqrt_mod_iter(a, p)
+    for i in range(2):
+        assert pow(next(it), 2, p) == a
+
+    assert type(next(sqrt_mod_iter(9, 27))) is int
+    assert type(next(sqrt_mod_iter(9, 27, ZZ))) is type(ZZ(1))
+    assert type(next(sqrt_mod_iter(1, 7, ZZ))) is type(ZZ(1))
+
+    assert is_nthpow_residue(2, 1, 5)
+
+    #issue 10816
+    assert is_nthpow_residue(1, 0, 1) is False
+    assert is_nthpow_residue(1, 0, 2) is True
+    assert is_nthpow_residue(3, 0, 2) is True
+    assert is_nthpow_residue(0, 1, 8) is True
+    assert is_nthpow_residue(2, 3, 2) is True
+    assert is_nthpow_residue(2, 3, 9) is False
+    assert is_nthpow_residue(3, 5, 30) is True
+    assert is_nthpow_residue(21, 11, 20) is True
+    assert is_nthpow_residue(7, 10, 20) is False
+    assert is_nthpow_residue(5, 10, 20) is True
+    assert is_nthpow_residue(3, 10, 48) is False
+    assert is_nthpow_residue(1, 10, 40) is True
+    assert is_nthpow_residue(3, 10, 24) is False
+    assert is_nthpow_residue(1, 10, 24) is True
+    assert is_nthpow_residue(3, 10, 24) is False
+    assert is_nthpow_residue(2, 10, 48) is False
+    assert is_nthpow_residue(81, 3, 972) is False
+    assert is_nthpow_residue(243, 5, 5103) is True
+    assert is_nthpow_residue(243, 3, 1240029) is False
+    assert is_nthpow_residue(36010, 8, 87382) is True
+    assert is_nthpow_residue(28552, 6, 2218) is True
+    assert is_nthpow_residue(92712, 9, 50026) is True
+    x = {pow(i, 56, 1024) for i in range(1024)}
+    assert {a for a in range(1024) if is_nthpow_residue(a, 56, 1024)} == x
+    x = { pow(i, 256, 2048) for i in range(2048)}
+    assert {a for a in range(2048) if is_nthpow_residue(a, 256, 2048)} == x
+    x = { pow(i, 11, 324000) for i in range(1000)}
+    assert [ is_nthpow_residue(a, 11, 324000) for a in x]
+    x = { pow(i, 17, 22217575536) for i in range(1000)}
+    assert [ is_nthpow_residue(a, 17, 22217575536) for a in x]
+    assert is_nthpow_residue(676, 3, 5364)
+    assert is_nthpow_residue(9, 12, 36)
+    assert is_nthpow_residue(32, 10, 41)
+    assert is_nthpow_residue(4, 2, 64)
+    assert is_nthpow_residue(31, 4, 41)
+    assert not is_nthpow_residue(2, 2, 5)
+    assert is_nthpow_residue(8547, 12, 10007)
+    assert is_nthpow_residue(Dummy(even=True) + 3, 3, 2) == True
+    # _nthroot_mod_prime_power
+    for p in primerange(2, 10):
+        for a in range(3):
+            for n in range(3, 5):
+                ans = _nthroot_mod_prime_power(a, n, p, 1)
+                assert isinstance(ans, list)
+                if len(ans) == 0:
+                    for b in range(p):
+                        assert pow(b, n, p) != a % p
+                    for k in range(2, 10):
+                        assert _nthroot_mod_prime_power(a, n, p, k) == []
+                else:
+                    for b in range(p):
+                        pred = pow(b, n, p) == a % p
+                        assert not(pred ^ (b in ans))
+                    for k in range(2, 10):
+                        ans = _nthroot_mod_prime_power(a, n, p, k)
+                        if not ans:
+                            break
+                        for b in ans:
+                            assert pow(b, n , p**k) == a
+
+    assert nthroot_mod(Dummy(odd=True), 3, 2) == 1
+    assert nthroot_mod(29, 31, 74) == 45
+    assert nthroot_mod(1801, 11, 2663) == 44
+    for a, q, p in [(51922, 2, 203017), (43, 3, 109), (1801, 11, 2663),
+          (26118163, 1303, 33333347), (1499, 7, 2663), (595, 6, 2663),
+          (1714, 12, 2663), (28477, 9, 33343)]:
+        r = nthroot_mod(a, q, p)
+        assert pow(r, q, p) == a
+    assert nthroot_mod(11, 3, 109) is None
+    assert nthroot_mod(16, 5, 36, True) == [4, 22]
+    assert nthroot_mod(9, 16, 36, True) == [3, 9, 15, 21, 27, 33]
+    assert nthroot_mod(4, 3, 3249000) is None
+    assert nthroot_mod(36010, 8, 87382, True) == [40208, 47174]
+    assert nthroot_mod(0, 12, 37, True) == [0]
+    assert nthroot_mod(0, 7, 100, True) == [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
+    assert nthroot_mod(4, 4, 27, True) == [5, 22]
+    assert nthroot_mod(4, 4, 121, True) == [19, 102]
+    assert nthroot_mod(2, 3, 7, True) == []
+    for p in range(1, 20):
+        for a in range(p):
+            for n in range(1, p):
+                ans = nthroot_mod(a, n, p, True)
+                assert isinstance(ans, list)
+                for b in range(p):
+                    pred = pow(b, n, p) == a
+                    assert not(pred ^ (b in ans))
+                ans2 = nthroot_mod(a, n, p, False)
+                if ans2 is None:
+                    assert ans == []
+                else:
+                    assert ans2 in ans
+
+    x = Symbol('x', positive=True)
+    i = Symbol('i', integer=True)
+    assert _discrete_log_trial_mul(587, 2**7, 2) == 7
+    assert _discrete_log_trial_mul(941, 7**18, 7) == 18
+    assert _discrete_log_trial_mul(389, 3**81, 3) == 81
+    assert _discrete_log_trial_mul(191, 19**123, 19) == 123
+    assert _discrete_log_shanks_steps(442879, 7**2, 7) == 2
+    assert _discrete_log_shanks_steps(874323, 5**19, 5) == 19
+    assert _discrete_log_shanks_steps(6876342, 7**71, 7) == 71
+    assert _discrete_log_shanks_steps(2456747, 3**321, 3) == 321
+    assert _discrete_log_pollard_rho(6013199, 2**6, 2, rseed=0) == 6
+    assert _discrete_log_pollard_rho(6138719, 2**19, 2, rseed=0) == 19
+    assert _discrete_log_pollard_rho(36721943, 2**40, 2, rseed=0) == 40
+    assert _discrete_log_pollard_rho(24567899, 3**333, 3, rseed=0) == 333
+    raises(ValueError, lambda: _discrete_log_pollard_rho(11, 7, 31, rseed=0))
+    raises(ValueError, lambda: _discrete_log_pollard_rho(227, 3**7, 5, rseed=0))
+    assert _discrete_log_index_calculus(983, 948, 2, 491) == 183
+    assert _discrete_log_index_calculus(633383, 21794, 2, 316691) == 68048
+    assert _discrete_log_index_calculus(941762639, 68822582, 2, 470881319) == 338029275
+    assert _discrete_log_index_calculus(999231337607, 888188918786, 2, 499615668803) == 142811376514
+    assert _discrete_log_index_calculus(47747730623, 19410045286, 43425105668, 645239603) == 590504662
+    assert _discrete_log_pohlig_hellman(98376431, 11**9, 11) == 9
+    assert _discrete_log_pohlig_hellman(78723213, 11**31, 11) == 31
+    assert _discrete_log_pohlig_hellman(32942478, 11**98, 11) == 98
+    assert _discrete_log_pohlig_hellman(14789363, 11**444, 11) == 444
+    assert discrete_log(1, 0, 2) == 0
+    raises(ValueError, lambda: discrete_log(-4, 1, 3))
+    raises(ValueError, lambda: discrete_log(10, 3, 2))
+    assert discrete_log(587, 2**9, 2) == 9
+    assert discrete_log(2456747, 3**51, 3) == 51
+    assert discrete_log(32942478, 11**127, 11) == 127
+    assert discrete_log(432751500361, 7**324, 7) == 324
+    assert discrete_log(265390227570863,184500076053622, 2) == 17835221372061
+    assert discrete_log(22708823198678103974314518195029102158525052496759285596453269189798311427475159776411276642277139650833937,
+                        17463946429475485293747680247507700244427944625055089103624311227422110546803452417458985046168310373075327,
+                        123456) == 2068031853682195777930683306640554533145512201725884603914601918777510185469769997054750835368413389728895
+    args = 5779, 3528, 6215
+    assert discrete_log(*args) == 687
+    assert discrete_log(*Tuple(*args)) == 687
+    assert quadratic_congruence(400, 85, 125, 1600) == [295, 615, 935, 1255, 1575]
+    assert quadratic_congruence(3, 6, 5, 25) == [3, 20]
+    assert quadratic_congruence(120, 80, 175, 500) == []
+    assert quadratic_congruence(15, 14, 7, 2) == [1]
+    assert quadratic_congruence(8, 15, 7, 29) == [10, 28]
+    assert quadratic_congruence(160, 200, 300, 461) == [144, 431]
+    assert quadratic_congruence(100000, 123456, 7415263, 48112959837082048697) == [30417843635344493501, 36001135160550533083]
+    assert quadratic_congruence(65, 121, 72, 277) == [249, 252]
+    assert quadratic_congruence(5, 10, 14, 2) == [0]
+    assert quadratic_congruence(10, 17, 19, 2) == [1]
+    assert quadratic_congruence(10, 14, 20, 2) == [0, 1]
+    assert quadratic_congruence(2**48-7, 2**48-1, 4, 2**48) == [8249717183797, 31960993774868]
+    assert polynomial_congruence(6*x**5 + 10*x**4 + 5*x**3 + x**2 + x + 1,
+        972000) == [220999, 242999, 463999, 485999, 706999, 728999, 949999, 971999]
+
+    assert polynomial_congruence(x**3 - 10*x**2 + 12*x - 82, 33075) == [30287]
+    assert polynomial_congruence(x**2 + x + 47, 2401) == [785, 1615]
+    assert polynomial_congruence(10*x**2 + 14*x + 20, 2) == [0, 1]
+    assert polynomial_congruence(x**3 + 3, 16) == [5]
+    assert polynomial_congruence(65*x**2 + 121*x + 72, 277) == [249, 252]
+    assert polynomial_congruence(x**4 - 4, 27) == [5, 22]
+    assert polynomial_congruence(35*x**3 - 6*x**2 - 567*x + 2308, 148225) == [86957,
+        111157, 122531, 146731]
+    assert polynomial_congruence(x**16 - 9, 36) == [3, 9, 15, 21, 27, 33]
+    assert polynomial_congruence(x**6 - 2*x**5 - 35, 6125) == [3257]
+    raises(ValueError, lambda: polynomial_congruence(x**x, 6125))
+    raises(ValueError, lambda: polynomial_congruence(x**i, 6125))
+    raises(ValueError, lambda: polynomial_congruence(0.1*x**2 + 6, 100))
+
+    assert binomial_mod(-1, 1, 10) == 0
+    assert binomial_mod(1, -1, 10) == 0
+    raises(ValueError, lambda: binomial_mod(2, 1, -1))
+    assert binomial_mod(51, 10, 10) == 0
+    assert binomial_mod(10**3, 500, 3**6) == 567
+    assert binomial_mod(10**18 - 1, 123456789, 4) == 0
+    assert binomial_mod(10**18, 10**12, (10**5 + 3)**2) == 3744312326
+
+
+def test_binomial_p_pow():
+    n, binomials, binomial = 1000, [1], 1
+    for i in range(1, n + 1):
+        binomial *= n - i + 1
+        binomial //= i
+        binomials.append(binomial)
+
+    # Test powers of two, which the algorithm treats slightly differently
+    trials_2 = 100
+    for _ in range(trials_2):
+        m, power = randint(0, n), randint(1, 20)
+        assert _binomial_mod_prime_power(n, m, 2, power) == binomials[m] % 2**power
+
+    # Test against other prime powers
+    primes = list(sieve.primerange(2*n))
+    trials = 1000
+    for _ in range(trials):
+        m, prime, power = randint(0, n), choice(primes), randint(1, 10)
+        assert _binomial_mod_prime_power(n, m, prime, power) == binomials[m] % prime**power
+
+
+def test_deprecated_ntheory_symbolic_functions():
+    from sympy.testing.pytest import warns_deprecated_sympy
+
+    with warns_deprecated_sympy():
+        assert mobius(3) == -1
+    with warns_deprecated_sympy():
+        assert legendre_symbol(2, 3) == -1
+    with warns_deprecated_sympy():
+        assert jacobi_symbol(2, 3) == -1
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b39d031bca26bc599eb9eb0e12dfe48f7e6db174
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/__init__.py
@@ -0,0 +1,4 @@
+"""Used for translating a string into a SymPy expression. """
+__all__ = ['parse_expr']
+
+from .sympy_parser import parse_expr
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..42016234430d009ad7a5a97736cce8714a16a8d1
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/__pycache__/sympy_parser.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/__pycache__/sympy_parser.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d14c0096d09164914ca48a7ce4c844068d8f9653
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/__pycache__/sympy_parser.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/ast_parser.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/ast_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..95a773d5bec6e130810b7b7925fdff57270aec17
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/ast_parser.py
@@ -0,0 +1,79 @@
+"""
+This module implements the functionality to take any Python expression as a
+string and fix all numbers and other things before evaluating it,
+thus
+
+1/2
+
+returns
+
+Integer(1)/Integer(2)
+
+We use the ast module for this. It is well documented at docs.python.org.
+
+Some tips to understand how this works: use dump() to get a nice
+representation of any node. Then write a string of what you want to get,
+e.g. "Integer(1)", parse it, dump it and you'll see that you need to do
+"Call(Name('Integer', Load()), [node], [], None, None)". You do not need
+to bother with lineno and col_offset, just call fix_missing_locations()
+before returning the node.
+"""
+
+from sympy.core.basic import Basic
+from sympy.core.sympify import SympifyError
+
+from ast import parse, NodeTransformer, Call, Name, Load, \
+    fix_missing_locations, Constant, Tuple
+
+class Transform(NodeTransformer):
+
+    def __init__(self, local_dict, global_dict):
+        NodeTransformer.__init__(self)
+        self.local_dict = local_dict
+        self.global_dict = global_dict
+
+    def visit_Constant(self, node):
+        if isinstance(node.value, int):
+            return fix_missing_locations(Call(func=Name('Integer', Load()),
+                    args=[node], keywords=[]))
+        elif isinstance(node.value, float):
+            return fix_missing_locations(Call(func=Name('Float', Load()),
+                    args=[node], keywords=[]))
+        return node
+
+    def visit_Name(self, node):
+        if node.id in self.local_dict:
+            return node
+        elif node.id in self.global_dict:
+            name_obj = self.global_dict[node.id]
+
+            if isinstance(name_obj, (Basic, type)) or callable(name_obj):
+                return node
+        elif node.id in ['True', 'False']:
+            return node
+        return fix_missing_locations(Call(func=Name('Symbol', Load()),
+                args=[Constant(node.id)], keywords=[]))
+
+    def visit_Lambda(self, node):
+        args = [self.visit(arg) for arg in node.args.args]
+        body = self.visit(node.body)
+        n = Call(func=Name('Lambda', Load()),
+            args=[Tuple(args, Load()), body], keywords=[])
+        return fix_missing_locations(n)
+
+def parse_expr(s, local_dict):
+    """
+    Converts the string "s" to a SymPy expression, in local_dict.
+
+    It converts all numbers to Integers before feeding it to Python and
+    automatically creates Symbols.
+    """
+    global_dict = {}
+    exec('from sympy import *', global_dict)
+    try:
+        a = parse(s.strip(), mode="eval")
+    except SyntaxError:
+        raise SympifyError("Cannot parse %s." % repr(s))
+    a = Transform(local_dict, global_dict).visit(a)
+    e = compile(a, "", "eval")
+    return eval(e, global_dict, local_dict)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/Autolev.g4 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/Autolev.g4
new file mode 100644
index 0000000000000000000000000000000000000000..94feea5fa4f49e9d1054eca2cd60c996aebff7c2
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/Autolev.g4
@@ -0,0 +1,118 @@
+grammar Autolev;
+
+options {
+        language = Python3;
+}
+
+prog:   stat+;
+
+stat:   varDecl
+    |   functionCall
+    |   codeCommands
+    |   massDecl
+    |   inertiaDecl
+    |   assignment
+    |   settings
+    ;
+
+assignment:   vec equals expr #vecAssign
+          |   ID '[' index ']' equals expr #indexAssign
+          |   ID diff? equals expr #regularAssign;
+
+equals:   ('='|'+='|'-='|':='|'*='|'/='|'^=');
+
+index:   expr (',' expr)* ;
+
+diff:   ('\'')+;
+
+functionCall:   ID '(' (expr (',' expr)*)? ')'
+            |   (Mass|Inertia) '(' (ID (',' ID)*)? ')';
+
+varDecl:   varType varDecl2 (',' varDecl2)*;
+
+varType:   Newtonian|Frames|Bodies|Particles|Points|Constants
+       |   Specifieds|Imaginary|Variables ('\'')*|MotionVariables ('\'')*;
+
+varDecl2:   ID ('{' INT ',' INT '}')? (('{' INT ':' INT (',' INT ':' INT)* '}'))? ('{' INT '}')? ('+'|'-')? ('\'')* ('=' expr)?;
+
+ranges:   ('{' INT ':' INT (',' INT ':' INT)* '}');
+
+massDecl:   Mass massDecl2 (',' massDecl2)*;
+
+massDecl2:   ID '=' expr;
+
+inertiaDecl:   Inertia ID ('(' ID ')')? (',' expr)+;
+
+matrix:   '[' expr ((','|';') expr)* ']';
+matrixInOutput:   (ID (ID '=' (FLOAT|INT)?))|FLOAT|INT;
+
+codeCommands:   units
+            |   inputs
+            |   outputs
+            |   codegen
+            |   commands;
+
+settings:   ID (EXP|ID|FLOAT|INT)?;
+
+units:     UnitSystem ID (',' ID)*;
+inputs:    Input inputs2 (',' inputs2)*;
+id_diff:   ID diff?;
+inputs2:   id_diff '=' expr expr?;
+outputs:   Output outputs2 (',' outputs2)*;
+outputs2:  expr expr?;
+codegen:   ID functionCall ('['matrixInOutput (',' matrixInOutput)*']')? ID'.'ID;
+
+commands:  Save ID'.'ID
+        |  Encode ID (',' ID)*;
+
+vec:  ID ('>')+
+   |  '0>'
+   |  '1>>';
+
+expr:   expr '^' expr  # Exponent
+    |   expr ('*'|'/') expr         # MulDiv
+    |   expr ('+'|'-') expr         # AddSub
+    |   EXP                         # exp
+    |   '-' expr                    # negativeOne
+    |   FLOAT                       # float
+    |   INT                         # int
+    |   ID('\'')*                   # id
+    |   vec                         # VectorOrDyadic
+    |   ID '['expr (',' expr)* ']'  # Indexing
+    |   functionCall                # function
+    |   matrix                      # matrices
+    |   '(' expr ')'                # parens
+    |   expr '=' expr               # idEqualsExpr
+    |   expr ':' expr               # colon
+    |   ID? ranges ('\'')*          # rangess
+    ;
+
+// These are to take care of the case insensitivity of Autolev.
+Mass: ('M'|'m')('A'|'a')('S'|'s')('S'|'s');
+Inertia: ('I'|'i')('N'|'n')('E'|'e')('R'|'r')('T'|'t')('I'|'i')('A'|'a');
+Input: ('I'|'i')('N'|'n')('P'|'p')('U'|'u')('T'|'t')('S'|'s')?;
+Output: ('O'|'o')('U'|'u')('T'|'t')('P'|'p')('U'|'u')('T'|'t');
+Save: ('S'|'s')('A'|'a')('V'|'v')('E'|'e');
+UnitSystem: ('U'|'u')('N'|'n')('I'|'i')('T'|'t')('S'|'s')('Y'|'y')('S'|'s')('T'|'t')('E'|'e')('M'|'m');
+Encode: ('E'|'e')('N'|'n')('C'|'c')('O'|'o')('D'|'d')('E'|'e');
+Newtonian: ('N'|'n')('E'|'e')('W'|'w')('T'|'t')('O'|'o')('N'|'n')('I'|'i')('A'|'a')('N'|'n');
+Frames: ('F'|'f')('R'|'r')('A'|'a')('M'|'m')('E'|'e')('S'|'s')?;
+Bodies: ('B'|'b')('O'|'o')('D'|'d')('I'|'i')('E'|'e')('S'|'s')?;
+Particles: ('P'|'p')('A'|'a')('R'|'r')('T'|'t')('I'|'i')('C'|'c')('L'|'l')('E'|'e')('S'|'s')?;
+Points: ('P'|'p')('O'|'o')('I'|'i')('N'|'n')('T'|'t')('S'|'s')?;
+Constants: ('C'|'c')('O'|'o')('N'|'n')('S'|'s')('T'|'t')('A'|'a')('N'|'n')('T'|'t')('S'|'s')?;
+Specifieds: ('S'|'s')('P'|'p')('E'|'e')('C'|'c')('I'|'i')('F'|'f')('I'|'i')('E'|'e')('D'|'d')('S'|'s')?;
+Imaginary: ('I'|'i')('M'|'m')('A'|'a')('G'|'g')('I'|'i')('N'|'n')('A'|'a')('R'|'r')('Y'|'y');
+Variables: ('V'|'v')('A'|'a')('R'|'r')('I'|'i')('A'|'a')('B'|'b')('L'|'l')('E'|'e')('S'|'s')?;
+MotionVariables: ('M'|'m')('O'|'o')('T'|'t')('I'|'i')('O'|'o')('N'|'n')('V'|'v')('A'|'a')('R'|'r')('I'|'i')('A'|'a')('B'|'b')('L'|'l')('E'|'e')('S'|'s')?;
+
+fragment DIFF:   ('\'')*;
+fragment DIGIT:  [0-9];
+INT:   [0-9]+ ;         // match integers
+FLOAT:  DIGIT+ '.' DIGIT*
+     |  '.' DIGIT+;
+EXP:   FLOAT 'E' INT
+|      FLOAT 'E' '-' INT;
+LINE_COMMENT : '%' .*? '\r'? '\n' -> skip ;
+ID:   [a-zA-Z][a-zA-Z0-9_]*;
+WS:   [ \t\r\n&]+ -> skip ; // toss out whitespace
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec81bb83325d68e1c11b43a1df5ec56846367e9f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/__init__.py
@@ -0,0 +1,97 @@
+from sympy.external import import_module
+from sympy.utilities.decorator import doctest_depends_on
+
+@doctest_depends_on(modules=('antlr4',))
+def parse_autolev(autolev_code, include_numeric=False):
+    """Parses Autolev code (version 4.1) to SymPy code.
+
+    Parameters
+    =========
+    autolev_code : Can be an str or any object with a readlines() method (such as a file handle or StringIO).
+    include_numeric : boolean, optional
+        If True NumPy, PyDy, or other numeric code is included for numeric evaluation lines in the Autolev code.
+
+    Returns
+    =======
+    sympy_code : str
+        Equivalent SymPy and/or numpy/pydy code as the input code.
+
+
+    Example (Double Pendulum)
+    =========================
+    >>> my_al_text = ("MOTIONVARIABLES' Q{2}', U{2}'",
+    ... "CONSTANTS L,M,G",
+    ... "NEWTONIAN N",
+    ... "FRAMES A,B",
+    ... "SIMPROT(N, A, 3, Q1)",
+    ... "SIMPROT(N, B, 3, Q2)",
+    ... "W_A_N>=U1*N3>",
+    ... "W_B_N>=U2*N3>",
+    ... "POINT O",
+    ... "PARTICLES P,R",
+    ... "P_O_P> = L*A1>",
+    ... "P_P_R> = L*B1>",
+    ... "V_O_N> = 0>",
+    ... "V2PTS(N, A, O, P)",
+    ... "V2PTS(N, B, P, R)",
+    ... "MASS P=M, R=M",
+    ... "Q1' = U1",
+    ... "Q2' = U2",
+    ... "GRAVITY(G*N1>)",
+    ... "ZERO = FR() + FRSTAR()",
+    ... "KANE()",
+    ... "INPUT M=1,G=9.81,L=1",
+    ... "INPUT Q1=.1,Q2=.2,U1=0,U2=0",
+    ... "INPUT TFINAL=10, INTEGSTP=.01",
+    ... "CODE DYNAMICS() some_filename.c")
+    >>> my_al_text = '\\n'.join(my_al_text)
+    >>> from sympy.parsing.autolev import parse_autolev
+    >>> print(parse_autolev(my_al_text, include_numeric=True))
+    import sympy.physics.mechanics as _me
+    import sympy as _sm
+    import math as m
+    import numpy as _np
+    
+    q1, q2, u1, u2 = _me.dynamicsymbols('q1 q2 u1 u2')
+    q1_d, q2_d, u1_d, u2_d = _me.dynamicsymbols('q1_ q2_ u1_ u2_', 1)
+    l, m, g = _sm.symbols('l m g', real=True)
+    frame_n = _me.ReferenceFrame('n')
+    frame_a = _me.ReferenceFrame('a')
+    frame_b = _me.ReferenceFrame('b')
+    frame_a.orient(frame_n, 'Axis', [q1, frame_n.z])
+    frame_b.orient(frame_n, 'Axis', [q2, frame_n.z])
+    frame_a.set_ang_vel(frame_n, u1*frame_n.z)
+    frame_b.set_ang_vel(frame_n, u2*frame_n.z)
+    point_o = _me.Point('o')
+    particle_p = _me.Particle('p', _me.Point('p_pt'), _sm.Symbol('m'))
+    particle_r = _me.Particle('r', _me.Point('r_pt'), _sm.Symbol('m'))
+    particle_p.point.set_pos(point_o, l*frame_a.x)
+    particle_r.point.set_pos(particle_p.point, l*frame_b.x)
+    point_o.set_vel(frame_n, 0)
+    particle_p.point.v2pt_theory(point_o,frame_n,frame_a)
+    particle_r.point.v2pt_theory(particle_p.point,frame_n,frame_b)
+    particle_p.mass = m
+    particle_r.mass = m
+    force_p = particle_p.mass*(g*frame_n.x)
+    force_r = particle_r.mass*(g*frame_n.x)
+    kd_eqs = [q1_d - u1, q2_d - u2]
+    forceList = [(particle_p.point,particle_p.mass*(g*frame_n.x)), (particle_r.point,particle_r.mass*(g*frame_n.x))]
+    kane = _me.KanesMethod(frame_n, q_ind=[q1,q2], u_ind=[u1, u2], kd_eqs = kd_eqs)
+    fr, frstar = kane.kanes_equations([particle_p, particle_r], forceList)
+    zero = fr+frstar
+    from pydy.system import System
+    sys = System(kane, constants = {l:1, m:1, g:9.81},
+    specifieds={},
+    initial_conditions={q1:.1, q2:.2, u1:0, u2:0},
+    times = _np.linspace(0.0, 10, 10/.01))
+    
+    y=sys.integrate()
+    
+    """
+
+    _autolev = import_module(
+        'sympy.parsing.autolev._parse_autolev_antlr',
+        import_kwargs={'fromlist': ['X']})
+
+    if _autolev is not None:
+        return _autolev.parse_autolev(autolev_code, include_numeric)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b71e9f51fd455558a9eb42dc840604c6c96e4b3
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/__init__.py
@@ -0,0 +1,5 @@
+# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
+#
+# Generated with antlr4
+#    antlr4 is licensed under the BSD-3-Clause License
+#    https://github.com/antlr/antlr4/blob/master/LICENSE.txt
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/autolevlexer.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/autolevlexer.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3b3b1d27ade809a63d9fd328a1572c17625443e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/autolevlexer.py
@@ -0,0 +1,253 @@
+# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
+#
+# Generated with antlr4
+#    antlr4 is licensed under the BSD-3-Clause License
+#    https://github.com/antlr/antlr4/blob/master/LICENSE.txt
+from antlr4 import *
+from io import StringIO
+import sys
+if sys.version_info[1] > 5:
+    from typing import TextIO
+else:
+    from typing.io import TextIO
+
+
+def serializedATN():
+    return [
+        4,0,49,393,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,
+        2,6,7,6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2,
+        13,7,13,2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7,
+        19,2,20,7,20,2,21,7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7,25,2,
+        26,7,26,2,27,7,27,2,28,7,28,2,29,7,29,2,30,7,30,2,31,7,31,2,32,7,
+        32,2,33,7,33,2,34,7,34,2,35,7,35,2,36,7,36,2,37,7,37,2,38,7,38,2,
+        39,7,39,2,40,7,40,2,41,7,41,2,42,7,42,2,43,7,43,2,44,7,44,2,45,7,
+        45,2,46,7,46,2,47,7,47,2,48,7,48,2,49,7,49,2,50,7,50,1,0,1,0,1,1,
+        1,1,1,2,1,2,1,3,1,3,1,3,1,4,1,4,1,4,1,5,1,5,1,5,1,6,1,6,1,6,1,7,
+        1,7,1,7,1,8,1,8,1,8,1,9,1,9,1,10,1,10,1,11,1,11,1,12,1,12,1,13,1,
+        13,1,14,1,14,1,15,1,15,1,16,1,16,1,17,1,17,1,18,1,18,1,19,1,19,1,
+        20,1,20,1,21,1,21,1,21,1,22,1,22,1,22,1,22,1,23,1,23,1,24,1,24,1,
+        25,1,25,1,26,1,26,1,26,1,26,1,26,1,27,1,27,1,27,1,27,1,27,1,27,1,
+        27,1,27,1,28,1,28,1,28,1,28,1,28,1,28,3,28,184,8,28,1,29,1,29,1,
+        29,1,29,1,29,1,29,1,29,1,30,1,30,1,30,1,30,1,30,1,31,1,31,1,31,1,
+        31,1,31,1,31,1,31,1,31,1,31,1,31,1,31,1,32,1,32,1,32,1,32,1,32,1,
+        32,1,32,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,34,1,
+        34,1,34,1,34,1,34,1,34,3,34,232,8,34,1,35,1,35,1,35,1,35,1,35,1,
+        35,3,35,240,8,35,1,36,1,36,1,36,1,36,1,36,1,36,1,36,1,36,1,36,3,
+        36,251,8,36,1,37,1,37,1,37,1,37,1,37,1,37,3,37,259,8,37,1,38,1,38,
+        1,38,1,38,1,38,1,38,1,38,1,38,1,38,3,38,270,8,38,1,39,1,39,1,39,
+        1,39,1,39,1,39,1,39,1,39,1,39,1,39,3,39,282,8,39,1,40,1,40,1,40,
+        1,40,1,40,1,40,1,40,1,40,1,40,1,40,1,41,1,41,1,41,1,41,1,41,1,41,
+        1,41,1,41,1,41,3,41,303,8,41,1,42,1,42,1,42,1,42,1,42,1,42,1,42,
+        1,42,1,42,1,42,1,42,1,42,1,42,1,42,1,42,3,42,320,8,42,1,43,5,43,
+        323,8,43,10,43,12,43,326,9,43,1,44,1,44,1,45,4,45,331,8,45,11,45,
+        12,45,332,1,46,4,46,336,8,46,11,46,12,46,337,1,46,1,46,5,46,342,
+        8,46,10,46,12,46,345,9,46,1,46,1,46,4,46,349,8,46,11,46,12,46,350,
+        3,46,353,8,46,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47,3,47,
+        364,8,47,1,48,1,48,5,48,368,8,48,10,48,12,48,371,9,48,1,48,3,48,
+        374,8,48,1,48,1,48,1,48,1,48,1,49,1,49,5,49,382,8,49,10,49,12,49,
+        385,9,49,1,50,4,50,388,8,50,11,50,12,50,389,1,50,1,50,1,369,0,51,
+        1,1,3,2,5,3,7,4,9,5,11,6,13,7,15,8,17,9,19,10,21,11,23,12,25,13,
+        27,14,29,15,31,16,33,17,35,18,37,19,39,20,41,21,43,22,45,23,47,24,
+        49,25,51,26,53,27,55,28,57,29,59,30,61,31,63,32,65,33,67,34,69,35,
+        71,36,73,37,75,38,77,39,79,40,81,41,83,42,85,43,87,0,89,0,91,44,
+        93,45,95,46,97,47,99,48,101,49,1,0,24,2,0,77,77,109,109,2,0,65,65,
+        97,97,2,0,83,83,115,115,2,0,73,73,105,105,2,0,78,78,110,110,2,0,
+        69,69,101,101,2,0,82,82,114,114,2,0,84,84,116,116,2,0,80,80,112,
+        112,2,0,85,85,117,117,2,0,79,79,111,111,2,0,86,86,118,118,2,0,89,
+        89,121,121,2,0,67,67,99,99,2,0,68,68,100,100,2,0,87,87,119,119,2,
+        0,70,70,102,102,2,0,66,66,98,98,2,0,76,76,108,108,2,0,71,71,103,
+        103,1,0,48,57,2,0,65,90,97,122,4,0,48,57,65,90,95,95,97,122,4,0,
+        9,10,13,13,32,32,38,38,410,0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0,0,
+        7,1,0,0,0,0,9,1,0,0,0,0,11,1,0,0,0,0,13,1,0,0,0,0,15,1,0,0,0,0,17,
+        1,0,0,0,0,19,1,0,0,0,0,21,1,0,0,0,0,23,1,0,0,0,0,25,1,0,0,0,0,27,
+        1,0,0,0,0,29,1,0,0,0,0,31,1,0,0,0,0,33,1,0,0,0,0,35,1,0,0,0,0,37,
+        1,0,0,0,0,39,1,0,0,0,0,41,1,0,0,0,0,43,1,0,0,0,0,45,1,0,0,0,0,47,
+        1,0,0,0,0,49,1,0,0,0,0,51,1,0,0,0,0,53,1,0,0,0,0,55,1,0,0,0,0,57,
+        1,0,0,0,0,59,1,0,0,0,0,61,1,0,0,0,0,63,1,0,0,0,0,65,1,0,0,0,0,67,
+        1,0,0,0,0,69,1,0,0,0,0,71,1,0,0,0,0,73,1,0,0,0,0,75,1,0,0,0,0,77,
+        1,0,0,0,0,79,1,0,0,0,0,81,1,0,0,0,0,83,1,0,0,0,0,85,1,0,0,0,0,91,
+        1,0,0,0,0,93,1,0,0,0,0,95,1,0,0,0,0,97,1,0,0,0,0,99,1,0,0,0,0,101,
+        1,0,0,0,1,103,1,0,0,0,3,105,1,0,0,0,5,107,1,0,0,0,7,109,1,0,0,0,
+        9,112,1,0,0,0,11,115,1,0,0,0,13,118,1,0,0,0,15,121,1,0,0,0,17,124,
+        1,0,0,0,19,127,1,0,0,0,21,129,1,0,0,0,23,131,1,0,0,0,25,133,1,0,
+        0,0,27,135,1,0,0,0,29,137,1,0,0,0,31,139,1,0,0,0,33,141,1,0,0,0,
+        35,143,1,0,0,0,37,145,1,0,0,0,39,147,1,0,0,0,41,149,1,0,0,0,43,151,
+        1,0,0,0,45,154,1,0,0,0,47,158,1,0,0,0,49,160,1,0,0,0,51,162,1,0,
+        0,0,53,164,1,0,0,0,55,169,1,0,0,0,57,177,1,0,0,0,59,185,1,0,0,0,
+        61,192,1,0,0,0,63,197,1,0,0,0,65,208,1,0,0,0,67,215,1,0,0,0,69,225,
+        1,0,0,0,71,233,1,0,0,0,73,241,1,0,0,0,75,252,1,0,0,0,77,260,1,0,
+        0,0,79,271,1,0,0,0,81,283,1,0,0,0,83,293,1,0,0,0,85,304,1,0,0,0,
+        87,324,1,0,0,0,89,327,1,0,0,0,91,330,1,0,0,0,93,352,1,0,0,0,95,363,
+        1,0,0,0,97,365,1,0,0,0,99,379,1,0,0,0,101,387,1,0,0,0,103,104,5,
+        91,0,0,104,2,1,0,0,0,105,106,5,93,0,0,106,4,1,0,0,0,107,108,5,61,
+        0,0,108,6,1,0,0,0,109,110,5,43,0,0,110,111,5,61,0,0,111,8,1,0,0,
+        0,112,113,5,45,0,0,113,114,5,61,0,0,114,10,1,0,0,0,115,116,5,58,
+        0,0,116,117,5,61,0,0,117,12,1,0,0,0,118,119,5,42,0,0,119,120,5,61,
+        0,0,120,14,1,0,0,0,121,122,5,47,0,0,122,123,5,61,0,0,123,16,1,0,
+        0,0,124,125,5,94,0,0,125,126,5,61,0,0,126,18,1,0,0,0,127,128,5,44,
+        0,0,128,20,1,0,0,0,129,130,5,39,0,0,130,22,1,0,0,0,131,132,5,40,
+        0,0,132,24,1,0,0,0,133,134,5,41,0,0,134,26,1,0,0,0,135,136,5,123,
+        0,0,136,28,1,0,0,0,137,138,5,125,0,0,138,30,1,0,0,0,139,140,5,58,
+        0,0,140,32,1,0,0,0,141,142,5,43,0,0,142,34,1,0,0,0,143,144,5,45,
+        0,0,144,36,1,0,0,0,145,146,5,59,0,0,146,38,1,0,0,0,147,148,5,46,
+        0,0,148,40,1,0,0,0,149,150,5,62,0,0,150,42,1,0,0,0,151,152,5,48,
+        0,0,152,153,5,62,0,0,153,44,1,0,0,0,154,155,5,49,0,0,155,156,5,62,
+        0,0,156,157,5,62,0,0,157,46,1,0,0,0,158,159,5,94,0,0,159,48,1,0,
+        0,0,160,161,5,42,0,0,161,50,1,0,0,0,162,163,5,47,0,0,163,52,1,0,
+        0,0,164,165,7,0,0,0,165,166,7,1,0,0,166,167,7,2,0,0,167,168,7,2,
+        0,0,168,54,1,0,0,0,169,170,7,3,0,0,170,171,7,4,0,0,171,172,7,5,0,
+        0,172,173,7,6,0,0,173,174,7,7,0,0,174,175,7,3,0,0,175,176,7,1,0,
+        0,176,56,1,0,0,0,177,178,7,3,0,0,178,179,7,4,0,0,179,180,7,8,0,0,
+        180,181,7,9,0,0,181,183,7,7,0,0,182,184,7,2,0,0,183,182,1,0,0,0,
+        183,184,1,0,0,0,184,58,1,0,0,0,185,186,7,10,0,0,186,187,7,9,0,0,
+        187,188,7,7,0,0,188,189,7,8,0,0,189,190,7,9,0,0,190,191,7,7,0,0,
+        191,60,1,0,0,0,192,193,7,2,0,0,193,194,7,1,0,0,194,195,7,11,0,0,
+        195,196,7,5,0,0,196,62,1,0,0,0,197,198,7,9,0,0,198,199,7,4,0,0,199,
+        200,7,3,0,0,200,201,7,7,0,0,201,202,7,2,0,0,202,203,7,12,0,0,203,
+        204,7,2,0,0,204,205,7,7,0,0,205,206,7,5,0,0,206,207,7,0,0,0,207,
+        64,1,0,0,0,208,209,7,5,0,0,209,210,7,4,0,0,210,211,7,13,0,0,211,
+        212,7,10,0,0,212,213,7,14,0,0,213,214,7,5,0,0,214,66,1,0,0,0,215,
+        216,7,4,0,0,216,217,7,5,0,0,217,218,7,15,0,0,218,219,7,7,0,0,219,
+        220,7,10,0,0,220,221,7,4,0,0,221,222,7,3,0,0,222,223,7,1,0,0,223,
+        224,7,4,0,0,224,68,1,0,0,0,225,226,7,16,0,0,226,227,7,6,0,0,227,
+        228,7,1,0,0,228,229,7,0,0,0,229,231,7,5,0,0,230,232,7,2,0,0,231,
+        230,1,0,0,0,231,232,1,0,0,0,232,70,1,0,0,0,233,234,7,17,0,0,234,
+        235,7,10,0,0,235,236,7,14,0,0,236,237,7,3,0,0,237,239,7,5,0,0,238,
+        240,7,2,0,0,239,238,1,0,0,0,239,240,1,0,0,0,240,72,1,0,0,0,241,242,
+        7,8,0,0,242,243,7,1,0,0,243,244,7,6,0,0,244,245,7,7,0,0,245,246,
+        7,3,0,0,246,247,7,13,0,0,247,248,7,18,0,0,248,250,7,5,0,0,249,251,
+        7,2,0,0,250,249,1,0,0,0,250,251,1,0,0,0,251,74,1,0,0,0,252,253,7,
+        8,0,0,253,254,7,10,0,0,254,255,7,3,0,0,255,256,7,4,0,0,256,258,7,
+        7,0,0,257,259,7,2,0,0,258,257,1,0,0,0,258,259,1,0,0,0,259,76,1,0,
+        0,0,260,261,7,13,0,0,261,262,7,10,0,0,262,263,7,4,0,0,263,264,7,
+        2,0,0,264,265,7,7,0,0,265,266,7,1,0,0,266,267,7,4,0,0,267,269,7,
+        7,0,0,268,270,7,2,0,0,269,268,1,0,0,0,269,270,1,0,0,0,270,78,1,0,
+        0,0,271,272,7,2,0,0,272,273,7,8,0,0,273,274,7,5,0,0,274,275,7,13,
+        0,0,275,276,7,3,0,0,276,277,7,16,0,0,277,278,7,3,0,0,278,279,7,5,
+        0,0,279,281,7,14,0,0,280,282,7,2,0,0,281,280,1,0,0,0,281,282,1,0,
+        0,0,282,80,1,0,0,0,283,284,7,3,0,0,284,285,7,0,0,0,285,286,7,1,0,
+        0,286,287,7,19,0,0,287,288,7,3,0,0,288,289,7,4,0,0,289,290,7,1,0,
+        0,290,291,7,6,0,0,291,292,7,12,0,0,292,82,1,0,0,0,293,294,7,11,0,
+        0,294,295,7,1,0,0,295,296,7,6,0,0,296,297,7,3,0,0,297,298,7,1,0,
+        0,298,299,7,17,0,0,299,300,7,18,0,0,300,302,7,5,0,0,301,303,7,2,
+        0,0,302,301,1,0,0,0,302,303,1,0,0,0,303,84,1,0,0,0,304,305,7,0,0,
+        0,305,306,7,10,0,0,306,307,7,7,0,0,307,308,7,3,0,0,308,309,7,10,
+        0,0,309,310,7,4,0,0,310,311,7,11,0,0,311,312,7,1,0,0,312,313,7,6,
+        0,0,313,314,7,3,0,0,314,315,7,1,0,0,315,316,7,17,0,0,316,317,7,18,
+        0,0,317,319,7,5,0,0,318,320,7,2,0,0,319,318,1,0,0,0,319,320,1,0,
+        0,0,320,86,1,0,0,0,321,323,5,39,0,0,322,321,1,0,0,0,323,326,1,0,
+        0,0,324,322,1,0,0,0,324,325,1,0,0,0,325,88,1,0,0,0,326,324,1,0,0,
+        0,327,328,7,20,0,0,328,90,1,0,0,0,329,331,7,20,0,0,330,329,1,0,0,
+        0,331,332,1,0,0,0,332,330,1,0,0,0,332,333,1,0,0,0,333,92,1,0,0,0,
+        334,336,3,89,44,0,335,334,1,0,0,0,336,337,1,0,0,0,337,335,1,0,0,
+        0,337,338,1,0,0,0,338,339,1,0,0,0,339,343,5,46,0,0,340,342,3,89,
+        44,0,341,340,1,0,0,0,342,345,1,0,0,0,343,341,1,0,0,0,343,344,1,0,
+        0,0,344,353,1,0,0,0,345,343,1,0,0,0,346,348,5,46,0,0,347,349,3,89,
+        44,0,348,347,1,0,0,0,349,350,1,0,0,0,350,348,1,0,0,0,350,351,1,0,
+        0,0,351,353,1,0,0,0,352,335,1,0,0,0,352,346,1,0,0,0,353,94,1,0,0,
+        0,354,355,3,93,46,0,355,356,5,69,0,0,356,357,3,91,45,0,357,364,1,
+        0,0,0,358,359,3,93,46,0,359,360,5,69,0,0,360,361,5,45,0,0,361,362,
+        3,91,45,0,362,364,1,0,0,0,363,354,1,0,0,0,363,358,1,0,0,0,364,96,
+        1,0,0,0,365,369,5,37,0,0,366,368,9,0,0,0,367,366,1,0,0,0,368,371,
+        1,0,0,0,369,370,1,0,0,0,369,367,1,0,0,0,370,373,1,0,0,0,371,369,
+        1,0,0,0,372,374,5,13,0,0,373,372,1,0,0,0,373,374,1,0,0,0,374,375,
+        1,0,0,0,375,376,5,10,0,0,376,377,1,0,0,0,377,378,6,48,0,0,378,98,
+        1,0,0,0,379,383,7,21,0,0,380,382,7,22,0,0,381,380,1,0,0,0,382,385,
+        1,0,0,0,383,381,1,0,0,0,383,384,1,0,0,0,384,100,1,0,0,0,385,383,
+        1,0,0,0,386,388,7,23,0,0,387,386,1,0,0,0,388,389,1,0,0,0,389,387,
+        1,0,0,0,389,390,1,0,0,0,390,391,1,0,0,0,391,392,6,50,0,0,392,102,
+        1,0,0,0,21,0,183,231,239,250,258,269,281,302,319,324,332,337,343,
+        350,352,363,369,373,383,389,1,6,0,0
+    ]
+
+class AutolevLexer(Lexer):
+
+    atn = ATNDeserializer().deserialize(serializedATN())
+
+    decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
+
+    T__0 = 1
+    T__1 = 2
+    T__2 = 3
+    T__3 = 4
+    T__4 = 5
+    T__5 = 6
+    T__6 = 7
+    T__7 = 8
+    T__8 = 9
+    T__9 = 10
+    T__10 = 11
+    T__11 = 12
+    T__12 = 13
+    T__13 = 14
+    T__14 = 15
+    T__15 = 16
+    T__16 = 17
+    T__17 = 18
+    T__18 = 19
+    T__19 = 20
+    T__20 = 21
+    T__21 = 22
+    T__22 = 23
+    T__23 = 24
+    T__24 = 25
+    T__25 = 26
+    Mass = 27
+    Inertia = 28
+    Input = 29
+    Output = 30
+    Save = 31
+    UnitSystem = 32
+    Encode = 33
+    Newtonian = 34
+    Frames = 35
+    Bodies = 36
+    Particles = 37
+    Points = 38
+    Constants = 39
+    Specifieds = 40
+    Imaginary = 41
+    Variables = 42
+    MotionVariables = 43
+    INT = 44
+    FLOAT = 45
+    EXP = 46
+    LINE_COMMENT = 47
+    ID = 48
+    WS = 49
+
+    channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ]
+
+    modeNames = [ "DEFAULT_MODE" ]
+
+    literalNames = [ "",
+            "'['", "']'", "'='", "'+='", "'-='", "':='", "'*='", "'/='",
+            "'^='", "','", "'''", "'('", "')'", "'{'", "'}'", "':'", "'+'",
+            "'-'", "';'", "'.'", "'>'", "'0>'", "'1>>'", "'^'", "'*'", "'/'" ]
+
+    symbolicNames = [ "",
+            "Mass", "Inertia", "Input", "Output", "Save", "UnitSystem",
+            "Encode", "Newtonian", "Frames", "Bodies", "Particles", "Points",
+            "Constants", "Specifieds", "Imaginary", "Variables", "MotionVariables",
+            "INT", "FLOAT", "EXP", "LINE_COMMENT", "ID", "WS" ]
+
+    ruleNames = [ "T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6",
+                  "T__7", "T__8", "T__9", "T__10", "T__11", "T__12", "T__13",
+                  "T__14", "T__15", "T__16", "T__17", "T__18", "T__19",
+                  "T__20", "T__21", "T__22", "T__23", "T__24", "T__25",
+                  "Mass", "Inertia", "Input", "Output", "Save", "UnitSystem",
+                  "Encode", "Newtonian", "Frames", "Bodies", "Particles",
+                  "Points", "Constants", "Specifieds", "Imaginary", "Variables",
+                  "MotionVariables", "DIFF", "DIGIT", "INT", "FLOAT", "EXP",
+                  "LINE_COMMENT", "ID", "WS" ]
+
+    grammarFileName = "Autolev.g4"
+
+    def __init__(self, input=None, output:TextIO = sys.stdout):
+        super().__init__(input, output)
+        self.checkVersion("4.11.1")
+        self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
+        self._actions = None
+        self._predicates = None
+
+
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/autolevlistener.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/autolevlistener.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f391a298a71ecf2d04cf921a919cbb68b181fab
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/autolevlistener.py
@@ -0,0 +1,421 @@
+# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
+#
+# Generated with antlr4
+#    antlr4 is licensed under the BSD-3-Clause License
+#    https://github.com/antlr/antlr4/blob/master/LICENSE.txt
+from antlr4 import *
+if __name__ is not None and "." in __name__:
+    from .autolevparser import AutolevParser
+else:
+    from autolevparser import AutolevParser
+
+# This class defines a complete listener for a parse tree produced by AutolevParser.
+class AutolevListener(ParseTreeListener):
+
+    # Enter a parse tree produced by AutolevParser#prog.
+    def enterProg(self, ctx:AutolevParser.ProgContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#prog.
+    def exitProg(self, ctx:AutolevParser.ProgContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#stat.
+    def enterStat(self, ctx:AutolevParser.StatContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#stat.
+    def exitStat(self, ctx:AutolevParser.StatContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#vecAssign.
+    def enterVecAssign(self, ctx:AutolevParser.VecAssignContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#vecAssign.
+    def exitVecAssign(self, ctx:AutolevParser.VecAssignContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#indexAssign.
+    def enterIndexAssign(self, ctx:AutolevParser.IndexAssignContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#indexAssign.
+    def exitIndexAssign(self, ctx:AutolevParser.IndexAssignContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#regularAssign.
+    def enterRegularAssign(self, ctx:AutolevParser.RegularAssignContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#regularAssign.
+    def exitRegularAssign(self, ctx:AutolevParser.RegularAssignContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#equals.
+    def enterEquals(self, ctx:AutolevParser.EqualsContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#equals.
+    def exitEquals(self, ctx:AutolevParser.EqualsContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#index.
+    def enterIndex(self, ctx:AutolevParser.IndexContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#index.
+    def exitIndex(self, ctx:AutolevParser.IndexContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#diff.
+    def enterDiff(self, ctx:AutolevParser.DiffContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#diff.
+    def exitDiff(self, ctx:AutolevParser.DiffContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#functionCall.
+    def enterFunctionCall(self, ctx:AutolevParser.FunctionCallContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#functionCall.
+    def exitFunctionCall(self, ctx:AutolevParser.FunctionCallContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#varDecl.
+    def enterVarDecl(self, ctx:AutolevParser.VarDeclContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#varDecl.
+    def exitVarDecl(self, ctx:AutolevParser.VarDeclContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#varType.
+    def enterVarType(self, ctx:AutolevParser.VarTypeContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#varType.
+    def exitVarType(self, ctx:AutolevParser.VarTypeContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#varDecl2.
+    def enterVarDecl2(self, ctx:AutolevParser.VarDecl2Context):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#varDecl2.
+    def exitVarDecl2(self, ctx:AutolevParser.VarDecl2Context):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#ranges.
+    def enterRanges(self, ctx:AutolevParser.RangesContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#ranges.
+    def exitRanges(self, ctx:AutolevParser.RangesContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#massDecl.
+    def enterMassDecl(self, ctx:AutolevParser.MassDeclContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#massDecl.
+    def exitMassDecl(self, ctx:AutolevParser.MassDeclContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#massDecl2.
+    def enterMassDecl2(self, ctx:AutolevParser.MassDecl2Context):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#massDecl2.
+    def exitMassDecl2(self, ctx:AutolevParser.MassDecl2Context):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#inertiaDecl.
+    def enterInertiaDecl(self, ctx:AutolevParser.InertiaDeclContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#inertiaDecl.
+    def exitInertiaDecl(self, ctx:AutolevParser.InertiaDeclContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#matrix.
+    def enterMatrix(self, ctx:AutolevParser.MatrixContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#matrix.
+    def exitMatrix(self, ctx:AutolevParser.MatrixContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#matrixInOutput.
+    def enterMatrixInOutput(self, ctx:AutolevParser.MatrixInOutputContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#matrixInOutput.
+    def exitMatrixInOutput(self, ctx:AutolevParser.MatrixInOutputContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#codeCommands.
+    def enterCodeCommands(self, ctx:AutolevParser.CodeCommandsContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#codeCommands.
+    def exitCodeCommands(self, ctx:AutolevParser.CodeCommandsContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#settings.
+    def enterSettings(self, ctx:AutolevParser.SettingsContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#settings.
+    def exitSettings(self, ctx:AutolevParser.SettingsContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#units.
+    def enterUnits(self, ctx:AutolevParser.UnitsContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#units.
+    def exitUnits(self, ctx:AutolevParser.UnitsContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#inputs.
+    def enterInputs(self, ctx:AutolevParser.InputsContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#inputs.
+    def exitInputs(self, ctx:AutolevParser.InputsContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#id_diff.
+    def enterId_diff(self, ctx:AutolevParser.Id_diffContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#id_diff.
+    def exitId_diff(self, ctx:AutolevParser.Id_diffContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#inputs2.
+    def enterInputs2(self, ctx:AutolevParser.Inputs2Context):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#inputs2.
+    def exitInputs2(self, ctx:AutolevParser.Inputs2Context):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#outputs.
+    def enterOutputs(self, ctx:AutolevParser.OutputsContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#outputs.
+    def exitOutputs(self, ctx:AutolevParser.OutputsContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#outputs2.
+    def enterOutputs2(self, ctx:AutolevParser.Outputs2Context):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#outputs2.
+    def exitOutputs2(self, ctx:AutolevParser.Outputs2Context):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#codegen.
+    def enterCodegen(self, ctx:AutolevParser.CodegenContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#codegen.
+    def exitCodegen(self, ctx:AutolevParser.CodegenContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#commands.
+    def enterCommands(self, ctx:AutolevParser.CommandsContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#commands.
+    def exitCommands(self, ctx:AutolevParser.CommandsContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#vec.
+    def enterVec(self, ctx:AutolevParser.VecContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#vec.
+    def exitVec(self, ctx:AutolevParser.VecContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#parens.
+    def enterParens(self, ctx:AutolevParser.ParensContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#parens.
+    def exitParens(self, ctx:AutolevParser.ParensContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#VectorOrDyadic.
+    def enterVectorOrDyadic(self, ctx:AutolevParser.VectorOrDyadicContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#VectorOrDyadic.
+    def exitVectorOrDyadic(self, ctx:AutolevParser.VectorOrDyadicContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#Exponent.
+    def enterExponent(self, ctx:AutolevParser.ExponentContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#Exponent.
+    def exitExponent(self, ctx:AutolevParser.ExponentContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#MulDiv.
+    def enterMulDiv(self, ctx:AutolevParser.MulDivContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#MulDiv.
+    def exitMulDiv(self, ctx:AutolevParser.MulDivContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#AddSub.
+    def enterAddSub(self, ctx:AutolevParser.AddSubContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#AddSub.
+    def exitAddSub(self, ctx:AutolevParser.AddSubContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#float.
+    def enterFloat(self, ctx:AutolevParser.FloatContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#float.
+    def exitFloat(self, ctx:AutolevParser.FloatContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#int.
+    def enterInt(self, ctx:AutolevParser.IntContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#int.
+    def exitInt(self, ctx:AutolevParser.IntContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#idEqualsExpr.
+    def enterIdEqualsExpr(self, ctx:AutolevParser.IdEqualsExprContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#idEqualsExpr.
+    def exitIdEqualsExpr(self, ctx:AutolevParser.IdEqualsExprContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#negativeOne.
+    def enterNegativeOne(self, ctx:AutolevParser.NegativeOneContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#negativeOne.
+    def exitNegativeOne(self, ctx:AutolevParser.NegativeOneContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#function.
+    def enterFunction(self, ctx:AutolevParser.FunctionContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#function.
+    def exitFunction(self, ctx:AutolevParser.FunctionContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#rangess.
+    def enterRangess(self, ctx:AutolevParser.RangessContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#rangess.
+    def exitRangess(self, ctx:AutolevParser.RangessContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#colon.
+    def enterColon(self, ctx:AutolevParser.ColonContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#colon.
+    def exitColon(self, ctx:AutolevParser.ColonContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#id.
+    def enterId(self, ctx:AutolevParser.IdContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#id.
+    def exitId(self, ctx:AutolevParser.IdContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#exp.
+    def enterExp(self, ctx:AutolevParser.ExpContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#exp.
+    def exitExp(self, ctx:AutolevParser.ExpContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#matrices.
+    def enterMatrices(self, ctx:AutolevParser.MatricesContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#matrices.
+    def exitMatrices(self, ctx:AutolevParser.MatricesContext):
+        pass
+
+
+    # Enter a parse tree produced by AutolevParser#Indexing.
+    def enterIndexing(self, ctx:AutolevParser.IndexingContext):
+        pass
+
+    # Exit a parse tree produced by AutolevParser#Indexing.
+    def exitIndexing(self, ctx:AutolevParser.IndexingContext):
+        pass
+
+
+
+del AutolevParser
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/autolevparser.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/autolevparser.py
new file mode 100644
index 0000000000000000000000000000000000000000..e63ef1c110812580d06291ee7c7ec40b6a076cea
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_antlr/autolevparser.py
@@ -0,0 +1,3063 @@
+# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
+#
+# Generated with antlr4
+#    antlr4 is licensed under the BSD-3-Clause License
+#    https://github.com/antlr/antlr4/blob/master/LICENSE.txt
+from antlr4 import *
+from io import StringIO
+import sys
+if sys.version_info[1] > 5:
+	from typing import TextIO
+else:
+	from typing.io import TextIO
+
+def serializedATN():
+    return [
+        4,1,49,431,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,6,7,
+        6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2,13,7,13,
+        2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7,19,2,20,
+        7,20,2,21,7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7,25,2,26,7,26,
+        2,27,7,27,1,0,4,0,58,8,0,11,0,12,0,59,1,1,1,1,1,1,1,1,1,1,1,1,1,
+        1,3,1,69,8,1,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,
+        3,2,84,8,2,1,2,1,2,1,2,3,2,89,8,2,1,3,1,3,1,4,1,4,1,4,5,4,96,8,4,
+        10,4,12,4,99,9,4,1,5,4,5,102,8,5,11,5,12,5,103,1,6,1,6,1,6,1,6,1,
+        6,5,6,111,8,6,10,6,12,6,114,9,6,3,6,116,8,6,1,6,1,6,1,6,1,6,1,6,
+        1,6,5,6,124,8,6,10,6,12,6,127,9,6,3,6,129,8,6,1,6,3,6,132,8,6,1,
+        7,1,7,1,7,1,7,5,7,138,8,7,10,7,12,7,141,9,7,1,8,1,8,1,8,1,8,1,8,
+        1,8,1,8,1,8,1,8,1,8,5,8,153,8,8,10,8,12,8,156,9,8,1,8,1,8,5,8,160,
+        8,8,10,8,12,8,163,9,8,3,8,165,8,8,1,9,1,9,1,9,1,9,1,9,1,9,3,9,173,
+        8,9,1,9,1,9,1,9,1,9,1,9,1,9,1,9,1,9,5,9,183,8,9,10,9,12,9,186,9,
+        9,1,9,3,9,189,8,9,1,9,1,9,1,9,3,9,194,8,9,1,9,3,9,197,8,9,1,9,5,
+        9,200,8,9,10,9,12,9,203,9,9,1,9,1,9,3,9,207,8,9,1,10,1,10,1,10,1,
+        10,1,10,1,10,1,10,1,10,5,10,217,8,10,10,10,12,10,220,9,10,1,10,1,
+        10,1,11,1,11,1,11,1,11,5,11,228,8,11,10,11,12,11,231,9,11,1,12,1,
+        12,1,12,1,12,1,13,1,13,1,13,1,13,1,13,3,13,242,8,13,1,13,1,13,4,
+        13,246,8,13,11,13,12,13,247,1,14,1,14,1,14,1,14,5,14,254,8,14,10,
+        14,12,14,257,9,14,1,14,1,14,1,15,1,15,1,15,1,15,3,15,265,8,15,1,
+        15,1,15,3,15,269,8,15,1,16,1,16,1,16,1,16,1,16,3,16,276,8,16,1,17,
+        1,17,3,17,280,8,17,1,18,1,18,1,18,1,18,5,18,286,8,18,10,18,12,18,
+        289,9,18,1,19,1,19,1,19,1,19,5,19,295,8,19,10,19,12,19,298,9,19,
+        1,20,1,20,3,20,302,8,20,1,21,1,21,1,21,1,21,3,21,308,8,21,1,22,1,
+        22,1,22,1,22,5,22,314,8,22,10,22,12,22,317,9,22,1,23,1,23,3,23,321,
+        8,23,1,24,1,24,1,24,1,24,1,24,1,24,5,24,329,8,24,10,24,12,24,332,
+        9,24,1,24,1,24,3,24,336,8,24,1,24,1,24,1,24,1,24,1,25,1,25,1,25,
+        1,25,1,25,1,25,1,25,1,25,5,25,350,8,25,10,25,12,25,353,9,25,3,25,
+        355,8,25,1,26,1,26,4,26,359,8,26,11,26,12,26,360,1,26,1,26,3,26,
+        365,8,26,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,5,27,375,8,27,10,
+        27,12,27,378,9,27,1,27,1,27,1,27,1,27,1,27,1,27,5,27,386,8,27,10,
+        27,12,27,389,9,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,3,
+        27,400,8,27,1,27,1,27,5,27,404,8,27,10,27,12,27,407,9,27,3,27,409,
+        8,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,
+        1,27,1,27,1,27,5,27,426,8,27,10,27,12,27,429,9,27,1,27,0,1,54,28,
+        0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,
+        46,48,50,52,54,0,7,1,0,3,9,1,0,27,28,1,0,17,18,2,0,10,10,19,19,1,
+        0,44,45,2,0,44,46,48,48,1,0,25,26,483,0,57,1,0,0,0,2,68,1,0,0,0,
+        4,88,1,0,0,0,6,90,1,0,0,0,8,92,1,0,0,0,10,101,1,0,0,0,12,131,1,0,
+        0,0,14,133,1,0,0,0,16,164,1,0,0,0,18,166,1,0,0,0,20,208,1,0,0,0,
+        22,223,1,0,0,0,24,232,1,0,0,0,26,236,1,0,0,0,28,249,1,0,0,0,30,268,
+        1,0,0,0,32,275,1,0,0,0,34,277,1,0,0,0,36,281,1,0,0,0,38,290,1,0,
+        0,0,40,299,1,0,0,0,42,303,1,0,0,0,44,309,1,0,0,0,46,318,1,0,0,0,
+        48,322,1,0,0,0,50,354,1,0,0,0,52,364,1,0,0,0,54,408,1,0,0,0,56,58,
+        3,2,1,0,57,56,1,0,0,0,58,59,1,0,0,0,59,57,1,0,0,0,59,60,1,0,0,0,
+        60,1,1,0,0,0,61,69,3,14,7,0,62,69,3,12,6,0,63,69,3,32,16,0,64,69,
+        3,22,11,0,65,69,3,26,13,0,66,69,3,4,2,0,67,69,3,34,17,0,68,61,1,
+        0,0,0,68,62,1,0,0,0,68,63,1,0,0,0,68,64,1,0,0,0,68,65,1,0,0,0,68,
+        66,1,0,0,0,68,67,1,0,0,0,69,3,1,0,0,0,70,71,3,52,26,0,71,72,3,6,
+        3,0,72,73,3,54,27,0,73,89,1,0,0,0,74,75,5,48,0,0,75,76,5,1,0,0,76,
+        77,3,8,4,0,77,78,5,2,0,0,78,79,3,6,3,0,79,80,3,54,27,0,80,89,1,0,
+        0,0,81,83,5,48,0,0,82,84,3,10,5,0,83,82,1,0,0,0,83,84,1,0,0,0,84,
+        85,1,0,0,0,85,86,3,6,3,0,86,87,3,54,27,0,87,89,1,0,0,0,88,70,1,0,
+        0,0,88,74,1,0,0,0,88,81,1,0,0,0,89,5,1,0,0,0,90,91,7,0,0,0,91,7,
+        1,0,0,0,92,97,3,54,27,0,93,94,5,10,0,0,94,96,3,54,27,0,95,93,1,0,
+        0,0,96,99,1,0,0,0,97,95,1,0,0,0,97,98,1,0,0,0,98,9,1,0,0,0,99,97,
+        1,0,0,0,100,102,5,11,0,0,101,100,1,0,0,0,102,103,1,0,0,0,103,101,
+        1,0,0,0,103,104,1,0,0,0,104,11,1,0,0,0,105,106,5,48,0,0,106,115,
+        5,12,0,0,107,112,3,54,27,0,108,109,5,10,0,0,109,111,3,54,27,0,110,
+        108,1,0,0,0,111,114,1,0,0,0,112,110,1,0,0,0,112,113,1,0,0,0,113,
+        116,1,0,0,0,114,112,1,0,0,0,115,107,1,0,0,0,115,116,1,0,0,0,116,
+        117,1,0,0,0,117,132,5,13,0,0,118,119,7,1,0,0,119,128,5,12,0,0,120,
+        125,5,48,0,0,121,122,5,10,0,0,122,124,5,48,0,0,123,121,1,0,0,0,124,
+        127,1,0,0,0,125,123,1,0,0,0,125,126,1,0,0,0,126,129,1,0,0,0,127,
+        125,1,0,0,0,128,120,1,0,0,0,128,129,1,0,0,0,129,130,1,0,0,0,130,
+        132,5,13,0,0,131,105,1,0,0,0,131,118,1,0,0,0,132,13,1,0,0,0,133,
+        134,3,16,8,0,134,139,3,18,9,0,135,136,5,10,0,0,136,138,3,18,9,0,
+        137,135,1,0,0,0,138,141,1,0,0,0,139,137,1,0,0,0,139,140,1,0,0,0,
+        140,15,1,0,0,0,141,139,1,0,0,0,142,165,5,34,0,0,143,165,5,35,0,0,
+        144,165,5,36,0,0,145,165,5,37,0,0,146,165,5,38,0,0,147,165,5,39,
+        0,0,148,165,5,40,0,0,149,165,5,41,0,0,150,154,5,42,0,0,151,153,5,
+        11,0,0,152,151,1,0,0,0,153,156,1,0,0,0,154,152,1,0,0,0,154,155,1,
+        0,0,0,155,165,1,0,0,0,156,154,1,0,0,0,157,161,5,43,0,0,158,160,5,
+        11,0,0,159,158,1,0,0,0,160,163,1,0,0,0,161,159,1,0,0,0,161,162,1,
+        0,0,0,162,165,1,0,0,0,163,161,1,0,0,0,164,142,1,0,0,0,164,143,1,
+        0,0,0,164,144,1,0,0,0,164,145,1,0,0,0,164,146,1,0,0,0,164,147,1,
+        0,0,0,164,148,1,0,0,0,164,149,1,0,0,0,164,150,1,0,0,0,164,157,1,
+        0,0,0,165,17,1,0,0,0,166,172,5,48,0,0,167,168,5,14,0,0,168,169,5,
+        44,0,0,169,170,5,10,0,0,170,171,5,44,0,0,171,173,5,15,0,0,172,167,
+        1,0,0,0,172,173,1,0,0,0,173,188,1,0,0,0,174,175,5,14,0,0,175,176,
+        5,44,0,0,176,177,5,16,0,0,177,184,5,44,0,0,178,179,5,10,0,0,179,
+        180,5,44,0,0,180,181,5,16,0,0,181,183,5,44,0,0,182,178,1,0,0,0,183,
+        186,1,0,0,0,184,182,1,0,0,0,184,185,1,0,0,0,185,187,1,0,0,0,186,
+        184,1,0,0,0,187,189,5,15,0,0,188,174,1,0,0,0,188,189,1,0,0,0,189,
+        193,1,0,0,0,190,191,5,14,0,0,191,192,5,44,0,0,192,194,5,15,0,0,193,
+        190,1,0,0,0,193,194,1,0,0,0,194,196,1,0,0,0,195,197,7,2,0,0,196,
+        195,1,0,0,0,196,197,1,0,0,0,197,201,1,0,0,0,198,200,5,11,0,0,199,
+        198,1,0,0,0,200,203,1,0,0,0,201,199,1,0,0,0,201,202,1,0,0,0,202,
+        206,1,0,0,0,203,201,1,0,0,0,204,205,5,3,0,0,205,207,3,54,27,0,206,
+        204,1,0,0,0,206,207,1,0,0,0,207,19,1,0,0,0,208,209,5,14,0,0,209,
+        210,5,44,0,0,210,211,5,16,0,0,211,218,5,44,0,0,212,213,5,10,0,0,
+        213,214,5,44,0,0,214,215,5,16,0,0,215,217,5,44,0,0,216,212,1,0,0,
+        0,217,220,1,0,0,0,218,216,1,0,0,0,218,219,1,0,0,0,219,221,1,0,0,
+        0,220,218,1,0,0,0,221,222,5,15,0,0,222,21,1,0,0,0,223,224,5,27,0,
+        0,224,229,3,24,12,0,225,226,5,10,0,0,226,228,3,24,12,0,227,225,1,
+        0,0,0,228,231,1,0,0,0,229,227,1,0,0,0,229,230,1,0,0,0,230,23,1,0,
+        0,0,231,229,1,0,0,0,232,233,5,48,0,0,233,234,5,3,0,0,234,235,3,54,
+        27,0,235,25,1,0,0,0,236,237,5,28,0,0,237,241,5,48,0,0,238,239,5,
+        12,0,0,239,240,5,48,0,0,240,242,5,13,0,0,241,238,1,0,0,0,241,242,
+        1,0,0,0,242,245,1,0,0,0,243,244,5,10,0,0,244,246,3,54,27,0,245,243,
+        1,0,0,0,246,247,1,0,0,0,247,245,1,0,0,0,247,248,1,0,0,0,248,27,1,
+        0,0,0,249,250,5,1,0,0,250,255,3,54,27,0,251,252,7,3,0,0,252,254,
+        3,54,27,0,253,251,1,0,0,0,254,257,1,0,0,0,255,253,1,0,0,0,255,256,
+        1,0,0,0,256,258,1,0,0,0,257,255,1,0,0,0,258,259,5,2,0,0,259,29,1,
+        0,0,0,260,261,5,48,0,0,261,262,5,48,0,0,262,264,5,3,0,0,263,265,
+        7,4,0,0,264,263,1,0,0,0,264,265,1,0,0,0,265,269,1,0,0,0,266,269,
+        5,45,0,0,267,269,5,44,0,0,268,260,1,0,0,0,268,266,1,0,0,0,268,267,
+        1,0,0,0,269,31,1,0,0,0,270,276,3,36,18,0,271,276,3,38,19,0,272,276,
+        3,44,22,0,273,276,3,48,24,0,274,276,3,50,25,0,275,270,1,0,0,0,275,
+        271,1,0,0,0,275,272,1,0,0,0,275,273,1,0,0,0,275,274,1,0,0,0,276,
+        33,1,0,0,0,277,279,5,48,0,0,278,280,7,5,0,0,279,278,1,0,0,0,279,
+        280,1,0,0,0,280,35,1,0,0,0,281,282,5,32,0,0,282,287,5,48,0,0,283,
+        284,5,10,0,0,284,286,5,48,0,0,285,283,1,0,0,0,286,289,1,0,0,0,287,
+        285,1,0,0,0,287,288,1,0,0,0,288,37,1,0,0,0,289,287,1,0,0,0,290,291,
+        5,29,0,0,291,296,3,42,21,0,292,293,5,10,0,0,293,295,3,42,21,0,294,
+        292,1,0,0,0,295,298,1,0,0,0,296,294,1,0,0,0,296,297,1,0,0,0,297,
+        39,1,0,0,0,298,296,1,0,0,0,299,301,5,48,0,0,300,302,3,10,5,0,301,
+        300,1,0,0,0,301,302,1,0,0,0,302,41,1,0,0,0,303,304,3,40,20,0,304,
+        305,5,3,0,0,305,307,3,54,27,0,306,308,3,54,27,0,307,306,1,0,0,0,
+        307,308,1,0,0,0,308,43,1,0,0,0,309,310,5,30,0,0,310,315,3,46,23,
+        0,311,312,5,10,0,0,312,314,3,46,23,0,313,311,1,0,0,0,314,317,1,0,
+        0,0,315,313,1,0,0,0,315,316,1,0,0,0,316,45,1,0,0,0,317,315,1,0,0,
+        0,318,320,3,54,27,0,319,321,3,54,27,0,320,319,1,0,0,0,320,321,1,
+        0,0,0,321,47,1,0,0,0,322,323,5,48,0,0,323,335,3,12,6,0,324,325,5,
+        1,0,0,325,330,3,30,15,0,326,327,5,10,0,0,327,329,3,30,15,0,328,326,
+        1,0,0,0,329,332,1,0,0,0,330,328,1,0,0,0,330,331,1,0,0,0,331,333,
+        1,0,0,0,332,330,1,0,0,0,333,334,5,2,0,0,334,336,1,0,0,0,335,324,
+        1,0,0,0,335,336,1,0,0,0,336,337,1,0,0,0,337,338,5,48,0,0,338,339,
+        5,20,0,0,339,340,5,48,0,0,340,49,1,0,0,0,341,342,5,31,0,0,342,343,
+        5,48,0,0,343,344,5,20,0,0,344,355,5,48,0,0,345,346,5,33,0,0,346,
+        351,5,48,0,0,347,348,5,10,0,0,348,350,5,48,0,0,349,347,1,0,0,0,350,
+        353,1,0,0,0,351,349,1,0,0,0,351,352,1,0,0,0,352,355,1,0,0,0,353,
+        351,1,0,0,0,354,341,1,0,0,0,354,345,1,0,0,0,355,51,1,0,0,0,356,358,
+        5,48,0,0,357,359,5,21,0,0,358,357,1,0,0,0,359,360,1,0,0,0,360,358,
+        1,0,0,0,360,361,1,0,0,0,361,365,1,0,0,0,362,365,5,22,0,0,363,365,
+        5,23,0,0,364,356,1,0,0,0,364,362,1,0,0,0,364,363,1,0,0,0,365,53,
+        1,0,0,0,366,367,6,27,-1,0,367,409,5,46,0,0,368,369,5,18,0,0,369,
+        409,3,54,27,12,370,409,5,45,0,0,371,409,5,44,0,0,372,376,5,48,0,
+        0,373,375,5,11,0,0,374,373,1,0,0,0,375,378,1,0,0,0,376,374,1,0,0,
+        0,376,377,1,0,0,0,377,409,1,0,0,0,378,376,1,0,0,0,379,409,3,52,26,
+        0,380,381,5,48,0,0,381,382,5,1,0,0,382,387,3,54,27,0,383,384,5,10,
+        0,0,384,386,3,54,27,0,385,383,1,0,0,0,386,389,1,0,0,0,387,385,1,
+        0,0,0,387,388,1,0,0,0,388,390,1,0,0,0,389,387,1,0,0,0,390,391,5,
+        2,0,0,391,409,1,0,0,0,392,409,3,12,6,0,393,409,3,28,14,0,394,395,
+        5,12,0,0,395,396,3,54,27,0,396,397,5,13,0,0,397,409,1,0,0,0,398,
+        400,5,48,0,0,399,398,1,0,0,0,399,400,1,0,0,0,400,401,1,0,0,0,401,
+        405,3,20,10,0,402,404,5,11,0,0,403,402,1,0,0,0,404,407,1,0,0,0,405,
+        403,1,0,0,0,405,406,1,0,0,0,406,409,1,0,0,0,407,405,1,0,0,0,408,
+        366,1,0,0,0,408,368,1,0,0,0,408,370,1,0,0,0,408,371,1,0,0,0,408,
+        372,1,0,0,0,408,379,1,0,0,0,408,380,1,0,0,0,408,392,1,0,0,0,408,
+        393,1,0,0,0,408,394,1,0,0,0,408,399,1,0,0,0,409,427,1,0,0,0,410,
+        411,10,16,0,0,411,412,5,24,0,0,412,426,3,54,27,17,413,414,10,15,
+        0,0,414,415,7,6,0,0,415,426,3,54,27,16,416,417,10,14,0,0,417,418,
+        7,2,0,0,418,426,3,54,27,15,419,420,10,3,0,0,420,421,5,3,0,0,421,
+        426,3,54,27,4,422,423,10,2,0,0,423,424,5,16,0,0,424,426,3,54,27,
+        3,425,410,1,0,0,0,425,413,1,0,0,0,425,416,1,0,0,0,425,419,1,0,0,
+        0,425,422,1,0,0,0,426,429,1,0,0,0,427,425,1,0,0,0,427,428,1,0,0,
+        0,428,55,1,0,0,0,429,427,1,0,0,0,50,59,68,83,88,97,103,112,115,125,
+        128,131,139,154,161,164,172,184,188,193,196,201,206,218,229,241,
+        247,255,264,268,275,279,287,296,301,307,315,320,330,335,351,354,
+        360,364,376,387,399,405,408,425,427
+    ]
+
+class AutolevParser ( Parser ):
+
+    grammarFileName = "Autolev.g4"
+
+    atn = ATNDeserializer().deserialize(serializedATN())
+
+    decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
+
+    sharedContextCache = PredictionContextCache()
+
+    literalNames = [ "", "'['", "']'", "'='", "'+='", "'-='", "':='",
+                     "'*='", "'/='", "'^='", "','", "'''", "'('", "')'",
+                     "'{'", "'}'", "':'", "'+'", "'-'", "';'", "'.'", "'>'",
+                     "'0>'", "'1>>'", "'^'", "'*'", "'/'" ]
+
+    symbolicNames = [ "", "", "", "",
+                      "", "", "", "",
+                      "", "", "", "",
+                      "", "", "", "",
+                      "", "", "", "",
+                      "", "", "", "",
+                      "", "", "", "Mass", "Inertia",
+                      "Input", "Output", "Save", "UnitSystem", "Encode",
+                      "Newtonian", "Frames", "Bodies", "Particles", "Points",
+                      "Constants", "Specifieds", "Imaginary", "Variables",
+                      "MotionVariables", "INT", "FLOAT", "EXP", "LINE_COMMENT",
+                      "ID", "WS" ]
+
+    RULE_prog = 0
+    RULE_stat = 1
+    RULE_assignment = 2
+    RULE_equals = 3
+    RULE_index = 4
+    RULE_diff = 5
+    RULE_functionCall = 6
+    RULE_varDecl = 7
+    RULE_varType = 8
+    RULE_varDecl2 = 9
+    RULE_ranges = 10
+    RULE_massDecl = 11
+    RULE_massDecl2 = 12
+    RULE_inertiaDecl = 13
+    RULE_matrix = 14
+    RULE_matrixInOutput = 15
+    RULE_codeCommands = 16
+    RULE_settings = 17
+    RULE_units = 18
+    RULE_inputs = 19
+    RULE_id_diff = 20
+    RULE_inputs2 = 21
+    RULE_outputs = 22
+    RULE_outputs2 = 23
+    RULE_codegen = 24
+    RULE_commands = 25
+    RULE_vec = 26
+    RULE_expr = 27
+
+    ruleNames =  [ "prog", "stat", "assignment", "equals", "index", "diff",
+                   "functionCall", "varDecl", "varType", "varDecl2", "ranges",
+                   "massDecl", "massDecl2", "inertiaDecl", "matrix", "matrixInOutput",
+                   "codeCommands", "settings", "units", "inputs", "id_diff",
+                   "inputs2", "outputs", "outputs2", "codegen", "commands",
+                   "vec", "expr" ]
+
+    EOF = Token.EOF
+    T__0=1
+    T__1=2
+    T__2=3
+    T__3=4
+    T__4=5
+    T__5=6
+    T__6=7
+    T__7=8
+    T__8=9
+    T__9=10
+    T__10=11
+    T__11=12
+    T__12=13
+    T__13=14
+    T__14=15
+    T__15=16
+    T__16=17
+    T__17=18
+    T__18=19
+    T__19=20
+    T__20=21
+    T__21=22
+    T__22=23
+    T__23=24
+    T__24=25
+    T__25=26
+    Mass=27
+    Inertia=28
+    Input=29
+    Output=30
+    Save=31
+    UnitSystem=32
+    Encode=33
+    Newtonian=34
+    Frames=35
+    Bodies=36
+    Particles=37
+    Points=38
+    Constants=39
+    Specifieds=40
+    Imaginary=41
+    Variables=42
+    MotionVariables=43
+    INT=44
+    FLOAT=45
+    EXP=46
+    LINE_COMMENT=47
+    ID=48
+    WS=49
+
+    def __init__(self, input:TokenStream, output:TextIO = sys.stdout):
+        super().__init__(input, output)
+        self.checkVersion("4.11.1")
+        self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache)
+        self._predicates = None
+
+
+
+
+    class ProgContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def stat(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(AutolevParser.StatContext)
+            else:
+                return self.getTypedRuleContext(AutolevParser.StatContext,i)
+
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_prog
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterProg" ):
+                listener.enterProg(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitProg" ):
+                listener.exitProg(self)
+
+
+
+
+    def prog(self):
+
+        localctx = AutolevParser.ProgContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 0, self.RULE_prog)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 57
+            self._errHandler.sync(self)
+            _la = self._input.LA(1)
+            while True:
+                self.state = 56
+                self.stat()
+                self.state = 59
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+                if not (((_la) & ~0x3f) == 0 and ((1 << _la) & 299067041120256) != 0):
+                    break
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class StatContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def varDecl(self):
+            return self.getTypedRuleContext(AutolevParser.VarDeclContext,0)
+
+
+        def functionCall(self):
+            return self.getTypedRuleContext(AutolevParser.FunctionCallContext,0)
+
+
+        def codeCommands(self):
+            return self.getTypedRuleContext(AutolevParser.CodeCommandsContext,0)
+
+
+        def massDecl(self):
+            return self.getTypedRuleContext(AutolevParser.MassDeclContext,0)
+
+
+        def inertiaDecl(self):
+            return self.getTypedRuleContext(AutolevParser.InertiaDeclContext,0)
+
+
+        def assignment(self):
+            return self.getTypedRuleContext(AutolevParser.AssignmentContext,0)
+
+
+        def settings(self):
+            return self.getTypedRuleContext(AutolevParser.SettingsContext,0)
+
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_stat
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterStat" ):
+                listener.enterStat(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitStat" ):
+                listener.exitStat(self)
+
+
+
+
+    def stat(self):
+
+        localctx = AutolevParser.StatContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 2, self.RULE_stat)
+        try:
+            self.state = 68
+            self._errHandler.sync(self)
+            la_ = self._interp.adaptivePredict(self._input,1,self._ctx)
+            if la_ == 1:
+                self.enterOuterAlt(localctx, 1)
+                self.state = 61
+                self.varDecl()
+                pass
+
+            elif la_ == 2:
+                self.enterOuterAlt(localctx, 2)
+                self.state = 62
+                self.functionCall()
+                pass
+
+            elif la_ == 3:
+                self.enterOuterAlt(localctx, 3)
+                self.state = 63
+                self.codeCommands()
+                pass
+
+            elif la_ == 4:
+                self.enterOuterAlt(localctx, 4)
+                self.state = 64
+                self.massDecl()
+                pass
+
+            elif la_ == 5:
+                self.enterOuterAlt(localctx, 5)
+                self.state = 65
+                self.inertiaDecl()
+                pass
+
+            elif la_ == 6:
+                self.enterOuterAlt(localctx, 6)
+                self.state = 66
+                self.assignment()
+                pass
+
+            elif la_ == 7:
+                self.enterOuterAlt(localctx, 7)
+                self.state = 67
+                self.settings()
+                pass
+
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class AssignmentContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_assignment
+
+
+        def copyFrom(self, ctx:ParserRuleContext):
+            super().copyFrom(ctx)
+
+
+
+    class VecAssignContext(AssignmentContext):
+
+        def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.AssignmentContext
+            super().__init__(parser)
+            self.copyFrom(ctx)
+
+        def vec(self):
+            return self.getTypedRuleContext(AutolevParser.VecContext,0)
+
+        def equals(self):
+            return self.getTypedRuleContext(AutolevParser.EqualsContext,0)
+
+        def expr(self):
+            return self.getTypedRuleContext(AutolevParser.ExprContext,0)
+
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterVecAssign" ):
+                listener.enterVecAssign(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitVecAssign" ):
+                listener.exitVecAssign(self)
+
+
+    class RegularAssignContext(AssignmentContext):
+
+        def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.AssignmentContext
+            super().__init__(parser)
+            self.copyFrom(ctx)
+
+        def ID(self):
+            return self.getToken(AutolevParser.ID, 0)
+        def equals(self):
+            return self.getTypedRuleContext(AutolevParser.EqualsContext,0)
+
+        def expr(self):
+            return self.getTypedRuleContext(AutolevParser.ExprContext,0)
+
+        def diff(self):
+            return self.getTypedRuleContext(AutolevParser.DiffContext,0)
+
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterRegularAssign" ):
+                listener.enterRegularAssign(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitRegularAssign" ):
+                listener.exitRegularAssign(self)
+
+
+    class IndexAssignContext(AssignmentContext):
+
+        def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.AssignmentContext
+            super().__init__(parser)
+            self.copyFrom(ctx)
+
+        def ID(self):
+            return self.getToken(AutolevParser.ID, 0)
+        def index(self):
+            return self.getTypedRuleContext(AutolevParser.IndexContext,0)
+
+        def equals(self):
+            return self.getTypedRuleContext(AutolevParser.EqualsContext,0)
+
+        def expr(self):
+            return self.getTypedRuleContext(AutolevParser.ExprContext,0)
+
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterIndexAssign" ):
+                listener.enterIndexAssign(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitIndexAssign" ):
+                listener.exitIndexAssign(self)
+
+
+
+    def assignment(self):
+
+        localctx = AutolevParser.AssignmentContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 4, self.RULE_assignment)
+        self._la = 0 # Token type
+        try:
+            self.state = 88
+            self._errHandler.sync(self)
+            la_ = self._interp.adaptivePredict(self._input,3,self._ctx)
+            if la_ == 1:
+                localctx = AutolevParser.VecAssignContext(self, localctx)
+                self.enterOuterAlt(localctx, 1)
+                self.state = 70
+                self.vec()
+                self.state = 71
+                self.equals()
+                self.state = 72
+                self.expr(0)
+                pass
+
+            elif la_ == 2:
+                localctx = AutolevParser.IndexAssignContext(self, localctx)
+                self.enterOuterAlt(localctx, 2)
+                self.state = 74
+                self.match(AutolevParser.ID)
+                self.state = 75
+                self.match(AutolevParser.T__0)
+                self.state = 76
+                self.index()
+                self.state = 77
+                self.match(AutolevParser.T__1)
+                self.state = 78
+                self.equals()
+                self.state = 79
+                self.expr(0)
+                pass
+
+            elif la_ == 3:
+                localctx = AutolevParser.RegularAssignContext(self, localctx)
+                self.enterOuterAlt(localctx, 3)
+                self.state = 81
+                self.match(AutolevParser.ID)
+                self.state = 83
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+                if _la==11:
+                    self.state = 82
+                    self.diff()
+
+
+                self.state = 85
+                self.equals()
+                self.state = 86
+                self.expr(0)
+                pass
+
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class EqualsContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_equals
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterEquals" ):
+                listener.enterEquals(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitEquals" ):
+                listener.exitEquals(self)
+
+
+
+
+    def equals(self):
+
+        localctx = AutolevParser.EqualsContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 6, self.RULE_equals)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 90
+            _la = self._input.LA(1)
+            if not(((_la) & ~0x3f) == 0 and ((1 << _la) & 1016) != 0):
+                self._errHandler.recoverInline(self)
+            else:
+                self._errHandler.reportMatch(self)
+                self.consume()
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class IndexContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def expr(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(AutolevParser.ExprContext)
+            else:
+                return self.getTypedRuleContext(AutolevParser.ExprContext,i)
+
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_index
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterIndex" ):
+                listener.enterIndex(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitIndex" ):
+                listener.exitIndex(self)
+
+
+
+
+    def index(self):
+
+        localctx = AutolevParser.IndexContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 8, self.RULE_index)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 92
+            self.expr(0)
+            self.state = 97
+            self._errHandler.sync(self)
+            _la = self._input.LA(1)
+            while _la==10:
+                self.state = 93
+                self.match(AutolevParser.T__9)
+                self.state = 94
+                self.expr(0)
+                self.state = 99
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class DiffContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_diff
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterDiff" ):
+                listener.enterDiff(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitDiff" ):
+                listener.exitDiff(self)
+
+
+
+
+    def diff(self):
+
+        localctx = AutolevParser.DiffContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 10, self.RULE_diff)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 101
+            self._errHandler.sync(self)
+            _la = self._input.LA(1)
+            while True:
+                self.state = 100
+                self.match(AutolevParser.T__10)
+                self.state = 103
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+                if not (_la==11):
+                    break
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class FunctionCallContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def ID(self, i:int=None):
+            if i is None:
+                return self.getTokens(AutolevParser.ID)
+            else:
+                return self.getToken(AutolevParser.ID, i)
+
+        def expr(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(AutolevParser.ExprContext)
+            else:
+                return self.getTypedRuleContext(AutolevParser.ExprContext,i)
+
+
+        def Mass(self):
+            return self.getToken(AutolevParser.Mass, 0)
+
+        def Inertia(self):
+            return self.getToken(AutolevParser.Inertia, 0)
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_functionCall
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterFunctionCall" ):
+                listener.enterFunctionCall(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitFunctionCall" ):
+                listener.exitFunctionCall(self)
+
+
+
+
+    def functionCall(self):
+
+        localctx = AutolevParser.FunctionCallContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 12, self.RULE_functionCall)
+        self._la = 0 # Token type
+        try:
+            self.state = 131
+            self._errHandler.sync(self)
+            token = self._input.LA(1)
+            if token in [48]:
+                self.enterOuterAlt(localctx, 1)
+                self.state = 105
+                self.match(AutolevParser.ID)
+                self.state = 106
+                self.match(AutolevParser.T__11)
+                self.state = 115
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+                if ((_la) & ~0x3f) == 0 and ((1 << _la) & 404620694540290) != 0:
+                    self.state = 107
+                    self.expr(0)
+                    self.state = 112
+                    self._errHandler.sync(self)
+                    _la = self._input.LA(1)
+                    while _la==10:
+                        self.state = 108
+                        self.match(AutolevParser.T__9)
+                        self.state = 109
+                        self.expr(0)
+                        self.state = 114
+                        self._errHandler.sync(self)
+                        _la = self._input.LA(1)
+
+
+
+                self.state = 117
+                self.match(AutolevParser.T__12)
+                pass
+            elif token in [27, 28]:
+                self.enterOuterAlt(localctx, 2)
+                self.state = 118
+                _la = self._input.LA(1)
+                if not(_la==27 or _la==28):
+                    self._errHandler.recoverInline(self)
+                else:
+                    self._errHandler.reportMatch(self)
+                    self.consume()
+                self.state = 119
+                self.match(AutolevParser.T__11)
+                self.state = 128
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+                if _la==48:
+                    self.state = 120
+                    self.match(AutolevParser.ID)
+                    self.state = 125
+                    self._errHandler.sync(self)
+                    _la = self._input.LA(1)
+                    while _la==10:
+                        self.state = 121
+                        self.match(AutolevParser.T__9)
+                        self.state = 122
+                        self.match(AutolevParser.ID)
+                        self.state = 127
+                        self._errHandler.sync(self)
+                        _la = self._input.LA(1)
+
+
+
+                self.state = 130
+                self.match(AutolevParser.T__12)
+                pass
+            else:
+                raise NoViableAltException(self)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class VarDeclContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def varType(self):
+            return self.getTypedRuleContext(AutolevParser.VarTypeContext,0)
+
+
+        def varDecl2(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(AutolevParser.VarDecl2Context)
+            else:
+                return self.getTypedRuleContext(AutolevParser.VarDecl2Context,i)
+
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_varDecl
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterVarDecl" ):
+                listener.enterVarDecl(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitVarDecl" ):
+                listener.exitVarDecl(self)
+
+
+
+
+    def varDecl(self):
+
+        localctx = AutolevParser.VarDeclContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 14, self.RULE_varDecl)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 133
+            self.varType()
+            self.state = 134
+            self.varDecl2()
+            self.state = 139
+            self._errHandler.sync(self)
+            _la = self._input.LA(1)
+            while _la==10:
+                self.state = 135
+                self.match(AutolevParser.T__9)
+                self.state = 136
+                self.varDecl2()
+                self.state = 141
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class VarTypeContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def Newtonian(self):
+            return self.getToken(AutolevParser.Newtonian, 0)
+
+        def Frames(self):
+            return self.getToken(AutolevParser.Frames, 0)
+
+        def Bodies(self):
+            return self.getToken(AutolevParser.Bodies, 0)
+
+        def Particles(self):
+            return self.getToken(AutolevParser.Particles, 0)
+
+        def Points(self):
+            return self.getToken(AutolevParser.Points, 0)
+
+        def Constants(self):
+            return self.getToken(AutolevParser.Constants, 0)
+
+        def Specifieds(self):
+            return self.getToken(AutolevParser.Specifieds, 0)
+
+        def Imaginary(self):
+            return self.getToken(AutolevParser.Imaginary, 0)
+
+        def Variables(self):
+            return self.getToken(AutolevParser.Variables, 0)
+
+        def MotionVariables(self):
+            return self.getToken(AutolevParser.MotionVariables, 0)
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_varType
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterVarType" ):
+                listener.enterVarType(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitVarType" ):
+                listener.exitVarType(self)
+
+
+
+
+    def varType(self):
+
+        localctx = AutolevParser.VarTypeContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 16, self.RULE_varType)
+        self._la = 0 # Token type
+        try:
+            self.state = 164
+            self._errHandler.sync(self)
+            token = self._input.LA(1)
+            if token in [34]:
+                self.enterOuterAlt(localctx, 1)
+                self.state = 142
+                self.match(AutolevParser.Newtonian)
+                pass
+            elif token in [35]:
+                self.enterOuterAlt(localctx, 2)
+                self.state = 143
+                self.match(AutolevParser.Frames)
+                pass
+            elif token in [36]:
+                self.enterOuterAlt(localctx, 3)
+                self.state = 144
+                self.match(AutolevParser.Bodies)
+                pass
+            elif token in [37]:
+                self.enterOuterAlt(localctx, 4)
+                self.state = 145
+                self.match(AutolevParser.Particles)
+                pass
+            elif token in [38]:
+                self.enterOuterAlt(localctx, 5)
+                self.state = 146
+                self.match(AutolevParser.Points)
+                pass
+            elif token in [39]:
+                self.enterOuterAlt(localctx, 6)
+                self.state = 147
+                self.match(AutolevParser.Constants)
+                pass
+            elif token in [40]:
+                self.enterOuterAlt(localctx, 7)
+                self.state = 148
+                self.match(AutolevParser.Specifieds)
+                pass
+            elif token in [41]:
+                self.enterOuterAlt(localctx, 8)
+                self.state = 149
+                self.match(AutolevParser.Imaginary)
+                pass
+            elif token in [42]:
+                self.enterOuterAlt(localctx, 9)
+                self.state = 150
+                self.match(AutolevParser.Variables)
+                self.state = 154
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+                while _la==11:
+                    self.state = 151
+                    self.match(AutolevParser.T__10)
+                    self.state = 156
+                    self._errHandler.sync(self)
+                    _la = self._input.LA(1)
+
+                pass
+            elif token in [43]:
+                self.enterOuterAlt(localctx, 10)
+                self.state = 157
+                self.match(AutolevParser.MotionVariables)
+                self.state = 161
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+                while _la==11:
+                    self.state = 158
+                    self.match(AutolevParser.T__10)
+                    self.state = 163
+                    self._errHandler.sync(self)
+                    _la = self._input.LA(1)
+
+                pass
+            else:
+                raise NoViableAltException(self)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class VarDecl2Context(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def ID(self):
+            return self.getToken(AutolevParser.ID, 0)
+
+        def INT(self, i:int=None):
+            if i is None:
+                return self.getTokens(AutolevParser.INT)
+            else:
+                return self.getToken(AutolevParser.INT, i)
+
+        def expr(self):
+            return self.getTypedRuleContext(AutolevParser.ExprContext,0)
+
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_varDecl2
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterVarDecl2" ):
+                listener.enterVarDecl2(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitVarDecl2" ):
+                listener.exitVarDecl2(self)
+
+
+
+
+    def varDecl2(self):
+
+        localctx = AutolevParser.VarDecl2Context(self, self._ctx, self.state)
+        self.enterRule(localctx, 18, self.RULE_varDecl2)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 166
+            self.match(AutolevParser.ID)
+            self.state = 172
+            self._errHandler.sync(self)
+            la_ = self._interp.adaptivePredict(self._input,15,self._ctx)
+            if la_ == 1:
+                self.state = 167
+                self.match(AutolevParser.T__13)
+                self.state = 168
+                self.match(AutolevParser.INT)
+                self.state = 169
+                self.match(AutolevParser.T__9)
+                self.state = 170
+                self.match(AutolevParser.INT)
+                self.state = 171
+                self.match(AutolevParser.T__14)
+
+
+            self.state = 188
+            self._errHandler.sync(self)
+            la_ = self._interp.adaptivePredict(self._input,17,self._ctx)
+            if la_ == 1:
+                self.state = 174
+                self.match(AutolevParser.T__13)
+                self.state = 175
+                self.match(AutolevParser.INT)
+                self.state = 176
+                self.match(AutolevParser.T__15)
+                self.state = 177
+                self.match(AutolevParser.INT)
+                self.state = 184
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+                while _la==10:
+                    self.state = 178
+                    self.match(AutolevParser.T__9)
+                    self.state = 179
+                    self.match(AutolevParser.INT)
+                    self.state = 180
+                    self.match(AutolevParser.T__15)
+                    self.state = 181
+                    self.match(AutolevParser.INT)
+                    self.state = 186
+                    self._errHandler.sync(self)
+                    _la = self._input.LA(1)
+
+                self.state = 187
+                self.match(AutolevParser.T__14)
+
+
+            self.state = 193
+            self._errHandler.sync(self)
+            _la = self._input.LA(1)
+            if _la==14:
+                self.state = 190
+                self.match(AutolevParser.T__13)
+                self.state = 191
+                self.match(AutolevParser.INT)
+                self.state = 192
+                self.match(AutolevParser.T__14)
+
+
+            self.state = 196
+            self._errHandler.sync(self)
+            _la = self._input.LA(1)
+            if _la==17 or _la==18:
+                self.state = 195
+                _la = self._input.LA(1)
+                if not(_la==17 or _la==18):
+                    self._errHandler.recoverInline(self)
+                else:
+                    self._errHandler.reportMatch(self)
+                    self.consume()
+
+
+            self.state = 201
+            self._errHandler.sync(self)
+            _la = self._input.LA(1)
+            while _la==11:
+                self.state = 198
+                self.match(AutolevParser.T__10)
+                self.state = 203
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+
+            self.state = 206
+            self._errHandler.sync(self)
+            _la = self._input.LA(1)
+            if _la==3:
+                self.state = 204
+                self.match(AutolevParser.T__2)
+                self.state = 205
+                self.expr(0)
+
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class RangesContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def INT(self, i:int=None):
+            if i is None:
+                return self.getTokens(AutolevParser.INT)
+            else:
+                return self.getToken(AutolevParser.INT, i)
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_ranges
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterRanges" ):
+                listener.enterRanges(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitRanges" ):
+                listener.exitRanges(self)
+
+
+
+
+    def ranges(self):
+
+        localctx = AutolevParser.RangesContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 20, self.RULE_ranges)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 208
+            self.match(AutolevParser.T__13)
+            self.state = 209
+            self.match(AutolevParser.INT)
+            self.state = 210
+            self.match(AutolevParser.T__15)
+            self.state = 211
+            self.match(AutolevParser.INT)
+            self.state = 218
+            self._errHandler.sync(self)
+            _la = self._input.LA(1)
+            while _la==10:
+                self.state = 212
+                self.match(AutolevParser.T__9)
+                self.state = 213
+                self.match(AutolevParser.INT)
+                self.state = 214
+                self.match(AutolevParser.T__15)
+                self.state = 215
+                self.match(AutolevParser.INT)
+                self.state = 220
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+
+            self.state = 221
+            self.match(AutolevParser.T__14)
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class MassDeclContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def Mass(self):
+            return self.getToken(AutolevParser.Mass, 0)
+
+        def massDecl2(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(AutolevParser.MassDecl2Context)
+            else:
+                return self.getTypedRuleContext(AutolevParser.MassDecl2Context,i)
+
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_massDecl
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterMassDecl" ):
+                listener.enterMassDecl(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitMassDecl" ):
+                listener.exitMassDecl(self)
+
+
+
+
+    def massDecl(self):
+
+        localctx = AutolevParser.MassDeclContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 22, self.RULE_massDecl)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 223
+            self.match(AutolevParser.Mass)
+            self.state = 224
+            self.massDecl2()
+            self.state = 229
+            self._errHandler.sync(self)
+            _la = self._input.LA(1)
+            while _la==10:
+                self.state = 225
+                self.match(AutolevParser.T__9)
+                self.state = 226
+                self.massDecl2()
+                self.state = 231
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class MassDecl2Context(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def ID(self):
+            return self.getToken(AutolevParser.ID, 0)
+
+        def expr(self):
+            return self.getTypedRuleContext(AutolevParser.ExprContext,0)
+
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_massDecl2
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterMassDecl2" ):
+                listener.enterMassDecl2(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitMassDecl2" ):
+                listener.exitMassDecl2(self)
+
+
+
+
+    def massDecl2(self):
+
+        localctx = AutolevParser.MassDecl2Context(self, self._ctx, self.state)
+        self.enterRule(localctx, 24, self.RULE_massDecl2)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 232
+            self.match(AutolevParser.ID)
+            self.state = 233
+            self.match(AutolevParser.T__2)
+            self.state = 234
+            self.expr(0)
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class InertiaDeclContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def Inertia(self):
+            return self.getToken(AutolevParser.Inertia, 0)
+
+        def ID(self, i:int=None):
+            if i is None:
+                return self.getTokens(AutolevParser.ID)
+            else:
+                return self.getToken(AutolevParser.ID, i)
+
+        def expr(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(AutolevParser.ExprContext)
+            else:
+                return self.getTypedRuleContext(AutolevParser.ExprContext,i)
+
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_inertiaDecl
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterInertiaDecl" ):
+                listener.enterInertiaDecl(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitInertiaDecl" ):
+                listener.exitInertiaDecl(self)
+
+
+
+
+    def inertiaDecl(self):
+
+        localctx = AutolevParser.InertiaDeclContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 26, self.RULE_inertiaDecl)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 236
+            self.match(AutolevParser.Inertia)
+            self.state = 237
+            self.match(AutolevParser.ID)
+            self.state = 241
+            self._errHandler.sync(self)
+            _la = self._input.LA(1)
+            if _la==12:
+                self.state = 238
+                self.match(AutolevParser.T__11)
+                self.state = 239
+                self.match(AutolevParser.ID)
+                self.state = 240
+                self.match(AutolevParser.T__12)
+
+
+            self.state = 245
+            self._errHandler.sync(self)
+            _la = self._input.LA(1)
+            while True:
+                self.state = 243
+                self.match(AutolevParser.T__9)
+                self.state = 244
+                self.expr(0)
+                self.state = 247
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+                if not (_la==10):
+                    break
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class MatrixContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def expr(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(AutolevParser.ExprContext)
+            else:
+                return self.getTypedRuleContext(AutolevParser.ExprContext,i)
+
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_matrix
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterMatrix" ):
+                listener.enterMatrix(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitMatrix" ):
+                listener.exitMatrix(self)
+
+
+
+
+    def matrix(self):
+
+        localctx = AutolevParser.MatrixContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 28, self.RULE_matrix)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 249
+            self.match(AutolevParser.T__0)
+            self.state = 250
+            self.expr(0)
+            self.state = 255
+            self._errHandler.sync(self)
+            _la = self._input.LA(1)
+            while _la==10 or _la==19:
+                self.state = 251
+                _la = self._input.LA(1)
+                if not(_la==10 or _la==19):
+                    self._errHandler.recoverInline(self)
+                else:
+                    self._errHandler.reportMatch(self)
+                    self.consume()
+                self.state = 252
+                self.expr(0)
+                self.state = 257
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+
+            self.state = 258
+            self.match(AutolevParser.T__1)
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class MatrixInOutputContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def ID(self, i:int=None):
+            if i is None:
+                return self.getTokens(AutolevParser.ID)
+            else:
+                return self.getToken(AutolevParser.ID, i)
+
+        def FLOAT(self):
+            return self.getToken(AutolevParser.FLOAT, 0)
+
+        def INT(self):
+            return self.getToken(AutolevParser.INT, 0)
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_matrixInOutput
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterMatrixInOutput" ):
+                listener.enterMatrixInOutput(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitMatrixInOutput" ):
+                listener.exitMatrixInOutput(self)
+
+
+
+
+    def matrixInOutput(self):
+
+        localctx = AutolevParser.MatrixInOutputContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 30, self.RULE_matrixInOutput)
+        self._la = 0 # Token type
+        try:
+            self.state = 268
+            self._errHandler.sync(self)
+            token = self._input.LA(1)
+            if token in [48]:
+                self.enterOuterAlt(localctx, 1)
+                self.state = 260
+                self.match(AutolevParser.ID)
+
+                self.state = 261
+                self.match(AutolevParser.ID)
+                self.state = 262
+                self.match(AutolevParser.T__2)
+                self.state = 264
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+                if _la==44 or _la==45:
+                    self.state = 263
+                    _la = self._input.LA(1)
+                    if not(_la==44 or _la==45):
+                        self._errHandler.recoverInline(self)
+                    else:
+                        self._errHandler.reportMatch(self)
+                        self.consume()
+
+
+                pass
+            elif token in [45]:
+                self.enterOuterAlt(localctx, 2)
+                self.state = 266
+                self.match(AutolevParser.FLOAT)
+                pass
+            elif token in [44]:
+                self.enterOuterAlt(localctx, 3)
+                self.state = 267
+                self.match(AutolevParser.INT)
+                pass
+            else:
+                raise NoViableAltException(self)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class CodeCommandsContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def units(self):
+            return self.getTypedRuleContext(AutolevParser.UnitsContext,0)
+
+
+        def inputs(self):
+            return self.getTypedRuleContext(AutolevParser.InputsContext,0)
+
+
+        def outputs(self):
+            return self.getTypedRuleContext(AutolevParser.OutputsContext,0)
+
+
+        def codegen(self):
+            return self.getTypedRuleContext(AutolevParser.CodegenContext,0)
+
+
+        def commands(self):
+            return self.getTypedRuleContext(AutolevParser.CommandsContext,0)
+
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_codeCommands
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterCodeCommands" ):
+                listener.enterCodeCommands(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitCodeCommands" ):
+                listener.exitCodeCommands(self)
+
+
+
+
+    def codeCommands(self):
+
+        localctx = AutolevParser.CodeCommandsContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 32, self.RULE_codeCommands)
+        try:
+            self.state = 275
+            self._errHandler.sync(self)
+            token = self._input.LA(1)
+            if token in [32]:
+                self.enterOuterAlt(localctx, 1)
+                self.state = 270
+                self.units()
+                pass
+            elif token in [29]:
+                self.enterOuterAlt(localctx, 2)
+                self.state = 271
+                self.inputs()
+                pass
+            elif token in [30]:
+                self.enterOuterAlt(localctx, 3)
+                self.state = 272
+                self.outputs()
+                pass
+            elif token in [48]:
+                self.enterOuterAlt(localctx, 4)
+                self.state = 273
+                self.codegen()
+                pass
+            elif token in [31, 33]:
+                self.enterOuterAlt(localctx, 5)
+                self.state = 274
+                self.commands()
+                pass
+            else:
+                raise NoViableAltException(self)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class SettingsContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def ID(self, i:int=None):
+            if i is None:
+                return self.getTokens(AutolevParser.ID)
+            else:
+                return self.getToken(AutolevParser.ID, i)
+
+        def EXP(self):
+            return self.getToken(AutolevParser.EXP, 0)
+
+        def FLOAT(self):
+            return self.getToken(AutolevParser.FLOAT, 0)
+
+        def INT(self):
+            return self.getToken(AutolevParser.INT, 0)
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_settings
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterSettings" ):
+                listener.enterSettings(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitSettings" ):
+                listener.exitSettings(self)
+
+
+
+
+    def settings(self):
+
+        localctx = AutolevParser.SettingsContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 34, self.RULE_settings)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 277
+            self.match(AutolevParser.ID)
+            self.state = 279
+            self._errHandler.sync(self)
+            la_ = self._interp.adaptivePredict(self._input,30,self._ctx)
+            if la_ == 1:
+                self.state = 278
+                _la = self._input.LA(1)
+                if not(((_la) & ~0x3f) == 0 and ((1 << _la) & 404620279021568) != 0):
+                    self._errHandler.recoverInline(self)
+                else:
+                    self._errHandler.reportMatch(self)
+                    self.consume()
+
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class UnitsContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def UnitSystem(self):
+            return self.getToken(AutolevParser.UnitSystem, 0)
+
+        def ID(self, i:int=None):
+            if i is None:
+                return self.getTokens(AutolevParser.ID)
+            else:
+                return self.getToken(AutolevParser.ID, i)
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_units
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterUnits" ):
+                listener.enterUnits(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitUnits" ):
+                listener.exitUnits(self)
+
+
+
+
+    def units(self):
+
+        localctx = AutolevParser.UnitsContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 36, self.RULE_units)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 281
+            self.match(AutolevParser.UnitSystem)
+            self.state = 282
+            self.match(AutolevParser.ID)
+            self.state = 287
+            self._errHandler.sync(self)
+            _la = self._input.LA(1)
+            while _la==10:
+                self.state = 283
+                self.match(AutolevParser.T__9)
+                self.state = 284
+                self.match(AutolevParser.ID)
+                self.state = 289
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class InputsContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def Input(self):
+            return self.getToken(AutolevParser.Input, 0)
+
+        def inputs2(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(AutolevParser.Inputs2Context)
+            else:
+                return self.getTypedRuleContext(AutolevParser.Inputs2Context,i)
+
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_inputs
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterInputs" ):
+                listener.enterInputs(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitInputs" ):
+                listener.exitInputs(self)
+
+
+
+
+    def inputs(self):
+
+        localctx = AutolevParser.InputsContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 38, self.RULE_inputs)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 290
+            self.match(AutolevParser.Input)
+            self.state = 291
+            self.inputs2()
+            self.state = 296
+            self._errHandler.sync(self)
+            _la = self._input.LA(1)
+            while _la==10:
+                self.state = 292
+                self.match(AutolevParser.T__9)
+                self.state = 293
+                self.inputs2()
+                self.state = 298
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class Id_diffContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def ID(self):
+            return self.getToken(AutolevParser.ID, 0)
+
+        def diff(self):
+            return self.getTypedRuleContext(AutolevParser.DiffContext,0)
+
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_id_diff
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterId_diff" ):
+                listener.enterId_diff(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitId_diff" ):
+                listener.exitId_diff(self)
+
+
+
+
+    def id_diff(self):
+
+        localctx = AutolevParser.Id_diffContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 40, self.RULE_id_diff)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 299
+            self.match(AutolevParser.ID)
+            self.state = 301
+            self._errHandler.sync(self)
+            _la = self._input.LA(1)
+            if _la==11:
+                self.state = 300
+                self.diff()
+
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class Inputs2Context(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def id_diff(self):
+            return self.getTypedRuleContext(AutolevParser.Id_diffContext,0)
+
+
+        def expr(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(AutolevParser.ExprContext)
+            else:
+                return self.getTypedRuleContext(AutolevParser.ExprContext,i)
+
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_inputs2
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterInputs2" ):
+                listener.enterInputs2(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitInputs2" ):
+                listener.exitInputs2(self)
+
+
+
+
+    def inputs2(self):
+
+        localctx = AutolevParser.Inputs2Context(self, self._ctx, self.state)
+        self.enterRule(localctx, 42, self.RULE_inputs2)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 303
+            self.id_diff()
+            self.state = 304
+            self.match(AutolevParser.T__2)
+            self.state = 305
+            self.expr(0)
+            self.state = 307
+            self._errHandler.sync(self)
+            la_ = self._interp.adaptivePredict(self._input,34,self._ctx)
+            if la_ == 1:
+                self.state = 306
+                self.expr(0)
+
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class OutputsContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def Output(self):
+            return self.getToken(AutolevParser.Output, 0)
+
+        def outputs2(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(AutolevParser.Outputs2Context)
+            else:
+                return self.getTypedRuleContext(AutolevParser.Outputs2Context,i)
+
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_outputs
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterOutputs" ):
+                listener.enterOutputs(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitOutputs" ):
+                listener.exitOutputs(self)
+
+
+
+
+    def outputs(self):
+
+        localctx = AutolevParser.OutputsContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 44, self.RULE_outputs)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 309
+            self.match(AutolevParser.Output)
+            self.state = 310
+            self.outputs2()
+            self.state = 315
+            self._errHandler.sync(self)
+            _la = self._input.LA(1)
+            while _la==10:
+                self.state = 311
+                self.match(AutolevParser.T__9)
+                self.state = 312
+                self.outputs2()
+                self.state = 317
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class Outputs2Context(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def expr(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(AutolevParser.ExprContext)
+            else:
+                return self.getTypedRuleContext(AutolevParser.ExprContext,i)
+
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_outputs2
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterOutputs2" ):
+                listener.enterOutputs2(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitOutputs2" ):
+                listener.exitOutputs2(self)
+
+
+
+
+    def outputs2(self):
+
+        localctx = AutolevParser.Outputs2Context(self, self._ctx, self.state)
+        self.enterRule(localctx, 46, self.RULE_outputs2)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 318
+            self.expr(0)
+            self.state = 320
+            self._errHandler.sync(self)
+            la_ = self._interp.adaptivePredict(self._input,36,self._ctx)
+            if la_ == 1:
+                self.state = 319
+                self.expr(0)
+
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class CodegenContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def ID(self, i:int=None):
+            if i is None:
+                return self.getTokens(AutolevParser.ID)
+            else:
+                return self.getToken(AutolevParser.ID, i)
+
+        def functionCall(self):
+            return self.getTypedRuleContext(AutolevParser.FunctionCallContext,0)
+
+
+        def matrixInOutput(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(AutolevParser.MatrixInOutputContext)
+            else:
+                return self.getTypedRuleContext(AutolevParser.MatrixInOutputContext,i)
+
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_codegen
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterCodegen" ):
+                listener.enterCodegen(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitCodegen" ):
+                listener.exitCodegen(self)
+
+
+
+
+    def codegen(self):
+
+        localctx = AutolevParser.CodegenContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 48, self.RULE_codegen)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 322
+            self.match(AutolevParser.ID)
+            self.state = 323
+            self.functionCall()
+            self.state = 335
+            self._errHandler.sync(self)
+            _la = self._input.LA(1)
+            if _la==1:
+                self.state = 324
+                self.match(AutolevParser.T__0)
+                self.state = 325
+                self.matrixInOutput()
+                self.state = 330
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+                while _la==10:
+                    self.state = 326
+                    self.match(AutolevParser.T__9)
+                    self.state = 327
+                    self.matrixInOutput()
+                    self.state = 332
+                    self._errHandler.sync(self)
+                    _la = self._input.LA(1)
+
+                self.state = 333
+                self.match(AutolevParser.T__1)
+
+
+            self.state = 337
+            self.match(AutolevParser.ID)
+            self.state = 338
+            self.match(AutolevParser.T__19)
+            self.state = 339
+            self.match(AutolevParser.ID)
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class CommandsContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def Save(self):
+            return self.getToken(AutolevParser.Save, 0)
+
+        def ID(self, i:int=None):
+            if i is None:
+                return self.getTokens(AutolevParser.ID)
+            else:
+                return self.getToken(AutolevParser.ID, i)
+
+        def Encode(self):
+            return self.getToken(AutolevParser.Encode, 0)
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_commands
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterCommands" ):
+                listener.enterCommands(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitCommands" ):
+                listener.exitCommands(self)
+
+
+
+
+    def commands(self):
+
+        localctx = AutolevParser.CommandsContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 50, self.RULE_commands)
+        self._la = 0 # Token type
+        try:
+            self.state = 354
+            self._errHandler.sync(self)
+            token = self._input.LA(1)
+            if token in [31]:
+                self.enterOuterAlt(localctx, 1)
+                self.state = 341
+                self.match(AutolevParser.Save)
+                self.state = 342
+                self.match(AutolevParser.ID)
+                self.state = 343
+                self.match(AutolevParser.T__19)
+                self.state = 344
+                self.match(AutolevParser.ID)
+                pass
+            elif token in [33]:
+                self.enterOuterAlt(localctx, 2)
+                self.state = 345
+                self.match(AutolevParser.Encode)
+                self.state = 346
+                self.match(AutolevParser.ID)
+                self.state = 351
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+                while _la==10:
+                    self.state = 347
+                    self.match(AutolevParser.T__9)
+                    self.state = 348
+                    self.match(AutolevParser.ID)
+                    self.state = 353
+                    self._errHandler.sync(self)
+                    _la = self._input.LA(1)
+
+                pass
+            else:
+                raise NoViableAltException(self)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class VecContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def ID(self):
+            return self.getToken(AutolevParser.ID, 0)
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_vec
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterVec" ):
+                listener.enterVec(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitVec" ):
+                listener.exitVec(self)
+
+
+
+
+    def vec(self):
+
+        localctx = AutolevParser.VecContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 52, self.RULE_vec)
+        try:
+            self.state = 364
+            self._errHandler.sync(self)
+            token = self._input.LA(1)
+            if token in [48]:
+                self.enterOuterAlt(localctx, 1)
+                self.state = 356
+                self.match(AutolevParser.ID)
+                self.state = 358
+                self._errHandler.sync(self)
+                _alt = 1
+                while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
+                    if _alt == 1:
+                        self.state = 357
+                        self.match(AutolevParser.T__20)
+
+                    else:
+                        raise NoViableAltException(self)
+                    self.state = 360
+                    self._errHandler.sync(self)
+                    _alt = self._interp.adaptivePredict(self._input,41,self._ctx)
+
+                pass
+            elif token in [22]:
+                self.enterOuterAlt(localctx, 2)
+                self.state = 362
+                self.match(AutolevParser.T__21)
+                pass
+            elif token in [23]:
+                self.enterOuterAlt(localctx, 3)
+                self.state = 363
+                self.match(AutolevParser.T__22)
+                pass
+            else:
+                raise NoViableAltException(self)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class ExprContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+
+        def getRuleIndex(self):
+            return AutolevParser.RULE_expr
+
+
+        def copyFrom(self, ctx:ParserRuleContext):
+            super().copyFrom(ctx)
+
+
+    class ParensContext(ExprContext):
+
+        def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
+            super().__init__(parser)
+            self.copyFrom(ctx)
+
+        def expr(self):
+            return self.getTypedRuleContext(AutolevParser.ExprContext,0)
+
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterParens" ):
+                listener.enterParens(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitParens" ):
+                listener.exitParens(self)
+
+
+    class VectorOrDyadicContext(ExprContext):
+
+        def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
+            super().__init__(parser)
+            self.copyFrom(ctx)
+
+        def vec(self):
+            return self.getTypedRuleContext(AutolevParser.VecContext,0)
+
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterVectorOrDyadic" ):
+                listener.enterVectorOrDyadic(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitVectorOrDyadic" ):
+                listener.exitVectorOrDyadic(self)
+
+
+    class ExponentContext(ExprContext):
+
+        def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
+            super().__init__(parser)
+            self.copyFrom(ctx)
+
+        def expr(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(AutolevParser.ExprContext)
+            else:
+                return self.getTypedRuleContext(AutolevParser.ExprContext,i)
+
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterExponent" ):
+                listener.enterExponent(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitExponent" ):
+                listener.exitExponent(self)
+
+
+    class MulDivContext(ExprContext):
+
+        def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
+            super().__init__(parser)
+            self.copyFrom(ctx)
+
+        def expr(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(AutolevParser.ExprContext)
+            else:
+                return self.getTypedRuleContext(AutolevParser.ExprContext,i)
+
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterMulDiv" ):
+                listener.enterMulDiv(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitMulDiv" ):
+                listener.exitMulDiv(self)
+
+
+    class AddSubContext(ExprContext):
+
+        def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
+            super().__init__(parser)
+            self.copyFrom(ctx)
+
+        def expr(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(AutolevParser.ExprContext)
+            else:
+                return self.getTypedRuleContext(AutolevParser.ExprContext,i)
+
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterAddSub" ):
+                listener.enterAddSub(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitAddSub" ):
+                listener.exitAddSub(self)
+
+
+    class FloatContext(ExprContext):
+
+        def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
+            super().__init__(parser)
+            self.copyFrom(ctx)
+
+        def FLOAT(self):
+            return self.getToken(AutolevParser.FLOAT, 0)
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterFloat" ):
+                listener.enterFloat(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitFloat" ):
+                listener.exitFloat(self)
+
+
+    class IntContext(ExprContext):
+
+        def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
+            super().__init__(parser)
+            self.copyFrom(ctx)
+
+        def INT(self):
+            return self.getToken(AutolevParser.INT, 0)
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterInt" ):
+                listener.enterInt(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitInt" ):
+                listener.exitInt(self)
+
+
+    class IdEqualsExprContext(ExprContext):
+
+        def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
+            super().__init__(parser)
+            self.copyFrom(ctx)
+
+        def expr(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(AutolevParser.ExprContext)
+            else:
+                return self.getTypedRuleContext(AutolevParser.ExprContext,i)
+
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterIdEqualsExpr" ):
+                listener.enterIdEqualsExpr(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitIdEqualsExpr" ):
+                listener.exitIdEqualsExpr(self)
+
+
+    class NegativeOneContext(ExprContext):
+
+        def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
+            super().__init__(parser)
+            self.copyFrom(ctx)
+
+        def expr(self):
+            return self.getTypedRuleContext(AutolevParser.ExprContext,0)
+
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterNegativeOne" ):
+                listener.enterNegativeOne(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitNegativeOne" ):
+                listener.exitNegativeOne(self)
+
+
+    class FunctionContext(ExprContext):
+
+        def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
+            super().__init__(parser)
+            self.copyFrom(ctx)
+
+        def functionCall(self):
+            return self.getTypedRuleContext(AutolevParser.FunctionCallContext,0)
+
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterFunction" ):
+                listener.enterFunction(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitFunction" ):
+                listener.exitFunction(self)
+
+
+    class RangessContext(ExprContext):
+
+        def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
+            super().__init__(parser)
+            self.copyFrom(ctx)
+
+        def ranges(self):
+            return self.getTypedRuleContext(AutolevParser.RangesContext,0)
+
+        def ID(self):
+            return self.getToken(AutolevParser.ID, 0)
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterRangess" ):
+                listener.enterRangess(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitRangess" ):
+                listener.exitRangess(self)
+
+
+    class ColonContext(ExprContext):
+
+        def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
+            super().__init__(parser)
+            self.copyFrom(ctx)
+
+        def expr(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(AutolevParser.ExprContext)
+            else:
+                return self.getTypedRuleContext(AutolevParser.ExprContext,i)
+
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterColon" ):
+                listener.enterColon(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitColon" ):
+                listener.exitColon(self)
+
+
+    class IdContext(ExprContext):
+
+        def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
+            super().__init__(parser)
+            self.copyFrom(ctx)
+
+        def ID(self):
+            return self.getToken(AutolevParser.ID, 0)
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterId" ):
+                listener.enterId(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitId" ):
+                listener.exitId(self)
+
+
+    class ExpContext(ExprContext):
+
+        def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
+            super().__init__(parser)
+            self.copyFrom(ctx)
+
+        def EXP(self):
+            return self.getToken(AutolevParser.EXP, 0)
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterExp" ):
+                listener.enterExp(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitExp" ):
+                listener.exitExp(self)
+
+
+    class MatricesContext(ExprContext):
+
+        def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
+            super().__init__(parser)
+            self.copyFrom(ctx)
+
+        def matrix(self):
+            return self.getTypedRuleContext(AutolevParser.MatrixContext,0)
+
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterMatrices" ):
+                listener.enterMatrices(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitMatrices" ):
+                listener.exitMatrices(self)
+
+
+    class IndexingContext(ExprContext):
+
+        def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
+            super().__init__(parser)
+            self.copyFrom(ctx)
+
+        def ID(self):
+            return self.getToken(AutolevParser.ID, 0)
+        def expr(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(AutolevParser.ExprContext)
+            else:
+                return self.getTypedRuleContext(AutolevParser.ExprContext,i)
+
+
+        def enterRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "enterIndexing" ):
+                listener.enterIndexing(self)
+
+        def exitRule(self, listener:ParseTreeListener):
+            if hasattr( listener, "exitIndexing" ):
+                listener.exitIndexing(self)
+
+
+
+    def expr(self, _p:int=0):
+        _parentctx = self._ctx
+        _parentState = self.state
+        localctx = AutolevParser.ExprContext(self, self._ctx, _parentState)
+        _prevctx = localctx
+        _startState = 54
+        self.enterRecursionRule(localctx, 54, self.RULE_expr, _p)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 408
+            self._errHandler.sync(self)
+            la_ = self._interp.adaptivePredict(self._input,47,self._ctx)
+            if la_ == 1:
+                localctx = AutolevParser.ExpContext(self, localctx)
+                self._ctx = localctx
+                _prevctx = localctx
+
+                self.state = 367
+                self.match(AutolevParser.EXP)
+                pass
+
+            elif la_ == 2:
+                localctx = AutolevParser.NegativeOneContext(self, localctx)
+                self._ctx = localctx
+                _prevctx = localctx
+                self.state = 368
+                self.match(AutolevParser.T__17)
+                self.state = 369
+                self.expr(12)
+                pass
+
+            elif la_ == 3:
+                localctx = AutolevParser.FloatContext(self, localctx)
+                self._ctx = localctx
+                _prevctx = localctx
+                self.state = 370
+                self.match(AutolevParser.FLOAT)
+                pass
+
+            elif la_ == 4:
+                localctx = AutolevParser.IntContext(self, localctx)
+                self._ctx = localctx
+                _prevctx = localctx
+                self.state = 371
+                self.match(AutolevParser.INT)
+                pass
+
+            elif la_ == 5:
+                localctx = AutolevParser.IdContext(self, localctx)
+                self._ctx = localctx
+                _prevctx = localctx
+                self.state = 372
+                self.match(AutolevParser.ID)
+                self.state = 376
+                self._errHandler.sync(self)
+                _alt = self._interp.adaptivePredict(self._input,43,self._ctx)
+                while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
+                    if _alt==1:
+                        self.state = 373
+                        self.match(AutolevParser.T__10)
+                    self.state = 378
+                    self._errHandler.sync(self)
+                    _alt = self._interp.adaptivePredict(self._input,43,self._ctx)
+
+                pass
+
+            elif la_ == 6:
+                localctx = AutolevParser.VectorOrDyadicContext(self, localctx)
+                self._ctx = localctx
+                _prevctx = localctx
+                self.state = 379
+                self.vec()
+                pass
+
+            elif la_ == 7:
+                localctx = AutolevParser.IndexingContext(self, localctx)
+                self._ctx = localctx
+                _prevctx = localctx
+                self.state = 380
+                self.match(AutolevParser.ID)
+                self.state = 381
+                self.match(AutolevParser.T__0)
+                self.state = 382
+                self.expr(0)
+                self.state = 387
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+                while _la==10:
+                    self.state = 383
+                    self.match(AutolevParser.T__9)
+                    self.state = 384
+                    self.expr(0)
+                    self.state = 389
+                    self._errHandler.sync(self)
+                    _la = self._input.LA(1)
+
+                self.state = 390
+                self.match(AutolevParser.T__1)
+                pass
+
+            elif la_ == 8:
+                localctx = AutolevParser.FunctionContext(self, localctx)
+                self._ctx = localctx
+                _prevctx = localctx
+                self.state = 392
+                self.functionCall()
+                pass
+
+            elif la_ == 9:
+                localctx = AutolevParser.MatricesContext(self, localctx)
+                self._ctx = localctx
+                _prevctx = localctx
+                self.state = 393
+                self.matrix()
+                pass
+
+            elif la_ == 10:
+                localctx = AutolevParser.ParensContext(self, localctx)
+                self._ctx = localctx
+                _prevctx = localctx
+                self.state = 394
+                self.match(AutolevParser.T__11)
+                self.state = 395
+                self.expr(0)
+                self.state = 396
+                self.match(AutolevParser.T__12)
+                pass
+
+            elif la_ == 11:
+                localctx = AutolevParser.RangessContext(self, localctx)
+                self._ctx = localctx
+                _prevctx = localctx
+                self.state = 399
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+                if _la==48:
+                    self.state = 398
+                    self.match(AutolevParser.ID)
+
+
+                self.state = 401
+                self.ranges()
+                self.state = 405
+                self._errHandler.sync(self)
+                _alt = self._interp.adaptivePredict(self._input,46,self._ctx)
+                while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
+                    if _alt==1:
+                        self.state = 402
+                        self.match(AutolevParser.T__10)
+                    self.state = 407
+                    self._errHandler.sync(self)
+                    _alt = self._interp.adaptivePredict(self._input,46,self._ctx)
+
+                pass
+
+
+            self._ctx.stop = self._input.LT(-1)
+            self.state = 427
+            self._errHandler.sync(self)
+            _alt = self._interp.adaptivePredict(self._input,49,self._ctx)
+            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
+                if _alt==1:
+                    if self._parseListeners is not None:
+                        self.triggerExitRuleEvent()
+                    _prevctx = localctx
+                    self.state = 425
+                    self._errHandler.sync(self)
+                    la_ = self._interp.adaptivePredict(self._input,48,self._ctx)
+                    if la_ == 1:
+                        localctx = AutolevParser.ExponentContext(self, AutolevParser.ExprContext(self, _parentctx, _parentState))
+                        self.pushNewRecursionContext(localctx, _startState, self.RULE_expr)
+                        self.state = 410
+                        if not self.precpred(self._ctx, 16):
+                            from antlr4.error.Errors import FailedPredicateException
+                            raise FailedPredicateException(self, "self.precpred(self._ctx, 16)")
+                        self.state = 411
+                        self.match(AutolevParser.T__23)
+                        self.state = 412
+                        self.expr(17)
+                        pass
+
+                    elif la_ == 2:
+                        localctx = AutolevParser.MulDivContext(self, AutolevParser.ExprContext(self, _parentctx, _parentState))
+                        self.pushNewRecursionContext(localctx, _startState, self.RULE_expr)
+                        self.state = 413
+                        if not self.precpred(self._ctx, 15):
+                            from antlr4.error.Errors import FailedPredicateException
+                            raise FailedPredicateException(self, "self.precpred(self._ctx, 15)")
+                        self.state = 414
+                        _la = self._input.LA(1)
+                        if not(_la==25 or _la==26):
+                            self._errHandler.recoverInline(self)
+                        else:
+                            self._errHandler.reportMatch(self)
+                            self.consume()
+                        self.state = 415
+                        self.expr(16)
+                        pass
+
+                    elif la_ == 3:
+                        localctx = AutolevParser.AddSubContext(self, AutolevParser.ExprContext(self, _parentctx, _parentState))
+                        self.pushNewRecursionContext(localctx, _startState, self.RULE_expr)
+                        self.state = 416
+                        if not self.precpred(self._ctx, 14):
+                            from antlr4.error.Errors import FailedPredicateException
+                            raise FailedPredicateException(self, "self.precpred(self._ctx, 14)")
+                        self.state = 417
+                        _la = self._input.LA(1)
+                        if not(_la==17 or _la==18):
+                            self._errHandler.recoverInline(self)
+                        else:
+                            self._errHandler.reportMatch(self)
+                            self.consume()
+                        self.state = 418
+                        self.expr(15)
+                        pass
+
+                    elif la_ == 4:
+                        localctx = AutolevParser.IdEqualsExprContext(self, AutolevParser.ExprContext(self, _parentctx, _parentState))
+                        self.pushNewRecursionContext(localctx, _startState, self.RULE_expr)
+                        self.state = 419
+                        if not self.precpred(self._ctx, 3):
+                            from antlr4.error.Errors import FailedPredicateException
+                            raise FailedPredicateException(self, "self.precpred(self._ctx, 3)")
+                        self.state = 420
+                        self.match(AutolevParser.T__2)
+                        self.state = 421
+                        self.expr(4)
+                        pass
+
+                    elif la_ == 5:
+                        localctx = AutolevParser.ColonContext(self, AutolevParser.ExprContext(self, _parentctx, _parentState))
+                        self.pushNewRecursionContext(localctx, _startState, self.RULE_expr)
+                        self.state = 422
+                        if not self.precpred(self._ctx, 2):
+                            from antlr4.error.Errors import FailedPredicateException
+                            raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
+                        self.state = 423
+                        self.match(AutolevParser.T__15)
+                        self.state = 424
+                        self.expr(3)
+                        pass
+
+
+                self.state = 429
+                self._errHandler.sync(self)
+                _alt = self._interp.adaptivePredict(self._input,49,self._ctx)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.unrollRecursionContexts(_parentctx)
+        return localctx
+
+
+
+    def sempred(self, localctx:RuleContext, ruleIndex:int, predIndex:int):
+        if self._predicates == None:
+            self._predicates = dict()
+        self._predicates[27] = self.expr_sempred
+        pred = self._predicates.get(ruleIndex, None)
+        if pred is None:
+            raise Exception("No predicate with index:" + str(ruleIndex))
+        else:
+            return pred(localctx, predIndex)
+
+    def expr_sempred(self, localctx:ExprContext, predIndex:int):
+            if predIndex == 0:
+                return self.precpred(self._ctx, 16)
+
+
+            if predIndex == 1:
+                return self.precpred(self._ctx, 15)
+
+
+            if predIndex == 2:
+                return self.precpred(self._ctx, 14)
+
+
+            if predIndex == 3:
+                return self.precpred(self._ctx, 3)
+
+
+            if predIndex == 4:
+                return self.precpred(self._ctx, 2)
+
+
+
+
+
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_build_autolev_antlr.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_build_autolev_antlr.py
new file mode 100644
index 0000000000000000000000000000000000000000..8314b2f546c0a18a8e281768b60d66556c852e3b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_build_autolev_antlr.py
@@ -0,0 +1,86 @@
+import os
+import subprocess
+import glob
+
+from sympy.utilities.misc import debug
+
+here = os.path.dirname(__file__)
+grammar_file = os.path.abspath(os.path.join(here, "Autolev.g4"))
+dir_autolev_antlr = os.path.join(here, "_antlr")
+
+header = '''\
+# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
+#
+# Generated with antlr4
+#    antlr4 is licensed under the BSD-3-Clause License
+#    https://github.com/antlr/antlr4/blob/master/LICENSE.txt
+'''
+
+
+def check_antlr_version():
+    debug("Checking antlr4 version...")
+
+    try:
+        debug(subprocess.check_output(["antlr4"])
+              .decode('utf-8').split("\n")[0])
+        return True
+    except (subprocess.CalledProcessError, FileNotFoundError):
+        debug("The 'antlr4' command line tool is not installed, "
+              "or not on your PATH.\n"
+              "> Please refer to the README.md file for more information.")
+        return False
+
+
+def build_parser(output_dir=dir_autolev_antlr):
+    check_antlr_version()
+
+    debug("Updating ANTLR-generated code in {}".format(output_dir))
+
+    if not os.path.exists(output_dir):
+        os.makedirs(output_dir)
+
+    with open(os.path.join(output_dir, "__init__.py"), "w+") as fp:
+        fp.write(header)
+
+    args = [
+        "antlr4",
+        grammar_file,
+        "-o", output_dir,
+        "-no-visitor",
+    ]
+
+    debug("Running code generation...\n\t$ {}".format(" ".join(args)))
+    subprocess.check_output(args, cwd=output_dir)
+
+    debug("Applying headers, removing unnecessary files and renaming...")
+    # Handle case insensitive file systems. If the files are already
+    # generated, they will be written to autolev* but Autolev*.* won't match them.
+    for path in (glob.glob(os.path.join(output_dir, "Autolev*.*")) or
+        glob.glob(os.path.join(output_dir, "autolev*.*"))):
+
+        # Remove files ending in .interp or .tokens as they are not needed.
+        if not path.endswith(".py"):
+            os.unlink(path)
+            continue
+
+        new_path = os.path.join(output_dir, os.path.basename(path).lower())
+        with open(path, 'r') as f:
+            lines = [line.rstrip().replace('AutolevParser import', 'autolevparser import') +'\n'
+                     for line in f]
+
+        os.unlink(path)
+
+        with open(new_path, "w") as out_file:
+            offset = 0
+            while lines[offset].startswith('#'):
+                offset += 1
+            out_file.write(header)
+            out_file.writelines(lines[offset:])
+
+        debug("\t{}".format(new_path))
+
+    return True
+
+
+if __name__ == "__main__":
+    build_parser()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_listener_autolev_antlr.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_listener_autolev_antlr.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ca2f8af88de18036b90788fd29d02707f098213
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_listener_autolev_antlr.py
@@ -0,0 +1,2083 @@
+import collections
+import warnings
+
+from sympy.external import import_module
+
+autolevparser = import_module('sympy.parsing.autolev._antlr.autolevparser',
+                              import_kwargs={'fromlist': ['AutolevParser']})
+autolevlexer = import_module('sympy.parsing.autolev._antlr.autolevlexer',
+                             import_kwargs={'fromlist': ['AutolevLexer']})
+autolevlistener = import_module('sympy.parsing.autolev._antlr.autolevlistener',
+                                import_kwargs={'fromlist': ['AutolevListener']})
+
+AutolevParser = getattr(autolevparser, 'AutolevParser', None)
+AutolevLexer = getattr(autolevlexer, 'AutolevLexer', None)
+AutolevListener = getattr(autolevlistener, 'AutolevListener', None)
+
+
+def strfunc(z):
+    if z == 0:
+        return ""
+    elif z == 1:
+        return "_d"
+    else:
+        return "_" + "d" * z
+
+def declare_phy_entities(self, ctx, phy_type, i, j=None):
+    if phy_type in ("frame", "newtonian"):
+        declare_frames(self, ctx, i, j)
+    elif phy_type == "particle":
+        declare_particles(self, ctx, i, j)
+    elif phy_type == "point":
+        declare_points(self, ctx, i, j)
+    elif phy_type == "bodies":
+        declare_bodies(self, ctx, i, j)
+
+def declare_frames(self, ctx, i, j=None):
+    if "{" in ctx.getText():
+        if j:
+            name1 = ctx.ID().getText().lower() + str(i) + str(j)
+        else:
+            name1 = ctx.ID().getText().lower() + str(i)
+    else:
+        name1 = ctx.ID().getText().lower()
+    name2 = "frame_" + name1
+    if self.getValue(ctx.parentCtx.varType()) == "newtonian":
+        self.newtonian = name2
+
+    self.symbol_table2.update({name1: name2})
+
+    self.symbol_table.update({name1 + "1>": name2 + ".x"})
+    self.symbol_table.update({name1 + "2>": name2 + ".y"})
+    self.symbol_table.update({name1 + "3>": name2 + ".z"})
+
+    self.type2.update({name1: "frame"})
+    self.write(name2 + " = " + "_me.ReferenceFrame('" + name1 + "')\n")
+
+def declare_points(self, ctx, i, j=None):
+    if "{" in ctx.getText():
+        if j:
+            name1 = ctx.ID().getText().lower() + str(i) + str(j)
+        else:
+            name1 = ctx.ID().getText().lower() + str(i)
+    else:
+        name1 = ctx.ID().getText().lower()
+
+    name2 = "point_" + name1
+
+    self.symbol_table2.update({name1: name2})
+    self.type2.update({name1: "point"})
+    self.write(name2 + " = " + "_me.Point('" + name1 + "')\n")
+
+def declare_particles(self, ctx, i, j=None):
+    if "{" in ctx.getText():
+        if j:
+            name1 = ctx.ID().getText().lower() + str(i) + str(j)
+        else:
+            name1 = ctx.ID().getText().lower() + str(i)
+    else:
+        name1 = ctx.ID().getText().lower()
+
+    name2 = "particle_" + name1
+
+    self.symbol_table2.update({name1: name2})
+    self.type2.update({name1: "particle"})
+    self.bodies.update({name1: name2})
+    self.write(name2 + " = " + "_me.Particle('" + name1 + "', " + "_me.Point('" +
+                name1 + "_pt" + "'), " + "_sm.Symbol('m'))\n")
+
+def declare_bodies(self, ctx, i, j=None):
+    if "{" in ctx.getText():
+        if j:
+            name1 = ctx.ID().getText().lower() + str(i) + str(j)
+        else:
+            name1 = ctx.ID().getText().lower() + str(i)
+    else:
+        name1 = ctx.ID().getText().lower()
+
+    name2 = "body_" + name1
+    self.bodies.update({name1: name2})
+    masscenter = name2 + "_cm"
+    refFrame = name2 + "_f"
+
+    self.symbol_table2.update({name1: name2})
+    self.symbol_table2.update({name1 + "o": masscenter})
+    self.symbol_table.update({name1 + "1>": refFrame+".x"})
+    self.symbol_table.update({name1 + "2>": refFrame+".y"})
+    self.symbol_table.update({name1 + "3>": refFrame+".z"})
+
+    self.type2.update({name1: "bodies"})
+    self.type2.update({name1+"o": "point"})
+
+    self.write(masscenter + " = " + "_me.Point('" + name1 + "_cm" + "')\n")
+    if self.newtonian:
+        self.write(masscenter + ".set_vel(" + self.newtonian + ", " + "0)\n")
+    self.write(refFrame + " = " + "_me.ReferenceFrame('" + name1 + "_f" + "')\n")
+    # We set a dummy mass and inertia here.
+    # They will be reset using the setters later in the code anyway.
+    self.write(name2 + " = " + "_me.RigidBody('" + name1 + "', " + masscenter + ", " +
+                refFrame + ", " + "_sm.symbols('m'), (_me.outer(" + refFrame +
+                ".x," + refFrame + ".x)," + masscenter + "))\n")
+
+def inertia_func(self, v1, v2, l, frame):
+
+    if self.type2[v1] == "particle":
+        l.append("_me.inertia_of_point_mass(" + self.bodies[v1] + ".mass, " + self.bodies[v1] +
+                 ".point.pos_from(" + self.symbol_table2[v2] + "), " + frame + ")")
+
+    elif self.type2[v1] == "bodies":
+        # Inertia has been defined about center of mass.
+        if self.inertia_point[v1] == v1 + "o":
+            # Asking point is cm as well
+            if v2 == self.inertia_point[v1]:
+                l.append(self.symbol_table2[v1] + ".inertia[0]")
+
+            # Asking point is not cm
+            else:
+                l.append(self.bodies[v1] + ".inertia[0]" + " + " +
+                         "_me.inertia_of_point_mass(" + self.bodies[v1] +
+                         ".mass, " + self.bodies[v1] + ".masscenter" +
+                         ".pos_from(" + self.symbol_table2[v2] +
+                         "), " + frame + ")")
+
+        # Inertia has been defined about another point
+        else:
+            # Asking point is the defined point
+            if v2 == self.inertia_point[v1]:
+                l.append(self.symbol_table2[v1] + ".inertia[0]")
+            # Asking point is cm
+            elif v2 == v1 + "o":
+                l.append(self.bodies[v1] + ".inertia[0]" + " - " +
+                         "_me.inertia_of_point_mass(" + self.bodies[v1] +
+                         ".mass, " + self.bodies[v1] + ".masscenter" +
+                         ".pos_from(" + self.symbol_table2[self.inertia_point[v1]] +
+                         "), " + frame + ")")
+            # Asking point is some other point
+            else:
+                l.append(self.bodies[v1] + ".inertia[0]" + " - " +
+                         "_me.inertia_of_point_mass(" + self.bodies[v1] +
+                         ".mass, " + self.bodies[v1] + ".masscenter" +
+                         ".pos_from(" + self.symbol_table2[self.inertia_point[v1]] +
+                         "), " + frame + ")" + " + " +
+                         "_me.inertia_of_point_mass(" + self.bodies[v1] +
+                         ".mass, " + self.bodies[v1] + ".masscenter" +
+                         ".pos_from(" + self.symbol_table2[v2] +
+                         "), " + frame + ")")
+
+
+def processConstants(self, ctx):
+    # Process constant declarations of the type: Constants F = 3, g = 9.81
+    name = ctx.ID().getText().lower()
+    if "=" in ctx.getText():
+        self.symbol_table.update({name: name})
+        # self.inputs.update({self.symbol_table[name]: self.getValue(ctx.getChild(2))})
+        self.write(self.symbol_table[name] + " = " + "_sm.S(" + self.getValue(ctx.getChild(2)) + ")\n")
+        self.type.update({name: "constants"})
+        return
+
+    # Constants declarations of the type: Constants A, B
+    else:
+        if "{" not in ctx.getText():
+            self.symbol_table[name] = name
+            self.type[name] = "constants"
+
+    # Process constant declarations of the type: Constants C+, D-
+    if ctx.getChildCount() == 2:
+        # This is set for declaring nonpositive=True and nonnegative=True
+        if ctx.getChild(1).getText() == "+":
+            self.sign[name] = "+"
+        elif ctx.getChild(1).getText() == "-":
+            self.sign[name] = "-"
+    else:
+        if "{" not in ctx.getText():
+            self.sign[name] = "o"
+
+    # Process constant declarations of the type: Constants K{4}, a{1:2, 1:2}, b{1:2}
+    if "{" in ctx.getText():
+        if ":" in ctx.getText():
+            num1 = int(ctx.INT(0).getText())
+            num2 = int(ctx.INT(1).getText()) + 1
+        else:
+            num1 = 1
+            num2 = int(ctx.INT(0).getText()) + 1
+
+        if ":" in ctx.getText():
+            if "," in ctx.getText():
+                num3 = int(ctx.INT(2).getText())
+                num4 = int(ctx.INT(3).getText()) + 1
+                for i in range(num1, num2):
+                    for j in range(num3, num4):
+                        self.symbol_table[name + str(i) + str(j)] = name + str(i) + str(j)
+                        self.type[name + str(i) + str(j)] = "constants"
+                        self.var_list.append(name + str(i) + str(j))
+                        self.sign[name + str(i) + str(j)] = "o"
+            else:
+                for i in range(num1, num2):
+                    self.symbol_table[name + str(i)] = name + str(i)
+                    self.type[name + str(i)] = "constants"
+                    self.var_list.append(name + str(i))
+                    self.sign[name + str(i)] = "o"
+
+        elif "," in ctx.getText():
+            for i in range(1, int(ctx.INT(0).getText()) + 1):
+                for j in range(1, int(ctx.INT(1).getText()) + 1):
+                    self.symbol_table[name] = name + str(i) + str(j)
+                    self.type[name + str(i) + str(j)] = "constants"
+                    self.var_list.append(name + str(i) + str(j))
+                    self.sign[name + str(i) + str(j)] = "o"
+
+        else:
+            for i in range(num1, num2):
+                self.symbol_table[name + str(i)] = name + str(i)
+                self.type[name + str(i)] = "constants"
+                self.var_list.append(name + str(i))
+                self.sign[name + str(i)] = "o"
+
+    if "{" not in ctx.getText():
+        self.var_list.append(name)
+
+
+def writeConstants(self, ctx):
+    l1 = list(filter(lambda x: self.sign[x] == "o", self.var_list))
+    l2 = list(filter(lambda x: self.sign[x] == "+", self.var_list))
+    l3 = list(filter(lambda x: self.sign[x] == "-", self.var_list))
+    try:
+        if self.settings["complex"] == "on":
+            real = ", real=True"
+        elif self.settings["complex"] == "off":
+            real = ""
+    except Exception:
+        real = ", real=True"
+
+    if l1:
+        a = ", ".join(l1) + " = " + "_sm.symbols(" + "'" +\
+            " ".join(l1) + "'" + real + ")\n"
+        self.write(a)
+    if l2:
+        a = ", ".join(l2) + " = " + "_sm.symbols(" + "'" +\
+            " ".join(l2) + "'" + real + ", nonnegative=True)\n"
+        self.write(a)
+    if l3:
+        a = ", ".join(l3) + " = " + "_sm.symbols(" + "'" + \
+            " ".join(l3) + "'" + real + ", nonpositive=True)\n"
+        self.write(a)
+    self.var_list = []
+
+
+def processVariables(self, ctx):
+    # Specified F = x*N1> + y*N2>
+    name = ctx.ID().getText().lower()
+    if "=" in ctx.getText():
+        text = name + "'"*(ctx.getChildCount()-3)
+        self.write(text + " = " + self.getValue(ctx.expr()) + "\n")
+        return
+
+    # Process variables of the type: Variables qA, qB
+    if ctx.getChildCount() == 1:
+        self.symbol_table[name] = name
+        if self.getValue(ctx.parentCtx.getChild(0)) in ("variable", "specified", "motionvariable", "motionvariable'"):
+            self.type.update({name: self.getValue(ctx.parentCtx.getChild(0))})
+
+        self.var_list.append(name)
+        self.sign[name] = 0
+
+    # Process variables of the type: Variables x', y''
+    elif "'" in ctx.getText() and "{" not in ctx.getText():
+        if ctx.getText().count("'") > self.maxDegree:
+            self.maxDegree = ctx.getText().count("'")
+        for i in range(ctx.getChildCount()):
+            self.sign[name + strfunc(i)] = i
+            self.symbol_table[name + "'"*i] = name + strfunc(i)
+            if self.getValue(ctx.parentCtx.getChild(0)) in ("variable", "specified", "motionvariable", "motionvariable'"):
+                self.type.update({name + "'"*i: self.getValue(ctx.parentCtx.getChild(0))})
+            self.var_list.append(name + strfunc(i))
+
+    elif "{" in ctx.getText():
+        # Process variables of the type: Variables x{3}, y{2}
+
+        if "'" in ctx.getText():
+            dash_count = ctx.getText().count("'")
+            if dash_count > self.maxDegree:
+                self.maxDegree = dash_count
+
+        if ":" in ctx.getText():
+            # Variables C{1:2, 1:2}
+            if "," in ctx.getText():
+                num1 = int(ctx.INT(0).getText())
+                num2 = int(ctx.INT(1).getText()) + 1
+                num3 = int(ctx.INT(2).getText())
+                num4 = int(ctx.INT(3).getText()) + 1
+            # Variables C{1:2}
+            else:
+                num1 = int(ctx.INT(0).getText())
+                num2 = int(ctx.INT(1).getText()) + 1
+
+        # Variables C{1,3}
+        elif "," in ctx.getText():
+            num1 = 1
+            num2 = int(ctx.INT(0).getText()) + 1
+            num3 = 1
+            num4 = int(ctx.INT(1).getText()) + 1
+        else:
+            num1 = 1
+            num2 = int(ctx.INT(0).getText()) + 1
+
+        for i in range(num1, num2):
+            try:
+                for j in range(num3, num4):
+                    try:
+                        for z in range(dash_count+1):
+                            self.symbol_table.update({name + str(i) + str(j) + "'"*z: name + str(i) + str(j) + strfunc(z)})
+                            if self.getValue(ctx.parentCtx.getChild(0)) in ("variable", "specified", "motionvariable", "motionvariable'"):
+                                self.type.update({name + str(i) + str(j) +  "'"*z: self.getValue(ctx.parentCtx.getChild(0))})
+                            self.var_list.append(name + str(i) + str(j) + strfunc(z))
+                            self.sign.update({name + str(i) + str(j) + strfunc(z): z})
+                            if dash_count > self.maxDegree:
+                                self.maxDegree = dash_count
+                    except Exception:
+                        self.symbol_table.update({name + str(i) + str(j): name + str(i) + str(j)})
+                        if self.getValue(ctx.parentCtx.getChild(0)) in ("variable", "specified", "motionvariable", "motionvariable'"):
+                            self.type.update({name + str(i) + str(j): self.getValue(ctx.parentCtx.getChild(0))})
+                        self.var_list.append(name + str(i) + str(j))
+                        self.sign.update({name + str(i) + str(j): 0})
+            except Exception:
+                try:
+                    for z in range(dash_count+1):
+                        self.symbol_table.update({name + str(i) + "'"*z: name + str(i) + strfunc(z)})
+                        if self.getValue(ctx.parentCtx.getChild(0)) in ("variable", "specified", "motionvariable", "motionvariable'"):
+                            self.type.update({name + str(i) +  "'"*z: self.getValue(ctx.parentCtx.getChild(0))})
+                        self.var_list.append(name + str(i) + strfunc(z))
+                        self.sign.update({name + str(i) + strfunc(z): z})
+                        if dash_count > self.maxDegree:
+                            self.maxDegree = dash_count
+                except Exception:
+                    self.symbol_table.update({name + str(i): name + str(i)})
+                    if self.getValue(ctx.parentCtx.getChild(0)) in ("variable", "specified", "motionvariable", "motionvariable'"):
+                        self.type.update({name + str(i): self.getValue(ctx.parentCtx.getChild(0))})
+                    self.var_list.append(name + str(i))
+                    self.sign.update({name + str(i): 0})
+
+def writeVariables(self, ctx):
+    #print(self.sign)
+    #print(self.symbol_table)
+    if self.var_list:
+        for i in range(self.maxDegree+1):
+            if i == 0:
+                j = ""
+                t = ""
+            else:
+                j = str(i)
+                t = ", "
+            l = []
+            for k in list(filter(lambda x: self.sign[x] == i, self.var_list)):
+                if i == 0:
+                    l.append(k)
+                if i == 1:
+                    l.append(k[:-1])
+                if i > 1:
+                    l.append(k[:-2])
+            a = ", ".join(list(filter(lambda x: self.sign[x] == i, self.var_list))) + " = " +\
+                "_me.dynamicsymbols(" + "'" + " ".join(l) + "'" + t + j + ")\n"
+            l = []
+            self.write(a)
+        self.maxDegree = 0
+    self.var_list = []
+
+def processImaginary(self, ctx):
+    name = ctx.ID().getText().lower()
+    self.symbol_table[name] = name
+    self.type[name] = "imaginary"
+    self.var_list.append(name)
+
+
+def writeImaginary(self, ctx):
+    a = ", ".join(self.var_list) + " = " + "_sm.symbols(" + "'" + \
+        " ".join(self.var_list) + "')\n"
+    b = ", ".join(self.var_list) + " = " + "_sm.I\n"
+    self.write(a)
+    self.write(b)
+    self.var_list = []
+
+if AutolevListener:
+    class MyListener(AutolevListener):  # type: ignore
+        def __init__(self, include_numeric=False):
+            # Stores data in tree nodes(tree annotation). Especially useful for expr reconstruction.
+            self.tree_property = {}
+
+            # Stores the declared variables, constants etc as they are declared in Autolev and SymPy
+            # {"": ""}.
+            self.symbol_table = collections.OrderedDict()
+
+            # Similar to symbol_table. Used for storing Physical entities like Frames, Points,
+            # Particles, Bodies etc
+            self.symbol_table2 = collections.OrderedDict()
+
+            # Used to store nonpositive, nonnegative etc for constants and number of "'"s (order of diff)
+            # in variables.
+            self.sign = {}
+
+            # Simple list used as a store to pass around variables between the 'process' and 'write'
+            # methods.
+            self.var_list = []
+
+            # Stores the type of a declared variable (constants, variables, specifieds etc)
+            self.type = collections.OrderedDict()
+
+            # Similar to self.type. Used for storing the type of Physical entities like Frames, Points,
+            # Particles, Bodies etc
+            self.type2 = collections.OrderedDict()
+
+            # These lists are used to distinguish matrix, numeric and vector expressions.
+            self.matrix_expr = []
+            self.numeric_expr = []
+            self.vector_expr = []
+            self.fr_expr = []
+
+            self.output_code = []
+
+            # Stores the variables and their rhs for substituting upon the Autolev command EXPLICIT.
+            self.explicit = collections.OrderedDict()
+
+            # Write code to import common dependencies.
+            self.output_code.append("import sympy.physics.mechanics as _me\n")
+            self.output_code.append("import sympy as _sm\n")
+            self.output_code.append("import math as m\n")
+            self.output_code.append("import numpy as _np\n")
+            self.output_code.append("\n")
+
+            # Just a store for the max degree variable in a line.
+            self.maxDegree = 0
+
+            # Stores the input parameters which are then used for codegen and numerical analysis.
+            self.inputs = collections.OrderedDict()
+            # Stores the variables which appear in Output Autolev commands.
+            self.outputs = []
+            # Stores the settings specified by the user. Ex: Complex on/off, Degrees on/off
+            self.settings = {}
+            # Boolean which changes the behaviour of some expression reconstruction
+            # when parsing Input Autolev commands.
+            self.in_inputs = False
+            self.in_outputs = False
+
+            # Stores for the physical entities.
+            self.newtonian = None
+            self.bodies = collections.OrderedDict()
+            self.constants = []
+            self.forces = collections.OrderedDict()
+            self.q_ind = []
+            self.q_dep = []
+            self.u_ind = []
+            self.u_dep = []
+            self.kd_eqs = []
+            self.dependent_variables = []
+            self.kd_equivalents = collections.OrderedDict()
+            self.kd_equivalents2 = collections.OrderedDict()
+            self.kd_eqs_supplied = None
+            self.kane_type = "no_args"
+            self.inertia_point = collections.OrderedDict()
+            self.kane_parsed = False
+            self.t = False
+
+            # PyDy ode code will be included only if this flag is set to True.
+            self.include_numeric = include_numeric
+
+        def write(self, string):
+            self.output_code.append(string)
+
+        def getValue(self, node):
+            return self.tree_property[node]
+
+        def setValue(self, node, value):
+            self.tree_property[node] = value
+
+        def getSymbolTable(self):
+            return self.symbol_table
+
+        def getType(self):
+            return self.type
+
+        def exitVarDecl(self, ctx):
+            # This event method handles variable declarations. The parse tree node varDecl contains
+            # one or more varDecl2 nodes. Eg varDecl for 'Constants a{1:2, 1:2}, b{1:2}' has two varDecl2
+            # nodes(one for a{1:2, 1:2} and one for b{1:2}).
+
+            # Variable declarations are processed and stored in the event method exitVarDecl2.
+            # This stored information is used to write the final SymPy output code in the exitVarDecl event method.
+
+            # determine the type of declaration
+            if self.getValue(ctx.varType()) == "constant":
+                writeConstants(self, ctx)
+            elif self.getValue(ctx.varType()) in\
+            ("variable", "motionvariable", "motionvariable'", "specified"):
+                writeVariables(self, ctx)
+            elif self.getValue(ctx.varType()) == "imaginary":
+                writeImaginary(self, ctx)
+
+        def exitVarType(self, ctx):
+            # Annotate the varType tree node with the type of the variable declaration.
+            name = ctx.getChild(0).getText().lower()
+            if name[-1] == "s" and name != "bodies":
+                self.setValue(ctx, name[:-1])
+            else:
+                self.setValue(ctx, name)
+
+        def exitVarDecl2(self, ctx):
+            # Variable declarations are processed and stored in the event method exitVarDecl2.
+            # This stored information is used to write the final SymPy output code in the exitVarDecl event method.
+            # This is the case for constants, variables, specifieds etc.
+
+            # This isn't the case for all types of declarations though. For instance
+            # Frames A, B, C, N cannot be defined on one line in SymPy. So we do not append A, B, C, N
+            # to a var_list or use exitVarDecl. exitVarDecl2 directly writes out to the file.
+
+            # determine the type of declaration
+            if self.getValue(ctx.parentCtx.varType()) == "constant":
+                processConstants(self, ctx)
+
+            elif self.getValue(ctx.parentCtx.varType()) in \
+            ("variable", "motionvariable", "motionvariable'", "specified"):
+                processVariables(self, ctx)
+
+            elif self.getValue(ctx.parentCtx.varType()) == "imaginary":
+                processImaginary(self, ctx)
+
+            elif self.getValue(ctx.parentCtx.varType()) in ("frame", "newtonian", "point", "particle", "bodies"):
+                if "{" in ctx.getText():
+                    if ":" in ctx.getText() and "," not in ctx.getText():
+                        num1 = int(ctx.INT(0).getText())
+                        num2 = int(ctx.INT(1).getText()) + 1
+                    elif ":" not in ctx.getText() and "," in ctx.getText():
+                        num1 = 1
+                        num2 = int(ctx.INT(0).getText()) + 1
+                        num3 = 1
+                        num4 = int(ctx.INT(1).getText()) + 1
+                    elif ":" in ctx.getText() and "," in ctx.getText():
+                        num1 = int(ctx.INT(0).getText())
+                        num2 = int(ctx.INT(1).getText()) + 1
+                        num3 = int(ctx.INT(2).getText())
+                        num4 = int(ctx.INT(3).getText()) + 1
+                    else:
+                        num1 = 1
+                        num2 = int(ctx.INT(0).getText()) + 1
+                else:
+                    num1 = 1
+                    num2 = 2
+                for i in range(num1, num2):
+                    try:
+                        for j in range(num3, num4):
+                            declare_phy_entities(self, ctx, self.getValue(ctx.parentCtx.varType()), i, j)
+                    except Exception:
+                        declare_phy_entities(self, ctx, self.getValue(ctx.parentCtx.varType()), i)
+        # ================== Subrules of parser rule expr (Start) ====================== #
+
+        def exitId(self, ctx):
+            # Tree annotation for ID which is a labeled subrule of the parser rule expr.
+            # A_C
+            python_keywords = ["and", "as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except",\
+            "exec", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "not", "or", "pass", "print",\
+            "raise", "return", "try", "while", "with", "yield"]
+
+            if ctx.ID().getText().lower() in python_keywords:
+                warnings.warn("Python keywords must not be used as identifiers. Please refer to the list of keywords at https://docs.python.org/2.5/ref/keywords.html",
+                SyntaxWarning)
+
+            if "_" in ctx.ID().getText() and ctx.ID().getText().count('_') == 1:
+                e1, e2 = ctx.ID().getText().lower().split('_')
+                try:
+                    if self.type2[e1] == "frame":
+                        e1 = self.symbol_table2[e1]
+                    elif self.type2[e1] == "bodies":
+                        e1 = self.symbol_table2[e1] + "_f"
+                    if self.type2[e2] == "frame":
+                        e2 = self.symbol_table2[e2]
+                    elif self.type2[e2] == "bodies":
+                        e2 = self.symbol_table2[e2] + "_f"
+
+                    self.setValue(ctx, e1 + ".dcm(" + e2 + ")")
+                except Exception:
+                    self.setValue(ctx, ctx.ID().getText().lower())
+            else:
+                # Reserved constant Pi
+                if ctx.ID().getText().lower() == "pi":
+                    self.setValue(ctx, "_sm.pi")
+                    self.numeric_expr.append(ctx)
+
+                # Reserved variable T (for time)
+                elif ctx.ID().getText().lower() == "t":
+                    self.setValue(ctx, "_me.dynamicsymbols._t")
+                    if not self.in_inputs and not self.in_outputs:
+                        self.t = True
+
+                else:
+                    idText = ctx.ID().getText().lower() + "'"*(ctx.getChildCount() - 1)
+                    if idText in self.type.keys() and self.type[idText] == "matrix":
+                        self.matrix_expr.append(ctx)
+                    if self.in_inputs:
+                        try:
+                            self.setValue(ctx, self.symbol_table[idText])
+                        except Exception:
+                            self.setValue(ctx, idText.lower())
+                    else:
+                        try:
+                            self.setValue(ctx, self.symbol_table[idText])
+                        except Exception:
+                            pass
+
+        def exitInt(self, ctx):
+            # Tree annotation for int which is a labeled subrule of the parser rule expr.
+            int_text = ctx.INT().getText()
+            self.setValue(ctx, int_text)
+            self.numeric_expr.append(ctx)
+
+        def exitFloat(self, ctx):
+            # Tree annotation for float which is a labeled subrule of the parser rule expr.
+            floatText = ctx.FLOAT().getText()
+            self.setValue(ctx, floatText)
+            self.numeric_expr.append(ctx)
+
+        def exitAddSub(self, ctx):
+            # Tree annotation for AddSub which is a labeled subrule of the parser rule expr.
+            # The subrule is expr = expr (+|-) expr
+            if ctx.expr(0) in self.matrix_expr or ctx.expr(1) in self.matrix_expr:
+                self.matrix_expr.append(ctx)
+            if ctx.expr(0) in self.vector_expr or ctx.expr(1) in self.vector_expr:
+                self.vector_expr.append(ctx)
+            if ctx.expr(0) in self.numeric_expr and ctx.expr(1) in self.numeric_expr:
+                self.numeric_expr.append(ctx)
+            self.setValue(ctx, self.getValue(ctx.expr(0)) + ctx.getChild(1).getText() +
+                          self.getValue(ctx.expr(1)))
+
+        def exitMulDiv(self, ctx):
+            # Tree annotation for MulDiv which is a labeled subrule of the parser rule expr.
+            # The subrule is expr = expr (*|/) expr
+            try:
+                if ctx.expr(0) in self.vector_expr and ctx.expr(1) in self.vector_expr:
+                    self.setValue(ctx, "_me.outer(" + self.getValue(ctx.expr(0)) + ", " +
+                                  self.getValue(ctx.expr(1)) + ")")
+                else:
+                    if ctx.expr(0) in self.matrix_expr or ctx.expr(1) in self.matrix_expr:
+                        self.matrix_expr.append(ctx)
+                    if ctx.expr(0) in self.vector_expr or ctx.expr(1) in self.vector_expr:
+                        self.vector_expr.append(ctx)
+                    if ctx.expr(0) in self.numeric_expr and ctx.expr(1) in self.numeric_expr:
+                        self.numeric_expr.append(ctx)
+                    self.setValue(ctx, self.getValue(ctx.expr(0)) + ctx.getChild(1).getText() +
+                                  self.getValue(ctx.expr(1)))
+            except Exception:
+                pass
+
+        def exitNegativeOne(self, ctx):
+            # Tree annotation for negativeOne which is a labeled subrule of the parser rule expr.
+            self.setValue(ctx, "-1*" + self.getValue(ctx.getChild(1)))
+            if ctx.getChild(1) in self.matrix_expr:
+                self.matrix_expr.append(ctx)
+            if ctx.getChild(1) in self.numeric_expr:
+                self.numeric_expr.append(ctx)
+
+        def exitParens(self, ctx):
+            # Tree annotation for parens which is a labeled subrule of the parser rule expr.
+            # The subrule is expr = '(' expr ')'
+            if ctx.expr() in self.matrix_expr:
+                self.matrix_expr.append(ctx)
+            if ctx.expr() in self.vector_expr:
+                self.vector_expr.append(ctx)
+            if ctx.expr() in self.numeric_expr:
+                self.numeric_expr.append(ctx)
+            self.setValue(ctx, "(" + self.getValue(ctx.expr()) + ")")
+
+        def exitExponent(self, ctx):
+            # Tree annotation for Exponent which is a labeled subrule of the parser rule expr.
+            # The subrule is expr = expr ^ expr
+            if ctx.expr(0) in self.matrix_expr or ctx.expr(1) in self.matrix_expr:
+                self.matrix_expr.append(ctx)
+            if ctx.expr(0) in self.vector_expr or ctx.expr(1) in self.vector_expr:
+                self.vector_expr.append(ctx)
+            if ctx.expr(0) in self.numeric_expr and ctx.expr(1) in self.numeric_expr:
+                self.numeric_expr.append(ctx)
+            self.setValue(ctx, self.getValue(ctx.expr(0)) + "**" + self.getValue(ctx.expr(1)))
+
+        def exitExp(self, ctx):
+            s = ctx.EXP().getText()[ctx.EXP().getText().index('E')+1:]
+            if "-" in s:
+                s = s[0] + s[1:].lstrip("0")
+            else:
+                s = s.lstrip("0")
+            self.setValue(ctx, ctx.EXP().getText()[:ctx.EXP().getText().index('E')] +
+                          "*10**(" + s + ")")
+
+        def exitFunction(self, ctx):
+            # Tree annotation for function which is a labeled subrule of the parser rule expr.
+
+            # The difference between this and FunctionCall is that this is used for non standalone functions
+            # appearing in expressions and assignments.
+            # Eg:
+            # When we come across a standalone function say Expand(E, n:m) then it is categorized as FunctionCall
+            # which is a parser rule in itself under rule stat. exitFunctionCall() takes care of it and writes to the file.
+            #
+            # On the other hand, while we come across E_diff = D(E, y), we annotate the tree node
+            # of the function D(E, y) with the SymPy equivalent in exitFunction().
+            # In this case it is the method exitAssignment() that writes the code to the file and not exitFunction().
+
+            ch = ctx.getChild(0)
+            func_name = ch.getChild(0).getText().lower()
+
+            # Expand(y, n:m) *
+            if func_name == "expand":
+                expr = self.getValue(ch.expr(0))
+                if ch.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"):
+                    self.matrix_expr.append(ctx)
+                    # _sm.Matrix([i.expand() for i in z]).reshape(z.shape[0], z.shape[1])
+                    self.setValue(ctx, "_sm.Matrix([i.expand() for i in " + expr + "])" +
+                                  ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])")
+                else:
+                    self.setValue(ctx, "(" + expr + ")" + "." + "expand()")
+
+            # Factor(y, x) *
+            elif func_name == "factor":
+                expr = self.getValue(ch.expr(0))
+                if ch.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"):
+                    self.matrix_expr.append(ctx)
+                    self.setValue(ctx, "_sm.Matrix([_sm.factor(i, " + self.getValue(ch.expr(1)) + ") for i in " +
+                                  expr + "])" + ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])")
+                else:
+                    self.setValue(ctx, "_sm.factor(" + "(" + expr + ")" +
+                                  ", " + self.getValue(ch.expr(1)) + ")")
+
+            # D(y, x)
+            elif func_name == "d":
+                expr = self.getValue(ch.expr(0))
+                if ch.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"):
+                    self.matrix_expr.append(ctx)
+                    self.setValue(ctx, "_sm.Matrix([i.diff(" + self.getValue(ch.expr(1)) + ") for i in " +
+                                  expr + "])" + ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])")
+                else:
+                    if ch.getChildCount() == 8:
+                        frame = self.symbol_table2[ch.expr(2).getText().lower()]
+                        self.setValue(ctx, "(" + expr + ")" + "." + "diff(" + self.getValue(ch.expr(1)) +
+                                      ", " + frame + ")")
+                    else:
+                        self.setValue(ctx, "(" + expr + ")" + "." + "diff(" +
+                                      self.getValue(ch.expr(1)) + ")")
+
+            # Dt(y)
+            elif func_name == "dt":
+                expr = self.getValue(ch.expr(0))
+                if ch.expr(0) in self.vector_expr:
+                    text = "dt("
+                else:
+                    text = "diff(_sm.Symbol('t')"
+                if ch.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"):
+                    self.matrix_expr.append(ctx)
+                    self.setValue(ctx, "_sm.Matrix([i." + text +
+                                  ") for i in " + expr + "])" +
+                                  ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])")
+                else:
+                    if ch.getChildCount() == 6:
+                        frame = self.symbol_table2[ch.expr(1).getText().lower()]
+                        self.setValue(ctx, "(" + expr + ")" + "." + "dt(" +
+                                      frame + ")")
+                    else:
+                        self.setValue(ctx, "(" + expr + ")" + "." + text + ")")
+
+            # Explicit(EXPRESS(IMPLICIT>,C))
+            elif func_name == "explicit":
+                if ch.expr(0) in self.vector_expr:
+                    self.vector_expr.append(ctx)
+                expr = self.getValue(ch.expr(0))
+                if self.explicit.keys():
+                    explicit_list = []
+                    for i in self.explicit.keys():
+                        explicit_list.append(i + ":" + self.explicit[i])
+                    self.setValue(ctx, "(" + expr + ")" + ".subs({" + ", ".join(explicit_list) + "})")
+                else:
+                    self.setValue(ctx, expr)
+
+            # Taylor(y, 0:2, w=a, x=0)
+            # TODO: Currently only works with symbols. Make it work for dynamicsymbols.
+            elif func_name == "taylor":
+                exp = self.getValue(ch.expr(0))
+                order = self.getValue(ch.expr(1).expr(1))
+                x = (ch.getChildCount()-6)//2
+                l = []
+                for i in range(x):
+                    index = 2 + i
+                    child = ch.expr(index)
+                    l.append(".series(" + self.getValue(child.getChild(0)) +
+                             ", " + self.getValue(child.getChild(2)) +
+                             ", " + order + ").removeO()")
+                self.setValue(ctx, "(" + exp + ")" + "".join(l))
+
+            # Evaluate(y, a=x, b=2)
+            elif func_name == "evaluate":
+                expr = self.getValue(ch.expr(0))
+                l = []
+                x = (ch.getChildCount()-4)//2
+                for i in range(x):
+                    index = 1 + i
+                    child = ch.expr(index)
+                    l.append(self.getValue(child.getChild(0)) + ":" +
+                             self.getValue(child.getChild(2)))
+
+                if ch.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"):
+                    self.matrix_expr.append(ctx)
+                    self.setValue(ctx, "_sm.Matrix([i.subs({" + ",".join(l) + "}) for i in " +
+                                  expr + "])" +
+                                  ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])")
+                else:
+                    if self.explicit:
+                        explicit_list = []
+                        for i in self.explicit.keys():
+                            explicit_list.append(i + ":" + self.explicit[i])
+                        self.setValue(ctx, "(" + expr + ")" + ".subs({" + ",".join(explicit_list) +
+                                      "}).subs({" + ",".join(l) + "})")
+                    else:
+                        self.setValue(ctx, "(" + expr + ")" + ".subs({" + ",".join(l) + "})")
+
+            # Polynomial([a, b, c], x)
+            elif func_name == "polynomial":
+                self.setValue(ctx, "_sm.Poly(" + self.getValue(ch.expr(0)) + ", " +
+                              self.getValue(ch.expr(1)) + ")")
+
+            # Roots(Poly, x, 2)
+            # Roots([1; 2; 3; 4])
+            elif func_name == "roots":
+                self.matrix_expr.append(ctx)
+                expr = self.getValue(ch.expr(0))
+                if ch.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"):
+                    self.setValue(ctx, "[i.evalf() for i in " + "_sm.solve(" +
+                                  "_sm.Poly(" + expr + ", " + "x),x)]")
+                else:
+                    self.setValue(ctx, "[i.evalf() for i in " + "_sm.solve(" +
+                                  expr + ", " + self.getValue(ch.expr(1)) + ")]")
+
+            # Transpose(A), Inv(A)
+            elif func_name in ("transpose", "inv", "inverse"):
+                self.matrix_expr.append(ctx)
+                if func_name == "transpose":
+                    e = ".T"
+                elif func_name in ("inv", "inverse"):
+                    e = "**(-1)"
+                self.setValue(ctx, "(" + self.getValue(ch.expr(0)) + ")" + e)
+
+            # Eig(A)
+            elif func_name == "eig":
+                # "_sm.Matrix([i.evalf() for i in " +
+                self.setValue(ctx, "_sm.Matrix([i.evalf() for i in (" +
+                              self.getValue(ch.expr(0)) + ").eigenvals().keys()])")
+
+            # Diagmat(n, m, x)
+            # Diagmat(3, 1)
+            elif func_name == "diagmat":
+                self.matrix_expr.append(ctx)
+                if ch.getChildCount() == 6:
+                    l = []
+                    for i in range(int(self.getValue(ch.expr(0)))):
+                        l.append(self.getValue(ch.expr(1)) + ",")
+
+                    self.setValue(ctx, "_sm.diag(" + ("".join(l))[:-1] + ")")
+
+                elif ch.getChildCount() == 8:
+                    # _sm.Matrix([x if i==j else 0 for i in range(n) for j in range(m)]).reshape(n, m)
+                    n = self.getValue(ch.expr(0))
+                    m = self.getValue(ch.expr(1))
+                    x = self.getValue(ch.expr(2))
+                    self.setValue(ctx, "_sm.Matrix([" + x + " if i==j else 0 for i in range(" +
+                                  n + ") for j in range(" + m + ")]).reshape(" + n + ", " + m + ")")
+
+            # Cols(A)
+            # Cols(A, 1)
+            # Cols(A, 1, 2:4, 3)
+            elif func_name in ("cols", "rows"):
+                self.matrix_expr.append(ctx)
+                if func_name == "cols":
+                    e1 = ".cols"
+                    e2 = ".T."
+                else:
+                    e1 = ".rows"
+                    e2 = "."
+                if ch.getChildCount() == 4:
+                    self.setValue(ctx, "(" + self.getValue(ch.expr(0)) + ")" + e1)
+                elif ch.getChildCount() == 6:
+                    self.setValue(ctx, "(" + self.getValue(ch.expr(0)) + ")" +
+                                  e1[:-1] + "(" + str(int(self.getValue(ch.expr(1))) - 1) + ")")
+                else:
+                    l = []
+                    for i in range(4, ch.getChildCount()):
+                        try:
+                            if ch.getChild(i).getChildCount() > 1 and ch.getChild(i).getChild(1).getText() == ":":
+                                for j in range(int(ch.getChild(i).getChild(0).getText()),
+                                int(ch.getChild(i).getChild(2).getText())+1):
+                                    l.append("(" + self.getValue(ch.getChild(2)) + ")" + e2 +
+                                             "row(" + str(j-1) + ")")
+                            else:
+                                l.append("(" + self.getValue(ch.getChild(2)) + ")" + e2 +
+                                         "row(" + str(int(ch.getChild(i).getText())-1) + ")")
+                        except Exception:
+                            pass
+                    self.setValue(ctx, "_sm.Matrix([" + ",".join(l) + "])")
+
+            # Det(A) Trace(A)
+            elif func_name in ["det", "trace"]:
+                self.setValue(ctx, "(" + self.getValue(ch.expr(0)) + ")" + "." +
+                              func_name + "()")
+
+            # Element(A, 2, 3)
+            elif func_name == "element":
+                self.setValue(ctx, "(" + self.getValue(ch.expr(0)) + ")" + "[" +
+                              str(int(self.getValue(ch.expr(1)))-1) + "," +
+                              str(int(self.getValue(ch.expr(2)))-1) + "]")
+
+            elif func_name in \
+            ["cos", "sin", "tan", "cosh", "sinh", "tanh", "acos", "asin", "atan",
+            "log", "exp", "sqrt", "factorial", "floor", "sign"]:
+                self.setValue(ctx, "_sm." + func_name + "(" + self.getValue(ch.expr(0)) + ")")
+
+            elif func_name == "ceil":
+                self.setValue(ctx, "_sm.ceiling" + "(" + self.getValue(ch.expr(0)) + ")")
+
+            elif func_name == "sqr":
+                self.setValue(ctx, "(" + self.getValue(ch.expr(0)) +
+                              ")" + "**2")
+
+            elif func_name == "log10":
+                self.setValue(ctx, "_sm.log" +
+                              "(" + self.getValue(ch.expr(0)) + ", 10)")
+
+            elif func_name == "atan2":
+                self.setValue(ctx, "_sm.atan2" + "(" + self.getValue(ch.expr(0)) + ", " +
+                              self.getValue(ch.expr(1)) + ")")
+
+            elif func_name in ["int", "round"]:
+                self.setValue(ctx, func_name +
+                              "(" + self.getValue(ch.expr(0)) + ")")
+
+            elif func_name == "abs":
+                self.setValue(ctx, "_sm.Abs(" + self.getValue(ch.expr(0)) + ")")
+
+            elif func_name in ["max", "min"]:
+                # max(x, y, z)
+                l = []
+                for i in range(1, ch.getChildCount()):
+                    if ch.getChild(i) in self.tree_property.keys():
+                        l.append(self.getValue(ch.getChild(i)))
+                    elif ch.getChild(i).getText() in [",", "(", ")"]:
+                        l.append(ch.getChild(i).getText())
+                self.setValue(ctx, "_sm." + ch.getChild(0).getText().capitalize() + "".join(l))
+
+            # Coef(y, x)
+            elif func_name == "coef":
+                #A41_A53=COEF([RHS(U4);RHS(U5)],[U1,U2,U3])
+                if ch.expr(0) in self.matrix_expr and ch.expr(1) in self.matrix_expr:
+                    icount = jcount = 0
+                    for i in range(ch.expr(0).getChild(0).getChildCount()):
+                        try:
+                            ch.expr(0).getChild(0).getChild(i).getRuleIndex()
+                            icount+=1
+                        except Exception:
+                            pass
+                    for j in range(ch.expr(1).getChild(0).getChildCount()):
+                        try:
+                            ch.expr(1).getChild(0).getChild(j).getRuleIndex()
+                            jcount+=1
+                        except Exception:
+                            pass
+                    l = []
+                    for i in range(icount):
+                        for j in range(jcount):
+                            # a41_a53[i,j] = u4.expand().coeff(u1)
+                            l.append(self.getValue(ch.expr(0).getChild(0).expr(i)) + ".expand().coeff("
+                                     + self.getValue(ch.expr(1).getChild(0).expr(j)) + ")")
+                    self.setValue(ctx, "_sm.Matrix([" + ", ".join(l) + "]).reshape(" + str(icount) + ", " + str(jcount) + ")")
+                else:
+                    self.setValue(ctx, "(" + self.getValue(ch.expr(0)) +
+                                  ")" + ".expand().coeff(" + self.getValue(ch.expr(1)) + ")")
+
+            # Exclude(y, x) Include(y, x)
+            elif func_name in ("exclude", "include"):
+                if func_name == "exclude":
+                    e = "0"
+                else:
+                    e = "1"
+                expr = self.getValue(ch.expr(0))
+                if ch.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"):
+                    self.matrix_expr.append(ctx)
+                    self.setValue(ctx, "_sm.Matrix([i.collect(" + self.getValue(ch.expr(1)) + "])" +
+                                  ".coeff(" + self.getValue(ch.expr(1)) + "," + e + ")" + "for i in " + expr + ")" +
+                                  ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])")
+                else:
+                    self.setValue(ctx, "(" + expr +
+                                  ")" + ".collect(" + self.getValue(ch.expr(1)) + ")" +
+                                  ".coeff(" + self.getValue(ch.expr(1)) + "," + e + ")")
+
+            # RHS(y)
+            elif func_name == "rhs":
+                self.setValue(ctx, self.explicit[self.getValue(ch.expr(0))])
+
+            # Arrange(y, n, x) *
+            elif func_name == "arrange":
+                expr = self.getValue(ch.expr(0))
+                if ch.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"):
+                    self.matrix_expr.append(ctx)
+                    self.setValue(ctx, "_sm.Matrix([i.collect(" + self.getValue(ch.expr(2)) +
+                                  ")" + "for i in " + expr + "])"+
+                                  ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])")
+                else:
+                    self.setValue(ctx, "(" + expr +
+                                  ")" + ".collect(" + self.getValue(ch.expr(2)) + ")")
+
+            # Replace(y, sin(x)=3)
+            elif func_name == "replace":
+                l = []
+                for i in range(1, ch.getChildCount()):
+                    try:
+                        if ch.getChild(i).getChild(1).getText() == "=":
+                            l.append(self.getValue(ch.getChild(i).getChild(0)) +
+                                     ":" + self.getValue(ch.getChild(i).getChild(2)))
+                    except Exception:
+                        pass
+                expr = self.getValue(ch.expr(0))
+                if ch.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"):
+                    self.matrix_expr.append(ctx)
+                    self.setValue(ctx, "_sm.Matrix([i.subs({" + ",".join(l) + "}) for i in " +
+                                  expr + "])" +
+                                  ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])")
+                else:
+                    self.setValue(ctx, "(" + self.getValue(ch.expr(0)) + ")" +
+                                  ".subs({" + ",".join(l) + "})")
+
+            # Dot(Loop>, N1>)
+            elif func_name == "dot":
+                l = []
+                num = (ch.expr(1).getChild(0).getChildCount()-1)//2
+                if ch.expr(1) in self.matrix_expr:
+                    for i in range(num):
+                        l.append("_me.dot(" + self.getValue(ch.expr(0)) + ", " + self.getValue(ch.expr(1).getChild(0).expr(i)) + ")")
+                    self.setValue(ctx, "_sm.Matrix([" + ",".join(l) + "]).reshape(" + str(num) + ", " + "1)")
+                else:
+                    self.setValue(ctx, "_me.dot(" + self.getValue(ch.expr(0)) + ", " + self.getValue(ch.expr(1)) + ")")
+            # Cross(w_A_N>, P_NA_AB>)
+            elif func_name == "cross":
+                self.vector_expr.append(ctx)
+                self.setValue(ctx, "_me.cross(" + self.getValue(ch.expr(0)) + ", " + self.getValue(ch.expr(1)) + ")")
+
+            # Mag(P_O_Q>)
+            elif func_name == "mag":
+                self.setValue(ctx, self.getValue(ch.expr(0)) + "." + "magnitude()")
+
+            # MATRIX(A, I_R>>)
+            elif func_name == "matrix":
+                if self.type2[ch.expr(0).getText().lower()] == "frame":
+                    text = ""
+                elif self.type2[ch.expr(0).getText().lower()] == "bodies":
+                    text = "_f"
+                self.setValue(ctx, "(" + self.getValue(ch.expr(1)) + ")" + ".to_matrix(" +
+                              self.symbol_table2[ch.expr(0).getText().lower()] + text + ")")
+
+            # VECTOR(A, ROWS(EIGVECS,1))
+            elif func_name == "vector":
+                if self.type2[ch.expr(0).getText().lower()] == "frame":
+                    text = ""
+                elif self.type2[ch.expr(0).getText().lower()] == "bodies":
+                    text = "_f"
+                v = self.getValue(ch.expr(1))
+                f = self.symbol_table2[ch.expr(0).getText().lower()] + text
+                self.setValue(ctx, v + "[0]*" + f + ".x +" + v + "[1]*" + f + ".y +" +
+                              v + "[2]*" + f + ".z")
+
+            # Express(A2>, B)
+            # Here I am dealing with all the Inertia commands as I expect the users to use Inertia
+            # commands only with Express because SymPy needs the Reference frame to be specified unlike Autolev.
+            elif func_name == "express":
+                self.vector_expr.append(ctx)
+                if self.type2[ch.expr(1).getText().lower()] == "frame":
+                    frame = self.symbol_table2[ch.expr(1).getText().lower()]
+                else:
+                    frame = self.symbol_table2[ch.expr(1).getText().lower()] + "_f"
+                if ch.expr(0).getText().lower() == "1>>":
+                    self.setValue(ctx, "_me.inertia(" + frame + ", 1, 1, 1)")
+
+                elif '_' in ch.expr(0).getText().lower() and ch.expr(0).getText().lower().count('_') == 2\
+                and ch.expr(0).getText().lower()[0] == "i" and ch.expr(0).getText().lower()[-2:] == ">>":
+                    v1 = ch.expr(0).getText().lower()[:-2].split('_')[1]
+                    v2 = ch.expr(0).getText().lower()[:-2].split('_')[2]
+                    l = []
+                    inertia_func(self, v1, v2, l, frame)
+                    self.setValue(ctx, " + ".join(l))
+
+                elif ch.expr(0).getChild(0).getChild(0).getText().lower() == "inertia":
+                    if ch.expr(0).getChild(0).getChildCount() == 4:
+                        l = []
+                        v2 = ch.expr(0).getChild(0).ID(0).getText().lower()
+                        for v1 in self.bodies:
+                            inertia_func(self, v1, v2, l, frame)
+                        self.setValue(ctx, " + ".join(l))
+
+                    else:
+                        l = []
+                        l2 = []
+                        v2 = ch.expr(0).getChild(0).ID(0).getText().lower()
+                        for i in range(1, (ch.expr(0).getChild(0).getChildCount()-2)//2):
+                            l2.append(ch.expr(0).getChild(0).ID(i).getText().lower())
+                        for v1 in l2:
+                            inertia_func(self, v1, v2, l, frame)
+                        self.setValue(ctx, " + ".join(l))
+
+                else:
+                    self.setValue(ctx, "(" + self.getValue(ch.expr(0)) + ")" + ".express(" +
+                                  self.symbol_table2[ch.expr(1).getText().lower()] + ")")
+            # CM(P)
+            elif func_name == "cm":
+                if self.type2[ch.expr(0).getText().lower()] == "point":
+                    text = ""
+                else:
+                    text = ".point"
+                if ch.getChildCount() == 4:
+                    self.setValue(ctx, "_me.functions.center_of_mass(" + self.symbol_table2[ch.expr(0).getText().lower()] +
+                                  text + "," + ", ".join(self.bodies.values()) + ")")
+                else:
+                    bodies = []
+                    for i in range(1, (ch.getChildCount()-1)//2):
+                        bodies.append(self.symbol_table2[ch.expr(i).getText().lower()])
+                    self.setValue(ctx, "_me.functions.center_of_mass(" + self.symbol_table2[ch.expr(0).getText().lower()] +
+                                  text + "," + ", ".join(bodies) + ")")
+
+            # PARTIALS(V_P1_E>,U1)
+            elif func_name == "partials":
+                speeds = []
+                for i in range(1, (ch.getChildCount()-1)//2):
+                    if self.kd_equivalents2:
+                        speeds.append(self.kd_equivalents2[self.symbol_table[ch.expr(i).getText().lower()]])
+                    else:
+                        speeds.append(self.symbol_table[ch.expr(i).getText().lower()])
+                v1, v2, v3 = ch.expr(0).getText().lower().replace(">","").split('_')
+                if self.type2[v2] == "point":
+                    point = self.symbol_table2[v2]
+                elif self.type2[v2] == "particle":
+                    point = self.symbol_table2[v2] + ".point"
+                frame = self.symbol_table2[v3]
+                self.setValue(ctx, point + ".partial_velocity(" + frame + ", " + ",".join(speeds) + ")")
+
+            # UnitVec(A1>+A2>+A3>)
+            elif func_name == "unitvec":
+                self.setValue(ctx, "(" + self.getValue(ch.expr(0)) + ")" + ".normalize()")
+
+            # Units(deg, rad)
+            elif func_name == "units":
+                if ch.expr(0).getText().lower() == "deg" and ch.expr(1).getText().lower() == "rad":
+                    factor = 0.0174533
+                elif ch.expr(0).getText().lower() == "rad" and ch.expr(1).getText().lower() == "deg":
+                    factor = 57.2958
+                self.setValue(ctx, str(factor))
+            # Mass(A)
+            elif func_name == "mass":
+                l = []
+                try:
+                    ch.ID(0).getText().lower()
+                    for i in range((ch.getChildCount()-1)//2):
+                        l.append(self.symbol_table2[ch.ID(i).getText().lower()] + ".mass")
+                    self.setValue(ctx, "+".join(l))
+                except Exception:
+                    for i in self.bodies.keys():
+                        l.append(self.bodies[i] + ".mass")
+                    self.setValue(ctx, "+".join(l))
+
+            # Fr() FrStar()
+            # _me.KanesMethod(n, q_ind, u_ind, kd, velocity_constraints).kanes_equations(pl, fl)[0]
+            elif func_name in ["fr", "frstar"]:
+                if not self.kane_parsed:
+                    if self.kd_eqs:
+                        for i in self.kd_eqs:
+                            self.q_ind.append(self.symbol_table[i.strip().split('-')[0].replace("'","")])
+                            self.u_ind.append(self.symbol_table[i.strip().split('-')[1].replace("'","")])
+
+                    for i in range(len(self.kd_eqs)):
+                        self.kd_eqs[i] = self.symbol_table[self.kd_eqs[i].strip().split('-')[0]] + " - " +\
+                                         self.symbol_table[self.kd_eqs[i].strip().split('-')[1]]
+
+                    # Do all of this if kd_eqs are not specified
+                    if not self.kd_eqs:
+                        self.kd_eqs_supplied = False
+                        self.matrix_expr.append(ctx)
+                        for i in self.type.keys():
+                            if self.type[i] == "motionvariable":
+                                if self.sign[self.symbol_table[i.lower()]] == 0:
+                                    self.q_ind.append(self.symbol_table[i.lower()])
+                                elif self.sign[self.symbol_table[i.lower()]] == 1:
+                                    name = "u_" + self.symbol_table[i.lower()]
+                                    self.symbol_table.update({name: name})
+                                    self.write(name + " = " + "_me.dynamicsymbols('" + name + "')\n")
+                                    if self.symbol_table[i.lower()] not in self.dependent_variables:
+                                        self.u_ind.append(name)
+                                        self.kd_equivalents.update({name: self.symbol_table[i.lower()]})
+                                    else:
+                                        self.u_dep.append(name)
+                                        self.kd_equivalents.update({name: self.symbol_table[i.lower()]})
+
+                        for i in self.kd_equivalents.keys():
+                            self.kd_eqs.append(self.kd_equivalents[i] + "-" + i)
+
+                    if not self.u_ind and not self.kd_eqs:
+                        self.u_ind = self.q_ind.copy()
+                        self.q_ind = []
+
+                # deal with velocity constraints
+                if self.dependent_variables:
+                    for i in self.dependent_variables:
+                        self.u_dep.append(i)
+                        if i in self.u_ind:
+                            self.u_ind.remove(i)
+
+
+                self.u_dep[:] = [i for i in self.u_dep if i not in self.kd_equivalents.values()]
+
+                force_list = []
+                for i in self.forces.keys():
+                    force_list.append("(" + i + "," + self.forces[i] + ")")
+                if self.u_dep:
+                    u_dep_text = ", u_dependent=[" + ", ".join(self.u_dep) + "]"
+                else:
+                    u_dep_text = ""
+                if self.dependent_variables:
+                    velocity_constraints_text = ", velocity_constraints = velocity_constraints"
+                else:
+                    velocity_constraints_text = ""
+                if ctx.parentCtx not in self.fr_expr:
+                    self.write("kd_eqs = [" + ", ".join(self.kd_eqs) + "]\n")
+                    self.write("forceList = " + "[" + ", ".join(force_list) + "]\n")
+                    self.write("kane = _me.KanesMethod(" + self.newtonian + ", " + "q_ind=[" +
+                            ",".join(self.q_ind) + "], " + "u_ind=[" +
+                            ", ".join(self.u_ind) + "]" + u_dep_text + ", " +
+                            "kd_eqs = kd_eqs" + velocity_constraints_text + ")\n")
+                    self.write("fr, frstar = kane." + "kanes_equations([" +
+                                ", ".join(self.bodies.values()) + "], forceList)\n")
+                    self.fr_expr.append(ctx.parentCtx)
+                self.kane_parsed = True
+                self.setValue(ctx, func_name)
+
+        def exitMatrices(self, ctx):
+            # Tree annotation for Matrices which is a labeled subrule of the parser rule expr.
+
+            # MO = [a, b; c, d]
+            # we generate _sm.Matrix([a, b, c, d]).reshape(2, 2)
+            # The reshape values are determined by counting the "," and ";" in the Autolev matrix
+
+            # Eg:
+            # [1, 2, 3; 4, 5, 6; 7, 8, 9; 10, 11, 12]
+            # semicolon_count = 3 and rows = 3+1 = 4
+            # comma_count = 8 and cols = 8/rows + 1 = 8/4 + 1 = 3
+
+            # TODO** Parse block matrices
+            self.matrix_expr.append(ctx)
+            l = []
+            semicolon_count = 0
+            comma_count = 0
+            for i in range(ctx.matrix().getChildCount()):
+                child = ctx.matrix().getChild(i)
+                if child == AutolevParser.ExprContext:
+                    l.append(self.getValue(child))
+                elif child.getText() == ";":
+                    semicolon_count += 1
+                    l.append(",")
+                elif child.getText() == ",":
+                    comma_count += 1
+                    l.append(",")
+                else:
+                    try:
+                        try:
+                            l.append(self.getValue(child))
+                        except Exception:
+                            l.append(self.symbol_table[child.getText().lower()])
+                    except Exception:
+                        l.append(child.getText().lower())
+            num_of_rows = semicolon_count + 1
+            num_of_cols = (comma_count//num_of_rows) + 1
+
+            self.setValue(ctx, "_sm.Matrix(" + "".join(l) + ")" + ".reshape(" +
+                          str(num_of_rows) + ", " + str(num_of_cols) + ")")
+
+        def exitVectorOrDyadic(self, ctx):
+            self.vector_expr.append(ctx)
+            ch = ctx.vec()
+
+            if ch.getChild(0).getText() == "0>":
+                self.setValue(ctx, "0")
+
+            elif ch.getChild(0).getText() == "1>>":
+                self.setValue(ctx, "1>>")
+
+            elif "_" in ch.ID().getText() and ch.ID().getText().count('_') == 2:
+                vec_text = ch.getText().lower()
+                v1, v2, v3 = ch.ID().getText().lower().split('_')
+
+                if v1 == "p":
+                    if self.type2[v2] == "point":
+                        e2 = self.symbol_table2[v2]
+                    elif self.type2[v2] == "particle":
+                        e2 = self.symbol_table2[v2] + ".point"
+                    if self.type2[v3] == "point":
+                        e3 = self.symbol_table2[v3]
+                    elif self.type2[v3] == "particle":
+                        e3 = self.symbol_table2[v3] + ".point"
+                    get_vec = e3 + ".pos_from(" + e2 + ")"
+                    self.setValue(ctx, get_vec)
+
+                elif v1 in ("w", "alf"):
+                    if v1 == "w":
+                        text = ".ang_vel_in("
+                    elif v1 == "alf":
+                        text = ".ang_acc_in("
+                    if self.type2[v2] == "bodies":
+                        e2 = self.symbol_table2[v2] + "_f"
+                    elif self.type2[v2] == "frame":
+                        e2 = self.symbol_table2[v2]
+                    if self.type2[v3] == "bodies":
+                        e3 = self.symbol_table2[v3] + "_f"
+                    elif self.type2[v3] == "frame":
+                        e3 = self.symbol_table2[v3]
+                    get_vec = e2 + text + e3 + ")"
+                    self.setValue(ctx, get_vec)
+
+                elif v1 in ("v", "a"):
+                    if v1 == "v":
+                        text = ".vel("
+                    elif v1 == "a":
+                        text = ".acc("
+                    if self.type2[v2] == "point":
+                        e2 = self.symbol_table2[v2]
+                    elif self.type2[v2] == "particle":
+                        e2 = self.symbol_table2[v2] + ".point"
+                    get_vec = e2 + text + self.symbol_table2[v3] + ")"
+                    self.setValue(ctx, get_vec)
+
+                else:
+                    self.setValue(ctx, vec_text.replace(">", ""))
+
+            else:
+                vec_text = ch.getText().lower()
+                name = self.symbol_table[vec_text]
+                self.setValue(ctx, name)
+
+        def exitIndexing(self, ctx):
+            if ctx.getChildCount() == 4:
+                try:
+                    int_text = str(int(self.getValue(ctx.getChild(2))) - 1)
+                except Exception:
+                    int_text = self.getValue(ctx.getChild(2)) + " - 1"
+                self.setValue(ctx, ctx.ID().getText().lower() + "[" + int_text + "]")
+            elif ctx.getChildCount() == 6:
+                try:
+                    int_text1 = str(int(self.getValue(ctx.getChild(2))) - 1)
+                except Exception:
+                    int_text1 = self.getValue(ctx.getChild(2)) + " - 1"
+                try:
+                    int_text2 = str(int(self.getValue(ctx.getChild(4))) - 1)
+                except Exception:
+                    int_text2 = self.getValue(ctx.getChild(2)) + " - 1"
+                self.setValue(ctx, ctx.ID().getText().lower() + "[" + int_text1 + ", " + int_text2 + "]")
+
+
+        # ================== Subrules of parser rule expr (End) ====================== #
+
+        def exitRegularAssign(self, ctx):
+            # Handle assignments of type ID = expr
+            if ctx.equals().getText() in ["=", "+=", "-=", "*=", "/="]:
+                equals = ctx.equals().getText()
+            elif ctx.equals().getText() == ":=":
+                equals = " = "
+            elif ctx.equals().getText() == "^=":
+                equals = "**="
+
+            try:
+                a = ctx.ID().getText().lower() + "'"*ctx.diff().getText().count("'")
+            except Exception:
+                a = ctx.ID().getText().lower()
+
+            if a in self.type.keys() and self.type[a] in ("motionvariable", "motionvariable'") and\
+            self.type[ctx.expr().getText().lower()] in ("motionvariable", "motionvariable'"):
+                b = ctx.expr().getText().lower()
+                if "'" in b and "'" not in a:
+                    a, b = b, a
+                if not self.kane_parsed:
+                    self.kd_eqs.append(a + "-" + b)
+                    self.kd_equivalents.update({self.symbol_table[a]:
+                                                self.symbol_table[b]})
+                    self.kd_equivalents2.update({self.symbol_table[b]:
+                                                    self.symbol_table[a]})
+
+            if a in self.symbol_table.keys() and a in self.type.keys() and self.type[a] in ("variable", "motionvariable"):
+                self.explicit.update({self.symbol_table[a]: self.getValue(ctx.expr())})
+
+            else:
+                if ctx.expr() in self.matrix_expr:
+                    self.type.update({a: "matrix"})
+
+                try:
+                    b = self.symbol_table[a]
+                except KeyError:
+                    self.symbol_table[a] = a
+
+                if "_" in a and a.count("_") == 1:
+                    e1, e2 = a.split('_')
+                    if e1 in self.type2.keys() and self.type2[e1] in ("frame", "bodies")\
+                    and e2 in self.type2.keys() and self.type2[e2] in ("frame", "bodies"):
+                        if self.type2[e1] == "bodies":
+                            t1 = "_f"
+                        else:
+                            t1 = ""
+                        if self.type2[e2] == "bodies":
+                            t2 = "_f"
+                        else:
+                            t2 = ""
+
+                        self.write(self.symbol_table2[e2] + t2 + ".orient(" + self.symbol_table2[e1] +
+                                   t1 + ", 'DCM', " + self.getValue(ctx.expr()) + ")\n")
+                    else:
+                        self.write(self.symbol_table[a] + " " + equals + " " +
+                                    self.getValue(ctx.expr()) + "\n")
+                else:
+                    self.write(self.symbol_table[a] + " " + equals + " " +
+                                self.getValue(ctx.expr()) + "\n")
+
+        def exitIndexAssign(self, ctx):
+            # Handle assignments of type ID[index] = expr
+                if ctx.equals().getText() in ["=", "+=", "-=", "*=", "/="]:
+                    equals = ctx.equals().getText()
+                elif ctx.equals().getText() == ":=":
+                    equals = " = "
+                elif ctx.equals().getText() == "^=":
+                    equals = "**="
+
+                text = ctx.ID().getText().lower()
+                self.type.update({text: "matrix"})
+                # Handle assignments of type ID[2] = expr
+                if ctx.index().getChildCount() == 1:
+                    if ctx.index().getChild(0).getText() == "1":
+                        self.type.update({text: "matrix"})
+                        self.symbol_table.update({text: text})
+                        self.write(text + " = " + "_sm.Matrix([[0]])\n")
+                        self.write(text + "[0] = " + self.getValue(ctx.expr()) + "\n")
+                    else:
+                        # m = m.row_insert(m.shape[0], _sm.Matrix([[0]]))
+                        self.write(text + " = " + text +
+                                   ".row_insert(" + text + ".shape[0]" + ", " + "_sm.Matrix([[0]])" + ")\n")
+                        self.write(text + "[" + text + ".shape[0]-1" + "] = " + self.getValue(ctx.expr()) + "\n")
+
+                # Handle assignments of type ID[2, 2] = expr
+                elif ctx.index().getChildCount() == 3:
+                    l = []
+                    try:
+                        l.append(str(int(self.getValue(ctx.index().getChild(0)))-1))
+                    except Exception:
+                        l.append(self.getValue(ctx.index().getChild(0)) + "-1")
+                    l.append(",")
+                    try:
+                        l.append(str(int(self.getValue(ctx.index().getChild(2)))-1))
+                    except Exception:
+                        l.append(self.getValue(ctx.index().getChild(2)) + "-1")
+                    self.write(self.symbol_table[ctx.ID().getText().lower()] +
+                               "[" + "".join(l) + "]" + " " + equals + " " + self.getValue(ctx.expr()) + "\n")
+
+        def exitVecAssign(self, ctx):
+            # Handle assignments of the type vec = expr
+            ch = ctx.vec()
+            vec_text = ch.getText().lower()
+
+            if "_" in ch.ID().getText():
+                num = ch.ID().getText().count('_')
+
+                if num == 2:
+                    v1, v2, v3 = ch.ID().getText().lower().split('_')
+
+                    if v1 == "p":
+                        if self.type2[v2] == "point":
+                            e2 = self.symbol_table2[v2]
+                        elif self.type2[v2] == "particle":
+                            e2 = self.symbol_table2[v2] + ".point"
+                        if self.type2[v3] == "point":
+                            e3 = self.symbol_table2[v3]
+                        elif self.type2[v3] == "particle":
+                            e3 = self.symbol_table2[v3] + ".point"
+                        # ab.set_pos(na, la*a.x)
+                        self.write(e3 + ".set_pos(" + e2 + ", " + self.getValue(ctx.expr()) + ")\n")
+
+                    elif v1 in ("w", "alf"):
+                        if v1 == "w":
+                            text = ".set_ang_vel("
+                        elif v1 == "alf":
+                            text = ".set_ang_acc("
+                        # a.set_ang_vel(n, qad*a.z)
+                        if self.type2[v2] == "bodies":
+                            e2 = self.symbol_table2[v2] + "_f"
+                        else:
+                            e2 = self.symbol_table2[v2]
+                        if self.type2[v3] == "bodies":
+                            e3 = self.symbol_table2[v3] + "_f"
+                        else:
+                            e3 = self.symbol_table2[v3]
+                        self.write(e2 + text + e3 + ", " + self.getValue(ctx.expr()) + ")\n")
+
+                    elif v1 in ("v", "a"):
+                        if v1 == "v":
+                            text = ".set_vel("
+                        elif v1 == "a":
+                            text = ".set_acc("
+                        if self.type2[v2] == "point":
+                            e2 = self.symbol_table2[v2]
+                        elif self.type2[v2] == "particle":
+                            e2 = self.symbol_table2[v2] + ".point"
+                        self.write(e2 + text + self.symbol_table2[v3] +
+                                   ", " + self.getValue(ctx.expr()) + ")\n")
+                    elif v1 == "i":
+                        if v2 in self.type2.keys() and self.type2[v2] == "bodies":
+                            self.write(self.symbol_table2[v2] + ".inertia = (" + self.getValue(ctx.expr()) +
+                            ", " + self.symbol_table2[v3] + ")\n")
+                            self.inertia_point.update({v2: v3})
+                        elif v2 in self.type2.keys() and self.type2[v2] == "particle":
+                            self.write(ch.ID().getText().lower() + " = " + self.getValue(ctx.expr()) + "\n")
+                        else:
+                            self.write(ch.ID().getText().lower() + " = " + self.getValue(ctx.expr()) + "\n")
+                    else:
+                        self.write(ch.ID().getText().lower() + " = " + self.getValue(ctx.expr()) + "\n")
+
+                elif num == 1:
+                    v1, v2 = ch.ID().getText().lower().split('_')
+
+                    if v1 in ("force", "torque"):
+                        if self.type2[v2] in ("point", "frame"):
+                            e2 = self.symbol_table2[v2]
+                        elif self.type2[v2] == "particle":
+                            e2 = self.symbol_table2[v2] + ".point"
+                        self.symbol_table.update({vec_text: ch.ID().getText().lower()})
+
+                        if e2 in self.forces.keys():
+                            self.forces[e2] = self.forces[e2] + " + " + self.getValue(ctx.expr())
+                        else:
+                            self.forces.update({e2: self.getValue(ctx.expr())})
+                        self.write(ch.ID().getText().lower() + " = " + self.forces[e2] + "\n")
+
+                    else:
+                        name = ch.ID().getText().lower()
+                        self.symbol_table.update({vec_text: name})
+                        self.write(ch.ID().getText().lower() + " = " + self.getValue(ctx.expr()) + "\n")
+                else:
+                    name = ch.ID().getText().lower()
+                    self.symbol_table.update({vec_text: name})
+                    self.write(name + " " + ctx.getChild(1).getText() + " " + self.getValue(ctx.expr()) + "\n")
+            else:
+                name = ch.ID().getText().lower()
+                self.symbol_table.update({vec_text: name})
+                self.write(name + " " + ctx.getChild(1).getText() + " " + self.getValue(ctx.expr()) + "\n")
+
+        def enterInputs2(self, ctx):
+            self.in_inputs = True
+
+        # Inputs
+        def exitInputs2(self, ctx):
+            # Stores numerical values given by the input command which
+            # are used for codegen and numerical analysis.
+            if ctx.getChildCount() == 3:
+                try:
+                    self.inputs.update({self.symbol_table[ctx.id_diff().getText().lower()]: self.getValue(ctx.expr(0))})
+                except Exception:
+                    self.inputs.update({ctx.id_diff().getText().lower(): self.getValue(ctx.expr(0))})
+            elif ctx.getChildCount() == 4:
+                try:
+                    self.inputs.update({self.symbol_table[ctx.id_diff().getText().lower()]:
+                    (self.getValue(ctx.expr(0)), self.getValue(ctx.expr(1)))})
+                except Exception:
+                    self.inputs.update({ctx.id_diff().getText().lower():
+                    (self.getValue(ctx.expr(0)), self.getValue(ctx.expr(1)))})
+
+            self.in_inputs = False
+
+        def enterOutputs(self, ctx):
+            self.in_outputs = True
+        def exitOutputs(self, ctx):
+            self.in_outputs = False
+
+        def exitOutputs2(self, ctx):
+            try:
+                if "[" in ctx.expr(1).getText():
+                    self.outputs.append(self.symbol_table[ctx.expr(0).getText().lower()] +
+                                        ctx.expr(1).getText().lower())
+                else:
+                    self.outputs.append(self.symbol_table[ctx.expr(0).getText().lower()])
+
+            except Exception:
+                pass
+
+        # Code commands
+        def exitCodegen(self, ctx):
+            # Handles the CODE() command ie the solvers and the codgen part.
+            # Uses linsolve for the algebraic solvers and nsolve for non linear solvers.
+
+            if ctx.functionCall().getChild(0).getText().lower() == "algebraic":
+                matrix_name = self.getValue(ctx.functionCall().expr(0))
+                e = []
+                d = []
+                for i in range(1, (ctx.functionCall().getChildCount()-2)//2):
+                    a = self.getValue(ctx.functionCall().expr(i))
+                    e.append(a)
+
+                for i in self.inputs.keys():
+                    d.append(i + ":" + self.inputs[i])
+                self.write(matrix_name + "_list" + " = " + "[]\n")
+                self.write("for i in " + matrix_name + ":  " + matrix_name +
+                           "_list" + ".append(i.subs({" + ", ".join(d) + "}))\n")
+                self.write("print(_sm.linsolve(" + matrix_name + "_list" + ", " + ",".join(e) + "))\n")
+
+            elif ctx.functionCall().getChild(0).getText().lower() == "nonlinear":
+                e = []
+                d = []
+                guess = []
+                for i in range(1, (ctx.functionCall().getChildCount()-2)//2):
+                    a = self.getValue(ctx.functionCall().expr(i))
+                    e.append(a)
+                #print(self.inputs)
+                for i in self.inputs.keys():
+                    if i in self.symbol_table.keys():
+                        if type(self.inputs[i]) is tuple:
+                            j, z = self.inputs[i]
+                        else:
+                            j = self.inputs[i]
+                            z = ""
+                        if i not in e:
+                            if z == "deg":
+                                d.append(i + ":" + "_np.deg2rad(" + j + ")")
+                            else:
+                                d.append(i + ":" + j)
+                        else:
+                            if z == "deg":
+                                guess.append("_np.deg2rad(" + j + ")")
+                            else:
+                                guess.append(j)
+
+                self.write("matrix_list" + " = " + "[]\n")
+                self.write("for i in " + self.getValue(ctx.functionCall().expr(0)) + ":")
+                self.write("matrix_list" + ".append(i.subs({" + ", ".join(d) + "}))\n")
+                self.write("print(_sm.nsolve(matrix_list," + "(" + ",".join(e) + ")" +
+                           ",(" + ",".join(guess) + ")" + "))\n")
+
+            elif ctx.functionCall().getChild(0).getText().lower() in ["ode", "dynamics"] and self.include_numeric:
+                if self.kane_type == "no_args":
+                    for i in self.symbol_table.keys():
+                        try:
+                            if self.type[i] == "constants" or self.type[self.symbol_table[i]] == "constants":
+                                self.constants.append(self.symbol_table[i])
+                        except Exception:
+                            pass
+                    q_add_u = self.q_ind + self.q_dep + self.u_ind + self.u_dep
+                    x0 = []
+                    for i in q_add_u:
+                        try:
+                            if i in self.inputs.keys():
+                                if type(self.inputs[i]) is tuple:
+                                    if self.inputs[i][1] == "deg":
+                                        x0.append(i + ":" + "_np.deg2rad(" + self.inputs[i][0] + ")")
+                                    else:
+                                        x0.append(i + ":" + self.inputs[i][0])
+                                else:
+                                    x0.append(i + ":" + self.inputs[i])
+                            elif self.kd_equivalents[i] in self.inputs.keys():
+                                if type(self.inputs[self.kd_equivalents[i]]) is tuple:
+                                    x0.append(i + ":" + self.inputs[self.kd_equivalents[i]][0])
+                                else:
+                                    x0.append(i + ":" + self.inputs[self.kd_equivalents[i]])
+                        except Exception:
+                            pass
+
+                    # numerical constants
+                    numerical_constants = []
+                    for i in self.constants:
+                        if i in self.inputs.keys():
+                            if type(self.inputs[i]) is tuple:
+                                numerical_constants.append(self.inputs[i][0])
+                            else:
+                                numerical_constants.append(self.inputs[i])
+
+                    # t = linspace
+                    t_final = self.inputs["tfinal"]
+                    integ_stp = self.inputs["integstp"]
+
+                    self.write("from pydy.system import System\n")
+                    const_list = []
+                    if numerical_constants:
+                        for i in range(len(self.constants)):
+                            const_list.append(self.constants[i] + ":" + numerical_constants[i])
+                    specifieds = []
+                    if self.t:
+                        specifieds.append("_me.dynamicsymbols('t')" + ":" + "lambda x, t: t")
+
+                    for i in self.inputs:
+                        if i in self.symbol_table.keys() and self.symbol_table[i] not in\
+                        self.constants + self.q_ind + self.q_dep + self.u_ind + self.u_dep:
+                            specifieds.append(self.symbol_table[i] + ":" + self.inputs[i])
+
+                    self.write("sys = System(kane, constants = {" + ", ".join(const_list) + "},\n" +
+                               "specifieds={" + ", ".join(specifieds) + "},\n" +
+                               "initial_conditions={" + ", ".join(x0) + "},\n" +
+                               "times = _np.linspace(0.0, " + str(t_final) + ", " + str(t_final) +
+                               "/" + str(integ_stp) + "))\n\ny=sys.integrate()\n")
+
+                    # For outputs other than qs and us.
+                    other_outputs = []
+                    for i in self.outputs:
+                        if i not in q_add_u:
+                            if "[" in i:
+                                other_outputs.append((i[:-3] + i[-2], i[:-3] + "[" + str(int(i[-2])-1) + "]"))
+                            else:
+                                other_outputs.append((i, i))
+
+                    for i in other_outputs:
+                        self.write(i[0] + "_out" + " = " + "[]\n")
+                    if other_outputs:
+                        self.write("for i in y:\n")
+                        self.write("    q_u_dict = dict(zip(sys.coordinates+sys.speeds, i))\n")
+                        for i in other_outputs:
+                            self.write(" "*4 + i[0] + "_out" + ".append(" + i[1] + ".subs(q_u_dict)" +
+                                    ".subs(sys.constants).evalf())\n")
+
+        # Standalone function calls (used for dual functions)
+        def exitFunctionCall(self, ctx):
+            # Basically deals with standalone function calls ie functions which are not a part of
+            # expressions and assignments. Autolev Dual functions can both appear in standalone
+            # function calls and also on the right hand side as part of expr or assignment.
+
+            # Dual functions are indicated by a * in the comments below
+
+            # Checks if the function is a statement on its own
+            if ctx.parentCtx.getRuleIndex() == AutolevParser.RULE_stat:
+                func_name = ctx.getChild(0).getText().lower()
+                # Expand(E, n:m) *
+                if func_name == "expand":
+                    # If the first argument is a pre declared variable.
+                    expr = self.getValue(ctx.expr(0))
+                    symbol = self.symbol_table[ctx.expr(0).getText().lower()]
+                    if ctx.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"):
+                        self.write(symbol + " = " + "_sm.Matrix([i.expand() for i in " + expr + "])" +
+                                   ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])\n")
+                    else:
+                        self.write(symbol + " = " + symbol + "." + "expand()\n")
+
+                # Factor(E, x) *
+                elif func_name == "factor":
+                    expr = self.getValue(ctx.expr(0))
+                    symbol = self.symbol_table[ctx.expr(0).getText().lower()]
+                    if ctx.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"):
+                        self.write(symbol + " = " + "_sm.Matrix([_sm.factor(i," + self.getValue(ctx.expr(1)) +
+                                   ") for i in " + expr + "])" +
+                                   ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])\n")
+                    else:
+                        self.write(expr + " = " + "_sm.factor(" + expr + ", " +
+                                   self.getValue(ctx.expr(1)) + ")\n")
+
+                # Solve(Zero, x, y)
+                elif func_name == "solve":
+                    l = []
+                    l2 = []
+                    num = 0
+                    for i in range(1, ctx.getChildCount()):
+                        if ctx.getChild(i).getText() == ",":
+                            num+=1
+                        try:
+                            l.append(self.getValue(ctx.getChild(i)))
+                        except Exception:
+                            l.append(ctx.getChild(i).getText())
+
+                        if i != 2:
+                            try:
+                                l2.append(self.getValue(ctx.getChild(i)))
+                            except Exception:
+                                pass
+
+                    for i in l2:
+                        self.explicit.update({i: "_sm.solve" + "".join(l) + "[" + i + "]"})
+
+                    self.write("print(_sm.solve" + "".join(l) + ")\n")
+
+                # Arrange(y, n, x) *
+                elif func_name == "arrange":
+                    expr = self.getValue(ctx.expr(0))
+                    symbol = self.symbol_table[ctx.expr(0).getText().lower()]
+
+                    if ctx.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"):
+                        self.write(symbol + " = " + "_sm.Matrix([i.collect(" + self.getValue(ctx.expr(2)) +
+                                   ")" + "for i in " + expr + "])" +
+                                   ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])\n")
+                    else:
+                        self.write(self.getValue(ctx.expr(0)) + ".collect(" +
+                                   self.getValue(ctx.expr(2)) + ")\n")
+
+                # Eig(M, EigenValue, EigenVec)
+                elif func_name == "eig":
+                    self.symbol_table.update({ctx.expr(1).getText().lower(): ctx.expr(1).getText().lower()})
+                    self.symbol_table.update({ctx.expr(2).getText().lower(): ctx.expr(2).getText().lower()})
+                    # _sm.Matrix([i.evalf() for i in (i_s_so).eigenvals().keys()])
+                    self.write(ctx.expr(1).getText().lower() + " = " +
+                               "_sm.Matrix([i.evalf() for i in " +
+                               "(" + self.getValue(ctx.expr(0)) + ")" + ".eigenvals().keys()])\n")
+                    # _sm.Matrix([i[2][0].evalf() for i in (i_s_o).eigenvects()]).reshape(i_s_o.shape[0], i_s_o.shape[1])
+                    self.write(ctx.expr(2).getText().lower() + " = " +
+                               "_sm.Matrix([i[2][0].evalf() for i in " + "(" + self.getValue(ctx.expr(0)) + ")" +
+                               ".eigenvects()]).reshape(" + self.getValue(ctx.expr(0)) + ".shape[0], " +
+                               self.getValue(ctx.expr(0)) + ".shape[1])\n")
+
+                # Simprot(N, A, 3, qA)
+                elif func_name == "simprot":
+                    # A.orient(N, 'Axis', qA, N.z)
+                    if self.type2[ctx.expr(0).getText().lower()] == "frame":
+                        frame1 = self.symbol_table2[ctx.expr(0).getText().lower()]
+                    elif self.type2[ctx.expr(0).getText().lower()] == "bodies":
+                        frame1 = self.symbol_table2[ctx.expr(0).getText().lower()] + "_f"
+                    if self.type2[ctx.expr(1).getText().lower()] == "frame":
+                        frame2 = self.symbol_table2[ctx.expr(1).getText().lower()]
+                    elif self.type2[ctx.expr(1).getText().lower()] == "bodies":
+                        frame2 = self.symbol_table2[ctx.expr(1).getText().lower()] + "_f"
+                    e2 = ""
+                    if ctx.expr(2).getText()[0] == "-":
+                        e2 = "-1*"
+                    if ctx.expr(2).getText() in ("1", "-1"):
+                        e = frame1 + ".x"
+                    elif ctx.expr(2).getText() in ("2", "-2"):
+                        e = frame1 + ".y"
+                    elif ctx.expr(2).getText() in ("3", "-3"):
+                        e = frame1 + ".z"
+                    else:
+                        e = self.getValue(ctx.expr(2))
+                        e2 = ""
+
+                    if "degrees" in self.settings.keys() and self.settings["degrees"] == "off":
+                        value = self.getValue(ctx.expr(3))
+                    else:
+                        if ctx.expr(3) in self.numeric_expr:
+                            value = "_np.deg2rad(" + self.getValue(ctx.expr(3)) + ")"
+                        else:
+                            value = self.getValue(ctx.expr(3))
+                    self.write(frame2 + ".orient(" + frame1 +
+                               ", " + "'Axis'" + ", " + "[" + value +
+                               ", " + e2 + e + "]" + ")\n")
+
+                # Express(A2>, B) *
+                elif func_name == "express":
+                    if self.type2[ctx.expr(1).getText().lower()] == "bodies":
+                        f = "_f"
+                    else:
+                        f = ""
+
+                    if '_' in ctx.expr(0).getText().lower() and ctx.expr(0).getText().count('_') == 2:
+                        vec = ctx.expr(0).getText().lower().replace(">", "").split('_')
+                        v1 = self.symbol_table2[vec[1]]
+                        v2 = self.symbol_table2[vec[2]]
+                        if vec[0] == "p":
+                            self.write(v2 + ".set_pos(" + v1 + ", " + "(" + self.getValue(ctx.expr(0)) +
+                                    ")" + ".express(" + self.symbol_table2[ctx.expr(1).getText().lower()] + f + "))\n")
+                        elif vec[0] == "v":
+                            self.write(v1 + ".set_vel(" + v2 + ", " + "(" + self.getValue(ctx.expr(0)) +
+                                    ")" + ".express(" + self.symbol_table2[ctx.expr(1).getText().lower()] + f + "))\n")
+                        elif vec[0] == "a":
+                            self.write(v1 + ".set_acc(" + v2 + ", " + "(" + self.getValue(ctx.expr(0)) +
+                                    ")" + ".express(" + self.symbol_table2[ctx.expr(1).getText().lower()] + f + "))\n")
+                        else:
+                            self.write(self.getValue(ctx.expr(0)) + " = " + "(" + self.getValue(ctx.expr(0)) + ")" + ".express(" +
+                                        self.symbol_table2[ctx.expr(1).getText().lower()] + f + ")\n")
+                    else:
+                        self.write(self.getValue(ctx.expr(0)) + " = " + "(" + self.getValue(ctx.expr(0)) + ")" + ".express(" +
+                                    self.symbol_table2[ctx.expr(1).getText().lower()] + f + ")\n")
+
+                # Angvel(A, B)
+                elif func_name == "angvel":
+                    self.write("print(" + self.symbol_table2[ctx.expr(1).getText().lower()] +
+                               ".ang_vel_in(" + self.symbol_table2[ctx.expr(0).getText().lower()] + "))\n")
+
+                # v2pts(N, A, O, P)
+                elif func_name in ("v2pts", "a2pts", "v2pt", "a1pt"):
+                    if func_name == "v2pts":
+                        text = ".v2pt_theory("
+                    elif func_name == "a2pts":
+                        text = ".a2pt_theory("
+                    elif func_name == "v1pt":
+                        text = ".v1pt_theory("
+                    elif func_name == "a1pt":
+                        text = ".a1pt_theory("
+                    if self.type2[ctx.expr(1).getText().lower()] == "frame":
+                        frame = self.symbol_table2[ctx.expr(1).getText().lower()]
+                    elif self.type2[ctx.expr(1).getText().lower()] == "bodies":
+                        frame = self.symbol_table2[ctx.expr(1).getText().lower()] + "_f"
+                    expr_list = []
+                    for i in range(2, 4):
+                        if self.type2[ctx.expr(i).getText().lower()] == "point":
+                            expr_list.append(self.symbol_table2[ctx.expr(i).getText().lower()])
+                        elif self.type2[ctx.expr(i).getText().lower()] == "particle":
+                            expr_list.append(self.symbol_table2[ctx.expr(i).getText().lower()] + ".point")
+
+                    self.write(expr_list[1] + text + expr_list[0] +
+                               "," + self.symbol_table2[ctx.expr(0).getText().lower()] + "," +
+                               frame + ")\n")
+
+                # Gravity(g*N1>)
+                elif func_name == "gravity":
+                    for i in self.bodies.keys():
+                        if self.type2[i] == "bodies":
+                            e = self.symbol_table2[i] + ".masscenter"
+                        elif self.type2[i] == "particle":
+                            e = self.symbol_table2[i] + ".point"
+                        if e in self.forces.keys():
+                            self.forces[e] = self.forces[e] + self.symbol_table2[i] +\
+                                             ".mass*(" + self.getValue(ctx.expr(0)) + ")"
+                        else:
+                            self.forces.update({e: self.symbol_table2[i] +
+                                               ".mass*(" + self.getValue(ctx.expr(0)) + ")"})
+                        self.write("force_" + i + " = " + self.forces[e] + "\n")
+
+                # Explicit(EXPRESS(IMPLICIT>,C))
+                elif func_name == "explicit":
+                    if ctx.expr(0) in self.vector_expr:
+                        self.vector_expr.append(ctx)
+                    expr = self.getValue(ctx.expr(0))
+                    if self.explicit.keys():
+                        explicit_list = []
+                        for i in self.explicit.keys():
+                            explicit_list.append(i + ":" + self.explicit[i])
+                        if '_' in ctx.expr(0).getText().lower() and ctx.expr(0).getText().count('_') == 2:
+                            vec = ctx.expr(0).getText().lower().replace(">", "").split('_')
+                            v1 = self.symbol_table2[vec[1]]
+                            v2 = self.symbol_table2[vec[2]]
+                            if vec[0] == "p":
+                                self.write(v2 + ".set_pos(" + v1 + ", " + "(" + expr +
+                                        ")" + ".subs({" + ", ".join(explicit_list) + "}))\n")
+                            elif vec[0] == "v":
+                                self.write(v2 + ".set_vel(" + v1 + ", " + "(" + expr +
+                                        ")" + ".subs({" + ", ".join(explicit_list) + "}))\n")
+                            elif vec[0] == "a":
+                                self.write(v2 + ".set_acc(" + v1 + ", " + "(" + expr +
+                                        ")" + ".subs({" + ", ".join(explicit_list) + "}))\n")
+                            else:
+                                self.write(expr + " = " + "(" + expr + ")" + ".subs({" + ", ".join(explicit_list) + "})\n")
+                        else:
+                            self.write(expr + " = " + "(" + expr + ")" + ".subs({" + ", ".join(explicit_list) + "})\n")
+
+                # Force(O/Q, -k*Stretch*Uvec>)
+                elif func_name in ("force", "torque"):
+
+                    if "/" in ctx.expr(0).getText().lower():
+                        p1 = ctx.expr(0).getText().lower().split('/')[0]
+                        p2 = ctx.expr(0).getText().lower().split('/')[1]
+                        if self.type2[p1] in ("point", "frame"):
+                            pt1 = self.symbol_table2[p1]
+                        elif self.type2[p1] == "particle":
+                            pt1 = self.symbol_table2[p1] + ".point"
+                        if self.type2[p2] in ("point", "frame"):
+                            pt2 = self.symbol_table2[p2]
+                        elif self.type2[p2] == "particle":
+                            pt2 = self.symbol_table2[p2] + ".point"
+                        if pt1 in self.forces.keys():
+                            self.forces[pt1] = self.forces[pt1] + " + -1*("+self.getValue(ctx.expr(1)) + ")"
+                            self.write("force_" + p1 + " = " + self.forces[pt1] + "\n")
+                        else:
+                            self.forces.update({pt1: "-1*("+self.getValue(ctx.expr(1)) + ")"})
+                            self.write("force_" + p1 + " = " + self.forces[pt1] + "\n")
+                        if pt2 in self.forces.keys():
+                            self.forces[pt2] = self.forces[pt2] + "+ " + self.getValue(ctx.expr(1))
+                            self.write("force_" + p2 + " = " + self.forces[pt2] + "\n")
+                        else:
+                            self.forces.update({pt2: self.getValue(ctx.expr(1))})
+                            self.write("force_" + p2 + " = " + self.forces[pt2] + "\n")
+
+                    elif ctx.expr(0).getChildCount() == 1:
+                        p1 = ctx.expr(0).getText().lower()
+                        if self.type2[p1] in ("point", "frame"):
+                            pt1 = self.symbol_table2[p1]
+                        elif self.type2[p1] == "particle":
+                            pt1 = self.symbol_table2[p1] + ".point"
+                        if pt1 in self.forces.keys():
+                            self.forces[pt1] = self.forces[pt1] + "+ -1*(" + self.getValue(ctx.expr(1)) + ")"
+                        else:
+                            self.forces.update({pt1: "-1*(" + self.getValue(ctx.expr(1)) + ")"})
+
+                # Constrain(Dependent[qB])
+                elif func_name == "constrain":
+                    if ctx.getChild(2).getChild(0).getText().lower() == "dependent":
+                        self.write("velocity_constraints = [i for i in dependent]\n")
+                    x = (ctx.expr(0).getChildCount()-2)//2
+                    for i in range(x):
+                        self.dependent_variables.append(self.getValue(ctx.expr(0).expr(i)))
+
+                # Kane()
+                elif func_name == "kane":
+                    if ctx.getChildCount() == 3:
+                        self.kane_type = "no_args"
+
+        # Settings
+        def exitSettings(self, ctx):
+            # Stores settings like Complex on/off, Degrees on/off etc in self.settings.
+            try:
+                self.settings.update({ctx.getChild(0).getText().lower():
+                                     ctx.getChild(1).getText().lower()})
+            except Exception:
+                pass
+
+        def exitMassDecl2(self, ctx):
+            # Used for declaring the masses of particles and rigidbodies.
+            particle = self.symbol_table2[ctx.getChild(0).getText().lower()]
+            if ctx.getText().count("=") == 2:
+                if ctx.expr().expr(1) in self.numeric_expr:
+                    e = "_sm.S(" + self.getValue(ctx.expr().expr(1)) + ")"
+                else:
+                    e = self.getValue(ctx.expr().expr(1))
+                self.symbol_table.update({ctx.expr().expr(0).getText().lower(): ctx.expr().expr(0).getText().lower()})
+                self.write(ctx.expr().expr(0).getText().lower() + " = " + e + "\n")
+                mass = ctx.expr().expr(0).getText().lower()
+            else:
+                try:
+                    if ctx.expr() in self.numeric_expr:
+                        mass = "_sm.S(" + self.getValue(ctx.expr()) + ")"
+                    else:
+                        mass = self.getValue(ctx.expr())
+                except Exception:
+                    a_text = ctx.expr().getText().lower()
+                    self.symbol_table.update({a_text: a_text})
+                    self.type.update({a_text: "constants"})
+                    self.write(a_text + " = " + "_sm.symbols('" + a_text + "')\n")
+                    mass = a_text
+
+            self.write(particle + ".mass = " + mass + "\n")
+
+        def exitInertiaDecl(self, ctx):
+            inertia_list = []
+            try:
+                ctx.ID(1).getText()
+                num = 5
+            except Exception:
+                num = 2
+            for i in range((ctx.getChildCount()-num)//2):
+                try:
+                    if ctx.expr(i) in self.numeric_expr:
+                        inertia_list.append("_sm.S(" + self.getValue(ctx.expr(i)) + ")")
+                    else:
+                        inertia_list.append(self.getValue(ctx.expr(i)))
+                except Exception:
+                    a_text = ctx.expr(i).getText().lower()
+                    self.symbol_table.update({a_text: a_text})
+                    self.type.update({a_text: "constants"})
+                    self.write(a_text + " = " + "_sm.symbols('" + a_text + "')\n")
+                    inertia_list.append(a_text)
+
+            if len(inertia_list) < 6:
+                for i in range(6-len(inertia_list)):
+                    inertia_list.append("0")
+            # body_a.inertia = (_me.inertia(body_a, I1, I2, I3, 0, 0, 0), body_a_cm)
+            try:
+                frame = self.symbol_table2[ctx.ID(1).getText().lower()]
+                point = self.symbol_table2[ctx.ID(0).getText().lower().split('_')[1]]
+                body = self.symbol_table2[ctx.ID(0).getText().lower().split('_')[0]]
+                self.inertia_point.update({ctx.ID(0).getText().lower().split('_')[0]
+                                          : ctx.ID(0).getText().lower().split('_')[1]})
+                self.write(body + ".inertia" + " = " + "(_me.inertia(" + frame + ", " +
+                           ", ".join(inertia_list) + "), " + point + ")\n")
+
+            except Exception:
+                body_name = self.symbol_table2[ctx.ID(0).getText().lower()]
+                body_name_cm = body_name + "_cm"
+                self.inertia_point.update({ctx.ID(0).getText().lower(): ctx.ID(0).getText().lower() + "o"})
+                self.write(body_name + ".inertia" + " = " + "(_me.inertia(" + body_name + "_f" + ", " +
+                           ", ".join(inertia_list) + "), " + body_name_cm + ")\n")
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_parse_autolev_antlr.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_parse_autolev_antlr.py
new file mode 100644
index 0000000000000000000000000000000000000000..e43924aac30903ade996b31921d3960afae90284
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/_parse_autolev_antlr.py
@@ -0,0 +1,38 @@
+from importlib.metadata import version
+from sympy.external import import_module
+
+
+autolevparser = import_module('sympy.parsing.autolev._antlr.autolevparser',
+                              import_kwargs={'fromlist': ['AutolevParser']})
+autolevlexer = import_module('sympy.parsing.autolev._antlr.autolevlexer',
+                             import_kwargs={'fromlist': ['AutolevLexer']})
+autolevlistener = import_module('sympy.parsing.autolev._antlr.autolevlistener',
+                                import_kwargs={'fromlist': ['AutolevListener']})
+
+AutolevParser = getattr(autolevparser, 'AutolevParser', None)
+AutolevLexer = getattr(autolevlexer, 'AutolevLexer', None)
+AutolevListener = getattr(autolevlistener, 'AutolevListener', None)
+
+
+def parse_autolev(autolev_code, include_numeric):
+    antlr4 = import_module('antlr4')
+    if not antlr4 or not version('antlr4-python3-runtime').startswith('4.11'):
+        raise ImportError("Autolev parsing requires the antlr4 Python package,"
+                          " provided by pip (antlr4-python3-runtime)"
+                          " conda (antlr-python-runtime), version 4.11")
+    try:
+        l = autolev_code.readlines()
+        input_stream = antlr4.InputStream("".join(l))
+    except Exception:
+        input_stream = antlr4.InputStream(autolev_code)
+
+    if AutolevListener:
+        from ._listener_autolev_antlr import MyListener
+        lexer = AutolevLexer(input_stream)
+        token_stream = antlr4.CommonTokenStream(lexer)
+        parser = AutolevParser(token_stream)
+        tree = parser.prog()
+        my_listener = MyListener(include_numeric)
+        walker = antlr4.ParseTreeWalker()
+        walker.walk(my_listener, tree)
+        return "".join(my_listener.output_code)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/README.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/README.txt
new file mode 100644
index 0000000000000000000000000000000000000000..946b006bac33544fadd2dc6d24c22240c8fbc8e4
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/README.txt
@@ -0,0 +1,9 @@
+# parsing/tests/test_autolev.py uses the .al files in this directory as inputs and checks
+# the equivalence of the parser generated codes and the respective .py files.
+
+# By default, this directory contains tests for all rules of the parser.
+
+# Additional tests consisting of full physics examples shall be made available soon in
+# the form of another repository. One shall be able to copy the contents of that repo
+# to this folder and use those tests after uncommenting the respective code in
+# parsing/tests/test_autolev.py.
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.al b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.al
new file mode 100644
index 0000000000000000000000000000000000000000..3bbb4d51b853bfd759df38d666a42adc1cbea190
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.al
@@ -0,0 +1,33 @@
+CONSTANTS G,LB,W,H
+MOTIONVARIABLES' THETA'',PHI'',OMEGA',ALPHA'
+NEWTONIAN N
+BODIES A,B
+SIMPROT(N,A,2,THETA)
+SIMPROT(A,B,3,PHI)
+POINT O
+LA = (LB-H/2)/2
+P_O_AO> = LA*A3>
+P_O_BO> = LB*A3>
+OMEGA = THETA'
+ALPHA = PHI'
+W_A_N> = OMEGA*N2>
+W_B_A> = ALPHA*A3>
+V_O_N> = 0>
+V2PTS(N, A, O, AO)
+V2PTS(N, A, O, BO)
+MASS A=MA, B=MB
+IAXX = 1/12*MA*(2*LA)^2
+IAYY = IAXX
+IAZZ = 0
+IBXX = 1/12*MB*H^2
+IBYY = 1/12*MB*(W^2+H^2)
+IBZZ = 1/12*MB*W^2
+INERTIA A, IAXX, IAYY, IAZZ
+INERTIA B, IBXX, IBYY, IBZZ
+GRAVITY(G*N3>)
+ZERO = FR() + FRSTAR()
+KANE()
+INPUT LB=0.2,H=0.1,W=0.2,MA=0.01,MB=0.1,G=9.81
+INPUT THETA = 90 DEG, PHI = 0.5 DEG, OMEGA=0, ALPHA=0
+INPUT TFINAL=10, INTEGSTP=0.02
+CODE DYNAMICS() some_filename.c
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py
new file mode 100644
index 0000000000000000000000000000000000000000..4435635720bb38f40366f55bb3ace0f6f6899284
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py
@@ -0,0 +1,55 @@
+import sympy.physics.mechanics as _me
+import sympy as _sm
+import math as m
+import numpy as _np
+
+g, lb, w, h = _sm.symbols('g lb w h', real=True)
+theta, phi, omega, alpha = _me.dynamicsymbols('theta phi omega alpha')
+theta_d, phi_d, omega_d, alpha_d = _me.dynamicsymbols('theta_ phi_ omega_ alpha_', 1)
+theta_dd, phi_dd = _me.dynamicsymbols('theta_ phi_', 2)
+frame_n = _me.ReferenceFrame('n')
+body_a_cm = _me.Point('a_cm')
+body_a_cm.set_vel(frame_n, 0)
+body_a_f = _me.ReferenceFrame('a_f')
+body_a = _me.RigidBody('a', body_a_cm, body_a_f, _sm.symbols('m'), (_me.outer(body_a_f.x,body_a_f.x),body_a_cm))
+body_b_cm = _me.Point('b_cm')
+body_b_cm.set_vel(frame_n, 0)
+body_b_f = _me.ReferenceFrame('b_f')
+body_b = _me.RigidBody('b', body_b_cm, body_b_f, _sm.symbols('m'), (_me.outer(body_b_f.x,body_b_f.x),body_b_cm))
+body_a_f.orient(frame_n, 'Axis', [theta, frame_n.y])
+body_b_f.orient(body_a_f, 'Axis', [phi, body_a_f.z])
+point_o = _me.Point('o')
+la = (lb-h/2)/2
+body_a_cm.set_pos(point_o, la*body_a_f.z)
+body_b_cm.set_pos(point_o, lb*body_a_f.z)
+body_a_f.set_ang_vel(frame_n, omega*frame_n.y)
+body_b_f.set_ang_vel(body_a_f, alpha*body_a_f.z)
+point_o.set_vel(frame_n, 0)
+body_a_cm.v2pt_theory(point_o,frame_n,body_a_f)
+body_b_cm.v2pt_theory(point_o,frame_n,body_a_f)
+ma = _sm.symbols('ma')
+body_a.mass = ma
+mb = _sm.symbols('mb')
+body_b.mass = mb
+iaxx = 1/12*ma*(2*la)**2
+iayy = iaxx
+iazz = 0
+ibxx = 1/12*mb*h**2
+ibyy = 1/12*mb*(w**2+h**2)
+ibzz = 1/12*mb*w**2
+body_a.inertia = (_me.inertia(body_a_f, iaxx, iayy, iazz, 0, 0, 0), body_a_cm)
+body_b.inertia = (_me.inertia(body_b_f, ibxx, ibyy, ibzz, 0, 0, 0), body_b_cm)
+force_a = body_a.mass*(g*frame_n.z)
+force_b = body_b.mass*(g*frame_n.z)
+kd_eqs = [theta_d - omega, phi_d - alpha]
+forceList = [(body_a.masscenter,body_a.mass*(g*frame_n.z)), (body_b.masscenter,body_b.mass*(g*frame_n.z))]
+kane = _me.KanesMethod(frame_n, q_ind=[theta,phi], u_ind=[omega, alpha], kd_eqs = kd_eqs)
+fr, frstar = kane.kanes_equations([body_a, body_b], forceList)
+zero = fr+frstar
+from pydy.system import System
+sys = System(kane, constants = {g:9.81, lb:0.2, w:0.2, h:0.1, ma:0.01, mb:0.1},
+specifieds={},
+initial_conditions={theta:_np.deg2rad(90), phi:_np.deg2rad(0.5), omega:0, alpha:0},
+times = _np.linspace(0.0, 10, 10/0.02))
+
+y=sys.integrate()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.al b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.al
new file mode 100644
index 0000000000000000000000000000000000000000..0b6d72a072e093a6cb048a0b7976041ee9c2f4f3
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.al
@@ -0,0 +1,25 @@
+MOTIONVARIABLES' Q{2}', U{2}'
+CONSTANTS L,M,G
+NEWTONIAN N
+FRAMES A,B
+SIMPROT(N, A, 3, Q1)
+SIMPROT(N, B, 3, Q2)
+W_A_N>=U1*N3>
+W_B_N>=U2*N3>
+POINT O
+PARTICLES P,R
+P_O_P> = L*A1>
+P_P_R> = L*B1>
+V_O_N> = 0>
+V2PTS(N, A, O, P)
+V2PTS(N, B, P, R)
+MASS P=M, R=M
+Q1' = U1
+Q2' = U2
+GRAVITY(G*N1>)
+ZERO = FR() + FRSTAR()
+KANE()
+INPUT M=1,G=9.81,L=1
+INPUT Q1=.1,Q2=.2,U1=0,U2=0
+INPUT TFINAL=10, INTEGSTP=.01
+CODE DYNAMICS() some_filename.c
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.py
new file mode 100644
index 0000000000000000000000000000000000000000..12c73c3b4b198399f4c45f5e00d556c859caff74
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.py
@@ -0,0 +1,39 @@
+import sympy.physics.mechanics as _me
+import sympy as _sm
+import math as m
+import numpy as _np
+
+q1, q2, u1, u2 = _me.dynamicsymbols('q1 q2 u1 u2')
+q1_d, q2_d, u1_d, u2_d = _me.dynamicsymbols('q1_ q2_ u1_ u2_', 1)
+l, m, g = _sm.symbols('l m g', real=True)
+frame_n = _me.ReferenceFrame('n')
+frame_a = _me.ReferenceFrame('a')
+frame_b = _me.ReferenceFrame('b')
+frame_a.orient(frame_n, 'Axis', [q1, frame_n.z])
+frame_b.orient(frame_n, 'Axis', [q2, frame_n.z])
+frame_a.set_ang_vel(frame_n, u1*frame_n.z)
+frame_b.set_ang_vel(frame_n, u2*frame_n.z)
+point_o = _me.Point('o')
+particle_p = _me.Particle('p', _me.Point('p_pt'), _sm.Symbol('m'))
+particle_r = _me.Particle('r', _me.Point('r_pt'), _sm.Symbol('m'))
+particle_p.point.set_pos(point_o, l*frame_a.x)
+particle_r.point.set_pos(particle_p.point, l*frame_b.x)
+point_o.set_vel(frame_n, 0)
+particle_p.point.v2pt_theory(point_o,frame_n,frame_a)
+particle_r.point.v2pt_theory(particle_p.point,frame_n,frame_b)
+particle_p.mass = m
+particle_r.mass = m
+force_p = particle_p.mass*(g*frame_n.x)
+force_r = particle_r.mass*(g*frame_n.x)
+kd_eqs = [q1_d - u1, q2_d - u2]
+forceList = [(particle_p.point,particle_p.mass*(g*frame_n.x)), (particle_r.point,particle_r.mass*(g*frame_n.x))]
+kane = _me.KanesMethod(frame_n, q_ind=[q1,q2], u_ind=[u1, u2], kd_eqs = kd_eqs)
+fr, frstar = kane.kanes_equations([particle_p, particle_r], forceList)
+zero = fr+frstar
+from pydy.system import System
+sys = System(kane, constants = {l:1, m:1, g:9.81},
+specifieds={},
+initial_conditions={q1:.1, q2:.2, u1:0, u2:0},
+times = _np.linspace(0.0, 10, 10/.01))
+
+y=sys.integrate()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.al b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.al
new file mode 100644
index 0000000000000000000000000000000000000000..4892e5ca8cb18cad6b14a2a37cbdc1f7fb8217ac
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.al
@@ -0,0 +1,19 @@
+CONSTANTS M,K,B,G
+MOTIONVARIABLES' POSITION',SPEED'
+VARIABLES O
+FORCE = O*SIN(T)
+NEWTONIAN CEILING
+POINTS ORIGIN
+V_ORIGIN_CEILING> = 0>
+PARTICLES BLOCK
+P_ORIGIN_BLOCK> = POSITION*CEILING1>
+MASS BLOCK=M
+V_BLOCK_CEILING>=SPEED*CEILING1>
+POSITION' = SPEED
+FORCE_MAGNITUDE = M*G-K*POSITION-B*SPEED+FORCE
+FORCE_BLOCK>=EXPLICIT(FORCE_MAGNITUDE*CEILING1>)
+ZERO = FR() + FRSTAR()
+KANE()
+INPUT TFINAL=10.0, INTEGSTP=0.01
+INPUT M=1.0, K=1.0, B=0.2, G=9.8, POSITION=0.1, SPEED=-1.0, O=2
+CODE DYNAMICS() dummy_file.c
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a5baab9642ff140e0ee81027a1e8f9152d7050c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.py
@@ -0,0 +1,31 @@
+import sympy.physics.mechanics as _me
+import sympy as _sm
+import math as m
+import numpy as _np
+
+m, k, b, g = _sm.symbols('m k b g', real=True)
+position, speed = _me.dynamicsymbols('position speed')
+position_d, speed_d = _me.dynamicsymbols('position_ speed_', 1)
+o = _me.dynamicsymbols('o')
+force = o*_sm.sin(_me.dynamicsymbols._t)
+frame_ceiling = _me.ReferenceFrame('ceiling')
+point_origin = _me.Point('origin')
+point_origin.set_vel(frame_ceiling, 0)
+particle_block = _me.Particle('block', _me.Point('block_pt'), _sm.Symbol('m'))
+particle_block.point.set_pos(point_origin, position*frame_ceiling.x)
+particle_block.mass = m
+particle_block.point.set_vel(frame_ceiling, speed*frame_ceiling.x)
+force_magnitude = m*g-k*position-b*speed+force
+force_block = (force_magnitude*frame_ceiling.x).subs({position_d:speed})
+kd_eqs = [position_d - speed]
+forceList = [(particle_block.point,(force_magnitude*frame_ceiling.x).subs({position_d:speed}))]
+kane = _me.KanesMethod(frame_ceiling, q_ind=[position], u_ind=[speed], kd_eqs = kd_eqs)
+fr, frstar = kane.kanes_equations([particle_block], forceList)
+zero = fr+frstar
+from pydy.system import System
+sys = System(kane, constants = {m:1.0, k:1.0, b:0.2, g:9.8},
+specifieds={_me.dynamicsymbols('t'):lambda x, t: t, o:2},
+initial_conditions={position:0.1, speed:-1*1.0},
+times = _np.linspace(0.0, 10.0, 10.0/0.01))
+
+y=sys.integrate()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.al b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.al
new file mode 100644
index 0000000000000000000000000000000000000000..74f5062d80926db7acd634a04759abce857087e5
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.al
@@ -0,0 +1,20 @@
+MOTIONVARIABLES' Q{2}''
+CONSTANTS L,M,G
+NEWTONIAN N
+POINT PN
+V_PN_N> = 0>
+THETA1 = ATAN(Q2/Q1)
+FRAMES A
+SIMPROT(N, A, 3, THETA1)
+PARTICLES P
+P_PN_P> = Q1*N1>+Q2*N2>
+MASS P=M
+V_P_N>=DT(P_P_PN>, N)
+F_V = DOT(EXPRESS(V_P_N>,A), A1>)
+GRAVITY(G*N1>)
+DEPENDENT[1] = F_V
+CONSTRAIN(DEPENDENT[Q1'])
+ZERO=FR()+FRSTAR()
+F_C = MAG(P_P_PN>)-L
+CONFIG[1]=F_C
+ZERO[2]=CONFIG[1]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc972ebd518e77da5e1902c149f2699979865e7f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.py
@@ -0,0 +1,36 @@
+import sympy.physics.mechanics as _me
+import sympy as _sm
+import math as m
+import numpy as _np
+
+q1, q2 = _me.dynamicsymbols('q1 q2')
+q1_d, q2_d = _me.dynamicsymbols('q1_ q2_', 1)
+q1_dd, q2_dd = _me.dynamicsymbols('q1_ q2_', 2)
+l, m, g = _sm.symbols('l m g', real=True)
+frame_n = _me.ReferenceFrame('n')
+point_pn = _me.Point('pn')
+point_pn.set_vel(frame_n, 0)
+theta1 = _sm.atan(q2/q1)
+frame_a = _me.ReferenceFrame('a')
+frame_a.orient(frame_n, 'Axis', [theta1, frame_n.z])
+particle_p = _me.Particle('p', _me.Point('p_pt'), _sm.Symbol('m'))
+particle_p.point.set_pos(point_pn, q1*frame_n.x+q2*frame_n.y)
+particle_p.mass = m
+particle_p.point.set_vel(frame_n, (point_pn.pos_from(particle_p.point)).dt(frame_n))
+f_v = _me.dot((particle_p.point.vel(frame_n)).express(frame_a), frame_a.x)
+force_p = particle_p.mass*(g*frame_n.x)
+dependent = _sm.Matrix([[0]])
+dependent[0] = f_v
+velocity_constraints = [i for i in dependent]
+u_q1_d = _me.dynamicsymbols('u_q1_d')
+u_q2_d = _me.dynamicsymbols('u_q2_d')
+kd_eqs = [q1_d-u_q1_d, q2_d-u_q2_d]
+forceList = [(particle_p.point,particle_p.mass*(g*frame_n.x))]
+kane = _me.KanesMethod(frame_n, q_ind=[q1,q2], u_ind=[u_q2_d], u_dependent=[u_q1_d], kd_eqs = kd_eqs, velocity_constraints = velocity_constraints)
+fr, frstar = kane.kanes_equations([particle_p], forceList)
+zero = fr+frstar
+f_c = point_pn.pos_from(particle_p.point).magnitude()-l
+config = _sm.Matrix([[0]])
+config[0] = f_c
+zero = zero.row_insert(zero.shape[0], _sm.Matrix([[0]]))
+zero[zero.shape[0]-1] = config[0]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest1.al b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest1.al
new file mode 100644
index 0000000000000000000000000000000000000000..457e79fd646677c0decdc69f921bc05e9e0dcf51
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest1.al
@@ -0,0 +1,8 @@
+% ruletest1.al
+CONSTANTS F = 3, G = 9.81
+CONSTANTS A, B
+CONSTANTS S, S1, S2+, S3+, S4-
+CONSTANTS K{4}, L{1:3}, P{1:2,1:3}
+CONSTANTS C{2,3}
+E1 = A*F + S2 - G
+E2 = F^2 + K3*K2*G
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest1.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest1.py
new file mode 100644
index 0000000000000000000000000000000000000000..8466392ac930f13f2419c9c04eef9dcc2884e9bd
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest1.py
@@ -0,0 +1,15 @@
+import sympy.physics.mechanics as _me
+import sympy as _sm
+import math as m
+import numpy as _np
+
+f = _sm.S(3)
+g = _sm.S(9.81)
+a, b = _sm.symbols('a b', real=True)
+s, s1 = _sm.symbols('s s1', real=True)
+s2, s3 = _sm.symbols('s2 s3', real=True, nonnegative=True)
+s4 = _sm.symbols('s4', real=True, nonpositive=True)
+k1, k2, k3, k4, l1, l2, l3, p11, p12, p13, p21, p22, p23 = _sm.symbols('k1 k2 k3 k4 l1 l2 l3 p11 p12 p13 p21 p22 p23', real=True)
+c11, c12, c13, c21, c22, c23 = _sm.symbols('c11 c12 c13 c21 c22 c23', real=True)
+e1 = a*f+s2-g
+e2 = f**2+k3*k2*g
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest10.al b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest10.al
new file mode 100644
index 0000000000000000000000000000000000000000..9d5f76f063c43bcb5e2a8d4f29619a6952abf9e5
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest10.al
@@ -0,0 +1,58 @@
+% ruletest10.al
+
+VARIABLES X,Y
+COMPLEX ON
+CONSTANTS A,B
+E = A*(B*X+Y)^2
+M = [E;E]
+EXPAND(E)
+EXPAND(M)
+FACTOR(E,X)
+FACTOR(M,X)
+
+EQN[1] = A*X + B*Y
+EQN[2] = 2*A*X - 3*B*Y
+SOLVE(EQN, X, Y)
+RHS_Y = RHS(Y)
+E = (X+Y)^2 + 2*X^2
+ARRANGE(E, 2, X)
+
+CONSTANTS A,B,C
+M = [A,B;C,0]
+M2 = EVALUATE(M,A=1,B=2,C=3)
+EIG(M2, EIGVALUE, EIGVEC)
+
+NEWTONIAN N
+FRAMES A
+SIMPROT(N, A, N1>, X)
+DEGREES OFF
+SIMPROT(N, A, N1>, PI/2)
+
+CONSTANTS C{3}
+V> = C1*A1> + C2*A2> + C3*A3>
+POINTS O, P
+P_P_O> = C1*A1>
+EXPRESS(V>,N)
+EXPRESS(P_P_O>,N)
+W_A_N> = C3*A3>
+ANGVEL(A,N)
+
+V2PTS(N,A,O,P)
+PARTICLES P{2}
+V2PTS(N,A,P1,P2)
+A2PTS(N,A,P1,P)
+
+BODIES B{2}
+CONSTANT G
+GRAVITY(G*N1>)
+
+VARIABLE Z
+V> = X*A1> + Y*A3>
+P_P_O> = X*A1> + Y*A2>
+X = 2*Z
+Y = Z
+EXPLICIT(V>)
+EXPLICIT(P_P_O>)
+
+FORCE(O/P1, X*Y*A1>)
+FORCE(P2, X*Y*A1>)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest10.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest10.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b9674e47d5f6132c5a79a33b9d8d55a131942d6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest10.py
@@ -0,0 +1,64 @@
+import sympy.physics.mechanics as _me
+import sympy as _sm
+import math as m
+import numpy as _np
+
+x, y = _me.dynamicsymbols('x y')
+a, b = _sm.symbols('a b', real=True)
+e = a*(b*x+y)**2
+m = _sm.Matrix([e,e]).reshape(2, 1)
+e = e.expand()
+m = _sm.Matrix([i.expand() for i in m]).reshape((m).shape[0], (m).shape[1])
+e = _sm.factor(e, x)
+m = _sm.Matrix([_sm.factor(i,x) for i in m]).reshape((m).shape[0], (m).shape[1])
+eqn = _sm.Matrix([[0]])
+eqn[0] = a*x+b*y
+eqn = eqn.row_insert(eqn.shape[0], _sm.Matrix([[0]]))
+eqn[eqn.shape[0]-1] = 2*a*x-3*b*y
+print(_sm.solve(eqn,x,y))
+rhs_y = _sm.solve(eqn,x,y)[y]
+e = (x+y)**2+2*x**2
+e.collect(x)
+a, b, c = _sm.symbols('a b c', real=True)
+m = _sm.Matrix([a,b,c,0]).reshape(2, 2)
+m2 = _sm.Matrix([i.subs({a:1,b:2,c:3}) for i in m]).reshape((m).shape[0], (m).shape[1])
+eigvalue = _sm.Matrix([i.evalf() for i in (m2).eigenvals().keys()])
+eigvec = _sm.Matrix([i[2][0].evalf() for i in (m2).eigenvects()]).reshape(m2.shape[0], m2.shape[1])
+frame_n = _me.ReferenceFrame('n')
+frame_a = _me.ReferenceFrame('a')
+frame_a.orient(frame_n, 'Axis', [x, frame_n.x])
+frame_a.orient(frame_n, 'Axis', [_sm.pi/2, frame_n.x])
+c1, c2, c3 = _sm.symbols('c1 c2 c3', real=True)
+v = c1*frame_a.x+c2*frame_a.y+c3*frame_a.z
+point_o = _me.Point('o')
+point_p = _me.Point('p')
+point_o.set_pos(point_p, c1*frame_a.x)
+v = (v).express(frame_n)
+point_o.set_pos(point_p, (point_o.pos_from(point_p)).express(frame_n))
+frame_a.set_ang_vel(frame_n, c3*frame_a.z)
+print(frame_n.ang_vel_in(frame_a))
+point_p.v2pt_theory(point_o,frame_n,frame_a)
+particle_p1 = _me.Particle('p1', _me.Point('p1_pt'), _sm.Symbol('m'))
+particle_p2 = _me.Particle('p2', _me.Point('p2_pt'), _sm.Symbol('m'))
+particle_p2.point.v2pt_theory(particle_p1.point,frame_n,frame_a)
+point_p.a2pt_theory(particle_p1.point,frame_n,frame_a)
+body_b1_cm = _me.Point('b1_cm')
+body_b1_cm.set_vel(frame_n, 0)
+body_b1_f = _me.ReferenceFrame('b1_f')
+body_b1 = _me.RigidBody('b1', body_b1_cm, body_b1_f, _sm.symbols('m'), (_me.outer(body_b1_f.x,body_b1_f.x),body_b1_cm))
+body_b2_cm = _me.Point('b2_cm')
+body_b2_cm.set_vel(frame_n, 0)
+body_b2_f = _me.ReferenceFrame('b2_f')
+body_b2 = _me.RigidBody('b2', body_b2_cm, body_b2_f, _sm.symbols('m'), (_me.outer(body_b2_f.x,body_b2_f.x),body_b2_cm))
+g = _sm.symbols('g', real=True)
+force_p1 = particle_p1.mass*(g*frame_n.x)
+force_p2 = particle_p2.mass*(g*frame_n.x)
+force_b1 = body_b1.mass*(g*frame_n.x)
+force_b2 = body_b2.mass*(g*frame_n.x)
+z = _me.dynamicsymbols('z')
+v = x*frame_a.x+y*frame_a.z
+point_o.set_pos(point_p, x*frame_a.x+y*frame_a.y)
+v = (v).subs({x:2*z, y:z})
+point_o.set_pos(point_p, (point_o.pos_from(point_p)).subs({x:2*z, y:z}))
+force_o = -1*(x*y*frame_a.x)
+force_p1 = particle_p1.mass*(g*frame_n.x)+ x*y*frame_a.x
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest11.al b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest11.al
new file mode 100644
index 0000000000000000000000000000000000000000..60934c1ca563024828110bfe984a90d5686b89e4
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest11.al
@@ -0,0 +1,6 @@
+VARIABLES X, Y
+CONSTANTS A{1:2, 1:2}, B{1:2}
+EQN[1] = A11*x + A12*y - B1
+EQN[2] = A21*x + A22*y - B2
+INPUT A11=2, A12=5, A21=3, A22=4, B1=7, B2=6
+CODE ALGEBRAIC(EQN, X, Y) some_filename.c
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest11.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest11.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ec2397ea96261d7b582d1f699e3897caae88f20
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest11.py
@@ -0,0 +1,14 @@
+import sympy.physics.mechanics as _me
+import sympy as _sm
+import math as m
+import numpy as _np
+
+x, y = _me.dynamicsymbols('x y')
+a11, a12, a21, a22, b1, b2 = _sm.symbols('a11 a12 a21 a22 b1 b2', real=True)
+eqn = _sm.Matrix([[0]])
+eqn[0] = a11*x+a12*y-b1
+eqn = eqn.row_insert(eqn.shape[0], _sm.Matrix([[0]]))
+eqn[eqn.shape[0]-1] = a21*x+a22*y-b2
+eqn_list = []
+for i in eqn:  eqn_list.append(i.subs({a11:2, a12:5, a21:3, a22:4, b1:7, b2:6}))
+print(_sm.linsolve(eqn_list, x,y))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest12.al b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest12.al
new file mode 100644
index 0000000000000000000000000000000000000000..f147f55afd1438436767960e0487d5d9e7161c8f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest12.al
@@ -0,0 +1,7 @@
+VARIABLES X,Y
+CONSTANTS A,B,R
+EQN[1] = A*X^3+B*Y^2-R
+EQN[2] = A*SIN(X)^2 + B*COS(2*Y) - R^2
+INPUT A=2.0, B=3.0, R=1.0
+INPUT X = 30 DEG, Y = 3.14
+CODE NONLINEAR(EQN,X,Y) some_filename.c
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest12.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest12.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d7d996fa649f796a536dba20c1a36554acd8046
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest12.py
@@ -0,0 +1,14 @@
+import sympy.physics.mechanics as _me
+import sympy as _sm
+import math as m
+import numpy as _np
+
+x, y = _me.dynamicsymbols('x y')
+a, b, r = _sm.symbols('a b r', real=True)
+eqn = _sm.Matrix([[0]])
+eqn[0] = a*x**3+b*y**2-r
+eqn = eqn.row_insert(eqn.shape[0], _sm.Matrix([[0]]))
+eqn[eqn.shape[0]-1] = a*_sm.sin(x)**2+b*_sm.cos(2*y)-r**2
+matrix_list = []
+for i in eqn:matrix_list.append(i.subs({a:2.0, b:3.0, r:1.0}))
+print(_sm.nsolve(matrix_list,(x,y),(_np.deg2rad(30),3.14)))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest2.al b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest2.al
new file mode 100644
index 0000000000000000000000000000000000000000..17937e58bd20a9fb82f44ccd05f0c081a1aa6c9b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest2.al
@@ -0,0 +1,12 @@
+% ruletest2.al
+VARIABLES X1,X2
+SPECIFIED F1 = X1*X2 + 3*X1^2
+SPECIFIED F2=X1*T+X2*T^2
+VARIABLE X', Y''
+MOTIONVARIABLES Q{3}, U{2}
+VARIABLES P{2}'
+VARIABLE W{3}', R{2}''
+VARIABLES C{1:2, 1:2}
+VARIABLES D{1,3}
+VARIABLES J{1:2}
+IMAGINARY N
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest2.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest2.py
new file mode 100644
index 0000000000000000000000000000000000000000..31c1d9974c2292466b805b91f8254bffaa94e2ac
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest2.py
@@ -0,0 +1,22 @@
+import sympy.physics.mechanics as _me
+import sympy as _sm
+import math as m
+import numpy as _np
+
+x1, x2 = _me.dynamicsymbols('x1 x2')
+f1 = x1*x2+3*x1**2
+f2 = x1*_me.dynamicsymbols._t+x2*_me.dynamicsymbols._t**2
+x, y = _me.dynamicsymbols('x y')
+x_d, y_d = _me.dynamicsymbols('x_ y_', 1)
+y_dd = _me.dynamicsymbols('y_', 2)
+q1, q2, q3, u1, u2 = _me.dynamicsymbols('q1 q2 q3 u1 u2')
+p1, p2 = _me.dynamicsymbols('p1 p2')
+p1_d, p2_d = _me.dynamicsymbols('p1_ p2_', 1)
+w1, w2, w3, r1, r2 = _me.dynamicsymbols('w1 w2 w3 r1 r2')
+w1_d, w2_d, w3_d, r1_d, r2_d = _me.dynamicsymbols('w1_ w2_ w3_ r1_ r2_', 1)
+r1_dd, r2_dd = _me.dynamicsymbols('r1_ r2_', 2)
+c11, c12, c21, c22 = _me.dynamicsymbols('c11 c12 c21 c22')
+d11, d12, d13 = _me.dynamicsymbols('d11 d12 d13')
+j1, j2 = _me.dynamicsymbols('j1 j2')
+n = _sm.symbols('n')
+n = _sm.I
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest3.al b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest3.al
new file mode 100644
index 0000000000000000000000000000000000000000..f263f1802ebca2725481dd5fdd3540bf8e9f11bf
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest3.al
@@ -0,0 +1,25 @@
+% ruletest3.al
+FRAMES A, B
+NEWTONIAN N
+
+VARIABLES X{3}
+CONSTANTS L
+
+V1> = X1*A1> + X2*A2> + X3*A3>
+V2> = X1*B1> + X2*B2> + X3*B3>
+V3> = X1*N1> + X2*N2> + X3*N3>
+
+V> = V1> + V2> + V3>
+
+POINTS C, D
+POINTS PO{3}
+
+PARTICLES L
+PARTICLES P{3}
+
+BODIES S
+BODIES R{2}
+
+V4> = X1*S1> + X2*S2> + X3*S3>
+
+P_C_SO> = L*N1>
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest3.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest3.py
new file mode 100644
index 0000000000000000000000000000000000000000..23f79aa571337f200b3ff4d56b5747f7704985c0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest3.py
@@ -0,0 +1,37 @@
+import sympy.physics.mechanics as _me
+import sympy as _sm
+import math as m
+import numpy as _np
+
+frame_a = _me.ReferenceFrame('a')
+frame_b = _me.ReferenceFrame('b')
+frame_n = _me.ReferenceFrame('n')
+x1, x2, x3 = _me.dynamicsymbols('x1 x2 x3')
+l = _sm.symbols('l', real=True)
+v1 = x1*frame_a.x+x2*frame_a.y+x3*frame_a.z
+v2 = x1*frame_b.x+x2*frame_b.y+x3*frame_b.z
+v3 = x1*frame_n.x+x2*frame_n.y+x3*frame_n.z
+v = v1+v2+v3
+point_c = _me.Point('c')
+point_d = _me.Point('d')
+point_po1 = _me.Point('po1')
+point_po2 = _me.Point('po2')
+point_po3 = _me.Point('po3')
+particle_l = _me.Particle('l', _me.Point('l_pt'), _sm.Symbol('m'))
+particle_p1 = _me.Particle('p1', _me.Point('p1_pt'), _sm.Symbol('m'))
+particle_p2 = _me.Particle('p2', _me.Point('p2_pt'), _sm.Symbol('m'))
+particle_p3 = _me.Particle('p3', _me.Point('p3_pt'), _sm.Symbol('m'))
+body_s_cm = _me.Point('s_cm')
+body_s_cm.set_vel(frame_n, 0)
+body_s_f = _me.ReferenceFrame('s_f')
+body_s = _me.RigidBody('s', body_s_cm, body_s_f, _sm.symbols('m'), (_me.outer(body_s_f.x,body_s_f.x),body_s_cm))
+body_r1_cm = _me.Point('r1_cm')
+body_r1_cm.set_vel(frame_n, 0)
+body_r1_f = _me.ReferenceFrame('r1_f')
+body_r1 = _me.RigidBody('r1', body_r1_cm, body_r1_f, _sm.symbols('m'), (_me.outer(body_r1_f.x,body_r1_f.x),body_r1_cm))
+body_r2_cm = _me.Point('r2_cm')
+body_r2_cm.set_vel(frame_n, 0)
+body_r2_f = _me.ReferenceFrame('r2_f')
+body_r2 = _me.RigidBody('r2', body_r2_cm, body_r2_f, _sm.symbols('m'), (_me.outer(body_r2_f.x,body_r2_f.x),body_r2_cm))
+v4 = x1*body_s_f.x+x2*body_s_f.y+x3*body_s_f.z
+body_s_cm.set_pos(point_c, l*frame_n.x)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest4.al b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest4.al
new file mode 100644
index 0000000000000000000000000000000000000000..7302bd7724bad9b763c75fe4230faa42b5070408
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest4.al
@@ -0,0 +1,20 @@
+% ruletest4.al
+
+FRAMES A, B
+MOTIONVARIABLES Q{3}
+SIMPROT(A, B, 1, Q3)
+DCM = A_B
+M = DCM*3 - A_B
+
+VARIABLES R
+CIRCLE_AREA = PI*R^2
+
+VARIABLES U, A
+VARIABLES X, Y
+S = U*T - 1/2*A*T^2
+
+EXPR1 = 2*A*0.5 - 1.25 + 0.25
+EXPR2 = -X^2 + Y^2 + 0.25*(X+Y)^2
+EXPR3 = 0.5E-10
+
+DYADIC>> = A1>*A1> + A2>*A2> + A3>*A3>
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest4.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest4.py
new file mode 100644
index 0000000000000000000000000000000000000000..74b18543e04d6c9e42dd569d2152040c13ae0899
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest4.py
@@ -0,0 +1,20 @@
+import sympy.physics.mechanics as _me
+import sympy as _sm
+import math as m
+import numpy as _np
+
+frame_a = _me.ReferenceFrame('a')
+frame_b = _me.ReferenceFrame('b')
+q1, q2, q3 = _me.dynamicsymbols('q1 q2 q3')
+frame_b.orient(frame_a, 'Axis', [q3, frame_a.x])
+dcm = frame_a.dcm(frame_b)
+m = dcm*3-frame_a.dcm(frame_b)
+r = _me.dynamicsymbols('r')
+circle_area = _sm.pi*r**2
+u, a = _me.dynamicsymbols('u a')
+x, y = _me.dynamicsymbols('x y')
+s = u*_me.dynamicsymbols._t-1/2*a*_me.dynamicsymbols._t**2
+expr1 = 2*a*0.5-1.25+0.25
+expr2 = -1*x**2+y**2+0.25*(x+y)**2
+expr3 = 0.5*10**(-10)
+dyadic = _me.outer(frame_a.x, frame_a.x)+_me.outer(frame_a.y, frame_a.y)+_me.outer(frame_a.z, frame_a.z)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest5.al b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest5.al
new file mode 100644
index 0000000000000000000000000000000000000000..a859dc8bb1f0251af14809681d995c59b31377ba
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest5.al
@@ -0,0 +1,32 @@
+% ruletest5.al
+VARIABLES X', Y'
+
+E1 = (X+Y)^2 + (X-Y)^3
+E2 = (X-Y)^2
+E3 = X^2 + Y^2 + 2*X*Y
+
+M1 = [E1;E2]
+M2 = [(X+Y)^2,(X-Y)^2]
+M3 = M1 + [X;Y]
+
+AM = EXPAND(M1)
+CM = EXPAND([(X+Y)^2,(X-Y)^2])
+EM = EXPAND(M1 + [X;Y])
+F = EXPAND(E1)
+G = EXPAND(E2)
+
+A = FACTOR(E3, X)
+BM = FACTOR(M1, X)
+CM = FACTOR(M1 + [X;Y], X)
+
+A = D(E3, X)
+B = D(E3, Y)
+CM = D(M2, X)
+DM = D(M1 + [X;Y], X)
+FRAMES A, B
+A_B = [1,0,0;1,0,0;1,0,0]
+V1> = X*A1> + Y*A2> + X*Y*A3>
+E> = D(V1>, X, B)
+FM = DT(M1)
+GM = DT([(X+Y)^2,(X-Y)^2])
+H> = DT(V1>, B)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest5.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest5.py
new file mode 100644
index 0000000000000000000000000000000000000000..93684435b402f5b56e2f4a5c3c81500208556423
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest5.py
@@ -0,0 +1,33 @@
+import sympy.physics.mechanics as _me
+import sympy as _sm
+import math as m
+import numpy as _np
+
+x, y = _me.dynamicsymbols('x y')
+x_d, y_d = _me.dynamicsymbols('x_ y_', 1)
+e1 = (x+y)**2+(x-y)**3
+e2 = (x-y)**2
+e3 = x**2+y**2+2*x*y
+m1 = _sm.Matrix([e1,e2]).reshape(2, 1)
+m2 = _sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)
+m3 = m1+_sm.Matrix([x,y]).reshape(2, 1)
+am = _sm.Matrix([i.expand() for i in m1]).reshape((m1).shape[0], (m1).shape[1])
+cm = _sm.Matrix([i.expand() for i in _sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)]).reshape((_sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)).shape[0], (_sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)).shape[1])
+em = _sm.Matrix([i.expand() for i in m1+_sm.Matrix([x,y]).reshape(2, 1)]).reshape((m1+_sm.Matrix([x,y]).reshape(2, 1)).shape[0], (m1+_sm.Matrix([x,y]).reshape(2, 1)).shape[1])
+f = (e1).expand()
+g = (e2).expand()
+a = _sm.factor((e3), x)
+bm = _sm.Matrix([_sm.factor(i, x) for i in m1]).reshape((m1).shape[0], (m1).shape[1])
+cm = _sm.Matrix([_sm.factor(i, x) for i in m1+_sm.Matrix([x,y]).reshape(2, 1)]).reshape((m1+_sm.Matrix([x,y]).reshape(2, 1)).shape[0], (m1+_sm.Matrix([x,y]).reshape(2, 1)).shape[1])
+a = (e3).diff(x)
+b = (e3).diff(y)
+cm = _sm.Matrix([i.diff(x) for i in m2]).reshape((m2).shape[0], (m2).shape[1])
+dm = _sm.Matrix([i.diff(x) for i in m1+_sm.Matrix([x,y]).reshape(2, 1)]).reshape((m1+_sm.Matrix([x,y]).reshape(2, 1)).shape[0], (m1+_sm.Matrix([x,y]).reshape(2, 1)).shape[1])
+frame_a = _me.ReferenceFrame('a')
+frame_b = _me.ReferenceFrame('b')
+frame_b.orient(frame_a, 'DCM', _sm.Matrix([1,0,0,1,0,0,1,0,0]).reshape(3, 3))
+v1 = x*frame_a.x+y*frame_a.y+x*y*frame_a.z
+e = (v1).diff(x, frame_b)
+fm = _sm.Matrix([i.diff(_sm.Symbol('t')) for i in m1]).reshape((m1).shape[0], (m1).shape[1])
+gm = _sm.Matrix([i.diff(_sm.Symbol('t')) for i in _sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)]).reshape((_sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)).shape[0], (_sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)).shape[1])
+h = (v1).dt(frame_b)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest6.al b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest6.al
new file mode 100644
index 0000000000000000000000000000000000000000..7ec3ba61590e77772ae631237df048b932fe778c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest6.al
@@ -0,0 +1,41 @@
+% ruletest6.al
+VARIABLES Q{2}
+VARIABLES X,Y,Z
+Q1 = X^2 + Y^2
+Q2 = X-Y
+E = Q1 + Q2
+A = EXPLICIT(E)
+E2 = COS(X)
+E3 = COS(X*Y)
+A = TAYLOR(E2, 0:2, X=0)
+B = TAYLOR(E3, 0:2, X=0, Y=0)
+
+E = EXPAND((X+Y)^2)
+A = EVALUATE(E, X=1, Y=Z)
+BM = EVALUATE([E;2*E], X=1, Y=Z)
+
+E = Q1 + Q2
+A = EVALUATE(E, X=2, Y=Z^2)
+
+CONSTANTS J,K,L
+P1 = POLYNOMIAL([J,K,L],X)
+P2 = POLYNOMIAL(J*X+K,X,1)
+
+ROOT1 = ROOTS(P1, X, 2)
+ROOT2 = ROOTS([1;2;3])
+
+M = [1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16]
+
+AM = TRANSPOSE(M) + M
+BM = EIG(M)
+C1 = DIAGMAT(4, 1)
+C2 = DIAGMAT(3, 4, 2)
+DM = INV(M+C1)
+E = DET(M+C1) + TRACE([1,0;0,1])
+F = ELEMENT(M, 2, 3)
+
+A = COLS(M)
+BM = COLS(M, 1)
+CM = COLS(M, 1, 2:4, 3)
+DM = ROWS(M, 1)
+EM = ROWS(M, 1, 2:4, 3)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest6.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest6.py
new file mode 100644
index 0000000000000000000000000000000000000000..85f1a0b49518bb0ae5766cbe91b9c24a1b8e9c20
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest6.py
@@ -0,0 +1,36 @@
+import sympy.physics.mechanics as _me
+import sympy as _sm
+import math as m
+import numpy as _np
+
+q1, q2 = _me.dynamicsymbols('q1 q2')
+x, y, z = _me.dynamicsymbols('x y z')
+e = q1+q2
+a = (e).subs({q1:x**2+y**2, q2:x-y})
+e2 = _sm.cos(x)
+e3 = _sm.cos(x*y)
+a = (e2).series(x, 0, 2).removeO()
+b = (e3).series(x, 0, 2).removeO().series(y, 0, 2).removeO()
+e = ((x+y)**2).expand()
+a = (e).subs({q1:x**2+y**2,q2:x-y}).subs({x:1,y:z})
+bm = _sm.Matrix([i.subs({x:1,y:z}) for i in _sm.Matrix([e,2*e]).reshape(2, 1)]).reshape((_sm.Matrix([e,2*e]).reshape(2, 1)).shape[0], (_sm.Matrix([e,2*e]).reshape(2, 1)).shape[1])
+e = q1+q2
+a = (e).subs({q1:x**2+y**2,q2:x-y}).subs({x:2,y:z**2})
+j, k, l = _sm.symbols('j k l', real=True)
+p1 = _sm.Poly(_sm.Matrix([j,k,l]).reshape(1, 3), x)
+p2 = _sm.Poly(j*x+k, x)
+root1 = [i.evalf() for i in _sm.solve(p1, x)]
+root2 = [i.evalf() for i in _sm.solve(_sm.Poly(_sm.Matrix([1,2,3]).reshape(3, 1), x),x)]
+m = _sm.Matrix([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]).reshape(4, 4)
+am = (m).T+m
+bm = _sm.Matrix([i.evalf() for i in (m).eigenvals().keys()])
+c1 = _sm.diag(1,1,1,1)
+c2 = _sm.Matrix([2 if i==j else 0 for i in range(3) for j in range(4)]).reshape(3, 4)
+dm = (m+c1)**(-1)
+e = (m+c1).det()+(_sm.Matrix([1,0,0,1]).reshape(2, 2)).trace()
+f = (m)[1,2]
+a = (m).cols
+bm = (m).col(0)
+cm = _sm.Matrix([(m).T.row(0),(m).T.row(1),(m).T.row(2),(m).T.row(3),(m).T.row(2)])
+dm = (m).row(0)
+em = _sm.Matrix([(m).row(0),(m).row(1),(m).row(2),(m).row(3),(m).row(2)])
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest7.al b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest7.al
new file mode 100644
index 0000000000000000000000000000000000000000..2904a602f589645d22e1d3d378d077dd6a1ec27e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest7.al
@@ -0,0 +1,39 @@
+% ruletest7.al
+VARIABLES X', Y'
+E = COS(X) + SIN(X) + TAN(X)&
++ COSH(X) + SINH(X) + TANH(X)&
++ ACOS(X) + ASIN(X) + ATAN(X)&
++ LOG(X) + EXP(X) + SQRT(X)&
++ FACTORIAL(X) + CEIL(X) +&
+FLOOR(X) + SIGN(X)
+
+E = SQR(X) + LOG10(X)
+
+A = ABS(-1) + INT(1.5) + ROUND(1.9)
+
+E1 = 2*X + 3*Y
+E2 = X + Y
+
+AM = COEF([E1;E2], [X,Y])
+B = COEF(E1, X)
+C = COEF(E2, Y)
+D1 = EXCLUDE(E1, X)
+D2 = INCLUDE(E1, X)
+FM = ARRANGE([E1,E2],2,X)
+F = ARRANGE(E1, 2, Y)
+G = REPLACE(E1, X=2*X)
+GM = REPLACE([E1;E2], X=3)
+
+FRAMES A, B
+VARIABLES THETA
+SIMPROT(A,B,3,THETA)
+V1> = 2*A1> - 3*A2> + A3>
+V2> = B1> + B2> + B3>
+A = DOT(V1>, V2>)
+BM = DOT(V1>, [V2>;2*V2>])
+C> = CROSS(V1>,V2>)
+D = MAG(2*V1>) + MAG(3*V1>)
+DYADIC>> = 3*A1>*A1> + A2>*A2> + 2*A3>*A3>
+AM = MATRIX(B, DYADIC>>)
+M = [1;2;3]
+V> = VECTOR(A, M)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest7.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest7.py
new file mode 100644
index 0000000000000000000000000000000000000000..19147856dc3b0d451184a6bb539c1c331f61a6d2
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest7.py
@@ -0,0 +1,35 @@
+import sympy.physics.mechanics as _me
+import sympy as _sm
+import math as m
+import numpy as _np
+
+x, y = _me.dynamicsymbols('x y')
+x_d, y_d = _me.dynamicsymbols('x_ y_', 1)
+e = _sm.cos(x)+_sm.sin(x)+_sm.tan(x)+_sm.cosh(x)+_sm.sinh(x)+_sm.tanh(x)+_sm.acos(x)+_sm.asin(x)+_sm.atan(x)+_sm.log(x)+_sm.exp(x)+_sm.sqrt(x)+_sm.factorial(x)+_sm.ceiling(x)+_sm.floor(x)+_sm.sign(x)
+e = (x)**2+_sm.log(x, 10)
+a = _sm.Abs(-1*1)+int(1.5)+round(1.9)
+e1 = 2*x+3*y
+e2 = x+y
+am = _sm.Matrix([e1.expand().coeff(x), e1.expand().coeff(y), e2.expand().coeff(x), e2.expand().coeff(y)]).reshape(2, 2)
+b = (e1).expand().coeff(x)
+c = (e2).expand().coeff(y)
+d1 = (e1).collect(x).coeff(x,0)
+d2 = (e1).collect(x).coeff(x,1)
+fm = _sm.Matrix([i.collect(x)for i in _sm.Matrix([e1,e2]).reshape(1, 2)]).reshape((_sm.Matrix([e1,e2]).reshape(1, 2)).shape[0], (_sm.Matrix([e1,e2]).reshape(1, 2)).shape[1])
+f = (e1).collect(y)
+g = (e1).subs({x:2*x})
+gm = _sm.Matrix([i.subs({x:3}) for i in _sm.Matrix([e1,e2]).reshape(2, 1)]).reshape((_sm.Matrix([e1,e2]).reshape(2, 1)).shape[0], (_sm.Matrix([e1,e2]).reshape(2, 1)).shape[1])
+frame_a = _me.ReferenceFrame('a')
+frame_b = _me.ReferenceFrame('b')
+theta = _me.dynamicsymbols('theta')
+frame_b.orient(frame_a, 'Axis', [theta, frame_a.z])
+v1 = 2*frame_a.x-3*frame_a.y+frame_a.z
+v2 = frame_b.x+frame_b.y+frame_b.z
+a = _me.dot(v1, v2)
+bm = _sm.Matrix([_me.dot(v1, v2),_me.dot(v1, 2*v2)]).reshape(2, 1)
+c = _me.cross(v1, v2)
+d = 2*v1.magnitude()+3*v1.magnitude()
+dyadic = _me.outer(3*frame_a.x, frame_a.x)+_me.outer(frame_a.y, frame_a.y)+_me.outer(2*frame_a.z, frame_a.z)
+am = (dyadic).to_matrix(frame_b)
+m = _sm.Matrix([1,2,3]).reshape(3, 1)
+v = m[0]*frame_a.x +m[1]*frame_a.y +m[2]*frame_a.z
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest8.al b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest8.al
new file mode 100644
index 0000000000000000000000000000000000000000..4b2462c51e6730f46bf60b4b21ab6cfbf1993640
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest8.al
@@ -0,0 +1,38 @@
+% ruletest8.al
+FRAMES A
+CONSTANTS C{3}
+A>> = EXPRESS(1>>,A)
+PARTICLES P1, P2
+BODIES R
+R_A = [1,1,1;1,1,0;0,0,1]
+POINT O
+MASS P1=M1, P2=M2, R=MR
+INERTIA R, I1, I2, I3
+P_P1_O> = C1*A1>
+P_P2_O> = C2*A2>
+P_RO_O> = C3*A3>
+A>> = EXPRESS(I_P1_O>>, A)
+A>> = EXPRESS(I_P2_O>>, A)
+A>> = EXPRESS(I_R_O>>, A)
+A>> = EXPRESS(INERTIA(O), A)
+A>> = EXPRESS(INERTIA(O, P1, R), A)
+A>> = EXPRESS(I_R_O>>, A)
+A>> = EXPRESS(I_R_RO>>, A)
+
+P_P1_P2> = C1*A1> + C2*A2>
+P_P1_RO> = C3*A1>
+P_P2_RO> = C3*A2>
+
+B> = CM(O)
+B> = CM(O, P1, R)
+B> = CM(P1)
+
+MOTIONVARIABLES U{3}
+V> = U1*A1> + U2*A2> + U3*A3>
+U> = UNITVEC(V> + C1*A1>)
+V_P1_A> = U1*A1>
+A> = PARTIALS(V_P1_A>, U1)
+
+M = MASS(P1,R)
+M = MASS(P2)
+M = MASS()
\ No newline at end of file
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest8.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest8.py
new file mode 100644
index 0000000000000000000000000000000000000000..6809c47138e40027c700536e807ca7cfa5f468d7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest8.py
@@ -0,0 +1,49 @@
+import sympy.physics.mechanics as _me
+import sympy as _sm
+import math as m
+import numpy as _np
+
+frame_a = _me.ReferenceFrame('a')
+c1, c2, c3 = _sm.symbols('c1 c2 c3', real=True)
+a = _me.inertia(frame_a, 1, 1, 1)
+particle_p1 = _me.Particle('p1', _me.Point('p1_pt'), _sm.Symbol('m'))
+particle_p2 = _me.Particle('p2', _me.Point('p2_pt'), _sm.Symbol('m'))
+body_r_cm = _me.Point('r_cm')
+body_r_f = _me.ReferenceFrame('r_f')
+body_r = _me.RigidBody('r', body_r_cm, body_r_f, _sm.symbols('m'), (_me.outer(body_r_f.x,body_r_f.x),body_r_cm))
+frame_a.orient(body_r_f, 'DCM', _sm.Matrix([1,1,1,1,1,0,0,0,1]).reshape(3, 3))
+point_o = _me.Point('o')
+m1 = _sm.symbols('m1')
+particle_p1.mass = m1
+m2 = _sm.symbols('m2')
+particle_p2.mass = m2
+mr = _sm.symbols('mr')
+body_r.mass = mr
+i1 = _sm.symbols('i1')
+i2 = _sm.symbols('i2')
+i3 = _sm.symbols('i3')
+body_r.inertia = (_me.inertia(body_r_f, i1, i2, i3, 0, 0, 0), body_r_cm)
+point_o.set_pos(particle_p1.point, c1*frame_a.x)
+point_o.set_pos(particle_p2.point, c2*frame_a.y)
+point_o.set_pos(body_r_cm, c3*frame_a.z)
+a = _me.inertia_of_point_mass(particle_p1.mass, particle_p1.point.pos_from(point_o), frame_a)
+a = _me.inertia_of_point_mass(particle_p2.mass, particle_p2.point.pos_from(point_o), frame_a)
+a = body_r.inertia[0] + _me.inertia_of_point_mass(body_r.mass, body_r.masscenter.pos_from(point_o), frame_a)
+a = _me.inertia_of_point_mass(particle_p1.mass, particle_p1.point.pos_from(point_o), frame_a) + _me.inertia_of_point_mass(particle_p2.mass, particle_p2.point.pos_from(point_o), frame_a) + body_r.inertia[0] + _me.inertia_of_point_mass(body_r.mass, body_r.masscenter.pos_from(point_o), frame_a)
+a = _me.inertia_of_point_mass(particle_p1.mass, particle_p1.point.pos_from(point_o), frame_a) + body_r.inertia[0] + _me.inertia_of_point_mass(body_r.mass, body_r.masscenter.pos_from(point_o), frame_a)
+a = body_r.inertia[0] + _me.inertia_of_point_mass(body_r.mass, body_r.masscenter.pos_from(point_o), frame_a)
+a = body_r.inertia[0]
+particle_p2.point.set_pos(particle_p1.point, c1*frame_a.x+c2*frame_a.y)
+body_r_cm.set_pos(particle_p1.point, c3*frame_a.x)
+body_r_cm.set_pos(particle_p2.point, c3*frame_a.y)
+b = _me.functions.center_of_mass(point_o,particle_p1, particle_p2, body_r)
+b = _me.functions.center_of_mass(point_o,particle_p1, body_r)
+b = _me.functions.center_of_mass(particle_p1.point,particle_p1, particle_p2, body_r)
+u1, u2, u3 = _me.dynamicsymbols('u1 u2 u3')
+v = u1*frame_a.x+u2*frame_a.y+u3*frame_a.z
+u = (v+c1*frame_a.x).normalize()
+particle_p1.point.set_vel(frame_a, u1*frame_a.x)
+a = particle_p1.point.partial_velocity(frame_a, u1)
+m = particle_p1.mass+body_r.mass
+m = particle_p2.mass
+m = particle_p1.mass+particle_p2.mass+body_r.mass
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest9.al b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest9.al
new file mode 100644
index 0000000000000000000000000000000000000000..df5c70f05b76fc215f829672e281491b0c96c6a6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest9.al
@@ -0,0 +1,54 @@
+% ruletest9.al
+NEWTONIAN N
+FRAMES A
+A> = 0>
+D>> = EXPRESS(1>>, A)
+
+POINTS PO{2}
+PARTICLES P{2}
+MOTIONVARIABLES' C{3}'
+BODIES R
+P_P1_PO2> = C1*A1>
+V> = 2*P_P1_PO2> + C2*A2>
+
+W_A_N> = C3*A3>
+V> = 2*W_A_N> + C2*A2>
+W_R_N> = C3*A3>
+V> = 2*W_R_N> + C2*A2>
+
+ALF_A_N> = DT(W_A_N>, A)
+V> = 2*ALF_A_N> + C2*A2>
+
+V_P1_A> = C1*A1> + C3*A2>
+A_RO_N> = C2*A2>
+V_A> = CROSS(A_RO_N>, V_P1_A>)
+
+X_B_C> = V_A>
+X_B_D> = 2*X_B_C>
+A_B_C_D_E> = X_B_D>*2
+
+A_B_C = 2*C1*C2*C3
+A_B_C += 2*C1
+A_B_C := 3*C1
+
+MOTIONVARIABLES' Q{2}', U{2}'
+Q1' = U1
+Q2' = U2
+
+VARIABLES X'', Y''
+SPECIFIED YY
+Y'' = X*X'^2 + 1
+YY = X*X'^2 + 1
+
+M[1] = 2*X
+M[2] = 2*Y
+A = 2*M[1]
+
+M = [1,2,3;4,5,6;7,8,9]
+M[1, 2] = 5
+A = M[1, 2]*2
+
+FORCE_RO> = Q1*N1>
+TORQUE_A> = Q2*N3>
+FORCE_RO> = Q2*N2>
+F> = FORCE_RO>*2
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest9.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest9.py
new file mode 100644
index 0000000000000000000000000000000000000000..09d8ae4ee8385bde5c38b946458a43c8ffdaa9b8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/ruletest9.py
@@ -0,0 +1,55 @@
+import sympy.physics.mechanics as _me
+import sympy as _sm
+import math as m
+import numpy as _np
+
+frame_n = _me.ReferenceFrame('n')
+frame_a = _me.ReferenceFrame('a')
+a = 0
+d = _me.inertia(frame_a, 1, 1, 1)
+point_po1 = _me.Point('po1')
+point_po2 = _me.Point('po2')
+particle_p1 = _me.Particle('p1', _me.Point('p1_pt'), _sm.Symbol('m'))
+particle_p2 = _me.Particle('p2', _me.Point('p2_pt'), _sm.Symbol('m'))
+c1, c2, c3 = _me.dynamicsymbols('c1 c2 c3')
+c1_d, c2_d, c3_d = _me.dynamicsymbols('c1_ c2_ c3_', 1)
+body_r_cm = _me.Point('r_cm')
+body_r_cm.set_vel(frame_n, 0)
+body_r_f = _me.ReferenceFrame('r_f')
+body_r = _me.RigidBody('r', body_r_cm, body_r_f, _sm.symbols('m'), (_me.outer(body_r_f.x,body_r_f.x),body_r_cm))
+point_po2.set_pos(particle_p1.point, c1*frame_a.x)
+v = 2*point_po2.pos_from(particle_p1.point)+c2*frame_a.y
+frame_a.set_ang_vel(frame_n, c3*frame_a.z)
+v = 2*frame_a.ang_vel_in(frame_n)+c2*frame_a.y
+body_r_f.set_ang_vel(frame_n, c3*frame_a.z)
+v = 2*body_r_f.ang_vel_in(frame_n)+c2*frame_a.y
+frame_a.set_ang_acc(frame_n, (frame_a.ang_vel_in(frame_n)).dt(frame_a))
+v = 2*frame_a.ang_acc_in(frame_n)+c2*frame_a.y
+particle_p1.point.set_vel(frame_a, c1*frame_a.x+c3*frame_a.y)
+body_r_cm.set_acc(frame_n, c2*frame_a.y)
+v_a = _me.cross(body_r_cm.acc(frame_n), particle_p1.point.vel(frame_a))
+x_b_c = v_a
+x_b_d = 2*x_b_c
+a_b_c_d_e = x_b_d*2
+a_b_c = 2*c1*c2*c3
+a_b_c += 2*c1
+a_b_c  =  3*c1
+q1, q2, u1, u2 = _me.dynamicsymbols('q1 q2 u1 u2')
+q1_d, q2_d, u1_d, u2_d = _me.dynamicsymbols('q1_ q2_ u1_ u2_', 1)
+x, y = _me.dynamicsymbols('x y')
+x_d, y_d = _me.dynamicsymbols('x_ y_', 1)
+x_dd, y_dd = _me.dynamicsymbols('x_ y_', 2)
+yy = _me.dynamicsymbols('yy')
+yy = x*x_d**2+1
+m = _sm.Matrix([[0]])
+m[0] = 2*x
+m = m.row_insert(m.shape[0], _sm.Matrix([[0]]))
+m[m.shape[0]-1] = 2*y
+a = 2*m[0]
+m = _sm.Matrix([1,2,3,4,5,6,7,8,9]).reshape(3, 3)
+m[0,1] = 5
+a = m[0, 1]*2
+force_ro = q1*frame_n.x
+torque_a = q2*frame_n.z
+force_ro = q1*frame_n.x + q2*frame_n.y
+f = force_ro*2
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/c/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/c/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..18d3d5301cb001c78fc4a9bc04b25aa36f282a93
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/c/__init__.py
@@ -0,0 +1 @@
+"""Used for translating C source code into a SymPy expression"""
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/c/c_parser.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/c/c_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e7223f8351205272e803773589649fcf1902f15
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/c/c_parser.py
@@ -0,0 +1,1059 @@
+from sympy.external import import_module
+import os
+
+cin = import_module('clang.cindex', import_kwargs = {'fromlist': ['cindex']})
+
+"""
+This module contains all the necessary Classes and Function used to Parse C and
+C++ code into SymPy expression
+The module serves as a backend for SymPyExpression to parse C code
+It is also dependent on Clang's AST and SymPy's Codegen AST.
+The module only supports the features currently supported by the Clang and
+codegen AST which will be updated as the development of codegen AST and this
+module progresses.
+You might find unexpected bugs and exceptions while using the module, feel free
+to report them to the SymPy Issue Tracker
+
+Features Supported
+==================
+
+- Variable Declarations (integers and reals)
+- Assignment (using integer & floating literal and function calls)
+- Function Definitions and Declaration
+- Function Calls
+- Compound statements, Return statements
+
+Notes
+=====
+
+The module is dependent on an external dependency which needs to be installed
+to use the features of this module.
+
+Clang: The C and C++ compiler which is used to extract an AST from the provided
+C source code.
+
+References
+==========
+
+.. [1] https://github.com/sympy/sympy/issues
+.. [2] https://clang.llvm.org/docs/
+.. [3] https://clang.llvm.org/docs/IntroductionToTheClangAST.html
+
+"""
+
+if cin:
+    from sympy.codegen.ast import (Variable, Integer, Float,
+        FunctionPrototype, FunctionDefinition, FunctionCall,
+        none, Return, Assignment, intc, int8, int16, int64,
+        uint8, uint16, uint32, uint64, float32, float64, float80,
+        aug_assign, bool_, While, CodeBlock)
+    from sympy.codegen.cnodes import (PreDecrement, PostDecrement,
+        PreIncrement, PostIncrement)
+    from sympy.core import Add, Mod, Mul, Pow, Rel
+    from sympy.logic.boolalg import And, as_Boolean, Not, Or
+    from sympy.core.symbol import Symbol
+    from sympy.core.sympify import sympify
+    from sympy.logic.boolalg import (false, true)
+    import sys
+    import tempfile
+
+    class BaseParser:
+        """Base Class for the C parser"""
+
+        def __init__(self):
+            """Initializes the Base parser creating a Clang AST index"""
+            self.index = cin.Index.create()
+
+        def diagnostics(self, out):
+            """Diagostics function for the Clang AST"""
+            for diag in self.tu.diagnostics:
+                # tu = translation unit
+                print('%s %s (line %s, col %s) %s' % (
+                        {
+                            4: 'FATAL',
+                            3: 'ERROR',
+                            2: 'WARNING',
+                            1: 'NOTE',
+                            0: 'IGNORED',
+                        }[diag.severity],
+                        diag.location.file,
+                        diag.location.line,
+                        diag.location.column,
+                        diag.spelling
+                    ), file=out)
+
+    class CCodeConverter(BaseParser):
+        """The Code Convereter for Clang AST
+
+        The converter object takes the C source code or file as input and
+        converts them to SymPy Expressions.
+        """
+
+        def __init__(self):
+            """Initializes the code converter"""
+            super().__init__()
+            self._py_nodes = []
+            self._data_types = {
+                "void": {
+                    cin.TypeKind.VOID: none
+                },
+                "bool": {
+                    cin.TypeKind.BOOL: bool_
+                },
+                "int": {
+                    cin.TypeKind.SCHAR: int8,
+                    cin.TypeKind.SHORT: int16,
+                    cin.TypeKind.INT: intc,
+                    cin.TypeKind.LONG: int64,
+                    cin.TypeKind.UCHAR: uint8,
+                    cin.TypeKind.USHORT: uint16,
+                    cin.TypeKind.UINT: uint32,
+                    cin.TypeKind.ULONG: uint64
+                },
+                "float": {
+                    cin.TypeKind.FLOAT: float32,
+                    cin.TypeKind.DOUBLE: float64,
+                    cin.TypeKind.LONGDOUBLE: float80
+                }
+            }
+
+        def parse(self, filename, flags):
+            """Function to parse a file with C source code
+
+            It takes the filename as an attribute and creates a Clang AST
+            Translation Unit parsing the file.
+            Then the transformation function is called on the translation unit,
+            whose results are collected into a list which is returned by the
+            function.
+
+            Parameters
+            ==========
+
+            filename : string
+                Path to the C file to be parsed
+
+            flags: list
+                Arguments to be passed to Clang while parsing the C code
+
+            Returns
+            =======
+
+            py_nodes: list
+                A list of SymPy AST nodes
+
+            """
+            filepath = os.path.abspath(filename)
+            self.tu = self.index.parse(
+                filepath,
+                args=flags,
+                options=cin.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD
+            )
+            for child in self.tu.cursor.get_children():
+                if child.kind == cin.CursorKind.VAR_DECL or child.kind == cin.CursorKind.FUNCTION_DECL:
+                    self._py_nodes.append(self.transform(child))
+            return self._py_nodes
+
+        def parse_str(self, source, flags):
+            """Function to parse a string with C source code
+
+            It takes the source code as an attribute, stores it in a temporary
+            file and creates a Clang AST Translation Unit parsing the file.
+            Then the transformation function is called on the translation unit,
+            whose results are collected into a list which is returned by the
+            function.
+
+            Parameters
+            ==========
+
+            source : string
+                A string containing the C source code to be parsed
+
+            flags: list
+                Arguments to be passed to Clang while parsing the C code
+
+            Returns
+            =======
+
+            py_nodes: list
+                A list of SymPy AST nodes
+
+            """
+            file = tempfile.NamedTemporaryFile(mode = 'w+', suffix = '.cpp')
+            file.write(source)
+            file.flush()
+            file.seek(0)
+            self.tu = self.index.parse(
+                file.name,
+                args=flags,
+                options=cin.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD
+            )
+            file.close()
+            for child in self.tu.cursor.get_children():
+                if child.kind == cin.CursorKind.VAR_DECL or child.kind == cin.CursorKind.FUNCTION_DECL:
+                    self._py_nodes.append(self.transform(child))
+            return self._py_nodes
+
+        def transform(self, node):
+            """Transformation Function for Clang AST nodes
+
+            It determines the kind of node and calls the respective
+            transformation function for that node.
+
+            Raises
+            ======
+
+            NotImplementedError : if the transformation for the provided node
+            is not implemented
+
+            """
+            handler = getattr(self, 'transform_%s' % node.kind.name.lower(), None)
+
+            if handler is None:
+                print(
+                    "Ignoring node of type %s (%s)" % (
+                        node.kind,
+                        ' '.join(
+                            t.spelling for t in node.get_tokens())
+                        ),
+                    file=sys.stderr
+                )
+
+            return handler(node)
+
+        def transform_var_decl(self, node):
+            """Transformation Function for Variable Declaration
+
+            Used to create nodes for variable declarations and assignments with
+            values or function call for the respective nodes in the clang AST
+
+            Returns
+            =======
+
+            A variable node as Declaration, with the initial value if given
+
+            Raises
+            ======
+
+            NotImplementedError : if called for data types not currently
+            implemented
+
+            Notes
+            =====
+
+            The function currently supports following data types:
+
+            Boolean:
+                bool, _Bool
+
+            Integer:
+                8-bit: signed char and unsigned char
+                16-bit: short, short int, signed short,
+                    signed short int, unsigned short, unsigned short int
+                32-bit: int, signed int, unsigned int
+                64-bit: long, long int, signed long,
+                    signed long int, unsigned long, unsigned long int
+
+            Floating point:
+                Single Precision: float
+                Double Precision: double
+                Extended Precision: long double
+
+            """
+            if node.type.kind in self._data_types["int"]:
+                type = self._data_types["int"][node.type.kind]
+            elif node.type.kind in self._data_types["float"]:
+                type = self._data_types["float"][node.type.kind]
+            elif node.type.kind in self._data_types["bool"]:
+                type = self._data_types["bool"][node.type.kind]
+            else:
+                raise NotImplementedError("Only bool, int "
+                    "and float are supported")
+            try:
+                children = node.get_children()
+                child = next(children)
+
+                #ignoring namespace and type details for the variable
+                while child.kind == cin.CursorKind.NAMESPACE_REF or child.kind == cin.CursorKind.TYPE_REF:
+                    child = next(children)
+
+                val = self.transform(child)
+
+                supported_rhs = [
+                    cin.CursorKind.INTEGER_LITERAL,
+                    cin.CursorKind.FLOATING_LITERAL,
+                    cin.CursorKind.UNEXPOSED_EXPR,
+                    cin.CursorKind.BINARY_OPERATOR,
+                    cin.CursorKind.PAREN_EXPR,
+                    cin.CursorKind.UNARY_OPERATOR,
+                    cin.CursorKind.CXX_BOOL_LITERAL_EXPR
+                ]
+
+                if child.kind in supported_rhs:
+                    if isinstance(val, str):
+                        value = Symbol(val)
+                    elif isinstance(val, bool):
+                        if node.type.kind in self._data_types["int"]:
+                            value = Integer(0) if val == False else Integer(1)
+                        elif node.type.kind in self._data_types["float"]:
+                            value = Float(0.0) if val == False else Float(1.0)
+                        elif node.type.kind in self._data_types["bool"]:
+                            value = sympify(val)
+                    elif isinstance(val, (Integer, int, Float, float)):
+                        if node.type.kind in self._data_types["int"]:
+                            value = Integer(val)
+                        elif node.type.kind in self._data_types["float"]:
+                            value = Float(val)
+                        elif node.type.kind in self._data_types["bool"]:
+                            value = sympify(bool(val))
+                    else:
+                        value = val
+
+                    return Variable(
+                    node.spelling
+                    ).as_Declaration(
+                        type = type,
+                        value = value
+                    )
+
+                elif child.kind == cin.CursorKind.CALL_EXPR:
+                    return Variable(
+                        node.spelling
+                        ).as_Declaration(
+                            value = val
+                        )
+
+                else:
+                    raise NotImplementedError("Given "
+                        "variable declaration \"{}\" "
+                        "is not possible to parse yet!"
+                        .format(" ".join(
+                            t.spelling for t in node.get_tokens()
+                            )
+                        ))
+
+            except StopIteration:
+                return Variable(
+                node.spelling
+                ).as_Declaration(
+                    type = type
+                )
+
+        def transform_function_decl(self, node):
+            """Transformation Function For Function Declaration
+
+            Used to create nodes for function declarations and definitions for
+            the respective nodes in the clang AST
+
+            Returns
+            =======
+
+            function : Codegen AST node
+                - FunctionPrototype node if function body is not present
+                - FunctionDefinition node if the function body is present
+
+
+            """
+
+            if node.result_type.kind in self._data_types["int"]:
+                ret_type = self._data_types["int"][node.result_type.kind]
+            elif node.result_type.kind in self._data_types["float"]:
+                ret_type = self._data_types["float"][node.result_type.kind]
+            elif node.result_type.kind in self._data_types["bool"]:
+                ret_type = self._data_types["bool"][node.result_type.kind]
+            elif node.result_type.kind in self._data_types["void"]:
+                ret_type = self._data_types["void"][node.result_type.kind]
+            else:
+                raise NotImplementedError("Only void, bool, int "
+                    "and float are supported")
+            body = []
+            param = []
+
+            # Subsequent nodes will be the parameters for the function.
+            for child in node.get_children():
+                decl = self.transform(child)
+                if child.kind == cin.CursorKind.PARM_DECL:
+                    param.append(decl)
+                elif child.kind == cin.CursorKind.COMPOUND_STMT:
+                    for val in decl:
+                        body.append(val)
+                else:
+                    body.append(decl)
+
+            if body == []:
+                function = FunctionPrototype(
+                    return_type = ret_type,
+                    name = node.spelling,
+                    parameters = param
+                )
+            else:
+                function = FunctionDefinition(
+                    return_type = ret_type,
+                    name = node.spelling,
+                    parameters = param,
+                    body = body
+                )
+            return function
+
+        def transform_parm_decl(self, node):
+            """Transformation function for Parameter Declaration
+
+            Used to create parameter nodes for the required functions for the
+            respective nodes in the clang AST
+
+            Returns
+            =======
+
+            param : Codegen AST Node
+                Variable node with the value and type of the variable
+
+            Raises
+            ======
+
+            ValueError if multiple children encountered in the parameter node
+
+            """
+            if node.type.kind in self._data_types["int"]:
+                type = self._data_types["int"][node.type.kind]
+            elif node.type.kind in self._data_types["float"]:
+                type = self._data_types["float"][node.type.kind]
+            elif node.type.kind in self._data_types["bool"]:
+                type = self._data_types["bool"][node.type.kind]
+            else:
+                raise NotImplementedError("Only bool, int "
+                    "and float are supported")
+            try:
+                children = node.get_children()
+                child = next(children)
+
+                # Any namespace nodes can be ignored
+                while child.kind in [cin.CursorKind.NAMESPACE_REF,
+                                     cin.CursorKind.TYPE_REF,
+                                     cin.CursorKind.TEMPLATE_REF]:
+                    child = next(children)
+
+                # If there is a child, it is the default value of the parameter.
+                lit = self.transform(child)
+                if node.type.kind in self._data_types["int"]:
+                    val = Integer(lit)
+                elif node.type.kind in self._data_types["float"]:
+                    val = Float(lit)
+                elif node.type.kind in self._data_types["bool"]:
+                    val = sympify(bool(lit))
+                else:
+                    raise NotImplementedError("Only bool, int "
+                        "and float are supported")
+
+                param = Variable(
+                    node.spelling
+                ).as_Declaration(
+                    type = type,
+                    value = val
+                )
+            except StopIteration:
+                param = Variable(
+                    node.spelling
+                ).as_Declaration(
+                    type = type
+                )
+
+            try:
+                self.transform(next(children))
+                raise ValueError("Can't handle multiple children on parameter")
+            except StopIteration:
+                pass
+
+            return param
+
+        def transform_integer_literal(self, node):
+            """Transformation function for integer literal
+
+            Used to get the value and type of the given integer literal.
+
+            Returns
+            =======
+
+            val : list
+                List with two arguments type and Value
+                type contains the type of the integer
+                value contains the value stored in the variable
+
+            Notes
+            =====
+
+            Only Base Integer type supported for now
+
+            """
+            try:
+                value = next(node.get_tokens()).spelling
+            except StopIteration:
+                # No tokens
+                value = node.literal
+            return int(value)
+
+        def transform_floating_literal(self, node):
+            """Transformation function for floating literal
+
+            Used to get the value and type of the given floating literal.
+
+            Returns
+            =======
+
+            val : list
+                List with two arguments type and Value
+                type contains the type of float
+                value contains the value stored in the variable
+
+            Notes
+            =====
+
+            Only Base Float type supported for now
+
+            """
+            try:
+                value = next(node.get_tokens()).spelling
+            except (StopIteration, ValueError):
+                # No tokens
+                value = node.literal
+            return float(value)
+
+        def transform_string_literal(self, node):
+            #TODO: No string type in AST
+            #type =
+            #try:
+            #    value = next(node.get_tokens()).spelling
+            #except (StopIteration, ValueError):
+                # No tokens
+            #    value = node.literal
+            #val = [type, value]
+            #return val
+            pass
+
+        def transform_character_literal(self, node):
+            """Transformation function for character literal
+
+            Used to get the value of the given character literal.
+
+            Returns
+            =======
+
+            val : int
+                val contains the ascii value of the character literal
+
+            Notes
+            =====
+
+            Only for cases where character is assigned to a integer value,
+            since character literal is not in SymPy AST
+
+            """
+            try:
+                value = next(node.get_tokens()).spelling
+            except (StopIteration, ValueError):
+                # No tokens
+                value = node.literal
+            return ord(str(value[1]))
+
+        def transform_cxx_bool_literal_expr(self, node):
+            """Transformation function for boolean literal
+
+            Used to get the value of the given boolean literal.
+
+            Returns
+            =======
+
+            value : bool
+                value contains the boolean value of the variable
+
+            """
+            try:
+                value = next(node.get_tokens()).spelling
+            except (StopIteration, ValueError):
+                value = node.literal
+            return True if value == 'true' else False
+
+        def transform_unexposed_decl(self,node):
+            """Transformation function for unexposed declarations"""
+            pass
+
+        def transform_unexposed_expr(self, node):
+            """Transformation function for unexposed expression
+
+            Unexposed expressions are used to wrap float, double literals and
+            expressions
+
+            Returns
+            =======
+
+            expr : Codegen AST Node
+                the result from the wrapped expression
+
+            None : NoneType
+                No children are found for the node
+
+            Raises
+            ======
+
+            ValueError if the expression contains multiple children
+
+            """
+            # Ignore unexposed nodes; pass whatever is the first
+            # (and should be only) child unaltered.
+            try:
+                children = node.get_children()
+                expr = self.transform(next(children))
+            except StopIteration:
+                return None
+
+            try:
+                next(children)
+                raise ValueError("Unexposed expression has > 1 children.")
+            except StopIteration:
+                pass
+
+            return expr
+
+        def transform_decl_ref_expr(self, node):
+            """Returns the name of the declaration reference"""
+            return node.spelling
+
+        def transform_call_expr(self, node):
+            """Transformation function for a call expression
+
+            Used to create function call nodes for the function calls present
+            in the C code
+
+            Returns
+            =======
+
+            FunctionCall : Codegen AST Node
+                FunctionCall node with parameters if any parameters are present
+
+            """
+            param = []
+            children = node.get_children()
+            child = next(children)
+
+            while child.kind == cin.CursorKind.NAMESPACE_REF:
+                child = next(children)
+            while child.kind == cin.CursorKind.TYPE_REF:
+                child = next(children)
+
+            first_child = self.transform(child)
+            try:
+                for child in children:
+                    arg = self.transform(child)
+                    if child.kind == cin.CursorKind.INTEGER_LITERAL:
+                        param.append(Integer(arg))
+                    elif child.kind == cin.CursorKind.FLOATING_LITERAL:
+                        param.append(Float(arg))
+                    else:
+                        param.append(arg)
+                return FunctionCall(first_child, param)
+
+            except StopIteration:
+                return FunctionCall(first_child)
+
+        def transform_return_stmt(self, node):
+            """Returns the Return Node for a return statement"""
+            return Return(next(node.get_children()).spelling)
+
+        def transform_compound_stmt(self, node):
+            """Transformation function for compound statements
+
+            Returns
+            =======
+
+            expr : list
+                list of Nodes for the expressions present in the statement
+
+            None : NoneType
+                if the compound statement is empty
+
+            """
+            expr = []
+            children = node.get_children()
+
+            for child in children:
+                expr.append(self.transform(child))
+            return expr
+
+        def transform_decl_stmt(self, node):
+            """Transformation function for declaration statements
+
+            These statements are used to wrap different kinds of declararions
+            like variable or function declaration
+            The function calls the transformer function for the child of the
+            given node
+
+            Returns
+            =======
+
+            statement : Codegen AST Node
+                contains the node returned by the children node for the type of
+                declaration
+
+            Raises
+            ======
+
+            ValueError if multiple children present
+
+            """
+            try:
+                children = node.get_children()
+                statement = self.transform(next(children))
+            except StopIteration:
+                pass
+
+            try:
+                self.transform(next(children))
+                raise ValueError("Don't know how to handle multiple statements")
+            except StopIteration:
+                pass
+
+            return statement
+
+        def transform_paren_expr(self, node):
+            """Transformation function for Parenthesized expressions
+
+            Returns the result from its children nodes
+
+            """
+            return self.transform(next(node.get_children()))
+
+        def transform_compound_assignment_operator(self, node):
+            """Transformation function for handling shorthand operators
+
+            Returns
+            =======
+
+            augmented_assignment_expression: Codegen AST node
+                    shorthand assignment expression represented as Codegen AST
+
+            Raises
+            ======
+
+            NotImplementedError
+                If the shorthand operator for bitwise operators
+                (~=, ^=, &=, |=, <<=, >>=) is encountered
+
+            """
+            return self.transform_binary_operator(node)
+
+        def transform_unary_operator(self, node):
+            """Transformation function for handling unary operators
+
+            Returns
+            =======
+
+            unary_expression: Codegen AST node
+                    simplified unary expression represented as Codegen AST
+
+            Raises
+            ======
+
+            NotImplementedError
+                If dereferencing operator(*), address operator(&) or
+                bitwise NOT operator(~) is encountered
+
+            """
+            # supported operators list
+            operators_list = ['+', '-', '++', '--', '!']
+            tokens = list(node.get_tokens())
+
+            # it can be either pre increment/decrement or any other operator from the list
+            if tokens[0].spelling in operators_list:
+                child = self.transform(next(node.get_children()))
+                # (decl_ref) e.g.; int a = ++b; or simply ++b;
+                if isinstance(child, str):
+                    if tokens[0].spelling == '+':
+                        return Symbol(child)
+                    if tokens[0].spelling == '-':
+                        return Mul(Symbol(child), -1)
+                    if tokens[0].spelling == '++':
+                        return PreIncrement(Symbol(child))
+                    if tokens[0].spelling == '--':
+                        return PreDecrement(Symbol(child))
+                    if tokens[0].spelling == '!':
+                        return Not(Symbol(child))
+                # e.g.; int a = -1; or int b = -(1 + 2);
+                else:
+                    if tokens[0].spelling == '+':
+                        return child
+                    if tokens[0].spelling == '-':
+                        return Mul(child, -1)
+                    if tokens[0].spelling == '!':
+                        return Not(sympify(bool(child)))
+
+            # it can be either post increment/decrement
+            # since variable name is obtained in token[0].spelling
+            elif tokens[1].spelling in ['++', '--']:
+                child = self.transform(next(node.get_children()))
+                if tokens[1].spelling == '++':
+                    return PostIncrement(Symbol(child))
+                if tokens[1].spelling == '--':
+                    return PostDecrement(Symbol(child))
+            else:
+                raise NotImplementedError("Dereferencing operator, "
+                    "Address operator and bitwise NOT operator "
+                    "have not been implemented yet!")
+
+        def transform_binary_operator(self, node):
+            """Transformation function for handling binary operators
+
+            Returns
+            =======
+
+            binary_expression: Codegen AST node
+                    simplified binary expression represented as Codegen AST
+
+            Raises
+            ======
+
+            NotImplementedError
+                If a bitwise operator or
+                unary operator(which is a child of any binary
+                operator in Clang AST) is encountered
+
+            """
+            # get all the tokens of assignment
+            # and store it in the tokens list
+            tokens = list(node.get_tokens())
+
+            # supported operators list
+            operators_list = ['+', '-', '*', '/', '%','=',
+            '>', '>=', '<', '<=', '==', '!=', '&&', '||', '+=', '-=',
+            '*=', '/=', '%=']
+
+            # this stack will contain variable content
+            # and type of variable in the rhs
+            combined_variables_stack = []
+
+            # this stack will contain operators
+            # to be processed in the rhs
+            operators_stack = []
+
+            # iterate through every token
+            for token in tokens:
+                # token is either '(', ')' or
+                # any of the supported operators from the operator list
+                if token.kind == cin.TokenKind.PUNCTUATION:
+
+                    # push '(' to the operators stack
+                    if token.spelling == '(':
+                        operators_stack.append('(')
+
+                    elif token.spelling == ')':
+                        # keep adding the expression to the
+                        # combined variables stack unless
+                        # '(' is found
+                        while (operators_stack
+                            and operators_stack[-1] != '('):
+                            if len(combined_variables_stack) < 2:
+                                raise NotImplementedError(
+                                    "Unary operators as a part of "
+                                    "binary operators is not "
+                                    "supported yet!")
+                            rhs = combined_variables_stack.pop()
+                            lhs = combined_variables_stack.pop()
+                            operator = operators_stack.pop()
+                            combined_variables_stack.append(
+                                self.perform_operation(
+                                lhs, rhs, operator))
+
+                        # pop '('
+                        operators_stack.pop()
+
+                    # token is an operator (supported)
+                    elif token.spelling in operators_list:
+                        while (operators_stack
+                            and self.priority_of(token.spelling)
+                            <= self.priority_of(
+                            operators_stack[-1])):
+                            if len(combined_variables_stack) < 2:
+                                raise NotImplementedError(
+                                    "Unary operators as a part of "
+                                    "binary operators is not "
+                                    "supported yet!")
+                            rhs = combined_variables_stack.pop()
+                            lhs = combined_variables_stack.pop()
+                            operator = operators_stack.pop()
+                            combined_variables_stack.append(
+                                self.perform_operation(
+                                lhs, rhs, operator))
+
+                        # push current operator
+                        operators_stack.append(token.spelling)
+
+                    # token is a bitwise operator
+                    elif token.spelling in ['&', '|', '^', '<<', '>>']:
+                        raise NotImplementedError(
+                            "Bitwise operator has not been "
+                            "implemented yet!")
+
+                    # token is a shorthand bitwise operator
+                    elif token.spelling in ['&=', '|=', '^=', '<<=',
+                    '>>=']:
+                        raise NotImplementedError(
+                            "Shorthand bitwise operator has not been "
+                            "implemented yet!")
+                    else:
+                        raise NotImplementedError(
+                            "Given token {} is not implemented yet!"
+                            .format(token.spelling))
+
+                # token is an identifier(variable)
+                elif token.kind == cin.TokenKind.IDENTIFIER:
+                    combined_variables_stack.append(
+                        [token.spelling, 'identifier'])
+
+                # token is a literal
+                elif token.kind == cin.TokenKind.LITERAL:
+                    combined_variables_stack.append(
+                        [token.spelling, 'literal'])
+
+                # token is a keyword, either true or false
+                elif (token.kind == cin.TokenKind.KEYWORD
+                    and token.spelling in ['true', 'false']):
+                    combined_variables_stack.append(
+                        [token.spelling, 'boolean'])
+                else:
+                    raise NotImplementedError(
+                        "Given token {} is not implemented yet!"
+                        .format(token.spelling))
+
+            # process remaining operators
+            while operators_stack:
+                if len(combined_variables_stack) < 2:
+                    raise NotImplementedError(
+                        "Unary operators as a part of "
+                        "binary operators is not "
+                        "supported yet!")
+                rhs = combined_variables_stack.pop()
+                lhs = combined_variables_stack.pop()
+                operator = operators_stack.pop()
+                combined_variables_stack.append(
+                    self.perform_operation(lhs, rhs, operator))
+
+            return combined_variables_stack[-1][0]
+
+        def priority_of(self, op):
+            """To get the priority of given operator"""
+            if op in ['=', '+=', '-=', '*=', '/=', '%=']:
+                return 1
+            if op in ['&&', '||']:
+                return 2
+            if op in ['<', '<=', '>', '>=', '==', '!=']:
+                return 3
+            if op in ['+', '-']:
+                return 4
+            if op in ['*', '/', '%']:
+                return 5
+            return 0
+
+        def perform_operation(self, lhs, rhs, op):
+            """Performs operation supported by the SymPy core
+
+            Returns
+            =======
+
+            combined_variable: list
+                contains variable content and type of variable
+
+            """
+            lhs_value = self.get_expr_for_operand(lhs)
+            rhs_value = self.get_expr_for_operand(rhs)
+            if op == '+':
+                return [Add(lhs_value, rhs_value), 'expr']
+            if op == '-':
+                return [Add(lhs_value, -rhs_value), 'expr']
+            if op == '*':
+                return [Mul(lhs_value, rhs_value), 'expr']
+            if op == '/':
+                return [Mul(lhs_value, Pow(rhs_value, Integer(-1))), 'expr']
+            if op == '%':
+                return [Mod(lhs_value, rhs_value), 'expr']
+            if op in ['<', '<=', '>', '>=', '==', '!=']:
+                return [Rel(lhs_value, rhs_value, op), 'expr']
+            if op == '&&':
+                return [And(as_Boolean(lhs_value), as_Boolean(rhs_value)), 'expr']
+            if op == '||':
+                return [Or(as_Boolean(lhs_value), as_Boolean(rhs_value)), 'expr']
+            if op == '=':
+                return [Assignment(Variable(lhs_value), rhs_value), 'expr']
+            if op in ['+=', '-=', '*=', '/=', '%=']:
+                return [aug_assign(Variable(lhs_value), op[0], rhs_value), 'expr']
+
+        def get_expr_for_operand(self, combined_variable):
+            """Gives out SymPy Codegen AST node
+
+            AST node returned is corresponding to
+            combined variable passed.Combined variable contains
+            variable content and type of variable
+
+            """
+            if combined_variable[1] == 'identifier':
+                return Symbol(combined_variable[0])
+            if combined_variable[1] == 'literal':
+                if '.' in combined_variable[0]:
+                    return Float(float(combined_variable[0]))
+                else:
+                    return Integer(int(combined_variable[0]))
+            if combined_variable[1] == 'expr':
+                return combined_variable[0]
+            if combined_variable[1] == 'boolean':
+                    return true if combined_variable[0] == 'true' else false
+
+        def transform_null_stmt(self, node):
+            """Handles Null Statement and returns None"""
+            return none
+
+        def transform_while_stmt(self, node):
+            """Transformation function for handling while statement
+
+            Returns
+            =======
+
+            while statement : Codegen AST Node
+                contains the while statement node having condition and
+                statement block
+
+            """
+            children = node.get_children()
+
+            condition = self.transform(next(children))
+            statements = self.transform(next(children))
+
+            if isinstance(statements, list):
+                statement_block = CodeBlock(*statements)
+            else:
+                statement_block = CodeBlock(statements)
+
+            return While(condition, statement_block)
+
+
+
+else:
+    class CCodeConverter():  # type: ignore
+        def __init__(self, *args, **kwargs):
+            raise ImportError("Module not Installed")
+
+
+def parse_c(source):
+    """Function for converting a C source code
+
+    The function reads the source code present in the given file and parses it
+    to give out SymPy Expressions
+
+    Returns
+    =======
+
+    src : list
+        List of Python expression strings
+
+    """
+    converter = CCodeConverter()
+    if os.path.exists(source):
+        src = converter.parse(source, flags = [])
+    else:
+        src = converter.parse_str(source, flags = [])
+    return src
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/fortran/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/fortran/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c65e37cf3de2dddbcee0fa5c7eeac2fdc9f685db
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/fortran/__init__.py
@@ -0,0 +1 @@
+"""Used for translating Fortran source code into a SymPy expression. """
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/fortran/fortran_parser.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/fortran/fortran_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..504249f6119a59a90d91c5e989f893cffe20e643
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/fortran/fortran_parser.py
@@ -0,0 +1,347 @@
+from sympy.external import import_module
+
+lfortran = import_module('lfortran')
+
+if lfortran:
+    from sympy.codegen.ast import (Variable, IntBaseType, FloatBaseType, String,
+                                   Return, FunctionDefinition, Assignment)
+    from sympy.core import Add, Mul, Integer, Float
+    from sympy.core.symbol import Symbol
+
+    asr_mod = lfortran.asr
+    asr = lfortran.asr.asr
+    src_to_ast = lfortran.ast.src_to_ast
+    ast_to_asr = lfortran.semantic.ast_to_asr.ast_to_asr
+
+    """
+    This module contains all the necessary Classes and Function used to Parse
+    Fortran code into SymPy expression
+
+    The module and its API are currently under development and experimental.
+    It is also dependent on LFortran for the ASR that is converted to SymPy syntax
+    which is also under development.
+    The module only supports the features currently supported by the LFortran ASR
+    which will be updated as the development of LFortran and this module progresses
+
+    You might find unexpected bugs and exceptions while using the module, feel free
+    to report them to the SymPy Issue Tracker
+
+    The API for the module might also change while in development if better and
+    more effective ways are discovered for the process
+
+    Features Supported
+    ==================
+
+    - Variable Declarations (integers and reals)
+    - Function Definitions
+    - Assignments and Basic Binary Operations
+
+
+    Notes
+    =====
+
+    The module depends on an external dependency
+
+    LFortran : Required to parse Fortran source code into ASR
+
+
+    References
+    ==========
+
+    .. [1] https://github.com/sympy/sympy/issues
+    .. [2] https://gitlab.com/lfortran/lfortran
+    .. [3] https://docs.lfortran.org/
+
+    """
+
+
+    class ASR2PyVisitor(asr.ASTVisitor):  # type: ignore
+        """
+        Visitor Class for LFortran ASR
+
+        It is a Visitor class derived from asr.ASRVisitor which visits all the
+        nodes of the LFortran ASR and creates corresponding AST node for each
+        ASR node
+
+        """
+
+        def __init__(self):
+            """Initialize the Parser"""
+            self._py_ast = []
+
+        def visit_TranslationUnit(self, node):
+            """
+            Function to visit all the elements of the Translation Unit
+            created by LFortran ASR
+            """
+            for s in node.global_scope.symbols:
+                sym = node.global_scope.symbols[s]
+                self.visit(sym)
+            for item in node.items:
+                self.visit(item)
+
+        def visit_Assignment(self, node):
+            """Visitor Function for Assignment
+
+            Visits each Assignment is the LFortran ASR and creates corresponding
+            assignment for SymPy.
+
+            Notes
+            =====
+
+            The function currently only supports variable assignment and binary
+            operation assignments of varying multitudes. Any type of numberS or
+            array is not supported.
+
+            Raises
+            ======
+
+            NotImplementedError() when called for Numeric assignments or Arrays
+
+            """
+            # TODO: Arithmetic Assignment
+            if isinstance(node.target, asr.Variable):
+                target = node.target
+                value = node.value
+                if isinstance(value, asr.Variable):
+                    new_node = Assignment(
+                            Variable(
+                                    target.name
+                                ),
+                            Variable(
+                                    value.name
+                                )
+                        )
+                elif (type(value) == asr.BinOp):
+                    exp_ast = call_visitor(value)
+                    for expr in exp_ast:
+                        new_node = Assignment(
+                                Variable(target.name),
+                                expr
+                            )
+                else:
+                    raise NotImplementedError("Numeric assignments not supported")
+            else:
+                raise NotImplementedError("Arrays not supported")
+            self._py_ast.append(new_node)
+
+        def visit_BinOp(self, node):
+            """Visitor Function for Binary Operations
+
+            Visits each binary operation present in the LFortran ASR like addition,
+            subtraction, multiplication, division and creates the corresponding
+            operation node in SymPy's AST
+
+            In case of more than one binary operations, the function calls the
+            call_visitor() function on the child nodes of the binary operations
+            recursively until all the operations have been processed.
+
+            Notes
+            =====
+
+            The function currently only supports binary operations with Variables
+            or other binary operations. Numerics are not supported as of yet.
+
+            Raises
+            ======
+
+            NotImplementedError() when called for Numeric assignments
+
+            """
+            # TODO: Integer Binary Operations
+            op = node.op
+            lhs = node.left
+            rhs = node.right
+
+            if (type(lhs) == asr.Variable):
+                left_value = Symbol(lhs.name)
+            elif(type(lhs) == asr.BinOp):
+                l_exp_ast = call_visitor(lhs)
+                for exp in l_exp_ast:
+                    left_value = exp
+            else:
+                raise NotImplementedError("Numbers Currently not supported")
+
+            if (type(rhs) == asr.Variable):
+                right_value = Symbol(rhs.name)
+            elif(type(rhs) == asr.BinOp):
+                r_exp_ast = call_visitor(rhs)
+                for exp in r_exp_ast:
+                    right_value = exp
+            else:
+                raise NotImplementedError("Numbers Currently not supported")
+
+            if isinstance(op, asr.Add):
+                new_node = Add(left_value, right_value)
+            elif isinstance(op, asr.Sub):
+                new_node = Add(left_value, -right_value)
+            elif isinstance(op, asr.Div):
+                new_node = Mul(left_value, 1/right_value)
+            elif isinstance(op, asr.Mul):
+                new_node = Mul(left_value, right_value)
+
+            self._py_ast.append(new_node)
+
+        def visit_Variable(self, node):
+            """Visitor Function for Variable Declaration
+
+            Visits each variable declaration present in the ASR and creates a
+            Symbol declaration for each variable
+
+            Notes
+            =====
+
+            The functions currently only support declaration of integer and
+            real variables. Other data types are still under development.
+
+            Raises
+            ======
+
+            NotImplementedError() when called for unsupported data types
+
+            """
+            if isinstance(node.type, asr.Integer):
+                var_type = IntBaseType(String('integer'))
+                value = Integer(0)
+            elif isinstance(node.type, asr.Real):
+                var_type = FloatBaseType(String('real'))
+                value = Float(0.0)
+            else:
+                raise NotImplementedError("Data type not supported")
+
+            if not (node.intent == 'in'):
+                new_node = Variable(
+                    node.name
+                ).as_Declaration(
+                    type = var_type,
+                    value = value
+                )
+                self._py_ast.append(new_node)
+
+        def visit_Sequence(self, seq):
+            """Visitor Function for code sequence
+
+            Visits a code sequence/ block and calls the visitor function on all the
+            children of the code block to create corresponding code in python
+
+            """
+            if seq is not None:
+                for node in seq:
+                    self._py_ast.append(call_visitor(node))
+
+        def visit_Num(self, node):
+            """Visitor Function for Numbers in ASR
+
+            This function is currently under development and will be updated
+            with improvements in the LFortran ASR
+
+            """
+            # TODO:Numbers when the LFortran ASR is updated
+            # self._py_ast.append(Integer(node.n))
+            pass
+
+        def visit_Function(self, node):
+            """Visitor Function for function Definitions
+
+            Visits each function definition present in the ASR and creates a
+            function definition node in the Python AST with all the elements of the
+            given function
+
+            The functions declare all the variables required as SymPy symbols in
+            the function before the function definition
+
+            This function also the call_visior_function to parse the contents of
+            the function body
+
+            """
+            # TODO: Return statement, variable declaration
+            fn_args = [Variable(arg_iter.name) for arg_iter in node.args]
+            fn_body = []
+            fn_name = node.name
+            for i in node.body:
+                fn_ast = call_visitor(i)
+            try:
+                fn_body_expr = fn_ast
+            except UnboundLocalError:
+                fn_body_expr = []
+            for sym in node.symtab.symbols:
+                decl = call_visitor(node.symtab.symbols[sym])
+                for symbols in decl:
+                    fn_body.append(symbols)
+            for elem in fn_body_expr:
+                fn_body.append(elem)
+            fn_body.append(
+                Return(
+                    Variable(
+                        node.return_var.name
+                    )
+                )
+            )
+            if isinstance(node.return_var.type, asr.Integer):
+                ret_type = IntBaseType(String('integer'))
+            elif isinstance(node.return_var.type, asr.Real):
+                ret_type = FloatBaseType(String('real'))
+            else:
+                raise NotImplementedError("Data type not supported")
+            new_node = FunctionDefinition(
+                        return_type = ret_type,
+                        name = fn_name,
+                        parameters = fn_args,
+                        body = fn_body
+                    )
+            self._py_ast.append(new_node)
+
+        def ret_ast(self):
+            """Returns the AST nodes"""
+            return self._py_ast
+else:
+    class ASR2PyVisitor():  # type: ignore
+        def __init__(self, *args, **kwargs):
+            raise ImportError('lfortran not available')
+
+def call_visitor(fort_node):
+    """Calls the AST Visitor on the Module
+
+    This function is used to call the AST visitor for a program or module
+    It imports all the required modules and calls the visit() function
+    on the given node
+
+    Parameters
+    ==========
+
+    fort_node : LFortran ASR object
+        Node for the operation for which the NodeVisitor is called
+
+    Returns
+    =======
+
+    res_ast : list
+        list of SymPy AST Nodes
+
+    """
+    v = ASR2PyVisitor()
+    v.visit(fort_node)
+    res_ast = v.ret_ast()
+    return res_ast
+
+
+def src_to_sympy(src):
+    """Wrapper function to convert the given Fortran source code to SymPy Expressions
+
+    Parameters
+    ==========
+
+    src : string
+        A string with the Fortran source code
+
+    Returns
+    =======
+
+    py_src : string
+        A string with the Python source code compatible with SymPy
+
+    """
+    a_ast = src_to_ast(src, translation_unit=False)
+    a = ast_to_asr(a_ast)
+    py_src = call_visitor(a)
+    return py_src
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/LICENSE.txt b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..6bbfda911b2afada41a568218e31a6502dc68f44
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/LICENSE.txt
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright 2016, latex2sympy
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/LaTeX.g4 b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/LaTeX.g4
new file mode 100644
index 0000000000000000000000000000000000000000..fc2c30f9817931e2060b549a39f98a6a4f9cb1f7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/LaTeX.g4
@@ -0,0 +1,312 @@
+/*
+ ANTLR4 LaTeX Math Grammar
+
+ Ported from latex2sympy by @augustt198 https://github.com/augustt198/latex2sympy See license in
+ LICENSE.txt
+ */
+
+/*
+ After changing this file, it is necessary to run `python setup.py antlr` in the root directory of
+ the repository. This will regenerate the code in `sympy/parsing/latex/_antlr/*.py`.
+ */
+
+grammar LaTeX;
+
+options {
+	language = Python3;
+}
+
+WS: [ \t\r\n]+ -> skip;
+THINSPACE: ('\\,' | '\\thinspace') -> skip;
+MEDSPACE: ('\\:' | '\\medspace') -> skip;
+THICKSPACE: ('\\;' | '\\thickspace') -> skip;
+QUAD: '\\quad' -> skip;
+QQUAD: '\\qquad' -> skip;
+NEGTHINSPACE: ('\\!' | '\\negthinspace') -> skip;
+NEGMEDSPACE: '\\negmedspace' -> skip;
+NEGTHICKSPACE: '\\negthickspace' -> skip;
+CMD_LEFT: '\\left' -> skip;
+CMD_RIGHT: '\\right' -> skip;
+
+IGNORE:
+	(
+		'\\vrule'
+		| '\\vcenter'
+		| '\\vbox'
+		| '\\vskip'
+		| '\\vspace'
+		| '\\hfil'
+		| '\\*'
+		| '\\-'
+		| '\\.'
+		| '\\/'
+		| '\\"'
+		| '\\('
+		| '\\='
+	) -> skip;
+
+ADD: '+';
+SUB: '-';
+MUL: '*';
+DIV: '/';
+
+L_PAREN: '(';
+R_PAREN: ')';
+L_BRACE: '{';
+R_BRACE: '}';
+L_BRACE_LITERAL: '\\{';
+R_BRACE_LITERAL: '\\}';
+L_BRACKET: '[';
+R_BRACKET: ']';
+
+BAR: '|';
+
+R_BAR: '\\right|';
+L_BAR: '\\left|';
+
+L_ANGLE: '\\langle';
+R_ANGLE: '\\rangle';
+FUNC_LIM: '\\lim';
+LIM_APPROACH_SYM:
+	'\\to'
+	| '\\rightarrow'
+	| '\\Rightarrow'
+	| '\\longrightarrow'
+	| '\\Longrightarrow';
+FUNC_INT:
+    '\\int'
+    | '\\int\\limits';
+FUNC_SUM: '\\sum';
+FUNC_PROD: '\\prod';
+
+FUNC_EXP: '\\exp';
+FUNC_LOG: '\\log';
+FUNC_LG: '\\lg';
+FUNC_LN: '\\ln';
+FUNC_SIN: '\\sin';
+FUNC_COS: '\\cos';
+FUNC_TAN: '\\tan';
+FUNC_CSC: '\\csc';
+FUNC_SEC: '\\sec';
+FUNC_COT: '\\cot';
+
+FUNC_ARCSIN: '\\arcsin';
+FUNC_ARCCOS: '\\arccos';
+FUNC_ARCTAN: '\\arctan';
+FUNC_ARCCSC: '\\arccsc';
+FUNC_ARCSEC: '\\arcsec';
+FUNC_ARCCOT: '\\arccot';
+
+FUNC_SINH: '\\sinh';
+FUNC_COSH: '\\cosh';
+FUNC_TANH: '\\tanh';
+FUNC_ARSINH: '\\arsinh';
+FUNC_ARCOSH: '\\arcosh';
+FUNC_ARTANH: '\\artanh';
+
+L_FLOOR: '\\lfloor';
+R_FLOOR: '\\rfloor';
+L_CEIL: '\\lceil';
+R_CEIL: '\\rceil';
+
+FUNC_SQRT: '\\sqrt';
+FUNC_OVERLINE: '\\overline';
+
+CMD_TIMES: '\\times';
+CMD_CDOT: '\\cdot';
+CMD_DIV: '\\div';
+CMD_FRAC:
+    '\\frac'
+    | '\\dfrac'
+    | '\\tfrac';
+CMD_BINOM: '\\binom';
+CMD_DBINOM: '\\dbinom';
+CMD_TBINOM: '\\tbinom';
+
+CMD_MATHIT: '\\mathit';
+
+UNDERSCORE: '_';
+CARET: '^';
+COLON: ':';
+
+fragment WS_CHAR: [ \t\r\n];
+DIFFERENTIAL: 'd' WS_CHAR*? ([a-zA-Z] | '\\' [a-zA-Z]+);
+
+LETTER: [a-zA-Z];
+DIGIT: [0-9];
+
+EQUAL: (('&' WS_CHAR*?)? '=') | ('=' (WS_CHAR*? '&')?);
+NEQ: '\\neq';
+
+LT: '<';
+LTE: ('\\leq' | '\\le' | LTE_Q | LTE_S);
+LTE_Q: '\\leqq';
+LTE_S: '\\leqslant';
+
+GT: '>';
+GTE: ('\\geq' | '\\ge' | GTE_Q | GTE_S);
+GTE_Q: '\\geqq';
+GTE_S: '\\geqslant';
+
+BANG: '!';
+
+SINGLE_QUOTES: '\''+;
+
+SYMBOL: '\\' [a-zA-Z]+;
+
+math: relation;
+
+relation:
+	relation (EQUAL | LT | LTE | GT | GTE | NEQ) relation
+	| expr;
+
+equality: expr EQUAL expr;
+
+expr: additive;
+
+additive: additive (ADD | SUB) additive | mp;
+
+// mult part
+mp:
+	mp (MUL | CMD_TIMES | CMD_CDOT | DIV | CMD_DIV | COLON) mp
+	| unary;
+
+mp_nofunc:
+	mp_nofunc (
+		MUL
+		| CMD_TIMES
+		| CMD_CDOT
+		| DIV
+		| CMD_DIV
+		| COLON
+	) mp_nofunc
+	| unary_nofunc;
+
+unary: (ADD | SUB) unary | postfix+;
+
+unary_nofunc:
+	(ADD | SUB) unary_nofunc
+	| postfix postfix_nofunc*;
+
+postfix: exp postfix_op*;
+postfix_nofunc: exp_nofunc postfix_op*;
+postfix_op: BANG | eval_at;
+
+eval_at:
+	BAR (eval_at_sup | eval_at_sub | eval_at_sup eval_at_sub);
+
+eval_at_sub: UNDERSCORE L_BRACE (expr | equality) R_BRACE;
+
+eval_at_sup: CARET L_BRACE (expr | equality) R_BRACE;
+
+exp: exp CARET (atom | L_BRACE expr R_BRACE) subexpr? | comp;
+
+exp_nofunc:
+	exp_nofunc CARET (atom | L_BRACE expr R_BRACE) subexpr?
+	| comp_nofunc;
+
+comp:
+	group
+	| abs_group
+	| func
+	| atom
+	| floor
+	| ceil;
+
+comp_nofunc:
+	group
+	| abs_group
+	| atom
+	| floor
+	| ceil;
+
+group:
+	L_PAREN expr R_PAREN
+	| L_BRACKET expr R_BRACKET
+	| L_BRACE expr R_BRACE
+	| L_BRACE_LITERAL expr R_BRACE_LITERAL;
+
+abs_group: BAR expr BAR;
+
+number: DIGIT+ (',' DIGIT DIGIT DIGIT)* ('.' DIGIT+)?;
+
+atom: (LETTER | SYMBOL) (subexpr? SINGLE_QUOTES? | SINGLE_QUOTES? subexpr?)
+	| number
+	| DIFFERENTIAL
+	| mathit
+	| frac
+	| binom
+	| bra
+	| ket;
+
+bra: L_ANGLE expr (R_BAR | BAR);
+ket: (L_BAR | BAR) expr R_ANGLE;
+
+mathit: CMD_MATHIT L_BRACE mathit_text R_BRACE;
+mathit_text: LETTER*;
+
+frac: CMD_FRAC (upperd = DIGIT | L_BRACE upper = expr R_BRACE)
+    (lowerd = DIGIT | L_BRACE lower = expr R_BRACE);
+
+binom:
+	(CMD_BINOM | CMD_DBINOM | CMD_TBINOM) L_BRACE n = expr R_BRACE L_BRACE k = expr R_BRACE;
+
+floor: L_FLOOR val = expr R_FLOOR;
+ceil: L_CEIL val = expr R_CEIL;
+
+func_normal:
+	FUNC_EXP
+	| FUNC_LOG
+	| FUNC_LG
+	| FUNC_LN
+	| FUNC_SIN
+	| FUNC_COS
+	| FUNC_TAN
+	| FUNC_CSC
+	| FUNC_SEC
+	| FUNC_COT
+	| FUNC_ARCSIN
+	| FUNC_ARCCOS
+	| FUNC_ARCTAN
+	| FUNC_ARCCSC
+	| FUNC_ARCSEC
+	| FUNC_ARCCOT
+	| FUNC_SINH
+	| FUNC_COSH
+	| FUNC_TANH
+	| FUNC_ARSINH
+	| FUNC_ARCOSH
+	| FUNC_ARTANH;
+
+func:
+	func_normal (subexpr? supexpr? | supexpr? subexpr?) (
+		L_PAREN func_arg R_PAREN
+		| func_arg_noparens
+	)
+	| (LETTER | SYMBOL) (subexpr? SINGLE_QUOTES? | SINGLE_QUOTES? subexpr?) // e.g. f(x), f_1'(x)
+	L_PAREN args R_PAREN
+	| FUNC_INT (subexpr supexpr | supexpr subexpr)? (
+		additive? DIFFERENTIAL
+		| frac
+		| additive
+	)
+	| FUNC_SQRT (L_BRACKET root = expr R_BRACKET)? L_BRACE base = expr R_BRACE
+	| FUNC_OVERLINE L_BRACE base = expr R_BRACE
+	| (FUNC_SUM | FUNC_PROD) (subeq supexpr | supexpr subeq) mp
+	| FUNC_LIM limit_sub mp;
+
+args: (expr ',' args) | expr;
+
+limit_sub:
+	UNDERSCORE L_BRACE (LETTER | SYMBOL) LIM_APPROACH_SYM expr (
+		CARET ((L_BRACE (ADD | SUB) R_BRACE) | ADD | SUB)
+	)? R_BRACE;
+
+func_arg: expr | (expr ',' func_arg);
+func_arg_noparens: mp_nofunc;
+
+subexpr: UNDERSCORE (atom | L_BRACE expr R_BRACE);
+supexpr: CARET (atom | L_BRACE expr R_BRACE);
+
+subeq: UNDERSCORE L_BRACE equality R_BRACE;
+supeq: UNDERSCORE L_BRACE equality R_BRACE;
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9466d37b8b06f1f292c73f975e44d21c96da10d1
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/__init__.py
@@ -0,0 +1,204 @@
+from sympy.external import import_module
+from sympy.utilities.decorator import doctest_depends_on
+from re import compile as rcompile
+
+from sympy.parsing.latex.lark import LarkLaTeXParser, TransformToSymPyExpr, parse_latex_lark # noqa
+
+from .errors import LaTeXParsingError  # noqa
+
+
+IGNORE_L = r"\s*[{]*\s*"
+IGNORE_R = r"\s*[}]*\s*"
+NO_LEFT = r"(? len(latex_str):
+            e = len(latex_str)
+            eellipsis = ""
+
+        if x[3] in END_DELIM_REPR:
+            err = (f"Extra '{x[2]}' at index {x[0]} or "
+                   "missing corresponding "
+                   f"'{BEGIN_DELIM_REPR[MATRIX_DELIMS_INV[x[3]]]}' "
+                   f"in LaTeX string: {sellipsis}{latex_str[s:e]}"
+                   f"{eellipsis}")
+            raise LaTeXParsingError(err)
+
+        if x[7] is None:
+            err = (f"Extra '{x[2]}' at index {x[0]} or "
+                   "missing corresponding "
+                   f"'{END_DELIM_REPR[MATRIX_DELIMS[x[3]]]}' "
+                   f"in LaTeX string: {sellipsis}{latex_str[s:e]}"
+                   f"{eellipsis}")
+            raise LaTeXParsingError(err)
+
+        correct_end_regex = MATRIX_DELIMS[x[3]]
+        sellipsis = "..." if x[0] > 0 else ""
+        eellipsis = "..." if x[5] < len(latex_str) else ""
+        if x[7] != correct_end_regex:
+            err = ("Expected "
+                   f"'{END_DELIM_REPR[correct_end_regex]}' "
+                   f"to close the '{x[2]}' at index {x[0]} but "
+                   f"found '{x[6]}' at index {x[4]} of LaTeX "
+                   f"string instead: {sellipsis}{latex_str[x[0]:x[5]]}"
+                   f"{eellipsis}")
+            raise LaTeXParsingError(err)
+
+__doctest_requires__ = {('parse_latex',): ['antlr4', 'lark']}
+
+
+@doctest_depends_on(modules=('antlr4', 'lark'))
+def parse_latex(s, strict=False, backend="antlr"):
+    r"""Converts the input LaTeX string ``s`` to a SymPy ``Expr``.
+
+    Parameters
+    ==========
+
+    s : str
+        The LaTeX string to parse. In Python source containing LaTeX,
+        *raw strings* (denoted with ``r"``, like this one) are preferred,
+        as LaTeX makes liberal use of the ``\`` character, which would
+        trigger escaping in normal Python strings.
+    backend : str, optional
+        Currently, there are two backends supported: ANTLR, and Lark.
+        The default setting is to use the ANTLR backend, which can be
+        changed to Lark if preferred.
+
+        Use ``backend="antlr"`` for the ANTLR-based parser, and
+        ``backend="lark"`` for the Lark-based parser.
+
+        The ``backend`` option is case-sensitive, and must be in
+        all lowercase.
+    strict : bool, optional
+        This option is only available with the ANTLR backend.
+
+        If True, raise an exception if the string cannot be parsed as
+        valid LaTeX. If False, try to recover gracefully from common
+        mistakes.
+
+    Examples
+    ========
+
+    >>> from sympy.parsing.latex import parse_latex
+    >>> expr = parse_latex(r"\frac {1 + \sqrt {\a}} {\b}")
+    >>> expr
+    (sqrt(a) + 1)/b
+    >>> expr.evalf(4, subs=dict(a=5, b=2))
+    1.618
+    >>> func = parse_latex(r"\int_1^\alpha \dfrac{\mathrm{d}t}{t}", backend="lark")
+    >>> func.evalf(subs={"alpha": 2})
+    0.693147180559945
+    """
+
+    check_matrix_delimiters(s)
+
+    if backend == "antlr":
+        _latex = import_module(
+            'sympy.parsing.latex._parse_latex_antlr',
+            import_kwargs={'fromlist': ['X']})
+
+        if _latex is not None:
+            return _latex.parse_latex(s, strict)
+    elif backend == "lark":
+        return parse_latex_lark(s)
+    else:
+        raise NotImplementedError(f"Using the '{backend}' backend in the LaTeX" \
+                                   " parser is not supported.")
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d690e1eb8631ee7731fc1875769d3a4704a1743
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__init__.py
@@ -0,0 +1,9 @@
+# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
+#
+# Generated from ../LaTeX.g4, derived from latex2sympy
+#     latex2sympy is licensed under the MIT license
+#     https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt
+#
+# Generated with antlr4
+#    antlr4 is licensed under the BSD-3-Clause License
+#    https://github.com/antlr/antlr4/blob/master/LICENSE.txt
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/latexlexer.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/latexlexer.py
new file mode 100644
index 0000000000000000000000000000000000000000..46ca959736c967782eef360b9b3268ccd0be0979
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/latexlexer.py
@@ -0,0 +1,512 @@
+# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
+#
+# Generated from ../LaTeX.g4, derived from latex2sympy
+#     latex2sympy is licensed under the MIT license
+#     https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt
+#
+# Generated with antlr4
+#    antlr4 is licensed under the BSD-3-Clause License
+#    https://github.com/antlr/antlr4/blob/master/LICENSE.txt
+from antlr4 import *
+from io import StringIO
+import sys
+if sys.version_info[1] > 5:
+    from typing import TextIO
+else:
+    from typing.io import TextIO
+
+
+def serializedATN():
+    return [
+        4,0,91,911,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,
+        2,6,7,6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2,
+        13,7,13,2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7,
+        19,2,20,7,20,2,21,7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7,25,2,
+        26,7,26,2,27,7,27,2,28,7,28,2,29,7,29,2,30,7,30,2,31,7,31,2,32,7,
+        32,2,33,7,33,2,34,7,34,2,35,7,35,2,36,7,36,2,37,7,37,2,38,7,38,2,
+        39,7,39,2,40,7,40,2,41,7,41,2,42,7,42,2,43,7,43,2,44,7,44,2,45,7,
+        45,2,46,7,46,2,47,7,47,2,48,7,48,2,49,7,49,2,50,7,50,2,51,7,51,2,
+        52,7,52,2,53,7,53,2,54,7,54,2,55,7,55,2,56,7,56,2,57,7,57,2,58,7,
+        58,2,59,7,59,2,60,7,60,2,61,7,61,2,62,7,62,2,63,7,63,2,64,7,64,2,
+        65,7,65,2,66,7,66,2,67,7,67,2,68,7,68,2,69,7,69,2,70,7,70,2,71,7,
+        71,2,72,7,72,2,73,7,73,2,74,7,74,2,75,7,75,2,76,7,76,2,77,7,77,2,
+        78,7,78,2,79,7,79,2,80,7,80,2,81,7,81,2,82,7,82,2,83,7,83,2,84,7,
+        84,2,85,7,85,2,86,7,86,2,87,7,87,2,88,7,88,2,89,7,89,2,90,7,90,2,
+        91,7,91,1,0,1,0,1,1,1,1,1,2,4,2,191,8,2,11,2,12,2,192,1,2,1,2,1,
+        3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,3,3,209,8,3,1,3,1,
+        3,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,3,4,224,8,4,1,4,1,
+        4,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,3,5,241,8,
+        5,1,5,1,5,1,6,1,6,1,6,1,6,1,6,1,6,1,6,1,6,1,7,1,7,1,7,1,7,1,7,1,
+        7,1,7,1,7,1,7,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,
+        8,1,8,1,8,3,8,277,8,8,1,8,1,8,1,9,1,9,1,9,1,9,1,9,1,9,1,9,1,9,1,
+        9,1,9,1,9,1,9,1,9,1,9,1,9,1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,10,
+        1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,11,1,11,1,11,1,11,
+        1,11,1,11,1,11,1,11,1,12,1,12,1,12,1,12,1,12,1,12,1,12,1,12,1,12,
+        1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,
+        1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,
+        1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,
+        1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,3,13,
+        381,8,13,1,13,1,13,1,14,1,14,1,15,1,15,1,16,1,16,1,17,1,17,1,18,
+        1,18,1,19,1,19,1,20,1,20,1,21,1,21,1,22,1,22,1,22,1,23,1,23,1,23,
+        1,24,1,24,1,25,1,25,1,26,1,26,1,27,1,27,1,27,1,27,1,27,1,27,1,27,
+        1,27,1,28,1,28,1,28,1,28,1,28,1,28,1,28,1,29,1,29,1,29,1,29,1,29,
+        1,29,1,29,1,29,1,30,1,30,1,30,1,30,1,30,1,30,1,30,1,30,1,31,1,31,
+        1,31,1,31,1,31,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,
+        1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,
+        1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,
+        1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,
+        1,32,1,32,1,32,1,32,1,32,1,32,3,32,504,8,32,1,33,1,33,1,33,1,33,
+        1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,3,33,521,
+        8,33,1,34,1,34,1,34,1,34,1,34,1,35,1,35,1,35,1,35,1,35,1,35,1,36,
+        1,36,1,36,1,36,1,36,1,37,1,37,1,37,1,37,1,37,1,38,1,38,1,38,1,38,
+        1,39,1,39,1,39,1,39,1,40,1,40,1,40,1,40,1,40,1,41,1,41,1,41,1,41,
+        1,41,1,42,1,42,1,42,1,42,1,42,1,43,1,43,1,43,1,43,1,43,1,44,1,44,
+        1,44,1,44,1,44,1,45,1,45,1,45,1,45,1,45,1,46,1,46,1,46,1,46,1,46,
+        1,46,1,46,1,46,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,48,1,48,
+        1,48,1,48,1,48,1,48,1,48,1,48,1,49,1,49,1,49,1,49,1,49,1,49,1,49,
+        1,49,1,50,1,50,1,50,1,50,1,50,1,50,1,50,1,50,1,51,1,51,1,51,1,51,
+        1,51,1,51,1,51,1,51,1,52,1,52,1,52,1,52,1,52,1,52,1,53,1,53,1,53,
+        1,53,1,53,1,53,1,54,1,54,1,54,1,54,1,54,1,54,1,55,1,55,1,55,1,55,
+        1,55,1,55,1,55,1,55,1,56,1,56,1,56,1,56,1,56,1,56,1,56,1,56,1,57,
+        1,57,1,57,1,57,1,57,1,57,1,57,1,57,1,58,1,58,1,58,1,58,1,58,1,58,
+        1,58,1,58,1,59,1,59,1,59,1,59,1,59,1,59,1,59,1,59,1,60,1,60,1,60,
+        1,60,1,60,1,60,1,60,1,61,1,61,1,61,1,61,1,61,1,61,1,61,1,62,1,62,
+        1,62,1,62,1,62,1,62,1,63,1,63,1,63,1,63,1,63,1,63,1,63,1,63,1,63,
+        1,63,1,64,1,64,1,64,1,64,1,64,1,64,1,64,1,65,1,65,1,65,1,65,1,65,
+        1,65,1,66,1,66,1,66,1,66,1,66,1,67,1,67,1,67,1,67,1,67,1,67,1,67,
+        1,67,1,67,1,67,1,67,1,67,1,67,1,67,1,67,1,67,1,67,3,67,753,8,67,
+        1,68,1,68,1,68,1,68,1,68,1,68,1,68,1,69,1,69,1,69,1,69,1,69,1,69,
+        1,69,1,69,1,70,1,70,1,70,1,70,1,70,1,70,1,70,1,70,1,71,1,71,1,71,
+        1,71,1,71,1,71,1,71,1,71,1,72,1,72,1,73,1,73,1,74,1,74,1,75,1,75,
+        1,76,1,76,5,76,796,8,76,10,76,12,76,799,9,76,1,76,1,76,1,76,4,76,
+        804,8,76,11,76,12,76,805,3,76,808,8,76,1,77,1,77,1,78,1,78,1,79,
+        1,79,5,79,816,8,79,10,79,12,79,819,9,79,3,79,821,8,79,1,79,1,79,
+        1,79,5,79,826,8,79,10,79,12,79,829,9,79,1,79,3,79,832,8,79,3,79,
+        834,8,79,1,80,1,80,1,80,1,80,1,80,1,81,1,81,1,82,1,82,1,82,1,82,
+        1,82,1,82,1,82,1,82,1,82,3,82,852,8,82,1,83,1,83,1,83,1,83,1,83,
+        1,83,1,84,1,84,1,84,1,84,1,84,1,84,1,84,1,84,1,84,1,84,1,85,1,85,
+        1,86,1,86,1,86,1,86,1,86,1,86,1,86,1,86,1,86,3,86,881,8,86,1,87,
+        1,87,1,87,1,87,1,87,1,87,1,88,1,88,1,88,1,88,1,88,1,88,1,88,1,88,
+        1,88,1,88,1,89,1,89,1,90,4,90,902,8,90,11,90,12,90,903,1,91,1,91,
+        4,91,908,8,91,11,91,12,91,909,3,797,817,827,0,92,1,1,3,2,5,3,7,4,
+        9,5,11,6,13,7,15,8,17,9,19,10,21,11,23,12,25,13,27,14,29,15,31,16,
+        33,17,35,18,37,19,39,20,41,21,43,22,45,23,47,24,49,25,51,26,53,27,
+        55,28,57,29,59,30,61,31,63,32,65,33,67,34,69,35,71,36,73,37,75,38,
+        77,39,79,40,81,41,83,42,85,43,87,44,89,45,91,46,93,47,95,48,97,49,
+        99,50,101,51,103,52,105,53,107,54,109,55,111,56,113,57,115,58,117,
+        59,119,60,121,61,123,62,125,63,127,64,129,65,131,66,133,67,135,68,
+        137,69,139,70,141,71,143,72,145,73,147,74,149,75,151,0,153,76,155,
+        77,157,78,159,79,161,80,163,81,165,82,167,83,169,84,171,85,173,86,
+        175,87,177,88,179,89,181,90,183,91,1,0,3,3,0,9,10,13,13,32,32,2,
+        0,65,90,97,122,1,0,48,57,949,0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0,
+        0,7,1,0,0,0,0,9,1,0,0,0,0,11,1,0,0,0,0,13,1,0,0,0,0,15,1,0,0,0,0,
+        17,1,0,0,0,0,19,1,0,0,0,0,21,1,0,0,0,0,23,1,0,0,0,0,25,1,0,0,0,0,
+        27,1,0,0,0,0,29,1,0,0,0,0,31,1,0,0,0,0,33,1,0,0,0,0,35,1,0,0,0,0,
+        37,1,0,0,0,0,39,1,0,0,0,0,41,1,0,0,0,0,43,1,0,0,0,0,45,1,0,0,0,0,
+        47,1,0,0,0,0,49,1,0,0,0,0,51,1,0,0,0,0,53,1,0,0,0,0,55,1,0,0,0,0,
+        57,1,0,0,0,0,59,1,0,0,0,0,61,1,0,0,0,0,63,1,0,0,0,0,65,1,0,0,0,0,
+        67,1,0,0,0,0,69,1,0,0,0,0,71,1,0,0,0,0,73,1,0,0,0,0,75,1,0,0,0,0,
+        77,1,0,0,0,0,79,1,0,0,0,0,81,1,0,0,0,0,83,1,0,0,0,0,85,1,0,0,0,0,
+        87,1,0,0,0,0,89,1,0,0,0,0,91,1,0,0,0,0,93,1,0,0,0,0,95,1,0,0,0,0,
+        97,1,0,0,0,0,99,1,0,0,0,0,101,1,0,0,0,0,103,1,0,0,0,0,105,1,0,0,
+        0,0,107,1,0,0,0,0,109,1,0,0,0,0,111,1,0,0,0,0,113,1,0,0,0,0,115,
+        1,0,0,0,0,117,1,0,0,0,0,119,1,0,0,0,0,121,1,0,0,0,0,123,1,0,0,0,
+        0,125,1,0,0,0,0,127,1,0,0,0,0,129,1,0,0,0,0,131,1,0,0,0,0,133,1,
+        0,0,0,0,135,1,0,0,0,0,137,1,0,0,0,0,139,1,0,0,0,0,141,1,0,0,0,0,
+        143,1,0,0,0,0,145,1,0,0,0,0,147,1,0,0,0,0,149,1,0,0,0,0,153,1,0,
+        0,0,0,155,1,0,0,0,0,157,1,0,0,0,0,159,1,0,0,0,0,161,1,0,0,0,0,163,
+        1,0,0,0,0,165,1,0,0,0,0,167,1,0,0,0,0,169,1,0,0,0,0,171,1,0,0,0,
+        0,173,1,0,0,0,0,175,1,0,0,0,0,177,1,0,0,0,0,179,1,0,0,0,0,181,1,
+        0,0,0,0,183,1,0,0,0,1,185,1,0,0,0,3,187,1,0,0,0,5,190,1,0,0,0,7,
+        208,1,0,0,0,9,223,1,0,0,0,11,240,1,0,0,0,13,244,1,0,0,0,15,252,1,
+        0,0,0,17,276,1,0,0,0,19,280,1,0,0,0,21,295,1,0,0,0,23,312,1,0,0,
+        0,25,320,1,0,0,0,27,380,1,0,0,0,29,384,1,0,0,0,31,386,1,0,0,0,33,
+        388,1,0,0,0,35,390,1,0,0,0,37,392,1,0,0,0,39,394,1,0,0,0,41,396,
+        1,0,0,0,43,398,1,0,0,0,45,400,1,0,0,0,47,403,1,0,0,0,49,406,1,0,
+        0,0,51,408,1,0,0,0,53,410,1,0,0,0,55,412,1,0,0,0,57,420,1,0,0,0,
+        59,427,1,0,0,0,61,435,1,0,0,0,63,443,1,0,0,0,65,503,1,0,0,0,67,520,
+        1,0,0,0,69,522,1,0,0,0,71,527,1,0,0,0,73,533,1,0,0,0,75,538,1,0,
+        0,0,77,543,1,0,0,0,79,547,1,0,0,0,81,551,1,0,0,0,83,556,1,0,0,0,
+        85,561,1,0,0,0,87,566,1,0,0,0,89,571,1,0,0,0,91,576,1,0,0,0,93,581,
+        1,0,0,0,95,589,1,0,0,0,97,597,1,0,0,0,99,605,1,0,0,0,101,613,1,0,
+        0,0,103,621,1,0,0,0,105,629,1,0,0,0,107,635,1,0,0,0,109,641,1,0,
+        0,0,111,647,1,0,0,0,113,655,1,0,0,0,115,663,1,0,0,0,117,671,1,0,
+        0,0,119,679,1,0,0,0,121,687,1,0,0,0,123,694,1,0,0,0,125,701,1,0,
+        0,0,127,707,1,0,0,0,129,717,1,0,0,0,131,724,1,0,0,0,133,730,1,0,
+        0,0,135,752,1,0,0,0,137,754,1,0,0,0,139,761,1,0,0,0,141,769,1,0,
+        0,0,143,777,1,0,0,0,145,785,1,0,0,0,147,787,1,0,0,0,149,789,1,0,
+        0,0,151,791,1,0,0,0,153,793,1,0,0,0,155,809,1,0,0,0,157,811,1,0,
+        0,0,159,833,1,0,0,0,161,835,1,0,0,0,163,840,1,0,0,0,165,851,1,0,
+        0,0,167,853,1,0,0,0,169,859,1,0,0,0,171,869,1,0,0,0,173,880,1,0,
+        0,0,175,882,1,0,0,0,177,888,1,0,0,0,179,898,1,0,0,0,181,901,1,0,
+        0,0,183,905,1,0,0,0,185,186,5,44,0,0,186,2,1,0,0,0,187,188,5,46,
+        0,0,188,4,1,0,0,0,189,191,7,0,0,0,190,189,1,0,0,0,191,192,1,0,0,
+        0,192,190,1,0,0,0,192,193,1,0,0,0,193,194,1,0,0,0,194,195,6,2,0,
+        0,195,6,1,0,0,0,196,197,5,92,0,0,197,209,5,44,0,0,198,199,5,92,0,
+        0,199,200,5,116,0,0,200,201,5,104,0,0,201,202,5,105,0,0,202,203,
+        5,110,0,0,203,204,5,115,0,0,204,205,5,112,0,0,205,206,5,97,0,0,206,
+        207,5,99,0,0,207,209,5,101,0,0,208,196,1,0,0,0,208,198,1,0,0,0,209,
+        210,1,0,0,0,210,211,6,3,0,0,211,8,1,0,0,0,212,213,5,92,0,0,213,224,
+        5,58,0,0,214,215,5,92,0,0,215,216,5,109,0,0,216,217,5,101,0,0,217,
+        218,5,100,0,0,218,219,5,115,0,0,219,220,5,112,0,0,220,221,5,97,0,
+        0,221,222,5,99,0,0,222,224,5,101,0,0,223,212,1,0,0,0,223,214,1,0,
+        0,0,224,225,1,0,0,0,225,226,6,4,0,0,226,10,1,0,0,0,227,228,5,92,
+        0,0,228,241,5,59,0,0,229,230,5,92,0,0,230,231,5,116,0,0,231,232,
+        5,104,0,0,232,233,5,105,0,0,233,234,5,99,0,0,234,235,5,107,0,0,235,
+        236,5,115,0,0,236,237,5,112,0,0,237,238,5,97,0,0,238,239,5,99,0,
+        0,239,241,5,101,0,0,240,227,1,0,0,0,240,229,1,0,0,0,241,242,1,0,
+        0,0,242,243,6,5,0,0,243,12,1,0,0,0,244,245,5,92,0,0,245,246,5,113,
+        0,0,246,247,5,117,0,0,247,248,5,97,0,0,248,249,5,100,0,0,249,250,
+        1,0,0,0,250,251,6,6,0,0,251,14,1,0,0,0,252,253,5,92,0,0,253,254,
+        5,113,0,0,254,255,5,113,0,0,255,256,5,117,0,0,256,257,5,97,0,0,257,
+        258,5,100,0,0,258,259,1,0,0,0,259,260,6,7,0,0,260,16,1,0,0,0,261,
+        262,5,92,0,0,262,277,5,33,0,0,263,264,5,92,0,0,264,265,5,110,0,0,
+        265,266,5,101,0,0,266,267,5,103,0,0,267,268,5,116,0,0,268,269,5,
+        104,0,0,269,270,5,105,0,0,270,271,5,110,0,0,271,272,5,115,0,0,272,
+        273,5,112,0,0,273,274,5,97,0,0,274,275,5,99,0,0,275,277,5,101,0,
+        0,276,261,1,0,0,0,276,263,1,0,0,0,277,278,1,0,0,0,278,279,6,8,0,
+        0,279,18,1,0,0,0,280,281,5,92,0,0,281,282,5,110,0,0,282,283,5,101,
+        0,0,283,284,5,103,0,0,284,285,5,109,0,0,285,286,5,101,0,0,286,287,
+        5,100,0,0,287,288,5,115,0,0,288,289,5,112,0,0,289,290,5,97,0,0,290,
+        291,5,99,0,0,291,292,5,101,0,0,292,293,1,0,0,0,293,294,6,9,0,0,294,
+        20,1,0,0,0,295,296,5,92,0,0,296,297,5,110,0,0,297,298,5,101,0,0,
+        298,299,5,103,0,0,299,300,5,116,0,0,300,301,5,104,0,0,301,302,5,
+        105,0,0,302,303,5,99,0,0,303,304,5,107,0,0,304,305,5,115,0,0,305,
+        306,5,112,0,0,306,307,5,97,0,0,307,308,5,99,0,0,308,309,5,101,0,
+        0,309,310,1,0,0,0,310,311,6,10,0,0,311,22,1,0,0,0,312,313,5,92,0,
+        0,313,314,5,108,0,0,314,315,5,101,0,0,315,316,5,102,0,0,316,317,
+        5,116,0,0,317,318,1,0,0,0,318,319,6,11,0,0,319,24,1,0,0,0,320,321,
+        5,92,0,0,321,322,5,114,0,0,322,323,5,105,0,0,323,324,5,103,0,0,324,
+        325,5,104,0,0,325,326,5,116,0,0,326,327,1,0,0,0,327,328,6,12,0,0,
+        328,26,1,0,0,0,329,330,5,92,0,0,330,331,5,118,0,0,331,332,5,114,
+        0,0,332,333,5,117,0,0,333,334,5,108,0,0,334,381,5,101,0,0,335,336,
+        5,92,0,0,336,337,5,118,0,0,337,338,5,99,0,0,338,339,5,101,0,0,339,
+        340,5,110,0,0,340,341,5,116,0,0,341,342,5,101,0,0,342,381,5,114,
+        0,0,343,344,5,92,0,0,344,345,5,118,0,0,345,346,5,98,0,0,346,347,
+        5,111,0,0,347,381,5,120,0,0,348,349,5,92,0,0,349,350,5,118,0,0,350,
+        351,5,115,0,0,351,352,5,107,0,0,352,353,5,105,0,0,353,381,5,112,
+        0,0,354,355,5,92,0,0,355,356,5,118,0,0,356,357,5,115,0,0,357,358,
+        5,112,0,0,358,359,5,97,0,0,359,360,5,99,0,0,360,381,5,101,0,0,361,
+        362,5,92,0,0,362,363,5,104,0,0,363,364,5,102,0,0,364,365,5,105,0,
+        0,365,381,5,108,0,0,366,367,5,92,0,0,367,381,5,42,0,0,368,369,5,
+        92,0,0,369,381,5,45,0,0,370,371,5,92,0,0,371,381,5,46,0,0,372,373,
+        5,92,0,0,373,381,5,47,0,0,374,375,5,92,0,0,375,381,5,34,0,0,376,
+        377,5,92,0,0,377,381,5,40,0,0,378,379,5,92,0,0,379,381,5,61,0,0,
+        380,329,1,0,0,0,380,335,1,0,0,0,380,343,1,0,0,0,380,348,1,0,0,0,
+        380,354,1,0,0,0,380,361,1,0,0,0,380,366,1,0,0,0,380,368,1,0,0,0,
+        380,370,1,0,0,0,380,372,1,0,0,0,380,374,1,0,0,0,380,376,1,0,0,0,
+        380,378,1,0,0,0,381,382,1,0,0,0,382,383,6,13,0,0,383,28,1,0,0,0,
+        384,385,5,43,0,0,385,30,1,0,0,0,386,387,5,45,0,0,387,32,1,0,0,0,
+        388,389,5,42,0,0,389,34,1,0,0,0,390,391,5,47,0,0,391,36,1,0,0,0,
+        392,393,5,40,0,0,393,38,1,0,0,0,394,395,5,41,0,0,395,40,1,0,0,0,
+        396,397,5,123,0,0,397,42,1,0,0,0,398,399,5,125,0,0,399,44,1,0,0,
+        0,400,401,5,92,0,0,401,402,5,123,0,0,402,46,1,0,0,0,403,404,5,92,
+        0,0,404,405,5,125,0,0,405,48,1,0,0,0,406,407,5,91,0,0,407,50,1,0,
+        0,0,408,409,5,93,0,0,409,52,1,0,0,0,410,411,5,124,0,0,411,54,1,0,
+        0,0,412,413,5,92,0,0,413,414,5,114,0,0,414,415,5,105,0,0,415,416,
+        5,103,0,0,416,417,5,104,0,0,417,418,5,116,0,0,418,419,5,124,0,0,
+        419,56,1,0,0,0,420,421,5,92,0,0,421,422,5,108,0,0,422,423,5,101,
+        0,0,423,424,5,102,0,0,424,425,5,116,0,0,425,426,5,124,0,0,426,58,
+        1,0,0,0,427,428,5,92,0,0,428,429,5,108,0,0,429,430,5,97,0,0,430,
+        431,5,110,0,0,431,432,5,103,0,0,432,433,5,108,0,0,433,434,5,101,
+        0,0,434,60,1,0,0,0,435,436,5,92,0,0,436,437,5,114,0,0,437,438,5,
+        97,0,0,438,439,5,110,0,0,439,440,5,103,0,0,440,441,5,108,0,0,441,
+        442,5,101,0,0,442,62,1,0,0,0,443,444,5,92,0,0,444,445,5,108,0,0,
+        445,446,5,105,0,0,446,447,5,109,0,0,447,64,1,0,0,0,448,449,5,92,
+        0,0,449,450,5,116,0,0,450,504,5,111,0,0,451,452,5,92,0,0,452,453,
+        5,114,0,0,453,454,5,105,0,0,454,455,5,103,0,0,455,456,5,104,0,0,
+        456,457,5,116,0,0,457,458,5,97,0,0,458,459,5,114,0,0,459,460,5,114,
+        0,0,460,461,5,111,0,0,461,504,5,119,0,0,462,463,5,92,0,0,463,464,
+        5,82,0,0,464,465,5,105,0,0,465,466,5,103,0,0,466,467,5,104,0,0,467,
+        468,5,116,0,0,468,469,5,97,0,0,469,470,5,114,0,0,470,471,5,114,0,
+        0,471,472,5,111,0,0,472,504,5,119,0,0,473,474,5,92,0,0,474,475,5,
+        108,0,0,475,476,5,111,0,0,476,477,5,110,0,0,477,478,5,103,0,0,478,
+        479,5,114,0,0,479,480,5,105,0,0,480,481,5,103,0,0,481,482,5,104,
+        0,0,482,483,5,116,0,0,483,484,5,97,0,0,484,485,5,114,0,0,485,486,
+        5,114,0,0,486,487,5,111,0,0,487,504,5,119,0,0,488,489,5,92,0,0,489,
+        490,5,76,0,0,490,491,5,111,0,0,491,492,5,110,0,0,492,493,5,103,0,
+        0,493,494,5,114,0,0,494,495,5,105,0,0,495,496,5,103,0,0,496,497,
+        5,104,0,0,497,498,5,116,0,0,498,499,5,97,0,0,499,500,5,114,0,0,500,
+        501,5,114,0,0,501,502,5,111,0,0,502,504,5,119,0,0,503,448,1,0,0,
+        0,503,451,1,0,0,0,503,462,1,0,0,0,503,473,1,0,0,0,503,488,1,0,0,
+        0,504,66,1,0,0,0,505,506,5,92,0,0,506,507,5,105,0,0,507,508,5,110,
+        0,0,508,521,5,116,0,0,509,510,5,92,0,0,510,511,5,105,0,0,511,512,
+        5,110,0,0,512,513,5,116,0,0,513,514,5,92,0,0,514,515,5,108,0,0,515,
+        516,5,105,0,0,516,517,5,109,0,0,517,518,5,105,0,0,518,519,5,116,
+        0,0,519,521,5,115,0,0,520,505,1,0,0,0,520,509,1,0,0,0,521,68,1,0,
+        0,0,522,523,5,92,0,0,523,524,5,115,0,0,524,525,5,117,0,0,525,526,
+        5,109,0,0,526,70,1,0,0,0,527,528,5,92,0,0,528,529,5,112,0,0,529,
+        530,5,114,0,0,530,531,5,111,0,0,531,532,5,100,0,0,532,72,1,0,0,0,
+        533,534,5,92,0,0,534,535,5,101,0,0,535,536,5,120,0,0,536,537,5,112,
+        0,0,537,74,1,0,0,0,538,539,5,92,0,0,539,540,5,108,0,0,540,541,5,
+        111,0,0,541,542,5,103,0,0,542,76,1,0,0,0,543,544,5,92,0,0,544,545,
+        5,108,0,0,545,546,5,103,0,0,546,78,1,0,0,0,547,548,5,92,0,0,548,
+        549,5,108,0,0,549,550,5,110,0,0,550,80,1,0,0,0,551,552,5,92,0,0,
+        552,553,5,115,0,0,553,554,5,105,0,0,554,555,5,110,0,0,555,82,1,0,
+        0,0,556,557,5,92,0,0,557,558,5,99,0,0,558,559,5,111,0,0,559,560,
+        5,115,0,0,560,84,1,0,0,0,561,562,5,92,0,0,562,563,5,116,0,0,563,
+        564,5,97,0,0,564,565,5,110,0,0,565,86,1,0,0,0,566,567,5,92,0,0,567,
+        568,5,99,0,0,568,569,5,115,0,0,569,570,5,99,0,0,570,88,1,0,0,0,571,
+        572,5,92,0,0,572,573,5,115,0,0,573,574,5,101,0,0,574,575,5,99,0,
+        0,575,90,1,0,0,0,576,577,5,92,0,0,577,578,5,99,0,0,578,579,5,111,
+        0,0,579,580,5,116,0,0,580,92,1,0,0,0,581,582,5,92,0,0,582,583,5,
+        97,0,0,583,584,5,114,0,0,584,585,5,99,0,0,585,586,5,115,0,0,586,
+        587,5,105,0,0,587,588,5,110,0,0,588,94,1,0,0,0,589,590,5,92,0,0,
+        590,591,5,97,0,0,591,592,5,114,0,0,592,593,5,99,0,0,593,594,5,99,
+        0,0,594,595,5,111,0,0,595,596,5,115,0,0,596,96,1,0,0,0,597,598,5,
+        92,0,0,598,599,5,97,0,0,599,600,5,114,0,0,600,601,5,99,0,0,601,602,
+        5,116,0,0,602,603,5,97,0,0,603,604,5,110,0,0,604,98,1,0,0,0,605,
+        606,5,92,0,0,606,607,5,97,0,0,607,608,5,114,0,0,608,609,5,99,0,0,
+        609,610,5,99,0,0,610,611,5,115,0,0,611,612,5,99,0,0,612,100,1,0,
+        0,0,613,614,5,92,0,0,614,615,5,97,0,0,615,616,5,114,0,0,616,617,
+        5,99,0,0,617,618,5,115,0,0,618,619,5,101,0,0,619,620,5,99,0,0,620,
+        102,1,0,0,0,621,622,5,92,0,0,622,623,5,97,0,0,623,624,5,114,0,0,
+        624,625,5,99,0,0,625,626,5,99,0,0,626,627,5,111,0,0,627,628,5,116,
+        0,0,628,104,1,0,0,0,629,630,5,92,0,0,630,631,5,115,0,0,631,632,5,
+        105,0,0,632,633,5,110,0,0,633,634,5,104,0,0,634,106,1,0,0,0,635,
+        636,5,92,0,0,636,637,5,99,0,0,637,638,5,111,0,0,638,639,5,115,0,
+        0,639,640,5,104,0,0,640,108,1,0,0,0,641,642,5,92,0,0,642,643,5,116,
+        0,0,643,644,5,97,0,0,644,645,5,110,0,0,645,646,5,104,0,0,646,110,
+        1,0,0,0,647,648,5,92,0,0,648,649,5,97,0,0,649,650,5,114,0,0,650,
+        651,5,115,0,0,651,652,5,105,0,0,652,653,5,110,0,0,653,654,5,104,
+        0,0,654,112,1,0,0,0,655,656,5,92,0,0,656,657,5,97,0,0,657,658,5,
+        114,0,0,658,659,5,99,0,0,659,660,5,111,0,0,660,661,5,115,0,0,661,
+        662,5,104,0,0,662,114,1,0,0,0,663,664,5,92,0,0,664,665,5,97,0,0,
+        665,666,5,114,0,0,666,667,5,116,0,0,667,668,5,97,0,0,668,669,5,110,
+        0,0,669,670,5,104,0,0,670,116,1,0,0,0,671,672,5,92,0,0,672,673,5,
+        108,0,0,673,674,5,102,0,0,674,675,5,108,0,0,675,676,5,111,0,0,676,
+        677,5,111,0,0,677,678,5,114,0,0,678,118,1,0,0,0,679,680,5,92,0,0,
+        680,681,5,114,0,0,681,682,5,102,0,0,682,683,5,108,0,0,683,684,5,
+        111,0,0,684,685,5,111,0,0,685,686,5,114,0,0,686,120,1,0,0,0,687,
+        688,5,92,0,0,688,689,5,108,0,0,689,690,5,99,0,0,690,691,5,101,0,
+        0,691,692,5,105,0,0,692,693,5,108,0,0,693,122,1,0,0,0,694,695,5,
+        92,0,0,695,696,5,114,0,0,696,697,5,99,0,0,697,698,5,101,0,0,698,
+        699,5,105,0,0,699,700,5,108,0,0,700,124,1,0,0,0,701,702,5,92,0,0,
+        702,703,5,115,0,0,703,704,5,113,0,0,704,705,5,114,0,0,705,706,5,
+        116,0,0,706,126,1,0,0,0,707,708,5,92,0,0,708,709,5,111,0,0,709,710,
+        5,118,0,0,710,711,5,101,0,0,711,712,5,114,0,0,712,713,5,108,0,0,
+        713,714,5,105,0,0,714,715,5,110,0,0,715,716,5,101,0,0,716,128,1,
+        0,0,0,717,718,5,92,0,0,718,719,5,116,0,0,719,720,5,105,0,0,720,721,
+        5,109,0,0,721,722,5,101,0,0,722,723,5,115,0,0,723,130,1,0,0,0,724,
+        725,5,92,0,0,725,726,5,99,0,0,726,727,5,100,0,0,727,728,5,111,0,
+        0,728,729,5,116,0,0,729,132,1,0,0,0,730,731,5,92,0,0,731,732,5,100,
+        0,0,732,733,5,105,0,0,733,734,5,118,0,0,734,134,1,0,0,0,735,736,
+        5,92,0,0,736,737,5,102,0,0,737,738,5,114,0,0,738,739,5,97,0,0,739,
+        753,5,99,0,0,740,741,5,92,0,0,741,742,5,100,0,0,742,743,5,102,0,
+        0,743,744,5,114,0,0,744,745,5,97,0,0,745,753,5,99,0,0,746,747,5,
+        92,0,0,747,748,5,116,0,0,748,749,5,102,0,0,749,750,5,114,0,0,750,
+        751,5,97,0,0,751,753,5,99,0,0,752,735,1,0,0,0,752,740,1,0,0,0,752,
+        746,1,0,0,0,753,136,1,0,0,0,754,755,5,92,0,0,755,756,5,98,0,0,756,
+        757,5,105,0,0,757,758,5,110,0,0,758,759,5,111,0,0,759,760,5,109,
+        0,0,760,138,1,0,0,0,761,762,5,92,0,0,762,763,5,100,0,0,763,764,5,
+        98,0,0,764,765,5,105,0,0,765,766,5,110,0,0,766,767,5,111,0,0,767,
+        768,5,109,0,0,768,140,1,0,0,0,769,770,5,92,0,0,770,771,5,116,0,0,
+        771,772,5,98,0,0,772,773,5,105,0,0,773,774,5,110,0,0,774,775,5,111,
+        0,0,775,776,5,109,0,0,776,142,1,0,0,0,777,778,5,92,0,0,778,779,5,
+        109,0,0,779,780,5,97,0,0,780,781,5,116,0,0,781,782,5,104,0,0,782,
+        783,5,105,0,0,783,784,5,116,0,0,784,144,1,0,0,0,785,786,5,95,0,0,
+        786,146,1,0,0,0,787,788,5,94,0,0,788,148,1,0,0,0,789,790,5,58,0,
+        0,790,150,1,0,0,0,791,792,7,0,0,0,792,152,1,0,0,0,793,797,5,100,
+        0,0,794,796,3,151,75,0,795,794,1,0,0,0,796,799,1,0,0,0,797,798,1,
+        0,0,0,797,795,1,0,0,0,798,807,1,0,0,0,799,797,1,0,0,0,800,808,7,
+        1,0,0,801,803,5,92,0,0,802,804,7,1,0,0,803,802,1,0,0,0,804,805,1,
+        0,0,0,805,803,1,0,0,0,805,806,1,0,0,0,806,808,1,0,0,0,807,800,1,
+        0,0,0,807,801,1,0,0,0,808,154,1,0,0,0,809,810,7,1,0,0,810,156,1,
+        0,0,0,811,812,7,2,0,0,812,158,1,0,0,0,813,817,5,38,0,0,814,816,3,
+        151,75,0,815,814,1,0,0,0,816,819,1,0,0,0,817,818,1,0,0,0,817,815,
+        1,0,0,0,818,821,1,0,0,0,819,817,1,0,0,0,820,813,1,0,0,0,820,821,
+        1,0,0,0,821,822,1,0,0,0,822,834,5,61,0,0,823,831,5,61,0,0,824,826,
+        3,151,75,0,825,824,1,0,0,0,826,829,1,0,0,0,827,828,1,0,0,0,827,825,
+        1,0,0,0,828,830,1,0,0,0,829,827,1,0,0,0,830,832,5,38,0,0,831,827,
+        1,0,0,0,831,832,1,0,0,0,832,834,1,0,0,0,833,820,1,0,0,0,833,823,
+        1,0,0,0,834,160,1,0,0,0,835,836,5,92,0,0,836,837,5,110,0,0,837,838,
+        5,101,0,0,838,839,5,113,0,0,839,162,1,0,0,0,840,841,5,60,0,0,841,
+        164,1,0,0,0,842,843,5,92,0,0,843,844,5,108,0,0,844,845,5,101,0,0,
+        845,852,5,113,0,0,846,847,5,92,0,0,847,848,5,108,0,0,848,852,5,101,
+        0,0,849,852,3,167,83,0,850,852,3,169,84,0,851,842,1,0,0,0,851,846,
+        1,0,0,0,851,849,1,0,0,0,851,850,1,0,0,0,852,166,1,0,0,0,853,854,
+        5,92,0,0,854,855,5,108,0,0,855,856,5,101,0,0,856,857,5,113,0,0,857,
+        858,5,113,0,0,858,168,1,0,0,0,859,860,5,92,0,0,860,861,5,108,0,0,
+        861,862,5,101,0,0,862,863,5,113,0,0,863,864,5,115,0,0,864,865,5,
+        108,0,0,865,866,5,97,0,0,866,867,5,110,0,0,867,868,5,116,0,0,868,
+        170,1,0,0,0,869,870,5,62,0,0,870,172,1,0,0,0,871,872,5,92,0,0,872,
+        873,5,103,0,0,873,874,5,101,0,0,874,881,5,113,0,0,875,876,5,92,0,
+        0,876,877,5,103,0,0,877,881,5,101,0,0,878,881,3,175,87,0,879,881,
+        3,177,88,0,880,871,1,0,0,0,880,875,1,0,0,0,880,878,1,0,0,0,880,879,
+        1,0,0,0,881,174,1,0,0,0,882,883,5,92,0,0,883,884,5,103,0,0,884,885,
+        5,101,0,0,885,886,5,113,0,0,886,887,5,113,0,0,887,176,1,0,0,0,888,
+        889,5,92,0,0,889,890,5,103,0,0,890,891,5,101,0,0,891,892,5,113,0,
+        0,892,893,5,115,0,0,893,894,5,108,0,0,894,895,5,97,0,0,895,896,5,
+        110,0,0,896,897,5,116,0,0,897,178,1,0,0,0,898,899,5,33,0,0,899,180,
+        1,0,0,0,900,902,5,39,0,0,901,900,1,0,0,0,902,903,1,0,0,0,903,901,
+        1,0,0,0,903,904,1,0,0,0,904,182,1,0,0,0,905,907,5,92,0,0,906,908,
+        7,1,0,0,907,906,1,0,0,0,908,909,1,0,0,0,909,907,1,0,0,0,909,910,
+        1,0,0,0,910,184,1,0,0,0,22,0,192,208,223,240,276,380,503,520,752,
+        797,805,807,817,820,827,831,833,851,880,903,909,1,6,0,0
+    ]
+
+class LaTeXLexer(Lexer):
+
+    atn = ATNDeserializer().deserialize(serializedATN())
+
+    decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
+
+    T__0 = 1
+    T__1 = 2
+    WS = 3
+    THINSPACE = 4
+    MEDSPACE = 5
+    THICKSPACE = 6
+    QUAD = 7
+    QQUAD = 8
+    NEGTHINSPACE = 9
+    NEGMEDSPACE = 10
+    NEGTHICKSPACE = 11
+    CMD_LEFT = 12
+    CMD_RIGHT = 13
+    IGNORE = 14
+    ADD = 15
+    SUB = 16
+    MUL = 17
+    DIV = 18
+    L_PAREN = 19
+    R_PAREN = 20
+    L_BRACE = 21
+    R_BRACE = 22
+    L_BRACE_LITERAL = 23
+    R_BRACE_LITERAL = 24
+    L_BRACKET = 25
+    R_BRACKET = 26
+    BAR = 27
+    R_BAR = 28
+    L_BAR = 29
+    L_ANGLE = 30
+    R_ANGLE = 31
+    FUNC_LIM = 32
+    LIM_APPROACH_SYM = 33
+    FUNC_INT = 34
+    FUNC_SUM = 35
+    FUNC_PROD = 36
+    FUNC_EXP = 37
+    FUNC_LOG = 38
+    FUNC_LG = 39
+    FUNC_LN = 40
+    FUNC_SIN = 41
+    FUNC_COS = 42
+    FUNC_TAN = 43
+    FUNC_CSC = 44
+    FUNC_SEC = 45
+    FUNC_COT = 46
+    FUNC_ARCSIN = 47
+    FUNC_ARCCOS = 48
+    FUNC_ARCTAN = 49
+    FUNC_ARCCSC = 50
+    FUNC_ARCSEC = 51
+    FUNC_ARCCOT = 52
+    FUNC_SINH = 53
+    FUNC_COSH = 54
+    FUNC_TANH = 55
+    FUNC_ARSINH = 56
+    FUNC_ARCOSH = 57
+    FUNC_ARTANH = 58
+    L_FLOOR = 59
+    R_FLOOR = 60
+    L_CEIL = 61
+    R_CEIL = 62
+    FUNC_SQRT = 63
+    FUNC_OVERLINE = 64
+    CMD_TIMES = 65
+    CMD_CDOT = 66
+    CMD_DIV = 67
+    CMD_FRAC = 68
+    CMD_BINOM = 69
+    CMD_DBINOM = 70
+    CMD_TBINOM = 71
+    CMD_MATHIT = 72
+    UNDERSCORE = 73
+    CARET = 74
+    COLON = 75
+    DIFFERENTIAL = 76
+    LETTER = 77
+    DIGIT = 78
+    EQUAL = 79
+    NEQ = 80
+    LT = 81
+    LTE = 82
+    LTE_Q = 83
+    LTE_S = 84
+    GT = 85
+    GTE = 86
+    GTE_Q = 87
+    GTE_S = 88
+    BANG = 89
+    SINGLE_QUOTES = 90
+    SYMBOL = 91
+
+    channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ]
+
+    modeNames = [ "DEFAULT_MODE" ]
+
+    literalNames = [ "",
+            "','", "'.'", "'\\quad'", "'\\qquad'", "'\\negmedspace'", "'\\negthickspace'",
+            "'\\left'", "'\\right'", "'+'", "'-'", "'*'", "'/'", "'('",
+            "')'", "'{'", "'}'", "'\\{'", "'\\}'", "'['", "']'", "'|'",
+            "'\\right|'", "'\\left|'", "'\\langle'", "'\\rangle'", "'\\lim'",
+            "'\\sum'", "'\\prod'", "'\\exp'", "'\\log'", "'\\lg'", "'\\ln'",
+            "'\\sin'", "'\\cos'", "'\\tan'", "'\\csc'", "'\\sec'", "'\\cot'",
+            "'\\arcsin'", "'\\arccos'", "'\\arctan'", "'\\arccsc'", "'\\arcsec'",
+            "'\\arccot'", "'\\sinh'", "'\\cosh'", "'\\tanh'", "'\\arsinh'",
+            "'\\arcosh'", "'\\artanh'", "'\\lfloor'", "'\\rfloor'", "'\\lceil'",
+            "'\\rceil'", "'\\sqrt'", "'\\overline'", "'\\times'", "'\\cdot'",
+            "'\\div'", "'\\binom'", "'\\dbinom'", "'\\tbinom'", "'\\mathit'",
+            "'_'", "'^'", "':'", "'\\neq'", "'<'", "'\\leqq'", "'\\leqslant'",
+            "'>'", "'\\geqq'", "'\\geqslant'", "'!'" ]
+
+    symbolicNames = [ "",
+            "WS", "THINSPACE", "MEDSPACE", "THICKSPACE", "QUAD", "QQUAD",
+            "NEGTHINSPACE", "NEGMEDSPACE", "NEGTHICKSPACE", "CMD_LEFT",
+            "CMD_RIGHT", "IGNORE", "ADD", "SUB", "MUL", "DIV", "L_PAREN",
+            "R_PAREN", "L_BRACE", "R_BRACE", "L_BRACE_LITERAL", "R_BRACE_LITERAL",
+            "L_BRACKET", "R_BRACKET", "BAR", "R_BAR", "L_BAR", "L_ANGLE",
+            "R_ANGLE", "FUNC_LIM", "LIM_APPROACH_SYM", "FUNC_INT", "FUNC_SUM",
+            "FUNC_PROD", "FUNC_EXP", "FUNC_LOG", "FUNC_LG", "FUNC_LN", "FUNC_SIN",
+            "FUNC_COS", "FUNC_TAN", "FUNC_CSC", "FUNC_SEC", "FUNC_COT",
+            "FUNC_ARCSIN", "FUNC_ARCCOS", "FUNC_ARCTAN", "FUNC_ARCCSC",
+            "FUNC_ARCSEC", "FUNC_ARCCOT", "FUNC_SINH", "FUNC_COSH", "FUNC_TANH",
+            "FUNC_ARSINH", "FUNC_ARCOSH", "FUNC_ARTANH", "L_FLOOR", "R_FLOOR",
+            "L_CEIL", "R_CEIL", "FUNC_SQRT", "FUNC_OVERLINE", "CMD_TIMES",
+            "CMD_CDOT", "CMD_DIV", "CMD_FRAC", "CMD_BINOM", "CMD_DBINOM",
+            "CMD_TBINOM", "CMD_MATHIT", "UNDERSCORE", "CARET", "COLON",
+            "DIFFERENTIAL", "LETTER", "DIGIT", "EQUAL", "NEQ", "LT", "LTE",
+            "LTE_Q", "LTE_S", "GT", "GTE", "GTE_Q", "GTE_S", "BANG", "SINGLE_QUOTES",
+            "SYMBOL" ]
+
+    ruleNames = [ "T__0", "T__1", "WS", "THINSPACE", "MEDSPACE", "THICKSPACE",
+                  "QUAD", "QQUAD", "NEGTHINSPACE", "NEGMEDSPACE", "NEGTHICKSPACE",
+                  "CMD_LEFT", "CMD_RIGHT", "IGNORE", "ADD", "SUB", "MUL",
+                  "DIV", "L_PAREN", "R_PAREN", "L_BRACE", "R_BRACE", "L_BRACE_LITERAL",
+                  "R_BRACE_LITERAL", "L_BRACKET", "R_BRACKET", "BAR", "R_BAR",
+                  "L_BAR", "L_ANGLE", "R_ANGLE", "FUNC_LIM", "LIM_APPROACH_SYM",
+                  "FUNC_INT", "FUNC_SUM", "FUNC_PROD", "FUNC_EXP", "FUNC_LOG",
+                  "FUNC_LG", "FUNC_LN", "FUNC_SIN", "FUNC_COS", "FUNC_TAN",
+                  "FUNC_CSC", "FUNC_SEC", "FUNC_COT", "FUNC_ARCSIN", "FUNC_ARCCOS",
+                  "FUNC_ARCTAN", "FUNC_ARCCSC", "FUNC_ARCSEC", "FUNC_ARCCOT",
+                  "FUNC_SINH", "FUNC_COSH", "FUNC_TANH", "FUNC_ARSINH",
+                  "FUNC_ARCOSH", "FUNC_ARTANH", "L_FLOOR", "R_FLOOR", "L_CEIL",
+                  "R_CEIL", "FUNC_SQRT", "FUNC_OVERLINE", "CMD_TIMES", "CMD_CDOT",
+                  "CMD_DIV", "CMD_FRAC", "CMD_BINOM", "CMD_DBINOM", "CMD_TBINOM",
+                  "CMD_MATHIT", "UNDERSCORE", "CARET", "COLON", "WS_CHAR",
+                  "DIFFERENTIAL", "LETTER", "DIGIT", "EQUAL", "NEQ", "LT",
+                  "LTE", "LTE_Q", "LTE_S", "GT", "GTE", "GTE_Q", "GTE_S",
+                  "BANG", "SINGLE_QUOTES", "SYMBOL" ]
+
+    grammarFileName = "LaTeX.g4"
+
+    def __init__(self, input=None, output:TextIO = sys.stdout):
+        super().__init__(input, output)
+        self.checkVersion("4.11.1")
+        self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
+        self._actions = None
+        self._predicates = None
+
+
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/latexparser.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/latexparser.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6f58119055ded8f77380bbef52c77ddd6a01cfe
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/latexparser.py
@@ -0,0 +1,3652 @@
+# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
+#
+# Generated from ../LaTeX.g4, derived from latex2sympy
+#     latex2sympy is licensed under the MIT license
+#     https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt
+#
+# Generated with antlr4
+#    antlr4 is licensed under the BSD-3-Clause License
+#    https://github.com/antlr/antlr4/blob/master/LICENSE.txt
+from antlr4 import *
+from io import StringIO
+import sys
+if sys.version_info[1] > 5:
+	from typing import TextIO
+else:
+	from typing.io import TextIO
+
+def serializedATN():
+    return [
+        4,1,91,522,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,6,7,
+        6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2,13,7,13,
+        2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7,19,2,20,
+        7,20,2,21,7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7,25,2,26,7,26,
+        2,27,7,27,2,28,7,28,2,29,7,29,2,30,7,30,2,31,7,31,2,32,7,32,2,33,
+        7,33,2,34,7,34,2,35,7,35,2,36,7,36,2,37,7,37,2,38,7,38,2,39,7,39,
+        2,40,7,40,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,5,1,91,8,1,10,1,12,1,94,
+        9,1,1,2,1,2,1,2,1,2,1,3,1,3,1,4,1,4,1,4,1,4,1,4,1,4,5,4,108,8,4,
+        10,4,12,4,111,9,4,1,5,1,5,1,5,1,5,1,5,1,5,5,5,119,8,5,10,5,12,5,
+        122,9,5,1,6,1,6,1,6,1,6,1,6,1,6,5,6,130,8,6,10,6,12,6,133,9,6,1,
+        7,1,7,1,7,4,7,138,8,7,11,7,12,7,139,3,7,142,8,7,1,8,1,8,1,8,1,8,
+        5,8,148,8,8,10,8,12,8,151,9,8,3,8,153,8,8,1,9,1,9,5,9,157,8,9,10,
+        9,12,9,160,9,9,1,10,1,10,5,10,164,8,10,10,10,12,10,167,9,10,1,11,
+        1,11,3,11,171,8,11,1,12,1,12,1,12,1,12,1,12,1,12,3,12,179,8,12,1,
+        13,1,13,1,13,1,13,3,13,185,8,13,1,13,1,13,1,14,1,14,1,14,1,14,3,
+        14,193,8,14,1,14,1,14,1,15,1,15,1,15,1,15,1,15,1,15,1,15,1,15,1,
+        15,1,15,3,15,207,8,15,1,15,3,15,210,8,15,5,15,212,8,15,10,15,12,
+        15,215,9,15,1,16,1,16,1,16,1,16,1,16,1,16,1,16,1,16,1,16,1,16,3,
+        16,227,8,16,1,16,3,16,230,8,16,5,16,232,8,16,10,16,12,16,235,9,16,
+        1,17,1,17,1,17,1,17,1,17,1,17,3,17,243,8,17,1,18,1,18,1,18,1,18,
+        1,18,3,18,250,8,18,1,19,1,19,1,19,1,19,1,19,1,19,1,19,1,19,1,19,
+        1,19,1,19,1,19,1,19,1,19,1,19,1,19,3,19,268,8,19,1,20,1,20,1,20,
+        1,20,1,21,4,21,275,8,21,11,21,12,21,276,1,21,1,21,1,21,1,21,5,21,
+        283,8,21,10,21,12,21,286,9,21,1,21,1,21,4,21,290,8,21,11,21,12,21,
+        291,3,21,294,8,21,1,22,1,22,3,22,298,8,22,1,22,3,22,301,8,22,1,22,
+        3,22,304,8,22,1,22,3,22,307,8,22,3,22,309,8,22,1,22,1,22,1,22,1,
+        22,1,22,1,22,1,22,3,22,318,8,22,1,23,1,23,1,23,1,23,1,24,1,24,1,
+        24,1,24,1,25,1,25,1,25,1,25,1,25,1,26,5,26,334,8,26,10,26,12,26,
+        337,9,26,1,27,1,27,1,27,1,27,1,27,1,27,3,27,345,8,27,1,27,1,27,1,
+        27,1,27,1,27,3,27,352,8,27,1,28,1,28,1,28,1,28,1,28,1,28,1,28,1,
+        28,1,29,1,29,1,29,1,29,1,30,1,30,1,30,1,30,1,31,1,31,1,32,1,32,3,
+        32,374,8,32,1,32,3,32,377,8,32,1,32,3,32,380,8,32,1,32,3,32,383,
+        8,32,3,32,385,8,32,1,32,1,32,1,32,1,32,1,32,3,32,392,8,32,1,32,1,
+        32,3,32,396,8,32,1,32,3,32,399,8,32,1,32,3,32,402,8,32,1,32,3,32,
+        405,8,32,3,32,407,8,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,
+        32,1,32,1,32,3,32,420,8,32,1,32,3,32,423,8,32,1,32,1,32,1,32,3,32,
+        428,8,32,1,32,1,32,1,32,1,32,1,32,3,32,435,8,32,1,32,1,32,1,32,1,
+        32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,3,
+        32,453,8,32,1,32,1,32,1,32,1,32,1,32,1,32,3,32,461,8,32,1,33,1,33,
+        1,33,1,33,1,33,3,33,468,8,33,1,34,1,34,1,34,1,34,1,34,1,34,1,34,
+        1,34,1,34,1,34,1,34,3,34,481,8,34,3,34,483,8,34,1,34,1,34,1,35,1,
+        35,1,35,1,35,1,35,3,35,492,8,35,1,36,1,36,1,37,1,37,1,37,1,37,1,
+        37,1,37,3,37,502,8,37,1,38,1,38,1,38,1,38,1,38,1,38,3,38,510,8,38,
+        1,39,1,39,1,39,1,39,1,39,1,40,1,40,1,40,1,40,1,40,1,40,0,6,2,8,10,
+        12,30,32,41,0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,
+        38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,
+        0,9,2,0,79,82,85,86,1,0,15,16,3,0,17,18,65,67,75,75,2,0,77,77,91,
+        91,1,0,27,28,2,0,27,27,29,29,1,0,69,71,1,0,37,58,1,0,35,36,563,0,
+        82,1,0,0,0,2,84,1,0,0,0,4,95,1,0,0,0,6,99,1,0,0,0,8,101,1,0,0,0,
+        10,112,1,0,0,0,12,123,1,0,0,0,14,141,1,0,0,0,16,152,1,0,0,0,18,154,
+        1,0,0,0,20,161,1,0,0,0,22,170,1,0,0,0,24,172,1,0,0,0,26,180,1,0,
+        0,0,28,188,1,0,0,0,30,196,1,0,0,0,32,216,1,0,0,0,34,242,1,0,0,0,
+        36,249,1,0,0,0,38,267,1,0,0,0,40,269,1,0,0,0,42,274,1,0,0,0,44,317,
+        1,0,0,0,46,319,1,0,0,0,48,323,1,0,0,0,50,327,1,0,0,0,52,335,1,0,
+        0,0,54,338,1,0,0,0,56,353,1,0,0,0,58,361,1,0,0,0,60,365,1,0,0,0,
+        62,369,1,0,0,0,64,460,1,0,0,0,66,467,1,0,0,0,68,469,1,0,0,0,70,491,
+        1,0,0,0,72,493,1,0,0,0,74,495,1,0,0,0,76,503,1,0,0,0,78,511,1,0,
+        0,0,80,516,1,0,0,0,82,83,3,2,1,0,83,1,1,0,0,0,84,85,6,1,-1,0,85,
+        86,3,6,3,0,86,92,1,0,0,0,87,88,10,2,0,0,88,89,7,0,0,0,89,91,3,2,
+        1,3,90,87,1,0,0,0,91,94,1,0,0,0,92,90,1,0,0,0,92,93,1,0,0,0,93,3,
+        1,0,0,0,94,92,1,0,0,0,95,96,3,6,3,0,96,97,5,79,0,0,97,98,3,6,3,0,
+        98,5,1,0,0,0,99,100,3,8,4,0,100,7,1,0,0,0,101,102,6,4,-1,0,102,103,
+        3,10,5,0,103,109,1,0,0,0,104,105,10,2,0,0,105,106,7,1,0,0,106,108,
+        3,8,4,3,107,104,1,0,0,0,108,111,1,0,0,0,109,107,1,0,0,0,109,110,
+        1,0,0,0,110,9,1,0,0,0,111,109,1,0,0,0,112,113,6,5,-1,0,113,114,3,
+        14,7,0,114,120,1,0,0,0,115,116,10,2,0,0,116,117,7,2,0,0,117,119,
+        3,10,5,3,118,115,1,0,0,0,119,122,1,0,0,0,120,118,1,0,0,0,120,121,
+        1,0,0,0,121,11,1,0,0,0,122,120,1,0,0,0,123,124,6,6,-1,0,124,125,
+        3,16,8,0,125,131,1,0,0,0,126,127,10,2,0,0,127,128,7,2,0,0,128,130,
+        3,12,6,3,129,126,1,0,0,0,130,133,1,0,0,0,131,129,1,0,0,0,131,132,
+        1,0,0,0,132,13,1,0,0,0,133,131,1,0,0,0,134,135,7,1,0,0,135,142,3,
+        14,7,0,136,138,3,18,9,0,137,136,1,0,0,0,138,139,1,0,0,0,139,137,
+        1,0,0,0,139,140,1,0,0,0,140,142,1,0,0,0,141,134,1,0,0,0,141,137,
+        1,0,0,0,142,15,1,0,0,0,143,144,7,1,0,0,144,153,3,16,8,0,145,149,
+        3,18,9,0,146,148,3,20,10,0,147,146,1,0,0,0,148,151,1,0,0,0,149,147,
+        1,0,0,0,149,150,1,0,0,0,150,153,1,0,0,0,151,149,1,0,0,0,152,143,
+        1,0,0,0,152,145,1,0,0,0,153,17,1,0,0,0,154,158,3,30,15,0,155,157,
+        3,22,11,0,156,155,1,0,0,0,157,160,1,0,0,0,158,156,1,0,0,0,158,159,
+        1,0,0,0,159,19,1,0,0,0,160,158,1,0,0,0,161,165,3,32,16,0,162,164,
+        3,22,11,0,163,162,1,0,0,0,164,167,1,0,0,0,165,163,1,0,0,0,165,166,
+        1,0,0,0,166,21,1,0,0,0,167,165,1,0,0,0,168,171,5,89,0,0,169,171,
+        3,24,12,0,170,168,1,0,0,0,170,169,1,0,0,0,171,23,1,0,0,0,172,178,
+        5,27,0,0,173,179,3,28,14,0,174,179,3,26,13,0,175,176,3,28,14,0,176,
+        177,3,26,13,0,177,179,1,0,0,0,178,173,1,0,0,0,178,174,1,0,0,0,178,
+        175,1,0,0,0,179,25,1,0,0,0,180,181,5,73,0,0,181,184,5,21,0,0,182,
+        185,3,6,3,0,183,185,3,4,2,0,184,182,1,0,0,0,184,183,1,0,0,0,185,
+        186,1,0,0,0,186,187,5,22,0,0,187,27,1,0,0,0,188,189,5,74,0,0,189,
+        192,5,21,0,0,190,193,3,6,3,0,191,193,3,4,2,0,192,190,1,0,0,0,192,
+        191,1,0,0,0,193,194,1,0,0,0,194,195,5,22,0,0,195,29,1,0,0,0,196,
+        197,6,15,-1,0,197,198,3,34,17,0,198,213,1,0,0,0,199,200,10,2,0,0,
+        200,206,5,74,0,0,201,207,3,44,22,0,202,203,5,21,0,0,203,204,3,6,
+        3,0,204,205,5,22,0,0,205,207,1,0,0,0,206,201,1,0,0,0,206,202,1,0,
+        0,0,207,209,1,0,0,0,208,210,3,74,37,0,209,208,1,0,0,0,209,210,1,
+        0,0,0,210,212,1,0,0,0,211,199,1,0,0,0,212,215,1,0,0,0,213,211,1,
+        0,0,0,213,214,1,0,0,0,214,31,1,0,0,0,215,213,1,0,0,0,216,217,6,16,
+        -1,0,217,218,3,36,18,0,218,233,1,0,0,0,219,220,10,2,0,0,220,226,
+        5,74,0,0,221,227,3,44,22,0,222,223,5,21,0,0,223,224,3,6,3,0,224,
+        225,5,22,0,0,225,227,1,0,0,0,226,221,1,0,0,0,226,222,1,0,0,0,227,
+        229,1,0,0,0,228,230,3,74,37,0,229,228,1,0,0,0,229,230,1,0,0,0,230,
+        232,1,0,0,0,231,219,1,0,0,0,232,235,1,0,0,0,233,231,1,0,0,0,233,
+        234,1,0,0,0,234,33,1,0,0,0,235,233,1,0,0,0,236,243,3,38,19,0,237,
+        243,3,40,20,0,238,243,3,64,32,0,239,243,3,44,22,0,240,243,3,58,29,
+        0,241,243,3,60,30,0,242,236,1,0,0,0,242,237,1,0,0,0,242,238,1,0,
+        0,0,242,239,1,0,0,0,242,240,1,0,0,0,242,241,1,0,0,0,243,35,1,0,0,
+        0,244,250,3,38,19,0,245,250,3,40,20,0,246,250,3,44,22,0,247,250,
+        3,58,29,0,248,250,3,60,30,0,249,244,1,0,0,0,249,245,1,0,0,0,249,
+        246,1,0,0,0,249,247,1,0,0,0,249,248,1,0,0,0,250,37,1,0,0,0,251,252,
+        5,19,0,0,252,253,3,6,3,0,253,254,5,20,0,0,254,268,1,0,0,0,255,256,
+        5,25,0,0,256,257,3,6,3,0,257,258,5,26,0,0,258,268,1,0,0,0,259,260,
+        5,21,0,0,260,261,3,6,3,0,261,262,5,22,0,0,262,268,1,0,0,0,263,264,
+        5,23,0,0,264,265,3,6,3,0,265,266,5,24,0,0,266,268,1,0,0,0,267,251,
+        1,0,0,0,267,255,1,0,0,0,267,259,1,0,0,0,267,263,1,0,0,0,268,39,1,
+        0,0,0,269,270,5,27,0,0,270,271,3,6,3,0,271,272,5,27,0,0,272,41,1,
+        0,0,0,273,275,5,78,0,0,274,273,1,0,0,0,275,276,1,0,0,0,276,274,1,
+        0,0,0,276,277,1,0,0,0,277,284,1,0,0,0,278,279,5,1,0,0,279,280,5,
+        78,0,0,280,281,5,78,0,0,281,283,5,78,0,0,282,278,1,0,0,0,283,286,
+        1,0,0,0,284,282,1,0,0,0,284,285,1,0,0,0,285,293,1,0,0,0,286,284,
+        1,0,0,0,287,289,5,2,0,0,288,290,5,78,0,0,289,288,1,0,0,0,290,291,
+        1,0,0,0,291,289,1,0,0,0,291,292,1,0,0,0,292,294,1,0,0,0,293,287,
+        1,0,0,0,293,294,1,0,0,0,294,43,1,0,0,0,295,308,7,3,0,0,296,298,3,
+        74,37,0,297,296,1,0,0,0,297,298,1,0,0,0,298,300,1,0,0,0,299,301,
+        5,90,0,0,300,299,1,0,0,0,300,301,1,0,0,0,301,309,1,0,0,0,302,304,
+        5,90,0,0,303,302,1,0,0,0,303,304,1,0,0,0,304,306,1,0,0,0,305,307,
+        3,74,37,0,306,305,1,0,0,0,306,307,1,0,0,0,307,309,1,0,0,0,308,297,
+        1,0,0,0,308,303,1,0,0,0,309,318,1,0,0,0,310,318,3,42,21,0,311,318,
+        5,76,0,0,312,318,3,50,25,0,313,318,3,54,27,0,314,318,3,56,28,0,315,
+        318,3,46,23,0,316,318,3,48,24,0,317,295,1,0,0,0,317,310,1,0,0,0,
+        317,311,1,0,0,0,317,312,1,0,0,0,317,313,1,0,0,0,317,314,1,0,0,0,
+        317,315,1,0,0,0,317,316,1,0,0,0,318,45,1,0,0,0,319,320,5,30,0,0,
+        320,321,3,6,3,0,321,322,7,4,0,0,322,47,1,0,0,0,323,324,7,5,0,0,324,
+        325,3,6,3,0,325,326,5,31,0,0,326,49,1,0,0,0,327,328,5,72,0,0,328,
+        329,5,21,0,0,329,330,3,52,26,0,330,331,5,22,0,0,331,51,1,0,0,0,332,
+        334,5,77,0,0,333,332,1,0,0,0,334,337,1,0,0,0,335,333,1,0,0,0,335,
+        336,1,0,0,0,336,53,1,0,0,0,337,335,1,0,0,0,338,344,5,68,0,0,339,
+        345,5,78,0,0,340,341,5,21,0,0,341,342,3,6,3,0,342,343,5,22,0,0,343,
+        345,1,0,0,0,344,339,1,0,0,0,344,340,1,0,0,0,345,351,1,0,0,0,346,
+        352,5,78,0,0,347,348,5,21,0,0,348,349,3,6,3,0,349,350,5,22,0,0,350,
+        352,1,0,0,0,351,346,1,0,0,0,351,347,1,0,0,0,352,55,1,0,0,0,353,354,
+        7,6,0,0,354,355,5,21,0,0,355,356,3,6,3,0,356,357,5,22,0,0,357,358,
+        5,21,0,0,358,359,3,6,3,0,359,360,5,22,0,0,360,57,1,0,0,0,361,362,
+        5,59,0,0,362,363,3,6,3,0,363,364,5,60,0,0,364,59,1,0,0,0,365,366,
+        5,61,0,0,366,367,3,6,3,0,367,368,5,62,0,0,368,61,1,0,0,0,369,370,
+        7,7,0,0,370,63,1,0,0,0,371,384,3,62,31,0,372,374,3,74,37,0,373,372,
+        1,0,0,0,373,374,1,0,0,0,374,376,1,0,0,0,375,377,3,76,38,0,376,375,
+        1,0,0,0,376,377,1,0,0,0,377,385,1,0,0,0,378,380,3,76,38,0,379,378,
+        1,0,0,0,379,380,1,0,0,0,380,382,1,0,0,0,381,383,3,74,37,0,382,381,
+        1,0,0,0,382,383,1,0,0,0,383,385,1,0,0,0,384,373,1,0,0,0,384,379,
+        1,0,0,0,385,391,1,0,0,0,386,387,5,19,0,0,387,388,3,70,35,0,388,389,
+        5,20,0,0,389,392,1,0,0,0,390,392,3,72,36,0,391,386,1,0,0,0,391,390,
+        1,0,0,0,392,461,1,0,0,0,393,406,7,3,0,0,394,396,3,74,37,0,395,394,
+        1,0,0,0,395,396,1,0,0,0,396,398,1,0,0,0,397,399,5,90,0,0,398,397,
+        1,0,0,0,398,399,1,0,0,0,399,407,1,0,0,0,400,402,5,90,0,0,401,400,
+        1,0,0,0,401,402,1,0,0,0,402,404,1,0,0,0,403,405,3,74,37,0,404,403,
+        1,0,0,0,404,405,1,0,0,0,405,407,1,0,0,0,406,395,1,0,0,0,406,401,
+        1,0,0,0,407,408,1,0,0,0,408,409,5,19,0,0,409,410,3,66,33,0,410,411,
+        5,20,0,0,411,461,1,0,0,0,412,419,5,34,0,0,413,414,3,74,37,0,414,
+        415,3,76,38,0,415,420,1,0,0,0,416,417,3,76,38,0,417,418,3,74,37,
+        0,418,420,1,0,0,0,419,413,1,0,0,0,419,416,1,0,0,0,419,420,1,0,0,
+        0,420,427,1,0,0,0,421,423,3,8,4,0,422,421,1,0,0,0,422,423,1,0,0,
+        0,423,424,1,0,0,0,424,428,5,76,0,0,425,428,3,54,27,0,426,428,3,8,
+        4,0,427,422,1,0,0,0,427,425,1,0,0,0,427,426,1,0,0,0,428,461,1,0,
+        0,0,429,434,5,63,0,0,430,431,5,25,0,0,431,432,3,6,3,0,432,433,5,
+        26,0,0,433,435,1,0,0,0,434,430,1,0,0,0,434,435,1,0,0,0,435,436,1,
+        0,0,0,436,437,5,21,0,0,437,438,3,6,3,0,438,439,5,22,0,0,439,461,
+        1,0,0,0,440,441,5,64,0,0,441,442,5,21,0,0,442,443,3,6,3,0,443,444,
+        5,22,0,0,444,461,1,0,0,0,445,452,7,8,0,0,446,447,3,78,39,0,447,448,
+        3,76,38,0,448,453,1,0,0,0,449,450,3,76,38,0,450,451,3,78,39,0,451,
+        453,1,0,0,0,452,446,1,0,0,0,452,449,1,0,0,0,453,454,1,0,0,0,454,
+        455,3,10,5,0,455,461,1,0,0,0,456,457,5,32,0,0,457,458,3,68,34,0,
+        458,459,3,10,5,0,459,461,1,0,0,0,460,371,1,0,0,0,460,393,1,0,0,0,
+        460,412,1,0,0,0,460,429,1,0,0,0,460,440,1,0,0,0,460,445,1,0,0,0,
+        460,456,1,0,0,0,461,65,1,0,0,0,462,463,3,6,3,0,463,464,5,1,0,0,464,
+        465,3,66,33,0,465,468,1,0,0,0,466,468,3,6,3,0,467,462,1,0,0,0,467,
+        466,1,0,0,0,468,67,1,0,0,0,469,470,5,73,0,0,470,471,5,21,0,0,471,
+        472,7,3,0,0,472,473,5,33,0,0,473,482,3,6,3,0,474,480,5,74,0,0,475,
+        476,5,21,0,0,476,477,7,1,0,0,477,481,5,22,0,0,478,481,5,15,0,0,479,
+        481,5,16,0,0,480,475,1,0,0,0,480,478,1,0,0,0,480,479,1,0,0,0,481,
+        483,1,0,0,0,482,474,1,0,0,0,482,483,1,0,0,0,483,484,1,0,0,0,484,
+        485,5,22,0,0,485,69,1,0,0,0,486,492,3,6,3,0,487,488,3,6,3,0,488,
+        489,5,1,0,0,489,490,3,70,35,0,490,492,1,0,0,0,491,486,1,0,0,0,491,
+        487,1,0,0,0,492,71,1,0,0,0,493,494,3,12,6,0,494,73,1,0,0,0,495,501,
+        5,73,0,0,496,502,3,44,22,0,497,498,5,21,0,0,498,499,3,6,3,0,499,
+        500,5,22,0,0,500,502,1,0,0,0,501,496,1,0,0,0,501,497,1,0,0,0,502,
+        75,1,0,0,0,503,509,5,74,0,0,504,510,3,44,22,0,505,506,5,21,0,0,506,
+        507,3,6,3,0,507,508,5,22,0,0,508,510,1,0,0,0,509,504,1,0,0,0,509,
+        505,1,0,0,0,510,77,1,0,0,0,511,512,5,73,0,0,512,513,5,21,0,0,513,
+        514,3,4,2,0,514,515,5,22,0,0,515,79,1,0,0,0,516,517,5,73,0,0,517,
+        518,5,21,0,0,518,519,3,4,2,0,519,520,5,22,0,0,520,81,1,0,0,0,59,
+        92,109,120,131,139,141,149,152,158,165,170,178,184,192,206,209,213,
+        226,229,233,242,249,267,276,284,291,293,297,300,303,306,308,317,
+        335,344,351,373,376,379,382,384,391,395,398,401,404,406,419,422,
+        427,434,452,460,467,480,482,491,501,509
+    ]
+
+class LaTeXParser ( Parser ):
+
+    grammarFileName = "LaTeX.g4"
+
+    atn = ATNDeserializer().deserialize(serializedATN())
+
+    decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
+
+    sharedContextCache = PredictionContextCache()
+
+    literalNames = [ "", "','", "'.'", "", "",
+                     "", "", "'\\quad'", "'\\qquad'",
+                     "", "'\\negmedspace'", "'\\negthickspace'",
+                     "'\\left'", "'\\right'", "", "'+'", "'-'",
+                     "'*'", "'/'", "'('", "')'", "'{'", "'}'", "'\\{'",
+                     "'\\}'", "'['", "']'", "'|'", "'\\right|'", "'\\left|'",
+                     "'\\langle'", "'\\rangle'", "'\\lim'", "",
+                     "", "'\\sum'", "'\\prod'", "'\\exp'", "'\\log'",
+                     "'\\lg'", "'\\ln'", "'\\sin'", "'\\cos'", "'\\tan'",
+                     "'\\csc'", "'\\sec'", "'\\cot'", "'\\arcsin'", "'\\arccos'",
+                     "'\\arctan'", "'\\arccsc'", "'\\arcsec'", "'\\arccot'",
+                     "'\\sinh'", "'\\cosh'", "'\\tanh'", "'\\arsinh'", "'\\arcosh'",
+                     "'\\artanh'", "'\\lfloor'", "'\\rfloor'", "'\\lceil'",
+                     "'\\rceil'", "'\\sqrt'", "'\\overline'", "'\\times'",
+                     "'\\cdot'", "'\\div'", "", "'\\binom'", "'\\dbinom'",
+                     "'\\tbinom'", "'\\mathit'", "'_'", "'^'", "':'", "",
+                     "", "", "", "'\\neq'", "'<'",
+                     "", "'\\leqq'", "'\\leqslant'", "'>'", "",
+                     "'\\geqq'", "'\\geqslant'", "'!'" ]
+
+    symbolicNames = [ "", "", "", "WS", "THINSPACE",
+                      "MEDSPACE", "THICKSPACE", "QUAD", "QQUAD", "NEGTHINSPACE",
+                      "NEGMEDSPACE", "NEGTHICKSPACE", "CMD_LEFT", "CMD_RIGHT",
+                      "IGNORE", "ADD", "SUB", "MUL", "DIV", "L_PAREN", "R_PAREN",
+                      "L_BRACE", "R_BRACE", "L_BRACE_LITERAL", "R_BRACE_LITERAL",
+                      "L_BRACKET", "R_BRACKET", "BAR", "R_BAR", "L_BAR",
+                      "L_ANGLE", "R_ANGLE", "FUNC_LIM", "LIM_APPROACH_SYM",
+                      "FUNC_INT", "FUNC_SUM", "FUNC_PROD", "FUNC_EXP", "FUNC_LOG",
+                      "FUNC_LG", "FUNC_LN", "FUNC_SIN", "FUNC_COS", "FUNC_TAN",
+                      "FUNC_CSC", "FUNC_SEC", "FUNC_COT", "FUNC_ARCSIN",
+                      "FUNC_ARCCOS", "FUNC_ARCTAN", "FUNC_ARCCSC", "FUNC_ARCSEC",
+                      "FUNC_ARCCOT", "FUNC_SINH", "FUNC_COSH", "FUNC_TANH",
+                      "FUNC_ARSINH", "FUNC_ARCOSH", "FUNC_ARTANH", "L_FLOOR",
+                      "R_FLOOR", "L_CEIL", "R_CEIL", "FUNC_SQRT", "FUNC_OVERLINE",
+                      "CMD_TIMES", "CMD_CDOT", "CMD_DIV", "CMD_FRAC", "CMD_BINOM",
+                      "CMD_DBINOM", "CMD_TBINOM", "CMD_MATHIT", "UNDERSCORE",
+                      "CARET", "COLON", "DIFFERENTIAL", "LETTER", "DIGIT",
+                      "EQUAL", "NEQ", "LT", "LTE", "LTE_Q", "LTE_S", "GT",
+                      "GTE", "GTE_Q", "GTE_S", "BANG", "SINGLE_QUOTES",
+                      "SYMBOL" ]
+
+    RULE_math = 0
+    RULE_relation = 1
+    RULE_equality = 2
+    RULE_expr = 3
+    RULE_additive = 4
+    RULE_mp = 5
+    RULE_mp_nofunc = 6
+    RULE_unary = 7
+    RULE_unary_nofunc = 8
+    RULE_postfix = 9
+    RULE_postfix_nofunc = 10
+    RULE_postfix_op = 11
+    RULE_eval_at = 12
+    RULE_eval_at_sub = 13
+    RULE_eval_at_sup = 14
+    RULE_exp = 15
+    RULE_exp_nofunc = 16
+    RULE_comp = 17
+    RULE_comp_nofunc = 18
+    RULE_group = 19
+    RULE_abs_group = 20
+    RULE_number = 21
+    RULE_atom = 22
+    RULE_bra = 23
+    RULE_ket = 24
+    RULE_mathit = 25
+    RULE_mathit_text = 26
+    RULE_frac = 27
+    RULE_binom = 28
+    RULE_floor = 29
+    RULE_ceil = 30
+    RULE_func_normal = 31
+    RULE_func = 32
+    RULE_args = 33
+    RULE_limit_sub = 34
+    RULE_func_arg = 35
+    RULE_func_arg_noparens = 36
+    RULE_subexpr = 37
+    RULE_supexpr = 38
+    RULE_subeq = 39
+    RULE_supeq = 40
+
+    ruleNames =  [ "math", "relation", "equality", "expr", "additive", "mp",
+                   "mp_nofunc", "unary", "unary_nofunc", "postfix", "postfix_nofunc",
+                   "postfix_op", "eval_at", "eval_at_sub", "eval_at_sup",
+                   "exp", "exp_nofunc", "comp", "comp_nofunc", "group",
+                   "abs_group", "number", "atom", "bra", "ket", "mathit",
+                   "mathit_text", "frac", "binom", "floor", "ceil", "func_normal",
+                   "func", "args", "limit_sub", "func_arg", "func_arg_noparens",
+                   "subexpr", "supexpr", "subeq", "supeq" ]
+
+    EOF = Token.EOF
+    T__0=1
+    T__1=2
+    WS=3
+    THINSPACE=4
+    MEDSPACE=5
+    THICKSPACE=6
+    QUAD=7
+    QQUAD=8
+    NEGTHINSPACE=9
+    NEGMEDSPACE=10
+    NEGTHICKSPACE=11
+    CMD_LEFT=12
+    CMD_RIGHT=13
+    IGNORE=14
+    ADD=15
+    SUB=16
+    MUL=17
+    DIV=18
+    L_PAREN=19
+    R_PAREN=20
+    L_BRACE=21
+    R_BRACE=22
+    L_BRACE_LITERAL=23
+    R_BRACE_LITERAL=24
+    L_BRACKET=25
+    R_BRACKET=26
+    BAR=27
+    R_BAR=28
+    L_BAR=29
+    L_ANGLE=30
+    R_ANGLE=31
+    FUNC_LIM=32
+    LIM_APPROACH_SYM=33
+    FUNC_INT=34
+    FUNC_SUM=35
+    FUNC_PROD=36
+    FUNC_EXP=37
+    FUNC_LOG=38
+    FUNC_LG=39
+    FUNC_LN=40
+    FUNC_SIN=41
+    FUNC_COS=42
+    FUNC_TAN=43
+    FUNC_CSC=44
+    FUNC_SEC=45
+    FUNC_COT=46
+    FUNC_ARCSIN=47
+    FUNC_ARCCOS=48
+    FUNC_ARCTAN=49
+    FUNC_ARCCSC=50
+    FUNC_ARCSEC=51
+    FUNC_ARCCOT=52
+    FUNC_SINH=53
+    FUNC_COSH=54
+    FUNC_TANH=55
+    FUNC_ARSINH=56
+    FUNC_ARCOSH=57
+    FUNC_ARTANH=58
+    L_FLOOR=59
+    R_FLOOR=60
+    L_CEIL=61
+    R_CEIL=62
+    FUNC_SQRT=63
+    FUNC_OVERLINE=64
+    CMD_TIMES=65
+    CMD_CDOT=66
+    CMD_DIV=67
+    CMD_FRAC=68
+    CMD_BINOM=69
+    CMD_DBINOM=70
+    CMD_TBINOM=71
+    CMD_MATHIT=72
+    UNDERSCORE=73
+    CARET=74
+    COLON=75
+    DIFFERENTIAL=76
+    LETTER=77
+    DIGIT=78
+    EQUAL=79
+    NEQ=80
+    LT=81
+    LTE=82
+    LTE_Q=83
+    LTE_S=84
+    GT=85
+    GTE=86
+    GTE_Q=87
+    GTE_S=88
+    BANG=89
+    SINGLE_QUOTES=90
+    SYMBOL=91
+
+    def __init__(self, input:TokenStream, output:TextIO = sys.stdout):
+        super().__init__(input, output)
+        self.checkVersion("4.11.1")
+        self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache)
+        self._predicates = None
+
+
+
+
+    class MathContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def relation(self):
+            return self.getTypedRuleContext(LaTeXParser.RelationContext,0)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_math
+
+
+
+
+    def math(self):
+
+        localctx = LaTeXParser.MathContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 0, self.RULE_math)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 82
+            self.relation(0)
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class RelationContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def expr(self):
+            return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
+
+
+        def relation(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(LaTeXParser.RelationContext)
+            else:
+                return self.getTypedRuleContext(LaTeXParser.RelationContext,i)
+
+
+        def EQUAL(self):
+            return self.getToken(LaTeXParser.EQUAL, 0)
+
+        def LT(self):
+            return self.getToken(LaTeXParser.LT, 0)
+
+        def LTE(self):
+            return self.getToken(LaTeXParser.LTE, 0)
+
+        def GT(self):
+            return self.getToken(LaTeXParser.GT, 0)
+
+        def GTE(self):
+            return self.getToken(LaTeXParser.GTE, 0)
+
+        def NEQ(self):
+            return self.getToken(LaTeXParser.NEQ, 0)
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_relation
+
+
+
+    def relation(self, _p:int=0):
+        _parentctx = self._ctx
+        _parentState = self.state
+        localctx = LaTeXParser.RelationContext(self, self._ctx, _parentState)
+        _prevctx = localctx
+        _startState = 2
+        self.enterRecursionRule(localctx, 2, self.RULE_relation, _p)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 85
+            self.expr()
+            self._ctx.stop = self._input.LT(-1)
+            self.state = 92
+            self._errHandler.sync(self)
+            _alt = self._interp.adaptivePredict(self._input,0,self._ctx)
+            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
+                if _alt==1:
+                    if self._parseListeners is not None:
+                        self.triggerExitRuleEvent()
+                    _prevctx = localctx
+                    localctx = LaTeXParser.RelationContext(self, _parentctx, _parentState)
+                    self.pushNewRecursionContext(localctx, _startState, self.RULE_relation)
+                    self.state = 87
+                    if not self.precpred(self._ctx, 2):
+                        from antlr4.error.Errors import FailedPredicateException
+                        raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
+                    self.state = 88
+                    _la = self._input.LA(1)
+                    if not((((_la - 79)) & ~0x3f) == 0 and ((1 << (_la - 79)) & 207) != 0):
+                        self._errHandler.recoverInline(self)
+                    else:
+                        self._errHandler.reportMatch(self)
+                        self.consume()
+                    self.state = 89
+                    self.relation(3)
+                self.state = 94
+                self._errHandler.sync(self)
+                _alt = self._interp.adaptivePredict(self._input,0,self._ctx)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.unrollRecursionContexts(_parentctx)
+        return localctx
+
+
+    class EqualityContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def expr(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(LaTeXParser.ExprContext)
+            else:
+                return self.getTypedRuleContext(LaTeXParser.ExprContext,i)
+
+
+        def EQUAL(self):
+            return self.getToken(LaTeXParser.EQUAL, 0)
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_equality
+
+
+
+
+    def equality(self):
+
+        localctx = LaTeXParser.EqualityContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 4, self.RULE_equality)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 95
+            self.expr()
+            self.state = 96
+            self.match(LaTeXParser.EQUAL)
+            self.state = 97
+            self.expr()
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class ExprContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def additive(self):
+            return self.getTypedRuleContext(LaTeXParser.AdditiveContext,0)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_expr
+
+
+
+
+    def expr(self):
+
+        localctx = LaTeXParser.ExprContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 6, self.RULE_expr)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 99
+            self.additive(0)
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class AdditiveContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def mp(self):
+            return self.getTypedRuleContext(LaTeXParser.MpContext,0)
+
+
+        def additive(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(LaTeXParser.AdditiveContext)
+            else:
+                return self.getTypedRuleContext(LaTeXParser.AdditiveContext,i)
+
+
+        def ADD(self):
+            return self.getToken(LaTeXParser.ADD, 0)
+
+        def SUB(self):
+            return self.getToken(LaTeXParser.SUB, 0)
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_additive
+
+
+
+    def additive(self, _p:int=0):
+        _parentctx = self._ctx
+        _parentState = self.state
+        localctx = LaTeXParser.AdditiveContext(self, self._ctx, _parentState)
+        _prevctx = localctx
+        _startState = 8
+        self.enterRecursionRule(localctx, 8, self.RULE_additive, _p)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 102
+            self.mp(0)
+            self._ctx.stop = self._input.LT(-1)
+            self.state = 109
+            self._errHandler.sync(self)
+            _alt = self._interp.adaptivePredict(self._input,1,self._ctx)
+            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
+                if _alt==1:
+                    if self._parseListeners is not None:
+                        self.triggerExitRuleEvent()
+                    _prevctx = localctx
+                    localctx = LaTeXParser.AdditiveContext(self, _parentctx, _parentState)
+                    self.pushNewRecursionContext(localctx, _startState, self.RULE_additive)
+                    self.state = 104
+                    if not self.precpred(self._ctx, 2):
+                        from antlr4.error.Errors import FailedPredicateException
+                        raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
+                    self.state = 105
+                    _la = self._input.LA(1)
+                    if not(_la==15 or _la==16):
+                        self._errHandler.recoverInline(self)
+                    else:
+                        self._errHandler.reportMatch(self)
+                        self.consume()
+                    self.state = 106
+                    self.additive(3)
+                self.state = 111
+                self._errHandler.sync(self)
+                _alt = self._interp.adaptivePredict(self._input,1,self._ctx)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.unrollRecursionContexts(_parentctx)
+        return localctx
+
+
+    class MpContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def unary(self):
+            return self.getTypedRuleContext(LaTeXParser.UnaryContext,0)
+
+
+        def mp(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(LaTeXParser.MpContext)
+            else:
+                return self.getTypedRuleContext(LaTeXParser.MpContext,i)
+
+
+        def MUL(self):
+            return self.getToken(LaTeXParser.MUL, 0)
+
+        def CMD_TIMES(self):
+            return self.getToken(LaTeXParser.CMD_TIMES, 0)
+
+        def CMD_CDOT(self):
+            return self.getToken(LaTeXParser.CMD_CDOT, 0)
+
+        def DIV(self):
+            return self.getToken(LaTeXParser.DIV, 0)
+
+        def CMD_DIV(self):
+            return self.getToken(LaTeXParser.CMD_DIV, 0)
+
+        def COLON(self):
+            return self.getToken(LaTeXParser.COLON, 0)
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_mp
+
+
+
+    def mp(self, _p:int=0):
+        _parentctx = self._ctx
+        _parentState = self.state
+        localctx = LaTeXParser.MpContext(self, self._ctx, _parentState)
+        _prevctx = localctx
+        _startState = 10
+        self.enterRecursionRule(localctx, 10, self.RULE_mp, _p)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 113
+            self.unary()
+            self._ctx.stop = self._input.LT(-1)
+            self.state = 120
+            self._errHandler.sync(self)
+            _alt = self._interp.adaptivePredict(self._input,2,self._ctx)
+            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
+                if _alt==1:
+                    if self._parseListeners is not None:
+                        self.triggerExitRuleEvent()
+                    _prevctx = localctx
+                    localctx = LaTeXParser.MpContext(self, _parentctx, _parentState)
+                    self.pushNewRecursionContext(localctx, _startState, self.RULE_mp)
+                    self.state = 115
+                    if not self.precpred(self._ctx, 2):
+                        from antlr4.error.Errors import FailedPredicateException
+                        raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
+                    self.state = 116
+                    _la = self._input.LA(1)
+                    if not((((_la - 17)) & ~0x3f) == 0 and ((1 << (_la - 17)) & 290200700988686339) != 0):
+                        self._errHandler.recoverInline(self)
+                    else:
+                        self._errHandler.reportMatch(self)
+                        self.consume()
+                    self.state = 117
+                    self.mp(3)
+                self.state = 122
+                self._errHandler.sync(self)
+                _alt = self._interp.adaptivePredict(self._input,2,self._ctx)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.unrollRecursionContexts(_parentctx)
+        return localctx
+
+
+    class Mp_nofuncContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def unary_nofunc(self):
+            return self.getTypedRuleContext(LaTeXParser.Unary_nofuncContext,0)
+
+
+        def mp_nofunc(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(LaTeXParser.Mp_nofuncContext)
+            else:
+                return self.getTypedRuleContext(LaTeXParser.Mp_nofuncContext,i)
+
+
+        def MUL(self):
+            return self.getToken(LaTeXParser.MUL, 0)
+
+        def CMD_TIMES(self):
+            return self.getToken(LaTeXParser.CMD_TIMES, 0)
+
+        def CMD_CDOT(self):
+            return self.getToken(LaTeXParser.CMD_CDOT, 0)
+
+        def DIV(self):
+            return self.getToken(LaTeXParser.DIV, 0)
+
+        def CMD_DIV(self):
+            return self.getToken(LaTeXParser.CMD_DIV, 0)
+
+        def COLON(self):
+            return self.getToken(LaTeXParser.COLON, 0)
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_mp_nofunc
+
+
+
+    def mp_nofunc(self, _p:int=0):
+        _parentctx = self._ctx
+        _parentState = self.state
+        localctx = LaTeXParser.Mp_nofuncContext(self, self._ctx, _parentState)
+        _prevctx = localctx
+        _startState = 12
+        self.enterRecursionRule(localctx, 12, self.RULE_mp_nofunc, _p)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 124
+            self.unary_nofunc()
+            self._ctx.stop = self._input.LT(-1)
+            self.state = 131
+            self._errHandler.sync(self)
+            _alt = self._interp.adaptivePredict(self._input,3,self._ctx)
+            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
+                if _alt==1:
+                    if self._parseListeners is not None:
+                        self.triggerExitRuleEvent()
+                    _prevctx = localctx
+                    localctx = LaTeXParser.Mp_nofuncContext(self, _parentctx, _parentState)
+                    self.pushNewRecursionContext(localctx, _startState, self.RULE_mp_nofunc)
+                    self.state = 126
+                    if not self.precpred(self._ctx, 2):
+                        from antlr4.error.Errors import FailedPredicateException
+                        raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
+                    self.state = 127
+                    _la = self._input.LA(1)
+                    if not((((_la - 17)) & ~0x3f) == 0 and ((1 << (_la - 17)) & 290200700988686339) != 0):
+                        self._errHandler.recoverInline(self)
+                    else:
+                        self._errHandler.reportMatch(self)
+                        self.consume()
+                    self.state = 128
+                    self.mp_nofunc(3)
+                self.state = 133
+                self._errHandler.sync(self)
+                _alt = self._interp.adaptivePredict(self._input,3,self._ctx)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.unrollRecursionContexts(_parentctx)
+        return localctx
+
+
+    class UnaryContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def unary(self):
+            return self.getTypedRuleContext(LaTeXParser.UnaryContext,0)
+
+
+        def ADD(self):
+            return self.getToken(LaTeXParser.ADD, 0)
+
+        def SUB(self):
+            return self.getToken(LaTeXParser.SUB, 0)
+
+        def postfix(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(LaTeXParser.PostfixContext)
+            else:
+                return self.getTypedRuleContext(LaTeXParser.PostfixContext,i)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_unary
+
+
+
+
+    def unary(self):
+
+        localctx = LaTeXParser.UnaryContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 14, self.RULE_unary)
+        self._la = 0 # Token type
+        try:
+            self.state = 141
+            self._errHandler.sync(self)
+            token = self._input.LA(1)
+            if token in [15, 16]:
+                self.enterOuterAlt(localctx, 1)
+                self.state = 134
+                _la = self._input.LA(1)
+                if not(_la==15 or _la==16):
+                    self._errHandler.recoverInline(self)
+                else:
+                    self._errHandler.reportMatch(self)
+                    self.consume()
+                self.state = 135
+                self.unary()
+                pass
+            elif token in [19, 21, 23, 25, 27, 29, 30, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 61, 63, 64, 68, 69, 70, 71, 72, 76, 77, 78, 91]:
+                self.enterOuterAlt(localctx, 2)
+                self.state = 137
+                self._errHandler.sync(self)
+                _alt = 1
+                while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
+                    if _alt == 1:
+                        self.state = 136
+                        self.postfix()
+
+                    else:
+                        raise NoViableAltException(self)
+                    self.state = 139
+                    self._errHandler.sync(self)
+                    _alt = self._interp.adaptivePredict(self._input,4,self._ctx)
+
+                pass
+            else:
+                raise NoViableAltException(self)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class Unary_nofuncContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def unary_nofunc(self):
+            return self.getTypedRuleContext(LaTeXParser.Unary_nofuncContext,0)
+
+
+        def ADD(self):
+            return self.getToken(LaTeXParser.ADD, 0)
+
+        def SUB(self):
+            return self.getToken(LaTeXParser.SUB, 0)
+
+        def postfix(self):
+            return self.getTypedRuleContext(LaTeXParser.PostfixContext,0)
+
+
+        def postfix_nofunc(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(LaTeXParser.Postfix_nofuncContext)
+            else:
+                return self.getTypedRuleContext(LaTeXParser.Postfix_nofuncContext,i)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_unary_nofunc
+
+
+
+
+    def unary_nofunc(self):
+
+        localctx = LaTeXParser.Unary_nofuncContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 16, self.RULE_unary_nofunc)
+        self._la = 0 # Token type
+        try:
+            self.state = 152
+            self._errHandler.sync(self)
+            token = self._input.LA(1)
+            if token in [15, 16]:
+                self.enterOuterAlt(localctx, 1)
+                self.state = 143
+                _la = self._input.LA(1)
+                if not(_la==15 or _la==16):
+                    self._errHandler.recoverInline(self)
+                else:
+                    self._errHandler.reportMatch(self)
+                    self.consume()
+                self.state = 144
+                self.unary_nofunc()
+                pass
+            elif token in [19, 21, 23, 25, 27, 29, 30, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 61, 63, 64, 68, 69, 70, 71, 72, 76, 77, 78, 91]:
+                self.enterOuterAlt(localctx, 2)
+                self.state = 145
+                self.postfix()
+                self.state = 149
+                self._errHandler.sync(self)
+                _alt = self._interp.adaptivePredict(self._input,6,self._ctx)
+                while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
+                    if _alt==1:
+                        self.state = 146
+                        self.postfix_nofunc()
+                    self.state = 151
+                    self._errHandler.sync(self)
+                    _alt = self._interp.adaptivePredict(self._input,6,self._ctx)
+
+                pass
+            else:
+                raise NoViableAltException(self)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class PostfixContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def exp(self):
+            return self.getTypedRuleContext(LaTeXParser.ExpContext,0)
+
+
+        def postfix_op(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(LaTeXParser.Postfix_opContext)
+            else:
+                return self.getTypedRuleContext(LaTeXParser.Postfix_opContext,i)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_postfix
+
+
+
+
+    def postfix(self):
+
+        localctx = LaTeXParser.PostfixContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 18, self.RULE_postfix)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 154
+            self.exp(0)
+            self.state = 158
+            self._errHandler.sync(self)
+            _alt = self._interp.adaptivePredict(self._input,8,self._ctx)
+            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
+                if _alt==1:
+                    self.state = 155
+                    self.postfix_op()
+                self.state = 160
+                self._errHandler.sync(self)
+                _alt = self._interp.adaptivePredict(self._input,8,self._ctx)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class Postfix_nofuncContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def exp_nofunc(self):
+            return self.getTypedRuleContext(LaTeXParser.Exp_nofuncContext,0)
+
+
+        def postfix_op(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(LaTeXParser.Postfix_opContext)
+            else:
+                return self.getTypedRuleContext(LaTeXParser.Postfix_opContext,i)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_postfix_nofunc
+
+
+
+
+    def postfix_nofunc(self):
+
+        localctx = LaTeXParser.Postfix_nofuncContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 20, self.RULE_postfix_nofunc)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 161
+            self.exp_nofunc(0)
+            self.state = 165
+            self._errHandler.sync(self)
+            _alt = self._interp.adaptivePredict(self._input,9,self._ctx)
+            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
+                if _alt==1:
+                    self.state = 162
+                    self.postfix_op()
+                self.state = 167
+                self._errHandler.sync(self)
+                _alt = self._interp.adaptivePredict(self._input,9,self._ctx)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class Postfix_opContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def BANG(self):
+            return self.getToken(LaTeXParser.BANG, 0)
+
+        def eval_at(self):
+            return self.getTypedRuleContext(LaTeXParser.Eval_atContext,0)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_postfix_op
+
+
+
+
+    def postfix_op(self):
+
+        localctx = LaTeXParser.Postfix_opContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 22, self.RULE_postfix_op)
+        try:
+            self.state = 170
+            self._errHandler.sync(self)
+            token = self._input.LA(1)
+            if token in [89]:
+                self.enterOuterAlt(localctx, 1)
+                self.state = 168
+                self.match(LaTeXParser.BANG)
+                pass
+            elif token in [27]:
+                self.enterOuterAlt(localctx, 2)
+                self.state = 169
+                self.eval_at()
+                pass
+            else:
+                raise NoViableAltException(self)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class Eval_atContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def BAR(self):
+            return self.getToken(LaTeXParser.BAR, 0)
+
+        def eval_at_sup(self):
+            return self.getTypedRuleContext(LaTeXParser.Eval_at_supContext,0)
+
+
+        def eval_at_sub(self):
+            return self.getTypedRuleContext(LaTeXParser.Eval_at_subContext,0)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_eval_at
+
+
+
+
+    def eval_at(self):
+
+        localctx = LaTeXParser.Eval_atContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 24, self.RULE_eval_at)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 172
+            self.match(LaTeXParser.BAR)
+            self.state = 178
+            self._errHandler.sync(self)
+            la_ = self._interp.adaptivePredict(self._input,11,self._ctx)
+            if la_ == 1:
+                self.state = 173
+                self.eval_at_sup()
+                pass
+
+            elif la_ == 2:
+                self.state = 174
+                self.eval_at_sub()
+                pass
+
+            elif la_ == 3:
+                self.state = 175
+                self.eval_at_sup()
+                self.state = 176
+                self.eval_at_sub()
+                pass
+
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class Eval_at_subContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def UNDERSCORE(self):
+            return self.getToken(LaTeXParser.UNDERSCORE, 0)
+
+        def L_BRACE(self):
+            return self.getToken(LaTeXParser.L_BRACE, 0)
+
+        def R_BRACE(self):
+            return self.getToken(LaTeXParser.R_BRACE, 0)
+
+        def expr(self):
+            return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
+
+
+        def equality(self):
+            return self.getTypedRuleContext(LaTeXParser.EqualityContext,0)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_eval_at_sub
+
+
+
+
+    def eval_at_sub(self):
+
+        localctx = LaTeXParser.Eval_at_subContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 26, self.RULE_eval_at_sub)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 180
+            self.match(LaTeXParser.UNDERSCORE)
+            self.state = 181
+            self.match(LaTeXParser.L_BRACE)
+            self.state = 184
+            self._errHandler.sync(self)
+            la_ = self._interp.adaptivePredict(self._input,12,self._ctx)
+            if la_ == 1:
+                self.state = 182
+                self.expr()
+                pass
+
+            elif la_ == 2:
+                self.state = 183
+                self.equality()
+                pass
+
+
+            self.state = 186
+            self.match(LaTeXParser.R_BRACE)
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class Eval_at_supContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def CARET(self):
+            return self.getToken(LaTeXParser.CARET, 0)
+
+        def L_BRACE(self):
+            return self.getToken(LaTeXParser.L_BRACE, 0)
+
+        def R_BRACE(self):
+            return self.getToken(LaTeXParser.R_BRACE, 0)
+
+        def expr(self):
+            return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
+
+
+        def equality(self):
+            return self.getTypedRuleContext(LaTeXParser.EqualityContext,0)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_eval_at_sup
+
+
+
+
+    def eval_at_sup(self):
+
+        localctx = LaTeXParser.Eval_at_supContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 28, self.RULE_eval_at_sup)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 188
+            self.match(LaTeXParser.CARET)
+            self.state = 189
+            self.match(LaTeXParser.L_BRACE)
+            self.state = 192
+            self._errHandler.sync(self)
+            la_ = self._interp.adaptivePredict(self._input,13,self._ctx)
+            if la_ == 1:
+                self.state = 190
+                self.expr()
+                pass
+
+            elif la_ == 2:
+                self.state = 191
+                self.equality()
+                pass
+
+
+            self.state = 194
+            self.match(LaTeXParser.R_BRACE)
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class ExpContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def comp(self):
+            return self.getTypedRuleContext(LaTeXParser.CompContext,0)
+
+
+        def exp(self):
+            return self.getTypedRuleContext(LaTeXParser.ExpContext,0)
+
+
+        def CARET(self):
+            return self.getToken(LaTeXParser.CARET, 0)
+
+        def atom(self):
+            return self.getTypedRuleContext(LaTeXParser.AtomContext,0)
+
+
+        def L_BRACE(self):
+            return self.getToken(LaTeXParser.L_BRACE, 0)
+
+        def expr(self):
+            return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
+
+
+        def R_BRACE(self):
+            return self.getToken(LaTeXParser.R_BRACE, 0)
+
+        def subexpr(self):
+            return self.getTypedRuleContext(LaTeXParser.SubexprContext,0)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_exp
+
+
+
+    def exp(self, _p:int=0):
+        _parentctx = self._ctx
+        _parentState = self.state
+        localctx = LaTeXParser.ExpContext(self, self._ctx, _parentState)
+        _prevctx = localctx
+        _startState = 30
+        self.enterRecursionRule(localctx, 30, self.RULE_exp, _p)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 197
+            self.comp()
+            self._ctx.stop = self._input.LT(-1)
+            self.state = 213
+            self._errHandler.sync(self)
+            _alt = self._interp.adaptivePredict(self._input,16,self._ctx)
+            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
+                if _alt==1:
+                    if self._parseListeners is not None:
+                        self.triggerExitRuleEvent()
+                    _prevctx = localctx
+                    localctx = LaTeXParser.ExpContext(self, _parentctx, _parentState)
+                    self.pushNewRecursionContext(localctx, _startState, self.RULE_exp)
+                    self.state = 199
+                    if not self.precpred(self._ctx, 2):
+                        from antlr4.error.Errors import FailedPredicateException
+                        raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
+                    self.state = 200
+                    self.match(LaTeXParser.CARET)
+                    self.state = 206
+                    self._errHandler.sync(self)
+                    token = self._input.LA(1)
+                    if token in [27, 29, 30, 68, 69, 70, 71, 72, 76, 77, 78, 91]:
+                        self.state = 201
+                        self.atom()
+                        pass
+                    elif token in [21]:
+                        self.state = 202
+                        self.match(LaTeXParser.L_BRACE)
+                        self.state = 203
+                        self.expr()
+                        self.state = 204
+                        self.match(LaTeXParser.R_BRACE)
+                        pass
+                    else:
+                        raise NoViableAltException(self)
+
+                    self.state = 209
+                    self._errHandler.sync(self)
+                    la_ = self._interp.adaptivePredict(self._input,15,self._ctx)
+                    if la_ == 1:
+                        self.state = 208
+                        self.subexpr()
+
+
+                self.state = 215
+                self._errHandler.sync(self)
+                _alt = self._interp.adaptivePredict(self._input,16,self._ctx)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.unrollRecursionContexts(_parentctx)
+        return localctx
+
+
+    class Exp_nofuncContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def comp_nofunc(self):
+            return self.getTypedRuleContext(LaTeXParser.Comp_nofuncContext,0)
+
+
+        def exp_nofunc(self):
+            return self.getTypedRuleContext(LaTeXParser.Exp_nofuncContext,0)
+
+
+        def CARET(self):
+            return self.getToken(LaTeXParser.CARET, 0)
+
+        def atom(self):
+            return self.getTypedRuleContext(LaTeXParser.AtomContext,0)
+
+
+        def L_BRACE(self):
+            return self.getToken(LaTeXParser.L_BRACE, 0)
+
+        def expr(self):
+            return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
+
+
+        def R_BRACE(self):
+            return self.getToken(LaTeXParser.R_BRACE, 0)
+
+        def subexpr(self):
+            return self.getTypedRuleContext(LaTeXParser.SubexprContext,0)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_exp_nofunc
+
+
+
+    def exp_nofunc(self, _p:int=0):
+        _parentctx = self._ctx
+        _parentState = self.state
+        localctx = LaTeXParser.Exp_nofuncContext(self, self._ctx, _parentState)
+        _prevctx = localctx
+        _startState = 32
+        self.enterRecursionRule(localctx, 32, self.RULE_exp_nofunc, _p)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 217
+            self.comp_nofunc()
+            self._ctx.stop = self._input.LT(-1)
+            self.state = 233
+            self._errHandler.sync(self)
+            _alt = self._interp.adaptivePredict(self._input,19,self._ctx)
+            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
+                if _alt==1:
+                    if self._parseListeners is not None:
+                        self.triggerExitRuleEvent()
+                    _prevctx = localctx
+                    localctx = LaTeXParser.Exp_nofuncContext(self, _parentctx, _parentState)
+                    self.pushNewRecursionContext(localctx, _startState, self.RULE_exp_nofunc)
+                    self.state = 219
+                    if not self.precpred(self._ctx, 2):
+                        from antlr4.error.Errors import FailedPredicateException
+                        raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
+                    self.state = 220
+                    self.match(LaTeXParser.CARET)
+                    self.state = 226
+                    self._errHandler.sync(self)
+                    token = self._input.LA(1)
+                    if token in [27, 29, 30, 68, 69, 70, 71, 72, 76, 77, 78, 91]:
+                        self.state = 221
+                        self.atom()
+                        pass
+                    elif token in [21]:
+                        self.state = 222
+                        self.match(LaTeXParser.L_BRACE)
+                        self.state = 223
+                        self.expr()
+                        self.state = 224
+                        self.match(LaTeXParser.R_BRACE)
+                        pass
+                    else:
+                        raise NoViableAltException(self)
+
+                    self.state = 229
+                    self._errHandler.sync(self)
+                    la_ = self._interp.adaptivePredict(self._input,18,self._ctx)
+                    if la_ == 1:
+                        self.state = 228
+                        self.subexpr()
+
+
+                self.state = 235
+                self._errHandler.sync(self)
+                _alt = self._interp.adaptivePredict(self._input,19,self._ctx)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.unrollRecursionContexts(_parentctx)
+        return localctx
+
+
+    class CompContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def group(self):
+            return self.getTypedRuleContext(LaTeXParser.GroupContext,0)
+
+
+        def abs_group(self):
+            return self.getTypedRuleContext(LaTeXParser.Abs_groupContext,0)
+
+
+        def func(self):
+            return self.getTypedRuleContext(LaTeXParser.FuncContext,0)
+
+
+        def atom(self):
+            return self.getTypedRuleContext(LaTeXParser.AtomContext,0)
+
+
+        def floor(self):
+            return self.getTypedRuleContext(LaTeXParser.FloorContext,0)
+
+
+        def ceil(self):
+            return self.getTypedRuleContext(LaTeXParser.CeilContext,0)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_comp
+
+
+
+
+    def comp(self):
+
+        localctx = LaTeXParser.CompContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 34, self.RULE_comp)
+        try:
+            self.state = 242
+            self._errHandler.sync(self)
+            la_ = self._interp.adaptivePredict(self._input,20,self._ctx)
+            if la_ == 1:
+                self.enterOuterAlt(localctx, 1)
+                self.state = 236
+                self.group()
+                pass
+
+            elif la_ == 2:
+                self.enterOuterAlt(localctx, 2)
+                self.state = 237
+                self.abs_group()
+                pass
+
+            elif la_ == 3:
+                self.enterOuterAlt(localctx, 3)
+                self.state = 238
+                self.func()
+                pass
+
+            elif la_ == 4:
+                self.enterOuterAlt(localctx, 4)
+                self.state = 239
+                self.atom()
+                pass
+
+            elif la_ == 5:
+                self.enterOuterAlt(localctx, 5)
+                self.state = 240
+                self.floor()
+                pass
+
+            elif la_ == 6:
+                self.enterOuterAlt(localctx, 6)
+                self.state = 241
+                self.ceil()
+                pass
+
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class Comp_nofuncContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def group(self):
+            return self.getTypedRuleContext(LaTeXParser.GroupContext,0)
+
+
+        def abs_group(self):
+            return self.getTypedRuleContext(LaTeXParser.Abs_groupContext,0)
+
+
+        def atom(self):
+            return self.getTypedRuleContext(LaTeXParser.AtomContext,0)
+
+
+        def floor(self):
+            return self.getTypedRuleContext(LaTeXParser.FloorContext,0)
+
+
+        def ceil(self):
+            return self.getTypedRuleContext(LaTeXParser.CeilContext,0)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_comp_nofunc
+
+
+
+
+    def comp_nofunc(self):
+
+        localctx = LaTeXParser.Comp_nofuncContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 36, self.RULE_comp_nofunc)
+        try:
+            self.state = 249
+            self._errHandler.sync(self)
+            la_ = self._interp.adaptivePredict(self._input,21,self._ctx)
+            if la_ == 1:
+                self.enterOuterAlt(localctx, 1)
+                self.state = 244
+                self.group()
+                pass
+
+            elif la_ == 2:
+                self.enterOuterAlt(localctx, 2)
+                self.state = 245
+                self.abs_group()
+                pass
+
+            elif la_ == 3:
+                self.enterOuterAlt(localctx, 3)
+                self.state = 246
+                self.atom()
+                pass
+
+            elif la_ == 4:
+                self.enterOuterAlt(localctx, 4)
+                self.state = 247
+                self.floor()
+                pass
+
+            elif la_ == 5:
+                self.enterOuterAlt(localctx, 5)
+                self.state = 248
+                self.ceil()
+                pass
+
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class GroupContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def L_PAREN(self):
+            return self.getToken(LaTeXParser.L_PAREN, 0)
+
+        def expr(self):
+            return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
+
+
+        def R_PAREN(self):
+            return self.getToken(LaTeXParser.R_PAREN, 0)
+
+        def L_BRACKET(self):
+            return self.getToken(LaTeXParser.L_BRACKET, 0)
+
+        def R_BRACKET(self):
+            return self.getToken(LaTeXParser.R_BRACKET, 0)
+
+        def L_BRACE(self):
+            return self.getToken(LaTeXParser.L_BRACE, 0)
+
+        def R_BRACE(self):
+            return self.getToken(LaTeXParser.R_BRACE, 0)
+
+        def L_BRACE_LITERAL(self):
+            return self.getToken(LaTeXParser.L_BRACE_LITERAL, 0)
+
+        def R_BRACE_LITERAL(self):
+            return self.getToken(LaTeXParser.R_BRACE_LITERAL, 0)
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_group
+
+
+
+
+    def group(self):
+
+        localctx = LaTeXParser.GroupContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 38, self.RULE_group)
+        try:
+            self.state = 267
+            self._errHandler.sync(self)
+            token = self._input.LA(1)
+            if token in [19]:
+                self.enterOuterAlt(localctx, 1)
+                self.state = 251
+                self.match(LaTeXParser.L_PAREN)
+                self.state = 252
+                self.expr()
+                self.state = 253
+                self.match(LaTeXParser.R_PAREN)
+                pass
+            elif token in [25]:
+                self.enterOuterAlt(localctx, 2)
+                self.state = 255
+                self.match(LaTeXParser.L_BRACKET)
+                self.state = 256
+                self.expr()
+                self.state = 257
+                self.match(LaTeXParser.R_BRACKET)
+                pass
+            elif token in [21]:
+                self.enterOuterAlt(localctx, 3)
+                self.state = 259
+                self.match(LaTeXParser.L_BRACE)
+                self.state = 260
+                self.expr()
+                self.state = 261
+                self.match(LaTeXParser.R_BRACE)
+                pass
+            elif token in [23]:
+                self.enterOuterAlt(localctx, 4)
+                self.state = 263
+                self.match(LaTeXParser.L_BRACE_LITERAL)
+                self.state = 264
+                self.expr()
+                self.state = 265
+                self.match(LaTeXParser.R_BRACE_LITERAL)
+                pass
+            else:
+                raise NoViableAltException(self)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class Abs_groupContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def BAR(self, i:int=None):
+            if i is None:
+                return self.getTokens(LaTeXParser.BAR)
+            else:
+                return self.getToken(LaTeXParser.BAR, i)
+
+        def expr(self):
+            return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_abs_group
+
+
+
+
+    def abs_group(self):
+
+        localctx = LaTeXParser.Abs_groupContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 40, self.RULE_abs_group)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 269
+            self.match(LaTeXParser.BAR)
+            self.state = 270
+            self.expr()
+            self.state = 271
+            self.match(LaTeXParser.BAR)
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class NumberContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def DIGIT(self, i:int=None):
+            if i is None:
+                return self.getTokens(LaTeXParser.DIGIT)
+            else:
+                return self.getToken(LaTeXParser.DIGIT, i)
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_number
+
+
+
+
+    def number(self):
+
+        localctx = LaTeXParser.NumberContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 42, self.RULE_number)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 274
+            self._errHandler.sync(self)
+            _alt = 1
+            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
+                if _alt == 1:
+                    self.state = 273
+                    self.match(LaTeXParser.DIGIT)
+
+                else:
+                    raise NoViableAltException(self)
+                self.state = 276
+                self._errHandler.sync(self)
+                _alt = self._interp.adaptivePredict(self._input,23,self._ctx)
+
+            self.state = 284
+            self._errHandler.sync(self)
+            _alt = self._interp.adaptivePredict(self._input,24,self._ctx)
+            while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
+                if _alt==1:
+                    self.state = 278
+                    self.match(LaTeXParser.T__0)
+                    self.state = 279
+                    self.match(LaTeXParser.DIGIT)
+                    self.state = 280
+                    self.match(LaTeXParser.DIGIT)
+                    self.state = 281
+                    self.match(LaTeXParser.DIGIT)
+                self.state = 286
+                self._errHandler.sync(self)
+                _alt = self._interp.adaptivePredict(self._input,24,self._ctx)
+
+            self.state = 293
+            self._errHandler.sync(self)
+            la_ = self._interp.adaptivePredict(self._input,26,self._ctx)
+            if la_ == 1:
+                self.state = 287
+                self.match(LaTeXParser.T__1)
+                self.state = 289
+                self._errHandler.sync(self)
+                _alt = 1
+                while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
+                    if _alt == 1:
+                        self.state = 288
+                        self.match(LaTeXParser.DIGIT)
+
+                    else:
+                        raise NoViableAltException(self)
+                    self.state = 291
+                    self._errHandler.sync(self)
+                    _alt = self._interp.adaptivePredict(self._input,25,self._ctx)
+
+
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class AtomContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def LETTER(self):
+            return self.getToken(LaTeXParser.LETTER, 0)
+
+        def SYMBOL(self):
+            return self.getToken(LaTeXParser.SYMBOL, 0)
+
+        def subexpr(self):
+            return self.getTypedRuleContext(LaTeXParser.SubexprContext,0)
+
+
+        def SINGLE_QUOTES(self):
+            return self.getToken(LaTeXParser.SINGLE_QUOTES, 0)
+
+        def number(self):
+            return self.getTypedRuleContext(LaTeXParser.NumberContext,0)
+
+
+        def DIFFERENTIAL(self):
+            return self.getToken(LaTeXParser.DIFFERENTIAL, 0)
+
+        def mathit(self):
+            return self.getTypedRuleContext(LaTeXParser.MathitContext,0)
+
+
+        def frac(self):
+            return self.getTypedRuleContext(LaTeXParser.FracContext,0)
+
+
+        def binom(self):
+            return self.getTypedRuleContext(LaTeXParser.BinomContext,0)
+
+
+        def bra(self):
+            return self.getTypedRuleContext(LaTeXParser.BraContext,0)
+
+
+        def ket(self):
+            return self.getTypedRuleContext(LaTeXParser.KetContext,0)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_atom
+
+
+
+
+    def atom(self):
+
+        localctx = LaTeXParser.AtomContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 44, self.RULE_atom)
+        self._la = 0 # Token type
+        try:
+            self.state = 317
+            self._errHandler.sync(self)
+            token = self._input.LA(1)
+            if token in [77, 91]:
+                self.enterOuterAlt(localctx, 1)
+                self.state = 295
+                _la = self._input.LA(1)
+                if not(_la==77 or _la==91):
+                    self._errHandler.recoverInline(self)
+                else:
+                    self._errHandler.reportMatch(self)
+                    self.consume()
+                self.state = 308
+                self._errHandler.sync(self)
+                la_ = self._interp.adaptivePredict(self._input,31,self._ctx)
+                if la_ == 1:
+                    self.state = 297
+                    self._errHandler.sync(self)
+                    la_ = self._interp.adaptivePredict(self._input,27,self._ctx)
+                    if la_ == 1:
+                        self.state = 296
+                        self.subexpr()
+
+
+                    self.state = 300
+                    self._errHandler.sync(self)
+                    la_ = self._interp.adaptivePredict(self._input,28,self._ctx)
+                    if la_ == 1:
+                        self.state = 299
+                        self.match(LaTeXParser.SINGLE_QUOTES)
+
+
+                    pass
+
+                elif la_ == 2:
+                    self.state = 303
+                    self._errHandler.sync(self)
+                    la_ = self._interp.adaptivePredict(self._input,29,self._ctx)
+                    if la_ == 1:
+                        self.state = 302
+                        self.match(LaTeXParser.SINGLE_QUOTES)
+
+
+                    self.state = 306
+                    self._errHandler.sync(self)
+                    la_ = self._interp.adaptivePredict(self._input,30,self._ctx)
+                    if la_ == 1:
+                        self.state = 305
+                        self.subexpr()
+
+
+                    pass
+
+
+                pass
+            elif token in [78]:
+                self.enterOuterAlt(localctx, 2)
+                self.state = 310
+                self.number()
+                pass
+            elif token in [76]:
+                self.enterOuterAlt(localctx, 3)
+                self.state = 311
+                self.match(LaTeXParser.DIFFERENTIAL)
+                pass
+            elif token in [72]:
+                self.enterOuterAlt(localctx, 4)
+                self.state = 312
+                self.mathit()
+                pass
+            elif token in [68]:
+                self.enterOuterAlt(localctx, 5)
+                self.state = 313
+                self.frac()
+                pass
+            elif token in [69, 70, 71]:
+                self.enterOuterAlt(localctx, 6)
+                self.state = 314
+                self.binom()
+                pass
+            elif token in [30]:
+                self.enterOuterAlt(localctx, 7)
+                self.state = 315
+                self.bra()
+                pass
+            elif token in [27, 29]:
+                self.enterOuterAlt(localctx, 8)
+                self.state = 316
+                self.ket()
+                pass
+            else:
+                raise NoViableAltException(self)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class BraContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def L_ANGLE(self):
+            return self.getToken(LaTeXParser.L_ANGLE, 0)
+
+        def expr(self):
+            return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
+
+
+        def R_BAR(self):
+            return self.getToken(LaTeXParser.R_BAR, 0)
+
+        def BAR(self):
+            return self.getToken(LaTeXParser.BAR, 0)
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_bra
+
+
+
+
+    def bra(self):
+
+        localctx = LaTeXParser.BraContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 46, self.RULE_bra)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 319
+            self.match(LaTeXParser.L_ANGLE)
+            self.state = 320
+            self.expr()
+            self.state = 321
+            _la = self._input.LA(1)
+            if not(_la==27 or _la==28):
+                self._errHandler.recoverInline(self)
+            else:
+                self._errHandler.reportMatch(self)
+                self.consume()
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class KetContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def expr(self):
+            return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
+
+
+        def R_ANGLE(self):
+            return self.getToken(LaTeXParser.R_ANGLE, 0)
+
+        def L_BAR(self):
+            return self.getToken(LaTeXParser.L_BAR, 0)
+
+        def BAR(self):
+            return self.getToken(LaTeXParser.BAR, 0)
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_ket
+
+
+
+
+    def ket(self):
+
+        localctx = LaTeXParser.KetContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 48, self.RULE_ket)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 323
+            _la = self._input.LA(1)
+            if not(_la==27 or _la==29):
+                self._errHandler.recoverInline(self)
+            else:
+                self._errHandler.reportMatch(self)
+                self.consume()
+            self.state = 324
+            self.expr()
+            self.state = 325
+            self.match(LaTeXParser.R_ANGLE)
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class MathitContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def CMD_MATHIT(self):
+            return self.getToken(LaTeXParser.CMD_MATHIT, 0)
+
+        def L_BRACE(self):
+            return self.getToken(LaTeXParser.L_BRACE, 0)
+
+        def mathit_text(self):
+            return self.getTypedRuleContext(LaTeXParser.Mathit_textContext,0)
+
+
+        def R_BRACE(self):
+            return self.getToken(LaTeXParser.R_BRACE, 0)
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_mathit
+
+
+
+
+    def mathit(self):
+
+        localctx = LaTeXParser.MathitContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 50, self.RULE_mathit)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 327
+            self.match(LaTeXParser.CMD_MATHIT)
+            self.state = 328
+            self.match(LaTeXParser.L_BRACE)
+            self.state = 329
+            self.mathit_text()
+            self.state = 330
+            self.match(LaTeXParser.R_BRACE)
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class Mathit_textContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def LETTER(self, i:int=None):
+            if i is None:
+                return self.getTokens(LaTeXParser.LETTER)
+            else:
+                return self.getToken(LaTeXParser.LETTER, i)
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_mathit_text
+
+
+
+
+    def mathit_text(self):
+
+        localctx = LaTeXParser.Mathit_textContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 52, self.RULE_mathit_text)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 335
+            self._errHandler.sync(self)
+            _la = self._input.LA(1)
+            while _la==77:
+                self.state = 332
+                self.match(LaTeXParser.LETTER)
+                self.state = 337
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class FracContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+            self.upperd = None # Token
+            self.upper = None # ExprContext
+            self.lowerd = None # Token
+            self.lower = None # ExprContext
+
+        def CMD_FRAC(self):
+            return self.getToken(LaTeXParser.CMD_FRAC, 0)
+
+        def L_BRACE(self, i:int=None):
+            if i is None:
+                return self.getTokens(LaTeXParser.L_BRACE)
+            else:
+                return self.getToken(LaTeXParser.L_BRACE, i)
+
+        def R_BRACE(self, i:int=None):
+            if i is None:
+                return self.getTokens(LaTeXParser.R_BRACE)
+            else:
+                return self.getToken(LaTeXParser.R_BRACE, i)
+
+        def DIGIT(self, i:int=None):
+            if i is None:
+                return self.getTokens(LaTeXParser.DIGIT)
+            else:
+                return self.getToken(LaTeXParser.DIGIT, i)
+
+        def expr(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(LaTeXParser.ExprContext)
+            else:
+                return self.getTypedRuleContext(LaTeXParser.ExprContext,i)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_frac
+
+
+
+
+    def frac(self):
+
+        localctx = LaTeXParser.FracContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 54, self.RULE_frac)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 338
+            self.match(LaTeXParser.CMD_FRAC)
+            self.state = 344
+            self._errHandler.sync(self)
+            token = self._input.LA(1)
+            if token in [78]:
+                self.state = 339
+                localctx.upperd = self.match(LaTeXParser.DIGIT)
+                pass
+            elif token in [21]:
+                self.state = 340
+                self.match(LaTeXParser.L_BRACE)
+                self.state = 341
+                localctx.upper = self.expr()
+                self.state = 342
+                self.match(LaTeXParser.R_BRACE)
+                pass
+            else:
+                raise NoViableAltException(self)
+
+            self.state = 351
+            self._errHandler.sync(self)
+            token = self._input.LA(1)
+            if token in [78]:
+                self.state = 346
+                localctx.lowerd = self.match(LaTeXParser.DIGIT)
+                pass
+            elif token in [21]:
+                self.state = 347
+                self.match(LaTeXParser.L_BRACE)
+                self.state = 348
+                localctx.lower = self.expr()
+                self.state = 349
+                self.match(LaTeXParser.R_BRACE)
+                pass
+            else:
+                raise NoViableAltException(self)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class BinomContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+            self.n = None # ExprContext
+            self.k = None # ExprContext
+
+        def L_BRACE(self, i:int=None):
+            if i is None:
+                return self.getTokens(LaTeXParser.L_BRACE)
+            else:
+                return self.getToken(LaTeXParser.L_BRACE, i)
+
+        def R_BRACE(self, i:int=None):
+            if i is None:
+                return self.getTokens(LaTeXParser.R_BRACE)
+            else:
+                return self.getToken(LaTeXParser.R_BRACE, i)
+
+        def CMD_BINOM(self):
+            return self.getToken(LaTeXParser.CMD_BINOM, 0)
+
+        def CMD_DBINOM(self):
+            return self.getToken(LaTeXParser.CMD_DBINOM, 0)
+
+        def CMD_TBINOM(self):
+            return self.getToken(LaTeXParser.CMD_TBINOM, 0)
+
+        def expr(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(LaTeXParser.ExprContext)
+            else:
+                return self.getTypedRuleContext(LaTeXParser.ExprContext,i)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_binom
+
+
+
+
+    def binom(self):
+
+        localctx = LaTeXParser.BinomContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 56, self.RULE_binom)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 353
+            _la = self._input.LA(1)
+            if not((((_la - 69)) & ~0x3f) == 0 and ((1 << (_la - 69)) & 7) != 0):
+                self._errHandler.recoverInline(self)
+            else:
+                self._errHandler.reportMatch(self)
+                self.consume()
+            self.state = 354
+            self.match(LaTeXParser.L_BRACE)
+            self.state = 355
+            localctx.n = self.expr()
+            self.state = 356
+            self.match(LaTeXParser.R_BRACE)
+            self.state = 357
+            self.match(LaTeXParser.L_BRACE)
+            self.state = 358
+            localctx.k = self.expr()
+            self.state = 359
+            self.match(LaTeXParser.R_BRACE)
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class FloorContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+            self.val = None # ExprContext
+
+        def L_FLOOR(self):
+            return self.getToken(LaTeXParser.L_FLOOR, 0)
+
+        def R_FLOOR(self):
+            return self.getToken(LaTeXParser.R_FLOOR, 0)
+
+        def expr(self):
+            return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_floor
+
+
+
+
+    def floor(self):
+
+        localctx = LaTeXParser.FloorContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 58, self.RULE_floor)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 361
+            self.match(LaTeXParser.L_FLOOR)
+            self.state = 362
+            localctx.val = self.expr()
+            self.state = 363
+            self.match(LaTeXParser.R_FLOOR)
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class CeilContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+            self.val = None # ExprContext
+
+        def L_CEIL(self):
+            return self.getToken(LaTeXParser.L_CEIL, 0)
+
+        def R_CEIL(self):
+            return self.getToken(LaTeXParser.R_CEIL, 0)
+
+        def expr(self):
+            return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_ceil
+
+
+
+
+    def ceil(self):
+
+        localctx = LaTeXParser.CeilContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 60, self.RULE_ceil)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 365
+            self.match(LaTeXParser.L_CEIL)
+            self.state = 366
+            localctx.val = self.expr()
+            self.state = 367
+            self.match(LaTeXParser.R_CEIL)
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class Func_normalContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def FUNC_EXP(self):
+            return self.getToken(LaTeXParser.FUNC_EXP, 0)
+
+        def FUNC_LOG(self):
+            return self.getToken(LaTeXParser.FUNC_LOG, 0)
+
+        def FUNC_LG(self):
+            return self.getToken(LaTeXParser.FUNC_LG, 0)
+
+        def FUNC_LN(self):
+            return self.getToken(LaTeXParser.FUNC_LN, 0)
+
+        def FUNC_SIN(self):
+            return self.getToken(LaTeXParser.FUNC_SIN, 0)
+
+        def FUNC_COS(self):
+            return self.getToken(LaTeXParser.FUNC_COS, 0)
+
+        def FUNC_TAN(self):
+            return self.getToken(LaTeXParser.FUNC_TAN, 0)
+
+        def FUNC_CSC(self):
+            return self.getToken(LaTeXParser.FUNC_CSC, 0)
+
+        def FUNC_SEC(self):
+            return self.getToken(LaTeXParser.FUNC_SEC, 0)
+
+        def FUNC_COT(self):
+            return self.getToken(LaTeXParser.FUNC_COT, 0)
+
+        def FUNC_ARCSIN(self):
+            return self.getToken(LaTeXParser.FUNC_ARCSIN, 0)
+
+        def FUNC_ARCCOS(self):
+            return self.getToken(LaTeXParser.FUNC_ARCCOS, 0)
+
+        def FUNC_ARCTAN(self):
+            return self.getToken(LaTeXParser.FUNC_ARCTAN, 0)
+
+        def FUNC_ARCCSC(self):
+            return self.getToken(LaTeXParser.FUNC_ARCCSC, 0)
+
+        def FUNC_ARCSEC(self):
+            return self.getToken(LaTeXParser.FUNC_ARCSEC, 0)
+
+        def FUNC_ARCCOT(self):
+            return self.getToken(LaTeXParser.FUNC_ARCCOT, 0)
+
+        def FUNC_SINH(self):
+            return self.getToken(LaTeXParser.FUNC_SINH, 0)
+
+        def FUNC_COSH(self):
+            return self.getToken(LaTeXParser.FUNC_COSH, 0)
+
+        def FUNC_TANH(self):
+            return self.getToken(LaTeXParser.FUNC_TANH, 0)
+
+        def FUNC_ARSINH(self):
+            return self.getToken(LaTeXParser.FUNC_ARSINH, 0)
+
+        def FUNC_ARCOSH(self):
+            return self.getToken(LaTeXParser.FUNC_ARCOSH, 0)
+
+        def FUNC_ARTANH(self):
+            return self.getToken(LaTeXParser.FUNC_ARTANH, 0)
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_func_normal
+
+
+
+
+    def func_normal(self):
+
+        localctx = LaTeXParser.Func_normalContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 62, self.RULE_func_normal)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 369
+            _la = self._input.LA(1)
+            if not(((_la) & ~0x3f) == 0 and ((1 << _la) & 576460614864470016) != 0):
+                self._errHandler.recoverInline(self)
+            else:
+                self._errHandler.reportMatch(self)
+                self.consume()
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class FuncContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+            self.root = None # ExprContext
+            self.base = None # ExprContext
+
+        def func_normal(self):
+            return self.getTypedRuleContext(LaTeXParser.Func_normalContext,0)
+
+
+        def L_PAREN(self):
+            return self.getToken(LaTeXParser.L_PAREN, 0)
+
+        def func_arg(self):
+            return self.getTypedRuleContext(LaTeXParser.Func_argContext,0)
+
+
+        def R_PAREN(self):
+            return self.getToken(LaTeXParser.R_PAREN, 0)
+
+        def func_arg_noparens(self):
+            return self.getTypedRuleContext(LaTeXParser.Func_arg_noparensContext,0)
+
+
+        def subexpr(self):
+            return self.getTypedRuleContext(LaTeXParser.SubexprContext,0)
+
+
+        def supexpr(self):
+            return self.getTypedRuleContext(LaTeXParser.SupexprContext,0)
+
+
+        def args(self):
+            return self.getTypedRuleContext(LaTeXParser.ArgsContext,0)
+
+
+        def LETTER(self):
+            return self.getToken(LaTeXParser.LETTER, 0)
+
+        def SYMBOL(self):
+            return self.getToken(LaTeXParser.SYMBOL, 0)
+
+        def SINGLE_QUOTES(self):
+            return self.getToken(LaTeXParser.SINGLE_QUOTES, 0)
+
+        def FUNC_INT(self):
+            return self.getToken(LaTeXParser.FUNC_INT, 0)
+
+        def DIFFERENTIAL(self):
+            return self.getToken(LaTeXParser.DIFFERENTIAL, 0)
+
+        def frac(self):
+            return self.getTypedRuleContext(LaTeXParser.FracContext,0)
+
+
+        def additive(self):
+            return self.getTypedRuleContext(LaTeXParser.AdditiveContext,0)
+
+
+        def FUNC_SQRT(self):
+            return self.getToken(LaTeXParser.FUNC_SQRT, 0)
+
+        def L_BRACE(self):
+            return self.getToken(LaTeXParser.L_BRACE, 0)
+
+        def R_BRACE(self):
+            return self.getToken(LaTeXParser.R_BRACE, 0)
+
+        def expr(self, i:int=None):
+            if i is None:
+                return self.getTypedRuleContexts(LaTeXParser.ExprContext)
+            else:
+                return self.getTypedRuleContext(LaTeXParser.ExprContext,i)
+
+
+        def L_BRACKET(self):
+            return self.getToken(LaTeXParser.L_BRACKET, 0)
+
+        def R_BRACKET(self):
+            return self.getToken(LaTeXParser.R_BRACKET, 0)
+
+        def FUNC_OVERLINE(self):
+            return self.getToken(LaTeXParser.FUNC_OVERLINE, 0)
+
+        def mp(self):
+            return self.getTypedRuleContext(LaTeXParser.MpContext,0)
+
+
+        def FUNC_SUM(self):
+            return self.getToken(LaTeXParser.FUNC_SUM, 0)
+
+        def FUNC_PROD(self):
+            return self.getToken(LaTeXParser.FUNC_PROD, 0)
+
+        def subeq(self):
+            return self.getTypedRuleContext(LaTeXParser.SubeqContext,0)
+
+
+        def FUNC_LIM(self):
+            return self.getToken(LaTeXParser.FUNC_LIM, 0)
+
+        def limit_sub(self):
+            return self.getTypedRuleContext(LaTeXParser.Limit_subContext,0)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_func
+
+
+
+
+    def func(self):
+
+        localctx = LaTeXParser.FuncContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 64, self.RULE_func)
+        self._la = 0 # Token type
+        try:
+            self.state = 460
+            self._errHandler.sync(self)
+            token = self._input.LA(1)
+            if token in [37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58]:
+                self.enterOuterAlt(localctx, 1)
+                self.state = 371
+                self.func_normal()
+                self.state = 384
+                self._errHandler.sync(self)
+                la_ = self._interp.adaptivePredict(self._input,40,self._ctx)
+                if la_ == 1:
+                    self.state = 373
+                    self._errHandler.sync(self)
+                    _la = self._input.LA(1)
+                    if _la==73:
+                        self.state = 372
+                        self.subexpr()
+
+
+                    self.state = 376
+                    self._errHandler.sync(self)
+                    _la = self._input.LA(1)
+                    if _la==74:
+                        self.state = 375
+                        self.supexpr()
+
+
+                    pass
+
+                elif la_ == 2:
+                    self.state = 379
+                    self._errHandler.sync(self)
+                    _la = self._input.LA(1)
+                    if _la==74:
+                        self.state = 378
+                        self.supexpr()
+
+
+                    self.state = 382
+                    self._errHandler.sync(self)
+                    _la = self._input.LA(1)
+                    if _la==73:
+                        self.state = 381
+                        self.subexpr()
+
+
+                    pass
+
+
+                self.state = 391
+                self._errHandler.sync(self)
+                la_ = self._interp.adaptivePredict(self._input,41,self._ctx)
+                if la_ == 1:
+                    self.state = 386
+                    self.match(LaTeXParser.L_PAREN)
+                    self.state = 387
+                    self.func_arg()
+                    self.state = 388
+                    self.match(LaTeXParser.R_PAREN)
+                    pass
+
+                elif la_ == 2:
+                    self.state = 390
+                    self.func_arg_noparens()
+                    pass
+
+
+                pass
+            elif token in [77, 91]:
+                self.enterOuterAlt(localctx, 2)
+                self.state = 393
+                _la = self._input.LA(1)
+                if not(_la==77 or _la==91):
+                    self._errHandler.recoverInline(self)
+                else:
+                    self._errHandler.reportMatch(self)
+                    self.consume()
+                self.state = 406
+                self._errHandler.sync(self)
+                la_ = self._interp.adaptivePredict(self._input,46,self._ctx)
+                if la_ == 1:
+                    self.state = 395
+                    self._errHandler.sync(self)
+                    _la = self._input.LA(1)
+                    if _la==73:
+                        self.state = 394
+                        self.subexpr()
+
+
+                    self.state = 398
+                    self._errHandler.sync(self)
+                    _la = self._input.LA(1)
+                    if _la==90:
+                        self.state = 397
+                        self.match(LaTeXParser.SINGLE_QUOTES)
+
+
+                    pass
+
+                elif la_ == 2:
+                    self.state = 401
+                    self._errHandler.sync(self)
+                    _la = self._input.LA(1)
+                    if _la==90:
+                        self.state = 400
+                        self.match(LaTeXParser.SINGLE_QUOTES)
+
+
+                    self.state = 404
+                    self._errHandler.sync(self)
+                    _la = self._input.LA(1)
+                    if _la==73:
+                        self.state = 403
+                        self.subexpr()
+
+
+                    pass
+
+
+                self.state = 408
+                self.match(LaTeXParser.L_PAREN)
+                self.state = 409
+                self.args()
+                self.state = 410
+                self.match(LaTeXParser.R_PAREN)
+                pass
+            elif token in [34]:
+                self.enterOuterAlt(localctx, 3)
+                self.state = 412
+                self.match(LaTeXParser.FUNC_INT)
+                self.state = 419
+                self._errHandler.sync(self)
+                token = self._input.LA(1)
+                if token in [73]:
+                    self.state = 413
+                    self.subexpr()
+                    self.state = 414
+                    self.supexpr()
+                    pass
+                elif token in [74]:
+                    self.state = 416
+                    self.supexpr()
+                    self.state = 417
+                    self.subexpr()
+                    pass
+                elif token in [15, 16, 19, 21, 23, 25, 27, 29, 30, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 61, 63, 64, 68, 69, 70, 71, 72, 76, 77, 78, 91]:
+                    pass
+                else:
+                    pass
+                self.state = 427
+                self._errHandler.sync(self)
+                la_ = self._interp.adaptivePredict(self._input,49,self._ctx)
+                if la_ == 1:
+                    self.state = 422
+                    self._errHandler.sync(self)
+                    la_ = self._interp.adaptivePredict(self._input,48,self._ctx)
+                    if la_ == 1:
+                        self.state = 421
+                        self.additive(0)
+
+
+                    self.state = 424
+                    self.match(LaTeXParser.DIFFERENTIAL)
+                    pass
+
+                elif la_ == 2:
+                    self.state = 425
+                    self.frac()
+                    pass
+
+                elif la_ == 3:
+                    self.state = 426
+                    self.additive(0)
+                    pass
+
+
+                pass
+            elif token in [63]:
+                self.enterOuterAlt(localctx, 4)
+                self.state = 429
+                self.match(LaTeXParser.FUNC_SQRT)
+                self.state = 434
+                self._errHandler.sync(self)
+                _la = self._input.LA(1)
+                if _la==25:
+                    self.state = 430
+                    self.match(LaTeXParser.L_BRACKET)
+                    self.state = 431
+                    localctx.root = self.expr()
+                    self.state = 432
+                    self.match(LaTeXParser.R_BRACKET)
+
+
+                self.state = 436
+                self.match(LaTeXParser.L_BRACE)
+                self.state = 437
+                localctx.base = self.expr()
+                self.state = 438
+                self.match(LaTeXParser.R_BRACE)
+                pass
+            elif token in [64]:
+                self.enterOuterAlt(localctx, 5)
+                self.state = 440
+                self.match(LaTeXParser.FUNC_OVERLINE)
+                self.state = 441
+                self.match(LaTeXParser.L_BRACE)
+                self.state = 442
+                localctx.base = self.expr()
+                self.state = 443
+                self.match(LaTeXParser.R_BRACE)
+                pass
+            elif token in [35, 36]:
+                self.enterOuterAlt(localctx, 6)
+                self.state = 445
+                _la = self._input.LA(1)
+                if not(_la==35 or _la==36):
+                    self._errHandler.recoverInline(self)
+                else:
+                    self._errHandler.reportMatch(self)
+                    self.consume()
+                self.state = 452
+                self._errHandler.sync(self)
+                token = self._input.LA(1)
+                if token in [73]:
+                    self.state = 446
+                    self.subeq()
+                    self.state = 447
+                    self.supexpr()
+                    pass
+                elif token in [74]:
+                    self.state = 449
+                    self.supexpr()
+                    self.state = 450
+                    self.subeq()
+                    pass
+                else:
+                    raise NoViableAltException(self)
+
+                self.state = 454
+                self.mp(0)
+                pass
+            elif token in [32]:
+                self.enterOuterAlt(localctx, 7)
+                self.state = 456
+                self.match(LaTeXParser.FUNC_LIM)
+                self.state = 457
+                self.limit_sub()
+                self.state = 458
+                self.mp(0)
+                pass
+            else:
+                raise NoViableAltException(self)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class ArgsContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def expr(self):
+            return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
+
+
+        def args(self):
+            return self.getTypedRuleContext(LaTeXParser.ArgsContext,0)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_args
+
+
+
+
+    def args(self):
+
+        localctx = LaTeXParser.ArgsContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 66, self.RULE_args)
+        try:
+            self.state = 467
+            self._errHandler.sync(self)
+            la_ = self._interp.adaptivePredict(self._input,53,self._ctx)
+            if la_ == 1:
+                self.enterOuterAlt(localctx, 1)
+                self.state = 462
+                self.expr()
+                self.state = 463
+                self.match(LaTeXParser.T__0)
+                self.state = 464
+                self.args()
+                pass
+
+            elif la_ == 2:
+                self.enterOuterAlt(localctx, 2)
+                self.state = 466
+                self.expr()
+                pass
+
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class Limit_subContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def UNDERSCORE(self):
+            return self.getToken(LaTeXParser.UNDERSCORE, 0)
+
+        def L_BRACE(self, i:int=None):
+            if i is None:
+                return self.getTokens(LaTeXParser.L_BRACE)
+            else:
+                return self.getToken(LaTeXParser.L_BRACE, i)
+
+        def LIM_APPROACH_SYM(self):
+            return self.getToken(LaTeXParser.LIM_APPROACH_SYM, 0)
+
+        def expr(self):
+            return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
+
+
+        def R_BRACE(self, i:int=None):
+            if i is None:
+                return self.getTokens(LaTeXParser.R_BRACE)
+            else:
+                return self.getToken(LaTeXParser.R_BRACE, i)
+
+        def LETTER(self):
+            return self.getToken(LaTeXParser.LETTER, 0)
+
+        def SYMBOL(self):
+            return self.getToken(LaTeXParser.SYMBOL, 0)
+
+        def CARET(self):
+            return self.getToken(LaTeXParser.CARET, 0)
+
+        def ADD(self):
+            return self.getToken(LaTeXParser.ADD, 0)
+
+        def SUB(self):
+            return self.getToken(LaTeXParser.SUB, 0)
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_limit_sub
+
+
+
+
+    def limit_sub(self):
+
+        localctx = LaTeXParser.Limit_subContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 68, self.RULE_limit_sub)
+        self._la = 0 # Token type
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 469
+            self.match(LaTeXParser.UNDERSCORE)
+            self.state = 470
+            self.match(LaTeXParser.L_BRACE)
+            self.state = 471
+            _la = self._input.LA(1)
+            if not(_la==77 or _la==91):
+                self._errHandler.recoverInline(self)
+            else:
+                self._errHandler.reportMatch(self)
+                self.consume()
+            self.state = 472
+            self.match(LaTeXParser.LIM_APPROACH_SYM)
+            self.state = 473
+            self.expr()
+            self.state = 482
+            self._errHandler.sync(self)
+            _la = self._input.LA(1)
+            if _la==74:
+                self.state = 474
+                self.match(LaTeXParser.CARET)
+                self.state = 480
+                self._errHandler.sync(self)
+                token = self._input.LA(1)
+                if token in [21]:
+                    self.state = 475
+                    self.match(LaTeXParser.L_BRACE)
+                    self.state = 476
+                    _la = self._input.LA(1)
+                    if not(_la==15 or _la==16):
+                        self._errHandler.recoverInline(self)
+                    else:
+                        self._errHandler.reportMatch(self)
+                        self.consume()
+                    self.state = 477
+                    self.match(LaTeXParser.R_BRACE)
+                    pass
+                elif token in [15]:
+                    self.state = 478
+                    self.match(LaTeXParser.ADD)
+                    pass
+                elif token in [16]:
+                    self.state = 479
+                    self.match(LaTeXParser.SUB)
+                    pass
+                else:
+                    raise NoViableAltException(self)
+
+
+
+            self.state = 484
+            self.match(LaTeXParser.R_BRACE)
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class Func_argContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def expr(self):
+            return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
+
+
+        def func_arg(self):
+            return self.getTypedRuleContext(LaTeXParser.Func_argContext,0)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_func_arg
+
+
+
+
+    def func_arg(self):
+
+        localctx = LaTeXParser.Func_argContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 70, self.RULE_func_arg)
+        try:
+            self.state = 491
+            self._errHandler.sync(self)
+            la_ = self._interp.adaptivePredict(self._input,56,self._ctx)
+            if la_ == 1:
+                self.enterOuterAlt(localctx, 1)
+                self.state = 486
+                self.expr()
+                pass
+
+            elif la_ == 2:
+                self.enterOuterAlt(localctx, 2)
+                self.state = 487
+                self.expr()
+                self.state = 488
+                self.match(LaTeXParser.T__0)
+                self.state = 489
+                self.func_arg()
+                pass
+
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class Func_arg_noparensContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def mp_nofunc(self):
+            return self.getTypedRuleContext(LaTeXParser.Mp_nofuncContext,0)
+
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_func_arg_noparens
+
+
+
+
+    def func_arg_noparens(self):
+
+        localctx = LaTeXParser.Func_arg_noparensContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 72, self.RULE_func_arg_noparens)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 493
+            self.mp_nofunc(0)
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class SubexprContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def UNDERSCORE(self):
+            return self.getToken(LaTeXParser.UNDERSCORE, 0)
+
+        def atom(self):
+            return self.getTypedRuleContext(LaTeXParser.AtomContext,0)
+
+
+        def L_BRACE(self):
+            return self.getToken(LaTeXParser.L_BRACE, 0)
+
+        def expr(self):
+            return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
+
+
+        def R_BRACE(self):
+            return self.getToken(LaTeXParser.R_BRACE, 0)
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_subexpr
+
+
+
+
+    def subexpr(self):
+
+        localctx = LaTeXParser.SubexprContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 74, self.RULE_subexpr)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 495
+            self.match(LaTeXParser.UNDERSCORE)
+            self.state = 501
+            self._errHandler.sync(self)
+            token = self._input.LA(1)
+            if token in [27, 29, 30, 68, 69, 70, 71, 72, 76, 77, 78, 91]:
+                self.state = 496
+                self.atom()
+                pass
+            elif token in [21]:
+                self.state = 497
+                self.match(LaTeXParser.L_BRACE)
+                self.state = 498
+                self.expr()
+                self.state = 499
+                self.match(LaTeXParser.R_BRACE)
+                pass
+            else:
+                raise NoViableAltException(self)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class SupexprContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def CARET(self):
+            return self.getToken(LaTeXParser.CARET, 0)
+
+        def atom(self):
+            return self.getTypedRuleContext(LaTeXParser.AtomContext,0)
+
+
+        def L_BRACE(self):
+            return self.getToken(LaTeXParser.L_BRACE, 0)
+
+        def expr(self):
+            return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
+
+
+        def R_BRACE(self):
+            return self.getToken(LaTeXParser.R_BRACE, 0)
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_supexpr
+
+
+
+
+    def supexpr(self):
+
+        localctx = LaTeXParser.SupexprContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 76, self.RULE_supexpr)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 503
+            self.match(LaTeXParser.CARET)
+            self.state = 509
+            self._errHandler.sync(self)
+            token = self._input.LA(1)
+            if token in [27, 29, 30, 68, 69, 70, 71, 72, 76, 77, 78, 91]:
+                self.state = 504
+                self.atom()
+                pass
+            elif token in [21]:
+                self.state = 505
+                self.match(LaTeXParser.L_BRACE)
+                self.state = 506
+                self.expr()
+                self.state = 507
+                self.match(LaTeXParser.R_BRACE)
+                pass
+            else:
+                raise NoViableAltException(self)
+
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class SubeqContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def UNDERSCORE(self):
+            return self.getToken(LaTeXParser.UNDERSCORE, 0)
+
+        def L_BRACE(self):
+            return self.getToken(LaTeXParser.L_BRACE, 0)
+
+        def equality(self):
+            return self.getTypedRuleContext(LaTeXParser.EqualityContext,0)
+
+
+        def R_BRACE(self):
+            return self.getToken(LaTeXParser.R_BRACE, 0)
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_subeq
+
+
+
+
+    def subeq(self):
+
+        localctx = LaTeXParser.SubeqContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 78, self.RULE_subeq)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 511
+            self.match(LaTeXParser.UNDERSCORE)
+            self.state = 512
+            self.match(LaTeXParser.L_BRACE)
+            self.state = 513
+            self.equality()
+            self.state = 514
+            self.match(LaTeXParser.R_BRACE)
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+    class SupeqContext(ParserRuleContext):
+        __slots__ = 'parser'
+
+        def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
+            super().__init__(parent, invokingState)
+            self.parser = parser
+
+        def UNDERSCORE(self):
+            return self.getToken(LaTeXParser.UNDERSCORE, 0)
+
+        def L_BRACE(self):
+            return self.getToken(LaTeXParser.L_BRACE, 0)
+
+        def equality(self):
+            return self.getTypedRuleContext(LaTeXParser.EqualityContext,0)
+
+
+        def R_BRACE(self):
+            return self.getToken(LaTeXParser.R_BRACE, 0)
+
+        def getRuleIndex(self):
+            return LaTeXParser.RULE_supeq
+
+
+
+
+    def supeq(self):
+
+        localctx = LaTeXParser.SupeqContext(self, self._ctx, self.state)
+        self.enterRule(localctx, 80, self.RULE_supeq)
+        try:
+            self.enterOuterAlt(localctx, 1)
+            self.state = 516
+            self.match(LaTeXParser.UNDERSCORE)
+            self.state = 517
+            self.match(LaTeXParser.L_BRACE)
+            self.state = 518
+            self.equality()
+            self.state = 519
+            self.match(LaTeXParser.R_BRACE)
+        except RecognitionException as re:
+            localctx.exception = re
+            self._errHandler.reportError(self, re)
+            self._errHandler.recover(self, re)
+        finally:
+            self.exitRule()
+        return localctx
+
+
+
+    def sempred(self, localctx:RuleContext, ruleIndex:int, predIndex:int):
+        if self._predicates == None:
+            self._predicates = dict()
+        self._predicates[1] = self.relation_sempred
+        self._predicates[4] = self.additive_sempred
+        self._predicates[5] = self.mp_sempred
+        self._predicates[6] = self.mp_nofunc_sempred
+        self._predicates[15] = self.exp_sempred
+        self._predicates[16] = self.exp_nofunc_sempred
+        pred = self._predicates.get(ruleIndex, None)
+        if pred is None:
+            raise Exception("No predicate with index:" + str(ruleIndex))
+        else:
+            return pred(localctx, predIndex)
+
+    def relation_sempred(self, localctx:RelationContext, predIndex:int):
+            if predIndex == 0:
+                return self.precpred(self._ctx, 2)
+
+
+    def additive_sempred(self, localctx:AdditiveContext, predIndex:int):
+            if predIndex == 1:
+                return self.precpred(self._ctx, 2)
+
+
+    def mp_sempred(self, localctx:MpContext, predIndex:int):
+            if predIndex == 2:
+                return self.precpred(self._ctx, 2)
+
+
+    def mp_nofunc_sempred(self, localctx:Mp_nofuncContext, predIndex:int):
+            if predIndex == 3:
+                return self.precpred(self._ctx, 2)
+
+
+    def exp_sempred(self, localctx:ExpContext, predIndex:int):
+            if predIndex == 4:
+                return self.precpred(self._ctx, 2)
+
+
+    def exp_nofunc_sempred(self, localctx:Exp_nofuncContext, predIndex:int):
+            if predIndex == 5:
+                return self.precpred(self._ctx, 2)
+
+
+
+
+
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/_build_latex_antlr.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/_build_latex_antlr.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee50da5b7861154823812c7773360b53dfd29ff6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/_build_latex_antlr.py
@@ -0,0 +1,91 @@
+import os
+import subprocess
+import glob
+
+from sympy.utilities.misc import debug
+
+here = os.path.dirname(__file__)
+grammar_file = os.path.abspath(os.path.join(here, "LaTeX.g4"))
+dir_latex_antlr = os.path.join(here, "_antlr")
+
+header = '''\
+# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
+#
+# Generated from ../LaTeX.g4, derived from latex2sympy
+#     latex2sympy is licensed under the MIT license
+#     https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt
+#
+# Generated with antlr4
+#    antlr4 is licensed under the BSD-3-Clause License
+#    https://github.com/antlr/antlr4/blob/master/LICENSE.txt
+'''
+
+
+def check_antlr_version():
+    debug("Checking antlr4 version...")
+
+    try:
+        debug(subprocess.check_output(["antlr4"])
+              .decode('utf-8').split("\n")[0])
+        return True
+    except (subprocess.CalledProcessError, FileNotFoundError):
+        debug("The 'antlr4' command line tool is not installed, "
+              "or not on your PATH.\n"
+              "> Please refer to the README.md file for more information.")
+        return False
+
+
+def build_parser(output_dir=dir_latex_antlr):
+    check_antlr_version()
+
+    debug("Updating ANTLR-generated code in {}".format(output_dir))
+
+    if not os.path.exists(output_dir):
+        os.makedirs(output_dir)
+
+    with open(os.path.join(output_dir, "__init__.py"), "w+") as fp:
+        fp.write(header)
+
+    args = [
+        "antlr4",
+        grammar_file,
+        "-o", output_dir,
+        # for now, not generating these as latex2sympy did not use them
+        "-no-visitor",
+        "-no-listener",
+    ]
+
+    debug("Running code generation...\n\t$ {}".format(" ".join(args)))
+    subprocess.check_output(args, cwd=output_dir)
+
+    debug("Applying headers, removing unnecessary files and renaming...")
+    # Handle case insensitive file systems. If the files are already
+    # generated, they will be written to latex* but LaTeX*.* won't match them.
+    for path in (glob.glob(os.path.join(output_dir, "LaTeX*.*")) or
+        glob.glob(os.path.join(output_dir, "latex*.*"))):
+
+        # Remove files ending in .interp or .tokens as they are not needed.
+        if not path.endswith(".py"):
+            os.unlink(path)
+            continue
+
+        new_path = os.path.join(output_dir, os.path.basename(path).lower())
+        with open(path, 'r') as f:
+            lines = [line.rstrip() + '\n' for line in f]
+
+        os.unlink(path)
+
+        with open(new_path, "w") as out_file:
+            offset = 0
+            while lines[offset].startswith('#'):
+                offset += 1
+            out_file.write(header)
+            out_file.writelines(lines[offset:])
+
+        debug("\t{}".format(new_path))
+
+    return True
+
+
+if __name__ == "__main__":
+    build_parser()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/_parse_latex_antlr.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/_parse_latex_antlr.py
new file mode 100644
index 0000000000000000000000000000000000000000..26604375b3a9622f8c1dacdb1d678d09c2c3ad41
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/_parse_latex_antlr.py
@@ -0,0 +1,607 @@
+# Ported from latex2sympy by @augustt198
+# https://github.com/augustt198/latex2sympy
+# See license in LICENSE.txt
+from importlib.metadata import version
+import sympy
+from sympy.external import import_module
+from sympy.printing.str import StrPrinter
+from sympy.physics.quantum.state import Bra, Ket
+
+from .errors import LaTeXParsingError
+
+
+LaTeXParser = LaTeXLexer = MathErrorListener = None
+
+try:
+    LaTeXParser = import_module('sympy.parsing.latex._antlr.latexparser',
+                                import_kwargs={'fromlist': ['LaTeXParser']}).LaTeXParser
+    LaTeXLexer = import_module('sympy.parsing.latex._antlr.latexlexer',
+                               import_kwargs={'fromlist': ['LaTeXLexer']}).LaTeXLexer
+except Exception:
+    pass
+
+ErrorListener = import_module('antlr4.error.ErrorListener',
+                              warn_not_installed=True,
+                              import_kwargs={'fromlist': ['ErrorListener']}
+                              )
+
+
+
+if ErrorListener:
+    class MathErrorListener(ErrorListener.ErrorListener):  # type:ignore # noqa:F811
+        def __init__(self, src):
+            super(ErrorListener.ErrorListener, self).__init__()
+            self.src = src
+
+        def syntaxError(self, recog, symbol, line, col, msg, e):
+            fmt = "%s\n%s\n%s"
+            marker = "~" * col + "^"
+
+            if msg.startswith("missing"):
+                err = fmt % (msg, self.src, marker)
+            elif msg.startswith("no viable"):
+                err = fmt % ("I expected something else here", self.src, marker)
+            elif msg.startswith("mismatched"):
+                names = LaTeXParser.literalNames
+                expected = [
+                    names[i] for i in e.getExpectedTokens() if i < len(names)
+                ]
+                if len(expected) < 10:
+                    expected = " ".join(expected)
+                    err = (fmt % ("I expected one of these: " + expected, self.src,
+                                  marker))
+                else:
+                    err = (fmt % ("I expected something else here", self.src,
+                                  marker))
+            else:
+                err = fmt % ("I don't understand this", self.src, marker)
+            raise LaTeXParsingError(err)
+
+
+def parse_latex(sympy, strict=False):
+    antlr4 = import_module('antlr4')
+
+    if None in [antlr4, MathErrorListener] or \
+            not version('antlr4-python3-runtime').startswith('4.11'):
+        raise ImportError("LaTeX parsing requires the antlr4 Python package,"
+                          " provided by pip (antlr4-python3-runtime) or"
+                          " conda (antlr-python-runtime), version 4.11")
+
+    sympy = sympy.strip()
+    matherror = MathErrorListener(sympy)
+
+    stream = antlr4.InputStream(sympy)
+    lex = LaTeXLexer(stream)
+    lex.removeErrorListeners()
+    lex.addErrorListener(matherror)
+
+    tokens = antlr4.CommonTokenStream(lex)
+    parser = LaTeXParser(tokens)
+
+    # remove default console error listener
+    parser.removeErrorListeners()
+    parser.addErrorListener(matherror)
+
+    relation = parser.math().relation()
+    if strict and (relation.start.start != 0 or relation.stop.stop != len(sympy) - 1):
+        raise LaTeXParsingError("Invalid LaTeX")
+    expr = convert_relation(relation)
+
+    return expr
+
+
+def convert_relation(rel):
+    if rel.expr():
+        return convert_expr(rel.expr())
+
+    lh = convert_relation(rel.relation(0))
+    rh = convert_relation(rel.relation(1))
+    if rel.LT():
+        return sympy.StrictLessThan(lh, rh)
+    elif rel.LTE():
+        return sympy.LessThan(lh, rh)
+    elif rel.GT():
+        return sympy.StrictGreaterThan(lh, rh)
+    elif rel.GTE():
+        return sympy.GreaterThan(lh, rh)
+    elif rel.EQUAL():
+        return sympy.Eq(lh, rh)
+    elif rel.NEQ():
+        return sympy.Ne(lh, rh)
+
+
+def convert_expr(expr):
+    return convert_add(expr.additive())
+
+
+def convert_add(add):
+    if add.ADD():
+        lh = convert_add(add.additive(0))
+        rh = convert_add(add.additive(1))
+        return sympy.Add(lh, rh, evaluate=False)
+    elif add.SUB():
+        lh = convert_add(add.additive(0))
+        rh = convert_add(add.additive(1))
+        if hasattr(rh, "is_Atom") and rh.is_Atom:
+            return sympy.Add(lh, -1 * rh, evaluate=False)
+        return sympy.Add(lh, sympy.Mul(-1, rh, evaluate=False), evaluate=False)
+    else:
+        return convert_mp(add.mp())
+
+
+def convert_mp(mp):
+    if hasattr(mp, 'mp'):
+        mp_left = mp.mp(0)
+        mp_right = mp.mp(1)
+    else:
+        mp_left = mp.mp_nofunc(0)
+        mp_right = mp.mp_nofunc(1)
+
+    if mp.MUL() or mp.CMD_TIMES() or mp.CMD_CDOT():
+        lh = convert_mp(mp_left)
+        rh = convert_mp(mp_right)
+        return sympy.Mul(lh, rh, evaluate=False)
+    elif mp.DIV() or mp.CMD_DIV() or mp.COLON():
+        lh = convert_mp(mp_left)
+        rh = convert_mp(mp_right)
+        return sympy.Mul(lh, sympy.Pow(rh, -1, evaluate=False), evaluate=False)
+    else:
+        if hasattr(mp, 'unary'):
+            return convert_unary(mp.unary())
+        else:
+            return convert_unary(mp.unary_nofunc())
+
+
+def convert_unary(unary):
+    if hasattr(unary, 'unary'):
+        nested_unary = unary.unary()
+    else:
+        nested_unary = unary.unary_nofunc()
+    if hasattr(unary, 'postfix_nofunc'):
+        first = unary.postfix()
+        tail = unary.postfix_nofunc()
+        postfix = [first] + tail
+    else:
+        postfix = unary.postfix()
+
+    if unary.ADD():
+        return convert_unary(nested_unary)
+    elif unary.SUB():
+        numabs = convert_unary(nested_unary)
+        # Use Integer(-n) instead of Mul(-1, n)
+        return -numabs
+    elif postfix:
+        return convert_postfix_list(postfix)
+
+
+def convert_postfix_list(arr, i=0):
+    if i >= len(arr):
+        raise LaTeXParsingError("Index out of bounds")
+
+    res = convert_postfix(arr[i])
+    if isinstance(res, sympy.Expr):
+        if i == len(arr) - 1:
+            return res  # nothing to multiply by
+        else:
+            if i > 0:
+                left = convert_postfix(arr[i - 1])
+                right = convert_postfix(arr[i + 1])
+                if isinstance(left, sympy.Expr) and isinstance(
+                        right, sympy.Expr):
+                    left_syms = convert_postfix(arr[i - 1]).atoms(sympy.Symbol)
+                    right_syms = convert_postfix(arr[i + 1]).atoms(
+                        sympy.Symbol)
+                    # if the left and right sides contain no variables and the
+                    # symbol in between is 'x', treat as multiplication.
+                    if not (left_syms or right_syms) and str(res) == 'x':
+                        return convert_postfix_list(arr, i + 1)
+            # multiply by next
+            return sympy.Mul(
+                res, convert_postfix_list(arr, i + 1), evaluate=False)
+    else:  # must be derivative
+        wrt = res[0]
+        if i == len(arr) - 1:
+            raise LaTeXParsingError("Expected expression for derivative")
+        else:
+            expr = convert_postfix_list(arr, i + 1)
+            return sympy.Derivative(expr, wrt)
+
+
+def do_subs(expr, at):
+    if at.expr():
+        at_expr = convert_expr(at.expr())
+        syms = at_expr.atoms(sympy.Symbol)
+        if len(syms) == 0:
+            return expr
+        elif len(syms) > 0:
+            sym = next(iter(syms))
+            return expr.subs(sym, at_expr)
+    elif at.equality():
+        lh = convert_expr(at.equality().expr(0))
+        rh = convert_expr(at.equality().expr(1))
+        return expr.subs(lh, rh)
+
+
+def convert_postfix(postfix):
+    if hasattr(postfix, 'exp'):
+        exp_nested = postfix.exp()
+    else:
+        exp_nested = postfix.exp_nofunc()
+
+    exp = convert_exp(exp_nested)
+    for op in postfix.postfix_op():
+        if op.BANG():
+            if isinstance(exp, list):
+                raise LaTeXParsingError("Cannot apply postfix to derivative")
+            exp = sympy.factorial(exp, evaluate=False)
+        elif op.eval_at():
+            ev = op.eval_at()
+            at_b = None
+            at_a = None
+            if ev.eval_at_sup():
+                at_b = do_subs(exp, ev.eval_at_sup())
+            if ev.eval_at_sub():
+                at_a = do_subs(exp, ev.eval_at_sub())
+            if at_b is not None and at_a is not None:
+                exp = sympy.Add(at_b, -1 * at_a, evaluate=False)
+            elif at_b is not None:
+                exp = at_b
+            elif at_a is not None:
+                exp = at_a
+
+    return exp
+
+
+def convert_exp(exp):
+    if hasattr(exp, 'exp'):
+        exp_nested = exp.exp()
+    else:
+        exp_nested = exp.exp_nofunc()
+
+    if exp_nested:
+        base = convert_exp(exp_nested)
+        if isinstance(base, list):
+            raise LaTeXParsingError("Cannot raise derivative to power")
+        if exp.atom():
+            exponent = convert_atom(exp.atom())
+        elif exp.expr():
+            exponent = convert_expr(exp.expr())
+        return sympy.Pow(base, exponent, evaluate=False)
+    else:
+        if hasattr(exp, 'comp'):
+            return convert_comp(exp.comp())
+        else:
+            return convert_comp(exp.comp_nofunc())
+
+
+def convert_comp(comp):
+    if comp.group():
+        return convert_expr(comp.group().expr())
+    elif comp.abs_group():
+        return sympy.Abs(convert_expr(comp.abs_group().expr()), evaluate=False)
+    elif comp.atom():
+        return convert_atom(comp.atom())
+    elif comp.floor():
+        return convert_floor(comp.floor())
+    elif comp.ceil():
+        return convert_ceil(comp.ceil())
+    elif comp.func():
+        return convert_func(comp.func())
+
+
+def convert_atom(atom):
+    if atom.LETTER():
+        sname = atom.LETTER().getText()
+        if atom.subexpr():
+            if atom.subexpr().expr():  # subscript is expr
+                subscript = convert_expr(atom.subexpr().expr())
+            else:  # subscript is atom
+                subscript = convert_atom(atom.subexpr().atom())
+            sname += '_{' + StrPrinter().doprint(subscript) + '}'
+        if atom.SINGLE_QUOTES():
+            sname += atom.SINGLE_QUOTES().getText()  # put after subscript for easy identify
+        return sympy.Symbol(sname)
+    elif atom.SYMBOL():
+        s = atom.SYMBOL().getText()[1:]
+        if s == "infty":
+            return sympy.oo
+        else:
+            if atom.subexpr():
+                subscript = None
+                if atom.subexpr().expr():  # subscript is expr
+                    subscript = convert_expr(atom.subexpr().expr())
+                else:  # subscript is atom
+                    subscript = convert_atom(atom.subexpr().atom())
+                subscriptName = StrPrinter().doprint(subscript)
+                s += '_{' + subscriptName + '}'
+            return sympy.Symbol(s)
+    elif atom.number():
+        s = atom.number().getText().replace(",", "")
+        return sympy.Number(s)
+    elif atom.DIFFERENTIAL():
+        var = get_differential_var(atom.DIFFERENTIAL())
+        return sympy.Symbol('d' + var.name)
+    elif atom.mathit():
+        text = rule2text(atom.mathit().mathit_text())
+        return sympy.Symbol(text)
+    elif atom.frac():
+        return convert_frac(atom.frac())
+    elif atom.binom():
+        return convert_binom(atom.binom())
+    elif atom.bra():
+        val = convert_expr(atom.bra().expr())
+        return Bra(val)
+    elif atom.ket():
+        val = convert_expr(atom.ket().expr())
+        return Ket(val)
+
+
+def rule2text(ctx):
+    stream = ctx.start.getInputStream()
+    # starting index of starting token
+    startIdx = ctx.start.start
+    # stopping index of stopping token
+    stopIdx = ctx.stop.stop
+
+    return stream.getText(startIdx, stopIdx)
+
+
+def convert_frac(frac):
+    diff_op = False
+    partial_op = False
+    if frac.lower and frac.upper:
+        lower_itv = frac.lower.getSourceInterval()
+        lower_itv_len = lower_itv[1] - lower_itv[0] + 1
+        if (frac.lower.start == frac.lower.stop
+                and frac.lower.start.type == LaTeXLexer.DIFFERENTIAL):
+            wrt = get_differential_var_str(frac.lower.start.text)
+            diff_op = True
+        elif (lower_itv_len == 2 and frac.lower.start.type == LaTeXLexer.SYMBOL
+              and frac.lower.start.text == '\\partial'
+              and (frac.lower.stop.type == LaTeXLexer.LETTER
+                   or frac.lower.stop.type == LaTeXLexer.SYMBOL)):
+            partial_op = True
+            wrt = frac.lower.stop.text
+            if frac.lower.stop.type == LaTeXLexer.SYMBOL:
+                wrt = wrt[1:]
+
+        if diff_op or partial_op:
+            wrt = sympy.Symbol(wrt)
+            if (diff_op and frac.upper.start == frac.upper.stop
+                    and frac.upper.start.type == LaTeXLexer.LETTER
+                    and frac.upper.start.text == 'd'):
+                return [wrt]
+            elif (partial_op and frac.upper.start == frac.upper.stop
+                  and frac.upper.start.type == LaTeXLexer.SYMBOL
+                  and frac.upper.start.text == '\\partial'):
+                return [wrt]
+            upper_text = rule2text(frac.upper)
+
+            expr_top = None
+            if diff_op and upper_text.startswith('d'):
+                expr_top = parse_latex(upper_text[1:])
+            elif partial_op and frac.upper.start.text == '\\partial':
+                expr_top = parse_latex(upper_text[len('\\partial'):])
+            if expr_top:
+                return sympy.Derivative(expr_top, wrt)
+    if frac.upper:
+        expr_top = convert_expr(frac.upper)
+    else:
+        expr_top = sympy.Number(frac.upperd.text)
+    if frac.lower:
+        expr_bot = convert_expr(frac.lower)
+    else:
+        expr_bot = sympy.Number(frac.lowerd.text)
+    inverse_denom = sympy.Pow(expr_bot, -1, evaluate=False)
+    if expr_top == 1:
+        return inverse_denom
+    else:
+        return sympy.Mul(expr_top, inverse_denom, evaluate=False)
+
+def convert_binom(binom):
+    expr_n = convert_expr(binom.n)
+    expr_k = convert_expr(binom.k)
+    return sympy.binomial(expr_n, expr_k, evaluate=False)
+
+def convert_floor(floor):
+    val = convert_expr(floor.val)
+    return sympy.floor(val, evaluate=False)
+
+def convert_ceil(ceil):
+    val = convert_expr(ceil.val)
+    return sympy.ceiling(val, evaluate=False)
+
+def convert_func(func):
+    if func.func_normal():
+        if func.L_PAREN():  # function called with parenthesis
+            arg = convert_func_arg(func.func_arg())
+        else:
+            arg = convert_func_arg(func.func_arg_noparens())
+
+        name = func.func_normal().start.text[1:]
+
+        # change arc -> a
+        if name in [
+                "arcsin", "arccos", "arctan", "arccsc", "arcsec", "arccot"
+        ]:
+            name = "a" + name[3:]
+            expr = getattr(sympy.functions, name)(arg, evaluate=False)
+        if name in ["arsinh", "arcosh", "artanh"]:
+            name = "a" + name[2:]
+            expr = getattr(sympy.functions, name)(arg, evaluate=False)
+
+        if name == "exp":
+            expr = sympy.exp(arg, evaluate=False)
+
+        if name in ("log", "lg", "ln"):
+            if func.subexpr():
+                if func.subexpr().expr():
+                    base = convert_expr(func.subexpr().expr())
+                else:
+                    base = convert_atom(func.subexpr().atom())
+            elif name == "lg":  # ISO 80000-2:2019
+                base = 10
+            elif name in ("ln", "log"):  # SymPy's latex printer prints ln as log by default
+                base = sympy.E
+            expr = sympy.log(arg, base, evaluate=False)
+
+        func_pow = None
+        should_pow = True
+        if func.supexpr():
+            if func.supexpr().expr():
+                func_pow = convert_expr(func.supexpr().expr())
+            else:
+                func_pow = convert_atom(func.supexpr().atom())
+
+        if name in [
+                "sin", "cos", "tan", "csc", "sec", "cot", "sinh", "cosh",
+                "tanh"
+        ]:
+            if func_pow == -1:
+                name = "a" + name
+                should_pow = False
+            expr = getattr(sympy.functions, name)(arg, evaluate=False)
+
+        if func_pow and should_pow:
+            expr = sympy.Pow(expr, func_pow, evaluate=False)
+
+        return expr
+    elif func.LETTER() or func.SYMBOL():
+        if func.LETTER():
+            fname = func.LETTER().getText()
+        elif func.SYMBOL():
+            fname = func.SYMBOL().getText()[1:]
+        fname = str(fname)  # can't be unicode
+        if func.subexpr():
+            if func.subexpr().expr():  # subscript is expr
+                subscript = convert_expr(func.subexpr().expr())
+            else:  # subscript is atom
+                subscript = convert_atom(func.subexpr().atom())
+            subscriptName = StrPrinter().doprint(subscript)
+            fname += '_{' + subscriptName + '}'
+        if func.SINGLE_QUOTES():
+            fname += func.SINGLE_QUOTES().getText()
+        input_args = func.args()
+        output_args = []
+        while input_args.args():  # handle multiple arguments to function
+            output_args.append(convert_expr(input_args.expr()))
+            input_args = input_args.args()
+        output_args.append(convert_expr(input_args.expr()))
+        return sympy.Function(fname)(*output_args)
+    elif func.FUNC_INT():
+        return handle_integral(func)
+    elif func.FUNC_SQRT():
+        expr = convert_expr(func.base)
+        if func.root:
+            r = convert_expr(func.root)
+            return sympy.root(expr, r, evaluate=False)
+        else:
+            return sympy.sqrt(expr, evaluate=False)
+    elif func.FUNC_OVERLINE():
+        expr = convert_expr(func.base)
+        return sympy.conjugate(expr, evaluate=False)
+    elif func.FUNC_SUM():
+        return handle_sum_or_prod(func, "summation")
+    elif func.FUNC_PROD():
+        return handle_sum_or_prod(func, "product")
+    elif func.FUNC_LIM():
+        return handle_limit(func)
+
+
+def convert_func_arg(arg):
+    if hasattr(arg, 'expr'):
+        return convert_expr(arg.expr())
+    else:
+        return convert_mp(arg.mp_nofunc())
+
+
+def handle_integral(func):
+    if func.additive():
+        integrand = convert_add(func.additive())
+    elif func.frac():
+        integrand = convert_frac(func.frac())
+    else:
+        integrand = 1
+
+    int_var = None
+    if func.DIFFERENTIAL():
+        int_var = get_differential_var(func.DIFFERENTIAL())
+    else:
+        for sym in integrand.atoms(sympy.Symbol):
+            s = str(sym)
+            if len(s) > 1 and s[0] == 'd':
+                if s[1] == '\\':
+                    int_var = sympy.Symbol(s[2:])
+                else:
+                    int_var = sympy.Symbol(s[1:])
+                int_sym = sym
+        if int_var:
+            integrand = integrand.subs(int_sym, 1)
+        else:
+            # Assume dx by default
+            int_var = sympy.Symbol('x')
+
+    if func.subexpr():
+        if func.subexpr().atom():
+            lower = convert_atom(func.subexpr().atom())
+        else:
+            lower = convert_expr(func.subexpr().expr())
+        if func.supexpr().atom():
+            upper = convert_atom(func.supexpr().atom())
+        else:
+            upper = convert_expr(func.supexpr().expr())
+        return sympy.Integral(integrand, (int_var, lower, upper))
+    else:
+        return sympy.Integral(integrand, int_var)
+
+
+def handle_sum_or_prod(func, name):
+    val = convert_mp(func.mp())
+    iter_var = convert_expr(func.subeq().equality().expr(0))
+    start = convert_expr(func.subeq().equality().expr(1))
+    if func.supexpr().expr():  # ^{expr}
+        end = convert_expr(func.supexpr().expr())
+    else:  # ^atom
+        end = convert_atom(func.supexpr().atom())
+
+    if name == "summation":
+        return sympy.Sum(val, (iter_var, start, end))
+    elif name == "product":
+        return sympy.Product(val, (iter_var, start, end))
+
+
+def handle_limit(func):
+    sub = func.limit_sub()
+    if sub.LETTER():
+        var = sympy.Symbol(sub.LETTER().getText())
+    elif sub.SYMBOL():
+        var = sympy.Symbol(sub.SYMBOL().getText()[1:])
+    else:
+        var = sympy.Symbol('x')
+    if sub.SUB():
+        direction = "-"
+    elif sub.ADD():
+        direction = "+"
+    else:
+        direction = "+-"
+    approaching = convert_expr(sub.expr())
+    content = convert_mp(func.mp())
+
+    return sympy.Limit(content, var, approaching, direction)
+
+
+def get_differential_var(d):
+    text = get_differential_var_str(d.getText())
+    return sympy.Symbol(text)
+
+
+def get_differential_var_str(text):
+    for i in range(1, len(text)):
+        c = text[i]
+        if not (c == " " or c == "\r" or c == "\n" or c == "\t"):
+            idx = i
+            break
+    text = text[idx:]
+    if text[0] == "\\":
+        text = text[1:]
+    return text
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/errors.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/errors.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8c3ef9f06279df42d4b2054acc4cfe39b6682a5
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/errors.py
@@ -0,0 +1,2 @@
+class LaTeXParsingError(Exception):
+    pass
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/lark/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/lark/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..92e58d3172e100cc376d0b416b3835d164bd5647
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/lark/__init__.py
@@ -0,0 +1,2 @@
+from .latex_parser import parse_latex_lark, LarkLaTeXParser # noqa
+from .transformer import TransformToSymPyExpr # noqa
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/lark/grammar/greek_symbols.lark b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/lark/grammar/greek_symbols.lark
new file mode 100644
index 0000000000000000000000000000000000000000..7439fab9dcac284dc3c9b5fbfa4fc6db8b29dfd2
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/lark/grammar/greek_symbols.lark
@@ -0,0 +1,28 @@
+// Greek symbols
+// TODO: Shouold we include the uppercase variants for the symbols where the uppercase variant doesn't have a separate meaning?
+ALPHA: "\\alpha"
+BETA: "\\beta"
+GAMMA: "\\gamma"
+DELTA: "\\delta" // TODO: Should this be included? Delta usually denotes other things.
+EPSILON: "\\epsilon" |  "\\varepsilon"
+ZETA: "\\zeta"
+ETA: "\\eta"
+THETA: "\\theta" | "\\vartheta"
+// TODO: Should I add iota to the list?
+KAPPA: "\\kappa"
+LAMBDA: "\\lambda" // TODO: What about the uppercase variant?
+MU: "\\mu"
+NU: "\\nu"
+XI: "\\xi"
+// TODO: Should there be a separate note for transforming \pi into sympy.pi?
+RHO: "\\rho" | "\\varrho"
+// TODO: What should we do about sigma?
+TAU: "\\tau"
+UPSILON: "\\upsilon"
+PHI: "\\phi" | "\\varphi"
+CHI: "\\chi"
+PSI: "\\psi"
+OMEGA: "\\omega"
+
+GREEK_SYMBOL: ALPHA | BETA | GAMMA | DELTA | EPSILON | ZETA | ETA | THETA | KAPPA
+    | LAMBDA | MU | NU | XI | RHO | TAU | UPSILON | PHI | CHI | PSI | OMEGA
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/lark/grammar/latex.lark b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/lark/grammar/latex.lark
new file mode 100644
index 0000000000000000000000000000000000000000..43e8d0e9105fa4da9bcdd2c0fa6111f6d523c9a9
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/lark/grammar/latex.lark
@@ -0,0 +1,403 @@
+%ignore /[ \t\n\r]+/
+
+%ignore "\\," | "\\thinspace" | "\\:" | "\\medspace" | "\\;" | "\\thickspace"
+%ignore "\\quad" | "\\qquad"
+%ignore "\\!" | "\\negthinspace" | "\\negmedspace" | "\\negthickspace"
+%ignore "\\vrule" | "\\vcenter" | "\\vbox" | "\\vskip" | "\\vspace" | "\\hfill"
+%ignore "\\*" | "\\-" | "\\." | "\\/" | "\\(" | "\\="
+
+%ignore "\\left" | "\\right"
+%ignore "\\limits" | "\\nolimits"
+%ignore "\\displaystyle"
+
+///////////////////// tokens ///////////////////////
+
+// basic binary operators
+ADD: "+"
+SUB: "-"
+MUL: "*"
+DIV: "/"
+
+// tokens with distinct left and right symbols
+L_BRACE: "{"
+R_BRACE: "}"
+L_BRACE_LITERAL: "\\{"
+R_BRACE_LITERAL: "\\}"
+L_BRACKET: "["
+R_BRACKET: "]"
+L_CEIL: "\\lceil"
+R_CEIL: "\\rceil"
+L_FLOOR: "\\lfloor"
+R_FLOOR: "\\rfloor"
+L_PAREN: "("
+R_PAREN: ")"
+
+// limit, integral, sum, and product symbols
+FUNC_LIM:  "\\lim"
+LIM_APPROACH_SYM: "\\to" | "\\rightarrow" | "\\Rightarrow" | "\\longrightarrow" | "\\Longrightarrow"
+FUNC_INT:  "\\int" | "\\intop"
+FUNC_SUM:  "\\sum"
+FUNC_PROD: "\\prod"
+
+// common functions
+FUNC_EXP:  "\\exp"
+FUNC_LOG:  "\\log"
+FUNC_LN:   "\\ln"
+FUNC_LG:   "\\lg"
+FUNC_MIN: "\\min"
+FUNC_MAX: "\\max"
+
+// trigonometric functions
+FUNC_SIN:  "\\sin"
+FUNC_COS:  "\\cos"
+FUNC_TAN:  "\\tan"
+FUNC_CSC:  "\\csc"
+FUNC_SEC:  "\\sec"
+FUNC_COT:  "\\cot"
+
+// inverse trigonometric functions
+FUNC_ARCSIN: "\\arcsin"
+FUNC_ARCCOS: "\\arccos"
+FUNC_ARCTAN: "\\arctan"
+FUNC_ARCCSC: "\\arccsc"
+FUNC_ARCSEC: "\\arcsec"
+FUNC_ARCCOT: "\\arccot"
+
+// hyperbolic trigonometric functions
+FUNC_SINH: "\\sinh"
+FUNC_COSH: "\\cosh"
+FUNC_TANH: "\\tanh"
+FUNC_ARSINH: "\\arsinh"
+FUNC_ARCOSH: "\\arcosh"
+FUNC_ARTANH: "\\artanh"
+
+FUNC_SQRT: "\\sqrt"
+
+// miscellaneous symbols
+CMD_TIMES: "\\times"
+CMD_CDOT:  "\\cdot"
+CMD_DIV:   "\\div"
+CMD_FRAC:  "\\frac" | "\\dfrac" | "\\tfrac" | "\\nicefrac"
+CMD_BINOM: "\\binom" | "\\dbinom" | "\\tbinom"
+CMD_OVERLINE: "\\overline"
+CMD_LANGLE: "\\langle"
+CMD_RANGLE: "\\rangle"
+
+CMD_MATHIT: "\\mathit"
+
+CMD_INFTY: "\\infty"
+
+BANG: "!"
+BAR: "|"
+CARET: "^"
+COLON: ":"
+UNDERSCORE: "_"
+
+// relational symbols
+EQUAL: "="
+NOT_EQUAL: "\\neq" | "\\ne"
+LT: "<"
+LTE: "\\leq" | "\\le" | "\\leqslant"
+GT: ">"
+GTE: "\\geq" | "\\ge" | "\\geqslant"
+
+DIV_SYMBOL: CMD_DIV | DIV
+MUL_SYMBOL: MUL | CMD_TIMES | CMD_CDOT
+
+%import .greek_symbols.GREEK_SYMBOL
+
+UPRIGHT_DIFFERENTIAL_SYMBOL: "\\text{d}" | "\\mathrm{d}"
+DIFFERENTIAL_SYMBOL: "d" | UPRIGHT_DIFFERENTIAL_SYMBOL
+
+// disallow "d" as a variable name because we want to parse "d" as a differential symbol.
+SYMBOL: /[a-zA-Z]'*/
+GREEK_SYMBOL_WITH_PRIMES: GREEK_SYMBOL "'"*
+LATIN_SYMBOL_WITH_LATIN_SUBSCRIPT: /([a-zA-Z]'*)_(([A-Za-z0-9]|[a-zA-Z]+)|\{([A-Za-z0-9]|[a-zA-Z]+'*)\})/
+LATIN_SYMBOL_WITH_GREEK_SUBSCRIPT: /([a-zA-Z]'*)_/ GREEK_SYMBOL | /([a-zA-Z]'*)_/ L_BRACE GREEK_SYMBOL_WITH_PRIMES R_BRACE
+// best to define the variant with braces like that instead of shoving it all into one case like in
+// /([a-zA-Z])_/ L_BRACE? GREEK_SYMBOL R_BRACE? because then we can easily error out on input like
+// r"h_{\theta"
+GREEK_SYMBOL_WITH_LATIN_SUBSCRIPT: GREEK_SYMBOL_WITH_PRIMES /_(([A-Za-z0-9]|[a-zA-Z]+)|\{([A-Za-z0-9]|[a-zA-Z]+'*)\})/
+GREEK_SYMBOL_WITH_GREEK_SUBSCRIPT: GREEK_SYMBOL_WITH_PRIMES /_/ (GREEK_SYMBOL | L_BRACE GREEK_SYMBOL_WITH_PRIMES R_BRACE)
+MULTI_LETTER_SYMBOL: /[a-zA-Z]+(\s+[a-zA-Z]+)*'*/
+
+%import common.DIGIT -> DIGIT
+
+CMD_PRIME: "\\prime"
+CMD_ASTERISK: "\\ast"
+
+PRIMES: "'"+
+STARS: "*"+
+PRIMES_VIA_CMD: CMD_PRIME+
+STARS_VIA_CMD: CMD_ASTERISK+
+
+CMD_IMAGINARY_UNIT: "\\imaginaryunit"
+
+CMD_BEGIN: "\\begin"
+CMD_END: "\\end"
+
+// matrices
+IGNORE_L: /[ \t\n\r]*/ L_BRACE* /[ \t\n\r]*/
+IGNORE_R: /[ \t\n\r]*/ R_BRACE* /[ \t\n\r]*/
+ARRAY_MATRIX_BEGIN: L_BRACE "array" R_BRACE L_BRACE /[^}]*/ R_BRACE
+ARRAY_MATRIX_END: L_BRACE "array" R_BRACE
+AMSMATH_MATRIX: L_BRACE "matrix" R_BRACE
+AMSMATH_PMATRIX: L_BRACE "pmatrix" R_BRACE
+AMSMATH_BMATRIX: L_BRACE "bmatrix" R_BRACE
+// Without the (L|R)_PARENs and (L|R)_BRACKETs, a matrix defined using
+// \begin{array}...\end{array} or \begin{matrix}...\end{matrix} must
+// not qualify as a complete matrix expression; this is done so that
+// if we have \begin{array}...\end{array} or \begin{matrix}...\end{matrix}
+// between BAR pairs, then they should be interpreted as determinants as
+// opposed to sympy.Abs (absolute value) applied to a matrix.
+CMD_BEGIN_AMSPMATRIX_AMSBMATRIX: CMD_BEGIN (AMSMATH_PMATRIX | AMSMATH_BMATRIX)
+CMD_BEGIN_ARRAY_AMSMATRIX: (L_PAREN | L_BRACKET) IGNORE_L CMD_BEGIN (ARRAY_MATRIX_BEGIN | AMSMATH_MATRIX)
+CMD_MATRIX_BEGIN: CMD_BEGIN_AMSPMATRIX_AMSBMATRIX | CMD_BEGIN_ARRAY_AMSMATRIX
+CMD_END_AMSPMATRIX_AMSBMATRIX: CMD_END (AMSMATH_PMATRIX | AMSMATH_BMATRIX)
+CMD_END_ARRAY_AMSMATRIX: CMD_END (ARRAY_MATRIX_END | AMSMATH_MATRIX) IGNORE_R "\\right"? (R_PAREN | R_BRACKET)
+CMD_MATRIX_END: CMD_END_AMSPMATRIX_AMSBMATRIX | CMD_END_ARRAY_AMSMATRIX
+MATRIX_COL_DELIM: "&"
+MATRIX_ROW_DELIM: "\\\\"
+FUNC_MATRIX_TRACE: "\\trace"
+FUNC_MATRIX_ADJUGATE: "\\adjugate"
+
+// determinants
+AMSMATH_VMATRIX: L_BRACE "vmatrix" R_BRACE
+CMD_DETERMINANT_BEGIN_SIMPLE: CMD_BEGIN AMSMATH_VMATRIX
+CMD_DETERMINANT_BEGIN_VARIANT: BAR IGNORE_L CMD_BEGIN (ARRAY_MATRIX_BEGIN | AMSMATH_MATRIX)
+CMD_DETERMINANT_BEGIN: CMD_DETERMINANT_BEGIN_SIMPLE | CMD_DETERMINANT_BEGIN_VARIANT
+CMD_DETERMINANT_END_SIMPLE: CMD_END AMSMATH_VMATRIX
+CMD_DETERMINANT_END_VARIANT: CMD_END (ARRAY_MATRIX_END | AMSMATH_MATRIX) IGNORE_R "\\right"? BAR
+CMD_DETERMINANT_END: CMD_DETERMINANT_END_SIMPLE | CMD_DETERMINANT_END_VARIANT
+FUNC_DETERMINANT: "\\det"
+
+//////////////////// grammar //////////////////////
+
+latex_string: _relation | _expression
+
+_one_letter_symbol: SYMBOL
+    | LATIN_SYMBOL_WITH_LATIN_SUBSCRIPT
+    | LATIN_SYMBOL_WITH_GREEK_SUBSCRIPT
+    | GREEK_SYMBOL_WITH_LATIN_SUBSCRIPT
+    | GREEK_SYMBOL_WITH_GREEK_SUBSCRIPT
+    | GREEK_SYMBOL_WITH_PRIMES
+// LuaTeX-generated outputs of \mathit{foo'} and \mathit{foo}'
+// seem to be the same on the surface. We allow both styles.
+multi_letter_symbol: CMD_MATHIT L_BRACE MULTI_LETTER_SYMBOL R_BRACE
+    | CMD_MATHIT L_BRACE MULTI_LETTER_SYMBOL R_BRACE /'+/
+number: /\d+(\.\d*)?/ | CMD_IMAGINARY_UNIT
+
+_atomic_expr: _one_letter_symbol
+    | multi_letter_symbol
+    | number
+    | CMD_INFTY
+
+group_round_parentheses: L_PAREN _expression R_PAREN
+group_square_brackets: L_BRACKET _expression R_BRACKET
+group_curly_parentheses: L_BRACE _expression R_BRACE
+
+_relation: eq | ne | lt | lte | gt | gte
+
+eq: _expression EQUAL _expression
+ne: _expression NOT_EQUAL _expression
+lt: _expression LT _expression
+lte: _expression LTE _expression
+gt: _expression GT _expression
+gte: _expression GTE _expression
+
+_expression_core: _atomic_expr | group_curly_parentheses
+
+add: _expression ADD _expression_mul
+    | ADD _expression_mul
+sub: _expression SUB _expression_mul
+    | SUB _expression_mul
+mul: _expression_mul MUL_SYMBOL _expression_power
+div: _expression_mul DIV_SYMBOL _expression_power
+
+adjacent_expressions: (_one_letter_symbol | number) _expression_mul
+    | group_round_parentheses (group_round_parentheses | _one_letter_symbol)
+    | _function _function
+    | fraction _expression_mul
+
+_expression_func: _expression_core
+    | group_round_parentheses
+    | fraction
+    | binomial
+    | _function
+    | _integral// | derivative
+    | limit
+    | matrix
+
+_expression_power: _expression_func | superscript | matrix_prime | symbol_prime
+
+_expression_mul: _expression_power
+    | mul | div | adjacent_expressions
+    | summation | product
+
+_expression: _expression_mul | add | sub
+
+_limit_dir: "+" | "-" | L_BRACE ("+" | "-") R_BRACE
+
+limit_dir_expr: _expression CARET _limit_dir
+
+group_curly_parentheses_lim: L_BRACE _expression LIM_APPROACH_SYM (limit_dir_expr | _expression) R_BRACE
+
+limit: FUNC_LIM UNDERSCORE group_curly_parentheses_lim _expression
+
+differential: DIFFERENTIAL_SYMBOL _one_letter_symbol
+
+//_derivative_operator: CMD_FRAC L_BRACE DIFFERENTIAL_SYMBOL R_BRACE L_BRACE differential R_BRACE
+
+//derivative: _derivative_operator _expression
+
+_integral: normal_integral | integral_with_special_fraction
+
+normal_integral: FUNC_INT _expression DIFFERENTIAL_SYMBOL _one_letter_symbol
+    | FUNC_INT (CARET _expression_core UNDERSCORE _expression_core)? _expression? DIFFERENTIAL_SYMBOL _one_letter_symbol
+    | FUNC_INT (UNDERSCORE _expression_core CARET _expression_core)? _expression? DIFFERENTIAL_SYMBOL _one_letter_symbol
+
+group_curly_parentheses_int: L_BRACE _expression? differential R_BRACE
+
+special_fraction: CMD_FRAC group_curly_parentheses_int group_curly_parentheses
+
+integral_with_special_fraction: FUNC_INT special_fraction
+    | FUNC_INT (CARET _expression_core UNDERSCORE _expression_core)? special_fraction
+    | FUNC_INT (UNDERSCORE _expression_core CARET _expression_core)? special_fraction
+
+group_curly_parentheses_special: UNDERSCORE L_BRACE _atomic_expr EQUAL _atomic_expr R_BRACE CARET _expression_core
+    | CARET _expression_core UNDERSCORE L_BRACE _atomic_expr EQUAL _atomic_expr R_BRACE
+
+summation: FUNC_SUM group_curly_parentheses_special _expression
+    | FUNC_SUM group_curly_parentheses_special _expression
+
+product: FUNC_PROD group_curly_parentheses_special _expression
+    | FUNC_PROD group_curly_parentheses_special _expression
+
+superscript: _expression_func CARET (_expression_power | CMD_PRIME | CMD_ASTERISK)
+    | _expression_func CARET L_BRACE (PRIMES | STARS | PRIMES_VIA_CMD | STARS_VIA_CMD) R_BRACE
+
+matrix_prime: (matrix | group_round_parentheses) PRIMES
+
+symbol_prime: (LATIN_SYMBOL_WITH_LATIN_SUBSCRIPT
+    | LATIN_SYMBOL_WITH_GREEK_SUBSCRIPT
+    | GREEK_SYMBOL_WITH_LATIN_SUBSCRIPT
+    | GREEK_SYMBOL_WITH_GREEK_SUBSCRIPT) PRIMES
+
+fraction: _basic_fraction
+    | _simple_fraction
+    | _general_fraction
+
+_basic_fraction: CMD_FRAC DIGIT (DIGIT | SYMBOL | GREEK_SYMBOL_WITH_PRIMES)
+
+_simple_fraction: CMD_FRAC DIGIT group_curly_parentheses
+    | CMD_FRAC group_curly_parentheses (DIGIT | SYMBOL | GREEK_SYMBOL_WITH_PRIMES)
+
+_general_fraction: CMD_FRAC group_curly_parentheses group_curly_parentheses
+
+binomial: _basic_binomial
+    | _simple_binomial
+    | _general_binomial
+
+_basic_binomial: CMD_BINOM DIGIT (DIGIT | SYMBOL | GREEK_SYMBOL_WITH_PRIMES)
+
+_simple_binomial: CMD_BINOM DIGIT group_curly_parentheses
+    | CMD_BINOM group_curly_parentheses (DIGIT | SYMBOL | GREEK_SYMBOL_WITH_PRIMES)
+
+_general_binomial: CMD_BINOM group_curly_parentheses group_curly_parentheses
+
+list_of_expressions: _expression ("," _expression)*
+
+function_applied: _one_letter_symbol L_PAREN list_of_expressions R_PAREN
+
+min: FUNC_MIN L_PAREN list_of_expressions R_PAREN
+
+max: FUNC_MAX L_PAREN list_of_expressions R_PAREN
+
+bra: CMD_LANGLE _expression BAR
+
+ket: BAR _expression CMD_RANGLE
+
+inner_product: CMD_LANGLE _expression BAR _expression CMD_RANGLE
+
+_function: function_applied
+    | abs | floor | ceil
+    | _trigonometric_function | _inverse_trigonometric_function
+    | _trigonometric_function_power
+    | _hyperbolic_trigonometric_function | _inverse_hyperbolic_trigonometric_function
+    | exponential
+    | log
+    | square_root
+    | factorial
+    | conjugate
+    | max | min
+    | bra | ket | inner_product
+    | determinant
+    | trace
+    | adjugate
+
+exponential: FUNC_EXP _expression
+
+log: FUNC_LOG _expression
+    | FUNC_LN _expression
+    | FUNC_LG _expression
+    | FUNC_LOG UNDERSCORE (DIGIT | _one_letter_symbol) _expression
+    | FUNC_LOG UNDERSCORE group_curly_parentheses _expression
+
+square_root: FUNC_SQRT group_curly_parentheses
+    | FUNC_SQRT group_square_brackets group_curly_parentheses
+
+factorial: _expression_func BANG
+
+conjugate: CMD_OVERLINE group_curly_parentheses
+    | CMD_OVERLINE DIGIT
+
+_trigonometric_function: sin | cos | tan | csc | sec | cot
+
+sin: FUNC_SIN _expression
+cos: FUNC_COS _expression
+tan: FUNC_TAN _expression
+csc: FUNC_CSC _expression
+sec: FUNC_SEC _expression
+cot: FUNC_COT _expression
+
+_trigonometric_function_power: sin_power | cos_power | tan_power | csc_power | sec_power | cot_power
+
+sin_power: FUNC_SIN CARET _expression_core _expression
+cos_power: FUNC_COS CARET _expression_core _expression
+tan_power: FUNC_TAN CARET _expression_core _expression
+csc_power: FUNC_CSC CARET _expression_core _expression
+sec_power: FUNC_SEC CARET _expression_core _expression
+cot_power: FUNC_COT CARET _expression_core _expression
+
+_hyperbolic_trigonometric_function: sinh | cosh | tanh
+
+sinh: FUNC_SINH _expression
+cosh: FUNC_COSH _expression
+tanh: FUNC_TANH _expression
+
+_inverse_trigonometric_function: arcsin | arccos | arctan | arccsc | arcsec | arccot
+
+arcsin: FUNC_ARCSIN _expression
+arccos: FUNC_ARCCOS _expression
+arctan: FUNC_ARCTAN _expression
+arccsc: FUNC_ARCCSC _expression
+arcsec: FUNC_ARCSEC _expression
+arccot: FUNC_ARCCOT _expression
+
+_inverse_hyperbolic_trigonometric_function: asinh | acosh | atanh
+
+asinh: FUNC_ARSINH _expression
+acosh: FUNC_ARCOSH _expression
+atanh: FUNC_ARTANH _expression
+
+abs: BAR _expression BAR
+floor: L_FLOOR _expression R_FLOOR
+ceil: L_CEIL _expression R_CEIL
+
+matrix: CMD_MATRIX_BEGIN matrix_body CMD_MATRIX_END
+matrix_body: matrix_row (MATRIX_ROW_DELIM matrix_row)* (MATRIX_ROW_DELIM)?
+matrix_row: _expression (MATRIX_COL_DELIM _expression)*
+determinant: (CMD_DETERMINANT_BEGIN matrix_body CMD_DETERMINANT_END)
+    | FUNC_DETERMINANT _expression
+trace: FUNC_MATRIX_TRACE _expression
+adjugate: FUNC_MATRIX_ADJUGATE _expression
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/lark/latex_parser.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/lark/latex_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..29f594b0de4bfd4648df1554d5863a37afff035f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/lark/latex_parser.py
@@ -0,0 +1,145 @@
+import os
+import logging
+import re
+from pathlib import Path
+
+from sympy.external import import_module
+from sympy.parsing.latex.lark.transformer import TransformToSymPyExpr
+
+_lark = import_module("lark")
+
+
+class LarkLaTeXParser:
+    r"""Class for converting input `\mathrm{\LaTeX}` strings into SymPy Expressions.
+    It holds all the necessary internal data for doing so, and exposes hooks for
+    customizing its behavior.
+
+    Parameters
+    ==========
+
+    print_debug_output : bool, optional
+
+        If set to ``True``, prints debug output to the logger. Defaults to ``False``.
+
+    transform : bool, optional
+
+        If set to ``True``, the class runs the Transformer class on the parse tree
+        generated by running ``Lark.parse`` on the input string. Defaults to ``True``.
+
+        Setting it to ``False`` can help with debugging the `\mathrm{\LaTeX}` grammar.
+
+    grammar_file : str, optional
+
+        The path to the grammar file that the parser should use. If set to ``None``,
+        it uses the default grammar, which is in ``grammar/latex.lark``, relative to
+        the ``sympy/parsing/latex/lark/`` directory.
+
+    transformer : str, optional
+
+        The name of the Transformer class to use. If set to ``None``, it uses the
+        default transformer class, which is :py:func:`TransformToSymPyExpr`.
+
+    """
+    def __init__(self, print_debug_output=False, transform=True, grammar_file=None, transformer=None):
+        grammar_dir_path = os.path.join(os.path.dirname(__file__), "grammar/")
+
+        if grammar_file is None:
+            latex_grammar = Path(os.path.join(grammar_dir_path, "latex.lark")).read_text(encoding="utf-8")
+        else:
+            latex_grammar = Path(grammar_file).read_text(encoding="utf-8")
+
+        self.parser = _lark.Lark(
+            latex_grammar,
+            source_path=grammar_dir_path,
+            parser="earley",
+            start="latex_string",
+            lexer="auto",
+            ambiguity="explicit",
+            propagate_positions=False,
+            maybe_placeholders=False,
+            keep_all_tokens=True)
+
+        self.print_debug_output = print_debug_output
+        self.transform_expr = transform
+
+        if transformer is None:
+            self.transformer = TransformToSymPyExpr()
+        else:
+            self.transformer = transformer()
+
+    def doparse(self, s: str):
+        if self.print_debug_output:
+            _lark.logger.setLevel(logging.DEBUG)
+
+        parse_tree = self.parser.parse(s)
+
+        if not self.transform_expr:
+            # exit early and return the parse tree
+            _lark.logger.debug("expression = %s", s)
+            _lark.logger.debug(parse_tree)
+            _lark.logger.debug(parse_tree.pretty())
+            return parse_tree
+
+        if self.print_debug_output:
+            # print this stuff before attempting to run the transformer
+            _lark.logger.debug("expression = %s", s)
+            # print the `parse_tree` variable
+            _lark.logger.debug(parse_tree.pretty())
+
+        sympy_expression = self.transformer.transform(parse_tree)
+
+        if self.print_debug_output:
+            _lark.logger.debug("SymPy expression = %s", sympy_expression)
+
+        return sympy_expression
+
+
+if _lark is not None:
+    _lark_latex_parser = LarkLaTeXParser()
+
+
+def parse_latex_lark(s: str):
+    """
+    Experimental LaTeX parser using Lark.
+
+    This function is still under development and its API may change with the
+    next releases of SymPy.
+    """
+    if _lark is None:
+        raise ImportError("Lark is probably not installed")
+    return _lark_latex_parser.doparse(s)
+
+
+def _pretty_print_lark_trees(tree, indent=0, show_expr=True):
+    if isinstance(tree, _lark.Token):
+        return tree.value
+
+    data = str(tree.data)
+
+    is_expr = data.startswith("expression")
+
+    if is_expr:
+        data = re.sub(r"^expression", "E", data)
+
+    is_ambig = (data == "_ambig")
+
+    if is_ambig:
+        new_indent = indent + 2
+    else:
+        new_indent = indent
+
+    output = ""
+    show_node = not is_expr or show_expr
+
+    if show_node:
+        output += str(data) + "("
+
+    if is_ambig:
+        output += "\n" + "\n".join([" " * new_indent + _pretty_print_lark_trees(i, new_indent, show_expr) for i in tree.children])
+    else:
+        output += ",".join([_pretty_print_lark_trees(i, new_indent, show_expr) for i in tree.children])
+
+    if show_node:
+        output += ")"
+
+    return output
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/lark/transformer.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/lark/transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..cbd514b6517336207a57de6d28bcce25858071dc
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/latex/lark/transformer.py
@@ -0,0 +1,730 @@
+import re
+
+import sympy
+from sympy.external import import_module
+from sympy.parsing.latex.errors import LaTeXParsingError
+
+lark = import_module("lark")
+
+if lark:
+    from lark import Transformer, Token, Tree  # type: ignore
+else:
+    class Transformer:  # type: ignore
+        def transform(self, *args):
+            pass
+
+
+    class Token:  # type: ignore
+        pass
+
+
+    class Tree:  # type: ignore
+        pass
+
+
+# noinspection PyPep8Naming,PyMethodMayBeStatic
+class TransformToSymPyExpr(Transformer):
+    """Returns a SymPy expression that is generated by traversing the ``lark.Tree``
+    passed to the ``.transform()`` function.
+
+    Notes
+    =====
+
+    **This class is never supposed to be used directly.**
+
+    In order to tweak the behavior of this class, it has to be subclassed and then after
+    the required modifications are made, the name of the new class should be passed to
+    the :py:class:`LarkLaTeXParser` class by using the ``transformer`` argument in the
+    constructor.
+
+    Parameters
+    ==========
+
+    visit_tokens : bool, optional
+        For information about what this option does, see `here
+        `_.
+
+        Note that the option must be set to ``True`` for the default parser to work.
+    """
+
+    SYMBOL = sympy.Symbol
+    DIGIT = sympy.core.numbers.Integer
+
+    def CMD_INFTY(self, tokens):
+        return sympy.oo
+
+    def GREEK_SYMBOL_WITH_PRIMES(self, tokens):
+        # we omit the first character because it is a backslash. Also, if the variable name has "var" in it,
+        # like "varphi" or "varepsilon", we remove that too
+        variable_name = re.sub("var", "", tokens[1:])
+
+        return sympy.Symbol(variable_name)
+
+    def LATIN_SYMBOL_WITH_LATIN_SUBSCRIPT(self, tokens):
+        base, sub = tokens.value.split("_")
+        if sub.startswith("{"):
+            return sympy.Symbol("%s_{%s}" % (base, sub[1:-1]))
+        else:
+            return sympy.Symbol("%s_{%s}" % (base, sub))
+
+    def GREEK_SYMBOL_WITH_LATIN_SUBSCRIPT(self, tokens):
+        base, sub = tokens.value.split("_")
+        greek_letter = re.sub("var", "", base[1:])
+
+        if sub.startswith("{"):
+            return sympy.Symbol("%s_{%s}" % (greek_letter, sub[1:-1]))
+        else:
+            return sympy.Symbol("%s_{%s}" % (greek_letter, sub))
+
+    def LATIN_SYMBOL_WITH_GREEK_SUBSCRIPT(self, tokens):
+        base, sub = tokens.value.split("_")
+        if sub.startswith("{"):
+            greek_letter = sub[2:-1]
+        else:
+            greek_letter = sub[1:]
+
+        greek_letter = re.sub("var", "", greek_letter)
+        return sympy.Symbol("%s_{%s}" % (base, greek_letter))
+
+
+    def GREEK_SYMBOL_WITH_GREEK_SUBSCRIPT(self, tokens):
+        base, sub = tokens.value.split("_")
+        greek_base = re.sub("var", "", base[1:])
+
+        if sub.startswith("{"):
+            greek_sub = sub[2:-1]
+        else:
+            greek_sub = sub[1:]
+
+        greek_sub = re.sub("var", "", greek_sub)
+        return sympy.Symbol("%s_{%s}" % (greek_base, greek_sub))
+
+    def multi_letter_symbol(self, tokens):
+        if len(tokens) == 4: # no primes (single quotes) on symbol
+            return sympy.Symbol(tokens[2])
+        if len(tokens) == 5: # there are primes on the symbol
+            return sympy.Symbol(tokens[2] + tokens[4])
+
+    def number(self, tokens):
+        if tokens[0].type == "CMD_IMAGINARY_UNIT":
+            return sympy.I
+
+        if "." in tokens[0]:
+            return sympy.core.numbers.Float(tokens[0])
+        else:
+            return sympy.core.numbers.Integer(tokens[0])
+
+    def latex_string(self, tokens):
+        return tokens[0]
+
+    def group_round_parentheses(self, tokens):
+        return tokens[1]
+
+    def group_square_brackets(self, tokens):
+        return tokens[1]
+
+    def group_curly_parentheses(self, tokens):
+        return tokens[1]
+
+    def eq(self, tokens):
+        return sympy.Eq(tokens[0], tokens[2])
+
+    def ne(self, tokens):
+        return sympy.Ne(tokens[0], tokens[2])
+
+    def lt(self, tokens):
+        return sympy.Lt(tokens[0], tokens[2])
+
+    def lte(self, tokens):
+        return sympy.Le(tokens[0], tokens[2])
+
+    def gt(self, tokens):
+        return sympy.Gt(tokens[0], tokens[2])
+
+    def gte(self, tokens):
+        return sympy.Ge(tokens[0], tokens[2])
+
+    def add(self, tokens):
+        if len(tokens) == 2: # +a
+            return tokens[1]
+        if len(tokens) == 3: # a + b
+            lh = tokens[0]
+            rh = tokens[2]
+
+            if self._obj_is_sympy_Matrix(lh) or self._obj_is_sympy_Matrix(rh):
+                return sympy.MatAdd(lh, rh)
+
+            return sympy.Add(lh, rh)
+
+    def sub(self, tokens):
+        if len(tokens) == 2: # -a
+            x = tokens[1]
+
+            if self._obj_is_sympy_Matrix(x):
+                return sympy.MatMul(-1, x)
+
+            return -x
+        if len(tokens) == 3: # a - b
+            lh = tokens[0]
+            rh = tokens[2]
+
+            if self._obj_is_sympy_Matrix(lh) or self._obj_is_sympy_Matrix(rh):
+                return sympy.MatAdd(lh, sympy.MatMul(-1, rh))
+
+            return sympy.Add(lh, -rh)
+
+    def mul(self, tokens):
+        lh = tokens[0]
+        rh = tokens[2]
+
+        if self._obj_is_sympy_Matrix(lh) or self._obj_is_sympy_Matrix(rh):
+            return sympy.MatMul(lh, rh)
+
+        return sympy.Mul(lh, rh)
+
+    def div(self, tokens):
+        return self._handle_division(tokens[0], tokens[2])
+
+    def adjacent_expressions(self, tokens):
+        # Most of the time, if two expressions are next to each other, it means implicit multiplication,
+        # but not always
+        from sympy.physics.quantum import Bra, Ket
+        if isinstance(tokens[0], Ket) and isinstance(tokens[1], Bra):
+            from sympy.physics.quantum import OuterProduct
+            return OuterProduct(tokens[0], tokens[1])
+        elif tokens[0] == sympy.Symbol("d"):
+            # If the leftmost token is a "d", then it is highly likely that this is a differential
+            return tokens[0], tokens[1]
+        elif isinstance(tokens[0], tuple):
+            # then we have a derivative
+            return sympy.Derivative(tokens[1], tokens[0][1])
+        else:
+            return sympy.Mul(tokens[0], tokens[1])
+
+    def superscript(self, tokens):
+        def isprime(x):
+            return isinstance(x, Token) and x.type == "PRIMES"
+
+        def iscmdprime(x):
+            return isinstance(x, Token) and (x.type == "PRIMES_VIA_CMD"
+                                             or x.type == "CMD_PRIME")
+
+        def isstar(x):
+            return isinstance(x, Token) and x.type == "STARS"
+
+        def iscmdstar(x):
+            return isinstance(x, Token) and (x.type == "STARS_VIA_CMD"
+                                             or x.type == "CMD_ASTERISK")
+
+        base = tokens[0]
+        if len(tokens) == 3: # a^b OR a^\prime OR a^\ast
+            sup = tokens[2]
+        if len(tokens) == 5:
+            # a^{'}, a^{''}, ... OR
+            # a^{*}, a^{**}, ... OR
+            # a^{\prime}, a^{\prime\prime}, ... OR
+            # a^{\ast}, a^{\ast\ast}, ...
+            sup = tokens[3]
+
+        if self._obj_is_sympy_Matrix(base):
+            if sup == sympy.Symbol("T"):
+                return sympy.Transpose(base)
+            if sup == sympy.Symbol("H"):
+                return sympy.adjoint(base)
+            if isprime(sup):
+                sup = sup.value
+                if len(sup) % 2 == 0:
+                    return base
+                return sympy.Transpose(base)
+            if iscmdprime(sup):
+                sup = sup.value
+                if (len(sup)/len(r"\prime")) % 2 == 0:
+                    return base
+                return sympy.Transpose(base)
+            if isstar(sup):
+                sup = sup.value
+                # need .doit() in order to be consistent with
+                # sympy.adjoint() which returns the evaluated adjoint
+                # of a matrix
+                if len(sup) % 2 == 0:
+                    return base.doit()
+                return sympy.adjoint(base)
+            if iscmdstar(sup):
+                sup = sup.value
+                # need .doit() for same reason as above
+                if (len(sup)/len(r"\ast")) % 2 == 0:
+                    return base.doit()
+                return sympy.adjoint(base)
+
+        if isprime(sup) or iscmdprime(sup) or isstar(sup) or iscmdstar(sup):
+            raise LaTeXParsingError(f"{base} with superscript {sup} is not understood.")
+
+        return sympy.Pow(base, sup)
+
+    def matrix_prime(self, tokens):
+        base = tokens[0]
+        primes = tokens[1].value
+
+        if not self._obj_is_sympy_Matrix(base):
+            raise LaTeXParsingError(f"({base}){primes} is not understood.")
+
+        if len(primes) % 2 == 0:
+            return base
+
+        return sympy.Transpose(base)
+
+    def symbol_prime(self, tokens):
+        base = tokens[0]
+        primes = tokens[1].value
+
+        return sympy.Symbol(f"{base.name}{primes}")
+
+    def fraction(self, tokens):
+        numerator = tokens[1]
+        if isinstance(tokens[2], tuple):
+            # we only need the variable w.r.t. which we are differentiating
+            _, variable = tokens[2]
+
+            # we will pass this information upwards
+            return "derivative", variable
+        else:
+            denominator = tokens[2]
+            return self._handle_division(numerator, denominator)
+
+    def binomial(self, tokens):
+        return sympy.binomial(tokens[1], tokens[2])
+
+    def normal_integral(self, tokens):
+        underscore_index = None
+        caret_index = None
+
+        if "_" in tokens:
+            # we need to know the index because the next item in the list is the
+            # arguments for the lower bound of the integral
+            underscore_index = tokens.index("_")
+
+        if "^" in tokens:
+            # we need to know the index because the next item in the list is the
+            # arguments for the upper bound of the integral
+            caret_index = tokens.index("^")
+
+        lower_bound = tokens[underscore_index + 1] if underscore_index else None
+        upper_bound = tokens[caret_index + 1] if caret_index else None
+
+        differential_symbol = self._extract_differential_symbol(tokens)
+
+        if differential_symbol is None:
+            raise LaTeXParsingError("Differential symbol was not found in the expression."
+                                    "Valid differential symbols are \"d\", \"\\text{d}, and \"\\mathrm{d}\".")
+
+        # else we can assume that a differential symbol was found
+        differential_variable_index = tokens.index(differential_symbol) + 1
+        differential_variable = tokens[differential_variable_index]
+
+        # we can't simply do something like `if (lower_bound and not upper_bound) ...` because this would
+        # evaluate to `True` if the `lower_bound` is 0 and upper bound is non-zero
+        if lower_bound is not None and upper_bound is None:
+            # then one was given and the other wasn't
+            raise LaTeXParsingError("Lower bound for the integral was found, but upper bound was not found.")
+
+        if upper_bound is not None and lower_bound is None:
+            # then one was given and the other wasn't
+            raise LaTeXParsingError("Upper bound for the integral was found, but lower bound was not found.")
+
+        # check if any expression was given or not. If it wasn't, then set the integrand to 1.
+        if underscore_index is not None and underscore_index == differential_variable_index - 3:
+            # The Token at differential_variable_index - 2 should be the integrand. However, if going one more step
+            # backwards after that gives us the underscore, then that means that there _was_ no integrand.
+            # Example: \int^7_0 dx
+            integrand = 1
+        elif caret_index is not None and caret_index == differential_variable_index - 3:
+            # The Token at differential_variable_index - 2 should be the integrand. However, if going one more step
+            # backwards after that gives us the caret, then that means that there _was_ no integrand.
+            # Example: \int_0^7 dx
+            integrand = 1
+        elif differential_variable_index == 2:
+            # this means we have something like "\int dx", because the "\int" symbol will always be
+            # at index 0 in `tokens`
+            integrand = 1
+        else:
+            # The Token at differential_variable_index - 1 is the differential symbol itself, so we need to go one
+            # more step before that.
+            integrand = tokens[differential_variable_index - 2]
+
+        if lower_bound is not None:
+            # then we have a definite integral
+
+            # we can assume that either both the lower and upper bounds are given, or
+            # neither of them are
+            return sympy.Integral(integrand, (differential_variable, lower_bound, upper_bound))
+        else:
+            # we have an indefinite integral
+            return sympy.Integral(integrand, differential_variable)
+
+    def group_curly_parentheses_int(self, tokens):
+        # return signature is a tuple consisting of the expression in the numerator, along with the variable of
+        # integration
+        if len(tokens) == 3:
+            return 1, tokens[1]
+        elif len(tokens) == 4:
+            return tokens[1], tokens[2]
+        # there are no other possibilities
+
+    def special_fraction(self, tokens):
+        numerator, variable = tokens[1]
+        denominator = tokens[2]
+
+        # We pass the integrand, along with information about the variable of integration, upw
+        return sympy.Mul(numerator, sympy.Pow(denominator, -1)), variable
+
+    def integral_with_special_fraction(self, tokens):
+        underscore_index = None
+        caret_index = None
+
+        if "_" in tokens:
+            # we need to know the index because the next item in the list is the
+            # arguments for the lower bound of the integral
+            underscore_index = tokens.index("_")
+
+        if "^" in tokens:
+            # we need to know the index because the next item in the list is the
+            # arguments for the upper bound of the integral
+            caret_index = tokens.index("^")
+
+        lower_bound = tokens[underscore_index + 1] if underscore_index else None
+        upper_bound = tokens[caret_index + 1] if caret_index else None
+
+        # we can't simply do something like `if (lower_bound and not upper_bound) ...` because this would
+        # evaluate to `True` if the `lower_bound` is 0 and upper bound is non-zero
+        if lower_bound is not None and upper_bound is None:
+            # then one was given and the other wasn't
+            raise LaTeXParsingError("Lower bound for the integral was found, but upper bound was not found.")
+
+        if upper_bound is not None and lower_bound is None:
+            # then one was given and the other wasn't
+            raise LaTeXParsingError("Upper bound for the integral was found, but lower bound was not found.")
+
+        integrand, differential_variable = tokens[-1]
+
+        if lower_bound is not None:
+            # then we have a definite integral
+
+            # we can assume that either both the lower and upper bounds are given, or
+            # neither of them are
+            return sympy.Integral(integrand, (differential_variable, lower_bound, upper_bound))
+        else:
+            # we have an indefinite integral
+            return sympy.Integral(integrand, differential_variable)
+
+    def group_curly_parentheses_special(self, tokens):
+        underscore_index = tokens.index("_")
+        caret_index = tokens.index("^")
+
+        # given the type of expressions we are parsing, we can assume that the lower limit
+        # will always use braces around its arguments. This is because we don't support
+        # converting unconstrained sums into SymPy expressions.
+
+        # first we isolate the bottom limit
+        left_brace_index = tokens.index("{", underscore_index)
+        right_brace_index = tokens.index("}", underscore_index)
+
+        bottom_limit = tokens[left_brace_index + 1: right_brace_index]
+
+        # next, we isolate the upper limit
+        top_limit = tokens[caret_index + 1:]
+
+        # the code below will be useful for supporting things like `\sum_{n = 0}^{n = 5} n^2`
+        # if "{" in top_limit:
+        #     left_brace_index = tokens.index("{", caret_index)
+        #     if left_brace_index != -1:
+        #         # then there's a left brace in the string, and we need to find the closing right brace
+        #         right_brace_index = tokens.index("}", caret_index)
+        #         top_limit = tokens[left_brace_index + 1: right_brace_index]
+
+        # print(f"top  limit = {top_limit}")
+
+        index_variable = bottom_limit[0]
+        lower_limit = bottom_limit[-1]
+        upper_limit = top_limit[0]  # for now, the index will always be 0
+
+        # print(f"return value = ({index_variable}, {lower_limit}, {upper_limit})")
+
+        return index_variable, lower_limit, upper_limit
+
+    def summation(self, tokens):
+        return sympy.Sum(tokens[2], tokens[1])
+
+    def product(self, tokens):
+        return sympy.Product(tokens[2], tokens[1])
+
+    def limit_dir_expr(self, tokens):
+        caret_index = tokens.index("^")
+
+        if "{" in tokens:
+            left_curly_brace_index = tokens.index("{", caret_index)
+            direction = tokens[left_curly_brace_index + 1]
+        else:
+            direction = tokens[caret_index + 1]
+
+        if direction == "+":
+            return tokens[0], "+"
+        elif direction == "-":
+            return tokens[0], "-"
+        else:
+            return tokens[0], "+-"
+
+    def group_curly_parentheses_lim(self, tokens):
+        limit_variable = tokens[1]
+        if isinstance(tokens[3], tuple):
+            destination, direction = tokens[3]
+        else:
+            destination = tokens[3]
+            direction = "+-"
+
+        return limit_variable, destination, direction
+
+    def limit(self, tokens):
+        limit_variable, destination, direction = tokens[2]
+
+        return sympy.Limit(tokens[-1], limit_variable, destination, direction)
+
+    def differential(self, tokens):
+        return tokens[1]
+
+    def derivative(self, tokens):
+        return sympy.Derivative(tokens[-1], tokens[5])
+
+    def list_of_expressions(self, tokens):
+        if len(tokens) == 1:
+            # we return it verbatim because the function_applied node expects
+            # a list
+            return tokens
+        else:
+            def remove_tokens(args):
+                if isinstance(args, Token):
+                    if args.type != "COMMA":
+                        # An unexpected token was encountered
+                        raise LaTeXParsingError("A comma token was expected, but some other token was encountered.")
+                    return False
+                return True
+
+            return filter(remove_tokens, tokens)
+
+    def function_applied(self, tokens):
+        return sympy.Function(tokens[0])(*tokens[2])
+
+    def min(self, tokens):
+        return sympy.Min(*tokens[2])
+
+    def max(self, tokens):
+        return sympy.Max(*tokens[2])
+
+    def bra(self, tokens):
+        from sympy.physics.quantum import Bra
+        return Bra(tokens[1])
+
+    def ket(self, tokens):
+        from sympy.physics.quantum import Ket
+        return Ket(tokens[1])
+
+    def inner_product(self, tokens):
+        from sympy.physics.quantum import Bra, Ket, InnerProduct
+        return InnerProduct(Bra(tokens[1]), Ket(tokens[3]))
+
+    def sin(self, tokens):
+        return sympy.sin(tokens[1])
+
+    def cos(self, tokens):
+        return sympy.cos(tokens[1])
+
+    def tan(self, tokens):
+        return sympy.tan(tokens[1])
+
+    def csc(self, tokens):
+        return sympy.csc(tokens[1])
+
+    def sec(self, tokens):
+        return sympy.sec(tokens[1])
+
+    def cot(self, tokens):
+        return sympy.cot(tokens[1])
+
+    def sin_power(self, tokens):
+        exponent = tokens[2]
+        if exponent == -1:
+            return sympy.asin(tokens[-1])
+        else:
+            return sympy.Pow(sympy.sin(tokens[-1]), exponent)
+
+    def cos_power(self, tokens):
+        exponent = tokens[2]
+        if exponent == -1:
+            return sympy.acos(tokens[-1])
+        else:
+            return sympy.Pow(sympy.cos(tokens[-1]), exponent)
+
+    def tan_power(self, tokens):
+        exponent = tokens[2]
+        if exponent == -1:
+            return sympy.atan(tokens[-1])
+        else:
+            return sympy.Pow(sympy.tan(tokens[-1]), exponent)
+
+    def csc_power(self, tokens):
+        exponent = tokens[2]
+        if exponent == -1:
+            return sympy.acsc(tokens[-1])
+        else:
+            return sympy.Pow(sympy.csc(tokens[-1]), exponent)
+
+    def sec_power(self, tokens):
+        exponent = tokens[2]
+        if exponent == -1:
+            return sympy.asec(tokens[-1])
+        else:
+            return sympy.Pow(sympy.sec(tokens[-1]), exponent)
+
+    def cot_power(self, tokens):
+        exponent = tokens[2]
+        if exponent == -1:
+            return sympy.acot(tokens[-1])
+        else:
+            return sympy.Pow(sympy.cot(tokens[-1]), exponent)
+
+    def arcsin(self, tokens):
+        return sympy.asin(tokens[1])
+
+    def arccos(self, tokens):
+        return sympy.acos(tokens[1])
+
+    def arctan(self, tokens):
+        return sympy.atan(tokens[1])
+
+    def arccsc(self, tokens):
+        return sympy.acsc(tokens[1])
+
+    def arcsec(self, tokens):
+        return sympy.asec(tokens[1])
+
+    def arccot(self, tokens):
+        return sympy.acot(tokens[1])
+
+    def sinh(self, tokens):
+        return sympy.sinh(tokens[1])
+
+    def cosh(self, tokens):
+        return sympy.cosh(tokens[1])
+
+    def tanh(self, tokens):
+        return sympy.tanh(tokens[1])
+
+    def asinh(self, tokens):
+        return sympy.asinh(tokens[1])
+
+    def acosh(self, tokens):
+        return sympy.acosh(tokens[1])
+
+    def atanh(self, tokens):
+        return sympy.atanh(tokens[1])
+
+    def abs(self, tokens):
+        return sympy.Abs(tokens[1])
+
+    def floor(self, tokens):
+        return sympy.floor(tokens[1])
+
+    def ceil(self, tokens):
+        return sympy.ceiling(tokens[1])
+
+    def factorial(self, tokens):
+        return sympy.factorial(tokens[0])
+
+    def conjugate(self, tokens):
+        return sympy.conjugate(tokens[1])
+
+    def square_root(self, tokens):
+        if len(tokens) == 2:
+            # then there was no square bracket argument
+            return sympy.sqrt(tokens[1])
+        elif len(tokens) == 3:
+            # then there _was_ a square bracket argument
+            return sympy.root(tokens[2], tokens[1])
+
+    def exponential(self, tokens):
+        return sympy.exp(tokens[1])
+
+    def log(self, tokens):
+        if tokens[0].type == "FUNC_LG":
+            # we don't need to check if there's an underscore or not because having one
+            # in this case would be meaningless
+            # TODO: ANTLR refers to ISO 80000-2:2019. should we keep base 10 or base 2?
+            return sympy.log(tokens[1], 10)
+        elif tokens[0].type == "FUNC_LN":
+            return sympy.log(tokens[1])
+        elif tokens[0].type == "FUNC_LOG":
+            # we check if a base was specified or not
+            if "_" in tokens:
+                # then a base was specified
+                return sympy.log(tokens[3], tokens[2])
+            else:
+                # a base was not specified
+                return sympy.log(tokens[1])
+
+    def _extract_differential_symbol(self, s: str):
+        differential_symbols = {"d", r"\text{d}", r"\mathrm{d}"}
+
+        differential_symbol = next((symbol for symbol in differential_symbols if symbol in s), None)
+
+        return differential_symbol
+
+    def matrix(self, tokens):
+        def is_matrix_row(x):
+            return (isinstance(x, Tree) and x.data == "matrix_row")
+
+        def is_not_col_delim(y):
+            return (not isinstance(y, Token) or y.type != "MATRIX_COL_DELIM")
+
+        matrix_body = tokens[1].children
+        return sympy.Matrix([[y for y in x.children if is_not_col_delim(y)]
+                             for x in matrix_body if is_matrix_row(x)])
+
+    def determinant(self, tokens):
+        if len(tokens) == 2: # \det A
+            if not self._obj_is_sympy_Matrix(tokens[1]):
+                raise LaTeXParsingError("Cannot take determinant of non-matrix.")
+
+            return tokens[1].det()
+
+        if len(tokens) == 3: # | A |
+            return self.matrix(tokens).det()
+
+    def trace(self, tokens):
+        if not self._obj_is_sympy_Matrix(tokens[1]):
+            raise LaTeXParsingError("Cannot take trace of non-matrix.")
+
+        return sympy.Trace(tokens[1])
+
+    def adjugate(self, tokens):
+        if not self._obj_is_sympy_Matrix(tokens[1]):
+            raise LaTeXParsingError("Cannot take adjugate of non-matrix.")
+
+        # need .doit() since MatAdd does not support .adjugate() method
+        return tokens[1].doit().adjugate()
+
+    def _obj_is_sympy_Matrix(self, obj):
+        if hasattr(obj, "is_Matrix"):
+            return obj.is_Matrix
+
+        return isinstance(obj, sympy.Matrix)
+
+    def _handle_division(self, numerator, denominator):
+        if self._obj_is_sympy_Matrix(denominator):
+            raise LaTeXParsingError("Cannot divide by matrices like this since "
+                                    "it is not clear if left or right multiplication "
+                                    "by the inverse is intended. Try explicitly "
+                                    "multiplying by the inverse instead.")
+
+        if self._obj_is_sympy_Matrix(numerator):
+            return sympy.MatMul(numerator, sympy.Pow(denominator, -1))
+
+        return sympy.Mul(numerator, sympy.Pow(denominator, -1))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/mathematica.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/mathematica.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5824a8c33ee402d03e6c5617eeeea21d4a457d1
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/mathematica.py
@@ -0,0 +1,1085 @@
+from __future__ import annotations
+import re
+import typing
+from itertools import product
+from typing import Any, Callable
+
+import sympy
+from sympy import Mul, Add, Pow, Rational, log, exp, sqrt, cos, sin, tan, asin, acos, acot, asec, acsc, sinh, cosh, tanh, asinh, \
+    acosh, atanh, acoth, asech, acsch, expand, im, flatten, polylog, cancel, expand_trig, sign, simplify, \
+    UnevaluatedExpr, S, atan, atan2, Mod, Max, Min, rf, Ei, Si, Ci, airyai, airyaiprime, airybi, primepi, prime, \
+    isprime, cot, sec, csc, csch, sech, coth, Function, I, pi, Tuple, GreaterThan, StrictGreaterThan, StrictLessThan, \
+    LessThan, Equality, Or, And, Lambda, Integer, Dummy, symbols
+from sympy.core.sympify import sympify, _sympify
+from sympy.functions.special.bessel import airybiprime
+from sympy.functions.special.error_functions import li
+from sympy.utilities.exceptions import sympy_deprecation_warning
+
+
+def mathematica(s, additional_translations=None):
+    sympy_deprecation_warning(
+        """The ``mathematica`` function for the Mathematica parser is now
+deprecated. Use ``parse_mathematica`` instead.
+The parameter ``additional_translation`` can be replaced by SymPy's
+.replace( ) or .subs( ) methods on the output expression instead.""",
+        deprecated_since_version="1.11",
+        active_deprecations_target="mathematica-parser-new",
+    )
+    parser = MathematicaParser(additional_translations)
+    return sympify(parser._parse_old(s))
+
+
+def parse_mathematica(s):
+    """
+    Translate a string containing a Wolfram Mathematica expression to a SymPy
+    expression.
+
+    If the translator is unable to find a suitable SymPy expression, the
+    ``FullForm`` of the Mathematica expression will be output, using SymPy
+    ``Function`` objects as nodes of the syntax tree.
+
+    Examples
+    ========
+
+    >>> from sympy.parsing.mathematica import parse_mathematica
+    >>> parse_mathematica("Sin[x]^2 Tan[y]")
+    sin(x)**2*tan(y)
+    >>> e = parse_mathematica("F[7,5,3]")
+    >>> e
+    F(7, 5, 3)
+    >>> from sympy import Function, Max, Min
+    >>> e.replace(Function("F"), lambda *x: Max(*x)*Min(*x))
+    21
+
+    Both standard input form and Mathematica full form are supported:
+
+    >>> parse_mathematica("x*(a + b)")
+    x*(a + b)
+    >>> parse_mathematica("Times[x, Plus[a, b]]")
+    x*(a + b)
+
+    To get a matrix from Wolfram's code:
+
+    >>> m = parse_mathematica("{{a, b}, {c, d}}")
+    >>> m
+    ((a, b), (c, d))
+    >>> from sympy import Matrix
+    >>> Matrix(m)
+    Matrix([
+    [a, b],
+    [c, d]])
+
+    If the translation into equivalent SymPy expressions fails, an SymPy
+    expression equivalent to Wolfram Mathematica's "FullForm" will be created:
+
+    >>> parse_mathematica("x_.")
+    Optional(Pattern(x, Blank()))
+    >>> parse_mathematica("Plus @@ {x, y, z}")
+    Apply(Plus, (x, y, z))
+    >>> parse_mathematica("f[x_, 3] := x^3 /; x > 0")
+    SetDelayed(f(Pattern(x, Blank()), 3), Condition(x**3, x > 0))
+    """
+    parser = MathematicaParser()
+    return parser.parse(s)
+
+
+def _parse_Function(*args):
+    if len(args) == 1:
+        arg = args[0]
+        Slot = Function("Slot")
+        slots = arg.atoms(Slot)
+        numbers = [a.args[0] for a in slots]
+        number_of_arguments = max(numbers)
+        if isinstance(number_of_arguments, Integer):
+            variables = symbols(f"dummy0:{number_of_arguments}", cls=Dummy)
+            return Lambda(variables, arg.xreplace({Slot(i+1): v for i, v in enumerate(variables)}))
+        return Lambda((), arg)
+    elif len(args) == 2:
+        variables = args[0]
+        body = args[1]
+        return Lambda(variables, body)
+    else:
+        raise SyntaxError("Function node expects 1 or 2 arguments")
+
+
+def _deco(cls):
+    cls._initialize_class()
+    return cls
+
+
+@_deco
+class MathematicaParser:
+    """
+    An instance of this class converts a string of a Wolfram Mathematica
+    expression to a SymPy expression.
+
+    The main parser acts internally in three stages:
+
+    1. tokenizer: tokenizes the Mathematica expression and adds the missing *
+        operators. Handled by ``_from_mathematica_to_tokens(...)``
+    2. full form list: sort the list of strings output by the tokenizer into a
+        syntax tree of nested lists and strings, equivalent to Mathematica's
+        ``FullForm`` expression output. This is handled by the function
+        ``_from_tokens_to_fullformlist(...)``.
+    3. SymPy expression: the syntax tree expressed as full form list is visited
+        and the nodes with equivalent classes in SymPy are replaced. Unknown
+        syntax tree nodes are cast to SymPy ``Function`` objects. This is
+        handled by ``_from_fullformlist_to_sympy(...)``.
+
+    """
+
+    # left: Mathematica, right: SymPy
+    CORRESPONDENCES = {
+        'Sqrt[x]': 'sqrt(x)',
+        'Rational[x,y]': 'Rational(x,y)',
+        'Exp[x]': 'exp(x)',
+        'Log[x]': 'log(x)',
+        'Log[x,y]': 'log(y,x)',
+        'Log2[x]': 'log(x,2)',
+        'Log10[x]': 'log(x,10)',
+        'Mod[x,y]': 'Mod(x,y)',
+        'Max[*x]': 'Max(*x)',
+        'Min[*x]': 'Min(*x)',
+        'Pochhammer[x,y]':'rf(x,y)',
+        'ArcTan[x,y]':'atan2(y,x)',
+        'ExpIntegralEi[x]': 'Ei(x)',
+        'SinIntegral[x]': 'Si(x)',
+        'CosIntegral[x]': 'Ci(x)',
+        'AiryAi[x]': 'airyai(x)',
+        'AiryAiPrime[x]': 'airyaiprime(x)',
+        'AiryBi[x]' :'airybi(x)',
+        'AiryBiPrime[x]' :'airybiprime(x)',
+        'LogIntegral[x]':' li(x)',
+        'PrimePi[x]': 'primepi(x)',
+        'Prime[x]': 'prime(x)',
+        'PrimeQ[x]': 'isprime(x)'
+    }
+
+    # trigonometric, e.t.c.
+    for arc, tri, h in product(('', 'Arc'), (
+            'Sin', 'Cos', 'Tan', 'Cot', 'Sec', 'Csc'), ('', 'h')):
+        fm = arc + tri + h + '[x]'
+        if arc:  # arc func
+            fs = 'a' + tri.lower() + h + '(x)'
+        else:    # non-arc func
+            fs = tri.lower() + h + '(x)'
+        CORRESPONDENCES.update({fm: fs})
+
+    REPLACEMENTS = {
+        ' ': '',
+        '^': '**',
+        '{': '[',
+        '}': ']',
+    }
+
+    RULES = {
+        # a single whitespace to '*'
+        'whitespace': (
+            re.compile(r'''
+                (?:(?<=[a-zA-Z\d])|(?<=\d\.))     # a letter or a number
+                \s+                               # any number of whitespaces
+                (?:(?=[a-zA-Z\d])|(?=\.\d))       # a letter or a number
+                ''', re.VERBOSE),
+            '*'),
+
+        # add omitted '*' character
+        'add*_1': (
+            re.compile(r'''
+                (?:(?<=[])\d])|(?<=\d\.))       # ], ) or a number
+                                                # ''
+                (?=[(a-zA-Z])                   # ( or a single letter
+                ''', re.VERBOSE),
+            '*'),
+
+        # add omitted '*' character (variable letter preceding)
+        'add*_2': (
+            re.compile(r'''
+                (?<=[a-zA-Z])       # a letter
+                \(                  # ( as a character
+                (?=.)               # any characters
+                ''', re.VERBOSE),
+            '*('),
+
+        # convert 'Pi' to 'pi'
+        'Pi': (
+            re.compile(r'''
+                (?:
+                \A|(?<=[^a-zA-Z])
+                )
+                Pi                  # 'Pi' is 3.14159... in Mathematica
+                (?=[^a-zA-Z])
+                ''', re.VERBOSE),
+            'pi'),
+    }
+
+    # Mathematica function name pattern
+    FM_PATTERN = re.compile(r'''
+                (?:
+                \A|(?<=[^a-zA-Z])   # at the top or a non-letter
+                )
+                [A-Z][a-zA-Z\d]*    # Function
+                (?=\[)              # [ as a character
+                ''', re.VERBOSE)
+
+    # list or matrix pattern (for future usage)
+    ARG_MTRX_PATTERN = re.compile(r'''
+                \{.*\}
+                ''', re.VERBOSE)
+
+    # regex string for function argument pattern
+    ARGS_PATTERN_TEMPLATE = r'''
+                (?:
+                \A|(?<=[^a-zA-Z])
+                )
+                {arguments}         # model argument like x, y,...
+                (?=[^a-zA-Z])
+                '''
+
+    # will contain transformed CORRESPONDENCES dictionary
+    TRANSLATIONS: dict[tuple[str, int], dict[str, Any]] = {}
+
+    # cache for a raw users' translation dictionary
+    cache_original: dict[tuple[str, int], dict[str, Any]] = {}
+
+    # cache for a compiled users' translation dictionary
+    cache_compiled: dict[tuple[str, int], dict[str, Any]] = {}
+
+    @classmethod
+    def _initialize_class(cls):
+        # get a transformed CORRESPONDENCES dictionary
+        d = cls._compile_dictionary(cls.CORRESPONDENCES)
+        cls.TRANSLATIONS.update(d)
+
+    def __init__(self, additional_translations=None):
+        self.translations = {}
+
+        # update with TRANSLATIONS (class constant)
+        self.translations.update(self.TRANSLATIONS)
+
+        if additional_translations is None:
+            additional_translations = {}
+
+        # check the latest added translations
+        if self.__class__.cache_original != additional_translations:
+            if not isinstance(additional_translations, dict):
+                raise ValueError('The argument must be dict type')
+
+            # get a transformed additional_translations dictionary
+            d = self._compile_dictionary(additional_translations)
+
+            # update cache
+            self.__class__.cache_original = additional_translations
+            self.__class__.cache_compiled = d
+
+        # merge user's own translations
+        self.translations.update(self.__class__.cache_compiled)
+
+    @classmethod
+    def _compile_dictionary(cls, dic):
+        # for return
+        d = {}
+
+        for fm, fs in dic.items():
+            # check function form
+            cls._check_input(fm)
+            cls._check_input(fs)
+
+            # uncover '*' hiding behind a whitespace
+            fm = cls._apply_rules(fm, 'whitespace')
+            fs = cls._apply_rules(fs, 'whitespace')
+
+            # remove whitespace(s)
+            fm = cls._replace(fm, ' ')
+            fs = cls._replace(fs, ' ')
+
+            # search Mathematica function name
+            m = cls.FM_PATTERN.search(fm)
+
+            # if no-hit
+            if m is None:
+                err = "'{f}' function form is invalid.".format(f=fm)
+                raise ValueError(err)
+
+            # get Mathematica function name like 'Log'
+            fm_name = m.group()
+
+            # get arguments of Mathematica function
+            args, end = cls._get_args(m)
+
+            # function side check. (e.g.) '2*Func[x]' is invalid.
+            if m.start() != 0 or end != len(fm):
+                err = "'{f}' function form is invalid.".format(f=fm)
+                raise ValueError(err)
+
+            # check the last argument's 1st character
+            if args[-1][0] == '*':
+                key_arg = '*'
+            else:
+                key_arg = len(args)
+
+            key = (fm_name, key_arg)
+
+            # convert '*x' to '\\*x' for regex
+            re_args = [x if x[0] != '*' else '\\' + x for x in args]
+
+            # for regex. Example: (?:(x|y|z))
+            xyz = '(?:(' + '|'.join(re_args) + '))'
+
+            # string for regex compile
+            patStr = cls.ARGS_PATTERN_TEMPLATE.format(arguments=xyz)
+
+            pat = re.compile(patStr, re.VERBOSE)
+
+            # update dictionary
+            d[key] = {}
+            d[key]['fs'] = fs  # SymPy function template
+            d[key]['args'] = args  # args are ['x', 'y'] for example
+            d[key]['pat'] = pat
+
+        return d
+
+    def _convert_function(self, s):
+        '''Parse Mathematica function to SymPy one'''
+
+        # compiled regex object
+        pat = self.FM_PATTERN
+
+        scanned = ''                # converted string
+        cur = 0                     # position cursor
+        while True:
+            m = pat.search(s)
+
+            if m is None:
+                # append the rest of string
+                scanned += s
+                break
+
+            # get Mathematica function name
+            fm = m.group()
+
+            # get arguments, and the end position of fm function
+            args, end = self._get_args(m)
+
+            # the start position of fm function
+            bgn = m.start()
+
+            # convert Mathematica function to SymPy one
+            s = self._convert_one_function(s, fm, args, bgn, end)
+
+            # update cursor
+            cur = bgn
+
+            # append converted part
+            scanned += s[:cur]
+
+            # shrink s
+            s = s[cur:]
+
+        return scanned
+
+    def _convert_one_function(self, s, fm, args, bgn, end):
+        # no variable-length argument
+        if (fm, len(args)) in self.translations:
+            key = (fm, len(args))
+
+            # x, y,... model arguments
+            x_args = self.translations[key]['args']
+
+            # make CORRESPONDENCES between model arguments and actual ones
+            d = dict(zip(x_args, args))
+
+        # with variable-length argument
+        elif (fm, '*') in self.translations:
+            key = (fm, '*')
+
+            # x, y,..*args (model arguments)
+            x_args = self.translations[key]['args']
+
+            # make CORRESPONDENCES between model arguments and actual ones
+            d = {}
+            for i, x in enumerate(x_args):
+                if x[0] == '*':
+                    d[x] = ','.join(args[i:])
+                    break
+                d[x] = args[i]
+
+        # out of self.translations
+        else:
+            err = "'{f}' is out of the whitelist.".format(f=fm)
+            raise ValueError(err)
+
+        # template string of converted function
+        template = self.translations[key]['fs']
+
+        # regex pattern for x_args
+        pat = self.translations[key]['pat']
+
+        scanned = ''
+        cur = 0
+        while True:
+            m = pat.search(template)
+
+            if m is None:
+                scanned += template
+                break
+
+            # get model argument
+            x = m.group()
+
+            # get a start position of the model argument
+            xbgn = m.start()
+
+            # add the corresponding actual argument
+            scanned += template[:xbgn] + d[x]
+
+            # update cursor to the end of the model argument
+            cur = m.end()
+
+            # shrink template
+            template = template[cur:]
+
+        # update to swapped string
+        s = s[:bgn] + scanned + s[end:]
+
+        return s
+
+    @classmethod
+    def _get_args(cls, m):
+        '''Get arguments of a Mathematica function'''
+
+        s = m.string                # whole string
+        anc = m.end() + 1           # pointing the first letter of arguments
+        square, curly = [], []      # stack for brackets
+        args = []
+
+        # current cursor
+        cur = anc
+        for i, c in enumerate(s[anc:], anc):
+            # extract one argument
+            if c == ',' and (not square) and (not curly):
+                args.append(s[cur:i])       # add an argument
+                cur = i + 1                 # move cursor
+
+            # handle list or matrix (for future usage)
+            if c == '{':
+                curly.append(c)
+            elif c == '}':
+                curly.pop()
+
+            # seek corresponding ']' with skipping irrevant ones
+            if c == '[':
+                square.append(c)
+            elif c == ']':
+                if square:
+                    square.pop()
+                else:   # empty stack
+                    args.append(s[cur:i])
+                    break
+
+        # the next position to ']' bracket (the function end)
+        func_end = i + 1
+
+        return args, func_end
+
+    @classmethod
+    def _replace(cls, s, bef):
+        aft = cls.REPLACEMENTS[bef]
+        s = s.replace(bef, aft)
+        return s
+
+    @classmethod
+    def _apply_rules(cls, s, bef):
+        pat, aft = cls.RULES[bef]
+        return pat.sub(aft, s)
+
+    @classmethod
+    def _check_input(cls, s):
+        for bracket in (('[', ']'), ('{', '}'), ('(', ')')):
+            if s.count(bracket[0]) != s.count(bracket[1]):
+                err = "'{f}' function form is invalid.".format(f=s)
+                raise ValueError(err)
+
+        if '{' in s:
+            err = "Currently list is not supported."
+            raise ValueError(err)
+
+    def _parse_old(self, s):
+        # input check
+        self._check_input(s)
+
+        # uncover '*' hiding behind a whitespace
+        s = self._apply_rules(s, 'whitespace')
+
+        # remove whitespace(s)
+        s = self._replace(s, ' ')
+
+        # add omitted '*' character
+        s = self._apply_rules(s, 'add*_1')
+        s = self._apply_rules(s, 'add*_2')
+
+        # translate function
+        s = self._convert_function(s)
+
+        # '^' to '**'
+        s = self._replace(s, '^')
+
+        # 'Pi' to 'pi'
+        s = self._apply_rules(s, 'Pi')
+
+        # '{', '}' to '[', ']', respectively
+#        s = cls._replace(s, '{')   # currently list is not taken into account
+#        s = cls._replace(s, '}')
+
+        return s
+
+    def parse(self, s):
+        s2 = self._from_mathematica_to_tokens(s)
+        s3 = self._from_tokens_to_fullformlist(s2)
+        s4 = self._from_fullformlist_to_sympy(s3)
+        return s4
+
+    INFIX = "Infix"
+    PREFIX = "Prefix"
+    POSTFIX = "Postfix"
+    FLAT = "Flat"
+    RIGHT = "Right"
+    LEFT = "Left"
+
+    _mathematica_op_precedence: list[tuple[str, str | None, dict[str, str | Callable]]] = [
+        (POSTFIX, None, {";": lambda x: x + ["Null"] if isinstance(x, list) and x and x[0] == "CompoundExpression" else ["CompoundExpression", x, "Null"]}),
+        (INFIX, FLAT, {";": "CompoundExpression"}),
+        (INFIX, RIGHT, {"=": "Set", ":=": "SetDelayed", "+=": "AddTo", "-=": "SubtractFrom", "*=": "TimesBy", "/=": "DivideBy"}),
+        (INFIX, LEFT, {"//": lambda x, y: [x, y]}),
+        (POSTFIX, None, {"&": "Function"}),
+        (INFIX, LEFT, {"/.": "ReplaceAll"}),
+        (INFIX, RIGHT, {"->": "Rule", ":>": "RuleDelayed"}),
+        (INFIX, LEFT, {"/;": "Condition"}),
+        (INFIX, FLAT, {"|": "Alternatives"}),
+        (POSTFIX, None, {"..": "Repeated", "...": "RepeatedNull"}),
+        (INFIX, FLAT, {"||": "Or"}),
+        (INFIX, FLAT, {"&&": "And"}),
+        (PREFIX, None, {"!": "Not"}),
+        (INFIX, FLAT, {"===": "SameQ", "=!=": "UnsameQ"}),
+        (INFIX, FLAT, {"==": "Equal", "!=": "Unequal", "<=": "LessEqual", "<": "Less", ">=": "GreaterEqual", ">": "Greater"}),
+        (INFIX, None, {";;": "Span"}),
+        (INFIX, FLAT, {"+": "Plus", "-": "Plus"}),
+        (INFIX, FLAT, {"*": "Times", "/": "Times"}),
+        (INFIX, FLAT, {".": "Dot"}),
+        (PREFIX, None, {"-": lambda x: MathematicaParser._get_neg(x),
+                        "+": lambda x: x}),
+        (INFIX, RIGHT, {"^": "Power"}),
+        (INFIX, RIGHT, {"@@": "Apply", "/@": "Map", "//@": "MapAll", "@@@": lambda x, y: ["Apply", x, y, ["List", "1"]]}),
+        (POSTFIX, None, {"'": "Derivative", "!": "Factorial", "!!": "Factorial2", "--": "Decrement"}),
+        (INFIX, None, {"[": lambda x, y: [x, *y], "[[": lambda x, y: ["Part", x, *y]}),
+        (PREFIX, None, {"{": lambda x: ["List", *x], "(": lambda x: x[0]}),
+        (INFIX, None, {"?": "PatternTest"}),
+        (POSTFIX, None, {
+            "_": lambda x: ["Pattern", x, ["Blank"]],
+            "_.": lambda x: ["Optional", ["Pattern", x, ["Blank"]]],
+            "__": lambda x: ["Pattern", x, ["BlankSequence"]],
+            "___": lambda x: ["Pattern", x, ["BlankNullSequence"]],
+        }),
+        (INFIX, None, {"_": lambda x, y: ["Pattern", x, ["Blank", y]]}),
+        (PREFIX, None, {"#": "Slot", "##": "SlotSequence"}),
+    ]
+
+    _missing_arguments_default = {
+        "#": lambda: ["Slot", "1"],
+        "##": lambda: ["SlotSequence", "1"],
+    }
+
+    _literal = r"[A-Za-z][A-Za-z0-9]*"
+    _number = r"(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)"
+
+    _enclosure_open = ["(", "[", "[[", "{"]
+    _enclosure_close = [")", "]", "]]", "}"]
+
+    @classmethod
+    def _get_neg(cls, x):
+        return f"-{x}" if isinstance(x, str) and re.match(MathematicaParser._number, x) else ["Times", "-1", x]
+
+    @classmethod
+    def _get_inv(cls, x):
+        return ["Power", x, "-1"]
+
+    _regex_tokenizer = None
+
+    def _get_tokenizer(self):
+        if self._regex_tokenizer is not None:
+            # Check if the regular expression has already been compiled:
+            return self._regex_tokenizer
+        tokens = [self._literal, self._number]
+        tokens_escape = self._enclosure_open[:] + self._enclosure_close[:]
+        for typ, strat, symdict in self._mathematica_op_precedence:
+            for k in symdict:
+                tokens_escape.append(k)
+        tokens_escape.sort(key=lambda x: -len(x))
+        tokens.extend(map(re.escape, tokens_escape))
+        tokens.append(",")
+        tokens.append("\n")
+        tokenizer = re.compile("(" + "|".join(tokens) + ")")
+        self._regex_tokenizer = tokenizer
+        return self._regex_tokenizer
+
+    def _from_mathematica_to_tokens(self, code: str):
+        tokenizer = self._get_tokenizer()
+
+        # Find strings:
+        code_splits: list[str | list] = []
+        while True:
+            string_start = code.find("\"")
+            if string_start == -1:
+                if len(code) > 0:
+                    code_splits.append(code)
+                break
+            match_end = re.search(r'(? 0:
+                code_splits.append(code[:string_start])
+            code_splits.append(["_Str", code[string_start+1:string_end].replace('\\"', '"')])
+            code = code[string_end+1:]
+
+        # Remove comments:
+        for i, code_split in enumerate(code_splits):
+            if isinstance(code_split, list):
+                continue
+            while True:
+                pos_comment_start = code_split.find("(*")
+                if pos_comment_start == -1:
+                    break
+                pos_comment_end = code_split.find("*)")
+                if pos_comment_end == -1 or pos_comment_end < pos_comment_start:
+                    raise SyntaxError("mismatch in comment (*  *) code")
+                code_split = code_split[:pos_comment_start] + code_split[pos_comment_end+2:]
+            code_splits[i] = code_split
+
+        # Tokenize the input strings with a regular expression:
+        token_lists = [tokenizer.findall(i) if isinstance(i, str) and i.isascii() else [i] for i in code_splits]
+        tokens = [j for i in token_lists for j in i]
+
+        # Remove newlines at the beginning
+        while tokens and tokens[0] == "\n":
+            tokens.pop(0)
+        # Remove newlines at the end
+        while tokens and tokens[-1] == "\n":
+            tokens.pop(-1)
+
+        return tokens
+
+    def _is_op(self, token: str | list) -> bool:
+        if isinstance(token, list):
+            return False
+        if re.match(self._literal, token):
+            return False
+        if re.match("-?" + self._number, token):
+            return False
+        return True
+
+    def _is_valid_star1(self, token: str | list) -> bool:
+        if token in (")", "}"):
+            return True
+        return not self._is_op(token)
+
+    def _is_valid_star2(self, token: str | list) -> bool:
+        if token in ("(", "{"):
+            return True
+        return not self._is_op(token)
+
+    def _from_tokens_to_fullformlist(self, tokens: list):
+        stack: list[list] = [[]]
+        open_seq = []
+        pointer: int = 0
+        while pointer < len(tokens):
+            token = tokens[pointer]
+            if token in self._enclosure_open:
+                stack[-1].append(token)
+                open_seq.append(token)
+                stack.append([])
+            elif token == ",":
+                if len(stack[-1]) == 0 and stack[-2][-1] == open_seq[-1]:
+                    raise SyntaxError("%s cannot be followed by comma ," % open_seq[-1])
+                stack[-1] = self._parse_after_braces(stack[-1])
+                stack.append([])
+            elif token in self._enclosure_close:
+                ind = self._enclosure_close.index(token)
+                if self._enclosure_open[ind] != open_seq[-1]:
+                    unmatched_enclosure = SyntaxError("unmatched enclosure")
+                    if token == "]]" and open_seq[-1] == "[":
+                        if open_seq[-2] == "[":
+                            # These two lines would be logically correct, but are
+                            # unnecessary:
+                            # token = "]"
+                            # tokens[pointer] = "]"
+                            tokens.insert(pointer+1, "]")
+                        elif open_seq[-2] == "[[":
+                            if tokens[pointer+1] == "]":
+                                tokens[pointer+1] = "]]"
+                            elif tokens[pointer+1] == "]]":
+                                tokens[pointer+1] = "]]"
+                                tokens.insert(pointer+2, "]")
+                            else:
+                                raise unmatched_enclosure
+                    else:
+                        raise unmatched_enclosure
+                if len(stack[-1]) == 0 and stack[-2][-1] == "(":
+                    raise SyntaxError("( ) not valid syntax")
+                last_stack = self._parse_after_braces(stack[-1], True)
+                stack[-1] = last_stack
+                new_stack_element = []
+                while stack[-1][-1] != open_seq[-1]:
+                    new_stack_element.append(stack.pop())
+                new_stack_element.reverse()
+                if open_seq[-1] == "(" and len(new_stack_element) != 1:
+                    raise SyntaxError("( must be followed by one expression, %i detected" % len(new_stack_element))
+                stack[-1].append(new_stack_element)
+                open_seq.pop(-1)
+            else:
+                stack[-1].append(token)
+            pointer += 1
+        if len(stack) != 1:
+            raise RuntimeError("Stack should have only one element")
+        return self._parse_after_braces(stack[0])
+
+    def _util_remove_newlines(self, lines: list, tokens: list, inside_enclosure: bool):
+        pointer = 0
+        size = len(tokens)
+        while pointer < size:
+            token = tokens[pointer]
+            if token == "\n":
+                if inside_enclosure:
+                    # Ignore newlines inside enclosures
+                    tokens.pop(pointer)
+                    size -= 1
+                    continue
+                if pointer == 0:
+                    tokens.pop(0)
+                    size -= 1
+                    continue
+                if pointer > 1:
+                    try:
+                        prev_expr = self._parse_after_braces(tokens[:pointer], inside_enclosure)
+                    except SyntaxError:
+                        tokens.pop(pointer)
+                        size -= 1
+                        continue
+                else:
+                    prev_expr = tokens[0]
+                if len(prev_expr) > 0 and prev_expr[0] == "CompoundExpression":
+                    lines.extend(prev_expr[1:])
+                else:
+                    lines.append(prev_expr)
+                for i in range(pointer):
+                    tokens.pop(0)
+                size -= pointer
+                pointer = 0
+                continue
+            pointer += 1
+
+    def _util_add_missing_asterisks(self, tokens: list):
+        size: int = len(tokens)
+        pointer: int = 0
+        while pointer < size:
+            if (pointer > 0 and
+                    self._is_valid_star1(tokens[pointer - 1]) and
+                    self._is_valid_star2(tokens[pointer])):
+                # This is a trick to add missing * operators in the expression,
+                # `"*" in op_dict` makes sure the precedence level is the same as "*",
+                # while `not self._is_op( ... )` makes sure this and the previous
+                # expression are not operators.
+                if tokens[pointer] == "(":
+                    # ( has already been processed by now, replace:
+                    tokens[pointer] = "*"
+                    tokens[pointer + 1] = tokens[pointer + 1][0]
+                else:
+                    tokens.insert(pointer, "*")
+                    pointer += 1
+                    size += 1
+            pointer += 1
+
+    def _parse_after_braces(self, tokens: list, inside_enclosure: bool = False):
+        op_dict: dict
+        changed: bool = False
+        lines: list = []
+
+        self._util_remove_newlines(lines, tokens, inside_enclosure)
+
+        for op_type, grouping_strat, op_dict in reversed(self._mathematica_op_precedence):
+            if "*" in op_dict:
+                self._util_add_missing_asterisks(tokens)
+            size: int = len(tokens)
+            pointer: int = 0
+            while pointer < size:
+                token = tokens[pointer]
+                if isinstance(token, str) and token in op_dict:
+                    op_name: str | Callable = op_dict[token]
+                    node: list
+                    first_index: int
+                    if isinstance(op_name, str):
+                        node = [op_name]
+                        first_index = 1
+                    else:
+                        node = []
+                        first_index = 0
+                    if token in ("+", "-") and op_type == self.PREFIX and pointer > 0 and not self._is_op(tokens[pointer - 1]):
+                        # Make sure that PREFIX + - don't match expressions like a + b or a - b,
+                        # the INFIX + - are supposed to match that expression:
+                        pointer += 1
+                        continue
+                    if op_type == self.INFIX:
+                        if pointer == 0 or pointer == size - 1 or self._is_op(tokens[pointer - 1]) or self._is_op(tokens[pointer + 1]):
+                            pointer += 1
+                            continue
+                    changed = True
+                    tokens[pointer] = node
+                    if op_type == self.INFIX:
+                        arg1 = tokens.pop(pointer-1)
+                        arg2 = tokens.pop(pointer)
+                        if token == "/":
+                            arg2 = self._get_inv(arg2)
+                        elif token == "-":
+                            arg2 = self._get_neg(arg2)
+                        pointer -= 1
+                        size -= 2
+                        node.append(arg1)
+                        node_p = node
+                        if grouping_strat == self.FLAT:
+                            while pointer + 2 < size and self._check_op_compatible(tokens[pointer+1], token):
+                                node_p.append(arg2)
+                                other_op = tokens.pop(pointer+1)
+                                arg2 = tokens.pop(pointer+1)
+                                if other_op == "/":
+                                    arg2 = self._get_inv(arg2)
+                                elif other_op == "-":
+                                    arg2 = self._get_neg(arg2)
+                                size -= 2
+                            node_p.append(arg2)
+                        elif grouping_strat == self.RIGHT:
+                            while pointer + 2 < size and tokens[pointer+1] == token:
+                                node_p.append([op_name, arg2])
+                                node_p = node_p[-1]
+                                tokens.pop(pointer+1)
+                                arg2 = tokens.pop(pointer+1)
+                                size -= 2
+                            node_p.append(arg2)
+                        elif grouping_strat == self.LEFT:
+                            while pointer + 1 < size and tokens[pointer+1] == token:
+                                if isinstance(op_name, str):
+                                    node_p[first_index] = [op_name, node_p[first_index], arg2]
+                                else:
+                                    node_p[first_index] = op_name(node_p[first_index], arg2)
+                                tokens.pop(pointer+1)
+                                arg2 = tokens.pop(pointer+1)
+                                size -= 2
+                            node_p.append(arg2)
+                        else:
+                            node.append(arg2)
+                    elif op_type == self.PREFIX:
+                        if grouping_strat is not None:
+                            raise TypeError("'Prefix' op_type should not have a grouping strat")
+                        if pointer == size - 1 or self._is_op(tokens[pointer + 1]):
+                            tokens[pointer] = self._missing_arguments_default[token]()
+                        else:
+                            node.append(tokens.pop(pointer+1))
+                            size -= 1
+                    elif op_type == self.POSTFIX:
+                        if grouping_strat is not None:
+                            raise TypeError("'Prefix' op_type should not have a grouping strat")
+                        if pointer == 0 or self._is_op(tokens[pointer - 1]):
+                            tokens[pointer] = self._missing_arguments_default[token]()
+                        else:
+                            node.append(tokens.pop(pointer-1))
+                            pointer -= 1
+                            size -= 1
+                    if isinstance(op_name, Callable):  # type: ignore
+                        op_call: Callable = typing.cast(Callable, op_name)
+                        new_node = op_call(*node)
+                        node.clear()
+                        if isinstance(new_node, list):
+                            node.extend(new_node)
+                        else:
+                            tokens[pointer] = new_node
+                pointer += 1
+        if len(tokens) > 1 or (len(lines) == 0 and len(tokens) == 0):
+            if changed:
+                # Trick to deal with cases in which an operator with lower
+                # precedence should be transformed before an operator of higher
+                # precedence. Such as in the case of `#&[x]` (that is
+                # equivalent to `Lambda(d_, d_)(x)` in SymPy). In this case the
+                # operator `&` has lower precedence than `[`, but needs to be
+                # evaluated first because otherwise `# (&[x])` is not a valid
+                # expression:
+                return self._parse_after_braces(tokens, inside_enclosure)
+            raise SyntaxError("unable to create a single AST for the expression")
+        if len(lines) > 0:
+            if tokens[0] and tokens[0][0] == "CompoundExpression":
+                tokens = tokens[0][1:]
+            compound_expression = ["CompoundExpression", *lines, *tokens]
+            return compound_expression
+        return tokens[0]
+
+    def _check_op_compatible(self, op1: str, op2: str):
+        if op1 == op2:
+            return True
+        muldiv = {"*", "/"}
+        addsub = {"+", "-"}
+        if op1 in muldiv and op2 in muldiv:
+            return True
+        if op1 in addsub and op2 in addsub:
+            return True
+        return False
+
+    def _from_fullform_to_fullformlist(self, wmexpr: str):
+        """
+        Parses FullForm[Downvalues[]] generated by Mathematica
+        """
+        out: list = []
+        stack = [out]
+        generator = re.finditer(r'[\[\],]', wmexpr)
+        last_pos = 0
+        for match in generator:
+            if match is None:
+                break
+            position = match.start()
+            last_expr = wmexpr[last_pos:position].replace(',', '').replace(']', '').replace('[', '').strip()
+
+            if match.group() == ',':
+                if last_expr != '':
+                    stack[-1].append(last_expr)
+            elif match.group() == ']':
+                if last_expr != '':
+                    stack[-1].append(last_expr)
+                stack.pop()
+            elif match.group() == '[':
+                stack[-1].append([last_expr])
+                stack.append(stack[-1][-1])
+            last_pos = match.end()
+        return out[0]
+
+    def _from_fullformlist_to_fullformsympy(self, pylist: list):
+        from sympy import Function, Symbol
+
+        def converter(expr):
+            if isinstance(expr, list):
+                if len(expr) > 0:
+                    head = expr[0]
+                    args = [converter(arg) for arg in expr[1:]]
+                    return Function(head)(*args)
+                else:
+                    raise ValueError("Empty list of expressions")
+            elif isinstance(expr, str):
+                return Symbol(expr)
+            else:
+                return _sympify(expr)
+
+        return converter(pylist)
+
+    _node_conversions = {
+        "Times": Mul,
+        "Plus": Add,
+        "Power": Pow,
+        "Rational": Rational,
+        "Log": lambda *a: log(*reversed(a)),
+        "Log2": lambda x: log(x, 2),
+        "Log10": lambda x: log(x, 10),
+        "Exp": exp,
+        "Sqrt": sqrt,
+
+        "Sin": sin,
+        "Cos": cos,
+        "Tan": tan,
+        "Cot": cot,
+        "Sec": sec,
+        "Csc": csc,
+
+        "ArcSin": asin,
+        "ArcCos": acos,
+        "ArcTan": lambda *a: atan2(*reversed(a)) if len(a) == 2 else atan(*a),
+        "ArcCot": acot,
+        "ArcSec": asec,
+        "ArcCsc": acsc,
+
+        "Sinh": sinh,
+        "Cosh": cosh,
+        "Tanh": tanh,
+        "Coth": coth,
+        "Sech": sech,
+        "Csch": csch,
+
+        "ArcSinh": asinh,
+        "ArcCosh": acosh,
+        "ArcTanh": atanh,
+        "ArcCoth": acoth,
+        "ArcSech": asech,
+        "ArcCsch": acsch,
+
+        "Expand": expand,
+        "Im": im,
+        "Re": sympy.re,
+        "Flatten": flatten,
+        "Polylog": polylog,
+        "Cancel": cancel,
+        # Gamma=gamma,
+        "TrigExpand": expand_trig,
+        "Sign": sign,
+        "Simplify": simplify,
+        "Defer": UnevaluatedExpr,
+        "Identity": S,
+        # Sum=Sum_doit,
+        # Module=With,
+        # Block=With,
+        "Null": lambda *a: S.Zero,
+        "Mod": Mod,
+        "Max": Max,
+        "Min": Min,
+        "Pochhammer": rf,
+        "ExpIntegralEi": Ei,
+        "SinIntegral": Si,
+        "CosIntegral": Ci,
+        "AiryAi": airyai,
+        "AiryAiPrime": airyaiprime,
+        "AiryBi": airybi,
+        "AiryBiPrime": airybiprime,
+        "LogIntegral": li,
+        "PrimePi": primepi,
+        "Prime": prime,
+        "PrimeQ": isprime,
+
+        "List": Tuple,
+        "Greater": StrictGreaterThan,
+        "GreaterEqual": GreaterThan,
+        "Less": StrictLessThan,
+        "LessEqual": LessThan,
+        "Equal": Equality,
+        "Or": Or,
+        "And": And,
+
+        "Function": _parse_Function,
+    }
+
+    _atom_conversions = {
+        "I": I,
+        "Pi": pi,
+    }
+
+    def _from_fullformlist_to_sympy(self, full_form_list):
+
+        def recurse(expr):
+            if isinstance(expr, list):
+                if isinstance(expr[0], list):
+                    head = recurse(expr[0])
+                else:
+                    head = self._node_conversions.get(expr[0], Function(expr[0]))
+                return head(*[recurse(arg) for arg in expr[1:]])
+            else:
+                return self._atom_conversions.get(expr, sympify(expr))
+
+        return recurse(full_form_list)
+
+    def _from_fullformsympy_to_sympy(self, mform):
+
+        expr = mform
+        for mma_form, sympy_node in self._node_conversions.items():
+            expr = expr.replace(Function(mma_form), sympy_node)
+        return expr
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/maxima.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/maxima.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a8ee5b17bb03a36e338803cb10f9ebf22763c2c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/maxima.py
@@ -0,0 +1,71 @@
+import re
+from sympy.concrete.products import product
+from sympy.concrete.summations import Sum
+from sympy.core.sympify import sympify
+from sympy.functions.elementary.trigonometric import (cos, sin)
+
+
+class MaximaHelpers:
+    def maxima_expand(expr):
+        return expr.expand()
+
+    def maxima_float(expr):
+        return expr.evalf()
+
+    def maxima_trigexpand(expr):
+        return expr.expand(trig=True)
+
+    def maxima_sum(a1, a2, a3, a4):
+        return Sum(a1, (a2, a3, a4)).doit()
+
+    def maxima_product(a1, a2, a3, a4):
+        return product(a1, (a2, a3, a4))
+
+    def maxima_csc(expr):
+        return 1/sin(expr)
+
+    def maxima_sec(expr):
+        return 1/cos(expr)
+
+sub_dict = {
+    'pi': re.compile(r'%pi'),
+    'E': re.compile(r'%e'),
+    'I': re.compile(r'%i'),
+    '**': re.compile(r'\^'),
+    'oo': re.compile(r'\binf\b'),
+    '-oo': re.compile(r'\bminf\b'),
+    "'-'": re.compile(r'\bminus\b'),
+    'maxima_expand': re.compile(r'\bexpand\b'),
+    'maxima_float': re.compile(r'\bfloat\b'),
+    'maxima_trigexpand': re.compile(r'\btrigexpand'),
+    'maxima_sum': re.compile(r'\bsum\b'),
+    'maxima_product': re.compile(r'\bproduct\b'),
+    'cancel': re.compile(r'\bratsimp\b'),
+    'maxima_csc': re.compile(r'\bcsc\b'),
+    'maxima_sec': re.compile(r'\bsec\b')
+}
+
+var_name = re.compile(r'^\s*(\w+)\s*:')
+
+
+def parse_maxima(str, globals=None, name_dict={}):
+    str = str.strip()
+    str = str.rstrip('; ')
+
+    for k, v in sub_dict.items():
+        str = v.sub(k, str)
+
+    assign_var = None
+    var_match = var_name.search(str)
+    if var_match:
+        assign_var = var_match.group(1)
+        str = str[var_match.end():].strip()
+
+    dct = MaximaHelpers.__dict__.copy()
+    dct.update(name_dict)
+    obj = sympify(str, locals=dct)
+
+    if assign_var and globals:
+        globals[assign_var] = obj
+
+    return obj
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/sym_expr.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/sym_expr.py
new file mode 100644
index 0000000000000000000000000000000000000000..9dbd0e94eb51147b51825fcf15cbec5ae18bb1b6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/sym_expr.py
@@ -0,0 +1,279 @@
+from sympy.printing import pycode, ccode, fcode
+from sympy.external import import_module
+from sympy.utilities.decorator import doctest_depends_on
+
+lfortran = import_module('lfortran')
+cin = import_module('clang.cindex', import_kwargs = {'fromlist': ['cindex']})
+
+if lfortran:
+    from sympy.parsing.fortran.fortran_parser import src_to_sympy
+if cin:
+    from sympy.parsing.c.c_parser import parse_c
+
+@doctest_depends_on(modules=['lfortran', 'clang.cindex'])
+class SymPyExpression:  # type: ignore
+    """Class to store and handle SymPy expressions
+
+    This class will hold SymPy Expressions and handle the API for the
+    conversion to and from different languages.
+
+    It works with the C and the Fortran Parser to generate SymPy expressions
+    which are stored here and which can be converted to multiple language's
+    source code.
+
+    Notes
+    =====
+
+    The module and its API are currently under development and experimental
+    and can be changed during development.
+
+    The Fortran parser does not support numeric assignments, so all the
+    variables have been Initialized to zero.
+
+    The module also depends on external dependencies:
+
+    - LFortran which is required to use the Fortran parser
+    - Clang which is required for the C parser
+
+    Examples
+    ========
+
+    Example of parsing C code:
+
+    >>> from sympy.parsing.sym_expr import SymPyExpression
+    >>> src = '''
+    ... int a,b;
+    ... float c = 2, d =4;
+    ... '''
+    >>> a = SymPyExpression(src, 'c')
+    >>> a.return_expr()
+    [Declaration(Variable(a, type=intc)),
+    Declaration(Variable(b, type=intc)),
+    Declaration(Variable(c, type=float32, value=2.0)),
+    Declaration(Variable(d, type=float32, value=4.0))]
+
+    An example of variable definition:
+
+    >>> from sympy.parsing.sym_expr import SymPyExpression
+    >>> src2 = '''
+    ... integer :: a, b, c, d
+    ... real :: p, q, r, s
+    ... '''
+    >>> p = SymPyExpression()
+    >>> p.convert_to_expr(src2, 'f')
+    >>> p.convert_to_c()
+    ['int a = 0', 'int b = 0', 'int c = 0', 'int d = 0', 'double p = 0.0', 'double q = 0.0', 'double r = 0.0', 'double s = 0.0']
+
+    An example of Assignment:
+
+    >>> from sympy.parsing.sym_expr import SymPyExpression
+    >>> src3 = '''
+    ... integer :: a, b, c, d, e
+    ... d = a + b - c
+    ... e = b * d + c * e / a
+    ... '''
+    >>> p = SymPyExpression(src3, 'f')
+    >>> p.convert_to_python()
+    ['a = 0', 'b = 0', 'c = 0', 'd = 0', 'e = 0', 'd = a + b - c', 'e = b*d + c*e/a']
+
+    An example of function definition:
+
+    >>> from sympy.parsing.sym_expr import SymPyExpression
+    >>> src = '''
+    ... integer function f(a,b)
+    ... integer, intent(in) :: a, b
+    ... integer :: r
+    ... end function
+    ... '''
+    >>> a = SymPyExpression(src, 'f')
+    >>> a.convert_to_python()
+    ['def f(a, b):\\n   f = 0\\n    r = 0\\n    return f']
+
+    """
+
+    def __init__(self, source_code = None, mode = None):
+        """Constructor for SymPyExpression class"""
+        super().__init__()
+        if not(mode or source_code):
+            self._expr = []
+        elif mode:
+            if source_code:
+                if mode.lower() == 'f':
+                    if lfortran:
+                        self._expr = src_to_sympy(source_code)
+                    else:
+                        raise ImportError("LFortran is not installed, cannot parse Fortran code")
+                elif mode.lower() == 'c':
+                    if cin:
+                        self._expr = parse_c(source_code)
+                    else:
+                        raise ImportError("Clang is not installed, cannot parse C code")
+                else:
+                    raise NotImplementedError(
+                        'Parser for specified language is not implemented'
+                    )
+            else:
+                raise ValueError('Source code not present')
+        else:
+            raise ValueError('Please specify a mode for conversion')
+
+    def convert_to_expr(self, src_code, mode):
+        """Converts the given source code to SymPy Expressions
+
+        Attributes
+        ==========
+
+        src_code : String
+            the source code or filename of the source code that is to be
+            converted
+
+        mode: String
+            the mode to determine which parser is to be used according to
+            the language of the source code
+            f or F for Fortran
+            c or C for C/C++
+
+        Examples
+        ========
+
+        >>> from sympy.parsing.sym_expr import SymPyExpression
+        >>> src3 = '''
+        ... integer function f(a,b) result(r)
+        ... integer, intent(in) :: a, b
+        ... integer :: x
+        ... r = a + b -x
+        ... end function
+        ... '''
+        >>> p = SymPyExpression()
+        >>> p.convert_to_expr(src3, 'f')
+        >>> p.return_expr()
+        [FunctionDefinition(integer, name=f, parameters=(Variable(a), Variable(b)), body=CodeBlock(
+        Declaration(Variable(r, type=integer, value=0)),
+        Declaration(Variable(x, type=integer, value=0)),
+        Assignment(Variable(r), a + b - x),
+        Return(Variable(r))
+        ))]
+
+
+
+
+        """
+        if mode.lower() == 'f':
+            if lfortran:
+                self._expr = src_to_sympy(src_code)
+            else:
+                raise ImportError("LFortran is not installed, cannot parse Fortran code")
+        elif mode.lower() == 'c':
+            if cin:
+                self._expr = parse_c(src_code)
+            else:
+                raise ImportError("Clang is not installed, cannot parse C code")
+        else:
+            raise NotImplementedError(
+                "Parser for specified language has not been implemented"
+            )
+
+    def convert_to_python(self):
+        """Returns a list with Python code for the SymPy expressions
+
+        Examples
+        ========
+
+        >>> from sympy.parsing.sym_expr import SymPyExpression
+        >>> src2 = '''
+        ... integer :: a, b, c, d
+        ... real :: p, q, r, s
+        ... c = a/b
+        ... d = c/a
+        ... s = p/q
+        ... r = q/p
+        ... '''
+        >>> p = SymPyExpression(src2, 'f')
+        >>> p.convert_to_python()
+        ['a = 0', 'b = 0', 'c = 0', 'd = 0', 'p = 0.0', 'q = 0.0', 'r = 0.0', 's = 0.0', 'c = a/b', 'd = c/a', 's = p/q', 'r = q/p']
+
+        """
+        self._pycode = []
+        for iter in self._expr:
+            self._pycode.append(pycode(iter))
+        return self._pycode
+
+    def convert_to_c(self):
+        """Returns a list with the c source code for the SymPy expressions
+
+
+        Examples
+        ========
+
+        >>> from sympy.parsing.sym_expr import SymPyExpression
+        >>> src2 = '''
+        ... integer :: a, b, c, d
+        ... real :: p, q, r, s
+        ... c = a/b
+        ... d = c/a
+        ... s = p/q
+        ... r = q/p
+        ... '''
+        >>> p = SymPyExpression()
+        >>> p.convert_to_expr(src2, 'f')
+        >>> p.convert_to_c()
+        ['int a = 0', 'int b = 0', 'int c = 0', 'int d = 0', 'double p = 0.0', 'double q = 0.0', 'double r = 0.0', 'double s = 0.0', 'c = a/b;', 'd = c/a;', 's = p/q;', 'r = q/p;']
+
+        """
+        self._ccode = []
+        for iter in self._expr:
+            self._ccode.append(ccode(iter))
+        return self._ccode
+
+    def convert_to_fortran(self):
+        """Returns a list with the fortran source code for the SymPy expressions
+
+        Examples
+        ========
+
+        >>> from sympy.parsing.sym_expr import SymPyExpression
+        >>> src2 = '''
+        ... integer :: a, b, c, d
+        ... real :: p, q, r, s
+        ... c = a/b
+        ... d = c/a
+        ... s = p/q
+        ... r = q/p
+        ... '''
+        >>> p = SymPyExpression(src2, 'f')
+        >>> p.convert_to_fortran()
+        ['      integer*4 a', '      integer*4 b', '      integer*4 c', '      integer*4 d', '      real*8 p', '      real*8 q', '      real*8 r', '      real*8 s', '      c = a/b', '      d = c/a', '      s = p/q', '      r = q/p']
+
+        """
+        self._fcode = []
+        for iter in self._expr:
+            self._fcode.append(fcode(iter))
+        return self._fcode
+
+    def return_expr(self):
+        """Returns the expression list
+
+        Examples
+        ========
+
+        >>> from sympy.parsing.sym_expr import SymPyExpression
+        >>> src3 = '''
+        ... integer function f(a,b)
+        ... integer, intent(in) :: a, b
+        ... integer :: r
+        ... r = a+b
+        ... f = r
+        ... end function
+        ... '''
+        >>> p = SymPyExpression()
+        >>> p.convert_to_expr(src3, 'f')
+        >>> p.return_expr()
+        [FunctionDefinition(integer, name=f, parameters=(Variable(a), Variable(b)), body=CodeBlock(
+        Declaration(Variable(f, type=integer, value=0)),
+        Declaration(Variable(r, type=integer, value=0)),
+        Assignment(Variable(f), Variable(r)),
+        Return(Variable(f))
+        ))]
+
+        """
+        return self._expr
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/sympy_parser.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/sympy_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..9cfda9ce0f73ffa3773031c48b9e9c245f69fe0b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/sympy_parser.py
@@ -0,0 +1,1270 @@
+"""Transform a string with Python-like source code into SymPy expression. """
+from __future__ import annotations
+from tokenize import (generate_tokens, untokenize, TokenError,
+    NUMBER, STRING, NAME, OP, ENDMARKER, ERRORTOKEN, NEWLINE)
+
+from keyword import iskeyword
+
+import ast
+import unicodedata
+from io import StringIO
+import builtins
+import types
+from typing import Any, Callable
+from functools import reduce
+from sympy.assumptions.ask import AssumptionKeys
+from sympy.core.basic import Basic
+from sympy.core import Symbol
+from sympy.core.function import Function
+from sympy.utilities.misc import func_name
+from sympy.functions.elementary.miscellaneous import Max, Min
+
+
+null = ''
+
+TOKEN = tuple[int, str]
+DICT = dict[str, Any]
+TRANS = Callable[[list[TOKEN], DICT, DICT], list[TOKEN]]
+
+def _token_splittable(token_name: str) -> bool:
+    """
+    Predicate for whether a token name can be split into multiple tokens.
+
+    A token is splittable if it does not contain an underscore character and
+    it is not the name of a Greek letter. This is used to implicitly convert
+    expressions like 'xyz' into 'x*y*z'.
+    """
+    if '_' in token_name:
+        return False
+    try:
+        return not unicodedata.lookup('GREEK SMALL LETTER ' + token_name)
+    except KeyError:
+        return len(token_name) > 1
+
+
+def _token_callable(token: TOKEN, local_dict: DICT, global_dict: DICT, nextToken=None):
+    """
+    Predicate for whether a token name represents a callable function.
+
+    Essentially wraps ``callable``, but looks up the token name in the
+    locals and globals.
+    """
+    func = local_dict.get(token[1])
+    if not func:
+        func = global_dict.get(token[1])
+    return callable(func) and not isinstance(func, Symbol)
+
+
+def _add_factorial_tokens(name: str, result: list[TOKEN]) -> list[TOKEN]:
+    if result == [] or result[-1][1] == '(':
+        raise TokenError()
+
+    beginning = [(NAME, name), (OP, '(')]
+    end = [(OP, ')')]
+
+    diff = 0
+    length = len(result)
+
+    for index, token in enumerate(result[::-1]):
+        toknum, tokval = token
+        i = length - index - 1
+
+        if tokval == ')':
+            diff += 1
+        elif tokval == '(':
+            diff -= 1
+
+        if diff == 0:
+            if i - 1 >= 0 and result[i - 1][0] == NAME:
+                return result[:i - 1] + beginning + result[i - 1:] + end
+            else:
+                return result[:i] + beginning + result[i:] + end
+
+    return result
+
+
+class ParenthesisGroup(list[TOKEN]):
+    """List of tokens representing an expression in parentheses."""
+    pass
+
+
+class AppliedFunction:
+    """
+    A group of tokens representing a function and its arguments.
+
+    `exponent` is for handling the shorthand sin^2, ln^2, etc.
+    """
+    def __init__(self, function: TOKEN, args: ParenthesisGroup, exponent=None):
+        if exponent is None:
+            exponent = []
+        self.function = function
+        self.args = args
+        self.exponent = exponent
+        self.items = ['function', 'args', 'exponent']
+
+    def expand(self) -> list[TOKEN]:
+        """Return a list of tokens representing the function"""
+        return [self.function, *self.args]
+
+    def __getitem__(self, index):
+        return getattr(self, self.items[index])
+
+    def __repr__(self):
+        return "AppliedFunction(%s, %s, %s)" % (self.function, self.args,
+                                                self.exponent)
+
+
+def _flatten(result: list[TOKEN | AppliedFunction]):
+    result2: list[TOKEN] = []
+    for tok in result:
+        if isinstance(tok, AppliedFunction):
+            result2.extend(tok.expand())
+        else:
+            result2.append(tok)
+    return result2
+
+
+def _group_parentheses(recursor: TRANS):
+    def _inner(tokens: list[TOKEN], local_dict: DICT, global_dict: DICT):
+        """Group tokens between parentheses with ParenthesisGroup.
+
+        Also processes those tokens recursively.
+
+        """
+        result: list[TOKEN | ParenthesisGroup] = []
+        stacks: list[ParenthesisGroup] = []
+        stacklevel = 0
+        for token in tokens:
+            if token[0] == OP:
+                if token[1] == '(':
+                    stacks.append(ParenthesisGroup([]))
+                    stacklevel += 1
+                elif token[1] == ')':
+                    stacks[-1].append(token)
+                    stack = stacks.pop()
+
+                    if len(stacks) > 0:
+                        # We don't recurse here since the upper-level stack
+                        # would reprocess these tokens
+                        stacks[-1].extend(stack)
+                    else:
+                        # Recurse here to handle nested parentheses
+                        # Strip off the outer parentheses to avoid an infinite loop
+                        inner = stack[1:-1]
+                        inner = recursor(inner,
+                                         local_dict,
+                                         global_dict)
+                        parenGroup = [stack[0]] + inner + [stack[-1]]
+                        result.append(ParenthesisGroup(parenGroup))
+                    stacklevel -= 1
+                    continue
+            if stacklevel:
+                stacks[-1].append(token)
+            else:
+                result.append(token)
+        if stacklevel:
+            raise TokenError("Mismatched parentheses")
+        return result
+    return _inner
+
+
+def _apply_functions(tokens: list[TOKEN | ParenthesisGroup], local_dict: DICT, global_dict: DICT):
+    """Convert a NAME token + ParenthesisGroup into an AppliedFunction.
+
+    Note that ParenthesisGroups, if not applied to any function, are
+    converted back into lists of tokens.
+
+    """
+    result: list[TOKEN | AppliedFunction] = []
+    symbol = None
+    for tok in tokens:
+        if isinstance(tok, ParenthesisGroup):
+            if symbol and _token_callable(symbol, local_dict, global_dict):
+                result[-1] = AppliedFunction(symbol, tok)
+                symbol = None
+            else:
+                result.extend(tok)
+        elif tok[0] == NAME:
+            symbol = tok
+            result.append(tok)
+        else:
+            symbol = None
+            result.append(tok)
+    return result
+
+
+def _implicit_multiplication(tokens: list[TOKEN | AppliedFunction], local_dict: DICT, global_dict: DICT):
+    """Implicitly adds '*' tokens.
+
+    Cases:
+
+    - Two AppliedFunctions next to each other ("sin(x)cos(x)")
+
+    - AppliedFunction next to an open parenthesis ("sin x (cos x + 1)")
+
+    - A close parenthesis next to an AppliedFunction ("(x+2)sin x")\
+
+    - A close parenthesis next to an open parenthesis ("(x+2)(x+3)")
+
+    - AppliedFunction next to an implicitly applied function ("sin(x)cos x")
+
+    """
+    result: list[TOKEN | AppliedFunction] = []
+    skip = False
+    for tok, nextTok in zip(tokens, tokens[1:]):
+        result.append(tok)
+        if skip:
+            skip = False
+            continue
+        if tok[0] == OP and tok[1] == '.' and nextTok[0] == NAME:
+            # Dotted name. Do not do implicit multiplication
+            skip = True
+            continue
+        if isinstance(tok, AppliedFunction):
+            if isinstance(nextTok, AppliedFunction):
+                result.append((OP, '*'))
+            elif nextTok == (OP, '('):
+                # Applied function followed by an open parenthesis
+                if tok.function[1] == "Function":
+                    tok.function = (tok.function[0], 'Symbol')
+                result.append((OP, '*'))
+            elif nextTok[0] == NAME:
+                # Applied function followed by implicitly applied function
+                result.append((OP, '*'))
+        else:
+            if tok == (OP, ')'):
+                if isinstance(nextTok, AppliedFunction):
+                    # Close parenthesis followed by an applied function
+                    result.append((OP, '*'))
+                elif nextTok[0] == NAME:
+                    # Close parenthesis followed by an implicitly applied function
+                    result.append((OP, '*'))
+                elif nextTok == (OP, '('):
+                    # Close parenthesis followed by an open parenthesis
+                    result.append((OP, '*'))
+            elif tok[0] == NAME and not _token_callable(tok, local_dict, global_dict):
+                if isinstance(nextTok, AppliedFunction) or \
+                    (nextTok[0] == NAME and _token_callable(nextTok, local_dict, global_dict)):
+                    # Constant followed by (implicitly applied) function
+                    result.append((OP, '*'))
+                elif nextTok == (OP, '('):
+                    # Constant followed by parenthesis
+                    result.append((OP, '*'))
+                elif nextTok[0] == NAME:
+                    # Constant followed by constant
+                    result.append((OP, '*'))
+    if tokens:
+        result.append(tokens[-1])
+    return result
+
+
+def _implicit_application(tokens: list[TOKEN | AppliedFunction], local_dict: DICT, global_dict: DICT):
+    """Adds parentheses as needed after functions."""
+    result: list[TOKEN | AppliedFunction] = []
+    appendParen = 0  # number of closing parentheses to add
+    skip = 0  # number of tokens to delay before adding a ')' (to
+              # capture **, ^, etc.)
+    exponentSkip = False  # skipping tokens before inserting parentheses to
+                          # work with function exponentiation
+    for tok, nextTok in zip(tokens, tokens[1:]):
+        result.append(tok)
+        if (tok[0] == NAME and nextTok[0] not in [OP, ENDMARKER, NEWLINE]):
+            if _token_callable(tok, local_dict, global_dict, nextTok):  # type: ignore
+                result.append((OP, '('))
+                appendParen += 1
+        # name followed by exponent - function exponentiation
+        elif (tok[0] == NAME and nextTok[0] == OP and nextTok[1] == '**'):
+            if _token_callable(tok, local_dict, global_dict):  # type: ignore
+                exponentSkip = True
+        elif exponentSkip:
+            # if the last token added was an applied function (i.e. the
+            # power of the function exponent) OR a multiplication (as
+            # implicit multiplication would have added an extraneous
+            # multiplication)
+            if (isinstance(tok, AppliedFunction)
+                or (tok[0] == OP and tok[1] == '*')):
+                # don't add anything if the next token is a multiplication
+                # or if there's already a parenthesis (if parenthesis, still
+                # stop skipping tokens)
+                if not (nextTok[0] == OP and nextTok[1] == '*'):
+                    if not(nextTok[0] == OP and nextTok[1] == '('):
+                        result.append((OP, '('))
+                        appendParen += 1
+                    exponentSkip = False
+        elif appendParen:
+            if nextTok[0] == OP and nextTok[1] in ('^', '**', '*'):
+                skip = 1
+                continue
+            if skip:
+                skip -= 1
+                continue
+            result.append((OP, ')'))
+            appendParen -= 1
+
+    if tokens:
+        result.append(tokens[-1])
+
+    if appendParen:
+        result.extend([(OP, ')')] * appendParen)
+    return result
+
+
+def function_exponentiation(tokens: list[TOKEN], local_dict: DICT, global_dict: DICT):
+    """Allows functions to be exponentiated, e.g. ``cos**2(x)``.
+
+    Examples
+    ========
+
+    >>> from sympy.parsing.sympy_parser import (parse_expr,
+    ... standard_transformations, function_exponentiation)
+    >>> transformations = standard_transformations + (function_exponentiation,)
+    >>> parse_expr('sin**4(x)', transformations=transformations)
+    sin(x)**4
+    """
+    result: list[TOKEN] = []
+    exponent: list[TOKEN] = []
+    consuming_exponent = False
+    level = 0
+    for tok, nextTok in zip(tokens, tokens[1:]):
+        if tok[0] == NAME and nextTok[0] == OP and nextTok[1] == '**':
+            if _token_callable(tok, local_dict, global_dict):
+                consuming_exponent = True
+        elif consuming_exponent:
+            if tok[0] == NAME and tok[1] == 'Function':
+                tok = (NAME, 'Symbol')
+            exponent.append(tok)
+
+            # only want to stop after hitting )
+            if tok[0] == nextTok[0] == OP and tok[1] == ')' and nextTok[1] == '(':
+                consuming_exponent = False
+            # if implicit multiplication was used, we may have )*( instead
+            if tok[0] == nextTok[0] == OP and tok[1] == '*' and nextTok[1] == '(':
+                consuming_exponent = False
+                del exponent[-1]
+            continue
+        elif exponent and not consuming_exponent:
+            if tok[0] == OP:
+                if tok[1] == '(':
+                    level += 1
+                elif tok[1] == ')':
+                    level -= 1
+            if level == 0:
+                result.append(tok)
+                result.extend(exponent)
+                exponent = []
+                continue
+        result.append(tok)
+    if tokens:
+        result.append(tokens[-1])
+    if exponent:
+        result.extend(exponent)
+    return result
+
+
+def split_symbols_custom(predicate: Callable[[str], bool]):
+    """Creates a transformation that splits symbol names.
+
+    ``predicate`` should return True if the symbol name is to be split.
+
+    For instance, to retain the default behavior but avoid splitting certain
+    symbol names, a predicate like this would work:
+
+
+    >>> from sympy.parsing.sympy_parser import (parse_expr, _token_splittable,
+    ... standard_transformations, implicit_multiplication,
+    ... split_symbols_custom)
+    >>> def can_split(symbol):
+    ...     if symbol not in ('list', 'of', 'unsplittable', 'names'):
+    ...             return _token_splittable(symbol)
+    ...     return False
+    ...
+    >>> transformation = split_symbols_custom(can_split)
+    >>> parse_expr('unsplittable', transformations=standard_transformations +
+    ... (transformation, implicit_multiplication))
+    unsplittable
+    """
+    def _split_symbols(tokens: list[TOKEN], local_dict: DICT, global_dict: DICT):
+        result: list[TOKEN] = []
+        split = False
+        split_previous=False
+
+        for tok in tokens:
+            if split_previous:
+                # throw out closing parenthesis of Symbol that was split
+                split_previous=False
+                continue
+            split_previous=False
+
+            if tok[0] == NAME and tok[1] in ['Symbol', 'Function']:
+                split = True
+
+            elif split and tok[0] == NAME:
+                symbol = tok[1][1:-1]
+
+                if predicate(symbol):
+                    tok_type = result[-2][1]  # Symbol or Function
+                    del result[-2:]  # Get rid of the call to Symbol
+
+                    i = 0
+                    while i < len(symbol):
+                        char = symbol[i]
+                        if char in local_dict or char in global_dict:
+                            result.append((NAME, "%s" % char))
+                        elif char.isdigit():
+                            chars = [char]
+                            for i in range(i + 1, len(symbol)):
+                                if not symbol[i].isdigit():
+                                    i -= 1
+                                    break
+                                chars.append(symbol[i])
+                            char = ''.join(chars)
+                            result.extend([(NAME, 'Number'), (OP, '('),
+                                           (NAME, "'%s'" % char), (OP, ')')])
+                        else:
+                            use = tok_type if i == len(symbol) else 'Symbol'
+                            result.extend([(NAME, use), (OP, '('),
+                                           (NAME, "'%s'" % char), (OP, ')')])
+                        i += 1
+
+                    # Set split_previous=True so will skip
+                    # the closing parenthesis of the original Symbol
+                    split = False
+                    split_previous = True
+                    continue
+
+                else:
+                    split = False
+
+            result.append(tok)
+
+        return result
+
+    return _split_symbols
+
+
+#: Splits symbol names for implicit multiplication.
+#:
+#: Intended to let expressions like ``xyz`` be parsed as ``x*y*z``. Does not
+#: split Greek character names, so ``theta`` will *not* become
+#: ``t*h*e*t*a``. Generally this should be used with
+#: ``implicit_multiplication``.
+split_symbols = split_symbols_custom(_token_splittable)
+
+
+def implicit_multiplication(tokens: list[TOKEN], local_dict: DICT,
+                            global_dict: DICT) -> list[TOKEN]:
+    """Makes the multiplication operator optional in most cases.
+
+    Use this before :func:`implicit_application`, otherwise expressions like
+    ``sin 2x`` will be parsed as ``x * sin(2)`` rather than ``sin(2*x)``.
+
+    Examples
+    ========
+
+    >>> from sympy.parsing.sympy_parser import (parse_expr,
+    ... standard_transformations, implicit_multiplication)
+    >>> transformations = standard_transformations + (implicit_multiplication,)
+    >>> parse_expr('3 x y', transformations=transformations)
+    3*x*y
+    """
+    # These are interdependent steps, so we don't expose them separately
+    res1 = _group_parentheses(implicit_multiplication)(tokens, local_dict, global_dict)
+    res2 = _apply_functions(res1, local_dict, global_dict)
+    res3 = _implicit_multiplication(res2, local_dict, global_dict)
+    result = _flatten(res3)
+    return result
+
+
+def implicit_application(tokens: list[TOKEN], local_dict: DICT,
+                         global_dict: DICT) -> list[TOKEN]:
+    """Makes parentheses optional in some cases for function calls.
+
+    Use this after :func:`implicit_multiplication`, otherwise expressions
+    like ``sin 2x`` will be parsed as ``x * sin(2)`` rather than
+    ``sin(2*x)``.
+
+    Examples
+    ========
+
+    >>> from sympy.parsing.sympy_parser import (parse_expr,
+    ... standard_transformations, implicit_application)
+    >>> transformations = standard_transformations + (implicit_application,)
+    >>> parse_expr('cot z + csc z', transformations=transformations)
+    cot(z) + csc(z)
+    """
+    res1 = _group_parentheses(implicit_application)(tokens, local_dict, global_dict)
+    res2 = _apply_functions(res1, local_dict, global_dict)
+    res3 = _implicit_application(res2, local_dict, global_dict)
+    result = _flatten(res3)
+    return result
+
+
+def implicit_multiplication_application(result: list[TOKEN], local_dict: DICT,
+                                        global_dict: DICT) -> list[TOKEN]:
+    """Allows a slightly relaxed syntax.
+
+    - Parentheses for single-argument method calls are optional.
+
+    - Multiplication is implicit.
+
+    - Symbol names can be split (i.e. spaces are not needed between
+      symbols).
+
+    - Functions can be exponentiated.
+
+    Examples
+    ========
+
+    >>> from sympy.parsing.sympy_parser import (parse_expr,
+    ... standard_transformations, implicit_multiplication_application)
+    >>> parse_expr("10sin**2 x**2 + 3xyz + tan theta",
+    ... transformations=(standard_transformations +
+    ... (implicit_multiplication_application,)))
+    3*x*y*z + 10*sin(x**2)**2 + tan(theta)
+
+    """
+    for step in (split_symbols, implicit_multiplication,
+                 implicit_application, function_exponentiation):
+        result = step(result, local_dict, global_dict)
+
+    return result
+
+
+def auto_symbol(tokens: list[TOKEN], local_dict: DICT, global_dict: DICT):
+    """Inserts calls to ``Symbol``/``Function`` for undefined variables."""
+    result: list[TOKEN] = []
+    prevTok = (-1, '')
+
+    tokens.append((-1, ''))  # so zip traverses all tokens
+    for tok, nextTok in zip(tokens, tokens[1:]):
+        tokNum, tokVal = tok
+        nextTokNum, nextTokVal = nextTok
+        if tokNum == NAME:
+            name = tokVal
+
+            if (name in ['True', 'False', 'None']
+                    or iskeyword(name)
+                    # Don't convert attribute access
+                    or (prevTok[0] == OP and prevTok[1] == '.')
+                    # Don't convert keyword arguments
+                    or (prevTok[0] == OP and prevTok[1] in ('(', ',')
+                        and nextTokNum == OP and nextTokVal == '=')
+                    # the name has already been defined
+                    or name in local_dict and local_dict[name] is not null):
+                result.append((NAME, name))
+                continue
+            elif name in local_dict:
+                local_dict.setdefault(null, set()).add(name)
+                if nextTokVal == '(':
+                    local_dict[name] = Function(name)
+                else:
+                    local_dict[name] = Symbol(name)
+                result.append((NAME, name))
+                continue
+            elif name in global_dict:
+                obj = global_dict[name]
+                if isinstance(obj, (AssumptionKeys, Basic, type)) or callable(obj):
+                    result.append((NAME, name))
+                    continue
+
+            result.extend([
+                (NAME, 'Symbol' if nextTokVal != '(' else 'Function'),
+                (OP, '('),
+                (NAME, repr(str(name))),
+                (OP, ')'),
+            ])
+        else:
+            result.append((tokNum, tokVal))
+
+        prevTok = (tokNum, tokVal)
+
+    return result
+
+
+def lambda_notation(tokens: list[TOKEN], local_dict: DICT, global_dict: DICT):
+    """Substitutes "lambda" with its SymPy equivalent Lambda().
+    However, the conversion does not take place if only "lambda"
+    is passed because that is a syntax error.
+
+    """
+    result: list[TOKEN] = []
+    flag = False
+    toknum, tokval = tokens[0]
+    tokLen = len(tokens)
+
+    if toknum == NAME and tokval == 'lambda':
+        if tokLen == 2 or tokLen == 3 and tokens[1][0] == NEWLINE:
+            # In Python 3.6.7+, inputs without a newline get NEWLINE added to
+            # the tokens
+            result.extend(tokens)
+        elif tokLen > 2:
+            result.extend([
+                (NAME, 'Lambda'),
+                (OP, '('),
+                (OP, '('),
+                (OP, ')'),
+                (OP, ')'),
+            ])
+            for tokNum, tokVal in tokens[1:]:
+                if tokNum == OP and tokVal == ':':
+                    tokVal = ','
+                    flag = True
+                if not flag and tokNum == OP and tokVal in ('*', '**'):
+                    raise TokenError("Starred arguments in lambda not supported")
+                if flag:
+                    result.insert(-1, (tokNum, tokVal))
+                else:
+                    result.insert(-2, (tokNum, tokVal))
+    else:
+        result.extend(tokens)
+
+    return result
+
+
+def factorial_notation(tokens: list[TOKEN], local_dict: DICT, global_dict: DICT):
+    """Allows standard notation for factorial."""
+    result: list[TOKEN] = []
+    nfactorial = 0
+    for toknum, tokval in tokens:
+        if toknum == OP and tokval == "!":
+            # In Python 3.12 "!" are OP instead of ERRORTOKEN
+            nfactorial += 1
+        elif toknum == ERRORTOKEN:
+            op = tokval
+            if op == '!':
+                nfactorial += 1
+            else:
+                nfactorial = 0
+                result.append((OP, op))
+        else:
+            if nfactorial == 1:
+                result = _add_factorial_tokens('factorial', result)
+            elif nfactorial == 2:
+                result = _add_factorial_tokens('factorial2', result)
+            elif nfactorial > 2:
+                raise TokenError
+            nfactorial = 0
+            result.append((toknum, tokval))
+    return result
+
+
+def convert_xor(tokens: list[TOKEN], local_dict: DICT, global_dict: DICT):
+    """Treats XOR, ``^``, as exponentiation, ``**``."""
+    result: list[TOKEN] = []
+    for toknum, tokval in tokens:
+        if toknum == OP:
+            if tokval == '^':
+                result.append((OP, '**'))
+            else:
+                result.append((toknum, tokval))
+        else:
+            result.append((toknum, tokval))
+
+    return result
+
+
+def repeated_decimals(tokens: list[TOKEN], local_dict: DICT, global_dict: DICT):
+    """
+    Allows 0.2[1] notation to represent the repeated decimal 0.2111... (19/90)
+
+    Run this before auto_number.
+
+    """
+    result: list[TOKEN] = []
+
+    def is_digit(s):
+        return all(i in '0123456789_' for i in s)
+
+    # num will running match any DECIMAL [ INTEGER ]
+    num: list[TOKEN] = []
+    for toknum, tokval in tokens:
+        if toknum == NUMBER:
+            if (not num and '.' in tokval and 'e' not in tokval.lower() and
+                'j' not in tokval.lower()):
+                num.append((toknum, tokval))
+            elif is_digit(tokval) and (len(num) == 2 or
+                    len(num) == 3 and is_digit(num[-1][1])):
+                num.append((toknum, tokval))
+            else:
+                num = []
+        elif toknum == OP:
+            if tokval == '[' and len(num) == 1:
+                num.append((OP, tokval))
+            elif tokval == ']' and len(num) >= 3:
+                num.append((OP, tokval))
+            elif tokval == '.' and not num:
+                # handle .[1]
+                num.append((NUMBER, '0.'))
+            else:
+                num = []
+        else:
+            num = []
+
+        result.append((toknum, tokval))
+
+        if num and num[-1][1] == ']':
+            # pre.post[repetend] = a + b/c + d/e where a = pre, b/c = post,
+            # and d/e = repetend
+            result = result[:-len(num)]
+            pre, post = num[0][1].split('.')
+            repetend = num[2][1]
+            if len(num) == 5:
+                repetend += num[3][1]
+
+            pre = pre.replace('_', '')
+            post = post.replace('_', '')
+            repetend = repetend.replace('_', '')
+
+            zeros = '0'*len(post)
+            post, repetends = [w.lstrip('0') for w in [post, repetend]]
+                                        # or else interpreted as octal
+
+            a = pre or '0'
+            b, c = post or '0', '1' + zeros
+            d, e = repetends, ('9'*len(repetend)) + zeros
+
+            seq = [
+                (OP, '('),
+                    (NAME, 'Integer'),
+                    (OP, '('),
+                        (NUMBER, a),
+                    (OP, ')'),
+                    (OP, '+'),
+                    (NAME, 'Rational'),
+                    (OP, '('),
+                        (NUMBER, b),
+                        (OP, ','),
+                        (NUMBER, c),
+                    (OP, ')'),
+                    (OP, '+'),
+                    (NAME, 'Rational'),
+                    (OP, '('),
+                        (NUMBER, d),
+                        (OP, ','),
+                        (NUMBER, e),
+                    (OP, ')'),
+                (OP, ')'),
+            ]
+            result.extend(seq)
+            num = []
+
+    return result
+
+
+def auto_number(tokens: list[TOKEN], local_dict: DICT, global_dict: DICT):
+    """
+    Converts numeric literals to use SymPy equivalents.
+
+    Complex numbers use ``I``, integer literals use ``Integer``, and float
+    literals use ``Float``.
+
+    """
+    result: list[TOKEN] = []
+
+    for toknum, tokval in tokens:
+        if toknum == NUMBER:
+            number = tokval
+            postfix = []
+
+            if number.endswith(('j', 'J')):
+                number = number[:-1]
+                postfix = [(OP, '*'), (NAME, 'I')]
+
+            if '.' in number or (('e' in number or 'E' in number) and
+                    not (number.startswith(('0x', '0X')))):
+                seq = [(NAME, 'Float'), (OP, '('),
+                    (NUMBER, repr(str(number))), (OP, ')')]
+            else:
+                seq = [(NAME, 'Integer'), (OP, '('), (
+                    NUMBER, number), (OP, ')')]
+
+            result.extend(seq + postfix)
+        else:
+            result.append((toknum, tokval))
+
+    return result
+
+
+def rationalize(tokens: list[TOKEN], local_dict: DICT, global_dict: DICT):
+    """Converts floats into ``Rational``. Run AFTER ``auto_number``."""
+    result: list[TOKEN] = []
+    passed_float = False
+    for toknum, tokval in tokens:
+        if toknum == NAME:
+            if tokval == 'Float':
+                passed_float = True
+                tokval = 'Rational'
+            result.append((toknum, tokval))
+        elif passed_float == True and toknum == NUMBER:
+            passed_float = False
+            result.append((STRING, tokval))
+        else:
+            result.append((toknum, tokval))
+
+    return result
+
+
+def _transform_equals_sign(tokens: list[TOKEN], local_dict: DICT, global_dict: DICT):
+    """Transforms the equals sign ``=`` to instances of Eq.
+
+    This is a helper function for ``convert_equals_signs``.
+    Works with expressions containing one equals sign and no
+    nesting. Expressions like ``(1=2)=False`` will not work with this
+    and should be used with ``convert_equals_signs``.
+
+    Examples: 1=2     to Eq(1,2)
+              1*2=x   to Eq(1*2, x)
+
+    This does not deal with function arguments yet.
+
+    """
+    result: list[TOKEN] = []
+    if (OP, "=") in tokens:
+        result.append((NAME, "Eq"))
+        result.append((OP, "("))
+        for token in tokens:
+            if token == (OP, "="):
+                result.append((OP, ","))
+                continue
+            result.append(token)
+        result.append((OP, ")"))
+    else:
+        result = tokens
+    return result
+
+
+def convert_equals_signs(tokens: list[TOKEN], local_dict: DICT,
+                         global_dict: DICT) -> list[TOKEN]:
+    """ Transforms all the equals signs ``=`` to instances of Eq.
+
+    Parses the equals signs in the expression and replaces them with
+    appropriate Eq instances. Also works with nested equals signs.
+
+    Does not yet play well with function arguments.
+    For example, the expression ``(x=y)`` is ambiguous and can be interpreted
+    as x being an argument to a function and ``convert_equals_signs`` will not
+    work for this.
+
+    See also
+    ========
+    convert_equality_operators
+
+    Examples
+    ========
+
+    >>> from sympy.parsing.sympy_parser import (parse_expr,
+    ... standard_transformations, convert_equals_signs)
+    >>> parse_expr("1*2=x", transformations=(
+    ... standard_transformations + (convert_equals_signs,)))
+    Eq(2, x)
+    >>> parse_expr("(1*2=x)=False", transformations=(
+    ... standard_transformations + (convert_equals_signs,)))
+    Eq(Eq(2, x), False)
+
+    """
+    res1 = _group_parentheses(convert_equals_signs)(tokens, local_dict, global_dict)
+    res2 = _apply_functions(res1, local_dict, global_dict)
+    res3 = _transform_equals_sign(res2, local_dict, global_dict)
+    result = _flatten(res3)
+    return result
+
+
+#: Standard transformations for :func:`parse_expr`.
+#: Inserts calls to :class:`~.Symbol`, :class:`~.Integer`, and other SymPy
+#: datatypes and allows the use of standard factorial notation (e.g. ``x!``).
+standard_transformations: tuple[TRANS, ...] \
+    = (lambda_notation, auto_symbol, repeated_decimals, auto_number,
+       factorial_notation)
+
+
+def stringify_expr(s: str, local_dict: DICT, global_dict: DICT,
+        transformations: tuple[TRANS, ...]) -> str:
+    """
+    Converts the string ``s`` to Python code, in ``local_dict``
+
+    Generally, ``parse_expr`` should be used.
+    """
+
+    tokens = []
+    input_code = StringIO(s.strip())
+    for toknum, tokval, _, _, _ in generate_tokens(input_code.readline):
+        tokens.append((toknum, tokval))
+
+    for transform in transformations:
+        tokens = transform(tokens, local_dict, global_dict)
+
+    return untokenize(tokens)
+
+
+def eval_expr(code, local_dict: DICT, global_dict: DICT):
+    """
+    Evaluate Python code generated by ``stringify_expr``.
+
+    Generally, ``parse_expr`` should be used.
+    """
+    expr = eval(
+        code, global_dict, local_dict)  # take local objects in preference
+    return expr
+
+
+def parse_expr(s: str, local_dict: DICT | None = None,
+               transformations: tuple[TRANS, ...] | str \
+                   = standard_transformations,
+               global_dict: DICT | None = None, evaluate=True):
+    """Converts the string ``s`` to a SymPy expression, in ``local_dict``.
+
+    .. warning::
+        Note that this function uses ``eval``, and thus shouldn't be used on
+        unsanitized input.
+
+    Parameters
+    ==========
+
+    s : str
+        The string to parse.
+
+    local_dict : dict, optional
+        A dictionary of local variables to use when parsing.
+
+    global_dict : dict, optional
+        A dictionary of global variables. By default, this is initialized
+        with ``from sympy import *``; provide this parameter to override
+        this behavior (for instance, to parse ``"Q & S"``).
+
+    transformations : tuple or str
+        A tuple of transformation functions used to modify the tokens of the
+        parsed expression before evaluation. The default transformations
+        convert numeric literals into their SymPy equivalents, convert
+        undefined variables into SymPy symbols, and allow the use of standard
+        mathematical factorial notation (e.g. ``x!``). Selection via
+        string is available (see below).
+
+    evaluate : bool, optional
+        When False, the order of the arguments will remain as they were in the
+        string and automatic simplification that would normally occur is
+        suppressed. (see examples)
+
+    Examples
+    ========
+
+    >>> from sympy.parsing.sympy_parser import parse_expr
+    >>> parse_expr("1/2")
+    1/2
+    >>> type(_)
+    
+    >>> from sympy.parsing.sympy_parser import standard_transformations,\\
+    ... implicit_multiplication_application
+    >>> transformations = (standard_transformations +
+    ...     (implicit_multiplication_application,))
+    >>> parse_expr("2x", transformations=transformations)
+    2*x
+
+    When evaluate=False, some automatic simplifications will not occur:
+
+    >>> parse_expr("2**3"), parse_expr("2**3", evaluate=False)
+    (8, 2**3)
+
+    In addition the order of the arguments will not be made canonical.
+    This feature allows one to tell exactly how the expression was entered:
+
+    >>> a = parse_expr('1 + x', evaluate=False)
+    >>> b = parse_expr('x + 1', evaluate=False)
+    >>> a == b
+    False
+    >>> a.args
+    (1, x)
+    >>> b.args
+    (x, 1)
+
+    Note, however, that when these expressions are printed they will
+    appear the same:
+
+    >>> assert str(a) == str(b)
+
+    As a convenience, transformations can be seen by printing ``transformations``:
+
+    >>> from sympy.parsing.sympy_parser import transformations
+
+    >>> print(transformations)
+    0: lambda_notation
+    1: auto_symbol
+    2: repeated_decimals
+    3: auto_number
+    4: factorial_notation
+    5: implicit_multiplication_application
+    6: convert_xor
+    7: implicit_application
+    8: implicit_multiplication
+    9: convert_equals_signs
+    10: function_exponentiation
+    11: rationalize
+
+    The ``T`` object provides a way to select these transformations:
+
+    >>> from sympy.parsing.sympy_parser import T
+
+    If you print it, you will see the same list as shown above.
+
+    >>> str(T) == str(transformations)
+    True
+
+    Standard slicing will return a tuple of transformations:
+
+    >>> T[:5] == standard_transformations
+    True
+
+    So ``T`` can be used to specify the parsing transformations:
+
+    >>> parse_expr("2x", transformations=T[:5])
+    Traceback (most recent call last):
+    ...
+    SyntaxError: invalid syntax
+    >>> parse_expr("2x", transformations=T[:6])
+    2*x
+    >>> parse_expr('.3', transformations=T[3, 11])
+    3/10
+    >>> parse_expr('.3x', transformations=T[:])
+    3*x/10
+
+    As a further convenience, strings 'implicit' and 'all' can be used
+    to select 0-5 and all the transformations, respectively.
+
+    >>> parse_expr('.3x', transformations='all')
+    3*x/10
+
+    See Also
+    ========
+
+    stringify_expr, eval_expr, standard_transformations,
+    implicit_multiplication_application
+
+    """
+
+    if local_dict is None:
+        local_dict = {}
+    elif not isinstance(local_dict, dict):
+        raise TypeError('expecting local_dict to be a dict')
+    elif null in local_dict:
+        raise ValueError('cannot use "" in local_dict')
+
+    if global_dict is None:
+        global_dict = {}
+        exec('from sympy import *', global_dict)
+
+        builtins_dict = vars(builtins)
+        for name, obj in builtins_dict.items():
+            if isinstance(obj, types.BuiltinFunctionType):
+                global_dict[name] = obj
+        global_dict['max'] = Max
+        global_dict['min'] = Min
+
+    elif not isinstance(global_dict, dict):
+        raise TypeError('expecting global_dict to be a dict')
+
+    transformations = transformations or ()
+    if isinstance(transformations, str):
+        if transformations == 'all':
+            _transformations = T[:]
+        elif transformations == 'implicit':
+            _transformations = T[:6]
+        else:
+            raise ValueError('unknown transformation group name')
+    else:
+        _transformations = transformations
+
+    code = stringify_expr(s, local_dict, global_dict, _transformations)
+
+    if not evaluate:
+        code = compile(evaluateFalse(code), '', 'eval') # type: ignore
+
+    try:
+        rv = eval_expr(code, local_dict, global_dict)
+        # restore neutral definitions for names
+        for i in local_dict.pop(null, ()):
+            local_dict[i] = null
+        return rv
+    except Exception as e:
+        # restore neutral definitions for names
+        for i in local_dict.pop(null, ()):
+            local_dict[i] = null
+        raise e from ValueError(f"Error from parse_expr with transformed code: {code!r}")
+
+
+def evaluateFalse(s: str):
+    """
+    Replaces operators with the SymPy equivalent and sets evaluate=False.
+    """
+    node = ast.parse(s)
+    transformed_node = EvaluateFalseTransformer().visit(node)
+    # node is a Module, we want an Expression
+    transformed_node = ast.Expression(transformed_node.body[0].value)
+
+    return ast.fix_missing_locations(transformed_node)
+
+
+class EvaluateFalseTransformer(ast.NodeTransformer):
+    operators = {
+        ast.Add: 'Add',
+        ast.Mult: 'Mul',
+        ast.Pow: 'Pow',
+        ast.Sub: 'Add',
+        ast.Div: 'Mul',
+        ast.BitOr: 'Or',
+        ast.BitAnd: 'And',
+        ast.BitXor: 'Not',
+    }
+    functions = (
+        'Abs', 'im', 're', 'sign', 'arg', 'conjugate',
+        'acos', 'acot', 'acsc', 'asec', 'asin', 'atan',
+        'acosh', 'acoth', 'acsch', 'asech', 'asinh', 'atanh',
+        'cos', 'cot', 'csc', 'sec', 'sin', 'tan',
+        'cosh', 'coth', 'csch', 'sech', 'sinh', 'tanh',
+        'exp', 'ln', 'log', 'sqrt', 'cbrt',
+    )
+
+    relational_operators = {
+        ast.NotEq: 'Ne',
+        ast.Lt: 'Lt',
+        ast.LtE: 'Le',
+        ast.Gt: 'Gt',
+        ast.GtE: 'Ge',
+        ast.Eq: 'Eq'
+    }
+    def visit_Compare(self, node):
+        def reducer(acc, op_right):
+            result, left = acc
+            op, right = op_right
+            if op.__class__ not in self.relational_operators:
+                raise ValueError("Only equation or inequality operators are supported")
+            new = ast.Call(
+                func=ast.Name(
+                    id=self.relational_operators[op.__class__], ctx=ast.Load()
+                ),
+                args=[self.visit(left), self.visit(right)],
+                keywords=[ast.keyword(arg="evaluate", value=ast.Constant(value=False))],
+            )
+            return result + [new], right
+
+        args, _ = reduce(
+            reducer, zip(node.ops, node.comparators), ([], node.left)
+        )
+        if len(args) == 1:
+            return args[0]
+        return ast.Call(
+            func=ast.Name(id=self.operators[ast.BitAnd], ctx=ast.Load()),
+            args=args,
+            keywords=[ast.keyword(arg="evaluate", value=ast.Constant(value=False))],
+        )
+
+    def flatten(self, args, func):
+        result = []
+        for arg in args:
+            if isinstance(arg, ast.Call):
+                arg_func = arg.func
+                if isinstance(arg_func, ast.Call):
+                    arg_func = arg_func.func
+                if arg_func.id == func:
+                    result.extend(self.flatten(arg.args, func))
+                else:
+                    result.append(arg)
+            else:
+                result.append(arg)
+        return result
+
+    def visit_BinOp(self, node):
+        if node.op.__class__ in self.operators:
+            sympy_class = self.operators[node.op.__class__]
+            right = self.visit(node.right)
+            left = self.visit(node.left)
+
+            rev = False
+            if isinstance(node.op, ast.Sub):
+                right = ast.Call(
+                    func=ast.Name(id='Mul', ctx=ast.Load()),
+                    args=[ast.UnaryOp(op=ast.USub(), operand=ast.Constant(1)), right],
+                    keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False))]
+                )
+            elif isinstance(node.op, ast.Div):
+                if isinstance(node.left, ast.UnaryOp):
+                    left, right = right, left
+                    rev = True
+                    left = ast.Call(
+                    func=ast.Name(id='Pow', ctx=ast.Load()),
+                    args=[left, ast.UnaryOp(op=ast.USub(), operand=ast.Constant(1))],
+                    keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False))]
+                )
+                else:
+                    right = ast.Call(
+                    func=ast.Name(id='Pow', ctx=ast.Load()),
+                    args=[right, ast.UnaryOp(op=ast.USub(), operand=ast.Constant(1))],
+                    keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False))]
+                )
+
+            if rev:  # undo reversal
+                left, right = right, left
+            new_node = ast.Call(
+                func=ast.Name(id=sympy_class, ctx=ast.Load()),
+                args=[left, right],
+                keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False))]
+            )
+
+            if sympy_class in ('Add', 'Mul'):
+                # Denest Add or Mul as appropriate
+                new_node.args = self.flatten(new_node.args, sympy_class)
+
+            return new_node
+        return node
+
+    def visit_Call(self, node):
+        new_node = self.generic_visit(node)
+        if isinstance(node.func, ast.Name) and node.func.id in self.functions:
+            new_node.keywords.append(ast.keyword(arg='evaluate', value=ast.Constant(value=False)))
+        return new_node
+
+
+_transformation = {  # items can be added but never re-ordered
+0: lambda_notation,
+1: auto_symbol,
+2: repeated_decimals,
+3: auto_number,
+4: factorial_notation,
+5: implicit_multiplication_application,
+6: convert_xor,
+7: implicit_application,
+8: implicit_multiplication,
+9: convert_equals_signs,
+10: function_exponentiation,
+11: rationalize}
+
+transformations = '\n'.join('%s: %s' % (i, func_name(f)) for i, f in _transformation.items())
+
+
+class _T():
+    """class to retrieve transformations from a given slice
+
+    EXAMPLES
+    ========
+
+    >>> from sympy.parsing.sympy_parser import T, standard_transformations
+    >>> assert T[:5] == standard_transformations
+    """
+    def __init__(self):
+        self.N = len(_transformation)
+
+    def __str__(self):
+        return transformations
+
+    def __getitem__(self, t):
+        if not type(t) is tuple:
+            t = (t,)
+        i = []
+        for ti in t:
+            if type(ti) is int:
+                i.append(range(self.N)[ti])
+            elif type(ti) is slice:
+                i.extend(range(*ti.indices(self.N)))
+            else:
+                raise TypeError('unexpected slice arg')
+        return tuple([_transformation[_] for _ in i])
+
+T = _T()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_ast_parser.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_ast_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..24572190df72f9be11b5830355b0d6b9e3bb53ad
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_ast_parser.py
@@ -0,0 +1,25 @@
+from sympy.core.singleton import S
+from sympy.core.symbol import symbols
+from sympy.parsing.ast_parser import parse_expr
+from sympy.testing.pytest import raises
+from sympy.core.sympify import SympifyError
+import warnings
+
+def test_parse_expr():
+    a, b = symbols('a, b')
+    # tests issue_16393
+    assert parse_expr('a + b', {}) == a + b
+    raises(SympifyError, lambda: parse_expr('a + ', {}))
+
+    # tests Transform.visit_Constant
+    assert parse_expr('1 + 2', {}) == S(3)
+    assert parse_expr('1 + 2.0', {}) == S(3.0)
+
+    # tests Transform.visit_Name
+    assert parse_expr('Rational(1, 2)', {}) == S(1)/2
+    assert parse_expr('a', {'a': a}) == a
+
+    # tests issue_23092
+    with warnings.catch_warnings():
+        warnings.simplefilter('error')
+        assert parse_expr('6 * 7', {}) == S(42)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_autolev.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_autolev.py
new file mode 100644
index 0000000000000000000000000000000000000000..dfcaef13565c5e2187dc6e90113b407a7967c331
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_autolev.py
@@ -0,0 +1,178 @@
+import os
+
+from sympy.functions.elementary.trigonometric import (cos, sin)
+from sympy.external import import_module
+from sympy.testing.pytest import skip
+from sympy.parsing.autolev import parse_autolev
+
+antlr4 = import_module("antlr4")
+
+if not antlr4:
+    disabled = True
+
+FILE_DIR = os.path.dirname(
+    os.path.dirname(os.path.abspath(os.path.realpath(__file__))))
+
+
+def _test_examples(in_filename, out_filename, test_name=""):
+
+    in_file_path = os.path.join(FILE_DIR, 'autolev', 'test-examples',
+                                in_filename)
+    correct_file_path = os.path.join(FILE_DIR, 'autolev', 'test-examples',
+                                     out_filename)
+    with open(in_file_path) as f:
+        generated_code = parse_autolev(f, include_numeric=True)
+
+    with open(correct_file_path) as f:
+        for idx, line1 in enumerate(f):
+            if line1.startswith("#"):
+                break
+            try:
+                line2 = generated_code.split('\n')[idx]
+                assert line1.rstrip() == line2.rstrip()
+            except Exception:
+                msg = 'mismatch in ' + test_name + ' in line no: {0}'
+                raise AssertionError(msg.format(idx+1))
+
+
+def test_rule_tests():
+
+    l = ["ruletest1", "ruletest2", "ruletest3", "ruletest4", "ruletest5",
+         "ruletest6", "ruletest7", "ruletest8", "ruletest9", "ruletest10",
+         "ruletest11", "ruletest12"]
+
+    for i in l:
+        in_filepath = i + ".al"
+        out_filepath = i + ".py"
+        _test_examples(in_filepath, out_filepath, i)
+
+
+def test_pydy_examples():
+
+    l = ["mass_spring_damper", "chaos_pendulum", "double_pendulum",
+         "non_min_pendulum"]
+
+    for i in l:
+        in_filepath = os.path.join("pydy-example-repo", i + ".al")
+        out_filepath = os.path.join("pydy-example-repo", i + ".py")
+        _test_examples(in_filepath, out_filepath, i)
+
+
+def test_autolev_tutorial():
+
+    dir_path = os.path.join(FILE_DIR, 'autolev', 'test-examples',
+                            'autolev-tutorial')
+
+    if os.path.isdir(dir_path):
+        l = ["tutor1", "tutor2", "tutor3", "tutor4", "tutor5", "tutor6",
+             "tutor7"]
+        for i in l:
+            in_filepath = os.path.join("autolev-tutorial", i + ".al")
+            out_filepath = os.path.join("autolev-tutorial", i + ".py")
+            _test_examples(in_filepath, out_filepath, i)
+
+
+def test_dynamics_online():
+
+    dir_path = os.path.join(FILE_DIR, 'autolev', 'test-examples',
+                            'dynamics-online')
+
+    if os.path.isdir(dir_path):
+        ch1 = ["1-4", "1-5", "1-6", "1-7", "1-8", "1-9_1", "1-9_2", "1-9_3"]
+        ch2 = ["2-1", "2-2", "2-3", "2-4", "2-5", "2-6", "2-7", "2-8", "2-9",
+               "circular"]
+        ch3 = ["3-1_1", "3-1_2", "3-2_1", "3-2_2", "3-2_3", "3-2_4", "3-2_5",
+               "3-3"]
+        ch4 = ["4-1_1", "4-2_1", "4-4_1", "4-4_2", "4-5_1", "4-5_2"]
+        chapters = [(ch1, "ch1"), (ch2, "ch2"), (ch3, "ch3"), (ch4, "ch4")]
+        for ch, name in chapters:
+            for i in ch:
+                in_filepath = os.path.join("dynamics-online", name, i + ".al")
+                out_filepath = os.path.join("dynamics-online", name, i + ".py")
+                _test_examples(in_filepath, out_filepath, i)
+
+
+def test_output_01():
+    """Autolev example calculates the position, velocity, and acceleration of a
+    point and expresses in a single reference frame::
+
+          (1) FRAMES C,D,F
+          (2) VARIABLES FD'',DC''
+          (3) CONSTANTS R,L
+          (4) POINTS O,E
+          (5) SIMPROT(F,D,1,FD)
+       -> (6) F_D = [1, 0, 0; 0, COS(FD), -SIN(FD); 0, SIN(FD), COS(FD)]
+          (7) SIMPROT(D,C,2,DC)
+       -> (8) D_C = [COS(DC), 0, SIN(DC); 0, 1, 0; -SIN(DC), 0, COS(DC)]
+          (9) W_C_F> = EXPRESS(W_C_F>, F)
+       -> (10) W_C_F> = FD'*F1> + COS(FD)*DC'*F2> + SIN(FD)*DC'*F3>
+          (11) P_O_E>=R*D2>-L*C1>
+          (12) P_O_E>=EXPRESS(P_O_E>, D)
+       -> (13) P_O_E> = -L*COS(DC)*D1> + R*D2> + L*SIN(DC)*D3>
+          (14) V_E_F>=EXPRESS(DT(P_O_E>,F),D)
+       -> (15) V_E_F> = L*SIN(DC)*DC'*D1> - L*SIN(DC)*FD'*D2> + (R*FD'+L*COS(DC)*DC')*D3>
+          (16) A_E_F>=EXPRESS(DT(V_E_F>,F),D)
+       -> (17) A_E_F> = L*(COS(DC)*DC'^2+SIN(DC)*DC'')*D1> + (-R*FD'^2-2*L*COS(DC)*DC'*FD'-L*SIN(DC)*FD'')*D2> + (R*FD''+L*COS(DC)*DC''-L*SIN(DC)*DC'^2-L*SIN(DC)*FD'^2)*D3>
+
+    """
+
+    if not antlr4:
+        skip('Test skipped: antlr4 is not installed.')
+
+    autolev_input = """\
+FRAMES C,D,F
+VARIABLES FD'',DC''
+CONSTANTS R,L
+POINTS O,E
+SIMPROT(F,D,1,FD)
+SIMPROT(D,C,2,DC)
+W_C_F>=EXPRESS(W_C_F>,F)
+P_O_E>=R*D2>-L*C1>
+P_O_E>=EXPRESS(P_O_E>,D)
+V_E_F>=EXPRESS(DT(P_O_E>,F),D)
+A_E_F>=EXPRESS(DT(V_E_F>,F),D)\
+"""
+
+    sympy_input = parse_autolev(autolev_input)
+
+    g = {}
+    l = {}
+    exec(sympy_input, g, l)
+
+    w_c_f = l['frame_c'].ang_vel_in(l['frame_f'])
+    # P_O_E> means "the position of point E wrt to point O"
+    p_o_e = l['point_e'].pos_from(l['point_o'])
+    v_e_f = l['point_e'].vel(l['frame_f'])
+    a_e_f = l['point_e'].acc(l['frame_f'])
+
+    # NOTE : The Autolev outputs above were manually transformed into
+    # equivalent SymPy physics vector expressions. Would be nice to automate
+    # this transformation.
+    expected_w_c_f = (l['fd'].diff()*l['frame_f'].x +
+                      cos(l['fd'])*l['dc'].diff()*l['frame_f'].y +
+                      sin(l['fd'])*l['dc'].diff()*l['frame_f'].z)
+
+    assert (w_c_f - expected_w_c_f).simplify() == 0
+
+    expected_p_o_e = (-l['l']*cos(l['dc'])*l['frame_d'].x +
+                      l['r']*l['frame_d'].y +
+                      l['l']*sin(l['dc'])*l['frame_d'].z)
+
+    assert (p_o_e - expected_p_o_e).simplify() == 0
+
+    expected_v_e_f = (l['l']*sin(l['dc'])*l['dc'].diff()*l['frame_d'].x -
+                      l['l']*sin(l['dc'])*l['fd'].diff()*l['frame_d'].y +
+                      (l['r']*l['fd'].diff() +
+                       l['l']*cos(l['dc'])*l['dc'].diff())*l['frame_d'].z)
+    assert (v_e_f - expected_v_e_f).simplify() == 0
+
+    expected_a_e_f = (l['l']*(cos(l['dc'])*l['dc'].diff()**2 +
+                              sin(l['dc'])*l['dc'].diff().diff())*l['frame_d'].x +
+                      (-l['r']*l['fd'].diff()**2 -
+                       2*l['l']*cos(l['dc'])*l['dc'].diff()*l['fd'].diff() -
+                       l['l']*sin(l['dc'])*l['fd'].diff().diff())*l['frame_d'].y +
+                      (l['r']*l['fd'].diff().diff() +
+                       l['l']*cos(l['dc'])*l['dc'].diff().diff() -
+                       l['l']*sin(l['dc'])*l['dc'].diff()**2 -
+                       l['l']*sin(l['dc'])*l['fd'].diff()**2)*l['frame_d'].z)
+    assert (a_e_f - expected_a_e_f).simplify() == 0
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_c_parser.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_c_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..b74622e40030cba180cb4fc354216ccca119baec
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_c_parser.py
@@ -0,0 +1,5248 @@
+from sympy.parsing.sym_expr import SymPyExpression
+from sympy.testing.pytest import raises, XFAIL
+from sympy.external import import_module
+
+cin = import_module('clang.cindex', import_kwargs = {'fromlist': ['cindex']})
+
+if cin:
+    from sympy.codegen.ast import (Variable, String, Return,
+        FunctionDefinition, Integer, Float, Declaration, CodeBlock,
+        FunctionPrototype, FunctionCall, NoneToken, Assignment, Type,
+        IntBaseType, SignedIntType, UnsignedIntType, FloatType,
+        AddAugmentedAssignment, SubAugmentedAssignment,
+        MulAugmentedAssignment, DivAugmentedAssignment,
+        ModAugmentedAssignment, While)
+    from sympy.codegen.cnodes import (PreDecrement, PostDecrement,
+        PreIncrement, PostIncrement)
+    from sympy.core import (Add, Mul, Mod, Pow, Rational,
+        StrictLessThan, LessThan, StrictGreaterThan, GreaterThan,
+        Equality, Unequality)
+    from sympy.logic.boolalg import And, Not, Or
+    from sympy.core.symbol import Symbol
+    from sympy.logic.boolalg import (false, true)
+    import os
+
+    def test_variable():
+        c_src1 = (
+            'int a;' + '\n' +
+            'int b;' + '\n'
+        )
+        c_src2 = (
+            'float a;' + '\n'
+            + 'float b;' + '\n'
+        )
+        c_src3 = (
+            'int a;' + '\n' +
+            'float b;' + '\n' +
+            'int c;'
+        )
+        c_src4 = (
+            'int x = 1, y = 6.78;' + '\n' +
+            'float p = 2, q = 9.67;'
+        )
+
+        res1 = SymPyExpression(c_src1, 'c').return_expr()
+        res2 = SymPyExpression(c_src2, 'c').return_expr()
+        res3 = SymPyExpression(c_src3, 'c').return_expr()
+        res4 = SymPyExpression(c_src4, 'c').return_expr()
+
+        assert res1[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type=IntBaseType(String('intc'))
+            )
+        )
+
+        assert res1[1] == Declaration(
+            Variable(
+                Symbol('b'),
+                type=IntBaseType(String('intc'))
+            )
+        )
+
+        assert res2[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    )
+            )
+        )
+        assert res2[1] == Declaration(
+            Variable(
+                Symbol('b'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    )
+            )
+        )
+
+        assert res3[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type=IntBaseType(String('intc'))
+            )
+        )
+
+        assert res3[1] == Declaration(
+            Variable(
+                Symbol('b'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    )
+            )
+        )
+
+        assert res3[2] == Declaration(
+            Variable(
+                Symbol('c'),
+                type=IntBaseType(String('intc'))
+            )
+        )
+
+        assert res4[0] == Declaration(
+            Variable(
+                Symbol('x'),
+                type=IntBaseType(String('intc')),
+                value=Integer(1)
+            )
+        )
+
+        assert res4[1] == Declaration(
+            Variable(
+                Symbol('y'),
+                type=IntBaseType(String('intc')),
+                value=Integer(6)
+            )
+        )
+
+        assert res4[2] == Declaration(
+            Variable(
+                Symbol('p'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('2.0', precision=53)
+            )
+        )
+
+        assert res4[3] == Declaration(
+            Variable(
+                Symbol('q'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('9.67', precision=53)
+            )
+        )
+
+
+    def test_int():
+        c_src1 = 'int a = 1;'
+        c_src2 = (
+            'int a = 1;' + '\n' +
+            'int b = 2;' + '\n'
+        )
+        c_src3 = 'int a = 2.345, b = 5.67;'
+        c_src4 = 'int p = 6, q = 23.45;'
+        c_src5 = "int x = '0', y = 'a';"
+        c_src6 = "int r = true, s = false;"
+
+        # cin.TypeKind.UCHAR
+        c_src_type1 = (
+            "signed char a = 1, b = 5.1;"
+            )
+
+        # cin.TypeKind.SHORT
+        c_src_type2 = (
+            "short a = 1, b = 5.1;"
+            "signed short c = 1, d = 5.1;"
+            "short int e = 1, f = 5.1;"
+            "signed short int g = 1, h = 5.1;"
+            )
+
+        # cin.TypeKind.INT
+        c_src_type3 = (
+            "signed int a = 1, b = 5.1;"
+            "int c = 1, d = 5.1;"
+            )
+
+        # cin.TypeKind.LONG
+        c_src_type4 = (
+            "long a = 1, b = 5.1;"
+            "long int c = 1, d = 5.1;"
+            )
+
+        # cin.TypeKind.UCHAR
+        c_src_type5 = "unsigned char a = 1, b = 5.1;"
+
+        # cin.TypeKind.USHORT
+        c_src_type6 = (
+            "unsigned short a = 1, b = 5.1;"
+            "unsigned short int c = 1, d = 5.1;"
+            )
+
+        # cin.TypeKind.UINT
+        c_src_type7 = "unsigned int a = 1, b = 5.1;"
+
+        # cin.TypeKind.ULONG
+        c_src_type8 = (
+            "unsigned long a = 1, b = 5.1;"
+            "unsigned long int c = 1, d = 5.1;"
+            )
+
+        res1 = SymPyExpression(c_src1, 'c').return_expr()
+        res2 = SymPyExpression(c_src2, 'c').return_expr()
+        res3 = SymPyExpression(c_src3, 'c').return_expr()
+        res4 = SymPyExpression(c_src4, 'c').return_expr()
+        res5 = SymPyExpression(c_src5, 'c').return_expr()
+        res6 = SymPyExpression(c_src6, 'c').return_expr()
+
+        res_type1 = SymPyExpression(c_src_type1, 'c').return_expr()
+        res_type2 = SymPyExpression(c_src_type2, 'c').return_expr()
+        res_type3 = SymPyExpression(c_src_type3, 'c').return_expr()
+        res_type4 = SymPyExpression(c_src_type4, 'c').return_expr()
+        res_type5 = SymPyExpression(c_src_type5, 'c').return_expr()
+        res_type6 = SymPyExpression(c_src_type6, 'c').return_expr()
+        res_type7 = SymPyExpression(c_src_type7, 'c').return_expr()
+        res_type8 = SymPyExpression(c_src_type8, 'c').return_expr()
+
+        assert res1[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(1)
+            )
+        )
+
+        assert res2[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(1)
+            )
+        )
+
+        assert res2[1] == Declaration(
+            Variable(
+                Symbol('b'),
+                type=IntBaseType(String('intc')),
+                value=Integer(2)
+            )
+        )
+
+        assert res3[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(2)
+            )
+        )
+
+        assert res3[1] == Declaration(
+            Variable(
+                Symbol('b'),
+                type=IntBaseType(String('intc')),
+                value=Integer(5)
+            )
+        )
+
+        assert res4[0] == Declaration(
+            Variable(
+                Symbol('p'),
+                type=IntBaseType(String('intc')),
+                value=Integer(6)
+            )
+        )
+
+        assert res4[1] == Declaration(
+            Variable(
+                Symbol('q'),
+                type=IntBaseType(String('intc')),
+                value=Integer(23)
+            )
+        )
+
+        assert res5[0] == Declaration(
+            Variable(
+                Symbol('x'),
+                type=IntBaseType(String('intc')),
+                value=Integer(48)
+            )
+        )
+
+        assert res5[1] == Declaration(
+            Variable(
+                Symbol('y'),
+                type=IntBaseType(String('intc')),
+                value=Integer(97)
+            )
+        )
+
+        assert res6[0] == Declaration(
+            Variable(
+                Symbol('r'),
+                type=IntBaseType(String('intc')),
+                value=Integer(1)
+            )
+        )
+
+        assert res6[1] == Declaration(
+            Variable(
+                Symbol('s'),
+                type=IntBaseType(String('intc')),
+                value=Integer(0)
+            )
+        )
+
+        assert res_type1[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type=SignedIntType(
+                    String('int8'),
+                    nbits=Integer(8)
+                    ),
+                value=Integer(1)
+                )
+            )
+
+        assert res_type1[1] == Declaration(
+            Variable(
+                Symbol('b'),
+                type=SignedIntType(
+                    String('int8'),
+                    nbits=Integer(8)
+                    ),
+                value=Integer(5)
+                )
+            )
+
+        assert res_type2[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type=SignedIntType(
+                    String('int16'),
+                    nbits=Integer(16)
+                    ),
+                value=Integer(1)
+                )
+            )
+
+        assert res_type2[1] == Declaration(
+            Variable(
+                Symbol('b'),
+                type=SignedIntType(
+                    String('int16'),
+                    nbits=Integer(16)
+                    ),
+                value=Integer(5)
+                )
+            )
+
+        assert res_type2[2] == Declaration(
+            Variable(Symbol('c'),
+                type=SignedIntType(
+                    String('int16'),
+                    nbits=Integer(16)
+                    ),
+                value=Integer(1)
+                )
+            )
+
+        assert res_type2[3] == Declaration(
+            Variable(
+                Symbol('d'),
+                type=SignedIntType(
+                    String('int16'),
+                    nbits=Integer(16)
+                    ),
+                value=Integer(5)
+                )
+            )
+
+        assert res_type2[4] == Declaration(
+            Variable(
+                Symbol('e'),
+                type=SignedIntType(
+                    String('int16'),
+                    nbits=Integer(16)
+                    ),
+                value=Integer(1)
+                )
+            )
+
+        assert res_type2[5] == Declaration(
+            Variable(
+                Symbol('f'),
+                type=SignedIntType(
+                    String('int16'),
+                    nbits=Integer(16)
+                    ),
+                value=Integer(5)
+                )
+            )
+
+        assert res_type2[6] == Declaration(
+            Variable(
+                Symbol('g'),
+                type=SignedIntType(
+                    String('int16'),
+                    nbits=Integer(16)
+                    ),
+                value=Integer(1)
+                )
+            )
+
+        assert res_type2[7] == Declaration(
+            Variable(
+                Symbol('h'),
+                type=SignedIntType(
+                    String('int16'),
+                    nbits=Integer(16)
+                    ),
+                value=Integer(5)
+                )
+            )
+
+        assert res_type3[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(1)
+                )
+            )
+
+        assert res_type3[1] == Declaration(
+            Variable(
+                Symbol('b'),
+                type=IntBaseType(String('intc')),
+                value=Integer(5)
+                )
+            )
+
+        assert res_type3[2] == Declaration(
+            Variable(
+                Symbol('c'),
+                type=IntBaseType(String('intc')),
+                value=Integer(1)
+                )
+            )
+
+        assert res_type3[3] == Declaration(
+            Variable(
+                Symbol('d'),
+                type=IntBaseType(String('intc')),
+                value=Integer(5)
+                )
+            )
+
+        assert res_type4[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type=SignedIntType(
+                    String('int64'),
+                    nbits=Integer(64)
+                    ),
+                value=Integer(1)
+                )
+            )
+
+        assert res_type4[1] == Declaration(
+            Variable(
+                Symbol('b'),
+                type=SignedIntType(
+                    String('int64'),
+                    nbits=Integer(64)
+                    ),
+                value=Integer(5)
+                )
+            )
+
+        assert res_type4[2] == Declaration(
+            Variable(
+                Symbol('c'),
+                type=SignedIntType(
+                    String('int64'),
+                    nbits=Integer(64)
+                    ),
+                value=Integer(1)
+                )
+            )
+
+        assert res_type4[3] == Declaration(
+            Variable(
+                Symbol('d'),
+                type=SignedIntType(
+                    String('int64'),
+                    nbits=Integer(64)
+                    ),
+                value=Integer(5)
+                )
+            )
+
+        assert res_type5[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type=UnsignedIntType(
+                    String('uint8'),
+                    nbits=Integer(8)
+                    ),
+                value=Integer(1)
+                )
+            )
+
+        assert res_type5[1] == Declaration(
+            Variable(
+                Symbol('b'),
+                type=UnsignedIntType(
+                    String('uint8'),
+                    nbits=Integer(8)
+                    ),
+                value=Integer(5)
+                )
+            )
+
+        assert res_type6[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type=UnsignedIntType(
+                    String('uint16'),
+                    nbits=Integer(16)
+                    ),
+                value=Integer(1)
+                )
+            )
+
+        assert res_type6[1] == Declaration(
+            Variable(
+                Symbol('b'),
+                type=UnsignedIntType(
+                    String('uint16'),
+                    nbits=Integer(16)
+                    ),
+                value=Integer(5)
+                )
+            )
+
+        assert res_type6[2] == Declaration(
+            Variable(
+                Symbol('c'),
+                type=UnsignedIntType(
+                    String('uint16'),
+                    nbits=Integer(16)
+                    ),
+                value=Integer(1)
+                )
+            )
+
+        assert res_type6[3] == Declaration(
+            Variable(
+                Symbol('d'),
+                type=UnsignedIntType(
+                    String('uint16'),
+                    nbits=Integer(16)
+                    ),
+                value=Integer(5)
+                )
+            )
+
+        assert res_type7[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type=UnsignedIntType(
+                    String('uint32'),
+                    nbits=Integer(32)
+                    ),
+                value=Integer(1)
+                )
+            )
+
+        assert res_type7[1] == Declaration(
+            Variable(
+                Symbol('b'),
+                type=UnsignedIntType(
+                    String('uint32'),
+                    nbits=Integer(32)
+                    ),
+                value=Integer(5)
+                )
+            )
+
+        assert res_type8[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type=UnsignedIntType(
+                    String('uint64'),
+                    nbits=Integer(64)
+                    ),
+                value=Integer(1)
+                )
+            )
+
+        assert res_type8[1] == Declaration(
+            Variable(
+                Symbol('b'),
+                type=UnsignedIntType(
+                    String('uint64'),
+                    nbits=Integer(64)
+                    ),
+                value=Integer(5)
+                )
+            )
+
+        assert res_type8[2] == Declaration(
+            Variable(
+                Symbol('c'),
+                type=UnsignedIntType(
+                    String('uint64'),
+                    nbits=Integer(64)
+                    ),
+                value=Integer(1)
+                )
+            )
+
+        assert res_type8[3] == Declaration(
+            Variable(
+                Symbol('d'),
+                type=UnsignedIntType(
+                    String('uint64'),
+                    nbits=Integer(64)
+                    ),
+                value=Integer(5)
+                )
+            )
+
+
+    def test_float():
+        c_src1 = 'float a = 1.0;'
+        c_src2 = (
+            'float a = 1.25;' + '\n' +
+            'float b = 2.39;' + '\n'
+        )
+        c_src3 = 'float x = 1, y = 2;'
+        c_src4 = 'float p = 5, e = 7.89;'
+        c_src5 = 'float r = true, s = false;'
+
+        # cin.TypeKind.FLOAT
+        c_src_type1 = 'float x = 1, y = 2.5;'
+
+        # cin.TypeKind.DOUBLE
+        c_src_type2 = 'double x = 1, y = 2.5;'
+
+        # cin.TypeKind.LONGDOUBLE
+        c_src_type3 = 'long double x = 1, y = 2.5;'
+
+        res1 = SymPyExpression(c_src1, 'c').return_expr()
+        res2 = SymPyExpression(c_src2, 'c').return_expr()
+        res3 = SymPyExpression(c_src3, 'c').return_expr()
+        res4 = SymPyExpression(c_src4, 'c').return_expr()
+        res5 = SymPyExpression(c_src5, 'c').return_expr()
+
+        res_type1 = SymPyExpression(c_src_type1, 'c').return_expr()
+        res_type2 = SymPyExpression(c_src_type2, 'c').return_expr()
+        res_type3 = SymPyExpression(c_src_type3, 'c').return_expr()
+
+        assert res1[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('1.0', precision=53)
+                )
+            )
+
+        assert res2[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('1.25', precision=53)
+            )
+        )
+
+        assert res2[1] == Declaration(
+            Variable(
+                Symbol('b'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('2.3900000000000001', precision=53)
+            )
+        )
+
+        assert res3[0] == Declaration(
+            Variable(
+                Symbol('x'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('1.0', precision=53)
+            )
+        )
+
+        assert res3[1] == Declaration(
+            Variable(
+                Symbol('y'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('2.0', precision=53)
+            )
+        )
+
+        assert res4[0] == Declaration(
+            Variable(
+                Symbol('p'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                ),
+                value=Float('5.0', precision=53)
+            )
+        )
+
+        assert res4[1] == Declaration(
+            Variable(
+                Symbol('e'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('7.89', precision=53)
+            )
+        )
+
+        assert res5[0] == Declaration(
+            Variable(
+                Symbol('r'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('1.0', precision=53)
+            )
+        )
+
+        assert res5[1] == Declaration(
+            Variable(
+                Symbol('s'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('0.0', precision=53)
+            )
+        )
+
+        assert res_type1[0] == Declaration(
+            Variable(
+                Symbol('x'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('1.0', precision=53)
+                )
+            )
+
+        assert res_type1[1] == Declaration(
+            Variable(
+                Symbol('y'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('2.5', precision=53)
+                )
+            )
+        assert res_type2[0] == Declaration(
+            Variable(
+                Symbol('x'),
+                type=FloatType(
+                    String('float64'),
+                    nbits=Integer(64),
+                    nmant=Integer(52),
+                    nexp=Integer(11)
+                    ),
+                value=Float('1.0', precision=53)
+                )
+            )
+
+        assert res_type2[1] == Declaration(
+            Variable(
+                Symbol('y'),
+                type=FloatType(
+                    String('float64'),
+                    nbits=Integer(64),
+                    nmant=Integer(52),
+                    nexp=Integer(11)
+                    ),
+                value=Float('2.5', precision=53)
+                )
+            )
+
+        assert res_type3[0] == Declaration(
+            Variable(
+                Symbol('x'),
+                type=FloatType(
+                    String('float80'),
+                    nbits=Integer(80),
+                    nmant=Integer(63),
+                    nexp=Integer(15)
+                    ),
+                value=Float('1.0', precision=53)
+                )
+            )
+
+        assert res_type3[1] == Declaration(
+            Variable(
+                Symbol('y'),
+                type=FloatType(
+                    String('float80'),
+                    nbits=Integer(80),
+                    nmant=Integer(63),
+                    nexp=Integer(15)
+                    ),
+                value=Float('2.5', precision=53)
+                )
+            )
+
+
+    def test_bool():
+        c_src1 = (
+            'bool a = true, b = false;'
+        )
+
+        c_src2 = (
+            'bool a = 1, b = 0;'
+        )
+
+        c_src3 = (
+            'bool a = 10, b = 20;'
+        )
+
+        c_src4 = (
+            'bool a = 19.1, b = 9.0, c = 0.0;'
+        )
+
+        res1 = SymPyExpression(c_src1, 'c').return_expr()
+        res2 = SymPyExpression(c_src2, 'c').return_expr()
+        res3 = SymPyExpression(c_src3, 'c').return_expr()
+        res4 = SymPyExpression(c_src4, 'c').return_expr()
+
+        assert res1[0] == Declaration(
+            Variable(Symbol('a'),
+                type=Type(String('bool')),
+                value=true
+                )
+            )
+
+        assert res1[1] == Declaration(
+            Variable(Symbol('b'),
+                type=Type(String('bool')),
+                value=false
+                )
+            )
+
+        assert res2[0] == Declaration(
+            Variable(Symbol('a'),
+                type=Type(String('bool')),
+                value=true)
+            )
+
+        assert res2[1] == Declaration(
+            Variable(Symbol('b'),
+                type=Type(String('bool')),
+                value=false
+                )
+            )
+
+        assert res3[0] == Declaration(
+            Variable(Symbol('a'),
+                type=Type(String('bool')),
+                value=true
+                )
+            )
+
+        assert res3[1] == Declaration(
+            Variable(Symbol('b'),
+                type=Type(String('bool')),
+                value=true
+                )
+            )
+
+        assert res4[0] == Declaration(
+            Variable(Symbol('a'),
+                type=Type(String('bool')),
+                value=true)
+            )
+
+        assert res4[1] == Declaration(
+            Variable(Symbol('b'),
+                type=Type(String('bool')),
+                value=true
+                )
+            )
+
+        assert res4[2] == Declaration(
+            Variable(Symbol('c'),
+                type=Type(String('bool')),
+                value=false
+                )
+            )
+
+    @XFAIL # this is expected to fail because of a bug in the C parser.
+    def test_function():
+        c_src1 = (
+            'void fun1()' + '\n' +
+            '{' + '\n' +
+            'int a;' + '\n' +
+            '}'
+        )
+        c_src2 = (
+            'int fun2()' + '\n' +
+            '{'+ '\n' +
+            'int a;' + '\n' +
+            'return a;' + '\n' +
+            '}'
+        )
+        c_src3 = (
+            'float fun3()' + '\n' +
+            '{' + '\n' +
+            'float b;' + '\n' +
+            'return b;' + '\n' +
+            '}'
+        )
+        c_src4 = (
+            'float fun4()' + '\n' +
+            '{}'
+        )
+
+        res1 = SymPyExpression(c_src1, 'c').return_expr()
+        res2 = SymPyExpression(c_src2, 'c').return_expr()
+        res3 = SymPyExpression(c_src3, 'c').return_expr()
+        res4 = SymPyExpression(c_src4, 'c').return_expr()
+
+        assert res1[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('fun1'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(
+                        Symbol('a'),
+                        type=IntBaseType(String('intc'))
+                    )
+                )
+            )
+        )
+
+        assert res2[0] == FunctionDefinition(
+            IntBaseType(String('intc')),
+            name=String('fun2'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(
+                        Symbol('a'),
+                        type=IntBaseType(String('intc'))
+                    )
+                ),
+                Return('a')
+            )
+        )
+
+        assert res3[0] == FunctionDefinition(
+            FloatType(
+                String('float32'),
+                nbits=Integer(32),
+                nmant=Integer(23),
+                nexp=Integer(8)
+                ),
+            name=String('fun3'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(
+                        Symbol('b'),
+                        type=FloatType(
+                            String('float32'),
+                            nbits=Integer(32),
+                            nmant=Integer(23),
+                            nexp=Integer(8)
+                            )
+                    )
+                ),
+                Return('b')
+            )
+        )
+
+        assert res4[0] == FunctionPrototype(
+            FloatType(
+                String('float32'),
+                nbits=Integer(32),
+                nmant=Integer(23),
+                nexp=Integer(8)
+                ),
+            name=String('fun4'),
+            parameters=()
+        )
+
+    @XFAIL # this is expected to fail because of a bug in the C parser.
+    def test_parameters():
+        c_src1 = (
+            'void fun1( int a)' + '\n' +
+            '{' + '\n' +
+            'int i;' + '\n' +
+            '}'
+        )
+        c_src2 = (
+            'int fun2(float x, float y)' + '\n' +
+            '{'+ '\n' +
+            'int a;' + '\n' +
+            'return a;' + '\n' +
+            '}'
+        )
+        c_src3 = (
+            'float fun3(int p, float q, int r)' + '\n' +
+            '{' + '\n' +
+            'float b;' + '\n' +
+            'return b;' + '\n' +
+            '}'
+        )
+
+        res1 = SymPyExpression(c_src1, 'c').return_expr()
+        res2 = SymPyExpression(c_src2, 'c').return_expr()
+        res3 = SymPyExpression(c_src3, 'c').return_expr()
+
+        assert res1[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('fun1'),
+            parameters=(
+                Variable(
+                    Symbol('a'),
+                    type=IntBaseType(String('intc'))
+                ),
+            ),
+            body=CodeBlock(
+                Declaration(
+                    Variable(
+                        Symbol('i'),
+                        type=IntBaseType(String('intc'))
+                    )
+                )
+            )
+        )
+
+        assert res2[0] == FunctionDefinition(
+            IntBaseType(String('intc')),
+            name=String('fun2'),
+            parameters=(
+                Variable(
+                    Symbol('x'),
+                    type=FloatType(
+                        String('float32'),
+                        nbits=Integer(32),
+                        nmant=Integer(23),
+                        nexp=Integer(8)
+                        )
+                ),
+                Variable(
+                    Symbol('y'),
+                    type=FloatType(
+                        String('float32'),
+                        nbits=Integer(32),
+                        nmant=Integer(23),
+                        nexp=Integer(8)
+                        )
+                )
+            ),
+            body=CodeBlock(
+                Declaration(
+                    Variable(
+                        Symbol('a'),
+                        type=IntBaseType(String('intc'))
+                    )
+                ),
+                Return('a')
+            )
+        )
+
+        assert res3[0] == FunctionDefinition(
+            FloatType(
+                String('float32'),
+                nbits=Integer(32),
+                nmant=Integer(23),
+                nexp=Integer(8)
+                ),
+            name=String('fun3'),
+            parameters=(
+                Variable(
+                    Symbol('p'),
+                    type=IntBaseType(String('intc'))
+                ),
+                Variable(
+                    Symbol('q'),
+                    type=FloatType(
+                        String('float32'),
+                        nbits=Integer(32),
+                        nmant=Integer(23),
+                        nexp=Integer(8)
+                        )
+                ),
+                Variable(
+                    Symbol('r'),
+                    type=IntBaseType(String('intc'))
+                )
+            ),
+            body=CodeBlock(
+                Declaration(
+                    Variable(
+                        Symbol('b'),
+                        type=FloatType(
+                            String('float32'),
+                            nbits=Integer(32),
+                            nmant=Integer(23),
+                            nexp=Integer(8)
+                            )
+                    )
+                ),
+                Return('b')
+            )
+        )
+
+    @XFAIL # this is expected to fail because of a bug in the C parser.
+    def test_function_call():
+        c_src1 = (
+            'int fun1(int x)' + '\n' +
+            '{' + '\n' +
+            'return x;' + '\n' +
+            '}' + '\n' +
+            'void caller()' + '\n' +
+            '{' + '\n' +
+            'int x = fun1(2);' + '\n' +
+            '}'
+        )
+
+        c_src2 = (
+            'int fun2(int a, int b, int c)' + '\n' +
+            '{' + '\n' +
+            'return a;' + '\n' +
+            '}' + '\n' +
+            'void caller()' + '\n' +
+            '{' + '\n' +
+            'int y = fun2(2, 3, 4);' + '\n' +
+            '}'
+        )
+
+        c_src3 = (
+            'int fun3(int a, int b, int c)' + '\n' +
+            '{' + '\n' +
+            'return b;' + '\n' +
+            '}' + '\n' +
+            'void caller()' + '\n' +
+            '{' + '\n' +
+            'int p;' + '\n' +
+            'int q;' + '\n' +
+            'int r;' + '\n' +
+            'int z = fun3(p, q, r);' + '\n' +
+            '}'
+        )
+
+        c_src4 = (
+            'int fun4(float a, float b, int c)' + '\n' +
+            '{' + '\n' +
+            'return c;' + '\n' +
+            '}' + '\n' +
+            'void caller()' + '\n' +
+            '{' + '\n' +
+            'float x;' + '\n' +
+            'float y;' + '\n' +
+            'int z;' + '\n' +
+            'int i = fun4(x, y, z)' + '\n' +
+            '}'
+        )
+
+        c_src5 = (
+            'int fun()' + '\n' +
+            '{' + '\n' +
+            'return 1;' + '\n' +
+            '}' + '\n' +
+            'void caller()' + '\n' +
+            '{' + '\n' +
+            'int a = fun()' + '\n' +
+            '}'
+        )
+
+        res1 = SymPyExpression(c_src1, 'c').return_expr()
+        res2 = SymPyExpression(c_src2, 'c').return_expr()
+        res3 = SymPyExpression(c_src3, 'c').return_expr()
+        res4 = SymPyExpression(c_src4, 'c').return_expr()
+        res5 = SymPyExpression(c_src5, 'c').return_expr()
+
+
+        assert res1[0] == FunctionDefinition(
+            IntBaseType(String('intc')),
+            name=String('fun1'),
+            parameters=(Variable(Symbol('x'),
+                type=IntBaseType(String('intc'))
+                ),
+            ),
+            body=CodeBlock(
+                Return('x')
+                )
+            )
+
+        assert res1[1] == FunctionDefinition(
+            NoneToken(),
+            name=String('caller'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('x'),
+                        value=FunctionCall(String('fun1'),
+                            function_args=(
+                                Integer(2),
+                                )
+                            )
+                        )
+                    )
+                )
+            )
+
+        assert res2[0] == FunctionDefinition(
+            IntBaseType(String('intc')),
+            name=String('fun2'),
+            parameters=(Variable(Symbol('a'),
+                type=IntBaseType(String('intc'))
+                ),
+            Variable(Symbol('b'),
+                type=IntBaseType(String('intc'))
+                ),
+            Variable(Symbol('c'),
+                type=IntBaseType(String('intc'))
+                )
+            ),
+            body=CodeBlock(
+                Return('a')
+                )
+            )
+
+        assert res2[1] == FunctionDefinition(
+            NoneToken(),
+            name=String('caller'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('y'),
+                        value=FunctionCall(
+                            String('fun2'),
+                            function_args=(
+                                Integer(2),
+                                Integer(3),
+                                Integer(4)
+                                )
+                            )
+                        )
+                    )
+                )
+            )
+
+        assert res3[0] == FunctionDefinition(
+            IntBaseType(String('intc')),
+            name=String('fun3'),
+            parameters=(
+                Variable(Symbol('a'),
+                    type=IntBaseType(String('intc'))
+                    ),
+                Variable(Symbol('b'),
+                    type=IntBaseType(String('intc'))
+                    ),
+                Variable(Symbol('c'),
+                    type=IntBaseType(String('intc'))
+                    )
+                ),
+            body=CodeBlock(
+                Return('b')
+                )
+            )
+
+        assert res3[1] == FunctionDefinition(
+            NoneToken(),
+            name=String('caller'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('p'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('q'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('r'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('z'),
+                        value=FunctionCall(
+                            String('fun3'),
+                            function_args=(
+                                Symbol('p'),
+                                Symbol('q'),
+                                Symbol('r')
+                                )
+                            )
+                        )
+                    )
+                )
+            )
+
+        assert res4[0] == FunctionDefinition(
+            IntBaseType(String('intc')),
+            name=String('fun4'),
+            parameters=(Variable(Symbol('a'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    )
+                ),
+            Variable(Symbol('b'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    )
+                ),
+            Variable(Symbol('c'),
+                type=IntBaseType(String('intc'))
+                )
+            ),
+            body=CodeBlock(
+                Return('c')
+                )
+            )
+
+        assert res4[1] == FunctionDefinition(
+            NoneToken(),
+            name=String('caller'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('x'),
+                        type=FloatType(
+                            String('float32'),
+                            nbits=Integer(32),
+                            nmant=Integer(23),
+                            nexp=Integer(8)
+                            )
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('y'),
+                        type=FloatType(
+                            String('float32'),
+                            nbits=Integer(32),
+                            nmant=Integer(23),
+                            nexp=Integer(8)
+                            )
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('z'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('i'),
+                        value=FunctionCall(String('fun4'),
+                            function_args=(
+                                Symbol('x'),
+                                Symbol('y'),
+                                Symbol('z')
+                                )
+                            )
+                        )
+                    )
+                )
+            )
+
+        assert res5[0] == FunctionDefinition(
+            IntBaseType(String('intc')),
+            name=String('fun'),
+            parameters=(),
+            body=CodeBlock(
+                Return('')
+                )
+            )
+
+        assert res5[1] == FunctionDefinition(
+            NoneToken(),
+            name=String('caller'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        value=FunctionCall(String('fun'),
+                            function_args=()
+                            )
+                        )
+                    )
+                )
+            )
+
+
+    def test_parse():
+        c_src1 = (
+            'int a;' + '\n' +
+            'int b;' + '\n'
+        )
+        c_src2 = (
+            'void fun1()' + '\n' +
+            '{' + '\n' +
+            'int a;' + '\n' +
+            '}'
+        )
+
+        f1 = open('..a.h', 'w')
+        f2 = open('..b.h', 'w')
+
+        f1.write(c_src1)
+        f2. write(c_src2)
+
+        f1.close()
+        f2.close()
+
+        res1 = SymPyExpression('..a.h', 'c').return_expr()
+        res2 = SymPyExpression('..b.h', 'c').return_expr()
+
+        os.remove('..a.h')
+        os.remove('..b.h')
+
+        assert res1[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type=IntBaseType(String('intc'))
+            )
+        )
+        assert res1[1] == Declaration(
+            Variable(
+                Symbol('b'),
+                type=IntBaseType(String('intc'))
+            )
+        )
+        assert res2[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('fun1'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(
+                        Symbol('a'),
+                        type=IntBaseType(String('intc'))
+                    )
+                )
+            )
+        )
+
+
+    def test_binary_operators():
+        c_src1 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a;' + '\n' +
+                'a = 1;' + '\n' +
+            '}'
+        )
+        c_src2 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a = 0;' + '\n' +
+                'a = a + 1;' + '\n' +
+                'a = 3*a - 10;' + '\n' +
+            '}'
+        )
+        c_src3 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a = 10;' + '\n' +
+                'a = 1 + a - 3 * 6;' + '\n' +
+            '}'
+        )
+        c_src4 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a;' + '\n' +
+                'int b;' + '\n' +
+                'a = 100;' + '\n' +
+                'b = a*a + a*a + a + 19*a + 1 + 24;' + '\n' +
+            '}'
+        )
+        c_src5 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a;' + '\n' +
+                'int b;' + '\n' +
+                'int c;' + '\n' +
+                'int d;' + '\n' +
+                'a = 1;' + '\n' +
+                'b = 2;' + '\n' +
+                'c = b;' + '\n' +
+                'd = ((a+b)*(a+c))*((c-d)*(a+c));' + '\n' +
+            '}'
+        )
+        c_src6 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a;' + '\n' +
+                'int b;' + '\n' +
+                'int c;' + '\n' +
+                'int d;' + '\n' +
+                'a = 1;' + '\n' +
+                'b = 2;' + '\n' +
+                'c = 3;' + '\n' +
+                'd = (a*a*a*a + 3*b*b + b + b + c*d);' + '\n' +
+            '}'
+        )
+        c_src7 = (
+            'void func()'+
+            '{' + '\n' +
+                'float a;' + '\n' +
+                'a = 1.01;' + '\n' +
+            '}'
+        )
+
+        c_src8 = (
+            'void func()'+
+            '{' + '\n' +
+                'float a;' + '\n' +
+                'a = 10.0 + 2.5;' + '\n' +
+            '}'
+        )
+
+        c_src9 = (
+            'void func()'+
+            '{' + '\n' +
+                'float a;' + '\n' +
+                'a = 10.0 / 2.5;' + '\n' +
+            '}'
+        )
+
+        c_src10 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a;' + '\n' +
+                'a = 100 / 4;' + '\n' +
+            '}'
+        )
+
+        c_src11 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a;' + '\n' +
+                'a = 20 - 100 / 4 * 5 + 10;' + '\n' +
+            '}'
+        )
+
+        c_src12 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a;' + '\n' +
+                'a = (20 - 100) / 4 * (5 + 10);' + '\n' +
+            '}'
+        )
+
+        c_src13 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a;' + '\n' +
+                'int b;' + '\n' +
+                'float c;' + '\n' +
+                'c = b/a;' + '\n' +
+            '}'
+        )
+
+        c_src14 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a = 2;' + '\n' +
+                'int d = 5;' + '\n' +
+                'int n = 10;' + '\n' +
+                'int s;' + '\n' +
+                's = (a/2)*(2*a + (n-1)*d);' + '\n' +
+            '}'
+        )
+
+        c_src15 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a;' + '\n' +
+                'a = 1 % 2;' + '\n' +
+            '}'
+        )
+
+        c_src16 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a = 2;' + '\n' +
+                'int b;' + '\n' +
+                'b = a % 3;' + '\n' +
+            '}'
+        )
+
+        c_src17 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a = 100;' + '\n' +
+                'int b = 3;' + '\n' +
+                'int c;' + '\n' +
+                'c = a % b;' + '\n' +
+            '}'
+        )
+
+        c_src18 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a = 100;' + '\n' +
+                'int b = 3;' + '\n' +
+                'int mod = 1000000007;' + '\n' +
+                'int c;' + '\n' +
+                'c = (a + b * (100/a)) % mod;' + '\n' +
+            '}'
+        )
+
+        c_src19 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a = 100;' + '\n' +
+                'int b = 3;' + '\n' +
+                'int mod = 1000000007;' + '\n' +
+                'int c;' + '\n' +
+                'c = ((a % mod + b % mod) % mod' \
+                '* (a % mod - b % mod) % mod) % mod;' + '\n' +
+            '}'
+        )
+
+        c_src20 = (
+            'void func()'+
+            '{' + '\n' +
+            'bool a' + '\n' +
+            'bool b;' + '\n' +
+            'a = 1 == 2;' + '\n' +
+            'b = 1 != 2;' + '\n' +
+            '}'
+        )
+
+        c_src21 = (
+            'void func()'+
+            '{' + '\n' +
+            'bool a;' + '\n' +
+            'bool b;' + '\n' +
+            'bool c;' + '\n' +
+            'bool d;' + '\n' +
+            'a = 1 == 2;' + '\n' +
+            'b = 1 <= 2;' + '\n' +
+            'c = 1 > 2;' + '\n' +
+            'd = 1 >= 2;' + '\n' +
+            '}'
+        )
+
+        c_src22 = (
+            'void func()'+
+            '{' + '\n' +
+            'int a = 1;' + '\n' +
+            'int b = 2;' + '\n' +
+
+            'bool c1;' + '\n' +
+            'bool c2;' + '\n' +
+            'bool c3;' + '\n' +
+            'bool c4;' + '\n' +
+            'bool c5;' + '\n' +
+            'bool c6;' + '\n' +
+            'bool c7;' + '\n' +
+            'bool c8;' + '\n' +
+
+            'c1 = a == 1;' + '\n' +
+            'c2 = b == 2;' + '\n' +
+
+            'c3 = 1 != a;' + '\n' +
+            'c4 = 1 != b;' + '\n' +
+
+            'c5 = a < 0;' + '\n' +
+            'c6 = b <= 10;' + '\n' +
+            'c7 = a > 0;' + '\n' +
+            'c8 = b >= 11;' + '\n' +
+            '}'
+        )
+
+        c_src23 = (
+            'void func()'+
+            '{' + '\n' +
+            'int a = 3;' + '\n' +
+            'int b = 4;' + '\n' +
+
+            'bool c1;' + '\n' +
+            'bool c2;' + '\n' +
+            'bool c3;' + '\n' +
+            'bool c4;' + '\n' +
+            'bool c5;' + '\n' +
+            'bool c6;' + '\n' +
+
+            'c1 = a == b;' + '\n' +
+            'c2 = a != b;' + '\n' +
+            'c3 = a < b;' + '\n' +
+            'c4 = a <= b;' + '\n' +
+            'c5 = a > b;' + '\n' +
+            'c6 = a >= b;' + '\n' +
+            '}'
+        )
+
+        c_src24 = (
+            'void func()'+
+            '{' + '\n' +
+            'float a = 1.25'
+            'float b = 2.5;' + '\n' +
+
+            'bool c1;' + '\n' +
+            'bool c2;' + '\n' +
+            'bool c3;' + '\n' +
+            'bool c4;' + '\n' +
+
+            'c1 = a == 1.25;' + '\n' +
+            'c2 = b == 2.54;' + '\n' +
+
+            'c3 = 1.2 != a;' + '\n' +
+            'c4 = 1.5 != b;' + '\n' +
+            '}'
+        )
+
+        c_src25 = (
+            'void func()'+
+            '{' + '\n' +
+            'float a = 1.25' + '\n' +
+            'float b = 2.5;' + '\n' +
+
+            'bool c1;' + '\n' +
+            'bool c2;' + '\n' +
+            'bool c3;' + '\n' +
+            'bool c4;' + '\n' +
+            'bool c5;' + '\n' +
+            'bool c6;' + '\n' +
+
+            'c1 = a == b;' + '\n' +
+            'c2 = a != b;' + '\n' +
+            'c3 = a < b;' + '\n' +
+            'c4 = a <= b;' + '\n' +
+            'c5 = a > b;' + '\n' +
+            'c6 = a >= b;' + '\n' +
+            '}'
+        )
+
+        c_src26 = (
+            'void func()'+
+            '{' + '\n' +
+            'bool c1;' + '\n' +
+            'bool c2;' + '\n' +
+            'bool c3;' + '\n' +
+            'bool c4;' + '\n' +
+            'bool c5;' + '\n' +
+            'bool c6;' + '\n' +
+
+            'c1 = true == true;' + '\n' +
+            'c2 = true == false;' + '\n' +
+            'c3 = false == false;' + '\n' +
+
+            'c4 = true != true;' + '\n' +
+            'c5 = true != false;' + '\n' +
+            'c6 = false != false;' + '\n' +
+            '}'
+        )
+
+        c_src27 = (
+            'void func()'+
+            '{' + '\n' +
+            'bool c1;' + '\n' +
+            'bool c2;' + '\n' +
+            'bool c3;' + '\n' +
+            'bool c4;' + '\n' +
+            'bool c5;' + '\n' +
+            'bool c6;' + '\n' +
+
+            'c1 = true && true;' + '\n' +
+            'c2 = true && false;' + '\n' +
+            'c3 = false && false;' + '\n' +
+
+            'c4 = true || true;' + '\n' +
+            'c5 = true || false;' + '\n' +
+            'c6 = false || false;' + '\n' +
+            '}'
+        )
+
+        c_src28 = (
+            'void func()'+
+            '{' + '\n' +
+            'bool a;' + '\n' +
+            'bool c1;' + '\n' +
+            'bool c2;' + '\n' +
+            'bool c3;' + '\n' +
+            'bool c4;' + '\n' +
+
+            'c1 = a && true;' + '\n' +
+            'c2 = false && a;' + '\n' +
+
+            'c3 = true || a;' + '\n' +
+            'c4 = a || false;' + '\n' +
+            '}'
+        )
+
+        c_src29 = (
+            'void func()'+
+            '{' + '\n' +
+            'int a;' + '\n' +
+            'bool c1;' + '\n' +
+            'bool c2;' + '\n' +
+            'bool c3;' + '\n' +
+            'bool c4;' + '\n' +
+
+            'c1 = a && 1;' + '\n' +
+            'c2 = a && 0;' + '\n' +
+
+            'c3 = a || 1;' + '\n' +
+            'c4 = 0 || a;' + '\n' +
+            '}'
+        )
+
+        c_src30 = (
+            'void func()'+
+            '{' + '\n' +
+            'int a;' + '\n' +
+            'int b;' + '\n' +
+            'bool c;'+ '\n' +
+            'bool d;'+ '\n' +
+
+            'bool c1;' + '\n' +
+            'bool c2;' + '\n' +
+            'bool c3;' + '\n' +
+            'bool c4;' + '\n' +
+            'bool c5;' + '\n' +
+            'bool c6;' + '\n' +
+
+            'c1 = a && b;' + '\n' +
+            'c2 = a && c;' + '\n' +
+            'c3 = c && d;' + '\n' +
+
+            'c4 = a || b;' + '\n' +
+            'c5 = a || c;' + '\n' +
+            'c6 = c || d;' + '\n' +
+            '}'
+        )
+
+        c_src_raise1 = (
+            'void func()'+
+            '{' + '\n' +
+            'int a;' + '\n' +
+            'a = -1;' + '\n' +
+            '}'
+        )
+
+        c_src_raise2 = (
+            'void func()'+
+            '{' + '\n' +
+            'int a;' + '\n' +
+            'a = -+1;' + '\n' +
+            '}'
+        )
+
+        c_src_raise3 = (
+            'void func()'+
+            '{' + '\n' +
+            'int a;' + '\n' +
+            'a = 2*-2;' + '\n' +
+            '}'
+        )
+
+        c_src_raise4 = (
+            'void func()'+
+            '{' + '\n' +
+            'int a;' + '\n' +
+            'a = (int)2.0;' + '\n' +
+            '}'
+        )
+
+        c_src_raise5 = (
+            'void func()'+
+            '{' + '\n' +
+            'int a=100;' + '\n' +
+            'a = (a==100)?(1):(0);' + '\n' +
+            '}'
+        )
+
+        res1 = SymPyExpression(c_src1, 'c').return_expr()
+        res2 = SymPyExpression(c_src2, 'c').return_expr()
+        res3 = SymPyExpression(c_src3, 'c').return_expr()
+        res4 = SymPyExpression(c_src4, 'c').return_expr()
+        res5 = SymPyExpression(c_src5, 'c').return_expr()
+        res6 = SymPyExpression(c_src6, 'c').return_expr()
+        res7 = SymPyExpression(c_src7, 'c').return_expr()
+        res8 = SymPyExpression(c_src8, 'c').return_expr()
+        res9 = SymPyExpression(c_src9, 'c').return_expr()
+        res10 = SymPyExpression(c_src10, 'c').return_expr()
+        res11 = SymPyExpression(c_src11, 'c').return_expr()
+        res12 = SymPyExpression(c_src12, 'c').return_expr()
+        res13 = SymPyExpression(c_src13, 'c').return_expr()
+        res14 = SymPyExpression(c_src14, 'c').return_expr()
+        res15 = SymPyExpression(c_src15, 'c').return_expr()
+        res16 = SymPyExpression(c_src16, 'c').return_expr()
+        res17 = SymPyExpression(c_src17, 'c').return_expr()
+        res18 = SymPyExpression(c_src18, 'c').return_expr()
+        res19 = SymPyExpression(c_src19, 'c').return_expr()
+        res20 = SymPyExpression(c_src20, 'c').return_expr()
+        res21 = SymPyExpression(c_src21, 'c').return_expr()
+        res22 = SymPyExpression(c_src22, 'c').return_expr()
+        res23 = SymPyExpression(c_src23, 'c').return_expr()
+        res24 = SymPyExpression(c_src24, 'c').return_expr()
+        res25 = SymPyExpression(c_src25, 'c').return_expr()
+        res26 = SymPyExpression(c_src26, 'c').return_expr()
+        res27 = SymPyExpression(c_src27, 'c').return_expr()
+        res28 = SymPyExpression(c_src28, 'c').return_expr()
+        res29 = SymPyExpression(c_src29, 'c').return_expr()
+        res30 = SymPyExpression(c_src30, 'c').return_expr()
+
+        assert res1[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Assignment(Variable(Symbol('a')), Integer(1))
+                )
+            )
+
+        assert res2[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                    type=IntBaseType(String('intc')),
+                    value=Integer(0))),
+                Assignment(
+                    Variable(Symbol('a')),
+                    Add(Symbol('a'),
+                        Integer(1))
+                    ),
+                Assignment(Variable(Symbol('a')),
+                    Add(
+                        Mul(
+                            Integer(3),
+                            Symbol('a')),
+                        Integer(-10)
+                        )
+                    )
+                )
+            )
+
+        assert res3[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(10)
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('a')),
+                    Add(
+                        Symbol('a'),
+                        Integer(-17)
+                        )
+                    )
+                )
+            )
+
+        assert res4[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('b'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('a')),
+                    Integer(100)),
+                Assignment(
+                    Variable(Symbol('b')),
+                    Add(
+                        Mul(
+                            Integer(2),
+                        Pow(
+                            Symbol('a'),
+                            Integer(2))
+                        ),
+                        Mul(
+                            Integer(20),
+                            Symbol('a')),
+                        Integer(25)
+                        )
+                    )
+                )
+            )
+
+        assert res5[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('b'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('d'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('a')),
+                    Integer(1)),
+                Assignment(
+                    Variable(Symbol('b')),
+                    Integer(2)
+                    ),
+                Assignment(
+                    Variable(Symbol('c')),
+                    Symbol('b')),
+                Assignment(
+                    Variable(Symbol('d')),
+                    Mul(
+                        Add(
+                            Symbol('a'),
+                            Symbol('b')),
+                        Pow(
+                            Add(
+                                Symbol('a'),
+                                Symbol('c')
+                                ),
+                            Integer(2)
+                            ),
+                        Add(
+                            Symbol('c'),
+                            Mul(
+                                Integer(-1),
+                                Symbol('d')
+                                )
+                            )
+                        )
+                    )
+                )
+            )
+
+        assert res6[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('b'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('d'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('a')),
+                    Integer(1)
+                    ),
+                Assignment(
+                    Variable(Symbol('b')),
+                    Integer(2)
+                    ),
+                Assignment(
+                    Variable(Symbol('c')),
+                    Integer(3)
+                    ),
+                Assignment(
+                    Variable(Symbol('d')),
+                    Add(
+                        Pow(
+                            Symbol('a'),
+                            Integer(4)
+                            ),
+                        Mul(
+                            Integer(3),
+                            Pow(
+                                Symbol('b'),
+                                Integer(2)
+                                )
+                            ),
+                        Mul(
+                            Integer(2),
+                            Symbol('b')
+                            ),
+                        Mul(
+                            Symbol('c'),
+                            Symbol('d')
+                            )
+                        )
+                    )
+                )
+            )
+
+        assert res7[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=FloatType(
+                            String('float32'),
+                            nbits=Integer(32),
+                            nmant=Integer(23),
+                            nexp=Integer(8)
+                            )
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('a')),
+                    Float('1.01', precision=53)
+                    )
+                )
+            )
+
+        assert res8[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=FloatType(
+                            String('float32'),
+                            nbits=Integer(32),
+                            nmant=Integer(23),
+                            nexp=Integer(8)
+                            )
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('a')),
+                    Float('12.5', precision=53)
+                    )
+                )
+            )
+
+        assert res9[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=FloatType(
+                            String('float32'),
+                            nbits=Integer(32),
+                            nmant=Integer(23),
+                            nexp=Integer(8)
+                            )
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('a')),
+                    Float('4.0', precision=53)
+                    )
+                )
+            )
+
+        assert res10[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('a')),
+                    Integer(25)
+                    )
+                )
+            )
+
+        assert res11[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('a')),
+                    Integer(-95)
+                    )
+                )
+            )
+
+        assert res12[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('a')),
+                    Integer(-300)
+                    )
+                )
+            )
+
+        assert res13[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('b'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c'),
+                        type=FloatType(
+                            String('float32'),
+                            nbits=Integer(32),
+                            nmant=Integer(23),
+                            nexp=Integer(8)
+                            )
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c')),
+                    Mul(
+                        Pow(
+                            Symbol('a'),
+                            Integer(-1)
+                            ),
+                        Symbol('b')
+                        )
+                    )
+                )
+            )
+
+        assert res14[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(2)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('d'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(5)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('n'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(10)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('s'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('s')),
+                    Mul(
+                        Rational(1, 2),
+                        Symbol('a'),
+                        Add(
+                            Mul(
+                                Integer(2),
+                                Symbol('a')
+                                ),
+                            Mul(
+                                Symbol('d'),
+                                Add(
+                                    Symbol('n'),
+                                    Integer(-1)
+                                    )
+                                )
+                            )
+                        )
+                    )
+                )
+            )
+
+        assert res15[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('a')),
+                    Integer(1)
+                    )
+                )
+            )
+
+        assert res16[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(2)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('b'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('b')),
+                    Mod(
+                        Symbol('a'),
+                        Integer(3)
+                        )
+                    )
+                )
+            )
+
+        assert res17[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(100)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('b'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(3)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c')),
+                    Mod(
+                        Symbol('a'),
+                        Symbol('b')
+                        )
+                    )
+                )
+            )
+
+        assert res18[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(100)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('b'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(3)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('mod'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(1000000007)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c')),
+                    Mod(
+                        Add(
+                            Symbol('a'),
+                            Mul(
+                                Integer(100),
+                                Pow(
+                                    Symbol('a'),
+                                    Integer(-1)
+                                    ),
+                                Symbol('b')
+                                )
+                            ),
+                        Symbol('mod')
+                        )
+                    )
+                )
+            )
+
+        assert res19[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(100)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('b'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(3)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('mod'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(1000000007)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c')),
+                    Mod(
+                        Mul(
+                            Add(
+                                Mod(
+                                    Symbol('a'),
+                                    Symbol('mod')
+                                    ),
+                                Mul(
+                                    Integer(-1),
+                                    Mod(
+                                        Symbol('b'),
+                                        Symbol('mod')
+                                        )
+                                    )
+                                ),
+                            Mod(
+                                Add(
+                                    Symbol('a'),
+                                    Symbol('b')
+                                    ),
+                                Symbol('mod')
+                                )
+                            ),
+                        Symbol('mod')
+                        )
+                    )
+                )
+            )
+
+        assert res20[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('b'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('a')),
+                    false
+                    ),
+                Assignment(
+                    Variable(Symbol('b')),
+                    true
+                    )
+                )
+            )
+
+        assert res21[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('b'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('d'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('a')),
+                    false
+                    ),
+                Assignment(
+                    Variable(Symbol('b')),
+                    true
+                    ),
+                Assignment(
+                    Variable(Symbol('c')),
+                    false
+                    ),
+                Assignment(
+                    Variable(Symbol('d')),
+                    false
+                    )
+                )
+            )
+
+        assert res22[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(1)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('b'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(2)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c1'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c2'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c3'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c4'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c5'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c6'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c7'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c8'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c1')),
+                    Equality(
+                        Symbol('a'),
+                        Integer(1)
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c2')),
+                    Equality(
+                        Symbol('b'),
+                        Integer(2)
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c3')),
+                    Unequality(
+                        Integer(1),
+                        Symbol('a')
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c4')),
+                    Unequality(
+                        Integer(1),
+                        Symbol('b')
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c5')),
+                    StrictLessThan(
+                        Symbol('a'),
+                        Integer(0)
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c6')),
+                    LessThan(
+                        Symbol('b'),
+                        Integer(10)
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c7')),
+                    StrictGreaterThan(
+                        Symbol('a'),
+                        Integer(0)
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c8')),
+                    GreaterThan(
+                        Symbol('b'),
+                        Integer(11)
+                        )
+                    )
+                )
+            )
+
+        assert res23[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(3)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('b'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(4)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c1'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c2'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c3'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c4'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c5'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c6'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c1')),
+                    Equality(
+                        Symbol('a'),
+                        Symbol('b')
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c2')),
+                    Unequality(
+                        Symbol('a'),
+                        Symbol('b')
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c3')),
+                    StrictLessThan(
+                        Symbol('a'),
+                        Symbol('b')
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c4')),
+                    LessThan(
+                        Symbol('a'),
+                        Symbol('b')
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c5')),
+                    StrictGreaterThan(
+                        Symbol('a'),
+                        Symbol('b')
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c6')),
+                    GreaterThan(
+                        Symbol('a'),
+                        Symbol('b')
+                        )
+                    )
+                )
+            )
+
+        assert res24[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=FloatType(
+                            String('float32'),
+                            nbits=Integer(32),
+                            nmant=Integer(23),
+                            nexp=Integer(8)
+                            )
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c1'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c2'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c3'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c4'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c1')),
+                    Equality(
+                        Symbol('a'),
+                        Float('1.25', precision=53)
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c3')),
+                    Unequality(
+                        Float('1.2', precision=53),
+                        Symbol('a')
+                        )
+                    )
+                )
+            )
+
+
+        assert res25[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=FloatType(
+                            String('float32'),
+                            nbits=Integer(32),
+                            nmant=Integer(23),
+                            nexp=Integer(8)
+                            ),
+                        value=Float('1.25', precision=53)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('b'),
+                        type=FloatType(
+                            String('float32'),
+                            nbits=Integer(32),
+                            nmant=Integer(23),
+                            nexp=Integer(8)
+                            ),
+                        value=Float('2.5', precision=53)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c1'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c2'),
+                        type=Type(String('bool')
+                            )
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c3'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c4'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c5'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c6'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c1')),
+                    Equality(
+                        Symbol('a'),
+                        Symbol('b')
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c2')),
+                    Unequality(
+                        Symbol('a'),
+                        Symbol('b')
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c3')),
+                    StrictLessThan(
+                        Symbol('a'),
+                        Symbol('b')
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c4')),
+                    LessThan(
+                        Symbol('a'),
+                        Symbol('b')
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c5')),
+                    StrictGreaterThan(
+                        Symbol('a'),
+                        Symbol('b')
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c6')),
+                    GreaterThan(
+                        Symbol('a'),
+                        Symbol('b')
+                        )
+                    )
+                )
+            )
+
+        assert res26[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(), body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('c1'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c2'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c3'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c4'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c5'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c6'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c1')),
+                    true
+                    ),
+                Assignment(
+                    Variable(Symbol('c2')),
+                    false
+                    ),
+                Assignment(
+                    Variable(Symbol('c3')),
+                    true
+                    ),
+                Assignment(
+                    Variable(Symbol('c4')),
+                    false
+                    ),
+                Assignment(
+                    Variable(Symbol('c5')),
+                    true
+                    ),
+                Assignment(
+                    Variable(Symbol('c6')),
+                    false
+                    )
+                )
+            )
+
+        assert res27[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('c1'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c2'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c3'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c4'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c5'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c6'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c1')),
+                    true
+                    ),
+                Assignment(
+                    Variable(Symbol('c2')),
+                    false
+                    ),
+                Assignment(
+                    Variable(Symbol('c3')),
+                    false
+                    ),
+                Assignment(
+                    Variable(Symbol('c4')),
+                    true
+                    ),
+                Assignment(
+                    Variable(Symbol('c5')),
+                    true
+                    ),
+                Assignment(
+                    Variable(Symbol('c6')),
+                    false)
+                )
+            )
+
+        assert res28[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c1'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c2'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c3'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c4'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c1')),
+                    Symbol('a')
+                    ),
+                Assignment(
+                    Variable(Symbol('c2')),
+                    false
+                    ),
+                Assignment(
+                    Variable(Symbol('c3')),
+                    true
+                    ),
+                Assignment(
+                    Variable(Symbol('c4')),
+                    Symbol('a')
+                    )
+                )
+            )
+
+        assert res29[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c1'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c2'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c3'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c4'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c1')),
+                    Symbol('a')
+                    ),
+                Assignment(
+                    Variable(Symbol('c2')),
+                    false
+                    ),
+                Assignment(
+                    Variable(Symbol('c3')),
+                    true
+                    ),
+                Assignment(
+                    Variable(Symbol('c4')),
+                    Symbol('a')
+                    )
+                )
+            )
+
+        assert res30[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('b'),
+                        type=IntBaseType(String('intc'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('d'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c1'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c2'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c3'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c4'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c5'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c6'),
+                        type=Type(String('bool'))
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c1')),
+                    And(
+                        Symbol('a'),
+                        Symbol('b')
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c2')),
+                    And(
+                        Symbol('a'),
+                        Symbol('c')
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c3')),
+                    And(
+                        Symbol('c'),
+                        Symbol('d')
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c4')),
+                    Or(
+                        Symbol('a'),
+                        Symbol('b')
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c5')),
+                    Or(
+                        Symbol('a'),
+                        Symbol('c')
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('c6')),
+                    Or(
+                        Symbol('c'),
+                        Symbol('d')
+                        )
+                    )
+                )
+            )
+
+        raises(NotImplementedError, lambda: SymPyExpression(c_src_raise1, 'c'))
+        raises(NotImplementedError, lambda: SymPyExpression(c_src_raise2, 'c'))
+        raises(NotImplementedError, lambda: SymPyExpression(c_src_raise3, 'c'))
+        raises(NotImplementedError, lambda: SymPyExpression(c_src_raise4, 'c'))
+        raises(NotImplementedError, lambda: SymPyExpression(c_src_raise5, 'c'))
+
+
+    @XFAIL
+    def test_var_decl():
+        c_src1 = (
+            'int b = 100;' + '\n' +
+            'int a = b;' + '\n'
+        )
+
+        c_src2 = (
+            'int a = 1;' + '\n' +
+            'int b = a + 1;' + '\n'
+        )
+
+        c_src3 = (
+            'float a = 10.0 + 2.5;' + '\n' +
+            'float b = a * 20.0;' + '\n'
+        )
+
+        c_src4 = (
+            'int a = 1 + 100 - 3 * 6;' + '\n'
+        )
+
+        c_src5 = (
+            'int a = (((1 + 100) * 12) - 3) * (6 - 10);' + '\n'
+        )
+
+        c_src6 = (
+            'int b = 2;' + '\n' +
+            'int c = 3;' + '\n' +
+            'int a = b + c * 4;' + '\n'
+        )
+
+        c_src7 = (
+            'int b = 1;' + '\n' +
+            'int c = b + 2;' + '\n' +
+            'int a = 10 * b * b * c;' + '\n'
+        )
+
+        c_src8 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a = 1;' + '\n' +
+                'int b = 2;' + '\n' +
+                'int temp = a;' + '\n' +
+                'a = b;' + '\n' +
+                'b = temp;' + '\n' +
+            '}'
+        )
+
+        c_src9 = (
+            'int a = 1;' + '\n' +
+            'int b = 2;' + '\n' +
+            'int c = a;' + '\n' +
+            'int d = a + b + c;' + '\n' +
+            'int e = a*a*a + 3*a*a*b + 3*a*b*b + b*b*b;' + '\n'
+            'int f = (a + b + c) * (a + b - c);' + '\n' +
+            'int g = (a + b + c + d)*(a + b + c + d)*(a * (b - c));'
+            + '\n'
+        )
+
+        c_src10 = (
+            'float a = 10.0;' + '\n' +
+            'float b = 2.5;' + '\n' +
+            'float c = a*a + 2*a*b + b*b;' + '\n'
+        )
+
+        c_src11 = (
+            'float a = 10.0 / 2.5;' + '\n'
+        )
+
+        c_src12 = (
+            'int a = 100 / 4;' + '\n'
+        )
+
+        c_src13 = (
+            'int a = 20 - 100 / 4 * 5 + 10;' + '\n'
+        )
+
+        c_src14 = (
+            'int a = (20 - 100) / 4 * (5 + 10);' + '\n'
+        )
+
+        c_src15 = (
+            'int a = 4;' + '\n' +
+            'int b = 2;' + '\n' +
+            'float c = b/a;' + '\n'
+        )
+
+        c_src16 = (
+            'int a = 2;' + '\n' +
+            'int d = 5;' + '\n' +
+            'int n = 10;' + '\n' +
+            'int s = (a/2)*(2*a + (n-1)*d);' + '\n'
+        )
+
+        c_src17 = (
+            'int a = 1 % 2;' + '\n'
+        )
+
+        c_src18 = (
+            'int a = 2;' + '\n' +
+            'int b = a % 3;' + '\n'
+        )
+
+        c_src19 = (
+            'int a = 100;' + '\n' +
+            'int b = 3;' + '\n' +
+            'int c = a % b;' + '\n'
+        )
+
+        c_src20 = (
+            'int a = 100;' + '\n' +
+            'int b = 3;' + '\n' +
+            'int mod = 1000000007;' + '\n' +
+            'int c = (a + b * (100/a)) % mod;' + '\n'
+        )
+
+        c_src21 = (
+            'int a = 100;' + '\n' +
+            'int b = 3;' + '\n' +
+            'int mod = 1000000007;' + '\n' +
+            'int c = ((a % mod + b % mod) % mod *' \
+            '(a % mod - b % mod) % mod) % mod;' + '\n'
+        )
+
+        c_src22 = (
+            'bool a = 1 == 2, b = 1 != 2;'
+        )
+
+        c_src23 = (
+            'bool a = 1 < 2, b = 1 <= 2, c = 1 > 2, d = 1 >= 2;'
+        )
+
+        c_src24 = (
+            'int a = 1, b = 2;' + '\n' +
+
+            'bool c1 = a == 1;' + '\n' +
+            'bool c2 = b == 2;' + '\n' +
+
+            'bool c3 = 1 != a;' + '\n' +
+            'bool c4 = 1 != b;' + '\n' +
+
+            'bool c5 = a < 0;' + '\n' +
+            'bool c6 = b <= 10;' + '\n' +
+            'bool c7 = a > 0;' + '\n' +
+            'bool c8 = b >= 11;'
+
+        )
+
+        c_src25 = (
+            'int a = 3, b = 4;' + '\n' +
+
+            'bool c1 = a == b;' + '\n' +
+            'bool c2 = a != b;' + '\n' +
+            'bool c3 = a < b;' + '\n' +
+            'bool c4 = a <= b;' + '\n' +
+            'bool c5 = a > b;' + '\n' +
+            'bool c6 = a >= b;'
+        )
+
+        c_src26 = (
+            'float a = 1.25, b = 2.5;' + '\n' +
+
+            'bool c1 = a == 1.25;' + '\n' +
+            'bool c2 = b == 2.54;' + '\n' +
+
+            'bool c3 = 1.2 != a;' + '\n' +
+            'bool c4 = 1.5 != b;'
+        )
+
+        c_src27 = (
+            'float a = 1.25, b = 2.5;' + '\n' +
+
+            'bool c1 = a == b;' + '\n' +
+            'bool c2 = a != b;' + '\n' +
+            'bool c3 = a < b;' + '\n' +
+            'bool c4 = a <= b;' + '\n' +
+            'bool c5 = a > b;' + '\n' +
+            'bool c6 = a >= b;'
+        )
+
+        c_src28 = (
+            'bool c1 = true == true;' + '\n' +
+            'bool c2 = true == false;' + '\n' +
+            'bool c3 = false == false;' + '\n' +
+
+            'bool c4 = true != true;' + '\n' +
+            'bool c5 = true != false;' + '\n' +
+            'bool c6 = false != false;'
+        )
+
+        c_src29 = (
+            'bool c1 = true && true;' + '\n' +
+            'bool c2 = true && false;' + '\n' +
+            'bool c3 = false && false;' + '\n' +
+
+            'bool c4 = true || true;' + '\n' +
+            'bool c5 = true || false;' + '\n' +
+            'bool c6 = false || false;'
+        )
+
+        c_src30 = (
+            'bool a = false;' + '\n' +
+
+            'bool c1 = a && true;' + '\n' +
+            'bool c2 = false && a;' + '\n' +
+
+            'bool c3 = true || a;' + '\n' +
+            'bool c4 = a || false;'
+        )
+
+        c_src31 = (
+            'int a = 1;' + '\n' +
+
+            'bool c1 = a && 1;' + '\n' +
+            'bool c2 = a && 0;' + '\n' +
+
+            'bool c3 = a || 1;' + '\n' +
+            'bool c4 = 0 || a;'
+        )
+
+        c_src32 = (
+            'int a = 1, b = 0;' + '\n' +
+            'bool c = false, d = true;'+ '\n' +
+
+            'bool c1 = a && b;' + '\n' +
+            'bool c2 = a && c;' + '\n' +
+            'bool c3 = c && d;' + '\n' +
+
+            'bool c4 = a || b;' + '\n' +
+            'bool c5 = a || c;' + '\n' +
+            'bool c6 = c || d;'
+        )
+
+        c_src_raise1 = (
+            "char a = 'b';"
+        )
+
+        c_src_raise2 = (
+            'int a[] = {10, 20};'
+        )
+
+        res1 = SymPyExpression(c_src1, 'c').return_expr()
+        res2 = SymPyExpression(c_src2, 'c').return_expr()
+        res3 = SymPyExpression(c_src3, 'c').return_expr()
+        res4 = SymPyExpression(c_src4, 'c').return_expr()
+        res5 = SymPyExpression(c_src5, 'c').return_expr()
+        res6 = SymPyExpression(c_src6, 'c').return_expr()
+        res7 = SymPyExpression(c_src7, 'c').return_expr()
+        res8 = SymPyExpression(c_src8, 'c').return_expr()
+        res9 = SymPyExpression(c_src9, 'c').return_expr()
+        res10 = SymPyExpression(c_src10, 'c').return_expr()
+        res11 = SymPyExpression(c_src11, 'c').return_expr()
+        res12 = SymPyExpression(c_src12, 'c').return_expr()
+        res13 = SymPyExpression(c_src13, 'c').return_expr()
+        res14 = SymPyExpression(c_src14, 'c').return_expr()
+        res15 = SymPyExpression(c_src15, 'c').return_expr()
+        res16 = SymPyExpression(c_src16, 'c').return_expr()
+        res17 = SymPyExpression(c_src17, 'c').return_expr()
+        res18 = SymPyExpression(c_src18, 'c').return_expr()
+        res19 = SymPyExpression(c_src19, 'c').return_expr()
+        res20 = SymPyExpression(c_src20, 'c').return_expr()
+        res21 = SymPyExpression(c_src21, 'c').return_expr()
+        res22 = SymPyExpression(c_src22, 'c').return_expr()
+        res23 = SymPyExpression(c_src23, 'c').return_expr()
+        res24 = SymPyExpression(c_src24, 'c').return_expr()
+        res25 = SymPyExpression(c_src25, 'c').return_expr()
+        res26 = SymPyExpression(c_src26, 'c').return_expr()
+        res27 = SymPyExpression(c_src27, 'c').return_expr()
+        res28 = SymPyExpression(c_src28, 'c').return_expr()
+        res29 = SymPyExpression(c_src29, 'c').return_expr()
+        res30 = SymPyExpression(c_src30, 'c').return_expr()
+        res31 = SymPyExpression(c_src31, 'c').return_expr()
+        res32 = SymPyExpression(c_src32, 'c').return_expr()
+
+        assert res1[0] == Declaration(
+            Variable(Symbol('b'),
+                type=IntBaseType(String('intc')),
+                value=Integer(100)
+                )
+            )
+
+        assert res1[1] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Symbol('b')
+                )
+            )
+
+        assert res2[0] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(1)
+                )
+            )
+
+        assert res2[1] == Declaration(Variable(Symbol('b'),
+            type=IntBaseType(String('intc')),
+            value=Add(
+                Symbol('a'),
+                Integer(1)
+                )
+            )
+        )
+
+        assert res3[0] == Declaration(
+            Variable(Symbol('a'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('12.5', precision=53)
+                )
+            )
+
+        assert res3[1] == Declaration(
+            Variable(Symbol('b'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Mul(
+                    Float('20.0', precision=53),
+                    Symbol('a')
+                    )
+                )
+            )
+
+        assert res4[0] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(83)
+                )
+            )
+
+        assert res5[0] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(-4836)
+                )
+            )
+
+        assert res6[0] == Declaration(
+            Variable(Symbol('b'),
+                type=IntBaseType(String('intc')),
+                value=Integer(2)
+                )
+            )
+
+        assert res6[1] == Declaration(
+            Variable(Symbol('c'),
+                type=IntBaseType(String('intc')),
+                value=Integer(3)
+                )
+            )
+
+        assert res6[2] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Add(
+                    Symbol('b'),
+                    Mul(
+                        Integer(4),
+                        Symbol('c')
+                        )
+                    )
+                )
+            )
+
+        assert res7[0] == Declaration(
+            Variable(Symbol('b'),
+                type=IntBaseType(String('intc')),
+                value=Integer(1)
+                )
+            )
+
+        assert res7[1] == Declaration(
+            Variable(Symbol('c'),
+                type=IntBaseType(String('intc')),
+                value=Add(
+                    Symbol('b'),
+                    Integer(2)
+                    )
+                )
+            )
+
+        assert res7[2] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Mul(
+                    Integer(10),
+                    Pow(
+                        Symbol('b'),
+                        Integer(2)
+                        ),
+                    Symbol('c')
+                    )
+                )
+            )
+
+        assert res8[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(1)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('b'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(2)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('temp'),
+                        type=IntBaseType(String('intc')),
+                        value=Symbol('a')
+                        )
+                    ),
+                Assignment(
+                    Variable(Symbol('a')),
+                    Symbol('b')
+                    ),
+                Assignment(
+                    Variable(Symbol('b')),
+                    Symbol('temp')
+                    )
+                )
+            )
+
+        assert res9[0] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(1)
+                )
+            )
+
+        assert res9[1] == Declaration(
+            Variable(Symbol('b'),
+                type=IntBaseType(String('intc')),
+                value=Integer(2)
+                )
+            )
+
+        assert res9[2] == Declaration(
+            Variable(Symbol('c'),
+                type=IntBaseType(String('intc')),
+                value=Symbol('a')
+                )
+            )
+
+        assert res9[3] == Declaration(
+            Variable(Symbol('d'),
+                type=IntBaseType(String('intc')),
+                value=Add(
+                    Symbol('a'),
+                    Symbol('b'),
+                    Symbol('c')
+                    )
+                )
+            )
+
+        assert res9[4] == Declaration(
+            Variable(Symbol('e'),
+                type=IntBaseType(String('intc')),
+                value=Add(
+                    Pow(
+                        Symbol('a'),
+                        Integer(3)
+                        ),
+                    Mul(
+                        Integer(3),
+                        Pow(
+                            Symbol('a'),
+                            Integer(2)
+                            ),
+                        Symbol('b')
+                        ),
+                    Mul(
+                        Integer(3),
+                        Symbol('a'),
+                        Pow(
+                            Symbol('b'),
+                            Integer(2)
+                            )
+                        ),
+                    Pow(
+                        Symbol('b'),
+                        Integer(3)
+                        )
+                    )
+                )
+            )
+
+        assert res9[5] == Declaration(
+            Variable(Symbol('f'),
+                type=IntBaseType(String('intc')),
+                value=Mul(
+                    Add(
+                        Symbol('a'),
+                        Symbol('b'),
+                        Mul(
+                            Integer(-1),
+                            Symbol('c')
+                            )
+                        ),
+                    Add(
+                        Symbol('a'),
+                        Symbol('b'),
+                        Symbol('c')
+                        )
+                    )
+                )
+            )
+
+        assert res9[6] == Declaration(
+            Variable(Symbol('g'),
+                type=IntBaseType(String('intc')),
+                value=Mul(
+                    Symbol('a'),
+                    Add(
+                        Symbol('b'),
+                        Mul(
+                            Integer(-1),
+                            Symbol('c')
+                            )
+                        ),
+                    Pow(
+                        Add(
+                            Symbol('a'),
+                            Symbol('b'),
+                            Symbol('c'),
+                            Symbol('d')
+                            ),
+                        Integer(2)
+                        )
+                    )
+                )
+            )
+
+        assert res10[0] == Declaration(
+            Variable(Symbol('a'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('10.0', precision=53)
+                )
+            )
+
+        assert res10[1] == Declaration(
+            Variable(Symbol('b'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('2.5', precision=53)
+                )
+            )
+
+        assert res10[2] == Declaration(
+            Variable(Symbol('c'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Add(
+                    Pow(
+                        Symbol('a'),
+                        Integer(2)
+                        ),
+                    Mul(
+                        Integer(2),
+                        Symbol('a'),
+                        Symbol('b')
+                        ),
+                    Pow(
+                        Symbol('b'),
+                        Integer(2)
+                        )
+                    )
+                )
+            )
+
+        assert res11[0] == Declaration(
+            Variable(Symbol('a'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('4.0', precision=53)
+                )
+            )
+
+        assert res12[0] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(25)
+                )
+            )
+
+        assert res13[0] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(-95)
+                )
+            )
+
+        assert res14[0] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(-300)
+                )
+            )
+
+        assert res15[0] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(4)
+                )
+            )
+
+        assert res15[1] == Declaration(
+            Variable(Symbol('b'),
+                type=IntBaseType(String('intc')),
+                value=Integer(2)
+                )
+            )
+
+        assert res15[2] == Declaration(
+            Variable(Symbol('c'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Mul(
+                    Pow(
+                        Symbol('a'),
+                        Integer(-1)
+                        ),
+                    Symbol('b')
+                    )
+                )
+            )
+
+        assert res16[0] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(2)
+                )
+            )
+
+        assert res16[1] == Declaration(
+            Variable(Symbol('d'),
+                type=IntBaseType(String('intc')),
+                value=Integer(5)
+                )
+            )
+
+        assert res16[2] == Declaration(
+            Variable(Symbol('n'),
+                type=IntBaseType(String('intc')),
+                value=Integer(10)
+                )
+            )
+
+        assert res16[3] == Declaration(
+            Variable(Symbol('s'),
+                type=IntBaseType(String('intc')),
+                value=Mul(
+                    Rational(1, 2),
+                    Symbol('a'),
+                    Add(
+                        Mul(
+                            Integer(2),
+                            Symbol('a')
+                            ),
+                        Mul(
+                            Symbol('d'),
+                            Add(
+                                Symbol('n'),
+                                Integer(-1)
+                                )
+                            )
+                        )
+                    )
+                )
+            )
+
+        assert res17[0] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(1)
+                )
+            )
+
+        assert res18[0] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(2)
+                )
+            )
+
+        assert res18[1] == Declaration(
+            Variable(Symbol('b'),
+                type=IntBaseType(String('intc')),
+                value=Mod(
+                    Symbol('a'),
+                    Integer(3)
+                    )
+                )
+            )
+
+        assert res19[0] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(100)
+                )
+            )
+        assert res19[1] == Declaration(
+            Variable(Symbol('b'),
+                type=IntBaseType(String('intc')),
+                value=Integer(3)
+                )
+            )
+
+        assert res19[2] == Declaration(
+            Variable(Symbol('c'),
+                type=IntBaseType(String('intc')),
+                value=Mod(
+                    Symbol('a'),
+                    Symbol('b')
+                    )
+                )
+            )
+
+        assert res20[0] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(100)
+                )
+            )
+
+        assert res20[1] == Declaration(
+            Variable(Symbol('b'),
+                type=IntBaseType(String('intc')),
+                value=Integer(3)
+                )
+            )
+
+        assert res20[2] == Declaration(
+            Variable(Symbol('mod'),
+                type=IntBaseType(String('intc')),
+                value=Integer(1000000007)
+                )
+            )
+
+        assert res20[3] == Declaration(
+            Variable(Symbol('c'),
+                type=IntBaseType(String('intc')),
+                value=Mod(
+                    Add(
+                        Symbol('a'),
+                        Mul(
+                            Integer(100),
+                            Pow(
+                                Symbol('a'),
+                                Integer(-1)
+                                ),
+                            Symbol('b')
+                            )
+                        ),
+                    Symbol('mod')
+                    )
+                )
+            )
+
+        assert res21[0] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(100)
+                )
+            )
+
+        assert res21[1] == Declaration(
+            Variable(Symbol('b'),
+                type=IntBaseType(String('intc')),
+                value=Integer(3)
+                )
+            )
+
+        assert res21[2] == Declaration(
+            Variable(Symbol('mod'),
+                type=IntBaseType(String('intc')),
+                value=Integer(1000000007)
+                )
+            )
+
+        assert res21[3] == Declaration(
+            Variable(Symbol('c'),
+                type=IntBaseType(String('intc')),
+                value=Mod(
+                    Mul(
+                        Add(
+                            Symbol('a'),
+                            Mul(
+                                Integer(-1),
+                                Symbol('b')
+                                )
+                            ),
+                        Add(
+                            Symbol('a'),
+                            Symbol('b')
+                            )
+                        ),
+                    Symbol('mod')
+                    )
+                )
+            )
+
+        assert res22[0] == Declaration(
+            Variable(Symbol('a'),
+                type=Type(String('bool')),
+                value=false
+                )
+            )
+
+        assert res22[1] == Declaration(
+            Variable(Symbol('b'),
+                type=Type(String('bool')),
+                value=true
+                )
+            )
+
+        assert res23[0] == Declaration(
+            Variable(Symbol('a'),
+                type=Type(String('bool')),
+                value=true
+                )
+            )
+
+        assert res23[1] == Declaration(
+            Variable(Symbol('b'),
+                type=Type(String('bool')),
+                value=true
+                )
+            )
+
+        assert res23[2] == Declaration(
+            Variable(Symbol('c'),
+                type=Type(String('bool')),
+                value=false
+                )
+            )
+
+        assert res23[3] == Declaration(
+            Variable(Symbol('d'),
+                type=Type(String('bool')),
+                value=false
+                )
+            )
+
+        assert res24[0] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(1)
+                )
+            )
+
+        assert res24[1] == Declaration(
+            Variable(Symbol('b'),
+                type=IntBaseType(String('intc')),
+                value=Integer(2)
+                )
+            )
+
+        assert res24[2] == Declaration(
+            Variable(Symbol('c1'),
+                type=Type(String('bool')),
+                value=Equality(
+                    Symbol('a'),
+                    Integer(1)
+                    )
+                )
+            )
+
+        assert res24[3] == Declaration(
+            Variable(Symbol('c2'),
+                type=Type(String('bool')),
+                value=Equality(
+                    Symbol('b'),
+                    Integer(2)
+                    )
+                )
+            )
+
+        assert res24[4] == Declaration(
+            Variable(Symbol('c3'),
+                type=Type(String('bool')),
+                value=Unequality(
+                    Integer(1),
+                    Symbol('a')
+                    )
+                )
+            )
+
+        assert res24[5] == Declaration(
+            Variable(Symbol('c4'),
+                type=Type(String('bool')),
+                value=Unequality(
+                    Integer(1),
+                    Symbol('b')
+                    )
+                )
+            )
+
+        assert res24[6] == Declaration(
+            Variable(Symbol('c5'),
+                type=Type(String('bool')),
+                value=StrictLessThan(Symbol('a'),
+                    Integer(0)
+                    )
+                )
+            )
+
+        assert res24[7] == Declaration(
+            Variable(Symbol('c6'),
+                type=Type(String('bool')),
+                value=LessThan(
+                    Symbol('b'),
+                    Integer(10)
+                    )
+                )
+            )
+
+        assert res24[8] == Declaration(
+            Variable(Symbol('c7'),
+                type=Type(String('bool')),
+                value=StrictGreaterThan(
+                    Symbol('a'),
+                    Integer(0)
+                    )
+                )
+            )
+
+        assert res24[9] == Declaration(
+            Variable(Symbol('c8'),
+                type=Type(String('bool')),
+                value=GreaterThan(
+                    Symbol('b'),
+                    Integer(11)
+                    )
+                )
+            )
+
+        assert res25[0] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(3)
+                )
+            )
+
+        assert res25[1] == Declaration(
+            Variable(Symbol('b'),
+                type=IntBaseType(String('intc')),
+                value=Integer(4)
+                )
+            )
+
+        assert res25[2] == Declaration(Variable(Symbol('c1'),
+            type=Type(String('bool')),
+            value=Equality(
+                Symbol('a'),
+                Symbol('b')
+                )
+            )
+        )
+
+        assert res25[3] == Declaration(
+            Variable(Symbol('c2'),
+                type=Type(String('bool')),
+                value=Unequality(
+                    Symbol('a'),
+                    Symbol('b')
+                    )
+                )
+            )
+
+        assert res25[4] == Declaration(
+            Variable(Symbol('c3'),
+                type=Type(String('bool')),
+                value=StrictLessThan(
+                    Symbol('a'),
+                    Symbol('b')
+                    )
+                )
+            )
+
+        assert res25[5] == Declaration(
+            Variable(Symbol('c4'),
+                type=Type(String('bool')),
+                value=LessThan(
+                    Symbol('a'),
+                    Symbol('b')
+                    )
+                )
+            )
+
+        assert res25[6] == Declaration(
+            Variable(Symbol('c5'),
+                type=Type(String('bool')),
+                value=StrictGreaterThan(
+                    Symbol('a'),
+                    Symbol('b')
+                    )
+                )
+            )
+
+        assert res25[7] == Declaration(
+            Variable(Symbol('c6'),
+                type=Type(String('bool')),
+                value=GreaterThan(
+                    Symbol('a'),
+                    Symbol('b')
+                    )
+                )
+            )
+
+        assert res26[0] == Declaration(
+            Variable(Symbol('a'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('1.25', precision=53)
+                )
+            )
+
+        assert res26[1] == Declaration(
+            Variable(Symbol('b'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('2.5', precision=53)
+                )
+            )
+
+        assert res26[2] == Declaration(
+            Variable(Symbol('c1'),
+                type=Type(String('bool')),
+                value=Equality(
+                    Symbol('a'),
+                    Float('1.25', precision=53)
+                    )
+                )
+            )
+
+        assert res26[3] == Declaration(
+            Variable(Symbol('c2'),
+                type=Type(String('bool')),
+                value=Equality(
+                    Symbol('b'),
+                    Float('2.54', precision=53)
+                    )
+                )
+            )
+
+        assert res26[4] == Declaration(
+            Variable(Symbol('c3'),
+                type=Type(String('bool')),
+                value=Unequality(
+                    Float('1.2', precision=53),
+                    Symbol('a')
+                    )
+                )
+            )
+
+        assert res26[5] == Declaration(
+            Variable(Symbol('c4'),
+                type=Type(String('bool')),
+                value=Unequality(
+                    Float('1.5', precision=53),
+                    Symbol('b')
+                    )
+                )
+            )
+
+        assert res27[0] == Declaration(
+            Variable(Symbol('a'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('1.25', precision=53)
+                )
+            )
+
+        assert res27[1] == Declaration(
+            Variable(Symbol('b'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('2.5', precision=53)
+                )
+            )
+
+        assert res27[2] == Declaration(
+            Variable(Symbol('c1'),
+                type=Type(String('bool')),
+                value=Equality(
+                    Symbol('a'),
+                    Symbol('b')
+                    )
+                )
+            )
+
+        assert res27[3] == Declaration(
+            Variable(Symbol('c2'),
+                type=Type(String('bool')),
+                value=Unequality(
+                    Symbol('a'),
+                    Symbol('b')
+                    )
+                )
+            )
+
+        assert res27[4] == Declaration(
+            Variable(Symbol('c3'),
+                type=Type(String('bool')),
+                value=StrictLessThan(
+                    Symbol('a'),
+                    Symbol('b')
+                    )
+                )
+            )
+
+        assert res27[5] == Declaration(
+            Variable(Symbol('c4'),
+                type=Type(String('bool')),
+                value=LessThan(
+                    Symbol('a'),
+                    Symbol('b')
+                    )
+                )
+            )
+
+        assert res27[6] == Declaration(
+            Variable(Symbol('c5'),
+                type=Type(String('bool')),
+                value=StrictGreaterThan(
+                    Symbol('a'),
+                    Symbol('b')
+                    )
+                )
+            )
+
+        assert res27[7] == Declaration(
+            Variable(Symbol('c6'),
+                type=Type(String('bool')),
+                value=GreaterThan(
+                    Symbol('a'),
+                    Symbol('b')
+                    )
+                )
+            )
+
+        assert res28[0] == Declaration(
+            Variable(Symbol('c1'),
+                type=Type(String('bool')),
+                value=true
+                )
+            )
+
+        assert res28[1] == Declaration(
+            Variable(Symbol('c2'),
+                type=Type(String('bool')),
+                value=false
+                )
+            )
+
+        assert res28[2] == Declaration(
+            Variable(Symbol('c3'),
+                type=Type(String('bool')),
+                value=true
+                )
+            )
+
+        assert res28[3] == Declaration(
+            Variable(Symbol('c4'),
+                type=Type(String('bool')),
+                value=false
+                )
+            )
+
+        assert res28[4] == Declaration(
+            Variable(Symbol('c5'),
+                type=Type(String('bool')),
+                value=true
+                )
+            )
+
+        assert res28[5] == Declaration(
+            Variable(Symbol('c6'),
+                type=Type(String('bool')),
+                value=false
+                )
+            )
+
+        assert res29[0] == Declaration(
+            Variable(Symbol('c1'),
+                type=Type(String('bool')),
+                value=true
+                )
+            )
+
+        assert res29[1] == Declaration(
+            Variable(Symbol('c2'),
+                type=Type(String('bool')),
+                value=false
+                )
+            )
+
+        assert res29[2] == Declaration(
+            Variable(Symbol('c3'),
+                type=Type(String('bool')),
+                value=false
+                )
+            )
+
+        assert res29[3] == Declaration(
+            Variable(Symbol('c4'),
+                type=Type(String('bool')),
+                value=true
+                )
+            )
+
+        assert res29[4] == Declaration(
+            Variable(Symbol('c5'),
+                type=Type(String('bool')),
+                value=true
+                )
+            )
+
+        assert res29[5] == Declaration(
+            Variable(Symbol('c6'),
+                type=Type(String('bool')),
+                value=false
+                )
+            )
+
+        assert res30[0] == Declaration(
+            Variable(Symbol('a'),
+                type=Type(String('bool')),
+                value=false
+                )
+            )
+
+        assert res30[1] == Declaration(
+            Variable(Symbol('c1'),
+                type=Type(String('bool')),
+                value=Symbol('a')
+                )
+            )
+
+        assert res30[2] == Declaration(
+            Variable(Symbol('c2'),
+                type=Type(String('bool')),
+                value=false
+                )
+            )
+
+        assert res30[3] == Declaration(
+            Variable(Symbol('c3'),
+                type=Type(String('bool')),
+                value=true
+                )
+            )
+
+        assert res30[4] == Declaration(
+            Variable(Symbol('c4'),
+                type=Type(String('bool')),
+                value=Symbol('a')
+                )
+            )
+
+        assert res31[0] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(1)
+                )
+            )
+
+        assert res31[1] == Declaration(
+            Variable(Symbol('c1'),
+                type=Type(String('bool')),
+                value=Symbol('a')
+                )
+            )
+
+        assert res31[2] == Declaration(
+            Variable(Symbol('c2'),
+                type=Type(String('bool')),
+                value=false
+                )
+            )
+
+        assert res31[3] == Declaration(
+            Variable(Symbol('c3'),
+                type=Type(String('bool')),
+                value=true
+                )
+            )
+
+        assert res31[4] == Declaration(
+            Variable(Symbol('c4'),
+                type=Type(String('bool')),
+                value=Symbol('a')
+                )
+            )
+
+        assert res32[0] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(1)
+                )
+            )
+
+        assert res32[1] == Declaration(
+            Variable(Symbol('b'),
+                type=IntBaseType(String('intc')),
+                value=Integer(0)
+                )
+            )
+
+        assert res32[2] == Declaration(
+            Variable(Symbol('c'),
+                type=Type(String('bool')),
+                value=false
+                )
+            )
+
+        assert res32[3] == Declaration(
+            Variable(Symbol('d'),
+                type=Type(String('bool')),
+                value=true
+                )
+            )
+
+        assert res32[4] == Declaration(
+            Variable(Symbol('c1'),
+                type=Type(String('bool')),
+                value=And(
+                    Symbol('a'),
+                    Symbol('b')
+                    )
+                )
+            )
+
+        assert res32[5] == Declaration(
+            Variable(Symbol('c2'),
+                type=Type(String('bool')),
+                value=And(
+                    Symbol('a'),
+                    Symbol('c')
+                    )
+                )
+            )
+
+        assert res32[6] == Declaration(
+            Variable(Symbol('c3'),
+                type=Type(String('bool')),
+                value=And(
+                    Symbol('c'),
+                    Symbol('d')
+                    )
+                )
+            )
+
+        assert res32[7] == Declaration(
+            Variable(Symbol('c4'),
+                type=Type(String('bool')),
+                value=Or(
+                    Symbol('a'),
+                    Symbol('b')
+                    )
+                )
+            )
+
+        assert res32[8] == Declaration(
+            Variable(Symbol('c5'),
+                type=Type(String('bool')),
+                value=Or(
+                    Symbol('a'),
+                    Symbol('c')
+                    )
+                )
+            )
+
+        assert res32[9] == Declaration(
+            Variable(Symbol('c6'),
+                type=Type(String('bool')),
+                value=Or(
+                    Symbol('c'),
+                    Symbol('d')
+                    )
+                )
+            )
+
+        raises(NotImplementedError, lambda: SymPyExpression(c_src_raise1, 'c'))
+        raises(NotImplementedError, lambda: SymPyExpression(c_src_raise2, 'c'))
+
+
+    def test_paren_expr():
+        c_src1 = (
+            'int a = (1);'
+            'int b = (1 + 2 * 3);'
+        )
+
+        c_src2 = (
+            'int a = 1, b = 2, c = 3;'
+            'int d = (a);'
+            'int e = (a + 1);'
+            'int f = (a + b * c - d / e);'
+        )
+
+        res1 = SymPyExpression(c_src1, 'c').return_expr()
+        res2 = SymPyExpression(c_src2, 'c').return_expr()
+
+        assert res1[0] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(1)
+                )
+            )
+
+        assert res1[1] == Declaration(
+            Variable(Symbol('b'),
+                type=IntBaseType(String('intc')),
+                value=Integer(7)
+                )
+            )
+
+        assert res2[0] == Declaration(
+            Variable(Symbol('a'),
+                type=IntBaseType(String('intc')),
+                value=Integer(1)
+                )
+            )
+
+        assert res2[1] == Declaration(
+            Variable(Symbol('b'),
+                type=IntBaseType(String('intc')),
+                value=Integer(2)
+                )
+            )
+
+        assert res2[2] == Declaration(
+            Variable(Symbol('c'),
+                type=IntBaseType(String('intc')),
+                value=Integer(3)
+                )
+            )
+
+        assert res2[3] == Declaration(
+            Variable(Symbol('d'),
+                type=IntBaseType(String('intc')),
+                value=Symbol('a')
+                )
+            )
+
+        assert res2[4] == Declaration(
+            Variable(Symbol('e'),
+                type=IntBaseType(String('intc')),
+                value=Add(
+                    Symbol('a'),
+                    Integer(1)
+                    )
+                )
+            )
+
+        assert res2[5] == Declaration(
+            Variable(Symbol('f'),
+                type=IntBaseType(String('intc')),
+                value=Add(
+                    Symbol('a'),
+                    Mul(
+                        Symbol('b'),
+                        Symbol('c')
+                        ),
+                    Mul(
+                        Integer(-1),
+                        Symbol('d'),
+                        Pow(
+                            Symbol('e'),
+                            Integer(-1)
+                            )
+                        )
+                    )
+                )
+            )
+
+
+    def test_unary_operators():
+        c_src1 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a = 10;' + '\n' +
+                'int b = 20;' + '\n' +
+                '++a;' + '\n' +
+                '--b;' + '\n' +
+                'a++;' + '\n' +
+                'b--;' + '\n' +
+            '}'
+        )
+
+        c_src2 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a = 10;' + '\n' +
+                'int b = -100;' + '\n' +
+                'int c = +19;' + '\n' +
+                'int d = ++a;' + '\n' +
+                'int e = --b;' + '\n' +
+                'int f = a++;' + '\n' +
+                'int g = b--;' + '\n' +
+                'bool h = !false;' + '\n' +
+                'bool i = !d;' + '\n' +
+                'bool j = !0;' + '\n' +
+                'bool k = !10.0;' + '\n' +
+            '}'
+        )
+
+        c_src_raise1 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a = 10;' + '\n' +
+                'int b = ~a;' + '\n' +
+            '}'
+        )
+
+        c_src_raise2 = (
+            'void func()'+
+            '{' + '\n' +
+                'int a = 10;' + '\n' +
+                'int b = *&a;' + '\n' +
+            '}'
+        )
+
+        res1 = SymPyExpression(c_src1, 'c').return_expr()
+        res2 = SymPyExpression(c_src2, 'c').return_expr()
+
+        assert res1[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(10)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('b'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(20)
+                        )
+                    ),
+                PreIncrement(Symbol('a')),
+                PreDecrement(Symbol('b')),
+                PostIncrement(Symbol('a')),
+                PostDecrement(Symbol('b'))
+                )
+            )
+
+        assert res2[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('a'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(10)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('b'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(-100)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('c'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(19)
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('d'),
+                        type=IntBaseType(String('intc')),
+                        value=PreIncrement(Symbol('a'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('e'),
+                        type=IntBaseType(String('intc')),
+                        value=PreDecrement(Symbol('b'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('f'),
+                        type=IntBaseType(String('intc')),
+                        value=PostIncrement(Symbol('a'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('g'),
+                        type=IntBaseType(String('intc')),
+                        value=PostDecrement(Symbol('b'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('h'),
+                        type=Type(String('bool')),
+                        value=true
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('i'),
+                        type=Type(String('bool')),
+                        value=Not(Symbol('d'))
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('j'),
+                        type=Type(String('bool')),
+                        value=true
+                        )
+                    ),
+                Declaration(
+                    Variable(Symbol('k'),
+                        type=Type(String('bool')),
+                        value=false
+                        )
+                    )
+                )
+            )
+
+        raises(NotImplementedError, lambda: SymPyExpression(c_src_raise1, 'c'))
+        raises(NotImplementedError, lambda: SymPyExpression(c_src_raise2, 'c'))
+
+
+    def test_compound_assignment_operator():
+        c_src = (
+            'void func()'+
+            '{' + '\n' +
+                'int a = 100;' + '\n' +
+                'a += 10;' + '\n' +
+                'a -= 10;' + '\n' +
+                'a *= 10;' + '\n' +
+                'a /= 10;' + '\n' +
+                'a %= 10;' + '\n' +
+            '}'
+        )
+
+        res = SymPyExpression(c_src, 'c').return_expr()
+
+        assert res[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(
+                        Symbol('a'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(100)
+                        )
+                    ),
+                AddAugmentedAssignment(
+                    Variable(Symbol('a')),
+                    Integer(10)
+                    ),
+                SubAugmentedAssignment(
+                    Variable(Symbol('a')),
+                    Integer(10)
+                    ),
+                MulAugmentedAssignment(
+                    Variable(Symbol('a')),
+                    Integer(10)
+                    ),
+                DivAugmentedAssignment(
+                    Variable(Symbol('a')),
+                    Integer(10)
+                    ),
+                ModAugmentedAssignment(
+                    Variable(Symbol('a')),
+                    Integer(10)
+                    )
+                )
+            )
+
+    @XFAIL # this is expected to fail because of a bug in the C parser.
+    def test_while_stmt():
+        c_src1 = (
+            'void func()'+
+            '{' + '\n' +
+                'int i = 0;' + '\n' +
+                'while(i < 10)' + '\n' +
+                '{' + '\n' +
+                    'i++;' + '\n' +
+                '}'
+            '}'
+        )
+
+        c_src2 = (
+            'void func()'+
+            '{' + '\n' +
+                'int i = 0;' + '\n' +
+                'while(i < 10)' + '\n' +
+                    'i++;' + '\n' +
+            '}'
+        )
+
+        c_src3 = (
+            'void func()'+
+            '{' + '\n' +
+                'int i = 10;' + '\n' +
+                'int cnt = 0;' + '\n' +
+                'while(i > 0)' + '\n' +
+                '{' + '\n' +
+                    'i--;' + '\n' +
+                    'cnt++;' + '\n' +
+                '}' + '\n' +
+            '}'
+        )
+
+        c_src4 = (
+            'int digit_sum(int n)'+
+            '{' + '\n' +
+                'int sum = 0;' + '\n' +
+                'while(n > 0)' + '\n' +
+                '{' + '\n' +
+                    'sum += (n % 10);' + '\n' +
+                    'n /= 10;' + '\n' +
+                '}' + '\n' +
+                'return sum;' + '\n' +
+            '}'
+        )
+
+        c_src5 = (
+            'void func()'+
+            '{' + '\n' +
+                'while(1);' + '\n' +
+            '}'
+        )
+
+        res1 = SymPyExpression(c_src1, 'c').return_expr()
+        res2 = SymPyExpression(c_src2, 'c').return_expr()
+        res3 = SymPyExpression(c_src3, 'c').return_expr()
+        res4 = SymPyExpression(c_src4, 'c').return_expr()
+        res5 = SymPyExpression(c_src5, 'c').return_expr()
+
+        assert res1[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(Symbol('i'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(0)
+                        )
+                    ),
+                While(
+                    StrictLessThan(
+                        Symbol('i'),
+                        Integer(10)
+                        ),
+                    body=CodeBlock(
+                        PostIncrement(
+                            Symbol('i')
+                            )
+                        )
+                    )
+                )
+            )
+
+        assert res2[0] == res1[0]
+
+        assert res3[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                Declaration(
+                    Variable(
+                        Symbol('i'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(10)
+                        )
+                    ),
+                Declaration(
+                    Variable(
+                        Symbol('cnt'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(0)
+                        )
+                    ),
+                While(
+                    StrictGreaterThan(
+                        Symbol('i'),
+                        Integer(0)
+                        ),
+                    body=CodeBlock(
+                        PostDecrement(
+                            Symbol('i')
+                            ),
+                        PostIncrement(
+                            Symbol('cnt')
+                            )
+                        )
+                    )
+                )
+            )
+
+        assert res4[0] == FunctionDefinition(
+            IntBaseType(String('intc')),
+            name=String('digit_sum'),
+            parameters=(
+                Variable(
+                    Symbol('n'),
+                    type=IntBaseType(String('intc'))
+                    ),
+                ),
+            body=CodeBlock(
+                Declaration(
+                    Variable(
+                        Symbol('sum'),
+                        type=IntBaseType(String('intc')),
+                        value=Integer(0)
+                        )
+                    ),
+                While(
+                    StrictGreaterThan(
+                        Symbol('n'),
+                        Integer(0)
+                        ),
+                    body=CodeBlock(
+                        AddAugmentedAssignment(
+                            Variable(
+                                Symbol('sum')
+                                ),
+                            Mod(
+                                Symbol('n'),
+                                Integer(10)
+                                )
+                            ),
+                        DivAugmentedAssignment(
+                            Variable(
+                                Symbol('n')
+                                ),
+                            Integer(10)
+                            )
+                        )
+                    ),
+                Return('sum')
+                )
+            )
+
+        assert res5[0] == FunctionDefinition(
+            NoneToken(),
+            name=String('func'),
+            parameters=(),
+            body=CodeBlock(
+                While(
+                    Integer(1),
+                    body=CodeBlock(
+                        NoneToken()
+                        )
+                    )
+                )
+            )
+
+
+else:
+    def test_raise():
+        from sympy.parsing.c.c_parser import CCodeConverter
+        raises(ImportError, lambda: CCodeConverter())
+        raises(ImportError, lambda: SymPyExpression(' ', mode = 'c'))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_custom_latex.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_custom_latex.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5eff1c9ec79528c7f9e3a06cf9e2f84c86091ee
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_custom_latex.py
@@ -0,0 +1,69 @@
+import os
+import tempfile
+from pathlib import Path
+
+import sympy
+from sympy.testing.pytest import raises
+from sympy.parsing.latex.lark import LarkLaTeXParser, TransformToSymPyExpr, parse_latex_lark
+from sympy.external import import_module
+
+lark = import_module("lark")
+
+# disable tests if lark is not present
+disabled = lark is None
+
+grammar_file = os.path.join(os.path.dirname(__file__), "../latex/lark/grammar/latex.lark")
+
+modification1 = """
+%override DIV_SYMBOL: DIV
+%override MUL_SYMBOL: MUL | CMD_TIMES
+"""
+
+modification2 = r"""
+%override number: /\d+(,\d*)?/
+"""
+
+def init_custom_parser(modification, transformer=None):
+    latex_grammar = Path(grammar_file).read_text(encoding="utf-8")
+    latex_grammar += modification
+
+    with tempfile.NamedTemporaryFile() as f:
+        f.write(bytes(latex_grammar, encoding="utf8"))
+        f.flush()
+
+        parser = LarkLaTeXParser(grammar_file=f.name, transformer=transformer)
+
+    return parser
+
+def test_custom1():
+    # Removes the parser's ability to understand \cdot and \div.
+
+    parser = init_custom_parser(modification1)
+
+    with raises(lark.exceptions.UnexpectedCharacters):
+        parser.doparse(r"a \cdot b")
+        parser.doparse(r"x \div y")
+
+class CustomTransformer(TransformToSymPyExpr):
+    def number(self, tokens):
+        if "," in tokens[0]:
+            # The Float constructor expects a dot as the decimal separator
+            return sympy.core.numbers.Float(tokens[0].replace(",", "."))
+        else:
+            return sympy.core.numbers.Integer(tokens[0])
+
+def test_custom2():
+    # Makes the parser parse commas as the decimal separator instead of dots
+
+    parser = init_custom_parser(modification2, CustomTransformer)
+
+    with raises(lark.exceptions.UnexpectedCharacters):
+        # Asserting that the default parser cannot parse numbers which have commas as
+        # the decimal separator
+        parse_latex_lark("100,1")
+        parse_latex_lark("0,009")
+
+    parser.doparse("100,1")
+    parser.doparse("0,009")
+    parser.doparse("2,71828")
+    parser.doparse("3,14159")
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_fortran_parser.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_fortran_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..9bcd54533ef231dd0a116910453dff0e993bc727
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_fortran_parser.py
@@ -0,0 +1,406 @@
+from sympy.testing.pytest import raises
+from sympy.parsing.sym_expr import SymPyExpression
+from sympy.external import import_module
+
+lfortran = import_module('lfortran')
+
+if lfortran:
+    from sympy.codegen.ast import (Variable, IntBaseType, FloatBaseType, String,
+                                   Return, FunctionDefinition, Assignment,
+                                   Declaration, CodeBlock)
+    from sympy.core import Integer, Float, Add
+    from sympy.core.symbol import Symbol
+
+
+    expr1 = SymPyExpression()
+    expr2 = SymPyExpression()
+    src = """\
+    integer :: a, b, c, d
+    real :: p, q, r, s
+    """
+
+
+    def test_sym_expr():
+        src1 = (
+            src +
+            """\
+            d = a + b -c
+            """
+        )
+        expr3 = SymPyExpression(src,'f')
+        expr4 = SymPyExpression(src1,'f')
+        ls1 = expr3.return_expr()
+        ls2 = expr4.return_expr()
+        for i in range(0, 7):
+            assert isinstance(ls1[i], Declaration)
+            assert isinstance(ls2[i], Declaration)
+        assert isinstance(ls2[8], Assignment)
+        assert ls1[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type = IntBaseType(String('integer')),
+                value = Integer(0)
+            )
+        )
+        assert ls1[1] == Declaration(
+            Variable(
+                Symbol('b'),
+                type = IntBaseType(String('integer')),
+                value = Integer(0)
+            )
+        )
+        assert ls1[2] == Declaration(
+            Variable(
+                Symbol('c'),
+                type = IntBaseType(String('integer')),
+                value = Integer(0)
+            )
+        )
+        assert ls1[3] == Declaration(
+            Variable(
+                Symbol('d'),
+                type = IntBaseType(String('integer')),
+                value = Integer(0)
+            )
+        )
+        assert ls1[4] == Declaration(
+            Variable(
+                Symbol('p'),
+                type = FloatBaseType(String('real')),
+                value = Float(0.0)
+            )
+        )
+        assert ls1[5] == Declaration(
+            Variable(
+                Symbol('q'),
+                type = FloatBaseType(String('real')),
+                value = Float(0.0)
+            )
+        )
+        assert ls1[6] == Declaration(
+            Variable(
+                Symbol('r'),
+                type = FloatBaseType(String('real')),
+                value = Float(0.0)
+            )
+        )
+        assert ls1[7] == Declaration(
+            Variable(
+                Symbol('s'),
+                type = FloatBaseType(String('real')),
+                value = Float(0.0)
+            )
+        )
+        assert ls2[8] == Assignment(
+            Variable(Symbol('d')),
+            Symbol('a') + Symbol('b') - Symbol('c')
+        )
+
+    def test_assignment():
+        src1 = (
+            src +
+            """\
+            a = b
+            c = d
+            p = q
+            r = s
+            """
+        )
+        expr1.convert_to_expr(src1, 'f')
+        ls1 = expr1.return_expr()
+        for iter in range(0, 12):
+            if iter < 8:
+                assert isinstance(ls1[iter], Declaration)
+            else:
+                assert isinstance(ls1[iter], Assignment)
+        assert ls1[8] == Assignment(
+            Variable(Symbol('a')),
+            Variable(Symbol('b'))
+        )
+        assert ls1[9] == Assignment(
+            Variable(Symbol('c')),
+            Variable(Symbol('d'))
+        )
+        assert ls1[10] == Assignment(
+            Variable(Symbol('p')),
+            Variable(Symbol('q'))
+        )
+        assert ls1[11] == Assignment(
+            Variable(Symbol('r')),
+            Variable(Symbol('s'))
+        )
+
+
+    def test_binop_add():
+        src1 = (
+            src +
+            """\
+            c = a + b
+            d = a + c
+            s = p + q + r
+            """
+        )
+        expr1.convert_to_expr(src1, 'f')
+        ls1 = expr1.return_expr()
+        for iter in range(8, 11):
+            assert isinstance(ls1[iter], Assignment)
+        assert ls1[8] == Assignment(
+            Variable(Symbol('c')),
+            Symbol('a') + Symbol('b')
+        )
+        assert ls1[9] == Assignment(
+            Variable(Symbol('d')),
+            Symbol('a') + Symbol('c')
+        )
+        assert ls1[10] == Assignment(
+            Variable(Symbol('s')),
+            Symbol('p') + Symbol('q') + Symbol('r')
+        )
+
+
+    def test_binop_sub():
+        src1 = (
+            src +
+            """\
+            c = a - b
+            d = a - c
+            s = p - q - r
+            """
+        )
+        expr1.convert_to_expr(src1, 'f')
+        ls1 = expr1.return_expr()
+        for iter in range(8, 11):
+            assert isinstance(ls1[iter], Assignment)
+        assert ls1[8] == Assignment(
+            Variable(Symbol('c')),
+            Symbol('a') - Symbol('b')
+        )
+        assert ls1[9] == Assignment(
+            Variable(Symbol('d')),
+            Symbol('a') - Symbol('c')
+        )
+        assert ls1[10] == Assignment(
+            Variable(Symbol('s')),
+            Symbol('p') - Symbol('q') - Symbol('r')
+        )
+
+
+    def test_binop_mul():
+        src1 = (
+            src +
+            """\
+            c = a * b
+            d = a * c
+            s = p * q * r
+            """
+        )
+        expr1.convert_to_expr(src1, 'f')
+        ls1 = expr1.return_expr()
+        for iter in range(8, 11):
+            assert isinstance(ls1[iter], Assignment)
+        assert ls1[8] == Assignment(
+            Variable(Symbol('c')),
+            Symbol('a') * Symbol('b')
+        )
+        assert ls1[9] == Assignment(
+            Variable(Symbol('d')),
+            Symbol('a') * Symbol('c')
+        )
+        assert ls1[10] == Assignment(
+            Variable(Symbol('s')),
+            Symbol('p') * Symbol('q') * Symbol('r')
+        )
+
+
+    def test_binop_div():
+        src1 = (
+            src +
+            """\
+            c = a / b
+            d = a / c
+            s = p / q
+            r = q / p
+            """
+        )
+        expr1.convert_to_expr(src1, 'f')
+        ls1 = expr1.return_expr()
+        for iter in range(8, 12):
+            assert isinstance(ls1[iter], Assignment)
+        assert ls1[8] == Assignment(
+            Variable(Symbol('c')),
+            Symbol('a') / Symbol('b')
+        )
+        assert ls1[9] == Assignment(
+            Variable(Symbol('d')),
+            Symbol('a') / Symbol('c')
+        )
+        assert ls1[10] == Assignment(
+            Variable(Symbol('s')),
+            Symbol('p') / Symbol('q')
+        )
+        assert ls1[11] == Assignment(
+            Variable(Symbol('r')),
+            Symbol('q') / Symbol('p')
+        )
+
+    def test_mul_binop():
+        src1 = (
+            src +
+            """\
+            d = a + b - c
+            c = a * b + d
+            s = p * q / r
+            r = p * s + q / p
+            """
+        )
+        expr1.convert_to_expr(src1, 'f')
+        ls1 = expr1.return_expr()
+        for iter in range(8, 12):
+            assert isinstance(ls1[iter], Assignment)
+        assert ls1[8] == Assignment(
+            Variable(Symbol('d')),
+            Symbol('a') + Symbol('b') - Symbol('c')
+        )
+        assert ls1[9] == Assignment(
+            Variable(Symbol('c')),
+            Symbol('a') * Symbol('b') + Symbol('d')
+        )
+        assert ls1[10] == Assignment(
+            Variable(Symbol('s')),
+            Symbol('p') * Symbol('q') / Symbol('r')
+        )
+        assert ls1[11] == Assignment(
+            Variable(Symbol('r')),
+            Symbol('p') * Symbol('s') + Symbol('q') / Symbol('p')
+        )
+
+
+    def test_function():
+        src1 = """\
+        integer function f(a,b)
+        integer :: x, y
+        f = x + y
+        end function
+        """
+        expr1.convert_to_expr(src1, 'f')
+        for iter in expr1.return_expr():
+            assert isinstance(iter, FunctionDefinition)
+            assert iter == FunctionDefinition(
+                IntBaseType(String('integer')),
+                name=String('f'),
+                parameters=(
+                    Variable(Symbol('a')),
+                    Variable(Symbol('b'))
+                ),
+                body=CodeBlock(
+                    Declaration(
+                        Variable(
+                            Symbol('a'),
+                            type=IntBaseType(String('integer')),
+                            value=Integer(0)
+                        )
+                    ),
+                    Declaration(
+                        Variable(
+                            Symbol('b'),
+                            type=IntBaseType(String('integer')),
+                            value=Integer(0)
+                        )
+                    ),
+                    Declaration(
+                        Variable(
+                            Symbol('f'),
+                            type=IntBaseType(String('integer')),
+                            value=Integer(0)
+                        )
+                    ),
+                    Declaration(
+                        Variable(
+                            Symbol('x'),
+                            type=IntBaseType(String('integer')),
+                            value=Integer(0)
+                        )
+                    ),
+                    Declaration(
+                        Variable(
+                            Symbol('y'),
+                            type=IntBaseType(String('integer')),
+                            value=Integer(0)
+                        )
+                    ),
+                    Assignment(
+                        Variable(Symbol('f')),
+                        Add(Symbol('x'), Symbol('y'))
+                    ),
+                    Return(Variable(Symbol('f')))
+                )
+            )
+
+
+    def test_var():
+        expr1.convert_to_expr(src, 'f')
+        ls = expr1.return_expr()
+        for iter in expr1.return_expr():
+            assert isinstance(iter, Declaration)
+        assert ls[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type = IntBaseType(String('integer')),
+                value = Integer(0)
+            )
+        )
+        assert ls[1] == Declaration(
+            Variable(
+                Symbol('b'),
+                type = IntBaseType(String('integer')),
+                value = Integer(0)
+            )
+        )
+        assert ls[2] == Declaration(
+            Variable(
+                Symbol('c'),
+                type = IntBaseType(String('integer')),
+                value = Integer(0)
+            )
+        )
+        assert ls[3] == Declaration(
+            Variable(
+                Symbol('d'),
+                type = IntBaseType(String('integer')),
+                value = Integer(0)
+            )
+        )
+        assert ls[4] == Declaration(
+            Variable(
+                Symbol('p'),
+                type = FloatBaseType(String('real')),
+                value = Float(0.0)
+            )
+        )
+        assert ls[5] == Declaration(
+            Variable(
+                Symbol('q'),
+                type = FloatBaseType(String('real')),
+                value = Float(0.0)
+            )
+        )
+        assert ls[6] == Declaration(
+            Variable(
+                Symbol('r'),
+                type = FloatBaseType(String('real')),
+                value = Float(0.0)
+            )
+        )
+        assert ls[7] == Declaration(
+            Variable(
+                Symbol('s'),
+                type = FloatBaseType(String('real')),
+                value = Float(0.0)
+            )
+        )
+
+else:
+    def test_raise():
+        from sympy.parsing.fortran.fortran_parser import ASR2PyVisitor
+        raises(ImportError, lambda: ASR2PyVisitor())
+        raises(ImportError, lambda: SymPyExpression(' ', mode = 'f'))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_implicit_multiplication_application.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_implicit_multiplication_application.py
new file mode 100644
index 0000000000000000000000000000000000000000..56df361e77b0c0f94bdb53b03e0dc30a8a10899f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_implicit_multiplication_application.py
@@ -0,0 +1,195 @@
+import sympy
+from sympy.parsing.sympy_parser import (
+    parse_expr,
+    standard_transformations,
+    convert_xor,
+    implicit_multiplication_application,
+    implicit_multiplication,
+    implicit_application,
+    function_exponentiation,
+    split_symbols,
+    split_symbols_custom,
+    _token_splittable
+)
+from sympy.testing.pytest import raises
+
+
+def test_implicit_multiplication():
+    cases = {
+        '5x': '5*x',
+        'abc': 'a*b*c',
+        '3sin(x)': '3*sin(x)',
+        '(x+1)(x+2)': '(x+1)*(x+2)',
+        '(5 x**2)sin(x)': '(5*x**2)*sin(x)',
+        '2 sin(x) cos(x)': '2*sin(x)*cos(x)',
+        'pi x': 'pi*x',
+        'x pi': 'x*pi',
+        'E x': 'E*x',
+        'EulerGamma y': 'EulerGamma*y',
+        'E pi': 'E*pi',
+        'pi (x + 2)': 'pi*(x+2)',
+        '(x + 2) pi': '(x+2)*pi',
+        'pi sin(x)': 'pi*sin(x)',
+    }
+    transformations = standard_transformations + (convert_xor,)
+    transformations2 = transformations + (split_symbols,
+                                          implicit_multiplication)
+    for case in cases:
+        implicit = parse_expr(case, transformations=transformations2)
+        normal = parse_expr(cases[case], transformations=transformations)
+        assert(implicit == normal)
+
+    application = ['sin x', 'cos 2*x', 'sin cos x']
+    for case in application:
+        raises(SyntaxError,
+               lambda: parse_expr(case, transformations=transformations2))
+    raises(TypeError,
+           lambda: parse_expr('sin**2(x)', transformations=transformations2))
+
+
+def test_implicit_application():
+    cases = {
+        'factorial': 'factorial',
+        'sin x': 'sin(x)',
+        'tan y**3': 'tan(y**3)',
+        'cos 2*x': 'cos(2*x)',
+        '(cot)': 'cot',
+        'sin cos tan x': 'sin(cos(tan(x)))'
+    }
+    transformations = standard_transformations + (convert_xor,)
+    transformations2 = transformations + (implicit_application,)
+    for case in cases:
+        implicit = parse_expr(case, transformations=transformations2)
+        normal = parse_expr(cases[case], transformations=transformations)
+        assert(implicit == normal), (implicit, normal)
+
+    multiplication = ['x y', 'x sin x', '2x']
+    for case in multiplication:
+        raises(SyntaxError,
+               lambda: parse_expr(case, transformations=transformations2))
+    raises(TypeError,
+           lambda: parse_expr('sin**2(x)', transformations=transformations2))
+
+
+def test_function_exponentiation():
+    cases = {
+        'sin**2(x)': 'sin(x)**2',
+        'exp^y(z)': 'exp(z)^y',
+        'sin**2(E^(x))': 'sin(E^(x))**2'
+    }
+    transformations = standard_transformations + (convert_xor,)
+    transformations2 = transformations + (function_exponentiation,)
+    for case in cases:
+        implicit = parse_expr(case, transformations=transformations2)
+        normal = parse_expr(cases[case], transformations=transformations)
+        assert(implicit == normal)
+
+    other_implicit = ['x y', 'x sin x', '2x', 'sin x',
+                      'cos 2*x', 'sin cos x']
+    for case in other_implicit:
+        raises(SyntaxError,
+               lambda: parse_expr(case, transformations=transformations2))
+
+    assert parse_expr('x**2', local_dict={ 'x': sympy.Symbol('x') },
+                      transformations=transformations2) == parse_expr('x**2')
+
+
+def test_symbol_splitting():
+    # By default Greek letter names should not be split (lambda is a keyword
+    # so skip it)
+    transformations = standard_transformations + (split_symbols,)
+    greek_letters = ('alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta',
+                     'eta', 'theta', 'iota', 'kappa', 'mu', 'nu', 'xi',
+                     'omicron', 'pi', 'rho', 'sigma', 'tau', 'upsilon',
+                     'phi', 'chi', 'psi', 'omega')
+
+    for letter in greek_letters:
+        assert(parse_expr(letter, transformations=transformations) ==
+               parse_expr(letter))
+
+    # Make sure symbol splitting resolves names
+    transformations += (implicit_multiplication,)
+    local_dict = { 'e': sympy.E }
+    cases = {
+        'xe': 'E*x',
+        'Iy': 'I*y',
+        'ee': 'E*E',
+    }
+    for case, expected in cases.items():
+        assert(parse_expr(case, local_dict=local_dict,
+                          transformations=transformations) ==
+               parse_expr(expected))
+
+    # Make sure custom splitting works
+    def can_split(symbol):
+        if symbol not in ('unsplittable', 'names'):
+            return _token_splittable(symbol)
+        return False
+    transformations = standard_transformations
+    transformations += (split_symbols_custom(can_split),
+                        implicit_multiplication)
+
+    assert(parse_expr('unsplittable', transformations=transformations) ==
+           parse_expr('unsplittable'))
+    assert(parse_expr('names', transformations=transformations) ==
+           parse_expr('names'))
+    assert(parse_expr('xy', transformations=transformations) ==
+           parse_expr('x*y'))
+    for letter in greek_letters:
+        assert(parse_expr(letter, transformations=transformations) ==
+               parse_expr(letter))
+
+
+def test_all_implicit_steps():
+    cases = {
+        '2x': '2*x',  # implicit multiplication
+        'x y': 'x*y',
+        'xy': 'x*y',
+        'sin x': 'sin(x)',  # add parentheses
+        '2sin x': '2*sin(x)',
+        'x y z': 'x*y*z',
+        'sin(2 * 3x)': 'sin(2 * 3 * x)',
+        'sin(x) (1 + cos(x))': 'sin(x) * (1 + cos(x))',
+        '(x + 2) sin(x)': '(x + 2) * sin(x)',
+        '(x + 2) sin x': '(x + 2) * sin(x)',
+        'sin(sin x)': 'sin(sin(x))',
+        'sin x!': 'sin(factorial(x))',
+        'sin x!!': 'sin(factorial2(x))',
+        'factorial': 'factorial',  # don't apply a bare function
+        'x sin x': 'x * sin(x)',  # both application and multiplication
+        'xy sin x': 'x * y * sin(x)',
+        '(x+2)(x+3)': '(x + 2) * (x+3)',
+        'x**2 + 2xy + y**2': 'x**2 + 2 * x * y + y**2',  # split the xy
+        'pi': 'pi',  # don't mess with constants
+        'None': 'None',
+        'ln sin x': 'ln(sin(x))',  # multiple implicit function applications
+        'sin x**2': 'sin(x**2)',  # implicit application to an exponential
+        'alpha': 'Symbol("alpha")',  # don't split Greek letters/subscripts
+        'x_2': 'Symbol("x_2")',
+        'sin^2 x**2': 'sin(x**2)**2',  # function raised to a power
+        'sin**3(x)': 'sin(x)**3',
+        '(factorial)': 'factorial',
+        'tan 3x': 'tan(3*x)',
+        'sin^2(3*E^(x))': 'sin(3*E**(x))**2',
+        'sin**2(E^(3x))': 'sin(E**(3*x))**2',
+        'sin^2 (3x*E^(x))': 'sin(3*x*E^x)**2',
+        'pi sin x': 'pi*sin(x)',
+    }
+    transformations = standard_transformations + (convert_xor,)
+    transformations2 = transformations + (implicit_multiplication_application,)
+    for case in cases:
+        implicit = parse_expr(case, transformations=transformations2)
+        normal = parse_expr(cases[case], transformations=transformations)
+        assert(implicit == normal)
+
+
+def test_no_methods_implicit_multiplication():
+    # Issue 21020
+    u = sympy.Symbol('u')
+    transformations = standard_transformations + \
+                      (implicit_multiplication,)
+    expr = parse_expr('x.is_polynomial(x)', transformations=transformations)
+    assert expr == True
+    expr = parse_expr('(exp(x) / (1 + exp(2x))).subs(exp(x), u)',
+                      transformations=transformations)
+    assert expr == u/(u**2 + 1)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_latex.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_latex.py
new file mode 100644
index 0000000000000000000000000000000000000000..49a48966eacaa1cd7a242dcd0e7699c992bb1268
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_latex.py
@@ -0,0 +1,358 @@
+from sympy.testing.pytest import raises, XFAIL
+from sympy.external import import_module
+
+from sympy.concrete.products import Product
+from sympy.concrete.summations import Sum
+from sympy.core.add import Add
+from sympy.core.function import (Derivative, Function)
+from sympy.core.mul import Mul
+from sympy.core.numbers import (E, oo)
+from sympy.core.power import Pow
+from sympy.core.relational import (GreaterThan, LessThan, StrictGreaterThan, StrictLessThan, Unequality)
+from sympy.core.symbol import Symbol
+from sympy.functions.combinatorial.factorials import (binomial, factorial)
+from sympy.functions.elementary.complexes import (Abs, conjugate)
+from sympy.functions.elementary.exponential import (exp, log)
+from sympy.functions.elementary.integers import (ceiling, floor)
+from sympy.functions.elementary.miscellaneous import (root, sqrt)
+from sympy.functions.elementary.trigonometric import (asin, cos, csc, sec, sin, tan)
+from sympy.integrals.integrals import Integral
+from sympy.series.limits import Limit
+
+from sympy.core.relational import Eq, Ne, Lt, Le, Gt, Ge
+from sympy.physics.quantum.state import Bra, Ket
+from sympy.abc import x, y, z, a, b, c, t, k, n
+antlr4 = import_module("antlr4")
+
+# disable tests if antlr4-python3-runtime is not present
+disabled = antlr4 is None
+
+theta = Symbol('theta')
+f = Function('f')
+
+
+# shorthand definitions
+def _Add(a, b):
+    return Add(a, b, evaluate=False)
+
+
+def _Mul(a, b):
+    return Mul(a, b, evaluate=False)
+
+
+def _Pow(a, b):
+    return Pow(a, b, evaluate=False)
+
+
+def _Sqrt(a):
+    return sqrt(a, evaluate=False)
+
+
+def _Conjugate(a):
+    return conjugate(a, evaluate=False)
+
+
+def _Abs(a):
+    return Abs(a, evaluate=False)
+
+
+def _factorial(a):
+    return factorial(a, evaluate=False)
+
+
+def _exp(a):
+    return exp(a, evaluate=False)
+
+
+def _log(a, b):
+    return log(a, b, evaluate=False)
+
+
+def _binomial(n, k):
+    return binomial(n, k, evaluate=False)
+
+
+def test_import():
+    from sympy.parsing.latex._build_latex_antlr import (
+        build_parser,
+        check_antlr_version,
+        dir_latex_antlr
+    )
+    # XXX: It would be better to come up with a test for these...
+    del build_parser, check_antlr_version, dir_latex_antlr
+
+
+# These LaTeX strings should parse to the corresponding SymPy expression
+GOOD_PAIRS = [
+    (r"0", 0),
+    (r"1", 1),
+    (r"-3.14", -3.14),
+    (r"(-7.13)(1.5)", _Mul(-7.13, 1.5)),
+    (r"x", x),
+    (r"2x", 2*x),
+    (r"x^2", x**2),
+    (r"x^\frac{1}{2}", _Pow(x, _Pow(2, -1))),
+    (r"x^{3 + 1}", x**_Add(3, 1)),
+    (r"-c", -c),
+    (r"a \cdot b", a * b),
+    (r"a / b", a / b),
+    (r"a \div b", a / b),
+    (r"a + b", a + b),
+    (r"a + b - a", _Add(a+b, -a)),
+    (r"a^2 + b^2 = c^2", Eq(a**2 + b**2, c**2)),
+    (r"(x + y) z", _Mul(_Add(x, y), z)),
+    (r"a'b+ab'", _Add(_Mul(Symbol("a'"), b), _Mul(a, Symbol("b'")))),
+    (r"y''_1", Symbol("y_{1}''")),
+    (r"y_1''", Symbol("y_{1}''")),
+    (r"\left(x + y\right) z", _Mul(_Add(x, y), z)),
+    (r"\left( x + y\right ) z", _Mul(_Add(x, y), z)),
+    (r"\left(  x + y\right ) z", _Mul(_Add(x, y), z)),
+    (r"\left[x + y\right] z", _Mul(_Add(x, y), z)),
+    (r"\left\{x + y\right\} z", _Mul(_Add(x, y), z)),
+    (r"1+1", _Add(1, 1)),
+    (r"0+1", _Add(0, 1)),
+    (r"1*2", _Mul(1, 2)),
+    (r"0*1", _Mul(0, 1)),
+    (r"1 \times 2 ", _Mul(1, 2)),
+    (r"x = y", Eq(x, y)),
+    (r"x \neq y", Ne(x, y)),
+    (r"x < y", Lt(x, y)),
+    (r"x > y", Gt(x, y)),
+    (r"x \leq y", Le(x, y)),
+    (r"x \geq y", Ge(x, y)),
+    (r"x \le y", Le(x, y)),
+    (r"x \ge y", Ge(x, y)),
+    (r"\lfloor x \rfloor", floor(x)),
+    (r"\lceil x \rceil", ceiling(x)),
+    (r"\langle x |", Bra('x')),
+    (r"| x \rangle", Ket('x')),
+    (r"\sin \theta", sin(theta)),
+    (r"\sin(\theta)", sin(theta)),
+    (r"\sin^{-1} a", asin(a)),
+    (r"\sin a \cos b", _Mul(sin(a), cos(b))),
+    (r"\sin \cos \theta", sin(cos(theta))),
+    (r"\sin(\cos \theta)", sin(cos(theta))),
+    (r"\frac{a}{b}", a / b),
+    (r"\dfrac{a}{b}", a / b),
+    (r"\tfrac{a}{b}", a / b),
+    (r"\frac12", _Pow(2, -1)),
+    (r"\frac12y", _Mul(_Pow(2, -1), y)),
+    (r"\frac1234", _Mul(_Pow(2, -1), 34)),
+    (r"\frac2{3}", _Mul(2, _Pow(3, -1))),
+    (r"\frac{\sin{x}}2", _Mul(sin(x), _Pow(2, -1))),
+    (r"\frac{a + b}{c}", _Mul(a + b, _Pow(c, -1))),
+    (r"\frac{7}{3}", _Mul(7, _Pow(3, -1))),
+    (r"(\csc x)(\sec y)", csc(x)*sec(y)),
+    (r"\lim_{x \to 3} a", Limit(a, x, 3, dir='+-')),
+    (r"\lim_{x \rightarrow 3} a", Limit(a, x, 3, dir='+-')),
+    (r"\lim_{x \Rightarrow 3} a", Limit(a, x, 3, dir='+-')),
+    (r"\lim_{x \longrightarrow 3} a", Limit(a, x, 3, dir='+-')),
+    (r"\lim_{x \Longrightarrow 3} a", Limit(a, x, 3, dir='+-')),
+    (r"\lim_{x \to 3^{+}} a", Limit(a, x, 3, dir='+')),
+    (r"\lim_{x \to 3^{-}} a", Limit(a, x, 3, dir='-')),
+    (r"\lim_{x \to 3^+} a", Limit(a, x, 3, dir='+')),
+    (r"\lim_{x \to 3^-} a", Limit(a, x, 3, dir='-')),
+    (r"\infty", oo),
+    (r"\lim_{x \to \infty} \frac{1}{x}", Limit(_Pow(x, -1), x, oo)),
+    (r"\frac{d}{dx} x", Derivative(x, x)),
+    (r"\frac{d}{dt} x", Derivative(x, t)),
+    (r"f(x)", f(x)),
+    (r"f(x, y)", f(x, y)),
+    (r"f(x, y, z)", f(x, y, z)),
+    (r"f'_1(x)", Function("f_{1}'")(x)),
+    (r"f_{1}''(x+y)", Function("f_{1}''")(x+y)),
+    (r"\frac{d f(x)}{dx}", Derivative(f(x), x)),
+    (r"\frac{d\theta(x)}{dx}", Derivative(Function('theta')(x), x)),
+    (r"x \neq y", Unequality(x, y)),
+    (r"|x|", _Abs(x)),
+    (r"||x||", _Abs(Abs(x))),
+    (r"|x||y|", _Abs(x)*_Abs(y)),
+    (r"||x||y||", _Abs(_Abs(x)*_Abs(y))),
+    (r"\pi^{|xy|}", Symbol('pi')**_Abs(x*y)),
+    (r"\int x dx", Integral(x, x)),
+    (r"\int x d\theta", Integral(x, theta)),
+    (r"\int (x^2 - y)dx", Integral(x**2 - y, x)),
+    (r"\int x + a dx", Integral(_Add(x, a), x)),
+    (r"\int da", Integral(1, a)),
+    (r"\int_0^7 dx", Integral(1, (x, 0, 7))),
+    (r"\int\limits_{0}^{1} x dx", Integral(x, (x, 0, 1))),
+    (r"\int_a^b x dx", Integral(x, (x, a, b))),
+    (r"\int^b_a x dx", Integral(x, (x, a, b))),
+    (r"\int_{a}^b x dx", Integral(x, (x, a, b))),
+    (r"\int^{b}_a x dx", Integral(x, (x, a, b))),
+    (r"\int_{a}^{b} x dx", Integral(x, (x, a, b))),
+    (r"\int^{b}_{a} x dx", Integral(x, (x, a, b))),
+    (r"\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))),
+    (r"\int (x+a)", Integral(_Add(x, a), x)),
+    (r"\int a + b + c dx", Integral(_Add(_Add(a, b), c), x)),
+    (r"\int \frac{dz}{z}", Integral(Pow(z, -1), z)),
+    (r"\int \frac{3 dz}{z}", Integral(3*Pow(z, -1), z)),
+    (r"\int \frac{1}{x} dx", Integral(Pow(x, -1), x)),
+    (r"\int \frac{1}{a} + \frac{1}{b} dx",
+     Integral(_Add(_Pow(a, -1), Pow(b, -1)), x)),
+    (r"\int \frac{3 \cdot d\theta}{\theta}",
+     Integral(3*_Pow(theta, -1), theta)),
+    (r"\int \frac{1}{x} + 1 dx", Integral(_Add(_Pow(x, -1), 1), x)),
+    (r"x_0", Symbol('x_{0}')),
+    (r"x_{1}", Symbol('x_{1}')),
+    (r"x_a", Symbol('x_{a}')),
+    (r"x_{b}", Symbol('x_{b}')),
+    (r"h_\theta", Symbol('h_{theta}')),
+    (r"h_{\theta}", Symbol('h_{theta}')),
+    (r"h_{\theta}(x_0, x_1)",
+     Function('h_{theta}')(Symbol('x_{0}'), Symbol('x_{1}'))),
+    (r"x!", _factorial(x)),
+    (r"100!", _factorial(100)),
+    (r"\theta!", _factorial(theta)),
+    (r"(x + 1)!", _factorial(_Add(x, 1))),
+    (r"(x!)!", _factorial(_factorial(x))),
+    (r"x!!!", _factorial(_factorial(_factorial(x)))),
+    (r"5!7!", _Mul(_factorial(5), _factorial(7))),
+    (r"\sqrt{x}", sqrt(x)),
+    (r"\sqrt{x + b}", sqrt(_Add(x, b))),
+    (r"\sqrt[3]{\sin x}", root(sin(x), 3)),
+    (r"\sqrt[y]{\sin x}", root(sin(x), y)),
+    (r"\sqrt[\theta]{\sin x}", root(sin(x), theta)),
+    (r"\sqrt{\frac{12}{6}}", _Sqrt(_Mul(12, _Pow(6, -1)))),
+    (r"\overline{z}", _Conjugate(z)),
+    (r"\overline{\overline{z}}", _Conjugate(_Conjugate(z))),
+    (r"\overline{x + y}", _Conjugate(_Add(x, y))),
+    (r"\overline{x} + \overline{y}", _Conjugate(x) + _Conjugate(y)),
+    (r"x < y", StrictLessThan(x, y)),
+    (r"x \leq y", LessThan(x, y)),
+    (r"x > y", StrictGreaterThan(x, y)),
+    (r"x \geq y", GreaterThan(x, y)),
+    (r"\mathit{x}", Symbol('x')),
+    (r"\mathit{test}", Symbol('test')),
+    (r"\mathit{TEST}", Symbol('TEST')),
+    (r"\mathit{HELLO world}", Symbol('HELLO world')),
+    (r"\sum_{k = 1}^{3} c", Sum(c, (k, 1, 3))),
+    (r"\sum_{k = 1}^3 c", Sum(c, (k, 1, 3))),
+    (r"\sum^{3}_{k = 1} c", Sum(c, (k, 1, 3))),
+    (r"\sum^3_{k = 1} c", Sum(c, (k, 1, 3))),
+    (r"\sum_{k = 1}^{10} k^2", Sum(k**2, (k, 1, 10))),
+    (r"\sum_{n = 0}^{\infty} \frac{1}{n!}",
+     Sum(_Pow(_factorial(n), -1), (n, 0, oo))),
+    (r"\prod_{a = b}^{c} x", Product(x, (a, b, c))),
+    (r"\prod_{a = b}^c x", Product(x, (a, b, c))),
+    (r"\prod^{c}_{a = b} x", Product(x, (a, b, c))),
+    (r"\prod^c_{a = b} x", Product(x, (a, b, c))),
+    (r"\exp x", _exp(x)),
+    (r"\exp(x)", _exp(x)),
+    (r"\lg x", _log(x, 10)),
+    (r"\ln x", _log(x, E)),
+    (r"\ln xy", _log(x*y, E)),
+    (r"\log x", _log(x, E)),
+    (r"\log xy", _log(x*y, E)),
+    (r"\log_{2} x", _log(x, 2)),
+    (r"\log_{a} x", _log(x, a)),
+    (r"\log_{11} x", _log(x, 11)),
+    (r"\log_{a^2} x", _log(x, _Pow(a, 2))),
+    (r"[x]", x),
+    (r"[a + b]", _Add(a, b)),
+    (r"\frac{d}{dx} [ \tan x ]", Derivative(tan(x), x)),
+    (r"\binom{n}{k}", _binomial(n, k)),
+    (r"\tbinom{n}{k}", _binomial(n, k)),
+    (r"\dbinom{n}{k}", _binomial(n, k)),
+    (r"\binom{n}{0}", _binomial(n, 0)),
+    (r"x^\binom{n}{k}", _Pow(x, _binomial(n, k))),
+    (r"a \, b", _Mul(a, b)),
+    (r"a \thinspace b", _Mul(a, b)),
+    (r"a \: b", _Mul(a, b)),
+    (r"a \medspace b", _Mul(a, b)),
+    (r"a \; b", _Mul(a, b)),
+    (r"a \thickspace b", _Mul(a, b)),
+    (r"a \quad b", _Mul(a, b)),
+    (r"a \qquad b", _Mul(a, b)),
+    (r"a \! b", _Mul(a, b)),
+    (r"a \negthinspace b", _Mul(a, b)),
+    (r"a \negmedspace b", _Mul(a, b)),
+    (r"a \negthickspace b", _Mul(a, b)),
+    (r"\int x \, dx", Integral(x, x)),
+    (r"\log_2 x", _log(x, 2)),
+    (r"\log_a x", _log(x, a)),
+    (r"5^0 - 4^0", _Add(_Pow(5, 0), _Mul(-1, _Pow(4, 0)))),
+    (r"3x - 1", _Add(_Mul(3, x), -1))
+]
+
+
+def test_parseable():
+    from sympy.parsing.latex import parse_latex
+    for latex_str, sympy_expr in GOOD_PAIRS:
+        assert parse_latex(latex_str) == sympy_expr, latex_str
+
+# These bad LaTeX strings should raise a LaTeXParsingError when parsed
+BAD_STRINGS = [
+    r"(",
+    r")",
+    r"\frac{d}{dx}",
+    r"(\frac{d}{dx})",
+    r"\sqrt{}",
+    r"\sqrt",
+    r"\overline{}",
+    r"\overline",
+    r"{",
+    r"}",
+    r"\mathit{x + y}",
+    r"\mathit{21}",
+    r"\frac{2}{}",
+    r"\frac{}{2}",
+    r"\int",
+    r"!",
+    r"!0",
+    r"_",
+    r"^",
+    r"|",
+    r"||x|",
+    r"()",
+    r"((((((((((((((((()))))))))))))))))",
+    r"-",
+    r"\frac{d}{dx} + \frac{d}{dt}",
+    r"f(x,,y)",
+    r"f(x,y,",
+    r"\sin^x",
+    r"\cos^2",
+    r"@",
+    r"#",
+    r"$",
+    r"%",
+    r"&",
+    r"*",
+    r"" "\\",
+    r"~",
+    r"\frac{(2 + x}{1 - x)}",
+]
+
+def test_not_parseable():
+    from sympy.parsing.latex import parse_latex, LaTeXParsingError
+    for latex_str in BAD_STRINGS:
+        with raises(LaTeXParsingError):
+            parse_latex(latex_str)
+
+# At time of migration from latex2sympy, should fail but doesn't
+FAILING_BAD_STRINGS = [
+    r"\cos 1 \cos",
+    r"f(,",
+    r"f()",
+    r"a \div \div b",
+    r"a \cdot \cdot b",
+    r"a // b",
+    r"a +",
+    r"1.1.1",
+    r"1 +",
+    r"a / b /",
+]
+
+@XFAIL
+def test_failing_not_parseable():
+    from sympy.parsing.latex import parse_latex, LaTeXParsingError
+    for latex_str in FAILING_BAD_STRINGS:
+        with raises(LaTeXParsingError):
+            parse_latex(latex_str)
+
+# In strict mode, FAILING_BAD_STRINGS would fail
+def test_strict_mode():
+    from sympy.parsing.latex import parse_latex, LaTeXParsingError
+    for latex_str in FAILING_BAD_STRINGS:
+        with raises(LaTeXParsingError):
+            parse_latex(latex_str, strict=True)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_latex_deps.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_latex_deps.py
new file mode 100644
index 0000000000000000000000000000000000000000..7df44c2b19e34024db6e898f7c4eac962dcaa1c9
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_latex_deps.py
@@ -0,0 +1,16 @@
+from sympy.external import import_module
+from sympy.testing.pytest import ignore_warnings, raises
+
+antlr4 = import_module("antlr4", warn_not_installed=False)
+
+# disable tests if antlr4-python3-runtime is not present
+if antlr4:
+    disabled = True
+
+
+def test_no_import():
+    from sympy.parsing.latex import parse_latex
+
+    with ignore_warnings(UserWarning):
+        with raises(ImportError):
+            parse_latex('1 + 1')
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_latex_lark.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_latex_lark.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd1f72a66c788ac41d923005ea988664d05a16c1
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_latex_lark.py
@@ -0,0 +1,872 @@
+from sympy.testing.pytest import XFAIL
+from sympy.parsing.latex.lark import parse_latex_lark
+from sympy.external import import_module
+
+from sympy.concrete.products import Product
+from sympy.concrete.summations import Sum
+from sympy.core.function import Derivative, Function
+from sympy.core.numbers import E, oo, Rational
+from sympy.core.power import Pow
+from sympy.core.parameters import evaluate
+from sympy.core.relational import GreaterThan, LessThan, StrictGreaterThan, StrictLessThan, Unequality
+from sympy.core.symbol import Symbol
+from sympy.functions.combinatorial.factorials import binomial, factorial
+from sympy.functions.elementary.complexes import Abs, conjugate
+from sympy.functions.elementary.exponential import exp, log
+from sympy.functions.elementary.integers import ceiling, floor
+from sympy.functions.elementary.miscellaneous import root, sqrt, Min, Max
+from sympy.functions.elementary.trigonometric import asin, cos, csc, sec, sin, tan
+from sympy.integrals.integrals import Integral
+from sympy.series.limits import Limit
+from sympy import Matrix, MatAdd, MatMul, Transpose, Trace
+from sympy import I
+
+from sympy.core.relational import Eq, Ne, Lt, Le, Gt, Ge
+from sympy.physics.quantum import Bra, Ket, InnerProduct
+from sympy.abc import x, y, z, a, b, c, d, t, k, n
+
+from .test_latex import theta, f, _Add, _Mul, _Pow, _Sqrt, _Conjugate, _Abs, _factorial, _exp, _binomial
+
+lark = import_module("lark")
+
+# disable tests if lark is not present
+disabled = lark is None
+
+# shorthand definitions that are only needed for the Lark LaTeX parser
+def _Min(*args):
+    return Min(*args, evaluate=False)
+
+
+def _Max(*args):
+    return Max(*args, evaluate=False)
+
+
+def _log(a, b=E):
+    if b == E:
+        return log(a, evaluate=False)
+    else:
+        return log(a, b, evaluate=False)
+
+
+def _MatAdd(a, b):
+    return MatAdd(a, b, evaluate=False)
+
+
+def _MatMul(a, b):
+    return MatMul(a, b, evaluate=False)
+
+
+# These LaTeX strings should parse to the corresponding SymPy expression
+SYMBOL_EXPRESSION_PAIRS = [
+    (r"x_0", Symbol('x_{0}')),
+    (r"x_{1}", Symbol('x_{1}')),
+    (r"x_a", Symbol('x_{a}')),
+    (r"x_{b}", Symbol('x_{b}')),
+    (r"h_\theta", Symbol('h_{theta}')),
+    (r"h_{\theta}", Symbol('h_{theta}')),
+    (r"y''_1", Symbol("y''_{1}")),
+    (r"y_1''", Symbol("y_{1}''")),
+    (r"\mathit{x}", Symbol('x')),
+    (r"\mathit{test}", Symbol('test')),
+    (r"\mathit{TEST}", Symbol('TEST')),
+    (r"\mathit{HELLO world}", Symbol('HELLO world')),
+    (r"a'", Symbol("a'")),
+    (r"a''", Symbol("a''")),
+    (r"\alpha'", Symbol("alpha'")),
+    (r"\alpha''", Symbol("alpha''")),
+    (r"a_b", Symbol("a_{b}")),
+    (r"a_b'", Symbol("a_{b}'")),
+    (r"a'_b", Symbol("a'_{b}")),
+    (r"a'_b'", Symbol("a'_{b}'")),
+    (r"a_{b'}", Symbol("a_{b'}")),
+    (r"a_{b'}'", Symbol("a_{b'}'")),
+    (r"a'_{b'}", Symbol("a'_{b'}")),
+    (r"a'_{b'}'", Symbol("a'_{b'}'")),
+    (r"\mathit{foo}'", Symbol("foo'")),
+    (r"\mathit{foo'}", Symbol("foo'")),
+    (r"\mathit{foo'}'", Symbol("foo''")),
+    (r"a_b''", Symbol("a_{b}''")),
+    (r"a''_b", Symbol("a''_{b}")),
+    (r"a''_b'''", Symbol("a''_{b}'''")),
+    (r"a_{b''}", Symbol("a_{b''}")),
+    (r"a_{b''}''", Symbol("a_{b''}''")),
+    (r"a''_{b''}", Symbol("a''_{b''}")),
+    (r"a''_{b''}'''", Symbol("a''_{b''}'''")),
+    (r"\mathit{foo}''", Symbol("foo''")),
+    (r"\mathit{foo''}", Symbol("foo''")),
+    (r"\mathit{foo''}'''", Symbol("foo'''''")),
+    (r"a_\alpha", Symbol("a_{alpha}")),
+    (r"a_\alpha'", Symbol("a_{alpha}'")),
+    (r"a'_\alpha", Symbol("a'_{alpha}")),
+    (r"a'_\alpha'", Symbol("a'_{alpha}'")),
+    (r"a_{\alpha'}", Symbol("a_{alpha'}")),
+    (r"a_{\alpha'}'", Symbol("a_{alpha'}'")),
+    (r"a'_{\alpha'}", Symbol("a'_{alpha'}")),
+    (r"a'_{\alpha'}'", Symbol("a'_{alpha'}'")),
+    (r"a_\alpha''", Symbol("a_{alpha}''")),
+    (r"a''_\alpha", Symbol("a''_{alpha}")),
+    (r"a''_\alpha'''", Symbol("a''_{alpha}'''")),
+    (r"a_{\alpha''}", Symbol("a_{alpha''}")),
+    (r"a_{\alpha''}''", Symbol("a_{alpha''}''")),
+    (r"a''_{\alpha''}", Symbol("a''_{alpha''}")),
+    (r"a''_{\alpha''}'''", Symbol("a''_{alpha''}'''")),
+    (r"\alpha_b", Symbol("alpha_{b}")),
+    (r"\alpha_b'", Symbol("alpha_{b}'")),
+    (r"\alpha'_b", Symbol("alpha'_{b}")),
+    (r"\alpha'_b'", Symbol("alpha'_{b}'")),
+    (r"\alpha_{b'}", Symbol("alpha_{b'}")),
+    (r"\alpha_{b'}'", Symbol("alpha_{b'}'")),
+    (r"\alpha'_{b'}", Symbol("alpha'_{b'}")),
+    (r"\alpha'_{b'}'", Symbol("alpha'_{b'}'")),
+    (r"\alpha_b''", Symbol("alpha_{b}''")),
+    (r"\alpha''_b", Symbol("alpha''_{b}")),
+    (r"\alpha''_b'''", Symbol("alpha''_{b}'''")),
+    (r"\alpha_{b''}", Symbol("alpha_{b''}")),
+    (r"\alpha_{b''}''", Symbol("alpha_{b''}''")),
+    (r"\alpha''_{b''}", Symbol("alpha''_{b''}")),
+    (r"\alpha''_{b''}'''", Symbol("alpha''_{b''}'''")),
+    (r"\alpha_\beta", Symbol("alpha_{beta}")),
+    (r"\alpha_{\beta}", Symbol("alpha_{beta}")),
+    (r"\alpha_{\beta'}", Symbol("alpha_{beta'}")),
+    (r"\alpha_{\beta''}", Symbol("alpha_{beta''}")),
+    (r"\alpha'_\beta", Symbol("alpha'_{beta}")),
+    (r"\alpha'_{\beta}", Symbol("alpha'_{beta}")),
+    (r"\alpha'_{\beta'}", Symbol("alpha'_{beta'}")),
+    (r"\alpha'_{\beta''}", Symbol("alpha'_{beta''}")),
+    (r"\alpha''_\beta", Symbol("alpha''_{beta}")),
+    (r"\alpha''_{\beta}", Symbol("alpha''_{beta}")),
+    (r"\alpha''_{\beta'}", Symbol("alpha''_{beta'}")),
+    (r"\alpha''_{\beta''}", Symbol("alpha''_{beta''}")),
+    (r"\alpha_\beta'", Symbol("alpha_{beta}'")),
+    (r"\alpha_{\beta}'", Symbol("alpha_{beta}'")),
+    (r"\alpha_{\beta'}'", Symbol("alpha_{beta'}'")),
+    (r"\alpha_{\beta''}'", Symbol("alpha_{beta''}'")),
+    (r"\alpha'_\beta'", Symbol("alpha'_{beta}'")),
+    (r"\alpha'_{\beta}'", Symbol("alpha'_{beta}'")),
+    (r"\alpha'_{\beta'}'", Symbol("alpha'_{beta'}'")),
+    (r"\alpha'_{\beta''}'", Symbol("alpha'_{beta''}'")),
+    (r"\alpha''_\beta'", Symbol("alpha''_{beta}'")),
+    (r"\alpha''_{\beta}'", Symbol("alpha''_{beta}'")),
+    (r"\alpha''_{\beta'}'", Symbol("alpha''_{beta'}'")),
+    (r"\alpha''_{\beta''}'", Symbol("alpha''_{beta''}'")),
+    (r"\alpha_\beta''", Symbol("alpha_{beta}''")),
+    (r"\alpha_{\beta}''", Symbol("alpha_{beta}''")),
+    (r"\alpha_{\beta'}''", Symbol("alpha_{beta'}''")),
+    (r"\alpha_{\beta''}''", Symbol("alpha_{beta''}''")),
+    (r"\alpha'_\beta''", Symbol("alpha'_{beta}''")),
+    (r"\alpha'_{\beta}''", Symbol("alpha'_{beta}''")),
+    (r"\alpha'_{\beta'}''", Symbol("alpha'_{beta'}''")),
+    (r"\alpha'_{\beta''}''", Symbol("alpha'_{beta''}''")),
+    (r"\alpha''_\beta''", Symbol("alpha''_{beta}''")),
+    (r"\alpha''_{\beta}''", Symbol("alpha''_{beta}''")),
+    (r"\alpha''_{\beta'}''", Symbol("alpha''_{beta'}''")),
+    (r"\alpha''_{\beta''}''", Symbol("alpha''_{beta''}''"))
+
+]
+
+UNEVALUATED_SIMPLE_EXPRESSION_PAIRS = [
+    (r"0", 0),
+    (r"1", 1),
+    (r"-3.14", -3.14),
+    (r"(-7.13)(1.5)", _Mul(-7.13, 1.5)),
+    (r"1+1", _Add(1, 1)),
+    (r"0+1", _Add(0, 1)),
+    (r"1*2", _Mul(1, 2)),
+    (r"0*1", _Mul(0, 1)),
+    (r"x", x),
+    (r"2x", 2 * x),
+    (r"3x - 1", _Add(_Mul(3, x), -1)),
+    (r"-c", -c),
+    (r"\infty", oo),
+    (r"a \cdot b", a * b),
+    (r"1 \times 2 ", _Mul(1, 2)),
+    (r"a / b", a / b),
+    (r"a \div b", a / b),
+    (r"a + b", a + b),
+    (r"a + b - a", _Add(a + b, -a)),
+    (r"(x + y) z", _Mul(_Add(x, y), z)),
+    (r"a'b+ab'", _Add(_Mul(Symbol("a'"), b), _Mul(a, Symbol("b'"))))
+]
+
+EVALUATED_SIMPLE_EXPRESSION_PAIRS = [
+    (r"(-7.13)(1.5)", -10.695),
+    (r"1+1", 2),
+    (r"0+1", 1),
+    (r"1*2", 2),
+    (r"0*1", 0),
+    (r"2x", 2 * x),
+    (r"3x - 1", 3 * x - 1),
+    (r"-c", -c),
+    (r"a \cdot b", a * b),
+    (r"1 \times 2 ", 2),
+    (r"a / b", a / b),
+    (r"a \div b", a / b),
+    (r"a + b", a + b),
+    (r"a + b - a", b),
+    (r"(x + y) z", (x + y) * z),
+]
+
+UNEVALUATED_FRACTION_EXPRESSION_PAIRS = [
+    (r"\frac{a}{b}", a / b),
+    (r"\dfrac{a}{b}", a / b),
+    (r"\tfrac{a}{b}", a / b),
+    (r"\frac12", _Mul(1, _Pow(2, -1))),
+    (r"\frac12y", _Mul(_Mul(1, _Pow(2, -1)), y)),
+    (r"\frac1234", _Mul(_Mul(1, _Pow(2, -1)), 34)),
+    (r"\frac2{3}", _Mul(2, _Pow(3, -1))),
+    (r"\frac{a + b}{c}", _Mul(a + b, _Pow(c, -1))),
+    (r"\frac{7}{3}", _Mul(7, _Pow(3, -1)))
+]
+
+EVALUATED_FRACTION_EXPRESSION_PAIRS = [
+    (r"\frac{a}{b}", a / b),
+    (r"\dfrac{a}{b}", a / b),
+    (r"\tfrac{a}{b}", a / b),
+    (r"\frac12", Rational(1, 2)),
+    (r"\frac12y", y / 2),
+    (r"\frac1234", 17),
+    (r"\frac2{3}", Rational(2, 3)),
+    (r"\frac{a + b}{c}", (a + b) / c),
+    (r"\frac{7}{3}", Rational(7, 3))
+]
+
+RELATION_EXPRESSION_PAIRS = [
+    (r"x = y", Eq(x, y)),
+    (r"x \neq y", Ne(x, y)),
+    (r"x < y", Lt(x, y)),
+    (r"x > y", Gt(x, y)),
+    (r"x \leq y", Le(x, y)),
+    (r"x \geq y", Ge(x, y)),
+    (r"x \le y", Le(x, y)),
+    (r"x \ge y", Ge(x, y)),
+    (r"x < y", StrictLessThan(x, y)),
+    (r"x \leq y", LessThan(x, y)),
+    (r"x > y", StrictGreaterThan(x, y)),
+    (r"x \geq y", GreaterThan(x, y)),
+    (r"x \neq y", Unequality(x, y)), # same as 2nd one in the list
+    (r"a^2 + b^2 = c^2", Eq(a**2 + b**2, c**2))
+]
+
+UNEVALUATED_POWER_EXPRESSION_PAIRS = [
+    (r"x^2", x ** 2),
+    (r"x^\frac{1}{2}", _Pow(x, _Mul(1, _Pow(2, -1)))),
+    (r"x^{3 + 1}", x ** _Add(3, 1)),
+    (r"\pi^{|xy|}", Symbol('pi') ** _Abs(x * y)),
+    (r"5^0 - 4^0", _Add(_Pow(5, 0), _Mul(-1, _Pow(4, 0))))
+]
+
+EVALUATED_POWER_EXPRESSION_PAIRS = [
+    (r"x^2", x ** 2),
+    (r"x^\frac{1}{2}", sqrt(x)),
+    (r"x^{3 + 1}", x ** 4),
+    (r"\pi^{|xy|}", Symbol('pi') ** _Abs(x * y)),
+    (r"5^0 - 4^0", 0)
+]
+
+UNEVALUATED_INTEGRAL_EXPRESSION_PAIRS = [
+    (r"\int x dx", Integral(_Mul(1, x), x)),
+    (r"\int x \, dx", Integral(_Mul(1, x), x)),
+    (r"\int x d\theta", Integral(_Mul(1, x), theta)),
+    (r"\int (x^2 - y)dx", Integral(_Mul(1, x ** 2 - y), x)),
+    (r"\int x + a dx", Integral(_Mul(1, _Add(x, a)), x)),
+    (r"\int da", Integral(_Mul(1, 1), a)),
+    (r"\int_0^7 dx", Integral(_Mul(1, 1), (x, 0, 7))),
+    (r"\int\limits_{0}^{1} x dx", Integral(_Mul(1, x), (x, 0, 1))),
+    (r"\int_a^b x dx", Integral(_Mul(1, x), (x, a, b))),
+    (r"\int^b_a x dx", Integral(_Mul(1, x), (x, a, b))),
+    (r"\int_{a}^b x dx", Integral(_Mul(1, x), (x, a, b))),
+    (r"\int^{b}_a x dx", Integral(_Mul(1, x), (x, a, b))),
+    (r"\int_{a}^{b} x dx", Integral(_Mul(1, x), (x, a, b))),
+    (r"\int^{b}_{a} x dx", Integral(_Mul(1, x), (x, a, b))),
+    (r"\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))),
+    (r"\int a + b + c dx", Integral(_Mul(1, _Add(_Add(a, b), c)), x)),
+    (r"\int \frac{dz}{z}", Integral(_Mul(1, _Mul(1, Pow(z, -1))), z)),
+    (r"\int \frac{3 dz}{z}", Integral(_Mul(1, _Mul(3, _Pow(z, -1))), z)),
+    (r"\int \frac{1}{x} dx", Integral(_Mul(1, _Mul(1, Pow(x, -1))), x)),
+    (r"\int \frac{1}{a} + \frac{1}{b} dx",
+     Integral(_Mul(1, _Add(_Mul(1, _Pow(a, -1)), _Mul(1, Pow(b, -1)))), x)),
+    (r"\int \frac{1}{x} + 1 dx", Integral(_Mul(1, _Add(_Mul(1, _Pow(x, -1)), 1)), x))
+]
+
+EVALUATED_INTEGRAL_EXPRESSION_PAIRS = [
+    (r"\int x dx", Integral(x, x)),
+    (r"\int x \, dx", Integral(x, x)),
+    (r"\int x d\theta", Integral(x, theta)),
+    (r"\int (x^2 - y)dx", Integral(x ** 2 - y, x)),
+    (r"\int x + a dx", Integral(x + a, x)),
+    (r"\int da", Integral(1, a)),
+    (r"\int_0^7 dx", Integral(1, (x, 0, 7))),
+    (r"\int\limits_{0}^{1} x dx", Integral(x, (x, 0, 1))),
+    (r"\int_a^b x dx", Integral(x, (x, a, b))),
+    (r"\int^b_a x dx", Integral(x, (x, a, b))),
+    (r"\int_{a}^b x dx", Integral(x, (x, a, b))),
+    (r"\int^{b}_a x dx", Integral(x, (x, a, b))),
+    (r"\int_{a}^{b} x dx", Integral(x, (x, a, b))),
+    (r"\int^{b}_{a} x dx", Integral(x, (x, a, b))),
+    (r"\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))),
+    (r"\int a + b + c dx", Integral(a + b + c, x)),
+    (r"\int \frac{dz}{z}", Integral(Pow(z, -1), z)),
+    (r"\int \frac{3 dz}{z}", Integral(3 * Pow(z, -1), z)),
+    (r"\int \frac{1}{x} dx", Integral(1 / x, x)),
+    (r"\int \frac{1}{a} + \frac{1}{b} dx", Integral(1 / a + 1 / b, x)),
+    (r"\int \frac{1}{a} - \frac{1}{b} dx", Integral(1 / a - 1 / b, x)),
+    (r"\int \frac{1}{x} + 1 dx", Integral(1 / x + 1, x))
+]
+
+DERIVATIVE_EXPRESSION_PAIRS = [
+    (r"\frac{d}{dx} x", Derivative(x, x)),
+    (r"\frac{d}{dt} x", Derivative(x, t)),
+    (r"\frac{d}{dx} ( \tan x )", Derivative(tan(x), x)),
+    (r"\frac{d f(x)}{dx}", Derivative(f(x), x)),
+    (r"\frac{d\theta(x)}{dx}", Derivative(Function('theta')(x), x))
+]
+
+TRIGONOMETRIC_EXPRESSION_PAIRS = [
+    (r"\sin \theta", sin(theta)),
+    (r"\sin(\theta)", sin(theta)),
+    (r"\sin^{-1} a", asin(a)),
+    (r"\sin a \cos b", _Mul(sin(a), cos(b))),
+    (r"\sin \cos \theta", sin(cos(theta))),
+    (r"\sin(\cos \theta)", sin(cos(theta))),
+    (r"(\csc x)(\sec y)", csc(x) * sec(y)),
+    (r"\frac{\sin{x}}2", _Mul(sin(x), _Pow(2, -1)))
+]
+
+UNEVALUATED_LIMIT_EXPRESSION_PAIRS = [
+    (r"\lim_{x \to 3} a", Limit(a, x, 3, dir="+-")),
+    (r"\lim_{x \rightarrow 3} a", Limit(a, x, 3, dir="+-")),
+    (r"\lim_{x \Rightarrow 3} a", Limit(a, x, 3, dir="+-")),
+    (r"\lim_{x \longrightarrow 3} a", Limit(a, x, 3, dir="+-")),
+    (r"\lim_{x \Longrightarrow 3} a", Limit(a, x, 3, dir="+-")),
+    (r"\lim_{x \to 3^{+}} a", Limit(a, x, 3, dir="+")),
+    (r"\lim_{x \to 3^{-}} a", Limit(a, x, 3, dir="-")),
+    (r"\lim_{x \to 3^+} a", Limit(a, x, 3, dir="+")),
+    (r"\lim_{x \to 3^-} a", Limit(a, x, 3, dir="-")),
+    (r"\lim_{x \to \infty} \frac{1}{x}", Limit(_Mul(1, _Pow(x, -1)), x, oo))
+]
+
+EVALUATED_LIMIT_EXPRESSION_PAIRS = [
+    (r"\lim_{x \to \infty} \frac{1}{x}", Limit(1 / x, x, oo))
+]
+
+UNEVALUATED_SQRT_EXPRESSION_PAIRS = [
+    (r"\sqrt{x}", sqrt(x)),
+    (r"\sqrt{x + b}", sqrt(_Add(x, b))),
+    (r"\sqrt[3]{\sin x}", _Pow(sin(x), _Pow(3, -1))),
+    # the above test needed to be handled differently than the ones below because root
+    # acts differently if its second argument is a number
+    (r"\sqrt[y]{\sin x}", root(sin(x), y)),
+    (r"\sqrt[\theta]{\sin x}", root(sin(x), theta)),
+    (r"\sqrt{\frac{12}{6}}", _Sqrt(_Mul(12, _Pow(6, -1))))
+]
+
+EVALUATED_SQRT_EXPRESSION_PAIRS = [
+    (r"\sqrt{x}", sqrt(x)),
+    (r"\sqrt{x + b}", sqrt(x + b)),
+    (r"\sqrt[3]{\sin x}", root(sin(x), 3)),
+    (r"\sqrt[y]{\sin x}", root(sin(x), y)),
+    (r"\sqrt[\theta]{\sin x}", root(sin(x), theta)),
+    (r"\sqrt{\frac{12}{6}}", sqrt(2))
+]
+
+UNEVALUATED_FACTORIAL_EXPRESSION_PAIRS = [
+    (r"x!", _factorial(x)),
+    (r"100!", _factorial(100)),
+    (r"\theta!", _factorial(theta)),
+    (r"(x + 1)!", _factorial(_Add(x, 1))),
+    (r"(x!)!", _factorial(_factorial(x))),
+    (r"x!!!", _factorial(_factorial(_factorial(x)))),
+    (r"5!7!", _Mul(_factorial(5), _factorial(7)))
+]
+
+EVALUATED_FACTORIAL_EXPRESSION_PAIRS = [
+    (r"x!", factorial(x)),
+    (r"100!", factorial(100)),
+    (r"\theta!", factorial(theta)),
+    (r"(x + 1)!", factorial(x + 1)),
+    (r"(x!)!", factorial(factorial(x))),
+    (r"x!!!", factorial(factorial(factorial(x)))),
+    (r"5!7!", factorial(5) * factorial(7)),
+    (r"24! \times 24!", factorial(24) * factorial(24))
+]
+
+UNEVALUATED_SUM_EXPRESSION_PAIRS = [
+    (r"\sum_{k = 1}^{3} c", Sum(_Mul(1, c), (k, 1, 3))),
+    (r"\sum_{k = 1}^3 c", Sum(_Mul(1, c), (k, 1, 3))),
+    (r"\sum^{3}_{k = 1} c", Sum(_Mul(1, c), (k, 1, 3))),
+    (r"\sum^3_{k = 1} c", Sum(_Mul(1, c), (k, 1, 3))),
+    (r"\sum_{k = 1}^{10} k^2", Sum(_Mul(1, k ** 2), (k, 1, 10))),
+    (r"\sum_{n = 0}^{\infty} \frac{1}{n!}",
+     Sum(_Mul(1, _Mul(1, _Pow(_factorial(n), -1))), (n, 0, oo)))
+]
+
+EVALUATED_SUM_EXPRESSION_PAIRS = [
+    (r"\sum_{k = 1}^{3} c", Sum(c, (k, 1, 3))),
+    (r"\sum_{k = 1}^3 c", Sum(c, (k, 1, 3))),
+    (r"\sum^{3}_{k = 1} c", Sum(c, (k, 1, 3))),
+    (r"\sum^3_{k = 1} c", Sum(c, (k, 1, 3))),
+    (r"\sum_{k = 1}^{10} k^2", Sum(k ** 2, (k, 1, 10))),
+    (r"\sum_{n = 0}^{\infty} \frac{1}{n!}", Sum(1 / factorial(n), (n, 0, oo)))
+]
+
+UNEVALUATED_PRODUCT_EXPRESSION_PAIRS = [
+    (r"\prod_{a = b}^{c} x", Product(x, (a, b, c))),
+    (r"\prod_{a = b}^c x", Product(x, (a, b, c))),
+    (r"\prod^{c}_{a = b} x", Product(x, (a, b, c))),
+    (r"\prod^c_{a = b} x", Product(x, (a, b, c)))
+]
+
+APPLIED_FUNCTION_EXPRESSION_PAIRS = [
+    (r"f(x)", f(x)),
+    (r"f(x, y)", f(x, y)),
+    (r"f(x, y, z)", f(x, y, z)),
+    (r"f'_1(x)", Function("f_{1}'")(x)),
+    (r"f_{1}''(x+y)", Function("f_{1}''")(x + y)),
+    (r"h_{\theta}(x_0, x_1)",
+     Function('h_{theta}')(Symbol('x_{0}'), Symbol('x_{1}')))
+]
+
+UNEVALUATED_COMMON_FUNCTION_EXPRESSION_PAIRS = [
+    (r"|x|", _Abs(x)),
+    (r"||x||", _Abs(Abs(x))),
+    (r"|x||y|", _Abs(x) * _Abs(y)),
+    (r"||x||y||", _Abs(_Abs(x) * _Abs(y))),
+    (r"\lfloor x \rfloor", floor(x)),
+    (r"\lceil x \rceil", ceiling(x)),
+    (r"\exp x", _exp(x)),
+    (r"\exp(x)", _exp(x)),
+    (r"\lg x", _log(x, 10)),
+    (r"\ln x", _log(x)),
+    (r"\ln xy", _log(x * y)),
+    (r"\log x", _log(x)),
+    (r"\log xy", _log(x * y)),
+    (r"\log_{2} x", _log(x, 2)),
+    (r"\log_{a} x", _log(x, a)),
+    (r"\log_{11} x", _log(x, 11)),
+    (r"\log_{a^2} x", _log(x, _Pow(a, 2))),
+    (r"\log_2 x", _log(x, 2)),
+    (r"\log_a x", _log(x, a)),
+    (r"\overline{z}", _Conjugate(z)),
+    (r"\overline{\overline{z}}", _Conjugate(_Conjugate(z))),
+    (r"\overline{x + y}", _Conjugate(_Add(x, y))),
+    (r"\overline{x} + \overline{y}", _Conjugate(x) + _Conjugate(y)),
+    (r"\min(a, b)", _Min(a, b)),
+    (r"\min(a, b, c - d, xy)", _Min(a, b, c - d, x * y)),
+    (r"\max(a, b)", _Max(a, b)),
+    (r"\max(a, b, c - d, xy)", _Max(a, b, c - d, x * y)),
+    # physics things don't have an `evaluate=False` variant
+    (r"\langle x |", Bra('x')),
+    (r"| x \rangle", Ket('x')),
+    (r"\langle x | y \rangle", InnerProduct(Bra('x'), Ket('y'))),
+]
+
+EVALUATED_COMMON_FUNCTION_EXPRESSION_PAIRS = [
+    (r"|x|", Abs(x)),
+    (r"||x||", Abs(Abs(x))),
+    (r"|x||y|", Abs(x) * Abs(y)),
+    (r"||x||y||", Abs(Abs(x) * Abs(y))),
+    (r"\lfloor x \rfloor", floor(x)),
+    (r"\lceil x \rceil", ceiling(x)),
+    (r"\exp x", exp(x)),
+    (r"\exp(x)", exp(x)),
+    (r"\lg x", log(x, 10)),
+    (r"\ln x", log(x)),
+    (r"\ln xy", log(x * y)),
+    (r"\log x", log(x)),
+    (r"\log xy", log(x * y)),
+    (r"\log_{2} x", log(x, 2)),
+    (r"\log_{a} x", log(x, a)),
+    (r"\log_{11} x", log(x, 11)),
+    (r"\log_{a^2} x", log(x, _Pow(a, 2))),
+    (r"\log_2 x", log(x, 2)),
+    (r"\log_a x", log(x, a)),
+    (r"\overline{z}", conjugate(z)),
+    (r"\overline{\overline{z}}", conjugate(conjugate(z))),
+    (r"\overline{x + y}", conjugate(x + y)),
+    (r"\overline{x} + \overline{y}", conjugate(x) + conjugate(y)),
+    (r"\min(a, b)", Min(a, b)),
+    (r"\min(a, b, c - d, xy)", Min(a, b, c - d, x * y)),
+    (r"\max(a, b)", Max(a, b)),
+    (r"\max(a, b, c - d, xy)", Max(a, b, c - d, x * y)),
+    (r"\langle x |", Bra('x')),
+    (r"| x \rangle", Ket('x')),
+    (r"\langle x | y \rangle", InnerProduct(Bra('x'), Ket('y'))),
+]
+
+SPACING_RELATED_EXPRESSION_PAIRS = [
+    (r"a \, b", _Mul(a, b)),
+    (r"a \thinspace b", _Mul(a, b)),
+    (r"a \: b", _Mul(a, b)),
+    (r"a \medspace b", _Mul(a, b)),
+    (r"a \; b", _Mul(a, b)),
+    (r"a \thickspace b", _Mul(a, b)),
+    (r"a \quad b", _Mul(a, b)),
+    (r"a \qquad b", _Mul(a, b)),
+    (r"a \! b", _Mul(a, b)),
+    (r"a \negthinspace b", _Mul(a, b)),
+    (r"a \negmedspace b", _Mul(a, b)),
+    (r"a \negthickspace b", _Mul(a, b))
+]
+
+UNEVALUATED_BINOMIAL_EXPRESSION_PAIRS = [
+    (r"\binom{n}{k}", _binomial(n, k)),
+    (r"\tbinom{n}{k}", _binomial(n, k)),
+    (r"\dbinom{n}{k}", _binomial(n, k)),
+    (r"\binom{n}{0}", _binomial(n, 0)),
+    (r"x^\binom{n}{k}", _Pow(x, _binomial(n, k)))
+]
+
+EVALUATED_BINOMIAL_EXPRESSION_PAIRS = [
+    (r"\binom{n}{k}", binomial(n, k)),
+    (r"\tbinom{n}{k}", binomial(n, k)),
+    (r"\dbinom{n}{k}", binomial(n, k)),
+    (r"\binom{n}{0}", binomial(n, 0)),
+    (r"x^\binom{n}{k}", x ** binomial(n, k))
+]
+
+MISCELLANEOUS_EXPRESSION_PAIRS = [
+    (r"\left(x + y\right) z", _Mul(_Add(x, y), z)),
+    (r"\left( x + y\right ) z", _Mul(_Add(x, y), z)),
+    (r"\left(  x + y\right ) z", _Mul(_Add(x, y), z)),
+]
+
+UNEVALUATED_LITERAL_COMPLEX_NUMBER_EXPRESSION_PAIRS = [
+    (r"\imaginaryunit^2", _Pow(I, 2)),
+    (r"|\imaginaryunit|", _Abs(I)),
+    (r"\overline{\imaginaryunit}", _Conjugate(I)),
+    (r"\imaginaryunit+\imaginaryunit", _Add(I, I)),
+    (r"\imaginaryunit-\imaginaryunit", _Add(I, -I)),
+    (r"\imaginaryunit*\imaginaryunit", _Mul(I, I)),
+    (r"\imaginaryunit/\imaginaryunit", _Mul(I, _Pow(I, -1))),
+    (r"(1+\imaginaryunit)/|1+\imaginaryunit|", _Mul(_Add(1, I), _Pow(_Abs(_Add(1, I)), -1)))
+]
+
+UNEVALUATED_MATRIX_EXPRESSION_PAIRS = [
+    (r"\begin{pmatrix}a & b \\x & y\end{pmatrix}",
+     Matrix([[a, b], [x, y]])),
+    (r"\begin{pmatrix}a & b \\x & y\\\end{pmatrix}",
+     Matrix([[a, b], [x, y]])),
+    (r"\begin{bmatrix}a & b \\x & y\end{bmatrix}",
+     Matrix([[a, b], [x, y]])),
+    (r"\left(\begin{matrix}a & b \\x & y\end{matrix}\right)",
+     Matrix([[a, b], [x, y]])),
+    (r"\left[\begin{matrix}a & b \\x & y\end{matrix}\right]",
+     Matrix([[a, b], [x, y]])),
+    (r"\left[\begin{array}{cc}a & b \\x & y\end{array}\right]",
+     Matrix([[a, b], [x, y]])),
+    (r"\left(\begin{array}{cc}a & b \\x & y\end{array}\right)",
+     Matrix([[a, b], [x, y]])),
+    (r"\left( { \begin{array}{cc}a & b \\x & y\end{array} } \right)",
+     Matrix([[a, b], [x, y]])),
+    (r"+\begin{pmatrix}a & b \\x & y\end{pmatrix}",
+     Matrix([[a, b], [x, y]])),
+    ((r"\begin{pmatrix}x & y \\a & b\end{pmatrix}+"
+      r"\begin{pmatrix}a & b \\x & y\end{pmatrix}"),
+     _MatAdd(Matrix([[x, y], [a, b]]), Matrix([[a, b], [x, y]]))),
+    (r"-\begin{pmatrix}a & b \\x & y\end{pmatrix}",
+     _MatMul(-1, Matrix([[a, b], [x, y]]))),
+    ((r"\begin{pmatrix}x & y \\a & b\end{pmatrix}-"
+      r"\begin{pmatrix}a & b \\x & y\end{pmatrix}"),
+     _MatAdd(Matrix([[x, y], [a, b]]), _MatMul(-1, Matrix([[a, b], [x, y]])))),
+    ((r"\begin{pmatrix}a & b & c \\x & y & z \\a & b & c \end{pmatrix}*"
+      r"\begin{pmatrix}x & y & z \\a & b & c \\a & b & c \end{pmatrix}*"
+      r"\begin{pmatrix}a & b & c \\x & y & z \\x & y & z \end{pmatrix}"),
+     _MatMul(_MatMul(Matrix([[a, b, c], [x, y, z], [a, b, c]]),
+                     Matrix([[x, y, z], [a, b, c], [a, b, c]])),
+             Matrix([[a, b, c], [x, y, z], [x, y, z]]))),
+    (r"\begin{pmatrix}a & b \\x & y\end{pmatrix}/2",
+     _MatMul(Matrix([[a, b], [x, y]]), _Pow(2, -1))),
+    (r"\begin{pmatrix}a & b \\x & y\end{pmatrix}^2",
+     _Pow(Matrix([[a, b], [x, y]]), 2)),
+    (r"\begin{pmatrix}a & b \\x & y\end{pmatrix}^{-1}",
+     _Pow(Matrix([[a, b], [x, y]]), -1)),
+    (r"\begin{pmatrix}a & b \\x & y\end{pmatrix}^T",
+     Transpose(Matrix([[a, b], [x, y]]))),
+    (r"\begin{pmatrix}a & b \\x & y\end{pmatrix}^{T}",
+     Transpose(Matrix([[a, b], [x, y]]))),
+    (r"\begin{pmatrix}a & b \\x & y\end{pmatrix}^\mathit{T}",
+     Transpose(Matrix([[a, b], [x, y]]))),
+    (r"\begin{pmatrix}1 & 2 \\3 & 4\end{pmatrix}^T",
+     Transpose(Matrix([[1, 2], [3, 4]]))),
+    ((r"(\begin{pmatrix}1 & 2 \\3 & 4\end{pmatrix}+"
+      r"\begin{pmatrix}1 & 2 \\3 & 4\end{pmatrix}^T)*"
+      r"\begin{bmatrix}1\\0\end{bmatrix}"),
+     _MatMul(_MatAdd(Matrix([[1, 2], [3, 4]]),
+                     Transpose(Matrix([[1, 2], [3, 4]]))),
+                Matrix([[1], [0]]))),
+    ((r"(\begin{pmatrix}a & b \\x & y\end{pmatrix}+"
+      r"\begin{pmatrix}x & y \\a & b\end{pmatrix})^2"),
+    _Pow(_MatAdd(Matrix([[a, b], [x, y]]),
+                 Matrix([[x, y], [a, b]])), 2)),
+    ((r"(\begin{pmatrix}a & b \\x & y\end{pmatrix}+"
+      r"\begin{pmatrix}x & y \\a & b\end{pmatrix})^T"),
+    Transpose(_MatAdd(Matrix([[a, b], [x, y]]),
+                      Matrix([[x, y], [a, b]])))),
+    (r"\overline{\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}}",
+     _Conjugate(_MatAdd(Matrix([[I, 2], [3, 4]]),
+                        Matrix([[I, 2], [3, 4]]))))
+]
+
+EVALUATED_MATRIX_EXPRESSION_PAIRS = [
+    (r"\det\left(\left[   { \begin{array}{cc}a&b\\x&y\end{array} } \right]\right)",
+     Matrix([[a, b], [x, y]]).det()),
+    (r"\det \begin{pmatrix}1&2\\3&4\end{pmatrix}", -2),
+    (r"\det{\begin{pmatrix}1&2\\3&4\end{pmatrix}}", -2),
+    (r"\det(\begin{pmatrix}1&2\\3&4\end{pmatrix})", -2),
+    (r"\det\left(\begin{pmatrix}1&2\\3&4\end{pmatrix}\right)", -2),
+    (r"\begin{pmatrix}a & b \\x & y\end{pmatrix}/\begin{vmatrix}a & b \\x & y\end{vmatrix}",
+     _MatMul(Matrix([[a, b], [x, y]]), _Pow(Matrix([[a, b], [x, y]]).det(), -1))),
+    (r"\begin{pmatrix}a & b \\x & y\end{pmatrix}/|\begin{matrix}a & b \\x & y\end{matrix}|",
+     _MatMul(Matrix([[a, b], [x, y]]), _Pow(Matrix([[a, b], [x, y]]).det(), -1))),
+    (r"\frac{\begin{pmatrix}a & b \\x & y\end{pmatrix}}{| { \begin{matrix}a & b \\x & y\end{matrix} } |}",
+     _MatMul(Matrix([[a, b], [x, y]]), _Pow(Matrix([[a, b], [x, y]]).det(), -1))),
+    (r"\overline{\begin{pmatrix}\imaginaryunit & 1+\imaginaryunit \\-\imaginaryunit & 4\end{pmatrix}}",
+     Matrix([[-I, 1-I], [I, 4]])),
+    (r"\begin{pmatrix}\imaginaryunit & 1+\imaginaryunit \\-\imaginaryunit & 4\end{pmatrix}^H",
+     Matrix([[-I, I], [1-I, 4]])),
+    (r"\trace(\begin{pmatrix}\imaginaryunit & 1+\imaginaryunit \\-\imaginaryunit & 4\end{pmatrix})",
+     Trace(Matrix([[I, 1+I], [-I, 4]]))),
+    (r"\adjugate(\begin{pmatrix}1 & 2 \\3 & 4\end{pmatrix})",
+     Matrix([[4, -2], [-3, 1]])),
+    (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^\ast",
+     Matrix([[-2*I, 6], [4, 8]])),
+    (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{\ast}",
+     Matrix([[-2*I, 6], [4, 8]])),
+    (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{\ast\ast}",
+     Matrix([[2*I, 4], [6, 8]])),
+    (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{\ast\ast\ast}",
+     Matrix([[-2*I, 6], [4, 8]])),
+    (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{*}",
+     Matrix([[-2*I, 6], [4, 8]])),
+    (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{**}",
+     Matrix([[2*I, 4], [6, 8]])),
+    (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{***}",
+     Matrix([[-2*I, 6], [4, 8]])),
+    (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^\prime",
+     Transpose(_MatAdd(Matrix([[I, 2], [3, 4]]),
+                       Matrix([[I, 2], [3, 4]])))),
+    (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{\prime}",
+     Transpose(_MatAdd(Matrix([[I, 2], [3, 4]]),
+                       Matrix([[I, 2], [3, 4]])))),
+    (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{\prime\prime}",
+     _MatAdd(Matrix([[I, 2], [3, 4]]),
+             Matrix([[I, 2], [3, 4]]))),
+    (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{\prime\prime\prime}",
+     Transpose(_MatAdd(Matrix([[I, 2], [3, 4]]),
+                       Matrix([[I, 2], [3, 4]])))),
+    (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{'}",
+     Transpose(_MatAdd(Matrix([[I, 2], [3, 4]]),
+                       Matrix([[I, 2], [3, 4]])))),
+    (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{''}",
+     _MatAdd(Matrix([[I, 2], [3, 4]]),
+             Matrix([[I, 2], [3, 4]]))),
+    (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^{'''}",
+     Transpose(_MatAdd(Matrix([[I, 2], [3, 4]]),
+                       Matrix([[I, 2], [3, 4]])))),
+    (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})'",
+     Transpose(_MatAdd(Matrix([[I, 2], [3, 4]]),
+                       Matrix([[I, 2], [3, 4]])))),
+    (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})''",
+     _MatAdd(Matrix([[I, 2], [3, 4]]),
+             Matrix([[I, 2], [3, 4]]))),
+    (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})'''",
+     Transpose(_MatAdd(Matrix([[I, 2], [3, 4]]),
+                       Matrix([[I, 2], [3, 4]])))),
+    (r"\det(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})",
+     (_MatAdd(Matrix([[I, 2], [3, 4]]),
+              Matrix([[I, 2], [3, 4]]))).det()),
+    (r"\trace(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})",
+     Trace(_MatAdd(Matrix([[I, 2], [3, 4]]),
+                   Matrix([[I, 2], [3, 4]])))),
+    (r"\adjugate(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})",
+     (Matrix([[8, -4], [-6, 2*I]]))),
+    (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^T",
+     Transpose(_MatAdd(Matrix([[I, 2], [3, 4]]),
+                       Matrix([[I, 2], [3, 4]])))),
+    (r"(\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix}+\begin{pmatrix}\imaginaryunit&2\\3&4\end{pmatrix})^H",
+     (Matrix([[-2*I, 6], [4, 8]])))
+]
+
+
+def test_symbol_expressions():
+    expected_failures = {6, 7}
+    for i, (latex_str, sympy_expr) in enumerate(SYMBOL_EXPRESSION_PAIRS):
+        if i in expected_failures:
+            continue
+        with evaluate(False):
+            assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+
+def test_simple_expressions():
+    expected_failures = {20}
+    for i, (latex_str, sympy_expr) in enumerate(UNEVALUATED_SIMPLE_EXPRESSION_PAIRS):
+        if i in expected_failures:
+            continue
+        with evaluate(False):
+            assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+    for i, (latex_str, sympy_expr) in enumerate(EVALUATED_SIMPLE_EXPRESSION_PAIRS):
+        if i in expected_failures:
+            continue
+        assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+
+def test_fraction_expressions():
+    for latex_str, sympy_expr in UNEVALUATED_FRACTION_EXPRESSION_PAIRS:
+        with evaluate(False):
+            assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+    for latex_str, sympy_expr in EVALUATED_FRACTION_EXPRESSION_PAIRS:
+        assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+
+def test_relation_expressions():
+    for latex_str, sympy_expr in RELATION_EXPRESSION_PAIRS:
+        with evaluate(False):
+            assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+def test_power_expressions():
+    expected_failures = {3}
+    for i, (latex_str, sympy_expr) in enumerate(UNEVALUATED_POWER_EXPRESSION_PAIRS):
+        if i in expected_failures:
+            continue
+        with evaluate(False):
+            assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+    for i, (latex_str, sympy_expr) in enumerate(EVALUATED_POWER_EXPRESSION_PAIRS):
+        if i in expected_failures:
+            continue
+        assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+
+def test_integral_expressions():
+    expected_failures = {14}
+    for i, (latex_str, sympy_expr) in enumerate(UNEVALUATED_INTEGRAL_EXPRESSION_PAIRS):
+        if i in expected_failures:
+            continue
+        with evaluate(False):
+            assert parse_latex_lark(latex_str) == sympy_expr, i
+
+    for i, (latex_str, sympy_expr) in enumerate(EVALUATED_INTEGRAL_EXPRESSION_PAIRS):
+        if i in expected_failures:
+            continue
+        assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+
+def test_derivative_expressions():
+    expected_failures = {3, 4}
+    for i, (latex_str, sympy_expr) in enumerate(DERIVATIVE_EXPRESSION_PAIRS):
+        if i in expected_failures:
+            continue
+        with evaluate(False):
+            assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+    for i, (latex_str, sympy_expr) in enumerate(DERIVATIVE_EXPRESSION_PAIRS):
+        if i in expected_failures:
+            continue
+        assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+
+def test_trigonometric_expressions():
+    expected_failures = {3}
+    for i, (latex_str, sympy_expr) in enumerate(TRIGONOMETRIC_EXPRESSION_PAIRS):
+        if i in expected_failures:
+            continue
+        with evaluate(False):
+            assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+
+def test_limit_expressions():
+    for latex_str, sympy_expr in UNEVALUATED_LIMIT_EXPRESSION_PAIRS:
+        with evaluate(False):
+            assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+
+def test_square_root_expressions():
+    for latex_str, sympy_expr in UNEVALUATED_SQRT_EXPRESSION_PAIRS:
+        with evaluate(False):
+            assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+    for latex_str, sympy_expr in EVALUATED_SQRT_EXPRESSION_PAIRS:
+        assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+
+def test_factorial_expressions():
+    for latex_str, sympy_expr in UNEVALUATED_FACTORIAL_EXPRESSION_PAIRS:
+        with evaluate(False):
+            assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+    for latex_str, sympy_expr in EVALUATED_FACTORIAL_EXPRESSION_PAIRS:
+        assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+
+def test_sum_expressions():
+    for latex_str, sympy_expr in UNEVALUATED_SUM_EXPRESSION_PAIRS:
+        with evaluate(False):
+            assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+    for latex_str, sympy_expr in EVALUATED_SUM_EXPRESSION_PAIRS:
+        assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+
+def test_product_expressions():
+    for latex_str, sympy_expr in UNEVALUATED_PRODUCT_EXPRESSION_PAIRS:
+        with evaluate(False):
+            assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+@XFAIL
+def test_applied_function_expressions():
+    expected_failures = {0, 3, 4}  # 0 is ambiguous, and the others require not-yet-added features
+    # not sure why 1, and 2 are failing
+    for i, (latex_str, sympy_expr) in enumerate(APPLIED_FUNCTION_EXPRESSION_PAIRS):
+        if i in expected_failures:
+            continue
+        with evaluate(False):
+            assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+
+def test_common_function_expressions():
+    for latex_str, sympy_expr in UNEVALUATED_COMMON_FUNCTION_EXPRESSION_PAIRS:
+        with evaluate(False):
+            assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+    for latex_str, sympy_expr in EVALUATED_COMMON_FUNCTION_EXPRESSION_PAIRS:
+        assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+
+# unhandled bug causing these to fail
+@XFAIL
+def test_spacing():
+    for latex_str, sympy_expr in SPACING_RELATED_EXPRESSION_PAIRS:
+        with evaluate(False):
+            assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+
+def test_binomial_expressions():
+    for latex_str, sympy_expr in UNEVALUATED_BINOMIAL_EXPRESSION_PAIRS:
+        with evaluate(False):
+            assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+    for latex_str, sympy_expr in EVALUATED_BINOMIAL_EXPRESSION_PAIRS:
+        assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+
+def test_miscellaneous_expressions():
+    for latex_str, sympy_expr in MISCELLANEOUS_EXPRESSION_PAIRS:
+        with evaluate(False):
+            assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+
+def test_literal_complex_number_expressions():
+    for latex_str, sympy_expr in UNEVALUATED_LITERAL_COMPLEX_NUMBER_EXPRESSION_PAIRS:
+        with evaluate(False):
+            assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+
+def test_matrix_expressions():
+    for latex_str, sympy_expr in UNEVALUATED_MATRIX_EXPRESSION_PAIRS:
+        with evaluate(False):
+            assert parse_latex_lark(latex_str) == sympy_expr, latex_str
+
+    for latex_str, sympy_expr in EVALUATED_MATRIX_EXPRESSION_PAIRS:
+        assert parse_latex_lark(latex_str) == sympy_expr, latex_str
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_mathematica.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_mathematica.py
new file mode 100644
index 0000000000000000000000000000000000000000..df193b6d61f9c82778d8e0a40b893cbe6cb8f06a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_mathematica.py
@@ -0,0 +1,280 @@
+from sympy import sin, Function, symbols, Dummy, Lambda, cos
+from sympy.parsing.mathematica import parse_mathematica, MathematicaParser
+from sympy.core.sympify import sympify
+from sympy.abc import n, w, x, y, z
+from sympy.testing.pytest import raises
+
+
+def test_mathematica():
+    d = {
+        '- 6x': '-6*x',
+        'Sin[x]^2': 'sin(x)**2',
+        '2(x-1)': '2*(x-1)',
+        '3y+8': '3*y+8',
+        'ArcSin[2x+9(4-x)^2]/x': 'asin(2*x+9*(4-x)**2)/x',
+        'x+y': 'x+y',
+        '355/113': '355/113',
+        '2.718281828': '2.718281828',
+        'Cos(1/2 * π)': 'Cos(π/2)',
+        'Sin[12]': 'sin(12)',
+        'Exp[Log[4]]': 'exp(log(4))',
+        '(x+1)(x+3)': '(x+1)*(x+3)',
+        'Cos[ArcCos[3.6]]': 'cos(acos(3.6))',
+        'Cos[x]==Sin[y]': 'Eq(cos(x), sin(y))',
+        '2*Sin[x+y]': '2*sin(x+y)',
+        'Sin[x]+Cos[y]': 'sin(x)+cos(y)',
+        'Sin[Cos[x]]': 'sin(cos(x))',
+        '2*Sqrt[x+y]': '2*sqrt(x+y)',   # Test case from the issue 4259
+        '+Sqrt[2]': 'sqrt(2)',
+        '-Sqrt[2]': '-sqrt(2)',
+        '-1/Sqrt[2]': '-1/sqrt(2)',
+        '-(1/Sqrt[3])': '-(1/sqrt(3))',
+        '1/(2*Sqrt[5])': '1/(2*sqrt(5))',
+        'Mod[5,3]': 'Mod(5,3)',
+        '-Mod[5,3]': '-Mod(5,3)',
+        '(x+1)y': '(x+1)*y',
+        'x(y+1)': 'x*(y+1)',
+        'Sin[x]Cos[y]': 'sin(x)*cos(y)',
+        'Sin[x]^2Cos[y]^2': 'sin(x)**2*cos(y)**2',
+        'Cos[x]^2(1 - Cos[y]^2)': 'cos(x)**2*(1-cos(y)**2)',
+        'x y': 'x*y',
+        'x  y': 'x*y',
+        '2 x': '2*x',
+        'x 8': 'x*8',
+        '2 8': '2*8',
+        '4.x': '4.*x',
+        '4. 3': '4.*3',
+        '4. 3.': '4.*3.',
+        '1 2 3': '1*2*3',
+        ' -  2 *  Sqrt[  2 3 *   ( 1   +  5 ) ]  ': '-2*sqrt(2*3*(1+5))',
+        'Log[2,4]': 'log(4,2)',
+        'Log[Log[2,4],4]': 'log(4,log(4,2))',
+        'Exp[Sqrt[2]^2Log[2, 8]]': 'exp(sqrt(2)**2*log(8,2))',
+        'ArcSin[Cos[0]]': 'asin(cos(0))',
+        'Log2[16]': 'log(16,2)',
+        'Max[1,-2,3,-4]': 'Max(1,-2,3,-4)',
+        'Min[1,-2,3]': 'Min(1,-2,3)',
+        'Exp[I Pi/2]': 'exp(I*pi/2)',
+        'ArcTan[x,y]': 'atan2(y,x)',
+        'Pochhammer[x,y]': 'rf(x,y)',
+        'ExpIntegralEi[x]': 'Ei(x)',
+        'SinIntegral[x]': 'Si(x)',
+        'CosIntegral[x]': 'Ci(x)',
+        'AiryAi[x]': 'airyai(x)',
+        'AiryAiPrime[5]': 'airyaiprime(5)',
+        'AiryBi[x]': 'airybi(x)',
+        'AiryBiPrime[7]': 'airybiprime(7)',
+        'LogIntegral[4]': ' li(4)',
+        'PrimePi[7]': 'primepi(7)',
+        'Prime[5]': 'prime(5)',
+        'PrimeQ[5]': 'isprime(5)',
+        'Rational[2,19]': 'Rational(2,19)',    # test case for issue 25716
+        }
+
+    for e in d:
+        assert parse_mathematica(e) == sympify(d[e])
+
+    # The parsed form of this expression should not evaluate the Lambda object:
+    assert parse_mathematica("Sin[#]^2 + Cos[#]^2 &[x]") == sin(x)**2 + cos(x)**2
+
+    d1, d2, d3 = symbols("d1:4", cls=Dummy)
+    assert parse_mathematica("Sin[#] + Cos[#3] &").dummy_eq(Lambda((d1, d2, d3), sin(d1) + cos(d3)))
+    assert parse_mathematica("Sin[#^2] &").dummy_eq(Lambda(d1, sin(d1**2)))
+    assert parse_mathematica("Function[x, x^3]") == Lambda(x, x**3)
+    assert parse_mathematica("Function[{x, y}, x^2 + y^2]") == Lambda((x, y), x**2 + y**2)
+
+
+def test_parser_mathematica_tokenizer():
+    parser = MathematicaParser()
+
+    chain = lambda expr: parser._from_tokens_to_fullformlist(parser._from_mathematica_to_tokens(expr))
+
+    # Basic patterns
+    assert chain("x") == "x"
+    assert chain("42") == "42"
+    assert chain(".2") == ".2"
+    assert chain("+x") == "x"
+    assert chain("-1") == "-1"
+    assert chain("- 3") == "-3"
+    assert chain("α") == "α"
+    assert chain("+Sin[x]") == ["Sin", "x"]
+    assert chain("-Sin[x]") == ["Times", "-1", ["Sin", "x"]]
+    assert chain("x(a+1)") == ["Times", "x", ["Plus", "a", "1"]]
+    assert chain("(x)") == "x"
+    assert chain("(+x)") == "x"
+    assert chain("-a") == ["Times", "-1", "a"]
+    assert chain("(-x)") == ["Times", "-1", "x"]
+    assert chain("(x + y)") == ["Plus", "x", "y"]
+    assert chain("3 + 4") == ["Plus", "3", "4"]
+    assert chain("a - 3") == ["Plus", "a", "-3"]
+    assert chain("a - b") == ["Plus", "a", ["Times", "-1", "b"]]
+    assert chain("7 * 8") == ["Times", "7", "8"]
+    assert chain("a + b*c") == ["Plus", "a", ["Times", "b", "c"]]
+    assert chain("a + b* c* d + 2 * e") == ["Plus", "a", ["Times", "b", "c", "d"], ["Times", "2", "e"]]
+    assert chain("a / b") == ["Times", "a", ["Power", "b", "-1"]]
+
+    # Missing asterisk (*) patterns:
+    assert chain("x y") == ["Times", "x", "y"]
+    assert chain("3 4") == ["Times", "3", "4"]
+    assert chain("a[b] c") == ["Times", ["a", "b"], "c"]
+    assert chain("(x) (y)") == ["Times", "x", "y"]
+    assert chain("3 (a)") == ["Times", "3", "a"]
+    assert chain("(a) b") == ["Times", "a", "b"]
+    assert chain("4.2") == "4.2"
+    assert chain("4 2") == ["Times", "4", "2"]
+    assert chain("4  2") == ["Times", "4", "2"]
+    assert chain("3 . 4") == ["Dot", "3", "4"]
+    assert chain("4. 2") == ["Times", "4.", "2"]
+    assert chain("x.y") == ["Dot", "x", "y"]
+    assert chain("4.y") == ["Times", "4.", "y"]
+    assert chain("4 .y") == ["Dot", "4", "y"]
+    assert chain("x.4") == ["Times", "x", ".4"]
+    assert chain("x0.3") == ["Times", "x0", ".3"]
+    assert chain("x. 4") == ["Dot", "x", "4"]
+
+    # Comments
+    assert chain("a (* +b *) + c") == ["Plus", "a", "c"]
+    assert chain("a (* + b *) + (**)c (* +d *) + e") == ["Plus", "a", "c", "e"]
+    assert chain("""a + (*
+    + b
+    *) c + (* d
+    *) e
+    """) == ["Plus", "a", "c", "e"]
+
+    # Operators couples + and -, * and / are mutually associative:
+    # (i.e. expression gets flattened when mixing these operators)
+    assert chain("a*b/c") == ["Times", "a", "b", ["Power", "c", "-1"]]
+    assert chain("a/b*c") == ["Times", "a", ["Power", "b", "-1"], "c"]
+    assert chain("a+b-c") == ["Plus", "a", "b", ["Times", "-1", "c"]]
+    assert chain("a-b+c") == ["Plus", "a", ["Times", "-1", "b"], "c"]
+    assert chain("-a + b -c ") == ["Plus", ["Times", "-1", "a"], "b", ["Times", "-1", "c"]]
+    assert chain("a/b/c*d") == ["Times", "a", ["Power", "b", "-1"], ["Power", "c", "-1"], "d"]
+    assert chain("a/b/c") == ["Times", "a", ["Power", "b", "-1"], ["Power", "c", "-1"]]
+    assert chain("a-b-c") == ["Plus", "a", ["Times", "-1", "b"], ["Times", "-1", "c"]]
+    assert chain("1/a") == ["Times", "1", ["Power", "a", "-1"]]
+    assert chain("1/a/b") == ["Times", "1", ["Power", "a", "-1"], ["Power", "b", "-1"]]
+    assert chain("-1/a*b") == ["Times", "-1", ["Power", "a", "-1"], "b"]
+
+    # Enclosures of various kinds, i.e. ( )  [ ]  [[ ]]  { }
+    assert chain("(a + b) + c") == ["Plus", ["Plus", "a", "b"], "c"]
+    assert chain(" a + (b + c) + d ") == ["Plus", "a", ["Plus", "b", "c"], "d"]
+    assert chain("a * (b + c)") == ["Times", "a", ["Plus", "b", "c"]]
+    assert chain("a b (c d)") == ["Times", "a", "b", ["Times", "c", "d"]]
+    assert chain("{a, b, 2, c}") == ["List", "a", "b", "2", "c"]
+    assert chain("{a, {b, c}}") == ["List", "a", ["List", "b", "c"]]
+    assert chain("{{a}}") == ["List", ["List", "a"]]
+    assert chain("a[b, c]") == ["a", "b", "c"]
+    assert chain("a[[b, c]]") == ["Part", "a", "b", "c"]
+    assert chain("a[b[c]]") == ["a", ["b", "c"]]
+    assert chain("a[[b, c[[d, {e,f}]]]]") == ["Part", "a", "b", ["Part", "c", "d", ["List", "e", "f"]]]
+    assert chain("a[b[[c,d]]]") == ["a", ["Part", "b", "c", "d"]]
+    assert chain("a[[b[c]]]") == ["Part", "a", ["b", "c"]]
+    assert chain("a[[b[[c]]]]") == ["Part", "a", ["Part", "b", "c"]]
+    assert chain("a[[b[c[[d]]]]]") == ["Part", "a", ["b", ["Part", "c", "d"]]]
+    assert chain("a[b[[c[d]]]]") == ["a", ["Part", "b", ["c", "d"]]]
+    assert chain("x[[a+1, b+2, c+3]]") == ["Part", "x", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]]
+    assert chain("x[a+1, b+2, c+3]") == ["x", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]]
+    assert chain("{a+1, b+2, c+3}") == ["List", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]]
+
+    # Flat operator:
+    assert chain("a*b*c*d*e") == ["Times", "a", "b", "c", "d", "e"]
+    assert chain("a +b + c+ d+e") == ["Plus", "a", "b", "c", "d", "e"]
+
+    # Right priority operator:
+    assert chain("a^b") == ["Power", "a", "b"]
+    assert chain("a^b^c") == ["Power", "a", ["Power", "b", "c"]]
+    assert chain("a^b^c^d") == ["Power", "a", ["Power", "b", ["Power", "c", "d"]]]
+
+    # Left priority operator:
+    assert chain("a/.b") == ["ReplaceAll", "a", "b"]
+    assert chain("a/.b/.c/.d") == ["ReplaceAll", ["ReplaceAll", ["ReplaceAll", "a", "b"], "c"], "d"]
+
+    assert chain("a//b") == ["a", "b"]
+    assert chain("a//b//c") == [["a", "b"], "c"]
+    assert chain("a//b//c//d") == [[["a", "b"], "c"], "d"]
+
+    # Compound expressions
+    assert chain("a;b") == ["CompoundExpression", "a", "b"]
+    assert chain("a;") == ["CompoundExpression", "a", "Null"]
+    assert chain("a;b;") == ["CompoundExpression", "a", "b", "Null"]
+    assert chain("a[b;c]") == ["a", ["CompoundExpression", "b", "c"]]
+    assert chain("a[b,c;d,e]") == ["a", "b", ["CompoundExpression", "c", "d"], "e"]
+    assert chain("a[b,c;,d]") == ["a", "b", ["CompoundExpression", "c", "Null"], "d"]
+
+    # New lines
+    assert chain("a\nb\n") == ["CompoundExpression", "a", "b"]
+    assert chain("a\n\nb\n (c \nd)  \n") == ["CompoundExpression", "a", "b", ["Times", "c", "d"]]
+    assert chain("\na; b\nc") == ["CompoundExpression", "a", "b", "c"]
+    assert chain("a + \nb\n") == ["Plus", "a", "b"]
+    assert chain("a\nb; c; d\n e; (f \n g); h + \n i") == ["CompoundExpression", "a", "b", "c", "d", "e", ["Times", "f", "g"], ["Plus", "h", "i"]]
+    assert chain("\n{\na\nb; c; d\n e (f \n g); h + \n i\n\n}\n") == ["List", ["CompoundExpression", ["Times", "a", "b"], "c", ["Times", "d", "e", ["Times", "f", "g"]], ["Plus", "h", "i"]]]
+
+    # Patterns
+    assert chain("y_") == ["Pattern", "y", ["Blank"]]
+    assert chain("y_.") == ["Optional", ["Pattern", "y", ["Blank"]]]
+    assert chain("y__") == ["Pattern", "y", ["BlankSequence"]]
+    assert chain("y___") == ["Pattern", "y", ["BlankNullSequence"]]
+    assert chain("a[b_.,c_]") == ["a", ["Optional", ["Pattern", "b", ["Blank"]]], ["Pattern", "c", ["Blank"]]]
+    assert chain("b_. c") == ["Times", ["Optional", ["Pattern", "b", ["Blank"]]], "c"]
+
+    # Slots for lambda functions
+    assert chain("#") == ["Slot", "1"]
+    assert chain("#3") == ["Slot", "3"]
+    assert chain("#n") == ["Slot", "n"]
+    assert chain("##") == ["SlotSequence", "1"]
+    assert chain("##a") == ["SlotSequence", "a"]
+
+    # Lambda functions
+    assert chain("x&") == ["Function", "x"]
+    assert chain("#&") == ["Function", ["Slot", "1"]]
+    assert chain("#+3&") == ["Function", ["Plus", ["Slot", "1"], "3"]]
+    assert chain("#1 + #2&") == ["Function", ["Plus", ["Slot", "1"], ["Slot", "2"]]]
+    assert chain("# + #&") == ["Function", ["Plus", ["Slot", "1"], ["Slot", "1"]]]
+    assert chain("#&[x]") == [["Function", ["Slot", "1"]], "x"]
+    assert chain("#1 + #2 & [x, y]") == [["Function", ["Plus", ["Slot", "1"], ["Slot", "2"]]], "x", "y"]
+    assert chain("#1^2#2^3&") == ["Function", ["Times", ["Power", ["Slot", "1"], "2"], ["Power", ["Slot", "2"], "3"]]]
+
+    # Strings inside Mathematica expressions:
+    assert chain('"abc"') == ["_Str", "abc"]
+    assert chain('"a\\"b"') == ["_Str", 'a"b']
+    # This expression does not make sense mathematically, it's just testing the parser:
+    assert chain('x + "abc" ^ 3') == ["Plus", "x", ["Power", ["_Str", "abc"], "3"]]
+    assert chain('"a (* b *) c"') == ["_Str", "a (* b *) c"]
+    assert chain('"a" (* b *) ') == ["_Str", "a"]
+    assert chain('"a [ b] "') == ["_Str", "a [ b] "]
+    raises(SyntaxError, lambda: chain('"'))
+    raises(SyntaxError, lambda: chain('"\\"'))
+    raises(SyntaxError, lambda: chain('"abc'))
+    raises(SyntaxError, lambda: chain('"abc\\"def'))
+
+    # Invalid expressions:
+    raises(SyntaxError, lambda: chain("(,"))
+    raises(SyntaxError, lambda: chain("()"))
+    raises(SyntaxError, lambda: chain("a (* b"))
+
+
+def test_parser_mathematica_exp_alt():
+    parser = MathematicaParser()
+
+    convert_chain2 = lambda expr: parser._from_fullformlist_to_fullformsympy(parser._from_fullform_to_fullformlist(expr))
+    convert_chain3 = lambda expr: parser._from_fullformsympy_to_sympy(convert_chain2(expr))
+
+    Sin, Times, Plus, Power = symbols("Sin Times Plus Power", cls=Function)
+
+    full_form1 = "Sin[Times[x, y]]"
+    full_form2 = "Plus[Times[x, y], z]"
+    full_form3 = "Sin[Times[x, Plus[y, z], Power[w, n]]]]"
+    full_form4 = "Rational[Rational[x, y], z]"
+
+    assert parser._from_fullform_to_fullformlist(full_form1) == ["Sin", ["Times", "x", "y"]]
+    assert parser._from_fullform_to_fullformlist(full_form2) == ["Plus", ["Times", "x", "y"], "z"]
+    assert parser._from_fullform_to_fullformlist(full_form3) == ["Sin", ["Times", "x", ["Plus", "y", "z"], ["Power", "w", "n"]]]
+    assert parser._from_fullform_to_fullformlist(full_form4) == ["Rational", ["Rational", "x", "y"], "z"]
+
+    assert convert_chain2(full_form1) == Sin(Times(x, y))
+    assert convert_chain2(full_form2) == Plus(Times(x, y), z)
+    assert convert_chain2(full_form3) == Sin(Times(x, Plus(y, z), Power(w, n)))
+
+    assert convert_chain3(full_form1) == sin(x*y)
+    assert convert_chain3(full_form2) == x*y + z
+    assert convert_chain3(full_form3) == sin(x*(y + z)*w**n)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_maxima.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_maxima.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0bc1db8f1385ed52e8c677a1bcc759f5118d01e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_maxima.py
@@ -0,0 +1,50 @@
+from sympy.parsing.maxima import parse_maxima
+from sympy.core.numbers import (E, Rational, oo)
+from sympy.core.symbol import Symbol
+from sympy.functions.combinatorial.factorials import factorial
+from sympy.functions.elementary.complexes import Abs
+from sympy.functions.elementary.exponential import log
+from sympy.functions.elementary.trigonometric import (cos, sin)
+from sympy.abc import x
+
+n = Symbol('n', integer=True)
+
+
+def test_parser():
+    assert Abs(parse_maxima('float(1/3)') - 0.333333333) < 10**(-5)
+    assert parse_maxima('13^26') == 91733330193268616658399616009
+    assert parse_maxima('sin(%pi/2) + cos(%pi/3)') == Rational(3, 2)
+    assert parse_maxima('log(%e)') == 1
+
+
+def test_injection():
+    parse_maxima('c: x+1', globals=globals())
+    # c created by parse_maxima
+    assert c == x + 1 # noqa:F821
+
+    parse_maxima('g: sqrt(81)', globals=globals())
+    # g created by parse_maxima
+    assert g == 9 # noqa:F821
+
+
+def test_maxima_functions():
+    assert parse_maxima('expand( (x+1)^2)') == x**2 + 2*x + 1
+    assert parse_maxima('factor( x**2 + 2*x + 1)') == (x + 1)**2
+    assert parse_maxima('2*cos(x)^2 + sin(x)^2') == 2*cos(x)**2 + sin(x)**2
+    assert parse_maxima('trigexpand(sin(2*x)+cos(2*x))') == \
+        -1 + 2*cos(x)**2 + 2*cos(x)*sin(x)
+    assert parse_maxima('solve(x^2-4,x)') == [-2, 2]
+    assert parse_maxima('limit((1+1/x)^x,x,inf)') == E
+    assert parse_maxima('limit(sqrt(-x)/x,x,0,minus)') is -oo
+    assert parse_maxima('diff(x^x, x)') == x**x*(1 + log(x))
+    assert parse_maxima('sum(k, k, 1, n)', name_dict={
+        "n": Symbol('n', integer=True),
+        "k": Symbol('k', integer=True)
+    }) == (n**2 + n)/2
+    assert parse_maxima('product(k, k, 1, n)', name_dict={
+        "n": Symbol('n', integer=True),
+        "k": Symbol('k', integer=True)
+    }) == factorial(n)
+    assert parse_maxima('ratsimp((x^2-1)/(x+1))') == x - 1
+    assert Abs( parse_maxima(
+        'float(sec(%pi/3) + csc(%pi/3))') - 3.154700538379252) < 10**(-5)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_sym_expr.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_sym_expr.py
new file mode 100644
index 0000000000000000000000000000000000000000..99912805db381b96e7f41a348fe6f90d71adf781
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_sym_expr.py
@@ -0,0 +1,209 @@
+from sympy.parsing.sym_expr import SymPyExpression
+from sympy.testing.pytest import raises
+from sympy.external import import_module
+
+lfortran = import_module('lfortran')
+cin = import_module('clang.cindex', import_kwargs = {'fromlist': ['cindex']})
+
+if lfortran and cin:
+    from sympy.codegen.ast import (Variable, IntBaseType, FloatBaseType, String,
+                                   Declaration, FloatType)
+    from sympy.core import Integer, Float
+    from sympy.core.symbol import Symbol
+
+    expr1 = SymPyExpression()
+    src = """\
+    integer :: a, b, c, d
+    real :: p, q, r, s
+    """
+
+    def test_c_parse():
+        src1 = """\
+        int a, b = 4;
+        float c, d = 2.4;
+        """
+        expr1.convert_to_expr(src1, 'c')
+        ls = expr1.return_expr()
+
+        assert ls[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type=IntBaseType(String('intc'))
+            )
+        )
+        assert ls[1] == Declaration(
+            Variable(
+                Symbol('b'),
+                type=IntBaseType(String('intc')),
+                value=Integer(4)
+            )
+        )
+        assert ls[2] == Declaration(
+            Variable(
+                Symbol('c'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    )
+            )
+        )
+        assert ls[3] == Declaration(
+            Variable(
+                Symbol('d'),
+                type=FloatType(
+                    String('float32'),
+                    nbits=Integer(32),
+                    nmant=Integer(23),
+                    nexp=Integer(8)
+                    ),
+                value=Float('2.3999999999999999', precision=53)
+            )
+        )
+
+
+    def test_fortran_parse():
+        expr = SymPyExpression(src, 'f')
+        ls = expr.return_expr()
+
+        assert ls[0] == Declaration(
+            Variable(
+                Symbol('a'),
+                type=IntBaseType(String('integer')),
+                value=Integer(0)
+            )
+        )
+        assert ls[1] == Declaration(
+            Variable(
+                Symbol('b'),
+                type=IntBaseType(String('integer')),
+                value=Integer(0)
+            )
+        )
+        assert ls[2] == Declaration(
+            Variable(
+                Symbol('c'),
+                type=IntBaseType(String('integer')),
+                value=Integer(0)
+            )
+        )
+        assert ls[3] == Declaration(
+            Variable(
+                Symbol('d'),
+                type=IntBaseType(String('integer')),
+                value=Integer(0)
+            )
+        )
+        assert ls[4] == Declaration(
+            Variable(
+                Symbol('p'),
+                type=FloatBaseType(String('real')),
+                value=Float('0.0', precision=53)
+            )
+        )
+        assert ls[5] == Declaration(
+            Variable(
+                Symbol('q'),
+                type=FloatBaseType(String('real')),
+                value=Float('0.0', precision=53)
+            )
+        )
+        assert ls[6] == Declaration(
+            Variable(
+                Symbol('r'),
+                type=FloatBaseType(String('real')),
+                value=Float('0.0', precision=53)
+            )
+        )
+        assert ls[7] == Declaration(
+            Variable(
+                Symbol('s'),
+                type=FloatBaseType(String('real')),
+                value=Float('0.0', precision=53)
+            )
+        )
+
+
+    def test_convert_py():
+        src1 = (
+            src +
+            """\
+            a = b + c
+            s = p * q / r
+            """
+        )
+        expr1.convert_to_expr(src1, 'f')
+        exp_py = expr1.convert_to_python()
+        assert exp_py == [
+            'a = 0',
+            'b = 0',
+            'c = 0',
+            'd = 0',
+            'p = 0.0',
+            'q = 0.0',
+            'r = 0.0',
+            's = 0.0',
+            'a = b + c',
+            's = p*q/r'
+        ]
+
+
+    def test_convert_fort():
+        src1 = (
+            src +
+            """\
+            a = b + c
+            s = p * q / r
+            """
+        )
+        expr1.convert_to_expr(src1, 'f')
+        exp_fort = expr1.convert_to_fortran()
+        assert exp_fort == [
+            '      integer*4 a',
+            '      integer*4 b',
+            '      integer*4 c',
+            '      integer*4 d',
+            '      real*8 p',
+            '      real*8 q',
+            '      real*8 r',
+            '      real*8 s',
+            '      a = b + c',
+            '      s = p*q/r'
+        ]
+
+
+    def test_convert_c():
+        src1 = (
+            src +
+            """\
+            a = b + c
+            s = p * q / r
+            """
+        )
+        expr1.convert_to_expr(src1, 'f')
+        exp_c = expr1.convert_to_c()
+        assert exp_c == [
+            'int a = 0',
+            'int b = 0',
+            'int c = 0',
+            'int d = 0',
+            'double p = 0.0',
+            'double q = 0.0',
+            'double r = 0.0',
+            'double s = 0.0',
+            'a = b + c;',
+            's = p*q/r;'
+        ]
+
+
+    def test_exceptions():
+        src = 'int a;'
+        raises(ValueError, lambda: SymPyExpression(src))
+        raises(ValueError, lambda: SymPyExpression(mode = 'c'))
+        raises(NotImplementedError, lambda: SymPyExpression(src, mode = 'd'))
+
+elif not lfortran and not cin:
+    def test_raise():
+        raises(ImportError, lambda: SymPyExpression('int a;', 'c'))
+        raises(ImportError, lambda: SymPyExpression('integer :: a', 'f'))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_sympy_parser.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_sympy_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..43ecccbe262ffb4093248d891aa7423c8f62c628
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/parsing/tests/test_sympy_parser.py
@@ -0,0 +1,371 @@
+# -*- coding: utf-8 -*-
+
+
+import builtins
+import types
+
+from sympy.assumptions import Q
+from sympy.core import Symbol, Function, Float, Rational, Integer, I, Mul, Pow, Eq, Lt, Le, Gt, Ge, Ne
+from sympy.functions import exp, factorial, factorial2, sin, Min, Max
+from sympy.logic import And
+from sympy.series import Limit
+from sympy.testing.pytest import raises
+
+from sympy.parsing.sympy_parser import (
+    parse_expr, standard_transformations, rationalize, TokenError,
+    split_symbols, implicit_multiplication, convert_equals_signs,
+    convert_xor, function_exponentiation, lambda_notation, auto_symbol,
+    repeated_decimals, implicit_multiplication_application,
+    auto_number, factorial_notation, implicit_application,
+    _transformation, T
+    )
+
+
+def test_sympy_parser():
+    x = Symbol('x')
+    inputs = {
+        '2*x': 2 * x,
+        '3.00': Float(3),
+        '22/7': Rational(22, 7),
+        '2+3j': 2 + 3*I,
+        'exp(x)': exp(x),
+        'x!': factorial(x),
+        'x!!': factorial2(x),
+        '(x + 1)! - 1': factorial(x + 1) - 1,
+        '3.[3]': Rational(10, 3),
+        '.0[3]': Rational(1, 30),
+        '3.2[3]': Rational(97, 30),
+        '1.3[12]': Rational(433, 330),
+        '1 + 3.[3]': Rational(13, 3),
+        '1 + .0[3]': Rational(31, 30),
+        '1 + 3.2[3]': Rational(127, 30),
+        '.[0011]': Rational(1, 909),
+        '0.1[00102] + 1': Rational(366697, 333330),
+        '1.[0191]': Rational(10190, 9999),
+        '10!': 3628800,
+        '-(2)': -Integer(2),
+        '[-1, -2, 3]': [Integer(-1), Integer(-2), Integer(3)],
+        'Symbol("x").free_symbols': x.free_symbols,
+        "S('S(3).n(n=3)')": Float(3, 3),
+        'factorint(12, visual=True)': Mul(
+            Pow(2, 2, evaluate=False),
+            Pow(3, 1, evaluate=False),
+            evaluate=False),
+        'Limit(sin(x), x, 0, dir="-")': Limit(sin(x), x, 0, dir='-'),
+        'Q.even(x)': Q.even(x),
+
+
+    }
+    for text, result in inputs.items():
+        assert parse_expr(text) == result
+
+    raises(TypeError, lambda:
+        parse_expr('x', standard_transformations))
+    raises(TypeError, lambda:
+        parse_expr('x', transformations=lambda x,y: 1))
+    raises(TypeError, lambda:
+        parse_expr('x', transformations=(lambda x,y: 1,)))
+    raises(TypeError, lambda: parse_expr('x', transformations=((),)))
+    raises(TypeError, lambda: parse_expr('x', {}, [], []))
+    raises(TypeError, lambda: parse_expr('x', [], [], {}))
+    raises(TypeError, lambda: parse_expr('x', [], [], {}))
+
+
+def test_rationalize():
+    inputs = {
+        '0.123': Rational(123, 1000)
+    }
+    transformations = standard_transformations + (rationalize,)
+    for text, result in inputs.items():
+        assert parse_expr(text, transformations=transformations) == result
+
+
+def test_factorial_fail():
+    inputs = ['x!!!', 'x!!!!', '(!)']
+
+
+    for text in inputs:
+        try:
+            parse_expr(text)
+            assert False
+        except TokenError:
+            assert True
+
+
+def test_repeated_fail():
+    inputs = ['1[1]', '.1e1[1]', '0x1[1]', '1.1j[1]', '1.1[1 + 1]',
+        '0.1[[1]]', '0x1.1[1]']
+
+
+    # All are valid Python, so only raise TypeError for invalid indexing
+    for text in inputs:
+        raises(TypeError, lambda: parse_expr(text))
+
+
+    inputs = ['0.1[', '0.1[1', '0.1[]']
+    for text in inputs:
+        raises((TokenError, SyntaxError), lambda: parse_expr(text))
+
+
+def test_repeated_dot_only():
+    assert parse_expr('.[1]') == Rational(1, 9)
+    assert parse_expr('1 + .[1]') == Rational(10, 9)
+
+
+def test_local_dict():
+    local_dict = {
+        'my_function': lambda x: x + 2
+    }
+    inputs = {
+        'my_function(2)': Integer(4)
+    }
+    for text, result in inputs.items():
+        assert parse_expr(text, local_dict=local_dict) == result
+
+
+def test_local_dict_split_implmult():
+    t = standard_transformations + (split_symbols, implicit_multiplication,)
+    w = Symbol('w', real=True)
+    y = Symbol('y')
+    assert parse_expr('yx', local_dict={'x':w}, transformations=t) == y*w
+
+
+def test_local_dict_symbol_to_fcn():
+    x = Symbol('x')
+    d = {'foo': Function('bar')}
+    assert parse_expr('foo(x)', local_dict=d) == d['foo'](x)
+    d = {'foo': Symbol('baz')}
+    raises(TypeError, lambda: parse_expr('foo(x)', local_dict=d))
+
+
+def test_global_dict():
+    global_dict = {
+        'Symbol': Symbol
+    }
+    inputs = {
+        'Q & S': And(Symbol('Q'), Symbol('S'))
+    }
+    for text, result in inputs.items():
+        assert parse_expr(text, global_dict=global_dict) == result
+
+
+def test_no_globals():
+
+    # Replicate creating the default global_dict:
+    default_globals = {}
+    exec('from sympy import *', default_globals)
+    builtins_dict = vars(builtins)
+    for name, obj in builtins_dict.items():
+        if isinstance(obj, types.BuiltinFunctionType):
+            default_globals[name] = obj
+    default_globals['max'] = Max
+    default_globals['min'] = Min
+
+    # Need to include Symbol or parse_expr will not work:
+    default_globals.pop('Symbol')
+    global_dict = {'Symbol':Symbol}
+
+    for name in default_globals:
+        obj = parse_expr(name, global_dict=global_dict)
+        assert obj == Symbol(name)
+
+
+def test_issue_2515():
+    raises(TokenError, lambda: parse_expr('(()'))
+    raises(TokenError, lambda: parse_expr('"""'))
+
+
+def test_issue_7663():
+    x = Symbol('x')
+    e = '2*(x+1)'
+    assert parse_expr(e, evaluate=False) == parse_expr(e, evaluate=False)
+    assert parse_expr(e, evaluate=False).equals(2*(x+1))
+
+def test_recursive_evaluate_false_10560():
+    inputs = {
+        '4*-3' : '4*-3',
+        '-4*3' : '(-4)*3',
+        "-2*x*y": '(-2)*x*y',
+        "x*-4*x": "x*(-4)*x"
+    }
+    for text, result in inputs.items():
+        assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False)
+
+
+def test_function_evaluate_false():
+    inputs = [
+        'Abs(0)', 'im(0)', 're(0)', 'sign(0)', 'arg(0)', 'conjugate(0)',
+        'acos(0)', 'acot(0)', 'acsc(0)', 'asec(0)', 'asin(0)', 'atan(0)',
+        'acosh(0)', 'acoth(0)', 'acsch(0)', 'asech(0)', 'asinh(0)', 'atanh(0)',
+        'cos(0)', 'cot(0)', 'csc(0)', 'sec(0)', 'sin(0)', 'tan(0)',
+        'cosh(0)', 'coth(0)', 'csch(0)', 'sech(0)', 'sinh(0)', 'tanh(0)',
+        'exp(0)', 'log(0)', 'sqrt(0)',
+    ]
+    for case in inputs:
+        expr = parse_expr(case, evaluate=False)
+        assert case == str(expr) != str(expr.doit())
+    assert str(parse_expr('ln(0)', evaluate=False)) == 'log(0)'
+    assert str(parse_expr('cbrt(0)', evaluate=False)) == '0**(1/3)'
+
+
+def test_issue_10773():
+    inputs = {
+    '-10/5': '(-10)/5',
+    '-10/-5' : '(-10)/(-5)',
+    }
+    for text, result in inputs.items():
+        assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False)
+
+
+def test_split_symbols():
+    transformations = standard_transformations + \
+                      (split_symbols, implicit_multiplication,)
+    x = Symbol('x')
+    y = Symbol('y')
+    xy = Symbol('xy')
+
+
+    assert parse_expr("xy") == xy
+    assert parse_expr("xy", transformations=transformations) == x*y
+
+
+def test_split_symbols_function():
+    transformations = standard_transformations + \
+                      (split_symbols, implicit_multiplication,)
+    x = Symbol('x')
+    y = Symbol('y')
+    a = Symbol('a')
+    f = Function('f')
+
+
+    assert parse_expr("ay(x+1)", transformations=transformations) == a*y*(x+1)
+    assert parse_expr("af(x+1)", transformations=transformations,
+                      local_dict={'f':f}) == a*f(x+1)
+
+
+def test_functional_exponent():
+    t = standard_transformations + (convert_xor, function_exponentiation)
+    x = Symbol('x')
+    y = Symbol('y')
+    a = Symbol('a')
+    yfcn = Function('y')
+    assert parse_expr("sin^2(x)", transformations=t) == (sin(x))**2
+    assert parse_expr("sin^y(x)", transformations=t) == (sin(x))**y
+    assert parse_expr("exp^y(x)", transformations=t) == (exp(x))**y
+    assert parse_expr("E^y(x)", transformations=t) == exp(yfcn(x))
+    assert parse_expr("a^y(x)", transformations=t) == a**(yfcn(x))
+
+
+def test_match_parentheses_implicit_multiplication():
+    transformations = standard_transformations + \
+                      (implicit_multiplication,)
+    raises(TokenError, lambda: parse_expr('(1,2),(3,4]',transformations=transformations))
+
+
+def test_convert_equals_signs():
+    transformations = standard_transformations + \
+                        (convert_equals_signs, )
+    x = Symbol('x')
+    y = Symbol('y')
+    assert parse_expr("1*2=x", transformations=transformations) == Eq(2, x)
+    assert parse_expr("y = x", transformations=transformations) == Eq(y, x)
+    assert parse_expr("(2*y = x) = False",
+        transformations=transformations) == Eq(Eq(2*y, x), False)
+
+
+def test_parse_function_issue_3539():
+    x = Symbol('x')
+    f = Function('f')
+    assert parse_expr('f(x)') == f(x)
+
+def test_issue_24288():
+    assert parse_expr("1 < 2", evaluate=False) == Lt(1, 2, evaluate=False)
+    assert parse_expr("1 <= 2", evaluate=False) == Le(1, 2, evaluate=False)
+    assert parse_expr("1 > 2", evaluate=False) == Gt(1, 2, evaluate=False)
+    assert parse_expr("1 >= 2", evaluate=False) == Ge(1, 2, evaluate=False)
+    assert parse_expr("1 != 2", evaluate=False) == Ne(1, 2, evaluate=False)
+    assert parse_expr("1 == 2", evaluate=False) == Eq(1, 2, evaluate=False)
+    assert parse_expr("1 < 2 < 3", evaluate=False) == And(Lt(1, 2, evaluate=False), Lt(2, 3, evaluate=False), evaluate=False)
+    assert parse_expr("1 <= 2 <= 3", evaluate=False) == And(Le(1, 2, evaluate=False), Le(2, 3, evaluate=False), evaluate=False)
+    assert parse_expr("1 < 2 <= 3 < 4", evaluate=False) == \
+        And(Lt(1, 2, evaluate=False), Le(2, 3, evaluate=False), Lt(3, 4, evaluate=False), evaluate=False)
+    # Valid Python relational operators that SymPy does not decide how to handle them yet
+    raises(ValueError, lambda: parse_expr("1 in 2", evaluate=False))
+    raises(ValueError, lambda: parse_expr("1 is 2", evaluate=False))
+    raises(ValueError, lambda: parse_expr("1 not in 2", evaluate=False))
+    raises(ValueError, lambda: parse_expr("1 is not 2", evaluate=False))
+
+def test_split_symbols_numeric():
+    transformations = (
+        standard_transformations +
+        (implicit_multiplication_application,))
+
+    n = Symbol('n')
+    expr1 = parse_expr('2**n * 3**n')
+    expr2 = parse_expr('2**n3**n', transformations=transformations)
+    assert expr1 == expr2 == 2**n*3**n
+
+    expr1 = parse_expr('n12n34', transformations=transformations)
+    assert expr1 == n*12*n*34
+
+
+def test_unicode_names():
+    assert parse_expr('α') == Symbol('α')
+
+
+def test_python3_features():
+    assert parse_expr("123_456") == 123456
+    assert parse_expr("1.2[3_4]") == parse_expr("1.2[34]") == Rational(611, 495)
+    assert parse_expr("1.2[012_012]") == parse_expr("1.2[012012]") == Rational(400, 333)
+    assert parse_expr('.[3_4]') == parse_expr('.[34]') == Rational(34, 99)
+    assert parse_expr('.1[3_4]') == parse_expr('.1[34]') == Rational(133, 990)
+    assert parse_expr('123_123.123_123[3_4]') == parse_expr('123123.123123[34]') == Rational(12189189189211, 99000000)
+
+
+def test_issue_19501():
+    x = Symbol('x')
+    eq = parse_expr('E**x(1+x)', local_dict={'x': x}, transformations=(
+        standard_transformations +
+        (implicit_multiplication_application,)))
+    assert eq.free_symbols == {x}
+
+
+def test_parsing_definitions():
+    from sympy.abc import x
+    assert len(_transformation) == 12  # if this changes, extend below
+    assert _transformation[0] == lambda_notation
+    assert _transformation[1] == auto_symbol
+    assert _transformation[2] == repeated_decimals
+    assert _transformation[3] == auto_number
+    assert _transformation[4] == factorial_notation
+    assert _transformation[5] == implicit_multiplication_application
+    assert _transformation[6] == convert_xor
+    assert _transformation[7] == implicit_application
+    assert _transformation[8] == implicit_multiplication
+    assert _transformation[9] == convert_equals_signs
+    assert _transformation[10] == function_exponentiation
+    assert _transformation[11] == rationalize
+    assert T[:5] == T[0,1,2,3,4] == standard_transformations
+    t = _transformation
+    assert T[-1, 0] == (t[len(t) - 1], t[0])
+    assert T[:5, 8] == standard_transformations + (t[8],)
+    assert parse_expr('0.3x^2', transformations='all') == 3*x**2/10
+    assert parse_expr('sin 3x', transformations='implicit') == sin(3*x)
+
+
+def test_builtins():
+    cases = [
+        ('abs(x)', 'Abs(x)'),
+        ('max(x, y)', 'Max(x, y)'),
+        ('min(x, y)', 'Min(x, y)'),
+        ('pow(x, y)', 'Pow(x, y)'),
+    ]
+    for built_in_func_call, sympy_func_call in cases:
+        assert parse_expr(built_in_func_call) == parse_expr(sympy_func_call)
+    assert str(parse_expr('pow(38, -1, 97)')) == '23'
+
+
+def test_issue_22822():
+    raises(ValueError, lambda: parse_expr('x', {'': 1}))
+    data = {'some_parameter': None}
+    assert parse_expr('some_parameter is None', data) is True
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/hydrogen.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/hydrogen.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3bac274c66a2cf97d4238d9e3951e39df820931
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/hydrogen.py
@@ -0,0 +1,265 @@
+from sympy.core.numbers import Float
+from sympy.core.singleton import S
+from sympy.functions.combinatorial.factorials import factorial
+from sympy.functions.elementary.exponential import exp
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.special.polynomials import assoc_laguerre
+from sympy.functions.special.spherical_harmonics import Ynm
+
+
+def R_nl(n, l, r, Z=1):
+    """
+    Returns the Hydrogen radial wavefunction R_{nl}.
+
+    Parameters
+    ==========
+
+    n : integer
+        Principal Quantum Number which is
+        an integer with possible values as 1, 2, 3, 4,...
+    l : integer
+        ``l`` is the Angular Momentum Quantum Number with
+        values ranging from 0 to ``n-1``.
+    r :
+        Radial coordinate.
+    Z :
+        Atomic number (1 for Hydrogen, 2 for Helium, ...)
+
+    Everything is in Hartree atomic units.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.hydrogen import R_nl
+    >>> from sympy.abc import r, Z
+    >>> R_nl(1, 0, r, Z)
+    2*sqrt(Z**3)*exp(-Z*r)
+    >>> R_nl(2, 0, r, Z)
+    sqrt(2)*(-Z*r + 2)*sqrt(Z**3)*exp(-Z*r/2)/4
+    >>> R_nl(2, 1, r, Z)
+    sqrt(6)*Z*r*sqrt(Z**3)*exp(-Z*r/2)/12
+
+    For Hydrogen atom, you can just use the default value of Z=1:
+
+    >>> R_nl(1, 0, r)
+    2*exp(-r)
+    >>> R_nl(2, 0, r)
+    sqrt(2)*(2 - r)*exp(-r/2)/4
+    >>> R_nl(3, 0, r)
+    2*sqrt(3)*(2*r**2/9 - 2*r + 3)*exp(-r/3)/27
+
+    For Silver atom, you would use Z=47:
+
+    >>> R_nl(1, 0, r, Z=47)
+    94*sqrt(47)*exp(-47*r)
+    >>> R_nl(2, 0, r, Z=47)
+    47*sqrt(94)*(2 - 47*r)*exp(-47*r/2)/4
+    >>> R_nl(3, 0, r, Z=47)
+    94*sqrt(141)*(4418*r**2/9 - 94*r + 3)*exp(-47*r/3)/27
+
+    The normalization of the radial wavefunction is:
+
+    >>> from sympy import integrate, oo
+    >>> integrate(R_nl(1, 0, r)**2 * r**2, (r, 0, oo))
+    1
+    >>> integrate(R_nl(2, 0, r)**2 * r**2, (r, 0, oo))
+    1
+    >>> integrate(R_nl(2, 1, r)**2 * r**2, (r, 0, oo))
+    1
+
+    It holds for any atomic number:
+
+    >>> integrate(R_nl(1, 0, r, Z=2)**2 * r**2, (r, 0, oo))
+    1
+    >>> integrate(R_nl(2, 0, r, Z=3)**2 * r**2, (r, 0, oo))
+    1
+    >>> integrate(R_nl(2, 1, r, Z=4)**2 * r**2, (r, 0, oo))
+    1
+
+    """
+    # sympify arguments
+    n, l, r, Z = map(S, [n, l, r, Z])
+    # radial quantum number
+    n_r = n - l - 1
+    # rescaled "r"
+    a = 1/Z  # Bohr radius
+    r0 = 2 * r / (n * a)
+    # normalization coefficient
+    C = sqrt((S(2)/(n*a))**3 * factorial(n_r) / (2*n*factorial(n + l)))
+    # This is an equivalent normalization coefficient, that can be found in
+    # some books. Both coefficients seem to be the same fast:
+    # C =  S(2)/n**2 * sqrt(1/a**3 * factorial(n_r) / (factorial(n+l)))
+    return C * r0**l * assoc_laguerre(n_r, 2*l + 1, r0).expand() * exp(-r0/2)
+
+
+def Psi_nlm(n, l, m, r, phi, theta, Z=1):
+    """
+    Returns the Hydrogen wave function psi_{nlm}. It's the product of
+    the radial wavefunction R_{nl} and the spherical harmonic Y_{l}^{m}.
+
+    Parameters
+    ==========
+
+    n : integer
+        Principal Quantum Number which is
+        an integer with possible values as 1, 2, 3, 4,...
+    l : integer
+        ``l`` is the Angular Momentum Quantum Number with
+        values ranging from 0 to ``n-1``.
+    m : integer
+        ``m`` is the Magnetic Quantum Number with values
+        ranging from ``-l`` to ``l``.
+    r :
+        radial coordinate
+    phi :
+        azimuthal angle
+    theta :
+        polar angle
+    Z :
+        atomic number (1 for Hydrogen, 2 for Helium, ...)
+
+    Everything is in Hartree atomic units.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.hydrogen import Psi_nlm
+    >>> from sympy import Symbol
+    >>> r=Symbol("r", positive=True)
+    >>> phi=Symbol("phi", real=True)
+    >>> theta=Symbol("theta", real=True)
+    >>> Z=Symbol("Z", positive=True, integer=True, nonzero=True)
+    >>> Psi_nlm(1,0,0,r,phi,theta,Z)
+    Z**(3/2)*exp(-Z*r)/sqrt(pi)
+    >>> Psi_nlm(2,1,1,r,phi,theta,Z)
+    -Z**(5/2)*r*exp(I*phi)*exp(-Z*r/2)*sin(theta)/(8*sqrt(pi))
+
+    Integrating the absolute square of a hydrogen wavefunction psi_{nlm}
+    over the whole space leads 1.
+
+    The normalization of the hydrogen wavefunctions Psi_nlm is:
+
+    >>> from sympy import integrate, conjugate, pi, oo, sin
+    >>> wf=Psi_nlm(2,1,1,r,phi,theta,Z)
+    >>> abs_sqrd=wf*conjugate(wf)
+    >>> jacobi=r**2*sin(theta)
+    >>> integrate(abs_sqrd*jacobi, (r,0,oo), (phi,0,2*pi), (theta,0,pi))
+    1
+    """
+
+    # sympify arguments
+    n, l, m, r, phi, theta, Z = map(S, [n, l, m, r, phi, theta, Z])
+    # check if values for n,l,m make physically sense
+    if n.is_integer and n < 1:
+        raise ValueError("'n' must be positive integer")
+    if l.is_integer and not (n > l):
+        raise ValueError("'n' must be greater than 'l'")
+    if m.is_integer and not (abs(m) <= l):
+        raise ValueError("|'m'| must be less or equal 'l'")
+    # return the hydrogen wave function
+    return R_nl(n, l, r, Z)*Ynm(l, m, theta, phi).expand(func=True)
+
+
+def E_nl(n, Z=1):
+    """
+    Returns the energy of the state (n, l) in Hartree atomic units.
+
+    The energy does not depend on "l".
+
+    Parameters
+    ==========
+
+    n : integer
+        Principal Quantum Number which is
+        an integer with possible values as 1, 2, 3, 4,...
+    Z :
+        Atomic number (1 for Hydrogen, 2 for Helium, ...)
+
+    Examples
+    ========
+
+    >>> from sympy.physics.hydrogen import E_nl
+    >>> from sympy.abc import n, Z
+    >>> E_nl(n, Z)
+    -Z**2/(2*n**2)
+    >>> E_nl(1)
+    -1/2
+    >>> E_nl(2)
+    -1/8
+    >>> E_nl(3)
+    -1/18
+    >>> E_nl(3, 47)
+    -2209/18
+
+    """
+    n, Z = S(n), S(Z)
+    if n.is_integer and (n < 1):
+        raise ValueError("'n' must be positive integer")
+    return -Z**2/(2*n**2)
+
+
+def E_nl_dirac(n, l, spin_up=True, Z=1, c=Float("137.035999037")):
+    """
+    Returns the relativistic energy of the state (n, l, spin) in Hartree atomic
+    units.
+
+    The energy is calculated from the Dirac equation. The rest mass energy is
+    *not* included.
+
+    Parameters
+    ==========
+
+    n : integer
+        Principal Quantum Number which is
+        an integer with possible values as 1, 2, 3, 4,...
+    l : integer
+        ``l`` is the Angular Momentum Quantum Number with
+        values ranging from 0 to ``n-1``.
+    spin_up :
+        True if the electron spin is up (default), otherwise down
+    Z :
+        Atomic number (1 for Hydrogen, 2 for Helium, ...)
+    c :
+        Speed of light in atomic units. Default value is 137.035999037,
+        taken from https://arxiv.org/abs/1012.3627
+
+    Examples
+    ========
+
+    >>> from sympy.physics.hydrogen import E_nl_dirac
+    >>> E_nl_dirac(1, 0)
+    -0.500006656595360
+
+    >>> E_nl_dirac(2, 0)
+    -0.125002080189006
+    >>> E_nl_dirac(2, 1)
+    -0.125000416028342
+    >>> E_nl_dirac(2, 1, False)
+    -0.125002080189006
+
+    >>> E_nl_dirac(3, 0)
+    -0.0555562951740285
+    >>> E_nl_dirac(3, 1)
+    -0.0555558020932949
+    >>> E_nl_dirac(3, 1, False)
+    -0.0555562951740285
+    >>> E_nl_dirac(3, 2)
+    -0.0555556377366884
+    >>> E_nl_dirac(3, 2, False)
+    -0.0555558020932949
+
+    """
+    n, l, Z, c = map(S, [n, l, Z, c])
+    if not (l >= 0):
+        raise ValueError("'l' must be positive or zero")
+    if not (n > l):
+        raise ValueError("'n' must be greater than 'l'")
+    if (l == 0 and spin_up is False):
+        raise ValueError("Spin must be up for l==0.")
+    # skappa is sign*kappa, where sign contains the correct sign
+    if spin_up:
+        skappa = -l - 1
+    else:
+        skappa = -l
+    beta = sqrt(skappa**2 - Z**2/c**2)
+    return c**2/sqrt(1 + Z**2/(n + skappa + beta)**2/c**2) - c**2
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/matrices.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/matrices.py
new file mode 100644
index 0000000000000000000000000000000000000000..d91466220d63956053b91bd76b948ee677e7c191
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/matrices.py
@@ -0,0 +1,176 @@
+"""Known matrices related to physics"""
+
+from sympy.core.numbers import I
+from sympy.matrices.dense import MutableDenseMatrix as Matrix
+from sympy.utilities.decorator import deprecated
+
+
+def msigma(i):
+    r"""Returns a Pauli matrix `\sigma_i` with `i=1,2,3`.
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Pauli_matrices
+
+    Examples
+    ========
+
+    >>> from sympy.physics.matrices import msigma
+    >>> msigma(1)
+    Matrix([
+    [0, 1],
+    [1, 0]])
+    """
+    if i == 1:
+        mat = (
+            (0, 1),
+            (1, 0)
+        )
+    elif i == 2:
+        mat = (
+            (0, -I),
+            (I, 0)
+        )
+    elif i == 3:
+        mat = (
+            (1, 0),
+            (0, -1)
+        )
+    else:
+        raise IndexError("Invalid Pauli index")
+    return Matrix(mat)
+
+
+def pat_matrix(m, dx, dy, dz):
+    """Returns the Parallel Axis Theorem matrix to translate the inertia
+    matrix a distance of `(dx, dy, dz)` for a body of mass m.
+
+    Examples
+    ========
+
+    To translate a body having a mass of 2 units a distance of 1 unit along
+    the `x`-axis we get:
+
+    >>> from sympy.physics.matrices import pat_matrix
+    >>> pat_matrix(2, 1, 0, 0)
+    Matrix([
+    [0, 0, 0],
+    [0, 2, 0],
+    [0, 0, 2]])
+
+    """
+    dxdy = -dx*dy
+    dydz = -dy*dz
+    dzdx = -dz*dx
+    dxdx = dx**2
+    dydy = dy**2
+    dzdz = dz**2
+    mat = ((dydy + dzdz, dxdy, dzdx),
+           (dxdy, dxdx + dzdz, dydz),
+           (dzdx, dydz, dydy + dxdx))
+    return m*Matrix(mat)
+
+
+def mgamma(mu, lower=False):
+    r"""Returns a Dirac gamma matrix `\gamma^\mu` in the standard
+    (Dirac) representation.
+
+    Explanation
+    ===========
+
+    If you want `\gamma_\mu`, use ``gamma(mu, True)``.
+
+    We use a convention:
+
+    `\gamma^5 = i \cdot \gamma^0 \cdot \gamma^1 \cdot \gamma^2 \cdot \gamma^3`
+
+    `\gamma_5 = i \cdot \gamma_0 \cdot \gamma_1 \cdot \gamma_2 \cdot \gamma_3 = - \gamma^5`
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Gamma_matrices
+
+    Examples
+    ========
+
+    >>> from sympy.physics.matrices import mgamma
+    >>> mgamma(1)
+    Matrix([
+    [ 0,  0, 0, 1],
+    [ 0,  0, 1, 0],
+    [ 0, -1, 0, 0],
+    [-1,  0, 0, 0]])
+    """
+    if mu not in (0, 1, 2, 3, 5):
+        raise IndexError("Invalid Dirac index")
+    if mu == 0:
+        mat = (
+            (1, 0, 0, 0),
+            (0, 1, 0, 0),
+            (0, 0, -1, 0),
+            (0, 0, 0, -1)
+        )
+    elif mu == 1:
+        mat = (
+            (0, 0, 0, 1),
+            (0, 0, 1, 0),
+            (0, -1, 0, 0),
+            (-1, 0, 0, 0)
+        )
+    elif mu == 2:
+        mat = (
+            (0, 0, 0, -I),
+            (0, 0, I, 0),
+            (0, I, 0, 0),
+            (-I, 0, 0, 0)
+        )
+    elif mu == 3:
+        mat = (
+            (0, 0, 1, 0),
+            (0, 0, 0, -1),
+            (-1, 0, 0, 0),
+            (0, 1, 0, 0)
+        )
+    elif mu == 5:
+        mat = (
+            (0, 0, 1, 0),
+            (0, 0, 0, 1),
+            (1, 0, 0, 0),
+            (0, 1, 0, 0)
+        )
+    m = Matrix(mat)
+    if lower:
+        if mu in (1, 2, 3, 5):
+            m = -m
+    return m
+
+#Minkowski tensor using the convention (+,-,-,-) used in the Quantum Field
+#Theory
+minkowski_tensor = Matrix( (
+    (1, 0, 0, 0),
+    (0, -1, 0, 0),
+    (0, 0, -1, 0),
+    (0, 0, 0, -1)
+))
+
+
+@deprecated(
+    """
+    The sympy.physics.matrices.mdft method is deprecated. Use
+    sympy.DFT(n).as_explicit() instead.
+    """,
+    deprecated_since_version="1.9",
+    active_deprecations_target="deprecated-physics-mdft",
+)
+def mdft(n):
+    r"""
+    .. deprecated:: 1.9
+
+       Use DFT from sympy.matrices.expressions.fourier instead.
+
+       To get identical behavior to ``mdft(n)``, use ``DFT(n).as_explicit()``.
+    """
+    from sympy.matrices.expressions.fourier import DFT
+    return DFT(n).as_mutable()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d2d83d452fd30e718546c0eac26fe03bbef59c06
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/__init__.py
@@ -0,0 +1,38 @@
+__all__ = [
+    'TWave',
+
+    'RayTransferMatrix', 'FreeSpace', 'FlatRefraction', 'CurvedRefraction',
+    'FlatMirror', 'CurvedMirror', 'ThinLens', 'GeometricRay', 'BeamParameter',
+    'waist2rayleigh', 'rayleigh2waist', 'geometric_conj_ab',
+    'geometric_conj_af', 'geometric_conj_bf', 'gaussian_conj',
+    'conjugate_gauss_beams',
+
+    'Medium',
+
+    'refraction_angle', 'deviation', 'fresnel_coefficients', 'brewster_angle',
+    'critical_angle', 'lens_makers_formula', 'mirror_formula', 'lens_formula',
+    'hyperfocal_distance', 'transverse_magnification',
+
+    'jones_vector', 'stokes_vector', 'jones_2_stokes', 'linear_polarizer',
+    'phase_retarder', 'half_wave_retarder', 'quarter_wave_retarder',
+    'transmissive_filter', 'reflective_filter', 'mueller_matrix',
+    'polarizing_beam_splitter',
+]
+from .waves import TWave
+
+from .gaussopt import (RayTransferMatrix, FreeSpace, FlatRefraction,
+        CurvedRefraction, FlatMirror, CurvedMirror, ThinLens, GeometricRay,
+        BeamParameter, waist2rayleigh, rayleigh2waist, geometric_conj_ab,
+        geometric_conj_af, geometric_conj_bf, gaussian_conj,
+        conjugate_gauss_beams)
+
+from .medium import Medium
+
+from .utils import (refraction_angle, deviation, fresnel_coefficients,
+        brewster_angle, critical_angle, lens_makers_formula, mirror_formula,
+        lens_formula, hyperfocal_distance, transverse_magnification)
+
+from .polarization import (jones_vector, stokes_vector, jones_2_stokes,
+        linear_polarizer, phase_retarder, half_wave_retarder,
+        quarter_wave_retarder, transmissive_filter, reflective_filter,
+        mueller_matrix, polarizing_beam_splitter)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/gaussopt.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/gaussopt.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9e8ef555d60e3204341cdc65cdd05fb02b2f196
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/gaussopt.py
@@ -0,0 +1,923 @@
+"""
+Gaussian optics.
+
+The module implements:
+
+- Ray transfer matrices for geometrical and gaussian optics.
+
+  See RayTransferMatrix, GeometricRay and BeamParameter
+
+- Conjugation relations for geometrical and gaussian optics.
+
+  See geometric_conj*, gauss_conj and conjugate_gauss_beams
+
+The conventions for the distances are as follows:
+
+focal distance
+    positive for convergent lenses
+object distance
+    positive for real objects
+image distance
+    positive for real images
+"""
+
+__all__ = [
+    'RayTransferMatrix',
+    'FreeSpace',
+    'FlatRefraction',
+    'CurvedRefraction',
+    'FlatMirror',
+    'CurvedMirror',
+    'ThinLens',
+    'GeometricRay',
+    'BeamParameter',
+    'waist2rayleigh',
+    'rayleigh2waist',
+    'geometric_conj_ab',
+    'geometric_conj_af',
+    'geometric_conj_bf',
+    'gaussian_conj',
+    'conjugate_gauss_beams',
+]
+
+
+from sympy.core.expr import Expr
+from sympy.core.numbers import (I, pi)
+from sympy.core.sympify import sympify
+from sympy.functions.elementary.complexes import (im, re)
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import atan2
+from sympy.matrices.dense import Matrix, MutableDenseMatrix
+from sympy.polys.rationaltools import together
+from sympy.utilities.misc import filldedent
+
+###
+# A, B, C, D matrices
+###
+
+
+class RayTransferMatrix(MutableDenseMatrix):
+    """
+    Base class for a Ray Transfer Matrix.
+
+    It should be used if there is not already a more specific subclass mentioned
+    in See Also.
+
+    Parameters
+    ==========
+
+    parameters :
+        A, B, C and D or 2x2 matrix (Matrix(2, 2, [A, B, C, D]))
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import RayTransferMatrix, ThinLens
+    >>> from sympy import Symbol, Matrix
+
+    >>> mat = RayTransferMatrix(1, 2, 3, 4)
+    >>> mat
+    Matrix([
+    [1, 2],
+    [3, 4]])
+
+    >>> RayTransferMatrix(Matrix([[1, 2], [3, 4]]))
+    Matrix([
+    [1, 2],
+    [3, 4]])
+
+    >>> mat.A
+    1
+
+    >>> f = Symbol('f')
+    >>> lens = ThinLens(f)
+    >>> lens
+    Matrix([
+    [   1, 0],
+    [-1/f, 1]])
+
+    >>> lens.C
+    -1/f
+
+    See Also
+    ========
+
+    GeometricRay, BeamParameter,
+    FreeSpace, FlatRefraction, CurvedRefraction,
+    FlatMirror, CurvedMirror, ThinLens
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Ray_transfer_matrix_analysis
+    """
+
+    def __new__(cls, *args):
+
+        if len(args) == 4:
+            temp = ((args[0], args[1]), (args[2], args[3]))
+        elif len(args) == 1 \
+            and isinstance(args[0], Matrix) \
+                and args[0].shape == (2, 2):
+            temp = args[0]
+        else:
+            raise ValueError(filldedent('''
+                Expecting 2x2 Matrix or the 4 elements of
+                the Matrix but got %s''' % str(args)))
+        return Matrix.__new__(cls, temp)
+
+    def __mul__(self, other):
+        if isinstance(other, RayTransferMatrix):
+            return RayTransferMatrix(Matrix(self)*Matrix(other))
+        elif isinstance(other, GeometricRay):
+            return GeometricRay(Matrix(self)*Matrix(other))
+        elif isinstance(other, BeamParameter):
+            temp = Matrix(self)*Matrix(((other.q,), (1,)))
+            q = (temp[0]/temp[1]).expand(complex=True)
+            return BeamParameter(other.wavelen,
+                                 together(re(q)),
+                                 z_r=together(im(q)))
+        else:
+            return Matrix.__mul__(self, other)
+
+    @property
+    def A(self):
+        """
+        The A parameter of the Matrix.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.optics import RayTransferMatrix
+        >>> mat = RayTransferMatrix(1, 2, 3, 4)
+        >>> mat.A
+        1
+        """
+        return self[0, 0]
+
+    @property
+    def B(self):
+        """
+        The B parameter of the Matrix.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.optics import RayTransferMatrix
+        >>> mat = RayTransferMatrix(1, 2, 3, 4)
+        >>> mat.B
+        2
+        """
+        return self[0, 1]
+
+    @property
+    def C(self):
+        """
+        The C parameter of the Matrix.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.optics import RayTransferMatrix
+        >>> mat = RayTransferMatrix(1, 2, 3, 4)
+        >>> mat.C
+        3
+        """
+        return self[1, 0]
+
+    @property
+    def D(self):
+        """
+        The D parameter of the Matrix.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.optics import RayTransferMatrix
+        >>> mat = RayTransferMatrix(1, 2, 3, 4)
+        >>> mat.D
+        4
+        """
+        return self[1, 1]
+
+
+class FreeSpace(RayTransferMatrix):
+    """
+    Ray Transfer Matrix for free space.
+
+    Parameters
+    ==========
+
+    distance
+
+    See Also
+    ========
+
+    RayTransferMatrix
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import FreeSpace
+    >>> from sympy import symbols
+    >>> d = symbols('d')
+    >>> FreeSpace(d)
+    Matrix([
+    [1, d],
+    [0, 1]])
+    """
+    def __new__(cls, d):
+        return RayTransferMatrix.__new__(cls, 1, d, 0, 1)
+
+
+class FlatRefraction(RayTransferMatrix):
+    """
+    Ray Transfer Matrix for refraction.
+
+    Parameters
+    ==========
+
+    n1 :
+        Refractive index of one medium.
+    n2 :
+        Refractive index of other medium.
+
+    See Also
+    ========
+
+    RayTransferMatrix
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import FlatRefraction
+    >>> from sympy import symbols
+    >>> n1, n2 = symbols('n1 n2')
+    >>> FlatRefraction(n1, n2)
+    Matrix([
+    [1,     0],
+    [0, n1/n2]])
+    """
+    def __new__(cls, n1, n2):
+        n1, n2 = map(sympify, (n1, n2))
+        return RayTransferMatrix.__new__(cls, 1, 0, 0, n1/n2)
+
+
+class CurvedRefraction(RayTransferMatrix):
+    """
+    Ray Transfer Matrix for refraction on curved interface.
+
+    Parameters
+    ==========
+
+    R :
+        Radius of curvature (positive for concave).
+    n1 :
+        Refractive index of one medium.
+    n2 :
+        Refractive index of other medium.
+
+    See Also
+    ========
+
+    RayTransferMatrix
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import CurvedRefraction
+    >>> from sympy import symbols
+    >>> R, n1, n2 = symbols('R n1 n2')
+    >>> CurvedRefraction(R, n1, n2)
+    Matrix([
+    [               1,     0],
+    [(n1 - n2)/(R*n2), n1/n2]])
+    """
+    def __new__(cls, R, n1, n2):
+        R, n1, n2 = map(sympify, (R, n1, n2))
+        return RayTransferMatrix.__new__(cls, 1, 0, (n1 - n2)/R/n2, n1/n2)
+
+
+class FlatMirror(RayTransferMatrix):
+    """
+    Ray Transfer Matrix for reflection.
+
+    See Also
+    ========
+
+    RayTransferMatrix
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import FlatMirror
+    >>> FlatMirror()
+    Matrix([
+    [1, 0],
+    [0, 1]])
+    """
+    def __new__(cls):
+        return RayTransferMatrix.__new__(cls, 1, 0, 0, 1)
+
+
+class CurvedMirror(RayTransferMatrix):
+    """
+    Ray Transfer Matrix for reflection from curved surface.
+
+    Parameters
+    ==========
+
+    R : radius of curvature (positive for concave)
+
+    See Also
+    ========
+
+    RayTransferMatrix
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import CurvedMirror
+    >>> from sympy import symbols
+    >>> R = symbols('R')
+    >>> CurvedMirror(R)
+    Matrix([
+    [   1, 0],
+    [-2/R, 1]])
+    """
+    def __new__(cls, R):
+        R = sympify(R)
+        return RayTransferMatrix.__new__(cls, 1, 0, -2/R, 1)
+
+
+class ThinLens(RayTransferMatrix):
+    """
+    Ray Transfer Matrix for a thin lens.
+
+    Parameters
+    ==========
+
+    f :
+        The focal distance.
+
+    See Also
+    ========
+
+    RayTransferMatrix
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import ThinLens
+    >>> from sympy import symbols
+    >>> f = symbols('f')
+    >>> ThinLens(f)
+    Matrix([
+    [   1, 0],
+    [-1/f, 1]])
+    """
+    def __new__(cls, f):
+        f = sympify(f)
+        return RayTransferMatrix.__new__(cls, 1, 0, -1/f, 1)
+
+
+###
+# Representation for geometric ray
+###
+
+class GeometricRay(MutableDenseMatrix):
+    """
+    Representation for a geometric ray in the Ray Transfer Matrix formalism.
+
+    Parameters
+    ==========
+
+    h : height, and
+    angle : angle, or
+    matrix : a 2x1 matrix (Matrix(2, 1, [height, angle]))
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import GeometricRay, FreeSpace
+    >>> from sympy import symbols, Matrix
+    >>> d, h, angle = symbols('d, h, angle')
+
+    >>> GeometricRay(h, angle)
+    Matrix([
+    [    h],
+    [angle]])
+
+    >>> FreeSpace(d)*GeometricRay(h, angle)
+    Matrix([
+    [angle*d + h],
+    [      angle]])
+
+    >>> GeometricRay( Matrix( ((h,), (angle,)) ) )
+    Matrix([
+    [    h],
+    [angle]])
+
+    See Also
+    ========
+
+    RayTransferMatrix
+
+    """
+
+    def __new__(cls, *args):
+        if len(args) == 1 and isinstance(args[0], Matrix) \
+                and args[0].shape == (2, 1):
+            temp = args[0]
+        elif len(args) == 2:
+            temp = ((args[0],), (args[1],))
+        else:
+            raise ValueError(filldedent('''
+                Expecting 2x1 Matrix or the 2 elements of
+                the Matrix but got %s''' % str(args)))
+        return Matrix.__new__(cls, temp)
+
+    @property
+    def height(self):
+        """
+        The distance from the optical axis.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.optics import GeometricRay
+        >>> from sympy import symbols
+        >>> h, angle = symbols('h, angle')
+        >>> gRay = GeometricRay(h, angle)
+        >>> gRay.height
+        h
+        """
+        return self[0]
+
+    @property
+    def angle(self):
+        """
+        The angle with the optical axis.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.optics import GeometricRay
+        >>> from sympy import symbols
+        >>> h, angle = symbols('h, angle')
+        >>> gRay = GeometricRay(h, angle)
+        >>> gRay.angle
+        angle
+        """
+        return self[1]
+
+
+###
+# Representation for gauss beam
+###
+
+class BeamParameter(Expr):
+    """
+    Representation for a gaussian ray in the Ray Transfer Matrix formalism.
+
+    Parameters
+    ==========
+
+    wavelen : the wavelength,
+    z : the distance to waist, and
+    w : the waist, or
+    z_r : the rayleigh range.
+    n : the refractive index of medium.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import BeamParameter
+    >>> p = BeamParameter(530e-9, 1, w=1e-3)
+    >>> p.q
+    1 + 1.88679245283019*I*pi
+
+    >>> p.q.n()
+    1.0 + 5.92753330865999*I
+    >>> p.w_0.n()
+    0.00100000000000000
+    >>> p.z_r.n()
+    5.92753330865999
+
+    >>> from sympy.physics.optics import FreeSpace
+    >>> fs = FreeSpace(10)
+    >>> p1 = fs*p
+    >>> p.w.n()
+    0.00101413072159615
+    >>> p1.w.n()
+    0.00210803120913829
+
+    See Also
+    ========
+
+    RayTransferMatrix
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Complex_beam_parameter
+    .. [2] https://en.wikipedia.org/wiki/Gaussian_beam
+    """
+    #TODO A class Complex may be implemented. The BeamParameter may
+    # subclass it. See:
+    # https://groups.google.com/d/topic/sympy/7XkU07NRBEs/discussion
+
+    def __new__(cls, wavelen, z, z_r=None, w=None, n=1):
+        wavelen = sympify(wavelen)
+        z = sympify(z)
+        n = sympify(n)
+
+        if z_r is not None and w is None:
+            z_r = sympify(z_r)
+        elif w is not None and z_r is None:
+            z_r = waist2rayleigh(sympify(w), wavelen, n)
+        elif z_r is None and w is None:
+            raise ValueError('Must specify one of w and z_r.')
+
+        return Expr.__new__(cls, wavelen, z, z_r, n)
+
+    @property
+    def wavelen(self):
+        return self.args[0]
+
+    @property
+    def z(self):
+        return self.args[1]
+
+    @property
+    def z_r(self):
+        return self.args[2]
+
+    @property
+    def n(self):
+        return self.args[3]
+
+    @property
+    def q(self):
+        """
+        The complex parameter representing the beam.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.optics import BeamParameter
+        >>> p = BeamParameter(530e-9, 1, w=1e-3)
+        >>> p.q
+        1 + 1.88679245283019*I*pi
+        """
+        return self.z + I*self.z_r
+
+    @property
+    def radius(self):
+        """
+        The radius of curvature of the phase front.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.optics import BeamParameter
+        >>> p = BeamParameter(530e-9, 1, w=1e-3)
+        >>> p.radius
+        1 + 3.55998576005696*pi**2
+        """
+        return self.z*(1 + (self.z_r/self.z)**2)
+
+    @property
+    def w(self):
+        """
+        The radius of the beam w(z), at any position z along the beam.
+        The beam radius at `1/e^2` intensity (axial value).
+
+        See Also
+        ========
+
+        w_0 :
+            The minimal radius of beam.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.optics import BeamParameter
+        >>> p = BeamParameter(530e-9, 1, w=1e-3)
+        >>> p.w
+        0.001*sqrt(0.2809/pi**2 + 1)
+        """
+        return self.w_0*sqrt(1 + (self.z/self.z_r)**2)
+
+    @property
+    def w_0(self):
+        """
+         The minimal radius of beam at `1/e^2` intensity (peak value).
+
+        See Also
+        ========
+
+        w : the beam radius at `1/e^2` intensity (axial value).
+
+        Examples
+        ========
+
+        >>> from sympy.physics.optics import BeamParameter
+        >>> p = BeamParameter(530e-9, 1, w=1e-3)
+        >>> p.w_0
+        0.00100000000000000
+        """
+        return sqrt(self.z_r/(pi*self.n)*self.wavelen)
+
+    @property
+    def divergence(self):
+        """
+        Half of the total angular spread.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.optics import BeamParameter
+        >>> p = BeamParameter(530e-9, 1, w=1e-3)
+        >>> p.divergence
+        0.00053/pi
+        """
+        return self.wavelen/pi/self.w_0
+
+    @property
+    def gouy(self):
+        """
+        The Gouy phase.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.optics import BeamParameter
+        >>> p = BeamParameter(530e-9, 1, w=1e-3)
+        >>> p.gouy
+        atan(0.53/pi)
+        """
+        return atan2(self.z, self.z_r)
+
+    @property
+    def waist_approximation_limit(self):
+        """
+        The minimal waist for which the gauss beam approximation is valid.
+
+        Explanation
+        ===========
+
+        The gauss beam is a solution to the paraxial equation. For curvatures
+        that are too great it is not a valid approximation.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.optics import BeamParameter
+        >>> p = BeamParameter(530e-9, 1, w=1e-3)
+        >>> p.waist_approximation_limit
+        1.06e-6/pi
+        """
+        return 2*self.wavelen/pi
+
+
+###
+# Utilities
+###
+
+def waist2rayleigh(w, wavelen, n=1):
+    """
+    Calculate the rayleigh range from the waist of a gaussian beam.
+
+    See Also
+    ========
+
+    rayleigh2waist, BeamParameter
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import waist2rayleigh
+    >>> from sympy import symbols
+    >>> w, wavelen = symbols('w wavelen')
+    >>> waist2rayleigh(w, wavelen)
+    pi*w**2/wavelen
+    """
+    w, wavelen = map(sympify, (w, wavelen))
+    return w**2*n*pi/wavelen
+
+
+def rayleigh2waist(z_r, wavelen):
+    """Calculate the waist from the rayleigh range of a gaussian beam.
+
+    See Also
+    ========
+
+    waist2rayleigh, BeamParameter
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import rayleigh2waist
+    >>> from sympy import symbols
+    >>> z_r, wavelen = symbols('z_r wavelen')
+    >>> rayleigh2waist(z_r, wavelen)
+    sqrt(wavelen*z_r)/sqrt(pi)
+    """
+    z_r, wavelen = map(sympify, (z_r, wavelen))
+    return sqrt(z_r/pi*wavelen)
+
+
+def geometric_conj_ab(a, b):
+    """
+    Conjugation relation for geometrical beams under paraxial conditions.
+
+    Explanation
+    ===========
+
+    Takes the distances to the optical element and returns the needed
+    focal distance.
+
+    See Also
+    ========
+
+    geometric_conj_af, geometric_conj_bf
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import geometric_conj_ab
+    >>> from sympy import symbols
+    >>> a, b = symbols('a b')
+    >>> geometric_conj_ab(a, b)
+    a*b/(a + b)
+    """
+    a, b = map(sympify, (a, b))
+    if a.is_infinite or b.is_infinite:
+        return a if b.is_infinite else b
+    else:
+        return a*b/(a + b)
+
+
+def geometric_conj_af(a, f):
+    """
+    Conjugation relation for geometrical beams under paraxial conditions.
+
+    Explanation
+    ===========
+
+    Takes the object distance (for geometric_conj_af) or the image distance
+    (for geometric_conj_bf) to the optical element and the focal distance.
+    Then it returns the other distance needed for conjugation.
+
+    See Also
+    ========
+
+    geometric_conj_ab
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics.gaussopt import geometric_conj_af, geometric_conj_bf
+    >>> from sympy import symbols
+    >>> a, b, f = symbols('a b f')
+    >>> geometric_conj_af(a, f)
+    a*f/(a - f)
+    >>> geometric_conj_bf(b, f)
+    b*f/(b - f)
+    """
+    a, f = map(sympify, (a, f))
+    return -geometric_conj_ab(a, -f)
+
+geometric_conj_bf = geometric_conj_af
+
+
+def gaussian_conj(s_in, z_r_in, f):
+    """
+    Conjugation relation for gaussian beams.
+
+    Parameters
+    ==========
+
+    s_in :
+        The distance to optical element from the waist.
+    z_r_in :
+        The rayleigh range of the incident beam.
+    f :
+        The focal length of the optical element.
+
+    Returns
+    =======
+
+    a tuple containing (s_out, z_r_out, m)
+    s_out :
+        The distance between the new waist and the optical element.
+    z_r_out :
+        The rayleigh range of the emergent beam.
+    m :
+        The ration between the new and the old waists.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import gaussian_conj
+    >>> from sympy import symbols
+    >>> s_in, z_r_in, f = symbols('s_in z_r_in f')
+
+    >>> gaussian_conj(s_in, z_r_in, f)[0]
+    1/(-1/(s_in + z_r_in**2/(-f + s_in)) + 1/f)
+
+    >>> gaussian_conj(s_in, z_r_in, f)[1]
+    z_r_in/(1 - s_in**2/f**2 + z_r_in**2/f**2)
+
+    >>> gaussian_conj(s_in, z_r_in, f)[2]
+    1/sqrt(1 - s_in**2/f**2 + z_r_in**2/f**2)
+    """
+    s_in, z_r_in, f = map(sympify, (s_in, z_r_in, f))
+    s_out = 1 / ( -1/(s_in + z_r_in**2/(s_in - f)) + 1/f )
+    m = 1/sqrt((1 - (s_in/f)**2) + (z_r_in/f)**2)
+    z_r_out = z_r_in / ((1 - (s_in/f)**2) + (z_r_in/f)**2)
+    return (s_out, z_r_out, m)
+
+
+def conjugate_gauss_beams(wavelen, waist_in, waist_out, **kwargs):
+    """
+    Find the optical setup conjugating the object/image waists.
+
+    Parameters
+    ==========
+
+    wavelen :
+        The wavelength of the beam.
+    waist_in and waist_out :
+        The waists to be conjugated.
+    f :
+        The focal distance of the element used in the conjugation.
+
+    Returns
+    =======
+
+    a tuple containing (s_in, s_out, f)
+    s_in :
+        The distance before the optical element.
+    s_out :
+        The distance after the optical element.
+    f :
+        The focal distance of the optical element.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import conjugate_gauss_beams
+    >>> from sympy import symbols, factor
+    >>> l, w_i, w_o, f = symbols('l w_i w_o f')
+
+    >>> conjugate_gauss_beams(l, w_i, w_o, f=f)[0]
+    f*(1 - sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2)))
+
+    >>> factor(conjugate_gauss_beams(l, w_i, w_o, f=f)[1])
+    f*w_o**2*(w_i**2/w_o**2 - sqrt(w_i**2/w_o**2 -
+              pi**2*w_i**4/(f**2*l**2)))/w_i**2
+
+    >>> conjugate_gauss_beams(l, w_i, w_o, f=f)[2]
+    f
+    """
+    #TODO add the other possible arguments
+    wavelen, waist_in, waist_out = map(sympify, (wavelen, waist_in, waist_out))
+    m = waist_out / waist_in
+    z = waist2rayleigh(waist_in, wavelen)
+    if len(kwargs) != 1:
+        raise ValueError("The function expects only one named argument")
+    elif 'dist' in kwargs:
+        raise NotImplementedError(filldedent('''
+            Currently only focal length is supported as a parameter'''))
+    elif 'f' in kwargs:
+        f = sympify(kwargs['f'])
+        s_in = f * (1 - sqrt(1/m**2 - z**2/f**2))
+        s_out = gaussian_conj(s_in, z, f)[0]
+    elif 's_in' in kwargs:
+        raise NotImplementedError(filldedent('''
+            Currently only focal length is supported as a parameter'''))
+    else:
+        raise ValueError(filldedent('''
+            The functions expects the focal length as a named argument'''))
+    return (s_in, s_out, f)
+
+#TODO
+#def plot_beam():
+#    """Plot the beam radius as it propagates in space."""
+#    pass
+
+#TODO
+#def plot_beam_conjugation():
+#    """
+#    Plot the intersection of two beams.
+#
+#    Represents the conjugation relation.
+#
+#    See Also
+#    ========
+#
+#    conjugate_gauss_beams
+#    """
+#    pass
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/medium.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/medium.py
new file mode 100644
index 0000000000000000000000000000000000000000..764b68caad5865b8f3cee028a14cfa304796b4c0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/medium.py
@@ -0,0 +1,253 @@
+"""
+**Contains**
+
+* Medium
+"""
+from sympy.physics.units import second, meter, kilogram, ampere
+
+__all__ = ['Medium']
+
+from sympy.core.basic import Basic
+from sympy.core.symbol import Str
+from sympy.core.sympify import _sympify
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.physics.units import speed_of_light, u0, e0
+
+
+c = speed_of_light.convert_to(meter/second)
+_e0mksa = e0.convert_to(ampere**2*second**4/(kilogram*meter**3))
+_u0mksa = u0.convert_to(meter*kilogram/(ampere**2*second**2))
+
+
+class Medium(Basic):
+
+    """
+    This class represents an optical medium. The prime reason to implement this is
+    to facilitate refraction, Fermat's principle, etc.
+
+    Explanation
+    ===========
+
+    An optical medium is a material through which electromagnetic waves propagate.
+    The permittivity and permeability of the medium define how electromagnetic
+    waves propagate in it.
+
+
+    Parameters
+    ==========
+
+    name: string
+        The display name of the Medium.
+
+    permittivity: Sympifyable
+        Electric permittivity of the space.
+
+    permeability: Sympifyable
+        Magnetic permeability of the space.
+
+    n: Sympifyable
+        Index of refraction of the medium.
+
+
+    Examples
+    ========
+
+    >>> from sympy.abc import epsilon, mu
+    >>> from sympy.physics.optics import Medium
+    >>> m1 = Medium('m1')
+    >>> m2 = Medium('m2', epsilon, mu)
+    >>> m1.intrinsic_impedance
+    149896229*pi*kilogram*meter**2/(1250000*ampere**2*second**3)
+    >>> m2.refractive_index
+    299792458*meter*sqrt(epsilon*mu)/second
+
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Optical_medium
+
+    """
+
+    def __new__(cls, name, permittivity=None, permeability=None, n=None):
+        if not isinstance(name, Str):
+            name = Str(name)
+
+        permittivity = _sympify(permittivity) if permittivity is not None else permittivity
+        permeability = _sympify(permeability) if permeability is not None else permeability
+        n = _sympify(n) if n is not None else n
+
+        if n is not None:
+            if permittivity is not None and permeability is None:
+                permeability = n**2/(c**2*permittivity)
+                return MediumPP(name, permittivity, permeability)
+            elif permeability is not None and permittivity is None:
+                permittivity = n**2/(c**2*permeability)
+                return MediumPP(name, permittivity, permeability)
+            elif permittivity is not None and permittivity is not None:
+                raise ValueError("Specifying all of permittivity, permeability, and n is not allowed")
+            else:
+                return MediumN(name, n)
+        elif permittivity is not None and permeability is not None:
+            return MediumPP(name, permittivity, permeability)
+        elif permittivity is None and permeability is None:
+            return MediumPP(name, _e0mksa, _u0mksa)
+        else:
+            raise ValueError("Arguments are underspecified. Either specify n or any two of permittivity, "
+                             "permeability, and n")
+
+    @property
+    def name(self):
+        return self.args[0]
+
+    @property
+    def speed(self):
+        """
+        Returns speed of the electromagnetic wave travelling in the medium.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.optics import Medium
+        >>> m = Medium('m')
+        >>> m.speed
+        299792458*meter/second
+        >>> m2 = Medium('m2', n=1)
+        >>> m.speed == m2.speed
+        True
+
+        """
+        return c / self.n
+
+    @property
+    def refractive_index(self):
+        """
+        Returns refractive index of the medium.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.optics import Medium
+        >>> m = Medium('m')
+        >>> m.refractive_index
+        1
+
+        """
+        return (c/self.speed)
+
+
+class MediumN(Medium):
+
+    """
+    Represents an optical medium for which only the refractive index is known.
+    Useful for simple ray optics.
+
+    This class should never be instantiated directly.
+    Instead it should be instantiated indirectly by instantiating Medium with
+    only n specified.
+
+    Examples
+    ========
+    >>> from sympy.physics.optics import Medium
+    >>> m = Medium('m', n=2)
+    >>> m
+    MediumN(Str('m'), 2)
+    """
+
+    def __new__(cls, name, n):
+        obj = super(Medium, cls).__new__(cls, name, n)
+        return obj
+
+    @property
+    def n(self):
+        return self.args[1]
+
+
+class MediumPP(Medium):
+    """
+    Represents an optical medium for which the permittivity and permeability are known.
+
+    This class should never be instantiated directly. Instead it should be
+    instantiated indirectly by instantiating Medium with any two of
+    permittivity, permeability, and n specified, or by not specifying any
+    of permittivity, permeability, or n, in which case default values for
+    permittivity and permeability will be used.
+
+    Examples
+    ========
+    >>> from sympy.physics.optics import Medium
+    >>> from sympy.abc import epsilon, mu
+    >>> m1 = Medium('m1', permittivity=epsilon, permeability=mu)
+    >>> m1
+    MediumPP(Str('m1'), epsilon, mu)
+    >>> m2 = Medium('m2')
+    >>> m2
+    MediumPP(Str('m2'), 625000*ampere**2*second**4/(22468879468420441*pi*kilogram*meter**3), pi*kilogram*meter/(2500000*ampere**2*second**2))
+    """
+
+
+    def __new__(cls, name, permittivity, permeability):
+        obj = super(Medium, cls).__new__(cls, name, permittivity, permeability)
+        return obj
+
+    @property
+    def intrinsic_impedance(self):
+        """
+        Returns intrinsic impedance of the medium.
+
+        Explanation
+        ===========
+
+        The intrinsic impedance of a medium is the ratio of the
+        transverse components of the electric and magnetic fields
+        of the electromagnetic wave travelling in the medium.
+        In a region with no electrical conductivity it simplifies
+        to the square root of ratio of magnetic permeability to
+        electric permittivity.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.optics import Medium
+        >>> m = Medium('m')
+        >>> m.intrinsic_impedance
+        149896229*pi*kilogram*meter**2/(1250000*ampere**2*second**3)
+
+        """
+        return sqrt(self.permeability / self.permittivity)
+
+    @property
+    def permittivity(self):
+        """
+        Returns electric permittivity of the medium.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.optics import Medium
+        >>> m = Medium('m')
+        >>> m.permittivity
+        625000*ampere**2*second**4/(22468879468420441*pi*kilogram*meter**3)
+
+        """
+        return self.args[1]
+
+    @property
+    def permeability(self):
+        """
+        Returns magnetic permeability of the medium.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.optics import Medium
+        >>> m = Medium('m')
+        >>> m.permeability
+        pi*kilogram*meter/(2500000*ampere**2*second**2)
+
+        """
+        return self.args[2]
+
+    @property
+    def n(self):
+        return c*sqrt(self.permittivity*self.permeability)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/polarization.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/polarization.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bdb546548ad082ef38f5f0c159d7eadd38f6d30
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/polarization.py
@@ -0,0 +1,732 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+The module implements routines to model the polarization of optical fields
+and can be used to calculate the effects of polarization optical elements on
+the fields.
+
+- Jones vectors.
+
+- Stokes vectors.
+
+- Jones matrices.
+
+- Mueller matrices.
+
+Examples
+========
+
+We calculate a generic Jones vector:
+
+>>> from sympy import symbols, pprint, zeros, simplify
+>>> from sympy.physics.optics.polarization import (jones_vector, stokes_vector,
+...     half_wave_retarder, polarizing_beam_splitter, jones_2_stokes)
+
+>>> psi, chi, p, I0 = symbols("psi, chi, p, I0", real=True)
+>>> x0 = jones_vector(psi, chi)
+>>> pprint(x0, use_unicode=True)
+⎡-ⅈ⋅sin(χ)⋅sin(ψ) + cos(χ)⋅cos(ψ)⎤
+⎢                                ⎥
+⎣ⅈ⋅sin(χ)⋅cos(ψ) + sin(ψ)⋅cos(χ) ⎦
+
+And the more general Stokes vector:
+
+>>> s0 = stokes_vector(psi, chi, p, I0)
+>>> pprint(s0, use_unicode=True)
+⎡          I₀          ⎤
+⎢                      ⎥
+⎢I₀⋅p⋅cos(2⋅χ)⋅cos(2⋅ψ)⎥
+⎢                      ⎥
+⎢I₀⋅p⋅sin(2⋅ψ)⋅cos(2⋅χ)⎥
+⎢                      ⎥
+⎣    I₀⋅p⋅sin(2⋅χ)     ⎦
+
+We calculate how the Jones vector is modified by a half-wave plate:
+
+>>> alpha = symbols("alpha", real=True)
+>>> HWP = half_wave_retarder(alpha)
+>>> x1 = simplify(HWP*x0)
+
+We calculate the very common operation of passing a beam through a half-wave
+plate and then through a polarizing beam-splitter. We do this by putting this
+Jones vector as the first entry of a two-Jones-vector state that is transformed
+by a 4x4 Jones matrix modelling the polarizing beam-splitter to get the
+transmitted and reflected Jones vectors:
+
+>>> PBS = polarizing_beam_splitter()
+>>> X1 = zeros(4, 1)
+>>> X1[:2, :] = x1
+>>> X2 = PBS*X1
+>>> transmitted_port = X2[:2, :]
+>>> reflected_port = X2[2:, :]
+
+This allows us to calculate how the power in both ports depends on the initial
+polarization:
+
+>>> transmitted_power = jones_2_stokes(transmitted_port)[0]
+>>> reflected_power = jones_2_stokes(reflected_port)[0]
+>>> print(transmitted_power)
+cos(-2*alpha + chi + psi)**2/2 + cos(2*alpha + chi - psi)**2/2
+
+
+>>> print(reflected_power)
+sin(-2*alpha + chi + psi)**2/2 + sin(2*alpha + chi - psi)**2/2
+
+Please see the description of the individual functions for further
+details and examples.
+
+References
+==========
+
+.. [1] https://en.wikipedia.org/wiki/Jones_calculus
+.. [2] https://en.wikipedia.org/wiki/Mueller_calculus
+.. [3] https://en.wikipedia.org/wiki/Stokes_parameters
+
+"""
+
+from sympy.core.numbers import (I, pi)
+from sympy.functions.elementary.complexes import (Abs, im, re)
+from sympy.functions.elementary.exponential import exp
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import (cos, sin)
+from sympy.matrices.dense import Matrix
+from sympy.simplify.simplify import simplify
+from sympy.physics.quantum import TensorProduct
+
+
+def jones_vector(psi, chi):
+    """A Jones vector corresponding to a polarization ellipse with `psi` tilt,
+    and `chi` circularity.
+
+    Parameters
+    ==========
+
+    psi : numeric type or SymPy Symbol
+        The tilt of the polarization relative to the `x` axis.
+
+    chi : numeric type or SymPy Symbol
+        The angle adjacent to the mayor axis of the polarization ellipse.
+
+
+    Returns
+    =======
+
+    Matrix :
+        A Jones vector.
+
+    Examples
+    ========
+
+    The axes on the Poincaré sphere.
+
+    >>> from sympy import pprint, symbols, pi
+    >>> from sympy.physics.optics.polarization import jones_vector
+    >>> psi, chi = symbols("psi, chi", real=True)
+
+    A general Jones vector.
+
+    >>> pprint(jones_vector(psi, chi), use_unicode=True)
+    ⎡-ⅈ⋅sin(χ)⋅sin(ψ) + cos(χ)⋅cos(ψ)⎤
+    ⎢                                ⎥
+    ⎣ⅈ⋅sin(χ)⋅cos(ψ) + sin(ψ)⋅cos(χ) ⎦
+
+    Horizontal polarization.
+
+    >>> pprint(jones_vector(0, 0), use_unicode=True)
+    ⎡1⎤
+    ⎢ ⎥
+    ⎣0⎦
+
+    Vertical polarization.
+
+    >>> pprint(jones_vector(pi/2, 0), use_unicode=True)
+    ⎡0⎤
+    ⎢ ⎥
+    ⎣1⎦
+
+    Diagonal polarization.
+
+    >>> pprint(jones_vector(pi/4, 0), use_unicode=True)
+    ⎡√2⎤
+    ⎢──⎥
+    ⎢2 ⎥
+    ⎢  ⎥
+    ⎢√2⎥
+    ⎢──⎥
+    ⎣2 ⎦
+
+    Anti-diagonal polarization.
+
+    >>> pprint(jones_vector(-pi/4, 0), use_unicode=True)
+    ⎡ √2 ⎤
+    ⎢ ── ⎥
+    ⎢ 2  ⎥
+    ⎢    ⎥
+    ⎢-√2 ⎥
+    ⎢────⎥
+    ⎣ 2  ⎦
+
+    Right-hand circular polarization.
+
+    >>> pprint(jones_vector(0, pi/4), use_unicode=True)
+    ⎡ √2 ⎤
+    ⎢ ── ⎥
+    ⎢ 2  ⎥
+    ⎢    ⎥
+    ⎢√2⋅ⅈ⎥
+    ⎢────⎥
+    ⎣ 2  ⎦
+
+    Left-hand circular polarization.
+
+    >>> pprint(jones_vector(0, -pi/4), use_unicode=True)
+    ⎡  √2  ⎤
+    ⎢  ──  ⎥
+    ⎢  2   ⎥
+    ⎢      ⎥
+    ⎢-√2⋅ⅈ ⎥
+    ⎢──────⎥
+    ⎣  2   ⎦
+
+    """
+    return Matrix([-I*sin(chi)*sin(psi) + cos(chi)*cos(psi),
+                   I*sin(chi)*cos(psi) + sin(psi)*cos(chi)])
+
+
+def stokes_vector(psi, chi, p=1, I=1):
+    """A Stokes vector corresponding to a polarization ellipse with ``psi``
+    tilt, and ``chi`` circularity.
+
+    Parameters
+    ==========
+
+    psi : numeric type or SymPy Symbol
+        The tilt of the polarization relative to the ``x`` axis.
+    chi : numeric type or SymPy Symbol
+        The angle adjacent to the mayor axis of the polarization ellipse.
+    p : numeric type or SymPy Symbol
+        The degree of polarization.
+    I : numeric type or SymPy Symbol
+        The intensity of the field.
+
+
+    Returns
+    =======
+
+    Matrix :
+        A Stokes vector.
+
+    Examples
+    ========
+
+    The axes on the Poincaré sphere.
+
+    >>> from sympy import pprint, symbols, pi
+    >>> from sympy.physics.optics.polarization import stokes_vector
+    >>> psi, chi, p, I = symbols("psi, chi, p, I", real=True)
+    >>> pprint(stokes_vector(psi, chi, p, I), use_unicode=True)
+    ⎡          I          ⎤
+    ⎢                     ⎥
+    ⎢I⋅p⋅cos(2⋅χ)⋅cos(2⋅ψ)⎥
+    ⎢                     ⎥
+    ⎢I⋅p⋅sin(2⋅ψ)⋅cos(2⋅χ)⎥
+    ⎢                     ⎥
+    ⎣    I⋅p⋅sin(2⋅χ)     ⎦
+
+
+    Horizontal polarization
+
+    >>> pprint(stokes_vector(0, 0), use_unicode=True)
+    ⎡1⎤
+    ⎢ ⎥
+    ⎢1⎥
+    ⎢ ⎥
+    ⎢0⎥
+    ⎢ ⎥
+    ⎣0⎦
+
+    Vertical polarization
+
+    >>> pprint(stokes_vector(pi/2, 0), use_unicode=True)
+    ⎡1 ⎤
+    ⎢  ⎥
+    ⎢-1⎥
+    ⎢  ⎥
+    ⎢0 ⎥
+    ⎢  ⎥
+    ⎣0 ⎦
+
+    Diagonal polarization
+
+    >>> pprint(stokes_vector(pi/4, 0), use_unicode=True)
+    ⎡1⎤
+    ⎢ ⎥
+    ⎢0⎥
+    ⎢ ⎥
+    ⎢1⎥
+    ⎢ ⎥
+    ⎣0⎦
+
+    Anti-diagonal polarization
+
+    >>> pprint(stokes_vector(-pi/4, 0), use_unicode=True)
+    ⎡1 ⎤
+    ⎢  ⎥
+    ⎢0 ⎥
+    ⎢  ⎥
+    ⎢-1⎥
+    ⎢  ⎥
+    ⎣0 ⎦
+
+    Right-hand circular polarization
+
+    >>> pprint(stokes_vector(0, pi/4), use_unicode=True)
+    ⎡1⎤
+    ⎢ ⎥
+    ⎢0⎥
+    ⎢ ⎥
+    ⎢0⎥
+    ⎢ ⎥
+    ⎣1⎦
+
+    Left-hand circular polarization
+
+    >>> pprint(stokes_vector(0, -pi/4), use_unicode=True)
+    ⎡1 ⎤
+    ⎢  ⎥
+    ⎢0 ⎥
+    ⎢  ⎥
+    ⎢0 ⎥
+    ⎢  ⎥
+    ⎣-1⎦
+
+    Unpolarized light
+
+    >>> pprint(stokes_vector(0, 0, 0), use_unicode=True)
+    ⎡1⎤
+    ⎢ ⎥
+    ⎢0⎥
+    ⎢ ⎥
+    ⎢0⎥
+    ⎢ ⎥
+    ⎣0⎦
+
+    """
+    S0 = I
+    S1 = I*p*cos(2*psi)*cos(2*chi)
+    S2 = I*p*sin(2*psi)*cos(2*chi)
+    S3 = I*p*sin(2*chi)
+    return Matrix([S0, S1, S2, S3])
+
+
+def jones_2_stokes(e):
+    """Return the Stokes vector for a Jones vector ``e``.
+
+    Parameters
+    ==========
+
+    e : SymPy Matrix
+        A Jones vector.
+
+    Returns
+    =======
+
+    SymPy Matrix
+        A Jones vector.
+
+    Examples
+    ========
+
+    The axes on the Poincaré sphere.
+
+    >>> from sympy import pprint, pi
+    >>> from sympy.physics.optics.polarization import jones_vector
+    >>> from sympy.physics.optics.polarization import jones_2_stokes
+    >>> H = jones_vector(0, 0)
+    >>> V = jones_vector(pi/2, 0)
+    >>> D = jones_vector(pi/4, 0)
+    >>> A = jones_vector(-pi/4, 0)
+    >>> R = jones_vector(0, pi/4)
+    >>> L = jones_vector(0, -pi/4)
+    >>> pprint([jones_2_stokes(e) for e in [H, V, D, A, R, L]],
+    ...         use_unicode=True)
+    ⎡⎡1⎤  ⎡1 ⎤  ⎡1⎤  ⎡1 ⎤  ⎡1⎤  ⎡1 ⎤⎤
+    ⎢⎢ ⎥  ⎢  ⎥  ⎢ ⎥  ⎢  ⎥  ⎢ ⎥  ⎢  ⎥⎥
+    ⎢⎢1⎥  ⎢-1⎥  ⎢0⎥  ⎢0 ⎥  ⎢0⎥  ⎢0 ⎥⎥
+    ⎢⎢ ⎥, ⎢  ⎥, ⎢ ⎥, ⎢  ⎥, ⎢ ⎥, ⎢  ⎥⎥
+    ⎢⎢0⎥  ⎢0 ⎥  ⎢1⎥  ⎢-1⎥  ⎢0⎥  ⎢0 ⎥⎥
+    ⎢⎢ ⎥  ⎢  ⎥  ⎢ ⎥  ⎢  ⎥  ⎢ ⎥  ⎢  ⎥⎥
+    ⎣⎣0⎦  ⎣0 ⎦  ⎣0⎦  ⎣0 ⎦  ⎣1⎦  ⎣-1⎦⎦
+
+    """
+    ex, ey = e
+    return Matrix([Abs(ex)**2 + Abs(ey)**2,
+                   Abs(ex)**2 - Abs(ey)**2,
+                   2*re(ex*ey.conjugate()),
+                   -2*im(ex*ey.conjugate())])
+
+
+def linear_polarizer(theta=0):
+    """A linear polarizer Jones matrix with transmission axis at
+    an angle ``theta``.
+
+    Parameters
+    ==========
+
+    theta : numeric type or SymPy Symbol
+        The angle of the transmission axis relative to the horizontal plane.
+
+    Returns
+    =======
+
+    SymPy Matrix
+        A Jones matrix representing the polarizer.
+
+    Examples
+    ========
+
+    A generic polarizer.
+
+    >>> from sympy import pprint, symbols
+    >>> from sympy.physics.optics.polarization import linear_polarizer
+    >>> theta = symbols("theta", real=True)
+    >>> J = linear_polarizer(theta)
+    >>> pprint(J, use_unicode=True)
+    ⎡      2                     ⎤
+    ⎢   cos (θ)     sin(θ)⋅cos(θ)⎥
+    ⎢                            ⎥
+    ⎢                     2      ⎥
+    ⎣sin(θ)⋅cos(θ)     sin (θ)   ⎦
+
+
+    """
+    M = Matrix([[cos(theta)**2, sin(theta)*cos(theta)],
+                [sin(theta)*cos(theta), sin(theta)**2]])
+    return M
+
+
+def phase_retarder(theta=0, delta=0):
+    """A phase retarder Jones matrix with retardance ``delta`` at angle ``theta``.
+
+    Parameters
+    ==========
+
+    theta : numeric type or SymPy Symbol
+        The angle of the fast axis relative to the horizontal plane.
+    delta : numeric type or SymPy Symbol
+        The phase difference between the fast and slow axes of the
+        transmitted light.
+
+    Returns
+    =======
+
+    SymPy Matrix :
+        A Jones matrix representing the retarder.
+
+    Examples
+    ========
+
+    A generic retarder.
+
+    >>> from sympy import pprint, symbols
+    >>> from sympy.physics.optics.polarization import phase_retarder
+    >>> theta, delta = symbols("theta, delta", real=True)
+    >>> R = phase_retarder(theta, delta)
+    >>> pprint(R, use_unicode=True)
+    ⎡                          -ⅈ⋅δ               -ⅈ⋅δ               ⎤
+    ⎢                          ─────              ─────              ⎥
+    ⎢⎛ ⅈ⋅δ    2         2   ⎞    2    ⎛     ⅈ⋅δ⎞    2                ⎥
+    ⎢⎝ℯ   ⋅sin (θ) + cos (θ)⎠⋅ℯ       ⎝1 - ℯ   ⎠⋅ℯ     ⋅sin(θ)⋅cos(θ)⎥
+    ⎢                                                                ⎥
+    ⎢            -ⅈ⋅δ                                           -ⅈ⋅δ ⎥
+    ⎢            ─────                                          ─────⎥
+    ⎢⎛     ⅈ⋅δ⎞    2                  ⎛ ⅈ⋅δ    2         2   ⎞    2  ⎥
+    ⎣⎝1 - ℯ   ⎠⋅ℯ     ⋅sin(θ)⋅cos(θ)  ⎝ℯ   ⋅cos (θ) + sin (θ)⎠⋅ℯ     ⎦
+
+    """
+    R = Matrix([[cos(theta)**2 + exp(I*delta)*sin(theta)**2,
+                (1-exp(I*delta))*cos(theta)*sin(theta)],
+                [(1-exp(I*delta))*cos(theta)*sin(theta),
+                sin(theta)**2 + exp(I*delta)*cos(theta)**2]])
+    return R*exp(-I*delta/2)
+
+
+def half_wave_retarder(theta):
+    """A half-wave retarder Jones matrix at angle ``theta``.
+
+    Parameters
+    ==========
+
+    theta : numeric type or SymPy Symbol
+        The angle of the fast axis relative to the horizontal plane.
+
+    Returns
+    =======
+
+    SymPy Matrix
+        A Jones matrix representing the retarder.
+
+    Examples
+    ========
+
+    A generic half-wave plate.
+
+    >>> from sympy import pprint, symbols
+    >>> from sympy.physics.optics.polarization import half_wave_retarder
+    >>> theta= symbols("theta", real=True)
+    >>> HWP = half_wave_retarder(theta)
+    >>> pprint(HWP, use_unicode=True)
+    ⎡   ⎛     2         2   ⎞                        ⎤
+    ⎢-ⅈ⋅⎝- sin (θ) + cos (θ)⎠    -2⋅ⅈ⋅sin(θ)⋅cos(θ)  ⎥
+    ⎢                                                ⎥
+    ⎢                             ⎛   2         2   ⎞⎥
+    ⎣   -2⋅ⅈ⋅sin(θ)⋅cos(θ)     -ⅈ⋅⎝sin (θ) - cos (θ)⎠⎦
+
+    """
+    return phase_retarder(theta, pi)
+
+
+def quarter_wave_retarder(theta):
+    """A quarter-wave retarder Jones matrix at angle ``theta``.
+
+    Parameters
+    ==========
+
+    theta : numeric type or SymPy Symbol
+        The angle of the fast axis relative to the horizontal plane.
+
+    Returns
+    =======
+
+    SymPy Matrix
+        A Jones matrix representing the retarder.
+
+    Examples
+    ========
+
+    A generic quarter-wave plate.
+
+    >>> from sympy import pprint, symbols
+    >>> from sympy.physics.optics.polarization import quarter_wave_retarder
+    >>> theta= symbols("theta", real=True)
+    >>> QWP = quarter_wave_retarder(theta)
+    >>> pprint(QWP, use_unicode=True)
+    ⎡                       -ⅈ⋅π            -ⅈ⋅π               ⎤
+    ⎢                       ─────           ─────              ⎥
+    ⎢⎛     2         2   ⎞    4               4                ⎥
+    ⎢⎝ⅈ⋅sin (θ) + cos (θ)⎠⋅ℯ       (1 - ⅈ)⋅ℯ     ⋅sin(θ)⋅cos(θ)⎥
+    ⎢                                                          ⎥
+    ⎢         -ⅈ⋅π                                        -ⅈ⋅π ⎥
+    ⎢         ─────                                       ─────⎥
+    ⎢           4                  ⎛   2           2   ⎞    4  ⎥
+    ⎣(1 - ⅈ)⋅ℯ     ⋅sin(θ)⋅cos(θ)  ⎝sin (θ) + ⅈ⋅cos (θ)⎠⋅ℯ     ⎦
+
+    """
+    return phase_retarder(theta, pi/2)
+
+
+def transmissive_filter(T):
+    """An attenuator Jones matrix with transmittance ``T``.
+
+    Parameters
+    ==========
+
+    T : numeric type or SymPy Symbol
+        The transmittance of the attenuator.
+
+    Returns
+    =======
+
+    SymPy Matrix
+        A Jones matrix representing the filter.
+
+    Examples
+    ========
+
+    A generic filter.
+
+    >>> from sympy import pprint, symbols
+    >>> from sympy.physics.optics.polarization import transmissive_filter
+    >>> T = symbols("T", real=True)
+    >>> NDF = transmissive_filter(T)
+    >>> pprint(NDF, use_unicode=True)
+    ⎡√T  0 ⎤
+    ⎢      ⎥
+    ⎣0   √T⎦
+
+    """
+    return Matrix([[sqrt(T), 0], [0, sqrt(T)]])
+
+
+def reflective_filter(R):
+    """A reflective filter Jones matrix with reflectance ``R``.
+
+    Parameters
+    ==========
+
+    R : numeric type or SymPy Symbol
+        The reflectance of the filter.
+
+    Returns
+    =======
+
+    SymPy Matrix
+        A Jones matrix representing the filter.
+
+    Examples
+    ========
+
+    A generic filter.
+
+    >>> from sympy import pprint, symbols
+    >>> from sympy.physics.optics.polarization import reflective_filter
+    >>> R = symbols("R", real=True)
+    >>> pprint(reflective_filter(R), use_unicode=True)
+    ⎡√R   0 ⎤
+    ⎢       ⎥
+    ⎣0   -√R⎦
+
+    """
+    return Matrix([[sqrt(R), 0], [0, -sqrt(R)]])
+
+
+def mueller_matrix(J):
+    """The Mueller matrix corresponding to Jones matrix `J`.
+
+    Parameters
+    ==========
+
+    J : SymPy Matrix
+        A Jones matrix.
+
+    Returns
+    =======
+
+    SymPy Matrix
+        The corresponding Mueller matrix.
+
+    Examples
+    ========
+
+    Generic optical components.
+
+    >>> from sympy import pprint, symbols
+    >>> from sympy.physics.optics.polarization import (mueller_matrix,
+    ...     linear_polarizer, half_wave_retarder, quarter_wave_retarder)
+    >>> theta = symbols("theta", real=True)
+
+    A linear_polarizer
+
+    >>> pprint(mueller_matrix(linear_polarizer(theta)), use_unicode=True)
+    ⎡            cos(2⋅θ)      sin(2⋅θ)     ⎤
+    ⎢  1/2       ────────      ────────    0⎥
+    ⎢               2             2         ⎥
+    ⎢                                       ⎥
+    ⎢cos(2⋅θ)  cos(4⋅θ)   1    sin(4⋅θ)     ⎥
+    ⎢────────  ──────── + ─    ────────    0⎥
+    ⎢   2         4       4       4         ⎥
+    ⎢                                       ⎥
+    ⎢sin(2⋅θ)    sin(4⋅θ)    1   cos(4⋅θ)   ⎥
+    ⎢────────    ────────    ─ - ────────  0⎥
+    ⎢   2           4        4      4       ⎥
+    ⎢                                       ⎥
+    ⎣   0           0             0        0⎦
+
+    A half-wave plate
+
+    >>> pprint(mueller_matrix(half_wave_retarder(theta)), use_unicode=True)
+    ⎡1              0                           0               0 ⎤
+    ⎢                                                             ⎥
+    ⎢        4           2                                        ⎥
+    ⎢0  8⋅sin (θ) - 8⋅sin (θ) + 1           sin(4⋅θ)            0 ⎥
+    ⎢                                                             ⎥
+    ⎢                                     4           2           ⎥
+    ⎢0          sin(4⋅θ)           - 8⋅sin (θ) + 8⋅sin (θ) - 1  0 ⎥
+    ⎢                                                             ⎥
+    ⎣0              0                           0               -1⎦
+
+    A quarter-wave plate
+
+    >>> pprint(mueller_matrix(quarter_wave_retarder(theta)), use_unicode=True)
+    ⎡1       0             0            0    ⎤
+    ⎢                                        ⎥
+    ⎢   cos(4⋅θ)   1    sin(4⋅θ)             ⎥
+    ⎢0  ──────── + ─    ────────    -sin(2⋅θ)⎥
+    ⎢      2       2       2                 ⎥
+    ⎢                                        ⎥
+    ⎢     sin(4⋅θ)    1   cos(4⋅θ)           ⎥
+    ⎢0    ────────    ─ - ────────  cos(2⋅θ) ⎥
+    ⎢        2        2      2               ⎥
+    ⎢                                        ⎥
+    ⎣0    sin(2⋅θ)     -cos(2⋅θ)        0    ⎦
+
+    """
+    A = Matrix([[1, 0, 0, 1],
+                [1, 0, 0, -1],
+                [0, 1, 1, 0],
+                [0, -I, I, 0]])
+
+    return simplify(A*TensorProduct(J, J.conjugate())*A.inv())
+
+
+def polarizing_beam_splitter(Tp=1, Rs=1, Ts=0, Rp=0, phia=0, phib=0):
+    r"""A polarizing beam splitter Jones matrix at angle `theta`.
+
+    Parameters
+    ==========
+
+    J : SymPy Matrix
+        A Jones matrix.
+    Tp : numeric type or SymPy Symbol
+        The transmissivity of the P-polarized component.
+    Rs : numeric type or SymPy Symbol
+        The reflectivity of the S-polarized component.
+    Ts : numeric type or SymPy Symbol
+        The transmissivity of the S-polarized component.
+    Rp : numeric type or SymPy Symbol
+        The reflectivity of the P-polarized component.
+    phia : numeric type or SymPy Symbol
+        The phase difference between transmitted and reflected component for
+        output mode a.
+    phib : numeric type or SymPy Symbol
+        The phase difference between transmitted and reflected component for
+        output mode b.
+
+
+    Returns
+    =======
+
+    SymPy Matrix
+        A 4x4 matrix representing the PBS. This matrix acts on a 4x1 vector
+        whose first two entries are the Jones vector on one of the PBS ports,
+        and the last two entries the Jones vector on the other port.
+
+    Examples
+    ========
+
+    Generic polarizing beam-splitter.
+
+    >>> from sympy import pprint, symbols
+    >>> from sympy.physics.optics.polarization import polarizing_beam_splitter
+    >>> Ts, Rs, Tp, Rp = symbols(r"Ts, Rs, Tp, Rp", positive=True)
+    >>> phia, phib = symbols("phi_a, phi_b", real=True)
+    >>> PBS = polarizing_beam_splitter(Tp, Rs, Ts, Rp, phia, phib)
+    >>> pprint(PBS, use_unicode=False)
+    [   ____                           ____                    ]
+    [ \/ Tp            0           I*\/ Rp           0         ]
+    [                                                          ]
+    [                  ____                       ____  I*phi_a]
+    [   0            \/ Ts            0      -I*\/ Rs *e       ]
+    [                                                          ]
+    [    ____                         ____                     ]
+    [I*\/ Rp           0            \/ Tp            0         ]
+    [                                                          ]
+    [               ____  I*phi_b                    ____      ]
+    [   0      -I*\/ Rs *e            0            \/ Ts       ]
+
+    """
+    PBS = Matrix([[sqrt(Tp), 0, I*sqrt(Rp), 0],
+                  [0, sqrt(Ts), 0, -I*sqrt(Rs)*exp(I*phia)],
+                  [I*sqrt(Rp), 0, sqrt(Tp), 0],
+                  [0, -I*sqrt(Rs)*exp(I*phib), 0, sqrt(Ts)]])
+    return PBS
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/tests/test_gaussopt.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/tests/test_gaussopt.py
new file mode 100644
index 0000000000000000000000000000000000000000..5271f3cbb69cf5de861ff332d36418b79daeb1b5
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/tests/test_gaussopt.py
@@ -0,0 +1,102 @@
+from sympy.core.evalf import N
+from sympy.core.numbers import (Float, I, oo, pi)
+from sympy.core.symbol import symbols
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import atan2
+from sympy.matrices.dense import Matrix
+from sympy.polys.polytools import factor
+
+from sympy.physics.optics import (BeamParameter, CurvedMirror,
+  CurvedRefraction, FlatMirror, FlatRefraction, FreeSpace, GeometricRay,
+  RayTransferMatrix, ThinLens, conjugate_gauss_beams,
+  gaussian_conj, geometric_conj_ab, geometric_conj_af, geometric_conj_bf,
+  rayleigh2waist, waist2rayleigh)
+
+
+def streq(a, b):
+    return str(a) == str(b)
+
+
+def test_gauss_opt():
+    mat = RayTransferMatrix(1, 2, 3, 4)
+    assert mat == Matrix([[1, 2], [3, 4]])
+    assert mat == RayTransferMatrix( Matrix([[1, 2], [3, 4]]) )
+    assert [mat.A, mat.B, mat.C, mat.D] == [1, 2, 3, 4]
+
+    d, f, h, n1, n2, R = symbols('d f h n1 n2 R')
+    lens = ThinLens(f)
+    assert lens == Matrix([[   1, 0], [-1/f, 1]])
+    assert lens.C == -1/f
+    assert FreeSpace(d) == Matrix([[ 1, d], [0, 1]])
+    assert FlatRefraction(n1, n2) == Matrix([[1, 0], [0, n1/n2]])
+    assert CurvedRefraction(
+        R, n1, n2) == Matrix([[1, 0], [(n1 - n2)/(R*n2), n1/n2]])
+    assert FlatMirror() == Matrix([[1, 0], [0, 1]])
+    assert CurvedMirror(R) == Matrix([[   1, 0], [-2/R, 1]])
+    assert ThinLens(f) == Matrix([[   1, 0], [-1/f, 1]])
+
+    mul = CurvedMirror(R)*FreeSpace(d)
+    mul_mat = Matrix([[   1, 0], [-2/R, 1]])*Matrix([[ 1, d], [0, 1]])
+    assert mul.A == mul_mat[0, 0]
+    assert mul.B == mul_mat[0, 1]
+    assert mul.C == mul_mat[1, 0]
+    assert mul.D == mul_mat[1, 1]
+
+    angle = symbols('angle')
+    assert GeometricRay(h, angle) == Matrix([[    h], [angle]])
+    assert FreeSpace(
+        d)*GeometricRay(h, angle) == Matrix([[angle*d + h], [angle]])
+    assert GeometricRay( Matrix( ((h,), (angle,)) ) ) == Matrix([[h], [angle]])
+    assert (FreeSpace(d)*GeometricRay(h, angle)).height == angle*d + h
+    assert (FreeSpace(d)*GeometricRay(h, angle)).angle == angle
+
+    p = BeamParameter(530e-9, 1, w=1e-3)
+    assert streq(p.q, 1 + 1.88679245283019*I*pi)
+    assert streq(N(p.q), 1.0 + 5.92753330865999*I)
+    assert streq(N(p.w_0), Float(0.00100000000000000))
+    assert streq(N(p.z_r), Float(5.92753330865999))
+    fs = FreeSpace(10)
+    p1 = fs*p
+    assert streq(N(p.w), Float(0.00101413072159615))
+    assert streq(N(p1.w), Float(0.00210803120913829))
+
+    w, wavelen = symbols('w wavelen')
+    assert waist2rayleigh(w, wavelen) == pi*w**2/wavelen
+    z_r, wavelen = symbols('z_r wavelen')
+    assert rayleigh2waist(z_r, wavelen) == sqrt(wavelen*z_r)/sqrt(pi)
+
+    a, b, f = symbols('a b f')
+    assert geometric_conj_ab(a, b) == a*b/(a + b)
+    assert geometric_conj_af(a, f) == a*f/(a - f)
+    assert geometric_conj_bf(b, f) == b*f/(b - f)
+    assert geometric_conj_ab(oo, b) == b
+    assert geometric_conj_ab(a, oo) == a
+
+    s_in, z_r_in, f = symbols('s_in z_r_in f')
+    assert gaussian_conj(
+        s_in, z_r_in, f)[0] == 1/(-1/(s_in + z_r_in**2/(-f + s_in)) + 1/f)
+    assert gaussian_conj(
+        s_in, z_r_in, f)[1] == z_r_in/(1 - s_in**2/f**2 + z_r_in**2/f**2)
+    assert gaussian_conj(
+        s_in, z_r_in, f)[2] == 1/sqrt(1 - s_in**2/f**2 + z_r_in**2/f**2)
+
+    l, w_i, w_o, f = symbols('l w_i w_o f')
+    assert conjugate_gauss_beams(l, w_i, w_o, f=f)[0] == f*(
+        -sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2)) + 1)
+    assert factor(conjugate_gauss_beams(l, w_i, w_o, f=f)[1]) == f*w_o**2*(
+        w_i**2/w_o**2 - sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2)))/w_i**2
+    assert conjugate_gauss_beams(l, w_i, w_o, f=f)[2] == f
+
+    z, l, w_0 = symbols('z l w_0', positive=True)
+    p = BeamParameter(l, z, w=w_0)
+    assert p.radius == z*(pi**2*w_0**4/(l**2*z**2) + 1)
+    assert p.w == w_0*sqrt(l**2*z**2/(pi**2*w_0**4) + 1)
+    assert p.w_0 == w_0
+    assert p.divergence == l/(pi*w_0)
+    assert p.gouy == atan2(z, pi*w_0**2/l)
+    assert p.waist_approximation_limit == 2*l/pi
+
+    p = BeamParameter(530e-9, 1, w=1e-3, n=2)
+    assert streq(p.q, 1 + 3.77358490566038*I*pi)
+    assert streq(N(p.z_r), Float(11.8550666173200))
+    assert streq(N(p.w_0), Float(0.00100000000000000))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/tests/test_medium.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/tests/test_medium.py
new file mode 100644
index 0000000000000000000000000000000000000000..dfbb485f5b8e401f38c7f1cfa573f960a2479d7b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/tests/test_medium.py
@@ -0,0 +1,48 @@
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.physics.optics import Medium
+from sympy.abc import epsilon, mu, n
+from sympy.physics.units import speed_of_light, u0, e0, m, kg, s, A
+
+from sympy.testing.pytest import raises
+
+c = speed_of_light.convert_to(m/s)
+e0 = e0.convert_to(A**2*s**4/(kg*m**3))
+u0 = u0.convert_to(m*kg/(A**2*s**2))
+
+
+def test_medium():
+    m1 = Medium('m1')
+    assert m1.intrinsic_impedance == sqrt(u0/e0)
+    assert m1.speed == 1/sqrt(e0*u0)
+    assert m1.refractive_index == c*sqrt(e0*u0)
+    assert m1.permittivity == e0
+    assert m1.permeability == u0
+    m2 = Medium('m2', epsilon, mu)
+    assert m2.intrinsic_impedance == sqrt(mu/epsilon)
+    assert m2.speed == 1/sqrt(epsilon*mu)
+    assert m2.refractive_index == c*sqrt(epsilon*mu)
+    assert m2.permittivity == epsilon
+    assert m2.permeability == mu
+    # Increasing electric permittivity and magnetic permeability
+    # by small amount from its value in vacuum.
+    m3 = Medium('m3', 9.0*10**(-12)*s**4*A**2/(m**3*kg), 1.45*10**(-6)*kg*m/(A**2*s**2))
+    assert m3.refractive_index > m1.refractive_index
+    assert m3 != m1
+    # Decreasing electric permittivity and magnetic permeability
+    # by small amount from its value in vacuum.
+    m4 = Medium('m4', 7.0*10**(-12)*s**4*A**2/(m**3*kg), 1.15*10**(-6)*kg*m/(A**2*s**2))
+    assert m4.refractive_index < m1.refractive_index
+    m5 = Medium('m5', permittivity=710*10**(-12)*s**4*A**2/(m**3*kg), n=1.33)
+    assert abs(m5.intrinsic_impedance - 6.24845417765552*kg*m**2/(A**2*s**3)) \
+                < 1e-12*kg*m**2/(A**2*s**3)
+    assert abs(m5.speed - 225407863.157895*m/s) < 1e-6*m/s
+    assert abs(m5.refractive_index - 1.33000000000000) < 1e-12
+    assert abs(m5.permittivity - 7.1e-10*A**2*s**4/(kg*m**3)) \
+                < 1e-20*A**2*s**4/(kg*m**3)
+    assert abs(m5.permeability - 2.77206575232851e-8*kg*m/(A**2*s**2)) \
+                < 1e-20*kg*m/(A**2*s**2)
+    m6 = Medium('m6', None, mu, n)
+    assert m6.permittivity == n**2/(c**2*mu)
+    # test for equality of refractive indices
+    assert Medium('m7').refractive_index == Medium('m8', e0, u0).refractive_index
+    raises(ValueError, lambda:Medium('m9', e0, u0, 2))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/tests/test_polarization.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/tests/test_polarization.py
new file mode 100644
index 0000000000000000000000000000000000000000..99c595d82a4a296066d5075f6182895a8de54d91
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/tests/test_polarization.py
@@ -0,0 +1,57 @@
+from sympy.physics.optics.polarization import (jones_vector, stokes_vector,
+    jones_2_stokes, linear_polarizer, phase_retarder, half_wave_retarder,
+    quarter_wave_retarder, transmissive_filter, reflective_filter,
+    mueller_matrix, polarizing_beam_splitter)
+from sympy.core.numbers import (I, pi)
+from sympy.core.singleton import S
+from sympy.core.symbol import symbols
+from sympy.functions.elementary.exponential import exp
+from sympy.matrices.dense import Matrix
+
+
+def test_polarization():
+    assert jones_vector(0, 0) == Matrix([1, 0])
+    assert jones_vector(pi/2, 0) == Matrix([0, 1])
+    #################################################################
+    assert stokes_vector(0, 0) == Matrix([1, 1, 0, 0])
+    assert stokes_vector(pi/2, 0) == Matrix([1, -1, 0, 0])
+    #################################################################
+    H = jones_vector(0, 0)
+    V = jones_vector(pi/2, 0)
+    D = jones_vector(pi/4, 0)
+    A = jones_vector(-pi/4, 0)
+    R = jones_vector(0, pi/4)
+    L = jones_vector(0, -pi/4)
+
+    res = [Matrix([1, 1, 0, 0]),
+           Matrix([1, -1, 0, 0]),
+           Matrix([1, 0, 1, 0]),
+           Matrix([1, 0, -1, 0]),
+           Matrix([1, 0, 0, 1]),
+           Matrix([1, 0, 0, -1])]
+
+    assert [jones_2_stokes(e) for e in [H, V, D, A, R, L]] == res
+    #################################################################
+    assert linear_polarizer(0) == Matrix([[1, 0], [0, 0]])
+    #################################################################
+    delta = symbols("delta", real=True)
+    res = Matrix([[exp(-I*delta/2), 0], [0, exp(I*delta/2)]])
+    assert phase_retarder(0, delta) == res
+    #################################################################
+    assert half_wave_retarder(0) == Matrix([[-I, 0], [0, I]])
+    #################################################################
+    res = Matrix([[exp(-I*pi/4), 0], [0, I*exp(-I*pi/4)]])
+    assert quarter_wave_retarder(0) == res
+    #################################################################
+    assert transmissive_filter(1) == Matrix([[1, 0], [0, 1]])
+    #################################################################
+    assert reflective_filter(1) == Matrix([[1, 0], [0, -1]])
+
+    res = Matrix([[S(1)/2, S(1)/2, 0, 0],
+                  [S(1)/2, S(1)/2, 0, 0],
+                  [0, 0, 0, 0],
+                  [0, 0, 0, 0]])
+    assert mueller_matrix(linear_polarizer(0)) == res
+    #################################################################
+    res = Matrix([[1, 0, 0, 0], [0, 0, 0, -I], [0, 0, 1, 0], [0, -I, 0, 0]])
+    assert polarizing_beam_splitter() == res
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/tests/test_utils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/tests/test_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c93883a081d3614a604aeadc8a4b617181de669
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/tests/test_utils.py
@@ -0,0 +1,202 @@
+from sympy.core.numbers import comp, Rational
+from sympy.physics.optics.utils import (refraction_angle, fresnel_coefficients,
+        deviation, brewster_angle, critical_angle, lens_makers_formula,
+        mirror_formula, lens_formula, hyperfocal_distance,
+        transverse_magnification)
+from sympy.physics.optics.medium import Medium
+from sympy.physics.units import e0
+
+from sympy.core.numbers import oo
+from sympy.core.symbol import symbols
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.matrices.dense import Matrix
+from sympy.geometry.point import Point3D
+from sympy.geometry.line import Ray3D
+from sympy.geometry.plane import Plane
+
+from sympy.testing.pytest import raises
+
+
+ae = lambda a, b, n: comp(a, b, 10**-n)
+
+
+def test_refraction_angle():
+    n1, n2 = symbols('n1, n2')
+    m1 = Medium('m1')
+    m2 = Medium('m2')
+    r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
+    i = Matrix([1, 1, 1])
+    n = Matrix([0, 0, 1])
+    normal_ray = Ray3D(Point3D(0, 0, 0), Point3D(0, 0, 1))
+    P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
+    assert refraction_angle(r1, 1, 1, n) == Matrix([
+                                            [ 1],
+                                            [ 1],
+                                            [-1]])
+    assert refraction_angle([1, 1, 1], 1, 1, n) == Matrix([
+                                            [ 1],
+                                            [ 1],
+                                            [-1]])
+    assert refraction_angle((1, 1, 1), 1, 1, n) == Matrix([
+                                            [ 1],
+                                            [ 1],
+                                            [-1]])
+    assert refraction_angle(i, 1, 1, [0, 0, 1]) == Matrix([
+                                            [ 1],
+                                            [ 1],
+                                            [-1]])
+    assert refraction_angle(i, 1, 1, (0, 0, 1)) == Matrix([
+                                            [ 1],
+                                            [ 1],
+                                            [-1]])
+    assert refraction_angle(i, 1, 1, normal_ray) == Matrix([
+                                            [ 1],
+                                            [ 1],
+                                            [-1]])
+    assert refraction_angle(i, 1, 1, plane=P) == Matrix([
+                                            [ 1],
+                                            [ 1],
+                                            [-1]])
+    assert refraction_angle(r1, 1, 1, plane=P) == \
+        Ray3D(Point3D(0, 0, 0), Point3D(1, 1, -1))
+    assert refraction_angle(r1, m1, 1.33, plane=P) == \
+        Ray3D(Point3D(0, 0, 0), Point3D(Rational(100, 133), Rational(100, 133), -789378201649271*sqrt(3)/1000000000000000))
+    assert refraction_angle(r1, 1, m2, plane=P) == \
+        Ray3D(Point3D(0, 0, 0), Point3D(1, 1, -1))
+    assert refraction_angle(r1, n1, n2, plane=P) == \
+        Ray3D(Point3D(0, 0, 0), Point3D(n1/n2, n1/n2, -sqrt(3)*sqrt(-2*n1**2/(3*n2**2) + 1)))
+    assert refraction_angle(r1, 1.33, 1, plane=P) == 0  # TIR
+    assert refraction_angle(r1, 1, 1, normal_ray) == \
+        Ray3D(Point3D(0, 0, 0), direction_ratio=[1, 1, -1])
+    assert ae(refraction_angle(0.5, 1, 2), 0.24207, 5)
+    assert ae(refraction_angle(0.5, 2, 1), 1.28293, 5)
+    raises(ValueError, lambda: refraction_angle(r1, m1, m2, normal_ray, P))
+    raises(TypeError, lambda: refraction_angle(m1, m1, m2)) # can add other values for arg[0]
+    raises(TypeError, lambda: refraction_angle(r1, m1, m2, None, i))
+    raises(TypeError, lambda: refraction_angle(r1, m1, m2, m2))
+
+
+def test_fresnel_coefficients():
+    assert all(ae(i, j, 5) for i, j in zip(
+        fresnel_coefficients(0.5, 1, 1.33),
+        [0.11163, -0.17138, 0.83581, 0.82862]))
+    assert all(ae(i, j, 5) for i, j in zip(
+        fresnel_coefficients(0.5, 1.33, 1),
+        [-0.07726, 0.20482, 1.22724, 1.20482]))
+    m1 = Medium('m1')
+    m2 = Medium('m2', n=2)
+    assert all(ae(i, j, 5) for i, j in zip(
+        fresnel_coefficients(0.3, m1, m2),
+        [0.31784, -0.34865, 0.65892, 0.65135]))
+    ans = [[-0.23563, -0.97184], [0.81648, -0.57738]]
+    got = fresnel_coefficients(0.6, m2, m1)
+    for i, j in zip(got, ans):
+        for a, b in zip(i.as_real_imag(), j):
+            assert ae(a, b, 5)
+
+
+def test_deviation():
+    n1, n2 = symbols('n1, n2')
+    r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
+    n = Matrix([0, 0, 1])
+    i = Matrix([-1, -1, -1])
+    normal_ray = Ray3D(Point3D(0, 0, 0), Point3D(0, 0, 1))
+    P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
+    assert deviation(r1, 1, 1, normal=n) == 0
+    assert deviation(r1, 1, 1, plane=P) == 0
+    assert deviation(r1, 1, 1.1, plane=P).evalf(3) + 0.119 < 1e-3
+    assert deviation(i, 1, 1.1, normal=normal_ray).evalf(3) + 0.119 < 1e-3
+    assert deviation(r1, 1.33, 1, plane=P) is None  # TIR
+    assert deviation(r1, 1, 1, normal=[0, 0, 1]) == 0
+    assert deviation([-1, -1, -1], 1, 1, normal=[0, 0, 1]) == 0
+    assert ae(deviation(0.5, 1, 2), -0.25793, 5)
+    assert ae(deviation(0.5, 2, 1), 0.78293, 5)
+
+
+def test_brewster_angle():
+    m1 = Medium('m1', n=1)
+    m2 = Medium('m2', n=1.33)
+    assert ae(brewster_angle(m1, m2), 0.93, 2)
+    m1 = Medium('m1', permittivity=e0, n=1)
+    m2 = Medium('m2', permittivity=e0, n=1.33)
+    assert ae(brewster_angle(m1, m2), 0.93, 2)
+    assert ae(brewster_angle(1, 1.33), 0.93, 2)
+
+
+def test_critical_angle():
+    m1 = Medium('m1', n=1)
+    m2 = Medium('m2', n=1.33)
+    assert ae(critical_angle(m2, m1), 0.85, 2)
+
+
+def test_lens_makers_formula():
+    n1, n2 = symbols('n1, n2')
+    m1 = Medium('m1', permittivity=e0, n=1)
+    m2 = Medium('m2', permittivity=e0, n=1.33)
+    assert lens_makers_formula(n1, n2, 10, -10) == 5.0*n2/(n1 - n2)
+    assert ae(lens_makers_formula(m1, m2, 10, -10), -20.15, 2)
+    assert ae(lens_makers_formula(1.33, 1, 10, -10),  15.15, 2)
+
+
+def test_mirror_formula():
+    u, v, f = symbols('u, v, f')
+    assert mirror_formula(focal_length=f, u=u) == f*u/(-f + u)
+    assert mirror_formula(focal_length=f, v=v) == f*v/(-f + v)
+    assert mirror_formula(u=u, v=v) == u*v/(u + v)
+    assert mirror_formula(u=oo, v=v) == v
+    assert mirror_formula(u=oo, v=oo) is oo
+    assert mirror_formula(focal_length=oo, u=u) == -u
+    assert mirror_formula(u=u, v=oo) == u
+    assert mirror_formula(focal_length=oo, v=oo) is oo
+    assert mirror_formula(focal_length=f, v=oo) == f
+    assert mirror_formula(focal_length=oo, v=v) == -v
+    assert mirror_formula(focal_length=oo, u=oo) is oo
+    assert mirror_formula(focal_length=f, u=oo) == f
+    assert mirror_formula(focal_length=oo, u=u) == -u
+    raises(ValueError, lambda: mirror_formula(focal_length=f, u=u, v=v))
+
+
+def test_lens_formula():
+    u, v, f = symbols('u, v, f')
+    assert lens_formula(focal_length=f, u=u) == f*u/(f + u)
+    assert lens_formula(focal_length=f, v=v) == f*v/(f - v)
+    assert lens_formula(u=u, v=v) == u*v/(u - v)
+    assert lens_formula(u=oo, v=v) == v
+    assert lens_formula(u=oo, v=oo) is oo
+    assert lens_formula(focal_length=oo, u=u) == u
+    assert lens_formula(u=u, v=oo) == -u
+    assert lens_formula(focal_length=oo, v=oo) is -oo
+    assert lens_formula(focal_length=oo, v=v) == v
+    assert lens_formula(focal_length=f, v=oo) == -f
+    assert lens_formula(focal_length=oo, u=oo) is oo
+    assert lens_formula(focal_length=oo, u=u) == u
+    assert lens_formula(focal_length=f, u=oo) == f
+    raises(ValueError, lambda: lens_formula(focal_length=f, u=u, v=v))
+
+
+def test_hyperfocal_distance():
+    f, N, c = symbols('f, N, c')
+    assert hyperfocal_distance(f=f, N=N, c=c) == f**2/(N*c)
+    assert ae(hyperfocal_distance(f=0.5, N=8, c=0.0033), 9.47, 2)
+
+
+def test_transverse_magnification():
+    si, so = symbols('si, so')
+    assert transverse_magnification(si, so) == -si/so
+    assert transverse_magnification(30, 15) == -2
+
+
+def test_lens_makers_formula_thick_lens():
+    n1, n2 = symbols('n1, n2')
+    m1 = Medium('m1', permittivity=e0, n=1)
+    m2 = Medium('m2', permittivity=e0, n=1.33)
+    assert ae(lens_makers_formula(m1, m2, 10, -10, d=1), -19.82, 2)
+    assert lens_makers_formula(n1, n2, 1, -1, d=0.1) == n2/((2.0 - (0.1*n1 - 0.1*n2)/n1)*(n1 - n2))
+
+
+def test_lens_makers_formula_plano_lens():
+    n1, n2 = symbols('n1, n2')
+    m1 = Medium('m1', permittivity=e0, n=1)
+    m2 = Medium('m2', permittivity=e0, n=1.33)
+    assert ae(lens_makers_formula(m1, m2, 10, oo), -40.30, 2)
+    assert lens_makers_formula(n1, n2, 10, oo) == 10.0*n2/(n1 - n2)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/tests/test_waves.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/tests/test_waves.py
new file mode 100644
index 0000000000000000000000000000000000000000..3cb8f804fb5be86d6174cb7c7b15fd8979c85ff8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/tests/test_waves.py
@@ -0,0 +1,82 @@
+from sympy.core.function import (Derivative, Function)
+from sympy.core.numbers import (I, pi)
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import (atan2, cos, sin)
+from sympy.simplify.simplify import simplify
+from sympy.abc import epsilon, mu
+from sympy.functions.elementary.exponential import exp
+from sympy.physics.units import speed_of_light, m, s
+from sympy.physics.optics import TWave
+
+from sympy.testing.pytest import raises
+
+c = speed_of_light.convert_to(m/s)
+
+def test_twave():
+    A1, phi1, A2, phi2, f = symbols('A1, phi1, A2, phi2, f')
+    n = Symbol('n')  # Refractive index
+    t = Symbol('t')  # Time
+    x = Symbol('x')  # Spatial variable
+    E = Function('E')
+    w1 = TWave(A1, f, phi1)
+    w2 = TWave(A2, f, phi2)
+    assert w1.amplitude == A1
+    assert w1.frequency == f
+    assert w1.phase == phi1
+    assert w1.wavelength == c/(f*n)
+    assert w1.time_period == 1/f
+    assert w1.angular_velocity == 2*pi*f
+    assert w1.wavenumber == 2*pi*f*n/c
+    assert w1.speed == c/n
+
+    w3 = w1 + w2
+    assert w3.amplitude == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)
+    assert w3.frequency == f
+    assert w3.phase == atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2))
+    assert w3.wavelength == c/(f*n)
+    assert w3.time_period == 1/f
+    assert w3.angular_velocity == 2*pi*f
+    assert w3.wavenumber == 2*pi*f*n/c
+    assert w3.speed == c/n
+    assert simplify(w3.rewrite(sin) - w2.rewrite(sin) - w1.rewrite(sin)) == 0
+    assert w3.rewrite('pde') == epsilon*mu*Derivative(E(x, t), t, t) + Derivative(E(x, t), x, x)
+    assert w3.rewrite(cos) == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2)
+        + A2**2)*cos(pi*f*n*x*s/(149896229*m) - 2*pi*f*t + atan2(A1*sin(phi1)
+        + A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2)))
+    assert w3.rewrite(exp) == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2)
+        + A2**2)*exp(I*(-2*pi*f*t + atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1)
+        + A2*cos(phi2)) + pi*s*f*n*x/(149896229*m)))
+
+    w4 = TWave(A1, None, 0, 1/f)
+    assert w4.frequency == f
+
+    w5 = w1 - w2
+    assert w5.amplitude == sqrt(A1**2 - 2*A1*A2*cos(phi1 - phi2) + A2**2)
+    assert w5.frequency == f
+    assert w5.phase == atan2(A1*sin(phi1) - A2*sin(phi2), A1*cos(phi1) - A2*cos(phi2))
+    assert w5.wavelength == c/(f*n)
+    assert w5.time_period == 1/f
+    assert w5.angular_velocity == 2*pi*f
+    assert w5.wavenumber == 2*pi*f*n/c
+    assert w5.speed == c/n
+    assert simplify(w5.rewrite(sin) - w1.rewrite(sin) + w2.rewrite(sin)) == 0
+    assert w5.rewrite('pde') == epsilon*mu*Derivative(E(x, t), t, t) + Derivative(E(x, t), x, x)
+    assert w5.rewrite(cos) == sqrt(A1**2 - 2*A1*A2*cos(phi1 - phi2)
+        + A2**2)*cos(-2*pi*f*t + atan2(A1*sin(phi1) - A2*sin(phi2), A1*cos(phi1)
+        - A2*cos(phi2)) + pi*s*f*n*x/(149896229*m))
+    assert w5.rewrite(exp) == sqrt(A1**2 - 2*A1*A2*cos(phi1 - phi2)
+        + A2**2)*exp(I*(-2*pi*f*t + atan2(A1*sin(phi1) - A2*sin(phi2), A1*cos(phi1)
+        - A2*cos(phi2)) + pi*s*f*n*x/(149896229*m)))
+
+    w6 = 2*w1
+    assert w6.amplitude == 2*A1
+    assert w6.frequency == f
+    assert w6.phase == phi1
+    w7 = -w6
+    assert w7.amplitude == -2*A1
+    assert w7.frequency == f
+    assert w7.phase == phi1
+
+    raises(ValueError, lambda:TWave(A1))
+    raises(ValueError, lambda:TWave(A1, f, phi1, t))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/utils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..72c3b78bd4b09eb069757fb3f8d3632f09ec4b80
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/utils.py
@@ -0,0 +1,698 @@
+"""
+**Contains**
+
+* refraction_angle
+* fresnel_coefficients
+* deviation
+* brewster_angle
+* critical_angle
+* lens_makers_formula
+* mirror_formula
+* lens_formula
+* hyperfocal_distance
+* transverse_magnification
+"""
+
+__all__ = ['refraction_angle',
+           'deviation',
+           'fresnel_coefficients',
+           'brewster_angle',
+           'critical_angle',
+           'lens_makers_formula',
+           'mirror_formula',
+           'lens_formula',
+           'hyperfocal_distance',
+           'transverse_magnification'
+           ]
+
+from sympy.core.numbers import (Float, I, oo, pi, zoo)
+from sympy.core.singleton import S
+from sympy.core.symbol import Symbol
+from sympy.core.sympify import sympify
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import (acos, asin, atan2, cos, sin, tan)
+from sympy.matrices.dense import Matrix
+from sympy.polys.polytools import cancel
+from sympy.series.limits import Limit
+from sympy.geometry.line import Ray3D
+from sympy.geometry.util import intersection
+from sympy.geometry.plane import Plane
+from sympy.utilities.iterables import is_sequence
+from .medium import Medium
+
+
+def refractive_index_of_medium(medium):
+    """
+    Helper function that returns refractive index, given a medium
+    """
+    if isinstance(medium, Medium):
+        n = medium.refractive_index
+    else:
+        n = sympify(medium)
+    return n
+
+
+def refraction_angle(incident, medium1, medium2, normal=None, plane=None):
+    """
+    This function calculates transmitted vector after refraction at planar
+    surface. ``medium1`` and ``medium2`` can be ``Medium`` or any sympifiable object.
+    If ``incident`` is a number then treated as angle of incidence (in radians)
+    in which case refraction angle is returned.
+
+    If ``incident`` is an object of `Ray3D`, `normal` also has to be an instance
+    of `Ray3D` in order to get the output as a `Ray3D`. Please note that if
+    plane of separation is not provided and normal is an instance of `Ray3D`,
+    ``normal`` will be assumed to be intersecting incident ray at the plane of
+    separation. This will not be the case when `normal` is a `Matrix` or
+    any other sequence.
+    If ``incident`` is an instance of `Ray3D` and `plane` has not been provided
+    and ``normal`` is not `Ray3D`, output will be a `Matrix`.
+
+    Parameters
+    ==========
+
+    incident : Matrix, Ray3D, sequence or a number
+        Incident vector or angle of incidence
+    medium1 : sympy.physics.optics.medium.Medium or sympifiable
+        Medium 1 or its refractive index
+    medium2 : sympy.physics.optics.medium.Medium or sympifiable
+        Medium 2 or its refractive index
+    normal : Matrix, Ray3D, or sequence
+        Normal vector
+    plane : Plane
+        Plane of separation of the two media.
+
+    Returns
+    =======
+
+    Returns an angle of refraction or a refracted ray depending on inputs.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import refraction_angle
+    >>> from sympy.geometry import Point3D, Ray3D, Plane
+    >>> from sympy.matrices import Matrix
+    >>> from sympy import symbols, pi
+    >>> n = Matrix([0, 0, 1])
+    >>> P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
+    >>> r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
+    >>> refraction_angle(r1, 1, 1, n)
+    Matrix([
+    [ 1],
+    [ 1],
+    [-1]])
+    >>> refraction_angle(r1, 1, 1, plane=P)
+    Ray3D(Point3D(0, 0, 0), Point3D(1, 1, -1))
+
+    With different index of refraction of the two media
+
+    >>> n1, n2 = symbols('n1, n2')
+    >>> refraction_angle(r1, n1, n2, n)
+    Matrix([
+    [                                n1/n2],
+    [                                n1/n2],
+    [-sqrt(3)*sqrt(-2*n1**2/(3*n2**2) + 1)]])
+    >>> refraction_angle(r1, n1, n2, plane=P)
+    Ray3D(Point3D(0, 0, 0), Point3D(n1/n2, n1/n2, -sqrt(3)*sqrt(-2*n1**2/(3*n2**2) + 1)))
+    >>> round(refraction_angle(pi/6, 1.2, 1.5), 5)
+    0.41152
+    """
+
+    n1 = refractive_index_of_medium(medium1)
+    n2 = refractive_index_of_medium(medium2)
+
+    # check if an incidence angle was supplied instead of a ray
+    try:
+        angle_of_incidence = float(incident)
+    except TypeError:
+        angle_of_incidence = None
+
+    try:
+        critical_angle_ = critical_angle(medium1, medium2)
+    except (ValueError, TypeError):
+        critical_angle_ = None
+
+    if angle_of_incidence is not None:
+        if normal is not None or plane is not None:
+            raise ValueError('Normal/plane not allowed if incident is an angle')
+
+        if not 0.0 <= angle_of_incidence < pi*0.5:
+            raise ValueError('Angle of incidence not in range [0:pi/2)')
+
+        if critical_angle_ and angle_of_incidence > critical_angle_:
+            raise ValueError('Ray undergoes total internal reflection')
+        return asin(n1*sin(angle_of_incidence)/n2)
+
+    # Treat the incident as ray below
+    # A flag to check whether to return Ray3D or not
+    return_ray = False
+
+    if plane is not None and normal is not None:
+        raise ValueError("Either plane or normal is acceptable.")
+
+    if not isinstance(incident, Matrix):
+        if is_sequence(incident):
+            _incident = Matrix(incident)
+        elif isinstance(incident, Ray3D):
+            _incident = Matrix(incident.direction_ratio)
+        else:
+            raise TypeError(
+                "incident should be a Matrix, Ray3D, or sequence")
+    else:
+        _incident = incident
+
+    # If plane is provided, get direction ratios of the normal
+    # to the plane from the plane else go with `normal` param.
+    if plane is not None:
+        if not isinstance(plane, Plane):
+            raise TypeError("plane should be an instance of geometry.plane.Plane")
+        # If we have the plane, we can get the intersection
+        # point of incident ray and the plane and thus return
+        # an instance of Ray3D.
+        if isinstance(incident, Ray3D):
+            return_ray = True
+            intersection_pt = plane.intersection(incident)[0]
+        _normal = Matrix(plane.normal_vector)
+    else:
+        if not isinstance(normal, Matrix):
+            if is_sequence(normal):
+                _normal = Matrix(normal)
+            elif isinstance(normal, Ray3D):
+                _normal = Matrix(normal.direction_ratio)
+                if isinstance(incident, Ray3D):
+                    intersection_pt = intersection(incident, normal)
+                    if len(intersection_pt) == 0:
+                        raise ValueError(
+                            "Normal isn't concurrent with the incident ray.")
+                    else:
+                        return_ray = True
+                        intersection_pt = intersection_pt[0]
+            else:
+                raise TypeError(
+                    "Normal should be a Matrix, Ray3D, or sequence")
+        else:
+            _normal = normal
+
+    eta = n1/n2  # Relative index of refraction
+    # Calculating magnitude of the vectors
+    mag_incident = sqrt(sum(i**2 for i in _incident))
+    mag_normal = sqrt(sum(i**2 for i in _normal))
+    # Converting vectors to unit vectors by dividing
+    # them with their magnitudes
+    _incident /= mag_incident
+    _normal /= mag_normal
+    c1 = -_incident.dot(_normal)  # cos(angle_of_incidence)
+    cs2 = 1 - eta**2*(1 - c1**2)  # cos(angle_of_refraction)**2
+    if cs2.is_negative:  # This is the case of total internal reflection(TIR).
+        return S.Zero
+    drs = eta*_incident + (eta*c1 - sqrt(cs2))*_normal
+    # Multiplying unit vector by its magnitude
+    drs = drs*mag_incident
+    if not return_ray:
+        return drs
+    else:
+        return Ray3D(intersection_pt, direction_ratio=drs)
+
+
+def fresnel_coefficients(angle_of_incidence, medium1, medium2):
+    """
+    This function uses Fresnel equations to calculate reflection and
+    transmission coefficients. Those are obtained for both polarisations
+    when the electric field vector is in the plane of incidence (labelled 'p')
+    and when the electric field vector is perpendicular to the plane of
+    incidence (labelled 's'). There are four real coefficients unless the
+    incident ray reflects in total internal in which case there are two complex
+    ones. Angle of incidence is the angle between the incident ray and the
+    surface normal. ``medium1`` and ``medium2`` can be ``Medium`` or any
+    sympifiable object.
+
+    Parameters
+    ==========
+
+    angle_of_incidence : sympifiable
+
+    medium1 : Medium or sympifiable
+        Medium 1 or its refractive index
+
+    medium2 : Medium or sympifiable
+        Medium 2 or its refractive index
+
+    Returns
+    =======
+
+    Returns a list with four real Fresnel coefficients:
+    [reflection p (TM), reflection s (TE),
+    transmission p (TM), transmission s (TE)]
+    If the ray is undergoes total internal reflection then returns a
+    list of two complex Fresnel coefficients:
+    [reflection p (TM), reflection s (TE)]
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import fresnel_coefficients
+    >>> fresnel_coefficients(0.3, 1, 2)
+    [0.317843553417859, -0.348645229818821,
+            0.658921776708929, 0.651354770181179]
+    >>> fresnel_coefficients(0.6, 2, 1)
+    [-0.235625382192159 - 0.971843958291041*I,
+             0.816477005968898 - 0.577377951366403*I]
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Fresnel_equations
+    """
+    if not 0 <= 2*angle_of_incidence < pi:
+        raise ValueError('Angle of incidence not in range [0:pi/2)')
+
+    n1 = refractive_index_of_medium(medium1)
+    n2 = refractive_index_of_medium(medium2)
+
+    angle_of_refraction = asin(n1*sin(angle_of_incidence)/n2)
+    try:
+        angle_of_total_internal_reflection_onset = critical_angle(n1, n2)
+    except ValueError:
+        angle_of_total_internal_reflection_onset = None
+
+    if angle_of_total_internal_reflection_onset is None or\
+    angle_of_total_internal_reflection_onset > angle_of_incidence:
+        R_s = -sin(angle_of_incidence - angle_of_refraction)\
+                /sin(angle_of_incidence + angle_of_refraction)
+        R_p = tan(angle_of_incidence - angle_of_refraction)\
+                /tan(angle_of_incidence + angle_of_refraction)
+        T_s = 2*sin(angle_of_refraction)*cos(angle_of_incidence)\
+                /sin(angle_of_incidence + angle_of_refraction)
+        T_p = 2*sin(angle_of_refraction)*cos(angle_of_incidence)\
+                /(sin(angle_of_incidence + angle_of_refraction)\
+                *cos(angle_of_incidence - angle_of_refraction))
+        return [R_p, R_s, T_p, T_s]
+    else:
+        n = n2/n1
+        R_s = cancel((cos(angle_of_incidence)-\
+                I*sqrt(sin(angle_of_incidence)**2 - n**2))\
+                /(cos(angle_of_incidence)+\
+                I*sqrt(sin(angle_of_incidence)**2 - n**2)))
+        R_p = cancel((n**2*cos(angle_of_incidence)-\
+                I*sqrt(sin(angle_of_incidence)**2 - n**2))\
+                /(n**2*cos(angle_of_incidence)+\
+                I*sqrt(sin(angle_of_incidence)**2 - n**2)))
+        return [R_p, R_s]
+
+
+def deviation(incident, medium1, medium2, normal=None, plane=None):
+    """
+    This function calculates the angle of deviation of a ray
+    due to refraction at planar surface.
+
+    Parameters
+    ==========
+
+    incident : Matrix, Ray3D, sequence or float
+        Incident vector or angle of incidence
+    medium1 : sympy.physics.optics.medium.Medium or sympifiable
+        Medium 1 or its refractive index
+    medium2 : sympy.physics.optics.medium.Medium or sympifiable
+        Medium 2 or its refractive index
+    normal : Matrix, Ray3D, or sequence
+        Normal vector
+    plane : Plane
+        Plane of separation of the two media.
+
+    Returns angular deviation between incident and refracted rays
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import deviation
+    >>> from sympy.geometry import Point3D, Ray3D, Plane
+    >>> from sympy.matrices import Matrix
+    >>> from sympy import symbols
+    >>> n1, n2 = symbols('n1, n2')
+    >>> n = Matrix([0, 0, 1])
+    >>> P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
+    >>> r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
+    >>> deviation(r1, 1, 1, n)
+    0
+    >>> deviation(r1, n1, n2, plane=P)
+    -acos(-sqrt(-2*n1**2/(3*n2**2) + 1)) + acos(-sqrt(3)/3)
+    >>> round(deviation(0.1, 1.2, 1.5), 5)
+    -0.02005
+    """
+    refracted = refraction_angle(incident,
+                                 medium1,
+                                 medium2,
+                                 normal=normal,
+                                 plane=plane)
+    try:
+        angle_of_incidence = Float(incident)
+    except TypeError:
+        angle_of_incidence = None
+
+    if angle_of_incidence is not None:
+        return float(refracted) - angle_of_incidence
+
+    if refracted != 0:
+        if isinstance(refracted, Ray3D):
+            refracted = Matrix(refracted.direction_ratio)
+
+        if not isinstance(incident, Matrix):
+            if is_sequence(incident):
+                _incident = Matrix(incident)
+            elif isinstance(incident, Ray3D):
+                _incident = Matrix(incident.direction_ratio)
+            else:
+                raise TypeError(
+                    "incident should be a Matrix, Ray3D, or sequence")
+        else:
+            _incident = incident
+
+        if plane is None:
+            if not isinstance(normal, Matrix):
+                if is_sequence(normal):
+                    _normal = Matrix(normal)
+                elif isinstance(normal, Ray3D):
+                    _normal = Matrix(normal.direction_ratio)
+                else:
+                    raise TypeError(
+                        "normal should be a Matrix, Ray3D, or sequence")
+            else:
+                _normal = normal
+        else:
+            _normal = Matrix(plane.normal_vector)
+
+        mag_incident = sqrt(sum(i**2 for i in _incident))
+        mag_normal = sqrt(sum(i**2 for i in _normal))
+        mag_refracted = sqrt(sum(i**2 for i in refracted))
+        _incident /= mag_incident
+        _normal /= mag_normal
+        refracted /= mag_refracted
+        i = acos(_incident.dot(_normal))
+        r = acos(refracted.dot(_normal))
+        return i - r
+
+
+def brewster_angle(medium1, medium2):
+    """
+    This function calculates the Brewster's angle of incidence to Medium 2 from
+    Medium 1 in radians.
+
+    Parameters
+    ==========
+
+    medium 1 : Medium or sympifiable
+        Refractive index of Medium 1
+    medium 2 : Medium or sympifiable
+        Refractive index of Medium 1
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import brewster_angle
+    >>> brewster_angle(1, 1.33)
+    0.926093295503462
+
+    """
+
+    n1 = refractive_index_of_medium(medium1)
+    n2 = refractive_index_of_medium(medium2)
+
+    return atan2(n2, n1)
+
+def critical_angle(medium1, medium2):
+    """
+    This function calculates the critical angle of incidence (marking the onset
+    of total internal) to Medium 2 from Medium 1 in radians.
+
+    Parameters
+    ==========
+
+    medium 1 : Medium or sympifiable
+        Refractive index of Medium 1.
+    medium 2 : Medium or sympifiable
+        Refractive index of Medium 1.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import critical_angle
+    >>> critical_angle(1.33, 1)
+    0.850908514477849
+
+    """
+
+    n1 = refractive_index_of_medium(medium1)
+    n2 = refractive_index_of_medium(medium2)
+
+    if n2 > n1:
+        raise ValueError('Total internal reflection impossible for n1 < n2')
+    else:
+        return asin(n2/n1)
+
+
+
+def lens_makers_formula(n_lens, n_surr, r1, r2, d=0):
+    """
+    This function calculates focal length of a lens.
+    It follows cartesian sign convention.
+
+    Parameters
+    ==========
+
+    n_lens : Medium or sympifiable
+        Index of refraction of lens.
+    n_surr : Medium or sympifiable
+        Index of reflection of surrounding.
+    r1 : sympifiable
+        Radius of curvature of first surface.
+    r2 : sympifiable
+        Radius of curvature of second surface.
+    d : sympifiable, optional
+        Thickness of lens, default value is 0.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import lens_makers_formula
+    >>> from sympy import S
+    >>> lens_makers_formula(1.33, 1, 10, -10)
+    15.1515151515151
+    >>> lens_makers_formula(1.2, 1, 10, S.Infinity)
+    50.0000000000000
+    >>> lens_makers_formula(1.33, 1, 10, -10, d=1)
+    15.3418463277618
+
+    """
+
+    if isinstance(n_lens, Medium):
+        n_lens = n_lens.refractive_index
+    else:
+        n_lens = sympify(n_lens)
+    if isinstance(n_surr, Medium):
+        n_surr = n_surr.refractive_index
+    else:
+        n_surr = sympify(n_surr)
+    d = sympify(d)
+
+    focal_length = 1/((n_lens - n_surr) / n_surr*(1/r1 - 1/r2 + (((n_lens - n_surr) * d) / (n_lens * r1 * r2))))
+
+    if focal_length == zoo:
+        return S.Infinity
+    return focal_length
+
+
+def mirror_formula(focal_length=None, u=None, v=None):
+    """
+    This function provides one of the three parameters
+    when two of them are supplied.
+    This is valid only for paraxial rays.
+
+    Parameters
+    ==========
+
+    focal_length : sympifiable
+        Focal length of the mirror.
+    u : sympifiable
+        Distance of object from the pole on
+        the principal axis.
+    v : sympifiable
+        Distance of the image from the pole
+        on the principal axis.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import mirror_formula
+    >>> from sympy.abc import f, u, v
+    >>> mirror_formula(focal_length=f, u=u)
+    f*u/(-f + u)
+    >>> mirror_formula(focal_length=f, v=v)
+    f*v/(-f + v)
+    >>> mirror_formula(u=u, v=v)
+    u*v/(u + v)
+
+    """
+    if focal_length and u and v:
+        raise ValueError("Please provide only two parameters")
+
+    focal_length = sympify(focal_length)
+    u = sympify(u)
+    v = sympify(v)
+    if u is oo:
+        _u = Symbol('u')
+    if v is oo:
+        _v = Symbol('v')
+    if focal_length is oo:
+        _f = Symbol('f')
+    if focal_length is None:
+        if u is oo and v is oo:
+            return Limit(Limit(_v*_u/(_v + _u), _u, oo), _v, oo).doit()
+        if u is oo:
+            return Limit(v*_u/(v + _u), _u, oo).doit()
+        if v is oo:
+            return Limit(_v*u/(_v + u), _v, oo).doit()
+        return v*u/(v + u)
+    if u is None:
+        if v is oo and focal_length is oo:
+            return Limit(Limit(_v*_f/(_v - _f), _v, oo), _f, oo).doit()
+        if v is oo:
+            return Limit(_v*focal_length/(_v - focal_length), _v, oo).doit()
+        if focal_length is oo:
+            return Limit(v*_f/(v - _f), _f, oo).doit()
+        return v*focal_length/(v - focal_length)
+    if v is None:
+        if u is oo and focal_length is oo:
+            return Limit(Limit(_u*_f/(_u - _f), _u, oo), _f, oo).doit()
+        if u is oo:
+            return Limit(_u*focal_length/(_u - focal_length), _u, oo).doit()
+        if focal_length is oo:
+            return Limit(u*_f/(u - _f), _f, oo).doit()
+        return u*focal_length/(u - focal_length)
+
+
+def lens_formula(focal_length=None, u=None, v=None):
+    """
+    This function provides one of the three parameters
+    when two of them are supplied.
+    This is valid only for paraxial rays.
+
+    Parameters
+    ==========
+
+    focal_length : sympifiable
+        Focal length of the mirror.
+    u : sympifiable
+        Distance of object from the optical center on
+        the principal axis.
+    v : sympifiable
+        Distance of the image from the optical center
+        on the principal axis.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.optics import lens_formula
+    >>> from sympy.abc import f, u, v
+    >>> lens_formula(focal_length=f, u=u)
+    f*u/(f + u)
+    >>> lens_formula(focal_length=f, v=v)
+    f*v/(f - v)
+    >>> lens_formula(u=u, v=v)
+    u*v/(u - v)
+
+    """
+    if focal_length and u and v:
+        raise ValueError("Please provide only two parameters")
+
+    focal_length = sympify(focal_length)
+    u = sympify(u)
+    v = sympify(v)
+    if u is oo:
+        _u = Symbol('u')
+    if v is oo:
+        _v = Symbol('v')
+    if focal_length is oo:
+        _f = Symbol('f')
+    if focal_length is None:
+        if u is oo and v is oo:
+            return Limit(Limit(_v*_u/(_u - _v), _u, oo), _v, oo).doit()
+        if u is oo:
+            return Limit(v*_u/(_u - v), _u, oo).doit()
+        if v is oo:
+            return Limit(_v*u/(u - _v), _v, oo).doit()
+        return v*u/(u - v)
+    if u is None:
+        if v is oo and focal_length is oo:
+            return Limit(Limit(_v*_f/(_f - _v), _v, oo), _f, oo).doit()
+        if v is oo:
+            return Limit(_v*focal_length/(focal_length - _v), _v, oo).doit()
+        if focal_length is oo:
+            return Limit(v*_f/(_f - v), _f, oo).doit()
+        return v*focal_length/(focal_length - v)
+    if v is None:
+        if u is oo and focal_length is oo:
+            return Limit(Limit(_u*_f/(_u + _f), _u, oo), _f, oo).doit()
+        if u is oo:
+            return Limit(_u*focal_length/(_u + focal_length), _u, oo).doit()
+        if focal_length is oo:
+            return Limit(u*_f/(u + _f), _f, oo).doit()
+        return u*focal_length/(u + focal_length)
+
+def hyperfocal_distance(f, N, c):
+    """
+
+    Parameters
+    ==========
+
+    f: sympifiable
+        Focal length of a given lens.
+
+    N: sympifiable
+        F-number of a given lens.
+
+    c: sympifiable
+        Circle of Confusion (CoC) of a given image format.
+
+    Example
+    =======
+
+    >>> from sympy.physics.optics import hyperfocal_distance
+    >>> round(hyperfocal_distance(f = 0.5, N = 8, c = 0.0033), 2)
+    9.47
+    """
+
+    f = sympify(f)
+    N = sympify(N)
+    c = sympify(c)
+
+    return (1/(N * c))*(f**2)
+
+def transverse_magnification(si, so):
+    """
+
+    Calculates the transverse magnification upon reflection in a mirror,
+    which is the ratio of the image size to the object size.
+
+    Parameters
+    ==========
+
+    so: sympifiable
+        Lens-object distance.
+
+    si: sympifiable
+        Lens-image distance.
+
+    Example
+    =======
+
+    >>> from sympy.physics.optics import transverse_magnification
+    >>> transverse_magnification(30, 15)
+    -2
+
+    """
+
+    si = sympify(si)
+    so = sympify(so)
+
+    return (-(si/so))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/waves.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/waves.py
new file mode 100644
index 0000000000000000000000000000000000000000..61e2ff4db578543f9f2694f239f03439bfab2c41
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/optics/waves.py
@@ -0,0 +1,340 @@
+"""
+This module has all the classes and functions related to waves in optics.
+
+**Contains**
+
+* TWave
+"""
+
+__all__ = ['TWave']
+
+from sympy.core.basic import Basic
+from sympy.core.expr import Expr
+from sympy.core.function import Derivative, Function
+from sympy.core.numbers import (Number, pi, I)
+from sympy.core.singleton import S
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.core.sympify import _sympify, sympify
+from sympy.functions.elementary.exponential import exp
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import (atan2, cos, sin)
+from sympy.physics.units import speed_of_light, meter, second
+
+
+c = speed_of_light.convert_to(meter/second)
+
+
+class TWave(Expr):
+
+    r"""
+    This is a simple transverse sine wave travelling in a one-dimensional space.
+    Basic properties are required at the time of creation of the object,
+    but they can be changed later with respective methods provided.
+
+    Explanation
+    ===========
+
+    It is represented as :math:`A \times cos(k*x - \omega \times t + \phi )`,
+    where :math:`A` is the amplitude, :math:`\omega` is the angular frequency,
+    :math:`k` is the wavenumber (spatial frequency), :math:`x` is a spatial variable
+    to represent the position on the dimension on which the wave propagates,
+    and :math:`\phi` is the phase angle of the wave.
+
+
+    Arguments
+    =========
+
+    amplitude : Sympifyable
+        Amplitude of the wave.
+    frequency : Sympifyable
+        Frequency of the wave.
+    phase : Sympifyable
+        Phase angle of the wave.
+    time_period : Sympifyable
+        Time period of the wave.
+    n : Sympifyable
+        Refractive index of the medium.
+
+    Raises
+    =======
+
+    ValueError : When neither frequency nor time period is provided
+        or they are not consistent.
+    TypeError : When anything other than TWave objects is added.
+
+
+    Examples
+    ========
+
+    >>> from sympy import symbols
+    >>> from sympy.physics.optics import TWave
+    >>> A1, phi1, A2, phi2, f = symbols('A1, phi1, A2, phi2, f')
+    >>> w1 = TWave(A1, f, phi1)
+    >>> w2 = TWave(A2, f, phi2)
+    >>> w3 = w1 + w2  # Superposition of two waves
+    >>> w3
+    TWave(sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2), f,
+        atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2)), 1/f, n)
+    >>> w3.amplitude
+    sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)
+    >>> w3.phase
+    atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2))
+    >>> w3.speed
+    299792458*meter/(second*n)
+    >>> w3.angular_velocity
+    2*pi*f
+
+    """
+
+    def __new__(
+            cls,
+            amplitude,
+            frequency=None,
+            phase=S.Zero,
+            time_period=None,
+            n=Symbol('n')):
+        if time_period is not None:
+            time_period = _sympify(time_period)
+            _frequency = S.One/time_period
+        if frequency is not None:
+            frequency = _sympify(frequency)
+            _time_period = S.One/frequency
+            if time_period is not None:
+                if frequency != S.One/time_period:
+                    raise ValueError("frequency and time_period should be consistent.")
+        if frequency is None and time_period is None:
+            raise ValueError("Either frequency or time period is needed.")
+        if frequency is None:
+            frequency = _frequency
+        if time_period is None:
+            time_period = _time_period
+
+        amplitude = _sympify(amplitude)
+        phase = _sympify(phase)
+        n = sympify(n)
+        obj = Basic.__new__(cls, amplitude, frequency, phase, time_period, n)
+        return obj
+
+    @property
+    def amplitude(self):
+        """
+        Returns the amplitude of the wave.
+
+        Examples
+        ========
+
+        >>> from sympy import symbols
+        >>> from sympy.physics.optics import TWave
+        >>> A, phi, f = symbols('A, phi, f')
+        >>> w = TWave(A, f, phi)
+        >>> w.amplitude
+        A
+        """
+        return self.args[0]
+
+    @property
+    def frequency(self):
+        """
+        Returns the frequency of the wave,
+        in cycles per second.
+
+        Examples
+        ========
+
+        >>> from sympy import symbols
+        >>> from sympy.physics.optics import TWave
+        >>> A, phi, f = symbols('A, phi, f')
+        >>> w = TWave(A, f, phi)
+        >>> w.frequency
+        f
+        """
+        return self.args[1]
+
+    @property
+    def phase(self):
+        """
+        Returns the phase angle of the wave,
+        in radians.
+
+        Examples
+        ========
+
+        >>> from sympy import symbols
+        >>> from sympy.physics.optics import TWave
+        >>> A, phi, f = symbols('A, phi, f')
+        >>> w = TWave(A, f, phi)
+        >>> w.phase
+        phi
+        """
+        return self.args[2]
+
+    @property
+    def time_period(self):
+        """
+        Returns the temporal period of the wave,
+        in seconds per cycle.
+
+        Examples
+        ========
+
+        >>> from sympy import symbols
+        >>> from sympy.physics.optics import TWave
+        >>> A, phi, f = symbols('A, phi, f')
+        >>> w = TWave(A, f, phi)
+        >>> w.time_period
+        1/f
+        """
+        return self.args[3]
+
+    @property
+    def n(self):
+        """
+        Returns the refractive index of the medium
+        """
+        return self.args[4]
+
+    @property
+    def wavelength(self):
+        """
+        Returns the wavelength (spatial period) of the wave,
+        in meters per cycle.
+        It depends on the medium of the wave.
+
+        Examples
+        ========
+
+        >>> from sympy import symbols
+        >>> from sympy.physics.optics import TWave
+        >>> A, phi, f = symbols('A, phi, f')
+        >>> w = TWave(A, f, phi)
+        >>> w.wavelength
+        299792458*meter/(second*f*n)
+        """
+        return c/(self.frequency*self.n)
+
+
+    @property
+    def speed(self):
+        """
+        Returns the propagation speed of the wave,
+        in meters per second.
+        It is dependent on the propagation medium.
+
+        Examples
+        ========
+
+        >>> from sympy import symbols
+        >>> from sympy.physics.optics import TWave
+        >>> A, phi, f = symbols('A, phi, f')
+        >>> w = TWave(A, f, phi)
+        >>> w.speed
+        299792458*meter/(second*n)
+        """
+        return self.wavelength*self.frequency
+
+    @property
+    def angular_velocity(self):
+        """
+        Returns the angular velocity of the wave,
+        in radians per second.
+
+        Examples
+        ========
+
+        >>> from sympy import symbols
+        >>> from sympy.physics.optics import TWave
+        >>> A, phi, f = symbols('A, phi, f')
+        >>> w = TWave(A, f, phi)
+        >>> w.angular_velocity
+        2*pi*f
+        """
+        return 2*pi*self.frequency
+
+    @property
+    def wavenumber(self):
+        """
+        Returns the wavenumber of the wave,
+        in radians per meter.
+
+        Examples
+        ========
+
+        >>> from sympy import symbols
+        >>> from sympy.physics.optics import TWave
+        >>> A, phi, f = symbols('A, phi, f')
+        >>> w = TWave(A, f, phi)
+        >>> w.wavenumber
+        pi*second*f*n/(149896229*meter)
+        """
+        return 2*pi/self.wavelength
+
+    def __str__(self):
+        """String representation of a TWave."""
+        from sympy.printing import sstr
+        return type(self).__name__ + sstr(self.args)
+
+    __repr__ = __str__
+
+    def __add__(self, other):
+        """
+        Addition of two waves will result in their superposition.
+        The type of interference will depend on their phase angles.
+        """
+        if isinstance(other, TWave):
+            if self.frequency == other.frequency and self.wavelength == other.wavelength:
+                return TWave(sqrt(self.amplitude**2 + other.amplitude**2 + 2 *
+                                  self.amplitude*other.amplitude*cos(
+                                      self.phase - other.phase)),
+                             self.frequency,
+                             atan2(self.amplitude*sin(self.phase)
+                             + other.amplitude*sin(other.phase),
+                             self.amplitude*cos(self.phase)
+                             + other.amplitude*cos(other.phase))
+                             )
+            else:
+                raise NotImplementedError("Interference of waves with different frequencies"
+                    " has not been implemented.")
+        else:
+            raise TypeError(type(other).__name__ + " and TWave objects cannot be added.")
+
+    def __mul__(self, other):
+        """
+        Multiplying a wave by a scalar rescales the amplitude of the wave.
+        """
+        other = sympify(other)
+        if isinstance(other, Number):
+            return TWave(self.amplitude*other, *self.args[1:])
+        else:
+            raise TypeError(type(other).__name__ + " and TWave objects cannot be multiplied.")
+
+    def __sub__(self, other):
+        return self.__add__(-1*other)
+
+    def __neg__(self):
+        return self.__mul__(-1)
+
+    def __radd__(self, other):
+        return self.__add__(other)
+
+    def __rmul__(self, other):
+        return self.__mul__(other)
+
+    def __rsub__(self, other):
+        return (-self).__radd__(other)
+
+    def _eval_rewrite_as_sin(self, *args, **kwargs):
+        return self.amplitude*sin(self.wavenumber*Symbol('x')
+            - self.angular_velocity*Symbol('t') + self.phase + pi/2, evaluate=False)
+
+    def _eval_rewrite_as_cos(self, *args, **kwargs):
+        return self.amplitude*cos(self.wavenumber*Symbol('x')
+            - self.angular_velocity*Symbol('t') + self.phase)
+
+    def _eval_rewrite_as_pde(self, *args, **kwargs):
+        mu, epsilon, x, t = symbols('mu, epsilon, x, t')
+        E = Function('E')
+        return Derivative(E(x, t), x, 2) + mu*epsilon*Derivative(E(x, t), t, 2)
+
+    def _eval_rewrite_as_exp(self, *args, **kwargs):
+        return self.amplitude*exp(I*(self.wavenumber*Symbol('x')
+            - self.angular_velocity*Symbol('t') + self.phase))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/paulialgebra.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/paulialgebra.py
new file mode 100644
index 0000000000000000000000000000000000000000..300957354ff34907035aa1d1a48b00276230a1e5
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/paulialgebra.py
@@ -0,0 +1,231 @@
+"""
+This module implements Pauli algebra by subclassing Symbol. Only algebraic
+properties of Pauli matrices are used (we do not use the Matrix class).
+
+See the documentation to the class Pauli for examples.
+
+References
+==========
+
+.. [1] https://en.wikipedia.org/wiki/Pauli_matrices
+"""
+
+from sympy.core.add import Add
+from sympy.core.mul import Mul
+from sympy.core.numbers import I
+from sympy.core.power import Pow
+from sympy.core.symbol import Symbol
+from sympy.physics.quantum import TensorProduct
+
+__all__ = ['evaluate_pauli_product']
+
+
+def delta(i, j):
+    """
+    Returns 1 if ``i == j``, else 0.
+
+    This is used in the multiplication of Pauli matrices.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.paulialgebra import delta
+    >>> delta(1, 1)
+    1
+    >>> delta(2, 3)
+    0
+    """
+    if i == j:
+        return 1
+    else:
+        return 0
+
+
+def epsilon(i, j, k):
+    """
+    Return 1 if i,j,k is equal to (1,2,3), (2,3,1), or (3,1,2);
+    -1 if ``i``,``j``,``k`` is equal to (1,3,2), (3,2,1), or (2,1,3);
+    else return 0.
+
+    This is used in the multiplication of Pauli matrices.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.paulialgebra import epsilon
+    >>> epsilon(1, 2, 3)
+    1
+    >>> epsilon(1, 3, 2)
+    -1
+    """
+    if (i, j, k) in ((1, 2, 3), (2, 3, 1), (3, 1, 2)):
+        return 1
+    elif (i, j, k) in ((1, 3, 2), (3, 2, 1), (2, 1, 3)):
+        return -1
+    else:
+        return 0
+
+
+class Pauli(Symbol):
+    """
+    The class representing algebraic properties of Pauli matrices.
+
+    Explanation
+    ===========
+
+    The symbol used to display the Pauli matrices can be changed with an
+    optional parameter ``label="sigma"``. Pauli matrices with different
+    ``label`` attributes cannot multiply together.
+
+    If the left multiplication of symbol or number with Pauli matrix is needed,
+    please use parentheses  to separate Pauli and symbolic multiplication
+    (for example: 2*I*(Pauli(3)*Pauli(2))).
+
+    Another variant is to use evaluate_pauli_product function to evaluate
+    the product of Pauli matrices and other symbols (with commutative
+    multiply rules).
+
+    See Also
+    ========
+
+    evaluate_pauli_product
+
+    Examples
+    ========
+
+    >>> from sympy.physics.paulialgebra import Pauli
+    >>> Pauli(1)
+    sigma1
+    >>> Pauli(1)*Pauli(2)
+    I*sigma3
+    >>> Pauli(1)*Pauli(1)
+    1
+    >>> Pauli(3)**4
+    1
+    >>> Pauli(1)*Pauli(2)*Pauli(3)
+    I
+
+    >>> from sympy.physics.paulialgebra import Pauli
+    >>> Pauli(1, label="tau")
+    tau1
+    >>> Pauli(1)*Pauli(2, label="tau")
+    sigma1*tau2
+    >>> Pauli(1, label="tau")*Pauli(2, label="tau")
+    I*tau3
+
+    >>> from sympy import I
+    >>> I*(Pauli(2)*Pauli(3))
+    -sigma1
+
+    >>> from sympy.physics.paulialgebra import evaluate_pauli_product
+    >>> f = I*Pauli(2)*Pauli(3)
+    >>> f
+    I*sigma2*sigma3
+    >>> evaluate_pauli_product(f)
+    -sigma1
+    """
+
+    __slots__ = ("i", "label")
+
+    def __new__(cls, i, label="sigma"):
+        if i not in [1, 2, 3]:
+            raise IndexError("Invalid Pauli index")
+        obj = Symbol.__new__(cls, "%s%d" %(label,i), commutative=False, hermitian=True)
+        obj.i = i
+        obj.label = label
+        return obj
+
+    def __getnewargs_ex__(self):
+        return (self.i, self.label), {}
+
+    def _hashable_content(self):
+        return (self.i, self.label)
+
+    # FIXME don't work for -I*Pauli(2)*Pauli(3)
+    def __mul__(self, other):
+        if isinstance(other, Pauli):
+            j = self.i
+            k = other.i
+            jlab = self.label
+            klab = other.label
+
+            if jlab == klab:
+                return delta(j, k) \
+                    + I*epsilon(j, k, 1)*Pauli(1,jlab) \
+                    + I*epsilon(j, k, 2)*Pauli(2,jlab) \
+                    + I*epsilon(j, k, 3)*Pauli(3,jlab)
+        return super().__mul__(other)
+
+    def _eval_power(b, e):
+        if e.is_Integer and e.is_positive:
+            return super().__pow__(int(e) % 2)
+
+
+def evaluate_pauli_product(arg):
+    '''Help function to evaluate Pauli matrices product
+    with symbolic objects.
+
+    Parameters
+    ==========
+
+    arg: symbolic expression that contains Paulimatrices
+
+    Examples
+    ========
+
+    >>> from sympy.physics.paulialgebra import Pauli, evaluate_pauli_product
+    >>> from sympy import I
+    >>> evaluate_pauli_product(I*Pauli(1)*Pauli(2))
+    -sigma3
+
+    >>> from sympy.abc import x
+    >>> evaluate_pauli_product(x**2*Pauli(2)*Pauli(1))
+    -I*x**2*sigma3
+    '''
+    start = arg
+    end = arg
+
+    if isinstance(arg, Pow) and isinstance(arg.args[0], Pauli):
+        if arg.args[1].is_odd:
+            return arg.args[0]
+        else:
+            return 1
+
+    if isinstance(arg, Add):
+        return Add(*[evaluate_pauli_product(part) for part in arg.args])
+
+    if isinstance(arg, TensorProduct):
+        return TensorProduct(*[evaluate_pauli_product(part) for part in arg.args])
+
+    elif not(isinstance(arg, Mul)):
+        return arg
+
+    while not start == end or start == arg and end == arg:
+        start = end
+
+        tmp = start.as_coeff_mul()
+        sigma_product = 1
+        com_product = 1
+        keeper = 1
+
+        for el in tmp[1]:
+            if isinstance(el, Pauli):
+                sigma_product *= el
+            elif not el.is_commutative:
+                if isinstance(el, Pow) and isinstance(el.args[0], Pauli):
+                    if el.args[1].is_odd:
+                        sigma_product *= el.args[0]
+                elif isinstance(el, TensorProduct):
+                    keeper = keeper*sigma_product*\
+                        TensorProduct(
+                            *[evaluate_pauli_product(part) for part in el.args]
+                        )
+                    sigma_product = 1
+                else:
+                    keeper = keeper*sigma_product*el
+                    sigma_product = 1
+            else:
+                com_product *= el
+        end = tmp[0]*keeper*sigma_product*com_product
+        if end == arg: break
+    return end
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/qho_1d.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/qho_1d.py
new file mode 100644
index 0000000000000000000000000000000000000000..f418e0e954656923fbfa64cea2145581ddf65aea
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/qho_1d.py
@@ -0,0 +1,88 @@
+from sympy.core import S, pi, Rational
+from sympy.functions import hermite, sqrt, exp, factorial, Abs
+from sympy.physics.quantum.constants import hbar
+
+
+def psi_n(n, x, m, omega):
+    """
+    Returns the wavefunction psi_{n} for the One-dimensional harmonic oscillator.
+
+    Parameters
+    ==========
+
+    n :
+        the "nodal" quantum number.  Corresponds to the number of nodes in the
+        wavefunction.  ``n >= 0``
+    x :
+        x coordinate.
+    m :
+        Mass of the particle.
+    omega :
+        Angular frequency of the oscillator.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.qho_1d import psi_n
+    >>> from sympy.abc import m, x, omega
+    >>> psi_n(0, x, m, omega)
+    (m*omega)**(1/4)*exp(-m*omega*x**2/(2*hbar))/(hbar**(1/4)*pi**(1/4))
+
+    """
+
+    # sympify arguments
+    n, x, m, omega = map(S, [n, x, m, omega])
+    nu = m * omega / hbar
+    # normalization coefficient
+    C = (nu/pi)**Rational(1, 4) * sqrt(1/(2**n*factorial(n)))
+
+    return C * exp(-nu* x**2 /2) * hermite(n, sqrt(nu)*x)
+
+
+def E_n(n, omega):
+    """
+    Returns the Energy of the One-dimensional harmonic oscillator.
+
+    Parameters
+    ==========
+
+    n :
+        The "nodal" quantum number.
+    omega :
+        The harmonic oscillator angular frequency.
+
+    Notes
+    =====
+
+    The unit of the returned value matches the unit of hw, since the energy is
+    calculated as:
+
+        E_n = hbar * omega*(n + 1/2)
+
+    Examples
+    ========
+
+    >>> from sympy.physics.qho_1d import E_n
+    >>> from sympy.abc import x, omega
+    >>> E_n(x, omega)
+    hbar*omega*(x + 1/2)
+    """
+
+    return hbar * omega * (n + S.Half)
+
+
+def coherent_state(n, alpha):
+    """
+    Returns  for the coherent states of 1D harmonic oscillator.
+    See https://en.wikipedia.org/wiki/Coherent_states
+
+    Parameters
+    ==========
+
+    n :
+        The "nodal" quantum number.
+    alpha :
+        The eigen value of annihilation operator.
+    """
+
+    return exp(- Abs(alpha)**2/2)*(alpha**n)/sqrt(factorial(n))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..36203f1a48c4c53832ce44942878ddc7b89f8091
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/__init__.py
@@ -0,0 +1,65 @@
+# Names exposed by 'from sympy.physics.quantum import *'
+
+__all__ = [
+    'AntiCommutator',
+
+    'qapply',
+
+    'Commutator',
+
+    'Dagger',
+
+    'HilbertSpaceError', 'HilbertSpace', 'TensorProductHilbertSpace',
+    'TensorPowerHilbertSpace', 'DirectSumHilbertSpace', 'ComplexSpace', 'L2',
+    'FockSpace',
+
+    'InnerProduct',
+
+    'Operator', 'HermitianOperator', 'UnitaryOperator', 'IdentityOperator',
+    'OuterProduct', 'DifferentialOperator',
+
+    'represent', 'rep_innerproduct', 'rep_expectation', 'integrate_result',
+    'get_basis', 'enumerate_states',
+
+    'KetBase', 'BraBase', 'StateBase', 'State', 'Ket', 'Bra', 'TimeDepState',
+    'TimeDepBra', 'TimeDepKet', 'OrthogonalKet', 'OrthogonalBra',
+    'OrthogonalState', 'Wavefunction',
+
+    'TensorProduct', 'tensor_product_simp',
+
+    'hbar', 'HBar',
+
+    '_postprocess_state_mul', '_postprocess_state_pow'
+]
+
+from .anticommutator import AntiCommutator
+
+from .qapply import qapply
+
+from .commutator import Commutator
+
+from .dagger import Dagger
+
+from .hilbert import (HilbertSpaceError, HilbertSpace,
+        TensorProductHilbertSpace, TensorPowerHilbertSpace,
+        DirectSumHilbertSpace, ComplexSpace, L2, FockSpace)
+
+from .innerproduct import InnerProduct
+
+from .operator import (Operator, HermitianOperator, UnitaryOperator,
+        IdentityOperator, OuterProduct, DifferentialOperator)
+
+from .represent import (represent, rep_innerproduct, rep_expectation,
+        integrate_result, get_basis, enumerate_states)
+
+from .state import (KetBase, BraBase, StateBase, State, Ket, Bra,
+        TimeDepState, TimeDepBra, TimeDepKet, OrthogonalKet,
+        OrthogonalBra, OrthogonalState, Wavefunction)
+
+from .tensorproduct import TensorProduct, tensor_product_simp
+
+from .constants import hbar, HBar
+
+# These are private, but need to be imported so they are registered
+# as postprocessing transformers with Mul and Pow.
+from .transforms import _postprocess_state_mul, _postprocess_state_pow
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/anticommutator.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/anticommutator.py
new file mode 100644
index 0000000000000000000000000000000000000000..cbd26eade640b60a48eaac8c8b0abaf236478ca9
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/anticommutator.py
@@ -0,0 +1,166 @@
+"""The anti-commutator: ``{A,B} = A*B + B*A``."""
+
+from sympy.core.expr import Expr
+from sympy.core.kind import KindDispatcher
+from sympy.core.mul import Mul
+from sympy.core.numbers import Integer
+from sympy.core.singleton import S
+from sympy.printing.pretty.stringpict import prettyForm
+
+from sympy.physics.quantum.dagger import Dagger
+from sympy.physics.quantum.kind import _OperatorKind, OperatorKind
+
+__all__ = [
+    'AntiCommutator'
+]
+
+#-----------------------------------------------------------------------------
+# Anti-commutator
+#-----------------------------------------------------------------------------
+
+
+class AntiCommutator(Expr):
+    """The standard anticommutator, in an unevaluated state.
+
+    Explanation
+    ===========
+
+    Evaluating an anticommutator is defined [1]_ as: ``{A, B} = A*B + B*A``.
+    This class returns the anticommutator in an unevaluated form.  To evaluate
+    the anticommutator, use the ``.doit()`` method.
+
+    Canonical ordering of an anticommutator is ``{A, B}`` for ``A < B``. The
+    arguments of the anticommutator are put into canonical order using
+    ``__cmp__``. If ``B < A``, then ``{A, B}`` is returned as ``{B, A}``.
+
+    Parameters
+    ==========
+
+    A : Expr
+        The first argument of the anticommutator {A,B}.
+    B : Expr
+        The second argument of the anticommutator {A,B}.
+
+    Examples
+    ========
+
+    >>> from sympy import symbols
+    >>> from sympy.physics.quantum import AntiCommutator
+    >>> from sympy.physics.quantum import Operator, Dagger
+    >>> x, y = symbols('x,y')
+    >>> A = Operator('A')
+    >>> B = Operator('B')
+
+    Create an anticommutator and use ``doit()`` to multiply them out.
+
+    >>> ac = AntiCommutator(A,B); ac
+    {A,B}
+    >>> ac.doit()
+    A*B + B*A
+
+    The commutator orders it arguments in canonical order:
+
+    >>> ac = AntiCommutator(B,A); ac
+    {A,B}
+
+    Commutative constants are factored out:
+
+    >>> AntiCommutator(3*x*A,x*y*B)
+    3*x**2*y*{A,B}
+
+    Adjoint operations applied to the anticommutator are properly applied to
+    the arguments:
+
+    >>> Dagger(AntiCommutator(A,B))
+    {Dagger(A),Dagger(B)}
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Commutator
+    """
+    is_commutative = False
+
+    _kind_dispatcher = KindDispatcher("AntiCommutator_kind_dispatcher", commutative=True)
+
+    @property
+    def kind(self):
+        arg_kinds = (a.kind for a in self.args)
+        return self._kind_dispatcher(*arg_kinds)
+
+    def __new__(cls, A, B):
+        r = cls.eval(A, B)
+        if r is not None:
+            return r
+        obj = Expr.__new__(cls, A, B)
+        return obj
+
+    @classmethod
+    def eval(cls, a, b):
+        if not (a and b):
+            return S.Zero
+        if a == b:
+            return Integer(2)*a**2
+        if a.is_commutative or b.is_commutative:
+            return Integer(2)*a*b
+
+        # [xA,yB]  ->  xy*[A,B]
+        ca, nca = a.args_cnc()
+        cb, ncb = b.args_cnc()
+        c_part = ca + cb
+        if c_part:
+            return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb)))
+
+        # Canonical ordering of arguments
+        #The Commutator [A,B] is on canonical form if A < B.
+        if a.compare(b) == 1:
+            return cls(b, a)
+
+    def doit(self, **hints):
+        """ Evaluate anticommutator """
+        # Keep the import of Operator here to avoid problems with
+        # circular imports.
+        from sympy.physics.quantum.operator import Operator
+        A = self.args[0]
+        B = self.args[1]
+        if isinstance(A, Operator) and isinstance(B, Operator):
+            try:
+                comm = A._eval_anticommutator(B, **hints)
+            except NotImplementedError:
+                try:
+                    comm = B._eval_anticommutator(A, **hints)
+                except NotImplementedError:
+                    comm = None
+            if comm is not None:
+                return comm.doit(**hints)
+        return (A*B + B*A).doit(**hints)
+
+    def _eval_adjoint(self):
+        return AntiCommutator(Dagger(self.args[0]), Dagger(self.args[1]))
+
+    def _sympyrepr(self, printer, *args):
+        return "%s(%s,%s)" % (
+            self.__class__.__name__, printer._print(
+                self.args[0]), printer._print(self.args[1])
+        )
+
+    def _sympystr(self, printer, *args):
+        return "{%s,%s}" % (
+            printer._print(self.args[0]), printer._print(self.args[1]))
+
+    def _pretty(self, printer, *args):
+        pform = printer._print(self.args[0], *args)
+        pform = prettyForm(*pform.right(prettyForm(',')))
+        pform = prettyForm(*pform.right(printer._print(self.args[1], *args)))
+        pform = prettyForm(*pform.parens(left='{', right='}'))
+        return pform
+
+    def _latex(self, printer, *args):
+        return "\\left\\{%s,%s\\right\\}" % tuple([
+            printer._print(arg, *args) for arg in self.args])
+
+
+@AntiCommutator._kind_dispatcher.register(_OperatorKind, _OperatorKind)
+def find_op_kind(e1, e2):
+    """Find the kind of an anticommutator of two OperatorKinds."""
+    return OperatorKind
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/boson.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/boson.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f24cae2a7ad2f438234fcf00dadb2a4a9d76fe8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/boson.py
@@ -0,0 +1,243 @@
+"""Bosonic quantum operators."""
+
+from sympy.core.numbers import Integer
+from sympy.core.singleton import S
+from sympy.functions.elementary.complexes import conjugate
+from sympy.functions.elementary.exponential import exp
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.physics.quantum import Operator
+from sympy.physics.quantum import HilbertSpace, FockSpace, Ket, Bra
+from sympy.functions.special.tensor_functions import KroneckerDelta
+
+
+__all__ = [
+    'BosonOp',
+    'BosonFockKet',
+    'BosonFockBra',
+    'BosonCoherentKet',
+    'BosonCoherentBra'
+]
+
+
+class BosonOp(Operator):
+    """A bosonic operator that satisfies [a, Dagger(a)] == 1.
+
+    Parameters
+    ==========
+
+    name : str
+        A string that labels the bosonic mode.
+
+    annihilation : bool
+        A bool that indicates if the bosonic operator is an annihilation (True,
+        default value) or creation operator (False)
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum import Dagger, Commutator
+    >>> from sympy.physics.quantum.boson import BosonOp
+    >>> a = BosonOp("a")
+    >>> Commutator(a, Dagger(a)).doit()
+    1
+    """
+
+    @property
+    def name(self):
+        return self.args[0]
+
+    @property
+    def is_annihilation(self):
+        return bool(self.args[1])
+
+    @classmethod
+    def default_args(self):
+        return ("a", True)
+
+    def __new__(cls, *args, **hints):
+        if not len(args) in [1, 2]:
+            raise ValueError('1 or 2 parameters expected, got %s' % args)
+
+        if len(args) == 1:
+            args = (args[0], S.One)
+
+        if len(args) == 2:
+            args = (args[0], Integer(args[1]))
+
+        return Operator.__new__(cls, *args)
+
+    def _eval_commutator_BosonOp(self, other, **hints):
+        if self.name == other.name:
+            # [a^\dagger, a] = -1
+            if not self.is_annihilation and other.is_annihilation:
+                return S.NegativeOne
+
+        elif 'independent' in hints and hints['independent']:
+            # [a, b] = 0
+            return S.Zero
+
+        return None
+
+    def _eval_commutator_FermionOp(self, other, **hints):
+        return S.Zero
+
+    def _eval_anticommutator_BosonOp(self, other, **hints):
+        if 'independent' in hints and hints['independent']:
+            # {a, b} = 2 * a * b, because [a, b] = 0
+            return 2 * self * other
+
+        return None
+
+    def _eval_adjoint(self):
+        return BosonOp(str(self.name), not self.is_annihilation)
+
+    def _print_contents_latex(self, printer, *args):
+        if self.is_annihilation:
+            return r'{%s}' % str(self.name)
+        else:
+            return r'{{%s}^\dagger}' % str(self.name)
+
+    def _print_contents(self, printer, *args):
+        if self.is_annihilation:
+            return r'%s' % str(self.name)
+        else:
+            return r'Dagger(%s)' % str(self.name)
+
+    def _print_contents_pretty(self, printer, *args):
+        from sympy.printing.pretty.stringpict import prettyForm
+        pform = printer._print(self.args[0], *args)
+        if self.is_annihilation:
+            return pform
+        else:
+            return pform**prettyForm('\N{DAGGER}')
+
+
+class BosonFockKet(Ket):
+    """Fock state ket for a bosonic mode.
+
+    Parameters
+    ==========
+
+    n : Number
+        The Fock state number.
+
+    """
+
+    def __new__(cls, n):
+        return Ket.__new__(cls, n)
+
+    @property
+    def n(self):
+        return self.label[0]
+
+    @classmethod
+    def dual_class(self):
+        return BosonFockBra
+
+    @classmethod
+    def _eval_hilbert_space(cls, label):
+        return FockSpace()
+
+    def _eval_innerproduct_BosonFockBra(self, bra, **hints):
+        return KroneckerDelta(self.n, bra.n)
+
+    def _apply_from_right_to_BosonOp(self, op, **options):
+        if op.is_annihilation:
+            return sqrt(self.n) * BosonFockKet(self.n - 1)
+        else:
+            return sqrt(self.n + 1) * BosonFockKet(self.n + 1)
+
+
+class BosonFockBra(Bra):
+    """Fock state bra for a bosonic mode.
+
+    Parameters
+    ==========
+
+    n : Number
+        The Fock state number.
+
+    """
+
+    def __new__(cls, n):
+        return Bra.__new__(cls, n)
+
+    @property
+    def n(self):
+        return self.label[0]
+
+    @classmethod
+    def dual_class(self):
+        return BosonFockKet
+
+    @classmethod
+    def _eval_hilbert_space(cls, label):
+        return FockSpace()
+
+
+class BosonCoherentKet(Ket):
+    """Coherent state ket for a bosonic mode.
+
+    Parameters
+    ==========
+
+    alpha : Number, Symbol
+        The complex amplitude of the coherent state.
+
+    """
+
+    def __new__(cls, alpha):
+        return Ket.__new__(cls, alpha)
+
+    @property
+    def alpha(self):
+        return self.label[0]
+
+    @classmethod
+    def dual_class(self):
+        return BosonCoherentBra
+
+    @classmethod
+    def _eval_hilbert_space(cls, label):
+        return HilbertSpace()
+
+    def _eval_innerproduct_BosonCoherentBra(self, bra, **hints):
+        if self.alpha == bra.alpha:
+            return S.One
+        else:
+            return exp(-(abs(self.alpha)**2 + abs(bra.alpha)**2 - 2 * conjugate(bra.alpha) * self.alpha)/2)
+
+    def _apply_from_right_to_BosonOp(self, op, **options):
+        if op.is_annihilation:
+            return self.alpha * self
+        else:
+            return None
+
+
+class BosonCoherentBra(Bra):
+    """Coherent state bra for a bosonic mode.
+
+    Parameters
+    ==========
+
+    alpha : Number, Symbol
+        The complex amplitude of the coherent state.
+
+    """
+
+    def __new__(cls, alpha):
+        return Bra.__new__(cls, alpha)
+
+    @property
+    def alpha(self):
+        return self.label[0]
+
+    @classmethod
+    def dual_class(self):
+        return BosonCoherentKet
+
+    def _apply_operator_BosonOp(self, op, **options):
+        if not op.is_annihilation:
+            return self.alpha * self
+        else:
+            return None
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/cartesian.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/cartesian.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3af1856f22c8fe4535b24be30bf99d0b3541a50
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/cartesian.py
@@ -0,0 +1,341 @@
+"""Operators and states for 1D cartesian position and momentum.
+
+TODO:
+
+* Add 3D classes to mappings in operatorset.py
+
+"""
+
+from sympy.core.numbers import (I, pi)
+from sympy.core.singleton import S
+from sympy.functions.elementary.exponential import exp
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.special.delta_functions import DiracDelta
+from sympy.sets.sets import Interval
+
+from sympy.physics.quantum.constants import hbar
+from sympy.physics.quantum.hilbert import L2
+from sympy.physics.quantum.operator import DifferentialOperator, HermitianOperator
+from sympy.physics.quantum.state import Ket, Bra, State
+
+__all__ = [
+    'XOp',
+    'YOp',
+    'ZOp',
+    'PxOp',
+    'X',
+    'Y',
+    'Z',
+    'Px',
+    'XKet',
+    'XBra',
+    'PxKet',
+    'PxBra',
+    'PositionState3D',
+    'PositionKet3D',
+    'PositionBra3D'
+]
+
+#-------------------------------------------------------------------------
+# Position operators
+#-------------------------------------------------------------------------
+
+
+class XOp(HermitianOperator):
+    """1D cartesian position operator."""
+
+    @classmethod
+    def default_args(self):
+        return ("X",)
+
+    @classmethod
+    def _eval_hilbert_space(self, args):
+        return L2(Interval(S.NegativeInfinity, S.Infinity))
+
+    def _eval_commutator_PxOp(self, other):
+        return I*hbar
+
+    def _apply_operator_XKet(self, ket, **options):
+        return ket.position*ket
+
+    def _apply_operator_PositionKet3D(self, ket, **options):
+        return ket.position_x*ket
+
+    def _represent_PxKet(self, basis, *, index=1, **options):
+        states = basis._enumerate_state(2, start_index=index)
+        coord1 = states[0].momentum
+        coord2 = states[1].momentum
+        d = DifferentialOperator(coord1)
+        delta = DiracDelta(coord1 - coord2)
+
+        return I*hbar*(d*delta)
+
+
+class YOp(HermitianOperator):
+    """ Y cartesian coordinate operator (for 2D or 3D systems) """
+
+    @classmethod
+    def default_args(self):
+        return ("Y",)
+
+    @classmethod
+    def _eval_hilbert_space(self, args):
+        return L2(Interval(S.NegativeInfinity, S.Infinity))
+
+    def _apply_operator_PositionKet3D(self, ket, **options):
+        return ket.position_y*ket
+
+
+class ZOp(HermitianOperator):
+    """ Z cartesian coordinate operator (for 3D systems) """
+
+    @classmethod
+    def default_args(self):
+        return ("Z",)
+
+    @classmethod
+    def _eval_hilbert_space(self, args):
+        return L2(Interval(S.NegativeInfinity, S.Infinity))
+
+    def _apply_operator_PositionKet3D(self, ket, **options):
+        return ket.position_z*ket
+
+#-------------------------------------------------------------------------
+# Momentum operators
+#-------------------------------------------------------------------------
+
+
+class PxOp(HermitianOperator):
+    """1D cartesian momentum operator."""
+
+    @classmethod
+    def default_args(self):
+        return ("Px",)
+
+    @classmethod
+    def _eval_hilbert_space(self, args):
+        return L2(Interval(S.NegativeInfinity, S.Infinity))
+
+    def _apply_operator_PxKet(self, ket, **options):
+        return ket.momentum*ket
+
+    def _represent_XKet(self, basis, *, index=1, **options):
+        states = basis._enumerate_state(2, start_index=index)
+        coord1 = states[0].position
+        coord2 = states[1].position
+        d = DifferentialOperator(coord1)
+        delta = DiracDelta(coord1 - coord2)
+
+        return -I*hbar*(d*delta)
+
+X = XOp('X')
+Y = YOp('Y')
+Z = ZOp('Z')
+Px = PxOp('Px')
+
+#-------------------------------------------------------------------------
+# Position eigenstates
+#-------------------------------------------------------------------------
+
+
+class XKet(Ket):
+    """1D cartesian position eigenket."""
+
+    @classmethod
+    def _operators_to_state(self, op, **options):
+        return self.__new__(self, *_lowercase_labels(op), **options)
+
+    def _state_to_operators(self, op_class, **options):
+        return op_class.__new__(op_class,
+                                *_uppercase_labels(self), **options)
+
+    @classmethod
+    def default_args(self):
+        return ("x",)
+
+    @classmethod
+    def dual_class(self):
+        return XBra
+
+    @property
+    def position(self):
+        """The position of the state."""
+        return self.label[0]
+
+    def _enumerate_state(self, num_states, **options):
+        return _enumerate_continuous_1D(self, num_states, **options)
+
+    def _eval_innerproduct_XBra(self, bra, **hints):
+        return DiracDelta(self.position - bra.position)
+
+    def _eval_innerproduct_PxBra(self, bra, **hints):
+        return exp(-I*self.position*bra.momentum/hbar)/sqrt(2*pi*hbar)
+
+
+class XBra(Bra):
+    """1D cartesian position eigenbra."""
+
+    @classmethod
+    def default_args(self):
+        return ("x",)
+
+    @classmethod
+    def dual_class(self):
+        return XKet
+
+    @property
+    def position(self):
+        """The position of the state."""
+        return self.label[0]
+
+
+class PositionState3D(State):
+    """ Base class for 3D cartesian position eigenstates """
+
+    @classmethod
+    def _operators_to_state(self, op, **options):
+        return self.__new__(self, *_lowercase_labels(op), **options)
+
+    def _state_to_operators(self, op_class, **options):
+        return op_class.__new__(op_class,
+                                *_uppercase_labels(self), **options)
+
+    @classmethod
+    def default_args(self):
+        return ("x", "y", "z")
+
+    @property
+    def position_x(self):
+        """ The x coordinate of the state """
+        return self.label[0]
+
+    @property
+    def position_y(self):
+        """ The y coordinate of the state """
+        return self.label[1]
+
+    @property
+    def position_z(self):
+        """ The z coordinate of the state """
+        return self.label[2]
+
+
+class PositionKet3D(Ket, PositionState3D):
+    """ 3D cartesian position eigenket """
+
+    def _eval_innerproduct_PositionBra3D(self, bra, **options):
+        x_diff = self.position_x - bra.position_x
+        y_diff = self.position_y - bra.position_y
+        z_diff = self.position_z - bra.position_z
+
+        return DiracDelta(x_diff)*DiracDelta(y_diff)*DiracDelta(z_diff)
+
+    @classmethod
+    def dual_class(self):
+        return PositionBra3D
+
+
+# XXX: The type:ignore here is because mypy gives Definition of
+# "_state_to_operators" in base class "PositionState3D" is incompatible with
+# definition in base class "BraBase"
+class PositionBra3D(Bra, PositionState3D):  # type: ignore
+    """ 3D cartesian position eigenbra """
+
+    @classmethod
+    def dual_class(self):
+        return PositionKet3D
+
+#-------------------------------------------------------------------------
+# Momentum eigenstates
+#-------------------------------------------------------------------------
+
+
+class PxKet(Ket):
+    """1D cartesian momentum eigenket."""
+
+    @classmethod
+    def _operators_to_state(self, op, **options):
+        return self.__new__(self, *_lowercase_labels(op), **options)
+
+    def _state_to_operators(self, op_class, **options):
+        return op_class.__new__(op_class,
+                                *_uppercase_labels(self), **options)
+
+    @classmethod
+    def default_args(self):
+        return ("px",)
+
+    @classmethod
+    def dual_class(self):
+        return PxBra
+
+    @property
+    def momentum(self):
+        """The momentum of the state."""
+        return self.label[0]
+
+    def _enumerate_state(self, *args, **options):
+        return _enumerate_continuous_1D(self, *args, **options)
+
+    def _eval_innerproduct_XBra(self, bra, **hints):
+        return exp(I*self.momentum*bra.position/hbar)/sqrt(2*pi*hbar)
+
+    def _eval_innerproduct_PxBra(self, bra, **hints):
+        return DiracDelta(self.momentum - bra.momentum)
+
+
+class PxBra(Bra):
+    """1D cartesian momentum eigenbra."""
+
+    @classmethod
+    def default_args(self):
+        return ("px",)
+
+    @classmethod
+    def dual_class(self):
+        return PxKet
+
+    @property
+    def momentum(self):
+        """The momentum of the state."""
+        return self.label[0]
+
+#-------------------------------------------------------------------------
+# Global helper functions
+#-------------------------------------------------------------------------
+
+
+def _enumerate_continuous_1D(*args, **options):
+    state = args[0]
+    num_states = args[1]
+    state_class = state.__class__
+    index_list = options.pop('index_list', [])
+
+    if len(index_list) == 0:
+        start_index = options.pop('start_index', 1)
+        index_list = list(range(start_index, start_index + num_states))
+
+    enum_states = [0 for i in range(len(index_list))]
+
+    for i, ind in enumerate(index_list):
+        label = state.args[0]
+        enum_states[i] = state_class(str(label) + "_" + str(ind), **options)
+
+    return enum_states
+
+
+def _lowercase_labels(ops):
+    if not isinstance(ops, set):
+        ops = [ops]
+
+    return [str(arg.label[0]).lower() for arg in ops]
+
+
+def _uppercase_labels(ops):
+    if not isinstance(ops, set):
+        ops = [ops]
+
+    new_args = [str(arg.label[0])[0].upper() +
+                str(arg.label[0])[1:] for arg in ops]
+
+    return new_args
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/cg.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/cg.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f285cd39413a953246777c42fb6763c22a5716b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/cg.py
@@ -0,0 +1,754 @@
+#TODO:
+# -Implement Clebsch-Gordan symmetries
+# -Improve simplification method
+# -Implement new simplifications
+"""Clebsch-Gordon Coefficients."""
+
+from sympy.concrete.summations import Sum
+from sympy.core.add import Add
+from sympy.core.expr import Expr
+from sympy.core.function import expand
+from sympy.core.mul import Mul
+from sympy.core.power import Pow
+from sympy.core.relational import Eq
+from sympy.core.singleton import S
+from sympy.core.symbol import (Wild, symbols)
+from sympy.core.sympify import sympify
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.printing.pretty.stringpict import prettyForm, stringPict
+
+from sympy.functions.special.tensor_functions import KroneckerDelta
+from sympy.physics.wigner import clebsch_gordan, wigner_3j, wigner_6j, wigner_9j
+from sympy.printing.precedence import PRECEDENCE
+
+__all__ = [
+    'CG',
+    'Wigner3j',
+    'Wigner6j',
+    'Wigner9j',
+    'cg_simp'
+]
+
+#-----------------------------------------------------------------------------
+# CG Coefficients
+#-----------------------------------------------------------------------------
+
+
+class Wigner3j(Expr):
+    """Class for the Wigner-3j symbols.
+
+    Explanation
+    ===========
+
+    Wigner 3j-symbols are coefficients determined by the coupling of
+    two angular momenta. When created, they are expressed as symbolic
+    quantities that, for numerical parameters, can be evaluated using the
+    ``.doit()`` method [1]_.
+
+    Parameters
+    ==========
+
+    j1, m1, j2, m2, j3, m3 : Number, Symbol
+        Terms determining the angular momentum of coupled angular momentum
+        systems.
+
+    Examples
+    ========
+
+    Declare a Wigner-3j coefficient and calculate its value
+
+        >>> from sympy.physics.quantum.cg import Wigner3j
+        >>> w3j = Wigner3j(6,0,4,0,2,0)
+        >>> w3j
+        Wigner3j(6, 0, 4, 0, 2, 0)
+        >>> w3j.doit()
+        sqrt(715)/143
+
+    See Also
+    ========
+
+    CG: Clebsch-Gordan coefficients
+
+    References
+    ==========
+
+    .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
+    """
+
+    is_commutative = True
+
+    def __new__(cls, j1, m1, j2, m2, j3, m3):
+        args = map(sympify, (j1, m1, j2, m2, j3, m3))
+        return Expr.__new__(cls, *args)
+
+    @property
+    def j1(self):
+        return self.args[0]
+
+    @property
+    def m1(self):
+        return self.args[1]
+
+    @property
+    def j2(self):
+        return self.args[2]
+
+    @property
+    def m2(self):
+        return self.args[3]
+
+    @property
+    def j3(self):
+        return self.args[4]
+
+    @property
+    def m3(self):
+        return self.args[5]
+
+    @property
+    def is_symbolic(self):
+        return not all(arg.is_number for arg in self.args)
+
+    # This is modified from the _print_Matrix method
+    def _pretty(self, printer, *args):
+        m = ((printer._print(self.j1), printer._print(self.m1)),
+            (printer._print(self.j2), printer._print(self.m2)),
+            (printer._print(self.j3), printer._print(self.m3)))
+        hsep = 2
+        vsep = 1
+        maxw = [-1]*3
+        for j in range(3):
+            maxw[j] = max(m[j][i].width() for i in range(2))
+        D = None
+        for i in range(2):
+            D_row = None
+            for j in range(3):
+                s = m[j][i]
+                wdelta = maxw[j] - s.width()
+                wleft = wdelta //2
+                wright = wdelta - wleft
+
+                s = prettyForm(*s.right(' '*wright))
+                s = prettyForm(*s.left(' '*wleft))
+
+                if D_row is None:
+                    D_row = s
+                    continue
+                D_row = prettyForm(*D_row.right(' '*hsep))
+                D_row = prettyForm(*D_row.right(s))
+            if D is None:
+                D = D_row
+                continue
+            for _ in range(vsep):
+                D = prettyForm(*D.below(' '))
+            D = prettyForm(*D.below(D_row))
+        D = prettyForm(*D.parens())
+        return D
+
+    def _latex(self, printer, *args):
+        label = map(printer._print, (self.j1, self.j2, self.j3,
+                    self.m1, self.m2, self.m3))
+        return r'\left(\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \end{array}\right)' % \
+            tuple(label)
+
+    def doit(self, **hints):
+        if self.is_symbolic:
+            raise ValueError("Coefficients must be numerical")
+        return wigner_3j(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3)
+
+
+class CG(Wigner3j):
+    r"""Class for Clebsch-Gordan coefficient.
+
+    Explanation
+    ===========
+
+    Clebsch-Gordan coefficients describe the angular momentum coupling between
+    two systems. The coefficients give the expansion of a coupled total angular
+    momentum state and an uncoupled tensor product state. The Clebsch-Gordan
+    coefficients are defined as [1]_:
+
+    .. math ::
+        C^{j_3,m_3}_{j_1,m_1,j_2,m_2} = \left\langle j_1,m_1;j_2,m_2 | j_3,m_3\right\rangle
+
+    Parameters
+    ==========
+
+    j1, m1, j2, m2 : Number, Symbol
+        Angular momenta of states 1 and 2.
+
+    j3, m3: Number, Symbol
+        Total angular momentum of the coupled system.
+
+    Examples
+    ========
+
+    Define a Clebsch-Gordan coefficient and evaluate its value
+
+        >>> from sympy.physics.quantum.cg import CG
+        >>> from sympy import S
+        >>> cg = CG(S(3)/2, S(3)/2, S(1)/2, -S(1)/2, 1, 1)
+        >>> cg
+        CG(3/2, 3/2, 1/2, -1/2, 1, 1)
+        >>> cg.doit()
+        sqrt(3)/2
+        >>> CG(j1=S(1)/2, m1=-S(1)/2, j2=S(1)/2, m2=+S(1)/2, j3=1, m3=0).doit()
+        sqrt(2)/2
+
+
+    Compare [2]_.
+
+    See Also
+    ========
+
+    Wigner3j: Wigner-3j symbols
+
+    References
+    ==========
+
+    .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
+    .. [2] `Clebsch-Gordan Coefficients, Spherical Harmonics, and d Functions
+        `_
+        in P.A. Zyla *et al.* (Particle Data Group), Prog. Theor. Exp. Phys.
+        2020, 083C01 (2020).
+    """
+    precedence = PRECEDENCE["Pow"] - 1
+
+    def doit(self, **hints):
+        if self.is_symbolic:
+            raise ValueError("Coefficients must be numerical")
+        return clebsch_gordan(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3)
+
+    def _pretty(self, printer, *args):
+        bot = printer._print_seq(
+            (self.j1, self.m1, self.j2, self.m2), delimiter=',')
+        top = printer._print_seq((self.j3, self.m3), delimiter=',')
+
+        pad = max(top.width(), bot.width())
+        bot = prettyForm(*bot.left(' '))
+        top = prettyForm(*top.left(' '))
+
+        if not pad == bot.width():
+            bot = prettyForm(*bot.right(' '*(pad - bot.width())))
+        if not pad == top.width():
+            top = prettyForm(*top.right(' '*(pad - top.width())))
+        s = stringPict('C' + ' '*pad)
+        s = prettyForm(*s.below(bot))
+        s = prettyForm(*s.above(top))
+        return s
+
+    def _latex(self, printer, *args):
+        label = map(printer._print, (self.j3, self.m3, self.j1,
+                    self.m1, self.j2, self.m2))
+        return r'C^{%s,%s}_{%s,%s,%s,%s}' % tuple(label)
+
+
+class Wigner6j(Expr):
+    """Class for the Wigner-6j symbols
+
+    See Also
+    ========
+
+    Wigner3j: Wigner-3j symbols
+
+    """
+    def __new__(cls, j1, j2, j12, j3, j, j23):
+        args = map(sympify, (j1, j2, j12, j3, j, j23))
+        return Expr.__new__(cls, *args)
+
+    @property
+    def j1(self):
+        return self.args[0]
+
+    @property
+    def j2(self):
+        return self.args[1]
+
+    @property
+    def j12(self):
+        return self.args[2]
+
+    @property
+    def j3(self):
+        return self.args[3]
+
+    @property
+    def j(self):
+        return self.args[4]
+
+    @property
+    def j23(self):
+        return self.args[5]
+
+    @property
+    def is_symbolic(self):
+        return not all(arg.is_number for arg in self.args)
+
+    # This is modified from the _print_Matrix method
+    def _pretty(self, printer, *args):
+        m = ((printer._print(self.j1), printer._print(self.j3)),
+            (printer._print(self.j2), printer._print(self.j)),
+            (printer._print(self.j12), printer._print(self.j23)))
+        hsep = 2
+        vsep = 1
+        maxw = [-1]*3
+        for j in range(3):
+            maxw[j] = max(m[j][i].width() for i in range(2))
+        D = None
+        for i in range(2):
+            D_row = None
+            for j in range(3):
+                s = m[j][i]
+                wdelta = maxw[j] - s.width()
+                wleft = wdelta //2
+                wright = wdelta - wleft
+
+                s = prettyForm(*s.right(' '*wright))
+                s = prettyForm(*s.left(' '*wleft))
+
+                if D_row is None:
+                    D_row = s
+                    continue
+                D_row = prettyForm(*D_row.right(' '*hsep))
+                D_row = prettyForm(*D_row.right(s))
+            if D is None:
+                D = D_row
+                continue
+            for _ in range(vsep):
+                D = prettyForm(*D.below(' '))
+            D = prettyForm(*D.below(D_row))
+        D = prettyForm(*D.parens(left='{', right='}'))
+        return D
+
+    def _latex(self, printer, *args):
+        label = map(printer._print, (self.j1, self.j2, self.j12,
+                    self.j3, self.j, self.j23))
+        return r'\left\{\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \end{array}\right\}' % \
+            tuple(label)
+
+    def doit(self, **hints):
+        if self.is_symbolic:
+            raise ValueError("Coefficients must be numerical")
+        return wigner_6j(self.j1, self.j2, self.j12, self.j3, self.j, self.j23)
+
+
+class Wigner9j(Expr):
+    """Class for the Wigner-9j symbols
+
+    See Also
+    ========
+
+    Wigner3j: Wigner-3j symbols
+
+    """
+    def __new__(cls, j1, j2, j12, j3, j4, j34, j13, j24, j):
+        args = map(sympify, (j1, j2, j12, j3, j4, j34, j13, j24, j))
+        return Expr.__new__(cls, *args)
+
+    @property
+    def j1(self):
+        return self.args[0]
+
+    @property
+    def j2(self):
+        return self.args[1]
+
+    @property
+    def j12(self):
+        return self.args[2]
+
+    @property
+    def j3(self):
+        return self.args[3]
+
+    @property
+    def j4(self):
+        return self.args[4]
+
+    @property
+    def j34(self):
+        return self.args[5]
+
+    @property
+    def j13(self):
+        return self.args[6]
+
+    @property
+    def j24(self):
+        return self.args[7]
+
+    @property
+    def j(self):
+        return self.args[8]
+
+    @property
+    def is_symbolic(self):
+        return not all(arg.is_number for arg in self.args)
+
+    # This is modified from the _print_Matrix method
+    def _pretty(self, printer, *args):
+        m = (
+            (printer._print(
+                self.j1), printer._print(self.j3), printer._print(self.j13)),
+            (printer._print(
+                self.j2), printer._print(self.j4), printer._print(self.j24)),
+            (printer._print(self.j12), printer._print(self.j34), printer._print(self.j)))
+        hsep = 2
+        vsep = 1
+        maxw = [-1]*3
+        for j in range(3):
+            maxw[j] = max(m[j][i].width() for i in range(3))
+        D = None
+        for i in range(3):
+            D_row = None
+            for j in range(3):
+                s = m[j][i]
+                wdelta = maxw[j] - s.width()
+                wleft = wdelta //2
+                wright = wdelta - wleft
+
+                s = prettyForm(*s.right(' '*wright))
+                s = prettyForm(*s.left(' '*wleft))
+
+                if D_row is None:
+                    D_row = s
+                    continue
+                D_row = prettyForm(*D_row.right(' '*hsep))
+                D_row = prettyForm(*D_row.right(s))
+            if D is None:
+                D = D_row
+                continue
+            for _ in range(vsep):
+                D = prettyForm(*D.below(' '))
+            D = prettyForm(*D.below(D_row))
+        D = prettyForm(*D.parens(left='{', right='}'))
+        return D
+
+    def _latex(self, printer, *args):
+        label = map(printer._print, (self.j1, self.j2, self.j12, self.j3,
+                self.j4, self.j34, self.j13, self.j24, self.j))
+        return r'\left\{\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \\ %s & %s & %s \end{array}\right\}' % \
+            tuple(label)
+
+    def doit(self, **hints):
+        if self.is_symbolic:
+            raise ValueError("Coefficients must be numerical")
+        return wigner_9j(self.j1, self.j2, self.j12, self.j3, self.j4, self.j34, self.j13, self.j24, self.j)
+
+
+def cg_simp(e):
+    """Simplify and combine CG coefficients.
+
+    Explanation
+    ===========
+
+    This function uses various symmetry and properties of sums and
+    products of Clebsch-Gordan coefficients to simplify statements
+    involving these terms [1]_.
+
+    Examples
+    ========
+
+    Simplify the sum over CG(a,alpha,0,0,a,alpha) for all alpha to
+    2*a+1
+
+        >>> from sympy.physics.quantum.cg import CG, cg_simp
+        >>> a = CG(1,1,0,0,1,1)
+        >>> b = CG(1,0,0,0,1,0)
+        >>> c = CG(1,-1,0,0,1,-1)
+        >>> cg_simp(a+b+c)
+        3
+
+    See Also
+    ========
+
+    CG: Clebsh-Gordan coefficients
+
+    References
+    ==========
+
+    .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
+    """
+    if isinstance(e, Add):
+        return _cg_simp_add(e)
+    elif isinstance(e, Sum):
+        return _cg_simp_sum(e)
+    elif isinstance(e, Mul):
+        return Mul(*[cg_simp(arg) for arg in e.args])
+    elif isinstance(e, Pow):
+        return Pow(cg_simp(e.base), e.exp)
+    else:
+        return e
+
+
+def _cg_simp_add(e):
+    #TODO: Improve simplification method
+    """Takes a sum of terms involving Clebsch-Gordan coefficients and
+    simplifies the terms.
+
+    Explanation
+    ===========
+
+    First, we create two lists, cg_part, which is all the terms involving CG
+    coefficients, and other_part, which is all other terms. The cg_part list
+    is then passed to the simplification methods, which return the new cg_part
+    and any additional terms that are added to other_part
+    """
+    cg_part = []
+    other_part = []
+
+    e = expand(e)
+    for arg in e.args:
+        if arg.has(CG):
+            if isinstance(arg, Sum):
+                other_part.append(_cg_simp_sum(arg))
+            elif isinstance(arg, Mul):
+                terms = 1
+                for term in arg.args:
+                    if isinstance(term, Sum):
+                        terms *= _cg_simp_sum(term)
+                    else:
+                        terms *= term
+                if terms.has(CG):
+                    cg_part.append(terms)
+                else:
+                    other_part.append(terms)
+            else:
+                cg_part.append(arg)
+        else:
+            other_part.append(arg)
+
+    cg_part, other = _check_varsh_871_1(cg_part)
+    other_part.append(other)
+    cg_part, other = _check_varsh_871_2(cg_part)
+    other_part.append(other)
+    cg_part, other = _check_varsh_872_9(cg_part)
+    other_part.append(other)
+    return Add(*cg_part) + Add(*other_part)
+
+
+def _check_varsh_871_1(term_list):
+    # Sum( CG(a,alpha,b,0,a,alpha), (alpha, -a, a)) == KroneckerDelta(b,0)
+    a, alpha, b, lt = map(Wild, ('a', 'alpha', 'b', 'lt'))
+    expr = lt*CG(a, alpha, b, 0, a, alpha)
+    simp = (2*a + 1)*KroneckerDelta(b, 0)
+    sign = lt/abs(lt)
+    build_expr = 2*a + 1
+    index_expr = a + alpha
+    return _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, lt), (a, b), build_expr, index_expr)
+
+
+def _check_varsh_871_2(term_list):
+    # Sum((-1)**(a-alpha)*CG(a,alpha,a,-alpha,c,0),(alpha,-a,a))
+    a, alpha, c, lt = map(Wild, ('a', 'alpha', 'c', 'lt'))
+    expr = lt*CG(a, alpha, a, -alpha, c, 0)
+    simp = sqrt(2*a + 1)*KroneckerDelta(c, 0)
+    sign = (-1)**(a - alpha)*lt/abs(lt)
+    build_expr = 2*a + 1
+    index_expr = a + alpha
+    return _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, c, lt), (a, c), build_expr, index_expr)
+
+
+def _check_varsh_872_9(term_list):
+    # Sum( CG(a,alpha,b,beta,c,gamma)*CG(a,alpha',b,beta',c,gamma), (gamma, -c, c), (c, abs(a-b), a+b))
+    a, alpha, alphap, b, beta, betap, c, gamma, lt = map(Wild, (
+        'a', 'alpha', 'alphap', 'b', 'beta', 'betap', 'c', 'gamma', 'lt'))
+    # Case alpha==alphap, beta==betap
+
+    # For numerical alpha,beta
+    expr = lt*CG(a, alpha, b, beta, c, gamma)**2
+    simp = S.One
+    sign = lt/abs(lt)
+    x = abs(a - b)
+    y = abs(alpha + beta)
+    build_expr = a + b + 1 - Piecewise((x, x > y), (0, Eq(x, y)), (y, y > x))
+    index_expr = a + b - c
+    term_list, other1 = _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, beta, c, gamma, lt), (a, alpha, b, beta), build_expr, index_expr)
+
+    # For symbolic alpha,beta
+    x = abs(a - b)
+    y = a + b
+    build_expr = (y + 1 - x)*(x + y + 1)
+    index_expr = (c - x)*(x + c) + c + gamma
+    term_list, other2 = _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, beta, c, gamma, lt), (a, alpha, b, beta), build_expr, index_expr)
+
+    # Case alpha!=alphap or beta!=betap
+    # Note: this only works with leading term of 1, pattern matching is unable to match when there is a Wild leading term
+    # For numerical alpha,alphap,beta,betap
+    expr = CG(a, alpha, b, beta, c, gamma)*CG(a, alphap, b, betap, c, gamma)
+    simp = KroneckerDelta(alpha, alphap)*KroneckerDelta(beta, betap)
+    sign = S.One
+    x = abs(a - b)
+    y = abs(alpha + beta)
+    build_expr = a + b + 1 - Piecewise((x, x > y), (0, Eq(x, y)), (y, y > x))
+    index_expr = a + b - c
+    term_list, other3 = _check_cg_simp(expr, simp, sign, S.One, term_list, (a, alpha, alphap, b, beta, betap, c, gamma), (a, alpha, alphap, b, beta, betap), build_expr, index_expr)
+
+    # For symbolic alpha,alphap,beta,betap
+    x = abs(a - b)
+    y = a + b
+    build_expr = (y + 1 - x)*(x + y + 1)
+    index_expr = (c - x)*(x + c) + c + gamma
+    term_list, other4 = _check_cg_simp(expr, simp, sign, S.One, term_list, (a, alpha, alphap, b, beta, betap, c, gamma), (a, alpha, alphap, b, beta, betap), build_expr, index_expr)
+
+    return term_list, other1 + other2 + other4
+
+
+def _check_cg_simp(expr, simp, sign, lt, term_list, variables, dep_variables, build_index_expr, index_expr):
+    """ Checks for simplifications that can be made, returning a tuple of the
+    simplified list of terms and any terms generated by simplification.
+
+    Parameters
+    ==========
+
+    expr: expression
+        The expression with Wild terms that will be matched to the terms in
+        the sum
+
+    simp: expression
+        The expression with Wild terms that is substituted in place of the CG
+        terms in the case of simplification
+
+    sign: expression
+        The expression with Wild terms denoting the sign that is on expr that
+        must match
+
+    lt: expression
+        The expression with Wild terms that gives the leading term of the
+        matched expr
+
+    term_list: list
+        A list of all of the terms is the sum to be simplified
+
+    variables: list
+        A list of all the variables that appears in expr
+
+    dep_variables: list
+        A list of the variables that must match for all the terms in the sum,
+        i.e. the dependent variables
+
+    build_index_expr: expression
+        Expression with Wild terms giving the number of elements in cg_index
+
+    index_expr: expression
+        Expression with Wild terms giving the index terms have when storing
+        them to cg_index
+
+    """
+    other_part = 0
+    i = 0
+    while i < len(term_list):
+        sub_1 = _check_cg(term_list[i], expr, len(variables))
+        if sub_1 is None:
+            i += 1
+            continue
+        if not build_index_expr.subs(sub_1).is_number:
+            i += 1
+            continue
+        sub_dep = [(x, sub_1[x]) for x in dep_variables]
+        cg_index = [None]*build_index_expr.subs(sub_1)
+        for j in range(i, len(term_list)):
+            sub_2 = _check_cg(term_list[j], expr.subs(sub_dep), len(variables) - len(dep_variables), sign=(sign.subs(sub_1), sign.subs(sub_dep)))
+            if sub_2 is None:
+                continue
+            if not index_expr.subs(sub_dep).subs(sub_2).is_number:
+                continue
+            cg_index[index_expr.subs(sub_dep).subs(sub_2)] = j, expr.subs(lt, 1).subs(sub_dep).subs(sub_2), lt.subs(sub_2), sign.subs(sub_dep).subs(sub_2)
+        if not any(i is None for i in cg_index):
+            min_lt = min(*[ abs(term[2]) for term in cg_index ])
+            indices = [ term[0] for term in cg_index]
+            indices.sort()
+            indices.reverse()
+            [ term_list.pop(j) for j in indices ]
+            for term in cg_index:
+                if abs(term[2]) > min_lt:
+                    term_list.append( (term[2] - min_lt*term[3])*term[1] )
+            other_part += min_lt*(sign*simp).subs(sub_1)
+        else:
+            i += 1
+    return term_list, other_part
+
+
+def _check_cg(cg_term, expr, length, sign=None):
+    """Checks whether a term matches the given expression"""
+    # TODO: Check for symmetries
+    matches = cg_term.match(expr)
+    if matches is None:
+        return
+    if sign is not None:
+        if not isinstance(sign, tuple):
+            raise TypeError('sign must be a tuple')
+        if not sign[0] == (sign[1]).subs(matches):
+            return
+    if len(matches) == length:
+        return matches
+
+
+def _cg_simp_sum(e):
+    e = _check_varsh_sum_871_1(e)
+    e = _check_varsh_sum_871_2(e)
+    e = _check_varsh_sum_872_4(e)
+    return e
+
+
+def _check_varsh_sum_871_1(e):
+    a = Wild('a')
+    alpha = symbols('alpha')
+    b = Wild('b')
+    match = e.match(Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a)))
+    if match is not None and len(match) == 2:
+        return ((2*a + 1)*KroneckerDelta(b, 0)).subs(match)
+    return e
+
+
+def _check_varsh_sum_871_2(e):
+    a = Wild('a')
+    alpha = symbols('alpha')
+    c = Wild('c')
+    match = e.match(
+        Sum((-1)**(a - alpha)*CG(a, alpha, a, -alpha, c, 0), (alpha, -a, a)))
+    if match is not None and len(match) == 2:
+        return (sqrt(2*a + 1)*KroneckerDelta(c, 0)).subs(match)
+    return e
+
+
+def _check_varsh_sum_872_4(e):
+    alpha = symbols('alpha')
+    beta = symbols('beta')
+    a = Wild('a')
+    b = Wild('b')
+    c = Wild('c')
+    cp = Wild('cp')
+    gamma = Wild('gamma')
+    gammap = Wild('gammap')
+    cg1 = CG(a, alpha, b, beta, c, gamma)
+    cg2 = CG(a, alpha, b, beta, cp, gammap)
+    match1 = e.match(Sum(cg1*cg2, (alpha, -a, a), (beta, -b, b)))
+    if match1 is not None and len(match1) == 6:
+        return (KroneckerDelta(c, cp)*KroneckerDelta(gamma, gammap)).subs(match1)
+    match2 = e.match(Sum(cg1**2, (alpha, -a, a), (beta, -b, b)))
+    if match2 is not None and len(match2) == 4:
+        return S.One
+    return e
+
+
+def _cg_list(term):
+    if isinstance(term, CG):
+        return (term,), 1, 1
+    cg = []
+    coeff = 1
+    if not isinstance(term, (Mul, Pow)):
+        raise NotImplementedError('term must be CG, Add, Mul or Pow')
+    if isinstance(term, Pow) and term.exp.is_number:
+        if term.exp.is_number:
+            [ cg.append(term.base) for _ in range(term.exp) ]
+        else:
+            return (term,), 1, 1
+    if isinstance(term, Mul):
+        for arg in term.args:
+            if isinstance(arg, CG):
+                cg.append(arg)
+            else:
+                coeff *= arg
+        return cg, coeff, coeff/abs(coeff)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/circuitplot.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/circuitplot.py
new file mode 100644
index 0000000000000000000000000000000000000000..316a4be613b2e275565999130c06ea678acd8b96
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/circuitplot.py
@@ -0,0 +1,370 @@
+"""Matplotlib based plotting of quantum circuits.
+
+Todo:
+
+* Optimize printing of large circuits.
+* Get this to work with single gates.
+* Do a better job checking the form of circuits to make sure it is a Mul of
+  Gates.
+* Get multi-target gates plotting.
+* Get initial and final states to plot.
+* Get measurements to plot. Might need to rethink measurement as a gate
+  issue.
+* Get scale and figsize to be handled in a better way.
+* Write some tests/examples!
+"""
+
+from __future__ import annotations
+
+from sympy.core.mul import Mul
+from sympy.external import import_module
+from sympy.physics.quantum.gate import Gate, OneQubitGate, CGate, CGateS
+
+
+__all__ = [
+    'CircuitPlot',
+    'circuit_plot',
+    'labeller',
+    'Mz',
+    'Mx',
+    'CreateOneQubitGate',
+    'CreateCGate',
+]
+
+np = import_module('numpy')
+matplotlib = import_module(
+    'matplotlib', import_kwargs={'fromlist': ['pyplot']},
+    catch=(RuntimeError,))  # This is raised in environments that have no display.
+
+if np and matplotlib:
+    pyplot = matplotlib.pyplot
+    Line2D = matplotlib.lines.Line2D
+    Circle = matplotlib.patches.Circle
+
+#from matplotlib import rc
+#rc('text',usetex=True)
+
+class CircuitPlot:
+    """A class for managing a circuit plot."""
+
+    scale = 1.0
+    fontsize = 20.0
+    linewidth = 1.0
+    control_radius = 0.05
+    not_radius = 0.15
+    swap_delta = 0.05
+    labels: list[str] = []
+    inits: dict[str, str] = {}
+    label_buffer = 0.5
+
+    def __init__(self, c, nqubits, **kwargs):
+        if not np or not matplotlib:
+            raise ImportError('numpy or matplotlib not available.')
+        self.circuit = c
+        self.ngates = len(self.circuit.args)
+        self.nqubits = nqubits
+        self.update(kwargs)
+        self._create_grid()
+        self._create_figure()
+        self._plot_wires()
+        self._plot_gates()
+        self._finish()
+
+    def update(self, kwargs):
+        """Load the kwargs into the instance dict."""
+        self.__dict__.update(kwargs)
+
+    def _create_grid(self):
+        """Create the grid of wires."""
+        scale = self.scale
+        wire_grid = np.arange(0.0, self.nqubits*scale, scale, dtype=float)
+        gate_grid = np.arange(0.0, self.ngates*scale, scale, dtype=float)
+        self._wire_grid = wire_grid
+        self._gate_grid = gate_grid
+
+    def _create_figure(self):
+        """Create the main matplotlib figure."""
+        self._figure = pyplot.figure(
+            figsize=(self.ngates*self.scale, self.nqubits*self.scale),
+            facecolor='w',
+            edgecolor='w'
+        )
+        ax = self._figure.add_subplot(
+            1, 1, 1,
+            frameon=True
+        )
+        ax.set_axis_off()
+        offset = 0.5*self.scale
+        ax.set_xlim(self._gate_grid[0] - offset, self._gate_grid[-1] + offset)
+        ax.set_ylim(self._wire_grid[0] - offset, self._wire_grid[-1] + offset)
+        ax.set_aspect('equal')
+        self._axes = ax
+
+    def _plot_wires(self):
+        """Plot the wires of the circuit diagram."""
+        xstart = self._gate_grid[0]
+        xstop = self._gate_grid[-1]
+        xdata = (xstart - self.scale, xstop + self.scale)
+        for i in range(self.nqubits):
+            ydata = (self._wire_grid[i], self._wire_grid[i])
+            line = Line2D(
+                xdata, ydata,
+                color='k',
+                lw=self.linewidth
+            )
+            self._axes.add_line(line)
+            if self.labels:
+                init_label_buffer = 0
+                if self.inits.get(self.labels[i]): init_label_buffer = 0.25
+                self._axes.text(
+                    xdata[0]-self.label_buffer-init_label_buffer,ydata[0],
+                    render_label(self.labels[i],self.inits),
+                    size=self.fontsize,
+                    color='k',ha='center',va='center')
+        self._plot_measured_wires()
+
+    def _plot_measured_wires(self):
+        ismeasured = self._measurements()
+        xstop = self._gate_grid[-1]
+        dy = 0.04 # amount to shift wires when doubled
+        # Plot doubled wires after they are measured
+        for im in ismeasured:
+            xdata = (self._gate_grid[ismeasured[im]],xstop+self.scale)
+            ydata = (self._wire_grid[im]+dy,self._wire_grid[im]+dy)
+            line = Line2D(
+                xdata, ydata,
+                color='k',
+                lw=self.linewidth
+            )
+            self._axes.add_line(line)
+        # Also double any controlled lines off these wires
+        for i,g in enumerate(self._gates()):
+            if isinstance(g, (CGate, CGateS)):
+                wires = g.controls + g.targets
+                for wire in wires:
+                    if wire in ismeasured and \
+                           self._gate_grid[i] > self._gate_grid[ismeasured[wire]]:
+                        ydata = min(wires), max(wires)
+                        xdata = self._gate_grid[i]-dy, self._gate_grid[i]-dy
+                        line = Line2D(
+                            xdata, ydata,
+                            color='k',
+                            lw=self.linewidth
+                            )
+                        self._axes.add_line(line)
+    def _gates(self):
+        """Create a list of all gates in the circuit plot."""
+        gates = []
+        if isinstance(self.circuit, Mul):
+            for g in reversed(self.circuit.args):
+                if isinstance(g, Gate):
+                    gates.append(g)
+        elif isinstance(self.circuit, Gate):
+            gates.append(self.circuit)
+        return gates
+
+    def _plot_gates(self):
+        """Iterate through the gates and plot each of them."""
+        for i, gate in enumerate(self._gates()):
+            gate.plot_gate(self, i)
+
+    def _measurements(self):
+        """Return a dict ``{i:j}`` where i is the index of the wire that has
+        been measured, and j is the gate where the wire is measured.
+        """
+        ismeasured = {}
+        for i,g in enumerate(self._gates()):
+            if getattr(g,'measurement',False):
+                for target in g.targets:
+                    if target in ismeasured:
+                        if ismeasured[target] > i:
+                            ismeasured[target] = i
+                    else:
+                        ismeasured[target] = i
+        return ismeasured
+
+    def _finish(self):
+        # Disable clipping to make panning work well for large circuits.
+        for o in self._figure.findobj():
+            o.set_clip_on(False)
+
+    def one_qubit_box(self, t, gate_idx, wire_idx):
+        """Draw a box for a single qubit gate."""
+        x = self._gate_grid[gate_idx]
+        y = self._wire_grid[wire_idx]
+        self._axes.text(
+            x, y, t,
+            color='k',
+            ha='center',
+            va='center',
+            bbox={"ec": 'k', "fc": 'w', "fill": True, "lw": self.linewidth},
+            size=self.fontsize
+        )
+
+    def two_qubit_box(self, t, gate_idx, wire_idx):
+        """Draw a box for a two qubit gate. Does not work yet.
+        """
+        # x = self._gate_grid[gate_idx]
+        # y = self._wire_grid[wire_idx]+0.5
+        print(self._gate_grid)
+        print(self._wire_grid)
+        # unused:
+        # obj = self._axes.text(
+        #     x, y, t,
+        #     color='k',
+        #     ha='center',
+        #     va='center',
+        #     bbox=dict(ec='k', fc='w', fill=True, lw=self.linewidth),
+        #     size=self.fontsize
+        # )
+
+    def control_line(self, gate_idx, min_wire, max_wire):
+        """Draw a vertical control line."""
+        xdata = (self._gate_grid[gate_idx], self._gate_grid[gate_idx])
+        ydata = (self._wire_grid[min_wire], self._wire_grid[max_wire])
+        line = Line2D(
+            xdata, ydata,
+            color='k',
+            lw=self.linewidth
+        )
+        self._axes.add_line(line)
+
+    def control_point(self, gate_idx, wire_idx):
+        """Draw a control point."""
+        x = self._gate_grid[gate_idx]
+        y = self._wire_grid[wire_idx]
+        radius = self.control_radius
+        c = Circle(
+            (x, y),
+            radius*self.scale,
+            ec='k',
+            fc='k',
+            fill=True,
+            lw=self.linewidth
+        )
+        self._axes.add_patch(c)
+
+    def not_point(self, gate_idx, wire_idx):
+        """Draw a NOT gates as the circle with plus in the middle."""
+        x = self._gate_grid[gate_idx]
+        y = self._wire_grid[wire_idx]
+        radius = self.not_radius
+        c = Circle(
+            (x, y),
+            radius,
+            ec='k',
+            fc='w',
+            fill=False,
+            lw=self.linewidth
+        )
+        self._axes.add_patch(c)
+        l = Line2D(
+            (x, x), (y - radius, y + radius),
+            color='k',
+            lw=self.linewidth
+        )
+        self._axes.add_line(l)
+
+    def swap_point(self, gate_idx, wire_idx):
+        """Draw a swap point as a cross."""
+        x = self._gate_grid[gate_idx]
+        y = self._wire_grid[wire_idx]
+        d = self.swap_delta
+        l1 = Line2D(
+            (x - d, x + d),
+            (y - d, y + d),
+            color='k',
+            lw=self.linewidth
+        )
+        l2 = Line2D(
+            (x - d, x + d),
+            (y + d, y - d),
+            color='k',
+            lw=self.linewidth
+        )
+        self._axes.add_line(l1)
+        self._axes.add_line(l2)
+
+def circuit_plot(c, nqubits, **kwargs):
+    """Draw the circuit diagram for the circuit with nqubits.
+
+    Parameters
+    ==========
+
+    c : circuit
+        The circuit to plot. Should be a product of Gate instances.
+    nqubits : int
+        The number of qubits to include in the circuit. Must be at least
+        as big as the largest ``min_qubits`` of the gates.
+    """
+    return CircuitPlot(c, nqubits, **kwargs)
+
+def render_label(label, inits={}):
+    """Slightly more flexible way to render labels.
+
+    >>> from sympy.physics.quantum.circuitplot import render_label
+    >>> render_label('q0')
+    '$\\\\left|q0\\\\right\\\\rangle$'
+    >>> render_label('q0', {'q0':'0'})
+    '$\\\\left|q0\\\\right\\\\rangle=\\\\left|0\\\\right\\\\rangle$'
+    """
+    init = inits.get(label)
+    if init:
+        return r'$\left|%s\right\rangle=\left|%s\right\rangle$' % (label, init)
+    return r'$\left|%s\right\rangle$' % label
+
+def labeller(n, symbol='q'):
+    """Autogenerate labels for wires of quantum circuits.
+
+    Parameters
+    ==========
+
+    n : int
+        number of qubits in the circuit.
+    symbol : string
+        A character string to precede all gate labels. E.g. 'q_0', 'q_1', etc.
+
+    >>> from sympy.physics.quantum.circuitplot import labeller
+    >>> labeller(2)
+    ['q_1', 'q_0']
+    >>> labeller(3,'j')
+    ['j_2', 'j_1', 'j_0']
+    """
+    return ['%s_%d' % (symbol,n-i-1) for i in range(n)]
+
+class Mz(OneQubitGate):
+    """Mock-up of a z measurement gate.
+
+    This is in circuitplot rather than gate.py because it's not a real
+    gate, it just draws one.
+    """
+    measurement = True
+    gate_name='Mz'
+    gate_name_latex='M_z'
+
+class Mx(OneQubitGate):
+    """Mock-up of an x measurement gate.
+
+    This is in circuitplot rather than gate.py because it's not a real
+    gate, it just draws one.
+    """
+    measurement = True
+    gate_name='Mx'
+    gate_name_latex='M_x'
+
+class CreateOneQubitGate(type):
+    def __new__(mcl, name, latexname=None):
+        if not latexname:
+            latexname = name
+        return type(name + "Gate", (OneQubitGate,),
+            {'gate_name': name, 'gate_name_latex': latexname})
+
+def CreateCGate(name, latexname=None):
+    """Use a lexical closure to make a controlled gate.
+    """
+    if not latexname:
+        latexname = name
+    onequbitgate = CreateOneQubitGate(name, latexname)
+    def ControlledGate(ctrls,target):
+        return CGate(tuple(ctrls),onequbitgate(target))
+    return ControlledGate
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/circuitutils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/circuitutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..84955d3d724a2658f2dc3b26738133bd46f1aa57
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/circuitutils.py
@@ -0,0 +1,488 @@
+"""Primitive circuit operations on quantum circuits."""
+
+from functools import reduce
+
+from sympy.core.sorting import default_sort_key
+from sympy.core.containers import Tuple
+from sympy.core.mul import Mul
+from sympy.core.symbol import Symbol
+from sympy.core.sympify import sympify
+from sympy.utilities import numbered_symbols
+from sympy.physics.quantum.gate import Gate
+
+__all__ = [
+    'kmp_table',
+    'find_subcircuit',
+    'replace_subcircuit',
+    'convert_to_symbolic_indices',
+    'convert_to_real_indices',
+    'random_reduce',
+    'random_insert'
+]
+
+
+def kmp_table(word):
+    """Build the 'partial match' table of the Knuth-Morris-Pratt algorithm.
+
+    Note: This is applicable to strings or
+    quantum circuits represented as tuples.
+    """
+
+    # Current position in subcircuit
+    pos = 2
+    # Beginning position of candidate substring that
+    # may reappear later in word
+    cnd = 0
+    # The 'partial match' table that helps one determine
+    # the next location to start substring search
+    table = []
+    table.append(-1)
+    table.append(0)
+
+    while pos < len(word):
+        if word[pos - 1] == word[cnd]:
+            cnd = cnd + 1
+            table.append(cnd)
+            pos = pos + 1
+        elif cnd > 0:
+            cnd = table[cnd]
+        else:
+            table.append(0)
+            pos = pos + 1
+
+    return table
+
+
+def find_subcircuit(circuit, subcircuit, start=0, end=0):
+    """Finds the subcircuit in circuit, if it exists.
+
+    Explanation
+    ===========
+
+    If the subcircuit exists, the index of the start of
+    the subcircuit in circuit is returned; otherwise,
+    -1 is returned.  The algorithm that is implemented
+    is the Knuth-Morris-Pratt algorithm.
+
+    Parameters
+    ==========
+
+    circuit : tuple, Gate or Mul
+        A tuple of Gates or Mul representing a quantum circuit
+    subcircuit : tuple, Gate or Mul
+        A tuple of Gates or Mul to find in circuit
+    start : int
+        The location to start looking for subcircuit.
+        If start is the same or past end, -1 is returned.
+    end : int
+        The last place to look for a subcircuit.  If end
+        is less than 1 (one), then the length of circuit
+        is taken to be end.
+
+    Examples
+    ========
+
+    Find the first instance of a subcircuit:
+
+    >>> from sympy.physics.quantum.circuitutils import find_subcircuit
+    >>> from sympy.physics.quantum.gate import X, Y, Z, H
+    >>> circuit = X(0)*Z(0)*Y(0)*H(0)
+    >>> subcircuit = Z(0)*Y(0)
+    >>> find_subcircuit(circuit, subcircuit)
+    1
+
+    Find the first instance starting at a specific position:
+
+    >>> find_subcircuit(circuit, subcircuit, start=1)
+    1
+
+    >>> find_subcircuit(circuit, subcircuit, start=2)
+    -1
+
+    >>> circuit = circuit*subcircuit
+    >>> find_subcircuit(circuit, subcircuit, start=2)
+    4
+
+    Find the subcircuit within some interval:
+
+    >>> find_subcircuit(circuit, subcircuit, start=2, end=2)
+    -1
+    """
+
+    if isinstance(circuit, Mul):
+        circuit = circuit.args
+
+    if isinstance(subcircuit, Mul):
+        subcircuit = subcircuit.args
+
+    if len(subcircuit) == 0 or len(subcircuit) > len(circuit):
+        return -1
+
+    if end < 1:
+        end = len(circuit)
+
+    # Location in circuit
+    pos = start
+    # Location in the subcircuit
+    index = 0
+    # 'Partial match' table
+    table = kmp_table(subcircuit)
+
+    while (pos + index) < end:
+        if subcircuit[index] == circuit[pos + index]:
+            index = index + 1
+        else:
+            pos = pos + index - table[index]
+            index = table[index] if table[index] > -1 else 0
+
+        if index == len(subcircuit):
+            return pos
+
+    return -1
+
+
+def replace_subcircuit(circuit, subcircuit, replace=None, pos=0):
+    """Replaces a subcircuit with another subcircuit in circuit,
+    if it exists.
+
+    Explanation
+    ===========
+
+    If multiple instances of subcircuit exists, the first instance is
+    replaced.  The position to being searching from (if different from
+    0) may be optionally given.  If subcircuit cannot be found, circuit
+    is returned.
+
+    Parameters
+    ==========
+
+    circuit : tuple, Gate or Mul
+        A quantum circuit.
+    subcircuit : tuple, Gate or Mul
+        The circuit to be replaced.
+    replace : tuple, Gate or Mul
+        The replacement circuit.
+    pos : int
+        The location to start search and replace
+        subcircuit, if it exists.  This may be used
+        if it is known beforehand that multiple
+        instances exist, and it is desirable to
+        replace a specific instance.  If a negative number
+        is given, pos will be defaulted to 0.
+
+    Examples
+    ========
+
+    Find and remove the subcircuit:
+
+    >>> from sympy.physics.quantum.circuitutils import replace_subcircuit
+    >>> from sympy.physics.quantum.gate import X, Y, Z, H
+    >>> circuit = X(0)*Z(0)*Y(0)*H(0)*X(0)*H(0)*Y(0)
+    >>> subcircuit = Z(0)*Y(0)
+    >>> replace_subcircuit(circuit, subcircuit)
+    (X(0), H(0), X(0), H(0), Y(0))
+
+    Remove the subcircuit given a starting search point:
+
+    >>> replace_subcircuit(circuit, subcircuit, pos=1)
+    (X(0), H(0), X(0), H(0), Y(0))
+
+    >>> replace_subcircuit(circuit, subcircuit, pos=2)
+    (X(0), Z(0), Y(0), H(0), X(0), H(0), Y(0))
+
+    Replace the subcircuit:
+
+    >>> replacement = H(0)*Z(0)
+    >>> replace_subcircuit(circuit, subcircuit, replace=replacement)
+    (X(0), H(0), Z(0), H(0), X(0), H(0), Y(0))
+    """
+
+    if pos < 0:
+        pos = 0
+
+    if isinstance(circuit, Mul):
+        circuit = circuit.args
+
+    if isinstance(subcircuit, Mul):
+        subcircuit = subcircuit.args
+
+    if isinstance(replace, Mul):
+        replace = replace.args
+    elif replace is None:
+        replace = ()
+
+    # Look for the subcircuit starting at pos
+    loc = find_subcircuit(circuit, subcircuit, start=pos)
+
+    # If subcircuit was found
+    if loc > -1:
+        # Get the gates to the left of subcircuit
+        left = circuit[0:loc]
+        # Get the gates to the right of subcircuit
+        right = circuit[loc + len(subcircuit):len(circuit)]
+        # Recombine the left and right side gates into a circuit
+        circuit = left + replace + right
+
+    return circuit
+
+
+def _sympify_qubit_map(mapping):
+    new_map = {}
+    for key in mapping:
+        new_map[key] = sympify(mapping[key])
+    return new_map
+
+
+def convert_to_symbolic_indices(seq, start=None, gen=None, qubit_map=None):
+    """Returns the circuit with symbolic indices and the
+    dictionary mapping symbolic indices to real indices.
+
+    The mapping is 1 to 1 and onto (bijective).
+
+    Parameters
+    ==========
+
+    seq : tuple, Gate/Integer/tuple or Mul
+        A tuple of Gate, Integer, or tuple objects, or a Mul
+    start : Symbol
+        An optional starting symbolic index
+    gen : object
+        An optional numbered symbol generator
+    qubit_map : dict
+        An existing mapping of symbolic indices to real indices
+
+    All symbolic indices have the format 'i#', where # is
+    some number >= 0.
+    """
+
+    if isinstance(seq, Mul):
+        seq = seq.args
+
+    # A numbered symbol generator
+    index_gen = numbered_symbols(prefix='i', start=-1)
+    cur_ndx = next(index_gen)
+
+    # keys are symbolic indices; values are real indices
+    ndx_map = {}
+
+    def create_inverse_map(symb_to_real_map):
+        rev_items = lambda item: (item[1], item[0])
+        return dict(map(rev_items, symb_to_real_map.items()))
+
+    if start is not None:
+        if not isinstance(start, Symbol):
+            msg = 'Expected Symbol for starting index, got %r.' % start
+            raise TypeError(msg)
+        cur_ndx = start
+
+    if gen is not None:
+        if not isinstance(gen, numbered_symbols().__class__):
+            msg = 'Expected a generator, got %r.' % gen
+            raise TypeError(msg)
+        index_gen = gen
+
+    if qubit_map is not None:
+        if not isinstance(qubit_map, dict):
+            msg = ('Expected dict for existing map, got ' +
+                   '%r.' % qubit_map)
+            raise TypeError(msg)
+        ndx_map = qubit_map
+
+    ndx_map = _sympify_qubit_map(ndx_map)
+    # keys are real indices; keys are symbolic indices
+    inv_map = create_inverse_map(ndx_map)
+
+    sym_seq = ()
+    for item in seq:
+        # Nested items, so recurse
+        if isinstance(item, Gate):
+            result = convert_to_symbolic_indices(item.args,
+                                                 qubit_map=ndx_map,
+                                                 start=cur_ndx,
+                                                 gen=index_gen)
+            sym_item, new_map, cur_ndx, index_gen = result
+            ndx_map.update(new_map)
+            inv_map = create_inverse_map(ndx_map)
+
+        elif isinstance(item, (tuple, Tuple)):
+            result = convert_to_symbolic_indices(item,
+                                                 qubit_map=ndx_map,
+                                                 start=cur_ndx,
+                                                 gen=index_gen)
+            sym_item, new_map, cur_ndx, index_gen = result
+            ndx_map.update(new_map)
+            inv_map = create_inverse_map(ndx_map)
+
+        elif item in inv_map:
+            sym_item = inv_map[item]
+
+        else:
+            cur_ndx = next(gen)
+            ndx_map[cur_ndx] = item
+            inv_map[item] = cur_ndx
+            sym_item = cur_ndx
+
+        if isinstance(item, Gate):
+            sym_item = item.__class__(*sym_item)
+
+        sym_seq = sym_seq + (sym_item,)
+
+    return sym_seq, ndx_map, cur_ndx, index_gen
+
+
+def convert_to_real_indices(seq, qubit_map):
+    """Returns the circuit with real indices.
+
+    Parameters
+    ==========
+
+    seq : tuple, Gate/Integer/tuple or Mul
+        A tuple of Gate, Integer, or tuple objects or a Mul
+    qubit_map : dict
+        A dictionary mapping symbolic indices to real indices.
+
+    Examples
+    ========
+
+    Change the symbolic indices to real integers:
+
+    >>> from sympy import symbols
+    >>> from sympy.physics.quantum.circuitutils import convert_to_real_indices
+    >>> from sympy.physics.quantum.gate import X, Y, H
+    >>> i0, i1 = symbols('i:2')
+    >>> index_map = {i0 : 0, i1 : 1}
+    >>> convert_to_real_indices(X(i0)*Y(i1)*H(i0)*X(i1), index_map)
+    (X(0), Y(1), H(0), X(1))
+    """
+
+    if isinstance(seq, Mul):
+        seq = seq.args
+
+    if not isinstance(qubit_map, dict):
+        msg = 'Expected dict for qubit_map, got %r.' % qubit_map
+        raise TypeError(msg)
+
+    qubit_map = _sympify_qubit_map(qubit_map)
+    real_seq = ()
+    for item in seq:
+        # Nested items, so recurse
+        if isinstance(item, Gate):
+            real_item = convert_to_real_indices(item.args, qubit_map)
+
+        elif isinstance(item, (tuple, Tuple)):
+            real_item = convert_to_real_indices(item, qubit_map)
+
+        else:
+            real_item = qubit_map[item]
+
+        if isinstance(item, Gate):
+            real_item = item.__class__(*real_item)
+
+        real_seq = real_seq + (real_item,)
+
+    return real_seq
+
+
+def random_reduce(circuit, gate_ids, seed=None):
+    """Shorten the length of a quantum circuit.
+
+    Explanation
+    ===========
+
+    random_reduce looks for circuit identities in circuit, randomly chooses
+    one to remove, and returns a shorter yet equivalent circuit.  If no
+    identities are found, the same circuit is returned.
+
+    Parameters
+    ==========
+
+    circuit : Gate tuple of Mul
+        A tuple of Gates representing a quantum circuit
+    gate_ids : list, GateIdentity
+        List of gate identities to find in circuit
+    seed : int or list
+        seed used for _randrange; to override the random selection, provide a
+        list of integers: the elements of gate_ids will be tested in the order
+        given by the list
+
+    """
+    from sympy.core.random import _randrange
+
+    if not gate_ids:
+        return circuit
+
+    if isinstance(circuit, Mul):
+        circuit = circuit.args
+
+    ids = flatten_ids(gate_ids)
+
+    # Create the random integer generator with the seed
+    randrange = _randrange(seed)
+
+    # Look for an identity in the circuit
+    while ids:
+        i = randrange(len(ids))
+        id = ids.pop(i)
+        if find_subcircuit(circuit, id) != -1:
+            break
+    else:
+        # no identity was found
+        return circuit
+
+    # return circuit with the identity removed
+    return replace_subcircuit(circuit, id)
+
+
+def random_insert(circuit, choices, seed=None):
+    """Insert a circuit into another quantum circuit.
+
+    Explanation
+    ===========
+
+    random_insert randomly chooses a location in the circuit to insert
+    a randomly selected circuit from amongst the given choices.
+
+    Parameters
+    ==========
+
+    circuit : Gate tuple or Mul
+        A tuple or Mul of Gates representing a quantum circuit
+    choices : list
+        Set of circuit choices
+    seed : int or list
+        seed used for _randrange; to override the random selections, give
+        a list two integers, [i, j] where i is the circuit location where
+        choice[j] will be inserted.
+
+    Notes
+    =====
+
+    Indices for insertion should be [0, n] if n is the length of the
+    circuit.
+    """
+    from sympy.core.random import _randrange
+
+    if not choices:
+        return circuit
+
+    if isinstance(circuit, Mul):
+        circuit = circuit.args
+
+    # get the location in the circuit and the element to insert from choices
+    randrange = _randrange(seed)
+    loc = randrange(len(circuit) + 1)
+    choice = choices[randrange(len(choices))]
+
+    circuit = list(circuit)
+    circuit[loc: loc] = choice
+    return tuple(circuit)
+
+# Flatten the GateIdentity objects (with gate rules) into one single list
+
+
+def flatten_ids(ids):
+    collapse = lambda acc, an_id: acc + sorted(an_id.equivalent_ids,
+                                        key=default_sort_key)
+    ids = reduce(collapse, ids, [])
+    ids.sort(key=default_sort_key)
+    return ids
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/commutator.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/commutator.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2d97a679e27387077429a9973de21ad868e84ac
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/commutator.py
@@ -0,0 +1,256 @@
+"""The commutator: [A,B] = A*B - B*A."""
+
+from sympy.core.add import Add
+from sympy.core.expr import Expr
+from sympy.core.kind import KindDispatcher
+from sympy.core.mul import Mul
+from sympy.core.power import Pow
+from sympy.core.singleton import S
+from sympy.printing.pretty.stringpict import prettyForm
+
+from sympy.physics.quantum.dagger import Dagger
+from sympy.physics.quantum.kind import _OperatorKind, OperatorKind
+
+
+__all__ = [
+    'Commutator'
+]
+
+#-----------------------------------------------------------------------------
+# Commutator
+#-----------------------------------------------------------------------------
+
+
+class Commutator(Expr):
+    """The standard commutator, in an unevaluated state.
+
+    Explanation
+    ===========
+
+    Evaluating a commutator is defined [1]_ as: ``[A, B] = A*B - B*A``. This
+    class returns the commutator in an unevaluated form. To evaluate the
+    commutator, use the ``.doit()`` method.
+
+    Canonical ordering of a commutator is ``[A, B]`` for ``A < B``. The
+    arguments of the commutator are put into canonical order using ``__cmp__``.
+    If ``B < A``, then ``[B, A]`` is returned as ``-[A, B]``.
+
+    Parameters
+    ==========
+
+    A : Expr
+        The first argument of the commutator [A,B].
+    B : Expr
+        The second argument of the commutator [A,B].
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum import Commutator, Dagger, Operator
+    >>> from sympy.abc import x, y
+    >>> A = Operator('A')
+    >>> B = Operator('B')
+    >>> C = Operator('C')
+
+    Create a commutator and use ``.doit()`` to evaluate it:
+
+    >>> comm = Commutator(A, B)
+    >>> comm
+    [A,B]
+    >>> comm.doit()
+    A*B - B*A
+
+    The commutator orders it arguments in canonical order:
+
+    >>> comm = Commutator(B, A); comm
+    -[A,B]
+
+    Commutative constants are factored out:
+
+    >>> Commutator(3*x*A, x*y*B)
+    3*x**2*y*[A,B]
+
+    Using ``.expand(commutator=True)``, the standard commutator expansion rules
+    can be applied:
+
+    >>> Commutator(A+B, C).expand(commutator=True)
+    [A,C] + [B,C]
+    >>> Commutator(A, B+C).expand(commutator=True)
+    [A,B] + [A,C]
+    >>> Commutator(A*B, C).expand(commutator=True)
+    [A,C]*B + A*[B,C]
+    >>> Commutator(A, B*C).expand(commutator=True)
+    [A,B]*C + B*[A,C]
+
+    Adjoint operations applied to the commutator are properly applied to the
+    arguments:
+
+    >>> Dagger(Commutator(A, B))
+    -[Dagger(A),Dagger(B)]
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Commutator
+    """
+    is_commutative = False
+
+    _kind_dispatcher = KindDispatcher("Commutator_kind_dispatcher", commutative=True)
+
+    @property
+    def kind(self):
+        arg_kinds = (a.kind for a in self.args)
+        return self._kind_dispatcher(*arg_kinds)
+
+    def __new__(cls, A, B):
+        r = cls.eval(A, B)
+        if r is not None:
+            return r
+        obj = Expr.__new__(cls, A, B)
+        return obj
+
+    @classmethod
+    def eval(cls, a, b):
+        if not (a and b):
+            return S.Zero
+        if a == b:
+            return S.Zero
+        if a.is_commutative or b.is_commutative:
+            return S.Zero
+
+        # [xA,yB]  ->  xy*[A,B]
+        ca, nca = a.args_cnc()
+        cb, ncb = b.args_cnc()
+        c_part = ca + cb
+        if c_part:
+            return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb)))
+
+        # Canonical ordering of arguments
+        # The Commutator [A, B] is in canonical form if A < B.
+        if a.compare(b) == 1:
+            return S.NegativeOne*cls(b, a)
+
+    def _expand_pow(self, A, B, sign):
+        exp = A.exp
+        if not exp.is_integer or not exp.is_constant() or abs(exp) <= 1:
+            # nothing to do
+            return self
+        base = A.base
+        if exp.is_negative:
+            base = A.base**-1
+            exp = -exp
+        comm = Commutator(base, B).expand(commutator=True)
+
+        result = base**(exp - 1) * comm
+        for i in range(1, exp):
+            result += base**(exp - 1 - i) * comm * base**i
+        return sign*result.expand()
+
+    def _eval_expand_commutator(self, **hints):
+        A = self.args[0]
+        B = self.args[1]
+
+        if isinstance(A, Add):
+            # [A + B, C]  ->  [A, C] + [B, C]
+            sargs = []
+            for term in A.args:
+                comm = Commutator(term, B)
+                if isinstance(comm, Commutator):
+                    comm = comm._eval_expand_commutator()
+                sargs.append(comm)
+            return Add(*sargs)
+        elif isinstance(B, Add):
+            # [A, B + C]  ->  [A, B] + [A, C]
+            sargs = []
+            for term in B.args:
+                comm = Commutator(A, term)
+                if isinstance(comm, Commutator):
+                    comm = comm._eval_expand_commutator()
+                sargs.append(comm)
+            return Add(*sargs)
+        elif isinstance(A, Mul):
+            # [A*B, C] -> A*[B, C] + [A, C]*B
+            a = A.args[0]
+            b = Mul(*A.args[1:])
+            c = B
+            comm1 = Commutator(b, c)
+            comm2 = Commutator(a, c)
+            if isinstance(comm1, Commutator):
+                comm1 = comm1._eval_expand_commutator()
+            if isinstance(comm2, Commutator):
+                comm2 = comm2._eval_expand_commutator()
+            first = Mul(a, comm1)
+            second = Mul(comm2, b)
+            return Add(first, second)
+        elif isinstance(B, Mul):
+            # [A, B*C] -> [A, B]*C + B*[A, C]
+            a = A
+            b = B.args[0]
+            c = Mul(*B.args[1:])
+            comm1 = Commutator(a, b)
+            comm2 = Commutator(a, c)
+            if isinstance(comm1, Commutator):
+                comm1 = comm1._eval_expand_commutator()
+            if isinstance(comm2, Commutator):
+                comm2 = comm2._eval_expand_commutator()
+            first = Mul(comm1, c)
+            second = Mul(b, comm2)
+            return Add(first, second)
+        elif isinstance(A, Pow):
+            # [A**n, C] -> A**(n - 1)*[A, C] + A**(n - 2)*[A, C]*A + ... + [A, C]*A**(n-1)
+            return self._expand_pow(A, B, 1)
+        elif isinstance(B, Pow):
+            # [A, C**n] -> C**(n - 1)*[C, A] + C**(n - 2)*[C, A]*C + ... + [C, A]*C**(n-1)
+            return self._expand_pow(B, A, -1)
+
+        # No changes, so return self
+        return self
+
+    def doit(self, **hints):
+        """ Evaluate commutator """
+        # Keep the import of Operator here to avoid problems with
+        # circular imports.
+        from sympy.physics.quantum.operator import Operator
+        A = self.args[0]
+        B = self.args[1]
+        if isinstance(A, Operator) and isinstance(B, Operator):
+            try:
+                comm = A._eval_commutator(B, **hints)
+            except NotImplementedError:
+                try:
+                    comm = -1*B._eval_commutator(A, **hints)
+                except NotImplementedError:
+                    comm = None
+            if comm is not None:
+                return comm.doit(**hints)
+        return (A*B - B*A).doit(**hints)
+
+    def _eval_adjoint(self):
+        return Commutator(Dagger(self.args[1]), Dagger(self.args[0]))
+
+    def _sympyrepr(self, printer, *args):
+        return "%s(%s,%s)" % (
+            self.__class__.__name__, printer._print(
+                self.args[0]), printer._print(self.args[1])
+        )
+
+    def _sympystr(self, printer, *args):
+        return "[%s,%s]" % (
+            printer._print(self.args[0]), printer._print(self.args[1]))
+
+    def _pretty(self, printer, *args):
+        pform = printer._print(self.args[0], *args)
+        pform = prettyForm(*pform.right(prettyForm(',')))
+        pform = prettyForm(*pform.right(printer._print(self.args[1], *args)))
+        pform = prettyForm(*pform.parens(left='[', right=']'))
+        return pform
+
+    def _latex(self, printer, *args):
+        return "\\left[%s,%s\\right]" % tuple([
+            printer._print(arg, *args) for arg in self.args])
+
+
+@Commutator._kind_dispatcher.register(_OperatorKind, _OperatorKind)
+def find_op_kind(e1, e2):
+    """Find the kind of an anticommutator of two OperatorKinds."""
+    return OperatorKind
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/constants.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e848bf24e95e3bd612169128a1845202066c6e9
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/constants.py
@@ -0,0 +1,59 @@
+"""Constants (like hbar) related to quantum mechanics."""
+
+from sympy.core.numbers import NumberSymbol
+from sympy.core.singleton import Singleton
+from sympy.printing.pretty.stringpict import prettyForm
+import mpmath.libmp as mlib
+
+#-----------------------------------------------------------------------------
+# Constants
+#-----------------------------------------------------------------------------
+
+__all__ = [
+    'hbar',
+    'HBar',
+]
+
+
+class HBar(NumberSymbol, metaclass=Singleton):
+    """Reduced Plank's constant in numerical and symbolic form [1]_.
+
+    Examples
+    ========
+
+        >>> from sympy.physics.quantum.constants import hbar
+        >>> hbar.evalf()
+        1.05457162000000e-34
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Planck_constant
+    """
+
+    is_real = True
+    is_positive = True
+    is_negative = False
+    is_irrational = True
+
+    __slots__ = ()
+
+    def _as_mpf_val(self, prec):
+        return mlib.from_float(1.05457162e-34, prec)
+
+    def _sympyrepr(self, printer, *args):
+        return 'HBar()'
+
+    def _sympystr(self, printer, *args):
+        return 'hbar'
+
+    def _pretty(self, printer, *args):
+        if printer._use_unicode:
+            return prettyForm('\N{PLANCK CONSTANT OVER TWO PI}')
+        return prettyForm('hbar')
+
+    def _latex(self, printer, *args):
+        return r'\hbar'
+
+# Create an instance for everyone to use.
+hbar = HBar()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/dagger.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/dagger.py
new file mode 100644
index 0000000000000000000000000000000000000000..f96f01e3b9ac86ae30b03e3b97293bbafceaed8a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/dagger.py
@@ -0,0 +1,95 @@
+"""Hermitian conjugation."""
+
+from sympy.core import Expr, sympify
+from sympy.functions.elementary.complexes import adjoint
+
+__all__ = [
+    'Dagger'
+]
+
+
+class Dagger(adjoint):
+    """General Hermitian conjugate operation.
+
+    Explanation
+    ===========
+
+    Take the Hermetian conjugate of an argument [1]_. For matrices this
+    operation is equivalent to transpose and complex conjugate [2]_.
+
+    Parameters
+    ==========
+
+    arg : Expr
+        The SymPy expression that we want to take the dagger of.
+    evaluate : bool
+        Whether the resulting expression should be directly evaluated.
+
+    Examples
+    ========
+
+    Daggering various quantum objects:
+
+        >>> from sympy.physics.quantum.dagger import Dagger
+        >>> from sympy.physics.quantum.state import Ket, Bra
+        >>> from sympy.physics.quantum.operator import Operator
+        >>> Dagger(Ket('psi'))
+        >> Dagger(Bra('phi'))
+        |phi>
+        >>> Dagger(Operator('A'))
+        Dagger(A)
+
+    Inner and outer products::
+
+        >>> from sympy.physics.quantum import InnerProduct, OuterProduct
+        >>> Dagger(InnerProduct(Bra('a'), Ket('b')))
+        
+        >>> Dagger(OuterProduct(Ket('a'), Bra('b')))
+        |b>>> A = Operator('A')
+        >>> B = Operator('B')
+        >>> Dagger(A*B)
+        Dagger(B)*Dagger(A)
+        >>> Dagger(A+B)
+        Dagger(A) + Dagger(B)
+        >>> Dagger(A**2)
+        Dagger(A)**2
+
+    Dagger also seamlessly handles complex numbers and matrices::
+
+        >>> from sympy import Matrix, I
+        >>> m = Matrix([[1,I],[2,I]])
+        >>> m
+        Matrix([
+        [1, I],
+        [2, I]])
+        >>> Dagger(m)
+        Matrix([
+        [ 1,  2],
+        [-I, -I]])
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Hermitian_adjoint
+    .. [2] https://en.wikipedia.org/wiki/Hermitian_transpose
+    """
+
+    @property
+    def kind(self):
+        """Find the kind of a dagger of something (just the kind of the something)."""
+        return self.args[0].kind
+
+    def __new__(cls, arg, evaluate=True):
+        if hasattr(arg, 'adjoint') and evaluate:
+            return arg.adjoint()
+        elif hasattr(arg, 'conjugate') and hasattr(arg, 'transpose') and evaluate:
+            return arg.conjugate().transpose()
+        return Expr.__new__(cls, sympify(arg))
+
+adjoint.__name__ = "Dagger"
+adjoint._sympyrepr = lambda a, b: "Dagger(%s)" % b._print(a.args[0])
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/density.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/density.py
new file mode 100644
index 0000000000000000000000000000000000000000..941373e8105dd0c725626396dfd9cd794b19d3f5
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/density.py
@@ -0,0 +1,315 @@
+from itertools import product
+
+from sympy.core.add import Add
+from sympy.core.containers import Tuple
+from sympy.core.function import expand
+from sympy.core.mul import Mul
+from sympy.core.singleton import S
+from sympy.functions.elementary.exponential import log
+from sympy.matrices.dense import MutableDenseMatrix as Matrix
+from sympy.printing.pretty.stringpict import prettyForm
+from sympy.physics.quantum.dagger import Dagger
+from sympy.physics.quantum.operator import HermitianOperator
+from sympy.physics.quantum.represent import represent
+from sympy.physics.quantum.matrixutils import numpy_ndarray, scipy_sparse_matrix, to_numpy
+from sympy.physics.quantum.trace import Tr
+
+
+class Density(HermitianOperator):
+    """Density operator for representing mixed states.
+
+    TODO: Density operator support for Qubits
+
+    Parameters
+    ==========
+
+    values : tuples/lists
+    Each tuple/list should be of form (state, prob) or [state,prob]
+
+    Examples
+    ========
+
+    Create a density operator with 2 states represented by Kets.
+
+    >>> from sympy.physics.quantum.state import Ket
+    >>> from sympy.physics.quantum.density import Density
+    >>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
+    >>> d
+    Density((|0>, 0.5),(|1>, 0.5))
+
+    """
+    @classmethod
+    def _eval_args(cls, args):
+        # call this to qsympify the args
+        args = super()._eval_args(args)
+
+        for arg in args:
+            # Check if arg is a tuple
+            if not (isinstance(arg, Tuple) and len(arg) == 2):
+                raise ValueError("Each argument should be of form [state,prob]"
+                                 " or ( state, prob )")
+
+        return args
+
+    def states(self):
+        """Return list of all states.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.quantum.state import Ket
+        >>> from sympy.physics.quantum.density import Density
+        >>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
+        >>> d.states()
+        (|0>, |1>)
+
+        """
+        return Tuple(*[arg[0] for arg in self.args])
+
+    def probs(self):
+        """Return list of all probabilities.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.quantum.state import Ket
+        >>> from sympy.physics.quantum.density import Density
+        >>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
+        >>> d.probs()
+        (0.5, 0.5)
+
+        """
+        return Tuple(*[arg[1] for arg in self.args])
+
+    def get_state(self, index):
+        """Return specific state by index.
+
+        Parameters
+        ==========
+
+        index : index of state to be returned
+
+        Examples
+        ========
+
+        >>> from sympy.physics.quantum.state import Ket
+        >>> from sympy.physics.quantum.density import Density
+        >>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
+        >>> d.states()[1]
+        |1>
+
+        """
+        state = self.args[index][0]
+        return state
+
+    def get_prob(self, index):
+        """Return probability of specific state by index.
+
+        Parameters
+        ===========
+
+        index : index of states whose probability is returned.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.quantum.state import Ket
+        >>> from sympy.physics.quantum.density import Density
+        >>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
+        >>> d.probs()[1]
+        0.500000000000000
+
+        """
+        prob = self.args[index][1]
+        return prob
+
+    def apply_op(self, op):
+        """op will operate on each individual state.
+
+        Parameters
+        ==========
+
+        op : Operator
+
+        Examples
+        ========
+
+        >>> from sympy.physics.quantum.state import Ket
+        >>> from sympy.physics.quantum.density import Density
+        >>> from sympy.physics.quantum.operator import Operator
+        >>> A = Operator('A')
+        >>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
+        >>> d.apply_op(A)
+        Density((A*|0>, 0.5),(A*|1>, 0.5))
+
+        """
+        new_args = [(op*state, prob) for (state, prob) in self.args]
+        return Density(*new_args)
+
+    def doit(self, **hints):
+        """Expand the density operator into an outer product format.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.quantum.state import Ket
+        >>> from sympy.physics.quantum.density import Density
+        >>> from sympy.physics.quantum.operator import Operator
+        >>> A = Operator('A')
+        >>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
+        >>> d.doit()
+        0.5*|0><0| + 0.5*|1><1|
+
+        """
+
+        terms = []
+        for (state, prob) in self.args:
+            state = state.expand()  # needed to break up (a+b)*c
+            if (isinstance(state, Add)):
+                for arg in product(state.args, repeat=2):
+                    terms.append(prob*self._generate_outer_prod(arg[0],
+                                                                arg[1]))
+            else:
+                terms.append(prob*self._generate_outer_prod(state, state))
+
+        return Add(*terms)
+
+    def _generate_outer_prod(self, arg1, arg2):
+        c_part1, nc_part1 = arg1.args_cnc()
+        c_part2, nc_part2 = arg2.args_cnc()
+
+        if (len(nc_part1) == 0 or len(nc_part2) == 0):
+            raise ValueError('Atleast one-pair of'
+                             ' Non-commutative instance required'
+                             ' for outer product.')
+
+        # We were able to remove some tensor product simplifications that
+        # used to be here as those transformations are not automatically
+        # applied by transforms.py.
+        op = Mul(*nc_part1)*Dagger(Mul(*nc_part2))
+
+        return Mul(*c_part1)*Mul(*c_part2) * op
+
+    def _represent(self, **options):
+        return represent(self.doit(), **options)
+
+    def _print_operator_name_latex(self, printer, *args):
+        return r'\rho'
+
+    def _print_operator_name_pretty(self, printer, *args):
+        return prettyForm('\N{GREEK SMALL LETTER RHO}')
+
+    def _eval_trace(self, **kwargs):
+        indices = kwargs.get('indices', [])
+        return Tr(self.doit(), indices).doit()
+
+    def entropy(self):
+        """ Compute the entropy of a density matrix.
+
+        Refer to density.entropy() method  for examples.
+        """
+        return entropy(self)
+
+
+def entropy(density):
+    """Compute the entropy of a matrix/density object.
+
+    This computes -Tr(density*ln(density)) using the eigenvalue decomposition
+    of density, which is given as either a Density instance or a matrix
+    (numpy.ndarray, sympy.Matrix or scipy.sparse).
+
+    Parameters
+    ==========
+
+    density : density matrix of type Density, SymPy matrix,
+    scipy.sparse or numpy.ndarray
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum.density import Density, entropy
+    >>> from sympy.physics.quantum.spin import JzKet
+    >>> from sympy import S
+    >>> up = JzKet(S(1)/2,S(1)/2)
+    >>> down = JzKet(S(1)/2,-S(1)/2)
+    >>> d = Density((up,S(1)/2),(down,S(1)/2))
+    >>> entropy(d)
+    log(2)/2
+
+    """
+    if isinstance(density, Density):
+        density = represent(density)  # represent in Matrix
+
+    if isinstance(density, scipy_sparse_matrix):
+        density = to_numpy(density)
+
+    if isinstance(density, Matrix):
+        eigvals = density.eigenvals().keys()
+        return expand(-sum(e*log(e) for e in eigvals))
+    elif isinstance(density, numpy_ndarray):
+        import numpy as np
+        eigvals = np.linalg.eigvals(density)
+        return -np.sum(eigvals*np.log(eigvals))
+    else:
+        raise ValueError(
+            "numpy.ndarray, scipy.sparse or SymPy matrix expected")
+
+
+def fidelity(state1, state2):
+    """ Computes the fidelity [1]_ between two quantum states
+
+    The arguments provided to this function should be a square matrix or a
+    Density object. If it is a square matrix, it is assumed to be diagonalizable.
+
+    Parameters
+    ==========
+
+    state1, state2 : a density matrix or Matrix
+
+
+    Examples
+    ========
+
+    >>> from sympy import S, sqrt
+    >>> from sympy.physics.quantum.dagger import Dagger
+    >>> from sympy.physics.quantum.spin import JzKet
+    >>> from sympy.physics.quantum.density import fidelity
+    >>> from sympy.physics.quantum.represent import represent
+    >>>
+    >>> up = JzKet(S(1)/2,S(1)/2)
+    >>> down = JzKet(S(1)/2,-S(1)/2)
+    >>> amp = 1/sqrt(2)
+    >>> updown = (amp*up) + (amp*down)
+    >>>
+    >>> # represent turns Kets into matrices
+    >>> up_dm = represent(up*Dagger(up))
+    >>> down_dm = represent(down*Dagger(down))
+    >>> updown_dm = represent(updown*Dagger(updown))
+    >>>
+    >>> fidelity(up_dm, up_dm)
+    1
+    >>> fidelity(up_dm, down_dm) #orthogonal states
+    0
+    >>> fidelity(up_dm, updown_dm).evalf().round(3)
+    0.707
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Fidelity_of_quantum_states
+
+    """
+    state1 = represent(state1) if isinstance(state1, Density) else state1
+    state2 = represent(state2) if isinstance(state2, Density) else state2
+
+    if not isinstance(state1, Matrix) or not isinstance(state2, Matrix):
+        raise ValueError("state1 and state2 must be of type Density or Matrix "
+                         "received type=%s for state1 and type=%s for state2" %
+                         (type(state1), type(state2)))
+
+    if state1.shape != state2.shape and state1.is_square:
+        raise ValueError("The dimensions of both args should be equal and the "
+                         "matrix obtained should be a square matrix")
+
+    sqrt_state1 = state1**S.Half
+    return Tr((sqrt_state1*state2*sqrt_state1)**S.Half).doit()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/fermion.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/fermion.py
new file mode 100644
index 0000000000000000000000000000000000000000..8080bd3b0904b837652fdae7be0bd526da2d508f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/fermion.py
@@ -0,0 +1,191 @@
+"""Fermionic quantum operators."""
+
+from sympy.core.numbers import Integer
+from sympy.core.singleton import S
+from sympy.physics.quantum import Operator
+from sympy.physics.quantum import HilbertSpace, Ket, Bra
+from sympy.functions.special.tensor_functions import KroneckerDelta
+
+
+__all__ = [
+    'FermionOp',
+    'FermionFockKet',
+    'FermionFockBra'
+]
+
+
+class FermionOp(Operator):
+    """A fermionic operator that satisfies {c, Dagger(c)} == 1.
+
+    Parameters
+    ==========
+
+    name : str
+        A string that labels the fermionic mode.
+
+    annihilation : bool
+        A bool that indicates if the fermionic operator is an annihilation
+        (True, default value) or creation operator (False)
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum import Dagger, AntiCommutator
+    >>> from sympy.physics.quantum.fermion import FermionOp
+    >>> c = FermionOp("c")
+    >>> AntiCommutator(c, Dagger(c)).doit()
+    1
+    """
+    @property
+    def name(self):
+        return self.args[0]
+
+    @property
+    def is_annihilation(self):
+        return bool(self.args[1])
+
+    @classmethod
+    def default_args(self):
+        return ("c", True)
+
+    def __new__(cls, *args, **hints):
+        if not len(args) in [1, 2]:
+            raise ValueError('1 or 2 parameters expected, got %s' % args)
+
+        if len(args) == 1:
+            args = (args[0], S.One)
+
+        if len(args) == 2:
+            args = (args[0], Integer(args[1]))
+
+        return Operator.__new__(cls, *args)
+
+    def _eval_commutator_FermionOp(self, other, **hints):
+        if 'independent' in hints and hints['independent']:
+            # [c, d] = 0
+            return S.Zero
+
+        return None
+
+    def _eval_anticommutator_FermionOp(self, other, **hints):
+        if self.name == other.name:
+            # {a^\dagger, a} = 1
+            if not self.is_annihilation and other.is_annihilation:
+                return S.One
+
+        elif 'independent' in hints and hints['independent']:
+            # {c, d} = 2 * c * d, because [c, d] = 0 for independent operators
+            return 2 * self * other
+
+        return None
+
+    def _eval_anticommutator_BosonOp(self, other, **hints):
+        # because fermions and bosons commute
+        return 2 * self * other
+
+    def _eval_commutator_BosonOp(self, other, **hints):
+        return S.Zero
+
+    def _eval_adjoint(self):
+        return FermionOp(str(self.name), not self.is_annihilation)
+
+    def _print_contents_latex(self, printer, *args):
+        if self.is_annihilation:
+            return r'{%s}' % str(self.name)
+        else:
+            return r'{{%s}^\dagger}' % str(self.name)
+
+    def _print_contents(self, printer, *args):
+        if self.is_annihilation:
+            return r'%s' % str(self.name)
+        else:
+            return r'Dagger(%s)' % str(self.name)
+
+    def _print_contents_pretty(self, printer, *args):
+        from sympy.printing.pretty.stringpict import prettyForm
+        pform = printer._print(self.args[0], *args)
+        if self.is_annihilation:
+            return pform
+        else:
+            return pform**prettyForm('\N{DAGGER}')
+
+    def _eval_power(self, exp):
+        from sympy.core.singleton import S
+        if exp == 0:
+            return S.One
+        elif exp == 1:
+            return self
+        elif (exp > 1) == True and exp.is_integer == True:
+            return S.Zero
+        elif (exp < 0) == True or exp.is_integer == False:
+            raise ValueError("Fermionic operators can only be raised to a"
+                " positive integer power")
+        return Operator._eval_power(self, exp)
+
+class FermionFockKet(Ket):
+    """Fock state ket for a fermionic mode.
+
+    Parameters
+    ==========
+
+    n : Number
+        The Fock state number.
+
+    """
+
+    def __new__(cls, n):
+        if n not in (0, 1):
+            raise ValueError("n must be 0 or 1")
+        return Ket.__new__(cls, n)
+
+    @property
+    def n(self):
+        return self.label[0]
+
+    @classmethod
+    def dual_class(self):
+        return FermionFockBra
+
+    @classmethod
+    def _eval_hilbert_space(cls, label):
+        return HilbertSpace()
+
+    def _eval_innerproduct_FermionFockBra(self, bra, **hints):
+        return KroneckerDelta(self.n, bra.n)
+
+    def _apply_from_right_to_FermionOp(self, op, **options):
+        if op.is_annihilation:
+            if self.n == 1:
+                return FermionFockKet(0)
+            else:
+                return S.Zero
+        else:
+            if self.n == 0:
+                return FermionFockKet(1)
+            else:
+                return S.Zero
+
+
+class FermionFockBra(Bra):
+    """Fock state bra for a fermionic mode.
+
+    Parameters
+    ==========
+
+    n : Number
+        The Fock state number.
+
+    """
+
+    def __new__(cls, n):
+        if n not in (0, 1):
+            raise ValueError("n must be 0 or 1")
+        return Bra.__new__(cls, n)
+
+    @property
+    def n(self):
+        return self.label[0]
+
+    @classmethod
+    def dual_class(self):
+        return FermionFockKet
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/gate.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/gate.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8bcf5cd3611173cd9ebd6308dbbc896f5257f20
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/gate.py
@@ -0,0 +1,1309 @@
+"""An implementation of gates that act on qubits.
+
+Gates are unitary operators that act on the space of qubits.
+
+Medium Term Todo:
+
+* Optimize Gate._apply_operators_Qubit to remove the creation of many
+  intermediate Qubit objects.
+* Add commutation relationships to all operators and use this in gate_sort.
+* Fix gate_sort and gate_simp.
+* Get multi-target UGates plotting properly.
+* Get UGate to work with either sympy/numpy matrices and output either
+  format. This should also use the matrix slots.
+"""
+
+from itertools import chain
+import random
+
+from sympy.core.add import Add
+from sympy.core.containers import Tuple
+from sympy.core.mul import Mul
+from sympy.core.numbers import (I, Integer)
+from sympy.core.power import Pow
+from sympy.core.numbers import Number
+from sympy.core.singleton import S as _S
+from sympy.core.sorting import default_sort_key
+from sympy.core.sympify import _sympify
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.printing.pretty.stringpict import prettyForm, stringPict
+
+from sympy.physics.quantum.anticommutator import AntiCommutator
+from sympy.physics.quantum.commutator import Commutator
+from sympy.physics.quantum.qexpr import QuantumError
+from sympy.physics.quantum.hilbert import ComplexSpace
+from sympy.physics.quantum.operator import (UnitaryOperator, Operator,
+                                            HermitianOperator)
+from sympy.physics.quantum.matrixutils import matrix_tensor_product, matrix_eye
+from sympy.physics.quantum.matrixcache import matrix_cache
+
+from sympy.matrices.matrixbase import MatrixBase
+
+from sympy.utilities.iterables import is_sequence
+
+__all__ = [
+    'Gate',
+    'CGate',
+    'UGate',
+    'OneQubitGate',
+    'TwoQubitGate',
+    'IdentityGate',
+    'HadamardGate',
+    'XGate',
+    'YGate',
+    'ZGate',
+    'TGate',
+    'PhaseGate',
+    'SwapGate',
+    'CNotGate',
+    # Aliased gate names
+    'CNOT',
+    'SWAP',
+    'H',
+    'X',
+    'Y',
+    'Z',
+    'T',
+    'S',
+    'Phase',
+    'normalized',
+    'gate_sort',
+    'gate_simp',
+    'random_circuit',
+    'CPHASE',
+    'CGateS',
+]
+
+#-----------------------------------------------------------------------------
+# Gate Super-Classes
+#-----------------------------------------------------------------------------
+
+_normalized = True
+
+
+def _max(*args, **kwargs):
+    if "key" not in kwargs:
+        kwargs["key"] = default_sort_key
+    return max(*args, **kwargs)
+
+
+def _min(*args, **kwargs):
+    if "key" not in kwargs:
+        kwargs["key"] = default_sort_key
+    return min(*args, **kwargs)
+
+
+def normalized(normalize):
+    r"""Set flag controlling normalization of Hadamard gates by `1/\sqrt{2}`.
+
+    This is a global setting that can be used to simplify the look of various
+    expressions, by leaving off the leading `1/\sqrt{2}` of the Hadamard gate.
+
+    Parameters
+    ----------
+    normalize : bool
+        Should the Hadamard gate include the `1/\sqrt{2}` normalization factor?
+        When True, the Hadamard gate will have the `1/\sqrt{2}`. When False, the
+        Hadamard gate will not have this factor.
+    """
+    global _normalized
+    _normalized = normalize
+
+
+def _validate_targets_controls(tandc):
+    tandc = list(tandc)
+    # Check for integers
+    for bit in tandc:
+        if not bit.is_Integer and not bit.is_Symbol:
+            raise TypeError('Integer expected, got: %r' % tandc[bit])
+    # Detect duplicates
+    if len(set(tandc)) != len(tandc):
+        raise QuantumError(
+            'Target/control qubits in a gate cannot be duplicated'
+        )
+
+
+class Gate(UnitaryOperator):
+    """Non-controlled unitary gate operator that acts on qubits.
+
+    This is a general abstract gate that needs to be subclassed to do anything
+    useful.
+
+    Parameters
+    ----------
+    label : tuple, int
+        A list of the target qubits (as ints) that the gate will apply to.
+
+    Examples
+    ========
+
+
+    """
+
+    _label_separator = ','
+
+    gate_name = 'G'
+    gate_name_latex = 'G'
+
+    #-------------------------------------------------------------------------
+    # Initialization/creation
+    #-------------------------------------------------------------------------
+
+    @classmethod
+    def _eval_args(cls, args):
+        args = Tuple(*UnitaryOperator._eval_args(args))
+        _validate_targets_controls(args)
+        return args
+
+    @classmethod
+    def _eval_hilbert_space(cls, args):
+        """This returns the smallest possible Hilbert space."""
+        return ComplexSpace(2)**(_max(args) + 1)
+
+    #-------------------------------------------------------------------------
+    # Properties
+    #-------------------------------------------------------------------------
+
+    @property
+    def nqubits(self):
+        """The total number of qubits this gate acts on.
+
+        For controlled gate subclasses this includes both target and control
+        qubits, so that, for examples the CNOT gate acts on 2 qubits.
+        """
+        return len(self.targets)
+
+    @property
+    def min_qubits(self):
+        """The minimum number of qubits this gate needs to act on."""
+        return _max(self.targets) + 1
+
+    @property
+    def targets(self):
+        """A tuple of target qubits."""
+        return self.label
+
+    @property
+    def gate_name_plot(self):
+        return r'$%s$' % self.gate_name_latex
+
+    #-------------------------------------------------------------------------
+    # Gate methods
+    #-------------------------------------------------------------------------
+
+    def get_target_matrix(self, format='sympy'):
+        """The matrix representation of the target part of the gate.
+
+        Parameters
+        ----------
+        format : str
+            The format string ('sympy','numpy', etc.)
+        """
+        raise NotImplementedError(
+            'get_target_matrix is not implemented in Gate.')
+
+    #-------------------------------------------------------------------------
+    # Apply
+    #-------------------------------------------------------------------------
+
+    def _apply_operator_IntQubit(self, qubits, **options):
+        """Redirect an apply from IntQubit to Qubit"""
+        return self._apply_operator_Qubit(qubits, **options)
+
+    def _apply_operator_Qubit(self, qubits, **options):
+        """Apply this gate to a Qubit."""
+
+        # Check number of qubits this gate acts on.
+        if qubits.nqubits < self.min_qubits:
+            raise QuantumError(
+                'Gate needs a minimum of %r qubits to act on, got: %r' %
+                (self.min_qubits, qubits.nqubits)
+            )
+
+        # If the controls are not met, just return
+        if isinstance(self, CGate):
+            if not self.eval_controls(qubits):
+                return qubits
+
+        targets = self.targets
+        target_matrix = self.get_target_matrix(format='sympy')
+
+        # Find which column of the target matrix this applies to.
+        column_index = 0
+        n = 1
+        for target in targets:
+            column_index += n*qubits[target]
+            n = n << 1
+        column = target_matrix[:, int(column_index)]
+
+        # Now apply each column element to the qubit.
+        result = 0
+        for index in range(column.rows):
+            # TODO: This can be optimized to reduce the number of Qubit
+            # creations. We should simply manipulate the raw list of qubit
+            # values and then build the new Qubit object once.
+            # Make a copy of the incoming qubits.
+            new_qubit = qubits.__class__(*qubits.args)
+            # Flip the bits that need to be flipped.
+            for bit, target in enumerate(targets):
+                if new_qubit[target] != (index >> bit) & 1:
+                    new_qubit = new_qubit.flip(target)
+            # The value in that row and column times the flipped-bit qubit
+            # is the result for that part.
+            result += column[index]*new_qubit
+        return result
+
+    #-------------------------------------------------------------------------
+    # Represent
+    #-------------------------------------------------------------------------
+
+    def _represent_default_basis(self, **options):
+        return self._represent_ZGate(None, **options)
+
+    def _represent_ZGate(self, basis, **options):
+        format = options.get('format', 'sympy')
+        nqubits = options.get('nqubits', 0)
+        if nqubits == 0:
+            raise QuantumError(
+                'The number of qubits must be given as nqubits.')
+
+        # Make sure we have enough qubits for the gate.
+        if nqubits < self.min_qubits:
+            raise QuantumError(
+                'The number of qubits %r is too small for the gate.' % nqubits
+            )
+
+        target_matrix = self.get_target_matrix(format)
+        targets = self.targets
+        if isinstance(self, CGate):
+            controls = self.controls
+        else:
+            controls = []
+        m = represent_zbasis(
+            controls, targets, target_matrix, nqubits, format
+        )
+        return m
+
+    #-------------------------------------------------------------------------
+    # Print methods
+    #-------------------------------------------------------------------------
+
+    def _sympystr(self, printer, *args):
+        label = self._print_label(printer, *args)
+        return '%s(%s)' % (self.gate_name, label)
+
+    def _pretty(self, printer, *args):
+        a = stringPict(self.gate_name)
+        b = self._print_label_pretty(printer, *args)
+        return self._print_subscript_pretty(a, b)
+
+    def _latex(self, printer, *args):
+        label = self._print_label(printer, *args)
+        return '%s_{%s}' % (self.gate_name_latex, label)
+
+    def plot_gate(self, axes, gate_idx, gate_grid, wire_grid):
+        raise NotImplementedError('plot_gate is not implemented.')
+
+
+class CGate(Gate):
+    """A general unitary gate with control qubits.
+
+    A general control gate applies a target gate to a set of targets if all
+    of the control qubits have a particular values (set by
+    ``CGate.control_value``).
+
+    Parameters
+    ----------
+    label : tuple
+        The label in this case has the form (controls, gate), where controls
+        is a tuple/list of control qubits (as ints) and gate is a ``Gate``
+        instance that is the target operator.
+
+    Examples
+    ========
+
+    """
+
+    gate_name = 'C'
+    gate_name_latex = 'C'
+
+    # The values this class controls for.
+    control_value = _S.One
+
+    simplify_cgate = False
+
+    #-------------------------------------------------------------------------
+    # Initialization
+    #-------------------------------------------------------------------------
+
+    @classmethod
+    def _eval_args(cls, args):
+        # _eval_args has the right logic for the controls argument.
+        controls = args[0]
+        gate = args[1]
+        if not is_sequence(controls):
+            controls = (controls,)
+        controls = UnitaryOperator._eval_args(controls)
+        _validate_targets_controls(chain(controls, gate.targets))
+        return (Tuple(*controls), gate)
+
+    @classmethod
+    def _eval_hilbert_space(cls, args):
+        """This returns the smallest possible Hilbert space."""
+        return ComplexSpace(2)**_max(_max(args[0]) + 1, args[1].min_qubits)
+
+    #-------------------------------------------------------------------------
+    # Properties
+    #-------------------------------------------------------------------------
+
+    @property
+    def nqubits(self):
+        """The total number of qubits this gate acts on.
+
+        For controlled gate subclasses this includes both target and control
+        qubits, so that, for examples the CNOT gate acts on 2 qubits.
+        """
+        return len(self.targets) + len(self.controls)
+
+    @property
+    def min_qubits(self):
+        """The minimum number of qubits this gate needs to act on."""
+        return _max(_max(self.controls), _max(self.targets)) + 1
+
+    @property
+    def targets(self):
+        """A tuple of target qubits."""
+        return self.gate.targets
+
+    @property
+    def controls(self):
+        """A tuple of control qubits."""
+        return tuple(self.label[0])
+
+    @property
+    def gate(self):
+        """The non-controlled gate that will be applied to the targets."""
+        return self.label[1]
+
+    #-------------------------------------------------------------------------
+    # Gate methods
+    #-------------------------------------------------------------------------
+
+    def get_target_matrix(self, format='sympy'):
+        return self.gate.get_target_matrix(format)
+
+    def eval_controls(self, qubit):
+        """Return True/False to indicate if the controls are satisfied."""
+        return all(qubit[bit] == self.control_value for bit in self.controls)
+
+    def decompose(self, **options):
+        """Decompose the controlled gate into CNOT and single qubits gates."""
+        if len(self.controls) == 1:
+            c = self.controls[0]
+            t = self.gate.targets[0]
+            if isinstance(self.gate, YGate):
+                g1 = PhaseGate(t)
+                g2 = CNotGate(c, t)
+                g3 = PhaseGate(t)
+                g4 = ZGate(t)
+                return g1*g2*g3*g4
+            if isinstance(self.gate, ZGate):
+                g1 = HadamardGate(t)
+                g2 = CNotGate(c, t)
+                g3 = HadamardGate(t)
+                return g1*g2*g3
+        else:
+            return self
+
+    #-------------------------------------------------------------------------
+    # Print methods
+    #-------------------------------------------------------------------------
+
+    def _print_label(self, printer, *args):
+        controls = self._print_sequence(self.controls, ',', printer, *args)
+        gate = printer._print(self.gate, *args)
+        return '(%s),%s' % (controls, gate)
+
+    def _pretty(self, printer, *args):
+        controls = self._print_sequence_pretty(
+            self.controls, ',', printer, *args)
+        gate = printer._print(self.gate)
+        gate_name = stringPict(self.gate_name)
+        first = self._print_subscript_pretty(gate_name, controls)
+        gate = self._print_parens_pretty(gate)
+        final = prettyForm(*first.right(gate))
+        return final
+
+    def _latex(self, printer, *args):
+        controls = self._print_sequence(self.controls, ',', printer, *args)
+        gate = printer._print(self.gate, *args)
+        return r'%s_{%s}{\left(%s\right)}' % \
+            (self.gate_name_latex, controls, gate)
+
+    def plot_gate(self, circ_plot, gate_idx):
+        """
+        Plot the controlled gate. If *simplify_cgate* is true, simplify
+        C-X and C-Z gates into their more familiar forms.
+        """
+        min_wire = int(_min(chain(self.controls, self.targets)))
+        max_wire = int(_max(chain(self.controls, self.targets)))
+        circ_plot.control_line(gate_idx, min_wire, max_wire)
+        for c in self.controls:
+            circ_plot.control_point(gate_idx, int(c))
+        if self.simplify_cgate:
+            if self.gate.gate_name == 'X':
+                self.gate.plot_gate_plus(circ_plot, gate_idx)
+            elif self.gate.gate_name == 'Z':
+                circ_plot.control_point(gate_idx, self.targets[0])
+            else:
+                self.gate.plot_gate(circ_plot, gate_idx)
+        else:
+            self.gate.plot_gate(circ_plot, gate_idx)
+
+    #-------------------------------------------------------------------------
+    # Miscellaneous
+    #-------------------------------------------------------------------------
+
+    def _eval_dagger(self):
+        if isinstance(self.gate, HermitianOperator):
+            return self
+        else:
+            return Gate._eval_dagger(self)
+
+    def _eval_inverse(self):
+        if isinstance(self.gate, HermitianOperator):
+            return self
+        else:
+            return Gate._eval_inverse(self)
+
+    def _eval_power(self, exp):
+        if isinstance(self.gate, HermitianOperator):
+            if exp == -1:
+                return Gate._eval_power(self, exp)
+            elif abs(exp) % 2 == 0:
+                return self*(Gate._eval_inverse(self))
+            else:
+                return self
+        else:
+            return Gate._eval_power(self, exp)
+
+class CGateS(CGate):
+    """Version of CGate that allows gate simplifications.
+    I.e. cnot looks like an oplus, cphase has dots, etc.
+    """
+    simplify_cgate=True
+
+
+class UGate(Gate):
+    """General gate specified by a set of targets and a target matrix.
+
+    Parameters
+    ----------
+    label : tuple
+        A tuple of the form (targets, U), where targets is a tuple of the
+        target qubits and U is a unitary matrix with dimension of
+        len(targets).
+    """
+    gate_name = 'U'
+    gate_name_latex = 'U'
+
+    #-------------------------------------------------------------------------
+    # Initialization
+    #-------------------------------------------------------------------------
+
+    @classmethod
+    def _eval_args(cls, args):
+        targets = args[0]
+        if not is_sequence(targets):
+            targets = (targets,)
+        targets = Gate._eval_args(targets)
+        _validate_targets_controls(targets)
+        mat = args[1]
+        if not isinstance(mat, MatrixBase):
+            raise TypeError('Matrix expected, got: %r' % mat)
+        #make sure this matrix is of a Basic type
+        mat = _sympify(mat)
+        dim = 2**len(targets)
+        if not all(dim == shape for shape in mat.shape):
+            raise IndexError(
+                'Number of targets must match the matrix size: %r %r' %
+                (targets, mat)
+            )
+        return (targets, mat)
+
+    @classmethod
+    def _eval_hilbert_space(cls, args):
+        """This returns the smallest possible Hilbert space."""
+        return ComplexSpace(2)**(_max(args[0]) + 1)
+
+    #-------------------------------------------------------------------------
+    # Properties
+    #-------------------------------------------------------------------------
+
+    @property
+    def targets(self):
+        """A tuple of target qubits."""
+        return tuple(self.label[0])
+
+    #-------------------------------------------------------------------------
+    # Gate methods
+    #-------------------------------------------------------------------------
+
+    def get_target_matrix(self, format='sympy'):
+        """The matrix rep. of the target part of the gate.
+
+        Parameters
+        ----------
+        format : str
+            The format string ('sympy','numpy', etc.)
+        """
+        return self.label[1]
+
+    #-------------------------------------------------------------------------
+    # Print methods
+    #-------------------------------------------------------------------------
+    def _pretty(self, printer, *args):
+        targets = self._print_sequence_pretty(
+            self.targets, ',', printer, *args)
+        gate_name = stringPict(self.gate_name)
+        return self._print_subscript_pretty(gate_name, targets)
+
+    def _latex(self, printer, *args):
+        targets = self._print_sequence(self.targets, ',', printer, *args)
+        return r'%s_{%s}' % (self.gate_name_latex, targets)
+
+    def plot_gate(self, circ_plot, gate_idx):
+        circ_plot.one_qubit_box(
+            self.gate_name_plot,
+            gate_idx, int(self.targets[0])
+        )
+
+
+class OneQubitGate(Gate):
+    """A single qubit unitary gate base class."""
+
+    nqubits = _S.One
+
+    def plot_gate(self, circ_plot, gate_idx):
+        circ_plot.one_qubit_box(
+            self.gate_name_plot,
+            gate_idx, int(self.targets[0])
+        )
+
+    def _eval_commutator(self, other, **hints):
+        if isinstance(other, OneQubitGate):
+            if self.targets != other.targets or self.__class__ == other.__class__:
+                return _S.Zero
+        return Operator._eval_commutator(self, other, **hints)
+
+    def _eval_anticommutator(self, other, **hints):
+        if isinstance(other, OneQubitGate):
+            if self.targets != other.targets or self.__class__ == other.__class__:
+                return Integer(2)*self*other
+        return Operator._eval_anticommutator(self, other, **hints)
+
+
+class TwoQubitGate(Gate):
+    """A two qubit unitary gate base class."""
+
+    nqubits = Integer(2)
+
+#-----------------------------------------------------------------------------
+# Single Qubit Gates
+#-----------------------------------------------------------------------------
+
+
+class IdentityGate(OneQubitGate):
+    """The single qubit identity gate.
+
+    Parameters
+    ----------
+    target : int
+        The target qubit this gate will apply to.
+
+    Examples
+    ========
+
+    """
+    is_hermitian = True
+    gate_name = '1'
+    gate_name_latex = '1'
+
+    # Short cut version of gate._apply_operator_Qubit
+    def _apply_operator_Qubit(self, qubits, **options):
+        # Check number of qubits this gate acts on (see gate._apply_operator_Qubit)
+        if qubits.nqubits < self.min_qubits:
+            raise QuantumError(
+                'Gate needs a minimum of %r qubits to act on, got: %r' %
+                (self.min_qubits, qubits.nqubits)
+            )
+        return qubits # no computation required for IdentityGate
+
+    def get_target_matrix(self, format='sympy'):
+        return matrix_cache.get_matrix('eye2', format)
+
+    def _eval_commutator(self, other, **hints):
+        return _S.Zero
+
+    def _eval_anticommutator(self, other, **hints):
+        return Integer(2)*other
+
+
+class HadamardGate(HermitianOperator, OneQubitGate):
+    """The single qubit Hadamard gate.
+
+    Parameters
+    ----------
+    target : int
+        The target qubit this gate will apply to.
+
+    Examples
+    ========
+
+    >>> from sympy import sqrt
+    >>> from sympy.physics.quantum.qubit import Qubit
+    >>> from sympy.physics.quantum.gate import HadamardGate
+    >>> from sympy.physics.quantum.qapply import qapply
+    >>> qapply(HadamardGate(0)*Qubit('1'))
+    sqrt(2)*|0>/2 - sqrt(2)*|1>/2
+    >>> # Hadamard on bell state, applied on 2 qubits.
+    >>> psi = 1/sqrt(2)*(Qubit('00')+Qubit('11'))
+    >>> qapply(HadamardGate(0)*HadamardGate(1)*psi)
+    sqrt(2)*|00>/2 + sqrt(2)*|11>/2
+
+    """
+    gate_name = 'H'
+    gate_name_latex = 'H'
+
+    def get_target_matrix(self, format='sympy'):
+        if _normalized:
+            return matrix_cache.get_matrix('H', format)
+        else:
+            return matrix_cache.get_matrix('Hsqrt2', format)
+
+    def _eval_commutator_XGate(self, other, **hints):
+        return I*sqrt(2)*YGate(self.targets[0])
+
+    def _eval_commutator_YGate(self, other, **hints):
+        return I*sqrt(2)*(ZGate(self.targets[0]) - XGate(self.targets[0]))
+
+    def _eval_commutator_ZGate(self, other, **hints):
+        return -I*sqrt(2)*YGate(self.targets[0])
+
+    def _eval_anticommutator_XGate(self, other, **hints):
+        return sqrt(2)*IdentityGate(self.targets[0])
+
+    def _eval_anticommutator_YGate(self, other, **hints):
+        return _S.Zero
+
+    def _eval_anticommutator_ZGate(self, other, **hints):
+        return sqrt(2)*IdentityGate(self.targets[0])
+
+
+class XGate(HermitianOperator, OneQubitGate):
+    """The single qubit X, or NOT, gate.
+
+    Parameters
+    ----------
+    target : int
+        The target qubit this gate will apply to.
+
+    Examples
+    ========
+
+    """
+    gate_name = 'X'
+    gate_name_latex = 'X'
+
+    def get_target_matrix(self, format='sympy'):
+        return matrix_cache.get_matrix('X', format)
+
+    def plot_gate(self, circ_plot, gate_idx):
+        OneQubitGate.plot_gate(self,circ_plot,gate_idx)
+
+    def plot_gate_plus(self, circ_plot, gate_idx):
+        circ_plot.not_point(
+            gate_idx, int(self.label[0])
+        )
+
+    def _eval_commutator_YGate(self, other, **hints):
+        return Integer(2)*I*ZGate(self.targets[0])
+
+    def _eval_anticommutator_XGate(self, other, **hints):
+        return Integer(2)*IdentityGate(self.targets[0])
+
+    def _eval_anticommutator_YGate(self, other, **hints):
+        return _S.Zero
+
+    def _eval_anticommutator_ZGate(self, other, **hints):
+        return _S.Zero
+
+
+class YGate(HermitianOperator, OneQubitGate):
+    """The single qubit Y gate.
+
+    Parameters
+    ----------
+    target : int
+        The target qubit this gate will apply to.
+
+    Examples
+    ========
+
+    """
+    gate_name = 'Y'
+    gate_name_latex = 'Y'
+
+    def get_target_matrix(self, format='sympy'):
+        return matrix_cache.get_matrix('Y', format)
+
+    def _eval_commutator_ZGate(self, other, **hints):
+        return Integer(2)*I*XGate(self.targets[0])
+
+    def _eval_anticommutator_YGate(self, other, **hints):
+        return Integer(2)*IdentityGate(self.targets[0])
+
+    def _eval_anticommutator_ZGate(self, other, **hints):
+        return _S.Zero
+
+
+class ZGate(HermitianOperator, OneQubitGate):
+    """The single qubit Z gate.
+
+    Parameters
+    ----------
+    target : int
+        The target qubit this gate will apply to.
+
+    Examples
+    ========
+
+    """
+    gate_name = 'Z'
+    gate_name_latex = 'Z'
+
+    def get_target_matrix(self, format='sympy'):
+        return matrix_cache.get_matrix('Z', format)
+
+    def _eval_commutator_XGate(self, other, **hints):
+        return Integer(2)*I*YGate(self.targets[0])
+
+    def _eval_anticommutator_YGate(self, other, **hints):
+        return _S.Zero
+
+
+class PhaseGate(OneQubitGate):
+    """The single qubit phase, or S, gate.
+
+    This gate rotates the phase of the state by pi/2 if the state is ``|1>`` and
+    does nothing if the state is ``|0>``.
+
+    Parameters
+    ----------
+    target : int
+        The target qubit this gate will apply to.
+
+    Examples
+    ========
+
+    """
+    is_hermitian =  False
+    gate_name = 'S'
+    gate_name_latex = 'S'
+
+    def get_target_matrix(self, format='sympy'):
+        return matrix_cache.get_matrix('S', format)
+
+    def _eval_commutator_ZGate(self, other, **hints):
+        return _S.Zero
+
+    def _eval_commutator_TGate(self, other, **hints):
+        return _S.Zero
+
+
+class TGate(OneQubitGate):
+    """The single qubit pi/8 gate.
+
+    This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and
+    does nothing if the state is ``|0>``.
+
+    Parameters
+    ----------
+    target : int
+        The target qubit this gate will apply to.
+
+    Examples
+    ========
+
+    """
+    is_hermitian = False
+    gate_name = 'T'
+    gate_name_latex = 'T'
+
+    def get_target_matrix(self, format='sympy'):
+        return matrix_cache.get_matrix('T', format)
+
+    def _eval_commutator_ZGate(self, other, **hints):
+        return _S.Zero
+
+    def _eval_commutator_PhaseGate(self, other, **hints):
+        return _S.Zero
+
+
+# Aliases for gate names.
+H = HadamardGate
+X = XGate
+Y = YGate
+Z = ZGate
+T = TGate
+Phase = S = PhaseGate
+
+
+#-----------------------------------------------------------------------------
+# 2 Qubit Gates
+#-----------------------------------------------------------------------------
+
+
+class CNotGate(HermitianOperator, CGate, TwoQubitGate):
+    """Two qubit controlled-NOT.
+
+    This gate performs the NOT or X gate on the target qubit if the control
+    qubits all have the value 1.
+
+    Parameters
+    ----------
+    label : tuple
+        A tuple of the form (control, target).
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum.gate import CNOT
+    >>> from sympy.physics.quantum.qapply import qapply
+    >>> from sympy.physics.quantum.qubit import Qubit
+    >>> c = CNOT(1,0)
+    >>> qapply(c*Qubit('10')) # note that qubits are indexed from right to left
+    |11>
+
+    """
+    gate_name = 'CNOT'
+    gate_name_latex = r'\text{CNOT}'
+    simplify_cgate = True
+
+    #-------------------------------------------------------------------------
+    # Initialization
+    #-------------------------------------------------------------------------
+
+    @classmethod
+    def _eval_args(cls, args):
+        args = Gate._eval_args(args)
+        return args
+
+    @classmethod
+    def _eval_hilbert_space(cls, args):
+        """This returns the smallest possible Hilbert space."""
+        return ComplexSpace(2)**(_max(args) + 1)
+
+    #-------------------------------------------------------------------------
+    # Properties
+    #-------------------------------------------------------------------------
+
+    @property
+    def min_qubits(self):
+        """The minimum number of qubits this gate needs to act on."""
+        return _max(self.label) + 1
+
+    @property
+    def targets(self):
+        """A tuple of target qubits."""
+        return (self.label[1],)
+
+    @property
+    def controls(self):
+        """A tuple of control qubits."""
+        return (self.label[0],)
+
+    @property
+    def gate(self):
+        """The non-controlled gate that will be applied to the targets."""
+        return XGate(self.label[1])
+
+    #-------------------------------------------------------------------------
+    # Properties
+    #-------------------------------------------------------------------------
+
+    # The default printing of Gate works better than those of CGate, so we
+    # go around the overridden methods in CGate.
+
+    def _print_label(self, printer, *args):
+        return Gate._print_label(self, printer, *args)
+
+    def _pretty(self, printer, *args):
+        return Gate._pretty(self, printer, *args)
+
+    def _latex(self, printer, *args):
+        return Gate._latex(self, printer, *args)
+
+    #-------------------------------------------------------------------------
+    # Commutator/AntiCommutator
+    #-------------------------------------------------------------------------
+
+    def _eval_commutator_ZGate(self, other, **hints):
+        """[CNOT(i, j), Z(i)] == 0."""
+        if self.controls[0] == other.targets[0]:
+            return _S.Zero
+        else:
+            raise NotImplementedError('Commutator not implemented: %r' % other)
+
+    def _eval_commutator_TGate(self, other, **hints):
+        """[CNOT(i, j), T(i)] == 0."""
+        return self._eval_commutator_ZGate(other, **hints)
+
+    def _eval_commutator_PhaseGate(self, other, **hints):
+        """[CNOT(i, j), S(i)] == 0."""
+        return self._eval_commutator_ZGate(other, **hints)
+
+    def _eval_commutator_XGate(self, other, **hints):
+        """[CNOT(i, j), X(j)] == 0."""
+        if self.targets[0] == other.targets[0]:
+            return _S.Zero
+        else:
+            raise NotImplementedError('Commutator not implemented: %r' % other)
+
+    def _eval_commutator_CNotGate(self, other, **hints):
+        """[CNOT(i, j), CNOT(i,k)] == 0."""
+        if self.controls[0] == other.controls[0]:
+            return _S.Zero
+        else:
+            raise NotImplementedError('Commutator not implemented: %r' % other)
+
+
+class SwapGate(TwoQubitGate):
+    """Two qubit SWAP gate.
+
+    This gate swap the values of the two qubits.
+
+    Parameters
+    ----------
+    label : tuple
+        A tuple of the form (target1, target2).
+
+    Examples
+    ========
+
+    """
+    is_hermitian = True
+    gate_name = 'SWAP'
+    gate_name_latex = r'\text{SWAP}'
+
+    def get_target_matrix(self, format='sympy'):
+        return matrix_cache.get_matrix('SWAP', format)
+
+    def decompose(self, **options):
+        """Decompose the SWAP gate into CNOT gates."""
+        i, j = self.targets[0], self.targets[1]
+        g1 = CNotGate(i, j)
+        g2 = CNotGate(j, i)
+        return g1*g2*g1
+
+    def plot_gate(self, circ_plot, gate_idx):
+        min_wire = int(_min(self.targets))
+        max_wire = int(_max(self.targets))
+        circ_plot.control_line(gate_idx, min_wire, max_wire)
+        circ_plot.swap_point(gate_idx, min_wire)
+        circ_plot.swap_point(gate_idx, max_wire)
+
+    def _represent_ZGate(self, basis, **options):
+        """Represent the SWAP gate in the computational basis.
+
+        The following representation is used to compute this:
+
+        SWAP = |1><1|x|1><1| + |0><0|x|0><0| + |1><0|x|0><1| + |0><1|x|1><0|
+        """
+        format = options.get('format', 'sympy')
+        targets = [int(t) for t in self.targets]
+        min_target = _min(targets)
+        max_target = _max(targets)
+        nqubits = options.get('nqubits', self.min_qubits)
+
+        op01 = matrix_cache.get_matrix('op01', format)
+        op10 = matrix_cache.get_matrix('op10', format)
+        op11 = matrix_cache.get_matrix('op11', format)
+        op00 = matrix_cache.get_matrix('op00', format)
+        eye2 = matrix_cache.get_matrix('eye2', format)
+
+        result = None
+        for i, j in ((op01, op10), (op10, op01), (op00, op00), (op11, op11)):
+            product = nqubits*[eye2]
+            product[nqubits - min_target - 1] = i
+            product[nqubits - max_target - 1] = j
+            new_result = matrix_tensor_product(*product)
+            if result is None:
+                result = new_result
+            else:
+                result = result + new_result
+
+        return result
+
+
+# Aliases for gate names.
+CNOT = CNotGate
+SWAP = SwapGate
+def CPHASE(a,b): return CGateS((a,),Z(b))
+
+
+#-----------------------------------------------------------------------------
+# Represent
+#-----------------------------------------------------------------------------
+
+
+def represent_zbasis(controls, targets, target_matrix, nqubits, format='sympy'):
+    """Represent a gate with controls, targets and target_matrix.
+
+    This function does the low-level work of representing gates as matrices
+    in the standard computational basis (ZGate). Currently, we support two
+    main cases:
+
+    1. One target qubit and no control qubits.
+    2. One target qubits and multiple control qubits.
+
+    For the base of multiple controls, we use the following expression [1]:
+
+    1_{2**n} + (|1><1|)^{(n-1)} x (target-matrix - 1_{2})
+
+    Parameters
+    ----------
+    controls : list, tuple
+        A sequence of control qubits.
+    targets : list, tuple
+        A sequence of target qubits.
+    target_matrix : sympy.Matrix, numpy.matrix, scipy.sparse
+        The matrix form of the transformation to be performed on the target
+        qubits.  The format of this matrix must match that passed into
+        the `format` argument.
+    nqubits : int
+        The total number of qubits used for the representation.
+    format : str
+        The format of the final matrix ('sympy', 'numpy', 'scipy.sparse').
+
+    Examples
+    ========
+
+    References
+    ----------
+    [1] http://www.johnlapeyre.com/qinf/qinf_html/node6.html.
+    """
+    controls = [int(x) for x in controls]
+    targets = [int(x) for x in targets]
+    nqubits = int(nqubits)
+
+    # This checks for the format as well.
+    op11 = matrix_cache.get_matrix('op11', format)
+    eye2 = matrix_cache.get_matrix('eye2', format)
+
+    # Plain single qubit case
+    if len(controls) == 0 and len(targets) == 1:
+        product = []
+        bit = targets[0]
+        # Fill product with [I1,Gate,I2] such that the unitaries,
+        # I, cause the gate to be applied to the correct Qubit
+        if bit != nqubits - 1:
+            product.append(matrix_eye(2**(nqubits - bit - 1), format=format))
+        product.append(target_matrix)
+        if bit != 0:
+            product.append(matrix_eye(2**bit, format=format))
+        return matrix_tensor_product(*product)
+
+    # Single target, multiple controls.
+    elif len(targets) == 1 and len(controls) >= 1:
+        target = targets[0]
+
+        # Build the non-trivial part.
+        product2 = []
+        for i in range(nqubits):
+            product2.append(matrix_eye(2, format=format))
+        for control in controls:
+            product2[nqubits - 1 - control] = op11
+        product2[nqubits - 1 - target] = target_matrix - eye2
+
+        return matrix_eye(2**nqubits, format=format) + \
+            matrix_tensor_product(*product2)
+
+    # Multi-target, multi-control is not yet implemented.
+    else:
+        raise NotImplementedError(
+            'The representation of multi-target, multi-control gates '
+            'is not implemented.'
+        )
+
+
+#-----------------------------------------------------------------------------
+# Gate manipulation functions.
+#-----------------------------------------------------------------------------
+
+
+def gate_simp(circuit):
+    """Simplifies gates symbolically
+
+    It first sorts gates using gate_sort. It then applies basic
+    simplification rules to the circuit, e.g., XGate**2 = Identity
+    """
+
+    # Bubble sort out gates that commute.
+    circuit = gate_sort(circuit)
+
+    # Do simplifications by subing a simplification into the first element
+    # which can be simplified. We recursively call gate_simp with new circuit
+    # as input more simplifications exist.
+    if isinstance(circuit, Add):
+        return sum(gate_simp(t) for t in circuit.args)
+    elif isinstance(circuit, Mul):
+        circuit_args = circuit.args
+    elif isinstance(circuit, Pow):
+        b, e = circuit.as_base_exp()
+        circuit_args = (gate_simp(b)**e,)
+    else:
+        return circuit
+
+    # Iterate through each element in circuit, simplify if possible.
+    for i in range(len(circuit_args)):
+        # H,X,Y or Z squared is 1.
+        # T**2 = S, S**2 = Z
+        if isinstance(circuit_args[i], Pow):
+            if isinstance(circuit_args[i].base,
+                (HadamardGate, XGate, YGate, ZGate)) \
+                    and isinstance(circuit_args[i].exp, Number):
+                # Build a new circuit taking replacing the
+                # H,X,Y,Z squared with one.
+                newargs = (circuit_args[:i] +
+                          (circuit_args[i].base**(circuit_args[i].exp % 2),) +
+                           circuit_args[i + 1:])
+                # Recursively simplify the new circuit.
+                circuit = gate_simp(Mul(*newargs))
+                break
+            elif isinstance(circuit_args[i].base, PhaseGate):
+                # Build a new circuit taking old circuit but splicing
+                # in simplification.
+                newargs = circuit_args[:i]
+                # Replace PhaseGate**2 with ZGate.
+                newargs = newargs + (ZGate(circuit_args[i].base.args[0])**
+                (Integer(circuit_args[i].exp/2)), circuit_args[i].base**
+                (circuit_args[i].exp % 2))
+                # Append the last elements.
+                newargs = newargs + circuit_args[i + 1:]
+                # Recursively simplify the new circuit.
+                circuit = gate_simp(Mul(*newargs))
+                break
+            elif isinstance(circuit_args[i].base, TGate):
+                # Build a new circuit taking all the old elements.
+                newargs = circuit_args[:i]
+
+                # Put an Phasegate in place of any TGate**2.
+                newargs = newargs + (PhaseGate(circuit_args[i].base.args[0])**
+                Integer(circuit_args[i].exp/2), circuit_args[i].base**
+                    (circuit_args[i].exp % 2))
+
+                # Append the last elements.
+                newargs = newargs + circuit_args[i + 1:]
+                # Recursively simplify the new circuit.
+                circuit = gate_simp(Mul(*newargs))
+                break
+    return circuit
+
+
+def gate_sort(circuit):
+    """Sorts the gates while keeping track of commutation relations
+
+    This function uses a bubble sort to rearrange the order of gate
+    application. Keeps track of Quantum computations special commutation
+    relations (e.g. things that apply to the same Qubit do not commute with
+    each other)
+
+    circuit is the Mul of gates that are to be sorted.
+    """
+    # Make sure we have an Add or Mul.
+    if isinstance(circuit, Add):
+        return sum(gate_sort(t) for t in circuit.args)
+    if isinstance(circuit, Pow):
+        return gate_sort(circuit.base)**circuit.exp
+    elif isinstance(circuit, Gate):
+        return circuit
+    if not isinstance(circuit, Mul):
+        return circuit
+
+    changes = True
+    while changes:
+        changes = False
+        circ_array = circuit.args
+        for i in range(len(circ_array) - 1):
+            # Go through each element and switch ones that are in wrong order
+            if isinstance(circ_array[i], (Gate, Pow)) and \
+                    isinstance(circ_array[i + 1], (Gate, Pow)):
+                # If we have a Pow object, look at only the base
+                first_base, first_exp = circ_array[i].as_base_exp()
+                second_base, second_exp = circ_array[i + 1].as_base_exp()
+
+                # Use SymPy's hash based sorting. This is not mathematical
+                # sorting, but is rather based on comparing hashes of objects.
+                # See Basic.compare for details.
+                if first_base.compare(second_base) > 0:
+                    if Commutator(first_base, second_base).doit() == 0:
+                        new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
+                                   (circuit.args[i],) + circuit.args[i + 2:])
+                        circuit = Mul(*new_args)
+                        changes = True
+                        break
+                    if AntiCommutator(first_base, second_base).doit() == 0:
+                        new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
+                                   (circuit.args[i],) + circuit.args[i + 2:])
+                        sign = _S.NegativeOne**(first_exp*second_exp)
+                        circuit = sign*Mul(*new_args)
+                        changes = True
+                        break
+    return circuit
+
+
+#-----------------------------------------------------------------------------
+# Utility functions
+#-----------------------------------------------------------------------------
+
+
+def random_circuit(ngates, nqubits, gate_space=(X, Y, Z, S, T, H, CNOT, SWAP)):
+    """Return a random circuit of ngates and nqubits.
+
+    This uses an equally weighted sample of (X, Y, Z, S, T, H, CNOT, SWAP)
+    gates.
+
+    Parameters
+    ----------
+    ngates : int
+        The number of gates in the circuit.
+    nqubits : int
+        The number of qubits in the circuit.
+    gate_space : tuple
+        A tuple of the gate classes that will be used in the circuit.
+        Repeating gate classes multiple times in this tuple will increase
+        the frequency they appear in the random circuit.
+    """
+    qubit_space = range(nqubits)
+    result = []
+    for i in range(ngates):
+        g = random.choice(gate_space)
+        if g == CNotGate or g == SwapGate:
+            qubits = random.sample(qubit_space, 2)
+            g = g(*qubits)
+        else:
+            qubit = random.choice(qubit_space)
+            g = g(qubit)
+        result.append(g)
+    return Mul(*result)
+
+
+def zx_basis_transform(self, format='sympy'):
+    """Transformation matrix from Z to X basis."""
+    return matrix_cache.get_matrix('ZX', format)
+
+
+def zy_basis_transform(self, format='sympy'):
+    """Transformation matrix from Z to Y basis."""
+    return matrix_cache.get_matrix('ZY', format)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/grover.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/grover.py
new file mode 100644
index 0000000000000000000000000000000000000000..a03bd3a61a6e0960ab66d55bcc0fc7f25936199e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/grover.py
@@ -0,0 +1,345 @@
+"""Grover's algorithm and helper functions.
+
+Todo:
+
+* W gate construction (or perhaps -W gate based on Mermin's book)
+* Generalize the algorithm for an unknown function that returns 1 on multiple
+  qubit states, not just one.
+* Implement _represent_ZGate in OracleGate
+"""
+
+from sympy.core.numbers import pi
+from sympy.core.sympify import sympify
+from sympy.core.basic import Atom
+from sympy.functions.elementary.integers import floor
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.matrices.dense import eye
+from sympy.core.numbers import NegativeOne
+from sympy.physics.quantum.qapply import qapply
+from sympy.physics.quantum.qexpr import QuantumError
+from sympy.physics.quantum.hilbert import ComplexSpace
+from sympy.physics.quantum.operator import UnitaryOperator
+from sympy.physics.quantum.gate import Gate
+from sympy.physics.quantum.qubit import IntQubit
+
+__all__ = [
+    'OracleGate',
+    'WGate',
+    'superposition_basis',
+    'grover_iteration',
+    'apply_grover'
+]
+
+
+def superposition_basis(nqubits):
+    """Creates an equal superposition of the computational basis.
+
+    Parameters
+    ==========
+
+    nqubits : int
+        The number of qubits.
+
+    Returns
+    =======
+
+    state : Qubit
+        An equal superposition of the computational basis with nqubits.
+
+    Examples
+    ========
+
+    Create an equal superposition of 2 qubits::
+
+        >>> from sympy.physics.quantum.grover import superposition_basis
+        >>> superposition_basis(2)
+        |0>/2 + |1>/2 + |2>/2 + |3>/2
+    """
+
+    amp = 1/sqrt(2**nqubits)
+    return sum(amp*IntQubit(n, nqubits=nqubits) for n in range(2**nqubits))
+
+class OracleGateFunction(Atom):
+    """Wrapper for python functions used in `OracleGate`s"""
+
+    def __new__(cls, function):
+        if not callable(function):
+            raise TypeError('Callable expected, got: %r' % function)
+        obj = Atom.__new__(cls)
+        obj.function = function
+        return obj
+
+    def _hashable_content(self):
+        return type(self), self.function
+
+    def __call__(self, *args):
+        return self.function(*args)
+
+
+class OracleGate(Gate):
+    """A black box gate.
+
+    The gate marks the desired qubits of an unknown function by flipping
+    the sign of the qubits.  The unknown function returns true when it
+    finds its desired qubits and false otherwise.
+
+    Parameters
+    ==========
+
+    qubits : int
+        Number of qubits.
+
+    oracle : callable
+        A callable function that returns a boolean on a computational basis.
+
+    Examples
+    ========
+
+    Apply an Oracle gate that flips the sign of ``|2>`` on different qubits::
+
+        >>> from sympy.physics.quantum.qubit import IntQubit
+        >>> from sympy.physics.quantum.qapply import qapply
+        >>> from sympy.physics.quantum.grover import OracleGate
+        >>> f = lambda qubits: qubits == IntQubit(2)
+        >>> v = OracleGate(2, f)
+        >>> qapply(v*IntQubit(2))
+        -|2>
+        >>> qapply(v*IntQubit(3))
+        |3>
+    """
+
+    gate_name = 'V'
+    gate_name_latex = 'V'
+
+    #-------------------------------------------------------------------------
+    # Initialization/creation
+    #-------------------------------------------------------------------------
+
+    @classmethod
+    def _eval_args(cls, args):
+        if len(args) != 2:
+            raise QuantumError(
+                'Insufficient/excessive arguments to Oracle.  Please ' +
+                'supply the number of qubits and an unknown function.'
+            )
+        sub_args = (args[0],)
+        sub_args = UnitaryOperator._eval_args(sub_args)
+        if not sub_args[0].is_Integer:
+            raise TypeError('Integer expected, got: %r' % sub_args[0])
+
+        function = args[1]
+        if not isinstance(function, OracleGateFunction):
+            function = OracleGateFunction(function)
+
+        return (sub_args[0], function)
+
+    @classmethod
+    def _eval_hilbert_space(cls, args):
+        """This returns the smallest possible Hilbert space."""
+        return ComplexSpace(2)**args[0]
+
+    #-------------------------------------------------------------------------
+    # Properties
+    #-------------------------------------------------------------------------
+
+    @property
+    def search_function(self):
+        """The unknown function that helps find the sought after qubits."""
+        return self.label[1]
+
+    @property
+    def targets(self):
+        """A tuple of target qubits."""
+        return sympify(tuple(range(self.args[0])))
+
+    #-------------------------------------------------------------------------
+    # Apply
+    #-------------------------------------------------------------------------
+
+    def _apply_operator_Qubit(self, qubits, **options):
+        """Apply this operator to a Qubit subclass.
+
+        Parameters
+        ==========
+
+        qubits : Qubit
+            The qubit subclass to apply this operator to.
+
+        Returns
+        =======
+
+        state : Expr
+            The resulting quantum state.
+        """
+        if qubits.nqubits != self.nqubits:
+            raise QuantumError(
+                'OracleGate operates on %r qubits, got: %r'
+                % (self.nqubits, qubits.nqubits)
+            )
+        # If function returns 1 on qubits
+            # return the negative of the qubits (flip the sign)
+        if self.search_function(qubits):
+            return -qubits
+        else:
+            return qubits
+
+    #-------------------------------------------------------------------------
+    # Represent
+    #-------------------------------------------------------------------------
+
+    def _represent_ZGate(self, basis, **options):
+        """
+        Represent the OracleGate in the computational basis.
+        """
+        nbasis = 2**self.nqubits  # compute it only once
+        matrixOracle = eye(nbasis)
+        # Flip the sign given the output of the oracle function
+        for i in range(nbasis):
+            if self.search_function(IntQubit(i, nqubits=self.nqubits)):
+                matrixOracle[i, i] = NegativeOne()
+        return matrixOracle
+
+
+class WGate(Gate):
+    """General n qubit W Gate in Grover's algorithm.
+
+    The gate performs the operation ``2|phi> = (tensor product of n Hadamards)*(|0> with n qubits)``
+
+    Parameters
+    ==========
+
+    nqubits : int
+        The number of qubits to operate on
+
+    """
+
+    gate_name = 'W'
+    gate_name_latex = 'W'
+
+    @classmethod
+    def _eval_args(cls, args):
+        if len(args) != 1:
+            raise QuantumError(
+                'Insufficient/excessive arguments to W gate.  Please ' +
+                'supply the number of qubits to operate on.'
+            )
+        args = UnitaryOperator._eval_args(args)
+        if not args[0].is_Integer:
+            raise TypeError('Integer expected, got: %r' % args[0])
+        return args
+
+    #-------------------------------------------------------------------------
+    # Properties
+    #-------------------------------------------------------------------------
+
+    @property
+    def targets(self):
+        return sympify(tuple(reversed(range(self.args[0]))))
+
+    #-------------------------------------------------------------------------
+    # Apply
+    #-------------------------------------------------------------------------
+
+    def _apply_operator_Qubit(self, qubits, **options):
+        """
+        qubits: a set of qubits (Qubit)
+        Returns: quantum object (quantum expression - QExpr)
+        """
+        if qubits.nqubits != self.nqubits:
+            raise QuantumError(
+                'WGate operates on %r qubits, got: %r'
+                % (self.nqubits, qubits.nqubits)
+            )
+
+        # See 'Quantum Computer Science' by David Mermin p.92 -> W|a> result
+        # Return (2/(sqrt(2^n)))|phi> - |a> where |a> is the current basis
+        # state and phi is the superposition of basis states (see function
+        # create_computational_basis above)
+        basis_states = superposition_basis(self.nqubits)
+        change_to_basis = (2/sqrt(2**self.nqubits))*basis_states
+        return change_to_basis - qubits
+
+
+def grover_iteration(qstate, oracle):
+    """Applies one application of the Oracle and W Gate, WV.
+
+    Parameters
+    ==========
+
+    qstate : Qubit
+        A superposition of qubits.
+    oracle : OracleGate
+        The black box operator that flips the sign of the desired basis qubits.
+
+    Returns
+    =======
+
+    Qubit : The qubits after applying the Oracle and W gate.
+
+    Examples
+    ========
+
+    Perform one iteration of grover's algorithm to see a phase change::
+
+        >>> from sympy.physics.quantum.qapply import qapply
+        >>> from sympy.physics.quantum.qubit import IntQubit
+        >>> from sympy.physics.quantum.grover import OracleGate
+        >>> from sympy.physics.quantum.grover import superposition_basis
+        >>> from sympy.physics.quantum.grover import grover_iteration
+        >>> numqubits = 2
+        >>> basis_states = superposition_basis(numqubits)
+        >>> f = lambda qubits: qubits == IntQubit(2)
+        >>> v = OracleGate(numqubits, f)
+        >>> qapply(grover_iteration(basis_states, v))
+        |2>
+
+    """
+    wgate = WGate(oracle.nqubits)
+    return wgate*oracle*qstate
+
+
+def apply_grover(oracle, nqubits, iterations=None):
+    """Applies grover's algorithm.
+
+    Parameters
+    ==========
+
+    oracle : callable
+        The unknown callable function that returns true when applied to the
+        desired qubits and false otherwise.
+
+    Returns
+    =======
+
+    state : Expr
+        The resulting state after Grover's algorithm has been iterated.
+
+    Examples
+    ========
+
+    Apply grover's algorithm to an even superposition of 2 qubits::
+
+        >>> from sympy.physics.quantum.qapply import qapply
+        >>> from sympy.physics.quantum.qubit import IntQubit
+        >>> from sympy.physics.quantum.grover import apply_grover
+        >>> f = lambda qubits: qubits == IntQubit(2)
+        >>> qapply(apply_grover(f, 2))
+        |2>
+
+    """
+    if nqubits <= 0:
+        raise QuantumError(
+            'Grover\'s algorithm needs nqubits > 0, received %r qubits'
+            % nqubits
+        )
+    if iterations is None:
+        iterations = floor(sqrt(2**nqubits)*(pi/4))
+
+    v = OracleGate(nqubits, oracle)
+    iterated = superposition_basis(nqubits)
+    for iter in range(iterations):
+        iterated = grover_iteration(iterated, v)
+        iterated = qapply(iterated)
+
+    return iterated
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/hilbert.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/hilbert.py
new file mode 100644
index 0000000000000000000000000000000000000000..f475a9e83a6ccc93e9e2dbb9873ad111c1d05f93
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/hilbert.py
@@ -0,0 +1,653 @@
+"""Hilbert spaces for quantum mechanics.
+
+Authors:
+* Brian Granger
+* Matt Curry
+"""
+
+from functools import reduce
+
+from sympy.core.basic import Basic
+from sympy.core.singleton import S
+from sympy.core.sympify import sympify
+from sympy.sets.sets import Interval
+from sympy.printing.pretty.stringpict import prettyForm
+from sympy.physics.quantum.qexpr import QuantumError
+
+
+__all__ = [
+    'HilbertSpaceError',
+    'HilbertSpace',
+    'TensorProductHilbertSpace',
+    'TensorPowerHilbertSpace',
+    'DirectSumHilbertSpace',
+    'ComplexSpace',
+    'L2',
+    'FockSpace'
+]
+
+#-----------------------------------------------------------------------------
+# Main objects
+#-----------------------------------------------------------------------------
+
+
+class HilbertSpaceError(QuantumError):
+    pass
+
+#-----------------------------------------------------------------------------
+# Main objects
+#-----------------------------------------------------------------------------
+
+
+class HilbertSpace(Basic):
+    """An abstract Hilbert space for quantum mechanics.
+
+    In short, a Hilbert space is an abstract vector space that is complete
+    with inner products defined [1]_.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum.hilbert import HilbertSpace
+    >>> hs = HilbertSpace()
+    >>> hs
+    H
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Hilbert_space
+    """
+
+    def __new__(cls):
+        obj = Basic.__new__(cls)
+        return obj
+
+    @property
+    def dimension(self):
+        """Return the Hilbert dimension of the space."""
+        raise NotImplementedError('This Hilbert space has no dimension.')
+
+    def __add__(self, other):
+        return DirectSumHilbertSpace(self, other)
+
+    def __radd__(self, other):
+        return DirectSumHilbertSpace(other, self)
+
+    def __mul__(self, other):
+        return TensorProductHilbertSpace(self, other)
+
+    def __rmul__(self, other):
+        return TensorProductHilbertSpace(other, self)
+
+    def __pow__(self, other, mod=None):
+        if mod is not None:
+            raise ValueError('The third argument to __pow__ is not supported \
+            for Hilbert spaces.')
+        return TensorPowerHilbertSpace(self, other)
+
+    def __contains__(self, other):
+        """Is the operator or state in this Hilbert space.
+
+        This is checked by comparing the classes of the Hilbert spaces, not
+        the instances. This is to allow Hilbert Spaces with symbolic
+        dimensions.
+        """
+        if other.hilbert_space.__class__ == self.__class__:
+            return True
+        else:
+            return False
+
+    def _sympystr(self, printer, *args):
+        return 'H'
+
+    def _pretty(self, printer, *args):
+        ustr = '\N{LATIN CAPITAL LETTER H}'
+        return prettyForm(ustr)
+
+    def _latex(self, printer, *args):
+        return r'\mathcal{H}'
+
+
+class ComplexSpace(HilbertSpace):
+    """Finite dimensional Hilbert space of complex vectors.
+
+    The elements of this Hilbert space are n-dimensional complex valued
+    vectors with the usual inner product that takes the complex conjugate
+    of the vector on the right.
+
+    A classic example of this type of Hilbert space is spin-1/2, which is
+    ``ComplexSpace(2)``. Generalizing to spin-s, the space is
+    ``ComplexSpace(2*s+1)``.  Quantum computing with N qubits is done with the
+    direct product space ``ComplexSpace(2)**N``.
+
+    Examples
+    ========
+
+    >>> from sympy import symbols
+    >>> from sympy.physics.quantum.hilbert import ComplexSpace
+    >>> c1 = ComplexSpace(2)
+    >>> c1
+    C(2)
+    >>> c1.dimension
+    2
+
+    >>> n = symbols('n')
+    >>> c2 = ComplexSpace(n)
+    >>> c2
+    C(n)
+    >>> c2.dimension
+    n
+
+    """
+
+    def __new__(cls, dimension):
+        dimension = sympify(dimension)
+        r = cls.eval(dimension)
+        if isinstance(r, Basic):
+            return r
+        obj = Basic.__new__(cls, dimension)
+        return obj
+
+    @classmethod
+    def eval(cls, dimension):
+        if len(dimension.atoms()) == 1:
+            if not (dimension.is_Integer and dimension > 0 or dimension is S.Infinity
+            or dimension.is_Symbol):
+                raise TypeError('The dimension of a ComplexSpace can only'
+                                'be a positive integer, oo, or a Symbol: %r'
+                                % dimension)
+        else:
+            for dim in dimension.atoms():
+                if not (dim.is_Integer or dim is S.Infinity or dim.is_Symbol):
+                    raise TypeError('The dimension of a ComplexSpace can only'
+                                    ' contain integers, oo, or a Symbol: %r'
+                                    % dim)
+
+    @property
+    def dimension(self):
+        return self.args[0]
+
+    def _sympyrepr(self, printer, *args):
+        return "%s(%s)" % (self.__class__.__name__,
+                           printer._print(self.dimension, *args))
+
+    def _sympystr(self, printer, *args):
+        return "C(%s)" % printer._print(self.dimension, *args)
+
+    def _pretty(self, printer, *args):
+        ustr = '\N{LATIN CAPITAL LETTER C}'
+        pform_exp = printer._print(self.dimension, *args)
+        pform_base = prettyForm(ustr)
+        return pform_base**pform_exp
+
+    def _latex(self, printer, *args):
+        return r'\mathcal{C}^{%s}' % printer._print(self.dimension, *args)
+
+
+class L2(HilbertSpace):
+    """The Hilbert space of square integrable functions on an interval.
+
+    An L2 object takes in a single SymPy Interval argument which represents
+    the interval its functions (vectors) are defined on.
+
+    Examples
+    ========
+
+    >>> from sympy import Interval, oo
+    >>> from sympy.physics.quantum.hilbert import L2
+    >>> hs = L2(Interval(0,oo))
+    >>> hs
+    L2(Interval(0, oo))
+    >>> hs.dimension
+    oo
+    >>> hs.interval
+    Interval(0, oo)
+
+    """
+
+    def __new__(cls, interval):
+        if not isinstance(interval, Interval):
+            raise TypeError('L2 interval must be an Interval instance: %r'
+            % interval)
+        obj = Basic.__new__(cls, interval)
+        return obj
+
+    @property
+    def dimension(self):
+        return S.Infinity
+
+    @property
+    def interval(self):
+        return self.args[0]
+
+    def _sympyrepr(self, printer, *args):
+        return "L2(%s)" % printer._print(self.interval, *args)
+
+    def _sympystr(self, printer, *args):
+        return "L2(%s)" % printer._print(self.interval, *args)
+
+    def _pretty(self, printer, *args):
+        pform_exp = prettyForm('2')
+        pform_base = prettyForm('L')
+        return pform_base**pform_exp
+
+    def _latex(self, printer, *args):
+        interval = printer._print(self.interval, *args)
+        return r'{\mathcal{L}^2}\left( %s \right)' % interval
+
+
+class FockSpace(HilbertSpace):
+    """The Hilbert space for second quantization.
+
+    Technically, this Hilbert space is a infinite direct sum of direct
+    products of single particle Hilbert spaces [1]_. This is a mess, so we have
+    a class to represent it directly.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum.hilbert import FockSpace
+    >>> hs = FockSpace()
+    >>> hs
+    F
+    >>> hs.dimension
+    oo
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Fock_space
+    """
+
+    def __new__(cls):
+        obj = Basic.__new__(cls)
+        return obj
+
+    @property
+    def dimension(self):
+        return S.Infinity
+
+    def _sympyrepr(self, printer, *args):
+        return "FockSpace()"
+
+    def _sympystr(self, printer, *args):
+        return "F"
+
+    def _pretty(self, printer, *args):
+        ustr = '\N{LATIN CAPITAL LETTER F}'
+        return prettyForm(ustr)
+
+    def _latex(self, printer, *args):
+        return r'\mathcal{F}'
+
+
+class TensorProductHilbertSpace(HilbertSpace):
+    """A tensor product of Hilbert spaces [1]_.
+
+    The tensor product between Hilbert spaces is represented by the
+    operator ``*`` Products of the same Hilbert space will be combined into
+    tensor powers.
+
+    A ``TensorProductHilbertSpace`` object takes in an arbitrary number of
+    ``HilbertSpace`` objects as its arguments. In addition, multiplication of
+    ``HilbertSpace`` objects will automatically return this tensor product
+    object.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
+    >>> from sympy import symbols
+
+    >>> c = ComplexSpace(2)
+    >>> f = FockSpace()
+    >>> hs = c*f
+    >>> hs
+    C(2)*F
+    >>> hs.dimension
+    oo
+    >>> hs.spaces
+    (C(2), F)
+
+    >>> c1 = ComplexSpace(2)
+    >>> n = symbols('n')
+    >>> c2 = ComplexSpace(n)
+    >>> hs = c1*c2
+    >>> hs
+    C(2)*C(n)
+    >>> hs.dimension
+    2*n
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products
+    """
+
+    def __new__(cls, *args):
+        r = cls.eval(args)
+        if isinstance(r, Basic):
+            return r
+        obj = Basic.__new__(cls, *args)
+        return obj
+
+    @classmethod
+    def eval(cls, args):
+        """Evaluates the direct product."""
+        new_args = []
+        recall = False
+        #flatten arguments
+        for arg in args:
+            if isinstance(arg, TensorProductHilbertSpace):
+                new_args.extend(arg.args)
+                recall = True
+            elif isinstance(arg, (HilbertSpace, TensorPowerHilbertSpace)):
+                new_args.append(arg)
+            else:
+                raise TypeError('Hilbert spaces can only be multiplied by \
+                other Hilbert spaces: %r' % arg)
+        #combine like arguments into direct powers
+        comb_args = []
+        prev_arg = None
+        for new_arg in new_args:
+            if prev_arg is not None:
+                if isinstance(new_arg, TensorPowerHilbertSpace) and \
+                    isinstance(prev_arg, TensorPowerHilbertSpace) and \
+                        new_arg.base == prev_arg.base:
+                    prev_arg = new_arg.base**(new_arg.exp + prev_arg.exp)
+                elif isinstance(new_arg, TensorPowerHilbertSpace) and \
+                        new_arg.base == prev_arg:
+                    prev_arg = prev_arg**(new_arg.exp + 1)
+                elif isinstance(prev_arg, TensorPowerHilbertSpace) and \
+                        new_arg == prev_arg.base:
+                    prev_arg = new_arg**(prev_arg.exp + 1)
+                elif new_arg == prev_arg:
+                    prev_arg = new_arg**2
+                else:
+                    comb_args.append(prev_arg)
+                    prev_arg = new_arg
+            elif prev_arg is None:
+                prev_arg = new_arg
+        comb_args.append(prev_arg)
+        if recall:
+            return TensorProductHilbertSpace(*comb_args)
+        elif len(comb_args) == 1:
+            return TensorPowerHilbertSpace(comb_args[0].base, comb_args[0].exp)
+        else:
+            return None
+
+    @property
+    def dimension(self):
+        arg_list = [arg.dimension for arg in self.args]
+        if S.Infinity in arg_list:
+            return S.Infinity
+        else:
+            return reduce(lambda x, y: x*y, arg_list)
+
+    @property
+    def spaces(self):
+        """A tuple of the Hilbert spaces in this tensor product."""
+        return self.args
+
+    def _spaces_printer(self, printer, *args):
+        spaces_strs = []
+        for arg in self.args:
+            s = printer._print(arg, *args)
+            if isinstance(arg, DirectSumHilbertSpace):
+                s = '(%s)' % s
+            spaces_strs.append(s)
+        return spaces_strs
+
+    def _sympyrepr(self, printer, *args):
+        spaces_reprs = self._spaces_printer(printer, *args)
+        return "TensorProductHilbertSpace(%s)" % ','.join(spaces_reprs)
+
+    def _sympystr(self, printer, *args):
+        spaces_strs = self._spaces_printer(printer, *args)
+        return '*'.join(spaces_strs)
+
+    def _pretty(self, printer, *args):
+        length = len(self.args)
+        pform = printer._print('', *args)
+        for i in range(length):
+            next_pform = printer._print(self.args[i], *args)
+            if isinstance(self.args[i], (DirectSumHilbertSpace,
+                          TensorProductHilbertSpace)):
+                next_pform = prettyForm(
+                    *next_pform.parens(left='(', right=')')
+                )
+            pform = prettyForm(*pform.right(next_pform))
+            if i != length - 1:
+                if printer._use_unicode:
+                    pform = prettyForm(*pform.right(' ' + '\N{N-ARY CIRCLED TIMES OPERATOR}' + ' '))
+                else:
+                    pform = prettyForm(*pform.right(' x '))
+        return pform
+
+    def _latex(self, printer, *args):
+        length = len(self.args)
+        s = ''
+        for i in range(length):
+            arg_s = printer._print(self.args[i], *args)
+            if isinstance(self.args[i], (DirectSumHilbertSpace,
+                 TensorProductHilbertSpace)):
+                arg_s = r'\left(%s\right)' % arg_s
+            s = s + arg_s
+            if i != length - 1:
+                s = s + r'\otimes '
+        return s
+
+
+class DirectSumHilbertSpace(HilbertSpace):
+    """A direct sum of Hilbert spaces [1]_.
+
+    This class uses the ``+`` operator to represent direct sums between
+    different Hilbert spaces.
+
+    A ``DirectSumHilbertSpace`` object takes in an arbitrary number of
+    ``HilbertSpace`` objects as its arguments. Also, addition of
+    ``HilbertSpace`` objects will automatically return a direct sum object.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
+
+    >>> c = ComplexSpace(2)
+    >>> f = FockSpace()
+    >>> hs = c+f
+    >>> hs
+    C(2)+F
+    >>> hs.dimension
+    oo
+    >>> list(hs.spaces)
+    [C(2), F]
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Hilbert_space#Direct_sums
+    """
+    def __new__(cls, *args):
+        r = cls.eval(args)
+        if isinstance(r, Basic):
+            return r
+        obj = Basic.__new__(cls, *args)
+        return obj
+
+    @classmethod
+    def eval(cls, args):
+        """Evaluates the direct product."""
+        new_args = []
+        recall = False
+        #flatten arguments
+        for arg in args:
+            if isinstance(arg, DirectSumHilbertSpace):
+                new_args.extend(arg.args)
+                recall = True
+            elif isinstance(arg, HilbertSpace):
+                new_args.append(arg)
+            else:
+                raise TypeError('Hilbert spaces can only be summed with other \
+                Hilbert spaces: %r' % arg)
+        if recall:
+            return DirectSumHilbertSpace(*new_args)
+        else:
+            return None
+
+    @property
+    def dimension(self):
+        arg_list = [arg.dimension for arg in self.args]
+        if S.Infinity in arg_list:
+            return S.Infinity
+        else:
+            return reduce(lambda x, y: x + y, arg_list)
+
+    @property
+    def spaces(self):
+        """A tuple of the Hilbert spaces in this direct sum."""
+        return self.args
+
+    def _sympyrepr(self, printer, *args):
+        spaces_reprs = [printer._print(arg, *args) for arg in self.args]
+        return "DirectSumHilbertSpace(%s)" % ','.join(spaces_reprs)
+
+    def _sympystr(self, printer, *args):
+        spaces_strs = [printer._print(arg, *args) for arg in self.args]
+        return '+'.join(spaces_strs)
+
+    def _pretty(self, printer, *args):
+        length = len(self.args)
+        pform = printer._print('', *args)
+        for i in range(length):
+            next_pform = printer._print(self.args[i], *args)
+            if isinstance(self.args[i], (DirectSumHilbertSpace,
+                          TensorProductHilbertSpace)):
+                next_pform = prettyForm(
+                    *next_pform.parens(left='(', right=')')
+                )
+            pform = prettyForm(*pform.right(next_pform))
+            if i != length - 1:
+                if printer._use_unicode:
+                    pform = prettyForm(*pform.right(' \N{CIRCLED PLUS} '))
+                else:
+                    pform = prettyForm(*pform.right(' + '))
+        return pform
+
+    def _latex(self, printer, *args):
+        length = len(self.args)
+        s = ''
+        for i in range(length):
+            arg_s = printer._print(self.args[i], *args)
+            if isinstance(self.args[i], (DirectSumHilbertSpace,
+                 TensorProductHilbertSpace)):
+                arg_s = r'\left(%s\right)' % arg_s
+            s = s + arg_s
+            if i != length - 1:
+                s = s + r'\oplus '
+        return s
+
+
+class TensorPowerHilbertSpace(HilbertSpace):
+    """An exponentiated Hilbert space [1]_.
+
+    Tensor powers (repeated tensor products) are represented by the
+    operator ``**`` Identical Hilbert spaces that are multiplied together
+    will be automatically combined into a single tensor power object.
+
+    Any Hilbert space, product, or sum may be raised to a tensor power. The
+    ``TensorPowerHilbertSpace`` takes two arguments: the Hilbert space; and the
+    tensor power (number).
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
+    >>> from sympy import symbols
+
+    >>> n = symbols('n')
+    >>> c = ComplexSpace(2)
+    >>> hs = c**n
+    >>> hs
+    C(2)**n
+    >>> hs.dimension
+    2**n
+
+    >>> c = ComplexSpace(2)
+    >>> c*c
+    C(2)**2
+    >>> f = FockSpace()
+    >>> c*f*f
+    C(2)*F**2
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products
+    """
+
+    def __new__(cls, *args):
+        r = cls.eval(args)
+        if isinstance(r, Basic):
+            return r
+        return Basic.__new__(cls, *r)
+
+    @classmethod
+    def eval(cls, args):
+        new_args = args[0], sympify(args[1])
+        exp = new_args[1]
+        #simplify hs**1 -> hs
+        if exp is S.One:
+            return args[0]
+        #simplify hs**0 -> 1
+        if exp is S.Zero:
+            return S.One
+        #check (and allow) for hs**(x+42+y...) case
+        if len(exp.atoms()) == 1:
+            if not (exp.is_Integer and exp >= 0 or exp.is_Symbol):
+                raise ValueError('Hilbert spaces can only be raised to \
+                positive integers or Symbols: %r' % exp)
+        else:
+            for power in exp.atoms():
+                if not (power.is_Integer or power.is_Symbol):
+                    raise ValueError('Tensor powers can only contain integers \
+                    or Symbols: %r' % power)
+        return new_args
+
+    @property
+    def base(self):
+        return self.args[0]
+
+    @property
+    def exp(self):
+        return self.args[1]
+
+    @property
+    def dimension(self):
+        if self.base.dimension is S.Infinity:
+            return S.Infinity
+        else:
+            return self.base.dimension**self.exp
+
+    def _sympyrepr(self, printer, *args):
+        return "TensorPowerHilbertSpace(%s,%s)" % (printer._print(self.base,
+        *args), printer._print(self.exp, *args))
+
+    def _sympystr(self, printer, *args):
+        return "%s**%s" % (printer._print(self.base, *args),
+        printer._print(self.exp, *args))
+
+    def _pretty(self, printer, *args):
+        pform_exp = printer._print(self.exp, *args)
+        if printer._use_unicode:
+            pform_exp = prettyForm(*pform_exp.left(prettyForm('\N{N-ARY CIRCLED TIMES OPERATOR}')))
+        else:
+            pform_exp = prettyForm(*pform_exp.left(prettyForm('x')))
+        pform_base = printer._print(self.base, *args)
+        return pform_base**pform_exp
+
+    def _latex(self, printer, *args):
+        base = printer._print(self.base, *args)
+        exp = printer._print(self.exp, *args)
+        return r'{%s}^{\otimes %s}' % (base, exp)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/identitysearch.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/identitysearch.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a178e9b808450b7ce91175600d6b393fc9797d6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/identitysearch.py
@@ -0,0 +1,853 @@
+from collections import deque
+from sympy.core.random import randint
+
+from sympy.external import import_module
+from sympy.core.basic import Basic
+from sympy.core.mul import Mul
+from sympy.core.numbers import Number, equal_valued
+from sympy.core.power import Pow
+from sympy.core.singleton import S
+from sympy.physics.quantum.represent import represent
+from sympy.physics.quantum.dagger import Dagger
+
+__all__ = [
+    # Public interfaces
+    'generate_gate_rules',
+    'generate_equivalent_ids',
+    'GateIdentity',
+    'bfs_identity_search',
+    'random_identity_search',
+
+    # "Private" functions
+    'is_scalar_sparse_matrix',
+    'is_scalar_nonsparse_matrix',
+    'is_degenerate',
+    'is_reducible',
+]
+
+np = import_module('numpy')
+scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
+
+
+def is_scalar_sparse_matrix(circuit, nqubits, identity_only, eps=1e-11):
+    """Checks if a given scipy.sparse matrix is a scalar matrix.
+
+    A scalar matrix is such that B = bI, where B is the scalar
+    matrix, b is some scalar multiple, and I is the identity
+    matrix.  A scalar matrix would have only the element b along
+    it's main diagonal and zeroes elsewhere.
+
+    Parameters
+    ==========
+
+    circuit : Gate tuple
+        Sequence of quantum gates representing a quantum circuit
+    nqubits : int
+        Number of qubits in the circuit
+    identity_only : bool
+        Check for only identity matrices
+    eps : number
+        The tolerance value for zeroing out elements in the matrix.
+        Values in the range [-eps, +eps] will be changed to a zero.
+    """
+
+    if not np or not scipy:
+        pass
+
+    matrix = represent(Mul(*circuit), nqubits=nqubits,
+                       format='scipy.sparse')
+
+    # In some cases, represent returns a 1D scalar value in place
+    # of a multi-dimensional scalar matrix
+    if (isinstance(matrix, int)):
+        return matrix == 1 if identity_only else True
+
+    # If represent returns a matrix, check if the matrix is diagonal
+    # and if every item along the diagonal is the same
+    else:
+        # Due to floating pointing operations, must zero out
+        # elements that are "very" small in the dense matrix
+        # See parameter for default value.
+
+        # Get the ndarray version of the dense matrix
+        dense_matrix = matrix.todense().getA()
+        # Since complex values can't be compared, must split
+        # the matrix into real and imaginary components
+        # Find the real values in between -eps and eps
+        bool_real = np.logical_and(dense_matrix.real > -eps,
+                                   dense_matrix.real < eps)
+        # Find the imaginary values between -eps and eps
+        bool_imag = np.logical_and(dense_matrix.imag > -eps,
+                                   dense_matrix.imag < eps)
+        # Replaces values between -eps and eps with 0
+        corrected_real = np.where(bool_real, 0.0, dense_matrix.real)
+        corrected_imag = np.where(bool_imag, 0.0, dense_matrix.imag)
+        # Convert the matrix with real values into imaginary values
+        corrected_imag = corrected_imag * complex(1j)
+        # Recombine the real and imaginary components
+        corrected_dense = corrected_real + corrected_imag
+
+        # Check if it's diagonal
+        row_indices = corrected_dense.nonzero()[0]
+        col_indices = corrected_dense.nonzero()[1]
+        # Check if the rows indices and columns indices are the same
+        # If they match, then matrix only contains elements along diagonal
+        bool_indices = row_indices == col_indices
+        is_diagonal = bool_indices.all()
+
+        first_element = corrected_dense[0][0]
+        # If the first element is a zero, then can't rescale matrix
+        # and definitely not diagonal
+        if (first_element == 0.0 + 0.0j):
+            return False
+
+        # The dimensions of the dense matrix should still
+        # be 2^nqubits if there are elements all along the
+        # the main diagonal
+        trace_of_corrected = (corrected_dense/first_element).trace()
+        expected_trace = pow(2, nqubits)
+        has_correct_trace = trace_of_corrected == expected_trace
+
+        # If only looking for identity matrices
+        # first element must be a 1
+        real_is_one = abs(first_element.real - 1.0) < eps
+        imag_is_zero = abs(first_element.imag) < eps
+        is_one = real_is_one and imag_is_zero
+        is_identity = is_one if identity_only else True
+        return bool(is_diagonal and has_correct_trace and is_identity)
+
+
+def is_scalar_nonsparse_matrix(circuit, nqubits, identity_only, eps=None):
+    """Checks if a given circuit, in matrix form, is equivalent to
+    a scalar value.
+
+    Parameters
+    ==========
+
+    circuit : Gate tuple
+        Sequence of quantum gates representing a quantum circuit
+    nqubits : int
+        Number of qubits in the circuit
+    identity_only : bool
+        Check for only identity matrices
+    eps : number
+        This argument is ignored. It is just for signature compatibility with
+        is_scalar_sparse_matrix.
+
+    Note: Used in situations when is_scalar_sparse_matrix has bugs
+    """
+
+    matrix = represent(Mul(*circuit), nqubits=nqubits)
+
+    # In some cases, represent returns a 1D scalar value in place
+    # of a multi-dimensional scalar matrix
+    if (isinstance(matrix, Number)):
+        return matrix == 1 if identity_only else True
+
+    # If represent returns a matrix, check if the matrix is diagonal
+    # and if every item along the diagonal is the same
+    else:
+        # Added up the diagonal elements
+        matrix_trace = matrix.trace()
+        # Divide the trace by the first element in the matrix
+        # if matrix is not required to be the identity matrix
+        adjusted_matrix_trace = (matrix_trace/matrix[0]
+                                 if not identity_only
+                                 else matrix_trace)
+
+        is_identity = equal_valued(matrix[0], 1) if identity_only else True
+
+        has_correct_trace = adjusted_matrix_trace == pow(2, nqubits)
+
+        # The matrix is scalar if it's diagonal and the adjusted trace
+        # value is equal to 2^nqubits
+        return bool(
+            matrix.is_diagonal() and has_correct_trace and is_identity)
+
+if np and scipy:
+    is_scalar_matrix = is_scalar_sparse_matrix
+else:
+    is_scalar_matrix = is_scalar_nonsparse_matrix
+
+
+def _get_min_qubits(a_gate):
+    if isinstance(a_gate, Pow):
+        return a_gate.base.min_qubits
+    else:
+        return a_gate.min_qubits
+
+
+def ll_op(left, right):
+    """Perform a LL operation.
+
+    A LL operation multiplies both left and right circuits
+    with the dagger of the left circuit's leftmost gate, and
+    the dagger is multiplied on the left side of both circuits.
+
+    If a LL is possible, it returns the new gate rule as a
+    2-tuple (LHS, RHS), where LHS is the left circuit and
+    and RHS is the right circuit of the new rule.
+    If a LL is not possible, None is returned.
+
+    Parameters
+    ==========
+
+    left : Gate tuple
+        The left circuit of a gate rule expression.
+    right : Gate tuple
+        The right circuit of a gate rule expression.
+
+    Examples
+    ========
+
+    Generate a new gate rule using a LL operation:
+
+    >>> from sympy.physics.quantum.identitysearch import ll_op
+    >>> from sympy.physics.quantum.gate import X, Y, Z
+    >>> x = X(0); y = Y(0); z = Z(0)
+    >>> ll_op((x, y, z), ())
+    ((Y(0), Z(0)), (X(0),))
+
+    >>> ll_op((y, z), (x,))
+    ((Z(0),), (Y(0), X(0)))
+    """
+
+    if (len(left) > 0):
+        ll_gate = left[0]
+        ll_gate_is_unitary = is_scalar_matrix(
+            (Dagger(ll_gate), ll_gate), _get_min_qubits(ll_gate), True)
+
+    if (len(left) > 0 and ll_gate_is_unitary):
+        # Get the new left side w/o the leftmost gate
+        new_left = left[1:len(left)]
+        # Add the leftmost gate to the left position on the right side
+        new_right = (Dagger(ll_gate),) + right
+        # Return the new gate rule
+        return (new_left, new_right)
+
+    return None
+
+
+def lr_op(left, right):
+    """Perform a LR operation.
+
+    A LR operation multiplies both left and right circuits
+    with the dagger of the left circuit's rightmost gate, and
+    the dagger is multiplied on the right side of both circuits.
+
+    If a LR is possible, it returns the new gate rule as a
+    2-tuple (LHS, RHS), where LHS is the left circuit and
+    and RHS is the right circuit of the new rule.
+    If a LR is not possible, None is returned.
+
+    Parameters
+    ==========
+
+    left : Gate tuple
+        The left circuit of a gate rule expression.
+    right : Gate tuple
+        The right circuit of a gate rule expression.
+
+    Examples
+    ========
+
+    Generate a new gate rule using a LR operation:
+
+    >>> from sympy.physics.quantum.identitysearch import lr_op
+    >>> from sympy.physics.quantum.gate import X, Y, Z
+    >>> x = X(0); y = Y(0); z = Z(0)
+    >>> lr_op((x, y, z), ())
+    ((X(0), Y(0)), (Z(0),))
+
+    >>> lr_op((x, y), (z,))
+    ((X(0),), (Z(0), Y(0)))
+    """
+
+    if (len(left) > 0):
+        lr_gate = left[len(left) - 1]
+        lr_gate_is_unitary = is_scalar_matrix(
+            (Dagger(lr_gate), lr_gate), _get_min_qubits(lr_gate), True)
+
+    if (len(left) > 0 and lr_gate_is_unitary):
+        # Get the new left side w/o the rightmost gate
+        new_left = left[0:len(left) - 1]
+        # Add the rightmost gate to the right position on the right side
+        new_right = right + (Dagger(lr_gate),)
+        # Return the new gate rule
+        return (new_left, new_right)
+
+    return None
+
+
+def rl_op(left, right):
+    """Perform a RL operation.
+
+    A RL operation multiplies both left and right circuits
+    with the dagger of the right circuit's leftmost gate, and
+    the dagger is multiplied on the left side of both circuits.
+
+    If a RL is possible, it returns the new gate rule as a
+    2-tuple (LHS, RHS), where LHS is the left circuit and
+    and RHS is the right circuit of the new rule.
+    If a RL is not possible, None is returned.
+
+    Parameters
+    ==========
+
+    left : Gate tuple
+        The left circuit of a gate rule expression.
+    right : Gate tuple
+        The right circuit of a gate rule expression.
+
+    Examples
+    ========
+
+    Generate a new gate rule using a RL operation:
+
+    >>> from sympy.physics.quantum.identitysearch import rl_op
+    >>> from sympy.physics.quantum.gate import X, Y, Z
+    >>> x = X(0); y = Y(0); z = Z(0)
+    >>> rl_op((x,), (y, z))
+    ((Y(0), X(0)), (Z(0),))
+
+    >>> rl_op((x, y), (z,))
+    ((Z(0), X(0), Y(0)), ())
+    """
+
+    if (len(right) > 0):
+        rl_gate = right[0]
+        rl_gate_is_unitary = is_scalar_matrix(
+            (Dagger(rl_gate), rl_gate), _get_min_qubits(rl_gate), True)
+
+    if (len(right) > 0 and rl_gate_is_unitary):
+        # Get the new right side w/o the leftmost gate
+        new_right = right[1:len(right)]
+        # Add the leftmost gate to the left position on the left side
+        new_left = (Dagger(rl_gate),) + left
+        # Return the new gate rule
+        return (new_left, new_right)
+
+    return None
+
+
+def rr_op(left, right):
+    """Perform a RR operation.
+
+    A RR operation multiplies both left and right circuits
+    with the dagger of the right circuit's rightmost gate, and
+    the dagger is multiplied on the right side of both circuits.
+
+    If a RR is possible, it returns the new gate rule as a
+    2-tuple (LHS, RHS), where LHS is the left circuit and
+    and RHS is the right circuit of the new rule.
+    If a RR is not possible, None is returned.
+
+    Parameters
+    ==========
+
+    left : Gate tuple
+        The left circuit of a gate rule expression.
+    right : Gate tuple
+        The right circuit of a gate rule expression.
+
+    Examples
+    ========
+
+    Generate a new gate rule using a RR operation:
+
+    >>> from sympy.physics.quantum.identitysearch import rr_op
+    >>> from sympy.physics.quantum.gate import X, Y, Z
+    >>> x = X(0); y = Y(0); z = Z(0)
+    >>> rr_op((x, y), (z,))
+    ((X(0), Y(0), Z(0)), ())
+
+    >>> rr_op((x,), (y, z))
+    ((X(0), Z(0)), (Y(0),))
+    """
+
+    if (len(right) > 0):
+        rr_gate = right[len(right) - 1]
+        rr_gate_is_unitary = is_scalar_matrix(
+            (Dagger(rr_gate), rr_gate), _get_min_qubits(rr_gate), True)
+
+    if (len(right) > 0 and rr_gate_is_unitary):
+        # Get the new right side w/o the rightmost gate
+        new_right = right[0:len(right) - 1]
+        # Add the rightmost gate to the right position on the right side
+        new_left = left + (Dagger(rr_gate),)
+        # Return the new gate rule
+        return (new_left, new_right)
+
+    return None
+
+
+def generate_gate_rules(gate_seq, return_as_muls=False):
+    """Returns a set of gate rules.  Each gate rules is represented
+    as a 2-tuple of tuples or Muls.  An empty tuple represents an arbitrary
+    scalar value.
+
+    This function uses the four operations (LL, LR, RL, RR)
+    to generate the gate rules.
+
+    A gate rule is an expression such as ABC = D or AB = CD, where
+    A, B, C, and D are gates.  Each value on either side of the
+    equal sign represents a circuit.  The four operations allow
+    one to find a set of equivalent circuits from a gate identity.
+    The letters denoting the operation tell the user what
+    activities to perform on each expression.  The first letter
+    indicates which side of the equal sign to focus on.  The
+    second letter indicates which gate to focus on given the
+    side.  Once this information is determined, the inverse
+    of the gate is multiplied on both circuits to create a new
+    gate rule.
+
+    For example, given the identity, ABCD = 1, a LL operation
+    means look at the left value and multiply both left sides by the
+    inverse of the leftmost gate A.  If A is Hermitian, the inverse
+    of A is still A.  The resulting new rule is BCD = A.
+
+    The following is a summary of the four operations.  Assume
+    that in the examples, all gates are Hermitian.
+
+        LL : left circuit, left multiply
+             ABCD = E -> AABCD = AE -> BCD = AE
+        LR : left circuit, right multiply
+             ABCD = E -> ABCDD = ED -> ABC = ED
+        RL : right circuit, left multiply
+             ABC = ED -> EABC = EED -> EABC = D
+        RR : right circuit, right multiply
+             AB = CD -> ABD = CDD -> ABD = C
+
+    The number of gate rules generated is n*(n+1), where n
+    is the number of gates in the sequence (unproven).
+
+    Parameters
+    ==========
+
+    gate_seq : Gate tuple, Mul, or Number
+        A variable length tuple or Mul of Gates whose product is equal to
+        a scalar matrix
+    return_as_muls : bool
+        True to return a set of Muls; False to return a set of tuples
+
+    Examples
+    ========
+
+    Find the gate rules of the current circuit using tuples:
+
+    >>> from sympy.physics.quantum.identitysearch import generate_gate_rules
+    >>> from sympy.physics.quantum.gate import X, Y, Z
+    >>> x = X(0); y = Y(0); z = Z(0)
+    >>> generate_gate_rules((x, x))
+    {((X(0),), (X(0),)), ((X(0), X(0)), ())}
+
+    >>> generate_gate_rules((x, y, z))
+    {((), (X(0), Z(0), Y(0))), ((), (Y(0), X(0), Z(0))),
+     ((), (Z(0), Y(0), X(0))), ((X(0),), (Z(0), Y(0))),
+     ((Y(0),), (X(0), Z(0))), ((Z(0),), (Y(0), X(0))),
+     ((X(0), Y(0)), (Z(0),)), ((Y(0), Z(0)), (X(0),)),
+     ((Z(0), X(0)), (Y(0),)), ((X(0), Y(0), Z(0)), ()),
+     ((Y(0), Z(0), X(0)), ()), ((Z(0), X(0), Y(0)), ())}
+
+    Find the gate rules of the current circuit using Muls:
+
+    >>> generate_gate_rules(x*x, return_as_muls=True)
+    {(1, 1)}
+
+    >>> generate_gate_rules(x*y*z, return_as_muls=True)
+    {(1, X(0)*Z(0)*Y(0)), (1, Y(0)*X(0)*Z(0)),
+     (1, Z(0)*Y(0)*X(0)), (X(0)*Y(0), Z(0)),
+     (Y(0)*Z(0), X(0)), (Z(0)*X(0), Y(0)),
+     (X(0)*Y(0)*Z(0), 1), (Y(0)*Z(0)*X(0), 1),
+     (Z(0)*X(0)*Y(0), 1), (X(0), Z(0)*Y(0)),
+     (Y(0), X(0)*Z(0)), (Z(0), Y(0)*X(0))}
+    """
+
+    if isinstance(gate_seq, Number):
+        if return_as_muls:
+            return {(S.One, S.One)}
+        else:
+            return {((), ())}
+
+    elif isinstance(gate_seq, Mul):
+        gate_seq = gate_seq.args
+
+    # Each item in queue is a 3-tuple:
+    #     i)   first item is the left side of an equality
+    #    ii)   second item is the right side of an equality
+    #   iii)   third item is the number of operations performed
+    # The argument, gate_seq, will start on the left side, and
+    # the right side will be empty, implying the presence of an
+    # identity.
+    queue = deque()
+    # A set of gate rules
+    rules = set()
+    # Maximum number of operations to perform
+    max_ops = len(gate_seq)
+
+    def process_new_rule(new_rule, ops):
+        if new_rule is not None:
+            new_left, new_right = new_rule
+
+            if new_rule not in rules and (new_right, new_left) not in rules:
+                rules.add(new_rule)
+            # If haven't reached the max limit on operations
+            if ops + 1 < max_ops:
+                queue.append(new_rule + (ops + 1,))
+
+    queue.append((gate_seq, (), 0))
+    rules.add((gate_seq, ()))
+
+    while len(queue) > 0:
+        left, right, ops = queue.popleft()
+
+        # Do a LL
+        new_rule = ll_op(left, right)
+        process_new_rule(new_rule, ops)
+        # Do a LR
+        new_rule = lr_op(left, right)
+        process_new_rule(new_rule, ops)
+        # Do a RL
+        new_rule = rl_op(left, right)
+        process_new_rule(new_rule, ops)
+        # Do a RR
+        new_rule = rr_op(left, right)
+        process_new_rule(new_rule, ops)
+
+    if return_as_muls:
+        # Convert each rule as tuples into a rule as muls
+        mul_rules = set()
+        for rule in rules:
+            left, right = rule
+            mul_rules.add((Mul(*left), Mul(*right)))
+
+        rules = mul_rules
+
+    return rules
+
+
+def generate_equivalent_ids(gate_seq, return_as_muls=False):
+    """Returns a set of equivalent gate identities.
+
+    A gate identity is a quantum circuit such that the product
+    of the gates in the circuit is equal to a scalar value.
+    For example, XYZ = i, where X, Y, Z are the Pauli gates and
+    i is the imaginary value, is considered a gate identity.
+
+    This function uses the four operations (LL, LR, RL, RR)
+    to generate the gate rules and, subsequently, to locate equivalent
+    gate identities.
+
+    Note that all equivalent identities are reachable in n operations
+    from the starting gate identity, where n is the number of gates
+    in the sequence.
+
+    The max number of gate identities is 2n, where n is the number
+    of gates in the sequence (unproven).
+
+    Parameters
+    ==========
+
+    gate_seq : Gate tuple, Mul, or Number
+        A variable length tuple or Mul of Gates whose product is equal to
+        a scalar matrix.
+    return_as_muls: bool
+        True to return as Muls; False to return as tuples
+
+    Examples
+    ========
+
+    Find equivalent gate identities from the current circuit with tuples:
+
+    >>> from sympy.physics.quantum.identitysearch import generate_equivalent_ids
+    >>> from sympy.physics.quantum.gate import X, Y, Z
+    >>> x = X(0); y = Y(0); z = Z(0)
+    >>> generate_equivalent_ids((x, x))
+    {(X(0), X(0))}
+
+    >>> generate_equivalent_ids((x, y, z))
+    {(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)),
+     (Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))}
+
+    Find equivalent gate identities from the current circuit with Muls:
+
+    >>> generate_equivalent_ids(x*x, return_as_muls=True)
+    {1}
+
+    >>> generate_equivalent_ids(x*y*z, return_as_muls=True)
+    {X(0)*Y(0)*Z(0), X(0)*Z(0)*Y(0), Y(0)*X(0)*Z(0),
+     Y(0)*Z(0)*X(0), Z(0)*X(0)*Y(0), Z(0)*Y(0)*X(0)}
+    """
+
+    if isinstance(gate_seq, Number):
+        return {S.One}
+    elif isinstance(gate_seq, Mul):
+        gate_seq = gate_seq.args
+
+    # Filter through the gate rules and keep the rules
+    # with an empty tuple either on the left or right side
+
+    # A set of equivalent gate identities
+    eq_ids = set()
+
+    gate_rules = generate_gate_rules(gate_seq)
+    for rule in gate_rules:
+        l, r = rule
+        if l == ():
+            eq_ids.add(r)
+        elif r == ():
+            eq_ids.add(l)
+
+    if return_as_muls:
+        convert_to_mul = lambda id_seq: Mul(*id_seq)
+        eq_ids = set(map(convert_to_mul, eq_ids))
+
+    return eq_ids
+
+
+class GateIdentity(Basic):
+    """Wrapper class for circuits that reduce to a scalar value.
+
+    A gate identity is a quantum circuit such that the product
+    of the gates in the circuit is equal to a scalar value.
+    For example, XYZ = i, where X, Y, Z are the Pauli gates and
+    i is the imaginary value, is considered a gate identity.
+
+    Parameters
+    ==========
+
+    args : Gate tuple
+        A variable length tuple of Gates that form an identity.
+
+    Examples
+    ========
+
+    Create a GateIdentity and look at its attributes:
+
+    >>> from sympy.physics.quantum.identitysearch import GateIdentity
+    >>> from sympy.physics.quantum.gate import X, Y, Z
+    >>> x = X(0); y = Y(0); z = Z(0)
+    >>> an_identity = GateIdentity(x, y, z)
+    >>> an_identity.circuit
+    X(0)*Y(0)*Z(0)
+
+    >>> an_identity.equivalent_ids
+    {(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)),
+     (Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))}
+    """
+
+    def __new__(cls, *args):
+        # args should be a tuple - a variable length argument list
+        obj = Basic.__new__(cls, *args)
+        obj._circuit = Mul(*args)
+        obj._rules = generate_gate_rules(args)
+        obj._eq_ids = generate_equivalent_ids(args)
+
+        return obj
+
+    @property
+    def circuit(self):
+        return self._circuit
+
+    @property
+    def gate_rules(self):
+        return self._rules
+
+    @property
+    def equivalent_ids(self):
+        return self._eq_ids
+
+    @property
+    def sequence(self):
+        return self.args
+
+    def __str__(self):
+        """Returns the string of gates in a tuple."""
+        return str(self.circuit)
+
+
+def is_degenerate(identity_set, gate_identity):
+    """Checks if a gate identity is a permutation of another identity.
+
+    Parameters
+    ==========
+
+    identity_set : set
+        A Python set with GateIdentity objects.
+    gate_identity : GateIdentity
+        The GateIdentity to check for existence in the set.
+
+    Examples
+    ========
+
+    Check if the identity is a permutation of another identity:
+
+    >>> from sympy.physics.quantum.identitysearch import (
+    ...     GateIdentity, is_degenerate)
+    >>> from sympy.physics.quantum.gate import X, Y, Z
+    >>> x = X(0); y = Y(0); z = Z(0)
+    >>> an_identity = GateIdentity(x, y, z)
+    >>> id_set = {an_identity}
+    >>> another_id = (y, z, x)
+    >>> is_degenerate(id_set, another_id)
+    True
+
+    >>> another_id = (x, x)
+    >>> is_degenerate(id_set, another_id)
+    False
+    """
+
+    # For now, just iteratively go through the set and check if the current
+    # gate_identity is a permutation of an identity in the set
+    for an_id in identity_set:
+        if (gate_identity in an_id.equivalent_ids):
+            return True
+    return False
+
+
+def is_reducible(circuit, nqubits, begin, end):
+    """Determines if a circuit is reducible by checking
+    if its subcircuits are scalar values.
+
+    Parameters
+    ==========
+
+    circuit : Gate tuple
+        A tuple of Gates representing a circuit.  The circuit to check
+        if a gate identity is contained in a subcircuit.
+    nqubits : int
+        The number of qubits the circuit operates on.
+    begin : int
+        The leftmost gate in the circuit to include in a subcircuit.
+    end : int
+        The rightmost gate in the circuit to include in a subcircuit.
+
+    Examples
+    ========
+
+    Check if the circuit can be reduced:
+
+    >>> from sympy.physics.quantum.identitysearch import is_reducible
+    >>> from sympy.physics.quantum.gate import X, Y, Z
+    >>> x = X(0); y = Y(0); z = Z(0)
+    >>> is_reducible((x, y, z), 1, 0, 3)
+    True
+
+    Check if an interval in the circuit can be reduced:
+
+    >>> is_reducible((x, y, z), 1, 1, 3)
+    False
+
+    >>> is_reducible((x, y, y), 1, 1, 3)
+    True
+    """
+
+    current_circuit = ()
+    # Start from the gate at "end" and go down to almost the gate at "begin"
+    for ndx in reversed(range(begin, end)):
+        next_gate = circuit[ndx]
+        current_circuit = (next_gate,) + current_circuit
+
+        # If a circuit as a matrix is equivalent to a scalar value
+        if (is_scalar_matrix(current_circuit, nqubits, False)):
+            return True
+
+    return False
+
+
+def bfs_identity_search(gate_list, nqubits, max_depth=None,
+       identity_only=False):
+    """Constructs a set of gate identities from the list of possible gates.
+
+    Performs a breadth first search over the space of gate identities.
+    This allows the finding of the shortest gate identities first.
+
+    Parameters
+    ==========
+
+    gate_list : list, Gate
+        A list of Gates from which to search for gate identities.
+    nqubits : int
+        The number of qubits the quantum circuit operates on.
+    max_depth : int
+        The longest quantum circuit to construct from gate_list.
+    identity_only : bool
+        True to search for gate identities that reduce to identity;
+        False to search for gate identities that reduce to a scalar.
+
+    Examples
+    ========
+
+    Find a list of gate identities:
+
+    >>> from sympy.physics.quantum.identitysearch import bfs_identity_search
+    >>> from sympy.physics.quantum.gate import X, Y, Z
+    >>> x = X(0); y = Y(0); z = Z(0)
+    >>> bfs_identity_search([x], 1, max_depth=2)
+    {GateIdentity(X(0), X(0))}
+
+    >>> bfs_identity_search([x, y, z], 1)
+    {GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)),
+     GateIdentity(Z(0), Z(0)), GateIdentity(X(0), Y(0), Z(0))}
+
+    Find a list of identities that only equal to 1:
+
+    >>> bfs_identity_search([x, y, z], 1, identity_only=True)
+    {GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)),
+     GateIdentity(Z(0), Z(0))}
+    """
+
+    if max_depth is None or max_depth <= 0:
+        max_depth = len(gate_list)
+
+    id_only = identity_only
+
+    # Start with an empty sequence (implicitly contains an IdentityGate)
+    queue = deque([()])
+
+    # Create an empty set of gate identities
+    ids = set()
+
+    # Begin searching for gate identities in given space.
+    while (len(queue) > 0):
+        current_circuit = queue.popleft()
+
+        for next_gate in gate_list:
+            new_circuit = current_circuit + (next_gate,)
+
+            # Determines if a (strict) subcircuit is a scalar matrix
+            circuit_reducible = is_reducible(new_circuit, nqubits,
+                                             1, len(new_circuit))
+
+            # In many cases when the matrix is a scalar value,
+            # the evaluated matrix will actually be an integer
+            if (is_scalar_matrix(new_circuit, nqubits, id_only) and
+                not is_degenerate(ids, new_circuit) and
+                    not circuit_reducible):
+                ids.add(GateIdentity(*new_circuit))
+
+            elif (len(new_circuit) < max_depth and
+                  not circuit_reducible):
+                queue.append(new_circuit)
+
+    return ids
+
+
+def random_identity_search(gate_list, numgates, nqubits):
+    """Randomly selects numgates from gate_list and checks if it is
+    a gate identity.
+
+    If the circuit is a gate identity, the circuit is returned;
+    Otherwise, None is returned.
+    """
+
+    gate_size = len(gate_list)
+    circuit = ()
+
+    for i in range(numgates):
+        next_gate = gate_list[randint(0, gate_size - 1)]
+        circuit = circuit + (next_gate,)
+
+    is_scalar = is_scalar_matrix(circuit, nqubits, False)
+
+    return circuit if is_scalar else None
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/innerproduct.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/innerproduct.py
new file mode 100644
index 0000000000000000000000000000000000000000..11fed882b6068a4df5a787ff90eee5392f97447a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/innerproduct.py
@@ -0,0 +1,138 @@
+"""Symbolic inner product."""
+
+from sympy.core.expr import Expr
+from sympy.core.kind import NumberKind
+from sympy.functions.elementary.complexes import conjugate
+from sympy.printing.pretty.stringpict import prettyForm
+from sympy.physics.quantum.dagger import Dagger
+
+
+__all__ = [
+    'InnerProduct'
+]
+
+
+# InnerProduct is not an QExpr because it is really just a regular commutative
+# number. We have gone back and forth about this, but we gain a lot by having
+# it subclass Expr. The main challenges were getting Dagger to work
+# (we use _eval_conjugate) and represent (we can use atoms and subs). Having
+# it be an Expr, mean that there are no commutative QExpr subclasses,
+# which simplifies the design of everything.
+
+class InnerProduct(Expr):
+    """An unevaluated inner product between a Bra and a Ket [1].
+
+    Parameters
+    ==========
+
+    bra : BraBase or subclass
+        The bra on the left side of the inner product.
+    ket : KetBase or subclass
+        The ket on the right side of the inner product.
+
+    Examples
+    ========
+
+    Create an InnerProduct and check its properties:
+
+        >>> from sympy.physics.quantum import Bra, Ket
+        >>> b = Bra('b')
+        >>> k = Ket('k')
+        >>> ip = b*k
+        >>> ip
+        
+        >>> ip.bra
+        >> ip.ket
+        |k>
+
+    In quantum expressions, inner products will be automatically
+    identified and created::
+
+        >>> b*k
+        
+
+    In more complex expressions, where there is ambiguity in whether inner or
+    outer products should be created, inner products have high priority::
+
+        >>> k*b*k*b
+        *|k> moved to the left of the expression
+    because inner products are commutative complex numbers.
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Inner_product
+    """
+
+    kind = NumberKind
+
+    is_complex = True
+
+    def __new__(cls, bra, ket):
+        # Keep the import of BraBase and KetBase here to avoid problems
+        # with circular imports.
+        from sympy.physics.quantum.state import KetBase, BraBase
+        if not isinstance(ket, KetBase):
+            raise TypeError('KetBase subclass expected, got: %r' % ket)
+        if not isinstance(bra, BraBase):
+            raise TypeError('BraBase subclass expected, got: %r' % ket)
+        obj = Expr.__new__(cls, bra, ket)
+        return obj
+
+    @property
+    def bra(self):
+        return self.args[0]
+
+    @property
+    def ket(self):
+        return self.args[1]
+
+    def _eval_conjugate(self):
+        return InnerProduct(Dagger(self.ket), Dagger(self.bra))
+
+    def _sympyrepr(self, printer, *args):
+        return '%s(%s,%s)' % (self.__class__.__name__,
+            printer._print(self.bra, *args), printer._print(self.ket, *args))
+
+    def _sympystr(self, printer, *args):
+        sbra = printer._print(self.bra)
+        sket = printer._print(self.ket)
+        return '%s|%s' % (sbra[:-1], sket[1:])
+
+    def _pretty(self, printer, *args):
+        # Print state contents
+        bra = self.bra._print_contents_pretty(printer, *args)
+        ket = self.ket._print_contents_pretty(printer, *args)
+        # Print brackets
+        height = max(bra.height(), ket.height())
+        use_unicode = printer._use_unicode
+        lbracket, _ = self.bra._pretty_brackets(height, use_unicode)
+        cbracket, rbracket = self.ket._pretty_brackets(height, use_unicode)
+        # Build innerproduct
+        pform = prettyForm(*bra.left(lbracket))
+        pform = prettyForm(*pform.right(cbracket))
+        pform = prettyForm(*pform.right(ket))
+        pform = prettyForm(*pform.right(rbracket))
+        return pform
+
+    def _latex(self, printer, *args):
+        bra_label = self.bra._print_contents_latex(printer, *args)
+        ket = printer._print(self.ket, *args)
+        return r'\left\langle %s \right. %s' % (bra_label, ket)
+
+    def doit(self, **hints):
+        try:
+            r = self.ket._eval_innerproduct(self.bra, **hints)
+        except NotImplementedError:
+            try:
+                r = conjugate(
+                    self.bra.dual._eval_innerproduct(self.ket.dual, **hints)
+                )
+            except NotImplementedError:
+                r = None
+        if r is not None:
+            return r
+        return self
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/kind.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/kind.py
new file mode 100644
index 0000000000000000000000000000000000000000..14b5bd2c7b0c87f49dc7e6dc9c1b492fbfad6d56
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/kind.py
@@ -0,0 +1,103 @@
+"""Kinds for Operators, Bras, and Kets.
+
+This module defines kinds for operators, bras, and kets. These are useful
+in various places in ``sympy.physics.quantum`` as you often want to know
+what the kind is of a compound expression. For example, if you multiply
+an operator, bra, or ket by a number, you get back another operator, bra,
+or ket - even though if you did an ``isinstance`` check you would find that
+you have a ``Mul`` instead. The kind system is meant to give you a quick
+way of determining how a compound expression behaves in terms of lower
+level kinds.
+
+The resolution calculation of kinds for compound expressions can be found
+either in container classes or in functions that are registered with
+kind dispatchers.
+"""
+
+from sympy.core.mul import Mul
+from sympy.core.kind import Kind, _NumberKind
+
+
+__all__ = [
+    '_KetKind',
+    'KetKind',
+    '_BraKind',
+    'BraKind',
+    '_OperatorKind',
+    'OperatorKind',
+]
+
+
+class _KetKind(Kind):
+    """A kind for quantum kets."""
+
+    def __new__(cls):
+        obj = super().__new__(cls)
+        return obj
+
+    def __repr__(self):
+        return "KetKind"
+
+# Create an instance as many situations need this.
+KetKind = _KetKind()
+
+
+class _BraKind(Kind):
+    """A kind for quantum bras."""
+
+    def __new__(cls):
+        obj = super().__new__(cls)
+        return obj
+
+    def __repr__(self):
+        return "BraKind"
+
+# Create an instance as many situations need this.
+BraKind = _BraKind()
+
+
+from sympy.core.kind import Kind
+
+class _OperatorKind(Kind):
+    """A kind for quantum operators."""
+
+    def __new__(cls):
+        obj = super().__new__(cls)
+        return obj
+
+    def __repr__(self):
+        return "OperatorKind"
+
+# Create an instance as many situations need this.
+OperatorKind = _OperatorKind()
+
+
+#-----------------------------------------------------------------------------
+# Kind resolution.
+#-----------------------------------------------------------------------------
+
+# Note: We can't currently add kind dispatchers for the following combinations
+#       as the Mul._kind_dispatcher is set to commutative and will also
+#       register the opposite order, which isn't correct for these pairs:
+#
+# 1. (_OperatorKind, _KetKind)
+# 2. (_BraKind, _OperatorKind)
+# 3. (_BraKind, _KetKind)
+
+
+@Mul._kind_dispatcher.register(_NumberKind, _KetKind)
+def _mul_number_ket_kind(lhs, rhs):
+    """Perform the kind calculation of NumberKind*KetKind -> KetKind."""
+    return KetKind
+
+
+@Mul._kind_dispatcher.register(_NumberKind, _BraKind)
+def _mul_number_bra_kind(lhs, rhs):
+    """Perform the kind calculation of NumberKind*BraKind -> BraKind."""
+    return BraKind
+
+
+@Mul._kind_dispatcher.register(_NumberKind, _OperatorKind)
+def _mul_operator_kind(lhs, rhs):
+    """Perform the kind calculation of NumberKind*OperatorKind -> OperatorKind."""
+    return OperatorKind
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/matrixcache.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/matrixcache.py
new file mode 100644
index 0000000000000000000000000000000000000000..3cfab3c3490c909966d8a56af395ffa578724ea7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/matrixcache.py
@@ -0,0 +1,103 @@
+"""A cache for storing small matrices in multiple formats."""
+
+from sympy.core.numbers import (I, Rational, pi)
+from sympy.core.power import Pow
+from sympy.functions.elementary.exponential import exp
+from sympy.matrices.dense import Matrix
+
+from sympy.physics.quantum.matrixutils import (
+    to_sympy, to_numpy, to_scipy_sparse
+)
+
+
+class MatrixCache:
+    """A cache for small matrices in different formats.
+
+    This class takes small matrices in the standard ``sympy.Matrix`` format,
+    and then converts these to both ``numpy.matrix`` and
+    ``scipy.sparse.csr_matrix`` matrices. These matrices are then stored for
+    future recovery.
+    """
+
+    def __init__(self, dtype='complex'):
+        self._cache = {}
+        self.dtype = dtype
+
+    def cache_matrix(self, name, m):
+        """Cache a matrix by its name.
+
+        Parameters
+        ----------
+        name : str
+            A descriptive name for the matrix, like "identity2".
+        m : list of lists
+            The raw matrix data as a SymPy Matrix.
+        """
+        try:
+            self._sympy_matrix(name, m)
+        except ImportError:
+            pass
+        try:
+            self._numpy_matrix(name, m)
+        except ImportError:
+            pass
+        try:
+            self._scipy_sparse_matrix(name, m)
+        except ImportError:
+            pass
+
+    def get_matrix(self, name, format):
+        """Get a cached matrix by name and format.
+
+        Parameters
+        ----------
+        name : str
+            A descriptive name for the matrix, like "identity2".
+        format : str
+            The format desired ('sympy', 'numpy', 'scipy.sparse')
+        """
+        m = self._cache.get((name, format))
+        if m is not None:
+            return m
+        raise NotImplementedError(
+            'Matrix with name %s and format %s is not available.' %
+            (name, format)
+        )
+
+    def _store_matrix(self, name, format, m):
+        self._cache[(name, format)] = m
+
+    def _sympy_matrix(self, name, m):
+        self._store_matrix(name, 'sympy', to_sympy(m))
+
+    def _numpy_matrix(self, name, m):
+        m = to_numpy(m, dtype=self.dtype)
+        self._store_matrix(name, 'numpy', m)
+
+    def _scipy_sparse_matrix(self, name, m):
+        # TODO: explore different sparse formats. But sparse.kron will use
+        # coo in most cases, so we use that here.
+        m = to_scipy_sparse(m, dtype=self.dtype)
+        self._store_matrix(name, 'scipy.sparse', m)
+
+
+sqrt2_inv = Pow(2, Rational(-1, 2), evaluate=False)
+
+# Save the common matrices that we will need
+matrix_cache = MatrixCache()
+matrix_cache.cache_matrix('eye2', Matrix([[1, 0], [0, 1]]))
+matrix_cache.cache_matrix('op11', Matrix([[0, 0], [0, 1]]))  # |1><1|
+matrix_cache.cache_matrix('op00', Matrix([[1, 0], [0, 0]]))  # |0><0|
+matrix_cache.cache_matrix('op10', Matrix([[0, 0], [1, 0]]))  # |1><0|
+matrix_cache.cache_matrix('op01', Matrix([[0, 1], [0, 0]]))  # |0><1|
+matrix_cache.cache_matrix('X', Matrix([[0, 1], [1, 0]]))
+matrix_cache.cache_matrix('Y', Matrix([[0, -I], [I, 0]]))
+matrix_cache.cache_matrix('Z', Matrix([[1, 0], [0, -1]]))
+matrix_cache.cache_matrix('S', Matrix([[1, 0], [0, I]]))
+matrix_cache.cache_matrix('T', Matrix([[1, 0], [0, exp(I*pi/4)]]))
+matrix_cache.cache_matrix('H', sqrt2_inv*Matrix([[1, 1], [1, -1]]))
+matrix_cache.cache_matrix('Hsqrt2', Matrix([[1, 1], [1, -1]]))
+matrix_cache.cache_matrix(
+    'SWAP', Matrix([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]))
+matrix_cache.cache_matrix('ZX', sqrt2_inv*Matrix([[1, 1], [1, -1]]))
+matrix_cache.cache_matrix('ZY', Matrix([[I, 0], [0, -I]]))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/matrixutils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/matrixutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..1082ea326b68256dac96030e36d72efa664495d2
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/matrixutils.py
@@ -0,0 +1,272 @@
+"""Utilities to deal with sympy.Matrix, numpy and scipy.sparse."""
+
+from sympy.core.expr import Expr
+from sympy.core.numbers import I
+from sympy.core.singleton import S
+from sympy.matrices.matrixbase import MatrixBase
+from sympy.matrices import eye, zeros
+from sympy.external import import_module
+
+__all__ = [
+    'numpy_ndarray',
+    'scipy_sparse_matrix',
+    'sympy_to_numpy',
+    'sympy_to_scipy_sparse',
+    'numpy_to_sympy',
+    'scipy_sparse_to_sympy',
+    'flatten_scalar',
+    'matrix_dagger',
+    'to_sympy',
+    'to_numpy',
+    'to_scipy_sparse',
+    'matrix_tensor_product',
+    'matrix_zeros'
+]
+
+# Conditionally define the base classes for numpy and scipy.sparse arrays
+# for use in isinstance tests.
+
+np = import_module('numpy')
+if not np:
+    class numpy_ndarray:
+        pass
+else:
+    numpy_ndarray = np.ndarray  # type: ignore
+
+scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
+if not scipy:
+    class scipy_sparse_matrix:
+        pass
+    sparse = None
+else:
+    sparse = scipy.sparse
+    scipy_sparse_matrix = sparse.spmatrix # type: ignore
+
+
+def sympy_to_numpy(m, **options):
+    """Convert a SymPy Matrix/complex number to a numpy matrix or scalar."""
+    if not np:
+        raise ImportError
+    dtype = options.get('dtype', 'complex')
+    if isinstance(m, MatrixBase):
+        return np.array(m.tolist(), dtype=dtype)
+    elif isinstance(m, Expr):
+        if m.is_Number or m.is_NumberSymbol or m == I:
+            return complex(m)
+    raise TypeError('Expected MatrixBase or complex scalar, got: %r' % m)
+
+
+def sympy_to_scipy_sparse(m, **options):
+    """Convert a SymPy Matrix/complex number to a numpy matrix or scalar."""
+    if not np or not sparse:
+        raise ImportError
+    dtype = options.get('dtype', 'complex')
+    if isinstance(m, MatrixBase):
+        return sparse.csr_matrix(np.array(m.tolist(), dtype=dtype))
+    elif isinstance(m, Expr):
+        if m.is_Number or m.is_NumberSymbol or m == I:
+            return complex(m)
+    raise TypeError('Expected MatrixBase or complex scalar, got: %r' % m)
+
+
+def scipy_sparse_to_sympy(m, **options):
+    """Convert a scipy.sparse matrix to a SymPy matrix."""
+    return MatrixBase(m.todense())
+
+
+def numpy_to_sympy(m, **options):
+    """Convert a numpy matrix to a SymPy matrix."""
+    return MatrixBase(m)
+
+
+def to_sympy(m, **options):
+    """Convert a numpy/scipy.sparse matrix to a SymPy matrix."""
+    if isinstance(m, MatrixBase):
+        return m
+    elif isinstance(m, numpy_ndarray):
+        return numpy_to_sympy(m)
+    elif isinstance(m, scipy_sparse_matrix):
+        return scipy_sparse_to_sympy(m)
+    elif isinstance(m, Expr):
+        return m
+    raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m)
+
+
+def to_numpy(m, **options):
+    """Convert a sympy/scipy.sparse matrix to a numpy matrix."""
+    dtype = options.get('dtype', 'complex')
+    if isinstance(m, (MatrixBase, Expr)):
+        return sympy_to_numpy(m, dtype=dtype)
+    elif isinstance(m, numpy_ndarray):
+        return m
+    elif isinstance(m, scipy_sparse_matrix):
+        return m.todense()
+    raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m)
+
+
+def to_scipy_sparse(m, **options):
+    """Convert a sympy/numpy matrix to a scipy.sparse matrix."""
+    dtype = options.get('dtype', 'complex')
+    if isinstance(m, (MatrixBase, Expr)):
+        return sympy_to_scipy_sparse(m, dtype=dtype)
+    elif isinstance(m, numpy_ndarray):
+        if not sparse:
+            raise ImportError
+        return sparse.csr_matrix(m)
+    elif isinstance(m, scipy_sparse_matrix):
+        return m
+    raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m)
+
+
+def flatten_scalar(e):
+    """Flatten a 1x1 matrix to a scalar, return larger matrices unchanged."""
+    if isinstance(e, MatrixBase):
+        if e.shape == (1, 1):
+            e = e[0]
+    if isinstance(e, (numpy_ndarray, scipy_sparse_matrix)):
+        if e.shape == (1, 1):
+            e = complex(e[0, 0])
+    return e
+
+
+def matrix_dagger(e):
+    """Return the dagger of a sympy/numpy/scipy.sparse matrix."""
+    if isinstance(e, MatrixBase):
+        return e.H
+    elif isinstance(e, (numpy_ndarray, scipy_sparse_matrix)):
+        return e.conjugate().transpose()
+    raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % e)
+
+
+# TODO: Move this into sympy.matrices.
+def _sympy_tensor_product(*matrices):
+    """Compute the kronecker product of a sequence of SymPy Matrices.
+    """
+    from sympy.matrices.expressions.kronecker import matrix_kronecker_product
+
+    return matrix_kronecker_product(*matrices)
+
+
+def _numpy_tensor_product(*product):
+    """numpy version of tensor product of multiple arguments."""
+    if not np:
+        raise ImportError
+    answer = product[0]
+    for item in product[1:]:
+        answer = np.kron(answer, item)
+    return answer
+
+
+def _scipy_sparse_tensor_product(*product):
+    """scipy.sparse version of tensor product of multiple arguments."""
+    if not sparse:
+        raise ImportError
+    answer = product[0]
+    for item in product[1:]:
+        answer = sparse.kron(answer, item)
+    # The final matrices will just be multiplied, so csr is a good final
+    # sparse format.
+    return sparse.csr_matrix(answer)
+
+
+def matrix_tensor_product(*product):
+    """Compute the matrix tensor product of sympy/numpy/scipy.sparse matrices."""
+    if isinstance(product[0], MatrixBase):
+        return _sympy_tensor_product(*product)
+    elif isinstance(product[0], numpy_ndarray):
+        return _numpy_tensor_product(*product)
+    elif isinstance(product[0], scipy_sparse_matrix):
+        return _scipy_sparse_tensor_product(*product)
+
+
+def _numpy_eye(n):
+    """numpy version of complex eye."""
+    if not np:
+        raise ImportError
+    return np.array(np.eye(n, dtype='complex'))
+
+
+def _scipy_sparse_eye(n):
+    """scipy.sparse version of complex eye."""
+    if not sparse:
+        raise ImportError
+    return sparse.eye(n, n, dtype='complex')
+
+
+def matrix_eye(n, **options):
+    """Get the version of eye and tensor_product for a given format."""
+    format = options.get('format', 'sympy')
+    if format == 'sympy':
+        return eye(n)
+    elif format == 'numpy':
+        return _numpy_eye(n)
+    elif format == 'scipy.sparse':
+        return _scipy_sparse_eye(n)
+    raise NotImplementedError('Invalid format: %r' % format)
+
+
+def _numpy_zeros(m, n, **options):
+    """numpy version of zeros."""
+    dtype = options.get('dtype', 'float64')
+    if not np:
+        raise ImportError
+    return np.zeros((m, n), dtype=dtype)
+
+
+def _scipy_sparse_zeros(m, n, **options):
+    """scipy.sparse version of zeros."""
+    spmatrix = options.get('spmatrix', 'csr')
+    dtype = options.get('dtype', 'float64')
+    if not sparse:
+        raise ImportError
+    if spmatrix == 'lil':
+        return sparse.lil_matrix((m, n), dtype=dtype)
+    elif spmatrix == 'csr':
+        return sparse.csr_matrix((m, n), dtype=dtype)
+
+
+def matrix_zeros(m, n, **options):
+    """"Get a zeros matrix for a given format."""
+    format = options.get('format', 'sympy')
+    if format == 'sympy':
+        return zeros(m, n)
+    elif format == 'numpy':
+        return _numpy_zeros(m, n, **options)
+    elif format == 'scipy.sparse':
+        return _scipy_sparse_zeros(m, n, **options)
+    raise NotImplementedError('Invaild format: %r' % format)
+
+
+def _numpy_matrix_to_zero(e):
+    """Convert a numpy zero matrix to the zero scalar."""
+    if not np:
+        raise ImportError
+    test = np.zeros_like(e)
+    if np.allclose(e, test):
+        return 0.0
+    else:
+        return e
+
+
+def _scipy_sparse_matrix_to_zero(e):
+    """Convert a scipy.sparse zero matrix to the zero scalar."""
+    if not np:
+        raise ImportError
+    edense = e.todense()
+    test = np.zeros_like(edense)
+    if np.allclose(edense, test):
+        return 0.0
+    else:
+        return e
+
+
+def matrix_to_zero(e):
+    """Convert a zero matrix to the scalar zero."""
+    if isinstance(e, MatrixBase):
+        if zeros(*e.shape) == e:
+            e = S.Zero
+    elif isinstance(e, numpy_ndarray):
+        e = _numpy_matrix_to_zero(e)
+    elif isinstance(e, scipy_sparse_matrix):
+        e = _scipy_sparse_matrix_to_zero(e)
+    return e
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/operator.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/operator.py
new file mode 100644
index 0000000000000000000000000000000000000000..b44617e15c19e8b30b76f011630430787233e724
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/operator.py
@@ -0,0 +1,653 @@
+"""Quantum mechanical operators.
+
+TODO:
+
+* Fix early 0 in apply_operators.
+* Debug and test apply_operators.
+* Get cse working with classes in this file.
+* Doctests and documentation of special methods for InnerProduct, Commutator,
+  AntiCommutator, represent, apply_operators.
+"""
+from typing import Optional
+
+from sympy.core.add import Add
+from sympy.core.expr import Expr
+from sympy.core.function import (Derivative, expand)
+from sympy.core.mul import Mul
+from sympy.core.numbers import oo
+from sympy.core.singleton import S
+from sympy.printing.pretty.stringpict import prettyForm
+from sympy.physics.quantum.dagger import Dagger
+from sympy.physics.quantum.kind import OperatorKind
+from sympy.physics.quantum.qexpr import QExpr, dispatch_method
+from sympy.matrices import eye
+from sympy.utilities.exceptions import sympy_deprecation_warning
+
+
+
+__all__ = [
+    'Operator',
+    'HermitianOperator',
+    'UnitaryOperator',
+    'IdentityOperator',
+    'OuterProduct',
+    'DifferentialOperator'
+]
+
+#-----------------------------------------------------------------------------
+# Operators and outer products
+#-----------------------------------------------------------------------------
+
+
+class Operator(QExpr):
+    """Base class for non-commuting quantum operators.
+
+    An operator maps between quantum states [1]_. In quantum mechanics,
+    observables (including, but not limited to, measured physical values) are
+    represented as Hermitian operators [2]_.
+
+    Parameters
+    ==========
+
+    args : tuple
+        The list of numbers or parameters that uniquely specify the
+        operator. For time-dependent operators, this will include the time.
+
+    Examples
+    ========
+
+    Create an operator and examine its attributes::
+
+        >>> from sympy.physics.quantum import Operator
+        >>> from sympy import I
+        >>> A = Operator('A')
+        >>> A
+        A
+        >>> A.hilbert_space
+        H
+        >>> A.label
+        (A,)
+        >>> A.is_commutative
+        False
+
+    Create another operator and do some arithmetic operations::
+
+        >>> B = Operator('B')
+        >>> C = 2*A*A + I*B
+        >>> C
+        2*A**2 + I*B
+
+    Operators do not commute::
+
+        >>> A.is_commutative
+        False
+        >>> B.is_commutative
+        False
+        >>> A*B == B*A
+        False
+
+    Polymonials of operators respect the commutation properties::
+
+        >>> e = (A+B)**3
+        >>> e.expand()
+        A*B*A + A*B**2 + A**2*B + A**3 + B*A*B + B*A**2 + B**2*A + B**3
+
+    Operator inverses are handle symbolically::
+
+        >>> A.inv()
+        A**(-1)
+        >>> A*A.inv()
+        1
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Operator_%28physics%29
+    .. [2] https://en.wikipedia.org/wiki/Observable
+    """
+    is_hermitian: Optional[bool] = None
+    is_unitary: Optional[bool] = None
+    @classmethod
+    def default_args(self):
+        return ("O",)
+
+    kind = OperatorKind
+
+    #-------------------------------------------------------------------------
+    # Printing
+    #-------------------------------------------------------------------------
+
+    _label_separator = ','
+
+    def _print_operator_name(self, printer, *args):
+        return self.__class__.__name__
+
+    _print_operator_name_latex = _print_operator_name
+
+    def _print_operator_name_pretty(self, printer, *args):
+        return prettyForm(self.__class__.__name__)
+
+    def _print_contents(self, printer, *args):
+        if len(self.label) == 1:
+            return self._print_label(printer, *args)
+        else:
+            return '%s(%s)' % (
+                self._print_operator_name(printer, *args),
+                self._print_label(printer, *args)
+            )
+
+    def _print_contents_pretty(self, printer, *args):
+        if len(self.label) == 1:
+            return self._print_label_pretty(printer, *args)
+        else:
+            pform = self._print_operator_name_pretty(printer, *args)
+            label_pform = self._print_label_pretty(printer, *args)
+            label_pform = prettyForm(
+                *label_pform.parens(left='(', right=')')
+            )
+            pform = prettyForm(*pform.right(label_pform))
+            return pform
+
+    def _print_contents_latex(self, printer, *args):
+        if len(self.label) == 1:
+            return self._print_label_latex(printer, *args)
+        else:
+            return r'%s\left(%s\right)' % (
+                self._print_operator_name_latex(printer, *args),
+                self._print_label_latex(printer, *args)
+            )
+
+    #-------------------------------------------------------------------------
+    # _eval_* methods
+    #-------------------------------------------------------------------------
+
+    def _eval_commutator(self, other, **options):
+        """Evaluate [self, other] if known, return None if not known."""
+        return dispatch_method(self, '_eval_commutator', other, **options)
+
+    def _eval_anticommutator(self, other, **options):
+        """Evaluate [self, other] if known."""
+        return dispatch_method(self, '_eval_anticommutator', other, **options)
+
+    #-------------------------------------------------------------------------
+    # Operator application
+    #-------------------------------------------------------------------------
+
+    def _apply_operator(self, ket, **options):
+        return dispatch_method(self, '_apply_operator', ket, **options)
+
+    def _apply_from_right_to(self, bra, **options):
+        return None
+
+    def matrix_element(self, *args):
+        raise NotImplementedError('matrix_elements is not defined')
+
+    def inverse(self):
+        return self._eval_inverse()
+
+    inv = inverse
+
+    def _eval_inverse(self):
+        return self**(-1)
+
+
+class HermitianOperator(Operator):
+    """A Hermitian operator that satisfies H == Dagger(H).
+
+    Parameters
+    ==========
+
+    args : tuple
+        The list of numbers or parameters that uniquely specify the
+        operator. For time-dependent operators, this will include the time.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum import Dagger, HermitianOperator
+    >>> H = HermitianOperator('H')
+    >>> Dagger(H)
+    H
+    """
+
+    is_hermitian = True
+
+    def _eval_inverse(self):
+        if isinstance(self, UnitaryOperator):
+            return self
+        else:
+            return Operator._eval_inverse(self)
+
+    def _eval_power(self, exp):
+        if isinstance(self, UnitaryOperator):
+            # so all eigenvalues of self are 1 or -1
+            if exp.is_even:
+                from sympy.core.singleton import S
+                return S.One # is identity, see Issue 24153.
+            elif exp.is_odd:
+                return self
+        # No simplification in all other cases
+        return Operator._eval_power(self, exp)
+
+
+class UnitaryOperator(Operator):
+    """A unitary operator that satisfies U*Dagger(U) == 1.
+
+    Parameters
+    ==========
+
+    args : tuple
+        The list of numbers or parameters that uniquely specify the
+        operator. For time-dependent operators, this will include the time.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum import Dagger, UnitaryOperator
+    >>> U = UnitaryOperator('U')
+    >>> U*Dagger(U)
+    1
+    """
+    is_unitary = True
+    def _eval_adjoint(self):
+        return self._eval_inverse()
+
+
+class IdentityOperator(Operator):
+    """An identity operator I that satisfies op * I == I * op == op for any
+    operator op.
+
+    .. deprecated:: 1.14.
+        Use the scalar S.One instead as the multiplicative identity for
+        operators and states.
+
+    Parameters
+    ==========
+
+    N : Integer
+        Optional parameter that specifies the dimension of the Hilbert space
+        of operator. This is used when generating a matrix representation.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum import IdentityOperator
+    >>> IdentityOperator() # doctest: +SKIP
+    I
+    """
+    is_hermitian = True
+    is_unitary = True
+    @property
+    def dimension(self):
+        return self.N
+
+    @classmethod
+    def default_args(self):
+        return (oo,)
+
+    def __init__(self, *args, **hints):
+        sympy_deprecation_warning(
+            """
+            IdentityOperator has been deprecated. In the future, please use
+            S.One as the identity for quantum operators and states.
+            """,
+            deprecated_since_version="1.14",
+            active_deprecations_target='deprecated-operator-identity',
+        )
+        if not len(args) in (0, 1):
+            raise ValueError('0 or 1 parameters expected, got %s' % args)
+
+        self.N = args[0] if (len(args) == 1 and args[0]) else oo
+
+    def _eval_commutator(self, other, **hints):
+        return S.Zero
+
+    def _eval_anticommutator(self, other, **hints):
+        return 2 * other
+
+    def _eval_inverse(self):
+        return self
+
+    def _eval_adjoint(self):
+        return self
+
+    def _apply_operator(self, ket, **options):
+        return ket
+
+    def _apply_from_right_to(self, bra, **options):
+        return bra
+
+    def _eval_power(self, exp):
+        return self
+
+    def _print_contents(self, printer, *args):
+        return 'I'
+
+    def _print_contents_pretty(self, printer, *args):
+        return prettyForm('I')
+
+    def _print_contents_latex(self, printer, *args):
+        return r'{\mathcal{I}}'
+
+    def _represent_default_basis(self, **options):
+        if not self.N or self.N == oo:
+            raise NotImplementedError('Cannot represent infinite dimensional' +
+                                      ' identity operator as a matrix')
+
+        format = options.get('format', 'sympy')
+        if format != 'sympy':
+            raise NotImplementedError('Representation in format ' +
+                                      '%s not implemented.' % format)
+
+        return eye(self.N)
+
+
+class OuterProduct(Operator):
+    """An unevaluated outer product between a ket and bra.
+
+    This constructs an outer product between any subclass of ``KetBase`` and
+    ``BraBase`` as ``|a>>> from sympy.physics.quantum import Ket, Bra, OuterProduct, Dagger
+
+        >>> k = Ket('k')
+        >>> b = Bra('b')
+        >>> op = OuterProduct(k, b)
+        >>> op
+        |k>>> op.hilbert_space
+        H
+        >>> op.ket
+        |k>
+        >>> op.bra
+        >> Dagger(op)
+        |b>>> k*b
+        |k>>> b*k*b
+        *>> from sympy import Derivative, Function, Symbol
+    >>> from sympy.physics.quantum.operator import DifferentialOperator
+    >>> from sympy.physics.quantum.state import Wavefunction
+    >>> from sympy.physics.quantum.qapply import qapply
+    >>> f = Function('f')
+    >>> x = Symbol('x')
+    >>> d = DifferentialOperator(1/x*Derivative(f(x), x), f(x))
+    >>> w = Wavefunction(x**2, x)
+    >>> d.function
+    f(x)
+    >>> d.variables
+    (x,)
+    >>> qapply(d*w)
+    Wavefunction(2, x)
+
+    """
+
+    @property
+    def variables(self):
+        """
+        Returns the variables with which the function in the specified
+        arbitrary expression is evaluated
+
+        Examples
+        ========
+
+        >>> from sympy.physics.quantum.operator import DifferentialOperator
+        >>> from sympy import Symbol, Function, Derivative
+        >>> x = Symbol('x')
+        >>> f = Function('f')
+        >>> d = DifferentialOperator(1/x*Derivative(f(x), x), f(x))
+        >>> d.variables
+        (x,)
+        >>> y = Symbol('y')
+        >>> d = DifferentialOperator(Derivative(f(x, y), x) +
+        ...                          Derivative(f(x, y), y), f(x, y))
+        >>> d.variables
+        (x, y)
+        """
+
+        return self.args[-1].args
+
+    @property
+    def function(self):
+        """
+        Returns the function which is to be replaced with the Wavefunction
+
+        Examples
+        ========
+
+        >>> from sympy.physics.quantum.operator import DifferentialOperator
+        >>> from sympy import Function, Symbol, Derivative
+        >>> x = Symbol('x')
+        >>> f = Function('f')
+        >>> d = DifferentialOperator(Derivative(f(x), x), f(x))
+        >>> d.function
+        f(x)
+        >>> y = Symbol('y')
+        >>> d = DifferentialOperator(Derivative(f(x, y), x) +
+        ...                          Derivative(f(x, y), y), f(x, y))
+        >>> d.function
+        f(x, y)
+        """
+
+        return self.args[-1]
+
+    @property
+    def expr(self):
+        """
+        Returns the arbitrary expression which is to have the Wavefunction
+        substituted into it
+
+        Examples
+        ========
+
+        >>> from sympy.physics.quantum.operator import DifferentialOperator
+        >>> from sympy import Function, Symbol, Derivative
+        >>> x = Symbol('x')
+        >>> f = Function('f')
+        >>> d = DifferentialOperator(Derivative(f(x), x), f(x))
+        >>> d.expr
+        Derivative(f(x), x)
+        >>> y = Symbol('y')
+        >>> d = DifferentialOperator(Derivative(f(x, y), x) +
+        ...                          Derivative(f(x, y), y), f(x, y))
+        >>> d.expr
+        Derivative(f(x, y), x) + Derivative(f(x, y), y)
+        """
+
+        return self.args[0]
+
+    @property
+    def free_symbols(self):
+        """
+        Return the free symbols of the expression.
+        """
+
+        return self.expr.free_symbols
+
+    def _apply_operator_Wavefunction(self, func, **options):
+        from sympy.physics.quantum.state import Wavefunction
+        var = self.variables
+        wf_vars = func.args[1:]
+
+        f = self.function
+        new_expr = self.expr.subs(f, func(*var))
+        new_expr = new_expr.doit()
+
+        return Wavefunction(new_expr, *wf_vars)
+
+    def _eval_derivative(self, symbol):
+        new_expr = Derivative(self.expr, symbol)
+        return DifferentialOperator(new_expr, self.args[-1])
+
+    #-------------------------------------------------------------------------
+    # Printing
+    #-------------------------------------------------------------------------
+
+    def _print(self, printer, *args):
+        return '%s(%s)' % (
+            self._print_operator_name(printer, *args),
+            self._print_label(printer, *args)
+        )
+
+    def _print_pretty(self, printer, *args):
+        pform = self._print_operator_name_pretty(printer, *args)
+        label_pform = self._print_label_pretty(printer, *args)
+        label_pform = prettyForm(
+            *label_pform.parens(left='(', right=')')
+        )
+        pform = prettyForm(*pform.right(label_pform))
+        return pform
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/operatorordering.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/operatorordering.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6ba3dd83b4b79b773793b0094e636cc8a901f44
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/operatorordering.py
@@ -0,0 +1,290 @@
+"""Functions for reordering operator expressions."""
+
+import warnings
+
+from sympy.core.add import Add
+from sympy.core.mul import Mul
+from sympy.core.numbers import Integer
+from sympy.core.power import Pow
+from sympy.physics.quantum import Commutator, AntiCommutator
+from sympy.physics.quantum.boson import BosonOp
+from sympy.physics.quantum.fermion import FermionOp
+
+__all__ = [
+    'normal_order',
+    'normal_ordered_form'
+]
+
+
+def _expand_powers(factors):
+    """
+    Helper function for normal_ordered_form and normal_order: Expand a
+    power expression to a multiplication expression so that that the
+    expression can be handled by the normal ordering functions.
+    """
+
+    new_factors = []
+    for factor in factors.args:
+        if (isinstance(factor, Pow)
+                and isinstance(factor.args[1], Integer)
+                and factor.args[1] > 0):
+            for n in range(factor.args[1]):
+                new_factors.append(factor.args[0])
+        else:
+            new_factors.append(factor)
+
+    return new_factors
+
+def _normal_ordered_form_factor(product, independent=False, recursive_limit=10,
+                                _recursive_depth=0):
+    """
+    Helper function for normal_ordered_form_factor: Write multiplication
+    expression with bosonic or fermionic operators on normally ordered form,
+    using the bosonic and fermionic commutation relations. The resulting
+    operator expression is equivalent to the argument, but will in general be
+    a sum of operator products instead of a simple product.
+    """
+
+    factors = _expand_powers(product)
+
+    new_factors = []
+    n = 0
+    while n < len(factors) - 1:
+        current, next = factors[n], factors[n + 1]
+        if any(not isinstance(f, (FermionOp, BosonOp)) for f in (current, next)):
+            new_factors.append(current)
+            n += 1
+            continue
+
+        key_1 = (current.is_annihilation, str(current.name))
+        key_2 = (next.is_annihilation, str(next.name))
+
+        if key_1 <= key_2:
+            new_factors.append(current)
+            n += 1
+            continue
+
+        n += 2
+        if current.is_annihilation and not next.is_annihilation:
+            if isinstance(current, BosonOp) and isinstance(next, BosonOp):
+                if current.args[0] != next.args[0]:
+                    if independent:
+                        c = 0
+                    else:
+                        c = Commutator(current, next)
+                    new_factors.append(next * current + c)
+                else:
+                    new_factors.append(next * current + 1)
+            elif isinstance(current, FermionOp) and isinstance(next, FermionOp):
+                if current.args[0] != next.args[0]:
+                    if independent:
+                        c = 0
+                    else:
+                        c = AntiCommutator(current, next)
+                    new_factors.append(-next * current + c)
+                else:
+                    new_factors.append(-next * current + 1)
+        elif (current.is_annihilation == next.is_annihilation and
+            isinstance(current, FermionOp) and isinstance(next, FermionOp)):
+            new_factors.append(-next * current)
+        else:
+            new_factors.append(next * current)
+
+    if n == len(factors) - 1:
+        new_factors.append(factors[-1])
+
+    if new_factors == factors:
+        return product
+    else:
+        expr = Mul(*new_factors).expand()
+        return normal_ordered_form(expr,
+                                   recursive_limit=recursive_limit,
+                                   _recursive_depth=_recursive_depth + 1,
+                                   independent=independent)
+
+
+def _normal_ordered_form_terms(expr, independent=False, recursive_limit=10,
+                               _recursive_depth=0):
+    """
+    Helper function for normal_ordered_form: loop through each term in an
+    addition expression and call _normal_ordered_form_factor to perform the
+    factor to an normally ordered expression.
+    """
+
+    new_terms = []
+    for term in expr.args:
+        if isinstance(term, Mul):
+            new_term = _normal_ordered_form_factor(
+                term, recursive_limit=recursive_limit,
+                _recursive_depth=_recursive_depth, independent=independent)
+            new_terms.append(new_term)
+        else:
+            new_terms.append(term)
+
+    return Add(*new_terms)
+
+
+def normal_ordered_form(expr, independent=False, recursive_limit=10,
+                        _recursive_depth=0):
+    """Write an expression with bosonic or fermionic operators on normal
+    ordered form, where each term is normally ordered. Note that this
+    normal ordered form is equivalent to the original expression.
+
+    Parameters
+    ==========
+
+    expr : expression
+        The expression write on normal ordered form.
+    independent : bool (default False)
+        Whether to consider operator with different names as operating in
+        different Hilbert spaces. If False, the (anti-)commutation is left
+        explicit.
+    recursive_limit : int (default 10)
+        The number of allowed recursive applications of the function.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum import Dagger
+    >>> from sympy.physics.quantum.boson import BosonOp
+    >>> from sympy.physics.quantum.operatorordering import normal_ordered_form
+    >>> a = BosonOp("a")
+    >>> normal_ordered_form(a * Dagger(a))
+    1 + Dagger(a)*a
+    """
+
+    if _recursive_depth > recursive_limit:
+        warnings.warn("Too many recursions, aborting")
+        return expr
+
+    if isinstance(expr, Add):
+        return _normal_ordered_form_terms(expr,
+                                          recursive_limit=recursive_limit,
+                                          _recursive_depth=_recursive_depth,
+                                          independent=independent)
+    elif isinstance(expr, Mul):
+        return _normal_ordered_form_factor(expr,
+                                           recursive_limit=recursive_limit,
+                                           _recursive_depth=_recursive_depth,
+                                           independent=independent)
+    else:
+        return expr
+
+
+def _normal_order_factor(product, recursive_limit=10, _recursive_depth=0):
+    """
+    Helper function for normal_order: Normal order a multiplication expression
+    with bosonic or fermionic operators. In general the resulting operator
+    expression will not be equivalent to original product.
+    """
+
+    factors = _expand_powers(product)
+
+    n = 0
+    new_factors = []
+    while n < len(factors) - 1:
+
+        if (isinstance(factors[n], BosonOp) and
+                factors[n].is_annihilation):
+            # boson
+            if not isinstance(factors[n + 1], BosonOp):
+                new_factors.append(factors[n])
+            else:
+                if factors[n + 1].is_annihilation:
+                    new_factors.append(factors[n])
+                else:
+                    if factors[n].args[0] != factors[n + 1].args[0]:
+                        new_factors.append(factors[n + 1] * factors[n])
+                    else:
+                        new_factors.append(factors[n + 1] * factors[n])
+                    n += 1
+
+        elif (isinstance(factors[n], FermionOp) and
+              factors[n].is_annihilation):
+            # fermion
+            if not isinstance(factors[n + 1], FermionOp):
+                new_factors.append(factors[n])
+            else:
+                if factors[n + 1].is_annihilation:
+                    new_factors.append(factors[n])
+                else:
+                    if factors[n].args[0] != factors[n + 1].args[0]:
+                        new_factors.append(-factors[n + 1] * factors[n])
+                    else:
+                        new_factors.append(-factors[n + 1] * factors[n])
+                    n += 1
+
+        else:
+            new_factors.append(factors[n])
+
+        n += 1
+
+    if n == len(factors) - 1:
+        new_factors.append(factors[-1])
+
+    if new_factors == factors:
+        return product
+    else:
+        expr = Mul(*new_factors).expand()
+        return normal_order(expr,
+                            recursive_limit=recursive_limit,
+                            _recursive_depth=_recursive_depth + 1)
+
+
+def _normal_order_terms(expr, recursive_limit=10, _recursive_depth=0):
+    """
+    Helper function for normal_order: look through each term in an addition
+    expression and call _normal_order_factor to perform the normal ordering
+    on the factors.
+    """
+
+    new_terms = []
+    for term in expr.args:
+        if isinstance(term, Mul):
+            new_term = _normal_order_factor(term,
+                                            recursive_limit=recursive_limit,
+                                            _recursive_depth=_recursive_depth)
+            new_terms.append(new_term)
+        else:
+            new_terms.append(term)
+
+    return Add(*new_terms)
+
+
+def normal_order(expr, recursive_limit=10, _recursive_depth=0):
+    """Normal order an expression with bosonic or fermionic operators. Note
+    that this normal order is not equivalent to the original expression, but
+    the creation and annihilation operators in each term in expr is reordered
+    so that the expression becomes normal ordered.
+
+    Parameters
+    ==========
+
+    expr : expression
+        The expression to normal order.
+
+    recursive_limit : int (default 10)
+        The number of allowed recursive applications of the function.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum import Dagger
+    >>> from sympy.physics.quantum.boson import BosonOp
+    >>> from sympy.physics.quantum.operatorordering import normal_order
+    >>> a = BosonOp("a")
+    >>> normal_order(a * Dagger(a))
+    Dagger(a)*a
+    """
+    if _recursive_depth > recursive_limit:
+        warnings.warn("Too many recursions, aborting")
+        return expr
+
+    if isinstance(expr, Add):
+        return _normal_order_terms(expr, recursive_limit=recursive_limit,
+                                   _recursive_depth=_recursive_depth)
+    elif isinstance(expr, Mul):
+        return _normal_order_factor(expr, recursive_limit=recursive_limit,
+                                    _recursive_depth=_recursive_depth)
+    else:
+        return expr
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/operatorset.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/operatorset.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf32bcabbe5d33381dff0b94a9b130375032adef
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/operatorset.py
@@ -0,0 +1,279 @@
+""" A module for mapping operators to their corresponding eigenstates
+and vice versa
+
+It contains a global dictionary with eigenstate-operator pairings.
+If a new state-operator pair is created, this dictionary should be
+updated as well.
+
+It also contains functions operators_to_state and state_to_operators
+for mapping between the two. These can handle both classes and
+instances of operators and states. See the individual function
+descriptions for details.
+
+TODO List:
+- Update the dictionary with a complete list of state-operator pairs
+"""
+
+from sympy.physics.quantum.cartesian import (XOp, YOp, ZOp, XKet, PxOp, PxKet,
+                                             PositionKet3D)
+from sympy.physics.quantum.operator import Operator
+from sympy.physics.quantum.state import StateBase, BraBase, Ket
+from sympy.physics.quantum.spin import (JxOp, JyOp, JzOp, J2Op, JxKet, JyKet,
+                                        JzKet)
+
+__all__ = [
+    'operators_to_state',
+    'state_to_operators'
+]
+
+#state_mapping stores the mappings between states and their associated
+#operators or tuples of operators. This should be updated when new
+#classes are written! Entries are of the form PxKet : PxOp or
+#something like 3DKet : (ROp, ThetaOp, PhiOp)
+
+#frozenset is used so that the reverse mapping can be made
+#(regular sets are not hashable because they are mutable
+state_mapping = { JxKet: frozenset((J2Op, JxOp)),
+                  JyKet: frozenset((J2Op, JyOp)),
+                  JzKet: frozenset((J2Op, JzOp)),
+                  Ket: Operator,
+                  PositionKet3D: frozenset((XOp, YOp, ZOp)),
+                  PxKet: PxOp,
+                  XKet: XOp }
+
+op_mapping = {v: k for k, v in state_mapping.items()}
+
+
+def operators_to_state(operators, **options):
+    """ Returns the eigenstate of the given operator or set of operators
+
+    A global function for mapping operator classes to their associated
+    states. It takes either an Operator or a set of operators and
+    returns the state associated with these.
+
+    This function can handle both instances of a given operator or
+    just the class itself (i.e. both XOp() and XOp)
+
+    There are multiple use cases to consider:
+
+    1) A class or set of classes is passed: First, we try to
+    instantiate default instances for these operators. If this fails,
+    then the class is simply returned. If we succeed in instantiating
+    default instances, then we try to call state._operators_to_state
+    on the operator instances. If this fails, the class is returned.
+    Otherwise, the instance returned by _operators_to_state is returned.
+
+    2) An instance or set of instances is passed: In this case,
+    state._operators_to_state is called on the instances passed. If
+    this fails, a state class is returned. If the method returns an
+    instance, that instance is returned.
+
+    In both cases, if the operator class or set does not exist in the
+    state_mapping dictionary, None is returned.
+
+    Parameters
+    ==========
+
+    arg: Operator or set
+         The class or instance of the operator or set of operators
+         to be mapped to a state
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum.cartesian import XOp, PxOp
+    >>> from sympy.physics.quantum.operatorset import operators_to_state
+    >>> from sympy.physics.quantum.operator import Operator
+    >>> operators_to_state(XOp)
+    |x>
+    >>> operators_to_state(XOp())
+    |x>
+    >>> operators_to_state(PxOp)
+    |px>
+    >>> operators_to_state(PxOp())
+    |px>
+    >>> operators_to_state(Operator)
+    |psi>
+    >>> operators_to_state(Operator())
+    |psi>
+    """
+
+    if not (isinstance(operators, (Operator, set)) or issubclass(operators, Operator)):
+        raise NotImplementedError("Argument is not an Operator or a set!")
+
+    if isinstance(operators, set):
+        for s in operators:
+            if not (isinstance(s, Operator)
+                   or issubclass(s, Operator)):
+                raise NotImplementedError("Set is not all Operators!")
+
+        ops = frozenset(operators)
+
+        if ops in op_mapping:  # ops is a list of classes in this case
+            #Try to get an object from default instances of the
+            #operators...if this fails, return the class
+            try:
+                op_instances = [op() for op in ops]
+                ret = _get_state(op_mapping[ops], set(op_instances), **options)
+            except NotImplementedError:
+                ret = op_mapping[ops]
+
+            return ret
+        else:
+            tmp = [type(o) for o in ops]
+            classes = frozenset(tmp)
+
+            if classes in op_mapping:
+                ret = _get_state(op_mapping[classes], ops, **options)
+            else:
+                ret = None
+
+            return ret
+    else:
+        if operators in op_mapping:
+            try:
+                op_instance = operators()
+                ret = _get_state(op_mapping[operators], op_instance, **options)
+            except NotImplementedError:
+                ret = op_mapping[operators]
+
+            return ret
+        elif type(operators) in op_mapping:
+            return _get_state(op_mapping[type(operators)], operators, **options)
+        else:
+            return None
+
+
+def state_to_operators(state, **options):
+    """ Returns the operator or set of operators corresponding to the
+    given eigenstate
+
+    A global function for mapping state classes to their associated
+    operators or sets of operators. It takes either a state class
+    or instance.
+
+    This function can handle both instances of a given state or just
+    the class itself (i.e. both XKet() and XKet)
+
+    There are multiple use cases to consider:
+
+    1) A state class is passed: In this case, we first try
+    instantiating a default instance of the class. If this succeeds,
+    then we try to call state._state_to_operators on that instance.
+    If the creation of the default instance or if the calling of
+    _state_to_operators fails, then either an operator class or set of
+    operator classes is returned. Otherwise, the appropriate
+    operator instances are returned.
+
+    2) A state instance is returned: Here, state._state_to_operators
+    is called for the instance. If this fails, then a class or set of
+    operator classes is returned. Otherwise, the instances are returned.
+
+    In either case, if the state's class does not exist in
+    state_mapping, None is returned.
+
+    Parameters
+    ==========
+
+    arg: StateBase class or instance (or subclasses)
+         The class or instance of the state to be mapped to an
+         operator or set of operators
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum.cartesian import XKet, PxKet, XBra, PxBra
+    >>> from sympy.physics.quantum.operatorset import state_to_operators
+    >>> from sympy.physics.quantum.state import Ket, Bra
+    >>> state_to_operators(XKet)
+    X
+    >>> state_to_operators(XKet())
+    X
+    >>> state_to_operators(PxKet)
+    Px
+    >>> state_to_operators(PxKet())
+    Px
+    >>> state_to_operators(PxBra)
+    Px
+    >>> state_to_operators(XBra)
+    X
+    >>> state_to_operators(Ket)
+    O
+    >>> state_to_operators(Bra)
+    O
+    """
+
+    if not (isinstance(state, StateBase) or issubclass(state, StateBase)):
+        raise NotImplementedError("Argument is not a state!")
+
+    if state in state_mapping:  # state is a class
+        state_inst = _make_default(state)
+        try:
+            ret = _get_ops(state_inst,
+                           _make_set(state_mapping[state]), **options)
+        except (NotImplementedError, TypeError):
+            ret = state_mapping[state]
+    elif type(state) in state_mapping:
+        ret = _get_ops(state,
+                       _make_set(state_mapping[type(state)]), **options)
+    elif isinstance(state, BraBase) and state.dual_class() in state_mapping:
+        ret = _get_ops(state,
+                       _make_set(state_mapping[state.dual_class()]))
+    elif issubclass(state, BraBase) and state.dual_class() in state_mapping:
+        state_inst = _make_default(state)
+        try:
+            ret = _get_ops(state_inst,
+                           _make_set(state_mapping[state.dual_class()]))
+        except (NotImplementedError, TypeError):
+            ret = state_mapping[state.dual_class()]
+    else:
+        ret = None
+
+    return _make_set(ret)
+
+
+def _make_default(expr):
+    # XXX: Catching TypeError like this is a bad way of distinguishing between
+    # classes and instances. The logic using this function should be rewritten
+    # somehow.
+    try:
+        ret = expr()
+    except TypeError:
+        ret = expr
+
+    return ret
+
+
+def _get_state(state_class, ops, **options):
+    # Try to get a state instance from the operator INSTANCES.
+    # If this fails, get the class
+    try:
+        ret = state_class._operators_to_state(ops, **options)
+    except NotImplementedError:
+        ret = _make_default(state_class)
+
+    return ret
+
+
+def _get_ops(state_inst, op_classes, **options):
+    # Try to get operator instances from the state INSTANCE.
+    # If this fails, just return the classes
+    try:
+        ret = state_inst._state_to_operators(op_classes, **options)
+    except NotImplementedError:
+        if isinstance(op_classes, (set, tuple, frozenset)):
+            ret = tuple(_make_default(x) for x in op_classes)
+        else:
+            ret = _make_default(op_classes)
+
+    if isinstance(ret, set) and len(ret) == 1:
+        return ret[0]
+
+    return ret
+
+
+def _make_set(ops):
+    if isinstance(ops, (tuple, list, frozenset)):
+        return set(ops)
+    else:
+        return ops
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/pauli.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/pauli.py
new file mode 100644
index 0000000000000000000000000000000000000000..89762ed2b38e1c5df3775714ee08d3700df0fa65
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/pauli.py
@@ -0,0 +1,675 @@
+"""Pauli operators and states"""
+
+from sympy.core.add import Add
+from sympy.core.mul import Mul
+from sympy.core.numbers import I
+from sympy.core.power import Pow
+from sympy.core.singleton import S
+from sympy.functions.elementary.exponential import exp
+from sympy.physics.quantum import Operator, Ket, Bra
+from sympy.physics.quantum import ComplexSpace
+from sympy.matrices import Matrix
+from sympy.functions.special.tensor_functions import KroneckerDelta
+
+__all__ = [
+    'SigmaX', 'SigmaY', 'SigmaZ', 'SigmaMinus', 'SigmaPlus', 'SigmaZKet',
+    'SigmaZBra', 'qsimplify_pauli'
+]
+
+
+class SigmaOpBase(Operator):
+    """Pauli sigma operator, base class"""
+
+    @property
+    def name(self):
+        return self.args[0]
+
+    @property
+    def use_name(self):
+        return bool(self.args[0]) is not False
+
+    @classmethod
+    def default_args(self):
+        return (False,)
+
+    def __new__(cls, *args, **hints):
+        return Operator.__new__(cls, *args, **hints)
+
+    def _eval_commutator_BosonOp(self, other, **hints):
+        return S.Zero
+
+
+class SigmaX(SigmaOpBase):
+    """Pauli sigma x operator
+
+    Parameters
+    ==========
+
+    name : str
+        An optional string that labels the operator. Pauli operators with
+        different names commute.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum import represent
+    >>> from sympy.physics.quantum.pauli import SigmaX
+    >>> sx = SigmaX()
+    >>> sx
+    SigmaX()
+    >>> represent(sx)
+    Matrix([
+    [0, 1],
+    [1, 0]])
+    """
+
+    def __new__(cls, *args, **hints):
+        return SigmaOpBase.__new__(cls, *args, **hints)
+
+    def _eval_commutator_SigmaY(self, other, **hints):
+        if self.name != other.name:
+            return S.Zero
+        else:
+            return 2 * I * SigmaZ(self.name)
+
+    def _eval_commutator_SigmaZ(self, other, **hints):
+        if self.name != other.name:
+            return S.Zero
+        else:
+            return - 2 * I * SigmaY(self.name)
+
+    def _eval_commutator_BosonOp(self, other, **hints):
+        return S.Zero
+
+    def _eval_anticommutator_SigmaY(self, other, **hints):
+        return S.Zero
+
+    def _eval_anticommutator_SigmaZ(self, other, **hints):
+        return S.Zero
+
+    def _eval_adjoint(self):
+        return self
+
+    def _print_contents_latex(self, printer, *args):
+        if self.use_name:
+            return r'{\sigma_x^{(%s)}}' % str(self.name)
+        else:
+            return r'{\sigma_x}'
+
+    def _print_contents(self, printer, *args):
+        return 'SigmaX()'
+
+    def _eval_power(self, e):
+        if e.is_Integer and e.is_positive:
+            return SigmaX(self.name).__pow__(int(e) % 2)
+
+    def _represent_default_basis(self, **options):
+        format = options.get('format', 'sympy')
+        if format == 'sympy':
+            return Matrix([[0, 1], [1, 0]])
+        else:
+            raise NotImplementedError('Representation in format ' +
+                                      format + ' not implemented.')
+
+
+class SigmaY(SigmaOpBase):
+    """Pauli sigma y operator
+
+    Parameters
+    ==========
+
+    name : str
+        An optional string that labels the operator. Pauli operators with
+        different names commute.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum import represent
+    >>> from sympy.physics.quantum.pauli import SigmaY
+    >>> sy = SigmaY()
+    >>> sy
+    SigmaY()
+    >>> represent(sy)
+    Matrix([
+    [0, -I],
+    [I,  0]])
+    """
+
+    def __new__(cls, *args, **hints):
+        return SigmaOpBase.__new__(cls, *args)
+
+    def _eval_commutator_SigmaZ(self, other, **hints):
+        if self.name != other.name:
+            return S.Zero
+        else:
+            return 2 * I * SigmaX(self.name)
+
+    def _eval_commutator_SigmaX(self, other, **hints):
+        if self.name != other.name:
+            return S.Zero
+        else:
+            return - 2 * I * SigmaZ(self.name)
+
+    def _eval_anticommutator_SigmaX(self, other, **hints):
+        return S.Zero
+
+    def _eval_anticommutator_SigmaZ(self, other, **hints):
+        return S.Zero
+
+    def _eval_adjoint(self):
+        return self
+
+    def _print_contents_latex(self, printer, *args):
+        if self.use_name:
+            return r'{\sigma_y^{(%s)}}' % str(self.name)
+        else:
+            return r'{\sigma_y}'
+
+    def _print_contents(self, printer, *args):
+        return 'SigmaY()'
+
+    def _eval_power(self, e):
+        if e.is_Integer and e.is_positive:
+            return SigmaY(self.name).__pow__(int(e) % 2)
+
+    def _represent_default_basis(self, **options):
+        format = options.get('format', 'sympy')
+        if format == 'sympy':
+            return Matrix([[0, -I], [I, 0]])
+        else:
+            raise NotImplementedError('Representation in format ' +
+                                      format + ' not implemented.')
+
+
+class SigmaZ(SigmaOpBase):
+    """Pauli sigma z operator
+
+    Parameters
+    ==========
+
+    name : str
+        An optional string that labels the operator. Pauli operators with
+        different names commute.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum import represent
+    >>> from sympy.physics.quantum.pauli import SigmaZ
+    >>> sz = SigmaZ()
+    >>> sz ** 3
+    SigmaZ()
+    >>> represent(sz)
+    Matrix([
+    [1,  0],
+    [0, -1]])
+    """
+
+    def __new__(cls, *args, **hints):
+        return SigmaOpBase.__new__(cls, *args)
+
+    def _eval_commutator_SigmaX(self, other, **hints):
+        if self.name != other.name:
+            return S.Zero
+        else:
+            return 2 * I * SigmaY(self.name)
+
+    def _eval_commutator_SigmaY(self, other, **hints):
+        if self.name != other.name:
+            return S.Zero
+        else:
+            return - 2 * I * SigmaX(self.name)
+
+    def _eval_anticommutator_SigmaX(self, other, **hints):
+        return S.Zero
+
+    def _eval_anticommutator_SigmaY(self, other, **hints):
+        return S.Zero
+
+    def _eval_adjoint(self):
+        return self
+
+    def _print_contents_latex(self, printer, *args):
+        if self.use_name:
+            return r'{\sigma_z^{(%s)}}' % str(self.name)
+        else:
+            return r'{\sigma_z}'
+
+    def _print_contents(self, printer, *args):
+        return 'SigmaZ()'
+
+    def _eval_power(self, e):
+        if e.is_Integer and e.is_positive:
+            return SigmaZ(self.name).__pow__(int(e) % 2)
+
+    def _represent_default_basis(self, **options):
+        format = options.get('format', 'sympy')
+        if format == 'sympy':
+            return Matrix([[1, 0], [0, -1]])
+        else:
+            raise NotImplementedError('Representation in format ' +
+                                      format + ' not implemented.')
+
+
+class SigmaMinus(SigmaOpBase):
+    """Pauli sigma minus operator
+
+    Parameters
+    ==========
+
+    name : str
+        An optional string that labels the operator. Pauli operators with
+        different names commute.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum import represent, Dagger
+    >>> from sympy.physics.quantum.pauli import SigmaMinus
+    >>> sm = SigmaMinus()
+    >>> sm
+    SigmaMinus()
+    >>> Dagger(sm)
+    SigmaPlus()
+    >>> represent(sm)
+    Matrix([
+    [0, 0],
+    [1, 0]])
+    """
+
+    def __new__(cls, *args, **hints):
+        return SigmaOpBase.__new__(cls, *args)
+
+    def _eval_commutator_SigmaX(self, other, **hints):
+        if self.name != other.name:
+            return S.Zero
+        else:
+            return -SigmaZ(self.name)
+
+    def _eval_commutator_SigmaY(self, other, **hints):
+        if self.name != other.name:
+            return S.Zero
+        else:
+            return I * SigmaZ(self.name)
+
+    def _eval_commutator_SigmaZ(self, other, **hints):
+        return 2 * self
+
+    def _eval_commutator_SigmaMinus(self, other, **hints):
+        return SigmaZ(self.name)
+
+    def _eval_anticommutator_SigmaZ(self, other, **hints):
+        return S.Zero
+
+    def _eval_anticommutator_SigmaX(self, other, **hints):
+        return S.One
+
+    def _eval_anticommutator_SigmaY(self, other, **hints):
+        return I * S.NegativeOne
+
+    def _eval_anticommutator_SigmaPlus(self, other, **hints):
+        return S.One
+
+    def _eval_adjoint(self):
+        return SigmaPlus(self.name)
+
+    def _eval_power(self, e):
+        if e.is_Integer and e.is_positive:
+            return S.Zero
+
+    def _print_contents_latex(self, printer, *args):
+        if self.use_name:
+            return r'{\sigma_-^{(%s)}}' % str(self.name)
+        else:
+            return r'{\sigma_-}'
+
+    def _print_contents(self, printer, *args):
+        return 'SigmaMinus()'
+
+    def _represent_default_basis(self, **options):
+        format = options.get('format', 'sympy')
+        if format == 'sympy':
+            return Matrix([[0, 0], [1, 0]])
+        else:
+            raise NotImplementedError('Representation in format ' +
+                                      format + ' not implemented.')
+
+
+class SigmaPlus(SigmaOpBase):
+    """Pauli sigma plus operator
+
+    Parameters
+    ==========
+
+    name : str
+        An optional string that labels the operator. Pauli operators with
+        different names commute.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum import represent, Dagger
+    >>> from sympy.physics.quantum.pauli import SigmaPlus
+    >>> sp = SigmaPlus()
+    >>> sp
+    SigmaPlus()
+    >>> Dagger(sp)
+    SigmaMinus()
+    >>> represent(sp)
+    Matrix([
+    [0, 1],
+    [0, 0]])
+    """
+
+    def __new__(cls, *args, **hints):
+        return SigmaOpBase.__new__(cls, *args)
+
+    def _eval_commutator_SigmaX(self, other, **hints):
+        if self.name != other.name:
+            return S.Zero
+        else:
+            return SigmaZ(self.name)
+
+    def _eval_commutator_SigmaY(self, other, **hints):
+        if self.name != other.name:
+            return S.Zero
+        else:
+            return I * SigmaZ(self.name)
+
+    def _eval_commutator_SigmaZ(self, other, **hints):
+        if self.name != other.name:
+            return S.Zero
+        else:
+            return -2 * self
+
+    def _eval_commutator_SigmaMinus(self, other, **hints):
+        return SigmaZ(self.name)
+
+    def _eval_anticommutator_SigmaZ(self, other, **hints):
+        return S.Zero
+
+    def _eval_anticommutator_SigmaX(self, other, **hints):
+        return S.One
+
+    def _eval_anticommutator_SigmaY(self, other, **hints):
+        return I
+
+    def _eval_anticommutator_SigmaMinus(self, other, **hints):
+        return S.One
+
+    def _eval_adjoint(self):
+        return SigmaMinus(self.name)
+
+    def _eval_mul(self, other):
+        return self * other
+
+    def _eval_power(self, e):
+        if e.is_Integer and e.is_positive:
+            return S.Zero
+
+    def _print_contents_latex(self, printer, *args):
+        if self.use_name:
+            return r'{\sigma_+^{(%s)}}' % str(self.name)
+        else:
+            return r'{\sigma_+}'
+
+    def _print_contents(self, printer, *args):
+        return 'SigmaPlus()'
+
+    def _represent_default_basis(self, **options):
+        format = options.get('format', 'sympy')
+        if format == 'sympy':
+            return Matrix([[0, 1], [0, 0]])
+        else:
+            raise NotImplementedError('Representation in format ' +
+                                      format + ' not implemented.')
+
+
+class SigmaZKet(Ket):
+    """Ket for a two-level system quantum system.
+
+    Parameters
+    ==========
+
+    n : Number
+        The state number (0 or 1).
+
+    """
+
+    def __new__(cls, n):
+        if n not in (0, 1):
+            raise ValueError("n must be 0 or 1")
+        return Ket.__new__(cls, n)
+
+    @property
+    def n(self):
+        return self.label[0]
+
+    @classmethod
+    def dual_class(self):
+        return SigmaZBra
+
+    @classmethod
+    def _eval_hilbert_space(cls, label):
+        return ComplexSpace(2)
+
+    def _eval_innerproduct_SigmaZBra(self, bra, **hints):
+        return KroneckerDelta(self.n, bra.n)
+
+    def _apply_from_right_to_SigmaZ(self, op, **options):
+        if self.n == 0:
+            return self
+        else:
+            return S.NegativeOne * self
+
+    def _apply_from_right_to_SigmaX(self, op, **options):
+        return SigmaZKet(1) if self.n == 0 else SigmaZKet(0)
+
+    def _apply_from_right_to_SigmaY(self, op, **options):
+        return I * SigmaZKet(1) if self.n == 0 else (-I) * SigmaZKet(0)
+
+    def _apply_from_right_to_SigmaMinus(self, op, **options):
+        if self.n == 0:
+            return SigmaZKet(1)
+        else:
+            return S.Zero
+
+    def _apply_from_right_to_SigmaPlus(self, op, **options):
+        if self.n == 0:
+            return S.Zero
+        else:
+            return SigmaZKet(0)
+
+    def _represent_default_basis(self, **options):
+        format = options.get('format', 'sympy')
+        if format == 'sympy':
+            return Matrix([[1], [0]]) if self.n == 0 else Matrix([[0], [1]])
+        else:
+            raise NotImplementedError('Representation in format ' +
+                                      format + ' not implemented.')
+
+
+class SigmaZBra(Bra):
+    """Bra for a two-level quantum system.
+
+    Parameters
+    ==========
+
+    n : Number
+        The state number (0 or 1).
+
+    """
+
+    def __new__(cls, n):
+        if n not in (0, 1):
+            raise ValueError("n must be 0 or 1")
+        return Bra.__new__(cls, n)
+
+    @property
+    def n(self):
+        return self.label[0]
+
+    @classmethod
+    def dual_class(self):
+        return SigmaZKet
+
+
+def _qsimplify_pauli_product(a, b):
+    """
+    Internal helper function for simplifying products of Pauli operators.
+    """
+    if not (isinstance(a, SigmaOpBase) and isinstance(b, SigmaOpBase)):
+        return Mul(a, b)
+
+    if a.name != b.name:
+        # Pauli matrices with different labels commute; sort by name
+        if a.name < b.name:
+            return Mul(a, b)
+        else:
+            return Mul(b, a)
+
+    elif isinstance(a, SigmaX):
+
+        if isinstance(b, SigmaX):
+            return S.One
+
+        if isinstance(b, SigmaY):
+            return I * SigmaZ(a.name)
+
+        if isinstance(b, SigmaZ):
+            return - I * SigmaY(a.name)
+
+        if isinstance(b, SigmaMinus):
+            return (S.Half + SigmaZ(a.name)/2)
+
+        if isinstance(b, SigmaPlus):
+            return (S.Half - SigmaZ(a.name)/2)
+
+    elif isinstance(a, SigmaY):
+
+        if isinstance(b, SigmaX):
+            return - I * SigmaZ(a.name)
+
+        if isinstance(b, SigmaY):
+            return S.One
+
+        if isinstance(b, SigmaZ):
+            return I * SigmaX(a.name)
+
+        if isinstance(b, SigmaMinus):
+            return -I * (S.One + SigmaZ(a.name))/2
+
+        if isinstance(b, SigmaPlus):
+            return I * (S.One - SigmaZ(a.name))/2
+
+    elif isinstance(a, SigmaZ):
+
+        if isinstance(b, SigmaX):
+            return I * SigmaY(a.name)
+
+        if isinstance(b, SigmaY):
+            return - I * SigmaX(a.name)
+
+        if isinstance(b, SigmaZ):
+            return S.One
+
+        if isinstance(b, SigmaMinus):
+            return - SigmaMinus(a.name)
+
+        if isinstance(b, SigmaPlus):
+            return SigmaPlus(a.name)
+
+    elif isinstance(a, SigmaMinus):
+
+        if isinstance(b, SigmaX):
+            return (S.One - SigmaZ(a.name))/2
+
+        if isinstance(b, SigmaY):
+            return - I * (S.One - SigmaZ(a.name))/2
+
+        if isinstance(b, SigmaZ):
+            # (SigmaX(a.name) - I * SigmaY(a.name))/2
+            return SigmaMinus(b.name)
+
+        if isinstance(b, SigmaMinus):
+            return S.Zero
+
+        if isinstance(b, SigmaPlus):
+            return S.Half - SigmaZ(a.name)/2
+
+    elif isinstance(a, SigmaPlus):
+
+        if isinstance(b, SigmaX):
+            return (S.One + SigmaZ(a.name))/2
+
+        if isinstance(b, SigmaY):
+            return I * (S.One + SigmaZ(a.name))/2
+
+        if isinstance(b, SigmaZ):
+            #-(SigmaX(a.name) + I * SigmaY(a.name))/2
+            return -SigmaPlus(a.name)
+
+        if isinstance(b, SigmaMinus):
+            return (S.One + SigmaZ(a.name))/2
+
+        if isinstance(b, SigmaPlus):
+            return S.Zero
+
+    else:
+        return a * b
+
+
+def qsimplify_pauli(e):
+    """
+    Simplify an expression that includes products of pauli operators.
+
+    Parameters
+    ==========
+
+    e : expression
+        An expression that contains products of Pauli operators that is
+        to be simplified.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum.pauli import SigmaX, SigmaY
+    >>> from sympy.physics.quantum.pauli import qsimplify_pauli
+    >>> sx, sy = SigmaX(), SigmaY()
+    >>> sx * sy
+    SigmaX()*SigmaY()
+    >>> qsimplify_pauli(sx * sy)
+    I*SigmaZ()
+    """
+    if isinstance(e, Operator):
+        return e
+
+    if isinstance(e, (Add, Pow, exp)):
+        t = type(e)
+        return t(*(qsimplify_pauli(arg) for arg in e.args))
+
+    if isinstance(e, Mul):
+
+        c, nc = e.args_cnc()
+
+        nc_s = []
+        while nc:
+            curr = nc.pop(0)
+
+            while (len(nc) and
+                   isinstance(curr, SigmaOpBase) and
+                   isinstance(nc[0], SigmaOpBase) and
+                   curr.name == nc[0].name):
+
+                x = nc.pop(0)
+                y = _qsimplify_pauli_product(curr, x)
+                c1, nc1 = y.args_cnc()
+                curr = Mul(*nc1)
+                c = c + c1
+
+            nc_s.append(curr)
+
+        return Mul(*c) * Mul(*nc_s)
+
+    return e
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/piab.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/piab.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8ac8135ee03e640f745070602c7dd8ca20f2767
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/piab.py
@@ -0,0 +1,72 @@
+"""1D quantum particle in a box."""
+
+from sympy.core.numbers import pi
+from sympy.core.singleton import S
+from sympy.core.symbol import Symbol
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import sin
+from sympy.sets.sets import Interval
+
+from sympy.physics.quantum.operator import HermitianOperator
+from sympy.physics.quantum.state import Ket, Bra
+from sympy.physics.quantum.constants import hbar
+from sympy.functions.special.tensor_functions import KroneckerDelta
+from sympy.physics.quantum.hilbert import L2
+
+m = Symbol('m')
+L = Symbol('L')
+
+
+__all__ = [
+    'PIABHamiltonian',
+    'PIABKet',
+    'PIABBra'
+]
+
+
+class PIABHamiltonian(HermitianOperator):
+    """Particle in a box Hamiltonian operator."""
+
+    @classmethod
+    def _eval_hilbert_space(cls, label):
+        return L2(Interval(S.NegativeInfinity, S.Infinity))
+
+    def _apply_operator_PIABKet(self, ket, **options):
+        n = ket.label[0]
+        return (n**2*pi**2*hbar**2)/(2*m*L**2)*ket
+
+
+class PIABKet(Ket):
+    """Particle in a box eigenket."""
+
+    @classmethod
+    def _eval_hilbert_space(cls, args):
+        return L2(Interval(S.NegativeInfinity, S.Infinity))
+
+    @classmethod
+    def dual_class(self):
+        return PIABBra
+
+    def _represent_default_basis(self, **options):
+        return self._represent_XOp(None, **options)
+
+    def _represent_XOp(self, basis, **options):
+        x = Symbol('x')
+        n = Symbol('n')
+        subs_info = options.get('subs', {})
+        return sqrt(2/L)*sin(n*pi*x/L).subs(subs_info)
+
+    def _eval_innerproduct_PIABBra(self, bra):
+        return KroneckerDelta(bra.label[0], self.label[0])
+
+
+class PIABBra(Bra):
+    """Particle in a box eigenbra."""
+
+    @classmethod
+    def _eval_hilbert_space(cls, label):
+        return L2(Interval(S.NegativeInfinity, S.Infinity))
+
+    @classmethod
+    def dual_class(self):
+        return PIABKet
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/qapply.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/qapply.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2d8c92e51552c8114d65a1304fcd1925ae752f4
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/qapply.py
@@ -0,0 +1,263 @@
+"""Logic for applying operators to states.
+
+Todo:
+* Sometimes the final result needs to be expanded, we should do this by hand.
+"""
+
+from sympy.concrete import Sum
+from sympy.core.add import Add
+from sympy.core.kind import NumberKind
+from sympy.core.mul import Mul
+from sympy.core.power import Pow
+from sympy.core.singleton import S
+from sympy.core.sympify import sympify, _sympify
+
+from sympy.physics.quantum.anticommutator import AntiCommutator
+from sympy.physics.quantum.commutator import Commutator
+from sympy.physics.quantum.dagger import Dagger
+from sympy.physics.quantum.innerproduct import InnerProduct
+from sympy.physics.quantum.operator import OuterProduct, Operator
+from sympy.physics.quantum.state import State, KetBase, BraBase, Wavefunction
+from sympy.physics.quantum.tensorproduct import TensorProduct
+
+__all__ = [
+    'qapply'
+]
+
+
+#-----------------------------------------------------------------------------
+# Main code
+#-----------------------------------------------------------------------------
+
+
+def ip_doit_func(e):
+    """Transform the inner products in an expression by calling ``.doit()``."""
+    return e.replace(InnerProduct, lambda *args: InnerProduct(*args).doit())
+
+
+def sum_doit_func(e):
+    """Transform the sums in an expression by calling ``.doit()``."""
+    return e.replace(Sum, lambda *args: Sum(*args).doit())
+
+
+def qapply(e, **options):
+    """Apply operators to states in a quantum expression.
+
+    Parameters
+    ==========
+
+    e : Expr
+        The expression containing operators and states. This expression tree
+        will be walked to find operators acting on states symbolically.
+    options : dict
+        A dict of key/value pairs that determine how the operator actions
+        are carried out.
+
+        The following options are valid:
+
+        * ``dagger``: try to apply Dagger operators to the left
+          (default: False).
+        * ``ip_doit``: call ``.doit()`` in inner products when they are
+          encountered (default: True).
+        * ``sum_doit``: call ``.doit()`` on sums when they are encountered
+          (default: False). This is helpful for collapsing sums over Kronecker
+          delta's that are created when calling ``qapply``.
+
+    Returns
+    =======
+
+    e : Expr
+        The original expression, but with the operators applied to states.
+
+    Examples
+    ========
+
+        >>> from sympy.physics.quantum import qapply, Ket, Bra
+        >>> b = Bra('b')
+        >>> k = Ket('k')
+        >>> A = k * b
+        >>> A
+        |k>>> qapply(A * b.dual / (b * b.dual))
+        |k>
+        >>> qapply(k.dual * A / (k.dual * k))
+         and A*(|a>+|b>) and all Commutators and
+    # TensorProducts. The only problem with this is that if we can't apply
+    # all the Operators, we have just expanded everything.
+    # TODO: don't expand the scalars in front of each Mul.
+    e = e.expand(commutator=True, tensorproduct=True)
+
+    # If we just have a raw ket, return it.
+    if isinstance(e, KetBase):
+        return e
+
+    # We have an Add(a, b, c, ...) and compute
+    # Add(qapply(a), qapply(b), ...)
+    elif isinstance(e, Add):
+        result = 0
+        for arg in e.args:
+            result += qapply(arg, **options)
+        return result.expand()
+
+    # For a Density operator call qapply on its state
+    elif isinstance(e, Density):
+        new_args = [(qapply(state, **options), prob) for (state,
+                     prob) in e.args]
+        return Density(*new_args)
+
+    # For a raw TensorProduct, call qapply on its args.
+    elif isinstance(e, TensorProduct):
+        return TensorProduct(*[qapply(t, **options) for t in e.args])
+
+    # For a Sum, call qapply on its function.
+    elif isinstance(e, Sum):
+        result = Sum(qapply(e.function, **options), *e.limits)
+        result = sum_doit_func(result) if sum_doit else result
+        return result
+
+    # For a Pow, call qapply on its base.
+    elif isinstance(e, Pow):
+        return qapply(e.base, **options)**e.exp
+
+    # We have a Mul where there might be actual operators to apply to kets.
+    elif isinstance(e, Mul):
+        c_part, nc_part = e.args_cnc()
+        c_mul = Mul(*c_part)
+        nc_mul = Mul(*nc_part)
+        if not nc_part: # If we only have a commuting part, just return it.
+            result = c_mul
+        elif isinstance(nc_mul, Mul):
+            result = c_mul*qapply_Mul(nc_mul, **options)
+        else:
+            result = c_mul*qapply(nc_mul, **options)
+        if result == e and dagger:
+            result = Dagger(qapply_Mul(Dagger(e), **options))
+        result = ip_doit_func(result) if ip_doit else result
+        result = sum_doit_func(result) if sum_doit else result
+        return result
+
+    # In all other cases (State, Operator, Pow, Commutator, InnerProduct,
+    # OuterProduct) we won't ever have operators to apply to kets.
+    else:
+        return e
+
+
+def qapply_Mul(e, **options):
+
+    args = list(e.args)
+    extra = S.One
+    result = None
+
+    # If we only have 0 or 1 args, we have nothing to do and return.
+    if len(args) <= 1 or not isinstance(e, Mul):
+        return e
+    rhs = args.pop()
+    lhs = args.pop()
+
+    # Make sure we have two non-commutative objects before proceeding.
+    if (not isinstance(rhs, Wavefunction) and sympify(rhs).is_commutative) or \
+            (not isinstance(lhs, Wavefunction) and sympify(lhs).is_commutative):
+        return e
+
+    # For a Pow with an integer exponent, apply one of them and reduce the
+    # exponent by one.
+    if isinstance(lhs, Pow) and lhs.exp.is_Integer:
+        args.append(lhs.base**(lhs.exp - 1))
+        lhs = lhs.base
+
+    # Pull OuterProduct apart
+    if isinstance(lhs, OuterProduct):
+        args.append(lhs.ket)
+        lhs = lhs.bra
+
+    if isinstance(rhs, OuterProduct):
+        extra = rhs.bra # Append to the right of the result
+        rhs = rhs.ket
+
+    # Call .doit() on Commutator/AntiCommutator.
+    if isinstance(lhs, (Commutator, AntiCommutator)):
+        comm = lhs.doit()
+        if isinstance(comm, Add):
+            return qapply(
+                e.func(*(args + [comm.args[0], rhs])) +
+                e.func(*(args + [comm.args[1], rhs])),
+                **options
+            )*extra
+        else:
+            return qapply(e.func(*args)*comm*rhs, **options)*extra
+
+    # Apply tensor products of operators to states
+    if isinstance(lhs, TensorProduct) and all(isinstance(arg, (Operator, State, Mul, Pow)) or arg == 1 for arg in lhs.args) and \
+            isinstance(rhs, TensorProduct) and all(isinstance(arg, (Operator, State, Mul, Pow)) or arg == 1 for arg in rhs.args) and \
+            len(lhs.args) == len(rhs.args):
+        result = TensorProduct(*[qapply(lhs.args[n]*rhs.args[n], **options) for n in range(len(lhs.args))]).expand(tensorproduct=True)
+        return qapply_Mul(e.func(*args), **options)*result*extra
+
+    # For Sums, move the Sum to the right.
+    if isinstance(rhs, Sum):
+        if isinstance(lhs, Sum):
+            if set(lhs.variables).intersection(set(rhs.variables)):
+                raise ValueError('Duplicated dummy indices in separate sums in qapply.')
+            limits = lhs.limits + rhs.limits
+            result = Sum(qapply(lhs.function*rhs.function, **options), *limits)
+            return qapply_Mul(e.func(*args)*result, **options)
+        else:
+            result = Sum(qapply(lhs*rhs.function, **options), *rhs.limits)
+            return qapply_Mul(e.func(*args)*result, **options)
+
+    if isinstance(lhs, Sum):
+        result = Sum(qapply(lhs.function*rhs, **options), *lhs.limits)
+        return qapply_Mul(e.func(*args)*result, **options)
+
+    # Now try to actually apply the operator and build an inner product.
+    _apply = getattr(lhs, '_apply_operator', None)
+    if _apply is not None:
+        try:
+            result = _apply(rhs, **options)
+        except NotImplementedError:
+            result = None
+    else:
+        result = None
+
+    if result is None:
+        _apply_right = getattr(rhs, '_apply_from_right_to', None)
+        if _apply_right is not None:
+            try:
+                result = _apply_right(lhs, **options)
+            except NotImplementedError:
+                result = None
+
+    if result is None:
+        if isinstance(lhs, BraBase) and isinstance(rhs, KetBase):
+            result = InnerProduct(lhs, rhs)
+
+    # TODO: I may need to expand before returning the final result.
+    if isinstance(result, (int, complex, float)):
+        return _sympify(result)
+    elif result is None:
+        if len(args) == 0:
+            # We had two args to begin with so args=[].
+            return e
+        else:
+            return qapply_Mul(e.func(*(args + [lhs])), **options)*rhs*extra
+    elif isinstance(result, InnerProduct):
+        return result*qapply_Mul(e.func(*args), **options)*extra
+    else:  # result is a scalar times a Mul, Add or TensorProduct
+        return qapply(e.func(*args)*result, **options)*extra
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/qasm.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/qasm.py
new file mode 100644
index 0000000000000000000000000000000000000000..39b49d9a67399114e7d03f12148854b2e41b0b26
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/qasm.py
@@ -0,0 +1,224 @@
+"""
+
+qasm.py - Functions to parse a set of qasm commands into a SymPy Circuit.
+
+Examples taken from Chuang's page: https://web.archive.org/web/20220120121541/https://www.media.mit.edu/quanta/qasm2circ/
+
+The code returns a circuit and an associated list of labels.
+
+>>> from sympy.physics.quantum.qasm import Qasm
+>>> q = Qasm('qubit q0', 'qubit q1', 'h q0', 'cnot q0,q1')
+>>> q.get_circuit()
+CNOT(1,0)*H(1)
+
+>>> q = Qasm('qubit q0', 'qubit q1', 'cnot q0,q1', 'cnot q1,q0', 'cnot q0,q1')
+>>> q.get_circuit()
+CNOT(1,0)*CNOT(0,1)*CNOT(1,0)
+"""
+
+__all__ = [
+    'Qasm',
+    ]
+
+from math import prod
+
+from sympy.physics.quantum.gate import H, CNOT, X, Z, CGate, CGateS, SWAP, S, T,CPHASE
+from sympy.physics.quantum.circuitplot import Mz
+
+def read_qasm(lines):
+    return Qasm(*lines.splitlines())
+
+def read_qasm_file(filename):
+    return Qasm(*open(filename).readlines())
+
+def flip_index(i, n):
+    """Reorder qubit indices from largest to smallest.
+
+    >>> from sympy.physics.quantum.qasm import flip_index
+    >>> flip_index(0, 2)
+    1
+    >>> flip_index(1, 2)
+    0
+    """
+    return n-i-1
+
+def trim(line):
+    """Remove everything following comment # characters in line.
+
+    >>> from sympy.physics.quantum.qasm import trim
+    >>> trim('nothing happens here')
+    'nothing happens here'
+    >>> trim('something #happens here')
+    'something '
+    """
+    if '#' not in line:
+        return line
+    return line.split('#')[0]
+
+def get_index(target, labels):
+    """Get qubit labels from the rest of the line,and return indices
+
+    >>> from sympy.physics.quantum.qasm import get_index
+    >>> get_index('q0', ['q0', 'q1'])
+    1
+    >>> get_index('q1', ['q0', 'q1'])
+    0
+    """
+    nq = len(labels)
+    return flip_index(labels.index(target), nq)
+
+def get_indices(targets, labels):
+    return [get_index(t, labels) for t in targets]
+
+def nonblank(args):
+    for line in args:
+        line = trim(line)
+        if line.isspace():
+            continue
+        yield line
+    return
+
+def fullsplit(line):
+    words = line.split()
+    rest = ' '.join(words[1:])
+    return fixcommand(words[0]), [s.strip() for s in rest.split(',')]
+
+def fixcommand(c):
+    """Fix Qasm command names.
+
+    Remove all of forbidden characters from command c, and
+    replace 'def' with 'qdef'.
+    """
+    forbidden_characters = ['-']
+    c = c.lower()
+    for char in forbidden_characters:
+        c = c.replace(char, '')
+    if c == 'def':
+        return 'qdef'
+    return c
+
+def stripquotes(s):
+    """Replace explicit quotes in a string.
+
+    >>> from sympy.physics.quantum.qasm import stripquotes
+    >>> stripquotes("'S'") == 'S'
+    True
+    >>> stripquotes('"S"') == 'S'
+    True
+    >>> stripquotes('S') == 'S'
+    True
+    """
+    s = s.replace('"', '') # Remove second set of quotes?
+    s = s.replace("'", '')
+    return s
+
+class Qasm:
+    """Class to form objects from Qasm lines
+
+    >>> from sympy.physics.quantum.qasm import Qasm
+    >>> q = Qasm('qubit q0', 'qubit q1', 'h q0', 'cnot q0,q1')
+    >>> q.get_circuit()
+    CNOT(1,0)*H(1)
+    >>> q = Qasm('qubit q0', 'qubit q1', 'cnot q0,q1', 'cnot q1,q0', 'cnot q0,q1')
+    >>> q.get_circuit()
+    CNOT(1,0)*CNOT(0,1)*CNOT(1,0)
+    """
+    def __init__(self, *args, **kwargs):
+        self.defs = {}
+        self.circuit = []
+        self.labels = []
+        self.inits = {}
+        self.add(*args)
+        self.kwargs = kwargs
+
+    def add(self, *lines):
+        for line in nonblank(lines):
+            command, rest = fullsplit(line)
+            if self.defs.get(command): #defs come first, since you can override built-in
+                function = self.defs.get(command)
+                indices = self.indices(rest)
+                if len(indices) == 1:
+                    self.circuit.append(function(indices[0]))
+                else:
+                    self.circuit.append(function(indices[:-1], indices[-1]))
+            elif hasattr(self, command):
+                function = getattr(self, command)
+                function(*rest)
+            else:
+                print("Function %s not defined. Skipping" % command)
+
+    def get_circuit(self):
+        return prod(reversed(self.circuit))
+
+    def get_labels(self):
+        return list(reversed(self.labels))
+
+    def plot(self):
+        from sympy.physics.quantum.circuitplot import CircuitPlot
+        circuit, labels = self.get_circuit(), self.get_labels()
+        CircuitPlot(circuit, len(labels), labels=labels, inits=self.inits)
+
+    def qubit(self, arg, init=None):
+        self.labels.append(arg)
+        if init: self.inits[arg] = init
+
+    def indices(self, args):
+        return get_indices(args, self.labels)
+
+    def index(self, arg):
+        return get_index(arg, self.labels)
+
+    def nop(self, *args):
+        pass
+
+    def x(self, arg):
+        self.circuit.append(X(self.index(arg)))
+
+    def z(self, arg):
+        self.circuit.append(Z(self.index(arg)))
+
+    def h(self, arg):
+        self.circuit.append(H(self.index(arg)))
+
+    def s(self, arg):
+        self.circuit.append(S(self.index(arg)))
+
+    def t(self, arg):
+        self.circuit.append(T(self.index(arg)))
+
+    def measure(self, arg):
+        self.circuit.append(Mz(self.index(arg)))
+
+    def cnot(self, a1, a2):
+        self.circuit.append(CNOT(*self.indices([a1, a2])))
+
+    def swap(self, a1, a2):
+        self.circuit.append(SWAP(*self.indices([a1, a2])))
+
+    def cphase(self, a1, a2):
+        self.circuit.append(CPHASE(*self.indices([a1, a2])))
+
+    def toffoli(self, a1, a2, a3):
+        i1, i2, i3 = self.indices([a1, a2, a3])
+        self.circuit.append(CGateS((i1, i2), X(i3)))
+
+    def cx(self, a1, a2):
+        fi, fj = self.indices([a1, a2])
+        self.circuit.append(CGate(fi, X(fj)))
+
+    def cz(self, a1, a2):
+        fi, fj = self.indices([a1, a2])
+        self.circuit.append(CGate(fi, Z(fj)))
+
+    def defbox(self, *args):
+        print("defbox not supported yet. Skipping: ", args)
+
+    def qdef(self, name, ncontrols, symbol):
+        from sympy.physics.quantum.circuitplot import CreateOneQubitGate, CreateCGate
+        ncontrols = int(ncontrols)
+        command = fixcommand(name)
+        symbol = stripquotes(symbol)
+        if ncontrols > 0:
+            self.defs[command] = CreateCGate(symbol)
+        else:
+            self.defs[command] = CreateOneQubitGate(symbol)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/qexpr.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/qexpr.py
new file mode 100644
index 0000000000000000000000000000000000000000..64f7e2a200fa7d89b35db1da551bcbd25492f2d9
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/qexpr.py
@@ -0,0 +1,409 @@
+from sympy.core.expr import Expr
+from sympy.core.symbol import Symbol
+from sympy.core.sympify import sympify
+from sympy.matrices.dense import Matrix
+from sympy.printing.pretty.stringpict import prettyForm
+from sympy.core.containers import Tuple
+from sympy.utilities.iterables import is_sequence
+
+from sympy.physics.quantum.dagger import Dagger
+from sympy.physics.quantum.matrixutils import (
+    numpy_ndarray, scipy_sparse_matrix,
+    to_sympy, to_numpy, to_scipy_sparse
+)
+
+__all__ = [
+    'QuantumError',
+    'QExpr'
+]
+
+
+#-----------------------------------------------------------------------------
+# Error handling
+#-----------------------------------------------------------------------------
+
+class QuantumError(Exception):
+    pass
+
+
+def _qsympify_sequence(seq):
+    """Convert elements of a sequence to standard form.
+
+    This is like sympify, but it performs special logic for arguments passed
+    to QExpr. The following conversions are done:
+
+    * (list, tuple, Tuple) => _qsympify_sequence each element and convert
+      sequence to a Tuple.
+    * basestring => Symbol
+    * Matrix => Matrix
+    * other => sympify
+
+    Strings are passed to Symbol, not sympify to make sure that variables like
+    'pi' are kept as Symbols, not the SymPy built-in number subclasses.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum.qexpr import _qsympify_sequence
+    >>> _qsympify_sequence((1,2,[3,4,[1,]]))
+    (1, 2, (3, 4, (1,)))
+
+    """
+
+    return tuple(__qsympify_sequence_helper(seq))
+
+
+def __qsympify_sequence_helper(seq):
+    """
+       Helper function for _qsympify_sequence
+       This function does the actual work.
+    """
+    #base case. If not a list, do Sympification
+    if not is_sequence(seq):
+        if isinstance(seq, Matrix):
+            return seq
+        elif isinstance(seq, str):
+            return Symbol(seq)
+        else:
+            return sympify(seq)
+
+    # base condition, when seq is QExpr and also
+    # is iterable.
+    if isinstance(seq, QExpr):
+        return seq
+
+    #if list, recurse on each item in the list
+    result = [__qsympify_sequence_helper(item) for item in seq]
+
+    return Tuple(*result)
+
+
+#-----------------------------------------------------------------------------
+# Basic Quantum Expression from which all objects descend
+#-----------------------------------------------------------------------------
+
+class QExpr(Expr):
+    """A base class for all quantum object like operators and states."""
+
+    # In sympy, slots are for instance attributes that are computed
+    # dynamically by the __new__ method. They are not part of args, but they
+    # derive from args.
+
+    # The Hilbert space a quantum Object belongs to.
+    __slots__ = ('hilbert_space', )
+
+    is_commutative = False
+
+    # The separator used in printing the label.
+    _label_separator = ''
+
+    def __new__(cls, *args, **kwargs):
+        """Construct a new quantum object.
+
+        Parameters
+        ==========
+
+        args : tuple
+            The list of numbers or parameters that uniquely specify the
+            quantum object. For a state, this will be its symbol or its
+            set of quantum numbers.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.quantum.qexpr import QExpr
+        >>> q = QExpr(0)
+        >>> q
+        0
+        >>> q.label
+        (0,)
+        >>> q.hilbert_space
+        H
+        >>> q.args
+        (0,)
+        >>> q.is_commutative
+        False
+        """
+
+        # First compute args and call Expr.__new__ to create the instance
+        args = cls._eval_args(args, **kwargs)
+        if len(args) == 0:
+            args = cls._eval_args(tuple(cls.default_args()), **kwargs)
+        inst = Expr.__new__(cls, *args)
+        # Now set the slots on the instance
+        inst.hilbert_space = cls._eval_hilbert_space(args)
+        return inst
+
+    @classmethod
+    def _new_rawargs(cls, hilbert_space, *args, **old_assumptions):
+        """Create new instance of this class with hilbert_space and args.
+
+        This is used to bypass the more complex logic in the ``__new__``
+        method in cases where you already have the exact ``hilbert_space``
+        and ``args``. This should be used when you are positive these
+        arguments are valid, in their final, proper form and want to optimize
+        the creation of the object.
+        """
+
+        obj = Expr.__new__(cls, *args, **old_assumptions)
+        obj.hilbert_space = hilbert_space
+        return obj
+
+    #-------------------------------------------------------------------------
+    # Properties
+    #-------------------------------------------------------------------------
+
+    @property
+    def label(self):
+        """The label is the unique set of identifiers for the object.
+
+        Usually, this will include all of the information about the state
+        *except* the time (in the case of time-dependent objects).
+
+        This must be a tuple, rather than a Tuple.
+        """
+        if len(self.args) == 0:  # If there is no label specified, return the default
+            return self._eval_args(list(self.default_args()))
+        else:
+            return self.args
+
+    @property
+    def is_symbolic(self):
+        return True
+
+    @classmethod
+    def default_args(self):
+        """If no arguments are specified, then this will return a default set
+        of arguments to be run through the constructor.
+
+        NOTE: Any classes that override this MUST return a tuple of arguments.
+        Should be overridden by subclasses to specify the default arguments for kets and operators
+        """
+        raise NotImplementedError("No default arguments for this class!")
+
+    #-------------------------------------------------------------------------
+    # _eval_* methods
+    #-------------------------------------------------------------------------
+
+    def _eval_adjoint(self):
+        obj = Expr._eval_adjoint(self)
+        if obj is None:
+            obj = Expr.__new__(Dagger, self)
+        if isinstance(obj, QExpr):
+            obj.hilbert_space = self.hilbert_space
+        return obj
+
+    @classmethod
+    def _eval_args(cls, args):
+        """Process the args passed to the __new__ method.
+
+        This simply runs args through _qsympify_sequence.
+        """
+        return _qsympify_sequence(args)
+
+    @classmethod
+    def _eval_hilbert_space(cls, args):
+        """Compute the Hilbert space instance from the args.
+        """
+        from sympy.physics.quantum.hilbert import HilbertSpace
+        return HilbertSpace()
+
+    #-------------------------------------------------------------------------
+    # Printing
+    #-------------------------------------------------------------------------
+
+    # Utilities for printing: these operate on raw SymPy objects
+
+    def _print_sequence(self, seq, sep, printer, *args):
+        result = []
+        for item in seq:
+            result.append(printer._print(item, *args))
+        return sep.join(result)
+
+    def _print_sequence_pretty(self, seq, sep, printer, *args):
+        pform = printer._print(seq[0], *args)
+        for item in seq[1:]:
+            pform = prettyForm(*pform.right(sep))
+            pform = prettyForm(*pform.right(printer._print(item, *args)))
+        return pform
+
+    # Utilities for printing: these operate prettyForm objects
+
+    def _print_subscript_pretty(self, a, b):
+        top = prettyForm(*b.left(' '*a.width()))
+        bot = prettyForm(*a.right(' '*b.width()))
+        return prettyForm(binding=prettyForm.POW, *bot.below(top))
+
+    def _print_superscript_pretty(self, a, b):
+        return a**b
+
+    def _print_parens_pretty(self, pform, left='(', right=')'):
+        return prettyForm(*pform.parens(left=left, right=right))
+
+    # Printing of labels (i.e. args)
+
+    def _print_label(self, printer, *args):
+        """Prints the label of the QExpr
+
+        This method prints self.label, using self._label_separator to separate
+        the elements. This method should not be overridden, instead, override
+        _print_contents to change printing behavior.
+        """
+        return self._print_sequence(
+            self.label, self._label_separator, printer, *args
+        )
+
+    def _print_label_repr(self, printer, *args):
+        return self._print_sequence(
+            self.label, ',', printer, *args
+        )
+
+    def _print_label_pretty(self, printer, *args):
+        return self._print_sequence_pretty(
+            self.label, self._label_separator, printer, *args
+        )
+
+    def _print_label_latex(self, printer, *args):
+        return self._print_sequence(
+            self.label, self._label_separator, printer, *args
+        )
+
+    # Printing of contents (default to label)
+
+    def _print_contents(self, printer, *args):
+        """Printer for contents of QExpr
+
+        Handles the printing of any unique identifying contents of a QExpr to
+        print as its contents, such as any variables or quantum numbers. The
+        default is to print the label, which is almost always the args. This
+        should not include printing of any brackets or parentheses.
+        """
+        return self._print_label(printer, *args)
+
+    def _print_contents_pretty(self, printer, *args):
+        return self._print_label_pretty(printer, *args)
+
+    def _print_contents_latex(self, printer, *args):
+        return self._print_label_latex(printer, *args)
+
+    # Main printing methods
+
+    def _sympystr(self, printer, *args):
+        """Default printing behavior of QExpr objects
+
+        Handles the default printing of a QExpr. To add other things to the
+        printing of the object, such as an operator name to operators or
+        brackets to states, the class should override the _print/_pretty/_latex
+        functions directly and make calls to _print_contents where appropriate.
+        This allows things like InnerProduct to easily control its printing the
+        printing of contents.
+        """
+        return self._print_contents(printer, *args)
+
+    def _sympyrepr(self, printer, *args):
+        classname = self.__class__.__name__
+        label = self._print_label_repr(printer, *args)
+        return '%s(%s)' % (classname, label)
+
+    def _pretty(self, printer, *args):
+        pform = self._print_contents_pretty(printer, *args)
+        return pform
+
+    def _latex(self, printer, *args):
+        return self._print_contents_latex(printer, *args)
+
+    #-------------------------------------------------------------------------
+    # Represent
+    #-------------------------------------------------------------------------
+
+    def _represent_default_basis(self, **options):
+        raise NotImplementedError('This object does not have a default basis')
+
+    def _represent(self, *, basis=None, **options):
+        """Represent this object in a given basis.
+
+        This method dispatches to the actual methods that perform the
+        representation. Subclases of QExpr should define various methods to
+        determine how the object will be represented in various bases. The
+        format of these methods is::
+
+            def _represent_BasisName(self, basis, **options):
+
+        Thus to define how a quantum object is represented in the basis of
+        the operator Position, you would define::
+
+            def _represent_Position(self, basis, **options):
+
+        Usually, basis object will be instances of Operator subclasses, but
+        there is a chance we will relax this in the future to accommodate other
+        types of basis sets that are not associated with an operator.
+
+        If the ``format`` option is given it can be ("sympy", "numpy",
+        "scipy.sparse"). This will ensure that any matrices that result from
+        representing the object are returned in the appropriate matrix format.
+
+        Parameters
+        ==========
+
+        basis : Operator
+            The Operator whose basis functions will be used as the basis for
+            representation.
+        options : dict
+            A dictionary of key/value pairs that give options and hints for
+            the representation, such as the number of basis functions to
+            be used.
+        """
+        if basis is None:
+            result = self._represent_default_basis(**options)
+        else:
+            result = dispatch_method(self, '_represent', basis, **options)
+
+        # If we get a matrix representation, convert it to the right format.
+        format = options.get('format', 'sympy')
+        result = self._format_represent(result, format)
+        return result
+
+    def _format_represent(self, result, format):
+        if format == 'sympy' and not isinstance(result, Matrix):
+            return to_sympy(result)
+        elif format == 'numpy' and not isinstance(result, numpy_ndarray):
+            return to_numpy(result)
+        elif format == 'scipy.sparse' and \
+                not isinstance(result, scipy_sparse_matrix):
+            return to_scipy_sparse(result)
+
+        return result
+
+
+def split_commutative_parts(e):
+    """Split into commutative and non-commutative parts."""
+    c_part, nc_part = e.args_cnc()
+    c_part = list(c_part)
+    return c_part, nc_part
+
+
+def split_qexpr_parts(e):
+    """Split an expression into Expr and noncommutative QExpr parts."""
+    expr_part = []
+    qexpr_part = []
+    for arg in e.args:
+        if not isinstance(arg, QExpr):
+            expr_part.append(arg)
+        else:
+            qexpr_part.append(arg)
+    return expr_part, qexpr_part
+
+
+def dispatch_method(self, basename, arg, **options):
+    """Dispatch a method to the proper handlers."""
+    method_name = '%s_%s' % (basename, arg.__class__.__name__)
+    if hasattr(self, method_name):
+        f = getattr(self, method_name)
+        # This can raise and we will allow it to propagate.
+        result = f(arg, **options)
+        if result is not None:
+            return result
+    raise NotImplementedError(
+        "%s.%s cannot handle: %r" %
+        (self.__class__.__name__, basename, arg)
+    )
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/qft.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/qft.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6a3fa4539267f7bb6cf015521007e292b3d4cfd
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/qft.py
@@ -0,0 +1,215 @@
+"""An implementation of qubits and gates acting on them.
+
+Todo:
+
+* Update docstrings.
+* Update tests.
+* Implement apply using decompose.
+* Implement represent using decompose or something smarter. For this to
+  work we first have to implement represent for SWAP.
+* Decide if we want upper index to be inclusive in the constructor.
+* Fix the printing of Rk gates in plotting.
+"""
+
+from sympy.core.expr import Expr
+from sympy.core.numbers import (I, Integer, pi)
+from sympy.core.symbol import Symbol
+from sympy.functions.elementary.exponential import exp
+from sympy.matrices.dense import Matrix
+from sympy.functions import sqrt
+
+from sympy.physics.quantum.qapply import qapply
+from sympy.physics.quantum.qexpr import QuantumError, QExpr
+from sympy.matrices import eye
+from sympy.physics.quantum.tensorproduct import matrix_tensor_product
+
+from sympy.physics.quantum.gate import (
+    Gate, HadamardGate, SwapGate, OneQubitGate, CGate, PhaseGate, TGate, ZGate
+)
+
+from sympy.functions.elementary.complexes import sign
+
+__all__ = [
+    'QFT',
+    'IQFT',
+    'RkGate',
+    'Rk'
+]
+
+#-----------------------------------------------------------------------------
+# Fourier stuff
+#-----------------------------------------------------------------------------
+
+
+class RkGate(OneQubitGate):
+    """This is the R_k gate of the QTF."""
+    gate_name = 'Rk'
+    gate_name_latex = 'R'
+
+    def __new__(cls, *args):
+        if len(args) != 2:
+            raise QuantumError(
+                'Rk gates only take two arguments, got: %r' % args
+            )
+        # For small k, Rk gates simplify to other gates, using these
+        # substitutions give us familiar results for the QFT for small numbers
+        # of qubits.
+        target = args[0]
+        k = args[1]
+        if k == 1:
+            return ZGate(target)
+        elif k == 2:
+            return PhaseGate(target)
+        elif k == 3:
+            return TGate(target)
+        args = cls._eval_args(args)
+        inst = Expr.__new__(cls, *args)
+        inst.hilbert_space = cls._eval_hilbert_space(args)
+        return inst
+
+    @classmethod
+    def _eval_args(cls, args):
+        # Fall back to this, because Gate._eval_args assumes that args is
+        # all targets and can't contain duplicates.
+        return QExpr._eval_args(args)
+
+    @property
+    def k(self):
+        return self.label[1]
+
+    @property
+    def targets(self):
+        return self.label[:1]
+
+    @property
+    def gate_name_plot(self):
+        return r'$%s_%s$' % (self.gate_name_latex, str(self.k))
+
+    def get_target_matrix(self, format='sympy'):
+        if format == 'sympy':
+            return Matrix([[1, 0], [0, exp(sign(self.k)*Integer(2)*pi*I/(Integer(2)**abs(self.k)))]])
+        raise NotImplementedError(
+            'Invalid format for the R_k gate: %r' % format)
+
+
+Rk = RkGate
+
+
+class Fourier(Gate):
+    """Superclass of Quantum Fourier and Inverse Quantum Fourier Gates."""
+
+    @classmethod
+    def _eval_args(self, args):
+        if len(args) != 2:
+            raise QuantumError(
+                'QFT/IQFT only takes two arguments, got: %r' % args
+            )
+        if args[0] >= args[1]:
+            raise QuantumError("Start must be smaller than finish")
+        return Gate._eval_args(args)
+
+    def _represent_default_basis(self, **options):
+        return self._represent_ZGate(None, **options)
+
+    def _represent_ZGate(self, basis, **options):
+        """
+            Represents the (I)QFT In the Z Basis
+        """
+        nqubits = options.get('nqubits', 0)
+        if nqubits == 0:
+            raise QuantumError(
+                'The number of qubits must be given as nqubits.')
+        if nqubits < self.min_qubits:
+            raise QuantumError(
+                'The number of qubits %r is too small for the gate.' % nqubits
+            )
+        size = self.size
+        omega = self.omega
+
+        #Make a matrix that has the basic Fourier Transform Matrix
+        arrayFT = [[omega**(
+            i*j % size)/sqrt(size) for i in range(size)] for j in range(size)]
+        matrixFT = Matrix(arrayFT)
+
+        #Embed the FT Matrix in a higher space, if necessary
+        if self.label[0] != 0:
+            matrixFT = matrix_tensor_product(eye(2**self.label[0]), matrixFT)
+        if self.min_qubits < nqubits:
+            matrixFT = matrix_tensor_product(
+                matrixFT, eye(2**(nqubits - self.min_qubits)))
+
+        return matrixFT
+
+    @property
+    def targets(self):
+        return range(self.label[0], self.label[1])
+
+    @property
+    def min_qubits(self):
+        return self.label[1]
+
+    @property
+    def size(self):
+        """Size is the size of the QFT matrix"""
+        return 2**(self.label[1] - self.label[0])
+
+    @property
+    def omega(self):
+        return Symbol('omega')
+
+
+class QFT(Fourier):
+    """The forward quantum Fourier transform."""
+
+    gate_name = 'QFT'
+    gate_name_latex = 'QFT'
+
+    def decompose(self):
+        """Decomposes QFT into elementary gates."""
+        start = self.label[0]
+        finish = self.label[1]
+        circuit = 1
+        for level in reversed(range(start, finish)):
+            circuit = HadamardGate(level)*circuit
+            for i in range(level - start):
+                circuit = CGate(level - i - 1, RkGate(level, i + 2))*circuit
+        for i in range((finish - start)//2):
+            circuit = SwapGate(i + start, finish - i - 1)*circuit
+        return circuit
+
+    def _apply_operator_Qubit(self, qubits, **options):
+        return qapply(self.decompose()*qubits)
+
+    def _eval_inverse(self):
+        return IQFT(*self.args)
+
+    @property
+    def omega(self):
+        return exp(2*pi*I/self.size)
+
+
+class IQFT(Fourier):
+    """The inverse quantum Fourier transform."""
+
+    gate_name = 'IQFT'
+    gate_name_latex = '{QFT^{-1}}'
+
+    def decompose(self):
+        """Decomposes IQFT into elementary gates."""
+        start = self.args[0]
+        finish = self.args[1]
+        circuit = 1
+        for i in range((finish - start)//2):
+            circuit = SwapGate(i + start, finish - i - 1)*circuit
+        for level in range(start, finish):
+            for i in reversed(range(level - start)):
+                circuit = CGate(level - i - 1, RkGate(level, -i - 2))*circuit
+            circuit = HadamardGate(level)*circuit
+        return circuit
+
+    def _eval_inverse(self):
+        return QFT(*self.args)
+
+    @property
+    def omega(self):
+        return exp(-2*pi*I/self.size)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/qubit.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/qubit.py
new file mode 100644
index 0000000000000000000000000000000000000000..71d1dbc01e3a16e2a4b64eec3c3800b7218b2636
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/qubit.py
@@ -0,0 +1,811 @@
+"""Qubits for quantum computing.
+
+Todo:
+* Finish implementing measurement logic. This should include POVM.
+* Update docstrings.
+* Update tests.
+"""
+
+
+import math
+
+from sympy.core.add import Add
+from sympy.core.mul import Mul
+from sympy.core.numbers import Integer
+from sympy.core.power import Pow
+from sympy.core.singleton import S
+from sympy.functions.elementary.complexes import conjugate
+from sympy.functions.elementary.exponential import log
+from sympy.core.basic import _sympify
+from sympy.external.gmpy import SYMPY_INTS
+from sympy.matrices import Matrix, zeros
+from sympy.printing.pretty.stringpict import prettyForm
+
+from sympy.physics.quantum.hilbert import ComplexSpace
+from sympy.physics.quantum.state import Ket, Bra, State
+
+from sympy.physics.quantum.qexpr import QuantumError
+from sympy.physics.quantum.represent import represent
+from sympy.physics.quantum.matrixutils import (
+    numpy_ndarray, scipy_sparse_matrix
+)
+from mpmath.libmp.libintmath import bitcount
+
+__all__ = [
+    'Qubit',
+    'QubitBra',
+    'IntQubit',
+    'IntQubitBra',
+    'qubit_to_matrix',
+    'matrix_to_qubit',
+    'matrix_to_density',
+    'measure_all',
+    'measure_partial',
+    'measure_partial_oneshot',
+    'measure_all_oneshot'
+]
+
+#-----------------------------------------------------------------------------
+# Qubit Classes
+#-----------------------------------------------------------------------------
+
+
+class QubitState(State):
+    """Base class for Qubit and QubitBra."""
+
+    #-------------------------------------------------------------------------
+    # Initialization/creation
+    #-------------------------------------------------------------------------
+
+    @classmethod
+    def _eval_args(cls, args):
+        # If we are passed a QubitState or subclass, we just take its qubit
+        # values directly.
+        if len(args) == 1 and isinstance(args[0], QubitState):
+            return args[0].qubit_values
+
+        # Turn strings into tuple of strings
+        if len(args) == 1 and isinstance(args[0], str):
+            args = tuple( S.Zero if qb == "0" else S.One for qb in args[0])
+        else:
+            args = tuple( S.Zero if qb == "0" else S.One if qb == "1" else qb for qb in args)
+        args = tuple(_sympify(arg) for arg in args)
+
+        # Validate input (must have 0 or 1 input)
+        for element in args:
+            if element not in (S.Zero, S.One):
+                raise ValueError(
+                    "Qubit values must be 0 or 1, got: %r" % element)
+        return args
+
+    @classmethod
+    def _eval_hilbert_space(cls, args):
+        return ComplexSpace(2)**len(args)
+
+    #-------------------------------------------------------------------------
+    # Properties
+    #-------------------------------------------------------------------------
+
+    @property
+    def dimension(self):
+        """The number of Qubits in the state."""
+        return len(self.qubit_values)
+
+    @property
+    def nqubits(self):
+        return self.dimension
+
+    @property
+    def qubit_values(self):
+        """Returns the values of the qubits as a tuple."""
+        return self.label
+
+    #-------------------------------------------------------------------------
+    # Special methods
+    #-------------------------------------------------------------------------
+
+    def __len__(self):
+        return self.dimension
+
+    def __getitem__(self, bit):
+        return self.qubit_values[int(self.dimension - bit - 1)]
+
+    #-------------------------------------------------------------------------
+    # Utility methods
+    #-------------------------------------------------------------------------
+
+    def flip(self, *bits):
+        """Flip the bit(s) given."""
+        newargs = list(self.qubit_values)
+        for i in bits:
+            bit = int(self.dimension - i - 1)
+            if newargs[bit] == 1:
+                newargs[bit] = 0
+            else:
+                newargs[bit] = 1
+        return self.__class__(*tuple(newargs))
+
+
+class Qubit(QubitState, Ket):
+    """A multi-qubit ket in the computational (z) basis.
+
+    We use the normal convention that the least significant qubit is on the
+    right, so ``|00001>`` has a 1 in the least significant qubit.
+
+    Parameters
+    ==========
+
+    values : list, str
+        The qubit values as a list of ints ([0,0,0,1,1,]) or a string ('011').
+
+    Examples
+    ========
+
+    Create a qubit in a couple of different ways and look at their attributes:
+
+        >>> from sympy.physics.quantum.qubit import Qubit
+        >>> Qubit(0,0,0)
+        |000>
+        >>> q = Qubit('0101')
+        >>> q
+        |0101>
+
+        >>> q.nqubits
+        4
+        >>> len(q)
+        4
+        >>> q.dimension
+        4
+        >>> q.qubit_values
+        (0, 1, 0, 1)
+
+    We can flip the value of an individual qubit:
+
+        >>> q.flip(1)
+        |0111>
+
+    We can take the dagger of a Qubit to get a bra:
+
+        >>> from sympy.physics.quantum.dagger import Dagger
+        >>> Dagger(q)
+        <0101|
+        >>> type(Dagger(q))
+        
+
+    Inner products work as expected:
+
+        >>> ip = Dagger(q)*q
+        >>> ip
+        <0101|0101>
+        >>> ip.doit()
+        1
+    """
+
+    @classmethod
+    def dual_class(self):
+        return QubitBra
+
+    def _eval_innerproduct_QubitBra(self, bra, **hints):
+        if self.label == bra.label:
+            return S.One
+        else:
+            return S.Zero
+
+    def _represent_default_basis(self, **options):
+        return self._represent_ZGate(None, **options)
+
+    def _represent_ZGate(self, basis, **options):
+        """Represent this qubits in the computational basis (ZGate).
+        """
+        _format = options.get('format', 'sympy')
+        n = 1
+        definite_state = 0
+        for it in reversed(self.qubit_values):
+            definite_state += n*it
+            n = n*2
+        result = [0]*(2**self.dimension)
+        result[int(definite_state)] = 1
+        if _format == 'sympy':
+            return Matrix(result)
+        elif _format == 'numpy':
+            import numpy as np
+            return np.array(result, dtype='complex').transpose()
+        elif _format == 'scipy.sparse':
+            from scipy import sparse
+            return sparse.csr_matrix(result, dtype='complex').transpose()
+
+    def _eval_trace(self, bra, **kwargs):
+        indices = kwargs.get('indices', [])
+
+        #sort index list to begin trace from most-significant
+        #qubit
+        sorted_idx = list(indices)
+        if len(sorted_idx) == 0:
+            sorted_idx = list(range(0, self.nqubits))
+        sorted_idx.sort()
+
+        #trace out for each of index
+        new_mat = self*bra
+        for i in range(len(sorted_idx) - 1, -1, -1):
+            # start from tracing out from leftmost qubit
+            new_mat = self._reduced_density(new_mat, int(sorted_idx[i]))
+
+        if (len(sorted_idx) == self.nqubits):
+            #in case full trace was requested
+            return new_mat[0]
+        else:
+            return matrix_to_density(new_mat)
+
+    def _reduced_density(self, matrix, qubit, **options):
+        """Compute the reduced density matrix by tracing out one qubit.
+           The qubit argument should be of type Python int, since it is used
+           in bit operations
+        """
+        def find_index_that_is_projected(j, k, qubit):
+            bit_mask = 2**qubit - 1
+            return ((j >> qubit) << (1 + qubit)) + (j & bit_mask) + (k << qubit)
+
+        old_matrix = represent(matrix, **options)
+        old_size = old_matrix.cols
+        #we expect the old_size to be even
+        new_size = old_size//2
+        new_matrix = Matrix().zeros(new_size)
+
+        for i in range(new_size):
+            for j in range(new_size):
+                for k in range(2):
+                    col = find_index_that_is_projected(j, k, qubit)
+                    row = find_index_that_is_projected(i, k, qubit)
+                    new_matrix[i, j] += old_matrix[row, col]
+
+        return new_matrix
+
+
+class QubitBra(QubitState, Bra):
+    """A multi-qubit bra in the computational (z) basis.
+
+    We use the normal convention that the least significant qubit is on the
+    right, so ``|00001>`` has a 1 in the least significant qubit.
+
+    Parameters
+    ==========
+
+    values : list, str
+        The qubit values as a list of ints ([0,0,0,1,1,]) or a string ('011').
+
+    See also
+    ========
+
+    Qubit: Examples using qubits
+
+    """
+    @classmethod
+    def dual_class(self):
+        return Qubit
+
+
+class IntQubitState(QubitState):
+    """A base class for qubits that work with binary representations."""
+
+    @classmethod
+    def _eval_args(cls, args, nqubits=None):
+        # The case of a QubitState instance
+        if len(args) == 1 and isinstance(args[0], QubitState):
+            return QubitState._eval_args(args)
+        # otherwise, args should be integer
+        elif not all(isinstance(a, (int, Integer)) for a in args):
+            raise ValueError('values must be integers, got (%s)' % (tuple(type(a) for a in args),))
+        # use nqubits if specified
+        if nqubits is not None:
+            if not isinstance(nqubits, (int, Integer)):
+                raise ValueError('nqubits must be an integer, got (%s)' % type(nqubits))
+            if len(args) != 1:
+                raise ValueError(
+                    'too many positional arguments (%s). should be (number, nqubits=n)' % (args,))
+            return cls._eval_args_with_nqubits(args[0], nqubits)
+        # For a single argument, we construct the binary representation of
+        # that integer with the minimal number of bits.
+        if len(args) == 1 and args[0] > 1:
+            #rvalues is the minimum number of bits needed to express the number
+            rvalues = reversed(range(bitcount(abs(args[0]))))
+            qubit_values = [(args[0] >> i) & 1 for i in rvalues]
+            return QubitState._eval_args(qubit_values)
+        # For two numbers, the second number is the number of bits
+        # on which it is expressed, so IntQubit(0,5) == |00000>.
+        elif len(args) == 2 and args[1] > 1:
+            return cls._eval_args_with_nqubits(args[0], args[1])
+        else:
+            return QubitState._eval_args(args)
+
+    @classmethod
+    def _eval_args_with_nqubits(cls, number, nqubits):
+        need = bitcount(abs(number))
+        if nqubits < need:
+            raise ValueError(
+                'cannot represent %s with %s bits' % (number, nqubits))
+        qubit_values = [(number >> i) & 1 for i in reversed(range(nqubits))]
+        return QubitState._eval_args(qubit_values)
+
+    def as_int(self):
+        """Return the numerical value of the qubit."""
+        number = 0
+        n = 1
+        for i in reversed(self.qubit_values):
+            number += n*i
+            n = n << 1
+        return number
+
+    def _print_label(self, printer, *args):
+        return str(self.as_int())
+
+    def _print_label_pretty(self, printer, *args):
+        label = self._print_label(printer, *args)
+        return prettyForm(label)
+
+    _print_label_repr = _print_label
+    _print_label_latex = _print_label
+
+
+class IntQubit(IntQubitState, Qubit):
+    """A qubit ket that store integers as binary numbers in qubit values.
+
+    The differences between this class and ``Qubit`` are:
+
+    * The form of the constructor.
+    * The qubit values are printed as their corresponding integer, rather
+      than the raw qubit values. The internal storage format of the qubit
+      values in the same as ``Qubit``.
+
+    Parameters
+    ==========
+
+    values : int, tuple
+        If a single argument, the integer we want to represent in the qubit
+        values. This integer will be represented using the fewest possible
+        number of qubits.
+        If a pair of integers and the second value is more than one, the first
+        integer gives the integer to represent in binary form and the second
+        integer gives the number of qubits to use.
+        List of zeros and ones is also accepted to generate qubit by bit pattern.
+
+    nqubits : int
+        The integer that represents the number of qubits.
+        This number should be passed with keyword ``nqubits=N``.
+        You can use this in order to avoid ambiguity of Qubit-style tuple of bits.
+        Please see the example below for more details.
+
+    Examples
+    ========
+
+    Create a qubit for the integer 5:
+
+        >>> from sympy.physics.quantum.qubit import IntQubit
+        >>> from sympy.physics.quantum.qubit import Qubit
+        >>> q = IntQubit(5)
+        >>> q
+        |5>
+
+    We can also create an ``IntQubit`` by passing a ``Qubit`` instance.
+
+        >>> q = IntQubit(Qubit('101'))
+        >>> q
+        |5>
+        >>> q.as_int()
+        5
+        >>> q.nqubits
+        3
+        >>> q.qubit_values
+        (1, 0, 1)
+
+    We can go back to the regular qubit form.
+
+        >>> Qubit(q)
+        |101>
+
+    Please note that ``IntQubit`` also accepts a ``Qubit``-style list of bits.
+    So, the code below yields qubits 3, not a single bit ``1``.
+
+        >>> IntQubit(1, 1)
+        |3>
+
+    To avoid ambiguity, use ``nqubits`` parameter.
+    Use of this keyword is recommended especially when you provide the values by variables.
+
+        >>> IntQubit(1, nqubits=1)
+        |1>
+        >>> a = 1
+        >>> IntQubit(a, nqubits=1)
+        |1>
+    """
+    @classmethod
+    def dual_class(self):
+        return IntQubitBra
+
+    def _eval_innerproduct_IntQubitBra(self, bra, **hints):
+        return Qubit._eval_innerproduct_QubitBra(self, bra)
+
+class IntQubitBra(IntQubitState, QubitBra):
+    """A qubit bra that store integers as binary numbers in qubit values."""
+
+    @classmethod
+    def dual_class(self):
+        return IntQubit
+
+
+#-----------------------------------------------------------------------------
+# Qubit <---> Matrix conversion functions
+#-----------------------------------------------------------------------------
+
+
+def matrix_to_qubit(matrix):
+    """Convert from the matrix repr. to a sum of Qubit objects.
+
+    Parameters
+    ----------
+    matrix : Matrix, numpy.matrix, scipy.sparse
+        The matrix to build the Qubit representation of. This works with
+        SymPy matrices, numpy matrices and scipy.sparse sparse matrices.
+
+    Examples
+    ========
+
+    Represent a state and then go back to its qubit form:
+
+        >>> from sympy.physics.quantum.qubit import matrix_to_qubit, Qubit
+        >>> from sympy.physics.quantum.represent import represent
+        >>> q = Qubit('01')
+        >>> matrix_to_qubit(represent(q))
+        |01>
+    """
+    # Determine the format based on the type of the input matrix
+    format = 'sympy'
+    if isinstance(matrix, numpy_ndarray):
+        format = 'numpy'
+    if isinstance(matrix, scipy_sparse_matrix):
+        format = 'scipy.sparse'
+
+    # Make sure it is of correct dimensions for a Qubit-matrix representation.
+    # This logic should work with sympy, numpy or scipy.sparse matrices.
+    if matrix.shape[0] == 1:
+        mlistlen = matrix.shape[1]
+        nqubits = log(mlistlen, 2)
+        ket = False
+        cls = QubitBra
+    elif matrix.shape[1] == 1:
+        mlistlen = matrix.shape[0]
+        nqubits = log(mlistlen, 2)
+        ket = True
+        cls = Qubit
+    else:
+        raise QuantumError(
+            'Matrix must be a row/column vector, got %r' % matrix
+        )
+    if not isinstance(nqubits, Integer):
+        raise QuantumError('Matrix must be a row/column vector of size '
+                           '2**nqubits, got: %r' % matrix)
+    # Go through each item in matrix, if element is non-zero, make it into a
+    # Qubit item times the element.
+    result = 0
+    for i in range(mlistlen):
+        if ket:
+            element = matrix[i, 0]
+        else:
+            element = matrix[0, i]
+        if format in ('numpy', 'scipy.sparse'):
+            element = complex(element)
+        if element:
+            # Form Qubit array; 0 in bit-locations where i is 0, 1 in
+            # bit-locations where i is 1
+            qubit_array = [int(i & (1 << x) != 0) for x in range(nqubits)]
+            qubit_array.reverse()
+            result = result + element*cls(*qubit_array)
+
+    # If SymPy simplified by pulling out a constant coefficient, undo that.
+    if isinstance(result, (Mul, Add, Pow)):
+        result = result.expand()
+
+    return result
+
+
+def matrix_to_density(mat):
+    """
+    Works by finding the eigenvectors and eigenvalues of the matrix.
+    We know we can decompose rho by doing:
+    sum(EigenVal*|Eigenvect>>> from sympy.physics.quantum.qubit import Qubit, measure_all
+        >>> from sympy.physics.quantum.gate import H
+        >>> from sympy.physics.quantum.qapply import qapply
+
+        >>> c = H(0)*H(1)*Qubit('00')
+        >>> c
+        H(0)*H(1)*|00>
+        >>> q = qapply(c)
+        >>> measure_all(q)
+        [(|00>, 1/4), (|01>, 1/4), (|10>, 1/4), (|11>, 1/4)]
+    """
+    m = qubit_to_matrix(qubit, format)
+
+    if format == 'sympy':
+        results = []
+
+        if normalize:
+            m = m.normalized()
+
+        size = max(m.shape)  # Max of shape to account for bra or ket
+        nqubits = int(math.log(size)/math.log(2))
+        for i in range(size):
+            if m[i]:
+                results.append(
+                    (Qubit(IntQubit(i, nqubits=nqubits)), m[i]*conjugate(m[i]))
+                )
+        return results
+    else:
+        raise NotImplementedError(
+            "This function cannot handle non-SymPy matrix formats yet"
+        )
+
+
+def measure_partial(qubit, bits, format='sympy', normalize=True):
+    """Perform a partial ensemble measure on the specified qubits.
+
+    Parameters
+    ==========
+
+    qubits : Qubit
+        The qubit to measure.  This can be any Qubit or a linear combination
+        of them.
+    bits : tuple
+        The qubits to measure.
+    format : str
+        The format of the intermediate matrices to use. Possible values are
+        ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is
+        implemented.
+
+    Returns
+    =======
+
+    result : list
+        A list that consists of primitive states and their probabilities.
+
+    Examples
+    ========
+
+        >>> from sympy.physics.quantum.qubit import Qubit, measure_partial
+        >>> from sympy.physics.quantum.gate import H
+        >>> from sympy.physics.quantum.qapply import qapply
+
+        >>> c = H(0)*H(1)*Qubit('00')
+        >>> c
+        H(0)*H(1)*|00>
+        >>> q = qapply(c)
+        >>> measure_partial(q, (0,))
+        [(sqrt(2)*|00>/2 + sqrt(2)*|10>/2, 1/2), (sqrt(2)*|01>/2 + sqrt(2)*|11>/2, 1/2)]
+    """
+    m = qubit_to_matrix(qubit, format)
+
+    if isinstance(bits, (SYMPY_INTS, Integer)):
+        bits = (int(bits),)
+
+    if format == 'sympy':
+        if normalize:
+            m = m.normalized()
+
+        possible_outcomes = _get_possible_outcomes(m, bits)
+
+        # Form output from function.
+        output = []
+        for outcome in possible_outcomes:
+            # Calculate probability of finding the specified bits with
+            # given values.
+            prob_of_outcome = 0
+            prob_of_outcome += (outcome.H*outcome)[0]
+
+            # If the output has a chance, append it to output with found
+            # probability.
+            if prob_of_outcome != 0:
+                if normalize:
+                    next_matrix = matrix_to_qubit(outcome.normalized())
+                else:
+                    next_matrix = matrix_to_qubit(outcome)
+
+                output.append((
+                    next_matrix,
+                    prob_of_outcome
+                ))
+
+        return output
+    else:
+        raise NotImplementedError(
+            "This function cannot handle non-SymPy matrix formats yet"
+        )
+
+
+def measure_partial_oneshot(qubit, bits, format='sympy'):
+    """Perform a partial oneshot measurement on the specified qubits.
+
+    A oneshot measurement is equivalent to performing a measurement on a
+    quantum system. This type of measurement does not return the probabilities
+    like an ensemble measurement does, but rather returns *one* of the
+    possible resulting states. The exact state that is returned is determined
+    by picking a state randomly according to the ensemble probabilities.
+
+    Parameters
+    ----------
+    qubits : Qubit
+        The qubit to measure.  This can be any Qubit or a linear combination
+        of them.
+    bits : tuple
+        The qubits to measure.
+    format : str
+        The format of the intermediate matrices to use. Possible values are
+        ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is
+        implemented.
+
+    Returns
+    -------
+    result : Qubit
+        The qubit that the system collapsed to upon measurement.
+    """
+    import random
+    m = qubit_to_matrix(qubit, format)
+
+    if format == 'sympy':
+        m = m.normalized()
+        possible_outcomes = _get_possible_outcomes(m, bits)
+
+        # Form output from function
+        random_number = random.random()
+        total_prob = 0
+        for outcome in possible_outcomes:
+            # Calculate probability of finding the specified bits
+            # with given values
+            total_prob += (outcome.H*outcome)[0]
+            if total_prob >= random_number:
+                return matrix_to_qubit(outcome.normalized())
+    else:
+        raise NotImplementedError(
+            "This function cannot handle non-SymPy matrix formats yet"
+        )
+
+
+def _get_possible_outcomes(m, bits):
+    """Get the possible states that can be produced in a measurement.
+
+    Parameters
+    ----------
+    m : Matrix
+        The matrix representing the state of the system.
+    bits : tuple, list
+        Which bits will be measured.
+
+    Returns
+    -------
+    result : list
+        The list of possible states which can occur given this measurement.
+        These are un-normalized so we can derive the probability of finding
+        this state by taking the inner product with itself
+    """
+
+    # This is filled with loads of dirty binary tricks...You have been warned
+
+    size = max(m.shape)  # Max of shape to account for bra or ket
+    nqubits = int(math.log2(size) + .1)  # Number of qubits possible
+
+    # Make the output states and put in output_matrices, nothing in them now.
+    # Each state will represent a possible outcome of the measurement
+    # Thus, output_matrices[0] is the matrix which we get when all measured
+    # bits return 0. and output_matrices[1] is the matrix for only the 0th
+    # bit being true
+    output_matrices = []
+    for i in range(1 << len(bits)):
+        output_matrices.append(zeros(2**nqubits, 1))
+
+    # Bitmasks will help sort how to determine possible outcomes.
+    # When the bit mask is and-ed with a matrix-index,
+    # it will determine which state that index belongs to
+    bit_masks = []
+    for bit in bits:
+        bit_masks.append(1 << bit)
+
+    # Make possible outcome states
+    for i in range(2**nqubits):
+        trueness = 0  # This tells us to which output_matrix this value belongs
+        # Find trueness
+        for j in range(len(bit_masks)):
+            if i & bit_masks[j]:
+                trueness += j + 1
+        # Put the value in the correct output matrix
+        output_matrices[trueness][i] = m[i]
+    return output_matrices
+
+
+def measure_all_oneshot(qubit, format='sympy'):
+    """Perform a oneshot ensemble measurement on all qubits.
+
+    A oneshot measurement is equivalent to performing a measurement on a
+    quantum system. This type of measurement does not return the probabilities
+    like an ensemble measurement does, but rather returns *one* of the
+    possible resulting states. The exact state that is returned is determined
+    by picking a state randomly according to the ensemble probabilities.
+
+    Parameters
+    ----------
+    qubits : Qubit
+        The qubit to measure.  This can be any Qubit or a linear combination
+        of them.
+    format : str
+        The format of the intermediate matrices to use. Possible values are
+        ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is
+        implemented.
+
+    Returns
+    -------
+    result : Qubit
+        The qubit that the system collapsed to upon measurement.
+    """
+    import random
+    m = qubit_to_matrix(qubit)
+
+    if format == 'sympy':
+        m = m.normalized()
+        random_number = random.random()
+        total = 0
+        result = 0
+        for i in m:
+            total += i*i.conjugate()
+            if total > random_number:
+                break
+            result += 1
+        return Qubit(IntQubit(result, nqubits=int(math.log2(max(m.shape)) + .1)))
+    else:
+        raise NotImplementedError(
+            "This function cannot handle non-SymPy matrix formats yet"
+        )
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/represent.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/represent.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a1ada80aa6a3dd2caad43ec132fb9a148947106
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/represent.py
@@ -0,0 +1,574 @@
+"""Logic for representing operators in state in various bases.
+
+TODO:
+
+* Get represent working with continuous hilbert spaces.
+* Document default basis functionality.
+"""
+
+from sympy.core.add import Add
+from sympy.core.expr import Expr
+from sympy.core.mul import Mul
+from sympy.core.numbers import I
+from sympy.core.power import Pow
+from sympy.integrals.integrals import integrate
+from sympy.physics.quantum.dagger import Dagger
+from sympy.physics.quantum.commutator import Commutator
+from sympy.physics.quantum.anticommutator import AntiCommutator
+from sympy.physics.quantum.innerproduct import InnerProduct
+from sympy.physics.quantum.qexpr import QExpr
+from sympy.physics.quantum.tensorproduct import TensorProduct
+from sympy.physics.quantum.matrixutils import flatten_scalar
+from sympy.physics.quantum.state import KetBase, BraBase, StateBase
+from sympy.physics.quantum.operator import Operator, OuterProduct
+from sympy.physics.quantum.qapply import qapply
+from sympy.physics.quantum.operatorset import operators_to_state, state_to_operators
+
+
+__all__ = [
+    'represent',
+    'rep_innerproduct',
+    'rep_expectation',
+    'integrate_result',
+    'get_basis',
+    'enumerate_states'
+]
+
+#-----------------------------------------------------------------------------
+# Represent
+#-----------------------------------------------------------------------------
+
+
+def _sympy_to_scalar(e):
+    """Convert from a SymPy scalar to a Python scalar."""
+    if isinstance(e, Expr):
+        if e.is_Integer:
+            return int(e)
+        elif e.is_Float:
+            return float(e)
+        elif e.is_Rational:
+            return float(e)
+        elif e.is_Number or e.is_NumberSymbol or e == I:
+            return complex(e)
+    raise TypeError('Expected number, got: %r' % e)
+
+
+def represent(expr, **options):
+    """Represent the quantum expression in the given basis.
+
+    In quantum mechanics abstract states and operators can be represented in
+    various basis sets. Under this operation the follow transforms happen:
+
+    * Ket -> column vector or function
+    * Bra -> row vector of function
+    * Operator -> matrix or differential operator
+
+    This function is the top-level interface for this action.
+
+    This function walks the SymPy expression tree looking for ``QExpr``
+    instances that have a ``_represent`` method. This method is then called
+    and the object is replaced by the representation returned by this method.
+    By default, the ``_represent`` method will dispatch to other methods
+    that handle the representation logic for a particular basis set. The
+    naming convention for these methods is the following::
+
+        def _represent_FooBasis(self, e, basis, **options)
+
+    This function will have the logic for representing instances of its class
+    in the basis set having a class named ``FooBasis``.
+
+    Parameters
+    ==========
+
+    expr  : Expr
+        The expression to represent.
+    basis : Operator, basis set
+        An object that contains the information about the basis set. If an
+        operator is used, the basis is assumed to be the orthonormal
+        eigenvectors of that operator. In general though, the basis argument
+        can be any object that contains the basis set information.
+    options : dict
+        Key/value pairs of options that are passed to the underlying method
+        that finds the representation. These options can be used to
+        control how the representation is done. For example, this is where
+        the size of the basis set would be set.
+
+    Returns
+    =======
+
+    e : Expr
+        The SymPy expression of the represented quantum expression.
+
+    Examples
+    ========
+
+    Here we subclass ``Operator`` and ``Ket`` to create the z-spin operator
+    and its spin 1/2 up eigenstate. By defining the ``_represent_SzOp``
+    method, the ket can be represented in the z-spin basis.
+
+    >>> from sympy.physics.quantum import Operator, represent, Ket
+    >>> from sympy import Matrix
+
+    >>> class SzUpKet(Ket):
+    ...     def _represent_SzOp(self, basis, **options):
+    ...         return Matrix([1,0])
+    ...
+    >>> class SzOp(Operator):
+    ...     pass
+    ...
+    >>> sz = SzOp('Sz')
+    >>> up = SzUpKet('up')
+    >>> represent(up, basis=sz)
+    Matrix([
+    [1],
+    [0]])
+
+    Here we see an example of representations in a continuous
+    basis. We see that the result of representing various combinations
+    of cartesian position operators and kets give us continuous
+    expressions involving DiracDelta functions.
+
+    >>> from sympy.physics.quantum.cartesian import XOp, XKet, XBra
+    >>> X = XOp()
+    >>> x = XKet()
+    >>> y = XBra('y')
+    >>> represent(X*x)
+    x*DiracDelta(x - x_2)
+    """
+
+    format = options.get('format', 'sympy')
+    if format == 'numpy':
+        import numpy as np
+    if isinstance(expr, QExpr) and not isinstance(expr, OuterProduct):
+        options['replace_none'] = False
+        temp_basis = get_basis(expr, **options)
+        if temp_basis is not None:
+            options['basis'] = temp_basis
+        try:
+            return expr._represent(**options)
+        except NotImplementedError as strerr:
+            #If no _represent_FOO method exists, map to the
+            #appropriate basis state and try
+            #the other methods of representation
+            options['replace_none'] = True
+
+            if isinstance(expr, (KetBase, BraBase)):
+                try:
+                    return rep_innerproduct(expr, **options)
+                except NotImplementedError:
+                    raise NotImplementedError(strerr)
+            elif isinstance(expr, Operator):
+                try:
+                    return rep_expectation(expr, **options)
+                except NotImplementedError:
+                    raise NotImplementedError(strerr)
+            else:
+                raise NotImplementedError(strerr)
+    elif isinstance(expr, Add):
+        result = represent(expr.args[0], **options)
+        for args in expr.args[1:]:
+            # scipy.sparse doesn't support += so we use plain = here.
+            result = result + represent(args, **options)
+        return result
+    elif isinstance(expr, Pow):
+        base, exp = expr.as_base_exp()
+        if format in ('numpy', 'scipy.sparse'):
+            exp = _sympy_to_scalar(exp)
+        base = represent(base, **options)
+        # scipy.sparse doesn't support negative exponents
+        # and warns when inverting a matrix in csr format.
+        if format == 'scipy.sparse' and exp < 0:
+            from scipy.sparse.linalg import inv
+            exp = - exp
+            base = inv(base.tocsc()).tocsr()
+        if format == 'numpy':
+            return np.linalg.matrix_power(base, exp)
+        return base ** exp
+    elif isinstance(expr, TensorProduct):
+        new_args = [represent(arg, **options) for arg in expr.args]
+        return TensorProduct(*new_args)
+    elif isinstance(expr, Dagger):
+        return Dagger(represent(expr.args[0], **options))
+    elif isinstance(expr, Commutator):
+        A = expr.args[0]
+        B = expr.args[1]
+        return represent(Mul(A, B) - Mul(B, A), **options)
+    elif isinstance(expr, AntiCommutator):
+        A = expr.args[0]
+        B = expr.args[1]
+        return represent(Mul(A, B) + Mul(B, A), **options)
+    elif not isinstance(expr, (Mul, OuterProduct, InnerProduct)):
+        # We have removed special handling of inner products that used to be
+        # required (before automatic transforms).
+        # For numpy and scipy.sparse, we can only handle numerical prefactors.
+        if format in ('numpy', 'scipy.sparse'):
+            return _sympy_to_scalar(expr)
+        return expr
+
+    if not isinstance(expr, (Mul, OuterProduct, InnerProduct)):
+        raise TypeError('Mul expected, got: %r' % expr)
+
+    if "index" in options:
+        options["index"] += 1
+    else:
+        options["index"] = 1
+
+    if "unities" not in options:
+        options["unities"] = []
+
+    result = represent(expr.args[-1], **options)
+    last_arg = expr.args[-1]
+
+    for arg in reversed(expr.args[:-1]):
+        if isinstance(last_arg, Operator):
+            options["index"] += 1
+            options["unities"].append(options["index"])
+        elif isinstance(last_arg, BraBase) and isinstance(arg, KetBase):
+            options["index"] += 1
+        elif isinstance(last_arg, KetBase) and isinstance(arg, Operator):
+            options["unities"].append(options["index"])
+        elif isinstance(last_arg, KetBase) and isinstance(arg, BraBase):
+            options["unities"].append(options["index"])
+
+        next_arg = represent(arg, **options)
+        if format == 'numpy' and isinstance(next_arg, np.ndarray):
+            # Must use np.matmult to "matrix multiply" two np.ndarray
+            result = np.matmul(next_arg, result)
+        else:
+            result = next_arg*result
+        last_arg = arg
+
+    # All three matrix formats create 1 by 1 matrices when inner products of
+    # vectors are taken. In these cases, we simply return a scalar.
+    result = flatten_scalar(result)
+
+    result = integrate_result(expr, result, **options)
+
+    return result
+
+
+def rep_innerproduct(expr, **options):
+    """
+    Returns an innerproduct like representation (e.g. ````) for the
+    given state.
+
+    Attempts to calculate inner product with a bra from the specified
+    basis. Should only be passed an instance of KetBase or BraBase
+
+    Parameters
+    ==========
+
+    expr : KetBase or BraBase
+        The expression to be represented
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum.represent import rep_innerproduct
+    >>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet
+    >>> rep_innerproduct(XKet())
+    DiracDelta(x - x_1)
+    >>> rep_innerproduct(XKet(), basis=PxOp())
+    sqrt(2)*exp(-I*px_1*x/hbar)/(2*sqrt(hbar)*sqrt(pi))
+    >>> rep_innerproduct(PxKet(), basis=XOp())
+    sqrt(2)*exp(I*px*x_1/hbar)/(2*sqrt(hbar)*sqrt(pi))
+
+    """
+
+    if not isinstance(expr, (KetBase, BraBase)):
+        raise TypeError("expr passed is not a Bra or Ket")
+
+    basis = get_basis(expr, **options)
+
+    if not isinstance(basis, StateBase):
+        raise NotImplementedError("Can't form this representation!")
+
+    if "index" not in options:
+        options["index"] = 1
+
+    basis_kets = enumerate_states(basis, options["index"], 2)
+
+    if isinstance(expr, BraBase):
+        bra = expr
+        ket = (basis_kets[1] if basis_kets[0].dual == expr else basis_kets[0])
+    else:
+        bra = (basis_kets[1].dual if basis_kets[0]
+               == expr else basis_kets[0].dual)
+        ket = expr
+
+    prod = InnerProduct(bra, ket)
+    result = prod.doit()
+
+    format = options.get('format', 'sympy')
+    result = expr._format_represent(result, format)
+    return result
+
+
+def rep_expectation(expr, **options):
+    """
+    Returns an ```` type representation for the given operator.
+
+    Parameters
+    ==========
+
+    expr : Operator
+        Operator to be represented in the specified basis
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum.cartesian import XOp, PxOp, PxKet
+    >>> from sympy.physics.quantum.represent import rep_expectation
+    >>> rep_expectation(XOp())
+    x_1*DiracDelta(x_1 - x_2)
+    >>> rep_expectation(XOp(), basis=PxOp())
+    
+    >>> rep_expectation(XOp(), basis=PxKet())
+    
+
+    """
+
+    if "index" not in options:
+        options["index"] = 1
+
+    if not isinstance(expr, Operator):
+        raise TypeError("The passed expression is not an operator")
+
+    basis_state = get_basis(expr, **options)
+
+    if basis_state is None or not isinstance(basis_state, StateBase):
+        raise NotImplementedError("Could not get basis kets for this operator")
+
+    basis_kets = enumerate_states(basis_state, options["index"], 2)
+
+    bra = basis_kets[1].dual
+    ket = basis_kets[0]
+
+    result = qapply(bra*expr*ket)
+    return result
+
+
+def integrate_result(orig_expr, result, **options):
+    """
+    Returns the result of integrating over any unities ``(|x>>> from sympy import symbols, DiracDelta
+    >>> from sympy.physics.quantum.represent import integrate_result
+    >>> from sympy.physics.quantum.cartesian import XOp, XKet
+    >>> x_ket = XKet()
+    >>> X_op = XOp()
+    >>> x, x_1, x_2 = symbols('x, x_1, x_2')
+    >>> integrate_result(X_op*x_ket, x*DiracDelta(x-x_1)*DiracDelta(x_1-x_2))
+    x*DiracDelta(x - x_1)*DiracDelta(x_1 - x_2)
+    >>> integrate_result(X_op*x_ket, x*DiracDelta(x-x_1)*DiracDelta(x_1-x_2),
+    ...     unities=[1])
+    x*DiracDelta(x - x_2)
+
+    """
+    if not isinstance(result, Expr):
+        return result
+
+    options['replace_none'] = True
+    if "basis" not in options:
+        arg = orig_expr.args[-1]
+        options["basis"] = get_basis(arg, **options)
+    elif not isinstance(options["basis"], StateBase):
+        options["basis"] = get_basis(orig_expr, **options)
+
+    basis = options.pop("basis", None)
+
+    if basis is None:
+        return result
+
+    unities = options.pop("unities", [])
+
+    if len(unities) == 0:
+        return result
+
+    kets = enumerate_states(basis, unities)
+    coords = [k.label[0] for k in kets]
+
+    for coord in coords:
+        if coord in result.free_symbols:
+            #TODO: Add support for sets of operators
+            basis_op = state_to_operators(basis)
+            start = basis_op.hilbert_space.interval.start
+            end = basis_op.hilbert_space.interval.end
+            result = integrate(result, (coord, start, end))
+
+    return result
+
+
+def get_basis(expr, *, basis=None, replace_none=True, **options):
+    """
+    Returns a basis state instance corresponding to the basis specified in
+    options=s. If no basis is specified, the function tries to form a default
+    basis state of the given expression.
+
+    There are three behaviors:
+
+    1. The basis specified in options is already an instance of StateBase. If
+       this is the case, it is simply returned. If the class is specified but
+       not an instance, a default instance is returned.
+
+    2. The basis specified is an operator or set of operators. If this
+       is the case, the operator_to_state mapping method is used.
+
+    3. No basis is specified. If expr is a state, then a default instance of
+       its class is returned.  If expr is an operator, then it is mapped to the
+       corresponding state.  If it is neither, then we cannot obtain the basis
+       state.
+
+    If the basis cannot be mapped, then it is not changed.
+
+    This will be called from within represent, and represent will
+    only pass QExpr's.
+
+    TODO (?): Support for Muls and other types of expressions?
+
+    Parameters
+    ==========
+
+    expr : Operator or StateBase
+        Expression whose basis is sought
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum.represent import get_basis
+    >>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet
+    >>> x = XKet()
+    >>> X = XOp()
+    >>> get_basis(x)
+    |x>
+    >>> get_basis(X)
+    |x>
+    >>> get_basis(x, basis=PxOp())
+    |px>
+    >>> get_basis(x, basis=PxKet)
+    |px>
+
+    """
+
+    if basis is None and not replace_none:
+        return None
+
+    if basis is None:
+        if isinstance(expr, KetBase):
+            return _make_default(expr.__class__)
+        elif isinstance(expr, BraBase):
+            return _make_default(expr.dual_class())
+        elif isinstance(expr, Operator):
+            state_inst = operators_to_state(expr)
+            return (state_inst if state_inst is not None else None)
+        else:
+            return None
+    elif (isinstance(basis, Operator) or
+          (not isinstance(basis, StateBase) and issubclass(basis, Operator))):
+        state = operators_to_state(basis)
+        if state is None:
+            return None
+        elif isinstance(state, StateBase):
+            return state
+        else:
+            return _make_default(state)
+    elif isinstance(basis, StateBase):
+        return basis
+    elif issubclass(basis, StateBase):
+        return _make_default(basis)
+    else:
+        return None
+
+
+def _make_default(expr):
+    # XXX: Catching TypeError like this is a bad way of distinguishing
+    # instances from classes. The logic using this function should be
+    # rewritten somehow.
+    try:
+        expr = expr()
+    except TypeError:
+        return expr
+
+    return expr
+
+
+def enumerate_states(*args, **options):
+    """
+    Returns instances of the given state with dummy indices appended
+
+    Operates in two different modes:
+
+    1. Two arguments are passed to it. The first is the base state which is to
+       be indexed, and the second argument is a list of indices to append.
+
+    2. Three arguments are passed. The first is again the base state to be
+       indexed. The second is the start index for counting.  The final argument
+       is the number of kets you wish to receive.
+
+    Tries to call state._enumerate_state. If this fails, returns an empty list
+
+    Parameters
+    ==========
+
+    args : list
+        See list of operation modes above for explanation
+
+    Examples
+    ========
+
+    >>> from sympy.physics.quantum.cartesian import XBra, XKet
+    >>> from sympy.physics.quantum.represent import enumerate_states
+    >>> test = XKet('foo')
+    >>> enumerate_states(test, 1, 3)
+    [|foo_1>, |foo_2>, |foo_3>]
+    >>> test2 = XBra('bar')
+    >>> enumerate_states(test2, [4, 5, 10])
+    [>> from sympy.physics.quantum.sho1d import RaisingOp
+        >>> from sympy.physics.quantum import Dagger
+
+        >>> ad = RaisingOp('a')
+        >>> ad.rewrite('xp').doit()
+        sqrt(2)*(m*omega*X - I*Px)/(2*sqrt(hbar)*sqrt(m*omega))
+
+        >>> Dagger(ad)
+        a
+
+    Taking the commutator of a^dagger with other Operators:
+
+        >>> from sympy.physics.quantum import Commutator
+        >>> from sympy.physics.quantum.sho1d import RaisingOp, LoweringOp
+        >>> from sympy.physics.quantum.sho1d import NumberOp
+
+        >>> ad = RaisingOp('a')
+        >>> a = LoweringOp('a')
+        >>> N = NumberOp('N')
+        >>> Commutator(ad, a).doit()
+        -1
+        >>> Commutator(ad, N).doit()
+        -RaisingOp(a)
+
+    Apply a^dagger to a state:
+
+        >>> from sympy.physics.quantum import qapply
+        >>> from sympy.physics.quantum.sho1d import RaisingOp, SHOKet
+
+        >>> ad = RaisingOp('a')
+        >>> k = SHOKet('k')
+        >>> qapply(ad*k)
+        sqrt(k + 1)*|k + 1>
+
+    Matrix Representation
+
+        >>> from sympy.physics.quantum.sho1d import RaisingOp
+        >>> from sympy.physics.quantum.represent import represent
+        >>> ad = RaisingOp('a')
+        >>> represent(ad, basis=N, ndim=4, format='sympy')
+        Matrix([
+        [0,       0,       0, 0],
+        [1,       0,       0, 0],
+        [0, sqrt(2),       0, 0],
+        [0,       0, sqrt(3), 0]])
+
+    """
+
+    def _eval_rewrite_as_xp(self, *args, **kwargs):
+        return (S.One/sqrt(Integer(2)*hbar*m*omega))*(
+            S.NegativeOne*I*Px + m*omega*X)
+
+    def _eval_adjoint(self):
+        return LoweringOp(*self.args)
+
+    def _eval_commutator_LoweringOp(self, other):
+        return S.NegativeOne
+
+    def _eval_commutator_NumberOp(self, other):
+        return S.NegativeOne*self
+
+    def _apply_operator_SHOKet(self, ket, **options):
+        temp = ket.n + S.One
+        return sqrt(temp)*SHOKet(temp)
+
+    def _represent_default_basis(self, **options):
+        return self._represent_NumberOp(None, **options)
+
+    def _represent_XOp(self, basis, **options):
+        # This logic is good but the underlying position
+        # representation logic is broken.
+        # temp = self.rewrite('xp').doit()
+        # result = represent(temp, basis=X)
+        # return result
+        raise NotImplementedError('Position representation is not implemented')
+
+    def _represent_NumberOp(self, basis, **options):
+        ndim_info = options.get('ndim', 4)
+        format = options.get('format','sympy')
+        matrix = matrix_zeros(ndim_info, ndim_info, **options)
+        for i in range(ndim_info - 1):
+            value = sqrt(i + 1)
+            if format == 'scipy.sparse':
+                value = float(value)
+            matrix[i + 1, i] = value
+        if format == 'scipy.sparse':
+            matrix = matrix.tocsr()
+        return matrix
+
+    #--------------------------------------------------------------------------
+    # Printing Methods
+    #--------------------------------------------------------------------------
+
+    def _print_contents(self, printer, *args):
+        arg0 = printer._print(self.args[0], *args)
+        return '%s(%s)' % (self.__class__.__name__, arg0)
+
+    def _print_contents_pretty(self, printer, *args):
+        from sympy.printing.pretty.stringpict import prettyForm
+        pform = printer._print(self.args[0], *args)
+        pform = pform**prettyForm('\N{DAGGER}')
+        return pform
+
+    def _print_contents_latex(self, printer, *args):
+        arg = printer._print(self.args[0])
+        return '%s^{\\dagger}' % arg
+
+class LoweringOp(SHOOp):
+    """The Lowering Operator or 'a'.
+
+    When 'a' acts on a state it lowers the state up by one. Taking
+    the adjoint of 'a' returns a^dagger, the Raising Operator. 'a'
+    can be rewritten in terms of position and momentum. We can
+    represent 'a' as a matrix, which will be its default basis.
+
+    Parameters
+    ==========
+
+    args : tuple
+        The list of numbers or parameters that uniquely specify the
+        operator.
+
+    Examples
+    ========
+
+    Create a Lowering Operator and rewrite it in terms of position and
+    momentum, and show that taking its adjoint returns a^dagger:
+
+        >>> from sympy.physics.quantum.sho1d import LoweringOp
+        >>> from sympy.physics.quantum import Dagger
+
+        >>> a = LoweringOp('a')
+        >>> a.rewrite('xp').doit()
+        sqrt(2)*(m*omega*X + I*Px)/(2*sqrt(hbar)*sqrt(m*omega))
+
+        >>> Dagger(a)
+        RaisingOp(a)
+
+    Taking the commutator of 'a' with other Operators:
+
+        >>> from sympy.physics.quantum import Commutator
+        >>> from sympy.physics.quantum.sho1d import LoweringOp, RaisingOp
+        >>> from sympy.physics.quantum.sho1d import NumberOp
+
+        >>> a = LoweringOp('a')
+        >>> ad = RaisingOp('a')
+        >>> N = NumberOp('N')
+        >>> Commutator(a, ad).doit()
+        1
+        >>> Commutator(a, N).doit()
+        a
+
+    Apply 'a' to a state:
+
+        >>> from sympy.physics.quantum import qapply
+        >>> from sympy.physics.quantum.sho1d import LoweringOp, SHOKet
+
+        >>> a = LoweringOp('a')
+        >>> k = SHOKet('k')
+        >>> qapply(a*k)
+        sqrt(k)*|k - 1>
+
+    Taking 'a' of the lowest state will return 0:
+
+        >>> from sympy.physics.quantum import qapply
+        >>> from sympy.physics.quantum.sho1d import LoweringOp, SHOKet
+
+        >>> a = LoweringOp('a')
+        >>> k = SHOKet(0)
+        >>> qapply(a*k)
+        0
+
+    Matrix Representation
+
+        >>> from sympy.physics.quantum.sho1d import LoweringOp
+        >>> from sympy.physics.quantum.represent import represent
+        >>> a = LoweringOp('a')
+        >>> represent(a, basis=N, ndim=4, format='sympy')
+        Matrix([
+        [0, 1,       0,       0],
+        [0, 0, sqrt(2),       0],
+        [0, 0,       0, sqrt(3)],
+        [0, 0,       0,       0]])
+
+    """
+
+    def _eval_rewrite_as_xp(self, *args, **kwargs):
+        return (S.One/sqrt(Integer(2)*hbar*m*omega))*(
+            I*Px + m*omega*X)
+
+    def _eval_adjoint(self):
+        return RaisingOp(*self.args)
+
+    def _eval_commutator_RaisingOp(self, other):
+        return S.One
+
+    def _eval_commutator_NumberOp(self, other):
+        return self
+
+    def _apply_operator_SHOKet(self, ket, **options):
+        temp = ket.n - Integer(1)
+        if ket.n is S.Zero:
+            return S.Zero
+        else:
+            return sqrt(ket.n)*SHOKet(temp)
+
+    def _represent_default_basis(self, **options):
+        return self._represent_NumberOp(None, **options)
+
+    def _represent_XOp(self, basis, **options):
+        # This logic is good but the underlying position
+        # representation logic is broken.
+        # temp = self.rewrite('xp').doit()
+        # result = represent(temp, basis=X)
+        # return result
+        raise NotImplementedError('Position representation is not implemented')
+
+    def _represent_NumberOp(self, basis, **options):
+        ndim_info = options.get('ndim', 4)
+        format = options.get('format', 'sympy')
+        matrix = matrix_zeros(ndim_info, ndim_info, **options)
+        for i in range(ndim_info - 1):
+            value = sqrt(i + 1)
+            if format == 'scipy.sparse':
+                value = float(value)
+            matrix[i,i + 1] = value
+        if format == 'scipy.sparse':
+            matrix = matrix.tocsr()
+        return matrix
+
+
+class NumberOp(SHOOp):
+    """The Number Operator is simply a^dagger*a
+
+    It is often useful to write a^dagger*a as simply the Number Operator
+    because the Number Operator commutes with the Hamiltonian. And can be
+    expressed using the Number Operator. Also the Number Operator can be
+    applied to states. We can represent the Number Operator as a matrix,
+    which will be its default basis.
+
+    Parameters
+    ==========
+
+    args : tuple
+        The list of numbers or parameters that uniquely specify the
+        operator.
+
+    Examples
+    ========
+
+    Create a Number Operator and rewrite it in terms of the ladder
+    operators, position and momentum operators, and Hamiltonian:
+
+        >>> from sympy.physics.quantum.sho1d import NumberOp
+
+        >>> N = NumberOp('N')
+        >>> N.rewrite('a').doit()
+        RaisingOp(a)*a
+        >>> N.rewrite('xp').doit()
+        -1/2 + (m**2*omega**2*X**2 + Px**2)/(2*hbar*m*omega)
+        >>> N.rewrite('H').doit()
+        -1/2 + H/(hbar*omega)
+
+    Take the Commutator of the Number Operator with other Operators:
+
+        >>> from sympy.physics.quantum import Commutator
+        >>> from sympy.physics.quantum.sho1d import NumberOp, Hamiltonian
+        >>> from sympy.physics.quantum.sho1d import RaisingOp, LoweringOp
+
+        >>> N = NumberOp('N')
+        >>> H = Hamiltonian('H')
+        >>> ad = RaisingOp('a')
+        >>> a = LoweringOp('a')
+        >>> Commutator(N,H).doit()
+        0
+        >>> Commutator(N,ad).doit()
+        RaisingOp(a)
+        >>> Commutator(N,a).doit()
+        -a
+
+    Apply the Number Operator to a state:
+
+        >>> from sympy.physics.quantum import qapply
+        >>> from sympy.physics.quantum.sho1d import NumberOp, SHOKet
+
+        >>> N = NumberOp('N')
+        >>> k = SHOKet('k')
+        >>> qapply(N*k)
+        k*|k>
+
+    Matrix Representation
+
+        >>> from sympy.physics.quantum.sho1d import NumberOp
+        >>> from sympy.physics.quantum.represent import represent
+        >>> N = NumberOp('N')
+        >>> represent(N, basis=N, ndim=4, format='sympy')
+        Matrix([
+        [0, 0, 0, 0],
+        [0, 1, 0, 0],
+        [0, 0, 2, 0],
+        [0, 0, 0, 3]])
+
+    """
+
+    def _eval_rewrite_as_a(self, *args, **kwargs):
+        return ad*a
+
+    def _eval_rewrite_as_xp(self, *args, **kwargs):
+        return (S.One/(Integer(2)*m*hbar*omega))*(Px**2 + (
+            m*omega*X)**2) - S.Half
+
+    def _eval_rewrite_as_H(self, *args, **kwargs):
+        return H/(hbar*omega) - S.Half
+
+    def _apply_operator_SHOKet(self, ket, **options):
+        return ket.n*ket
+
+    def _eval_commutator_Hamiltonian(self, other):
+        return S.Zero
+
+    def _eval_commutator_RaisingOp(self, other):
+        return other
+
+    def _eval_commutator_LoweringOp(self, other):
+        return S.NegativeOne*other
+
+    def _represent_default_basis(self, **options):
+        return self._represent_NumberOp(None, **options)
+
+    def _represent_XOp(self, basis, **options):
+        # This logic is good but the underlying position
+        # representation logic is broken.
+        # temp = self.rewrite('xp').doit()
+        # result = represent(temp, basis=X)
+        # return result
+        raise NotImplementedError('Position representation is not implemented')
+
+    def _represent_NumberOp(self, basis, **options):
+        ndim_info = options.get('ndim', 4)
+        format = options.get('format', 'sympy')
+        matrix = matrix_zeros(ndim_info, ndim_info, **options)
+        for i in range(ndim_info):
+            value = i
+            if format == 'scipy.sparse':
+                value = float(value)
+            matrix[i,i] = value
+        if format == 'scipy.sparse':
+            matrix = matrix.tocsr()
+        return matrix
+
+
+class Hamiltonian(SHOOp):
+    """The Hamiltonian Operator.
+
+    The Hamiltonian is used to solve the time-independent Schrodinger
+    equation. The Hamiltonian can be expressed using the ladder operators,
+    as well as by position and momentum. We can represent the Hamiltonian
+    Operator as a matrix, which will be its default basis.
+
+    Parameters
+    ==========
+
+    args : tuple
+        The list of numbers or parameters that uniquely specify the
+        operator.
+
+    Examples
+    ========
+
+    Create a Hamiltonian Operator and rewrite it in terms of the ladder
+    operators, position and momentum, and the Number Operator:
+
+        >>> from sympy.physics.quantum.sho1d import Hamiltonian
+
+        >>> H = Hamiltonian('H')
+        >>> H.rewrite('a').doit()
+        hbar*omega*(1/2 + RaisingOp(a)*a)
+        >>> H.rewrite('xp').doit()
+        (m**2*omega**2*X**2 + Px**2)/(2*m)
+        >>> H.rewrite('N').doit()
+        hbar*omega*(1/2 + N)
+
+    Take the Commutator of the Hamiltonian and the Number Operator:
+
+        >>> from sympy.physics.quantum import Commutator
+        >>> from sympy.physics.quantum.sho1d import Hamiltonian, NumberOp
+
+        >>> H = Hamiltonian('H')
+        >>> N = NumberOp('N')
+        >>> Commutator(H,N).doit()
+        0
+
+    Apply the Hamiltonian Operator to a state:
+
+        >>> from sympy.physics.quantum import qapply
+        >>> from sympy.physics.quantum.sho1d import Hamiltonian, SHOKet
+
+        >>> H = Hamiltonian('H')
+        >>> k = SHOKet('k')
+        >>> qapply(H*k)
+        hbar*k*omega*|k> + hbar*omega*|k>/2
+
+    Matrix Representation
+
+        >>> from sympy.physics.quantum.sho1d import Hamiltonian
+        >>> from sympy.physics.quantum.represent import represent
+
+        >>> H = Hamiltonian('H')
+        >>> represent(H, basis=N, ndim=4, format='sympy')
+        Matrix([
+        [hbar*omega/2,              0,              0,              0],
+        [           0, 3*hbar*omega/2,              0,              0],
+        [           0,              0, 5*hbar*omega/2,              0],
+        [           0,              0,              0, 7*hbar*omega/2]])
+
+    """
+
+    def _eval_rewrite_as_a(self, *args, **kwargs):
+        return hbar*omega*(ad*a + S.Half)
+
+    def _eval_rewrite_as_xp(self, *args, **kwargs):
+        return (S.One/(Integer(2)*m))*(Px**2 + (m*omega*X)**2)
+
+    def _eval_rewrite_as_N(self, *args, **kwargs):
+        return hbar*omega*(N + S.Half)
+
+    def _apply_operator_SHOKet(self, ket, **options):
+        return (hbar*omega*(ket.n + S.Half))*ket
+
+    def _eval_commutator_NumberOp(self, other):
+        return S.Zero
+
+    def _represent_default_basis(self, **options):
+        return self._represent_NumberOp(None, **options)
+
+    def _represent_XOp(self, basis, **options):
+        # This logic is good but the underlying position
+        # representation logic is broken.
+        # temp = self.rewrite('xp').doit()
+        # result = represent(temp, basis=X)
+        # return result
+        raise NotImplementedError('Position representation is not implemented')
+
+    def _represent_NumberOp(self, basis, **options):
+        ndim_info = options.get('ndim', 4)
+        format = options.get('format', 'sympy')
+        matrix = matrix_zeros(ndim_info, ndim_info, **options)
+        for i in range(ndim_info):
+            value = i + S.Half
+            if format == 'scipy.sparse':
+                value = float(value)
+            matrix[i,i] = value
+        if format == 'scipy.sparse':
+            matrix = matrix.tocsr()
+        return hbar*omega*matrix
+
+#------------------------------------------------------------------------------
+
+class SHOState(State):
+    """State class for SHO states"""
+
+    @classmethod
+    def _eval_hilbert_space(cls, label):
+        return ComplexSpace(S.Infinity)
+
+    @property
+    def n(self):
+        return self.args[0]
+
+
+class SHOKet(SHOState, Ket):
+    """1D eigenket.
+
+    Inherits from SHOState and Ket.
+
+    Parameters
+    ==========
+
+    args : tuple
+        The list of numbers or parameters that uniquely specify the ket
+        This is usually its quantum numbers or its symbol.
+
+    Examples
+    ========
+
+    Ket's know about their associated bra:
+
+        >>> from sympy.physics.quantum.sho1d import SHOKet
+
+        >>> k = SHOKet('k')
+        >>> k.dual
+        >> k.dual_class()
+        
+
+    Take the Inner Product with a bra:
+
+        >>> from sympy.physics.quantum import InnerProduct
+        >>> from sympy.physics.quantum.sho1d import SHOKet, SHOBra
+
+        >>> k = SHOKet('k')
+        >>> b = SHOBra('b')
+        >>> InnerProduct(b,k).doit()
+        KroneckerDelta(b, k)
+
+    Vector representation of a numerical state ket:
+
+        >>> from sympy.physics.quantum.sho1d import SHOKet, NumberOp
+        >>> from sympy.physics.quantum.represent import represent
+
+        >>> k = SHOKet(3)
+        >>> N = NumberOp('N')
+        >>> represent(k, basis=N, ndim=4)
+        Matrix([
+        [0],
+        [0],
+        [0],
+        [1]])
+
+    """
+
+    @classmethod
+    def dual_class(self):
+        return SHOBra
+
+    def _eval_innerproduct_SHOBra(self, bra, **hints):
+        result = KroneckerDelta(self.n, bra.n)
+        return result
+
+    def _represent_default_basis(self, **options):
+        return self._represent_NumberOp(None, **options)
+
+    def _represent_NumberOp(self, basis, **options):
+        ndim_info = options.get('ndim', 4)
+        format = options.get('format', 'sympy')
+        options['spmatrix'] = 'lil'
+        vector = matrix_zeros(ndim_info, 1, **options)
+        if isinstance(self.n, Integer):
+            if self.n >= ndim_info:
+                return ValueError("N-Dimension too small")
+            if format == 'scipy.sparse':
+                vector[int(self.n), 0] = 1.0
+                vector = vector.tocsr()
+            elif format == 'numpy':
+                vector[int(self.n), 0] = 1.0
+            else:
+                vector[self.n, 0] = S.One
+            return vector
+        else:
+            return ValueError("Not Numerical State")
+
+
+class SHOBra(SHOState, Bra):
+    """A time-independent Bra in SHO.
+
+    Inherits from SHOState and Bra.
+
+    Parameters
+    ==========
+
+    args : tuple
+        The list of numbers or parameters that uniquely specify the ket
+        This is usually its quantum numbers or its symbol.
+
+    Examples
+    ========
+
+    Bra's know about their associated ket:
+
+        >>> from sympy.physics.quantum.sho1d import SHOBra
+
+        >>> b = SHOBra('b')
+        >>> b.dual
+        |b>
+        >>> b.dual_class()
+        
+
+    Vector representation of a numerical state bra:
+
+        >>> from sympy.physics.quantum.sho1d import SHOBra, NumberOp
+        >>> from sympy.physics.quantum.represent import represent
+
+        >>> b = SHOBra(3)
+        >>> N = NumberOp('N')
+        >>> represent(b, basis=N, ndim=4)
+        Matrix([[0, 0, 0, 1]])
+
+    """
+
+    @classmethod
+    def dual_class(self):
+        return SHOKet
+
+    def _represent_default_basis(self, **options):
+        return self._represent_NumberOp(None, **options)
+
+    def _represent_NumberOp(self, basis, **options):
+        ndim_info = options.get('ndim', 4)
+        format = options.get('format', 'sympy')
+        options['spmatrix'] = 'lil'
+        vector = matrix_zeros(1, ndim_info, **options)
+        if isinstance(self.n, Integer):
+            if self.n >= ndim_info:
+                return ValueError("N-Dimension too small")
+            if format == 'scipy.sparse':
+                vector[0, int(self.n)] = 1.0
+                vector = vector.tocsr()
+            elif format == 'numpy':
+                vector[0, int(self.n)] = 1.0
+            else:
+                vector[0, self.n] = S.One
+            return vector
+        else:
+            return ValueError("Not Numerical State")
+
+
+ad = RaisingOp('a')
+a = LoweringOp('a')
+H = Hamiltonian('H')
+N = NumberOp('N')
+omega = Symbol('omega')
+m = Symbol('m')
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/shor.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/shor.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc9e55229d74634bdb82efc03c2d1649e088efb3
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/shor.py
@@ -0,0 +1,173 @@
+"""Shor's algorithm and helper functions.
+
+Todo:
+
+* Get the CMod gate working again using the new Gate API.
+* Fix everything.
+* Update docstrings and reformat.
+"""
+
+import math
+import random
+
+from sympy.core.mul import Mul
+from sympy.core.singleton import S
+from sympy.functions.elementary.exponential import log
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.core.intfunc import igcd
+from sympy.ntheory import continued_fraction_periodic as continued_fraction
+from sympy.utilities.iterables import variations
+
+from sympy.physics.quantum.gate import Gate
+from sympy.physics.quantum.qubit import Qubit, measure_partial_oneshot
+from sympy.physics.quantum.qapply import qapply
+from sympy.physics.quantum.qft import QFT
+from sympy.physics.quantum.qexpr import QuantumError
+
+
+class OrderFindingException(QuantumError):
+    pass
+
+
+class CMod(Gate):
+    """A controlled mod gate.
+
+    This is black box controlled Mod function for use by shor's algorithm.
+    TODO: implement a decompose property that returns how to do this in terms
+    of elementary gates
+    """
+
+    @classmethod
+    def _eval_args(cls, args):
+        # t = args[0]
+        # a = args[1]
+        # N = args[2]
+        raise NotImplementedError('The CMod gate has not been completed.')
+
+    @property
+    def t(self):
+        """Size of 1/2 input register.  First 1/2 holds output."""
+        return self.label[0]
+
+    @property
+    def a(self):
+        """Base of the controlled mod function."""
+        return self.label[1]
+
+    @property
+    def N(self):
+        """N is the type of modular arithmetic we are doing."""
+        return self.label[2]
+
+    def _apply_operator_Qubit(self, qubits, **options):
+        """
+            This directly calculates the controlled mod of the second half of
+            the register and puts it in the second
+            This will look pretty when we get Tensor Symbolically working
+        """
+        n = 1
+        k = 0
+        # Determine the value stored in high memory.
+        for i in range(self.t):
+            k += n*qubits[self.t + i]
+            n *= 2
+
+        # The value to go in low memory will be out.
+        out = int(self.a**k % self.N)
+
+        # Create array for new qbit-ket which will have high memory unaffected
+        outarray = list(qubits.args[0][:self.t])
+
+        # Place out in low memory
+        for i in reversed(range(self.t)):
+            outarray.append((out >> i) & 1)
+
+        return Qubit(*outarray)
+
+
+def shor(N):
+    """This function implements Shor's factoring algorithm on the Integer N
+
+    The algorithm starts by picking a random number (a) and seeing if it is
+    coprime with N. If it is not, then the gcd of the two numbers is a factor
+    and we are done. Otherwise, it begins the period_finding subroutine which
+    finds the period of a in modulo N arithmetic. This period, if even, can
+    be used to calculate factors by taking a**(r/2)-1 and a**(r/2)+1.
+    These values are returned.
+    """
+    a = random.randrange(N - 2) + 2
+    if igcd(N, a) != 1:
+        return igcd(N, a)
+    r = period_find(a, N)
+    if r % 2 == 1:
+        shor(N)
+    answer = (igcd(a**(r/2) - 1, N), igcd(a**(r/2) + 1, N))
+    return answer
+
+
+def getr(x, y, N):
+    fraction = continued_fraction(x, y)
+    # Now convert into r
+    total = ratioize(fraction, N)
+    return total
+
+
+def ratioize(list, N):
+    if list[0] > N:
+        return S.Zero
+    if len(list) == 1:
+        return list[0]
+    return list[0] + ratioize(list[1:], N)
+
+
+def period_find(a, N):
+    """Finds the period of a in modulo N arithmetic
+
+    This is quantum part of Shor's algorithm. It takes two registers,
+    puts first in superposition of states with Hadamards so: ``|k>|0>``
+    with k being all possible choices. It then does a controlled mod and
+    a QFT to determine the order of a.
+    """
+    epsilon = .5
+    # picks out t's such that maintains accuracy within epsilon
+    t = int(2*math.ceil(log(N, 2)))
+    # make the first half of register be 0's |000...000>
+    start = [0 for x in range(t)]
+    # Put second half into superposition of states so we have |1>x|0> + |2>x|0> + ... |k>x>|0> + ... + |2**n-1>x|0>
+    factor = 1/sqrt(2**t)
+    qubits = 0
+    for arr in variations(range(2), t, repetition=True):
+        qbitArray = list(arr) + start
+        qubits = qubits + Qubit(*qbitArray)
+    circuit = (factor*qubits).expand()
+    # Controlled second half of register so that we have:
+    # |1>x|a**1 %N> + |2>x|a**2 %N> + ... + |k>x|a**k %N >+ ... + |2**n-1=k>x|a**k % n>
+    circuit = CMod(t, a, N)*circuit
+    # will measure first half of register giving one of the a**k%N's
+
+    circuit = qapply(circuit)
+    for i in range(t):
+        circuit = measure_partial_oneshot(circuit, i)
+    # Now apply Inverse Quantum Fourier Transform on the second half of the register
+
+    circuit = qapply(QFT(t, t*2).decompose()*circuit, floatingPoint=True)
+    for i in range(t):
+        circuit = measure_partial_oneshot(circuit, i + t)
+    if isinstance(circuit, Qubit):
+        register = circuit
+    elif isinstance(circuit, Mul):
+        register = circuit.args[-1]
+    else:
+        register = circuit.args[-1].args[-1]
+
+    n = 1
+    answer = 0
+    for i in range(len(register)/2):
+        answer += n*register[i + t]
+        n = n << 1
+    if answer == 0:
+        raise OrderFindingException(
+            "Order finder returned 0. Happens with chance %f" % epsilon)
+    #turn answer into r using continued fractions
+    g = getr(answer, 2**t, N)
+    return g
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/spin.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/spin.py
new file mode 100644
index 0000000000000000000000000000000000000000..6be53d01711adbed8c078fffca1d618c1aa3c6e6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/spin.py
@@ -0,0 +1,2150 @@
+"""Quantum mechanical angular momentum."""
+
+from sympy.concrete.summations import Sum
+from sympy.core.add import Add
+from sympy.core.containers import Tuple
+from sympy.core.expr import Expr
+from sympy.core.numbers import int_valued
+from sympy.core.mul import Mul
+from sympy.core.numbers import (I, Integer, Rational, pi)
+from sympy.core.singleton import S
+from sympy.core.symbol import (Dummy, symbols)
+from sympy.core.sympify import sympify
+from sympy.functions.combinatorial.factorials import (binomial, factorial)
+from sympy.functions.elementary.exponential import exp
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import (cos, sin)
+from sympy.simplify.simplify import simplify
+from sympy.matrices import zeros
+from sympy.printing.pretty.stringpict import prettyForm, stringPict
+from sympy.printing.pretty.pretty_symbology import pretty_symbol
+
+from sympy.physics.quantum.qexpr import QExpr
+from sympy.physics.quantum.operator import (HermitianOperator, Operator,
+                                            UnitaryOperator)
+from sympy.physics.quantum.state import Bra, Ket, State
+from sympy.functions.special.tensor_functions import KroneckerDelta
+from sympy.physics.quantum.constants import hbar
+from sympy.physics.quantum.hilbert import ComplexSpace, DirectSumHilbertSpace
+from sympy.physics.quantum.tensorproduct import TensorProduct
+from sympy.physics.quantum.cg import CG
+from sympy.physics.quantum.qapply import qapply
+
+
+__all__ = [
+    'm_values',
+    'Jplus',
+    'Jminus',
+    'Jx',
+    'Jy',
+    'Jz',
+    'J2',
+    'Rotation',
+    'WignerD',
+    'JxKet',
+    'JxBra',
+    'JyKet',
+    'JyBra',
+    'JzKet',
+    'JzBra',
+    'JzOp',
+    'J2Op',
+    'JxKetCoupled',
+    'JxBraCoupled',
+    'JyKetCoupled',
+    'JyBraCoupled',
+    'JzKetCoupled',
+    'JzBraCoupled',
+    'couple',
+    'uncouple'
+]
+
+
+def m_values(j):
+    j = sympify(j)
+    size = 2*j + 1
+    if not size.is_Integer or not size > 0:
+        raise ValueError(
+            'Only integer or half-integer values allowed for j, got: : %r' % j
+        )
+    return size, [j - i for i in range(int(2*j + 1))]
+
+
+#-----------------------------------------------------------------------------
+# Spin Operators
+#-----------------------------------------------------------------------------
+
+
+class SpinOpBase:
+    """Base class for spin operators."""
+
+    @classmethod
+    def _eval_hilbert_space(cls, label):
+        # We consider all j values so our space is infinite.
+        return ComplexSpace(S.Infinity)
+
+    @property
+    def name(self):
+        return self.args[0]
+
+    def _print_contents(self, printer, *args):
+        return '%s%s' % (self.name, self._coord)
+
+    def _print_contents_pretty(self, printer, *args):
+        a = stringPict(str(self.name))
+        b = stringPict(self._coord)
+        return self._print_subscript_pretty(a, b)
+
+    def _print_contents_latex(self, printer, *args):
+        return r'%s_%s' % ((self.name, self._coord))
+
+    def _represent_base(self, basis, **options):
+        j = options.get('j', S.Half)
+        size, mvals = m_values(j)
+        result = zeros(size, size)
+        for p in range(size):
+            for q in range(size):
+                me = self.matrix_element(j, mvals[p], j, mvals[q])
+                result[p, q] = me
+        return result
+
+    def _apply_op(self, ket, orig_basis, **options):
+        state = ket.rewrite(self.basis)
+        # If the state has only one term
+        if isinstance(state, State):
+            ret = (hbar*state.m)*state
+        # state is a linear combination of states
+        elif isinstance(state, Sum):
+            ret = self._apply_operator_Sum(state, **options)
+        else:
+            ret = qapply(self*state)
+        if ret == self*state:
+            raise NotImplementedError
+        return ret.rewrite(orig_basis)
+
+    def _apply_operator_JxKet(self, ket, **options):
+        return self._apply_op(ket, 'Jx', **options)
+
+    def _apply_operator_JxKetCoupled(self, ket, **options):
+        return self._apply_op(ket, 'Jx', **options)
+
+    def _apply_operator_JyKet(self, ket, **options):
+        return self._apply_op(ket, 'Jy', **options)
+
+    def _apply_operator_JyKetCoupled(self, ket, **options):
+        return self._apply_op(ket, 'Jy', **options)
+
+    def _apply_operator_JzKet(self, ket, **options):
+        return self._apply_op(ket, 'Jz', **options)
+
+    def _apply_operator_JzKetCoupled(self, ket, **options):
+        return self._apply_op(ket, 'Jz', **options)
+
+    def _apply_operator_TensorProduct(self, tp, **options):
+        # Uncoupling operator is only easily found for coordinate basis spin operators
+        # TODO: add methods for uncoupling operators
+        if not isinstance(self, (JxOp, JyOp, JzOp)):
+            raise NotImplementedError
+        result = []
+        for n in range(len(tp.args)):
+            arg = []
+            arg.extend(tp.args[:n])
+            arg.append(self._apply_operator(tp.args[n]))
+            arg.extend(tp.args[n + 1:])
+            result.append(tp.__class__(*arg))
+        return Add(*result).expand()
+
+    # TODO: move this to qapply_Mul
+    def _apply_operator_Sum(self, s, **options):
+        new_func = qapply(self*s.function)
+        if new_func == self*s.function:
+            raise NotImplementedError
+        return Sum(new_func, *s.limits)
+
+    def _eval_trace(self, **options):
+        #TODO: use options to use different j values
+        #For now eval at default basis
+
+        # is it efficient to represent each time
+        # to do a trace?
+        return self._represent_default_basis().trace()
+
+
+class JplusOp(SpinOpBase, Operator):
+    """The J+ operator."""
+
+    _coord = '+'
+
+    basis = 'Jz'
+
+    def _eval_commutator_JminusOp(self, other):
+        return 2*hbar*JzOp(self.name)
+
+    def _apply_operator_JzKet(self, ket, **options):
+        j = ket.j
+        m = ket.m
+        if m.is_Number and j.is_Number:
+            if m >= j:
+                return S.Zero
+        return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKet(j, m + S.One)
+
+    def _apply_operator_JzKetCoupled(self, ket, **options):
+        j = ket.j
+        m = ket.m
+        jn = ket.jn
+        coupling = ket.coupling
+        if m.is_Number and j.is_Number:
+            if m >= j:
+                return S.Zero
+        return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKetCoupled(j, m + S.One, jn, coupling)
+
+    def matrix_element(self, j, m, jp, mp):
+        result = hbar*sqrt(j*(j + S.One) - mp*(mp + S.One))
+        result *= KroneckerDelta(m, mp + 1)
+        result *= KroneckerDelta(j, jp)
+        return result
+
+    def _represent_default_basis(self, **options):
+        return self._represent_JzOp(None, **options)
+
+    def _represent_JzOp(self, basis, **options):
+        return self._represent_base(basis, **options)
+
+    def _eval_rewrite_as_xyz(self, *args, **kwargs):
+        return JxOp(args[0]) + I*JyOp(args[0])
+
+
+class JminusOp(SpinOpBase, Operator):
+    """The J- operator."""
+
+    _coord = '-'
+
+    basis = 'Jz'
+
+    def _apply_operator_JzKet(self, ket, **options):
+        j = ket.j
+        m = ket.m
+        if m.is_Number and j.is_Number:
+            if m <= -j:
+                return S.Zero
+        return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKet(j, m - S.One)
+
+    def _apply_operator_JzKetCoupled(self, ket, **options):
+        j = ket.j
+        m = ket.m
+        jn = ket.jn
+        coupling = ket.coupling
+        if m.is_Number and j.is_Number:
+            if m <= -j:
+                return S.Zero
+        return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKetCoupled(j, m - S.One, jn, coupling)
+
+    def matrix_element(self, j, m, jp, mp):
+        result = hbar*sqrt(j*(j + S.One) - mp*(mp - S.One))
+        result *= KroneckerDelta(m, mp - 1)
+        result *= KroneckerDelta(j, jp)
+        return result
+
+    def _represent_default_basis(self, **options):
+        return self._represent_JzOp(None, **options)
+
+    def _represent_JzOp(self, basis, **options):
+        return self._represent_base(basis, **options)
+
+    def _eval_rewrite_as_xyz(self, *args, **kwargs):
+        return JxOp(args[0]) - I*JyOp(args[0])
+
+
+class JxOp(SpinOpBase, HermitianOperator):
+    """The Jx operator."""
+
+    _coord = 'x'
+
+    basis = 'Jx'
+
+    def _eval_commutator_JyOp(self, other):
+        return I*hbar*JzOp(self.name)
+
+    def _eval_commutator_JzOp(self, other):
+        return -I*hbar*JyOp(self.name)
+
+    def _apply_operator_JzKet(self, ket, **options):
+        jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options)
+        jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options)
+        return (jp + jm)/Integer(2)
+
+    def _apply_operator_JzKetCoupled(self, ket, **options):
+        jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
+        jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
+        return (jp + jm)/Integer(2)
+
+    def _represent_default_basis(self, **options):
+        return self._represent_JzOp(None, **options)
+
+    def _represent_JzOp(self, basis, **options):
+        jp = JplusOp(self.name)._represent_JzOp(basis, **options)
+        jm = JminusOp(self.name)._represent_JzOp(basis, **options)
+        return (jp + jm)/Integer(2)
+
+    def _eval_rewrite_as_plusminus(self, *args, **kwargs):
+        return (JplusOp(args[0]) + JminusOp(args[0]))/2
+
+
+class JyOp(SpinOpBase, HermitianOperator):
+    """The Jy operator."""
+
+    _coord = 'y'
+
+    basis = 'Jy'
+
+    def _eval_commutator_JzOp(self, other):
+        return I*hbar*JxOp(self.name)
+
+    def _eval_commutator_JxOp(self, other):
+        return -I*hbar*J2Op(self.name)
+
+    def _apply_operator_JzKet(self, ket, **options):
+        jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options)
+        jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options)
+        return (jp - jm)/(Integer(2)*I)
+
+    def _apply_operator_JzKetCoupled(self, ket, **options):
+        jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
+        jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
+        return (jp - jm)/(Integer(2)*I)
+
+    def _represent_default_basis(self, **options):
+        return self._represent_JzOp(None, **options)
+
+    def _represent_JzOp(self, basis, **options):
+        jp = JplusOp(self.name)._represent_JzOp(basis, **options)
+        jm = JminusOp(self.name)._represent_JzOp(basis, **options)
+        return (jp - jm)/(Integer(2)*I)
+
+    def _eval_rewrite_as_plusminus(self, *args, **kwargs):
+        return (JplusOp(args[0]) - JminusOp(args[0]))/(2*I)
+
+
+class JzOp(SpinOpBase, HermitianOperator):
+    """The Jz operator."""
+
+    _coord = 'z'
+
+    basis = 'Jz'
+
+    def _eval_commutator_JxOp(self, other):
+        return I*hbar*JyOp(self.name)
+
+    def _eval_commutator_JyOp(self, other):
+        return -I*hbar*JxOp(self.name)
+
+    def _eval_commutator_JplusOp(self, other):
+        return hbar*JplusOp(self.name)
+
+    def _eval_commutator_JminusOp(self, other):
+        return -hbar*JminusOp(self.name)
+
+    def matrix_element(self, j, m, jp, mp):
+        result = hbar*mp
+        result *= KroneckerDelta(m, mp)
+        result *= KroneckerDelta(j, jp)
+        return result
+
+    def _represent_default_basis(self, **options):
+        return self._represent_JzOp(None, **options)
+
+    def _represent_JzOp(self, basis, **options):
+        return self._represent_base(basis, **options)
+
+
+class J2Op(SpinOpBase, HermitianOperator):
+    """The J^2 operator."""
+
+    _coord = '2'
+
+    def _eval_commutator_JxOp(self, other):
+        return S.Zero
+
+    def _eval_commutator_JyOp(self, other):
+        return S.Zero
+
+    def _eval_commutator_JzOp(self, other):
+        return S.Zero
+
+    def _eval_commutator_JplusOp(self, other):
+        return S.Zero
+
+    def _eval_commutator_JminusOp(self, other):
+        return S.Zero
+
+    def _apply_operator_JxKet(self, ket, **options):
+        j = ket.j
+        return hbar**2*j*(j + 1)*ket
+
+    def _apply_operator_JxKetCoupled(self, ket, **options):
+        j = ket.j
+        return hbar**2*j*(j + 1)*ket
+
+    def _apply_operator_JyKet(self, ket, **options):
+        j = ket.j
+        return hbar**2*j*(j + 1)*ket
+
+    def _apply_operator_JyKetCoupled(self, ket, **options):
+        j = ket.j
+        return hbar**2*j*(j + 1)*ket
+
+    def _apply_operator_JzKet(self, ket, **options):
+        j = ket.j
+        return hbar**2*j*(j + 1)*ket
+
+    def _apply_operator_JzKetCoupled(self, ket, **options):
+        j = ket.j
+        return hbar**2*j*(j + 1)*ket
+
+    def matrix_element(self, j, m, jp, mp):
+        result = (hbar**2)*j*(j + 1)
+        result *= KroneckerDelta(m, mp)
+        result *= KroneckerDelta(j, jp)
+        return result
+
+    def _represent_default_basis(self, **options):
+        return self._represent_JzOp(None, **options)
+
+    def _represent_JzOp(self, basis, **options):
+        return self._represent_base(basis, **options)
+
+    def _print_contents_pretty(self, printer, *args):
+        a = prettyForm(str(self.name))
+        b = prettyForm('2')
+        return a**b
+
+    def _print_contents_latex(self, printer, *args):
+        return r'%s^2' % str(self.name)
+
+    def _eval_rewrite_as_xyz(self, *args, **kwargs):
+        return JxOp(args[0])**2 + JyOp(args[0])**2 + JzOp(args[0])**2
+
+    def _eval_rewrite_as_plusminus(self, *args, **kwargs):
+        a = args[0]
+        return JzOp(a)**2 + \
+            S.Half*(JplusOp(a)*JminusOp(a) + JminusOp(a)*JplusOp(a))
+
+
+class Rotation(UnitaryOperator):
+    """Wigner D operator in terms of Euler angles.
+
+    Defines the rotation operator in terms of the Euler angles defined by
+    the z-y-z convention for a passive transformation. That is the coordinate
+    axes are rotated first about the z-axis, giving the new x'-y'-z' axes. Then
+    this new coordinate system is rotated about the new y'-axis, giving new
+    x''-y''-z'' axes. Then this new coordinate system is rotated about the
+    z''-axis. Conventions follow those laid out in [1]_.
+
+    Parameters
+    ==========
+
+    alpha : Number, Symbol
+        First Euler Angle
+    beta : Number, Symbol
+        Second Euler angle
+    gamma : Number, Symbol
+        Third Euler angle
+
+    Examples
+    ========
+
+    A simple example rotation operator:
+
+        >>> from sympy import pi
+        >>> from sympy.physics.quantum.spin import Rotation
+        >>> Rotation(pi, 0, pi/2)
+        R(pi,0,pi/2)
+
+    With symbolic Euler angles and calculating the inverse rotation operator:
+
+        >>> from sympy import symbols
+        >>> a, b, c = symbols('a b c')
+        >>> Rotation(a, b, c)
+        R(a,b,c)
+        >>> Rotation(a, b, c).inverse()
+        R(-c,-b,-a)
+
+    See Also
+    ========
+
+    WignerD: Symbolic Wigner-D function
+    D: Wigner-D function
+    d: Wigner small-d function
+
+    References
+    ==========
+
+    .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
+    """
+
+    @classmethod
+    def _eval_args(cls, args):
+        args = QExpr._eval_args(args)
+        if len(args) != 3:
+            raise ValueError('3 Euler angles required, got: %r' % args)
+        return args
+
+    @classmethod
+    def _eval_hilbert_space(cls, label):
+        # We consider all j values so our space is infinite.
+        return ComplexSpace(S.Infinity)
+
+    @property
+    def alpha(self):
+        return self.label[0]
+
+    @property
+    def beta(self):
+        return self.label[1]
+
+    @property
+    def gamma(self):
+        return self.label[2]
+
+    def _print_operator_name(self, printer, *args):
+        return 'R'
+
+    def _print_operator_name_pretty(self, printer, *args):
+        if printer._use_unicode:
+            return prettyForm('\N{SCRIPT CAPITAL R}' + ' ')
+        else:
+            return prettyForm("R ")
+
+    def _print_operator_name_latex(self, printer, *args):
+        return r'\mathcal{R}'
+
+    def _eval_inverse(self):
+        return Rotation(-self.gamma, -self.beta, -self.alpha)
+
+    @classmethod
+    def D(cls, j, m, mp, alpha, beta, gamma):
+        """Wigner D-function.
+
+        Returns an instance of the WignerD class corresponding to the Wigner-D
+        function specified by the parameters.
+
+        Parameters
+        ===========
+
+        j : Number
+            Total angular momentum
+        m : Number
+            Eigenvalue of angular momentum along axis after rotation
+        mp : Number
+            Eigenvalue of angular momentum along rotated axis
+        alpha : Number, Symbol
+            First Euler angle of rotation
+        beta : Number, Symbol
+            Second Euler angle of rotation
+        gamma : Number, Symbol
+            Third Euler angle of rotation
+
+        Examples
+        ========
+
+        Return the Wigner-D matrix element for a defined rotation, both
+        numerical and symbolic:
+
+            >>> from sympy.physics.quantum.spin import Rotation
+            >>> from sympy import pi, symbols
+            >>> alpha, beta, gamma = symbols('alpha beta gamma')
+            >>> Rotation.D(1, 1, 0,pi, pi/2,-pi)
+            WignerD(1, 1, 0, pi, pi/2, -pi)
+
+        See Also
+        ========
+
+        WignerD: Symbolic Wigner-D function
+
+        """
+        return WignerD(j, m, mp, alpha, beta, gamma)
+
+    @classmethod
+    def d(cls, j, m, mp, beta):
+        """Wigner small-d function.
+
+        Returns an instance of the WignerD class corresponding to the Wigner-D
+        function specified by the parameters with the alpha and gamma angles
+        given as 0.
+
+        Parameters
+        ===========
+
+        j : Number
+            Total angular momentum
+        m : Number
+            Eigenvalue of angular momentum along axis after rotation
+        mp : Number
+            Eigenvalue of angular momentum along rotated axis
+        beta : Number, Symbol
+            Second Euler angle of rotation
+
+        Examples
+        ========
+
+        Return the Wigner-D matrix element for a defined rotation, both
+        numerical and symbolic:
+
+            >>> from sympy.physics.quantum.spin import Rotation
+            >>> from sympy import pi, symbols
+            >>> beta = symbols('beta')
+            >>> Rotation.d(1, 1, 0, pi/2)
+            WignerD(1, 1, 0, 0, pi/2, 0)
+
+        See Also
+        ========
+
+        WignerD: Symbolic Wigner-D function
+
+        """
+        return WignerD(j, m, mp, 0, beta, 0)
+
+    def matrix_element(self, j, m, jp, mp):
+        result = self.__class__.D(
+            jp, m, mp, self.alpha, self.beta, self.gamma
+        )
+        result *= KroneckerDelta(j, jp)
+        return result
+
+    def _represent_base(self, basis, **options):
+        j = sympify(options.get('j', S.Half))
+        # TODO: move evaluation up to represent function/implement elsewhere
+        evaluate = sympify(options.get('doit'))
+        size, mvals = m_values(j)
+        result = zeros(size, size)
+        for p in range(size):
+            for q in range(size):
+                me = self.matrix_element(j, mvals[p], j, mvals[q])
+                if evaluate:
+                    result[p, q] = me.doit()
+                else:
+                    result[p, q] = me
+        return result
+
+    def _represent_default_basis(self, **options):
+        return self._represent_JzOp(None, **options)
+
+    def _represent_JzOp(self, basis, **options):
+        return self._represent_base(basis, **options)
+
+    def _apply_operator_uncoupled(self, state, ket, *, dummy=True, **options):
+        a = self.alpha
+        b = self.beta
+        g = self.gamma
+        j = ket.j
+        m = ket.m
+        if j.is_number:
+            s = []
+            size = m_values(j)
+            sz = size[1]
+            for mp in sz:
+                r = Rotation.D(j, m, mp, a, b, g)
+                z = r.doit()
+                s.append(z*state(j, mp))
+            return Add(*s)
+        else:
+            if dummy:
+                mp = Dummy('mp')
+            else:
+                mp = symbols('mp')
+            return Sum(Rotation.D(j, m, mp, a, b, g)*state(j, mp), (mp, -j, j))
+
+    def _apply_operator_JxKet(self, ket, **options):
+        return self._apply_operator_uncoupled(JxKet, ket, **options)
+
+    def _apply_operator_JyKet(self, ket, **options):
+        return self._apply_operator_uncoupled(JyKet, ket, **options)
+
+    def _apply_operator_JzKet(self, ket, **options):
+        return self._apply_operator_uncoupled(JzKet, ket, **options)
+
+    def _apply_operator_coupled(self, state, ket, *, dummy=True, **options):
+        a = self.alpha
+        b = self.beta
+        g = self.gamma
+        j = ket.j
+        m = ket.m
+        jn = ket.jn
+        coupling = ket.coupling
+        if j.is_number:
+            s = []
+            size = m_values(j)
+            sz = size[1]
+            for mp in sz:
+                r = Rotation.D(j, m, mp, a, b, g)
+                z = r.doit()
+                s.append(z*state(j, mp, jn, coupling))
+            return Add(*s)
+        else:
+            if dummy:
+                mp = Dummy('mp')
+            else:
+                mp = symbols('mp')
+            return Sum(Rotation.D(j, m, mp, a, b, g)*state(
+                j, mp, jn, coupling), (mp, -j, j))
+
+    def _apply_operator_JxKetCoupled(self, ket, **options):
+        return self._apply_operator_coupled(JxKetCoupled, ket, **options)
+
+    def _apply_operator_JyKetCoupled(self, ket, **options):
+        return self._apply_operator_coupled(JyKetCoupled, ket, **options)
+
+    def _apply_operator_JzKetCoupled(self, ket, **options):
+        return self._apply_operator_coupled(JzKetCoupled, ket, **options)
+
+class WignerD(Expr):
+    r"""Wigner-D function
+
+    The Wigner D-function gives the matrix elements of the rotation
+    operator in the jm-representation. For the Euler angles `\alpha`,
+    `\beta`, `\gamma`, the D-function is defined such that:
+
+    .. math ::
+         = \delta_{jj'} D(j, m, m', \alpha, \beta, \gamma)
+
+    Where the rotation operator is as defined by the Rotation class [1]_.
+
+    The Wigner D-function defined in this way gives:
+
+    .. math ::
+        D(j, m, m', \alpha, \beta, \gamma) = e^{-i m \alpha} d(j, m, m', \beta) e^{-i m' \gamma}
+
+    Where d is the Wigner small-d function, which is given by Rotation.d.
+
+    The Wigner small-d function gives the component of the Wigner
+    D-function that is determined by the second Euler angle. That is the
+    Wigner D-function is:
+
+    .. math ::
+        D(j, m, m', \alpha, \beta, \gamma) = e^{-i m \alpha} d(j, m, m', \beta) e^{-i m' \gamma}
+
+    Where d is the small-d function. The Wigner D-function is given by
+    Rotation.D.
+
+    Note that to evaluate the D-function, the j, m and mp parameters must
+    be integer or half integer numbers.
+
+    Parameters
+    ==========
+
+    j : Number
+        Total angular momentum
+    m : Number
+        Eigenvalue of angular momentum along axis after rotation
+    mp : Number
+        Eigenvalue of angular momentum along rotated axis
+    alpha : Number, Symbol
+        First Euler angle of rotation
+    beta : Number, Symbol
+        Second Euler angle of rotation
+    gamma : Number, Symbol
+        Third Euler angle of rotation
+
+    Examples
+    ========
+
+    Evaluate the Wigner-D matrix elements of a simple rotation:
+
+        >>> from sympy.physics.quantum.spin import Rotation
+        >>> from sympy import pi
+        >>> rot = Rotation.D(1, 1, 0, pi, pi/2, 0)
+        >>> rot
+        WignerD(1, 1, 0, pi, pi/2, 0)
+        >>> rot.doit()
+        sqrt(2)/2
+
+    Evaluate the Wigner-d matrix elements of a simple rotation
+
+        >>> rot = Rotation.d(1, 1, 0, pi/2)
+        >>> rot
+        WignerD(1, 1, 0, 0, pi/2, 0)
+        >>> rot.doit()
+        -sqrt(2)/2
+
+    See Also
+    ========
+
+    Rotation: Rotation operator
+
+    References
+    ==========
+
+    .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
+    """
+
+    is_commutative = True
+
+    def __new__(cls, *args, **hints):
+        if not len(args) == 6:
+            raise ValueError('6 parameters expected, got %s' % args)
+        args = sympify(args)
+        evaluate = hints.get('evaluate', False)
+        if evaluate:
+            return Expr.__new__(cls, *args)._eval_wignerd()
+        return Expr.__new__(cls, *args)
+
+    @property
+    def j(self):
+        return self.args[0]
+
+    @property
+    def m(self):
+        return self.args[1]
+
+    @property
+    def mp(self):
+        return self.args[2]
+
+    @property
+    def alpha(self):
+        return self.args[3]
+
+    @property
+    def beta(self):
+        return self.args[4]
+
+    @property
+    def gamma(self):
+        return self.args[5]
+
+    def _latex(self, printer, *args):
+        if self.alpha == 0 and self.gamma == 0:
+            return r'd^{%s}_{%s,%s}\left(%s\right)' % \
+                (
+                    printer._print(self.j), printer._print(
+                        self.m), printer._print(self.mp),
+                    printer._print(self.beta) )
+        return r'D^{%s}_{%s,%s}\left(%s,%s,%s\right)' % \
+            (
+                printer._print(
+                    self.j), printer._print(self.m), printer._print(self.mp),
+                printer._print(self.alpha), printer._print(self.beta), printer._print(self.gamma) )
+
+    def _pretty(self, printer, *args):
+        top = printer._print(self.j)
+
+        bot = printer._print(self.m)
+        bot = prettyForm(*bot.right(','))
+        bot = prettyForm(*bot.right(printer._print(self.mp)))
+
+        pad = max(top.width(), bot.width())
+        top = prettyForm(*top.left(' '))
+        bot = prettyForm(*bot.left(' '))
+        if pad > top.width():
+            top = prettyForm(*top.right(' '*(pad - top.width())))
+        if pad > bot.width():
+            bot = prettyForm(*bot.right(' '*(pad - bot.width())))
+        if self.alpha == 0 and self.gamma == 0:
+            args = printer._print(self.beta)
+            s = stringPict('d' + ' '*pad)
+        else:
+            args = printer._print(self.alpha)
+            args = prettyForm(*args.right(','))
+            args = prettyForm(*args.right(printer._print(self.beta)))
+            args = prettyForm(*args.right(','))
+            args = prettyForm(*args.right(printer._print(self.gamma)))
+
+            s = stringPict('D' + ' '*pad)
+
+        args = prettyForm(*args.parens())
+        s = prettyForm(*s.above(top))
+        s = prettyForm(*s.below(bot))
+        s = prettyForm(*s.right(args))
+        return s
+
+    def doit(self, **hints):
+        hints['evaluate'] = True
+        return WignerD(*self.args, **hints)
+
+    def _eval_wignerd(self):
+        j = self.j
+        m = self.m
+        mp = self.mp
+        alpha = self.alpha
+        beta = self.beta
+        gamma = self.gamma
+        if alpha == 0 and beta == 0 and gamma == 0:
+            return KroneckerDelta(m, mp)
+        if not j.is_number:
+            raise ValueError(
+                'j parameter must be numerical to evaluate, got %s' % j)
+        r = 0
+        if beta == pi/2:
+            # Varshalovich Equation (5), Section 4.16, page 113, setting
+            # alpha=gamma=0.
+            for k in range(2*j + 1):
+                if k > j + mp or k > j - m or k < mp - m:
+                    continue
+                r += (S.NegativeOne)**k*binomial(j + mp, k)*binomial(j - mp, k + m - mp)
+            r *= (S.NegativeOne)**(m - mp) / 2**j*sqrt(factorial(j + m) *
+                    factorial(j - m) / (factorial(j + mp)*factorial(j - mp)))
+        else:
+            # Varshalovich Equation(5), Section 4.7.2, page 87, where we set
+            # beta1=beta2=pi/2, and we get alpha=gamma=pi/2 and beta=phi+pi,
+            # then we use the Eq. (1), Section 4.4. page 79, to simplify:
+            # d(j, m, mp, beta+pi) = (-1)**(j-mp)*d(j, m, -mp, beta)
+            # This happens to be almost the same as in Eq.(10), Section 4.16,
+            # except that we need to substitute -mp for mp.
+            size, mvals = m_values(j)
+            for mpp in mvals:
+                r += Rotation.d(j, m, mpp, pi/2).doit()*(cos(-mpp*beta) + I*sin(-mpp*beta))*\
+                    Rotation.d(j, mpp, -mp, pi/2).doit()
+            # Empirical normalization factor so results match Varshalovich
+            # Tables 4.3-4.12
+            # Note that this exact normalization does not follow from the
+            # above equations
+            r = r*I**(2*j - m - mp)*(-1)**(2*m)
+            # Finally, simplify the whole expression
+            r = simplify(r)
+        r *= exp(-I*m*alpha)*exp(-I*mp*gamma)
+        return r
+
+
+Jx = JxOp('J')
+Jy = JyOp('J')
+Jz = JzOp('J')
+J2 = J2Op('J')
+Jplus = JplusOp('J')
+Jminus = JminusOp('J')
+
+
+#-----------------------------------------------------------------------------
+# Spin States
+#-----------------------------------------------------------------------------
+
+
+class SpinState(State):
+    """Base class for angular momentum states."""
+
+    _label_separator = ','
+
+    def __new__(cls, j, m):
+        j = sympify(j)
+        m = sympify(m)
+        if j.is_number:
+            if 2*j != int(2*j):
+                raise ValueError(
+                    'j must be integer or half-integer, got: %s' % j)
+            if j < 0:
+                raise ValueError('j must be >= 0, got: %s' % j)
+        if m.is_number:
+            if 2*m != int(2*m):
+                raise ValueError(
+                    'm must be integer or half-integer, got: %s' % m)
+        if j.is_number and m.is_number:
+            if abs(m) > j:
+                raise ValueError('Allowed values for m are -j <= m <= j, got j, m: %s, %s' % (j, m))
+            if int(j - m) != j - m:
+                raise ValueError('Both j and m must be integer or half-integer, got j, m: %s, %s' % (j, m))
+        return State.__new__(cls, j, m)
+
+    @property
+    def j(self):
+        return self.label[0]
+
+    @property
+    def m(self):
+        return self.label[1]
+
+    @classmethod
+    def _eval_hilbert_space(cls, label):
+        return ComplexSpace(2*label[0] + 1)
+
+    def _represent_base(self, **options):
+        j = self.j
+        m = self.m
+        alpha = sympify(options.get('alpha', 0))
+        beta = sympify(options.get('beta', 0))
+        gamma = sympify(options.get('gamma', 0))
+        size, mvals = m_values(j)
+        result = zeros(size, 1)
+        # breaks finding angles on L930
+        for p, mval in enumerate(mvals):
+            if m.is_number:
+                result[p, 0] = Rotation.D(
+                    self.j, mval, self.m, alpha, beta, gamma).doit()
+            else:
+                result[p, 0] = Rotation.D(self.j, mval,
+                                          self.m, alpha, beta, gamma)
+        return result
+
+    def _eval_rewrite_as_Jx(self, *args, **options):
+        if isinstance(self, Bra):
+            return self._rewrite_basis(Jx, JxBra, **options)
+        return self._rewrite_basis(Jx, JxKet, **options)
+
+    def _eval_rewrite_as_Jy(self, *args, **options):
+        if isinstance(self, Bra):
+            return self._rewrite_basis(Jy, JyBra, **options)
+        return self._rewrite_basis(Jy, JyKet, **options)
+
+    def _eval_rewrite_as_Jz(self, *args, **options):
+        if isinstance(self, Bra):
+            return self._rewrite_basis(Jz, JzBra, **options)
+        return self._rewrite_basis(Jz, JzKet, **options)
+
+    def _rewrite_basis(self, basis, evect, **options):
+        from sympy.physics.quantum.represent import represent
+        j = self.j
+        args = self.args[2:]
+        if j.is_number:
+            if isinstance(self, CoupledSpinState):
+                if j == int(j):
+                    start = j**2
+                else:
+                    start = (2*j - 1)*(2*j + 1)/4
+            else:
+                start = 0
+            vect = represent(self, basis=basis, **options)
+            result = Add(
+                *[vect[start + i]*evect(j, j - i, *args) for i in range(2*j + 1)])
+            if isinstance(self, CoupledSpinState) and options.get('coupled') is False:
+                return uncouple(result)
+            return result
+        else:
+            i = 0
+            mi = symbols('mi')
+            # make sure not to introduce a symbol already in the state
+            while self.subs(mi, 0) != self:
+                i += 1
+                mi = symbols('mi%d' % i)
+                break
+            # TODO: better way to get angles of rotation
+            if isinstance(self, CoupledSpinState):
+                test_args = (0, mi, (0, 0))
+            else:
+                test_args = (0, mi)
+            if isinstance(self, Ket):
+                angles = represent(
+                    self.__class__(*test_args), basis=basis)[0].args[3:6]
+            else:
+                angles = represent(self.__class__(
+                    *test_args), basis=basis)[0].args[0].args[3:6]
+            if angles == (0, 0, 0):
+                return self
+            else:
+                state = evect(j, mi, *args)
+                lt = Rotation.D(j, mi, self.m, *angles)
+                return Sum(lt*state, (mi, -j, j))
+
+    def _eval_innerproduct_JxBra(self, bra, **hints):
+        result = KroneckerDelta(self.j, bra.j)
+        if bra.dual_class() is not self.__class__:
+            result *= self._represent_JxOp(None)[bra.j - bra.m]
+        else:
+            result *= KroneckerDelta(
+                self.j, bra.j)*KroneckerDelta(self.m, bra.m)
+        return result
+
+    def _eval_innerproduct_JyBra(self, bra, **hints):
+        result = KroneckerDelta(self.j, bra.j)
+        if bra.dual_class() is not self.__class__:
+            result *= self._represent_JyOp(None)[bra.j - bra.m]
+        else:
+            result *= KroneckerDelta(
+                self.j, bra.j)*KroneckerDelta(self.m, bra.m)
+        return result
+
+    def _eval_innerproduct_JzBra(self, bra, **hints):
+        result = KroneckerDelta(self.j, bra.j)
+        if bra.dual_class() is not self.__class__:
+            result *= self._represent_JzOp(None)[bra.j - bra.m]
+        else:
+            result *= KroneckerDelta(
+                self.j, bra.j)*KroneckerDelta(self.m, bra.m)
+        return result
+
+    def _eval_trace(self, bra, **hints):
+
+        # One way to implement this method is to assume the basis set k is
+        # passed.
+        # Then we can apply the discrete form of Trace formula here
+        # Tr(|i>
+        #then we do qapply() on each each inner product and sum over them.
+
+        # OR
+
+        # Inner product of |i>>> from sympy.physics.quantum.spin import JzKet, JxKet
+        >>> from sympy import symbols
+        >>> JzKet(1, 0)
+        |1,0>
+        >>> j, m = symbols('j m')
+        >>> JzKet(j, m)
+        |j,m>
+
+    Rewriting the JzKet in terms of eigenkets of the Jx operator:
+    Note: that the resulting eigenstates are JxKet's
+
+        >>> JzKet(1,1).rewrite("Jx")
+        |1,-1>/2 - sqrt(2)*|1,0>/2 + |1,1>/2
+
+    Get the vector representation of a state in terms of the basis elements
+    of the Jx operator:
+
+        >>> from sympy.physics.quantum.represent import represent
+        >>> from sympy.physics.quantum.spin import Jx, Jz
+        >>> represent(JzKet(1,-1), basis=Jx)
+        Matrix([
+        [      1/2],
+        [sqrt(2)/2],
+        [      1/2]])
+
+    Apply innerproducts between states:
+
+        >>> from sympy.physics.quantum.innerproduct import InnerProduct
+        >>> from sympy.physics.quantum.spin import JxBra
+        >>> i = InnerProduct(JxBra(1,1), JzKet(1,1))
+        >>> i
+        <1,1|1,1>
+        >>> i.doit()
+        1/2
+
+    *Uncoupled States:*
+
+    Define an uncoupled state as a TensorProduct between two Jz eigenkets:
+
+        >>> from sympy.physics.quantum.tensorproduct import TensorProduct
+        >>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2')
+        >>> TensorProduct(JzKet(1,0), JzKet(1,1))
+        |1,0>x|1,1>
+        >>> TensorProduct(JzKet(j1,m1), JzKet(j2,m2))
+        |j1,m1>x|j2,m2>
+
+    A TensorProduct can be rewritten, in which case the eigenstates that make
+    up the tensor product is rewritten to the new basis:
+
+        >>> TensorProduct(JzKet(1,1),JxKet(1,1)).rewrite('Jz')
+        |1,1>x|1,-1>/2 + sqrt(2)*|1,1>x|1,0>/2 + |1,1>x|1,1>/2
+
+    The represent method for TensorProduct's gives the vector representation of
+    the state. Note that the state in the product basis is the equivalent of the
+    tensor product of the vector representation of the component eigenstates:
+
+        >>> represent(TensorProduct(JzKet(1,0),JzKet(1,1)))
+        Matrix([
+        [0],
+        [0],
+        [0],
+        [1],
+        [0],
+        [0],
+        [0],
+        [0],
+        [0]])
+        >>> represent(TensorProduct(JzKet(1,1),JxKet(1,1)), basis=Jz)
+        Matrix([
+        [      1/2],
+        [sqrt(2)/2],
+        [      1/2],
+        [        0],
+        [        0],
+        [        0],
+        [        0],
+        [        0],
+        [        0]])
+
+    See Also
+    ========
+
+    JzKetCoupled: Coupled eigenstates
+    sympy.physics.quantum.tensorproduct.TensorProduct: Used to specify uncoupled states
+    uncouple: Uncouples states given coupling parameters
+    couple: Couples uncoupled states
+
+    """
+
+    @classmethod
+    def dual_class(self):
+        return JzBra
+
+    @classmethod
+    def coupled_class(self):
+        return JzKetCoupled
+
+    def _represent_default_basis(self, **options):
+        return self._represent_JzOp(None, **options)
+
+    def _represent_JxOp(self, basis, **options):
+        return self._represent_base(beta=pi*Rational(3, 2), **options)
+
+    def _represent_JyOp(self, basis, **options):
+        return self._represent_base(alpha=pi*Rational(3, 2), beta=pi/2, gamma=pi/2, **options)
+
+    def _represent_JzOp(self, basis, **options):
+        return self._represent_base(**options)
+
+
+class JzBra(SpinState, Bra):
+    """Eigenbra of Jz.
+
+    See the JzKet for the usage of spin eigenstates.
+
+    See Also
+    ========
+
+    JzKet: Usage of spin states
+
+    """
+
+    @classmethod
+    def dual_class(self):
+        return JzKet
+
+    @classmethod
+    def coupled_class(self):
+        return JzBraCoupled
+
+
+# Method used primarily to create coupled_n and coupled_jn by __new__ in
+# CoupledSpinState
+# This same method is also used by the uncouple method, and is separated from
+# the CoupledSpinState class to maintain consistency in defining coupling
+def _build_coupled(jcoupling, length):
+    n_list = [ [n + 1] for n in range(length) ]
+    coupled_jn = []
+    coupled_n = []
+    for n1, n2, j_new in jcoupling:
+        coupled_jn.append(j_new)
+        coupled_n.append( (n_list[n1 - 1], n_list[n2 - 1]) )
+        n_sort = sorted(n_list[n1 - 1] + n_list[n2 - 1])
+        n_list[n_sort[0] - 1] = n_sort
+    return coupled_n, coupled_jn
+
+
+class CoupledSpinState(SpinState):
+    """Base class for coupled angular momentum states."""
+
+    def __new__(cls, j, m, jn, *jcoupling):
+        # Check j and m values using SpinState
+        SpinState(j, m)
+        # Build and check coupling scheme from arguments
+        if len(jcoupling) == 0:
+            # Use default coupling scheme
+            jcoupling = []
+            for n in range(2, len(jn)):
+                jcoupling.append( (1, n, Add(*[jn[i] for i in range(n)])) )
+            jcoupling.append( (1, len(jn), j) )
+        elif len(jcoupling) == 1:
+            # Use specified coupling scheme
+            jcoupling = jcoupling[0]
+        else:
+            raise TypeError("CoupledSpinState only takes 3 or 4 arguments, got: %s" % (len(jcoupling) + 3) )
+        # Check arguments have correct form
+        if not isinstance(jn, (list, tuple, Tuple)):
+            raise TypeError('jn must be Tuple, list or tuple, got %s' %
+                            jn.__class__.__name__)
+        if not isinstance(jcoupling, (list, tuple, Tuple)):
+            raise TypeError('jcoupling must be Tuple, list or tuple, got %s' %
+                            jcoupling.__class__.__name__)
+        if not all(isinstance(term, (list, tuple, Tuple)) for term in jcoupling):
+            raise TypeError(
+                'All elements of jcoupling must be list, tuple or Tuple')
+        if not len(jn) - 1 == len(jcoupling):
+            raise ValueError('jcoupling must have length of %d, got %d' %
+                             (len(jn) - 1, len(jcoupling)))
+        if not all(len(x) == 3 for x in jcoupling):
+            raise ValueError('All elements of jcoupling must have length 3')
+        # Build sympified args
+        j = sympify(j)
+        m = sympify(m)
+        jn = Tuple( *[sympify(ji) for ji in jn] )
+        jcoupling = Tuple( *[Tuple(sympify(
+            n1), sympify(n2), sympify(ji)) for (n1, n2, ji) in jcoupling] )
+        # Check values in coupling scheme give physical state
+        if any(2*ji != int(2*ji) for ji in jn if ji.is_number):
+            raise ValueError('All elements of jn must be integer or half-integer, got: %s' % jn)
+        if any(n1 != int(n1) or n2 != int(n2) for (n1, n2, _) in jcoupling):
+            raise ValueError('Indices in jcoupling must be integers')
+        if any(n1 < 1 or n2 < 1 or n1 > len(jn) or n2 > len(jn) for (n1, n2, _) in jcoupling):
+            raise ValueError('Indices must be between 1 and the number of coupled spin spaces')
+        if any(2*ji != int(2*ji) for (_, _, ji) in jcoupling if ji.is_number):
+            raise ValueError('All coupled j values in coupling scheme must be integer or half-integer')
+        coupled_n, coupled_jn = _build_coupled(jcoupling, len(jn))
+        jvals = list(jn)
+        for n, (n1, n2) in enumerate(coupled_n):
+            j1 = jvals[min(n1) - 1]
+            j2 = jvals[min(n2) - 1]
+            j3 = coupled_jn[n]
+            if sympify(j1).is_number and sympify(j2).is_number and sympify(j3).is_number:
+                if j1 + j2 < j3:
+                    raise ValueError('All couplings must have j1+j2 >= j3, '
+                        'in coupling number %d got j1,j2,j3: %d,%d,%d' % (n + 1, j1, j2, j3))
+                if abs(j1 - j2) > j3:
+                    raise ValueError("All couplings must have |j1+j2| <= j3, "
+                        "in coupling number %d got j1,j2,j3: %d,%d,%d" % (n + 1, j1, j2, j3))
+                if int_valued(j1 + j2):
+                    pass
+            jvals[min(n1 + n2) - 1] = j3
+        if len(jcoupling) > 0 and jcoupling[-1][2] != j:
+            raise ValueError('Last j value coupled together must be the final j of the state')
+        # Return state
+        return State.__new__(cls, j, m, jn, jcoupling)
+
+    def _print_label(self, printer, *args):
+        label = [printer._print(self.j), printer._print(self.m)]
+        for i, ji in enumerate(self.jn, start=1):
+            label.append('j%d=%s' % (
+                i, printer._print(ji)
+            ))
+        for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
+            label.append('j(%s)=%s' % (
+                ','.join(str(i) for i in sorted(n1 + n2)), printer._print(jn)
+            ))
+        return ','.join(label)
+
+    def _print_label_pretty(self, printer, *args):
+        label = [self.j, self.m]
+        for i, ji in enumerate(self.jn, start=1):
+            symb = 'j%d' % i
+            symb = pretty_symbol(symb)
+            symb = prettyForm(symb + '=')
+            item = prettyForm(*symb.right(printer._print(ji)))
+            label.append(item)
+        for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
+            n = ','.join(pretty_symbol("j%d" % i)[-1] for i in sorted(n1 + n2))
+            symb = prettyForm('j' + n + '=')
+            item = prettyForm(*symb.right(printer._print(jn)))
+            label.append(item)
+        return self._print_sequence_pretty(
+            label, self._label_separator, printer, *args
+        )
+
+    def _print_label_latex(self, printer, *args):
+        label = [
+            printer._print(self.j, *args),
+            printer._print(self.m, *args)
+        ]
+        for i, ji in enumerate(self.jn, start=1):
+            label.append('j_{%d}=%s' % (i, printer._print(ji, *args)) )
+        for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
+            n = ','.join(str(i) for i in sorted(n1 + n2))
+            label.append('j_{%s}=%s' % (n, printer._print(jn, *args)) )
+        return self._label_separator.join(label)
+
+    @property
+    def jn(self):
+        return self.label[2]
+
+    @property
+    def coupling(self):
+        return self.label[3]
+
+    @property
+    def coupled_jn(self):
+        return _build_coupled(self.label[3], len(self.label[2]))[1]
+
+    @property
+    def coupled_n(self):
+        return _build_coupled(self.label[3], len(self.label[2]))[0]
+
+    @classmethod
+    def _eval_hilbert_space(cls, label):
+        j = Add(*label[2])
+        if j.is_number:
+            return DirectSumHilbertSpace(*[ ComplexSpace(x) for x in range(int(2*j + 1), 0, -2) ])
+        else:
+            # TODO: Need hilbert space fix, see issue 5732
+            # Desired behavior:
+            #ji = symbols('ji')
+            #ret = Sum(ComplexSpace(2*ji + 1), (ji, 0, j))
+            # Temporary fix:
+            return ComplexSpace(2*j + 1)
+
+    def _represent_coupled_base(self, **options):
+        evect = self.uncoupled_class()
+        if not self.j.is_number:
+            raise ValueError(
+                'State must not have symbolic j value to represent')
+        if not self.hilbert_space.dimension.is_number:
+            raise ValueError(
+                'State must not have symbolic j values to represent')
+        result = zeros(self.hilbert_space.dimension, 1)
+        if self.j == int(self.j):
+            start = self.j**2
+        else:
+            start = (2*self.j - 1)*(1 + 2*self.j)/4
+        result[start:start + 2*self.j + 1, 0] = evect(
+            self.j, self.m)._represent_base(**options)
+        return result
+
+    def _eval_rewrite_as_Jx(self, *args, **options):
+        if isinstance(self, Bra):
+            return self._rewrite_basis(Jx, JxBraCoupled, **options)
+        return self._rewrite_basis(Jx, JxKetCoupled, **options)
+
+    def _eval_rewrite_as_Jy(self, *args, **options):
+        if isinstance(self, Bra):
+            return self._rewrite_basis(Jy, JyBraCoupled, **options)
+        return self._rewrite_basis(Jy, JyKetCoupled, **options)
+
+    def _eval_rewrite_as_Jz(self, *args, **options):
+        if isinstance(self, Bra):
+            return self._rewrite_basis(Jz, JzBraCoupled, **options)
+        return self._rewrite_basis(Jz, JzKetCoupled, **options)
+
+
+class JxKetCoupled(CoupledSpinState, Ket):
+    """Coupled eigenket of Jx.
+
+    See JzKetCoupled for the usage of coupled spin eigenstates.
+
+    See Also
+    ========
+
+    JzKetCoupled: Usage of coupled spin states
+
+    """
+
+    @classmethod
+    def dual_class(self):
+        return JxBraCoupled
+
+    @classmethod
+    def uncoupled_class(self):
+        return JxKet
+
+    def _represent_default_basis(self, **options):
+        return self._represent_JzOp(None, **options)
+
+    def _represent_JxOp(self, basis, **options):
+        return self._represent_coupled_base(**options)
+
+    def _represent_JyOp(self, basis, **options):
+        return self._represent_coupled_base(alpha=pi*Rational(3, 2), **options)
+
+    def _represent_JzOp(self, basis, **options):
+        return self._represent_coupled_base(beta=pi/2, **options)
+
+
+class JxBraCoupled(CoupledSpinState, Bra):
+    """Coupled eigenbra of Jx.
+
+    See JzKetCoupled for the usage of coupled spin eigenstates.
+
+    See Also
+    ========
+
+    JzKetCoupled: Usage of coupled spin states
+
+    """
+
+    @classmethod
+    def dual_class(self):
+        return JxKetCoupled
+
+    @classmethod
+    def uncoupled_class(self):
+        return JxBra
+
+
+class JyKetCoupled(CoupledSpinState, Ket):
+    """Coupled eigenket of Jy.
+
+    See JzKetCoupled for the usage of coupled spin eigenstates.
+
+    See Also
+    ========
+
+    JzKetCoupled: Usage of coupled spin states
+
+    """
+
+    @classmethod
+    def dual_class(self):
+        return JyBraCoupled
+
+    @classmethod
+    def uncoupled_class(self):
+        return JyKet
+
+    def _represent_default_basis(self, **options):
+        return self._represent_JzOp(None, **options)
+
+    def _represent_JxOp(self, basis, **options):
+        return self._represent_coupled_base(gamma=pi/2, **options)
+
+    def _represent_JyOp(self, basis, **options):
+        return self._represent_coupled_base(**options)
+
+    def _represent_JzOp(self, basis, **options):
+        return self._represent_coupled_base(alpha=pi*Rational(3, 2), beta=-pi/2, gamma=pi/2, **options)
+
+
+class JyBraCoupled(CoupledSpinState, Bra):
+    """Coupled eigenbra of Jy.
+
+    See JzKetCoupled for the usage of coupled spin eigenstates.
+
+    See Also
+    ========
+
+    JzKetCoupled: Usage of coupled spin states
+
+    """
+
+    @classmethod
+    def dual_class(self):
+        return JyKetCoupled
+
+    @classmethod
+    def uncoupled_class(self):
+        return JyBra
+
+
+class JzKetCoupled(CoupledSpinState, Ket):
+    r"""Coupled eigenket of Jz
+
+    Spin state that is an eigenket of Jz which represents the coupling of
+    separate spin spaces.
+
+    The arguments for creating instances of JzKetCoupled are ``j``, ``m``,
+    ``jn`` and an optional ``jcoupling`` argument. The ``j`` and ``m`` options
+    are the total angular momentum quantum numbers, as used for normal states
+    (e.g. JzKet).
+
+    The other required parameter in ``jn``, which is a tuple defining the `j_n`
+    angular momentum quantum numbers of the product spaces. So for example, if
+    a state represented the coupling of the product basis state
+    `\left|j_1,m_1\right\rangle\times\left|j_2,m_2\right\rangle`, the ``jn``
+    for this state would be ``(j1,j2)``.
+
+    The final option is ``jcoupling``, which is used to define how the spaces
+    specified by ``jn`` are coupled, which includes both the order these spaces
+    are coupled together and the quantum numbers that arise from these
+    couplings. The ``jcoupling`` parameter itself is a list of lists, such that
+    each of the sublists defines a single coupling between the spin spaces. If
+    there are N coupled angular momentum spaces, that is ``jn`` has N elements,
+    then there must be N-1 sublists. Each of these sublists making up the
+    ``jcoupling`` parameter have length 3. The first two elements are the
+    indices of the product spaces that are considered to be coupled together.
+    For example, if we want to couple `j_1` and `j_4`, the indices would be 1
+    and 4. If a state has already been coupled, it is referenced by the
+    smallest index that is coupled, so if `j_2` and `j_4` has already been
+    coupled to some `j_{24}`, then this value can be coupled by referencing it
+    with index 2. The final element of the sublist is the quantum number of the
+    coupled state. So putting everything together, into a valid sublist for
+    ``jcoupling``, if `j_1` and `j_2` are coupled to an angular momentum space
+    with quantum number `j_{12}` with the value ``j12``, the sublist would be
+    ``(1,2,j12)``, N-1 of these sublists are used in the list for
+    ``jcoupling``.
+
+    Note the ``jcoupling`` parameter is optional, if it is not specified, the
+    default coupling is taken. This default value is to coupled the spaces in
+    order and take the quantum number of the coupling to be the maximum value.
+    For example, if the spin spaces are `j_1`, `j_2`, `j_3`, `j_4`, then the
+    default coupling couples `j_1` and `j_2` to `j_{12}=j_1+j_2`, then,
+    `j_{12}` and `j_3` are coupled to `j_{123}=j_{12}+j_3`, and finally
+    `j_{123}` and `j_4` to `j=j_{123}+j_4`. The jcoupling value that would
+    correspond to this is:
+
+        ``((1,2,j1+j2),(1,3,j1+j2+j3))``
+
+    Parameters
+    ==========
+
+    args : tuple
+        The arguments that must be passed are ``j``, ``m``, ``jn``, and
+        ``jcoupling``. The ``j`` value is the total angular momentum. The ``m``
+        value is the eigenvalue of the Jz spin operator. The ``jn`` list are
+        the j values of argular momentum spaces coupled together. The
+        ``jcoupling`` parameter is an optional parameter defining how the spaces
+        are coupled together. See the above description for how these coupling
+        parameters are defined.
+
+    Examples
+    ========
+
+    Defining simple spin states, both numerical and symbolic:
+
+        >>> from sympy.physics.quantum.spin import JzKetCoupled
+        >>> from sympy import symbols
+        >>> JzKetCoupled(1, 0, (1, 1))
+        |1,0,j1=1,j2=1>
+        >>> j, m, j1, j2 = symbols('j m j1 j2')
+        >>> JzKetCoupled(j, m, (j1, j2))
+        |j,m,j1=j1,j2=j2>
+
+    Defining coupled spin states for more than 2 coupled spaces with various
+    coupling parameters:
+
+        >>> JzKetCoupled(2, 1, (1, 1, 1))
+        |2,1,j1=1,j2=1,j3=1,j(1,2)=2>
+        >>> JzKetCoupled(2, 1, (1, 1, 1), ((1,2,2),(1,3,2)) )
+        |2,1,j1=1,j2=1,j3=1,j(1,2)=2>
+        >>> JzKetCoupled(2, 1, (1, 1, 1), ((2,3,1),(1,2,2)) )
+        |2,1,j1=1,j2=1,j3=1,j(2,3)=1>
+
+    Rewriting the JzKetCoupled in terms of eigenkets of the Jx operator:
+    Note: that the resulting eigenstates are JxKetCoupled
+
+        >>> JzKetCoupled(1,1,(1,1)).rewrite("Jx")
+        |1,-1,j1=1,j2=1>/2 - sqrt(2)*|1,0,j1=1,j2=1>/2 + |1,1,j1=1,j2=1>/2
+
+    The rewrite method can be used to convert a coupled state to an uncoupled
+    state. This is done by passing coupled=False to the rewrite function:
+
+        >>> JzKetCoupled(1, 0, (1, 1)).rewrite('Jz', coupled=False)
+        -sqrt(2)*|1,-1>x|1,1>/2 + sqrt(2)*|1,1>x|1,-1>/2
+
+    Get the vector representation of a state in terms of the basis elements
+    of the Jx operator:
+
+        >>> from sympy.physics.quantum.represent import represent
+        >>> from sympy.physics.quantum.spin import Jx
+        >>> from sympy import S
+        >>> represent(JzKetCoupled(1,-1,(S(1)/2,S(1)/2)), basis=Jx)
+        Matrix([
+        [        0],
+        [      1/2],
+        [sqrt(2)/2],
+        [      1/2]])
+
+    See Also
+    ========
+
+    JzKet: Normal spin eigenstates
+    uncouple: Uncoupling of coupling spin states
+    couple: Coupling of uncoupled spin states
+
+    """
+
+    @classmethod
+    def dual_class(self):
+        return JzBraCoupled
+
+    @classmethod
+    def uncoupled_class(self):
+        return JzKet
+
+    def _represent_default_basis(self, **options):
+        return self._represent_JzOp(None, **options)
+
+    def _represent_JxOp(self, basis, **options):
+        return self._represent_coupled_base(beta=pi*Rational(3, 2), **options)
+
+    def _represent_JyOp(self, basis, **options):
+        return self._represent_coupled_base(alpha=pi*Rational(3, 2), beta=pi/2, gamma=pi/2, **options)
+
+    def _represent_JzOp(self, basis, **options):
+        return self._represent_coupled_base(**options)
+
+
+class JzBraCoupled(CoupledSpinState, Bra):
+    """Coupled eigenbra of Jz.
+
+    See the JzKetCoupled for the usage of coupled spin eigenstates.
+
+    See Also
+    ========
+
+    JzKetCoupled: Usage of coupled spin states
+
+    """
+
+    @classmethod
+    def dual_class(self):
+        return JzKetCoupled
+
+    @classmethod
+    def uncoupled_class(self):
+        return JzBra
+
+#-----------------------------------------------------------------------------
+# Coupling/uncoupling
+#-----------------------------------------------------------------------------
+
+
+def couple(expr, jcoupling_list=None):
+    """ Couple a tensor product of spin states
+
+    This function can be used to couple an uncoupled tensor product of spin
+    states. All of the eigenstates to be coupled must be of the same class. It
+    will return a linear combination of eigenstates that are subclasses of
+    CoupledSpinState determined by Clebsch-Gordan angular momentum coupling
+    coefficients.
+
+    Parameters
+    ==========
+
+    expr : Expr
+        An expression involving TensorProducts of spin states to be coupled.
+        Each state must be a subclass of SpinState and they all must be the
+        same class.
+
+    jcoupling_list : list or tuple
+        Elements of this list are sub-lists of length 2 specifying the order of
+        the coupling of the spin spaces. The length of this must be N-1, where N
+        is the number of states in the tensor product to be coupled. The
+        elements of this sublist are the same as the first two elements of each
+        sublist in the ``jcoupling`` parameter defined for JzKetCoupled. If this
+        parameter is not specified, the default value is taken, which couples
+        the first and second product basis spaces, then couples this new coupled
+        space to the third product space, etc
+
+    Examples
+    ========
+
+    Couple a tensor product of numerical states for two spaces:
+
+        >>> from sympy.physics.quantum.spin import JzKet, couple
+        >>> from sympy.physics.quantum.tensorproduct import TensorProduct
+        >>> couple(TensorProduct(JzKet(1,0), JzKet(1,1)))
+        -sqrt(2)*|1,1,j1=1,j2=1>/2 + sqrt(2)*|2,1,j1=1,j2=1>/2
+
+
+    Numerical coupling of three spaces using the default coupling method, i.e.
+    first and second spaces couple, then this couples to the third space:
+
+        >>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0)))
+        sqrt(6)*|2,2,j1=1,j2=1,j3=1,j(1,2)=2>/3 + sqrt(3)*|3,2,j1=1,j2=1,j3=1,j(1,2)=2>/3
+
+    Perform this same coupling, but we define the coupling to first couple
+    the first and third spaces:
+
+        >>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0)), ((1,3),(1,2)) )
+        sqrt(2)*|2,2,j1=1,j2=1,j3=1,j(1,3)=1>/2 - sqrt(6)*|2,2,j1=1,j2=1,j3=1,j(1,3)=2>/6 + sqrt(3)*|3,2,j1=1,j2=1,j3=1,j(1,3)=2>/3
+
+    Couple a tensor product of symbolic states:
+
+        >>> from sympy import symbols
+        >>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2')
+        >>> couple(TensorProduct(JzKet(j1,m1), JzKet(j2,m2)))
+        Sum(CG(j1, m1, j2, m2, j, m1 + m2)*|j,m1 + m2,j1=j1,j2=j2>, (j, m1 + m2, j1 + j2))
+
+    """
+    a = expr.atoms(TensorProduct)
+    for tp in a:
+        # Allow other tensor products to be in expression
+        if not all(isinstance(state, SpinState) for state in tp.args):
+            continue
+        # If tensor product has all spin states, raise error for invalid tensor product state
+        if not all(state.__class__ is tp.args[0].__class__ for state in tp.args):
+            raise TypeError('All states must be the same basis')
+        expr = expr.subs(tp, _couple(tp, jcoupling_list))
+    return expr
+
+
+def _couple(tp, jcoupling_list):
+    states = tp.args
+    coupled_evect = states[0].coupled_class()
+
+    # Define default coupling if none is specified
+    if jcoupling_list is None:
+        jcoupling_list = []
+        for n in range(1, len(states)):
+            jcoupling_list.append( (1, n + 1) )
+
+    # Check jcoupling_list valid
+    if not len(jcoupling_list) == len(states) - 1:
+        raise TypeError('jcoupling_list must be length %d, got %d' %
+                        (len(states) - 1, len(jcoupling_list)))
+    if not all( len(coupling) == 2 for coupling in jcoupling_list):
+        raise ValueError('Each coupling must define 2 spaces')
+    if any(n1 == n2 for n1, n2 in jcoupling_list):
+        raise ValueError('Spin spaces cannot couple to themselves')
+    if all(sympify(n1).is_number and sympify(n2).is_number for n1, n2 in jcoupling_list):
+        j_test = [0]*len(states)
+        for n1, n2 in jcoupling_list:
+            if j_test[n1 - 1] == -1 or j_test[n2 - 1] == -1:
+                raise ValueError('Spaces coupling j_n\'s are referenced by smallest n value')
+            j_test[max(n1, n2) - 1] = -1
+
+    # j values of states to be coupled together
+    jn = [state.j for state in states]
+    mn = [state.m for state in states]
+
+    # Create coupling_list, which defines all the couplings between all
+    # the spaces from jcoupling_list
+    coupling_list = []
+    n_list = [ [i + 1] for i in range(len(states)) ]
+    for j_coupling in jcoupling_list:
+        # Least n for all j_n which is coupled as first and second spaces
+        n1, n2 = j_coupling
+        # List of all n's coupled in first and second spaces
+        j1_n = list(n_list[n1 - 1])
+        j2_n = list(n_list[n2 - 1])
+        coupling_list.append( (j1_n, j2_n) )
+        # Set new j_n to be coupling of all j_n in both first and second spaces
+        n_list[ min(n1, n2) - 1 ] = sorted(j1_n + j2_n)
+
+    if all(state.j.is_number and state.m.is_number for state in states):
+        # Numerical coupling
+        # Iterate over difference between maximum possible j value of each coupling and the actual value
+        diff_max = [ Add( *[ jn[n - 1] - mn[n - 1] for n in coupling[0] +
+                         coupling[1] ] ) for coupling in coupling_list ]
+        result = []
+        for diff in range(diff_max[-1] + 1):
+            # Determine available configurations
+            n = len(coupling_list)
+            tot = binomial(diff + n - 1, diff)
+
+            for config_num in range(tot):
+                diff_list = _confignum_to_difflist(config_num, diff, n)
+
+                # Skip the configuration if non-physical
+                # This is a lazy check for physical states given the loose restrictions of diff_max
+                if any(d > m for d, m in zip(diff_list, diff_max)):
+                    continue
+
+                # Determine term
+                cg_terms = []
+                coupled_j = list(jn)
+                jcoupling = []
+                for (j1_n, j2_n), coupling_diff in zip(coupling_list, diff_list):
+                    j1 = coupled_j[ min(j1_n) - 1 ]
+                    j2 = coupled_j[ min(j2_n) - 1 ]
+                    j3 = j1 + j2 - coupling_diff
+                    coupled_j[ min(j1_n + j2_n) - 1 ] = j3
+                    m1 = Add( *[ mn[x - 1] for x in j1_n] )
+                    m2 = Add( *[ mn[x - 1] for x in j2_n] )
+                    m3 = m1 + m2
+                    cg_terms.append( (j1, m1, j2, m2, j3, m3) )
+                    jcoupling.append( (min(j1_n), min(j2_n), j3) )
+                # Better checks that state is physical
+                if any(abs(term[5]) > term[4] for term in cg_terms):
+                    continue
+                if any(term[0] + term[2] < term[4] for term in cg_terms):
+                    continue
+                if any(abs(term[0] - term[2]) > term[4] for term in cg_terms):
+                    continue
+                coeff = Mul( *[ CG(*term).doit() for term in cg_terms] )
+                state = coupled_evect(j3, m3, jn, jcoupling)
+                result.append(coeff*state)
+        return Add(*result)
+    else:
+        # Symbolic coupling
+        cg_terms = []
+        jcoupling = []
+        sum_terms = []
+        coupled_j = list(jn)
+        for j1_n, j2_n in coupling_list:
+            j1 = coupled_j[ min(j1_n) - 1 ]
+            j2 = coupled_j[ min(j2_n) - 1 ]
+            if len(j1_n + j2_n) == len(states):
+                j3 = symbols('j')
+            else:
+                j3_name = 'j' + ''.join(["%s" % n for n in j1_n + j2_n])
+                j3 = symbols(j3_name)
+            coupled_j[ min(j1_n + j2_n) - 1 ] = j3
+            m1 = Add( *[ mn[x - 1] for x in j1_n] )
+            m2 = Add( *[ mn[x - 1] for x in j2_n] )
+            m3 = m1 + m2
+            cg_terms.append( (j1, m1, j2, m2, j3, m3) )
+            jcoupling.append( (min(j1_n), min(j2_n), j3) )
+            sum_terms.append((j3, m3, j1 + j2))
+        coeff = Mul( *[ CG(*term) for term in cg_terms] )
+        state = coupled_evect(j3, m3, jn, jcoupling)
+        return Sum(coeff*state, *sum_terms)
+
+
+def uncouple(expr, jn=None, jcoupling_list=None):
+    """ Uncouple a coupled spin state
+
+    Gives the uncoupled representation of a coupled spin state. Arguments must
+    be either a spin state that is a subclass of CoupledSpinState or a spin
+    state that is a subclass of SpinState and an array giving the j values
+    of the spaces that are to be coupled
+
+    Parameters
+    ==========
+
+    expr : Expr
+        The expression containing states that are to be coupled. If the states
+        are a subclass of SpinState, the ``jn`` and ``jcoupling`` parameters
+        must be defined. If the states are a subclass of CoupledSpinState,
+        ``jn`` and ``jcoupling`` will be taken from the state.
+
+    jn : list or tuple
+        The list of the j-values that are coupled. If state is a
+        CoupledSpinState, this parameter is ignored. This must be defined if
+        state is not a subclass of CoupledSpinState. The syntax of this
+        parameter is the same as the ``jn`` parameter of JzKetCoupled.
+
+    jcoupling_list : list or tuple
+        The list defining how the j-values are coupled together. If state is a
+        CoupledSpinState, this parameter is ignored. This must be defined if
+        state is not a subclass of CoupledSpinState. The syntax of this
+        parameter is the same as the ``jcoupling`` parameter of JzKetCoupled.
+
+    Examples
+    ========
+
+    Uncouple a numerical state using a CoupledSpinState state:
+
+        >>> from sympy.physics.quantum.spin import JzKetCoupled, uncouple
+        >>> from sympy import S
+        >>> uncouple(JzKetCoupled(1, 0, (S(1)/2, S(1)/2)))
+        sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2
+
+    Perform the same calculation using a SpinState state:
+
+        >>> from sympy.physics.quantum.spin import JzKet
+        >>> uncouple(JzKet(1, 0), (S(1)/2, S(1)/2))
+        sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2
+
+    Uncouple a numerical state of three coupled spaces using a CoupledSpinState state:
+
+        >>> uncouple(JzKetCoupled(1, 1, (1, 1, 1), ((1,3,1),(1,2,1)) ))
+        |1,-1>x|1,1>x|1,1>/2 - |1,0>x|1,0>x|1,1>/2 + |1,1>x|1,0>x|1,0>/2 - |1,1>x|1,1>x|1,-1>/2
+
+    Perform the same calculation using a SpinState state:
+
+        >>> uncouple(JzKet(1, 1), (1, 1, 1), ((1,3,1),(1,2,1)) )
+        |1,-1>x|1,1>x|1,1>/2 - |1,0>x|1,0>x|1,1>/2 + |1,1>x|1,0>x|1,0>/2 - |1,1>x|1,1>x|1,-1>/2
+
+    Uncouple a symbolic state using a CoupledSpinState state:
+
+        >>> from sympy import symbols
+        >>> j,m,j1,j2 = symbols('j m j1 j2')
+        >>> uncouple(JzKetCoupled(j, m, (j1, j2)))
+        Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2))
+
+    Perform the same calculation using a SpinState state
+
+        >>> uncouple(JzKet(j, m), (j1, j2))
+        Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2))
+
+    """
+    a = expr.atoms(SpinState)
+    for state in a:
+        expr = expr.subs(state, _uncouple(state, jn, jcoupling_list))
+    return expr
+
+
+def _uncouple(state, jn, jcoupling_list):
+    if isinstance(state, CoupledSpinState):
+        jn = state.jn
+        coupled_n = state.coupled_n
+        coupled_jn = state.coupled_jn
+        evect = state.uncoupled_class()
+    elif isinstance(state, SpinState):
+        if jn is None:
+            raise ValueError("Must specify j-values for coupled state")
+        if not isinstance(jn, (list, tuple)):
+            raise TypeError("jn must be list or tuple")
+        if jcoupling_list is None:
+            # Use default
+            jcoupling_list = []
+            for i in range(1, len(jn)):
+                jcoupling_list.append(
+                    (1, 1 + i, Add(*[jn[j] for j in range(i + 1)])) )
+        if not isinstance(jcoupling_list, (list, tuple)):
+            raise TypeError("jcoupling must be a list or tuple")
+        if not len(jcoupling_list) == len(jn) - 1:
+            raise ValueError("Must specify 2 fewer coupling terms than the number of j values")
+        coupled_n, coupled_jn = _build_coupled(jcoupling_list, len(jn))
+        evect = state.__class__
+    else:
+        raise TypeError("state must be a spin state")
+    j = state.j
+    m = state.m
+    coupling_list = []
+    j_list = list(jn)
+
+    # Create coupling, which defines all the couplings between all the spaces
+    for j3, (n1, n2) in zip(coupled_jn, coupled_n):
+        # j's which are coupled as first and second spaces
+        j1 = j_list[n1[0] - 1]
+        j2 = j_list[n2[0] - 1]
+        # Build coupling list
+        coupling_list.append( (n1, n2, j1, j2, j3) )
+        # Set new value in j_list
+        j_list[min(n1 + n2) - 1] = j3
+
+    if j.is_number and m.is_number:
+        diff_max = [ 2*x for x in jn ]
+        diff = Add(*jn) - m
+
+        n = len(jn)
+        tot = binomial(diff + n - 1, diff)
+
+        result = []
+        for config_num in range(tot):
+            diff_list = _confignum_to_difflist(config_num, diff, n)
+            if any(d > p for d, p in zip(diff_list, diff_max)):
+                continue
+
+            cg_terms = []
+            for coupling in coupling_list:
+                j1_n, j2_n, j1, j2, j3 = coupling
+                m1 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j1_n ] )
+                m2 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j2_n ] )
+                m3 = m1 + m2
+                cg_terms.append( (j1, m1, j2, m2, j3, m3) )
+            coeff = Mul( *[ CG(*term).doit() for term in cg_terms ] )
+            state = TensorProduct(
+                *[ evect(j, j - d) for j, d in zip(jn, diff_list) ] )
+            result.append(coeff*state)
+        return Add(*result)
+    else:
+        # Symbolic coupling
+        m_str = "m1:%d" % (len(jn) + 1)
+        mvals = symbols(m_str)
+        cg_terms = [(j1, Add(*[mvals[n - 1] for n in j1_n]),
+                     j2, Add(*[mvals[n - 1] for n in j2_n]),
+                     j3, Add(*[mvals[n - 1] for n in j1_n + j2_n])) for j1_n, j2_n, j1, j2, j3 in coupling_list[:-1] ]
+        cg_terms.append(*[(j1, Add(*[mvals[n - 1] for n in j1_n]),
+                           j2, Add(*[mvals[n - 1] for n in j2_n]),
+                           j, m) for j1_n, j2_n, j1, j2, j3 in [coupling_list[-1]] ])
+        cg_coeff = Mul(*[CG(*cg_term) for cg_term in cg_terms])
+        sum_terms = [ (m, -j, j) for j, m in zip(jn, mvals) ]
+        state = TensorProduct( *[ evect(j, m) for j, m in zip(jn, mvals) ] )
+        return Sum(cg_coeff*state, *sum_terms)
+
+
+def _confignum_to_difflist(config_num, diff, list_len):
+    # Determines configuration of diffs into list_len number of slots
+    diff_list = []
+    for n in range(list_len):
+        prev_diff = diff
+        # Number of spots after current one
+        rem_spots = list_len - n - 1
+        # Number of configurations of distributing diff among the remaining spots
+        rem_configs = binomial(diff + rem_spots - 1, diff)
+        while config_num >= rem_configs:
+            config_num -= rem_configs
+            diff -= 1
+            rem_configs = binomial(diff + rem_spots - 1, diff)
+        diff_list.append(prev_diff - diff)
+    return diff_list
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/state.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/state.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ccd1ce9b9875b59a5d1293ab3026808bdc85b27
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/state.py
@@ -0,0 +1,987 @@
+"""Dirac notation for states."""
+
+from sympy.core.cache import cacheit
+from sympy.core.containers import Tuple
+from sympy.core.expr import Expr
+from sympy.core.function import Function
+from sympy.core.numbers import oo, equal_valued
+from sympy.core.singleton import S
+from sympy.functions.elementary.complexes import conjugate
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.integrals.integrals import integrate
+from sympy.printing.pretty.stringpict import stringPict
+from sympy.physics.quantum.qexpr import QExpr, dispatch_method
+from sympy.physics.quantum.kind import KetKind, BraKind
+
+
+__all__ = [
+    'KetBase',
+    'BraBase',
+    'StateBase',
+    'State',
+    'Ket',
+    'Bra',
+    'TimeDepState',
+    'TimeDepBra',
+    'TimeDepKet',
+    'OrthogonalKet',
+    'OrthogonalBra',
+    'OrthogonalState',
+    'Wavefunction'
+]
+
+
+#-----------------------------------------------------------------------------
+# States, bras and kets.
+#-----------------------------------------------------------------------------
+
+# ASCII brackets
+_lbracket = "<"
+_rbracket = ">"
+_straight_bracket = "|"
+
+
+# Unicode brackets
+# MATHEMATICAL ANGLE BRACKETS
+_lbracket_ucode = "\N{MATHEMATICAL LEFT ANGLE BRACKET}"
+_rbracket_ucode = "\N{MATHEMATICAL RIGHT ANGLE BRACKET}"
+# LIGHT VERTICAL BAR
+_straight_bracket_ucode = "\N{LIGHT VERTICAL BAR}"
+
+# Other options for unicode printing of <, > and | for Dirac notation.
+
+# LEFT-POINTING ANGLE BRACKET
+# _lbracket = "\u2329"
+# _rbracket = "\u232A"
+
+# LEFT ANGLE BRACKET
+# _lbracket = "\u3008"
+# _rbracket = "\u3009"
+
+# VERTICAL LINE
+# _straight_bracket = "\u007C"
+
+
+class StateBase(QExpr):
+    """Abstract base class for general abstract states in quantum mechanics.
+
+    All other state classes defined will need to inherit from this class. It
+    carries the basic structure for all other states such as dual, _eval_adjoint
+    and label.
+
+    This is an abstract base class and you should not instantiate it directly,
+    instead use State.
+    """
+
+    @classmethod
+    def _operators_to_state(self, ops, **options):
+        """ Returns the eigenstate instance for the passed operators.
+
+        This method should be overridden in subclasses. It will handle being
+        passed either an Operator instance or set of Operator instances. It
+        should return the corresponding state INSTANCE or simply raise a
+        NotImplementedError. See cartesian.py for an example.
+        """
+
+        raise NotImplementedError("Cannot map operators to states in this class. Method not implemented!")
+
+    def _state_to_operators(self, op_classes, **options):
+        """ Returns the operators which this state instance is an eigenstate
+        of.
+
+        This method should be overridden in subclasses. It will be called on
+        state instances and be passed the operator classes that we wish to make
+        into instances. The state instance will then transform the classes
+        appropriately, or raise a NotImplementedError if it cannot return
+        operator instances. See cartesian.py for examples,
+        """
+
+        raise NotImplementedError(
+            "Cannot map this state to operators. Method not implemented!")
+
+    @property
+    def operators(self):
+        """Return the operator(s) that this state is an eigenstate of"""
+        from .operatorset import state_to_operators  # import internally to avoid circular import errors
+        return state_to_operators(self)
+
+    def _enumerate_state(self, num_states, **options):
+        raise NotImplementedError("Cannot enumerate this state!")
+
+    def _represent_default_basis(self, **options):
+        return self._represent(basis=self.operators)
+
+    def _apply_operator(self, op, **options):
+        return None
+
+    #-------------------------------------------------------------------------
+    # Dagger/dual
+    #-------------------------------------------------------------------------
+
+    @property
+    def dual(self):
+        """Return the dual state of this one."""
+        return self.dual_class()._new_rawargs(self.hilbert_space, *self.args)
+
+    @classmethod
+    def dual_class(self):
+        """Return the class used to construct the dual."""
+        raise NotImplementedError(
+            'dual_class must be implemented in a subclass'
+        )
+
+    def _eval_adjoint(self):
+        """Compute the dagger of this state using the dual."""
+        return self.dual
+
+    #-------------------------------------------------------------------------
+    # Printing
+    #-------------------------------------------------------------------------
+
+    def _pretty_brackets(self, height, use_unicode=True):
+        # Return pretty printed brackets for the state
+        # Ideally, this could be done by pform.parens but it does not support the angled < and >
+
+        # Setup for unicode vs ascii
+        if use_unicode:
+            lbracket, rbracket = getattr(self, 'lbracket_ucode', ""), getattr(self, 'rbracket_ucode', "")
+            slash, bslash, vert = '\N{BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT}', \
+                                  '\N{BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT}', \
+                                  '\N{BOX DRAWINGS LIGHT VERTICAL}'
+        else:
+            lbracket, rbracket = getattr(self, 'lbracket', ""), getattr(self, 'rbracket', "")
+            slash, bslash, vert = '/', '\\', '|'
+
+        # If height is 1, just return brackets
+        if height == 1:
+            return stringPict(lbracket), stringPict(rbracket)
+        # Make height even
+        height += (height % 2)
+
+        brackets = []
+        for bracket in lbracket, rbracket:
+            # Create left bracket
+            if bracket in {_lbracket, _lbracket_ucode}:
+                bracket_args = [ ' ' * (height//2 - i - 1) +
+                                 slash for i in range(height // 2)]
+                bracket_args.extend(
+                    [' ' * i + bslash for i in range(height // 2)])
+            # Create right bracket
+            elif bracket in {_rbracket, _rbracket_ucode}:
+                bracket_args = [ ' ' * i + bslash for i in range(height // 2)]
+                bracket_args.extend([ ' ' * (
+                    height//2 - i - 1) + slash for i in range(height // 2)])
+            # Create straight bracket
+            elif bracket in {_straight_bracket, _straight_bracket_ucode}:
+                bracket_args = [vert] * height
+            else:
+                raise ValueError(bracket)
+            brackets.append(
+                stringPict('\n'.join(bracket_args), baseline=height//2))
+        return brackets
+
+    def _sympystr(self, printer, *args):
+        contents = self._print_contents(printer, *args)
+        return '%s%s%s' % (getattr(self, 'lbracket', ""), contents, getattr(self, 'rbracket', ""))
+
+    def _pretty(self, printer, *args):
+        from sympy.printing.pretty.stringpict import prettyForm
+        # Get brackets
+        pform = self._print_contents_pretty(printer, *args)
+        lbracket, rbracket = self._pretty_brackets(
+            pform.height(), printer._use_unicode)
+        # Put together state
+        pform = prettyForm(*pform.left(lbracket))
+        pform = prettyForm(*pform.right(rbracket))
+        return pform
+
+    def _latex(self, printer, *args):
+        contents = self._print_contents_latex(printer, *args)
+        # The extra {} brackets are needed to get matplotlib's latex
+        # rendered to render this properly.
+        return '{%s%s%s}' % (getattr(self, 'lbracket_latex', ""), contents, getattr(self, 'rbracket_latex', ""))
+
+
+class KetBase(StateBase):
+    """Base class for Kets.
+
+    This class defines the dual property and the brackets for printing. This is
+    an abstract base class and you should not instantiate it directly, instead
+    use Ket.
+    """
+
+    kind = KetKind
+
+    lbracket = _straight_bracket
+    rbracket = _rbracket
+    lbracket_ucode = _straight_bracket_ucode
+    rbracket_ucode = _rbracket_ucode
+    lbracket_latex = r'\left|'
+    rbracket_latex = r'\right\rangle '
+
+    @classmethod
+    def default_args(self):
+        return ("psi",)
+
+    @classmethod
+    def dual_class(self):
+        return BraBase
+
+    #-------------------------------------------------------------------------
+    # _eval_* methods
+    #-------------------------------------------------------------------------
+
+    def _eval_innerproduct(self, bra, **hints):
+        """Evaluate the inner product between this ket and a bra.
+
+        This is called to compute , where the ket is ``self``.
+
+        This method will dispatch to sub-methods having the format::
+
+            ``def _eval_innerproduct_BraClass(self, **hints):``
+
+        Subclasses should define these methods (one for each BraClass) to
+        teach the ket how to take inner products with bras.
+        """
+        return dispatch_method(self, '_eval_innerproduct', bra, **hints)
+
+    def _apply_from_right_to(self, op, **options):
+        """Apply an Operator to this Ket as Operator*Ket
+
+        This method will dispatch to methods having the format::
+
+            ``def _apply_from_right_to_OperatorName(op, **options):``
+
+        Subclasses should define these methods (one for each OperatorName) to
+        teach the Ket how to implement OperatorName*Ket
+
+        Parameters
+        ==========
+
+        op : Operator
+            The Operator that is acting on the Ket as op*Ket
+        options : dict
+            A dict of key/value pairs that control how the operator is applied
+            to the Ket.
+        """
+        return dispatch_method(self, '_apply_from_right_to', op, **options)
+
+
+class BraBase(StateBase):
+    """Base class for Bras.
+
+    This class defines the dual property and the brackets for printing. This
+    is an abstract base class and you should not instantiate it directly,
+    instead use Bra.
+    """
+
+    kind = BraKind
+
+    lbracket = _lbracket
+    rbracket = _straight_bracket
+    lbracket_ucode = _lbracket_ucode
+    rbracket_ucode = _straight_bracket_ucode
+    lbracket_latex = r'\left\langle '
+    rbracket_latex = r'\right|'
+
+    @classmethod
+    def _operators_to_state(self, ops, **options):
+        state = self.dual_class()._operators_to_state(ops, **options)
+        return state.dual
+
+    def _state_to_operators(self, op_classes, **options):
+        return self.dual._state_to_operators(op_classes, **options)
+
+    def _enumerate_state(self, num_states, **options):
+        dual_states = self.dual._enumerate_state(num_states, **options)
+        return [x.dual for x in dual_states]
+
+    @classmethod
+    def default_args(self):
+        return self.dual_class().default_args()
+
+    @classmethod
+    def dual_class(self):
+        return KetBase
+
+    def _represent(self, **options):
+        """A default represent that uses the Ket's version."""
+        from sympy.physics.quantum.dagger import Dagger
+        return Dagger(self.dual._represent(**options))
+
+
+class State(StateBase):
+    """General abstract quantum state used as a base class for Ket and Bra."""
+    pass
+
+
+class Ket(State, KetBase):
+    """A general time-independent Ket in quantum mechanics.
+
+    Inherits from State and KetBase. This class should be used as the base
+    class for all physical, time-independent Kets in a system. This class
+    and its subclasses will be the main classes that users will use for
+    expressing Kets in Dirac notation [1]_.
+
+    Parameters
+    ==========
+
+    args : tuple
+        The list of numbers or parameters that uniquely specify the
+        ket. This will usually be its symbol or its quantum numbers. For
+        time-dependent state, this will include the time.
+
+    Examples
+    ========
+
+    Create a simple Ket and looking at its properties::
+
+        >>> from sympy.physics.quantum import Ket
+        >>> from sympy import symbols, I
+        >>> k = Ket('psi')
+        >>> k
+        |psi>
+        >>> k.hilbert_space
+        H
+        >>> k.is_commutative
+        False
+        >>> k.label
+        (psi,)
+
+    Ket's know about their associated bra::
+
+        >>> k.dual
+        >> k.dual_class()
+        
+
+    Take a linear combination of two kets::
+
+        >>> k0 = Ket(0)
+        >>> k1 = Ket(1)
+        >>> 2*I*k0 - 4*k1
+        2*I*|0> - 4*|1>
+
+    Compound labels are passed as tuples::
+
+        >>> n, m = symbols('n,m')
+        >>> k = Ket(n,m)
+        >>> k
+        |nm>
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Bra-ket_notation
+    """
+
+    @classmethod
+    def dual_class(self):
+        return Bra
+
+
+class Bra(State, BraBase):
+    """A general time-independent Bra in quantum mechanics.
+
+    Inherits from State and BraBase. A Bra is the dual of a Ket [1]_. This
+    class and its subclasses will be the main classes that users will use for
+    expressing Bras in Dirac notation.
+
+    Parameters
+    ==========
+
+    args : tuple
+        The list of numbers or parameters that uniquely specify the
+        ket. This will usually be its symbol or its quantum numbers. For
+        time-dependent state, this will include the time.
+
+    Examples
+    ========
+
+    Create a simple Bra and look at its properties::
+
+        >>> from sympy.physics.quantum import Bra
+        >>> from sympy import symbols, I
+        >>> b = Bra('psi')
+        >>> b
+        >> b.hilbert_space
+        H
+        >>> b.is_commutative
+        False
+
+    Bra's know about their dual Ket's::
+
+        >>> b.dual
+        |psi>
+        >>> b.dual_class()
+        
+
+    Like Kets, Bras can have compound labels and be manipulated in a similar
+    manner::
+
+        >>> n, m = symbols('n,m')
+        >>> b = Bra(n,m) - I*Bra(m,n)
+        >>> b
+        -I*>> b.subs(n,m)
+        >> from sympy.physics.quantum import TimeDepKet
+        >>> k = TimeDepKet('psi', 't')
+        >>> k
+        |psi;t>
+        >>> k.time
+        t
+        >>> k.label
+        (psi,)
+        >>> k.hilbert_space
+        H
+
+    TimeDepKets know about their dual bra::
+
+        >>> k.dual
+        >> k.dual_class()
+        
+    """
+
+    @classmethod
+    def dual_class(self):
+        return TimeDepBra
+
+
+class TimeDepBra(TimeDepState, BraBase):
+    """General time-dependent Bra in quantum mechanics.
+
+    This inherits from TimeDepState and BraBase and is the main class that
+    should be used for Bras that vary with time. Its dual is a TimeDepBra.
+
+    Parameters
+    ==========
+
+    args : tuple
+        The list of numbers or parameters that uniquely specify the ket. This
+        will usually be its symbol or its quantum numbers. For time-dependent
+        state, this will include the time as the final argument.
+
+    Examples
+    ========
+
+        >>> from sympy.physics.quantum import TimeDepBra
+        >>> b = TimeDepBra('psi', 't')
+        >>> b
+        >> b.time
+        t
+        >>> b.label
+        (psi,)
+        >>> b.hilbert_space
+        H
+        >>> b.dual
+        |psi;t>
+    """
+
+    @classmethod
+    def dual_class(self):
+        return TimeDepKet
+
+
+class OrthogonalState(State):
+    """General abstract quantum state used as a base class for Ket and Bra."""
+    pass
+
+class OrthogonalKet(OrthogonalState, KetBase):
+    """Orthogonal Ket in quantum mechanics.
+
+    The inner product of two states with different labels will give zero,
+    states with the same label will give one.
+
+        >>> from sympy.physics.quantum import OrthogonalBra, OrthogonalKet
+        >>> from sympy.abc import m, n
+        >>> (OrthogonalBra(n)*OrthogonalKet(n)).doit()
+        1
+        >>> (OrthogonalBra(n)*OrthogonalKet(n+1)).doit()
+        0
+        >>> (OrthogonalBra(n)*OrthogonalKet(m)).doit()
+        
+    """
+
+    @classmethod
+    def dual_class(self):
+        return OrthogonalBra
+
+    def _eval_innerproduct(self, bra, **hints):
+
+        if len(self.args) != len(bra.args):
+            raise ValueError('Cannot multiply a ket that has a different number of labels.')
+
+        for arg, bra_arg in zip(self.args, bra.args):
+            diff = arg - bra_arg
+            diff = diff.expand()
+
+            is_zero = diff.is_zero
+
+            if is_zero is False:
+                return S.Zero # i.e. Integer(0)
+
+            if is_zero is None:
+                return None
+
+        return S.One # i.e. Integer(1)
+
+
+class OrthogonalBra(OrthogonalState, BraBase):
+    """Orthogonal Bra in quantum mechanics.
+    """
+
+    @classmethod
+    def dual_class(self):
+        return OrthogonalKet
+
+
+class Wavefunction(Function):
+    """Class for representations in continuous bases
+
+    This class takes an expression and coordinates in its constructor. It can
+    be used to easily calculate normalizations and probabilities.
+
+    Parameters
+    ==========
+
+    expr : Expr
+           The expression representing the functional form of the w.f.
+
+    coords : Symbol or tuple
+           The coordinates to be integrated over, and their bounds
+
+    Examples
+    ========
+
+    Particle in a box, specifying bounds in the more primitive way of using
+    Piecewise:
+
+        >>> from sympy import Symbol, Piecewise, pi, N
+        >>> from sympy.functions import sqrt, sin
+        >>> from sympy.physics.quantum.state import Wavefunction
+        >>> x = Symbol('x', real=True)
+        >>> n = 1
+        >>> L = 1
+        >>> g = Piecewise((0, x < 0), (0, x > L), (sqrt(2//L)*sin(n*pi*x/L), True))
+        >>> f = Wavefunction(g, x)
+        >>> f.norm
+        1
+        >>> f.is_normalized
+        True
+        >>> p = f.prob()
+        >>> p(0)
+        0
+        >>> p(L)
+        0
+        >>> p(0.5)
+        2
+        >>> p(0.85*L)
+        2*sin(0.85*pi)**2
+        >>> N(p(0.85*L))
+        0.412214747707527
+
+    Additionally, you can specify the bounds of the function and the indices in
+    a more compact way:
+
+        >>> from sympy import symbols, pi, diff
+        >>> from sympy.functions import sqrt, sin
+        >>> from sympy.physics.quantum.state import Wavefunction
+        >>> x, L = symbols('x,L', positive=True)
+        >>> n = symbols('n', integer=True, positive=True)
+        >>> g = sqrt(2/L)*sin(n*pi*x/L)
+        >>> f = Wavefunction(g, (x, 0, L))
+        >>> f.norm
+        1
+        >>> f(L+1)
+        0
+        >>> f(L-1)
+        sqrt(2)*sin(pi*n*(L - 1)/L)/sqrt(L)
+        >>> f(-1)
+        0
+        >>> f(0.85)
+        sqrt(2)*sin(0.85*pi*n/L)/sqrt(L)
+        >>> f(0.85, n=1, L=1)
+        sqrt(2)*sin(0.85*pi)
+        >>> f.is_commutative
+        False
+
+    All arguments are automatically sympified, so you can define the variables
+    as strings rather than symbols:
+
+        >>> expr = x**2
+        >>> f = Wavefunction(expr, 'x')
+        >>> type(f.variables[0])
+        
+
+    Derivatives of Wavefunctions will return Wavefunctions:
+
+        >>> diff(f, x)
+        Wavefunction(2*x, x)
+
+    """
+
+    #Any passed tuples for coordinates and their bounds need to be
+    #converted to Tuples before Function's constructor is called, to
+    #avoid errors from calling is_Float in the constructor
+    def __new__(cls, *args, **options):
+        new_args = [None for i in args]
+        ct = 0
+        for arg in args:
+            if isinstance(arg, tuple):
+                new_args[ct] = Tuple(*arg)
+            else:
+                new_args[ct] = arg
+            ct += 1
+
+        return super().__new__(cls, *new_args, **options)
+
+    def __call__(self, *args, **options):
+        var = self.variables
+
+        if len(args) != len(var):
+            raise NotImplementedError(
+                "Incorrect number of arguments to function!")
+
+        ct = 0
+        #If the passed value is outside the specified bounds, return 0
+        for v in var:
+            lower, upper = self.limits[v]
+
+            #Do the comparison to limits only if the passed symbol is actually
+            #a symbol present in the limits;
+            #Had problems with a comparison of x > L
+            if isinstance(args[ct], Expr) and \
+                not (lower in args[ct].free_symbols
+                     or upper in args[ct].free_symbols):
+                continue
+
+            if (args[ct] < lower) == True or (args[ct] > upper) == True:
+                return S.Zero
+
+            ct += 1
+
+        expr = self.expr
+
+        #Allows user to make a call like f(2, 4, m=1, n=1)
+        for symbol in list(expr.free_symbols):
+            if str(symbol) in options.keys():
+                val = options[str(symbol)]
+                expr = expr.subs(symbol, val)
+
+        return expr.subs(zip(var, args))
+
+    def _eval_derivative(self, symbol):
+        expr = self.expr
+        deriv = expr._eval_derivative(symbol)
+
+        return Wavefunction(deriv, *self.args[1:])
+
+    def _eval_conjugate(self):
+        return Wavefunction(conjugate(self.expr), *self.args[1:])
+
+    def _eval_transpose(self):
+        return self
+
+    @property
+    def is_commutative(self):
+        """
+        Override Function's is_commutative so that order is preserved in
+        represented expressions
+        """
+        return False
+
+    @classmethod
+    def eval(self, *args):
+        return None
+
+    @property
+    def variables(self):
+        """
+        Return the coordinates which the wavefunction depends on
+
+        Examples
+        ========
+
+            >>> from sympy.physics.quantum.state import Wavefunction
+            >>> from sympy import symbols
+            >>> x,y = symbols('x,y')
+            >>> f = Wavefunction(x*y, x, y)
+            >>> f.variables
+            (x, y)
+            >>> g = Wavefunction(x*y, x)
+            >>> g.variables
+            (x,)
+
+        """
+        var = [g[0] if isinstance(g, Tuple) else g for g in self._args[1:]]
+        return tuple(var)
+
+    @property
+    def limits(self):
+        """
+        Return the limits of the coordinates which the w.f. depends on If no
+        limits are specified, defaults to ``(-oo, oo)``.
+
+        Examples
+        ========
+
+            >>> from sympy.physics.quantum.state import Wavefunction
+            >>> from sympy import symbols
+            >>> x, y = symbols('x, y')
+            >>> f = Wavefunction(x**2, (x, 0, 1))
+            >>> f.limits
+            {x: (0, 1)}
+            >>> f = Wavefunction(x**2, x)
+            >>> f.limits
+            {x: (-oo, oo)}
+            >>> f = Wavefunction(x**2 + y**2, x, (y, -1, 2))
+            >>> f.limits
+            {x: (-oo, oo), y: (-1, 2)}
+
+        """
+        limits = [(g[1], g[2]) if isinstance(g, Tuple) else (-oo, oo)
+                  for g in self._args[1:]]
+        return dict(zip(self.variables, tuple(limits)))
+
+    @property
+    def expr(self):
+        """
+        Return the expression which is the functional form of the Wavefunction
+
+        Examples
+        ========
+
+            >>> from sympy.physics.quantum.state import Wavefunction
+            >>> from sympy import symbols
+            >>> x, y = symbols('x, y')
+            >>> f = Wavefunction(x**2, x)
+            >>> f.expr
+            x**2
+
+        """
+        return self._args[0]
+
+    @property
+    def is_normalized(self):
+        """
+        Returns true if the Wavefunction is properly normalized
+
+        Examples
+        ========
+
+            >>> from sympy import symbols, pi
+            >>> from sympy.functions import sqrt, sin
+            >>> from sympy.physics.quantum.state import Wavefunction
+            >>> x, L = symbols('x,L', positive=True)
+            >>> n = symbols('n', integer=True, positive=True)
+            >>> g = sqrt(2/L)*sin(n*pi*x/L)
+            >>> f = Wavefunction(g, (x, 0, L))
+            >>> f.is_normalized
+            True
+
+        """
+
+        return equal_valued(self.norm, 1)
+
+    @property  # type: ignore
+    @cacheit
+    def norm(self):
+        """
+        Return the normalization of the specified functional form.
+
+        This function integrates over the coordinates of the Wavefunction, with
+        the bounds specified.
+
+        Examples
+        ========
+
+            >>> from sympy import symbols, pi
+            >>> from sympy.functions import sqrt, sin
+            >>> from sympy.physics.quantum.state import Wavefunction
+            >>> x, L = symbols('x,L', positive=True)
+            >>> n = symbols('n', integer=True, positive=True)
+            >>> g = sqrt(2/L)*sin(n*pi*x/L)
+            >>> f = Wavefunction(g, (x, 0, L))
+            >>> f.norm
+            1
+            >>> g = sin(n*pi*x/L)
+            >>> f = Wavefunction(g, (x, 0, L))
+            >>> f.norm
+            sqrt(2)*sqrt(L)/2
+
+        """
+
+        exp = self.expr*conjugate(self.expr)
+        var = self.variables
+        limits = self.limits
+
+        for v in var:
+            curr_limits = limits[v]
+            exp = integrate(exp, (v, curr_limits[0], curr_limits[1]))
+
+        return sqrt(exp)
+
+    def normalize(self):
+        """
+        Return a normalized version of the Wavefunction
+
+        Examples
+        ========
+
+            >>> from sympy import symbols, pi
+            >>> from sympy.functions import sin
+            >>> from sympy.physics.quantum.state import Wavefunction
+            >>> x = symbols('x', real=True)
+            >>> L = symbols('L', positive=True)
+            >>> n = symbols('n', integer=True, positive=True)
+            >>> g = sin(n*pi*x/L)
+            >>> f = Wavefunction(g, (x, 0, L))
+            >>> f.normalize()
+            Wavefunction(sqrt(2)*sin(pi*n*x/L)/sqrt(L), (x, 0, L))
+
+        """
+        const = self.norm
+
+        if const is oo:
+            raise NotImplementedError("The function is not normalizable!")
+        else:
+            return Wavefunction((const)**(-1)*self.expr, *self.args[1:])
+
+    def prob(self):
+        r"""
+        Return the absolute magnitude of the w.f., `|\psi(x)|^2`
+
+        Examples
+        ========
+
+            >>> from sympy import symbols, pi
+            >>> from sympy.functions import sin
+            >>> from sympy.physics.quantum.state import Wavefunction
+            >>> x, L = symbols('x,L', real=True)
+            >>> n = symbols('n', integer=True)
+            >>> g = sin(n*pi*x/L)
+            >>> f = Wavefunction(g, (x, 0, L))
+            >>> f.prob()
+            Wavefunction(sin(pi*n*x/L)**2, x)
+
+        """
+
+        return Wavefunction(self.expr*conjugate(self.expr), *self.variables)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tensorproduct.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tensorproduct.py
new file mode 100644
index 0000000000000000000000000000000000000000..058b3459227e5a020e2d0397fc66f56a2f917293
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tensorproduct.py
@@ -0,0 +1,363 @@
+"""Abstract tensor product."""
+
+from sympy.core.add import Add
+from sympy.core.expr import Expr
+from sympy.core.kind import KindDispatcher
+from sympy.core.mul import Mul
+from sympy.core.power import Pow
+from sympy.core.sympify import sympify
+from sympy.matrices.dense import DenseMatrix as Matrix
+from sympy.matrices.immutable import ImmutableDenseMatrix as ImmutableMatrix
+from sympy.printing.pretty.stringpict import prettyForm
+from sympy.utilities.exceptions import sympy_deprecation_warning
+
+from sympy.physics.quantum.dagger import Dagger
+from sympy.physics.quantum.kind import (
+    KetKind, _KetKind,
+    BraKind, _BraKind,
+    OperatorKind, _OperatorKind
+)
+from sympy.physics.quantum.matrixutils import (
+    numpy_ndarray,
+    scipy_sparse_matrix,
+    matrix_tensor_product
+)
+from sympy.physics.quantum.state import Ket, Bra
+from sympy.physics.quantum.trace import Tr
+
+
+__all__ = [
+    'TensorProduct',
+    'tensor_product_simp'
+]
+
+#-----------------------------------------------------------------------------
+# Tensor product
+#-----------------------------------------------------------------------------
+
+_combined_printing = False
+
+
+def combined_tensor_printing(combined):
+    """Set flag controlling whether tensor products of states should be
+    printed as a combined bra/ket or as an explicit tensor product of different
+    bra/kets. This is a global setting for all TensorProduct class instances.
+
+    Parameters
+    ----------
+    combine : bool
+        When true, tensor product states are combined into one ket/bra, and
+        when false explicit tensor product notation is used between each
+        ket/bra.
+    """
+    global _combined_printing
+    _combined_printing = combined
+
+
+class TensorProduct(Expr):
+    """The tensor product of two or more arguments.
+
+    For matrices, this uses ``matrix_tensor_product`` to compute the Kronecker
+    or tensor product matrix. For other objects a symbolic ``TensorProduct``
+    instance is returned. The tensor product is a non-commutative
+    multiplication that is used primarily with operators and states in quantum
+    mechanics.
+
+    Currently, the tensor product distinguishes between commutative and
+    non-commutative arguments.  Commutative arguments are assumed to be scalars
+    and are pulled out in front of the ``TensorProduct``. Non-commutative
+    arguments remain in the resulting ``TensorProduct``.
+
+    Parameters
+    ==========
+
+    args : tuple
+        A sequence of the objects to take the tensor product of.
+
+    Examples
+    ========
+
+    Start with a simple tensor product of SymPy matrices::
+
+        >>> from sympy import Matrix
+        >>> from sympy.physics.quantum import TensorProduct
+
+        >>> m1 = Matrix([[1,2],[3,4]])
+        >>> m2 = Matrix([[1,0],[0,1]])
+        >>> TensorProduct(m1, m2)
+        Matrix([
+        [1, 0, 2, 0],
+        [0, 1, 0, 2],
+        [3, 0, 4, 0],
+        [0, 3, 0, 4]])
+        >>> TensorProduct(m2, m1)
+        Matrix([
+        [1, 2, 0, 0],
+        [3, 4, 0, 0],
+        [0, 0, 1, 2],
+        [0, 0, 3, 4]])
+
+    We can also construct tensor products of non-commutative symbols:
+
+        >>> from sympy import Symbol
+        >>> A = Symbol('A',commutative=False)
+        >>> B = Symbol('B',commutative=False)
+        >>> tp = TensorProduct(A, B)
+        >>> tp
+        AxB
+
+    We can take the dagger of a tensor product (note the order does NOT reverse
+    like the dagger of a normal product):
+
+        >>> from sympy.physics.quantum import Dagger
+        >>> Dagger(tp)
+        Dagger(A)xDagger(B)
+
+    Expand can be used to distribute a tensor product across addition:
+
+        >>> C = Symbol('C',commutative=False)
+        >>> tp = TensorProduct(A+B,C)
+        >>> tp
+        (A + B)xC
+        >>> tp.expand(tensorproduct=True)
+        AxC + BxC
+    """
+    is_commutative = False
+
+    _kind_dispatcher = KindDispatcher("TensorProduct_kind_dispatcher", commutative=True)
+
+    @property
+    def kind(self):
+        """Calculate the kind of a tensor product by looking at its children."""
+        arg_kinds = (a.kind for a in self.args)
+        return self._kind_dispatcher(*arg_kinds)
+
+    def __new__(cls, *args):
+        if isinstance(args[0], (Matrix, ImmutableMatrix, numpy_ndarray,
+                                                    scipy_sparse_matrix)):
+            return matrix_tensor_product(*args)
+        c_part, new_args = cls.flatten(sympify(args))
+        c_part = Mul(*c_part)
+        if len(new_args) == 0:
+            return c_part
+        elif len(new_args) == 1:
+            return c_part * new_args[0]
+        else:
+            tp = Expr.__new__(cls, *new_args)
+            return c_part * tp
+
+    @classmethod
+    def flatten(cls, args):
+        # TODO: disallow nested TensorProducts.
+        c_part = []
+        nc_parts = []
+        for arg in args:
+            cp, ncp = arg.args_cnc()
+            c_part.extend(list(cp))
+            nc_parts.append(Mul._from_args(ncp))
+        return c_part, nc_parts
+
+    def _eval_adjoint(self):
+        return TensorProduct(*[Dagger(i) for i in self.args])
+
+    def _eval_rewrite(self, rule, args, **hints):
+        return TensorProduct(*args).expand(tensorproduct=True)
+
+    def _sympystr(self, printer, *args):
+        length = len(self.args)
+        s = ''
+        for i in range(length):
+            if isinstance(self.args[i], (Add, Pow, Mul)):
+                s = s + '('
+            s = s + printer._print(self.args[i])
+            if isinstance(self.args[i], (Add, Pow, Mul)):
+                s = s + ')'
+            if i != length - 1:
+                s = s + 'x'
+        return s
+
+    def _pretty(self, printer, *args):
+
+        if (_combined_printing and
+                (all(isinstance(arg, Ket) for arg in self.args) or
+                 all(isinstance(arg, Bra) for arg in self.args))):
+
+            length = len(self.args)
+            pform = printer._print('', *args)
+            for i in range(length):
+                next_pform = printer._print('', *args)
+                length_i = len(self.args[i].args)
+                for j in range(length_i):
+                    part_pform = printer._print(self.args[i].args[j], *args)
+                    next_pform = prettyForm(*next_pform.right(part_pform))
+                    if j != length_i - 1:
+                        next_pform = prettyForm(*next_pform.right(', '))
+
+                if len(self.args[i].args) > 1:
+                    next_pform = prettyForm(
+                        *next_pform.parens(left='{', right='}'))
+                pform = prettyForm(*pform.right(next_pform))
+                if i != length - 1:
+                    pform = prettyForm(*pform.right(',' + ' '))
+
+            pform = prettyForm(*pform.left(self.args[0].lbracket))
+            pform = prettyForm(*pform.right(self.args[0].rbracket))
+            return pform
+
+        length = len(self.args)
+        pform = printer._print('', *args)
+        for i in range(length):
+            next_pform = printer._print(self.args[i], *args)
+            if isinstance(self.args[i], (Add, Mul)):
+                next_pform = prettyForm(
+                    *next_pform.parens(left='(', right=')')
+                )
+            pform = prettyForm(*pform.right(next_pform))
+            if i != length - 1:
+                if printer._use_unicode:
+                    pform = prettyForm(*pform.right('\N{N-ARY CIRCLED TIMES OPERATOR}' + ' '))
+                else:
+                    pform = prettyForm(*pform.right('x' + ' '))
+        return pform
+
+    def _latex(self, printer, *args):
+
+        if (_combined_printing and
+                (all(isinstance(arg, Ket) for arg in self.args) or
+                 all(isinstance(arg, Bra) for arg in self.args))):
+
+            def _label_wrap(label, nlabels):
+                return label if nlabels == 1 else r"\left\{%s\right\}" % label
+
+            s = r", ".join([_label_wrap(arg._print_label_latex(printer, *args),
+                                        len(arg.args)) for arg in self.args])
+
+            return r"{%s%s%s}" % (self.args[0].lbracket_latex, s,
+                                  self.args[0].rbracket_latex)
+
+        length = len(self.args)
+        s = ''
+        for i in range(length):
+            if isinstance(self.args[i], (Add, Mul)):
+                s = s + '\\left('
+            # The extra {} brackets are needed to get matplotlib's latex
+            # rendered to render this properly.
+            s = s + '{' + printer._print(self.args[i], *args) + '}'
+            if isinstance(self.args[i], (Add, Mul)):
+                s = s + '\\right)'
+            if i != length - 1:
+                s = s + '\\otimes '
+        return s
+
+    def doit(self, **hints):
+        return TensorProduct(*[item.doit(**hints) for item in self.args])
+
+    def _eval_expand_tensorproduct(self, **hints):
+        """Distribute TensorProducts across addition."""
+        args = self.args
+        add_args = []
+        for i in range(len(args)):
+            if isinstance(args[i], Add):
+                for aa in args[i].args:
+                    tp = TensorProduct(*args[:i] + (aa,) + args[i + 1:])
+                    c_part, nc_part = tp.args_cnc()
+                    # Check for TensorProduct object: is the one object in nc_part, if any:
+                    # (Note: any other object type to be expanded must be added here)
+                    if len(nc_part) == 1 and isinstance(nc_part[0], TensorProduct):
+                        nc_part = (nc_part[0]._eval_expand_tensorproduct(), )
+                    add_args.append(Mul(*c_part)*Mul(*nc_part))
+                break
+
+        if add_args:
+            return Add(*add_args)
+        else:
+            return self
+
+    def _eval_trace(self, **kwargs):
+        indices = kwargs.get('indices', None)
+        exp = self
+
+        if indices is None or len(indices) == 0:
+            return Mul(*[Tr(arg).doit() for arg in exp.args])
+        else:
+            return Mul(*[Tr(value).doit() if idx in indices else value
+                         for idx, value in enumerate(exp.args)])
+
+
+def tensor_product_simp_Mul(e):
+    """Simplify a Mul with tensor products.
+
+    .. deprecated:: 1.14.
+        The transformations applied by this function are not done automatically
+        when tensor products are combined.
+
+    Originally, the main use of this function is to simplify a ``Mul`` of
+    ``TensorProduct``s to a ``TensorProduct`` of ``Muls``.
+    """
+    sympy_deprecation_warning(
+        """
+        tensor_product_simp_Mul has been deprecated. The transformations
+        performed by this function are now done automatically when
+        tensor products are multiplied.
+        """,
+        deprecated_since_version="1.14",
+        active_deprecations_target='deprecated-tensorproduct-simp'
+    )
+    return e
+
+def tensor_product_simp_Pow(e):
+    """Evaluates ``Pow`` expressions whose base is ``TensorProduct``
+
+    .. deprecated:: 1.14.
+        The transformations applied by this function are not done automatically
+        when tensor products are combined.
+    """
+    sympy_deprecation_warning(
+        """
+        tensor_product_simp_Pow has been deprecated. The transformations
+        performed by this function are now done automatically when
+        tensor products are exponentiated.
+        """,
+        deprecated_since_version="1.14",
+        active_deprecations_target='deprecated-tensorproduct-simp'
+    )
+    return e
+
+
+def tensor_product_simp(e, **hints):
+    """Try to simplify and combine tensor products.
+
+    .. deprecated:: 1.14.
+        The transformations applied by this function are not done automatically
+        when tensor products are combined.
+
+    Originally, this function tried to pull expressions inside of ``TensorProducts``.
+    It only worked for relatively simple cases where the products have
+    only scalars, raw ``TensorProducts``, not ``Add``, ``Pow``, ``Commutators``
+    of ``TensorProducts``.
+    """
+    sympy_deprecation_warning(
+        """
+        tensor_product_simp has been deprecated. The transformations
+        performed by this function are now done automatically when
+        tensor products are combined.
+        """,
+        deprecated_since_version="1.14",
+        active_deprecations_target='deprecated-tensorproduct-simp'
+    )
+    return e
+
+
+@TensorProduct._kind_dispatcher.register(_OperatorKind, _OperatorKind)
+def find_op_kind(e1, e2):
+    return OperatorKind
+
+
+@TensorProduct._kind_dispatcher.register(_KetKind, _KetKind)
+def find_ket_kind(e1, e2):
+    return KetKind
+
+
+@TensorProduct._kind_dispatcher.register(_BraKind, _BraKind)
+def find_bra_kind(e1, e2):
+    return BraKind
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_anticommutator.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_anticommutator.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e6b6cbc50651742fcbbbe6adce3f20dfadc2ec5
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_anticommutator.py
@@ -0,0 +1,56 @@
+from sympy.core.numbers import Integer
+from sympy.core.symbol import symbols
+
+from sympy.physics.quantum.dagger import Dagger
+from sympy.physics.quantum.anticommutator import AntiCommutator as AComm
+from sympy.physics.quantum.operator import Operator
+
+
+a, b, c = symbols('a,b,c')
+A, B, C, D = symbols('A,B,C,D', commutative=False)
+
+
+def test_anticommutator():
+    ac = AComm(A, B)
+    assert isinstance(ac, AComm)
+    assert ac.is_commutative is False
+    assert ac.subs(A, C) == AComm(C, B)
+
+
+def test_commutator_identities():
+    assert AComm(a*A, b*B) == a*b*AComm(A, B)
+    assert AComm(A, A) == 2*A**2
+    assert AComm(A, B) == AComm(B, A)
+    assert AComm(a, b) == 2*a*b
+    assert AComm(A, B).doit() == A*B + B*A
+
+
+def test_anticommutator_dagger():
+    assert Dagger(AComm(A, B)) == AComm(Dagger(A), Dagger(B))
+
+
+class Foo(Operator):
+
+    def _eval_anticommutator_Bar(self, bar):
+        return Integer(0)
+
+
+class Bar(Operator):
+    pass
+
+
+class Tam(Operator):
+
+    def _eval_anticommutator_Foo(self, foo):
+        return Integer(1)
+
+
+def test_eval_commutator():
+    F = Foo('F')
+    B = Bar('B')
+    T = Tam('T')
+    assert AComm(F, B).doit() == 0
+    assert AComm(B, F).doit() == 0
+    assert AComm(F, T).doit() == 1
+    assert AComm(T, F).doit() == 1
+    assert AComm(B, T).doit() == B*T + T*B
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_boson.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_boson.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd8dab745bede8b1c70303917dae81146fc03395
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_boson.py
@@ -0,0 +1,50 @@
+from math import prod
+
+from sympy.core.numbers import Rational
+from sympy.functions.elementary.exponential import exp
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.physics.quantum import Dagger, Commutator, qapply
+from sympy.physics.quantum.boson import BosonOp
+from sympy.physics.quantum.boson import (
+    BosonFockKet, BosonFockBra, BosonCoherentKet, BosonCoherentBra)
+
+
+def test_bosonoperator():
+    a = BosonOp('a')
+    b = BosonOp('b')
+
+    assert isinstance(a, BosonOp)
+    assert isinstance(Dagger(a), BosonOp)
+
+    assert a.is_annihilation
+    assert not Dagger(a).is_annihilation
+
+    assert BosonOp("a") == BosonOp("a", True)
+    assert BosonOp("a") != BosonOp("c")
+    assert BosonOp("a", True) != BosonOp("a", False)
+
+    assert Commutator(a, Dagger(a)).doit() == 1
+
+    assert Commutator(a, Dagger(b)).doit() == a * Dagger(b) - Dagger(b) * a
+
+    assert Dagger(exp(a)) == exp(Dagger(a))
+
+
+def test_boson_states():
+    a = BosonOp("a")
+
+    # Fock states
+    n = 3
+    assert (BosonFockBra(0) * BosonFockKet(1)).doit() == 0
+    assert (BosonFockBra(1) * BosonFockKet(1)).doit() == 1
+    assert qapply(BosonFockBra(n) * Dagger(a)**n * BosonFockKet(0)) \
+        == sqrt(prod(range(1, n+1)))
+
+    # Coherent states
+    alpha1, alpha2 = 1.2, 4.3
+    assert (BosonCoherentBra(alpha1) * BosonCoherentKet(alpha1)).doit() == 1
+    assert (BosonCoherentBra(alpha2) * BosonCoherentKet(alpha2)).doit() == 1
+    assert abs((BosonCoherentBra(alpha1) * BosonCoherentKet(alpha2)).doit() -
+               exp((alpha1 - alpha2) ** 2 * Rational(-1, 2))) < 1e-12
+    assert qapply(a * BosonCoherentKet(alpha1)) == \
+        alpha1 * BosonCoherentKet(alpha1)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_cartesian.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_cartesian.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1dd435fab68c9c71ac3602bc4c53847cbe39d57
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_cartesian.py
@@ -0,0 +1,113 @@
+"""Tests for cartesian.py"""
+
+from sympy.core.numbers import (I, pi)
+from sympy.core.singleton import S
+from sympy.core.symbol import symbols
+from sympy.functions.elementary.exponential import exp
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.special.delta_functions import DiracDelta
+from sympy.sets.sets import Interval
+from sympy.testing.pytest import XFAIL
+
+from sympy.physics.quantum import qapply, represent, L2, Dagger
+from sympy.physics.quantum import Commutator, hbar
+from sympy.physics.quantum.cartesian import (
+    XOp, YOp, ZOp, PxOp, X, Y, Z, Px, XKet, XBra, PxKet, PxBra,
+    PositionKet3D, PositionBra3D
+)
+from sympy.physics.quantum.operator import DifferentialOperator
+
+x, y, z, x_1, x_2, x_3, y_1, z_1 = symbols('x,y,z,x_1,x_2,x_3,y_1,z_1')
+px, py, px_1, px_2 = symbols('px py px_1 px_2')
+
+
+def test_x():
+    assert X.hilbert_space == L2(Interval(S.NegativeInfinity, S.Infinity))
+    assert Commutator(X, Px).doit() == I*hbar
+    assert qapply(X*XKet(x)) == x*XKet(x)
+    assert XKet(x).dual_class() == XBra
+    assert XBra(x).dual_class() == XKet
+    assert (Dagger(XKet(y))*XKet(x)).doit() == DiracDelta(x - y)
+    assert (PxBra(px)*XKet(x)).doit() == \
+        exp(-I*x*px/hbar)/sqrt(2*pi*hbar)
+    assert represent(XKet(x)) == DiracDelta(x - x_1)
+    assert represent(XBra(x)) == DiracDelta(-x + x_1)
+    assert XBra(x).position == x
+    assert represent(XOp()*XKet()) == x*DiracDelta(x - x_2)
+    assert represent(XBra("y")*XKet()) == DiracDelta(x - y)
+    assert represent(
+        XKet()*XBra()) == DiracDelta(x - x_2) * DiracDelta(x_1 - x)
+
+    rep_p = represent(XOp(), basis=PxOp)
+    assert rep_p == hbar*I*DiracDelta(px_1 - px_2)*DifferentialOperator(px_1)
+    assert rep_p == represent(XOp(), basis=PxOp())
+    assert rep_p == represent(XOp(), basis=PxKet)
+    assert rep_p == represent(XOp(), basis=PxKet())
+
+    assert represent(XOp()*PxKet(), basis=PxKet) == \
+        hbar*I*DiracDelta(px - px_2)*DifferentialOperator(px)
+
+
+@XFAIL
+def _text_x_broken():
+    # represent has some broken logic that is relying in particular
+    # forms of input, rather than a full and proper handling of
+    # all valid quantum expressions. Marking this test as XFAIL until
+    # we can refactor represent.
+    assert represent(XOp()*XKet()*XBra('y')) == \
+        x*DiracDelta(x - x_3)*DiracDelta(x_1 - y)
+
+
+def test_p():
+    assert Px.hilbert_space == L2(Interval(S.NegativeInfinity, S.Infinity))
+    assert qapply(Px*PxKet(px)) == px*PxKet(px)
+    assert PxKet(px).dual_class() == PxBra
+    assert PxBra(x).dual_class() == PxKet
+    assert (Dagger(PxKet(py))*PxKet(px)).doit() == DiracDelta(px - py)
+    assert (XBra(x)*PxKet(px)).doit() == \
+        exp(I*x*px/hbar)/sqrt(2*pi*hbar)
+    assert represent(PxKet(px)) == DiracDelta(px - px_1)
+
+    rep_x = represent(PxOp(), basis=XOp)
+    assert rep_x == -hbar*I*DiracDelta(x_1 - x_2)*DifferentialOperator(x_1)
+    assert rep_x == represent(PxOp(), basis=XOp())
+    assert rep_x == represent(PxOp(), basis=XKet)
+    assert rep_x == represent(PxOp(), basis=XKet())
+
+    assert represent(PxOp()*XKet(), basis=XKet) == \
+        -hbar*I*DiracDelta(x - x_2)*DifferentialOperator(x)
+    assert represent(XBra("y")*PxOp()*XKet(), basis=XKet) == \
+        -hbar*I*DiracDelta(x - y)*DifferentialOperator(x)
+
+
+def test_3dpos():
+    assert Y.hilbert_space == L2(Interval(S.NegativeInfinity, S.Infinity))
+    assert Z.hilbert_space == L2(Interval(S.NegativeInfinity, S.Infinity))
+
+    test_ket = PositionKet3D(x, y, z)
+    assert qapply(X*test_ket) == x*test_ket
+    assert qapply(Y*test_ket) == y*test_ket
+    assert qapply(Z*test_ket) == z*test_ket
+    assert qapply(X*Y*test_ket) == x*y*test_ket
+    assert qapply(X*Y*Z*test_ket) == x*y*z*test_ket
+    assert qapply(Y*Z*test_ket) == y*z*test_ket
+
+    assert PositionKet3D() == test_ket
+    assert YOp() == Y
+    assert ZOp() == Z
+
+    assert PositionKet3D.dual_class() == PositionBra3D
+    assert PositionBra3D.dual_class() == PositionKet3D
+
+    other_ket = PositionKet3D(x_1, y_1, z_1)
+    assert (Dagger(other_ket)*test_ket).doit() == \
+        DiracDelta(x - x_1)*DiracDelta(y - y_1)*DiracDelta(z - z_1)
+
+    assert test_ket.position_x == x
+    assert test_ket.position_y == y
+    assert test_ket.position_z == z
+    assert other_ket.position_x == x_1
+    assert other_ket.position_y == y_1
+    assert other_ket.position_z == z_1
+
+    # TODO: Add tests for representations
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_cg.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_cg.py
new file mode 100644
index 0000000000000000000000000000000000000000..384512aaac7a8d984ff2a733e6349161dc9414a0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_cg.py
@@ -0,0 +1,183 @@
+from sympy.concrete.summations import Sum
+from sympy.core.numbers import Rational
+from sympy.core.singleton import S
+from sympy.core.symbol import symbols
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.physics.quantum.cg import Wigner3j, Wigner6j, Wigner9j, CG, cg_simp
+from sympy.functions.special.tensor_functions import KroneckerDelta
+
+
+def test_cg_simp_add():
+    j, m1, m1p, m2, m2p = symbols('j m1 m1p m2 m2p')
+    # Test Varshalovich 8.7.1 Eq 1
+    a = CG(S.Half, S.Half, 0, 0, S.Half, S.Half)
+    b = CG(S.Half, Rational(-1, 2), 0, 0, S.Half, Rational(-1, 2))
+    c = CG(1, 1, 0, 0, 1, 1)
+    d = CG(1, 0, 0, 0, 1, 0)
+    e = CG(1, -1, 0, 0, 1, -1)
+    assert cg_simp(a + b) == 2
+    assert cg_simp(c + d + e) == 3
+    assert cg_simp(a + b + c + d + e) == 5
+    assert cg_simp(a + b + c) == 2 + c
+    assert cg_simp(2*a + b) == 2 + a
+    assert cg_simp(2*c + d + e) == 3 + c
+    assert cg_simp(5*a + 5*b) == 10
+    assert cg_simp(5*c + 5*d + 5*e) == 15
+    assert cg_simp(-a - b) == -2
+    assert cg_simp(-c - d - e) == -3
+    assert cg_simp(-6*a - 6*b) == -12
+    assert cg_simp(-4*c - 4*d - 4*e) == -12
+    a = CG(S.Half, S.Half, j, 0, S.Half, S.Half)
+    b = CG(S.Half, Rational(-1, 2), j, 0, S.Half, Rational(-1, 2))
+    c = CG(1, 1, j, 0, 1, 1)
+    d = CG(1, 0, j, 0, 1, 0)
+    e = CG(1, -1, j, 0, 1, -1)
+    assert cg_simp(a + b) == 2*KroneckerDelta(j, 0)
+    assert cg_simp(c + d + e) == 3*KroneckerDelta(j, 0)
+    assert cg_simp(a + b + c + d + e) == 5*KroneckerDelta(j, 0)
+    assert cg_simp(a + b + c) == 2*KroneckerDelta(j, 0) + c
+    assert cg_simp(2*a + b) == 2*KroneckerDelta(j, 0) + a
+    assert cg_simp(2*c + d + e) == 3*KroneckerDelta(j, 0) + c
+    assert cg_simp(5*a + 5*b) == 10*KroneckerDelta(j, 0)
+    assert cg_simp(5*c + 5*d + 5*e) == 15*KroneckerDelta(j, 0)
+    assert cg_simp(-a - b) == -2*KroneckerDelta(j, 0)
+    assert cg_simp(-c - d - e) == -3*KroneckerDelta(j, 0)
+    assert cg_simp(-6*a - 6*b) == -12*KroneckerDelta(j, 0)
+    assert cg_simp(-4*c - 4*d - 4*e) == -12*KroneckerDelta(j, 0)
+    # Test Varshalovich 8.7.1 Eq 2
+    a = CG(S.Half, S.Half, S.Half, Rational(-1, 2), 0, 0)
+    b = CG(S.Half, Rational(-1, 2), S.Half, S.Half, 0, 0)
+    c = CG(1, 1, 1, -1, 0, 0)
+    d = CG(1, 0, 1, 0, 0, 0)
+    e = CG(1, -1, 1, 1, 0, 0)
+    assert cg_simp(a - b) == sqrt(2)
+    assert cg_simp(c - d + e) == sqrt(3)
+    assert cg_simp(a - b + c - d + e) == sqrt(2) + sqrt(3)
+    assert cg_simp(a - b + c) == sqrt(2) + c
+    assert cg_simp(2*a - b) == sqrt(2) + a
+    assert cg_simp(2*c - d + e) == sqrt(3) + c
+    assert cg_simp(5*a - 5*b) == 5*sqrt(2)
+    assert cg_simp(5*c - 5*d + 5*e) == 5*sqrt(3)
+    assert cg_simp(-a + b) == -sqrt(2)
+    assert cg_simp(-c + d - e) == -sqrt(3)
+    assert cg_simp(-6*a + 6*b) == -6*sqrt(2)
+    assert cg_simp(-4*c + 4*d - 4*e) == -4*sqrt(3)
+    a = CG(S.Half, S.Half, S.Half, Rational(-1, 2), j, 0)
+    b = CG(S.Half, Rational(-1, 2), S.Half, S.Half, j, 0)
+    c = CG(1, 1, 1, -1, j, 0)
+    d = CG(1, 0, 1, 0, j, 0)
+    e = CG(1, -1, 1, 1, j, 0)
+    assert cg_simp(a - b) == sqrt(2)*KroneckerDelta(j, 0)
+    assert cg_simp(c - d + e) == sqrt(3)*KroneckerDelta(j, 0)
+    assert cg_simp(a - b + c - d + e) == sqrt(
+        2)*KroneckerDelta(j, 0) + sqrt(3)*KroneckerDelta(j, 0)
+    assert cg_simp(a - b + c) == sqrt(2)*KroneckerDelta(j, 0) + c
+    assert cg_simp(2*a - b) == sqrt(2)*KroneckerDelta(j, 0) + a
+    assert cg_simp(2*c - d + e) == sqrt(3)*KroneckerDelta(j, 0) + c
+    assert cg_simp(5*a - 5*b) == 5*sqrt(2)*KroneckerDelta(j, 0)
+    assert cg_simp(5*c - 5*d + 5*e) == 5*sqrt(3)*KroneckerDelta(j, 0)
+    assert cg_simp(-a + b) == -sqrt(2)*KroneckerDelta(j, 0)
+    assert cg_simp(-c + d - e) == -sqrt(3)*KroneckerDelta(j, 0)
+    assert cg_simp(-6*a + 6*b) == -6*sqrt(2)*KroneckerDelta(j, 0)
+    assert cg_simp(-4*c + 4*d - 4*e) == -4*sqrt(3)*KroneckerDelta(j, 0)
+    # Test Varshalovich 8.7.2 Eq 9
+    # alpha=alphap,beta=betap case
+    # numerical
+    a = CG(S.Half, S.Half, S.Half, Rational(-1, 2), 1, 0)**2
+    b = CG(S.Half, S.Half, S.Half, Rational(-1, 2), 0, 0)**2
+    c = CG(1, 0, 1, 1, 1, 1)**2
+    d = CG(1, 0, 1, 1, 2, 1)**2
+    assert cg_simp(a + b) == 1
+    assert cg_simp(c + d) == 1
+    assert cg_simp(a + b + c + d) == 2
+    assert cg_simp(4*a + 4*b) == 4
+    assert cg_simp(4*c + 4*d) == 4
+    assert cg_simp(5*a + 3*b) == 3 + 2*a
+    assert cg_simp(5*c + 3*d) == 3 + 2*c
+    assert cg_simp(-a - b) == -1
+    assert cg_simp(-c - d) == -1
+    # symbolic
+    a = CG(S.Half, m1, S.Half, m2, 1, 1)**2
+    b = CG(S.Half, m1, S.Half, m2, 1, 0)**2
+    c = CG(S.Half, m1, S.Half, m2, 1, -1)**2
+    d = CG(S.Half, m1, S.Half, m2, 0, 0)**2
+    assert cg_simp(a + b + c + d) == 1
+    assert cg_simp(4*a + 4*b + 4*c + 4*d) == 4
+    assert cg_simp(3*a + 5*b + 3*c + 4*d) == 3 + 2*b + d
+    assert cg_simp(-a - b - c - d) == -1
+    a = CG(1, m1, 1, m2, 2, 2)**2
+    b = CG(1, m1, 1, m2, 2, 1)**2
+    c = CG(1, m1, 1, m2, 2, 0)**2
+    d = CG(1, m1, 1, m2, 2, -1)**2
+    e = CG(1, m1, 1, m2, 2, -2)**2
+    f = CG(1, m1, 1, m2, 1, 1)**2
+    g = CG(1, m1, 1, m2, 1, 0)**2
+    h = CG(1, m1, 1, m2, 1, -1)**2
+    i = CG(1, m1, 1, m2, 0, 0)**2
+    assert cg_simp(a + b + c + d + e + f + g + h + i) == 1
+    assert cg_simp(4*(a + b + c + d + e + f + g + h + i)) == 4
+    assert cg_simp(a + b + 2*c + d + 4*e + f + g + h + i) == 1 + c + 3*e
+    assert cg_simp(-a - b - c - d - e - f - g - h - i) == -1
+    # alpha!=alphap or beta!=betap case
+    # numerical
+    a = CG(S.Half, S(
+        1)/2, S.Half, Rational(-1, 2), 1, 0)*CG(S.Half, Rational(-1, 2), S.Half, S.Half, 1, 0)
+    b = CG(S.Half, S(
+        1)/2, S.Half, Rational(-1, 2), 0, 0)*CG(S.Half, Rational(-1, 2), S.Half, S.Half, 0, 0)
+    c = CG(1, 1, 1, 0, 2, 1)*CG(1, 0, 1, 1, 2, 1)
+    d = CG(1, 1, 1, 0, 1, 1)*CG(1, 0, 1, 1, 1, 1)
+    assert cg_simp(a + b) == 0
+    assert cg_simp(c + d) == 0
+    # symbolic
+    a = CG(S.Half, m1, S.Half, m2, 1, 1)*CG(S.Half, m1p, S.Half, m2p, 1, 1)
+    b = CG(S.Half, m1, S.Half, m2, 1, 0)*CG(S.Half, m1p, S.Half, m2p, 1, 0)
+    c = CG(S.Half, m1, S.Half, m2, 1, -1)*CG(S.Half, m1p, S.Half, m2p, 1, -1)
+    d = CG(S.Half, m1, S.Half, m2, 0, 0)*CG(S.Half, m1p, S.Half, m2p, 0, 0)
+    assert cg_simp(a + b + c + d) == KroneckerDelta(m1, m1p)*KroneckerDelta(m2, m2p)
+    a = CG(1, m1, 1, m2, 2, 2)*CG(1, m1p, 1, m2p, 2, 2)
+    b = CG(1, m1, 1, m2, 2, 1)*CG(1, m1p, 1, m2p, 2, 1)
+    c = CG(1, m1, 1, m2, 2, 0)*CG(1, m1p, 1, m2p, 2, 0)
+    d = CG(1, m1, 1, m2, 2, -1)*CG(1, m1p, 1, m2p, 2, -1)
+    e = CG(1, m1, 1, m2, 2, -2)*CG(1, m1p, 1, m2p, 2, -2)
+    f = CG(1, m1, 1, m2, 1, 1)*CG(1, m1p, 1, m2p, 1, 1)
+    g = CG(1, m1, 1, m2, 1, 0)*CG(1, m1p, 1, m2p, 1, 0)
+    h = CG(1, m1, 1, m2, 1, -1)*CG(1, m1p, 1, m2p, 1, -1)
+    i = CG(1, m1, 1, m2, 0, 0)*CG(1, m1p, 1, m2p, 0, 0)
+    assert cg_simp(
+        a + b + c + d + e + f + g + h + i) == KroneckerDelta(m1, m1p)*KroneckerDelta(m2, m2p)
+
+
+def test_cg_simp_sum():
+    x, a, b, c, cp, alpha, beta, gamma, gammap = symbols(
+        'x a b c cp alpha beta gamma gammap')
+    # Varshalovich 8.7.1 Eq 1
+    assert cg_simp(x * Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a)
+                   )) == x*(2*a + 1)*KroneckerDelta(b, 0)
+    assert cg_simp(x * Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a)) + CG(1, 0, 1, 0, 1, 0)) == x*(2*a + 1)*KroneckerDelta(b, 0) + CG(1, 0, 1, 0, 1, 0)
+    assert cg_simp(2 * Sum(CG(1, alpha, 0, 0, 1, alpha), (alpha, -1, 1))) == 6
+    # Varshalovich 8.7.1 Eq 2
+    assert cg_simp(x*Sum((-1)**(a - alpha) * CG(a, alpha, a, -alpha, c,
+                   0), (alpha, -a, a))) == x*sqrt(2*a + 1)*KroneckerDelta(c, 0)
+    assert cg_simp(3*Sum((-1)**(2 - alpha) * CG(
+        2, alpha, 2, -alpha, 0, 0), (alpha, -2, 2))) == 3*sqrt(5)
+    # Varshalovich 8.7.2 Eq 4
+    assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, cp, gammap), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(c, cp)*KroneckerDelta(gamma, gammap)
+    assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, c, gammap), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(gamma, gammap)
+    assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, cp, gamma), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(c, cp)
+    assert cg_simp(Sum(CG(
+        a, alpha, b, beta, c, gamma)**2, (alpha, -a, a), (beta, -b, b))) == 1
+    assert cg_simp(Sum(CG(2, alpha, 1, beta, 2, gamma)*CG(2, alpha, 1, beta, 2, gammap), (alpha, -2, 2), (beta, -1, 1))) == KroneckerDelta(gamma, gammap)
+
+
+def test_doit():
+    assert Wigner3j(S.Half, Rational(-1, 2), S.Half, S.Half, 0, 0).doit() == -sqrt(2)/2
+    assert Wigner3j(1/2,1/2,1/2,1/2,1/2,1/2).doit() == 0
+    assert Wigner3j(9/2,9/2,9/2,9/2,9/2,9/2).doit() ==  0
+    assert Wigner6j(1, 2, 3, 2, 1, 2).doit() == sqrt(21)/105
+    assert Wigner6j(3, 1, 2, 2, 2, 1).doit() == sqrt(21) / 105
+    assert Wigner9j(
+        2, 1, 1, Rational(3, 2), S.Half, 1, S.Half, S.Half, 0).doit() == sqrt(2)/12
+    assert CG(S.Half, S.Half, S.Half, Rational(-1, 2), 1, 0).doit() == sqrt(2)/2
+    # J minus M is not integer
+    assert Wigner3j(1, -1, S.Half, S.Half, 1, S.Half).doit() == 0
+    assert CG(4, -1, S.Half, S.Half, 4, Rational(-1, 2)).doit() == 0
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_circuitplot.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_circuitplot.py
new file mode 100644
index 0000000000000000000000000000000000000000..fcc89f77047450ad3f8663f371f483654dc70ea9
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_circuitplot.py
@@ -0,0 +1,69 @@
+from sympy.physics.quantum.circuitplot import labeller, render_label, Mz, CreateOneQubitGate,\
+     CreateCGate
+from sympy.physics.quantum.gate import CNOT, H, SWAP, CGate, S, T
+from sympy.external import import_module
+from sympy.testing.pytest import skip
+
+mpl = import_module('matplotlib')
+
+def test_render_label():
+    assert render_label('q0') == r'$\left|q0\right\rangle$'
+    assert render_label('q0', {'q0': '0'}) == r'$\left|q0\right\rangle=\left|0\right\rangle$'
+
+def test_Mz():
+    assert str(Mz(0)) == 'Mz(0)'
+
+def test_create1():
+    Qgate = CreateOneQubitGate('Q')
+    assert str(Qgate(0)) == 'Q(0)'
+
+def test_createc():
+    Qgate = CreateCGate('Q')
+    assert str(Qgate([1],0)) == 'C((1),Q(0))'
+
+def test_labeller():
+    """Test the labeller utility"""
+    assert labeller(2) == ['q_1', 'q_0']
+    assert labeller(3,'j') == ['j_2', 'j_1', 'j_0']
+
+def test_cnot():
+    """Test a simple cnot circuit. Right now this only makes sure the code doesn't
+    raise an exception, and some simple properties
+    """
+    if not mpl:
+        skip("matplotlib not installed")
+    else:
+        from sympy.physics.quantum.circuitplot import CircuitPlot
+
+    c = CircuitPlot(CNOT(1,0),2,labels=labeller(2))
+    assert c.ngates == 2
+    assert c.nqubits == 2
+    assert c.labels == ['q_1', 'q_0']
+
+    c = CircuitPlot(CNOT(1,0),2)
+    assert c.ngates == 2
+    assert c.nqubits == 2
+    assert c.labels == []
+
+def test_ex1():
+    if not mpl:
+        skip("matplotlib not installed")
+    else:
+        from sympy.physics.quantum.circuitplot import CircuitPlot
+
+    c = CircuitPlot(CNOT(1,0)*H(1),2,labels=labeller(2))
+    assert c.ngates == 2
+    assert c.nqubits == 2
+    assert c.labels == ['q_1', 'q_0']
+
+def test_ex4():
+    if not mpl:
+        skip("matplotlib not installed")
+    else:
+        from sympy.physics.quantum.circuitplot import CircuitPlot
+
+    c = CircuitPlot(SWAP(0,2)*H(0)* CGate((0,),S(1)) *H(1)*CGate((0,),T(2))\
+                    *CGate((1,),S(2))*H(2),3,labels=labeller(3,'j'))
+    assert c.ngates == 7
+    assert c.nqubits == 3
+    assert c.labels == ['j_2', 'j_1', 'j_0']
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_circuitutils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_circuitutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ea7232320417db8bf745871cff0e77aaf1901e7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_circuitutils.py
@@ -0,0 +1,402 @@
+from sympy.core.mul import Mul
+from sympy.core.numbers import Integer
+from sympy.core.symbol import Symbol
+from sympy.utilities import numbered_symbols
+from sympy.physics.quantum.gate import X, Y, Z, H, CNOT, CGate
+from sympy.physics.quantum.identitysearch import bfs_identity_search
+from sympy.physics.quantum.circuitutils import (kmp_table, find_subcircuit,
+        replace_subcircuit, convert_to_symbolic_indices,
+        convert_to_real_indices, random_reduce, random_insert,
+        flatten_ids)
+from sympy.testing.pytest import slow
+
+
+def create_gate_sequence(qubit=0):
+    gates = (X(qubit), Y(qubit), Z(qubit), H(qubit))
+    return gates
+
+
+def test_kmp_table():
+    word = ('a', 'b', 'c', 'd', 'a', 'b', 'd')
+    expected_table = [-1, 0, 0, 0, 0, 1, 2]
+    assert expected_table == kmp_table(word)
+
+    word = ('P', 'A', 'R', 'T', 'I', 'C', 'I', 'P', 'A', 'T', 'E', ' ',
+            'I', 'N', ' ', 'P', 'A', 'R', 'A', 'C', 'H', 'U', 'T', 'E')
+    expected_table = [-1, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0,
+                      0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0, 0]
+    assert expected_table == kmp_table(word)
+
+    x = X(0)
+    y = Y(0)
+    z = Z(0)
+    h = H(0)
+    word = (x, y, y, x, z)
+    expected_table = [-1, 0, 0, 0, 1]
+    assert expected_table == kmp_table(word)
+
+    word = (x, x, y, h, z)
+    expected_table = [-1, 0, 1, 0, 0]
+    assert expected_table == kmp_table(word)
+
+
+def test_find_subcircuit():
+    x = X(0)
+    y = Y(0)
+    z = Z(0)
+    h = H(0)
+    x1 = X(1)
+    y1 = Y(1)
+
+    i0 = Symbol('i0')
+    x_i0 = X(i0)
+    y_i0 = Y(i0)
+    z_i0 = Z(i0)
+    h_i0 = H(i0)
+
+    circuit = (x, y, z)
+
+    assert find_subcircuit(circuit, (x,)) == 0
+    assert find_subcircuit(circuit, (x1,)) == -1
+    assert find_subcircuit(circuit, (y,)) == 1
+    assert find_subcircuit(circuit, (h,)) == -1
+    assert find_subcircuit(circuit, Mul(x, h)) == -1
+    assert find_subcircuit(circuit, Mul(x, y, z)) == 0
+    assert find_subcircuit(circuit, Mul(y, z)) == 1
+    assert find_subcircuit(Mul(*circuit), (x, y, z, h)) == -1
+    assert find_subcircuit(Mul(*circuit), (z, y, x)) == -1
+    assert find_subcircuit(circuit, (x,), start=2, end=1) == -1
+
+    circuit = (x, y, x, y, z)
+    assert find_subcircuit(Mul(*circuit), Mul(x, y, z)) == 2
+    assert find_subcircuit(circuit, (x,), start=1) == 2
+    assert find_subcircuit(circuit, (x, y), start=1, end=2) == -1
+    assert find_subcircuit(Mul(*circuit), (x, y), start=1, end=3) == -1
+    assert find_subcircuit(circuit, (x, y), start=1, end=4) == 2
+    assert find_subcircuit(circuit, (x, y), start=2, end=4) == 2
+
+    circuit = (x, y, z, x1, x, y, z, h, x, y, x1,
+               x, y, z, h, y1, h)
+    assert find_subcircuit(circuit, (x, y, z, h, y1)) == 11
+
+    circuit = (x, y, x_i0, y_i0, z_i0, z)
+    assert find_subcircuit(circuit, (x_i0, y_i0, z_i0)) == 2
+
+    circuit = (x_i0, y_i0, z_i0, x_i0, y_i0, h_i0)
+    subcircuit = (x_i0, y_i0, z_i0)
+    result = find_subcircuit(circuit, subcircuit)
+    assert result == 0
+
+
+def test_replace_subcircuit():
+    x = X(0)
+    y = Y(0)
+    z = Z(0)
+    h = H(0)
+    cnot = CNOT(1, 0)
+    cgate_z = CGate((0,), Z(1))
+
+    # Standard cases
+    circuit = (z, y, x, x)
+    remove = (z, y, x)
+    assert replace_subcircuit(circuit, Mul(*remove)) == (x,)
+    assert replace_subcircuit(circuit, remove + (x,)) == ()
+    assert replace_subcircuit(circuit, remove, pos=1) == circuit
+    assert replace_subcircuit(circuit, remove, pos=0) == (x,)
+    assert replace_subcircuit(circuit, (x, x), pos=2) == (z, y)
+    assert replace_subcircuit(circuit, (h,)) == circuit
+
+    circuit = (x, y, x, y, z)
+    remove = (x, y, z)
+    assert replace_subcircuit(Mul(*circuit), Mul(*remove)) == (x, y)
+    remove = (x, y, x, y)
+    assert replace_subcircuit(circuit, remove) == (z,)
+
+    circuit = (x, h, cgate_z, h, cnot)
+    remove = (x, h, cgate_z)
+    assert replace_subcircuit(circuit, Mul(*remove), pos=-1) == (h, cnot)
+    assert replace_subcircuit(circuit, remove, pos=1) == circuit
+    remove = (h, h)
+    assert replace_subcircuit(circuit, remove) == circuit
+    remove = (h, cgate_z, h, cnot)
+    assert replace_subcircuit(circuit, remove) == (x,)
+
+    replace = (h, x)
+    actual = replace_subcircuit(circuit, remove,
+                     replace=replace)
+    assert actual == (x, h, x)
+
+    circuit = (x, y, h, x, y, z)
+    remove = (x, y)
+    replace = (cnot, cgate_z)
+    actual = replace_subcircuit(circuit, remove,
+                     replace=Mul(*replace))
+    assert actual == (cnot, cgate_z, h, x, y, z)
+
+    actual = replace_subcircuit(circuit, remove,
+                     replace=replace, pos=1)
+    assert actual == (x, y, h, cnot, cgate_z, z)
+
+
+def test_convert_to_symbolic_indices():
+    (x, y, z, h) = create_gate_sequence()
+
+    i0 = Symbol('i0')
+    exp_map = {i0: Integer(0)}
+    actual, act_map, sndx, gen = convert_to_symbolic_indices((x,))
+    assert actual == (X(i0),)
+    assert act_map == exp_map
+
+    expected = (X(i0), Y(i0), Z(i0), H(i0))
+    exp_map = {i0: Integer(0)}
+    actual, act_map, sndx, gen = convert_to_symbolic_indices((x, y, z, h))
+    assert actual == expected
+    assert exp_map == act_map
+
+    (x1, y1, z1, h1) = create_gate_sequence(1)
+    i1 = Symbol('i1')
+
+    expected = (X(i0), Y(i0), Z(i0), H(i0))
+    exp_map = {i0: Integer(1)}
+    actual, act_map, sndx, gen = convert_to_symbolic_indices((x1, y1, z1, h1))
+    assert actual == expected
+    assert act_map == exp_map
+
+    expected = (X(i0), Y(i0), Z(i0), H(i0), X(i1), Y(i1), Z(i1), H(i1))
+    exp_map = {i0: Integer(0), i1: Integer(1)}
+    actual, act_map, sndx, gen = convert_to_symbolic_indices((x, y, z, h,
+                                         x1, y1, z1, h1))
+    assert actual == expected
+    assert act_map == exp_map
+
+    exp_map = {i0: Integer(1), i1: Integer(0)}
+    actual, act_map, sndx, gen = convert_to_symbolic_indices(Mul(x1, y1,
+                                         z1, h1, x, y, z, h))
+    assert actual == expected
+    assert act_map == exp_map
+
+    expected = (X(i0), X(i1), Y(i0), Y(i1), Z(i0), Z(i1), H(i0), H(i1))
+    exp_map = {i0: Integer(0), i1: Integer(1)}
+    actual, act_map, sndx, gen = convert_to_symbolic_indices(Mul(x, x1,
+                                         y, y1, z, z1, h, h1))
+    assert actual == expected
+    assert act_map == exp_map
+
+    exp_map = {i0: Integer(1), i1: Integer(0)}
+    actual, act_map, sndx, gen = convert_to_symbolic_indices((x1, x, y1, y,
+                                         z1, z, h1, h))
+    assert actual == expected
+    assert act_map == exp_map
+
+    cnot_10 = CNOT(1, 0)
+    cnot_01 = CNOT(0, 1)
+    cgate_z_10 = CGate(1, Z(0))
+    cgate_z_01 = CGate(0, Z(1))
+
+    expected = (X(i0), X(i1), Y(i0), Y(i1), Z(i0), Z(i1),
+                H(i0), H(i1), CNOT(i1, i0), CNOT(i0, i1),
+                CGate(i1, Z(i0)), CGate(i0, Z(i1)))
+    exp_map = {i0: Integer(0), i1: Integer(1)}
+    args = (x, x1, y, y1, z, z1, h, h1, cnot_10, cnot_01,
+            cgate_z_10, cgate_z_01)
+    actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
+    assert actual == expected
+    assert act_map == exp_map
+
+    args = (x1, x, y1, y, z1, z, h1, h, cnot_10, cnot_01,
+            cgate_z_10, cgate_z_01)
+    expected = (X(i0), X(i1), Y(i0), Y(i1), Z(i0), Z(i1),
+                H(i0), H(i1), CNOT(i0, i1), CNOT(i1, i0),
+                CGate(i0, Z(i1)), CGate(i1, Z(i0)))
+    exp_map = {i0: Integer(1), i1: Integer(0)}
+    actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
+    assert actual == expected
+    assert act_map == exp_map
+
+    args = (cnot_10, h, cgate_z_01, h)
+    expected = (CNOT(i0, i1), H(i1), CGate(i1, Z(i0)), H(i1))
+    exp_map = {i0: Integer(1), i1: Integer(0)}
+    actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
+    assert actual == expected
+    assert act_map == exp_map
+
+    args = (cnot_01, h1, cgate_z_10, h1)
+    exp_map = {i0: Integer(0), i1: Integer(1)}
+    actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
+    assert actual == expected
+    assert act_map == exp_map
+
+    args = (cnot_10, h1, cgate_z_01, h1)
+    expected = (CNOT(i0, i1), H(i0), CGate(i1, Z(i0)), H(i0))
+    exp_map = {i0: Integer(1), i1: Integer(0)}
+    actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
+    assert actual == expected
+    assert act_map == exp_map
+
+    i2 = Symbol('i2')
+    ccgate_z = CGate(0, CGate(1, Z(2)))
+    ccgate_x = CGate(1, CGate(2, X(0)))
+    args = (ccgate_z, ccgate_x)
+
+    expected = (CGate(i0, CGate(i1, Z(i2))), CGate(i1, CGate(i2, X(i0))))
+    exp_map = {i0: Integer(0), i1: Integer(1), i2: Integer(2)}
+    actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
+    assert actual == expected
+    assert act_map == exp_map
+
+    ndx_map = {i0: Integer(0)}
+    index_gen = numbered_symbols(prefix='i', start=1)
+    actual, act_map, sndx, gen = convert_to_symbolic_indices(args,
+                                         qubit_map=ndx_map,
+                                         start=i0,
+                                         gen=index_gen)
+    assert actual == expected
+    assert act_map == exp_map
+
+    i3 = Symbol('i3')
+    cgate_x0_c321 = CGate((3, 2, 1), X(0))
+    exp_map = {i0: Integer(3), i1: Integer(2),
+               i2: Integer(1), i3: Integer(0)}
+    expected = (CGate((i0, i1, i2), X(i3)),)
+    args = (cgate_x0_c321,)
+    actual, act_map, sndx, gen = convert_to_symbolic_indices(args)
+    assert actual == expected
+    assert act_map == exp_map
+
+
+def test_convert_to_real_indices():
+    i0 = Symbol('i0')
+    i1 = Symbol('i1')
+
+    (x, y, z, h) = create_gate_sequence()
+
+    x_i0 = X(i0)
+    y_i0 = Y(i0)
+    z_i0 = Z(i0)
+
+    qubit_map = {i0: 0}
+    args = (z_i0, y_i0, x_i0)
+    expected = (z, y, x)
+    actual = convert_to_real_indices(args, qubit_map)
+    assert actual == expected
+
+    cnot_10 = CNOT(1, 0)
+    cnot_01 = CNOT(0, 1)
+    cgate_z_10 = CGate(1, Z(0))
+    cgate_z_01 = CGate(0, Z(1))
+
+    cnot_i1_i0 = CNOT(i1, i0)
+    cnot_i0_i1 = CNOT(i0, i1)
+    cgate_z_i1_i0 = CGate(i1, Z(i0))
+
+    qubit_map = {i0: 0, i1: 1}
+    args = (cnot_i1_i0,)
+    expected = (cnot_10,)
+    actual = convert_to_real_indices(args, qubit_map)
+    assert actual == expected
+
+    args = (cgate_z_i1_i0,)
+    expected = (cgate_z_10,)
+    actual = convert_to_real_indices(args, qubit_map)
+    assert actual == expected
+
+    args = (cnot_i0_i1,)
+    expected = (cnot_01,)
+    actual = convert_to_real_indices(args, qubit_map)
+    assert actual == expected
+
+    qubit_map = {i0: 1, i1: 0}
+    args = (cgate_z_i1_i0,)
+    expected = (cgate_z_01,)
+    actual = convert_to_real_indices(args, qubit_map)
+    assert actual == expected
+
+    i2 = Symbol('i2')
+    ccgate_z = CGate(i0, CGate(i1, Z(i2)))
+    ccgate_x = CGate(i1, CGate(i2, X(i0)))
+
+    qubit_map = {i0: 0, i1: 1, i2: 2}
+    args = (ccgate_z, ccgate_x)
+    expected = (CGate(0, CGate(1, Z(2))), CGate(1, CGate(2, X(0))))
+    actual = convert_to_real_indices(Mul(*args), qubit_map)
+    assert actual == expected
+
+    qubit_map = {i0: 1, i2: 0, i1: 2}
+    args = (ccgate_x, ccgate_z)
+    expected = (CGate(2, CGate(0, X(1))), CGate(1, CGate(2, Z(0))))
+    actual = convert_to_real_indices(args, qubit_map)
+    assert actual == expected
+
+
+@slow
+def test_random_reduce():
+    x = X(0)
+    y = Y(0)
+    z = Z(0)
+    h = H(0)
+    cnot = CNOT(1, 0)
+    cgate_z = CGate((0,), Z(1))
+
+    gate_list = [x, y, z]
+    ids = list(bfs_identity_search(gate_list, 1, max_depth=4))
+
+    circuit = (x, y, h, z, cnot)
+    assert random_reduce(circuit, []) == circuit
+    assert random_reduce(circuit, ids) == circuit
+
+    seq = [2, 11, 9, 3, 5]
+    circuit = (x, y, z, x, y, h)
+    assert random_reduce(circuit, ids, seed=seq) == (x, y, h)
+
+    circuit = (x, x, y, y, z, z)
+    assert random_reduce(circuit, ids, seed=seq) == (x, x, y, y)
+
+    seq = [14, 13, 0]
+    assert random_reduce(circuit, ids, seed=seq) == (y, y, z, z)
+
+    gate_list = [x, y, z, h, cnot, cgate_z]
+    ids = list(bfs_identity_search(gate_list, 2, max_depth=4))
+
+    seq = [25]
+    circuit = (x, y, z, y, h, y, h, cgate_z, h, cnot)
+    expected = (x, y, z, cgate_z, h, cnot)
+    assert random_reduce(circuit, ids, seed=seq) == expected
+    circuit = Mul(*circuit)
+    assert random_reduce(circuit, ids, seed=seq) == expected
+
+
+@slow
+def test_random_insert():
+    x = X(0)
+    y = Y(0)
+    z = Z(0)
+    h = H(0)
+    cnot = CNOT(1, 0)
+    cgate_z = CGate((0,), Z(1))
+
+    choices = [(x, x)]
+    circuit = (y, y)
+    loc, choice = 0, 0
+    actual = random_insert(circuit, choices, seed=[loc, choice])
+    assert actual == (x, x, y, y)
+
+    circuit = (x, y, z, h)
+    choices = [(h, h), (x, y, z)]
+    expected = (x, x, y, z, y, z, h)
+    loc, choice = 1, 1
+    actual = random_insert(circuit, choices, seed=[loc, choice])
+    assert actual == expected
+
+    gate_list = [x, y, z, h, cnot, cgate_z]
+    ids = list(bfs_identity_search(gate_list, 2, max_depth=4))
+
+    eq_ids = flatten_ids(ids)
+
+    circuit = (x, y, h, cnot, cgate_z)
+    expected = (x, z, x, z, x, y, h, cnot, cgate_z)
+    loc, choice = 1, 30
+    actual = random_insert(circuit, eq_ids, seed=[loc, choice])
+    assert actual == expected
+    circuit = Mul(*circuit)
+    actual = random_insert(circuit, eq_ids, seed=[loc, choice])
+    assert actual == expected
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_commutator.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_commutator.py
new file mode 100644
index 0000000000000000000000000000000000000000..04f45feddaca63d7306363a9235c63f534d11430
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_commutator.py
@@ -0,0 +1,81 @@
+from sympy.core.numbers import Integer
+from sympy.core.symbol import symbols
+
+from sympy.physics.quantum.dagger import Dagger
+from sympy.physics.quantum.commutator import Commutator as Comm
+from sympy.physics.quantum.operator import Operator
+
+
+a, b, c = symbols('a,b,c')
+n = symbols('n', integer=True)
+A, B, C, D = symbols('A,B,C,D', commutative=False)
+
+
+def test_commutator():
+    c = Comm(A, B)
+    assert c.is_commutative is False
+    assert isinstance(c, Comm)
+    assert c.subs(A, C) == Comm(C, B)
+
+
+def test_commutator_identities():
+    assert Comm(a*A, b*B) == a*b*Comm(A, B)
+    assert Comm(A, A) == 0
+    assert Comm(a, b) == 0
+    assert Comm(A, B) == -Comm(B, A)
+    assert Comm(A, B).doit() == A*B - B*A
+    assert Comm(A, B*C).expand(commutator=True) == Comm(A, B)*C + B*Comm(A, C)
+    assert Comm(A*B, C*D).expand(commutator=True) == \
+        A*C*Comm(B, D) + A*Comm(B, C)*D + C*Comm(A, D)*B + Comm(A, C)*D*B
+    assert Comm(A, B**2).expand(commutator=True) == Comm(A, B)*B + B*Comm(A, B)
+    assert Comm(A**2, C**2).expand(commutator=True) == \
+        Comm(A*B, C*D).expand(commutator=True).replace(B, A).replace(D, C) == \
+        A*C*Comm(A, C) + A*Comm(A, C)*C + C*Comm(A, C)*A + Comm(A, C)*C*A
+    assert Comm(A, C**-2).expand(commutator=True) == \
+        Comm(A, (1/C)*(1/D)).expand(commutator=True).replace(D, C)
+    assert Comm(A + B, C + D).expand(commutator=True) == \
+        Comm(A, C) + Comm(A, D) + Comm(B, C) + Comm(B, D)
+    assert Comm(A, B + C).expand(commutator=True) == Comm(A, B) + Comm(A, C)
+    assert Comm(A**n, B).expand(commutator=True) == Comm(A**n, B)
+
+    e = Comm(A, Comm(B, C)) + Comm(B, Comm(C, A)) + Comm(C, Comm(A, B))
+    assert e.doit().expand() == 0
+
+
+def test_commutator_dagger():
+    comm = Comm(A*B, C)
+    assert Dagger(comm).expand(commutator=True) == \
+        - Comm(Dagger(B), Dagger(C))*Dagger(A) - \
+        Dagger(B)*Comm(Dagger(A), Dagger(C))
+
+
+class Foo(Operator):
+
+    def _eval_commutator_Bar(self, bar):
+        return Integer(0)
+
+
+class Bar(Operator):
+    pass
+
+
+class Tam(Operator):
+
+    def _eval_commutator_Foo(self, foo):
+        return Integer(1)
+
+
+def test_eval_commutator():
+    F = Foo('F')
+    B = Bar('B')
+    T = Tam('T')
+    assert Comm(F, B).doit() == 0
+    assert Comm(B, F).doit() == 0
+    assert Comm(F, T).doit() == -1
+    assert Comm(T, F).doit() == 1
+    assert Comm(B, T).doit() == B*T - T*B
+    assert Comm(F**2, B).expand(commutator=True).doit() == 0
+    assert Comm(F**2, T).expand(commutator=True).doit() == -2*F
+    assert Comm(F, T**2).expand(commutator=True).doit() == -2*T
+    assert Comm(T**2, F).expand(commutator=True).doit() == 2*T
+    assert Comm(T**2, F**3).expand(commutator=True).doit() == 2*F*T*F + 2*F**2*T + 2*T*F**2
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_constants.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..48a773ea6b5afbaf956143b50b16b3b18aaf5beb
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_constants.py
@@ -0,0 +1,13 @@
+from sympy.core.numbers import Float
+
+from sympy.physics.quantum.constants import hbar
+
+
+def test_hbar():
+    assert hbar.is_commutative is True
+    assert hbar.is_real is True
+    assert hbar.is_positive is True
+    assert hbar.is_negative is False
+    assert hbar.is_irrational is True
+
+    assert hbar.evalf() == Float(1.05457162e-34)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_dagger.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_dagger.py
new file mode 100644
index 0000000000000000000000000000000000000000..1357c9320a20afa2ba905a117d90ed1ac2e9642c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_dagger.py
@@ -0,0 +1,103 @@
+from sympy.core.expr import Expr
+from sympy.core.mul import Mul
+from sympy.core.numbers import (I, Integer)
+from sympy.core.symbol import symbols
+from sympy.functions.elementary.complexes import conjugate
+from sympy.matrices.dense import Matrix
+
+from sympy.physics.quantum.dagger import adjoint, Dagger
+from sympy.external import import_module
+from sympy.testing.pytest import skip, warns_deprecated_sympy
+from sympy.physics.quantum.operator import Operator, IdentityOperator
+
+
+def test_scalars():
+    x = symbols('x', complex=True)
+    assert Dagger(x) == conjugate(x)
+    assert Dagger(I*x) == -I*conjugate(x)
+
+    i = symbols('i', real=True)
+    assert Dagger(i) == i
+
+    p = symbols('p')
+    assert isinstance(Dagger(p), conjugate)
+
+    i = Integer(3)
+    assert Dagger(i) == i
+
+    A = symbols('A', commutative=False)
+    assert Dagger(A).is_commutative is False
+
+
+def test_matrix():
+    x = symbols('x')
+    m = Matrix([[I, x*I], [2, 4]])
+    assert Dagger(m) == m.H
+
+
+def test_dagger_mul():
+    O = Operator('O')
+    assert Dagger(O)*O == Dagger(O)*O
+    with warns_deprecated_sympy():
+        I = IdentityOperator()
+        assert Dagger(O)*O*I == Mul(Dagger(O), O)*I
+    assert Dagger(O)*Dagger(O) == Dagger(O)**2
+    assert Dagger(O)*Dagger(I) == Dagger(O)
+
+
+class Foo(Expr):
+
+    def _eval_adjoint(self):
+        return I
+
+
+def test_eval_adjoint():
+    f = Foo()
+    d = Dagger(f)
+    assert d == I
+
+np = import_module('numpy')
+
+
+def test_numpy_dagger():
+    if not np:
+        skip("numpy not installed.")
+
+    a = np.array([[1.0, 2.0j], [-1.0j, 2.0]])
+    adag = a.copy().transpose().conjugate()
+    assert (Dagger(a) == adag).all()
+
+
+scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
+
+
+def test_scipy_sparse_dagger():
+    if not np:
+        skip("numpy not installed.")
+    if not scipy:
+        skip("scipy not installed.")
+    else:
+        sparse = scipy.sparse
+
+    a = sparse.csr_matrix([[1.0 + 0.0j, 2.0j], [-1.0j, 2.0 + 0.0j]])
+    adag = a.copy().transpose().conjugate()
+    assert np.linalg.norm((Dagger(a) - adag).todense()) == 0.0
+
+
+def test_unknown():
+    """Check treatment of unknown objects.
+    Objects without adjoint or conjugate/transpose methods
+    are sympified and wrapped in dagger.
+    """
+    x = symbols("x", commutative=False)
+    result = Dagger(x)
+    assert result.args == (x,) and isinstance(result, adjoint)
+
+
+def test_unevaluated():
+    """Check that evaluate=False returns unevaluated Dagger.
+    """
+    x = symbols("x", real=True)
+    assert Dagger(x) == x
+    result = Dagger(x, evaluate=False)
+    assert result.args == (x,) and isinstance(result, adjoint)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_density.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_density.py
new file mode 100644
index 0000000000000000000000000000000000000000..399acce6e201b39f65ea674048198fd2f087b4d0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_density.py
@@ -0,0 +1,289 @@
+from sympy.core.numbers import Rational
+from sympy.core.singleton import S
+from sympy.core.symbol import symbols
+from sympy.functions.elementary.exponential import log
+from sympy.external import import_module
+from sympy.physics.quantum.density import Density, entropy, fidelity
+from sympy.physics.quantum.state import Ket, TimeDepKet
+from sympy.physics.quantum.qubit import Qubit
+from sympy.physics.quantum.represent import represent
+from sympy.physics.quantum.dagger import Dagger
+from sympy.physics.quantum.cartesian import XKet, PxKet, PxOp, XOp
+from sympy.physics.quantum.spin import JzKet
+from sympy.physics.quantum.operator import OuterProduct
+from sympy.physics.quantum.trace import Tr
+from sympy.functions import sqrt
+from sympy.testing.pytest import raises
+from sympy.physics.quantum.matrixutils import scipy_sparse_matrix
+from sympy.physics.quantum.tensorproduct import TensorProduct
+
+
+def test_eval_args():
+    # check instance created
+    assert isinstance(Density([Ket(0), 0.5], [Ket(1), 0.5]), Density)
+    assert isinstance(Density([Qubit('00'), 1/sqrt(2)],
+                              [Qubit('11'), 1/sqrt(2)]), Density)
+
+    #test if Qubit object type preserved
+    d = Density([Qubit('00'), 1/sqrt(2)], [Qubit('11'), 1/sqrt(2)])
+    for (state, prob) in d.args:
+        assert isinstance(state, Qubit)
+
+    # check for value error, when prob is not provided
+    raises(ValueError, lambda: Density([Ket(0)], [Ket(1)]))
+
+
+def test_doit():
+
+    x, y = symbols('x y')
+    A, B, C, D, E, F = symbols('A B C D E F', commutative=False)
+    d = Density([XKet(), 0.5], [PxKet(), 0.5])
+    assert (0.5*(PxKet()*Dagger(PxKet())) +
+            0.5*(XKet()*Dagger(XKet()))) == d.doit()
+
+    # check for kets with expr in them
+    d_with_sym = Density([XKet(x*y), 0.5], [PxKet(x*y), 0.5])
+    assert (0.5*(PxKet(x*y)*Dagger(PxKet(x*y))) +
+            0.5*(XKet(x*y)*Dagger(XKet(x*y)))) == d_with_sym.doit()
+
+    d = Density([(A + B)*C, 1.0])
+    assert d.doit() == (1.0*A*C*Dagger(C)*Dagger(A) +
+                        1.0*A*C*Dagger(C)*Dagger(B) +
+                        1.0*B*C*Dagger(C)*Dagger(A) +
+                        1.0*B*C*Dagger(C)*Dagger(B))
+
+    #  With TensorProducts as args
+    # Density with simple tensor products as args
+    t = TensorProduct(A, B, C)
+    d = Density([t, 1.0])
+    assert d.doit() == \
+        1.0 * TensorProduct(A*Dagger(A), B*Dagger(B), C*Dagger(C))
+
+    # Density with multiple Tensorproducts as states
+    t2 = TensorProduct(A, B)
+    t3 = TensorProduct(C, D)
+
+    d = Density([t2, 0.5], [t3, 0.5])
+    assert d.doit() == (0.5 * TensorProduct(A*Dagger(A), B*Dagger(B)) +
+                        0.5 * TensorProduct(C*Dagger(C), D*Dagger(D)))
+
+    #Density with mixed states
+    d = Density([t2 + t3, 1.0])
+    assert d.doit() == (1.0 * TensorProduct(A*Dagger(A), B*Dagger(B)) +
+                        1.0 * TensorProduct(A*Dagger(C), B*Dagger(D)) +
+                        1.0 * TensorProduct(C*Dagger(A), D*Dagger(B)) +
+                        1.0 * TensorProduct(C*Dagger(C), D*Dagger(D)))
+
+    #Density operators with spin states
+    tp1 = TensorProduct(JzKet(1, 1), JzKet(1, -1))
+    d = Density([tp1, 1])
+
+    # full trace
+    t = Tr(d)
+    assert t.doit() == 1
+
+    #Partial trace on density operators with spin states
+    t = Tr(d, [0])
+    assert t.doit() == JzKet(1, -1) * Dagger(JzKet(1, -1))
+    t = Tr(d, [1])
+    assert t.doit() == JzKet(1, 1) * Dagger(JzKet(1, 1))
+
+    # with another spin state
+    tp2 = TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))
+    d = Density([tp2, 1])
+
+    #full trace
+    t = Tr(d)
+    assert t.doit() == 1
+
+    #Partial trace on density operators with spin states
+    t = Tr(d, [0])
+    assert t.doit() == JzKet(S.Half, Rational(-1, 2)) * Dagger(JzKet(S.Half, Rational(-1, 2)))
+    t = Tr(d, [1])
+    assert t.doit() == JzKet(S.Half, S.Half) * Dagger(JzKet(S.Half, S.Half))
+
+
+def test_apply_op():
+    d = Density([Ket(0), 0.5], [Ket(1), 0.5])
+    assert d.apply_op(XOp()) == Density([XOp()*Ket(0), 0.5],
+                                        [XOp()*Ket(1), 0.5])
+
+
+def test_represent():
+    x, y = symbols('x y')
+    d = Density([XKet(), 0.5], [PxKet(), 0.5])
+    assert (represent(0.5*(PxKet()*Dagger(PxKet()))) +
+            represent(0.5*(XKet()*Dagger(XKet())))) == represent(d)
+
+    # check for kets with expr in them
+    d_with_sym = Density([XKet(x*y), 0.5], [PxKet(x*y), 0.5])
+    assert (represent(0.5*(PxKet(x*y)*Dagger(PxKet(x*y)))) +
+            represent(0.5*(XKet(x*y)*Dagger(XKet(x*y))))) == \
+        represent(d_with_sym)
+
+    # check when given explicit basis
+    assert (represent(0.5*(XKet()*Dagger(XKet())), basis=PxOp()) +
+            represent(0.5*(PxKet()*Dagger(PxKet())), basis=PxOp())) == \
+        represent(d, basis=PxOp())
+
+
+def test_states():
+    d = Density([Ket(0), 0.5], [Ket(1), 0.5])
+    states = d.states()
+    assert states[0] == Ket(0) and states[1] == Ket(1)
+
+
+def test_probs():
+    d = Density([Ket(0), .75], [Ket(1), 0.25])
+    probs = d.probs()
+    assert probs[0] == 0.75 and probs[1] == 0.25
+
+    #probs can be symbols
+    x, y = symbols('x y')
+    d = Density([Ket(0), x], [Ket(1), y])
+    probs = d.probs()
+    assert probs[0] == x and probs[1] == y
+
+
+def test_get_state():
+    x, y = symbols('x y')
+    d = Density([Ket(0), x], [Ket(1), y])
+    states = (d.get_state(0), d.get_state(1))
+    assert states[0] == Ket(0) and states[1] == Ket(1)
+
+
+def test_get_prob():
+    x, y = symbols('x y')
+    d = Density([Ket(0), x], [Ket(1), y])
+    probs = (d.get_prob(0), d.get_prob(1))
+    assert probs[0] == x and probs[1] == y
+
+
+def test_entropy():
+    up = JzKet(S.Half, S.Half)
+    down = JzKet(S.Half, Rational(-1, 2))
+    d = Density((up, S.Half), (down, S.Half))
+
+    # test for density object
+    ent = entropy(d)
+    assert entropy(d) == log(2)/2
+    assert d.entropy() == log(2)/2
+
+    np = import_module('numpy', min_module_version='1.4.0')
+    if np:
+        #do this test only if 'numpy' is available on test machine
+        np_mat = represent(d, format='numpy')
+        ent = entropy(np_mat)
+        assert isinstance(np_mat, np.ndarray)
+        assert ent.real == 0.69314718055994529
+        assert ent.imag == 0
+
+    scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
+    if scipy and np:
+        #do this test only if numpy and scipy are available
+        mat = represent(d, format="scipy.sparse")
+        assert isinstance(mat, scipy_sparse_matrix)
+        assert ent.real == 0.69314718055994529
+        assert ent.imag == 0
+
+
+def test_eval_trace():
+    up = JzKet(S.Half, S.Half)
+    down = JzKet(S.Half, Rational(-1, 2))
+    d = Density((up, 0.5), (down, 0.5))
+
+    t = Tr(d)
+    assert t.doit() == 1.0
+
+    #test dummy time dependent states
+    class TestTimeDepKet(TimeDepKet):
+        def _eval_trace(self, bra, **options):
+            return 1
+
+    x, t = symbols('x t')
+    k1 = TestTimeDepKet(0, 0.5)
+    k2 = TestTimeDepKet(0, 1)
+    d = Density([k1, 0.5], [k2, 0.5])
+    assert d.doit() == (0.5 * OuterProduct(k1, k1.dual) +
+                        0.5 * OuterProduct(k2, k2.dual))
+
+    t = Tr(d)
+    assert t.doit() == 1.0
+
+
+def test_fidelity():
+    #test with kets
+    up = JzKet(S.Half, S.Half)
+    down = JzKet(S.Half, Rational(-1, 2))
+    updown = (S.One/sqrt(2))*up + (S.One/sqrt(2))*down
+
+    #check with matrices
+    up_dm = represent(up * Dagger(up))
+    down_dm = represent(down * Dagger(down))
+    updown_dm = represent(updown * Dagger(updown))
+
+    assert abs(fidelity(up_dm, up_dm) - 1) < 1e-3
+    assert fidelity(up_dm, down_dm) < 1e-3
+    assert abs(fidelity(up_dm, updown_dm) - (S.One/sqrt(2))) < 1e-3
+    assert abs(fidelity(updown_dm, down_dm) - (S.One/sqrt(2))) < 1e-3
+
+    #check with density
+    up_dm = Density([up, 1.0])
+    down_dm = Density([down, 1.0])
+    updown_dm = Density([updown, 1.0])
+
+    assert abs(fidelity(up_dm, up_dm) - 1) < 1e-3
+    assert abs(fidelity(up_dm, down_dm)) < 1e-3
+    assert abs(fidelity(up_dm, updown_dm) - (S.One/sqrt(2))) < 1e-3
+    assert abs(fidelity(updown_dm, down_dm) - (S.One/sqrt(2))) < 1e-3
+
+    #check mixed states with density
+    updown2 = sqrt(3)/2*up + S.Half*down
+    d1 = Density([updown, 0.25], [updown2, 0.75])
+    d2 = Density([updown, 0.75], [updown2, 0.25])
+    assert abs(fidelity(d1, d2) - 0.991) < 1e-3
+    assert abs(fidelity(d2, d1) - fidelity(d1, d2)) < 1e-3
+
+    #using qubits/density(pure states)
+    state1 = Qubit('0')
+    state2 = Qubit('1')
+    state3 = S.One/sqrt(2)*state1 + S.One/sqrt(2)*state2
+    state4 = sqrt(Rational(2, 3))*state1 + S.One/sqrt(3)*state2
+
+    state1_dm = Density([state1, 1])
+    state2_dm = Density([state2, 1])
+    state3_dm = Density([state3, 1])
+
+    assert fidelity(state1_dm, state1_dm) == 1
+    assert fidelity(state1_dm, state2_dm) == 0
+    assert abs(fidelity(state1_dm, state3_dm) - 1/sqrt(2)) < 1e-3
+    assert abs(fidelity(state3_dm, state2_dm) - 1/sqrt(2)) < 1e-3
+
+    #using qubits/density(mixed states)
+    d1 = Density([state3, 0.70], [state4, 0.30])
+    d2 = Density([state3, 0.20], [state4, 0.80])
+    assert abs(fidelity(d1, d1) - 1) < 1e-3
+    assert abs(fidelity(d1, d2) - 0.996) < 1e-3
+    assert abs(fidelity(d1, d2) - fidelity(d2, d1)) < 1e-3
+
+    #TODO: test for invalid arguments
+    # non-square matrix
+    mat1 = [[0, 0],
+            [0, 0],
+            [0, 0]]
+
+    mat2 = [[0, 0],
+            [0, 0]]
+    raises(ValueError, lambda: fidelity(mat1, mat2))
+
+    # unequal dimensions
+    mat1 = [[0, 0],
+            [0, 0]]
+    mat2 = [[0, 0, 0],
+            [0, 0, 0],
+            [0, 0, 0]]
+    raises(ValueError, lambda: fidelity(mat1, mat2))
+
+    # unsupported data-type
+    x, y = 1, 2  # random values that is not a matrix
+    raises(ValueError, lambda: fidelity(x, y))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_fermion.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_fermion.py
new file mode 100644
index 0000000000000000000000000000000000000000..061648c2d5578481196949c38e90ff169fcea972
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_fermion.py
@@ -0,0 +1,62 @@
+from pytest import raises
+
+import sympy
+from sympy.physics.quantum import Dagger, AntiCommutator, qapply
+from sympy.physics.quantum.fermion import FermionOp
+from sympy.physics.quantum.fermion import FermionFockKet, FermionFockBra
+from sympy import Symbol
+
+
+def test_fermionoperator():
+    c = FermionOp('c')
+    d = FermionOp('d')
+
+    assert isinstance(c, FermionOp)
+    assert isinstance(Dagger(c), FermionOp)
+
+    assert c.is_annihilation
+    assert not Dagger(c).is_annihilation
+
+    assert FermionOp("c") == FermionOp("c", True)
+    assert FermionOp("c") != FermionOp("d")
+    assert FermionOp("c", True) != FermionOp("c", False)
+
+    assert AntiCommutator(c, Dagger(c)).doit() == 1
+
+    assert AntiCommutator(c, Dagger(d)).doit() == c * Dagger(d) + Dagger(d) * c
+
+
+def test_fermion_states():
+    c = FermionOp("c")
+
+    # Fock states
+    assert (FermionFockBra(0) * FermionFockKet(1)).doit() == 0
+    assert (FermionFockBra(1) * FermionFockKet(1)).doit() == 1
+
+    assert qapply(c * FermionFockKet(1)) == FermionFockKet(0)
+    assert qapply(c * FermionFockKet(0)) == 0
+
+    assert qapply(Dagger(c) * FermionFockKet(0)) == FermionFockKet(1)
+    assert qapply(Dagger(c) * FermionFockKet(1)) == 0
+
+
+def test_power():
+    c = FermionOp("c")
+    assert c**0 == 1
+    assert c**1 == c
+    assert c**2 == 0
+    assert c**3 == 0
+    assert Dagger(c)**1 == Dagger(c)
+    assert Dagger(c)**2 == 0
+
+    assert (c**Symbol('a')).func == sympy.core.power.Pow
+    assert (c**Symbol('a')).args == (c, Symbol('a'))
+
+    with raises(ValueError):
+        c**-1
+
+    with raises(ValueError):
+        c**3.2
+
+    with raises(TypeError):
+        c**1j
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_gate.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_gate.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d7bf1d624faca8afe4b10699d23acc161ca0cdd
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_gate.py
@@ -0,0 +1,360 @@
+from sympy.core.mul import Mul
+from sympy.core.numbers import (I, Integer, Rational, pi)
+from sympy.core.symbol import (Wild, symbols)
+from sympy.functions.elementary.exponential import exp
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.matrices import Matrix, ImmutableMatrix
+
+from sympy.physics.quantum.gate import (XGate, YGate, ZGate, random_circuit,
+        CNOT, IdentityGate, H, X, Y, S, T, Z, SwapGate, gate_simp, gate_sort,
+        CNotGate, TGate, HadamardGate, PhaseGate, UGate, CGate)
+from sympy.physics.quantum.commutator import Commutator
+from sympy.physics.quantum.anticommutator import AntiCommutator
+from sympy.physics.quantum.represent import represent
+from sympy.physics.quantum.qapply import qapply
+from sympy.physics.quantum.qubit import Qubit, IntQubit, qubit_to_matrix, \
+    matrix_to_qubit
+from sympy.physics.quantum.matrixutils import matrix_to_zero
+from sympy.physics.quantum.matrixcache import sqrt2_inv
+from sympy.physics.quantum import Dagger
+
+
+def test_gate():
+    """Test a basic gate."""
+    h = HadamardGate(1)
+    assert h.min_qubits == 2
+    assert h.nqubits == 1
+
+    i0 = Wild('i0')
+    i1 = Wild('i1')
+    h0_w1 = HadamardGate(i0)
+    h0_w2 = HadamardGate(i0)
+    h1_w1 = HadamardGate(i1)
+
+    assert h0_w1 == h0_w2
+    assert h0_w1 != h1_w1
+    assert h1_w1 != h0_w2
+
+    cnot_10_w1 = CNOT(i1, i0)
+    cnot_10_w2 = CNOT(i1, i0)
+    cnot_01_w1 = CNOT(i0, i1)
+
+    assert cnot_10_w1 == cnot_10_w2
+    assert cnot_10_w1 != cnot_01_w1
+    assert cnot_10_w2 != cnot_01_w1
+
+
+def test_UGate():
+    a, b, c, d = symbols('a,b,c,d')
+    uMat = Matrix([[a, b], [c, d]])
+
+    # Test basic case where gate exists in 1-qubit space
+    u1 = UGate((0,), uMat)
+    assert represent(u1, nqubits=1) == uMat
+    assert qapply(u1*Qubit('0')) == a*Qubit('0') + c*Qubit('1')
+    assert qapply(u1*Qubit('1')) == b*Qubit('0') + d*Qubit('1')
+
+    # Test case where gate exists in a larger space
+    u2 = UGate((1,), uMat)
+    u2Rep = represent(u2, nqubits=2)
+    for i in range(4):
+        assert u2Rep*qubit_to_matrix(IntQubit(i, 2)) == \
+            qubit_to_matrix(qapply(u2*IntQubit(i, 2)))
+
+
+def test_cgate():
+    """Test the general CGate."""
+    # Test single control functionality
+    CNOTMatrix = Matrix(
+        [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
+    assert represent(CGate(1, XGate(0)), nqubits=2) == CNOTMatrix
+
+    # Test multiple control bit functionality
+    ToffoliGate = CGate((1, 2), XGate(0))
+    assert represent(ToffoliGate, nqubits=3) == \
+        Matrix(
+            [[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0],
+    [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0,
+        1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1],
+    [0, 0, 0, 0, 0, 0, 1, 0]])
+
+    ToffoliGate = CGate((3, 0), XGate(1))
+    assert qapply(ToffoliGate*Qubit('1001')) == \
+        matrix_to_qubit(represent(ToffoliGate*Qubit('1001'), nqubits=4))
+    assert qapply(ToffoliGate*Qubit('0000')) == \
+        matrix_to_qubit(represent(ToffoliGate*Qubit('0000'), nqubits=4))
+
+    CYGate = CGate(1, YGate(0))
+    CYGate_matrix = Matrix(
+        ((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 0, -I), (0, 0, I, 0)))
+    # Test 2 qubit controlled-Y gate decompose method.
+    assert represent(CYGate.decompose(), nqubits=2) == CYGate_matrix
+
+    CZGate = CGate(0, ZGate(1))
+    CZGate_matrix = Matrix(
+        ((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, -1)))
+    assert qapply(CZGate*Qubit('11')) == -Qubit('11')
+    assert matrix_to_qubit(represent(CZGate*Qubit('11'), nqubits=2)) == \
+        -Qubit('11')
+    # Test 2 qubit controlled-Z gate decompose method.
+    assert represent(CZGate.decompose(), nqubits=2) == CZGate_matrix
+
+    CPhaseGate = CGate(0, PhaseGate(1))
+    assert qapply(CPhaseGate*Qubit('11')) == \
+        I*Qubit('11')
+    assert matrix_to_qubit(represent(CPhaseGate*Qubit('11'), nqubits=2)) == \
+        I*Qubit('11')
+
+    # Test that the dagger, inverse, and power of CGate is evaluated properly
+    assert Dagger(CZGate) == CZGate
+    assert pow(CZGate, 1) == Dagger(CZGate)
+    assert Dagger(CZGate) == CZGate.inverse()
+    assert Dagger(CPhaseGate) != CPhaseGate
+    assert Dagger(CPhaseGate) == CPhaseGate.inverse()
+    assert Dagger(CPhaseGate) == pow(CPhaseGate, -1)
+    assert pow(CPhaseGate, -1) == CPhaseGate.inverse()
+
+
+def test_UGate_CGate_combo():
+    a, b, c, d = symbols('a,b,c,d')
+    uMat = Matrix([[a, b], [c, d]])
+    cMat = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, a, b], [0, 0, c, d]])
+
+    # Test basic case where gate exists in 1-qubit space.
+    u1 = UGate((0,), uMat)
+    cu1 = CGate(1, u1)
+    assert represent(cu1, nqubits=2) == cMat
+    assert qapply(cu1*Qubit('10')) == a*Qubit('10') + c*Qubit('11')
+    assert qapply(cu1*Qubit('11')) == b*Qubit('10') + d*Qubit('11')
+    assert qapply(cu1*Qubit('01')) == Qubit('01')
+    assert qapply(cu1*Qubit('00')) == Qubit('00')
+
+    # Test case where gate exists in a larger space.
+    u2 = UGate((1,), uMat)
+    u2Rep = represent(u2, nqubits=2)
+    for i in range(4):
+        assert u2Rep*qubit_to_matrix(IntQubit(i, 2)) == \
+            qubit_to_matrix(qapply(u2*IntQubit(i, 2)))
+
+def test_UGate_OneQubitGate_combo():
+    v, w, f, g = symbols('v w f g')
+    uMat1 = ImmutableMatrix([[v, w], [f, g]])
+    cMat1 = Matrix([[v, w + 1, 0, 0], [f + 1, g, 0, 0], [0, 0, v, w + 1], [0, 0, f + 1, g]])
+    u1 = X(0) + UGate(0, uMat1)
+    assert represent(u1, nqubits=2) == cMat1
+
+    uMat2 = ImmutableMatrix([[1/sqrt(2), 1/sqrt(2)], [I/sqrt(2), -I/sqrt(2)]])
+    cMat2_1 = Matrix([[Rational(1, 2) + I/2, Rational(1, 2) - I/2],
+                      [Rational(1, 2) - I/2, Rational(1, 2) + I/2]])
+    cMat2_2 = Matrix([[1, 0], [0, I]])
+    u2 = UGate(0, uMat2)
+    assert represent(H(0)*u2, nqubits=1) == cMat2_1
+    assert represent(u2*H(0), nqubits=1) == cMat2_2
+
+def test_represent_hadamard():
+    """Test the representation of the hadamard gate."""
+    circuit = HadamardGate(0)*Qubit('00')
+    answer = represent(circuit, nqubits=2)
+    # Check that the answers are same to within an epsilon.
+    assert answer == Matrix([sqrt2_inv, sqrt2_inv, 0, 0])
+
+
+def test_represent_xgate():
+    """Test the representation of the X gate."""
+    circuit = XGate(0)*Qubit('00')
+    answer = represent(circuit, nqubits=2)
+    assert Matrix([0, 1, 0, 0]) == answer
+
+
+def test_represent_ygate():
+    """Test the representation of the Y gate."""
+    circuit = YGate(0)*Qubit('00')
+    answer = represent(circuit, nqubits=2)
+    assert answer[0] == 0 and answer[1] == I and \
+        answer[2] == 0 and answer[3] == 0
+
+
+def test_represent_zgate():
+    """Test the representation of the Z gate."""
+    circuit = ZGate(0)*Qubit('00')
+    answer = represent(circuit, nqubits=2)
+    assert Matrix([1, 0, 0, 0]) == answer
+
+
+def test_represent_phasegate():
+    """Test the representation of the S gate."""
+    circuit = PhaseGate(0)*Qubit('01')
+    answer = represent(circuit, nqubits=2)
+    assert Matrix([0, I, 0, 0]) == answer
+
+
+def test_represent_tgate():
+    """Test the representation of the T gate."""
+    circuit = TGate(0)*Qubit('01')
+    assert Matrix([0, exp(I*pi/4), 0, 0]) == represent(circuit, nqubits=2)
+
+
+def test_compound_gates():
+    """Test a compound gate representation."""
+    circuit = YGate(0)*ZGate(0)*XGate(0)*HadamardGate(0)*Qubit('00')
+    answer = represent(circuit, nqubits=2)
+    assert Matrix([I/sqrt(2), I/sqrt(2), 0, 0]) == answer
+
+
+def test_cnot_gate():
+    """Test the CNOT gate."""
+    circuit = CNotGate(1, 0)
+    assert represent(circuit, nqubits=2) == \
+        Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
+    circuit = circuit*Qubit('111')
+    assert matrix_to_qubit(represent(circuit, nqubits=3)) == \
+        qapply(circuit)
+
+    circuit = CNotGate(1, 0)
+    assert Dagger(circuit) == circuit
+    assert Dagger(Dagger(circuit)) == circuit
+    assert circuit*circuit == 1
+
+
+def test_gate_sort():
+    """Test gate_sort."""
+    for g in (X, Y, Z, H, S, T):
+        assert gate_sort(g(2)*g(1)*g(0)) == g(0)*g(1)*g(2)
+    e = gate_sort(X(1)*H(0)**2*CNOT(0, 1)*X(1)*X(0))
+    assert e == H(0)**2*CNOT(0, 1)*X(0)*X(1)**2
+    assert gate_sort(Z(0)*X(0)) == -X(0)*Z(0)
+    assert gate_sort(Z(0)*X(0)**2) == X(0)**2*Z(0)
+    assert gate_sort(Y(0)*H(0)) == -H(0)*Y(0)
+    assert gate_sort(Y(0)*X(0)) == -X(0)*Y(0)
+    assert gate_sort(Z(0)*Y(0)) == -Y(0)*Z(0)
+    assert gate_sort(T(0)*S(0)) == S(0)*T(0)
+    assert gate_sort(Z(0)*S(0)) == S(0)*Z(0)
+    assert gate_sort(Z(0)*T(0)) == T(0)*Z(0)
+    assert gate_sort(Z(0)*CNOT(0, 1)) == CNOT(0, 1)*Z(0)
+    assert gate_sort(S(0)*CNOT(0, 1)) == CNOT(0, 1)*S(0)
+    assert gate_sort(T(0)*CNOT(0, 1)) == CNOT(0, 1)*T(0)
+    assert gate_sort(X(1)*CNOT(0, 1)) == CNOT(0, 1)*X(1)
+    # This takes a long time and should only be uncommented once in a while.
+    # nqubits = 5
+    # ngates = 10
+    # trials = 10
+    # for i in range(trials):
+    #     c = random_circuit(ngates, nqubits)
+    #     assert represent(c, nqubits=nqubits) == \
+    #            represent(gate_sort(c), nqubits=nqubits)
+
+
+def test_gate_simp():
+    """Test gate_simp."""
+    e = H(0)*X(1)*H(0)**2*CNOT(0, 1)*X(1)**3*X(0)*Z(3)**2*S(4)**3
+    assert gate_simp(e) == H(0)*CNOT(0, 1)*S(4)*X(0)*Z(4)
+    assert gate_simp(X(0)*X(0)) == 1
+    assert gate_simp(Y(0)*Y(0)) == 1
+    assert gate_simp(Z(0)*Z(0)) == 1
+    assert gate_simp(H(0)*H(0)) == 1
+    assert gate_simp(T(0)*T(0)) == S(0)
+    assert gate_simp(S(0)*S(0)) == Z(0)
+    assert gate_simp(Integer(1)) == Integer(1)
+    assert gate_simp(X(0)**2 + Y(0)**2) == Integer(2)
+
+
+def test_swap_gate():
+    """Test the SWAP gate."""
+    swap_gate_matrix = Matrix(
+        ((1, 0, 0, 0), (0, 0, 1, 0), (0, 1, 0, 0), (0, 0, 0, 1)))
+    assert represent(SwapGate(1, 0).decompose(), nqubits=2) == swap_gate_matrix
+    assert qapply(SwapGate(1, 3)*Qubit('0010')) == Qubit('1000')
+    nqubits = 4
+    for i in range(nqubits):
+        for j in range(i):
+            assert represent(SwapGate(i, j), nqubits=nqubits) == \
+                represent(SwapGate(i, j).decompose(), nqubits=nqubits)
+
+
+def test_one_qubit_commutators():
+    """Test single qubit gate commutation relations."""
+    for g1 in (IdentityGate, X, Y, Z, H, T, S):
+        for g2 in (IdentityGate, X, Y, Z, H, T, S):
+            e = Commutator(g1(0), g2(0))
+            a = matrix_to_zero(represent(e, nqubits=1, format='sympy'))
+            b = matrix_to_zero(represent(e.doit(), nqubits=1, format='sympy'))
+            assert a == b
+
+            e = Commutator(g1(0), g2(1))
+            assert e.doit() == 0
+
+
+def test_one_qubit_anticommutators():
+    """Test single qubit gate anticommutation relations."""
+    for g1 in (IdentityGate, X, Y, Z, H):
+        for g2 in (IdentityGate, X, Y, Z, H):
+            e = AntiCommutator(g1(0), g2(0))
+            a = matrix_to_zero(represent(e, nqubits=1, format='sympy'))
+            b = matrix_to_zero(represent(e.doit(), nqubits=1, format='sympy'))
+            assert a == b
+            e = AntiCommutator(g1(0), g2(1))
+            a = matrix_to_zero(represent(e, nqubits=2, format='sympy'))
+            b = matrix_to_zero(represent(e.doit(), nqubits=2, format='sympy'))
+            assert a == b
+
+
+def test_cnot_commutators():
+    """Test commutators of involving CNOT gates."""
+    assert Commutator(CNOT(0, 1), Z(0)).doit() == 0
+    assert Commutator(CNOT(0, 1), T(0)).doit() == 0
+    assert Commutator(CNOT(0, 1), S(0)).doit() == 0
+    assert Commutator(CNOT(0, 1), X(1)).doit() == 0
+    assert Commutator(CNOT(0, 1), CNOT(0, 1)).doit() == 0
+    assert Commutator(CNOT(0, 1), CNOT(0, 2)).doit() == 0
+    assert Commutator(CNOT(0, 2), CNOT(0, 1)).doit() == 0
+    assert Commutator(CNOT(1, 2), CNOT(1, 0)).doit() == 0
+
+
+def test_random_circuit():
+    c = random_circuit(10, 3)
+    assert isinstance(c, Mul)
+    m = represent(c, nqubits=3)
+    assert m.shape == (8, 8)
+    assert isinstance(m, Matrix)
+
+
+def test_hermitian_XGate():
+    x = XGate(1, 2)
+    x_dagger = Dagger(x)
+
+    assert (x == x_dagger)
+
+
+def test_hermitian_YGate():
+    y = YGate(1, 2)
+    y_dagger = Dagger(y)
+
+    assert (y == y_dagger)
+
+
+def test_hermitian_ZGate():
+    z = ZGate(1, 2)
+    z_dagger = Dagger(z)
+
+    assert (z == z_dagger)
+
+
+def test_unitary_XGate():
+    x = XGate(1, 2)
+    x_dagger = Dagger(x)
+
+    assert (x*x_dagger == 1)
+
+
+def test_unitary_YGate():
+    y = YGate(1, 2)
+    y_dagger = Dagger(y)
+
+    assert (y*y_dagger == 1)
+
+
+def test_unitary_ZGate():
+    z = ZGate(1, 2)
+    z_dagger = Dagger(z)
+
+    assert (z*z_dagger == 1)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_grover.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_grover.py
new file mode 100644
index 0000000000000000000000000000000000000000..b93a5bc5e59380a993dc34e4a160e75f799b3493
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_grover.py
@@ -0,0 +1,92 @@
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.matrices.dense import Matrix
+from sympy.physics.quantum.represent import represent
+from sympy.physics.quantum.qapply import qapply
+from sympy.physics.quantum.qubit import IntQubit
+from sympy.physics.quantum.grover import (apply_grover, superposition_basis,
+        OracleGate, grover_iteration, WGate)
+
+
+def return_one_on_two(qubits):
+    return qubits == IntQubit(2, qubits.nqubits)
+
+
+def return_one_on_one(qubits):
+    return qubits == IntQubit(1, nqubits=qubits.nqubits)
+
+
+def test_superposition_basis():
+    nbits = 2
+    first_half_state = IntQubit(0, nqubits=nbits)/2 + IntQubit(1, nqubits=nbits)/2
+    second_half_state = IntQubit(2, nbits)/2 + IntQubit(3, nbits)/2
+    assert first_half_state + second_half_state == superposition_basis(nbits)
+
+    nbits = 3
+    firstq = (1/sqrt(8))*IntQubit(0, nqubits=nbits) + (1/sqrt(8))*IntQubit(1, nqubits=nbits)
+    secondq = (1/sqrt(8))*IntQubit(2, nbits) + (1/sqrt(8))*IntQubit(3, nbits)
+    thirdq = (1/sqrt(8))*IntQubit(4, nbits) + (1/sqrt(8))*IntQubit(5, nbits)
+    fourthq = (1/sqrt(8))*IntQubit(6, nbits) + (1/sqrt(8))*IntQubit(7, nbits)
+    assert firstq + secondq + thirdq + fourthq == superposition_basis(nbits)
+
+
+def test_OracleGate():
+    v = OracleGate(1, lambda qubits: qubits == IntQubit(0))
+    assert qapply(v*IntQubit(0)) == -IntQubit(0)
+    assert qapply(v*IntQubit(1)) == IntQubit(1)
+
+    nbits = 2
+    v = OracleGate(2, return_one_on_two)
+    assert qapply(v*IntQubit(0, nbits)) == IntQubit(0, nqubits=nbits)
+    assert qapply(v*IntQubit(1, nbits)) == IntQubit(1, nqubits=nbits)
+    assert qapply(v*IntQubit(2, nbits)) == -IntQubit(2, nbits)
+    assert qapply(v*IntQubit(3, nbits)) == IntQubit(3, nbits)
+
+    assert represent(OracleGate(1, lambda qubits: qubits == IntQubit(0)), nqubits=1) == \
+           Matrix([[-1, 0], [0, 1]])
+    assert represent(v, nqubits=2) == Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
+
+
+def test_WGate():
+    nqubits = 2
+    basis_states = superposition_basis(nqubits)
+    assert qapply(WGate(nqubits)*basis_states) == basis_states
+
+    expected = ((2/sqrt(pow(2, nqubits)))*basis_states) - IntQubit(1, nqubits=nqubits)
+    assert qapply(WGate(nqubits)*IntQubit(1, nqubits=nqubits)) == expected
+
+
+def test_grover_iteration_1():
+    numqubits = 2
+    basis_states = superposition_basis(numqubits)
+    v = OracleGate(numqubits, return_one_on_one)
+    expected = IntQubit(1, nqubits=numqubits)
+    assert qapply(grover_iteration(basis_states, v)) == expected
+
+
+def test_grover_iteration_2():
+    numqubits = 4
+    basis_states = superposition_basis(numqubits)
+    v = OracleGate(numqubits, return_one_on_two)
+    # After (pi/4)sqrt(pow(2, n)), IntQubit(2) should have highest prob
+    # In this case, after around pi times (3 or 4)
+    iterated = grover_iteration(basis_states, v)
+    iterated = qapply(iterated)
+    iterated = grover_iteration(iterated, v)
+    iterated = qapply(iterated)
+    iterated = grover_iteration(iterated, v)
+    iterated = qapply(iterated)
+    # In this case, probability was highest after 3 iterations
+    # Probability of Qubit('0010') was 251/256 (3) vs 781/1024 (4)
+    # Ask about measurement
+    expected = (-13*basis_states)/64 + 264*IntQubit(2, numqubits)/256
+    assert qapply(expected) == iterated
+
+
+def test_grover():
+    nqubits = 2
+    assert apply_grover(return_one_on_one, nqubits) == IntQubit(1, nqubits=nqubits)
+
+    nqubits = 4
+    basis_states = superposition_basis(nqubits)
+    expected = (-13*basis_states)/64 + 264*IntQubit(2, nqubits)/256
+    assert apply_grover(return_one_on_two, 4) == qapply(expected)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/trace.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/trace.py
new file mode 100644
index 0000000000000000000000000000000000000000..03ab18f78a1bfcf5bfcd679f00eac8685144fd8c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/trace.py
@@ -0,0 +1,230 @@
+from sympy.core.add import Add
+from sympy.core.containers import Tuple
+from sympy.core.expr import Expr
+from sympy.core.mul import Mul
+from sympy.core.power import Pow
+from sympy.core.sorting import default_sort_key
+from sympy.core.sympify import sympify
+from sympy.matrices import Matrix
+
+
+def _is_scalar(e):
+    """ Helper method used in Tr"""
+
+    # sympify to set proper attributes
+    e = sympify(e)
+    if isinstance(e, Expr):
+        if (e.is_Integer or e.is_Float or
+            e.is_Rational or e.is_Number or
+            (e.is_Symbol and e.is_commutative)
+                ):
+            return True
+
+    return False
+
+
+def _cycle_permute(l):
+    """ Cyclic permutations based on canonical ordering
+
+    Explanation
+    ===========
+
+    This method does the sort based ascii values while
+    a better approach would be to used lexicographic sort.
+
+    TODO: Handle condition such as symbols have subscripts/superscripts
+    in case of lexicographic sort
+
+    """
+
+    if len(l) == 1:
+        return l
+
+    min_item = min(l, key=default_sort_key)
+    indices = [i for i, x in enumerate(l) if x == min_item]
+
+    le = list(l)
+    le.extend(l)  # duplicate and extend string for easy processing
+
+    # adding the first min_item index back for easier looping
+    indices.append(len(l) + indices[0])
+
+    # create sublist of items with first item as min_item and last_item
+    # in each of the sublist is item just before the next occurrence of
+    # minitem in the cycle formed.
+    sublist = [[le[indices[i]:indices[i + 1]]] for i in
+               range(len(indices) - 1)]
+
+    # we do comparison of strings by comparing elements
+    # in each sublist
+    idx = sublist.index(min(sublist))
+    ordered_l = le[indices[idx]:indices[idx] + len(l)]
+
+    return ordered_l
+
+
+def _rearrange_args(l):
+    """ this just moves the last arg to first position
+     to enable expansion of args
+     A,B,A ==> A**2,B
+    """
+    if len(l) == 1:
+        return l
+
+    x = list(l[-1:])
+    x.extend(l[0:-1])
+    return Mul(*x).args
+
+
+class Tr(Expr):
+    """ Generic Trace operation than can trace over:
+
+    a) SymPy matrix
+    b) operators
+    c) outer products
+
+    Parameters
+    ==========
+    o : operator, matrix, expr
+    i : tuple/list indices (optional)
+
+    Examples
+    ========
+
+    # TODO: Need to handle printing
+
+    a) Trace(A+B) = Tr(A) + Tr(B)
+    b) Trace(scalar*Operator) = scalar*Trace(Operator)
+
+    >>> from sympy.physics.quantum.trace import Tr
+    >>> from sympy import symbols, Matrix
+    >>> a, b = symbols('a b', commutative=True)
+    >>> A, B = symbols('A B', commutative=False)
+    >>> Tr(a*A,[2])
+    a*Tr(A)
+    >>> m = Matrix([[1,2],[1,1]])
+    >>> Tr(m)
+    2
+
+    """
+    def __new__(cls, *args):
+        """ Construct a Trace object.
+
+        Parameters
+        ==========
+        args = SymPy expression
+        indices = tuple/list if indices, optional
+
+        """
+
+        # expect no indices,int or a tuple/list/Tuple
+        if (len(args) == 2):
+            if not isinstance(args[1], (list, Tuple, tuple)):
+                indices = Tuple(args[1])
+            else:
+                indices = Tuple(*args[1])
+
+            expr = args[0]
+        elif (len(args) == 1):
+            indices = Tuple()
+            expr = args[0]
+        else:
+            raise ValueError("Arguments to Tr should be of form "
+                             "(expr[, [indices]])")
+
+        if isinstance(expr, Matrix):
+            return expr.trace()
+        elif hasattr(expr, 'trace') and callable(expr.trace):
+            #for any objects that have trace() defined e.g numpy
+            return expr.trace()
+        elif isinstance(expr, Add):
+            return Add(*[Tr(arg, indices) for arg in expr.args])
+        elif isinstance(expr, Mul):
+            c_part, nc_part = expr.args_cnc()
+            if len(nc_part) == 0:
+                return Mul(*c_part)
+            else:
+                obj = Expr.__new__(cls, Mul(*nc_part), indices )
+                #this check is needed to prevent cached instances
+                #being returned even if len(c_part)==0
+                return Mul(*c_part)*obj if len(c_part) > 0 else obj
+        elif isinstance(expr, Pow):
+            if (_is_scalar(expr.args[0]) and
+                    _is_scalar(expr.args[1])):
+                return expr
+            else:
+                return Expr.__new__(cls, expr, indices)
+        else:
+            if (_is_scalar(expr)):
+                return expr
+
+            return Expr.__new__(cls, expr, indices)
+
+    @property
+    def kind(self):
+        expr = self.args[0]
+        expr_kind = expr.kind
+        return expr_kind.element_kind
+
+    def doit(self, **hints):
+        """ Perform the trace operation.
+
+        #TODO: Current version ignores the indices set for partial trace.
+
+        >>> from sympy.physics.quantum.trace import Tr
+        >>> from sympy.physics.quantum.operator import OuterProduct
+        >>> from sympy.physics.quantum.spin import JzKet, JzBra
+        >>> t = Tr(OuterProduct(JzKet(1,1), JzBra(1,1)))
+        >>> t.doit()
+        1
+
+        """
+        if hasattr(self.args[0], '_eval_trace'):
+            return self.args[0]._eval_trace(indices=self.args[1])
+
+        return self
+
+    @property
+    def is_number(self):
+        # TODO : improve this implementation
+        return True
+
+    #TODO: Review if the permute method is needed
+    # and if it needs to return a new instance
+    def permute(self, pos):
+        """ Permute the arguments cyclically.
+
+        Parameters
+        ==========
+
+        pos : integer, if positive, shift-right, else shift-left
+
+        Examples
+        ========
+
+        >>> from sympy.physics.quantum.trace import Tr
+        >>> from sympy import symbols
+        >>> A, B, C, D = symbols('A B C D', commutative=False)
+        >>> t = Tr(A*B*C*D)
+        >>> t.permute(2)
+        Tr(C*D*A*B)
+        >>> t.permute(-2)
+        Tr(C*D*A*B)
+
+        """
+        if pos > 0:
+            pos = pos % len(self.args[0].args)
+        else:
+            pos = -(abs(pos) % len(self.args[0].args))
+
+        args = list(self.args[0].args[-pos:] + self.args[0].args[0:-pos])
+
+        return Tr(Mul(*(args)))
+
+    def _hashable_content(self):
+        if isinstance(self.args[0], Mul):
+            args = _cycle_permute(_rearrange_args(self.args[0].args))
+        else:
+            args = [self.args[0]]
+
+        return tuple(args) + (self.args[1], )
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/transforms.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..dcbbcd9040b4f8f987375c2f903031610d6f9061
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/quantum/transforms.py
@@ -0,0 +1,291 @@
+"""Transforms that are always applied to quantum expressions.
+
+This module uses the kind and _constructor_postprocessor_mapping APIs
+to transform different combinations of Operators, Bras, and Kets into
+Inner/Outer/TensorProducts. These transformations are registered
+with the postprocessing API of core classes like `Mul` and `Pow` and
+are always applied to any expression involving Bras, Kets, and
+Operators. This API replaces the custom `__mul__` and `__pow__`
+methods of the quantum classes, which were found to be inconsistent.
+
+THIS IS EXPERIMENTAL.
+"""
+from sympy.core.basic import Basic
+from sympy.core.expr import Expr
+from sympy.core.mul import Mul
+from sympy.core.singleton import S
+from sympy.multipledispatch.dispatcher import (
+    Dispatcher, ambiguity_register_error_ignore_dup
+)
+from sympy.utilities.misc import debug
+
+from sympy.physics.quantum.innerproduct import InnerProduct
+from sympy.physics.quantum.kind import KetKind, BraKind, OperatorKind
+from sympy.physics.quantum.operator import (
+    OuterProduct, IdentityOperator, Operator
+)
+from sympy.physics.quantum.state import BraBase, KetBase, StateBase
+from sympy.physics.quantum.tensorproduct import TensorProduct
+
+
+#-----------------------------------------------------------------------------
+# Multipledispatch based transformed for Mul and Pow
+#-----------------------------------------------------------------------------
+
+_transform_state_pair = Dispatcher('_transform_state_pair')
+"""Transform a pair of expression in a Mul to their canonical form.
+
+All functions that are registered with this dispatcher need to take
+two inputs and return either tuple of transformed outputs, or None if no
+transform is applied. The output tuple is inserted into the right place
+of the ``Mul`` that is being put into canonical form. It works something like
+the following:
+
+``Mul(a, b, c, d, e, f) -> Mul(*(_transform_state_pair(a, b) + (c, d, e, f))))``
+
+The transforms here are always applied when quantum objects are multiplied.
+
+THIS IS EXPERIMENTAL.
+
+However, users of ``sympy.physics.quantum`` can import this dispatcher and
+register their own transforms to control the canonical form of products
+of quantum expressions.
+"""
+
+@_transform_state_pair.register(Expr, Expr)
+def _transform_expr(a, b):
+    """Default transformer that does nothing for base types."""
+    return None
+
+
+# The identity times anything is the anything.
+_transform_state_pair.add(
+    (IdentityOperator, Expr),
+    lambda x, y: (y,),
+    on_ambiguity=ambiguity_register_error_ignore_dup
+)
+_transform_state_pair.add(
+    (Expr, IdentityOperator),
+    lambda x, y: (x,),
+    on_ambiguity=ambiguity_register_error_ignore_dup
+)
+_transform_state_pair.add(
+    (IdentityOperator, IdentityOperator),
+    lambda x, y: S.One,
+    on_ambiguity=ambiguity_register_error_ignore_dup
+)
+
+@_transform_state_pair.register(BraBase, KetBase)
+def _transform_bra_ket(a, b):
+    """Transform a bra*ket -> InnerProduct(bra, ket)."""
+    return (InnerProduct(a, b),)
+
+@_transform_state_pair.register(KetBase, BraBase)
+def _transform_ket_bra(a, b):
+    """Transform a keT*bra -> OuterProduct(ket, bra)."""
+    return (OuterProduct(a, b),)
+
+@_transform_state_pair.register(KetBase, KetBase)
+def _transform_ket_ket(a, b):
+    """Raise a TypeError if a user tries to multiply two kets.
+
+    Multiplication based on `*` is not a shorthand for tensor products.
+    """
+    raise TypeError(
+        'Multiplication of two kets is not allowed. Use TensorProduct instead.'
+    )
+
+@_transform_state_pair.register(BraBase, BraBase)
+def _transform_bra_bra(a, b):
+    """Raise a TypeError if a user tries to multiply two bras.
+
+    Multiplication based on `*` is not a shorthand for tensor products.
+    """
+    raise TypeError(
+        'Multiplication of two bras is not allowed. Use TensorProduct instead.'
+    )
+
+@_transform_state_pair.register(OuterProduct, KetBase)
+def _transform_op_ket(a, b):
+    return (InnerProduct(a.bra, b), a.ket)
+
+@_transform_state_pair.register(BraBase, OuterProduct)
+def _transform_bra_op(a, b):
+    return (InnerProduct(a, b.ket), b.bra)
+
+@_transform_state_pair.register(TensorProduct, KetBase)
+def _transform_tp_ket(a, b):
+    """Raise a TypeError if a user tries to multiply TensorProduct(*kets)*ket.
+
+    Multiplication based on `*` is not a shorthand for tensor products.
+    """
+    if a.kind == KetKind:
+        raise TypeError(
+            'Multiplication of TensorProduct(*kets)*ket is invalid.'
+        )
+
+@_transform_state_pair.register(KetBase, TensorProduct)
+def _transform_ket_tp(a, b):
+    """Raise a TypeError if a user tries to multiply ket*TensorProduct(*kets).
+
+    Multiplication based on `*` is not a shorthand for tensor products.
+    """
+    if b.kind == KetKind:
+        raise TypeError(
+            'Multiplication of ket*TensorProduct(*kets) is invalid.'
+        )
+
+@_transform_state_pair.register(TensorProduct, BraBase)
+def _transform_tp_bra(a, b):
+    """Raise a TypeError if a user tries to multiply TensorProduct(*bras)*bra.
+
+    Multiplication based on `*` is not a shorthand for tensor products.
+    """
+    if a.kind == BraKind:
+        raise TypeError(
+            'Multiplication of TensorProduct(*bras)*bra is invalid.'
+        )
+
+@_transform_state_pair.register(BraBase, TensorProduct)
+def _transform_bra_tp(a, b):
+    """Raise a TypeError if a user tries to multiply bra*TensorProduct(*bras).
+
+    Multiplication based on `*` is not a shorthand for tensor products.
+    """
+    if b.kind == BraKind:
+        raise TypeError(
+            'Multiplication of bra*TensorProduct(*bras) is invalid.'
+        )
+
+@_transform_state_pair.register(TensorProduct, TensorProduct)
+def _transform_tp_tp(a, b):
+    """Combine a product of tensor products if their number of args matches."""
+    debug('_transform_tp_tp', a, b)
+    if len(a.args) == len(b.args):
+        if a.kind == BraKind and b.kind == KetKind:
+            return tuple([InnerProduct(i, j) for (i, j) in zip(a.args, b.args)])
+        else:
+            return (TensorProduct(*(i*j for (i, j) in zip(a.args, b.args))), )
+
+@_transform_state_pair.register(OuterProduct, OuterProduct)
+def _transform_op_op(a, b):
+    """Extract an inner produt from a product of outer products."""
+    return (InnerProduct(a.bra, b.ket), OuterProduct(a.ket, b.bra))
+
+
+#-----------------------------------------------------------------------------
+# Postprocessing transforms for Mul and Pow
+#-----------------------------------------------------------------------------
+
+
+def _postprocess_state_mul(expr):
+    """Transform a ``Mul`` of quantum expressions into canonical form.
+
+    This function is registered ``_constructor_postprocessor_mapping`` as a
+    transformer for ``Mul``. This means that every time a quantum expression
+    is multiplied, this function will be called to transform it into canonical
+    form as defined by the binary functions registered with
+    ``_transform_state_pair``.
+
+    The algorithm of this function is as follows. It walks the args
+    of the input ``Mul`` from left to right and calls ``_transform_state_pair``
+    on every overlapping pair of args. Each time ``_transform_state_pair``
+    is called it can return a tuple of items or None. If None, the pair isn't
+    transformed. If a tuple, then the last element of the tuple goes back into
+    the args to be transformed again and the others are extended onto the result
+    args list.
+
+    The algorithm can be visualized in the following table:
+
+    step   result                                 args
+    ============================================================================
+    #0     []                                     [a, b, c, d, e, f]
+    #1     []                                     [T(a,b), c, d, e, f]
+    #2     [T(a,b)[:-1]]                          [T(a,b)[-1], c, d, e, f]
+    #3     [T(a,b)[:-1]]                          [T(T(a,b)[-1], c), d, e, f]
+    #4     [T(a,b)[:-1], T(T(a,b)[-1], c)[:-1]]   [T(T(T(a,b)[-1], c)[-1], d), e, f]
+    #5     ...
+
+    One limitation of the current implementation is that we assume that only the
+    last item of the transformed tuple goes back into the args to be transformed
+    again. These seems to handle the cases needed for Mul. However, we may need
+    to extend the algorithm to have the entire tuple go back into the args for
+    further transformation.
+    """
+    args = list(expr.args)
+    result = []
+
+    # Continue as long as we have at least 2 elements
+    while len(args) > 1:
+        # Get first two elements
+        first = args.pop(0)
+        second = args[0]  # Look at second element without popping yet
+
+        transformed = _transform_state_pair(first, second)
+
+        if transformed is None:
+            # If transform returns None, append first element
+            result.append(first)
+        else:
+            # This item was transformed, pop and discard
+            args.pop(0)
+            # The last item goes back to be transformed again
+            args.insert(0, transformed[-1])
+            # All other items go directly into the result
+            result.extend(transformed[:-1])
+
+    # Append any remaining element
+    if args:
+        result.append(args[0])
+
+    return Mul._from_args(result, is_commutative=False)
+
+
+def _postprocess_state_pow(expr):
+    """Handle bras and kets raised to powers.
+
+    Under ``*`` multiplication this is invalid. Users should use a
+    TensorProduct instead.
+    """
+    base, exp = expr.as_base_exp()
+    if base.kind == KetKind or base.kind == BraKind:
+        raise TypeError(
+            'A bra or ket to a power is invalid, use TensorProduct instead.'
+        )
+
+
+def _postprocess_tp_pow(expr):
+    """Handle TensorProduct(*operators)**(positive integer).
+
+    This handles a tensor product of operators, to an integer power.
+    The power here is interpreted as regular multiplication, not
+    tensor product exponentiation. The form of exponentiation performed
+    here leaves the space and dimension of the object the same.
+
+    This operation does not make sense for tensor product's of states.
+    """
+    base, exp = expr.as_base_exp()
+    debug('_postprocess_tp_pow: ', base, exp, expr.args)
+    if isinstance(base, TensorProduct) and exp.is_integer and exp.is_positive and base.kind == OperatorKind:
+        new_args = [a**exp for a in base.args]
+        return TensorProduct(*new_args)
+
+
+#-----------------------------------------------------------------------------
+# Register the transformers with Basic._constructor_postprocessor_mapping
+#-----------------------------------------------------------------------------
+
+
+Basic._constructor_postprocessor_mapping[StateBase] = {
+    "Mul": [_postprocess_state_mul],
+    "Pow": [_postprocess_state_pow]
+}
+
+Basic._constructor_postprocessor_mapping[TensorProduct] = {
+    "Mul": [_postprocess_state_mul],
+    "Pow": [_postprocess_tp_pow]
+}
+
+Basic._constructor_postprocessor_mapping[Operator] = {
+    "Mul": [_postprocess_state_mul]
+}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/secondquant.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/secondquant.py
new file mode 100644
index 0000000000000000000000000000000000000000..189e8e8b50c785759b03f19f28285f7988cfca75
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/secondquant.py
@@ -0,0 +1,3125 @@
+"""
+Second quantization operators and states for bosons.
+
+This follow the formulation of Fetter and Welecka, "Quantum Theory
+of Many-Particle Systems."
+"""
+from collections import defaultdict
+
+from sympy.core.add import Add
+from sympy.core.basic import Basic
+from sympy.core.cache import cacheit
+from sympy.core.containers import Tuple
+from sympy.core.expr import Expr
+from sympy.core.function import Function
+from sympy.core.mul import Mul
+from sympy.core.numbers import I
+from sympy.core.power import Pow
+from sympy.core.singleton import S
+from sympy.core.sorting import default_sort_key
+from sympy.core.symbol import Dummy, Symbol
+from sympy.core.sympify import sympify
+from sympy.functions.elementary.complexes import conjugate
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.special.tensor_functions import KroneckerDelta
+from sympy.matrices.dense import zeros
+from sympy.printing.str import StrPrinter
+from sympy.utilities.iterables import has_dups
+
+__all__ = [
+    'Dagger',
+    'KroneckerDelta',
+    'BosonicOperator',
+    'AnnihilateBoson',
+    'CreateBoson',
+    'AnnihilateFermion',
+    'CreateFermion',
+    'FockState',
+    'FockStateBra',
+    'FockStateKet',
+    'FockStateBosonKet',
+    'FockStateBosonBra',
+    'FockStateFermionKet',
+    'FockStateFermionBra',
+    'BBra',
+    'BKet',
+    'FBra',
+    'FKet',
+    'F',
+    'Fd',
+    'B',
+    'Bd',
+    'apply_operators',
+    'InnerProduct',
+    'BosonicBasis',
+    'VarBosonicBasis',
+    'FixedBosonicBasis',
+    'Commutator',
+    'matrix_rep',
+    'contraction',
+    'wicks',
+    'NO',
+    'evaluate_deltas',
+    'AntiSymmetricTensor',
+    'substitute_dummies',
+    'PermutationOperator',
+    'simplify_index_permutations',
+]
+
+
+class SecondQuantizationError(Exception):
+    pass
+
+
+class AppliesOnlyToSymbolicIndex(SecondQuantizationError):
+    pass
+
+
+class ContractionAppliesOnlyToFermions(SecondQuantizationError):
+    pass
+
+
+class ViolationOfPauliPrinciple(SecondQuantizationError):
+    pass
+
+
+class SubstitutionOfAmbigousOperatorFailed(SecondQuantizationError):
+    pass
+
+
+class WicksTheoremDoesNotApply(SecondQuantizationError):
+    pass
+
+
+class Dagger(Expr):
+    """
+    Hermitian conjugate of creation/annihilation operators.
+
+    Examples
+    ========
+
+    >>> from sympy import I
+    >>> from sympy.physics.secondquant import Dagger, B, Bd
+    >>> Dagger(2*I)
+    -2*I
+    >>> Dagger(B(0))
+    CreateBoson(0)
+    >>> Dagger(Bd(0))
+    AnnihilateBoson(0)
+
+    """
+
+    def __new__(cls, arg):
+        arg = sympify(arg)
+        r = cls.eval(arg)
+        if isinstance(r, Basic):
+            return r
+        obj = Basic.__new__(cls, arg)
+        return obj
+
+    @classmethod
+    def eval(cls, arg):
+        """
+        Evaluates the Dagger instance.
+
+        Examples
+        ========
+
+        >>> from sympy import I
+        >>> from sympy.physics.secondquant import Dagger, B, Bd
+        >>> Dagger(2*I)
+        -2*I
+        >>> Dagger(B(0))
+        CreateBoson(0)
+        >>> Dagger(Bd(0))
+        AnnihilateBoson(0)
+
+        The eval() method is called automatically.
+
+        """
+        dagger = getattr(arg, '_dagger_', None)
+        if dagger is not None:
+            return dagger()
+        if isinstance(arg, Symbol) and arg.is_commutative:
+            return conjugate(arg)
+        if isinstance(arg, Basic):
+            if arg.is_Add:
+                return Add(*tuple(map(Dagger, arg.args)))
+            if arg.is_Mul:
+                return Mul(*tuple(map(Dagger, reversed(arg.args))))
+            if arg.is_Number:
+                return arg
+            if arg.is_Pow:
+                return Pow(Dagger(arg.args[0]), arg.args[1])
+            if arg == I:
+                return -arg
+        if isinstance(arg, Function):
+            if all(a.is_commutative for a in arg.args):
+                return arg.func(*[Dagger(a) for a in arg.args])
+        else:
+            return None
+
+    def _dagger_(self):
+        return self.args[0]
+
+
+class TensorSymbol(Expr):
+
+    is_commutative = True
+
+
+class AntiSymmetricTensor(TensorSymbol):
+    """Stores upper and lower indices in separate Tuple's.
+
+    Each group of indices is assumed to be antisymmetric.
+
+    Examples
+    ========
+
+    >>> from sympy import symbols
+    >>> from sympy.physics.secondquant import AntiSymmetricTensor
+    >>> i, j = symbols('i j', below_fermi=True)
+    >>> a, b = symbols('a b', above_fermi=True)
+    >>> AntiSymmetricTensor('v', (a, i), (b, j))
+    AntiSymmetricTensor(v, (a, i), (b, j))
+    >>> AntiSymmetricTensor('v', (i, a), (b, j))
+    -AntiSymmetricTensor(v, (a, i), (b, j))
+
+    As you can see, the indices are automatically sorted to a canonical form.
+
+    """
+
+    def __new__(cls, symbol, upper, lower):
+
+        try:
+            upper, signu = _sort_anticommuting_fermions(
+                upper, key=_sqkey_index)
+            lower, signl = _sort_anticommuting_fermions(
+                lower, key=_sqkey_index)
+
+        except ViolationOfPauliPrinciple:
+            return S.Zero
+
+        symbol = sympify(symbol)
+        upper = Tuple(*upper)
+        lower = Tuple(*lower)
+
+        if (signu + signl) % 2:
+            return -TensorSymbol.__new__(cls, symbol, upper, lower)
+        else:
+
+            return TensorSymbol.__new__(cls, symbol, upper, lower)
+
+    def _latex(self, printer):
+        return "{%s^{%s}_{%s}}" % (
+            self.symbol,
+            "".join([ printer._print(i) for i in self.args[1]]),
+            "".join([ printer._print(i) for i in self.args[2]])
+        )
+
+    @property
+    def symbol(self):
+        """
+        Returns the symbol of the tensor.
+
+        Examples
+        ========
+
+        >>> from sympy import symbols
+        >>> from sympy.physics.secondquant import AntiSymmetricTensor
+        >>> i, j = symbols('i,j', below_fermi=True)
+        >>> a, b = symbols('a,b', above_fermi=True)
+        >>> AntiSymmetricTensor('v', (a, i), (b, j))
+        AntiSymmetricTensor(v, (a, i), (b, j))
+        >>> AntiSymmetricTensor('v', (a, i), (b, j)).symbol
+        v
+
+        """
+        return self.args[0]
+
+    @property
+    def upper(self):
+        """
+        Returns the upper indices.
+
+        Examples
+        ========
+
+        >>> from sympy import symbols
+        >>> from sympy.physics.secondquant import AntiSymmetricTensor
+        >>> i, j = symbols('i,j', below_fermi=True)
+        >>> a, b = symbols('a,b', above_fermi=True)
+        >>> AntiSymmetricTensor('v', (a, i), (b, j))
+        AntiSymmetricTensor(v, (a, i), (b, j))
+        >>> AntiSymmetricTensor('v', (a, i), (b, j)).upper
+        (a, i)
+
+
+        """
+        return self.args[1]
+
+    @property
+    def lower(self):
+        """
+        Returns the lower indices.
+
+        Examples
+        ========
+
+        >>> from sympy import symbols
+        >>> from sympy.physics.secondquant import AntiSymmetricTensor
+        >>> i, j = symbols('i,j', below_fermi=True)
+        >>> a, b = symbols('a,b', above_fermi=True)
+        >>> AntiSymmetricTensor('v', (a, i), (b, j))
+        AntiSymmetricTensor(v, (a, i), (b, j))
+        >>> AntiSymmetricTensor('v', (a, i), (b, j)).lower
+        (b, j)
+
+        """
+        return self.args[2]
+
+    def __str__(self):
+        return "%s(%s,%s)" % self.args
+
+
+class SqOperator(Expr):
+    """
+    Base class for Second Quantization operators.
+    """
+
+    op_symbol = 'sq'
+
+    is_commutative = False
+
+    def __new__(cls, k):
+        obj = Basic.__new__(cls, sympify(k))
+        return obj
+
+    @property
+    def state(self):
+        """
+        Returns the state index related to this operator.
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy.physics.secondquant import F, Fd, B, Bd
+        >>> p = Symbol('p')
+        >>> F(p).state
+        p
+        >>> Fd(p).state
+        p
+        >>> B(p).state
+        p
+        >>> Bd(p).state
+        p
+
+        """
+        return self.args[0]
+
+    @property
+    def is_symbolic(self):
+        """
+        Returns True if the state is a symbol (as opposed to a number).
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy.physics.secondquant import F
+        >>> p = Symbol('p')
+        >>> F(p).is_symbolic
+        True
+        >>> F(1).is_symbolic
+        False
+
+        """
+        if self.state.is_Integer:
+            return False
+        else:
+            return True
+
+    def __repr__(self):
+        return NotImplemented
+
+    def __str__(self):
+        return "%s(%r)" % (self.op_symbol, self.state)
+
+    def apply_operator(self, state):
+        """
+        Applies an operator to itself.
+        """
+        raise NotImplementedError('implement apply_operator in a subclass')
+
+
+class BosonicOperator(SqOperator):
+    pass
+
+
+class Annihilator(SqOperator):
+    pass
+
+
+class Creator(SqOperator):
+    pass
+
+
+class AnnihilateBoson(BosonicOperator, Annihilator):
+    """
+    Bosonic annihilation operator.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.secondquant import B
+    >>> from sympy.abc import x
+    >>> B(x)
+    AnnihilateBoson(x)
+    """
+
+    op_symbol = 'b'
+
+    def _dagger_(self):
+        return CreateBoson(self.state)
+
+    def apply_operator(self, state):
+        """
+        Apply state to self if self is not symbolic and state is a FockStateKet, else
+        multiply self by state.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.secondquant import B, BKet
+        >>> from sympy.abc import x, y, n
+        >>> B(x).apply_operator(y)
+        y*AnnihilateBoson(x)
+        >>> B(0).apply_operator(BKet((n,)))
+        sqrt(n)*FockStateBosonKet((n - 1,))
+
+        """
+        if not self.is_symbolic and isinstance(state, FockStateKet):
+            element = self.state
+            amp = sqrt(state[element])
+            return amp*state.down(element)
+        else:
+            return Mul(self, state)
+
+    def __repr__(self):
+        return "AnnihilateBoson(%s)" % self.state
+
+    def _latex(self, printer):
+        if self.state is S.Zero:
+            return "b_{0}"
+        else:
+            return "b_{%s}" % printer._print(self.state)
+
+class CreateBoson(BosonicOperator, Creator):
+    """
+    Bosonic creation operator.
+    """
+
+    op_symbol = 'b+'
+
+    def _dagger_(self):
+        return AnnihilateBoson(self.state)
+
+    def apply_operator(self, state):
+        """
+        Apply state to self if self is not symbolic and state is a FockStateKet, else
+        multiply self by state.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.secondquant import B, Dagger, BKet
+        >>> from sympy.abc import x, y, n
+        >>> Dagger(B(x)).apply_operator(y)
+        y*CreateBoson(x)
+        >>> B(0).apply_operator(BKet((n,)))
+        sqrt(n)*FockStateBosonKet((n - 1,))
+        """
+        if not self.is_symbolic and isinstance(state, FockStateKet):
+            element = self.state
+            amp = sqrt(state[element] + 1)
+            return amp*state.up(element)
+        else:
+            return Mul(self, state)
+
+    def __repr__(self):
+        return "CreateBoson(%s)" % self.state
+
+    def _latex(self, printer):
+        if self.state is S.Zero:
+            return "{b^\\dagger_{0}}"
+        else:
+            return "{b^\\dagger_{%s}}" % printer._print(self.state)
+
+B = AnnihilateBoson
+Bd = CreateBoson
+
+
+class FermionicOperator(SqOperator):
+
+    @property
+    def is_restricted(self):
+        """
+        Is this FermionicOperator restricted with respect to fermi level?
+
+        Returns
+        =======
+
+        1  : restricted to orbits above fermi
+        0  : no restriction
+        -1 : restricted to orbits below fermi
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy.physics.secondquant import F, Fd
+        >>> a = Symbol('a', above_fermi=True)
+        >>> i = Symbol('i', below_fermi=True)
+        >>> p = Symbol('p')
+
+        >>> F(a).is_restricted
+        1
+        >>> Fd(a).is_restricted
+        1
+        >>> F(i).is_restricted
+        -1
+        >>> Fd(i).is_restricted
+        -1
+        >>> F(p).is_restricted
+        0
+        >>> Fd(p).is_restricted
+        0
+
+        """
+        ass = self.args[0].assumptions0
+        if ass.get("below_fermi"):
+            return -1
+        if ass.get("above_fermi"):
+            return 1
+        return 0
+
+    @property
+    def is_above_fermi(self):
+        """
+        Does the index of this FermionicOperator allow values above fermi?
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy.physics.secondquant import F
+        >>> a = Symbol('a', above_fermi=True)
+        >>> i = Symbol('i', below_fermi=True)
+        >>> p = Symbol('p')
+
+        >>> F(a).is_above_fermi
+        True
+        >>> F(i).is_above_fermi
+        False
+        >>> F(p).is_above_fermi
+        True
+
+        Note
+        ====
+
+        The same applies to creation operators Fd
+
+        """
+        return not self.args[0].assumptions0.get("below_fermi")
+
+    @property
+    def is_below_fermi(self):
+        """
+        Does the index of this FermionicOperator allow values below fermi?
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy.physics.secondquant import F
+        >>> a = Symbol('a', above_fermi=True)
+        >>> i = Symbol('i', below_fermi=True)
+        >>> p = Symbol('p')
+
+        >>> F(a).is_below_fermi
+        False
+        >>> F(i).is_below_fermi
+        True
+        >>> F(p).is_below_fermi
+        True
+
+        The same applies to creation operators Fd
+
+        """
+        return not self.args[0].assumptions0.get("above_fermi")
+
+    @property
+    def is_only_below_fermi(self):
+        """
+        Is the index of this FermionicOperator restricted to values below fermi?
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy.physics.secondquant import F
+        >>> a = Symbol('a', above_fermi=True)
+        >>> i = Symbol('i', below_fermi=True)
+        >>> p = Symbol('p')
+
+        >>> F(a).is_only_below_fermi
+        False
+        >>> F(i).is_only_below_fermi
+        True
+        >>> F(p).is_only_below_fermi
+        False
+
+        The same applies to creation operators Fd
+        """
+        return self.is_below_fermi and not self.is_above_fermi
+
+    @property
+    def is_only_above_fermi(self):
+        """
+        Is the index of this FermionicOperator restricted to values above fermi?
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy.physics.secondquant import F
+        >>> a = Symbol('a', above_fermi=True)
+        >>> i = Symbol('i', below_fermi=True)
+        >>> p = Symbol('p')
+
+        >>> F(a).is_only_above_fermi
+        True
+        >>> F(i).is_only_above_fermi
+        False
+        >>> F(p).is_only_above_fermi
+        False
+
+        The same applies to creation operators Fd
+        """
+        return self.is_above_fermi and not self.is_below_fermi
+
+    def _sortkey(self):
+        h = hash(self)
+        label = str(self.args[0])
+
+        if self.is_only_q_creator:
+            return 1, label, h
+        if self.is_only_q_annihilator:
+            return 4, label, h
+        if isinstance(self, Annihilator):
+            return 3, label, h
+        if isinstance(self, Creator):
+            return 2, label, h
+
+
+class AnnihilateFermion(FermionicOperator, Annihilator):
+    """
+    Fermionic annihilation operator.
+    """
+
+    op_symbol = 'f'
+
+    def _dagger_(self):
+        return CreateFermion(self.state)
+
+    def apply_operator(self, state):
+        """
+        Apply state to self if self is not symbolic and state is a FockStateKet, else
+        multiply self by state.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.secondquant import B, Dagger, BKet
+        >>> from sympy.abc import x, y, n
+        >>> Dagger(B(x)).apply_operator(y)
+        y*CreateBoson(x)
+        >>> B(0).apply_operator(BKet((n,)))
+        sqrt(n)*FockStateBosonKet((n - 1,))
+        """
+        if isinstance(state, FockStateFermionKet):
+            element = self.state
+            return state.down(element)
+
+        elif isinstance(state, Mul):
+            c_part, nc_part = state.args_cnc()
+            if isinstance(nc_part[0], FockStateFermionKet):
+                element = self.state
+                return Mul(*(c_part + [nc_part[0].down(element)] + nc_part[1:]))
+            else:
+                return Mul(self, state)
+
+        else:
+            return Mul(self, state)
+
+    @property
+    def is_q_creator(self):
+        """
+        Can we create a quasi-particle?  (create hole or create particle)
+        If so, would that be above or below the fermi surface?
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy.physics.secondquant import F
+        >>> a = Symbol('a', above_fermi=True)
+        >>> i = Symbol('i', below_fermi=True)
+        >>> p = Symbol('p')
+
+        >>> F(a).is_q_creator
+        0
+        >>> F(i).is_q_creator
+        -1
+        >>> F(p).is_q_creator
+        -1
+
+        """
+        if self.is_below_fermi:
+            return -1
+        return 0
+
+    @property
+    def is_q_annihilator(self):
+        """
+        Can we destroy a quasi-particle?  (annihilate hole or annihilate particle)
+        If so, would that be above or below the fermi surface?
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy.physics.secondquant import F
+        >>> a = Symbol('a', above_fermi=1)
+        >>> i = Symbol('i', below_fermi=1)
+        >>> p = Symbol('p')
+
+        >>> F(a).is_q_annihilator
+        1
+        >>> F(i).is_q_annihilator
+        0
+        >>> F(p).is_q_annihilator
+        1
+
+        """
+        if self.is_above_fermi:
+            return 1
+        return 0
+
+    @property
+    def is_only_q_creator(self):
+        """
+        Always create a quasi-particle?  (create hole or create particle)
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy.physics.secondquant import F
+        >>> a = Symbol('a', above_fermi=True)
+        >>> i = Symbol('i', below_fermi=True)
+        >>> p = Symbol('p')
+
+        >>> F(a).is_only_q_creator
+        False
+        >>> F(i).is_only_q_creator
+        True
+        >>> F(p).is_only_q_creator
+        False
+
+        """
+        return self.is_only_below_fermi
+
+    @property
+    def is_only_q_annihilator(self):
+        """
+        Always destroy a quasi-particle?  (annihilate hole or annihilate particle)
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy.physics.secondquant import F
+        >>> a = Symbol('a', above_fermi=True)
+        >>> i = Symbol('i', below_fermi=True)
+        >>> p = Symbol('p')
+
+        >>> F(a).is_only_q_annihilator
+        True
+        >>> F(i).is_only_q_annihilator
+        False
+        >>> F(p).is_only_q_annihilator
+        False
+
+        """
+        return self.is_only_above_fermi
+
+    def __repr__(self):
+        return "AnnihilateFermion(%s)" % self.state
+
+    def _latex(self, printer):
+        if self.state is S.Zero:
+            return "a_{0}"
+        else:
+            return "a_{%s}" % printer._print(self.state)
+
+
+class CreateFermion(FermionicOperator, Creator):
+    """
+    Fermionic creation operator.
+    """
+
+    op_symbol = 'f+'
+
+    def _dagger_(self):
+        return AnnihilateFermion(self.state)
+
+    def apply_operator(self, state):
+        """
+        Apply state to self if self is not symbolic and state is a FockStateKet, else
+        multiply self by state.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.secondquant import B, Dagger, BKet
+        >>> from sympy.abc import x, y, n
+        >>> Dagger(B(x)).apply_operator(y)
+        y*CreateBoson(x)
+        >>> B(0).apply_operator(BKet((n,)))
+        sqrt(n)*FockStateBosonKet((n - 1,))
+        """
+        if isinstance(state, FockStateFermionKet):
+            element = self.state
+            return state.up(element)
+
+        elif isinstance(state, Mul):
+            c_part, nc_part = state.args_cnc()
+            if isinstance(nc_part[0], FockStateFermionKet):
+                element = self.state
+                return Mul(*(c_part + [nc_part[0].up(element)] + nc_part[1:]))
+
+        return Mul(self, state)
+
+    @property
+    def is_q_creator(self):
+        """
+        Can we create a quasi-particle?  (create hole or create particle)
+        If so, would that be above or below the fermi surface?
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy.physics.secondquant import Fd
+        >>> a = Symbol('a', above_fermi=True)
+        >>> i = Symbol('i', below_fermi=True)
+        >>> p = Symbol('p')
+
+        >>> Fd(a).is_q_creator
+        1
+        >>> Fd(i).is_q_creator
+        0
+        >>> Fd(p).is_q_creator
+        1
+
+        """
+        if self.is_above_fermi:
+            return 1
+        return 0
+
+    @property
+    def is_q_annihilator(self):
+        """
+        Can we destroy a quasi-particle?  (annihilate hole or annihilate particle)
+        If so, would that be above or below the fermi surface?
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy.physics.secondquant import Fd
+        >>> a = Symbol('a', above_fermi=1)
+        >>> i = Symbol('i', below_fermi=1)
+        >>> p = Symbol('p')
+
+        >>> Fd(a).is_q_annihilator
+        0
+        >>> Fd(i).is_q_annihilator
+        -1
+        >>> Fd(p).is_q_annihilator
+        -1
+
+        """
+        if self.is_below_fermi:
+            return -1
+        return 0
+
+    @property
+    def is_only_q_creator(self):
+        """
+        Always create a quasi-particle?  (create hole or create particle)
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy.physics.secondquant import Fd
+        >>> a = Symbol('a', above_fermi=True)
+        >>> i = Symbol('i', below_fermi=True)
+        >>> p = Symbol('p')
+
+        >>> Fd(a).is_only_q_creator
+        True
+        >>> Fd(i).is_only_q_creator
+        False
+        >>> Fd(p).is_only_q_creator
+        False
+
+        """
+        return self.is_only_above_fermi
+
+    @property
+    def is_only_q_annihilator(self):
+        """
+        Always destroy a quasi-particle?  (annihilate hole or annihilate particle)
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy.physics.secondquant import Fd
+        >>> a = Symbol('a', above_fermi=True)
+        >>> i = Symbol('i', below_fermi=True)
+        >>> p = Symbol('p')
+
+        >>> Fd(a).is_only_q_annihilator
+        False
+        >>> Fd(i).is_only_q_annihilator
+        True
+        >>> Fd(p).is_only_q_annihilator
+        False
+
+        """
+        return self.is_only_below_fermi
+
+    def __repr__(self):
+        return "CreateFermion(%s)" % self.state
+
+    def _latex(self, printer):
+        if self.state is S.Zero:
+            return "{a^\\dagger_{0}}"
+        else:
+            return "{a^\\dagger_{%s}}" % printer._print(self.state)
+
+Fd = CreateFermion
+F = AnnihilateFermion
+
+
+class FockState(Expr):
+    """
+    Many particle Fock state with a sequence of occupation numbers.
+
+    Anywhere you can have a FockState, you can also have S.Zero.
+    All code must check for this!
+
+    Base class to represent FockStates.
+    """
+    is_commutative = False
+
+    def __new__(cls, occupations):
+        """
+        occupations is a list with two possible meanings:
+
+        - For bosons it is a list of occupation numbers.
+          Element i is the number of particles in state i.
+
+        - For fermions it is a list of occupied orbits.
+          Element 0 is the state that was occupied first, element i
+          is the i'th occupied state.
+        """
+        occupations = list(map(sympify, occupations))
+        obj = Basic.__new__(cls, Tuple(*occupations))
+        return obj
+
+    def __getitem__(self, i):
+        i = int(i)
+        return self.args[0][i]
+
+    def __repr__(self):
+        return ("FockState(%r)") % (self.args)
+
+    def __str__(self):
+        return "%s%r%s" % (getattr(self, 'lbracket', ""), self._labels(), getattr(self, 'rbracket', ""))
+
+    def _labels(self):
+        return self.args[0]
+
+    def __len__(self):
+        return len(self.args[0])
+
+    def _latex(self, printer):
+        return "%s%s%s" % (getattr(self, 'lbracket_latex', ""), printer._print(self._labels()), getattr(self, 'rbracket_latex', ""))
+
+
+class BosonState(FockState):
+    """
+    Base class for FockStateBoson(Ket/Bra).
+    """
+
+    def up(self, i):
+        """
+        Performs the action of a creation operator.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.secondquant import BBra
+        >>> b = BBra([1, 2])
+        >>> b
+        FockStateBosonBra((1, 2))
+        >>> b.up(1)
+        FockStateBosonBra((1, 3))
+        """
+        i = int(i)
+        new_occs = list(self.args[0])
+        new_occs[i] = new_occs[i] + S.One
+        return self.__class__(new_occs)
+
+    def down(self, i):
+        """
+        Performs the action of an annihilation operator.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.secondquant import BBra
+        >>> b = BBra([1, 2])
+        >>> b
+        FockStateBosonBra((1, 2))
+        >>> b.down(1)
+        FockStateBosonBra((1, 1))
+        """
+        i = int(i)
+        new_occs = list(self.args[0])
+        if new_occs[i] == S.Zero:
+            return S.Zero
+        else:
+            new_occs[i] = new_occs[i] - S.One
+            return self.__class__(new_occs)
+
+
+class FermionState(FockState):
+    """
+    Base class for FockStateFermion(Ket/Bra).
+    """
+
+    fermi_level = 0
+
+    def __new__(cls, occupations, fermi_level=0):
+        occupations = list(map(sympify, occupations))
+        if len(occupations) > 1:
+            try:
+                (occupations, sign) = _sort_anticommuting_fermions(
+                    occupations, key=_sqkey_index)
+            except ViolationOfPauliPrinciple:
+                return S.Zero
+        else:
+            sign = 0
+
+        cls.fermi_level = fermi_level
+
+        if cls._count_holes(occupations) > fermi_level:
+            return S.Zero
+
+        if sign % 2:
+            return S.NegativeOne*FockState.__new__(cls, occupations)
+        else:
+            return FockState.__new__(cls, occupations)
+
+    def up(self, i):
+        """
+        Performs the action of a creation operator.
+
+        Explanation
+        ===========
+
+        If below fermi we try to remove a hole,
+        if above fermi we try to create a particle.
+
+        If general index p we return ``Kronecker(p,i)*self``
+        where ``i`` is a new symbol with restriction above or below.
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy.physics.secondquant import FKet
+        >>> a = Symbol('a', above_fermi=True)
+        >>> i = Symbol('i', below_fermi=True)
+        >>> p = Symbol('p')
+
+        >>> FKet([]).up(a)
+        FockStateFermionKet((a,))
+
+        A creator acting on vacuum below fermi vanishes
+
+        >>> FKet([]).up(i)
+        0
+
+
+        """
+        present = i in self.args[0]
+
+        if self._only_above_fermi(i):
+            if present:
+                return S.Zero
+            else:
+                return self._add_orbit(i)
+        elif self._only_below_fermi(i):
+            if present:
+                return self._remove_orbit(i)
+            else:
+                return S.Zero
+        else:
+            if present:
+                hole = Dummy("i", below_fermi=True)
+                return KroneckerDelta(i, hole)*self._remove_orbit(i)
+            else:
+                particle = Dummy("a", above_fermi=True)
+                return KroneckerDelta(i, particle)*self._add_orbit(i)
+
+    def down(self, i):
+        """
+        Performs the action of an annihilation operator.
+
+        Explanation
+        ===========
+
+        If below fermi we try to create a hole,
+        If above fermi we try to remove a particle.
+
+        If general index p we return ``Kronecker(p,i)*self``
+        where ``i`` is a new symbol with restriction above or below.
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy.physics.secondquant import FKet
+        >>> a = Symbol('a', above_fermi=True)
+        >>> i = Symbol('i', below_fermi=True)
+        >>> p = Symbol('p')
+
+        An annihilator acting on vacuum above fermi vanishes
+
+        >>> FKet([]).down(a)
+        0
+
+        Also below fermi, it vanishes, unless we specify a fermi level > 0
+
+        >>> FKet([]).down(i)
+        0
+        >>> FKet([],4).down(i)
+        FockStateFermionKet((i,))
+
+        """
+        present = i in self.args[0]
+
+        if self._only_above_fermi(i):
+            if present:
+                return self._remove_orbit(i)
+            else:
+                return S.Zero
+
+        elif self._only_below_fermi(i):
+            if present:
+                return S.Zero
+            else:
+                return self._add_orbit(i)
+        else:
+            if present:
+                hole = Dummy("i", below_fermi=True)
+                return KroneckerDelta(i, hole)*self._add_orbit(i)
+            else:
+                particle = Dummy("a", above_fermi=True)
+                return KroneckerDelta(i, particle)*self._remove_orbit(i)
+
+    @classmethod
+    def _only_below_fermi(cls, i):
+        """
+        Tests if given orbit is only below fermi surface.
+
+        If nothing can be concluded we return a conservative False.
+        """
+        if i.is_number:
+            return i <= cls.fermi_level
+        if i.assumptions0.get('below_fermi'):
+            return True
+        return False
+
+    @classmethod
+    def _only_above_fermi(cls, i):
+        """
+        Tests if given orbit is only above fermi surface.
+
+        If fermi level has not been set we return True.
+        If nothing can be concluded we return a conservative False.
+        """
+        if i.is_number:
+            return i > cls.fermi_level
+        if i.assumptions0.get('above_fermi'):
+            return True
+        return not cls.fermi_level
+
+    def _remove_orbit(self, i):
+        """
+        Removes particle/fills hole in orbit i. No input tests performed here.
+        """
+        new_occs = list(self.args[0])
+        pos = new_occs.index(i)
+        del new_occs[pos]
+        if (pos) % 2:
+            return S.NegativeOne*self.__class__(new_occs, self.fermi_level)
+        else:
+            return self.__class__(new_occs, self.fermi_level)
+
+    def _add_orbit(self, i):
+        """
+        Adds particle/creates hole in orbit i. No input tests performed here.
+        """
+        return self.__class__((i,) + self.args[0], self.fermi_level)
+
+    @classmethod
+    def _count_holes(cls, occupations):
+        """
+        Returns the number of identified hole states in occupations list.
+        """
+        return len([i for i in occupations if cls._only_below_fermi(i)])
+
+    def _negate_holes(self, occupations):
+        """
+        Returns the occupations list where states below the fermi level have negative labels.
+
+        For symbolic state labels, no sign is included.
+        """
+        return tuple([-i if self._only_below_fermi(i) and i.is_number else i for i in occupations])
+
+    def __repr__(self):
+        if self.fermi_level:
+            return "FockStateKet(%r, fermi_level=%s)" % (self.args[0], self.fermi_level)
+        else:
+            return "FockStateKet(%r)" % (self.args[0],)
+
+    def _labels(self):
+        return self._negate_holes(self.args[0])
+
+
+class FockStateKet(FockState):
+    """
+    Representation of a ket.
+    """
+    lbracket = '|'
+    rbracket = '>'
+    lbracket_latex = r'\left|'
+    rbracket_latex = r'\right\rangle'
+
+
+class FockStateBra(FockState):
+    """
+    Representation of a bra.
+    """
+    lbracket = '<'
+    rbracket = '|'
+    lbracket_latex = r'\left\langle'
+    rbracket_latex = r'\right|'
+
+    def __mul__(self, other):
+        if isinstance(other, FockStateKet):
+            return InnerProduct(self, other)
+        else:
+            return Expr.__mul__(self, other)
+
+
+class FockStateBosonKet(BosonState, FockStateKet):
+    """
+    Many particle Fock state with a sequence of occupation numbers.
+
+    Occupation numbers can be any integer >= 0.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.secondquant import BKet
+    >>> BKet([1, 2])
+    FockStateBosonKet((1, 2))
+    """
+    def _dagger_(self):
+        return FockStateBosonBra(*self.args)
+
+
+class FockStateBosonBra(BosonState, FockStateBra):
+    """
+    Describes a collection of BosonBra particles.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.secondquant import BBra
+    >>> BBra([1, 2])
+    FockStateBosonBra((1, 2))
+    """
+    def _dagger_(self):
+        return FockStateBosonKet(*self.args)
+
+
+class FockStateFermionKet(FermionState, FockStateKet):
+    """
+    Many-particle Fock state with a sequence of occupied orbits.
+
+    Explanation
+    ===========
+
+    Each state can only have one particle, so we choose to store a list of
+    occupied orbits rather than a tuple with occupation numbers (zeros and ones).
+
+    states below fermi level are holes, and are represented by negative labels
+    in the occupation list.
+
+    For symbolic state labels, the fermi_level caps the number of allowed hole-
+    states.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.secondquant import FKet
+    >>> FKet([1, 2])
+    FockStateFermionKet((1, 2))
+    """
+    def _dagger_(self):
+        return FockStateFermionBra(*self.args)
+
+
+class FockStateFermionBra(FermionState, FockStateBra):
+    """
+    See Also
+    ========
+
+    FockStateFermionKet
+
+    Examples
+    ========
+
+    >>> from sympy.physics.secondquant import FBra
+    >>> FBra([1, 2])
+    FockStateFermionBra((1, 2))
+    """
+    def _dagger_(self):
+        return FockStateFermionKet(*self.args)
+
+BBra = FockStateBosonBra
+BKet = FockStateBosonKet
+FBra = FockStateFermionBra
+FKet = FockStateFermionKet
+
+
+def _apply_Mul(m):
+    """
+    Take a Mul instance with operators and apply them to states.
+
+    Explanation
+    ===========
+
+    This method applies all operators with integer state labels
+    to the actual states.  For symbolic state labels, nothing is done.
+    When inner products of FockStates are encountered (like ),
+    they are converted to instances of InnerProduct.
+
+    This does not currently work on double inner products like,
+    .
+
+    If the argument is not a Mul, it is simply returned as is.
+    """
+    if not isinstance(m, Mul):
+        return m
+    c_part, nc_part = m.args_cnc()
+    n_nc = len(nc_part)
+    if n_nc in (0, 1):
+        return m
+    else:
+        last = nc_part[-1]
+        next_to_last = nc_part[-2]
+        if isinstance(last, FockStateKet):
+            if isinstance(next_to_last, SqOperator):
+                if next_to_last.is_symbolic:
+                    return m
+                else:
+                    result = next_to_last.apply_operator(last)
+                    if result == 0:
+                        return S.Zero
+                    else:
+                        return _apply_Mul(Mul(*(c_part + nc_part[:-2] + [result])))
+            elif isinstance(next_to_last, Pow):
+                if isinstance(next_to_last.base, SqOperator) and \
+                        next_to_last.exp.is_Integer:
+                    if next_to_last.base.is_symbolic:
+                        return m
+                    else:
+                        result = last
+                        for i in range(next_to_last.exp):
+                            result = next_to_last.base.apply_operator(result)
+                            if result == 0:
+                                break
+                        if result == 0:
+                            return S.Zero
+                        else:
+                            return _apply_Mul(Mul(*(c_part + nc_part[:-2] + [result])))
+                else:
+                    return m
+            elif isinstance(next_to_last, FockStateBra):
+                result = InnerProduct(next_to_last, last)
+                if result == 0:
+                    return S.Zero
+                else:
+                    return _apply_Mul(Mul(*(c_part + nc_part[:-2] + [result])))
+            else:
+                return m
+        else:
+            return m
+
+
+def apply_operators(e):
+    """
+    Take a SymPy expression with operators and states and apply the operators.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.secondquant import apply_operators
+    >>> from sympy import sympify
+    >>> apply_operators(sympify(3)+4)
+    7
+    """
+    e = e.expand()
+    muls = e.atoms(Mul)
+    subs_list = [(m, _apply_Mul(m)) for m in iter(muls)]
+    return e.subs(subs_list)
+
+
+class InnerProduct(Basic):
+    """
+    An unevaluated inner product between a bra and ket.
+
+    Explanation
+    ===========
+
+    Currently this class just reduces things to a product of
+    Kronecker Deltas.  In the future, we could introduce abstract
+    states like ``|a>`` and ``|b>``, and leave the inner product unevaluated as
+    ````.
+
+    """
+    is_commutative = True
+
+    def __new__(cls, bra, ket):
+        if not isinstance(bra, FockStateBra):
+            raise TypeError("must be a bra")
+        if not isinstance(ket, FockStateKet):
+            raise TypeError("must be a ket")
+        return cls.eval(bra, ket)
+
+    @classmethod
+    def eval(cls, bra, ket):
+        result = S.One
+        for i, j in zip(bra.args[0], ket.args[0]):
+            result *= KroneckerDelta(i, j)
+            if result == 0:
+                break
+        return result
+
+    @property
+    def bra(self):
+        """Returns the bra part of the state"""
+        return self.args[0]
+
+    @property
+    def ket(self):
+        """Returns the ket part of the state"""
+        return self.args[1]
+
+    def __repr__(self):
+        sbra = repr(self.bra)
+        sket = repr(self.ket)
+        return "%s|%s" % (sbra[:-1], sket[1:])
+
+    def __str__(self):
+        return self.__repr__()
+
+
+def matrix_rep(op, basis):
+    """
+    Find the representation of an operator in a basis.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.secondquant import VarBosonicBasis, B, matrix_rep
+    >>> b = VarBosonicBasis(5)
+    >>> o = B(0)
+    >>> matrix_rep(o, b)
+    Matrix([
+    [0, 1,       0,       0, 0],
+    [0, 0, sqrt(2),       0, 0],
+    [0, 0,       0, sqrt(3), 0],
+    [0, 0,       0,       0, 2],
+    [0, 0,       0,       0, 0]])
+    """
+    a = zeros(len(basis))
+    for i in range(len(basis)):
+        for j in range(len(basis)):
+            a[i, j] = apply_operators(Dagger(basis[i])*op*basis[j])
+    return a
+
+
+class BosonicBasis:
+    """
+    Base class for a basis set of bosonic Fock states.
+    """
+    pass
+
+
+class VarBosonicBasis:
+    """
+    A single state, variable particle number basis set.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.secondquant import VarBosonicBasis
+    >>> b = VarBosonicBasis(5)
+    >>> b
+    [FockState((0,)), FockState((1,)), FockState((2,)),
+     FockState((3,)), FockState((4,))]
+    """
+
+    def __init__(self, n_max):
+        self.n_max = n_max
+        self._build_states()
+
+    def _build_states(self):
+        self.basis = []
+        for i in range(self.n_max):
+            self.basis.append(FockStateBosonKet([i]))
+        self.n_basis = len(self.basis)
+
+    def index(self, state):
+        """
+        Returns the index of state in basis.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.secondquant import VarBosonicBasis
+        >>> b = VarBosonicBasis(3)
+        >>> state = b.state(1)
+        >>> b
+        [FockState((0,)), FockState((1,)), FockState((2,))]
+        >>> state
+        FockStateBosonKet((1,))
+        >>> b.index(state)
+        1
+        """
+        return self.basis.index(state)
+
+    def state(self, i):
+        """
+        The state of a single basis.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.secondquant import VarBosonicBasis
+        >>> b = VarBosonicBasis(5)
+        >>> b.state(3)
+        FockStateBosonKet((3,))
+        """
+        return self.basis[i]
+
+    def __getitem__(self, i):
+        return self.state(i)
+
+    def __len__(self):
+        return len(self.basis)
+
+    def __repr__(self):
+        return repr(self.basis)
+
+
+class FixedBosonicBasis(BosonicBasis):
+    """
+    Fixed particle number basis set.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.secondquant import FixedBosonicBasis
+    >>> b = FixedBosonicBasis(2, 2)
+    >>> state = b.state(1)
+    >>> b
+    [FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]
+    >>> state
+    FockStateBosonKet((1, 1))
+    >>> b.index(state)
+    1
+    """
+    def __init__(self, n_particles, n_levels):
+        self.n_particles = n_particles
+        self.n_levels = n_levels
+        self._build_particle_locations()
+        self._build_states()
+
+    def _build_particle_locations(self):
+        tup = ["i%i" % i for i in range(self.n_particles)]
+        first_loop = "for i0 in range(%i)" % self.n_levels
+        other_loops = ''
+        for cur, prev in zip(tup[1:], tup):
+            temp = "for %s in range(%s + 1) " % (cur, prev)
+            other_loops = other_loops + temp
+        tup_string = "(%s)" % ", ".join(tup)
+        list_comp = "[%s %s %s]" % (tup_string, first_loop, other_loops)
+        result = eval(list_comp)
+        if self.n_particles == 1:
+            result = [(item,) for item in result]
+        self.particle_locations = result
+
+    def _build_states(self):
+        self.basis = []
+        for tuple_of_indices in self.particle_locations:
+            occ_numbers = self.n_levels*[0]
+            for level in tuple_of_indices:
+                occ_numbers[level] += 1
+            self.basis.append(FockStateBosonKet(occ_numbers))
+        self.n_basis = len(self.basis)
+
+    def index(self, state):
+        """Returns the index of state in basis.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.secondquant import FixedBosonicBasis
+        >>> b = FixedBosonicBasis(2, 3)
+        >>> b.index(b.state(3))
+        3
+        """
+        return self.basis.index(state)
+
+    def state(self, i):
+        """Returns the state that lies at index i of the basis
+
+        Examples
+        ========
+
+        >>> from sympy.physics.secondquant import FixedBosonicBasis
+        >>> b = FixedBosonicBasis(2, 3)
+        >>> b.state(3)
+        FockStateBosonKet((1, 0, 1))
+        """
+        return self.basis[i]
+
+    def __getitem__(self, i):
+        return self.state(i)
+
+    def __len__(self):
+        return len(self.basis)
+
+    def __repr__(self):
+        return repr(self.basis)
+
+
+class Commutator(Function):
+    """
+    The Commutator:  [A, B] = A*B - B*A
+
+    The arguments are ordered according to .__cmp__()
+
+    Examples
+    ========
+
+    >>> from sympy import symbols
+    >>> from sympy.physics.secondquant import Commutator
+    >>> A, B = symbols('A,B', commutative=False)
+    >>> Commutator(B, A)
+    -Commutator(A, B)
+
+    Evaluate the commutator with .doit()
+
+    >>> comm = Commutator(A,B); comm
+    Commutator(A, B)
+    >>> comm.doit()
+    A*B - B*A
+
+
+    For two second quantization operators the commutator is evaluated
+    immediately:
+
+    >>> from sympy.physics.secondquant import Fd, F
+    >>> a = symbols('a', above_fermi=True)
+    >>> i = symbols('i', below_fermi=True)
+    >>> p,q = symbols('p,q')
+
+    >>> Commutator(Fd(a),Fd(i))
+    2*NO(CreateFermion(a)*CreateFermion(i))
+
+    But for more complicated expressions, the evaluation is triggered by
+    a call to .doit()
+
+    >>> comm = Commutator(Fd(p)*Fd(q),F(i)); comm
+    Commutator(CreateFermion(p)*CreateFermion(q), AnnihilateFermion(i))
+    >>> comm.doit(wicks=True)
+    -KroneckerDelta(i, p)*CreateFermion(q) +
+     KroneckerDelta(i, q)*CreateFermion(p)
+
+    """
+
+    is_commutative = False
+
+    @classmethod
+    def eval(cls, a, b):
+        """
+        The Commutator [A,B] is on canonical form if A < B.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.secondquant import Commutator, F, Fd
+        >>> from sympy.abc import x
+        >>> c1 = Commutator(F(x), Fd(x))
+        >>> c2 = Commutator(Fd(x), F(x))
+        >>> Commutator.eval(c1, c2)
+        0
+        """
+        if not (a and b):
+            return S.Zero
+        if a == b:
+            return S.Zero
+        if a.is_commutative or b.is_commutative:
+            return S.Zero
+
+        #
+        # [A+B,C]  ->  [A,C] + [B,C]
+        #
+        a = a.expand()
+        if isinstance(a, Add):
+            return Add(*[cls(term, b) for term in a.args])
+        b = b.expand()
+        if isinstance(b, Add):
+            return Add(*[cls(a, term) for term in b.args])
+
+        #
+        # [xA,yB]  ->  xy*[A,B]
+        #
+        ca, nca = a.args_cnc()
+        cb, ncb = b.args_cnc()
+        c_part = list(ca) + list(cb)
+        if c_part:
+            return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb)))
+
+        #
+        # single second quantization operators
+        #
+        if isinstance(a, BosonicOperator) and isinstance(b, BosonicOperator):
+            if isinstance(b, CreateBoson) and isinstance(a, AnnihilateBoson):
+                return KroneckerDelta(a.state, b.state)
+            if isinstance(a, CreateBoson) and isinstance(b, AnnihilateBoson):
+                return S.NegativeOne*KroneckerDelta(a.state, b.state)
+            else:
+                return S.Zero
+        if isinstance(a, FermionicOperator) and isinstance(b, FermionicOperator):
+            return wicks(a*b) - wicks(b*a)
+
+        #
+        # Canonical ordering of arguments
+        #
+        if a.sort_key() > b.sort_key():
+            return S.NegativeOne*cls(b, a)
+
+    def doit(self, **hints):
+        """
+        Enables the computation of complex expressions.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.secondquant import Commutator, F, Fd
+        >>> from sympy import symbols
+        >>> i, j = symbols('i,j', below_fermi=True)
+        >>> a, b = symbols('a,b', above_fermi=True)
+        >>> c = Commutator(Fd(a)*F(i),Fd(b)*F(j))
+        >>> c.doit(wicks=True)
+        0
+        """
+        a = self.args[0]
+        b = self.args[1]
+
+        if hints.get("wicks"):
+            a = a.doit(**hints)
+            b = b.doit(**hints)
+            try:
+                return wicks(a*b) - wicks(b*a)
+            except ContractionAppliesOnlyToFermions:
+                pass
+            except WicksTheoremDoesNotApply:
+                pass
+
+        return (a*b - b*a).doit(**hints)
+
+    def __repr__(self):
+        return "Commutator(%s,%s)" % (self.args[0], self.args[1])
+
+    def __str__(self):
+        return "[%s,%s]" % (self.args[0], self.args[1])
+
+    def _latex(self, printer):
+        return "\\left[%s,%s\\right]" % tuple([
+            printer._print(arg) for arg in self.args])
+
+
+class NO(Expr):
+    """
+    This Object is used to represent normal ordering brackets.
+
+    i.e.  {abcd}  sometimes written  :abcd:
+
+    Explanation
+    ===========
+
+    Applying the function NO(arg) to an argument means that all operators in
+    the argument will be assumed to anticommute, and have vanishing
+    contractions.  This allows an immediate reordering to canonical form
+    upon object creation.
+
+    Examples
+    ========
+
+    >>> from sympy import symbols
+    >>> from sympy.physics.secondquant import NO, F, Fd
+    >>> p,q = symbols('p,q')
+    >>> NO(Fd(p)*F(q))
+    NO(CreateFermion(p)*AnnihilateFermion(q))
+    >>> NO(F(q)*Fd(p))
+    -NO(CreateFermion(p)*AnnihilateFermion(q))
+
+
+    Note
+    ====
+
+    If you want to generate a normal ordered equivalent of an expression, you
+    should use the function wicks().  This class only indicates that all
+    operators inside the brackets anticommute, and have vanishing contractions.
+    Nothing more, nothing less.
+
+    """
+    is_commutative = False
+
+    def __new__(cls, arg):
+        """
+        Use anticommutation to get canonical form of operators.
+
+        Explanation
+        ===========
+
+        Employ associativity of normal ordered product: {ab{cd}} = {abcd}
+        but note that {ab}{cd} /= {abcd}.
+
+        We also employ distributivity: {ab + cd} = {ab} + {cd}.
+
+        Canonical form also implies expand() {ab(c+d)} = {abc} + {abd}.
+
+        """
+
+        # {ab + cd} = {ab} + {cd}
+        arg = sympify(arg)
+        arg = arg.expand()
+        if arg.is_Add:
+            return Add(*[ cls(term) for term in arg.args])
+
+        if arg.is_Mul:
+
+            # take coefficient outside of normal ordering brackets
+            c_part, seq = arg.args_cnc()
+            if c_part:
+                coeff = Mul(*c_part)
+                if not seq:
+                    return coeff
+            else:
+                coeff = S.One
+
+            # {ab{cd}} = {abcd}
+            newseq = []
+            foundit = False
+            for fac in seq:
+                if isinstance(fac, NO):
+                    newseq.extend(fac.args)
+                    foundit = True
+                else:
+                    newseq.append(fac)
+            if foundit:
+                return coeff*cls(Mul(*newseq))
+
+            # We assume that the user don't mix B and F operators
+            if isinstance(seq[0], BosonicOperator):
+                raise NotImplementedError
+
+            try:
+                newseq, sign = _sort_anticommuting_fermions(seq)
+            except ViolationOfPauliPrinciple:
+                return S.Zero
+
+            if sign % 2:
+                return (S.NegativeOne*coeff)*cls(Mul(*newseq))
+            elif sign:
+                return coeff*cls(Mul(*newseq))
+            else:
+                pass  # since sign==0, no permutations was necessary
+
+            # if we couldn't do anything with Mul object, we just
+            # mark it as normal ordered
+            if coeff != S.One:
+                return coeff*cls(Mul(*newseq))
+            return Expr.__new__(cls, Mul(*newseq))
+
+        if isinstance(arg, NO):
+            return arg
+
+        # if object was not Mul or Add, normal ordering does not apply
+        return arg
+
+    @property
+    def has_q_creators(self):
+        """
+        Return 0 if the leftmost argument of the first argument is a not a
+        q_creator, else 1 if it is above fermi or -1 if it is below fermi.
+
+        Examples
+        ========
+
+        >>> from sympy import symbols
+        >>> from sympy.physics.secondquant import NO, F, Fd
+
+        >>> a = symbols('a', above_fermi=True)
+        >>> i = symbols('i', below_fermi=True)
+        >>> NO(Fd(a)*Fd(i)).has_q_creators
+        1
+        >>> NO(F(i)*F(a)).has_q_creators
+        -1
+        >>> NO(Fd(i)*F(a)).has_q_creators           #doctest: +SKIP
+        0
+
+        """
+        return self.args[0].args[0].is_q_creator
+
+    @property
+    def has_q_annihilators(self):
+        """
+        Return 0 if the rightmost argument of the first argument is a not a
+        q_annihilator, else 1 if it is above fermi or -1 if it is below fermi.
+
+        Examples
+        ========
+
+        >>> from sympy import symbols
+        >>> from sympy.physics.secondquant import NO, F, Fd
+
+        >>> a = symbols('a', above_fermi=True)
+        >>> i = symbols('i', below_fermi=True)
+        >>> NO(Fd(a)*Fd(i)).has_q_annihilators
+        -1
+        >>> NO(F(i)*F(a)).has_q_annihilators
+        1
+        >>> NO(Fd(a)*F(i)).has_q_annihilators
+        0
+
+        """
+        return self.args[0].args[-1].is_q_annihilator
+
+    def doit(self, **hints):
+        """
+        Either removes the brackets or enables complex computations
+        in its arguments.
+
+        Examples
+        ========
+
+        >>> from sympy.physics.secondquant import NO, Fd, F
+        >>> from textwrap import fill
+        >>> from sympy import symbols, Dummy
+        >>> p,q = symbols('p,q', cls=Dummy)
+        >>> print(fill(str(NO(Fd(p)*F(q)).doit())))
+        KroneckerDelta(_a, _p)*KroneckerDelta(_a,
+        _q)*CreateFermion(_a)*AnnihilateFermion(_a) + KroneckerDelta(_a,
+        _p)*KroneckerDelta(_i, _q)*CreateFermion(_a)*AnnihilateFermion(_i) -
+        KroneckerDelta(_a, _q)*KroneckerDelta(_i,
+        _p)*AnnihilateFermion(_a)*CreateFermion(_i) - KroneckerDelta(_i,
+        _p)*KroneckerDelta(_i, _q)*AnnihilateFermion(_i)*CreateFermion(_i)
+        """
+        if hints.get("remove_brackets", True):
+            return self._remove_brackets()
+        else:
+            return self.__new__(type(self), self.args[0].doit(**hints))
+
+    def _remove_brackets(self):
+        """
+        Returns the sorted string without normal order brackets.
+
+        The returned string have the property that no nonzero
+        contractions exist.
+        """
+
+        # check if any creator is also an annihilator
+        subslist = []
+        for i in self.iter_q_creators():
+            if self[i].is_q_annihilator:
+                assume = self[i].state.assumptions0
+
+                # only operators with a dummy index can be split in two terms
+                if isinstance(self[i].state, Dummy):
+
+                    # create indices with fermi restriction
+                    assume.pop("above_fermi", None)
+                    assume["below_fermi"] = True
+                    below = Dummy('i', **assume)
+                    assume.pop("below_fermi", None)
+                    assume["above_fermi"] = True
+                    above = Dummy('a', **assume)
+
+                    cls = type(self[i])
+                    split = (
+                        self[i].__new__(cls, below)
+                        * KroneckerDelta(below, self[i].state)
+                        + self[i].__new__(cls, above)
+                        * KroneckerDelta(above, self[i].state)
+                    )
+                    subslist.append((self[i], split))
+                else:
+                    raise SubstitutionOfAmbigousOperatorFailed(self[i])
+        if subslist:
+            result = NO(self.subs(subslist))
+            if isinstance(result, Add):
+                return Add(*[term.doit() for term in result.args])
+        else:
+            return self.args[0]
+
+    def _expand_operators(self):
+        """
+        Returns a sum of NO objects that contain no ambiguous q-operators.
+
+        Explanation
+        ===========
+
+        If an index q has range both above and below fermi, the operator F(q)
+        is ambiguous in the sense that it can be both a q-creator and a q-annihilator.
+        If q is dummy, it is assumed to be a summation variable and this method
+        rewrites it into a sum of NO terms with unambiguous operators:
+
+        {Fd(p)*F(q)} = {Fd(a)*F(b)} + {Fd(a)*F(i)} + {Fd(j)*F(b)} -{F(i)*Fd(j)}
+
+        where a,b are above and i,j are below fermi level.
+        """
+        return NO(self._remove_brackets)
+
+    def __getitem__(self, i):
+        if isinstance(i, slice):
+            indices = i.indices(len(self))
+            return [self.args[0].args[i] for i in range(*indices)]
+        else:
+            return self.args[0].args[i]
+
+    def __len__(self):
+        return len(self.args[0].args)
+
+    def iter_q_annihilators(self):
+        """
+        Iterates over the annihilation operators.
+
+        Examples
+        ========
+
+        >>> from sympy import symbols
+        >>> i, j = symbols('i j', below_fermi=True)
+        >>> a, b = symbols('a b', above_fermi=True)
+        >>> from sympy.physics.secondquant import NO, F, Fd
+        >>> no = NO(Fd(a)*F(i)*F(b)*Fd(j))
+
+        >>> no.iter_q_creators()
+        
+        >>> list(no.iter_q_creators())
+        [0, 1]
+        >>> list(no.iter_q_annihilators())
+        [3, 2]
+
+        """
+        ops = self.args[0].args
+        iter = range(len(ops) - 1, -1, -1)
+        for i in iter:
+            if ops[i].is_q_annihilator:
+                yield i
+            else:
+                break
+
+    def iter_q_creators(self):
+        """
+        Iterates over the creation operators.
+
+        Examples
+        ========
+
+        >>> from sympy import symbols
+        >>> i, j = symbols('i j', below_fermi=True)
+        >>> a, b = symbols('a b', above_fermi=True)
+        >>> from sympy.physics.secondquant import NO, F, Fd
+        >>> no = NO(Fd(a)*F(i)*F(b)*Fd(j))
+
+        >>> no.iter_q_creators()
+        
+        >>> list(no.iter_q_creators())
+        [0, 1]
+        >>> list(no.iter_q_annihilators())
+        [3, 2]
+
+        """
+
+        ops = self.args[0].args
+        iter = range(0, len(ops))
+        for i in iter:
+            if ops[i].is_q_creator:
+                yield i
+            else:
+                break
+
+    def get_subNO(self, i):
+        """
+        Returns a NO() without FermionicOperator at index i.
+
+        Examples
+        ========
+
+        >>> from sympy import symbols
+        >>> from sympy.physics.secondquant import F, NO
+        >>> p, q, r = symbols('p,q,r')
+
+        >>> NO(F(p)*F(q)*F(r)).get_subNO(1)
+        NO(AnnihilateFermion(p)*AnnihilateFermion(r))
+
+        """
+        arg0 = self.args[0]  # it's a Mul by definition of how it's created
+        mul = arg0._new_rawargs(*(arg0.args[:i] + arg0.args[i + 1:]))
+        return NO(mul)
+
+    def _latex(self, printer):
+        return "\\left\\{%s\\right\\}" % printer._print(self.args[0])
+
+    def __repr__(self):
+        return "NO(%s)" % self.args[0]
+
+    def __str__(self):
+        return ":%s:" % self.args[0]
+
+
+def contraction(a, b):
+    """
+    Calculates contraction of Fermionic operators a and b.
+
+    Examples
+    ========
+
+    >>> from sympy import symbols
+    >>> from sympy.physics.secondquant import F, Fd, contraction
+    >>> p, q = symbols('p,q')
+    >>> a, b = symbols('a,b', above_fermi=True)
+    >>> i, j = symbols('i,j', below_fermi=True)
+
+    A contraction is non-zero only if a quasi-creator is to the right of a
+    quasi-annihilator:
+
+    >>> contraction(F(a),Fd(b))
+    KroneckerDelta(a, b)
+    >>> contraction(Fd(i),F(j))
+    KroneckerDelta(i, j)
+
+    For general indices a non-zero result restricts the indices to below/above
+    the fermi surface:
+
+    >>> contraction(Fd(p),F(q))
+    KroneckerDelta(_i, q)*KroneckerDelta(p, q)
+    >>> contraction(F(p),Fd(q))
+    KroneckerDelta(_a, q)*KroneckerDelta(p, q)
+
+    Two creators or two annihilators always vanishes:
+
+    >>> contraction(F(p),F(q))
+    0
+    >>> contraction(Fd(p),Fd(q))
+    0
+
+    """
+    if isinstance(b, FermionicOperator) and isinstance(a, FermionicOperator):
+        if isinstance(a, AnnihilateFermion) and isinstance(b, CreateFermion):
+            if b.state.assumptions0.get("below_fermi"):
+                return S.Zero
+            if a.state.assumptions0.get("below_fermi"):
+                return S.Zero
+            if b.state.assumptions0.get("above_fermi"):
+                return KroneckerDelta(a.state, b.state)
+            if a.state.assumptions0.get("above_fermi"):
+                return KroneckerDelta(a.state, b.state)
+
+            return (KroneckerDelta(a.state, b.state)*
+                    KroneckerDelta(b.state, Dummy('a', above_fermi=True)))
+        if isinstance(b, AnnihilateFermion) and isinstance(a, CreateFermion):
+            if b.state.assumptions0.get("above_fermi"):
+                return S.Zero
+            if a.state.assumptions0.get("above_fermi"):
+                return S.Zero
+            if b.state.assumptions0.get("below_fermi"):
+                return KroneckerDelta(a.state, b.state)
+            if a.state.assumptions0.get("below_fermi"):
+                return KroneckerDelta(a.state, b.state)
+
+            return (KroneckerDelta(a.state, b.state)*
+                    KroneckerDelta(b.state, Dummy('i', below_fermi=True)))
+
+        # vanish if 2xAnnihilator or 2xCreator
+        return S.Zero
+
+    else:
+        #not fermion operators
+        t = ( isinstance(i, FermionicOperator) for i in (a, b) )
+        raise ContractionAppliesOnlyToFermions(*t)
+
+
+def _sqkey_operator(sq_operator):
+    """Generates key for canonical sorting of SQ operators."""
+    return sq_operator._sortkey()
+
+def _sqkey_index(index):
+    """Key for sorting of indices.
+
+    particle < hole < general
+
+    FIXME: This is a bottle-neck, can we do it faster?
+    """
+    h = hash(index)
+    label = str(index)
+    if isinstance(index, Dummy):
+        if index.assumptions0.get('above_fermi'):
+            return (20, label, h)
+        elif index.assumptions0.get('below_fermi'):
+            return (21, label, h)
+        else:
+            return (22, label, h)
+
+    if index.assumptions0.get('above_fermi'):
+        return (10, label, h)
+    elif index.assumptions0.get('below_fermi'):
+        return (11, label, h)
+    else:
+        return (12, label, h)
+
+
+
+def _sort_anticommuting_fermions(string1, key=_sqkey_operator):
+    """Sort fermionic operators to canonical order, assuming all pairs anticommute.
+
+    Explanation
+    ===========
+
+    Uses a bidirectional bubble sort.  Items in string1 are not referenced
+    so in principle they may be any comparable objects.   The sorting depends on the
+    operators '>' and '=='.
+
+    If the Pauli principle is violated, an exception is raised.
+
+    Returns
+    =======
+
+    tuple (sorted_str, sign)
+
+    sorted_str: list containing the sorted operators
+    sign: int telling how many times the sign should be changed
+          (if sign==0 the string was already sorted)
+    """
+
+    verified = False
+    sign = 0
+    rng = list(range(len(string1) - 1))
+    rev = list(range(len(string1) - 3, -1, -1))
+
+    keys = list(map(key, string1))
+    key_val = dict(list(zip(keys, string1)))
+
+    while not verified:
+        verified = True
+        for i in rng:
+            left = keys[i]
+            right = keys[i + 1]
+            if left == right:
+                raise ViolationOfPauliPrinciple([left, right])
+            if left > right:
+                verified = False
+                keys[i:i + 2] = [right, left]
+                sign = sign + 1
+        if verified:
+            break
+        for i in rev:
+            left = keys[i]
+            right = keys[i + 1]
+            if left == right:
+                raise ViolationOfPauliPrinciple([left, right])
+            if left > right:
+                verified = False
+                keys[i:i + 2] = [right, left]
+                sign = sign + 1
+    string1 = [ key_val[k] for k in keys ]
+    return (string1, sign)
+
+
+def evaluate_deltas(e):
+    """
+    We evaluate KroneckerDelta symbols in the expression assuming Einstein summation.
+
+    Explanation
+    ===========
+
+    If one index is repeated it is summed over and in effect substituted with
+    the other one. If both indices are repeated we substitute according to what
+    is the preferred index.  this is determined by
+    KroneckerDelta.preferred_index and KroneckerDelta.killable_index.
+
+    In case there are no possible substitutions or if a substitution would
+    imply a loss of information, nothing is done.
+
+    In case an index appears in more than one KroneckerDelta, the resulting
+    substitution depends on the order of the factors.  Since the ordering is platform
+    dependent, the literal expression resulting from this function may be hard to
+    predict.
+
+    Examples
+    ========
+
+    We assume the following:
+
+    >>> from sympy import symbols, Function, Dummy, KroneckerDelta
+    >>> from sympy.physics.secondquant import evaluate_deltas
+    >>> i,j = symbols('i j', below_fermi=True, cls=Dummy)
+    >>> a,b = symbols('a b', above_fermi=True, cls=Dummy)
+    >>> p,q = symbols('p q', cls=Dummy)
+    >>> f = Function('f')
+    >>> t = Function('t')
+
+    The order of preference for these indices according to KroneckerDelta is
+    (a, b, i, j, p, q).
+
+    Trivial cases:
+
+    >>> evaluate_deltas(KroneckerDelta(i,j)*f(i))       # d_ij f(i) -> f(j)
+    f(_j)
+    >>> evaluate_deltas(KroneckerDelta(i,j)*f(j))       # d_ij f(j) -> f(i)
+    f(_i)
+    >>> evaluate_deltas(KroneckerDelta(i,p)*f(p))       # d_ip f(p) -> f(i)
+    f(_i)
+    >>> evaluate_deltas(KroneckerDelta(q,p)*f(p))       # d_qp f(p) -> f(q)
+    f(_q)
+    >>> evaluate_deltas(KroneckerDelta(q,p)*f(q))       # d_qp f(q) -> f(p)
+    f(_p)
+
+    More interesting cases:
+
+    >>> evaluate_deltas(KroneckerDelta(i,p)*t(a,i)*f(p,q))
+    f(_i, _q)*t(_a, _i)
+    >>> evaluate_deltas(KroneckerDelta(a,p)*t(a,i)*f(p,q))
+    f(_a, _q)*t(_a, _i)
+    >>> evaluate_deltas(KroneckerDelta(p,q)*f(p,q))
+    f(_p, _p)
+
+    Finally, here are some cases where nothing is done, because that would
+    imply a loss of information:
+
+    >>> evaluate_deltas(KroneckerDelta(i,p)*f(q))
+    f(_q)*KroneckerDelta(_i, _p)
+    >>> evaluate_deltas(KroneckerDelta(i,p)*f(i))
+    f(_i)*KroneckerDelta(_i, _p)
+    """
+
+    # We treat Deltas only in mul objects
+    # for general function objects we don't evaluate KroneckerDeltas in arguments,
+    # but here we hard code exceptions to this rule
+    accepted_functions = (
+        Add,
+    )
+    if isinstance(e, accepted_functions):
+        return e.func(*[evaluate_deltas(arg) for arg in e.args])
+
+    elif isinstance(e, Mul):
+        # find all occurrences of delta function and count each index present in
+        # expression.
+        deltas = []
+        indices = {}
+        for i in e.args:
+            for s in i.free_symbols:
+                if s in indices:
+                    indices[s] += 1
+                else:
+                    indices[s] = 0  # geek counting simplifies logic below
+            if isinstance(i, KroneckerDelta):
+                deltas.append(i)
+
+        for d in deltas:
+            # If we do something, and there are more deltas, we should recurse
+            # to treat the resulting expression properly
+            if d.killable_index.is_Symbol and indices[d.killable_index]:
+                e = e.subs(d.killable_index, d.preferred_index)
+                if len(deltas) > 1:
+                    return evaluate_deltas(e)
+            elif (d.preferred_index.is_Symbol and indices[d.preferred_index]
+                  and d.indices_contain_equal_information):
+                e = e.subs(d.preferred_index, d.killable_index)
+                if len(deltas) > 1:
+                    return evaluate_deltas(e)
+            else:
+                pass
+
+        return e
+    # nothing to do, maybe we hit a Symbol or a number
+    else:
+        return e
+
+
+def substitute_dummies(expr, new_indices=False, pretty_indices={}):
+    """
+    Collect terms by substitution of dummy variables.
+
+    Explanation
+    ===========
+
+    This routine allows simplification of Add expressions containing terms
+    which differ only due to dummy variables.
+
+    The idea is to substitute all dummy variables consistently depending on
+    the structure of the term.  For each term, we obtain a sequence of all
+    dummy variables, where the order is determined by the index range, what
+    factors the index belongs to and its position in each factor.  See
+    _get_ordered_dummies() for more information about the sorting of dummies.
+    The index sequence is then substituted consistently in each term.
+
+    Examples
+    ========
+
+    >>> from sympy import symbols, Function, Dummy
+    >>> from sympy.physics.secondquant import substitute_dummies
+    >>> a,b,c,d = symbols('a b c d', above_fermi=True, cls=Dummy)
+    >>> i,j = symbols('i j', below_fermi=True, cls=Dummy)
+    >>> f = Function('f')
+
+    >>> expr = f(a,b) + f(c,d); expr
+    f(_a, _b) + f(_c, _d)
+
+    Since a, b, c and d are equivalent summation indices, the expression can be
+    simplified to a single term (for which the dummy indices are still summed over)
+
+    >>> substitute_dummies(expr)
+    2*f(_a, _b)
+
+
+    Controlling output:
+
+    By default the dummy symbols that are already present in the expression
+    will be reused in a different permutation.  However, if new_indices=True,
+    new dummies will be generated and inserted.  The keyword 'pretty_indices'
+    can be used to control this generation of new symbols.
+
+    By default the new dummies will be generated on the form i_1, i_2, a_1,
+    etc.  If you supply a dictionary with key:value pairs in the form:
+
+        { index_group: string_of_letters }
+
+    The letters will be used as labels for the new dummy symbols.  The
+    index_groups must be one of 'above', 'below' or 'general'.
+
+    >>> expr = f(a,b,i,j)
+    >>> my_dummies = { 'above':'st', 'below':'uv' }
+    >>> substitute_dummies(expr, new_indices=True, pretty_indices=my_dummies)
+    f(_s, _t, _u, _v)
+
+    If we run out of letters, or if there is no keyword for some index_group
+    the default dummy generator will be used as a fallback:
+
+    >>> p,q = symbols('p q', cls=Dummy)  # general indices
+    >>> expr = f(p,q)
+    >>> substitute_dummies(expr, new_indices=True, pretty_indices=my_dummies)
+    f(_p_0, _p_1)
+
+    """
+
+    # setup the replacing dummies
+    if new_indices:
+        letters_above = pretty_indices.get('above', "")
+        letters_below = pretty_indices.get('below', "")
+        letters_general = pretty_indices.get('general', "")
+        len_above = len(letters_above)
+        len_below = len(letters_below)
+        len_general = len(letters_general)
+
+        def _i(number):
+            try:
+                return letters_below[number]
+            except IndexError:
+                return 'i_' + str(number - len_below)
+
+        def _a(number):
+            try:
+                return letters_above[number]
+            except IndexError:
+                return 'a_' + str(number - len_above)
+
+        def _p(number):
+            try:
+                return letters_general[number]
+            except IndexError:
+                return 'p_' + str(number - len_general)
+
+    aboves = []
+    belows = []
+    generals = []
+
+    dummies = expr.atoms(Dummy)
+    if not new_indices:
+        dummies = sorted(dummies, key=default_sort_key)
+
+    # generate lists with the dummies we will insert
+    a = i = p = 0
+    for d in dummies:
+        assum = d.assumptions0
+
+        if assum.get("above_fermi"):
+            if new_indices:
+                sym = _a(a)
+                a += 1
+            l1 = aboves
+        elif assum.get("below_fermi"):
+            if new_indices:
+                sym = _i(i)
+                i += 1
+            l1 = belows
+        else:
+            if new_indices:
+                sym = _p(p)
+                p += 1
+            l1 = generals
+
+        if new_indices:
+            l1.append(Dummy(sym, **assum))
+        else:
+            l1.append(d)
+
+    expr = expr.expand()
+    terms = Add.make_args(expr)
+    new_terms = []
+    for term in terms:
+        i = iter(belows)
+        a = iter(aboves)
+        p = iter(generals)
+        ordered = _get_ordered_dummies(term)
+        subsdict = {}
+        for d in ordered:
+            if d.assumptions0.get('below_fermi'):
+                subsdict[d] = next(i)
+            elif d.assumptions0.get('above_fermi'):
+                subsdict[d] = next(a)
+            else:
+                subsdict[d] = next(p)
+        subslist = []
+        final_subs = []
+        for k, v in subsdict.items():
+            if k == v:
+                continue
+            if v in subsdict:
+                # We check if the sequence of substitutions end quickly.  In
+                # that case, we can avoid temporary symbols if we ensure the
+                # correct substitution order.
+                if subsdict[v] in subsdict:
+                    # (x, y) -> (y, x),  we need a temporary variable
+                    x = Dummy('x')
+                    subslist.append((k, x))
+                    final_subs.append((x, v))
+                else:
+                    # (x, y) -> (y, a),  x->y must be done last
+                    # but before temporary variables are resolved
+                    final_subs.insert(0, (k, v))
+            else:
+                subslist.append((k, v))
+        subslist.extend(final_subs)
+        new_terms.append(term.subs(subslist))
+    return Add(*new_terms)
+
+
+class KeyPrinter(StrPrinter):
+    """Printer for which only equal objects are equal in print"""
+    def _print_Dummy(self, expr):
+        return "(%s_%i)" % (expr.name, expr.dummy_index)
+
+
+def __kprint(expr):
+    p = KeyPrinter()
+    return p.doprint(expr)
+
+
+def _get_ordered_dummies(mul, verbose=False):
+    """Returns all dummies in the mul sorted in canonical order.
+
+    Explanation
+    ===========
+
+    The purpose of the canonical ordering is that dummies can be substituted
+    consistently across terms with the result that equivalent terms can be
+    simplified.
+
+    It is not possible to determine if two terms are equivalent based solely on
+    the dummy order.  However, a consistent substitution guided by the ordered
+    dummies should lead to trivially (non-)equivalent terms, thereby revealing
+    the equivalence.  This also means that if two terms have identical sequences of
+    dummies, the (non-)equivalence should already be apparent.
+
+    Strategy
+    --------
+
+    The canonical order is given by an arbitrary sorting rule.  A sort key
+    is determined for each dummy as a tuple that depends on all factors where
+    the index is present.  The dummies are thereby sorted according to the
+    contraction structure of the term, instead of sorting based solely on the
+    dummy symbol itself.
+
+    After all dummies in the term has been assigned a key, we check for identical
+    keys, i.e. unorderable dummies.  If any are found, we call a specialized
+    method, _determine_ambiguous(), that will determine a unique order based
+    on recursive calls to _get_ordered_dummies().
+
+    Key description
+    ---------------
+
+    A high level description of the sort key:
+
+        1. Range of the dummy index
+        2. Relation to external (non-dummy) indices
+        3. Position of the index in the first factor
+        4. Position of the index in the second factor
+
+    The sort key is a tuple with the following components:
+
+        1. A single character indicating the range of the dummy (above, below
+           or general.)
+        2. A list of strings with fully masked string representations of all
+           factors where the dummy is present.  By masked, we mean that dummies
+           are represented by a symbol to indicate either below fermi, above or
+           general.  No other information is displayed about the dummies at
+           this point.  The list is sorted stringwise.
+        3. An integer number indicating the position of the index, in the first
+           factor as sorted in 2.
+        4. An integer number indicating the position of the index, in the second
+           factor as sorted in 2.
+
+    If a factor is either of type AntiSymmetricTensor or SqOperator, the index
+    position in items 3 and 4 is indicated as 'upper' or 'lower' only.
+    (Creation operators are considered upper and annihilation operators lower.)
+
+    If the masked factors are identical, the two factors cannot be ordered
+    unambiguously in item 2.  In this case, items 3, 4 are left out.  If several
+    indices are contracted between the unorderable factors, it will be handled by
+    _determine_ambiguous()
+
+
+    """
+    # setup dicts to avoid repeated calculations in key()
+    args = Mul.make_args(mul)
+    fac_dum = { fac: fac.atoms(Dummy) for fac in args }
+    fac_repr = { fac: __kprint(fac) for fac in args }
+    all_dums = set().union(*fac_dum.values())
+    mask = {}
+    for d in all_dums:
+        if d.assumptions0.get('below_fermi'):
+            mask[d] = '0'
+        elif d.assumptions0.get('above_fermi'):
+            mask[d] = '1'
+        else:
+            mask[d] = '2'
+    dum_repr = {d: __kprint(d) for d in all_dums}
+
+    def _key(d):
+        dumstruct = [ fac for fac in fac_dum if d in fac_dum[fac] ]
+        other_dums = set().union(*[fac_dum[fac] for fac in dumstruct])
+        fac = dumstruct[-1]
+        if other_dums is fac_dum[fac]:
+            other_dums = fac_dum[fac].copy()
+        other_dums.remove(d)
+        masked_facs = [ fac_repr[fac] for fac in dumstruct ]
+        for d2 in other_dums:
+            masked_facs = [ fac.replace(dum_repr[d2], mask[d2])
+                    for fac in masked_facs ]
+        all_masked = [ fac.replace(dum_repr[d], mask[d])
+                       for fac in masked_facs ]
+        masked_facs = dict(list(zip(dumstruct, masked_facs)))
+
+        # dummies for which the ordering cannot be determined
+        if has_dups(all_masked):
+            all_masked.sort()
+            return mask[d], tuple(all_masked)  # positions are ambiguous
+
+        # sort factors according to fully masked strings
+        keydict = dict(list(zip(dumstruct, all_masked)))
+        dumstruct.sort(key=lambda x: keydict[x])
+        all_masked.sort()
+
+        pos_val = []
+        for fac in dumstruct:
+            if isinstance(fac, AntiSymmetricTensor):
+                if d in fac.upper:
+                    pos_val.append('u')
+                if d in fac.lower:
+                    pos_val.append('l')
+            elif isinstance(fac, Creator):
+                pos_val.append('u')
+            elif isinstance(fac, Annihilator):
+                pos_val.append('l')
+            elif isinstance(fac, NO):
+                ops = [ op for op in fac if op.has(d) ]
+                for op in ops:
+                    if isinstance(op, Creator):
+                        pos_val.append('u')
+                    else:
+                        pos_val.append('l')
+            else:
+                # fallback to position in string representation
+                facpos = -1
+                while 1:
+                    facpos = masked_facs[fac].find(dum_repr[d], facpos + 1)
+                    if facpos == -1:
+                        break
+                    pos_val.append(facpos)
+        return (mask[d], tuple(all_masked), pos_val[0], pos_val[-1])
+    dumkey = dict(list(zip(all_dums, list(map(_key, all_dums)))))
+    result = sorted(all_dums, key=lambda x: dumkey[x])
+    if has_dups(iter(dumkey.values())):
+        # We have ambiguities
+        unordered = defaultdict(set)
+        for d, k in dumkey.items():
+            unordered[k].add(d)
+        for k in [ k for k in unordered if len(unordered[k]) < 2 ]:
+            del unordered[k]
+
+        unordered = [ unordered[k] for k in sorted(unordered) ]
+        result = _determine_ambiguous(mul, result, unordered)
+    return result
+
+
+def _determine_ambiguous(term, ordered, ambiguous_groups):
+    # We encountered a term for which the dummy substitution is ambiguous.
+    # This happens for terms with 2 or more contractions between factors that
+    # cannot be uniquely ordered independent of summation indices.  For
+    # example:
+    #
+    # Sum(p, q) v^{p, .}_{q, .}v^{q, .}_{p, .}
+    #
+    # Assuming that the indices represented by . are dummies with the
+    # same range, the factors cannot be ordered, and there is no
+    # way to determine a consistent ordering of p and q.
+    #
+    # The strategy employed here, is to relabel all unambiguous dummies with
+    # non-dummy symbols and call _get_ordered_dummies again.  This procedure is
+    # applied to the entire term so there is a possibility that
+    # _determine_ambiguous() is called again from a deeper recursion level.
+
+    # break recursion if there are no ordered dummies
+    all_ambiguous = set()
+    for dummies in ambiguous_groups:
+        all_ambiguous |= dummies
+    all_ordered = set(ordered) - all_ambiguous
+    if not all_ordered:
+        # FIXME: If we arrive here, there are no ordered dummies. A method to
+        # handle this needs to be implemented.  In order to return something
+        # useful nevertheless, we choose arbitrarily the first dummy and
+        # determine the rest from this one.  This method is dependent on the
+        # actual dummy labels which violates an assumption for the
+        # canonicalization procedure.  A better implementation is needed.
+        group = [ d for d in ordered if d in ambiguous_groups[0] ]
+        d = group[0]
+        all_ordered.add(d)
+        ambiguous_groups[0].remove(d)
+
+    stored_counter = _symbol_factory._counter
+    subslist = []
+    for d in [ d for d in ordered if d in all_ordered ]:
+        nondum = _symbol_factory._next()
+        subslist.append((d, nondum))
+    newterm = term.subs(subslist)
+    neworder = _get_ordered_dummies(newterm)
+    _symbol_factory._set_counter(stored_counter)
+
+    # update ordered list with new information
+    for group in ambiguous_groups:
+        ordered_group = [ d for d in neworder if d in group ]
+        ordered_group.reverse()
+        result = []
+        for d in ordered:
+            if d in group:
+                result.append(ordered_group.pop())
+            else:
+                result.append(d)
+        ordered = result
+    return ordered
+
+
+class _SymbolFactory:
+    def __init__(self, label):
+        self._counterVar = 0
+        self._label = label
+
+    def _set_counter(self, value):
+        """
+        Sets counter to value.
+        """
+        self._counterVar = value
+
+    @property
+    def _counter(self):
+        """
+        What counter is currently at.
+        """
+        return self._counterVar
+
+    def _next(self):
+        """
+        Generates the next symbols and increments counter by 1.
+        """
+        s = Symbol("%s%i" % (self._label, self._counterVar))
+        self._counterVar += 1
+        return s
+_symbol_factory = _SymbolFactory('_]"]_')  # most certainly a unique label
+
+
+@cacheit
+def _get_contractions(string1, keep_only_fully_contracted=False):
+    """
+    Returns Add-object with contracted terms.
+
+    Uses recursion to find all contractions. -- Internal helper function --
+
+    Will find nonzero contractions in string1 between indices given in
+    leftrange and rightrange.
+
+    """
+
+    # Should we store current level of contraction?
+    if keep_only_fully_contracted and string1:
+        result = []
+    else:
+        result = [NO(Mul(*string1))]
+
+    for i in range(len(string1) - 1):
+        for j in range(i + 1, len(string1)):
+
+            c = contraction(string1[i], string1[j])
+
+            if c:
+                sign = (j - i + 1) % 2
+                if sign:
+                    coeff = S.NegativeOne*c
+                else:
+                    coeff = c
+
+                #
+                #  Call next level of recursion
+                #  ============================
+                #
+                # We now need to find more contractions among operators
+                #
+                # oplist = string1[:i]+ string1[i+1:j] + string1[j+1:]
+                #
+                # To prevent overcounting, we don't allow contractions
+                # we have already encountered. i.e. contractions between
+                #       string1[:i] <---> string1[i+1:j]
+                # and   string1[:i] <---> string1[j+1:].
+                #
+                # This leaves the case:
+                oplist = string1[i + 1:j] + string1[j + 1:]
+
+                if oplist:
+
+                    result.append(coeff*NO(
+                        Mul(*string1[:i])*_get_contractions( oplist,
+                            keep_only_fully_contracted=keep_only_fully_contracted)))
+
+                else:
+                    result.append(coeff*NO( Mul(*string1[:i])))
+
+        if keep_only_fully_contracted:
+            break   # next iteration over i leaves leftmost operator string1[0] uncontracted
+
+    return Add(*result)
+
+
+def wicks(e, **kw_args):
+    """
+    Returns the normal ordered equivalent of an expression using Wicks Theorem.
+
+    Examples
+    ========
+
+    >>> from sympy import symbols, Dummy
+    >>> from sympy.physics.secondquant import wicks, F, Fd
+    >>> p, q, r = symbols('p,q,r')
+    >>> wicks(Fd(p)*F(q))
+    KroneckerDelta(_i, q)*KroneckerDelta(p, q) + NO(CreateFermion(p)*AnnihilateFermion(q))
+
+    By default, the expression is expanded:
+
+    >>> wicks(F(p)*(F(q)+F(r)))
+    NO(AnnihilateFermion(p)*AnnihilateFermion(q)) + NO(AnnihilateFermion(p)*AnnihilateFermion(r))
+
+    With the keyword 'keep_only_fully_contracted=True', only fully contracted
+    terms are returned.
+
+    By request, the result can be simplified in the following order:
+     -- KroneckerDelta functions are evaluated
+     -- Dummy variables are substituted consistently across terms
+
+    >>> p, q, r = symbols('p q r', cls=Dummy)
+    >>> wicks(Fd(p)*(F(q)+F(r)), keep_only_fully_contracted=True)
+    KroneckerDelta(_i, _q)*KroneckerDelta(_p, _q) + KroneckerDelta(_i, _r)*KroneckerDelta(_p, _r)
+
+    """
+
+    if not e:
+        return S.Zero
+
+    opts = {
+        'simplify_kronecker_deltas': False,
+        'expand': True,
+        'simplify_dummies': False,
+        'keep_only_fully_contracted': False
+    }
+    opts.update(kw_args)
+
+    # check if we are already normally ordered
+    if isinstance(e, NO):
+        if opts['keep_only_fully_contracted']:
+            return S.Zero
+        else:
+            return e
+    elif isinstance(e, FermionicOperator):
+        if opts['keep_only_fully_contracted']:
+            return S.Zero
+        else:
+            return e
+
+    # break up any NO-objects, and evaluate commutators
+    e = e.doit(wicks=True)
+
+    # make sure we have only one term to consider
+    e = e.expand()
+    if isinstance(e, Add):
+        if opts['simplify_dummies']:
+            return substitute_dummies(Add(*[ wicks(term, **kw_args) for term in e.args]))
+        else:
+            return Add(*[ wicks(term, **kw_args) for term in e.args])
+
+    # For Mul-objects we can actually do something
+    if isinstance(e, Mul):
+
+        # we don't want to mess around with commuting part of Mul
+        # so we factorize it out before starting recursion
+        c_part = []
+        string1 = []
+        for factor in e.args:
+            if factor.is_commutative:
+                c_part.append(factor)
+            else:
+                string1.append(factor)
+        n = len(string1)
+
+        # catch trivial cases
+        if n == 0:
+            result = e
+        elif n == 1:
+            if opts['keep_only_fully_contracted']:
+                return S.Zero
+            else:
+                result = e
+
+        else:  # non-trivial
+
+            if isinstance(string1[0], BosonicOperator):
+                raise NotImplementedError
+
+            string1 = tuple(string1)
+
+            # recursion over higher order contractions
+            result = _get_contractions(string1,
+                keep_only_fully_contracted=opts['keep_only_fully_contracted'] )
+            result = Mul(*c_part)*result
+
+        if opts['expand']:
+            result = result.expand()
+        if opts['simplify_kronecker_deltas']:
+            result = evaluate_deltas(result)
+
+        return result
+
+    # there was nothing to do
+    return e
+
+
+class PermutationOperator(Expr):
+    """
+    Represents the index permutation operator P(ij).
+
+    P(ij)*f(i)*g(j) = f(i)*g(j) - f(j)*g(i)
+    """
+    is_commutative = True
+
+    def __new__(cls, i, j):
+        i, j = sorted(map(sympify, (i, j)), key=default_sort_key)
+        obj = Basic.__new__(cls, i, j)
+        return obj
+
+    def get_permuted(self, expr):
+        """
+        Returns -expr with permuted indices.
+
+        Explanation
+        ===========
+
+        >>> from sympy import symbols, Function
+        >>> from sympy.physics.secondquant import PermutationOperator
+        >>> p,q = symbols('p,q')
+        >>> f = Function('f')
+        >>> PermutationOperator(p,q).get_permuted(f(p,q))
+        -f(q, p)
+
+        """
+        i = self.args[0]
+        j = self.args[1]
+        if expr.has(i) and expr.has(j):
+            tmp = Dummy()
+            expr = expr.subs(i, tmp)
+            expr = expr.subs(j, i)
+            expr = expr.subs(tmp, j)
+            return S.NegativeOne*expr
+        else:
+            return expr
+
+    def _latex(self, printer):
+        return "P(%s%s)" % tuple(printer._print(i) for i in self.args)
+
+
+def simplify_index_permutations(expr, permutation_operators):
+    """
+    Performs simplification by introducing PermutationOperators where appropriate.
+
+    Explanation
+    ===========
+
+    Schematically:
+        [abij] - [abji] - [baij] + [baji] ->  P(ab)*P(ij)*[abij]
+
+    permutation_operators is a list of PermutationOperators to consider.
+
+    If permutation_operators=[P(ab),P(ij)] we will try to introduce the
+    permutation operators P(ij) and P(ab) in the expression.  If there are other
+    possible simplifications, we ignore them.
+
+    >>> from sympy import symbols, Function
+    >>> from sympy.physics.secondquant import simplify_index_permutations
+    >>> from sympy.physics.secondquant import PermutationOperator
+    >>> p,q,r,s = symbols('p,q,r,s')
+    >>> f = Function('f')
+    >>> g = Function('g')
+
+    >>> expr = f(p)*g(q) - f(q)*g(p); expr
+    f(p)*g(q) - f(q)*g(p)
+    >>> simplify_index_permutations(expr,[PermutationOperator(p,q)])
+    f(p)*g(q)*PermutationOperator(p, q)
+
+    >>> PermutList = [PermutationOperator(p,q),PermutationOperator(r,s)]
+    >>> expr = f(p,r)*g(q,s) - f(q,r)*g(p,s) + f(q,s)*g(p,r) - f(p,s)*g(q,r)
+    >>> simplify_index_permutations(expr,PermutList)
+    f(p, r)*g(q, s)*PermutationOperator(p, q)*PermutationOperator(r, s)
+
+    """
+
+    def _get_indices(expr, ind):
+        """
+        Collects indices recursively in predictable order.
+        """
+        result = []
+        for arg in expr.args:
+            if arg in ind:
+                result.append(arg)
+            else:
+                if arg.args:
+                    result.extend(_get_indices(arg, ind))
+        return result
+
+    def _choose_one_to_keep(a, b, ind):
+        # we keep the one where indices in ind are in order ind[0] < ind[1]
+        return min(a, b, key=lambda x: default_sort_key(_get_indices(x, ind)))
+
+    expr = expr.expand()
+    if isinstance(expr, Add):
+        terms = set(expr.args)
+
+        for P in permutation_operators:
+            new_terms = set()
+            on_hold = set()
+            while terms:
+                term = terms.pop()
+                permuted = P.get_permuted(term)
+                if permuted in terms | on_hold:
+                    try:
+                        terms.remove(permuted)
+                    except KeyError:
+                        on_hold.remove(permuted)
+                    keep = _choose_one_to_keep(term, permuted, P.args)
+                    new_terms.add(P*keep)
+                else:
+
+                    # Some terms must get a second chance because the permuted
+                    # term may already have canonical dummy ordering.  Then
+                    # substitute_dummies() does nothing.  However, the other
+                    # term, if it exists, will be able to match with us.
+                    permuted1 = permuted
+                    permuted = substitute_dummies(permuted)
+                    if permuted1 == permuted:
+                        on_hold.add(term)
+                    elif permuted in terms | on_hold:
+                        try:
+                            terms.remove(permuted)
+                        except KeyError:
+                            on_hold.remove(permuted)
+                        keep = _choose_one_to_keep(term, permuted, P.args)
+                        new_terms.add(P*keep)
+                    else:
+                        new_terms.add(term)
+            terms = new_terms | on_hold
+        return Add(*terms)
+    return expr
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/sho.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/sho.py
new file mode 100644
index 0000000000000000000000000000000000000000..c55b31b3fa9fca4fa33a9f8e91c90c2174fe81a5
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/sho.py
@@ -0,0 +1,95 @@
+from sympy.core import S, pi, Rational
+from sympy.functions import assoc_laguerre, sqrt, exp, factorial, factorial2
+
+
+def R_nl(n, l, nu, r):
+    """
+    Returns the radial wavefunction R_{nl} for a 3d isotropic harmonic
+    oscillator.
+
+    Parameters
+    ==========
+
+    n :
+        The "nodal" quantum number.  Corresponds to the number of nodes in
+        the wavefunction.  ``n >= 0``
+    l :
+        The quantum number for orbital angular momentum.
+    nu :
+        mass-scaled frequency: nu = m*omega/(2*hbar) where `m` is the mass
+        and `omega` the frequency of the oscillator.
+        (in atomic units ``nu == omega/2``)
+    r :
+        Radial coordinate.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.sho import R_nl
+    >>> from sympy.abc import r, nu, l
+    >>> R_nl(0, 0, 1, r)
+    2*2**(3/4)*exp(-r**2)/pi**(1/4)
+    >>> R_nl(1, 0, 1, r)
+    4*2**(1/4)*sqrt(3)*(3/2 - 2*r**2)*exp(-r**2)/(3*pi**(1/4))
+
+    l, nu and r may be symbolic:
+
+    >>> R_nl(0, 0, nu, r)
+    2*2**(3/4)*sqrt(nu**(3/2))*exp(-nu*r**2)/pi**(1/4)
+    >>> R_nl(0, l, 1, r)
+    r**l*sqrt(2**(l + 3/2)*2**(l + 2)/factorial2(2*l + 1))*exp(-r**2)/pi**(1/4)
+
+    The normalization of the radial wavefunction is:
+
+    >>> from sympy import Integral, oo
+    >>> Integral(R_nl(0, 0, 1, r)**2*r**2, (r, 0, oo)).n()
+    1.00000000000000
+    >>> Integral(R_nl(1, 0, 1, r)**2*r**2, (r, 0, oo)).n()
+    1.00000000000000
+    >>> Integral(R_nl(1, 1, 1, r)**2*r**2, (r, 0, oo)).n()
+    1.00000000000000
+
+    """
+    n, l, nu, r = map(S, [n, l, nu, r])
+
+    # formula uses n >= 1 (instead of nodal n >= 0)
+    n = n + 1
+    C = sqrt(
+            ((2*nu)**(l + Rational(3, 2))*2**(n + l + 1)*factorial(n - 1))/
+            (sqrt(pi)*(factorial2(2*n + 2*l - 1)))
+    )
+    return C*r**(l)*exp(-nu*r**2)*assoc_laguerre(n - 1, l + S.Half, 2*nu*r**2)
+
+
+def E_nl(n, l, hw):
+    """
+    Returns the Energy of an isotropic harmonic oscillator.
+
+    Parameters
+    ==========
+
+    n :
+        The "nodal" quantum number.
+    l :
+        The orbital angular momentum.
+    hw :
+        The harmonic oscillator parameter.
+
+    Notes
+    =====
+
+    The unit of the returned value matches the unit of hw, since the energy is
+    calculated as:
+
+        E_nl = (2*n + l + 3/2)*hw
+
+    Examples
+    ========
+
+    >>> from sympy.physics.sho import E_nl
+    >>> from sympy import symbols
+    >>> x, y, z = symbols('x, y, z')
+    >>> E_nl(x, y, z)
+    z*(2*x + y + 3/2)
+    """
+    return (2*n + l + Rational(3, 2))*hw
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/wigner.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/wigner.py
new file mode 100644
index 0000000000000000000000000000000000000000..e08f3fb4a480439fd2bb1f8ff8c305bf69d7abae
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/physics/wigner.py
@@ -0,0 +1,1213 @@
+# -*- coding: utf-8 -*-
+r"""
+Wigner, Clebsch-Gordan, Racah, and Gaunt coefficients
+
+Collection of functions for calculating Wigner 3j, 6j, 9j,
+Clebsch-Gordan, Racah as well as Gaunt coefficients exactly, all
+evaluating to a rational number times the square root of a rational
+number [Rasch03]_.
+
+Please see the description of the individual functions for further
+details and examples.
+
+References
+==========
+
+.. [Regge58] 'Symmetry Properties of Clebsch-Gordan Coefficients',
+  T. Regge, Nuovo Cimento, Volume 10, pp. 544 (1958)
+.. [Regge59] 'Symmetry Properties of Racah Coefficients',
+  T. Regge, Nuovo Cimento, Volume 11, pp. 116 (1959)
+.. [Edmonds74] A. R. Edmonds. Angular momentum in quantum mechanics.
+  Investigations in physics, 4.; Investigations in physics, no. 4.
+  Princeton, N.J., Princeton University Press, 1957.
+.. [Rasch03] J. Rasch and A. C. H. Yu, 'Efficient Storage Scheme for
+  Pre-calculated Wigner 3j, 6j and Gaunt Coefficients', SIAM
+  J. Sci. Comput. Volume 25, Issue 4, pp. 1416-1428 (2003)
+.. [Liberatodebrito82] 'FORTRAN program for the integral of three
+  spherical harmonics', A. Liberato de Brito,
+  Comput. Phys. Commun., Volume 25, pp. 81-85 (1982)
+.. [Homeier96] 'Some Properties of the Coupling Coefficients of Real
+  Spherical Harmonics and Their Relation to Gaunt Coefficients',
+  H. H. H. Homeier and E. O. Steinborn J. Mol. Struct., Volume 368,
+  pp. 31-37 (1996)
+
+Credits and Copyright
+=====================
+
+This code was taken from Sage with the permission of all authors:
+
+https://groups.google.com/forum/#!topic/sage-devel/M4NZdu-7O38
+
+Authors
+=======
+
+- Jens Rasch (2009-03-24): initial version for Sage
+
+- Jens Rasch (2009-05-31): updated to sage-4.0
+
+- Oscar Gerardo Lazo Arjona (2017-06-18): added Wigner D matrices
+
+- Phil Adam LeMaitre (2022-09-19): added real Gaunt coefficient
+
+Copyright (C) 2008 Jens Rasch 
+
+"""
+from sympy.concrete.summations import Sum
+from sympy.core.add import Add
+from sympy.core.numbers import int_valued
+from sympy.core.function import Function
+from sympy.core.numbers import (Float, I, Integer, pi, Rational)
+from sympy.core.singleton import S
+from sympy.core.symbol import Dummy
+from sympy.core.sympify import sympify
+from sympy.functions.combinatorial.factorials import (binomial, factorial)
+from sympy.functions.elementary.complexes import re
+from sympy.functions.elementary.exponential import exp
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import (cos, sin)
+from sympy.functions.special.spherical_harmonics import Ynm
+from sympy.matrices.dense import zeros
+from sympy.matrices.immutable import ImmutableMatrix
+from sympy.utilities.misc import as_int
+
+# This list of precomputed factorials is needed to massively
+# accelerate future calculations of the various coefficients
+_Factlist = [1]
+
+
+def _calc_factlist(nn):
+    r"""
+    Function calculates a list of precomputed factorials in order to
+    massively accelerate future calculations of the various
+    coefficients.
+
+    Parameters
+    ==========
+
+    nn : integer
+        Highest factorial to be computed.
+
+    Returns
+    =======
+
+    list of integers :
+        The list of precomputed factorials.
+
+    Examples
+    ========
+
+    Calculate list of factorials::
+
+        sage: from sage.functions.wigner import _calc_factlist
+        sage: _calc_factlist(10)
+        [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
+    """
+    if nn >= len(_Factlist):
+        for ii in range(len(_Factlist), int(nn + 1)):
+            _Factlist.append(_Factlist[ii - 1] * ii)
+    return _Factlist[:int(nn) + 1]
+
+
+def _int_or_halfint(value):
+    """return Python int unless value is half-int (then return float)"""
+    if isinstance(value, int):
+        return value
+    elif type(value) is float:
+        if value.is_integer():
+            return int(value)  # an int
+        if (2*value).is_integer():
+            return value  # a float
+    elif isinstance(value, Rational):
+        if value.q == 2:
+            return value.p/value.q  # a float
+        elif value.q == 1:
+            return value.p  # an int
+    elif isinstance(value, Float):
+        return _int_or_halfint(float(value))
+    raise ValueError("expecting integer or half-integer, got %s" % value)
+
+
+def wigner_3j(j_1, j_2, j_3, m_1, m_2, m_3):
+    r"""
+    Calculate the Wigner 3j symbol `\operatorname{Wigner3j}(j_1,j_2,j_3,m_1,m_2,m_3)`.
+
+    Parameters
+    ==========
+
+    j_1, j_2, j_3, m_1, m_2, m_3 :
+        Integer or half integer.
+
+    Returns
+    =======
+
+    Rational number times the square root of a rational number.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.wigner import wigner_3j
+    >>> wigner_3j(2, 6, 4, 0, 0, 0)
+    sqrt(715)/143
+    >>> wigner_3j(2, 6, 4, 0, 0, 1)
+    0
+
+    It is an error to have arguments that are not integer or half
+    integer values::
+
+        sage: wigner_3j(2.1, 6, 4, 0, 0, 0)
+        Traceback (most recent call last):
+        ...
+        ValueError: j values must be integer or half integer
+        sage: wigner_3j(2, 6, 4, 1, 0, -1.1)
+        Traceback (most recent call last):
+        ...
+        ValueError: m values must be integer or half integer
+
+    Notes
+    =====
+
+    The Wigner 3j symbol obeys the following symmetry rules:
+
+    - invariant under any permutation of the columns (with the
+      exception of a sign change where `J:=j_1+j_2+j_3`):
+
+      .. math::
+
+         \begin{aligned}
+         \operatorname{Wigner3j}(j_1,j_2,j_3,m_1,m_2,m_3)
+          &=\operatorname{Wigner3j}(j_3,j_1,j_2,m_3,m_1,m_2) \\
+          &=\operatorname{Wigner3j}(j_2,j_3,j_1,m_2,m_3,m_1) \\
+          &=(-1)^J \operatorname{Wigner3j}(j_3,j_2,j_1,m_3,m_2,m_1) \\
+          &=(-1)^J \operatorname{Wigner3j}(j_1,j_3,j_2,m_1,m_3,m_2) \\
+          &=(-1)^J \operatorname{Wigner3j}(j_2,j_1,j_3,m_2,m_1,m_3)
+         \end{aligned}
+
+    - invariant under space inflection, i.e.
+
+      .. math::
+
+         \operatorname{Wigner3j}(j_1,j_2,j_3,m_1,m_2,m_3)
+         =(-1)^J \operatorname{Wigner3j}(j_1,j_2,j_3,-m_1,-m_2,-m_3)
+
+    - symmetric with respect to the 72 additional symmetries based on
+      the work by [Regge58]_
+
+    - zero for `j_1`, `j_2`, `j_3` not fulfilling triangle relation
+
+    - zero for `m_1 + m_2 + m_3 \neq 0`
+
+    - zero for violating any one of the conditions
+         `m_1  \in \{-|j_1|, \ldots, |j_1|\}`,
+         `m_2  \in \{-|j_2|, \ldots, |j_2|\}`,
+         `m_3  \in \{-|j_3|, \ldots, |j_3|\}`
+
+    Algorithm
+    =========
+
+    This function uses the algorithm of [Edmonds74]_ to calculate the
+    value of the 3j symbol exactly. Note that the formula contains
+    alternating sums over large factorials and is therefore unsuitable
+    for finite precision arithmetic and only useful for a computer
+    algebra system [Rasch03]_.
+
+    Authors
+    =======
+
+    - Jens Rasch (2009-03-24): initial version
+    """
+
+    j_1, j_2, j_3, m_1, m_2, m_3 = \
+        map(_int_or_halfint, map(sympify,
+            [j_1, j_2, j_3, m_1, m_2, m_3]))
+
+    if m_1 + m_2 + m_3 != 0:
+        return S.Zero
+    a1 = j_1 + j_2 - j_3
+    if a1 < 0:
+        return S.Zero
+    a2 = j_1 - j_2 + j_3
+    if a2 < 0:
+        return S.Zero
+    a3 = -j_1 + j_2 + j_3
+    if a3 < 0:
+        return S.Zero
+    if (abs(m_1) > j_1) or (abs(m_2) > j_2) or (abs(m_3) > j_3):
+        return S.Zero
+    if not (int_valued(j_1 - m_1) and \
+            int_valued(j_2 - m_2) and \
+            int_valued(j_3 - m_3)):
+        return S.Zero
+
+    maxfact = max(j_1 + j_2 + j_3 + 1, j_1 + abs(m_1), j_2 + abs(m_2),
+                  j_3 + abs(m_3))
+    _calc_factlist(int(maxfact))
+
+    argsqrt = Integer(_Factlist[int(j_1 + j_2 - j_3)] *
+                     _Factlist[int(j_1 - j_2 + j_3)] *
+                     _Factlist[int(-j_1 + j_2 + j_3)] *
+                     _Factlist[int(j_1 - m_1)] *
+                     _Factlist[int(j_1 + m_1)] *
+                     _Factlist[int(j_2 - m_2)] *
+                     _Factlist[int(j_2 + m_2)] *
+                     _Factlist[int(j_3 - m_3)] *
+                     _Factlist[int(j_3 + m_3)]) / \
+        _Factlist[int(j_1 + j_2 + j_3 + 1)]
+
+    ressqrt = sqrt(argsqrt)
+    if ressqrt.is_complex or ressqrt.is_infinite:
+        ressqrt = ressqrt.as_real_imag()[0]
+
+    imin = max(-j_3 + j_1 + m_2, -j_3 + j_2 - m_1, 0)
+    imax = min(j_2 + m_2, j_1 - m_1, j_1 + j_2 - j_3)
+    sumres = 0
+    for ii in range(int(imin), int(imax) + 1):
+        den = _Factlist[ii] * \
+            _Factlist[int(ii + j_3 - j_1 - m_2)] * \
+            _Factlist[int(j_2 + m_2 - ii)] * \
+            _Factlist[int(j_1 - ii - m_1)] * \
+            _Factlist[int(ii + j_3 - j_2 + m_1)] * \
+            _Factlist[int(j_1 + j_2 - j_3 - ii)]
+        sumres = sumres + Integer((-1) ** ii) / den
+
+    prefid = Integer((-1) ** int(j_1 - j_2 - m_3))
+    res = ressqrt * sumres * prefid
+    return res
+
+
+def clebsch_gordan(j_1, j_2, j_3, m_1, m_2, m_3):
+    r"""
+    Calculates the Clebsch-Gordan coefficient.
+    `\left\langle j_1 m_1 \; j_2 m_2 | j_3 m_3 \right\rangle`.
+
+    The reference for this function is [Edmonds74]_.
+
+    Parameters
+    ==========
+
+    j_1, j_2, j_3, m_1, m_2, m_3 :
+        Integer or half integer.
+
+    Returns
+    =======
+
+    Rational number times the square root of a rational number.
+
+    Examples
+    ========
+
+    >>> from sympy import S
+    >>> from sympy.physics.wigner import clebsch_gordan
+    >>> clebsch_gordan(S(3)/2, S(1)/2, 2, S(3)/2, S(1)/2, 2)
+    1
+    >>> clebsch_gordan(S(3)/2, S(1)/2, 1, S(3)/2, -S(1)/2, 1)
+    sqrt(3)/2
+    >>> clebsch_gordan(S(3)/2, S(1)/2, 1, -S(1)/2, S(1)/2, 0)
+    -sqrt(2)/2
+
+    Notes
+    =====
+
+    The Clebsch-Gordan coefficient will be evaluated via its relation
+    to Wigner 3j symbols:
+
+    .. math::
+
+        \left\langle j_1 m_1 \; j_2 m_2 | j_3 m_3 \right\rangle
+        =(-1)^{j_1-j_2+m_3} \sqrt{2j_3+1}
+        \operatorname{Wigner3j}(j_1,j_2,j_3,m_1,m_2,-m_3)
+
+    See also the documentation on Wigner 3j symbols which exhibit much
+    higher symmetry relations than the Clebsch-Gordan coefficient.
+
+    Authors
+    =======
+
+    - Jens Rasch (2009-03-24): initial version
+    """
+    j_1 = sympify(j_1)
+    j_2 = sympify(j_2)
+    j_3 = sympify(j_3)
+    m_1 = sympify(m_1)
+    m_2 = sympify(m_2)
+    m_3 = sympify(m_3)
+
+    w = wigner_3j(j_1, j_2, j_3, m_1, m_2, -m_3)
+
+    return (-1) ** (j_1 - j_2 + m_3) * sqrt(2 * j_3 + 1) * w
+
+
+def _big_delta_coeff(aa, bb, cc, prec=None):
+    r"""
+    Calculates the Delta coefficient of the 3 angular momenta for
+    Racah symbols. Also checks that the differences are of integer
+    value.
+
+    Parameters
+    ==========
+
+    aa :
+        First angular momentum, integer or half integer.
+    bb :
+        Second angular momentum, integer or half integer.
+    cc :
+        Third angular momentum, integer or half integer.
+    prec :
+        Precision of the ``sqrt()`` calculation.
+
+    Returns
+    =======
+
+    double : Value of the Delta coefficient.
+
+    Examples
+    ========
+
+        sage: from sage.functions.wigner import _big_delta_coeff
+        sage: _big_delta_coeff(1,1,1)
+        1/2*sqrt(1/6)
+    """
+
+    # the triangle test will only pass if a) all 3 values are ints or
+    # b) 1 is an int and the other two are half-ints
+    if not int_valued(aa + bb - cc):
+        raise ValueError("j values must be integer or half integer and fulfill the triangle relation")
+    if not int_valued(aa + cc - bb):
+        raise ValueError("j values must be integer or half integer and fulfill the triangle relation")
+    if not int_valued(bb + cc - aa):
+        raise ValueError("j values must be integer or half integer and fulfill the triangle relation")
+    if (aa + bb - cc) < 0:
+        return S.Zero
+    if (aa + cc - bb) < 0:
+        return S.Zero
+    if (bb + cc - aa) < 0:
+        return S.Zero
+
+    maxfact = max(aa + bb - cc, aa + cc - bb, bb + cc - aa, aa + bb + cc + 1)
+    _calc_factlist(maxfact)
+
+    argsqrt = Integer(_Factlist[int(aa + bb - cc)] *
+                     _Factlist[int(aa + cc - bb)] *
+                     _Factlist[int(bb + cc - aa)]) / \
+        Integer(_Factlist[int(aa + bb + cc + 1)])
+
+    ressqrt = sqrt(argsqrt)
+    if prec:
+        ressqrt = ressqrt.evalf(prec).as_real_imag()[0]
+    return ressqrt
+
+
+def racah(aa, bb, cc, dd, ee, ff, prec=None):
+    r"""
+    Calculate the Racah symbol `W(a,b,c,d;e,f)`.
+
+    Parameters
+    ==========
+
+    a, ..., f :
+        Integer or half integer.
+    prec :
+        Precision, default: ``None``. Providing a precision can
+        drastically speed up the calculation.
+
+    Returns
+    =======
+
+    Rational number times the square root of a rational number
+    (if ``prec=None``), or real number if a precision is given.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.wigner import racah
+    >>> racah(3,3,3,3,3,3)
+    -1/14
+
+    Notes
+    =====
+
+    The Racah symbol is related to the Wigner 6j symbol:
+
+    .. math::
+
+       \operatorname{Wigner6j}(j_1,j_2,j_3,j_4,j_5,j_6)
+       =(-1)^{j_1+j_2+j_4+j_5} W(j_1,j_2,j_5,j_4,j_3,j_6)
+
+    Please see the 6j symbol for its much richer symmetries and for
+    additional properties.
+
+    Algorithm
+    =========
+
+    This function uses the algorithm of [Edmonds74]_ to calculate the
+    value of the 6j symbol exactly. Note that the formula contains
+    alternating sums over large factorials and is therefore unsuitable
+    for finite precision arithmetic and only useful for a computer
+    algebra system [Rasch03]_.
+
+    Authors
+    =======
+
+    - Jens Rasch (2009-03-24): initial version
+    """
+    prefac = _big_delta_coeff(aa, bb, ee, prec) * \
+        _big_delta_coeff(cc, dd, ee, prec) * \
+        _big_delta_coeff(aa, cc, ff, prec) * \
+        _big_delta_coeff(bb, dd, ff, prec)
+    if prefac == 0:
+        return S.Zero
+    imin = max(aa + bb + ee, cc + dd + ee, aa + cc + ff, bb + dd + ff)
+    imax = min(aa + bb + cc + dd, aa + dd + ee + ff, bb + cc + ee + ff)
+
+    maxfact = max(imax + 1, aa + bb + cc + dd, aa + dd + ee + ff,
+                 bb + cc + ee + ff)
+    _calc_factlist(maxfact)
+
+    sumres = 0
+    for kk in range(int(imin), int(imax) + 1):
+        den = _Factlist[int(kk - aa - bb - ee)] * \
+            _Factlist[int(kk - cc - dd - ee)] * \
+            _Factlist[int(kk - aa - cc - ff)] * \
+            _Factlist[int(kk - bb - dd - ff)] * \
+            _Factlist[int(aa + bb + cc + dd - kk)] * \
+            _Factlist[int(aa + dd + ee + ff - kk)] * \
+            _Factlist[int(bb + cc + ee + ff - kk)]
+        sumres = sumres + Integer((-1) ** kk * _Factlist[kk + 1]) / den
+
+    res = prefac * sumres * (-1) ** int(aa + bb + cc + dd)
+    return res
+
+
+def wigner_6j(j_1, j_2, j_3, j_4, j_5, j_6, prec=None):
+    r"""
+    Calculate the Wigner 6j symbol `\operatorname{Wigner6j}(j_1,j_2,j_3,j_4,j_5,j_6)`.
+
+    Parameters
+    ==========
+
+    j_1, ..., j_6 :
+        Integer or half integer.
+    prec :
+        Precision, default: ``None``. Providing a precision can
+        drastically speed up the calculation.
+
+    Returns
+    =======
+
+    Rational number times the square root of a rational number
+    (if ``prec=None``), or real number if a precision is given.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.wigner import wigner_6j
+    >>> wigner_6j(3,3,3,3,3,3)
+    -1/14
+    >>> wigner_6j(5,5,5,5,5,5)
+    1/52
+
+    It is an error to have arguments that are not integer or half
+    integer values or do not fulfill the triangle relation::
+
+        sage: wigner_6j(2.5,2.5,2.5,2.5,2.5,2.5)
+        Traceback (most recent call last):
+        ...
+        ValueError: j values must be integer or half integer and fulfill the triangle relation
+        sage: wigner_6j(0.5,0.5,1.1,0.5,0.5,1.1)
+        Traceback (most recent call last):
+        ...
+        ValueError: j values must be integer or half integer and fulfill the triangle relation
+
+    Notes
+    =====
+
+    The Wigner 6j symbol is related to the Racah symbol but exhibits
+    more symmetries as detailed below.
+
+    .. math::
+
+       \operatorname{Wigner6j}(j_1,j_2,j_3,j_4,j_5,j_6)
+        =(-1)^{j_1+j_2+j_4+j_5} W(j_1,j_2,j_5,j_4,j_3,j_6)
+
+    The Wigner 6j symbol obeys the following symmetry rules:
+
+    - Wigner 6j symbols are left invariant under any permutation of
+      the columns:
+
+      .. math::
+
+         \begin{aligned}
+         \operatorname{Wigner6j}(j_1,j_2,j_3,j_4,j_5,j_6)
+          &=\operatorname{Wigner6j}(j_3,j_1,j_2,j_6,j_4,j_5) \\
+          &=\operatorname{Wigner6j}(j_2,j_3,j_1,j_5,j_6,j_4) \\
+          &=\operatorname{Wigner6j}(j_3,j_2,j_1,j_6,j_5,j_4) \\
+          &=\operatorname{Wigner6j}(j_1,j_3,j_2,j_4,j_6,j_5) \\
+          &=\operatorname{Wigner6j}(j_2,j_1,j_3,j_5,j_4,j_6)
+         \end{aligned}
+
+    - They are invariant under the exchange of the upper and lower
+      arguments in each of any two columns, i.e.
+
+      .. math::
+
+         \begin{aligned}
+         \operatorname{Wigner6j}(j_1,j_2,j_3,j_4,j_5,j_6)
+          &=\operatorname{Wigner6j}(j_1,j_5,j_6,j_4,j_2,j_3)\\
+          &=\operatorname{Wigner6j}(j_4,j_2,j_6,j_1,j_5,j_3)\\
+          &=\operatorname{Wigner6j}(j_4,j_5,j_3,j_1,j_2,j_6)
+         \end{aligned}
+
+    - additional 6 symmetries [Regge59]_ giving rise to 144 symmetries
+      in total
+
+    - only non-zero if any triple of `j`'s fulfill a triangle relation
+
+    Algorithm
+    =========
+
+    This function uses the algorithm of [Edmonds74]_ to calculate the
+    value of the 6j symbol exactly. Note that the formula contains
+    alternating sums over large factorials and is therefore unsuitable
+    for finite precision arithmetic and only useful for a computer
+    algebra system [Rasch03]_.
+
+    """
+    j_1, j_2, j_3, j_4, j_5, j_6 = map(sympify, \
+                [j_1, j_2, j_3, j_4, j_5, j_6])
+    res = (-1) ** int(j_1 + j_2 + j_4 + j_5) * \
+        racah(j_1, j_2, j_5, j_4, j_3, j_6, prec)
+    return res
+
+
+def wigner_9j(j_1, j_2, j_3, j_4, j_5, j_6, j_7, j_8, j_9, prec=None):
+    r"""
+    Calculate the Wigner 9j symbol
+    `\operatorname{Wigner9j}(j_1,j_2,j_3,j_4,j_5,j_6,j_7,j_8,j_9)`.
+
+    Parameters
+    ==========
+
+    j_1, ..., j_9 :
+        Integer or half integer.
+    prec : precision, default
+        ``None``. Providing a precision can
+        drastically speed up the calculation.
+
+    Returns
+    =======
+
+    Rational number times the square root of a rational number
+    (if ``prec=None``), or real number if a precision is given.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.wigner import wigner_9j
+    >>> wigner_9j(1,1,1, 1,1,1, 1,1,0, prec=64)
+    0.05555555555555555555555555555555555555555555555555555555555555555
+
+    >>> wigner_9j(1/2,1/2,0, 1/2,3/2,1, 0,1,1, prec=64)
+    0.1666666666666666666666666666666666666666666666666666666666666667
+
+    It is an error to have arguments that are not integer or half
+    integer values or do not fulfill the triangle relation::
+
+        sage: wigner_9j(0.5,0.5,0.5, 0.5,0.5,0.5, 0.5,0.5,0.5,prec=64)
+        Traceback (most recent call last):
+        ...
+        ValueError: j values must be integer or half integer and fulfill the triangle relation
+        sage: wigner_9j(1,1,1, 0.5,1,1.5, 0.5,1,2.5,prec=64)
+        Traceback (most recent call last):
+        ...
+        ValueError: j values must be integer or half integer and fulfill the triangle relation
+
+    Algorithm
+    =========
+
+    This function uses the algorithm of [Edmonds74]_ to calculate the
+    value of the 3j symbol exactly. Note that the formula contains
+    alternating sums over large factorials and is therefore unsuitable
+    for finite precision arithmetic and only useful for a computer
+    algebra system [Rasch03]_.
+    """
+    j_1, j_2, j_3, j_4, j_5, j_6, j_7, j_8, j_9 = map(sympify, \
+                [j_1, j_2, j_3, j_4, j_5, j_6, j_7, j_8, j_9])
+    imax = int(min(j_1 + j_9, j_2 + j_6, j_4 + j_8) * 2)
+    imin = imax % 2
+    sumres = 0
+    for kk in range(imin, int(imax) + 1, 2):
+        sumres = sumres + (kk + 1) * \
+            racah(j_1, j_2, j_9, j_6, j_3, kk / 2, prec) * \
+            racah(j_4, j_6, j_8, j_2, j_5, kk / 2, prec) * \
+            racah(j_1, j_4, j_9, j_8, j_7, kk / 2, prec)
+    return sumres
+
+
+def gaunt(l_1, l_2, l_3, m_1, m_2, m_3, prec=None):
+    r"""
+    Calculate the Gaunt coefficient.
+
+    Explanation
+    ===========
+
+    The Gaunt coefficient is defined as the integral over three
+    spherical harmonics:
+
+    .. math::
+
+        \begin{aligned}
+        \operatorname{Gaunt}(l_1,l_2,l_3,m_1,m_2,m_3)
+        &=\int Y_{l_1,m_1}(\Omega)
+         Y_{l_2,m_2}(\Omega) Y_{l_3,m_3}(\Omega) \,d\Omega \\
+        &=\sqrt{\frac{(2l_1+1)(2l_2+1)(2l_3+1)}{4\pi}}
+         \operatorname{Wigner3j}(l_1,l_2,l_3,0,0,0)
+         \operatorname{Wigner3j}(l_1,l_2,l_3,m_1,m_2,m_3)
+        \end{aligned}
+
+    Parameters
+    ==========
+
+    l_1, l_2, l_3, m_1, m_2, m_3 :
+        Integer.
+    prec - precision, default: ``None``.
+        Providing a precision can
+        drastically speed up the calculation.
+
+    Returns
+    =======
+
+    Rational number times the square root of a rational number
+    (if ``prec=None``), or real number if a precision is given.
+
+    Examples
+    ========
+
+    >>> from sympy.physics.wigner import gaunt
+    >>> gaunt(1,0,1,1,0,-1)
+    -1/(2*sqrt(pi))
+    >>> gaunt(1000,1000,1200,9,3,-12).n(64)
+    0.006895004219221134484332976156744208248842039317638217822322799675
+
+    It is an error to use non-integer values for `l` and `m`::
+
+        sage: gaunt(1.2,0,1.2,0,0,0)
+        Traceback (most recent call last):
+        ...
+        ValueError: l values must be integer
+        sage: gaunt(1,0,1,1.1,0,-1.1)
+        Traceback (most recent call last):
+        ...
+        ValueError: m values must be integer
+
+    Notes
+    =====
+
+    The Gaunt coefficient obeys the following symmetry rules:
+
+    - invariant under any permutation of the columns
+
+      .. math::
+        \begin{aligned}
+          Y(l_1,l_2,l_3,m_1,m_2,m_3)
+          &=Y(l_3,l_1,l_2,m_3,m_1,m_2) \\
+          &=Y(l_2,l_3,l_1,m_2,m_3,m_1) \\
+          &=Y(l_3,l_2,l_1,m_3,m_2,m_1) \\
+          &=Y(l_1,l_3,l_2,m_1,m_3,m_2) \\
+          &=Y(l_2,l_1,l_3,m_2,m_1,m_3)
+        \end{aligned}
+
+    - invariant under space inflection, i.e.
+
+      .. math::
+          Y(l_1,l_2,l_3,m_1,m_2,m_3)
+          =Y(l_1,l_2,l_3,-m_1,-m_2,-m_3)
+
+    - symmetric with respect to the 72 Regge symmetries as inherited
+      for the `3j` symbols [Regge58]_
+
+    - zero for `l_1`, `l_2`, `l_3` not fulfilling triangle relation
+
+    - zero for violating any one of the conditions: `l_1 \ge |m_1|`,
+      `l_2 \ge |m_2|`, `l_3 \ge |m_3|`
+
+    - non-zero only for an even sum of the `l_i`, i.e.
+      `L = l_1 + l_2 + l_3 = 2n` for `n` in `\mathbb{N}`
+
+    Algorithms
+    ==========
+
+    This function uses the algorithm of [Liberatodebrito82]_ to
+    calculate the value of the Gaunt coefficient exactly. Note that
+    the formula contains alternating sums over large factorials and is
+    therefore unsuitable for finite precision arithmetic and only
+    useful for a computer algebra system [Rasch03]_.
+
+    Authors
+    =======
+
+    Jens Rasch (2009-03-24): initial version for Sage.
+    """
+    l_1, l_2, l_3, m_1, m_2, m_3 = [
+        as_int(i) for i in (l_1, l_2, l_3, m_1, m_2, m_3)]
+
+    if l_1 + l_2 - l_3 < 0:
+        return S.Zero
+    if l_1 - l_2 + l_3 < 0:
+        return S.Zero
+    if -l_1 + l_2 + l_3 < 0:
+        return S.Zero
+    if (m_1 + m_2 + m_3) != 0:
+        return S.Zero
+    if (abs(m_1) > l_1) or (abs(m_2) > l_2) or (abs(m_3) > l_3):
+        return S.Zero
+    bigL, remL = divmod(l_1 + l_2 + l_3, 2)
+    if remL % 2:
+        return S.Zero
+
+    imin = max(-l_3 + l_1 + m_2, -l_3 + l_2 - m_1, 0)
+    imax = min(l_2 + m_2, l_1 - m_1, l_1 + l_2 - l_3)
+
+    _calc_factlist(max(l_1 + l_2 + l_3 + 1, imax + 1))
+
+    ressqrt = sqrt((2 * l_1 + 1) * (2 * l_2 + 1) * (2 * l_3 + 1) * \
+        _Factlist[l_1 - m_1] * _Factlist[l_1 + m_1] * _Factlist[l_2 - m_2] * \
+        _Factlist[l_2 + m_2] * _Factlist[l_3 - m_3] * _Factlist[l_3 + m_3] / \
+        (4*pi))
+
+    prefac = Integer(_Factlist[bigL] * _Factlist[l_2 - l_1 + l_3] *
+                     _Factlist[l_1 - l_2 + l_3] * _Factlist[l_1 + l_2 - l_3])/ \
+        _Factlist[2 * bigL + 1]/ \
+        (_Factlist[bigL - l_1] *
+         _Factlist[bigL - l_2] * _Factlist[bigL - l_3])
+
+    sumres = 0
+    for ii in range(int(imin), int(imax) + 1):
+        den = _Factlist[ii] * _Factlist[ii + l_3 - l_1 - m_2] * \
+            _Factlist[l_2 + m_2 - ii] * _Factlist[l_1 - ii - m_1] * \
+            _Factlist[ii + l_3 - l_2 + m_1] * _Factlist[l_1 + l_2 - l_3 - ii]
+        sumres = sumres + Integer((-1) ** ii) / den
+
+    res = ressqrt * prefac * sumres * Integer((-1) ** (bigL + l_3 + m_1 - m_2))
+    if prec is not None:
+        res = res.n(prec)
+    return res
+
+
+def real_gaunt(l_1, l_2, l_3, mu_1, mu_2, mu_3, prec=None):
+    r"""
+    Calculate the real Gaunt coefficient.
+
+    Explanation
+    ===========
+
+    The real Gaunt coefficient is defined as the integral over three
+    real spherical harmonics:
+
+    .. math::
+        \begin{aligned}
+        \operatorname{RealGaunt}(l_1,l_2,l_3,\mu_1,\mu_2,\mu_3)
+        &=\int Z^{\mu_1}_{l_1}(\Omega)
+         Z^{\mu_2}_{l_2}(\Omega) Z^{\mu_3}_{l_3}(\Omega) \,d\Omega \\
+        \end{aligned}
+
+    Alternatively, it can be defined in terms of the standard Gaunt
+    coefficient by relating the real spherical harmonics to the standard
+    spherical harmonics via a unitary transformation `U`, i.e.
+    `Z^{\mu}_{l}(\Omega)=\sum_{m'}U^{\mu}_{m'}Y^{m'}_{l}(\Omega)` [Homeier96]_.
+    The real Gaunt coefficient is then defined as
+
+    .. math::
+        \begin{aligned}
+        \operatorname{RealGaunt}(l_1,l_2,l_3,\mu_1,\mu_2,\mu_3)
+        &=\int Z^{\mu_1}_{l_1}(\Omega)
+         Z^{\mu_2}_{l_2}(\Omega) Z^{\mu_3}_{l_3}(\Omega) \,d\Omega \\
+        &=\sum_{m'_1 m'_2 m'_3} U^{\mu_1}_{m'_1}U^{\mu_2}_{m'_2}U^{\mu_3}_{m'_3}
+         \operatorname{Gaunt}(l_1,l_2,l_3,m'_1,m'_2,m'_3)
+        \end{aligned}
+
+    The unitary matrix `U` has components
+
+    .. math::
+        \begin{aligned}
+        U^\mu_{m} = \delta_{|\mu||m|}*(\delta_{m0}\delta_{\mu 0} + \frac{1}{\sqrt{2}}\big[\Theta(\mu)\big(\delta_{m\mu}+(-1)^{m}\delta_{m-\mu}\big)
+        +i \Theta(-\mu)\big((-1)^{m}\delta_{m\mu}-\delta_{m-\mu}\big)\big])
+        \end{aligned}
+
+
+    where `\delta_{ij}` is the Kronecker delta symbol and `\Theta` is a step
+    function defined as
+
+    .. math::
+        \begin{aligned}
+        \Theta(x) = \begin{cases} 1 \,\text{for}\, x > 0 \\ 0 \,\text{for}\, x \leq 0 \end{cases}
+        \end{aligned}
+
+    Parameters
+    ==========
+
+    l_1, l_2, l_3, mu_1, mu_2, mu_3 :
+        Integer degree and order
+
+    prec - precision, default: ``None``.
+        Providing a precision can
+        drastically speed up the calculation.
+
+    Returns
+    =======
+
+    Rational number times the square root of a rational number.
+
+    Examples
+    ========
+    >>> from sympy.physics.wigner import real_gaunt
+    >>> real_gaunt(1,1,2,-1,1,-2)
+    sqrt(15)/(10*sqrt(pi))
+    >>> real_gaunt(10,10,20,-9,-9,0,prec=64)
+    -0.00002480019791932209313156167176797577821140084216297395518482071448
+
+    It is an error to use non-integer values for `l` and `\mu`::
+        real_gaunt(2.8,0.5,1.3,0,0,0)
+        Traceback (most recent call last):
+        ...
+        ValueError: l values must be integer
+
+        real_gaunt(2,2,4,0.7,1,-3.4)
+        Traceback (most recent call last):
+        ...
+        ValueError: mu values must be integer
+
+    Notes
+    =====
+
+    The real Gaunt coefficient inherits from the standard Gaunt coefficient,
+    the invariance under any permutation of the pairs `(l_i, \mu_i)` and the
+    requirement that the sum of the `l_i` be even to yield a non-zero value.
+    It also obeys the following symmetry rules:
+
+    - zero for `l_1`, `l_2`, `l_3` not fulfilling the condition
+      `l_1 \in \{l_{\text{max}}, l_{\text{max}}-2, \ldots, l_{\text{min}}\}`,
+      where `l_{\text{max}} = l_2+l_3`,
+
+      .. math::
+          \begin{aligned}
+          l_{\text{min}} = \begin{cases} \kappa(l_2, l_3, \mu_2, \mu_3) & \text{if}\,
+          \kappa(l_2, l_3, \mu_2, \mu_3) + l_{\text{max}}\, \text{is even} \\
+          \kappa(l_2, l_3, \mu_2, \mu_3)+1 & \text{if}\, \kappa(l_2, l_3, \mu_2, \mu_3) +
+          l_{\text{max}}\, \text{is odd}\end{cases}
+          \end{aligned}
+
+      and `\kappa(l_2, l_3, \mu_2, \mu_3) = \max{\big(|l_2-l_3|, \min{\big(|\mu_2+\mu_3|,
+      |\mu_2-\mu_3|\big)}\big)}`
+
+    - zero for an odd number of negative `\mu_i`
+
+    Algorithms
+    ==========
+
+    This function uses the algorithms of [Homeier96]_ and [Rasch03]_ to
+    calculate the value of the real Gaunt coefficient exactly. Note that
+    the formula used in [Rasch03]_ contains alternating sums over large
+    factorials and is therefore unsuitable for finite precision arithmetic
+    and only useful for a computer algebra system [Rasch03]_. However, this
+    function can in principle use any algorithm that computes the Gaunt
+    coefficient, so it is suitable for finite precision arithmetic in so far
+    as the algorithm which computes the Gaunt coefficient is.
+    """
+    l_1, l_2, l_3, mu_1, mu_2, mu_3 = [
+        as_int(i) for i in (l_1, l_2, l_3, mu_1, mu_2, mu_3)]
+
+    # check for quick exits
+    if sum(1 for i in (mu_1, mu_2, mu_3) if i < 0) % 2:
+        return S.Zero  # odd number of negative m
+    if (l_1 + l_2 + l_3) % 2:
+        return S.Zero  # sum of l is odd
+    lmax = l_2 + l_3
+    lmin = max(abs(l_2 - l_3), min(abs(mu_2 + mu_3), abs(mu_2 - mu_3)))
+    if (lmin + lmax) % 2:
+        lmin += 1
+    if lmin not in range(lmax, lmin - 2, -2):
+        return S.Zero
+
+    kron_del = lambda i, j: 1 if i == j else 0
+    s = lambda e: -1 if e % 2 else 1  #  (-1)**e to give +/-1, avoiding float when e<0
+
+    t = lambda x: 1 if x > 0 else 0
+    A = lambda mu, m: t(-mu) * (s(m) * kron_del(m, mu) - kron_del(m, -mu))
+    B = lambda mu, m: t(mu) * (kron_del(m, mu) + s(m) * kron_del(m, -mu))
+    U = lambda mu, m: kron_del(abs(mu), abs(m)) * (kron_del(mu, 0) * kron_del(m, 0) + (B(mu, m) + I * A(mu, m))/sqrt(2))
+
+    ugnt = 0
+    for m1 in range(-l_1, l_1+1):
+        U1 = U(mu_1, m1)
+        for m2 in range(-l_2, l_2+1):
+            U2 = U(mu_2, m2)
+            U3 = U(mu_3,-m1-m2)
+            ugnt = ugnt + re(U1*U2*U3)*gaunt(l_1, l_2, l_3, m1, m2, -m1 - m2, prec=prec)
+
+    return ugnt
+
+
+class Wigner3j(Function):
+
+    def doit(self, **hints):
+        if all(obj.is_number for obj in self.args):
+            return wigner_3j(*self.args)
+        else:
+            return self
+
+def dot_rot_grad_Ynm(j, p, l, m, theta, phi):
+    r"""
+    Returns dot product of rotational gradients of spherical harmonics.
+
+    Explanation
+    ===========
+
+    This function returns the right hand side of the following expression:
+
+    .. math ::
+        \vec{R}Y{_j^{p}} \cdot \vec{R}Y{_l^{m}} = (-1)^{m+p}
+        \sum\limits_{k=|l-j|}^{l+j}Y{_k^{m+p}}  * \alpha_{l,m,j,p,k} *
+        \frac{1}{2} (k^2-j^2-l^2+k-j-l)
+
+
+    Arguments
+    =========
+
+    j, p, l, m .... indices in spherical harmonics (expressions or integers)
+    theta, phi .... angle arguments in spherical harmonics
+
+    Example
+    =======
+
+    >>> from sympy import symbols
+    >>> from sympy.physics.wigner import dot_rot_grad_Ynm
+    >>> theta, phi = symbols("theta phi")
+    >>> dot_rot_grad_Ynm(3, 2, 2, 0, theta, phi).doit()
+    3*sqrt(55)*Ynm(5, 2, theta, phi)/(11*sqrt(pi))
+
+    """
+    j = sympify(j)
+    p = sympify(p)
+    l = sympify(l)
+    m = sympify(m)
+    theta = sympify(theta)
+    phi = sympify(phi)
+    k = Dummy("k")
+
+    def alpha(l,m,j,p,k):
+        return sqrt((2*l+1)*(2*j+1)*(2*k+1)/(4*pi)) * \
+                Wigner3j(j, l, k, S.Zero, S.Zero, S.Zero) * \
+                Wigner3j(j, l, k, p, m, -m-p)
+
+    return (S.NegativeOne)**(m+p) * Sum(Ynm(k, m+p, theta, phi) * alpha(l,m,j,p,k) / 2 \
+        *(k**2-j**2-l**2+k-j-l), (k, abs(l-j), l+j))
+
+
+def wigner_d_small(J, beta):
+    """Return the small Wigner d matrix for angular momentum J.
+
+    Explanation
+    ===========
+
+    J : An integer, half-integer, or SymPy symbol for the total angular
+        momentum of the angular momentum space being rotated.
+    beta : A real number representing the Euler angle of rotation about
+        the so-called line of nodes. See [Edmonds74]_.
+
+    Returns
+    =======
+
+    A matrix representing the corresponding Euler angle rotation( in the basis
+    of eigenvectors of `J_z`).
+
+    .. math ::
+        \\mathcal{d}_{\\beta} = \\exp\\big( \\frac{i\\beta}{\\hbar} J_y\\big)
+
+    such that
+
+    .. math ::
+        d^{(J)}_{m',m}(\\beta) = \\mathtt{wigner\\_d\\_small(J,beta)[J-mprime,J-m]}
+
+    The components are calculated using the general form [Edmonds74]_,
+    equation 4.1.15.
+
+    Examples
+    ========
+
+    >>> from sympy import Integer, symbols, pi, pprint
+    >>> from sympy.physics.wigner import wigner_d_small
+    >>> half = 1/Integer(2)
+    >>> beta = symbols("beta", real=True)
+    >>> pprint(wigner_d_small(half, beta), use_unicode=True)
+    ⎡   ⎛β⎞      ⎛β⎞⎤
+    ⎢cos⎜─⎟   sin⎜─⎟⎥
+    ⎢   ⎝2⎠      ⎝2⎠⎥
+    ⎢               ⎥
+    ⎢    ⎛β⎞     ⎛β⎞⎥
+    ⎢-sin⎜─⎟  cos⎜─⎟⎥
+    ⎣    ⎝2⎠     ⎝2⎠⎦
+
+    >>> pprint(wigner_d_small(2*half, beta), use_unicode=True)
+    ⎡        2⎛β⎞              ⎛β⎞    ⎛β⎞           2⎛β⎞     ⎤
+    ⎢     cos ⎜─⎟        √2⋅sin⎜─⎟⋅cos⎜─⎟        sin ⎜─⎟     ⎥
+    ⎢         ⎝2⎠              ⎝2⎠    ⎝2⎠            ⎝2⎠     ⎥
+    ⎢                                                        ⎥
+    ⎢       ⎛β⎞    ⎛β⎞       2⎛β⎞      2⎛β⎞        ⎛β⎞    ⎛β⎞⎥
+    ⎢-√2⋅sin⎜─⎟⋅cos⎜─⎟  - sin ⎜─⎟ + cos ⎜─⎟  √2⋅sin⎜─⎟⋅cos⎜─⎟⎥
+    ⎢       ⎝2⎠    ⎝2⎠        ⎝2⎠       ⎝2⎠        ⎝2⎠    ⎝2⎠⎥
+    ⎢                                                        ⎥
+    ⎢        2⎛β⎞               ⎛β⎞    ⎛β⎞          2⎛β⎞     ⎥
+    ⎢     sin ⎜─⎟        -√2⋅sin⎜─⎟⋅cos⎜─⎟       cos ⎜─⎟     ⎥
+    ⎣         ⎝2⎠               ⎝2⎠    ⎝2⎠           ⎝2⎠     ⎦
+
+    From table 4 in [Edmonds74]_
+
+    >>> pprint(wigner_d_small(half, beta).subs({beta:pi/2}), use_unicode=True)
+    ⎡ √2   √2⎤
+    ⎢ ──   ──⎥
+    ⎢ 2    2 ⎥
+    ⎢        ⎥
+    ⎢-√2   √2⎥
+    ⎢────  ──⎥
+    ⎣ 2    2 ⎦
+
+    >>> pprint(wigner_d_small(2*half, beta).subs({beta:pi/2}),
+    ... use_unicode=True)
+    ⎡       √2      ⎤
+    ⎢1/2    ──   1/2⎥
+    ⎢       2       ⎥
+    ⎢               ⎥
+    ⎢-√2         √2 ⎥
+    ⎢────   0    ── ⎥
+    ⎢ 2          2  ⎥
+    ⎢               ⎥
+    ⎢      -√2      ⎥
+    ⎢1/2   ────  1/2⎥
+    ⎣       2       ⎦
+
+    >>> pprint(wigner_d_small(3*half, beta).subs({beta:pi/2}),
+    ... use_unicode=True)
+    ⎡ √2    √6    √6   √2⎤
+    ⎢ ──    ──    ──   ──⎥
+    ⎢ 4     4     4    4 ⎥
+    ⎢                    ⎥
+    ⎢-√6   -√2    √2   √6⎥
+    ⎢────  ────   ──   ──⎥
+    ⎢ 4     4     4    4 ⎥
+    ⎢                    ⎥
+    ⎢ √6   -√2   -√2   √6⎥
+    ⎢ ──   ────  ────  ──⎥
+    ⎢ 4     4     4    4 ⎥
+    ⎢                    ⎥
+    ⎢-√2    √6   -√6   √2⎥
+    ⎢────   ──   ────  ──⎥
+    ⎣ 4     4     4    4 ⎦
+
+    >>> pprint(wigner_d_small(4*half, beta).subs({beta:pi/2}),
+    ... use_unicode=True)
+    ⎡             √6            ⎤
+    ⎢1/4   1/2    ──   1/2   1/4⎥
+    ⎢             4             ⎥
+    ⎢                           ⎥
+    ⎢-1/2  -1/2   0    1/2   1/2⎥
+    ⎢                           ⎥
+    ⎢ √6                     √6 ⎥
+    ⎢ ──    0    -1/2   0    ── ⎥
+    ⎢ 4                      4  ⎥
+    ⎢                           ⎥
+    ⎢-1/2  1/2    0    -1/2  1/2⎥
+    ⎢                           ⎥
+    ⎢             √6            ⎥
+    ⎢1/4   -1/2   ──   -1/2  1/4⎥
+    ⎣             4             ⎦
+
+    """
+    M = [J-i for i in range(2*J+1)]
+    d = zeros(2*J+1)
+
+    # Mi corresponds to Edmonds' $m'$, and Mj to $m$.
+    for i, Mi in enumerate(M):
+        for j, Mj in enumerate(M):
+
+            # We get the maximum and minimum value of sigma.
+            sigmamax = min([J-Mi, J-Mj])
+            sigmamin = max([0, -Mi-Mj])
+
+            dij = sqrt(factorial(J+Mi)*factorial(J-Mi) /
+                       factorial(J+Mj)/factorial(J-Mj))
+            terms = [(-1)**(J-Mi-s) *
+                     binomial(J+Mj, J-Mi-s) *
+                     binomial(J-Mj, s) *
+                     cos(beta/2)**(2*s+Mi+Mj) *
+                     sin(beta/2)**(2*J-2*s-Mj-Mi)
+                     for s in range(sigmamin, sigmamax+1)]
+
+            d[i, j] = dij*Add(*terms)
+
+    return ImmutableMatrix(d)
+
+
+def wigner_d(J, alpha, beta, gamma):
+    """Return the Wigner D matrix for angular momentum J.
+
+    Explanation
+    ===========
+
+    J :
+        An integer, half-integer, or SymPy symbol for the total angular
+        momentum of the angular momentum space being rotated.
+    alpha, beta, gamma - Real numbers representing the Euler.
+        Angles of rotation about the so-called figure axis, line of nodes,
+        and vertical. See [Edmonds74]_, however note that the symbols alpha
+        and gamma are swapped in this implementation.
+
+    Returns
+    =======
+
+    A matrix representing the corresponding Euler angle rotation (in the basis
+    of eigenvectors of `J_z`).
+
+    .. math ::
+        \\mathcal{D}_{\\alpha \\beta \\gamma} =
+        \\exp\\big( \\frac{i\\alpha}{\\hbar} J_z\\big)
+        \\exp\\big( \\frac{i\\beta}{\\hbar} J_y\\big)
+        \\exp\\big( \\frac{i\\gamma}{\\hbar} J_z\\big)
+
+    such that
+
+    .. math ::
+        \\mathcal{D}^{(J)}_{m',m}(\\alpha, \\beta, \\gamma) =
+        \\mathtt{wigner_d(J, alpha, beta, gamma)[J-mprime,J-m]}
+
+    The components are calculated using the general form [Edmonds74]_,
+    equation 4.1.12, however note that the angles alpha and gamma are swapped
+    in this implementation.
+
+    Examples
+    ========
+
+    The simplest possible example:
+
+    >>> from sympy.physics.wigner import wigner_d
+    >>> from sympy import Integer, symbols, pprint
+    >>> half = 1/Integer(2)
+    >>> alpha, beta, gamma = symbols("alpha, beta, gamma", real=True)
+    >>> pprint(wigner_d(half, alpha, beta, gamma), use_unicode=True)
+    ⎡  ⅈ⋅α  ⅈ⋅γ             ⅈ⋅α  -ⅈ⋅γ         ⎤
+    ⎢  ───  ───             ───  ─────        ⎥
+    ⎢   2    2     ⎛β⎞       2     2      ⎛β⎞ ⎥
+    ⎢ ℯ   ⋅ℯ   ⋅cos⎜─⎟     ℯ   ⋅ℯ     ⋅sin⎜─⎟ ⎥
+    ⎢              ⎝2⎠                    ⎝2⎠ ⎥
+    ⎢                                         ⎥
+    ⎢  -ⅈ⋅α   ⅈ⋅γ          -ⅈ⋅α   -ⅈ⋅γ        ⎥
+    ⎢  ─────  ───          ─────  ─────       ⎥
+    ⎢    2     2     ⎛β⎞     2      2      ⎛β⎞⎥
+    ⎢-ℯ     ⋅ℯ   ⋅sin⎜─⎟  ℯ     ⋅ℯ     ⋅cos⎜─⎟⎥
+    ⎣                ⎝2⎠                   ⎝2⎠⎦
+
+    """
+    d = wigner_d_small(J, beta)
+    M = [J-i for i in range(2*J+1)]
+    # Mi corresponds to Edmonds' $m'$, and Mj to $m$.
+    D = [[exp(I*Mi*alpha)*d[i, j]*exp(I*Mj*gamma)
+          for j, Mj in enumerate(M)] for i, Mi in enumerate(M)]
+    return ImmutableMatrix(D)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/pretty/__pycache__/pretty_symbology.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/pretty/__pycache__/pretty_symbology.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b502d42b5704a76859814cd60752529ca1fa9003
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/pretty/__pycache__/pretty_symbology.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/pretty/tests/test_pretty.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/pretty/tests/test_pretty.py
new file mode 100644
index 0000000000000000000000000000000000000000..1cca79bd1dc5c3ba81483c8fe2e87c35926d1b94
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/pretty/tests/test_pretty.py
@@ -0,0 +1,7972 @@
+# -*- coding: utf-8 -*-
+from sympy.concrete.products import Product
+from sympy.concrete.summations import Sum
+from sympy.core.add import Add
+from sympy.core.basic import Basic
+from sympy.core.containers import (Dict, Tuple)
+from sympy.core.function import (Derivative, Function, Lambda, Subs)
+from sympy.core.mul import Mul
+from sympy.core import (EulerGamma, GoldenRatio, Catalan)
+from sympy.core.numbers import (I, Rational, oo, pi)
+from sympy.core.power import Pow
+from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne)
+from sympy.core.singleton import S
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.functions.elementary.complexes import conjugate
+from sympy.functions.elementary.exponential import LambertW
+from sympy.functions.special.bessel import (airyai, airyaiprime, airybi, airybiprime)
+from sympy.functions.special.delta_functions import Heaviside
+from sympy.functions.special.error_functions import (fresnelc, fresnels)
+from sympy.functions.special.singularity_functions import SingularityFunction
+from sympy.functions.special.zeta_functions import dirichlet_eta
+from sympy.geometry.line import (Ray, Segment)
+from sympy.integrals.integrals import Integral
+from sympy.logic.boolalg import (And, Equivalent, ITE, Implies, Nand, Nor, Not, Or, Xor)
+from sympy.matrices.dense import (Matrix, diag)
+from sympy.matrices.expressions.slice import MatrixSlice
+from sympy.matrices.expressions.trace import Trace
+from sympy.polys.domains.finitefield import FF
+from sympy.polys.domains.integerring import ZZ
+from sympy.polys.domains.rationalfield import QQ
+from sympy.polys.domains.realfield import RR
+from sympy.polys.orderings import (grlex, ilex)
+from sympy.polys.polytools import groebner
+from sympy.polys.rootoftools import (RootSum, rootof)
+from sympy.series.formal import fps
+from sympy.series.fourier import fourier_series
+from sympy.series.limits import Limit
+from sympy.series.order import O
+from sympy.series.sequences import (SeqAdd, SeqFormula, SeqMul, SeqPer)
+from sympy.sets.contains import Contains
+from sympy.sets.fancysets import Range
+from sympy.sets.sets import (Complement, FiniteSet, Intersection, Interval, Union)
+from sympy.codegen.ast import (Assignment, AddAugmentedAssignment,
+    SubAugmentedAssignment, MulAugmentedAssignment, DivAugmentedAssignment, ModAugmentedAssignment)
+from sympy.core.expr import UnevaluatedExpr
+from sympy.physics.quantum.trace import Tr
+
+from sympy.functions import (Abs, Chi, Ci, Ei, KroneckerDelta,
+    Piecewise, Shi, Si, atan2, beta, binomial, catalan, ceiling, cos,
+    euler, exp, expint, factorial, factorial2, floor, gamma, hyper, log,
+    meijerg, sin, sqrt, subfactorial, tan, uppergamma, lerchphi, polylog,
+    elliptic_k, elliptic_f, elliptic_e, elliptic_pi, DiracDelta, bell,
+    bernoulli, fibonacci, tribonacci, lucas, stieltjes, mathieuc, mathieus,
+    mathieusprime, mathieucprime)
+
+from sympy.matrices import (Adjoint, Inverse, MatrixSymbol, Transpose,
+                            KroneckerProduct, BlockMatrix, OneMatrix, ZeroMatrix)
+from sympy.matrices.expressions import hadamard_power
+
+from sympy.physics import mechanics
+from sympy.physics.control.lti import (TransferFunction, Feedback, TransferFunctionMatrix,
+    Series, Parallel, MIMOSeries, MIMOParallel, MIMOFeedback, StateSpace)
+from sympy.physics.units import joule, degree
+from sympy.printing.pretty import pprint, pretty as xpretty
+from sympy.printing.pretty.pretty_symbology import center_accent, is_combining, center
+from sympy.sets.conditionset import ConditionSet
+
+from sympy.sets import ImageSet, ProductSet
+from sympy.sets.setexpr import SetExpr
+from sympy.stats.crv_types import Normal
+from sympy.stats.symbolic_probability import (Covariance, Expectation,
+                                              Probability, Variance)
+from sympy.tensor.array import (ImmutableDenseNDimArray, ImmutableSparseNDimArray,
+                                MutableDenseNDimArray, MutableSparseNDimArray, tensorproduct)
+from sympy.tensor.functions import TensorProduct
+from sympy.tensor.tensor import (TensorIndexType, tensor_indices, TensorHead,
+                                 TensorElement, tensor_heads)
+
+from sympy.testing.pytest import raises, _both_exp_pow, warns_deprecated_sympy
+
+from sympy.vector import CoordSys3D, Gradient, Curl, Divergence, Dot, Cross, Laplacian
+
+
+
+import sympy as sym
+class lowergamma(sym.lowergamma):
+    pass   # testing notation inheritance by a subclass with same name
+
+a, b, c, d, x, y, z, k, n, s, p = symbols('a,b,c,d,x,y,z,k,n,s,p')
+f = Function("f")
+th = Symbol('theta')
+ph = Symbol('phi')
+
+"""
+Expressions whose pretty-printing is tested here:
+(A '#' to the right of an expression indicates that its various acceptable
+orderings are accounted for by the tests.)
+
+
+BASIC EXPRESSIONS:
+
+oo
+(x**2)
+1/x
+y*x**-2
+x**Rational(-5,2)
+(-2)**x
+Pow(3, 1, evaluate=False)
+(x**2 + x + 1)  #
+1-x  #
+1-2*x  #
+x/y
+-x/y
+(x+2)/y  #
+(1+x)*y  #3
+-5*x/(x+10)  # correct placement of negative sign
+1 - Rational(3,2)*(x+1)
+-(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5) # issue 5524
+
+
+ORDERING:
+
+x**2 + x + 1
+1 - x
+1 - 2*x
+2*x**4 + y**2 - x**2 + y**3
+
+
+RELATIONAL:
+
+Eq(x, y)
+Lt(x, y)
+Gt(x, y)
+Le(x, y)
+Ge(x, y)
+Ne(x/(y+1), y**2)  #
+
+
+RATIONAL NUMBERS:
+
+y*x**-2
+y**Rational(3,2) * x**Rational(-5,2)
+sin(x)**3/tan(x)**2
+
+
+FUNCTIONS (ABS, CONJ, EXP, FUNCTION BRACES, FACTORIAL, FLOOR, CEILING):
+
+(2*x + exp(x))  #
+Abs(x)
+Abs(x/(x**2+1)) #
+Abs(1 / (y - Abs(x)))
+factorial(n)
+factorial(2*n)
+subfactorial(n)
+subfactorial(2*n)
+factorial(factorial(factorial(n)))
+factorial(n+1) #
+conjugate(x)
+conjugate(f(x+1)) #
+f(x)
+f(x, y)
+f(x/(y+1), y) #
+f(x**x**x**x**x**x)
+sin(x)**2
+conjugate(a+b*I)
+conjugate(exp(a+b*I))
+conjugate( f(1 + conjugate(f(x))) ) #
+f(x/(y+1), y)  # denom of first arg
+floor(1 / (y - floor(x)))
+ceiling(1 / (y - ceiling(x)))
+
+
+SQRT:
+
+sqrt(2)
+2**Rational(1,3)
+2**Rational(1,1000)
+sqrt(x**2 + 1)
+(1 + sqrt(5))**Rational(1,3)
+2**(1/x)
+sqrt(2+pi)
+(2+(1+x**2)/(2+x))**Rational(1,4)+(1+x**Rational(1,1000))/sqrt(3+x**2)
+
+
+DERIVATIVES:
+
+Derivative(log(x), x, evaluate=False)
+Derivative(log(x), x, evaluate=False) + x  #
+Derivative(log(x) + x**2, x, y, evaluate=False)
+Derivative(2*x*y, y, x, evaluate=False) + x**2  #
+beta(alpha).diff(alpha)
+
+
+INTEGRALS:
+
+Integral(log(x), x)
+Integral(x**2, x)
+Integral((sin(x))**2 / (tan(x))**2)
+Integral(x**(2**x), x)
+Integral(x**2, (x,1,2))
+Integral(x**2, (x,Rational(1,2),10))
+Integral(x**2*y**2, x,y)
+Integral(x**2, (x, None, 1))
+Integral(x**2, (x, 1, None))
+Integral(sin(th)/cos(ph), (th,0,pi), (ph, 0, 2*pi))
+
+
+MATRICES:
+
+Matrix([[x**2+1, 1], [y, x+y]])  #
+Matrix([[x/y, y, th], [0, exp(I*k*ph), 1]])
+
+
+PIECEWISE:
+
+Piecewise((x,x<1),(x**2,True))
+
+ITE:
+
+ITE(x, y, z)
+
+SEQUENCES (TUPLES, LISTS, DICTIONARIES):
+
+()
+[]
+{}
+(1/x,)
+[x**2, 1/x, x, y, sin(th)**2/cos(ph)**2]
+(x**2, 1/x, x, y, sin(th)**2/cos(ph)**2)
+{x: sin(x)}
+{1/x: 1/y, x: sin(x)**2}  #
+[x**2]
+(x**2,)
+{x**2: 1}
+
+
+LIMITS:
+
+Limit(x, x, oo)
+Limit(x**2, x, 0)
+Limit(1/x, x, 0)
+Limit(sin(x)/x, x, 0)
+
+
+UNITS:
+
+joule => kg*m**2/s
+
+
+SUBS:
+
+Subs(f(x), x, ph**2)
+Subs(f(x).diff(x), x, 0)
+Subs(f(x).diff(x)/y, (x, y), (0, Rational(1, 2)))
+
+
+ORDER:
+
+O(1)
+O(1/x)
+O(x**2 + y**2)
+
+"""
+
+
+def pretty(expr, order=None):
+    """ASCII pretty-printing"""
+    return xpretty(expr, order=order, use_unicode=False, wrap_line=False)
+
+
+def upretty(expr, order=None):
+    """Unicode pretty-printing"""
+    return xpretty(expr, order=order, use_unicode=True, wrap_line=False)
+
+
+def test_pretty_ascii_str():
+    assert pretty( 'xxx' ) == 'xxx'
+    assert pretty( "xxx" ) == 'xxx'
+    assert pretty( 'xxx\'xxx' ) == 'xxx\'xxx'
+    assert pretty( 'xxx"xxx' ) == 'xxx\"xxx'
+    assert pretty( 'xxx\"xxx' ) == 'xxx\"xxx'
+    assert pretty( "xxx'xxx" ) == 'xxx\'xxx'
+    assert pretty( "xxx\'xxx" ) == 'xxx\'xxx'
+    assert pretty( "xxx\"xxx" ) == 'xxx\"xxx'
+    assert pretty( "xxx\"xxx\'xxx" ) == 'xxx"xxx\'xxx'
+    assert pretty( "xxx\nxxx" ) == 'xxx\nxxx'
+
+
+def test_pretty_unicode_str():
+    assert pretty( 'xxx' ) == 'xxx'
+    assert pretty( 'xxx' ) == 'xxx'
+    assert pretty( 'xxx\'xxx' ) == 'xxx\'xxx'
+    assert pretty( 'xxx"xxx' ) == 'xxx\"xxx'
+    assert pretty( 'xxx\"xxx' ) == 'xxx\"xxx'
+    assert pretty( "xxx'xxx" ) == 'xxx\'xxx'
+    assert pretty( "xxx\'xxx" ) == 'xxx\'xxx'
+    assert pretty( "xxx\"xxx" ) == 'xxx\"xxx'
+    assert pretty( "xxx\"xxx\'xxx" ) == 'xxx"xxx\'xxx'
+    assert pretty( "xxx\nxxx" ) == 'xxx\nxxx'
+
+
+def test_upretty_greek():
+    assert upretty( oo ) == '∞'
+    assert upretty( Symbol('alpha^+_1') ) == 'α⁺₁'
+    assert upretty( Symbol('beta') ) == 'β'
+    assert upretty(Symbol('lambda')) == 'λ'
+
+
+def test_upretty_multiindex():
+    assert upretty( Symbol('beta12') ) == 'β₁₂'
+    assert upretty( Symbol('Y00') ) == 'Y₀₀'
+    assert upretty( Symbol('Y_00') ) == 'Y₀₀'
+    assert upretty( Symbol('F^+-') ) == 'F⁺⁻'
+
+
+def test_upretty_sub_super():
+    assert upretty( Symbol('beta_1_2') ) == 'β₁ ₂'
+    assert upretty( Symbol('beta^1^2') ) == 'β¹ ²'
+    assert upretty( Symbol('beta_1^2') ) == 'β²₁'
+    assert upretty( Symbol('beta_10_20') ) == 'β₁₀ ₂₀'
+    assert upretty( Symbol('beta_ax_gamma^i') ) == 'βⁱₐₓ ᵧ'
+    assert upretty( Symbol("F^1^2_3_4") ) == 'F¹ ²₃ ₄'
+    assert upretty( Symbol("F_1_2^3^4") ) == 'F³ ⁴₁ ₂'
+    assert upretty( Symbol("F_1_2_3_4") ) == 'F₁ ₂ ₃ ₄'
+    assert upretty( Symbol("F^1^2^3^4") ) == 'F¹ ² ³ ⁴'
+
+
+def test_upretty_subs_missing_in_24():
+    assert upretty( Symbol('F_beta') ) == 'Fᵦ'
+    assert upretty( Symbol('F_gamma') ) == 'Fᵧ'
+    assert upretty( Symbol('F_rho') ) == 'Fᵨ'
+    assert upretty( Symbol('F_phi') ) == 'Fᵩ'
+    assert upretty( Symbol('F_chi') ) == 'Fᵪ'
+
+    assert upretty( Symbol('F_a') ) == 'Fₐ'
+    assert upretty( Symbol('F_e') ) == 'Fₑ'
+    assert upretty( Symbol('F_i') ) == 'Fᵢ'
+    assert upretty( Symbol('F_o') ) == 'Fₒ'
+    assert upretty( Symbol('F_u') ) == 'Fᵤ'
+    assert upretty( Symbol('F_r') ) == 'Fᵣ'
+    assert upretty( Symbol('F_v') ) == 'Fᵥ'
+    assert upretty( Symbol('F_x') ) == 'Fₓ'
+
+
+def test_missing_in_2X_issue_9047():
+    assert upretty( Symbol('F_h') ) == 'Fₕ'
+    assert upretty( Symbol('F_k') ) == 'Fₖ'
+    assert upretty( Symbol('F_l') ) == 'Fₗ'
+    assert upretty( Symbol('F_m') ) == 'Fₘ'
+    assert upretty( Symbol('F_n') ) == 'Fₙ'
+    assert upretty( Symbol('F_p') ) == 'Fₚ'
+    assert upretty( Symbol('F_s') ) == 'Fₛ'
+    assert upretty( Symbol('F_t') ) == 'Fₜ'
+
+
+def test_upretty_modifiers():
+    # Accents
+    assert upretty( Symbol('Fmathring') ) == 'F̊'
+    assert upretty( Symbol('Fddddot') ) == 'F⃜'
+    assert upretty( Symbol('Fdddot') ) == 'F⃛'
+    assert upretty( Symbol('Fddot') ) == 'F̈'
+    assert upretty( Symbol('Fdot') ) == 'Ḟ'
+    assert upretty( Symbol('Fcheck') ) == 'F̌'
+    assert upretty( Symbol('Fbreve') ) == 'F̆'
+    assert upretty( Symbol('Facute') ) == 'F́'
+    assert upretty( Symbol('Fgrave') ) == 'F̀'
+    assert upretty( Symbol('Ftilde') ) == 'F̃'
+    assert upretty( Symbol('Fhat') ) == 'F̂'
+    assert upretty( Symbol('Fbar') ) == 'F̅'
+    assert upretty( Symbol('Fvec') ) == 'F⃗'
+    assert upretty( Symbol('Fprime') ) == 'F′'
+    assert upretty( Symbol('Fprm') ) == 'F′'
+    # No faces are actually implemented, but test to make sure the modifiers are stripped
+    assert upretty( Symbol('Fbold') ) == 'Fbold'
+    assert upretty( Symbol('Fbm') ) == 'Fbm'
+    assert upretty( Symbol('Fcal') ) == 'Fcal'
+    assert upretty( Symbol('Fscr') ) == 'Fscr'
+    assert upretty( Symbol('Ffrak') ) == 'Ffrak'
+    # Brackets
+    assert upretty( Symbol('Fnorm') ) == '‖F‖'
+    assert upretty( Symbol('Favg') ) == '⟨F⟩'
+    assert upretty( Symbol('Fabs') ) == '|F|'
+    assert upretty( Symbol('Fmag') ) == '|F|'
+    # Combinations
+    assert upretty( Symbol('xvecdot') ) == 'x⃗̇'
+    assert upretty( Symbol('xDotVec') ) == 'ẋ⃗'
+    assert upretty( Symbol('xHATNorm') ) == '‖x̂‖'
+    assert upretty( Symbol('xMathring_yCheckPRM__zbreveAbs') ) == 'x̊_y̌′__|z̆|'
+    assert upretty( Symbol('alphadothat_nVECDOT__tTildePrime') ) == 'α̇̂_n⃗̇__t̃′'
+    assert upretty( Symbol('x_dot') ) == 'x_dot'
+    assert upretty( Symbol('x__dot') ) == 'x__dot'
+
+
+def test_pretty_Cycle():
+    from sympy.combinatorics.permutations import Cycle
+    assert pretty(Cycle(1, 2)) == '(1 2)'
+    assert pretty(Cycle(2)) == '(2)'
+    assert pretty(Cycle(1, 3)(4, 5)) == '(1 3)(4 5)'
+    assert pretty(Cycle()) == '()'
+
+
+def test_pretty_Permutation():
+    from sympy.combinatorics.permutations import Permutation
+    p1 = Permutation(1, 2)(3, 4)
+    assert xpretty(p1, perm_cyclic=True, use_unicode=True) == "(1 2)(3 4)"
+    assert xpretty(p1, perm_cyclic=True, use_unicode=False) == "(1 2)(3 4)"
+    assert xpretty(p1, perm_cyclic=False, use_unicode=True) == \
+    '⎛0 1 2 3 4⎞\n'\
+    '⎝0 2 1 4 3⎠'
+    assert xpretty(p1, perm_cyclic=False, use_unicode=False) == \
+    "/0 1 2 3 4\\\n"\
+    "\\0 2 1 4 3/"
+
+    with warns_deprecated_sympy():
+        old_print_cyclic = Permutation.print_cyclic
+        Permutation.print_cyclic = False
+        assert xpretty(p1, use_unicode=True) == \
+        '⎛0 1 2 3 4⎞\n'\
+        '⎝0 2 1 4 3⎠'
+        assert xpretty(p1, use_unicode=False) == \
+        "/0 1 2 3 4\\\n"\
+        "\\0 2 1 4 3/"
+        Permutation.print_cyclic = old_print_cyclic
+
+
+def test_pretty_basic():
+    assert pretty( -Rational(1)/2 ) == '-1/2'
+    assert pretty( -Rational(13)/22 ) == \
+"""\
+-13 \n\
+----\n\
+ 22 \
+"""
+    expr = oo
+    ascii_str = \
+"""\
+oo\
+"""
+    ucode_str = \
+"""\
+∞\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = (x**2)
+    ascii_str = \
+"""\
+ 2\n\
+x \
+"""
+    ucode_str = \
+"""\
+ 2\n\
+x \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = 1/x
+    ascii_str = \
+"""\
+1\n\
+-\n\
+x\
+"""
+    ucode_str = \
+"""\
+1\n\
+─\n\
+x\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    # not the same as 1/x
+    expr = x**-1.0
+    ascii_str = \
+"""\
+ -1.0\n\
+x    \
+"""
+    ucode_str = \
+"""\
+ -1.0\n\
+x    \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    # see issue #2860
+    expr = Pow(S(2), -1.0, evaluate=False)
+    ascii_str = \
+"""\
+ -1.0\n\
+2    \
+"""
+    ucode_str = \
+"""\
+ -1.0\n\
+2    \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = y*x**-2
+    ascii_str = \
+"""\
+y \n\
+--\n\
+ 2\n\
+x \
+"""
+    ucode_str = \
+"""\
+y \n\
+──\n\
+ 2\n\
+x \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    #see issue #14033
+    expr = x**Rational(1, 3)
+    ascii_str = \
+"""\
+ 1/3\n\
+x   \
+"""
+    ucode_str = \
+"""\
+ 1/3\n\
+x   \
+"""
+    assert xpretty(expr, use_unicode=False, wrap_line=False,\
+    root_notation = False) == ascii_str
+    assert xpretty(expr, use_unicode=True, wrap_line=False,\
+    root_notation = False) == ucode_str
+
+    expr = x**Rational(-5, 2)
+    ascii_str = \
+"""\
+ 1  \n\
+----\n\
+ 5/2\n\
+x   \
+"""
+    ucode_str = \
+"""\
+ 1  \n\
+────\n\
+ 5/2\n\
+x   \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = (-2)**x
+    ascii_str = \
+"""\
+    x\n\
+(-2) \
+"""
+    ucode_str = \
+"""\
+    x\n\
+(-2) \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    # See issue 4923
+    expr = Pow(3, 1, evaluate=False)
+    ascii_str = \
+"""\
+ 1\n\
+3 \
+"""
+    ucode_str = \
+"""\
+ 1\n\
+3 \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = (x**2 + x + 1)
+    ascii_str_1 = \
+"""\
+         2\n\
+1 + x + x \
+"""
+    ascii_str_2 = \
+"""\
+ 2        \n\
+x  + x + 1\
+"""
+    ascii_str_3 = \
+"""\
+ 2        \n\
+x  + 1 + x\
+"""
+    ucode_str_1 = \
+"""\
+         2\n\
+1 + x + x \
+"""
+    ucode_str_2 = \
+"""\
+ 2        \n\
+x  + x + 1\
+"""
+    ucode_str_3 = \
+"""\
+ 2        \n\
+x  + 1 + x\
+"""
+    assert pretty(expr) in [ascii_str_1, ascii_str_2, ascii_str_3]
+    assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3]
+
+    expr = 1 - x
+    ascii_str_1 = \
+"""\
+1 - x\
+"""
+    ascii_str_2 = \
+"""\
+-x + 1\
+"""
+    ucode_str_1 = \
+"""\
+1 - x\
+"""
+    ucode_str_2 = \
+"""\
+-x + 1\
+"""
+    assert pretty(expr) in [ascii_str_1, ascii_str_2]
+    assert upretty(expr) in [ucode_str_1, ucode_str_2]
+
+    expr = 1 - 2*x
+    ascii_str_1 = \
+"""\
+1 - 2*x\
+"""
+    ascii_str_2 = \
+"""\
+-2*x + 1\
+"""
+    ucode_str_1 = \
+"""\
+1 - 2⋅x\
+"""
+    ucode_str_2 = \
+"""\
+-2⋅x + 1\
+"""
+    assert pretty(expr) in [ascii_str_1, ascii_str_2]
+    assert upretty(expr) in [ucode_str_1, ucode_str_2]
+
+    expr = x/y
+    ascii_str = \
+"""\
+x\n\
+-\n\
+y\
+"""
+    ucode_str = \
+"""\
+x\n\
+─\n\
+y\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = -x/y
+    ascii_str = \
+"""\
+-x \n\
+---\n\
+ y \
+"""
+    ucode_str = \
+"""\
+-x \n\
+───\n\
+ y \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = (x + 2)/y
+    ascii_str_1 = \
+"""\
+2 + x\n\
+-----\n\
+  y  \
+"""
+    ascii_str_2 = \
+"""\
+x + 2\n\
+-----\n\
+  y  \
+"""
+    ucode_str_1 = \
+"""\
+2 + x\n\
+─────\n\
+  y  \
+"""
+    ucode_str_2 = \
+"""\
+x + 2\n\
+─────\n\
+  y  \
+"""
+    assert pretty(expr) in [ascii_str_1, ascii_str_2]
+    assert upretty(expr) in [ucode_str_1, ucode_str_2]
+
+    expr = (1 + x)*y
+    ascii_str_1 = \
+"""\
+y*(1 + x)\
+"""
+    ascii_str_2 = \
+"""\
+(1 + x)*y\
+"""
+    ascii_str_3 = \
+"""\
+y*(x + 1)\
+"""
+    ucode_str_1 = \
+"""\
+y⋅(1 + x)\
+"""
+    ucode_str_2 = \
+"""\
+(1 + x)⋅y\
+"""
+    ucode_str_3 = \
+"""\
+y⋅(x + 1)\
+"""
+    assert pretty(expr) in [ascii_str_1, ascii_str_2, ascii_str_3]
+    assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3]
+
+    # Test for correct placement of the negative sign
+    expr = -5*x/(x + 10)
+    ascii_str_1 = \
+"""\
+-5*x  \n\
+------\n\
+10 + x\
+"""
+    ascii_str_2 = \
+"""\
+-5*x  \n\
+------\n\
+x + 10\
+"""
+    ucode_str_1 = \
+"""\
+-5⋅x  \n\
+──────\n\
+10 + x\
+"""
+    ucode_str_2 = \
+"""\
+-5⋅x  \n\
+──────\n\
+x + 10\
+"""
+    assert pretty(expr) in [ascii_str_1, ascii_str_2]
+    assert upretty(expr) in [ucode_str_1, ucode_str_2]
+
+    expr = -S.Half - 3*x
+    ascii_str = \
+"""\
+-3*x - 1/2\
+"""
+    ucode_str = \
+"""\
+-3⋅x - 1/2\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = S.Half - 3*x
+    ascii_str = \
+"""\
+1/2 - 3*x\
+"""
+    ucode_str = \
+"""\
+1/2 - 3⋅x\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = -S.Half - 3*x/2
+    ascii_str = \
+"""\
+  3*x   1\n\
+- --- - -\n\
+   2    2\
+"""
+    ucode_str = \
+"""\
+  3⋅x   1\n\
+- ─── - ─\n\
+   2    2\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = S.Half - 3*x/2
+    ascii_str = \
+"""\
+1   3*x\n\
+- - ---\n\
+2    2 \
+"""
+    ucode_str = \
+"""\
+1   3⋅x\n\
+─ - ───\n\
+2    2 \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_negative_fractions():
+    expr = -x/y
+    ascii_str =\
+"""\
+-x \n\
+---\n\
+ y \
+"""
+    ucode_str =\
+"""\
+-x \n\
+───\n\
+ y \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+    expr = -x*z/y
+    ascii_str =\
+"""\
+-x*z \n\
+-----\n\
+  y  \
+"""
+    ucode_str =\
+"""\
+-x⋅z \n\
+─────\n\
+  y  \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+    expr = x**2/y
+    ascii_str =\
+"""\
+ 2\n\
+x \n\
+--\n\
+y \
+"""
+    ucode_str =\
+"""\
+ 2\n\
+x \n\
+──\n\
+y \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+    expr = -x**2/y
+    ascii_str =\
+"""\
+  2 \n\
+-x  \n\
+----\n\
+ y  \
+"""
+    ucode_str =\
+"""\
+  2 \n\
+-x  \n\
+────\n\
+ y  \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+    expr = -x/(y*z)
+    ascii_str =\
+"""\
+-x \n\
+---\n\
+y*z\
+"""
+    ucode_str =\
+"""\
+-x \n\
+───\n\
+y⋅z\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+    expr = -a/y**2
+    ascii_str =\
+"""\
+-a \n\
+---\n\
+ 2 \n\
+y  \
+"""
+    ucode_str =\
+"""\
+-a \n\
+───\n\
+ 2 \n\
+y  \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+    expr = y**(-a/b)
+    ascii_str =\
+"""\
+ -a \n\
+ ---\n\
+  b \n\
+y   \
+"""
+    ucode_str =\
+"""\
+ -a \n\
+ ───\n\
+  b \n\
+y   \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+    expr = -1/y**2
+    ascii_str =\
+"""\
+-1 \n\
+---\n\
+ 2 \n\
+y  \
+"""
+    ucode_str =\
+"""\
+-1 \n\
+───\n\
+ 2 \n\
+y  \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+    expr = -10/b**2
+    ascii_str =\
+"""\
+-10 \n\
+----\n\
+  2 \n\
+ b  \
+"""
+    ucode_str =\
+"""\
+-10 \n\
+────\n\
+  2 \n\
+ b  \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+    expr = Rational(-200, 37)
+    ascii_str =\
+"""\
+-200 \n\
+-----\n\
+ 37  \
+"""
+    ucode_str =\
+"""\
+-200 \n\
+─────\n\
+ 37  \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_Mul():
+    expr = Mul(0, 1, evaluate=False)
+    assert pretty(expr) == "0*1"
+    assert upretty(expr) == "0⋅1"
+    expr = Mul(1, 0, evaluate=False)
+    assert pretty(expr) == "1*0"
+    assert upretty(expr) == "1⋅0"
+    expr = Mul(1, 1, evaluate=False)
+    assert pretty(expr) == "1*1"
+    assert upretty(expr) == "1⋅1"
+    expr = Mul(1, 1, 1, evaluate=False)
+    assert pretty(expr) == "1*1*1"
+    assert upretty(expr) == "1⋅1⋅1"
+    expr = Mul(1, 2, evaluate=False)
+    assert pretty(expr) == "1*2"
+    assert upretty(expr) == "1⋅2"
+    expr = Add(0, 1, evaluate=False)
+    assert pretty(expr) == "0 + 1"
+    assert upretty(expr) == "0 + 1"
+    expr = Mul(1, 1, 2, evaluate=False)
+    assert pretty(expr) == "1*1*2"
+    assert upretty(expr) == "1⋅1⋅2"
+    expr = Add(0, 0, 1, evaluate=False)
+    assert pretty(expr) == "0 + 0 + 1"
+    assert upretty(expr) == "0 + 0 + 1"
+    expr = Mul(1, -1, evaluate=False)
+    assert pretty(expr) == "1*-1"
+    assert upretty(expr) == "1⋅-1"
+    expr = Mul(1.0, x, evaluate=False)
+    assert pretty(expr) == "1.0*x"
+    assert upretty(expr) == "1.0⋅x"
+    expr = Mul(1, 1, 2, 3, x, evaluate=False)
+    assert pretty(expr) == "1*1*2*3*x"
+    assert upretty(expr) == "1⋅1⋅2⋅3⋅x"
+    expr = Mul(-1, 1, evaluate=False)
+    assert pretty(expr) == "-1*1"
+    assert upretty(expr) == "-1⋅1"
+    expr = Mul(4, 3, 2, 1, 0, y, x, evaluate=False)
+    assert pretty(expr) == "4*3*2*1*0*y*x"
+    assert upretty(expr) == "4⋅3⋅2⋅1⋅0⋅y⋅x"
+    expr = Mul(4, 3, 2, 1+z, 0, y, x, evaluate=False)
+    assert pretty(expr) == "4*3*2*(z + 1)*0*y*x"
+    assert upretty(expr) == "4⋅3⋅2⋅(z + 1)⋅0⋅y⋅x"
+    expr = Mul(Rational(2, 3), Rational(5, 7), evaluate=False)
+    assert pretty(expr) == "2/3*5/7"
+    assert upretty(expr) == "2/3⋅5/7"
+    expr = Mul(x + y, Rational(1, 2), evaluate=False)
+    assert pretty(expr) == "(x + y)*1/2"
+    assert upretty(expr) == "(x + y)⋅1/2"
+    expr = Mul(Rational(1, 2), x + y, evaluate=False)
+    assert pretty(expr) == "x + y\n-----\n  2  "
+    assert upretty(expr) == "x + y\n─────\n  2  "
+    expr = Mul(S.One, x + y, evaluate=False)
+    assert pretty(expr) == "1*(x + y)"
+    assert upretty(expr) == "1⋅(x + y)"
+    expr = Mul(x - y, S.One, evaluate=False)
+    assert pretty(expr) == "(x - y)*1"
+    assert upretty(expr) == "(x - y)⋅1"
+    expr = Mul(Rational(1, 2), x - y, S.One, x + y, evaluate=False)
+    assert pretty(expr) == "1/2*(x - y)*1*(x + y)"
+    assert upretty(expr) == "1/2⋅(x - y)⋅1⋅(x + y)"
+    expr = Mul(x + y, Rational(3, 4), S.One, y - z, evaluate=False)
+    assert pretty(expr) == "(x + y)*3/4*1*(y - z)"
+    assert upretty(expr) == "(x + y)⋅3/4⋅1⋅(y - z)"
+    expr = Mul(x + y, Rational(1, 1), Rational(3, 4), Rational(5, 6),evaluate=False)
+    assert pretty(expr) == "(x + y)*1*3/4*5/6"
+    assert upretty(expr) == "(x + y)⋅1⋅3/4⋅5/6"
+    expr = Mul(Rational(3, 4), x + y, S.One, y - z, evaluate=False)
+    assert pretty(expr) == "3/4*(x + y)*1*(y - z)"
+    assert upretty(expr) == "3/4⋅(x + y)⋅1⋅(y - z)"
+
+
+def test_issue_5524():
+    assert pretty(-(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5)) == \
+"""\
+         2           /         ___    \\\n\
+- (5 - y)  + (x - 5)*\\-x - 2*\\/ 2  + 5/\
+"""
+
+    assert upretty(-(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5)) == \
+"""\
+         2                          \n\
+- (5 - y)  + (x - 5)⋅(-x - 2⋅√2 + 5)\
+"""
+
+
+def test_pretty_ordering():
+    assert pretty(x**2 + x + 1, order='lex') == \
+"""\
+ 2        \n\
+x  + x + 1\
+"""
+    assert pretty(x**2 + x + 1, order='rev-lex') == \
+"""\
+         2\n\
+1 + x + x \
+"""
+    assert pretty(1 - x, order='lex') == '-x + 1'
+    assert pretty(1 - x, order='rev-lex') == '1 - x'
+
+    assert pretty(1 - 2*x, order='lex') == '-2*x + 1'
+    assert pretty(1 - 2*x, order='rev-lex') == '1 - 2*x'
+
+    f = 2*x**4 + y**2 - x**2 + y**3
+    assert pretty(f, order=None) == \
+"""\
+   4    2    3    2\n\
+2*x  - x  + y  + y \
+"""
+    assert pretty(f, order='lex') == \
+"""\
+   4    2    3    2\n\
+2*x  - x  + y  + y \
+"""
+    assert pretty(f, order='rev-lex') == \
+"""\
+ 2    3    2      4\n\
+y  + y  - x  + 2*x \
+"""
+
+    expr = x - x**3/6 + x**5/120 + O(x**6)
+    ascii_str = \
+"""\
+     3    5         \n\
+    x    x      / 6\\\n\
+x - -- + --- + O\\x /\n\
+    6    120        \
+"""
+    ucode_str = \
+"""\
+     3    5         \n\
+    x    x      ⎛ 6⎞\n\
+x - ── + ─── + O⎝x ⎠\n\
+    6    120        \
+"""
+    assert pretty(expr, order=None) == ascii_str
+    assert upretty(expr, order=None) == ucode_str
+
+    assert pretty(expr, order='lex') == ascii_str
+    assert upretty(expr, order='lex') == ucode_str
+
+    assert pretty(expr, order='rev-lex') == ascii_str
+    assert upretty(expr, order='rev-lex') == ucode_str
+
+
+def test_EulerGamma():
+    assert pretty(EulerGamma) == str(EulerGamma) == "EulerGamma"
+    assert upretty(EulerGamma) == "γ"
+
+
+def test_GoldenRatio():
+    assert pretty(GoldenRatio) == str(GoldenRatio) == "GoldenRatio"
+    assert upretty(GoldenRatio) == "φ"
+
+
+def test_Catalan():
+    assert pretty(Catalan) == upretty(Catalan) == "G"
+
+
+def test_pretty_relational():
+    expr = Eq(x, y)
+    ascii_str = \
+"""\
+x = y\
+"""
+    ucode_str = \
+"""\
+x = y\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Lt(x, y)
+    ascii_str = \
+"""\
+x < y\
+"""
+    ucode_str = \
+"""\
+x < y\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Gt(x, y)
+    ascii_str = \
+"""\
+x > y\
+"""
+    ucode_str = \
+"""\
+x > y\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Le(x, y)
+    ascii_str = \
+"""\
+x <= y\
+"""
+    ucode_str = \
+"""\
+x ≤ y\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Ge(x, y)
+    ascii_str = \
+"""\
+x >= y\
+"""
+    ucode_str = \
+"""\
+x ≥ y\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Ne(x/(y + 1), y**2)
+    ascii_str_1 = \
+"""\
+  x       2\n\
+----- != y \n\
+1 + y      \
+"""
+    ascii_str_2 = \
+"""\
+  x       2\n\
+----- != y \n\
+y + 1      \
+"""
+    ucode_str_1 = \
+"""\
+  x      2\n\
+───── ≠ y \n\
+1 + y     \
+"""
+    ucode_str_2 = \
+"""\
+  x      2\n\
+───── ≠ y \n\
+y + 1     \
+"""
+    assert pretty(expr) in [ascii_str_1, ascii_str_2]
+    assert upretty(expr) in [ucode_str_1, ucode_str_2]
+
+
+def test_Assignment():
+    expr = Assignment(x, y)
+    ascii_str = \
+"""\
+x := y\
+"""
+    ucode_str = \
+"""\
+x := y\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_AugmentedAssignment():
+    expr = AddAugmentedAssignment(x, y)
+    ascii_str = \
+"""\
+x += y\
+"""
+    ucode_str = \
+"""\
+x += y\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = SubAugmentedAssignment(x, y)
+    ascii_str = \
+"""\
+x -= y\
+"""
+    ucode_str = \
+"""\
+x -= y\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = MulAugmentedAssignment(x, y)
+    ascii_str = \
+"""\
+x *= y\
+"""
+    ucode_str = \
+"""\
+x *= y\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = DivAugmentedAssignment(x, y)
+    ascii_str = \
+"""\
+x /= y\
+"""
+    ucode_str = \
+"""\
+x /= y\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = ModAugmentedAssignment(x, y)
+    ascii_str = \
+"""\
+x %= y\
+"""
+    ucode_str = \
+"""\
+x %= y\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_pretty_rational():
+    expr = y*x**-2
+    ascii_str = \
+"""\
+y \n\
+--\n\
+ 2\n\
+x \
+"""
+    ucode_str = \
+"""\
+y \n\
+──\n\
+ 2\n\
+x \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = y**Rational(3, 2) * x**Rational(-5, 2)
+    ascii_str = \
+"""\
+ 3/2\n\
+y   \n\
+----\n\
+ 5/2\n\
+x   \
+"""
+    ucode_str = \
+"""\
+ 3/2\n\
+y   \n\
+────\n\
+ 5/2\n\
+x   \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = sin(x)**3/tan(x)**2
+    ascii_str = \
+"""\
+   3   \n\
+sin (x)\n\
+-------\n\
+   2   \n\
+tan (x)\
+"""
+    ucode_str = \
+"""\
+   3   \n\
+sin (x)\n\
+───────\n\
+   2   \n\
+tan (x)\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+@_both_exp_pow
+def test_pretty_functions():
+    """Tests for Abs, conjugate, exp, function braces, and factorial."""
+    expr = (2*x + exp(x))
+    ascii_str_1 = \
+"""\
+       x\n\
+2*x + e \
+"""
+    ascii_str_2 = \
+"""\
+ x      \n\
+e  + 2*x\
+"""
+    ucode_str_1 = \
+"""\
+       x\n\
+2⋅x + ℯ \
+"""
+    ucode_str_2 = \
+"""\
+ x     \n\
+ℯ + 2⋅x\
+"""
+    ucode_str_3 = \
+"""\
+ x      \n\
+ℯ  + 2⋅x\
+"""
+    assert pretty(expr) in [ascii_str_1, ascii_str_2]
+    assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3]
+
+    expr = Abs(x)
+    ascii_str = \
+"""\
+|x|\
+"""
+    ucode_str = \
+"""\
+│x│\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Abs(x/(x**2 + 1))
+    ascii_str_1 = \
+"""\
+|  x   |\n\
+|------|\n\
+|     2|\n\
+|1 + x |\
+"""
+    ascii_str_2 = \
+"""\
+|  x   |\n\
+|------|\n\
+| 2    |\n\
+|x  + 1|\
+"""
+    ucode_str_1 = \
+"""\
+│  x   │\n\
+│──────│\n\
+│     2│\n\
+│1 + x │\
+"""
+    ucode_str_2 = \
+"""\
+│  x   │\n\
+│──────│\n\
+│ 2    │\n\
+│x  + 1│\
+"""
+    assert pretty(expr) in [ascii_str_1, ascii_str_2]
+    assert upretty(expr) in [ucode_str_1, ucode_str_2]
+
+    expr = Abs(1 / (y - Abs(x)))
+    ascii_str = \
+"""\
+    1    \n\
+---------\n\
+|y - |x||\
+"""
+    ucode_str = \
+"""\
+    1    \n\
+─────────\n\
+│y - │x││\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    n = Symbol('n', integer=True)
+    expr = factorial(n)
+    ascii_str = \
+"""\
+n!\
+"""
+    ucode_str = \
+"""\
+n!\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = factorial(2*n)
+    ascii_str = \
+"""\
+(2*n)!\
+"""
+    ucode_str = \
+"""\
+(2⋅n)!\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = factorial(factorial(factorial(n)))
+    ascii_str = \
+"""\
+((n!)!)!\
+"""
+    ucode_str = \
+"""\
+((n!)!)!\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = factorial(n + 1)
+    ascii_str_1 = \
+"""\
+(1 + n)!\
+"""
+    ascii_str_2 = \
+"""\
+(n + 1)!\
+"""
+    ucode_str_1 = \
+"""\
+(1 + n)!\
+"""
+    ucode_str_2 = \
+"""\
+(n + 1)!\
+"""
+
+    assert pretty(expr) in [ascii_str_1, ascii_str_2]
+    assert upretty(expr) in [ucode_str_1, ucode_str_2]
+
+    expr = subfactorial(n)
+    ascii_str = \
+"""\
+!n\
+"""
+    ucode_str = \
+"""\
+!n\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = subfactorial(2*n)
+    ascii_str = \
+"""\
+!(2*n)\
+"""
+    ucode_str = \
+"""\
+!(2⋅n)\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    n = Symbol('n', integer=True)
+    expr = factorial2(n)
+    ascii_str = \
+"""\
+n!!\
+"""
+    ucode_str = \
+"""\
+n!!\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = factorial2(2*n)
+    ascii_str = \
+"""\
+(2*n)!!\
+"""
+    ucode_str = \
+"""\
+(2⋅n)!!\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = factorial2(factorial2(factorial2(n)))
+    ascii_str = \
+"""\
+((n!!)!!)!!\
+"""
+    ucode_str = \
+"""\
+((n!!)!!)!!\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = factorial2(n + 1)
+    ascii_str_1 = \
+"""\
+(1 + n)!!\
+"""
+    ascii_str_2 = \
+"""\
+(n + 1)!!\
+"""
+    ucode_str_1 = \
+"""\
+(1 + n)!!\
+"""
+    ucode_str_2 = \
+"""\
+(n + 1)!!\
+"""
+
+    assert pretty(expr) in [ascii_str_1, ascii_str_2]
+    assert upretty(expr) in [ucode_str_1, ucode_str_2]
+
+    expr = 2*binomial(n, k)
+    ascii_str = \
+"""\
+  /n\\\n\
+2*| |\n\
+  \\k/\
+"""
+    ucode_str = \
+"""\
+  ⎛n⎞\n\
+2⋅⎜ ⎟\n\
+  ⎝k⎠\
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = 2*binomial(2*n, k)
+    ascii_str = \
+"""\
+  /2*n\\\n\
+2*|   |\n\
+  \\ k /\
+"""
+    ucode_str = \
+"""\
+  ⎛2⋅n⎞\n\
+2⋅⎜   ⎟\n\
+  ⎝ k ⎠\
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = 2*binomial(n**2, k)
+    ascii_str = \
+"""\
+  / 2\\\n\
+  |n |\n\
+2*|  |\n\
+  \\k /\
+"""
+    ucode_str = \
+"""\
+  ⎛ 2⎞\n\
+  ⎜n ⎟\n\
+2⋅⎜  ⎟\n\
+  ⎝k ⎠\
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = catalan(n)
+    ascii_str = \
+"""\
+C \n\
+ n\
+"""
+    ucode_str = \
+"""\
+C \n\
+ n\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = catalan(n)
+    ascii_str = \
+"""\
+C \n\
+ n\
+"""
+    ucode_str = \
+"""\
+C \n\
+ n\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = bell(n)
+    ascii_str = \
+"""\
+B \n\
+ n\
+"""
+    ucode_str = \
+"""\
+B \n\
+ n\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = bernoulli(n)
+    ascii_str = \
+"""\
+B \n\
+ n\
+"""
+    ucode_str = \
+"""\
+B \n\
+ n\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = bernoulli(n, x)
+    ascii_str = \
+"""\
+B (x)\n\
+ n   \
+"""
+    ucode_str = \
+"""\
+B (x)\n\
+ n   \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = fibonacci(n)
+    ascii_str = \
+"""\
+F \n\
+ n\
+"""
+    ucode_str = \
+"""\
+F \n\
+ n\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = lucas(n)
+    ascii_str = \
+"""\
+L \n\
+ n\
+"""
+    ucode_str = \
+"""\
+L \n\
+ n\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = tribonacci(n)
+    ascii_str = \
+"""\
+T \n\
+ n\
+"""
+    ucode_str = \
+"""\
+T \n\
+ n\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = stieltjes(n)
+    ascii_str = \
+"""\
+stieltjes \n\
+         n\
+"""
+    ucode_str = \
+"""\
+γ \n\
+ n\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = stieltjes(n, x)
+    ascii_str = \
+"""\
+stieltjes (x)\n\
+         n   \
+"""
+    ucode_str = \
+"""\
+γ (x)\n\
+ n   \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = mathieuc(x, y, z)
+    ascii_str = 'C(x, y, z)'
+    ucode_str = 'C(x, y, z)'
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = mathieus(x, y, z)
+    ascii_str = 'S(x, y, z)'
+    ucode_str = 'S(x, y, z)'
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = mathieucprime(x, y, z)
+    ascii_str = "C'(x, y, z)"
+    ucode_str = "C'(x, y, z)"
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = mathieusprime(x, y, z)
+    ascii_str = "S'(x, y, z)"
+    ucode_str = "S'(x, y, z)"
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = conjugate(x)
+    ascii_str = \
+"""\
+_\n\
+x\
+"""
+    ucode_str = \
+"""\
+_\n\
+x\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    f = Function('f')
+    expr = conjugate(f(x + 1))
+    ascii_str_1 = \
+"""\
+________\n\
+f(1 + x)\
+"""
+    ascii_str_2 = \
+"""\
+________\n\
+f(x + 1)\
+"""
+    ucode_str_1 = \
+"""\
+________\n\
+f(1 + x)\
+"""
+    ucode_str_2 = \
+"""\
+________\n\
+f(x + 1)\
+"""
+    assert pretty(expr) in [ascii_str_1, ascii_str_2]
+    assert upretty(expr) in [ucode_str_1, ucode_str_2]
+
+    expr = f(x)
+    ascii_str = \
+"""\
+f(x)\
+"""
+    ucode_str = \
+"""\
+f(x)\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = f(x, y)
+    ascii_str = \
+"""\
+f(x, y)\
+"""
+    ucode_str = \
+"""\
+f(x, y)\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = f(x/(y + 1), y)
+    ascii_str_1 = \
+"""\
+ /  x     \\\n\
+f|-----, y|\n\
+ \\1 + y   /\
+"""
+    ascii_str_2 = \
+"""\
+ /  x     \\\n\
+f|-----, y|\n\
+ \\y + 1   /\
+"""
+    ucode_str_1 = \
+"""\
+ ⎛  x     ⎞\n\
+f⎜─────, y⎟\n\
+ ⎝1 + y   ⎠\
+"""
+    ucode_str_2 = \
+"""\
+ ⎛  x     ⎞\n\
+f⎜─────, y⎟\n\
+ ⎝y + 1   ⎠\
+"""
+    assert pretty(expr) in [ascii_str_1, ascii_str_2]
+    assert upretty(expr) in [ucode_str_1, ucode_str_2]
+
+    expr = f(x**x**x**x**x**x)
+    ascii_str = \
+"""\
+ / / / / / x\\\\\\\\\\
+ | | | | \\x /||||
+ | | | \\x    /|||
+ | | \\x       /||
+ | \\x          /|
+f\\x             /\
+"""
+    ucode_str = \
+"""\
+ ⎛ ⎛ ⎛ ⎛ ⎛ x⎞⎞⎞⎞⎞
+ ⎜ ⎜ ⎜ ⎜ ⎝x ⎠⎟⎟⎟⎟
+ ⎜ ⎜ ⎜ ⎝x    ⎠⎟⎟⎟
+ ⎜ ⎜ ⎝x       ⎠⎟⎟
+ ⎜ ⎝x          ⎠⎟
+f⎝x             ⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = sin(x)**2
+    ascii_str = \
+"""\
+   2   \n\
+sin (x)\
+"""
+    ucode_str = \
+"""\
+   2   \n\
+sin (x)\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = conjugate(a + b*I)
+    ascii_str = \
+"""\
+_     _\n\
+a - I*b\
+"""
+    ucode_str = \
+"""\
+_     _\n\
+a - ⅈ⋅b\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = conjugate(exp(a + b*I))
+    ascii_str = \
+"""\
+ _     _\n\
+ a - I*b\n\
+e       \
+"""
+    ucode_str = \
+"""\
+ _     _\n\
+ a - ⅈ⋅b\n\
+ℯ       \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = conjugate( f(1 + conjugate(f(x))) )
+    ascii_str_1 = \
+"""\
+___________\n\
+ /    ____\\\n\
+f\\1 + f(x)/\
+"""
+    ascii_str_2 = \
+"""\
+___________\n\
+ /____    \\\n\
+f\\f(x) + 1/\
+"""
+    ucode_str_1 = \
+"""\
+___________\n\
+ ⎛    ____⎞\n\
+f⎝1 + f(x)⎠\
+"""
+    ucode_str_2 = \
+"""\
+___________\n\
+ ⎛____    ⎞\n\
+f⎝f(x) + 1⎠\
+"""
+    assert pretty(expr) in [ascii_str_1, ascii_str_2]
+    assert upretty(expr) in [ucode_str_1, ucode_str_2]
+
+    expr = f(x/(y + 1), y)
+    ascii_str_1 = \
+"""\
+ /  x     \\\n\
+f|-----, y|\n\
+ \\1 + y   /\
+"""
+    ascii_str_2 = \
+"""\
+ /  x     \\\n\
+f|-----, y|\n\
+ \\y + 1   /\
+"""
+    ucode_str_1 = \
+"""\
+ ⎛  x     ⎞\n\
+f⎜─────, y⎟\n\
+ ⎝1 + y   ⎠\
+"""
+    ucode_str_2 = \
+"""\
+ ⎛  x     ⎞\n\
+f⎜─────, y⎟\n\
+ ⎝y + 1   ⎠\
+"""
+    assert pretty(expr) in [ascii_str_1, ascii_str_2]
+    assert upretty(expr) in [ucode_str_1, ucode_str_2]
+
+    expr = floor(1 / (y - floor(x)))
+    ascii_str = \
+"""\
+     /     1      \\\n\
+floor|------------|\n\
+     \\y - floor(x)/\
+"""
+    ucode_str = \
+"""\
+⎢   1   ⎥\n\
+⎢───────⎥\n\
+⎣y - ⌊x⌋⎦\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = ceiling(1 / (y - ceiling(x)))
+    ascii_str = \
+"""\
+       /      1       \\\n\
+ceiling|--------------|\n\
+       \\y - ceiling(x)/\
+"""
+    ucode_str = \
+"""\
+⎡   1   ⎤\n\
+⎢───────⎥\n\
+⎢y - ⌈x⌉⎥\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = euler(n)
+    ascii_str = \
+"""\
+E \n\
+ n\
+"""
+    ucode_str = \
+"""\
+E \n\
+ n\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = euler(1/(1 + 1/(1 + 1/n)))
+    ascii_str = \
+"""\
+E         \n\
+     1    \n\
+ ---------\n\
+       1  \n\
+ 1 + -----\n\
+         1\n\
+     1 + -\n\
+         n\
+"""
+
+    ucode_str = \
+"""\
+E         \n\
+     1    \n\
+ ─────────\n\
+       1  \n\
+ 1 + ─────\n\
+         1\n\
+     1 + ─\n\
+         n\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = euler(n, x)
+    ascii_str = \
+"""\
+E (x)\n\
+ n   \
+"""
+    ucode_str = \
+"""\
+E (x)\n\
+ n   \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = euler(n, x/2)
+    ascii_str = \
+"""\
+  /x\\\n\
+E |-|\n\
+ n\\2/\
+"""
+    ucode_str = \
+"""\
+  ⎛x⎞\n\
+E ⎜─⎟\n\
+ n⎝2⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_pretty_sqrt():
+    expr = sqrt(2)
+    ascii_str = \
+"""\
+  ___\n\
+\\/ 2 \
+"""
+    ucode_str = \
+"√2"
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = 2**Rational(1, 3)
+    ascii_str = \
+"""\
+3 ___\n\
+\\/ 2 \
+"""
+    ucode_str = \
+"""\
+3 ___\n\
+╲╱ 2 \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = 2**Rational(1, 1000)
+    ascii_str = \
+"""\
+1000___\n\
+  \\/ 2 \
+"""
+    ucode_str = \
+"""\
+1000___\n\
+  ╲╱ 2 \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = sqrt(x**2 + 1)
+    ascii_str = \
+"""\
+   ________\n\
+  /  2     \n\
+\\/  x  + 1 \
+"""
+    ucode_str = \
+"""\
+   ________\n\
+  ╱  2     \n\
+╲╱  x  + 1 \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = (1 + sqrt(5))**Rational(1, 3)
+    ascii_str = \
+"""\
+   ___________\n\
+3 /       ___ \n\
+\\/  1 + \\/ 5  \
+"""
+    ucode_str = \
+"""\
+3 ________\n\
+╲╱ 1 + √5 \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = 2**(1/x)
+    ascii_str = \
+"""\
+x ___\n\
+\\/ 2 \
+"""
+    ucode_str = \
+"""\
+x ___\n\
+╲╱ 2 \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = sqrt(2 + pi)
+    ascii_str = \
+"""\
+  ________\n\
+\\/ 2 + pi \
+"""
+    ucode_str = \
+"""\
+  _______\n\
+╲╱ 2 + π \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = (2 + (
+        1 + x**2)/(2 + x))**Rational(1, 4) + (1 + x**Rational(1, 1000))/sqrt(3 + x**2)
+    ascii_str = \
+"""\
+     ____________              \n\
+    /      2        1000___    \n\
+   /      x  + 1      \\/ x  + 1\n\
+4 /   2 + ------  + -----------\n\
+\\/        x + 2        ________\n\
+                      /  2     \n\
+                    \\/  x  + 3 \
+"""
+    ucode_str = \
+"""\
+     ____________              \n\
+    ╱      2        1000___    \n\
+   ╱      x  + 1      ╲╱ x  + 1\n\
+4 ╱   2 + ──────  + ───────────\n\
+╲╱        x + 2        ________\n\
+                      ╱  2     \n\
+                    ╲╱  x  + 3 \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_pretty_sqrt_char_knob():
+    # See PR #9234.
+    expr = sqrt(2)
+    ucode_str1 = \
+"""\
+  ___\n\
+╲╱ 2 \
+"""
+    ucode_str2 = \
+"√2"
+    assert xpretty(expr, use_unicode=True,
+                   use_unicode_sqrt_char=False) == ucode_str1
+    assert xpretty(expr, use_unicode=True,
+                   use_unicode_sqrt_char=True) == ucode_str2
+
+
+def test_pretty_sqrt_longsymbol_no_sqrt_char():
+    # Do not use unicode sqrt char for long symbols (see PR #9234).
+    expr = sqrt(Symbol('C1'))
+    ucode_str = \
+"""\
+  ____\n\
+╲╱ C₁ \
+"""
+    assert upretty(expr) == ucode_str
+
+
+def test_pretty_KroneckerDelta():
+    x, y = symbols("x, y")
+    expr = KroneckerDelta(x, y)
+    ascii_str = \
+"""\
+d   \n\
+ x,y\
+"""
+    ucode_str = \
+"""\
+δ   \n\
+ x,y\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_pretty_product():
+    n, m, k, l = symbols('n m k l')
+    f = symbols('f', cls=Function)
+    expr = Product(f((n/3)**2), (n, k**2, l))
+
+    unicode_str = \
+"""\
+    l           \n\
+─┬──────┬─      \n\
+ │      │   ⎛ 2⎞\n\
+ │      │   ⎜n ⎟\n\
+ │      │  f⎜──⎟\n\
+ │      │   ⎝9 ⎠\n\
+ │      │       \n\
+       2        \n\
+  n = k         """
+    ascii_str = \
+"""\
+    l           \n\
+__________      \n\
+ |      |   / 2\\\n\
+ |      |   |n |\n\
+ |      |  f|--|\n\
+ |      |   \\9 /\n\
+ |      |       \n\
+       2        \n\
+  n = k         """
+
+    expr = Product(f((n/3)**2), (n, k**2, l), (l, 1, m))
+
+    unicode_str = \
+"""\
+    m          l           \n\
+─┬──────┬─ ─┬──────┬─      \n\
+ │      │   │      │   ⎛ 2⎞\n\
+ │      │   │      │   ⎜n ⎟\n\
+ │      │   │      │  f⎜──⎟\n\
+ │      │   │      │   ⎝9 ⎠\n\
+ │      │   │      │       \n\
+  l = 1           2        \n\
+             n = k         """
+    ascii_str = \
+"""\
+    m          l           \n\
+__________ __________      \n\
+ |      |   |      |   / 2\\\n\
+ |      |   |      |   |n |\n\
+ |      |   |      |  f|--|\n\
+ |      |   |      |   \\9 /\n\
+ |      |   |      |       \n\
+  l = 1           2        \n\
+             n = k         """
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == unicode_str
+
+
+def test_pretty_Lambda():
+    # S.IdentityFunction is a special case
+    expr = Lambda(y, y)
+    assert pretty(expr) == "x -> x"
+    assert upretty(expr) == "x ↦ x"
+
+    expr = Lambda(x, x+1)
+    assert pretty(expr) == "x -> x + 1"
+    assert upretty(expr) == "x ↦ x + 1"
+
+    expr = Lambda(x, x**2)
+    ascii_str = \
+"""\
+      2\n\
+x -> x \
+"""
+    ucode_str = \
+"""\
+     2\n\
+x ↦ x \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Lambda(x, x**2)**2
+    ascii_str = \
+"""\
+         2
+/      2\\ \n\
+\\x -> x / \
+"""
+    ucode_str = \
+"""\
+        2
+⎛     2⎞ \n\
+⎝x ↦ x ⎠ \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Lambda((x, y), x)
+    ascii_str = "(x, y) -> x"
+    ucode_str = "(x, y) ↦ x"
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Lambda((x, y), x**2)
+    ascii_str = \
+"""\
+           2\n\
+(x, y) -> x \
+"""
+    ucode_str = \
+"""\
+          2\n\
+(x, y) ↦ x \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Lambda(((x, y),), x**2)
+    ascii_str = \
+"""\
+              2\n\
+((x, y),) -> x \
+"""
+    ucode_str = \
+"""\
+             2\n\
+((x, y),) ↦ x \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_pretty_TransferFunction():
+    tf1 = TransferFunction(s - 1, s + 1, s)
+    assert upretty(tf1) == "s - 1\n─────\ns + 1"
+    tf2 = TransferFunction(2*s + 1, 3 - p, s)
+    assert upretty(tf2) == "2⋅s + 1\n───────\n 3 - p "
+    tf3 = TransferFunction(p, p + 1, p)
+    assert upretty(tf3) == "  p  \n─────\np + 1"
+
+
+def test_pretty_Series():
+    tf1 = TransferFunction(x + y, x - 2*y, y)
+    tf2 = TransferFunction(x - y, x + y, y)
+    tf3 = TransferFunction(x**2 + y, y - x, y)
+    tf4 = TransferFunction(2, 3, y)
+
+    tfm1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]])
+    tfm2 = TransferFunctionMatrix([[tf3], [-tf4]])
+    tfm3 = TransferFunctionMatrix([[tf1, -tf2, -tf3], [tf3, -tf4, tf2]])
+    tfm4 = TransferFunctionMatrix([[tf1, tf2], [tf3, -tf4], [-tf2, -tf1]])
+    tfm5 = TransferFunctionMatrix([[-tf2, -tf1], [tf4, -tf3], [tf1, tf2]])
+
+    expected1 = \
+"""\
+          ⎛ 2    ⎞\n\
+⎛ x + y ⎞ ⎜x  + y⎟\n\
+⎜───────⎟⋅⎜──────⎟\n\
+⎝x - 2⋅y⎠ ⎝-x + y⎠\
+"""
+    expected2 = \
+"""\
+⎛-x + y⎞ ⎛-x - y ⎞\n\
+⎜──────⎟⋅⎜───────⎟\n\
+⎝x + y ⎠ ⎝x - 2⋅y⎠\
+"""
+    expected3 = \
+"""\
+⎛ 2    ⎞                            \n\
+⎜x  + y⎟ ⎛ x + y ⎞ ⎛-x - y    x - y⎞\n\
+⎜──────⎟⋅⎜───────⎟⋅⎜─────── + ─────⎟\n\
+⎝-x + y⎠ ⎝x - 2⋅y⎠ ⎝x - 2⋅y   x + y⎠\
+"""
+    expected4 = \
+"""\
+                  ⎛         2    ⎞\n\
+⎛ x + y    x - y⎞ ⎜x - y   x  + y⎟\n\
+⎜─────── + ─────⎟⋅⎜───── + ──────⎟\n\
+⎝x - 2⋅y   x + y⎠ ⎝x + y   -x + y⎠\
+"""
+    expected5 = \
+"""\
+⎡ x + y   x - y⎤  ⎡ 2    ⎤ \n\
+⎢───────  ─────⎥  ⎢x  + y⎥ \n\
+⎢x - 2⋅y  x + y⎥  ⎢──────⎥ \n\
+⎢              ⎥  ⎢-x + y⎥ \n\
+⎢ 2            ⎥ ⋅⎢      ⎥ \n\
+⎢x  + y     2  ⎥  ⎢ -2   ⎥ \n\
+⎢──────     ─  ⎥  ⎢ ───  ⎥ \n\
+⎣-x + y     3  ⎦τ ⎣  3   ⎦τ\
+"""
+    expected6 = \
+"""\
+                                               ⎛⎡ x + y    x - y ⎤    ⎡ x - y    x + y ⎤ ⎞\n\
+                                               ⎜⎢───────   ───── ⎥    ⎢ ─────   ───────⎥ ⎟\n\
+⎡ x + y   x - y⎤  ⎡                    2    ⎤  ⎜⎢x - 2⋅y   x + y ⎥    ⎢ x + y   x - 2⋅y⎥ ⎟\n\
+⎢───────  ─────⎥  ⎢ x + y   -x + y  - x  - y⎥  ⎜⎢                ⎥    ⎢                ⎥ ⎟\n\
+⎢x - 2⋅y  x + y⎥  ⎢───────  ──────  ────────⎥  ⎜⎢ 2              ⎥    ⎢          2     ⎥ ⎟\n\
+⎢              ⎥  ⎢x - 2⋅y  x + y    -x + y ⎥  ⎜⎢x  + y     -2   ⎥    ⎢  -2     x  + y ⎥ ⎟\n\
+⎢ 2            ⎥ ⋅⎢                         ⎥ ⋅⎜⎢──────     ───  ⎥  + ⎢  ───    ────── ⎥ ⎟\n\
+⎢x  + y     2  ⎥  ⎢ 2                       ⎥  ⎜⎢-x + y      3   ⎥    ⎢   3     -x + y ⎥ ⎟\n\
+⎢──────     ─  ⎥  ⎢x  + y    -2      x - y  ⎥  ⎜⎢                ⎥    ⎢                ⎥ ⎟\n\
+⎣-x + y     3  ⎦τ ⎢──────    ───     ─────  ⎥  ⎜⎢-x + y   -x - y ⎥    ⎢-x - y   -x + y ⎥ ⎟\n\
+                  ⎣-x + y     3      x + y  ⎦τ ⎜⎢──────   ───────⎥    ⎢───────  ────── ⎥ ⎟\n\
+                                               ⎝⎣x + y    x - 2⋅y⎦τ   ⎣x - 2⋅y  x + y  ⎦τ⎠\
+"""
+
+    assert upretty(Series(tf1, tf3)) == expected1
+    assert upretty(Series(-tf2, -tf1)) == expected2
+    assert upretty(Series(tf3, tf1, Parallel(-tf1, tf2))) == expected3
+    assert upretty(Series(Parallel(tf1, tf2), Parallel(tf2, tf3))) == expected4
+    assert upretty(MIMOSeries(tfm2, tfm1)) == expected5
+    assert upretty(MIMOSeries(MIMOParallel(tfm4, -tfm5), tfm3, tfm1)) == expected6
+
+
+def test_pretty_Parallel():
+    tf1 = TransferFunction(x + y, x - 2*y, y)
+    tf2 = TransferFunction(x - y, x + y, y)
+    tf3 = TransferFunction(x**2 + y, y - x, y)
+    tf4 = TransferFunction(y**2 - x, x**3 + x, y)
+
+    tfm1 = TransferFunctionMatrix([[tf1, tf2], [tf3, -tf4], [-tf2, -tf1]])
+    tfm2 = TransferFunctionMatrix([[-tf2, -tf1], [tf4, -tf3], [tf1, tf2]])
+    tfm3 = TransferFunctionMatrix([[-tf1, tf2], [-tf3, tf4], [tf2, tf1]])
+    tfm4 = TransferFunctionMatrix([[-tf1, -tf2], [-tf3, -tf4]])
+
+    expected1 = \
+"""\
+ x + y    x - y\n\
+─────── + ─────\n\
+x - 2⋅y   x + y\
+"""
+    expected2 = \
+"""\
+-x + y   -x - y \n\
+────── + ───────
+x + y    x - 2⋅y\
+"""
+    expected3 = \
+"""\
+ 2                                  \n\
+x  + y    x + y    ⎛-x - y ⎞ ⎛x - y⎞
+────── + ─────── + ⎜───────⎟⋅⎜─────⎟
+-x + y   x - 2⋅y   ⎝x - 2⋅y⎠ ⎝x + y⎠\
+"""
+
+    expected4 = \
+"""\
+                            ⎛ 2    ⎞\n\
+⎛ x + y ⎞ ⎛x - y⎞   ⎛x - y⎞ ⎜x  + y⎟\n\
+⎜───────⎟⋅⎜─────⎟ + ⎜─────⎟⋅⎜──────⎟\n\
+⎝x - 2⋅y⎠ ⎝x + y⎠   ⎝x + y⎠ ⎝-x + y⎠\
+"""
+    expected5 = \
+"""\
+⎡ x + y   -x + y ⎤    ⎡ x - y    x + y ⎤    ⎡ x + y    x - y ⎤ \n\
+⎢───────  ────── ⎥    ⎢ ─────   ───────⎥    ⎢───────   ───── ⎥ \n\
+⎢x - 2⋅y  x + y  ⎥    ⎢ x + y   x - 2⋅y⎥    ⎢x - 2⋅y   x + y ⎥ \n\
+⎢                ⎥    ⎢                ⎥    ⎢                ⎥ \n\
+⎢ 2            2 ⎥    ⎢     2    2     ⎥    ⎢ 2            2 ⎥ \n\
+⎢x  + y   x - y  ⎥    ⎢x - y    x  + y ⎥    ⎢x  + y   x - y  ⎥ \n\
+⎢──────   ────── ⎥  + ⎢──────   ────── ⎥  + ⎢──────   ────── ⎥ \n\
+⎢-x + y    3     ⎥    ⎢ 3       -x + y ⎥    ⎢-x + y    3     ⎥ \n\
+⎢         x  + x ⎥    ⎢x  + x          ⎥    ⎢         x  + x ⎥ \n\
+⎢                ⎥    ⎢                ⎥    ⎢                ⎥ \n\
+⎢-x + y   -x - y ⎥    ⎢-x - y   -x + y ⎥    ⎢-x + y   -x - y ⎥ \n\
+⎢──────   ───────⎥    ⎢───────  ────── ⎥    ⎢──────   ───────⎥ \n\
+⎣x + y    x - 2⋅y⎦τ   ⎣x - 2⋅y  x + y  ⎦τ   ⎣x + y    x - 2⋅y⎦τ\
+"""
+    expected6 = \
+"""\
+⎡ x - y    x + y ⎤                        ⎡-x + y   -x - y  ⎤ \n\
+⎢ ─────   ───────⎥                        ⎢──────   ─────── ⎥ \n\
+⎢ x + y   x - 2⋅y⎥  ⎡-x - y    -x + y⎤    ⎢x + y    x - 2⋅y ⎥ \n\
+⎢                ⎥  ⎢───────   ──────⎥    ⎢                 ⎥ \n\
+⎢     2    2     ⎥  ⎢x - 2⋅y   x + y ⎥    ⎢      2     2    ⎥ \n\
+⎢x - y    x  + y ⎥  ⎢                ⎥    ⎢-x + y   - x  - y⎥ \n\
+⎢──────   ────── ⎥ ⋅⎢   2           2⎥  + ⎢───────  ────────⎥ \n\
+⎢ 3       -x + y ⎥  ⎢- x  - y  x - y ⎥    ⎢ 3        -x + y ⎥ \n\
+⎢x  + x          ⎥  ⎢────────  ──────⎥    ⎢x  + x           ⎥ \n\
+⎢                ⎥  ⎢ -x + y    3    ⎥    ⎢                 ⎥ \n\
+⎢-x - y   -x + y ⎥  ⎣          x  + x⎦τ   ⎢ x + y    x - y  ⎥ \n\
+⎢───────  ────── ⎥                        ⎢───────   ─────  ⎥ \n\
+⎣x - 2⋅y  x + y  ⎦τ                       ⎣x - 2⋅y   x + y  ⎦τ\
+"""
+    assert upretty(Parallel(tf1, tf2)) == expected1
+    assert upretty(Parallel(-tf2, -tf1)) == expected2
+    assert upretty(Parallel(tf3, tf1, Series(-tf1, tf2))) == expected3
+    assert upretty(Parallel(Series(tf1, tf2), Series(tf2, tf3))) == expected4
+    assert upretty(MIMOParallel(-tfm3, -tfm2, tfm1)) == expected5
+    assert upretty(MIMOParallel(MIMOSeries(tfm4, -tfm2), tfm2)) == expected6
+
+
+def test_pretty_Feedback():
+    tf = TransferFunction(1, 1, y)
+    tf1 = TransferFunction(x + y, x - 2*y, y)
+    tf2 = TransferFunction(x - y, x + y, y)
+    tf3 = TransferFunction(y**2 - 2*y + 1, y + 5, y)
+    tf4 = TransferFunction(x - 2*y**3, x + y, x)
+    tf5 = TransferFunction(1 - x, x - y, y)
+    tf6 = TransferFunction(2, 2, x)
+    expected1 = \
+"""\
+     ⎛1⎞     \n\
+     ⎜─⎟     \n\
+     ⎝1⎠     \n\
+─────────────\n\
+1   ⎛ x + y ⎞\n\
+─ + ⎜───────⎟\n\
+1   ⎝x - 2⋅y⎠\
+"""
+    expected2 = \
+"""\
+                ⎛1⎞                 \n\
+                ⎜─⎟                 \n\
+                ⎝1⎠                 \n\
+────────────────────────────────────\n\
+                      ⎛ 2          ⎞\n\
+1   ⎛x - y⎞ ⎛ x + y ⎞ ⎜y  - 2⋅y + 1⎟\n\
+─ + ⎜─────⎟⋅⎜───────⎟⋅⎜────────────⎟\n\
+1   ⎝x + y⎠ ⎝x - 2⋅y⎠ ⎝   y + 5    ⎠\
+"""
+    expected3 = \
+"""\
+                 ⎛ x + y ⎞                  \n\
+                 ⎜───────⎟                  \n\
+                 ⎝x - 2⋅y⎠                  \n\
+────────────────────────────────────────────\n\
+                      ⎛ 2          ⎞        \n\
+1   ⎛ x + y ⎞ ⎛x - y⎞ ⎜y  - 2⋅y + 1⎟ ⎛1 - x⎞\n\
+─ + ⎜───────⎟⋅⎜─────⎟⋅⎜────────────⎟⋅⎜─────⎟\n\
+1   ⎝x - 2⋅y⎠ ⎝x + y⎠ ⎝   y + 5    ⎠ ⎝x - y⎠\
+"""
+    expected4 = \
+"""\
+  ⎛ x + y ⎞ ⎛x - y⎞  \n\
+  ⎜───────⎟⋅⎜─────⎟  \n\
+  ⎝x - 2⋅y⎠ ⎝x + y⎠  \n\
+─────────────────────\n\
+1   ⎛ x + y ⎞ ⎛x - y⎞\n\
+─ + ⎜───────⎟⋅⎜─────⎟\n\
+1   ⎝x - 2⋅y⎠ ⎝x + y⎠\
+"""
+    expected5 = \
+"""\
+      ⎛ x + y ⎞ ⎛x - y⎞      \n\
+      ⎜───────⎟⋅⎜─────⎟      \n\
+      ⎝x - 2⋅y⎠ ⎝x + y⎠      \n\
+─────────────────────────────\n\
+1   ⎛ x + y ⎞ ⎛x - y⎞ ⎛1 - x⎞\n\
+─ + ⎜───────⎟⋅⎜─────⎟⋅⎜─────⎟\n\
+1   ⎝x - 2⋅y⎠ ⎝x + y⎠ ⎝x - y⎠\
+"""
+    expected6 = \
+"""\
+           ⎛ 2          ⎞                   \n\
+           ⎜y  - 2⋅y + 1⎟ ⎛1 - x⎞           \n\
+           ⎜────────────⎟⋅⎜─────⎟           \n\
+           ⎝   y + 5    ⎠ ⎝x - y⎠           \n\
+────────────────────────────────────────────\n\
+    ⎛ 2          ⎞                          \n\
+1   ⎜y  - 2⋅y + 1⎟ ⎛1 - x⎞ ⎛x - y⎞ ⎛ x + y ⎞\n\
+─ + ⎜────────────⎟⋅⎜─────⎟⋅⎜─────⎟⋅⎜───────⎟\n\
+1   ⎝   y + 5    ⎠ ⎝x - y⎠ ⎝x + y⎠ ⎝x - 2⋅y⎠\
+"""
+    expected7 = \
+"""\
+    ⎛       3⎞    \n\
+    ⎜x - 2⋅y ⎟    \n\
+    ⎜────────⎟    \n\
+    ⎝ x + y  ⎠    \n\
+──────────────────\n\
+    ⎛       3⎞    \n\
+1   ⎜x - 2⋅y ⎟ ⎛2⎞\n\
+─ + ⎜────────⎟⋅⎜─⎟\n\
+1   ⎝ x + y  ⎠ ⎝2⎠\
+"""
+    expected8 = \
+"""\
+  ⎛1 - x⎞  \n\
+  ⎜─────⎟  \n\
+  ⎝x - y⎠  \n\
+───────────\n\
+1   ⎛1 - x⎞\n\
+─ + ⎜─────⎟\n\
+1   ⎝x - y⎠\
+"""
+    expected9 = \
+"""\
+      ⎛ x + y ⎞ ⎛x - y⎞      \n\
+      ⎜───────⎟⋅⎜─────⎟      \n\
+      ⎝x - 2⋅y⎠ ⎝x + y⎠      \n\
+─────────────────────────────\n\
+1   ⎛ x + y ⎞ ⎛x - y⎞ ⎛1 - x⎞\n\
+─ - ⎜───────⎟⋅⎜─────⎟⋅⎜─────⎟\n\
+1   ⎝x - 2⋅y⎠ ⎝x + y⎠ ⎝x - y⎠\
+"""
+    expected10 = \
+"""\
+  ⎛1 - x⎞  \n\
+  ⎜─────⎟  \n\
+  ⎝x - y⎠  \n\
+───────────\n\
+1   ⎛1 - x⎞\n\
+─ - ⎜─────⎟\n\
+1   ⎝x - y⎠\
+"""
+    assert upretty(Feedback(tf, tf1)) == expected1
+    assert upretty(Feedback(tf, tf2*tf1*tf3)) == expected2
+    assert upretty(Feedback(tf1, tf2*tf3*tf5)) == expected3
+    assert upretty(Feedback(tf1*tf2, tf)) == expected4
+    assert upretty(Feedback(tf1*tf2, tf5)) == expected5
+    assert upretty(Feedback(tf3*tf5, tf2*tf1)) == expected6
+    assert upretty(Feedback(tf4, tf6)) == expected7
+    assert upretty(Feedback(tf5, tf)) == expected8
+
+    assert upretty(Feedback(tf1*tf2, tf5, 1)) == expected9
+    assert upretty(Feedback(tf5, tf, 1)) == expected10
+
+
+def test_pretty_MIMOFeedback():
+    tf1 = TransferFunction(x + y, x - 2*y, y)
+    tf2 = TransferFunction(x - y, x + y, y)
+    tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
+    tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]])
+    tfm_3 = TransferFunctionMatrix([[tf1, tf1], [tf2, tf2]])
+
+    expected1 = \
+"""\
+⎛    ⎡ x + y    x - y ⎤  ⎡ x - y    x + y ⎤ ⎞-1   ⎡ x + y    x - y ⎤ \n\
+⎜    ⎢───────   ───── ⎥  ⎢ ─────   ───────⎥ ⎟     ⎢───────   ───── ⎥ \n\
+⎜    ⎢x - 2⋅y   x + y ⎥  ⎢ x + y   x - 2⋅y⎥ ⎟     ⎢x - 2⋅y   x + y ⎥ \n\
+⎜I - ⎢                ⎥ ⋅⎢                ⎥ ⎟   ⋅ ⎢                ⎥ \n\
+⎜    ⎢ x - y    x + y ⎥  ⎢ x + y    x - y ⎥ ⎟     ⎢ x - y    x + y ⎥ \n\
+⎜    ⎢ ─────   ───────⎥  ⎢───────   ───── ⎥ ⎟     ⎢ ─────   ───────⎥ \n\
+⎝    ⎣ x + y   x - 2⋅y⎦τ ⎣x - 2⋅y   x + y ⎦τ⎠     ⎣ x + y   x - 2⋅y⎦τ\
+"""
+    expected2 = \
+"""\
+⎛    ⎡ x + y    x - y ⎤  ⎡ x - y    x + y ⎤  ⎡ x + y    x + y ⎤ ⎞-1   ⎡ x + y    x - y ⎤  ⎡ x - y    x + y ⎤ \n\
+⎜    ⎢───────   ───── ⎥  ⎢ ─────   ───────⎥  ⎢───────  ───────⎥ ⎟     ⎢───────   ───── ⎥  ⎢ ─────   ───────⎥ \n\
+⎜    ⎢x - 2⋅y   x + y ⎥  ⎢ x + y   x - 2⋅y⎥  ⎢x - 2⋅y  x - 2⋅y⎥ ⎟     ⎢x - 2⋅y   x + y ⎥  ⎢ x + y   x - 2⋅y⎥ \n\
+⎜I + ⎢                ⎥ ⋅⎢                ⎥ ⋅⎢                ⎥ ⎟   ⋅ ⎢                ⎥ ⋅⎢                ⎥ \n\
+⎜    ⎢ x - y    x + y ⎥  ⎢ x + y    x - y ⎥  ⎢ x - y    x - y ⎥ ⎟     ⎢ x - y    x + y ⎥  ⎢ x + y    x - y ⎥ \n\
+⎜    ⎢ ─────   ───────⎥  ⎢───────   ───── ⎥  ⎢ ─────    ───── ⎥ ⎟     ⎢ ─────   ───────⎥  ⎢───────   ───── ⎥ \n\
+⎝    ⎣ x + y   x - 2⋅y⎦τ ⎣x - 2⋅y   x + y ⎦τ ⎣ x + y    x + y ⎦τ⎠     ⎣ x + y   x - 2⋅y⎦τ ⎣x - 2⋅y   x + y ⎦τ\
+"""
+
+    assert upretty(MIMOFeedback(tfm_1, tfm_2, 1)) == \
+        expected1  # Positive MIMOFeedback
+    assert upretty(MIMOFeedback(tfm_1*tfm_2, tfm_3)) == \
+        expected2  # Negative MIMOFeedback (Default)
+
+
+def test_pretty_TransferFunctionMatrix():
+    tf1 = TransferFunction(x + y, x - 2*y, y)
+    tf2 = TransferFunction(x - y, x + y, y)
+    tf3 = TransferFunction(y**2 - 2*y + 1, y + 5, y)
+    tf4 = TransferFunction(y, x**2 + x + 1, y)
+    tf5 = TransferFunction(1 - x, x - y, y)
+    tf6 = TransferFunction(2, 2, y)
+    expected1 = \
+"""\
+⎡ x + y ⎤ \n\
+⎢───────⎥ \n\
+⎢x - 2⋅y⎥ \n\
+⎢       ⎥ \n\
+⎢ x - y ⎥ \n\
+⎢ ───── ⎥ \n\
+⎣ x + y ⎦τ\
+"""
+    expected2 = \
+"""\
+⎡    x + y     ⎤ \n\
+⎢   ───────    ⎥ \n\
+⎢   x - 2⋅y    ⎥ \n\
+⎢              ⎥ \n\
+⎢    x - y     ⎥ \n\
+⎢    ─────     ⎥ \n\
+⎢    x + y     ⎥ \n\
+⎢              ⎥ \n\
+⎢   2          ⎥ \n\
+⎢- y  + 2⋅y - 1⎥ \n\
+⎢──────────────⎥ \n\
+⎣    y + 5     ⎦τ\
+"""
+    expected3 = \
+"""\
+⎡   x + y        x - y   ⎤ \n\
+⎢  ───────       ─────   ⎥ \n\
+⎢  x - 2⋅y       x + y   ⎥ \n\
+⎢                        ⎥ \n\
+⎢ 2                      ⎥ \n\
+⎢y  - 2⋅y + 1      y     ⎥ \n\
+⎢────────────  ──────────⎥ \n\
+⎢   y + 5       2        ⎥ \n\
+⎢              x  + x + 1⎥ \n\
+⎢                        ⎥ \n\
+⎢   1 - x          2     ⎥ \n\
+⎢   ─────          ─     ⎥ \n\
+⎣   x - y          2     ⎦τ\
+"""
+    expected4 = \
+"""\
+⎡    x - y        x + y       y     ⎤ \n\
+⎢    ─────       ───────  ──────────⎥ \n\
+⎢    x + y       x - 2⋅y   2        ⎥ \n\
+⎢                         x  + x + 1⎥ \n\
+⎢                                   ⎥ \n\
+⎢   2                               ⎥ \n\
+⎢- y  + 2⋅y - 1   x - 1      -2     ⎥ \n\
+⎢──────────────   ─────      ───    ⎥ \n\
+⎣    y + 5        x - y       2     ⎦τ\
+"""
+    expected5 = \
+"""\
+⎡ x + y  x - y   x + y       y     ⎤ \n\
+⎢───────⋅─────  ───────  ──────────⎥ \n\
+⎢x - 2⋅y x + y  x - 2⋅y   2        ⎥ \n\
+⎢                        x  + x + 1⎥ \n\
+⎢                                  ⎥ \n\
+⎢  1 - x   2     x + y      -2     ⎥ \n\
+⎢  ───── + ─    ───────     ───    ⎥ \n\
+⎣  x - y   2    x - 2⋅y      2     ⎦τ\
+"""
+
+    assert upretty(TransferFunctionMatrix([[tf1], [tf2]])) == expected1
+    assert upretty(TransferFunctionMatrix([[tf1], [tf2], [-tf3]])) == expected2
+    assert upretty(TransferFunctionMatrix([[tf1, tf2], [tf3, tf4], [tf5, tf6]])) == expected3
+    assert upretty(TransferFunctionMatrix([[tf2, tf1, tf4], [-tf3, -tf5, -tf6]])) == expected4
+    assert upretty(TransferFunctionMatrix([[Series(tf2, tf1), tf1, tf4], [Parallel(tf6, tf5), tf1, -tf6]])) == \
+        expected5
+
+
+def test_pretty_StateSpace():
+    ss1 = StateSpace(Matrix([a]), Matrix([b]), Matrix([c]), Matrix([d]))
+    A = Matrix([[0, 1], [1, 0]])
+    B = Matrix([1, 0])
+    C = Matrix([[0, 1]])
+    D = Matrix([0])
+    ss2 = StateSpace(A, B, C, D)
+    ss3 = StateSpace(Matrix([[-1.5, -2], [1, 0]]),
+                    Matrix([[0.5, 0], [0, 1]]),
+                    Matrix([[0, 1], [0, 2]]),
+                    Matrix([[2, 2], [1, 1]]))
+
+    expected1 = \
+"""\
+⎡[a]  [b]⎤\n\
+⎢        ⎥\n\
+⎣[c]  [d]⎦\
+"""
+    expected2 = \
+"""\
+⎡⎡0  1⎤  ⎡1⎤⎤\n\
+⎢⎢    ⎥  ⎢ ⎥⎥\n\
+⎢⎣1  0⎦  ⎣0⎦⎥\n\
+⎢           ⎥\n\
+⎣[0  1]  [0]⎦\
+"""
+    expected3 = \
+"""\
+⎡⎡-1.5  -2⎤  ⎡0.5  0⎤⎤\n\
+⎢⎢        ⎥  ⎢      ⎥⎥\n\
+⎢⎣ 1    0 ⎦  ⎣ 0   1⎦⎥\n\
+⎢                    ⎥\n\
+⎢  ⎡0  1⎤     ⎡2  2⎤ ⎥\n\
+⎢  ⎢    ⎥     ⎢    ⎥ ⎥\n\
+⎣  ⎣0  2⎦     ⎣1  1⎦ ⎦\
+"""
+
+    assert upretty(ss1) == expected1
+    assert upretty(ss2) == expected2
+    assert upretty(ss3) == expected3
+
+def test_pretty_order():
+    expr = O(1)
+    ascii_str = \
+"""\
+O(1)\
+"""
+    ucode_str = \
+"""\
+O(1)\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = O(1/x)
+    ascii_str = \
+"""\
+ /1\\\n\
+O|-|\n\
+ \\x/\
+"""
+    ucode_str = \
+"""\
+ ⎛1⎞\n\
+O⎜─⎟\n\
+ ⎝x⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = O(x**2 + y**2)
+    ascii_str = \
+"""\
+ / 2    2                  \\\n\
+O\\x  + y ; (x, y) -> (0, 0)/\
+"""
+    ucode_str = \
+"""\
+ ⎛ 2    2                 ⎞\n\
+O⎝x  + y ; (x, y) → (0, 0)⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = O(1, (x, oo))
+    ascii_str = \
+"""\
+O(1; x -> oo)\
+"""
+    ucode_str = \
+"""\
+O(1; x → ∞)\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = O(1/x, (x, oo))
+    ascii_str = \
+"""\
+ /1         \\\n\
+O|-; x -> oo|\n\
+ \\x         /\
+"""
+    ucode_str = \
+"""\
+ ⎛1       ⎞\n\
+O⎜─; x → ∞⎟\n\
+ ⎝x       ⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = O(x**2 + y**2, (x, oo), (y, oo))
+    ascii_str = \
+"""\
+ / 2    2                    \\\n\
+O\\x  + y ; (x, y) -> (oo, oo)/\
+"""
+    ucode_str = \
+"""\
+ ⎛ 2    2                 ⎞\n\
+O⎝x  + y ; (x, y) → (∞, ∞)⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_pretty_derivatives():
+    # Simple
+    expr = Derivative(log(x), x, evaluate=False)
+    ascii_str = \
+"""\
+d         \n\
+--(log(x))\n\
+dx        \
+"""
+    ucode_str = \
+"""\
+d         \n\
+──(log(x))\n\
+dx        \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Derivative(log(x), x, evaluate=False) + x
+    ascii_str_1 = \
+"""\
+    d         \n\
+x + --(log(x))\n\
+    dx        \
+"""
+    ascii_str_2 = \
+"""\
+d             \n\
+--(log(x)) + x\n\
+dx            \
+"""
+    ucode_str_1 = \
+"""\
+    d         \n\
+x + ──(log(x))\n\
+    dx        \
+"""
+    ucode_str_2 = \
+"""\
+d             \n\
+──(log(x)) + x\n\
+dx            \
+"""
+    assert pretty(expr) in [ascii_str_1, ascii_str_2]
+    assert upretty(expr) in [ucode_str_1, ucode_str_2]
+
+    # basic partial derivatives
+    expr = Derivative(log(x + y) + x, x)
+    ascii_str_1 = \
+"""\
+d                 \n\
+--(log(x + y) + x)\n\
+dx                \
+"""
+    ascii_str_2 = \
+"""\
+d                 \n\
+--(x + log(x + y))\n\
+dx                \
+"""
+    ucode_str_1 = \
+"""\
+∂                 \n\
+──(log(x + y) + x)\n\
+∂x                \
+"""
+    ucode_str_2 = \
+"""\
+∂                 \n\
+──(x + log(x + y))\n\
+∂x                \
+"""
+    assert pretty(expr) in [ascii_str_1, ascii_str_2]
+    assert upretty(expr) in [ucode_str_1, ucode_str_2], upretty(expr)
+
+    # Multiple symbols
+    expr = Derivative(log(x) + x**2, x, y)
+    ascii_str_1 = \
+"""\
+   2              \n\
+  d  /          2\\\n\
+-----\\log(x) + x /\n\
+dy dx             \
+"""
+    ascii_str_2 = \
+"""\
+   2              \n\
+  d  / 2         \\\n\
+-----\\x  + log(x)/\n\
+dy dx             \
+"""
+    ascii_str_3 = \
+"""\
+  2               \n\
+ d   / 2         \\\n\
+-----\\x  + log(x)/\n\
+dy dx             \
+"""
+    ucode_str_1 = \
+"""\
+   2              \n\
+  d  ⎛          2⎞\n\
+─────⎝log(x) + x ⎠\n\
+dy dx             \
+"""
+    ucode_str_2 = \
+"""\
+   2              \n\
+  d  ⎛ 2         ⎞\n\
+─────⎝x  + log(x)⎠\n\
+dy dx             \
+"""
+    ucode_str_3 = \
+"""\
+  2               \n\
+ d   ⎛ 2         ⎞\n\
+─────⎝x  + log(x)⎠\n\
+dy dx             \
+"""
+    assert pretty(expr) in [ascii_str_1, ascii_str_2, ascii_str_3]
+    assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3]
+
+    expr = Derivative(2*x*y, y, x) + x**2
+    ascii_str_1 = \
+"""\
+   2             \n\
+  d             2\n\
+-----(2*x*y) + x \n\
+dx dy            \
+"""
+    ascii_str_2 = \
+"""\
+        2        \n\
+ 2     d         \n\
+x  + -----(2*x*y)\n\
+     dx dy       \
+"""
+    ascii_str_3 = \
+"""\
+       2         \n\
+ 2    d          \n\
+x  + -----(2*x*y)\n\
+     dx dy       \
+"""
+    ucode_str_1 = \
+"""\
+   2             \n\
+  ∂             2\n\
+─────(2⋅x⋅y) + x \n\
+∂x ∂y            \
+"""
+    ucode_str_2 = \
+"""\
+        2        \n\
+ 2     ∂         \n\
+x  + ─────(2⋅x⋅y)\n\
+     ∂x ∂y       \
+"""
+    ucode_str_3 = \
+"""\
+       2         \n\
+ 2    ∂          \n\
+x  + ─────(2⋅x⋅y)\n\
+     ∂x ∂y       \
+"""
+    assert pretty(expr) in [ascii_str_1, ascii_str_2, ascii_str_3]
+    assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3]
+
+    expr = Derivative(2*x*y, x, x)
+    ascii_str = \
+"""\
+ 2        \n\
+d         \n\
+---(2*x*y)\n\
+  2       \n\
+dx        \
+"""
+    ucode_str = \
+"""\
+ 2        \n\
+∂         \n\
+───(2⋅x⋅y)\n\
+  2       \n\
+∂x        \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Derivative(2*x*y, x, 17)
+    ascii_str = \
+"""\
+ 17        \n\
+d          \n\
+----(2*x*y)\n\
+  17       \n\
+dx         \
+"""
+    ucode_str = \
+"""\
+ 17        \n\
+∂          \n\
+────(2⋅x⋅y)\n\
+  17       \n\
+∂x         \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Derivative(2*x*y, x, x, y)
+    ascii_str = \
+"""\
+   3         \n\
+  d          \n\
+------(2*x*y)\n\
+     2       \n\
+dy dx        \
+"""
+    ucode_str = \
+"""\
+   3         \n\
+  ∂          \n\
+──────(2⋅x⋅y)\n\
+     2       \n\
+∂y ∂x        \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    # Greek letters
+    alpha = Symbol('alpha')
+    beta = Function('beta')
+    expr = beta(alpha).diff(alpha)
+    ascii_str = \
+"""\
+  d                \n\
+------(beta(alpha))\n\
+dalpha             \
+"""
+    ucode_str = \
+"""\
+d       \n\
+──(β(α))\n\
+dα      \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Derivative(f(x), (x, n))
+
+    ascii_str = \
+"""\
+ n       \n\
+d        \n\
+---(f(x))\n\
+  n      \n\
+dx       \
+"""
+    ucode_str = \
+"""\
+ n       \n\
+d        \n\
+───(f(x))\n\
+  n      \n\
+dx       \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_pretty_integrals():
+    expr = Integral(log(x), x)
+    ascii_str = \
+"""\
+  /         \n\
+ |          \n\
+ | log(x) dx\n\
+ |          \n\
+/           \
+"""
+    ucode_str = \
+"""\
+⌠          \n\
+⎮ log(x) dx\n\
+⌡          \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Integral(x**2, x)
+    ascii_str = \
+"""\
+  /     \n\
+ |      \n\
+ |  2   \n\
+ | x  dx\n\
+ |      \n\
+/       \
+"""
+    ucode_str = \
+"""\
+⌠      \n\
+⎮  2   \n\
+⎮ x  dx\n\
+⌡      \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Integral((sin(x))**2 / (tan(x))**2)
+    ascii_str = \
+"""\
+  /          \n\
+ |           \n\
+ |    2      \n\
+ | sin (x)   \n\
+ | ------- dx\n\
+ |    2      \n\
+ | tan (x)   \n\
+ |           \n\
+/            \
+"""
+    ucode_str = \
+"""\
+⌠           \n\
+⎮    2      \n\
+⎮ sin (x)   \n\
+⎮ ─────── dx\n\
+⎮    2      \n\
+⎮ tan (x)   \n\
+⌡           \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Integral(x**(2**x), x)
+    ascii_str = \
+"""\
+  /        \n\
+ |         \n\
+ |  / x\\   \n\
+ |  \\2 /   \n\
+ | x     dx\n\
+ |         \n\
+/          \
+"""
+    ucode_str = \
+"""\
+⌠         \n\
+⎮  ⎛ x⎞   \n\
+⎮  ⎝2 ⎠   \n\
+⎮ x     dx\n\
+⌡         \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Integral(x**2, (x, 1, 2))
+    ascii_str = \
+"""\
+  2      \n\
+  /      \n\
+ |       \n\
+ |   2   \n\
+ |  x  dx\n\
+ |       \n\
+/        \n\
+1        \
+"""
+    ucode_str = \
+"""\
+2      \n\
+⌠      \n\
+⎮  2   \n\
+⎮ x  dx\n\
+⌡      \n\
+1      \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Integral(x**2, (x, Rational(1, 2), 10))
+    ascii_str = \
+"""\
+ 10      \n\
+  /      \n\
+ |       \n\
+ |   2   \n\
+ |  x  dx\n\
+ |       \n\
+/        \n\
+1/2      \
+"""
+    ucode_str = \
+"""\
+10       \n\
+⌠        \n\
+⎮    2   \n\
+⎮   x  dx\n\
+⌡        \n\
+1/2      \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Integral(x**2*y**2, x, y)
+    ascii_str = \
+"""\
+  /  /           \n\
+ |  |            \n\
+ |  |  2  2      \n\
+ |  | x *y  dx dy\n\
+ |  |            \n\
+/  /             \
+"""
+    ucode_str = \
+"""\
+⌠ ⌠            \n\
+⎮ ⎮  2  2      \n\
+⎮ ⎮ x ⋅y  dx dy\n\
+⌡ ⌡            \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Integral(sin(th)/cos(ph), (th, 0, pi), (ph, 0, 2*pi))
+    ascii_str = \
+"""\
+ 2*pi pi                           \n\
+   /   /                           \n\
+  |   |                            \n\
+  |   |  sin(theta)                \n\
+  |   |  ---------- d(theta) d(phi)\n\
+  |   |   cos(phi)                 \n\
+  |   |                            \n\
+ /   /                             \n\
+0    0                             \
+"""
+    ucode_str = \
+"""\
+2⋅π π             \n\
+ ⌠  ⌠             \n\
+ ⎮  ⎮ sin(θ)      \n\
+ ⎮  ⎮ ────── dθ dφ\n\
+ ⎮  ⎮ cos(φ)      \n\
+ ⌡  ⌡             \n\
+ 0  0             \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_pretty_matrix():
+    # Empty Matrix
+    expr = Matrix()
+    ascii_str = "[]"
+    unicode_str = "[]"
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == unicode_str
+    expr = Matrix(2, 0, lambda i, j: 0)
+    ascii_str = "[]"
+    unicode_str = "[]"
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == unicode_str
+    expr = Matrix(0, 2, lambda i, j: 0)
+    ascii_str = "[]"
+    unicode_str = "[]"
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == unicode_str
+    expr = Matrix([[x**2 + 1, 1], [y, x + y]])
+    ascii_str_1 = \
+"""\
+[     2       ]
+[1 + x     1  ]
+[             ]
+[  y     x + y]\
+"""
+    ascii_str_2 = \
+"""\
+[ 2           ]
+[x  + 1    1  ]
+[             ]
+[  y     x + y]\
+"""
+    ucode_str_1 = \
+"""\
+⎡     2       ⎤
+⎢1 + x     1  ⎥
+⎢             ⎥
+⎣  y     x + y⎦\
+"""
+    ucode_str_2 = \
+"""\
+⎡ 2           ⎤
+⎢x  + 1    1  ⎥
+⎢             ⎥
+⎣  y     x + y⎦\
+"""
+    assert pretty(expr) in [ascii_str_1, ascii_str_2]
+    assert upretty(expr) in [ucode_str_1, ucode_str_2]
+
+    expr = Matrix([[x/y, y, th], [0, exp(I*k*ph), 1]])
+    ascii_str = \
+"""\
+[x                 ]
+[-     y      theta]
+[y                 ]
+[                  ]
+[    I*k*phi       ]
+[0  e           1  ]\
+"""
+    ucode_str = \
+"""\
+⎡x           ⎤
+⎢─    y     θ⎥
+⎢y           ⎥
+⎢            ⎥
+⎢    ⅈ⋅k⋅φ   ⎥
+⎣0  ℯ       1⎦\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    unicode_str = \
+"""\
+⎡v̇_msc_00     0         0    ⎤
+⎢                            ⎥
+⎢   0      v̇_msc_01     0    ⎥
+⎢                            ⎥
+⎣   0         0      v̇_msc_02⎦\
+"""
+
+    expr = diag(*MatrixSymbol('vdot_msc',1,3))
+    assert upretty(expr) == unicode_str
+
+
+def test_pretty_ndim_arrays():
+    x, y, z, w = symbols("x y z w")
+
+    for ArrayType in (ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray):
+        # Basic: scalar array
+        M = ArrayType(x)
+
+        assert pretty(M) == "x"
+        assert upretty(M) == "x"
+
+        M = ArrayType([[1/x, y], [z, w]])
+        M1 = ArrayType([1/x, y, z])
+
+        M2 = tensorproduct(M1, M)
+        M3 = tensorproduct(M, M)
+
+        ascii_str = \
+"""\
+[1   ]\n\
+[-  y]\n\
+[x   ]\n\
+[    ]\n\
+[z  w]\
+"""
+        ucode_str = \
+"""\
+⎡1   ⎤\n\
+⎢─  y⎥\n\
+⎢x   ⎥\n\
+⎢    ⎥\n\
+⎣z  w⎦\
+"""
+        assert pretty(M) == ascii_str
+        assert upretty(M) == ucode_str
+
+        ascii_str = \
+"""\
+[1      ]\n\
+[-  y  z]\n\
+[x      ]\
+"""
+        ucode_str = \
+"""\
+⎡1      ⎤\n\
+⎢─  y  z⎥\n\
+⎣x      ⎦\
+"""
+        assert pretty(M1) == ascii_str
+        assert upretty(M1) == ucode_str
+
+        ascii_str = \
+"""\
+[[1   y]                       ]\n\
+[[--  -]              [z      ]]\n\
+[[ 2  x]  [ y    2 ]  [-   y*z]]\n\
+[[x    ]  [ -   y  ]  [x      ]]\n\
+[[     ]  [ x      ]  [       ]]\n\
+[[z   w]  [        ]  [ 2     ]]\n\
+[[-   -]  [y*z  w*y]  [z   w*z]]\n\
+[[x   x]                       ]\
+"""
+        ucode_str = \
+"""\
+⎡⎡1   y⎤                       ⎤\n\
+⎢⎢──  ─⎥              ⎡z      ⎤⎥\n\
+⎢⎢ 2  x⎥  ⎡ y    2 ⎤  ⎢─   y⋅z⎥⎥\n\
+⎢⎢x    ⎥  ⎢ ─   y  ⎥  ⎢x      ⎥⎥\n\
+⎢⎢     ⎥  ⎢ x      ⎥  ⎢       ⎥⎥\n\
+⎢⎢z   w⎥  ⎢        ⎥  ⎢ 2     ⎥⎥\n\
+⎢⎢─   ─⎥  ⎣y⋅z  w⋅y⎦  ⎣z   w⋅z⎦⎥\n\
+⎣⎣x   x⎦                       ⎦\
+"""
+        assert pretty(M2) == ascii_str
+        assert upretty(M2) == ucode_str
+
+        ascii_str = \
+"""\
+[ [1   y]             ]\n\
+[ [--  -]             ]\n\
+[ [ 2  x]   [ y    2 ]]\n\
+[ [x    ]   [ -   y  ]]\n\
+[ [     ]   [ x      ]]\n\
+[ [z   w]   [        ]]\n\
+[ [-   -]   [y*z  w*y]]\n\
+[ [x   x]             ]\n\
+[                     ]\n\
+[[z      ]  [ w      ]]\n\
+[[-   y*z]  [ -   w*y]]\n\
+[[x      ]  [ x      ]]\n\
+[[       ]  [        ]]\n\
+[[ 2     ]  [      2 ]]\n\
+[[z   w*z]  [w*z  w  ]]\
+"""
+        ucode_str = \
+"""\
+⎡ ⎡1   y⎤             ⎤\n\
+⎢ ⎢──  ─⎥             ⎥\n\
+⎢ ⎢ 2  x⎥   ⎡ y    2 ⎤⎥\n\
+⎢ ⎢x    ⎥   ⎢ ─   y  ⎥⎥\n\
+⎢ ⎢     ⎥   ⎢ x      ⎥⎥\n\
+⎢ ⎢z   w⎥   ⎢        ⎥⎥\n\
+⎢ ⎢─   ─⎥   ⎣y⋅z  w⋅y⎦⎥\n\
+⎢ ⎣x   x⎦             ⎥\n\
+⎢                     ⎥\n\
+⎢⎡z      ⎤  ⎡ w      ⎤⎥\n\
+⎢⎢─   y⋅z⎥  ⎢ ─   w⋅y⎥⎥\n\
+⎢⎢x      ⎥  ⎢ x      ⎥⎥\n\
+⎢⎢       ⎥  ⎢        ⎥⎥\n\
+⎢⎢ 2     ⎥  ⎢      2 ⎥⎥\n\
+⎣⎣z   w⋅z⎦  ⎣w⋅z  w  ⎦⎦\
+"""
+        assert pretty(M3) == ascii_str
+        assert upretty(M3) == ucode_str
+
+        Mrow = ArrayType([[x, y, 1 / z]])
+        Mcolumn = ArrayType([[x], [y], [1 / z]])
+        Mcol2 = ArrayType([Mcolumn.tolist()])
+
+        ascii_str = \
+"""\
+[[      1]]\n\
+[[x  y  -]]\n\
+[[      z]]\
+"""
+        ucode_str = \
+"""\
+⎡⎡      1⎤⎤\n\
+⎢⎢x  y  ─⎥⎥\n\
+⎣⎣      z⎦⎦\
+"""
+        assert pretty(Mrow) == ascii_str
+        assert upretty(Mrow) == ucode_str
+
+        ascii_str = \
+"""\
+[x]\n\
+[ ]\n\
+[y]\n\
+[ ]\n\
+[1]\n\
+[-]\n\
+[z]\
+"""
+        ucode_str = \
+"""\
+⎡x⎤\n\
+⎢ ⎥\n\
+⎢y⎥\n\
+⎢ ⎥\n\
+⎢1⎥\n\
+⎢─⎥\n\
+⎣z⎦\
+"""
+        assert pretty(Mcolumn) == ascii_str
+        assert upretty(Mcolumn) == ucode_str
+
+        ascii_str = \
+"""\
+[[x]]\n\
+[[ ]]\n\
+[[y]]\n\
+[[ ]]\n\
+[[1]]\n\
+[[-]]\n\
+[[z]]\
+"""
+        ucode_str = \
+"""\
+⎡⎡x⎤⎤\n\
+⎢⎢ ⎥⎥\n\
+⎢⎢y⎥⎥\n\
+⎢⎢ ⎥⎥\n\
+⎢⎢1⎥⎥\n\
+⎢⎢─⎥⎥\n\
+⎣⎣z⎦⎦\
+"""
+        assert pretty(Mcol2) == ascii_str
+        assert upretty(Mcol2) == ucode_str
+
+
+def test_tensor_TensorProduct():
+    A = MatrixSymbol("A", 3, 3)
+    B = MatrixSymbol("B", 3, 3)
+    assert upretty(TensorProduct(A, B)) == "A\u2297B"
+    assert upretty(TensorProduct(A, B, A)) == "A\u2297B\u2297A"
+
+
+def test_diffgeom_print_WedgeProduct():
+    from sympy.diffgeom.rn import R2
+    from sympy.diffgeom import WedgeProduct
+    wp = WedgeProduct(R2.dx, R2.dy)
+    assert upretty(wp) == "ⅆ x∧ⅆ y"
+    assert pretty(wp) == r"d x/\d y"
+
+
+def test_Adjoint():
+    X = MatrixSymbol('X', 2, 2)
+    Y = MatrixSymbol('Y', 2, 2)
+    assert pretty(Adjoint(X)) == " +\nX "
+    assert pretty(Adjoint(X + Y)) == "       +\n(X + Y) "
+    assert pretty(Adjoint(X) + Adjoint(Y)) == " +    +\nX  + Y "
+    assert pretty(Adjoint(X*Y)) == "     +\n(X*Y) "
+    assert pretty(Adjoint(Y)*Adjoint(X)) == " +  +\nY *X "
+    assert pretty(Adjoint(X**2)) == "    +\n/ 2\\ \n\\X / "
+    assert pretty(Adjoint(X)**2) == "    2\n/ +\\ \n\\X / "
+    assert pretty(Adjoint(Inverse(X))) == "     +\n/ -1\\ \n\\X  / "
+    assert pretty(Inverse(Adjoint(X))) == "    -1\n/ +\\  \n\\X /  "
+    assert pretty(Adjoint(Transpose(X))) == "    +\n/ T\\ \n\\X / "
+    assert pretty(Transpose(Adjoint(X))) == "    T\n/ +\\ \n\\X / "
+    assert upretty(Adjoint(X)) == " †\nX "
+    assert upretty(Adjoint(X + Y)) == "       †\n(X + Y) "
+    assert upretty(Adjoint(X) + Adjoint(Y)) == " †    †\nX  + Y "
+    assert upretty(Adjoint(X*Y)) == "     †\n(X⋅Y) "
+    assert upretty(Adjoint(Y)*Adjoint(X)) == " †  †\nY ⋅X "
+    assert upretty(Adjoint(X**2)) == \
+        "    †\n⎛ 2⎞ \n⎝X ⎠ "
+    assert upretty(Adjoint(X)**2) == \
+        "    2\n⎛ †⎞ \n⎝X ⎠ "
+    assert upretty(Adjoint(Inverse(X))) == \
+        "     †\n⎛ -1⎞ \n⎝X  ⎠ "
+    assert upretty(Inverse(Adjoint(X))) == \
+        "    -1\n⎛ †⎞  \n⎝X ⎠  "
+    assert upretty(Adjoint(Transpose(X))) == \
+        "    †\n⎛ T⎞ \n⎝X ⎠ "
+    assert upretty(Transpose(Adjoint(X))) == \
+        "    T\n⎛ †⎞ \n⎝X ⎠ "
+    m = Matrix(((1, 2), (3, 4)))
+    assert upretty(Adjoint(m)) == \
+        '      †\n'\
+        '⎡1  2⎤ \n'\
+        '⎢    ⎥ \n'\
+        '⎣3  4⎦ '
+    assert upretty(Adjoint(m+X)) == \
+        '            †\n'\
+        '⎛⎡1  2⎤    ⎞ \n'\
+        '⎜⎢    ⎥ + X⎟ \n'\
+        '⎝⎣3  4⎦    ⎠ '
+    assert upretty(Adjoint(BlockMatrix(((OneMatrix(2, 2), X),
+                                        (m, ZeroMatrix(2, 2)))))) == \
+        '           †\n'\
+        '⎡  𝟙     X⎤ \n'\
+        '⎢         ⎥ \n'\
+        '⎢⎡1  2⎤   ⎥ \n'\
+        '⎢⎢    ⎥  𝟘⎥ \n'\
+        '⎣⎣3  4⎦   ⎦ '
+
+
+def test_Transpose():
+    X = MatrixSymbol('X', 2, 2)
+    Y = MatrixSymbol('Y', 2, 2)
+    assert pretty(Transpose(X)) == " T\nX "
+    assert pretty(Transpose(X + Y)) == "       T\n(X + Y) "
+    assert pretty(Transpose(X) + Transpose(Y)) == " T    T\nX  + Y "
+    assert pretty(Transpose(X*Y)) == "     T\n(X*Y) "
+    assert pretty(Transpose(Y)*Transpose(X)) == " T  T\nY *X "
+    assert pretty(Transpose(X**2)) == "    T\n/ 2\\ \n\\X / "
+    assert pretty(Transpose(X)**2) == "    2\n/ T\\ \n\\X / "
+    assert pretty(Transpose(Inverse(X))) == "     T\n/ -1\\ \n\\X  / "
+    assert pretty(Inverse(Transpose(X))) == "    -1\n/ T\\  \n\\X /  "
+    assert upretty(Transpose(X)) == " T\nX "
+    assert upretty(Transpose(X + Y)) == "       T\n(X + Y) "
+    assert upretty(Transpose(X) + Transpose(Y)) == " T    T\nX  + Y "
+    assert upretty(Transpose(X*Y)) == "     T\n(X⋅Y) "
+    assert upretty(Transpose(Y)*Transpose(X)) == " T  T\nY ⋅X "
+    assert upretty(Transpose(X**2)) == \
+        "    T\n⎛ 2⎞ \n⎝X ⎠ "
+    assert upretty(Transpose(X)**2) == \
+        "    2\n⎛ T⎞ \n⎝X ⎠ "
+    assert upretty(Transpose(Inverse(X))) == \
+        "     T\n⎛ -1⎞ \n⎝X  ⎠ "
+    assert upretty(Inverse(Transpose(X))) == \
+        "    -1\n⎛ T⎞  \n⎝X ⎠  "
+    m = Matrix(((1, 2), (3, 4)))
+    assert upretty(Transpose(m)) == \
+        '      T\n'\
+        '⎡1  2⎤ \n'\
+        '⎢    ⎥ \n'\
+        '⎣3  4⎦ '
+    assert upretty(Transpose(m+X)) == \
+        '            T\n'\
+        '⎛⎡1  2⎤    ⎞ \n'\
+        '⎜⎢    ⎥ + X⎟ \n'\
+        '⎝⎣3  4⎦    ⎠ '
+    assert upretty(Transpose(BlockMatrix(((OneMatrix(2, 2), X),
+                                          (m, ZeroMatrix(2, 2)))))) == \
+        '           T\n'\
+        '⎡  𝟙     X⎤ \n'\
+        '⎢         ⎥ \n'\
+        '⎢⎡1  2⎤   ⎥ \n'\
+        '⎢⎢    ⎥  𝟘⎥ \n'\
+        '⎣⎣3  4⎦   ⎦ '
+
+
+def test_pretty_Trace_issue_9044():
+    X = Matrix([[1, 2], [3, 4]])
+    Y = Matrix([[2, 4], [6, 8]])
+    ascii_str_1 = \
+"""\
+  /[1  2]\\
+tr|[    ]|
+  \\[3  4]/\
+"""
+    ucode_str_1 = \
+"""\
+  ⎛⎡1  2⎤⎞
+tr⎜⎢    ⎥⎟
+  ⎝⎣3  4⎦⎠\
+"""
+    ascii_str_2 = \
+"""\
+  /[1  2]\\     /[2  4]\\
+tr|[    ]| + tr|[    ]|
+  \\[3  4]/     \\[6  8]/\
+"""
+    ucode_str_2 = \
+"""\
+  ⎛⎡1  2⎤⎞     ⎛⎡2  4⎤⎞
+tr⎜⎢    ⎥⎟ + tr⎜⎢    ⎥⎟
+  ⎝⎣3  4⎦⎠     ⎝⎣6  8⎦⎠\
+"""
+    assert pretty(Trace(X)) == ascii_str_1
+    assert upretty(Trace(X)) == ucode_str_1
+
+    assert pretty(Trace(X) + Trace(Y)) == ascii_str_2
+    assert upretty(Trace(X) + Trace(Y)) == ucode_str_2
+
+
+def test_MatrixSlice():
+    n = Symbol('n', integer=True)
+    x, y, z, w, t, = symbols('x y z w t')
+    X = MatrixSymbol('X', n, n)
+    Y = MatrixSymbol('Y', 10, 10)
+    Z = MatrixSymbol('Z', 10, 10)
+
+    expr = MatrixSlice(X, (None, None, None), (None, None, None))
+    assert pretty(expr) == upretty(expr) == 'X[:, :]'
+    expr = X[x:x + 1, y:y + 1]
+    assert pretty(expr) == upretty(expr) == 'X[x:x + 1, y:y + 1]'
+    expr = X[x:x + 1:2, y:y + 1:2]
+    assert pretty(expr) == upretty(expr) == 'X[x:x + 1:2, y:y + 1:2]'
+    expr = X[:x, y:]
+    assert pretty(expr) == upretty(expr) == 'X[:x, y:]'
+    expr = X[:x, y:]
+    assert pretty(expr) == upretty(expr) == 'X[:x, y:]'
+    expr = X[x:, :y]
+    assert pretty(expr) == upretty(expr) == 'X[x:, :y]'
+    expr = X[x:y, z:w]
+    assert pretty(expr) == upretty(expr) == 'X[x:y, z:w]'
+    expr = X[x:y:t, w:t:x]
+    assert pretty(expr) == upretty(expr) == 'X[x:y:t, w:t:x]'
+    expr = X[x::y, t::w]
+    assert pretty(expr) == upretty(expr) == 'X[x::y, t::w]'
+    expr = X[:x:y, :t:w]
+    assert pretty(expr) == upretty(expr) == 'X[:x:y, :t:w]'
+    expr = X[::x, ::y]
+    assert pretty(expr) == upretty(expr) == 'X[::x, ::y]'
+    expr = MatrixSlice(X, (0, None, None), (0, None, None))
+    assert pretty(expr) == upretty(expr) == 'X[:, :]'
+    expr = MatrixSlice(X, (None, n, None), (None, n, None))
+    assert pretty(expr) == upretty(expr) == 'X[:, :]'
+    expr = MatrixSlice(X, (0, n, None), (0, n, None))
+    assert pretty(expr) == upretty(expr) == 'X[:, :]'
+    expr = MatrixSlice(X, (0, n, 2), (0, n, 2))
+    assert pretty(expr) == upretty(expr) == 'X[::2, ::2]'
+    expr = X[1:2:3, 4:5:6]
+    assert pretty(expr) == upretty(expr) == 'X[1:2:3, 4:5:6]'
+    expr = X[1:3:5, 4:6:8]
+    assert pretty(expr) == upretty(expr) == 'X[1:3:5, 4:6:8]'
+    expr = X[1:10:2]
+    assert pretty(expr) == upretty(expr) == 'X[1:10:2, :]'
+    expr = Y[:5, 1:9:2]
+    assert pretty(expr) == upretty(expr) == 'Y[:5, 1:9:2]'
+    expr = Y[:5, 1:10:2]
+    assert pretty(expr) == upretty(expr) == 'Y[:5, 1::2]'
+    expr = Y[5, :5:2]
+    assert pretty(expr) == upretty(expr) == 'Y[5:6, :5:2]'
+    expr = X[0:1, 0:1]
+    assert pretty(expr) == upretty(expr) == 'X[:1, :1]'
+    expr = X[0:1:2, 0:1:2]
+    assert pretty(expr) == upretty(expr) == 'X[:1:2, :1:2]'
+    expr = (Y + Z)[2:, 2:]
+    assert pretty(expr) == upretty(expr) == '(Y + Z)[2:, 2:]'
+
+
+def test_MatrixExpressions():
+    n = Symbol('n', integer=True)
+    X = MatrixSymbol('X', n, n)
+
+    assert pretty(X) == upretty(X) == "X"
+
+    # Apply function elementwise (`ElementwiseApplyFunc`):
+
+    expr = (X.T*X).applyfunc(sin)
+
+    ascii_str = """\
+              / T  \\\n\
+(d -> sin(d)).\\X *X/\
+"""
+    ucode_str = """\
+             ⎛ T  ⎞\n\
+(d ↦ sin(d))˳⎝X ⋅X⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    lamda = Lambda(x, 1/x)
+    expr = (n*X).applyfunc(lamda)
+    ascii_str = """\
+/     1\\      \n\
+|x -> -|.(n*X)\n\
+\\     x/      \
+"""
+    ucode_str = """\
+⎛    1⎞      \n\
+⎜x ↦ ─⎟˳(n⋅X)\n\
+⎝    x⎠      \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_pretty_dotproduct():
+    from sympy.matrices.expressions.dotproduct import DotProduct
+    n = symbols("n", integer=True)
+    A = MatrixSymbol('A', n, 1)
+    B = MatrixSymbol('B', n, 1)
+    C = Matrix(1, 3, [1, 2, 3])
+    D = Matrix(1, 3, [1, 3, 4])
+
+    assert pretty(DotProduct(A, B)) == "A*B"
+    assert pretty(DotProduct(C, D)) == "[1  2  3]*[1  3  4]"
+    assert upretty(DotProduct(A, B)) == "A⋅B"
+    assert upretty(DotProduct(C, D)) == "[1  2  3]⋅[1  3  4]"
+
+
+def test_pretty_Determinant():
+    from sympy.matrices import Determinant, Inverse, BlockMatrix, OneMatrix, ZeroMatrix
+    m = Matrix(((1, 2), (3, 4)))
+    assert upretty(Determinant(m)) == '│1  2│\n│    │\n│3  4│'
+    assert upretty(Determinant(Inverse(m))) == \
+        '│      -1│\n'\
+        '│⎡1  2⎤  │\n'\
+        '│⎢    ⎥  │\n'\
+        '│⎣3  4⎦  │'
+    X = MatrixSymbol('X', 2, 2)
+    assert upretty(Determinant(X)) == '│X│'
+    assert upretty(Determinant(X + m)) == \
+        '│⎡1  2⎤    │\n'\
+        '│⎢    ⎥ + X│\n'\
+        '│⎣3  4⎦    │'
+    assert upretty(Determinant(BlockMatrix(((OneMatrix(2, 2), X),
+                                            (m, ZeroMatrix(2, 2)))))) == \
+        '│  𝟙     X│\n'\
+        '│         │\n'\
+        '│⎡1  2⎤   │\n'\
+        '│⎢    ⎥  𝟘│\n'\
+        '│⎣3  4⎦   │'
+
+
+def test_pretty_piecewise():
+    expr = Piecewise((x, x < 1), (x**2, True))
+    ascii_str = \
+"""\
+/x   for x < 1\n\
+|             \n\
+< 2           \n\
+|x   otherwise\n\
+\\             \
+"""
+    ucode_str = \
+"""\
+⎧x   for x < 1\n\
+⎪             \n\
+⎨ 2           \n\
+⎪x   otherwise\n\
+⎩             \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = -Piecewise((x, x < 1), (x**2, True))
+    ascii_str = \
+"""\
+ //x   for x < 1\\\n\
+ ||             |\n\
+-|< 2           |\n\
+ ||x   otherwise|\n\
+ \\\\             /\
+"""
+    ucode_str = \
+"""\
+ ⎛⎧x   for x < 1⎞\n\
+ ⎜⎪             ⎟\n\
+-⎜⎨ 2           ⎟\n\
+ ⎜⎪x   otherwise⎟\n\
+ ⎝⎩             ⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = x + Piecewise((x, x > 0), (y, True)) + Piecewise((x/y, x < 2),
+    (y**2, x > 2), (1, True)) + 1
+    ascii_str = \
+"""\
+                      //x            \\    \n\
+                      ||-   for x < 2|    \n\
+                      ||y            |    \n\
+    //x  for x > 0\\   ||             |    \n\
+x + |<            | + |< 2           | + 1\n\
+    \\\\y  otherwise/   ||y   for x > 2|    \n\
+                      ||             |    \n\
+                      ||1   otherwise|    \n\
+                      \\\\             /    \
+"""
+    ucode_str = \
+"""\
+                      ⎛⎧x            ⎞    \n\
+                      ⎜⎪─   for x < 2⎟    \n\
+                      ⎜⎪y            ⎟    \n\
+    ⎛⎧x  for x > 0⎞   ⎜⎪             ⎟    \n\
+x + ⎜⎨            ⎟ + ⎜⎨ 2           ⎟ + 1\n\
+    ⎝⎩y  otherwise⎠   ⎜⎪y   for x > 2⎟    \n\
+                      ⎜⎪             ⎟    \n\
+                      ⎜⎪1   otherwise⎟    \n\
+                      ⎝⎩             ⎠    \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = x - Piecewise((x, x > 0), (y, True)) + Piecewise((x/y, x < 2),
+    (y**2, x > 2), (1, True)) + 1
+    ascii_str = \
+"""\
+                      //x            \\    \n\
+                      ||-   for x < 2|    \n\
+                      ||y            |    \n\
+    //x  for x > 0\\   ||             |    \n\
+x - |<            | + |< 2           | + 1\n\
+    \\\\y  otherwise/   ||y   for x > 2|    \n\
+                      ||             |    \n\
+                      ||1   otherwise|    \n\
+                      \\\\             /    \
+"""
+    ucode_str = \
+"""\
+                      ⎛⎧x            ⎞    \n\
+                      ⎜⎪─   for x < 2⎟    \n\
+                      ⎜⎪y            ⎟    \n\
+    ⎛⎧x  for x > 0⎞   ⎜⎪             ⎟    \n\
+x - ⎜⎨            ⎟ + ⎜⎨ 2           ⎟ + 1\n\
+    ⎝⎩y  otherwise⎠   ⎜⎪y   for x > 2⎟    \n\
+                      ⎜⎪             ⎟    \n\
+                      ⎜⎪1   otherwise⎟    \n\
+                      ⎝⎩             ⎠    \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = x*Piecewise((x, x > 0), (y, True))
+    ascii_str = \
+"""\
+  //x  for x > 0\\\n\
+x*|<            |\n\
+  \\\\y  otherwise/\
+"""
+    ucode_str = \
+"""\
+  ⎛⎧x  for x > 0⎞\n\
+x⋅⎜⎨            ⎟\n\
+  ⎝⎩y  otherwise⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Piecewise((x, x > 0), (y, True))*Piecewise((x/y, x < 2), (y**2, x >
+    2), (1, True))
+    ascii_str = \
+"""\
+                //x            \\\n\
+                ||-   for x < 2|\n\
+                ||y            |\n\
+//x  for x > 0\\ ||             |\n\
+|<            |*|< 2           |\n\
+\\\\y  otherwise/ ||y   for x > 2|\n\
+                ||             |\n\
+                ||1   otherwise|\n\
+                \\\\             /\
+"""
+    ucode_str = \
+"""\
+                ⎛⎧x            ⎞\n\
+                ⎜⎪─   for x < 2⎟\n\
+                ⎜⎪y            ⎟\n\
+⎛⎧x  for x > 0⎞ ⎜⎪             ⎟\n\
+⎜⎨            ⎟⋅⎜⎨ 2           ⎟\n\
+⎝⎩y  otherwise⎠ ⎜⎪y   for x > 2⎟\n\
+                ⎜⎪             ⎟\n\
+                ⎜⎪1   otherwise⎟\n\
+                ⎝⎩             ⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = -Piecewise((x, x > 0), (y, True))*Piecewise((x/y, x < 2), (y**2, x
+        > 2), (1, True))
+    ascii_str = \
+"""\
+                 //x            \\\n\
+                 ||-   for x < 2|\n\
+                 ||y            |\n\
+ //x  for x > 0\\ ||             |\n\
+-|<            |*|< 2           |\n\
+ \\\\y  otherwise/ ||y   for x > 2|\n\
+                 ||             |\n\
+                 ||1   otherwise|\n\
+                 \\\\             /\
+"""
+    ucode_str = \
+"""\
+                 ⎛⎧x            ⎞\n\
+                 ⎜⎪─   for x < 2⎟\n\
+                 ⎜⎪y            ⎟\n\
+ ⎛⎧x  for x > 0⎞ ⎜⎪             ⎟\n\
+-⎜⎨            ⎟⋅⎜⎨ 2           ⎟\n\
+ ⎝⎩y  otherwise⎠ ⎜⎪y   for x > 2⎟\n\
+                 ⎜⎪             ⎟\n\
+                 ⎜⎪1   otherwise⎟\n\
+                 ⎝⎩             ⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Piecewise((0, Abs(1/y) < 1), (1, Abs(y) < 1), (y*meijerg(((2, 1),
+        ()), ((), (1, 0)), 1/y), True))
+    ascii_str = \
+"""\
+/                                 1     \n\
+|            0               for --- < 1\n\
+|                                |y|    \n\
+|                                       \n\
+<            1               for |y| < 1\n\
+|                                       \n\
+|   __0, 2 /1, 2       | 1\\             \n\
+|y*/__     |           | -|   otherwise \n\
+\\  \\_|2, 2 \\      0, 1 | y/             \
+"""
+    ucode_str = \
+"""\
+⎧                                 1     \n\
+⎪            0               for ─── < 1\n\
+⎪                                │y│    \n\
+⎪                                       \n\
+⎨            1               for │y│ < 1\n\
+⎪                                       \n\
+⎪  ╭─╮0, 2 ⎛1, 2       │ 1⎞             \n\
+⎪y⋅│╶┐     ⎜           │ ─⎟   otherwise \n\
+⎩  ╰─╯2, 2 ⎝      0, 1 │ y⎠             \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    # XXX: We have to use evaluate=False here because Piecewise._eval_power
+    # denests the power.
+    expr = Pow(Piecewise((x, x > 0), (y, True)), 2, evaluate=False)
+    ascii_str = \
+"""\
+               2\n\
+//x  for x > 0\\ \n\
+|<            | \n\
+\\\\y  otherwise/ \
+"""
+    ucode_str = \
+"""\
+               2\n\
+⎛⎧x  for x > 0⎞ \n\
+⎜⎨            ⎟ \n\
+⎝⎩y  otherwise⎠ \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_pretty_ITE():
+    expr = ITE(x, y, z)
+    assert pretty(expr) == (
+        '/y    for x  \n'
+        '<            \n'
+        '\\z  otherwise'
+        )
+    assert upretty(expr) == """\
+⎧y    for x  \n\
+⎨            \n\
+⎩z  otherwise\
+"""
+
+
+def test_pretty_seq():
+    expr = ()
+    ascii_str = \
+"""\
+()\
+"""
+    ucode_str = \
+"""\
+()\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = []
+    ascii_str = \
+"""\
+[]\
+"""
+    ucode_str = \
+"""\
+[]\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = {}
+    expr_2 = {}
+    ascii_str = \
+"""\
+{}\
+"""
+    ucode_str = \
+"""\
+{}\
+"""
+    assert pretty(expr) == ascii_str
+    assert pretty(expr_2) == ascii_str
+    assert upretty(expr) == ucode_str
+    assert upretty(expr_2) == ucode_str
+
+    expr = (1/x,)
+    ascii_str = \
+"""\
+ 1  \n\
+(-,)\n\
+ x  \
+"""
+    ucode_str = \
+"""\
+⎛1 ⎞\n\
+⎜─,⎟\n\
+⎝x ⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = [x**2, 1/x, x, y, sin(th)**2/cos(ph)**2]
+    ascii_str = \
+"""\
+                 2        \n\
+  2  1        sin (theta) \n\
+[x , -, x, y, -----------]\n\
+     x            2       \n\
+               cos (phi)  \
+"""
+    ucode_str = \
+"""\
+⎡                2   ⎤\n\
+⎢ 2  1        sin (θ)⎥\n\
+⎢x , ─, x, y, ───────⎥\n\
+⎢    x           2   ⎥\n\
+⎣             cos (φ)⎦\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = (x**2, 1/x, x, y, sin(th)**2/cos(ph)**2)
+    ascii_str = \
+"""\
+                 2        \n\
+  2  1        sin (theta) \n\
+(x , -, x, y, -----------)\n\
+     x            2       \n\
+               cos (phi)  \
+"""
+    ucode_str = \
+"""\
+⎛                2   ⎞\n\
+⎜ 2  1        sin (θ)⎟\n\
+⎜x , ─, x, y, ───────⎟\n\
+⎜    x           2   ⎟\n\
+⎝             cos (φ)⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Tuple(x**2, 1/x, x, y, sin(th)**2/cos(ph)**2)
+    ascii_str = \
+"""\
+                 2        \n\
+  2  1        sin (theta) \n\
+(x , -, x, y, -----------)\n\
+     x            2       \n\
+               cos (phi)  \
+"""
+    ucode_str = \
+"""\
+⎛                2   ⎞\n\
+⎜ 2  1        sin (θ)⎟\n\
+⎜x , ─, x, y, ───────⎟\n\
+⎜    x           2   ⎟\n\
+⎝             cos (φ)⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = {x: sin(x)}
+    expr_2 = Dict({x: sin(x)})
+    ascii_str = \
+"""\
+{x: sin(x)}\
+"""
+    ucode_str = \
+"""\
+{x: sin(x)}\
+"""
+    assert pretty(expr) == ascii_str
+    assert pretty(expr_2) == ascii_str
+    assert upretty(expr) == ucode_str
+    assert upretty(expr_2) == ucode_str
+
+    expr = {1/x: 1/y, x: sin(x)**2}
+    expr_2 = Dict({1/x: 1/y, x: sin(x)**2})
+    ascii_str = \
+"""\
+ 1  1        2    \n\
+{-: -, x: sin (x)}\n\
+ x  y             \
+"""
+    ucode_str = \
+"""\
+⎧1  1        2   ⎫\n\
+⎨─: ─, x: sin (x)⎬\n\
+⎩x  y            ⎭\
+"""
+    assert pretty(expr) == ascii_str
+    assert pretty(expr_2) == ascii_str
+    assert upretty(expr) == ucode_str
+    assert upretty(expr_2) == ucode_str
+
+    # There used to be a bug with pretty-printing sequences of even height.
+    expr = [x**2]
+    ascii_str = \
+"""\
+  2 \n\
+[x ]\
+"""
+    ucode_str = \
+"""\
+⎡ 2⎤\n\
+⎣x ⎦\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = (x**2,)
+    ascii_str = \
+"""\
+  2  \n\
+(x ,)\
+"""
+    ucode_str = \
+"""\
+⎛ 2 ⎞\n\
+⎝x ,⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Tuple(x**2)
+    ascii_str = \
+"""\
+  2  \n\
+(x ,)\
+"""
+    ucode_str = \
+"""\
+⎛ 2 ⎞\n\
+⎝x ,⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = {x**2: 1}
+    expr_2 = Dict({x**2: 1})
+    ascii_str = \
+"""\
+  2    \n\
+{x : 1}\
+"""
+    ucode_str = \
+"""\
+⎧ 2   ⎫\n\
+⎨x : 1⎬\n\
+⎩     ⎭\
+"""
+    assert pretty(expr) == ascii_str
+    assert pretty(expr_2) == ascii_str
+    assert upretty(expr) == ucode_str
+    assert upretty(expr_2) == ucode_str
+
+
+def test_any_object_in_sequence():
+    # Cf. issue 5306
+    b1 = Basic()
+    b2 = Basic(Basic())
+
+    expr = [b2, b1]
+    assert pretty(expr) == "[Basic(Basic()), Basic()]"
+    assert upretty(expr) == "[Basic(Basic()), Basic()]"
+
+    expr = {b2, b1}
+    assert pretty(expr) == "{Basic(), Basic(Basic())}"
+    assert upretty(expr) == "{Basic(), Basic(Basic())}"
+
+    expr = {b2: b1, b1: b2}
+    expr2 = Dict({b2: b1, b1: b2})
+    assert pretty(expr) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}"
+    assert pretty(
+        expr2) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}"
+    assert upretty(
+        expr) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}"
+    assert upretty(
+        expr2) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}"
+
+
+def test_print_builtin_set():
+    assert pretty(set()) == 'set()'
+    assert upretty(set()) == 'set()'
+
+    assert pretty(frozenset()) == 'frozenset()'
+    assert upretty(frozenset()) == 'frozenset()'
+
+    s1 = {1/x, x}
+    s2 = frozenset(s1)
+
+    assert pretty(s1) == \
+"""\
+ 1    \n\
+{-, x}
+ x    \
+"""
+    assert upretty(s1) == \
+"""\
+⎧1   ⎫
+⎨─, x⎬
+⎩x   ⎭\
+"""
+
+    assert pretty(s2) == \
+"""\
+           1     \n\
+frozenset({-, x})
+           x     \
+"""
+    assert upretty(s2) == \
+"""\
+         ⎛⎧1   ⎫⎞
+frozenset⎜⎨─, x⎬⎟
+         ⎝⎩x   ⎭⎠\
+"""
+
+
+def test_pretty_sets():
+    s = FiniteSet
+    assert pretty(s(*[x*y, x**2])) == \
+"""\
+  2      \n\
+{x , x*y}\
+"""
+    assert pretty(s(*range(1, 6))) == "{1, 2, 3, 4, 5}"
+    assert pretty(s(*range(1, 13))) == "{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}"
+
+    assert pretty({x*y, x**2}) == \
+"""\
+  2      \n\
+{x , x*y}\
+"""
+    assert pretty(set(range(1, 6))) == "{1, 2, 3, 4, 5}"
+    assert pretty(set(range(1, 13))) == \
+        "{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}"
+
+    assert pretty(frozenset([x*y, x**2])) == \
+"""\
+            2       \n\
+frozenset({x , x*y})\
+"""
+    assert pretty(frozenset(range(1, 6))) == "frozenset({1, 2, 3, 4, 5})"
+    assert pretty(frozenset(range(1, 13))) == \
+        "frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12})"
+
+    assert pretty(Range(0, 3, 1)) == '{0, 1, 2}'
+
+    ascii_str = '{0, 1, ..., 29}'
+    ucode_str = '{0, 1, …, 29}'
+    assert pretty(Range(0, 30, 1)) == ascii_str
+    assert upretty(Range(0, 30, 1)) == ucode_str
+
+    ascii_str = '{30, 29, ..., 2}'
+    ucode_str = '{30, 29, …, 2}'
+    assert pretty(Range(30, 1, -1)) == ascii_str
+    assert upretty(Range(30, 1, -1)) == ucode_str
+
+    ascii_str = '{0, 2, ...}'
+    ucode_str = '{0, 2, …}'
+    assert pretty(Range(0, oo, 2)) == ascii_str
+    assert upretty(Range(0, oo, 2)) == ucode_str
+
+    ascii_str = '{..., 2, 0}'
+    ucode_str = '{…, 2, 0}'
+    assert pretty(Range(oo, -2, -2)) == ascii_str
+    assert upretty(Range(oo, -2, -2)) == ucode_str
+
+    ascii_str = '{-2, -3, ...}'
+    ucode_str = '{-2, -3, …}'
+    assert pretty(Range(-2, -oo, -1)) == ascii_str
+    assert upretty(Range(-2, -oo, -1)) == ucode_str
+
+
+def test_pretty_SetExpr():
+    iv = Interval(1, 3)
+    se = SetExpr(iv)
+    ascii_str = "SetExpr([1, 3])"
+    ucode_str = "SetExpr([1, 3])"
+    assert pretty(se) == ascii_str
+    assert upretty(se) == ucode_str
+
+
+def test_pretty_ImageSet():
+    imgset = ImageSet(Lambda((x, y), x + y), {1, 2, 3}, {3, 4})
+    ascii_str = '{x + y | x in {1, 2, 3}, y in {3, 4}}'
+    ucode_str = '{x + y │ x ∊ {1, 2, 3}, y ∊ {3, 4}}'
+    assert pretty(imgset) == ascii_str
+    assert upretty(imgset) == ucode_str
+
+    imgset = ImageSet(Lambda(((x, y),), x + y), ProductSet({1, 2, 3}, {3, 4}))
+    ascii_str = '{x + y | (x, y) in {1, 2, 3} x {3, 4}}'
+    ucode_str = '{x + y │ (x, y) ∊ {1, 2, 3} × {3, 4}}'
+    assert pretty(imgset) == ascii_str
+    assert upretty(imgset) == ucode_str
+
+    imgset = ImageSet(Lambda(x, x**2), S.Naturals)
+    ascii_str = '''\
+  2                 \n\
+{x  | x in Naturals}'''
+    ucode_str = '''\
+⎧ 2 │      ⎫\n\
+⎨x  │ x ∊ ℕ⎬\n\
+⎩   │      ⎭'''
+    assert pretty(imgset) == ascii_str
+    assert upretty(imgset) == ucode_str
+
+    # TODO: The "x in N" parts below should be centered independently of the
+    # 1/x**2 fraction
+    imgset = ImageSet(Lambda(x, 1/x**2), S.Naturals)
+    ascii_str = '''\
+ 1                  \n\
+{-- | x in Naturals}
+  2                 \n\
+ x                  '''
+    ucode_str = '''\
+⎧1  │      ⎫\n\
+⎪── │ x ∊ ℕ⎪\n\
+⎨ 2 │      ⎬\n\
+⎪x  │      ⎪\n\
+⎩   │      ⎭'''
+    assert pretty(imgset) == ascii_str
+    assert upretty(imgset) == ucode_str
+
+    imgset = ImageSet(Lambda((x, y), 1/(x + y)**2), S.Naturals, S.Naturals)
+    ascii_str = '''\
+    1                                    \n\
+{-------- | x in Naturals, y in Naturals}
+        2                                \n\
+ (x + y)                                 '''
+    ucode_str = '''\
+⎧   1     │             ⎫
+⎪──────── │ x ∊ ℕ, y ∊ ℕ⎪
+⎨       2 │             ⎬
+⎪(x + y)  │             ⎪
+⎩         │             ⎭'''
+    assert pretty(imgset) == ascii_str
+    assert upretty(imgset) == ucode_str
+
+    # issue 23449 centering issue
+    assert upretty([Symbol("ihat") / (Symbol("i") + 1)]) == '''\
+⎡  î  ⎤
+⎢─────⎥
+⎣i + 1⎦\
+'''
+    assert upretty(Matrix([Symbol("ihat"), Symbol("i") + 1])) == '''\
+⎡  î  ⎤
+⎢     ⎥
+⎣i + 1⎦\
+'''
+
+
+def test_pretty_ConditionSet():
+    ascii_str = '{x | x in (-oo, oo) and sin(x) = 0}'
+    ucode_str = '{x │ x ∊ ℝ ∧ (sin(x) = 0)}'
+    assert pretty(ConditionSet(x, Eq(sin(x), 0), S.Reals)) == ascii_str
+    assert upretty(ConditionSet(x, Eq(sin(x), 0), S.Reals)) == ucode_str
+
+    assert pretty(ConditionSet(x, Contains(x, S.Reals, evaluate=False), FiniteSet(1))) == '{1}'
+    assert upretty(ConditionSet(x, Contains(x, S.Reals, evaluate=False), FiniteSet(1))) == '{1}'
+
+    assert pretty(ConditionSet(x, And(x > 1, x < -1), FiniteSet(1, 2, 3))) == "EmptySet"
+    assert upretty(ConditionSet(x, And(x > 1, x < -1), FiniteSet(1, 2, 3))) == "∅"
+
+    assert pretty(ConditionSet(x, Or(x > 1, x < -1), FiniteSet(1, 2))) == '{2}'
+    assert upretty(ConditionSet(x, Or(x > 1, x < -1), FiniteSet(1, 2))) == '{2}'
+
+    condset = ConditionSet(x, 1/x**2 > 0)
+    ascii_str = '''\
+     1      \n\
+{x | -- > 0}
+      2     \n\
+     x      '''
+    ucode_str = '''\
+⎧  │ ⎛1     ⎞⎫
+⎪x │ ⎜── > 0⎟⎪
+⎨  │ ⎜ 2    ⎟⎬
+⎪  │ ⎝x     ⎠⎪
+⎩  │         ⎭'''
+    assert pretty(condset) == ascii_str
+    assert upretty(condset) == ucode_str
+
+    condset = ConditionSet(x, 1/x**2 > 0, S.Reals)
+    ascii_str = '''\
+                        1      \n\
+{x | x in (-oo, oo) and -- > 0}
+                         2     \n\
+                        x      '''
+    ucode_str = '''\
+⎧  │         ⎛1     ⎞⎫
+⎪x │ x ∊ ℝ ∧ ⎜── > 0⎟⎪
+⎨  │         ⎜ 2    ⎟⎬
+⎪  │         ⎝x     ⎠⎪
+⎩  │                 ⎭'''
+    assert pretty(condset) == ascii_str
+    assert upretty(condset) == ucode_str
+
+
+def test_pretty_ComplexRegion():
+    from sympy.sets.fancysets import ComplexRegion
+    cregion = ComplexRegion(Interval(3, 5)*Interval(4, 6))
+    ascii_str = '{x + y*I | x, y in [3, 5] x [4, 6]}'
+    ucode_str = '{x + y⋅ⅈ │ x, y ∊ [3, 5] × [4, 6]}'
+    assert pretty(cregion) == ascii_str
+    assert upretty(cregion) == ucode_str
+
+    cregion = ComplexRegion(Interval(0, 1)*Interval(0, 2*pi), polar=True)
+    ascii_str = '{r*(I*sin(theta) + cos(theta)) | r, theta in [0, 1] x [0, 2*pi)}'
+    ucode_str = '{r⋅(ⅈ⋅sin(θ) + cos(θ)) │ r, θ ∊ [0, 1] × [0, 2⋅π)}'
+    assert pretty(cregion) == ascii_str
+    assert upretty(cregion) == ucode_str
+
+    cregion = ComplexRegion(Interval(3, 1/a**2)*Interval(4, 6))
+    ascii_str = '''\
+                       1            \n\
+{x + y*I | x, y in [3, --] x [4, 6]}
+                        2           \n\
+                       a            '''
+    ucode_str = '''\
+⎧        │        ⎡   1 ⎤         ⎫
+⎪x + y⋅ⅈ │ x, y ∊ ⎢3, ──⎥ × [4, 6]⎪
+⎨        │        ⎢    2⎥         ⎬
+⎪        │        ⎣   a ⎦         ⎪
+⎩        │                        ⎭'''
+    assert pretty(cregion) == ascii_str
+    assert upretty(cregion) == ucode_str
+
+    cregion = ComplexRegion(Interval(0, 1/a**2)*Interval(0, 2*pi), polar=True)
+    ascii_str = '''\
+                                                 1               \n\
+{r*(I*sin(theta) + cos(theta)) | r, theta in [0, --] x [0, 2*pi)}
+                                                  2              \n\
+                                                 a               '''
+    ucode_str = '''\
+⎧                      │        ⎡   1 ⎤           ⎫
+⎪r⋅(ⅈ⋅sin(θ) + cos(θ)) │ r, θ ∊ ⎢0, ──⎥ × [0, 2⋅π)⎪
+⎨                      │        ⎢    2⎥           ⎬
+⎪                      │        ⎣   a ⎦           ⎪
+⎩                      │                          ⎭'''
+    assert pretty(cregion) == ascii_str
+    assert upretty(cregion) == ucode_str
+
+
+def test_pretty_Union_issue_10414():
+    a, b = Interval(2, 3), Interval(4, 7)
+    ucode_str = '[2, 3] ∪ [4, 7]'
+    ascii_str = '[2, 3] U [4, 7]'
+    assert upretty(Union(a, b)) == ucode_str
+    assert pretty(Union(a, b)) == ascii_str
+
+
+def test_pretty_Intersection_issue_10414():
+    x, y, z, w = symbols('x, y, z, w')
+    a, b = Interval(x, y), Interval(z, w)
+    ucode_str = '[x, y] ∩ [z, w]'
+    ascii_str = '[x, y] n [z, w]'
+    assert upretty(Intersection(a, b)) == ucode_str
+    assert pretty(Intersection(a, b)) == ascii_str
+
+
+def test_ProductSet_exponent():
+    ucode_str = '      1\n[0, 1] '
+    assert upretty(Interval(0, 1)**1) == ucode_str
+    ucode_str = '      2\n[0, 1] '
+    assert upretty(Interval(0, 1)**2) == ucode_str
+
+
+def test_ProductSet_parenthesis():
+    ucode_str = '([4, 7] × {1, 2}) ∪ ([2, 3] × [4, 7])'
+
+    a, b = Interval(2, 3), Interval(4, 7)
+    assert upretty(Union(a*b, b*FiniteSet(1, 2))) == ucode_str
+
+
+def test_ProductSet_prod_char_issue_10413():
+    ascii_str = '[2, 3] x [4, 7]'
+    ucode_str = '[2, 3] × [4, 7]'
+
+    a, b = Interval(2, 3), Interval(4, 7)
+    assert pretty(a*b) == ascii_str
+    assert upretty(a*b) == ucode_str
+
+
+def test_pretty_sequences():
+    s1 = SeqFormula(a**2, (0, oo))
+    s2 = SeqPer((1, 2))
+
+    ascii_str = '[0, 1, 4, 9, ...]'
+    ucode_str = '[0, 1, 4, 9, …]'
+
+    assert pretty(s1) == ascii_str
+    assert upretty(s1) == ucode_str
+
+    ascii_str = '[1, 2, 1, 2, ...]'
+    ucode_str = '[1, 2, 1, 2, …]'
+    assert pretty(s2) == ascii_str
+    assert upretty(s2) == ucode_str
+
+    s3 = SeqFormula(a**2, (0, 2))
+    s4 = SeqPer((1, 2), (0, 2))
+
+    ascii_str = '[0, 1, 4]'
+    ucode_str = '[0, 1, 4]'
+
+    assert pretty(s3) == ascii_str
+    assert upretty(s3) == ucode_str
+
+    ascii_str = '[1, 2, 1]'
+    ucode_str = '[1, 2, 1]'
+    assert pretty(s4) == ascii_str
+    assert upretty(s4) == ucode_str
+
+    s5 = SeqFormula(a**2, (-oo, 0))
+    s6 = SeqPer((1, 2), (-oo, 0))
+
+    ascii_str = '[..., 9, 4, 1, 0]'
+    ucode_str = '[…, 9, 4, 1, 0]'
+
+    assert pretty(s5) == ascii_str
+    assert upretty(s5) == ucode_str
+
+    ascii_str = '[..., 2, 1, 2, 1]'
+    ucode_str = '[…, 2, 1, 2, 1]'
+    assert pretty(s6) == ascii_str
+    assert upretty(s6) == ucode_str
+
+    ascii_str = '[1, 3, 5, 11, ...]'
+    ucode_str = '[1, 3, 5, 11, …]'
+
+    assert pretty(SeqAdd(s1, s2)) == ascii_str
+    assert upretty(SeqAdd(s1, s2)) == ucode_str
+
+    ascii_str = '[1, 3, 5]'
+    ucode_str = '[1, 3, 5]'
+
+    assert pretty(SeqAdd(s3, s4)) == ascii_str
+    assert upretty(SeqAdd(s3, s4)) == ucode_str
+
+    ascii_str = '[..., 11, 5, 3, 1]'
+    ucode_str = '[…, 11, 5, 3, 1]'
+
+    assert pretty(SeqAdd(s5, s6)) == ascii_str
+    assert upretty(SeqAdd(s5, s6)) == ucode_str
+
+    ascii_str = '[0, 2, 4, 18, ...]'
+    ucode_str = '[0, 2, 4, 18, …]'
+
+    assert pretty(SeqMul(s1, s2)) == ascii_str
+    assert upretty(SeqMul(s1, s2)) == ucode_str
+
+    ascii_str = '[0, 2, 4]'
+    ucode_str = '[0, 2, 4]'
+
+    assert pretty(SeqMul(s3, s4)) == ascii_str
+    assert upretty(SeqMul(s3, s4)) == ucode_str
+
+    ascii_str = '[..., 18, 4, 2, 0]'
+    ucode_str = '[…, 18, 4, 2, 0]'
+
+    assert pretty(SeqMul(s5, s6)) == ascii_str
+    assert upretty(SeqMul(s5, s6)) == ucode_str
+
+    # Sequences with symbolic limits, issue 12629
+    s7 = SeqFormula(a**2, (a, 0, x))
+    raises(NotImplementedError, lambda: pretty(s7))
+    raises(NotImplementedError, lambda: upretty(s7))
+
+    b = Symbol('b')
+    s8 = SeqFormula(b*a**2, (a, 0, 2))
+    ascii_str = '[0, b, 4*b]'
+    ucode_str = '[0, b, 4⋅b]'
+    assert pretty(s8) == ascii_str
+    assert upretty(s8) == ucode_str
+
+
+def test_pretty_FourierSeries():
+    f = fourier_series(x, (x, -pi, pi))
+
+    ascii_str = \
+"""\
+                      2*sin(3*x)      \n\
+2*sin(x) - sin(2*x) + ---------- + ...\n\
+                          3           \
+"""
+
+    ucode_str = \
+"""\
+                      2⋅sin(3⋅x)    \n\
+2⋅sin(x) - sin(2⋅x) + ────────── + …\n\
+                          3         \
+"""
+
+    assert pretty(f) == ascii_str
+    assert upretty(f) == ucode_str
+
+
+def test_pretty_FormalPowerSeries():
+    f = fps(log(1 + x))
+
+
+    ascii_str = \
+"""\
+ oo              \n\
+____             \n\
+\\   `            \n\
+ \\         -k  k \n\
+  \\   -(-1)  *x  \n\
+  /   -----------\n\
+ /         k     \n\
+/___,            \n\
+k = 1            \
+"""
+
+    ucode_str = \
+"""\
+ ∞               \n\
+____             \n\
+╲                \n\
+ ╲         -k  k \n\
+  ╲   -(-1)  ⋅x  \n\
+  ╱   ───────────\n\
+ ╱         k     \n\
+╱                \n\
+‾‾‾‾             \n\
+k = 1            \
+"""
+
+    assert pretty(f) == ascii_str
+    assert upretty(f) == ucode_str
+
+
+def test_pretty_limits():
+    expr = Limit(x, x, oo)
+    ascii_str = \
+"""\
+ lim x\n\
+x->oo \
+"""
+    ucode_str = \
+"""\
+lim x\n\
+x─→∞ \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Limit(x**2, x, 0)
+    ascii_str = \
+"""\
+      2\n\
+ lim x \n\
+x->0+  \
+"""
+    ucode_str = \
+"""\
+      2\n\
+ lim x \n\
+x─→0⁺  \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Limit(1/x, x, 0)
+    ascii_str = \
+"""\
+     1\n\
+ lim -\n\
+x->0+x\
+"""
+    ucode_str = \
+"""\
+     1\n\
+ lim ─\n\
+x─→0⁺x\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Limit(sin(x)/x, x, 0)
+    ascii_str = \
+"""\
+     /sin(x)\\\n\
+ lim |------|\n\
+x->0+\\  x   /\
+"""
+    ucode_str = \
+"""\
+     ⎛sin(x)⎞\n\
+ lim ⎜──────⎟\n\
+x─→0⁺⎝  x   ⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Limit(sin(x)/x, x, 0, "-")
+    ascii_str = \
+"""\
+     /sin(x)\\\n\
+ lim |------|\n\
+x->0-\\  x   /\
+"""
+    ucode_str = \
+"""\
+     ⎛sin(x)⎞\n\
+ lim ⎜──────⎟\n\
+x─→0⁻⎝  x   ⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Limit(x + sin(x), x, 0)
+    ascii_str = \
+"""\
+ lim (x + sin(x))\n\
+x->0+            \
+"""
+    ucode_str = \
+"""\
+ lim (x + sin(x))\n\
+x─→0⁺            \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Limit(x, x, 0)**2
+    ascii_str = \
+"""\
+        2\n\
+/ lim x\\ \n\
+\\x->0+ / \
+"""
+    ucode_str = \
+"""\
+        2\n\
+⎛ lim x⎞ \n\
+⎝x─→0⁺ ⎠ \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Limit(x*Limit(y/2,y,0), x, 0)
+    ascii_str = \
+"""\
+     /       /y\\\\\n\
+ lim |x* lim |-||\n\
+x->0+\\  y->0+\\2//\
+"""
+    ucode_str = \
+"""\
+     ⎛       ⎛y⎞⎞\n\
+ lim ⎜x⋅ lim ⎜─⎟⎟\n\
+x─→0⁺⎝  y─→0⁺⎝2⎠⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = 2*Limit(x*Limit(y/2,y,0), x, 0)
+    ascii_str = \
+"""\
+       /       /y\\\\\n\
+2* lim |x* lim |-||\n\
+  x->0+\\  y->0+\\2//\
+"""
+    ucode_str = \
+"""\
+       ⎛       ⎛y⎞⎞\n\
+2⋅ lim ⎜x⋅ lim ⎜─⎟⎟\n\
+  x─→0⁺⎝  y─→0⁺⎝2⎠⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Limit(sin(x), x, 0, dir='+-')
+    ascii_str = \
+"""\
+lim sin(x)\n\
+x->0      \
+"""
+    ucode_str = \
+"""\
+lim sin(x)\n\
+x─→0      \
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_pretty_ComplexRootOf():
+    expr = rootof(x**5 + 11*x - 2, 0)
+    ascii_str = \
+"""\
+       / 5              \\\n\
+CRootOf\\x  + 11*x - 2, 0/\
+"""
+    ucode_str = \
+"""\
+       ⎛ 5              ⎞\n\
+CRootOf⎝x  + 11⋅x - 2, 0⎠\
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_pretty_RootSum():
+    expr = RootSum(x**5 + 11*x - 2, auto=False)
+    ascii_str = \
+"""\
+       / 5           \\\n\
+RootSum\\x  + 11*x - 2/\
+"""
+    ucode_str = \
+"""\
+       ⎛ 5           ⎞\n\
+RootSum⎝x  + 11⋅x - 2⎠\
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = RootSum(x**5 + 11*x - 2, Lambda(z, exp(z)))
+    ascii_str = \
+"""\
+       / 5                   z\\\n\
+RootSum\\x  + 11*x - 2, z -> e /\
+"""
+    ucode_str = \
+"""\
+       ⎛ 5                  z⎞\n\
+RootSum⎝x  + 11⋅x - 2, z ↦ ℯ ⎠\
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_GroebnerBasis():
+    expr = groebner([], x, y)
+
+    ascii_str = \
+"""\
+GroebnerBasis([], x, y, domain=ZZ, order=lex)\
+"""
+    ucode_str = \
+"""\
+GroebnerBasis([], x, y, domain=ℤ, order=lex)\
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1]
+    expr = groebner(F, x, y, order='grlex')
+
+    ascii_str = \
+"""\
+             /[ 2                 2              ]                              \\\n\
+GroebnerBasis\\[x  - x - 3*y + 1, y  - 2*x + y - 1], x, y, domain=ZZ, order=grlex/\
+"""
+    ucode_str = \
+"""\
+             ⎛⎡ 2                 2              ⎤                             ⎞\n\
+GroebnerBasis⎝⎣x  - x - 3⋅y + 1, y  - 2⋅x + y - 1⎦, x, y, domain=ℤ, order=grlex⎠\
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = expr.fglm('lex')
+
+    ascii_str = \
+"""\
+             /[       2           4      3      2           ]                            \\\n\
+GroebnerBasis\\[2*x - y  - y + 1, y  + 2*y  - 3*y  - 16*y + 7], x, y, domain=ZZ, order=lex/\
+"""
+    ucode_str = \
+"""\
+             ⎛⎡       2           4      3      2           ⎤                           ⎞\n\
+GroebnerBasis⎝⎣2⋅x - y  - y + 1, y  + 2⋅y  - 3⋅y  - 16⋅y + 7⎦, x, y, domain=ℤ, order=lex⎠\
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_pretty_UniversalSet():
+    assert pretty(S.UniversalSet) == "UniversalSet"
+    assert upretty(S.UniversalSet) == '𝕌'
+
+
+def test_pretty_Boolean():
+    expr = Not(x, evaluate=False)
+
+    assert pretty(expr) == "Not(x)"
+    assert upretty(expr) == "¬x"
+
+    expr = And(x, y)
+
+    assert pretty(expr) == "And(x, y)"
+    assert upretty(expr) == "x ∧ y"
+
+    expr = Or(x, y)
+
+    assert pretty(expr) == "Or(x, y)"
+    assert upretty(expr) == "x ∨ y"
+
+    syms = symbols('a:f')
+    expr = And(*syms)
+
+    assert pretty(expr) == "And(a, b, c, d, e, f)"
+    assert upretty(expr) == "a ∧ b ∧ c ∧ d ∧ e ∧ f"
+
+    expr = Or(*syms)
+
+    assert pretty(expr) == "Or(a, b, c, d, e, f)"
+    assert upretty(expr) == "a ∨ b ∨ c ∨ d ∨ e ∨ f"
+
+    expr = Xor(x, y, evaluate=False)
+
+    assert pretty(expr) == "Xor(x, y)"
+    assert upretty(expr) == "x ⊻ y"
+
+    expr = Nand(x, y, evaluate=False)
+
+    assert pretty(expr) == "Nand(x, y)"
+    assert upretty(expr) == "x ⊼ y"
+
+    expr = Nor(x, y, evaluate=False)
+
+    assert pretty(expr) == "Nor(x, y)"
+    assert upretty(expr) == "x ⊽ y"
+
+    expr = Implies(x, y, evaluate=False)
+
+    assert pretty(expr) == "Implies(x, y)"
+    assert upretty(expr) == "x → y"
+
+    # don't sort args
+    expr = Implies(y, x, evaluate=False)
+
+    assert pretty(expr) == "Implies(y, x)"
+    assert upretty(expr) == "y → x"
+
+    expr = Equivalent(x, y, evaluate=False)
+
+    assert pretty(expr) == "Equivalent(x, y)"
+    assert upretty(expr) == "x ⇔ y"
+
+    expr = Equivalent(y, x, evaluate=False)
+
+    assert pretty(expr) == "Equivalent(x, y)"
+    assert upretty(expr) == "x ⇔ y"
+
+
+def test_pretty_Domain():
+    expr = FF(23)
+
+    assert pretty(expr) == "GF(23)"
+    assert upretty(expr) == "ℤ₂₃"
+
+    expr = ZZ
+
+    assert pretty(expr) == "ZZ"
+    assert upretty(expr) == "ℤ"
+
+    expr = QQ
+
+    assert pretty(expr) == "QQ"
+    assert upretty(expr) == "ℚ"
+
+    expr = RR
+
+    assert pretty(expr) == "RR"
+    assert upretty(expr) == "ℝ"
+
+    expr = QQ[x]
+
+    assert pretty(expr) == "QQ[x]"
+    assert upretty(expr) == "ℚ[x]"
+
+    expr = QQ[x, y]
+
+    assert pretty(expr) == "QQ[x, y]"
+    assert upretty(expr) == "ℚ[x, y]"
+
+    expr = ZZ.frac_field(x)
+
+    assert pretty(expr) == "ZZ(x)"
+    assert upretty(expr) == "ℤ(x)"
+
+    expr = ZZ.frac_field(x, y)
+
+    assert pretty(expr) == "ZZ(x, y)"
+    assert upretty(expr) == "ℤ(x, y)"
+
+    expr = QQ.poly_ring(x, y, order=grlex)
+
+    assert pretty(expr) == "QQ[x, y, order=grlex]"
+    assert upretty(expr) == "ℚ[x, y, order=grlex]"
+
+    expr = QQ.poly_ring(x, y, order=ilex)
+
+    assert pretty(expr) == "QQ[x, y, order=ilex]"
+    assert upretty(expr) == "ℚ[x, y, order=ilex]"
+
+
+def test_pretty_prec():
+    assert xpretty(S("0.3"), full_prec=True, wrap_line=False) == "0.300000000000000"
+    assert xpretty(S("0.3"), full_prec="auto", wrap_line=False) == "0.300000000000000"
+    assert xpretty(S("0.3"), full_prec=False, wrap_line=False) == "0.3"
+    assert xpretty(S("0.3")*x, full_prec=True, use_unicode=False, wrap_line=False) in [
+        "0.300000000000000*x",
+        "x*0.300000000000000"
+    ]
+    assert xpretty(S("0.3")*x, full_prec="auto", use_unicode=False, wrap_line=False) in [
+        "0.3*x",
+        "x*0.3"
+    ]
+    assert xpretty(S("0.3")*x, full_prec=False, use_unicode=False, wrap_line=False) in [
+        "0.3*x",
+        "x*0.3"
+    ]
+
+
+def test_pprint():
+    import sys
+    from io import StringIO
+    fd = StringIO()
+    sso = sys.stdout
+    sys.stdout = fd
+    try:
+        pprint(pi, use_unicode=False, wrap_line=False)
+    finally:
+        sys.stdout = sso
+    assert fd.getvalue() == 'pi\n'
+
+
+def test_pretty_class():
+    """Test that the printer dispatcher correctly handles classes."""
+    class C:
+        pass   # C has no .__class__ and this was causing problems
+
+    class D:
+        pass
+
+    assert pretty( C ) == str( C )
+    assert pretty( D ) == str( D )
+
+
+def test_pretty_no_wrap_line():
+    huge_expr = 0
+    for i in range(20):
+        huge_expr += i*sin(i + x)
+    assert xpretty(huge_expr            ).find('\n') != -1
+    assert xpretty(huge_expr, wrap_line=False).find('\n') == -1
+
+
+def test_settings():
+    raises(TypeError, lambda: pretty(S(4), method="garbage"))
+
+
+def test_pretty_sum():
+    from sympy.abc import x, a, b, k, m, n
+
+    expr = Sum(k**k, (k, 0, n))
+    ascii_str = \
+"""\
+ n      \n\
+___     \n\
+\\  `    \n\
+ \\     k\n\
+ /    k \n\
+/__,    \n\
+k = 0   \
+"""
+    ucode_str = \
+"""\
+  n     \n\
+ ___    \n\
+ ╲      \n\
+  ╲    k\n\
+  ╱   k \n\
+ ╱      \n\
+ ‾‾‾    \n\
+k = 0   \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Sum(k**k, (k, oo, n))
+    ascii_str = \
+"""\
+  n      \n\
+ ___     \n\
+ \\  `    \n\
+  \\     k\n\
+  /    k \n\
+ /__,    \n\
+k = oo   \
+"""
+    ucode_str = \
+"""\
+  n     \n\
+ ___    \n\
+ ╲      \n\
+  ╲    k\n\
+  ╱   k \n\
+ ╱      \n\
+ ‾‾‾    \n\
+k = ∞   \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Sum(k**(Integral(x**n, (x, -oo, oo))), (k, 0, n**n))
+    ascii_str = \
+"""\
+   n              \n\
+  n               \n\
+______            \n\
+\\     `           \n\
+ \\        oo      \n\
+  \\        /      \n\
+   \\      |       \n\
+    \\     |   n   \n\
+     )    |  x  dx\n\
+    /     |       \n\
+   /     /        \n\
+  /      -oo      \n\
+ /      k         \n\
+/_____,           \n\
+ k = 0            \
+"""
+    ucode_str = \
+"""\
+   n            \n\
+  n             \n\
+______          \n\
+╲               \n\
+ ╲              \n\
+  ╲     ∞       \n\
+   ╲    ⌠       \n\
+    ╲   ⎮   n   \n\
+    ╱   ⎮  x  dx\n\
+   ╱    ⌡       \n\
+  ╱     -∞      \n\
+ ╱     k        \n\
+╱               \n\
+‾‾‾‾‾‾          \n\
+k = 0           \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Sum(k**(
+        Integral(x**n, (x, -oo, oo))), (k, 0, Integral(x**x, (x, -oo, oo))))
+    ascii_str = \
+"""\
+ oo                 \n\
+  /                 \n\
+ |                  \n\
+ |   x              \n\
+ |  x  dx           \n\
+ |                  \n\
+/                   \n\
+-oo                 \n\
+ ______             \n\
+ \\     `            \n\
+  \\         oo      \n\
+   \\         /      \n\
+    \\       |       \n\
+     \\      |   n   \n\
+      )     |  x  dx\n\
+     /      |       \n\
+    /      /        \n\
+   /       -oo      \n\
+  /       k         \n\
+ /_____,            \n\
+  k = 0             \
+"""
+    ucode_str = \
+"""\
+∞                 \n\
+⌠                 \n\
+⎮   x             \n\
+⎮  x  dx          \n\
+⌡                 \n\
+-∞                \n\
+ ______           \n\
+ ╲                \n\
+  ╲               \n\
+   ╲      ∞       \n\
+    ╲     ⌠       \n\
+     ╲    ⎮   n   \n\
+     ╱    ⎮  x  dx\n\
+    ╱     ⌡       \n\
+   ╱      -∞      \n\
+  ╱      k        \n\
+ ╱                \n\
+ ‾‾‾‾‾‾           \n\
+ k = 0            \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Sum(k**(Integral(x**n, (x, -oo, oo))), (
+        k, x + n + x**2 + n**2 + (x/n) + (1/x), Integral(x**x, (x, -oo, oo))))
+    ascii_str = \
+"""\
+          oo                          \n\
+           /                          \n\
+          |                           \n\
+          |   x                       \n\
+          |  x  dx                    \n\
+          |                           \n\
+         /                            \n\
+         -oo                          \n\
+          ______                      \n\
+          \\     `                     \n\
+           \\                  oo      \n\
+            \\                  /      \n\
+             \\                |       \n\
+              \\               |   n   \n\
+               )              |  x  dx\n\
+              /               |       \n\
+             /               /        \n\
+            /                -oo      \n\
+           /                k         \n\
+          /_____,                     \n\
+     2        2       1   x           \n\
+k = n  + n + x  + x + - + -           \n\
+                      x   n           \
+"""
+    ucode_str = \
+"""\
+         ∞                           \n\
+         ⌠                           \n\
+         ⎮   x                       \n\
+         ⎮  x  dx                    \n\
+         ⌡                           \n\
+         -∞                          \n\
+          ______                     \n\
+          ╲                          \n\
+           ╲                         \n\
+            ╲                ∞       \n\
+             ╲               ⌠       \n\
+              ╲              ⎮   n   \n\
+              ╱              ⎮  x  dx\n\
+             ╱               ⌡       \n\
+            ╱                -∞      \n\
+           ╱                k        \n\
+          ╱                          \n\
+          ‾‾‾‾‾‾                     \n\
+     2        2       1   x          \n\
+k = n  + n + x  + x + ─ + ─          \n\
+                      x   n          \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Sum(k**(
+        Integral(x**n, (x, -oo, oo))), (k, 0, x + n + x**2 + n**2 + (x/n) + (1/x)))
+    ascii_str = \
+"""\
+ 2        2       1   x           \n\
+n  + n + x  + x + - + -           \n\
+                  x   n           \n\
+        ______                    \n\
+        \\     `                   \n\
+         \\                oo      \n\
+          \\                /      \n\
+           \\              |       \n\
+            \\             |   n   \n\
+             )            |  x  dx\n\
+            /             |       \n\
+           /             /        \n\
+          /              -oo      \n\
+         /              k         \n\
+        /_____,                   \n\
+         k = 0                    \
+"""
+    ucode_str = \
+"""\
+ 2        2       1   x          \n\
+n  + n + x  + x + ─ + ─          \n\
+                  x   n          \n\
+        ______                   \n\
+        ╲                        \n\
+         ╲                       \n\
+          ╲              ∞       \n\
+           ╲             ⌠       \n\
+            ╲            ⎮   n   \n\
+            ╱            ⎮  x  dx\n\
+           ╱             ⌡       \n\
+          ╱              -∞      \n\
+         ╱              k        \n\
+        ╱                        \n\
+        ‾‾‾‾‾‾                   \n\
+         k = 0                   \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Sum(x, (x, 0, oo))
+    ascii_str = \
+"""\
+ oo    \n\
+ __    \n\
+ \\ `   \n\
+  )   x\n\
+ /_,   \n\
+x = 0  \
+"""
+    ucode_str = \
+"""\
+  ∞    \n\
+ ___   \n\
+ ╲     \n\
+  ╲    \n\
+  ╱   x\n\
+ ╱     \n\
+ ‾‾‾   \n\
+x = 0  \
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Sum(x**2, (x, 0, oo))
+    ascii_str = \
+"""\
+ oo     \n\
+___     \n\
+\\  `    \n\
+ \\     2\n\
+ /    x \n\
+/__,    \n\
+x = 0   \
+"""
+    ucode_str = \
+"""\
+  ∞     \n\
+ ___    \n\
+ ╲      \n\
+  ╲    2\n\
+  ╱   x \n\
+ ╱      \n\
+ ‾‾‾    \n\
+x = 0   \
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Sum(x/2, (x, 0, oo))
+    ascii_str = \
+"""\
+ oo    \n\
+___    \n\
+\\  `   \n\
+ \\    x\n\
+  )   -\n\
+ /    2\n\
+/__,   \n\
+x = 0  \
+"""
+    ucode_str = \
+"""\
+ ∞     \n\
+____   \n\
+╲      \n\
+ ╲     \n\
+  ╲   x\n\
+  ╱   ─\n\
+ ╱    2\n\
+╱      \n\
+‾‾‾‾   \n\
+x = 0  \
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Sum(x**3/2, (x, 0, oo))
+    ascii_str = \
+"""\
+ oo     \n\
+____    \n\
+\\   `   \n\
+ \\     3\n\
+  \\   x \n\
+  /   --\n\
+ /    2 \n\
+/___,   \n\
+x = 0   \
+"""
+    ucode_str = \
+"""\
+ ∞      \n\
+____    \n\
+╲       \n\
+ ╲     3\n\
+  ╲   x \n\
+  ╱   ──\n\
+ ╱    2 \n\
+╱       \n\
+‾‾‾‾    \n\
+x = 0   \
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Sum((x**3*y**(x/2))**n, (x, 0, oo))
+    ascii_str = \
+"""\
+ oo           \n\
+____          \n\
+\\   `         \n\
+ \\           n\n\
+  \\   /    x\\ \n\
+   )  |    -| \n\
+  /   | 3  2| \n\
+ /    \\x *y / \n\
+/___,         \n\
+x = 0         \
+"""
+    ucode_str = \
+"""\
+  ∞           \n\
+_____         \n\
+╲             \n\
+ ╲            \n\
+  ╲          n\n\
+   ╲  ⎛    x⎞ \n\
+   ╱  ⎜    ─⎟ \n\
+  ╱   ⎜ 3  2⎟ \n\
+ ╱    ⎝x ⋅y ⎠ \n\
+╱             \n\
+‾‾‾‾‾         \n\
+x = 0         \
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Sum(1/x**2, (x, 0, oo))
+    ascii_str = \
+"""\
+ oo     \n\
+____    \n\
+\\   `   \n\
+ \\    1 \n\
+  \\   --\n\
+  /    2\n\
+ /    x \n\
+/___,   \n\
+x = 0   \
+"""
+    ucode_str = \
+"""\
+ ∞      \n\
+____    \n\
+╲       \n\
+ ╲    1 \n\
+  ╲   ──\n\
+  ╱    2\n\
+ ╱    x \n\
+╱       \n\
+‾‾‾‾    \n\
+x = 0   \
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Sum(1/y**(a/b), (x, 0, oo))
+    ascii_str = \
+"""\
+ oo       \n\
+____      \n\
+\\   `     \n\
+ \\     -a \n\
+  \\    ---\n\
+  /     b \n\
+ /    y   \n\
+/___,     \n\
+x = 0     \
+"""
+    ucode_str = \
+"""\
+ ∞        \n\
+____      \n\
+╲         \n\
+ ╲     -a \n\
+  ╲    ───\n\
+  ╱     b \n\
+ ╱    y   \n\
+╱         \n\
+‾‾‾‾      \n\
+x = 0     \
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Sum(1/y**(a/b), (x, 0, oo), (y, 1, 2))
+    ascii_str = \
+"""\
+  2     oo     \n\
+____  ____     \n\
+\\   ` \\   `    \n\
+ \\     \\     -a\n\
+  \\     \\    --\n\
+  /     /    b \n\
+ /     /    y  \n\
+/___, /___,    \n\
+y = 1 x = 0    \
+"""
+    ucode_str = \
+"""\
+  2     ∞      \n\
+____  ____     \n\
+╲     ╲        \n\
+ ╲     ╲     -a\n\
+  ╲     ╲    ──\n\
+  ╱     ╱    b \n\
+ ╱     ╱    y  \n\
+╱     ╱        \n\
+‾‾‾‾  ‾‾‾‾     \n\
+y = 1 x = 0    \
+"""
+    expr = Sum(1/(1 + 1/(
+        1 + 1/k)) + 1, (k, 111, 1 + 1/n), (k, 1/(1 + m), oo)) + 1/(1 + 1/k)
+    ascii_str = \
+"""\
+              1                          \n\
+          1 + -                          \n\
+   oo         n                          \n\
+ _____    _____                          \n\
+ \\    `   \\    `                         \n\
+  \\        \\      /        1    \\        \n\
+   \\        \\     |1 + ---------|        \n\
+    \\        \\    |          1  |     1  \n\
+     )        )   |    1 + -----| + -----\n\
+    /        /    |            1|       1\n\
+   /        /     |        1 + -|   1 + -\n\
+  /        /      \\            k/       k\n\
+ /____,   /____,                         \n\
+      1   k = 111                        \n\
+k = -----                                \n\
+    m + 1                                \
+"""
+    ucode_str = \
+"""\
+              1                          \n\
+          1 + ─                          \n\
+   ∞          n                          \n\
+ ______   ______                         \n\
+ ╲        ╲                              \n\
+  ╲        ╲                             \n\
+   ╲        ╲     ⎛        1    ⎞        \n\
+    ╲        ╲    ⎜1 + ─────────⎟        \n\
+     ╲        ╲   ⎜          1  ⎟     1  \n\
+     ╱        ╱   ⎜    1 + ─────⎟ + ─────\n\
+    ╱        ╱    ⎜            1⎟       1\n\
+   ╱        ╱     ⎜        1 + ─⎟   1 + ─\n\
+  ╱        ╱      ⎝            k⎠       k\n\
+ ╱        ╱                              \n\
+ ‾‾‾‾‾‾   ‾‾‾‾‾‾                         \n\
+      1   k = 111                        \n\
+k = ─────                                \n\
+    m + 1                                \
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_units():
+    expr = joule
+    ascii_str1 = \
+"""\
+              2\n\
+kilogram*meter \n\
+---------------\n\
+          2    \n\
+    second     \
+"""
+    unicode_str1 = \
+"""\
+              2\n\
+kilogram⋅meter \n\
+───────────────\n\
+          2    \n\
+    second     \
+"""
+
+    ascii_str2 = \
+"""\
+                    2\n\
+3*x*y*kilogram*meter \n\
+---------------------\n\
+             2       \n\
+       second        \
+"""
+    unicode_str2 = \
+"""\
+                    2\n\
+3⋅x⋅y⋅kilogram⋅meter \n\
+─────────────────────\n\
+             2       \n\
+       second        \
+"""
+
+    from sympy.physics.units import kg, m, s
+    assert upretty(expr) == "joule"
+    assert pretty(expr) == "joule"
+    assert upretty(expr.convert_to(kg*m**2/s**2)) == unicode_str1
+    assert pretty(expr.convert_to(kg*m**2/s**2)) == ascii_str1
+    assert upretty(3*kg*x*m**2*y/s**2) == unicode_str2
+    assert pretty(3*kg*x*m**2*y/s**2) == ascii_str2
+
+
+def test_pretty_Subs():
+    f = Function('f')
+    expr = Subs(f(x), x, ph**2)
+    ascii_str = \
+"""\
+(f(x))|     2\n\
+      |x=phi \
+"""
+    unicode_str = \
+"""\
+(f(x))│   2\n\
+      │x=φ \
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == unicode_str
+
+    expr = Subs(f(x).diff(x), x, 0)
+    ascii_str = \
+"""\
+/d       \\|   \n\
+|--(f(x))||   \n\
+\\dx      /|x=0\
+"""
+    unicode_str = \
+"""\
+⎛d       ⎞│   \n\
+⎜──(f(x))⎟│   \n\
+⎝dx      ⎠│x=0\
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == unicode_str
+
+    expr = Subs(f(x).diff(x)/y, (x, y), (0, Rational(1, 2)))
+    ascii_str = \
+"""\
+/d       \\|          \n\
+|--(f(x))||          \n\
+|dx      ||          \n\
+|--------||          \n\
+\\   y    /|x=0, y=1/2\
+"""
+    unicode_str = \
+"""\
+⎛d       ⎞│          \n\
+⎜──(f(x))⎟│          \n\
+⎜dx      ⎟│          \n\
+⎜────────⎟│          \n\
+⎝   y    ⎠│x=0, y=1/2\
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == unicode_str
+
+
+def test_gammas():
+    assert upretty(lowergamma(x, y)) == "γ(x, y)"
+    assert upretty(uppergamma(x, y)) == "Γ(x, y)"
+    assert xpretty(gamma(x), use_unicode=True) == 'Γ(x)'
+    assert xpretty(gamma, use_unicode=True) == 'Γ'
+    assert xpretty(symbols('gamma', cls=Function)(x), use_unicode=True) == 'γ(x)'
+    assert xpretty(symbols('gamma', cls=Function), use_unicode=True) == 'γ'
+
+
+def test_beta():
+    assert xpretty(beta(x,y), use_unicode=True) == 'Β(x, y)'
+    assert xpretty(beta(x,y), use_unicode=False) == 'B(x, y)'
+    assert xpretty(beta, use_unicode=True) == 'Β'
+    assert xpretty(beta, use_unicode=False) == 'B'
+    mybeta = Function('beta')
+    assert xpretty(mybeta(x), use_unicode=True) == 'β(x)'
+    assert xpretty(mybeta(x, y, z), use_unicode=False) == 'beta(x, y, z)'
+    assert xpretty(mybeta, use_unicode=True) == 'β'
+
+
+# test that notation passes to subclasses of the same name only
+def test_function_subclass_different_name():
+    class mygamma(gamma):
+        pass
+    assert xpretty(mygamma, use_unicode=True) == r"mygamma"
+    assert xpretty(mygamma(x), use_unicode=True) == r"mygamma(x)"
+
+
+def test_SingularityFunction():
+    assert xpretty(SingularityFunction(x, 0, n), use_unicode=True) == (
+"""\
+   n\n\
+ \
+""")
+    assert xpretty(SingularityFunction(x, 1, n), use_unicode=True) == (
+"""\
+       n\n\
+ \
+""")
+    assert xpretty(SingularityFunction(x, -1, n), use_unicode=True) == (
+"""\
+       n\n\
+ \
+""")
+    assert xpretty(SingularityFunction(x, a, n), use_unicode=True) == (
+"""\
+        n\n\
+<-a + x> \
+""")
+    assert xpretty(SingularityFunction(x, y, n), use_unicode=True) == (
+"""\
+       n\n\
+ \
+""")
+    assert xpretty(SingularityFunction(x, 0, n), use_unicode=False) == (
+"""\
+   n\n\
+ \
+""")
+    assert xpretty(SingularityFunction(x, 1, n), use_unicode=False) == (
+"""\
+       n\n\
+ \
+""")
+    assert xpretty(SingularityFunction(x, -1, n), use_unicode=False) == (
+"""\
+       n\n\
+ \
+""")
+    assert xpretty(SingularityFunction(x, a, n), use_unicode=False) == (
+"""\
+        n\n\
+<-a + x> \
+""")
+    assert xpretty(SingularityFunction(x, y, n), use_unicode=False) == (
+"""\
+       n\n\
+ \
+""")
+
+
+def test_deltas():
+    assert xpretty(DiracDelta(x), use_unicode=True) == 'δ(x)'
+    assert xpretty(DiracDelta(x, 1), use_unicode=True) == \
+"""\
+ (1)    \n\
+δ    (x)\
+"""
+    assert xpretty(x*DiracDelta(x, 1), use_unicode=True) == \
+"""\
+   (1)    \n\
+x⋅δ    (x)\
+"""
+
+
+def test_hyper():
+    expr = hyper((), (), z)
+    ucode_str = \
+"""\
+ ┌─  ⎛  │  ⎞\n\
+ ├─  ⎜  │ z⎟\n\
+0╵ 0 ⎝  │  ⎠\
+"""
+    ascii_str = \
+"""\
+  _         \n\
+ |_  /  |  \\\n\
+ |   |  | z|\n\
+0  0 \\  |  /\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = hyper((), (1,), x)
+    ucode_str = \
+"""\
+ ┌─  ⎛  │  ⎞\n\
+ ├─  ⎜  │ x⎟\n\
+0╵ 1 ⎝1 │  ⎠\
+"""
+    ascii_str = \
+"""\
+  _         \n\
+ |_  /  |  \\\n\
+ |   |  | x|\n\
+0  1 \\1 |  /\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = hyper([2], [1], x)
+    ucode_str = \
+"""\
+ ┌─  ⎛2 │  ⎞\n\
+ ├─  ⎜  │ x⎟\n\
+1╵ 1 ⎝1 │  ⎠\
+"""
+    ascii_str = \
+"""\
+  _         \n\
+ |_  /2 |  \\\n\
+ |   |  | x|\n\
+1  1 \\1 |  /\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = hyper((pi/3, -2*k), (3, 4, 5, -3), x)
+    ucode_str = \
+"""\
+     ⎛  π         │  ⎞\n\
+ ┌─  ⎜  ─, -2⋅k   │  ⎟\n\
+ ├─  ⎜  3         │ x⎟\n\
+2╵ 4 ⎜            │  ⎟\n\
+     ⎝-3, 3, 4, 5 │  ⎠\
+"""
+    ascii_str = \
+"""\
+                      \n\
+  _  / pi         |  \\\n\
+ |_  | --, -2*k   |  |\n\
+ |   | 3          | x|\n\
+2  4 |            |  |\n\
+     \\-3, 3, 4, 5 |  /\
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = hyper((pi, S('2/3'), -2*k), (3, 4, 5, -3), x**2)
+    ucode_str = \
+"""\
+ ┌─  ⎛2/3, π, -2⋅k │  2⎞\n\
+ ├─  ⎜             │ x ⎟\n\
+3╵ 4 ⎝-3, 3, 4, 5  │   ⎠\
+"""
+    ascii_str = \
+"""\
+  _                      \n\
+ |_  /2/3, pi, -2*k |  2\\
+ |   |              | x |
+3  4 \\ -3, 3, 4, 5  |   /"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = hyper([1, 2], [3, 4], 1/(1/(1/(1/x + 1) + 1) + 1))
+    ucode_str = \
+"""\
+     ⎛     │       1      ⎞\n\
+     ⎜     │ ─────────────⎟\n\
+     ⎜     │         1    ⎟\n\
+ ┌─  ⎜1, 2 │ 1 + ─────────⎟\n\
+ ├─  ⎜     │           1  ⎟\n\
+2╵ 2 ⎜3, 4 │     1 + ─────⎟\n\
+     ⎜     │             1⎟\n\
+     ⎜     │         1 + ─⎟\n\
+     ⎝     │             x⎠\
+"""
+
+    ascii_str = \
+"""\
+                           \n\
+     /     |       1      \\\n\
+     |     | -------------|\n\
+  _  |     |         1    |\n\
+ |_  |1, 2 | 1 + ---------|\n\
+ |   |     |           1  |\n\
+2  2 |3, 4 |     1 + -----|\n\
+     |     |             1|\n\
+     |     |         1 + -|\n\
+     \\     |             x/\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_meijerg():
+    expr = meijerg([pi, pi, x], [1], [0, 1], [1, 2, 3], z)
+    ucode_str = \
+"""\
+╭─╮2, 3 ⎛π, π, x     1    │  ⎞\n\
+│╶┐     ⎜                 │ z⎟\n\
+╰─╯4, 5 ⎝ 0, 1    1, 2, 3 │  ⎠\
+"""
+    ascii_str = \
+"""\
+ __2, 3 /pi, pi, x     1    |  \\\n\
+/__     |                   | z|\n\
+\\_|4, 5 \\  0, 1     1, 2, 3 |  /\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = meijerg([1, pi/7], [2, pi, 5], [], [], z**2)
+    ucode_str = \
+"""\
+        ⎛   π          │   ⎞\n\
+╭─╮0, 2 ⎜1, ─  2, 5, π │  2⎟\n\
+│╶┐     ⎜   7          │ z ⎟\n\
+╰─╯5, 0 ⎜              │   ⎟\n\
+        ⎝              │   ⎠\
+"""
+    ascii_str = \
+"""\
+        /   pi           |   \\\n\
+ __0, 2 |1, --  2, 5, pi |  2|\n\
+/__     |   7            | z |\n\
+\\_|5, 0 |                |   |\n\
+        \\                |   /\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    ucode_str = \
+"""\
+╭─╮ 1, 10 ⎛1, 1, 1, 1, 1, 1, 1, 1, 1, 1  1 │  ⎞\n\
+│╶┐       ⎜                                │ z⎟\n\
+╰─╯11,  2 ⎝             1                1 │  ⎠\
+"""
+    ascii_str = \
+"""\
+ __ 1, 10 /1, 1, 1, 1, 1, 1, 1, 1, 1, 1  1 |  \\\n\
+/__       |                                | z|\n\
+\\_|11,  2 \\             1                1 |  /\
+"""
+
+    expr = meijerg([1]*10, [1], [1], [1], z)
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = meijerg([1, 2, ], [4, 3], [3], [4, 5], 1/(1/(1/(1/x + 1) + 1) + 1))
+
+    ucode_str = \
+"""\
+        ⎛           │       1      ⎞\n\
+        ⎜           │ ─────────────⎟\n\
+        ⎜           │         1    ⎟\n\
+╭─╮1, 2 ⎜1, 2  3, 4 │ 1 + ─────────⎟\n\
+│╶┐     ⎜           │           1  ⎟\n\
+╰─╯4, 3 ⎜ 3    4, 5 │     1 + ─────⎟\n\
+        ⎜           │             1⎟\n\
+        ⎜           │         1 + ─⎟\n\
+        ⎝           │             x⎠\
+"""
+
+    ascii_str = \
+"""\
+        /           |       1      \\\n\
+        |           | -------------|\n\
+        |           |         1    |\n\
+ __1, 2 |1, 2  3, 4 | 1 + ---------|\n\
+/__     |           |           1  |\n\
+\\_|4, 3 | 3    4, 5 |     1 + -----|\n\
+        |           |             1|\n\
+        |           |         1 + -|\n\
+        \\           |             x/\
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = Integral(expr, x)
+
+    ucode_str = \
+"""\
+⌠                                        \n\
+⎮         ⎛           │       1      ⎞   \n\
+⎮         ⎜           │ ─────────────⎟   \n\
+⎮         ⎜           │         1    ⎟   \n\
+⎮ ╭─╮1, 2 ⎜1, 2  3, 4 │ 1 + ─────────⎟   \n\
+⎮ │╶┐     ⎜           │           1  ⎟ dx\n\
+⎮ ╰─╯4, 3 ⎜ 3    4, 5 │     1 + ─────⎟   \n\
+⎮         ⎜           │             1⎟   \n\
+⎮         ⎜           │         1 + ─⎟   \n\
+⎮         ⎝           │             x⎠   \n\
+⌡                                        \
+"""
+
+    ascii_str = \
+"""\
+  /                                       \n\
+ |                                        \n\
+ |         /           |       1      \\   \n\
+ |         |           | -------------|   \n\
+ |         |           |         1    |   \n\
+ |  __1, 2 |1, 2  3, 4 | 1 + ---------|   \n\
+ | /__     |           |           1  | dx\n\
+ | \\_|4, 3 | 3    4, 5 |     1 + -----|   \n\
+ |         |           |             1|   \n\
+ |         |           |         1 + -|   \n\
+ |         \\           |             x/   \n\
+ |                                        \n\
+/                                         \
+"""
+
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_noncommutative():
+    A, B, C = symbols('A,B,C', commutative=False)
+
+    expr = A*B*C**-1
+    ascii_str = \
+"""\
+     -1\n\
+A*B*C  \
+"""
+    ucode_str = \
+"""\
+     -1\n\
+A⋅B⋅C  \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = C**-1*A*B
+    ascii_str = \
+"""\
+ -1    \n\
+C  *A*B\
+"""
+    ucode_str = \
+"""\
+ -1    \n\
+C  ⋅A⋅B\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = A*C**-1*B
+    ascii_str = \
+"""\
+   -1  \n\
+A*C  *B\
+"""
+    ucode_str = \
+"""\
+   -1  \n\
+A⋅C  ⋅B\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = A*C**-1*B/x
+    ascii_str = \
+"""\
+   -1  \n\
+A*C  *B\n\
+-------\n\
+   x   \
+"""
+    ucode_str = \
+"""\
+   -1  \n\
+A⋅C  ⋅B\n\
+───────\n\
+   x   \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_pretty_special_functions():
+    x, y = symbols("x y")
+
+    # atan2
+    expr = atan2(y/sqrt(200), sqrt(x))
+    ascii_str = \
+"""\
+     /  ___         \\\n\
+     |\\/ 2 *y    ___|\n\
+atan2|-------, \\/ x |\n\
+     \\  20          /\
+"""
+    ucode_str = \
+"""\
+     ⎛√2⋅y    ⎞\n\
+atan2⎜────, √x⎟\n\
+     ⎝ 20     ⎠\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_pretty_geometry():
+    e = Segment((0, 1), (0, 2))
+    assert pretty(e) == 'Segment2D(Point2D(0, 1), Point2D(0, 2))'
+    e = Ray((1, 1), angle=4.02*pi)
+    assert pretty(e) == 'Ray2D(Point2D(1, 1), Point2D(2, tan(pi/50) + 1))'
+
+
+def test_expint():
+    expr = Ei(x)
+    string = 'Ei(x)'
+    assert pretty(expr) == string
+    assert upretty(expr) == string
+
+    expr = expint(1, z)
+    ucode_str = "E₁(z)"
+    ascii_str = "expint(1, z)"
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    assert pretty(Shi(x)) == 'Shi(x)'
+    assert pretty(Si(x)) == 'Si(x)'
+    assert pretty(Ci(x)) == 'Ci(x)'
+    assert pretty(Chi(x)) == 'Chi(x)'
+    assert upretty(Shi(x)) == 'Shi(x)'
+    assert upretty(Si(x)) == 'Si(x)'
+    assert upretty(Ci(x)) == 'Ci(x)'
+    assert upretty(Chi(x)) == 'Chi(x)'
+
+
+def test_elliptic_functions():
+    ascii_str = \
+"""\
+ /  1  \\\n\
+K|-----|\n\
+ \\z + 1/\
+"""
+    ucode_str = \
+"""\
+ ⎛  1  ⎞\n\
+K⎜─────⎟\n\
+ ⎝z + 1⎠\
+"""
+    expr = elliptic_k(1/(z + 1))
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    ascii_str = \
+"""\
+ / |  1  \\\n\
+F|1|-----|\n\
+ \\ |z + 1/\
+"""
+    ucode_str = \
+"""\
+ ⎛ │  1  ⎞\n\
+F⎜1│─────⎟\n\
+ ⎝ │z + 1⎠\
+"""
+    expr = elliptic_f(1, 1/(1 + z))
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    ascii_str = \
+"""\
+ /  1  \\\n\
+E|-----|\n\
+ \\z + 1/\
+"""
+    ucode_str = \
+"""\
+ ⎛  1  ⎞\n\
+E⎜─────⎟\n\
+ ⎝z + 1⎠\
+"""
+    expr = elliptic_e(1/(z + 1))
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    ascii_str = \
+"""\
+ / |  1  \\\n\
+E|1|-----|\n\
+ \\ |z + 1/\
+"""
+    ucode_str = \
+"""\
+ ⎛ │  1  ⎞\n\
+E⎜1│─────⎟\n\
+ ⎝ │z + 1⎠\
+"""
+    expr = elliptic_e(1, 1/(1 + z))
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    ascii_str = \
+"""\
+  / |4\\\n\
+Pi|3|-|\n\
+  \\ |x/\
+"""
+    ucode_str = \
+"""\
+ ⎛ │4⎞\n\
+Π⎜3│─⎟\n\
+ ⎝ │x⎠\
+"""
+    expr = elliptic_pi(3, 4/x)
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    ascii_str = \
+"""\
+  /   4| \\\n\
+Pi|3; -|6|\n\
+  \\   x| /\
+"""
+    ucode_str = \
+"""\
+ ⎛   4│ ⎞\n\
+Π⎜3; ─│6⎟\n\
+ ⎝   x│ ⎠\
+"""
+    expr = elliptic_pi(3, 4/x, 6)
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_RandomDomain():
+    from sympy.stats import Normal, Die, Exponential, pspace, where
+    X = Normal('x1', 0, 1)
+    assert upretty(where(X > 0)) == "Domain: 0 < x₁ ∧ x₁ < ∞"
+
+    D = Die('d1', 6)
+    assert upretty(where(D > 4)) == 'Domain: d₁ = 5 ∨ d₁ = 6'
+
+    A = Exponential('a', 1)
+    B = Exponential('b', 1)
+    assert upretty(pspace(Tuple(A, B)).domain) == \
+        'Domain: 0 ≤ a ∧ 0 ≤ b ∧ a < ∞ ∧ b < ∞'
+
+
+def test_PrettyPoly():
+    F = QQ.frac_field(x, y)
+    R = QQ.poly_ring(x, y)
+
+    expr = F.convert(x/(x + y))
+    assert pretty(expr) == "x/(x + y)"
+    assert upretty(expr) == "x/(x + y)"
+
+    expr = R.convert(x + y)
+    assert pretty(expr) == "x + y"
+    assert upretty(expr) == "x + y"
+
+
+def test_issue_6285():
+    assert pretty(Pow(2, -5, evaluate=False)) == '1 \n--\n 5\n2 '
+    assert pretty(Pow(x, (1/pi))) == \
+    ' 1 \n'\
+    ' --\n'\
+    ' pi\n'\
+    'x  '
+
+
+def test_issue_6359():
+    assert pretty(Integral(x**2, x)**2) == \
+"""\
+          2
+/  /     \\ \n\
+| |      | \n\
+| |  2   | \n\
+| | x  dx| \n\
+| |      | \n\
+\\/       / \
+"""
+    assert upretty(Integral(x**2, x)**2) == \
+"""\
+         2
+⎛⌠      ⎞ \n\
+⎜⎮  2   ⎟ \n\
+⎜⎮ x  dx⎟ \n\
+⎝⌡      ⎠ \
+"""
+
+    assert pretty(Sum(x**2, (x, 0, 1))**2) == \
+"""\
+          2\n\
+/ 1      \\ \n\
+|___     | \n\
+|\\  `    | \n\
+| \\     2| \n\
+| /    x | \n\
+|/__,    | \n\
+\\x = 0   / \
+"""
+    assert upretty(Sum(x**2, (x, 0, 1))**2) == \
+"""\
+          2
+⎛  1     ⎞ \n\
+⎜ ___    ⎟ \n\
+⎜ ╲      ⎟ \n\
+⎜  ╲    2⎟ \n\
+⎜  ╱   x ⎟ \n\
+⎜ ╱      ⎟ \n\
+⎜ ‾‾‾    ⎟ \n\
+⎝x = 0   ⎠ \
+"""
+
+    assert pretty(Product(x**2, (x, 1, 2))**2) == \
+"""\
+           2
+/  2      \\ \n\
+|______   | \n\
+| |  |   2| \n\
+| |  |  x | \n\
+| |  |    | \n\
+\\x = 1    / \
+"""
+    assert upretty(Product(x**2, (x, 1, 2))**2) == \
+"""\
+           2
+⎛  2      ⎞ \n\
+⎜─┬──┬─   ⎟ \n\
+⎜ │  │   2⎟ \n\
+⎜ │  │  x ⎟ \n\
+⎜ │  │    ⎟ \n\
+⎝x = 1    ⎠ \
+"""
+
+    f = Function('f')
+    assert pretty(Derivative(f(x), x)**2) == \
+"""\
+          2
+/d       \\ \n\
+|--(f(x))| \n\
+\\dx      / \
+"""
+    assert upretty(Derivative(f(x), x)**2) == \
+"""\
+          2
+⎛d       ⎞ \n\
+⎜──(f(x))⎟ \n\
+⎝dx      ⎠ \
+"""
+
+
+def test_issue_6739():
+    ascii_str = \
+"""\
+  1  \n\
+-----\n\
+  ___\n\
+\\/ x \
+"""
+    ucode_str = \
+"""\
+1 \n\
+──\n\
+√x\
+"""
+    assert pretty(1/sqrt(x)) == ascii_str
+    assert upretty(1/sqrt(x)) == ucode_str
+
+
+def test_complicated_symbol_unchanged():
+    for symb_name in ["dexpr2_d1tau", "dexpr2^d1tau"]:
+        assert pretty(Symbol(symb_name)) == symb_name
+
+
+def test_categories():
+    from sympy.categories import (Object, IdentityMorphism,
+        NamedMorphism, Category, Diagram, DiagramGrid)
+
+    A1 = Object("A1")
+    A2 = Object("A2")
+    A3 = Object("A3")
+
+    f1 = NamedMorphism(A1, A2, "f1")
+    f2 = NamedMorphism(A2, A3, "f2")
+    id_A1 = IdentityMorphism(A1)
+
+    K1 = Category("K1")
+
+    assert pretty(A1) == "A1"
+    assert upretty(A1) == "A₁"
+
+    assert pretty(f1) == "f1:A1-->A2"
+    assert upretty(f1) == "f₁:A₁——▶A₂"
+    assert pretty(id_A1) == "id:A1-->A1"
+    assert upretty(id_A1) == "id:A₁——▶A₁"
+
+    assert pretty(f2*f1) == "f2*f1:A1-->A3"
+    assert upretty(f2*f1) == "f₂∘f₁:A₁——▶A₃"
+
+    assert pretty(K1) == "K1"
+    assert upretty(K1) == "K₁"
+
+    # Test how diagrams are printed.
+    d = Diagram()
+    assert pretty(d) == "EmptySet"
+    assert upretty(d) == "∅"
+
+    d = Diagram({f1: "unique", f2: S.EmptySet})
+    assert pretty(d) == "{f2*f1:A1-->A3: EmptySet, id:A1-->A1: " \
+        "EmptySet, id:A2-->A2: EmptySet, id:A3-->A3: " \
+        "EmptySet, f1:A1-->A2: {unique}, f2:A2-->A3: EmptySet}"
+
+    assert upretty(d) == "{f₂∘f₁:A₁——▶A₃: ∅, id:A₁——▶A₁: ∅, " \
+        "id:A₂——▶A₂: ∅, id:A₃——▶A₃: ∅, f₁:A₁——▶A₂: {unique}, f₂:A₂——▶A₃: ∅}"
+
+    d = Diagram({f1: "unique", f2: S.EmptySet}, {f2 * f1: "unique"})
+    assert pretty(d) == "{f2*f1:A1-->A3: EmptySet, id:A1-->A1: " \
+        "EmptySet, id:A2-->A2: EmptySet, id:A3-->A3: " \
+        "EmptySet, f1:A1-->A2: {unique}, f2:A2-->A3: EmptySet}" \
+        " ==> {f2*f1:A1-->A3: {unique}}"
+    assert upretty(d) == "{f₂∘f₁:A₁——▶A₃: ∅, id:A₁——▶A₁: ∅, id:A₂——▶A₂: " \
+        "∅, id:A₃——▶A₃: ∅, f₁:A₁——▶A₂: {unique}, f₂:A₂——▶A₃: ∅}" \
+        " ══▶ {f₂∘f₁:A₁——▶A₃: {unique}}"
+
+    grid = DiagramGrid(d)
+    assert pretty(grid) == "A1  A2\n      \nA3    "
+    assert upretty(grid) == "A₁  A₂\n      \nA₃    "
+
+
+def test_PrettyModules():
+    R = QQ.old_poly_ring(x, y)
+    F = R.free_module(2)
+    M = F.submodule([x, y], [1, x**2])
+
+    ucode_str = \
+"""\
+       2\n\
+ℚ[x, y] \
+"""
+    ascii_str = \
+"""\
+        2\n\
+QQ[x, y] \
+"""
+
+    assert upretty(F) == ucode_str
+    assert pretty(F) == ascii_str
+
+    ucode_str = \
+"""\
+╱        ⎡    2⎤╲\n\
+╲[x, y], ⎣1, x ⎦╱\
+"""
+    ascii_str = \
+"""\
+              2  \n\
+<[x, y], [1, x ]>\
+"""
+
+    assert upretty(M) == ucode_str
+    assert pretty(M) == ascii_str
+
+    I = R.ideal(x**2, y)
+
+    ucode_str = \
+"""\
+╱ 2   ╲\n\
+╲x , y╱\
+"""
+
+    ascii_str = \
+"""\
+  2    \n\
+\
+"""
+
+    assert upretty(I) == ucode_str
+    assert pretty(I) == ascii_str
+
+    Q = F / M
+
+    ucode_str = \
+"""\
+           2     \n\
+    ℚ[x, y]      \n\
+─────────────────\n\
+╱        ⎡    2⎤╲\n\
+╲[x, y], ⎣1, x ⎦╱\
+"""
+
+    ascii_str = \
+"""\
+            2    \n\
+    QQ[x, y]     \n\
+-----------------\n\
+              2  \n\
+<[x, y], [1, x ]>\
+"""
+
+    assert upretty(Q) == ucode_str
+    assert pretty(Q) == ascii_str
+
+    ucode_str = \
+"""\
+╱⎡    3⎤                                                ╲\n\
+│⎢   x ⎥   ╱        ⎡    2⎤╲           ╱        ⎡    2⎤╲│\n\
+│⎢1, ──⎥ + ╲[x, y], ⎣1, x ⎦╱, [2, y] + ╲[x, y], ⎣1, x ⎦╱│\n\
+╲⎣   2 ⎦                                                ╱\
+"""
+
+    ascii_str = \
+"""\
+      3                                                  \n\
+     x                   2                           2   \n\
+<[1, --] + <[x, y], [1, x ]>, [2, y] + <[x, y], [1, x ]>>\n\
+     2                                                   \
+"""
+
+
+def test_QuotientRing():
+    R = QQ.old_poly_ring(x)/[x**2 + 1]
+
+    ucode_str = \
+"""\
+  ℚ[x]  \n\
+────────\n\
+╱ 2    ╲\n\
+╲x  + 1╱\
+"""
+
+    ascii_str = \
+"""\
+ QQ[x]  \n\
+--------\n\
+  2     \n\
+\
+"""
+
+    assert upretty(R) == ucode_str
+    assert pretty(R) == ascii_str
+
+    ucode_str = \
+"""\
+    ╱ 2    ╲\n\
+1 + ╲x  + 1╱\
+"""
+
+    ascii_str = \
+"""\
+      2     \n\
+1 + \
+"""
+
+    assert upretty(R.one) == ucode_str
+    assert pretty(R.one) == ascii_str
+
+
+def test_Homomorphism():
+    from sympy.polys.agca import homomorphism
+
+    R = QQ.old_poly_ring(x)
+
+    expr = homomorphism(R.free_module(1), R.free_module(1), [0])
+
+    ucode_str = \
+"""\
+          1         1\n\
+[0] : ℚ[x]  ──> ℚ[x] \
+"""
+
+    ascii_str = \
+"""\
+           1          1\n\
+[0] : QQ[x]  --> QQ[x] \
+"""
+
+    assert upretty(expr) == ucode_str
+    assert pretty(expr) == ascii_str
+
+    expr = homomorphism(R.free_module(2), R.free_module(2), [0, 0])
+
+    ucode_str = \
+"""\
+⎡0  0⎤       2         2\n\
+⎢    ⎥ : ℚ[x]  ──> ℚ[x] \n\
+⎣0  0⎦                  \
+"""
+
+    ascii_str = \
+"""\
+[0  0]        2          2\n\
+[    ] : QQ[x]  --> QQ[x] \n\
+[0  0]                    \
+"""
+
+    assert upretty(expr) == ucode_str
+    assert pretty(expr) == ascii_str
+
+    expr = homomorphism(R.free_module(1), R.free_module(1) / [[x]], [0])
+
+    ucode_str = \
+"""\
+                    1\n\
+          1     ℚ[x] \n\
+[0] : ℚ[x]  ──> ─────\n\
+                <[x]>\
+"""
+
+    ascii_str = \
+"""\
+                      1\n\
+           1     QQ[x] \n\
+[0] : QQ[x]  --> ------\n\
+                 <[x]> \
+"""
+
+    assert upretty(expr) == ucode_str
+    assert pretty(expr) == ascii_str
+
+
+def test_Tr():
+    A, B = symbols('A B', commutative=False)
+    t = Tr(A*B)
+    assert pretty(t) == r'Tr(A*B)'
+    assert upretty(t) == 'Tr(A⋅B)'
+
+
+def test_pretty_Add():
+    eq = Mul(-2, x - 2, evaluate=False) + 5
+    assert pretty(eq) == '5 - 2*(x - 2)'
+
+
+def test_issue_7179():
+    assert upretty(Not(Equivalent(x, y))) == 'x ⇎ y'
+    assert upretty(Not(Implies(x, y))) == 'x ↛ y'
+
+
+def test_issue_7180():
+    assert upretty(Equivalent(x, y)) == 'x ⇔ y'
+
+
+def test_pretty_Complement():
+    assert pretty(S.Reals - S.Naturals) == '(-oo, oo) \\ Naturals'
+    assert upretty(S.Reals - S.Naturals) == 'ℝ \\ ℕ'
+    assert pretty(S.Reals - S.Naturals0) == '(-oo, oo) \\ Naturals0'
+    assert upretty(S.Reals - S.Naturals0) == 'ℝ \\ ℕ₀'
+
+
+def test_pretty_SymmetricDifference():
+    from sympy.sets.sets import SymmetricDifference
+    assert upretty(SymmetricDifference(Interval(2,3), Interval(3,5), \
+           evaluate = False)) == '[2, 3] ∆ [3, 5]'
+    with raises(NotImplementedError):
+        pretty(SymmetricDifference(Interval(2,3), Interval(3,5), evaluate = False))
+
+
+def test_pretty_Contains():
+    assert pretty(Contains(x, S.Integers)) == 'Contains(x, Integers)'
+    assert upretty(Contains(x, S.Integers)) == 'x ∈ ℤ'
+
+
+def test_issue_8292():
+    from sympy.core import sympify
+    e = sympify('((x+x**4)/(x-1))-(2*(x-1)**4/(x-1)**4)', evaluate=False)
+    ucode_str = \
+"""\
+           4    4    \n\
+  2⋅(x - 1)    x  + x\n\
+- ────────── + ──────\n\
+          4    x - 1 \n\
+   (x - 1)           \
+"""
+    ascii_str = \
+"""\
+           4    4    \n\
+  2*(x - 1)    x  + x\n\
+- ---------- + ------\n\
+          4    x - 1 \n\
+   (x - 1)           \
+"""
+    assert pretty(e) == ascii_str
+    assert upretty(e) == ucode_str
+
+
+def test_issue_4335():
+    y = Function('y')
+    expr = -y(x).diff(x)
+    ucode_str = \
+"""\
+ d       \n\
+-──(y(x))\n\
+ dx      \
+"""
+    ascii_str = \
+"""\
+  d       \n\
+- --(y(x))\n\
+  dx      \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_issue_8344():
+    from sympy.core import sympify
+    e = sympify('2*x*y**2/1**2 + 1', evaluate=False)
+    ucode_str = \
+"""\
+     2    \n\
+2⋅x⋅y     \n\
+────── + 1\n\
+   2      \n\
+  1       \
+"""
+    assert upretty(e) == ucode_str
+
+
+def test_issue_6324():
+    x = Pow(2, 3, evaluate=False)
+    y = Pow(10, -2, evaluate=False)
+    e = Mul(x, y, evaluate=False)
+    ucode_str = \
+"""\
+ 3 \n\
+2  \n\
+───\n\
+  2\n\
+10 \
+"""
+    assert upretty(e) == ucode_str
+
+
+def test_issue_7927():
+    e = sin(x/2)**cos(x/2)
+    ucode_str = \
+"""\
+           ⎛x⎞\n\
+        cos⎜─⎟\n\
+           ⎝2⎠\n\
+⎛   ⎛x⎞⎞      \n\
+⎜sin⎜─⎟⎟      \n\
+⎝   ⎝2⎠⎠      \
+"""
+    assert upretty(e) == ucode_str
+    e = sin(x)**(S(11)/13)
+    ucode_str = \
+"""\
+        11\n\
+        ──\n\
+        13\n\
+(sin(x))  \
+"""
+    assert upretty(e) == ucode_str
+
+
+def test_issue_6134():
+    from sympy.abc import lamda, t
+    phi = Function('phi')
+
+    e = lamda*x*Integral(phi(t)*pi*sin(pi*t), (t, 0, 1)) + lamda*x**2*Integral(phi(t)*2*pi*sin(2*pi*t), (t, 0, 1))
+    ucode_str = \
+"""\
+     1                              1                   \n\
+   2 ⌠                              ⌠                   \n\
+λ⋅x ⋅⎮ 2⋅π⋅φ(t)⋅sin(2⋅π⋅t) dt + λ⋅x⋅⎮ π⋅φ(t)⋅sin(π⋅t) dt\n\
+     ⌡                              ⌡                   \n\
+     0                              0                   \
+"""
+    assert upretty(e) == ucode_str
+
+
+def test_issue_9877():
+    ucode_str1 = '(2, 3) ∪ ([1, 2] \\ {x})'
+    a, b, c = Interval(2, 3, True, True), Interval(1, 2), FiniteSet(x)
+    assert upretty(Union(a, Complement(b, c))) == ucode_str1
+
+    ucode_str2 = '{x} ∩ {y} ∩ ({z} \\ [1, 2])'
+    d, e, f, g = FiniteSet(x), FiniteSet(y), FiniteSet(z), Interval(1, 2)
+    assert upretty(Intersection(d, e, Complement(f, g))) == ucode_str2
+
+
+def test_issue_13651():
+    expr1 = c + Mul(-1, a + b, evaluate=False)
+    assert pretty(expr1) == 'c - (a + b)'
+    expr2 = c + Mul(-1, a - b + d, evaluate=False)
+    assert pretty(expr2) == 'c - (a - b + d)'
+
+
+def test_pretty_primenu():
+    from sympy.functions.combinatorial.numbers import primenu
+
+    ascii_str1 = "nu(n)"
+    ucode_str1 = "ν(n)"
+
+    n = symbols('n', integer=True)
+    assert pretty(primenu(n)) == ascii_str1
+    assert upretty(primenu(n)) == ucode_str1
+
+
+def test_pretty_primeomega():
+    from sympy.functions.combinatorial.numbers import primeomega
+
+    ascii_str1 = "Omega(n)"
+    ucode_str1 = "Ω(n)"
+
+    n = symbols('n', integer=True)
+    assert pretty(primeomega(n)) == ascii_str1
+    assert upretty(primeomega(n)) == ucode_str1
+
+
+def test_pretty_Mod():
+    from sympy.core import Mod
+
+    ascii_str1 = "x mod 7"
+    ucode_str1 = "x mod 7"
+
+    ascii_str2 = "(x + 1) mod 7"
+    ucode_str2 = "(x + 1) mod 7"
+
+    ascii_str3 = "2*x mod 7"
+    ucode_str3 = "2⋅x mod 7"
+
+    ascii_str4 = "(x mod 7) + 1"
+    ucode_str4 = "(x mod 7) + 1"
+
+    ascii_str5 = "2*(x mod 7)"
+    ucode_str5 = "2⋅(x mod 7)"
+
+    x = symbols('x', integer=True)
+    assert pretty(Mod(x, 7)) == ascii_str1
+    assert upretty(Mod(x, 7)) == ucode_str1
+    assert pretty(Mod(x + 1, 7)) == ascii_str2
+    assert upretty(Mod(x + 1, 7)) == ucode_str2
+    assert pretty(Mod(2 * x, 7)) == ascii_str3
+    assert upretty(Mod(2 * x, 7)) == ucode_str3
+    assert pretty(Mod(x, 7) + 1) == ascii_str4
+    assert upretty(Mod(x, 7) + 1) == ucode_str4
+    assert pretty(2 * Mod(x, 7)) == ascii_str5
+    assert upretty(2 * Mod(x, 7)) == ucode_str5
+
+
+def test_issue_11801():
+    assert pretty(Symbol("")) == ""
+    assert upretty(Symbol("")) == ""
+
+
+def test_pretty_UnevaluatedExpr():
+    x = symbols('x')
+    he = UnevaluatedExpr(1/x)
+
+    ucode_str = \
+"""\
+1\n\
+─\n\
+x\
+"""
+
+    assert upretty(he) == ucode_str
+
+    ucode_str = \
+"""\
+   2\n\
+⎛1⎞ \n\
+⎜─⎟ \n\
+⎝x⎠ \
+"""
+
+    assert upretty(he**2) == ucode_str
+
+    ucode_str = \
+"""\
+    1\n\
+1 + ─\n\
+    x\
+"""
+
+    assert upretty(he + 1) == ucode_str
+
+    ucode_str = \
+('''\
+  1\n\
+x⋅─\n\
+  x\
+''')
+    assert upretty(x*he) == ucode_str
+
+
+def test_issue_10472():
+    M = (Matrix([[0, 0], [0, 0]]), Matrix([0, 0]))
+
+    ucode_str = \
+"""\
+⎛⎡0  0⎤  ⎡0⎤⎞
+⎜⎢    ⎥, ⎢ ⎥⎟
+⎝⎣0  0⎦  ⎣0⎦⎠\
+"""
+    assert upretty(M) == ucode_str
+
+
+def test_MatrixElement_printing():
+    # test cases for issue #11821
+    A = MatrixSymbol("A", 1, 3)
+    B = MatrixSymbol("B", 1, 3)
+    C = MatrixSymbol("C", 1, 3)
+
+    ascii_str1 = "A_00"
+    ucode_str1 = "A₀₀"
+    assert pretty(A[0, 0])  == ascii_str1
+    assert upretty(A[0, 0]) == ucode_str1
+
+    ascii_str1 = "3*A_00"
+    ucode_str1 = "3⋅A₀₀"
+    assert pretty(3*A[0, 0])  == ascii_str1
+    assert upretty(3*A[0, 0]) == ucode_str1
+
+    ascii_str1 = "(-B + A)[0, 0]"
+    ucode_str1 = "(-B + A)[0, 0]"
+    F = C[0, 0].subs(C, A - B)
+    assert pretty(F)  == ascii_str1
+    assert upretty(F) == ucode_str1
+
+
+def test_issue_12675():
+    x, y, t, j = symbols('x y t j')
+    e = CoordSys3D('e')
+
+    ucode_str = \
+"""\
+⎛   t⎞    \n\
+⎜⎛x⎞ ⎟ j_e\n\
+⎜⎜─⎟ ⎟    \n\
+⎝⎝y⎠ ⎠    \
+"""
+    assert upretty((x/y)**t*e.j) == ucode_str
+    ucode_str = \
+"""\
+⎛1⎞    \n\
+⎜─⎟ j_e\n\
+⎝y⎠    \
+"""
+    assert upretty((1/y)*e.j) == ucode_str
+
+
+def test_MatrixSymbol_printing():
+    # test cases for issue #14237
+    A = MatrixSymbol("A", 3, 3)
+    B = MatrixSymbol("B", 3, 3)
+    C = MatrixSymbol("C", 3, 3)
+    assert pretty(-A*B*C) == "-A*B*C"
+    assert pretty(A - B) == "-B + A"
+    assert pretty(A*B*C - A*B - B*C) == "-A*B -B*C + A*B*C"
+
+    # issue #14814
+    x = MatrixSymbol('x', n, n)
+    y = MatrixSymbol('y*', n, n)
+    assert pretty(x + y) == "x + y*"
+    ascii_str = \
+"""\
+     2     \n\
+-2*y*  -a*x\
+"""
+    assert pretty(-a*x + -2*y*y) == ascii_str
+
+
+def test_degree_printing():
+    expr1 = 90*degree
+    assert pretty(expr1) == '90°'
+    expr2 = x*degree
+    assert pretty(expr2) == 'x°'
+    expr3 = cos(x*degree + 90*degree)
+    assert pretty(expr3) == 'cos(x° + 90°)'
+
+
+def test_vector_expr_pretty_printing():
+    A = CoordSys3D('A')
+
+    assert upretty(Cross(A.i, A.x*A.i+3*A.y*A.j)) == "(i_A)×((x_A) i_A + (3⋅y_A) j_A)"
+    assert upretty(x*Cross(A.i, A.j)) == 'x⋅(i_A)×(j_A)'
+
+    assert upretty(Curl(A.x*A.i + 3*A.y*A.j)) == "∇×((x_A) i_A + (3⋅y_A) j_A)"
+
+    assert upretty(Divergence(A.x*A.i + 3*A.y*A.j)) == "∇⋅((x_A) i_A + (3⋅y_A) j_A)"
+
+    assert upretty(Dot(A.i, A.x*A.i+3*A.y*A.j)) == "(i_A)⋅((x_A) i_A + (3⋅y_A) j_A)"
+
+    assert upretty(Gradient(A.x+3*A.y)) == "∇(x_A + 3⋅y_A)"
+    assert upretty(Laplacian(A.x+3*A.y)) == "∆(x_A + 3⋅y_A)"
+    # TODO: add support for ASCII pretty.
+
+
+def test_pretty_print_tensor_expr():
+    L = TensorIndexType("L")
+    i, j, k = tensor_indices("i j k", L)
+    i0 = tensor_indices("i_0", L)
+    A, B, C, D = tensor_heads("A B C D", [L])
+    H = TensorHead("H", [L, L])
+
+    expr = -i
+    ascii_str = \
+"""\
+-i\
+"""
+    ucode_str = \
+"""\
+-i\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = A(i)
+    ascii_str = \
+"""\
+ i\n\
+A \n\
+  \
+"""
+    ucode_str = \
+"""\
+ i\n\
+A \n\
+  \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = A(i0)
+    ascii_str = \
+"""\
+ i_0\n\
+A   \n\
+    \
+"""
+    ucode_str = \
+"""\
+ i₀\n\
+A  \n\
+   \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = A(-i)
+    ascii_str = \
+"""\
+  \n\
+A \n\
+ i\
+"""
+    ucode_str = \
+"""\
+  \n\
+A \n\
+ i\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = -3*A(-i)
+    ascii_str = \
+"""\
+     \n\
+-3*A \n\
+    i\
+"""
+    ucode_str = \
+"""\
+     \n\
+-3⋅A \n\
+    i\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = H(i, -j)
+    ascii_str = \
+"""\
+ i \n\
+H  \n\
+  j\
+"""
+    ucode_str = \
+"""\
+ i \n\
+H  \n\
+  j\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = H(i, -i)
+    ascii_str = \
+"""\
+ L_0   \n\
+H      \n\
+    L_0\
+"""
+    ucode_str = \
+"""\
+ L₀  \n\
+H    \n\
+   L₀\
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = H(i, -j)*A(j)*B(k)
+    ascii_str = \
+"""\
+ i     L_0  k\n\
+H    *A   *B \n\
+  L_0        \
+"""
+    ucode_str = \
+"""\
+ i    L₀  k\n\
+H   ⋅A  ⋅B \n\
+  L₀       \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = (1+x)*A(i)
+    ascii_str = \
+"""\
+         i\n\
+(x + 1)*A \n\
+          \
+"""
+    ucode_str = \
+"""\
+         i\n\
+(x + 1)⋅A \n\
+          \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = A(i) + 3*B(i)
+    ascii_str = \
+"""\
+   i    i\n\
+3*B  + A \n\
+         \
+"""
+    ucode_str = \
+"""\
+   i    i\n\
+3⋅B  + A \n\
+         \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_pretty_print_tensor_partial_deriv():
+    from sympy.tensor.toperators import PartialDerivative
+
+    L = TensorIndexType("L")
+    i, j, k = tensor_indices("i j k", L)
+
+    A, B, C, D = tensor_heads("A B C D", [L])
+
+    H = TensorHead("H", [L, L])
+
+    expr = PartialDerivative(A(i), A(j))
+    ascii_str = \
+"""\
+ d / i\\\n\
+---|A |\n\
+  j\\  /\n\
+dA     \n\
+       \
+"""
+    ucode_str = \
+"""\
+ ∂ ⎛ i⎞\n\
+───⎜A ⎟\n\
+  j⎝  ⎠\n\
+∂A     \n\
+       \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = A(i)*PartialDerivative(H(k, -i), A(j))
+    ascii_str = \
+"""\
+ L_0  d / k   \\\n\
+A   *---|H    |\n\
+       j\\  L_0/\n\
+     dA        \n\
+               \
+"""
+    ucode_str = \
+"""\
+ L₀  ∂ ⎛ k  ⎞\n\
+A  ⋅───⎜H   ⎟\n\
+      j⎝  L₀⎠\n\
+    ∂A       \n\
+             \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = A(i)*PartialDerivative(B(k)*C(-i) + 3*H(k, -i), A(j))
+    ascii_str = \
+"""\
+ L_0  d /   k       k     \\\n\
+A   *---|3*H     + B *C   |\n\
+       j\\    L_0       L_0/\n\
+     dA                    \n\
+                           \
+"""
+    ucode_str = \
+"""\
+ L₀  ∂ ⎛   k      k    ⎞\n\
+A  ⋅───⎜3⋅H    + B ⋅C  ⎟\n\
+      j⎝    L₀       L₀⎠\n\
+    ∂A                  \n\
+                        \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = (A(i) + B(i))*PartialDerivative(C(j), D(j))
+    ascii_str = \
+"""\
+/ i    i\\   d  / L_0\\\n\
+|A  + B |*-----|C   |\n\
+\\       /   L_0\\    /\n\
+          dD         \n\
+                     \
+"""
+    ucode_str = \
+"""\
+⎛ i    i⎞  ∂  ⎛ L₀⎞\n\
+⎜A  + B ⎟⋅────⎜C  ⎟\n\
+⎝       ⎠   L₀⎝   ⎠\n\
+          ∂D       \n\
+                   \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = (A(i) + B(i))*PartialDerivative(C(-i), D(j))
+    ascii_str = \
+"""\
+/ L_0    L_0\\  d /    \\\n\
+|A    + B   |*---|C   |\n\
+\\           /   j\\ L_0/\n\
+              dD       \n\
+                       \
+"""
+    ucode_str = \
+"""\
+⎛ L₀    L₀⎞  ∂ ⎛   ⎞\n\
+⎜A   + B  ⎟⋅───⎜C  ⎟\n\
+⎝         ⎠   j⎝ L₀⎠\n\
+            ∂D      \n\
+                    \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = PartialDerivative(B(-i) + A(-i), A(-j), A(-n))
+    ucode_str = """\
+   2            \n\
+  ∂    ⎛       ⎞\n\
+───────⎜A  + B ⎟\n\
+       ⎝ i    i⎠\n\
+∂A  ∂A          \n\
+  n   j         \
+"""
+    assert upretty(expr) == ucode_str
+
+    expr = PartialDerivative(3*A(-i), A(-j), A(-n))
+    ucode_str = """\
+   2         \n\
+  ∂    ⎛    ⎞\n\
+───────⎜3⋅A ⎟\n\
+       ⎝   i⎠\n\
+∂A  ∂A       \n\
+  n   j      \
+"""
+    assert upretty(expr) == ucode_str
+
+    expr = TensorElement(H(i, j), {i:1})
+    ascii_str = \
+"""\
+ i=1,j\n\
+H     \n\
+      \
+"""
+    ucode_str = ascii_str
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = TensorElement(H(i, j), {i: 1, j: 1})
+    ascii_str = \
+"""\
+ i=1,j=1\n\
+H       \n\
+        \
+"""
+    ucode_str = ascii_str
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = TensorElement(H(i, j), {j: 1})
+    ascii_str = \
+"""\
+ i,j=1\n\
+H     \n\
+      \
+"""
+    ucode_str = ascii_str
+
+    expr = TensorElement(H(-i, j), {-i: 1})
+    ascii_str = \
+"""\
+    j\n\
+H    \n\
+ i=1 \
+"""
+    ucode_str = ascii_str
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_issue_15560():
+    a = MatrixSymbol('a', 1, 1)
+    e = pretty(a*(KroneckerProduct(a, a)))
+    result = 'a*(a x a)'
+    assert e == result
+
+
+def test_print_polylog():
+    # Part of issue 6013
+    uresult = 'Li₂(3)'
+    aresult = 'polylog(2, 3)'
+    assert pretty(polylog(2, 3)) == aresult
+    assert upretty(polylog(2, 3)) == uresult
+
+
+# Issue #25312
+def test_print_expint_polylog_symbolic_order():
+    s, z = symbols("s, z")
+    uresult = 'Liₛ(z)'
+    aresult = 'polylog(s, z)'
+    assert pretty(polylog(s, z)) == aresult
+    assert upretty(polylog(s, z)) == uresult
+    # TODO: TBD polylog(s - 1, z)
+    uresult = 'Eₛ(z)'
+    aresult = 'expint(s, z)'
+    assert pretty(expint(s, z)) == aresult
+    assert upretty(expint(s, z)) == uresult
+
+
+
+def test_print_polylog_long_order_issue_25309():
+    s, z = symbols("s, z")
+    ucode_str = \
+"""\
+       ⎛ 2   ⎞\n\
+polylog⎝s , z⎠\
+"""
+    assert upretty(polylog(s**2, z)) == ucode_str
+
+
+def test_print_lerchphi():
+    # Part of issue 6013
+    a = Symbol('a')
+    pretty(lerchphi(a, 1, 2))
+    uresult = 'Φ(a, 1, 2)'
+    aresult = 'lerchphi(a, 1, 2)'
+    assert pretty(lerchphi(a, 1, 2)) == aresult
+    assert upretty(lerchphi(a, 1, 2)) == uresult
+
+
+def test_issue_15583():
+
+    N = mechanics.ReferenceFrame('N')
+    result = '(n_x, n_y, n_z)'
+    e = pretty((N.x, N.y, N.z))
+    assert e == result
+
+
+def test_matrixSymbolBold():
+    # Issue 15871
+    def boldpretty(expr):
+        return xpretty(expr, use_unicode=True, wrap_line=False, mat_symbol_style="bold")
+
+    from sympy.matrices.expressions.trace import trace
+    A = MatrixSymbol("A", 2, 2)
+    assert boldpretty(trace(A)) == 'tr(𝐀)'
+
+    A = MatrixSymbol("A", 3, 3)
+    B = MatrixSymbol("B", 3, 3)
+    C = MatrixSymbol("C", 3, 3)
+
+    assert boldpretty(-A) == '-𝐀'
+    assert boldpretty(A - A*B - B) == '-𝐁 -𝐀⋅𝐁 + 𝐀'
+    assert boldpretty(-A*B - A*B*C - B) == '-𝐁 -𝐀⋅𝐁 -𝐀⋅𝐁⋅𝐂'
+
+    A = MatrixSymbol("Addot", 3, 3)
+    assert boldpretty(A) == '𝐀̈'
+    omega = MatrixSymbol("omega", 3, 3)
+    assert boldpretty(omega) == 'ω'
+    omega = MatrixSymbol("omeganorm", 3, 3)
+    assert boldpretty(omega) == '‖ω‖'
+
+    a = Symbol('alpha')
+    b = Symbol('b')
+    c = MatrixSymbol("c", 3, 1)
+    d = MatrixSymbol("d", 3, 1)
+
+    assert boldpretty(a*B*c+b*d) == 'b⋅𝐝 + α⋅𝐁⋅𝐜'
+
+    d = MatrixSymbol("delta", 3, 1)
+    B = MatrixSymbol("Beta", 3, 3)
+
+    assert boldpretty(a*B*c+b*d) == 'b⋅δ + α⋅Β⋅𝐜'
+
+    A = MatrixSymbol("A_2", 3, 3)
+    assert boldpretty(A) == '𝐀₂'
+
+
+def test_center_accent():
+    assert center_accent('a', '\N{COMBINING TILDE}') == 'ã'
+    assert center_accent('aa', '\N{COMBINING TILDE}') == 'aã'
+    assert center_accent('aaa', '\N{COMBINING TILDE}') == 'aãa'
+    assert center_accent('aaaa', '\N{COMBINING TILDE}') == 'aaãa'
+    assert center_accent('aaaaa', '\N{COMBINING TILDE}') == 'aaãaa'
+    assert center_accent('abcdefg', '\N{COMBINING FOUR DOTS ABOVE}') == 'abcd⃜efg'
+
+
+def test_imaginary_unit():
+    from sympy.printing.pretty import pretty  # b/c it was redefined above
+    assert pretty(1 + I, use_unicode=False) == '1 + I'
+    assert pretty(1 + I, use_unicode=True) == '1 + ⅈ'
+    assert pretty(1 + I, use_unicode=False, imaginary_unit='j') == '1 + I'
+    assert pretty(1 + I, use_unicode=True, imaginary_unit='j') == '1 + ⅉ'
+
+    raises(TypeError, lambda: pretty(I, imaginary_unit=I))
+    raises(ValueError, lambda: pretty(I, imaginary_unit="kkk"))
+
+
+def test_str_special_matrices():
+    from sympy.matrices import Identity, ZeroMatrix, OneMatrix
+    assert pretty(Identity(4)) == 'I'
+    assert upretty(Identity(4)) == '𝕀'
+    assert pretty(ZeroMatrix(2, 2)) == '0'
+    assert upretty(ZeroMatrix(2, 2)) == '𝟘'
+    assert pretty(OneMatrix(2, 2)) == '1'
+    assert upretty(OneMatrix(2, 2)) == '𝟙'
+
+
+def test_pretty_misc_functions():
+    assert pretty(LambertW(x)) == 'W(x)'
+    assert upretty(LambertW(x)) == 'W(x)'
+    assert pretty(LambertW(x, y)) == 'W(x, y)'
+    assert upretty(LambertW(x, y)) == 'W(x, y)'
+    assert pretty(airyai(x)) == 'Ai(x)'
+    assert upretty(airyai(x)) == 'Ai(x)'
+    assert pretty(airybi(x)) == 'Bi(x)'
+    assert upretty(airybi(x)) == 'Bi(x)'
+    assert pretty(airyaiprime(x)) == "Ai'(x)"
+    assert upretty(airyaiprime(x)) == "Ai'(x)"
+    assert pretty(airybiprime(x)) == "Bi'(x)"
+    assert upretty(airybiprime(x)) == "Bi'(x)"
+    assert pretty(fresnelc(x)) == 'C(x)'
+    assert upretty(fresnelc(x)) == 'C(x)'
+    assert pretty(fresnels(x)) == 'S(x)'
+    assert upretty(fresnels(x)) == 'S(x)'
+    assert pretty(Heaviside(x)) == 'Heaviside(x)'
+    assert upretty(Heaviside(x)) == 'θ(x)'
+    assert pretty(Heaviside(x, y)) == 'Heaviside(x, y)'
+    assert upretty(Heaviside(x, y)) == 'θ(x, y)'
+    assert pretty(dirichlet_eta(x)) == 'dirichlet_eta(x)'
+    assert upretty(dirichlet_eta(x)) == 'η(x)'
+
+
+def test_hadamard_power():
+    m, n, p = symbols('m, n, p', integer=True)
+    A = MatrixSymbol('A', m, n)
+    B = MatrixSymbol('B', m, n)
+
+    # Testing printer:
+    expr = hadamard_power(A, n)
+    ascii_str = \
+"""\
+ .n\n\
+A  \
+"""
+    ucode_str = \
+"""\
+ ∘n\n\
+A  \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = hadamard_power(A, 1+n)
+    ascii_str = \
+"""\
+ .(n + 1)\n\
+A        \
+"""
+    ucode_str = \
+"""\
+ ∘(n + 1)\n\
+A        \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+    expr = hadamard_power(A*B.T, 1+n)
+    ascii_str = \
+"""\
+      .(n + 1)\n\
+/   T\\        \n\
+\\A*B /        \
+"""
+    ucode_str = \
+"""\
+      ∘(n + 1)\n\
+⎛   T⎞        \n\
+⎝A⋅B ⎠        \
+"""
+    assert pretty(expr) == ascii_str
+    assert upretty(expr) == ucode_str
+
+
+def test_issue_17258():
+    n = Symbol('n', integer=True)
+    assert pretty(Sum(n, (n, -oo, 1))) == \
+    '   1     \n'\
+    '  __     \n'\
+    '  \\ `    \n'\
+    '   )    n\n'\
+    '  /_,    \n'\
+    'n = -oo  '
+
+    assert upretty(Sum(n, (n, -oo, 1))) == \
+"""\
+  1     \n\
+ ___    \n\
+ ╲      \n\
+  ╲     \n\
+  ╱    n\n\
+ ╱      \n\
+ ‾‾‾    \n\
+n = -∞  \
+"""
+
+
+def test_is_combining():
+    line = "v̇_m"
+    assert [is_combining(sym) for sym in line] == \
+        [False, True, False, False]
+
+
+def test_issue_17616():
+    assert pretty(pi**(1/exp(1))) == \
+   '  / -1\\\n'\
+   '  \\e  /\n'\
+   'pi     '
+
+    assert upretty(pi**(1/exp(1))) == \
+   ' ⎛ -1⎞\n'\
+   ' ⎝ℯ  ⎠\n'\
+   'π     '
+
+    assert pretty(pi**(1/pi)) == \
+    '  1 \n'\
+    '  --\n'\
+    '  pi\n'\
+    'pi  '
+
+    assert upretty(pi**(1/pi)) == \
+    ' 1\n'\
+    ' ─\n'\
+    ' π\n'\
+    'π '
+
+    assert pretty(pi**(1/EulerGamma)) == \
+    '      1     \n'\
+    '  ----------\n'\
+    '  EulerGamma\n'\
+    'pi          '
+
+    assert upretty(pi**(1/EulerGamma)) == \
+    ' 1\n'\
+    ' ─\n'\
+    ' γ\n'\
+    'π '
+
+    z = Symbol("x_17")
+    assert upretty(7**(1/z)) == \
+    'x₁₇___\n'\
+    ' ╲╱ 7 '
+
+    assert pretty(7**(1/z)) == \
+    'x_17___\n'\
+    '  \\/ 7 '
+
+
+def test_issue_17857():
+    assert pretty(Range(-oo, oo)) == '{..., -1, 0, 1, ...}'
+    assert pretty(Range(oo, -oo, -1)) == '{..., 1, 0, -1, ...}'
+
+
+def test_issue_18272():
+    x = Symbol('x')
+    n = Symbol('n')
+
+    assert upretty(ConditionSet(x, Eq(-x + exp(x), 0), S.Complexes)) == \
+    '⎧  │         ⎛      x    ⎞⎫\n'\
+    '⎨x │ x ∊ ℂ ∧ ⎝-x + ℯ  = 0⎠⎬\n'\
+    '⎩  │                      ⎭'
+    assert upretty(ConditionSet(x, Contains(n/2, Interval(0, oo)), FiniteSet(-n/2, n/2))) == \
+    '⎧  │     ⎧-n   n⎫   ⎛n         ⎞⎫\n'\
+    '⎨x │ x ∊ ⎨───, ─⎬ ∧ ⎜─ ∈ [0, ∞)⎟⎬\n'\
+    '⎩  │     ⎩ 2   2⎭   ⎝2         ⎠⎭'
+    assert upretty(ConditionSet(x, Eq(Piecewise((1, x >= 3), (x/2 - 1/2, x >= 2), (1/2, x >= 1),
+                (x/2, True)) - 1/2, 0), Interval(0, 3))) == \
+    '⎧  │              ⎛⎛⎧   1     for x ≥ 3⎞          ⎞⎫\n'\
+    '⎪  │              ⎜⎜⎪                  ⎟          ⎟⎪\n'\
+    '⎪  │              ⎜⎜⎪x                 ⎟          ⎟⎪\n'\
+    '⎪  │              ⎜⎜⎪─ - 0.5  for x ≥ 2⎟          ⎟⎪\n'\
+    '⎪  │              ⎜⎜⎪2                 ⎟          ⎟⎪\n'\
+    '⎨x │ x ∊ [0, 3] ∧ ⎜⎜⎨                  ⎟ - 0.5 = 0⎟⎬\n'\
+    '⎪  │              ⎜⎜⎪  0.5    for x ≥ 1⎟          ⎟⎪\n'\
+    '⎪  │              ⎜⎜⎪                  ⎟          ⎟⎪\n'\
+    '⎪  │              ⎜⎜⎪   x              ⎟          ⎟⎪\n'\
+    '⎪  │              ⎜⎜⎪   ─     otherwise⎟          ⎟⎪\n'\
+    '⎩  │              ⎝⎝⎩   2              ⎠          ⎠⎭'
+
+
+def test_Str():
+    from sympy.core.symbol import Str
+    assert pretty(Str('x')) == 'x'
+
+
+def test_symbolic_probability():
+    mu = symbols("mu")
+    sigma = symbols("sigma", positive=True)
+    X = Normal("X", mu, sigma)
+    assert pretty(Expectation(X)) == r'E[X]'
+    assert pretty(Variance(X)) == r'Var(X)'
+    assert pretty(Probability(X > 0)) == r'P(X > 0)'
+    Y = Normal("Y", mu, sigma)
+    assert pretty(Covariance(X, Y)) == 'Cov(X, Y)'
+
+
+def test_issue_21758():
+    from sympy.functions.elementary.piecewise import piecewise_fold
+    from sympy.series.fourier import FourierSeries
+    x = Symbol('x')
+    k, n = symbols('k n')
+    fo = FourierSeries(x, (x, -pi, pi), (0, SeqFormula(0, (k, 1, oo)), SeqFormula(
+        Piecewise((-2*pi*cos(n*pi)/n + 2*sin(n*pi)/n**2, (n > -oo) & (n < oo) & Ne(n, 0)),
+                  (0, True))*sin(n*x)/pi, (n, 1, oo))))
+    assert upretty(piecewise_fold(fo)) == \
+        '⎧                      2⋅sin(3⋅x)                                \n'\
+        '⎪2⋅sin(x) - sin(2⋅x) + ────────── + …  for n > -∞ ∧ n < ∞ ∧ n ≠ 0\n'\
+        '⎨                          3                                     \n'\
+        '⎪                                                                \n'\
+        '⎩                 0                            otherwise         '
+    assert pretty(FourierSeries(x, (x, -pi, pi), (0, SeqFormula(0, (k, 1, oo)),
+                                                 SeqFormula(0, (n, 1, oo))))) == '0'
+
+
+def test_diffgeom():
+    from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField
+    x,y = symbols('x y', real=True)
+    m = Manifold('M', 2)
+    assert pretty(m) == 'M'
+    p = Patch('P', m)
+    assert pretty(p) == "P"
+    rect = CoordSystem('rect', p, [x, y])
+    assert pretty(rect) == "rect"
+    b = BaseScalarField(rect, 0)
+    assert pretty(b) == "x"
+
+
+def test_deprecated_prettyForm():
+    with warns_deprecated_sympy():
+        from sympy.printing.pretty.pretty_symbology import xstr
+        assert xstr(1) == '1'
+
+    with warns_deprecated_sympy():
+        from sympy.printing.pretty.stringpict import prettyForm
+        p = prettyForm('s', unicode='s')
+
+    with warns_deprecated_sympy():
+        assert p.unicode == p.s == 's'
+
+
+def test_center():
+    assert center('1', 2) == '1 '
+    assert center('1', 3) == ' 1 '
+    assert center('1', 3, '-') == '-1-'
+    assert center('1', 5, '-') == '--1--'
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_aesaracode.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_aesaracode.py
new file mode 100644
index 0000000000000000000000000000000000000000..13308af65b382e77de33302bcd75344d2b00adbf
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_aesaracode.py
@@ -0,0 +1,633 @@
+"""
+Important note on tests in this module - the Aesara printing functions use a
+global cache by default, which means that tests using it will modify global
+state and thus not be independent from each other. Instead of using the "cache"
+keyword argument each time, this module uses the aesara_code_ and
+aesara_function_ functions defined below which default to using a new, empty
+cache instead.
+"""
+
+import logging
+
+from sympy.external import import_module
+from sympy.testing.pytest import raises, SKIP, warns_deprecated_sympy
+
+from sympy.utilities.exceptions import ignore_warnings
+
+
+aesaralogger = logging.getLogger('aesara.configdefaults')
+aesaralogger.setLevel(logging.CRITICAL)
+aesara = import_module('aesara')
+aesaralogger.setLevel(logging.WARNING)
+
+
+if aesara:
+    import numpy as np
+    aet = aesara.tensor
+    from aesara.scalar.basic import ScalarType
+    from aesara.graph.basic import Variable
+    from aesara.tensor.var import TensorVariable
+    from aesara.tensor.elemwise import Elemwise, DimShuffle
+    from aesara.tensor.math import Dot
+
+    from sympy.printing.aesaracode import true_divide
+
+    xt, yt, zt = [aet.scalar(name, 'floatX') for name in 'xyz']
+    Xt, Yt, Zt = [aet.tensor('floatX', (False, False), name=n) for n in 'XYZ']
+else:
+    #bin/test will not execute any tests now
+    disabled = True
+
+import sympy as sy
+from sympy.core.singleton import S
+from sympy.abc import x, y, z, t
+from sympy.printing.aesaracode import (aesara_code, dim_handling,
+        aesara_function)
+
+
+# Default set of matrix symbols for testing - make square so we can both
+# multiply and perform elementwise operations between them.
+X, Y, Z = [sy.MatrixSymbol(n, 4, 4) for n in 'XYZ']
+
+# For testing AppliedUndef
+f_t = sy.Function('f')(t)
+
+
+def aesara_code_(expr, **kwargs):
+    """ Wrapper for aesara_code that uses a new, empty cache by default. """
+    kwargs.setdefault('cache', {})
+    with warns_deprecated_sympy():
+        return aesara_code(expr, **kwargs)
+
+def aesara_function_(inputs, outputs, **kwargs):
+    """ Wrapper for aesara_function that uses a new, empty cache by default. """
+    kwargs.setdefault('cache', {})
+    with warns_deprecated_sympy():
+        return aesara_function(inputs, outputs, **kwargs)
+
+
+def fgraph_of(*exprs):
+    """ Transform SymPy expressions into Aesara Computation.
+
+    Parameters
+    ==========
+    exprs
+        SymPy expressions
+
+    Returns
+    =======
+    aesara.graph.fg.FunctionGraph
+    """
+    outs = list(map(aesara_code_, exprs))
+    ins = list(aesara.graph.basic.graph_inputs(outs))
+    ins, outs = aesara.graph.basic.clone(ins, outs)
+    return aesara.graph.fg.FunctionGraph(ins, outs)
+
+
+def aesara_simplify(fgraph):
+    """ Simplify a Aesara Computation.
+
+    Parameters
+    ==========
+    fgraph : aesara.graph.fg.FunctionGraph
+
+    Returns
+    =======
+    aesara.graph.fg.FunctionGraph
+    """
+    mode = aesara.compile.get_default_mode().excluding("fusion")
+    fgraph = fgraph.clone()
+    mode.optimizer.rewrite(fgraph)
+    return fgraph
+
+
+def theq(a, b):
+    """ Test two Aesara objects for equality.
+
+    Also accepts numeric types and lists/tuples of supported types.
+
+    Note - debugprint() has a bug where it will accept numeric types but does
+    not respect the "file" argument and in this case and instead prints the number
+    to stdout and returns an empty string. This can lead to tests passing where
+    they should fail because any two numbers will always compare as equal. To
+    prevent this we treat numbers as a separate case.
+    """
+    numeric_types = (int, float, np.number)
+    a_is_num = isinstance(a, numeric_types)
+    b_is_num = isinstance(b, numeric_types)
+
+    # Compare numeric types using regular equality
+    if a_is_num or b_is_num:
+        if not (a_is_num and b_is_num):
+            return False
+
+        return a == b
+
+    # Compare sequences element-wise
+    a_is_seq = isinstance(a, (tuple, list))
+    b_is_seq = isinstance(b, (tuple, list))
+
+    if a_is_seq or b_is_seq:
+        if not (a_is_seq and b_is_seq) or type(a) != type(b):
+            return False
+
+        return list(map(theq, a)) == list(map(theq, b))
+
+    # Otherwise, assume debugprint() can handle it
+    astr = aesara.printing.debugprint(a, file='str')
+    bstr = aesara.printing.debugprint(b, file='str')
+
+    # Check for bug mentioned above
+    for argname, argval, argstr in [('a', a, astr), ('b', b, bstr)]:
+        if argstr == '':
+            raise TypeError(
+                'aesara.printing.debugprint(%s) returned empty string '
+                '(%s is instance of %r)'
+                % (argname, argname, type(argval))
+            )
+
+    return astr == bstr
+
+
+def test_example_symbols():
+    """
+    Check that the example symbols in this module print to their Aesara
+    equivalents, as many of the other tests depend on this.
+    """
+    assert theq(xt, aesara_code_(x))
+    assert theq(yt, aesara_code_(y))
+    assert theq(zt, aesara_code_(z))
+    assert theq(Xt, aesara_code_(X))
+    assert theq(Yt, aesara_code_(Y))
+    assert theq(Zt, aesara_code_(Z))
+
+
+def test_Symbol():
+    """ Test printing a Symbol to a aesara variable. """
+    xx = aesara_code_(x)
+    assert isinstance(xx, Variable)
+    assert xx.broadcastable == ()
+    assert xx.name == x.name
+
+    xx2 = aesara_code_(x, broadcastables={x: (False,)})
+    assert xx2.broadcastable == (False,)
+    assert xx2.name == x.name
+
+def test_MatrixSymbol():
+    """ Test printing a MatrixSymbol to a aesara variable. """
+    XX = aesara_code_(X)
+    assert isinstance(XX, TensorVariable)
+    assert XX.broadcastable == (False, False)
+
+@SKIP  # TODO - this is currently not checked but should be implemented
+def test_MatrixSymbol_wrong_dims():
+    """ Test MatrixSymbol with invalid broadcastable. """
+    bcs = [(), (False,), (True,), (True, False), (False, True,), (True, True)]
+    for bc in bcs:
+        with raises(ValueError):
+            aesara_code_(X, broadcastables={X: bc})
+
+def test_AppliedUndef():
+    """ Test printing AppliedUndef instance, which works similarly to Symbol. """
+    ftt = aesara_code_(f_t)
+    assert isinstance(ftt, TensorVariable)
+    assert ftt.broadcastable == ()
+    assert ftt.name == 'f_t'
+
+
+def test_add():
+    expr = x + y
+    comp = aesara_code_(expr)
+    assert comp.owner.op == aesara.tensor.add
+
+def test_trig():
+    assert theq(aesara_code_(sy.sin(x)), aet.sin(xt))
+    assert theq(aesara_code_(sy.tan(x)), aet.tan(xt))
+
+def test_many():
+    """ Test printing a complex expression with multiple symbols. """
+    expr = sy.exp(x**2 + sy.cos(y)) * sy.log(2*z)
+    comp = aesara_code_(expr)
+    expected = aet.exp(xt**2 + aet.cos(yt)) * aet.log(2*zt)
+    assert theq(comp, expected)
+
+
+def test_dtype():
+    """ Test specifying specific data types through the dtype argument. """
+    for dtype in ['float32', 'float64', 'int8', 'int16', 'int32', 'int64']:
+        assert aesara_code_(x, dtypes={x: dtype}).type.dtype == dtype
+
+    # "floatX" type
+    assert aesara_code_(x, dtypes={x: 'floatX'}).type.dtype in ('float32', 'float64')
+
+    # Type promotion
+    assert aesara_code_(x + 1, dtypes={x: 'float32'}).type.dtype == 'float32'
+    assert aesara_code_(x + y, dtypes={x: 'float64', y: 'float32'}).type.dtype == 'float64'
+
+
+def test_broadcastables():
+    """ Test the "broadcastables" argument when printing symbol-like objects. """
+
+    # No restrictions on shape
+    for s in [x, f_t]:
+        for bc in [(), (False,), (True,), (False, False), (True, False)]:
+            assert aesara_code_(s, broadcastables={s: bc}).broadcastable == bc
+
+    # TODO - matrix broadcasting?
+
+def test_broadcasting():
+    """ Test "broadcastable" attribute after applying element-wise binary op. """
+
+    expr = x + y
+
+    cases = [
+        [(), (), ()],
+        [(False,), (False,), (False,)],
+        [(True,), (False,), (False,)],
+        [(False, True), (False, False), (False, False)],
+        [(True, False), (False, False), (False, False)],
+    ]
+
+    for bc1, bc2, bc3 in cases:
+        comp = aesara_code_(expr, broadcastables={x: bc1, y: bc2})
+        assert comp.broadcastable == bc3
+
+
+def test_MatMul():
+    expr = X*Y*Z
+    expr_t = aesara_code_(expr)
+    assert isinstance(expr_t.owner.op, Dot)
+    assert theq(expr_t, Xt.dot(Yt).dot(Zt))
+
+def test_Transpose():
+    assert isinstance(aesara_code_(X.T).owner.op, DimShuffle)
+
+def test_MatAdd():
+    expr = X+Y+Z
+    assert isinstance(aesara_code_(expr).owner.op, Elemwise)
+
+
+def test_Rationals():
+    assert theq(aesara_code_(sy.Integer(2) / 3), true_divide(2, 3))
+    assert theq(aesara_code_(S.Half), true_divide(1, 2))
+
+def test_Integers():
+    assert aesara_code_(sy.Integer(3)) == 3
+
+def test_factorial():
+    n = sy.Symbol('n')
+    assert aesara_code_(sy.factorial(n))
+
+def test_Derivative():
+    with ignore_warnings(UserWarning):
+        simp = lambda expr: aesara_simplify(fgraph_of(expr))
+        assert theq(simp(aesara_code_(sy.Derivative(sy.sin(x), x, evaluate=False))),
+                    simp(aesara.grad(aet.sin(xt), xt)))
+
+
+def test_aesara_function_simple():
+    """ Test aesara_function() with single output. """
+    f = aesara_function_([x, y], [x+y])
+    assert f(2, 3) == 5
+
+def test_aesara_function_multi():
+    """ Test aesara_function() with multiple outputs. """
+    f = aesara_function_([x, y], [x+y, x-y])
+    o1, o2 = f(2, 3)
+    assert o1 == 5
+    assert o2 == -1
+
+def test_aesara_function_numpy():
+    """ Test aesara_function() vs Numpy implementation. """
+    f = aesara_function_([x, y], [x+y], dim=1,
+                         dtypes={x: 'float64', y: 'float64'})
+    assert np.linalg.norm(f([1, 2], [3, 4]) - np.asarray([4, 6])) < 1e-9
+
+    f = aesara_function_([x, y], [x+y], dtypes={x: 'float64', y: 'float64'},
+                         dim=1)
+    xx = np.arange(3).astype('float64')
+    yy = 2*np.arange(3).astype('float64')
+    assert np.linalg.norm(f(xx, yy) - 3*np.arange(3)) < 1e-9
+
+
+def test_aesara_function_matrix():
+    m = sy.Matrix([[x, y], [z, x + y + z]])
+    expected = np.array([[1.0, 2.0], [3.0, 1.0 + 2.0 + 3.0]])
+    f = aesara_function_([x, y, z], [m])
+    np.testing.assert_allclose(f(1.0, 2.0, 3.0), expected)
+    f = aesara_function_([x, y, z], [m], scalar=True)
+    np.testing.assert_allclose(f(1.0, 2.0, 3.0), expected)
+    f = aesara_function_([x, y, z], [m, m])
+    assert isinstance(f(1.0, 2.0, 3.0), type([]))
+    np.testing.assert_allclose(f(1.0, 2.0, 3.0)[0], expected)
+    np.testing.assert_allclose(f(1.0, 2.0, 3.0)[1], expected)
+
+def test_dim_handling():
+    assert dim_handling([x], dim=2) == {x: (False, False)}
+    assert dim_handling([x, y], dims={x: 1, y: 2}) == {x: (False, True),
+                                                       y: (False, False)}
+    assert dim_handling([x], broadcastables={x: (False,)}) == {x: (False,)}
+
+def test_aesara_function_kwargs():
+    """
+    Test passing additional kwargs from aesara_function() to aesara.function().
+    """
+    import numpy as np
+    f = aesara_function_([x, y, z], [x+y], dim=1, on_unused_input='ignore',
+            dtypes={x: 'float64', y: 'float64', z: 'float64'})
+    assert np.linalg.norm(f([1, 2], [3, 4], [0, 0]) - np.asarray([4, 6])) < 1e-9
+
+    f = aesara_function_([x, y, z], [x+y],
+                        dtypes={x: 'float64', y: 'float64', z: 'float64'},
+                        dim=1, on_unused_input='ignore')
+    xx = np.arange(3).astype('float64')
+    yy = 2*np.arange(3).astype('float64')
+    zz = 2*np.arange(3).astype('float64')
+    assert np.linalg.norm(f(xx, yy, zz) - 3*np.arange(3)) < 1e-9
+
+def test_aesara_function_scalar():
+    """ Test the "scalar" argument to aesara_function(). """
+    from aesara.compile.function.types import Function
+
+    args = [
+        ([x, y], [x + y], None, [0]),  # Single 0d output
+        ([X, Y], [X + Y], None, [2]),  # Single 2d output
+        ([x, y], [x + y], {x: 0, y: 1}, [1]),  # Single 1d output
+        ([x, y], [x + y, x - y], None, [0, 0]),  # Two 0d outputs
+        ([x, y, X, Y], [x + y, X + Y], None, [0, 2]),  # One 0d output, one 2d
+    ]
+
+    # Create and test functions with and without the scalar setting
+    for inputs, outputs, in_dims, out_dims in args:
+        for scalar in [False, True]:
+
+            f = aesara_function_(inputs, outputs, dims=in_dims, scalar=scalar)
+
+            # Check the aesara_function attribute is set whether wrapped or not
+            assert isinstance(f.aesara_function, Function)
+
+            # Feed in inputs of the appropriate size and get outputs
+            in_values = [
+                np.ones([1 if bc else 5 for bc in i.type.broadcastable])
+                for i in f.aesara_function.input_storage
+            ]
+            out_values = f(*in_values)
+            if not isinstance(out_values, list):
+                out_values = [out_values]
+
+            # Check output types and shapes
+            assert len(out_dims) == len(out_values)
+            for d, value in zip(out_dims, out_values):
+
+                if scalar and d == 0:
+                    # Should have been converted to a scalar value
+                    assert isinstance(value, np.number)
+
+                else:
+                    # Otherwise should be an array
+                    assert isinstance(value, np.ndarray)
+                    assert value.ndim == d
+
+def test_aesara_function_bad_kwarg():
+    """
+    Passing an unknown keyword argument to aesara_function() should raise an
+    exception.
+    """
+    raises(Exception, lambda : aesara_function_([x], [x+1], foobar=3))
+
+
+def test_slice():
+    assert aesara_code_(slice(1, 2, 3)) == slice(1, 2, 3)
+
+    def theq_slice(s1, s2):
+        for attr in ['start', 'stop', 'step']:
+            a1 = getattr(s1, attr)
+            a2 = getattr(s2, attr)
+            if a1 is None or a2 is None:
+                if not (a1 is None or a2 is None):
+                    return False
+            elif not theq(a1, a2):
+                return False
+        return True
+
+    dtypes = {x: 'int32', y: 'int32'}
+    assert theq_slice(aesara_code_(slice(x, y), dtypes=dtypes), slice(xt, yt))
+    assert theq_slice(aesara_code_(slice(1, x, 3), dtypes=dtypes), slice(1, xt, 3))
+
+def test_MatrixSlice():
+    cache = {}
+
+    n = sy.Symbol('n', integer=True)
+    X = sy.MatrixSymbol('X', n, n)
+
+    Y = X[1:2:3, 4:5:6]
+    Yt = aesara_code_(Y, cache=cache)
+
+    s = ScalarType('int64')
+    assert tuple(Yt.owner.op.idx_list) == (slice(s, s, s), slice(s, s, s))
+    assert Yt.owner.inputs[0] == aesara_code_(X, cache=cache)
+    # == doesn't work in Aesara like it does in SymPy. You have to use
+    # equals.
+    assert all(Yt.owner.inputs[i].data == i for i in range(1, 7))
+
+    k = sy.Symbol('k')
+    aesara_code_(k, dtypes={k: 'int32'})
+    start, stop, step = 4, k, 2
+    Y = X[start:stop:step]
+    Yt = aesara_code_(Y, dtypes={n: 'int32', k: 'int32'})
+    # assert Yt.owner.op.idx_list[0].stop == kt
+
+def test_BlockMatrix():
+    n = sy.Symbol('n', integer=True)
+    A, B, C, D = [sy.MatrixSymbol(name, n, n) for name in 'ABCD']
+    At, Bt, Ct, Dt = map(aesara_code_, (A, B, C, D))
+    Block = sy.BlockMatrix([[A, B], [C, D]])
+    Blockt = aesara_code_(Block)
+    solutions = [aet.join(0, aet.join(1, At, Bt), aet.join(1, Ct, Dt)),
+                 aet.join(1, aet.join(0, At, Ct), aet.join(0, Bt, Dt))]
+    assert any(theq(Blockt, solution) for solution in solutions)
+
+@SKIP
+def test_BlockMatrix_Inverse_execution():
+    k, n = 2, 4
+    dtype = 'float32'
+    A = sy.MatrixSymbol('A', n, k)
+    B = sy.MatrixSymbol('B', n, n)
+    inputs = A, B
+    output = B.I*A
+
+    cutsizes = {A: [(n//2, n//2), (k//2, k//2)],
+                B: [(n//2, n//2), (n//2, n//2)]}
+    cutinputs = [sy.blockcut(i, *cutsizes[i]) for i in inputs]
+    cutoutput = output.subs(dict(zip(inputs, cutinputs)))
+
+    dtypes = dict(zip(inputs, [dtype]*len(inputs)))
+    f = aesara_function_(inputs, [output], dtypes=dtypes, cache={})
+    fblocked = aesara_function_(inputs, [sy.block_collapse(cutoutput)],
+                                dtypes=dtypes, cache={})
+
+    ninputs = [np.random.rand(*x.shape).astype(dtype) for x in inputs]
+    ninputs = [np.arange(n*k).reshape(A.shape).astype(dtype),
+               np.eye(n).astype(dtype)]
+    ninputs[1] += np.ones(B.shape)*1e-5
+
+    assert np.allclose(f(*ninputs), fblocked(*ninputs), rtol=1e-5)
+
+def test_DenseMatrix():
+    from aesara.tensor.basic import Join
+
+    t = sy.Symbol('theta')
+    for MatrixType in [sy.Matrix, sy.ImmutableMatrix]:
+        X = MatrixType([[sy.cos(t), -sy.sin(t)], [sy.sin(t), sy.cos(t)]])
+        tX = aesara_code_(X)
+        assert isinstance(tX, TensorVariable)
+        assert isinstance(tX.owner.op, Join)
+
+
+def test_cache_basic():
+    """ Test single symbol-like objects are cached when printed by themselves. """
+
+    # Pairs of objects which should be considered equivalent with respect to caching
+    pairs = [
+        (x, sy.Symbol('x')),
+        (X, sy.MatrixSymbol('X', *X.shape)),
+        (f_t, sy.Function('f')(sy.Symbol('t'))),
+    ]
+
+    for s1, s2 in pairs:
+        cache = {}
+        st = aesara_code_(s1, cache=cache)
+
+        # Test hit with same instance
+        assert aesara_code_(s1, cache=cache) is st
+
+        # Test miss with same instance but new cache
+        assert aesara_code_(s1, cache={}) is not st
+
+        # Test hit with different but equivalent instance
+        assert aesara_code_(s2, cache=cache) is st
+
+def test_global_cache():
+    """ Test use of the global cache. """
+    from sympy.printing.aesaracode import global_cache
+
+    backup = dict(global_cache)
+    try:
+        # Temporarily empty global cache
+        global_cache.clear()
+
+        for s in [x, X, f_t]:
+            with warns_deprecated_sympy():
+                st = aesara_code(s)
+                assert aesara_code(s) is st
+
+    finally:
+        # Restore global cache
+        global_cache.update(backup)
+
+def test_cache_types_distinct():
+    """
+    Test that symbol-like objects of different types (Symbol, MatrixSymbol,
+    AppliedUndef) are distinguished by the cache even if they have the same
+    name.
+    """
+    symbols = [sy.Symbol('f_t'), sy.MatrixSymbol('f_t', 4, 4), f_t]
+
+    cache = {}  # Single shared cache
+    printed = {}
+
+    for s in symbols:
+        st = aesara_code_(s, cache=cache)
+        assert st not in printed.values()
+        printed[s] = st
+
+    # Check all printed objects are distinct
+    assert len(set(map(id, printed.values()))) == len(symbols)
+
+    # Check retrieving
+    for s, st in printed.items():
+        with warns_deprecated_sympy():
+            assert aesara_code(s, cache=cache) is st
+
+def test_symbols_are_created_once():
+    """
+    Test that a symbol is cached and reused when it appears in an expression
+    more than once.
+    """
+    expr = sy.Add(x, x, evaluate=False)
+    comp = aesara_code_(expr)
+
+    assert theq(comp, xt + xt)
+    assert not theq(comp, xt + aesara_code_(x))
+
+def test_cache_complex():
+    """
+    Test caching on a complicated expression with multiple symbols appearing
+    multiple times.
+    """
+    expr = x ** 2 + (y - sy.exp(x)) * sy.sin(z - x * y)
+    symbol_names = {s.name for s in expr.free_symbols}
+    expr_t = aesara_code_(expr)
+
+    # Iterate through variables in the Aesara computational graph that the
+    # printed expression depends on
+    seen = set()
+    for v in aesara.graph.basic.ancestors([expr_t]):
+        # Owner-less, non-constant variables should be our symbols
+        if v.owner is None and not isinstance(v, aesara.graph.basic.Constant):
+            # Check it corresponds to a symbol and appears only once
+            assert v.name in symbol_names
+            assert v.name not in seen
+            seen.add(v.name)
+
+    # Check all were present
+    assert seen == symbol_names
+
+
+def test_Piecewise():
+    # A piecewise linear
+    expr = sy.Piecewise((0, x<0), (x, x<2), (1, True))  # ___/III
+    result = aesara_code_(expr)
+    assert result.owner.op == aet.switch
+
+    expected = aet.switch(xt<0, 0, aet.switch(xt<2, xt, 1))
+    assert theq(result, expected)
+
+    expr = sy.Piecewise((x, x < 0))
+    result = aesara_code_(expr)
+    expected = aet.switch(xt < 0, xt, np.nan)
+    assert theq(result, expected)
+
+    expr = sy.Piecewise((0, sy.And(x>0, x<2)), \
+        (x, sy.Or(x>2, x<0)))
+    result = aesara_code_(expr)
+    expected = aet.switch(aet.and_(xt>0,xt<2), 0, \
+        aet.switch(aet.or_(xt>2, xt<0), xt, np.nan))
+    assert theq(result, expected)
+
+
+def test_Relationals():
+    assert theq(aesara_code_(sy.Eq(x, y)), aet.eq(xt, yt))
+    # assert theq(aesara_code_(sy.Ne(x, y)), aet.neq(xt, yt))  # TODO - implement
+    assert theq(aesara_code_(x > y), xt > yt)
+    assert theq(aesara_code_(x < y), xt < yt)
+    assert theq(aesara_code_(x >= y), xt >= yt)
+    assert theq(aesara_code_(x <= y), xt <= yt)
+
+
+def test_complexfunctions():
+    dtypes = {x:'complex128', y:'complex128'}
+    with warns_deprecated_sympy():
+        xt, yt = aesara_code(x, dtypes=dtypes), aesara_code(y, dtypes=dtypes)
+    from sympy.functions.elementary.complexes import conjugate
+    from aesara.tensor import as_tensor_variable as atv
+    from aesara.tensor import complex as cplx
+    with warns_deprecated_sympy():
+        assert theq(aesara_code(y*conjugate(x), dtypes=dtypes), yt*(xt.conj()))
+        assert theq(aesara_code((1+2j)*x), xt*(atv(1.0)+atv(2.0)*cplx(0,1)))
+
+
+def test_constantfunctions():
+    with warns_deprecated_sympy():
+        tf = aesara_function([],[1+1j])
+    assert(tf()==1+1j)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_c.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_c.py
new file mode 100644
index 0000000000000000000000000000000000000000..626e7b6f244ea3227b886cd897d327f5d7bf66ec
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_c.py
@@ -0,0 +1,888 @@
+from sympy.core import (
+    S, pi, oo, Symbol, symbols, Rational, Integer, Float, Function, Mod, GoldenRatio, EulerGamma, Catalan,
+    Lambda, Dummy, nan, Mul, Pow, UnevaluatedExpr
+)
+from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne)
+from sympy.functions import (
+    Abs, acos, acosh, asin, asinh, atan, atanh, atan2, ceiling, cos, cosh, erf,
+    erfc, exp, floor, gamma, log, loggamma, Max, Min, Piecewise, sign, sin, sinh,
+    sqrt, tan, tanh, fibonacci, lucas
+)
+from sympy.sets import Range
+from sympy.logic import ITE, Implies, Equivalent
+from sympy.codegen import For, aug_assign, Assignment
+from sympy.testing.pytest import raises, XFAIL
+from sympy.printing.codeprinter import PrintMethodNotImplementedError
+from sympy.printing.c import C89CodePrinter, C99CodePrinter, get_math_macros
+from sympy.codegen.ast import (
+    AddAugmentedAssignment, Element, Type, FloatType, Declaration, Pointer, Variable, value_const, pointer_const,
+    While, Scope, Print, FunctionPrototype, FunctionDefinition, FunctionCall, Return,
+    real, float32, float64, float80, float128, intc, Comment, CodeBlock, stderr, QuotedString
+)
+from sympy.codegen.cfunctions import expm1, log1p, exp2, log2, fma, log10, Cbrt, hypot, Sqrt, isnan, isinf
+from sympy.codegen.cnodes import restrict
+from sympy.utilities.lambdify import implemented_function
+from sympy.tensor import IndexedBase, Idx
+from sympy.matrices import Matrix, MatrixSymbol, SparseMatrix
+
+from sympy.printing.codeprinter import ccode
+
+x, y, z = symbols('x,y,z')
+
+
+def test_printmethod():
+    class fabs(Abs):
+        def _ccode(self, printer):
+            return "fabs(%s)" % printer._print(self.args[0])
+
+    assert ccode(fabs(x)) == "fabs(x)"
+
+
+def test_ccode_sqrt():
+    assert ccode(sqrt(x)) == "sqrt(x)"
+    assert ccode(x**0.5) == "sqrt(x)"
+    assert ccode(sqrt(x)) == "sqrt(x)"
+
+
+def test_ccode_Pow():
+    assert ccode(x**3) == "pow(x, 3)"
+    assert ccode(x**(y**3)) == "pow(x, pow(y, 3))"
+    g = implemented_function('g', Lambda(x, 2*x))
+    assert ccode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \
+        "pow(3.5*2*x, -x + pow(y, x))/(pow(x, 2) + y)"
+    assert ccode(x**-1.0) == '1.0/x'
+    assert ccode(x**Rational(2, 3)) == 'pow(x, 2.0/3.0)'
+    assert ccode(x**Rational(2, 3), type_aliases={real: float80}) == 'powl(x, 2.0L/3.0L)'
+    _cond_cfunc = [(lambda base, exp: exp.is_integer, "dpowi"),
+                   (lambda base, exp: not exp.is_integer, "pow")]
+    assert ccode(x**3, user_functions={'Pow': _cond_cfunc}) == 'dpowi(x, 3)'
+    assert ccode(x**0.5, user_functions={'Pow': _cond_cfunc}) == 'pow(x, 0.5)'
+    assert ccode(x**Rational(16, 5), user_functions={'Pow': _cond_cfunc}) == 'pow(x, 16.0/5.0)'
+    _cond_cfunc2 = [(lambda base, exp: base == 2, lambda base, exp: 'exp2(%s)' % exp),
+                    (lambda base, exp: base != 2, 'pow')]
+    # Related to gh-11353
+    assert ccode(2**x, user_functions={'Pow': _cond_cfunc2}) == 'exp2(x)'
+    assert ccode(x**2, user_functions={'Pow': _cond_cfunc2}) == 'pow(x, 2)'
+    # For issue 14160
+    assert ccode(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False),
+                                                evaluate=False)) == '-2*x/(y*y)'
+
+
+def test_ccode_Max():
+    # Test for gh-11926
+    assert ccode(Max(x,x*x),user_functions={"Max":"my_max", "Pow":"my_pow"}) == 'my_max(x, my_pow(x, 2))'
+
+
+def test_ccode_Min_performance():
+    #Shouldn't take more than a few seconds
+    big_min = Min(*symbols('a[0:50]'))
+    for curr_standard in ('c89', 'c99', 'c11'):
+        output = ccode(big_min, standard=curr_standard)
+        assert output.count('(') == output.count(')')
+
+
+def test_ccode_constants_mathh():
+    assert ccode(exp(1)) == "M_E"
+    assert ccode(pi) == "M_PI"
+    assert ccode(oo, standard='c89') == "HUGE_VAL"
+    assert ccode(-oo, standard='c89') == "-HUGE_VAL"
+    assert ccode(oo) == "INFINITY"
+    assert ccode(-oo, standard='c99') == "-INFINITY"
+    assert ccode(pi, type_aliases={real: float80}) == "M_PIl"
+
+
+def test_ccode_constants_other():
+    assert ccode(2*GoldenRatio) == "const double GoldenRatio = %s;\n2*GoldenRatio" % GoldenRatio.evalf(17)
+    assert ccode(
+        2*Catalan) == "const double Catalan = %s;\n2*Catalan" % Catalan.evalf(17)
+    assert ccode(2*EulerGamma) == "const double EulerGamma = %s;\n2*EulerGamma" % EulerGamma.evalf(17)
+
+
+def test_ccode_Rational():
+    assert ccode(Rational(3, 7)) == "3.0/7.0"
+    assert ccode(Rational(3, 7), type_aliases={real: float80}) == "3.0L/7.0L"
+    assert ccode(Rational(18, 9)) == "2"
+    assert ccode(Rational(3, -7)) == "-3.0/7.0"
+    assert ccode(Rational(3, -7), type_aliases={real: float80}) == "-3.0L/7.0L"
+    assert ccode(Rational(-3, -7)) == "3.0/7.0"
+    assert ccode(Rational(-3, -7), type_aliases={real: float80}) == "3.0L/7.0L"
+    assert ccode(x + Rational(3, 7)) == "x + 3.0/7.0"
+    assert ccode(x + Rational(3, 7), type_aliases={real: float80}) == "x + 3.0L/7.0L"
+    assert ccode(Rational(3, 7)*x) == "(3.0/7.0)*x"
+    assert ccode(Rational(3, 7)*x, type_aliases={real: float80}) == "(3.0L/7.0L)*x"
+
+
+def test_ccode_Integer():
+    assert ccode(Integer(67)) == "67"
+    assert ccode(Integer(-1)) == "-1"
+
+
+def test_ccode_functions():
+    assert ccode(sin(x) ** cos(x)) == "pow(sin(x), cos(x))"
+
+
+def test_ccode_inline_function():
+    x = symbols('x')
+    g = implemented_function('g', Lambda(x, 2*x))
+    assert ccode(g(x)) == "2*x"
+    g = implemented_function('g', Lambda(x, 2*x/Catalan))
+    assert ccode(
+        g(x)) == "const double Catalan = %s;\n2*x/Catalan" % Catalan.evalf(17)
+    A = IndexedBase('A')
+    i = Idx('i', symbols('n', integer=True))
+    g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x)))
+    assert ccode(g(A[i]), assign_to=A[i]) == (
+        "for (int i=0; i y"
+    assert ccode(Ge(x, y)) == "x >= y"
+
+
+def test_ccode_Piecewise():
+    expr = Piecewise((x, x < 1), (x**2, True))
+    assert ccode(expr) == (
+            "((x < 1) ? (\n"
+            "   x\n"
+            ")\n"
+            ": (\n"
+            "   pow(x, 2)\n"
+            "))")
+    assert ccode(expr, assign_to="c") == (
+            "if (x < 1) {\n"
+            "   c = x;\n"
+            "}\n"
+            "else {\n"
+            "   c = pow(x, 2);\n"
+            "}")
+    expr = Piecewise((x, x < 1), (x + 1, x < 2), (x**2, True))
+    assert ccode(expr) == (
+            "((x < 1) ? (\n"
+            "   x\n"
+            ")\n"
+            ": ((x < 2) ? (\n"
+            "   x + 1\n"
+            ")\n"
+            ": (\n"
+            "   pow(x, 2)\n"
+            ")))")
+    assert ccode(expr, assign_to='c') == (
+            "if (x < 1) {\n"
+            "   c = x;\n"
+            "}\n"
+            "else if (x < 2) {\n"
+            "   c = x + 1;\n"
+            "}\n"
+            "else {\n"
+            "   c = pow(x, 2);\n"
+            "}")
+    # Check that Piecewise without a True (default) condition error
+    expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0))
+    raises(ValueError, lambda: ccode(expr))
+
+
+def test_ccode_sinc():
+    from sympy.functions.elementary.trigonometric import sinc
+    expr = sinc(x)
+    assert ccode(expr) == (
+            "(((x != 0) ? (\n"
+            "   sin(x)/x\n"
+            ")\n"
+            ": (\n"
+            "   1\n"
+            ")))")
+
+
+def test_ccode_Piecewise_deep():
+    p = ccode(2*Piecewise((x, x < 1), (x + 1, x < 2), (x**2, True)))
+    assert p == (
+            "2*((x < 1) ? (\n"
+            "   x\n"
+            ")\n"
+            ": ((x < 2) ? (\n"
+            "   x + 1\n"
+            ")\n"
+            ": (\n"
+            "   pow(x, 2)\n"
+            ")))")
+    expr = x*y*z + x**2 + y**2 + Piecewise((0, x < 0.5), (1, True)) + cos(z) - 1
+    assert ccode(expr) == (
+            "pow(x, 2) + x*y*z + pow(y, 2) + ((x < 0.5) ? (\n"
+            "   0\n"
+            ")\n"
+            ": (\n"
+            "   1\n"
+            ")) + cos(z) - 1")
+    assert ccode(expr, assign_to='c') == (
+            "c = pow(x, 2) + x*y*z + pow(y, 2) + ((x < 0.5) ? (\n"
+            "   0\n"
+            ")\n"
+            ": (\n"
+            "   1\n"
+            ")) + cos(z) - 1;")
+
+
+def test_ccode_ITE():
+    expr = ITE(x < 1, y, z)
+    assert ccode(expr) == (
+            "((x < 1) ? (\n"
+            "   y\n"
+            ")\n"
+            ": (\n"
+            "   z\n"
+            "))")
+
+
+def test_ccode_settings():
+    raises(TypeError, lambda: ccode(sin(x), method="garbage"))
+
+
+def test_ccode_Indexed():
+    s, n, m, o = symbols('s n m o', integer=True)
+    i, j, k = Idx('i', n), Idx('j', m), Idx('k', o)
+
+    x = IndexedBase('x')[j]
+    A = IndexedBase('A')[i, j]
+    B = IndexedBase('B')[i, j, k]
+
+    p = C99CodePrinter()
+
+    assert p._print_Indexed(x) == 'x[j]'
+    assert p._print_Indexed(A) == 'A[%s]' % (m*i+j)
+    assert p._print_Indexed(B) == 'B[%s]' % (i*o*m+j*o+k)
+
+    A = IndexedBase('A', shape=(5,3))[i, j]
+    assert p._print_Indexed(A) == 'A[%s]' % (3*i + j)
+
+    A = IndexedBase('A', shape=(5,3), strides='F')[i, j]
+    assert ccode(A) == 'A[%s]' % (i + 5*j)
+
+    A = IndexedBase('A', shape=(29,29), strides=(1, s), offset=o)[i, j]
+    assert ccode(A) == 'A[o + s*j + i]'
+
+    Abase = IndexedBase('A', strides=(s, m, n), offset=o)
+    assert ccode(Abase[i, j, k]) == 'A[m*j + n*k + o + s*i]'
+    assert ccode(Abase[2, 3, k]) == 'A[3*m + n*k + o + 2*s]'
+
+
+def test_Element():
+    assert ccode(Element('x', 'ij')) == 'x[i][j]'
+    assert ccode(Element('x', 'ij', strides='kl', offset='o')) == 'x[i*k + j*l + o]'
+    assert ccode(Element('x', (3,))) == 'x[3]'
+    assert ccode(Element('x', (3,4,5))) == 'x[3][4][5]'
+
+
+def test_ccode_Indexed_without_looking_for_contraction():
+    len_y = 5
+    y = IndexedBase('y', shape=(len_y,))
+    x = IndexedBase('x', shape=(len_y,))
+    Dy = IndexedBase('Dy', shape=(len_y-1,))
+    i = Idx('i', len_y-1)
+    e = Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i]))
+    code0 = ccode(e.rhs, assign_to=e.lhs, contract=False)
+    assert code0 == 'Dy[i] = (y[%s] - y[i])/(x[%s] - x[i]);' % (i + 1, i + 1)
+
+
+def test_ccode_loops_matrix_vector():
+    n, m = symbols('n m', integer=True)
+    A = IndexedBase('A')
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i = Idx('i', m)
+    j = Idx('j', n)
+
+    s = (
+        'for (int i=0; i0), (y, True)), sin(z)])
+    A = MatrixSymbol('A', 3, 1)
+    assert ccode(mat, A) == (
+        "A[0] = x*y;\n"
+        "if (y > 0) {\n"
+        "   A[1] = x + 2;\n"
+        "}\n"
+        "else {\n"
+        "   A[1] = y;\n"
+        "}\n"
+        "A[2] = sin(z);")
+    # Test using MatrixElements in expressions
+    expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0]
+    assert ccode(expr) == (
+        "((x > 0) ? (\n"
+        "   2*A[2]\n"
+        ")\n"
+        ": (\n"
+        "   A[2]\n"
+        ")) + sin(A[1]) + A[0]")
+    # Test using MatrixElements in a Matrix
+    q = MatrixSymbol('q', 5, 1)
+    M = MatrixSymbol('M', 3, 3)
+    m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])],
+        [q[1,0] + q[2,0], q[3, 0], 5],
+        [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]])
+    assert ccode(m, M) == (
+        "M[0] = sin(q[1]);\n"
+        "M[1] = 0;\n"
+        "M[2] = cos(q[2]);\n"
+        "M[3] = q[1] + q[2];\n"
+        "M[4] = q[3];\n"
+        "M[5] = 5;\n"
+        "M[6] = 2*q[4]/q[1];\n"
+        "M[7] = sqrt(q[0]) + 4;\n"
+        "M[8] = 0;")
+
+
+def test_sparse_matrix():
+    # gh-15791
+    with raises(PrintMethodNotImplementedError):
+        ccode(SparseMatrix([[1, 2, 3]]))
+
+    assert 'Not supported in C' in C89CodePrinter({'strict': False}).doprint(SparseMatrix([[1, 2, 3]]))
+
+
+
+def test_ccode_reserved_words():
+    x, y = symbols('x, if')
+    with raises(ValueError):
+        ccode(y**2, error_on_reserved=True, standard='C99')
+    assert ccode(y**2) == 'pow(if_, 2)'
+    assert ccode(x * y**2, dereference=[y]) == 'pow((*if_), 2)*x'
+    assert ccode(y**2, reserved_word_suffix='_unreserved') == 'pow(if_unreserved, 2)'
+
+
+def test_ccode_sign():
+    expr1, ref1 = sign(x) * y, 'y*(((x) > 0) - ((x) < 0))'
+    expr2, ref2 = sign(cos(x)), '(((cos(x)) > 0) - ((cos(x)) < 0))'
+    expr3, ref3 = sign(2 * x + x**2) * x + x**2, 'pow(x, 2) + x*(((pow(x, 2) + 2*x) > 0) - ((pow(x, 2) + 2*x) < 0))'
+    assert ccode(expr1) == ref1
+    assert ccode(expr1, 'z') == 'z = %s;' % ref1
+    assert ccode(expr2) == ref2
+    assert ccode(expr3) == ref3
+
+def test_ccode_Assignment():
+    assert ccode(Assignment(x, y + z)) == 'x = y + z;'
+    assert ccode(aug_assign(x, '+', y + z)) == 'x += y + z;'
+
+
+def test_ccode_For():
+    f = For(x, Range(0, 10, 2), [aug_assign(y, '*', x)])
+    assert ccode(f) == ("for (x = 0; x < 10; x += 2) {\n"
+                        "   y *= x;\n"
+                        "}")
+
+def test_ccode_Max_Min():
+    assert ccode(Max(x, 0), standard='C89') == '((0 > x) ? 0 : x)'
+    assert ccode(Max(x, 0), standard='C99') == 'fmax(0, x)'
+    assert ccode(Min(x, 0, sqrt(x)), standard='c89') == (
+        '((0 < ((x < sqrt(x)) ? x : sqrt(x))) ? 0 : ((x < sqrt(x)) ? x : sqrt(x)))'
+    )
+
+def test_ccode_standard():
+    assert ccode(expm1(x), standard='c99') == 'expm1(x)'
+    assert ccode(nan, standard='c99') == 'NAN'
+    assert ccode(float('nan'), standard='c99') == 'NAN'
+
+
+def test_C89CodePrinter():
+    c89printer = C89CodePrinter()
+    assert c89printer.language == 'C'
+    assert c89printer.standard == 'C89'
+    assert 'void' in c89printer.reserved_words
+    assert 'template' not in c89printer.reserved_words
+    assert c89printer.doprint(log10(x)) == 'log10(x)'
+
+
+def test_C99CodePrinter():
+    assert C99CodePrinter().doprint(expm1(x)) == 'expm1(x)'
+    assert C99CodePrinter().doprint(log1p(x)) == 'log1p(x)'
+    assert C99CodePrinter().doprint(exp2(x)) == 'exp2(x)'
+    assert C99CodePrinter().doprint(log2(x)) == 'log2(x)'
+    assert C99CodePrinter().doprint(fma(x, y, -z)) == 'fma(x, y, -z)'
+    assert C99CodePrinter().doprint(log10(x)) == 'log10(x)'
+    assert C99CodePrinter().doprint(Cbrt(x)) == 'cbrt(x)'  # note Cbrt due to cbrt already taken.
+    assert C99CodePrinter().doprint(hypot(x, y)) == 'hypot(x, y)'
+    assert C99CodePrinter().doprint(loggamma(x)) == 'lgamma(x)'
+    assert C99CodePrinter().doprint(Max(x, 3, x**2)) == 'fmax(3, fmax(x, pow(x, 2)))'
+    assert C99CodePrinter().doprint(Min(x, 3)) == 'fmin(3, x)'
+    c99printer = C99CodePrinter()
+    assert c99printer.language == 'C'
+    assert c99printer.standard == 'C99'
+    assert 'restrict' in c99printer.reserved_words
+    assert 'using' not in c99printer.reserved_words
+
+
+@XFAIL
+def test_C99CodePrinter__precision_f80():
+    f80_printer = C99CodePrinter({"type_aliases": {real: float80}})
+    assert f80_printer.doprint(sin(x + Float('2.1'))) == 'sinl(x + 2.1L)'
+
+
+def test_C99CodePrinter__precision():
+    n = symbols('n', integer=True)
+    p = symbols('p', integer=True, positive=True)
+    f32_printer = C99CodePrinter({"type_aliases": {real: float32}})
+    f64_printer = C99CodePrinter({"type_aliases": {real: float64}})
+    f80_printer = C99CodePrinter({"type_aliases": {real: float80}})
+    assert f32_printer.doprint(sin(x+2.1)) == 'sinf(x + 2.1F)'
+    assert f64_printer.doprint(sin(x+2.1)) == 'sin(x + 2.1000000000000001)'
+    assert f80_printer.doprint(sin(x+Float('2.0'))) == 'sinl(x + 2.0L)'
+
+    for printer, suffix in zip([f32_printer, f64_printer, f80_printer], ['f', '', 'l']):
+        def check(expr, ref):
+            assert printer.doprint(expr) == ref.format(s=suffix, S=suffix.upper())
+        check(Abs(n), 'abs(n)')
+        check(Abs(x + 2.0), 'fabs{s}(x + 2.0{S})')
+        check(sin(x + 4.0)**cos(x - 2.0), 'pow{s}(sin{s}(x + 4.0{S}), cos{s}(x - 2.0{S}))')
+        check(exp(x*8.0), 'exp{s}(8.0{S}*x)')
+        check(exp2(x), 'exp2{s}(x)')
+        check(expm1(x*4.0), 'expm1{s}(4.0{S}*x)')
+        check(Mod(p, 2), 'p % 2')
+        check(Mod(2*p + 3, 3*p + 5, evaluate=False), '(2*p + 3) % (3*p + 5)')
+        check(Mod(x + 2.0, 3.0), 'fmod{s}(1.0{S}*x + 2.0{S}, 3.0{S})')
+        check(Mod(x, 2.0*x + 3.0), 'fmod{s}(1.0{S}*x, 2.0{S}*x + 3.0{S})')
+        check(log(x/2), 'log{s}((1.0{S}/2.0{S})*x)')
+        check(log10(3*x/2), 'log10{s}((3.0{S}/2.0{S})*x)')
+        check(log2(x*8.0), 'log2{s}(8.0{S}*x)')
+        check(log1p(x), 'log1p{s}(x)')
+        check(2**x, 'pow{s}(2, x)')
+        check(2.0**x, 'pow{s}(2.0{S}, x)')
+        check(x**3, 'pow{s}(x, 3)')
+        check(x**4.0, 'pow{s}(x, 4.0{S})')
+        check(sqrt(3+x), 'sqrt{s}(x + 3)')
+        check(Cbrt(x-2.0), 'cbrt{s}(x - 2.0{S})')
+        check(hypot(x, y), 'hypot{s}(x, y)')
+        check(sin(3.*x + 2.), 'sin{s}(3.0{S}*x + 2.0{S})')
+        check(cos(3.*x - 1.), 'cos{s}(3.0{S}*x - 1.0{S})')
+        check(tan(4.*y + 2.), 'tan{s}(4.0{S}*y + 2.0{S})')
+        check(asin(3.*x + 2.), 'asin{s}(3.0{S}*x + 2.0{S})')
+        check(acos(3.*x + 2.), 'acos{s}(3.0{S}*x + 2.0{S})')
+        check(atan(3.*x + 2.), 'atan{s}(3.0{S}*x + 2.0{S})')
+        check(atan2(3.*x, 2.*y), 'atan2{s}(3.0{S}*x, 2.0{S}*y)')
+
+        check(sinh(3.*x + 2.), 'sinh{s}(3.0{S}*x + 2.0{S})')
+        check(cosh(3.*x - 1.), 'cosh{s}(3.0{S}*x - 1.0{S})')
+        check(tanh(4.0*y + 2.), 'tanh{s}(4.0{S}*y + 2.0{S})')
+        check(asinh(3.*x + 2.), 'asinh{s}(3.0{S}*x + 2.0{S})')
+        check(acosh(3.*x + 2.), 'acosh{s}(3.0{S}*x + 2.0{S})')
+        check(atanh(3.*x + 2.), 'atanh{s}(3.0{S}*x + 2.0{S})')
+        check(erf(42.*x), 'erf{s}(42.0{S}*x)')
+        check(erfc(42.*x), 'erfc{s}(42.0{S}*x)')
+        check(gamma(x), 'tgamma{s}(x)')
+        check(loggamma(x), 'lgamma{s}(x)')
+
+        check(ceiling(x + 2.), "ceil{s}(x) + 2")
+        check(floor(x + 2.), "floor{s}(x) + 2")
+        check(fma(x, y, -z), 'fma{s}(x, y, -z)')
+        check(Max(x, 8.0, x**4.0), 'fmax{s}(8.0{S}, fmax{s}(x, pow{s}(x, 4.0{S})))')
+        check(Min(x, 2.0), 'fmin{s}(2.0{S}, x)')
+
+
+def test_get_math_macros():
+    macros = get_math_macros()
+    assert macros[exp(1)] == 'M_E'
+    assert macros[1/Sqrt(2)] == 'M_SQRT1_2'
+
+
+def test_ccode_Declaration():
+    i = symbols('i', integer=True)
+    var1 = Variable(i, type=Type.from_expr(i))
+    dcl1 = Declaration(var1)
+    assert ccode(dcl1) == 'int i'
+
+    var2 = Variable(x, type=float32, attrs={value_const})
+    dcl2a = Declaration(var2)
+    assert ccode(dcl2a) == 'const float x'
+    dcl2b = var2.as_Declaration(value=pi)
+    assert ccode(dcl2b) == 'const float x = M_PI'
+
+    var3 = Variable(y, type=Type('bool'))
+    dcl3 = Declaration(var3)
+    printer = C89CodePrinter()
+    assert 'stdbool.h' not in printer.headers
+    assert printer.doprint(dcl3) == 'bool y'
+    assert 'stdbool.h' in printer.headers
+
+    u = symbols('u', real=True)
+    ptr4 = Pointer.deduced(u, attrs={pointer_const, restrict})
+    dcl4 = Declaration(ptr4)
+    assert ccode(dcl4) == 'double * const restrict u'
+
+    var5 = Variable(x, Type('__float128'), attrs={value_const})
+    dcl5a = Declaration(var5)
+    assert ccode(dcl5a) == 'const __float128 x'
+    var5b = Variable(var5.symbol, var5.type, pi, attrs=var5.attrs)
+    dcl5b = Declaration(var5b)
+    assert ccode(dcl5b) == 'const __float128 x = M_PI'
+
+
+def test_C99CodePrinter_custom_type():
+    # We will look at __float128 (new in glibc 2.26)
+    f128 = FloatType('_Float128', float128.nbits, float128.nmant, float128.nexp)
+    p128 = C99CodePrinter({
+        "type_aliases": {real: f128},
+        "type_literal_suffixes": {f128: 'Q'},
+        "type_func_suffixes": {f128: 'f128'},
+        "type_math_macro_suffixes": {
+            real: 'f128',
+            f128: 'f128'
+        },
+        "type_macros": {
+            f128: ('__STDC_WANT_IEC_60559_TYPES_EXT__',)
+        }
+    })
+    assert p128.doprint(x) == 'x'
+    assert not p128.headers
+    assert not p128.libraries
+    assert not p128.macros
+    assert p128.doprint(2.0) == '2.0Q'
+    assert not p128.headers
+    assert not p128.libraries
+    assert p128.macros == {'__STDC_WANT_IEC_60559_TYPES_EXT__'}
+
+    assert p128.doprint(Rational(1, 2)) == '1.0Q/2.0Q'
+    assert p128.doprint(sin(x)) == 'sinf128(x)'
+    assert p128.doprint(cos(2., evaluate=False)) == 'cosf128(2.0Q)'
+    assert p128.doprint(x**-1.0) == '1.0Q/x'
+
+    var5 = Variable(x, f128, attrs={value_const})
+
+    dcl5a = Declaration(var5)
+    assert ccode(dcl5a) == 'const _Float128 x'
+    var5b = Variable(x, f128, pi, attrs={value_const})
+    dcl5b = Declaration(var5b)
+    assert p128.doprint(dcl5b) == 'const _Float128 x = M_PIf128'
+    var5b = Variable(x, f128, value=Catalan.evalf(38), attrs={value_const})
+    dcl5c = Declaration(var5b)
+    assert p128.doprint(dcl5c) == 'const _Float128 x = %sQ' % Catalan.evalf(f128.decimal_dig)
+
+
+def test_MatrixElement_printing():
+    # test cases for issue #11821
+    A = MatrixSymbol("A", 1, 3)
+    B = MatrixSymbol("B", 1, 3)
+    C = MatrixSymbol("C", 1, 3)
+
+    assert(ccode(A[0, 0]) == "A[0]")
+    assert(ccode(3 * A[0, 0]) == "3*A[0]")
+
+    F = C[0, 0].subs(C, A - B)
+    assert(ccode(F) == "(A - B)[0]")
+
+def test_ccode_math_macros():
+    assert ccode(z + exp(1)) == 'z + M_E'
+    assert ccode(z + log2(exp(1))) == 'z + M_LOG2E'
+    assert ccode(z + 1/log(2)) == 'z + M_LOG2E'
+    assert ccode(z + log(2)) == 'z + M_LN2'
+    assert ccode(z + log(10)) == 'z + M_LN10'
+    assert ccode(z + pi) == 'z + M_PI'
+    assert ccode(z + pi/2) == 'z + M_PI_2'
+    assert ccode(z + pi/4) == 'z + M_PI_4'
+    assert ccode(z + 1/pi) == 'z + M_1_PI'
+    assert ccode(z + 2/pi) == 'z + M_2_PI'
+    assert ccode(z + 2/sqrt(pi)) == 'z + M_2_SQRTPI'
+    assert ccode(z + 2/Sqrt(pi)) == 'z + M_2_SQRTPI'
+    assert ccode(z + sqrt(2)) == 'z + M_SQRT2'
+    assert ccode(z + Sqrt(2)) == 'z + M_SQRT2'
+    assert ccode(z + 1/sqrt(2)) == 'z + M_SQRT1_2'
+    assert ccode(z + 1/Sqrt(2)) == 'z + M_SQRT1_2'
+
+
+def test_ccode_Type():
+    assert ccode(Type('float')) == 'float'
+    assert ccode(intc) == 'int'
+
+
+def test_ccode_codegen_ast():
+    # Note that C only allows comments of the form /* ... */, double forward
+    # slash is not standard C, and some C compilers will grind to a halt upon
+    # encountering them.
+    assert ccode(Comment("this is a comment")) == "/* this is a comment */"  # not //
+    assert ccode(While(abs(x) > 1, [aug_assign(x, '-', 1)])) == (
+        'while (fabs(x) > 1) {\n'
+        '   x -= 1;\n'
+        '}'
+    )
+    assert ccode(Scope([AddAugmentedAssignment(x, 1)])) == (
+        '{\n'
+        '   x += 1;\n'
+        '}'
+    )
+    inp_x = Declaration(Variable(x, type=real))
+    assert ccode(FunctionPrototype(real, 'pwer', [inp_x])) == 'double pwer(double x)'
+    assert ccode(FunctionDefinition(real, 'pwer', [inp_x], [Assignment(x, x**2)])) == (
+        'double pwer(double x){\n'
+        '   x = pow(x, 2);\n'
+        '}'
+    )
+
+    # Elements of CodeBlock are formatted as statements:
+    block = CodeBlock(
+        x,
+        Print([x, y], "%d %d"),
+        Print([QuotedString('hello'), y], "%s %d", file=stderr),
+        FunctionCall('pwer', [x]),
+        Return(x),
+    )
+    assert ccode(block) == '\n'.join([
+        'x;',
+        'printf("%d %d", x, y);',
+        'fprintf(stderr, "%s %d", "hello", y);',
+        'pwer(x);',
+        'return x;',
+    ])
+
+def test_ccode_UnevaluatedExpr():
+    assert ccode(UnevaluatedExpr(y * x) + z) == "z + x*y"
+    assert ccode(UnevaluatedExpr(y + x) + z) == "z + (x + y)"  # gh-21955
+    w = symbols('w')
+    assert ccode(UnevaluatedExpr(y + x) + UnevaluatedExpr(z + w)) == "(w + z) + (x + y)"
+
+    p, q, r = symbols("p q r", real=True)
+    q_r = UnevaluatedExpr(q + r)
+    expr = abs(exp(p+q_r))
+    assert ccode(expr) == "exp(p + (q + r))"
+
+
+def test_ccode_array_like_containers():
+    assert ccode([2,3,4]) == "{2, 3, 4}"
+    assert ccode((2,3,4)) == "{2, 3, 4}"
+
+def test_ccode__isinf_isnan():
+    assert ccode(isinf(x)) == 'isinf(x)'
+    assert ccode(isnan(x)) == 'isnan(x)'
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_conventions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_conventions.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8f1fa8532f96130828b89d1ba5ba11fd5bed7a4
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_conventions.py
@@ -0,0 +1,116 @@
+# -*- coding: utf-8 -*-
+
+from sympy.core.function import (Derivative, Function)
+from sympy.core.numbers import oo
+from sympy.core.symbol import symbols
+from sympy.functions.elementary.exponential import exp
+from sympy.functions.elementary.trigonometric import cos
+from sympy.integrals.integrals import Integral
+from sympy.functions.special.bessel import besselj
+from sympy.functions.special.polynomials import legendre
+from sympy.functions.combinatorial.numbers import bell
+from sympy.printing.conventions import split_super_sub, requires_partial
+from sympy.testing.pytest import XFAIL
+
+def test_super_sub():
+    assert split_super_sub("beta_13_2") == ("beta", [], ["13", "2"])
+    assert split_super_sub("beta_132_20") == ("beta", [], ["132", "20"])
+    assert split_super_sub("beta_13") == ("beta", [], ["13"])
+    assert split_super_sub("x_a_b") == ("x", [], ["a", "b"])
+    assert split_super_sub("x_1_2_3") == ("x", [], ["1", "2", "3"])
+    assert split_super_sub("x_a_b1") == ("x", [], ["a", "b1"])
+    assert split_super_sub("x_a_1") == ("x", [], ["a", "1"])
+    assert split_super_sub("x_1_a") == ("x", [], ["1", "a"])
+    assert split_super_sub("x_1^aa") == ("x", ["aa"], ["1"])
+    assert split_super_sub("x_1__aa") == ("x", ["aa"], ["1"])
+    assert split_super_sub("x_11^a") == ("x", ["a"], ["11"])
+    assert split_super_sub("x_11__a") == ("x", ["a"], ["11"])
+    assert split_super_sub("x_a_b_c_d") == ("x", [], ["a", "b", "c", "d"])
+    assert split_super_sub("x_a_b^c^d") == ("x", ["c", "d"], ["a", "b"])
+    assert split_super_sub("x_a_b__c__d") == ("x", ["c", "d"], ["a", "b"])
+    assert split_super_sub("x_a^b_c^d") == ("x", ["b", "d"], ["a", "c"])
+    assert split_super_sub("x_a__b_c__d") == ("x", ["b", "d"], ["a", "c"])
+    assert split_super_sub("x^a^b_c_d") == ("x", ["a", "b"], ["c", "d"])
+    assert split_super_sub("x__a__b_c_d") == ("x", ["a", "b"], ["c", "d"])
+    assert split_super_sub("x^a^b^c^d") == ("x", ["a", "b", "c", "d"], [])
+    assert split_super_sub("x__a__b__c__d") == ("x", ["a", "b", "c", "d"], [])
+    assert split_super_sub("alpha_11") == ("alpha", [], ["11"])
+    assert split_super_sub("alpha_11_11") == ("alpha", [], ["11", "11"])
+    assert split_super_sub("w1") == ("w", [], ["1"])
+    assert split_super_sub("w𝟙") == ("w", [], ["𝟙"])
+    assert split_super_sub("w11") == ("w", [], ["11"])
+    assert split_super_sub("w𝟙𝟙") == ("w", [], ["𝟙𝟙"])
+    assert split_super_sub("w𝟙2𝟙") == ("w", [], ["𝟙2𝟙"])
+    assert split_super_sub("w1^a") == ("w", ["a"], ["1"])
+    assert split_super_sub("ω1") == ("ω", [], ["1"])
+    assert split_super_sub("ω11") == ("ω", [], ["11"])
+    assert split_super_sub("ω1^a") == ("ω", ["a"], ["1"])
+    assert split_super_sub("ω𝟙^α") == ("ω", ["α"], ["𝟙"])
+    assert split_super_sub("ω𝟙2^3α") == ("ω", ["3α"], ["𝟙2"])
+    assert split_super_sub("") == ("", [], [])
+
+
+def test_requires_partial():
+    x, y, z, t, nu = symbols('x y z t nu')
+    n = symbols('n', integer=True)
+
+    f = x * y
+    assert requires_partial(Derivative(f, x)) is True
+    assert requires_partial(Derivative(f, y)) is True
+
+    ## integrating out one of the variables
+    assert requires_partial(Derivative(Integral(exp(-x * y), (x, 0, oo)), y, evaluate=False)) is False
+
+    ## bessel function with smooth parameter
+    f = besselj(nu, x)
+    assert requires_partial(Derivative(f, x)) is True
+    assert requires_partial(Derivative(f, nu)) is True
+
+    ## bessel function with integer parameter
+    f = besselj(n, x)
+    assert requires_partial(Derivative(f, x)) is False
+    # this is not really valid (differentiating with respect to an integer)
+    # but there's no reason to use the partial derivative symbol there. make
+    # sure we don't throw an exception here, though
+    assert requires_partial(Derivative(f, n)) is False
+
+    ## bell polynomial
+    f = bell(n, x)
+    assert requires_partial(Derivative(f, x)) is False
+    # again, invalid
+    assert requires_partial(Derivative(f, n)) is False
+
+    ## legendre polynomial
+    f = legendre(0, x)
+    assert requires_partial(Derivative(f, x)) is False
+
+    f = legendre(n, x)
+    assert requires_partial(Derivative(f, x)) is False
+    # again, invalid
+    assert requires_partial(Derivative(f, n)) is False
+
+    f = x ** n
+    assert requires_partial(Derivative(f, x)) is False
+
+    assert requires_partial(Derivative(Integral((x*y) ** n * exp(-x * y), (x, 0, oo)), y, evaluate=False)) is False
+
+    # parametric equation
+    f = (exp(t), cos(t))
+    g = sum(f)
+    assert requires_partial(Derivative(g, t)) is False
+
+    f = symbols('f', cls=Function)
+    assert requires_partial(Derivative(f(x), x)) is False
+    assert requires_partial(Derivative(f(x), y)) is False
+    assert requires_partial(Derivative(f(x, y), x)) is True
+    assert requires_partial(Derivative(f(x, y), y)) is True
+    assert requires_partial(Derivative(f(x, y), z)) is True
+    assert requires_partial(Derivative(f(x, y), x, y)) is True
+
+@XFAIL
+def test_requires_partial_unspecified_variables():
+    x, y = symbols('x y')
+    # function of unspecified variables
+    f = symbols('f', cls=Function)
+    assert requires_partial(Derivative(f, x)) is False
+    assert requires_partial(Derivative(f, x, y)) is True
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_cupy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_cupy.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf111ec1623390a3dbbf489235d2ed387624a36c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_cupy.py
@@ -0,0 +1,56 @@
+from sympy.concrete.summations import Sum
+from sympy.functions.elementary.exponential import log
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.utilities.lambdify import lambdify
+from sympy.abc import x, i, a, b
+from sympy.codegen.numpy_nodes import logaddexp
+from sympy.printing.numpy import CuPyPrinter, _cupy_known_constants, _cupy_known_functions
+
+from sympy.testing.pytest import skip, raises
+from sympy.external import import_module
+
+cp = import_module('cupy')
+
+def test_cupy_print():
+    prntr = CuPyPrinter()
+    assert prntr.doprint(logaddexp(a, b)) == 'cupy.logaddexp(a, b)'
+    assert prntr.doprint(sqrt(x)) == 'cupy.sqrt(x)'
+    assert prntr.doprint(log(x)) == 'cupy.log(x)'
+    assert prntr.doprint("acos(x)") == 'cupy.arccos(x)'
+    assert prntr.doprint("exp(x)") == 'cupy.exp(x)'
+    assert prntr.doprint("Abs(x)") == 'abs(x)'
+
+def test_not_cupy_print():
+    prntr = CuPyPrinter()
+    with raises(NotImplementedError):
+        prntr.doprint("abcd(x)")
+
+def test_cupy_sum():
+    if not cp:
+        skip("CuPy not installed")
+
+    s = Sum(x ** i, (i, a, b))
+    f = lambdify((a, b, x), s, 'cupy')
+
+    a_, b_ = 0, 10
+    x_ = cp.linspace(-1, +1, 10)
+    assert cp.allclose(f(a_, b_, x_), sum(x_ ** i_ for i_ in range(a_, b_ + 1)))
+
+    s = Sum(i * x, (i, a, b))
+    f = lambdify((a, b, x), s, 'numpy')
+
+    a_, b_ = 0, 10
+    x_ = cp.linspace(-1, +1, 10)
+    assert cp.allclose(f(a_, b_, x_), sum(i_ * x_ for i_ in range(a_, b_ + 1)))
+
+def test_cupy_known_funcs_consts():
+    assert _cupy_known_constants['NaN'] == 'cupy.nan'
+    assert _cupy_known_constants['EulerGamma'] == 'cupy.euler_gamma'
+
+    assert _cupy_known_functions['acos'] == 'cupy.arccos'
+    assert _cupy_known_functions['log'] == 'cupy.log'
+
+def test_cupy_print_methods():
+    prntr = CuPyPrinter()
+    assert hasattr(prntr, '_print_acos')
+    assert hasattr(prntr, '_print_log')
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_cxx.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_cxx.py
new file mode 100644
index 0000000000000000000000000000000000000000..d84ec75cbf0eeb60a1176b9cb3b401a3384454e7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_cxx.py
@@ -0,0 +1,86 @@
+from sympy.core.numbers import Float, Integer, Rational
+from sympy.core.symbol import symbols
+from sympy.functions import beta, Ei, zeta, Max, Min, sqrt, riemann_xi, frac
+from sympy.printing.cxx import CXX98CodePrinter, CXX11CodePrinter, CXX17CodePrinter, cxxcode
+from sympy.codegen.cfunctions import log1p
+
+
+x, y, u, v = symbols('x y u v')
+
+
+def test_CXX98CodePrinter():
+    assert CXX98CodePrinter().doprint(Max(x, 3)) in ('std::max(x, 3)', 'std::max(3, x)')
+    assert CXX98CodePrinter().doprint(Min(x, 3, sqrt(x))) == 'std::min(3, std::min(x, std::sqrt(x)))'
+    cxx98printer = CXX98CodePrinter()
+    assert cxx98printer.language == 'C++'
+    assert cxx98printer.standard == 'C++98'
+    assert 'template' in cxx98printer.reserved_words
+    assert 'alignas' not in cxx98printer.reserved_words
+
+
+def test_CXX11CodePrinter():
+    assert CXX11CodePrinter().doprint(log1p(x)) == 'std::log1p(x)'
+
+    cxx11printer = CXX11CodePrinter()
+    assert cxx11printer.language == 'C++'
+    assert cxx11printer.standard == 'C++11'
+    assert 'operator' in cxx11printer.reserved_words
+    assert 'noexcept' in cxx11printer.reserved_words
+    assert 'concept' not in cxx11printer.reserved_words
+
+
+def test_subclass_print_method():
+    class MyPrinter(CXX11CodePrinter):
+        def _print_log1p(self, expr):
+            return 'my_library::log1p(%s)' % ', '.join(map(self._print, expr.args))
+
+    assert MyPrinter().doprint(log1p(x)) == 'my_library::log1p(x)'
+
+
+def test_subclass_print_method__ns():
+    class MyPrinter(CXX11CodePrinter):
+        _ns = 'my_library::'
+
+    p = CXX11CodePrinter()
+    myp = MyPrinter()
+
+    assert p.doprint(log1p(x)) == 'std::log1p(x)'
+    assert myp.doprint(log1p(x)) == 'my_library::log1p(x)'
+
+
+def test_CXX17CodePrinter():
+    assert CXX17CodePrinter().doprint(beta(x, y)) == 'std::beta(x, y)'
+    assert CXX17CodePrinter().doprint(Ei(x)) == 'std::expint(x)'
+    assert CXX17CodePrinter().doprint(zeta(x)) == 'std::riemann_zeta(x)'
+
+    # Automatic rewrite
+    assert CXX17CodePrinter().doprint(frac(x)) == '(x - std::floor(x))'
+    assert CXX17CodePrinter().doprint(riemann_xi(x)) == '((1.0/2.0)*std::pow(M_PI, -1.0/2.0*x)*x*(x - 1)*std::tgamma((1.0/2.0)*x)*std::riemann_zeta(x))'
+
+
+def test_cxxcode():
+    assert sorted(cxxcode(sqrt(x)*.5).split('*')) == sorted(['0.5', 'std::sqrt(x)'])
+
+def test_cxxcode_nested_minmax():
+    assert cxxcode(Max(Min(x, y), Min(u, v))) \
+        == 'std::max(std::min(u, v), std::min(x, y))'
+    assert cxxcode(Min(Max(x, y), Max(u, v))) \
+        == 'std::min(std::max(u, v), std::max(x, y))'
+
+def test_subclass_Integer_Float():
+    class MyPrinter(CXX17CodePrinter):
+        def _print_Integer(self, arg):
+            return 'bigInt("%s")' % super()._print_Integer(arg)
+
+        def _print_Float(self, arg):
+            rat = Rational(arg)
+            return 'bigFloat(%s, %s)' % (
+                self._print(Integer(rat.p)),
+                self._print(Integer(rat.q))
+            )
+
+    p = MyPrinter()
+    for i in range(13):
+        assert p.doprint(i) == 'bigInt("%d")' % i
+    assert p.doprint(Float(0.5)) == 'bigFloat(bigInt("1"), bigInt("2"))'
+    assert p.doprint(x**-1.0) == 'bigFloat(bigInt("1"), bigInt("1"))/x'
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_dot.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_dot.py
new file mode 100644
index 0000000000000000000000000000000000000000..6213e237fb7aac6460a956b4c9fc1f7c8710fec6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_dot.py
@@ -0,0 +1,134 @@
+from sympy.printing.dot import (purestr, styleof, attrprint, dotnode,
+        dotedges, dotprint)
+from sympy.core.basic import Basic
+from sympy.core.expr import Expr
+from sympy.core.numbers import (Float, Integer)
+from sympy.core.singleton import S
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.printing.repr import srepr
+from sympy.abc import x
+
+
+def test_purestr():
+    assert purestr(Symbol('x')) == "Symbol('x')"
+    assert purestr(Basic(S(1), S(2))) == "Basic(Integer(1), Integer(2))"
+    assert purestr(Float(2)) == "Float('2.0', precision=53)"
+
+    assert purestr(Symbol('x'), with_args=True) == ("Symbol('x')", ())
+    assert purestr(Basic(S(1), S(2)), with_args=True) == \
+            ('Basic(Integer(1), Integer(2))', ('Integer(1)', 'Integer(2)'))
+    assert purestr(Float(2), with_args=True) == \
+        ("Float('2.0', precision=53)", ())
+
+
+def test_styleof():
+    styles = [(Basic, {'color': 'blue', 'shape': 'ellipse'}),
+              (Expr,  {'color': 'black'})]
+    assert styleof(Basic(S(1)), styles) == {'color': 'blue', 'shape': 'ellipse'}
+
+    assert styleof(x + 1, styles) == {'color': 'black', 'shape': 'ellipse'}
+
+
+def test_attrprint():
+    assert attrprint({'color': 'blue', 'shape': 'ellipse'}) == \
+           '"color"="blue", "shape"="ellipse"'
+
+def test_dotnode():
+
+    assert dotnode(x, repeat=False) == \
+        '"Symbol(\'x\')" ["color"="black", "label"="x", "shape"="ellipse"];'
+    assert dotnode(x+2, repeat=False) == \
+        '"Add(Integer(2), Symbol(\'x\'))" ' \
+        '["color"="black", "label"="Add", "shape"="ellipse"];', \
+        dotnode(x+2,repeat=0)
+
+    assert dotnode(x + x**2, repeat=False) == \
+        '"Add(Symbol(\'x\'), Pow(Symbol(\'x\'), Integer(2)))" ' \
+        '["color"="black", "label"="Add", "shape"="ellipse"];'
+    assert dotnode(x + x**2, repeat=True) == \
+        '"Add(Symbol(\'x\'), Pow(Symbol(\'x\'), Integer(2)))_()" ' \
+        '["color"="black", "label"="Add", "shape"="ellipse"];'
+
+def test_dotedges():
+    assert sorted(dotedges(x+2, repeat=False)) == [
+        '"Add(Integer(2), Symbol(\'x\'))" -> "Integer(2)";',
+        '"Add(Integer(2), Symbol(\'x\'))" -> "Symbol(\'x\')";'
+    ]
+    assert sorted(dotedges(x + 2, repeat=True)) == [
+        '"Add(Integer(2), Symbol(\'x\'))_()" -> "Integer(2)_(0,)";',
+        '"Add(Integer(2), Symbol(\'x\'))_()" -> "Symbol(\'x\')_(1,)";'
+    ]
+
+def test_dotprint():
+    text = dotprint(x+2, repeat=False)
+    assert all(e in text for e in dotedges(x+2, repeat=False))
+    assert all(
+        n in text for n in [dotnode(expr, repeat=False)
+        for expr in (x, Integer(2), x+2)])
+    assert 'digraph' in text
+
+    text = dotprint(x+x**2, repeat=False)
+    assert all(e in text for e in dotedges(x+x**2, repeat=False))
+    assert all(
+        n in text for n in [dotnode(expr, repeat=False)
+        for expr in (x, Integer(2), x**2)])
+    assert 'digraph' in text
+
+    text = dotprint(x+x**2, repeat=True)
+    assert all(e in text for e in dotedges(x+x**2, repeat=True))
+    assert all(
+        n in text for n in [dotnode(expr, pos=())
+        for expr in [x + x**2]])
+
+    text = dotprint(x**x, repeat=True)
+    assert all(e in text for e in dotedges(x**x, repeat=True))
+    assert all(
+        n in text for n in [dotnode(x, pos=(0,)), dotnode(x, pos=(1,))])
+    assert 'digraph' in text
+
+def test_dotprint_depth():
+    text = dotprint(3*x+2, depth=1)
+    assert dotnode(3*x+2) in text
+    assert dotnode(x) not in text
+    text = dotprint(3*x+2)
+    assert "depth" not in text
+
+def test_Matrix_and_non_basics():
+    from sympy.matrices.expressions.matexpr import MatrixSymbol
+    n = Symbol('n')
+    assert dotprint(MatrixSymbol('X', n, n)) == \
+"""digraph{
+
+# Graph style
+"ordering"="out"
+"rankdir"="TD"
+
+#########
+# Nodes #
+#########
+
+"MatrixSymbol(Str('X'), Symbol('n'), Symbol('n'))_()" ["color"="black", "label"="MatrixSymbol", "shape"="ellipse"];
+"Str('X')_(0,)" ["color"="blue", "label"="X", "shape"="ellipse"];
+"Symbol('n')_(1,)" ["color"="black", "label"="n", "shape"="ellipse"];
+"Symbol('n')_(2,)" ["color"="black", "label"="n", "shape"="ellipse"];
+
+#########
+# Edges #
+#########
+
+"MatrixSymbol(Str('X'), Symbol('n'), Symbol('n'))_()" -> "Str('X')_(0,)";
+"MatrixSymbol(Str('X'), Symbol('n'), Symbol('n'))_()" -> "Symbol('n')_(1,)";
+"MatrixSymbol(Str('X'), Symbol('n'), Symbol('n'))_()" -> "Symbol('n')_(2,)";
+}"""
+
+
+def test_labelfunc():
+    text = dotprint(x + 2, labelfunc=srepr)
+    assert "Symbol('x')" in text
+    assert "Integer(2)" in text
+
+
+def test_commutative():
+    x, y = symbols('x y', commutative=False)
+    assert dotprint(x + y) == dotprint(y + x)
+    assert dotprint(x*y) != dotprint(y*x)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_fortran.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_fortran.py
new file mode 100644
index 0000000000000000000000000000000000000000..c28a1ea16dcf2157b58d763286428dccc1944b71
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_fortran.py
@@ -0,0 +1,854 @@
+from sympy.core.add import Add
+from sympy.core.expr import Expr
+from sympy.core.function import (Function, Lambda, diff)
+from sympy.core.mod import Mod
+from sympy.core import (Catalan, EulerGamma, GoldenRatio)
+from sympy.core.numbers import (E, Float, I, Integer, Rational, pi)
+from sympy.core.relational import Eq
+from sympy.core.singleton import S
+from sympy.core.symbol import (Dummy, symbols)
+from sympy.functions.combinatorial.factorials import factorial
+from sympy.functions.elementary.complexes import (conjugate, sign)
+from sympy.functions.elementary.exponential import (exp, log)
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.functions.elementary.trigonometric import (atan2, cos, sin)
+from sympy.functions.special.gamma_functions import gamma
+from sympy.integrals.integrals import Integral
+from sympy.sets.fancysets import Range
+
+from sympy.codegen import For, Assignment, aug_assign
+from sympy.codegen.ast import Declaration, Variable, float32, float64, \
+        value_const, real, bool_, While, FunctionPrototype, FunctionDefinition, \
+        integer, Return, Element
+from sympy.core.expr import UnevaluatedExpr
+from sympy.core.relational import Relational
+from sympy.logic.boolalg import And, Or, Not, Equivalent, Xor
+from sympy.matrices import Matrix, MatrixSymbol
+from sympy.printing.fortran import fcode, FCodePrinter
+from sympy.tensor import IndexedBase, Idx
+from sympy.tensor.array.expressions import ArraySymbol, ArrayElement
+from sympy.utilities.lambdify import implemented_function
+from sympy.testing.pytest import raises
+
+
+def test_UnevaluatedExpr():
+    p, q, r = symbols("p q r", real=True)
+    q_r = UnevaluatedExpr(q + r)
+    expr = abs(exp(p+q_r))
+    assert fcode(expr, source_format="free") == "exp(p + (q + r))"
+    x, y, z = symbols("x y z")
+    y_z = UnevaluatedExpr(y + z)
+    expr2 = abs(exp(x+y_z))
+    assert fcode(expr2, human=False)[2].lstrip() == "exp(re(x) + re(y + z))"
+    assert fcode(expr2, user_functions={"re": "realpart"}).lstrip() == "exp(realpart(x) + realpart(y + z))"
+
+
+def test_printmethod():
+    x = symbols('x')
+
+    class nint(Function):
+        def _fcode(self, printer):
+            return "nint(%s)" % printer._print(self.args[0])
+    assert fcode(nint(x)) == "      nint(x)"
+
+
+def test_fcode_sign():  #issue 12267
+    x=symbols('x')
+    y=symbols('y', integer=True)
+    z=symbols('z', complex=True)
+    assert fcode(sign(x), standard=95, source_format='free') == "merge(0d0, dsign(1d0, x), x == 0d0)"
+    assert fcode(sign(y), standard=95, source_format='free') == "merge(0, isign(1, y), y == 0)"
+    assert fcode(sign(z), standard=95, source_format='free') == "merge(cmplx(0d0, 0d0), z/abs(z), abs(z) == 0d0)"
+    raises(NotImplementedError, lambda: fcode(sign(x)))
+
+
+def test_fcode_Pow():
+    x, y = symbols('x,y')
+    n = symbols('n', integer=True)
+
+    assert fcode(x**3) == "      x**3"
+    assert fcode(x**(y**3)) == "      x**(y**3)"
+    assert fcode(1/(sin(x)*3.5)**(x - y**x)/(x**2 + y)) == \
+        "      (3.5d0*sin(x))**(-x + y**x)/(x**2 + y)"
+    assert fcode(sqrt(x)) == '      sqrt(x)'
+    assert fcode(sqrt(n)) == '      sqrt(dble(n))'
+    assert fcode(x**0.5) == '      sqrt(x)'
+    assert fcode(sqrt(x)) == '      sqrt(x)'
+    assert fcode(sqrt(10)) == '      sqrt(10.0d0)'
+    assert fcode(x**-1.0) == '      1d0/x'
+    assert fcode(x**-2.0, 'y', source_format='free') == 'y = x**(-2.0d0)'  # 2823
+    assert fcode(x**Rational(3, 7)) == '      x**(3.0d0/7.0d0)'
+
+
+def test_fcode_Rational():
+    x = symbols('x')
+    assert fcode(Rational(3, 7)) == "      3.0d0/7.0d0"
+    assert fcode(Rational(18, 9)) == "      2"
+    assert fcode(Rational(3, -7)) == "      -3.0d0/7.0d0"
+    assert fcode(Rational(-3, -7)) == "      3.0d0/7.0d0"
+    assert fcode(x + Rational(3, 7)) == "      x + 3.0d0/7.0d0"
+    assert fcode(Rational(3, 7)*x) == "      (3.0d0/7.0d0)*x"
+
+
+def test_fcode_Integer():
+    assert fcode(Integer(67)) == "      67"
+    assert fcode(Integer(-1)) == "      -1"
+
+
+def test_fcode_Float():
+    assert fcode(Float(42.0)) == "      42.0000000000000d0"
+    assert fcode(Float(-1e20)) == "      -1.00000000000000d+20"
+
+
+def test_fcode_functions():
+    x, y = symbols('x,y')
+    assert fcode(sin(x) ** cos(y)) == "      sin(x)**cos(y)"
+    raises(NotImplementedError, lambda: fcode(Mod(x, y), standard=66))
+    raises(NotImplementedError, lambda: fcode(x % y, standard=66))
+    raises(NotImplementedError, lambda: fcode(Mod(x, y), standard=77))
+    raises(NotImplementedError, lambda: fcode(x % y, standard=77))
+    for standard in [90, 95, 2003, 2008]:
+        assert fcode(Mod(x, y), standard=standard) == "      modulo(x, y)"
+        assert fcode(x % y, standard=standard) == "      modulo(x, y)"
+
+
+def test_case():
+    ob = FCodePrinter()
+    x,x_,x__,y,X,X_,Y = symbols('x,x_,x__,y,X,X_,Y')
+    assert fcode(exp(x_) + sin(x*y) + cos(X*Y)) == \
+                        '      exp(x_) + sin(x*y) + cos(X__*Y_)'
+    assert fcode(exp(x__) + 2*x*Y*X_**Rational(7, 2)) == \
+                        '      2*X_**(7.0d0/2.0d0)*Y*x + exp(x__)'
+    assert fcode(exp(x_) + sin(x*y) + cos(X*Y), name_mangling=False) == \
+                        '      exp(x_) + sin(x*y) + cos(X*Y)'
+    assert fcode(x - cos(X), name_mangling=False) == '      x - cos(X)'
+    assert ob.doprint(X*sin(x) + x_, assign_to='me') == '      me = X*sin(x_) + x__'
+    assert ob.doprint(X*sin(x), assign_to='mu') == '      mu = X*sin(x_)'
+    assert ob.doprint(x_, assign_to='ad') == '      ad = x__'
+    n, m = symbols('n,m', integer=True)
+    A = IndexedBase('A')
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i = Idx('i', m)
+    I = Idx('I', n)
+    assert fcode(A[i, I]*x[I], assign_to=y[i], source_format='free') == (
+                                            "do i = 1, m\n"
+                                            "   y(i) = 0\n"
+                                            "end do\n"
+                                            "do i = 1, m\n"
+                                            "   do I_ = 1, n\n"
+                                            "      y(i) = A(i, I_)*x(I_) + y(i)\n"
+                                            "   end do\n"
+                                            "end do" )
+
+
+#issue 6814
+def test_fcode_functions_with_integers():
+    x= symbols('x')
+    log10_17 = log(10).evalf(17)
+    loglog10_17 = '0.8340324452479558d0'
+    assert fcode(x * log(10)) == "      x*%sd0" % log10_17
+    assert fcode(x * log(10)) == "      x*%sd0" % log10_17
+    assert fcode(x * log(S(10))) == "      x*%sd0" % log10_17
+    assert fcode(log(S(10))) == "      %sd0" % log10_17
+    assert fcode(exp(10)) == "      %sd0" % exp(10).evalf(17)
+    assert fcode(x * log(log(10))) == "      x*%s" % loglog10_17
+    assert fcode(x * log(log(S(10)))) == "      x*%s" % loglog10_17
+
+
+def test_fcode_NumberSymbol():
+    prec = 17
+    p = FCodePrinter()
+    assert fcode(Catalan) == '      parameter (Catalan = %sd0)\n      Catalan' % Catalan.evalf(prec)
+    assert fcode(EulerGamma) == '      parameter (EulerGamma = %sd0)\n      EulerGamma' % EulerGamma.evalf(prec)
+    assert fcode(E) == '      parameter (E = %sd0)\n      E' % E.evalf(prec)
+    assert fcode(GoldenRatio) == '      parameter (GoldenRatio = %sd0)\n      GoldenRatio' % GoldenRatio.evalf(prec)
+    assert fcode(pi) == '      parameter (pi = %sd0)\n      pi' % pi.evalf(prec)
+    assert fcode(
+        pi, precision=5) == '      parameter (pi = %sd0)\n      pi' % pi.evalf(5)
+    assert fcode(Catalan, human=False) == ({
+        (Catalan, p._print(Catalan.evalf(prec)))}, set(), '      Catalan')
+    assert fcode(EulerGamma, human=False) == ({(EulerGamma, p._print(
+        EulerGamma.evalf(prec)))}, set(), '      EulerGamma')
+    assert fcode(E, human=False) == (
+        {(E, p._print(E.evalf(prec)))}, set(), '      E')
+    assert fcode(GoldenRatio, human=False) == ({(GoldenRatio, p._print(
+        GoldenRatio.evalf(prec)))}, set(), '      GoldenRatio')
+    assert fcode(pi, human=False) == (
+        {(pi, p._print(pi.evalf(prec)))}, set(), '      pi')
+    assert fcode(pi, precision=5, human=False) == (
+        {(pi, p._print(pi.evalf(5)))}, set(), '      pi')
+
+
+def test_fcode_complex():
+    assert fcode(I) == "      cmplx(0,1)"
+    x = symbols('x')
+    assert fcode(4*I) == "      cmplx(0,4)"
+    assert fcode(3 + 4*I) == "      cmplx(3,4)"
+    assert fcode(3 + 4*I + x) == "      cmplx(3,4) + x"
+    assert fcode(I*x) == "      cmplx(0,1)*x"
+    assert fcode(3 + 4*I - x) == "      cmplx(3,4) - x"
+    x = symbols('x', imaginary=True)
+    assert fcode(5*x) == "      5*x"
+    assert fcode(I*x) == "      cmplx(0,1)*x"
+    assert fcode(3 + x) == "      x + 3"
+
+
+def test_implicit():
+    x, y = symbols('x,y')
+    assert fcode(sin(x)) == "      sin(x)"
+    assert fcode(atan2(x, y)) == "      atan2(x, y)"
+    assert fcode(conjugate(x)) == "      conjg(x)"
+
+
+def test_not_fortran():
+    x = symbols('x')
+    g = Function('g')
+    with raises(NotImplementedError):
+        fcode(gamma(x))
+    assert fcode(Integral(sin(x)), strict=False) == "C     Not supported in Fortran:\nC     Integral\n      Integral(sin(x), x)"
+    with raises(NotImplementedError):
+        fcode(g(x))
+
+
+def test_user_functions():
+    x = symbols('x')
+    assert fcode(sin(x), user_functions={"sin": "zsin"}) == "      zsin(x)"
+    x = symbols('x')
+    assert fcode(
+        gamma(x), user_functions={"gamma": "mygamma"}) == "      mygamma(x)"
+    g = Function('g')
+    assert fcode(g(x), user_functions={"g": "great"}) == "      great(x)"
+    n = symbols('n', integer=True)
+    assert fcode(
+        factorial(n), user_functions={"factorial": "fct"}) == "      fct(n)"
+
+
+def test_inline_function():
+    x = symbols('x')
+    g = implemented_function('g', Lambda(x, 2*x))
+    assert fcode(g(x)) == "      2*x"
+    g = implemented_function('g', Lambda(x, 2*pi/x))
+    assert fcode(g(x)) == (
+        "      parameter (pi = %sd0)\n"
+        "      2*pi/x"
+    ) % pi.evalf(17)
+    A = IndexedBase('A')
+    i = Idx('i', symbols('n', integer=True))
+    g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x)))
+    assert fcode(g(A[i]), assign_to=A[i]) == (
+        "      do i = 1, n\n"
+        "         A(i) = (A(i) + 1)*(A(i) + 2)*A(i)\n"
+        "      end do"
+    )
+
+
+def test_assign_to():
+    x = symbols('x')
+    assert fcode(sin(x), assign_to="s") == "      s = sin(x)"
+
+
+def test_line_wrapping():
+    x, y = symbols('x,y')
+    assert fcode(((x + y)**10).expand(), assign_to="var") == (
+        "      var = x**10 + 10*x**9*y + 45*x**8*y**2 + 120*x**7*y**3 + 210*x**6*\n"
+        "     @ y**4 + 252*x**5*y**5 + 210*x**4*y**6 + 120*x**3*y**7 + 45*x**2*y\n"
+        "     @ **8 + 10*x*y**9 + y**10"
+    )
+    e = [x**i for i in range(11)]
+    assert fcode(Add(*e)) == (
+        "      x**10 + x**9 + x**8 + x**7 + x**6 + x**5 + x**4 + x**3 + x**2 + x\n"
+        "     @ + 1"
+    )
+
+
+def test_fcode_precedence():
+    x, y = symbols("x y")
+    assert fcode(And(x < y, y < x + 1), source_format="free") == \
+        "x < y .and. y < x + 1"
+    assert fcode(Or(x < y, y < x + 1), source_format="free") == \
+        "x < y .or. y < x + 1"
+    assert fcode(Xor(x < y, y < x + 1, evaluate=False),
+        source_format="free") == "x < y .neqv. y < x + 1"
+    assert fcode(Equivalent(x < y, y < x + 1), source_format="free") == \
+        "x < y .eqv. y < x + 1"
+
+
+def test_fcode_Logical():
+    x, y, z = symbols("x y z")
+    # unary Not
+    assert fcode(Not(x), source_format="free") == ".not. x"
+    # binary And
+    assert fcode(And(x, y), source_format="free") == "x .and. y"
+    assert fcode(And(x, Not(y)), source_format="free") == "x .and. .not. y"
+    assert fcode(And(Not(x), y), source_format="free") == "y .and. .not. x"
+    assert fcode(And(Not(x), Not(y)), source_format="free") == \
+        ".not. x .and. .not. y"
+    assert fcode(Not(And(x, y), evaluate=False), source_format="free") == \
+        ".not. (x .and. y)"
+    # binary Or
+    assert fcode(Or(x, y), source_format="free") == "x .or. y"
+    assert fcode(Or(x, Not(y)), source_format="free") == "x .or. .not. y"
+    assert fcode(Or(Not(x), y), source_format="free") == "y .or. .not. x"
+    assert fcode(Or(Not(x), Not(y)), source_format="free") == \
+        ".not. x .or. .not. y"
+    assert fcode(Not(Or(x, y), evaluate=False), source_format="free") == \
+        ".not. (x .or. y)"
+    # mixed And/Or
+    assert fcode(And(Or(y, z), x), source_format="free") == "x .and. (y .or. z)"
+    assert fcode(And(Or(z, x), y), source_format="free") == "y .and. (x .or. z)"
+    assert fcode(And(Or(x, y), z), source_format="free") == "z .and. (x .or. y)"
+    assert fcode(Or(And(y, z), x), source_format="free") == "x .or. y .and. z"
+    assert fcode(Or(And(z, x), y), source_format="free") == "y .or. x .and. z"
+    assert fcode(Or(And(x, y), z), source_format="free") == "z .or. x .and. y"
+    # trinary And
+    assert fcode(And(x, y, z), source_format="free") == "x .and. y .and. z"
+    assert fcode(And(x, y, Not(z)), source_format="free") == \
+        "x .and. y .and. .not. z"
+    assert fcode(And(x, Not(y), z), source_format="free") == \
+        "x .and. z .and. .not. y"
+    assert fcode(And(Not(x), y, z), source_format="free") == \
+        "y .and. z .and. .not. x"
+    assert fcode(Not(And(x, y, z), evaluate=False), source_format="free") == \
+        ".not. (x .and. y .and. z)"
+    # trinary Or
+    assert fcode(Or(x, y, z), source_format="free") == "x .or. y .or. z"
+    assert fcode(Or(x, y, Not(z)), source_format="free") == \
+        "x .or. y .or. .not. z"
+    assert fcode(Or(x, Not(y), z), source_format="free") == \
+        "x .or. z .or. .not. y"
+    assert fcode(Or(Not(x), y, z), source_format="free") == \
+        "y .or. z .or. .not. x"
+    assert fcode(Not(Or(x, y, z), evaluate=False), source_format="free") == \
+        ".not. (x .or. y .or. z)"
+
+
+def test_fcode_Xlogical():
+    x, y, z = symbols("x y z")
+    # binary Xor
+    assert fcode(Xor(x, y, evaluate=False), source_format="free") == \
+        "x .neqv. y"
+    assert fcode(Xor(x, Not(y), evaluate=False), source_format="free") == \
+        "x .neqv. .not. y"
+    assert fcode(Xor(Not(x), y, evaluate=False), source_format="free") == \
+        "y .neqv. .not. x"
+    assert fcode(Xor(Not(x), Not(y), evaluate=False),
+        source_format="free") == ".not. x .neqv. .not. y"
+    assert fcode(Not(Xor(x, y, evaluate=False), evaluate=False),
+        source_format="free") == ".not. (x .neqv. y)"
+    # binary Equivalent
+    assert fcode(Equivalent(x, y), source_format="free") == "x .eqv. y"
+    assert fcode(Equivalent(x, Not(y)), source_format="free") == \
+        "x .eqv. .not. y"
+    assert fcode(Equivalent(Not(x), y), source_format="free") == \
+        "y .eqv. .not. x"
+    assert fcode(Equivalent(Not(x), Not(y)), source_format="free") == \
+        ".not. x .eqv. .not. y"
+    assert fcode(Not(Equivalent(x, y), evaluate=False),
+        source_format="free") == ".not. (x .eqv. y)"
+    # mixed And/Equivalent
+    assert fcode(Equivalent(And(y, z), x), source_format="free") == \
+        "x .eqv. y .and. z"
+    assert fcode(Equivalent(And(z, x), y), source_format="free") == \
+        "y .eqv. x .and. z"
+    assert fcode(Equivalent(And(x, y), z), source_format="free") == \
+        "z .eqv. x .and. y"
+    assert fcode(And(Equivalent(y, z), x), source_format="free") == \
+        "x .and. (y .eqv. z)"
+    assert fcode(And(Equivalent(z, x), y), source_format="free") == \
+        "y .and. (x .eqv. z)"
+    assert fcode(And(Equivalent(x, y), z), source_format="free") == \
+        "z .and. (x .eqv. y)"
+    # mixed Or/Equivalent
+    assert fcode(Equivalent(Or(y, z), x), source_format="free") == \
+        "x .eqv. y .or. z"
+    assert fcode(Equivalent(Or(z, x), y), source_format="free") == \
+        "y .eqv. x .or. z"
+    assert fcode(Equivalent(Or(x, y), z), source_format="free") == \
+        "z .eqv. x .or. y"
+    assert fcode(Or(Equivalent(y, z), x), source_format="free") == \
+        "x .or. (y .eqv. z)"
+    assert fcode(Or(Equivalent(z, x), y), source_format="free") == \
+        "y .or. (x .eqv. z)"
+    assert fcode(Or(Equivalent(x, y), z), source_format="free") == \
+        "z .or. (x .eqv. y)"
+    # mixed Xor/Equivalent
+    assert fcode(Equivalent(Xor(y, z, evaluate=False), x),
+        source_format="free") == "x .eqv. (y .neqv. z)"
+    assert fcode(Equivalent(Xor(z, x, evaluate=False), y),
+        source_format="free") == "y .eqv. (x .neqv. z)"
+    assert fcode(Equivalent(Xor(x, y, evaluate=False), z),
+        source_format="free") == "z .eqv. (x .neqv. y)"
+    assert fcode(Xor(Equivalent(y, z), x, evaluate=False),
+        source_format="free") == "x .neqv. (y .eqv. z)"
+    assert fcode(Xor(Equivalent(z, x), y, evaluate=False),
+        source_format="free") == "y .neqv. (x .eqv. z)"
+    assert fcode(Xor(Equivalent(x, y), z, evaluate=False),
+        source_format="free") == "z .neqv. (x .eqv. y)"
+    # mixed And/Xor
+    assert fcode(Xor(And(y, z), x, evaluate=False), source_format="free") == \
+        "x .neqv. y .and. z"
+    assert fcode(Xor(And(z, x), y, evaluate=False), source_format="free") == \
+        "y .neqv. x .and. z"
+    assert fcode(Xor(And(x, y), z, evaluate=False), source_format="free") == \
+        "z .neqv. x .and. y"
+    assert fcode(And(Xor(y, z, evaluate=False), x), source_format="free") == \
+        "x .and. (y .neqv. z)"
+    assert fcode(And(Xor(z, x, evaluate=False), y), source_format="free") == \
+        "y .and. (x .neqv. z)"
+    assert fcode(And(Xor(x, y, evaluate=False), z), source_format="free") == \
+        "z .and. (x .neqv. y)"
+    # mixed Or/Xor
+    assert fcode(Xor(Or(y, z), x, evaluate=False), source_format="free") == \
+        "x .neqv. y .or. z"
+    assert fcode(Xor(Or(z, x), y, evaluate=False), source_format="free") == \
+        "y .neqv. x .or. z"
+    assert fcode(Xor(Or(x, y), z, evaluate=False), source_format="free") == \
+        "z .neqv. x .or. y"
+    assert fcode(Or(Xor(y, z, evaluate=False), x), source_format="free") == \
+        "x .or. (y .neqv. z)"
+    assert fcode(Or(Xor(z, x, evaluate=False), y), source_format="free") == \
+        "y .or. (x .neqv. z)"
+    assert fcode(Or(Xor(x, y, evaluate=False), z), source_format="free") == \
+        "z .or. (x .neqv. y)"
+    # trinary Xor
+    assert fcode(Xor(x, y, z, evaluate=False), source_format="free") == \
+        "x .neqv. y .neqv. z"
+    assert fcode(Xor(x, y, Not(z), evaluate=False), source_format="free") == \
+        "x .neqv. y .neqv. .not. z"
+    assert fcode(Xor(x, Not(y), z, evaluate=False), source_format="free") == \
+        "x .neqv. z .neqv. .not. y"
+    assert fcode(Xor(Not(x), y, z, evaluate=False), source_format="free") == \
+        "y .neqv. z .neqv. .not. x"
+
+
+def test_fcode_Relational():
+    x, y = symbols("x y")
+    assert fcode(Relational(x, y, "=="), source_format="free") == "x == y"
+    assert fcode(Relational(x, y, "!="), source_format="free") == "x /= y"
+    assert fcode(Relational(x, y, ">="), source_format="free") == "x >= y"
+    assert fcode(Relational(x, y, "<="), source_format="free") == "x <= y"
+    assert fcode(Relational(x, y, ">"), source_format="free") == "x > y"
+    assert fcode(Relational(x, y, "<"), source_format="free") == "x < y"
+
+
+def test_fcode_Piecewise():
+    x = symbols('x')
+    expr = Piecewise((x, x < 1), (x**2, True))
+    # Check that inline conditional (merge) fails if standard isn't 95+
+    raises(NotImplementedError, lambda: fcode(expr))
+    code = fcode(expr, standard=95)
+    expected = "      merge(x, x**2, x < 1)"
+    assert code == expected
+    assert fcode(Piecewise((x, x < 1), (x**2, True)), assign_to="var") == (
+        "      if (x < 1) then\n"
+        "         var = x\n"
+        "      else\n"
+        "         var = x**2\n"
+        "      end if"
+    )
+    a = cos(x)/x
+    b = sin(x)/x
+    for i in range(10):
+        a = diff(a, x)
+        b = diff(b, x)
+    expected = (
+        "      if (x < 0) then\n"
+        "         weird_name = -cos(x)/x + 10*sin(x)/x**2 + 90*cos(x)/x**3 - 720*\n"
+        "     @ sin(x)/x**4 - 5040*cos(x)/x**5 + 30240*sin(x)/x**6 + 151200*cos(x\n"
+        "     @ )/x**7 - 604800*sin(x)/x**8 - 1814400*cos(x)/x**9 + 3628800*sin(x\n"
+        "     @ )/x**10 + 3628800*cos(x)/x**11\n"
+        "      else\n"
+        "         weird_name = -sin(x)/x - 10*cos(x)/x**2 + 90*sin(x)/x**3 + 720*\n"
+        "     @ cos(x)/x**4 - 5040*sin(x)/x**5 - 30240*cos(x)/x**6 + 151200*sin(x\n"
+        "     @ )/x**7 + 604800*cos(x)/x**8 - 1814400*sin(x)/x**9 - 3628800*cos(x\n"
+        "     @ )/x**10 + 3628800*sin(x)/x**11\n"
+        "      end if"
+    )
+    code = fcode(Piecewise((a, x < 0), (b, True)), assign_to="weird_name")
+    assert code == expected
+    code = fcode(Piecewise((x, x < 1), (x**2, x > 1), (sin(x), True)), standard=95)
+    expected = "      merge(x, merge(x**2, sin(x), x > 1), x < 1)"
+    assert code == expected
+    # Check that Piecewise without a True (default) condition error
+    expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0))
+    raises(ValueError, lambda: fcode(expr))
+
+
+def test_wrap_fortran():
+    #   "########################################################################"
+    printer = FCodePrinter()
+    lines = [
+        "C     This is a long comment on a single line that must be wrapped properly to produce nice output",
+        "      this = is + a + long + and + nasty + fortran + statement + that * must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement +  that * must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement +   that * must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement +   that*must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement +    that*must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement +     that*must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement +  that**must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement +   that**must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement +    that**must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement +     that**must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement(that)/must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran +     statement(that)/must + be + wrapped + properly",
+    ]
+    wrapped_lines = printer._wrap_fortran(lines)
+    expected_lines = [
+        "C     This is a long comment on a single line that must be wrapped",
+        "C     properly to produce nice output",
+        "      this = is + a + long + and + nasty + fortran + statement + that *",
+        "     @ must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement +  that *",
+        "     @ must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement +   that",
+        "     @ * must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement + that*",
+        "     @ must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement +   that*",
+        "     @ must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement +    that",
+        "     @ *must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement +",
+        "     @ that*must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement + that**",
+        "     @ must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement +  that**",
+        "     @ must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement +   that",
+        "     @ **must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement +    that",
+        "     @ **must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement +",
+        "     @ that**must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran + statement(that)/",
+        "     @ must + be + wrapped + properly",
+        "      this = is + a + long + and + nasty + fortran +     statement(that)",
+        "     @ /must + be + wrapped + properly",
+    ]
+    for line in wrapped_lines:
+        assert len(line) <= 72
+    for w, e in zip(wrapped_lines, expected_lines):
+        assert w == e
+    assert len(wrapped_lines) == len(expected_lines)
+
+
+def test_wrap_fortran_keep_d0():
+    printer = FCodePrinter()
+    lines = [
+        '      this_variable_is_very_long_because_we_try_to_test_line_break=1.0d0',
+        '      this_variable_is_very_long_because_we_try_to_test_line_break =1.0d0',
+        '      this_variable_is_very_long_because_we_try_to_test_line_break  = 1.0d0',
+        '      this_variable_is_very_long_because_we_try_to_test_line_break   = 1.0d0',
+        '      this_variable_is_very_long_because_we_try_to_test_line_break    = 1.0d0',
+        '      this_variable_is_very_long_because_we_try_to_test_line_break = 10.0d0'
+    ]
+    expected = [
+        '      this_variable_is_very_long_because_we_try_to_test_line_break=1.0d0',
+        '      this_variable_is_very_long_because_we_try_to_test_line_break =',
+        '     @ 1.0d0',
+        '      this_variable_is_very_long_because_we_try_to_test_line_break  =',
+        '     @ 1.0d0',
+        '      this_variable_is_very_long_because_we_try_to_test_line_break   =',
+        '     @ 1.0d0',
+        '      this_variable_is_very_long_because_we_try_to_test_line_break    =',
+        '     @ 1.0d0',
+        '      this_variable_is_very_long_because_we_try_to_test_line_break =',
+        '     @ 10.0d0'
+    ]
+    assert printer._wrap_fortran(lines) == expected
+
+
+def test_settings():
+    raises(TypeError, lambda: fcode(S(4), method="garbage"))
+
+
+def test_free_form_code_line():
+    x, y = symbols('x,y')
+    assert fcode(cos(x) + sin(y), source_format='free') == "sin(y) + cos(x)"
+
+
+def test_free_form_continuation_line():
+    x, y = symbols('x,y')
+    result = fcode(((cos(x) + sin(y))**(7)).expand(), source_format='free')
+    expected = (
+        'sin(y)**7 + 7*sin(y)**6*cos(x) + 21*sin(y)**5*cos(x)**2 + 35*sin(y)**4* &\n'
+        '      cos(x)**3 + 35*sin(y)**3*cos(x)**4 + 21*sin(y)**2*cos(x)**5 + 7* &\n'
+        '      sin(y)*cos(x)**6 + cos(x)**7'
+    )
+    assert result == expected
+
+
+def test_free_form_comment_line():
+    printer = FCodePrinter({'source_format': 'free'})
+    lines = [ "! This is a long comment on a single line that must be wrapped properly to produce nice output"]
+    expected = [
+        '! This is a long comment on a single line that must be wrapped properly',
+        '! to produce nice output']
+    assert printer._wrap_fortran(lines) == expected
+
+
+def test_loops():
+    n, m = symbols('n,m', integer=True)
+    A = IndexedBase('A')
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i = Idx('i', m)
+    j = Idx('j', n)
+
+    expected = (
+        'do i = 1, m\n'
+        '   y(i) = 0\n'
+        'end do\n'
+        'do i = 1, m\n'
+        '   do j = 1, n\n'
+        '      y(i) = %(rhs)s\n'
+        '   end do\n'
+        'end do'
+    )
+
+    code = fcode(A[i, j]*x[j], assign_to=y[i], source_format='free')
+    assert (code == expected % {'rhs': 'y(i) + A(i, j)*x(j)'} or
+            code == expected % {'rhs': 'y(i) + x(j)*A(i, j)'} or
+            code == expected % {'rhs': 'x(j)*A(i, j) + y(i)'} or
+            code == expected % {'rhs': 'A(i, j)*x(j) + y(i)'})
+
+
+def test_dummy_loops():
+    i, m = symbols('i m', integer=True, cls=Dummy)
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i = Idx(i, m)
+
+    expected = (
+        'do i_%(icount)i = 1, m_%(mcount)i\n'
+        '   y(i_%(icount)i) = x(i_%(icount)i)\n'
+        'end do'
+    ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index}
+    code = fcode(x[i], assign_to=y[i], source_format='free')
+    assert code == expected
+
+
+def test_fcode_Indexed_without_looking_for_contraction():
+    len_y = 5
+    y = IndexedBase('y', shape=(len_y,))
+    x = IndexedBase('x', shape=(len_y,))
+    Dy = IndexedBase('Dy', shape=(len_y-1,))
+    i = Idx('i', len_y-1)
+    e=Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i]))
+    code0 = fcode(e.rhs, assign_to=e.lhs, contract=False)
+    assert code0.endswith('Dy(i) = (y(i + 1) - y(i))/(x(i + 1) - x(i))')
+
+
+def test_element_like_objects():
+    len_y = 5
+    y = ArraySymbol('y', shape=(len_y,))
+    x = ArraySymbol('x', shape=(len_y,))
+    Dy = ArraySymbol('Dy', shape=(len_y-1,))
+    i = Idx('i', len_y-1)
+    e=Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i]))
+    code0 = fcode(Assignment(e.lhs, e.rhs))
+    assert code0.endswith('Dy(i) = (y(i + 1) - y(i))/(x(i + 1) - x(i))')
+
+    class ElementExpr(Element, Expr):
+        pass
+
+    e = e.subs((a, ElementExpr(a.name, a.indices)) for a in e.atoms(ArrayElement)  )
+    e=Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i]))
+    code0 = fcode(Assignment(e.lhs, e.rhs))
+    assert code0.endswith('Dy(i) = (y(i + 1) - y(i))/(x(i + 1) - x(i))')
+
+
+def test_derived_classes():
+    class MyFancyFCodePrinter(FCodePrinter):
+        _default_settings = FCodePrinter._default_settings.copy()
+
+    printer = MyFancyFCodePrinter()
+    x = symbols('x')
+    assert printer.doprint(sin(x), "bork") == "      bork = sin(x)"
+
+
+def test_indent():
+    codelines = (
+        'subroutine test(a)\n'
+        'integer :: a, i, j\n'
+        '\n'
+        'do\n'
+        'do \n'
+        'do j = 1, 5\n'
+        'if (a>b) then\n'
+        'if(b>0) then\n'
+        'a = 3\n'
+        'donot_indent_me = 2\n'
+        'do_not_indent_me_either = 2\n'
+        'ifIam_indented_something_went_wrong = 2\n'
+        'if_I_am_indented_something_went_wrong = 2\n'
+        'end should not be unindented here\n'
+        'end if\n'
+        'endif\n'
+        'end do\n'
+        'end do\n'
+        'enddo\n'
+        'end subroutine\n'
+        '\n'
+        'subroutine test2(a)\n'
+        'integer :: a\n'
+        'do\n'
+        'a = a + 1\n'
+        'end do \n'
+        'end subroutine\n'
+    )
+    expected = (
+        'subroutine test(a)\n'
+        'integer :: a, i, j\n'
+        '\n'
+        'do\n'
+        '   do \n'
+        '      do j = 1, 5\n'
+        '         if (a>b) then\n'
+        '            if(b>0) then\n'
+        '               a = 3\n'
+        '               donot_indent_me = 2\n'
+        '               do_not_indent_me_either = 2\n'
+        '               ifIam_indented_something_went_wrong = 2\n'
+        '               if_I_am_indented_something_went_wrong = 2\n'
+        '               end should not be unindented here\n'
+        '            end if\n'
+        '         endif\n'
+        '      end do\n'
+        '   end do\n'
+        'enddo\n'
+        'end subroutine\n'
+        '\n'
+        'subroutine test2(a)\n'
+        'integer :: a\n'
+        'do\n'
+        '   a = a + 1\n'
+        'end do \n'
+        'end subroutine\n'
+    )
+    p = FCodePrinter({'source_format': 'free'})
+    result = p.indent_code(codelines)
+    assert result == expected
+
+def test_Matrix_printing():
+    x, y, z = symbols('x,y,z')
+    # Test returning a Matrix
+    mat = Matrix([x*y, Piecewise((2 + x, y>0), (y, True)), sin(z)])
+    A = MatrixSymbol('A', 3, 1)
+    assert fcode(mat, A) == (
+        "      A(1, 1) = x*y\n"
+        "      if (y > 0) then\n"
+        "         A(2, 1) = x + 2\n"
+        "      else\n"
+        "         A(2, 1) = y\n"
+        "      end if\n"
+        "      A(3, 1) = sin(z)")
+    # Test using MatrixElements in expressions
+    expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0]
+    assert fcode(expr, standard=95) == (
+        "      merge(2*A(3, 1), A(3, 1), x > 0) + sin(A(2, 1)) + A(1, 1)")
+    # Test using MatrixElements in a Matrix
+    q = MatrixSymbol('q', 5, 1)
+    M = MatrixSymbol('M', 3, 3)
+    m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])],
+        [q[1,0] + q[2,0], q[3, 0], 5],
+        [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]])
+    assert fcode(m, M) == (
+        "      M(1, 1) = sin(q(2, 1))\n"
+        "      M(2, 1) = q(2, 1) + q(3, 1)\n"
+        "      M(3, 1) = 2*q(5, 1)/q(2, 1)\n"
+        "      M(1, 2) = 0\n"
+        "      M(2, 2) = q(4, 1)\n"
+        "      M(3, 2) = sqrt(q(1, 1)) + 4\n"
+        "      M(1, 3) = cos(q(3, 1))\n"
+        "      M(2, 3) = 5\n"
+        "      M(3, 3) = 0")
+
+
+def test_fcode_For():
+    x, y = symbols('x y')
+
+    f = For(x, Range(0, 10, 2), [Assignment(y, x * y)])
+    sol = fcode(f)
+    assert sol == ("      do x = 0, 9, 2\n"
+                   "         y = x*y\n"
+                   "      end do")
+
+
+def test_fcode_Declaration():
+    def check(expr, ref, **kwargs):
+        assert fcode(expr, standard=95, source_format='free', **kwargs) == ref
+
+    i = symbols('i', integer=True)
+    var1 = Variable.deduced(i)
+    dcl1 = Declaration(var1)
+    check(dcl1, "integer*4 :: i")
+
+
+    x, y = symbols('x y')
+    var2 = Variable(x, float32, value=42, attrs={value_const})
+    dcl2b = Declaration(var2)
+    check(dcl2b, 'real*4, parameter :: x = 42')
+
+    var3 = Variable(y, type=bool_)
+    dcl3 = Declaration(var3)
+    check(dcl3, 'logical :: y')
+
+    check(float32, "real*4")
+    check(float64, "real*8")
+    check(real, "real*4", type_aliases={real: float32})
+    check(real, "real*8", type_aliases={real: float64})
+
+
+def test_MatrixElement_printing():
+    # test cases for issue #11821
+    A = MatrixSymbol("A", 1, 3)
+    B = MatrixSymbol("B", 1, 3)
+    C = MatrixSymbol("C", 1, 3)
+
+    assert(fcode(A[0, 0]) == "      A(1, 1)")
+    assert(fcode(3 * A[0, 0]) == "      3*A(1, 1)")
+
+    F = C[0, 0].subs(C, A - B)
+    assert(fcode(F) == "      (A - B)(1, 1)")
+
+
+def test_aug_assign():
+    x = symbols('x')
+    assert fcode(aug_assign(x, '+', 1), source_format='free') == 'x = x + 1'
+
+
+def test_While():
+    x = symbols('x')
+    assert fcode(While(abs(x) > 1, [aug_assign(x, '-', 1)]), source_format='free') == (
+        'do while (abs(x) > 1)\n'
+        '   x = x - 1\n'
+        'end do'
+    )
+
+
+def test_FunctionPrototype_print():
+    x = symbols('x')
+    n = symbols('n', integer=True)
+    vx = Variable(x, type=real)
+    vn = Variable(n, type=integer)
+    fp1 = FunctionPrototype(real, 'power', [vx, vn])
+    # Should be changed to proper test once multi-line generation is working
+    # see https://github.com/sympy/sympy/issues/15824
+    raises(NotImplementedError, lambda: fcode(fp1))
+
+
+def test_FunctionDefinition_print():
+    x = symbols('x')
+    n = symbols('n', integer=True)
+    vx = Variable(x, type=real)
+    vn = Variable(n, type=integer)
+    body = [Assignment(x, x**n), Return(x)]
+    fd1 = FunctionDefinition(real, 'power', [vx, vn], body)
+    # Should be changed to proper test once multi-line generation is working
+    # see https://github.com/sympy/sympy/issues/15824
+    raises(NotImplementedError, lambda: fcode(fd1))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_glsl.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_glsl.py
new file mode 100644
index 0000000000000000000000000000000000000000..86ec1dfe4a37d141e8435c369cb692d3a9a3b7bc
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_glsl.py
@@ -0,0 +1,998 @@
+from sympy.core import (pi, symbols, Rational, Integer, GoldenRatio, EulerGamma,
+                        Catalan, Lambda, Dummy, Eq, Ne, Le, Lt, Gt, Ge)
+from sympy.functions import Piecewise, sin, cos, Abs, exp, ceiling, sqrt
+from sympy.testing.pytest import raises, warns_deprecated_sympy
+from sympy.printing.glsl import GLSLPrinter
+from sympy.printing.str import StrPrinter
+from sympy.utilities.lambdify import implemented_function
+from sympy.tensor import IndexedBase, Idx
+from sympy.matrices import Matrix, MatrixSymbol
+from sympy.core import Tuple
+from sympy.printing.glsl import glsl_code
+import textwrap
+
+x, y, z = symbols('x,y,z')
+
+
+def test_printmethod():
+    assert glsl_code(Abs(x)) == "abs(x)"
+
+def test_print_without_operators():
+    assert glsl_code(x*y,use_operators = False) == 'mul(x, y)'
+    assert glsl_code(x**y+z,use_operators = False) == 'add(pow(x, y), z)'
+    assert glsl_code(x*(y+z),use_operators = False) == 'mul(x, add(y, z))'
+    assert glsl_code(x*(y+z),use_operators = False) == 'mul(x, add(y, z))'
+    assert glsl_code(x*(y+z**y**0.5),use_operators = False) == 'mul(x, add(y, pow(z, sqrt(y))))'
+    assert glsl_code(-x-y, use_operators=False, zero='zero()') == 'sub(zero(), add(x, y))'
+    assert glsl_code(-x-y, use_operators=False) == 'sub(0.0, add(x, y))'
+
+def test_glsl_code_sqrt():
+    assert glsl_code(sqrt(x)) == "sqrt(x)"
+    assert glsl_code(x**0.5) == "sqrt(x)"
+    assert glsl_code(sqrt(x)) == "sqrt(x)"
+
+
+def test_glsl_code_Pow():
+    g = implemented_function('g', Lambda(x, 2*x))
+    assert glsl_code(x**3) == "pow(x, 3.0)"
+    assert glsl_code(x**(y**3)) == "pow(x, pow(y, 3.0))"
+    assert glsl_code(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \
+        "pow(3.5*2*x, -x + pow(y, x))/(pow(x, 2.0) + y)"
+    assert glsl_code(x**-1.0) == '1.0/x'
+
+
+def test_glsl_code_Relational():
+    assert glsl_code(Eq(x, y)) == "x == y"
+    assert glsl_code(Ne(x, y)) == "x != y"
+    assert glsl_code(Le(x, y)) == "x <= y"
+    assert glsl_code(Lt(x, y)) == "x < y"
+    assert glsl_code(Gt(x, y)) == "x > y"
+    assert glsl_code(Ge(x, y)) == "x >= y"
+
+
+def test_glsl_code_constants_mathh():
+    assert glsl_code(exp(1)) == "float E = 2.71828183;\nE"
+    assert glsl_code(pi) == "float pi = 3.14159265;\npi"
+    # assert glsl_code(oo) == "Number.POSITIVE_INFINITY"
+    # assert glsl_code(-oo) == "Number.NEGATIVE_INFINITY"
+
+
+def test_glsl_code_constants_other():
+    assert glsl_code(2*GoldenRatio) == "float GoldenRatio = 1.61803399;\n2*GoldenRatio"
+    assert glsl_code(2*Catalan) == "float Catalan = 0.915965594;\n2*Catalan"
+    assert glsl_code(2*EulerGamma) == "float EulerGamma = 0.577215665;\n2*EulerGamma"
+
+
+def test_glsl_code_Rational():
+    assert glsl_code(Rational(3, 7)) == "3.0/7.0"
+    assert glsl_code(Rational(18, 9)) == "2"
+    assert glsl_code(Rational(3, -7)) == "-3.0/7.0"
+    assert glsl_code(Rational(-3, -7)) == "3.0/7.0"
+
+
+def test_glsl_code_Integer():
+    assert glsl_code(Integer(67)) == "67"
+    assert glsl_code(Integer(-1)) == "-1"
+
+
+def test_glsl_code_functions():
+    assert glsl_code(sin(x) ** cos(x)) == "pow(sin(x), cos(x))"
+
+
+def test_glsl_code_inline_function():
+    x = symbols('x')
+    g = implemented_function('g', Lambda(x, 2*x))
+    assert glsl_code(g(x)) == "2*x"
+    g = implemented_function('g', Lambda(x, 2*x/Catalan))
+    assert glsl_code(g(x)) == "float Catalan = 0.915965594;\n2*x/Catalan"
+    A = IndexedBase('A')
+    i = Idx('i', symbols('n', integer=True))
+    g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x)))
+    assert glsl_code(g(A[i]), assign_to=A[i]) == (
+        "for (int i=0; i 1), (sin(x), x > 0))
+    raises(ValueError, lambda: glsl_code(expr))
+
+
+def test_glsl_code_Piecewise_deep():
+    p = glsl_code(2*Piecewise((x, x < 1), (x**2, True)))
+    s = \
+"""\
+2*((x < 1) ? (
+   x
+)
+: (
+   pow(x, 2.0)
+))\
+"""
+    assert p == s
+
+
+def test_glsl_code_settings():
+    raises(TypeError, lambda: glsl_code(sin(x), method="garbage"))
+
+
+def test_glsl_code_Indexed():
+    n, m, o = symbols('n m o', integer=True)
+    i, j, k = Idx('i', n), Idx('j', m), Idx('k', o)
+    p = GLSLPrinter()
+    p._not_c = set()
+
+    x = IndexedBase('x')[j]
+    assert p._print_Indexed(x) == 'x[j]'
+    A = IndexedBase('A')[i, j]
+    assert p._print_Indexed(A) == 'A[%s]' % (m*i+j)
+    B = IndexedBase('B')[i, j, k]
+    assert p._print_Indexed(B) == 'B[%s]' % (i*o*m+j*o+k)
+
+    assert p._not_c == set()
+
+def test_glsl_code_list_tuple_Tuple():
+    assert glsl_code([1,2,3,4]) == 'vec4(1, 2, 3, 4)'
+    assert glsl_code([1,2,3],glsl_types=False) == 'float[3](1, 2, 3)'
+    assert glsl_code([1,2,3]) == glsl_code((1,2,3))
+    assert glsl_code([1,2,3]) == glsl_code(Tuple(1,2,3))
+
+    m = MatrixSymbol('A',3,4)
+    assert glsl_code([m[0],m[1]])
+
+def test_glsl_code_loops_matrix_vector():
+    n, m = symbols('n m', integer=True)
+    A = IndexedBase('A')
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i = Idx('i', m)
+    j = Idx('j', n)
+
+    s = (
+        'for (int i=0; i0), (y, True)), sin(z)])
+    A = MatrixSymbol('A', 3, 1)
+    assert glsl_code(mat, assign_to=A) == (
+'''A[0][0] = x*y;
+if (y > 0) {
+   A[1][0] = x + 2;
+}
+else {
+   A[1][0] = y;
+}
+A[2][0] = sin(z);''' )
+    assert glsl_code(Matrix([A[0],A[1]]))
+    # Test using MatrixElements in expressions
+    expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0]
+    assert glsl_code(expr) == (
+'''((x > 0) ? (
+   2*A[2][0]
+)
+: (
+   A[2][0]
+)) + sin(A[1][0]) + A[0][0]''' )
+
+    # Test using MatrixElements in a Matrix
+    q = MatrixSymbol('q', 5, 1)
+    M = MatrixSymbol('M', 3, 3)
+    m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])],
+        [q[1,0] + q[2,0], q[3, 0], 5],
+        [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]])
+    assert glsl_code(m,M) == (
+'''M[0][0] = sin(q[1]);
+M[0][1] = 0;
+M[0][2] = cos(q[2]);
+M[1][0] = q[1] + q[2];
+M[1][1] = q[3];
+M[1][2] = 5;
+M[2][0] = 2*q[4]/q[1];
+M[2][1] = sqrt(q[0]) + 4;
+M[2][2] = 0;'''
+        )
+
+def test_Matrices_1x7():
+    gl = glsl_code
+    A = Matrix([1,2,3,4,5,6,7])
+    assert gl(A) == 'float[7](1, 2, 3, 4, 5, 6, 7)'
+    assert gl(A.transpose()) == 'float[7](1, 2, 3, 4, 5, 6, 7)'
+
+def test_Matrices_1x7_array_type_int():
+    gl = glsl_code
+    A = Matrix([1,2,3,4,5,6,7])
+    assert gl(A, array_type='int') == 'int[7](1, 2, 3, 4, 5, 6, 7)'
+
+def test_Tuple_array_type_custom():
+    gl = glsl_code
+    A = symbols('a b c')
+    assert gl(A, array_type='AbcType', glsl_types=False) == 'AbcType[3](a, b, c)'
+
+def test_Matrices_1x7_spread_assign_to_symbols():
+    gl = glsl_code
+    A = Matrix([1,2,3,4,5,6,7])
+    assign_to = symbols('x.a x.b x.c x.d x.e x.f x.g')
+    assert gl(A, assign_to=assign_to) == textwrap.dedent('''\
+        x.a = 1;
+        x.b = 2;
+        x.c = 3;
+        x.d = 4;
+        x.e = 5;
+        x.f = 6;
+        x.g = 7;'''
+    )
+
+def test_spread_assign_to_nested_symbols():
+    gl = glsl_code
+    expr = ((1,2,3), (1,2,3))
+    assign_to = (symbols('a b c'), symbols('x y z'))
+    assert gl(expr, assign_to=assign_to) == textwrap.dedent('''\
+        a = 1;
+        b = 2;
+        c = 3;
+        x = 1;
+        y = 2;
+        z = 3;'''
+    )
+
+def test_spread_assign_to_deeply_nested_symbols():
+    gl = glsl_code
+    a, b, c, x, y, z = symbols('a b c x y z')
+    expr = (((1,2),3), ((1,2),3))
+    assign_to = (((a, b), c), ((x, y), z))
+    assert gl(expr, assign_to=assign_to) == textwrap.dedent('''\
+        a = 1;
+        b = 2;
+        c = 3;
+        x = 1;
+        y = 2;
+        z = 3;'''
+    )
+
+def test_matrix_of_tuples_spread_assign_to_symbols():
+    gl = glsl_code
+    with warns_deprecated_sympy():
+        expr = Matrix([[(1,2),(3,4)],[(5,6),(7,8)]])
+    assign_to = (symbols('a b'), symbols('c d'), symbols('e f'), symbols('g h'))
+    assert gl(expr, assign_to) == textwrap.dedent('''\
+        a = 1;
+        b = 2;
+        c = 3;
+        d = 4;
+        e = 5;
+        f = 6;
+        g = 7;
+        h = 8;'''
+    )
+
+def test_cannot_assign_to_cause_mismatched_length():
+    expr = (1, 2)
+    assign_to = symbols('x y z')
+    raises(ValueError, lambda: glsl_code(expr, assign_to))
+
+def test_matrix_4x4_assign():
+    gl = glsl_code
+    expr = MatrixSymbol('A',4,4) * MatrixSymbol('B',4,4) + MatrixSymbol('C',4,4)
+    assign_to = MatrixSymbol('X',4,4)
+    assert gl(expr, assign_to=assign_to) == textwrap.dedent('''\
+        X[0][0] = A[0][0]*B[0][0] + A[0][1]*B[1][0] + A[0][2]*B[2][0] + A[0][3]*B[3][0] + C[0][0];
+        X[0][1] = A[0][0]*B[0][1] + A[0][1]*B[1][1] + A[0][2]*B[2][1] + A[0][3]*B[3][1] + C[0][1];
+        X[0][2] = A[0][0]*B[0][2] + A[0][1]*B[1][2] + A[0][2]*B[2][2] + A[0][3]*B[3][2] + C[0][2];
+        X[0][3] = A[0][0]*B[0][3] + A[0][1]*B[1][3] + A[0][2]*B[2][3] + A[0][3]*B[3][3] + C[0][3];
+        X[1][0] = A[1][0]*B[0][0] + A[1][1]*B[1][0] + A[1][2]*B[2][0] + A[1][3]*B[3][0] + C[1][0];
+        X[1][1] = A[1][0]*B[0][1] + A[1][1]*B[1][1] + A[1][2]*B[2][1] + A[1][3]*B[3][1] + C[1][1];
+        X[1][2] = A[1][0]*B[0][2] + A[1][1]*B[1][2] + A[1][2]*B[2][2] + A[1][3]*B[3][2] + C[1][2];
+        X[1][3] = A[1][0]*B[0][3] + A[1][1]*B[1][3] + A[1][2]*B[2][3] + A[1][3]*B[3][3] + C[1][3];
+        X[2][0] = A[2][0]*B[0][0] + A[2][1]*B[1][0] + A[2][2]*B[2][0] + A[2][3]*B[3][0] + C[2][0];
+        X[2][1] = A[2][0]*B[0][1] + A[2][1]*B[1][1] + A[2][2]*B[2][1] + A[2][3]*B[3][1] + C[2][1];
+        X[2][2] = A[2][0]*B[0][2] + A[2][1]*B[1][2] + A[2][2]*B[2][2] + A[2][3]*B[3][2] + C[2][2];
+        X[2][3] = A[2][0]*B[0][3] + A[2][1]*B[1][3] + A[2][2]*B[2][3] + A[2][3]*B[3][3] + C[2][3];
+        X[3][0] = A[3][0]*B[0][0] + A[3][1]*B[1][0] + A[3][2]*B[2][0] + A[3][3]*B[3][0] + C[3][0];
+        X[3][1] = A[3][0]*B[0][1] + A[3][1]*B[1][1] + A[3][2]*B[2][1] + A[3][3]*B[3][1] + C[3][1];
+        X[3][2] = A[3][0]*B[0][2] + A[3][1]*B[1][2] + A[3][2]*B[2][2] + A[3][3]*B[3][2] + C[3][2];
+        X[3][3] = A[3][0]*B[0][3] + A[3][1]*B[1][3] + A[3][2]*B[2][3] + A[3][3]*B[3][3] + C[3][3];'''
+    )
+
+def test_1xN_vecs():
+    gl = glsl_code
+    for i in range(1,10):
+        A = Matrix(range(i))
+        assert gl(A.transpose()) == gl(A)
+        assert gl(A,mat_transpose=True) == gl(A)
+        if i > 1:
+            if i <= 4:
+                assert gl(A) == 'vec%s(%s)' % (i,', '.join(str(s) for s in range(i)))
+            else:
+                assert gl(A) == 'float[%s](%s)' % (i,', '.join(str(s) for s in range(i)))
+
+def test_MxN_mats():
+    generatedAssertions='def test_misc_mats():\n'
+    for i in range(1,6):
+        for j in range(1,6):
+            A = Matrix([[x + y*j for x in range(j)] for y in range(i)])
+            gl = glsl_code(A)
+            glTransposed = glsl_code(A,mat_transpose=True)
+            generatedAssertions+='    mat = '+StrPrinter()._print(A)+'\n\n'
+            generatedAssertions+='    gl = \'\'\''+gl+'\'\'\'\n'
+            generatedAssertions+='    glTransposed = \'\'\''+glTransposed+'\'\'\'\n\n'
+            generatedAssertions+='    assert glsl_code(mat) == gl\n'
+            generatedAssertions+='    assert glsl_code(mat,mat_transpose=True) == glTransposed\n'
+            if i == 1 and j == 1:
+                assert gl == '0'
+            elif i <= 4 and j <= 4 and i>1 and j>1:
+                assert gl.startswith('mat%s' % j)
+                assert glTransposed.startswith('mat%s' % i)
+            elif i == 1 and j <= 4:
+                assert gl.startswith('vec')
+            elif j == 1 and i <= 4:
+                assert gl.startswith('vec')
+            elif i == 1:
+                assert gl.startswith('float[%s]('% j*i)
+                assert glTransposed.startswith('float[%s]('% j*i)
+            elif j == 1:
+                assert gl.startswith('float[%s]('% i*j)
+                assert glTransposed.startswith('float[%s]('% i*j)
+            else:
+                assert gl.startswith('float[%s](' % (i*j))
+                assert glTransposed.startswith('float[%s](' % (i*j))
+                glNested = glsl_code(A,mat_nested=True)
+                glNestedTransposed = glsl_code(A,mat_transpose=True,mat_nested=True)
+                assert glNested.startswith('float[%s][%s]' % (i,j))
+                assert glNestedTransposed.startswith('float[%s][%s]' % (j,i))
+                generatedAssertions+='    glNested = \'\'\''+glNested+'\'\'\'\n'
+                generatedAssertions+='    glNestedTransposed = \'\'\''+glNestedTransposed+'\'\'\'\n\n'
+                generatedAssertions+='    assert glsl_code(mat,mat_nested=True) == glNested\n'
+                generatedAssertions+='    assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed\n\n'
+    generateAssertions = False # set this to true to write bake these generated tests to a file
+    if generateAssertions:
+        gen = open('test_glsl_generated_matrices.py','w')
+        gen.write(generatedAssertions)
+        gen.close()
+
+
+# these assertions were generated from the previous function
+# glsl has complicated rules and this makes it easier to look over all the cases
+def test_misc_mats():
+
+    mat = Matrix([[0]])
+
+    gl = '''0'''
+    glTransposed = '''0'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+
+    mat = Matrix([[0, 1]])
+
+    gl = '''vec2(0, 1)'''
+    glTransposed = '''vec2(0, 1)'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+
+    mat = Matrix([[0, 1, 2]])
+
+    gl = '''vec3(0, 1, 2)'''
+    glTransposed = '''vec3(0, 1, 2)'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+
+    mat = Matrix([[0, 1, 2, 3]])
+
+    gl = '''vec4(0, 1, 2, 3)'''
+    glTransposed = '''vec4(0, 1, 2, 3)'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+
+    mat = Matrix([[0, 1, 2, 3, 4]])
+
+    gl = '''float[5](0, 1, 2, 3, 4)'''
+    glTransposed = '''float[5](0, 1, 2, 3, 4)'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+
+    mat = Matrix([
+[0],
+[1]])
+
+    gl = '''vec2(0, 1)'''
+    glTransposed = '''vec2(0, 1)'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+
+    mat = Matrix([
+[0, 1],
+[2, 3]])
+
+    gl = '''mat2(0, 1, 2, 3)'''
+    glTransposed = '''mat2(0, 2, 1, 3)'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+
+    mat = Matrix([
+[0, 1, 2],
+[3, 4, 5]])
+
+    gl = '''mat3x2(0, 1, 2, 3, 4, 5)'''
+    glTransposed = '''mat2x3(0, 3, 1, 4, 2, 5)'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+
+    mat = Matrix([
+[0, 1, 2, 3],
+[4, 5, 6, 7]])
+
+    gl = '''mat4x2(0, 1, 2, 3, 4, 5, 6, 7)'''
+    glTransposed = '''mat2x4(0, 4, 1, 5, 2, 6, 3, 7)'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+
+    mat = Matrix([
+[0, 1, 2, 3, 4],
+[5, 6, 7, 8, 9]])
+
+    gl = '''float[10](
+   0, 1, 2, 3, 4,
+   5, 6, 7, 8, 9
+) /* a 2x5 matrix */'''
+    glTransposed = '''float[10](
+   0, 5,
+   1, 6,
+   2, 7,
+   3, 8,
+   4, 9
+) /* a 5x2 matrix */'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+    glNested = '''float[2][5](
+   float[](0, 1, 2, 3, 4),
+   float[](5, 6, 7, 8, 9)
+)'''
+    glNestedTransposed = '''float[5][2](
+   float[](0, 5),
+   float[](1, 6),
+   float[](2, 7),
+   float[](3, 8),
+   float[](4, 9)
+)'''
+
+    assert glsl_code(mat,mat_nested=True) == glNested
+    assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed
+
+    mat = Matrix([
+[0],
+[1],
+[2]])
+
+    gl = '''vec3(0, 1, 2)'''
+    glTransposed = '''vec3(0, 1, 2)'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+
+    mat = Matrix([
+[0, 1],
+[2, 3],
+[4, 5]])
+
+    gl = '''mat2x3(0, 1, 2, 3, 4, 5)'''
+    glTransposed = '''mat3x2(0, 2, 4, 1, 3, 5)'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+
+    mat = Matrix([
+[0, 1, 2],
+[3, 4, 5],
+[6, 7, 8]])
+
+    gl = '''mat3(0, 1, 2, 3, 4, 5, 6, 7, 8)'''
+    glTransposed = '''mat3(0, 3, 6, 1, 4, 7, 2, 5, 8)'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+
+    mat = Matrix([
+[0, 1,  2,  3],
+[4, 5,  6,  7],
+[8, 9, 10, 11]])
+
+    gl = '''mat4x3(0, 1,  2,  3, 4, 5,  6,  7, 8, 9, 10, 11)'''
+    glTransposed = '''mat3x4(0, 4,  8, 1, 5,  9, 2, 6, 10, 3, 7, 11)'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+
+    mat = Matrix([
+[ 0,  1,  2,  3,  4],
+[ 5,  6,  7,  8,  9],
+[10, 11, 12, 13, 14]])
+
+    gl = '''float[15](
+   0,  1,  2,  3,  4,
+   5,  6,  7,  8,  9,
+   10, 11, 12, 13, 14
+) /* a 3x5 matrix */'''
+    glTransposed = '''float[15](
+   0, 5, 10,
+   1, 6, 11,
+   2, 7, 12,
+   3, 8, 13,
+   4, 9, 14
+) /* a 5x3 matrix */'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+    glNested = '''float[3][5](
+   float[]( 0,  1,  2,  3,  4),
+   float[]( 5,  6,  7,  8,  9),
+   float[](10, 11, 12, 13, 14)
+)'''
+    glNestedTransposed = '''float[5][3](
+   float[](0, 5, 10),
+   float[](1, 6, 11),
+   float[](2, 7, 12),
+   float[](3, 8, 13),
+   float[](4, 9, 14)
+)'''
+
+    assert glsl_code(mat,mat_nested=True) == glNested
+    assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed
+
+    mat = Matrix([
+[0],
+[1],
+[2],
+[3]])
+
+    gl = '''vec4(0, 1, 2, 3)'''
+    glTransposed = '''vec4(0, 1, 2, 3)'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+
+    mat = Matrix([
+[0, 1],
+[2, 3],
+[4, 5],
+[6, 7]])
+
+    gl = '''mat2x4(0, 1, 2, 3, 4, 5, 6, 7)'''
+    glTransposed = '''mat4x2(0, 2, 4, 6, 1, 3, 5, 7)'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+
+    mat = Matrix([
+[0,  1,  2],
+[3,  4,  5],
+[6,  7,  8],
+[9, 10, 11]])
+
+    gl = '''mat3x4(0,  1,  2, 3,  4,  5, 6,  7,  8, 9, 10, 11)'''
+    glTransposed = '''mat4x3(0, 3, 6,  9, 1, 4, 7, 10, 2, 5, 8, 11)'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+
+    mat = Matrix([
+[ 0,  1,  2,  3],
+[ 4,  5,  6,  7],
+[ 8,  9, 10, 11],
+[12, 13, 14, 15]])
+
+    gl = '''mat4( 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15)'''
+    glTransposed = '''mat4(0, 4,  8, 12, 1, 5,  9, 13, 2, 6, 10, 14, 3, 7, 11, 15)'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+
+    mat = Matrix([
+[ 0,  1,  2,  3,  4],
+[ 5,  6,  7,  8,  9],
+[10, 11, 12, 13, 14],
+[15, 16, 17, 18, 19]])
+
+    gl = '''float[20](
+   0,  1,  2,  3,  4,
+   5,  6,  7,  8,  9,
+   10, 11, 12, 13, 14,
+   15, 16, 17, 18, 19
+) /* a 4x5 matrix */'''
+    glTransposed = '''float[20](
+   0, 5, 10, 15,
+   1, 6, 11, 16,
+   2, 7, 12, 17,
+   3, 8, 13, 18,
+   4, 9, 14, 19
+) /* a 5x4 matrix */'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+    glNested = '''float[4][5](
+   float[]( 0,  1,  2,  3,  4),
+   float[]( 5,  6,  7,  8,  9),
+   float[](10, 11, 12, 13, 14),
+   float[](15, 16, 17, 18, 19)
+)'''
+    glNestedTransposed = '''float[5][4](
+   float[](0, 5, 10, 15),
+   float[](1, 6, 11, 16),
+   float[](2, 7, 12, 17),
+   float[](3, 8, 13, 18),
+   float[](4, 9, 14, 19)
+)'''
+
+    assert glsl_code(mat,mat_nested=True) == glNested
+    assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed
+
+    mat = Matrix([
+[0],
+[1],
+[2],
+[3],
+[4]])
+
+    gl = '''float[5](0, 1, 2, 3, 4)'''
+    glTransposed = '''float[5](0, 1, 2, 3, 4)'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+
+    mat = Matrix([
+[0, 1],
+[2, 3],
+[4, 5],
+[6, 7],
+[8, 9]])
+
+    gl = '''float[10](
+   0, 1,
+   2, 3,
+   4, 5,
+   6, 7,
+   8, 9
+) /* a 5x2 matrix */'''
+    glTransposed = '''float[10](
+   0, 2, 4, 6, 8,
+   1, 3, 5, 7, 9
+) /* a 2x5 matrix */'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+    glNested = '''float[5][2](
+   float[](0, 1),
+   float[](2, 3),
+   float[](4, 5),
+   float[](6, 7),
+   float[](8, 9)
+)'''
+    glNestedTransposed = '''float[2][5](
+   float[](0, 2, 4, 6, 8),
+   float[](1, 3, 5, 7, 9)
+)'''
+
+    assert glsl_code(mat,mat_nested=True) == glNested
+    assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed
+
+    mat = Matrix([
+[ 0,  1,  2],
+[ 3,  4,  5],
+[ 6,  7,  8],
+[ 9, 10, 11],
+[12, 13, 14]])
+
+    gl = '''float[15](
+   0,  1,  2,
+   3,  4,  5,
+   6,  7,  8,
+   9, 10, 11,
+   12, 13, 14
+) /* a 5x3 matrix */'''
+    glTransposed = '''float[15](
+   0, 3, 6,  9, 12,
+   1, 4, 7, 10, 13,
+   2, 5, 8, 11, 14
+) /* a 3x5 matrix */'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+    glNested = '''float[5][3](
+   float[]( 0,  1,  2),
+   float[]( 3,  4,  5),
+   float[]( 6,  7,  8),
+   float[]( 9, 10, 11),
+   float[](12, 13, 14)
+)'''
+    glNestedTransposed = '''float[3][5](
+   float[](0, 3, 6,  9, 12),
+   float[](1, 4, 7, 10, 13),
+   float[](2, 5, 8, 11, 14)
+)'''
+
+    assert glsl_code(mat,mat_nested=True) == glNested
+    assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed
+
+    mat = Matrix([
+[ 0,  1,  2,  3],
+[ 4,  5,  6,  7],
+[ 8,  9, 10, 11],
+[12, 13, 14, 15],
+[16, 17, 18, 19]])
+
+    gl = '''float[20](
+   0,  1,  2,  3,
+   4,  5,  6,  7,
+   8,  9, 10, 11,
+   12, 13, 14, 15,
+   16, 17, 18, 19
+) /* a 5x4 matrix */'''
+    glTransposed = '''float[20](
+   0, 4,  8, 12, 16,
+   1, 5,  9, 13, 17,
+   2, 6, 10, 14, 18,
+   3, 7, 11, 15, 19
+) /* a 4x5 matrix */'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+    glNested = '''float[5][4](
+   float[]( 0,  1,  2,  3),
+   float[]( 4,  5,  6,  7),
+   float[]( 8,  9, 10, 11),
+   float[](12, 13, 14, 15),
+   float[](16, 17, 18, 19)
+)'''
+    glNestedTransposed = '''float[4][5](
+   float[](0, 4,  8, 12, 16),
+   float[](1, 5,  9, 13, 17),
+   float[](2, 6, 10, 14, 18),
+   float[](3, 7, 11, 15, 19)
+)'''
+
+    assert glsl_code(mat,mat_nested=True) == glNested
+    assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed
+
+    mat = Matrix([
+[ 0,  1,  2,  3,  4],
+[ 5,  6,  7,  8,  9],
+[10, 11, 12, 13, 14],
+[15, 16, 17, 18, 19],
+[20, 21, 22, 23, 24]])
+
+    gl = '''float[25](
+   0,  1,  2,  3,  4,
+   5,  6,  7,  8,  9,
+   10, 11, 12, 13, 14,
+   15, 16, 17, 18, 19,
+   20, 21, 22, 23, 24
+) /* a 5x5 matrix */'''
+    glTransposed = '''float[25](
+   0, 5, 10, 15, 20,
+   1, 6, 11, 16, 21,
+   2, 7, 12, 17, 22,
+   3, 8, 13, 18, 23,
+   4, 9, 14, 19, 24
+) /* a 5x5 matrix */'''
+
+    assert glsl_code(mat) == gl
+    assert glsl_code(mat,mat_transpose=True) == glTransposed
+    glNested = '''float[5][5](
+   float[]( 0,  1,  2,  3,  4),
+   float[]( 5,  6,  7,  8,  9),
+   float[](10, 11, 12, 13, 14),
+   float[](15, 16, 17, 18, 19),
+   float[](20, 21, 22, 23, 24)
+)'''
+    glNestedTransposed = '''float[5][5](
+   float[](0, 5, 10, 15, 20),
+   float[](1, 6, 11, 16, 21),
+   float[](2, 7, 12, 17, 22),
+   float[](3, 8, 13, 18, 23),
+   float[](4, 9, 14, 19, 24)
+)'''
+
+    assert glsl_code(mat,mat_nested=True) == glNested
+    assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_gtk.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_gtk.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a595ab04d3a29d23e06ec12207bf917392aebce
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_gtk.py
@@ -0,0 +1,18 @@
+from sympy.functions.elementary.trigonometric import sin
+from sympy.printing.gtk import print_gtk
+from sympy.testing.pytest import XFAIL, raises
+
+# this test fails if python-lxml isn't installed. We don't want to depend on
+# anything with SymPy
+
+
+@XFAIL
+def test_1():
+    from sympy.abc import x
+    print_gtk(x**2, start_viewer=False)
+    print_gtk(x**2 + sin(x)/4, start_viewer=False)
+
+
+def test_settings():
+    from sympy.abc import x
+    raises(TypeError, lambda: print_gtk(x, method="garbage"))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_jax.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_jax.py
new file mode 100644
index 0000000000000000000000000000000000000000..365d87c5b91fdd49a8e46cfde9c2b5792c23a03c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_jax.py
@@ -0,0 +1,370 @@
+from sympy.concrete.summations import Sum
+from sympy.core.mod import Mod
+from sympy.core.relational import (Equality, Unequality)
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.matrices.expressions.blockmatrix import BlockMatrix
+from sympy.matrices.expressions.matexpr import MatrixSymbol
+from sympy.matrices.expressions.special import Identity
+from sympy.utilities.lambdify import lambdify
+
+from sympy.abc import x, i, j, a, b, c, d
+from sympy.core import Function, Pow, Symbol
+from sympy.codegen.matrix_nodes import MatrixSolve
+from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
+from sympy.codegen.cfunctions import log1p, expm1, hypot, log10, exp2, log2, Sqrt
+from sympy.tensor.array import Array
+from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayAdd, \
+    PermuteDims, ArrayDiagonal
+from sympy.printing.numpy import JaxPrinter, _jax_known_constants, _jax_known_functions
+from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
+
+from sympy.testing.pytest import skip, raises
+from sympy.external import import_module
+
+# Unlike NumPy which will aggressively promote operands to double precision,
+# jax always uses single precision. Double precision in jax can be
+# configured before the call to `import jax`, however this must be explicitly
+# configured and is not fully supported. Thus, the tests here have been modified
+# from the tests in test_numpy.py, only in the fact that they assert lambdify
+# function accuracy to only single precision accuracy.
+# https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
+
+jax = import_module('jax')
+
+if jax:
+    deafult_float_info = jax.numpy.finfo(jax.numpy.array([]).dtype)
+    JAX_DEFAULT_EPSILON = deafult_float_info.eps
+
+
+def test_jax_piecewise_regression():
+    """
+    NumPyPrinter needs to print Piecewise()'s choicelist as a list to avoid
+    breaking compatibility with numpy 1.8. This is not necessary in numpy 1.9+.
+    See gh-9747 and gh-9749 for details.
+    """
+    printer = JaxPrinter()
+    p = Piecewise((1, x < 0), (0, True))
+    assert printer.doprint(p) == \
+        'jax.numpy.select([jax.numpy.less(x, 0),True], [1,0], default=jax.numpy.nan)'
+    assert printer.module_imports == {'jax.numpy': {'select', 'less', 'nan'}}
+
+
+def test_jax_logaddexp():
+    lae = logaddexp(a, b)
+    assert JaxPrinter().doprint(lae) == 'jax.numpy.logaddexp(a, b)'
+    lae2 = logaddexp2(a, b)
+    assert JaxPrinter().doprint(lae2) == 'jax.numpy.logaddexp2(a, b)'
+
+
+def test_jax_sum():
+    if not jax:
+        skip("JAX not installed")
+
+    s = Sum(x ** i, (i, a, b))
+    f = lambdify((a, b, x), s, 'jax')
+
+    a_, b_ = 0, 10
+    x_ = jax.numpy.linspace(-1, +1, 10)
+    assert jax.numpy.allclose(f(a_, b_, x_), sum(x_ ** i_ for i_ in range(a_, b_ + 1)))
+
+    s = Sum(i * x, (i, a, b))
+    f = lambdify((a, b, x), s, 'jax')
+
+    a_, b_ = 0, 10
+    x_ = jax.numpy.linspace(-1, +1, 10)
+    assert jax.numpy.allclose(f(a_, b_, x_), sum(i_ * x_ for i_ in range(a_, b_ + 1)))
+
+
+def test_jax_multiple_sums():
+    if not jax:
+        skip("JAX not installed")
+
+    s = Sum((x + j) * i, (i, a, b), (j, c, d))
+    f = lambdify((a, b, c, d, x), s, 'jax')
+
+    a_, b_ = 0, 10
+    c_, d_ = 11, 21
+    x_ = jax.numpy.linspace(-1, +1, 10)
+    assert jax.numpy.allclose(f(a_, b_, c_, d_, x_),
+                       sum((x_ + j_) * i_ for i_ in range(a_, b_ + 1) for j_ in range(c_, d_ + 1)))
+
+
+def test_jax_codegen_einsum():
+    if not jax:
+        skip("JAX not installed")
+
+    M = MatrixSymbol("M", 2, 2)
+    N = MatrixSymbol("N", 2, 2)
+
+    cg = convert_matrix_to_array(M * N)
+    f = lambdify((M, N), cg, 'jax')
+
+    ma = jax.numpy.array([[1, 2], [3, 4]])
+    mb = jax.numpy.array([[1,-2], [-1, 3]])
+    assert (f(ma, mb) == jax.numpy.matmul(ma, mb)).all()
+
+
+def test_jax_codegen_extra():
+    if not jax:
+        skip("JAX not installed")
+
+    M = MatrixSymbol("M", 2, 2)
+    N = MatrixSymbol("N", 2, 2)
+    P = MatrixSymbol("P", 2, 2)
+    Q = MatrixSymbol("Q", 2, 2)
+    ma = jax.numpy.array([[1, 2], [3, 4]])
+    mb = jax.numpy.array([[1,-2], [-1, 3]])
+    mc = jax.numpy.array([[2, 0], [1, 2]])
+    md = jax.numpy.array([[1,-1], [4, 7]])
+
+    cg = ArrayTensorProduct(M, N)
+    f = lambdify((M, N), cg, 'jax')
+    assert (f(ma, mb) == jax.numpy.einsum(ma, [0, 1], mb, [2, 3])).all()
+
+    cg = ArrayAdd(M, N)
+    f = lambdify((M, N), cg, 'jax')
+    assert (f(ma, mb) == ma+mb).all()
+
+    cg = ArrayAdd(M, N, P)
+    f = lambdify((M, N, P), cg, 'jax')
+    assert (f(ma, mb, mc) == ma+mb+mc).all()
+
+    cg = ArrayAdd(M, N, P, Q)
+    f = lambdify((M, N, P, Q), cg, 'jax')
+    assert (f(ma, mb, mc, md) == ma+mb+mc+md).all()
+
+    cg = PermuteDims(M, [1, 0])
+    f = lambdify((M,), cg, 'jax')
+    assert (f(ma) == ma.T).all()
+
+    cg = PermuteDims(ArrayTensorProduct(M, N), [1, 2, 3, 0])
+    f = lambdify((M, N), cg, 'jax')
+    assert (f(ma, mb) == jax.numpy.transpose(jax.numpy.einsum(ma, [0, 1], mb, [2, 3]), (1, 2, 3, 0))).all()
+
+    cg = ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2))
+    f = lambdify((M, N), cg, 'jax')
+    assert (f(ma, mb) == jax.numpy.diagonal(jax.numpy.einsum(ma, [0, 1], mb, [2, 3]), axis1=1, axis2=2)).all()
+
+
+def test_jax_relational():
+    if not jax:
+        skip("JAX not installed")
+
+    e = Equality(x, 1)
+
+    f = lambdify((x,), e, 'jax')
+    x_ = jax.numpy.array([0, 1, 2])
+    assert jax.numpy.array_equal(f(x_), [False, True, False])
+
+    e = Unequality(x, 1)
+
+    f = lambdify((x,), e, 'jax')
+    x_ = jax.numpy.array([0, 1, 2])
+    assert jax.numpy.array_equal(f(x_), [True, False, True])
+
+    e = (x < 1)
+
+    f = lambdify((x,), e, 'jax')
+    x_ = jax.numpy.array([0, 1, 2])
+    assert jax.numpy.array_equal(f(x_), [True, False, False])
+
+    e = (x <= 1)
+
+    f = lambdify((x,), e, 'jax')
+    x_ = jax.numpy.array([0, 1, 2])
+    assert jax.numpy.array_equal(f(x_), [True, True, False])
+
+    e = (x > 1)
+
+    f = lambdify((x,), e, 'jax')
+    x_ = jax.numpy.array([0, 1, 2])
+    assert jax.numpy.array_equal(f(x_), [False, False, True])
+
+    e = (x >= 1)
+
+    f = lambdify((x,), e, 'jax')
+    x_ = jax.numpy.array([0, 1, 2])
+    assert jax.numpy.array_equal(f(x_), [False, True, True])
+
+    # Multi-condition expressions
+    e = (x >= 1) & (x < 2)
+    f = lambdify((x,), e, 'jax')
+    x_ = jax.numpy.array([0, 1, 2])
+    assert jax.numpy.array_equal(f(x_), [False, True, False])
+
+    e = (x >= 1) | (x < 2)
+    f = lambdify((x,), e, 'jax')
+    x_ = jax.numpy.array([0, 1, 2])
+    assert jax.numpy.array_equal(f(x_), [True, True, True])
+
+def test_jax_mod():
+    if not jax:
+        skip("JAX not installed")
+
+    e = Mod(a, b)
+    f = lambdify((a, b), e, 'jax')
+
+    a_ = jax.numpy.array([0, 1, 2, 3])
+    b_ = 2
+    assert jax.numpy.array_equal(f(a_, b_), [0, 1, 0, 1])
+
+    a_ = jax.numpy.array([0, 1, 2, 3])
+    b_ = jax.numpy.array([2, 2, 2, 2])
+    assert jax.numpy.array_equal(f(a_, b_), [0, 1, 0, 1])
+
+    a_ = jax.numpy.array([2, 3, 4, 5])
+    b_ = jax.numpy.array([2, 3, 4, 5])
+    assert jax.numpy.array_equal(f(a_, b_), [0, 0, 0, 0])
+
+
+def test_jax_pow():
+    if not jax:
+        skip('JAX not installed')
+
+    expr = Pow(2, -1, evaluate=False)
+    f = lambdify([], expr, 'jax')
+    assert f() == 0.5
+
+
+def test_jax_expm1():
+    if not jax:
+        skip("JAX not installed")
+
+    f = lambdify((a,), expm1(a), 'jax')
+    assert abs(f(1e-10) - 1e-10 - 5e-21) <= 1e-10 * JAX_DEFAULT_EPSILON
+
+
+def test_jax_log1p():
+    if not jax:
+        skip("JAX not installed")
+
+    f = lambdify((a,), log1p(a), 'jax')
+    assert abs(f(1e-99) - 1e-99) <= 1e-99 * JAX_DEFAULT_EPSILON
+
+def test_jax_hypot():
+    if not jax:
+        skip("JAX not installed")
+    assert abs(lambdify((a, b), hypot(a, b), 'jax')(3, 4) - 5) <= JAX_DEFAULT_EPSILON
+
+def test_jax_log10():
+    if not jax:
+        skip("JAX not installed")
+
+    assert abs(lambdify((a,), log10(a), 'jax')(100) - 2) <= JAX_DEFAULT_EPSILON
+
+
+def test_jax_exp2():
+    if not jax:
+        skip("JAX not installed")
+    assert abs(lambdify((a,), exp2(a), 'jax')(5) - 32) <= JAX_DEFAULT_EPSILON
+
+
+def test_jax_log2():
+    if not jax:
+        skip("JAX not installed")
+    assert abs(lambdify((a,), log2(a), 'jax')(256) - 8) <= JAX_DEFAULT_EPSILON
+
+
+def test_jax_Sqrt():
+    if not jax:
+        skip("JAX not installed")
+    assert abs(lambdify((a,), Sqrt(a), 'jax')(4) - 2) <= JAX_DEFAULT_EPSILON
+
+
+def test_jax_sqrt():
+    if not jax:
+        skip("JAX not installed")
+    assert abs(lambdify((a,), sqrt(a), 'jax')(4) - 2) <= JAX_DEFAULT_EPSILON
+
+
+def test_jax_matsolve():
+    if not jax:
+        skip("JAX not installed")
+
+    M = MatrixSymbol("M", 3, 3)
+    x = MatrixSymbol("x", 3, 1)
+
+    expr = M**(-1) * x + x
+    matsolve_expr = MatrixSolve(M, x) + x
+
+    f = lambdify((M, x), expr, 'jax')
+    f_matsolve = lambdify((M, x), matsolve_expr, 'jax')
+
+    m0 = jax.numpy.array([[1, 2, 3], [3, 2, 5], [5, 6, 7]])
+    assert jax.numpy.linalg.matrix_rank(m0) == 3
+
+    x0 = jax.numpy.array([3, 4, 5])
+
+    assert jax.numpy.allclose(f_matsolve(m0, x0), f(m0, x0))
+
+
+def test_16857():
+    if not jax:
+        skip("JAX not installed")
+
+    a_1 = MatrixSymbol('a_1', 10, 3)
+    a_2 = MatrixSymbol('a_2', 10, 3)
+    a_3 = MatrixSymbol('a_3', 10, 3)
+    a_4 = MatrixSymbol('a_4', 10, 3)
+    A = BlockMatrix([[a_1, a_2], [a_3, a_4]])
+    assert A.shape == (20, 6)
+
+    printer = JaxPrinter()
+    assert printer.doprint(A) == 'jax.numpy.block([[a_1, a_2], [a_3, a_4]])'
+
+
+def test_issue_17006():
+    if not jax:
+        skip("JAX not installed")
+
+    M = MatrixSymbol("M", 2, 2)
+
+    f = lambdify(M, M + Identity(2), 'jax')
+    ma = jax.numpy.array([[1, 2], [3, 4]])
+    mr = jax.numpy.array([[2, 2], [3, 5]])
+
+    assert (f(ma) == mr).all()
+
+    from sympy.core.symbol import symbols
+    n = symbols('n', integer=True)
+    N = MatrixSymbol("M", n, n)
+    raises(NotImplementedError, lambda: lambdify(N, N + Identity(n), 'jax'))
+
+
+def test_jax_array():
+    assert JaxPrinter().doprint(Array(((1, 2), (3, 5)))) == 'jax.numpy.array([[1, 2], [3, 5]])'
+    assert JaxPrinter().doprint(Array((1, 2))) == 'jax.numpy.array([1, 2])'
+
+
+def test_jax_known_funcs_consts():
+    assert _jax_known_constants['NaN'] == 'jax.numpy.nan'
+    assert _jax_known_constants['EulerGamma'] == 'jax.numpy.euler_gamma'
+
+    assert _jax_known_functions['acos'] == 'jax.numpy.arccos'
+    assert _jax_known_functions['log'] == 'jax.numpy.log'
+
+
+def test_jax_print_methods():
+    prntr = JaxPrinter()
+    assert hasattr(prntr, '_print_acos')
+    assert hasattr(prntr, '_print_log')
+
+
+def test_jax_printmethod():
+    printer = JaxPrinter()
+    assert hasattr(printer, 'printmethod')
+    assert printer.printmethod == '_jaxcode'
+
+
+def test_jax_custom_print_method():
+
+    class expm1(Function):
+
+        def _jaxcode(self, printer):
+            x, = self.args
+            function = f'expm1({printer._print(x)})'
+            return printer._module_format(printer._module + '.' + function)
+
+    printer = JaxPrinter()
+    assert printer.doprint(expm1(Symbol('x'))) == 'jax.numpy.expm1(x)'
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_jscode.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_jscode.py
new file mode 100644
index 0000000000000000000000000000000000000000..9199a8e0d62e87f2e964cb1712726a21c894fd20
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_jscode.py
@@ -0,0 +1,396 @@
+from sympy.core import (pi, oo, symbols, Rational, Integer, GoldenRatio,
+                        EulerGamma, Catalan, Lambda, Dummy, S, Eq, Ne, Le,
+                        Lt, Gt, Ge, Mod)
+from sympy.functions import (Piecewise, sin, cos, Abs, exp, ceiling, sqrt,
+                             sinh, cosh, tanh, asin, acos, acosh, Max, Min)
+from sympy.testing.pytest import raises
+from sympy.printing.jscode import JavascriptCodePrinter
+from sympy.utilities.lambdify import implemented_function
+from sympy.tensor import IndexedBase, Idx
+from sympy.matrices import Matrix, MatrixSymbol
+
+from sympy.printing.jscode import jscode
+
+x, y, z = symbols('x,y,z')
+
+
+def test_printmethod():
+    assert jscode(Abs(x)) == "Math.abs(x)"
+
+
+def test_jscode_sqrt():
+    assert jscode(sqrt(x)) == "Math.sqrt(x)"
+    assert jscode(x**0.5) == "Math.sqrt(x)"
+    assert jscode(x**(S.One/3)) == "Math.cbrt(x)"
+
+
+def test_jscode_Pow():
+    g = implemented_function('g', Lambda(x, 2*x))
+    assert jscode(x**3) == "Math.pow(x, 3)"
+    assert jscode(x**(y**3)) == "Math.pow(x, Math.pow(y, 3))"
+    assert jscode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \
+        "Math.pow(3.5*2*x, -x + Math.pow(y, x))/(Math.pow(x, 2) + y)"
+    assert jscode(x**-1.0) == '1/x'
+
+
+def test_jscode_constants_mathh():
+    assert jscode(exp(1)) == "Math.E"
+    assert jscode(pi) == "Math.PI"
+    assert jscode(oo) == "Number.POSITIVE_INFINITY"
+    assert jscode(-oo) == "Number.NEGATIVE_INFINITY"
+
+
+def test_jscode_constants_other():
+    assert jscode(
+        2*GoldenRatio) == "var GoldenRatio = %s;\n2*GoldenRatio" % GoldenRatio.evalf(17)
+    assert jscode(2*Catalan) == "var Catalan = %s;\n2*Catalan" % Catalan.evalf(17)
+    assert jscode(
+        2*EulerGamma) == "var EulerGamma = %s;\n2*EulerGamma" % EulerGamma.evalf(17)
+
+
+def test_jscode_Rational():
+    assert jscode(Rational(3, 7)) == "3/7"
+    assert jscode(Rational(18, 9)) == "2"
+    assert jscode(Rational(3, -7)) == "-3/7"
+    assert jscode(Rational(-3, -7)) == "3/7"
+
+
+def test_Relational():
+    assert jscode(Eq(x, y)) == "x == y"
+    assert jscode(Ne(x, y)) == "x != y"
+    assert jscode(Le(x, y)) == "x <= y"
+    assert jscode(Lt(x, y)) == "x < y"
+    assert jscode(Gt(x, y)) == "x > y"
+    assert jscode(Ge(x, y)) == "x >= y"
+
+
+def test_Mod():
+    assert jscode(Mod(x, y)) == '((x % y) + y) % y'
+    assert jscode(Mod(x, x + y)) == '((x % (x + y)) + (x + y)) % (x + y)'
+    p1, p2 = symbols('p1 p2', positive=True)
+    assert jscode(Mod(p1, p2)) == 'p1 % p2'
+    assert jscode(Mod(p1, p2 + 3)) == 'p1 % (p2 + 3)'
+    assert jscode(Mod(-3, -7, evaluate=False)) == '(-3) % (-7)'
+    assert jscode(-Mod(p1, p2)) == '-(p1 % p2)'
+    assert jscode(x*Mod(p1, p2)) == 'x*(p1 % p2)'
+
+
+def test_jscode_Integer():
+    assert jscode(Integer(67)) == "67"
+    assert jscode(Integer(-1)) == "-1"
+
+
+def test_jscode_functions():
+    assert jscode(sin(x) ** cos(x)) == "Math.pow(Math.sin(x), Math.cos(x))"
+    assert jscode(sinh(x) * cosh(x)) == "Math.sinh(x)*Math.cosh(x)"
+    assert jscode(Max(x, y) + Min(x, y)) == "Math.max(x, y) + Math.min(x, y)"
+    assert jscode(tanh(x)*acosh(y)) == "Math.tanh(x)*Math.acosh(y)"
+    assert jscode(asin(x)-acos(y)) == "-Math.acos(y) + Math.asin(x)"
+
+
+def test_jscode_inline_function():
+    x = symbols('x')
+    g = implemented_function('g', Lambda(x, 2*x))
+    assert jscode(g(x)) == "2*x"
+    g = implemented_function('g', Lambda(x, 2*x/Catalan))
+    assert jscode(g(x)) == "var Catalan = %s;\n2*x/Catalan" % Catalan.evalf(17)
+    A = IndexedBase('A')
+    i = Idx('i', symbols('n', integer=True))
+    g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x)))
+    assert jscode(g(A[i]), assign_to=A[i]) == (
+        "for (var i=0; i 1), (sin(x), x > 0))
+    raises(ValueError, lambda: jscode(expr))
+
+
+def test_jscode_Piecewise_deep():
+    p = jscode(2*Piecewise((x, x < 1), (x**2, True)))
+    s = \
+"""\
+2*((x < 1) ? (
+   x
+)
+: (
+   Math.pow(x, 2)
+))\
+"""
+    assert p == s
+
+
+def test_jscode_settings():
+    raises(TypeError, lambda: jscode(sin(x), method="garbage"))
+
+
+def test_jscode_Indexed():
+    n, m, o = symbols('n m o', integer=True)
+    i, j, k = Idx('i', n), Idx('j', m), Idx('k', o)
+    p = JavascriptCodePrinter()
+    p._not_c = set()
+
+    x = IndexedBase('x')[j]
+    assert p._print_Indexed(x) == 'x[j]'
+    A = IndexedBase('A')[i, j]
+    assert p._print_Indexed(A) == 'A[%s]' % (m*i+j)
+    B = IndexedBase('B')[i, j, k]
+    assert p._print_Indexed(B) == 'B[%s]' % (i*o*m+j*o+k)
+
+    assert p._not_c == set()
+
+
+def test_jscode_loops_matrix_vector():
+    n, m = symbols('n m', integer=True)
+    A = IndexedBase('A')
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i = Idx('i', m)
+    j = Idx('j', n)
+
+    s = (
+        'for (var i=0; i0), (y, True)), sin(z)])
+    A = MatrixSymbol('A', 3, 1)
+    assert jscode(mat, A) == (
+        "A[0] = x*y;\n"
+        "if (y > 0) {\n"
+        "   A[1] = x + 2;\n"
+        "}\n"
+        "else {\n"
+        "   A[1] = y;\n"
+        "}\n"
+        "A[2] = Math.sin(z);")
+    # Test using MatrixElements in expressions
+    expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0]
+    assert jscode(expr) == (
+        "((x > 0) ? (\n"
+        "   2*A[2]\n"
+        ")\n"
+        ": (\n"
+        "   A[2]\n"
+        ")) + Math.sin(A[1]) + A[0]")
+    # Test using MatrixElements in a Matrix
+    q = MatrixSymbol('q', 5, 1)
+    M = MatrixSymbol('M', 3, 3)
+    m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])],
+        [q[1,0] + q[2,0], q[3, 0], 5],
+        [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]])
+    assert jscode(m, M) == (
+        "M[0] = Math.sin(q[1]);\n"
+        "M[1] = 0;\n"
+        "M[2] = Math.cos(q[2]);\n"
+        "M[3] = q[1] + q[2];\n"
+        "M[4] = q[3];\n"
+        "M[5] = 5;\n"
+        "M[6] = 2*q[4]/q[1];\n"
+        "M[7] = Math.sqrt(q[0]) + 4;\n"
+        "M[8] = 0;")
+
+
+def test_MatrixElement_printing():
+    # test cases for issue #11821
+    A = MatrixSymbol("A", 1, 3)
+    B = MatrixSymbol("B", 1, 3)
+    C = MatrixSymbol("C", 1, 3)
+
+    assert(jscode(A[0, 0]) == "A[0]")
+    assert(jscode(3 * A[0, 0]) == "3*A[0]")
+
+    F = C[0, 0].subs(C, A - B)
+    assert(jscode(F) == "(A - B)[0]")
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_julia.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_julia.py
new file mode 100644
index 0000000000000000000000000000000000000000..b19c7b4fd4f21d8402ca2f577605322b3ec10f5b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_julia.py
@@ -0,0 +1,390 @@
+from sympy.core import (S, pi, oo, symbols, Function, Rational, Integer,
+                        Tuple, Symbol, Eq, Ne, Le, Lt, Gt, Ge)
+from sympy.core import EulerGamma, GoldenRatio, Catalan, Lambda, Mul, Pow
+from sympy.functions import Piecewise, sqrt, ceiling, exp, sin, cos, sinc
+from sympy.testing.pytest import raises
+from sympy.utilities.lambdify import implemented_function
+from sympy.matrices import (eye, Matrix, MatrixSymbol, Identity,
+                            HadamardProduct, SparseMatrix)
+from sympy.functions.special.bessel import (jn, yn, besselj, bessely, besseli,
+                                            besselk, hankel1, hankel2, airyai,
+                                            airybi, airyaiprime, airybiprime)
+from sympy.testing.pytest import XFAIL
+
+from sympy.printing.julia import julia_code
+
+x, y, z = symbols('x,y,z')
+
+
+def test_Integer():
+    assert julia_code(Integer(67)) == "67"
+    assert julia_code(Integer(-1)) == "-1"
+
+
+def test_Rational():
+    assert julia_code(Rational(3, 7)) == "3 // 7"
+    assert julia_code(Rational(18, 9)) == "2"
+    assert julia_code(Rational(3, -7)) == "-3 // 7"
+    assert julia_code(Rational(-3, -7)) == "3 // 7"
+    assert julia_code(x + Rational(3, 7)) == "x + 3 // 7"
+    assert julia_code(Rational(3, 7)*x) == "(3 // 7) * x"
+
+
+def test_Relational():
+    assert julia_code(Eq(x, y)) == "x == y"
+    assert julia_code(Ne(x, y)) == "x != y"
+    assert julia_code(Le(x, y)) == "x <= y"
+    assert julia_code(Lt(x, y)) == "x < y"
+    assert julia_code(Gt(x, y)) == "x > y"
+    assert julia_code(Ge(x, y)) == "x >= y"
+
+
+def test_Function():
+    assert julia_code(sin(x) ** cos(x)) == "sin(x) .^ cos(x)"
+    assert julia_code(abs(x)) == "abs(x)"
+    assert julia_code(ceiling(x)) == "ceil(x)"
+
+
+def test_Pow():
+    assert julia_code(x**3) == "x .^ 3"
+    assert julia_code(x**(y**3)) == "x .^ (y .^ 3)"
+    assert julia_code(x**Rational(2, 3)) == 'x .^ (2 // 3)'
+    g = implemented_function('g', Lambda(x, 2*x))
+    assert julia_code(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \
+        "(3.5 * 2 * x) .^ (-x + y .^ x) ./ (x .^ 2 + y)"
+    # For issue 14160
+    assert julia_code(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False),
+                                                evaluate=False)) == '-2 * x ./ (y .* y)'
+
+
+def test_basic_ops():
+    assert julia_code(x*y) == "x .* y"
+    assert julia_code(x + y) == "x + y"
+    assert julia_code(x - y) == "x - y"
+    assert julia_code(-x) == "-x"
+
+
+def test_1_over_x_and_sqrt():
+    # 1.0 and 0.5 would do something different in regular StrPrinter,
+    # but these are exact in IEEE floating point so no different here.
+    assert julia_code(1/x) == '1 ./ x'
+    assert julia_code(x**-1) == julia_code(x**-1.0) == '1 ./ x'
+    assert julia_code(1/sqrt(x)) == '1 ./ sqrt(x)'
+    assert julia_code(x**-S.Half) == julia_code(x**-0.5) == '1 ./ sqrt(x)'
+    assert julia_code(sqrt(x)) == 'sqrt(x)'
+    assert julia_code(x**S.Half) == julia_code(x**0.5) == 'sqrt(x)'
+    assert julia_code(1/pi) == '1 / pi'
+    assert julia_code(pi**-1) == julia_code(pi**-1.0) == '1 / pi'
+    assert julia_code(pi**-0.5) == '1 / sqrt(pi)'
+
+
+def test_mix_number_mult_symbols():
+    assert julia_code(3*x) == "3 * x"
+    assert julia_code(pi*x) == "pi * x"
+    assert julia_code(3/x) == "3 ./ x"
+    assert julia_code(pi/x) == "pi ./ x"
+    assert julia_code(x/3) == "x / 3"
+    assert julia_code(x/pi) == "x / pi"
+    assert julia_code(x*y) == "x .* y"
+    assert julia_code(3*x*y) == "3 * x .* y"
+    assert julia_code(3*pi*x*y) == "3 * pi * x .* y"
+    assert julia_code(x/y) == "x ./ y"
+    assert julia_code(3*x/y) == "3 * x ./ y"
+    assert julia_code(x*y/z) == "x .* y ./ z"
+    assert julia_code(x/y*z) == "x .* z ./ y"
+    assert julia_code(1/x/y) == "1 ./ (x .* y)"
+    assert julia_code(2*pi*x/y/z) == "2 * pi * x ./ (y .* z)"
+    assert julia_code(3*pi/x) == "3 * pi ./ x"
+    assert julia_code(S(3)/5) == "3 // 5"
+    assert julia_code(S(3)/5*x) == "(3 // 5) * x"
+    assert julia_code(x/y/z) == "x ./ (y .* z)"
+    assert julia_code((x+y)/z) == "(x + y) ./ z"
+    assert julia_code((x+y)/(z+x)) == "(x + y) ./ (x + z)"
+    assert julia_code((x+y)/EulerGamma) == "(x + y) / eulergamma"
+    assert julia_code(x/3/pi) == "x / (3 * pi)"
+    assert julia_code(S(3)/5*x*y/pi) == "(3 // 5) * x .* y / pi"
+
+
+def test_mix_number_pow_symbols():
+    assert julia_code(pi**3) == 'pi ^ 3'
+    assert julia_code(x**2) == 'x .^ 2'
+    assert julia_code(x**(pi**3)) == 'x .^ (pi ^ 3)'
+    assert julia_code(x**y) == 'x .^ y'
+    assert julia_code(x**(y**z)) == 'x .^ (y .^ z)'
+    assert julia_code((x**y)**z) == '(x .^ y) .^ z'
+
+
+def test_imag():
+    I = S('I')
+    assert julia_code(I) == "im"
+    assert julia_code(5*I) == "5im"
+    assert julia_code((S(3)/2)*I) == "(3 // 2) * im"
+    assert julia_code(3+4*I) == "3 + 4im"
+
+
+def test_constants():
+    assert julia_code(pi) == "pi"
+    assert julia_code(oo) == "Inf"
+    assert julia_code(-oo) == "-Inf"
+    assert julia_code(S.NegativeInfinity) == "-Inf"
+    assert julia_code(S.NaN) == "NaN"
+    assert julia_code(S.Exp1) == "e"
+    assert julia_code(exp(1)) == "e"
+
+
+def test_constants_other():
+    assert julia_code(2*GoldenRatio) == "2 * golden"
+    assert julia_code(2*Catalan) == "2 * catalan"
+    assert julia_code(2*EulerGamma) == "2 * eulergamma"
+
+
+def test_boolean():
+    assert julia_code(x & y) == "x && y"
+    assert julia_code(x | y) == "x || y"
+    assert julia_code(~x) == "!x"
+    assert julia_code(x & y & z) == "x && y && z"
+    assert julia_code(x | y | z) == "x || y || z"
+    assert julia_code((x & y) | z) == "z || x && y"
+    assert julia_code((x | y) & z) == "z && (x || y)"
+
+def test_sinc():
+    assert julia_code(sinc(x)) == 'sinc(x / pi)'
+    assert julia_code(sinc(x + 3)) == 'sinc((x + 3) / pi)'
+    assert julia_code(sinc(pi * (x + 3))) == 'sinc(x + 3)'
+
+def test_Matrices():
+    assert julia_code(Matrix(1, 1, [10])) == "[10]"
+    A = Matrix([[1, sin(x/2), abs(x)],
+                [0, 1, pi],
+                [0, exp(1), ceiling(x)]])
+    expected = ("[1 sin(x / 2)  abs(x);\n"
+                "0          1      pi;\n"
+                "0          e ceil(x)]")
+    assert julia_code(A) == expected
+    # row and columns
+    assert julia_code(A[:,0]) == "[1, 0, 0]"
+    assert julia_code(A[0,:]) == "[1 sin(x / 2) abs(x)]"
+    # empty matrices
+    assert julia_code(Matrix(0, 0, [])) == 'zeros(0, 0)'
+    assert julia_code(Matrix(0, 3, [])) == 'zeros(0, 3)'
+    # annoying to read but correct
+    assert julia_code(Matrix([[x, x - y, -y]])) == "[x x - y -y]"
+
+
+def test_vector_entries_hadamard():
+    # For a row or column, user might to use the other dimension
+    A = Matrix([[1, sin(2/x), 3*pi/x/5]])
+    assert julia_code(A) == "[1 sin(2 ./ x) (3 // 5) * pi ./ x]"
+    assert julia_code(A.T) == "[1, sin(2 ./ x), (3 // 5) * pi ./ x]"
+
+
+@XFAIL
+def test_Matrices_entries_not_hadamard():
+    # For Matrix with col >= 2, row >= 2, they need to be scalars
+    # FIXME: is it worth worrying about this?  Its not wrong, just
+    # leave it user's responsibility to put scalar data for x.
+    A = Matrix([[1, sin(2/x), 3*pi/x/5], [1, 2, x*y]])
+    expected = ("[1 sin(2/x) 3*pi/(5*x);\n"
+                "1        2        x*y]") # <- we give x.*y
+    assert julia_code(A) == expected
+
+
+def test_MatrixSymbol():
+    n = Symbol('n', integer=True)
+    A = MatrixSymbol('A', n, n)
+    B = MatrixSymbol('B', n, n)
+    assert julia_code(A*B) == "A * B"
+    assert julia_code(B*A) == "B * A"
+    assert julia_code(2*A*B) == "2 * A * B"
+    assert julia_code(B*2*A) == "2 * B * A"
+    assert julia_code(A*(B + 3*Identity(n))) == "A * (3 * eye(n) + B)"
+    assert julia_code(A**(x**2)) == "A ^ (x .^ 2)"
+    assert julia_code(A**3) == "A ^ 3"
+    assert julia_code(A**S.Half) == "A ^ (1 // 2)"
+
+
+def test_special_matrices():
+    assert julia_code(6*Identity(3)) == "6 * eye(3)"
+
+
+def test_containers():
+    assert julia_code([1, 2, 3, [4, 5, [6, 7]], 8, [9, 10], 11]) == \
+        "Any[1, 2, 3, Any[4, 5, Any[6, 7]], 8, Any[9, 10], 11]"
+    assert julia_code((1, 2, (3, 4))) == "(1, 2, (3, 4))"
+    assert julia_code([1]) == "Any[1]"
+    assert julia_code((1,)) == "(1,)"
+    assert julia_code(Tuple(*[1, 2, 3])) == "(1, 2, 3)"
+    assert julia_code((1, x*y, (3, x**2))) == "(1, x .* y, (3, x .^ 2))"
+    # scalar, matrix, empty matrix and empty list
+    assert julia_code((1, eye(3), Matrix(0, 0, []), [])) == "(1, [1 0 0;\n0 1 0;\n0 0 1], zeros(0, 0), Any[])"
+
+
+def test_julia_noninline():
+    source = julia_code((x+y)/Catalan, assign_to='me', inline=False)
+    expected = (
+        "const Catalan = %s\n"
+        "me = (x + y) / Catalan"
+    ) % Catalan.evalf(17)
+    assert source == expected
+
+
+def test_julia_piecewise():
+    expr = Piecewise((x, x < 1), (x**2, True))
+    assert julia_code(expr) == "((x < 1) ? (x) : (x .^ 2))"
+    assert julia_code(expr, assign_to="r") == (
+        "r = ((x < 1) ? (x) : (x .^ 2))")
+    assert julia_code(expr, assign_to="r", inline=False) == (
+        "if (x < 1)\n"
+        "    r = x\n"
+        "else\n"
+        "    r = x .^ 2\n"
+        "end")
+    expr = Piecewise((x**2, x < 1), (x**3, x < 2), (x**4, x < 3), (x**5, True))
+    expected = ("((x < 1) ? (x .^ 2) :\n"
+                "(x < 2) ? (x .^ 3) :\n"
+                "(x < 3) ? (x .^ 4) : (x .^ 5))")
+    assert julia_code(expr) == expected
+    assert julia_code(expr, assign_to="r") == "r = " + expected
+    assert julia_code(expr, assign_to="r", inline=False) == (
+        "if (x < 1)\n"
+        "    r = x .^ 2\n"
+        "elseif (x < 2)\n"
+        "    r = x .^ 3\n"
+        "elseif (x < 3)\n"
+        "    r = x .^ 4\n"
+        "else\n"
+        "    r = x .^ 5\n"
+        "end")
+    # Check that Piecewise without a True (default) condition error
+    expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0))
+    raises(ValueError, lambda: julia_code(expr))
+
+
+def test_julia_piecewise_times_const():
+    pw = Piecewise((x, x < 1), (x**2, True))
+    assert julia_code(2*pw) == "2 * ((x < 1) ? (x) : (x .^ 2))"
+    assert julia_code(pw/x) == "((x < 1) ? (x) : (x .^ 2)) ./ x"
+    assert julia_code(pw/(x*y)) == "((x < 1) ? (x) : (x .^ 2)) ./ (x .* y)"
+    assert julia_code(pw/3) == "((x < 1) ? (x) : (x .^ 2)) / 3"
+
+
+def test_julia_matrix_assign_to():
+    A = Matrix([[1, 2, 3]])
+    assert julia_code(A, assign_to='a') == "a = [1 2 3]"
+    A = Matrix([[1, 2], [3, 4]])
+    assert julia_code(A, assign_to='A') == "A = [1 2;\n3 4]"
+
+
+def test_julia_matrix_assign_to_more():
+    # assigning to Symbol or MatrixSymbol requires lhs/rhs match
+    A = Matrix([[1, 2, 3]])
+    B = MatrixSymbol('B', 1, 3)
+    C = MatrixSymbol('C', 2, 3)
+    assert julia_code(A, assign_to=B) == "B = [1 2 3]"
+    raises(ValueError, lambda: julia_code(A, assign_to=x))
+    raises(ValueError, lambda: julia_code(A, assign_to=C))
+
+
+def test_julia_matrix_1x1():
+    A = Matrix([[3]])
+    B = MatrixSymbol('B', 1, 1)
+    C = MatrixSymbol('C', 1, 2)
+    assert julia_code(A, assign_to=B) == "B = [3]"
+    # FIXME?
+    #assert julia_code(A, assign_to=x) == "x = [3]"
+    raises(ValueError, lambda: julia_code(A, assign_to=C))
+
+
+def test_julia_matrix_elements():
+    A = Matrix([[x, 2, x*y]])
+    assert julia_code(A[0, 0]**2 + A[0, 1] + A[0, 2]) == "x .^ 2 + x .* y + 2"
+    A = MatrixSymbol('AA', 1, 3)
+    assert julia_code(A) == "AA"
+    assert julia_code(A[0, 0]**2 + sin(A[0,1]) + A[0,2]) == \
+           "sin(AA[1,2]) + AA[1,1] .^ 2 + AA[1,3]"
+    assert julia_code(sum(A)) == "AA[1,1] + AA[1,2] + AA[1,3]"
+
+
+def test_julia_boolean():
+    assert julia_code(True) == "true"
+    assert julia_code(S.true) == "true"
+    assert julia_code(False) == "false"
+    assert julia_code(S.false) == "false"
+
+
+def test_julia_not_supported():
+    with raises(NotImplementedError):
+        julia_code(S.ComplexInfinity)
+
+    f = Function('f')
+    assert julia_code(f(x).diff(x), strict=False) == (
+        "# Not supported in Julia:\n"
+        "# Derivative\n"
+        "Derivative(f(x), x)"
+    )
+
+
+def test_trick_indent_with_end_else_words():
+    # words starting with "end" or "else" do not confuse the indenter
+    t1 = S('endless')
+    t2 = S('elsewhere')
+    pw = Piecewise((t1, x < 0), (t2, x <= 1), (1, True))
+    assert julia_code(pw, inline=False) == (
+        "if (x < 0)\n"
+        "    endless\n"
+        "elseif (x <= 1)\n"
+        "    elsewhere\n"
+        "else\n"
+        "    1\n"
+        "end")
+
+
+def test_haramard():
+    A = MatrixSymbol('A', 3, 3)
+    B = MatrixSymbol('B', 3, 3)
+    v = MatrixSymbol('v', 3, 1)
+    h = MatrixSymbol('h', 1, 3)
+    C = HadamardProduct(A, B)
+    assert julia_code(C) == "A .* B"
+    assert julia_code(C*v) == "(A .* B) * v"
+    assert julia_code(h*C*v) == "h * (A .* B) * v"
+    assert julia_code(C*A) == "(A .* B) * A"
+    # mixing Hadamard and scalar strange b/c we vectorize scalars
+    assert julia_code(C*x*y) == "(x .* y) * (A .* B)"
+
+
+def test_sparse():
+    M = SparseMatrix(5, 6, {})
+    M[2, 2] = 10
+    M[1, 2] = 20
+    M[1, 3] = 22
+    M[0, 3] = 30
+    M[3, 0] = x*y
+    assert julia_code(M) == (
+        "sparse([4, 2, 3, 1, 2], [1, 3, 3, 4, 4], [x .* y, 20, 10, 30, 22], 5, 6)"
+    )
+
+
+def test_specfun():
+    n = Symbol('n')
+    for f in [besselj, bessely, besseli, besselk]:
+        assert julia_code(f(n, x)) == f.__name__ + '(n, x)'
+    for f in [airyai, airyaiprime, airybi, airybiprime]:
+        assert julia_code(f(x)) == f.__name__ + '(x)'
+    assert julia_code(hankel1(n, x)) == 'hankelh1(n, x)'
+    assert julia_code(hankel2(n, x)) == 'hankelh2(n, x)'
+    assert julia_code(jn(n, x)) == 'sqrt(2) * sqrt(pi) * sqrt(1 ./ x) .* besselj(n + 1 // 2, x) / 2'
+    assert julia_code(yn(n, x)) == 'sqrt(2) * sqrt(pi) * sqrt(1 ./ x) .* bessely(n + 1 // 2, x) / 2'
+
+
+def test_MatrixElement_printing():
+    # test cases for issue #11821
+    A = MatrixSymbol("A", 1, 3)
+    B = MatrixSymbol("B", 1, 3)
+    C = MatrixSymbol("C", 1, 3)
+
+    assert(julia_code(A[0, 0]) == "A[1,1]")
+    assert(julia_code(3 * A[0, 0]) == "3 * A[1,1]")
+
+    F = C[0, 0].subs(C, A - B)
+    assert(julia_code(F) == "(A - B)[1,1]")
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_lambdarepr.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_lambdarepr.py
new file mode 100644
index 0000000000000000000000000000000000000000..94e09ada7a9ce7d01667edd8fc6ec35ebfbb9639
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_lambdarepr.py
@@ -0,0 +1,246 @@
+from sympy.concrete.summations import Sum
+from sympy.core.expr import Expr
+from sympy.core.symbol import symbols
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.functions.elementary.trigonometric import sin
+from sympy.matrices.dense import MutableDenseMatrix as Matrix
+from sympy.sets.sets import Interval
+from sympy.utilities.lambdify import lambdify
+from sympy.testing.pytest import raises
+
+from sympy.printing.tensorflow import TensorflowPrinter
+from sympy.printing.lambdarepr import lambdarepr, LambdaPrinter, NumExprPrinter
+
+
+x, y, z = symbols("x,y,z")
+i, a, b = symbols("i,a,b")
+j, c, d = symbols("j,c,d")
+
+
+def test_basic():
+    assert lambdarepr(x*y) == "x*y"
+    assert lambdarepr(x + y) in ["y + x", "x + y"]
+    assert lambdarepr(x**y) == "x**y"
+
+
+def test_matrix():
+    # Test printing a Matrix that has an element that is printed differently
+    # with the LambdaPrinter than with the StrPrinter.
+    e = x % 2
+    assert lambdarepr(e) != str(e)
+    assert lambdarepr(Matrix([e])) == 'ImmutableDenseMatrix([[x % 2]])'
+
+
+def test_piecewise():
+    # In each case, test eval() the lambdarepr() to make sure there are a
+    # correct number of parentheses. It will give a SyntaxError if there aren't.
+
+    h = "lambda x: "
+
+    p = Piecewise((x, x < 0))
+    l = lambdarepr(p)
+    eval(h + l)
+    assert l == "((x) if (x < 0) else None)"
+
+    p = Piecewise(
+        (1, x < 1),
+        (2, x < 2),
+        (0, True)
+    )
+    l = lambdarepr(p)
+    eval(h + l)
+    assert l == "((1) if (x < 1) else (2) if (x < 2) else (0))"
+
+    p = Piecewise(
+        (1, x < 1),
+        (2, x < 2),
+    )
+    l = lambdarepr(p)
+    eval(h + l)
+    assert l == "((1) if (x < 1) else (2) if (x < 2) else None)"
+
+    p = Piecewise(
+        (x, x < 1),
+        (x**2, Interval(3, 4, True, False).contains(x)),
+        (0, True),
+    )
+    l = lambdarepr(p)
+    eval(h + l)
+    assert l == "((x) if (x < 1) else (x**2) if (((x <= 4)) and ((x > 3))) else (0))"
+
+    p = Piecewise(
+        (x**2, x < 0),
+        (x, x < 1),
+        (2 - x, x >= 1),
+        (0, True), evaluate=False
+    )
+    l = lambdarepr(p)
+    eval(h + l)
+    assert l == "((x**2) if (x < 0) else (x) if (x < 1)"\
+                                " else (2 - x) if (x >= 1) else (0))"
+
+    p = Piecewise(
+        (x**2, x < 0),
+        (x, x < 1),
+        (2 - x, x >= 1), evaluate=False
+    )
+    l = lambdarepr(p)
+    eval(h + l)
+    assert l == "((x**2) if (x < 0) else (x) if (x < 1)"\
+                    " else (2 - x) if (x >= 1) else None)"
+
+    p = Piecewise(
+        (1, x >= 1),
+        (2, x >= 2),
+        (3, x >= 3),
+        (4, x >= 4),
+        (5, x >= 5),
+        (6, True)
+    )
+    l = lambdarepr(p)
+    eval(h + l)
+    assert l == "((1) if (x >= 1) else (2) if (x >= 2) else (3) if (x >= 3)"\
+                        " else (4) if (x >= 4) else (5) if (x >= 5) else (6))"
+
+    p = Piecewise(
+        (1, x <= 1),
+        (2, x <= 2),
+        (3, x <= 3),
+        (4, x <= 4),
+        (5, x <= 5),
+        (6, True)
+    )
+    l = lambdarepr(p)
+    eval(h + l)
+    assert l == "((1) if (x <= 1) else (2) if (x <= 2) else (3) if (x <= 3)"\
+                            " else (4) if (x <= 4) else (5) if (x <= 5) else (6))"
+
+    p = Piecewise(
+        (1, x > 1),
+        (2, x > 2),
+        (3, x > 3),
+        (4, x > 4),
+        (5, x > 5),
+        (6, True)
+    )
+    l = lambdarepr(p)
+    eval(h + l)
+    assert l =="((1) if (x > 1) else (2) if (x > 2) else (3) if (x > 3)"\
+                            " else (4) if (x > 4) else (5) if (x > 5) else (6))"
+
+    p = Piecewise(
+        (1, x < 1),
+        (2, x < 2),
+        (3, x < 3),
+        (4, x < 4),
+        (5, x < 5),
+        (6, True)
+    )
+    l = lambdarepr(p)
+    eval(h + l)
+    assert l == "((1) if (x < 1) else (2) if (x < 2) else (3) if (x < 3)"\
+                            " else (4) if (x < 4) else (5) if (x < 5) else (6))"
+
+    p = Piecewise(
+        (Piecewise(
+            (1, x > 0),
+            (2, True)
+        ), y > 0),
+        (3, True)
+    )
+    l = lambdarepr(p)
+    eval(h + l)
+    assert l == "((((1) if (x > 0) else (2))) if (y > 0) else (3))"
+
+
+def test_sum__1():
+    # In each case, test eval() the lambdarepr() to make sure that
+    # it evaluates to the same results as the symbolic expression
+    s = Sum(x ** i, (i, a, b))
+    l = lambdarepr(s)
+    assert l == "(builtins.sum(x**i for i in range(a, b+1)))"
+
+    args = x, a, b
+    f = lambdify(args, s)
+    v = 2, 3, 8
+    assert f(*v) == s.subs(zip(args, v)).doit()
+
+def test_sum__2():
+    s = Sum(i * x, (i, a, b))
+    l = lambdarepr(s)
+    assert l == "(builtins.sum(i*x for i in range(a, b+1)))"
+
+    args = x, a, b
+    f = lambdify(args, s)
+    v = 2, 3, 8
+    assert f(*v) == s.subs(zip(args, v)).doit()
+
+
+def test_multiple_sums():
+    s = Sum(i * x + j, (i, a, b), (j, c, d))
+
+    l = lambdarepr(s)
+    assert l == "(builtins.sum(i*x + j for j in range(c, d+1) for i in range(a, b+1)))"
+
+    args = x, a, b, c, d
+    f = lambdify(args, s)
+    vals = 2, 3, 4, 5, 6
+    f_ref = s.subs(zip(args, vals)).doit()
+    f_res = f(*vals)
+    assert f_res == f_ref
+
+
+def test_sqrt():
+    prntr = LambdaPrinter({'standard' : 'python3'})
+    assert prntr._print_Pow(sqrt(x), rational=False) == 'sqrt(x)'
+    assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)'
+
+
+def test_settings():
+    raises(TypeError, lambda: lambdarepr(sin(x), method="garbage"))
+
+
+def test_numexpr():
+    # test ITE rewrite as Piecewise
+    from sympy.logic.boolalg import ITE
+    expr = ITE(x > 0, True, False, evaluate=False)
+    assert NumExprPrinter().doprint(expr) == \
+           "numexpr.evaluate('where((x > 0), True, False)', truediv=True)"
+
+    from sympy.codegen.ast import Return, FunctionDefinition, Variable, Assignment
+    func_def = FunctionDefinition(None, 'foo', [Variable(x)], [Assignment(y,x), Return(y**2)])
+    expected = "def foo(x):\n"\
+               "    y = numexpr.evaluate('x', truediv=True)\n"\
+               "    return numexpr.evaluate('y**2', truediv=True)"
+    assert NumExprPrinter().doprint(func_def) == expected
+
+
+class CustomPrintedObject(Expr):
+    def _lambdacode(self, printer):
+        return 'lambda'
+
+    def _tensorflowcode(self, printer):
+        return 'tensorflow'
+
+    def _numpycode(self, printer):
+        return 'numpy'
+
+    def _numexprcode(self, printer):
+        return 'numexpr'
+
+    def _mpmathcode(self, printer):
+        return 'mpmath'
+
+
+def test_printmethod():
+    # In each case, printmethod is called to test
+    # its working
+
+    obj = CustomPrintedObject()
+    assert LambdaPrinter().doprint(obj) == 'lambda'
+    assert TensorflowPrinter().doprint(obj) == 'tensorflow'
+    assert NumExprPrinter().doprint(obj) == "numexpr.evaluate('numexpr', truediv=True)"
+
+    assert NumExprPrinter().doprint(Piecewise((y, x >= 0), (z, x < 0))) == \
+            "numexpr.evaluate('where((x >= 0), y, z)', truediv=True)"
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_latex.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_latex.py
new file mode 100644
index 0000000000000000000000000000000000000000..063611d09a923881cd94bd693f3f3f721535fd0c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_latex.py
@@ -0,0 +1,3164 @@
+from sympy import MatAdd, MatMul, Array
+from sympy.algebras.quaternion import Quaternion
+from sympy.calculus.accumulationbounds import AccumBounds
+from sympy.combinatorics.permutations import Cycle, Permutation, AppliedPermutation
+from sympy.concrete.products import Product
+from sympy.concrete.summations import Sum
+from sympy.core.containers import Tuple, Dict
+from sympy.core.expr import UnevaluatedExpr
+from sympy.core.function import (Derivative, Function, Lambda, Subs, diff)
+from sympy.core.mod import Mod
+from sympy.core.mul import Mul
+from sympy.core.numbers import (AlgebraicNumber, Float, I, Integer, Rational, oo, pi)
+from sympy.core.parameters import evaluate
+from sympy.core.power import Pow
+from sympy.core.relational import Eq, Ne
+from sympy.core.singleton import S
+from sympy.core.symbol import (Symbol, Wild, symbols)
+from sympy.functions.combinatorial.factorials import (FallingFactorial, RisingFactorial, binomial, factorial, factorial2, subfactorial)
+from sympy.functions.combinatorial.numbers import (bernoulli, bell, catalan, euler, genocchi,
+                                                   lucas, fibonacci, tribonacci, divisor_sigma, udivisor_sigma,
+                                                   mobius, primenu, primeomega,
+                                                   totient, reduced_totient)
+from sympy.functions.elementary.complexes import (Abs, arg, conjugate, im, polar_lift, re)
+from sympy.functions.elementary.exponential import (LambertW, exp, log)
+from sympy.functions.elementary.hyperbolic import (asinh, coth)
+from sympy.functions.elementary.integers import (ceiling, floor, frac)
+from sympy.functions.elementary.miscellaneous import (Max, Min, root, sqrt)
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.functions.elementary.trigonometric import (acsc, asin, cos, cot, sin, tan)
+from sympy.functions.special.beta_functions import beta
+from sympy.functions.special.delta_functions import (DiracDelta, Heaviside)
+from sympy.functions.special.elliptic_integrals import (elliptic_e, elliptic_f, elliptic_k, elliptic_pi)
+from sympy.functions.special.error_functions import (Chi, Ci, Ei, Shi, Si, expint)
+from sympy.functions.special.gamma_functions import (gamma, uppergamma)
+from sympy.functions.special.hyper import (hyper, meijerg)
+from sympy.functions.special.mathieu_functions import (mathieuc, mathieucprime, mathieus, mathieusprime)
+from sympy.functions.special.polynomials import (assoc_laguerre, assoc_legendre, chebyshevt, chebyshevu, gegenbauer, hermite, jacobi, laguerre, legendre)
+from sympy.functions.special.singularity_functions import SingularityFunction
+from sympy.functions.special.spherical_harmonics import (Ynm, Znm)
+from sympy.functions.special.tensor_functions import (KroneckerDelta, LeviCivita)
+from sympy.functions.special.zeta_functions import (dirichlet_eta, lerchphi, polylog, stieltjes, zeta)
+from sympy.integrals.integrals import Integral
+from sympy.integrals.transforms import (CosineTransform, FourierTransform, InverseCosineTransform, InverseFourierTransform, InverseLaplaceTransform, InverseMellinTransform, InverseSineTransform, LaplaceTransform, MellinTransform, SineTransform)
+from sympy.logic import Implies
+from sympy.logic.boolalg import (And, Or, Xor, Equivalent, false, Not, true)
+from sympy.matrices.dense import Matrix
+from sympy.matrices.expressions.kronecker import KroneckerProduct
+from sympy.matrices.expressions.matexpr import MatrixSymbol
+from sympy.matrices.expressions.permutation import PermutationMatrix
+from sympy.matrices.expressions.slice import MatrixSlice
+from sympy.matrices.expressions.dotproduct import DotProduct
+from sympy.physics.control.lti import TransferFunction, Series, Parallel, Feedback, TransferFunctionMatrix, MIMOSeries, MIMOParallel, MIMOFeedback
+from sympy.physics.quantum import Commutator, Operator
+from sympy.physics.quantum.trace import Tr
+from sympy.physics.units import meter, gibibyte, gram, microgram, second, milli, micro
+from sympy.polys.domains.integerring import ZZ
+from sympy.polys.fields import field
+from sympy.polys.polytools import Poly
+from sympy.polys.rings import ring
+from sympy.polys.rootoftools import (RootSum, rootof)
+from sympy.series.formal import fps
+from sympy.series.fourier import fourier_series
+from sympy.series.limits import Limit
+from sympy.series.order import Order
+from sympy.series.sequences import (SeqAdd, SeqFormula, SeqMul, SeqPer)
+from sympy.sets.conditionset import ConditionSet
+from sympy.sets.contains import Contains
+from sympy.sets.fancysets import (ComplexRegion, ImageSet, Range)
+from sympy.sets.ordinals import Ordinal, OrdinalOmega, OmegaPower
+from sympy.sets.powerset import PowerSet
+from sympy.sets.sets import (FiniteSet, Interval, Union, Intersection, Complement, SymmetricDifference, ProductSet)
+from sympy.sets.setexpr import SetExpr
+from sympy.stats.crv_types import Normal
+from sympy.stats.symbolic_probability import (Covariance, Expectation,
+                                              Probability, Variance)
+from sympy.tensor.array import (ImmutableDenseNDimArray,
+                                ImmutableSparseNDimArray,
+                                MutableSparseNDimArray,
+                                MutableDenseNDimArray,
+                                tensorproduct)
+from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayElement
+from sympy.tensor.indexed import (Idx, Indexed, IndexedBase)
+from sympy.tensor.toperators import PartialDerivative
+from sympy.vector import CoordSys3D, Cross, Curl, Dot, Divergence, Gradient, Laplacian
+
+
+from sympy.testing.pytest import (XFAIL, raises, _both_exp_pow,
+                                  warns_deprecated_sympy)
+from sympy.printing.latex import (latex, translate, greek_letters_set,
+                                  tex_greek_dictionary, multiline_latex,
+                                  latex_escape, LatexPrinter)
+
+import sympy as sym
+
+from sympy.abc import mu, tau
+
+
+class lowergamma(sym.lowergamma):
+    pass   # testing notation inheritance by a subclass with same name
+
+
+x, y, z, t, w, a, b, c, s, p = symbols('x y z t w a b c s p')
+k, m, n = symbols('k m n', integer=True)
+
+
+def test_printmethod():
+    class R(Abs):
+        def _latex(self, printer):
+            return "foo(%s)" % printer._print(self.args[0])
+    assert latex(R(x)) == r"foo(x)"
+
+    class R(Abs):
+        def _latex(self, printer):
+            return "foo"
+    assert latex(R(x)) == r"foo"
+
+
+def test_latex_basic():
+    assert latex(1 + x) == r"x + 1"
+    assert latex(x**2) == r"x^{2}"
+    assert latex(x**(1 + x)) == r"x^{x + 1}"
+    assert latex(x**3 + x + 1 + x**2) == r"x^{3} + x^{2} + x + 1"
+
+    assert latex(2*x*y) == r"2 x y"
+    assert latex(2*x*y, mul_symbol='dot') == r"2 \cdot x \cdot y"
+    assert latex(3*x**2*y, mul_symbol='\\,') == r"3\,x^{2}\,y"
+    assert latex(1.5*3**x, mul_symbol='\\,') == r"1.5 \cdot 3^{x}"
+
+    assert latex(x**S.Half**5) == r"\sqrt[32]{x}"
+    assert latex(Mul(S.Half, x**2, -5, evaluate=False)) == r"\frac{1}{2} x^{2} \left(-5\right)"
+    assert latex(Mul(S.Half, x**2, 5, evaluate=False)) == r"\frac{1}{2} x^{2} \cdot 5"
+    assert latex(Mul(-5, -5, evaluate=False)) == r"\left(-5\right) \left(-5\right)"
+    assert latex(Mul(5, -5, evaluate=False)) == r"5 \left(-5\right)"
+    assert latex(Mul(S.Half, -5, S.Half, evaluate=False)) == r"\frac{1}{2} \left(-5\right) \frac{1}{2}"
+    assert latex(Mul(5, I, 5, evaluate=False)) == r"5 i 5"
+    assert latex(Mul(5, I, -5, evaluate=False)) == r"5 i \left(-5\right)"
+    assert latex(Mul(Pow(x, 2), S.Half*x + 1)) == r"x^{2} \left(\frac{x}{2} + 1\right)"
+    assert latex(Mul(Pow(x, 3), Rational(2, 3)*x + 1)) == r"x^{3} \left(\frac{2 x}{3} + 1\right)"
+    assert latex(Mul(Pow(x, 11), 2*x + 1)) == r"x^{11} \left(2 x + 1\right)"
+
+    assert latex(Mul(0, 1, evaluate=False)) == r'0 \cdot 1'
+    assert latex(Mul(1, 0, evaluate=False)) == r'1 \cdot 0'
+    assert latex(Mul(1, 1, evaluate=False)) == r'1 \cdot 1'
+    assert latex(Mul(-1, 1, evaluate=False)) == r'\left(-1\right) 1'
+    assert latex(Mul(1, 1, 1, evaluate=False)) == r'1 \cdot 1 \cdot 1'
+    assert latex(Mul(1, 2, evaluate=False)) == r'1 \cdot 2'
+    assert latex(Mul(1, S.Half, evaluate=False)) == r'1 \cdot \frac{1}{2}'
+    assert latex(Mul(1, 1, S.Half, evaluate=False)) == \
+        r'1 \cdot 1 \cdot \frac{1}{2}'
+    assert latex(Mul(1, 1, 2, 3, x, evaluate=False)) == \
+        r'1 \cdot 1 \cdot 2 \cdot 3 x'
+    assert latex(Mul(1, -1, evaluate=False)) == r'1 \left(-1\right)'
+    assert latex(Mul(4, 3, 2, 1, 0, y, x, evaluate=False)) == \
+        r'4 \cdot 3 \cdot 2 \cdot 1 \cdot 0 y x'
+    assert latex(Mul(4, 3, 2, 1+z, 0, y, x, evaluate=False)) == \
+        r'4 \cdot 3 \cdot 2 \left(z + 1\right) 0 y x'
+    assert latex(Mul(Rational(2, 3), Rational(5, 7), evaluate=False)) == \
+        r'\frac{2}{3} \cdot \frac{5}{7}'
+
+    assert latex(1/x) == r"\frac{1}{x}"
+    assert latex(1/x, fold_short_frac=True) == r"1 / x"
+    assert latex(-S(3)/2) == r"- \frac{3}{2}"
+    assert latex(-S(3)/2, fold_short_frac=True) == r"- 3 / 2"
+    assert latex(1/x**2) == r"\frac{1}{x^{2}}"
+    assert latex(1/(x + y)/2) == r"\frac{1}{2 \left(x + y\right)}"
+    assert latex(x/2) == r"\frac{x}{2}"
+    assert latex(x/2, fold_short_frac=True) == r"x / 2"
+    assert latex((x + y)/(2*x)) == r"\frac{x + y}{2 x}"
+    assert latex((x + y)/(2*x), fold_short_frac=True) == \
+        r"\left(x + y\right) / 2 x"
+    assert latex((x + y)/(2*x), long_frac_ratio=0) == \
+        r"\frac{1}{2 x} \left(x + y\right)"
+    assert latex((x + y)/x) == r"\frac{x + y}{x}"
+    assert latex((x + y)/x, long_frac_ratio=3) == r"\frac{x + y}{x}"
+    assert latex((2*sqrt(2)*x)/3) == r"\frac{2 \sqrt{2} x}{3}"
+    assert latex((2*sqrt(2)*x)/3, long_frac_ratio=2) == \
+        r"\frac{2 x}{3} \sqrt{2}"
+    assert latex(binomial(x, y)) == r"{\binom{x}{y}}"
+
+    x_star = Symbol('x^*')
+    f = Function('f')
+    assert latex(x_star**2) == r"\left(x^{*}\right)^{2}"
+    assert latex(x_star**2, parenthesize_super=False) == r"{x^{*}}^{2}"
+    assert latex(Derivative(f(x_star), x_star,2)) == r"\frac{d^{2}}{d \left(x^{*}\right)^{2}} f{\left(x^{*} \right)}"
+    assert latex(Derivative(f(x_star), x_star,2), parenthesize_super=False) == r"\frac{d^{2}}{d {x^{*}}^{2}} f{\left(x^{*} \right)}"
+
+    assert latex(2*Integral(x, x)/3) == r"\frac{2 \int x\, dx}{3}"
+    assert latex(2*Integral(x, x)/3, fold_short_frac=True) == \
+        r"\left(2 \int x\, dx\right) / 3"
+
+    assert latex(sqrt(x)) == r"\sqrt{x}"
+    assert latex(x**Rational(1, 3)) == r"\sqrt[3]{x}"
+    assert latex(x**Rational(1, 3), root_notation=False) == r"x^{\frac{1}{3}}"
+    assert latex(sqrt(x)**3) == r"x^{\frac{3}{2}}"
+    assert latex(sqrt(x), itex=True) == r"\sqrt{x}"
+    assert latex(x**Rational(1, 3), itex=True) == r"\root{3}{x}"
+    assert latex(sqrt(x)**3, itex=True) == r"x^{\frac{3}{2}}"
+    assert latex(x**Rational(3, 4)) == r"x^{\frac{3}{4}}"
+    assert latex(x**Rational(3, 4), fold_frac_powers=True) == r"x^{3/4}"
+    assert latex((x + 1)**Rational(3, 4)) == \
+        r"\left(x + 1\right)^{\frac{3}{4}}"
+    assert latex((x + 1)**Rational(3, 4), fold_frac_powers=True) == \
+        r"\left(x + 1\right)^{3/4}"
+    assert latex(AlgebraicNumber(sqrt(2))) == r"\sqrt{2}"
+    assert latex(AlgebraicNumber(sqrt(2), [3, -7])) == r"-7 + 3 \sqrt{2}"
+    assert latex(AlgebraicNumber(sqrt(2), alias='alpha')) == r"\alpha"
+    assert latex(AlgebraicNumber(sqrt(2), [3, -7], alias='alpha')) == \
+        r"3 \alpha - 7"
+    assert latex(AlgebraicNumber(2**(S(1)/3), [1, 3, -7], alias='beta')) == \
+        r"\beta^{2} + 3 \beta - 7"
+
+    k = ZZ.cyclotomic_field(5)
+    assert latex(k.ext.field_element([1, 2, 3, 4])) == \
+        r"\zeta^{3} + 2 \zeta^{2} + 3 \zeta + 4"
+    assert latex(k.ext.field_element([1, 2, 3, 4]), order='old') == \
+        r"4 + 3 \zeta + 2 \zeta^{2} + \zeta^{3}"
+    assert latex(k.primes_above(19)[0]) == \
+        r"\left(19, \zeta^{2} + 5 \zeta + 1\right)"
+    assert latex(k.primes_above(19)[0], order='old') == \
+           r"\left(19, 1 + 5 \zeta + \zeta^{2}\right)"
+    assert latex(k.primes_above(7)[0]) == r"\left(7\right)"
+
+    assert latex(1.5e20*x) == r"1.5 \cdot 10^{20} x"
+    assert latex(1.5e20*x, mul_symbol='dot') == r"1.5 \cdot 10^{20} \cdot x"
+    assert latex(1.5e20*x, mul_symbol='times') == \
+        r"1.5 \times 10^{20} \times x"
+
+    assert latex(1/sin(x)) == r"\frac{1}{\sin{\left(x \right)}}"
+    assert latex(sin(x)**-1) == r"\frac{1}{\sin{\left(x \right)}}"
+    assert latex(sin(x)**Rational(3, 2)) == \
+        r"\sin^{\frac{3}{2}}{\left(x \right)}"
+    assert latex(sin(x)**Rational(3, 2), fold_frac_powers=True) == \
+        r"\sin^{3/2}{\left(x \right)}"
+
+    assert latex(~x) == r"\neg x"
+    assert latex(x & y) == r"x \wedge y"
+    assert latex(x & y & z) == r"x \wedge y \wedge z"
+    assert latex(x | y) == r"x \vee y"
+    assert latex(x | y | z) == r"x \vee y \vee z"
+    assert latex((x & y) | z) == r"z \vee \left(x \wedge y\right)"
+    assert latex(Implies(x, y)) == r"x \Rightarrow y"
+    assert latex(~(x >> ~y)) == r"x \not\Rightarrow \neg y"
+    assert latex(Implies(Or(x,y), z)) == r"\left(x \vee y\right) \Rightarrow z"
+    assert latex(Implies(z, Or(x,y))) == r"z \Rightarrow \left(x \vee y\right)"
+    assert latex(~(x & y)) == r"\neg \left(x \wedge y\right)"
+
+    assert latex(~x, symbol_names={x: "x_i"}) == r"\neg x_i"
+    assert latex(x & y, symbol_names={x: "x_i", y: "y_i"}) == \
+        r"x_i \wedge y_i"
+    assert latex(x & y & z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \
+        r"x_i \wedge y_i \wedge z_i"
+    assert latex(x | y, symbol_names={x: "x_i", y: "y_i"}) == r"x_i \vee y_i"
+    assert latex(x | y | z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \
+        r"x_i \vee y_i \vee z_i"
+    assert latex((x & y) | z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \
+        r"z_i \vee \left(x_i \wedge y_i\right)"
+    assert latex(Implies(x, y), symbol_names={x: "x_i", y: "y_i"}) == \
+        r"x_i \Rightarrow y_i"
+    assert latex(Pow(Rational(1, 3), -1, evaluate=False)) == r"\frac{1}{\frac{1}{3}}"
+    assert latex(Pow(Rational(1, 3), -2, evaluate=False)) == r"\frac{1}{(\frac{1}{3})^{2}}"
+    assert latex(Pow(Integer(1)/100, -1, evaluate=False)) == r"\frac{1}{\frac{1}{100}}"
+
+    p = Symbol('p', positive=True)
+    assert latex(exp(-p)*log(p)) == r"e^{- p} \log{\left(p \right)}"
+
+    assert latex(Pow(Rational(2, 3), -1, evaluate=False)) == r'\frac{1}{\frac{2}{3}}'
+    assert latex(Pow(Rational(4, 3), -1, evaluate=False)) == r'\frac{1}{\frac{4}{3}}'
+    assert latex(Pow(Rational(-3, 4), -1, evaluate=False)) == r'\frac{1}{- \frac{3}{4}}'
+    assert latex(Pow(Rational(-4, 4), -1, evaluate=False)) == r'\frac{1}{-1}'
+    assert latex(Pow(Rational(1, 3), -1, evaluate=False)) == r'\frac{1}{\frac{1}{3}}'
+    assert latex(Pow(Rational(-1, 3), -1, evaluate=False)) == r'\frac{1}{- \frac{1}{3}}'
+
+
+def test_latex_builtins():
+    assert latex(True) == r"\text{True}"
+    assert latex(False) == r"\text{False}"
+    assert latex(None) == r"\text{None}"
+    assert latex(true) == r"\text{True}"
+    assert latex(false) == r'\text{False}'
+
+
+def test_latex_SingularityFunction():
+    assert latex(SingularityFunction(x, 4, 5)) == \
+        r"{\left\langle x - 4 \right\rangle}^{5}"
+    assert latex(SingularityFunction(x, -3, 4)) == \
+        r"{\left\langle x + 3 \right\rangle}^{4}"
+    assert latex(SingularityFunction(x, 0, 4)) == \
+        r"{\left\langle x \right\rangle}^{4}"
+    assert latex(SingularityFunction(x, a, n)) == \
+        r"{\left\langle - a + x \right\rangle}^{n}"
+    assert latex(SingularityFunction(x, 4, -2)) == \
+        r"{\left\langle x - 4 \right\rangle}^{-2}"
+    assert latex(SingularityFunction(x, 4, -1)) == \
+        r"{\left\langle x - 4 \right\rangle}^{-1}"
+
+    assert latex(SingularityFunction(x, 4, 5)**3) == \
+        r"{\left({\langle x - 4 \rangle}^{5}\right)}^{3}"
+    assert latex(SingularityFunction(x, -3, 4)**3) == \
+        r"{\left({\langle x + 3 \rangle}^{4}\right)}^{3}"
+    assert latex(SingularityFunction(x, 0, 4)**3) == \
+        r"{\left({\langle x \rangle}^{4}\right)}^{3}"
+    assert latex(SingularityFunction(x, a, n)**3) == \
+        r"{\left({\langle - a + x \rangle}^{n}\right)}^{3}"
+    assert latex(SingularityFunction(x, 4, -2)**3) == \
+        r"{\left({\langle x - 4 \rangle}^{-2}\right)}^{3}"
+    assert latex((SingularityFunction(x, 4, -1)**3)**3) == \
+        r"{\left({\langle x - 4 \rangle}^{-1}\right)}^{9}"
+
+
+def test_latex_cycle():
+    assert latex(Cycle(1, 2, 4)) == r"\left( 1\; 2\; 4\right)"
+    assert latex(Cycle(1, 2)(4, 5, 6)) == \
+        r"\left( 1\; 2\right)\left( 4\; 5\; 6\right)"
+    assert latex(Cycle()) == r"\left( \right)"
+
+
+def test_latex_permutation():
+    assert latex(Permutation(1, 2, 4)) == r"\left( 1\; 2\; 4\right)"
+    assert latex(Permutation(1, 2)(4, 5, 6)) == \
+        r"\left( 1\; 2\right)\left( 4\; 5\; 6\right)"
+    assert latex(Permutation()) == r"\left( \right)"
+    assert latex(Permutation(2, 4)*Permutation(5)) == \
+        r"\left( 2\; 4\right)\left( 5\right)"
+    assert latex(Permutation(5)) == r"\left( 5\right)"
+
+    assert latex(Permutation(0, 1), perm_cyclic=False) == \
+        r"\begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}"
+    assert latex(Permutation(0, 1)(2, 3), perm_cyclic=False) == \
+        r"\begin{pmatrix} 0 & 1 & 2 & 3 \\ 1 & 0 & 3 & 2 \end{pmatrix}"
+    assert latex(Permutation(), perm_cyclic=False) == \
+        r"\left( \right)"
+
+    with warns_deprecated_sympy():
+        old_print_cyclic = Permutation.print_cyclic
+        Permutation.print_cyclic = False
+        assert latex(Permutation(0, 1)(2, 3)) == \
+            r"\begin{pmatrix} 0 & 1 & 2 & 3 \\ 1 & 0 & 3 & 2 \end{pmatrix}"
+        Permutation.print_cyclic = old_print_cyclic
+
+def test_latex_Float():
+    assert latex(Float(1.0e100)) == r"1.0 \cdot 10^{100}"
+    assert latex(Float(1.0e-100)) == r"1.0 \cdot 10^{-100}"
+    assert latex(Float(1.0e-100), mul_symbol="times") == \
+        r"1.0 \times 10^{-100}"
+    assert latex(Float('10000.0'), full_prec=False, min=-2, max=2) == \
+        r"1.0 \cdot 10^{4}"
+    assert latex(Float('10000.0'), full_prec=False, min=-2, max=4) == \
+        r"1.0 \cdot 10^{4}"
+    assert latex(Float('10000.0'), full_prec=False, min=-2, max=5) == \
+        r"10000.0"
+    assert latex(Float('0.099999'), full_prec=True,  min=-2, max=5) == \
+        r"9.99990000000000 \cdot 10^{-2}"
+
+
+def test_latex_vector_expressions():
+    A = CoordSys3D('A')
+
+    assert latex(Cross(A.i, A.j*A.x*3+A.k)) == \
+        r"\mathbf{\hat{i}_{A}} \times \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}} + \mathbf{\hat{k}_{A}}\right)"
+    assert latex(Cross(A.i, A.j)) == \
+        r"\mathbf{\hat{i}_{A}} \times \mathbf{\hat{j}_{A}}"
+    assert latex(x*Cross(A.i, A.j)) == \
+        r"x \left(\mathbf{\hat{i}_{A}} \times \mathbf{\hat{j}_{A}}\right)"
+    assert latex(Cross(x*A.i, A.j)) == \
+        r'- \mathbf{\hat{j}_{A}} \times \left(\left(x\right)\mathbf{\hat{i}_{A}}\right)'
+
+    assert latex(Curl(3*A.x*A.j)) == \
+        r"\nabla\times \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)"
+    assert latex(Curl(3*A.x*A.j+A.i)) == \
+        r"\nabla\times \left(\mathbf{\hat{i}_{A}} + \left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)"
+    assert latex(Curl(3*x*A.x*A.j)) == \
+        r"\nabla\times \left(\left(3 \mathbf{{x}_{A}} x\right)\mathbf{\hat{j}_{A}}\right)"
+    assert latex(x*Curl(3*A.x*A.j)) == \
+        r"x \left(\nabla\times \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)\right)"
+
+    assert latex(Divergence(3*A.x*A.j+A.i)) == \
+        r"\nabla\cdot \left(\mathbf{\hat{i}_{A}} + \left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)"
+    assert latex(Divergence(3*A.x*A.j)) == \
+        r"\nabla\cdot \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)"
+    assert latex(x*Divergence(3*A.x*A.j)) == \
+        r"x \left(\nabla\cdot \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)\right)"
+
+    assert latex(Dot(A.i, A.j*A.x*3+A.k)) == \
+        r"\mathbf{\hat{i}_{A}} \cdot \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}} + \mathbf{\hat{k}_{A}}\right)"
+    assert latex(Dot(A.i, A.j)) == \
+        r"\mathbf{\hat{i}_{A}} \cdot \mathbf{\hat{j}_{A}}"
+    assert latex(Dot(x*A.i, A.j)) == \
+        r"\mathbf{\hat{j}_{A}} \cdot \left(\left(x\right)\mathbf{\hat{i}_{A}}\right)"
+    assert latex(x*Dot(A.i, A.j)) == \
+        r"x \left(\mathbf{\hat{i}_{A}} \cdot \mathbf{\hat{j}_{A}}\right)"
+
+    assert latex(Gradient(A.x)) == r"\nabla \mathbf{{x}_{A}}"
+    assert latex(Gradient(A.x + 3*A.y)) == \
+        r"\nabla \left(\mathbf{{x}_{A}} + 3 \mathbf{{y}_{A}}\right)"
+    assert latex(x*Gradient(A.x)) == r"x \left(\nabla \mathbf{{x}_{A}}\right)"
+    assert latex(Gradient(x*A.x)) == r"\nabla \left(\mathbf{{x}_{A}} x\right)"
+
+    assert latex(Laplacian(A.x)) == r"\Delta \mathbf{{x}_{A}}"
+    assert latex(Laplacian(A.x + 3*A.y)) == \
+        r"\Delta \left(\mathbf{{x}_{A}} + 3 \mathbf{{y}_{A}}\right)"
+    assert latex(x*Laplacian(A.x)) == r"x \left(\Delta \mathbf{{x}_{A}}\right)"
+    assert latex(Laplacian(x*A.x)) == r"\Delta \left(\mathbf{{x}_{A}} x\right)"
+
+def test_latex_symbols():
+    Gamma, lmbda, rho = symbols('Gamma, lambda, rho')
+    tau, Tau, TAU, taU = symbols('tau, Tau, TAU, taU')
+    assert latex(tau) == r"\tau"
+    assert latex(Tau) == r"\mathrm{T}"
+    assert latex(TAU) == r"\tau"
+    assert latex(taU) == r"\tau"
+    # Check that all capitalized greek letters are handled explicitly
+    capitalized_letters = {l.capitalize() for l in greek_letters_set}
+    assert len(capitalized_letters - set(tex_greek_dictionary.keys())) == 0
+    assert latex(Gamma + lmbda) == r"\Gamma + \lambda"
+    assert latex(Gamma * lmbda) == r"\Gamma \lambda"
+    assert latex(Symbol('q1')) == r"q_{1}"
+    assert latex(Symbol('q21')) == r"q_{21}"
+    assert latex(Symbol('epsilon0')) == r"\epsilon_{0}"
+    assert latex(Symbol('omega1')) == r"\omega_{1}"
+    assert latex(Symbol('91')) == r"91"
+    assert latex(Symbol('alpha_new')) == r"\alpha_{new}"
+    assert latex(Symbol('C^orig')) == r"C^{orig}"
+    assert latex(Symbol('x^alpha')) == r"x^{\alpha}"
+    assert latex(Symbol('beta^alpha')) == r"\beta^{\alpha}"
+    assert latex(Symbol('e^Alpha')) == r"e^{\mathrm{A}}"
+    assert latex(Symbol('omega_alpha^beta')) == r"\omega^{\beta}_{\alpha}"
+    assert latex(Symbol('omega') ** Symbol('beta')) == r"\omega^{\beta}"
+
+
+@XFAIL
+def test_latex_symbols_failing():
+    rho, mass, volume = symbols('rho, mass, volume')
+    assert latex(
+        volume * rho == mass) == r"\rho \mathrm{volume} = \mathrm{mass}"
+    assert latex(volume / mass * rho == 1) == \
+        r"\rho \mathrm{volume} {\mathrm{mass}}^{(-1)} = 1"
+    assert latex(mass**3 * volume**3) == \
+        r"{\mathrm{mass}}^{3} \cdot {\mathrm{volume}}^{3}"
+
+
+@_both_exp_pow
+def test_latex_functions():
+    assert latex(exp(x)) == r"e^{x}"
+    assert latex(exp(1) + exp(2)) == r"e + e^{2}"
+
+    f = Function('f')
+    assert latex(f(x)) == r'f{\left(x \right)}'
+    assert latex(f) == r'f'
+
+    g = Function('g')
+    assert latex(g(x, y)) == r'g{\left(x,y \right)}'
+    assert latex(g) == r'g'
+
+    h = Function('h')
+    assert latex(h(x, y, z)) == r'h{\left(x,y,z \right)}'
+    assert latex(h) == r'h'
+
+    Li = Function('Li')
+    assert latex(Li) == r'\operatorname{Li}'
+    assert latex(Li(x)) == r'\operatorname{Li}{\left(x \right)}'
+
+    mybeta = Function('beta')
+    # not to be confused with the beta function
+    assert latex(mybeta(x, y, z)) == r"\beta{\left(x,y,z \right)}"
+    assert latex(beta(x, y)) == r'\operatorname{B}\left(x, y\right)'
+    assert latex(beta(x, evaluate=False)) == r'\operatorname{B}\left(x, x\right)'
+    assert latex(beta(x, y)**2) == r'\operatorname{B}^{2}\left(x, y\right)'
+    assert latex(mybeta(x)) == r"\beta{\left(x \right)}"
+    assert latex(mybeta) == r"\beta"
+
+    g = Function('gamma')
+    # not to be confused with the gamma function
+    assert latex(g(x, y, z)) == r"\gamma{\left(x,y,z \right)}"
+    assert latex(g(x)) == r"\gamma{\left(x \right)}"
+    assert latex(g) == r"\gamma"
+
+    a_1 = Function('a_1')
+    assert latex(a_1) == r"a_{1}"
+    assert latex(a_1(x)) == r"a_{1}{\left(x \right)}"
+    assert latex(Function('a_1')) == r"a_{1}"
+
+    # Issue #16925
+    # multi letter function names
+    # > simple
+    assert latex(Function('ab')) == r"\operatorname{ab}"
+    assert latex(Function('ab1')) == r"\operatorname{ab}_{1}"
+    assert latex(Function('ab12')) == r"\operatorname{ab}_{12}"
+    assert latex(Function('ab_1')) == r"\operatorname{ab}_{1}"
+    assert latex(Function('ab_12')) == r"\operatorname{ab}_{12}"
+    assert latex(Function('ab_c')) == r"\operatorname{ab}_{c}"
+    assert latex(Function('ab_cd')) == r"\operatorname{ab}_{cd}"
+    # > with argument
+    assert latex(Function('ab')(Symbol('x'))) == r"\operatorname{ab}{\left(x \right)}"
+    assert latex(Function('ab1')(Symbol('x'))) == r"\operatorname{ab}_{1}{\left(x \right)}"
+    assert latex(Function('ab12')(Symbol('x'))) == r"\operatorname{ab}_{12}{\left(x \right)}"
+    assert latex(Function('ab_1')(Symbol('x'))) == r"\operatorname{ab}_{1}{\left(x \right)}"
+    assert latex(Function('ab_c')(Symbol('x'))) == r"\operatorname{ab}_{c}{\left(x \right)}"
+    assert latex(Function('ab_cd')(Symbol('x'))) == r"\operatorname{ab}_{cd}{\left(x \right)}"
+
+    # > with power
+    #   does not work on functions without brackets
+
+    # > with argument and power combined
+    assert latex(Function('ab')()**2) == r"\operatorname{ab}^{2}{\left( \right)}"
+    assert latex(Function('ab1')()**2) == r"\operatorname{ab}_{1}^{2}{\left( \right)}"
+    assert latex(Function('ab12')()**2) == r"\operatorname{ab}_{12}^{2}{\left( \right)}"
+    assert latex(Function('ab_1')()**2) == r"\operatorname{ab}_{1}^{2}{\left( \right)}"
+    assert latex(Function('ab_12')()**2) == r"\operatorname{ab}_{12}^{2}{\left( \right)}"
+    assert latex(Function('ab')(Symbol('x'))**2) == r"\operatorname{ab}^{2}{\left(x \right)}"
+    assert latex(Function('ab1')(Symbol('x'))**2) == r"\operatorname{ab}_{1}^{2}{\left(x \right)}"
+    assert latex(Function('ab12')(Symbol('x'))**2) == r"\operatorname{ab}_{12}^{2}{\left(x \right)}"
+    assert latex(Function('ab_1')(Symbol('x'))**2) == r"\operatorname{ab}_{1}^{2}{\left(x \right)}"
+    assert latex(Function('ab_12')(Symbol('x'))**2) == \
+        r"\operatorname{ab}_{12}^{2}{\left(x \right)}"
+
+    # single letter function names
+    # > simple
+    assert latex(Function('a')) == r"a"
+    assert latex(Function('a1')) == r"a_{1}"
+    assert latex(Function('a12')) == r"a_{12}"
+    assert latex(Function('a_1')) == r"a_{1}"
+    assert latex(Function('a_12')) == r"a_{12}"
+
+    # > with argument
+    assert latex(Function('a')()) == r"a{\left( \right)}"
+    assert latex(Function('a1')()) == r"a_{1}{\left( \right)}"
+    assert latex(Function('a12')()) == r"a_{12}{\left( \right)}"
+    assert latex(Function('a_1')()) == r"a_{1}{\left( \right)}"
+    assert latex(Function('a_12')()) == r"a_{12}{\left( \right)}"
+
+    # > with power
+    #   does not work on functions without brackets
+
+    # > with argument and power combined
+    assert latex(Function('a')()**2) == r"a^{2}{\left( \right)}"
+    assert latex(Function('a1')()**2) == r"a_{1}^{2}{\left( \right)}"
+    assert latex(Function('a12')()**2) == r"a_{12}^{2}{\left( \right)}"
+    assert latex(Function('a_1')()**2) == r"a_{1}^{2}{\left( \right)}"
+    assert latex(Function('a_12')()**2) == r"a_{12}^{2}{\left( \right)}"
+    assert latex(Function('a')(Symbol('x'))**2) == r"a^{2}{\left(x \right)}"
+    assert latex(Function('a1')(Symbol('x'))**2) == r"a_{1}^{2}{\left(x \right)}"
+    assert latex(Function('a12')(Symbol('x'))**2) == r"a_{12}^{2}{\left(x \right)}"
+    assert latex(Function('a_1')(Symbol('x'))**2) == r"a_{1}^{2}{\left(x \right)}"
+    assert latex(Function('a_12')(Symbol('x'))**2) == r"a_{12}^{2}{\left(x \right)}"
+
+    assert latex(Function('a')()**32) == r"a^{32}{\left( \right)}"
+    assert latex(Function('a1')()**32) == r"a_{1}^{32}{\left( \right)}"
+    assert latex(Function('a12')()**32) == r"a_{12}^{32}{\left( \right)}"
+    assert latex(Function('a_1')()**32) == r"a_{1}^{32}{\left( \right)}"
+    assert latex(Function('a_12')()**32) == r"a_{12}^{32}{\left( \right)}"
+    assert latex(Function('a')(Symbol('x'))**32) == r"a^{32}{\left(x \right)}"
+    assert latex(Function('a1')(Symbol('x'))**32) == r"a_{1}^{32}{\left(x \right)}"
+    assert latex(Function('a12')(Symbol('x'))**32) == r"a_{12}^{32}{\left(x \right)}"
+    assert latex(Function('a_1')(Symbol('x'))**32) == r"a_{1}^{32}{\left(x \right)}"
+    assert latex(Function('a_12')(Symbol('x'))**32) == r"a_{12}^{32}{\left(x \right)}"
+
+    assert latex(Function('a')()**a) == r"a^{a}{\left( \right)}"
+    assert latex(Function('a1')()**a) == r"a_{1}^{a}{\left( \right)}"
+    assert latex(Function('a12')()**a) == r"a_{12}^{a}{\left( \right)}"
+    assert latex(Function('a_1')()**a) == r"a_{1}^{a}{\left( \right)}"
+    assert latex(Function('a_12')()**a) == r"a_{12}^{a}{\left( \right)}"
+    assert latex(Function('a')(Symbol('x'))**a) == r"a^{a}{\left(x \right)}"
+    assert latex(Function('a1')(Symbol('x'))**a) == r"a_{1}^{a}{\left(x \right)}"
+    assert latex(Function('a12')(Symbol('x'))**a) == r"a_{12}^{a}{\left(x \right)}"
+    assert latex(Function('a_1')(Symbol('x'))**a) == r"a_{1}^{a}{\left(x \right)}"
+    assert latex(Function('a_12')(Symbol('x'))**a) == r"a_{12}^{a}{\left(x \right)}"
+
+    ab = Symbol('ab')
+    assert latex(Function('a')()**ab) == r"a^{ab}{\left( \right)}"
+    assert latex(Function('a1')()**ab) == r"a_{1}^{ab}{\left( \right)}"
+    assert latex(Function('a12')()**ab) == r"a_{12}^{ab}{\left( \right)}"
+    assert latex(Function('a_1')()**ab) == r"a_{1}^{ab}{\left( \right)}"
+    assert latex(Function('a_12')()**ab) == r"a_{12}^{ab}{\left( \right)}"
+    assert latex(Function('a')(Symbol('x'))**ab) == r"a^{ab}{\left(x \right)}"
+    assert latex(Function('a1')(Symbol('x'))**ab) == r"a_{1}^{ab}{\left(x \right)}"
+    assert latex(Function('a12')(Symbol('x'))**ab) == r"a_{12}^{ab}{\left(x \right)}"
+    assert latex(Function('a_1')(Symbol('x'))**ab) == r"a_{1}^{ab}{\left(x \right)}"
+    assert latex(Function('a_12')(Symbol('x'))**ab) == r"a_{12}^{ab}{\left(x \right)}"
+
+    assert latex(Function('a^12')(x)) == R"a^{12}{\left(x \right)}"
+    assert latex(Function('a^12')(x) ** ab) == R"\left(a^{12}\right)^{ab}{\left(x \right)}"
+    assert latex(Function('a__12')(x)) == R"a^{12}{\left(x \right)}"
+    assert latex(Function('a__12')(x) ** ab) == R"\left(a^{12}\right)^{ab}{\left(x \right)}"
+    assert latex(Function('a_1__1_2')(x)) == R"a^{1}_{1 2}{\left(x \right)}"
+
+    # issue 5868
+    omega1 = Function('omega1')
+    assert latex(omega1) == r"\omega_{1}"
+    assert latex(omega1(x)) == r"\omega_{1}{\left(x \right)}"
+
+    assert latex(sin(x)) == r"\sin{\left(x \right)}"
+    assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}"
+    assert latex(sin(2*x**2), fold_func_brackets=True) == \
+        r"\sin {2 x^{2}}"
+    assert latex(sin(x**2), fold_func_brackets=True) == \
+        r"\sin {x^{2}}"
+
+    assert latex(asin(x)**2) == r"\operatorname{asin}^{2}{\left(x \right)}"
+    assert latex(asin(x)**2, inv_trig_style="full") == \
+        r"\arcsin^{2}{\left(x \right)}"
+    assert latex(asin(x)**2, inv_trig_style="power") == \
+        r"\sin^{-1}{\left(x \right)}^{2}"
+    assert latex(asin(x**2), inv_trig_style="power",
+                 fold_func_brackets=True) == \
+        r"\sin^{-1} {x^{2}}"
+    assert latex(acsc(x), inv_trig_style="full") == \
+        r"\operatorname{arccsc}{\left(x \right)}"
+    assert latex(asinh(x), inv_trig_style="full") == \
+        r"\operatorname{arsinh}{\left(x \right)}"
+
+    assert latex(factorial(k)) == r"k!"
+    assert latex(factorial(-k)) == r"\left(- k\right)!"
+    assert latex(factorial(k)**2) == r"k!^{2}"
+
+    assert latex(subfactorial(k)) == r"!k"
+    assert latex(subfactorial(-k)) == r"!\left(- k\right)"
+    assert latex(subfactorial(k)**2) == r"\left(!k\right)^{2}"
+
+    assert latex(factorial2(k)) == r"k!!"
+    assert latex(factorial2(-k)) == r"\left(- k\right)!!"
+    assert latex(factorial2(k)**2) == r"k!!^{2}"
+
+    assert latex(binomial(2, k)) == r"{\binom{2}{k}}"
+    assert latex(binomial(2, k)**2) == r"{\binom{2}{k}}^{2}"
+
+    assert latex(FallingFactorial(3, k)) == r"{\left(3\right)}_{k}"
+    assert latex(RisingFactorial(3, k)) == r"{3}^{\left(k\right)}"
+
+    assert latex(floor(x)) == r"\left\lfloor{x}\right\rfloor"
+    assert latex(ceiling(x)) == r"\left\lceil{x}\right\rceil"
+    assert latex(frac(x)) == r"\operatorname{frac}{\left(x\right)}"
+    assert latex(floor(x)**2) == r"\left\lfloor{x}\right\rfloor^{2}"
+    assert latex(ceiling(x)**2) == r"\left\lceil{x}\right\rceil^{2}"
+    assert latex(frac(x)**2) == r"\operatorname{frac}{\left(x\right)}^{2}"
+
+    assert latex(Min(x, 2, x**3)) == r"\min\left(2, x, x^{3}\right)"
+    assert latex(Min(x, y)**2) == r"\min\left(x, y\right)^{2}"
+    assert latex(Max(x, 2, x**3)) == r"\max\left(2, x, x^{3}\right)"
+    assert latex(Max(x, y)**2) == r"\max\left(x, y\right)^{2}"
+    assert latex(Abs(x)) == r"\left|{x}\right|"
+    assert latex(Abs(x)**2) == r"\left|{x}\right|^{2}"
+    assert latex(re(x)) == r"\operatorname{re}{\left(x\right)}"
+    assert latex(re(x + y)) == \
+        r"\operatorname{re}{\left(x\right)} + \operatorname{re}{\left(y\right)}"
+    assert latex(im(x)) == r"\operatorname{im}{\left(x\right)}"
+    assert latex(conjugate(x)) == r"\overline{x}"
+    assert latex(conjugate(x)**2) == r"\overline{x}^{2}"
+    assert latex(conjugate(x**2)) == r"\overline{x}^{2}"
+    assert latex(gamma(x)) == r"\Gamma\left(x\right)"
+    w = Wild('w')
+    assert latex(gamma(w)) == r"\Gamma\left(w\right)"
+    assert latex(Order(x)) == r"O\left(x\right)"
+    assert latex(Order(x, x)) == r"O\left(x\right)"
+    assert latex(Order(x, (x, 0))) == r"O\left(x\right)"
+    assert latex(Order(x, (x, oo))) == r"O\left(x; x\rightarrow \infty\right)"
+    assert latex(Order(x - y, (x, y))) == \
+        r"O\left(x - y; x\rightarrow y\right)"
+    assert latex(Order(x, x, y)) == \
+        r"O\left(x; \left( x, \  y\right)\rightarrow \left( 0, \  0\right)\right)"
+    assert latex(Order(x, x, y)) == \
+        r"O\left(x; \left( x, \  y\right)\rightarrow \left( 0, \  0\right)\right)"
+    assert latex(Order(x, (x, oo), (y, oo))) == \
+        r"O\left(x; \left( x, \  y\right)\rightarrow \left( \infty, \  \infty\right)\right)"
+    assert latex(lowergamma(x, y)) == r'\gamma\left(x, y\right)'
+    assert latex(lowergamma(x, y)**2) == r'\gamma^{2}\left(x, y\right)'
+    assert latex(uppergamma(x, y)) == r'\Gamma\left(x, y\right)'
+    assert latex(uppergamma(x, y)**2) == r'\Gamma^{2}\left(x, y\right)'
+
+    assert latex(cot(x)) == r'\cot{\left(x \right)}'
+    assert latex(coth(x)) == r'\coth{\left(x \right)}'
+    assert latex(re(x)) == r'\operatorname{re}{\left(x\right)}'
+    assert latex(im(x)) == r'\operatorname{im}{\left(x\right)}'
+    assert latex(root(x, y)) == r'x^{\frac{1}{y}}'
+    assert latex(arg(x)) == r'\arg{\left(x \right)}'
+
+    assert latex(zeta(x)) == r"\zeta\left(x\right)"
+    assert latex(zeta(x)**2) == r"\zeta^{2}\left(x\right)"
+    assert latex(zeta(x, y)) == r"\zeta\left(x, y\right)"
+    assert latex(zeta(x, y)**2) == r"\zeta^{2}\left(x, y\right)"
+    assert latex(dirichlet_eta(x)) == r"\eta\left(x\right)"
+    assert latex(dirichlet_eta(x)**2) == r"\eta^{2}\left(x\right)"
+    assert latex(polylog(x, y)) == r"\operatorname{Li}_{x}\left(y\right)"
+    assert latex(
+        polylog(x, y)**2) == r"\operatorname{Li}_{x}^{2}\left(y\right)"
+    assert latex(lerchphi(x, y, n)) == r"\Phi\left(x, y, n\right)"
+    assert latex(lerchphi(x, y, n)**2) == r"\Phi^{2}\left(x, y, n\right)"
+    assert latex(stieltjes(x)) == r"\gamma_{x}"
+    assert latex(stieltjes(x)**2) == r"\gamma_{x}^{2}"
+    assert latex(stieltjes(x, y)) == r"\gamma_{x}\left(y\right)"
+    assert latex(stieltjes(x, y)**2) == r"\gamma_{x}\left(y\right)^{2}"
+
+    assert latex(elliptic_k(z)) == r"K\left(z\right)"
+    assert latex(elliptic_k(z)**2) == r"K^{2}\left(z\right)"
+    assert latex(elliptic_f(x, y)) == r"F\left(x\middle| y\right)"
+    assert latex(elliptic_f(x, y)**2) == r"F^{2}\left(x\middle| y\right)"
+    assert latex(elliptic_e(x, y)) == r"E\left(x\middle| y\right)"
+    assert latex(elliptic_e(x, y)**2) == r"E^{2}\left(x\middle| y\right)"
+    assert latex(elliptic_e(z)) == r"E\left(z\right)"
+    assert latex(elliptic_e(z)**2) == r"E^{2}\left(z\right)"
+    assert latex(elliptic_pi(x, y, z)) == r"\Pi\left(x; y\middle| z\right)"
+    assert latex(elliptic_pi(x, y, z)**2) == \
+        r"\Pi^{2}\left(x; y\middle| z\right)"
+    assert latex(elliptic_pi(x, y)) == r"\Pi\left(x\middle| y\right)"
+    assert latex(elliptic_pi(x, y)**2) == r"\Pi^{2}\left(x\middle| y\right)"
+
+    assert latex(Ei(x)) == r'\operatorname{Ei}{\left(x \right)}'
+    assert latex(Ei(x)**2) == r'\operatorname{Ei}^{2}{\left(x \right)}'
+    assert latex(expint(x, y)) == r'\operatorname{E}_{x}\left(y\right)'
+    assert latex(expint(x, y)**2) == r'\operatorname{E}_{x}^{2}\left(y\right)'
+    assert latex(Shi(x)**2) == r'\operatorname{Shi}^{2}{\left(x \right)}'
+    assert latex(Si(x)**2) == r'\operatorname{Si}^{2}{\left(x \right)}'
+    assert latex(Ci(x)**2) == r'\operatorname{Ci}^{2}{\left(x \right)}'
+    assert latex(Chi(x)**2) == r'\operatorname{Chi}^{2}\left(x\right)'
+    assert latex(Chi(x)) == r'\operatorname{Chi}\left(x\right)'
+    assert latex(jacobi(n, a, b, x)) == \
+        r'P_{n}^{\left(a,b\right)}\left(x\right)'
+    assert latex(jacobi(n, a, b, x)**2) == \
+        r'\left(P_{n}^{\left(a,b\right)}\left(x\right)\right)^{2}'
+    assert latex(gegenbauer(n, a, x)) == \
+        r'C_{n}^{\left(a\right)}\left(x\right)'
+    assert latex(gegenbauer(n, a, x)**2) == \
+        r'\left(C_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
+    assert latex(chebyshevt(n, x)) == r'T_{n}\left(x\right)'
+    assert latex(chebyshevt(n, x)**2) == \
+        r'\left(T_{n}\left(x\right)\right)^{2}'
+    assert latex(chebyshevu(n, x)) == r'U_{n}\left(x\right)'
+    assert latex(chebyshevu(n, x)**2) == \
+        r'\left(U_{n}\left(x\right)\right)^{2}'
+    assert latex(legendre(n, x)) == r'P_{n}\left(x\right)'
+    assert latex(legendre(n, x)**2) == r'\left(P_{n}\left(x\right)\right)^{2}'
+    assert latex(assoc_legendre(n, a, x)) == \
+        r'P_{n}^{\left(a\right)}\left(x\right)'
+    assert latex(assoc_legendre(n, a, x)**2) == \
+        r'\left(P_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
+    assert latex(laguerre(n, x)) == r'L_{n}\left(x\right)'
+    assert latex(laguerre(n, x)**2) == r'\left(L_{n}\left(x\right)\right)^{2}'
+    assert latex(assoc_laguerre(n, a, x)) == \
+        r'L_{n}^{\left(a\right)}\left(x\right)'
+    assert latex(assoc_laguerre(n, a, x)**2) == \
+        r'\left(L_{n}^{\left(a\right)}\left(x\right)\right)^{2}'
+    assert latex(hermite(n, x)) == r'H_{n}\left(x\right)'
+    assert latex(hermite(n, x)**2) == r'\left(H_{n}\left(x\right)\right)^{2}'
+
+    theta = Symbol("theta", real=True)
+    phi = Symbol("phi", real=True)
+    assert latex(Ynm(n, m, theta, phi)) == r'Y_{n}^{m}\left(\theta,\phi\right)'
+    assert latex(Ynm(n, m, theta, phi)**3) == \
+        r'\left(Y_{n}^{m}\left(\theta,\phi\right)\right)^{3}'
+    assert latex(Znm(n, m, theta, phi)) == r'Z_{n}^{m}\left(\theta,\phi\right)'
+    assert latex(Znm(n, m, theta, phi)**3) == \
+        r'\left(Z_{n}^{m}\left(\theta,\phi\right)\right)^{3}'
+
+    # Test latex printing of function names with "_"
+    assert latex(polar_lift(0)) == \
+        r"\operatorname{polar\_lift}{\left(0 \right)}"
+    assert latex(polar_lift(0)**3) == \
+        r"\operatorname{polar\_lift}^{3}{\left(0 \right)}"
+
+    assert latex(totient(n)) == r'\phi\left(n\right)'
+    assert latex(totient(n) ** 2) == r'\left(\phi\left(n\right)\right)^{2}'
+
+    assert latex(reduced_totient(n)) == r'\lambda\left(n\right)'
+    assert latex(reduced_totient(n) ** 2) == \
+        r'\left(\lambda\left(n\right)\right)^{2}'
+
+    assert latex(divisor_sigma(x)) == r"\sigma\left(x\right)"
+    assert latex(divisor_sigma(x)**2) == r"\sigma^{2}\left(x\right)"
+    assert latex(divisor_sigma(x, y)) == r"\sigma_y\left(x\right)"
+    assert latex(divisor_sigma(x, y)**2) == r"\sigma^{2}_y\left(x\right)"
+
+    assert latex(udivisor_sigma(x)) == r"\sigma^*\left(x\right)"
+    assert latex(udivisor_sigma(x)**2) == r"\sigma^*^{2}\left(x\right)"
+    assert latex(udivisor_sigma(x, y)) == r"\sigma^*_y\left(x\right)"
+    assert latex(udivisor_sigma(x, y)**2) == r"\sigma^*^{2}_y\left(x\right)"
+
+    assert latex(primenu(n)) == r'\nu\left(n\right)'
+    assert latex(primenu(n) ** 2) == r'\left(\nu\left(n\right)\right)^{2}'
+
+    assert latex(primeomega(n)) == r'\Omega\left(n\right)'
+    assert latex(primeomega(n) ** 2) == \
+        r'\left(\Omega\left(n\right)\right)^{2}'
+
+    assert latex(LambertW(n)) == r'W\left(n\right)'
+    assert latex(LambertW(n, -1)) == r'W_{-1}\left(n\right)'
+    assert latex(LambertW(n, k)) == r'W_{k}\left(n\right)'
+    assert latex(LambertW(n) * LambertW(n)) == r"W^{2}\left(n\right)"
+    assert latex(Pow(LambertW(n), 2)) == r"W^{2}\left(n\right)"
+    assert latex(LambertW(n)**k) == r"W^{k}\left(n\right)"
+    assert latex(LambertW(n, k)**p) == r"W^{p}_{k}\left(n\right)"
+
+    assert latex(Mod(x, 7)) == r'x \bmod 7'
+    assert latex(Mod(x + 1, 7)) == r'\left(x + 1\right) \bmod 7'
+    assert latex(Mod(7, x + 1)) == r'7 \bmod \left(x + 1\right)'
+    assert latex(Mod(2 * x, 7)) == r'2 x \bmod 7'
+    assert latex(Mod(7, 2 * x)) == r'7 \bmod 2 x'
+    assert latex(Mod(x, 7) + 1) == r'\left(x \bmod 7\right) + 1'
+    assert latex(2 * Mod(x, 7)) == r'2 \left(x \bmod 7\right)'
+    assert latex(Mod(7, 2 * x)**n) == r'\left(7 \bmod 2 x\right)^{n}'
+
+    # some unknown function name should get rendered with \operatorname
+    fjlkd = Function('fjlkd')
+    assert latex(fjlkd(x)) == r'\operatorname{fjlkd}{\left(x \right)}'
+    # even when it is referred to without an argument
+    assert latex(fjlkd) == r'\operatorname{fjlkd}'
+
+
+# test that notation passes to subclasses of the same name only
+def test_function_subclass_different_name():
+    class mygamma(gamma):
+        pass
+    assert latex(mygamma) == r"\operatorname{mygamma}"
+    assert latex(mygamma(x)) == r"\operatorname{mygamma}{\left(x \right)}"
+
+
+def test_hyper_printing():
+    from sympy.abc import x, z
+
+    assert latex(meijerg(Tuple(pi, pi, x), Tuple(1),
+                         (0, 1), Tuple(1, 2, 3/pi), z)) == \
+        r'{G_{4, 5}^{2, 3}\left(\begin{matrix} \pi, \pi, x & 1 \\0, 1 & 1, 2, '\
+        r'\frac{3}{\pi} \end{matrix} \middle| {z} \right)}'
+    assert latex(meijerg(Tuple(), Tuple(1), (0,), Tuple(), z)) == \
+        r'{G_{1, 1}^{1, 0}\left(\begin{matrix}  & 1 \\0 &  \end{matrix} \middle| {z} \right)}'
+    assert latex(hyper((x, 2), (3,), z)) == \
+        r'{{}_{2}F_{1}\left(\begin{matrix} 2, x ' \
+        r'\\ 3 \end{matrix}\middle| {z} \right)}'
+    assert latex(hyper(Tuple(), Tuple(1), z)) == \
+        r'{{}_{0}F_{1}\left(\begin{matrix}  ' \
+        r'\\ 1 \end{matrix}\middle| {z} \right)}'
+
+
+def test_latex_bessel():
+    from sympy.functions.special.bessel import (besselj, bessely, besseli,
+                                                besselk, hankel1, hankel2,
+                                                jn, yn, hn1, hn2)
+    from sympy.abc import z
+    assert latex(besselj(n, z**2)**k) == r'J^{k}_{n}\left(z^{2}\right)'
+    assert latex(bessely(n, z)) == r'Y_{n}\left(z\right)'
+    assert latex(besseli(n, z)) == r'I_{n}\left(z\right)'
+    assert latex(besselk(n, z)) == r'K_{n}\left(z\right)'
+    assert latex(hankel1(n, z**2)**2) == \
+        r'\left(H^{(1)}_{n}\left(z^{2}\right)\right)^{2}'
+    assert latex(hankel2(n, z)) == r'H^{(2)}_{n}\left(z\right)'
+    assert latex(jn(n, z)) == r'j_{n}\left(z\right)'
+    assert latex(yn(n, z)) == r'y_{n}\left(z\right)'
+    assert latex(hn1(n, z)) == r'h^{(1)}_{n}\left(z\right)'
+    assert latex(hn2(n, z)) == r'h^{(2)}_{n}\left(z\right)'
+
+
+def test_latex_fresnel():
+    from sympy.functions.special.error_functions import (fresnels, fresnelc)
+    from sympy.abc import z
+    assert latex(fresnels(z)) == r'S\left(z\right)'
+    assert latex(fresnelc(z)) == r'C\left(z\right)'
+    assert latex(fresnels(z)**2) == r'S^{2}\left(z\right)'
+    assert latex(fresnelc(z)**2) == r'C^{2}\left(z\right)'
+
+
+def test_latex_brackets():
+    assert latex((-1)**x) == r"\left(-1\right)^{x}"
+
+
+def test_latex_indexed():
+    Psi_symbol = Symbol('Psi_0', complex=True, real=False)
+    Psi_indexed = IndexedBase(Symbol('Psi', complex=True, real=False))
+    symbol_latex = latex(Psi_symbol * conjugate(Psi_symbol))
+    indexed_latex = latex(Psi_indexed[0] * conjugate(Psi_indexed[0]))
+    # \\overline{{\\Psi}_{0}} {\\Psi}_{0}  vs.  \\Psi_{0} \\overline{\\Psi_{0}}
+    assert symbol_latex == r'\Psi_{0} \overline{\Psi_{0}}'
+    assert indexed_latex == r'\overline{{\Psi}_{0}} {\Psi}_{0}'
+
+    # Symbol('gamma') gives r'\gamma'
+    interval = '\\mathrel{..}\\nobreak '
+    assert latex(Indexed('x1', Symbol('i'))) == r'{x_{1}}_{i}'
+    assert latex(Indexed('x2', Idx('i'))) == r'{x_{2}}_{i}'
+    assert latex(Indexed('x3', Idx('i', Symbol('N')))) == r'{x_{3}}_{{i}_{0'+interval+'N - 1}}'
+    assert latex(Indexed('x3', Idx('i', Symbol('N')+1))) == r'{x_{3}}_{{i}_{0'+interval+'N}}'
+    assert latex(Indexed('x4', Idx('i', (Symbol('a'),Symbol('b'))))) == r'{x_{4}}_{{i}_{a'+interval+'b}}'
+    assert latex(IndexedBase('gamma')) == r'\gamma'
+    assert latex(IndexedBase('a b')) == r'a b'
+    assert latex(IndexedBase('a_b')) == r'a_{b}'
+
+
+def test_latex_derivatives():
+    # regular "d" for ordinary derivatives
+    assert latex(diff(x**3, x, evaluate=False)) == \
+        r"\frac{d}{d x} x^{3}"
+    assert latex(diff(sin(x) + x**2, x, evaluate=False)) == \
+        r"\frac{d}{d x} \left(x^{2} + \sin{\left(x \right)}\right)"
+    assert latex(diff(diff(sin(x) + x**2, x, evaluate=False), evaluate=False))\
+        == \
+        r"\frac{d^{2}}{d x^{2}} \left(x^{2} + \sin{\left(x \right)}\right)"
+    assert latex(diff(diff(diff(sin(x) + x**2, x, evaluate=False), evaluate=False), evaluate=False)) == \
+        r"\frac{d^{3}}{d x^{3}} \left(x^{2} + \sin{\left(x \right)}\right)"
+
+    # \partial for partial derivatives
+    assert latex(diff(sin(x * y), x, evaluate=False)) == \
+        r"\frac{\partial}{\partial x} \sin{\left(x y \right)}"
+    assert latex(diff(sin(x * y) + x**2, x, evaluate=False)) == \
+        r"\frac{\partial}{\partial x} \left(x^{2} + \sin{\left(x y \right)}\right)"
+    assert latex(diff(diff(sin(x*y) + x**2, x, evaluate=False), x, evaluate=False)) == \
+        r"\frac{\partial^{2}}{\partial x^{2}} \left(x^{2} + \sin{\left(x y \right)}\right)"
+    assert latex(diff(diff(diff(sin(x*y) + x**2, x, evaluate=False), x, evaluate=False), x, evaluate=False)) == \
+        r"\frac{\partial^{3}}{\partial x^{3}} \left(x^{2} + \sin{\left(x y \right)}\right)"
+
+    # mixed partial derivatives
+    f = Function("f")
+    assert latex(diff(diff(f(x, y), x, evaluate=False), y, evaluate=False)) == \
+        r"\frac{\partial^{2}}{\partial y\partial x} " + latex(f(x, y))
+
+    assert latex(diff(diff(diff(f(x, y), x, evaluate=False), x, evaluate=False), y, evaluate=False)) == \
+        r"\frac{\partial^{3}}{\partial y\partial x^{2}} " + latex(f(x, y))
+
+    # for negative nested Derivative
+    assert latex(diff(-diff(y**2,x,evaluate=False),x,evaluate=False)) == r'\frac{d}{d x} \left(- \frac{d}{d x} y^{2}\right)'
+    assert latex(diff(diff(-diff(diff(y,x,evaluate=False),x,evaluate=False),x,evaluate=False),x,evaluate=False)) == \
+        r'\frac{d^{2}}{d x^{2}} \left(- \frac{d^{2}}{d x^{2}} y\right)'
+
+    # use ordinary d when one of the variables has been integrated out
+    assert latex(diff(Integral(exp(-x*y), (x, 0, oo)), y, evaluate=False)) == \
+        r"\frac{d}{d y} \int\limits_{0}^{\infty} e^{- x y}\, dx"
+
+    # Derivative wrapped in power:
+    assert latex(diff(x, x, evaluate=False)**2) == \
+        r"\left(\frac{d}{d x} x\right)^{2}"
+
+    assert latex(diff(f(x), x)**2) == \
+        r"\left(\frac{d}{d x} f{\left(x \right)}\right)^{2}"
+
+    assert latex(diff(f(x), (x, n))) == \
+        r"\frac{d^{n}}{d x^{n}} f{\left(x \right)}"
+
+    x1 = Symbol('x1')
+    x2 = Symbol('x2')
+    assert latex(diff(f(x1, x2), x1)) == r'\frac{\partial}{\partial x_{1}} f{\left(x_{1},x_{2} \right)}'
+
+    n1 = Symbol('n1')
+    assert latex(diff(f(x), (x, n1))) == r'\frac{d^{n_{1}}}{d x^{n_{1}}} f{\left(x \right)}'
+
+    n2 = Symbol('n2')
+    assert latex(diff(f(x), (x, Max(n1, n2)))) == \
+        r'\frac{d^{\max\left(n_{1}, n_{2}\right)}}{d x^{\max\left(n_{1}, n_{2}\right)}} f{\left(x \right)}'
+
+    # set diff operator
+    assert latex(diff(f(x), x), diff_operator="rd") == r'\frac{\mathrm{d}}{\mathrm{d} x} f{\left(x \right)}'
+
+
+def test_latex_subs():
+    assert latex(Subs(x*y, (x, y), (1, 2))) == r'\left. x y \right|_{\substack{ x=1\\ y=2 }}'
+
+
+def test_latex_integrals():
+    assert latex(Integral(log(x), x)) == r"\int \log{\left(x \right)}\, dx"
+    assert latex(Integral(x**2, (x, 0, 1))) == \
+        r"\int\limits_{0}^{1} x^{2}\, dx"
+    assert latex(Integral(x**2, (x, 10, 20))) == \
+        r"\int\limits_{10}^{20} x^{2}\, dx"
+    assert latex(Integral(y*x**2, (x, 0, 1), y)) == \
+        r"\int\int\limits_{0}^{1} x^{2} y\, dx\, dy"
+    assert latex(Integral(y*x**2, (x, 0, 1), y), mode='equation*') == \
+        r"\begin{equation*}\int\int\limits_{0}^{1} x^{2} y\, dx\, dy\end{equation*}"
+    assert latex(Integral(y*x**2, (x, 0, 1), y), mode='equation*', itex=True) \
+        == r"$$\int\int_{0}^{1} x^{2} y\, dx\, dy$$"
+    assert latex(Integral(x, (x, 0))) == r"\int\limits^{0} x\, dx"
+    assert latex(Integral(x*y, x, y)) == r"\iint x y\, dx\, dy"
+    assert latex(Integral(x*y*z, x, y, z)) == r"\iiint x y z\, dx\, dy\, dz"
+    assert latex(Integral(x*y*z*t, x, y, z, t)) == \
+        r"\iiiint t x y z\, dx\, dy\, dz\, dt"
+    assert latex(Integral(x, x, x, x, x, x, x)) == \
+        r"\int\int\int\int\int\int x\, dx\, dx\, dx\, dx\, dx\, dx"
+    assert latex(Integral(x, x, y, (z, 0, 1))) == \
+        r"\int\limits_{0}^{1}\int\int x\, dx\, dy\, dz"
+
+    # for negative nested Integral
+    assert latex(Integral(-Integral(y**2,x),x)) == \
+        r'\int \left(- \int y^{2}\, dx\right)\, dx'
+    assert latex(Integral(-Integral(-Integral(y,x),x),x)) == \
+        r'\int \left(- \int \left(- \int y\, dx\right)\, dx\right)\, dx'
+
+    # fix issue #10806
+    assert latex(Integral(z, z)**2) == r"\left(\int z\, dz\right)^{2}"
+    assert latex(Integral(x + z, z)) == r"\int \left(x + z\right)\, dz"
+    assert latex(Integral(x+z/2, z)) == \
+        r"\int \left(x + \frac{z}{2}\right)\, dz"
+    assert latex(Integral(x**y, z)) == r"\int x^{y}\, dz"
+
+    # set diff operator
+    assert latex(Integral(x, x), diff_operator="rd") == r'\int x\, \mathrm{d}x'
+    assert latex(Integral(x, (x, 0, 1)), diff_operator="rd") == r'\int\limits_{0}^{1} x\, \mathrm{d}x'
+
+
+def test_latex_sets():
+    for s in (frozenset, set):
+        assert latex(s([x*y, x**2])) == r"\left\{x^{2}, x y\right\}"
+        assert latex(s(range(1, 6))) == r"\left\{1, 2, 3, 4, 5\right\}"
+        assert latex(s(range(1, 13))) == \
+            r"\left\{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12\right\}"
+
+    s = FiniteSet
+    assert latex(s(*[x*y, x**2])) == r"\left\{x^{2}, x y\right\}"
+    assert latex(s(*range(1, 6))) == r"\left\{1, 2, 3, 4, 5\right\}"
+    assert latex(s(*range(1, 13))) == \
+        r"\left\{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12\right\}"
+
+
+def test_latex_SetExpr():
+    iv = Interval(1, 3)
+    se = SetExpr(iv)
+    assert latex(se) == r"SetExpr\left(\left[1, 3\right]\right)"
+
+
+def test_latex_Range():
+    assert latex(Range(1, 51)) == r'\left\{1, 2, \ldots, 50\right\}'
+    assert latex(Range(1, 4)) == r'\left\{1, 2, 3\right\}'
+    assert latex(Range(0, 3, 1)) == r'\left\{0, 1, 2\right\}'
+    assert latex(Range(0, 30, 1)) == r'\left\{0, 1, \ldots, 29\right\}'
+    assert latex(Range(30, 1, -1)) == r'\left\{30, 29, \ldots, 2\right\}'
+    assert latex(Range(0, oo, 2)) == r'\left\{0, 2, \ldots\right\}'
+    assert latex(Range(oo, -2, -2)) == r'\left\{\ldots, 2, 0\right\}'
+    assert latex(Range(-2, -oo, -1)) == r'\left\{-2, -3, \ldots\right\}'
+    assert latex(Range(-oo, oo)) == r'\left\{\ldots, -1, 0, 1, \ldots\right\}'
+    assert latex(Range(oo, -oo, -1)) == r'\left\{\ldots, 1, 0, -1, \ldots\right\}'
+
+    a, b, c = symbols('a:c')
+    assert latex(Range(a, b, c)) == r'\text{Range}\left(a, b, c\right)'
+    assert latex(Range(a, 10, 1)) == r'\text{Range}\left(a, 10\right)'
+    assert latex(Range(0, b, 1)) == r'\text{Range}\left(b\right)'
+    assert latex(Range(0, 10, c)) == r'\text{Range}\left(0, 10, c\right)'
+
+    i = Symbol('i', integer=True)
+    n = Symbol('n', negative=True, integer=True)
+    p = Symbol('p', positive=True, integer=True)
+
+    assert latex(Range(i, i + 3)) == r'\left\{i, i + 1, i + 2\right\}'
+    assert latex(Range(-oo, n, 2)) == r'\left\{\ldots, n - 4, n - 2\right\}'
+    assert latex(Range(p, oo)) == r'\left\{p, p + 1, \ldots\right\}'
+    # The following will work if __iter__ is improved
+    # assert latex(Range(-3, p + 7)) == r'\left\{-3, -2,  \ldots, p + 6\right\}'
+    # Must have integer assumptions
+    assert latex(Range(a, a + 3)) == r'\text{Range}\left(a, a + 3\right)'
+
+
+def test_latex_sequences():
+    s1 = SeqFormula(a**2, (0, oo))
+    s2 = SeqPer((1, 2))
+
+    latex_str = r'\left[0, 1, 4, 9, \ldots\right]'
+    assert latex(s1) == latex_str
+
+    latex_str = r'\left[1, 2, 1, 2, \ldots\right]'
+    assert latex(s2) == latex_str
+
+    s3 = SeqFormula(a**2, (0, 2))
+    s4 = SeqPer((1, 2), (0, 2))
+
+    latex_str = r'\left[0, 1, 4\right]'
+    assert latex(s3) == latex_str
+
+    latex_str = r'\left[1, 2, 1\right]'
+    assert latex(s4) == latex_str
+
+    s5 = SeqFormula(a**2, (-oo, 0))
+    s6 = SeqPer((1, 2), (-oo, 0))
+
+    latex_str = r'\left[\ldots, 9, 4, 1, 0\right]'
+    assert latex(s5) == latex_str
+
+    latex_str = r'\left[\ldots, 2, 1, 2, 1\right]'
+    assert latex(s6) == latex_str
+
+    latex_str = r'\left[1, 3, 5, 11, \ldots\right]'
+    assert latex(SeqAdd(s1, s2)) == latex_str
+
+    latex_str = r'\left[1, 3, 5\right]'
+    assert latex(SeqAdd(s3, s4)) == latex_str
+
+    latex_str = r'\left[\ldots, 11, 5, 3, 1\right]'
+    assert latex(SeqAdd(s5, s6)) == latex_str
+
+    latex_str = r'\left[0, 2, 4, 18, \ldots\right]'
+    assert latex(SeqMul(s1, s2)) == latex_str
+
+    latex_str = r'\left[0, 2, 4\right]'
+    assert latex(SeqMul(s3, s4)) == latex_str
+
+    latex_str = r'\left[\ldots, 18, 4, 2, 0\right]'
+    assert latex(SeqMul(s5, s6)) == latex_str
+
+    # Sequences with symbolic limits, issue 12629
+    s7 = SeqFormula(a**2, (a, 0, x))
+    latex_str = r'\left\{a^{2}\right\}_{a=0}^{x}'
+    assert latex(s7) == latex_str
+
+    b = Symbol('b')
+    s8 = SeqFormula(b*a**2, (a, 0, 2))
+    latex_str = r'\left[0, b, 4 b\right]'
+    assert latex(s8) == latex_str
+
+
+def test_latex_FourierSeries():
+    latex_str = \
+        r'2 \sin{\left(x \right)} - \sin{\left(2 x \right)} + \frac{2 \sin{\left(3 x \right)}}{3} + \ldots'
+    assert latex(fourier_series(x, (x, -pi, pi))) == latex_str
+
+
+def test_latex_FormalPowerSeries():
+    latex_str = r'\sum_{k=1}^{\infty} - \frac{\left(-1\right)^{- k} x^{k}}{k}'
+    assert latex(fps(log(1 + x))) == latex_str
+
+
+def test_latex_intervals():
+    a = Symbol('a', real=True)
+    assert latex(Interval(0, 0)) == r"\left\{0\right\}"
+    assert latex(Interval(0, a)) == r"\left[0, a\right]"
+    assert latex(Interval(0, a, False, False)) == r"\left[0, a\right]"
+    assert latex(Interval(0, a, True, False)) == r"\left(0, a\right]"
+    assert latex(Interval(0, a, False, True)) == r"\left[0, a\right)"
+    assert latex(Interval(0, a, True, True)) == r"\left(0, a\right)"
+
+
+def test_latex_AccumuBounds():
+    a = Symbol('a', real=True)
+    assert latex(AccumBounds(0, 1)) == r"\left\langle 0, 1\right\rangle"
+    assert latex(AccumBounds(0, a)) == r"\left\langle 0, a\right\rangle"
+    assert latex(AccumBounds(a + 1, a + 2)) == \
+        r"\left\langle a + 1, a + 2\right\rangle"
+
+
+def test_latex_emptyset():
+    assert latex(S.EmptySet) == r"\emptyset"
+
+
+def test_latex_universalset():
+    assert latex(S.UniversalSet) == r"\mathbb{U}"
+
+
+def test_latex_commutator():
+    A = Operator('A')
+    B = Operator('B')
+    comm = Commutator(B, A)
+    assert latex(comm.doit()) == r"- (A B - B A)"
+
+
+def test_latex_union():
+    assert latex(Union(Interval(0, 1), Interval(2, 3))) == \
+        r"\left[0, 1\right] \cup \left[2, 3\right]"
+    assert latex(Union(Interval(1, 1), Interval(2, 2), Interval(3, 4))) == \
+        r"\left\{1, 2\right\} \cup \left[3, 4\right]"
+
+
+def test_latex_intersection():
+    assert latex(Intersection(Interval(0, 1), Interval(x, y))) == \
+        r"\left[0, 1\right] \cap \left[x, y\right]"
+
+
+def test_latex_symmetric_difference():
+    assert latex(SymmetricDifference(Interval(2, 5), Interval(4, 7),
+                                     evaluate=False)) == \
+        r'\left[2, 5\right] \triangle \left[4, 7\right]'
+
+
+def test_latex_Complement():
+    assert latex(Complement(S.Reals, S.Naturals)) == \
+        r"\mathbb{R} \setminus \mathbb{N}"
+
+
+def test_latex_productset():
+    line = Interval(0, 1)
+    bigline = Interval(0, 10)
+    fset = FiniteSet(1, 2, 3)
+    assert latex(line**2) == r"%s^{2}" % latex(line)
+    assert latex(line**10) == r"%s^{10}" % latex(line)
+    assert latex((line * bigline * fset).flatten()) == r"%s \times %s \times %s" % (
+        latex(line), latex(bigline), latex(fset))
+
+
+def test_latex_powerset():
+    fset = FiniteSet(1, 2, 3)
+    assert latex(PowerSet(fset)) == r'\mathcal{P}\left(\left\{1, 2, 3\right\}\right)'
+
+
+def test_latex_ordinals():
+    w = OrdinalOmega()
+    assert latex(w) == r"\omega"
+    wp = OmegaPower(2, 3)
+    assert latex(wp) == r'3 \omega^{2}'
+    assert latex(Ordinal(wp, OmegaPower(1, 1))) == r'3 \omega^{2} + \omega'
+    assert latex(Ordinal(OmegaPower(2, 1), OmegaPower(1, 2))) == r'\omega^{2} + 2 \omega'
+
+
+def test_set_operators_parenthesis():
+    a, b, c, d = symbols('a:d')
+    A = FiniteSet(a)
+    B = FiniteSet(b)
+    C = FiniteSet(c)
+    D = FiniteSet(d)
+
+    U1 = Union(A, B, evaluate=False)
+    U2 = Union(C, D, evaluate=False)
+    I1 = Intersection(A, B, evaluate=False)
+    I2 = Intersection(C, D, evaluate=False)
+    C1 = Complement(A, B, evaluate=False)
+    C2 = Complement(C, D, evaluate=False)
+    D1 = SymmetricDifference(A, B, evaluate=False)
+    D2 = SymmetricDifference(C, D, evaluate=False)
+    # XXX ProductSet does not support evaluate keyword
+    P1 = ProductSet(A, B)
+    P2 = ProductSet(C, D)
+
+    assert latex(Intersection(A, U2, evaluate=False)) == \
+        r'\left\{a\right\} \cap ' \
+        r'\left(\left\{c\right\} \cup \left\{d\right\}\right)'
+    assert latex(Intersection(U1, U2, evaluate=False)) == \
+        r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \
+        r'\cap \left(\left\{c\right\} \cup \left\{d\right\}\right)'
+    assert latex(Intersection(C1, C2, evaluate=False)) == \
+        r'\left(\left\{a\right\} \setminus ' \
+        r'\left\{b\right\}\right) \cap \left(\left\{c\right\} ' \
+        r'\setminus \left\{d\right\}\right)'
+    assert latex(Intersection(D1, D2, evaluate=False)) == \
+        r'\left(\left\{a\right\} \triangle ' \
+        r'\left\{b\right\}\right) \cap \left(\left\{c\right\} ' \
+        r'\triangle \left\{d\right\}\right)'
+    assert latex(Intersection(P1, P2, evaluate=False)) == \
+        r'\left(\left\{a\right\} \times \left\{b\right\}\right) ' \
+        r'\cap \left(\left\{c\right\} \times ' \
+        r'\left\{d\right\}\right)'
+
+    assert latex(Union(A, I2, evaluate=False)) == \
+        r'\left\{a\right\} \cup ' \
+        r'\left(\left\{c\right\} \cap \left\{d\right\}\right)'
+    assert latex(Union(I1, I2, evaluate=False)) == \
+        r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \
+        r'\cup \left(\left\{c\right\} \cap \left\{d\right\}\right)'
+    assert latex(Union(C1, C2, evaluate=False)) == \
+        r'\left(\left\{a\right\} \setminus ' \
+        r'\left\{b\right\}\right) \cup \left(\left\{c\right\} ' \
+        r'\setminus \left\{d\right\}\right)'
+    assert latex(Union(D1, D2, evaluate=False)) == \
+        r'\left(\left\{a\right\} \triangle ' \
+        r'\left\{b\right\}\right) \cup \left(\left\{c\right\} ' \
+        r'\triangle \left\{d\right\}\right)'
+    assert latex(Union(P1, P2, evaluate=False)) == \
+        r'\left(\left\{a\right\} \times \left\{b\right\}\right) ' \
+        r'\cup \left(\left\{c\right\} \times ' \
+        r'\left\{d\right\}\right)'
+
+    assert latex(Complement(A, C2, evaluate=False)) == \
+        r'\left\{a\right\} \setminus \left(\left\{c\right\} ' \
+        r'\setminus \left\{d\right\}\right)'
+    assert latex(Complement(U1, U2, evaluate=False)) == \
+        r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \
+        r'\setminus \left(\left\{c\right\} \cup ' \
+        r'\left\{d\right\}\right)'
+    assert latex(Complement(I1, I2, evaluate=False)) == \
+        r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \
+        r'\setminus \left(\left\{c\right\} \cap ' \
+        r'\left\{d\right\}\right)'
+    assert latex(Complement(D1, D2, evaluate=False)) == \
+        r'\left(\left\{a\right\} \triangle ' \
+        r'\left\{b\right\}\right) \setminus ' \
+        r'\left(\left\{c\right\} \triangle \left\{d\right\}\right)'
+    assert latex(Complement(P1, P2, evaluate=False)) == \
+        r'\left(\left\{a\right\} \times \left\{b\right\}\right) '\
+        r'\setminus \left(\left\{c\right\} \times '\
+        r'\left\{d\right\}\right)'
+
+    assert latex(SymmetricDifference(A, D2, evaluate=False)) == \
+        r'\left\{a\right\} \triangle \left(\left\{c\right\} ' \
+        r'\triangle \left\{d\right\}\right)'
+    assert latex(SymmetricDifference(U1, U2, evaluate=False)) == \
+        r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \
+        r'\triangle \left(\left\{c\right\} \cup ' \
+        r'\left\{d\right\}\right)'
+    assert latex(SymmetricDifference(I1, I2, evaluate=False)) == \
+        r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \
+        r'\triangle \left(\left\{c\right\} \cap ' \
+        r'\left\{d\right\}\right)'
+    assert latex(SymmetricDifference(C1, C2, evaluate=False)) == \
+        r'\left(\left\{a\right\} \setminus ' \
+        r'\left\{b\right\}\right) \triangle ' \
+        r'\left(\left\{c\right\} \setminus \left\{d\right\}\right)'
+    assert latex(SymmetricDifference(P1, P2, evaluate=False)) == \
+        r'\left(\left\{a\right\} \times \left\{b\right\}\right) ' \
+        r'\triangle \left(\left\{c\right\} \times ' \
+        r'\left\{d\right\}\right)'
+
+    # XXX This can be incorrect since cartesian product is not associative
+    assert latex(ProductSet(A, P2).flatten()) == \
+        r'\left\{a\right\} \times \left\{c\right\} \times ' \
+        r'\left\{d\right\}'
+    assert latex(ProductSet(U1, U2)) == \
+        r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \
+        r'\times \left(\left\{c\right\} \cup ' \
+        r'\left\{d\right\}\right)'
+    assert latex(ProductSet(I1, I2)) == \
+        r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \
+        r'\times \left(\left\{c\right\} \cap ' \
+        r'\left\{d\right\}\right)'
+    assert latex(ProductSet(C1, C2)) == \
+        r'\left(\left\{a\right\} \setminus ' \
+        r'\left\{b\right\}\right) \times \left(\left\{c\right\} ' \
+        r'\setminus \left\{d\right\}\right)'
+    assert latex(ProductSet(D1, D2)) == \
+        r'\left(\left\{a\right\} \triangle ' \
+        r'\left\{b\right\}\right) \times \left(\left\{c\right\} ' \
+        r'\triangle \left\{d\right\}\right)'
+
+
+def test_latex_Complexes():
+    assert latex(S.Complexes) == r"\mathbb{C}"
+
+
+def test_latex_Naturals():
+    assert latex(S.Naturals) == r"\mathbb{N}"
+
+
+def test_latex_Naturals0():
+    assert latex(S.Naturals0) == r"\mathbb{N}_0"
+
+
+def test_latex_Integers():
+    assert latex(S.Integers) == r"\mathbb{Z}"
+
+
+def test_latex_ImageSet():
+    x = Symbol('x')
+    assert latex(ImageSet(Lambda(x, x**2), S.Naturals)) == \
+        r"\left\{x^{2}\; \middle|\; x \in \mathbb{N}\right\}"
+
+    y = Symbol('y')
+    imgset = ImageSet(Lambda((x, y), x + y), {1, 2, 3}, {3, 4})
+    assert latex(imgset) == \
+        r"\left\{x + y\; \middle|\; x \in \left\{1, 2, 3\right\}, y \in \left\{3, 4\right\}\right\}"
+
+    imgset = ImageSet(Lambda(((x, y),), x + y), ProductSet({1, 2, 3}, {3, 4}))
+    assert latex(imgset) == \
+        r"\left\{x + y\; \middle|\; \left( x, \  y\right) \in \left\{1, 2, 3\right\} \times \left\{3, 4\right\}\right\}"
+
+
+def test_latex_ConditionSet():
+    x = Symbol('x')
+    assert latex(ConditionSet(x, Eq(x**2, 1), S.Reals)) == \
+        r"\left\{x\; \middle|\; x \in \mathbb{R} \wedge x^{2} = 1 \right\}"
+    assert latex(ConditionSet(x, Eq(x**2, 1), S.UniversalSet)) == \
+        r"\left\{x\; \middle|\; x^{2} = 1 \right\}"
+
+
+def test_latex_ComplexRegion():
+    assert latex(ComplexRegion(Interval(3, 5)*Interval(4, 6))) == \
+        r"\left\{x + y i\; \middle|\; x, y \in \left[3, 5\right] \times \left[4, 6\right] \right\}"
+    assert latex(ComplexRegion(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == \
+        r"\left\{r \left(i \sin{\left(\theta \right)} + \cos{\left(\theta "\
+        r"\right)}\right)\; \middle|\; r, \theta \in \left[0, 1\right] \times \left[0, 2 \pi\right) \right\}"
+
+
+def test_latex_Contains():
+    x = Symbol('x')
+    assert latex(Contains(x, S.Naturals)) == r"x \in \mathbb{N}"
+
+
+def test_latex_sum():
+    assert latex(Sum(x*y**2, (x, -2, 2), (y, -5, 5))) == \
+        r"\sum_{\substack{-2 \leq x \leq 2\\-5 \leq y \leq 5}} x y^{2}"
+    assert latex(Sum(x**2, (x, -2, 2))) == \
+        r"\sum_{x=-2}^{2} x^{2}"
+    assert latex(Sum(x**2 + y, (x, -2, 2))) == \
+        r"\sum_{x=-2}^{2} \left(x^{2} + y\right)"
+    assert latex(Sum(x**2 + y, (x, -2, 2))**2) == \
+        r"\left(\sum_{x=-2}^{2} \left(x^{2} + y\right)\right)^{2}"
+
+
+def test_latex_product():
+    assert latex(Product(x*y**2, (x, -2, 2), (y, -5, 5))) == \
+        r"\prod_{\substack{-2 \leq x \leq 2\\-5 \leq y \leq 5}} x y^{2}"
+    assert latex(Product(x**2, (x, -2, 2))) == \
+        r"\prod_{x=-2}^{2} x^{2}"
+    assert latex(Product(x**2 + y, (x, -2, 2))) == \
+        r"\prod_{x=-2}^{2} \left(x^{2} + y\right)"
+
+    assert latex(Product(x, (x, -2, 2))**2) == \
+        r"\left(\prod_{x=-2}^{2} x\right)^{2}"
+
+
+def test_latex_limits():
+    assert latex(Limit(x, x, oo)) == r"\lim_{x \to \infty} x"
+
+    # issue 8175
+    f = Function('f')
+    assert latex(Limit(f(x), x, 0)) == r"\lim_{x \to 0^+} f{\left(x \right)}"
+    assert latex(Limit(f(x), x, 0, "-")) == \
+        r"\lim_{x \to 0^-} f{\left(x \right)}"
+
+    # issue #10806
+    assert latex(Limit(f(x), x, 0)**2) == \
+        r"\left(\lim_{x \to 0^+} f{\left(x \right)}\right)^{2}"
+    # bi-directional limit
+    assert latex(Limit(f(x), x, 0, dir='+-')) == \
+        r"\lim_{x \to 0} f{\left(x \right)}"
+
+
+def test_latex_log():
+    assert latex(log(x)) == r"\log{\left(x \right)}"
+    assert latex(log(x), ln_notation=True) == r"\ln{\left(x \right)}"
+    assert latex(log(x) + log(y)) == \
+        r"\log{\left(x \right)} + \log{\left(y \right)}"
+    assert latex(log(x) + log(y), ln_notation=True) == \
+        r"\ln{\left(x \right)} + \ln{\left(y \right)}"
+    assert latex(pow(log(x), x)) == r"\log{\left(x \right)}^{x}"
+    assert latex(pow(log(x), x), ln_notation=True) == \
+        r"\ln{\left(x \right)}^{x}"
+
+
+def test_issue_3568():
+    beta = Symbol(r'\beta')
+    y = beta + x
+    assert latex(y) in [r'\beta + x', r'x + \beta']
+
+    beta = Symbol(r'beta')
+    y = beta + x
+    assert latex(y) in [r'\beta + x', r'x + \beta']
+
+
+def test_latex():
+    assert latex((2*tau)**Rational(7, 2)) == r"8 \sqrt{2} \tau^{\frac{7}{2}}"
+    assert latex((2*mu)**Rational(7, 2), mode='equation*') == \
+        r"\begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*}"
+    assert latex((2*mu)**Rational(7, 2), mode='equation', itex=True) == \
+        r"$$8 \sqrt{2} \mu^{\frac{7}{2}}$$"
+    assert latex([2/x, y]) == r"\left[ \frac{2}{x}, \  y\right]"
+
+
+def test_latex_dict():
+    d = {Rational(1): 1, x**2: 2, x: 3, x**3: 4}
+    assert latex(d) == \
+        r'\left\{ 1 : 1, \  x : 3, \  x^{2} : 2, \  x^{3} : 4\right\}'
+    D = Dict(d)
+    assert latex(D) == \
+        r'\left\{ 1 : 1, \  x : 3, \  x^{2} : 2, \  x^{3} : 4\right\}'
+
+
+def test_latex_list():
+    ll = [Symbol('omega1'), Symbol('a'), Symbol('alpha')]
+    assert latex(ll) == r'\left[ \omega_{1}, \  a, \  \alpha\right]'
+
+
+def test_latex_NumberSymbols():
+    assert latex(S.Catalan) == "G"
+    assert latex(S.EulerGamma) == r"\gamma"
+    assert latex(S.Exp1) == "e"
+    assert latex(S.GoldenRatio) == r"\phi"
+    assert latex(S.Pi) == r"\pi"
+    assert latex(S.TribonacciConstant) == r"\text{TribonacciConstant}"
+
+
+def test_latex_rational():
+    # tests issue 3973
+    assert latex(-Rational(1, 2)) == r"- \frac{1}{2}"
+    assert latex(Rational(-1, 2)) == r"- \frac{1}{2}"
+    assert latex(Rational(1, -2)) == r"- \frac{1}{2}"
+    assert latex(-Rational(-1, 2)) == r"\frac{1}{2}"
+    assert latex(-Rational(1, 2)*x) == r"- \frac{x}{2}"
+    assert latex(-Rational(1, 2)*x + Rational(-2, 3)*y) == \
+        r"- \frac{x}{2} - \frac{2 y}{3}"
+
+
+def test_latex_inverse():
+    # tests issue 4129
+    assert latex(1/x) == r"\frac{1}{x}"
+    assert latex(1/(x + y)) == r"\frac{1}{x + y}"
+
+
+def test_latex_DiracDelta():
+    assert latex(DiracDelta(x)) == r"\delta\left(x\right)"
+    assert latex(DiracDelta(x)**2) == r"\left(\delta\left(x\right)\right)^{2}"
+    assert latex(DiracDelta(x, 0)) == r"\delta\left(x\right)"
+    assert latex(DiracDelta(x, 5)) == \
+        r"\delta^{\left( 5 \right)}\left( x \right)"
+    assert latex(DiracDelta(x, 5)**2) == \
+        r"\left(\delta^{\left( 5 \right)}\left( x \right)\right)^{2}"
+
+
+def test_latex_Heaviside():
+    assert latex(Heaviside(x)) == r"\theta\left(x\right)"
+    assert latex(Heaviside(x)**2) == r"\left(\theta\left(x\right)\right)^{2}"
+
+
+def test_latex_KroneckerDelta():
+    assert latex(KroneckerDelta(x, y)) == r"\delta_{x y}"
+    assert latex(KroneckerDelta(x, y + 1)) == r"\delta_{x, y + 1}"
+    # issue 6578
+    assert latex(KroneckerDelta(x + 1, y)) == r"\delta_{y, x + 1}"
+    assert latex(Pow(KroneckerDelta(x, y), 2, evaluate=False)) == \
+        r"\left(\delta_{x y}\right)^{2}"
+
+
+def test_latex_LeviCivita():
+    assert latex(LeviCivita(x, y, z)) == r"\varepsilon_{x y z}"
+    assert latex(LeviCivita(x, y, z)**2) == \
+        r"\left(\varepsilon_{x y z}\right)^{2}"
+    assert latex(LeviCivita(x, y, z + 1)) == r"\varepsilon_{x, y, z + 1}"
+    assert latex(LeviCivita(x, y + 1, z)) == r"\varepsilon_{x, y + 1, z}"
+    assert latex(LeviCivita(x + 1, y, z)) == r"\varepsilon_{x + 1, y, z}"
+
+
+def test_mode():
+    expr = x + y
+    assert latex(expr) == r'x + y'
+    assert latex(expr, mode='plain') == r'x + y'
+    assert latex(expr, mode='inline') == r'$x + y$'
+    assert latex(
+        expr, mode='equation*') == r'\begin{equation*}x + y\end{equation*}'
+    assert latex(
+        expr, mode='equation') == r'\begin{equation}x + y\end{equation}'
+    raises(ValueError, lambda: latex(expr, mode='foo'))
+
+
+def test_latex_mathieu():
+    assert latex(mathieuc(x, y, z)) == r"C\left(x, y, z\right)"
+    assert latex(mathieus(x, y, z)) == r"S\left(x, y, z\right)"
+    assert latex(mathieuc(x, y, z)**2) == r"C\left(x, y, z\right)^{2}"
+    assert latex(mathieus(x, y, z)**2) == r"S\left(x, y, z\right)^{2}"
+    assert latex(mathieucprime(x, y, z)) == r"C^{\prime}\left(x, y, z\right)"
+    assert latex(mathieusprime(x, y, z)) == r"S^{\prime}\left(x, y, z\right)"
+    assert latex(mathieucprime(x, y, z)**2) == r"C^{\prime}\left(x, y, z\right)^{2}"
+    assert latex(mathieusprime(x, y, z)**2) == r"S^{\prime}\left(x, y, z\right)^{2}"
+
+def test_latex_Piecewise():
+    p = Piecewise((x, x < 1), (x**2, True))
+    assert latex(p) == r"\begin{cases} x & \text{for}\: x < 1 \\x^{2} &" \
+                       r" \text{otherwise} \end{cases}"
+    assert latex(p, itex=True) == \
+        r"\begin{cases} x & \text{for}\: x \lt 1 \\x^{2} &" \
+        r" \text{otherwise} \end{cases}"
+    p = Piecewise((x, x < 0), (0, x >= 0))
+    assert latex(p) == r'\begin{cases} x & \text{for}\: x < 0 \\0 &' \
+                       r' \text{otherwise} \end{cases}'
+    A, B = symbols("A B", commutative=False)
+    p = Piecewise((A**2, Eq(A, B)), (A*B, True))
+    s = r"\begin{cases} A^{2} & \text{for}\: A = B \\A B & \text{otherwise} \end{cases}"
+    assert latex(p) == s
+    assert latex(A*p) == r"A \left(%s\right)" % s
+    assert latex(p*A) == r"\left(%s\right) A" % s
+    assert latex(Piecewise((x, x < 1), (x**2, x < 2))) == \
+        r'\begin{cases} x & ' \
+        r'\text{for}\: x < 1 \\x^{2} & \text{for}\: x < 2 \end{cases}'
+
+
+def test_latex_Matrix():
+    M = Matrix([[1 + x, y], [y, x - 1]])
+    assert latex(M) == \
+        r'\left[\begin{matrix}x + 1 & y\\y & x - 1\end{matrix}\right]'
+    assert latex(M, mode='inline') == \
+        r'$\left[\begin{smallmatrix}x + 1 & y\\' \
+        r'y & x - 1\end{smallmatrix}\right]$'
+    assert latex(M, mat_str='array') == \
+        r'\left[\begin{array}{cc}x + 1 & y\\y & x - 1\end{array}\right]'
+    assert latex(M, mat_str='bmatrix') == \
+        r'\left[\begin{bmatrix}x + 1 & y\\y & x - 1\end{bmatrix}\right]'
+    assert latex(M, mat_delim=None, mat_str='bmatrix') == \
+        r'\begin{bmatrix}x + 1 & y\\y & x - 1\end{bmatrix}'
+
+    M2 = Matrix(1, 11, range(11))
+    assert latex(M2) == \
+        r'\left[\begin{array}{ccccccccccc}' \
+        r'0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10\end{array}\right]'
+
+
+def test_latex_matrix_with_functions():
+    t = symbols('t')
+    theta1 = symbols('theta1', cls=Function)
+
+    M = Matrix([[sin(theta1(t)), cos(theta1(t))],
+                [cos(theta1(t).diff(t)), sin(theta1(t).diff(t))]])
+
+    expected = (r'\left[\begin{matrix}\sin{\left('
+                r'\theta_{1}{\left(t \right)} \right)} & '
+                r'\cos{\left(\theta_{1}{\left(t \right)} \right)'
+                r'}\\\cos{\left(\frac{d}{d t} \theta_{1}{\left(t '
+                r'\right)} \right)} & \sin{\left(\frac{d}{d t} '
+                r'\theta_{1}{\left(t \right)} \right'
+                r')}\end{matrix}\right]')
+
+    assert latex(M) == expected
+
+
+def test_latex_NDimArray():
+    x, y, z, w = symbols("x y z w")
+
+    for ArrayType in (ImmutableDenseNDimArray, ImmutableSparseNDimArray,
+                      MutableDenseNDimArray, MutableSparseNDimArray):
+        # Basic: scalar array
+        M = ArrayType(x)
+
+        assert latex(M) == r"x"
+
+        M = ArrayType([[1 / x, y], [z, w]])
+        M1 = ArrayType([1 / x, y, z])
+
+        M2 = tensorproduct(M1, M)
+        M3 = tensorproduct(M, M)
+
+        assert latex(M) == \
+            r'\left[\begin{matrix}\frac{1}{x} & y\\z & w\end{matrix}\right]'
+        assert latex(M1) == \
+            r"\left[\begin{matrix}\frac{1}{x} & y & z\end{matrix}\right]"
+        assert latex(M2) == \
+            r"\left[\begin{matrix}" \
+            r"\left[\begin{matrix}\frac{1}{x^{2}} & \frac{y}{x}\\\frac{z}{x} & \frac{w}{x}\end{matrix}\right] & " \
+            r"\left[\begin{matrix}\frac{y}{x} & y^{2}\\y z & w y\end{matrix}\right] & " \
+            r"\left[\begin{matrix}\frac{z}{x} & y z\\z^{2} & w z\end{matrix}\right]" \
+            r"\end{matrix}\right]"
+        assert latex(M3) == \
+            r"""\left[\begin{matrix}"""\
+            r"""\left[\begin{matrix}\frac{1}{x^{2}} & \frac{y}{x}\\\frac{z}{x} & \frac{w}{x}\end{matrix}\right] & """\
+            r"""\left[\begin{matrix}\frac{y}{x} & y^{2}\\y z & w y\end{matrix}\right]\\"""\
+            r"""\left[\begin{matrix}\frac{z}{x} & y z\\z^{2} & w z\end{matrix}\right] & """\
+            r"""\left[\begin{matrix}\frac{w}{x} & w y\\w z & w^{2}\end{matrix}\right]"""\
+            r"""\end{matrix}\right]"""
+
+        Mrow = ArrayType([[x, y, 1/z]])
+        Mcolumn = ArrayType([[x], [y], [1/z]])
+        Mcol2 = ArrayType([Mcolumn.tolist()])
+
+        assert latex(Mrow) == \
+            r"\left[\left[\begin{matrix}x & y & \frac{1}{z}\end{matrix}\right]\right]"
+        assert latex(Mcolumn) == \
+            r"\left[\begin{matrix}x\\y\\\frac{1}{z}\end{matrix}\right]"
+        assert latex(Mcol2) == \
+            r'\left[\begin{matrix}\left[\begin{matrix}x\\y\\\frac{1}{z}\end{matrix}\right]\end{matrix}\right]'
+
+
+def test_latex_mul_symbol():
+    assert latex(4*4**x, mul_symbol='times') == r"4 \times 4^{x}"
+    assert latex(4*4**x, mul_symbol='dot') == r"4 \cdot 4^{x}"
+    assert latex(4*4**x, mul_symbol='ldot') == r"4 \,.\, 4^{x}"
+
+    assert latex(4*x, mul_symbol='times') == r"4 \times x"
+    assert latex(4*x, mul_symbol='dot') == r"4 \cdot x"
+    assert latex(4*x, mul_symbol='ldot') == r"4 \,.\, x"
+
+
+def test_latex_issue_4381():
+    y = 4*4**log(2)
+    assert latex(y) == r'4 \cdot 4^{\log{\left(2 \right)}}'
+    assert latex(1/y) == r'\frac{1}{4 \cdot 4^{\log{\left(2 \right)}}}'
+
+
+def test_latex_issue_4576():
+    assert latex(Symbol("beta_13_2")) == r"\beta_{13 2}"
+    assert latex(Symbol("beta_132_20")) == r"\beta_{132 20}"
+    assert latex(Symbol("beta_13")) == r"\beta_{13}"
+    assert latex(Symbol("x_a_b")) == r"x_{a b}"
+    assert latex(Symbol("x_1_2_3")) == r"x_{1 2 3}"
+    assert latex(Symbol("x_a_b1")) == r"x_{a b1}"
+    assert latex(Symbol("x_a_1")) == r"x_{a 1}"
+    assert latex(Symbol("x_1_a")) == r"x_{1 a}"
+    assert latex(Symbol("x_1^aa")) == r"x^{aa}_{1}"
+    assert latex(Symbol("x_1__aa")) == r"x^{aa}_{1}"
+    assert latex(Symbol("x_11^a")) == r"x^{a}_{11}"
+    assert latex(Symbol("x_11__a")) == r"x^{a}_{11}"
+    assert latex(Symbol("x_a_a_a_a")) == r"x_{a a a a}"
+    assert latex(Symbol("x_a_a^a^a")) == r"x^{a a}_{a a}"
+    assert latex(Symbol("x_a_a__a__a")) == r"x^{a a}_{a a}"
+    assert latex(Symbol("alpha_11")) == r"\alpha_{11}"
+    assert latex(Symbol("alpha_11_11")) == r"\alpha_{11 11}"
+    assert latex(Symbol("alpha_alpha")) == r"\alpha_{\alpha}"
+    assert latex(Symbol("alpha^aleph")) == r"\alpha^{\aleph}"
+    assert latex(Symbol("alpha__aleph")) == r"\alpha^{\aleph}"
+
+
+def test_latex_pow_fraction():
+    x = Symbol('x')
+    # Testing exp
+    assert r'e^{-x}' in latex(exp(-x)/2).replace(' ', '')  # Remove Whitespace
+
+    # Testing e^{-x} in case future changes alter behavior of muls or fracs
+    # In particular current output is \frac{1}{2}e^{- x} but perhaps this will
+    # change to \frac{e^{-x}}{2}
+
+    # Testing general, non-exp, power
+    assert r'3^{-x}' in latex(3**-x/2).replace(' ', '')
+
+
+def test_noncommutative():
+    A, B, C = symbols('A,B,C', commutative=False)
+
+    assert latex(A*B*C**-1) == r"A B C^{-1}"
+    assert latex(C**-1*A*B) == r"C^{-1} A B"
+    assert latex(A*C**-1*B) == r"A C^{-1} B"
+
+
+def test_latex_order():
+    expr = x**3 + x**2*y + y**4 + 3*x*y**3
+
+    assert latex(expr, order='lex') == r"x^{3} + x^{2} y + 3 x y^{3} + y^{4}"
+    assert latex(
+        expr, order='rev-lex') == r"y^{4} + 3 x y^{3} + x^{2} y + x^{3}"
+    assert latex(expr, order='none') == r"x^{3} + y^{4} + y x^{2} + 3 x y^{3}"
+
+
+def test_latex_Lambda():
+    assert latex(Lambda(x, x + 1)) == r"\left( x \mapsto x + 1 \right)"
+    assert latex(Lambda((x, y), x + 1)) == r"\left( \left( x, \  y\right) \mapsto x + 1 \right)"
+    assert latex(Lambda(x, x)) == r"\left( x \mapsto x \right)"
+
+def test_latex_PolyElement():
+    Ruv, u, v = ring("u,v", ZZ)
+    Rxyz, x, y, z = ring("x,y,z", Ruv)
+
+    assert latex(x - x) == r"0"
+    assert latex(x - 1) == r"x - 1"
+    assert latex(x + 1) == r"x + 1"
+
+    assert latex((u**2 + 3*u*v + 1)*x**2*y + u + 1) == \
+        r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + u + 1"
+    assert latex((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x) == \
+        r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + \left(u + 1\right) x"
+    assert latex((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1) == \
+        r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + \left(u + 1\right) x + 1"
+    assert latex((-u**2 + 3*u*v - 1)*x**2*y - (u + 1)*x - 1) == \
+        r"-\left({u}^{2} - 3 u v + 1\right) {x}^{2} y - \left(u + 1\right) x - 1"
+
+    assert latex(-(v**2 + v + 1)*x + 3*u*v + 1) == \
+        r"-\left({v}^{2} + v + 1\right) x + 3 u v + 1"
+    assert latex(-(v**2 + v + 1)*x - 3*u*v + 1) == \
+        r"-\left({v}^{2} + v + 1\right) x - 3 u v + 1"
+
+
+def test_latex_FracElement():
+    Fuv, u, v = field("u,v", ZZ)
+    Fxyzt, x, y, z, t = field("x,y,z,t", Fuv)
+
+    assert latex(x - x) == r"0"
+    assert latex(x - 1) == r"x - 1"
+    assert latex(x + 1) == r"x + 1"
+
+    assert latex(x/3) == r"\frac{x}{3}"
+    assert latex(x/z) == r"\frac{x}{z}"
+    assert latex(x*y/z) == r"\frac{x y}{z}"
+    assert latex(x/(z*t)) == r"\frac{x}{z t}"
+    assert latex(x*y/(z*t)) == r"\frac{x y}{z t}"
+
+    assert latex((x - 1)/y) == r"\frac{x - 1}{y}"
+    assert latex((x + 1)/y) == r"\frac{x + 1}{y}"
+    assert latex((-x - 1)/y) == r"\frac{-x - 1}{y}"
+    assert latex((x + 1)/(y*z)) == r"\frac{x + 1}{y z}"
+    assert latex(-y/(x + 1)) == r"\frac{-y}{x + 1}"
+    assert latex(y*z/(x + 1)) == r"\frac{y z}{x + 1}"
+
+    assert latex(((u + 1)*x*y + 1)/((v - 1)*z - 1)) == \
+        r"\frac{\left(u + 1\right) x y + 1}{\left(v - 1\right) z - 1}"
+    assert latex(((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)) == \
+        r"\frac{\left(u + 1\right) x y + 1}{\left(v - 1\right) z - u v t - 1}"
+
+
+def test_latex_Poly():
+    assert latex(Poly(x**2 + 2 * x, x)) == \
+        r"\operatorname{Poly}{\left( x^{2} + 2 x, x, domain=\mathbb{Z} \right)}"
+    assert latex(Poly(x/y, x)) == \
+        r"\operatorname{Poly}{\left( \frac{1}{y} x, x, domain=\mathbb{Z}\left(y\right) \right)}"
+    assert latex(Poly(2.0*x + y)) == \
+        r"\operatorname{Poly}{\left( 2.0 x + 1.0 y, x, y, domain=\mathbb{R} \right)}"
+
+
+def test_latex_Poly_order():
+    assert latex(Poly([a, 1, b, 2, c, 3], x)) == \
+        r'\operatorname{Poly}{\left( a x^{5} + x^{4} + b x^{3} + 2 x^{2} + c'\
+        r' x + 3, x, domain=\mathbb{Z}\left[a, b, c\right] \right)}'
+    assert latex(Poly([a, 1, b+c, 2, 3], x)) == \
+        r'\operatorname{Poly}{\left( a x^{4} + x^{3} + \left(b + c\right) '\
+        r'x^{2} + 2 x + 3, x, domain=\mathbb{Z}\left[a, b, c\right] \right)}'
+    assert latex(Poly(a*x**3 + x**2*y - x*y - c*y**3 - b*x*y**2 + y - a*x + b,
+                      (x, y))) == \
+        r'\operatorname{Poly}{\left( a x^{3} + x^{2}y -  b xy^{2} - xy -  '\
+        r'a x -  c y^{3} + y + b, x, y, domain=\mathbb{Z}\left[a, b, c\right] \right)}'
+
+
+def test_latex_ComplexRootOf():
+    assert latex(rootof(x**5 + x + 3, 0)) == \
+        r"\operatorname{CRootOf} {\left(x^{5} + x + 3, 0\right)}"
+
+
+def test_latex_RootSum():
+    assert latex(RootSum(x**5 + x + 3, sin)) == \
+        r"\operatorname{RootSum} {\left(x^{5} + x + 3, \left( x \mapsto \sin{\left(x \right)} \right)\right)}"
+
+
+def test_settings():
+    raises(TypeError, lambda: latex(x*y, method="garbage"))
+
+
+def test_latex_numbers():
+    assert latex(catalan(n)) == r"C_{n}"
+    assert latex(catalan(n)**2) == r"C_{n}^{2}"
+    assert latex(bernoulli(n)) == r"B_{n}"
+    assert latex(bernoulli(n, x)) == r"B_{n}\left(x\right)"
+    assert latex(bernoulli(n)**2) == r"B_{n}^{2}"
+    assert latex(bernoulli(n, x)**2) == r"B_{n}^{2}\left(x\right)"
+    assert latex(genocchi(n)) == r"G_{n}"
+    assert latex(genocchi(n, x)) == r"G_{n}\left(x\right)"
+    assert latex(genocchi(n)**2) == r"G_{n}^{2}"
+    assert latex(genocchi(n, x)**2) == r"G_{n}^{2}\left(x\right)"
+    assert latex(bell(n)) == r"B_{n}"
+    assert latex(bell(n, x)) == r"B_{n}\left(x\right)"
+    assert latex(bell(n, m, (x, y))) == r"B_{n, m}\left(x, y\right)"
+    assert latex(bell(n)**2) == r"B_{n}^{2}"
+    assert latex(bell(n, x)**2) == r"B_{n}^{2}\left(x\right)"
+    assert latex(bell(n, m, (x, y))**2) == r"B_{n, m}^{2}\left(x, y\right)"
+    assert latex(fibonacci(n)) == r"F_{n}"
+    assert latex(fibonacci(n, x)) == r"F_{n}\left(x\right)"
+    assert latex(fibonacci(n)**2) == r"F_{n}^{2}"
+    assert latex(fibonacci(n, x)**2) == r"F_{n}^{2}\left(x\right)"
+    assert latex(lucas(n)) == r"L_{n}"
+    assert latex(lucas(n)**2) == r"L_{n}^{2}"
+    assert latex(tribonacci(n)) == r"T_{n}"
+    assert latex(tribonacci(n, x)) == r"T_{n}\left(x\right)"
+    assert latex(tribonacci(n)**2) == r"T_{n}^{2}"
+    assert latex(tribonacci(n, x)**2) == r"T_{n}^{2}\left(x\right)"
+    assert latex(mobius(n)) == r"\mu\left(n\right)"
+    assert latex(mobius(n)**2) == r"\mu^{2}\left(n\right)"
+
+
+def test_latex_euler():
+    assert latex(euler(n)) == r"E_{n}"
+    assert latex(euler(n, x)) == r"E_{n}\left(x\right)"
+    assert latex(euler(n, x)**2) == r"E_{n}^{2}\left(x\right)"
+
+
+def test_lamda():
+    assert latex(Symbol('lamda')) == r"\lambda"
+    assert latex(Symbol('Lamda')) == r"\Lambda"
+
+
+def test_custom_symbol_names():
+    x = Symbol('x')
+    y = Symbol('y')
+    assert latex(x) == r"x"
+    assert latex(x, symbol_names={x: "x_i"}) == r"x_i"
+    assert latex(x + y, symbol_names={x: "x_i"}) == r"x_i + y"
+    assert latex(x**2, symbol_names={x: "x_i"}) == r"x_i^{2}"
+    assert latex(x + y, symbol_names={x: "x_i", y: "y_j"}) == r"x_i + y_j"
+
+
+def test_matAdd():
+    C = MatrixSymbol('C', 5, 5)
+    B = MatrixSymbol('B', 5, 5)
+
+    n = symbols("n")
+    h = MatrixSymbol("h", 1, 1)
+
+    assert latex(C - 2*B) in [r'- 2 B + C', r'C -2 B']
+    assert latex(C + 2*B) in [r'2 B + C', r'C + 2 B']
+    assert latex(B - 2*C) in [r'B - 2 C', r'- 2 C + B']
+    assert latex(B + 2*C) in [r'B + 2 C', r'2 C + B']
+
+    assert latex(n * h - (-h + h.T) * (h + h.T)) == 'n h - \\left(- h + h^{T}\\right) \\left(h + h^{T}\\right)'
+    assert latex(MatAdd(MatAdd(h, h), MatAdd(h, h))) == '\\left(h + h\\right) + \\left(h + h\\right)'
+    assert latex(MatMul(MatMul(h, h), MatMul(h, h))) == '\\left(h h\\right) \\left(h h\\right)'
+
+
+def test_matMul():
+    A = MatrixSymbol('A', 5, 5)
+    B = MatrixSymbol('B', 5, 5)
+    x = Symbol('x')
+    assert latex(2*A) == r'2 A'
+    assert latex(2*x*A) == r'2 x A'
+    assert latex(-2*A) == r'- 2 A'
+    assert latex(1.5*A) == r'1.5 A'
+    assert latex(sqrt(2)*A) == r'\sqrt{2} A'
+    assert latex(-sqrt(2)*A) == r'- \sqrt{2} A'
+    assert latex(2*sqrt(2)*x*A) == r'2 \sqrt{2} x A'
+    assert latex(-2*A*(A + 2*B)) in [r'- 2 A \left(A + 2 B\right)',
+                                        r'- 2 A \left(2 B + A\right)']
+
+
+def test_latex_MatrixSlice():
+    n = Symbol('n', integer=True)
+    x, y, z, w, t, = symbols('x y z w t')
+    X = MatrixSymbol('X', n, n)
+    Y = MatrixSymbol('Y', 10, 10)
+    Z = MatrixSymbol('Z', 10, 10)
+
+    assert latex(MatrixSlice(X, (None, None, None), (None, None, None))) == r'X\left[:, :\right]'
+    assert latex(X[x:x + 1, y:y + 1]) == r'X\left[x:x + 1, y:y + 1\right]'
+    assert latex(X[x:x + 1:2, y:y + 1:2]) == r'X\left[x:x + 1:2, y:y + 1:2\right]'
+    assert latex(X[:x, y:]) == r'X\left[:x, y:\right]'
+    assert latex(X[:x, y:]) == r'X\left[:x, y:\right]'
+    assert latex(X[x:, :y]) == r'X\left[x:, :y\right]'
+    assert latex(X[x:y, z:w]) == r'X\left[x:y, z:w\right]'
+    assert latex(X[x:y:t, w:t:x]) == r'X\left[x:y:t, w:t:x\right]'
+    assert latex(X[x::y, t::w]) == r'X\left[x::y, t::w\right]'
+    assert latex(X[:x:y, :t:w]) == r'X\left[:x:y, :t:w\right]'
+    assert latex(X[::x, ::y]) == r'X\left[::x, ::y\right]'
+    assert latex(MatrixSlice(X, (0, None, None), (0, None, None))) == r'X\left[:, :\right]'
+    assert latex(MatrixSlice(X, (None, n, None), (None, n, None))) == r'X\left[:, :\right]'
+    assert latex(MatrixSlice(X, (0, n, None), (0, n, None))) == r'X\left[:, :\right]'
+    assert latex(MatrixSlice(X, (0, n, 2), (0, n, 2))) == r'X\left[::2, ::2\right]'
+    assert latex(X[1:2:3, 4:5:6]) == r'X\left[1:2:3, 4:5:6\right]'
+    assert latex(X[1:3:5, 4:6:8]) == r'X\left[1:3:5, 4:6:8\right]'
+    assert latex(X[1:10:2]) == r'X\left[1:10:2, :\right]'
+    assert latex(Y[:5, 1:9:2]) == r'Y\left[:5, 1:9:2\right]'
+    assert latex(Y[:5, 1:10:2]) == r'Y\left[:5, 1::2\right]'
+    assert latex(Y[5, :5:2]) == r'Y\left[5:6, :5:2\right]'
+    assert latex(X[0:1, 0:1]) == r'X\left[:1, :1\right]'
+    assert latex(X[0:1:2, 0:1:2]) == r'X\left[:1:2, :1:2\right]'
+    assert latex((Y + Z)[2:, 2:]) == r'\left(Y + Z\right)\left[2:, 2:\right]'
+
+
+def test_latex_RandomDomain():
+    from sympy.stats import Normal, Die, Exponential, pspace, where
+    from sympy.stats.rv import RandomDomain
+
+    X = Normal('x1', 0, 1)
+    assert latex(where(X > 0)) == r"\text{Domain: }0 < x_{1} \wedge x_{1} < \infty"
+
+    D = Die('d1', 6)
+    assert latex(where(D > 4)) == r"\text{Domain: }d_{1} = 5 \vee d_{1} = 6"
+
+    A = Exponential('a', 1)
+    B = Exponential('b', 1)
+    assert latex(
+        pspace(Tuple(A, B)).domain) == \
+        r"\text{Domain: }0 \leq a \wedge 0 \leq b \wedge a < \infty \wedge b < \infty"
+
+    assert latex(RandomDomain(FiniteSet(x), FiniteSet(1, 2))) == \
+        r'\text{Domain: }\left\{x\right\} \in \left\{1, 2\right\}'
+
+def test_PrettyPoly():
+    from sympy.polys.domains import QQ
+    F = QQ.frac_field(x, y)
+    R = QQ[x, y]
+
+    assert latex(F.convert(x/(x + y))) == latex(x/(x + y))
+    assert latex(R.convert(x + y)) == latex(x + y)
+
+
+def test_integral_transforms():
+    x = Symbol("x")
+    k = Symbol("k")
+    f = Function("f")
+    a = Symbol("a")
+    b = Symbol("b")
+
+    assert latex(MellinTransform(f(x), x, k)) == \
+        r"\mathcal{M}_{x}\left[f{\left(x \right)}\right]\left(k\right)"
+    assert latex(InverseMellinTransform(f(k), k, x, a, b)) == \
+        r"\mathcal{M}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)"
+
+    assert latex(LaplaceTransform(f(x), x, k)) == \
+        r"\mathcal{L}_{x}\left[f{\left(x \right)}\right]\left(k\right)"
+    assert latex(InverseLaplaceTransform(f(k), k, x, (a, b))) == \
+        r"\mathcal{L}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)"
+
+    assert latex(FourierTransform(f(x), x, k)) == \
+        r"\mathcal{F}_{x}\left[f{\left(x \right)}\right]\left(k\right)"
+    assert latex(InverseFourierTransform(f(k), k, x)) == \
+        r"\mathcal{F}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)"
+
+    assert latex(CosineTransform(f(x), x, k)) == \
+        r"\mathcal{COS}_{x}\left[f{\left(x \right)}\right]\left(k\right)"
+    assert latex(InverseCosineTransform(f(k), k, x)) == \
+        r"\mathcal{COS}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)"
+
+    assert latex(SineTransform(f(x), x, k)) == \
+        r"\mathcal{SIN}_{x}\left[f{\left(x \right)}\right]\left(k\right)"
+    assert latex(InverseSineTransform(f(k), k, x)) == \
+        r"\mathcal{SIN}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)"
+
+
+def test_PolynomialRingBase():
+    from sympy.polys.domains import QQ
+    assert latex(QQ.old_poly_ring(x, y)) == r"\mathbb{Q}\left[x, y\right]"
+    assert latex(QQ.old_poly_ring(x, y, order="ilex")) == \
+        r"S_<^{-1}\mathbb{Q}\left[x, y\right]"
+
+
+def test_categories():
+    from sympy.categories import (Object, IdentityMorphism,
+                                  NamedMorphism, Category, Diagram,
+                                  DiagramGrid)
+
+    A1 = Object("A1")
+    A2 = Object("A2")
+    A3 = Object("A3")
+
+    f1 = NamedMorphism(A1, A2, "f1")
+    f2 = NamedMorphism(A2, A3, "f2")
+    id_A1 = IdentityMorphism(A1)
+
+    K1 = Category("K1")
+
+    assert latex(A1) == r"A_{1}"
+    assert latex(f1) == r"f_{1}:A_{1}\rightarrow A_{2}"
+    assert latex(id_A1) == r"id:A_{1}\rightarrow A_{1}"
+    assert latex(f2*f1) == r"f_{2}\circ f_{1}:A_{1}\rightarrow A_{3}"
+
+    assert latex(K1) == r"\mathbf{K_{1}}"
+
+    d = Diagram()
+    assert latex(d) == r"\emptyset"
+
+    d = Diagram({f1: "unique", f2: S.EmptySet})
+    assert latex(d) == r"\left\{ f_{2}\circ f_{1}:A_{1}" \
+        r"\rightarrow A_{3} : \emptyset, \  id:A_{1}\rightarrow " \
+        r"A_{1} : \emptyset, \  id:A_{2}\rightarrow A_{2} : " \
+        r"\emptyset, \  id:A_{3}\rightarrow A_{3} : \emptyset, " \
+        r"\  f_{1}:A_{1}\rightarrow A_{2} : \left\{unique\right\}, " \
+        r"\  f_{2}:A_{2}\rightarrow A_{3} : \emptyset\right\}"
+
+    d = Diagram({f1: "unique", f2: S.EmptySet}, {f2 * f1: "unique"})
+    assert latex(d) == r"\left\{ f_{2}\circ f_{1}:A_{1}" \
+        r"\rightarrow A_{3} : \emptyset, \  id:A_{1}\rightarrow " \
+        r"A_{1} : \emptyset, \  id:A_{2}\rightarrow A_{2} : " \
+        r"\emptyset, \  id:A_{3}\rightarrow A_{3} : \emptyset, " \
+        r"\  f_{1}:A_{1}\rightarrow A_{2} : \left\{unique\right\}," \
+        r" \  f_{2}:A_{2}\rightarrow A_{3} : \emptyset\right\}" \
+        r"\Longrightarrow \left\{ f_{2}\circ f_{1}:A_{1}" \
+        r"\rightarrow A_{3} : \left\{unique\right\}\right\}"
+
+    # A linear diagram.
+    A = Object("A")
+    B = Object("B")
+    C = Object("C")
+    f = NamedMorphism(A, B, "f")
+    g = NamedMorphism(B, C, "g")
+    d = Diagram([f, g])
+    grid = DiagramGrid(d)
+
+    assert latex(grid) == r"\begin{array}{cc}" + "\n" \
+        r"A & B \\" + "\n" \
+        r" & C " + "\n" \
+        r"\end{array}" + "\n"
+
+
+def test_Modules():
+    from sympy.polys.domains import QQ
+    from sympy.polys.agca import homomorphism
+
+    R = QQ.old_poly_ring(x, y)
+    F = R.free_module(2)
+    M = F.submodule([x, y], [1, x**2])
+
+    assert latex(F) == r"{\mathbb{Q}\left[x, y\right]}^{2}"
+    assert latex(M) == \
+        r"\left\langle {\left[ {x},{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle"
+
+    I = R.ideal(x**2, y)
+    assert latex(I) == r"\left\langle {x^{2}},{y} \right\rangle"
+
+    Q = F / M
+    assert latex(Q) == \
+        r"\frac{{\mathbb{Q}\left[x, y\right]}^{2}}{\left\langle {\left[ {x},"\
+        r"{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle}"
+    assert latex(Q.submodule([1, x**3/2], [2, y])) == \
+        r"\left\langle {{\left[ {1},{\frac{x^{3}}{2}} \right]} + {\left"\
+        r"\langle {\left[ {x},{y} \right]},{\left[ {1},{x^{2}} \right]} "\
+        r"\right\rangle}},{{\left[ {2},{y} \right]} + {\left\langle {\left[ "\
+        r"{x},{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle}} \right\rangle"
+
+    h = homomorphism(QQ.old_poly_ring(x).free_module(2),
+                     QQ.old_poly_ring(x).free_module(2), [0, 0])
+
+    assert latex(h) == \
+        r"{\left[\begin{matrix}0 & 0\\0 & 0\end{matrix}\right]} : "\
+        r"{{\mathbb{Q}\left[x\right]}^{2}} \to {{\mathbb{Q}\left[x\right]}^{2}}"
+
+
+def test_QuotientRing():
+    from sympy.polys.domains import QQ
+    R = QQ.old_poly_ring(x)/[x**2 + 1]
+
+    assert latex(R) == \
+        r"\frac{\mathbb{Q}\left[x\right]}{\left\langle {x^{2} + 1} \right\rangle}"
+    assert latex(R.one) == r"{1} + {\left\langle {x^{2} + 1} \right\rangle}"
+
+
+def test_Tr():
+    #TODO: Handle indices
+    A, B = symbols('A B', commutative=False)
+    t = Tr(A*B)
+    assert latex(t) == r'\operatorname{tr}\left(A B\right)'
+
+
+def test_Determinant():
+    from sympy.matrices import Determinant, Inverse, BlockMatrix, OneMatrix, ZeroMatrix
+    m = Matrix(((1, 2), (3, 4)))
+    assert latex(Determinant(m)) == '\\left|{\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}}\\right|'
+    assert latex(Determinant(Inverse(m))) == \
+        '\\left|{\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right]^{-1}}\\right|'
+    X = MatrixSymbol('X', 2, 2)
+    assert latex(Determinant(X)) == '\\left|{X}\\right|'
+    assert latex(Determinant(X + m)) == \
+        '\\left|{\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] + X}\\right|'
+    assert latex(Determinant(BlockMatrix(((OneMatrix(2, 2), X),
+                                          (m, ZeroMatrix(2, 2)))))) == \
+        '\\left|{\\begin{matrix}1 & X\\\\\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] & 0\\end{matrix}}\\right|'
+
+
+def test_Adjoint():
+    from sympy.matrices import Adjoint, Inverse, Transpose
+    X = MatrixSymbol('X', 2, 2)
+    Y = MatrixSymbol('Y', 2, 2)
+    assert latex(Adjoint(X)) == r'X^{\dagger}'
+    assert latex(Adjoint(X + Y)) == r'\left(X + Y\right)^{\dagger}'
+    assert latex(Adjoint(X) + Adjoint(Y)) == r'X^{\dagger} + Y^{\dagger}'
+    assert latex(Adjoint(X*Y)) == r'\left(X Y\right)^{\dagger}'
+    assert latex(Adjoint(Y)*Adjoint(X)) == r'Y^{\dagger} X^{\dagger}'
+    assert latex(Adjoint(X**2)) == r'\left(X^{2}\right)^{\dagger}'
+    assert latex(Adjoint(X)**2) == r'\left(X^{\dagger}\right)^{2}'
+    assert latex(Adjoint(Inverse(X))) == r'\left(X^{-1}\right)^{\dagger}'
+    assert latex(Inverse(Adjoint(X))) == r'\left(X^{\dagger}\right)^{-1}'
+    assert latex(Adjoint(Transpose(X))) == r'\left(X^{T}\right)^{\dagger}'
+    assert latex(Transpose(Adjoint(X))) == r'\left(X^{\dagger}\right)^{T}'
+    assert latex(Transpose(Adjoint(X) + Y)) == r'\left(X^{\dagger} + Y\right)^{T}'
+    m = Matrix(((1, 2), (3, 4)))
+    assert latex(Adjoint(m)) == '\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right]^{\\dagger}'
+    assert latex(Adjoint(m+X)) == \
+        '\\left(\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] + X\\right)^{\\dagger}'
+    from sympy.matrices import BlockMatrix, OneMatrix, ZeroMatrix
+    assert latex(Adjoint(BlockMatrix(((OneMatrix(2, 2), X),
+                                      (m, ZeroMatrix(2, 2)))))) == \
+        '\\left[\\begin{matrix}1 & X\\\\\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] & 0\\end{matrix}\\right]^{\\dagger}'
+    # Issue 20959
+    Mx = MatrixSymbol('M^x', 2, 2)
+    assert latex(Adjoint(Mx)) == r'\left(M^{x}\right)^{\dagger}'
+
+    # adjoint style
+    assert latex(Adjoint(X), adjoint_style="star") == r'X^{\ast}'
+    assert latex(Adjoint(X + Y), adjoint_style="hermitian") == r'\left(X + Y\right)^{\mathsf{H}}'
+    assert latex(Adjoint(X) + Adjoint(Y), adjoint_style="dagger") == r'X^{\dagger} + Y^{\dagger}'
+    assert latex(Adjoint(Y)*Adjoint(X)) == r'Y^{\dagger} X^{\dagger}'
+    assert latex(Adjoint(X**2), adjoint_style="star") == r'\left(X^{2}\right)^{\ast}'
+    assert latex(Adjoint(X)**2, adjoint_style="hermitian") == r'\left(X^{\mathsf{H}}\right)^{2}'
+
+def test_Transpose():
+    from sympy.matrices import Transpose, MatPow, HadamardPower
+    X = MatrixSymbol('X', 2, 2)
+    Y = MatrixSymbol('Y', 2, 2)
+    assert latex(Transpose(X)) == r'X^{T}'
+    assert latex(Transpose(X + Y)) == r'\left(X + Y\right)^{T}'
+
+    assert latex(Transpose(HadamardPower(X, 2))) == r'\left(X^{\circ {2}}\right)^{T}'
+    assert latex(HadamardPower(Transpose(X), 2)) == r'\left(X^{T}\right)^{\circ {2}}'
+    assert latex(Transpose(MatPow(X, 2))) == r'\left(X^{2}\right)^{T}'
+    assert latex(MatPow(Transpose(X), 2)) == r'\left(X^{T}\right)^{2}'
+    m = Matrix(((1, 2), (3, 4)))
+    assert latex(Transpose(m)) == '\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right]^{T}'
+    assert latex(Transpose(m+X)) == \
+        '\\left(\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] + X\\right)^{T}'
+    from sympy.matrices import BlockMatrix, OneMatrix, ZeroMatrix
+    assert latex(Transpose(BlockMatrix(((OneMatrix(2, 2), X),
+                                        (m, ZeroMatrix(2, 2)))))) == \
+        '\\left[\\begin{matrix}1 & X\\\\\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] & 0\\end{matrix}\\right]^{T}'
+    # Issue 20959
+    Mx = MatrixSymbol('M^x', 2, 2)
+    assert latex(Transpose(Mx)) == r'\left(M^{x}\right)^{T}'
+
+
+def test_Hadamard():
+    from sympy.matrices import HadamardProduct, HadamardPower
+    from sympy.matrices.expressions import MatAdd, MatMul, MatPow
+    X = MatrixSymbol('X', 2, 2)
+    Y = MatrixSymbol('Y', 2, 2)
+    assert latex(HadamardProduct(X, Y*Y)) == r'X \circ Y^{2}'
+    assert latex(HadamardProduct(X, Y)*Y) == r'\left(X \circ Y\right) Y'
+
+    assert latex(HadamardPower(X, 2)) == r'X^{\circ {2}}'
+    assert latex(HadamardPower(X, -1)) == r'X^{\circ \left({-1}\right)}'
+    assert latex(HadamardPower(MatAdd(X, Y), 2)) == \
+        r'\left(X + Y\right)^{\circ {2}}'
+    assert latex(HadamardPower(MatMul(X, Y), 2)) == \
+        r'\left(X Y\right)^{\circ {2}}'
+
+    assert latex(HadamardPower(MatPow(X, -1), -1)) == \
+        r'\left(X^{-1}\right)^{\circ \left({-1}\right)}'
+    assert latex(MatPow(HadamardPower(X, -1), -1)) == \
+        r'\left(X^{\circ \left({-1}\right)}\right)^{-1}'
+
+    assert latex(HadamardPower(X, n+1)) == \
+        r'X^{\circ \left({n + 1}\right)}'
+
+
+def test_MatPow():
+    from sympy.matrices.expressions import MatPow
+    X = MatrixSymbol('X', 2, 2)
+    Y = MatrixSymbol('Y', 2, 2)
+    assert latex(MatPow(X, 2)) == 'X^{2}'
+    assert latex(MatPow(X*X, 2)) == '\\left(X^{2}\\right)^{2}'
+    assert latex(MatPow(X*Y, 2)) == '\\left(X Y\\right)^{2}'
+    assert latex(MatPow(X + Y, 2)) == '\\left(X + Y\\right)^{2}'
+    assert latex(MatPow(X + X, 2)) == '\\left(2 X\\right)^{2}'
+    # Issue 20959
+    Mx = MatrixSymbol('M^x', 2, 2)
+    assert latex(MatPow(Mx, 2)) == r'\left(M^{x}\right)^{2}'
+
+
+def test_ElementwiseApplyFunction():
+    X = MatrixSymbol('X', 2, 2)
+    expr = (X.T*X).applyfunc(sin)
+    assert latex(expr) == r"{\left( d \mapsto \sin{\left(d \right)} \right)}_{\circ}\left({X^{T} X}\right)"
+    expr = X.applyfunc(Lambda(x, 1/x))
+    assert latex(expr) == r'{\left( x \mapsto \frac{1}{x} \right)}_{\circ}\left({X}\right)'
+
+
+def test_ZeroMatrix():
+    from sympy.matrices.expressions.special import ZeroMatrix
+    assert latex(ZeroMatrix(1, 1), mat_symbol_style='plain') == r"0"
+    assert latex(ZeroMatrix(1, 1), mat_symbol_style='bold') == r"\mathbf{0}"
+
+
+def test_OneMatrix():
+    from sympy.matrices.expressions.special import OneMatrix
+    assert latex(OneMatrix(3, 4), mat_symbol_style='plain') == r"1"
+    assert latex(OneMatrix(3, 4), mat_symbol_style='bold') == r"\mathbf{1}"
+
+
+def test_Identity():
+    from sympy.matrices.expressions.special import Identity
+    assert latex(Identity(1), mat_symbol_style='plain') == r"\mathbb{I}"
+    assert latex(Identity(1), mat_symbol_style='bold') == r"\mathbf{I}"
+
+
+def test_latex_DFT_IDFT():
+    from sympy.matrices.expressions.fourier import DFT, IDFT
+    assert latex(DFT(13)) == r"\text{DFT}_{13}"
+    assert latex(IDFT(x)) == r"\text{IDFT}_{x}"
+
+
+def test_boolean_args_order():
+    syms = symbols('a:f')
+
+    expr = And(*syms)
+    assert latex(expr) == r'a \wedge b \wedge c \wedge d \wedge e \wedge f'
+
+    expr = Or(*syms)
+    assert latex(expr) == r'a \vee b \vee c \vee d \vee e \vee f'
+
+    expr = Equivalent(*syms)
+    assert latex(expr) == \
+        r'a \Leftrightarrow b \Leftrightarrow c \Leftrightarrow d \Leftrightarrow e \Leftrightarrow f'
+
+    expr = Xor(*syms)
+    assert latex(expr) == \
+        r'a \veebar b \veebar c \veebar d \veebar e \veebar f'
+
+
+def test_imaginary():
+    i = sqrt(-1)
+    assert latex(i) == r'i'
+
+
+def test_builtins_without_args():
+    assert latex(sin) == r'\sin'
+    assert latex(cos) == r'\cos'
+    assert latex(tan) == r'\tan'
+    assert latex(log) == r'\log'
+    assert latex(Ei) == r'\operatorname{Ei}'
+    assert latex(zeta) == r'\zeta'
+
+
+def test_latex_greek_functions():
+    # bug because capital greeks that have roman equivalents should not use
+    # \Alpha, \Beta, \Eta, etc.
+    s = Function('Alpha')
+    assert latex(s) == r'\mathrm{A}'
+    assert latex(s(x)) == r'\mathrm{A}{\left(x \right)}'
+    s = Function('Beta')
+    assert latex(s) == r'\mathrm{B}'
+    s = Function('Eta')
+    assert latex(s) == r'\mathrm{H}'
+    assert latex(s(x)) == r'\mathrm{H}{\left(x \right)}'
+
+    # bug because sympy.core.numbers.Pi is special
+    p = Function('Pi')
+    # assert latex(p(x)) == r'\Pi{\left(x \right)}'
+    assert latex(p) == r'\Pi'
+
+    # bug because not all greeks are included
+    c = Function('chi')
+    assert latex(c(x)) == r'\chi{\left(x \right)}'
+    assert latex(c) == r'\chi'
+
+
+def test_translate():
+    s = 'Alpha'
+    assert translate(s) == r'\mathrm{A}'
+    s = 'Beta'
+    assert translate(s) == r'\mathrm{B}'
+    s = 'Eta'
+    assert translate(s) == r'\mathrm{H}'
+    s = 'omicron'
+    assert translate(s) == r'o'
+    s = 'Pi'
+    assert translate(s) == r'\Pi'
+    s = 'pi'
+    assert translate(s) == r'\pi'
+    s = 'LamdaHatDOT'
+    assert translate(s) == r'\dot{\hat{\Lambda}}'
+
+
+def test_other_symbols():
+    from sympy.printing.latex import other_symbols
+    for s in other_symbols:
+        assert latex(symbols(s)) == r"" "\\" + s
+
+
+def test_modifiers():
+    # Test each modifier individually in the simplest case
+    # (with funny capitalizations)
+    assert latex(symbols("xMathring")) == r"\mathring{x}"
+    assert latex(symbols("xCheck")) == r"\check{x}"
+    assert latex(symbols("xBreve")) == r"\breve{x}"
+    assert latex(symbols("xAcute")) == r"\acute{x}"
+    assert latex(symbols("xGrave")) == r"\grave{x}"
+    assert latex(symbols("xTilde")) == r"\tilde{x}"
+    assert latex(symbols("xPrime")) == r"{x}'"
+    assert latex(symbols("xddDDot")) == r"\ddddot{x}"
+    assert latex(symbols("xDdDot")) == r"\dddot{x}"
+    assert latex(symbols("xDDot")) == r"\ddot{x}"
+    assert latex(symbols("xBold")) == r"\boldsymbol{x}"
+    assert latex(symbols("xnOrM")) == r"\left\|{x}\right\|"
+    assert latex(symbols("xAVG")) == r"\left\langle{x}\right\rangle"
+    assert latex(symbols("xHat")) == r"\hat{x}"
+    assert latex(symbols("xDot")) == r"\dot{x}"
+    assert latex(symbols("xBar")) == r"\bar{x}"
+    assert latex(symbols("xVec")) == r"\vec{x}"
+    assert latex(symbols("xAbs")) == r"\left|{x}\right|"
+    assert latex(symbols("xMag")) == r"\left|{x}\right|"
+    assert latex(symbols("xPrM")) == r"{x}'"
+    assert latex(symbols("xBM")) == r"\boldsymbol{x}"
+    # Test strings that are *only* the names of modifiers
+    assert latex(symbols("Mathring")) == r"Mathring"
+    assert latex(symbols("Check")) == r"Check"
+    assert latex(symbols("Breve")) == r"Breve"
+    assert latex(symbols("Acute")) == r"Acute"
+    assert latex(symbols("Grave")) == r"Grave"
+    assert latex(symbols("Tilde")) == r"Tilde"
+    assert latex(symbols("Prime")) == r"Prime"
+    assert latex(symbols("DDot")) == r"\dot{D}"
+    assert latex(symbols("Bold")) == r"Bold"
+    assert latex(symbols("NORm")) == r"NORm"
+    assert latex(symbols("AVG")) == r"AVG"
+    assert latex(symbols("Hat")) == r"Hat"
+    assert latex(symbols("Dot")) == r"Dot"
+    assert latex(symbols("Bar")) == r"Bar"
+    assert latex(symbols("Vec")) == r"Vec"
+    assert latex(symbols("Abs")) == r"Abs"
+    assert latex(symbols("Mag")) == r"Mag"
+    assert latex(symbols("PrM")) == r"PrM"
+    assert latex(symbols("BM")) == r"BM"
+    assert latex(symbols("hbar")) == r"\hbar"
+    # Check a few combinations
+    assert latex(symbols("xvecdot")) == r"\dot{\vec{x}}"
+    assert latex(symbols("xDotVec")) == r"\vec{\dot{x}}"
+    assert latex(symbols("xHATNorm")) == r"\left\|{\hat{x}}\right\|"
+    # Check a couple big, ugly combinations
+    assert latex(symbols('xMathringBm_yCheckPRM__zbreveAbs')) == \
+        r"\boldsymbol{\mathring{x}}^{\left|{\breve{z}}\right|}_{{\check{y}}'}"
+    assert latex(symbols('alphadothat_nVECDOT__tTildePrime')) == \
+        r"\hat{\dot{\alpha}}^{{\tilde{t}}'}_{\dot{\vec{n}}}"
+
+
+def test_greek_symbols():
+    assert latex(Symbol('alpha'))   == r'\alpha'
+    assert latex(Symbol('beta'))    == r'\beta'
+    assert latex(Symbol('gamma'))   == r'\gamma'
+    assert latex(Symbol('delta'))   == r'\delta'
+    assert latex(Symbol('epsilon')) == r'\epsilon'
+    assert latex(Symbol('zeta'))    == r'\zeta'
+    assert latex(Symbol('eta'))     == r'\eta'
+    assert latex(Symbol('theta'))   == r'\theta'
+    assert latex(Symbol('iota'))    == r'\iota'
+    assert latex(Symbol('kappa'))   == r'\kappa'
+    assert latex(Symbol('lambda'))  == r'\lambda'
+    assert latex(Symbol('mu'))      == r'\mu'
+    assert latex(Symbol('nu'))      == r'\nu'
+    assert latex(Symbol('xi'))      == r'\xi'
+    assert latex(Symbol('omicron')) == r'o'
+    assert latex(Symbol('pi'))      == r'\pi'
+    assert latex(Symbol('rho'))     == r'\rho'
+    assert latex(Symbol('sigma'))   == r'\sigma'
+    assert latex(Symbol('tau'))     == r'\tau'
+    assert latex(Symbol('upsilon')) == r'\upsilon'
+    assert latex(Symbol('phi'))     == r'\phi'
+    assert latex(Symbol('chi'))     == r'\chi'
+    assert latex(Symbol('psi'))     == r'\psi'
+    assert latex(Symbol('omega'))   == r'\omega'
+
+    assert latex(Symbol('Alpha'))   == r'\mathrm{A}'
+    assert latex(Symbol('Beta'))    == r'\mathrm{B}'
+    assert latex(Symbol('Gamma'))   == r'\Gamma'
+    assert latex(Symbol('Delta'))   == r'\Delta'
+    assert latex(Symbol('Epsilon')) == r'\mathrm{E}'
+    assert latex(Symbol('Zeta'))    == r'\mathrm{Z}'
+    assert latex(Symbol('Eta'))     == r'\mathrm{H}'
+    assert latex(Symbol('Theta'))   == r'\Theta'
+    assert latex(Symbol('Iota'))    == r'\mathrm{I}'
+    assert latex(Symbol('Kappa'))   == r'\mathrm{K}'
+    assert latex(Symbol('Lambda'))  == r'\Lambda'
+    assert latex(Symbol('Mu'))      == r'\mathrm{M}'
+    assert latex(Symbol('Nu'))      == r'\mathrm{N}'
+    assert latex(Symbol('Xi'))      == r'\Xi'
+    assert latex(Symbol('Omicron')) == r'\mathrm{O}'
+    assert latex(Symbol('Pi'))      == r'\Pi'
+    assert latex(Symbol('Rho'))     == r'\mathrm{P}'
+    assert latex(Symbol('Sigma'))   == r'\Sigma'
+    assert latex(Symbol('Tau'))     == r'\mathrm{T}'
+    assert latex(Symbol('Upsilon')) == r'\Upsilon'
+    assert latex(Symbol('Phi'))     == r'\Phi'
+    assert latex(Symbol('Chi'))     == r'\mathrm{X}'
+    assert latex(Symbol('Psi'))     == r'\Psi'
+    assert latex(Symbol('Omega'))   == r'\Omega'
+
+    assert latex(Symbol('varepsilon')) == r'\varepsilon'
+    assert latex(Symbol('varkappa')) == r'\varkappa'
+    assert latex(Symbol('varphi')) == r'\varphi'
+    assert latex(Symbol('varpi')) == r'\varpi'
+    assert latex(Symbol('varrho')) == r'\varrho'
+    assert latex(Symbol('varsigma')) == r'\varsigma'
+    assert latex(Symbol('vartheta')) == r'\vartheta'
+
+
+def test_fancyset_symbols():
+    assert latex(S.Rationals) == r'\mathbb{Q}'
+    assert latex(S.Naturals) == r'\mathbb{N}'
+    assert latex(S.Naturals0) == r'\mathbb{N}_0'
+    assert latex(S.Integers) == r'\mathbb{Z}'
+    assert latex(S.Reals) == r'\mathbb{R}'
+    assert latex(S.Complexes) == r'\mathbb{C}'
+
+
+@XFAIL
+def test_builtin_without_args_mismatched_names():
+    assert latex(CosineTransform) == r'\mathcal{COS}'
+
+
+def test_builtin_no_args():
+    assert latex(Chi) == r'\operatorname{Chi}'
+    assert latex(beta) == r'\operatorname{B}'
+    assert latex(gamma) == r'\Gamma'
+    assert latex(KroneckerDelta) == r'\delta'
+    assert latex(DiracDelta) == r'\delta'
+    assert latex(lowergamma) == r'\gamma'
+
+
+def test_issue_6853():
+    p = Function('Pi')
+    assert latex(p(x)) == r"\Pi{\left(x \right)}"
+
+
+def test_Mul():
+    e = Mul(-2, x + 1, evaluate=False)
+    assert latex(e) == r'- 2 \left(x + 1\right)'
+    e = Mul(2, x + 1, evaluate=False)
+    assert latex(e) == r'2 \left(x + 1\right)'
+    e = Mul(S.Half, x + 1, evaluate=False)
+    assert latex(e) == r'\frac{x + 1}{2}'
+    e = Mul(y, x + 1, evaluate=False)
+    assert latex(e) == r'y \left(x + 1\right)'
+    e = Mul(-y, x + 1, evaluate=False)
+    assert latex(e) == r'- y \left(x + 1\right)'
+    e = Mul(-2, x + 1)
+    assert latex(e) == r'- 2 x - 2'
+    e = Mul(2, x + 1)
+    assert latex(e) == r'2 x + 2'
+
+
+def test_Pow():
+    e = Pow(2, 2, evaluate=False)
+    assert latex(e) == r'2^{2}'
+    assert latex(x**(Rational(-1, 3))) == r'\frac{1}{\sqrt[3]{x}}'
+    x2 = Symbol(r'x^2')
+    assert latex(x2**2) == r'\left(x^{2}\right)^{2}'
+    # Issue 11011
+    assert latex(S('1.453e4500')**x) == r'{1.453 \cdot 10^{4500}}^{x}'
+
+
+def test_issue_7180():
+    assert latex(Equivalent(x, y)) == r"x \Leftrightarrow y"
+    assert latex(Not(Equivalent(x, y))) == r"x \not\Leftrightarrow y"
+
+
+def test_issue_8409():
+    assert latex(S.Half**n) == r"\left(\frac{1}{2}\right)^{n}"
+
+
+def test_issue_8470():
+    from sympy.parsing.sympy_parser import parse_expr
+    e = parse_expr("-B*A", evaluate=False)
+    assert latex(e) == r"A \left(- B\right)"
+
+
+def test_issue_15439():
+    x = MatrixSymbol('x', 2, 2)
+    y = MatrixSymbol('y', 2, 2)
+    assert latex((x * y).subs(y, -y)) == r"x \left(- y\right)"
+    assert latex((x * y).subs(y, -2*y)) == r"x \left(- 2 y\right)"
+    assert latex((x * y).subs(x, -x)) == r"\left(- x\right) y"
+
+
+def test_issue_2934():
+    assert latex(Symbol(r'\frac{a_1}{b_1}')) == r'\frac{a_1}{b_1}'
+
+
+def test_issue_10489():
+    latexSymbolWithBrace = r'C_{x_{0}}'
+    s = Symbol(latexSymbolWithBrace)
+    assert latex(s) == latexSymbolWithBrace
+    assert latex(cos(s)) == r'\cos{\left(C_{x_{0}} \right)}'
+
+
+def test_issue_12886():
+    m__1, l__1 = symbols('m__1, l__1')
+    assert latex(m__1**2 + l__1**2) == \
+        r'\left(l^{1}\right)^{2} + \left(m^{1}\right)^{2}'
+
+
+def test_issue_13559():
+    from sympy.parsing.sympy_parser import parse_expr
+    expr = parse_expr('5/1', evaluate=False)
+    assert latex(expr) == r"\frac{5}{1}"
+
+
+def test_issue_13651():
+    expr = c + Mul(-1, a + b, evaluate=False)
+    assert latex(expr) == r"c - \left(a + b\right)"
+
+
+def test_latex_UnevaluatedExpr():
+    x = symbols("x")
+    he = UnevaluatedExpr(1/x)
+    assert latex(he) == latex(1/x) == r"\frac{1}{x}"
+    assert latex(he**2) == r"\left(\frac{1}{x}\right)^{2}"
+    assert latex(he + 1) == r"1 + \frac{1}{x}"
+    assert latex(x*he) == r"x \frac{1}{x}"
+
+
+def test_MatrixElement_printing():
+    # test cases for issue #11821
+    A = MatrixSymbol("A", 1, 3)
+    B = MatrixSymbol("B", 1, 3)
+    C = MatrixSymbol("C", 1, 3)
+
+    assert latex(A[0, 0]) == r"{A}_{0,0}"
+    assert latex(3 * A[0, 0]) == r"3 {A}_{0,0}"
+
+    F = C[0, 0].subs(C, A - B)
+    assert latex(F) == r"{\left(A - B\right)}_{0,0}"
+
+    i, j, k = symbols("i j k")
+    M = MatrixSymbol("M", k, k)
+    N = MatrixSymbol("N", k, k)
+    assert latex((M*N)[i, j]) == \
+        r'\sum_{i_{1}=0}^{k - 1} {M}_{i,i_{1}} {N}_{i_{1},j}'
+
+    X_a = MatrixSymbol('X_a', 3, 3)
+    assert latex(X_a[0, 0]) == r"{X_{a}}_{0,0}"
+
+
+def test_MatrixSymbol_printing():
+    # test cases for issue #14237
+    A = MatrixSymbol("A", 3, 3)
+    B = MatrixSymbol("B", 3, 3)
+    C = MatrixSymbol("C", 3, 3)
+
+    assert latex(-A) == r"- A"
+    assert latex(A - A*B - B) == r"A - A B - B"
+    assert latex(-A*B - A*B*C - B) == r"- A B - A B C - B"
+
+
+def test_DotProduct_printing():
+    X = MatrixSymbol('X', 3, 1)
+    Y = MatrixSymbol('Y', 3, 1)
+    a = Symbol('a')
+    assert latex(DotProduct(X, Y)) == r"X \cdot Y"
+    assert latex(DotProduct(a * X, Y)) == r"a X \cdot Y"
+    assert latex(a * DotProduct(X, Y)) == r"a \left(X \cdot Y\right)"
+
+
+def test_KroneckerProduct_printing():
+    A = MatrixSymbol('A', 3, 3)
+    B = MatrixSymbol('B', 2, 2)
+    assert latex(KroneckerProduct(A, B)) == r'A \otimes B'
+
+
+def test_Series_printing():
+    tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y)
+    tf2 = TransferFunction(x - y, x + y, y)
+    tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y)
+    assert latex(Series(tf1, tf2)) == \
+        r'\left(\frac{x y^{2} - z}{- t^{3} + y^{3}}\right) \left(\frac{x - y}{x + y}\right)'
+    assert latex(Series(tf1, tf2, tf3)) == \
+        r'\left(\frac{x y^{2} - z}{- t^{3} + y^{3}}\right) \left(\frac{x - y}{x + y}\right) \left(\frac{t x^{2} - t^{w} x + w}{t - y}\right)'
+    assert latex(Series(-tf2, tf1)) == \
+        r'\left(\frac{- x + y}{x + y}\right) \left(\frac{x y^{2} - z}{- t^{3} + y^{3}}\right)'
+
+    M_1 = Matrix([[5/s], [5/(2*s)]])
+    T_1 = TransferFunctionMatrix.from_Matrix(M_1, s)
+    M_2 = Matrix([[5, 6*s**3]])
+    T_2 = TransferFunctionMatrix.from_Matrix(M_2, s)
+    # Brackets
+    assert latex(T_1*(T_2 + T_2)) == \
+        r'\left[\begin{matrix}\frac{5}{s}\\\frac{5}{2 s}\end{matrix}\right]_\tau\cdot\left(\left[\begin{matrix}\frac{5}{1} &' \
+        r' \frac{6 s^{3}}{1}\end{matrix}\right]_\tau + \left[\begin{matrix}\frac{5}{1} & \frac{6 s^{3}}{1}\end{matrix}\right]_\tau\right)' \
+            == latex(MIMOSeries(MIMOParallel(T_2, T_2), T_1))
+    # No Brackets
+    M_3 = Matrix([[5, 6], [6, 5/s]])
+    T_3 = TransferFunctionMatrix.from_Matrix(M_3, s)
+    assert latex(T_1*T_2 + T_3) == r'\left[\begin{matrix}\frac{5}{s}\\\frac{5}{2 s}\end{matrix}\right]_\tau\cdot\left[\begin{matrix}' \
+        r'\frac{5}{1} & \frac{6 s^{3}}{1}\end{matrix}\right]_\tau + \left[\begin{matrix}\frac{5}{1} & \frac{6}{1}\\\frac{6}{1} & ' \
+            r'\frac{5}{s}\end{matrix}\right]_\tau' == latex(MIMOParallel(MIMOSeries(T_2, T_1), T_3))
+
+
+def test_TransferFunction_printing():
+    tf1 = TransferFunction(x - 1, x + 1, x)
+    assert latex(tf1) == r"\frac{x - 1}{x + 1}"
+    tf2 = TransferFunction(x + 1, 2 - y, x)
+    assert latex(tf2) == r"\frac{x + 1}{2 - y}"
+    tf3 = TransferFunction(y, y**2 + 2*y + 3, y)
+    assert latex(tf3) == r"\frac{y}{y^{2} + 2 y + 3}"
+
+
+def test_Parallel_printing():
+    tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y)
+    tf2 = TransferFunction(x - y, x + y, y)
+    assert latex(Parallel(tf1, tf2)) == \
+        r'\frac{x y^{2} - z}{- t^{3} + y^{3}} + \frac{x - y}{x + y}'
+    assert latex(Parallel(-tf2, tf1)) == \
+        r'\frac{- x + y}{x + y} + \frac{x y^{2} - z}{- t^{3} + y^{3}}'
+
+    M_1 = Matrix([[5, 6], [6, 5/s]])
+    T_1 = TransferFunctionMatrix.from_Matrix(M_1, s)
+    M_2 = Matrix([[5/s, 6], [6, 5/(s - 1)]])
+    T_2 = TransferFunctionMatrix.from_Matrix(M_2, s)
+    M_3 = Matrix([[6, 5/(s*(s - 1))], [5, 6]])
+    T_3 = TransferFunctionMatrix.from_Matrix(M_3, s)
+    assert latex(T_1 + T_2 + T_3) == r'\left[\begin{matrix}\frac{5}{1} & \frac{6}{1}\\\frac{6}{1} & \frac{5}{s}\end{matrix}\right]' \
+        r'_\tau + \left[\begin{matrix}\frac{5}{s} & \frac{6}{1}\\\frac{6}{1} & \frac{5}{s - 1}\end{matrix}\right]_\tau + \left[\begin{matrix}' \
+            r'\frac{6}{1} & \frac{5}{s \left(s - 1\right)}\\\frac{5}{1} & \frac{6}{1}\end{matrix}\right]_\tau' \
+                == latex(MIMOParallel(T_1, T_2, T_3)) == latex(MIMOParallel(T_1, MIMOParallel(T_2, T_3))) == latex(MIMOParallel(MIMOParallel(T_1, T_2), T_3))
+
+
+def test_TransferFunctionMatrix_printing():
+    tf1 = TransferFunction(p, p + x, p)
+    tf2 = TransferFunction(-s + p, p + s, p)
+    tf3 = TransferFunction(p, y**2 + 2*y + 3, p)
+    assert latex(TransferFunctionMatrix([[tf1], [tf2]])) == \
+        r'\left[\begin{matrix}\frac{p}{p + x}\\\frac{p - s}{p + s}\end{matrix}\right]_\tau'
+    assert latex(TransferFunctionMatrix([[tf1, tf2], [tf3, -tf1]])) == \
+        r'\left[\begin{matrix}\frac{p}{p + x} & \frac{p - s}{p + s}\\\frac{p}{y^{2} + 2 y + 3} & \frac{\left(-1\right) p}{p + x}\end{matrix}\right]_\tau'
+
+
+def test_Feedback_printing():
+    tf1 = TransferFunction(p, p + x, p)
+    tf2 = TransferFunction(-s + p, p + s, p)
+    # Negative Feedback (Default)
+    assert latex(Feedback(tf1, tf2)) == \
+        r'\frac{\frac{p}{p + x}}{\frac{1}{1} + \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}'
+    assert latex(Feedback(tf1*tf2, TransferFunction(1, 1, p))) == \
+        r'\frac{\left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}{\frac{1}{1} + \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}'
+    # Positive Feedback
+    assert latex(Feedback(tf1, tf2, 1)) == \
+        r'\frac{\frac{p}{p + x}}{\frac{1}{1} - \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}'
+    assert latex(Feedback(tf1*tf2, sign=1)) == \
+        r'\frac{\left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}{\frac{1}{1} - \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}'
+
+
+def test_MIMOFeedback_printing():
+    tf1 = TransferFunction(1, s, s)
+    tf2 = TransferFunction(s, s**2 - 1, s)
+    tf3 = TransferFunction(s, s - 1, s)
+    tf4 = TransferFunction(s**2, s**2 - 1, s)
+
+    tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]])
+    tfm_2 = TransferFunctionMatrix([[tf4, tf3], [tf2, tf1]])
+
+    # Negative Feedback (Default)
+    assert latex(MIMOFeedback(tfm_1, tfm_2)) == \
+        r'\left(I_{\tau} + \left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\cdot\left[' \
+        r'\begin{matrix}\frac{s^{2}}{s^{2} - 1} & \frac{s}{s - 1}\\\frac{s}{s^{2} - 1} & \frac{1}{s}\end{matrix}\right]_\tau\right)^{-1} \cdot \left[\begin{matrix}' \
+        r'\frac{1}{s} & \frac{s}{s^{2} - 1}\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau'
+
+    # Positive Feedback
+    assert latex(MIMOFeedback(tfm_1*tfm_2, tfm_1, 1)) == \
+        r'\left(I_{\tau} - \left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\cdot\left' \
+        r'[\begin{matrix}\frac{s^{2}}{s^{2} - 1} & \frac{s}{s - 1}\\\frac{s}{s^{2} - 1} & \frac{1}{s}\end{matrix}\right]_\tau\cdot\left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}' \
+        r'\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\right)^{-1} \cdot \left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}' \
+        r'\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\cdot\left[\begin{matrix}\frac{s^{2}}{s^{2} - 1} & \frac{s}{s - 1}\\\frac{s}{s^{2} - 1}' \
+        r' & \frac{1}{s}\end{matrix}\right]_\tau'
+
+
+def test_Quaternion_latex_printing():
+    q = Quaternion(x, y, z, t)
+    assert latex(q) == r"x + y i + z j + t k"
+    q = Quaternion(x, y, z, x*t)
+    assert latex(q) == r"x + y i + z j + t x k"
+    q = Quaternion(x, y, z, x + t)
+    assert latex(q) == r"x + y i + z j + \left(t + x\right) k"
+
+
+def test_TensorProduct_printing():
+    from sympy.tensor.functions import TensorProduct
+    A = MatrixSymbol("A", 3, 3)
+    B = MatrixSymbol("B", 3, 3)
+    assert latex(TensorProduct(A, B)) == r"A \otimes B"
+
+
+def test_WedgeProduct_printing():
+    from sympy.diffgeom.rn import R2
+    from sympy.diffgeom import WedgeProduct
+    wp = WedgeProduct(R2.dx, R2.dy)
+    assert latex(wp) == r"\operatorname{d}x \wedge \operatorname{d}y"
+
+
+def test_issue_9216():
+    expr_1 = Pow(1, -1, evaluate=False)
+    assert latex(expr_1) == r"1^{-1}"
+
+    expr_2 = Pow(1, Pow(1, -1, evaluate=False), evaluate=False)
+    assert latex(expr_2) == r"1^{1^{-1}}"
+
+    expr_3 = Pow(3, -2, evaluate=False)
+    assert latex(expr_3) == r"\frac{1}{9}"
+
+    expr_4 = Pow(1, -2, evaluate=False)
+    assert latex(expr_4) == r"1^{-2}"
+
+
+def test_latex_printer_tensor():
+    from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, tensor_heads
+    L = TensorIndexType("L")
+    i, j, k, l = tensor_indices("i j k l", L)
+    i0 = tensor_indices("i_0", L)
+    A, B, C, D = tensor_heads("A B C D", [L])
+    H = TensorHead("H", [L, L])
+    K = TensorHead("K", [L, L, L, L])
+
+    assert latex(i) == r"{}^{i}"
+    assert latex(-i) == r"{}_{i}"
+
+    expr = A(i)
+    assert latex(expr) == r"A{}^{i}"
+
+    expr = A(i0)
+    assert latex(expr) == r"A{}^{i_{0}}"
+
+    expr = A(-i)
+    assert latex(expr) == r"A{}_{i}"
+
+    expr = -3*A(i)
+    assert latex(expr) == r"-3A{}^{i}"
+
+    expr = K(i, j, -k, -i0)
+    assert latex(expr) == r"K{}^{ij}{}_{ki_{0}}"
+
+    expr = K(i, -j, -k, i0)
+    assert latex(expr) == r"K{}^{i}{}_{jk}{}^{i_{0}}"
+
+    expr = K(i, -j, k, -i0)
+    assert latex(expr) == r"K{}^{i}{}_{j}{}^{k}{}_{i_{0}}"
+
+    expr = H(i, -j)
+    assert latex(expr) == r"H{}^{i}{}_{j}"
+
+    expr = H(i, j)
+    assert latex(expr) == r"H{}^{ij}"
+
+    expr = H(-i, -j)
+    assert latex(expr) == r"H{}_{ij}"
+
+    expr = (1+x)*A(i)
+    assert latex(expr) == r"\left(x + 1\right)A{}^{i}"
+
+    expr = H(i, -i)
+    assert latex(expr) == r"H{}^{L_{0}}{}_{L_{0}}"
+
+    expr = H(i, -j)*A(j)*B(k)
+    assert latex(expr) == r"H{}^{i}{}_{L_{0}}A{}^{L_{0}}B{}^{k}"
+
+    expr = A(i) + 3*B(i)
+    assert latex(expr) == r"3B{}^{i} + A{}^{i}"
+
+    # Test ``TensorElement``:
+    from sympy.tensor.tensor import TensorElement
+
+    expr = TensorElement(K(i, j, k, l), {i: 3, k: 2})
+    assert latex(expr) == r'K{}^{i=3,j,k=2,l}'
+
+    expr = TensorElement(K(i, j, k, l), {i: 3})
+    assert latex(expr) == r'K{}^{i=3,jkl}'
+
+    expr = TensorElement(K(i, -j, k, l), {i: 3, k: 2})
+    assert latex(expr) == r'K{}^{i=3}{}_{j}{}^{k=2,l}'
+
+    expr = TensorElement(K(i, -j, k, -l), {i: 3, k: 2})
+    assert latex(expr) == r'K{}^{i=3}{}_{j}{}^{k=2}{}_{l}'
+
+    expr = TensorElement(K(i, j, -k, -l), {i: 3, -k: 2})
+    assert latex(expr) == r'K{}^{i=3,j}{}_{k=2,l}'
+
+    expr = TensorElement(K(i, j, -k, -l), {i: 3})
+    assert latex(expr) == r'K{}^{i=3,j}{}_{kl}'
+
+    expr = PartialDerivative(A(i), A(i))
+    assert latex(expr) == r"\frac{\partial}{\partial {A{}^{L_{0}}}}{A{}^{L_{0}}}"
+
+    expr = PartialDerivative(A(-i), A(-j))
+    assert latex(expr) == r"\frac{\partial}{\partial {A{}_{j}}}{A{}_{i}}"
+
+    expr = PartialDerivative(K(i, j, -k, -l), A(m), A(-n))
+    assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}^{m}} \partial {A{}_{n}}}{K{}^{ij}{}_{kl}}"
+
+    expr = PartialDerivative(B(-i) + A(-i), A(-j), A(-n))
+    assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}_{j}} \partial {A{}_{n}}}{\left(A{}_{i} + B{}_{i}\right)}"
+
+    expr = PartialDerivative(3*A(-i), A(-j), A(-n))
+    assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}_{j}} \partial {A{}_{n}}}{\left(3A{}_{i}\right)}"
+
+
+def test_multiline_latex():
+    a, b, c, d, e, f = symbols('a b c d e f')
+    expr = -a + 2*b -3*c +4*d -5*e
+    expected = r"\begin{eqnarray}" + "\n"\
+        r"f & = &- a \nonumber\\" + "\n"\
+        r"& & + 2 b \nonumber\\" + "\n"\
+        r"& & - 3 c \nonumber\\" + "\n"\
+        r"& & + 4 d \nonumber\\" + "\n"\
+        r"& & - 5 e " + "\n"\
+        r"\end{eqnarray}"
+    assert multiline_latex(f, expr, environment="eqnarray") == expected
+
+    expected2 = r'\begin{eqnarray}' + '\n'\
+        r'f & = &- a + 2 b \nonumber\\' + '\n'\
+        r'& & - 3 c + 4 d \nonumber\\' + '\n'\
+        r'& & - 5 e ' + '\n'\
+        r'\end{eqnarray}'
+
+    assert multiline_latex(f, expr, 2, environment="eqnarray") == expected2
+
+    expected3 = r'\begin{eqnarray}' + '\n'\
+        r'f & = &- a + 2 b - 3 c \nonumber\\'+ '\n'\
+        r'& & + 4 d - 5 e ' + '\n'\
+        r'\end{eqnarray}'
+
+    assert multiline_latex(f, expr, 3, environment="eqnarray") == expected3
+
+    expected3dots = r'\begin{eqnarray}' + '\n'\
+        r'f & = &- a + 2 b - 3 c \dots\nonumber\\'+ '\n'\
+        r'& & + 4 d - 5 e ' + '\n'\
+        r'\end{eqnarray}'
+
+    assert multiline_latex(f, expr, 3, environment="eqnarray", use_dots=True) == expected3dots
+
+    expected3align = r'\begin{align*}' + '\n'\
+        r'f = &- a + 2 b - 3 c \\'+ '\n'\
+        r'& + 4 d - 5 e ' + '\n'\
+        r'\end{align*}'
+
+    assert multiline_latex(f, expr, 3) == expected3align
+    assert multiline_latex(f, expr, 3, environment='align*') == expected3align
+
+    expected2ieee = r'\begin{IEEEeqnarray}{rCl}' + '\n'\
+        r'f & = &- a + 2 b \nonumber\\' + '\n'\
+        r'& & - 3 c + 4 d \nonumber\\' + '\n'\
+        r'& & - 5 e ' + '\n'\
+        r'\end{IEEEeqnarray}'
+
+    assert multiline_latex(f, expr, 2, environment="IEEEeqnarray") == expected2ieee
+
+    raises(ValueError, lambda: multiline_latex(f, expr, environment="foo"))
+
+def test_issue_15353():
+    a, x = symbols('a x')
+    # Obtained from nonlinsolve([(sin(a*x)),cos(a*x)],[x,a])
+    sol = ConditionSet(
+        Tuple(x, a), Eq(sin(a*x), 0) & Eq(cos(a*x), 0), S.Complexes**2)
+    assert latex(sol) == \
+        r'\left\{\left( x, \  a\right)\; \middle|\; \left( x, \  a\right) \in ' \
+        r'\mathbb{C}^{2} \wedge \sin{\left(a x \right)} = 0 \wedge ' \
+        r'\cos{\left(a x \right)} = 0 \right\}'
+
+
+def test_latex_symbolic_probability():
+    mu = symbols("mu")
+    sigma = symbols("sigma", positive=True)
+    X = Normal("X", mu, sigma)
+    assert latex(Expectation(X)) == r'\operatorname{E}\left[X\right]'
+    assert latex(Variance(X)) == r'\operatorname{Var}\left(X\right)'
+    assert latex(Probability(X > 0)) == r'\operatorname{P}\left(X > 0\right)'
+    Y = Normal("Y", mu, sigma)
+    assert latex(Covariance(X, Y)) == r'\operatorname{Cov}\left(X, Y\right)'
+
+
+def test_trace():
+    # Issue 15303
+    from sympy.matrices.expressions.trace import trace
+    A = MatrixSymbol("A", 2, 2)
+    assert latex(trace(A)) == r"\operatorname{tr}\left(A \right)"
+    assert latex(trace(A**2)) == r"\operatorname{tr}\left(A^{2} \right)"
+
+
+def test_print_basic():
+    # Issue 15303
+    from sympy.core.basic import Basic
+    from sympy.core.expr import Expr
+
+    # dummy class for testing printing where the function is not
+    # implemented in latex.py
+    class UnimplementedExpr(Expr):
+        def __new__(cls, e):
+            return Basic.__new__(cls, e)
+
+    # dummy function for testing
+    def unimplemented_expr(expr):
+        return UnimplementedExpr(expr).doit()
+
+    # override class name to use superscript / subscript
+    def unimplemented_expr_sup_sub(expr):
+        result = UnimplementedExpr(expr)
+        result.__class__.__name__ = 'UnimplementedExpr_x^1'
+        return result
+
+    assert latex(unimplemented_expr(x)) == r'\operatorname{UnimplementedExpr}\left(x\right)'
+    assert latex(unimplemented_expr(x**2)) == \
+        r'\operatorname{UnimplementedExpr}\left(x^{2}\right)'
+    assert latex(unimplemented_expr_sup_sub(x)) == \
+        r'\operatorname{UnimplementedExpr^{1}_{x}}\left(x\right)'
+
+
+def test_MatrixSymbol_bold():
+    # Issue #15871
+    from sympy.matrices.expressions.trace import trace
+    A = MatrixSymbol("A", 2, 2)
+    assert latex(trace(A), mat_symbol_style='bold') == \
+        r"\operatorname{tr}\left(\mathbf{A} \right)"
+    assert latex(trace(A), mat_symbol_style='plain') == \
+        r"\operatorname{tr}\left(A \right)"
+
+    A = MatrixSymbol("A", 3, 3)
+    B = MatrixSymbol("B", 3, 3)
+    C = MatrixSymbol("C", 3, 3)
+
+    assert latex(-A, mat_symbol_style='bold') == r"- \mathbf{A}"
+    assert latex(A - A*B - B, mat_symbol_style='bold') == \
+        r"\mathbf{A} - \mathbf{A} \mathbf{B} - \mathbf{B}"
+    assert latex(-A*B - A*B*C - B, mat_symbol_style='bold') == \
+        r"- \mathbf{A} \mathbf{B} - \mathbf{A} \mathbf{B} \mathbf{C} - \mathbf{B}"
+
+    A_k = MatrixSymbol("A_k", 3, 3)
+    assert latex(A_k, mat_symbol_style='bold') == r"\mathbf{A}_{k}"
+
+    A = MatrixSymbol(r"\nabla_k", 3, 3)
+    assert latex(A, mat_symbol_style='bold') == r"\mathbf{\nabla}_{k}"
+
+def test_AppliedPermutation():
+    p = Permutation(0, 1, 2)
+    x = Symbol('x')
+    assert latex(AppliedPermutation(p, x)) == \
+        r'\sigma_{\left( 0\; 1\; 2\right)}(x)'
+
+
+def test_PermutationMatrix():
+    p = Permutation(0, 1, 2)
+    assert latex(PermutationMatrix(p)) == r'P_{\left( 0\; 1\; 2\right)}'
+    p = Permutation(0, 3)(1, 2)
+    assert latex(PermutationMatrix(p)) == \
+        r'P_{\left( 0\; 3\right)\left( 1\; 2\right)}'
+
+
+def test_issue_21758():
+    from sympy.functions.elementary.piecewise import piecewise_fold
+    from sympy.series.fourier import FourierSeries
+    x = Symbol('x')
+    k, n = symbols('k n')
+    fo = FourierSeries(x, (x, -pi, pi), (0, SeqFormula(0, (k, 1, oo)), SeqFormula(
+        Piecewise((-2*pi*cos(n*pi)/n + 2*sin(n*pi)/n**2, (n > -oo) & (n < oo) & Ne(n, 0)),
+                  (0, True))*sin(n*x)/pi, (n, 1, oo))))
+    assert latex(piecewise_fold(fo)) == '\\begin{cases} 2 \\sin{\\left(x \\right)}' \
+            ' - \\sin{\\left(2 x \\right)} + \\frac{2 \\sin{\\left(3 x \\right)}}{3} +' \
+            ' \\ldots & \\text{for}\\: n > -\\infty \\wedge n < \\infty \\wedge ' \
+                'n \\neq 0 \\\\0 & \\text{otherwise} \\end{cases}'
+    assert latex(FourierSeries(x, (x, -pi, pi), (0, SeqFormula(0, (k, 1, oo)),
+                                                 SeqFormula(0, (n, 1, oo))))) == '0'
+
+
+def test_imaginary_unit():
+    assert latex(1 + I) == r'1 + i'
+    assert latex(1 + I, imaginary_unit='i') == r'1 + i'
+    assert latex(1 + I, imaginary_unit='j') == r'1 + j'
+    assert latex(1 + I, imaginary_unit='foo') == r'1 + foo'
+    assert latex(I, imaginary_unit="ti") == r'\text{i}'
+    assert latex(I, imaginary_unit="tj") == r'\text{j}'
+
+
+def test_text_re_im():
+    assert latex(im(x), gothic_re_im=True) == r'\Im{\left(x\right)}'
+    assert latex(im(x), gothic_re_im=False) == r'\operatorname{im}{\left(x\right)}'
+    assert latex(re(x), gothic_re_im=True) == r'\Re{\left(x\right)}'
+    assert latex(re(x), gothic_re_im=False) == r'\operatorname{re}{\left(x\right)}'
+
+
+def test_latex_diffgeom():
+    from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential
+    from sympy.diffgeom.rn import R2
+    x,y = symbols('x y', real=True)
+    m = Manifold('M', 2)
+    assert latex(m) == r'\text{M}'
+    p = Patch('P', m)
+    assert latex(p) == r'\text{P}_{\text{M}}'
+    rect = CoordSystem('rect', p, [x, y])
+    assert latex(rect) == r'\text{rect}^{\text{P}}_{\text{M}}'
+    b = BaseScalarField(rect, 0)
+    assert latex(b) == r'\mathbf{x}'
+
+    g = Function('g')
+    s_field = g(R2.x, R2.y)
+    assert latex(Differential(s_field)) == \
+        r'\operatorname{d}\left(g{\left(\mathbf{x},\mathbf{y} \right)}\right)'
+
+
+def test_unit_printing():
+    assert latex(5*meter) == r'5 \text{m}'
+    assert latex(3*gibibyte) == r'3 \text{gibibyte}'
+    assert latex(4*microgram/second) == r'\frac{4 \mu\text{g}}{\text{s}}'
+    assert latex(4*micro*gram/second) == r'\frac{4 \mu \text{g}}{\text{s}}'
+    assert latex(5*milli*meter) == r'5 \text{m} \text{m}'
+    assert latex(milli) == r'\text{m}'
+
+
+def test_issue_17092():
+    x_star = Symbol('x^*')
+    assert latex(Derivative(x_star, x_star,2)) == r'\frac{d^{2}}{d \left(x^{*}\right)^{2}} x^{*}'
+
+
+def test_latex_decimal_separator():
+
+    x, y, z, t = symbols('x y z t')
+    k, m, n = symbols('k m n', integer=True)
+    f, g, h = symbols('f g h', cls=Function)
+
+    # comma decimal_separator
+    assert(latex([1, 2.3, 4.5], decimal_separator='comma') == r'\left[ 1; \  2{,}3; \  4{,}5\right]')
+    assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='comma') == r'\left\{1; 2{,}3; 4{,}5\right\}')
+    assert(latex((1, 2.3, 4.6), decimal_separator = 'comma') == r'\left( 1; \  2{,}3; \  4{,}6\right)')
+    assert(latex((1,), decimal_separator='comma') == r'\left( 1;\right)')
+
+    # period decimal_separator
+    assert(latex([1, 2.3, 4.5], decimal_separator='period') == r'\left[ 1, \  2.3, \  4.5\right]' )
+    assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='period') == r'\left\{1, 2.3, 4.5\right\}')
+    assert(latex((1, 2.3, 4.6), decimal_separator = 'period') == r'\left( 1, \  2.3, \  4.6\right)')
+    assert(latex((1,), decimal_separator='period') == r'\left( 1,\right)')
+
+    # default decimal_separator
+    assert(latex([1, 2.3, 4.5]) == r'\left[ 1, \  2.3, \  4.5\right]')
+    assert(latex(FiniteSet(1, 2.3, 4.5)) == r'\left\{1, 2.3, 4.5\right\}')
+    assert(latex((1, 2.3, 4.6)) == r'\left( 1, \  2.3, \  4.6\right)')
+    assert(latex((1,)) == r'\left( 1,\right)')
+
+    assert(latex(Mul(3.4,5.3), decimal_separator = 'comma') == r'18{,}02')
+    assert(latex(3.4*5.3, decimal_separator = 'comma') == r'18{,}02')
+    x = symbols('x')
+    y = symbols('y')
+    z = symbols('z')
+    assert(latex(x*5.3 + 2**y**3.4 + 4.5 + z, decimal_separator = 'comma') == r'2^{y^{3{,}4}} + 5{,}3 x + z + 4{,}5')
+
+    assert(latex(0.987, decimal_separator='comma') == r'0{,}987')
+    assert(latex(S(0.987), decimal_separator='comma') == r'0{,}987')
+    assert(latex(.3, decimal_separator='comma') == r'0{,}3')
+    assert(latex(S(.3), decimal_separator='comma') == r'0{,}3')
+
+
+    assert(latex(5.8*10**(-7), decimal_separator='comma') == r'5{,}8 \cdot 10^{-7}')
+    assert(latex(S(5.7)*10**(-7), decimal_separator='comma') == r'5{,}7 \cdot 10^{-7}')
+    assert(latex(S(5.7*10**(-7)), decimal_separator='comma') == r'5{,}7 \cdot 10^{-7}')
+
+    x = symbols('x')
+    assert(latex(1.2*x+3.4, decimal_separator='comma') == r'1{,}2 x + 3{,}4')
+    assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='period') == r'\left\{1, 2.3, 4.5\right\}')
+
+    # Error Handling tests
+    raises(ValueError, lambda: latex([1,2.3,4.5], decimal_separator='non_existing_decimal_separator_in_list'))
+    raises(ValueError, lambda: latex(FiniteSet(1,2.3,4.5), decimal_separator='non_existing_decimal_separator_in_set'))
+    raises(ValueError, lambda: latex((1,2.3,4.5), decimal_separator='non_existing_decimal_separator_in_tuple'))
+
+def test_Str():
+    from sympy.core.symbol import Str
+    assert str(Str('x')) == r'x'
+
+def test_latex_escape():
+    assert latex_escape(r"~^\&%$#_{}") == "".join([
+        r'\textasciitilde',
+        r'\textasciicircum',
+        r'\textbackslash',
+        r'\&',
+        r'\%',
+        r'\$',
+        r'\#',
+        r'\_',
+        r'\{',
+        r'\}',
+    ])
+
+def test_emptyPrinter():
+    class MyObject:
+        def __repr__(self):
+            return ""
+
+    # unknown objects are monospaced
+    assert latex(MyObject()) == r"\mathtt{\text{}}"
+
+    # even if they are nested within other objects
+    assert latex((MyObject(),)) == r"\left( \mathtt{\text{}},\right)"
+
+def test_global_settings():
+    import inspect
+
+    # settings should be visible in the signature of `latex`
+    assert inspect.signature(latex).parameters['imaginary_unit'].default == r'i'
+    assert latex(I) == r'i'
+    try:
+        # but changing the defaults...
+        LatexPrinter.set_global_settings(imaginary_unit='j')
+        # ... should change the signature
+        assert inspect.signature(latex).parameters['imaginary_unit'].default == r'j'
+        assert latex(I) == r'j'
+    finally:
+        # there's no public API to undo this, but we need to make sure we do
+        # so as not to impact other tests
+        del LatexPrinter._global_settings['imaginary_unit']
+
+    # check we really did undo it
+    assert inspect.signature(latex).parameters['imaginary_unit'].default == r'i'
+    assert latex(I) == r'i'
+
+def test_pickleable():
+    # this tests that the _PrintFunction instance is pickleable
+    import pickle
+    assert pickle.loads(pickle.dumps(latex)) is latex
+
+def test_printing_latex_array_expressions():
+    assert latex(ArraySymbol("A", (2, 3, 4))) == "A"
+    assert latex(ArrayElement("A", (2, 1/(1-x), 0))) == "{{A}_{2, \\frac{1}{1 - x}, 0}}"
+    M = MatrixSymbol("M", 3, 3)
+    N = MatrixSymbol("N", 3, 3)
+    assert latex(ArrayElement(M*N, [x, 0])) == "{{\\left(M N\\right)}_{x, 0}}"
+
+def test_Array():
+    arr = Array(range(10))
+    assert latex(arr) == r'\left[\begin{matrix}0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9\end{matrix}\right]'
+
+    arr = Array(range(11))
+    # fill the empty argument with a bunch of 'c' to avoid latex errors
+    assert latex(arr) == r'\left[\begin{array}{ccccccccccc}0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10\end{array}\right]'
+
+def test_latex_with_unevaluated():
+    with evaluate(False):
+        assert latex(a * a) == r"a a"
+
+
+def test_latex_disable_split_super_sub():
+    assert latex(Symbol('u^a_b')) == 'u^{a}_{b}'
+    assert latex(Symbol('u^a_b'), disable_split_super_sub=False) == 'u^{a}_{b}'
+    assert latex(Symbol('u^a_b'), disable_split_super_sub=True) == 'u\\^a\\_b'
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_llvmjit.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_llvmjit.py
new file mode 100644
index 0000000000000000000000000000000000000000..709476f1d7517dc629210341594a70dc6f41808f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_llvmjit.py
@@ -0,0 +1,224 @@
+from sympy.external import import_module
+from sympy.testing.pytest import raises
+import ctypes
+
+
+if import_module('llvmlite'):
+    import sympy.printing.llvmjitcode as g
+else:
+    disabled = True
+
+import sympy
+from sympy.abc import a, b, n
+
+
+# copied from numpy.isclose documentation
+def isclose(a, b):
+    rtol = 1e-5
+    atol = 1e-8
+    return abs(a-b) <= atol + rtol*abs(b)
+
+
+def test_simple_expr():
+    e = a + 1.0
+    f = g.llvm_callable([a], e)
+    res = float(e.subs({a: 4.0}).evalf())
+    jit_res = f(4.0)
+
+    assert isclose(jit_res, res)
+
+
+def test_two_arg():
+    e = 4.0*a + b + 3.0
+    f = g.llvm_callable([a, b], e)
+    res = float(e.subs({a: 4.0, b: 3.0}).evalf())
+    jit_res = f(4.0, 3.0)
+
+    assert isclose(jit_res, res)
+
+
+def test_func():
+    e = 4.0*sympy.exp(-a)
+    f = g.llvm_callable([a], e)
+    res = float(e.subs({a: 1.5}).evalf())
+    jit_res = f(1.5)
+
+    assert isclose(jit_res, res)
+
+
+def test_two_func():
+    e = 4.0*sympy.exp(-a) + sympy.exp(b)
+    f = g.llvm_callable([a, b], e)
+    res = float(e.subs({a: 1.5, b: 2.0}).evalf())
+    jit_res = f(1.5, 2.0)
+
+    assert isclose(jit_res, res)
+
+
+def test_two_sqrt():
+    e = 4.0*sympy.sqrt(a) + sympy.sqrt(b)
+    f = g.llvm_callable([a, b], e)
+    res = float(e.subs({a: 1.5, b: 2.0}).evalf())
+    jit_res = f(1.5, 2.0)
+
+    assert isclose(jit_res, res)
+
+
+def test_two_pow():
+    e = a**1.5 + b**7
+    f = g.llvm_callable([a, b], e)
+    res = float(e.subs({a: 1.5, b: 2.0}).evalf())
+    jit_res = f(1.5, 2.0)
+
+    assert isclose(jit_res, res)
+
+
+def test_callback():
+    e = a + 1.2
+    f = g.llvm_callable([a], e, callback_type='scipy.integrate.test')
+    m = ctypes.c_int(1)
+    array_type = ctypes.c_double * 1
+    inp = {a: 2.2}
+    array = array_type(inp[a])
+    jit_res = f(m, array)
+
+    res = float(e.subs(inp).evalf())
+
+    assert isclose(jit_res, res)
+
+
+def test_callback_cubature():
+    e = a + 1.2
+    f = g.llvm_callable([a], e, callback_type='cubature')
+    m = ctypes.c_int(1)
+    array_type = ctypes.c_double * 1
+    inp = {a: 2.2}
+    array = array_type(inp[a])
+    out_array = array_type(0.0)
+    jit_ret = f(m, array, None, m, out_array)
+
+    assert jit_ret == 0
+
+    res = float(e.subs(inp).evalf())
+
+    assert isclose(out_array[0], res)
+
+
+def test_callback_two():
+    e = 3*a*b
+    f = g.llvm_callable([a, b], e, callback_type='scipy.integrate.test')
+    m = ctypes.c_int(2)
+    array_type = ctypes.c_double * 2
+    inp = {a: 0.2, b: 1.7}
+    array = array_type(inp[a], inp[b])
+    jit_res = f(m, array)
+
+    res = float(e.subs(inp).evalf())
+
+    assert isclose(jit_res, res)
+
+
+def test_callback_alt_two():
+    d = sympy.IndexedBase('d')
+    e = 3*d[0]*d[1]
+    f = g.llvm_callable([n, d], e, callback_type='scipy.integrate.test')
+    m = ctypes.c_int(2)
+    array_type = ctypes.c_double * 2
+    inp = {d[0]: 0.2, d[1]: 1.7}
+    array = array_type(inp[d[0]], inp[d[1]])
+    jit_res = f(m, array)
+
+    res = float(e.subs(inp).evalf())
+
+    assert isclose(jit_res, res)
+
+
+def test_multiple_statements():
+    # Match return from CSE
+    e = [[(b, 4.0*a)], [b + 5]]
+    f = g.llvm_callable([a], e)
+    b_val = e[0][0][1].subs({a: 1.5})
+    res = float(e[1][0].subs({b: b_val}).evalf())
+    jit_res = f(1.5)
+    assert isclose(jit_res, res)
+
+    f_callback = g.llvm_callable([a], e, callback_type='scipy.integrate.test')
+    m = ctypes.c_int(1)
+    array_type = ctypes.c_double * 1
+    array = array_type(1.5)
+    jit_callback_res = f_callback(m, array)
+    assert isclose(jit_callback_res, res)
+
+
+def test_cse():
+    e = a*a + b*b + sympy.exp(-a*a - b*b)
+    e2 = sympy.cse(e)
+    f = g.llvm_callable([a, b], e2)
+    res = float(e.subs({a: 2.3, b: 0.1}).evalf())
+    jit_res = f(2.3, 0.1)
+
+    assert isclose(jit_res, res)
+
+
+def eval_cse(e, sub_dict):
+    tmp_dict = {}
+    for tmp_name, tmp_expr in e[0]:
+        e2 = tmp_expr.subs(sub_dict)
+        e3 = e2.subs(tmp_dict)
+        tmp_dict[tmp_name] = e3
+    return [e.subs(sub_dict).subs(tmp_dict) for e in e[1]]
+
+
+def test_cse_multiple():
+    e1 = a*a
+    e2 = a*a + b*b
+    e3 = sympy.cse([e1, e2])
+
+    raises(NotImplementedError,
+           lambda: g.llvm_callable([a, b], e3, callback_type='scipy.integrate'))
+
+    f = g.llvm_callable([a, b], e3)
+    jit_res = f(0.1, 1.5)
+    assert len(jit_res) == 2
+    res = eval_cse(e3, {a: 0.1, b: 1.5})
+    assert isclose(res[0], jit_res[0])
+    assert isclose(res[1], jit_res[1])
+
+
+def test_callback_cubature_multiple():
+    e1 = a*a
+    e2 = a*a + b*b
+    e3 = sympy.cse([e1, e2, 4*e2])
+    f = g.llvm_callable([a, b], e3, callback_type='cubature')
+
+    # Number of input variables
+    ndim = 2
+    # Number of output expression values
+    outdim = 3
+
+    m = ctypes.c_int(ndim)
+    fdim = ctypes.c_int(outdim)
+    array_type = ctypes.c_double * ndim
+    out_array_type = ctypes.c_double * outdim
+    inp = {a: 0.2, b: 1.5}
+    array = array_type(inp[a], inp[b])
+    out_array = out_array_type()
+    jit_ret = f(m, array, None, fdim, out_array)
+
+    assert jit_ret == 0
+
+    res = eval_cse(e3, inp)
+
+    assert isclose(out_array[0], res[0])
+    assert isclose(out_array[1], res[1])
+    assert isclose(out_array[2], res[2])
+
+
+def test_symbol_not_found():
+    e = a*a + b
+    raises(LookupError, lambda: g.llvm_callable([a], e))
+
+
+def test_bad_callback():
+    e = a
+    raises(ValueError, lambda: g.llvm_callable([a], e, callback_type='bad_callback'))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_maple.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_maple.py
new file mode 100644
index 0000000000000000000000000000000000000000..9bb4c512ad3203bd64ae56b350e15734b3a6afb0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_maple.py
@@ -0,0 +1,381 @@
+from sympy.core import (S, pi, oo, symbols, Function, Rational, Integer,
+                        Tuple, Symbol, Eq, Ne, Le, Lt, Gt, Ge)
+from sympy.core import EulerGamma, GoldenRatio, Catalan, Lambda, Mul, Pow
+from sympy.functions import Piecewise, sqrt, ceiling, exp, sin, cos, sinc, lucas
+from sympy.testing.pytest import raises
+from sympy.utilities.lambdify import implemented_function
+from sympy.matrices import (eye, Matrix, MatrixSymbol, Identity,
+                            HadamardProduct, SparseMatrix)
+from sympy.functions.special.bessel import besseli
+
+from sympy.printing.maple import maple_code
+
+x, y, z = symbols('x,y,z')
+
+
+def test_Integer():
+    assert maple_code(Integer(67)) == "67"
+    assert maple_code(Integer(-1)) == "-1"
+
+
+def test_Rational():
+    assert maple_code(Rational(3, 7)) == "3/7"
+    assert maple_code(Rational(18, 9)) == "2"
+    assert maple_code(Rational(3, -7)) == "-3/7"
+    assert maple_code(Rational(-3, -7)) == "3/7"
+    assert maple_code(x + Rational(3, 7)) == "x + 3/7"
+    assert maple_code(Rational(3, 7) * x) == '(3/7)*x'
+
+
+def test_Relational():
+    assert maple_code(Eq(x, y)) == "x = y"
+    assert maple_code(Ne(x, y)) == "x <> y"
+    assert maple_code(Le(x, y)) == "x <= y"
+    assert maple_code(Lt(x, y)) == "x < y"
+    assert maple_code(Gt(x, y)) == "x > y"
+    assert maple_code(Ge(x, y)) == "x >= y"
+
+
+def test_Function():
+    assert maple_code(sin(x) ** cos(x)) == "sin(x)^cos(x)"
+    assert maple_code(abs(x)) == "abs(x)"
+    assert maple_code(ceiling(x)) == "ceil(x)"
+
+
+def test_Pow():
+    assert maple_code(x ** 3) == "x^3"
+    assert maple_code(x ** (y ** 3)) == "x^(y^3)"
+
+    assert maple_code((x ** 3) ** y) == "(x^3)^y"
+    assert maple_code(x ** Rational(2, 3)) == 'x^(2/3)'
+
+    g = implemented_function('g', Lambda(x, 2 * x))
+    assert maple_code(1 / (g(x) * 3.5) ** (x - y ** x) / (x ** 2 + y)) == \
+           "(3.5*2*x)^(-x + y^x)/(x^2 + y)"
+    # For issue 14160
+    assert maple_code(Mul(-2, x, Pow(Mul(y, y, evaluate=False), -1, evaluate=False),
+                          evaluate=False)) == '-2*x/(y*y)'
+
+
+def test_basic_ops():
+    assert maple_code(x * y) == "x*y"
+    assert maple_code(x + y) == "x + y"
+    assert maple_code(x - y) == "x - y"
+    assert maple_code(-x) == "-x"
+
+
+def test_1_over_x_and_sqrt():
+    # 1.0 and 0.5 would do something different in regular StrPrinter,
+    # but these are exact in IEEE floating point so no different here.
+    assert maple_code(1 / x) == '1/x'
+    assert maple_code(x ** -1) == maple_code(x ** -1.0) == '1/x'
+    assert maple_code(1 / sqrt(x)) == '1/sqrt(x)'
+    assert maple_code(x ** -S.Half) == maple_code(x ** -0.5) == '1/sqrt(x)'
+    assert maple_code(sqrt(x)) == 'sqrt(x)'
+    assert maple_code(x ** S.Half) == maple_code(x ** 0.5) == 'sqrt(x)'
+    assert maple_code(1 / pi) == '1/Pi'
+    assert maple_code(pi ** -1) == maple_code(pi ** -1.0) == '1/Pi'
+    assert maple_code(pi ** -0.5) == '1/sqrt(Pi)'
+
+
+def test_mix_number_mult_symbols():
+    assert maple_code(3 * x) == "3*x"
+    assert maple_code(pi * x) == "Pi*x"
+    assert maple_code(3 / x) == "3/x"
+    assert maple_code(pi / x) == "Pi/x"
+    assert maple_code(x / 3) == '(1/3)*x'
+    assert maple_code(x / pi) == "x/Pi"
+    assert maple_code(x * y) == "x*y"
+    assert maple_code(3 * x * y) == "3*x*y"
+    assert maple_code(3 * pi * x * y) == "3*Pi*x*y"
+    assert maple_code(x / y) == "x/y"
+    assert maple_code(3 * x / y) == "3*x/y"
+    assert maple_code(x * y / z) == "x*y/z"
+    assert maple_code(x / y * z) == "x*z/y"
+    assert maple_code(1 / x / y) == "1/(x*y)"
+    assert maple_code(2 * pi * x / y / z) == "2*Pi*x/(y*z)"
+    assert maple_code(3 * pi / x) == "3*Pi/x"
+    assert maple_code(S(3) / 5) == "3/5"
+    assert maple_code(S(3) / 5 * x) == '(3/5)*x'
+    assert maple_code(x / y / z) == "x/(y*z)"
+    assert maple_code((x + y) / z) == "(x + y)/z"
+    assert maple_code((x + y) / (z + x)) == "(x + y)/(x + z)"
+    assert maple_code((x + y) / EulerGamma) == '(x + y)/gamma'
+    assert maple_code(x / 3 / pi) == '(1/3)*x/Pi'
+    assert maple_code(S(3) / 5 * x * y / pi) == '(3/5)*x*y/Pi'
+
+
+def test_mix_number_pow_symbols():
+    assert maple_code(pi ** 3) == 'Pi^3'
+    assert maple_code(x ** 2) == 'x^2'
+
+    assert maple_code(x ** (pi ** 3)) == 'x^(Pi^3)'
+    assert maple_code(x ** y) == 'x^y'
+
+    assert maple_code(x ** (y ** z)) == 'x^(y^z)'
+    assert maple_code((x ** y) ** z) == '(x^y)^z'
+
+
+def test_imag():
+    I = S('I')
+    assert maple_code(I) == "I"
+    assert maple_code(5 * I) == "5*I"
+
+    assert maple_code((S(3) / 2) * I) == "(3/2)*I"
+    assert maple_code(3 + 4 * I) == "3 + 4*I"
+
+
+def test_constants():
+    assert maple_code(pi) == "Pi"
+    assert maple_code(oo) == "infinity"
+    assert maple_code(-oo) == "-infinity"
+    assert maple_code(S.NegativeInfinity) == "-infinity"
+    assert maple_code(S.NaN) == "undefined"
+    assert maple_code(S.Exp1) == "exp(1)"
+    assert maple_code(exp(1)) == "exp(1)"
+
+
+def test_constants_other():
+    assert maple_code(2 * GoldenRatio) == '2*(1/2 + (1/2)*sqrt(5))'
+    assert maple_code(2 * Catalan) == '2*Catalan'
+    assert maple_code(2 * EulerGamma) == "2*gamma"
+
+
+def test_boolean():
+    assert maple_code(x & y) == "x and y"
+    assert maple_code(x | y) == "x or y"
+    assert maple_code(~x) == "not x"
+    assert maple_code(x & y & z) == "x and y and z"
+    assert maple_code(x | y | z) == "x or y or z"
+    assert maple_code((x & y) | z) == "z or x and y"
+    assert maple_code((x | y) & z) == "z and (x or y)"
+
+
+def test_Matrices():
+    assert maple_code(Matrix(1, 1, [10])) == \
+           'Matrix([[10]], storage = rectangular)'
+
+    A = Matrix([[1, sin(x / 2), abs(x)],
+                [0, 1, pi],
+                [0, exp(1), ceiling(x)]])
+    expected = \
+        'Matrix(' \
+        '[[1, sin((1/2)*x), abs(x)],' \
+        ' [0, 1, Pi],' \
+        ' [0, exp(1), ceil(x)]], ' \
+        'storage = rectangular)'
+    assert maple_code(A) == expected
+
+    # row and columns
+    assert maple_code(A[:, 0]) == \
+           'Matrix([[1], [0], [0]], storage = rectangular)'
+    assert maple_code(A[0, :]) == \
+           'Matrix([[1, sin((1/2)*x), abs(x)]], storage = rectangular)'
+    assert maple_code(Matrix([[x, x - y, -y]])) == \
+           'Matrix([[x, x - y, -y]], storage = rectangular)'
+
+    # empty matrices
+    assert maple_code(Matrix(0, 0, [])) == \
+           'Matrix([], storage = rectangular)'
+    assert maple_code(Matrix(0, 3, [])) == \
+           'Matrix([], storage = rectangular)'
+
+def test_SparseMatrices():
+    assert maple_code(SparseMatrix(Identity(2))) == 'Matrix([[1, 0], [0, 1]], storage = sparse)'
+
+
+def test_vector_entries_hadamard():
+    # For a row or column, user might to use the other dimension
+    A = Matrix([[1, sin(2 / x), 3 * pi / x / 5]])
+    assert maple_code(A) == \
+           'Matrix([[1, sin(2/x), (3/5)*Pi/x]], storage = rectangular)'
+    assert maple_code(A.T) == \
+           'Matrix([[1], [sin(2/x)], [(3/5)*Pi/x]], storage = rectangular)'
+
+
+def test_Matrices_entries_not_hadamard():
+    A = Matrix([[1, sin(2 / x), 3 * pi / x / 5], [1, 2, x * y]])
+    expected = \
+        'Matrix([[1, sin(2/x), (3/5)*Pi/x], [1, 2, x*y]], ' \
+        'storage = rectangular)'
+    assert maple_code(A) == expected
+
+
+def test_MatrixSymbol():
+    n = Symbol('n', integer=True)
+    A = MatrixSymbol('A', n, n)
+    B = MatrixSymbol('B', n, n)
+    assert maple_code(A * B) == "A.B"
+    assert maple_code(B * A) == "B.A"
+    assert maple_code(2 * A * B) == "2*A.B"
+    assert maple_code(B * 2 * A) == "2*B.A"
+
+    assert maple_code(
+        A * (B + 3 * Identity(n))) == "A.(3*Matrix(n, shape = identity) + B)"
+
+    assert maple_code(A ** (x ** 2)) == "MatrixPower(A, x^2)"
+    assert maple_code(A ** 3) == "MatrixPower(A, 3)"
+    assert maple_code(A ** (S.Half)) == "MatrixPower(A, 1/2)"
+
+
+def test_special_matrices():
+    assert maple_code(6 * Identity(3)) == "6*Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]], storage = sparse)"
+    assert maple_code(Identity(x)) == 'Matrix(x, shape = identity)'
+
+
+def test_containers():
+    assert maple_code([1, 2, 3, [4, 5, [6, 7]], 8, [9, 10], 11]) == \
+           "[1, 2, 3, [4, 5, [6, 7]], 8, [9, 10], 11]"
+
+    assert maple_code((1, 2, (3, 4))) == "[1, 2, [3, 4]]"
+    assert maple_code([1]) == "[1]"
+    assert maple_code((1,)) == "[1]"
+    assert maple_code(Tuple(*[1, 2, 3])) == "[1, 2, 3]"
+    assert maple_code((1, x * y, (3, x ** 2))) == "[1, x*y, [3, x^2]]"
+    # scalar, matrix, empty matrix and empty list
+
+    assert maple_code((1, eye(3), Matrix(0, 0, []), [])) == \
+           "[1, Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]], storage = rectangular), Matrix([], storage = rectangular), []]"
+
+
+def test_maple_noninline():
+    source = maple_code((x + y)/Catalan, assign_to='me', inline=False)
+    expected = "me := (x + y)/Catalan"
+
+    assert source == expected
+
+
+def test_maple_matrix_assign_to():
+    A = Matrix([[1, 2, 3]])
+    assert maple_code(A, assign_to='a') == "a := Matrix([[1, 2, 3]], storage = rectangular)"
+    A = Matrix([[1, 2], [3, 4]])
+    assert maple_code(A, assign_to='A') == "A := Matrix([[1, 2], [3, 4]], storage = rectangular)"
+
+
+def test_maple_matrix_assign_to_more():
+    # assigning to Symbol or MatrixSymbol requires lhs/rhs match
+    A = Matrix([[1, 2, 3]])
+    B = MatrixSymbol('B', 1, 3)
+    C = MatrixSymbol('C', 2, 3)
+    assert maple_code(A, assign_to=B) == "B := Matrix([[1, 2, 3]], storage = rectangular)"
+    raises(ValueError, lambda: maple_code(A, assign_to=x))
+    raises(ValueError, lambda: maple_code(A, assign_to=C))
+
+
+def test_maple_matrix_1x1():
+    A = Matrix([[3]])
+    assert maple_code(A, assign_to='B') == "B := Matrix([[3]], storage = rectangular)"
+
+
+def test_maple_matrix_elements():
+    A = Matrix([[x, 2, x * y]])
+
+    assert maple_code(A[0, 0] ** 2 + A[0, 1] + A[0, 2]) == "x^2 + x*y + 2"
+    AA = MatrixSymbol('AA', 1, 3)
+    assert maple_code(AA) == "AA"
+
+    assert maple_code(AA[0, 0] ** 2 + sin(AA[0, 1]) + AA[0, 2]) == \
+           "sin(AA[1, 2]) + AA[1, 1]^2 + AA[1, 3]"
+    assert maple_code(sum(AA)) == "AA[1, 1] + AA[1, 2] + AA[1, 3]"
+
+
+def test_maple_boolean():
+    assert maple_code(True) == "true"
+    assert maple_code(S.true) == "true"
+    assert maple_code(False) == "false"
+    assert maple_code(S.false) == "false"
+
+
+def test_sparse():
+    M = SparseMatrix(5, 6, {})
+    M[2, 2] = 10
+    M[1, 2] = 20
+    M[1, 3] = 22
+    M[0, 3] = 30
+    M[3, 0] = x * y
+    assert maple_code(M) == \
+           'Matrix([[0, 0, 0, 30, 0, 0],' \
+           ' [0, 0, 20, 22, 0, 0],' \
+           ' [0, 0, 10, 0, 0, 0],' \
+           ' [x*y, 0, 0, 0, 0, 0],' \
+           ' [0, 0, 0, 0, 0, 0]], ' \
+           'storage = sparse)'
+
+# Not an important point.
+def test_maple_not_supported():
+    with raises(NotImplementedError):
+        maple_code(S.ComplexInfinity)
+
+
+def test_MatrixElement_printing():
+    # test cases for issue #11821
+    A = MatrixSymbol("A", 1, 3)
+    B = MatrixSymbol("B", 1, 3)
+
+    assert (maple_code(A[0, 0]) == "A[1, 1]")
+    assert (maple_code(3 * A[0, 0]) == "3*A[1, 1]")
+
+    F = A-B
+
+    assert (maple_code(F[0,0]) == "A[1, 1] - B[1, 1]")
+
+
+def test_hadamard():
+    A = MatrixSymbol('A', 3, 3)
+    B = MatrixSymbol('B', 3, 3)
+    v = MatrixSymbol('v', 3, 1)
+    h = MatrixSymbol('h', 1, 3)
+    C = HadamardProduct(A, B)
+    assert maple_code(C) == "A*B"
+
+    assert maple_code(C * v) == "(A*B).v"
+    # HadamardProduct is higher than dot product.
+
+    assert maple_code(h * C * v) == "h.(A*B).v"
+
+    assert maple_code(C * A) == "(A*B).A"
+    # mixing Hadamard and scalar strange b/c we vectorize scalars
+
+    assert maple_code(C * x * y) == "x*y*(A*B)"
+
+
+def test_maple_piecewise():
+    expr = Piecewise((x, x < 1), (x ** 2, True))
+
+    assert maple_code(expr) == "piecewise(x < 1, x, x^2)"
+    assert maple_code(expr, assign_to="r") == (
+        "r := piecewise(x < 1, x, x^2)")
+
+    expr = Piecewise((x ** 2, x < 1), (x ** 3, x < 2), (x ** 4, x < 3), (x ** 5, True))
+    expected = "piecewise(x < 1, x^2, x < 2, x^3, x < 3, x^4, x^5)"
+    assert maple_code(expr) == expected
+    assert maple_code(expr, assign_to="r") == "r := " + expected
+
+    # Check that Piecewise without a True (default) condition error
+    expr = Piecewise((x, x < 1), (x ** 2, x > 1), (sin(x), x > 0))
+    raises(ValueError, lambda: maple_code(expr))
+
+
+def test_maple_piecewise_times_const():
+    pw = Piecewise((x, x < 1), (x ** 2, True))
+
+    assert maple_code(2 * pw) == "2*piecewise(x < 1, x, x^2)"
+    assert maple_code(pw / x) == "piecewise(x < 1, x, x^2)/x"
+    assert maple_code(pw / (x * y)) == "piecewise(x < 1, x, x^2)/(x*y)"
+    assert maple_code(pw / 3) == "(1/3)*piecewise(x < 1, x, x^2)"
+
+
+def test_maple_derivatives():
+    f = Function('f')
+    assert maple_code(f(x).diff(x)) == 'diff(f(x), x)'
+    assert maple_code(f(x).diff(x, 2)) == 'diff(f(x), x$2)'
+
+
+def test_automatic_rewrites():
+    assert maple_code(lucas(x)) == '(2^(-x)*((1 - sqrt(5))^x + (1 + sqrt(5))^x))'
+    assert maple_code(sinc(x)) == '(piecewise(x <> 0, sin(x)/x, 1))'
+
+
+def test_specfun():
+    assert maple_code('asin(x)') == 'arcsin(x)'
+    assert maple_code(besseli(x, y)) == 'BesselI(x, y)'
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_mathematica.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_mathematica.py
new file mode 100644
index 0000000000000000000000000000000000000000..aaf6b537677442ae59a4f1bbd2b5774d6646f4e2
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_mathematica.py
@@ -0,0 +1,287 @@
+from sympy.core import (S, pi, oo, symbols, Function, Rational, Integer, Tuple,
+                        Derivative, Eq, Ne, Le, Lt, Gt, Ge)
+from sympy.integrals import Integral
+from sympy.concrete import Sum
+from sympy.functions import (exp, sin, cos, fresnelc, fresnels, conjugate, Max,
+                             Min, gamma, polygamma, loggamma, erf, erfi, erfc,
+                             erf2, expint, erfinv, erfcinv, Ei, Si, Ci, li,
+                             Shi, Chi, uppergamma, beta, subfactorial, erf2inv,
+                             factorial, factorial2, catalan, RisingFactorial,
+                             FallingFactorial, harmonic, atan2, sec, acsc,
+                             hermite, laguerre, assoc_laguerre, jacobi,
+                             gegenbauer, chebyshevt, chebyshevu, legendre,
+                             assoc_legendre, Li, LambertW)
+
+from sympy.printing.mathematica import mathematica_code as mcode
+
+x, y, z, w = symbols('x,y,z,w')
+f = Function('f')
+
+
+def test_Integer():
+    assert mcode(Integer(67)) == "67"
+    assert mcode(Integer(-1)) == "-1"
+
+
+def test_Rational():
+    assert mcode(Rational(3, 7)) == "3/7"
+    assert mcode(Rational(18, 9)) == "2"
+    assert mcode(Rational(3, -7)) == "-3/7"
+    assert mcode(Rational(-3, -7)) == "3/7"
+    assert mcode(x + Rational(3, 7)) == "x + 3/7"
+    assert mcode(Rational(3, 7)*x) == "(3/7)*x"
+
+
+def test_Relational():
+    assert mcode(Eq(x, y)) == "x == y"
+    assert mcode(Ne(x, y)) == "x != y"
+    assert mcode(Le(x, y)) == "x <= y"
+    assert mcode(Lt(x, y)) == "x < y"
+    assert mcode(Gt(x, y)) == "x > y"
+    assert mcode(Ge(x, y)) == "x >= y"
+
+
+def test_Function():
+    assert mcode(f(x, y, z)) == "f[x, y, z]"
+    assert mcode(sin(x) ** cos(x)) == "Sin[x]^Cos[x]"
+    assert mcode(sec(x) * acsc(x)) == "ArcCsc[x]*Sec[x]"
+    assert mcode(atan2(y, x)) == "ArcTan[x, y]"
+    assert mcode(conjugate(x)) == "Conjugate[x]"
+    assert mcode(Max(x, y, z)*Min(y, z)) == "Max[x, y, z]*Min[y, z]"
+    assert mcode(fresnelc(x)) == "FresnelC[x]"
+    assert mcode(fresnels(x)) == "FresnelS[x]"
+    assert mcode(gamma(x)) == "Gamma[x]"
+    assert mcode(uppergamma(x, y)) == "Gamma[x, y]"
+    assert mcode(polygamma(x, y)) == "PolyGamma[x, y]"
+    assert mcode(loggamma(x)) == "LogGamma[x]"
+    assert mcode(erf(x)) == "Erf[x]"
+    assert mcode(erfc(x)) == "Erfc[x]"
+    assert mcode(erfi(x)) == "Erfi[x]"
+    assert mcode(erf2(x, y)) == "Erf[x, y]"
+    assert mcode(expint(x, y)) == "ExpIntegralE[x, y]"
+    assert mcode(erfcinv(x)) == "InverseErfc[x]"
+    assert mcode(erfinv(x)) == "InverseErf[x]"
+    assert mcode(erf2inv(x, y)) == "InverseErf[x, y]"
+    assert mcode(Ei(x)) == "ExpIntegralEi[x]"
+    assert mcode(Ci(x)) == "CosIntegral[x]"
+    assert mcode(li(x)) == "LogIntegral[x]"
+    assert mcode(Si(x)) == "SinIntegral[x]"
+    assert mcode(Shi(x)) == "SinhIntegral[x]"
+    assert mcode(Chi(x)) == "CoshIntegral[x]"
+    assert mcode(beta(x, y)) == "Beta[x, y]"
+    assert mcode(factorial(x)) == "Factorial[x]"
+    assert mcode(factorial2(x)) == "Factorial2[x]"
+    assert mcode(subfactorial(x)) == "Subfactorial[x]"
+    assert mcode(FallingFactorial(x, y)) == "FactorialPower[x, y]"
+    assert mcode(RisingFactorial(x, y)) == "Pochhammer[x, y]"
+    assert mcode(catalan(x)) == "CatalanNumber[x]"
+    assert mcode(harmonic(x)) == "HarmonicNumber[x]"
+    assert mcode(harmonic(x, y)) == "HarmonicNumber[x, y]"
+    assert mcode(Li(x)) == "LogIntegral[x] - LogIntegral[2]"
+    assert mcode(LambertW(x)) == "ProductLog[x]"
+    assert mcode(LambertW(x, -1)) == "ProductLog[-1, x]"
+    assert mcode(LambertW(x, y)) == "ProductLog[y, x]"
+
+
+def test_special_polynomials():
+    assert mcode(hermite(x, y)) == "HermiteH[x, y]"
+    assert mcode(laguerre(x, y)) == "LaguerreL[x, y]"
+    assert mcode(assoc_laguerre(x, y, z)) == "LaguerreL[x, y, z]"
+    assert mcode(jacobi(x, y, z, w)) == "JacobiP[x, y, z, w]"
+    assert mcode(gegenbauer(x, y, z)) == "GegenbauerC[x, y, z]"
+    assert mcode(chebyshevt(x, y)) == "ChebyshevT[x, y]"
+    assert mcode(chebyshevu(x, y)) == "ChebyshevU[x, y]"
+    assert mcode(legendre(x, y)) == "LegendreP[x, y]"
+    assert mcode(assoc_legendre(x, y, z)) == "LegendreP[x, y, z]"
+
+
+def test_Pow():
+    assert mcode(x**3) == "x^3"
+    assert mcode(x**(y**3)) == "x^(y^3)"
+    assert mcode(1/(f(x)*3.5)**(x - y**x)/(x**2 + y)) == \
+        "(3.5*f[x])^(-x + y^x)/(x^2 + y)"
+    assert mcode(x**-1.0) == 'x^(-1.0)'
+    assert mcode(x**Rational(2, 3)) == 'x^(2/3)'
+
+
+def test_Mul():
+    A, B, C, D = symbols('A B C D', commutative=False)
+    assert mcode(x*y*z) == "x*y*z"
+    assert mcode(x*y*A) == "x*y*A"
+    assert mcode(x*y*A*B) == "x*y*A**B"
+    assert mcode(x*y*A*B*C) == "x*y*A**B**C"
+    assert mcode(x*A*B*(C + D)*A*y) == "x*y*A**B**(C + D)**A"
+
+
+def test_constants():
+    assert mcode(S.Zero) == "0"
+    assert mcode(S.One) == "1"
+    assert mcode(S.NegativeOne) == "-1"
+    assert mcode(S.Half) == "1/2"
+    assert mcode(S.ImaginaryUnit) == "I"
+
+    assert mcode(oo) == "Infinity"
+    assert mcode(S.NegativeInfinity) == "-Infinity"
+    assert mcode(S.ComplexInfinity) == "ComplexInfinity"
+    assert mcode(S.NaN) == "Indeterminate"
+
+    assert mcode(S.Exp1) == "E"
+    assert mcode(pi) == "Pi"
+    assert mcode(S.GoldenRatio) == "GoldenRatio"
+    assert mcode(S.TribonacciConstant) == \
+        "(1/3 + (1/3)*(19 - 3*33^(1/2))^(1/3) + " \
+        "(1/3)*(3*33^(1/2) + 19)^(1/3))"
+    assert mcode(2*S.TribonacciConstant) == \
+        "2*(1/3 + (1/3)*(19 - 3*33^(1/2))^(1/3) + " \
+        "(1/3)*(3*33^(1/2) + 19)^(1/3))"
+    assert mcode(S.EulerGamma) == "EulerGamma"
+    assert mcode(S.Catalan) == "Catalan"
+
+
+def test_containers():
+    assert mcode([1, 2, 3, [4, 5, [6, 7]], 8, [9, 10], 11]) == \
+        "{1, 2, 3, {4, 5, {6, 7}}, 8, {9, 10}, 11}"
+    assert mcode((1, 2, (3, 4))) == "{1, 2, {3, 4}}"
+    assert mcode([1]) == "{1}"
+    assert mcode((1,)) == "{1}"
+    assert mcode(Tuple(*[1, 2, 3])) == "{1, 2, 3}"
+
+
+def test_matrices():
+    from sympy.matrices import MutableDenseMatrix, MutableSparseMatrix, \
+        ImmutableDenseMatrix, ImmutableSparseMatrix
+    A = MutableDenseMatrix(
+        [[1, -1, 0, 0],
+         [0, 1, -1, 0],
+         [0, 0, 1, -1],
+         [0, 0, 0, 1]]
+    )
+    B = MutableSparseMatrix(A)
+    C = ImmutableDenseMatrix(A)
+    D = ImmutableSparseMatrix(A)
+
+    assert mcode(C) == mcode(A) == \
+        "{{1, -1, 0, 0}, " \
+        "{0, 1, -1, 0}, " \
+        "{0, 0, 1, -1}, " \
+        "{0, 0, 0, 1}}"
+
+    assert mcode(D) == mcode(B) == \
+        "SparseArray[{" \
+        "{1, 1} -> 1, {1, 2} -> -1, {2, 2} -> 1, {2, 3} -> -1, " \
+        "{3, 3} -> 1, {3, 4} -> -1, {4, 4} -> 1" \
+        "}, {4, 4}]"
+
+    # Trivial cases of matrices
+    assert mcode(MutableDenseMatrix(0, 0, [])) == '{}'
+    assert mcode(MutableSparseMatrix(0, 0, [])) == 'SparseArray[{}, {0, 0}]'
+    assert mcode(MutableDenseMatrix(0, 3, [])) == '{}'
+    assert mcode(MutableSparseMatrix(0, 3, [])) == 'SparseArray[{}, {0, 3}]'
+    assert mcode(MutableDenseMatrix(3, 0, [])) == '{{}, {}, {}}'
+    assert mcode(MutableSparseMatrix(3, 0, [])) == 'SparseArray[{}, {3, 0}]'
+
+def test_NDArray():
+    from sympy.tensor.array import (
+        MutableDenseNDimArray, ImmutableDenseNDimArray,
+        MutableSparseNDimArray, ImmutableSparseNDimArray)
+
+    example = MutableDenseNDimArray(
+        [[[1, 2, 3, 4],
+          [5, 6, 7, 8],
+          [9, 10, 11, 12]],
+         [[13, 14, 15, 16],
+          [17, 18, 19, 20],
+          [21, 22, 23, 24]]]
+    )
+
+    assert mcode(example) == \
+    "{{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}, " \
+    "{{13, 14, 15, 16}, {17, 18, 19, 20}, {21, 22, 23, 24}}}"
+
+    example = ImmutableDenseNDimArray(example)
+
+    assert mcode(example) == \
+    "{{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}, " \
+    "{{13, 14, 15, 16}, {17, 18, 19, 20}, {21, 22, 23, 24}}}"
+
+    example = MutableSparseNDimArray(example)
+
+    assert mcode(example) == \
+    "SparseArray[{" \
+        "{1, 1, 1} -> 1, {1, 1, 2} -> 2, {1, 1, 3} -> 3, " \
+        "{1, 1, 4} -> 4, {1, 2, 1} -> 5, {1, 2, 2} -> 6, " \
+        "{1, 2, 3} -> 7, {1, 2, 4} -> 8, {1, 3, 1} -> 9, " \
+        "{1, 3, 2} -> 10, {1, 3, 3} -> 11, {1, 3, 4} -> 12, " \
+        "{2, 1, 1} -> 13, {2, 1, 2} -> 14, {2, 1, 3} -> 15, " \
+        "{2, 1, 4} -> 16, {2, 2, 1} -> 17, {2, 2, 2} -> 18, " \
+        "{2, 2, 3} -> 19, {2, 2, 4} -> 20, {2, 3, 1} -> 21, " \
+        "{2, 3, 2} -> 22, {2, 3, 3} -> 23, {2, 3, 4} -> 24" \
+        "}, {2, 3, 4}]"
+
+    example = ImmutableSparseNDimArray(example)
+
+    assert mcode(example) == \
+    "SparseArray[{" \
+        "{1, 1, 1} -> 1, {1, 1, 2} -> 2, {1, 1, 3} -> 3, " \
+        "{1, 1, 4} -> 4, {1, 2, 1} -> 5, {1, 2, 2} -> 6, " \
+        "{1, 2, 3} -> 7, {1, 2, 4} -> 8, {1, 3, 1} -> 9, " \
+        "{1, 3, 2} -> 10, {1, 3, 3} -> 11, {1, 3, 4} -> 12, " \
+        "{2, 1, 1} -> 13, {2, 1, 2} -> 14, {2, 1, 3} -> 15, " \
+        "{2, 1, 4} -> 16, {2, 2, 1} -> 17, {2, 2, 2} -> 18, " \
+        "{2, 2, 3} -> 19, {2, 2, 4} -> 20, {2, 3, 1} -> 21, " \
+        "{2, 3, 2} -> 22, {2, 3, 3} -> 23, {2, 3, 4} -> 24" \
+        "}, {2, 3, 4}]"
+
+
+def test_Integral():
+    assert mcode(Integral(sin(sin(x)), x)) == "Hold[Integrate[Sin[Sin[x]], x]]"
+    assert mcode(Integral(exp(-x**2 - y**2),
+                          (x, -oo, oo),
+                          (y, -oo, oo))) == \
+        "Hold[Integrate[Exp[-x^2 - y^2], {x, -Infinity, Infinity}, " \
+        "{y, -Infinity, Infinity}]]"
+
+
+def test_Derivative():
+    assert mcode(Derivative(sin(x), x)) == "Hold[D[Sin[x], x]]"
+    assert mcode(Derivative(x, x)) == "Hold[D[x, x]]"
+    assert mcode(Derivative(sin(x)*y**4, x, 2)) == "Hold[D[y^4*Sin[x], {x, 2}]]"
+    assert mcode(Derivative(sin(x)*y**4, x, y, x)) == "Hold[D[y^4*Sin[x], x, y, x]]"
+    assert mcode(Derivative(sin(x)*y**4, x, y, 3, x)) == "Hold[D[y^4*Sin[x], x, {y, 3}, x]]"
+
+
+def test_Sum():
+    assert mcode(Sum(sin(x), (x, 0, 10))) == "Hold[Sum[Sin[x], {x, 0, 10}]]"
+    assert mcode(Sum(exp(-x**2 - y**2),
+                     (x, -oo, oo),
+                     (y, -oo, oo))) == \
+        "Hold[Sum[Exp[-x^2 - y^2], {x, -Infinity, Infinity}, " \
+        "{y, -Infinity, Infinity}]]"
+
+
+def test_comment():
+    from sympy.printing.mathematica import MCodePrinter
+    assert MCodePrinter()._get_comment("Hello World") == \
+        "(* Hello World *)"
+
+
+def test_userfuncs():
+    # Dictionary mutation test
+    some_function = symbols("some_function", cls=Function)
+    my_user_functions = {"some_function": "SomeFunction"}
+    assert mcode(
+        some_function(z),
+        user_functions=my_user_functions) == \
+        'SomeFunction[z]'
+    assert mcode(
+        some_function(z),
+        user_functions=my_user_functions) == \
+        'SomeFunction[z]'
+
+    # List argument test
+    my_user_functions = \
+        {"some_function": [(lambda x: True, "SomeOtherFunction")]}
+    assert mcode(
+        some_function(z),
+        user_functions=my_user_functions) == \
+        'SomeOtherFunction[z]'
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_mathml.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_mathml.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e7c2253c98fb1a4e99375774ad158df9b80b439
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_mathml.py
@@ -0,0 +1,2048 @@
+from sympy.calculus.accumulationbounds import AccumBounds
+from sympy.concrete.summations import Sum
+from sympy.core.basic import Basic
+from sympy.core.containers import Tuple
+from sympy.core.function import Derivative, Lambda, diff, Function
+from sympy.core.numbers import (zoo, Float, Integer, I, oo, pi, E,
+    Rational)
+from sympy.core.relational import Lt, Ge, Ne, Eq
+from sympy.core.singleton import S
+from sympy.core.symbol import symbols, Symbol
+from sympy.core.sympify import sympify
+from sympy.functions.combinatorial.factorials import (factorial2,
+    binomial, factorial)
+from sympy.functions.combinatorial.numbers import (lucas, bell,
+    catalan, euler, tribonacci, fibonacci, bernoulli, primenu, primeomega,
+    totient, reduced_totient)
+from sympy.functions.elementary.complexes import re, im, conjugate, Abs
+from sympy.functions.elementary.exponential import exp, LambertW, log
+from sympy.functions.elementary.hyperbolic import (tanh, acoth, atanh,
+    coth, asinh, acsch, asech, acosh, csch, sinh, cosh, sech)
+from sympy.functions.elementary.integers import ceiling, floor
+from sympy.functions.elementary.miscellaneous import Max, Min
+from sympy.functions.elementary.trigonometric import (csc, sec, tan,
+    atan, sin, asec, cot, cos, acot, acsc, asin, acos)
+from sympy.functions.special.delta_functions import Heaviside
+from sympy.functions.special.elliptic_integrals import (elliptic_pi,
+    elliptic_f, elliptic_k, elliptic_e)
+from sympy.functions.special.error_functions import (fresnelc,
+    fresnels, Ei, expint)
+from sympy.functions.special.gamma_functions import (gamma, uppergamma,
+    lowergamma)
+from sympy.functions.special.mathieu_functions import (mathieusprime,
+    mathieus, mathieucprime, mathieuc)
+from sympy.functions.special.polynomials import (jacobi, chebyshevu,
+    chebyshevt, hermite, assoc_legendre, gegenbauer, assoc_laguerre,
+    legendre, laguerre)
+from sympy.functions.special.singularity_functions import SingularityFunction
+from sympy.functions.special.zeta_functions import (polylog, stieltjes,
+    lerchphi, dirichlet_eta, zeta)
+from sympy.integrals.integrals import Integral
+from sympy.logic.boolalg import (Xor, Or, false, true, And, Equivalent,
+    Implies, Not)
+from sympy.matrices.dense import Matrix
+from sympy.matrices.expressions.determinant import Determinant
+from sympy.matrices.expressions.matexpr import MatrixSymbol
+from sympy.physics.quantum import (ComplexSpace, FockSpace, hbar,
+    HilbertSpace, Dagger)
+from sympy.printing.mathml import (MathMLPresentationPrinter,
+    MathMLPrinter, MathMLContentPrinter, mathml)
+from sympy.series.limits import Limit
+from sympy.sets.contains import Contains
+from sympy.sets.fancysets import Range
+from sympy.sets.sets import (Interval, Union, SymmetricDifference,
+    Complement, FiniteSet, Intersection, ProductSet)
+from sympy.stats.rv import RandomSymbol
+from sympy.tensor.indexed import IndexedBase
+from sympy.vector import (Divergence, CoordSys3D, Cross, Curl, Dot,
+    Laplacian, Gradient)
+from sympy.testing.pytest import raises, XFAIL
+
+x, y, z, a, b, c, d, e, n = symbols('x:z a:e n')
+mp = MathMLContentPrinter()
+mpp = MathMLPresentationPrinter()
+
+
+def test_mathml_printer():
+    m = MathMLPrinter()
+    assert m.doprint(1+x) == mp.doprint(1+x)
+
+
+def test_content_printmethod():
+    assert mp.doprint(1 + x) == 'x1'
+
+
+def test_content_mathml_core():
+    mml_1 = mp._print(1 + x)
+    assert mml_1.nodeName == 'apply'
+    nodes = mml_1.childNodes
+    assert len(nodes) == 3
+    assert nodes[0].nodeName == 'plus'
+    assert nodes[0].hasChildNodes() is False
+    assert nodes[0].nodeValue is None
+    assert nodes[1].nodeName in ['cn', 'ci']
+    if nodes[1].nodeName == 'cn':
+        assert nodes[1].childNodes[0].nodeValue == '1'
+        assert nodes[2].childNodes[0].nodeValue == 'x'
+    else:
+        assert nodes[1].childNodes[0].nodeValue == 'x'
+        assert nodes[2].childNodes[0].nodeValue == '1'
+
+    mml_2 = mp._print(x**2)
+    assert mml_2.nodeName == 'apply'
+    nodes = mml_2.childNodes
+    assert nodes[1].childNodes[0].nodeValue == 'x'
+    assert nodes[2].childNodes[0].nodeValue == '2'
+
+    mml_3 = mp._print(2*x)
+    assert mml_3.nodeName == 'apply'
+    nodes = mml_3.childNodes
+    assert nodes[0].nodeName == 'times'
+    assert nodes[1].childNodes[0].nodeValue == '2'
+    assert nodes[2].childNodes[0].nodeValue == 'x'
+
+    mml = mp._print(Float(1.0, 2)*x)
+    assert mml.nodeName == 'apply'
+    nodes = mml.childNodes
+    assert nodes[0].nodeName == 'times'
+    assert nodes[1].childNodes[0].nodeValue == '1.0'
+    assert nodes[2].childNodes[0].nodeValue == 'x'
+
+
+def test_content_mathml_functions():
+    mml_1 = mp._print(sin(x))
+    assert mml_1.nodeName == 'apply'
+    assert mml_1.childNodes[0].nodeName == 'sin'
+    assert mml_1.childNodes[1].nodeName == 'ci'
+
+    mml_2 = mp._print(diff(sin(x), x, evaluate=False))
+    assert mml_2.nodeName == 'apply'
+    assert mml_2.childNodes[0].nodeName == 'diff'
+    assert mml_2.childNodes[1].nodeName == 'bvar'
+    assert mml_2.childNodes[1].childNodes[
+        0].nodeName == 'ci'  # below bvar there's x/ci>
+
+    mml_3 = mp._print(diff(cos(x*y), x, evaluate=False))
+    assert mml_3.nodeName == 'apply'
+    assert mml_3.childNodes[0].nodeName == 'partialdiff'
+    assert mml_3.childNodes[1].nodeName == 'bvar'
+    assert mml_3.childNodes[1].childNodes[
+        0].nodeName == 'ci'  # below bvar there's x/ci>
+
+    mml_4 = mp._print(Lambda((x, y), x * y))
+    assert mml_4.nodeName == 'lambda'
+    assert mml_4.childNodes[0].nodeName == 'bvar'
+    assert mml_4.childNodes[0].childNodes[
+        0].nodeName == 'ci'  # below bvar there's x/ci>
+    assert mml_4.childNodes[1].nodeName == 'bvar'
+    assert mml_4.childNodes[1].childNodes[
+        0].nodeName == 'ci'  # below bvar there's y/ci>
+    assert mml_4.childNodes[2].nodeName == 'apply'
+
+
+def test_content_mathml_limits():
+    # XXX No unevaluated limits
+    lim_fun = sin(x)/x
+    mml_1 = mp._print(Limit(lim_fun, x, 0))
+    assert mml_1.childNodes[0].nodeName == 'limit'
+    assert mml_1.childNodes[1].nodeName == 'bvar'
+    assert mml_1.childNodes[2].nodeName == 'lowlimit'
+    assert mml_1.childNodes[3].toxml() == mp._print(lim_fun).toxml()
+
+
+def test_content_mathml_integrals():
+    integrand = x
+    mml_1 = mp._print(Integral(integrand, (x, 0, 1)))
+    assert mml_1.childNodes[0].nodeName == 'int'
+    assert mml_1.childNodes[1].nodeName == 'bvar'
+    assert mml_1.childNodes[2].nodeName == 'lowlimit'
+    assert mml_1.childNodes[3].nodeName == 'uplimit'
+    assert mml_1.childNodes[4].toxml() == mp._print(integrand).toxml()
+
+
+def test_content_mathml_matrices():
+    A = Matrix([1, 2, 3])
+    B = Matrix([[0, 5, 4], [2, 3, 1], [9, 7, 9]])
+    mll_1 = mp._print(A)
+    assert mll_1.childNodes[0].nodeName == 'matrixrow'
+    assert mll_1.childNodes[0].childNodes[0].nodeName == 'cn'
+    assert mll_1.childNodes[0].childNodes[0].childNodes[0].nodeValue == '1'
+    assert mll_1.childNodes[1].nodeName == 'matrixrow'
+    assert mll_1.childNodes[1].childNodes[0].nodeName == 'cn'
+    assert mll_1.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2'
+    assert mll_1.childNodes[2].nodeName == 'matrixrow'
+    assert mll_1.childNodes[2].childNodes[0].nodeName == 'cn'
+    assert mll_1.childNodes[2].childNodes[0].childNodes[0].nodeValue == '3'
+    mll_2 = mp._print(B)
+    assert mll_2.childNodes[0].nodeName == 'matrixrow'
+    assert mll_2.childNodes[0].childNodes[0].nodeName == 'cn'
+    assert mll_2.childNodes[0].childNodes[0].childNodes[0].nodeValue == '0'
+    assert mll_2.childNodes[0].childNodes[1].nodeName == 'cn'
+    assert mll_2.childNodes[0].childNodes[1].childNodes[0].nodeValue == '5'
+    assert mll_2.childNodes[0].childNodes[2].nodeName == 'cn'
+    assert mll_2.childNodes[0].childNodes[2].childNodes[0].nodeValue == '4'
+    assert mll_2.childNodes[1].nodeName == 'matrixrow'
+    assert mll_2.childNodes[1].childNodes[0].nodeName == 'cn'
+    assert mll_2.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2'
+    assert mll_2.childNodes[1].childNodes[1].nodeName == 'cn'
+    assert mll_2.childNodes[1].childNodes[1].childNodes[0].nodeValue == '3'
+    assert mll_2.childNodes[1].childNodes[2].nodeName == 'cn'
+    assert mll_2.childNodes[1].childNodes[2].childNodes[0].nodeValue == '1'
+    assert mll_2.childNodes[2].nodeName == 'matrixrow'
+    assert mll_2.childNodes[2].childNodes[0].nodeName == 'cn'
+    assert mll_2.childNodes[2].childNodes[0].childNodes[0].nodeValue == '9'
+    assert mll_2.childNodes[2].childNodes[1].nodeName == 'cn'
+    assert mll_2.childNodes[2].childNodes[1].childNodes[0].nodeValue == '7'
+    assert mll_2.childNodes[2].childNodes[2].nodeName == 'cn'
+    assert mll_2.childNodes[2].childNodes[2].childNodes[0].nodeValue == '9'
+
+
+def test_content_mathml_sums():
+    summand = x
+    mml_1 = mp._print(Sum(summand, (x, 1, 10)))
+    assert mml_1.childNodes[0].nodeName == 'sum'
+    assert mml_1.childNodes[1].nodeName == 'bvar'
+    assert mml_1.childNodes[2].nodeName == 'lowlimit'
+    assert mml_1.childNodes[3].nodeName == 'uplimit'
+    assert mml_1.childNodes[4].toxml() == mp._print(summand).toxml()
+
+
+def test_content_mathml_tuples():
+    mml_1 = mp._print([2])
+    assert mml_1.nodeName == 'list'
+    assert mml_1.childNodes[0].nodeName == 'cn'
+    assert len(mml_1.childNodes) == 1
+
+    mml_2 = mp._print([2, Integer(1)])
+    assert mml_2.nodeName == 'list'
+    assert mml_2.childNodes[0].nodeName == 'cn'
+    assert mml_2.childNodes[1].nodeName == 'cn'
+    assert len(mml_2.childNodes) == 2
+
+
+def test_content_mathml_add():
+    mml = mp._print(x**5 - x**4 + x)
+    assert mml.childNodes[0].nodeName == 'plus'
+    assert mml.childNodes[1].childNodes[0].nodeName == 'minus'
+    assert mml.childNodes[1].childNodes[1].nodeName == 'apply'
+
+
+def test_content_mathml_Rational():
+    mml_1 = mp._print(Rational(1, 1))
+    """should just return a number"""
+    assert mml_1.nodeName == 'cn'
+
+    mml_2 = mp._print(Rational(2, 5))
+    assert mml_2.childNodes[0].nodeName == 'divide'
+
+
+def test_content_mathml_constants():
+    mml = mp._print(I)
+    assert mml.nodeName == 'imaginaryi'
+
+    mml = mp._print(E)
+    assert mml.nodeName == 'exponentiale'
+
+    mml = mp._print(oo)
+    assert mml.nodeName == 'infinity'
+
+    mml = mp._print(pi)
+    assert mml.nodeName == 'pi'
+
+    assert mathml(hbar) == ''
+    assert mathml(S.TribonacciConstant) == ''
+    assert mathml(S.GoldenRatio) == 'φ'
+    mml = mathml(S.EulerGamma)
+    assert mml == ''
+
+    mml = mathml(S.EmptySet)
+    assert mml == ''
+
+    mml = mathml(S.true)
+    assert mml == ''
+
+    mml = mathml(S.false)
+    assert mml == ''
+
+    mml = mathml(S.NaN)
+    assert mml == ''
+
+
+def test_content_mathml_trig():
+    mml = mp._print(sin(x))
+    assert mml.childNodes[0].nodeName == 'sin'
+
+    mml = mp._print(cos(x))
+    assert mml.childNodes[0].nodeName == 'cos'
+
+    mml = mp._print(tan(x))
+    assert mml.childNodes[0].nodeName == 'tan'
+
+    mml = mp._print(cot(x))
+    assert mml.childNodes[0].nodeName == 'cot'
+
+    mml = mp._print(csc(x))
+    assert mml.childNodes[0].nodeName == 'csc'
+
+    mml = mp._print(sec(x))
+    assert mml.childNodes[0].nodeName == 'sec'
+
+    mml = mp._print(asin(x))
+    assert mml.childNodes[0].nodeName == 'arcsin'
+
+    mml = mp._print(acos(x))
+    assert mml.childNodes[0].nodeName == 'arccos'
+
+    mml = mp._print(atan(x))
+    assert mml.childNodes[0].nodeName == 'arctan'
+
+    mml = mp._print(acot(x))
+    assert mml.childNodes[0].nodeName == 'arccot'
+
+    mml = mp._print(acsc(x))
+    assert mml.childNodes[0].nodeName == 'arccsc'
+
+    mml = mp._print(asec(x))
+    assert mml.childNodes[0].nodeName == 'arcsec'
+
+    mml = mp._print(sinh(x))
+    assert mml.childNodes[0].nodeName == 'sinh'
+
+    mml = mp._print(cosh(x))
+    assert mml.childNodes[0].nodeName == 'cosh'
+
+    mml = mp._print(tanh(x))
+    assert mml.childNodes[0].nodeName == 'tanh'
+
+    mml = mp._print(coth(x))
+    assert mml.childNodes[0].nodeName == 'coth'
+
+    mml = mp._print(csch(x))
+    assert mml.childNodes[0].nodeName == 'csch'
+
+    mml = mp._print(sech(x))
+    assert mml.childNodes[0].nodeName == 'sech'
+
+    mml = mp._print(asinh(x))
+    assert mml.childNodes[0].nodeName == 'arcsinh'
+
+    mml = mp._print(atanh(x))
+    assert mml.childNodes[0].nodeName == 'arctanh'
+
+    mml = mp._print(acosh(x))
+    assert mml.childNodes[0].nodeName == 'arccosh'
+
+    mml = mp._print(acoth(x))
+    assert mml.childNodes[0].nodeName == 'arccoth'
+
+    mml = mp._print(acsch(x))
+    assert mml.childNodes[0].nodeName == 'arccsch'
+
+    mml = mp._print(asech(x))
+    assert mml.childNodes[0].nodeName == 'arcsech'
+
+
+def test_content_mathml_relational():
+    mml_1 = mp._print(Eq(x, 1))
+    assert mml_1.nodeName == 'apply'
+    assert mml_1.childNodes[0].nodeName == 'eq'
+    assert mml_1.childNodes[1].nodeName == 'ci'
+    assert mml_1.childNodes[1].childNodes[0].nodeValue == 'x'
+    assert mml_1.childNodes[2].nodeName == 'cn'
+    assert mml_1.childNodes[2].childNodes[0].nodeValue == '1'
+
+    mml_2 = mp._print(Ne(1, x))
+    assert mml_2.nodeName == 'apply'
+    assert mml_2.childNodes[0].nodeName == 'neq'
+    assert mml_2.childNodes[1].nodeName == 'cn'
+    assert mml_2.childNodes[1].childNodes[0].nodeValue == '1'
+    assert mml_2.childNodes[2].nodeName == 'ci'
+    assert mml_2.childNodes[2].childNodes[0].nodeValue == 'x'
+
+    mml_3 = mp._print(Ge(1, x))
+    assert mml_3.nodeName == 'apply'
+    assert mml_3.childNodes[0].nodeName == 'geq'
+    assert mml_3.childNodes[1].nodeName == 'cn'
+    assert mml_3.childNodes[1].childNodes[0].nodeValue == '1'
+    assert mml_3.childNodes[2].nodeName == 'ci'
+    assert mml_3.childNodes[2].childNodes[0].nodeValue == 'x'
+
+    mml_4 = mp._print(Lt(1, x))
+    assert mml_4.nodeName == 'apply'
+    assert mml_4.childNodes[0].nodeName == 'lt'
+    assert mml_4.childNodes[1].nodeName == 'cn'
+    assert mml_4.childNodes[1].childNodes[0].nodeValue == '1'
+    assert mml_4.childNodes[2].nodeName == 'ci'
+    assert mml_4.childNodes[2].childNodes[0].nodeValue == 'x'
+
+
+def test_content_symbol():
+    mml = mp._print(x)
+    assert mml.nodeName == 'ci'
+    assert mml.childNodes[0].nodeValue == 'x'
+    del mml
+
+    mml = mp._print(Symbol("x^2"))
+    assert mml.nodeName == 'ci'
+    assert mml.childNodes[0].nodeName == 'mml:msup'
+    assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x'
+    assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2'
+    del mml
+
+    mml = mp._print(Symbol("x__2"))
+    assert mml.nodeName == 'ci'
+    assert mml.childNodes[0].nodeName == 'mml:msup'
+    assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x'
+    assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2'
+    del mml
+
+    mml = mp._print(Symbol("x_2"))
+    assert mml.nodeName == 'ci'
+    assert mml.childNodes[0].nodeName == 'mml:msub'
+    assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x'
+    assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2'
+    del mml
+
+    mml = mp._print(Symbol("x^3_2"))
+    assert mml.nodeName == 'ci'
+    assert mml.childNodes[0].nodeName == 'mml:msubsup'
+    assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x'
+    assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2'
+    assert mml.childNodes[0].childNodes[2].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[2].childNodes[0].nodeValue == '3'
+    del mml
+
+    mml = mp._print(Symbol("x__3_2"))
+    assert mml.nodeName == 'ci'
+    assert mml.childNodes[0].nodeName == 'mml:msubsup'
+    assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x'
+    assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2'
+    assert mml.childNodes[0].childNodes[2].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[2].childNodes[0].nodeValue == '3'
+    del mml
+
+    mml = mp._print(Symbol("x_2_a"))
+    assert mml.nodeName == 'ci'
+    assert mml.childNodes[0].nodeName == 'mml:msub'
+    assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x'
+    assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mrow'
+    assert mml.childNodes[0].childNodes[1].childNodes[0].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[1].childNodes[0].childNodes[
+        0].nodeValue == '2'
+    assert mml.childNodes[0].childNodes[1].childNodes[1].nodeName == 'mml:mo'
+    assert mml.childNodes[0].childNodes[1].childNodes[1].childNodes[
+        0].nodeValue == ' '
+    assert mml.childNodes[0].childNodes[1].childNodes[2].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[1].childNodes[2].childNodes[
+        0].nodeValue == 'a'
+    del mml
+
+    mml = mp._print(Symbol("x^2^a"))
+    assert mml.nodeName == 'ci'
+    assert mml.childNodes[0].nodeName == 'mml:msup'
+    assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x'
+    assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mrow'
+    assert mml.childNodes[0].childNodes[1].childNodes[0].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[1].childNodes[0].childNodes[
+        0].nodeValue == '2'
+    assert mml.childNodes[0].childNodes[1].childNodes[1].nodeName == 'mml:mo'
+    assert mml.childNodes[0].childNodes[1].childNodes[1].childNodes[
+        0].nodeValue == ' '
+    assert mml.childNodes[0].childNodes[1].childNodes[2].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[1].childNodes[2].childNodes[
+        0].nodeValue == 'a'
+    del mml
+
+    mml = mp._print(Symbol("x__2__a"))
+    assert mml.nodeName == 'ci'
+    assert mml.childNodes[0].nodeName == 'mml:msup'
+    assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x'
+    assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mrow'
+    assert mml.childNodes[0].childNodes[1].childNodes[0].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[1].childNodes[0].childNodes[
+        0].nodeValue == '2'
+    assert mml.childNodes[0].childNodes[1].childNodes[1].nodeName == 'mml:mo'
+    assert mml.childNodes[0].childNodes[1].childNodes[1].childNodes[
+        0].nodeValue == ' '
+    assert mml.childNodes[0].childNodes[1].childNodes[2].nodeName == 'mml:mi'
+    assert mml.childNodes[0].childNodes[1].childNodes[2].childNodes[
+        0].nodeValue == 'a'
+    del mml
+
+
+def test_content_mathml_greek():
+    mml = mp._print(Symbol('alpha'))
+    assert mml.nodeName == 'ci'
+    assert mml.childNodes[0].nodeValue == '\N{GREEK SMALL LETTER ALPHA}'
+
+    assert mp.doprint(Symbol('alpha')) == 'α'
+    assert mp.doprint(Symbol('beta')) == 'β'
+    assert mp.doprint(Symbol('gamma')) == 'γ'
+    assert mp.doprint(Symbol('delta')) == 'δ'
+    assert mp.doprint(Symbol('epsilon')) == 'ε'
+    assert mp.doprint(Symbol('zeta')) == 'ζ'
+    assert mp.doprint(Symbol('eta')) == 'η'
+    assert mp.doprint(Symbol('theta')) == 'θ'
+    assert mp.doprint(Symbol('iota')) == 'ι'
+    assert mp.doprint(Symbol('kappa')) == 'κ'
+    assert mp.doprint(Symbol('lambda')) == 'λ'
+    assert mp.doprint(Symbol('mu')) == 'μ'
+    assert mp.doprint(Symbol('nu')) == 'ν'
+    assert mp.doprint(Symbol('xi')) == 'ξ'
+    assert mp.doprint(Symbol('omicron')) == 'ο'
+    assert mp.doprint(Symbol('pi')) == 'π'
+    assert mp.doprint(Symbol('rho')) == 'ρ'
+    assert mp.doprint(Symbol('varsigma')) == 'ς'
+    assert mp.doprint(Symbol('sigma')) == 'σ'
+    assert mp.doprint(Symbol('tau')) == 'τ'
+    assert mp.doprint(Symbol('upsilon')) == 'υ'
+    assert mp.doprint(Symbol('phi')) == 'φ'
+    assert mp.doprint(Symbol('chi')) == 'χ'
+    assert mp.doprint(Symbol('psi')) == 'ψ'
+    assert mp.doprint(Symbol('omega')) == 'ω'
+
+    assert mp.doprint(Symbol('Alpha')) == 'Α'
+    assert mp.doprint(Symbol('Beta')) == 'Β'
+    assert mp.doprint(Symbol('Gamma')) == 'Γ'
+    assert mp.doprint(Symbol('Delta')) == 'Δ'
+    assert mp.doprint(Symbol('Epsilon')) == 'Ε'
+    assert mp.doprint(Symbol('Zeta')) == 'Ζ'
+    assert mp.doprint(Symbol('Eta')) == 'Η'
+    assert mp.doprint(Symbol('Theta')) == 'Θ'
+    assert mp.doprint(Symbol('Iota')) == 'Ι'
+    assert mp.doprint(Symbol('Kappa')) == 'Κ'
+    assert mp.doprint(Symbol('Lambda')) == 'Λ'
+    assert mp.doprint(Symbol('Mu')) == 'Μ'
+    assert mp.doprint(Symbol('Nu')) == 'Ν'
+    assert mp.doprint(Symbol('Xi')) == 'Ξ'
+    assert mp.doprint(Symbol('Omicron')) == 'Ο'
+    assert mp.doprint(Symbol('Pi')) == 'Π'
+    assert mp.doprint(Symbol('Rho')) == 'Ρ'
+    assert mp.doprint(Symbol('Sigma')) == 'Σ'
+    assert mp.doprint(Symbol('Tau')) == 'Τ'
+    assert mp.doprint(Symbol('Upsilon')) == 'Υ'
+    assert mp.doprint(Symbol('Phi')) == 'Φ'
+    assert mp.doprint(Symbol('Chi')) == 'Χ'
+    assert mp.doprint(Symbol('Psi')) == 'Ψ'
+    assert mp.doprint(Symbol('Omega')) == 'Ω'
+
+
+def test_content_mathml_order():
+    expr = x**3 + x**2*y + 3*x*y**3 + y**4
+
+    mp = MathMLContentPrinter({'order': 'lex'})
+    mml = mp._print(expr)
+
+    assert mml.childNodes[1].childNodes[0].nodeName == 'power'
+    assert mml.childNodes[1].childNodes[1].childNodes[0].data == 'x'
+    assert mml.childNodes[1].childNodes[2].childNodes[0].data == '3'
+
+    assert mml.childNodes[4].childNodes[0].nodeName == 'power'
+    assert mml.childNodes[4].childNodes[1].childNodes[0].data == 'y'
+    assert mml.childNodes[4].childNodes[2].childNodes[0].data == '4'
+
+    mp = MathMLContentPrinter({'order': 'rev-lex'})
+    mml = mp._print(expr)
+
+    assert mml.childNodes[1].childNodes[0].nodeName == 'power'
+    assert mml.childNodes[1].childNodes[1].childNodes[0].data == 'y'
+    assert mml.childNodes[1].childNodes[2].childNodes[0].data == '4'
+
+    assert mml.childNodes[4].childNodes[0].nodeName == 'power'
+    assert mml.childNodes[4].childNodes[1].childNodes[0].data == 'x'
+    assert mml.childNodes[4].childNodes[2].childNodes[0].data == '3'
+
+
+def test_content_settings():
+    raises(TypeError, lambda: mathml(x, method="garbage"))
+
+
+def test_content_mathml_logic():
+    assert mathml(And(x, y)) == 'xy'
+    assert mathml(Or(x, y)) == 'xy'
+    assert mathml(Xor(x, y)) == 'xy'
+    assert mathml(Implies(x, y)) == 'xy'
+    assert mathml(Not(x)) == 'x'
+
+
+def test_content_finite_sets():
+    assert mathml(FiniteSet(a)) == 'a'
+    assert mathml(FiniteSet(a, b)) == 'ab'
+    assert mathml(FiniteSet(FiniteSet(a, b), c)) == \
+        'cab'
+
+    A = FiniteSet(a)
+    B = FiniteSet(b)
+    C = FiniteSet(c)
+    D = FiniteSet(d)
+
+    U1 = Union(A, B, evaluate=False)
+    U2 = Union(C, D, evaluate=False)
+    I1 = Intersection(A, B, evaluate=False)
+    I2 = Intersection(C, D, evaluate=False)
+    C1 = Complement(A, B, evaluate=False)
+    C2 = Complement(C, D, evaluate=False)
+    # XXX ProductSet does not support evaluate keyword
+    P1 = ProductSet(A, B)
+    P2 = ProductSet(C, D)
+
+    assert mathml(U1) == \
+        'ab'
+    assert mathml(I1) == \
+        'ab' \
+        ''
+    assert mathml(C1) == \
+        'ab'
+    assert mathml(P1) == \
+        'ab' \
+        ''
+
+    assert mathml(Intersection(A, U2, evaluate=False)) == \
+        'a' \
+        'cd'
+    assert mathml(Intersection(U1, U2, evaluate=False)) == \
+        'a' \
+        'bc' \
+        'd'
+
+    # XXX Does the parenthesis appear correctly for these examples in mathjax?
+    assert mathml(Intersection(C1, C2, evaluate=False)) == \
+        'a' \
+        'bc' \
+        'd'
+    assert mathml(Intersection(P1, P2, evaluate=False)) == \
+        'a' \
+        'b' \
+        'cd'
+
+    assert mathml(Union(A, I2, evaluate=False)) == \
+        'a' \
+        'cd'
+    assert mathml(Union(I1, I2, evaluate=False)) == \
+        'a' \
+        'bc' \
+        'd'
+    assert mathml(Union(C1, C2, evaluate=False)) == \
+        'a' \
+        'bc' \
+        'd'
+    assert mathml(Union(P1, P2, evaluate=False)) == \
+        'a' \
+        'b' \
+        'cd'
+
+    assert mathml(Complement(A, C2, evaluate=False)) == \
+        'a' \
+        'cd'
+    assert mathml(Complement(U1, U2, evaluate=False)) == \
+        'a' \
+        'bc' \
+        'd'
+    assert mathml(Complement(I1, I2, evaluate=False)) == \
+        'a' \
+        'bc' \
+        'd'
+    assert mathml(Complement(P1, P2, evaluate=False)) == \
+        'a' \
+        'b' \
+        'cd'
+
+    assert mathml(ProductSet(A, P2)) == \
+        'a' \
+        'c' \
+        'd'
+    assert mathml(ProductSet(U1, U2)) == \
+        'a' \
+        'bc' \
+        'd'
+    assert mathml(ProductSet(I1, I2)) == \
+        'a' \
+        'b' \
+        'cd'
+    assert mathml(ProductSet(C1, C2)) == \
+        'a' \
+        'b' \
+        'cd'
+
+
+def test_presentation_printmethod():
+    assert mpp.doprint(1 + x) == 'x+1'
+    assert mpp.doprint(x**2) == 'x2'
+    assert mpp.doprint(x**-1) == '1x'
+    assert mpp.doprint(x**-2) == \
+        '1x2'
+    assert mpp.doprint(2*x) == \
+        '2x'
+
+
+def test_presentation_mathml_core():
+    mml_1 = mpp._print(1 + x)
+    assert mml_1.nodeName == 'mrow'
+    nodes = mml_1.childNodes
+    assert len(nodes) == 3
+    assert nodes[0].nodeName in ['mi', 'mn']
+    assert nodes[1].nodeName == 'mo'
+    if nodes[0].nodeName == 'mn':
+        assert nodes[0].childNodes[0].nodeValue == '1'
+        assert nodes[2].childNodes[0].nodeValue == 'x'
+    else:
+        assert nodes[0].childNodes[0].nodeValue == 'x'
+        assert nodes[2].childNodes[0].nodeValue == '1'
+
+    mml_2 = mpp._print(x**2)
+    assert mml_2.nodeName == 'msup'
+    nodes = mml_2.childNodes
+    assert nodes[0].childNodes[0].nodeValue == 'x'
+    assert nodes[1].childNodes[0].nodeValue == '2'
+
+    mml_3 = mpp._print(2*x)
+    assert mml_3.nodeName == 'mrow'
+    nodes = mml_3.childNodes
+    assert nodes[0].childNodes[0].nodeValue == '2'
+    assert nodes[1].childNodes[0].nodeValue == '⁢'
+    assert nodes[2].childNodes[0].nodeValue == 'x'
+
+    mml = mpp._print(Float(1.0, 2)*x)
+    assert mml.nodeName == 'mrow'
+    nodes = mml.childNodes
+    assert nodes[0].childNodes[0].nodeValue == '1.0'
+    assert nodes[1].childNodes[0].nodeValue == '⁢'
+    assert nodes[2].childNodes[0].nodeValue == 'x'
+
+
+def test_presentation_mathml_functions():
+    mml_1 = mpp._print(sin(x))
+    assert mml_1.childNodes[0].childNodes[0
+        ].nodeValue == 'sin'
+    assert mml_1.childNodes[1].childNodes[1
+        ].childNodes[0].nodeValue == 'x'
+
+    mml_2 = mpp._print(diff(sin(x), x, evaluate=False))
+    assert mml_2.nodeName == 'mrow'
+    assert mml_2.childNodes[0].childNodes[0
+        ].childNodes[0].childNodes[0].nodeValue == 'ⅆ'
+    assert mml_2.childNodes[1].childNodes[1
+        ].nodeName == 'mrow'
+    assert mml_2.childNodes[0].childNodes[1
+        ].childNodes[0].childNodes[0].nodeValue == 'ⅆ'
+
+    mml_3 = mpp._print(diff(cos(x*y), x, evaluate=False))
+    assert mml_3.childNodes[0].nodeName == 'mfrac'
+    assert mml_3.childNodes[0].childNodes[0
+        ].childNodes[0].childNodes[0].nodeValue == '∂'
+    assert mml_3.childNodes[1].childNodes[0
+        ].childNodes[0].nodeValue == 'cos'
+
+
+def test_print_derivative():
+    f = Function('f')
+    d = Derivative(f(x, y, z), x, z, x, z, z, y)
+    assert mathml(d) == \
+        'yz2xzxxyz'
+    assert mathml(d, printer='presentation') == \
+        '6y2zxzxf(x,y,z)'
+
+
+def test_presentation_mathml_limits():
+    lim_fun = sin(x)/x
+    mml_1 = mpp._print(Limit(lim_fun, x, 0))
+    assert mml_1.childNodes[0].nodeName == 'munder'
+    assert mml_1.childNodes[0].childNodes[0
+        ].childNodes[0].nodeValue == 'lim'
+    assert mml_1.childNodes[0].childNodes[1
+        ].childNodes[0].childNodes[0
+        ].nodeValue == 'x'
+    assert mml_1.childNodes[0].childNodes[1
+        ].childNodes[1].childNodes[0
+        ].nodeValue == '→'
+    assert mml_1.childNodes[0].childNodes[1
+        ].childNodes[2].childNodes[0
+        ].nodeValue == '0'
+
+
+def test_presentation_mathml_integrals():
+    assert mpp.doprint(Integral(x, (x, 0, 1))) == \
+        '01'\
+        'xx'
+    assert mpp.doprint(Integral(log(x), x)) == \
+        'log(x' \
+        ')x'
+    assert mpp.doprint(Integral(x*y, x, y)) == \
+        'x'\
+        'yyx'
+    z, w = symbols('z w')
+    assert mpp.doprint(Integral(x*y*z, x, y, z)) == \
+        'x'\
+        'yz'\
+        'zyx'
+    assert mpp.doprint(Integral(x*y*z*w, x, y, z, w)) == \
+        ''\
+        'w'\
+        'xy'\
+        'zw'\
+        'zyx'
+    assert mpp.doprint(Integral(x, x, y, (z, 0, 1))) == \
+        '01'\
+        'xz'\
+        'yx'
+    assert mpp.doprint(Integral(x, (x, 0))) == \
+        '0x'\
+        'x'
+
+
+def test_presentation_mathml_matrices():
+    A = Matrix([1, 2, 3])
+    B = Matrix([[0, 5, 4], [2, 3, 1], [9, 7, 9]])
+    mll_1 = mpp._print(A)
+    assert mll_1.childNodes[1].nodeName == 'mtable'
+    assert mll_1.childNodes[1].childNodes[0].nodeName == 'mtr'
+    assert len(mll_1.childNodes[1].childNodes) == 3
+    assert mll_1.childNodes[1].childNodes[0].childNodes[0].nodeName == 'mtd'
+    assert len(mll_1.childNodes[1].childNodes[0].childNodes) == 1
+    assert mll_1.childNodes[1].childNodes[0].childNodes[0
+        ].childNodes[0].childNodes[0].nodeValue == '1'
+    assert mll_1.childNodes[1].childNodes[1].childNodes[0
+        ].childNodes[0].childNodes[0].nodeValue == '2'
+    assert mll_1.childNodes[1].childNodes[2].childNodes[0
+        ].childNodes[0].childNodes[0].nodeValue == '3'
+    mll_2 = mpp._print(B)
+    assert mll_2.childNodes[1].nodeName == 'mtable'
+    assert mll_2.childNodes[1].childNodes[0].nodeName == 'mtr'
+    assert len(mll_2.childNodes[1].childNodes) == 3
+    assert mll_2.childNodes[1].childNodes[0].childNodes[0].nodeName == 'mtd'
+    assert len(mll_2.childNodes[1].childNodes[0].childNodes) == 3
+    assert mll_2.childNodes[1].childNodes[0].childNodes[0
+        ].childNodes[0].childNodes[0].nodeValue == '0'
+    assert mll_2.childNodes[1].childNodes[0].childNodes[1
+        ].childNodes[0].childNodes[0].nodeValue == '5'
+    assert mll_2.childNodes[1].childNodes[0].childNodes[2
+        ].childNodes[0].childNodes[0].nodeValue == '4'
+    assert mll_2.childNodes[1].childNodes[1].childNodes[0
+        ].childNodes[0].childNodes[0].nodeValue == '2'
+    assert mll_2.childNodes[1].childNodes[1].childNodes[1
+        ].childNodes[0].childNodes[0].nodeValue == '3'
+    assert mll_2.childNodes[1].childNodes[1].childNodes[2
+        ].childNodes[0].childNodes[0].nodeValue == '1'
+    assert mll_2.childNodes[1].childNodes[2].childNodes[0
+        ].childNodes[0].childNodes[0].nodeValue == '9'
+    assert mll_2.childNodes[1].childNodes[2].childNodes[1
+        ].childNodes[0].childNodes[0].nodeValue == '7'
+    assert mll_2.childNodes[1].childNodes[2].childNodes[2
+        ].childNodes[0].childNodes[0].nodeValue == '9'
+
+
+def test_presentation_mathml_sums():
+    mml_1 = mpp._print(Sum(x, (x, 1, 10)))
+    assert mml_1.childNodes[0].nodeName == 'munderover'
+    assert len(mml_1.childNodes[0].childNodes) == 3
+    assert mml_1.childNodes[0].childNodes[0].childNodes[0
+        ].nodeValue == '∑'
+    assert len(mml_1.childNodes[0].childNodes[1].childNodes) == 3
+    assert mml_1.childNodes[0].childNodes[2].childNodes[0
+        ].nodeValue == '10'
+    assert mml_1.childNodes[1].childNodes[0].nodeValue == 'x'
+
+    assert mpp.doprint(Sum(x, (x, 1, 10))) == \
+        'x=110x'
+    assert mpp.doprint(Sum(x + y, (x, 1, 10))) == \
+        'x=110(x+y)'
+
+
+def test_presentation_mathml_add():
+    mml = mpp._print(x**5 - x**4 + x)
+    assert len(mml.childNodes) == 5
+    assert mml.childNodes[0].childNodes[0].childNodes[0
+        ].nodeValue == 'x'
+    assert mml.childNodes[0].childNodes[1].childNodes[0
+        ].nodeValue == '5'
+    assert mml.childNodes[1].childNodes[0].nodeValue == '-'
+    assert mml.childNodes[2].childNodes[0].childNodes[0
+        ].nodeValue == 'x'
+    assert mml.childNodes[2].childNodes[1].childNodes[0
+        ].nodeValue == '4'
+    assert mml.childNodes[3].childNodes[0].nodeValue == '+'
+    assert mml.childNodes[4].childNodes[0].nodeValue == 'x'
+
+
+def test_presentation_mathml_Rational():
+    mml_1 = mpp._print(Rational(1, 1))
+    assert mml_1.nodeName == 'mn'
+
+    mml_2 = mpp._print(Rational(2, 5))
+    assert mml_2.nodeName == 'mfrac'
+    assert mml_2.childNodes[0].childNodes[0].nodeValue == '2'
+    assert mml_2.childNodes[1].childNodes[0].nodeValue == '5'
+
+
+def test_presentation_mathml_constants():
+    mml = mpp._print(I)
+    assert mml.childNodes[0].nodeValue == 'ⅈ'
+
+    mml = mpp._print(E)
+    assert mml.childNodes[0].nodeValue == 'ⅇ'
+
+    mml = mpp._print(oo)
+    assert mml.childNodes[0].nodeValue == '∞'
+
+    mml = mpp._print(pi)
+    assert mml.childNodes[0].nodeValue == 'π'
+
+    assert mathml(hbar, printer='presentation') == ''
+    assert mathml(S.TribonacciConstant, printer='presentation'
+        ) == 'TribonacciConstant'
+    assert mathml(S.EulerGamma, printer='presentation'
+        ) == 'γ'
+    assert mathml(S.GoldenRatio, printer='presentation'
+        ) == 'Φ'
+
+    assert mathml(zoo, printer='presentation') == \
+        '~'
+
+    assert mathml(S.NaN, printer='presentation') == 'NaN'
+
+def test_presentation_mathml_trig():
+    mml = mpp._print(sin(x))
+    assert mml.childNodes[0].childNodes[0].nodeValue == 'sin'
+
+    mml = mpp._print(cos(x))
+    assert mml.childNodes[0].childNodes[0].nodeValue == 'cos'
+
+    mml = mpp._print(tan(x))
+    assert mml.childNodes[0].childNodes[0].nodeValue == 'tan'
+
+    mml = mpp._print(asin(x))
+    assert mml.childNodes[0].childNodes[0].nodeValue == 'arcsin'
+
+    mml = mpp._print(acos(x))
+    assert mml.childNodes[0].childNodes[0].nodeValue == 'arccos'
+
+    mml = mpp._print(atan(x))
+    assert mml.childNodes[0].childNodes[0].nodeValue == 'arctan'
+
+    mml = mpp._print(sinh(x))
+    assert mml.childNodes[0].childNodes[0].nodeValue == 'sinh'
+
+    mml = mpp._print(cosh(x))
+    assert mml.childNodes[0].childNodes[0].nodeValue == 'cosh'
+
+    mml = mpp._print(tanh(x))
+    assert mml.childNodes[0].childNodes[0].nodeValue == 'tanh'
+
+    mml = mpp._print(asinh(x))
+    assert mml.childNodes[0].childNodes[0].nodeValue == 'arcsinh'
+
+    mml = mpp._print(atanh(x))
+    assert mml.childNodes[0].childNodes[0].nodeValue == 'arctanh'
+
+    mml = mpp._print(acosh(x))
+    assert mml.childNodes[0].childNodes[0].nodeValue == 'arccosh'
+
+
+def test_presentation_mathml_relational():
+    mml_1 = mpp._print(Eq(x, 1))
+    assert len(mml_1.childNodes) == 3
+    assert mml_1.childNodes[0].nodeName == 'mi'
+    assert mml_1.childNodes[0].childNodes[0].nodeValue == 'x'
+    assert mml_1.childNodes[1].nodeName == 'mo'
+    assert mml_1.childNodes[1].childNodes[0].nodeValue == '='
+    assert mml_1.childNodes[2].nodeName == 'mn'
+    assert mml_1.childNodes[2].childNodes[0].nodeValue == '1'
+
+    mml_2 = mpp._print(Ne(1, x))
+    assert len(mml_2.childNodes) == 3
+    assert mml_2.childNodes[0].nodeName == 'mn'
+    assert mml_2.childNodes[0].childNodes[0].nodeValue == '1'
+    assert mml_2.childNodes[1].nodeName == 'mo'
+    assert mml_2.childNodes[1].childNodes[0].nodeValue == '≠'
+    assert mml_2.childNodes[2].nodeName == 'mi'
+    assert mml_2.childNodes[2].childNodes[0].nodeValue == 'x'
+
+    mml_3 = mpp._print(Ge(1, x))
+    assert len(mml_3.childNodes) == 3
+    assert mml_3.childNodes[0].nodeName == 'mn'
+    assert mml_3.childNodes[0].childNodes[0].nodeValue == '1'
+    assert mml_3.childNodes[1].nodeName == 'mo'
+    assert mml_3.childNodes[1].childNodes[0].nodeValue == '≥'
+    assert mml_3.childNodes[2].nodeName == 'mi'
+    assert mml_3.childNodes[2].childNodes[0].nodeValue == 'x'
+
+    mml_4 = mpp._print(Lt(1, x))
+    assert len(mml_4.childNodes) == 3
+    assert mml_4.childNodes[0].nodeName == 'mn'
+    assert mml_4.childNodes[0].childNodes[0].nodeValue == '1'
+    assert mml_4.childNodes[1].nodeName == 'mo'
+    assert mml_4.childNodes[1].childNodes[0].nodeValue == '<'
+    assert mml_4.childNodes[2].nodeName == 'mi'
+    assert mml_4.childNodes[2].childNodes[0].nodeValue == 'x'
+
+
+def test_presentation_symbol():
+    mml = mpp._print(x)
+    assert mml.nodeName == 'mi'
+    assert mml.childNodes[0].nodeValue == 'x'
+    del mml
+
+    mml = mpp._print(Symbol("x^2"))
+    assert mml.nodeName == 'msup'
+    assert mml.childNodes[0].nodeName == 'mi'
+    assert mml.childNodes[0].childNodes[0].nodeValue == 'x'
+    assert mml.childNodes[1].nodeName == 'mi'
+    assert mml.childNodes[1].childNodes[0].nodeValue == '2'
+    del mml
+
+    mml = mpp._print(Symbol("x__2"))
+    assert mml.nodeName == 'msup'
+    assert mml.childNodes[0].nodeName == 'mi'
+    assert mml.childNodes[0].childNodes[0].nodeValue == 'x'
+    assert mml.childNodes[1].nodeName == 'mi'
+    assert mml.childNodes[1].childNodes[0].nodeValue == '2'
+    del mml
+
+    mml = mpp._print(Symbol("x_2"))
+    assert mml.nodeName == 'msub'
+    assert mml.childNodes[0].nodeName == 'mi'
+    assert mml.childNodes[0].childNodes[0].nodeValue == 'x'
+    assert mml.childNodes[1].nodeName == 'mi'
+    assert mml.childNodes[1].childNodes[0].nodeValue == '2'
+    del mml
+
+    mml = mpp._print(Symbol("x^3_2"))
+    assert mml.nodeName == 'msubsup'
+    assert mml.childNodes[0].nodeName == 'mi'
+    assert mml.childNodes[0].childNodes[0].nodeValue == 'x'
+    assert mml.childNodes[1].nodeName == 'mi'
+    assert mml.childNodes[1].childNodes[0].nodeValue == '2'
+    assert mml.childNodes[2].nodeName == 'mi'
+    assert mml.childNodes[2].childNodes[0].nodeValue == '3'
+    del mml
+
+    mml = mpp._print(Symbol("x__3_2"))
+    assert mml.nodeName == 'msubsup'
+    assert mml.childNodes[0].nodeName == 'mi'
+    assert mml.childNodes[0].childNodes[0].nodeValue == 'x'
+    assert mml.childNodes[1].nodeName == 'mi'
+    assert mml.childNodes[1].childNodes[0].nodeValue == '2'
+    assert mml.childNodes[2].nodeName == 'mi'
+    assert mml.childNodes[2].childNodes[0].nodeValue == '3'
+    del mml
+
+    mml = mpp._print(Symbol("x_2_a"))
+    assert mml.nodeName == 'msub'
+    assert mml.childNodes[0].nodeName == 'mi'
+    assert mml.childNodes[0].childNodes[0].nodeValue == 'x'
+    assert mml.childNodes[1].nodeName == 'mrow'
+    assert mml.childNodes[1].childNodes[0].nodeName == 'mi'
+    assert mml.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2'
+    assert mml.childNodes[1].childNodes[1].nodeName == 'mo'
+    assert mml.childNodes[1].childNodes[1].childNodes[0].nodeValue == ' '
+    assert mml.childNodes[1].childNodes[2].nodeName == 'mi'
+    assert mml.childNodes[1].childNodes[2].childNodes[0].nodeValue == 'a'
+    del mml
+
+    mml = mpp._print(Symbol("x^2^a"))
+    assert mml.nodeName == 'msup'
+    assert mml.childNodes[0].nodeName == 'mi'
+    assert mml.childNodes[0].childNodes[0].nodeValue == 'x'
+    assert mml.childNodes[1].nodeName == 'mrow'
+    assert mml.childNodes[1].childNodes[0].nodeName == 'mi'
+    assert mml.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2'
+    assert mml.childNodes[1].childNodes[1].nodeName == 'mo'
+    assert mml.childNodes[1].childNodes[1].childNodes[0].nodeValue == ' '
+    assert mml.childNodes[1].childNodes[2].nodeName == 'mi'
+    assert mml.childNodes[1].childNodes[2].childNodes[0].nodeValue == 'a'
+    del mml
+
+    mml = mpp._print(Symbol("x__2__a"))
+    assert mml.nodeName == 'msup'
+    assert mml.childNodes[0].nodeName == 'mi'
+    assert mml.childNodes[0].childNodes[0].nodeValue == 'x'
+    assert mml.childNodes[1].nodeName == 'mrow'
+    assert mml.childNodes[1].childNodes[0].nodeName == 'mi'
+    assert mml.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2'
+    assert mml.childNodes[1].childNodes[1].nodeName == 'mo'
+    assert mml.childNodes[1].childNodes[1].childNodes[0].nodeValue == ' '
+    assert mml.childNodes[1].childNodes[2].nodeName == 'mi'
+    assert mml.childNodes[1].childNodes[2].childNodes[0].nodeValue == 'a'
+    del mml
+
+
+def test_presentation_mathml_greek():
+    mml = mpp._print(Symbol('alpha'))
+    assert mml.nodeName == 'mi'
+    assert mml.childNodes[0].nodeValue == '\N{GREEK SMALL LETTER ALPHA}'
+
+    assert mpp.doprint(Symbol('alpha')) == 'α'
+    assert mpp.doprint(Symbol('beta')) == 'β'
+    assert mpp.doprint(Symbol('gamma')) == 'γ'
+    assert mpp.doprint(Symbol('delta')) == 'δ'
+    assert mpp.doprint(Symbol('epsilon')) == 'ε'
+    assert mpp.doprint(Symbol('zeta')) == 'ζ'
+    assert mpp.doprint(Symbol('eta')) == 'η'
+    assert mpp.doprint(Symbol('theta')) == 'θ'
+    assert mpp.doprint(Symbol('iota')) == 'ι'
+    assert mpp.doprint(Symbol('kappa')) == 'κ'
+    assert mpp.doprint(Symbol('lambda')) == 'λ'
+    assert mpp.doprint(Symbol('mu')) == 'μ'
+    assert mpp.doprint(Symbol('nu')) == 'ν'
+    assert mpp.doprint(Symbol('xi')) == 'ξ'
+    assert mpp.doprint(Symbol('omicron')) == 'ο'
+    assert mpp.doprint(Symbol('pi')) == 'π'
+    assert mpp.doprint(Symbol('rho')) == 'ρ'
+    assert mpp.doprint(Symbol('varsigma')) == 'ς'
+    assert mpp.doprint(Symbol('sigma')) == 'σ'
+    assert mpp.doprint(Symbol('tau')) == 'τ'
+    assert mpp.doprint(Symbol('upsilon')) == 'υ'
+    assert mpp.doprint(Symbol('phi')) == 'φ'
+    assert mpp.doprint(Symbol('chi')) == 'χ'
+    assert mpp.doprint(Symbol('psi')) == 'ψ'
+    assert mpp.doprint(Symbol('omega')) == 'ω'
+
+    assert mpp.doprint(Symbol('Alpha')) == 'Α'
+    assert mpp.doprint(Symbol('Beta')) == 'Β'
+    assert mpp.doprint(Symbol('Gamma')) == 'Γ'
+    assert mpp.doprint(Symbol('Delta')) == 'Δ'
+    assert mpp.doprint(Symbol('Epsilon')) == 'Ε'
+    assert mpp.doprint(Symbol('Zeta')) == 'Ζ'
+    assert mpp.doprint(Symbol('Eta')) == 'Η'
+    assert mpp.doprint(Symbol('Theta')) == 'Θ'
+    assert mpp.doprint(Symbol('Iota')) == 'Ι'
+    assert mpp.doprint(Symbol('Kappa')) == 'Κ'
+    assert mpp.doprint(Symbol('Lambda')) == 'Λ'
+    assert mpp.doprint(Symbol('Mu')) == 'Μ'
+    assert mpp.doprint(Symbol('Nu')) == 'Ν'
+    assert mpp.doprint(Symbol('Xi')) == 'Ξ'
+    assert mpp.doprint(Symbol('Omicron')) == 'Ο'
+    assert mpp.doprint(Symbol('Pi')) == 'Π'
+    assert mpp.doprint(Symbol('Rho')) == 'Ρ'
+    assert mpp.doprint(Symbol('Sigma')) == 'Σ'
+    assert mpp.doprint(Symbol('Tau')) == 'Τ'
+    assert mpp.doprint(Symbol('Upsilon')) == 'Υ'
+    assert mpp.doprint(Symbol('Phi')) == 'Φ'
+    assert mpp.doprint(Symbol('Chi')) == 'Χ'
+    assert mpp.doprint(Symbol('Psi')) == 'Ψ'
+    assert mpp.doprint(Symbol('Omega')) == 'Ω'
+
+
+def test_presentation_mathml_order():
+    expr = x**3 + x**2*y + 3*x*y**3 + y**4
+
+    mp = MathMLPresentationPrinter({'order': 'lex'})
+    mml = mp._print(expr)
+    assert mml.childNodes[0].nodeName == 'msup'
+    assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x'
+    assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '3'
+
+    assert mml.childNodes[6].nodeName == 'msup'
+    assert mml.childNodes[6].childNodes[0].childNodes[0].nodeValue == 'y'
+    assert mml.childNodes[6].childNodes[1].childNodes[0].nodeValue == '4'
+
+    mp = MathMLPresentationPrinter({'order': 'rev-lex'})
+    mml = mp._print(expr)
+
+    assert mml.childNodes[0].nodeName == 'msup'
+    assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'y'
+    assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '4'
+
+    assert mml.childNodes[6].nodeName == 'msup'
+    assert mml.childNodes[6].childNodes[0].childNodes[0].nodeValue == 'x'
+    assert mml.childNodes[6].childNodes[1].childNodes[0].nodeValue == '3'
+
+
+def test_print_intervals():
+    a = Symbol('a', real=True)
+    assert mpp.doprint(Interval(0, a)) == \
+        '[0,a]'
+    assert mpp.doprint(Interval(0, a, False, False)) == \
+        '[0,a]'
+    assert mpp.doprint(Interval(0, a, True, False)) == \
+        '(0,a]'
+    assert mpp.doprint(Interval(0, a, False, True)) == \
+        '[0,a)'
+    assert mpp.doprint(Interval(0, a, True, True)) == \
+        '(0,a)'
+
+
+def test_print_tuples():
+    assert mpp.doprint(Tuple(0,)) == \
+        '(0)'
+    assert mpp.doprint(Tuple(0, a)) == \
+        '(0,a)'
+    assert mpp.doprint(Tuple(0, a, a)) == \
+        '(0,a,a)'
+    assert mpp.doprint(Tuple(0, 1, 2, 3, 4)) == \
+        '(0,1,2,3,4)'
+    assert mpp.doprint(Tuple(0, 1, Tuple(2, 3, 4))) == \
+        '(0,1,(2,3'\
+        ',4))'
+
+
+def test_print_re_im():
+    assert mpp.doprint(re(x)) == \
+        '(x)'
+    assert mpp.doprint(im(x)) == \
+        '(x)'
+    assert mpp.doprint(re(x + 1, evaluate=False)) == \
+        '(x+1)'
+    assert mpp.doprint(im(x + 1, evaluate=False)) == \
+        '(x+1)'
+
+
+def test_print_Abs():
+    assert mpp.doprint(Abs(x)) == \
+        '|x|'
+    assert mpp.doprint(Abs(x + 1)) == \
+        '|x+1|'
+
+
+def test_print_Determinant():
+    assert mpp.doprint(Determinant(Matrix([[1, 2], [3, 4]]))) == \
+        '|[1234]|'
+
+
+def test_presentation_settings():
+    raises(TypeError, lambda: mathml(x, printer='presentation',
+                                     method="garbage"))
+
+
+def test_print_domains():
+    from sympy.sets import Integers, Naturals, Naturals0, Reals, Complexes
+
+    assert mpp.doprint(Complexes) == ''
+    assert mpp.doprint(Integers) == ''
+    assert mpp.doprint(Naturals) == ''
+    assert mpp.doprint(Naturals0) == \
+        '0'
+    assert mpp.doprint(Reals) == ''
+
+
+def test_print_expression_with_minus():
+    assert mpp.doprint(-x) == '-x'
+    assert mpp.doprint(-x/y) == \
+        '-xy'
+    assert mpp.doprint(-Rational(1, 2)) == \
+        '-12'
+
+
+def test_print_AssocOp():
+    from sympy.core.operations import AssocOp
+
+    class TestAssocOp(AssocOp):
+        identity = 0
+
+    expr = TestAssocOp(1, 2)
+    assert mpp.doprint(expr) == \
+        'testassocop12'
+
+
+def test_print_basic():
+    expr = Basic(S(1), S(2))
+    assert mpp.doprint(expr) == \
+        'basic(1,2)'
+    assert mp.doprint(expr) == '12'
+
+
+def test_mat_delim_print():
+    expr = Matrix([[1, 2], [3, 4]])
+    assert mathml(expr, printer='presentation', mat_delim='[') == \
+        '[1'\
+        '234'\
+        ']'
+    assert mathml(expr, printer='presentation', mat_delim='(') == \
+        '(12'\
+        '34)'
+    assert mathml(expr, printer='presentation', mat_delim='') == \
+        '12'\
+        '34'
+
+
+def test_ln_notation_print():
+    expr = log(x)
+    assert mathml(expr, printer='presentation') == \
+        'log(x)'
+    assert mathml(expr, printer='presentation', ln_notation=False) == \
+        'log(x)'
+    assert mathml(expr, printer='presentation', ln_notation=True) == \
+        'ln(x)'
+
+
+def test_mul_symbol_print():
+    expr = x * y
+    assert mathml(expr, printer='presentation') == \
+        'xy'
+    assert mathml(expr, printer='presentation', mul_symbol=None) == \
+        'xy'
+    assert mathml(expr, printer='presentation', mul_symbol='dot') == \
+        'x·y'
+    assert mathml(expr, printer='presentation', mul_symbol='ldot') == \
+        'xy'
+    assert mathml(expr, printer='presentation', mul_symbol='times') == \
+        'x×y'
+
+
+def test_print_lerchphi():
+    assert mpp.doprint(lerchphi(1, 2, 3)) == \
+        'Φ(1,2,3)'
+
+
+def test_print_polylog():
+    assert mp.doprint(polylog(x, y)) == \
+        'xy'
+    assert mpp.doprint(polylog(x, y)) == \
+        'Lix(y)'
+
+
+def test_print_set_frozenset():
+    f = frozenset({1, 5, 3})
+    assert mpp.doprint(f) == \
+        '{1,3,5}'
+    s = set({1, 2, 3})
+    assert mpp.doprint(s) == \
+        '{1,2,3}'
+
+
+def test_print_FiniteSet():
+    f1 = FiniteSet(x, 1, 3)
+    assert mpp.doprint(f1) == \
+        '{1,3,x}'
+
+
+def test_print_LambertW():
+    assert mpp.doprint(LambertW(x)) == 'W(x)'
+    assert mpp.doprint(LambertW(x, y)) == 'W(x,y)'
+
+
+def test_print_EmptySet():
+    assert mpp.doprint(S.EmptySet) == ''
+
+
+def test_print_UniversalSet():
+    assert mpp.doprint(S.UniversalSet) == '𝕌'
+
+
+def test_print_spaces():
+    assert mpp.doprint(HilbertSpace()) == ''
+    assert mpp.doprint(ComplexSpace(2)) == '𝒞2'
+    assert mpp.doprint(FockSpace()) == ''
+
+
+def test_print_constants():
+    assert mpp.doprint(hbar) == ''
+    assert mpp.doprint(S.TribonacciConstant) == 'TribonacciConstant'
+    assert mpp.doprint(S.GoldenRatio) == 'Φ'
+    assert mpp.doprint(S.EulerGamma) == 'γ'
+
+
+def test_print_Contains():
+    assert mpp.doprint(Contains(x, S.Naturals)) == \
+        'x'
+
+
+def test_print_Dagger():
+    x = symbols('x', commutative=False)
+    assert mpp.doprint(Dagger(x)) == 'x'
+
+
+def test_print_SetOp():
+    f1 = FiniteSet(x, 1, 3)
+    f2 = FiniteSet(y, 2, 4)
+
+    prntr = lambda x: mathml(x, printer='presentation')
+
+    assert prntr(Union(f1, f2, evaluate=False)) == \
+    '{1,3,x'\
+    '}{2,'\
+    '4,y}'
+    assert prntr(Intersection(f1, f2, evaluate=False)) == \
+    '{1,3,x'\
+    '}{2'\
+    ',4,y}'
+    assert prntr(Complement(f1, f2, evaluate=False)) == \
+    '{1,3,x'\
+    '}{2'\
+    ',4,y}'
+    assert prntr(SymmetricDifference(f1, f2, evaluate=False)) == \
+    '{1,3,x'\
+    '}{2'\
+    ',4,y}'
+
+    A = FiniteSet(a)
+    C = FiniteSet(c)
+    D = FiniteSet(d)
+
+    U1 = Union(C, D, evaluate=False)
+    I1 = Intersection(C, D, evaluate=False)
+    C1 = Complement(C, D, evaluate=False)
+    D1 = SymmetricDifference(C, D, evaluate=False)
+    # XXX ProductSet does not support evaluate keyword
+    P1 = ProductSet(C, D)
+
+    assert prntr(Union(A, I1, evaluate=False)) == \
+        '{a}' \
+        '({' \
+        'c}{' \
+        'd})'
+    assert prntr(Intersection(A, C1, evaluate=False)) == \
+        '{a}' \
+        '({' \
+        'c}{' \
+        'd})'
+    assert prntr(Complement(A, D1, evaluate=False)) == \
+        '{a}' \
+        '({' \
+        'c}{' \
+        'd})'
+    assert prntr(SymmetricDifference(A, P1, evaluate=False)) == \
+        '{a}' \
+        '({' \
+        'c}×{' \
+        'd})'
+    assert prntr(ProductSet(A, U1)) == \
+        '{a}' \
+        '×({' \
+        'c}{' \
+        'd})'
+
+
+def test_print_logic():
+    assert mpp.doprint(And(x, y)) == \
+        'xy'
+    assert mpp.doprint(Or(x, y)) == \
+        'xy'
+    assert mpp.doprint(Xor(x, y)) == \
+        'xy'
+    assert mpp.doprint(Implies(x, y)) == \
+        'xy'
+    assert mpp.doprint(Equivalent(x, y)) == \
+        'xy'
+
+    assert mpp.doprint(And(Eq(x, y), x > 4)) == \
+        'x=y'\
+        'x>4'
+    assert mpp.doprint(And(Eq(x, 3), y < 3, x > y + 1)) == \
+        'x=3'\
+        'x>y+1'\
+        'y<3'
+    assert mpp.doprint(Or(Eq(x, y), x > 4)) == \
+        'x=y'\
+        'x>4'
+    assert mpp.doprint(And(Eq(x, 3), Or(y < 3, x > y + 1))) == \
+        'x=3'\
+        '(x>'\
+        'y+1'\
+        'y<3)'
+
+    assert mpp.doprint(Not(x)) == '¬x'
+    assert mpp.doprint(Not(And(x, y))) == \
+        '¬(xy)'
+
+
+def test_root_notation_print():
+    assert mathml(x**(S.One/3), printer='presentation') == \
+        'x3'
+    assert mathml(x**(S.One/3), printer='presentation', root_notation=False) ==\
+        'x13'
+    assert mathml(x**(S.One/3), printer='content') == \
+        '3x'
+    assert mathml(x**(S.One/3), printer='content', root_notation=False) == \
+        'x13'
+    assert mathml(x**(Rational(-1, 3)), printer='presentation') == \
+        '1x3'
+    assert mathml(x**(Rational(-1, 3)), printer='presentation', root_notation=False) \
+        == '1x13'
+
+
+def test_fold_frac_powers_print():
+    expr = x ** Rational(5, 2)
+    assert mathml(expr, printer='presentation') == \
+        'x52'
+    assert mathml(expr, printer='presentation', fold_frac_powers=True) == \
+        'x52'
+    assert mathml(expr, printer='presentation', fold_frac_powers=False) == \
+        'x52'
+
+
+def test_fold_short_frac_print():
+    expr = Rational(2, 5)
+    assert mathml(expr, printer='presentation') == \
+        '25'
+    assert mathml(expr, printer='presentation', fold_short_frac=True) == \
+        '25'
+    assert mathml(expr, printer='presentation', fold_short_frac=False) == \
+        '25'
+
+
+def test_print_factorials():
+    assert mpp.doprint(factorial(x)) == 'x!'
+    assert mpp.doprint(factorial(x + 1)) == \
+        '(x+1)!'
+    assert mpp.doprint(factorial2(x)) == 'x!!'
+    assert mpp.doprint(factorial2(x + 1)) == \
+        '(x+1)!!'
+    assert mpp.doprint(binomial(x, y)) == \
+        '(xy)'
+    assert mpp.doprint(binomial(4, x + y)) == \
+        '(4x'\
+        '+y)'
+
+
+def test_print_floor():
+    expr = floor(x)
+    assert mathml(expr, printer='presentation') == \
+        'x'
+
+
+def test_print_ceiling():
+    expr = ceiling(x)
+    assert mathml(expr, printer='presentation') == \
+        'x'
+
+
+def test_print_Lambda():
+    expr = Lambda(x, x+1)
+    assert mathml(expr, printer='presentation') == \
+        '(xx+1)'
+    expr = Lambda((x, y), x + y)
+    assert mathml(expr, printer='presentation') == \
+        '((x,y)x+y)'
+
+
+def test_print_conjugate():
+    assert mpp.doprint(conjugate(x)) == \
+        'x'
+    assert mpp.doprint(conjugate(x + 1)) == \
+        'x+1'
+
+
+def test_print_AccumBounds():
+    a = Symbol('a', real=True)
+    assert mpp.doprint(AccumBounds(0, 1)) == '0,1'
+    assert mpp.doprint(AccumBounds(0, a)) == '0,a'
+    assert mpp.doprint(AccumBounds(a + 1, a + 2)) == 'a+1,a+2'
+
+
+def test_print_Float():
+    assert mpp.doprint(Float(1e100)) == '1.0·10100'
+    assert mpp.doprint(Float(1e-100)) == '1.0·10-100'
+    assert mpp.doprint(Float(-1e100)) == '-1.0·10100'
+    assert mpp.doprint(Float(1.0*oo)) == ''
+    assert mpp.doprint(Float(-1.0*oo)) == '-'
+
+
+def test_print_different_functions():
+    assert mpp.doprint(gamma(x)) == 'Γ(x)'
+    assert mpp.doprint(lowergamma(x, y)) == 'γ(x,y)'
+    assert mpp.doprint(uppergamma(x, y)) == 'Γ(x,y)'
+    assert mpp.doprint(zeta(x)) == 'ζ(x)'
+    assert mpp.doprint(zeta(x, y)) == 'ζ(x,y)'
+    assert mpp.doprint(dirichlet_eta(x)) ==  'η(x)'
+    assert mpp.doprint(elliptic_k(x)) == 'Κ(x)'
+    assert mpp.doprint(totient(x)) == 'ϕ(x)'
+    assert mpp.doprint(reduced_totient(x)) == 'λ(x)'
+    assert mpp.doprint(primenu(x)) == 'ν(x)'
+    assert mpp.doprint(primeomega(x)) == 'Ω(x)'
+    assert mpp.doprint(fresnels(x)) == 'S(x)'
+    assert mpp.doprint(fresnelc(x)) ==  'C(x)'
+    assert mpp.doprint(Heaviside(x)) == 'Θ(x,12)'
+
+
+def test_mathml_builtins():
+    assert mpp.doprint(None) == 'None'
+    assert mpp.doprint(true) == 'True'
+    assert mpp.doprint(false) == 'False'
+
+
+def test_mathml_Range():
+    assert mpp.doprint(Range(1, 51)) == \
+        '{1,2,,50}'
+    assert mpp.doprint(Range(1, 4)) == \
+        '{1,2,3}'
+    assert mpp.doprint(Range(0, 3, 1)) == \
+        '{0,1,2}'
+    assert mpp.doprint(Range(0, 30, 1)) == \
+        '{0,1,,29}'
+    assert mpp.doprint(Range(30, 1, -1)) == \
+        '{30,29,,2}'
+    assert mpp.doprint(Range(0, oo, 2)) == \
+        '{0,2,}'
+    assert mpp.doprint(Range(oo, -2, -2)) == \
+        '{,2,0}'
+    assert mpp.doprint(Range(-2, -oo, -1)) == \
+        '{-2,-3,}'
+
+
+def test_print_exp():
+    assert mpp.doprint(exp(x)) == \
+        'x'
+    assert mpp.doprint(exp(1) + exp(2)) == \
+        '+2'
+
+
+def test_print_MinMax():
+    assert mpp.doprint(Min(x, y)) == \
+        'min(x,y)'
+    assert mpp.doprint(Min(x, 2, x**3)) == \
+        'min(2,x,x3)'
+    assert mpp.doprint(Max(x, y)) == \
+        'max(x,y)'
+    assert mpp.doprint(Max(x, 2, x**3)) == \
+        'max(2,x,x3)'
+
+
+def test_mathml_presentation_numbers():
+    n = Symbol('n')
+    assert mathml(catalan(n), printer='presentation') == \
+        'Cn'
+    assert mathml(bernoulli(n), printer='presentation') == \
+        'Bn'
+    assert mathml(bell(n), printer='presentation') == \
+        'Bn'
+    assert mathml(euler(n), printer='presentation') == \
+        'En'
+    assert mathml(fibonacci(n), printer='presentation') == \
+        'Fn'
+    assert mathml(lucas(n), printer='presentation') == \
+        'Ln'
+    assert mathml(tribonacci(n), printer='presentation') == \
+        'Tn'
+    assert mathml(bernoulli(n, x), printer='presentation') == \
+        mathml(bell(n, x), printer='presentation') == \
+        'Bn(x)'
+    assert mathml(euler(n, x), printer='presentation') == \
+        'En(x)'
+    assert mathml(fibonacci(n, x), printer='presentation') == \
+        'Fn(x)'
+    assert mathml(tribonacci(n, x), printer='presentation') == \
+        'Tn(x)'
+
+
+def test_mathml_presentation_mathieu():
+    assert mathml(mathieuc(x, y, z), printer='presentation') == \
+        'C(x,y,z)'
+    assert mathml(mathieus(x, y, z), printer='presentation') == \
+        'S(x,y,z)'
+    assert mathml(mathieucprime(x, y, z), printer='presentation') == \
+        'C′(x,y,z)'
+    assert mathml(mathieusprime(x, y, z), printer='presentation') == \
+        'S′(x,y,z)'
+
+
+def test_mathml_presentation_stieltjes():
+    assert mathml(stieltjes(n), printer='presentation') == \
+         'γn'
+    assert mathml(stieltjes(n, x), printer='presentation') == \
+         'γn(x)'
+
+
+def test_print_matrix_symbol():
+    A = MatrixSymbol('A', 1, 2)
+    assert mpp.doprint(A) == 'A'
+    assert mp.doprint(A) == 'A'
+    assert mathml(A, printer='presentation', mat_symbol_style="bold") == \
+        'A'
+    # No effect in content printer
+    assert mathml(A, mat_symbol_style="bold") == 'A'
+
+
+def test_print_hadamard():
+    from sympy.matrices.expressions import HadamardProduct
+    from sympy.matrices.expressions import Transpose
+
+    X = MatrixSymbol('X', 2, 2)
+    Y = MatrixSymbol('Y', 2, 2)
+
+    assert mathml(HadamardProduct(X, Y*Y), printer="presentation") == \
+        '' \
+        'X' \
+        '' \
+        'Y2' \
+        ''
+
+    assert mathml(HadamardProduct(X, Y)*Y, printer="presentation") == \
+        '' \
+        '(' \
+        'XY' \
+        ')' \
+        'Y' \
+        ''
+
+    assert mathml(HadamardProduct(X, Y, Y), printer="presentation") == \
+        '' \
+        'X' \
+        'Y' \
+        'Y' \
+        ''
+
+    assert mathml(
+        Transpose(HadamardProduct(X, Y)), printer="presentation") == \
+            '' \
+            '(' \
+            'XY' \
+            ')' \
+            'T' \
+            ''
+
+
+def test_print_random_symbol():
+    R = RandomSymbol(Symbol('R'))
+    assert mpp.doprint(R) == 'R'
+    assert mp.doprint(R) == 'R'
+
+
+def test_print_IndexedBase():
+    assert mathml(IndexedBase(a)[b], printer='presentation') == \
+        'ab'
+    assert mathml(IndexedBase(a)[b, c, d], printer='presentation') == \
+        'a(b,c,d)'
+    assert mathml(IndexedBase(a)[b]*IndexedBase(c)[d]*IndexedBase(e),
+                  printer='presentation') == \
+                  'ab⁢'\
+                  'cde'
+
+
+def test_print_Indexed():
+    assert mathml(IndexedBase(a), printer='presentation') == 'a'
+    assert mathml(IndexedBase(a/b), printer='presentation') == \
+        'ab'
+    assert mathml(IndexedBase((a, b)), printer='presentation') == \
+        '(a,b)'
+
+def test_print_MatrixElement():
+    i, j = symbols('i j')
+    A = MatrixSymbol('A', i, j)
+    assert mathml(A[0,0],printer = 'presentation') == \
+        'A0,0'
+    assert mathml(A[i,j], printer = 'presentation') == \
+        'Ai,j'
+    assert mathml(A[i*j,0], printer = 'presentation') == \
+        'Aij,0'
+
+
+def test_print_Vector():
+    ACS = CoordSys3D('A')
+    assert mathml(Cross(ACS.i, ACS.j*ACS.x*3 + ACS.k), printer='presentation') == \
+        'i^'\
+        'A×('\
+        '(3'\
+        'xA'\
+        ')'\
+        'j^'\
+        'A+'\
+        'k^'\
+        'A)'
+    assert mathml(Cross(ACS.i, ACS.j), printer='presentation') == \
+        'i^'\
+        'A×'\
+        'j^'\
+        'A'
+    assert mathml(x*Cross(ACS.i, ACS.j), printer='presentation') == \
+        'x('\
+        'i^'\
+        'A×'\
+        'j^'\
+        'A)'
+    assert mathml(Cross(x*ACS.i, ACS.j), printer='presentation') == \
+        '-j'\
+        '^A'\
+        '×((x)'\
+        'i'\
+        '^A'\
+        ')'
+    assert mathml(Curl(3*ACS.x*ACS.j), printer='presentation') == \
+        '×(('\
+        '3x'\
+        'A)'\
+        'j^'\
+        'A)'
+    assert mathml(Curl(3*x*ACS.x*ACS.j), printer='presentation') == \
+        '×(('\
+        '3x'\
+        'A'\
+        'x)'\
+        'j^'\
+        'A)'
+    assert mathml(x*Curl(3*ACS.x*ACS.j), printer='presentation') == \
+        'x('\
+        '×((3'\
+        'x'\
+        'A)'\
+        'j'\
+        '^A)'\
+        ')'
+    assert mathml(Curl(3*x*ACS.x*ACS.j + ACS.i), printer='presentation') == \
+        '×('\
+        'i^'\
+        'A+('\
+        '3x'\
+        'A'\
+        'x)'\
+        'j^'\
+        'A)'
+    assert mathml(Divergence(3*ACS.x*ACS.j), printer='presentation') == \
+        '·(('\
+        '3x'\
+        'A)'\
+        'j'\
+        '^A)'
+    assert mathml(x*Divergence(3*ACS.x*ACS.j), printer='presentation') == \
+        'x('\
+        '·((3'\
+        'x'\
+        'A)'\
+        'j'\
+        '^A'\
+        '))'
+    assert mathml(Divergence(3*x*ACS.x*ACS.j + ACS.i), printer='presentation') == \
+        '·('\
+        'i^'\
+        'A+('\
+        '3'\
+        'xA'\
+        'x)'\
+        'j'\
+        '^A'\
+        ')'
+    assert mathml(Dot(ACS.i, ACS.j*ACS.x*3+ACS.k), printer='presentation') == \
+        'i^'\
+        'A·('\
+        '(3'\
+        'xA'\
+        ')'\
+        'j^'\
+        'A+'\
+        'k^'\
+        'A)'
+    assert mathml(Dot(ACS.i, ACS.j), printer='presentation') == \
+        'i^'\
+        'A·'\
+        'j^'\
+        'A'
+    assert mathml(Dot(x*ACS.i, ACS.j), printer='presentation') == \
+        'j^'\
+        'A·('\
+        '(x)'\
+        'i^'\
+        'A)'
+    assert mathml(x*Dot(ACS.i, ACS.j), printer='presentation') == \
+        'x('\
+        'i^'\
+        'A·'\
+        'j^'\
+        'A)'
+    assert mathml(Gradient(ACS.x), printer='presentation') == \
+        'x'\
+        'A'
+    assert mathml(Gradient(ACS.x + 3*ACS.y), printer='presentation') == \
+        '('\
+        'xA+3'\
+        'y'\
+        'A)'
+    assert mathml(x*Gradient(ACS.x), printer='presentation') == \
+        'x('\
+        'xA'\
+        ')'
+    assert mathml(Gradient(x*ACS.x), printer='presentation') == \
+        '('\
+        'xA'\
+        'x)'
+    assert mathml(Cross(ACS.z, ACS.x), printer='presentation') == \
+        '-x'\
+        'A×'\
+        'zA'
+    assert mathml(Laplacian(ACS.x), printer='presentation') == \
+        'x'\
+        'A'
+    assert mathml(Laplacian(ACS.x + 3*ACS.y), printer='presentation') == \
+        '('\
+        'xA+3'\
+        'y'\
+        'A)'
+    assert mathml(x*Laplacian(ACS.x), printer='presentation') == \
+        'x('\
+        'xA'\
+        ')'
+    assert mathml(Laplacian(x*ACS.x), printer='presentation') == \
+        '('\
+        'xA'\
+        'x)'
+
+@XFAIL
+def test_vector_cross_xfail():
+    ACS = CoordSys3D('A')
+    assert mathml(Cross(ACS.x, ACS.z) + Cross(ACS.z, ACS.x), printer='presentation') == \
+        '0^'
+
+def test_print_elliptic_f():
+    assert mathml(elliptic_f(x, y), printer = 'presentation') == \
+        '𝖥(x|y)'
+    assert mathml(elliptic_f(x/y, y), printer = 'presentation') == \
+        '𝖥(xy|y)'
+
+def test_print_elliptic_e():
+    assert mathml(elliptic_e(x), printer = 'presentation') == \
+        '𝖤(x)'
+    assert mathml(elliptic_e(x, y), printer = 'presentation') == \
+        '𝖤(x|y)'
+
+def test_print_elliptic_pi():
+    assert mathml(elliptic_pi(x, y), printer = 'presentation') == \
+        '𝛱(x|y)'
+    assert mathml(elliptic_pi(x, y, z), printer = 'presentation') == \
+        '𝛱(x;y|z)'
+
+def test_print_Ei():
+    assert mathml(Ei(x), printer = 'presentation') == \
+        'Ei(x)'
+    assert mathml(Ei(x**y), printer = 'presentation') == \
+        'Ei(xy)'
+
+def test_print_expint():
+    assert mathml(expint(x, y), printer = 'presentation') == \
+        'Ex(y)'
+    assert mathml(expint(IndexedBase(x)[1], IndexedBase(x)[2]), printer = 'presentation') == \
+        'Ex1(x2)'
+
+def test_print_jacobi():
+    assert mathml(jacobi(n, a, b, x), printer = 'presentation') == \
+        'Pn(a,b)(x)'
+
+def test_print_gegenbauer():
+    assert mathml(gegenbauer(n, a, x), printer = 'presentation') == \
+        'Cn(a)(x)'
+
+def test_print_chebyshevt():
+    assert mathml(chebyshevt(n, x), printer = 'presentation') == \
+        'Tn(x)'
+
+def test_print_chebyshevu():
+    assert mathml(chebyshevu(n, x), printer = 'presentation') == \
+        'Un(x)'
+
+def test_print_legendre():
+    assert mathml(legendre(n, x), printer = 'presentation') == \
+        'Pn(x)'
+
+def test_print_assoc_legendre():
+    assert mathml(assoc_legendre(n, a, x), printer = 'presentation') == \
+        'Pn(a)(x)'
+
+def test_print_laguerre():
+    assert mathml(laguerre(n, x), printer = 'presentation') == \
+        'Ln(x)'
+
+def test_print_assoc_laguerre():
+    assert mathml(assoc_laguerre(n, a, x), printer = 'presentation') == \
+        'Ln(a)(x)'
+
+def test_print_hermite():
+    assert mathml(hermite(n, x), printer = 'presentation') == \
+        'Hn(x)'
+
+def test_mathml_SingularityFunction():
+    assert mathml(SingularityFunction(x, 4, 5), printer='presentation') == \
+        'x-45'
+    assert mathml(SingularityFunction(x, -3, 4), printer='presentation') == \
+        'x+34'
+    assert mathml(SingularityFunction(x, 0, 4), printer='presentation') == \
+        'x4'
+    assert mathml(SingularityFunction(x, a, n), printer='presentation') == \
+        '-a+xn'
+    assert mathml(SingularityFunction(x, 4, -2), printer='presentation') == \
+        'x-4-2'
+    assert mathml(SingularityFunction(x, 4, -1), printer='presentation') == \
+        'x-4-1'
+
+
+def test_mathml_matrix_functions():
+    from sympy.matrices import Adjoint, Inverse, Transpose
+    X = MatrixSymbol('X', 2, 2)
+    Y = MatrixSymbol('Y', 2, 2)
+    assert mathml(Adjoint(X), printer='presentation') == \
+        'X'
+    assert mathml(Adjoint(X + Y), printer='presentation') == \
+        '(X+Y)'
+    assert mathml(Adjoint(X) + Adjoint(Y), printer='presentation') == \
+        'X+' \
+        'Y'
+    assert mathml(Adjoint(X*Y), printer='presentation') == \
+        '(X' \
+        'Y)'
+    assert mathml(Adjoint(Y)*Adjoint(X), printer='presentation') == \
+        'Y⁢' \
+        'X'
+    assert mathml(Adjoint(X**2), printer='presentation') == \
+        '(X2)'
+    assert mathml(Adjoint(X)**2, printer='presentation') == \
+        '(X)2'
+    assert mathml(Adjoint(Inverse(X)), printer='presentation') == \
+        '(X-1)'
+    assert mathml(Inverse(Adjoint(X)), printer='presentation') == \
+        '(X)-1'
+    assert mathml(Adjoint(Transpose(X)), printer='presentation') == \
+        '(XT)'
+    assert mathml(Transpose(Adjoint(X)), printer='presentation') ==  \
+        '(X)T'
+    assert mathml(Transpose(Adjoint(X) + Y), printer='presentation') ==  \
+        '(X' \
+        '+Y)T'
+    assert mathml(Transpose(X), printer='presentation') == \
+        'XT'
+    assert mathml(Transpose(X + Y), printer='presentation') == \
+        '(X+Y)T'
+
+
+def test_mathml_special_matrices():
+    from sympy.matrices import Identity, ZeroMatrix, OneMatrix
+    assert mathml(Identity(4), printer='presentation') == '𝕀'
+    assert mathml(ZeroMatrix(2, 2), printer='presentation') == '𝟘'
+    assert mathml(OneMatrix(2, 2), printer='presentation') == '𝟙'
+
+def test_mathml_piecewise():
+    from sympy.functions.elementary.piecewise import Piecewise
+    # Content MathML
+    assert mathml(Piecewise((x, x <= 1), (x**2, True))) == \
+        'xx1x2'
+
+    raises(ValueError, lambda: mathml(Piecewise((x, x <= 1))))
+
+
+def test_issue_17857():
+    assert mathml(Range(-oo, oo), printer='presentation') == \
+        '{,-1,0,1,}'
+    assert mathml(Range(oo, -oo, -1), printer='presentation') == \
+        '{,1,0,-1,}'
+
+
+def test_float_roundtrip():
+    x = sympify(0.8975979010256552)
+    y = float(mp.doprint(x).strip(''))
+    assert x == y
+
+
+def test_content_mathml_disable_split_super_sub():
+    mp = MathMLContentPrinter()
+    assert mp.doprint(Symbol('u_b')) == 'ub'
+    mp = MathMLContentPrinter({'disable_split_super_sub': False})
+    assert mp.doprint(Symbol('u_b')) == 'ub'
+    mp = MathMLContentPrinter({'disable_split_super_sub': True})
+    assert mp.doprint(Symbol('u_b')) == 'u_b'
+
+def test_presentation_mathml_disable_split_super_sub():
+    mpp = MathMLPresentationPrinter()
+    assert mpp.doprint(Symbol('u_b')) == 'ub'
+    mpp = MathMLPresentationPrinter({'disable_split_super_sub': False})
+    assert mpp.doprint(Symbol('u_b')) == 'ub'
+    mpp = MathMLPresentationPrinter({'disable_split_super_sub': True})
+    assert mpp.doprint(Symbol('u_b')) == 'u_b'
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_numpy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_numpy.py
new file mode 100644
index 0000000000000000000000000000000000000000..fee1c6bd95e54790a048220f37b8e5de79017d2f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_numpy.py
@@ -0,0 +1,381 @@
+from sympy.concrete.summations import Sum
+from sympy.core.mod import Mod
+from sympy.core.relational import (Equality, Unequality)
+from sympy.core.symbol import Symbol
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.functions.special.gamma_functions import polygamma
+from sympy.functions.special.error_functions import (Si, Ci)
+from sympy.matrices import Matrix
+from sympy.matrices.expressions.blockmatrix import BlockMatrix
+from sympy.matrices.expressions.matexpr import MatrixSymbol
+from sympy.matrices.expressions.special import Identity
+from sympy.utilities.lambdify import lambdify
+from sympy import symbols, Min, Max
+
+from sympy.abc import x, i, j, a, b, c, d
+from sympy.core import Pow
+from sympy.codegen.matrix_nodes import MatrixSolve
+from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
+from sympy.codegen.cfunctions import log1p, expm1, hypot, log10, exp2, log2, Sqrt
+from sympy.tensor.array import Array
+from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayAdd, \
+    PermuteDims, ArrayDiagonal
+from sympy.printing.numpy import NumPyPrinter, SciPyPrinter, _numpy_known_constants, \
+    _numpy_known_functions, _scipy_known_constants, _scipy_known_functions
+from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
+
+from sympy.testing.pytest import skip, raises
+from sympy.external import import_module
+
+np = import_module('numpy')
+jax = import_module('jax')
+
+if np:
+    deafult_float_info = np.finfo(np.array([]).dtype)
+    NUMPY_DEFAULT_EPSILON = deafult_float_info.eps
+
+def test_numpy_piecewise_regression():
+    """
+    NumPyPrinter needs to print Piecewise()'s choicelist as a list to avoid
+    breaking compatibility with numpy 1.8. This is not necessary in numpy 1.9+.
+    See gh-9747 and gh-9749 for details.
+    """
+    printer = NumPyPrinter()
+    p = Piecewise((1, x < 0), (0, True))
+    assert printer.doprint(p) == \
+        'numpy.select([numpy.less(x, 0),True], [1,0], default=numpy.nan)'
+    assert printer.module_imports == {'numpy': {'select', 'less', 'nan'}}
+
+def test_numpy_logaddexp():
+    lae = logaddexp(a, b)
+    assert NumPyPrinter().doprint(lae) == 'numpy.logaddexp(a, b)'
+    lae2 = logaddexp2(a, b)
+    assert NumPyPrinter().doprint(lae2) == 'numpy.logaddexp2(a, b)'
+
+
+def test_sum():
+    if not np:
+        skip("NumPy not installed")
+
+    s = Sum(x ** i, (i, a, b))
+    f = lambdify((a, b, x), s, 'numpy')
+
+    a_, b_ = 0, 10
+    x_ = np.linspace(-1, +1, 10)
+    assert np.allclose(f(a_, b_, x_), sum(x_ ** i_ for i_ in range(a_, b_ + 1)))
+
+    s = Sum(i * x, (i, a, b))
+    f = lambdify((a, b, x), s, 'numpy')
+
+    a_, b_ = 0, 10
+    x_ = np.linspace(-1, +1, 10)
+    assert np.allclose(f(a_, b_, x_), sum(i_ * x_ for i_ in range(a_, b_ + 1)))
+
+
+def test_multiple_sums():
+    if not np:
+        skip("NumPy not installed")
+
+    s = Sum((x + j) * i, (i, a, b), (j, c, d))
+    f = lambdify((a, b, c, d, x), s, 'numpy')
+
+    a_, b_ = 0, 10
+    c_, d_ = 11, 21
+    x_ = np.linspace(-1, +1, 10)
+    assert np.allclose(f(a_, b_, c_, d_, x_),
+                       sum((x_ + j_) * i_ for i_ in range(a_, b_ + 1) for j_ in range(c_, d_ + 1)))
+
+
+def test_codegen_einsum():
+    if not np:
+        skip("NumPy not installed")
+
+    M = MatrixSymbol("M", 2, 2)
+    N = MatrixSymbol("N", 2, 2)
+
+    cg = convert_matrix_to_array(M * N)
+    f = lambdify((M, N), cg, 'numpy')
+
+    ma = np.array([[1, 2], [3, 4]])
+    mb = np.array([[1,-2], [-1, 3]])
+    assert (f(ma, mb) == np.matmul(ma, mb)).all()
+
+
+def test_codegen_extra():
+    if not np:
+        skip("NumPy not installed")
+
+    M = MatrixSymbol("M", 2, 2)
+    N = MatrixSymbol("N", 2, 2)
+    P = MatrixSymbol("P", 2, 2)
+    Q = MatrixSymbol("Q", 2, 2)
+    ma = np.array([[1, 2], [3, 4]])
+    mb = np.array([[1,-2], [-1, 3]])
+    mc = np.array([[2, 0], [1, 2]])
+    md = np.array([[1,-1], [4, 7]])
+
+    cg = ArrayTensorProduct(M, N)
+    f = lambdify((M, N), cg, 'numpy')
+    assert (f(ma, mb) == np.einsum(ma, [0, 1], mb, [2, 3])).all()
+
+    cg = ArrayAdd(M, N)
+    f = lambdify((M, N), cg, 'numpy')
+    assert (f(ma, mb) == ma+mb).all()
+
+    cg = ArrayAdd(M, N, P)
+    f = lambdify((M, N, P), cg, 'numpy')
+    assert (f(ma, mb, mc) == ma+mb+mc).all()
+
+    cg = ArrayAdd(M, N, P, Q)
+    f = lambdify((M, N, P, Q), cg, 'numpy')
+    assert (f(ma, mb, mc, md) == ma+mb+mc+md).all()
+
+    cg = PermuteDims(M, [1, 0])
+    f = lambdify((M,), cg, 'numpy')
+    assert (f(ma) == ma.T).all()
+
+    cg = PermuteDims(ArrayTensorProduct(M, N), [1, 2, 3, 0])
+    f = lambdify((M, N), cg, 'numpy')
+    assert (f(ma, mb) == np.transpose(np.einsum(ma, [0, 1], mb, [2, 3]), (1, 2, 3, 0))).all()
+
+    cg = ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2))
+    f = lambdify((M, N), cg, 'numpy')
+    assert (f(ma, mb) == np.diagonal(np.einsum(ma, [0, 1], mb, [2, 3]), axis1=1, axis2=2)).all()
+
+
+def test_relational():
+    if not np:
+        skip("NumPy not installed")
+
+    e = Equality(x, 1)
+
+    f = lambdify((x,), e)
+    x_ = np.array([0, 1, 2])
+    assert np.array_equal(f(x_), [False, True, False])
+
+    e = Unequality(x, 1)
+
+    f = lambdify((x,), e)
+    x_ = np.array([0, 1, 2])
+    assert np.array_equal(f(x_), [True, False, True])
+
+    e = (x < 1)
+
+    f = lambdify((x,), e)
+    x_ = np.array([0, 1, 2])
+    assert np.array_equal(f(x_), [True, False, False])
+
+    e = (x <= 1)
+
+    f = lambdify((x,), e)
+    x_ = np.array([0, 1, 2])
+    assert np.array_equal(f(x_), [True, True, False])
+
+    e = (x > 1)
+
+    f = lambdify((x,), e)
+    x_ = np.array([0, 1, 2])
+    assert np.array_equal(f(x_), [False, False, True])
+
+    e = (x >= 1)
+
+    f = lambdify((x,), e)
+    x_ = np.array([0, 1, 2])
+    assert np.array_equal(f(x_), [False, True, True])
+
+
+def test_mod():
+    if not np:
+        skip("NumPy not installed")
+
+    e = Mod(a, b)
+    f = lambdify((a, b), e)
+
+    a_ = np.array([0, 1, 2, 3])
+    b_ = 2
+    assert np.array_equal(f(a_, b_), [0, 1, 0, 1])
+
+    a_ = np.array([0, 1, 2, 3])
+    b_ = np.array([2, 2, 2, 2])
+    assert np.array_equal(f(a_, b_), [0, 1, 0, 1])
+
+    a_ = np.array([2, 3, 4, 5])
+    b_ = np.array([2, 3, 4, 5])
+    assert np.array_equal(f(a_, b_), [0, 0, 0, 0])
+
+
+def test_pow():
+    if not np:
+        skip('NumPy not installed')
+
+    expr = Pow(2, -1, evaluate=False)
+    f = lambdify([], expr, 'numpy')
+    assert f() == 0.5
+
+
+def test_expm1():
+    if not np:
+        skip("NumPy not installed")
+
+    f = lambdify((a,), expm1(a), 'numpy')
+    assert abs(f(1e-10) - 1e-10 - 5e-21) <= 1e-10 * NUMPY_DEFAULT_EPSILON
+
+
+def test_log1p():
+    if not np:
+        skip("NumPy not installed")
+
+    f = lambdify((a,), log1p(a), 'numpy')
+    assert abs(f(1e-99) - 1e-99) <= 1e-99 * NUMPY_DEFAULT_EPSILON
+
+def test_hypot():
+    if not np:
+        skip("NumPy not installed")
+    assert abs(lambdify((a, b), hypot(a, b), 'numpy')(3, 4) - 5) <= NUMPY_DEFAULT_EPSILON
+
+def test_log10():
+    if not np:
+        skip("NumPy not installed")
+    assert abs(lambdify((a,), log10(a), 'numpy')(100) - 2) <= NUMPY_DEFAULT_EPSILON
+
+
+def test_exp2():
+    if not np:
+        skip("NumPy not installed")
+    assert abs(lambdify((a,), exp2(a), 'numpy')(5) - 32) <= NUMPY_DEFAULT_EPSILON
+
+
+def test_log2():
+    if not np:
+        skip("NumPy not installed")
+    assert abs(lambdify((a,), log2(a), 'numpy')(256) - 8) <= NUMPY_DEFAULT_EPSILON
+
+
+def test_Sqrt():
+    if not np:
+        skip("NumPy not installed")
+    assert abs(lambdify((a,), Sqrt(a), 'numpy')(4) - 2) <= NUMPY_DEFAULT_EPSILON
+
+
+def test_sqrt():
+    if not np:
+        skip("NumPy not installed")
+    assert abs(lambdify((a,), sqrt(a), 'numpy')(4) - 2) <= NUMPY_DEFAULT_EPSILON
+
+
+def test_matsolve():
+    if not np:
+        skip("NumPy not installed")
+
+    M = MatrixSymbol("M", 3, 3)
+    x = MatrixSymbol("x", 3, 1)
+
+    expr = M**(-1) * x + x
+    matsolve_expr = MatrixSolve(M, x) + x
+
+    f = lambdify((M, x), expr)
+    f_matsolve = lambdify((M, x), matsolve_expr)
+
+    m0 = np.array([[1, 2, 3], [3, 2, 5], [5, 6, 7]])
+    assert np.linalg.matrix_rank(m0) == 3
+
+    x0 = np.array([3, 4, 5])
+
+    assert np.allclose(f_matsolve(m0, x0), f(m0, x0))
+
+
+def test_16857():
+    if not np:
+        skip("NumPy not installed")
+
+    a_1 = MatrixSymbol('a_1', 10, 3)
+    a_2 = MatrixSymbol('a_2', 10, 3)
+    a_3 = MatrixSymbol('a_3', 10, 3)
+    a_4 = MatrixSymbol('a_4', 10, 3)
+    A = BlockMatrix([[a_1, a_2], [a_3, a_4]])
+    assert A.shape == (20, 6)
+
+    printer = NumPyPrinter()
+    assert printer.doprint(A) == 'numpy.block([[a_1, a_2], [a_3, a_4]])'
+
+
+def test_issue_17006():
+    if not np:
+        skip("NumPy not installed")
+
+    M = MatrixSymbol("M", 2, 2)
+
+    f = lambdify(M, M + Identity(2))
+    ma = np.array([[1, 2], [3, 4]])
+    mr = np.array([[2, 2], [3, 5]])
+
+    assert (f(ma) == mr).all()
+
+    from sympy.core.symbol import symbols
+    n = symbols('n', integer=True)
+    N = MatrixSymbol("M", n, n)
+    raises(NotImplementedError, lambda: lambdify(N, N + Identity(n)))
+
+def test_jax_tuple_compatibility():
+    if not jax:
+        skip("Jax not installed")
+
+    x, y, z = symbols('x y z')
+    expr = Max(x, y, z) + Min(x, y, z)
+    func = lambdify((x, y, z), expr, 'jax')
+    input_tuple1, input_tuple2 = (1, 2, 3), (4, 5, 6)
+    input_array1, input_array2 = jax.numpy.asarray(input_tuple1), jax.numpy.asarray(input_tuple2)
+    assert np.allclose(func(*input_tuple1), func(*input_array1))
+    assert np.allclose(func(*input_tuple2), func(*input_array2))
+
+def test_numpy_array():
+    p = NumPyPrinter()
+    assert p.doprint(Array([[1, 2], [3, 5]])) == 'numpy.array([[1, 2], [3, 5]])'
+    assert p.doprint(Array([1, 2])) == 'numpy.array([1, 2])'
+    assert p.doprint(Array([[[1, 2, 3]]])) == 'numpy.array([[[1, 2, 3]]])'
+    assert p.doprint(Array([], (0,))) == 'numpy.zeros((0,))'
+    assert p.doprint(Array([], (0, 0))) == 'numpy.zeros((0, 0))'
+    assert p.doprint(Array([], (0, 1))) == 'numpy.zeros((0, 1))'
+    assert p.doprint(Array([], (1, 0))) == 'numpy.zeros((1, 0))'
+    assert p.doprint(Array([1], ())) == 'numpy.array(1)'
+
+def test_numpy_matrix():
+    p = NumPyPrinter()
+    assert p.doprint(Matrix([[1, 2], [3, 5]])) == 'numpy.array([[1, 2], [3, 5]])'
+    assert p.doprint(Matrix([1, 2])) == 'numpy.array([[1], [2]])'
+    assert p.doprint(Matrix(0, 0, [])) == 'numpy.zeros((0, 0))'
+    assert p.doprint(Matrix(0, 1, [])) == 'numpy.zeros((0, 1))'
+    assert p.doprint(Matrix(1, 0, [])) == 'numpy.zeros((1, 0))'
+
+def test_numpy_known_funcs_consts():
+    assert _numpy_known_constants['NaN'] == 'numpy.nan'
+    assert _numpy_known_constants['EulerGamma'] == 'numpy.euler_gamma'
+
+    assert _numpy_known_functions['acos'] == 'numpy.arccos'
+    assert _numpy_known_functions['log'] == 'numpy.log'
+
+def test_scipy_known_funcs_consts():
+    assert _scipy_known_constants['GoldenRatio'] == 'scipy.constants.golden_ratio'
+    assert _scipy_known_constants['Pi'] == 'scipy.constants.pi'
+
+    assert _scipy_known_functions['erf'] == 'scipy.special.erf'
+    assert _scipy_known_functions['factorial'] == 'scipy.special.factorial'
+
+def test_numpy_print_methods():
+    prntr = NumPyPrinter()
+    assert hasattr(prntr, '_print_acos')
+    assert hasattr(prntr, '_print_log')
+
+def test_scipy_print_methods():
+    prntr = SciPyPrinter()
+    assert hasattr(prntr, '_print_acos')
+    assert hasattr(prntr, '_print_log')
+    assert hasattr(prntr, '_print_erf')
+    assert hasattr(prntr, '_print_factorial')
+    assert hasattr(prntr, '_print_chebyshevt')
+    k = Symbol('k', integer=True, nonnegative=True)
+    x = Symbol('x', real=True)
+    assert prntr.doprint(polygamma(k, x)) == "scipy.special.polygamma(k, x)"
+    assert prntr.doprint(Si(x)) == "scipy.special.sici(x)[0]"
+    assert prntr.doprint(Ci(x)) == "scipy.special.sici(x)[1]"
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_octave.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_octave.py
new file mode 100644
index 0000000000000000000000000000000000000000..1aba318f873c48ec702f1b4e3a6cc047f75d647d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_octave.py
@@ -0,0 +1,515 @@
+from sympy.core import (S, pi, oo, symbols, Function, Rational, Integer,
+                        Tuple, Symbol, EulerGamma, GoldenRatio, Catalan,
+                        Lambda, Mul, Pow, Mod, Eq, Ne, Le, Lt, Gt, Ge)
+from sympy.codegen.matrix_nodes import MatrixSolve
+from sympy.functions import (arg, atan2, bernoulli, beta, ceiling, chebyshevu,
+                             chebyshevt, conjugate, DiracDelta, exp, expint,
+                             factorial, floor, harmonic, Heaviside, im,
+                             laguerre, LambertW, log, Max, Min, Piecewise,
+                             polylog, re, RisingFactorial, sign, sinc, sqrt,
+                             zeta, binomial, legendre, dirichlet_eta,
+                             riemann_xi)
+from sympy.functions import (sin, cos, tan, cot, sec, csc, asin, acos, acot,
+                             atan, asec, acsc, sinh, cosh, tanh, coth, csch,
+                             sech, asinh, acosh, atanh, acoth, asech, acsch)
+from sympy.testing.pytest import raises, XFAIL
+from sympy.utilities.lambdify import implemented_function
+from sympy.matrices import (eye, Matrix, MatrixSymbol, Identity,
+                            HadamardProduct, SparseMatrix, HadamardPower)
+from sympy.functions.special.bessel import (jn, yn, besselj, bessely, besseli,
+                                            besselk, hankel1, hankel2, airyai,
+                                            airybi, airyaiprime, airybiprime)
+from sympy.functions.special.gamma_functions import (gamma, lowergamma,
+                                                     uppergamma, loggamma,
+                                                     polygamma)
+from sympy.functions.special.error_functions import (Chi, Ci, erf, erfc, erfi,
+                                                     erfcinv, erfinv, fresnelc,
+                                                     fresnels, li, Shi, Si, Li,
+                                                     erf2, Ei)
+from sympy.printing.octave import octave_code, octave_code as mcode
+
+x, y, z = symbols('x,y,z')
+
+
+def test_Integer():
+    assert mcode(Integer(67)) == "67"
+    assert mcode(Integer(-1)) == "-1"
+
+
+def test_Rational():
+    assert mcode(Rational(3, 7)) == "3/7"
+    assert mcode(Rational(18, 9)) == "2"
+    assert mcode(Rational(3, -7)) == "-3/7"
+    assert mcode(Rational(-3, -7)) == "3/7"
+    assert mcode(x + Rational(3, 7)) == "x + 3/7"
+    assert mcode(Rational(3, 7)*x) == "3*x/7"
+
+
+def test_Relational():
+    assert mcode(Eq(x, y)) == "x == y"
+    assert mcode(Ne(x, y)) == "x != y"
+    assert mcode(Le(x, y)) == "x <= y"
+    assert mcode(Lt(x, y)) == "x < y"
+    assert mcode(Gt(x, y)) == "x > y"
+    assert mcode(Ge(x, y)) == "x >= y"
+
+
+def test_Function():
+    assert mcode(sin(x) ** cos(x)) == "sin(x).^cos(x)"
+    assert mcode(sign(x)) == "sign(x)"
+    assert mcode(exp(x)) == "exp(x)"
+    assert mcode(log(x)) == "log(x)"
+    assert mcode(factorial(x)) == "factorial(x)"
+    assert mcode(floor(x)) == "floor(x)"
+    assert mcode(atan2(y, x)) == "atan2(y, x)"
+    assert mcode(beta(x, y)) == 'beta(x, y)'
+    assert mcode(polylog(x, y)) == 'polylog(x, y)'
+    assert mcode(harmonic(x)) == 'harmonic(x)'
+    assert mcode(bernoulli(x)) == "bernoulli(x)"
+    assert mcode(bernoulli(x, y)) == "bernoulli(x, y)"
+    assert mcode(legendre(x, y)) == "legendre(x, y)"
+
+
+def test_Function_change_name():
+    assert mcode(abs(x)) == "abs(x)"
+    assert mcode(ceiling(x)) == "ceil(x)"
+    assert mcode(arg(x)) == "angle(x)"
+    assert mcode(im(x)) == "imag(x)"
+    assert mcode(re(x)) == "real(x)"
+    assert mcode(conjugate(x)) == "conj(x)"
+    assert mcode(chebyshevt(y, x)) == "chebyshevT(y, x)"
+    assert mcode(chebyshevu(y, x)) == "chebyshevU(y, x)"
+    assert mcode(laguerre(x, y)) == "laguerreL(x, y)"
+    assert mcode(Chi(x)) == "coshint(x)"
+    assert mcode(Shi(x)) ==  "sinhint(x)"
+    assert mcode(Ci(x)) == "cosint(x)"
+    assert mcode(Si(x)) ==  "sinint(x)"
+    assert mcode(li(x)) ==  "logint(x)"
+    assert mcode(loggamma(x)) ==  "gammaln(x)"
+    assert mcode(polygamma(x, y)) == "psi(x, y)"
+    assert mcode(RisingFactorial(x, y)) == "pochhammer(x, y)"
+    assert mcode(DiracDelta(x)) == "dirac(x)"
+    assert mcode(DiracDelta(x, 3)) == "dirac(3, x)"
+    assert mcode(Heaviside(x)) == "heaviside(x, 1/2)"
+    assert mcode(Heaviside(x, y)) == "heaviside(x, y)"
+    assert mcode(binomial(x, y)) == "bincoeff(x, y)"
+    assert mcode(Mod(x, y)) == "mod(x, y)"
+
+
+def test_minmax():
+    assert mcode(Max(x, y) + Min(x, y)) == "max(x, y) + min(x, y)"
+    assert mcode(Max(x, y, z)) == "max(x, max(y, z))"
+    assert mcode(Min(x, y, z)) == "min(x, min(y, z))"
+
+
+def test_Pow():
+    assert mcode(x**3) == "x.^3"
+    assert mcode(x**(y**3)) == "x.^(y.^3)"
+    assert mcode(x**Rational(2, 3)) == 'x.^(2/3)'
+    g = implemented_function('g', Lambda(x, 2*x))
+    assert mcode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \
+        "(3.5*2*x).^(-x + y.^x)./(x.^2 + y)"
+    # For issue 14160
+    assert mcode(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False),
+                                                evaluate=False)) == '-2*x./(y.*y)'
+
+
+def test_basic_ops():
+    assert mcode(x*y) == "x.*y"
+    assert mcode(x + y) == "x + y"
+    assert mcode(x - y) == "x - y"
+    assert mcode(-x) == "-x"
+
+
+def test_1_over_x_and_sqrt():
+    # 1.0 and 0.5 would do something different in regular StrPrinter,
+    # but these are exact in IEEE floating point so no different here.
+    assert mcode(1/x) == '1./x'
+    assert mcode(x**-1) == mcode(x**-1.0) == '1./x'
+    assert mcode(1/sqrt(x)) == '1./sqrt(x)'
+    assert mcode(x**-S.Half) == mcode(x**-0.5) == '1./sqrt(x)'
+    assert mcode(sqrt(x)) == 'sqrt(x)'
+    assert mcode(x**S.Half) == mcode(x**0.5) == 'sqrt(x)'
+    assert mcode(1/pi) == '1/pi'
+    assert mcode(pi**-1) == mcode(pi**-1.0) == '1/pi'
+    assert mcode(pi**-0.5) == '1/sqrt(pi)'
+
+
+def test_mix_number_mult_symbols():
+    assert mcode(3*x) == "3*x"
+    assert mcode(pi*x) == "pi*x"
+    assert mcode(3/x) == "3./x"
+    assert mcode(pi/x) == "pi./x"
+    assert mcode(x/3) == "x/3"
+    assert mcode(x/pi) == "x/pi"
+    assert mcode(x*y) == "x.*y"
+    assert mcode(3*x*y) == "3*x.*y"
+    assert mcode(3*pi*x*y) == "3*pi*x.*y"
+    assert mcode(x/y) == "x./y"
+    assert mcode(3*x/y) == "3*x./y"
+    assert mcode(x*y/z) == "x.*y./z"
+    assert mcode(x/y*z) == "x.*z./y"
+    assert mcode(1/x/y) == "1./(x.*y)"
+    assert mcode(2*pi*x/y/z) == "2*pi*x./(y.*z)"
+    assert mcode(3*pi/x) == "3*pi./x"
+    assert mcode(S(3)/5) == "3/5"
+    assert mcode(S(3)/5*x) == "3*x/5"
+    assert mcode(x/y/z) == "x./(y.*z)"
+    assert mcode((x+y)/z) == "(x + y)./z"
+    assert mcode((x+y)/(z+x)) == "(x + y)./(x + z)"
+    assert mcode((x+y)/EulerGamma) == "(x + y)/%s" % EulerGamma.evalf(17)
+    assert mcode(x/3/pi) == "x/(3*pi)"
+    assert mcode(S(3)/5*x*y/pi) == "3*x.*y/(5*pi)"
+
+
+def test_mix_number_pow_symbols():
+    assert mcode(pi**3) == 'pi^3'
+    assert mcode(x**2) == 'x.^2'
+    assert mcode(x**(pi**3)) == 'x.^(pi^3)'
+    assert mcode(x**y) == 'x.^y'
+    assert mcode(x**(y**z)) == 'x.^(y.^z)'
+    assert mcode((x**y)**z) == '(x.^y).^z'
+
+
+def test_imag():
+    I = S('I')
+    assert mcode(I) == "1i"
+    assert mcode(5*I) == "5i"
+    assert mcode((S(3)/2)*I) == "3*1i/2"
+    assert mcode(3+4*I) == "3 + 4i"
+    assert mcode(sqrt(3)*I) == "sqrt(3)*1i"
+
+
+def test_constants():
+    assert mcode(pi) == "pi"
+    assert mcode(oo) == "inf"
+    assert mcode(-oo) == "-inf"
+    assert mcode(S.NegativeInfinity) == "-inf"
+    assert mcode(S.NaN) == "NaN"
+    assert mcode(S.Exp1) == "exp(1)"
+    assert mcode(exp(1)) == "exp(1)"
+
+
+def test_constants_other():
+    assert mcode(2*GoldenRatio) == "2*(1+sqrt(5))/2"
+    assert mcode(2*Catalan) == "2*%s" % Catalan.evalf(17)
+    assert mcode(2*EulerGamma) == "2*%s" % EulerGamma.evalf(17)
+
+
+def test_boolean():
+    assert mcode(x & y) == "x & y"
+    assert mcode(x | y) == "x | y"
+    assert mcode(~x) == "~x"
+    assert mcode(x & y & z) == "x & y & z"
+    assert mcode(x | y | z) == "x | y | z"
+    assert mcode((x & y) | z) == "z | x & y"
+    assert mcode((x | y) & z) == "z & (x | y)"
+
+
+def test_KroneckerDelta():
+    from sympy.functions import KroneckerDelta
+    assert mcode(KroneckerDelta(x, y)) == "double(x == y)"
+    assert mcode(KroneckerDelta(x, y + 1)) == "double(x == (y + 1))"
+    assert mcode(KroneckerDelta(2**x, y)) == "double((2.^x) == y)"
+
+
+def test_Matrices():
+    assert mcode(Matrix(1, 1, [10])) == "10"
+    A = Matrix([[1, sin(x/2), abs(x)],
+                [0, 1, pi],
+                [0, exp(1), ceiling(x)]])
+    expected = "[1 sin(x/2) abs(x); 0 1 pi; 0 exp(1) ceil(x)]"
+    assert mcode(A) == expected
+    # row and columns
+    assert mcode(A[:,0]) == "[1; 0; 0]"
+    assert mcode(A[0,:]) == "[1 sin(x/2) abs(x)]"
+    # empty matrices
+    assert mcode(Matrix(0, 0, [])) == '[]'
+    assert mcode(Matrix(0, 3, [])) == 'zeros(0, 3)'
+    # annoying to read but correct
+    assert mcode(Matrix([[x, x - y, -y]])) == "[x x - y -y]"
+
+
+def test_vector_entries_hadamard():
+    # For a row or column, user might to use the other dimension
+    A = Matrix([[1, sin(2/x), 3*pi/x/5]])
+    assert mcode(A) == "[1 sin(2./x) 3*pi./(5*x)]"
+    assert mcode(A.T) == "[1; sin(2./x); 3*pi./(5*x)]"
+
+
+@XFAIL
+def test_Matrices_entries_not_hadamard():
+    # For Matrix with col >= 2, row >= 2, they need to be scalars
+    # FIXME: is it worth worrying about this?  Its not wrong, just
+    # leave it user's responsibility to put scalar data for x.
+    A = Matrix([[1, sin(2/x), 3*pi/x/5], [1, 2, x*y]])
+    expected = ("[1 sin(2/x) 3*pi/(5*x);\n"
+                "1        2        x*y]") # <- we give x.*y
+    assert mcode(A) == expected
+
+
+def test_MatrixSymbol():
+    n = Symbol('n', integer=True)
+    A = MatrixSymbol('A', n, n)
+    B = MatrixSymbol('B', n, n)
+    assert mcode(A*B) == "A*B"
+    assert mcode(B*A) == "B*A"
+    assert mcode(2*A*B) == "2*A*B"
+    assert mcode(B*2*A) == "2*B*A"
+    assert mcode(A*(B + 3*Identity(n))) == "A*(3*eye(n) + B)"
+    assert mcode(A**(x**2)) == "A^(x.^2)"
+    assert mcode(A**3) == "A^3"
+    assert mcode(A**S.Half) == "A^(1/2)"
+
+
+def test_MatrixSolve():
+    n = Symbol('n', integer=True)
+    A = MatrixSymbol('A', n, n)
+    x = MatrixSymbol('x', n, 1)
+    assert mcode(MatrixSolve(A, x)) == "A \\ x"
+
+def test_special_matrices():
+    assert mcode(6*Identity(3)) == "6*eye(3)"
+
+
+def test_containers():
+    assert mcode([1, 2, 3, [4, 5, [6, 7]], 8, [9, 10], 11]) == \
+        "{1, 2, 3, {4, 5, {6, 7}}, 8, {9, 10}, 11}"
+    assert mcode((1, 2, (3, 4))) == "{1, 2, {3, 4}}"
+    assert mcode([1]) == "{1}"
+    assert mcode((1,)) == "{1}"
+    assert mcode(Tuple(*[1, 2, 3])) == "{1, 2, 3}"
+    assert mcode((1, x*y, (3, x**2))) == "{1, x.*y, {3, x.^2}}"
+    # scalar, matrix, empty matrix and empty list
+    assert mcode((1, eye(3), Matrix(0, 0, []), [])) == "{1, [1 0 0; 0 1 0; 0 0 1], [], {}}"
+
+
+def test_octave_noninline():
+    source = mcode((x+y)/Catalan, assign_to='me', inline=False)
+    expected = (
+        "Catalan = %s;\n"
+        "me = (x + y)/Catalan;"
+    ) % Catalan.evalf(17)
+    assert source == expected
+
+
+def test_octave_piecewise():
+    expr = Piecewise((x, x < 1), (x**2, True))
+    assert mcode(expr) == "((x < 1).*(x) + (~(x < 1)).*(x.^2))"
+    assert mcode(expr, assign_to="r") == (
+        "r = ((x < 1).*(x) + (~(x < 1)).*(x.^2));")
+    assert mcode(expr, assign_to="r", inline=False) == (
+        "if (x < 1)\n"
+        "  r = x;\n"
+        "else\n"
+        "  r = x.^2;\n"
+        "end")
+    expr = Piecewise((x**2, x < 1), (x**3, x < 2), (x**4, x < 3), (x**5, True))
+    expected = ("((x < 1).*(x.^2) + (~(x < 1)).*( ...\n"
+                "(x < 2).*(x.^3) + (~(x < 2)).*( ...\n"
+                "(x < 3).*(x.^4) + (~(x < 3)).*(x.^5))))")
+    assert mcode(expr) == expected
+    assert mcode(expr, assign_to="r") == "r = " + expected + ";"
+    assert mcode(expr, assign_to="r", inline=False) == (
+        "if (x < 1)\n"
+        "  r = x.^2;\n"
+        "elseif (x < 2)\n"
+        "  r = x.^3;\n"
+        "elseif (x < 3)\n"
+        "  r = x.^4;\n"
+        "else\n"
+        "  r = x.^5;\n"
+        "end")
+    # Check that Piecewise without a True (default) condition error
+    expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0))
+    raises(ValueError, lambda: mcode(expr))
+
+
+def test_octave_piecewise_times_const():
+    pw = Piecewise((x, x < 1), (x**2, True))
+    assert mcode(2*pw) == "2*((x < 1).*(x) + (~(x < 1)).*(x.^2))"
+    assert mcode(pw/x) == "((x < 1).*(x) + (~(x < 1)).*(x.^2))./x"
+    assert mcode(pw/(x*y)) == "((x < 1).*(x) + (~(x < 1)).*(x.^2))./(x.*y)"
+    assert mcode(pw/3) == "((x < 1).*(x) + (~(x < 1)).*(x.^2))/3"
+
+
+def test_octave_matrix_assign_to():
+    A = Matrix([[1, 2, 3]])
+    assert mcode(A, assign_to='a') == "a = [1 2 3];"
+    A = Matrix([[1, 2], [3, 4]])
+    assert mcode(A, assign_to='A') == "A = [1 2; 3 4];"
+
+
+def test_octave_matrix_assign_to_more():
+    # assigning to Symbol or MatrixSymbol requires lhs/rhs match
+    A = Matrix([[1, 2, 3]])
+    B = MatrixSymbol('B', 1, 3)
+    C = MatrixSymbol('C', 2, 3)
+    assert mcode(A, assign_to=B) == "B = [1 2 3];"
+    raises(ValueError, lambda: mcode(A, assign_to=x))
+    raises(ValueError, lambda: mcode(A, assign_to=C))
+
+
+def test_octave_matrix_1x1():
+    A = Matrix([[3]])
+    B = MatrixSymbol('B', 1, 1)
+    C = MatrixSymbol('C', 1, 2)
+    assert mcode(A, assign_to=B) == "B = 3;"
+    # FIXME?
+    #assert mcode(A, assign_to=x) == "x = 3;"
+    raises(ValueError, lambda: mcode(A, assign_to=C))
+
+
+def test_octave_matrix_elements():
+    A = Matrix([[x, 2, x*y]])
+    assert mcode(A[0, 0]**2 + A[0, 1] + A[0, 2]) == "x.^2 + x.*y + 2"
+    A = MatrixSymbol('AA', 1, 3)
+    assert mcode(A) == "AA"
+    assert mcode(A[0, 0]**2 + sin(A[0,1]) + A[0,2]) == \
+           "sin(AA(1, 2)) + AA(1, 1).^2 + AA(1, 3)"
+    assert mcode(sum(A)) == "AA(1, 1) + AA(1, 2) + AA(1, 3)"
+
+
+def test_octave_boolean():
+    assert mcode(True) == "true"
+    assert mcode(S.true) == "true"
+    assert mcode(False) == "false"
+    assert mcode(S.false) == "false"
+
+
+def test_octave_not_supported():
+    with raises(NotImplementedError):
+        mcode(S.ComplexInfinity)
+    f = Function('f')
+    assert mcode(f(x).diff(x), strict=False) == (
+        "% Not supported in Octave:\n"
+        "% Derivative\n"
+        "Derivative(f(x), x)"
+    )
+
+
+def test_octave_not_supported_not_on_whitelist():
+    from sympy.functions.special.polynomials import assoc_laguerre
+    with raises(NotImplementedError):
+        mcode(assoc_laguerre(x, y, z))
+
+
+def test_octave_expint():
+    assert mcode(expint(1, x)) == "expint(x)"
+    with raises(NotImplementedError):
+        mcode(expint(2, x))
+    assert mcode(expint(y, x), strict=False) == (
+        "% Not supported in Octave:\n"
+        "% expint\n"
+        "expint(y, x)"
+    )
+
+
+def test_trick_indent_with_end_else_words():
+    # words starting with "end" or "else" do not confuse the indenter
+    t1 = S('endless')
+    t2 = S('elsewhere')
+    pw = Piecewise((t1, x < 0), (t2, x <= 1), (1, True))
+    assert mcode(pw, inline=False) == (
+        "if (x < 0)\n"
+        "  endless\n"
+        "elseif (x <= 1)\n"
+        "  elsewhere\n"
+        "else\n"
+        "  1\n"
+        "end")
+
+
+def test_hadamard():
+    A = MatrixSymbol('A', 3, 3)
+    B = MatrixSymbol('B', 3, 3)
+    v = MatrixSymbol('v', 3, 1)
+    h = MatrixSymbol('h', 1, 3)
+    C = HadamardProduct(A, B)
+    n = Symbol('n')
+    assert mcode(C) == "A.*B"
+    assert mcode(C*v) == "(A.*B)*v"
+    assert mcode(h*C*v) == "h*(A.*B)*v"
+    assert mcode(C*A) == "(A.*B)*A"
+    # mixing Hadamard and scalar strange b/c we vectorize scalars
+    assert mcode(C*x*y) == "(x.*y)*(A.*B)"
+
+    # Testing HadamardPower:
+    assert mcode(HadamardPower(A, n)) == "A.**n"
+    assert mcode(HadamardPower(A, 1+n)) == "A.**(n + 1)"
+    assert mcode(HadamardPower(A*B.T, 1+n)) == "(A*B.T).**(n + 1)"
+
+
+def test_sparse():
+    M = SparseMatrix(5, 6, {})
+    M[2, 2] = 10
+    M[1, 2] = 20
+    M[1, 3] = 22
+    M[0, 3] = 30
+    M[3, 0] = x*y
+    assert mcode(M) == (
+        "sparse([4 2 3 1 2], [1 3 3 4 4], [x.*y 20 10 30 22], 5, 6)"
+    )
+
+
+def test_sinc():
+    assert mcode(sinc(x)) == 'sinc(x/pi)'
+    assert mcode(sinc(x + 3)) == 'sinc((x + 3)/pi)'
+    assert mcode(sinc(pi*(x + 3))) == 'sinc(x + 3)'
+
+
+def test_trigfun():
+    for f in (sin, cos, tan, cot, sec, csc, asin, acos, acot, atan, asec, acsc,
+              sinh, cosh, tanh, coth, csch, sech, asinh, acosh, atanh, acoth,
+              asech, acsch):
+        assert octave_code(f(x) == f.__name__ + '(x)')
+
+
+def test_specfun():
+    n = Symbol('n')
+    for f in [besselj, bessely, besseli, besselk]:
+        assert octave_code(f(n, x)) == f.__name__ + '(n, x)'
+    for f in (erfc, erfi, erf, erfinv, erfcinv, fresnelc, fresnels, gamma):
+        assert octave_code(f(x)) == f.__name__ + '(x)'
+    assert octave_code(hankel1(n, x)) == 'besselh(n, 1, x)'
+    assert octave_code(hankel2(n, x)) == 'besselh(n, 2, x)'
+    assert octave_code(airyai(x)) == 'airy(0, x)'
+    assert octave_code(airyaiprime(x)) == 'airy(1, x)'
+    assert octave_code(airybi(x)) == 'airy(2, x)'
+    assert octave_code(airybiprime(x)) == 'airy(3, x)'
+    assert octave_code(uppergamma(n, x)) == '(gammainc(x, n, \'upper\').*gamma(n))'
+    assert octave_code(lowergamma(n, x)) == '(gammainc(x, n).*gamma(n))'
+    assert octave_code(z**lowergamma(n, x)) == 'z.^(gammainc(x, n).*gamma(n))'
+    assert octave_code(jn(n, x)) == 'sqrt(2)*sqrt(pi)*sqrt(1./x).*besselj(n + 1/2, x)/2'
+    assert octave_code(yn(n, x)) == 'sqrt(2)*sqrt(pi)*sqrt(1./x).*bessely(n + 1/2, x)/2'
+    assert octave_code(LambertW(x)) == 'lambertw(x)'
+    assert octave_code(LambertW(x, n)) == 'lambertw(n, x)'
+
+    # Automatic rewrite
+    assert octave_code(Ei(x)) == '(logint(exp(x)))'
+    assert octave_code(dirichlet_eta(x)) == '(((x == 1).*(log(2)) + (~(x == 1)).*((1 - 2.^(1 - x)).*zeta(x))))'
+    assert octave_code(riemann_xi(x)) == '(pi.^(-x/2).*x.*(x - 1).*gamma(x/2).*zeta(x)/2)'
+
+
+def test_MatrixElement_printing():
+    # test cases for issue #11821
+    A = MatrixSymbol("A", 1, 3)
+    B = MatrixSymbol("B", 1, 3)
+    C = MatrixSymbol("C", 1, 3)
+
+    assert mcode(A[0, 0]) == "A(1, 1)"
+    assert mcode(3 * A[0, 0]) == "3*A(1, 1)"
+
+    F = C[0, 0].subs(C, A - B)
+    assert mcode(F) == "(A - B)(1, 1)"
+
+
+def test_zeta_printing_issue_14820():
+    assert octave_code(zeta(x)) == 'zeta(x)'
+    with raises(NotImplementedError):
+        octave_code(zeta(x, y))
+
+
+def test_automatic_rewrite():
+    assert octave_code(Li(x)) == '(logint(x) - logint(2))'
+    assert octave_code(erf2(x, y)) == '(-erf(x) + erf(y))'
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_precedence.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_precedence.py
new file mode 100644
index 0000000000000000000000000000000000000000..d08ea07483857e8c2ee7f930aa53d2dacdc58193
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_precedence.py
@@ -0,0 +1,128 @@
+from sympy.concrete.products import Product
+from sympy.concrete.summations import Sum
+from sympy.core.function import Derivative, Function
+from sympy.core.numbers import Integer, Rational, Float, oo
+from sympy.core.relational import Rel
+from sympy.core.symbol import symbols
+from sympy.functions import sin
+from sympy.integrals.integrals import Integral
+from sympy.series.order import Order
+
+from sympy.printing.precedence import precedence, PRECEDENCE
+
+x, y = symbols("x,y")
+
+
+def test_Add():
+    assert precedence(x + y) == PRECEDENCE["Add"]
+    assert precedence(x*y + 1) == PRECEDENCE["Add"]
+
+
+def test_Function():
+    assert precedence(sin(x)) == PRECEDENCE["Func"]
+
+def test_Derivative():
+    assert precedence(Derivative(x, y)) == PRECEDENCE["Atom"]
+
+def test_Integral():
+    assert precedence(Integral(x, y)) == PRECEDENCE["Atom"]
+
+
+def test_Mul():
+    assert precedence(x*y) == PRECEDENCE["Mul"]
+    assert precedence(-x*y) == PRECEDENCE["Add"]
+
+
+def test_Number():
+    assert precedence(Integer(0)) == PRECEDENCE["Atom"]
+    assert precedence(Integer(1)) == PRECEDENCE["Atom"]
+    assert precedence(Integer(-1)) == PRECEDENCE["Add"]
+    assert precedence(Integer(10)) == PRECEDENCE["Atom"]
+    assert precedence(Rational(5, 2)) == PRECEDENCE["Mul"]
+    assert precedence(Rational(-5, 2)) == PRECEDENCE["Add"]
+    assert precedence(Float(5)) == PRECEDENCE["Atom"]
+    assert precedence(Float(-5)) == PRECEDENCE["Add"]
+    assert precedence(oo) == PRECEDENCE["Atom"]
+    assert precedence(-oo) == PRECEDENCE["Add"]
+
+
+def test_Order():
+    assert precedence(Order(x)) == PRECEDENCE["Atom"]
+
+
+def test_Pow():
+    assert precedence(x**y) == PRECEDENCE["Pow"]
+    assert precedence(-x**y) == PRECEDENCE["Add"]
+    assert precedence(x**-y) == PRECEDENCE["Pow"]
+
+
+def test_Product():
+    assert precedence(Product(x, (x, y, y + 1))) == PRECEDENCE["Atom"]
+
+
+def test_Relational():
+    assert precedence(Rel(x + y, y, "<")) == PRECEDENCE["Relational"]
+
+
+def test_Sum():
+    assert precedence(Sum(x, (x, y, y + 1))) == PRECEDENCE["Atom"]
+
+
+def test_Symbol():
+    assert precedence(x) == PRECEDENCE["Atom"]
+
+
+def test_And_Or():
+    # precedence relations between logical operators, ...
+    assert precedence(x & y) > precedence(x | y)
+    assert precedence(~y) > precedence(x & y)
+    # ... and with other operators (cfr. other programming languages)
+    assert precedence(x + y) > precedence(x | y)
+    assert precedence(x + y) > precedence(x & y)
+    assert precedence(x*y) > precedence(x | y)
+    assert precedence(x*y) > precedence(x & y)
+    assert precedence(~y) > precedence(x*y)
+    assert precedence(~y) > precedence(x - y)
+    # double checks
+    assert precedence(x & y) == PRECEDENCE["And"]
+    assert precedence(x | y) == PRECEDENCE["Or"]
+    assert precedence(~y) == PRECEDENCE["Not"]
+
+
+def test_custom_function_precedence_comparison():
+    """
+    Test cases for custom functions with different precedence values,
+    specifically handling:
+    1. Functions with precedence < PRECEDENCE["Mul"] (50)
+    2. Functions with precedence = Func (70)
+
+    Key distinction:
+    1. Lower precedence functions (45) need parentheses: -2*(x F y)
+    2. Higher precedence functions (70) don't: -2*x F y
+    """
+    class LowPrecedenceF(Function):
+        precedence = PRECEDENCE["Mul"] - 5
+        def _sympystr(self, printer):
+            return f"{printer._print(self.args[0])} F {printer._print(self.args[1])}"
+
+    class HighPrecedenceF(Function):
+        precedence = PRECEDENCE["Func"]
+        def _sympystr(self, printer):
+            return f"{printer._print(self.args[0])} F {printer._print(self.args[1])}"
+
+    def test_low_precedence():
+        expr1 = 2 * LowPrecedenceF(x, y)
+        assert str(expr1) == "2*(x F y)"
+
+        expr2 = -2 * LowPrecedenceF(x, y)
+        assert str(expr2) == "-2*(x F y)"
+
+    def test_high_precedence():
+        expr1 = 2 * HighPrecedenceF(x, y)
+        assert str(expr1) == "2*x F y"
+
+        expr2 = -2 * HighPrecedenceF(x, y)
+        assert str(expr2) == "-2*x F y"
+
+    test_low_precedence()
+    test_high_precedence()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_preview.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_preview.py
new file mode 100644
index 0000000000000000000000000000000000000000..91771ceb0466d6b0fee00570426713d02da14872
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_preview.py
@@ -0,0 +1,38 @@
+# -*- coding: utf-8 -*-
+
+from sympy.core.relational import Eq
+from sympy.core.symbol import Symbol
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.printing.preview import preview
+
+from io import BytesIO
+
+
+def test_preview():
+    x = Symbol('x')
+    obj = BytesIO()
+    try:
+        preview(x, output='png', viewer='BytesIO', outputbuffer=obj)
+    except RuntimeError:
+        pass  # latex not installed on CI server
+
+
+def test_preview_unicode_symbol():
+    # issue 9107
+    a = Symbol('α')
+    obj = BytesIO()
+    try:
+        preview(a, output='png', viewer='BytesIO', outputbuffer=obj)
+    except RuntimeError:
+        pass  # latex not installed on CI server
+
+
+def test_preview_latex_construct_in_expr():
+    # see PR 9801
+    x = Symbol('x')
+    pw = Piecewise((1, Eq(x, 0)), (0, True))
+    obj = BytesIO()
+    try:
+        preview(pw, output='png', viewer='BytesIO', outputbuffer=obj)
+    except RuntimeError:
+        pass  # latex not installed on CI server
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_pycode.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_pycode.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c38fe81d830149cdce6b55f15e6e07513fdd146
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_pycode.py
@@ -0,0 +1,493 @@
+from sympy import Not
+from sympy.codegen import Assignment
+from sympy.codegen.ast import none
+from sympy.codegen.cfunctions import expm1, log1p
+from sympy.codegen.scipy_nodes import cosm1
+from sympy.codegen.matrix_nodes import MatrixSolve
+from sympy.core import Expr, Mod, symbols, Eq, Le, Gt, zoo, oo, Rational, Pow
+from sympy.core.function import Derivative
+from sympy.core.numbers import pi
+from sympy.core.singleton import S
+from sympy.functions import acos, KroneckerDelta, Piecewise, sign, sqrt, Min, Max, cot, acsch, asec, coth, sec, log, sin, cos, tan, asin, atan, sinh, cosh, tanh, asinh, acosh, atanh
+from sympy.functions.elementary.trigonometric import atan2
+from sympy.logic import And, Or
+from sympy.matrices import SparseMatrix, MatrixSymbol, Identity
+from sympy.printing.codeprinter import PrintMethodNotImplementedError
+from sympy.printing.pycode import (
+    MpmathPrinter, CmathPrinter, PythonCodePrinter, pycode, SymPyPrinter
+)
+from sympy.printing.tensorflow import TensorflowPrinter
+from sympy.printing.numpy import NumPyPrinter, SciPyPrinter
+from sympy.testing.pytest import raises, skip
+from sympy.tensor import IndexedBase, Idx
+from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayDiagonal, ArrayContraction, ZeroArray, OneArray
+from sympy.external import import_module
+from sympy.functions.special.gamma_functions import loggamma
+
+
+
+x, y, z = symbols('x y z')
+p = IndexedBase("p")
+
+
+def test_PythonCodePrinter():
+    prntr = PythonCodePrinter()
+
+    assert not prntr.module_imports
+
+    assert prntr.doprint(x**y) == 'x**y'
+    assert prntr.doprint(Mod(x, 2)) == 'x % 2'
+    assert prntr.doprint(-Mod(x, y)) == '-(x % y)'
+    assert prntr.doprint(Mod(-x, y)) == '(-x) % y'
+    assert prntr.doprint(And(x, y)) == 'x and y'
+    assert prntr.doprint(Or(x, y)) == 'x or y'
+    assert prntr.doprint(1/(x+y)) == '1/(x + y)'
+    assert prntr.doprint(Not(x)) == 'not x'
+    assert not prntr.module_imports
+
+    assert prntr.doprint(pi) == 'math.pi'
+    assert prntr.module_imports == {'math': {'pi'}}
+
+    assert prntr.doprint(x**Rational(1, 2)) == 'math.sqrt(x)'
+    assert prntr.doprint(sqrt(x)) == 'math.sqrt(x)'
+    assert prntr.module_imports == {'math': {'pi', 'sqrt'}}
+
+    assert prntr.doprint(acos(x)) == 'math.acos(x)'
+    assert prntr.doprint(cot(x)) == '(1/math.tan(x))'
+    assert prntr.doprint(coth(x)) == '((math.exp(x) + math.exp(-x))/(math.exp(x) - math.exp(-x)))'
+    assert prntr.doprint(asec(x)) == '(math.acos(1/x))'
+    assert prntr.doprint(acsch(x)) == '(math.log(math.sqrt(1 + x**(-2)) + 1/x))'
+
+    assert prntr.doprint(Assignment(x, 2)) == 'x = 2'
+    assert prntr.doprint(Piecewise((1, Eq(x, 0)),
+                        (2, x>6))) == '((1) if (x == 0) else (2) if (x > 6) else None)'
+    assert prntr.doprint(Piecewise((2, Le(x, 0)),
+                        (3, Gt(x, 0)), evaluate=False)) == '((2) if (x <= 0) else'\
+                                                        ' (3) if (x > 0) else None)'
+    assert prntr.doprint(sign(x)) == '(0.0 if x == 0 else math.copysign(1, x))'
+    assert prntr.doprint(p[0, 1]) == 'p[0, 1]'
+    assert prntr.doprint(KroneckerDelta(x,y)) == '(1 if x == y else 0)'
+
+    assert prntr.doprint((2,3)) == "(2, 3)"
+    assert prntr.doprint([2,3]) == "[2, 3]"
+
+    assert prntr.doprint(Min(x, y)) == "min(x, y)"
+    assert prntr.doprint(Max(x, y)) == "max(x, y)"
+
+
+def test_PythonCodePrinter_standard():
+    prntr = PythonCodePrinter()
+
+    assert prntr.standard == 'python3'
+
+    raises(ValueError, lambda: PythonCodePrinter({'standard':'python4'}))
+
+
+def test_CmathPrinter():
+    p = CmathPrinter()
+
+    assert p.doprint(sqrt(x)) == 'cmath.sqrt(x)'
+    assert p.doprint(log(x)) == 'cmath.log(x)'
+
+    assert p.doprint(sin(x)) == 'cmath.sin(x)'
+    assert p.doprint(cos(x)) == 'cmath.cos(x)'
+    assert p.doprint(tan(x)) == 'cmath.tan(x)'
+
+    assert p.doprint(asin(x)) == 'cmath.asin(x)'
+    assert p.doprint(acos(x)) == 'cmath.acos(x)'
+    assert p.doprint(atan(x)) == 'cmath.atan(x)'
+
+    assert p.doprint(sinh(x)) == 'cmath.sinh(x)'
+    assert p.doprint(cosh(x)) == 'cmath.cosh(x)'
+    assert p.doprint(tanh(x)) == 'cmath.tanh(x)'
+
+    assert p.doprint(asinh(x)) == 'cmath.asinh(x)'
+    assert p.doprint(acosh(x)) == 'cmath.acosh(x)'
+    assert p.doprint(atanh(x)) == 'cmath.atanh(x)'
+
+
+def test_MpmathPrinter():
+    p = MpmathPrinter()
+    assert p.doprint(sign(x)) == 'mpmath.sign(x)'
+    assert p.doprint(Rational(1, 2)) == 'mpmath.mpf(1)/mpmath.mpf(2)'
+
+    assert p.doprint(S.Exp1) == 'mpmath.e'
+    assert p.doprint(S.Pi) == 'mpmath.pi'
+    assert p.doprint(S.GoldenRatio) == 'mpmath.phi'
+    assert p.doprint(S.EulerGamma) == 'mpmath.euler'
+    assert p.doprint(S.NaN) == 'mpmath.nan'
+    assert p.doprint(S.Infinity) == 'mpmath.inf'
+    assert p.doprint(S.NegativeInfinity) == 'mpmath.ninf'
+    assert p.doprint(loggamma(x)) == 'mpmath.loggamma(x)'
+
+
+def test_NumPyPrinter():
+    from sympy.core.function import Lambda
+    from sympy.matrices.expressions.adjoint import Adjoint
+    from sympy.matrices.expressions.diagonal import (DiagMatrix, DiagonalMatrix, DiagonalOf)
+    from sympy.matrices.expressions.funcmatrix import FunctionMatrix
+    from sympy.matrices.expressions.hadamard import HadamardProduct
+    from sympy.matrices.expressions.kronecker import KroneckerProduct
+    from sympy.matrices.expressions.special import (OneMatrix, ZeroMatrix)
+    from sympy.abc import a, b
+    p = NumPyPrinter()
+    assert p.doprint(sign(x)) == 'numpy.sign(x)'
+    A = MatrixSymbol("A", 2, 2)
+    B = MatrixSymbol("B", 2, 2)
+    C = MatrixSymbol("C", 1, 5)
+    D = MatrixSymbol("D", 3, 4)
+    assert p.doprint(A**(-1)) == "numpy.linalg.inv(A)"
+    assert p.doprint(A**5) == "numpy.linalg.matrix_power(A, 5)"
+    assert p.doprint(Identity(3)) == "numpy.eye(3)"
+
+    u = MatrixSymbol('x', 2, 1)
+    v = MatrixSymbol('y', 2, 1)
+    assert p.doprint(MatrixSolve(A, u)) == 'numpy.linalg.solve(A, x)'
+    assert p.doprint(MatrixSolve(A, u) + v) == 'numpy.linalg.solve(A, x) + y'
+
+    assert p.doprint(ZeroMatrix(2, 3)) == "numpy.zeros((2, 3))"
+    assert p.doprint(OneMatrix(2, 3)) == "numpy.ones((2, 3))"
+    assert p.doprint(FunctionMatrix(4, 5, Lambda((a, b), a + b))) == \
+        "numpy.fromfunction(lambda a, b: a + b, (4, 5))"
+    assert p.doprint(HadamardProduct(A, B)) == "numpy.multiply(A, B)"
+    assert p.doprint(KroneckerProduct(A, B)) == "numpy.kron(A, B)"
+    assert p.doprint(Adjoint(A)) == "numpy.conjugate(numpy.transpose(A))"
+    assert p.doprint(DiagonalOf(A)) == "numpy.reshape(numpy.diag(A), (-1, 1))"
+    assert p.doprint(DiagMatrix(C)) == "numpy.diagflat(C)"
+    assert p.doprint(DiagonalMatrix(D)) == "numpy.multiply(D, numpy.eye(3, 4))"
+
+    # Workaround for numpy negative integer power errors
+    assert p.doprint(x**-1) == 'x**(-1.0)'
+    assert p.doprint(x**-2) == 'x**(-2.0)'
+
+    expr = Pow(2, -1, evaluate=False)
+    assert p.doprint(expr) == "2**(-1.0)"
+
+    assert p.doprint(S.Exp1) == 'numpy.e'
+    assert p.doprint(S.Pi) == 'numpy.pi'
+    assert p.doprint(S.EulerGamma) == 'numpy.euler_gamma'
+    assert p.doprint(S.NaN) == 'numpy.nan'
+    assert p.doprint(S.Infinity) == 'numpy.inf'
+    assert p.doprint(S.NegativeInfinity) == '-numpy.inf'
+
+    # Function rewriting operator precedence fix
+    assert p.doprint(sec(x)**2) == '(numpy.cos(x)**(-1.0))**2'
+
+
+def test_issue_18770():
+    numpy = import_module('numpy')
+    if not numpy:
+        skip("numpy not installed.")
+
+    from sympy.functions.elementary.miscellaneous import (Max, Min)
+    from sympy.utilities.lambdify import lambdify
+
+    expr1 = Min(0.1*x + 3, x + 1, 0.5*x + 1)
+    func = lambdify(x, expr1, "numpy")
+    assert (func(numpy.linspace(0, 3, 3)) == [1.0, 1.75, 2.5 ]).all()
+    assert  func(4) == 3
+
+    expr1 = Max(x**2, x**3)
+    func = lambdify(x,expr1, "numpy")
+    assert (func(numpy.linspace(-1, 2, 4)) == [1, 0, 1, 8] ).all()
+    assert func(4) == 64
+
+
+def test_SciPyPrinter():
+    p = SciPyPrinter()
+    expr = acos(x)
+    assert 'numpy' not in p.module_imports
+    assert p.doprint(expr) == 'numpy.arccos(x)'
+    assert 'numpy' in p.module_imports
+    assert not any(m.startswith('scipy') for m in p.module_imports)
+    smat = SparseMatrix(2, 5, {(0, 1): 3})
+    assert p.doprint(smat) == \
+        'scipy.sparse.coo_matrix(([3], ([0], [1])), shape=(2, 5))'
+    assert 'scipy.sparse' in p.module_imports
+
+    assert p.doprint(S.GoldenRatio) == 'scipy.constants.golden_ratio'
+    assert p.doprint(S.Pi) == 'scipy.constants.pi'
+    assert p.doprint(S.Exp1) == 'numpy.e'
+
+
+def test_pycode_reserved_words():
+    s1, s2 = symbols('if else')
+    raises(ValueError, lambda: pycode(s1 + s2, error_on_reserved=True))
+    py_str = pycode(s1 + s2)
+    assert py_str in ('else_ + if_', 'if_ + else_')
+
+
+def test_issue_20762():
+    # Make sure pycode removes curly braces from subscripted variables
+    a_b, b, a_11 = symbols('a_{b} b a_{11}')
+    expr = a_b*b
+    assert pycode(expr) == 'a_b*b'
+    expr = a_11*b
+    assert pycode(expr) == 'a_11*b'
+
+
+def test_sqrt():
+    prntr = PythonCodePrinter()
+    assert prntr._print_Pow(sqrt(x), rational=False) == 'math.sqrt(x)'
+    assert prntr._print_Pow(1/sqrt(x), rational=False) == '1/math.sqrt(x)'
+
+    prntr = PythonCodePrinter({'standard' : 'python3'})
+    assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)'
+    assert prntr._print_Pow(1/sqrt(x), rational=True) == 'x**(-1/2)'
+
+    prntr = MpmathPrinter()
+    assert prntr._print_Pow(sqrt(x), rational=False) == 'mpmath.sqrt(x)'
+    assert prntr._print_Pow(sqrt(x), rational=True) == \
+        "x**(mpmath.mpf(1)/mpmath.mpf(2))"
+
+    prntr = NumPyPrinter()
+    assert prntr._print_Pow(sqrt(x), rational=False) == 'numpy.sqrt(x)'
+    assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)'
+
+    prntr = SciPyPrinter()
+    assert prntr._print_Pow(sqrt(x), rational=False) == 'numpy.sqrt(x)'
+    assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)'
+
+    prntr = SymPyPrinter()
+    assert prntr._print_Pow(sqrt(x), rational=False) == 'sympy.sqrt(x)'
+    assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)'
+
+
+def test_frac():
+    from sympy.functions.elementary.integers import frac
+
+    expr = frac(x)
+    prntr = NumPyPrinter()
+    assert prntr.doprint(expr) == 'numpy.mod(x, 1)'
+
+    prntr = SciPyPrinter()
+    assert prntr.doprint(expr) == 'numpy.mod(x, 1)'
+
+    prntr = PythonCodePrinter()
+    assert prntr.doprint(expr) == 'x % 1'
+
+    prntr = MpmathPrinter()
+    assert prntr.doprint(expr) == 'mpmath.frac(x)'
+
+    prntr = SymPyPrinter()
+    assert prntr.doprint(expr) == 'sympy.functions.elementary.integers.frac(x)'
+
+
+class CustomPrintedObject(Expr):
+    def _numpycode(self, printer):
+        return 'numpy'
+
+    def _mpmathcode(self, printer):
+        return 'mpmath'
+
+
+def test_printmethod():
+    obj = CustomPrintedObject()
+    assert NumPyPrinter().doprint(obj) == 'numpy'
+    assert MpmathPrinter().doprint(obj) == 'mpmath'
+
+
+def test_codegen_ast_nodes():
+    assert pycode(none) == 'None'
+
+
+def test_issue_14283():
+    prntr = PythonCodePrinter()
+
+    assert prntr.doprint(zoo) == "math.nan"
+    assert prntr.doprint(-oo) == "float('-inf')"
+
+
+def test_NumPyPrinter_print_seq():
+    n = NumPyPrinter()
+
+    assert n._print_seq(range(2)) == '(0, 1,)'
+
+
+def test_issue_16535_16536():
+    from sympy.functions.special.gamma_functions import (lowergamma, uppergamma)
+
+    a = symbols('a')
+    expr1 = lowergamma(a, x)
+    expr2 = uppergamma(a, x)
+
+    prntr = SciPyPrinter()
+    assert prntr.doprint(expr1) == 'scipy.special.gamma(a)*scipy.special.gammainc(a, x)'
+    assert prntr.doprint(expr2) == 'scipy.special.gamma(a)*scipy.special.gammaincc(a, x)'
+
+    p_numpy = NumPyPrinter()
+    p_pycode = PythonCodePrinter({'strict': False})
+
+    for expr in [expr1, expr2]:
+        with raises(NotImplementedError):
+            p_numpy.doprint(expr1)
+        assert "Not supported" in p_pycode.doprint(expr)
+
+
+def test_Integral():
+    from sympy.functions.elementary.exponential import exp
+    from sympy.integrals.integrals import Integral
+
+    single = Integral(exp(-x), (x, 0, oo))
+    double = Integral(x**2*exp(x*y), (x, -z, z), (y, 0, z))
+    indefinite = Integral(x**2, x)
+    evaluateat = Integral(x**2, (x, 1))
+
+    prntr = SciPyPrinter()
+    assert prntr.doprint(single) == 'scipy.integrate.quad(lambda x: numpy.exp(-x), 0, numpy.inf)[0]'
+    assert prntr.doprint(double) == 'scipy.integrate.nquad(lambda x, y: x**2*numpy.exp(x*y), ((-z, z), (0, z)))[0]'
+    raises(NotImplementedError, lambda: prntr.doprint(indefinite))
+    raises(NotImplementedError, lambda: prntr.doprint(evaluateat))
+
+    prntr = MpmathPrinter()
+    assert prntr.doprint(single) == 'mpmath.quad(lambda x: mpmath.exp(-x), (0, mpmath.inf))'
+    assert prntr.doprint(double) == 'mpmath.quad(lambda x, y: x**2*mpmath.exp(x*y), (-z, z), (0, z))'
+    raises(NotImplementedError, lambda: prntr.doprint(indefinite))
+    raises(NotImplementedError, lambda: prntr.doprint(evaluateat))
+
+
+def test_fresnel_integrals():
+    from sympy.functions.special.error_functions import (fresnelc, fresnels)
+
+    expr1 = fresnelc(x)
+    expr2 = fresnels(x)
+
+    prntr = SciPyPrinter()
+    assert prntr.doprint(expr1) == 'scipy.special.fresnel(x)[1]'
+    assert prntr.doprint(expr2) == 'scipy.special.fresnel(x)[0]'
+
+    p_numpy = NumPyPrinter()
+    p_pycode = PythonCodePrinter()
+    p_mpmath = MpmathPrinter()
+    for expr in [expr1, expr2]:
+        with raises(NotImplementedError):
+            p_numpy.doprint(expr)
+        with raises(NotImplementedError):
+            p_pycode.doprint(expr)
+
+    assert p_mpmath.doprint(expr1) == 'mpmath.fresnelc(x)'
+    assert p_mpmath.doprint(expr2) == 'mpmath.fresnels(x)'
+
+
+def test_beta():
+    from sympy.functions.special.beta_functions import beta
+
+    expr = beta(x, y)
+
+    prntr = SciPyPrinter()
+    assert prntr.doprint(expr) == 'scipy.special.beta(x, y)'
+
+    prntr = NumPyPrinter()
+    assert prntr.doprint(expr) == '(math.gamma(x)*math.gamma(y)/math.gamma(x + y))'
+
+    prntr = PythonCodePrinter()
+    assert prntr.doprint(expr) == '(math.gamma(x)*math.gamma(y)/math.gamma(x + y))'
+
+    prntr = PythonCodePrinter({'allow_unknown_functions': True})
+    assert prntr.doprint(expr) == '(math.gamma(x)*math.gamma(y)/math.gamma(x + y))'
+
+    prntr = MpmathPrinter()
+    assert prntr.doprint(expr) ==  'mpmath.beta(x, y)'
+
+def test_airy():
+    from sympy.functions.special.bessel import (airyai, airybi)
+
+    expr1 = airyai(x)
+    expr2 = airybi(x)
+
+    prntr = SciPyPrinter()
+    assert prntr.doprint(expr1) == 'scipy.special.airy(x)[0]'
+    assert prntr.doprint(expr2) == 'scipy.special.airy(x)[2]'
+
+    prntr = NumPyPrinter({'strict': False})
+    assert "Not supported" in prntr.doprint(expr1)
+    assert "Not supported" in prntr.doprint(expr2)
+
+    prntr = PythonCodePrinter({'strict': False})
+    assert "Not supported" in prntr.doprint(expr1)
+    assert "Not supported" in prntr.doprint(expr2)
+
+def test_airy_prime():
+    from sympy.functions.special.bessel import (airyaiprime, airybiprime)
+
+    expr1 = airyaiprime(x)
+    expr2 = airybiprime(x)
+
+    prntr = SciPyPrinter()
+    assert prntr.doprint(expr1) == 'scipy.special.airy(x)[1]'
+    assert prntr.doprint(expr2) == 'scipy.special.airy(x)[3]'
+
+    prntr = NumPyPrinter({'strict': False})
+    assert "Not supported" in prntr.doprint(expr1)
+    assert "Not supported" in prntr.doprint(expr2)
+
+    prntr = PythonCodePrinter({'strict': False})
+    assert "Not supported" in prntr.doprint(expr1)
+    assert "Not supported" in prntr.doprint(expr2)
+
+
+def test_numerical_accuracy_functions():
+    prntr = SciPyPrinter()
+    assert prntr.doprint(expm1(x)) == 'numpy.expm1(x)'
+    assert prntr.doprint(log1p(x)) == 'numpy.log1p(x)'
+    assert prntr.doprint(cosm1(x)) == 'scipy.special.cosm1(x)'
+
+def test_array_printer():
+    A = ArraySymbol('A', (4,4,6,6,6))
+    I = IndexedBase('I')
+    i,j,k = Idx('i', (0,1)), Idx('j', (2,3)), Idx('k', (4,5))
+
+    prntr = NumPyPrinter()
+    assert prntr.doprint(ZeroArray(5)) == 'numpy.zeros((5,))'
+    assert prntr.doprint(OneArray(5)) == 'numpy.ones((5,))'
+    assert prntr.doprint(ArrayContraction(A, [2,3])) == 'numpy.einsum("abccd->abd", A)'
+    assert prntr.doprint(I) == 'I'
+    assert prntr.doprint(ArrayDiagonal(A, [2,3,4])) == 'numpy.einsum("abccc->abc", A)'
+    assert prntr.doprint(ArrayDiagonal(A, [0,1], [2,3])) == 'numpy.einsum("aabbc->cab", A)'
+    assert prntr.doprint(ArrayContraction(A, [2], [3])) == 'numpy.einsum("abcde->abe", A)'
+    assert prntr.doprint(Assignment(I[i,j,k], I[i,j,k])) == 'I = I'
+
+    prntr = TensorflowPrinter()
+    assert prntr.doprint(ZeroArray(5)) == 'tensorflow.zeros((5,))'
+    assert prntr.doprint(OneArray(5)) == 'tensorflow.ones((5,))'
+    assert prntr.doprint(ArrayContraction(A, [2,3])) == 'tensorflow.linalg.einsum("abccd->abd", A)'
+    assert prntr.doprint(I) == 'I'
+    assert prntr.doprint(ArrayDiagonal(A, [2,3,4])) == 'tensorflow.linalg.einsum("abccc->abc", A)'
+    assert prntr.doprint(ArrayDiagonal(A, [0,1], [2,3])) == 'tensorflow.linalg.einsum("aabbc->cab", A)'
+    assert prntr.doprint(ArrayContraction(A, [2], [3])) == 'tensorflow.linalg.einsum("abcde->abe", A)'
+    assert prntr.doprint(Assignment(I[i,j,k], I[i,j,k])) == 'I = I'
+
+
+def test_custom_Derivative_methods():
+    class MyPrinter(SciPyPrinter):
+        def _print_Derivative_cosm1(self, args, seq_orders):
+            arg, = args
+            order, = seq_orders
+            return 'my_custom_cosm1(%s, deriv_order=%d)' % (self._print(arg), order)
+
+        def _print_Derivative_atan2(self, args, seq_orders):
+            arg1, arg2 = args
+            ord1, ord2 = seq_orders
+            return 'my_custom_atan2(%s, %s, deriv1=%d, deriv2=%d)' % (
+                self._print(arg1), self._print(arg2), ord1, ord2
+            )
+
+    p = MyPrinter()
+    cosm1_1 = cosm1(x).diff(x, evaluate=False)
+    assert p.doprint(cosm1_1) == 'my_custom_cosm1(x, deriv_order=1)'
+    atan2_2_3 = atan2(x, y).diff(x, 2, y, 3, evaluate=False)
+    assert p.doprint(atan2_2_3) == 'my_custom_atan2(x, y, deriv1=2, deriv2=3)'
+
+    try:
+        p.doprint(expm1(x).diff(x, evaluate=False))
+    except PrintMethodNotImplementedError as e:
+        assert '_print_Derivative_expm1' in repr(e)
+    else:
+        assert False  # should have thrown
+
+    try:
+        p.doprint(Derivative(cosm1(x**2),x))
+    except ValueError as e:
+        assert '_print_Derivative(' in repr(e)
+    else:
+        assert False  # should have thrown
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_python.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_python.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb94a662be90934a672d08b3de44a22e2580d8b6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_python.py
@@ -0,0 +1,203 @@
+from sympy.core.function import (Derivative, Function)
+from sympy.core.numbers import (I, Rational, oo, pi)
+from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne)
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.functions.elementary.complexes import (Abs, conjugate)
+from sympy.functions.elementary.exponential import (exp, log)
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import sin
+from sympy.integrals.integrals import Integral
+from sympy.matrices.dense import Matrix
+from sympy.series.limits import limit
+
+from sympy.printing.python import python
+
+from sympy.testing.pytest import raises, XFAIL
+
+x, y = symbols('x,y')
+th = Symbol('theta')
+ph = Symbol('phi')
+
+
+def test_python_basic():
+    # Simple numbers/symbols
+    assert python(-Rational(1)/2) == "e = Rational(-1, 2)"
+    assert python(-Rational(13)/22) == "e = Rational(-13, 22)"
+    assert python(oo) == "e = oo"
+
+    # Powers
+    assert python(x**2) == "x = Symbol(\'x\')\ne = x**2"
+    assert python(1/x) == "x = Symbol('x')\ne = 1/x"
+    assert python(y*x**-2) == "y = Symbol('y')\nx = Symbol('x')\ne = y/x**2"
+    assert python(
+        x**Rational(-5, 2)) == "x = Symbol('x')\ne = x**Rational(-5, 2)"
+
+    # Sums of terms
+    assert python(x**2 + x + 1) in [
+        "x = Symbol('x')\ne = 1 + x + x**2",
+        "x = Symbol('x')\ne = x + x**2 + 1",
+        "x = Symbol('x')\ne = x**2 + x + 1", ]
+    assert python(1 - x) in [
+        "x = Symbol('x')\ne = 1 - x",
+        "x = Symbol('x')\ne = -x + 1"]
+    assert python(1 - 2*x) in [
+        "x = Symbol('x')\ne = 1 - 2*x",
+        "x = Symbol('x')\ne = -2*x + 1"]
+    assert python(1 - Rational(3, 2)*y/x) in [
+        "y = Symbol('y')\nx = Symbol('x')\ne = 1 - 3/2*y/x",
+        "y = Symbol('y')\nx = Symbol('x')\ne = -3/2*y/x + 1",
+        "y = Symbol('y')\nx = Symbol('x')\ne = 1 - 3*y/(2*x)"]
+
+    # Multiplication
+    assert python(x/y) == "x = Symbol('x')\ny = Symbol('y')\ne = x/y"
+    assert python(-x/y) == "x = Symbol('x')\ny = Symbol('y')\ne = -x/y"
+    assert python((x + 2)/y) in [
+        "y = Symbol('y')\nx = Symbol('x')\ne = 1/y*(2 + x)",
+        "y = Symbol('y')\nx = Symbol('x')\ne = 1/y*(x + 2)",
+        "x = Symbol('x')\ny = Symbol('y')\ne = 1/y*(2 + x)",
+        "x = Symbol('x')\ny = Symbol('y')\ne = (2 + x)/y",
+        "x = Symbol('x')\ny = Symbol('y')\ne = (x + 2)/y"]
+    assert python((1 + x)*y) in [
+        "y = Symbol('y')\nx = Symbol('x')\ne = y*(1 + x)",
+        "y = Symbol('y')\nx = Symbol('x')\ne = y*(x + 1)", ]
+
+    # Check for proper placement of negative sign
+    assert python(-5*x/(x + 10)) == "x = Symbol('x')\ne = -5*x/(x + 10)"
+    assert python(1 - Rational(3, 2)*(x + 1)) in [
+        "x = Symbol('x')\ne = Rational(-3, 2)*x + Rational(-1, 2)",
+        "x = Symbol('x')\ne = -3*x/2 + Rational(-1, 2)",
+        "x = Symbol('x')\ne = -3*x/2 + Rational(-1, 2)"
+    ]
+
+
+def test_python_keyword_symbol_name_escaping():
+    # Check for escaping of keywords
+    assert python(
+        5*Symbol("lambda")) == "lambda_ = Symbol('lambda')\ne = 5*lambda_"
+    assert (python(5*Symbol("lambda") + 7*Symbol("lambda_")) ==
+            "lambda__ = Symbol('lambda')\nlambda_ = Symbol('lambda_')\ne = 7*lambda_ + 5*lambda__")
+    assert (python(5*Symbol("for") + Function("for_")(8)) ==
+            "for__ = Symbol('for')\nfor_ = Function('for_')\ne = 5*for__ + for_(8)")
+
+
+def test_python_keyword_function_name_escaping():
+    assert python(
+        5*Function("for")(8)) == "for_ = Function('for')\ne = 5*for_(8)"
+
+
+def test_python_relational():
+    assert python(Eq(x, y)) == "x = Symbol('x')\ny = Symbol('y')\ne = Eq(x, y)"
+    assert python(Ge(x, y)) == "x = Symbol('x')\ny = Symbol('y')\ne = x >= y"
+    assert python(Le(x, y)) == "x = Symbol('x')\ny = Symbol('y')\ne = x <= y"
+    assert python(Gt(x, y)) == "x = Symbol('x')\ny = Symbol('y')\ne = x > y"
+    assert python(Lt(x, y)) == "x = Symbol('x')\ny = Symbol('y')\ne = x < y"
+    assert python(Ne(x/(y + 1), y**2)) in [
+        "x = Symbol('x')\ny = Symbol('y')\ne = Ne(x/(1 + y), y**2)",
+        "x = Symbol('x')\ny = Symbol('y')\ne = Ne(x/(y + 1), y**2)"]
+
+
+def test_python_functions():
+    # Simple
+    assert python(2*x + exp(x)) in "x = Symbol('x')\ne = 2*x + exp(x)"
+    assert python(sqrt(2)) == 'e = sqrt(2)'
+    assert python(2**Rational(1, 3)) == 'e = 2**Rational(1, 3)'
+    assert python(sqrt(2 + pi)) == 'e = sqrt(2 + pi)'
+    assert python((2 + pi)**Rational(1, 3)) == 'e = (2 + pi)**Rational(1, 3)'
+    assert python(2**Rational(1, 4)) == 'e = 2**Rational(1, 4)'
+    assert python(Abs(x)) == "x = Symbol('x')\ne = Abs(x)"
+    assert python(
+        Abs(x/(x**2 + 1))) in ["x = Symbol('x')\ne = Abs(x/(1 + x**2))",
+            "x = Symbol('x')\ne = Abs(x/(x**2 + 1))"]
+
+    # Univariate/Multivariate functions
+    f = Function('f')
+    assert python(f(x)) == "x = Symbol('x')\nf = Function('f')\ne = f(x)"
+    assert python(f(x, y)) == "x = Symbol('x')\ny = Symbol('y')\nf = Function('f')\ne = f(x, y)"
+    assert python(f(x/(y + 1), y)) in [
+        "x = Symbol('x')\ny = Symbol('y')\nf = Function('f')\ne = f(x/(1 + y), y)",
+        "x = Symbol('x')\ny = Symbol('y')\nf = Function('f')\ne = f(x/(y + 1), y)"]
+
+    # Nesting of square roots
+    assert python(sqrt((sqrt(x + 1)) + 1)) in [
+        "x = Symbol('x')\ne = sqrt(1 + sqrt(1 + x))",
+        "x = Symbol('x')\ne = sqrt(sqrt(x + 1) + 1)"]
+
+    # Nesting of powers
+    assert python((((x + 1)**Rational(1, 3)) + 1)**Rational(1, 3)) in [
+        "x = Symbol('x')\ne = (1 + (1 + x)**Rational(1, 3))**Rational(1, 3)",
+        "x = Symbol('x')\ne = ((x + 1)**Rational(1, 3) + 1)**Rational(1, 3)"]
+
+    # Function powers
+    assert python(sin(x)**2) == "x = Symbol('x')\ne = sin(x)**2"
+
+
+@XFAIL
+def test_python_functions_conjugates():
+    a, b = map(Symbol, 'ab')
+    assert python( conjugate(a + b*I) ) == '_     _\na - I*b'
+    assert python( conjugate(exp(a + b*I)) ) == ' _     _\n a - I*b\ne       '
+
+
+def test_python_derivatives():
+    # Simple
+    f_1 = Derivative(log(x), x, evaluate=False)
+    assert python(f_1) == "x = Symbol('x')\ne = Derivative(log(x), x)"
+
+    f_2 = Derivative(log(x), x, evaluate=False) + x
+    assert python(f_2) == "x = Symbol('x')\ne = x + Derivative(log(x), x)"
+
+    # Multiple symbols
+    f_3 = Derivative(log(x) + x**2, x, y, evaluate=False)
+    assert python(f_3) == \
+        "x = Symbol('x')\ny = Symbol('y')\ne = Derivative(x**2 + log(x), x, y)"
+
+    f_4 = Derivative(2*x*y, y, x, evaluate=False) + x**2
+    assert python(f_4) in [
+        "x = Symbol('x')\ny = Symbol('y')\ne = x**2 + Derivative(2*x*y, y, x)",
+        "x = Symbol('x')\ny = Symbol('y')\ne = Derivative(2*x*y, y, x) + x**2"]
+
+
+def test_python_integrals():
+    # Simple
+    f_1 = Integral(log(x), x)
+    assert python(f_1) == "x = Symbol('x')\ne = Integral(log(x), x)"
+
+    f_2 = Integral(x**2, x)
+    assert python(f_2) == "x = Symbol('x')\ne = Integral(x**2, x)"
+
+    # Double nesting of pow
+    f_3 = Integral(x**(2**x), x)
+    assert python(f_3) == "x = Symbol('x')\ne = Integral(x**(2**x), x)"
+
+    # Definite integrals
+    f_4 = Integral(x**2, (x, 1, 2))
+    assert python(f_4) == "x = Symbol('x')\ne = Integral(x**2, (x, 1, 2))"
+
+    f_5 = Integral(x**2, (x, Rational(1, 2), 10))
+    assert python(
+        f_5) == "x = Symbol('x')\ne = Integral(x**2, (x, Rational(1, 2), 10))"
+
+    # Nested integrals
+    f_6 = Integral(x**2*y**2, x, y)
+    assert python(f_6) == "x = Symbol('x')\ny = Symbol('y')\ne = Integral(x**2*y**2, x, y)"
+
+
+def test_python_matrix():
+    p = python(Matrix([[x**2+1, 1], [y, x+y]]))
+    s = "x = Symbol('x')\ny = Symbol('y')\ne = MutableDenseMatrix([[x**2 + 1, 1], [y, x + y]])"
+    assert p == s
+
+def test_python_limits():
+    assert python(limit(x, x, oo)) == 'e = oo'
+    assert python(limit(x**2, x, 0)) == 'e = 0'
+
+def test_issue_20762():
+    # Make sure Python removes curly braces from subscripted variables
+    a_b = Symbol('a_{b}')
+    b = Symbol('b')
+    expr = a_b*b
+    assert python(expr) == "a_b = Symbol('a_{b}')\nb = Symbol('b')\ne = a_b*b"
+
+
+def test_settings():
+    raises(TypeError, lambda: python(x, method="garbage"))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_rcode.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_rcode.py
new file mode 100644
index 0000000000000000000000000000000000000000..a83235b0654c6bf24c30846dbf68678d29cd3c80
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_rcode.py
@@ -0,0 +1,476 @@
+from sympy.core import (S, pi, oo, Symbol, symbols, Rational, Integer,
+                        GoldenRatio, EulerGamma, Catalan, Lambda, Dummy)
+from sympy.functions import (Piecewise, sin, cos, Abs, exp, ceiling, sqrt,
+                             gamma, sign, Max, Min, factorial, beta)
+from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne)
+from sympy.sets import Range
+from sympy.logic import ITE
+from sympy.codegen import For, aug_assign, Assignment
+from sympy.testing.pytest import raises
+from sympy.printing.rcode import RCodePrinter
+from sympy.utilities.lambdify import implemented_function
+from sympy.tensor import IndexedBase, Idx
+from sympy.matrices import Matrix, MatrixSymbol
+
+from sympy.printing.rcode import rcode
+
+x, y, z = symbols('x,y,z')
+
+
+def test_printmethod():
+    class fabs(Abs):
+        def _rcode(self, printer):
+            return "abs(%s)" % printer._print(self.args[0])
+
+    assert rcode(fabs(x)) == "abs(x)"
+
+
+def test_rcode_sqrt():
+    assert rcode(sqrt(x)) == "sqrt(x)"
+    assert rcode(x**0.5) == "sqrt(x)"
+    assert rcode(sqrt(x)) == "sqrt(x)"
+
+
+def test_rcode_Pow():
+    assert rcode(x**3) == "x^3"
+    assert rcode(x**(y**3)) == "x^(y^3)"
+    g = implemented_function('g', Lambda(x, 2*x))
+    assert rcode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \
+        "(3.5*2*x)^(-x + y^x)/(x^2 + y)"
+    assert rcode(x**-1.0) == '1.0/x'
+    assert rcode(x**Rational(2, 3)) == 'x^(2.0/3.0)'
+    _cond_cfunc = [(lambda base, exp: exp.is_integer, "dpowi"),
+                   (lambda base, exp: not exp.is_integer, "pow")]
+    assert rcode(x**3, user_functions={'Pow': _cond_cfunc}) == 'dpowi(x, 3)'
+    assert rcode(x**3.2, user_functions={'Pow': _cond_cfunc}) == 'pow(x, 3.2)'
+
+
+def test_rcode_Max():
+    # Test for gh-11926
+    assert rcode(Max(x,x*x),user_functions={"Max":"my_max", "Pow":"my_pow"}) == 'my_max(x, my_pow(x, 2))'
+
+
+def test_rcode_constants_mathh():
+    assert rcode(exp(1)) == "exp(1)"
+    assert rcode(pi) == "pi"
+    assert rcode(oo) == "Inf"
+    assert rcode(-oo) == "-Inf"
+
+
+def test_rcode_constants_other():
+    assert rcode(2*GoldenRatio) == "GoldenRatio = 1.61803398874989;\n2*GoldenRatio"
+    assert rcode(
+        2*Catalan) == "Catalan = 0.915965594177219;\n2*Catalan"
+    assert rcode(2*EulerGamma) == "EulerGamma = 0.577215664901533;\n2*EulerGamma"
+
+
+def test_rcode_Rational():
+    assert rcode(Rational(3, 7)) == "3.0/7.0"
+    assert rcode(Rational(18, 9)) == "2"
+    assert rcode(Rational(3, -7)) == "-3.0/7.0"
+    assert rcode(Rational(-3, -7)) == "3.0/7.0"
+    assert rcode(x + Rational(3, 7)) == "x + 3.0/7.0"
+    assert rcode(Rational(3, 7)*x) == "(3.0/7.0)*x"
+
+
+def test_rcode_Integer():
+    assert rcode(Integer(67)) == "67"
+    assert rcode(Integer(-1)) == "-1"
+
+
+def test_rcode_functions():
+    assert rcode(sin(x) ** cos(x)) == "sin(x)^cos(x)"
+    assert rcode(factorial(x) + gamma(y)) == "factorial(x) + gamma(y)"
+    assert rcode(beta(Min(x, y), Max(x, y))) == "beta(min(x, y), max(x, y))"
+
+
+def test_rcode_inline_function():
+    x = symbols('x')
+    g = implemented_function('g', Lambda(x, 2*x))
+    assert rcode(g(x)) == "2*x"
+    g = implemented_function('g', Lambda(x, 2*x/Catalan))
+    assert rcode(
+        g(x)) == "Catalan = %s;\n2*x/Catalan" % Catalan.n()
+    A = IndexedBase('A')
+    i = Idx('i', symbols('n', integer=True))
+    g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x)))
+    res=rcode(g(A[i]), assign_to=A[i])
+    ref=(
+        "for (i in 1:n){\n"
+        "   A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n"
+        "}"
+    )
+    assert res == ref
+
+
+def test_rcode_exceptions():
+    assert rcode(ceiling(x)) == "ceiling(x)"
+    assert rcode(Abs(x)) == "abs(x)"
+    assert rcode(gamma(x)) == "gamma(x)"
+
+
+def test_rcode_user_functions():
+    x = symbols('x', integer=False)
+    n = symbols('n', integer=True)
+    custom_functions = {
+        "ceiling": "myceil",
+        "Abs": [(lambda x: not x.is_integer, "fabs"), (lambda x: x.is_integer, "abs")],
+    }
+    assert rcode(ceiling(x), user_functions=custom_functions) == "myceil(x)"
+    assert rcode(Abs(x), user_functions=custom_functions) == "fabs(x)"
+    assert rcode(Abs(n), user_functions=custom_functions) == "abs(n)"
+
+
+def test_rcode_boolean():
+    assert rcode(True) == "True"
+    assert rcode(S.true) == "True"
+    assert rcode(False) == "False"
+    assert rcode(S.false) == "False"
+    assert rcode(x & y) == "x & y"
+    assert rcode(x | y) == "x | y"
+    assert rcode(~x) == "!x"
+    assert rcode(x & y & z) == "x & y & z"
+    assert rcode(x | y | z) == "x | y | z"
+    assert rcode((x & y) | z) == "z | x & y"
+    assert rcode((x | y) & z) == "z & (x | y)"
+
+def test_rcode_Relational():
+    assert rcode(Eq(x, y)) == "x == y"
+    assert rcode(Ne(x, y)) == "x != y"
+    assert rcode(Le(x, y)) == "x <= y"
+    assert rcode(Lt(x, y)) == "x < y"
+    assert rcode(Gt(x, y)) == "x > y"
+    assert rcode(Ge(x, y)) == "x >= y"
+
+
+def test_rcode_Piecewise():
+    expr = Piecewise((x, x < 1), (x**2, True))
+    res=rcode(expr)
+    ref="ifelse(x < 1,x,x^2)"
+    assert res == ref
+    tau=Symbol("tau")
+    res=rcode(expr,tau)
+    ref="tau = ifelse(x < 1,x,x^2);"
+    assert res == ref
+
+    expr = 2*Piecewise((x, x < 1), (x**2, x<2), (x**3,True))
+    assert rcode(expr) == "2*ifelse(x < 1,x,ifelse(x < 2,x^2,x^3))"
+    res = rcode(expr, assign_to='c')
+    assert res == "c = 2*ifelse(x < 1,x,ifelse(x < 2,x^2,x^3));"
+
+    # Check that Piecewise without a True (default) condition error
+    #expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0))
+    #raises(ValueError, lambda: rcode(expr))
+    expr = 2*Piecewise((x, x < 1), (x**2, x<2))
+    assert(rcode(expr))== "2*ifelse(x < 1,x,ifelse(x < 2,x^2,NA))"
+
+
+def test_rcode_sinc():
+    from sympy.functions.elementary.trigonometric import sinc
+    expr = sinc(x)
+    res = rcode(expr)
+    ref = "(ifelse(x != 0,sin(x)/x,1))"
+    assert res == ref
+
+
+def test_rcode_Piecewise_deep():
+    p = rcode(2*Piecewise((x, x < 1), (x + 1, x < 2), (x**2, True)))
+    assert p == "2*ifelse(x < 1,x,ifelse(x < 2,x + 1,x^2))"
+    expr = x*y*z + x**2 + y**2 + Piecewise((0, x < 0.5), (1, True)) + cos(z) - 1
+    p = rcode(expr)
+    ref="x^2 + x*y*z + y^2 + ifelse(x < 0.5,0,1) + cos(z) - 1"
+    assert p == ref
+
+    ref="c = x^2 + x*y*z + y^2 + ifelse(x < 0.5,0,1) + cos(z) - 1;"
+    p = rcode(expr, assign_to='c')
+    assert p == ref
+
+
+def test_rcode_ITE():
+    expr = ITE(x < 1, y, z)
+    p = rcode(expr)
+    ref="ifelse(x < 1,y,z)"
+    assert p == ref
+
+
+def test_rcode_settings():
+    raises(TypeError, lambda: rcode(sin(x), method="garbage"))
+
+
+def test_rcode_Indexed():
+    n, m, o = symbols('n m o', integer=True)
+    i, j, k = Idx('i', n), Idx('j', m), Idx('k', o)
+    p = RCodePrinter()
+    p._not_r = set()
+
+    x = IndexedBase('x')[j]
+    assert p._print_Indexed(x) == 'x[j]'
+    A = IndexedBase('A')[i, j]
+    assert p._print_Indexed(A) == 'A[i, j]'
+    B = IndexedBase('B')[i, j, k]
+    assert p._print_Indexed(B) == 'B[i, j, k]'
+
+    assert p._not_r == set()
+
+def test_rcode_Indexed_without_looking_for_contraction():
+    len_y = 5
+    y = IndexedBase('y', shape=(len_y,))
+    x = IndexedBase('x', shape=(len_y,))
+    Dy = IndexedBase('Dy', shape=(len_y-1,))
+    i = Idx('i', len_y-1)
+    e=Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i]))
+    code0 = rcode(e.rhs, assign_to=e.lhs, contract=False)
+    assert code0 == 'Dy[i] = (y[%s] - y[i])/(x[%s] - x[i]);' % (i + 1, i + 1)
+
+
+def test_rcode_loops_matrix_vector():
+    n, m = symbols('n m', integer=True)
+    A = IndexedBase('A')
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i = Idx('i', m)
+    j = Idx('j', n)
+
+    s = (
+        'for (i in 1:m){\n'
+        '   y[i] = 0;\n'
+        '}\n'
+        'for (i in 1:m){\n'
+        '   for (j in 1:n){\n'
+        '      y[i] = A[i, j]*x[j] + y[i];\n'
+        '   }\n'
+        '}'
+    )
+    c = rcode(A[i, j]*x[j], assign_to=y[i])
+    assert c == s
+
+
+def test_dummy_loops():
+    # the following line could also be
+    # [Dummy(s, integer=True) for s in 'im']
+    # or [Dummy(integer=True) for s in 'im']
+    i, m = symbols('i m', integer=True, cls=Dummy)
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i = Idx(i, m)
+
+    expected = (
+            'for (i_%(icount)i in 1:m_%(mcount)i){\n'
+        '   y[i_%(icount)i] = x[i_%(icount)i];\n'
+        '}'
+    ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index}
+    code = rcode(x[i], assign_to=y[i])
+    assert code == expected
+
+
+def test_rcode_loops_add():
+    n, m = symbols('n m', integer=True)
+    A = IndexedBase('A')
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    z = IndexedBase('z')
+    i = Idx('i', m)
+    j = Idx('j', n)
+
+    s = (
+        'for (i in 1:m){\n'
+        '   y[i] = x[i] + z[i];\n'
+        '}\n'
+        'for (i in 1:m){\n'
+        '   for (j in 1:n){\n'
+        '      y[i] = A[i, j]*x[j] + y[i];\n'
+        '   }\n'
+        '}'
+    )
+    c = rcode(A[i, j]*x[j] + x[i] + z[i], assign_to=y[i])
+    assert c == s
+
+
+def test_rcode_loops_multiple_contractions():
+    n, m, o, p = symbols('n m o p', integer=True)
+    a = IndexedBase('a')
+    b = IndexedBase('b')
+    y = IndexedBase('y')
+    i = Idx('i', m)
+    j = Idx('j', n)
+    k = Idx('k', o)
+    l = Idx('l', p)
+
+    s = (
+        'for (i in 1:m){\n'
+        '   y[i] = 0;\n'
+        '}\n'
+        'for (i in 1:m){\n'
+        '   for (j in 1:n){\n'
+        '      for (k in 1:o){\n'
+        '         for (l in 1:p){\n'
+        '            y[i] = a[i, j, k, l]*b[j, k, l] + y[i];\n'
+        '         }\n'
+        '      }\n'
+        '   }\n'
+        '}'
+    )
+    c = rcode(b[j, k, l]*a[i, j, k, l], assign_to=y[i])
+    assert c == s
+
+
+def test_rcode_loops_addfactor():
+    n, m, o, p = symbols('n m o p', integer=True)
+    a = IndexedBase('a')
+    b = IndexedBase('b')
+    c = IndexedBase('c')
+    y = IndexedBase('y')
+    i = Idx('i', m)
+    j = Idx('j', n)
+    k = Idx('k', o)
+    l = Idx('l', p)
+
+    s = (
+        'for (i in 1:m){\n'
+        '   y[i] = 0;\n'
+        '}\n'
+        'for (i in 1:m){\n'
+        '   for (j in 1:n){\n'
+        '      for (k in 1:o){\n'
+        '         for (l in 1:p){\n'
+        '            y[i] = (a[i, j, k, l] + b[i, j, k, l])*c[j, k, l] + y[i];\n'
+        '         }\n'
+        '      }\n'
+        '   }\n'
+        '}'
+    )
+    c = rcode((a[i, j, k, l] + b[i, j, k, l])*c[j, k, l], assign_to=y[i])
+    assert c == s
+
+
+def test_rcode_loops_multiple_terms():
+    n, m, o, p = symbols('n m o p', integer=True)
+    a = IndexedBase('a')
+    b = IndexedBase('b')
+    c = IndexedBase('c')
+    y = IndexedBase('y')
+    i = Idx('i', m)
+    j = Idx('j', n)
+    k = Idx('k', o)
+
+    s0 = (
+        'for (i in 1:m){\n'
+        '   y[i] = 0;\n'
+        '}\n'
+    )
+    s1 = (
+        'for (i in 1:m){\n'
+        '   for (j in 1:n){\n'
+        '      for (k in 1:o){\n'
+        '         y[i] = b[j]*b[k]*c[i, j, k] + y[i];\n'
+        '      }\n'
+        '   }\n'
+        '}\n'
+    )
+    s2 = (
+        'for (i in 1:m){\n'
+        '   for (k in 1:o){\n'
+        '      y[i] = a[i, k]*b[k] + y[i];\n'
+        '   }\n'
+        '}\n'
+    )
+    s3 = (
+        'for (i in 1:m){\n'
+        '   for (j in 1:n){\n'
+        '      y[i] = a[i, j]*b[j] + y[i];\n'
+        '   }\n'
+        '}\n'
+    )
+    c = rcode(
+        b[j]*a[i, j] + b[k]*a[i, k] + b[j]*b[k]*c[i, j, k], assign_to=y[i])
+
+    ref={}
+    ref[0] = s0 + s1 + s2 + s3[:-1]
+    ref[1] = s0 + s1 + s3 + s2[:-1]
+    ref[2] = s0 + s2 + s1 + s3[:-1]
+    ref[3] = s0 + s2 + s3 + s1[:-1]
+    ref[4] = s0 + s3 + s1 + s2[:-1]
+    ref[5] = s0 + s3 + s2 + s1[:-1]
+
+    assert (c == ref[0] or
+            c == ref[1] or
+            c == ref[2] or
+            c == ref[3] or
+            c == ref[4] or
+            c == ref[5])
+
+
+def test_dereference_printing():
+    expr = x + y + sin(z) + z
+    assert rcode(expr, dereference=[z]) == "x + y + (*z) + sin((*z))"
+
+
+def test_Matrix_printing():
+    # Test returning a Matrix
+    mat = Matrix([x*y, Piecewise((2 + x, y>0), (y, True)), sin(z)])
+    A = MatrixSymbol('A', 3, 1)
+    p = rcode(mat, A)
+    assert p == (
+        "A[0] = x*y;\n"
+        "A[1] = ifelse(y > 0,x + 2,y);\n"
+        "A[2] = sin(z);")
+    # Test using MatrixElements in expressions
+    expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0]
+    p = rcode(expr)
+    assert p  == ("ifelse(x > 0,2*A[2],A[2]) + sin(A[1]) + A[0]")
+    # Test using MatrixElements in a Matrix
+    q = MatrixSymbol('q', 5, 1)
+    M = MatrixSymbol('M', 3, 3)
+    m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])],
+        [q[1,0] + q[2,0], q[3, 0], 5],
+        [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]])
+    assert rcode(m, M) == (
+        "M[0] = sin(q[1]);\n"
+        "M[1] = 0;\n"
+        "M[2] = cos(q[2]);\n"
+        "M[3] = q[1] + q[2];\n"
+        "M[4] = q[3];\n"
+        "M[5] = 5;\n"
+        "M[6] = 2*q[4]/q[1];\n"
+        "M[7] = sqrt(q[0]) + 4;\n"
+        "M[8] = 0;")
+
+
+def test_rcode_sgn():
+
+    expr = sign(x) * y
+    assert rcode(expr) == 'y*sign(x)'
+    p = rcode(expr, 'z')
+    assert p  == 'z = y*sign(x);'
+
+    p = rcode(sign(2 * x + x**2) * x + x**2)
+    assert p  == "x^2 + x*sign(x^2 + 2*x)"
+
+    expr = sign(cos(x))
+    p = rcode(expr)
+    assert p == 'sign(cos(x))'
+
+def test_rcode_Assignment():
+    assert rcode(Assignment(x, y + z)) == 'x = y + z;'
+    assert rcode(aug_assign(x, '+', y + z)) == 'x += y + z;'
+
+
+def test_rcode_For():
+    f = For(x, Range(0, 10, 2), [aug_assign(y, '*', x)])
+    sol = rcode(f)
+    assert sol == ("for(x in seq(from=0, to=9, by=2){\n"
+                   "   y *= x;\n"
+                   "}")
+
+
+def test_MatrixElement_printing():
+    # test cases for issue #11821
+    A = MatrixSymbol("A", 1, 3)
+    B = MatrixSymbol("B", 1, 3)
+    C = MatrixSymbol("C", 1, 3)
+
+    assert(rcode(A[0, 0]) == "A[0]")
+    assert(rcode(3 * A[0, 0]) == "3*A[0]")
+
+    F = C[0, 0].subs(C, A - B)
+    assert(rcode(F) == "(A - B)[0]")
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_repr.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_repr.py
new file mode 100644
index 0000000000000000000000000000000000000000..da58883b4fb027ed82db842a0a1ce5f76a49a8bb
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_repr.py
@@ -0,0 +1,382 @@
+from __future__ import annotations
+from typing import Any
+
+from sympy.external.gmpy import GROUND_TYPES
+from sympy.testing.pytest import raises, warns_deprecated_sympy
+from sympy.assumptions.ask import Q
+from sympy.core.function import (Function, WildFunction)
+from sympy.core.numbers import (AlgebraicNumber, Float, Integer, Rational)
+from sympy.core.singleton import S
+from sympy.core.symbol import (Dummy, Symbol, Wild, symbols)
+from sympy.core.sympify import sympify
+from sympy.functions.elementary.complexes import Abs
+from sympy.functions.elementary.miscellaneous import (root, sqrt)
+from sympy.functions.elementary.trigonometric import sin
+from sympy.functions.special.delta_functions import Heaviside
+from sympy.logic.boolalg import (false, true)
+from sympy.matrices.dense import (Matrix, ones)
+from sympy.matrices.expressions.matexpr import MatrixSymbol
+from sympy.matrices.immutable import ImmutableDenseMatrix
+from sympy.combinatorics import Cycle, Permutation
+from sympy.core.symbol import Str
+from sympy.geometry import Point, Ellipse
+from sympy.printing import srepr
+from sympy.polys import ring, field, ZZ, QQ, lex, grlex, Poly
+from sympy.polys.polyclasses import DMP
+from sympy.polys.agca.extensions import FiniteExtension
+
+x, y = symbols('x,y')
+
+# eval(srepr(expr)) == expr has to succeed in the right environment. The right
+# environment is the scope of "from sympy import *" for most cases.
+ENV: dict[str, Any] = {"Str": Str}
+exec("from sympy import *", ENV)
+
+
+def sT(expr, string, import_stmt=None, **kwargs):
+    """
+    sT := sreprTest
+
+    Tests that srepr delivers the expected string and that
+    the condition eval(srepr(expr))==expr holds.
+    """
+    if import_stmt is None:
+        ENV2 = ENV
+    else:
+        ENV2 = ENV.copy()
+        exec(import_stmt, ENV2)
+
+    assert srepr(expr, **kwargs) == string
+    assert eval(string, ENV2) == expr
+
+
+def test_printmethod():
+    class R(Abs):
+        def _sympyrepr(self, printer):
+            return "foo(%s)" % printer._print(self.args[0])
+    assert srepr(R(x)) == "foo(Symbol('x'))"
+
+
+def test_Add():
+    sT(x + y, "Add(Symbol('x'), Symbol('y'))")
+    assert srepr(x**2 + 1, order='lex') == "Add(Pow(Symbol('x'), Integer(2)), Integer(1))"
+    assert srepr(x**2 + 1, order='old') == "Add(Integer(1), Pow(Symbol('x'), Integer(2)))"
+    assert srepr(sympify('x + 3 - 2', evaluate=False), order='none') == "Add(Symbol('x'), Integer(3), Mul(Integer(-1), Integer(2)))"
+
+
+def test_more_than_255_args_issue_10259():
+    from sympy.core.add import Add
+    from sympy.core.mul import Mul
+    for op in (Add, Mul):
+        expr = op(*symbols('x:256'))
+        assert eval(srepr(expr)) == expr
+
+
+def test_Function():
+    sT(Function("f")(x), "Function('f')(Symbol('x'))")
+    # test unapplied Function
+    sT(Function('f'), "Function('f')")
+
+    sT(sin(x), "sin(Symbol('x'))")
+    sT(sin, "sin")
+
+
+def test_Heaviside():
+    sT(Heaviside(x), "Heaviside(Symbol('x'))")
+    sT(Heaviside(x, 1), "Heaviside(Symbol('x'), Integer(1))")
+
+
+def test_Geometry():
+    sT(Point(0, 0), "Point2D(Integer(0), Integer(0))")
+    sT(Ellipse(Point(0, 0), 5, 1),
+       "Ellipse(Point2D(Integer(0), Integer(0)), Integer(5), Integer(1))")
+    # TODO more tests
+
+
+def test_Singletons():
+    sT(S.Catalan, 'Catalan')
+    sT(S.ComplexInfinity, 'zoo')
+    sT(S.EulerGamma, 'EulerGamma')
+    sT(S.Exp1, 'E')
+    sT(S.GoldenRatio, 'GoldenRatio')
+    sT(S.TribonacciConstant, 'TribonacciConstant')
+    sT(S.Half, 'Rational(1, 2)')
+    sT(S.ImaginaryUnit, 'I')
+    sT(S.Infinity, 'oo')
+    sT(S.NaN, 'nan')
+    sT(S.NegativeInfinity, '-oo')
+    sT(S.NegativeOne, 'Integer(-1)')
+    sT(S.One, 'Integer(1)')
+    sT(S.Pi, 'pi')
+    sT(S.Zero, 'Integer(0)')
+    sT(S.Complexes, 'Complexes')
+    sT(S.EmptySequence, 'EmptySequence')
+    sT(S.EmptySet, 'EmptySet')
+    # sT(S.IdentityFunction, 'Lambda(_x, _x)')
+    sT(S.Naturals, 'Naturals')
+    sT(S.Naturals0, 'Naturals0')
+    sT(S.Rationals, 'Rationals')
+    sT(S.Reals, 'Reals')
+    sT(S.UniversalSet, 'UniversalSet')
+
+
+def test_Integer():
+    sT(Integer(4), "Integer(4)")
+
+
+def test_list():
+    sT([x, Integer(4)], "[Symbol('x'), Integer(4)]")
+
+
+def test_Matrix():
+    for cls, name in [(Matrix, "MutableDenseMatrix"), (ImmutableDenseMatrix, "ImmutableDenseMatrix")]:
+        sT(cls([[x**+1, 1], [y, x + y]]),
+           "%s([[Symbol('x'), Integer(1)], [Symbol('y'), Add(Symbol('x'), Symbol('y'))]])" % name)
+
+        sT(cls(), "%s([])" % name)
+
+        sT(cls([[x**+1, 1], [y, x + y]]), "%s([[Symbol('x'), Integer(1)], [Symbol('y'), Add(Symbol('x'), Symbol('y'))]])" % name)
+
+
+def test_empty_Matrix():
+    sT(ones(0, 3), "MutableDenseMatrix(0, 3, [])")
+    sT(ones(4, 0), "MutableDenseMatrix(4, 0, [])")
+    sT(ones(0, 0), "MutableDenseMatrix([])")
+
+
+def test_Rational():
+    sT(Rational(1, 3), "Rational(1, 3)")
+    sT(Rational(-1, 3), "Rational(-1, 3)")
+
+
+def test_Float():
+    sT(Float('1.23', dps=3), "Float('1.22998', precision=13)")
+    sT(Float('1.23456789', dps=9), "Float('1.23456788994', precision=33)")
+    sT(Float('1.234567890123456789', dps=19),
+       "Float('1.234567890123456789013', precision=66)")
+    sT(Float('0.60038617995049726', dps=15),
+       "Float('0.60038617995049726', precision=53)")
+
+    sT(Float('1.23', precision=13), "Float('1.22998', precision=13)")
+    sT(Float('1.23456789', precision=33),
+       "Float('1.23456788994', precision=33)")
+    sT(Float('1.234567890123456789', precision=66),
+       "Float('1.234567890123456789013', precision=66)")
+    sT(Float('0.60038617995049726', precision=53),
+       "Float('0.60038617995049726', precision=53)")
+
+    sT(Float('0.60038617995049726', 15),
+       "Float('0.60038617995049726', precision=53)")
+
+
+def test_Symbol():
+    sT(x, "Symbol('x')")
+    sT(y, "Symbol('y')")
+    sT(Symbol('x', negative=True), "Symbol('x', negative=True)")
+
+
+def test_Symbol_two_assumptions():
+    x = Symbol('x', negative=0, integer=1)
+    # order could vary
+    s1 = "Symbol('x', integer=True, negative=False)"
+    s2 = "Symbol('x', negative=False, integer=True)"
+    assert srepr(x) in (s1, s2)
+    assert eval(srepr(x), ENV) == x
+
+
+def test_Symbol_no_special_commutative_treatment():
+    sT(Symbol('x'), "Symbol('x')")
+    sT(Symbol('x', commutative=False), "Symbol('x', commutative=False)")
+    sT(Symbol('x', commutative=0), "Symbol('x', commutative=False)")
+    sT(Symbol('x', commutative=True), "Symbol('x', commutative=True)")
+    sT(Symbol('x', commutative=1), "Symbol('x', commutative=True)")
+
+
+def test_Wild():
+    sT(Wild('x', even=True), "Wild('x', even=True)")
+
+
+def test_Dummy():
+    d = Dummy('d')
+    sT(d, "Dummy('d', dummy_index=%s)" % str(d.dummy_index))
+
+
+def test_Dummy_assumption():
+    d = Dummy('d', nonzero=True)
+    assert d == eval(srepr(d))
+    s1 = "Dummy('d', dummy_index=%s, nonzero=True)" % str(d.dummy_index)
+    s2 = "Dummy('d', nonzero=True, dummy_index=%s)" % str(d.dummy_index)
+    assert srepr(d) in (s1, s2)
+
+
+def test_Dummy_from_Symbol():
+    # should not get the full dictionary of assumptions
+    n = Symbol('n', integer=True)
+    d = n.as_dummy()
+    assert srepr(d
+        ) == "Dummy('n', dummy_index=%s)" % str(d.dummy_index)
+
+
+def test_tuple():
+    sT((x,), "(Symbol('x'),)")
+    sT((x, y), "(Symbol('x'), Symbol('y'))")
+
+
+def test_WildFunction():
+    sT(WildFunction('w'), "WildFunction('w')")
+
+
+def test_settins():
+    raises(TypeError, lambda: srepr(x, method="garbage"))
+
+
+def test_Mul():
+    sT(3*x**3*y, "Mul(Integer(3), Pow(Symbol('x'), Integer(3)), Symbol('y'))")
+    assert srepr(3*x**3*y, order='old') == "Mul(Integer(3), Symbol('y'), Pow(Symbol('x'), Integer(3)))"
+    assert srepr(sympify('(x+4)*2*x*7', evaluate=False), order='none') == "Mul(Add(Symbol('x'), Integer(4)), Integer(2), Symbol('x'), Integer(7))"
+
+
+def test_AlgebraicNumber():
+    a = AlgebraicNumber(sqrt(2))
+    sT(a, "AlgebraicNumber(Pow(Integer(2), Rational(1, 2)), [Integer(1), Integer(0)])")
+    a = AlgebraicNumber(root(-2, 3))
+    sT(a, "AlgebraicNumber(Pow(Integer(-2), Rational(1, 3)), [Integer(1), Integer(0)])")
+
+
+def test_PolyRing():
+    assert srepr(ring("x", ZZ, lex)[0]) == "PolyRing((Symbol('x'),), ZZ, lex)"
+    assert srepr(ring("x,y", QQ, grlex)[0]) == "PolyRing((Symbol('x'), Symbol('y')), QQ, grlex)"
+    assert srepr(ring("x,y,z", ZZ["t"], lex)[0]) == "PolyRing((Symbol('x'), Symbol('y'), Symbol('z')), ZZ[t], lex)"
+
+
+def test_FracField():
+    assert srepr(field("x", ZZ, lex)[0]) == "FracField((Symbol('x'),), ZZ, lex)"
+    assert srepr(field("x,y", QQ, grlex)[0]) == "FracField((Symbol('x'), Symbol('y')), QQ, grlex)"
+    assert srepr(field("x,y,z", ZZ["t"], lex)[0]) == "FracField((Symbol('x'), Symbol('y'), Symbol('z')), ZZ[t], lex)"
+
+
+def test_PolyElement():
+    R, x, y = ring("x,y", ZZ)
+    assert srepr(3*x**2*y + 1) == "PolyElement(PolyRing((Symbol('x'), Symbol('y')), ZZ, lex), [((2, 1), 3), ((0, 0), 1)])"
+
+
+def test_FracElement():
+    F, x, y = field("x,y", ZZ)
+    assert srepr((3*x**2*y + 1)/(x - y**2)) == "FracElement(FracField((Symbol('x'), Symbol('y')), ZZ, lex), [((2, 1), 3), ((0, 0), 1)], [((1, 0), 1), ((0, 2), -1)])"
+
+
+def test_FractionField():
+    assert srepr(QQ.frac_field(x)) == \
+        "FractionField(FracField((Symbol('x'),), QQ, lex))"
+    assert srepr(QQ.frac_field(x, y, order=grlex)) == \
+        "FractionField(FracField((Symbol('x'), Symbol('y')), QQ, grlex))"
+
+
+def test_PolynomialRingBase():
+    assert srepr(ZZ.old_poly_ring(x)) == \
+        "GlobalPolynomialRing(ZZ, Symbol('x'))"
+    assert srepr(ZZ[x].old_poly_ring(y)) == \
+        "GlobalPolynomialRing(ZZ[x], Symbol('y'))"
+    assert srepr(QQ.frac_field(x).old_poly_ring(y)) == \
+        "GlobalPolynomialRing(FractionField(FracField((Symbol('x'),), QQ, lex)), Symbol('y'))"
+
+
+def test_DMP():
+    p1 = DMP([1, 2], ZZ)
+    p2 = ZZ.old_poly_ring(x)([1, 2])
+    if GROUND_TYPES != 'flint':
+        assert srepr(p1) == "DMP_Python([1, 2], ZZ)"
+        assert srepr(p2) == "DMP_Python([1, 2], ZZ)"
+    else:
+        assert srepr(p1) == "DUP_Flint([1, 2], ZZ)"
+        assert srepr(p2) == "DUP_Flint([1, 2], ZZ)"
+
+
+def test_FiniteExtension():
+    assert srepr(FiniteExtension(Poly(x**2 + 1, x))) == \
+        "FiniteExtension(Poly(x**2 + 1, x, domain='ZZ'))"
+
+
+def test_ExtensionElement():
+    A = FiniteExtension(Poly(x**2 + 1, x))
+    if GROUND_TYPES != 'flint':
+        ans = "ExtElem(DMP_Python([1, 0], ZZ), FiniteExtension(Poly(x**2 + 1, x, domain='ZZ')))"
+    else:
+        ans = "ExtElem(DUP_Flint([1, 0], ZZ), FiniteExtension(Poly(x**2 + 1, x, domain='ZZ')))"
+    assert srepr(A.generator) == ans
+
+def test_BooleanAtom():
+    assert srepr(true) == "true"
+    assert srepr(false) == "false"
+
+
+def test_Integers():
+    sT(S.Integers, "Integers")
+
+
+def test_Naturals():
+    sT(S.Naturals, "Naturals")
+
+
+def test_Naturals0():
+    sT(S.Naturals0, "Naturals0")
+
+
+def test_Reals():
+    sT(S.Reals, "Reals")
+
+
+def test_matrix_expressions():
+    n = symbols('n', integer=True)
+    A = MatrixSymbol("A", n, n)
+    B = MatrixSymbol("B", n, n)
+    sT(A, "MatrixSymbol(Str('A'), Symbol('n', integer=True), Symbol('n', integer=True))")
+    sT(A*B, "MatMul(MatrixSymbol(Str('A'), Symbol('n', integer=True), Symbol('n', integer=True)), MatrixSymbol(Str('B'), Symbol('n', integer=True), Symbol('n', integer=True)))")
+    sT(A + B, "MatAdd(MatrixSymbol(Str('A'), Symbol('n', integer=True), Symbol('n', integer=True)), MatrixSymbol(Str('B'), Symbol('n', integer=True), Symbol('n', integer=True)))")
+
+
+def test_Cycle():
+    # FIXME: sT fails because Cycle is not immutable and calling srepr(Cycle(1, 2))
+    # adds keys to the Cycle dict (GH-17661)
+    #import_stmt = "from sympy.combinatorics import Cycle"
+    #sT(Cycle(1, 2), "Cycle(1, 2)", import_stmt)
+    assert srepr(Cycle(1, 2)) == "Cycle(1, 2)"
+
+
+def test_Permutation():
+    import_stmt = "from sympy.combinatorics import Permutation"
+    sT(Permutation(1, 2)(3, 4), "Permutation([0, 2, 1, 4, 3])", import_stmt, perm_cyclic=False)
+    sT(Permutation(1, 2)(3, 4), "Permutation(1, 2)(3, 4)", import_stmt, perm_cyclic=True)
+
+    with warns_deprecated_sympy():
+        old_print_cyclic = Permutation.print_cyclic
+        Permutation.print_cyclic = False
+        sT(Permutation(1, 2)(3, 4), "Permutation([0, 2, 1, 4, 3])", import_stmt)
+        Permutation.print_cyclic = old_print_cyclic
+
+def test_dict():
+    from sympy.abc import x, y, z
+    d = {}
+    assert srepr(d) == "{}"
+    d = {x: y}
+    assert srepr(d) == "{Symbol('x'): Symbol('y')}"
+    d = {x: y, y: z}
+    assert srepr(d) in (
+        "{Symbol('x'): Symbol('y'), Symbol('y'): Symbol('z')}",
+        "{Symbol('y'): Symbol('z'), Symbol('x'): Symbol('y')}",
+    )
+    d = {x: {y: z}}
+    assert srepr(d) == "{Symbol('x'): {Symbol('y'): Symbol('z')}}"
+
+def test_set():
+    from sympy.abc import x, y
+    s = set()
+    assert srepr(s) == "set()"
+    s = {x, y}
+    assert srepr(s) in ("{Symbol('x'), Symbol('y')}", "{Symbol('y'), Symbol('x')}")
+
+def test_Predicate():
+    sT(Q.even, "Q.even")
+
+def test_AppliedPredicate():
+    sT(Q.even(Symbol('z')), "AppliedPredicate(Q.even, Symbol('z'))")
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_rust.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_rust.py
new file mode 100644
index 0000000000000000000000000000000000000000..c81d592faca0d4a31e5a9618a48d67cb19ca94d8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_rust.py
@@ -0,0 +1,363 @@
+from sympy.core import (S, pi, oo, symbols, Rational, Integer,
+                        GoldenRatio, EulerGamma, Catalan, Lambda, Dummy,
+                        Eq, Ne, Le, Lt, Gt, Ge, Mod)
+from sympy.functions import (Piecewise, sin, cos, Abs, exp, ceiling, sqrt,
+                             sign, floor)
+from sympy.logic import ITE
+from sympy.testing.pytest import raises
+from sympy.utilities.lambdify import implemented_function
+from sympy.tensor import IndexedBase, Idx
+from sympy.matrices import MatrixSymbol, SparseMatrix, Matrix
+
+from sympy.printing.codeprinter import rust_code
+
+x, y, z = symbols('x,y,z', integer=False, real=True)
+k, m, n = symbols('k,m,n', integer=True)
+
+
+def test_Integer():
+    assert rust_code(Integer(42)) == "42"
+    assert rust_code(Integer(-56)) == "-56"
+
+
+def test_Relational():
+    assert rust_code(Eq(x, y)) == "x == y"
+    assert rust_code(Ne(x, y)) == "x != y"
+    assert rust_code(Le(x, y)) == "x <= y"
+    assert rust_code(Lt(x, y)) == "x < y"
+    assert rust_code(Gt(x, y)) == "x > y"
+    assert rust_code(Ge(x, y)) == "x >= y"
+
+
+def test_Rational():
+    assert rust_code(Rational(3, 7)) == "3_f64/7.0"
+    assert rust_code(Rational(18, 9)) == "2"
+    assert rust_code(Rational(3, -7)) == "-3_f64/7.0"
+    assert rust_code(Rational(-3, -7)) == "3_f64/7.0"
+    assert rust_code(x + Rational(3, 7)) == "x + 3_f64/7.0"
+    assert rust_code(Rational(3, 7)*x) == "(3_f64/7.0)*x"
+
+
+def test_basic_ops():
+    assert rust_code(x + y) == "x + y"
+    assert rust_code(x - y) == "x - y"
+    assert rust_code(x * y) == "x*y"
+    assert rust_code(x / y) == "x*y.recip()"
+    assert rust_code(-x) == "-x"
+    assert rust_code(2 * x) == "2.0*x"
+    assert rust_code(y + 2) == "y + 2.0"
+    assert rust_code(x + n) == "n as f64 + x"
+
+def test_printmethod():
+    class fabs(Abs):
+        def _rust_code(self, printer):
+            return "%s.fabs()" % printer._print(self.args[0])
+    assert rust_code(fabs(x)) == "x.fabs()"
+    a = MatrixSymbol("a", 1, 3)
+    assert rust_code(a[0,0]) == 'a[0]'
+
+
+def test_Functions():
+    assert rust_code(sin(x) ** cos(x)) == "x.sin().powf(x.cos())"
+    assert rust_code(abs(x)) == "x.abs()"
+    assert rust_code(ceiling(x)) == "x.ceil()"
+    assert rust_code(floor(x)) == "x.floor()"
+
+    # Automatic rewrite
+    assert rust_code(Mod(x, 3)) == 'x - 3.0*((1_f64/3.0)*x).floor()'
+
+
+def test_Pow():
+    assert rust_code(1/x) == "x.recip()"
+    assert rust_code(x**-1) == rust_code(x**-1.0) == "x.recip()"
+    assert rust_code(sqrt(x)) == "x.sqrt()"
+    assert rust_code(x**S.Half) == rust_code(x**0.5) == "x.sqrt()"
+
+    assert rust_code(1/sqrt(x)) == "x.sqrt().recip()"
+    assert rust_code(x**-S.Half) == rust_code(x**-0.5) == "x.sqrt().recip()"
+
+    assert rust_code(1/pi) == "PI.recip()"
+    assert rust_code(pi**-1) == rust_code(pi**-1.0) == "PI.recip()"
+    assert rust_code(pi**-0.5) == "PI.sqrt().recip()"
+
+    assert rust_code(x**Rational(1, 3)) == "x.cbrt()"
+    assert rust_code(2**x) == "x.exp2()"
+    assert rust_code(exp(x)) == "x.exp()"
+    assert rust_code(x**3) == "x.powi(3)"
+    assert rust_code(x**(y**3)) == "x.powf(y.powi(3))"
+    assert rust_code(x**Rational(2, 3)) == "x.powf(2_f64/3.0)"
+
+    g = implemented_function('g', Lambda(x, 2*x))
+    assert rust_code(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \
+        "(3.5*2.0*x).powf(-x + y.powf(x))/(x.powi(2) + y)"
+    _cond_cfunc = [(lambda base, exp: exp.is_integer, "dpowi", 1),
+                   (lambda base, exp: not exp.is_integer, "pow", 1)]
+    assert rust_code(x**3, user_functions={'Pow': _cond_cfunc}) == 'x.dpowi(3)'
+    assert rust_code(x**3.2, user_functions={'Pow': _cond_cfunc}) == 'x.pow(3.2)'
+
+
+def test_constants():
+    assert rust_code(pi) == "PI"
+    assert rust_code(oo) == "INFINITY"
+    assert rust_code(S.Infinity) == "INFINITY"
+    assert rust_code(-oo) == "NEG_INFINITY"
+    assert rust_code(S.NegativeInfinity) == "NEG_INFINITY"
+    assert rust_code(S.NaN) == "NAN"
+    assert rust_code(exp(1)) == "E"
+    assert rust_code(S.Exp1) == "E"
+
+
+def test_constants_other():
+    assert rust_code(2*GoldenRatio) == "const GoldenRatio: f64 = %s;\n2.0*GoldenRatio" % GoldenRatio.evalf(17)
+    assert rust_code(
+            2*Catalan) == "const Catalan: f64 = %s;\n2.0*Catalan" % Catalan.evalf(17)
+    assert rust_code(2*EulerGamma) == "const EulerGamma: f64 = %s;\n2.0*EulerGamma" % EulerGamma.evalf(17)
+
+
+def test_boolean():
+    assert rust_code(True) == "true"
+    assert rust_code(S.true) == "true"
+    assert rust_code(False) == "false"
+    assert rust_code(S.false) == "false"
+    assert rust_code(k & m) == "k && m"
+    assert rust_code(k | m) == "k || m"
+    assert rust_code(~k) == "!k"
+    assert rust_code(k & m & n) == "k && m && n"
+    assert rust_code(k | m | n) == "k || m || n"
+    assert rust_code((k & m) | n) == "n || k && m"
+    assert rust_code((k | m) & n) == "n && (k || m)"
+
+
+def test_Piecewise():
+    expr = Piecewise((x, x < 1), (x + 2, True))
+    assert rust_code(expr) == (
+            "if (x < 1.0) {\n"
+            "    x\n"
+            "} else {\n"
+            "    x + 2.0\n"
+            "}")
+    assert rust_code(expr, assign_to="r") == (
+        "r = if (x < 1.0) {\n"
+        "    x\n"
+        "} else {\n"
+        "    x + 2.0\n"
+        "};")
+    assert rust_code(expr, assign_to="r", inline=True) == (
+        "r = if (x < 1.0) { x } else { x + 2.0 };")
+    expr = Piecewise((x, x < 1), (x + 1, x < 5), (x + 2, True))
+    assert rust_code(expr, inline=True) == (
+        "if (x < 1.0) { x } else if (x < 5.0) { x + 1.0 } else { x + 2.0 }")
+    assert rust_code(expr, assign_to="r", inline=True) == (
+        "r = if (x < 1.0) { x } else if (x < 5.0) { x + 1.0 } else { x + 2.0 };")
+    assert rust_code(expr, assign_to="r") == (
+        "r = if (x < 1.0) {\n"
+        "    x\n"
+        "} else if (x < 5.0) {\n"
+        "    x + 1.0\n"
+        "} else {\n"
+        "    x + 2.0\n"
+        "};")
+    expr = 2*Piecewise((x, x < 1), (x + 1, x < 5), (x + 2, True))
+    assert rust_code(expr, inline=True) == (
+        "2.0*if (x < 1.0) { x } else if (x < 5.0) { x + 1.0 } else { x + 2.0 }")
+    expr = 2*Piecewise((x, x < 1), (x + 1, x < 5), (x + 2, True)) - 42
+    assert rust_code(expr, inline=True) == (
+        "2.0*if (x < 1.0) { x } else if (x < 5.0) { x + 1.0 } else { x + 2.0 } - 42.0")
+    # Check that Piecewise without a True (default) condition error
+    expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0))
+    raises(ValueError, lambda: rust_code(expr))
+
+
+def test_dereference_printing():
+    expr = x + y + sin(z) + z
+    assert rust_code(expr, dereference=[z]) == "x + y + (*z) + (*z).sin()"
+
+
+def test_sign():
+    expr = sign(x) * y
+    assert rust_code(expr) == "y*(if (x == 0.0) { 0.0 } else { (x).signum() }) as f64"
+    assert rust_code(expr, assign_to='r') == "r = y*(if (x == 0.0) { 0.0 } else { (x).signum() }) as f64;"
+
+    expr = sign(x + y) + 42
+    assert rust_code(expr) == "(if (x + y == 0.0) { 0.0 } else { (x + y).signum() }) + 42"
+    assert rust_code(expr, assign_to='r') == "r = (if (x + y == 0.0) { 0.0 } else { (x + y).signum() }) + 42;"
+
+    expr = sign(cos(x))
+    assert rust_code(expr) == "(if (x.cos() == 0.0) { 0.0 } else { (x.cos()).signum() })"
+
+
+def test_reserved_words():
+
+    x, y = symbols("x if")
+
+    expr = sin(y)
+    assert rust_code(expr) == "if_.sin()"
+    assert rust_code(expr, dereference=[y]) == "(*if_).sin()"
+    assert rust_code(expr, reserved_word_suffix='_unreserved') == "if_unreserved.sin()"
+
+    with raises(ValueError):
+        rust_code(expr, error_on_reserved=True)
+
+
+def test_ITE():
+    ekpr = ITE(k < 1, m, n)
+    assert rust_code(ekpr) == (
+            "if (k < 1) {\n"
+            "    m\n"
+            "} else {\n"
+            "    n\n"
+            "}")
+
+
+def test_Indexed():
+    n, m, o = symbols('n m o', integer=True)
+    i, j, k = Idx('i', n), Idx('j', m), Idx('k', o)
+
+    x = IndexedBase('x')[j]
+    assert rust_code(x) == "x[j]"
+
+    A = IndexedBase('A')[i, j]
+    assert rust_code(A) == "A[m*i + j]"
+
+    B = IndexedBase('B')[i, j, k]
+    assert rust_code(B) == "B[m*o*i + o*j + k]"
+
+
+def test_dummy_loops():
+    i, m = symbols('i m', integer=True, cls=Dummy)
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i = Idx(i, m)
+
+    assert rust_code(x[i], assign_to=y[i]) == (
+        "for i in 0..m {\n"
+        "    y[i] = x[i];\n"
+        "}")
+
+
+def test_loops():
+    m, n = symbols('m n', integer=True)
+    A = IndexedBase('A')
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    z = IndexedBase('z')
+    i = Idx('i', m)
+    j = Idx('j', n)
+
+    assert rust_code(A[i, j]*x[j], assign_to=y[i]) == (
+        "for i in 0..m {\n"
+        "    y[i] = 0;\n"
+        "}\n"
+        "for i in 0..m {\n"
+        "    for j in 0..n {\n"
+        "        y[i] = A[n*i + j]*x[j] + y[i];\n"
+        "    }\n"
+        "}")
+
+    assert rust_code(A[i, j]*x[j] + x[i] + z[i], assign_to=y[i]) == (
+        "for i in 0..m {\n"
+        "    y[i] = x[i] + z[i];\n"
+        "}\n"
+        "for i in 0..m {\n"
+        "    for j in 0..n {\n"
+        "        y[i] = A[n*i + j]*x[j] + y[i];\n"
+        "    }\n"
+        "}")
+
+
+def test_loops_multiple_contractions():
+    n, m, o, p = symbols('n m o p', integer=True)
+    a = IndexedBase('a')
+    b = IndexedBase('b')
+    y = IndexedBase('y')
+    i = Idx('i', m)
+    j = Idx('j', n)
+    k = Idx('k', o)
+    l = Idx('l', p)
+
+    assert rust_code(b[j, k, l]*a[i, j, k, l], assign_to=y[i]) == (
+        "for i in 0..m {\n"
+        "    y[i] = 0;\n"
+        "}\n"
+        "for i in 0..m {\n"
+        "    for j in 0..n {\n"
+        "        for k in 0..o {\n"
+        "            for l in 0..p {\n"
+        "                y[i] = a[%s]*b[%s] + y[i];\n" % (i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\
+        "            }\n"
+        "        }\n"
+        "    }\n"
+        "}")
+
+
+def test_loops_addfactor():
+    m, n, o, p = symbols('m n o p', integer=True)
+    a = IndexedBase('a')
+    b = IndexedBase('b')
+    c = IndexedBase('c')
+    y = IndexedBase('y')
+    i = Idx('i', m)
+    j = Idx('j', n)
+    k = Idx('k', o)
+    l = Idx('l', p)
+
+    code = rust_code((a[i, j, k, l] + b[i, j, k, l])*c[j, k, l], assign_to=y[i])
+    assert code == (
+        "for i in 0..m {\n"
+        "    y[i] = 0;\n"
+        "}\n"
+        "for i in 0..m {\n"
+        "    for j in 0..n {\n"
+        "        for k in 0..o {\n"
+        "            for l in 0..p {\n"
+        "                y[i] = (a[%s] + b[%s])*c[%s] + y[i];\n" % (i*n*o*p + j*o*p + k*p + l, i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\
+        "            }\n"
+        "        }\n"
+        "    }\n"
+        "}")
+
+
+def test_settings():
+    raises(TypeError, lambda: rust_code(sin(x), method="garbage"))
+
+
+def test_inline_function():
+    x = symbols('x')
+    g = implemented_function('g', Lambda(x, 2*x))
+    assert rust_code(g(x)) == "2*x"
+
+    g = implemented_function('g', Lambda(x, 2*x/Catalan))
+    assert rust_code(g(x)) == (
+        "const Catalan: f64 = %s;\n2.0*x/Catalan" % Catalan.evalf(17))
+
+    A = IndexedBase('A')
+    i = Idx('i', symbols('n', integer=True))
+    g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x)))
+    assert rust_code(g(A[i]), assign_to=A[i]) == (
+        "for i in 0..n {\n"
+        "    A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n"
+        "}")
+
+
+def test_user_functions():
+    x = symbols('x', integer=False)
+    n = symbols('n', integer=True)
+    custom_functions = {
+        "ceiling": "ceil",
+        "Abs": [(lambda x: not x.is_integer, "fabs", 4), (lambda x: x.is_integer, "abs", 4)],
+    }
+    assert rust_code(ceiling(x), user_functions=custom_functions) == "x.ceil()"
+    assert rust_code(Abs(x), user_functions=custom_functions) == "fabs(x)"
+    assert rust_code(Abs(n), user_functions=custom_functions) == "abs(n)"
+
+
+def test_matrix():
+    assert rust_code(Matrix([1, 2, 3])) == '[1, 2, 3]'
+    with raises(ValueError):
+        rust_code(Matrix([[1, 2, 3]]))
+
+
+def test_sparse_matrix():
+    # gh-15791
+    with raises(NotImplementedError):
+        rust_code(SparseMatrix([[1, 2, 3]]))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_smtlib.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_smtlib.py
new file mode 100644
index 0000000000000000000000000000000000000000..48ff3d432d9042bf178f4e52dc46c787059937a3
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_smtlib.py
@@ -0,0 +1,553 @@
+import contextlib
+import itertools
+import re
+import typing
+from enum import Enum
+from typing import Callable
+
+import sympy
+from sympy import Add, Implies, sqrt
+from sympy.core import Mul, Pow
+from sympy.core import (S, pi, symbols, Function, Rational, Integer,
+                        Symbol, Eq, Ne, Le, Lt, Gt, Ge)
+from sympy.functions import Piecewise, exp, sin, cos
+from sympy.assumptions.ask import Q
+from sympy.printing.smtlib import smtlib_code
+from sympy.testing.pytest import raises, Failed
+
+x, y, z = symbols('x,y,z')
+
+
+class _W(Enum):
+    DEFAULTING_TO_FLOAT = re.compile("Could not infer type of `.+`. Defaulting to float.", re.IGNORECASE)
+    WILL_NOT_DECLARE = re.compile("Non-Symbol/Function `.+` will not be declared.", re.IGNORECASE)
+    WILL_NOT_ASSERT = re.compile("Non-Boolean expression `.+` will not be asserted. Converting to SMTLib verbatim.", re.IGNORECASE)
+
+
+@contextlib.contextmanager
+def _check_warns(expected: typing.Iterable[_W]):
+    warns: typing.List[str] = []
+    log_warn = warns.append
+    yield log_warn
+
+    errors = []
+    for i, (w, e) in enumerate(itertools.zip_longest(warns, expected)):
+        if not e:
+            errors += [f"[{i}] Received unexpected warning `{w}`."]
+        elif not w:
+            errors += [f"[{i}] Did not receive expected warning `{e.name}`."]
+        elif not e.value.match(w):
+            errors += [f"[{i}] Warning `{w}` does not match expected {e.name}."]
+
+    if errors: raise Failed('\n'.join(errors))
+
+
+def test_Integer():
+    with _check_warns([_W.WILL_NOT_ASSERT] * 2) as w:
+        assert smtlib_code(Integer(67), log_warn=w) == "67"
+        assert smtlib_code(Integer(-1), log_warn=w) == "-1"
+    with _check_warns([]) as w:
+        assert smtlib_code(Integer(67)) == "67"
+        assert smtlib_code(Integer(-1)) == "-1"
+
+
+def test_Rational():
+    with _check_warns([_W.WILL_NOT_ASSERT] * 4) as w:
+        assert smtlib_code(Rational(3, 7), log_warn=w) == "(/ 3 7)"
+        assert smtlib_code(Rational(18, 9), log_warn=w) == "2"
+        assert smtlib_code(Rational(3, -7), log_warn=w) == "(/ -3 7)"
+        assert smtlib_code(Rational(-3, -7), log_warn=w) == "(/ 3 7)"
+
+    with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT] * 2) as w:
+        assert smtlib_code(x + Rational(3, 7), auto_declare=False, log_warn=w) == "(+ (/ 3 7) x)"
+        assert smtlib_code(Rational(3, 7) * x, log_warn=w) == "(declare-const x Real)\n" \
+                                                              "(* (/ 3 7) x)"
+
+
+def test_Relational():
+    with _check_warns([_W.DEFAULTING_TO_FLOAT] * 12) as w:
+        assert smtlib_code(Eq(x, y), auto_declare=False, log_warn=w) == "(assert (= x y))"
+        assert smtlib_code(Ne(x, y), auto_declare=False, log_warn=w) == "(assert (not (= x y)))"
+        assert smtlib_code(Le(x, y), auto_declare=False, log_warn=w) == "(assert (<= x y))"
+        assert smtlib_code(Lt(x, y), auto_declare=False, log_warn=w) == "(assert (< x y))"
+        assert smtlib_code(Gt(x, y), auto_declare=False, log_warn=w) == "(assert (> x y))"
+        assert smtlib_code(Ge(x, y), auto_declare=False, log_warn=w) == "(assert (>= x y))"
+
+
+def test_AppliedBinaryRelation():
+    with _check_warns([_W.DEFAULTING_TO_FLOAT] * 12) as w:
+        assert smtlib_code(Q.eq(x, y), auto_declare=False, log_warn=w) == "(assert (= x y))"
+        assert smtlib_code(Q.ne(x, y), auto_declare=False, log_warn=w) == "(assert (not (= x y)))"
+        assert smtlib_code(Q.lt(x, y), auto_declare=False, log_warn=w) == "(assert (< x y))"
+        assert smtlib_code(Q.le(x, y), auto_declare=False, log_warn=w) == "(assert (<= x y))"
+        assert smtlib_code(Q.gt(x, y), auto_declare=False, log_warn=w) == "(assert (> x y))"
+        assert smtlib_code(Q.ge(x, y), auto_declare=False, log_warn=w) == "(assert (>= x y))"
+
+    raises(ValueError, lambda: smtlib_code(Q.complex(x), log_warn=w))
+
+
+def test_AppliedPredicate():
+    with _check_warns([_W.DEFAULTING_TO_FLOAT] * 6) as w:
+        assert smtlib_code(Q.positive(x), auto_declare=False, log_warn=w) == "(assert (> x 0))"
+        assert smtlib_code(Q.negative(x), auto_declare=False, log_warn=w) == "(assert (< x 0))"
+        assert smtlib_code(Q.zero(x), auto_declare=False, log_warn=w) == "(assert (= x 0))"
+        assert smtlib_code(Q.nonpositive(x), auto_declare=False, log_warn=w) == "(assert (<= x 0))"
+        assert smtlib_code(Q.nonnegative(x), auto_declare=False, log_warn=w) == "(assert (>= x 0))"
+        assert smtlib_code(Q.nonzero(x), auto_declare=False, log_warn=w) == "(assert (not (= x 0)))"
+
+def test_Function():
+    with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(sin(x) ** cos(x), auto_declare=False, log_warn=w) == "(pow (sin x) (cos x))"
+
+    with _check_warns([_W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(
+            abs(x),
+            symbol_table={x: int, y: bool},
+            known_types={int: "INTEGER_TYPE"},
+            known_functions={sympy.Abs: "ABSOLUTE_VALUE_OF"},
+            log_warn=w
+        ) == "(declare-const x INTEGER_TYPE)\n" \
+             "(ABSOLUTE_VALUE_OF x)"
+
+    my_fun1 = Function('f1')
+    with _check_warns([_W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(
+            my_fun1(x),
+            symbol_table={my_fun1: Callable[[bool], float]},
+            log_warn=w
+        ) == "(declare-const x Bool)\n" \
+             "(declare-fun f1 (Bool) Real)\n" \
+             "(f1 x)"
+
+    with _check_warns([]) as w:
+        assert smtlib_code(
+            my_fun1(x),
+            symbol_table={my_fun1: Callable[[bool], bool]},
+            log_warn=w
+        ) == "(declare-const x Bool)\n" \
+             "(declare-fun f1 (Bool) Bool)\n" \
+             "(assert (f1 x))"
+
+        assert smtlib_code(
+            Eq(my_fun1(x, z), y),
+            symbol_table={my_fun1: Callable[[int, bool], bool]},
+            log_warn=w
+        ) == "(declare-const x Int)\n" \
+             "(declare-const y Bool)\n" \
+             "(declare-const z Bool)\n" \
+             "(declare-fun f1 (Int Bool) Bool)\n" \
+             "(assert (= (f1 x z) y))"
+
+        assert smtlib_code(
+            Eq(my_fun1(x, z), y),
+            symbol_table={my_fun1: Callable[[int, bool], bool]},
+            known_functions={my_fun1: "MY_KNOWN_FUN", Eq: '=='},
+            log_warn=w
+        ) == "(declare-const x Int)\n" \
+             "(declare-const y Bool)\n" \
+             "(declare-const z Bool)\n" \
+             "(assert (== (MY_KNOWN_FUN x z) y))"
+
+    with _check_warns([_W.DEFAULTING_TO_FLOAT] * 3) as w:
+        assert smtlib_code(
+            Eq(my_fun1(x, z), y),
+            known_functions={my_fun1: "MY_KNOWN_FUN", Eq: '=='},
+            log_warn=w
+        ) == "(declare-const x Real)\n" \
+             "(declare-const y Real)\n" \
+             "(declare-const z Real)\n" \
+             "(assert (== (MY_KNOWN_FUN x z) y))"
+
+
+def test_Pow():
+    with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(x ** 3, auto_declare=False, log_warn=w) == "(pow x 3)"
+    with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(x ** (y ** 3), auto_declare=False, log_warn=w) == "(pow x (pow y 3))"
+    with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(x ** Rational(2, 3), auto_declare=False, log_warn=w) == '(pow x (/ 2 3))'
+
+        a = Symbol('a', integer=True)
+        b = Symbol('b', real=True)
+        c = Symbol('c')
+
+        def g(x): return 2 * x
+
+        # if x=1, y=2, then expr=2.333...
+        expr = 1 / (g(a) * 3.5) ** (a - b ** a) / (a ** 2 + b)
+
+    with _check_warns([]) as w:
+        assert smtlib_code(
+            [
+                Eq(a < 2, c),
+                Eq(b > a, c),
+                c & True,
+                Eq(expr, 2 + Rational(1, 3))
+            ],
+            log_warn=w
+        ) == '(declare-const a Int)\n' \
+             '(declare-const b Real)\n' \
+             '(declare-const c Bool)\n' \
+             '(assert (= (< a 2) c))\n' \
+             '(assert (= (> b a) c))\n' \
+             '(assert c)\n' \
+             '(assert (= ' \
+             '(* (pow (* 7.0 a) (+ (pow b a) (* -1 a))) (pow (+ b (pow a 2)) -1)) ' \
+             '(/ 7 3)' \
+             '))'
+
+    with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(
+            Mul(-2, c, Pow(Mul(b, b, evaluate=False), -1, evaluate=False), evaluate=False),
+            log_warn=w
+        ) == '(declare-const b Real)\n' \
+             '(declare-const c Real)\n' \
+             '(* -2 c (pow (* b b) -1))'
+
+
+def test_basic_ops():
+    with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(x * y, auto_declare=False, log_warn=w) == "(* x y)"
+
+    with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(x + y, auto_declare=False, log_warn=w) == "(+ x y)"
+
+    # with _check_warns([_SmtlibWarnings.DEFAULTING_TO_FLOAT, _SmtlibWarnings.DEFAULTING_TO_FLOAT, _SmtlibWarnings.WILL_NOT_ASSERT]) as w:
+    # todo: implement re-write, currently does '(+ x (* -1 y))' instead
+    # assert smtlib_code(x - y, auto_declare=False, log_warn=w) == "(- x y)"
+
+    with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(-x, auto_declare=False, log_warn=w) == "(* -1 x)"
+
+
+def test_quantifier_extensions():
+    from sympy.logic.boolalg import Boolean
+    from sympy import Interval, Tuple, sympify
+
+    # start For-all quantifier class example
+    class ForAll(Boolean):
+        def _smtlib(self, printer):
+            bound_symbol_declarations = [
+                printer._s_expr(sym.name, [
+                    printer._known_types[printer.symbol_table[sym]],
+                    Interval(start, end)
+                ]) for sym, start, end in self.limits
+            ]
+            return printer._s_expr('forall', [
+                printer._s_expr('', bound_symbol_declarations),
+                self.function
+            ])
+
+        @property
+        def bound_symbols(self):
+            return {s for s, _, _ in self.limits}
+
+        @property
+        def free_symbols(self):
+            bound_symbol_names = {s.name for s in self.bound_symbols}
+            return {
+                s for s in self.function.free_symbols
+                if s.name not in bound_symbol_names
+            }
+
+        def __new__(cls, *args):
+            limits = [sympify(a) for a in args if isinstance(a, (tuple, Tuple))]
+            function = [sympify(a) for a in args if isinstance(a, Boolean)]
+            assert len(limits) + len(function) == len(args)
+            assert len(function) == 1
+            function = function[0]
+
+            if isinstance(function, ForAll): return ForAll.__new__(
+                ForAll, *(limits + function.limits), function.function
+            )
+            inst = Boolean.__new__(cls)
+            inst._args = tuple(limits + [function])
+            inst.limits = limits
+            inst.function = function
+            return inst
+
+    # end For-All Quantifier class example
+
+    f = Function('f')
+    with _check_warns([_W.DEFAULTING_TO_FLOAT]) as w:
+        assert smtlib_code(
+            ForAll((x, -42, +21), Eq(f(x), f(x))),
+            symbol_table={f: Callable[[float], float]},
+            log_warn=w
+        ) == '(assert (forall ( (x Real [-42, 21])) true))'
+
+    with _check_warns([_W.DEFAULTING_TO_FLOAT] * 2) as w:
+        assert smtlib_code(
+            ForAll(
+                (x, -42, +21), (y, -100, 3),
+                Implies(Eq(x, y), Eq(f(x), f(y)))
+            ),
+            symbol_table={f: Callable[[float], float]},
+            log_warn=w
+        ) == '(declare-fun f (Real) Real)\n' \
+             '(assert (' \
+             'forall ( (x Real [-42, 21]) (y Real [-100, 3])) ' \
+             '(=> (= x y) (= (f x) (f y)))' \
+             '))'
+
+    a = Symbol('a', integer=True)
+    b = Symbol('b', real=True)
+    c = Symbol('c')
+
+    with _check_warns([]) as w:
+        assert smtlib_code(
+            ForAll(
+                (a, 2, 100), ForAll(
+                    (b, 2, 100),
+                    Implies(a < b, sqrt(a) < b) | c
+                )),
+            log_warn=w
+        ) == '(declare-const c Bool)\n' \
+             '(assert (forall ( (a Int [2, 100]) (b Real [2, 100])) ' \
+             '(or c (=> (< a b) (< (pow a (/ 1 2)) b)))' \
+             '))'
+
+
+def test_mix_number_mult_symbols():
+    with _check_warns([_W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(
+            1 / pi,
+            known_constants={pi: "MY_PI"},
+            log_warn=w
+        ) == '(pow MY_PI -1)'
+
+    with _check_warns([_W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(
+            [
+                Eq(pi, 3.14, evaluate=False),
+                1 / pi,
+            ],
+            known_constants={pi: "MY_PI"},
+            log_warn=w
+        ) == '(assert (= MY_PI 3.14))\n' \
+             '(pow MY_PI -1)'
+
+    with _check_warns([_W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(
+            Add(S.Zero, S.One, S.NegativeOne, S.Half,
+                S.Exp1, S.Pi, S.GoldenRatio, evaluate=False),
+            known_constants={
+                S.Pi: 'p', S.GoldenRatio: 'g',
+                S.Exp1: 'e'
+            },
+            known_functions={
+                Add: 'plus',
+                exp: 'exp'
+            },
+            precision=3,
+            log_warn=w
+        ) == '(plus 0 1 -1 (/ 1 2) (exp 1) p g)'
+
+    with _check_warns([_W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(
+            Add(S.Zero, S.One, S.NegativeOne, S.Half,
+                S.Exp1, S.Pi, S.GoldenRatio, evaluate=False),
+            known_constants={
+                S.Pi: 'p'
+            },
+            known_functions={
+                Add: 'plus',
+                exp: 'exp'
+            },
+            precision=3,
+            log_warn=w
+        ) == '(plus 0 1 -1 (/ 1 2) (exp 1) p 1.62)'
+
+    with _check_warns([_W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(
+            Add(S.Zero, S.One, S.NegativeOne, S.Half,
+                S.Exp1, S.Pi, S.GoldenRatio, evaluate=False),
+            known_functions={Add: 'plus'},
+            precision=3,
+            log_warn=w
+        ) == '(plus 0 1 -1 (/ 1 2) 2.72 3.14 1.62)'
+
+    with _check_warns([_W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(
+            Add(S.Zero, S.One, S.NegativeOne, S.Half,
+                S.Exp1, S.Pi, S.GoldenRatio, evaluate=False),
+            known_constants={S.Exp1: 'e'},
+            known_functions={Add: 'plus'},
+            precision=3,
+            log_warn=w
+        ) == '(plus 0 1 -1 (/ 1 2) e 3.14 1.62)'
+
+
+def test_boolean():
+    with _check_warns([]) as w:
+        assert smtlib_code(x & y, log_warn=w) == '(declare-const x Bool)\n' \
+                                                 '(declare-const y Bool)\n' \
+                                                 '(assert (and x y))'
+        assert smtlib_code(x | y, log_warn=w) == '(declare-const x Bool)\n' \
+                                                 '(declare-const y Bool)\n' \
+                                                 '(assert (or x y))'
+        assert smtlib_code(~x, log_warn=w) == '(declare-const x Bool)\n' \
+                                              '(assert (not x))'
+        assert smtlib_code(x & y & z, log_warn=w) == '(declare-const x Bool)\n' \
+                                                     '(declare-const y Bool)\n' \
+                                                     '(declare-const z Bool)\n' \
+                                                     '(assert (and x y z))'
+
+    with _check_warns([_W.DEFAULTING_TO_FLOAT]) as w:
+        assert smtlib_code((x & ~y) | (z > 3), log_warn=w) == '(declare-const x Bool)\n' \
+                                                              '(declare-const y Bool)\n' \
+                                                              '(declare-const z Real)\n' \
+                                                              '(assert (or (> z 3) (and x (not y))))'
+
+    f = Function('f')
+    g = Function('g')
+    h = Function('h')
+    with _check_warns([_W.DEFAULTING_TO_FLOAT]) as w:
+        assert smtlib_code(
+            [Gt(f(x), y),
+             Lt(y, g(z))],
+            symbol_table={
+                f: Callable[[bool], int], g: Callable[[bool], int],
+            }, log_warn=w
+        ) == '(declare-const x Bool)\n' \
+             '(declare-const y Real)\n' \
+             '(declare-const z Bool)\n' \
+             '(declare-fun f (Bool) Int)\n' \
+             '(declare-fun g (Bool) Int)\n' \
+             '(assert (> (f x) y))\n' \
+             '(assert (< y (g z)))'
+
+    with _check_warns([]) as w:
+        assert smtlib_code(
+            [Eq(f(x), y),
+             Lt(y, g(z))],
+            symbol_table={
+                f: Callable[[bool], int], g: Callable[[bool], int],
+            }, log_warn=w
+        ) == '(declare-const x Bool)\n' \
+             '(declare-const y Int)\n' \
+             '(declare-const z Bool)\n' \
+             '(declare-fun f (Bool) Int)\n' \
+             '(declare-fun g (Bool) Int)\n' \
+             '(assert (= (f x) y))\n' \
+             '(assert (< y (g z)))'
+
+    with _check_warns([]) as w:
+        assert smtlib_code(
+            [Eq(f(x), y),
+             Eq(g(f(x)), z),
+             Eq(h(g(f(x))), x)],
+            symbol_table={
+                f: Callable[[float], int],
+                g: Callable[[int], bool],
+                h: Callable[[bool], float]
+            },
+            log_warn=w
+        ) == '(declare-const x Real)\n' \
+             '(declare-const y Int)\n' \
+             '(declare-const z Bool)\n' \
+             '(declare-fun f (Real) Int)\n' \
+             '(declare-fun g (Int) Bool)\n' \
+             '(declare-fun h (Bool) Real)\n' \
+             '(assert (= (f x) y))\n' \
+             '(assert (= (g (f x)) z))\n' \
+             '(assert (= (h (g (f x))) x))'
+
+
+# todo: make smtlib_code support arrays
+# def test_containers():
+#     assert julia_code([1, 2, 3, [4, 5, [6, 7]], 8, [9, 10], 11]) == \
+#            "Any[1, 2, 3, Any[4, 5, Any[6, 7]], 8, Any[9, 10], 11]"
+#     assert julia_code((1, 2, (3, 4))) == "(1, 2, (3, 4))"
+#     assert julia_code([1]) == "Any[1]"
+#     assert julia_code((1,)) == "(1,)"
+#     assert julia_code(Tuple(*[1, 2, 3])) == "(1, 2, 3)"
+#     assert julia_code((1, x * y, (3, x ** 2))) == "(1, x .* y, (3, x .^ 2))"
+#     # scalar, matrix, empty matrix and empty list
+#     assert julia_code((1, eye(3), Matrix(0, 0, []), [])) == "(1, [1 0 0;\n0 1 0;\n0 0 1], zeros(0, 0), Any[])"
+
+def test_smtlib_piecewise():
+    with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(
+            Piecewise((x, x < 1),
+                      (x ** 2, True)),
+            auto_declare=False,
+            log_warn=w
+        ) == '(ite (< x 1) x (pow x 2))'
+
+    with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(
+            Piecewise((x ** 2, x < 1),
+                      (x ** 3, x < 2),
+                      (x ** 4, x < 3),
+                      (x ** 5, True)),
+            auto_declare=False,
+            log_warn=w
+        ) == '(ite (< x 1) (pow x 2) ' \
+             '(ite (< x 2) (pow x 3) ' \
+             '(ite (< x 3) (pow x 4) ' \
+             '(pow x 5))))'
+
+    # Check that Piecewise without a True (default) condition error
+    expr = Piecewise((x, x < 1), (x ** 2, x > 1), (sin(x), x > 0))
+    with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w:
+        raises(AssertionError, lambda: smtlib_code(expr, log_warn=w))
+
+
+def test_smtlib_piecewise_times_const():
+    pw = Piecewise((x, x < 1), (x ** 2, True))
+    with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(2 * pw, log_warn=w) == '(declare-const x Real)\n(* 2 (ite (< x 1) x (pow x 2)))'
+    with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(pw / x, log_warn=w) == '(declare-const x Real)\n(* (pow x -1) (ite (< x 1) x (pow x 2)))'
+    with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(pw / (x * y), log_warn=w) == '(declare-const x Real)\n(declare-const y Real)\n(* (pow x -1) (pow y -1) (ite (< x 1) x (pow x 2)))'
+    with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w:
+        assert smtlib_code(pw / 3, log_warn=w) == '(declare-const x Real)\n(* (/ 1 3) (ite (< x 1) x (pow x 2)))'
+
+
+# todo: make smtlib_code support arrays / matrices ?
+# def test_smtlib_matrix_assign_to():
+#     A = Matrix([[1, 2, 3]])
+#     assert smtlib_code(A, assign_to='a') == "a = [1 2 3]"
+#     A = Matrix([[1, 2], [3, 4]])
+#     assert smtlib_code(A, assign_to='A') == "A = [1 2;\n3 4]"
+
+# def test_julia_matrix_1x1():
+#     A = Matrix([[3]])
+#     B = MatrixSymbol('B', 1, 1)
+#     C = MatrixSymbol('C', 1, 2)
+#     assert julia_code(A, assign_to=B) == "B = [3]"
+#     raises(ValueError, lambda: julia_code(A, assign_to=C))
+
+# def test_julia_matrix_elements():
+#     A = Matrix([[x, 2, x * y]])
+#     assert julia_code(A[0, 0] ** 2 + A[0, 1] + A[0, 2]) == "x .^ 2 + x .* y + 2"
+#     A = MatrixSymbol('AA', 1, 3)
+#     assert julia_code(A) == "AA"
+#     assert julia_code(A[0, 0] ** 2 + sin(A[0, 1]) + A[0, 2]) == \
+#            "sin(AA[1,2]) + AA[1,1] .^ 2 + AA[1,3]"
+#     assert julia_code(sum(A)) == "AA[1,1] + AA[1,2] + AA[1,3]"
+
+def test_smtlib_boolean():
+    with _check_warns([]) as w:
+        assert smtlib_code(True, auto_assert=False, log_warn=w) == 'true'
+        assert smtlib_code(True, log_warn=w) == '(assert true)'
+        assert smtlib_code(S.true, log_warn=w) == '(assert true)'
+        assert smtlib_code(S.false, log_warn=w) == '(assert false)'
+        assert smtlib_code(False, log_warn=w) == '(assert false)'
+        assert smtlib_code(False, auto_assert=False, log_warn=w) == 'false'
+
+
+def test_not_supported():
+    f = Function('f')
+    with _check_warns([_W.DEFAULTING_TO_FLOAT, _W.WILL_NOT_ASSERT]) as w:
+        raises(KeyError, lambda: smtlib_code(f(x).diff(x), symbol_table={f: Callable[[float], float]}, log_warn=w))
+    with _check_warns([_W.WILL_NOT_ASSERT]) as w:
+        raises(KeyError, lambda: smtlib_code(S.ComplexInfinity, log_warn=w))
+
+
+def test_Float():
+    assert smtlib_code(0.0) == "0.0"
+    assert smtlib_code(0.000000000000000003) == '(* 3.0 (pow 10 -18))'
+    assert smtlib_code(5.3) == "5.3"
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_str.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_str.py
new file mode 100644
index 0000000000000000000000000000000000000000..675212964b03bf9a9806088225c28d7f70971ca7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_str.py
@@ -0,0 +1,1206 @@
+from sympy import MatAdd
+from sympy.algebras.quaternion import Quaternion
+from sympy.assumptions.ask import Q
+from sympy.calculus.accumulationbounds import AccumBounds
+from sympy.combinatorics.partitions import Partition
+from sympy.concrete.summations import (Sum, summation)
+from sympy.core.add import Add
+from sympy.core.containers import (Dict, Tuple)
+from sympy.core.expr import UnevaluatedExpr, Expr
+from sympy.core.function import (Derivative, Function, Lambda, Subs, WildFunction)
+from sympy.core.mul import Mul
+from sympy.core import (Catalan, EulerGamma, GoldenRatio, TribonacciConstant)
+from sympy.core.numbers import (E, Float, I, Integer, Rational, nan, oo, pi, zoo)
+from sympy.core.parameters import _exp_is_pow
+from sympy.core.power import Pow
+from sympy.core.relational import (Eq, Rel, Ne)
+from sympy.core.singleton import S
+from sympy.core.symbol import (Dummy, Symbol, Wild, symbols)
+from sympy.functions.combinatorial.factorials import (factorial, factorial2, subfactorial)
+from sympy.functions.elementary.complexes import Abs
+from sympy.functions.elementary.exponential import exp
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import (cos, sin)
+from sympy.functions.special.delta_functions import Heaviside
+from sympy.functions.special.zeta_functions import zeta
+from sympy.integrals.integrals import Integral
+from sympy.logic.boolalg import (Equivalent, false, true, Xor)
+from sympy.matrices.dense import Matrix
+from sympy.matrices.expressions.matexpr import MatrixSymbol
+from sympy.matrices.expressions import Identity
+from sympy.matrices.expressions.slice import MatrixSlice
+from sympy.matrices import SparseMatrix
+from sympy.polys.polytools import factor
+from sympy.series.limits import Limit
+from sympy.series.order import O
+from sympy.sets.sets import (Complement, FiniteSet, Interval, SymmetricDifference)
+from sympy.stats import (Covariance, Expectation, Probability, Variance)
+from sympy.stats.rv import RandomSymbol
+from sympy.external import import_module
+from sympy.physics.control.lti import TransferFunction, Series, Parallel, \
+    Feedback, TransferFunctionMatrix, MIMOSeries, MIMOParallel, MIMOFeedback
+from sympy.physics.units import second, joule
+from sympy.polys import (Poly, rootof, RootSum, groebner, ring, field, ZZ, QQ,
+    ZZ_I, QQ_I, lex, grlex)
+from sympy.geometry import Point, Circle, Polygon, Ellipse, Triangle
+from sympy.tensor import NDimArray
+from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayElement
+
+from sympy.testing.pytest import raises, warns_deprecated_sympy
+
+from sympy.printing import sstr, sstrrepr, StrPrinter
+from sympy.physics.quantum.trace import Tr
+
+x, y, z, w, t = symbols('x,y,z,w,t')
+d = Dummy('d')
+
+
+def test_printmethod():
+    class R(Abs):
+        def _sympystr(self, printer):
+            return "foo(%s)" % printer._print(self.args[0])
+    assert sstr(R(x)) == "foo(x)"
+
+    class R(Abs):
+        def _sympystr(self, printer):
+            return "foo"
+    assert sstr(R(x)) == "foo"
+
+
+def test_Abs():
+    assert str(Abs(x)) == "Abs(x)"
+    assert str(Abs(Rational(1, 6))) == "1/6"
+    assert str(Abs(Rational(-1, 6))) == "1/6"
+
+
+def test_Add():
+    assert str(x + y) == "x + y"
+    assert str(x + 1) == "x + 1"
+    assert str(x + x**2) == "x**2 + x"
+    assert str(Add(0, 1, evaluate=False)) == "0 + 1"
+    assert str(Add(0, 0, 1, evaluate=False)) == "0 + 0 + 1"
+    assert str(1.0*x) == "1.0*x"
+    assert str(5 + x + y + x*y + x**2 + y**2) == "x**2 + x*y + x + y**2 + y + 5"
+    assert str(1 + x + x**2/2 + x**3/3) == "x**3/3 + x**2/2 + x + 1"
+    assert str(2*x - 7*x**2 + 2 + 3*y) == "-7*x**2 + 2*x + 3*y + 2"
+    assert str(x - y) == "x - y"
+    assert str(2 - x) == "2 - x"
+    assert str(x - 2) == "x - 2"
+    assert str(x - y - z - w) == "-w + x - y - z"
+    assert str(x - z*y**2*z*w) == "-w*y**2*z**2 + x"
+    assert str(x - 1*y*x*y) == "-x*y**2 + x"
+    assert str(sin(x).series(x, 0, 15)) == "x - x**3/6 + x**5/120 - x**7/5040 + x**9/362880 - x**11/39916800 + x**13/6227020800 + O(x**15)"
+    assert str(Add(Add(-w, x, evaluate=False), Add(-y, z,  evaluate=False),  evaluate=False)) == "(-w + x) + (-y + z)"
+    assert str(Add(Add(-x, -y, evaluate=False), -z, evaluate=False)) == "-z + (-x - y)"
+    assert str(Add(Add(Add(-x, -y, evaluate=False), -z, evaluate=False), -t, evaluate=False)) == "-t + (-z + (-x - y))"
+
+
+def test_Catalan():
+    assert str(Catalan) == "Catalan"
+
+
+def test_ComplexInfinity():
+    assert str(zoo) == "zoo"
+
+
+def test_Derivative():
+    assert str(Derivative(x, y)) == "Derivative(x, y)"
+    assert str(Derivative(x**2, x, evaluate=False)) == "Derivative(x**2, x)"
+    assert str(Derivative(
+        x**2/y, x, y, evaluate=False)) == "Derivative(x**2/y, x, y)"
+
+
+def test_dict():
+    assert str({1: 1 + x}) == sstr({1: 1 + x}) == "{1: x + 1}"
+    assert str({1: x**2, 2: y*x}) in ("{1: x**2, 2: x*y}", "{2: x*y, 1: x**2}")
+    assert sstr({1: x**2, 2: y*x}) == "{1: x**2, 2: x*y}"
+
+
+def test_Dict():
+    assert str(Dict({1: 1 + x})) == sstr({1: 1 + x}) == "{1: x + 1}"
+    assert str(Dict({1: x**2, 2: y*x})) in (
+        "{1: x**2, 2: x*y}", "{2: x*y, 1: x**2}")
+    assert sstr(Dict({1: x**2, 2: y*x})) == "{1: x**2, 2: x*y}"
+
+
+def test_Dummy():
+    assert str(d) == "_d"
+    assert str(d + x) == "_d + x"
+
+
+def test_EulerGamma():
+    assert str(EulerGamma) == "EulerGamma"
+
+
+def test_Exp():
+    assert str(E) == "E"
+    with _exp_is_pow(True):
+        assert str(exp(x)) == "E**x"
+
+
+def test_factorial():
+    n = Symbol('n', integer=True)
+    assert str(factorial(-2)) == "zoo"
+    assert str(factorial(0)) == "1"
+    assert str(factorial(7)) == "5040"
+    assert str(factorial(n)) == "factorial(n)"
+    assert str(factorial(2*n)) == "factorial(2*n)"
+    assert str(factorial(factorial(n))) == 'factorial(factorial(n))'
+    assert str(factorial(factorial2(n))) == 'factorial(factorial2(n))'
+    assert str(factorial2(factorial(n))) == 'factorial2(factorial(n))'
+    assert str(factorial2(factorial2(n))) == 'factorial2(factorial2(n))'
+    assert str(subfactorial(3)) == "2"
+    assert str(subfactorial(n)) == "subfactorial(n)"
+    assert str(subfactorial(2*n)) == "subfactorial(2*n)"
+
+
+def test_Function():
+    f = Function('f')
+    fx = f(x)
+    w = WildFunction('w')
+    assert str(f) == "f"
+    assert str(fx) == "f(x)"
+    assert str(w) == "w_"
+
+
+def test_Geometry():
+    assert sstr(Point(0, 0)) == 'Point2D(0, 0)'
+    assert sstr(Circle(Point(0, 0), 3)) == 'Circle(Point2D(0, 0), 3)'
+    assert sstr(Ellipse(Point(1, 2), 3, 4)) == 'Ellipse(Point2D(1, 2), 3, 4)'
+    assert sstr(Triangle(Point(1, 1), Point(7, 8), Point(0, -1))) == \
+        'Triangle(Point2D(1, 1), Point2D(7, 8), Point2D(0, -1))'
+    assert sstr(Polygon(Point(5, 6), Point(-2, -3), Point(0, 0), Point(4, 7))) == \
+        'Polygon(Point2D(5, 6), Point2D(-2, -3), Point2D(0, 0), Point2D(4, 7))'
+    assert sstr(Triangle(Point(0, 0), Point(1, 0), Point(0, 1)), sympy_integers=True) == \
+        'Triangle(Point2D(S(0), S(0)), Point2D(S(1), S(0)), Point2D(S(0), S(1)))'
+    assert sstr(Ellipse(Point(1, 2), 3, 4), sympy_integers=True) == \
+        'Ellipse(Point2D(S(1), S(2)), S(3), S(4))'
+
+
+def test_GoldenRatio():
+    assert str(GoldenRatio) == "GoldenRatio"
+
+
+def test_Heaviside():
+    assert str(Heaviside(x)) == str(Heaviside(x, S.Half)) == "Heaviside(x)"
+    assert str(Heaviside(x, 1)) == "Heaviside(x, 1)"
+
+
+def test_TribonacciConstant():
+    assert str(TribonacciConstant) == "TribonacciConstant"
+
+
+def test_ImaginaryUnit():
+    assert str(I) == "I"
+
+
+def test_Infinity():
+    assert str(oo) == "oo"
+    assert str(oo*I) == "oo*I"
+
+
+def test_Integer():
+    assert str(Integer(-1)) == "-1"
+    assert str(Integer(1)) == "1"
+    assert str(Integer(-3)) == "-3"
+    assert str(Integer(0)) == "0"
+    assert str(Integer(25)) == "25"
+
+
+def test_Integral():
+    assert str(Integral(sin(x), y)) == "Integral(sin(x), y)"
+    assert str(Integral(sin(x), (y, 0, 1))) == "Integral(sin(x), (y, 0, 1))"
+
+
+def test_Interval():
+    n = (S.NegativeInfinity, 1, 2, S.Infinity)
+    for i in range(len(n)):
+        for j in range(i + 1, len(n)):
+            for l in (True, False):
+                for r in (True, False):
+                    ival = Interval(n[i], n[j], l, r)
+                    assert S(str(ival)) == ival
+
+
+def test_AccumBounds():
+    a = Symbol('a', real=True)
+    assert str(AccumBounds(0, a)) == "AccumBounds(0, a)"
+    assert str(AccumBounds(0, 1)) == "AccumBounds(0, 1)"
+
+
+def test_Lambda():
+    assert str(Lambda(d, d**2)) == "Lambda(_d, _d**2)"
+    # issue 2908
+    assert str(Lambda((), 1)) == "Lambda((), 1)"
+    assert str(Lambda((), x)) == "Lambda((), x)"
+    assert str(Lambda((x, y), x+y)) == "Lambda((x, y), x + y)"
+    assert str(Lambda(((x, y),), x+y)) == "Lambda(((x, y),), x + y)"
+
+
+def test_Limit():
+    assert str(Limit(sin(x)/x, x, y)) == "Limit(sin(x)/x, x, y, dir='+')"
+    assert str(Limit(1/x, x, 0)) == "Limit(1/x, x, 0, dir='+')"
+    assert str(
+        Limit(sin(x)/x, x, y, dir="-")) == "Limit(sin(x)/x, x, y, dir='-')"
+
+
+def test_list():
+    assert str([x]) == sstr([x]) == "[x]"
+    assert str([x**2, x*y + 1]) == sstr([x**2, x*y + 1]) == "[x**2, x*y + 1]"
+    assert str([x**2, [y + x]]) == sstr([x**2, [y + x]]) == "[x**2, [x + y]]"
+
+
+def test_Matrix_str():
+    M = Matrix([[x**+1, 1], [y, x + y]])
+    assert str(M) == "Matrix([[x, 1], [y, x + y]])"
+    assert sstr(M) == "Matrix([\n[x,     1],\n[y, x + y]])"
+    M = Matrix([[1]])
+    assert str(M) == sstr(M) == "Matrix([[1]])"
+    M = Matrix([[1, 2]])
+    assert str(M) == sstr(M) ==  "Matrix([[1, 2]])"
+    M = Matrix()
+    assert str(M) == sstr(M) == "Matrix(0, 0, [])"
+    M = Matrix(0, 1, lambda i, j: 0)
+    assert str(M) == sstr(M) == "Matrix(0, 1, [])"
+
+
+def test_Mul():
+    assert str(x/y) == "x/y"
+    assert str(y/x) == "y/x"
+    assert str(x/y/z) == "x/(y*z)"
+    assert str((x + 1)/(y + 2)) == "(x + 1)/(y + 2)"
+    assert str(2*x/3) == '2*x/3'
+    assert str(-2*x/3) == '-2*x/3'
+    assert str(-1.0*x) == '-1.0*x'
+    assert str(1.0*x) == '1.0*x'
+    assert str(Mul(0, 1, evaluate=False)) == '0*1'
+    assert str(Mul(1, 0, evaluate=False)) == '1*0'
+    assert str(Mul(1, 1, evaluate=False)) == '1*1'
+    assert str(Mul(1, 1, 1, evaluate=False)) == '1*1*1'
+    assert str(Mul(1, 2, evaluate=False)) == '1*2'
+    assert str(Mul(1, S.Half, evaluate=False)) == '1*(1/2)'
+    assert str(Mul(1, 1, S.Half, evaluate=False)) == '1*1*(1/2)'
+    assert str(Mul(1, 1, 2, 3, x, evaluate=False)) == '1*1*2*3*x'
+    assert str(Mul(1, -1, evaluate=False)) == '1*(-1)'
+    assert str(Mul(-1, 1, evaluate=False)) == '-1*1'
+    assert str(Mul(4, 3, 2, 1, 0, y, x, evaluate=False)) == '4*3*2*1*0*y*x'
+    assert str(Mul(4, 3, 2, 1+z, 0, y, x, evaluate=False)) == '4*3*2*(z + 1)*0*y*x'
+    assert str(Mul(Rational(2, 3), Rational(5, 7), evaluate=False)) == '(2/3)*(5/7)'
+    # For issue 14160
+    assert str(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False),
+                                                evaluate=False)) == '-2*x/(y*y)'
+    # issue 21537
+    assert str(Mul(x, Pow(1/y, -1, evaluate=False), evaluate=False)) == 'x/(1/y)'
+
+    # Issue 24108
+    from sympy.core.parameters import evaluate
+    with evaluate(False):
+        assert str(Mul(Pow(Integer(2), Integer(-1)), Add(Integer(-1), Mul(Integer(-1), Integer(1))))) == "(-1 - 1*1)/2"
+
+    class CustomClass1(Expr):
+        is_commutative = True
+
+    class CustomClass2(Expr):
+        is_commutative = True
+    cc1 = CustomClass1()
+    cc2 = CustomClass2()
+    assert str(Rational(2)*cc1) == '2*CustomClass1()'
+    assert str(cc1*Rational(2)) == '2*CustomClass1()'
+    assert str(cc1*Float("1.5")) == '1.5*CustomClass1()'
+    assert str(cc2*Rational(2)) == '2*CustomClass2()'
+    assert str(cc2*Rational(2)*cc1) == '2*CustomClass1()*CustomClass2()'
+    assert str(cc1*Rational(2)*cc2) == '2*CustomClass1()*CustomClass2()'
+
+
+def test_NaN():
+    assert str(nan) == "nan"
+
+
+def test_NegativeInfinity():
+    assert str(-oo) == "-oo"
+
+def test_Order():
+    assert str(O(x)) == "O(x)"
+    assert str(O(x**2)) == "O(x**2)"
+    assert str(O(x*y)) == "O(x*y, x, y)"
+    assert str(O(x, x)) == "O(x)"
+    assert str(O(x, (x, 0))) == "O(x)"
+    assert str(O(x, (x, oo))) == "O(x, (x, oo))"
+    assert str(O(x, x, y)) == "O(x, x, y)"
+    assert str(O(x, x, y)) == "O(x, x, y)"
+    assert str(O(x, (x, oo), (y, oo))) == "O(x, (x, oo), (y, oo))"
+
+
+def test_Permutation_Cycle():
+    from sympy.combinatorics import Permutation, Cycle
+
+    # general principle: economically, canonically show all moved elements
+    # and the size of the permutation.
+
+    for p, s in [
+        (Cycle(),
+        '()'),
+        (Cycle(2),
+        '(2)'),
+        (Cycle(2, 1),
+        '(1 2)'),
+        (Cycle(1, 2)(5)(6, 7)(10),
+        '(1 2)(6 7)(10)'),
+        (Cycle(3, 4)(1, 2)(3, 4),
+        '(1 2)(4)'),
+    ]:
+        assert sstr(p) == s
+
+    for p, s in [
+        (Permutation([]),
+        'Permutation([])'),
+        (Permutation([], size=1),
+        'Permutation([0])'),
+        (Permutation([], size=2),
+        'Permutation([0, 1])'),
+        (Permutation([], size=10),
+        'Permutation([], size=10)'),
+        (Permutation([1, 0, 2]),
+        'Permutation([1, 0, 2])'),
+        (Permutation([1, 0, 2, 3, 4, 5]),
+        'Permutation([1, 0], size=6)'),
+        (Permutation([1, 0, 2, 3, 4, 5], size=10),
+        'Permutation([1, 0], size=10)'),
+    ]:
+        assert sstr(p, perm_cyclic=False) == s
+
+    for p, s in [
+        (Permutation([]),
+        '()'),
+        (Permutation([], size=1),
+        '(0)'),
+        (Permutation([], size=2),
+        '(1)'),
+        (Permutation([], size=10),
+        '(9)'),
+        (Permutation([1, 0, 2]),
+        '(2)(0 1)'),
+        (Permutation([1, 0, 2, 3, 4, 5]),
+        '(5)(0 1)'),
+        (Permutation([1, 0, 2, 3, 4, 5], size=10),
+        '(9)(0 1)'),
+        (Permutation([0, 1, 3, 2, 4, 5], size=10),
+        '(9)(2 3)'),
+    ]:
+        assert sstr(p) == s
+
+
+    with warns_deprecated_sympy():
+        old_print_cyclic = Permutation.print_cyclic
+        Permutation.print_cyclic = False
+        assert sstr(Permutation([1, 0, 2])) == 'Permutation([1, 0, 2])'
+        Permutation.print_cyclic = old_print_cyclic
+
+def test_Pi():
+    assert str(pi) == "pi"
+
+
+def test_Poly():
+    assert str(Poly(0, x)) == "Poly(0, x, domain='ZZ')"
+    assert str(Poly(1, x)) == "Poly(1, x, domain='ZZ')"
+    assert str(Poly(x, x)) == "Poly(x, x, domain='ZZ')"
+
+    assert str(Poly(2*x + 1, x)) == "Poly(2*x + 1, x, domain='ZZ')"
+    assert str(Poly(2*x - 1, x)) == "Poly(2*x - 1, x, domain='ZZ')"
+
+    assert str(Poly(-1, x)) == "Poly(-1, x, domain='ZZ')"
+    assert str(Poly(-x, x)) == "Poly(-x, x, domain='ZZ')"
+
+    assert str(Poly(-2*x + 1, x)) == "Poly(-2*x + 1, x, domain='ZZ')"
+    assert str(Poly(-2*x - 1, x)) == "Poly(-2*x - 1, x, domain='ZZ')"
+
+    assert str(Poly(x - 1, x)) == "Poly(x - 1, x, domain='ZZ')"
+    assert str(Poly(2*x + x**5, x)) == "Poly(x**5 + 2*x, x, domain='ZZ')"
+
+    assert str(Poly(3**(2*x), 3**x)) == "Poly((3**x)**2, 3**x, domain='ZZ')"
+    assert str(Poly((x**2)**x)) == "Poly(((x**2)**x), (x**2)**x, domain='ZZ')"
+
+    assert str(Poly((x + y)**3, (x + y), expand=False)
+                ) == "Poly((x + y)**3, x + y, domain='ZZ')"
+    assert str(Poly((x - 1)**2, (x - 1), expand=False)
+                ) == "Poly((x - 1)**2, x - 1, domain='ZZ')"
+
+    assert str(
+        Poly(x**2 + 1 + y, x)) == "Poly(x**2 + y + 1, x, domain='ZZ[y]')"
+    assert str(
+        Poly(x**2 - 1 + y, x)) == "Poly(x**2 + y - 1, x, domain='ZZ[y]')"
+
+    assert str(Poly(x**2 + I*x, x)) == "Poly(x**2 + I*x, x, domain='ZZ_I')"
+    assert str(Poly(x**2 - I*x, x)) == "Poly(x**2 - I*x, x, domain='ZZ_I')"
+
+    assert str(Poly(-x*y*z + x*y - 1, x, y, z)
+               ) == "Poly(-x*y*z + x*y - 1, x, y, z, domain='ZZ')"
+    assert str(Poly(-w*x**21*y**7*z + (1 + w)*z**3 - 2*x*z + 1, x, y, z)) == \
+        "Poly(-w*x**21*y**7*z - 2*x*z + (w + 1)*z**3 + 1, x, y, z, domain='ZZ[w]')"
+
+    assert str(Poly(x**2 + 1, x, modulus=2)) == "Poly(x**2 + 1, x, modulus=2)"
+    assert str(Poly(2*x**2 + 3*x + 4, x, modulus=17)) == "Poly(2*x**2 + 3*x + 4, x, modulus=17)"
+
+
+def test_PolyRing():
+    assert str(ring("x", ZZ, lex)[0]) == "Polynomial ring in x over ZZ with lex order"
+    assert str(ring("x,y", QQ, grlex)[0]) == "Polynomial ring in x, y over QQ with grlex order"
+    assert str(ring("x,y,z", ZZ["t"], lex)[0]) == "Polynomial ring in x, y, z over ZZ[t] with lex order"
+
+
+def test_FracField():
+    assert str(field("x", ZZ, lex)[0]) == "Rational function field in x over ZZ with lex order"
+    assert str(field("x,y", QQ, grlex)[0]) == "Rational function field in x, y over QQ with grlex order"
+    assert str(field("x,y,z", ZZ["t"], lex)[0]) == "Rational function field in x, y, z over ZZ[t] with lex order"
+
+
+def test_PolyElement():
+    Ruv, u,v = ring("u,v", ZZ)
+    Rxyz, x,y,z = ring("x,y,z", Ruv)
+    Rx_zzi, xz = ring("x", ZZ_I)
+
+    assert str(x - x) == "0"
+    assert str(x - 1) == "x - 1"
+    assert str(x + 1) == "x + 1"
+    assert str(x**2) == "x**2"
+
+    assert str((u**2 + 3*u*v + 1)*x**2*y + u + 1) == "(u**2 + 3*u*v + 1)*x**2*y + u + 1"
+    assert str((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x) == "(u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x"
+    assert str((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1) == "(u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1"
+    assert str((-u**2 + 3*u*v - 1)*x**2*y - (u + 1)*x - 1) == "-(u**2 - 3*u*v + 1)*x**2*y - (u + 1)*x - 1"
+
+    assert str(-(v**2 + v + 1)*x + 3*u*v + 1) == "-(v**2 + v + 1)*x + 3*u*v + 1"
+    assert str(-(v**2 + v + 1)*x - 3*u*v + 1) == "-(v**2 + v + 1)*x - 3*u*v + 1"
+
+    assert str((1+I)*xz + 2) == "(1 + 1*I)*x + (2 + 0*I)"
+
+
+def test_FracElement():
+    Fuv, u,v = field("u,v", ZZ)
+    Fxyzt, x,y,z,t = field("x,y,z,t", Fuv)
+    Rx_zzi, xz = field("x", QQ_I)
+    i = QQ_I(0, 1)
+
+    assert str(x - x) == "0"
+    assert str(x - 1) == "x - 1"
+    assert str(x + 1) == "x + 1"
+
+    assert str(x/3) == "x/3"
+    assert str(x/z) == "x/z"
+    assert str(x*y/z) == "x*y/z"
+    assert str(x/(z*t)) == "x/(z*t)"
+    assert str(x*y/(z*t)) == "x*y/(z*t)"
+
+    assert str((x - 1)/y) == "(x - 1)/y"
+    assert str((x + 1)/y) == "(x + 1)/y"
+    assert str((-x - 1)/y) == "(-x - 1)/y"
+    assert str((x + 1)/(y*z)) == "(x + 1)/(y*z)"
+    assert str(-y/(x + 1)) == "-y/(x + 1)"
+    assert str(y*z/(x + 1)) == "y*z/(x + 1)"
+
+    assert str(((u + 1)*x*y + 1)/((v - 1)*z - 1)) == "((u + 1)*x*y + 1)/((v - 1)*z - 1)"
+    assert str(((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)) == "((u + 1)*x*y + 1)/((v - 1)*z - u*v*t - 1)"
+
+    assert str((1+i)/xz) == "(1 + 1*I)/x"
+    assert str(((1+i)*xz - i)/xz) == "((1 + 1*I)*x + (0 + -1*I))/x"
+
+
+def test_GaussianInteger():
+    assert str(ZZ_I(1, 0)) == "1"
+    assert str(ZZ_I(-1, 0)) == "-1"
+    assert str(ZZ_I(0, 1)) == "I"
+    assert str(ZZ_I(0, -1)) == "-I"
+    assert str(ZZ_I(0, 2)) == "2*I"
+    assert str(ZZ_I(0, -2)) == "-2*I"
+    assert str(ZZ_I(1, 1)) == "1 + I"
+    assert str(ZZ_I(-1, -1)) == "-1 - I"
+    assert str(ZZ_I(-1, -2)) == "-1 - 2*I"
+
+
+def test_GaussianRational():
+    assert str(QQ_I(1, 0)) == "1"
+    assert str(QQ_I(QQ(2, 3), 0)) == "2/3"
+    assert str(QQ_I(0, QQ(2, 3))) == "2*I/3"
+    assert str(QQ_I(QQ(1, 2), QQ(-2, 3))) == "1/2 - 2*I/3"
+
+
+def test_Pow():
+    assert str(x**-1) == "1/x"
+    assert str(x**-2) == "x**(-2)"
+    assert str(x**2) == "x**2"
+    assert str((x + y)**-1) == "1/(x + y)"
+    assert str((x + y)**-2) == "(x + y)**(-2)"
+    assert str((x + y)**2) == "(x + y)**2"
+    assert str((x + y)**(1 + x)) == "(x + y)**(x + 1)"
+    assert str(x**Rational(1, 3)) == "x**(1/3)"
+    assert str(1/x**Rational(1, 3)) == "x**(-1/3)"
+    assert str(sqrt(sqrt(x))) == "x**(1/4)"
+    # not the same as x**-1
+    assert str(x**-1.0) == 'x**(-1.0)'
+    # see issue #2860
+    assert str(Pow(S(2), -1.0, evaluate=False)) == '2**(-1.0)'
+
+
+def test_sqrt():
+    assert str(sqrt(x)) == "sqrt(x)"
+    assert str(sqrt(x**2)) == "sqrt(x**2)"
+    assert str(1/sqrt(x)) == "1/sqrt(x)"
+    assert str(1/sqrt(x**2)) == "1/sqrt(x**2)"
+    assert str(y/sqrt(x)) == "y/sqrt(x)"
+    assert str(x**0.5) == "x**0.5"
+    assert str(1/x**0.5) == "x**(-0.5)"
+
+
+def test_Rational():
+    n1 = Rational(1, 4)
+    n2 = Rational(1, 3)
+    n3 = Rational(2, 4)
+    n4 = Rational(2, -4)
+    n5 = Rational(0)
+    n7 = Rational(3)
+    n8 = Rational(-3)
+    assert str(n1*n2) == "1/12"
+    assert str(n1*n2) == "1/12"
+    assert str(n3) == "1/2"
+    assert str(n1*n3) == "1/8"
+    assert str(n1 + n3) == "3/4"
+    assert str(n1 + n2) == "7/12"
+    assert str(n1 + n4) == "-1/4"
+    assert str(n4*n4) == "1/4"
+    assert str(n4 + n2) == "-1/6"
+    assert str(n4 + n5) == "-1/2"
+    assert str(n4*n5) == "0"
+    assert str(n3 + n4) == "0"
+    assert str(n1**n7) == "1/64"
+    assert str(n2**n7) == "1/27"
+    assert str(n2**n8) == "27"
+    assert str(n7**n8) == "1/27"
+    assert str(Rational("-25")) == "-25"
+    assert str(Rational("1.25")) == "5/4"
+    assert str(Rational("-2.6e-2")) == "-13/500"
+    assert str(S("25/7")) == "25/7"
+    assert str(S("-123/569")) == "-123/569"
+    assert str(S("0.1[23]", rational=1)) == "61/495"
+    assert str(S("5.1[666]", rational=1)) == "31/6"
+    assert str(S("-5.1[666]", rational=1)) == "-31/6"
+    assert str(S("0.[9]", rational=1)) == "1"
+    assert str(S("-0.[9]", rational=1)) == "-1"
+
+    assert str(sqrt(Rational(1, 4))) == "1/2"
+    assert str(sqrt(Rational(1, 36))) == "1/6"
+
+    assert str((123**25) ** Rational(1, 25)) == "123"
+    assert str((123**25 + 1)**Rational(1, 25)) != "123"
+    assert str((123**25 - 1)**Rational(1, 25)) != "123"
+    assert str((123**25 - 1)**Rational(1, 25)) != "122"
+
+    assert str(sqrt(Rational(81, 36))**3) == "27/8"
+    assert str(1/sqrt(Rational(81, 36))**3) == "8/27"
+
+    assert str(sqrt(-4)) == str(2*I)
+    assert str(2**Rational(1, 10**10)) == "2**(1/10000000000)"
+
+    assert sstr(Rational(2, 3), sympy_integers=True) == "S(2)/3"
+    x = Symbol("x")
+    assert sstr(x**Rational(2, 3), sympy_integers=True) == "x**(S(2)/3)"
+    assert sstr(Eq(x, Rational(2, 3)), sympy_integers=True) == "Eq(x, S(2)/3)"
+    assert sstr(Limit(x, x, Rational(7, 2)), sympy_integers=True) == \
+        "Limit(x, x, S(7)/2, dir='+')"
+
+
+def test_Float():
+    # NOTE dps is the whole number of decimal digits
+    assert str(Float('1.23', dps=1 + 2)) == '1.23'
+    assert str(Float('1.23456789', dps=1 + 8)) == '1.23456789'
+    assert str(
+        Float('1.234567890123456789', dps=1 + 18)) == '1.234567890123456789'
+    assert str(pi.evalf(1 + 2)) == '3.14'
+    assert str(pi.evalf(1 + 14)) == '3.14159265358979'
+    assert str(pi.evalf(1 + 64)) == ('3.141592653589793238462643383279'
+                                     '5028841971693993751058209749445923')
+    assert str(pi.round(-1)) == '0.0'
+    assert str((pi**400 - (pi**400).round(1)).n(2)) == '-0.e+88'
+    assert sstr(Float("100"), full_prec=False, min=-2, max=2) == '1.0e+2'
+    assert sstr(Float("100"), full_prec=False, min=-2, max=3) == '100.0'
+    assert sstr(Float("0.1"), full_prec=False, min=-2, max=3) == '0.1'
+    assert sstr(Float("0.099"), min=-2, max=3) == '9.90000000000000e-2'
+
+
+def test_Relational():
+    assert str(Rel(x, y, "<")) == "x < y"
+    assert str(Rel(x + y, y, "==")) == "Eq(x + y, y)"
+    assert str(Rel(x, y, "!=")) == "Ne(x, y)"
+    assert str(Eq(x, 1) | Eq(x, 2)) == "Eq(x, 1) | Eq(x, 2)"
+    assert str(Ne(x, 1) & Ne(x, 2)) == "Ne(x, 1) & Ne(x, 2)"
+
+
+def test_AppliedBinaryRelation():
+    assert str(Q.eq(x, y)) == "Q.eq(x, y)"
+    assert str(Q.ne(x, y)) == "Q.ne(x, y)"
+
+
+def test_CRootOf():
+    assert str(rootof(x**5 + 2*x - 1, 0)) == "CRootOf(x**5 + 2*x - 1, 0)"
+
+
+def test_RootSum():
+    f = x**5 + 2*x - 1
+
+    assert str(
+        RootSum(f, Lambda(z, z), auto=False)) == "RootSum(x**5 + 2*x - 1)"
+    assert str(RootSum(f, Lambda(
+        z, z**2), auto=False)) == "RootSum(x**5 + 2*x - 1, Lambda(z, z**2))"
+
+
+def test_GroebnerBasis():
+    assert str(groebner(
+        [], x, y)) == "GroebnerBasis([], x, y, domain='ZZ', order='lex')"
+
+    F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1]
+
+    assert str(groebner(F, order='grlex')) == \
+        "GroebnerBasis([x**2 - x - 3*y + 1, y**2 - 2*x + y - 1], x, y, domain='ZZ', order='grlex')"
+    assert str(groebner(F, order='lex')) == \
+        "GroebnerBasis([2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7], x, y, domain='ZZ', order='lex')"
+
+def test_set():
+    assert sstr(set()) == 'set()'
+    assert sstr(frozenset()) == 'frozenset()'
+
+    assert sstr({1}) == '{1}'
+    assert sstr(frozenset([1])) == 'frozenset({1})'
+    assert sstr({1, 2, 3}) == '{1, 2, 3}'
+    assert sstr(frozenset([1, 2, 3])) == 'frozenset({1, 2, 3})'
+
+    assert sstr(
+        {1, x, x**2, x**3, x**4}) == '{1, x, x**2, x**3, x**4}'
+    assert sstr(
+        frozenset([1, x, x**2, x**3, x**4])) == 'frozenset({1, x, x**2, x**3, x**4})'
+
+
+def test_SparseMatrix():
+    M = SparseMatrix([[x**+1, 1], [y, x + y]])
+    assert str(M) == "Matrix([[x, 1], [y, x + y]])"
+    assert sstr(M) == "Matrix([\n[x,     1],\n[y, x + y]])"
+
+
+def test_Sum():
+    assert str(summation(cos(3*z), (z, x, y))) == "Sum(cos(3*z), (z, x, y))"
+    assert str(Sum(x*y**2, (x, -2, 2), (y, -5, 5))) == \
+        "Sum(x*y**2, (x, -2, 2), (y, -5, 5))"
+
+
+def test_Symbol():
+    assert str(y) == "y"
+    assert str(x) == "x"
+    e = x
+    assert str(e) == "x"
+
+
+def test_tuple():
+    assert str((x,)) == sstr((x,)) == "(x,)"
+    assert str((x + y, 1 + x)) == sstr((x + y, 1 + x)) == "(x + y, x + 1)"
+    assert str((x + y, (
+        1 + x, x**2))) == sstr((x + y, (1 + x, x**2))) == "(x + y, (x + 1, x**2))"
+
+
+def test_Series_str():
+    tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y)
+    tf2 = TransferFunction(x - y, x + y, y)
+    tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y)
+    assert str(Series(tf1, tf2)) == \
+        "Series(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y))"
+    assert str(Series(tf1, tf2, tf3)) == \
+        "Series(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y), TransferFunction(t*x**2 - t**w*x + w, t - y, y))"
+    assert str(Series(-tf2, tf1)) == \
+        "Series(TransferFunction(-x + y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y))"
+
+
+def test_MIMOSeries_str():
+    tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y)
+    tf2 = TransferFunction(x - y, x + y, y)
+    tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
+    tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]])
+    assert str(MIMOSeries(tfm_1, tfm_2)) == \
+        "MIMOSeries(TransferFunctionMatrix(((TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), "\
+            "(TransferFunction(x - y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y)))), "\
+                "TransferFunctionMatrix(((TransferFunction(x - y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y)), "\
+                    "(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)))))"
+
+
+def test_TransferFunction_str():
+    tf1 = TransferFunction(x - 1, x + 1, x)
+    assert str(tf1) == "TransferFunction(x - 1, x + 1, x)"
+    tf2 = TransferFunction(x + 1, 2 - y, x)
+    assert str(tf2) == "TransferFunction(x + 1, 2 - y, x)"
+    tf3 = TransferFunction(y, y**2 + 2*y + 3, y)
+    assert str(tf3) == "TransferFunction(y, y**2 + 2*y + 3, y)"
+
+
+def test_Parallel_str():
+    tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y)
+    tf2 = TransferFunction(x - y, x + y, y)
+    tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y)
+    assert str(Parallel(tf1, tf2)) == \
+        "Parallel(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y))"
+    assert str(Parallel(tf1, tf2, tf3)) == \
+        "Parallel(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y), TransferFunction(t*x**2 - t**w*x + w, t - y, y))"
+    assert str(Parallel(-tf2, tf1)) == \
+        "Parallel(TransferFunction(-x + y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y))"
+
+
+def test_MIMOParallel_str():
+    tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y)
+    tf2 = TransferFunction(x - y, x + y, y)
+    tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
+    tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]])
+    assert str(MIMOParallel(tfm_1, tfm_2)) == \
+        "MIMOParallel(TransferFunctionMatrix(((TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), "\
+            "(TransferFunction(x - y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y)))), "\
+                "TransferFunctionMatrix(((TransferFunction(x - y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y)), "\
+                    "(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)))))"
+
+
+def test_Feedback_str():
+    tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y)
+    tf2 = TransferFunction(x - y, x + y, y)
+    tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y)
+    assert str(Feedback(tf1*tf2, tf3)) == \
+        "Feedback(Series(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), " \
+        "TransferFunction(t*x**2 - t**w*x + w, t - y, y), -1)"
+    assert str(Feedback(tf1, TransferFunction(1, 1, y), 1)) == \
+        "Feedback(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(1, 1, y), 1)"
+
+
+def test_MIMOFeedback_str():
+    tf1 = TransferFunction(x**2 - y**3, y - z, x)
+    tf2 = TransferFunction(y - x, z + y, x)
+    tfm_1 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]])
+    tfm_2 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
+    assert (str(MIMOFeedback(tfm_1, tfm_2)) \
+            == "MIMOFeedback(TransferFunctionMatrix(((TransferFunction(-x + y, y + z, x), TransferFunction(x**2 - y**3, y - z, x))," \
+            " (TransferFunction(x**2 - y**3, y - z, x), TransferFunction(-x + y, y + z, x)))), " \
+            "TransferFunctionMatrix(((TransferFunction(x**2 - y**3, y - z, x), " \
+            "TransferFunction(-x + y, y + z, x)), (TransferFunction(-x + y, y + z, x), TransferFunction(x**2 - y**3, y - z, x)))), -1)")
+    assert (str(MIMOFeedback(tfm_1, tfm_2, 1)) \
+            == "MIMOFeedback(TransferFunctionMatrix(((TransferFunction(-x + y, y + z, x), TransferFunction(x**2 - y**3, y - z, x)), " \
+            "(TransferFunction(x**2 - y**3, y - z, x), TransferFunction(-x + y, y + z, x)))), " \
+            "TransferFunctionMatrix(((TransferFunction(x**2 - y**3, y - z, x), TransferFunction(-x + y, y + z, x)), "\
+            "(TransferFunction(-x + y, y + z, x), TransferFunction(x**2 - y**3, y - z, x)))), 1)")
+
+
+def test_TransferFunctionMatrix_str():
+    tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y)
+    tf2 = TransferFunction(x - y, x + y, y)
+    tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y)
+    assert str(TransferFunctionMatrix([[tf1], [tf2]])) == \
+        "TransferFunctionMatrix(((TransferFunction(x*y**2 - z, -t**3 + y**3, y),), (TransferFunction(x - y, x + y, y),)))"
+    assert str(TransferFunctionMatrix([[tf1, tf2], [tf3, tf2]])) == \
+        "TransferFunctionMatrix(((TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), (TransferFunction(t*x**2 - t**w*x + w, t - y, y), TransferFunction(x - y, x + y, y))))"
+
+
+def test_Quaternion_str_printer():
+    q = Quaternion(x, y, z, t)
+    assert str(q) == "x + y*i + z*j + t*k"
+    q = Quaternion(x,y,z,x*t)
+    assert str(q) == "x + y*i + z*j + t*x*k"
+    q = Quaternion(x,y,z,x+t)
+    assert str(q) == "x + y*i + z*j + (t + x)*k"
+
+
+def test_Quantity_str():
+    assert sstr(second, abbrev=True) == "s"
+    assert sstr(joule, abbrev=True) == "J"
+    assert str(second) == "second"
+    assert str(joule) == "joule"
+
+
+def test_wild_str():
+    # Check expressions containing Wild not causing infinite recursion
+    w = Wild('x')
+    assert str(w + 1) == 'x_ + 1'
+    assert str(exp(2**w) + 5) == 'exp(2**x_) + 5'
+    assert str(3*w + 1) == '3*x_ + 1'
+    assert str(1/w + 1) == '1 + 1/x_'
+    assert str(w**2 + 1) == 'x_**2 + 1'
+    assert str(1/(1 - w)) == '1/(1 - x_)'
+
+
+def test_wild_matchpy():
+    from sympy.utilities.matchpy_connector import WildDot, WildPlus, WildStar
+
+    matchpy = import_module("matchpy")
+
+    if matchpy is None:
+        return
+
+    wd = WildDot('w_')
+    wp = WildPlus('w__')
+    ws = WildStar('w___')
+
+    assert str(wd) == 'w_'
+    assert str(wp) == 'w__'
+    assert str(ws) == 'w___'
+
+    assert str(wp/ws + 2**wd) == '2**w_ + w__/w___'
+    assert str(sin(wd)*cos(wp)*sqrt(ws)) == 'sqrt(w___)*sin(w_)*cos(w__)'
+
+
+def test_zeta():
+    assert str(zeta(3)) == "zeta(3)"
+
+
+def test_issue_3101():
+    e = x - y
+    a = str(e)
+    b = str(e)
+    assert a == b
+
+
+def test_issue_3103():
+    e = -2*sqrt(x) - y/sqrt(x)/2
+    assert str(e) not in ["(-2)*x**1/2(-1/2)*x**(-1/2)*y",
+            "-2*x**1/2(-1/2)*x**(-1/2)*y", "-2*x**1/2-1/2*x**-1/2*w"]
+    assert str(e) == "-2*sqrt(x) - y/(2*sqrt(x))"
+
+
+def test_issue_4021():
+    e = Integral(x, x) + 1
+    assert str(e) == 'Integral(x, x) + 1'
+
+
+def test_sstrrepr():
+    assert sstr('abc') == 'abc'
+    assert sstrrepr('abc') == "'abc'"
+
+    e = ['a', 'b', 'c', x]
+    assert sstr(e) == "[a, b, c, x]"
+    assert sstrrepr(e) == "['a', 'b', 'c', x]"
+
+
+def test_infinity():
+    assert sstr(oo*I) == "oo*I"
+
+
+def test_full_prec():
+    assert sstr(S("0.3"), full_prec=True) == "0.300000000000000"
+    assert sstr(S("0.3"), full_prec="auto") == "0.300000000000000"
+    assert sstr(S("0.3"), full_prec=False) == "0.3"
+    assert sstr(S("0.3")*x, full_prec=True) in [
+        "0.300000000000000*x",
+        "x*0.300000000000000"
+    ]
+    assert sstr(S("0.3")*x, full_prec="auto") in [
+        "0.3*x",
+        "x*0.3"
+    ]
+    assert sstr(S("0.3")*x, full_prec=False) in [
+        "0.3*x",
+        "x*0.3"
+    ]
+
+
+def test_noncommutative():
+    A, B, C = symbols('A,B,C', commutative=False)
+
+    assert sstr(A*B*C**-1) == "A*B*C**(-1)"
+    assert sstr(C**-1*A*B) == "C**(-1)*A*B"
+    assert sstr(A*C**-1*B) == "A*C**(-1)*B"
+    assert sstr(sqrt(A)) == "sqrt(A)"
+    assert sstr(1/sqrt(A)) == "A**(-1/2)"
+
+
+def test_empty_printer():
+    str_printer = StrPrinter()
+    assert str_printer.emptyPrinter("foo") == "foo"
+    assert str_printer.emptyPrinter(x*y) == "x*y"
+    assert str_printer.emptyPrinter(32) == "32"
+
+def test_decimal_printer():
+    dec_printer = StrPrinter(settings={"dps":3})
+    f = Function('f')
+    assert dec_printer.doprint(f(1.329294)) == "f(1.33)"
+
+
+def test_settings():
+    raises(TypeError, lambda: sstr(S(4), method="garbage"))
+
+
+def test_RandomDomain():
+    from sympy.stats import Normal, Die, Exponential, pspace, where
+    X = Normal('x1', 0, 1)
+    assert str(where(X > 0)) == "Domain: (0 < x1) & (x1 < oo)"
+
+    D = Die('d1', 6)
+    assert str(where(D > 4)) == "Domain: Eq(d1, 5) | Eq(d1, 6)"
+
+    A = Exponential('a', 1)
+    B = Exponential('b', 1)
+    assert str(pspace(Tuple(A, B)).domain) == "Domain: (0 <= a) & (0 <= b) & (a < oo) & (b < oo)"
+
+
+def test_FiniteSet():
+    assert str(FiniteSet(*range(1, 51))) == (
+        '{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,'
+        ' 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,'
+        ' 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50}'
+    )
+    assert str(FiniteSet(*range(1, 6))) == '{1, 2, 3, 4, 5}'
+    assert str(FiniteSet(*[x*y, x**2])) == '{x**2, x*y}'
+    assert str(FiniteSet(FiniteSet(FiniteSet(x, y), 5), FiniteSet(x,y), 5)
+               ) == 'FiniteSet(5, FiniteSet(5, {x, y}), {x, y})'
+
+
+def test_Partition():
+    assert str(Partition(FiniteSet(x, y), {z})) == 'Partition({z}, {x, y})'
+
+def test_UniversalSet():
+    assert str(S.UniversalSet) == 'UniversalSet'
+
+
+def test_PrettyPoly():
+    F = QQ.frac_field(x, y)
+    R = QQ[x, y]
+    assert sstr(F.convert(x/(x + y))) == sstr(x/(x + y))
+    assert sstr(R.convert(x + y)) == sstr(x + y)
+
+
+def test_categories():
+    from sympy.categories import (Object, NamedMorphism,
+        IdentityMorphism, Category)
+
+    A = Object("A")
+    B = Object("B")
+
+    f = NamedMorphism(A, B, "f")
+    id_A = IdentityMorphism(A)
+
+    K = Category("K")
+
+    assert str(A) == 'Object("A")'
+    assert str(f) == 'NamedMorphism(Object("A"), Object("B"), "f")'
+    assert str(id_A) == 'IdentityMorphism(Object("A"))'
+
+    assert str(K) == 'Category("K")'
+
+
+def test_Tr():
+    A, B = symbols('A B', commutative=False)
+    t = Tr(A*B)
+    assert str(t) == 'Tr(A*B)'
+
+
+def test_issue_6387():
+    assert str(factor(-3.0*z + 3)) == '-3.0*(1.0*z - 1.0)'
+
+
+def test_MatMul_MatAdd():
+    X, Y = MatrixSymbol("X", 2, 2), MatrixSymbol("Y", 2, 2)
+    assert str(2*(X + Y)) == "2*X + 2*Y"
+
+    assert str(I*X) == "I*X"
+    assert str(-I*X) == "-I*X"
+    assert str((1 + I)*X) == '(1 + I)*X'
+    assert str(-(1 + I)*X) == '(-1 - I)*X'
+    assert str(MatAdd(MatAdd(X, Y), MatAdd(X, Y))) == '(X + Y) + (X + Y)'
+
+
+def test_MatrixSlice():
+    n = Symbol('n', integer=True)
+    X = MatrixSymbol('X', n, n)
+    Y = MatrixSymbol('Y', 10, 10)
+    Z = MatrixSymbol('Z', 10, 10)
+
+    assert str(MatrixSlice(X, (None, None, None), (None, None, None))) == 'X[:, :]'
+    assert str(X[x:x + 1, y:y + 1]) == 'X[x:x + 1, y:y + 1]'
+    assert str(X[x:x + 1:2, y:y + 1:2]) == 'X[x:x + 1:2, y:y + 1:2]'
+    assert str(X[:x, y:]) == 'X[:x, y:]'
+    assert str(X[:x, y:]) == 'X[:x, y:]'
+    assert str(X[x:, :y]) == 'X[x:, :y]'
+    assert str(X[x:y, z:w]) == 'X[x:y, z:w]'
+    assert str(X[x:y:t, w:t:x]) == 'X[x:y:t, w:t:x]'
+    assert str(X[x::y, t::w]) == 'X[x::y, t::w]'
+    assert str(X[:x:y, :t:w]) == 'X[:x:y, :t:w]'
+    assert str(X[::x, ::y]) == 'X[::x, ::y]'
+    assert str(MatrixSlice(X, (0, None, None), (0, None, None))) == 'X[:, :]'
+    assert str(MatrixSlice(X, (None, n, None), (None, n, None))) == 'X[:, :]'
+    assert str(MatrixSlice(X, (0, n, None), (0, n, None))) == 'X[:, :]'
+    assert str(MatrixSlice(X, (0, n, 2), (0, n, 2))) == 'X[::2, ::2]'
+    assert str(X[1:2:3, 4:5:6]) == 'X[1:2:3, 4:5:6]'
+    assert str(X[1:3:5, 4:6:8]) == 'X[1:3:5, 4:6:8]'
+    assert str(X[1:10:2]) == 'X[1:10:2, :]'
+    assert str(Y[:5, 1:9:2]) == 'Y[:5, 1:9:2]'
+    assert str(Y[:5, 1:10:2]) == 'Y[:5, 1::2]'
+    assert str(Y[5, :5:2]) == 'Y[5:6, :5:2]'
+    assert str(X[0:1, 0:1]) == 'X[:1, :1]'
+    assert str(X[0:1:2, 0:1:2]) == 'X[:1:2, :1:2]'
+    assert str((Y + Z)[2:, 2:]) == '(Y + Z)[2:, 2:]'
+
+def test_true_false():
+    assert str(true) == repr(true) == sstr(true) == "True"
+    assert str(false) == repr(false) == sstr(false) == "False"
+
+def test_Equivalent():
+    assert str(Equivalent(y, x)) == "Equivalent(x, y)"
+
+def test_Xor():
+    assert str(Xor(y, x, evaluate=False)) == "x ^ y"
+
+def test_Complement():
+    assert str(Complement(S.Reals, S.Naturals)) == 'Complement(Reals, Naturals)'
+
+def test_SymmetricDifference():
+    assert str(SymmetricDifference(Interval(2, 3), Interval(3, 4),evaluate=False)) == \
+           'SymmetricDifference(Interval(2, 3), Interval(3, 4))'
+
+
+def test_UnevaluatedExpr():
+    a, b = symbols("a b")
+    expr1 = 2*UnevaluatedExpr(a+b)
+    assert str(expr1) == "2*(a + b)"
+
+
+def test_MatrixElement_printing():
+    # test cases for issue #11821
+    A = MatrixSymbol("A", 1, 3)
+    B = MatrixSymbol("B", 1, 3)
+    C = MatrixSymbol("C", 1, 3)
+
+    assert(str(A[0, 0]) == "A[0, 0]")
+    assert(str(3 * A[0, 0]) == "3*A[0, 0]")
+
+    F = C[0, 0].subs(C, A - B)
+    assert str(F) == "(A - B)[0, 0]"
+
+
+def test_MatrixSymbol_printing():
+    A = MatrixSymbol("A", 3, 3)
+    B = MatrixSymbol("B", 3, 3)
+
+    assert str(A - A*B - B) == "A - A*B - B"
+    assert str(A*B - (A+B)) == "-A + A*B - B"
+    assert str(A**(-1)) == "A**(-1)"
+    assert str(A**3) == "A**3"
+
+
+def test_MatrixExpressions():
+    n = Symbol('n', integer=True)
+    X = MatrixSymbol('X', n, n)
+
+    assert str(X) == "X"
+
+    # Apply function elementwise (`ElementwiseApplyFunc`):
+
+    expr = (X.T*X).applyfunc(sin)
+    assert str(expr) == 'Lambda(_d, sin(_d)).(X.T*X)'
+
+    lamda = Lambda(x, 1/x)
+    expr = (n*X).applyfunc(lamda)
+    assert str(expr) == 'Lambda(x, 1/x).(n*X)'
+
+
+def test_Subs_printing():
+    assert str(Subs(x, (x,), (1,))) == 'Subs(x, x, 1)'
+    assert str(Subs(x + y, (x, y), (1, 2))) == 'Subs(x + y, (x, y), (1, 2))'
+
+
+def test_issue_15716():
+    e = Integral(factorial(x), (x, -oo, oo))
+    assert e.as_terms() == ([(e, ((1.0, 0.0), (1,), ()))], [e])
+
+
+def test_str_special_matrices():
+    from sympy.matrices import Identity, ZeroMatrix, OneMatrix
+    assert str(Identity(4)) == 'I'
+    assert str(ZeroMatrix(2, 2)) == '0'
+    assert str(OneMatrix(2, 2)) == '1'
+
+
+def test_issue_14567():
+    assert factorial(Sum(-1, (x, 0, 0))) + y  # doesn't raise an error
+
+
+def test_issue_21823():
+    assert str(Partition([1, 2])) == 'Partition({1, 2})'
+    assert str(Partition({1, 2})) == 'Partition({1, 2})'
+
+
+def test_issue_22689():
+    assert str(Mul(Pow(x,-2, evaluate=False), Pow(3,-1,evaluate=False), evaluate=False)) == "1/(x**2*3)"
+
+
+def test_issue_21119_21460():
+    ss = lambda x: str(S(x, evaluate=False))
+    assert ss('4/2') == '4/2'
+    assert ss('4/-2') == '4/(-2)'
+    assert ss('-4/2') == '-4/2'
+    assert ss('-4/-2') == '-4/(-2)'
+    assert ss('-2*3/-1') == '-2*3/(-1)'
+    assert ss('-2*3/-1/2') == '-2*3/(-1*2)'
+    assert ss('4/2/1') == '4/(2*1)'
+    assert ss('-2/-1/2') == '-2/(-1*2)'
+    assert ss('2*3*4**(-2*3)') == '2*3/4**(2*3)'
+    assert ss('2*3*1*4**(-2*3)') == '2*3*1/4**(2*3)'
+
+
+def test_Str():
+    from sympy.core.symbol import Str
+    assert str(Str('x')) == 'x'
+    assert sstrrepr(Str('x')) == "Str('x')"
+
+
+def test_diffgeom():
+    from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField
+    x,y = symbols('x y', real=True)
+    m = Manifold('M', 2)
+    assert str(m) == "M"
+    p = Patch('P', m)
+    assert str(p) == "P"
+    rect = CoordSystem('rect', p, [x, y])
+    assert str(rect) == "rect"
+    b = BaseScalarField(rect, 0)
+    assert str(b) == "x"
+
+def test_NDimArray():
+    assert sstr(NDimArray(1.0), full_prec=True) == '1.00000000000000'
+    assert sstr(NDimArray(1.0), full_prec=False) == '1.0'
+    assert sstr(NDimArray([1.0, 2.0]), full_prec=True) == '[1.00000000000000, 2.00000000000000]'
+    assert sstr(NDimArray([1.0, 2.0]), full_prec=False) == '[1.0, 2.0]'
+    assert sstr(NDimArray([], (0,))) == 'ImmutableDenseNDimArray([], (0,))'
+    assert sstr(NDimArray([], (0, 0))) == 'ImmutableDenseNDimArray([], (0, 0))'
+    assert sstr(NDimArray([], (0, 1))) == 'ImmutableDenseNDimArray([], (0, 1))'
+    assert sstr(NDimArray([], (1, 0))) == 'ImmutableDenseNDimArray([], (1, 0))'
+
+def test_Predicate():
+    assert sstr(Q.even) == 'Q.even'
+
+def test_AppliedPredicate():
+    assert sstr(Q.even(x)) == 'Q.even(x)'
+
+def test_printing_str_array_expressions():
+    assert sstr(ArraySymbol("A", (2, 3, 4))) == "A"
+    assert sstr(ArrayElement("A", (2, 1/(1-x), 0))) == "A[2, 1/(1 - x), 0]"
+    M = MatrixSymbol("M", 3, 3)
+    N = MatrixSymbol("N", 3, 3)
+    assert sstr(ArrayElement(M*N, [x, 0])) == "(M*N)[x, 0]"
+
+def test_printing_stats():
+    # issue 24132
+    x = RandomSymbol("x")
+    y = RandomSymbol("y")
+    z1 = Probability(x > 0)*Identity(2)
+    z2 = Expectation(x)*Identity(2)
+    z3 = Variance(x)*Identity(2)
+    z4 = Covariance(x, y) * Identity(2)
+
+    assert str(z1) == "Probability(x > 0)*I"
+    assert str(z2) == "Expectation(x)*I"
+    assert str(z3) == "Variance(x)*I"
+    assert str(z4) ==  "Covariance(x, y)*I"
+    assert z1.is_commutative == False
+    assert z2.is_commutative == False
+    assert z3.is_commutative == False
+    assert z4.is_commutative == False
+    assert z2._eval_is_commutative() == False
+    assert z3._eval_is_commutative() == False
+    assert z4._eval_is_commutative() == False
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_tableform.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_tableform.py
new file mode 100644
index 0000000000000000000000000000000000000000..05802dd104a12f2f53d137167ecf31d201ff8dfc
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_tableform.py
@@ -0,0 +1,182 @@
+from sympy.core.singleton import S
+from sympy.printing.tableform import TableForm
+from sympy.printing.latex import latex
+from sympy.abc import x
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import sin
+from sympy.testing.pytest import raises
+
+from textwrap import dedent
+
+
+def test_TableForm():
+    s = str(TableForm([["a", "b"], ["c", "d"], ["e", 0]],
+        headings="automatic"))
+    assert s == (
+        '  | 1 2\n'
+        '-------\n'
+        '1 | a b\n'
+        '2 | c d\n'
+        '3 | e  '
+    )
+    s = str(TableForm([["a", "b"], ["c", "d"], ["e", 0]],
+        headings="automatic", wipe_zeros=False))
+    assert s == dedent('''\
+          | 1 2
+        -------
+        1 | a b
+        2 | c d
+        3 | e 0''')
+    s = str(TableForm([[x**2, "b"], ["c", x**2], ["e", "f"]],
+            headings=("automatic", None)))
+    assert s == (
+        '1 | x**2 b   \n'
+        '2 | c    x**2\n'
+        '3 | e    f   '
+    )
+    s = str(TableForm([["a", "b"], ["c", "d"], ["e", "f"]],
+            headings=(None, "automatic")))
+    assert s == dedent('''\
+        1 2
+        ---
+        a b
+        c d
+        e f''')
+    s = str(TableForm([[5, 7], [4, 2], [10, 3]],
+            headings=[["Group A", "Group B", "Group C"], ["y1", "y2"]]))
+    assert s == (
+        '        | y1 y2\n'
+        '---------------\n'
+        'Group A | 5  7 \n'
+        'Group B | 4  2 \n'
+        'Group C | 10 3 '
+    )
+    raises(
+        ValueError,
+        lambda:
+        TableForm(
+            [[5, 7], [4, 2], [10, 3]],
+            headings=[["Group A", "Group B", "Group C"], ["y1", "y2"]],
+            alignments="middle")
+    )
+    s = str(TableForm([[5, 7], [4, 2], [10, 3]],
+            headings=[["Group A", "Group B", "Group C"], ["y1", "y2"]],
+            alignments="right"))
+    assert s == dedent('''\
+                | y1 y2
+        ---------------
+        Group A |  5  7
+        Group B |  4  2
+        Group C | 10  3''')
+
+    # other alignment permutations
+    d = [[1, 100], [100, 1]]
+    s = TableForm(d, headings=(('xxx', 'x'), None), alignments='l')
+    assert str(s) == (
+        'xxx | 1   100\n'
+        '  x | 100 1  '
+    )
+    s = TableForm(d, headings=(('xxx', 'x'), None), alignments='lr')
+    assert str(s) == dedent('''\
+    xxx | 1   100
+      x | 100   1''')
+    s = TableForm(d, headings=(('xxx', 'x'), None), alignments='clr')
+    assert str(s) == dedent('''\
+    xxx | 1   100
+     x  | 100   1''')
+
+    s = TableForm(d, headings=(('xxx', 'x'), None))
+    assert str(s) == (
+        'xxx | 1   100\n'
+        '  x | 100 1  '
+    )
+
+    raises(ValueError, lambda: TableForm(d, alignments='clr'))
+
+    #pad
+    s = str(TableForm([[None, "-", 2], [1]], pad='?'))
+    assert s == dedent('''\
+        ? - 2
+        1 ? ?''')
+
+
+def test_TableForm_latex():
+    s = latex(TableForm([[0, x**3], ["c", S.One/4], [sqrt(x), sin(x**2)]],
+            wipe_zeros=True, headings=("automatic", "automatic")))
+    assert s == (
+        '\\begin{tabular}{r l l}\n'
+        ' & 1 & 2 \\\\\n'
+        '\\hline\n'
+        '1 &   & $x^{3}$ \\\\\n'
+        '2 & $c$ & $\\frac{1}{4}$ \\\\\n'
+        '3 & $\\sqrt{x}$ & $\\sin{\\left(x^{2} \\right)}$ \\\\\n'
+        '\\end{tabular}'
+    )
+    s = latex(TableForm([[0, x**3], ["c", S.One/4], [sqrt(x), sin(x**2)]],
+            wipe_zeros=True, headings=("automatic", "automatic"), alignments='l'))
+    assert s == (
+        '\\begin{tabular}{r l l}\n'
+        ' & 1 & 2 \\\\\n'
+        '\\hline\n'
+        '1 &   & $x^{3}$ \\\\\n'
+        '2 & $c$ & $\\frac{1}{4}$ \\\\\n'
+        '3 & $\\sqrt{x}$ & $\\sin{\\left(x^{2} \\right)}$ \\\\\n'
+        '\\end{tabular}'
+    )
+    s = latex(TableForm([[0, x**3], ["c", S.One/4], [sqrt(x), sin(x**2)]],
+            wipe_zeros=True, headings=("automatic", "automatic"), alignments='l'*3))
+    assert s == (
+        '\\begin{tabular}{l l l}\n'
+        ' & 1 & 2 \\\\\n'
+        '\\hline\n'
+        '1 &   & $x^{3}$ \\\\\n'
+        '2 & $c$ & $\\frac{1}{4}$ \\\\\n'
+        '3 & $\\sqrt{x}$ & $\\sin{\\left(x^{2} \\right)}$ \\\\\n'
+        '\\end{tabular}'
+    )
+    s = latex(TableForm([["a", x**3], ["c", S.One/4], [sqrt(x), sin(x**2)]],
+            headings=("automatic", "automatic")))
+    assert s == (
+        '\\begin{tabular}{r l l}\n'
+        ' & 1 & 2 \\\\\n'
+        '\\hline\n'
+        '1 & $a$ & $x^{3}$ \\\\\n'
+        '2 & $c$ & $\\frac{1}{4}$ \\\\\n'
+        '3 & $\\sqrt{x}$ & $\\sin{\\left(x^{2} \\right)}$ \\\\\n'
+        '\\end{tabular}'
+    )
+    s = latex(TableForm([["a", x**3], ["c", S.One/4], [sqrt(x), sin(x**2)]],
+            formats=['(%s)', None], headings=("automatic", "automatic")))
+    assert s == (
+        '\\begin{tabular}{r l l}\n'
+        ' & 1 & 2 \\\\\n'
+        '\\hline\n'
+        '1 & (a) & $x^{3}$ \\\\\n'
+        '2 & (c) & $\\frac{1}{4}$ \\\\\n'
+        '3 & (sqrt(x)) & $\\sin{\\left(x^{2} \\right)}$ \\\\\n'
+        '\\end{tabular}'
+    )
+
+    def neg_in_paren(x, i, j):
+        if i % 2:
+            return ('(%s)' if x < 0 else '%s') % x
+        else:
+            pass  # use default print
+    s = latex(TableForm([[-1, 2], [-3, 4]],
+            formats=[neg_in_paren]*2, headings=("automatic", "automatic")))
+    assert s == (
+        '\\begin{tabular}{r l l}\n'
+        ' & 1 & 2 \\\\\n'
+        '\\hline\n'
+        '1 & -1 & 2 \\\\\n'
+        '2 & (-3) & 4 \\\\\n'
+        '\\end{tabular}'
+    )
+    s = latex(TableForm([["a", x**3], ["c", S.One/4], [sqrt(x), sin(x**2)]]))
+    assert s == (
+        '\\begin{tabular}{l l}\n'
+        '$a$ & $x^{3}$ \\\\\n'
+        '$c$ & $\\frac{1}{4}$ \\\\\n'
+        '$\\sqrt{x}$ & $\\sin{\\left(x^{2} \\right)}$ \\\\\n'
+        '\\end{tabular}'
+    )
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_tensorflow.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_tensorflow.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9c92cd17b13e1148ebf83f13f66854b983491fe
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_tensorflow.py
@@ -0,0 +1,493 @@
+import random
+from sympy.core.function import Derivative
+from sympy.core.symbol import symbols
+from sympy import Piecewise
+from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayAdd, \
+    PermuteDims, ArrayDiagonal
+from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt
+from sympy.external import import_module
+from sympy.functions import \
+    Abs, ceiling, exp, floor, sign, sin, asin, sqrt, cos, \
+    acos, tan, atan, atan2, cosh, acosh, sinh, asinh, tanh, atanh, \
+    re, im, arg, erf, loggamma, log
+from sympy.codegen.cfunctions import isnan, isinf
+from sympy.matrices import Matrix, MatrixBase, eye, randMatrix
+from sympy.matrices.expressions import \
+    Determinant, HadamardProduct, Inverse, MatrixSymbol, Trace
+from sympy.printing.tensorflow import tensorflow_code
+from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
+from sympy.utilities.lambdify import lambdify
+from sympy.testing.pytest import skip
+from sympy.testing.pytest import XFAIL
+
+
+tf = tensorflow = import_module("tensorflow")
+
+if tensorflow:
+    # Hide Tensorflow warnings
+    import os
+    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
+
+
+M = MatrixSymbol("M", 3, 3)
+N = MatrixSymbol("N", 3, 3)
+P = MatrixSymbol("P", 3, 3)
+Q = MatrixSymbol("Q", 3, 3)
+
+x, y, z, t = symbols("x y z t")
+
+if tf is not None:
+    llo = [list(range(i, i+3)) for i in range(0, 9, 3)]
+    m3x3 = tf.constant(llo)
+    m3x3sympy = Matrix(llo)
+
+
+def _compare_tensorflow_matrix(variables, expr, use_float=False):
+    f = lambdify(variables, expr, 'tensorflow')
+    if not use_float:
+        random_matrices = [randMatrix(v.rows, v.cols) for v in variables]
+    else:
+        random_matrices = [randMatrix(v.rows, v.cols)/100. for v in variables]
+
+    graph = tf.Graph()
+    r = None
+    with graph.as_default():
+        random_variables = [eval(tensorflow_code(i)) for i in random_matrices]
+        session = tf.compat.v1.Session(graph=graph)
+        r = session.run(f(*random_variables))
+
+    e = expr.subs(dict(zip(variables, random_matrices)))
+    e = e.doit()
+    if e.is_Matrix:
+        if not isinstance(e, MatrixBase):
+            e = e.as_explicit()
+        e = e.tolist()
+
+    if not use_float:
+        assert (r == e).all()
+    else:
+        r = [i for row in r for i in row]
+        e = [i for row in e for i in row]
+        assert all(
+            abs(a-b) < 10**-(4-int(log(abs(a), 10))) for a, b in zip(r, e))
+
+
+# Creating a custom inverse test.
+# See https://github.com/sympy/sympy/issues/18469
+def _compare_tensorflow_matrix_inverse(variables, expr, use_float=False):
+    f = lambdify(variables, expr, 'tensorflow')
+    if not use_float:
+        random_matrices = [eye(v.rows, v.cols)*4 for v in variables]
+    else:
+        random_matrices = [eye(v.rows, v.cols)*3.14 for v in variables]
+
+    graph = tf.Graph()
+    r = None
+    with graph.as_default():
+        random_variables = [eval(tensorflow_code(i)) for i in random_matrices]
+        session = tf.compat.v1.Session(graph=graph)
+        r = session.run(f(*random_variables))
+
+    e = expr.subs(dict(zip(variables, random_matrices)))
+    e = e.doit()
+    if e.is_Matrix:
+        if not isinstance(e, MatrixBase):
+            e = e.as_explicit()
+        e = e.tolist()
+
+    if not use_float:
+        assert (r == e).all()
+    else:
+        r = [i for row in r for i in row]
+        e = [i for row in e for i in row]
+        assert all(
+            abs(a-b) < 10**-(4-int(log(abs(a), 10))) for a, b in zip(r, e))
+
+
+def _compare_tensorflow_matrix_scalar(variables, expr):
+    f = lambdify(variables, expr, 'tensorflow')
+    random_matrices = [
+        randMatrix(v.rows, v.cols).evalf() / 100 for v in variables]
+
+    graph = tf.Graph()
+    r = None
+    with graph.as_default():
+        random_variables = [eval(tensorflow_code(i)) for i in random_matrices]
+        session = tf.compat.v1.Session(graph=graph)
+        r = session.run(f(*random_variables))
+
+    e = expr.subs(dict(zip(variables, random_matrices)))
+    e = e.doit()
+    assert abs(r-e) < 10**-6
+
+
+def _compare_tensorflow_scalar(
+    variables, expr, rng=lambda: random.randint(0, 10)):
+    f = lambdify(variables, expr, 'tensorflow')
+    rvs = [rng() for v in variables]
+
+    graph = tf.Graph()
+    r = None
+    with graph.as_default():
+        tf_rvs = [eval(tensorflow_code(i)) for i in rvs]
+        session = tf.compat.v1.Session(graph=graph)
+        r = session.run(f(*tf_rvs))
+
+    e = expr.subs(dict(zip(variables, rvs))).evalf().doit()
+    assert abs(r-e) < 10**-6
+
+
+def _compare_tensorflow_relational(
+    variables, expr, rng=lambda: random.randint(0, 10)):
+    f = lambdify(variables, expr, 'tensorflow')
+    rvs = [rng() for v in variables]
+
+    graph = tf.Graph()
+    r = None
+    with graph.as_default():
+        tf_rvs = [eval(tensorflow_code(i)) for i in rvs]
+        session = tf.compat.v1.Session(graph=graph)
+        r = session.run(f(*tf_rvs))
+
+    e = expr.subs(dict(zip(variables, rvs))).doit()
+    assert r == e
+
+
+def test_tensorflow_printing():
+    assert tensorflow_code(eye(3)) == \
+        "tensorflow.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]])"
+
+    expr = Matrix([[x, sin(y)], [exp(z), -t]])
+    assert tensorflow_code(expr) == \
+        "tensorflow.Variable(" \
+            "[[x, tensorflow.math.sin(y)]," \
+            " [tensorflow.math.exp(z), -t]])"
+
+
+# This (random) test is XFAIL because it fails occasionally
+# See https://github.com/sympy/sympy/issues/18469
+@XFAIL
+def test_tensorflow_math():
+    if not tf:
+        skip("TensorFlow not installed")
+
+    expr = Abs(x)
+    assert tensorflow_code(expr) == "tensorflow.math.abs(x)"
+    _compare_tensorflow_scalar((x,), expr)
+
+    expr = sign(x)
+    assert tensorflow_code(expr) == "tensorflow.math.sign(x)"
+    _compare_tensorflow_scalar((x,), expr)
+
+    expr = ceiling(x)
+    assert tensorflow_code(expr) == "tensorflow.math.ceil(x)"
+    _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
+
+    expr = floor(x)
+    assert tensorflow_code(expr) == "tensorflow.math.floor(x)"
+    _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
+
+    expr = exp(x)
+    assert tensorflow_code(expr) == "tensorflow.math.exp(x)"
+    _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
+
+    expr = sqrt(x)
+    assert tensorflow_code(expr) == "tensorflow.math.sqrt(x)"
+    _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
+
+    expr = x ** 4
+    assert tensorflow_code(expr) == "tensorflow.math.pow(x, 4)"
+    _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
+
+    expr = cos(x)
+    assert tensorflow_code(expr) == "tensorflow.math.cos(x)"
+    _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
+
+    expr = acos(x)
+    assert tensorflow_code(expr) == "tensorflow.math.acos(x)"
+    _compare_tensorflow_scalar((x,), expr, rng=lambda: random.uniform(0, 0.95))
+
+    expr = sin(x)
+    assert tensorflow_code(expr) == "tensorflow.math.sin(x)"
+    _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
+
+    expr = asin(x)
+    assert tensorflow_code(expr) == "tensorflow.math.asin(x)"
+    _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
+
+    expr = tan(x)
+    assert tensorflow_code(expr) == "tensorflow.math.tan(x)"
+    _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
+
+    expr = atan(x)
+    assert tensorflow_code(expr) == "tensorflow.math.atan(x)"
+    _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
+
+    expr = atan2(y, x)
+    assert tensorflow_code(expr) == "tensorflow.math.atan2(y, x)"
+    _compare_tensorflow_scalar((y, x), expr, rng=lambda: random.random())
+
+    expr = cosh(x)
+    assert tensorflow_code(expr) == "tensorflow.math.cosh(x)"
+    _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random())
+
+    expr = acosh(x)
+    assert tensorflow_code(expr) == "tensorflow.math.acosh(x)"
+    _compare_tensorflow_scalar((x,), expr, rng=lambda: random.uniform(1, 2))
+
+    expr = sinh(x)
+    assert tensorflow_code(expr) == "tensorflow.math.sinh(x)"
+    _compare_tensorflow_scalar((x,), expr, rng=lambda: random.uniform(1, 2))
+
+    expr = asinh(x)
+    assert tensorflow_code(expr) == "tensorflow.math.asinh(x)"
+    _compare_tensorflow_scalar((x,), expr, rng=lambda: random.uniform(1, 2))
+
+    expr = tanh(x)
+    assert tensorflow_code(expr) == "tensorflow.math.tanh(x)"
+    _compare_tensorflow_scalar((x,), expr, rng=lambda: random.uniform(1, 2))
+
+    expr = atanh(x)
+    assert tensorflow_code(expr) == "tensorflow.math.atanh(x)"
+    _compare_tensorflow_scalar(
+        (x,), expr, rng=lambda: random.uniform(-.5, .5))
+
+    expr = erf(x)
+    assert tensorflow_code(expr) == "tensorflow.math.erf(x)"
+    _compare_tensorflow_scalar(
+        (x,), expr, rng=lambda: random.random())
+
+    expr = loggamma(x)
+    assert tensorflow_code(expr) == "tensorflow.math.lgamma(x)"
+    _compare_tensorflow_scalar(
+        (x,), expr, rng=lambda: random.random())
+
+
+def test_tensorflow_complexes():
+    assert tensorflow_code(re(x)) == "tensorflow.math.real(x)"
+    assert tensorflow_code(im(x)) == "tensorflow.math.imag(x)"
+    assert tensorflow_code(arg(x)) == "tensorflow.math.angle(x)"
+
+
+def test_tensorflow_relational():
+    if not tf:
+        skip("TensorFlow not installed")
+
+    expr = Eq(x, y)
+    assert tensorflow_code(expr) == "tensorflow.math.equal(x, y)"
+    _compare_tensorflow_relational((x, y), expr)
+
+    expr = Ne(x, y)
+    assert tensorflow_code(expr) == "tensorflow.math.not_equal(x, y)"
+    _compare_tensorflow_relational((x, y), expr)
+
+    expr = Ge(x, y)
+    assert tensorflow_code(expr) == "tensorflow.math.greater_equal(x, y)"
+    _compare_tensorflow_relational((x, y), expr)
+
+    expr = Gt(x, y)
+    assert tensorflow_code(expr) == "tensorflow.math.greater(x, y)"
+    _compare_tensorflow_relational((x, y), expr)
+
+    expr = Le(x, y)
+    assert tensorflow_code(expr) == "tensorflow.math.less_equal(x, y)"
+    _compare_tensorflow_relational((x, y), expr)
+
+    expr = Lt(x, y)
+    assert tensorflow_code(expr) == "tensorflow.math.less(x, y)"
+    _compare_tensorflow_relational((x, y), expr)
+
+
+# This (random) test is XFAIL because it fails occasionally
+# See https://github.com/sympy/sympy/issues/18469
+@XFAIL
+def test_tensorflow_matrices():
+    if not tf:
+        skip("TensorFlow not installed")
+
+    expr = M
+    assert tensorflow_code(expr) == "M"
+    _compare_tensorflow_matrix((M,), expr)
+
+    expr = M + N
+    assert tensorflow_code(expr) == "tensorflow.math.add(M, N)"
+    _compare_tensorflow_matrix((M, N), expr)
+
+    expr = M * N
+    assert tensorflow_code(expr) == "tensorflow.linalg.matmul(M, N)"
+    _compare_tensorflow_matrix((M, N), expr)
+
+    expr = HadamardProduct(M, N)
+    assert tensorflow_code(expr) == "tensorflow.math.multiply(M, N)"
+    _compare_tensorflow_matrix((M, N), expr)
+
+    expr = M*N*P*Q
+    assert tensorflow_code(expr) == \
+        "tensorflow.linalg.matmul(" \
+            "tensorflow.linalg.matmul(" \
+                "tensorflow.linalg.matmul(M, N), P), Q)"
+    _compare_tensorflow_matrix((M, N, P, Q), expr)
+
+    expr = M**3
+    assert tensorflow_code(expr) == \
+        "tensorflow.linalg.matmul(tensorflow.linalg.matmul(M, M), M)"
+    _compare_tensorflow_matrix((M,), expr)
+
+    expr = Trace(M)
+    assert tensorflow_code(expr) == "tensorflow.linalg.trace(M)"
+    _compare_tensorflow_matrix((M,), expr)
+
+    expr = Determinant(M)
+    assert tensorflow_code(expr) == "tensorflow.linalg.det(M)"
+    _compare_tensorflow_matrix_scalar((M,), expr)
+
+    expr = Inverse(M)
+    assert tensorflow_code(expr) == "tensorflow.linalg.inv(M)"
+    _compare_tensorflow_matrix_inverse((M,), expr, use_float=True)
+
+    expr = M.T
+    assert tensorflow_code(expr, tensorflow_version='1.14') == \
+        "tensorflow.linalg.matrix_transpose(M)"
+    assert tensorflow_code(expr, tensorflow_version='1.13') == \
+        "tensorflow.matrix_transpose(M)"
+
+    _compare_tensorflow_matrix((M,), expr)
+
+
+def test_codegen_einsum():
+    if not tf:
+        skip("TensorFlow not installed")
+
+    graph = tf.Graph()
+    with graph.as_default():
+        session = tf.compat.v1.Session(graph=graph)
+
+        M = MatrixSymbol("M", 2, 2)
+        N = MatrixSymbol("N", 2, 2)
+
+        cg = convert_matrix_to_array(M * N)
+        f = lambdify((M, N), cg, 'tensorflow')
+
+        ma = tf.constant([[1, 2], [3, 4]])
+        mb = tf.constant([[1,-2], [-1, 3]])
+        y = session.run(f(ma, mb))
+        c = session.run(tf.matmul(ma, mb))
+        assert (y == c).all()
+
+
+def test_codegen_extra():
+    if not tf:
+        skip("TensorFlow not installed")
+
+    graph = tf.Graph()
+    with graph.as_default():
+        session = tf.compat.v1.Session()
+
+        M = MatrixSymbol("M", 2, 2)
+        N = MatrixSymbol("N", 2, 2)
+        P = MatrixSymbol("P", 2, 2)
+        Q = MatrixSymbol("Q", 2, 2)
+        ma = tf.constant([[1, 2], [3, 4]])
+        mb = tf.constant([[1,-2], [-1, 3]])
+        mc = tf.constant([[2, 0], [1, 2]])
+        md = tf.constant([[1,-1], [4, 7]])
+
+        cg = ArrayTensorProduct(M, N)
+        assert tensorflow_code(cg) == \
+            'tensorflow.linalg.einsum("ab,cd", M, N)'
+        f = lambdify((M, N), cg, 'tensorflow')
+        y = session.run(f(ma, mb))
+        c = session.run(tf.einsum("ij,kl", ma, mb))
+        assert (y == c).all()
+
+        cg = ArrayAdd(M, N)
+        assert tensorflow_code(cg) == 'tensorflow.math.add(M, N)'
+        f = lambdify((M, N), cg, 'tensorflow')
+        y = session.run(f(ma, mb))
+        c = session.run(ma + mb)
+        assert (y == c).all()
+
+        cg = ArrayAdd(M, N, P)
+        assert tensorflow_code(cg) == \
+            'tensorflow.math.add(tensorflow.math.add(M, N), P)'
+        f = lambdify((M, N, P), cg, 'tensorflow')
+        y = session.run(f(ma, mb, mc))
+        c = session.run(ma + mb + mc)
+        assert (y == c).all()
+
+        cg = ArrayAdd(M, N, P, Q)
+        assert tensorflow_code(cg) == \
+            'tensorflow.math.add(' \
+                'tensorflow.math.add(tensorflow.math.add(M, N), P), Q)'
+        f = lambdify((M, N, P, Q), cg, 'tensorflow')
+        y = session.run(f(ma, mb, mc, md))
+        c = session.run(ma + mb + mc + md)
+        assert (y == c).all()
+
+        cg = PermuteDims(M, [1, 0])
+        assert tensorflow_code(cg) == 'tensorflow.transpose(M, [1, 0])'
+        f = lambdify((M,), cg, 'tensorflow')
+        y = session.run(f(ma))
+        c = session.run(tf.transpose(ma))
+        assert (y == c).all()
+
+        cg = PermuteDims(ArrayTensorProduct(M, N), [1, 2, 3, 0])
+        assert tensorflow_code(cg) == \
+            'tensorflow.transpose(' \
+                'tensorflow.linalg.einsum("ab,cd", M, N), [1, 2, 3, 0])'
+        f = lambdify((M, N), cg, 'tensorflow')
+        y = session.run(f(ma, mb))
+        c = session.run(tf.transpose(tf.einsum("ab,cd", ma, mb), [1, 2, 3, 0]))
+        assert (y == c).all()
+
+        cg = ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2))
+        assert tensorflow_code(cg) == \
+            'tensorflow.linalg.einsum("ab,bc->acb", M, N)'
+        f = lambdify((M, N), cg, 'tensorflow')
+        y = session.run(f(ma, mb))
+        c = session.run(tf.einsum("ab,bc->acb", ma, mb))
+        assert (y == c).all()
+
+
+def test_MatrixElement_printing():
+    A = MatrixSymbol("A", 1, 3)
+    B = MatrixSymbol("B", 1, 3)
+    C = MatrixSymbol("C", 1, 3)
+
+    assert tensorflow_code(A[0, 0]) == "A[0, 0]"
+    assert tensorflow_code(3 * A[0, 0]) == "3*A[0, 0]"
+
+    F = C[0, 0].subs(C, A - B)
+    assert tensorflow_code(F) == "(tensorflow.math.add((-1)*B, A))[0, 0]"
+
+
+def test_tensorflow_Derivative():
+    expr = Derivative(sin(x), x)
+    assert tensorflow_code(expr) == \
+        "tensorflow.gradients(tensorflow.math.sin(x), x)[0]"
+
+def test_tensorflow_isnan_isinf():
+    if not tf:
+        skip("TensorFlow not installed")
+
+    # Test for isnan
+    x = symbols("x")
+    # Return 0 if x is of nan value, and 1 otherwise
+    expression = Piecewise((0.0, isnan(x)), (1.0, True))
+    printed_code = tensorflow_code(expression)
+    expected_printed_code = "tensorflow.where(tensorflow.math.is_nan(x), 0.0, 1.0)"
+    assert tensorflow_code(expression) == expected_printed_code, f"Incorrect printed result {printed_code}, expected {expected_printed_code}"
+    for _input, _expected in [(float('nan'), 0.0), (float('inf'), 1.0), (float('-inf'), 1.0), (1.0, 1.0)]:
+        _output = lambdify((x), expression, modules="tensorflow")(x=tf.constant([_input]))
+        assert (_output == _expected).numpy().all()
+
+    # Test for isinf
+    x = symbols("x")
+    # Return 0 if x is of nan value, and 1 otherwise
+    expression = Piecewise((0.0, isinf(x)), (1.0, True))
+    printed_code = tensorflow_code(expression)
+    expected_printed_code = "tensorflow.where(tensorflow.math.is_inf(x), 0.0, 1.0)"
+    assert tensorflow_code(expression) == expected_printed_code, f"Incorrect printed result {printed_code}, expected {expected_printed_code}"
+    for _input, _expected in [(float('inf'), 0.0), (float('-inf'), 0.0), (float('nan'), 1.0), (1.0, 1.0)]:
+        _output = lambdify((x), expression, modules="tensorflow")(x=tf.constant([_input]))
+        assert (_output == _expected).numpy().all()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_theanocode.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_theanocode.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ff40f78cb4de16149cb5e780756b7e32b574b71
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_theanocode.py
@@ -0,0 +1,639 @@
+"""
+Important note on tests in this module - the Theano printing functions use a
+global cache by default, which means that tests using it will modify global
+state and thus not be independent from each other. Instead of using the "cache"
+keyword argument each time, this module uses the theano_code_ and
+theano_function_ functions defined below which default to using a new, empty
+cache instead.
+"""
+
+import logging
+
+from sympy.external import import_module
+from sympy.testing.pytest import raises, SKIP, warns_deprecated_sympy
+
+theanologger = logging.getLogger('theano.configdefaults')
+theanologger.setLevel(logging.CRITICAL)
+theano = import_module('theano')
+theanologger.setLevel(logging.WARNING)
+
+
+if theano:
+    import numpy as np
+    ts = theano.scalar
+    tt = theano.tensor
+    xt, yt, zt = [tt.scalar(name, 'floatX') for name in 'xyz']
+    Xt, Yt, Zt = [tt.tensor('floatX', (False, False), name=n) for n in 'XYZ']
+else:
+    #bin/test will not execute any tests now
+    disabled = True
+
+import sympy as sy
+from sympy.core.singleton import S
+from sympy.abc import x, y, z, t
+from sympy.printing.theanocode import (theano_code, dim_handling,
+        theano_function)
+
+
+# Default set of matrix symbols for testing - make square so we can both
+# multiply and perform elementwise operations between them.
+X, Y, Z = [sy.MatrixSymbol(n, 4, 4) for n in 'XYZ']
+
+# For testing AppliedUndef
+f_t = sy.Function('f')(t)
+
+
+def theano_code_(expr, **kwargs):
+    """ Wrapper for theano_code that uses a new, empty cache by default. """
+    kwargs.setdefault('cache', {})
+    with warns_deprecated_sympy():
+        return theano_code(expr, **kwargs)
+
+def theano_function_(inputs, outputs, **kwargs):
+    """ Wrapper for theano_function that uses a new, empty cache by default. """
+    kwargs.setdefault('cache', {})
+    with warns_deprecated_sympy():
+        return theano_function(inputs, outputs, **kwargs)
+
+
+def fgraph_of(*exprs):
+    """ Transform SymPy expressions into Theano Computation.
+
+    Parameters
+    ==========
+    exprs
+        SymPy expressions
+
+    Returns
+    =======
+    theano.gof.FunctionGraph
+    """
+    outs = list(map(theano_code_, exprs))
+    ins = theano.gof.graph.inputs(outs)
+    ins, outs = theano.gof.graph.clone(ins, outs)
+    return theano.gof.FunctionGraph(ins, outs)
+
+
+def theano_simplify(fgraph):
+    """ Simplify a Theano Computation.
+
+    Parameters
+    ==========
+    fgraph : theano.gof.FunctionGraph
+
+    Returns
+    =======
+    theano.gof.FunctionGraph
+    """
+    mode = theano.compile.get_default_mode().excluding("fusion")
+    fgraph = fgraph.clone()
+    mode.optimizer.optimize(fgraph)
+    return fgraph
+
+
+def theq(a, b):
+    """ Test two Theano objects for equality.
+
+    Also accepts numeric types and lists/tuples of supported types.
+
+    Note - debugprint() has a bug where it will accept numeric types but does
+    not respect the "file" argument and in this case and instead prints the number
+    to stdout and returns an empty string. This can lead to tests passing where
+    they should fail because any two numbers will always compare as equal. To
+    prevent this we treat numbers as a separate case.
+    """
+    numeric_types = (int, float, np.number)
+    a_is_num = isinstance(a, numeric_types)
+    b_is_num = isinstance(b, numeric_types)
+
+    # Compare numeric types using regular equality
+    if a_is_num or b_is_num:
+        if not (a_is_num and b_is_num):
+            return False
+
+        return a == b
+
+    # Compare sequences element-wise
+    a_is_seq = isinstance(a, (tuple, list))
+    b_is_seq = isinstance(b, (tuple, list))
+
+    if a_is_seq or b_is_seq:
+        if not (a_is_seq and b_is_seq) or type(a) != type(b):
+            return False
+
+        return list(map(theq, a)) == list(map(theq, b))
+
+    # Otherwise, assume debugprint() can handle it
+    astr = theano.printing.debugprint(a, file='str')
+    bstr = theano.printing.debugprint(b, file='str')
+
+    # Check for bug mentioned above
+    for argname, argval, argstr in [('a', a, astr), ('b', b, bstr)]:
+        if argstr == '':
+            raise TypeError(
+                'theano.printing.debugprint(%s) returned empty string '
+                '(%s is instance of %r)'
+                % (argname, argname, type(argval))
+            )
+
+    return astr == bstr
+
+
+def test_example_symbols():
+    """
+    Check that the example symbols in this module print to their Theano
+    equivalents, as many of the other tests depend on this.
+    """
+    assert theq(xt, theano_code_(x))
+    assert theq(yt, theano_code_(y))
+    assert theq(zt, theano_code_(z))
+    assert theq(Xt, theano_code_(X))
+    assert theq(Yt, theano_code_(Y))
+    assert theq(Zt, theano_code_(Z))
+
+
+def test_Symbol():
+    """ Test printing a Symbol to a theano variable. """
+    xx = theano_code_(x)
+    assert isinstance(xx, (tt.TensorVariable, ts.ScalarVariable))
+    assert xx.broadcastable == ()
+    assert xx.name == x.name
+
+    xx2 = theano_code_(x, broadcastables={x: (False,)})
+    assert xx2.broadcastable == (False,)
+    assert xx2.name == x.name
+
+def test_MatrixSymbol():
+    """ Test printing a MatrixSymbol to a theano variable. """
+    XX = theano_code_(X)
+    assert isinstance(XX, tt.TensorVariable)
+    assert XX.broadcastable == (False, False)
+
+@SKIP  # TODO - this is currently not checked but should be implemented
+def test_MatrixSymbol_wrong_dims():
+    """ Test MatrixSymbol with invalid broadcastable. """
+    bcs = [(), (False,), (True,), (True, False), (False, True,), (True, True)]
+    for bc in bcs:
+        with raises(ValueError):
+            theano_code_(X, broadcastables={X: bc})
+
+def test_AppliedUndef():
+    """ Test printing AppliedUndef instance, which works similarly to Symbol. """
+    ftt = theano_code_(f_t)
+    assert isinstance(ftt, tt.TensorVariable)
+    assert ftt.broadcastable == ()
+    assert ftt.name == 'f_t'
+
+
+def test_add():
+    expr = x + y
+    comp = theano_code_(expr)
+    assert comp.owner.op == theano.tensor.add
+
+def test_trig():
+    assert theq(theano_code_(sy.sin(x)), tt.sin(xt))
+    assert theq(theano_code_(sy.tan(x)), tt.tan(xt))
+
+def test_many():
+    """ Test printing a complex expression with multiple symbols. """
+    expr = sy.exp(x**2 + sy.cos(y)) * sy.log(2*z)
+    comp = theano_code_(expr)
+    expected = tt.exp(xt**2 + tt.cos(yt)) * tt.log(2*zt)
+    assert theq(comp, expected)
+
+
+def test_dtype():
+    """ Test specifying specific data types through the dtype argument. """
+    for dtype in ['float32', 'float64', 'int8', 'int16', 'int32', 'int64']:
+        assert theano_code_(x, dtypes={x: dtype}).type.dtype == dtype
+
+    # "floatX" type
+    assert theano_code_(x, dtypes={x: 'floatX'}).type.dtype in ('float32', 'float64')
+
+    # Type promotion
+    assert theano_code_(x + 1, dtypes={x: 'float32'}).type.dtype == 'float32'
+    assert theano_code_(x + y, dtypes={x: 'float64', y: 'float32'}).type.dtype == 'float64'
+
+
+def test_broadcastables():
+    """ Test the "broadcastables" argument when printing symbol-like objects. """
+
+    # No restrictions on shape
+    for s in [x, f_t]:
+        for bc in [(), (False,), (True,), (False, False), (True, False)]:
+            assert theano_code_(s, broadcastables={s: bc}).broadcastable == bc
+
+    # TODO - matrix broadcasting?
+
+def test_broadcasting():
+    """ Test "broadcastable" attribute after applying element-wise binary op. """
+
+    expr = x + y
+
+    cases = [
+        [(), (), ()],
+        [(False,), (False,), (False,)],
+        [(True,), (False,), (False,)],
+        [(False, True), (False, False), (False, False)],
+        [(True, False), (False, False), (False, False)],
+    ]
+
+    for bc1, bc2, bc3 in cases:
+        comp = theano_code_(expr, broadcastables={x: bc1, y: bc2})
+        assert comp.broadcastable == bc3
+
+
+def test_MatMul():
+    expr = X*Y*Z
+    expr_t = theano_code_(expr)
+    assert isinstance(expr_t.owner.op, tt.Dot)
+    assert theq(expr_t, Xt.dot(Yt).dot(Zt))
+
+def test_Transpose():
+    assert isinstance(theano_code_(X.T).owner.op, tt.DimShuffle)
+
+def test_MatAdd():
+    expr = X+Y+Z
+    assert isinstance(theano_code_(expr).owner.op, tt.Elemwise)
+
+
+def test_Rationals():
+    assert theq(theano_code_(sy.Integer(2) / 3), tt.true_div(2, 3))
+    assert theq(theano_code_(S.Half), tt.true_div(1, 2))
+
+def test_Integers():
+    assert theano_code_(sy.Integer(3)) == 3
+
+def test_factorial():
+    n = sy.Symbol('n')
+    assert theano_code_(sy.factorial(n))
+
+def test_Derivative():
+    simp = lambda expr: theano_simplify(fgraph_of(expr))
+    assert theq(simp(theano_code_(sy.Derivative(sy.sin(x), x, evaluate=False))),
+                simp(theano.grad(tt.sin(xt), xt)))
+
+
+def test_theano_function_simple():
+    """ Test theano_function() with single output. """
+    f = theano_function_([x, y], [x+y])
+    assert f(2, 3) == 5
+
+def test_theano_function_multi():
+    """ Test theano_function() with multiple outputs. """
+    f = theano_function_([x, y], [x+y, x-y])
+    o1, o2 = f(2, 3)
+    assert o1 == 5
+    assert o2 == -1
+
+def test_theano_function_numpy():
+    """ Test theano_function() vs Numpy implementation. """
+    f = theano_function_([x, y], [x+y], dim=1,
+                         dtypes={x: 'float64', y: 'float64'})
+    assert np.linalg.norm(f([1, 2], [3, 4]) - np.asarray([4, 6])) < 1e-9
+
+    f = theano_function_([x, y], [x+y], dtypes={x: 'float64', y: 'float64'},
+                         dim=1)
+    xx = np.arange(3).astype('float64')
+    yy = 2*np.arange(3).astype('float64')
+    assert np.linalg.norm(f(xx, yy) - 3*np.arange(3)) < 1e-9
+
+
+def test_theano_function_matrix():
+    m = sy.Matrix([[x, y], [z, x + y + z]])
+    expected = np.array([[1.0, 2.0], [3.0, 1.0 + 2.0 + 3.0]])
+    f = theano_function_([x, y, z], [m])
+    np.testing.assert_allclose(f(1.0, 2.0, 3.0), expected)
+    f = theano_function_([x, y, z], [m], scalar=True)
+    np.testing.assert_allclose(f(1.0, 2.0, 3.0), expected)
+    f = theano_function_([x, y, z], [m, m])
+    assert isinstance(f(1.0, 2.0, 3.0), type([]))
+    np.testing.assert_allclose(f(1.0, 2.0, 3.0)[0], expected)
+    np.testing.assert_allclose(f(1.0, 2.0, 3.0)[1], expected)
+
+def test_dim_handling():
+    assert dim_handling([x], dim=2) == {x: (False, False)}
+    assert dim_handling([x, y], dims={x: 1, y: 2}) == {x: (False, True),
+                                                       y: (False, False)}
+    assert dim_handling([x], broadcastables={x: (False,)}) == {x: (False,)}
+
+def test_theano_function_kwargs():
+    """
+    Test passing additional kwargs from theano_function() to theano.function().
+    """
+    import numpy as np
+    f = theano_function_([x, y, z], [x+y], dim=1, on_unused_input='ignore',
+            dtypes={x: 'float64', y: 'float64', z: 'float64'})
+    assert np.linalg.norm(f([1, 2], [3, 4], [0, 0]) - np.asarray([4, 6])) < 1e-9
+
+    f = theano_function_([x, y, z], [x+y],
+                        dtypes={x: 'float64', y: 'float64', z: 'float64'},
+                        dim=1, on_unused_input='ignore')
+    xx = np.arange(3).astype('float64')
+    yy = 2*np.arange(3).astype('float64')
+    zz = 2*np.arange(3).astype('float64')
+    assert np.linalg.norm(f(xx, yy, zz) - 3*np.arange(3)) < 1e-9
+
+def test_theano_function_scalar():
+    """ Test the "scalar" argument to theano_function(). """
+
+    args = [
+        ([x, y], [x + y], None, [0]),  # Single 0d output
+        ([X, Y], [X + Y], None, [2]),  # Single 2d output
+        ([x, y], [x + y], {x: 0, y: 1}, [1]),  # Single 1d output
+        ([x, y], [x + y, x - y], None, [0, 0]),  # Two 0d outputs
+        ([x, y, X, Y], [x + y, X + Y], None, [0, 2]),  # One 0d output, one 2d
+    ]
+
+    # Create and test functions with and without the scalar setting
+    for inputs, outputs, in_dims, out_dims in args:
+        for scalar in [False, True]:
+
+            f = theano_function_(inputs, outputs, dims=in_dims, scalar=scalar)
+
+            # Check the theano_function attribute is set whether wrapped or not
+            assert isinstance(f.theano_function, theano.compile.function_module.Function)
+
+            # Feed in inputs of the appropriate size and get outputs
+            in_values = [
+                np.ones([1 if bc else 5 for bc in i.type.broadcastable])
+                for i in f.theano_function.input_storage
+            ]
+            out_values = f(*in_values)
+            if not isinstance(out_values, list):
+                out_values = [out_values]
+
+            # Check output types and shapes
+            assert len(out_dims) == len(out_values)
+            for d, value in zip(out_dims, out_values):
+
+                if scalar and d == 0:
+                    # Should have been converted to a scalar value
+                    assert isinstance(value, np.number)
+
+                else:
+                    # Otherwise should be an array
+                    assert isinstance(value, np.ndarray)
+                    assert value.ndim == d
+
+def test_theano_function_bad_kwarg():
+    """
+    Passing an unknown keyword argument to theano_function() should raise an
+    exception.
+    """
+    raises(Exception, lambda : theano_function_([x], [x+1], foobar=3))
+
+
+def test_slice():
+    assert theano_code_(slice(1, 2, 3)) == slice(1, 2, 3)
+
+    def theq_slice(s1, s2):
+        for attr in ['start', 'stop', 'step']:
+            a1 = getattr(s1, attr)
+            a2 = getattr(s2, attr)
+            if a1 is None or a2 is None:
+                if not (a1 is None or a2 is None):
+                    return False
+            elif not theq(a1, a2):
+                return False
+        return True
+
+    dtypes = {x: 'int32', y: 'int32'}
+    assert theq_slice(theano_code_(slice(x, y), dtypes=dtypes), slice(xt, yt))
+    assert theq_slice(theano_code_(slice(1, x, 3), dtypes=dtypes), slice(1, xt, 3))
+
+def test_MatrixSlice():
+    from theano import Constant
+
+    cache = {}
+
+    n = sy.Symbol('n', integer=True)
+    X = sy.MatrixSymbol('X', n, n)
+
+    Y = X[1:2:3, 4:5:6]
+    Yt = theano_code_(Y, cache=cache)
+
+    s = ts.Scalar('int64')
+    assert tuple(Yt.owner.op.idx_list) == (slice(s, s, s), slice(s, s, s))
+    assert Yt.owner.inputs[0] == theano_code_(X, cache=cache)
+    # == doesn't work in theano like it does in SymPy. You have to use
+    # equals.
+    assert all(Yt.owner.inputs[i].equals(Constant(s, i)) for i in range(1, 7))
+
+    k = sy.Symbol('k')
+    theano_code_(k, dtypes={k: 'int32'})
+    start, stop, step = 4, k, 2
+    Y = X[start:stop:step]
+    Yt = theano_code_(Y, dtypes={n: 'int32', k: 'int32'})
+    # assert Yt.owner.op.idx_list[0].stop == kt
+
+def test_BlockMatrix():
+    n = sy.Symbol('n', integer=True)
+    A, B, C, D = [sy.MatrixSymbol(name, n, n) for name in 'ABCD']
+    At, Bt, Ct, Dt = map(theano_code_, (A, B, C, D))
+    Block = sy.BlockMatrix([[A, B], [C, D]])
+    Blockt = theano_code_(Block)
+    solutions = [tt.join(0, tt.join(1, At, Bt), tt.join(1, Ct, Dt)),
+                 tt.join(1, tt.join(0, At, Ct), tt.join(0, Bt, Dt))]
+    assert any(theq(Blockt, solution) for solution in solutions)
+
+@SKIP
+def test_BlockMatrix_Inverse_execution():
+    k, n = 2, 4
+    dtype = 'float32'
+    A = sy.MatrixSymbol('A', n, k)
+    B = sy.MatrixSymbol('B', n, n)
+    inputs = A, B
+    output = B.I*A
+
+    cutsizes = {A: [(n//2, n//2), (k//2, k//2)],
+                B: [(n//2, n//2), (n//2, n//2)]}
+    cutinputs = [sy.blockcut(i, *cutsizes[i]) for i in inputs]
+    cutoutput = output.subs(dict(zip(inputs, cutinputs)))
+
+    dtypes = dict(zip(inputs, [dtype]*len(inputs)))
+    f = theano_function_(inputs, [output], dtypes=dtypes, cache={})
+    fblocked = theano_function_(inputs, [sy.block_collapse(cutoutput)],
+                                dtypes=dtypes, cache={})
+
+    ninputs = [np.random.rand(*x.shape).astype(dtype) for x in inputs]
+    ninputs = [np.arange(n*k).reshape(A.shape).astype(dtype),
+               np.eye(n).astype(dtype)]
+    ninputs[1] += np.ones(B.shape)*1e-5
+
+    assert np.allclose(f(*ninputs), fblocked(*ninputs), rtol=1e-5)
+
+def test_DenseMatrix():
+    t = sy.Symbol('theta')
+    for MatrixType in [sy.Matrix, sy.ImmutableMatrix]:
+        X = MatrixType([[sy.cos(t), -sy.sin(t)], [sy.sin(t), sy.cos(t)]])
+        tX = theano_code_(X)
+        assert isinstance(tX, tt.TensorVariable)
+        assert tX.owner.op == tt.join_
+
+
+def test_cache_basic():
+    """ Test single symbol-like objects are cached when printed by themselves. """
+
+    # Pairs of objects which should be considered equivalent with respect to caching
+    pairs = [
+        (x, sy.Symbol('x')),
+        (X, sy.MatrixSymbol('X', *X.shape)),
+        (f_t, sy.Function('f')(sy.Symbol('t'))),
+    ]
+
+    for s1, s2 in pairs:
+        cache = {}
+        st = theano_code_(s1, cache=cache)
+
+        # Test hit with same instance
+        assert theano_code_(s1, cache=cache) is st
+
+        # Test miss with same instance but new cache
+        assert theano_code_(s1, cache={}) is not st
+
+        # Test hit with different but equivalent instance
+        assert theano_code_(s2, cache=cache) is st
+
+def test_global_cache():
+    """ Test use of the global cache. """
+    from sympy.printing.theanocode import global_cache
+
+    backup = dict(global_cache)
+    try:
+        # Temporarily empty global cache
+        global_cache.clear()
+
+        for s in [x, X, f_t]:
+            with warns_deprecated_sympy():
+                st = theano_code(s)
+                assert theano_code(s) is st
+
+    finally:
+        # Restore global cache
+        global_cache.update(backup)
+
+def test_cache_types_distinct():
+    """
+    Test that symbol-like objects of different types (Symbol, MatrixSymbol,
+    AppliedUndef) are distinguished by the cache even if they have the same
+    name.
+    """
+    symbols = [sy.Symbol('f_t'), sy.MatrixSymbol('f_t', 4, 4), f_t]
+
+    cache = {}  # Single shared cache
+    printed = {}
+
+    for s in symbols:
+        st = theano_code_(s, cache=cache)
+        assert st not in printed.values()
+        printed[s] = st
+
+    # Check all printed objects are distinct
+    assert len(set(map(id, printed.values()))) == len(symbols)
+
+    # Check retrieving
+    for s, st in printed.items():
+        with warns_deprecated_sympy():
+            assert theano_code(s, cache=cache) is st
+
+def test_symbols_are_created_once():
+    """
+    Test that a symbol is cached and reused when it appears in an expression
+    more than once.
+    """
+    expr = sy.Add(x, x, evaluate=False)
+    comp = theano_code_(expr)
+
+    assert theq(comp, xt + xt)
+    assert not theq(comp, xt + theano_code_(x))
+
+def test_cache_complex():
+    """
+    Test caching on a complicated expression with multiple symbols appearing
+    multiple times.
+    """
+    expr = x ** 2 + (y - sy.exp(x)) * sy.sin(z - x * y)
+    symbol_names = {s.name for s in expr.free_symbols}
+    expr_t = theano_code_(expr)
+
+    # Iterate through variables in the Theano computational graph that the
+    # printed expression depends on
+    seen = set()
+    for v in theano.gof.graph.ancestors([expr_t]):
+        # Owner-less, non-constant variables should be our symbols
+        if v.owner is None and not isinstance(v, theano.gof.graph.Constant):
+            # Check it corresponds to a symbol and appears only once
+            assert v.name in symbol_names
+            assert v.name not in seen
+            seen.add(v.name)
+
+    # Check all were present
+    assert seen == symbol_names
+
+
+def test_Piecewise():
+    # A piecewise linear
+    expr = sy.Piecewise((0, x<0), (x, x<2), (1, True))  # ___/III
+    result = theano_code_(expr)
+    assert result.owner.op == tt.switch
+
+    expected = tt.switch(xt<0, 0, tt.switch(xt<2, xt, 1))
+    assert theq(result, expected)
+
+    expr = sy.Piecewise((x, x < 0))
+    result = theano_code_(expr)
+    expected = tt.switch(xt < 0, xt, np.nan)
+    assert theq(result, expected)
+
+    expr = sy.Piecewise((0, sy.And(x>0, x<2)), \
+        (x, sy.Or(x>2, x<0)))
+    result = theano_code_(expr)
+    expected = tt.switch(tt.and_(xt>0,xt<2), 0, \
+        tt.switch(tt.or_(xt>2, xt<0), xt, np.nan))
+    assert theq(result, expected)
+
+
+def test_Relationals():
+    assert theq(theano_code_(sy.Eq(x, y)), tt.eq(xt, yt))
+    # assert theq(theano_code_(sy.Ne(x, y)), tt.neq(xt, yt))  # TODO - implement
+    assert theq(theano_code_(x > y), xt > yt)
+    assert theq(theano_code_(x < y), xt < yt)
+    assert theq(theano_code_(x >= y), xt >= yt)
+    assert theq(theano_code_(x <= y), xt <= yt)
+
+
+def test_complexfunctions():
+    with warns_deprecated_sympy():
+        xt, yt = theano_code_(x, dtypes={x:'complex128'}), theano_code_(y, dtypes={y: 'complex128'})
+    from sympy.functions.elementary.complexes import conjugate
+    from theano.tensor import as_tensor_variable as atv
+    from theano.tensor import complex as cplx
+    with warns_deprecated_sympy():
+        assert theq(theano_code_(y*conjugate(x)), yt*(xt.conj()))
+        assert theq(theano_code_((1+2j)*x), xt*(atv(1.0)+atv(2.0)*cplx(0,1)))
+
+
+def test_constantfunctions():
+    with warns_deprecated_sympy():
+        tf = theano_function_([],[1+1j])
+    assert(tf()==1+1j)
+
+
+def test_Exp1():
+    """
+    Test that exp(1) prints without error and evaluates close to SymPy's E
+    """
+    # sy.exp(1) should yield same instance of E as sy.E (singleton), but extra
+    # check added for sanity
+    e_a = sy.exp(1)
+    e_b = sy.E
+
+    np.testing.assert_allclose(float(e_a), np.e)
+    np.testing.assert_allclose(float(e_b), np.e)
+
+    e = theano_code_(e_a)
+    np.testing.assert_allclose(float(e_a), e.eval())
+
+    e = theano_code_(e_b)
+    np.testing.assert_allclose(float(e_b), e.eval())
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_torch.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_torch.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ce2c6cec75e03264f93b472a79eb073742e3486
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_torch.py
@@ -0,0 +1,531 @@
+import random
+import math
+
+from sympy import symbols, Derivative
+from sympy.printing.pytorch import torch_code
+from sympy import (eye, MatrixSymbol, Matrix)
+from sympy.tensor.array import NDimArray
+from sympy.tensor.array.expressions.array_expressions import (
+    ArrayTensorProduct, ArrayAdd,
+    PermuteDims, ArrayDiagonal, _CodegenArrayAbstract)
+from sympy.utilities.lambdify import lambdify
+from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt
+from sympy.functions import \
+    Abs, ceiling, exp, floor, sign, sin, asin, cos, \
+    acos, tan, atan, atan2, cosh, acosh, sinh, asinh, tanh, atanh, \
+    re, im, arg, erf, loggamma, sqrt
+from sympy.testing.pytest import skip
+from sympy.external import import_module
+from sympy.matrices.expressions import \
+    Determinant, HadamardProduct, Inverse, Trace
+from sympy.matrices import randMatrix
+from sympy.matrices import Identity, ZeroMatrix, OneMatrix
+from sympy import conjugate, I
+from sympy import Heaviside, gamma, polygamma
+
+
+
+torch = import_module("torch")
+
+M = MatrixSymbol("M", 3, 3)
+N = MatrixSymbol("N", 3, 3)
+P = MatrixSymbol("P", 3, 3)
+Q = MatrixSymbol("Q", 3, 3)
+
+x, y, z, t = symbols("x y z t")
+
+if torch is not None:
+    llo = [list(range(i, i + 3)) for i in range(0, 9, 3)]
+    m3x3 = torch.tensor(llo, dtype=torch.float64)
+    m3x3sympy = Matrix(llo)
+
+
+def _compare_torch_matrix(variables, expr):
+    f = lambdify(variables, expr, 'torch')
+
+    random_matrices = [randMatrix(i.shape[0], i.shape[1]) for i in variables]
+    random_variables = [torch.tensor(i.tolist(), dtype=torch.float64) for i in random_matrices]
+    r = f(*random_variables)
+    e = expr.subs(dict(zip(variables, random_matrices))).doit()
+
+    if isinstance(e, _CodegenArrayAbstract):
+        e = e.doit()
+
+    if hasattr(e, 'is_number') and e.is_number:
+        if isinstance(r, torch.Tensor) and r.dim() == 0:
+            r = r.item()
+            e = float(e)
+            assert abs(r - e) < 1e-6
+            return
+
+    if e.is_Matrix or isinstance(e, NDimArray):
+        e = torch.tensor(e.tolist(), dtype=torch.float64)
+        assert torch.allclose(r, e, atol=1e-6)
+    else:
+        raise TypeError(f"Cannot compare {type(r)} with {type(e)}")
+
+
+def _compare_torch_scalar(variables, expr, rng=lambda: random.uniform(-5, 5)):
+    f = lambdify(variables, expr, 'torch')
+    rvs = [rng() for v in variables]
+    t_rvs = [torch.tensor(i, dtype=torch.float64) for i in rvs]
+    r = f(*t_rvs)
+    if isinstance(r, torch.Tensor):
+        r = r.item()
+    e = expr.subs(dict(zip(variables, rvs))).doit()
+    assert abs(r - e) < 1e-6
+
+
+def _compare_torch_relational(variables, expr, rng=lambda: random.randint(0, 10)):
+    f = lambdify(variables, expr, 'torch')
+    rvs = [rng() for v in variables]
+    t_rvs = [torch.tensor(i, dtype=torch.float64) for i in rvs]
+    r = f(*t_rvs)
+    e = bool(expr.subs(dict(zip(variables, rvs))).doit())
+    assert r.item() == e
+
+
+def test_torch_math():
+    if not torch:
+        skip("PyTorch not installed")
+
+    expr = Abs(x)
+    assert torch_code(expr) == "torch.abs(x)"
+    f = lambdify(x, expr, 'torch')
+    ma = torch.tensor([[-1, 2, -3, -4]], dtype=torch.float64)
+    y_abs = f(ma)
+    c = torch.abs(ma)
+    assert torch.all(y_abs == c)
+
+    expr = sign(x)
+    assert torch_code(expr) == "torch.sign(x)"
+    _compare_torch_scalar((x,), expr, rng=lambda: random.uniform(-10, 10))
+
+    expr = ceiling(x)
+    assert torch_code(expr) == "torch.ceil(x)"
+    _compare_torch_scalar((x,), expr, rng=lambda: random.random())
+
+    expr = floor(x)
+    assert torch_code(expr) == "torch.floor(x)"
+    _compare_torch_scalar((x,), expr, rng=lambda: random.random())
+
+    expr = exp(x)
+    assert torch_code(expr) == "torch.exp(x)"
+    _compare_torch_scalar((x,), expr, rng=lambda: random.uniform(-2, 2))
+
+    expr = sqrt(x)
+    assert torch_code(expr) == "torch.sqrt(x)"
+    _compare_torch_scalar((x,), expr, rng=lambda: random.random())
+
+    expr = x ** 4
+    assert torch_code(expr) == "torch.pow(x, 4)"
+    _compare_torch_scalar((x,), expr, rng=lambda: random.random())
+
+    expr = cos(x)
+    assert torch_code(expr) == "torch.cos(x)"
+    _compare_torch_scalar((x,), expr, rng=lambda: random.random())
+
+    expr = acos(x)
+    assert torch_code(expr) == "torch.acos(x)"
+    _compare_torch_scalar((x,), expr, rng=lambda: random.uniform(-0.99, 0.99))
+
+    expr = sin(x)
+    assert torch_code(expr) == "torch.sin(x)"
+    _compare_torch_scalar((x,), expr, rng=lambda: random.random())
+
+    expr = asin(x)
+    assert torch_code(expr) == "torch.asin(x)"
+    _compare_torch_scalar((x,), expr, rng=lambda: random.uniform(-0.99, 0.99))
+
+    expr = tan(x)
+    assert torch_code(expr) == "torch.tan(x)"
+    _compare_torch_scalar((x,), expr, rng=lambda: random.uniform(-1.5, 1.5))
+
+    expr = atan(x)
+    assert torch_code(expr) == "torch.atan(x)"
+    _compare_torch_scalar((x,), expr, rng=lambda: random.uniform(-5, 5))
+
+    expr = atan2(y, x)
+    assert torch_code(expr) == "torch.atan2(y, x)"
+    _compare_torch_scalar((y, x), expr, rng=lambda: random.uniform(-5, 5))
+
+    expr = cosh(x)
+    assert torch_code(expr) == "torch.cosh(x)"
+    _compare_torch_scalar((x,), expr, rng=lambda: random.uniform(-2, 2))
+
+    expr = acosh(x)
+    assert torch_code(expr) == "torch.acosh(x)"
+    _compare_torch_scalar((x,), expr, rng=lambda: random.uniform(1.1, 5))
+
+    expr = sinh(x)
+    assert torch_code(expr) == "torch.sinh(x)"
+    _compare_torch_scalar((x,), expr, rng=lambda: random.uniform(-2, 2))
+
+    expr = asinh(x)
+    assert torch_code(expr) == "torch.asinh(x)"
+    _compare_torch_scalar((x,), expr, rng=lambda: random.uniform(-5, 5))
+
+    expr = tanh(x)
+    assert torch_code(expr) == "torch.tanh(x)"
+    _compare_torch_scalar((x,), expr, rng=lambda: random.uniform(-2, 2))
+
+    expr = atanh(x)
+    assert torch_code(expr) == "torch.atanh(x)"
+    _compare_torch_scalar((x,), expr, rng=lambda: random.uniform(-0.9, 0.9))
+
+    expr = erf(x)
+    assert torch_code(expr) == "torch.erf(x)"
+    _compare_torch_scalar((x,), expr, rng=lambda: random.uniform(-2, 2))
+
+    expr = loggamma(x)
+    assert torch_code(expr) == "torch.lgamma(x)"
+    _compare_torch_scalar((x,), expr, rng=lambda: random.uniform(0.5, 5))
+
+
+def test_torch_complexes():
+    assert torch_code(re(x)) == "torch.real(x)"
+    assert torch_code(im(x)) == "torch.imag(x)"
+    assert torch_code(arg(x)) == "torch.angle(x)"
+
+
+def test_torch_relational():
+    if not torch:
+        skip("PyTorch not installed")
+
+    expr = Eq(x, y)
+    assert torch_code(expr) == "torch.eq(x, y)"
+    _compare_torch_relational((x, y), expr)
+
+    expr = Ne(x, y)
+    assert torch_code(expr) == "torch.ne(x, y)"
+    _compare_torch_relational((x, y), expr)
+
+    expr = Ge(x, y)
+    assert torch_code(expr) == "torch.ge(x, y)"
+    _compare_torch_relational((x, y), expr)
+
+    expr = Gt(x, y)
+    assert torch_code(expr) == "torch.gt(x, y)"
+    _compare_torch_relational((x, y), expr)
+
+    expr = Le(x, y)
+    assert torch_code(expr) == "torch.le(x, y)"
+    _compare_torch_relational((x, y), expr)
+
+    expr = Lt(x, y)
+    assert torch_code(expr) == "torch.lt(x, y)"
+    _compare_torch_relational((x, y), expr)
+
+
+def test_torch_matrix():
+    if torch is None:
+        skip("PyTorch not installed")
+
+    expr = M
+    assert torch_code(expr) == "M"
+    f = lambdify((M,), expr, "torch")
+    eye_mat = eye(3)
+    eye_tensor = torch.tensor(eye_mat.tolist(), dtype=torch.float64)
+    assert torch.allclose(f(eye_tensor), eye_tensor)
+
+    expr = M * N
+    assert torch_code(expr) == "torch.matmul(M, N)"
+    _compare_torch_matrix((M, N), expr)
+
+    expr = M ** 3
+    assert torch_code(expr) == "torch.mm(torch.mm(M, M), M)"
+    _compare_torch_matrix((M,), expr)
+
+    expr = M * N * P * Q
+    assert torch_code(expr) == "torch.matmul(torch.matmul(torch.matmul(M, N), P), Q)"
+    _compare_torch_matrix((M, N, P, Q), expr)
+
+    expr = Trace(M)
+    assert torch_code(expr) == "torch.trace(M)"
+    _compare_torch_matrix((M,), expr)
+
+    expr = Determinant(M)
+    assert torch_code(expr) == "torch.det(M)"
+    _compare_torch_matrix((M,), expr)
+
+    expr = HadamardProduct(M, N)
+    assert torch_code(expr) == "torch.mul(M, N)"
+    _compare_torch_matrix((M, N), expr)
+
+    expr = Inverse(M)
+    assert torch_code(expr) == "torch.linalg.inv(M)"
+
+    # For inverse, use a matrix that's guaranteed to be invertible
+    eye_mat = eye(3)
+    eye_tensor = torch.tensor(eye_mat.tolist(), dtype=torch.float64)
+    f = lambdify((M,), expr, "torch")
+    result = f(eye_tensor)
+    expected = torch.linalg.inv(eye_tensor)
+    assert torch.allclose(result, expected)
+
+
+def test_torch_array_operations():
+    if not torch:
+        skip("PyTorch not installed")
+
+    M = MatrixSymbol("M", 2, 2)
+    N = MatrixSymbol("N", 2, 2)
+    P = MatrixSymbol("P", 2, 2)
+    Q = MatrixSymbol("Q", 2, 2)
+
+    ma = torch.tensor([[1., 2.], [3., 4.]], dtype=torch.float64)
+    mb = torch.tensor([[1., -2.], [-1., 3.]], dtype=torch.float64)
+    mc = torch.tensor([[2., 0.], [1., 2.]], dtype=torch.float64)
+    md = torch.tensor([[1., -1.], [4., 7.]], dtype=torch.float64)
+
+    cg = ArrayTensorProduct(M, N)
+    assert torch_code(cg) == 'torch.einsum("ab,cd", M, N)'
+    f = lambdify((M, N), cg, 'torch')
+    y = f(ma, mb)
+    c = torch.einsum("ij,kl", ma, mb)
+    assert torch.allclose(y, c)
+
+    cg = ArrayAdd(M, N)
+    assert torch_code(cg) == 'torch.add(M, N)'
+    f = lambdify((M, N), cg, 'torch')
+    y = f(ma, mb)
+    c = ma + mb
+    assert torch.allclose(y, c)
+
+    cg = ArrayAdd(M, N, P)
+    assert torch_code(cg) == 'torch.add(torch.add(M, N), P)'
+    f = lambdify((M, N, P), cg, 'torch')
+    y = f(ma, mb, mc)
+    c = ma + mb + mc
+    assert torch.allclose(y, c)
+
+    cg = ArrayAdd(M, N, P, Q)
+    assert torch_code(cg) == 'torch.add(torch.add(torch.add(M, N), P), Q)'
+    f = lambdify((M, N, P, Q), cg, 'torch')
+    y = f(ma, mb, mc, md)
+    c = ma + mb + mc + md
+    assert torch.allclose(y, c)
+
+    cg = PermuteDims(M, [1, 0])
+    assert torch_code(cg) == 'M.permute(1, 0)'
+    f = lambdify((M,), cg, 'torch')
+    y = f(ma)
+    c = ma.T
+    assert torch.allclose(y, c)
+
+    cg = PermuteDims(ArrayTensorProduct(M, N), [1, 2, 3, 0])
+    assert torch_code(cg) == 'torch.einsum("ab,cd", M, N).permute(1, 2, 3, 0)'
+    f = lambdify((M, N), cg, 'torch')
+    y = f(ma, mb)
+    c = torch.einsum("ab,cd", ma, mb).permute(1, 2, 3, 0)
+    assert torch.allclose(y, c)
+
+    cg = ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2))
+    assert torch_code(cg) == 'torch.einsum("ab,bc->acb", M, N)'
+    f = lambdify((M, N), cg, 'torch')
+    y = f(ma, mb)
+    c = torch.einsum("ab,bc->acb", ma, mb)
+    assert torch.allclose(y, c)
+
+
+def test_torch_derivative():
+    """Test derivative handling."""
+    expr = Derivative(sin(x), x)
+    assert torch_code(expr) == 'torch.autograd.grad(torch.sin(x), x)[0]'
+
+
+def test_torch_printing_dtype():
+    if not torch:
+        skip("PyTorch not installed")
+
+    # matrix printing with default dtype
+    expr = Matrix([[x, sin(y)], [exp(z), -t]])
+    assert "dtype=torch.float64" in torch_code(expr)
+
+    # explicit dtype
+    assert "dtype=torch.float32" in torch_code(expr, dtype="torch.float32")
+
+    # with requires_grad
+    result = torch_code(expr, requires_grad=True)
+    assert "requires_grad=True" in result
+    assert "dtype=torch.float64" in result
+
+    # both
+    result = torch_code(expr, requires_grad=True, dtype="torch.float32")
+    assert "requires_grad=True" in result
+    assert "dtype=torch.float32" in result
+
+
+def test_requires_grad():
+    if not torch:
+        skip("PyTorch not installed")
+
+    expr = sin(x) + cos(y)
+    f = lambdify([x, y], expr, 'torch')
+
+    # make sure the gradients flow
+    x_val = torch.tensor(1.0, requires_grad=True)
+    y_val = torch.tensor(2.0, requires_grad=True)
+    result = f(x_val, y_val)
+    assert result.requires_grad
+    result.backward()
+
+    # x_val.grad should be cos(x_val) which is close to cos(1.0)
+    assert abs(x_val.grad.item() - float(cos(1.0).evalf())) < 1e-6
+
+    # y_val.grad should be -sin(y_val) which is close to -sin(2.0)
+    assert abs(y_val.grad.item() - float(-sin(2.0).evalf())) < 1e-6
+
+
+def test_torch_multi_variable_derivatives():
+    if not torch:
+        skip("PyTorch not installed")
+
+    x, y, z = symbols("x y z")
+
+    expr = Derivative(sin(x), x)
+    assert torch_code(expr) == "torch.autograd.grad(torch.sin(x), x)[0]"
+
+    expr = Derivative(sin(x), (x, 2))
+    assert torch_code(
+        expr) == "torch.autograd.grad(torch.autograd.grad(torch.sin(x), x, create_graph=True)[0], x, create_graph=True)[0]"
+
+    expr = Derivative(sin(x * y), x, y)
+    result = torch_code(expr)
+    expected = "torch.autograd.grad(torch.autograd.grad(torch.sin(x*y), x, create_graph=True)[0], y, create_graph=True)[0]"
+    normalized_result = result.replace(" ", "")
+    normalized_expected = expected.replace(" ", "")
+    assert normalized_result == normalized_expected
+
+    expr = Derivative(sin(x), x, x)
+    result = torch_code(expr)
+    expected = "torch.autograd.grad(torch.autograd.grad(torch.sin(x), x, create_graph=True)[0], x, create_graph=True)[0]"
+    assert result == expected
+
+    expr = Derivative(sin(x * y * z), x, (y, 2), z)
+    result = torch_code(expr)
+    expected = "torch.autograd.grad(torch.autograd.grad(torch.autograd.grad(torch.autograd.grad(torch.sin(x*y*z), x, create_graph=True)[0], y, create_graph=True)[0], y, create_graph=True)[0], z, create_graph=True)[0]"
+    normalized_result = result.replace(" ", "")
+    normalized_expected = expected.replace(" ", "")
+    assert normalized_result == normalized_expected
+
+
+def test_torch_derivative_lambdify():
+    if not torch:
+        skip("PyTorch not installed")
+
+    x = symbols("x")
+    y = symbols("y")
+
+    expr = Derivative(x ** 2, x)
+    f = lambdify(x, expr, 'torch')
+    x_val = torch.tensor(2.0, requires_grad=True)
+    result = f(x_val)
+    assert torch.isclose(result, torch.tensor(4.0))
+
+    expr = Derivative(sin(x), (x, 2))
+    f = lambdify(x, expr, 'torch')
+    # Second derivative of sin(x) at x=0 is 0, not -1
+    x_val = torch.tensor(0.0, requires_grad=True)
+    result = f(x_val)
+    assert torch.isclose(result, torch.tensor(0.0), atol=1e-5)
+
+    x_val = torch.tensor(math.pi / 2, requires_grad=True)
+    result = f(x_val)
+    assert torch.isclose(result, torch.tensor(-1.0), atol=1e-5)
+
+    expr = Derivative(x * y ** 2, x, y)
+    f = lambdify((x, y), expr, 'torch')
+    x_val = torch.tensor(2.0, requires_grad=True)
+    y_val = torch.tensor(3.0, requires_grad=True)
+    result = f(x_val, y_val)
+    assert torch.isclose(result, torch.tensor(6.0))
+
+
+def test_torch_special_matrices():
+    if not torch:
+        skip("PyTorch not installed")
+
+    expr = Identity(3)
+    assert torch_code(expr) == "torch.eye(3)"
+
+    n = symbols("n")
+    expr = Identity(n)
+    assert torch_code(expr) == "torch.eye(n, n)"
+
+    expr = ZeroMatrix(2, 3)
+    assert torch_code(expr) == "torch.zeros((2, 3))"
+
+    m, n = symbols("m n")
+    expr = ZeroMatrix(m, n)
+    assert torch_code(expr) == "torch.zeros((m, n))"
+
+    expr = OneMatrix(2, 3)
+    assert torch_code(expr) == "torch.ones((2, 3))"
+
+    expr = OneMatrix(m, n)
+    assert torch_code(expr) == "torch.ones((m, n))"
+
+
+def test_torch_special_matrices_lambdify():
+    if not torch:
+        skip("PyTorch not installed")
+
+    expr = Identity(3)
+    f = lambdify([], expr, 'torch')
+    result = f()
+    expected = torch.eye(3)
+    assert torch.allclose(result, expected)
+
+    expr = ZeroMatrix(2, 3)
+    f = lambdify([], expr, 'torch')
+    result = f()
+    expected = torch.zeros((2, 3))
+    assert torch.allclose(result, expected)
+
+    expr = OneMatrix(2, 3)
+    f = lambdify([], expr, 'torch')
+    result = f()
+    expected = torch.ones((2, 3))
+    assert torch.allclose(result, expected)
+
+
+def test_torch_complex_operations():
+    if not torch:
+        skip("PyTorch not installed")
+
+    expr = conjugate(x)
+    assert torch_code(expr) == "torch.conj(x)"
+
+    # SymPy distributes conjugate over addition and applies specific rules for each term
+    expr = conjugate(sin(x) + I * cos(y))
+    assert torch_code(expr) == "torch.sin(torch.conj(x)) - 1j*torch.cos(torch.conj(y))"
+
+    expr = I
+    assert torch_code(expr) == "1j"
+
+    expr = 2 * I + x
+    assert torch_code(expr) == "x + 2*1j"
+
+    expr = exp(I * x)
+    assert torch_code(expr) == "torch.exp(1j*x)"
+
+
+def test_torch_special_functions():
+    if not torch:
+        skip("PyTorch not installed")
+
+    expr = Heaviside(x)
+    assert torch_code(expr) == "torch.heaviside(x, 1/2)"
+
+    expr = Heaviside(x, 0)
+    assert torch_code(expr) == "torch.heaviside(x, 0)"
+
+    expr = gamma(x)
+    assert torch_code(expr) == "torch.special.gamma(x)"
+
+    expr = polygamma(0, x)  # Use polygamma instead of digamma because sympy will default to that anyway
+    assert torch_code(expr) == "torch.special.digamma(x)"
+
+    expr = gamma(sin(x))
+    assert torch_code(expr) == "torch.special.gamma(torch.sin(x))"
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_tree.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_tree.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf116d0cac5d38f225815fcd2d4ac90cd0dd96d7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/printing/tests/test_tree.py
@@ -0,0 +1,196 @@
+from sympy.printing.tree import tree
+from sympy.testing.pytest import XFAIL
+
+
+# Remove this flag after making _assumptions cache deterministic.
+@XFAIL
+def test_print_tree_MatAdd():
+    from sympy.matrices.expressions import MatrixSymbol
+    A = MatrixSymbol('A', 3, 3)
+    B = MatrixSymbol('B', 3, 3)
+
+    test_str = [
+        'MatAdd: A + B\n',
+        'algebraic: False\n',
+        'commutative: False\n',
+        'complex: False\n',
+        'composite: False\n',
+        'even: False\n',
+        'extended_negative: False\n',
+        'extended_nonnegative: False\n',
+        'extended_nonpositive: False\n',
+        'extended_nonzero: False\n',
+        'extended_positive: False\n',
+        'extended_real: False\n',
+        'imaginary: False\n',
+        'integer: False\n',
+        'irrational: False\n',
+        'negative: False\n',
+        'noninteger: False\n',
+        'nonnegative: False\n',
+        'nonpositive: False\n',
+        'nonzero: False\n',
+        'odd: False\n',
+        'positive: False\n',
+        'prime: False\n',
+        'rational: False\n',
+        'real: False\n',
+        'transcendental: False\n',
+        'zero: False\n',
+        '+-MatrixSymbol: A\n',
+        '| algebraic: False\n',
+        '| commutative: False\n',
+        '| complex: False\n',
+        '| composite: False\n',
+        '| even: False\n',
+        '| extended_negative: False\n',
+        '| extended_nonnegative: False\n',
+        '| extended_nonpositive: False\n',
+        '| extended_nonzero: False\n',
+        '| extended_positive: False\n',
+        '| extended_real: False\n',
+        '| imaginary: False\n',
+        '| integer: False\n',
+        '| irrational: False\n',
+        '| negative: False\n',
+        '| noninteger: False\n',
+        '| nonnegative: False\n',
+        '| nonpositive: False\n',
+        '| nonzero: False\n',
+        '| odd: False\n',
+        '| positive: False\n',
+        '| prime: False\n',
+        '| rational: False\n',
+        '| real: False\n',
+        '| transcendental: False\n',
+        '| zero: False\n',
+        '| +-Symbol: A\n',
+        '| | commutative: True\n',
+        '| +-Integer: 3\n',
+        '| | algebraic: True\n',
+        '| | commutative: True\n',
+        '| | complex: True\n',
+        '| | extended_negative: False\n',
+        '| | extended_nonnegative: True\n',
+        '| | extended_real: True\n',
+        '| | finite: True\n',
+        '| | hermitian: True\n',
+        '| | imaginary: False\n',
+        '| | infinite: False\n',
+        '| | integer: True\n',
+        '| | irrational: False\n',
+        '| | negative: False\n',
+        '| | noninteger: False\n',
+        '| | nonnegative: True\n',
+        '| | rational: True\n',
+        '| | real: True\n',
+        '| | transcendental: False\n',
+        '| +-Integer: 3\n',
+        '|   algebraic: True\n',
+        '|   commutative: True\n',
+        '|   complex: True\n',
+        '|   extended_negative: False\n',
+        '|   extended_nonnegative: True\n',
+        '|   extended_real: True\n',
+        '|   finite: True\n',
+        '|   hermitian: True\n',
+        '|   imaginary: False\n',
+        '|   infinite: False\n',
+        '|   integer: True\n',
+        '|   irrational: False\n',
+        '|   negative: False\n',
+        '|   noninteger: False\n',
+        '|   nonnegative: True\n',
+        '|   rational: True\n',
+        '|   real: True\n',
+        '|   transcendental: False\n',
+        '+-MatrixSymbol: B\n',
+        '  algebraic: False\n',
+        '  commutative: False\n',
+        '  complex: False\n',
+        '  composite: False\n',
+        '  even: False\n',
+        '  extended_negative: False\n',
+        '  extended_nonnegative: False\n',
+        '  extended_nonpositive: False\n',
+        '  extended_nonzero: False\n',
+        '  extended_positive: False\n',
+        '  extended_real: False\n',
+        '  imaginary: False\n',
+        '  integer: False\n',
+        '  irrational: False\n',
+        '  negative: False\n',
+        '  noninteger: False\n',
+        '  nonnegative: False\n',
+        '  nonpositive: False\n',
+        '  nonzero: False\n',
+        '  odd: False\n',
+        '  positive: False\n',
+        '  prime: False\n',
+        '  rational: False\n',
+        '  real: False\n',
+        '  transcendental: False\n',
+        '  zero: False\n',
+        '  +-Symbol: B\n',
+        '  | commutative: True\n',
+        '  +-Integer: 3\n',
+        '  | algebraic: True\n',
+        '  | commutative: True\n',
+        '  | complex: True\n',
+        '  | extended_negative: False\n',
+        '  | extended_nonnegative: True\n',
+        '  | extended_real: True\n',
+        '  | finite: True\n',
+        '  | hermitian: True\n',
+        '  | imaginary: False\n',
+        '  | infinite: False\n',
+        '  | integer: True\n',
+        '  | irrational: False\n',
+        '  | negative: False\n',
+        '  | noninteger: False\n',
+        '  | nonnegative: True\n',
+        '  | rational: True\n',
+        '  | real: True\n',
+        '  | transcendental: False\n',
+        '  +-Integer: 3\n',
+        '    algebraic: True\n',
+        '    commutative: True\n',
+        '    complex: True\n',
+        '    extended_negative: False\n',
+        '    extended_nonnegative: True\n',
+        '    extended_real: True\n',
+        '    finite: True\n',
+        '    hermitian: True\n',
+        '    imaginary: False\n',
+        '    infinite: False\n',
+        '    integer: True\n',
+        '    irrational: False\n',
+        '    negative: False\n',
+        '    noninteger: False\n',
+        '    nonnegative: True\n',
+        '    rational: True\n',
+        '    real: True\n',
+        '    transcendental: False\n'
+    ]
+
+    assert tree(A + B) == "".join(test_str)
+
+
+def test_print_tree_MatAdd_noassumptions():
+    from sympy.matrices.expressions import MatrixSymbol
+    A = MatrixSymbol('A', 3, 3)
+    B = MatrixSymbol('B', 3, 3)
+
+    test_str = \
+"""MatAdd: A + B
++-MatrixSymbol: A
+| +-Str: A
+| +-Integer: 3
+| +-Integer: 3
++-MatrixSymbol: B
+  +-Str: B
+  +-Integer: 3
+  +-Integer: 3
+"""
+
+    assert tree(A + B, assumptions=False) == test_str
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sandbox/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sandbox/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a84b7517819bb2fc9886274e09d955a74cabca1
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sandbox/__init__.py
@@ -0,0 +1,8 @@
+"""
+Sandbox module of SymPy.
+
+This module contains experimental code, use at your own risk!
+
+There is no warranty that this code will still be located here in future
+versions of SymPy.
+"""
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sandbox/indexed_integrals.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sandbox/indexed_integrals.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0c17d141448b5a71cb814bff76a710a5bd43f88
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sandbox/indexed_integrals.py
@@ -0,0 +1,72 @@
+from sympy.tensor import Indexed
+from sympy.core.containers import Tuple
+from sympy.core.symbol import Dummy
+from sympy.core.sympify import sympify
+from sympy.integrals.integrals import Integral
+
+
+class IndexedIntegral(Integral):
+    """
+    Experimental class to test integration by indexed variables.
+
+    Usage is analogue to ``Integral``, it simply adds awareness of
+    integration over indices.
+
+    Contraction of non-identical index symbols referring to the same
+    ``IndexedBase`` is not yet supported.
+
+    Examples
+    ========
+
+    >>> from sympy.sandbox.indexed_integrals import IndexedIntegral
+    >>> from sympy import IndexedBase, symbols
+    >>> A = IndexedBase('A')
+    >>> i, j = symbols('i j', integer=True)
+    >>> ii = IndexedIntegral(A[i], A[i])
+    >>> ii
+    Integral(_A[i], _A[i])
+    >>> ii.doit()
+    A[i]**2/2
+
+    If the indices are different, indexed objects are considered to be
+    different variables:
+
+    >>> i2 = IndexedIntegral(A[j], A[i])
+    >>> i2
+    Integral(A[j], _A[i])
+    >>> i2.doit()
+    A[i]*A[j]
+    """
+
+    def __new__(cls, function, *limits, **assumptions):
+        repl, limits = IndexedIntegral._indexed_process_limits(limits)
+        function = sympify(function)
+        function = function.xreplace(repl)
+        obj = Integral.__new__(cls, function, *limits, **assumptions)
+        obj._indexed_repl = repl
+        obj._indexed_reverse_repl = {val: key for key, val in repl.items()}
+        return obj
+
+    def doit(self):
+        res = super().doit()
+        return res.xreplace(self._indexed_reverse_repl)
+
+    @staticmethod
+    def _indexed_process_limits(limits):
+        repl = {}
+        newlimits = []
+        for i in limits:
+            if isinstance(i, (tuple, list, Tuple)):
+                v = i[0]
+                vrest = i[1:]
+            else:
+                v = i
+                vrest = ()
+            if isinstance(v, Indexed):
+                if v not in repl:
+                    r = Dummy(str(v))
+                    repl[v] = r
+                newlimits.append((r,)+vrest)
+            else:
+                newlimits.append(i)
+        return repl, newlimits
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sandbox/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sandbox/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sandbox/tests/test_indexed_integrals.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sandbox/tests/test_indexed_integrals.py
new file mode 100644
index 0000000000000000000000000000000000000000..61b98f0ffec29e026f6dfe8e16fde8b5818b0b09
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sandbox/tests/test_indexed_integrals.py
@@ -0,0 +1,25 @@
+from sympy.sandbox.indexed_integrals import IndexedIntegral
+from sympy.core.symbol import symbols
+from sympy.functions.elementary.trigonometric import (cos, sin)
+from sympy.tensor.indexed import (Idx, IndexedBase)
+
+
+def test_indexed_integrals():
+    A = IndexedBase('A')
+    i, j = symbols('i j', integer=True)
+    a1, a2 = symbols('a1:3', cls=Idx)
+    assert isinstance(a1, Idx)
+
+    assert IndexedIntegral(1, A[i]).doit() == A[i]
+    assert IndexedIntegral(A[i], A[i]).doit() == A[i] ** 2 / 2
+    assert IndexedIntegral(A[j], A[i]).doit() == A[i] * A[j]
+    assert IndexedIntegral(A[i] * A[j], A[i]).doit() == A[i] ** 2 * A[j] / 2
+    assert IndexedIntegral(sin(A[i]), A[i]).doit() == -cos(A[i])
+    assert IndexedIntegral(sin(A[j]), A[i]).doit() == sin(A[j]) * A[i]
+
+    assert IndexedIntegral(1, A[a1]).doit() == A[a1]
+    assert IndexedIntegral(A[a1], A[a1]).doit() == A[a1] ** 2 / 2
+    assert IndexedIntegral(A[a2], A[a1]).doit() == A[a1] * A[a2]
+    assert IndexedIntegral(A[a1] * A[a2], A[a1]).doit() == A[a1] ** 2 * A[a2] / 2
+    assert IndexedIntegral(sin(A[a1]), A[a1]).doit() == -cos(A[a1])
+    assert IndexedIntegral(sin(A[a2]), A[a1]).doit() == sin(A[a2]) * A[a1]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..953653e21856b82bc0b708ccd922efb728a084ed
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__init__.py
@@ -0,0 +1,23 @@
+"""A module that handles series: find a limit, order the series etc.
+"""
+from .order import Order
+from .limits import limit, Limit
+from .gruntz import gruntz
+from .series import series
+from .approximants import approximants
+from .residues import residue
+from .sequences import SeqPer, SeqFormula, sequence, SeqAdd, SeqMul
+from .fourier import fourier_series
+from .formal import fps
+from .limitseq import difference_delta, limit_seq
+
+from sympy.core.singleton import S
+EmptySequence = S.EmptySequence
+
+O = Order
+
+__all__ = ['Order', 'O', 'limit', 'Limit', 'gruntz', 'series', 'approximants',
+        'residue', 'EmptySequence', 'SeqPer', 'SeqFormula', 'sequence',
+        'SeqAdd', 'SeqMul', 'fourier_series', 'fps', 'difference_delta',
+        'limit_seq'
+        ]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..046a768b6a5d739ab6b40c80ea1ab253c79cb577
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/approximants.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/approximants.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..50488baaa842dbda18a0fb2b01c27976f70a220e
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/approximants.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/formal.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/formal.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b39aaca395b00c9c92f5dfd2a3398fa2a2b54f62
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/formal.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/fourier.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/fourier.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dcc230412ade23ef55365f7db60d45175cd464ea
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/fourier.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/gruntz.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/gruntz.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3bca21e71153b021c3168cc254d16b9aede67114
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/gruntz.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/limits.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/limits.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..418fdd244ed64e5751a70f558b301fe3fd2ed543
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/limits.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/limitseq.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/limitseq.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5cd4ed3bc85c6be4f190a353e8467c5ac89dec95
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/limitseq.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/order.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/order.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..51a0f48d0cf3c06f01e90e2fc2f92532f7fec22e
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/order.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/residues.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/residues.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6a4e7280e796e0c7a13352c097689a80e581f9f7
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/residues.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/sequences.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/sequences.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5082ba2b73128d55250ce74b3a2b9ca2bb6c6bd1
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/sequences.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/series.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/series.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..00f07869de39e916f81074f8485c1d766d610bd8
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/series.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/series_class.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/series_class.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5f52f51c9cd1fdbc3519d1fc8a71d8abf2370936
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/__pycache__/series_class.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/acceleration.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/acceleration.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2c7c1629a4b0d52e2aa33bd415886dfed515693
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/acceleration.py
@@ -0,0 +1,101 @@
+"""
+Convergence acceleration / extrapolation methods for series and
+sequences.
+
+References:
+Carl M. Bender & Steven A. Orszag, "Advanced Mathematical Methods for
+Scientists and Engineers: Asymptotic Methods and Perturbation Theory",
+Springer 1999. (Shanks transformation: pp. 368-375, Richardson
+extrapolation: pp. 375-377.)
+"""
+
+from sympy.core.numbers import Integer
+from sympy.core.singleton import S
+from sympy.functions.combinatorial.factorials import factorial
+
+
+def richardson(A, k, n, N):
+    """
+    Calculate an approximation for lim k->oo A(k) using Richardson
+    extrapolation with the terms A(n), A(n+1), ..., A(n+N+1).
+    Choosing N ~= 2*n often gives good results.
+
+    Examples
+    ========
+
+    A simple example is to calculate exp(1) using the limit definition.
+    This limit converges slowly; n = 100 only produces two accurate
+    digits:
+
+        >>> from sympy.abc import n
+        >>> e = (1 + 1/n)**n
+        >>> print(round(e.subs(n, 100).evalf(), 10))
+        2.7048138294
+
+    Richardson extrapolation with 11 appropriately chosen terms gives
+    a value that is accurate to the indicated precision:
+
+        >>> from sympy import E
+        >>> from sympy.series.acceleration import richardson
+        >>> print(round(richardson(e, n, 10, 20).evalf(), 10))
+        2.7182818285
+        >>> print(round(E.evalf(), 10))
+        2.7182818285
+
+    Another useful application is to speed up convergence of series.
+    Computing 100 terms of the zeta(2) series 1/k**2 yields only
+    two accurate digits:
+
+        >>> from sympy.abc import k, n
+        >>> from sympy import Sum
+        >>> A = Sum(k**-2, (k, 1, n))
+        >>> print(round(A.subs(n, 100).evalf(), 10))
+        1.6349839002
+
+    Richardson extrapolation performs much better:
+
+        >>> from sympy import pi
+        >>> print(round(richardson(A, n, 10, 20).evalf(), 10))
+        1.6449340668
+        >>> print(round(((pi**2)/6).evalf(), 10))     # Exact value
+        1.6449340668
+
+    """
+    s = S.Zero
+    for j in range(0, N + 1):
+        s += (A.subs(k, Integer(n + j)).doit() * (n + j)**N *
+              S.NegativeOne**(j + N) / (factorial(j) * factorial(N - j)))
+    return s
+
+
+def shanks(A, k, n, m=1):
+    """
+    Calculate an approximation for lim k->oo A(k) using the n-term Shanks
+    transformation S(A)(n). With m > 1, calculate the m-fold recursive
+    Shanks transformation S(S(...S(A)...))(n).
+
+    The Shanks transformation is useful for summing Taylor series that
+    converge slowly near a pole or singularity, e.g. for log(2):
+
+        >>> from sympy.abc import k, n
+        >>> from sympy import Sum, Integer
+        >>> from sympy.series.acceleration import shanks
+        >>> A = Sum(Integer(-1)**(k+1) / k, (k, 1, n))
+        >>> print(round(A.subs(n, 100).doit().evalf(), 10))
+        0.6881721793
+        >>> print(round(shanks(A, n, 25).evalf(), 10))
+        0.6931396564
+        >>> print(round(shanks(A, n, 25, 5).evalf(), 10))
+        0.6931471806
+
+    The correct value is 0.6931471805599453094172321215.
+    """
+    table = [A.subs(k, Integer(j)).doit() for j in range(n + m + 2)]
+    table2 = table.copy()
+
+    for i in range(1, m + 1):
+        for j in range(i, n + m + 1):
+            x, y, z = table[j - 1], table[j], table[j + 1]
+            table2[j] = (z*x - y**2) / (z + x - 2*y)
+        table = table2.copy()
+    return table[n]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/approximants.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/approximants.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d54ce41bc7367606ae6260f8e9ac00149cedc0f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/approximants.py
@@ -0,0 +1,103 @@
+from sympy.core.singleton import S
+from sympy.core.symbol import Symbol
+from sympy.polys.polytools import lcm
+from sympy.utilities import public
+
+@public
+def approximants(l, X=Symbol('x'), simplify=False):
+    """
+    Return a generator for consecutive Pade approximants for a series.
+    It can also be used for computing the rational generating function of a
+    series when possible, since the last approximant returned by the generator
+    will be the generating function (if any).
+
+    Explanation
+    ===========
+
+    The input list can contain more complex expressions than integer or rational
+    numbers; symbols may also be involved in the computation. An example below
+    show how to compute the generating function of the whole Pascal triangle.
+
+    The generator can be asked to apply the sympy.simplify function on each
+    generated term, which will make the computation slower; however it may be
+    useful when symbols are involved in the expressions.
+
+    Examples
+    ========
+
+    >>> from sympy.series import approximants
+    >>> from sympy import lucas, fibonacci, symbols, binomial
+    >>> g = [lucas(k) for k in range(16)]
+    >>> [e for e in approximants(g)]
+    [2, -4/(x - 2), (5*x - 2)/(3*x - 1), (x - 2)/(x**2 + x - 1)]
+
+    >>> h = [fibonacci(k) for k in range(16)]
+    >>> [e for e in approximants(h)]
+    [x, -x/(x - 1), (x**2 - x)/(2*x - 1), -x/(x**2 + x - 1)]
+
+    >>> x, t = symbols("x,t")
+    >>> p=[sum(binomial(k,i)*x**i for i in range(k+1)) for k in range(16)]
+    >>> y = approximants(p, t)
+    >>> for k in range(3): print(next(y))
+    1
+    (x + 1)/((-x - 1)*(t*(x + 1) + (x + 1)/(-x - 1)))
+    nan
+
+    >>> y = approximants(p, t, simplify=True)
+    >>> for k in range(3): print(next(y))
+    1
+    -1/(t*(x + 1) - 1)
+    nan
+
+    See Also
+    ========
+
+    sympy.concrete.guess.guess_generating_function_rational
+    mpmath.pade
+    """
+    from sympy.simplify import simplify as simp
+    from sympy.simplify.radsimp import denom
+    p1, q1 = [S.One], [S.Zero]
+    p2, q2 = [S.Zero], [S.One]
+    while len(l):
+        b = 0
+        while l[b]==0:
+            b += 1
+            if b == len(l):
+                return
+        m = [S.One/l[b]]
+        for k in range(b+1, len(l)):
+            s = 0
+            for j in range(b, k):
+                s -= l[j+1] * m[b-j-1]
+            m.append(s/l[b])
+        l = m
+        a, l[0] = l[0], 0
+        p = [0] * max(len(p2), b+len(p1))
+        q = [0] * max(len(q2), b+len(q1))
+        for k in range(len(p2)):
+            p[k] = a*p2[k]
+        for k in range(b, b+len(p1)):
+            p[k] += p1[k-b]
+        for k in range(len(q2)):
+            q[k] = a*q2[k]
+        for k in range(b, b+len(q1)):
+            q[k] += q1[k-b]
+        while p[-1]==0: p.pop()
+        while q[-1]==0: q.pop()
+        p1, p2 = p2, p
+        q1, q2 = q2, q
+
+        # yield result
+        c = 1
+        for x in p:
+            c = lcm(c, denom(x))
+        for x in q:
+            c = lcm(c, denom(x))
+        out = ( sum(c*e*X**k for k, e in enumerate(p))
+              / sum(c*e*X**k for k, e in enumerate(q)) )
+        if simplify:
+            yield(simp(out))
+        else:
+            yield out
+    return
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/aseries.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/aseries.py
new file mode 100644
index 0000000000000000000000000000000000000000..dbbe0664e6d43a9329f37789c16c48143eda5413
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/aseries.py
@@ -0,0 +1,10 @@
+from sympy.core.sympify import sympify
+
+
+def aseries(expr, x=None, n=6, bound=0, hir=False):
+    """
+    See the docstring of Expr.aseries() for complete details of this wrapper.
+
+    """
+    expr = sympify(expr)
+    return expr.aseries(x, n, bound, hir)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/benchmarks/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/benchmarks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/benchmarks/bench_limit.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/benchmarks/bench_limit.py
new file mode 100644
index 0000000000000000000000000000000000000000..eafc28328848dad4b3ea433537971f5785253afe
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/benchmarks/bench_limit.py
@@ -0,0 +1,9 @@
+from sympy.core.numbers import oo
+from sympy.core.symbol import Symbol
+from sympy.series.limits import limit
+
+x = Symbol('x')
+
+
+def timeit_limit_1x():
+    limit(1/x, x, oo)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/benchmarks/bench_order.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/benchmarks/bench_order.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c85fa173dfc2a478792de8ab816c23ba9d408ef
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/benchmarks/bench_order.py
@@ -0,0 +1,10 @@
+from sympy.core.add import Add
+from sympy.core.symbol import Symbol
+from sympy.series.order import O
+
+x = Symbol('x')
+l = [x**i for i in range(1000)]
+l.append(O(x**1001))
+
+def timeit_order_1x():
+    Add(*l)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/formal.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/formal.py
new file mode 100644
index 0000000000000000000000000000000000000000..ada591e03dd607daf8f8a5da1cf38cf283a3ed86
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/formal.py
@@ -0,0 +1,1863 @@
+"""Formal Power Series"""
+
+from collections import defaultdict
+
+from sympy.core.numbers import (nan, oo, zoo)
+from sympy.core.add import Add
+from sympy.core.expr import Expr
+from sympy.core.function import Derivative, Function, expand
+from sympy.core.mul import Mul
+from sympy.core.numbers import Rational
+from sympy.core.relational import Eq
+from sympy.sets.sets import Interval
+from sympy.core.singleton import S
+from sympy.core.symbol import Wild, Dummy, symbols, Symbol
+from sympy.core.sympify import sympify
+from sympy.discrete.convolutions import convolution
+from sympy.functions.combinatorial.factorials import binomial, factorial, rf
+from sympy.functions.combinatorial.numbers import bell
+from sympy.functions.elementary.integers import floor, frac, ceiling
+from sympy.functions.elementary.miscellaneous import Min, Max
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.series.limits import Limit
+from sympy.series.order import Order
+from sympy.series.sequences import sequence
+from sympy.series.series_class import SeriesBase
+from sympy.utilities.iterables import iterable
+
+
+
+def rational_algorithm(f, x, k, order=4, full=False):
+    """
+    Rational algorithm for computing
+    formula of coefficients of Formal Power Series
+    of a function.
+
+    Explanation
+    ===========
+
+    Applicable when f(x) or some derivative of f(x)
+    is a rational function in x.
+
+    :func:`rational_algorithm` uses :func:`~.apart` function for partial fraction
+    decomposition. :func:`~.apart` by default uses 'undetermined coefficients
+    method'. By setting ``full=True``, 'Bronstein's algorithm' can be used
+    instead.
+
+    Looks for derivative of a function up to 4'th order (by default).
+    This can be overridden using order option.
+
+    Parameters
+    ==========
+
+    x : Symbol
+    order : int, optional
+        Order of the derivative of ``f``, Default is 4.
+    full : bool
+
+    Returns
+    =======
+
+    formula : Expr
+    ind : Expr
+        Independent terms.
+    order : int
+    full : bool
+
+    Examples
+    ========
+
+    >>> from sympy import log, atan
+    >>> from sympy.series.formal import rational_algorithm as ra
+    >>> from sympy.abc import x, k
+
+    >>> ra(1 / (1 - x), x, k)
+    (1, 0, 0)
+    >>> ra(log(1 + x), x, k)
+    (-1/((-1)**k*k), 0, 1)
+
+    >>> ra(atan(x), x, k, full=True)
+    ((-I/(2*(-I)**k) + I/(2*I**k))/k, 0, 1)
+
+    Notes
+    =====
+
+    By setting ``full=True``, range of admissible functions to be solved using
+    ``rational_algorithm`` can be increased. This option should be used
+    carefully as it can significantly slow down the computation as ``doit`` is
+    performed on the :class:`~.RootSum` object returned by the :func:`~.apart`
+    function. Use ``full=False`` whenever possible.
+
+    See Also
+    ========
+
+    sympy.polys.partfrac.apart
+
+    References
+    ==========
+
+    .. [1] Formal Power Series - Dominik Gruntz, Wolfram Koepf
+    .. [2] Power Series in Computer Algebra - Wolfram Koepf
+
+    """
+    from sympy.polys import RootSum, apart
+    from sympy.integrals import integrate
+
+    diff = f
+    ds = []  # list of diff
+
+    for i in range(order + 1):
+        if i:
+            diff = diff.diff(x)
+
+        if diff.is_rational_function(x):
+            coeff, sep = S.Zero, S.Zero
+
+            terms = apart(diff, x, full=full)
+            if terms.has(RootSum):
+                terms = terms.doit()
+
+            for t in Add.make_args(terms):
+                num, den = t.as_numer_denom()
+                if not den.has(x):
+                    sep += t
+                else:
+                    if isinstance(den, Mul):
+                        # m*(n*x - a)**j -> (n*x - a)**j
+                        ind = den.as_independent(x)
+                        den = ind[1]
+                        num /= ind[0]
+
+                    # (n*x - a)**j -> (x - b)
+                    den, j = den.as_base_exp()
+                    a, xterm = den.as_coeff_add(x)
+
+                    # term -> m/x**n
+                    if not a:
+                        sep += t
+                        continue
+
+                    xc = xterm[0].coeff(x)
+                    a /= -xc
+                    num /= xc**j
+
+                    ak = ((-1)**j * num *
+                          binomial(j + k - 1, k).rewrite(factorial) /
+                          a**(j + k))
+                    coeff += ak
+
+            # Hacky, better way?
+            if coeff.is_zero:
+                return None
+            if (coeff.has(x) or coeff.has(zoo) or coeff.has(oo) or
+                    coeff.has(nan)):
+                return None
+
+            for j in range(i):
+                coeff = (coeff / (k + j + 1))
+                sep = integrate(sep, x)
+                sep += (ds.pop() - sep).limit(x, 0)  # constant of integration
+            return (coeff.subs(k, k - i), sep, i)
+
+        else:
+            ds.append(diff)
+
+    return None
+
+
+def rational_independent(terms, x):
+    """
+    Returns a list of all the rationally independent terms.
+
+    Examples
+    ========
+
+    >>> from sympy import sin, cos
+    >>> from sympy.series.formal import rational_independent
+    >>> from sympy.abc import x
+
+    >>> rational_independent([cos(x), sin(x)], x)
+    [cos(x), sin(x)]
+    >>> rational_independent([x**2, sin(x), x*sin(x), x**3], x)
+    [x**3 + x**2, x*sin(x) + sin(x)]
+    """
+    if not terms:
+        return []
+
+    ind = terms[0:1]
+
+    for t in terms[1:]:
+        n = t.as_independent(x)[1]
+        for i, term in enumerate(ind):
+            d = term.as_independent(x)[1]
+            q = (n / d).cancel()
+            if q.is_rational_function(x):
+                ind[i] += t
+                break
+        else:
+            ind.append(t)
+    return ind
+
+
+def simpleDE(f, x, g, order=4):
+    r"""
+    Generates simple DE.
+
+    Explanation
+    ===========
+
+    DE is of the form
+
+    .. math::
+        f^k(x) + \sum\limits_{j=0}^{k-1} A_j f^j(x) = 0
+
+    where :math:`A_j` should be rational function in x.
+
+    Generates DE's upto order 4 (default). DE's can also have free parameters.
+
+    By increasing order, higher order DE's can be found.
+
+    Yields a tuple of (DE, order).
+    """
+    from sympy.solvers.solveset import linsolve
+
+    a = symbols('a:%d' % (order))
+
+    def _makeDE(k):
+        eq = f.diff(x, k) + Add(*[a[i]*f.diff(x, i) for i in range(0, k)])
+        DE = g(x).diff(x, k) + Add(*[a[i]*g(x).diff(x, i) for i in range(0, k)])
+        return eq, DE
+
+    found = False
+    for k in range(1, order + 1):
+        eq, DE = _makeDE(k)
+        eq = eq.expand()
+        terms = eq.as_ordered_terms()
+        ind = rational_independent(terms, x)
+        if found or len(ind) == k:
+            sol = dict(zip(a, (i for s in linsolve(ind, a[:k]) for i in s)))
+            if sol:
+                found = True
+                DE = DE.subs(sol)
+            DE = DE.as_numer_denom()[0]
+            DE = DE.factor().as_coeff_mul(Derivative)[1][0]
+            yield DE.collect(Derivative(g(x))), k
+
+
+def exp_re(DE, r, k):
+    """Converts a DE with constant coefficients (explike) into a RE.
+
+    Explanation
+    ===========
+
+    Performs the substitution:
+
+    .. math::
+        f^j(x) \\to r(k + j)
+
+    Normalises the terms so that lowest order of a term is always r(k).
+
+    Examples
+    ========
+
+    >>> from sympy import Function, Derivative
+    >>> from sympy.series.formal import exp_re
+    >>> from sympy.abc import x, k
+    >>> f, r = Function('f'), Function('r')
+
+    >>> exp_re(-f(x) + Derivative(f(x)), r, k)
+    -r(k) + r(k + 1)
+    >>> exp_re(Derivative(f(x), x) + Derivative(f(x), (x, 2)), r, k)
+    r(k) + r(k + 1)
+
+    See Also
+    ========
+
+    sympy.series.formal.hyper_re
+    """
+    RE = S.Zero
+
+    g = DE.atoms(Function).pop()
+
+    mini = None
+    for t in Add.make_args(DE):
+        coeff, d = t.as_independent(g)
+        if isinstance(d, Derivative):
+            j = d.derivative_count
+        else:
+            j = 0
+        if mini is None or j < mini:
+            mini = j
+        RE += coeff * r(k + j)
+    if mini:
+        RE = RE.subs(k, k - mini)
+    return RE
+
+
+def hyper_re(DE, r, k):
+    """
+    Converts a DE into a RE.
+
+    Explanation
+    ===========
+
+    Performs the substitution:
+
+    .. math::
+        x^l f^j(x) \\to (k + 1 - l)_j . a_{k + j - l}
+
+    Normalises the terms so that lowest order of a term is always r(k).
+
+    Examples
+    ========
+
+    >>> from sympy import Function, Derivative
+    >>> from sympy.series.formal import hyper_re
+    >>> from sympy.abc import x, k
+    >>> f, r = Function('f'), Function('r')
+
+    >>> hyper_re(-f(x) + Derivative(f(x)), r, k)
+    (k + 1)*r(k + 1) - r(k)
+    >>> hyper_re(-x*f(x) + Derivative(f(x), (x, 2)), r, k)
+    (k + 2)*(k + 3)*r(k + 3) - r(k)
+
+    See Also
+    ========
+
+    sympy.series.formal.exp_re
+    """
+    RE = S.Zero
+
+    g = DE.atoms(Function).pop()
+    x = g.atoms(Symbol).pop()
+
+    mini = None
+    for t in Add.make_args(DE.expand()):
+        coeff, d = t.as_independent(g)
+        c, v = coeff.as_independent(x)
+        l = v.as_coeff_exponent(x)[1]
+        if isinstance(d, Derivative):
+            j = d.derivative_count
+        else:
+            j = 0
+        RE += c * rf(k + 1 - l, j) * r(k + j - l)
+        if mini is None or j - l < mini:
+            mini = j - l
+
+    RE = RE.subs(k, k - mini)
+
+    m = Wild('m')
+    return RE.collect(r(k + m))
+
+
+def _transformation_a(f, x, P, Q, k, m, shift):
+    f *= x**(-shift)
+    P = P.subs(k, k + shift)
+    Q = Q.subs(k, k + shift)
+    return f, P, Q, m
+
+
+def _transformation_c(f, x, P, Q, k, m, scale):
+    f = f.subs(x, x**scale)
+    P = P.subs(k, k / scale)
+    Q = Q.subs(k, k / scale)
+    m *= scale
+    return f, P, Q, m
+
+
+def _transformation_e(f, x, P, Q, k, m):
+    f = f.diff(x)
+    P = P.subs(k, k + 1) * (k + m + 1)
+    Q = Q.subs(k, k + 1) * (k + 1)
+    return f, P, Q, m
+
+
+def _apply_shift(sol, shift):
+    return [(res, cond + shift) for res, cond in sol]
+
+
+def _apply_scale(sol, scale):
+    return [(res, cond / scale) for res, cond in sol]
+
+
+def _apply_integrate(sol, x, k):
+    return [(res / ((cond + 1)*(cond.as_coeff_Add()[1].coeff(k))), cond + 1)
+            for res, cond in sol]
+
+
+def _compute_formula(f, x, P, Q, k, m, k_max):
+    """Computes the formula for f."""
+    from sympy.polys import roots
+
+    sol = []
+    for i in range(k_max + 1, k_max + m + 1):
+        if (i < 0) == True:
+            continue
+        r = f.diff(x, i).limit(x, 0) / factorial(i)
+        if r.is_zero:
+            continue
+
+        kterm = m*k + i
+        res = r
+
+        p = P.subs(k, kterm)
+        q = Q.subs(k, kterm)
+        c1 = p.subs(k, 1/k).leadterm(k)[0]
+        c2 = q.subs(k, 1/k).leadterm(k)[0]
+        res *= (-c1 / c2)**k
+
+        res *= Mul(*[rf(-r, k)**mul for r, mul in roots(p, k).items()])
+        res /= Mul(*[rf(-r, k)**mul for r, mul in roots(q, k).items()])
+
+        sol.append((res, kterm))
+
+    return sol
+
+
+def _rsolve_hypergeometric(f, x, P, Q, k, m):
+    """
+    Recursive wrapper to rsolve_hypergeometric.
+
+    Explanation
+    ===========
+
+    Returns a Tuple of (formula, series independent terms,
+    maximum power of x in independent terms) if successful
+    otherwise ``None``.
+
+    See :func:`rsolve_hypergeometric` for details.
+    """
+    from sympy.polys import lcm, roots
+    from sympy.integrals import integrate
+
+    # transformation - c
+    proots, qroots = roots(P, k), roots(Q, k)
+    all_roots = dict(proots)
+    all_roots.update(qroots)
+    scale = lcm([r.as_numer_denom()[1] for r, t in all_roots.items()
+                 if r.is_rational])
+    f, P, Q, m = _transformation_c(f, x, P, Q, k, m, scale)
+
+    # transformation - a
+    qroots = roots(Q, k)
+    if qroots:
+        k_min = Min(*qroots.keys())
+    else:
+        k_min = S.Zero
+    shift = k_min + m
+    f, P, Q, m = _transformation_a(f, x, P, Q, k, m, shift)
+
+    l = (x*f).limit(x, 0)
+    if not isinstance(l, Limit) and l != 0:  # Ideally should only be l != 0
+        return None
+
+    qroots = roots(Q, k)
+    if qroots:
+        k_max = Max(*qroots.keys())
+    else:
+        k_max = S.Zero
+
+    ind, mp = S.Zero, -oo
+    for i in range(k_max + m + 1):
+        r = f.diff(x, i).limit(x, 0) / factorial(i)
+        if r.is_finite is False:
+            old_f = f
+            f, P, Q, m = _transformation_a(f, x, P, Q, k, m, i)
+            f, P, Q, m = _transformation_e(f, x, P, Q, k, m)
+            sol, ind, mp = _rsolve_hypergeometric(f, x, P, Q, k, m)
+            sol = _apply_integrate(sol, x, k)
+            sol = _apply_shift(sol, i)
+            ind = integrate(ind, x)
+            ind += (old_f - ind).limit(x, 0)  # constant of integration
+            mp += 1
+            return sol, ind, mp
+        elif r:
+            ind += r*x**(i + shift)
+            pow_x = Rational((i + shift), scale)
+            if pow_x > mp:
+                mp = pow_x  # maximum power of x
+    ind = ind.subs(x, x**(1/scale))
+
+    sol = _compute_formula(f, x, P, Q, k, m, k_max)
+    sol = _apply_shift(sol, shift)
+    sol = _apply_scale(sol, scale)
+
+    return sol, ind, mp
+
+
+def rsolve_hypergeometric(f, x, P, Q, k, m):
+    """
+    Solves RE of hypergeometric type.
+
+    Explanation
+    ===========
+
+    Attempts to solve RE of the form
+
+    Q(k)*a(k + m) - P(k)*a(k)
+
+    Transformations that preserve Hypergeometric type:
+
+        a. x**n*f(x): b(k + m) = R(k - n)*b(k)
+        b. f(A*x): b(k + m) = A**m*R(k)*b(k)
+        c. f(x**n): b(k + n*m) = R(k/n)*b(k)
+        d. f(x**(1/m)): b(k + 1) = R(k*m)*b(k)
+        e. f'(x): b(k + m) = ((k + m + 1)/(k + 1))*R(k + 1)*b(k)
+
+    Some of these transformations have been used to solve the RE.
+
+    Returns
+    =======
+
+    formula : Expr
+    ind : Expr
+        Independent terms.
+    order : int
+
+    Examples
+    ========
+
+    >>> from sympy import exp, ln, S
+    >>> from sympy.series.formal import rsolve_hypergeometric as rh
+    >>> from sympy.abc import x, k
+
+    >>> rh(exp(x), x, -S.One, (k + 1), k, 1)
+    (Piecewise((1/factorial(k), Eq(Mod(k, 1), 0)), (0, True)), 1, 1)
+
+    >>> rh(ln(1 + x), x, k**2, k*(k + 1), k, 1)
+    (Piecewise(((-1)**(k - 1)*factorial(k - 1)/RisingFactorial(2, k - 1),
+     Eq(Mod(k, 1), 0)), (0, True)), x, 2)
+
+    References
+    ==========
+
+    .. [1] Formal Power Series - Dominik Gruntz, Wolfram Koepf
+    .. [2] Power Series in Computer Algebra - Wolfram Koepf
+    """
+    result = _rsolve_hypergeometric(f, x, P, Q, k, m)
+
+    if result is None:
+        return None
+
+    sol_list, ind, mp = result
+
+    sol_dict = defaultdict(lambda: S.Zero)
+    for res, cond in sol_list:
+        j, mk = cond.as_coeff_Add()
+        c = mk.coeff(k)
+
+        if j.is_integer is False:
+            res *= x**frac(j)
+            j = floor(j)
+
+        res = res.subs(k, (k - j) / c)
+        cond = Eq(k % c, j % c)
+        sol_dict[cond] += res  # Group together formula for same conditions
+
+    sol = [(res, cond) for cond, res in sol_dict.items()]
+    sol.append((S.Zero, True))
+    sol = Piecewise(*sol)
+
+    if mp is -oo:
+        s = S.Zero
+    elif mp.is_integer is False:
+        s = ceiling(mp)
+    else:
+        s = mp + 1
+
+    #  save all the terms of
+    #  form 1/x**k in ind
+    if s < 0:
+        ind += sum(sequence(sol * x**k, (k, s, -1)))
+        s = S.Zero
+
+    return (sol, ind, s)
+
+
+def _solve_hyper_RE(f, x, RE, g, k):
+    """See docstring of :func:`rsolve_hypergeometric` for details."""
+    terms = Add.make_args(RE)
+
+    if len(terms) == 2:
+        gs = list(RE.atoms(Function))
+        P, Q = map(RE.coeff, gs)
+        m = gs[1].args[0] - gs[0].args[0]
+        if m < 0:
+            P, Q = Q, P
+            m = abs(m)
+        return rsolve_hypergeometric(f, x, P, Q, k, m)
+
+
+def _solve_explike_DE(f, x, DE, g, k):
+    """Solves DE with constant coefficients."""
+    from sympy.solvers import rsolve
+
+    for t in Add.make_args(DE):
+        coeff, d = t.as_independent(g)
+        if coeff.free_symbols:
+            return
+
+    RE = exp_re(DE, g, k)
+
+    init = {}
+    for i in range(len(Add.make_args(RE))):
+        if i:
+            f = f.diff(x)
+        init[g(k).subs(k, i)] = f.limit(x, 0)
+
+    sol = rsolve(RE, g(k), init)
+
+    if sol:
+        return (sol / factorial(k), S.Zero, S.Zero)
+
+
+def _solve_simple(f, x, DE, g, k):
+    """Converts DE into RE and solves using :func:`rsolve`."""
+    from sympy.solvers import rsolve
+
+    RE = hyper_re(DE, g, k)
+
+    init = {}
+    for i in range(len(Add.make_args(RE))):
+        if i:
+            f = f.diff(x)
+        init[g(k).subs(k, i)] = f.limit(x, 0) / factorial(i)
+
+    sol = rsolve(RE, g(k), init)
+
+    if sol:
+        return (sol, S.Zero, S.Zero)
+
+
+def _transform_explike_DE(DE, g, x, order, syms):
+    """Converts DE with free parameters into DE with constant coefficients."""
+    from sympy.solvers.solveset import linsolve
+
+    eq = []
+    highest_coeff = DE.coeff(Derivative(g(x), x, order))
+    for i in range(order):
+        coeff = DE.coeff(Derivative(g(x), x, i))
+        coeff = (coeff / highest_coeff).expand().collect(x)
+        eq.extend(Add.make_args(coeff))
+    temp = []
+    for e in eq:
+        if e.has(x):
+            break
+        elif e.has(Symbol):
+            temp.append(e)
+    else:
+        eq = temp
+    if eq:
+        sol = dict(zip(syms, (i for s in linsolve(eq, list(syms)) for i in s)))
+        if sol:
+            DE = DE.subs(sol)
+            DE = DE.factor().as_coeff_mul(Derivative)[1][0]
+            DE = DE.collect(Derivative(g(x)))
+    return DE
+
+
+def _transform_DE_RE(DE, g, k, order, syms):
+    """Converts DE with free parameters into RE of hypergeometric type."""
+    from sympy.solvers.solveset import linsolve
+
+    RE = hyper_re(DE, g, k)
+
+    eq = [RE.coeff(g(k + i)) for i in range(1, order)]
+    sol = dict(zip(syms, (i for s in linsolve(eq, list(syms)) for i in s)))
+    if sol:
+        m = Wild('m')
+        RE = RE.subs(sol)
+        RE = RE.factor().as_numer_denom()[0].collect(g(k + m))
+        RE = RE.as_coeff_mul(g)[1][0]
+        for i in range(order):  # smallest order should be g(k)
+            if RE.coeff(g(k + i)) and i:
+                RE = RE.subs(k, k - i)
+                break
+    return RE
+
+
+def solve_de(f, x, DE, order, g, k):
+    """
+    Solves the DE.
+
+    Explanation
+    ===========
+
+    Tries to solve DE by either converting into a RE containing two terms or
+    converting into a DE having constant coefficients.
+
+    Returns
+    =======
+
+    formula : Expr
+    ind : Expr
+        Independent terms.
+    order : int
+
+    Examples
+    ========
+
+    >>> from sympy import Derivative as D, Function
+    >>> from sympy import exp, ln
+    >>> from sympy.series.formal import solve_de
+    >>> from sympy.abc import x, k
+    >>> f = Function('f')
+
+    >>> solve_de(exp(x), x, D(f(x), x) - f(x), 1, f, k)
+    (Piecewise((1/factorial(k), Eq(Mod(k, 1), 0)), (0, True)), 1, 1)
+
+    >>> solve_de(ln(1 + x), x, (x + 1)*D(f(x), x, 2) + D(f(x)), 2, f, k)
+    (Piecewise(((-1)**(k - 1)*factorial(k - 1)/RisingFactorial(2, k - 1),
+     Eq(Mod(k, 1), 0)), (0, True)), x, 2)
+    """
+    sol = None
+    syms = DE.free_symbols.difference({g, x})
+
+    if syms:
+        RE = _transform_DE_RE(DE, g, k, order, syms)
+    else:
+        RE = hyper_re(DE, g, k)
+    if not RE.free_symbols.difference({k}):
+        sol = _solve_hyper_RE(f, x, RE, g, k)
+
+    if sol:
+        return sol
+
+    if syms:
+        DE = _transform_explike_DE(DE, g, x, order, syms)
+    if not DE.free_symbols.difference({x}):
+        sol = _solve_explike_DE(f, x, DE, g, k)
+
+    if sol:
+        return sol
+
+
+def hyper_algorithm(f, x, k, order=4):
+    """
+    Hypergeometric algorithm for computing Formal Power Series.
+
+    Explanation
+    ===========
+
+    Steps:
+        * Generates DE
+        * Convert the DE into RE
+        * Solves the RE
+
+    Examples
+    ========
+
+    >>> from sympy import exp, ln
+    >>> from sympy.series.formal import hyper_algorithm
+
+    >>> from sympy.abc import x, k
+
+    >>> hyper_algorithm(exp(x), x, k)
+    (Piecewise((1/factorial(k), Eq(Mod(k, 1), 0)), (0, True)), 1, 1)
+
+    >>> hyper_algorithm(ln(1 + x), x, k)
+    (Piecewise(((-1)**(k - 1)*factorial(k - 1)/RisingFactorial(2, k - 1),
+     Eq(Mod(k, 1), 0)), (0, True)), x, 2)
+
+    See Also
+    ========
+
+    sympy.series.formal.simpleDE
+    sympy.series.formal.solve_de
+    """
+    g = Function('g')
+
+    des = []  # list of DE's
+    sol = None
+    for DE, i in simpleDE(f, x, g, order):
+        if DE is not None:
+            sol = solve_de(f, x, DE, i, g, k)
+        if sol:
+            return sol
+        if not DE.free_symbols.difference({x}):
+            des.append(DE)
+
+    # If nothing works
+    # Try plain rsolve
+    for DE in des:
+        sol = _solve_simple(f, x, DE, g, k)
+        if sol:
+            return sol
+
+
+def _compute_fps(f, x, x0, dir, hyper, order, rational, full):
+    """Recursive wrapper to compute fps.
+
+    See :func:`compute_fps` for details.
+    """
+    if x0 in [S.Infinity, S.NegativeInfinity]:
+        dir = S.One if x0 is S.Infinity else -S.One
+        temp = f.subs(x, 1/x)
+        result = _compute_fps(temp, x, 0, dir, hyper, order, rational, full)
+        if result is None:
+            return None
+        return (result[0], result[1].subs(x, 1/x), result[2].subs(x, 1/x))
+    elif x0 or dir == -S.One:
+        if dir == -S.One:
+            rep = -x + x0
+            rep2 = -x
+            rep2b = x0
+        else:
+            rep = x + x0
+            rep2 = x
+            rep2b = -x0
+        temp = f.subs(x, rep)
+        result = _compute_fps(temp, x, 0, S.One, hyper, order, rational, full)
+        if result is None:
+            return None
+        return (result[0], result[1].subs(x, rep2 + rep2b),
+                result[2].subs(x, rep2 + rep2b))
+
+    if f.is_polynomial(x):
+        k = Dummy('k')
+        ak = sequence(Coeff(f, x, k), (k, 1, oo))
+        xk = sequence(x**k, (k, 0, oo))
+        ind = f.coeff(x, 0)
+        return ak, xk, ind
+
+    #  Break instances of Add
+    #  this allows application of different
+    #  algorithms on different terms increasing the
+    #  range of admissible functions.
+    if isinstance(f, Add):
+        result = False
+        ak = sequence(S.Zero, (0, oo))
+        ind, xk = S.Zero, None
+        for t in Add.make_args(f):
+            res = _compute_fps(t, x, 0, S.One, hyper, order, rational, full)
+            if res:
+                if not result:
+                    result = True
+                    xk = res[1]
+                if res[0].start > ak.start:
+                    seq = ak
+                    s, f = ak.start, res[0].start
+                else:
+                    seq = res[0]
+                    s, f = res[0].start, ak.start
+                save = Add(*[z[0]*z[1] for z in zip(seq[0:(f - s)], xk[s:f])])
+                ak += res[0]
+                ind += res[2] + save
+            else:
+                ind += t
+        if result:
+            return ak, xk, ind
+        return None
+
+    # The symbolic term - symb, if present, is being separated from the function
+    # Otherwise symb is being set to S.One
+    syms = f.free_symbols.difference({x})
+    (f, symb) = expand(f).as_independent(*syms)
+
+    result = None
+
+    # from here on it's x0=0 and dir=1 handling
+    k = Dummy('k')
+    if rational:
+        result = rational_algorithm(f, x, k, order, full)
+
+    if result is None and hyper:
+        result = hyper_algorithm(f, x, k, order)
+
+    if result is None:
+        return None
+
+    from sympy.simplify.powsimp import powsimp
+    if symb.is_zero:
+        symb = S.One
+    else:
+        symb = powsimp(symb)
+    ak = sequence(result[0], (k, result[2], oo))
+    xk_formula = powsimp(x**k * symb)
+    xk = sequence(xk_formula, (k, 0, oo))
+    ind = powsimp(result[1] * symb)
+
+    return ak, xk, ind
+
+
+def compute_fps(f, x, x0=0, dir=1, hyper=True, order=4, rational=True,
+                full=False):
+    """
+    Computes the formula for Formal Power Series of a function.
+
+    Explanation
+    ===========
+
+    Tries to compute the formula by applying the following techniques
+    (in order):
+
+    * rational_algorithm
+    * Hypergeometric algorithm
+
+    Parameters
+    ==========
+
+    x : Symbol
+    x0 : number, optional
+        Point to perform series expansion about. Default is 0.
+    dir : {1, -1, '+', '-'}, optional
+        If dir is 1 or '+' the series is calculated from the right and
+        for -1 or '-' the series is calculated from the left. For smooth
+        functions this flag will not alter the results. Default is 1.
+    hyper : {True, False}, optional
+        Set hyper to False to skip the hypergeometric algorithm.
+        By default it is set to False.
+    order : int, optional
+        Order of the derivative of ``f``, Default is 4.
+    rational : {True, False}, optional
+        Set rational to False to skip rational algorithm. By default it is set
+        to True.
+    full : {True, False}, optional
+        Set full to True to increase the range of rational algorithm.
+        See :func:`rational_algorithm` for details. By default it is set to
+        False.
+
+    Returns
+    =======
+
+    ak : sequence
+        Sequence of coefficients.
+    xk : sequence
+        Sequence of powers of x.
+    ind : Expr
+        Independent terms.
+    mul : Pow
+        Common terms.
+
+    See Also
+    ========
+
+    sympy.series.formal.rational_algorithm
+    sympy.series.formal.hyper_algorithm
+    """
+    f = sympify(f)
+    x = sympify(x)
+
+    if not f.has(x):
+        return None
+
+    x0 = sympify(x0)
+
+    if dir == '+':
+        dir = S.One
+    elif dir == '-':
+        dir = -S.One
+    elif dir not in [S.One, -S.One]:
+        raise ValueError("Dir must be '+' or '-'")
+    else:
+        dir = sympify(dir)
+
+    return _compute_fps(f, x, x0, dir, hyper, order, rational, full)
+
+
+class Coeff(Function):
+    """
+    Coeff(p, x, n) represents the nth coefficient of the polynomial p in x
+    """
+    @classmethod
+    def eval(cls, p, x, n):
+        if p.is_polynomial(x) and n.is_integer:
+            return p.coeff(x, n)
+
+
+class FormalPowerSeries(SeriesBase):
+    """
+    Represents Formal Power Series of a function.
+
+    Explanation
+    ===========
+
+    No computation is performed. This class should only to be used to represent
+    a series. No checks are performed.
+
+    For computing a series use :func:`fps`.
+
+    See Also
+    ========
+
+    sympy.series.formal.fps
+    """
+    def __new__(cls, *args):
+        args = map(sympify, args)
+        return Expr.__new__(cls, *args)
+
+    def __init__(self, *args):
+        ak = args[4][0]
+        k = ak.variables[0]
+        self.ak_seq = sequence(ak.formula, (k, 1, oo))
+        self.fact_seq = sequence(factorial(k), (k, 1, oo))
+        self.bell_coeff_seq = self.ak_seq * self.fact_seq
+        self.sign_seq = sequence((-1, 1), (k, 1, oo))
+
+    @property
+    def function(self):
+        return self.args[0]
+
+    @property
+    def x(self):
+        return self.args[1]
+
+    @property
+    def x0(self):
+        return self.args[2]
+
+    @property
+    def dir(self):
+        return self.args[3]
+
+    @property
+    def ak(self):
+        return self.args[4][0]
+
+    @property
+    def xk(self):
+        return self.args[4][1]
+
+    @property
+    def ind(self):
+        return self.args[4][2]
+
+    @property
+    def interval(self):
+        return Interval(0, oo)
+
+    @property
+    def start(self):
+        return self.interval.inf
+
+    @property
+    def stop(self):
+        return self.interval.sup
+
+    @property
+    def length(self):
+        return oo
+
+    @property
+    def infinite(self):
+        """Returns an infinite representation of the series"""
+        from sympy.concrete import Sum
+        ak, xk = self.ak, self.xk
+        k = ak.variables[0]
+        inf_sum = Sum(ak.formula * xk.formula, (k, ak.start, ak.stop))
+
+        return self.ind + inf_sum
+
+    def _get_pow_x(self, term):
+        """Returns the power of x in a term."""
+        xterm, pow_x = term.as_independent(self.x)[1].as_base_exp()
+        if not xterm.has(self.x):
+            return S.Zero
+        return pow_x
+
+    def polynomial(self, n=6):
+        """
+        Truncated series as polynomial.
+
+        Explanation
+        ===========
+
+        Returns series expansion of ``f`` upto order ``O(x**n)``
+        as a polynomial(without ``O`` term).
+        """
+        terms = []
+        sym = self.free_symbols
+        for i, t in enumerate(self):
+            xp = self._get_pow_x(t)
+            if xp.has(*sym):
+                xp = xp.as_coeff_add(*sym)[0]
+            if xp >= n:
+                break
+            elif xp.is_integer is True and i == n + 1:
+                break
+            elif t is not S.Zero:
+                terms.append(t)
+
+        return Add(*terms)
+
+    def truncate(self, n=6):
+        """
+        Truncated series.
+
+        Explanation
+        ===========
+
+        Returns truncated series expansion of f upto
+        order ``O(x**n)``.
+
+        If n is ``None``, returns an infinite iterator.
+        """
+        if n is None:
+            return iter(self)
+
+        x, x0 = self.x, self.x0
+        pt_xk = self.xk.coeff(n)
+        if x0 is S.NegativeInfinity:
+            x0 = S.Infinity
+
+        return self.polynomial(n) + Order(pt_xk, (x, x0))
+
+    def zero_coeff(self):
+        return self._eval_term(0)
+
+    def _eval_term(self, pt):
+        try:
+            pt_xk = self.xk.coeff(pt)
+            pt_ak = self.ak.coeff(pt).simplify()  # Simplify the coefficients
+        except IndexError:
+            term = S.Zero
+        else:
+            term = (pt_ak * pt_xk)
+
+        if self.ind:
+            ind = S.Zero
+            sym = self.free_symbols
+            for t in Add.make_args(self.ind):
+                pow_x = self._get_pow_x(t)
+                if pow_x.has(*sym):
+                    pow_x = pow_x.as_coeff_add(*sym)[0]
+                if pt == 0 and pow_x < 1:
+                    ind += t
+                elif pow_x >= pt and pow_x < pt + 1:
+                    ind += t
+            term += ind
+
+        return term.collect(self.x)
+
+    def _eval_subs(self, old, new):
+        x = self.x
+        if old.has(x):
+            return self
+
+    def _eval_as_leading_term(self, x, logx, cdir):
+        for t in self:
+            if t is not S.Zero:
+                return t
+
+    def _eval_derivative(self, x):
+        f = self.function.diff(x)
+        ind = self.ind.diff(x)
+
+        pow_xk = self._get_pow_x(self.xk.formula)
+        ak = self.ak
+        k = ak.variables[0]
+        if ak.formula.has(x):
+            form = []
+            for e, c in ak.formula.args:
+                temp = S.Zero
+                for t in Add.make_args(e):
+                    pow_x = self._get_pow_x(t)
+                    temp += t * (pow_xk + pow_x)
+                form.append((temp, c))
+            form = Piecewise(*form)
+            ak = sequence(form.subs(k, k + 1), (k, ak.start - 1, ak.stop))
+        else:
+            ak = sequence((ak.formula * pow_xk).subs(k, k + 1),
+                          (k, ak.start - 1, ak.stop))
+
+        return self.func(f, self.x, self.x0, self.dir, (ak, self.xk, ind))
+
+    def integrate(self, x=None, **kwargs):
+        """
+        Integrate Formal Power Series.
+
+        Examples
+        ========
+
+        >>> from sympy import fps, sin, integrate
+        >>> from sympy.abc import x
+        >>> f = fps(sin(x))
+        >>> f.integrate(x).truncate()
+        -1 + x**2/2 - x**4/24 + O(x**6)
+        >>> integrate(f, (x, 0, 1))
+        1 - cos(1)
+        """
+        from sympy.integrals import integrate
+
+        if x is None:
+            x = self.x
+        elif iterable(x):
+            return integrate(self.function, x)
+
+        f = integrate(self.function, x)
+        ind = integrate(self.ind, x)
+        ind += (f - ind).limit(x, 0)  # constant of integration
+
+        pow_xk = self._get_pow_x(self.xk.formula)
+        ak = self.ak
+        k = ak.variables[0]
+        if ak.formula.has(x):
+            form = []
+            for e, c in ak.formula.args:
+                temp = S.Zero
+                for t in Add.make_args(e):
+                    pow_x = self._get_pow_x(t)
+                    temp += t / (pow_xk + pow_x + 1)
+                form.append((temp, c))
+            form = Piecewise(*form)
+            ak = sequence(form.subs(k, k - 1), (k, ak.start + 1, ak.stop))
+        else:
+            ak = sequence((ak.formula / (pow_xk + 1)).subs(k, k - 1),
+                          (k, ak.start + 1, ak.stop))
+
+        return self.func(f, self.x, self.x0, self.dir, (ak, self.xk, ind))
+
+    def product(self, other, x=None, n=6):
+        """
+        Multiplies two Formal Power Series, using discrete convolution and
+        return the truncated terms upto specified order.
+
+        Parameters
+        ==========
+
+        n : Number, optional
+            Specifies the order of the term up to which the polynomial should
+            be truncated.
+
+        Examples
+        ========
+
+        >>> from sympy import fps, sin, exp
+        >>> from sympy.abc import x
+        >>> f1 = fps(sin(x))
+        >>> f2 = fps(exp(x))
+
+        >>> f1.product(f2, x).truncate(4)
+        x + x**2 + x**3/3 + O(x**4)
+
+        See Also
+        ========
+
+        sympy.discrete.convolutions
+        sympy.series.formal.FormalPowerSeriesProduct
+
+        """
+
+        if n is None:
+            return iter(self)
+
+        other = sympify(other)
+
+        if not isinstance(other, FormalPowerSeries):
+            raise ValueError("Both series should be an instance of FormalPowerSeries"
+                             " class.")
+
+        if self.dir != other.dir:
+            raise ValueError("Both series should be calculated from the"
+                             " same direction.")
+        elif self.x0 != other.x0:
+            raise ValueError("Both series should be calculated about the"
+                             " same point.")
+
+        elif self.x != other.x:
+            raise ValueError("Both series should have the same symbol.")
+
+        return FormalPowerSeriesProduct(self, other)
+
+    def coeff_bell(self, n):
+        r"""
+        self.coeff_bell(n) returns a sequence of Bell polynomials of the second kind.
+        Note that ``n`` should be a integer.
+
+        The second kind of Bell polynomials (are sometimes called "partial" Bell
+        polynomials or incomplete Bell polynomials) are defined as
+
+        .. math::
+            B_{n,k}(x_1, x_2,\dotsc x_{n-k+1}) =
+                \sum_{j_1+j_2+j_2+\dotsb=k \atop j_1+2j_2+3j_2+\dotsb=n}
+                \frac{n!}{j_1!j_2!\dotsb j_{n-k+1}!}
+                \left(\frac{x_1}{1!} \right)^{j_1}
+                \left(\frac{x_2}{2!} \right)^{j_2} \dotsb
+                \left(\frac{x_{n-k+1}}{(n-k+1)!} \right) ^{j_{n-k+1}}.
+
+        * ``bell(n, k, (x1, x2, ...))`` gives Bell polynomials of the second kind,
+          `B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})`.
+
+        See Also
+        ========
+
+        sympy.functions.combinatorial.numbers.bell
+
+        """
+
+        inner_coeffs = [bell(n, j, tuple(self.bell_coeff_seq[:n-j+1])) for j in range(1, n+1)]
+
+        k = Dummy('k')
+        return sequence(tuple(inner_coeffs), (k, 1, oo))
+
+    def compose(self, other, x=None, n=6):
+        r"""
+        Returns the truncated terms of the formal power series of the composed function,
+        up to specified ``n``.
+
+        Explanation
+        ===========
+
+        If ``f`` and ``g`` are two formal power series of two different functions,
+        then the coefficient sequence ``ak`` of the composed formal power series `fp`
+        will be as follows.
+
+        .. math::
+            \sum\limits_{k=0}^{n} b_k B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})
+
+        Parameters
+        ==========
+
+        n : Number, optional
+            Specifies the order of the term up to which the polynomial should
+            be truncated.
+
+        Examples
+        ========
+
+        >>> from sympy import fps, sin, exp
+        >>> from sympy.abc import x
+        >>> f1 = fps(exp(x))
+        >>> f2 = fps(sin(x))
+
+        >>> f1.compose(f2, x).truncate()
+        1 + x + x**2/2 - x**4/8 - x**5/15 + O(x**6)
+
+        >>> f1.compose(f2, x).truncate(8)
+        1 + x + x**2/2 - x**4/8 - x**5/15 - x**6/240 + x**7/90 + O(x**8)
+
+        See Also
+        ========
+
+        sympy.functions.combinatorial.numbers.bell
+        sympy.series.formal.FormalPowerSeriesCompose
+
+        References
+        ==========
+
+        .. [1] Comtet, Louis: Advanced combinatorics; the art of finite and infinite expansions. Reidel, 1974.
+
+        """
+
+        if n is None:
+            return iter(self)
+
+        other = sympify(other)
+
+        if not isinstance(other, FormalPowerSeries):
+            raise ValueError("Both series should be an instance of FormalPowerSeries"
+                             " class.")
+
+        if self.dir != other.dir:
+            raise ValueError("Both series should be calculated from the"
+                             " same direction.")
+        elif self.x0 != other.x0:
+            raise ValueError("Both series should be calculated about the"
+                             " same point.")
+
+        elif self.x != other.x:
+            raise ValueError("Both series should have the same symbol.")
+
+        if other._eval_term(0).as_coeff_mul(other.x)[0] is not S.Zero:
+            raise ValueError("The formal power series of the inner function should not have any "
+                "constant coefficient term.")
+
+        return FormalPowerSeriesCompose(self, other)
+
+    def inverse(self, x=None, n=6):
+        r"""
+        Returns the truncated terms of the inverse of the formal power series,
+        up to specified ``n``.
+
+        Explanation
+        ===========
+
+        If ``f`` and ``g`` are two formal power series of two different functions,
+        then the coefficient sequence ``ak`` of the composed formal power series ``fp``
+        will be as follows.
+
+        .. math::
+            \sum\limits_{k=0}^{n} (-1)^{k} x_0^{-k-1} B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})
+
+        Parameters
+        ==========
+
+        n : Number, optional
+            Specifies the order of the term up to which the polynomial should
+            be truncated.
+
+        Examples
+        ========
+
+        >>> from sympy import fps, exp, cos
+        >>> from sympy.abc import x
+        >>> f1 = fps(exp(x))
+        >>> f2 = fps(cos(x))
+
+        >>> f1.inverse(x).truncate()
+        1 - x + x**2/2 - x**3/6 + x**4/24 - x**5/120 + O(x**6)
+
+        >>> f2.inverse(x).truncate(8)
+        1 + x**2/2 + 5*x**4/24 + 61*x**6/720 + O(x**8)
+
+        See Also
+        ========
+
+        sympy.functions.combinatorial.numbers.bell
+        sympy.series.formal.FormalPowerSeriesInverse
+
+        References
+        ==========
+
+        .. [1] Comtet, Louis: Advanced combinatorics; the art of finite and infinite expansions. Reidel, 1974.
+
+        """
+
+        if n is None:
+            return iter(self)
+
+        if self._eval_term(0).is_zero:
+            raise ValueError("Constant coefficient should exist for an inverse of a formal"
+                " power series to exist.")
+
+        return FormalPowerSeriesInverse(self)
+
+    def __add__(self, other):
+        other = sympify(other)
+
+        if isinstance(other, FormalPowerSeries):
+            if self.dir != other.dir:
+                raise ValueError("Both series should be calculated from the"
+                                 " same direction.")
+            elif self.x0 != other.x0:
+                raise ValueError("Both series should be calculated about the"
+                                 " same point.")
+
+            x, y = self.x, other.x
+            f = self.function + other.function.subs(y, x)
+
+            if self.x not in f.free_symbols:
+                return f
+
+            ak = self.ak + other.ak
+            if self.ak.start > other.ak.start:
+                seq = other.ak
+                s, e = other.ak.start, self.ak.start
+            else:
+                seq = self.ak
+                s, e = self.ak.start, other.ak.start
+            save = Add(*[z[0]*z[1] for z in zip(seq[0:(e - s)], self.xk[s:e])])
+            ind = self.ind + other.ind + save
+
+            return self.func(f, x, self.x0, self.dir, (ak, self.xk, ind))
+
+        elif not other.has(self.x):
+            f = self.function + other
+            ind = self.ind + other
+
+            return self.func(f, self.x, self.x0, self.dir,
+                             (self.ak, self.xk, ind))
+
+        return Add(self, other)
+
+    def __radd__(self, other):
+        return self.__add__(other)
+
+    def __neg__(self):
+        return self.func(-self.function, self.x, self.x0, self.dir,
+                         (-self.ak, self.xk, -self.ind))
+
+    def __sub__(self, other):
+        return self.__add__(-other)
+
+    def __rsub__(self, other):
+        return (-self).__add__(other)
+
+    def __mul__(self, other):
+        other = sympify(other)
+
+        if other.has(self.x):
+            return Mul(self, other)
+
+        f = self.function * other
+        ak = self.ak.coeff_mul(other)
+        ind = self.ind * other
+
+        return self.func(f, self.x, self.x0, self.dir, (ak, self.xk, ind))
+
+    def __rmul__(self, other):
+        return self.__mul__(other)
+
+
+class FiniteFormalPowerSeries(FormalPowerSeries):
+    """Base Class for Product, Compose and Inverse classes"""
+
+    def __init__(self, *args):
+        pass
+
+    @property
+    def ffps(self):
+        return self.args[0]
+
+    @property
+    def gfps(self):
+        return self.args[1]
+
+    @property
+    def f(self):
+        return self.ffps.function
+
+    @property
+    def g(self):
+        return self.gfps.function
+
+    @property
+    def infinite(self):
+        raise NotImplementedError("No infinite version for an object of"
+                     " FiniteFormalPowerSeries class.")
+
+    def _eval_terms(self, n):
+        raise NotImplementedError("(%s)._eval_terms()" % self)
+
+    def _eval_term(self, pt):
+        raise NotImplementedError("By the current logic, one can get terms"
+                                   "upto a certain order, instead of getting term by term.")
+
+    def polynomial(self, n):
+        return self._eval_terms(n)
+
+    def truncate(self, n=6):
+        ffps = self.ffps
+        pt_xk = ffps.xk.coeff(n)
+        x, x0 = ffps.x, ffps.x0
+
+        return self.polynomial(n) + Order(pt_xk, (x, x0))
+
+    def _eval_derivative(self, x):
+        raise NotImplementedError
+
+    def integrate(self, x):
+        raise NotImplementedError
+
+
+class FormalPowerSeriesProduct(FiniteFormalPowerSeries):
+    """Represents the product of two formal power series of two functions.
+
+    Explanation
+    ===========
+
+    No computation is performed. Terms are calculated using a term by term logic,
+    instead of a point by point logic.
+
+    There are two differences between a :obj:`FormalPowerSeries` object and a
+    :obj:`FormalPowerSeriesProduct` object. The first argument contains the two
+    functions involved in the product. Also, the coefficient sequence contains
+    both the coefficient sequence of the formal power series of the involved functions.
+
+    See Also
+    ========
+
+    sympy.series.formal.FormalPowerSeries
+    sympy.series.formal.FiniteFormalPowerSeries
+
+    """
+
+    def __init__(self, *args):
+        ffps, gfps = self.ffps, self.gfps
+
+        k = ffps.ak.variables[0]
+        self.coeff1 = sequence(ffps.ak.formula, (k, 0, oo))
+
+        k = gfps.ak.variables[0]
+        self.coeff2 = sequence(gfps.ak.formula, (k, 0, oo))
+
+    @property
+    def function(self):
+        """Function of the product of two formal power series."""
+        return self.f * self.g
+
+    def _eval_terms(self, n):
+        """
+        Returns the first ``n`` terms of the product formal power series.
+        Term by term logic is implemented here.
+
+        Examples
+        ========
+
+        >>> from sympy import fps, sin, exp
+        >>> from sympy.abc import x
+        >>> f1 = fps(sin(x))
+        >>> f2 = fps(exp(x))
+        >>> fprod = f1.product(f2, x)
+
+        >>> fprod._eval_terms(4)
+        x**3/3 + x**2 + x
+
+        See Also
+        ========
+
+        sympy.series.formal.FormalPowerSeries.product
+
+        """
+        coeff1, coeff2 = self.coeff1, self.coeff2
+
+        aks = convolution(coeff1[:n], coeff2[:n])
+
+        terms = []
+        for i in range(0, n):
+            terms.append(aks[i] * self.ffps.xk.coeff(i))
+
+        return Add(*terms)
+
+
+class FormalPowerSeriesCompose(FiniteFormalPowerSeries):
+    """
+    Represents the composed formal power series of two functions.
+
+    Explanation
+    ===========
+
+    No computation is performed. Terms are calculated using a term by term logic,
+    instead of a point by point logic.
+
+    There are two differences between a :obj:`FormalPowerSeries` object and a
+    :obj:`FormalPowerSeriesCompose` object. The first argument contains the outer
+    function and the inner function involved in the omposition. Also, the
+    coefficient sequence contains the generic sequence which is to be multiplied
+    by a custom ``bell_seq`` finite sequence. The finite terms will then be added up to
+    get the final terms.
+
+    See Also
+    ========
+
+    sympy.series.formal.FormalPowerSeries
+    sympy.series.formal.FiniteFormalPowerSeries
+
+    """
+
+    @property
+    def function(self):
+        """Function for the composed formal power series."""
+        f, g, x = self.f, self.g, self.ffps.x
+        return f.subs(x, g)
+
+    def _eval_terms(self, n):
+        """
+        Returns the first `n` terms of the composed formal power series.
+        Term by term logic is implemented here.
+
+        Explanation
+        ===========
+
+        The coefficient sequence of the :obj:`FormalPowerSeriesCompose` object is the generic sequence.
+        It is multiplied by ``bell_seq`` to get a sequence, whose terms are added up to get
+        the final terms for the polynomial.
+
+        Examples
+        ========
+
+        >>> from sympy import fps, sin, exp
+        >>> from sympy.abc import x
+        >>> f1 = fps(exp(x))
+        >>> f2 = fps(sin(x))
+        >>> fcomp = f1.compose(f2, x)
+
+        >>> fcomp._eval_terms(6)
+        -x**5/15 - x**4/8 + x**2/2 + x + 1
+
+        >>> fcomp._eval_terms(8)
+        x**7/90 - x**6/240 - x**5/15 - x**4/8 + x**2/2 + x + 1
+
+        See Also
+        ========
+
+        sympy.series.formal.FormalPowerSeries.compose
+        sympy.series.formal.FormalPowerSeries.coeff_bell
+
+        """
+
+        ffps, gfps = self.ffps, self.gfps
+        terms = [ffps.zero_coeff()]
+
+        for i in range(1, n):
+            bell_seq = gfps.coeff_bell(i)
+            seq = (ffps.bell_coeff_seq * bell_seq)
+            terms.append(Add(*(seq[:i])) / ffps.fact_seq[i-1] * ffps.xk.coeff(i))
+
+        return Add(*terms)
+
+
+class FormalPowerSeriesInverse(FiniteFormalPowerSeries):
+    """
+    Represents the Inverse of a formal power series.
+
+    Explanation
+    ===========
+
+    No computation is performed. Terms are calculated using a term by term logic,
+    instead of a point by point logic.
+
+    There is a single difference between a :obj:`FormalPowerSeries` object and a
+    :obj:`FormalPowerSeriesInverse` object. The coefficient sequence contains the
+    generic sequence which is to be multiplied by a custom ``bell_seq`` finite sequence.
+    The finite terms will then be added up to get the final terms.
+
+    See Also
+    ========
+
+    sympy.series.formal.FormalPowerSeries
+    sympy.series.formal.FiniteFormalPowerSeries
+
+    """
+    def __init__(self, *args):
+        ffps = self.ffps
+        k = ffps.xk.variables[0]
+
+        inv = ffps.zero_coeff()
+        inv_seq = sequence(inv ** (-(k + 1)), (k, 1, oo))
+        self.aux_seq = ffps.sign_seq * ffps.fact_seq * inv_seq
+
+    @property
+    def function(self):
+        """Function for the inverse of a formal power series."""
+        f = self.f
+        return 1 / f
+
+    @property
+    def g(self):
+        raise ValueError("Only one function is considered while performing"
+                        "inverse of a formal power series.")
+
+    @property
+    def gfps(self):
+        raise ValueError("Only one function is considered while performing"
+                        "inverse of a formal power series.")
+
+    def _eval_terms(self, n):
+        """
+        Returns the first ``n`` terms of the composed formal power series.
+        Term by term logic is implemented here.
+
+        Explanation
+        ===========
+
+        The coefficient sequence of the `FormalPowerSeriesInverse` object is the generic sequence.
+        It is multiplied by ``bell_seq`` to get a sequence, whose terms are added up to get
+        the final terms for the polynomial.
+
+        Examples
+        ========
+
+        >>> from sympy import fps, exp, cos
+        >>> from sympy.abc import x
+        >>> f1 = fps(exp(x))
+        >>> f2 = fps(cos(x))
+        >>> finv1, finv2 = f1.inverse(), f2.inverse()
+
+        >>> finv1._eval_terms(6)
+        -x**5/120 + x**4/24 - x**3/6 + x**2/2 - x + 1
+
+        >>> finv2._eval_terms(8)
+        61*x**6/720 + 5*x**4/24 + x**2/2 + 1
+
+        See Also
+        ========
+
+        sympy.series.formal.FormalPowerSeries.inverse
+        sympy.series.formal.FormalPowerSeries.coeff_bell
+
+        """
+        ffps = self.ffps
+        terms = [ffps.zero_coeff()]
+
+        for i in range(1, n):
+            bell_seq = ffps.coeff_bell(i)
+            seq = (self.aux_seq * bell_seq)
+            terms.append(Add(*(seq[:i])) / ffps.fact_seq[i-1] * ffps.xk.coeff(i))
+
+        return Add(*terms)
+
+
+def fps(f, x=None, x0=0, dir=1, hyper=True, order=4, rational=True, full=False):
+    """
+    Generates Formal Power Series of ``f``.
+
+    Explanation
+    ===========
+
+    Returns the formal series expansion of ``f`` around ``x = x0``
+    with respect to ``x`` in the form of a ``FormalPowerSeries`` object.
+
+    Formal Power Series is represented using an explicit formula
+    computed using different algorithms.
+
+    See :func:`compute_fps` for the more details regarding the computation
+    of formula.
+
+    Parameters
+    ==========
+
+    x : Symbol, optional
+        If x is None and ``f`` is univariate, the univariate symbols will be
+        supplied, otherwise an error will be raised.
+    x0 : number, optional
+        Point to perform series expansion about. Default is 0.
+    dir : {1, -1, '+', '-'}, optional
+        If dir is 1 or '+' the series is calculated from the right and
+        for -1 or '-' the series is calculated from the left. For smooth
+        functions this flag will not alter the results. Default is 1.
+    hyper : {True, False}, optional
+        Set hyper to False to skip the hypergeometric algorithm.
+        By default it is set to False.
+    order : int, optional
+        Order of the derivative of ``f``, Default is 4.
+    rational : {True, False}, optional
+        Set rational to False to skip rational algorithm. By default it is set
+        to True.
+    full : {True, False}, optional
+        Set full to True to increase the range of rational algorithm.
+        See :func:`rational_algorithm` for details. By default it is set to
+        False.
+
+    Examples
+    ========
+
+    >>> from sympy import fps, ln, atan, sin
+    >>> from sympy.abc import x, n
+
+    Rational Functions
+
+    >>> fps(ln(1 + x)).truncate()
+    x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6)
+
+    >>> fps(atan(x), full=True).truncate()
+    x - x**3/3 + x**5/5 + O(x**6)
+
+    Symbolic Functions
+
+    >>> fps(x**n*sin(x**2), x).truncate(8)
+    -x**(n + 6)/6 + x**(n + 2) + O(x**(n + 8))
+
+    See Also
+    ========
+
+    sympy.series.formal.FormalPowerSeries
+    sympy.series.formal.compute_fps
+    """
+    f = sympify(f)
+
+    if x is None:
+        free = f.free_symbols
+        if len(free) == 1:
+            x = free.pop()
+        elif not free:
+            return f
+        else:
+            raise NotImplementedError("multivariate formal power series")
+
+    result = compute_fps(f, x, x0, dir, hyper, order, rational, full)
+
+    if result is None:
+        return f
+
+    return FormalPowerSeries(f, x, x0, dir, result)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/fourier.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/fourier.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4ad43a75d0e1d24bfc591383f68965fd8b504c7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/fourier.py
@@ -0,0 +1,811 @@
+"""Fourier Series"""
+
+from sympy.core.numbers import (oo, pi)
+from sympy.core.symbol import Wild
+from sympy.core.expr import Expr
+from sympy.core.add import Add
+from sympy.core.containers import Tuple
+from sympy.core.singleton import S
+from sympy.core.symbol import Dummy, Symbol
+from sympy.core.sympify import sympify
+from sympy.functions.elementary.trigonometric import sin, cos, sinc
+from sympy.series.series_class import SeriesBase
+from sympy.series.sequences import SeqFormula
+from sympy.sets.sets import Interval
+from sympy.utilities.iterables import is_sequence
+
+
+__doctest_requires__ = {('fourier_series',): ['matplotlib']}
+
+
+def fourier_cos_seq(func, limits, n):
+    """Returns the cos sequence in a Fourier series"""
+    from sympy.integrals import integrate
+    x, L = limits[0], limits[2] - limits[1]
+    cos_term = cos(2*n*pi*x / L)
+    formula = 2 * cos_term * integrate(func * cos_term, limits) / L
+    a0 = formula.subs(n, S.Zero) / 2
+    return a0, SeqFormula(2 * cos_term * integrate(func * cos_term, limits)
+                          / L, (n, 1, oo))
+
+
+def fourier_sin_seq(func, limits, n):
+    """Returns the sin sequence in a Fourier series"""
+    from sympy.integrals import integrate
+    x, L = limits[0], limits[2] - limits[1]
+    sin_term = sin(2*n*pi*x / L)
+    return SeqFormula(2 * sin_term * integrate(func * sin_term, limits)
+                      / L, (n, 1, oo))
+
+
+def _process_limits(func, limits):
+    """
+    Limits should be of the form (x, start, stop).
+    x should be a symbol. Both start and stop should be bounded.
+
+    Explanation
+    ===========
+
+    * If x is not given, x is determined from func.
+    * If limits is None. Limit of the form (x, -pi, pi) is returned.
+
+    Examples
+    ========
+
+    >>> from sympy.series.fourier import _process_limits as pari
+    >>> from sympy.abc import x
+    >>> pari(x**2, (x, -2, 2))
+    (x, -2, 2)
+    >>> pari(x**2, (-2, 2))
+    (x, -2, 2)
+    >>> pari(x**2, None)
+    (x, -pi, pi)
+    """
+    def _find_x(func):
+        free = func.free_symbols
+        if len(free) == 1:
+            return free.pop()
+        elif not free:
+            return Dummy('k')
+        else:
+            raise ValueError(
+                " specify dummy variables for %s. If the function contains"
+                " more than one free symbol, a dummy variable should be"
+                " supplied explicitly e.g. FourierSeries(m*n**2, (n, -pi, pi))"
+                % func)
+
+    x, start, stop = None, None, None
+    if limits is None:
+        x, start, stop = _find_x(func), -pi, pi
+    if is_sequence(limits, Tuple):
+        if len(limits) == 3:
+            x, start, stop = limits
+        elif len(limits) == 2:
+            x = _find_x(func)
+            start, stop = limits
+
+    if not isinstance(x, Symbol) or start is None or stop is None:
+        raise ValueError('Invalid limits given: %s' % str(limits))
+
+    unbounded = [S.NegativeInfinity, S.Infinity]
+    if start in unbounded or stop in unbounded:
+        raise ValueError("Both the start and end value should be bounded")
+
+    return sympify((x, start, stop))
+
+
+def finite_check(f, x, L):
+
+    def check_fx(exprs, x):
+        return x not in exprs.free_symbols
+
+    def check_sincos(_expr, x, L):
+        if isinstance(_expr, (sin, cos)):
+            sincos_args = _expr.args[0]
+
+            if sincos_args.match(a*(pi/L)*x + b) is not None:
+                return True
+            else:
+                return False
+
+    from sympy.simplify.fu import TR2, TR1, sincos_to_sum
+    _expr = sincos_to_sum(TR2(TR1(f)))
+    add_coeff = _expr.as_coeff_add()
+
+    a = Wild('a', properties=[lambda k: k.is_Integer, lambda k: k != S.Zero, ])
+    b = Wild('b', properties=[lambda k: x not in k.free_symbols, ])
+
+    for s in add_coeff[1]:
+        mul_coeffs = s.as_coeff_mul()[1]
+        for t in mul_coeffs:
+            if not (check_fx(t, x) or check_sincos(t, x, L)):
+                return False, f
+
+    return True, _expr
+
+
+class FourierSeries(SeriesBase):
+    r"""Represents Fourier sine/cosine series.
+
+    Explanation
+    ===========
+
+    This class only represents a fourier series.
+    No computation is performed.
+
+    For how to compute Fourier series, see the :func:`fourier_series`
+    docstring.
+
+    See Also
+    ========
+
+    sympy.series.fourier.fourier_series
+    """
+    def __new__(cls, *args):
+        args = map(sympify, args)
+        return Expr.__new__(cls, *args)
+
+    @property
+    def function(self):
+        return self.args[0]
+
+    @property
+    def x(self):
+        return self.args[1][0]
+
+    @property
+    def period(self):
+        return (self.args[1][1], self.args[1][2])
+
+    @property
+    def a0(self):
+        return self.args[2][0]
+
+    @property
+    def an(self):
+        return self.args[2][1]
+
+    @property
+    def bn(self):
+        return self.args[2][2]
+
+    @property
+    def interval(self):
+        return Interval(0, oo)
+
+    @property
+    def start(self):
+        return self.interval.inf
+
+    @property
+    def stop(self):
+        return self.interval.sup
+
+    @property
+    def length(self):
+        return oo
+
+    @property
+    def L(self):
+        return abs(self.period[1] - self.period[0]) / 2
+
+    def _eval_subs(self, old, new):
+        x = self.x
+        if old.has(x):
+            return self
+
+    def truncate(self, n=3):
+        """
+        Return the first n nonzero terms of the series.
+
+        If ``n`` is None return an iterator.
+
+        Parameters
+        ==========
+
+        n : int or None
+            Amount of non-zero terms in approximation or None.
+
+        Returns
+        =======
+
+        Expr or iterator :
+            Approximation of function expanded into Fourier series.
+
+        Examples
+        ========
+
+        >>> from sympy import fourier_series, pi
+        >>> from sympy.abc import x
+        >>> s = fourier_series(x, (x, -pi, pi))
+        >>> s.truncate(4)
+        2*sin(x) - sin(2*x) + 2*sin(3*x)/3 - sin(4*x)/2
+
+        See Also
+        ========
+
+        sympy.series.fourier.FourierSeries.sigma_approximation
+        """
+        if n is None:
+            return iter(self)
+
+        terms = []
+        for t in self:
+            if len(terms) == n:
+                break
+            if t is not S.Zero:
+                terms.append(t)
+
+        return Add(*terms)
+
+    def sigma_approximation(self, n=3):
+        r"""
+        Return :math:`\sigma`-approximation of Fourier series with respect
+        to order n.
+
+        Explanation
+        ===========
+
+        Sigma approximation adjusts a Fourier summation to eliminate the Gibbs
+        phenomenon which would otherwise occur at discontinuities.
+        A sigma-approximated summation for a Fourier series of a T-periodical
+        function can be written as
+
+        .. math::
+            s(\theta) = \frac{1}{2} a_0 + \sum _{k=1}^{m-1}
+            \operatorname{sinc} \Bigl( \frac{k}{m} \Bigr) \cdot
+            \left[ a_k \cos \Bigl( \frac{2\pi k}{T} \theta \Bigr)
+            + b_k \sin \Bigl( \frac{2\pi k}{T} \theta \Bigr) \right],
+
+        where :math:`a_0, a_k, b_k, k=1,\ldots,{m-1}` are standard Fourier
+        series coefficients and
+        :math:`\operatorname{sinc} \Bigl( \frac{k}{m} \Bigr)` is a Lanczos
+        :math:`\sigma` factor (expressed in terms of normalized
+        :math:`\operatorname{sinc}` function).
+
+        Parameters
+        ==========
+
+        n : int
+            Highest order of the terms taken into account in approximation.
+
+        Returns
+        =======
+
+        Expr :
+            Sigma approximation of function expanded into Fourier series.
+
+        Examples
+        ========
+
+        >>> from sympy import fourier_series, pi
+        >>> from sympy.abc import x
+        >>> s = fourier_series(x, (x, -pi, pi))
+        >>> s.sigma_approximation(4)
+        2*sin(x)*sinc(pi/4) - 2*sin(2*x)/pi + 2*sin(3*x)*sinc(3*pi/4)/3
+
+        See Also
+        ========
+
+        sympy.series.fourier.FourierSeries.truncate
+
+        Notes
+        =====
+
+        The behaviour of
+        :meth:`~sympy.series.fourier.FourierSeries.sigma_approximation`
+        is different from :meth:`~sympy.series.fourier.FourierSeries.truncate`
+        - it takes all nonzero terms of degree smaller than n, rather than
+        first n nonzero ones.
+
+        References
+        ==========
+
+        .. [1] https://en.wikipedia.org/wiki/Gibbs_phenomenon
+        .. [2] https://en.wikipedia.org/wiki/Sigma_approximation
+        """
+        terms = [sinc(pi * i / n) * t for i, t in enumerate(self[:n])
+                 if t is not S.Zero]
+        return Add(*terms)
+
+    def shift(self, s):
+        """
+        Shift the function by a term independent of x.
+
+        Explanation
+        ===========
+
+        f(x) -> f(x) + s
+
+        This is fast, if Fourier series of f(x) is already
+        computed.
+
+        Examples
+        ========
+
+        >>> from sympy import fourier_series, pi
+        >>> from sympy.abc import x
+        >>> s = fourier_series(x**2, (x, -pi, pi))
+        >>> s.shift(1).truncate()
+        -4*cos(x) + cos(2*x) + 1 + pi**2/3
+        """
+        s, x = sympify(s), self.x
+
+        if x in s.free_symbols:
+            raise ValueError("'%s' should be independent of %s" % (s, x))
+
+        a0 = self.a0 + s
+        sfunc = self.function + s
+
+        return self.func(sfunc, self.args[1], (a0, self.an, self.bn))
+
+    def shiftx(self, s):
+        """
+        Shift x by a term independent of x.
+
+        Explanation
+        ===========
+
+        f(x) -> f(x + s)
+
+        This is fast, if Fourier series of f(x) is already
+        computed.
+
+        Examples
+        ========
+
+        >>> from sympy import fourier_series, pi
+        >>> from sympy.abc import x
+        >>> s = fourier_series(x**2, (x, -pi, pi))
+        >>> s.shiftx(1).truncate()
+        -4*cos(x + 1) + cos(2*x + 2) + pi**2/3
+        """
+        s, x = sympify(s), self.x
+
+        if x in s.free_symbols:
+            raise ValueError("'%s' should be independent of %s" % (s, x))
+
+        an = self.an.subs(x, x + s)
+        bn = self.bn.subs(x, x + s)
+        sfunc = self.function.subs(x, x + s)
+
+        return self.func(sfunc, self.args[1], (self.a0, an, bn))
+
+    def scale(self, s):
+        """
+        Scale the function by a term independent of x.
+
+        Explanation
+        ===========
+
+        f(x) -> s * f(x)
+
+        This is fast, if Fourier series of f(x) is already
+        computed.
+
+        Examples
+        ========
+
+        >>> from sympy import fourier_series, pi
+        >>> from sympy.abc import x
+        >>> s = fourier_series(x**2, (x, -pi, pi))
+        >>> s.scale(2).truncate()
+        -8*cos(x) + 2*cos(2*x) + 2*pi**2/3
+        """
+        s, x = sympify(s), self.x
+
+        if x in s.free_symbols:
+            raise ValueError("'%s' should be independent of %s" % (s, x))
+
+        an = self.an.coeff_mul(s)
+        bn = self.bn.coeff_mul(s)
+        a0 = self.a0 * s
+        sfunc = self.args[0] * s
+
+        return self.func(sfunc, self.args[1], (a0, an, bn))
+
+    def scalex(self, s):
+        """
+        Scale x by a term independent of x.
+
+        Explanation
+        ===========
+
+        f(x) -> f(s*x)
+
+        This is fast, if Fourier series of f(x) is already
+        computed.
+
+        Examples
+        ========
+
+        >>> from sympy import fourier_series, pi
+        >>> from sympy.abc import x
+        >>> s = fourier_series(x**2, (x, -pi, pi))
+        >>> s.scalex(2).truncate()
+        -4*cos(2*x) + cos(4*x) + pi**2/3
+        """
+        s, x = sympify(s), self.x
+
+        if x in s.free_symbols:
+            raise ValueError("'%s' should be independent of %s" % (s, x))
+
+        an = self.an.subs(x, x * s)
+        bn = self.bn.subs(x, x * s)
+        sfunc = self.function.subs(x, x * s)
+
+        return self.func(sfunc, self.args[1], (self.a0, an, bn))
+
+    def _eval_as_leading_term(self, x, logx, cdir):
+        for t in self:
+            if t is not S.Zero:
+                return t
+
+    def _eval_term(self, pt):
+        if pt == 0:
+            return self.a0
+        return self.an.coeff(pt) + self.bn.coeff(pt)
+
+    def __neg__(self):
+        return self.scale(-1)
+
+    def __add__(self, other):
+        if isinstance(other, FourierSeries):
+            if self.period != other.period:
+                raise ValueError("Both the series should have same periods")
+
+            x, y = self.x, other.x
+            function = self.function + other.function.subs(y, x)
+
+            if self.x not in function.free_symbols:
+                return function
+
+            an = self.an + other.an
+            bn = self.bn + other.bn
+            a0 = self.a0 + other.a0
+
+            return self.func(function, self.args[1], (a0, an, bn))
+
+        return Add(self, other)
+
+    def __sub__(self, other):
+        return self.__add__(-other)
+
+
+class FiniteFourierSeries(FourierSeries):
+    r"""Represents Finite Fourier sine/cosine series.
+
+    For how to compute Fourier series, see the :func:`fourier_series`
+    docstring.
+
+    Parameters
+    ==========
+
+    f : Expr
+        Expression for finding fourier_series
+
+    limits : ( x, start, stop)
+        x is the independent variable for the expression f
+        (start, stop) is the period of the fourier series
+
+    exprs: (a0, an, bn) or Expr
+        a0 is the constant term a0 of the fourier series
+        an is a dictionary of coefficients of cos terms
+         an[k] = coefficient of cos(pi*(k/L)*x)
+        bn is a dictionary of coefficients of sin terms
+         bn[k] = coefficient of sin(pi*(k/L)*x)
+
+        or exprs can be an expression to be converted to fourier form
+
+    Methods
+    =======
+
+    This class is an extension of FourierSeries class.
+    Please refer to sympy.series.fourier.FourierSeries for
+    further information.
+
+    See Also
+    ========
+
+    sympy.series.fourier.FourierSeries
+    sympy.series.fourier.fourier_series
+    """
+
+    def __new__(cls, f, limits, exprs):
+        f = sympify(f)
+        limits = sympify(limits)
+        exprs = sympify(exprs)
+
+        if not (isinstance(exprs, Tuple) and len(exprs) == 3):  # exprs is not of form (a0, an, bn)
+            # Converts the expression to fourier form
+            c, e = exprs.as_coeff_add()
+            from sympy.simplify.fu import TR10
+            rexpr = c + Add(*[TR10(i) for i in e])
+            a0, exp_ls = rexpr.expand(trig=False, power_base=False, power_exp=False, log=False).as_coeff_add()
+
+            x = limits[0]
+            L = abs(limits[2] - limits[1]) / 2
+
+            a = Wild('a', properties=[lambda k: k.is_Integer, lambda k: k is not S.Zero, ])
+            b = Wild('b', properties=[lambda k: x not in k.free_symbols, ])
+
+            an = {}
+            bn = {}
+
+            # separates the coefficients of sin and cos terms in dictionaries an, and bn
+            for p in exp_ls:
+                t = p.match(b * cos(a * (pi / L) * x))
+                q = p.match(b * sin(a * (pi / L) * x))
+                if t:
+                    an[t[a]] = t[b] + an.get(t[a], S.Zero)
+                elif q:
+                    bn[q[a]] = q[b] + bn.get(q[a], S.Zero)
+                else:
+                    a0 += p
+
+            exprs = Tuple(a0, an, bn)
+
+        return Expr.__new__(cls, f, limits, exprs)
+
+    @property
+    def interval(self):
+        _length = 1 if self.a0 else 0
+        _length += max(set(self.an.keys()).union(set(self.bn.keys()))) + 1
+        return Interval(0, _length)
+
+    @property
+    def length(self):
+        return self.stop - self.start
+
+    def shiftx(self, s):
+        s, x = sympify(s), self.x
+
+        if x in s.free_symbols:
+            raise ValueError("'%s' should be independent of %s" % (s, x))
+
+        _expr = self.truncate().subs(x, x + s)
+        sfunc = self.function.subs(x, x + s)
+
+        return self.func(sfunc, self.args[1], _expr)
+
+    def scale(self, s):
+        s, x = sympify(s), self.x
+
+        if x in s.free_symbols:
+            raise ValueError("'%s' should be independent of %s" % (s, x))
+
+        _expr = self.truncate() * s
+        sfunc = self.function * s
+
+        return self.func(sfunc, self.args[1], _expr)
+
+    def scalex(self, s):
+        s, x = sympify(s), self.x
+
+        if x in s.free_symbols:
+            raise ValueError("'%s' should be independent of %s" % (s, x))
+
+        _expr = self.truncate().subs(x, x * s)
+        sfunc = self.function.subs(x, x * s)
+
+        return self.func(sfunc, self.args[1], _expr)
+
+    def _eval_term(self, pt):
+        if pt == 0:
+            return self.a0
+
+        _term = self.an.get(pt, S.Zero) * cos(pt * (pi / self.L) * self.x) \
+                + self.bn.get(pt, S.Zero) * sin(pt * (pi / self.L) * self.x)
+        return _term
+
+    def __add__(self, other):
+        if isinstance(other, FourierSeries):
+            return other.__add__(fourier_series(self.function, self.args[1],\
+                                                finite=False))
+        elif isinstance(other, FiniteFourierSeries):
+            if self.period != other.period:
+                raise ValueError("Both the series should have same periods")
+
+            x, y = self.x, other.x
+            function = self.function + other.function.subs(y, x)
+
+            if self.x not in function.free_symbols:
+                return function
+
+            return fourier_series(function, limits=self.args[1])
+
+
+def fourier_series(f, limits=None, finite=True):
+    r"""Computes the Fourier trigonometric series expansion.
+
+    Explanation
+    ===========
+
+    Fourier trigonometric series of $f(x)$ over the interval $(a, b)$
+    is defined as:
+
+    .. math::
+        \frac{a_0}{2} + \sum_{n=1}^{\infty}
+        (a_n \cos(\frac{2n \pi x}{L}) + b_n \sin(\frac{2n \pi x}{L}))
+
+    where the coefficients are:
+
+    .. math::
+        L = b - a
+
+    .. math::
+        a_0 = \frac{2}{L} \int_{a}^{b}{f(x) dx}
+
+    .. math::
+        a_n = \frac{2}{L} \int_{a}^{b}{f(x) \cos(\frac{2n \pi x}{L}) dx}
+
+    .. math::
+        b_n = \frac{2}{L} \int_{a}^{b}{f(x) \sin(\frac{2n \pi x}{L}) dx}
+
+    The condition whether the function $f(x)$ given should be periodic
+    or not is more than necessary, because it is sufficient to consider
+    the series to be converging to $f(x)$ only in the given interval,
+    not throughout the whole real line.
+
+    This also brings a lot of ease for the computation because
+    you do not have to make $f(x)$ artificially periodic by
+    wrapping it with piecewise, modulo operations,
+    but you can shape the function to look like the desired periodic
+    function only in the interval $(a, b)$, and the computed series will
+    automatically become the series of the periodic version of $f(x)$.
+
+    This property is illustrated in the examples section below.
+
+    Parameters
+    ==========
+
+    limits : (sym, start, end), optional
+        *sym* denotes the symbol the series is computed with respect to.
+
+        *start* and *end* denotes the start and the end of the interval
+        where the fourier series converges to the given function.
+
+        Default range is specified as $-\pi$ and $\pi$.
+
+    Returns
+    =======
+
+    FourierSeries
+        A symbolic object representing the Fourier trigonometric series.
+
+    Examples
+    ========
+
+    Computing the Fourier series of $f(x) = x^2$:
+
+    >>> from sympy import fourier_series, pi
+    >>> from sympy.abc import x
+    >>> f = x**2
+    >>> s = fourier_series(f, (x, -pi, pi))
+    >>> s1 = s.truncate(n=3)
+    >>> s1
+    -4*cos(x) + cos(2*x) + pi**2/3
+
+    Shifting of the Fourier series:
+
+    >>> s.shift(1).truncate()
+    -4*cos(x) + cos(2*x) + 1 + pi**2/3
+    >>> s.shiftx(1).truncate()
+    -4*cos(x + 1) + cos(2*x + 2) + pi**2/3
+
+    Scaling of the Fourier series:
+
+    >>> s.scale(2).truncate()
+    -8*cos(x) + 2*cos(2*x) + 2*pi**2/3
+    >>> s.scalex(2).truncate()
+    -4*cos(2*x) + cos(4*x) + pi**2/3
+
+    Computing the Fourier series of $f(x) = x$:
+
+    This illustrates how truncating to the higher order gives better
+    convergence.
+
+    .. plot::
+        :context: reset
+        :format: doctest
+        :include-source: True
+
+        >>> from sympy import fourier_series, pi, plot
+        >>> from sympy.abc import x
+        >>> f = x
+        >>> s = fourier_series(f, (x, -pi, pi))
+        >>> s1 = s.truncate(n = 3)
+        >>> s2 = s.truncate(n = 5)
+        >>> s3 = s.truncate(n = 7)
+        >>> p = plot(f, s1, s2, s3, (x, -pi, pi), show=False, legend=True)
+
+        >>> p[0].line_color = (0, 0, 0)
+        >>> p[0].label = 'x'
+        >>> p[1].line_color = (0.7, 0.7, 0.7)
+        >>> p[1].label = 'n=3'
+        >>> p[2].line_color = (0.5, 0.5, 0.5)
+        >>> p[2].label = 'n=5'
+        >>> p[3].line_color = (0.3, 0.3, 0.3)
+        >>> p[3].label = 'n=7'
+
+        >>> p.show()
+
+    This illustrates how the series converges to different sawtooth
+    waves if the different ranges are specified.
+
+    .. plot::
+        :context: close-figs
+        :format: doctest
+        :include-source: True
+
+        >>> s1 = fourier_series(x, (x, -1, 1)).truncate(10)
+        >>> s2 = fourier_series(x, (x, -pi, pi)).truncate(10)
+        >>> s3 = fourier_series(x, (x, 0, 1)).truncate(10)
+        >>> p = plot(x, s1, s2, s3, (x, -5, 5), show=False, legend=True)
+
+        >>> p[0].line_color = (0, 0, 0)
+        >>> p[0].label = 'x'
+        >>> p[1].line_color = (0.7, 0.7, 0.7)
+        >>> p[1].label = '[-1, 1]'
+        >>> p[2].line_color = (0.5, 0.5, 0.5)
+        >>> p[2].label = '[-pi, pi]'
+        >>> p[3].line_color = (0.3, 0.3, 0.3)
+        >>> p[3].label = '[0, 1]'
+
+        >>> p.show()
+
+    Notes
+    =====
+
+    Computing Fourier series can be slow
+    due to the integration required in computing
+    an, bn.
+
+    It is faster to compute Fourier series of a function
+    by using shifting and scaling on an already
+    computed Fourier series rather than computing
+    again.
+
+    e.g. If the Fourier series of ``x**2`` is known
+    the Fourier series of ``x**2 - 1`` can be found by shifting by ``-1``.
+
+    See Also
+    ========
+
+    sympy.series.fourier.FourierSeries
+
+    References
+    ==========
+
+    .. [1] https://mathworld.wolfram.com/FourierSeries.html
+    """
+    f = sympify(f)
+
+    limits = _process_limits(f, limits)
+    x = limits[0]
+
+    if x not in f.free_symbols:
+        return f
+
+    if finite:
+        L = abs(limits[2] - limits[1]) / 2
+        is_finite, res_f = finite_check(f, x, L)
+        if is_finite:
+            return FiniteFourierSeries(f, limits, res_f)
+
+    n = Dummy('n')
+    center = (limits[1] + limits[2]) / 2
+    if center.is_zero:
+        neg_f = f.subs(x, -x)
+        if f == neg_f:
+            a0, an = fourier_cos_seq(f, limits, n)
+            bn = SeqFormula(0, (1, oo))
+            return FourierSeries(f, limits, (a0, an, bn))
+        elif f == -neg_f:
+            a0 = S.Zero
+            an = SeqFormula(0, (1, oo))
+            bn = fourier_sin_seq(f, limits, n)
+            return FourierSeries(f, limits, (a0, an, bn))
+    a0, an = fourier_cos_seq(f, limits, n)
+    bn = fourier_sin_seq(f, limits, n)
+    return FourierSeries(f, limits, (a0, an, bn))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/gruntz.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/gruntz.py
new file mode 100644
index 0000000000000000000000000000000000000000..20ba3150e9918384141e755a39f5bacb0e76db55
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/gruntz.py
@@ -0,0 +1,701 @@
+"""
+Limits
+======
+
+Implemented according to the PhD thesis
+https://www.cybertester.com/data/gruntz.pdf, which contains very thorough
+descriptions of the algorithm including many examples.  We summarize here
+the gist of it.
+
+All functions are sorted according to how rapidly varying they are at
+infinity using the following rules. Any two functions f and g can be
+compared using the properties of L:
+
+L=lim  log|f(x)| / log|g(x)|           (for x -> oo)
+
+We define >, < ~ according to::
+
+    1. f > g .... L=+-oo
+
+        we say that:
+        - f is greater than any power of g
+        - f is more rapidly varying than g
+        - f goes to infinity/zero faster than g
+
+    2. f < g .... L=0
+
+        we say that:
+        - f is lower than any power of g
+
+    3. f ~ g .... L!=0, +-oo
+
+        we say that:
+        - both f and g are bounded from above and below by suitable integral
+          powers of the other
+
+Examples
+========
+::
+    2 < x < exp(x) < exp(x**2) < exp(exp(x))
+    2 ~ 3 ~ -5
+    x ~ x**2 ~ x**3 ~ 1/x ~ x**m ~ -x
+    exp(x) ~ exp(-x) ~ exp(2x) ~ exp(x)**2 ~ exp(x+exp(-x))
+    f ~ 1/f
+
+So we can divide all the functions into comparability classes (x and x^2
+belong to one class, exp(x) and exp(-x) belong to some other class). In
+principle, we could compare any two functions, but in our algorithm, we
+do not compare anything below the class 2~3~-5 (for example log(x) is
+below this), so we set 2~3~-5 as the lowest comparability class.
+
+Given the function f, we find the list of most rapidly varying (mrv set)
+subexpressions of it. This list belongs to the same comparability class.
+Let's say it is {exp(x), exp(2x)}. Using the rule f ~ 1/f we find an
+element "w" (either from the list or a new one) from the same
+comparability class which goes to zero at infinity. In our example we
+set w=exp(-x) (but we could also set w=exp(-2x) or w=exp(-3x) ...). We
+rewrite the mrv set using w, in our case {1/w, 1/w^2}, and substitute it
+into f. Then we expand f into a series in w::
+
+    f = c0*w^e0 + c1*w^e1 + ... + O(w^en),       where e0oo, lim f = lim c0*w^e0, because all the other terms go to zero,
+because w goes to zero faster than the ci and ei. So::
+
+    for e0>0, lim f = 0
+    for e0<0, lim f = +-oo   (the sign depends on the sign of c0)
+    for e0=0, lim f = lim c0
+
+We need to recursively compute limits at several places of the algorithm, but
+as is shown in the PhD thesis, it always finishes.
+
+Important functions from the implementation:
+
+compare(a, b, x) compares "a" and "b" by computing the limit L.
+mrv(e, x) returns list of most rapidly varying (mrv) subexpressions of "e"
+rewrite(e, Omega, x, wsym) rewrites "e" in terms of w
+leadterm(f, x) returns the lowest power term in the series of f
+mrv_leadterm(e, x) returns the lead term (c0, e0) for e
+limitinf(e, x) computes lim e  (for x->oo)
+limit(e, z, z0) computes any limit by converting it to the case x->oo
+
+All the functions are really simple and straightforward except
+rewrite(), which is the most difficult/complex part of the algorithm.
+When the algorithm fails, the bugs are usually in the series expansion
+(i.e. in SymPy) or in rewrite.
+
+This code is almost exact rewrite of the Maple code inside the Gruntz
+thesis.
+
+Debugging
+---------
+
+Because the gruntz algorithm is highly recursive, it's difficult to
+figure out what went wrong inside a debugger. Instead, turn on nice
+debug prints by defining the environment variable SYMPY_DEBUG. For
+example:
+
+[user@localhost]: SYMPY_DEBUG=True ./bin/isympy
+
+In [1]: limit(sin(x)/x, x, 0)
+limitinf(_x*sin(1/_x), _x) = 1
++-mrv_leadterm(_x*sin(1/_x), _x) = (1, 0)
+| +-mrv(_x*sin(1/_x), _x) = set([_x])
+| | +-mrv(_x, _x) = set([_x])
+| | +-mrv(sin(1/_x), _x) = set([_x])
+| |   +-mrv(1/_x, _x) = set([_x])
+| |     +-mrv(_x, _x) = set([_x])
+| +-mrv_leadterm(exp(_x)*sin(exp(-_x)), _x, set([exp(_x)])) = (1, 0)
+|   +-rewrite(exp(_x)*sin(exp(-_x)), set([exp(_x)]), _x, _w) = (1/_w*sin(_w), -_x)
+|     +-sign(_x, _x) = 1
+|     +-mrv_leadterm(1, _x) = (1, 0)
++-sign(0, _x) = 0
++-limitinf(1, _x) = 1
+
+And check manually which line is wrong. Then go to the source code and
+debug this function to figure out the exact problem.
+
+"""
+from functools import reduce
+
+from sympy.core import Basic, S, Mul, PoleError
+from sympy.core.cache import cacheit
+from sympy.core.function import AppliedUndef
+from sympy.core.intfunc import ilcm
+from sympy.core.numbers import I, oo
+from sympy.core.symbol import Dummy, Wild
+from sympy.core.traversal import bottom_up
+
+from sympy.functions import log, exp, sign as _sign
+from sympy.series.order import Order
+from sympy.utilities.misc import debug_decorator as debug
+from sympy.utilities.timeutils import timethis
+
+timeit = timethis('gruntz')
+
+
+def compare(a, b, x):
+    """Returns "<" if a" for a>b"""
+    # log(exp(...)) must always be simplified here for termination
+    la, lb = log(a), log(b)
+    if isinstance(a, Basic) and (isinstance(a, exp) or (a.is_Pow and a.base == S.Exp1)):
+        la = a.exp
+    if isinstance(b, Basic) and (isinstance(b, exp) or (b.is_Pow and b.base == S.Exp1)):
+        lb = b.exp
+
+    c = limitinf(la/lb, x)
+    if c == 0:
+        return "<"
+    elif c.is_infinite:
+        return ">"
+    else:
+        return "="
+
+
+class SubsSet(dict):
+    """
+    Stores (expr, dummy) pairs, and how to rewrite expr-s.
+
+    Explanation
+    ===========
+
+    The gruntz algorithm needs to rewrite certain expressions in term of a new
+    variable w. We cannot use subs, because it is just too smart for us. For
+    example::
+
+        > Omega=[exp(exp(_p - exp(-_p))/(1 - 1/_p)), exp(exp(_p))]
+        > O2=[exp(-exp(_p) + exp(-exp(-_p))*exp(_p)/(1 - 1/_p))/_w, 1/_w]
+        > e = exp(exp(_p - exp(-_p))/(1 - 1/_p)) - exp(exp(_p))
+        > e.subs(Omega[0],O2[0]).subs(Omega[1],O2[1])
+        -1/w + exp(exp(p)*exp(-exp(-p))/(1 - 1/p))
+
+    is really not what we want!
+
+    So we do it the hard way and keep track of all the things we potentially
+    want to substitute by dummy variables. Consider the expression::
+
+        exp(x - exp(-x)) + exp(x) + x.
+
+    The mrv set is {exp(x), exp(-x), exp(x - exp(-x))}.
+    We introduce corresponding dummy variables d1, d2, d3 and rewrite::
+
+        d3 + d1 + x.
+
+    This class first of all keeps track of the mapping expr->variable, i.e.
+    will at this stage be a dictionary::
+
+        {exp(x): d1, exp(-x): d2, exp(x - exp(-x)): d3}.
+
+    [It turns out to be more convenient this way round.]
+    But sometimes expressions in the mrv set have other expressions from the
+    mrv set as subexpressions, and we need to keep track of that as well. In
+    this case, d3 is really exp(x - d2), so rewrites at this stage is::
+
+        {d3: exp(x-d2)}.
+
+    The function rewrite uses all this information to correctly rewrite our
+    expression in terms of w. In this case w can be chosen to be exp(-x),
+    i.e. d2. The correct rewriting then is::
+
+        exp(-w)/w + 1/w + x.
+    """
+    def __init__(self):
+        self.rewrites = {}
+
+    def __repr__(self):
+        return super().__repr__() + ', ' + self.rewrites.__repr__()
+
+    def __getitem__(self, key):
+        if key not in self:
+            self[key] = Dummy()
+        return dict.__getitem__(self, key)
+
+    def do_subs(self, e):
+        """Substitute the variables with expressions"""
+        for expr, var in self.items():
+            e = e.xreplace({var: expr})
+        return e
+
+    def meets(self, s2):
+        """Tell whether or not self and s2 have non-empty intersection"""
+        return set(self.keys()).intersection(list(s2.keys())) != set()
+
+    def union(self, s2, exps=None):
+        """Compute the union of self and s2, adjusting exps"""
+        res = self.copy()
+        tr = {}
+        for expr, var in s2.items():
+            if expr in self:
+                if exps:
+                    exps = exps.xreplace({var: res[expr]})
+                tr[var] = res[expr]
+            else:
+                res[expr] = var
+        for var, rewr in s2.rewrites.items():
+            res.rewrites[var] = rewr.xreplace(tr)
+        return res, exps
+
+    def copy(self):
+        """Create a shallow copy of SubsSet"""
+        r = SubsSet()
+        r.rewrites = self.rewrites.copy()
+        for expr, var in self.items():
+            r[expr] = var
+        return r
+
+
+@debug
+def mrv(e, x):
+    """Returns a SubsSet of most rapidly varying (mrv) subexpressions of 'e',
+       and e rewritten in terms of these"""
+    from sympy.simplify.powsimp import powsimp
+    e = powsimp(e, deep=True, combine='exp')
+    if not isinstance(e, Basic):
+        raise TypeError("e should be an instance of Basic")
+    if not e.has(x):
+        return SubsSet(), e
+    elif e == x:
+        s = SubsSet()
+        return s, s[x]
+    elif e.is_Mul or e.is_Add:
+        i, d = e.as_independent(x)  # throw away x-independent terms
+        if d.func != e.func:
+            s, expr = mrv(d, x)
+            return s, e.func(i, expr)
+        a, b = d.as_two_terms()
+        s1, e1 = mrv(a, x)
+        s2, e2 = mrv(b, x)
+        return mrv_max1(s1, s2, e.func(i, e1, e2), x)
+    elif e.is_Pow and e.base != S.Exp1:
+        e1 = S.One
+        while e.is_Pow:
+            b1 = e.base
+            e1 *= e.exp
+            e = b1
+        if b1 == 1:
+            return SubsSet(), b1
+        if e1.has(x):
+            return mrv(exp(e1*log(b1)), x)
+        else:
+            s, expr = mrv(b1, x)
+            return s, expr**e1
+    elif isinstance(e, log):
+        s, expr = mrv(e.args[0], x)
+        return s, log(expr)
+    elif isinstance(e, exp) or (e.is_Pow and e.base == S.Exp1):
+        # We know from the theory of this algorithm that exp(log(...)) may always
+        # be simplified here, and doing so is vital for termination.
+        if isinstance(e.exp, log):
+            return mrv(e.exp.args[0], x)
+        # if a product has an infinite factor the result will be
+        # infinite if there is no zero, otherwise NaN; here, we
+        # consider the result infinite if any factor is infinite
+        li = limitinf(e.exp, x)
+        if any(_.is_infinite for _ in Mul.make_args(li)):
+            s1 = SubsSet()
+            e1 = s1[e]
+            s2, e2 = mrv(e.exp, x)
+            su = s1.union(s2)[0]
+            su.rewrites[e1] = exp(e2)
+            return mrv_max3(s1, e1, s2, exp(e2), su, e1, x)
+        else:
+            s, expr = mrv(e.exp, x)
+            return s, exp(expr)
+    elif isinstance(e, AppliedUndef):
+        raise ValueError("MRV set computation for UndefinedFunction is not allowed")
+    elif e.is_Function:
+        l = [mrv(a, x) for a in e.args]
+        l2 = [s for (s, _) in l if s != SubsSet()]
+        if len(l2) != 1:
+            # e.g. something like BesselJ(x, x)
+            raise NotImplementedError("MRV set computation for functions in"
+                                      " several variables not implemented.")
+        s, ss = l2[0], SubsSet()
+        args = [ss.do_subs(x[1]) for x in l]
+        return s, e.func(*args)
+    elif e.is_Derivative:
+        raise NotImplementedError("MRV set computation for derivatives"
+                                  " not implemented yet.")
+    raise NotImplementedError(
+        "Don't know how to calculate the mrv of '%s'" % e)
+
+
+def mrv_max3(f, expsf, g, expsg, union, expsboth, x):
+    """
+    Computes the maximum of two sets of expressions f and g, which
+    are in the same comparability class, i.e. max() compares (two elements of)
+    f and g and returns either (f, expsf) [if f is larger], (g, expsg)
+    [if g is larger] or (union, expsboth) [if f, g are of the same class].
+    """
+    if not isinstance(f, SubsSet):
+        raise TypeError("f should be an instance of SubsSet")
+    if not isinstance(g, SubsSet):
+        raise TypeError("g should be an instance of SubsSet")
+    if f == SubsSet():
+        return g, expsg
+    elif g == SubsSet():
+        return f, expsf
+    elif f.meets(g):
+        return union, expsboth
+
+    c = compare(list(f.keys())[0], list(g.keys())[0], x)
+    if c == ">":
+        return f, expsf
+    elif c == "<":
+        return g, expsg
+    else:
+        if c != "=":
+            raise ValueError("c should be =")
+        return union, expsboth
+
+
+def mrv_max1(f, g, exps, x):
+    """Computes the maximum of two sets of expressions f and g, which
+    are in the same comparability class, i.e. mrv_max1() compares (two elements of)
+    f and g and returns the set, which is in the higher comparability class
+    of the union of both, if they have the same order of variation.
+    Also returns exps, with the appropriate substitutions made.
+    """
+    u, b = f.union(g, exps)
+    return mrv_max3(f, g.do_subs(exps), g, f.do_subs(exps),
+                    u, b, x)
+
+
+@debug
+@cacheit
+@timeit
+def sign(e, x):
+    """
+    Returns a sign of an expression e(x) for x->oo.
+
+    ::
+
+        e >  0 for x sufficiently large ...  1
+        e == 0 for x sufficiently large ...  0
+        e <  0 for x sufficiently large ... -1
+
+    The result of this function is currently undefined if e changes sign
+    arbitrarily often for arbitrarily large x (e.g. sin(x)).
+
+    Note that this returns zero only if e is *constantly* zero
+    for x sufficiently large. [If e is constant, of course, this is just
+    the same thing as the sign of e.]
+    """
+    if not isinstance(e, Basic):
+        raise TypeError("e should be an instance of Basic")
+
+    if e.is_positive:
+        return 1
+    elif e.is_negative:
+        return -1
+    elif e.is_zero:
+        return 0
+
+    elif not e.has(x):
+        from sympy.simplify import logcombine
+        e = logcombine(e)
+        return _sign(e)
+    elif e == x:
+        return 1
+    elif e.is_Mul:
+        a, b = e.as_two_terms()
+        sa = sign(a, x)
+        if not sa:
+            return 0
+        return sa * sign(b, x)
+    elif isinstance(e, exp):
+        return 1
+    elif e.is_Pow:
+        if e.base == S.Exp1:
+            return 1
+        s = sign(e.base, x)
+        if s == 1:
+            return 1
+        if e.exp.is_Integer:
+            return s**e.exp
+    elif isinstance(e, log) and e.args[0].is_positive:
+        return sign(e.args[0] - 1, x)
+
+    # if all else fails, do it the hard way
+    c0, e0 = mrv_leadterm(e, x)
+    return sign(c0, x)
+
+
+@debug
+@timeit
+@cacheit
+def limitinf(e, x):
+    """Limit e(x) for x-> oo."""
+    # rewrite e in terms of tractable functions only
+
+    old = e
+    if not e.has(x):
+        return e  # e is a constant
+    from sympy.simplify.powsimp import powdenest
+    from sympy.calculus.util import AccumBounds
+    if e.has(Order):
+        e = e.expand().removeO()
+    if not x.is_positive or x.is_integer:
+        # We make sure that x.is_positive is True and x.is_integer is None
+        # so we get all the correct mathematical behavior from the expression.
+        # We need a fresh variable.
+        p = Dummy('p', positive=True)
+        e = e.subs(x, p)
+        x = p
+    e = e.rewrite('tractable', deep=True, limitvar=x)
+    e = powdenest(e)
+    if isinstance(e, AccumBounds):
+        if mrv_leadterm(e.min, x) != mrv_leadterm(e.max, x):
+            raise NotImplementedError
+        c0, e0 = mrv_leadterm(e.min, x)
+    else:
+        c0, e0 = mrv_leadterm(e, x)
+    sig = sign(e0, x)
+    if sig == 1:
+        return S.Zero  # e0>0: lim f = 0
+    elif sig == -1:  # e0<0: lim f = +-oo (the sign depends on the sign of c0)
+        if c0.match(I*Wild("a", exclude=[I])):
+            return c0*oo
+        s = sign(c0, x)
+        # the leading term shouldn't be 0:
+        if s == 0:
+            raise ValueError("Leading term should not be 0")
+        return s*oo
+    elif sig == 0:
+        if c0 == old:
+            c0 = c0.cancel()
+        return limitinf(c0, x)  # e0=0: lim f = lim c0
+    else:
+        raise ValueError("{} could not be evaluated".format(sig))
+
+
+def moveup2(s, x):
+    r = SubsSet()
+    for expr, var in s.items():
+        r[expr.xreplace({x: exp(x)})] = var
+    for var, expr in s.rewrites.items():
+        r.rewrites[var] = s.rewrites[var].xreplace({x: exp(x)})
+    return r
+
+
+def moveup(l, x):
+    return [e.xreplace({x: exp(x)}) for e in l]
+
+
+@debug
+@timeit
+@cacheit
+def mrv_leadterm(e, x):
+    """Returns (c0, e0) for e."""
+    Omega = SubsSet()
+    if not e.has(x):
+        return (e, S.Zero)
+    if Omega == SubsSet():
+        Omega, exps = mrv(e, x)
+    if not Omega:
+        # e really does not depend on x after simplification
+        return exps, S.Zero
+    if x in Omega:
+        # move the whole omega up (exponentiate each term):
+        Omega_up = moveup2(Omega, x)
+        exps_up = moveup([exps], x)[0]
+        # NOTE: there is no need to move this down!
+        Omega = Omega_up
+        exps = exps_up
+    #
+    # The positive dummy, w, is used here so log(w*2) etc. will expand;
+    # a unique dummy is needed in this algorithm
+    #
+    # For limits of complex functions, the algorithm would have to be
+    # improved, or just find limits of Re and Im components separately.
+    #
+    w = Dummy("w", positive=True)
+    f, logw = rewrite(exps, Omega, x, w)
+
+    # Ensure expressions of the form exp(log(...)) don't get simplified automatically in the previous steps.
+    # see: https://github.com/sympy/sympy/issues/15323#issuecomment-478639399
+    f = f.replace(lambda f: f.is_Pow and f.has(x), lambda f: exp(log(f.base)*f.exp))
+
+    try:
+        lt = f.leadterm(w, logx=logw)
+    except (NotImplementedError, PoleError, ValueError):
+        n0 = 1
+        _series = Order(1)
+        incr = S.One
+        while _series.is_Order:
+            _series = f._eval_nseries(w, n=n0+incr, logx=logw)
+            incr *= 2
+        series = _series.expand().removeO()
+        try:
+            lt = series.leadterm(w, logx=logw)
+        except (NotImplementedError, PoleError, ValueError):
+            lt = f.as_coeff_exponent(w)
+            if lt[0].has(w):
+                base = f.as_base_exp()[0].as_coeff_exponent(w)
+                ex = f.as_base_exp()[1]
+                lt = (base[0]**ex, base[1]*ex)
+    return (lt[0].subs(log(w), logw), lt[1])
+
+
+def build_expression_tree(Omega, rewrites):
+    r""" Helper function for rewrite.
+
+    We need to sort Omega (mrv set) so that we replace an expression before
+    we replace any expression in terms of which it has to be rewritten::
+
+        e1 ---> e2 ---> e3
+                 \
+                  -> e4
+
+    Here we can do e1, e2, e3, e4 or e1, e2, e4, e3.
+    To do this we assemble the nodes into a tree, and sort them by height.
+
+    This function builds the tree, rewrites then sorts the nodes.
+    """
+    class Node:
+        def __init__(self):
+            self.before = []
+            self.expr = None
+            self.var = None
+        def ht(self):
+            return reduce(lambda x, y: x + y,
+                          [x.ht() for x in self.before], 1)
+    nodes = {}
+    for expr, v in Omega:
+        n = Node()
+        n.var = v
+        n.expr = expr
+        nodes[v] = n
+    for _, v in Omega:
+        if v in rewrites:
+            n = nodes[v]
+            r = rewrites[v]
+            for _, v2 in Omega:
+                if r.has(v2):
+                    n.before.append(nodes[v2])
+
+    return nodes
+
+
+@debug
+@timeit
+def rewrite(e, Omega, x, wsym):
+    """e(x) ... the function
+    Omega ... the mrv set
+    wsym ... the symbol which is going to be used for w
+
+    Returns the rewritten e in terms of w and log(w). See test_rewrite1()
+    for examples and correct results.
+    """
+
+    from sympy import AccumBounds
+    if not isinstance(Omega, SubsSet):
+        raise TypeError("Omega should be an instance of SubsSet")
+    if len(Omega) == 0:
+        raise ValueError("Length cannot be 0")
+    # all items in Omega must be exponentials
+    for t in Omega.keys():
+        if not isinstance(t, exp):
+            raise ValueError("Value should be exp")
+    rewrites = Omega.rewrites
+    Omega = list(Omega.items())
+
+    nodes = build_expression_tree(Omega, rewrites)
+    Omega.sort(key=lambda x: nodes[x[1]].ht(), reverse=True)
+
+    # make sure we know the sign of each exp() term; after the loop,
+    # g is going to be the "w" - the simplest one in the mrv set
+    for g, _ in Omega:
+        sig = sign(g.exp, x)
+        if sig != 1 and sig != -1 and not sig.has(AccumBounds):
+            raise NotImplementedError('Result depends on the sign of %s' % sig)
+    if sig == 1:
+        wsym = 1/wsym  # if g goes to oo, substitute 1/w
+    # O2 is a list, which results by rewriting each item in Omega using "w"
+    O2 = []
+    denominators = []
+    for f, var in Omega:
+        c = limitinf(f.exp/g.exp, x)
+        if c.is_Rational:
+            denominators.append(c.q)
+        arg = f.exp
+        if var in rewrites:
+            if not isinstance(rewrites[var], exp):
+                raise ValueError("Value should be exp")
+            arg = rewrites[var].args[0]
+        O2.append((var, exp((arg - c*g.exp))*wsym**c))
+
+    # Remember that Omega contains subexpressions of "e". So now we find
+    # them in "e" and substitute them for our rewriting, stored in O2
+
+    # the following powsimp is necessary to automatically combine exponentials,
+    # so that the .xreplace() below succeeds:
+    # TODO this should not be necessary
+    from sympy.simplify.powsimp import powsimp
+    f = powsimp(e, deep=True, combine='exp')
+    for a, b in O2:
+        f = f.xreplace({a: b})
+
+    for _, var in Omega:
+        assert not f.has(var)
+
+    # finally compute the logarithm of w (logw).
+    logw = g.exp
+    if sig == 1:
+        logw = -logw  # log(w)->log(1/w)=-log(w)
+
+    # Some parts of SymPy have difficulty computing series expansions with
+    # non-integral exponents. The following heuristic improves the situation:
+    exponent = reduce(ilcm, denominators, 1)
+    f = f.subs({wsym: wsym**exponent})
+    logw /= exponent
+
+    # bottom_up function is required for a specific case - when f is
+    # -exp(p/(p + 1)) + exp(-p**2/(p + 1) + p). No current simplification
+    # methods reduce this to 0 while not expanding polynomials.
+    f = bottom_up(f, lambda w: getattr(w, 'normal', lambda: w)())
+
+    return f, logw
+
+
+def gruntz(e, z, z0, dir="+"):
+    """
+    Compute the limit of e(z) at the point z0 using the Gruntz algorithm.
+
+    Explanation
+    ===========
+
+    ``z0`` can be any expression, including oo and -oo.
+
+    For ``dir="+"`` (default) it calculates the limit from the right
+    (z->z0+) and for ``dir="-"`` the limit from the left (z->z0-). For infinite z0
+    (oo or -oo), the dir argument does not matter.
+
+    This algorithm is fully described in the module docstring in the gruntz.py
+    file. It relies heavily on the series expansion. Most frequently, gruntz()
+    is only used if the faster limit() function (which uses heuristics) fails.
+    """
+    if not z.is_symbol:
+        raise NotImplementedError("Second argument must be a Symbol")
+
+    # convert all limits to the limit z->oo; sign of z is handled in limitinf
+    r = None
+    if z0 in (oo, I*oo):
+        e0 = e
+    elif z0 in (-oo, -I*oo):
+        e0 = e.subs(z, -z)
+    else:
+        if str(dir) == "-":
+            e0 = e.subs(z, z0 - 1/z)
+        elif str(dir) == "+":
+            e0 = e.subs(z, z0 + 1/z)
+        else:
+            raise NotImplementedError("dir must be '+' or '-'")
+
+    r = limitinf(e0, z)
+
+    # This is a bit of a heuristic for nice results... we always rewrite
+    # tractable functions in terms of familiar intractable ones.
+    # It might be nicer to rewrite the exactly to what they were initially,
+    # but that would take some work to implement.
+    return r.rewrite('intractable', deep=True)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/kauers.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/kauers.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e9645ff15ee5ae3c1d1c8709f76aed1b366f50a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/kauers.py
@@ -0,0 +1,51 @@
+def finite_diff(expression, variable, increment=1):
+    """
+    Takes as input a polynomial expression and the variable used to construct
+    it and returns the difference between function's value when the input is
+    incremented to 1 and the original function value. If you want an increment
+    other than one supply it as a third argument.
+
+    Examples
+    ========
+
+    >>> from sympy.abc import x, y, z
+    >>> from sympy.series.kauers import finite_diff
+    >>> finite_diff(x**2, x)
+    2*x + 1
+    >>> finite_diff(y**3 + 2*y**2 + 3*y + 4, y)
+    3*y**2 + 7*y + 6
+    >>> finite_diff(x**2 + 3*x + 8, x, 2)
+    4*x + 10
+    >>> finite_diff(z**3 + 8*z, z, 3)
+    9*z**2 + 27*z + 51
+    """
+    expression = expression.expand()
+    expression2 = expression.subs(variable, variable + increment)
+    expression2 = expression2.expand()
+    return expression2 - expression
+
+def finite_diff_kauers(sum):
+    """
+    Takes as input a Sum instance and returns the difference between the sum
+    with the upper index incremented by 1 and the original sum. For example,
+    if S(n) is a sum, then finite_diff_kauers will return S(n + 1) - S(n).
+
+    Examples
+    ========
+
+    >>> from sympy.series.kauers import finite_diff_kauers
+    >>> from sympy import Sum
+    >>> from sympy.abc import x, y, m, n, k
+    >>> finite_diff_kauers(Sum(k, (k, 1, n)))
+    n + 1
+    >>> finite_diff_kauers(Sum(1/k, (k, 1, n)))
+    1/(n + 1)
+    >>> finite_diff_kauers(Sum((x*y**2), (x, 1, n), (y, 1, m)))
+    (m + 1)**2*(n + 1)
+    >>> finite_diff_kauers(Sum((x*y), (x, 1, m), (y, 1, n)))
+    (m + 1)*(n + 1)
+    """
+    function = sum.function
+    for l in sum.limits:
+        function = function.subs(l[0], l[- 1] + 1)
+    return function
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/limits.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/limits.py
new file mode 100644
index 0000000000000000000000000000000000000000..e15f7a1243452075a76553903cabf60e43942d8c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/limits.py
@@ -0,0 +1,394 @@
+from sympy.calculus.accumulationbounds import AccumBounds
+from sympy.core import S, Symbol, Add, sympify, Expr, PoleError, Mul
+from sympy.core.exprtools import factor_terms
+from sympy.core.numbers import Float, _illegal
+from sympy.core.function import AppliedUndef
+from sympy.core.symbol import Dummy
+from sympy.functions.combinatorial.factorials import factorial
+from sympy.functions.elementary.complexes import (Abs, sign, arg, re)
+from sympy.functions.elementary.exponential import (exp, log)
+from sympy.functions.special.gamma_functions import gamma
+from sympy.polys import PolynomialError, factor
+from sympy.series.order import Order
+from .gruntz import gruntz
+
+def limit(e, z, z0, dir="+"):
+    """Computes the limit of ``e(z)`` at the point ``z0``.
+
+    Parameters
+    ==========
+
+    e : expression, the limit of which is to be taken
+
+    z : symbol representing the variable in the limit.
+        Other symbols are treated as constants. Multivariate limits
+        are not supported.
+
+    z0 : the value toward which ``z`` tends. Can be any expression,
+        including ``oo`` and ``-oo``.
+
+    dir : string, optional (default: "+")
+        The limit is bi-directional if ``dir="+-"``, from the right
+        (z->z0+) if ``dir="+"``, and from the left (z->z0-) if
+        ``dir="-"``. For infinite ``z0`` (``oo`` or ``-oo``), the ``dir``
+        argument is determined from the direction of the infinity
+        (i.e., ``dir="-"`` for ``oo``).
+
+    Examples
+    ========
+
+    >>> from sympy import limit, sin, oo
+    >>> from sympy.abc import x
+    >>> limit(sin(x)/x, x, 0)
+    1
+    >>> limit(1/x, x, 0) # default dir='+'
+    oo
+    >>> limit(1/x, x, 0, dir="-")
+    -oo
+    >>> limit(1/x, x, 0, dir='+-')
+    zoo
+    >>> limit(1/x, x, oo)
+    0
+
+    Notes
+    =====
+
+    First we try some heuristics for easy and frequent cases like "x", "1/x",
+    "x**2" and similar, so that it's fast. For all other cases, we use the
+    Gruntz algorithm (see the gruntz() function).
+
+    See Also
+    ========
+
+     limit_seq : returns the limit of a sequence.
+    """
+
+    return Limit(e, z, z0, dir).doit(deep=False)
+
+
+def heuristics(e, z, z0, dir):
+    """Computes the limit of an expression term-wise.
+    Parameters are the same as for the ``limit`` function.
+    Works with the arguments of expression ``e`` one by one, computing
+    the limit of each and then combining the results. This approach
+    works only for simple limits, but it is fast.
+    """
+
+    rv = None
+    if z0 is S.Infinity:
+        rv = limit(e.subs(z, 1/z), z, S.Zero, "+")
+        if isinstance(rv, Limit):
+            return
+    elif (e.is_Mul or e.is_Add or e.is_Pow or (e.is_Function and not isinstance(e, AppliedUndef))):
+        r = []
+        from sympy.simplify.simplify import together
+        for a in e.args:
+            l = limit(a, z, z0, dir)
+            if l.has(S.Infinity) and l.is_finite is None:
+                if isinstance(e, Add):
+                    m = factor_terms(e)
+                    if not isinstance(m, Mul): # try together
+                        m = together(m)
+                    if not isinstance(m, Mul): # try factor if the previous methods failed
+                        m = factor(e)
+                    if isinstance(m, Mul):
+                        return heuristics(m, z, z0, dir)
+                    return
+                return
+            elif isinstance(l, Limit):
+                return
+            elif l is S.NaN:
+                return
+            else:
+                r.append(l)
+        if r:
+            rv = e.func(*r)
+            if rv is S.NaN and e.is_Mul and any(isinstance(rr, AccumBounds) for rr in r):
+                r2 = []
+                e2 = []
+                for ii, rval in enumerate(r):
+                    if isinstance(rval, AccumBounds):
+                        r2.append(rval)
+                    else:
+                        e2.append(e.args[ii])
+
+                if len(e2) > 0:
+                    e3 = Mul(*e2).simplify()
+                    l = limit(e3, z, z0, dir)
+                    rv = l * Mul(*r2)
+
+            if rv is S.NaN:
+                try:
+                    from sympy.simplify.ratsimp import ratsimp
+                    rat_e = ratsimp(e)
+                except PolynomialError:
+                    return
+                if rat_e is S.NaN or rat_e == e:
+                    return
+                return limit(rat_e, z, z0, dir)
+    return rv
+
+
+class Limit(Expr):
+    """Represents an unevaluated limit.
+
+    Examples
+    ========
+
+    >>> from sympy import Limit, sin
+    >>> from sympy.abc import x
+    >>> Limit(sin(x)/x, x, 0)
+    Limit(sin(x)/x, x, 0, dir='+')
+    >>> Limit(1/x, x, 0, dir="-")
+    Limit(1/x, x, 0, dir='-')
+
+    """
+
+    def __new__(cls, e, z, z0, dir="+"):
+        e = sympify(e)
+        z = sympify(z)
+        z0 = sympify(z0)
+
+        if z0 in (S.Infinity, S.ImaginaryUnit*S.Infinity):
+            dir = "-"
+        elif z0 in (S.NegativeInfinity, S.ImaginaryUnit*S.NegativeInfinity):
+            dir = "+"
+
+        if(z0.has(z)):
+            raise NotImplementedError("Limits approaching a variable point are"
+                    " not supported (%s -> %s)" % (z, z0))
+        if isinstance(dir, str):
+            dir = Symbol(dir)
+        elif not isinstance(dir, Symbol):
+            raise TypeError("direction must be of type basestring or "
+                    "Symbol, not %s" % type(dir))
+        if str(dir) not in ('+', '-', '+-'):
+            raise ValueError("direction must be one of '+', '-' "
+                    "or '+-', not %s" % dir)
+
+        obj = Expr.__new__(cls)
+        obj._args = (e, z, z0, dir)
+        return obj
+
+
+    @property
+    def free_symbols(self):
+        e = self.args[0]
+        isyms = e.free_symbols
+        isyms.difference_update(self.args[1].free_symbols)
+        isyms.update(self.args[2].free_symbols)
+        return isyms
+
+
+    def pow_heuristics(self, e):
+        _, z, z0, _ = self.args
+        b1, e1 = e.base, e.exp
+        if not b1.has(z):
+            res = limit(e1*log(b1), z, z0)
+            return exp(res)
+
+        ex_lim = limit(e1, z, z0)
+        base_lim = limit(b1, z, z0)
+
+        if base_lim is S.One:
+            if ex_lim in (S.Infinity, S.NegativeInfinity):
+                res = limit(e1*(b1 - 1), z, z0)
+                return exp(res)
+        if base_lim is S.NegativeInfinity and ex_lim is S.Infinity:
+            return S.ComplexInfinity
+
+
+    def doit(self, **hints):
+        """Evaluates the limit.
+
+        Parameters
+        ==========
+
+        deep : bool, optional (default: True)
+            Invoke the ``doit`` method of the expressions involved before
+            taking the limit.
+
+        hints : optional keyword arguments
+            To be passed to ``doit`` methods; only used if deep is True.
+        """
+
+        e, z, z0, dir = self.args
+
+        if str(dir) == '+-':
+            r = limit(e, z, z0, dir='+')
+            l = limit(e, z, z0, dir='-')
+            if isinstance(r, Limit) and isinstance(l, Limit):
+                if r.args[0] == l.args[0]:
+                    return self
+            if r == l:
+                return l
+            if r.is_infinite and l.is_infinite:
+                return S.ComplexInfinity
+            raise ValueError("The limit does not exist since "
+                             "left hand limit = %s and right hand limit = %s"
+                             % (l, r))
+
+        if z0 is S.ComplexInfinity:
+            raise NotImplementedError("Limits at complex "
+                                    "infinity are not implemented")
+
+        if z0.is_infinite:
+            cdir = sign(z0)
+            cdir = cdir/abs(cdir)
+            e = e.subs(z, cdir*z)
+            dir = "-"
+            z0 = S.Infinity
+
+        if hints.get('deep', True):
+            e = e.doit(**hints)
+            z = z.doit(**hints)
+            z0 = z0.doit(**hints)
+
+        if e == z:
+            return z0
+
+        if not e.has(z):
+            return e
+
+        if z0 is S.NaN:
+            return S.NaN
+
+        if e.has(*_illegal):
+            return self
+
+        if e.is_Order:
+            return Order(limit(e.expr, z, z0), *e.args[1:])
+
+        cdir = S.Zero
+        if str(dir) == "+":
+            cdir = S.One
+        elif str(dir) == "-":
+            cdir = S.NegativeOne
+
+        def set_signs(expr):
+            if not expr.args:
+                return expr
+            newargs = tuple(set_signs(arg) for arg in expr.args)
+            if newargs != expr.args:
+                expr = expr.func(*newargs)
+            abs_flag = isinstance(expr, Abs)
+            arg_flag = isinstance(expr, arg)
+            sign_flag = isinstance(expr, sign)
+            if abs_flag or sign_flag or arg_flag:
+                try:
+                    sig = limit(expr.args[0], z, z0, dir)
+                    if sig.is_zero:
+                        sig = limit(1/expr.args[0], z, z0, dir)
+                except NotImplementedError:
+                    return expr
+                else:
+                    if sig.is_extended_real:
+                        if (sig < 0) == True:
+                            return (-expr.args[0] if abs_flag else
+                                    S.NegativeOne if sign_flag else S.Pi)
+                        elif (sig > 0) == True:
+                            return (expr.args[0] if abs_flag else
+                                    S.One if sign_flag else S.Zero)
+            return expr
+
+        if e.has(Float):
+            # Convert floats like 0.5 to exact SymPy numbers like S.Half, to
+            # prevent rounding errors which can lead to unexpected execution
+            # of conditional blocks that work on comparisons
+            # Also see comments in https://github.com/sympy/sympy/issues/19453
+            from sympy.simplify.simplify import nsimplify
+            e = nsimplify(e)
+        e = set_signs(e)
+
+
+        if e.is_meromorphic(z, z0):
+            if z0 is S.Infinity:
+                newe = e.subs(z, 1/z)
+                # cdir changes sign as oo- should become 0+
+                cdir = -cdir
+            else:
+                newe = e.subs(z, z + z0)
+            try:
+                coeff, ex = newe.leadterm(z, cdir=cdir)
+            except ValueError:
+                pass
+            else:
+                if ex > 0:
+                    return S.Zero
+                elif ex == 0:
+                    return coeff
+                if cdir == 1 or not(int(ex) & 1):
+                    return S.Infinity*sign(coeff)
+                elif cdir == -1:
+                    return S.NegativeInfinity*sign(coeff)
+                else:
+                    return S.ComplexInfinity
+
+        if z0 is S.Infinity:
+            if e.is_Mul:
+                e = factor_terms(e)
+            dummy = Dummy('z', positive=z.is_positive, negative=z.is_negative, real=z.is_real)
+            newe = e.subs(z, 1/dummy)
+            # cdir changes sign as oo- should become 0+
+            cdir = -cdir
+            newz = dummy
+        else:
+            newe = e.subs(z, z + z0)
+            newz = z
+        try:
+            coeff, ex = newe.leadterm(newz, cdir=cdir)
+        except (ValueError, NotImplementedError, PoleError):
+            # The NotImplementedError catching is for custom functions
+            from sympy.simplify.powsimp import powsimp
+            e = powsimp(e)
+            if e.is_Pow:
+                r = self.pow_heuristics(e)
+                if r is not None:
+                    return r
+            try:
+                coeff = newe.as_leading_term(newz, cdir=cdir)
+                if coeff != newe and (coeff.has(exp) or coeff.has(S.Exp1)):
+                    return gruntz(coeff, newz, 0, "-" if re(cdir).is_negative else "+")
+            except (ValueError, NotImplementedError, PoleError):
+                pass
+        else:
+            if isinstance(coeff, AccumBounds) and ex == S.Zero:
+                return coeff
+            if coeff.has(S.Infinity, S.NegativeInfinity, S.ComplexInfinity, S.NaN):
+                return self
+            if not coeff.has(newz):
+                if ex.is_positive:
+                    return S.Zero
+                elif ex == 0:
+                    return coeff
+                elif ex.is_negative:
+                    if cdir == 1:
+                        return S.Infinity*sign(coeff)
+                    elif cdir == -1:
+                        return S.NegativeInfinity*sign(coeff)*S.NegativeOne**(S.One + ex)
+                    else:
+                        return S.ComplexInfinity
+                else:
+                    raise NotImplementedError("Not sure of sign of %s" % ex)
+
+        # gruntz fails on factorials but works with the gamma function
+        # If no factorial term is present, e should remain unchanged.
+        # factorial is defined to be zero for negative inputs (which
+        # differs from gamma) so only rewrite for non-negative z0.
+        if z0.is_extended_nonnegative:
+            e = e.rewrite(factorial, gamma)
+
+        l = None
+
+        try:
+            r = gruntz(e, z, z0, dir)
+            if r is S.NaN or l is S.NaN:
+                raise PoleError()
+        except (PoleError, ValueError):
+            if l is not None:
+                raise
+            r = heuristics(e, z, z0, dir)
+            if r is None:
+                return self
+
+        return r
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/limitseq.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/limitseq.py
new file mode 100644
index 0000000000000000000000000000000000000000..ceac4e7b63bfc09d9dfc26c12c7d2acc8b8d44da
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/limitseq.py
@@ -0,0 +1,257 @@
+"""Limits of sequences"""
+
+from sympy.calculus.accumulationbounds import AccumulationBounds
+from sympy.core.add import Add
+from sympy.core.function import PoleError
+from sympy.core.power import Pow
+from sympy.core.singleton import S
+from sympy.core.symbol import Dummy
+from sympy.core.sympify import sympify
+from sympy.functions.combinatorial.numbers import fibonacci
+from sympy.functions.combinatorial.factorials import factorial, subfactorial
+from sympy.functions.special.gamma_functions import gamma
+from sympy.functions.elementary.complexes import Abs
+from sympy.functions.elementary.miscellaneous import Max, Min
+from sympy.functions.elementary.trigonometric import cos, sin
+from sympy.series.limits import Limit
+
+
+def difference_delta(expr, n=None, step=1):
+    """Difference Operator.
+
+    Explanation
+    ===========
+
+    Discrete analog of differential operator. Given a sequence x[n],
+    returns the sequence x[n + step] - x[n].
+
+    Examples
+    ========
+
+    >>> from sympy import difference_delta as dd
+    >>> from sympy.abc import n
+    >>> dd(n*(n + 1), n)
+    2*n + 2
+    >>> dd(n*(n + 1), n, 2)
+    4*n + 6
+
+    References
+    ==========
+
+    .. [1] https://reference.wolfram.com/language/ref/DifferenceDelta.html
+    """
+    expr = sympify(expr)
+
+    if n is None:
+        f = expr.free_symbols
+        if len(f) == 1:
+            n = f.pop()
+        elif len(f) == 0:
+            return S.Zero
+        else:
+            raise ValueError("Since there is more than one variable in the"
+                             " expression, a variable must be supplied to"
+                             " take the difference of %s" % expr)
+    step = sympify(step)
+    if step.is_number is False or step.is_finite is False:
+        raise ValueError("Step should be a finite number.")
+
+    if hasattr(expr, '_eval_difference_delta'):
+        result = expr._eval_difference_delta(n, step)
+        if result:
+            return result
+
+    return expr.subs(n, n + step) - expr
+
+
+def dominant(expr, n):
+    """Finds the dominant term in a sum, that is a term that dominates
+    every other term.
+
+    Explanation
+    ===========
+
+    If limit(a/b, n, oo) is oo then a dominates b.
+    If limit(a/b, n, oo) is 0 then b dominates a.
+    Otherwise, a and b are comparable.
+
+    If there is no unique dominant term, then returns ``None``.
+
+    Examples
+    ========
+
+    >>> from sympy import Sum
+    >>> from sympy.series.limitseq import dominant
+    >>> from sympy.abc import n, k
+    >>> dominant(5*n**3 + 4*n**2 + n + 1, n)
+    5*n**3
+    >>> dominant(2**n + Sum(k, (k, 0, n)), n)
+    2**n
+
+    See Also
+    ========
+
+    sympy.series.limitseq.dominant
+    """
+    terms = Add.make_args(expr.expand(func=True))
+    term0 = terms[-1]
+    comp = [term0]  # comparable terms
+    for t in terms[:-1]:
+        r = term0/t
+        e = r.gammasimp()
+        if e == r:
+            e = r.factor()
+        l = limit_seq(e, n)
+        if l is None:
+            return None
+        elif l.is_zero:
+            term0 = t
+            comp = [term0]
+        elif l not in [S.Infinity, S.NegativeInfinity]:
+            comp.append(t)
+    if len(comp) > 1:
+        return None
+    return term0
+
+
+def _limit_inf(expr, n):
+    try:
+        return Limit(expr, n, S.Infinity).doit(deep=False)
+    except (NotImplementedError, PoleError):
+        return None
+
+
+def _limit_seq(expr, n, trials):
+    from sympy.concrete.summations import Sum
+
+    for i in range(trials):
+        if not expr.has(Sum):
+            result = _limit_inf(expr, n)
+            if result is not None:
+                return result
+
+        num, den = expr.as_numer_denom()
+        if not den.has(n) or not num.has(n):
+            result = _limit_inf(expr.doit(), n)
+            if result is not None:
+                return result
+            return None
+
+        num, den = (difference_delta(t.expand(), n) for t in [num, den])
+        expr = (num / den).gammasimp()
+
+        if not expr.has(Sum):
+            result = _limit_inf(expr, n)
+            if result is not None:
+                return result
+
+        num, den = expr.as_numer_denom()
+
+        num = dominant(num, n)
+        if num is None:
+            return None
+
+        den = dominant(den, n)
+        if den is None:
+            return None
+
+        expr = (num / den).gammasimp()
+
+
+def limit_seq(expr, n=None, trials=5):
+    """Finds the limit of a sequence as index ``n`` tends to infinity.
+
+    Parameters
+    ==========
+
+    expr : Expr
+        SymPy expression for the ``n-th`` term of the sequence
+    n : Symbol, optional
+        The index of the sequence, an integer that tends to positive
+        infinity. If None, inferred from the expression unless it has
+        multiple symbols.
+    trials: int, optional
+        The algorithm is highly recursive. ``trials`` is a safeguard from
+        infinite recursion in case the limit is not easily computed by the
+        algorithm. Try increasing ``trials`` if the algorithm returns ``None``.
+
+    Admissible Terms
+    ================
+
+    The algorithm is designed for sequences built from rational functions,
+    indefinite sums, and indefinite products over an indeterminate n. Terms of
+    alternating sign are also allowed, but more complex oscillatory behavior is
+    not supported.
+
+    Examples
+    ========
+
+    >>> from sympy import limit_seq, Sum, binomial
+    >>> from sympy.abc import n, k, m
+    >>> limit_seq((5*n**3 + 3*n**2 + 4) / (3*n**3 + 4*n - 5), n)
+    5/3
+    >>> limit_seq(binomial(2*n, n) / Sum(binomial(2*k, k), (k, 1, n)), n)
+    3/4
+    >>> limit_seq(Sum(k**2 * Sum(2**m/m, (m, 1, k)), (k, 1, n)) / (2**n*n), n)
+    4
+
+    See Also
+    ========
+
+    sympy.series.limitseq.dominant
+
+    References
+    ==========
+
+    .. [1] Computing Limits of Sequences - Manuel Kauers
+    """
+
+    from sympy.concrete.summations import Sum
+    if n is None:
+        free = expr.free_symbols
+        if len(free) == 1:
+            n = free.pop()
+        elif not free:
+            return expr
+        else:
+            raise ValueError("Expression has more than one variable. "
+                             "Please specify a variable.")
+    elif n not in expr.free_symbols:
+        return expr
+
+    expr = expr.rewrite(fibonacci, S.GoldenRatio)
+    expr = expr.rewrite(factorial, subfactorial, gamma)
+    n_ = Dummy("n", integer=True, positive=True)
+    n1 = Dummy("n", odd=True, positive=True)
+    n2 = Dummy("n", even=True, positive=True)
+
+    # If there is a negative term raised to a power involving n, or a
+    # trigonometric function, then consider even and odd n separately.
+    powers = (p.as_base_exp() for p in expr.atoms(Pow))
+    if (any(b.is_negative and e.has(n) for b, e in powers) or
+            expr.has(cos, sin)):
+        L1 = _limit_seq(expr.xreplace({n: n1}), n1, trials)
+        if L1 is not None:
+            L2 = _limit_seq(expr.xreplace({n: n2}), n2, trials)
+            if L1 != L2:
+                if L1.is_comparable and L2.is_comparable:
+                    return AccumulationBounds(Min(L1, L2), Max(L1, L2))
+                else:
+                    return None
+    else:
+        L1 = _limit_seq(expr.xreplace({n: n_}), n_, trials)
+    if L1 is not None:
+        return L1
+    else:
+        if expr.is_Add:
+            limits = [limit_seq(term, n, trials) for term in expr.args]
+            if any(result is None for result in limits):
+                return None
+            else:
+                return Add(*limits)
+        # Maybe the absolute value is easier to deal with (though not if
+        # it has a Sum). If it tends to 0, the limit is 0.
+        elif not expr.has(Sum):
+            lim = _limit_seq(Abs(expr.xreplace({n: n_})), n_, trials)
+            if lim is not None and lim.is_zero:
+                return S.Zero
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/order.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/order.py
new file mode 100644
index 0000000000000000000000000000000000000000..9cfd4309c2b7094ce02feab129e5f051c442d8cd
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/order.py
@@ -0,0 +1,522 @@
+from sympy.core import S, sympify, Expr, Dummy, Add, Mul
+from sympy.core.cache import cacheit
+from sympy.core.containers import Tuple
+from sympy.core.function import Function, PoleError, expand_power_base, expand_log
+from sympy.core.sorting import default_sort_key
+from sympy.functions.elementary.exponential import exp, log
+from sympy.sets.sets import Complement
+from sympy.utilities.iterables import uniq, is_sequence
+
+
+class Order(Expr):
+    r""" Represents the limiting behavior of some function.
+
+    Explanation
+    ===========
+
+    The order of a function characterizes the function based on the limiting
+    behavior of the function as it goes to some limit. Only taking the limit
+    point to be a number is currently supported. This is expressed in
+    big O notation [1]_.
+
+    The formal definition for the order of a function `g(x)` about a point `a`
+    is such that `g(x) = O(f(x))` as `x \rightarrow a` if and only if there
+    exists a `\delta > 0` and an `M > 0` such that `|g(x)| \leq M|f(x)|` for
+    `|x-a| < \delta`.  This is equivalent to `\limsup_{x \rightarrow a}
+    |g(x)/f(x)| < \infty`.
+
+    Let's illustrate it on the following example by taking the expansion of
+    `\sin(x)` about 0:
+
+    .. math ::
+        \sin(x) = x - x^3/3! + O(x^5)
+
+    where in this case `O(x^5) = x^5/5! - x^7/7! + \cdots`. By the definition
+    of `O`, there is a `\delta > 0` and an `M` such that:
+
+    .. math ::
+        |x^5/5! - x^7/7! + ....| <= M|x^5| \text{ for } |x| < \delta
+
+    or by the alternate definition:
+
+    .. math ::
+        \lim_{x \rightarrow 0} | (x^5/5! - x^7/7! + ....) / x^5| < \infty
+
+    which surely is true, because
+
+    .. math ::
+        \lim_{x \rightarrow 0} | (x^5/5! - x^7/7! + ....) / x^5| = 1/5!
+
+
+    As it is usually used, the order of a function can be intuitively thought
+    of representing all terms of powers greater than the one specified. For
+    example, `O(x^3)` corresponds to any terms proportional to `x^3,
+    x^4,\ldots` and any higher power. For a polynomial, this leaves terms
+    proportional to `x^2`, `x` and constants.
+
+    Examples
+    ========
+
+    >>> from sympy import O, oo, cos, pi
+    >>> from sympy.abc import x, y
+
+    >>> O(x + x**2)
+    O(x)
+    >>> O(x + x**2, (x, 0))
+    O(x)
+    >>> O(x + x**2, (x, oo))
+    O(x**2, (x, oo))
+
+    >>> O(1 + x*y)
+    O(1, x, y)
+    >>> O(1 + x*y, (x, 0), (y, 0))
+    O(1, x, y)
+    >>> O(1 + x*y, (x, oo), (y, oo))
+    O(x*y, (x, oo), (y, oo))
+
+    >>> O(1) in O(1, x)
+    True
+    >>> O(1, x) in O(1)
+    False
+    >>> O(x) in O(1, x)
+    True
+    >>> O(x**2) in O(x)
+    True
+
+    >>> O(x)*x
+    O(x**2)
+    >>> O(x) - O(x)
+    O(x)
+    >>> O(cos(x))
+    O(1)
+    >>> O(cos(x), (x, pi/2))
+    O(x - pi/2, (x, pi/2))
+
+    References
+    ==========
+
+    .. [1] `Big O notation `_
+
+    Notes
+    =====
+
+    In ``O(f(x), x)`` the expression ``f(x)`` is assumed to have a leading
+    term.  ``O(f(x), x)`` is automatically transformed to
+    ``O(f(x).as_leading_term(x),x)``.
+
+        ``O(expr*f(x), x)`` is ``O(f(x), x)``
+
+        ``O(expr, x)`` is ``O(1)``
+
+        ``O(0, x)`` is 0.
+
+    Multivariate O is also supported:
+
+        ``O(f(x, y), x, y)`` is transformed to
+        ``O(f(x, y).as_leading_term(x,y).as_leading_term(y), x, y)``
+
+    In the multivariate case, it is assumed the limits w.r.t. the various
+    symbols commute.
+
+    If no symbols are passed then all symbols in the expression are used
+    and the limit point is assumed to be zero.
+
+    """
+
+    is_Order = True
+
+    __slots__ = ()
+
+    @cacheit
+    def __new__(cls, expr, *args, **kwargs):
+        expr = sympify(expr)
+
+        if not args:
+            if expr.is_Order:
+                variables = expr.variables
+                point = expr.point
+            else:
+                variables = list(expr.free_symbols)
+                point = [S.Zero]*len(variables)
+        else:
+            args = list(args if is_sequence(args) else [args])
+            variables, point = [], []
+            if is_sequence(args[0]):
+                for a in args:
+                    v, p = list(map(sympify, a))
+                    variables.append(v)
+                    point.append(p)
+            else:
+                variables = list(map(sympify, args))
+                point = [S.Zero]*len(variables)
+
+        if not all(v.is_symbol for v in variables):
+            raise TypeError('Variables are not symbols, got %s' % variables)
+
+        if len(list(uniq(variables))) != len(variables):
+            raise ValueError('Variables are supposed to be unique symbols, got %s' % variables)
+
+        if expr.is_Order:
+            expr_vp = dict(expr.args[1:])
+            new_vp = dict(expr_vp)
+            vp = dict(zip(variables, point))
+            for v, p in vp.items():
+                if v in new_vp.keys():
+                    if p != new_vp[v]:
+                        raise NotImplementedError(
+                            "Mixing Order at different points is not supported.")
+                else:
+                    new_vp[v] = p
+            if set(expr_vp.keys()) == set(new_vp.keys()):
+                return expr
+            else:
+                variables = list(new_vp.keys())
+                point = [new_vp[v] for v in variables]
+
+        if expr is S.NaN:
+            return S.NaN
+
+        if any(x in p.free_symbols for x in variables for p in point):
+            raise ValueError('Got %s as a point.' % point)
+
+        if variables:
+            if any(p != point[0] for p in point):
+                raise NotImplementedError(
+                    "Multivariable orders at different points are not supported.")
+            if point[0] in (S.Infinity, S.Infinity*S.ImaginaryUnit):
+                s = {k: 1/Dummy() for k in variables}
+                rs = {1/v: 1/k for k, v in s.items()}
+                ps = [S.Zero for p in point]
+            elif point[0] in (S.NegativeInfinity, S.NegativeInfinity*S.ImaginaryUnit):
+                s = {k: -1/Dummy() for k in variables}
+                rs = {-1/v: -1/k for k, v in s.items()}
+                ps = [S.Zero for p in point]
+            elif point[0] is not S.Zero:
+                s = {k: Dummy() + point[0] for k in variables}
+                rs = {(v - point[0]).together(): k - point[0] for k, v in s.items()}
+                ps = [S.Zero for p in point]
+            else:
+                s = ()
+                rs = ()
+                ps = list(point)
+
+            expr = expr.subs(s)
+
+            if expr.is_Add:
+                expr = expr.factor()
+
+            if s:
+                args = tuple([r[0] for r in rs.items()])
+            else:
+                args = tuple(variables)
+
+            if len(variables) > 1:
+                # XXX: better way?  We need this expand() to
+                # workaround e.g: expr = x*(x + y).
+                # (x*(x + y)).as_leading_term(x, y) currently returns
+                # x*y (wrong order term!).  That's why we want to deal with
+                # expand()'ed expr (handled in "if expr.is_Add" branch below).
+                expr = expr.expand()
+
+            old_expr = None
+            while old_expr != expr:
+                old_expr = expr
+                if expr.is_Add:
+                    lst = expr.extract_leading_order(args)
+                    expr = Add(*[f.expr for (e, f) in lst])
+
+                elif expr:
+                    try:
+                        expr = expr.as_leading_term(*args)
+                    except PoleError:
+                        if isinstance(expr, Function) or\
+                                all(isinstance(arg, Function) for arg in expr.args):
+                            # It is not possible to simplify an expression
+                            # containing only functions (which raise error on
+                            # call to leading term) further
+                            pass
+                        else:
+                            orders = []
+                            pts = tuple(zip(args, ps))
+                            for arg in expr.args:
+                                try:
+                                    lt = arg.as_leading_term(*args)
+                                except PoleError:
+                                    lt = arg
+                                if lt not in args:
+                                    order = Order(lt)
+                                else:
+                                    order = Order(lt, *pts)
+                                orders.append(order)
+                            if expr.is_Add:
+                                new_expr = Order(Add(*orders), *pts)
+                                if new_expr.is_Add:
+                                    new_expr = Order(Add(*[a.expr for a in new_expr.args]), *pts)
+                                expr = new_expr.expr
+                            elif expr.is_Mul:
+                                expr = Mul(*[a.expr for a in orders])
+                            elif expr.is_Pow:
+                                e = expr.exp
+                                b = expr.base
+                                expr = exp(e * log(b))
+
+                    # It would probably be better to handle this somewhere
+                    # else. This is needed for a testcase in which there is a
+                    # symbol with the assumptions zero=True.
+                    if expr.is_zero:
+                        expr = S.Zero
+                    else:
+                        expr = expr.as_independent(*args, as_Add=False)[1]
+
+                    expr = expand_power_base(expr)
+                    expr = expand_log(expr)
+
+                    if len(args) == 1:
+                        # The definition of O(f(x)) symbol explicitly stated that
+                        # the argument of f(x) is irrelevant.  That's why we can
+                        # combine some power exponents (only "on top" of the
+                        # expression tree for f(x)), e.g.:
+                        # x**p * (-x)**q -> x**(p+q) for real p, q.
+                        x = args[0]
+                        margs = list(Mul.make_args(
+                            expr.as_independent(x, as_Add=False)[1]))
+
+                        for i, t in enumerate(margs):
+                            if t.is_Pow:
+                                b, q = t.args
+                                if b in (x, -x) and q.is_real and not q.has(x):
+                                    margs[i] = x**q
+                                elif b.is_Pow and not b.exp.has(x):
+                                    b, r = b.args
+                                    if b in (x, -x) and r.is_real:
+                                        margs[i] = x**(r*q)
+                                elif b.is_Mul and b.args[0] is S.NegativeOne:
+                                    b = -b
+                                    if b.is_Pow and not b.exp.has(x):
+                                        b, r = b.args
+                                        if b in (x, -x) and r.is_real:
+                                            margs[i] = x**(r*q)
+
+                        expr = Mul(*margs)
+
+            expr = expr.subs(rs)
+
+        if expr.is_Order:
+            expr = expr.expr
+
+        if not expr.has(*variables) and not expr.is_zero:
+            expr = S.One
+
+        # create Order instance:
+        vp = dict(zip(variables, point))
+        variables.sort(key=default_sort_key)
+        point = [vp[v] for v in variables]
+        args = (expr,) + Tuple(*zip(variables, point))
+        obj = Expr.__new__(cls, *args)
+        return obj
+
+    def _eval_nseries(self, x, n, logx, cdir=0):
+        return self
+
+    @property
+    def expr(self):
+        return self.args[0]
+
+    @property
+    def variables(self):
+        if self.args[1:]:
+            return tuple(x[0] for x in self.args[1:])
+        else:
+            return ()
+
+    @property
+    def point(self):
+        if self.args[1:]:
+            return tuple(x[1] for x in self.args[1:])
+        else:
+            return ()
+
+    @property
+    def free_symbols(self):
+        return self.expr.free_symbols | set(self.variables)
+
+    def _eval_power(b, e):
+        if e.is_Number and e.is_nonnegative:
+            return b.func(b.expr ** e, *b.args[1:])
+        if e == O(1):
+            return b
+        return
+
+    def as_expr_variables(self, order_symbols):
+        if order_symbols is None:
+            order_symbols = self.args[1:]
+        else:
+            if (not all(o[1] == order_symbols[0][1] for o in order_symbols) and
+                    not all(p == self.point[0] for p in self.point)):  # pragma: no cover
+                raise NotImplementedError('Order at points other than 0 '
+                    'or oo not supported, got %s as a point.' % self.point)
+            if order_symbols and order_symbols[0][1] != self.point[0]:
+                raise NotImplementedError(
+                        "Multiplying Order at different points is not supported.")
+            order_symbols = dict(order_symbols)
+            for s, p in dict(self.args[1:]).items():
+                if s not in order_symbols.keys():
+                    order_symbols[s] = p
+            order_symbols = sorted(order_symbols.items(), key=lambda x: default_sort_key(x[0]))
+        return self.expr, tuple(order_symbols)
+
+    def removeO(self):
+        return S.Zero
+
+    def getO(self):
+        return self
+
+    @cacheit
+    def contains(self, expr):
+        r"""
+        Return True if expr belongs to Order(self.expr, \*self.variables).
+        Return False if self belongs to expr.
+        Return None if the inclusion relation cannot be determined
+        (e.g. when self and expr have different symbols).
+        """
+        expr = sympify(expr)
+        if expr.is_zero:
+            return True
+        if expr is S.NaN:
+            return False
+        point = self.point[0] if self.point else S.Zero
+        if expr.is_Order:
+            if (any(p != point for p in expr.point) or
+                   any(p != point for p in self.point)):
+                return None
+            if expr.expr == self.expr:
+                # O(1) + O(1), O(1) + O(1, x), etc.
+                return all(x in self.args[1:] for x in expr.args[1:])
+            if expr.expr.is_Add:
+                return all(self.contains(x) for x in expr.expr.args)
+            if self.expr.is_Add and point.is_zero:
+                return any(self.func(x, *self.args[1:]).contains(expr)
+                            for x in self.expr.args)
+            if self.variables and expr.variables:
+                common_symbols = tuple(
+                    [s for s in self.variables if s in expr.variables])
+            elif self.variables:
+                common_symbols = self.variables
+            else:
+                common_symbols = expr.variables
+            if not common_symbols:
+                return None
+            if (self.expr.is_Pow and len(self.variables) == 1
+                and self.variables == expr.variables):
+                    symbol = self.variables[0]
+                    other = expr.expr.as_independent(symbol, as_Add=False)[1]
+                    if (other.is_Pow and other.base == symbol and
+                        self.expr.base == symbol):
+                            if point.is_zero:
+                                rv = (self.expr.exp - other.exp).is_nonpositive
+                            if point.is_infinite:
+                                rv = (self.expr.exp - other.exp).is_nonnegative
+                            if rv is not None:
+                                return rv
+
+            from sympy.simplify.powsimp import powsimp
+            r = None
+            ratio = self.expr/expr.expr
+            ratio = powsimp(ratio, deep=True, combine='exp')
+            for s in common_symbols:
+                from sympy.series.limits import Limit
+                l = Limit(ratio, s, point).doit(heuristics=False)
+                if not isinstance(l, Limit):
+                    l = l != 0
+                else:
+                    l = None
+                if r is None:
+                    r = l
+                else:
+                    if r != l:
+                        return
+            return r
+
+        if self.expr.is_Pow and len(self.variables) == 1:
+            symbol = self.variables[0]
+            other = expr.as_independent(symbol, as_Add=False)[1]
+            if (other.is_Pow and other.base == symbol and
+                self.expr.base == symbol):
+                    if point.is_zero:
+                        rv = (self.expr.exp - other.exp).is_nonpositive
+                    if point.is_infinite:
+                        rv = (self.expr.exp - other.exp).is_nonnegative
+                    if rv is not None:
+                        return rv
+
+        obj = self.func(expr, *self.args[1:])
+        return self.contains(obj)
+
+    def __contains__(self, other):
+        result = self.contains(other)
+        if result is None:
+            raise TypeError('contains did not evaluate to a bool')
+        return result
+
+    def _eval_subs(self, old, new):
+        if old in self.variables:
+            newexpr = self.expr.subs(old, new)
+            i = self.variables.index(old)
+            newvars = list(self.variables)
+            newpt = list(self.point)
+            if new.is_symbol:
+                newvars[i] = new
+            else:
+                syms = new.free_symbols
+                if len(syms) == 1 or old in syms:
+                    if old in syms:
+                        var = self.variables[i]
+                    else:
+                        var = syms.pop()
+                    # First, try to substitute self.point in the "new"
+                    # expr to see if this is a fixed point.
+                    # E.g.  O(y).subs(y, sin(x))
+                    from sympy import limit
+                    if new.has(Order) and limit(new.getO().expr, var, new.getO().point[0]) == self.point[i]:
+                        point = new.getO().point[0]
+                        return Order(newexpr, *zip([var], [point]))
+                    else:
+                        point = new.subs(var, self.point[i])
+                    if point != self.point[i]:
+                        from sympy.solvers.solveset import solveset
+                        d = Dummy()
+                        sol = solveset(old - new.subs(var, d), d)
+                        if isinstance(sol, Complement):
+                            e1 = sol.args[0]
+                            e2 = sol.args[1]
+                            sol = set(e1) - set(e2)
+                        res = [dict(zip((d, ), sol))]
+                        point = d.subs(res[0]).limit(old, self.point[i])
+                    newvars[i] = var
+                    newpt[i] = point
+                elif old not in syms:
+                    del newvars[i], newpt[i]
+                    if not syms and new == self.point[i]:
+                        newvars.extend(syms)
+                        newpt.extend([S.Zero]*len(syms))
+                else:
+                    return
+            return Order(newexpr, *zip(newvars, newpt))
+
+    def _eval_conjugate(self):
+        expr = self.expr._eval_conjugate()
+        if expr is not None:
+            return self.func(expr, *self.args[1:])
+
+    def _eval_derivative(self, x):
+        return self.func(self.expr.diff(x), *self.args[1:]) or self
+
+    def _eval_transpose(self):
+        expr = self.expr._eval_transpose()
+        if expr is not None:
+            return self.func(expr, *self.args[1:])
+
+    def __neg__(self):
+        return self
+
+O = Order
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/residues.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/residues.py
new file mode 100644
index 0000000000000000000000000000000000000000..a426f9e799bd040eea5124f718c2fa43e5de026b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/residues.py
@@ -0,0 +1,73 @@
+"""
+This module implements the Residue function and related tools for working
+with residues.
+"""
+
+from sympy.core.mul import Mul
+from sympy.core.singleton import S
+from sympy.core.sympify import sympify
+from sympy.utilities.timeutils import timethis
+
+
+@timethis('residue')
+def residue(expr, x, x0):
+    """
+    Finds the residue of ``expr`` at the point x=x0.
+
+    The residue is defined as the coefficient of ``1/(x-x0)`` in the power series
+    expansion about ``x=x0``.
+
+    Examples
+    ========
+
+    >>> from sympy import Symbol, residue, sin
+    >>> x = Symbol("x")
+    >>> residue(1/x, x, 0)
+    1
+    >>> residue(1/x**2, x, 0)
+    0
+    >>> residue(2/sin(x), x, 0)
+    2
+
+    This function is essential for the Residue Theorem [1].
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Residue_theorem
+    """
+    # The current implementation uses series expansion to
+    # calculate it. A more general implementation is explained in
+    # the section 5.6 of the Bronstein's book {M. Bronstein:
+    # Symbolic Integration I, Springer Verlag (2005)}. For purely
+    # rational functions, the algorithm is much easier. See
+    # sections 2.4, 2.5, and 2.7 (this section actually gives an
+    # algorithm for computing any Laurent series coefficient for
+    # a rational function). The theory in section 2.4 will help to
+    # understand why the resultant works in the general algorithm.
+    # For the definition of a resultant, see section 1.4 (and any
+    # previous sections for more review).
+
+    from sympy.series.order import Order
+    from sympy.simplify.radsimp import collect
+    expr = sympify(expr)
+    if x0 != 0:
+        expr = expr.subs(x, x + x0)
+    for n in (0, 1, 2, 4, 8, 16, 32):
+        s = expr.nseries(x, n=n)
+        if not s.has(Order) or s.getn() >= 0:
+            break
+    s = collect(s.removeO(), x)
+    if s.is_Add:
+        args = s.args
+    else:
+        args = [s]
+    res = S.Zero
+    for arg in args:
+        c, m = arg.as_coeff_mul(x)
+        m = Mul(*m)
+        if not (m in (S.One, x) or (m.is_Pow and m.exp.is_Integer)):
+            raise NotImplementedError('term of unexpected form: %s' % m)
+        if m == 1/x:
+            res += c
+    return res
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/sequences.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/sequences.py
new file mode 100644
index 0000000000000000000000000000000000000000..7787515ddb05afaf34751bf451544935723d0921
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/sequences.py
@@ -0,0 +1,1239 @@
+from sympy.core.basic import Basic
+from sympy.core.cache import cacheit
+from sympy.core.containers import Tuple
+from sympy.core.decorators import call_highest_priority
+from sympy.core.parameters import global_parameters
+from sympy.core.function import AppliedUndef, expand
+from sympy.core.mul import Mul
+from sympy.core.numbers import Integer
+from sympy.core.relational import Eq
+from sympy.core.singleton import S, Singleton
+from sympy.core.sorting import ordered
+from sympy.core.symbol import Dummy, Symbol, Wild
+from sympy.core.sympify import sympify
+from sympy.matrices import Matrix
+from sympy.polys import lcm, factor
+from sympy.sets.sets import Interval, Intersection
+from sympy.tensor.indexed import Idx
+from sympy.utilities.iterables import flatten, is_sequence, iterable
+
+
+###############################################################################
+#                            SEQUENCES                                        #
+###############################################################################
+
+
+class SeqBase(Basic):
+    """Base class for sequences"""
+
+    is_commutative = True
+    _op_priority = 15
+
+    @staticmethod
+    def _start_key(expr):
+        """Return start (if possible) else S.Infinity.
+
+        adapted from Set._infimum_key
+        """
+        try:
+            start = expr.start
+        except NotImplementedError:
+            start = S.Infinity
+        return start
+
+    def _intersect_interval(self, other):
+        """Returns start and stop.
+
+        Takes intersection over the two intervals.
+        """
+        interval = Intersection(self.interval, other.interval)
+        return interval.inf, interval.sup
+
+    @property
+    def gen(self):
+        """Returns the generator for the sequence"""
+        raise NotImplementedError("(%s).gen" % self)
+
+    @property
+    def interval(self):
+        """The interval on which the sequence is defined"""
+        raise NotImplementedError("(%s).interval" % self)
+
+    @property
+    def start(self):
+        """The starting point of the sequence. This point is included"""
+        raise NotImplementedError("(%s).start" % self)
+
+    @property
+    def stop(self):
+        """The ending point of the sequence. This point is included"""
+        raise NotImplementedError("(%s).stop" % self)
+
+    @property
+    def length(self):
+        """Length of the sequence"""
+        raise NotImplementedError("(%s).length" % self)
+
+    @property
+    def variables(self):
+        """Returns a tuple of variables that are bounded"""
+        return ()
+
+    @property
+    def free_symbols(self):
+        """
+        This method returns the symbols in the object, excluding those
+        that take on a specific value (i.e. the dummy symbols).
+
+        Examples
+        ========
+
+        >>> from sympy import SeqFormula
+        >>> from sympy.abc import n, m
+        >>> SeqFormula(m*n**2, (n, 0, 5)).free_symbols
+        {m}
+        """
+        return ({j for i in self.args for j in i.free_symbols
+                   .difference(self.variables)})
+
+    @cacheit
+    def coeff(self, pt):
+        """Returns the coefficient at point pt"""
+        if pt < self.start or pt > self.stop:
+            raise IndexError("Index %s out of bounds %s" % (pt, self.interval))
+        return self._eval_coeff(pt)
+
+    def _eval_coeff(self, pt):
+        raise NotImplementedError("The _eval_coeff method should be added to"
+                                  "%s to return coefficient so it is available"
+                                  "when coeff calls it."
+                                  % self.func)
+
+    def _ith_point(self, i):
+        """Returns the i'th point of a sequence.
+
+        Explanation
+        ===========
+
+        If start point is negative infinity, point is returned from the end.
+        Assumes the first point to be indexed zero.
+
+        Examples
+        =========
+
+        >>> from sympy import oo
+        >>> from sympy.series.sequences import SeqPer
+
+        bounded
+
+        >>> SeqPer((1, 2, 3), (-10, 10))._ith_point(0)
+        -10
+        >>> SeqPer((1, 2, 3), (-10, 10))._ith_point(5)
+        -5
+
+        End is at infinity
+
+        >>> SeqPer((1, 2, 3), (0, oo))._ith_point(5)
+        5
+
+        Starts at negative infinity
+
+        >>> SeqPer((1, 2, 3), (-oo, 0))._ith_point(5)
+        -5
+        """
+        if self.start is S.NegativeInfinity:
+            initial = self.stop
+        else:
+            initial = self.start
+
+        if self.start is S.NegativeInfinity:
+            step = -1
+        else:
+            step = 1
+
+        return initial + i*step
+
+    def _add(self, other):
+        """
+        Should only be used internally.
+
+        Explanation
+        ===========
+
+        self._add(other) returns a new, term-wise added sequence if self
+        knows how to add with other, otherwise it returns ``None``.
+
+        ``other`` should only be a sequence object.
+
+        Used within :class:`SeqAdd` class.
+        """
+        return None
+
+    def _mul(self, other):
+        """
+        Should only be used internally.
+
+        Explanation
+        ===========
+
+        self._mul(other) returns a new, term-wise multiplied sequence if self
+        knows how to multiply with other, otherwise it returns ``None``.
+
+        ``other`` should only be a sequence object.
+
+        Used within :class:`SeqMul` class.
+        """
+        return None
+
+    def coeff_mul(self, other):
+        """
+        Should be used when ``other`` is not a sequence. Should be
+        defined to define custom behaviour.
+
+        Examples
+        ========
+
+        >>> from sympy import SeqFormula
+        >>> from sympy.abc import n
+        >>> SeqFormula(n**2).coeff_mul(2)
+        SeqFormula(2*n**2, (n, 0, oo))
+
+        Notes
+        =====
+
+        '*' defines multiplication of sequences with sequences only.
+        """
+        return Mul(self, other)
+
+    def __add__(self, other):
+        """Returns the term-wise addition of 'self' and 'other'.
+
+        ``other`` should be a sequence.
+
+        Examples
+        ========
+
+        >>> from sympy import SeqFormula
+        >>> from sympy.abc import n
+        >>> SeqFormula(n**2) + SeqFormula(n**3)
+        SeqFormula(n**3 + n**2, (n, 0, oo))
+        """
+        if not isinstance(other, SeqBase):
+            raise TypeError('cannot add sequence and %s' % type(other))
+        return SeqAdd(self, other)
+
+    @call_highest_priority('__add__')
+    def __radd__(self, other):
+        return self + other
+
+    def __sub__(self, other):
+        """Returns the term-wise subtraction of ``self`` and ``other``.
+
+        ``other`` should be a sequence.
+
+        Examples
+        ========
+
+        >>> from sympy import SeqFormula
+        >>> from sympy.abc import n
+        >>> SeqFormula(n**2) - (SeqFormula(n))
+        SeqFormula(n**2 - n, (n, 0, oo))
+        """
+        if not isinstance(other, SeqBase):
+            raise TypeError('cannot subtract sequence and %s' % type(other))
+        return SeqAdd(self, -other)
+
+    @call_highest_priority('__sub__')
+    def __rsub__(self, other):
+        return (-self) + other
+
+    def __neg__(self):
+        """Negates the sequence.
+
+        Examples
+        ========
+
+        >>> from sympy import SeqFormula
+        >>> from sympy.abc import n
+        >>> -SeqFormula(n**2)
+        SeqFormula(-n**2, (n, 0, oo))
+        """
+        return self.coeff_mul(-1)
+
+    def __mul__(self, other):
+        """Returns the term-wise multiplication of 'self' and 'other'.
+
+        ``other`` should be a sequence. For ``other`` not being a
+        sequence see :func:`coeff_mul` method.
+
+        Examples
+        ========
+
+        >>> from sympy import SeqFormula
+        >>> from sympy.abc import n
+        >>> SeqFormula(n**2) * (SeqFormula(n))
+        SeqFormula(n**3, (n, 0, oo))
+        """
+        if not isinstance(other, SeqBase):
+            raise TypeError('cannot multiply sequence and %s' % type(other))
+        return SeqMul(self, other)
+
+    @call_highest_priority('__mul__')
+    def __rmul__(self, other):
+        return self * other
+
+    def __iter__(self):
+        for i in range(self.length):
+            pt = self._ith_point(i)
+            yield self.coeff(pt)
+
+    def __getitem__(self, index):
+        if isinstance(index, int):
+            index = self._ith_point(index)
+            return self.coeff(index)
+        elif isinstance(index, slice):
+            start, stop = index.start, index.stop
+            if start is None:
+                start = 0
+            if stop is None:
+                stop = self.length
+            return [self.coeff(self._ith_point(i)) for i in
+                    range(start, stop, index.step or 1)]
+
+    def find_linear_recurrence(self,n,d=None,gfvar=None):
+        r"""
+        Finds the shortest linear recurrence that satisfies the first n
+        terms of sequence of order `\leq` ``n/2`` if possible.
+        If ``d`` is specified, find shortest linear recurrence of order
+        `\leq` min(d, n/2) if possible.
+        Returns list of coefficients ``[b(1), b(2), ...]`` corresponding to the
+        recurrence relation ``x(n) = b(1)*x(n-1) + b(2)*x(n-2) + ...``
+        Returns ``[]`` if no recurrence is found.
+        If gfvar is specified, also returns ordinary generating function as a
+        function of gfvar.
+
+        Examples
+        ========
+
+        >>> from sympy import sequence, sqrt, oo, lucas
+        >>> from sympy.abc import n, x, y
+        >>> sequence(n**2).find_linear_recurrence(10, 2)
+        []
+        >>> sequence(n**2).find_linear_recurrence(10)
+        [3, -3, 1]
+        >>> sequence(2**n).find_linear_recurrence(10)
+        [2]
+        >>> sequence(23*n**4+91*n**2).find_linear_recurrence(10)
+        [5, -10, 10, -5, 1]
+        >>> sequence(sqrt(5)*(((1 + sqrt(5))/2)**n - (-(1 + sqrt(5))/2)**(-n))/5).find_linear_recurrence(10)
+        [1, 1]
+        >>> sequence(x+y*(-2)**(-n), (n, 0, oo)).find_linear_recurrence(30)
+        [1/2, 1/2]
+        >>> sequence(3*5**n + 12).find_linear_recurrence(20,gfvar=x)
+        ([6, -5], 3*(5 - 21*x)/((x - 1)*(5*x - 1)))
+        >>> sequence(lucas(n)).find_linear_recurrence(15,gfvar=x)
+        ([1, 1], (x - 2)/(x**2 + x - 1))
+        """
+        from sympy.simplify import simplify
+        x = [simplify(expand(t)) for t in self[:n]]
+        lx = len(x)
+        if d is None:
+            r = lx//2
+        else:
+            r = min(d,lx//2)
+        coeffs = []
+        for l in range(1, r+1):
+            l2 = 2*l
+            mlist = []
+            for k in range(l):
+                mlist.append(x[k:k+l])
+            m = Matrix(mlist)
+            if m.det() != 0:
+                y = simplify(m.LUsolve(Matrix(x[l:l2])))
+                if lx == l2:
+                    coeffs = flatten(y[::-1])
+                    break
+                mlist = []
+                for k in range(l,lx-l):
+                    mlist.append(x[k:k+l])
+                m = Matrix(mlist)
+                if m*y == Matrix(x[l2:]):
+                    coeffs = flatten(y[::-1])
+                    break
+        if gfvar is None:
+            return coeffs
+        else:
+            l = len(coeffs)
+            if l == 0:
+                return [], None
+            else:
+                n, d = x[l-1]*gfvar**(l-1), 1 - coeffs[l-1]*gfvar**l
+                for i in range(l-1):
+                    n += x[i]*gfvar**i
+                    for j in range(l-i-1):
+                        n -= coeffs[i]*x[j]*gfvar**(i+j+1)
+                    d -= coeffs[i]*gfvar**(i+1)
+                return coeffs, simplify(factor(n)/factor(d))
+
+class EmptySequence(SeqBase, metaclass=Singleton):
+    """Represents an empty sequence.
+
+    The empty sequence is also available as a singleton as
+    ``S.EmptySequence``.
+
+    Examples
+    ========
+
+    >>> from sympy import EmptySequence, SeqPer
+    >>> from sympy.abc import x
+    >>> EmptySequence
+    EmptySequence
+    >>> SeqPer((1, 2), (x, 0, 10)) + EmptySequence
+    SeqPer((1, 2), (x, 0, 10))
+    >>> SeqPer((1, 2)) * EmptySequence
+    EmptySequence
+    >>> EmptySequence.coeff_mul(-1)
+    EmptySequence
+    """
+
+    @property
+    def interval(self):
+        return S.EmptySet
+
+    @property
+    def length(self):
+        return S.Zero
+
+    def coeff_mul(self, coeff):
+        """See docstring of SeqBase.coeff_mul"""
+        return self
+
+    def __iter__(self):
+        return iter([])
+
+
+class SeqExpr(SeqBase):
+    """Sequence expression class.
+
+    Various sequences should inherit from this class.
+
+    Examples
+    ========
+
+    >>> from sympy.series.sequences import SeqExpr
+    >>> from sympy.abc import x
+    >>> from sympy import Tuple
+    >>> s = SeqExpr(Tuple(1, 2, 3), Tuple(x, 0, 10))
+    >>> s.gen
+    (1, 2, 3)
+    >>> s.interval
+    Interval(0, 10)
+    >>> s.length
+    11
+
+    See Also
+    ========
+
+    sympy.series.sequences.SeqPer
+    sympy.series.sequences.SeqFormula
+    """
+
+    @property
+    def gen(self):
+        return self.args[0]
+
+    @property
+    def interval(self):
+        return Interval(self.args[1][1], self.args[1][2])
+
+    @property
+    def start(self):
+        return self.interval.inf
+
+    @property
+    def stop(self):
+        return self.interval.sup
+
+    @property
+    def length(self):
+        return self.stop - self.start + 1
+
+    @property
+    def variables(self):
+        return (self.args[1][0],)
+
+
+class SeqPer(SeqExpr):
+    """
+    Represents a periodic sequence.
+
+    The elements are repeated after a given period.
+
+    Examples
+    ========
+
+    >>> from sympy import SeqPer, oo
+    >>> from sympy.abc import k
+
+    >>> s = SeqPer((1, 2, 3), (0, 5))
+    >>> s.periodical
+    (1, 2, 3)
+    >>> s.period
+    3
+
+    For value at a particular point
+
+    >>> s.coeff(3)
+    1
+
+    supports slicing
+
+    >>> s[:]
+    [1, 2, 3, 1, 2, 3]
+
+    iterable
+
+    >>> list(s)
+    [1, 2, 3, 1, 2, 3]
+
+    sequence starts from negative infinity
+
+    >>> SeqPer((1, 2, 3), (-oo, 0))[0:6]
+    [1, 2, 3, 1, 2, 3]
+
+    Periodic formulas
+
+    >>> SeqPer((k, k**2, k**3), (k, 0, oo))[0:6]
+    [0, 1, 8, 3, 16, 125]
+
+    See Also
+    ========
+
+    sympy.series.sequences.SeqFormula
+    """
+
+    def __new__(cls, periodical, limits=None):
+        periodical = sympify(periodical)
+
+        def _find_x(periodical):
+            free = periodical.free_symbols
+            if len(periodical.free_symbols) == 1:
+                return free.pop()
+            else:
+                return Dummy('k')
+
+        x, start, stop = None, None, None
+        if limits is None:
+            x, start, stop = _find_x(periodical), 0, S.Infinity
+        if is_sequence(limits, Tuple):
+            if len(limits) == 3:
+                x, start, stop = limits
+            elif len(limits) == 2:
+                x = _find_x(periodical)
+                start, stop = limits
+
+        if not isinstance(x, (Symbol, Idx)) or start is None or stop is None:
+            raise ValueError('Invalid limits given: %s' % str(limits))
+
+        if start is S.NegativeInfinity and stop is S.Infinity:
+                raise ValueError("Both the start and end value"
+                                 "cannot be unbounded")
+
+        limits = sympify((x, start, stop))
+
+        if is_sequence(periodical, Tuple):
+            periodical = sympify(tuple(flatten(periodical)))
+        else:
+            raise ValueError("invalid period %s should be something "
+                             "like e.g (1, 2) " % periodical)
+
+        if Interval(limits[1], limits[2]) is S.EmptySet:
+            return S.EmptySequence
+
+        return Basic.__new__(cls, periodical, limits)
+
+    @property
+    def period(self):
+        return len(self.gen)
+
+    @property
+    def periodical(self):
+        return self.gen
+
+    def _eval_coeff(self, pt):
+        if self.start is S.NegativeInfinity:
+            idx = (self.stop - pt) % self.period
+        else:
+            idx = (pt - self.start) % self.period
+        return self.periodical[idx].subs(self.variables[0], pt)
+
+    def _add(self, other):
+        """See docstring of SeqBase._add"""
+        if isinstance(other, SeqPer):
+            per1, lper1 = self.periodical, self.period
+            per2, lper2 = other.periodical, other.period
+
+            per_length = lcm(lper1, lper2)
+
+            new_per = []
+            for x in range(per_length):
+                ele1 = per1[x % lper1]
+                ele2 = per2[x % lper2]
+                new_per.append(ele1 + ele2)
+
+            start, stop = self._intersect_interval(other)
+            return SeqPer(new_per, (self.variables[0], start, stop))
+
+    def _mul(self, other):
+        """See docstring of SeqBase._mul"""
+        if isinstance(other, SeqPer):
+            per1, lper1 = self.periodical, self.period
+            per2, lper2 = other.periodical, other.period
+
+            per_length = lcm(lper1, lper2)
+
+            new_per = []
+            for x in range(per_length):
+                ele1 = per1[x % lper1]
+                ele2 = per2[x % lper2]
+                new_per.append(ele1 * ele2)
+
+            start, stop = self._intersect_interval(other)
+            return SeqPer(new_per, (self.variables[0], start, stop))
+
+    def coeff_mul(self, coeff):
+        """See docstring of SeqBase.coeff_mul"""
+        coeff = sympify(coeff)
+        per = [x * coeff for x in self.periodical]
+        return SeqPer(per, self.args[1])
+
+
+class SeqFormula(SeqExpr):
+    """
+    Represents sequence based on a formula.
+
+    Elements are generated using a formula.
+
+    Examples
+    ========
+
+    >>> from sympy import SeqFormula, oo, Symbol
+    >>> n = Symbol('n')
+    >>> s = SeqFormula(n**2, (n, 0, 5))
+    >>> s.formula
+    n**2
+
+    For value at a particular point
+
+    >>> s.coeff(3)
+    9
+
+    supports slicing
+
+    >>> s[:]
+    [0, 1, 4, 9, 16, 25]
+
+    iterable
+
+    >>> list(s)
+    [0, 1, 4, 9, 16, 25]
+
+    sequence starts from negative infinity
+
+    >>> SeqFormula(n**2, (-oo, 0))[0:6]
+    [0, 1, 4, 9, 16, 25]
+
+    See Also
+    ========
+
+    sympy.series.sequences.SeqPer
+    """
+
+    def __new__(cls, formula, limits=None):
+        formula = sympify(formula)
+
+        def _find_x(formula):
+            free = formula.free_symbols
+            if len(free) == 1:
+                return free.pop()
+            elif not free:
+                return Dummy('k')
+            else:
+                raise ValueError(
+                    " specify dummy variables for %s. If the formula contains"
+                    " more than one free symbol, a dummy variable should be"
+                    " supplied explicitly e.g., SeqFormula(m*n**2, (n, 0, 5))"
+                    % formula)
+
+        x, start, stop = None, None, None
+        if limits is None:
+            x, start, stop = _find_x(formula), 0, S.Infinity
+        if is_sequence(limits, Tuple):
+            if len(limits) == 3:
+                x, start, stop = limits
+            elif len(limits) == 2:
+                x = _find_x(formula)
+                start, stop = limits
+
+        if not isinstance(x, (Symbol, Idx)) or start is None or stop is None:
+            raise ValueError('Invalid limits given: %s' % str(limits))
+
+        if start is S.NegativeInfinity and stop is S.Infinity:
+                raise ValueError("Both the start and end value "
+                                 "cannot be unbounded")
+        limits = sympify((x, start, stop))
+
+        if Interval(limits[1], limits[2]) is S.EmptySet:
+            return S.EmptySequence
+
+        return Basic.__new__(cls, formula, limits)
+
+    @property
+    def formula(self):
+        return self.gen
+
+    def _eval_coeff(self, pt):
+        d = self.variables[0]
+        return self.formula.subs(d, pt)
+
+    def _add(self, other):
+        """See docstring of SeqBase._add"""
+        if isinstance(other, SeqFormula):
+            form1, v1 = self.formula, self.variables[0]
+            form2, v2 = other.formula, other.variables[0]
+            formula = form1 + form2.subs(v2, v1)
+            start, stop = self._intersect_interval(other)
+            return SeqFormula(formula, (v1, start, stop))
+
+    def _mul(self, other):
+        """See docstring of SeqBase._mul"""
+        if isinstance(other, SeqFormula):
+            form1, v1 = self.formula, self.variables[0]
+            form2, v2 = other.formula, other.variables[0]
+            formula = form1 * form2.subs(v2, v1)
+            start, stop = self._intersect_interval(other)
+            return SeqFormula(formula, (v1, start, stop))
+
+    def coeff_mul(self, coeff):
+        """See docstring of SeqBase.coeff_mul"""
+        coeff = sympify(coeff)
+        formula = self.formula * coeff
+        return SeqFormula(formula, self.args[1])
+
+    def expand(self, *args, **kwargs):
+        return SeqFormula(expand(self.formula, *args, **kwargs), self.args[1])
+
+class RecursiveSeq(SeqBase):
+    """
+    A finite degree recursive sequence.
+
+    Explanation
+    ===========
+
+    That is, a sequence a(n) that depends on a fixed, finite number of its
+    previous values. The general form is
+
+        a(n) = f(a(n - 1), a(n - 2), ..., a(n - d))
+
+    for some fixed, positive integer d, where f is some function defined by a
+    SymPy expression.
+
+    Parameters
+    ==========
+
+    recurrence : SymPy expression defining recurrence
+        This is *not* an equality, only the expression that the nth term is
+        equal to. For example, if :code:`a(n) = f(a(n - 1), ..., a(n - d))`,
+        then the expression should be :code:`f(a(n - 1), ..., a(n - d))`.
+
+    yn : applied undefined function
+        Represents the nth term of the sequence as e.g. :code:`y(n)` where
+        :code:`y` is an undefined function and `n` is the sequence index.
+
+    n : symbolic argument
+        The name of the variable that the recurrence is in, e.g., :code:`n` if
+        the recurrence function is :code:`y(n)`.
+
+    initial : iterable with length equal to the degree of the recurrence
+        The initial values of the recurrence.
+
+    start : start value of sequence (inclusive)
+
+    Examples
+    ========
+
+    >>> from sympy import Function, symbols
+    >>> from sympy.series.sequences import RecursiveSeq
+    >>> y = Function("y")
+    >>> n = symbols("n")
+    >>> fib = RecursiveSeq(y(n - 1) + y(n - 2), y(n), n, [0, 1])
+
+    >>> fib.coeff(3) # Value at a particular point
+    2
+
+    >>> fib[:6] # supports slicing
+    [0, 1, 1, 2, 3, 5]
+
+    >>> fib.recurrence # inspect recurrence
+    Eq(y(n), y(n - 2) + y(n - 1))
+
+    >>> fib.degree # automatically determine degree
+    2
+
+    >>> for x in zip(range(10), fib): # supports iteration
+    ...     print(x)
+    (0, 0)
+    (1, 1)
+    (2, 1)
+    (3, 2)
+    (4, 3)
+    (5, 5)
+    (6, 8)
+    (7, 13)
+    (8, 21)
+    (9, 34)
+
+    See Also
+    ========
+
+    sympy.series.sequences.SeqFormula
+
+    """
+
+    def __new__(cls, recurrence, yn, n, initial=None, start=0):
+        if not isinstance(yn, AppliedUndef):
+            raise TypeError("recurrence sequence must be an applied undefined function"
+                            ", found `{}`".format(yn))
+
+        if not isinstance(n, Basic) or not n.is_symbol:
+            raise TypeError("recurrence variable must be a symbol"
+                            ", found `{}`".format(n))
+
+        if yn.args != (n,):
+            raise TypeError("recurrence sequence does not match symbol")
+
+        y = yn.func
+
+        k = Wild("k", exclude=(n,))
+        degree = 0
+
+        # Find all applications of y in the recurrence and check that:
+        #   1. The function y is only being used with a single argument; and
+        #   2. All arguments are n + k for constant negative integers k.
+
+        prev_ys = recurrence.find(y)
+        for prev_y in prev_ys:
+            if len(prev_y.args) != 1:
+                raise TypeError("Recurrence should be in a single variable")
+
+            shift = prev_y.args[0].match(n + k)[k]
+            if not (shift.is_constant() and shift.is_integer and shift < 0):
+                raise TypeError("Recurrence should have constant,"
+                                " negative, integer shifts"
+                                " (found {})".format(prev_y))
+
+            if -shift > degree:
+                degree = -shift
+
+        if not initial:
+            initial = [Dummy("c_{}".format(k)) for k in range(degree)]
+
+        if len(initial) != degree:
+            raise ValueError("Number of initial terms must equal degree")
+
+        degree = Integer(degree)
+        start = sympify(start)
+
+        initial = Tuple(*(sympify(x) for x in initial))
+
+        seq = Basic.__new__(cls, recurrence, yn, n, initial, start)
+
+        seq.cache = {y(start + k): init for k, init in enumerate(initial)}
+        seq.degree = degree
+
+        return seq
+
+    @property
+    def _recurrence(self):
+        """Equation defining recurrence."""
+        return self.args[0]
+
+    @property
+    def recurrence(self):
+        """Equation defining recurrence."""
+        return Eq(self.yn, self.args[0])
+
+    @property
+    def yn(self):
+        """Applied function representing the nth term"""
+        return self.args[1]
+
+    @property
+    def y(self):
+        """Undefined function for the nth term of the sequence"""
+        return self.yn.func
+
+    @property
+    def n(self):
+        """Sequence index symbol"""
+        return self.args[2]
+
+    @property
+    def initial(self):
+        """The initial values of the sequence"""
+        return self.args[3]
+
+    @property
+    def start(self):
+        """The starting point of the sequence. This point is included"""
+        return self.args[4]
+
+    @property
+    def stop(self):
+        """The ending point of the sequence. (oo)"""
+        return S.Infinity
+
+    @property
+    def interval(self):
+        """Interval on which sequence is defined."""
+        return (self.start, S.Infinity)
+
+    def _eval_coeff(self, index):
+        if index - self.start < len(self.cache):
+            return self.cache[self.y(index)]
+
+        for current in range(len(self.cache), index + 1):
+            # Use xreplace over subs for performance.
+            # See issue #10697.
+            seq_index = self.start + current
+            current_recurrence = self._recurrence.xreplace({self.n: seq_index})
+            new_term = current_recurrence.xreplace(self.cache)
+
+            self.cache[self.y(seq_index)] = new_term
+
+        return self.cache[self.y(self.start + current)]
+
+    def __iter__(self):
+        index = self.start
+        while True:
+            yield self._eval_coeff(index)
+            index += 1
+
+
+def sequence(seq, limits=None):
+    """
+    Returns appropriate sequence object.
+
+    Explanation
+    ===========
+
+    If ``seq`` is a SymPy sequence, returns :class:`SeqPer` object
+    otherwise returns :class:`SeqFormula` object.
+
+    Examples
+    ========
+
+    >>> from sympy import sequence
+    >>> from sympy.abc import n
+    >>> sequence(n**2, (n, 0, 5))
+    SeqFormula(n**2, (n, 0, 5))
+    >>> sequence((1, 2, 3), (n, 0, 5))
+    SeqPer((1, 2, 3), (n, 0, 5))
+
+    See Also
+    ========
+
+    sympy.series.sequences.SeqPer
+    sympy.series.sequences.SeqFormula
+    """
+    seq = sympify(seq)
+
+    if is_sequence(seq, Tuple):
+        return SeqPer(seq, limits)
+    else:
+        return SeqFormula(seq, limits)
+
+
+###############################################################################
+#                            OPERATIONS                                       #
+###############################################################################
+
+
+class SeqExprOp(SeqBase):
+    """
+    Base class for operations on sequences.
+
+    Examples
+    ========
+
+    >>> from sympy.series.sequences import SeqExprOp, sequence
+    >>> from sympy.abc import n
+    >>> s1 = sequence(n**2, (n, 0, 10))
+    >>> s2 = sequence((1, 2, 3), (n, 5, 10))
+    >>> s = SeqExprOp(s1, s2)
+    >>> s.gen
+    (n**2, (1, 2, 3))
+    >>> s.interval
+    Interval(5, 10)
+    >>> s.length
+    6
+
+    See Also
+    ========
+
+    sympy.series.sequences.SeqAdd
+    sympy.series.sequences.SeqMul
+    """
+    @property
+    def gen(self):
+        """Generator for the sequence.
+
+        returns a tuple of generators of all the argument sequences.
+        """
+        return tuple(a.gen for a in self.args)
+
+    @property
+    def interval(self):
+        """Sequence is defined on the intersection
+        of all the intervals of respective sequences
+        """
+        return Intersection(*(a.interval for a in self.args))
+
+    @property
+    def start(self):
+        return self.interval.inf
+
+    @property
+    def stop(self):
+        return self.interval.sup
+
+    @property
+    def variables(self):
+        """Cumulative of all the bound variables"""
+        return tuple(flatten([a.variables for a in self.args]))
+
+    @property
+    def length(self):
+        return self.stop - self.start + 1
+
+
+class SeqAdd(SeqExprOp):
+    """Represents term-wise addition of sequences.
+
+    Rules:
+        * The interval on which sequence is defined is the intersection
+          of respective intervals of sequences.
+        * Anything + :class:`EmptySequence` remains unchanged.
+        * Other rules are defined in ``_add`` methods of sequence classes.
+
+    Examples
+    ========
+
+    >>> from sympy import EmptySequence, oo, SeqAdd, SeqPer, SeqFormula
+    >>> from sympy.abc import n
+    >>> SeqAdd(SeqPer((1, 2), (n, 0, oo)), EmptySequence)
+    SeqPer((1, 2), (n, 0, oo))
+    >>> SeqAdd(SeqPer((1, 2), (n, 0, 5)), SeqPer((1, 2), (n, 6, 10)))
+    EmptySequence
+    >>> SeqAdd(SeqPer((1, 2), (n, 0, oo)), SeqFormula(n**2, (n, 0, oo)))
+    SeqAdd(SeqFormula(n**2, (n, 0, oo)), SeqPer((1, 2), (n, 0, oo)))
+    >>> SeqAdd(SeqFormula(n**3), SeqFormula(n**2))
+    SeqFormula(n**3 + n**2, (n, 0, oo))
+
+    See Also
+    ========
+
+    sympy.series.sequences.SeqMul
+    """
+
+    def __new__(cls, *args, **kwargs):
+        evaluate = kwargs.get('evaluate', global_parameters.evaluate)
+
+        # flatten inputs
+        args = list(args)
+
+        # adapted from sympy.sets.sets.Union
+        def _flatten(arg):
+            if isinstance(arg, SeqBase):
+                if isinstance(arg, SeqAdd):
+                    return sum(map(_flatten, arg.args), [])
+                else:
+                    return [arg]
+            if iterable(arg):
+                return sum(map(_flatten, arg), [])
+            raise TypeError("Input must be Sequences or "
+                            " iterables of Sequences")
+        args = _flatten(args)
+
+        args = [a for a in args if a is not S.EmptySequence]
+
+        # Addition of no sequences is EmptySequence
+        if not args:
+            return S.EmptySequence
+
+        if Intersection(*(a.interval for a in args)) is S.EmptySet:
+            return S.EmptySequence
+
+        # reduce using known rules
+        if evaluate:
+            return SeqAdd.reduce(args)
+
+        args = list(ordered(args, SeqBase._start_key))
+
+        return Basic.__new__(cls, *args)
+
+    @staticmethod
+    def reduce(args):
+        """Simplify :class:`SeqAdd` using known rules.
+
+        Iterates through all pairs and ask the constituent
+        sequences if they can simplify themselves with any other constituent.
+
+        Notes
+        =====
+
+        adapted from ``Union.reduce``
+
+        """
+        new_args = True
+        while new_args:
+            for id1, s in enumerate(args):
+                new_args = False
+                for id2, t in enumerate(args):
+                    if id1 == id2:
+                        continue
+                    new_seq = s._add(t)
+                    # This returns None if s does not know how to add
+                    # with t. Returns the newly added sequence otherwise
+                    if new_seq is not None:
+                        new_args = [a for a in args if a not in (s, t)]
+                        new_args.append(new_seq)
+                        break
+                if new_args:
+                    args = new_args
+                    break
+
+        if len(args) == 1:
+            return args.pop()
+        else:
+            return SeqAdd(args, evaluate=False)
+
+    def _eval_coeff(self, pt):
+        """adds up the coefficients of all the sequences at point pt"""
+        return sum(a.coeff(pt) for a in self.args)
+
+
+class SeqMul(SeqExprOp):
+    r"""Represents term-wise multiplication of sequences.
+
+    Explanation
+    ===========
+
+    Handles multiplication of sequences only. For multiplication
+    with other objects see :func:`SeqBase.coeff_mul`.
+
+    Rules:
+        * The interval on which sequence is defined is the intersection
+          of respective intervals of sequences.
+        * Anything \* :class:`EmptySequence` returns :class:`EmptySequence`.
+        * Other rules are defined in ``_mul`` methods of sequence classes.
+
+    Examples
+    ========
+
+    >>> from sympy import EmptySequence, oo, SeqMul, SeqPer, SeqFormula
+    >>> from sympy.abc import n
+    >>> SeqMul(SeqPer((1, 2), (n, 0, oo)), EmptySequence)
+    EmptySequence
+    >>> SeqMul(SeqPer((1, 2), (n, 0, 5)), SeqPer((1, 2), (n, 6, 10)))
+    EmptySequence
+    >>> SeqMul(SeqPer((1, 2), (n, 0, oo)), SeqFormula(n**2))
+    SeqMul(SeqFormula(n**2, (n, 0, oo)), SeqPer((1, 2), (n, 0, oo)))
+    >>> SeqMul(SeqFormula(n**3), SeqFormula(n**2))
+    SeqFormula(n**5, (n, 0, oo))
+
+    See Also
+    ========
+
+    sympy.series.sequences.SeqAdd
+    """
+
+    def __new__(cls, *args, **kwargs):
+        evaluate = kwargs.get('evaluate', global_parameters.evaluate)
+
+        # flatten inputs
+        args = list(args)
+
+        # adapted from sympy.sets.sets.Union
+        def _flatten(arg):
+            if isinstance(arg, SeqBase):
+                if isinstance(arg, SeqMul):
+                    return sum(map(_flatten, arg.args), [])
+                else:
+                    return [arg]
+            elif iterable(arg):
+                return sum(map(_flatten, arg), [])
+            raise TypeError("Input must be Sequences or "
+                            " iterables of Sequences")
+        args = _flatten(args)
+
+        # Multiplication of no sequences is EmptySequence
+        if not args:
+            return S.EmptySequence
+
+        if Intersection(*(a.interval for a in args)) is S.EmptySet:
+            return S.EmptySequence
+
+        # reduce using known rules
+        if evaluate:
+            return SeqMul.reduce(args)
+
+        args = list(ordered(args, SeqBase._start_key))
+
+        return Basic.__new__(cls, *args)
+
+    @staticmethod
+    def reduce(args):
+        """Simplify a :class:`SeqMul` using known rules.
+
+        Explanation
+        ===========
+
+        Iterates through all pairs and ask the constituent
+        sequences if they can simplify themselves with any other constituent.
+
+        Notes
+        =====
+
+        adapted from ``Union.reduce``
+
+        """
+        new_args = True
+        while new_args:
+            for id1, s in enumerate(args):
+                new_args = False
+                for id2, t in enumerate(args):
+                    if id1 == id2:
+                        continue
+                    new_seq = s._mul(t)
+                    # This returns None if s does not know how to multiply
+                    # with t. Returns the newly multiplied sequence otherwise
+                    if new_seq is not None:
+                        new_args = [a for a in args if a not in (s, t)]
+                        new_args.append(new_seq)
+                        break
+                if new_args:
+                    args = new_args
+                    break
+
+        if len(args) == 1:
+            return args.pop()
+        else:
+            return SeqMul(args, evaluate=False)
+
+    def _eval_coeff(self, pt):
+        """multiplies the coefficients of all the sequences at point pt"""
+        val = 1
+        for a in self.args:
+            val *= a.coeff(pt)
+        return val
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/series.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/series.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9feec7d3b1987bfaa5238969f531e9f98b88b25
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/series.py
@@ -0,0 +1,63 @@
+from sympy.core.sympify import sympify
+
+
+def series(expr, x=None, x0=0, n=6, dir="+"):
+    """Series expansion of expr around point `x = x0`.
+
+    Parameters
+    ==========
+
+    expr : Expression
+           The expression whose series is to be expanded.
+
+    x : Symbol
+        It is the variable of the expression to be calculated.
+
+    x0 : Value
+         The value around which ``x`` is calculated. Can be any value
+         from ``-oo`` to ``oo``.
+
+    n : Value
+        The number of terms upto which the series is to be expanded.
+
+    dir : String, optional
+          The series-expansion can be bi-directional. If ``dir="+"``,
+          then (x->x0+). If ``dir="-"``, then (x->x0-). For infinite
+          ``x0`` (``oo`` or ``-oo``), the ``dir`` argument is determined
+          from the direction of the infinity (i.e., ``dir="-"`` for
+          ``oo``).
+
+    Examples
+    ========
+
+    >>> from sympy import series, tan, oo
+    >>> from sympy.abc import x
+    >>> f = tan(x)
+    >>> series(f, x, 2, 6, "+")
+    tan(2) + (1 + tan(2)**2)*(x - 2) + (x - 2)**2*(tan(2)**3 + tan(2)) +
+    (x - 2)**3*(1/3 + 4*tan(2)**2/3 + tan(2)**4) + (x - 2)**4*(tan(2)**5 +
+    5*tan(2)**3/3 + 2*tan(2)/3) + (x - 2)**5*(2/15 + 17*tan(2)**2/15 +
+    2*tan(2)**4 + tan(2)**6) + O((x - 2)**6, (x, 2))
+
+    >>> series(f, x, 2, 3, "-")
+    tan(2) + (2 - x)*(-tan(2)**2 - 1) + (2 - x)**2*(tan(2)**3 + tan(2))
+    + O((x - 2)**3, (x, 2))
+
+    >>> series(f, x, 2, oo, "+")
+    Traceback (most recent call last):
+    ...
+    TypeError: 'Infinity' object cannot be interpreted as an integer
+
+    Returns
+    =======
+
+    Expr
+        Series expansion of the expression about x0
+
+    See Also
+    ========
+
+    sympy.core.expr.Expr.series: See the docstring of Expr.series() for complete details of this wrapper.
+    """
+    expr = sympify(expr)
+    return expr.series(x, x0, n, dir)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/series_class.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/series_class.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff04993b266a3cbd3f767042d4325fb11edb2168
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/series_class.py
@@ -0,0 +1,99 @@
+"""
+Contains the base class for series
+Made using sequences in mind
+"""
+
+from sympy.core.expr import Expr
+from sympy.core.singleton import S
+from sympy.core.cache import cacheit
+
+
+class SeriesBase(Expr):
+    """Base Class for series"""
+
+    @property
+    def interval(self):
+        """The interval on which the series is defined"""
+        raise NotImplementedError("(%s).interval" % self)
+
+    @property
+    def start(self):
+        """The starting point of the series. This point is included"""
+        raise NotImplementedError("(%s).start" % self)
+
+    @property
+    def stop(self):
+        """The ending point of the series. This point is included"""
+        raise NotImplementedError("(%s).stop" % self)
+
+    @property
+    def length(self):
+        """Length of the series expansion"""
+        raise NotImplementedError("(%s).length" % self)
+
+    @property
+    def variables(self):
+        """Returns a tuple of variables that are bounded"""
+        return ()
+
+    @property
+    def free_symbols(self):
+        """
+        This method returns the symbols in the object, excluding those
+        that take on a specific value (i.e. the dummy symbols).
+        """
+        return ({j for i in self.args for j in i.free_symbols}
+                .difference(self.variables))
+
+    @cacheit
+    def term(self, pt):
+        """Term at point pt of a series"""
+        if pt < self.start or pt > self.stop:
+            raise IndexError("Index %s out of bounds %s" % (pt, self.interval))
+        return self._eval_term(pt)
+
+    def _eval_term(self, pt):
+        raise NotImplementedError("The _eval_term method should be added to"
+                                  "%s to return series term so it is available"
+                                  "when 'term' calls it."
+                                  % self.func)
+
+    def _ith_point(self, i):
+        """
+        Returns the i'th point of a series
+        If start point is negative infinity, point is returned from the end.
+        Assumes the first point to be indexed zero.
+
+        Examples
+        ========
+
+        TODO
+        """
+        if self.start is S.NegativeInfinity:
+            initial = self.stop
+            step = -1
+        else:
+            initial = self.start
+            step = 1
+
+        return initial + i*step
+
+    def __iter__(self):
+        i = 0
+        while i < self.length:
+            pt = self._ith_point(i)
+            yield self.term(pt)
+            i += 1
+
+    def __getitem__(self, index):
+        if isinstance(index, int):
+            index = self._ith_point(index)
+            return self.term(index)
+        elif isinstance(index, slice):
+            start, stop = index.start, index.stop
+            if start is None:
+                start = 0
+            if stop is None:
+                stop = self.length
+            return [self.term(self._ith_point(i)) for i in
+                    range(start, stop, index.step or 1)]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_approximants.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_approximants.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c03d2ce38add99b0dce8725b6c8d8844b31f76b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_approximants.py
@@ -0,0 +1,23 @@
+from sympy.series import approximants
+from sympy.core.symbol import symbols
+from sympy.functions.combinatorial.factorials import binomial
+from sympy.functions.combinatorial.numbers import (fibonacci, lucas)
+
+
+def test_approximants():
+    x, t = symbols("x,t")
+    g = [lucas(k) for k in range(16)]
+    assert list(approximants(g)) == (
+        [2, -4/(x - 2), (5*x - 2)/(3*x - 1), (x - 2)/(x**2 + x - 1)] )
+    g = [lucas(k)+fibonacci(k+2) for k in range(16)]
+    assert list(approximants(g)) == (
+        [3, -3/(x - 1), (3*x - 3)/(2*x - 1), -3/(x**2 + x - 1)] )
+    g = [lucas(k)**2 for k in range(16)]
+    assert list(approximants(g)) == (
+        [4, -16/(x - 4), (35*x - 4)/(9*x - 1), (37*x - 28)/(13*x**2 + 11*x - 7),
+        (50*x**2 + 63*x - 52)/(37*x**2 + 19*x - 13),
+        (-x**2 - 7*x + 4)/(x**3 - 2*x**2 - 2*x + 1)] )
+    p = [sum(binomial(k,i)*x**i for i in range(k+1)) for k in range(16)]
+    y = approximants(p, t, simplify=True)
+    assert next(y) == 1
+    assert next(y) == -1/(t*(x + 1) - 1)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_aseries.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_aseries.py
new file mode 100644
index 0000000000000000000000000000000000000000..cae0ac0a43f2406dd96e45c6a31939ac6b4cdcaa
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_aseries.py
@@ -0,0 +1,55 @@
+from sympy.core.function import PoleError
+from sympy.core.numbers import oo
+from sympy.core.symbol import Symbol
+from sympy.functions.elementary.exponential import (exp, log)
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import (cos, sin)
+from sympy.series.order import O
+from sympy.abc import x
+
+from sympy.testing.pytest import raises
+
+def test_simple():
+    # Gruntz' theses pp. 91 to 96
+    # 6.6
+    e = sin(1/x + exp(-x)) - sin(1/x)
+    assert e.aseries(x) == (1/(24*x**4) - 1/(2*x**2) + 1 + O(x**(-6), (x, oo)))*exp(-x)
+
+    e = exp(x) * (exp(1/x + exp(-x)) - exp(1/x))
+    assert e.aseries(x, n=4) == 1/(6*x**3) + 1/(2*x**2) + 1/x + 1 + O(x**(-4), (x, oo))
+
+    e = exp(exp(x) / (1 - 1/x))
+    assert e.aseries(x) == exp(exp(x) / (1 - 1/x))
+
+    # The implementation of bound in aseries is incorrect currently. This test
+    # should be commented out when that is fixed.
+    # assert e.aseries(x, bound=3) == exp(exp(x) / x**2)*exp(exp(x) / x)*exp(-exp(x) + exp(x)/(1 - 1/x) - \
+    #         exp(x) / x - exp(x) / x**2) * exp(exp(x))
+
+    e = exp(sin(1/x + exp(-exp(x)))) - exp(sin(1/x))
+    assert e.aseries(x, n=4) == (-1/(2*x**3) + 1/x + 1 + O(x**(-4), (x, oo)))*exp(-exp(x))
+
+    e3 = lambda x:exp(exp(exp(x)))
+    e = e3(x)/e3(x - 1/e3(x))
+    assert e.aseries(x, n=3) == 1 + exp(2*x + 2*exp(x))*exp(-2*exp(exp(x)))/2\
+            - exp(2*x + exp(x))*exp(-2*exp(exp(x)))/2 - exp(x + exp(x))*exp(-2*exp(exp(x)))/2\
+            + exp(x + exp(x))*exp(-exp(exp(x))) + O(exp(-3*exp(exp(x))), (x, oo))
+
+    e = exp(exp(x)) * (exp(sin(1/x + 1/exp(exp(x)))) - exp(sin(1/x)))
+    assert e.aseries(x, n=4) == -1/(2*x**3) + 1/x + 1 + O(x**(-4), (x, oo))
+
+    n = Symbol('n', integer=True)
+    e = (sqrt(n)*log(n)**2*exp(sqrt(log(n))*log(log(n))**2*exp(sqrt(log(log(n)))*log(log(log(n)))**3)))/n
+    assert e.aseries(n) == \
+            exp(exp(sqrt(log(log(n)))*log(log(log(n)))**3)*sqrt(log(n))*log(log(n))**2)*log(n)**2/sqrt(n)
+
+
+def test_hierarchical():
+    e = sin(1/x + exp(-x))
+    assert e.aseries(x, n=3, hir=True) == -exp(-2*x)*sin(1/x)/2 + \
+            exp(-x)*cos(1/x) + sin(1/x) + O(exp(-3*x), (x, oo))
+
+    e = sin(x) * cos(exp(-x))
+    assert e.aseries(x, hir=True) == exp(-4*x)*sin(x)/24 - \
+            exp(-2*x)*sin(x)/2 + sin(x) + O(exp(-6*x), (x, oo))
+    raises(PoleError, lambda: e.aseries(x))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_demidovich.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_demidovich.py
new file mode 100644
index 0000000000000000000000000000000000000000..98cafbae6f019dd3d97d306099d5780ed2f37f04
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_demidovich.py
@@ -0,0 +1,143 @@
+from sympy.core.numbers import (Rational, oo, pi)
+from sympy.core.singleton import S
+from sympy.core.symbol import Symbol
+from sympy.functions.elementary.exponential import (exp, log)
+from sympy.functions.elementary.miscellaneous import (root, sqrt)
+from sympy.functions.elementary.trigonometric import (asin, cos, sin, tan)
+from sympy.polys.rationaltools import together
+from sympy.series.limits import limit
+
+# Numbers listed with the tests refer to problem numbers in the book
+# "Anti-demidovich, problemas resueltos, Ed. URSS"
+
+x = Symbol("x")
+
+
+def test_leadterm():
+    assert (3 + 2*x**(log(3)/log(2) - 1)).leadterm(x) == (3, 0)
+
+
+def root3(x):
+    return root(x, 3)
+
+
+def root4(x):
+    return root(x, 4)
+
+
+def test_Limits_simple_0():
+    assert limit((2**(x + 1) + 3**(x + 1))/(2**x + 3**x), x, oo) == 3  # 175
+
+
+def test_Limits_simple_1():
+    assert limit((x + 1)*(x + 2)*(x + 3)/x**3, x, oo) == 1  # 172
+    assert limit(sqrt(x + 1) - sqrt(x), x, oo) == 0  # 179
+    assert limit((2*x - 3)*(3*x + 5)*(4*x - 6)/(3*x**3 + x - 1), x, oo) == 8  # Primjer 1
+    assert limit(x/root3(x**3 + 10), x, oo) == 1  # Primjer 2
+    assert limit((x + 1)**2/(x**2 + 1), x, oo) == 1  # 181
+
+
+def test_Limits_simple_2():
+    assert limit(1000*x/(x**2 - 1), x, oo) == 0  # 182
+    assert limit((x**2 - 5*x + 1)/(3*x + 7), x, oo) is oo  # 183
+    assert limit((2*x**2 - x + 3)/(x**3 - 8*x + 5), x, oo) == 0  # 184
+    assert limit((2*x**2 - 3*x - 4)/sqrt(x**4 + 1), x, oo) == 2  # 186
+    assert limit((2*x + 3)/(x + root3(x)), x, oo) == 2  # 187
+    assert limit(x**2/(10 + x*sqrt(x)), x, oo) is oo  # 188
+    assert limit(root3(x**2 + 1)/(x + 1), x, oo) == 0  # 189
+    assert limit(sqrt(x)/sqrt(x + sqrt(x + sqrt(x))), x, oo) == 1  # 190
+
+
+def test_Limits_simple_3a():
+    a = Symbol('a')
+    #issue 3513
+    assert together(limit((x**2 - (a + 1)*x + a)/(x**3 - a**3), x, a)) == \
+        (a - 1)/(3*a**2)  # 196
+
+
+def test_Limits_simple_3b():
+    h = Symbol("h")
+    assert limit(((x + h)**3 - x**3)/h, h, 0) == 3*x**2  # 197
+    assert limit((1/(1 - x) - 3/(1 - x**3)), x, 1) == -1  # 198
+    assert limit((sqrt(1 + x) - 1)/(root3(1 + x) - 1), x, 0) == Rational(3)/2  # Primer 4
+    assert limit((sqrt(x) - 1)/(x - 1), x, 1) == Rational(1)/2  # 199
+    assert limit((sqrt(x) - 8)/(root3(x) - 4), x, 64) == 3  # 200
+    assert limit((root3(x) - 1)/(root4(x) - 1), x, 1) == Rational(4)/3  # 201
+    assert limit(
+        (root3(x**2) - 2*root3(x) + 1)/(x - 1)**2, x, 1) == Rational(1)/9  # 202
+
+
+def test_Limits_simple_4a():
+    a = Symbol('a')
+    assert limit((sqrt(x) - sqrt(a))/(x - a), x, a) == 1/(2*sqrt(a))  # Primer 5
+    assert limit((sqrt(x) - 1)/(root3(x) - 1), x, 1) == Rational(3, 2)  # 205
+    assert limit((sqrt(1 + x) - sqrt(1 - x))/x, x, 0) == 1  # 207
+    assert limit(sqrt(x**2 - 5*x + 6) - x, x, oo) == Rational(-5, 2)  # 213
+
+
+def test_limits_simple_4aa():
+    assert limit(x*(sqrt(x**2 + 1) - x), x, oo) == Rational(1)/2  # 214
+
+
+def test_Limits_simple_4b():
+    #issue 3511
+    assert limit(x - root3(x**3 - 1), x, oo) == 0  # 215
+
+
+def test_Limits_simple_4c():
+    assert limit(log(1 + exp(x))/x, x, -oo) == 0  # 267a
+    assert limit(log(1 + exp(x))/x, x, oo) == 1  # 267b
+
+
+def test_bounded():
+    assert limit(sin(x)/x, x, oo) == 0  # 216b
+    assert limit(x*sin(1/x), x, 0) == 0  # 227a
+
+
+def test_f1a():
+    #issue 3508:
+    assert limit((sin(2*x)/x)**(1 + x), x, 0) == 2  # Primer 7
+
+
+def test_f1a2():
+    #issue 3509:
+    assert limit(((x - 1)/(x + 1))**x, x, oo) == exp(-2)  # Primer 9
+
+
+def test_f1b():
+    m = Symbol("m")
+    n = Symbol("n")
+    h = Symbol("h")
+    a = Symbol("a")
+    assert limit(sin(x)/x, x, 2) == sin(2)/2  # 216a
+    assert limit(sin(3*x)/x, x, 0) == 3  # 217
+    assert limit(sin(5*x)/sin(2*x), x, 0) == Rational(5, 2)  # 218
+    assert limit(sin(pi*x)/sin(3*pi*x), x, 0) == Rational(1, 3)  # 219
+    assert limit(x*sin(pi/x), x, oo) == pi  # 220
+    assert limit((1 - cos(x))/x**2, x, 0) == S.Half  # 221
+    assert limit(x*sin(1/x), x, oo) == 1  # 227b
+    assert limit((cos(m*x) - cos(n*x))/x**2, x, 0) == -m**2/2 + n**2/2  # 232
+    assert limit((tan(x) - sin(x))/x**3, x, 0) == S.Half  # 233
+    assert limit((x - sin(2*x))/(x + sin(3*x)), x, 0) == -Rational(1, 4)  # 237
+    assert limit((1 - sqrt(cos(x)))/x**2, x, 0) == Rational(1, 4)  # 239
+    assert limit((sqrt(1 + sin(x)) - sqrt(1 - sin(x)))/x, x, 0) == 1  # 240
+
+    assert limit((1 + h/x)**x, x, oo) == exp(h)  # Primer 9
+    assert limit((sin(x) - sin(a))/(x - a), x, a) == cos(a)  # 222, *176
+    assert limit((cos(x) - cos(a))/(x - a), x, a) == -sin(a)  # 223
+    assert limit((sin(x + h) - sin(x))/h, h, 0) == cos(x)  # 225
+
+
+def test_f2a():
+    assert limit(((x + 1)/(2*x + 1))**(x**2), x, oo) == 0  # Primer 8
+
+
+def test_f2():
+    assert limit((sqrt(
+        cos(x)) - root3(cos(x)))/(sin(x)**2), x, 0) == -Rational(1, 12)  # *184
+
+
+def test_f3():
+    a = Symbol('a')
+    #issue 3504
+    assert limit(asin(a*x)/x, x, 0) == a
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_formal.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_formal.py
new file mode 100644
index 0000000000000000000000000000000000000000..cac60b12534152a5783bb8f0faab2c06da6691fb
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_formal.py
@@ -0,0 +1,618 @@
+from sympy.concrete.summations import Sum
+from sympy.core.add import Add
+from sympy.core.function import (Derivative, Function)
+from sympy.core.mul import Mul
+from sympy.core.numbers import (I, Rational, oo, pi)
+from sympy.core.singleton import S
+from sympy.core.symbol import symbols
+from sympy.functions.combinatorial.factorials import factorial
+from sympy.functions.elementary.exponential import (exp, log)
+from sympy.functions.elementary.hyperbolic import (acosh, asech)
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin)
+from sympy.functions.special.bessel import airyai
+from sympy.functions.special.error_functions import erf
+from sympy.functions.special.gamma_functions import gamma
+from sympy.integrals.integrals import integrate
+from sympy.series.formal import fps
+from sympy.series.order import O
+from sympy.series.formal import (rational_algorithm, FormalPowerSeries,
+                                 FormalPowerSeriesProduct, FormalPowerSeriesCompose,
+                                 FormalPowerSeriesInverse, simpleDE,
+                                 rational_independent, exp_re, hyper_re)
+from sympy.testing.pytest import raises, XFAIL, slow
+
+x, y, z = symbols('x y z')
+n, m, k = symbols('n m k', integer=True)
+f, r = Function('f'), Function('r')
+
+
+def test_rational_algorithm():
+    f = 1 / ((x - 1)**2 * (x - 2))
+    assert rational_algorithm(f, x, k) == \
+        (-2**(-k - 1) + 1 - (factorial(k + 1) / factorial(k)), 0, 0)
+
+    f = (1 + x + x**2 + x**3) / ((x - 1) * (x - 2))
+    assert rational_algorithm(f, x, k) == \
+        (-15*2**(-k - 1) + 4, x + 4, 0)
+
+    f = z / (y*m - m*x - y*x + x**2)
+    assert rational_algorithm(f, x, k) == \
+        (((-y**(-k - 1)*z) / (y - m)) + ((m**(-k - 1)*z) / (y - m)), 0, 0)
+
+    f = x / (1 - x - x**2)
+    assert rational_algorithm(f, x, k) is None
+    assert rational_algorithm(f, x, k, full=True) == \
+        (((Rational(-1, 2) + sqrt(5)/2)**(-k - 1) *
+         (-sqrt(5)/10 + S.Half)) +
+         ((-sqrt(5)/2 - S.Half)**(-k - 1) *
+         (sqrt(5)/10 + S.Half)), 0, 0)
+
+    f = 1 / (x**2 + 2*x + 2)
+    assert rational_algorithm(f, x, k) is None
+    assert rational_algorithm(f, x, k, full=True) == \
+        ((I*(-1 + I)**(-k - 1)) / 2 - (I*(-1 - I)**(-k - 1)) / 2, 0, 0)
+
+    f = log(1 + x)
+    assert rational_algorithm(f, x, k) == \
+        (-(-1)**(-k) / k, 0, 1)
+
+    f = atan(x)
+    assert rational_algorithm(f, x, k) is None
+    assert rational_algorithm(f, x, k, full=True) == \
+        (((I*I**(-k)) / 2 - (I*(-I)**(-k)) / 2) / k, 0, 1)
+
+    f = x*atan(x) - log(1 + x**2) / 2
+    assert rational_algorithm(f, x, k) is None
+    assert rational_algorithm(f, x, k, full=True) == \
+        (((I*I**(-k + 1)) / 2 - (I*(-I)**(-k + 1)) / 2) /
+         (k*(k - 1)), 0, 2)
+
+    f = log((1 + x) / (1 - x)) / 2 - atan(x)
+    assert rational_algorithm(f, x, k) is None
+    assert rational_algorithm(f, x, k, full=True) == \
+        ((-(-1)**(-k) / 2 - (I*I**(-k)) / 2 + (I*(-I)**(-k)) / 2 +
+          S.Half) / k, 0, 1)
+
+    assert rational_algorithm(cos(x), x, k) is None
+
+
+def test_rational_independent():
+    ri = rational_independent
+    assert ri([], x) == []
+    assert ri([cos(x), sin(x)], x) == [cos(x), sin(x)]
+    assert ri([x**2, sin(x), x*sin(x), x**3], x) == \
+        [x**3 + x**2, x*sin(x) + sin(x)]
+    assert ri([S.One, x*log(x), log(x), sin(x)/x, cos(x), sin(x), x], x) == \
+        [x + 1, x*log(x) + log(x), sin(x)/x + sin(x), cos(x)]
+
+
+def test_simpleDE():
+    # Tests just the first valid DE
+    for DE in simpleDE(exp(x), x, f):
+        assert DE == (-f(x) + Derivative(f(x), x), 1)
+        break
+    for DE in simpleDE(sin(x), x, f):
+        assert DE == (f(x) + Derivative(f(x), x, x), 2)
+        break
+    for DE in simpleDE(log(1 + x), x, f):
+        assert DE == ((x + 1)*Derivative(f(x), x, 2) + Derivative(f(x), x), 2)
+        break
+    for DE in simpleDE(asin(x), x, f):
+        assert DE == (x*Derivative(f(x), x) + (x**2 - 1)*Derivative(f(x), x, x),
+                      2)
+        break
+    for DE in simpleDE(exp(x)*sin(x), x, f):
+        assert DE == (2*f(x) - 2*Derivative(f(x)) + Derivative(f(x), x, x), 2)
+        break
+    for DE in simpleDE(((1 + x)/(1 - x))**n, x, f):
+        assert DE == (2*n*f(x) + (x**2 - 1)*Derivative(f(x), x), 1)
+        break
+    for DE in simpleDE(airyai(x), x, f):
+        assert DE == (-x*f(x) + Derivative(f(x), x, x), 2)
+        break
+
+
+def test_exp_re():
+    d = -f(x) + Derivative(f(x), x)
+    assert exp_re(d, r, k) == -r(k) + r(k + 1)
+
+    d = f(x) + Derivative(f(x), x, x)
+    assert exp_re(d, r, k) == r(k) + r(k + 2)
+
+    d = f(x) + Derivative(f(x), x) + Derivative(f(x), x, x)
+    assert exp_re(d, r, k) == r(k) + r(k + 1) + r(k + 2)
+
+    d = Derivative(f(x), x) + Derivative(f(x), x, x)
+    assert exp_re(d, r, k) == r(k) + r(k + 1)
+
+    d = Derivative(f(x), x, 3) + Derivative(f(x), x, 4) + Derivative(f(x))
+    assert exp_re(d, r, k) == r(k) + r(k + 2) + r(k + 3)
+
+
+def test_hyper_re():
+    d = f(x) + Derivative(f(x), x, x)
+    assert hyper_re(d, r, k) == r(k) + (k+1)*(k+2)*r(k + 2)
+
+    d = -x*f(x) + Derivative(f(x), x, x)
+    assert hyper_re(d, r, k) == (k + 2)*(k + 3)*r(k + 3) - r(k)
+
+    d = 2*f(x) - 2*Derivative(f(x), x) + Derivative(f(x), x, x)
+    assert hyper_re(d, r, k) == \
+        (-2*k - 2)*r(k + 1) + (k + 1)*(k + 2)*r(k + 2) + 2*r(k)
+
+    d = 2*n*f(x) + (x**2 - 1)*Derivative(f(x), x)
+    assert hyper_re(d, r, k) == \
+        k*r(k) + 2*n*r(k + 1) + (-k - 2)*r(k + 2)
+
+    d = (x**10 + 4)*Derivative(f(x), x) + x*(x**10 - 1)*Derivative(f(x), x, x)
+    assert hyper_re(d, r, k) == \
+        (k*(k - 1) + k)*r(k) + (4*k - (k + 9)*(k + 10) + 40)*r(k + 10)
+
+    d = ((x**2 - 1)*Derivative(f(x), x, 3) + 3*x*Derivative(f(x), x, x) +
+         Derivative(f(x), x))
+    assert hyper_re(d, r, k) == \
+        ((k*(k - 2)*(k - 1) + 3*k*(k - 1) + k)*r(k) +
+         (-k*(k + 1)*(k + 2))*r(k + 2))
+
+
+def test_fps():
+    assert fps(1) == 1
+    assert fps(2, x) == 2
+    assert fps(2, x, dir='+') == 2
+    assert fps(2, x, dir='-') == 2
+    assert fps(1/x + 1/x**2) == 1/x + 1/x**2
+    assert fps(log(1 + x), hyper=False, rational=False) == log(1 + x)
+
+    f = fps(x**2 + x + 1)
+    assert isinstance(f, FormalPowerSeries)
+    assert f.function == x**2 + x + 1
+    assert f[0] == 1
+    assert f[2] == x**2
+    assert f.truncate(4) == x**2 + x + 1 + O(x**4)
+    assert f.polynomial() == x**2 + x + 1
+
+    f = fps(log(1 + x))
+    assert isinstance(f, FormalPowerSeries)
+    assert f.function == log(1 + x)
+    assert f.subs(x, y) == f
+    assert f[:5] == [0, x, -x**2/2, x**3/3, -x**4/4]
+    assert f.as_leading_term(x) == x
+    assert f.polynomial(6) == x - x**2/2 + x**3/3 - x**4/4 + x**5/5
+
+    k = f.ak.variables[0]
+    assert f.infinite == Sum((-(-1)**(-k)*x**k)/k, (k, 1, oo))
+
+    ft, s = f.truncate(n=None), f[:5]
+    for i, t in enumerate(ft):
+        if i == 5:
+            break
+        assert s[i] == t
+
+    f = sin(x).fps(x)
+    assert isinstance(f, FormalPowerSeries)
+    assert f.truncate() == x - x**3/6 + x**5/120 + O(x**6)
+
+    raises(NotImplementedError, lambda: fps(y*x))
+    raises(ValueError, lambda: fps(x, dir=0))
+
+
+@slow
+def test_fps__rational():
+    assert fps(1/x) == (1/x)
+    assert fps((x**2 + x + 1) / x**3, dir=-1) == (x**2 + x + 1) / x**3
+
+    f = 1 / ((x - 1)**2 * (x - 2))
+    assert fps(f, x).truncate() == \
+        (Rational(-1, 2) - x*Rational(5, 4) - 17*x**2/8 - 49*x**3/16 - 129*x**4/32 -
+         321*x**5/64 + O(x**6))
+
+    f = (1 + x + x**2 + x**3) / ((x - 1) * (x - 2))
+    assert fps(f, x).truncate() == \
+        (S.Half + x*Rational(5, 4) + 17*x**2/8 + 49*x**3/16 + 113*x**4/32 +
+         241*x**5/64 + O(x**6))
+
+    f = x / (1 - x - x**2)
+    assert fps(f, x, full=True).truncate() == \
+        x + x**2 + 2*x**3 + 3*x**4 + 5*x**5 + O(x**6)
+
+    f = 1 / (x**2 + 2*x + 2)
+    assert fps(f, x, full=True).truncate() == \
+        S.Half - x/2 + x**2/4 - x**4/8 + x**5/8 + O(x**6)
+
+    f = log(1 + x)
+    assert fps(f, x).truncate() == \
+        x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6)
+    assert fps(f, x, dir=1).truncate() == fps(f, x, dir=-1).truncate()
+    assert fps(f, x, 2).truncate() == \
+        (log(3) - Rational(2, 3) - (x - 2)**2/18 + (x - 2)**3/81 -
+         (x - 2)**4/324 + (x - 2)**5/1215 + x/3 + O((x - 2)**6, (x, 2)))
+    assert fps(f, x, 2, dir=-1).truncate() == \
+        (log(3) - Rational(2, 3) - (-x + 2)**2/18 - (-x + 2)**3/81 -
+         (-x + 2)**4/324 - (-x + 2)**5/1215 + x/3 + O((x - 2)**6, (x, 2)))
+
+    f = atan(x)
+    assert fps(f, x, full=True).truncate() == x - x**3/3 + x**5/5 + O(x**6)
+    assert fps(f, x, full=True, dir=1).truncate() == \
+        fps(f, x, full=True, dir=-1).truncate()
+    assert fps(f, x, 2, full=True).truncate() == \
+        (atan(2) - Rational(2, 5) - 2*(x - 2)**2/25 + 11*(x - 2)**3/375 -
+         6*(x - 2)**4/625 + 41*(x - 2)**5/15625 + x/5 + O((x - 2)**6, (x, 2)))
+    assert fps(f, x, 2, full=True, dir=-1).truncate() == \
+        (atan(2) - Rational(2, 5) - 2*(-x + 2)**2/25 - 11*(-x + 2)**3/375 -
+         6*(-x + 2)**4/625 - 41*(-x + 2)**5/15625 + x/5 + O((x - 2)**6, (x, 2)))
+
+    f = x*atan(x) - log(1 + x**2) / 2
+    assert fps(f, x, full=True).truncate() == x**2/2 - x**4/12 + O(x**6)
+
+    f = log((1 + x) / (1 - x)) / 2 - atan(x)
+    assert fps(f, x, full=True).truncate(n=10) == 2*x**3/3 + 2*x**7/7 + O(x**10)
+
+
+@slow
+def test_fps__hyper():
+    f = sin(x)
+    assert fps(f, x).truncate() == x - x**3/6 + x**5/120 + O(x**6)
+
+    f = cos(x)
+    assert fps(f, x).truncate() == 1 - x**2/2 + x**4/24 + O(x**6)
+
+    f = exp(x)
+    assert fps(f, x).truncate() == \
+        1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + O(x**6)
+
+    f = atan(x)
+    assert fps(f, x).truncate() == x - x**3/3 + x**5/5 + O(x**6)
+
+    f = exp(acos(x))
+    assert fps(f, x).truncate() == \
+        (exp(pi/2) - x*exp(pi/2) + x**2*exp(pi/2)/2 - x**3*exp(pi/2)/3 +
+         5*x**4*exp(pi/2)/24 - x**5*exp(pi/2)/6 + O(x**6))
+
+    f = exp(acosh(x))
+    assert fps(f, x).truncate() == I + x - I*x**2/2 - I*x**4/8 + O(x**6)
+
+    f = atan(1/x)
+    assert fps(f, x).truncate() == pi/2 - x + x**3/3 - x**5/5 + O(x**6)
+
+    f = x*atan(x) - log(1 + x**2) / 2
+    assert fps(f, x, rational=False).truncate() == x**2/2 - x**4/12 + O(x**6)
+
+    f = log(1 + x)
+    assert fps(f, x, rational=False).truncate() == \
+        x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6)
+
+    f = airyai(x**2)
+    assert fps(f, x).truncate() == \
+        (3**Rational(5, 6)*gamma(Rational(1, 3))/(6*pi) -
+         3**Rational(2, 3)*x**2/(3*gamma(Rational(1, 3))) + O(x**6))
+
+    f = exp(x)*sin(x)
+    assert fps(f, x).truncate() == x + x**2 + x**3/3 - x**5/30 + O(x**6)
+
+    f = exp(x)*sin(x)/x
+    assert fps(f, x).truncate() == 1 + x + x**2/3 - x**4/30 - x**5/90 + O(x**6)
+
+    f = sin(x) * cos(x)
+    assert fps(f, x).truncate() == x - 2*x**3/3 + 2*x**5/15 + O(x**6)
+
+
+def test_fps_shift():
+    f = x**-5*sin(x)
+    assert fps(f, x).truncate() == \
+        1/x**4 - 1/(6*x**2) + Rational(1, 120) - x**2/5040 + x**4/362880 + O(x**6)
+
+    f = x**2*atan(x)
+    assert fps(f, x, rational=False).truncate() == \
+        x**3 - x**5/3 + O(x**6)
+
+    f = cos(sqrt(x))*x
+    assert fps(f, x).truncate() == \
+        x - x**2/2 + x**3/24 - x**4/720 + x**5/40320 + O(x**6)
+
+    f = x**2*cos(sqrt(x))
+    assert fps(f, x).truncate() == \
+        x**2 - x**3/2 + x**4/24 - x**5/720 + O(x**6)
+
+
+def test_fps__Add_expr():
+    f = x*atan(x) - log(1 + x**2) / 2
+    assert fps(f, x).truncate() == x**2/2 - x**4/12 + O(x**6)
+
+    f = sin(x) + cos(x) - exp(x) + log(1 + x)
+    assert fps(f, x).truncate() == x - 3*x**2/2 - x**4/4 + x**5/5 + O(x**6)
+
+    f = 1/x + sin(x)
+    assert fps(f, x).truncate() == 1/x + x - x**3/6 + x**5/120 + O(x**6)
+
+    f = sin(x) - cos(x) + 1/(x - 1)
+    assert fps(f, x).truncate() == \
+        -2 - x**2/2 - 7*x**3/6 - 25*x**4/24 - 119*x**5/120 + O(x**6)
+
+
+def test_fps__asymptotic():
+    f = exp(x)
+    assert fps(f, x, oo) == f
+    assert fps(f, x, -oo).truncate() == O(1/x**6, (x, oo))
+
+    f = erf(x)
+    assert fps(f, x, oo).truncate() == 1 + O(1/x**6, (x, oo))
+    assert fps(f, x, -oo).truncate() == -1 + O(1/x**6, (x, oo))
+
+    f = atan(x)
+    assert fps(f, x, oo, full=True).truncate() == \
+        -1/(5*x**5) + 1/(3*x**3) - 1/x + pi/2 + O(1/x**6, (x, oo))
+    assert fps(f, x, -oo, full=True).truncate() == \
+        -1/(5*x**5) + 1/(3*x**3) - 1/x - pi/2 + O(1/x**6, (x, oo))
+
+    f = log(1 + x)
+    assert fps(f, x, oo) != \
+        (-1/(5*x**5) - 1/(4*x**4) + 1/(3*x**3) - 1/(2*x**2) + 1/x - log(1/x) +
+         O(1/x**6, (x, oo)))
+    assert fps(f, x, -oo) != \
+        (-1/(5*x**5) - 1/(4*x**4) + 1/(3*x**3) - 1/(2*x**2) + 1/x + I*pi -
+         log(-1/x) + O(1/x**6, (x, oo)))
+
+
+def test_fps__fractional():
+    f = sin(sqrt(x)) / x
+    assert fps(f, x).truncate() == \
+        (1/sqrt(x) - sqrt(x)/6 + x**Rational(3, 2)/120 -
+         x**Rational(5, 2)/5040 + x**Rational(7, 2)/362880 -
+         x**Rational(9, 2)/39916800 + x**Rational(11, 2)/6227020800 + O(x**6))
+
+    f = sin(sqrt(x)) * x
+    assert fps(f, x).truncate() == \
+        (x**Rational(3, 2) - x**Rational(5, 2)/6 + x**Rational(7, 2)/120 -
+         x**Rational(9, 2)/5040 + x**Rational(11, 2)/362880 + O(x**6))
+
+    f = atan(sqrt(x)) / x**2
+    assert fps(f, x).truncate() == \
+        (x**Rational(-3, 2) - x**Rational(-1, 2)/3 + x**S.Half/5 -
+         x**Rational(3, 2)/7 + x**Rational(5, 2)/9 - x**Rational(7, 2)/11 +
+         x**Rational(9, 2)/13 - x**Rational(11, 2)/15 + O(x**6))
+
+    f = exp(sqrt(x))
+    assert fps(f, x).truncate().expand() == \
+        (1 + x/2 + x**2/24 + x**3/720 + x**4/40320 + x**5/3628800 + sqrt(x) +
+         x**Rational(3, 2)/6 + x**Rational(5, 2)/120 + x**Rational(7, 2)/5040 +
+         x**Rational(9, 2)/362880 + x**Rational(11, 2)/39916800 + O(x**6))
+
+    f = exp(sqrt(x))*x
+    assert fps(f, x).truncate().expand() == \
+        (x + x**2/2 + x**3/24 + x**4/720 + x**5/40320 + x**Rational(3, 2) +
+         x**Rational(5, 2)/6 + x**Rational(7, 2)/120 + x**Rational(9, 2)/5040 +
+         x**Rational(11, 2)/362880 + O(x**6))
+
+
+def test_fps__logarithmic_singularity():
+    f = log(1 + 1/x)
+    assert fps(f, x) != \
+        -log(x) + x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6)
+    assert fps(f, x, rational=False) != \
+        -log(x) + x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6)
+
+
+@XFAIL
+def test_fps__logarithmic_singularity_fail():
+    f = asech(x)  # Algorithms for computing limits probably needs improvements
+    assert fps(f, x) == log(2) - log(x) - x**2/4 - 3*x**4/64 + O(x**6)
+
+
+def test_fps_symbolic():
+    f = x**n*sin(x**2)
+    assert fps(f, x).truncate(8) == x**(n + 2) - x**(n + 6)/6 + O(x**(n + 8), x)
+
+    f = x**n*log(1 + x)
+    fp = fps(f, x)
+    k = fp.ak.variables[0]
+    assert fp.infinite == \
+        Sum((-(-1)**(-k)*x**(k + n))/k, (k, 1, oo))
+
+    f = (x - 2)**n*log(1 + x)
+    assert fps(f, x, 2).truncate() == \
+        ((x - 2)**n*log(3) + (x - 2)**(n + 1)/3 - (x - 2)**(n + 2)/18 + (x - 2)**(n + 3)/81 -
+         (x - 2)**(n + 4)/324 + (x - 2)**(n + 5)/1215 + O((x - 2)**(n + 6), (x, 2)))
+
+    f = x**(n - 2)*cos(x)
+    assert fps(f, x).truncate() == \
+        (x**(n - 2) - x**n/2 + x**(n + 2)/24 + O(x**(n + 4), x))
+
+    f = x**(n - 2)*sin(x) + x**n*exp(x)
+    assert fps(f, x).truncate() == \
+        (x**(n - 1) + x**(n + 1) + x**(n + 2)/2 + x**n +
+         x**(n + 4)/24 + x**(n + 5)/60 + O(x**(n + 6), x))
+
+    f = x**n*atan(x)
+    assert fps(f, x, oo).truncate() == \
+        (-x**(n - 5)/5 + x**(n - 3)/3 + x**n*(pi/2 - 1/x) +
+         O((1/x)**(-n)/x**6, (x, oo)))
+
+    f = x**(n/2)*cos(x)
+    assert fps(f, x).truncate() == \
+        x**(n/2) - x**(n/2 + 2)/2 + x**(n/2 + 4)/24 + O(x**(n/2 + 6), x)
+
+    f = x**(n + m)*sin(x)
+    assert fps(f, x).truncate() == \
+        x**(m + n + 1) - x**(m + n + 3)/6 + x**(m + n + 5)/120 + O(x**(m + n + 6), x)
+
+
+def test_fps__slow():
+    f = x*exp(x)*sin(2*x)  # TODO: rsolve needs improvement
+    assert fps(f, x).truncate() == 2*x**2 + 2*x**3 - x**4/3 - x**5 + O(x**6)
+
+
+def test_fps__operations():
+    f1, f2 = fps(sin(x)), fps(cos(x))
+
+    fsum = f1 + f2
+    assert fsum.function == sin(x) + cos(x)
+    assert fsum.truncate() == \
+        1 + x - x**2/2 - x**3/6 + x**4/24 + x**5/120 + O(x**6)
+
+    fsum = f1 + 1
+    assert fsum.function == sin(x) + 1
+    assert fsum.truncate() == 1 + x - x**3/6 + x**5/120 + O(x**6)
+
+    fsum = 1 + f2
+    assert fsum.function == cos(x) + 1
+    assert fsum.truncate() == 2 - x**2/2 + x**4/24 + O(x**6)
+
+    assert (f1 + x) == Add(f1, x)
+
+    assert -f2.truncate() == -1 + x**2/2 - x**4/24 + O(x**6)
+    assert (f1 - f1) is S.Zero
+
+    fsub = f1 - f2
+    assert fsub.function == sin(x) - cos(x)
+    assert fsub.truncate() == \
+        -1 + x + x**2/2 - x**3/6 - x**4/24 + x**5/120 + O(x**6)
+
+    fsub = f1 - 1
+    assert fsub.function == sin(x) - 1
+    assert fsub.truncate() == -1 + x - x**3/6 + x**5/120 + O(x**6)
+
+    fsub = 1 - f2
+    assert fsub.function == -cos(x) + 1
+    assert fsub.truncate() == x**2/2 - x**4/24 + O(x**6)
+
+    raises(ValueError, lambda: f1 + fps(exp(x), dir=-1))
+    raises(ValueError, lambda: f1 + fps(exp(x), x0=1))
+
+    fm = f1 * 3
+
+    assert fm.function == 3*sin(x)
+    assert fm.truncate() == 3*x - x**3/2 + x**5/40 + O(x**6)
+
+    fm = 3 * f2
+
+    assert fm.function == 3*cos(x)
+    assert fm.truncate() == 3 - 3*x**2/2 + x**4/8 + O(x**6)
+
+    assert (f1 * f2) == Mul(f1, f2)
+    assert (f1 * x) == Mul(f1, x)
+
+    fd = f1.diff()
+    assert fd.function == cos(x)
+    assert fd.truncate() == 1 - x**2/2 + x**4/24 + O(x**6)
+
+    fd = f2.diff()
+    assert fd.function == -sin(x)
+    assert fd.truncate() == -x + x**3/6 - x**5/120 + O(x**6)
+
+    fd = f2.diff().diff()
+    assert fd.function == -cos(x)
+    assert fd.truncate() == -1 + x**2/2 - x**4/24 + O(x**6)
+
+    f3 = fps(exp(sqrt(x)))
+    fd = f3.diff()
+    assert fd.truncate().expand() == \
+        (1/(2*sqrt(x)) + S.Half + x/12 + x**2/240 + x**3/10080 + x**4/725760 +
+         x**5/79833600 + sqrt(x)/4 + x**Rational(3, 2)/48 + x**Rational(5, 2)/1440 +
+         x**Rational(7, 2)/80640 + x**Rational(9, 2)/7257600 + x**Rational(11, 2)/958003200 +
+         O(x**6))
+
+    assert f1.integrate((x, 0, 1)) == -cos(1) + 1
+    assert integrate(f1, (x, 0, 1)) == -cos(1) + 1
+
+    fi = integrate(f1, x)
+    assert fi.function == -cos(x)
+    assert fi.truncate() == -1 + x**2/2 - x**4/24 + O(x**6)
+
+    fi = f2.integrate(x)
+    assert fi.function == sin(x)
+    assert fi.truncate() == x - x**3/6 + x**5/120 + O(x**6)
+
+def test_fps__product():
+    f1, f2, f3 = fps(sin(x)), fps(exp(x)), fps(cos(x))
+
+    raises(ValueError, lambda: f1.product(exp(x), x))
+    raises(ValueError, lambda: f1.product(fps(exp(x), dir=-1), x, 4))
+    raises(ValueError, lambda: f1.product(fps(exp(x), x0=1), x, 4))
+    raises(ValueError, lambda: f1.product(fps(exp(y)), x, 4))
+
+    fprod = f1.product(f2, x)
+    assert isinstance(fprod, FormalPowerSeriesProduct)
+    assert isinstance(fprod.ffps, FormalPowerSeries)
+    assert isinstance(fprod.gfps, FormalPowerSeries)
+    assert fprod.f == sin(x)
+    assert fprod.g == exp(x)
+    assert fprod.function == sin(x) * exp(x)
+    assert fprod._eval_terms(4) == x + x**2 + x**3/3
+    assert fprod.truncate(4) == x + x**2 + x**3/3 + O(x**4)
+    assert fprod.polynomial(4) == x + x**2 + x**3/3
+
+    raises(NotImplementedError, lambda: fprod._eval_term(5))
+    raises(NotImplementedError, lambda: fprod.infinite)
+    raises(NotImplementedError, lambda: fprod._eval_derivative(x))
+    raises(NotImplementedError, lambda: fprod.integrate(x))
+
+    assert f1.product(f3, x)._eval_terms(4) == x - 2*x**3/3
+    assert f1.product(f3, x).truncate(4) == x - 2*x**3/3 + O(x**4)
+
+
+def test_fps__compose():
+    f1, f2, f3 = fps(exp(x)), fps(sin(x)), fps(cos(x))
+
+    raises(ValueError, lambda: f1.compose(sin(x), x))
+    raises(ValueError, lambda: f1.compose(fps(sin(x), dir=-1), x, 4))
+    raises(ValueError, lambda: f1.compose(fps(sin(x), x0=1), x, 4))
+    raises(ValueError, lambda: f1.compose(fps(sin(y)), x, 4))
+
+    raises(ValueError, lambda: f1.compose(f3, x))
+    raises(ValueError, lambda: f2.compose(f3, x))
+
+    fcomp = f1.compose(f2, x)
+    assert isinstance(fcomp, FormalPowerSeriesCompose)
+    assert isinstance(fcomp.ffps, FormalPowerSeries)
+    assert isinstance(fcomp.gfps, FormalPowerSeries)
+    assert fcomp.f == exp(x)
+    assert fcomp.g == sin(x)
+    assert fcomp.function == exp(sin(x))
+    assert fcomp._eval_terms(6) == 1 + x + x**2/2 - x**4/8 - x**5/15
+    assert fcomp.truncate() == 1 + x + x**2/2 - x**4/8 - x**5/15 + O(x**6)
+    assert fcomp.truncate(5) == 1 + x + x**2/2 - x**4/8 + O(x**5)
+
+    raises(NotImplementedError, lambda: fcomp._eval_term(5))
+    raises(NotImplementedError, lambda: fcomp.infinite)
+    raises(NotImplementedError, lambda: fcomp._eval_derivative(x))
+    raises(NotImplementedError, lambda: fcomp.integrate(x))
+
+    assert f1.compose(f2, x).truncate(4) == 1 + x + x**2/2 + O(x**4)
+    assert f1.compose(f2, x).truncate(8) == \
+        1 + x + x**2/2 - x**4/8 - x**5/15 - x**6/240 + x**7/90 + O(x**8)
+    assert f1.compose(f2, x).truncate(6) == \
+        1 + x + x**2/2 - x**4/8 - x**5/15 + O(x**6)
+
+    assert f2.compose(f2, x).truncate(4) == x - x**3/3 + O(x**4)
+    assert f2.compose(f2, x).truncate(8) == x - x**3/3 + x**5/10 - 8*x**7/315 + O(x**8)
+    assert f2.compose(f2, x).truncate(6) == x - x**3/3 + x**5/10 + O(x**6)
+
+
+def test_fps__inverse():
+    f1, f2, f3 = fps(sin(x)), fps(exp(x)), fps(cos(x))
+
+    raises(ValueError, lambda: f1.inverse(x))
+
+    finv = f2.inverse(x)
+    assert isinstance(finv, FormalPowerSeriesInverse)
+    assert isinstance(finv.ffps, FormalPowerSeries)
+    raises(ValueError, lambda: finv.gfps)
+
+    assert finv.f == exp(x)
+    assert finv.function == exp(-x)
+    assert finv._eval_terms(5) == 1 - x + x**2/2 - x**3/6 + x**4/24
+    assert finv.truncate() == 1 - x + x**2/2 - x**3/6 + x**4/24 - x**5/120 + O(x**6)
+    assert finv.truncate(5) == 1 - x + x**2/2 - x**3/6 + x**4/24 + O(x**5)
+
+    raises(NotImplementedError, lambda: finv._eval_term(5))
+    raises(ValueError, lambda: finv.g)
+    raises(NotImplementedError, lambda: finv.infinite)
+    raises(NotImplementedError, lambda: finv._eval_derivative(x))
+    raises(NotImplementedError, lambda: finv.integrate(x))
+
+    assert f2.inverse(x).truncate(8) == \
+        1 - x + x**2/2 - x**3/6 + x**4/24 - x**5/120 + x**6/720 - x**7/5040 + O(x**8)
+
+    assert f3.inverse(x).truncate() == 1 + x**2/2 + 5*x**4/24 + O(x**6)
+    assert f3.inverse(x).truncate(8) == 1 + x**2/2 + 5*x**4/24 + 61*x**6/720 + O(x**8)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_fourier.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_fourier.py
new file mode 100644
index 0000000000000000000000000000000000000000..994f182088b09b038e0e1b3885fec1c27f69f2b0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_fourier.py
@@ -0,0 +1,165 @@
+from sympy.core.add import Add
+from sympy.core.numbers import (Rational, oo, pi)
+from sympy.core.singleton import S
+from sympy.core.symbol import symbols
+from sympy.functions.elementary.exponential import (exp, log)
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.functions.elementary.trigonometric import (cos, sin, sinc, tan)
+from sympy.series.fourier import fourier_series
+from sympy.series.fourier import FourierSeries
+from sympy.testing.pytest import raises
+from functools import lru_cache
+
+x, y, z = symbols('x y z')
+
+# Don't declare these during import because they are slow
+@lru_cache()
+def _get_examples():
+    fo = fourier_series(x, (x, -pi, pi))
+    fe = fourier_series(x**2, (-pi, pi))
+    fp = fourier_series(Piecewise((0, x < 0), (pi, True)), (x, -pi, pi))
+    return fo, fe, fp
+
+
+def test_FourierSeries():
+    fo, fe, fp = _get_examples()
+
+    assert fourier_series(1, (-pi, pi)) == 1
+    assert (Piecewise((0, x < 0), (pi, True)).
+            fourier_series((x, -pi, pi)).truncate()) == fp.truncate()
+    assert isinstance(fo, FourierSeries)
+    assert fo.function == x
+    assert fo.x == x
+    assert fo.period == (-pi, pi)
+
+    assert fo.term(3) == 2*sin(3*x) / 3
+    assert fe.term(3) == -4*cos(3*x) / 9
+    assert fp.term(3) == 2*sin(3*x) / 3
+
+    assert fo.as_leading_term(x) == 2*sin(x)
+    assert fe.as_leading_term(x) == pi**2 / 3
+    assert fp.as_leading_term(x) == pi / 2
+
+    assert fo.truncate() == 2*sin(x) - sin(2*x) + (2*sin(3*x) / 3)
+    assert fe.truncate() == -4*cos(x) + cos(2*x) + pi**2 / 3
+    assert fp.truncate() == 2*sin(x) + (2*sin(3*x) / 3) + pi / 2
+
+    fot = fo.truncate(n=None)
+    s = [0, 2*sin(x), -sin(2*x)]
+    for i, t in enumerate(fot):
+        if i == 3:
+            break
+        assert s[i] == t
+
+    def _check_iter(f, i):
+        for ind, t in enumerate(f):
+            assert t == f[ind]  # noqa: PLR1736
+            if ind == i:
+                break
+
+    _check_iter(fo, 3)
+    _check_iter(fe, 3)
+    _check_iter(fp, 3)
+
+    assert fo.subs(x, x**2) == fo
+
+    raises(ValueError, lambda: fourier_series(x, (0, 1, 2)))
+    raises(ValueError, lambda: fourier_series(x, (x, 0, oo)))
+    raises(ValueError, lambda: fourier_series(x*y, (0, oo)))
+
+
+def test_FourierSeries_2():
+    p = Piecewise((0, x < 0), (x, True))
+    f = fourier_series(p, (x, -2, 2))
+
+    assert f.term(3) == (2*sin(3*pi*x / 2) / (3*pi) -
+                         4*cos(3*pi*x / 2) / (9*pi**2))
+    assert f.truncate() == (2*sin(pi*x / 2) / pi - sin(pi*x) / pi -
+                            4*cos(pi*x / 2) / pi**2 + S.Half)
+
+
+def test_square_wave():
+    """Test if fourier_series approximates discontinuous function correctly."""
+    square_wave = Piecewise((1, x < pi), (-1, True))
+    s = fourier_series(square_wave, (x, 0, 2*pi))
+
+    assert s.truncate(3) == 4 / pi * sin(x) + 4 / (3 * pi) * sin(3 * x) + \
+        4 / (5 * pi) * sin(5 * x)
+    assert s.sigma_approximation(4) == 4 / pi * sin(x) * sinc(pi / 4) + \
+        4 / (3 * pi) * sin(3 * x) * sinc(3 * pi / 4)
+
+
+def test_sawtooth_wave():
+    s = fourier_series(x, (x, 0, pi))
+    assert s.truncate(4) == \
+        pi/2 - sin(2*x) - sin(4*x)/2 - sin(6*x)/3
+    s = fourier_series(x, (x, 0, 1))
+    assert s.truncate(4) == \
+        S.Half - sin(2*pi*x)/pi - sin(4*pi*x)/(2*pi) - sin(6*pi*x)/(3*pi)
+
+
+def test_FourierSeries__operations():
+    fo, fe, fp = _get_examples()
+
+    fes = fe.scale(-1).shift(pi**2)
+    assert fes.truncate() == 4*cos(x) - cos(2*x) + 2*pi**2 / 3
+
+    assert fp.shift(-pi/2).truncate() == (2*sin(x) + (2*sin(3*x) / 3) +
+                                          (2*sin(5*x) / 5))
+
+    fos = fo.scale(3)
+    assert fos.truncate() == 6*sin(x) - 3*sin(2*x) + 2*sin(3*x)
+
+    fx = fe.scalex(2).shiftx(1)
+    assert fx.truncate() == -4*cos(2*x + 2) + cos(4*x + 4) + pi**2 / 3
+
+    fl = fe.scalex(3).shift(-pi).scalex(2).shiftx(1).scale(4)
+    assert fl.truncate() == (-16*cos(6*x + 6) + 4*cos(12*x + 12) -
+                             4*pi + 4*pi**2 / 3)
+
+    raises(ValueError, lambda: fo.shift(x))
+    raises(ValueError, lambda: fo.shiftx(sin(x)))
+    raises(ValueError, lambda: fo.scale(x*y))
+    raises(ValueError, lambda: fo.scalex(x**2))
+
+
+def test_FourierSeries__neg():
+    fo, fe, fp = _get_examples()
+
+    assert (-fo).truncate() == -2*sin(x) + sin(2*x) - (2*sin(3*x) / 3)
+    assert (-fe).truncate() == +4*cos(x) - cos(2*x) - pi**2 / 3
+
+
+def test_FourierSeries__add__sub():
+    fo, fe, fp = _get_examples()
+
+    assert fo + fo == fo.scale(2)
+    assert fo - fo == 0
+    assert -fe - fe == fe.scale(-2)
+
+    assert (fo + fe).truncate() == 2*sin(x) - sin(2*x) - 4*cos(x) + cos(2*x) \
+        + pi**2 / 3
+    assert (fo - fe).truncate() == 2*sin(x) - sin(2*x) + 4*cos(x) - cos(2*x) \
+        - pi**2 / 3
+
+    assert isinstance(fo + 1, Add)
+
+    raises(ValueError, lambda: fo + fourier_series(x, (x, 0, 2)))
+
+
+def test_FourierSeries_finite():
+
+    assert fourier_series(sin(x)).truncate(1) == sin(x)
+    # assert type(fourier_series(sin(x)*log(x))).truncate() == FourierSeries
+    # assert type(fourier_series(sin(x**2+6))).truncate() == FourierSeries
+    assert fourier_series(sin(x)*log(y)*exp(z),(x,pi,-pi)).truncate() == sin(x)*log(y)*exp(z)
+    assert fourier_series(sin(x)**6).truncate(oo) == -15*cos(2*x)/32 + 3*cos(4*x)/16 - cos(6*x)/32 \
+           + Rational(5, 16)
+    assert fourier_series(sin(x) ** 6).truncate() == -15 * cos(2 * x) / 32 + 3 * cos(4 * x) / 16 \
+           + Rational(5, 16)
+    assert fourier_series(sin(4*x+3) + cos(3*x+4)).truncate(oo) ==  -sin(4)*sin(3*x) + sin(4*x)*cos(3) \
+           + cos(4)*cos(3*x) + sin(3)*cos(4*x)
+    assert fourier_series(sin(x)+cos(x)*tan(x)).truncate(oo) == 2*sin(x)
+    assert fourier_series(cos(pi*x), (x, -1, 1)).truncate(oo) == cos(pi*x)
+    assert fourier_series(cos(3*pi*x + 4) - sin(4*pi*x)*log(pi*y), (x, -1, 1)).truncate(oo) == -log(pi*y)*sin(4*pi*x)\
+           - sin(4)*sin(3*pi*x) + cos(4)*cos(3*pi*x)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_gruntz.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_gruntz.py
new file mode 100644
index 0000000000000000000000000000000000000000..4cae15297048bc52a69a3d9ca57a7614cfcdc61c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_gruntz.py
@@ -0,0 +1,490 @@
+from sympy.core import EulerGamma
+from sympy.core.function import Function
+from sympy.core.numbers import (E, I, Integer, Rational, oo, pi)
+from sympy.core.singleton import S
+from sympy.core.symbol import Symbol
+from sympy.functions.elementary.exponential import (exp, log)
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import (acot, atan, cos, sin)
+from sympy.functions.special.error_functions import (Ei, erf)
+from sympy.functions.special.gamma_functions import (digamma, gamma, loggamma)
+from sympy.functions.special.zeta_functions import zeta
+from sympy.polys.polytools import cancel
+from sympy.functions.elementary.hyperbolic import cosh, coth, sinh, tanh
+from sympy.series.gruntz import compare, mrv, rewrite, mrv_leadterm, gruntz, \
+    sign
+from sympy.testing.pytest import XFAIL, raises, skip, slow
+
+"""
+This test suite is testing the limit algorithm using the bottom up approach.
+See the documentation in limits2.py. The algorithm itself is highly recursive
+by nature, so "compare" is logically the lowest part of the algorithm, yet in
+some sense it's the most complex part, because it needs to calculate a limit
+to return the result.
+
+Nevertheless, the rest of the algorithm depends on compare working correctly.
+"""
+
+x = Symbol('x', real=True)
+m = Symbol('m', real=True)
+
+
+runslow = False
+
+
+def _sskip():
+    if not runslow:
+        skip("slow")
+
+
+@slow
+def test_gruntz_evaluation():
+    # Gruntz' thesis pp. 122 to 123
+    # 8.1
+    assert gruntz(exp(x)*(exp(1/x - exp(-x)) - exp(1/x)), x, oo) == -1
+    # 8.2
+    assert gruntz(exp(x)*(exp(1/x + exp(-x) + exp(-x**2))
+                  - exp(1/x - exp(-exp(x)))), x, oo) == 1
+    # 8.3
+    assert gruntz(exp(exp(x - exp(-x))/(1 - 1/x)) - exp(exp(x)), x, oo) is oo
+    # 8.5
+    assert gruntz(exp(exp(exp(x + exp(-x)))) / exp(exp(exp(x))), x, oo) is oo
+    # 8.6
+    assert gruntz(exp(exp(exp(x))) / exp(exp(exp(x - exp(-exp(x))))),
+                  x, oo) is oo
+    # 8.7
+    assert gruntz(exp(exp(exp(x))) / exp(exp(exp(x - exp(-exp(exp(x)))))),
+                  x, oo) == 1
+    # 8.8
+    assert gruntz(exp(exp(x)) / exp(exp(x - exp(-exp(exp(x))))), x, oo) == 1
+    # 8.9
+    assert gruntz(log(x)**2 * exp(sqrt(log(x))*(log(log(x)))**2
+                  * exp(sqrt(log(log(x))) * (log(log(log(x))))**3)) / sqrt(x),
+                  x, oo) == 0
+    # 8.10
+    assert gruntz((x*log(x)*(log(x*exp(x) - x**2))**2)
+                  / (log(log(x**2 + 2*exp(exp(3*x**3*log(x)))))), x, oo) == Rational(1, 3)
+    # 8.11
+    assert gruntz((exp(x*exp(-x)/(exp(-x) + exp(-2*x**2/(x + 1)))) - exp(x))/x,
+                  x, oo) == -exp(2)
+    # 8.12
+    assert gruntz((3**x + 5**x)**(1/x), x, oo) == 5
+    # 8.13
+    assert gruntz(x/log(x**(log(x**(log(2)/log(x))))), x, oo) is oo
+    # 8.14
+    assert gruntz(exp(exp(2*log(x**5 + x)*log(log(x))))
+                  / exp(exp(10*log(x)*log(log(x)))), x, oo) is oo
+    # 8.15
+    assert gruntz(exp(exp(Rational(5, 2)*x**Rational(-5, 7) + Rational(21, 8)*x**Rational(6, 11)
+                          + 2*x**(-8) + Rational(54, 17)*x**Rational(49, 45)))**8
+                  / log(log(-log(Rational(4, 3)*x**Rational(-5, 14))))**Rational(7, 6), x, oo) is oo
+    # 8.16
+    assert gruntz((exp(4*x*exp(-x)/(1/exp(x) + 1/exp(2*x**2/(x + 1)))) - exp(x))
+                  / exp(x)**4, x, oo) == 1
+    # 8.17
+    assert gruntz(exp(x*exp(-x)/(exp(-x) + exp(-2*x**2/(x + 1))))/exp(x), x, oo) \
+        == 1
+    # 8.19
+    assert gruntz(log(x)*(log(log(x) + log(log(x))) - log(log(x)))
+                  / (log(log(x) + log(log(log(x))))), x, oo) == 1
+    # 8.20
+    assert gruntz(exp((log(log(x + exp(log(x)*log(log(x))))))
+                  / (log(log(log(exp(x) + x + log(x)))))), x, oo) == E
+    # Another
+    assert gruntz(exp(exp(exp(x + exp(-x)))) / exp(exp(x)), x, oo) is oo
+
+
+def test_gruntz_evaluation_slow():
+    _sskip()
+    # 8.4
+    assert gruntz(exp(exp(exp(x)/(1 - 1/x)))
+                  - exp(exp(exp(x)/(1 - 1/x - log(x)**(-log(x))))), x, oo) is -oo
+    # 8.18
+    assert gruntz((exp(exp(-x/(1 + exp(-x))))*exp(-x/(1 + exp(-x/(1 + exp(-x)))))
+                   *exp(exp(-x + exp(-x/(1 + exp(-x))))))
+                  / (exp(-x/(1 + exp(-x))))**2 - exp(x) + x, x, oo) == 2
+
+
+@slow
+def test_gruntz_eval_special():
+    # Gruntz, p. 126
+    assert gruntz(exp(x)*(sin(1/x + exp(-x)) - sin(1/x + exp(-x**2))), x, oo) == 1
+    assert gruntz((erf(x - exp(-exp(x))) - erf(x)) * exp(exp(x)) * exp(x**2),
+                  x, oo) == -2/sqrt(pi)
+    assert gruntz(exp(exp(x)) * (exp(sin(1/x + exp(-exp(x)))) - exp(sin(1/x))),
+                  x, oo) == 1
+    assert gruntz(exp(x)*(gamma(x + exp(-x)) - gamma(x)), x, oo) is oo
+    assert gruntz(exp(exp(digamma(digamma(x))))/x, x, oo) == exp(Rational(-1, 2))
+    assert gruntz(exp(exp(digamma(log(x))))/x, x, oo) == exp(Rational(-1, 2))
+    assert gruntz(digamma(digamma(digamma(x))), x, oo) is oo
+    assert gruntz(loggamma(loggamma(x)), x, oo) is oo
+    assert gruntz(((gamma(x + 1/gamma(x)) - gamma(x))/log(x) - cos(1/x))
+                  * x*log(x), x, oo) == Rational(-1, 2)
+    assert gruntz(x * (gamma(x - 1/gamma(x)) - gamma(x) + log(x)), x, oo) \
+        == S.Half
+    assert gruntz((gamma(x + 1/gamma(x)) - gamma(x)) / log(x), x, oo) == 1
+
+
+def test_gruntz_eval_special_slow():
+    _sskip()
+    assert gruntz(gamma(x + 1)/sqrt(2*pi)
+                  - exp(-x)*(x**(x + S.Half) + x**(x - S.Half)/12), x, oo) is oo
+    assert gruntz(exp(exp(exp(digamma(digamma(digamma(x))))))/x, x, oo) == 0
+
+
+@XFAIL
+def test_grunts_eval_special_slow_sometimes_fail():
+    _sskip()
+    # XXX This sometimes fails!!!
+    assert gruntz(exp(gamma(x - exp(-x))*exp(1/x)) - exp(gamma(x)), x, oo) is oo
+
+
+def test_gruntz_Ei():
+    assert gruntz((Ei(x - exp(-exp(x))) - Ei(x)) *exp(-x)*exp(exp(x))*x, x, oo) == -1
+
+
+@XFAIL
+def test_gruntz_eval_special_fail():
+    # TODO zeta function series
+    assert gruntz(
+        exp((log(2) + 1)*x) * (zeta(x + exp(-x)) - zeta(x)), x, oo) == -log(2)
+
+    # TODO 8.35 - 8.37 (bessel, max-min)
+
+
+def test_gruntz_hyperbolic():
+    assert gruntz(cosh(x), x, oo) is oo
+    assert gruntz(cosh(x), x, -oo) is oo
+    assert gruntz(sinh(x), x, oo) is oo
+    assert gruntz(sinh(x), x, -oo) is -oo
+    assert gruntz(2*cosh(x)*exp(x), x, oo) is oo
+    assert gruntz(2*cosh(x)*exp(x), x, -oo) == 1
+    assert gruntz(2*sinh(x)*exp(x), x, oo) is oo
+    assert gruntz(2*sinh(x)*exp(x), x, -oo) == -1
+    assert gruntz(tanh(x), x, oo) == 1
+    assert gruntz(tanh(x), x, -oo) == -1
+    assert gruntz(coth(x), x, oo) == 1
+    assert gruntz(coth(x), x, -oo) == -1
+
+
+def test_compare1():
+    assert compare(2, x, x) == "<"
+    assert compare(x, exp(x), x) == "<"
+    assert compare(exp(x), exp(x**2), x) == "<"
+    assert compare(exp(x**2), exp(exp(x)), x) == "<"
+    assert compare(1, exp(exp(x)), x) == "<"
+
+    assert compare(x, 2, x) == ">"
+    assert compare(exp(x), x, x) == ">"
+    assert compare(exp(x**2), exp(x), x) == ">"
+    assert compare(exp(exp(x)), exp(x**2), x) == ">"
+    assert compare(exp(exp(x)), 1, x) == ">"
+
+    assert compare(2, 3, x) == "="
+    assert compare(3, -5, x) == "="
+    assert compare(2, -5, x) == "="
+
+    assert compare(x, x**2, x) == "="
+    assert compare(x**2, x**3, x) == "="
+    assert compare(x**3, 1/x, x) == "="
+    assert compare(1/x, x**m, x) == "="
+    assert compare(x**m, -x, x) == "="
+
+    assert compare(exp(x), exp(-x), x) == "="
+    assert compare(exp(-x), exp(2*x), x) == "="
+    assert compare(exp(2*x), exp(x)**2, x) == "="
+    assert compare(exp(x)**2, exp(x + exp(-x)), x) == "="
+    assert compare(exp(x), exp(x + exp(-x)), x) == "="
+
+    assert compare(exp(x**2), 1/exp(x**2), x) == "="
+
+
+def test_compare2():
+    assert compare(exp(x), x**5, x) == ">"
+    assert compare(exp(x**2), exp(x)**2, x) == ">"
+    assert compare(exp(x), exp(x + exp(-x)), x) == "="
+    assert compare(exp(x + exp(-x)), exp(x), x) == "="
+    assert compare(exp(x + exp(-x)), exp(-x), x) == "="
+    assert compare(exp(-x), x, x) == ">"
+    assert compare(x, exp(-x), x) == "<"
+    assert compare(exp(x + 1/x), x, x) == ">"
+    assert compare(exp(-exp(x)), exp(x), x) == ">"
+    assert compare(exp(exp(-exp(x)) + x), exp(-exp(x)), x) == "<"
+
+
+def test_compare3():
+    assert compare(exp(exp(x)), exp(x + exp(-exp(x))), x) == ">"
+
+
+def test_sign1():
+    assert sign(Rational(0), x) == 0
+    assert sign(Rational(3), x) == 1
+    assert sign(Rational(-5), x) == -1
+    assert sign(log(x), x) == 1
+    assert sign(exp(-x), x) == 1
+    assert sign(exp(x), x) == 1
+    assert sign(-exp(x), x) == -1
+    assert sign(3 - 1/x, x) == 1
+    assert sign(-3 - 1/x, x) == -1
+    assert sign(sin(1/x), x) == 1
+    assert sign((x**Integer(2)), x) == 1
+    assert sign(x**2, x) == 1
+    assert sign(x**5, x) == 1
+
+
+def test_sign2():
+    assert sign(x, x) == 1
+    assert sign(-x, x) == -1
+    y = Symbol("y", positive=True)
+    assert sign(y, x) == 1
+    assert sign(-y, x) == -1
+    assert sign(y*x, x) == 1
+    assert sign(-y*x, x) == -1
+
+
+def mmrv(a, b):
+    return set(mrv(a, b)[0].keys())
+
+
+def test_mrv1():
+    assert mmrv(x, x) == {x}
+    assert mmrv(x + 1/x, x) == {x}
+    assert mmrv(x**2, x) == {x}
+    assert mmrv(log(x), x) == {x}
+    assert mmrv(exp(x), x) == {exp(x)}
+    assert mmrv(exp(-x), x) == {exp(-x)}
+    assert mmrv(exp(x**2), x) == {exp(x**2)}
+    assert mmrv(-exp(1/x), x) == {x}
+    assert mmrv(exp(x + 1/x), x) == {exp(x + 1/x)}
+
+
+def test_mrv2a():
+    assert mmrv(exp(x + exp(-exp(x))), x) == {exp(-exp(x))}
+    assert mmrv(exp(x + exp(-x)), x) == {exp(x + exp(-x)), exp(-x)}
+    assert mmrv(exp(1/x + exp(-x)), x) == {exp(-x)}
+
+#sometimes infinite recursion due to log(exp(x**2)) not simplifying
+
+
+def test_mrv2b():
+    assert mmrv(exp(x + exp(-x**2)), x) == {exp(-x**2)}
+
+#sometimes infinite recursion due to log(exp(x**2)) not simplifying
+
+
+def test_mrv2c():
+    assert mmrv(
+        exp(-x + 1/x**2) - exp(x + 1/x), x) == {exp(x + 1/x), exp(1/x**2 - x)}
+
+#sometimes infinite recursion due to log(exp(x**2)) not simplifying
+
+
+def test_mrv3():
+    assert mmrv(exp(x**2) + x*exp(x) + log(x)**x/x, x) == {exp(x**2)}
+    assert mmrv(
+        exp(x)*(exp(1/x + exp(-x)) - exp(1/x)), x) == {exp(x), exp(-x)}
+    assert mmrv(log(
+        x**2 + 2*exp(exp(3*x**3*log(x)))), x) == {exp(exp(3*x**3*log(x)))}
+    assert mmrv(log(x - log(x))/log(x), x) == {x}
+    assert mmrv(
+        (exp(1/x - exp(-x)) - exp(1/x))*exp(x), x) == {exp(x), exp(-x)}
+    assert mmrv(
+        1/exp(-x + exp(-x)) - exp(x), x) == {exp(x), exp(-x), exp(x - exp(-x))}
+    assert mmrv(log(log(x*exp(x*exp(x)) + 1)), x) == {exp(x*exp(x))}
+    assert mmrv(exp(exp(log(log(x) + 1/x))), x) == {x}
+
+
+def test_mrv4():
+    ln = log
+    assert mmrv((ln(ln(x) + ln(ln(x))) - ln(ln(x)))/ln(ln(x) + ln(ln(ln(x))))*ln(x),
+            x) == {x}
+    assert mmrv(log(log(x*exp(x*exp(x)) + 1)) - exp(exp(log(log(x) + 1/x))), x) == \
+        {exp(x*exp(x))}
+
+
+def mrewrite(a, b, c):
+    return rewrite(a[1], a[0], b, c)
+
+
+def test_rewrite1():
+    e = exp(x)
+    assert mrewrite(mrv(e, x), x, m) == (1/m, -x)
+    e = exp(x**2)
+    assert mrewrite(mrv(e, x), x, m) == (1/m, -x**2)
+    e = exp(x + 1/x)
+    assert mrewrite(mrv(e, x), x, m) == (1/m, -x - 1/x)
+    e = 1/exp(-x + exp(-x)) - exp(x)
+    assert mrewrite(mrv(e, x), x, m) == ((-m*exp(m) + m)*exp(-m)/m**2, -x)
+
+
+def test_rewrite2():
+    e = exp(x)*log(log(exp(x)))
+    assert mmrv(e, x) == {exp(x)}
+    assert mrewrite(mrv(e, x), x, m) == (1/m*log(x), -x)
+
+#sometimes infinite recursion due to log(exp(x**2)) not simplifying
+
+
+def test_rewrite3():
+    e = exp(-x + 1/x**2) - exp(x + 1/x)
+    #both of these are correct and should be equivalent:
+    assert mrewrite(mrv(e, x), x, m) in [(-1/m + m*exp(
+        (x**2 + x)/x**3), -x - 1/x), ((m**2 - exp((x**2 + x)/x**3))/m, x**(-2) - x)]
+
+
+def test_mrv_leadterm1():
+    assert mrv_leadterm(-exp(1/x), x) == (-1, 0)
+    assert mrv_leadterm(1/exp(-x + exp(-x)) - exp(x), x) == (-1, 0)
+    assert mrv_leadterm(
+        (exp(1/x - exp(-x)) - exp(1/x))*exp(x), x) == (-exp(1/x), 0)
+
+
+def test_mrv_leadterm2():
+    #Gruntz: p51, 3.25
+    assert mrv_leadterm((log(exp(x) + x) - x)/log(exp(x) + log(x))*exp(x), x) == \
+        (1, 0)
+
+
+def test_mrv_leadterm3():
+    #Gruntz: p56, 3.27
+    assert mmrv(exp(-x + exp(-x)*exp(-x*log(x))), x) == {exp(-x - x*log(x))}
+    assert mrv_leadterm(exp(-x + exp(-x)*exp(-x*log(x))), x) == (exp(-x), 0)
+
+
+def test_limit1():
+    assert gruntz(x, x, oo) is oo
+    assert gruntz(x, x, -oo) is -oo
+    assert gruntz(-x, x, oo) is -oo
+    assert gruntz(x**2, x, -oo) is oo
+    assert gruntz(-x**2, x, oo) is -oo
+    assert gruntz(x*log(x), x, 0, dir="+") == 0
+    assert gruntz(1/x, x, oo) == 0
+    assert gruntz(exp(x), x, oo) is oo
+    assert gruntz(-exp(x), x, oo) is -oo
+    assert gruntz(exp(x)/x, x, oo) is oo
+    assert gruntz(1/x - exp(-x), x, oo) == 0
+    assert gruntz(x + 1/x, x, oo) is oo
+
+
+def test_limit2():
+    assert gruntz(x**x, x, 0, dir="+") == 1
+    assert gruntz((exp(x) - 1)/x, x, 0) == 1
+    assert gruntz(1 + 1/x, x, oo) == 1
+    assert gruntz(-exp(1/x), x, oo) == -1
+    assert gruntz(x + exp(-x), x, oo) is oo
+    assert gruntz(x + exp(-x**2), x, oo) is oo
+    assert gruntz(x + exp(-exp(x)), x, oo) is oo
+    assert gruntz(13 + 1/x - exp(-x), x, oo) == 13
+
+
+def test_limit3():
+    a = Symbol('a')
+    assert gruntz(x - log(1 + exp(x)), x, oo) == 0
+    assert gruntz(x - log(a + exp(x)), x, oo) == 0
+    assert gruntz(exp(x)/(1 + exp(x)), x, oo) == 1
+    assert gruntz(exp(x)/(a + exp(x)), x, oo) == 1
+
+
+def test_limit4():
+    #issue 3463
+    assert gruntz((3**x + 5**x)**(1/x), x, oo) == 5
+    #issue 3463
+    assert gruntz((3**(1/x) + 5**(1/x))**x, x, 0) == 5
+
+
+@XFAIL
+def test_MrvTestCase_page47_ex3_21():
+    h = exp(-x/(1 + exp(-x)))
+    expr = exp(h)*exp(-x/(1 + h))*exp(exp(-x + h))/h**2 - exp(x) + x
+    assert mmrv(expr, x) == {1/h, exp(-x), exp(x), exp(x - h), exp(x/(1 + h))}
+
+
+def test_gruntz_I():
+    y = Symbol("y")
+    assert gruntz(I*x, x, oo) == I*oo
+    assert gruntz(y*I*x, x, oo) == y*I*oo
+    assert gruntz(y*3*I*x, x, oo) == y*I*oo
+    assert gruntz(y*3*sin(I)*x, x, oo) == y*I*oo
+
+
+def test_issue_4814():
+    assert gruntz((x + 1)**(1/log(x + 1)), x, oo) == E
+
+
+def test_intractable():
+    assert gruntz(1/gamma(x), x, oo) == 0
+    assert gruntz(1/loggamma(x), x, oo) == 0
+    assert gruntz(gamma(x)/loggamma(x), x, oo) is oo
+    assert gruntz(exp(gamma(x))/gamma(x), x, oo) is oo
+    assert gruntz(gamma(x), x, 3) == 2
+    assert gruntz(gamma(Rational(1, 7) + 1/x), x, oo) == gamma(Rational(1, 7))
+    assert gruntz(log(x**x)/log(gamma(x)), x, oo) == 1
+    assert gruntz(log(gamma(gamma(x)))/exp(x), x, oo) is oo
+
+
+def test_aseries_trig():
+    assert cancel(gruntz(1/log(atan(x)), x, oo)
+           - 1/(log(pi) + log(S.Half))) == 0
+    assert gruntz(1/acot(x), x, -oo) is -oo
+
+
+def test_exp_log_series():
+    assert gruntz(x/log(log(x*exp(x))), x, oo) is oo
+
+
+def test_issue_3644():
+    assert gruntz(((x**7 + x + 1)/(2**x + x**2))**(-1/x), x, oo) == 2
+
+
+def test_issue_6843():
+    n = Symbol('n', integer=True, positive=True)
+    r = (n + 1)*x**(n + 1)/(x**(n + 1) - 1) - x/(x - 1)
+    assert gruntz(r, x, 1).simplify() == n/2
+
+
+def test_issue_4190():
+    assert gruntz(x - gamma(1/x), x, oo) == S.EulerGamma
+
+
+@XFAIL
+def test_issue_5172():
+    n = Symbol('n')
+    r = Symbol('r', positive=True)
+    c = Symbol('c')
+    p = Symbol('p', positive=True)
+    m = Symbol('m', negative=True)
+    expr = ((2*n*(n - r + 1)/(n + r*(n - r + 1)))**c + \
+        (r - 1)*(n*(n - r + 2)/(n + r*(n - r + 1)))**c - n)/(n**c - n)
+    expr = expr.subs(c, c + 1)
+    assert gruntz(expr.subs(c, m), n, oo) == 1
+    # fail:
+    assert gruntz(expr.subs(c, p), n, oo).simplify() == \
+        (2**(p + 1) + r - 1)/(r + 1)**(p + 1)
+
+
+def test_issue_4109():
+    assert gruntz(1/gamma(x), x, 0) == 0
+    assert gruntz(x*gamma(x), x, 0) == 1
+
+
+def test_issue_6682():
+    assert gruntz(exp(2*Ei(-x))/x**2, x, 0) == exp(2*EulerGamma)
+
+
+def test_issue_7096():
+    from sympy.functions import sign
+    assert gruntz(x**-pi, x, 0, dir='-') == oo*sign((-1)**(-pi))
+
+
+def test_issue_7391_8166():
+    f = Function('f')
+    # limit should depend on the continuity of the expression at the point passed
+    raises(ValueError, lambda: gruntz(f(x), x, 4))
+    raises(ValueError, lambda: gruntz(x*f(x)**2/(x**2 + f(x)**4), x, 0))
+
+
+def test_issue_24210_25885():
+    eq = exp(x)/(1+1/x)**x**2
+    ans = sqrt(E)
+    assert gruntz(eq, x, oo) == ans
+    assert gruntz(1/eq, x, oo) == 1/ans
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_kauers.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_kauers.py
new file mode 100644
index 0000000000000000000000000000000000000000..bfb9044b33416bc38879649b258150ba2906250c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_kauers.py
@@ -0,0 +1,23 @@
+from sympy.series.kauers import finite_diff
+from sympy.series.kauers import finite_diff_kauers
+from sympy.abc import x, y, z, m, n, w
+from sympy.core.numbers import pi
+from sympy.functions.elementary.trigonometric import (cos, sin)
+from sympy.concrete.summations import Sum
+
+
+def test_finite_diff():
+    assert finite_diff(x**2 + 2*x + 1, x) == 2*x + 3
+    assert finite_diff(y**3 + 2*y**2 + 3*y + 5, y) == 3*y**2 + 7*y + 6
+    assert finite_diff(z**2 - 2*z + 3, z) == 2*z - 1
+    assert finite_diff(w**2 + 3*w - 2, w) == 2*w + 4
+    assert finite_diff(sin(x), x, pi/6) == -sin(x) + sin(x + pi/6)
+    assert finite_diff(cos(y), y, pi/3) == -cos(y) + cos(y + pi/3)
+    assert finite_diff(x**2 - 2*x + 3, x, 2) == 4*x
+    assert finite_diff(n**2 - 2*n + 3, n, 3) == 6*n + 3
+
+def test_finite_diff_kauers():
+    assert finite_diff_kauers(Sum(x**2, (x, 1, n))) == (n + 1)**2
+    assert finite_diff_kauers(Sum(y, (y, 1, m))) == (m + 1)
+    assert finite_diff_kauers(Sum((x*y), (x, 1, m), (y, 1, n))) == (m + 1)*(n + 1)
+    assert finite_diff_kauers(Sum((x*y**2), (x, 1, m), (y, 1, n))) == (n + 1)**2*(m + 1)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_limits.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_limits.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa3ab7683f057424f1c3215a06381d27687710dc
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_limits.py
@@ -0,0 +1,1440 @@
+from itertools import product
+
+from sympy.concrete.summations import Sum
+from sympy.core.function import (Function, diff)
+from sympy.core import EulerGamma, GoldenRatio
+from sympy.core.mod import Mod
+from sympy.core.numbers import (E, I, Rational, oo, pi, zoo)
+from sympy.core.singleton import S
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.functions.combinatorial.numbers import fibonacci
+from sympy.functions.combinatorial.factorials import (binomial, factorial, subfactorial)
+from sympy.functions.elementary.complexes import (Abs, re, sign)
+from sympy.functions.elementary.exponential import (LambertW, exp, log)
+from sympy.functions.elementary.hyperbolic import (atanh, asinh, acosh, acoth, acsch, asech, tanh, sinh)
+from sympy.functions.elementary.integers import (ceiling, floor, frac)
+from sympy.functions.elementary.miscellaneous import (cbrt, real_root, sqrt)
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.functions.elementary.trigonometric import (acos, acot, acsc, asec, asin,
+                                                      atan, cos, cot, csc, sec, sin, tan)
+from sympy.functions.special.bessel import (besseli, bessely, besselj, besselk)
+from sympy.functions.special.error_functions import (Ei, erf, erfc, erfi, fresnelc, fresnels)
+from sympy.functions.special.gamma_functions import (digamma, gamma, uppergamma)
+from sympy.functions.special.hyper import meijerg
+from sympy.integrals.integrals import (Integral, integrate)
+from sympy.series.limits import (Limit, limit)
+from sympy.simplify.simplify import (logcombine, simplify)
+from sympy.simplify.hyperexpand import hyperexpand
+
+from sympy.calculus.accumulationbounds import AccumBounds
+from sympy.core.mul import Mul
+from sympy.series.limits import heuristics
+from sympy.series.order import Order
+from sympy.testing.pytest import XFAIL, raises
+
+from sympy import elliptic_e, elliptic_k
+
+from sympy.abc import x, y, z, k
+n = Symbol('n', integer=True, positive=True)
+
+
+def test_basic1():
+    assert limit(x, x, oo) is oo
+    assert limit(x, x, -oo) is -oo
+    assert limit(-x, x, oo) is -oo
+    assert limit(x**2, x, -oo) is oo
+    assert limit(-x**2, x, oo) is -oo
+    assert limit(x*log(x), x, 0, dir="+") == 0
+    assert limit(1/x, x, oo) == 0
+    assert limit(exp(x), x, oo) is oo
+    assert limit(-exp(x), x, oo) is -oo
+    assert limit(exp(x)/x, x, oo) is oo
+    assert limit(1/x - exp(-x), x, oo) == 0
+    assert limit(x + 1/x, x, oo) is oo
+    assert limit(x - x**2, x, oo) is -oo
+    assert limit((1 + x)**(1 + sqrt(2)), x, 0) == 1
+    assert limit((1 + x)**oo, x, 0) == Limit((x + 1)**oo, x, 0)
+    assert limit((1 + x)**oo, x, 0, dir='-') == Limit((x + 1)**oo, x, 0, dir='-')
+    assert limit((1 + x + y)**oo, x, 0, dir='-') == Limit((1 + x + y)**oo, x, 0, dir='-')
+    assert limit(y/x/log(x), x, 0) == -oo*sign(y)
+    assert limit(cos(x + y)/x, x, 0) == sign(cos(y))*oo
+    assert limit(gamma(1/x + 3), x, oo) == 2
+    assert limit(S.NaN, x, -oo) is S.NaN
+    assert limit(Order(2)*x, x, S.NaN) is S.NaN
+    assert limit(1/(x - 1), x, 1, dir="+") is oo
+    assert limit(1/(x - 1), x, 1, dir="-") is -oo
+    assert limit(1/(5 - x)**3, x, 5, dir="+") is -oo
+    assert limit(1/(5 - x)**3, x, 5, dir="-") is oo
+    assert limit(1/sin(x), x, pi, dir="+") is -oo
+    assert limit(1/sin(x), x, pi, dir="-") is oo
+    assert limit(1/cos(x), x, pi/2, dir="+") is -oo
+    assert limit(1/cos(x), x, pi/2, dir="-") is oo
+    assert limit(1/tan(x**3), x, (2*pi)**Rational(1, 3), dir="+") is oo
+    assert limit(1/tan(x**3), x, (2*pi)**Rational(1, 3), dir="-") is -oo
+    assert limit(1/cot(x)**3, x, (pi*Rational(3, 2)), dir="+") is -oo
+    assert limit(1/cot(x)**3, x, (pi*Rational(3, 2)), dir="-") is oo
+    assert limit(tan(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity)
+    assert limit(cot(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity)
+    assert limit(sec(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity)
+    assert limit(csc(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity)
+
+    # test bi-directional limits
+    assert limit(sin(x)/x, x, 0, dir="+-") == 1
+    assert limit(x**2, x, 0, dir="+-") == 0
+    assert limit(1/x**2, x, 0, dir="+-") is oo
+
+    # test failing bi-directional limits
+    assert limit(1/x, x, 0, dir="+-") is zoo
+    # approaching 0
+    # from dir="+"
+    assert limit(1 + 1/x, x, 0) is oo
+    # from dir='-'
+    # Add
+    assert limit(1 + 1/x, x, 0, dir='-') is -oo
+    # Pow
+    assert limit(x**(-2), x, 0, dir='-') is oo
+    assert limit(x**(-3), x, 0, dir='-') is -oo
+    assert limit(1/sqrt(x), x, 0, dir='-') == (-oo)*I
+    assert limit(x**2, x, 0, dir='-') == 0
+    assert limit(sqrt(x), x, 0, dir='-') == 0
+    assert limit(x**-pi, x, 0, dir='-') == -oo*(-1)**(1 - pi)
+    assert limit((1 + cos(x))**oo, x, 0) == Limit((cos(x) + 1)**oo, x, 0)
+
+    # test pull request 22491
+    assert limit(1/asin(x), x, 0, dir = '+') == oo
+    assert limit(1/asin(x), x, 0, dir = '-') == -oo
+    assert limit(1/sinh(x), x, 0, dir = '+') == oo
+    assert limit(1/sinh(x), x, 0, dir = '-') == -oo
+    assert limit(log(1/x) + 1/sin(x), x, 0, dir = '+') == oo
+    assert limit(log(1/x) + 1/x, x, 0, dir = '+') == oo
+
+
+def test_basic2():
+    assert limit(x**x, x, 0, dir="+") == 1
+    assert limit((exp(x) - 1)/x, x, 0) == 1
+    assert limit(1 + 1/x, x, oo) == 1
+    assert limit(-exp(1/x), x, oo) == -1
+    assert limit(x + exp(-x), x, oo) is oo
+    assert limit(x + exp(-x**2), x, oo) is oo
+    assert limit(x + exp(-exp(x)), x, oo) is oo
+    assert limit(13 + 1/x - exp(-x), x, oo) == 13
+
+
+def test_basic3():
+    assert limit(1/x, x, 0, dir="+") is oo
+    assert limit(1/x, x, 0, dir="-") is -oo
+
+
+def test_basic4():
+    assert limit(2*x + y*x, x, 0) == 0
+    assert limit(2*x + y*x, x, 1) == 2 + y
+    assert limit(2*x**8 + y*x**(-3), x, -2) == 512 - y/8
+    assert limit(sqrt(x + 1) - sqrt(x), x, oo) == 0
+    assert integrate(1/(x**3 + 1), (x, 0, oo)) == 2*pi*sqrt(3)/9
+
+
+def test_log():
+    # https://github.com/sympy/sympy/issues/21598
+    a, b, c = symbols('a b c', positive=True)
+    A = log(a/b) - (log(a) - log(b))
+    assert A.limit(a, oo) == 0
+    assert (A * c).limit(a, oo) == 0
+
+    tau, x = symbols('tau x', positive=True)
+    # The value of manualintegrate in the issue
+    expr = tau**2*((tau - 1)*(tau + 1)*log(x + 1)/(tau**2 + 1)**2 + 1/((tau**2\
+            + 1)*(x + 1)) - (-2*tau*atan(x/tau) + (tau**2/2 - 1/2)*log(tau**2\
+            + x**2))/(tau**2 + 1)**2)
+    assert limit(expr, x, oo) == pi*tau**3/(tau**2 + 1)**2
+
+
+def test_piecewise():
+    # https://github.com/sympy/sympy/issues/18363
+    assert limit((real_root(x - 6, 3) + 2)/(x + 2), x, -2, '+') == Rational(1, 12)
+
+
+def test_piecewise2():
+    func1 = 2*sqrt(x)*Piecewise(((4*x - 2)/Abs(sqrt(4 - 4*(2*x - 1)**2)), 4*x - 2\
+            >= 0), ((2 - 4*x)/Abs(sqrt(4 - 4*(2*x - 1)**2)), True))
+    func2 = Piecewise((x**2/2, x <= 0.5), (x/2 - 0.125, True))
+    func3 = Piecewise(((x - 9) / 5, x < -1), ((x - 9) / 5, x > 4), (sqrt(Abs(x - 3)), True))
+    assert limit(func1, x, 0) == 1
+    assert limit(func2, x, 0) == 0
+    assert limit(func3, x, -1) == 2
+
+
+def test_basic5():
+    class my(Function):
+        @classmethod
+        def eval(cls, arg):
+            if arg is S.Infinity:
+                return S.NaN
+    assert limit(my(x), x, oo) == Limit(my(x), x, oo)
+
+
+def test_issue_3885():
+    assert limit(x*y + x*z, z, 2) == x*y + 2*x
+
+
+def test_Limit():
+    assert Limit(sin(x)/x, x, 0) != 1
+    assert Limit(sin(x)/x, x, 0).doit() == 1
+    assert Limit(x, x, 0, dir='+-').args == (x, x, 0, Symbol('+-'))
+
+
+def test_floor():
+    assert limit(floor(x), x, -2, "+") == -2
+    assert limit(floor(x), x, -2, "-") == -3
+    assert limit(floor(x), x, -1, "+") == -1
+    assert limit(floor(x), x, -1, "-") == -2
+    assert limit(floor(x), x, 0, "+") == 0
+    assert limit(floor(x), x, 0, "-") == -1
+    assert limit(floor(x), x, 1, "+") == 1
+    assert limit(floor(x), x, 1, "-") == 0
+    assert limit(floor(x), x, 2, "+") == 2
+    assert limit(floor(x), x, 2, "-") == 1
+    assert limit(floor(x), x, 248, "+") == 248
+    assert limit(floor(x), x, 248, "-") == 247
+
+    # https://github.com/sympy/sympy/issues/14478
+    assert limit(x*floor(3/x)/2, x, 0, '+') == Rational(3, 2)
+    assert limit(floor(x + 1/2) - floor(x), x, oo) == AccumBounds(-S.Half, S(3)/2)
+
+    # test issue 9158
+    assert limit(floor(atan(x)), x, oo) == 1
+    assert limit(floor(atan(x)), x, -oo) == -2
+    assert limit(ceiling(atan(x)), x, oo) == 2
+    assert limit(ceiling(atan(x)), x, -oo) == -1
+
+
+def test_floor_requires_robust_assumptions():
+    assert limit(floor(sin(x)), x, 0, "+") == 0
+    assert limit(floor(sin(x)), x, 0, "-") == -1
+    assert limit(floor(cos(x)), x, 0, "+") == 0
+    assert limit(floor(cos(x)), x, 0, "-") == 0
+    assert limit(floor(5 + sin(x)), x, 0, "+") == 5
+    assert limit(floor(5 + sin(x)), x, 0, "-") == 4
+    assert limit(floor(5 + cos(x)), x, 0, "+") == 5
+    assert limit(floor(5 + cos(x)), x, 0, "-") == 5
+
+
+def test_ceiling():
+    assert limit(ceiling(x), x, -2, "+") == -1
+    assert limit(ceiling(x), x, -2, "-") == -2
+    assert limit(ceiling(x), x, -1, "+") == 0
+    assert limit(ceiling(x), x, -1, "-") == -1
+    assert limit(ceiling(x), x, 0, "+") == 1
+    assert limit(ceiling(x), x, 0, "-") == 0
+    assert limit(ceiling(x), x, 1, "+") == 2
+    assert limit(ceiling(x), x, 1, "-") == 1
+    assert limit(ceiling(x), x, 2, "+") == 3
+    assert limit(ceiling(x), x, 2, "-") == 2
+    assert limit(ceiling(x), x, 248, "+") == 249
+    assert limit(ceiling(x), x, 248, "-") == 248
+
+    # https://github.com/sympy/sympy/issues/14478
+    assert limit(x*ceiling(3/x)/2, x, 0, '+') == Rational(3, 2)
+    assert limit(ceiling(x + 1/2) - ceiling(x), x, oo) == AccumBounds(-S.Half, S(3)/2)
+
+
+def test_ceiling_requires_robust_assumptions():
+    assert limit(ceiling(sin(x)), x, 0, "+") == 1
+    assert limit(ceiling(sin(x)), x, 0, "-") == 0
+    assert limit(ceiling(cos(x)), x, 0, "+") == 1
+    assert limit(ceiling(cos(x)), x, 0, "-") == 1
+    assert limit(ceiling(5 + sin(x)), x, 0, "+") == 6
+    assert limit(ceiling(5 + sin(x)), x, 0, "-") == 5
+    assert limit(ceiling(5 + cos(x)), x, 0, "+") == 6
+    assert limit(ceiling(5 + cos(x)), x, 0, "-") == 6
+
+
+def test_frac():
+    assert limit(frac(x), x, oo) == AccumBounds(0, 1)
+    assert limit(frac(x)**(1/x), x, oo) == AccumBounds(0, 1)
+    assert limit(frac(x)**(1/x), x, -oo) == AccumBounds(1, oo)
+    assert limit(frac(x)**x, x, oo) == AccumBounds(0, oo)  # wolfram gives (0, 1)
+    assert limit(frac(sin(x)), x, 0, "+") == 0
+    assert limit(frac(sin(x)), x, 0, "-") == 1
+    assert limit(frac(cos(x)), x, 0, "+-") == 1
+    assert limit(frac(x**2), x, 0, "+-") == 0
+    raises(ValueError, lambda: limit(frac(x), x, 0, '+-'))
+    assert limit(frac(-2*x + 1), x, 0, "+") == 1
+    assert limit(frac(-2*x + 1), x, 0, "-") == 0
+    assert limit(frac(x + S.Half), x, 0, "+-") == S(1)/2
+    assert limit(frac(1/x), x, 0) == AccumBounds(0, 1)
+
+
+def test_issue_14355():
+    assert limit(floor(sin(x)/x), x, 0, '+') == 0
+    assert limit(floor(sin(x)/x), x, 0, '-') == 0
+    # test comment https://github.com/sympy/sympy/issues/14355#issuecomment-372121314
+    assert limit(floor(-tan(x)/x), x, 0, '+') == -2
+    assert limit(floor(-tan(x)/x), x, 0, '-') == -2
+
+
+def test_atan():
+    x = Symbol("x", real=True)
+    assert limit(atan(x)*sin(1/x), x, 0) == 0
+    assert limit(atan(x) + sqrt(x + 1) - sqrt(x), x, oo) == pi/2
+
+
+def test_set_signs():
+    assert limit(abs(x), x, 0) == 0
+    assert limit(abs(sin(x)), x, 0) == 0
+    assert limit(abs(cos(x)), x, 0) == 1
+    assert limit(abs(sin(x + 1)), x, 0) == sin(1)
+
+    # https://github.com/sympy/sympy/issues/9449
+    assert limit((Abs(x + y) - Abs(x - y))/(2*x), x, 0) == sign(y)
+
+    # https://github.com/sympy/sympy/issues/12398
+    assert limit(Abs(log(x)/x**3), x, oo) == 0
+    assert limit(x*(Abs(log(x)/x**3)/Abs(log(x + 1)/(x + 1)**3) - 1), x, oo) == 3
+
+    # https://github.com/sympy/sympy/issues/18501
+    assert limit(Abs(log(x - 1)**3 - 1), x, 1, '+') == oo
+
+    # https://github.com/sympy/sympy/issues/18997
+    assert limit(Abs(log(x)), x, 0) == oo
+    assert limit(Abs(log(Abs(x))), x, 0) == oo
+
+    # https://github.com/sympy/sympy/issues/19026
+    z = Symbol('z', positive=True)
+    assert limit(Abs(log(z) + 1)/log(z), z, oo) == 1
+
+    # https://github.com/sympy/sympy/issues/20704
+    assert limit(z*(Abs(1/z + y) - Abs(y - 1/z))/2, z, 0) == 0
+
+    # https://github.com/sympy/sympy/issues/21606
+    assert limit(cos(z)/sign(z), z, pi, '-') == -1
+
+
+def test_heuristic():
+    x = Symbol("x", real=True)
+    assert heuristics(sin(1/x) + atan(x), x, 0, '+') == AccumBounds(-1, 1)
+    assert limit(log(2 + sqrt(atan(x))*sqrt(sin(1/x))), x, 0) == log(2)
+
+
+def test_issue_3871():
+    z = Symbol("z", positive=True)
+    f = -1/z*exp(-z*x)
+    assert limit(f, x, oo) == 0
+    assert f.limit(x, oo) == 0
+
+
+def test_exponential():
+    n = Symbol('n')
+    x = Symbol('x', real=True)
+    assert limit((1 + x/n)**n, n, oo) == exp(x)
+    assert limit((1 + x/(2*n))**n, n, oo) == exp(x/2)
+    assert limit((1 + x/(2*n + 1))**n, n, oo) == exp(x/2)
+    assert limit(((x - 1)/(x + 1))**x, x, oo) == exp(-2)
+    assert limit(1 + (1 + 1/x)**x, x, oo) == 1 + S.Exp1
+    assert limit((2 + 6*x)**x/(6*x)**x, x, oo) == exp(S('1/3'))
+
+
+def test_exponential2():
+    n = Symbol('n')
+    assert limit((1 + x/(n + sin(n)))**n, n, oo) == exp(x)
+
+
+def test_doit():
+    f = Integral(2 * x, x)
+    l = Limit(f, x, oo)
+    assert l.doit() is oo
+
+
+def test_series_AccumBounds():
+    assert limit(sin(k) - sin(k + 1), k, oo) == AccumBounds(-2, 2)
+    assert limit(cos(k) - cos(k + 1) + 1, k, oo) == AccumBounds(-1, 3)
+
+    # not the exact bound
+    assert limit(sin(k) - sin(k)*cos(k), k, oo) == AccumBounds(-2, 2)
+
+    # test for issue #9934
+    lo = (-3 + cos(1))/2
+    hi = (1 + cos(1))/2
+    t1 = Mul(AccumBounds(lo, hi), 1/(-1 + cos(1)), evaluate=False)
+    assert limit(simplify(Sum(cos(n).rewrite(exp), (n, 0, k)).doit().rewrite(sin)), k, oo) == t1
+
+    t2 = Mul(AccumBounds(-1 + sin(1)/2, sin(1)/2 + 1), 1/(1 - cos(1)))
+    assert limit(simplify(Sum(sin(n).rewrite(exp), (n, 0, k)).doit().rewrite(sin)), k, oo) == t2
+
+    assert limit(((sin(x) + 1)/2)**x, x, oo) == AccumBounds(0, oo)  # wolfram says 0
+
+    # https://github.com/sympy/sympy/issues/12312
+    e = 2**(-x)*(sin(x) + 1)**x
+    assert limit(e, x, oo) == AccumBounds(0, oo)
+
+
+def test_bessel_functions_at_infinity():
+    # Pull Request 23844 implements limits for all bessel and modified bessel
+    # functions approaching infinity along any direction i.e. abs(z0) tends to oo
+
+    assert limit(besselj(1, x), x, oo) == 0
+    assert limit(besselj(1, x), x, -oo) == 0
+    assert limit(besselj(1, x), x, I*oo) == oo*I
+    assert limit(besselj(1, x), x, -I*oo) == -oo*I
+    assert limit(bessely(1, x), x, oo) == 0
+    assert limit(bessely(1, x), x, -oo) == 0
+    assert limit(bessely(1, x), x, I*oo) == -oo
+    assert limit(bessely(1, x), x, -I*oo) == -oo
+    assert limit(besseli(1, x), x, oo) == oo
+    assert limit(besseli(1, x), x, -oo) == -oo
+    assert limit(besseli(1, x), x, I*oo) == 0
+    assert limit(besseli(1, x), x, -I*oo) == 0
+    assert limit(besselk(1, x), x, oo) == 0
+    assert limit(besselk(1, x), x, -oo) == -oo*I
+    assert limit(besselk(1, x), x, I*oo) == 0
+    assert limit(besselk(1, x), x, -I*oo) == 0
+
+    # test issue 14874
+    assert limit(besselk(0, x), x, oo) == 0
+
+
+@XFAIL
+def test_doit2():
+    f = Integral(2 * x, x)
+    l = Limit(f, x, oo)
+    # limit() breaks on the contained Integral.
+    assert l.doit(deep=False) == l
+
+
+def test_issue_2929():
+    assert limit((x * exp(x))/(exp(x) - 1), x, -oo) == 0
+
+
+def test_issue_3792():
+    assert limit((1 - cos(x))/x**2, x, S.Half) == 4 - 4*cos(S.Half)
+    assert limit(sin(sin(x + 1) + 1), x, 0) == sin(1 + sin(1))
+    assert limit(abs(sin(x + 1) + 1), x, 0) == 1 + sin(1)
+
+
+def test_issue_4090():
+    assert limit(1/(x + 3), x, 2) == Rational(1, 5)
+    assert limit(1/(x + pi), x, 2) == S.One/(2 + pi)
+    assert limit(log(x)/(x**2 + 3), x, 2) == log(2)/7
+    assert limit(log(x)/(x**2 + pi), x, 2) == log(2)/(4 + pi)
+
+
+def test_issue_4547():
+    assert limit(cot(x), x, 0, dir='+') is oo
+    assert limit(cot(x), x, pi/2, dir='+') == 0
+
+
+def test_issue_5164():
+    assert limit(x**0.5, x, oo) == oo**0.5 is oo
+    assert limit(x**0.5, x, 16) == 4 # Should this be a float?
+    assert limit(x**0.5, x, 0) == 0
+    assert limit(x**(-0.5), x, oo) == 0
+    assert limit(x**(-0.5), x, 4) == S.Half # Should this be a float?
+
+
+def test_issue_5383():
+    func = (1.0 * 1 + 1.0 * x)**(1.0 * 1 / x)
+    assert limit(func, x, 0) == E
+
+
+def test_issue_14793():
+    expr = ((x + S(1)/2) * log(x) - x + log(2*pi)/2 - \
+        log(factorial(x)) + S(1)/(12*x))*x**3
+    assert limit(expr, x, oo) == S(1)/360
+
+
+def test_issue_5183():
+    # using list(...) so py.test can recalculate values
+    tests = list(product([x, -x],
+                         [-1, 1],
+                         [2, 3, S.Half, Rational(2, 3)],
+                         ['-', '+']))
+    results = (oo, oo, -oo, oo, -oo*I, oo, -oo*(-1)**Rational(1, 3), oo,
+               0, 0, 0, 0, 0, 0, 0, 0,
+               oo, oo, oo, -oo, oo, -oo*I, oo, -oo*(-1)**Rational(1, 3),
+               0, 0, 0, 0, 0, 0, 0, 0)
+    assert len(tests) == len(results)
+    for i, (args, res) in enumerate(zip(tests, results)):
+        y, s, e, d = args
+        eq = y**(s*e)
+        try:
+            assert limit(eq, x, 0, dir=d) == res
+        except AssertionError:
+            if 0:  # change to 1 if you want to see the failing tests
+                print()
+                print(i, res, eq, d, limit(eq, x, 0, dir=d))
+            else:
+                assert None
+
+
+def test_issue_5184():
+    assert limit(sin(x)/x, x, oo) == 0
+    assert limit(atan(x), x, oo) == pi/2
+    assert limit(gamma(x), x, oo) is oo
+    assert limit(cos(x)/x, x, oo) == 0
+    assert limit(gamma(x), x, S.Half) == sqrt(pi)
+
+    r = Symbol('r', real=True)
+    assert limit(r*sin(1/r), r, 0) == 0
+
+
+def test_issue_5229():
+    assert limit((1 + y)**(1/y) - S.Exp1, y, 0) == 0
+
+
+def test_issue_4546():
+    # using list(...) so py.test can recalculate values
+    tests = list(product([cot, tan],
+                         [-pi/2, 0, pi/2, pi, pi*Rational(3, 2)],
+                         ['-', '+']))
+    results = (0, 0, -oo, oo, 0, 0, -oo, oo, 0, 0,
+               oo, -oo, 0, 0, oo, -oo, 0, 0, oo, -oo)
+    assert len(tests) == len(results)
+    for i, (args, res) in enumerate(zip(tests, results)):
+        f, l, d = args
+        eq = f(x)
+        try:
+            assert limit(eq, x, l, dir=d) == res
+        except AssertionError:
+            if 0:  # change to 1 if you want to see the failing tests
+                print()
+                print(i, res, eq, l, d, limit(eq, x, l, dir=d))
+            else:
+                assert None
+
+
+def test_issue_3934():
+    assert limit((1 + x**log(3))**(1/x), x, 0) == 1
+    assert limit((5**(1/x) + 3**(1/x))**x, x, 0) == 5
+
+
+def test_issue_5955():
+    assert limit((x**16)/(1 + x**16), x, oo) == 1
+    assert limit((x**100)/(1 + x**100), x, oo) == 1
+    assert limit((x**1885)/(1 + x**1885), x, oo) == 1
+    assert limit((x**1000/((x + 1)**1000 + exp(-x))), x, oo) == 1
+
+
+def test_newissue():
+    assert limit(exp(1/sin(x))/exp(cot(x)), x, 0) == 1
+
+
+def test_extended_real_line():
+    assert limit(x - oo, x, oo) == Limit(x - oo, x, oo)
+    assert limit(1/(x + sin(x)) - oo, x, 0) == Limit(1/(x + sin(x)) - oo, x, 0)
+    assert limit(oo/x, x, oo) == Limit(oo/x, x, oo)
+    assert limit(x - oo + 1/x, x, oo) == Limit(x - oo + 1/x, x, oo)
+
+
+@XFAIL
+def test_order_oo():
+    x = Symbol('x', positive=True)
+    assert Order(x)*oo != Order(1, x)
+    assert limit(oo/(x**2 - 4), x, oo) is oo
+
+
+def test_issue_5436():
+    raises(NotImplementedError, lambda: limit(exp(x*y), x, oo))
+    raises(NotImplementedError, lambda: limit(exp(-x*y), x, oo))
+
+
+def test_Limit_dir():
+    raises(TypeError, lambda: Limit(x, x, 0, dir=0))
+    raises(ValueError, lambda: Limit(x, x, 0, dir='0'))
+
+
+def test_polynomial():
+    assert limit((x + 1)**1000/((x + 1)**1000 + 1), x, oo) == 1
+    assert limit((x + 1)**1000/((x + 1)**1000 + 1), x, -oo) == 1
+    assert limit(x ** Rational(77, 3) / (1 + x ** Rational(77, 3)), x, oo) == 1
+    assert limit(x ** 101.1 / (1 + x ** 101.1), x, oo) == 1
+
+
+def test_rational():
+    assert limit(1/y - (1/(y + x) + x/(y + x)/y)/z, x, oo) == (z - 1)/(y*z)
+    assert limit(1/y - (1/(y + x) + x/(y + x)/y)/z, x, -oo) == (z - 1)/(y*z)
+
+
+def test_issue_5740():
+    assert limit(log(x)*z - log(2*x)*y, x, 0) == oo*sign(y - z)
+
+
+def test_issue_6366():
+    n = Symbol('n', integer=True, positive=True)
+    r = (n + 1)*x**(n + 1)/(x**(n + 1) - 1) - x/(x - 1)
+    assert limit(r, x, 1).cancel() == n/2
+
+
+def test_factorial():
+    f = factorial(x)
+    assert limit(f, x, oo) is oo
+    assert limit(x/f, x, oo) == 0
+    # see Stirling's approximation:
+    # https://en.wikipedia.org/wiki/Stirling's_approximation
+    assert limit(f/(sqrt(2*pi*x)*(x/E)**x), x, oo) == 1
+    assert limit(f, x, -oo) == gamma(-oo)
+
+
+def test_issue_6560():
+    e = (5*x**3/4 - x*Rational(3, 4) + (y*(3*x**2/2 - S.Half) +
+                             35*x**4/8 - 15*x**2/4 + Rational(3, 8))/(2*(y + 1)))
+    assert limit(e, y, oo) == 5*x**3/4 + 3*x**2/4 - 3*x/4 - Rational(1, 4)
+
+@XFAIL
+def test_issue_5172():
+    n = Symbol('n')
+    r = Symbol('r', positive=True)
+    c = Symbol('c')
+    p = Symbol('p', positive=True)
+    m = Symbol('m', negative=True)
+    expr = ((2*n*(n - r + 1)/(n + r*(n - r + 1)))**c +
+            (r - 1)*(n*(n - r + 2)/(n + r*(n - r + 1)))**c - n)/(n**c - n)
+    expr = expr.subs(c, c + 1)
+    raises(NotImplementedError, lambda: limit(expr, n, oo))
+    assert limit(expr.subs(c, m), n, oo) == 1
+    assert limit(expr.subs(c, p), n, oo).simplify() == \
+        (2**(p + 1) + r - 1)/(r + 1)**(p + 1)
+
+
+def test_issue_7088():
+    a = Symbol('a')
+    assert limit(sqrt(x/(x + a)), x, oo) == 1
+
+
+def test_branch_cuts():
+    assert limit(asin(I*x + 2), x, 0) == pi - asin(2)
+    assert limit(asin(I*x + 2), x, 0, '-') == asin(2)
+    assert limit(asin(I*x - 2), x, 0) == -asin(2)
+    assert limit(asin(I*x - 2), x, 0, '-') == -pi + asin(2)
+    assert limit(acos(I*x + 2), x, 0) == -acos(2)
+    assert limit(acos(I*x + 2), x, 0, '-') == acos(2)
+    assert limit(acos(I*x - 2), x, 0) == acos(-2)
+    assert limit(acos(I*x - 2), x, 0, '-') == 2*pi - acos(-2)
+    assert limit(atan(x + 2*I), x, 0) == I*atanh(2)
+    assert limit(atan(x + 2*I), x, 0, '-') == -pi + I*atanh(2)
+    assert limit(atan(x - 2*I), x, 0) == pi - I*atanh(2)
+    assert limit(atan(x - 2*I), x, 0, '-') == -I*atanh(2)
+    assert limit(atan(1/x), x, 0) == pi/2
+    assert limit(atan(1/x), x, 0, '-') == -pi/2
+    assert limit(atan(x), x, oo) == pi/2
+    assert limit(atan(x), x, -oo) == -pi/2
+    assert limit(acot(x + S(1)/2*I), x, 0) == pi - I*acoth(S(1)/2)
+    assert limit(acot(x + S(1)/2*I), x, 0, '-') == -I*acoth(S(1)/2)
+    assert limit(acot(x - S(1)/2*I), x, 0) == I*acoth(S(1)/2)
+    assert limit(acot(x - S(1)/2*I), x, 0, '-') == -pi + I*acoth(S(1)/2)
+    assert limit(acot(x), x, 0) == pi/2
+    assert limit(acot(x), x, 0, '-') == -pi/2
+    assert limit(asec(I*x + S(1)/2), x, 0) == asec(S(1)/2)
+    assert limit(asec(I*x + S(1)/2), x, 0, '-') == -asec(S(1)/2)
+    assert limit(asec(I*x - S(1)/2), x, 0) == 2*pi - asec(-S(1)/2)
+    assert limit(asec(I*x - S(1)/2), x, 0, '-') == asec(-S(1)/2)
+    assert limit(acsc(I*x + S(1)/2), x, 0) == acsc(S(1)/2)
+    assert limit(acsc(I*x + S(1)/2), x, 0, '-') == pi - acsc(S(1)/2)
+    assert limit(acsc(I*x - S(1)/2), x, 0) == -pi + acsc(S(1)/2)
+    assert limit(acsc(I*x - S(1)/2), x, 0, '-') == -acsc(S(1)/2)
+
+    assert limit(log(I*x - 1), x, 0) == I*pi
+    assert limit(log(I*x - 1), x, 0, '-') == -I*pi
+    assert limit(log(-I*x - 1), x, 0) == -I*pi
+    assert limit(log(-I*x - 1), x, 0, '-') == I*pi
+
+    assert limit(sqrt(I*x - 1), x, 0) == I
+    assert limit(sqrt(I*x - 1), x, 0, '-') == -I
+    assert limit(sqrt(-I*x - 1), x, 0) == -I
+    assert limit(sqrt(-I*x - 1), x, 0, '-') == I
+
+    assert limit(cbrt(I*x - 1), x, 0) == (-1)**(S(1)/3)
+    assert limit(cbrt(I*x - 1), x, 0, '-') == -(-1)**(S(2)/3)
+    assert limit(cbrt(-I*x - 1), x, 0) == -(-1)**(S(2)/3)
+    assert limit(cbrt(-I*x - 1), x, 0, '-') == (-1)**(S(1)/3)
+
+
+def test_issue_6364():
+    a = Symbol('a')
+    e = z/(1 - sqrt(1 + z)*sin(a)**2 - sqrt(1 - z)*cos(a)**2)
+    assert limit(e, z, 0) == 1/(cos(a)**2 - S.Half)
+
+
+def test_issue_6682():
+    assert limit(exp(2*Ei(-x))/x**2, x, 0) == exp(2*EulerGamma)
+
+
+def test_issue_4099():
+    a = Symbol('a')
+    assert limit(a/x, x, 0) == oo*sign(a)
+    assert limit(-a/x, x, 0) == -oo*sign(a)
+    assert limit(-a*x, x, oo) == -oo*sign(a)
+    assert limit(a*x, x, oo) == oo*sign(a)
+
+
+def test_issue_4503():
+    dx = Symbol('dx')
+    assert limit((sqrt(1 + exp(x + dx)) - sqrt(1 + exp(x)))/dx, dx, 0) == \
+        exp(x)/(2*sqrt(exp(x) + 1))
+
+
+def test_issue_6052():
+    G = meijerg((), (), (1,), (0,), -x)
+    g = hyperexpand(G)
+    assert limit(g, x, 0, '+-') == 0
+    assert limit(g, x, oo) == -oo
+
+
+def test_issue_7224():
+    expr = sqrt(x)*besseli(1,sqrt(8*x))
+    assert limit(x*diff(expr, x, x)/expr, x, 0) == 2
+    assert limit(x*diff(expr, x, x)/expr, x, 1).evalf() == 2.0
+
+
+def test_issue_7391_8166():
+    f = Function('f')
+    # limit should depend on the continuity of the expression at the point passed
+    assert limit(f(x), x, 4) == Limit(f(x), x, 4, dir='+')
+    assert limit(x*f(x)**2/(x**2 + f(x)**4), x, 0) == Limit(x*f(x)**2/(x**2 + f(x)**4), x, 0, dir='+')
+
+
+def test_issue_8208():
+    assert limit(n**(Rational(1, 1e9) - 1), n, oo) == 0
+
+
+def test_issue_8229():
+    assert limit((x**Rational(1, 4) - 2)/(sqrt(x) - 4)**Rational(2, 3), x, 16) == 0
+
+
+def test_issue_8433():
+    d, t = symbols('d t', positive=True)
+    assert limit(erf(1 - t/d), t, oo) == -1
+
+
+def test_issue_8481():
+    k = Symbol('k', integer=True, nonnegative=True)
+    lamda = Symbol('lamda', positive=True)
+    assert limit(lamda**k * exp(-lamda) / factorial(k), k, oo) == 0
+
+
+def test_issue_8462():
+    assert limit(binomial(n, n/2), n, oo) == oo
+    assert limit(binomial(n, n/2) * 3 ** (-n), n, oo) == 0
+
+
+def test_issue_8634():
+    n = Symbol('n', integer=True, positive=True)
+    x = Symbol('x')
+    assert limit(x**n, x, -oo) == oo*sign((-1)**n)
+
+
+def test_issue_8635_18176():
+    x = Symbol('x', real=True)
+    k = Symbol('k', positive=True)
+    assert limit(x**n - x**(n - 0), x, oo) == 0
+    assert limit(x**n - x**(n - 5), x, oo) == oo
+    assert limit(x**n - x**(n - 2.5), x, oo) == oo
+    assert limit(x**n - x**(n - k - 1), x, oo) == oo
+    x = Symbol('x', positive=True)
+    assert limit(x**n - x**(n - 1), x, oo) == oo
+    assert limit(x**n - x**(n + 2), x, oo) == -oo
+
+
+def test_issue_8730():
+    assert limit(subfactorial(x), x, oo) is oo
+
+
+def test_issue_9252():
+    n = Symbol('n', integer=True)
+    c = Symbol('c', positive=True)
+    assert limit((log(n))**(n/log(n)) / (1 + c)**n, n, oo) == 0
+    # limit should depend on the value of c
+    raises(NotImplementedError, lambda: limit((log(n))**(n/log(n)) / c**n, n, oo))
+
+
+def test_issue_9558():
+    assert limit(sin(x)**15, x, 0, '-') == 0
+
+
+def test_issue_10801():
+    # make sure limits work with binomial
+    assert limit(16**k / (k * binomial(2*k, k)**2), k, oo) == pi
+
+
+def test_issue_10976():
+    s, x = symbols('s x', real=True)
+    assert limit(erf(s*x)/erf(s), s, 0) == x
+
+
+def test_issue_9041():
+    assert limit(factorial(n) / ((n/exp(1))**n * sqrt(2*pi*n)), n, oo) == 1
+
+
+def test_issue_9205():
+    x, y, a = symbols('x, y, a')
+    assert Limit(x, x, a).free_symbols == {a}
+    assert Limit(x, x, a, '-').free_symbols == {a}
+    assert Limit(x + y, x + y, a).free_symbols == {a}
+    assert Limit(-x**2 + y, x**2, a).free_symbols == {y, a}
+
+
+def test_issue_9471():
+    assert limit(((27**(log(n,3)))/n**3),n,oo) == 1
+    assert limit(((27**(log(n,3)+1))/n**3),n,oo) == 27
+
+
+def test_issue_10382():
+    assert limit(fibonacci(n + 1)/fibonacci(n), n, oo) == GoldenRatio
+
+
+def test_issue_11496():
+    assert limit(erfc(log(1/x)), x, oo) == 2
+
+
+def test_issue_11879():
+    assert simplify(limit(((x+y)**n-x**n)/y, y, 0)) == n*x**(n-1)
+
+
+def test_limit_with_Float():
+    k = symbols("k")
+    assert limit(1.0 ** k, k, oo) == 1
+    assert limit(0.3*1.0**k, k, oo) == Rational(3, 10)
+
+
+def test_issue_10610():
+    assert limit(3**x*3**(-x - 1)*(x + 1)**2/x**2, x, oo) == Rational(1, 3)
+
+
+def test_issue_10868():
+    assert limit(log(x) + asech(x), x, 0, '+') == log(2)
+    assert limit(log(x) + asech(x), x, 0, '-') == log(2) + 2*I*pi
+    raises(ValueError, lambda: limit(log(x) + asech(x), x, 0, '+-'))
+    assert limit(log(x) + asech(x), x, oo) == oo
+    assert limit(log(x) + acsch(x), x, 0, '+') == log(2)
+    assert limit(log(x) + acsch(x), x, 0, '-') == -oo
+    raises(ValueError, lambda: limit(log(x) + acsch(x), x, 0, '+-'))
+    assert limit(log(x) + acsch(x), x, oo) == oo
+
+
+def test_issue_6599():
+    assert limit((n + cos(n))/n, n, oo) == 1
+
+
+def test_issue_12555():
+    assert limit((3**x + 2* x**10) / (x**10 + exp(x)), x, -oo) == 2
+    assert limit((3**x + 2* x**10) / (x**10 + exp(x)), x, oo) is oo
+
+
+def test_issue_12769():
+    r, z, x = symbols('r z x', real=True)
+    a, b, s0, K, F0, s, T = symbols('a b s0 K F0 s T', positive=True, real=True)
+    fx = (F0**b*K**b*r*s0 - sqrt((F0**2*K**(2*b)*a**2*(b - 1) + \
+        F0**(2*b)*K**2*a**2*(b - 1) + F0**(2*b)*K**(2*b)*s0**2*(b - 1)*(b**2 - 2*b + 1) - \
+        2*F0**(2*b)*K**(b + 1)*a*r*s0*(b**2 - 2*b +  1) + \
+        2*F0**(b + 1)*K**(2*b)*a*r*s0*(b**2 - 2*b + 1) - \
+        2*F0**(b + 1)*K**(b + 1)*a**2*(b - 1))/((b - 1)*(b**2 - 2*b + 1))))*(b*r -  b - r + 1)
+
+    assert fx.subs(K, F0).factor(deep=True) == limit(fx, K, F0).factor(deep=True)
+
+
+def test_issue_13332():
+    assert limit(sqrt(30)*5**(-5*x - 1)*(46656*x)**x*(5*x + 2)**(5*x + 5*S.Half) *
+                (6*x + 2)**(-6*x - 5*S.Half), x, oo) == Rational(25, 36)
+
+
+def test_issue_12564():
+    assert limit(x**2 + x*sin(x) + cos(x), x, -oo) is oo
+    assert limit(x**2 + x*sin(x) + cos(x), x, oo) is oo
+    assert limit(((x + cos(x))**2).expand(), x, oo) is oo
+    assert limit(((x + sin(x))**2).expand(), x, oo) is oo
+    assert limit(((x + cos(x))**2).expand(), x, -oo) is oo
+    assert limit(((x + sin(x))**2).expand(), x, -oo) is oo
+
+
+def test_issue_14456():
+    raises(NotImplementedError, lambda: Limit(exp(x), x, zoo).doit())
+    raises(NotImplementedError, lambda: Limit(x**2/(x+1), x, zoo).doit())
+
+
+def test_issue_14411():
+    assert limit(3*sec(4*pi*x - x/3), x, 3*pi/(24*pi - 2)) is -oo
+
+
+def test_issue_13382():
+    assert limit(x*(((x + 1)**2 + 1)/(x**2 + 1) - 1), x, oo) == 2
+
+
+def test_issue_13403():
+    assert limit(x*(-1 + (x + log(x + 1) + 1)/(x + log(x))), x, oo) == 1
+
+
+def test_issue_13416():
+    assert limit((-x**3*log(x)**3 + (x - 1)*(x + 1)**2*log(x + 1)**3)/(x**2*log(x)**3), x, oo) == 1
+
+
+def test_issue_13462():
+    assert limit(n**2*(2*n*(-(1 - 1/(2*n))**x + 1) - x - (-x**2/4 + x/4)/n), n, oo) == x**3/24 - x**2/8 + x/12
+
+
+def test_issue_13750():
+    a = Symbol('a')
+    assert limit(erf(a - x), x, oo) == -1
+    assert limit(erf(sqrt(x) - x), x, oo) == -1
+
+
+def test_issue_14276():
+    assert isinstance(limit(sin(x)**log(x), x, oo), Limit)
+    assert isinstance(limit(sin(x)**cos(x), x, oo), Limit)
+    assert isinstance(limit(sin(log(cos(x))), x, oo), Limit)
+    assert limit((1 + 1/(x**2 + cos(x)))**(x**2 + x), x, oo) == E
+
+
+def test_issue_14514():
+    assert limit((1/(log(x)**log(x)))**(1/x), x, oo) == 1
+
+
+def test_issues_14525():
+    assert limit(sin(x)**2 - cos(x) + tan(x)*csc(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity)
+    assert limit(sin(x)**2 - cos(x) + sin(x)*cot(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity)
+    assert limit(cot(x) - tan(x)**2, x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity)
+    assert limit(cos(x) - tan(x)**2, x, oo) == AccumBounds(S.NegativeInfinity, S.One)
+    assert limit(sin(x) - tan(x)**2, x, oo) == AccumBounds(S.NegativeInfinity, S.One)
+    assert limit(cos(x)**2 - tan(x)**2, x, oo) == AccumBounds(S.NegativeInfinity, S.One)
+    assert limit(tan(x)**2 + sin(x)**2 - cos(x), x, oo) == AccumBounds(-S.One, S.Infinity)
+
+
+def test_issue_14574():
+    assert limit(sqrt(x)*cos(x - x**2) / (x + 1), x, oo) == 0
+
+
+def test_issue_10102():
+    assert limit(fresnels(x), x, oo) == S.Half
+    assert limit(3 + fresnels(x), x, oo) == 3 + S.Half
+    assert limit(5*fresnels(x), x, oo) == Rational(5, 2)
+    assert limit(fresnelc(x), x, oo) == S.Half
+    assert limit(fresnels(x), x, -oo) == Rational(-1, 2)
+    assert limit(4*fresnelc(x), x, -oo) == -2
+
+
+def test_issue_14377():
+    raises(NotImplementedError, lambda: limit(exp(I*x)*sin(pi*x), x, oo))
+
+
+def test_issue_15146():
+    e = (x/2) * (-2*x**3 - 2*(x**3 - 1) * x**2 * digamma(x**3 + 1) + \
+        2*(x**3 - 1) * x**2 * digamma(x**3 + x + 1) + x + 3)
+    assert limit(e, x, oo) == S(1)/3
+
+
+def test_issue_15202():
+    e = (2**x*(2 + 2**(-x)*(-2*2**x + x + 2))/(x + 1))**(x + 1)
+    assert limit(e, x, oo) == exp(1)
+
+    e = (log(x, 2)**7 + 10*x*factorial(x) + 5**x) / (factorial(x + 1) + 3*factorial(x) + 10**x)
+    assert limit(e, x, oo) == 10
+
+
+def test_issue_15282():
+    assert limit((x**2000 - (x + 1)**2000) / x**1999, x, oo) == -2000
+
+
+def test_issue_15984():
+    assert limit((-x + log(exp(x) + 1))/x, x, oo, dir='-') == 0
+
+
+def test_issue_13571():
+    assert limit(uppergamma(x, 1) / gamma(x), x, oo) == 1
+
+
+def test_issue_13575():
+    assert limit(acos(erfi(x)), x, 1) == acos(erfi(S.One))
+
+
+def test_issue_17325():
+    assert Limit(sin(x)/x, x, 0, dir="+-").doit() == 1
+    assert Limit(x**2, x, 0, dir="+-").doit() == 0
+    assert Limit(1/x**2, x, 0, dir="+-").doit() is oo
+    assert Limit(1/x, x, 0, dir="+-").doit() is zoo
+
+
+def test_issue_10978():
+    assert LambertW(x).limit(x, 0) == 0
+
+
+def test_issue_14313_comment():
+    assert limit(floor(n/2), n, oo) is oo
+
+
+def test_issue_15323():
+    d = ((1 - 1/x)**x).diff(x)
+    assert limit(d, x, 1, dir='+') == 1
+
+
+def test_issue_12571():
+    assert limit(-LambertW(-log(x))/log(x), x, 1) == 1
+
+
+def test_issue_14590():
+    assert limit((x**3*((x + 1)/x)**x)/((x + 1)*(x + 2)*(x + 3)), x, oo) == exp(1)
+
+
+def test_issue_14393():
+    a, b = symbols('a b')
+    assert limit((x**b - y**b)/(x**a - y**a), x, y) == b*y**(-a + b)/a
+
+
+def test_issue_14556():
+    assert limit(factorial(n + 1)**(1/(n + 1)) - factorial(n)**(1/n), n, oo) == exp(-1)
+
+
+def test_issue_14811():
+    assert limit(((1 + ((S(2)/3)**(x + 1)))**(2**x))/(2**((S(4)/3)**(x - 1))), x, oo) == oo
+
+
+def test_issue_16222():
+    assert limit(exp(x), x, 1000000000) == exp(1000000000)
+
+
+def test_issue_16714():
+    assert limit(((x**(x + 1) + (x + 1)**x) / x**(x + 1))**x, x, oo) == exp(exp(1))
+
+
+def test_issue_16722():
+    z = symbols('z', positive=True)
+    assert limit(binomial(n + z, n)*n**-z, n, oo) == 1/gamma(z + 1)
+    z = symbols('z', positive=True, integer=True)
+    assert limit(binomial(n + z, n)*n**-z, n, oo) == 1/gamma(z + 1)
+
+
+def test_issue_17431():
+    assert limit(((n + 1) + 1) / (((n + 1) + 2) * factorial(n + 1)) *
+                 (n + 2) * factorial(n) / (n + 1), n, oo) == 0
+    assert limit((n + 2)**2*factorial(n)/((n + 1)*(n + 3)*factorial(n + 1))
+                 , n, oo) == 0
+    assert limit((n + 1) * factorial(n) / (n * factorial(n + 1)), n, oo) == 0
+
+
+def test_issue_17671():
+    assert limit(Ei(-log(x)) - log(log(x))/x, x, 1) == EulerGamma
+
+
+def test_issue_17751():
+    a, b, c, x = symbols('a b c x', positive=True)
+    assert limit((a + 1)*x - sqrt((a + 1)**2*x**2 + b*x + c), x, oo) == -b/(2*a + 2)
+
+
+def test_issue_17792():
+    assert limit(factorial(n)/sqrt(n)*(exp(1)/n)**n, n, oo) == sqrt(2)*sqrt(pi)
+
+
+def test_issue_18118():
+    assert limit(sign(sin(x)), x, 0, "-") == -1
+    assert limit(sign(sin(x)), x, 0, "+") == 1
+
+
+def test_issue_18306():
+    assert limit(sin(sqrt(x))/sqrt(sin(x)), x, 0, '+') == 1
+
+
+def test_issue_18378():
+    assert limit(log(exp(3*x) + x)/log(exp(x) + x**100), x, oo) == 3
+
+
+def test_issue_18399():
+    assert limit((1 - S(1)/2*x)**(3*x), x, oo) is zoo
+    assert limit((-x)**x, x, oo) is zoo
+
+
+def test_issue_18442():
+    assert limit(tan(x)**(2**(sqrt(pi))), x, oo, dir='-') == Limit(tan(x)**(2**(sqrt(pi))), x, oo, dir='-')
+
+
+def test_issue_18452():
+    assert limit(abs(log(x))**x, x, 0) == 1
+    assert limit(abs(log(x))**x, x, 0, "-") == 1
+
+
+def test_issue_18473():
+    assert limit(sin(x)**(1/x), x, oo) == Limit(sin(x)**(1/x), x, oo, dir='-')
+    assert limit(cos(x)**(1/x), x, oo) == Limit(cos(x)**(1/x), x, oo, dir='-')
+    assert limit(tan(x)**(1/x), x, oo) == Limit(tan(x)**(1/x), x, oo, dir='-')
+    assert limit((cos(x) + 2)**(1/x), x, oo) == 1
+    assert limit((sin(x) + 10)**(1/x), x, oo) == 1
+    assert limit((cos(x) - 2)**(1/x), x, oo) == Limit((cos(x) - 2)**(1/x), x, oo, dir='-')
+    assert limit((cos(x) + 1)**(1/x), x, oo) == AccumBounds(0, 1)
+    assert limit((tan(x)**2)**(2/x) , x, oo) == AccumBounds(0, oo)
+    assert limit((sin(x)**2)**(1/x), x, oo) == AccumBounds(0, 1)
+    # Tests for issue #23751
+    assert limit((cos(x) + 1)**(1/x), x, -oo) == AccumBounds(1, oo)
+    assert limit((sin(x)**2)**(1/x), x, -oo) == AccumBounds(1, oo)
+    assert limit((tan(x)**2)**(2/x) , x, -oo) == AccumBounds(0, oo)
+
+
+def test_issue_18482():
+    assert limit((2*exp(3*x)/(exp(2*x) + 1))**(1/x), x, oo) == exp(1)
+
+
+def test_issue_18508():
+    assert limit(sin(x)/sqrt(1-cos(x)), x, 0) == sqrt(2)
+    assert limit(sin(x)/sqrt(1-cos(x)), x, 0, dir='+') == sqrt(2)
+    assert limit(sin(x)/sqrt(1-cos(x)), x, 0, dir='-') == -sqrt(2)
+
+
+def test_issue_18521():
+    raises(NotImplementedError, lambda: limit(exp((2 - n) * x), x, oo))
+
+
+def test_issue_18969():
+    a, b = symbols('a b', positive=True)
+    assert limit(LambertW(a), a, b) == LambertW(b)
+    assert limit(exp(LambertW(a)), a, b) == exp(LambertW(b))
+
+
+def test_issue_18992():
+    assert limit(n/(factorial(n)**(1/n)), n, oo) == exp(1)
+
+
+def test_issue_19067():
+    x = Symbol('x')
+    assert limit(gamma(x)/(gamma(x - 1)*gamma(x + 2)), x, 0) == -1
+
+
+def test_issue_19586():
+    assert limit(x**(2**x*3**(-x)), x, oo) == 1
+
+
+def test_issue_13715():
+    n = Symbol('n')
+    p = Symbol('p', zero=True)
+    assert limit(n + p, n, 0) == 0
+
+
+def test_issue_15055():
+    assert limit(n**3*((-n - 1)*sin(1/n) + (n + 2)*sin(1/(n + 1)))/(-n + 1), n, oo) == 1
+
+
+def test_issue_16708():
+    m, vi = symbols('m vi', positive=True)
+    B, ti, d = symbols('B ti d')
+    assert limit((B*ti*vi - sqrt(m)*sqrt(-2*B*d*vi + m*(vi)**2) + m*vi)/(B*vi), B, 0) == (d + ti*vi)/vi
+
+
+def test_issue_19154():
+    assert limit(besseli(1, 3 *x)/(x *besseli(1, x)**3), x , oo) == 2*sqrt(3)*pi/3
+    assert limit(besseli(1, 3 *x)/(x *besseli(1, x)**3), x , -oo) == -2*sqrt(3)*pi/3
+
+
+def test_issue_19453():
+    beta = Symbol("beta", positive=True)
+    h = Symbol("h", positive=True)
+    m = Symbol("m", positive=True)
+    w = Symbol("omega", positive=True)
+    g = Symbol("g", positive=True)
+
+    e = exp(1)
+    q = 3*h**2*beta*g*e**(0.5*h*beta*w)
+    p = m**2*w**2
+    s = e**(h*beta*w) - 1
+    Z = -q/(4*p*s) - q/(2*p*s**2) - q*(e**(h*beta*w) + 1)/(2*p*s**3)\
+            + e**(0.5*h*beta*w)/s
+    E = -diff(log(Z), beta)
+
+    assert limit(E - 0.5*h*w, beta, oo) == 0
+    assert limit(E.simplify() - 0.5*h*w, beta, oo) == 0
+
+
+def test_issue_19739():
+    assert limit((-S(1)/4)**x, x, oo) == 0
+
+
+def test_issue_19766():
+    assert limit(2**(-x)*sqrt(4**(x + 1) + 1), x, oo) == 2
+
+
+def test_issue_19770():
+    m = Symbol('m')
+    # the result is not 0 for non-real m
+    assert limit(cos(m*x)/x, x, oo) == Limit(cos(m*x)/x, x, oo, dir='-')
+    m = Symbol('m', real=True)
+    # can be improved to give the correct result 0
+    assert limit(cos(m*x)/x, x, oo) == Limit(cos(m*x)/x, x, oo, dir='-')
+    m = Symbol('m', nonzero=True)
+    assert limit(cos(m*x), x, oo) == AccumBounds(-1, 1)
+    assert limit(cos(m*x)/x, x, oo) == 0
+
+
+def test_issue_7535():
+    assert limit(tan(x)/sin(tan(x)), x, pi/2) == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='+')
+    assert limit(tan(x)/sin(tan(x)), x, pi/2, dir='-') == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='-')
+    assert limit(tan(x)/sin(tan(x)), x, pi/2, dir='+-') == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='+-')
+    assert limit(sin(tan(x)),x,pi/2) == AccumBounds(-1, 1)
+    assert -oo*(1/sin(-oo)) == AccumBounds(-oo, oo)
+    assert oo*(1/sin(oo)) == AccumBounds(-oo, oo)
+    assert oo*(1/sin(-oo)) == AccumBounds(-oo, oo)
+    assert -oo*(1/sin(oo)) == AccumBounds(-oo, oo)
+
+
+def test_issue_20365():
+    assert limit(((x + 1)**(1/x) - E)/x, x, 0) == -E/2
+
+
+def test_issue_21031():
+    assert limit(((1 + x)**(1/x) - (1 + 2*x)**(1/(2*x)))/asin(x), x, 0) == E/2
+
+
+def test_issue_21038():
+    assert limit(sin(pi*x)/(3*x - 12), x, 4) == pi/3
+
+
+def test_issue_20578():
+    expr = abs(x) * sin(1/x)
+    assert limit(expr,x,0,'+') == 0
+    assert limit(expr,x,0,'-') == 0
+    assert limit(expr,x,0,'+-') == 0
+
+
+def test_issue_21227():
+    f = log(x)
+
+    assert f.nseries(x, logx=y) == y
+    assert f.nseries(x, logx=-x) == -x
+
+    f = log(-log(x))
+
+    assert f.nseries(x, logx=y) == log(-y)
+    assert f.nseries(x, logx=-x) == log(x)
+
+    f = log(log(x))
+
+    assert f.nseries(x, logx=y) == log(y)
+    assert f.nseries(x, logx=-x) == log(-x)
+    assert f.nseries(x, logx=x) == log(x)
+
+    f = log(log(log(1/x)))
+
+    assert f.nseries(x, logx=y) == log(log(-y))
+    assert f.nseries(x, logx=-y) == log(log(y))
+    assert f.nseries(x, logx=x) == log(log(-x))
+    assert f.nseries(x, logx=-x) == log(log(x))
+
+
+def test_issue_21415():
+    exp = (x-1)*cos(1/(x-1))
+    assert exp.limit(x,1) == 0
+    assert exp.expand().limit(x,1) == 0
+
+
+def test_issue_21530():
+    assert limit(sinh(n + 1)/sinh(n), n, oo) == E
+
+
+def test_issue_21550():
+    r = (sqrt(5) - 1)/2
+    assert limit((x - r)/(x**2 + x - 1), x, r) == sqrt(5)/5
+
+
+def test_issue_21661():
+    out = limit((x**(x + 1) * (log(x) + 1) + 1) / x, x, 11)
+    assert out == S(3138428376722)/11 + 285311670611*log(11)
+
+
+def test_issue_21701():
+    assert limit((besselj(z, x)/x**z).subs(z, 7), x, 0) == S(1)/645120
+
+
+def test_issue_21721():
+    a = Symbol('a', real=True)
+    I = integrate(1/(pi*(1 + (x - a)**2)), x)
+    assert I.limit(x, oo) == S.Half
+
+
+def test_issue_21756():
+    term = (1 - exp(-2*I*pi*z))/(1 - exp(-2*I*pi*z/5))
+    assert term.limit(z, 0) == 5
+    assert re(term).limit(z, 0) == 5
+
+
+def test_issue_21785():
+    a = Symbol('a')
+    assert sqrt((-a**2 + x**2)/(1 - x**2)).limit(a, 1, '-') == I
+
+
+def test_issue_22181():
+    assert limit((-1)**x * 2**(-x), x, oo) == 0
+
+
+def test_issue_22220():
+    e1 = sqrt(30)*atan(sqrt(30)*tan(x/2)/6)/30
+    e2 = sqrt(30)*I*(-log(sqrt(2)*tan(x/2) - 2*sqrt(15)*I/5) +
+                     +log(sqrt(2)*tan(x/2) + 2*sqrt(15)*I/5))/60
+
+    assert limit(e1, x, -pi) == -sqrt(30)*pi/60
+    assert limit(e2, x, -pi) == -sqrt(30)*pi/30
+
+    assert limit(e1, x, -pi, '-') == sqrt(30)*pi/60
+    assert limit(e2, x, -pi, '-') == 0
+
+    # test https://github.com/sympy/sympy/issues/22220#issuecomment-972727694
+    expr = log(x - I) - log(-x - I)
+    expr2 = logcombine(expr, force=True)
+    assert limit(expr, x, oo) == limit(expr2, x, oo) == I*pi
+
+    # test https://github.com/sympy/sympy/issues/22220#issuecomment-1077618340
+    expr = expr = (-log(tan(x/2) - I) +log(tan(x/2) + I))
+    assert limit(expr, x, pi, '+') == 2*I*pi
+    assert limit(expr, x, pi, '-') == 0
+
+
+def test_issue_22334():
+    k, n  = symbols('k, n', positive=True)
+    assert limit((n+1)**k/((n+1)**(k+1) - (n)**(k+1)), n, oo) == 1/(k + 1)
+    assert limit((n+1)**k/((n+1)**(k+1) - (n)**(k+1)).expand(), n, oo) == 1/(k + 1)
+    assert limit((n+1)**k/(n*(-n**k + (n + 1)**k) + (n + 1)**k), n, oo) == 1/(k + 1)
+
+
+def test_issue_22836_limit():
+    assert limit(2**(1/x)/factorial(1/(x)), x, 0) == S.Zero
+
+
+def test_sympyissue_22986():
+    assert limit(acosh(1 + 1/x)*sqrt(x), x, oo) == sqrt(2)
+
+
+def test_issue_23231():
+    f = (2**x - 2**(-x))/(2**x + 2**(-x))
+    assert limit(f, x, -oo) == -1
+
+
+def test_issue_23596():
+    assert integrate(((1 + x)/x**2)*exp(-1/x), (x, 0, oo)) == oo
+
+
+def test_issue_23752():
+    expr1 = sqrt(-I*x**2 + x - 3)
+    expr2 = sqrt(-I*x**2 + I*x - 3)
+    assert limit(expr1, x, 0, '+') == -sqrt(3)*I
+    assert limit(expr1, x, 0, '-') == -sqrt(3)*I
+    assert limit(expr2, x, 0, '+') == sqrt(3)*I
+    assert limit(expr2, x, 0, '-') == -sqrt(3)*I
+
+
+def test_issue_24276():
+    fx = log(tan(pi/2*tanh(x))).diff(x)
+    assert fx.limit(x, oo) == 2
+    assert fx.simplify().limit(x, oo) == 2
+    assert fx.rewrite(sin).limit(x, oo) == 2
+    assert fx.rewrite(sin).simplify().limit(x, oo) == 2
+
+def test_issue_25230():
+    a = Symbol('a', real = True)
+    b = Symbol('b', positive = True)
+    c = Symbol('c', negative = True)
+    n = Symbol('n', integer = True)
+    raises(NotImplementedError, lambda: limit(Mod(x, a), x, a))
+    assert limit(Mod(x, b), x, n*b, '+') == 0
+    assert limit(Mod(x, b), x, n*b, '-') == b
+    assert limit(Mod(x, c), x, n*c, '+') == c
+    assert limit(Mod(x, c), x, n*c, '-') == 0
+
+
+def test_issue_25582():
+
+    assert limit(asin(exp(x)), x, oo, '-') == -oo*I
+    assert limit(acos(exp(x)), x, oo, '-') == oo*I
+    assert limit(atan(exp(x)), x, oo, '-') == pi/2
+    assert limit(acot(exp(x)), x, oo, '-') == 0
+    assert limit(asec(exp(x)), x, oo, '-') == pi/2
+    assert limit(acsc(exp(x)), x, oo, '-') == 0
+
+
+def test_issue_25847():
+    #atan
+    assert limit(atan(sin(x)/x), x, 0, '+-') == pi/4
+    assert limit(atan(exp(1/x)), x, 0, '+') == pi/2
+    assert limit(atan(exp(1/x)), x, 0, '-') == 0
+
+    #asin
+    assert limit(asin(sin(x)/x), x, 0, '+-') == pi/2
+    assert limit(asin(exp(1/x)), x, 0, '+') == -oo*I
+    assert limit(asin(exp(1/x)), x, 0, '-') == 0
+
+    #acos
+    assert limit(acos(sin(x)/x), x, 0, '+-') == 0
+    assert limit(acos(exp(1/x)), x, 0, '+') == oo*I
+    assert limit(acos(exp(1/x)), x, 0, '-') == pi/2
+
+    #acot
+    assert limit(acot(sin(x)/x), x, 0, '+-') == pi/4
+    assert limit(acot(exp(1/x)), x, 0, '+') == 0
+    assert limit(acot(exp(1/x)), x, 0, '-') == pi/2
+
+    #asec
+    assert limit(asec(sin(x)/x), x, 0, '+-') == 0
+    assert limit(asec(exp(1/x)), x, 0, '+') == pi/2
+    assert limit(asec(exp(1/x)), x, 0, '-') == oo*I
+
+    #acsc
+    assert limit(acsc(sin(x)/x), x, 0, '+-') == pi/2
+    assert limit(acsc(exp(1/x)), x, 0, '+') == 0
+    assert limit(acsc(exp(1/x)), x, 0, '-') == -oo*I
+
+    #atanh
+    assert limit(atanh(sin(x)/x), x, 0, '+-') == oo
+    assert limit(atanh(exp(1/x)), x, 0, '+') == -I*pi/2
+    assert limit(atanh(exp(1/x)), x, 0, '-') == 0
+
+    #asinh
+    assert limit(asinh(sin(x)/x), x, 0, '+-') == log(1 + sqrt(2))
+    assert limit(asinh(exp(1/x)), x, 0, '+') == oo
+    assert limit(asinh(exp(1/x)), x, 0, '-') == 0
+
+    #acosh
+    assert limit(acosh(sin(x)/x), x, 0, '+-') == 0
+    assert limit(acosh(exp(1/x)), x, 0, '+') == oo
+    assert limit(acosh(exp(1/x)), x, 0, '-') == I*pi/2
+
+    #acoth
+    assert limit(acoth(sin(x)/x), x, 0, '+-') == oo
+    assert limit(acoth(exp(1/x)), x, 0, '+') == 0
+    assert limit(acoth(exp(1/x)), x, 0, '-') == -I*pi/2
+
+    #asech
+    assert limit(asech(sin(x)/x), x, 0, '+-') == 0
+    assert limit(asech(exp(1/x)), x, 0, '+') == I*pi/2
+    assert limit(asech(exp(1/x)), x, 0, '-') == oo
+
+    #acsch
+    assert limit(acsch(sin(x)/x), x, 0, '+-') == log(1 + sqrt(2))
+    assert limit(acsch(exp(1/x)), x, 0, '+') == 0
+    assert limit(acsch(exp(1/x)), x, 0, '-') == oo
+
+
+def test_issue_26040():
+    assert limit(besseli(0, x + 1)/besseli(0, x), x, oo) == S.Exp1
+
+
+def test_issue_26250():
+    e = elliptic_e(4*x/(x**2 + 2*x + 1))
+    k = elliptic_k(4*x/(x**2 + 2*x + 1))
+    e1 = ((1-3*x**2)*e**2/2 - (x**2-2*x+1)*e*k/2)
+    e2 = pi**2*(x**8 - 2*x**7 - x**6 + 4*x**5 - x**4 - 2*x**3 + x**2)
+    assert limit(e1/e2, x, 0) == -S(1)/8
+
+
+def test_issue_26513():
+    assert limit(abs((-x/(x+1))**x), x ,oo) == exp(-1)
+    assert limit((x/(x + 1))**x, x, oo) == exp(-1)
+    raises (NotImplementedError, lambda: limit((-x/(x+1))**x, x, oo))
+
+
+def test_issue_26916():
+    assert limit(Ei(x)*exp(-x), x, +oo) == 0
+    assert limit(Ei(x)*exp(-x), x, -oo) == 0
+
+
+def test_issue_22982_15323():
+    assert limit((log(E + 1/x) - 1)**(1 - sqrt(E + 1/x)), x, oo) == oo
+    assert limit((1 - 1/x)**x*(log(1 - 1/x) + 1/(x*(1 - 1/x))), x, 1, dir='+') == 1
+    assert limit((log(E + 1/x) )**(1 - sqrt(E + 1/x)), x, oo) == 1
+    assert limit((log(E + 1/x) - 1)**(- sqrt(E + 1/x)), x, oo) == oo
+
+
+def test_issue_26991():
+    assert limit(x/((x - 6)*sinh(tanh(0.03*x)) + tanh(x) - 0.5), x, oo) == 1/sinh(1)
+
+def test_issue_27278():
+    expr = (1/(x*log((x + 3)/x)))**x*((x + 1)*log((x + 4)/(x + 1)))**(x + 1)/3
+    assert limit(expr, x, oo) == 1
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_limitseq.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_limitseq.py
new file mode 100644
index 0000000000000000000000000000000000000000..362bb0397feb0ec63929920855c81279eca0bd6a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_limitseq.py
@@ -0,0 +1,177 @@
+from sympy.concrete.summations import Sum
+from sympy.core.add import Add
+from sympy.core.numbers import (I, Rational, oo, pi)
+from sympy.core.singleton import S
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.functions.combinatorial.factorials import (binomial, factorial, subfactorial)
+from sympy.functions.combinatorial.numbers import (fibonacci, harmonic)
+from sympy.functions.elementary.exponential import (exp, log)
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import (cos, sin)
+from sympy.functions.special.gamma_functions import gamma
+from sympy.series.limitseq import limit_seq
+from sympy.series.limitseq import difference_delta as dd
+from sympy.testing.pytest import raises, XFAIL
+from sympy.calculus.accumulationbounds import AccumulationBounds
+
+n, m, k = symbols('n m k', integer=True)
+
+
+def test_difference_delta():
+    e = n*(n + 1)
+    e2 = e * k
+
+    assert dd(e) == 2*n + 2
+    assert dd(e2, n, 2) == k*(4*n + 6)
+
+    raises(ValueError, lambda: dd(e2))
+    raises(ValueError, lambda: dd(e2, n, oo))
+
+
+def test_difference_delta__Sum():
+    e = Sum(1/k, (k, 1, n))
+    assert dd(e, n) == 1/(n + 1)
+    assert dd(e, n, 5) == Add(*[1/(i + n + 1) for i in range(5)])
+
+    e = Sum(1/k, (k, 1, 3*n))
+    assert dd(e, n) == Add(*[1/(i + 3*n + 1) for i in range(3)])
+
+    e = n * Sum(1/k, (k, 1, n))
+    assert dd(e, n) == 1 + Sum(1/k, (k, 1, n))
+
+    e = Sum(1/k, (k, 1, n), (m, 1, n))
+    assert dd(e, n) == harmonic(n)
+
+
+def test_difference_delta__Add():
+    e = n + n*(n + 1)
+    assert dd(e, n) == 2*n + 3
+    assert dd(e, n, 2) == 4*n + 8
+
+    e = n + Sum(1/k, (k, 1, n))
+    assert dd(e, n) == 1 + 1/(n + 1)
+    assert dd(e, n, 5) == 5 + Add(*[1/(i + n + 1) for i in range(5)])
+
+
+def test_difference_delta__Pow():
+    e = 4**n
+    assert dd(e, n) == 3*4**n
+    assert dd(e, n, 2) == 15*4**n
+
+    e = 4**(2*n)
+    assert dd(e, n) == 15*4**(2*n)
+    assert dd(e, n, 2) == 255*4**(2*n)
+
+    e = n**4
+    assert dd(e, n) == (n + 1)**4 - n**4
+
+    e = n**n
+    assert dd(e, n) == (n + 1)**(n + 1) - n**n
+
+
+def test_limit_seq():
+    e = binomial(2*n, n) / Sum(binomial(2*k, k), (k, 1, n))
+    assert limit_seq(e) == S(3) / 4
+    assert limit_seq(e, m) == e
+
+    e = (5*n**3 + 3*n**2 + 4) / (3*n**3 + 4*n - 5)
+    assert limit_seq(e, n) == S(5) / 3
+
+    e = (harmonic(n) * Sum(harmonic(k), (k, 1, n))) / (n * harmonic(2*n)**2)
+    assert limit_seq(e, n) == 1
+
+    e = Sum(k**2 * Sum(2**m/m, (m, 1, k)), (k, 1, n)) / (2**n*n)
+    assert limit_seq(e, n) == 4
+
+    e = (Sum(binomial(3*k, k) * binomial(5*k, k), (k, 1, n)) /
+         (binomial(3*n, n) * binomial(5*n, n)))
+    assert limit_seq(e, n) == S(84375) / 83351
+
+    e = Sum(harmonic(k)**2/k, (k, 1, 2*n)) / harmonic(n)**3
+    assert limit_seq(e, n) == S.One / 3
+
+    raises(ValueError, lambda: limit_seq(e * m))
+
+
+def test_alternating_sign():
+    assert limit_seq((-1)**n/n**2, n) == 0
+    assert limit_seq((-2)**(n+1)/(n + 3**n), n) == 0
+    assert limit_seq((2*n + (-1)**n)/(n + 1), n) == 2
+    assert limit_seq(sin(pi*n), n) == 0
+    assert limit_seq(cos(2*pi*n), n) == 1
+    assert limit_seq((S.NegativeOne/5)**n, n) == 0
+    assert limit_seq((Rational(-1, 5))**n, n) == 0
+    assert limit_seq((I/3)**n, n) == 0
+    assert limit_seq(sqrt(n)*(I/2)**n, n) == 0
+    assert limit_seq(n**7*(I/3)**n, n) == 0
+    assert limit_seq(n/(n + 1) + (I/2)**n, n) == 1
+
+
+def test_accum_bounds():
+    assert limit_seq((-1)**n, n) == AccumulationBounds(-1, 1)
+    assert limit_seq(cos(pi*n), n) == AccumulationBounds(-1, 1)
+    assert limit_seq(sin(pi*n/2)**2, n) == AccumulationBounds(0, 1)
+    assert limit_seq(2*(-3)**n/(n + 3**n), n) == AccumulationBounds(-2, 2)
+    assert limit_seq(3*n/(n + 1) + 2*(-1)**n, n) == AccumulationBounds(1, 5)
+
+
+def test_limitseq_sum():
+    from sympy.abc import x, y, z
+    assert limit_seq(Sum(1/x, (x, 1, y)) - log(y), y) == S.EulerGamma
+    assert limit_seq(Sum(1/x, (x, 1, y)) - 1/y, y) is S.Infinity
+    assert (limit_seq(binomial(2*x, x) / Sum(binomial(2*y, y), (y, 1, x)), x) ==
+            S(3) / 4)
+    assert (limit_seq(Sum(y**2 * Sum(2**z/z, (z, 1, y)), (y, 1, x)) /
+                  (2**x*x), x) == 4)
+
+
+def test_issue_9308():
+    assert limit_seq(subfactorial(n)/factorial(n), n) == exp(-1)
+
+
+def test_issue_10382():
+    n = Symbol('n', integer=True)
+    assert limit_seq(fibonacci(n+1)/fibonacci(n), n).together() == S.GoldenRatio
+
+
+def test_issue_11672():
+    assert limit_seq(Rational(-1, 2)**n, n) == 0
+
+
+def test_issue_14196():
+    k, n  = symbols('k, n', positive=True)
+    m = Symbol('m')
+    assert limit_seq(Sum(m**k, (m, 1, n)).doit()/(n**(k + 1)), n) == 1/(k + 1)
+
+
+def test_issue_16735():
+    assert limit_seq(5**n/factorial(n), n) == 0
+
+
+def test_issue_19868():
+    assert limit_seq(1/gamma(n + S.One/2), n) == 0
+
+
+@XFAIL
+def test_limit_seq_fail():
+    # improve Summation algorithm or add ad-hoc criteria
+    e = (harmonic(n)**3 * Sum(1/harmonic(k), (k, 1, n)) /
+         (n * Sum(harmonic(k)/k, (k, 1, n))))
+    assert limit_seq(e, n) == 2
+
+    # No unique dominant term
+    e = (Sum(2**k * binomial(2*k, k) / k**2, (k, 1, n)) /
+         (Sum(2**k/k*2, (k, 1, n)) * Sum(binomial(2*k, k), (k, 1, n))))
+    assert limit_seq(e, n) == S(3) / 7
+
+    # Simplifications of summations needs to be improved.
+    e = n**3*Sum(2**k/k**2, (k, 1, n))**2 / (2**n * Sum(2**k/k, (k, 1, n)))
+    assert limit_seq(e, n) == 2
+
+    e = (harmonic(n) * Sum(2**k/k, (k, 1, n)) /
+         (n * Sum(2**k*harmonic(k)/k**2, (k, 1, n))))
+    assert limit_seq(e, n) == 1
+
+    e = (Sum(2**k*factorial(k) / k**2, (k, 1, 2*n)) /
+         (Sum(4**k/k**2, (k, 1, n)) * Sum(factorial(k), (k, 1, 2*n))))
+    assert limit_seq(e, n) == S(3) / 16
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_lseries.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_lseries.py
new file mode 100644
index 0000000000000000000000000000000000000000..42d327bf60c76eebdc4570d631efef4bc84b58e3
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_lseries.py
@@ -0,0 +1,65 @@
+from sympy.core.numbers import E
+from sympy.core.singleton import S
+from sympy.functions.elementary.exponential import exp
+from sympy.functions.elementary.hyperbolic import tanh
+from sympy.functions.elementary.trigonometric import (cos, sin)
+from sympy.series.order import Order
+from sympy.abc import x, y
+
+
+def test_sin():
+    e = sin(x).lseries(x)
+    assert next(e) == x
+    assert next(e) == -x**3/6
+    assert next(e) == x**5/120
+
+
+def test_cos():
+    e = cos(x).lseries(x)
+    assert next(e) == 1
+    assert next(e) == -x**2/2
+    assert next(e) == x**4/24
+
+
+def test_exp():
+    e = exp(x).lseries(x)
+    assert next(e) == 1
+    assert next(e) == x
+    assert next(e) == x**2/2
+    assert next(e) == x**3/6
+
+
+def test_exp2():
+    e = exp(cos(x)).lseries(x)
+    assert next(e) == E
+    assert next(e) == -E*x**2/2
+    assert next(e) == E*x**4/6
+    assert next(e) == -31*E*x**6/720
+
+
+def test_simple():
+    assert list(x.lseries()) == [x]
+    assert list(S.One.lseries(x)) == [1]
+    assert not next((x/(x + y)).lseries(y)).has(Order)
+
+
+def test_issue_5183():
+    s = (x + 1/x).lseries()
+    assert list(s) == [1/x, x]
+    assert next((x + x**2).lseries()) == x
+    assert next(((1 + x)**7).lseries(x)) == 1
+    assert next((sin(x + y)).series(x, n=3).lseries(y)) == x
+    # it would be nice if all terms were grouped, but in the
+    # following case that would mean that all the terms would have
+    # to be known since, for example, every term has a constant in it.
+    s = ((1 + x)**7).series(x, 1, n=None)
+    assert [next(s) for i in range(2)] == [128, -448 + 448*x]
+
+
+def test_issue_6999():
+    s = tanh(x).lseries(x, 1)
+    assert next(s) == tanh(1)
+    assert next(s) == x - (x - 1)*tanh(1)**2 - 1
+    assert next(s) == -(x - 1)**2*tanh(1) + (x - 1)**2*tanh(1)**3
+    assert next(s) == -(x - 1)**3*tanh(1)**4 - (x - 1)**3/3 + \
+        4*(x - 1)**3*tanh(1)**2/3
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_nseries.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_nseries.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2f20add82d3e858e2ce145fc9fcd4a6548a48cc
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_nseries.py
@@ -0,0 +1,557 @@
+from sympy.calculus.util import AccumBounds
+from sympy.core.function import (Derivative, PoleError)
+from sympy.core.numbers import (E, I, Integer, Rational, pi)
+from sympy.core.singleton import S
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.functions.elementary.complexes import sign
+from sympy.functions.elementary.exponential import (exp, log)
+from sympy.functions.elementary.hyperbolic import (acosh, acoth, asinh, atanh, cosh, coth, sinh, tanh)
+from sympy.functions.elementary.integers import (ceiling, floor, frac)
+from sympy.functions.elementary.miscellaneous import (cbrt, sqrt)
+from sympy.functions.elementary.trigonometric import (asin, cos, cot, sin, tan)
+from sympy.series.limits import limit
+from sympy.series.order import O
+from sympy.abc import x, y, z
+
+from sympy.testing.pytest import raises, XFAIL
+
+
+def test_simple_1():
+    assert x.nseries(x, n=5) == x
+    assert y.nseries(x, n=5) == y
+    assert (1/(x*y)).nseries(y, n=5) == 1/(x*y)
+    assert Rational(3, 4).nseries(x, n=5) == Rational(3, 4)
+    assert x.nseries() == x
+
+
+def test_mul_0():
+    assert (x*log(x)).nseries(x, n=5) == x*log(x)
+
+
+def test_mul_1():
+    assert (x*log(2 + x)).nseries(x, n=5) == x*log(2) + x**2/2 - x**3/8 + \
+        x**4/24 + O(x**5)
+    assert (x*log(1 + x)).nseries(
+        x, n=5) == x**2 - x**3/2 + x**4/3 + O(x**5)
+
+
+def test_pow_0():
+    assert (x**2).nseries(x, n=5) == x**2
+    assert (1/x).nseries(x, n=5) == 1/x
+    assert (1/x**2).nseries(x, n=5) == 1/x**2
+    assert (x**Rational(2, 3)).nseries(x, n=5) == (x**Rational(2, 3))
+    assert (sqrt(x)**3).nseries(x, n=5) == (sqrt(x)**3)
+
+
+def test_pow_1():
+    assert ((1 + x)**2).nseries(x, n=5) == x**2 + 2*x + 1
+
+    # https://github.com/sympy/sympy/issues/21075
+    assert ((sqrt(x) + 1)**2).nseries(x) == 2*sqrt(x) + x + 1
+    assert ((sqrt(x) + cbrt(x))**2).nseries(x) == 2*x**Rational(5, 6)\
+        + x**Rational(2, 3) + x
+
+
+def test_geometric_1():
+    assert (1/(1 - x)).nseries(x, n=5) == 1 + x + x**2 + x**3 + x**4 + O(x**5)
+    assert (x/(1 - x)).nseries(x, n=6) == x + x**2 + x**3 + x**4 + x**5 + O(x**6)
+    assert (x**3/(1 - x)).nseries(x, n=8) == x**3 + x**4 + x**5 + x**6 + \
+        x**7 + O(x**8)
+
+
+def test_sqrt_1():
+    assert sqrt(1 + x).nseries(x, n=5) == 1 + x/2 - x**2/8 + x**3/16 - 5*x**4/128 + O(x**5)
+
+
+def test_exp_1():
+    assert exp(x).nseries(x, n=5) == 1 + x + x**2/2 + x**3/6 + x**4/24 + O(x**5)
+    assert exp(x).nseries(x, n=12) == 1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 +  \
+        x**6/720 + x**7/5040 + x**8/40320 + x**9/362880 + x**10/3628800 +  \
+        x**11/39916800 + O(x**12)
+    assert exp(1/x).nseries(x, n=5) == exp(1/x)
+    assert exp(1/(1 + x)).nseries(x, n=4) ==  \
+        (E*(1 - x - 13*x**3/6 + 3*x**2/2)).expand() + O(x**4)
+    assert exp(2 + x).nseries(x, n=5) ==  \
+        (exp(2)*(1 + x + x**2/2 + x**3/6 + x**4/24)).expand() + O(x**5)
+
+
+def test_exp_sqrt_1():
+    assert exp(1 + sqrt(x)).nseries(x, n=3) ==  \
+        (exp(1)*(1 + sqrt(x) + x/2 + sqrt(x)*x/6)).expand() + O(sqrt(x)**3)
+
+
+def test_power_x_x1():
+    assert (exp(x*log(x))).nseries(x, n=4) == \
+        1 + x*log(x) + x**2*log(x)**2/2 + x**3*log(x)**3/6 + O(x**4*log(x)**4)
+
+
+def test_power_x_x2():
+    assert (x**x).nseries(x, n=4) == \
+        1 + x*log(x) + x**2*log(x)**2/2 + x**3*log(x)**3/6 + O(x**4*log(x)**4)
+
+
+def test_log_singular1():
+    assert log(1 + 1/x).nseries(x, n=5) == x - log(x) - x**2/2 + x**3/3 - \
+        x**4/4 + O(x**5)
+
+
+def test_log_power1():
+    e = 1 / (1/x + x ** (log(3)/log(2)))
+    assert e.nseries(x, n=5) == -x**(log(3)/log(2) + 2) + x + O(x**5)
+
+
+def test_log_series():
+    l = Symbol('l')
+    e = 1/(1 - log(x))
+    assert e.nseries(x, n=5, logx=l) == 1/(1 - l)
+
+
+def test_log2():
+    e = log(-1/x)
+    assert e.nseries(x, n=5) == -log(x) + log(-1)
+
+
+def test_log3():
+    l = Symbol('l')
+    e = 1/log(-1/x)
+    assert e.nseries(x, n=4, logx=l) == 1/(-l + log(-1))
+
+
+def test_series1():
+    e = sin(x)
+    assert e.nseries(x, 0, 0) != 0
+    assert e.nseries(x, 0, 0) == O(1, x)
+    assert e.nseries(x, 0, 1) == O(x, x)
+    assert e.nseries(x, 0, 2) == x + O(x**2, x)
+    assert e.nseries(x, 0, 3) == x + O(x**3, x)
+    assert e.nseries(x, 0, 4) == x - x**3/6 + O(x**4, x)
+
+    e = (exp(x) - 1)/x
+    assert e.nseries(x, 0, 3) == 1 + x/2 + x**2/6 + O(x**3)
+
+    assert x.nseries(x, 0, 2) == x
+
+
+@XFAIL
+def test_series1_failing():
+    assert x.nseries(x, 0, 0) == O(1, x)
+    assert x.nseries(x, 0, 1) == O(x, x)
+
+
+def test_seriesbug1():
+    assert (1/x).nseries(x, 0, 3) == 1/x
+    assert (x + 1/x).nseries(x, 0, 3) == x + 1/x
+
+
+def test_series2x():
+    assert ((x + 1)**(-2)).nseries(x, 0, 4) == 1 - 2*x + 3*x**2 - 4*x**3 + O(x**4, x)
+    assert ((x + 1)**(-1)).nseries(x, 0, 4) == 1 - x + x**2 - x**3 + O(x**4, x)
+    assert ((x + 1)**0).nseries(x, 0, 3) == 1
+    assert ((x + 1)**1).nseries(x, 0, 3) == 1 + x
+    assert ((x + 1)**2).nseries(x, 0, 3) == x**2 + 2*x + 1
+    assert ((x + 1)**3).nseries(x, 0, 3) == 1 + 3*x + 3*x**2 + O(x**3)
+
+    assert (1/(1 + x)).nseries(x, 0, 4) == 1 - x + x**2 - x**3 + O(x**4, x)
+    assert (x + 3/(1 + 2*x)).nseries(x, 0, 4) == 3 - 5*x + 12*x**2 - 24*x**3 + O(x**4, x)
+
+    assert ((1/x + 1)**3).nseries(x, 0, 3) == 1 + 3/x + 3/x**2 + x**(-3)
+    assert (1/(1 + 1/x)).nseries(x, 0, 4) == x - x**2 + x**3 - O(x**4, x)
+    assert (1/(1 + 1/x**2)).nseries(x, 0, 6) == x**2 - x**4 + O(x**6, x)
+
+
+def test_bug2():  # 1/log(0)*log(0) problem
+    w = Symbol("w")
+    e = (w**(-1) + w**(
+        -log(3)*log(2)**(-1)))**(-1)*(3*w**(-log(3)*log(2)**(-1)) + 2*w**(-1))
+    e = e.expand()
+    assert e.nseries(w, 0, 4).subs(w, 0) == 3
+
+
+def test_exp():
+    e = (1 + x)**(1/x)
+    assert e.nseries(x, n=3) == exp(1) - x*exp(1)/2 + 11*exp(1)*x**2/24 + O(x**3)
+
+
+def test_exp2():
+    w = Symbol("w")
+    e = w**(1 - log(x)/(log(2) + log(x)))
+    logw = Symbol("logw")
+    assert e.nseries(
+        w, 0, 1, logx=logw) == exp(logw*log(2)/(log(x) + log(2)))
+
+
+def test_bug3():
+    e = (2/x + 3/x**2)/(1/x + 1/x**2)
+    assert e.nseries(x, n=3) == 3 - x + x**2 + O(x**3)
+
+
+def test_generalexponent():
+    p = 2
+    e = (2/x + 3/x**p)/(1/x + 1/x**p)
+    assert e.nseries(x, 0, 3) == 3 - x + x**2 + O(x**3)
+    p = S.Half
+    e = (2/x + 3/x**p)/(1/x + 1/x**p)
+    assert e.nseries(x, 0, 2) == 2 - x + sqrt(x) + x**(S(3)/2) + O(x**2)
+
+    e = 1 + sqrt(x)
+    assert e.nseries(x, 0, 4) == 1 + sqrt(x)
+
+# more complicated example
+
+
+def test_genexp_x():
+    e = 1/(1 + sqrt(x))
+    assert e.nseries(x, 0, 2) == \
+        1 + x - sqrt(x) - sqrt(x)**3 + O(x**2, x)
+
+# more complicated example
+
+
+def test_genexp_x2():
+    p = Rational(3, 2)
+    e = (2/x + 3/x**p)/(1/x + 1/x**p)
+    assert e.nseries(x, 0, 3) == 3 + x + x**2 - sqrt(x) - x**(S(3)/2) - x**(S(5)/2) + O(x**3)
+
+
+def test_seriesbug2():
+    w = Symbol("w")
+    #simple case (1):
+    e = ((2*w)/w)**(1 + w)
+    assert e.nseries(w, 0, 1) == 2 + O(w, w)
+    assert e.nseries(w, 0, 1).subs(w, 0) == 2
+
+
+def test_seriesbug2b():
+    w = Symbol("w")
+    #test sin
+    e = sin(2*w)/w
+    assert e.nseries(w, 0, 3) == 2 - 4*w**2/3 + O(w**3)
+
+
+def test_seriesbug2d():
+    w = Symbol("w", real=True)
+    e = log(sin(2*w)/w)
+    assert e.series(w, n=5) == log(2) - 2*w**2/3 - 4*w**4/45 + O(w**5)
+
+
+def test_seriesbug2c():
+    w = Symbol("w", real=True)
+    #more complicated case, but sin(x)~x, so the result is the same as in (1)
+    e = (sin(2*w)/w)**(1 + w)
+    assert e.series(w, 0, 1) == 2 + O(w)
+    assert e.series(w, 0, 3) == 2 + 2*w*log(2) + \
+        w**2*(Rational(-4, 3) + log(2)**2) + O(w**3)
+    assert e.series(w, 0, 2).subs(w, 0) == 2
+
+
+def test_expbug4():
+    x = Symbol("x", real=True)
+    assert (log(
+        sin(2*x)/x)*(1 + x)).series(x, 0, 2) == log(2) + x*log(2) + O(x**2, x)
+    assert exp(
+        log(sin(2*x)/x)*(1 + x)).series(x, 0, 2) == 2 + 2*x*log(2) + O(x**2)
+
+    assert exp(log(2) + O(x)).nseries(x, 0, 2) == 2 + O(x)
+    assert ((2 + O(x))**(1 + x)).nseries(x, 0, 2) == 2 + O(x)
+
+
+def test_logbug4():
+    assert log(2 + O(x)).nseries(x, 0, 2) == log(2) + O(x, x)
+
+
+def test_expbug5():
+    assert exp(log(1 + x)/x).nseries(x, n=3) == exp(1) + -exp(1)*x/2 + 11*exp(1)*x**2/24 + O(x**3)
+
+    assert exp(O(x)).nseries(x, 0, 2) == 1 + O(x)
+
+
+def test_sinsinbug():
+    assert sin(sin(x)).nseries(x, 0, 8) == x - x**3/3 + x**5/10 - 8*x**7/315 + O(x**8)
+
+
+def test_issue_3258():
+    a = x/(exp(x) - 1)
+    assert a.nseries(x, 0, 5) == 1 - x/2 - x**4/720 + x**2/12 + O(x**5)
+
+
+def test_issue_3204():
+    x = Symbol("x", nonnegative=True)
+    f = sin(x**3)**Rational(1, 3)
+    assert f.nseries(x, 0, 17) == x - x**7/18 - x**13/3240 + O(x**17)
+
+
+def test_issue_3224():
+    f = sqrt(1 - sqrt(y))
+    assert f.nseries(y, 0, 2) == 1 - sqrt(y)/2 - y/8 - sqrt(y)**3/16 + O(y**2)
+
+
+def test_issue_3463():
+    w, i = symbols('w,i')
+    r = log(5)/log(3)
+    p = w**(-1 + r)
+    e = 1/x*(-log(w**(1 + r)) + log(w + w**r))
+    e_ser = -r*log(w)/x + p/x - p**2/(2*x) + O(w)
+    assert e.nseries(w, n=1) == e_ser
+
+
+def test_sin():
+    assert sin(8*x).nseries(x, n=4) == 8*x - 256*x**3/3 + O(x**4)
+    assert sin(x + y).nseries(x, n=1) == sin(y) + O(x)
+    assert sin(x + y).nseries(x, n=2) == sin(y) + cos(y)*x + O(x**2)
+    assert sin(x + y).nseries(x, n=5) == sin(y) + cos(y)*x - sin(y)*x**2/2 - \
+        cos(y)*x**3/6 + sin(y)*x**4/24 + O(x**5)
+
+
+def test_issue_3515():
+    e = sin(8*x)/x
+    assert e.nseries(x, n=6) == 8 - 256*x**2/3 + 4096*x**4/15 + O(x**6)
+
+
+def test_issue_3505():
+    e = sin(x)**(-4)*(sqrt(cos(x))*sin(x)**2 -
+        cos(x)**Rational(1, 3)*sin(x)**2)
+    assert e.nseries(x, n=9) == Rational(-1, 12) - 7*x**2/288 - \
+        43*x**4/10368 - 1123*x**6/2488320 + 377*x**8/29859840 + O(x**9)
+
+
+def test_issue_3501():
+    a = Symbol("a")
+    e = x**(-2)*(x*sin(a + x) - x*sin(a))
+    assert e.nseries(x, n=6) == cos(a) - sin(a)*x/2 - cos(a)*x**2/6 + \
+        x**3*sin(a)/24 + x**4*cos(a)/120 - x**5*sin(a)/720 + O(x**6)
+    e = x**(-2)*(x*cos(a + x) - x*cos(a))
+    assert e.nseries(x, n=6) == -sin(a) - cos(a)*x/2 + sin(a)*x**2/6 + \
+        cos(a)*x**3/24 - x**4*sin(a)/120 - x**5*cos(a)/720 + O(x**6)
+
+
+def test_issue_3502():
+    e = sin(5*x)/sin(2*x)
+    assert e.nseries(x, n=2) == Rational(5, 2) + O(x**2)
+    assert e.nseries(x, n=6) == \
+        Rational(5, 2) - 35*x**2/4 + 329*x**4/48 + O(x**6)
+
+
+def test_issue_3503():
+    e = sin(2 + x)/(2 + x)
+    assert e.nseries(x, n=2) == sin(2)/2 + x*cos(2)/2 - x*sin(2)/4 + O(x**2)
+
+
+def test_issue_3506():
+    e = (x + sin(3*x))**(-2)*(x*(x + sin(3*x)) - (x + sin(3*x))*sin(2*x))
+    assert e.nseries(x, n=7) == \
+        Rational(-1, 4) + 5*x**2/96 + 91*x**4/768 + 11117*x**6/129024 + O(x**7)
+
+
+def test_issue_3508():
+    x = Symbol("x", real=True)
+    assert log(sin(x)).series(x, n=5) == log(x) - x**2/6 - x**4/180 + O(x**5)
+    e = -log(x) + x*(-log(x) + log(sin(2*x))) + log(sin(2*x))
+    assert e.series(x, n=5) == \
+        log(2) + log(2)*x - 2*x**2/3 - 2*x**3/3 - 4*x**4/45 + O(x**5)
+
+
+def test_issue_3507():
+    e = x**(-4)*(x**2 - x**2*sqrt(cos(x)))
+    assert e.nseries(x, n=9) == \
+        Rational(1, 4) + x**2/96 + 19*x**4/5760 + 559*x**6/645120 + 29161*x**8/116121600 + O(x**9)
+
+
+def test_issue_3639():
+    assert sin(cos(x)).nseries(x, n=5) == \
+        sin(1) - x**2*cos(1)/2 - x**4*sin(1)/8 + x**4*cos(1)/24 + O(x**5)
+
+
+def test_hyperbolic():
+    assert sinh(x).nseries(x, n=6) == x + x**3/6 + x**5/120 + O(x**6)
+    assert cosh(x).nseries(x, n=5) == 1 + x**2/2 + x**4/24 + O(x**5)
+    assert tanh(x).nseries(x, n=6) == x - x**3/3 + 2*x**5/15 + O(x**6)
+    assert coth(x).nseries(x, n=6) == \
+        1/x - x**3/45 + x/3 + 2*x**5/945 + O(x**6)
+    assert asinh(x).nseries(x, n=6) == x - x**3/6 + 3*x**5/40 + O(x**6)
+    assert acosh(x).nseries(x, n=6) == \
+        pi*I/2 - I*x - 3*I*x**5/40 - I*x**3/6 + O(x**6)
+    assert atanh(x).nseries(x, n=6) == x + x**3/3 + x**5/5 + O(x**6)
+    assert acoth(x).nseries(x, n=6) == -I*pi/2 + x + x**3/3 + x**5/5 + O(x**6)
+
+
+def test_series2():
+    w = Symbol("w", real=True)
+    x = Symbol("x", real=True)
+    e = w**(-2)*(w*exp(1/x - w) - w*exp(1/x))
+    assert e.nseries(w, n=4) == -exp(1/x) + w*exp(1/x)/2 - w**2*exp(1/x)/6 + w**3*exp(1/x)/24 + O(w**4)
+
+
+def test_series3():
+    w = Symbol("w", real=True)
+    e = w**(-6)*(w**3*tan(w) - w**3*sin(w))
+    assert e.nseries(w, n=8) == Integer(1)/2 + w**2/8 + 13*w**4/240 + 529*w**6/24192 + O(w**8)
+
+
+def test_bug4():
+    w = Symbol("w")
+    e = x/(w**4 + x**2*w**4 + 2*x*w**4)*w**4
+    assert e.nseries(w, n=2).removeO().expand() in [x/(1 + 2*x + x**2),
+        1/(1 + x/2 + 1/x/2)/2, 1/x/(1 + 2/x + x**(-2))]
+
+
+def test_bug5():
+    w = Symbol("w")
+    l = Symbol('l')
+    e = (-log(w) + log(1 + w*log(x)))**(-2)*w**(-2)*((-log(w) +
+        log(1 + x*w))*(-log(w) + log(1 + w*log(x)))*w - x*(-log(w) +
+        log(1 + w*log(x)))*w)
+    assert e.nseries(w, n=0, logx=l) == x/w/l + 1/w + O(1, w)
+    assert e.nseries(w, n=1, logx=l) == x/w/l + 1/w - x/l + 1/l*log(x) \
+        + x*log(x)/l**2 + O(w)
+
+
+def test_issue_4115():
+    assert (sin(x)/(1 - cos(x))).nseries(x, n=1) == 2/x + O(x)
+    assert (sin(x)**2/(1 - cos(x))).nseries(x, n=1) == 2 + O(x)
+
+
+def test_pole():
+    raises(PoleError, lambda: sin(1/x).series(x, 0, 5))
+    raises(PoleError, lambda: sin(1 + 1/x).series(x, 0, 5))
+    raises(PoleError, lambda: (x*sin(1/x)).series(x, 0, 5))
+
+
+def test_expsinbug():
+    assert exp(sin(x)).series(x, 0, 0) == O(1, x)
+    assert exp(sin(x)).series(x, 0, 1) == 1 + O(x)
+    assert exp(sin(x)).series(x, 0, 2) == 1 + x + O(x**2)
+    assert exp(sin(x)).series(x, 0, 3) == 1 + x + x**2/2 + O(x**3)
+    assert exp(sin(x)).series(x, 0, 4) == 1 + x + x**2/2 + O(x**4)
+    assert exp(sin(x)).series(x, 0, 5) == 1 + x + x**2/2 - x**4/8 + O(x**5)
+
+
+def test_floor():
+    x = Symbol('x')
+    assert floor(x).series(x) == 0
+    assert floor(-x).series(x) == -1
+    assert floor(sin(x)).series(x) == 0
+    assert floor(sin(-x)).series(x) == -1
+    assert floor(x**3).series(x) == 0
+    assert floor(-x**3).series(x) == -1
+    assert floor(cos(x)).series(x) == 0
+    assert floor(cos(-x)).series(x) == 0
+    assert floor(5 + sin(x)).series(x) == 5
+    assert floor(5 + sin(-x)).series(x) == 4
+
+    assert floor(x).series(x, 2) == 2
+    assert floor(-x).series(x, 2) == -3
+
+    x = Symbol('x', negative=True)
+    assert floor(x + 1.5).series(x) == 1
+
+
+def test_frac():
+    assert frac(x).series(x, cdir=1) == x
+    assert frac(x).series(x, cdir=-1) == 1 + x
+    assert frac(2*x + 1).series(x, cdir=1) == 2*x
+    assert frac(2*x + 1).series(x, cdir=-1) == 1 + 2*x
+    assert frac(x**2).series(x, cdir=1) == x**2
+    assert frac(x**2).series(x, cdir=-1) == x**2
+    assert frac(sin(x) + 5).series(x, cdir=1) == x - x**3/6 + x**5/120 + O(x**6)
+    assert frac(sin(x) + 5).series(x, cdir=-1) == 1 + x - x**3/6 + x**5/120 + O(x**6)
+    assert frac(sin(x) + S.Half).series(x) == S.Half + x - x**3/6 + x**5/120 + O(x**6)
+    assert frac(x**8).series(x, cdir=1) == O(x**6)
+    assert frac(1/x).series(x) == AccumBounds(0, 1) + O(x**6)
+
+
+def test_ceiling():
+    assert ceiling(x).series(x) == 1
+    assert ceiling(-x).series(x) == 0
+    assert ceiling(sin(x)).series(x) == 1
+    assert ceiling(sin(-x)).series(x) == 0
+    assert ceiling(1 - cos(x)).series(x) == 1
+    assert ceiling(1 - cos(-x)).series(x) == 1
+    assert ceiling(x).series(x, 2) == 3
+    assert ceiling(-x).series(x, 2) == -2
+
+
+def test_abs():
+    a = Symbol('a')
+    assert abs(x).nseries(x, n=4) == x
+    assert abs(-x).nseries(x, n=4) == x
+    assert abs(x + 1).nseries(x, n=4) == x + 1
+    assert abs(sin(x)).nseries(x, n=4) == x - Rational(1, 6)*x**3 + O(x**4)
+    assert abs(sin(-x)).nseries(x, n=4) == x - Rational(1, 6)*x**3 + O(x**4)
+    assert abs(x - a).nseries(x, 1) == -a*sign(1 - a) + (x - 1)*sign(1 - a) + sign(1 - a)
+
+
+def test_dir():
+    assert abs(x).series(x, 0, dir="+") == x
+    assert abs(x).series(x, 0, dir="-") == -x
+    assert floor(x + 2).series(x, 0, dir='+') == 2
+    assert floor(x + 2).series(x, 0, dir='-') == 1
+    assert floor(x + 2.2).series(x, 0, dir='-') == 2
+    assert ceiling(x + 2.2).series(x, 0, dir='-') == 3
+    assert sin(x + y).series(x, 0, dir='-') == sin(x + y).series(x, 0, dir='+')
+
+
+def test_cdir():
+    assert abs(x).series(x, 0, cdir=1) == x
+    assert abs(x).series(x, 0, cdir=-1) == -x
+    assert floor(x + 2).series(x, 0, cdir=1) == 2
+    assert floor(x + 2).series(x, 0, cdir=-1) == 1
+    assert floor(x + 2.2).series(x, 0, cdir=1) == 2
+    assert ceiling(x + 2.2).series(x, 0, cdir=-1) == 3
+    assert sin(x + y).series(x, 0, cdir=-1) == sin(x + y).series(x, 0, cdir=1)
+
+
+def test_issue_3504():
+    a = Symbol("a")
+    e = asin(a*x)/x
+    assert e.series(x, 4, n=2).removeO() == \
+        (x - 4)*(a/(4*sqrt(-16*a**2 + 1)) - asin(4*a)/16) + asin(4*a)/4
+
+
+def test_issue_4441():
+    a, b = symbols('a,b')
+    f = 1/(1 + a*x)
+    assert f.series(x, 0, 5) == 1 - a*x + a**2*x**2 - a**3*x**3 + \
+        a**4*x**4 + O(x**5)
+    f = 1/(1 + (a + b)*x)
+    assert f.series(x, 0, 3) == 1 + x*(-a - b)\
+        + x**2*(a + b)**2 + O(x**3)
+
+
+def test_issue_4329():
+    assert tan(x).series(x, pi/2, n=3).removeO() == \
+        -pi/6 + x/3 - 1/(x - pi/2)
+    assert cot(x).series(x, pi, n=3).removeO() == \
+        -x/3 + pi/3 + 1/(x - pi)
+    assert limit(tan(x)**tan(2*x), x, pi/4) == exp(-1)
+
+
+def test_issue_5183():
+    assert abs(x + x**2).series(n=1) == O(x)
+    assert abs(x + x**2).series(n=2) == x + O(x**2)
+    assert ((1 + x)**2).series(x, n=6) == x**2 + 2*x + 1
+    assert (1 + 1/x).series() == 1 + 1/x
+    assert Derivative(exp(x).series(), x).doit() == \
+        1 + x + x**2/2 + x**3/6 + x**4/24 + O(x**5)
+
+
+def test_issue_5654():
+    a = Symbol('a')
+    assert (1/(x**2+a**2)**2).nseries(x, x0=I*a, n=0) == \
+        -I/(4*a**3*(-I*a + x)) - 1/(4*a**2*(-I*a + x)**2) + O(1, (x, I*a))
+    assert (1/(x**2+a**2)**2).nseries(x, x0=I*a, n=1) == 3/(16*a**4) \
+        -I/(4*a**3*(-I*a + x)) - 1/(4*a**2*(-I*a + x)**2) + O(-I*a + x, (x, I*a))
+
+
+def test_issue_5925():
+    sx = sqrt(x + z).series(z, 0, 1)
+    sxy = sqrt(x + y + z).series(z, 0, 1)
+    s1, s2 = sx.subs(x, x + y), sxy
+    assert (s1 - s2).expand().removeO().simplify() == 0
+
+    sx = sqrt(x + z).series(z, 0, 1)
+    sxy = sqrt(x + y + z).series(z, 0, 1)
+    assert sxy.subs({x:1, y:2}) == sx.subs(x, 3)
+
+
+def test_exp_2():
+    assert exp(x**3).nseries(x, 0, 14) == 1 + x**3 + x**6/2 + x**9/6 + x**12/24 + O(x**14)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_order.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_order.py
new file mode 100644
index 0000000000000000000000000000000000000000..50fcb861ee2a76c730baae6d26cc1e7a00347176
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_order.py
@@ -0,0 +1,503 @@
+from sympy.core.add import Add
+from sympy.core.function import (Function, expand)
+from sympy.core.numbers import (I, Rational, nan, oo, pi)
+from sympy.core.singleton import S
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.functions.combinatorial.factorials import factorial
+from sympy.functions.elementary.complexes import (conjugate, transpose)
+from sympy.functions.elementary.exponential import (exp, log)
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import (cos, sin)
+from sympy.integrals.integrals import Integral
+from sympy.series.order import O, Order
+from sympy.core.expr import unchanged
+from sympy.testing.pytest import raises
+from sympy.abc import w, x, y, z
+from sympy.testing.pytest import XFAIL
+
+
+def test_caching_bug():
+    #needs to be a first test, so that all caches are clean
+    #cache it
+    O(w)
+    #and test that this won't raise an exception
+    O(w**(-1/x/log(3)*log(5)), w)
+
+
+def test_free_symbols():
+    assert Order(1).free_symbols == set()
+    assert Order(x).free_symbols == {x}
+    assert Order(1, x).free_symbols == {x}
+    assert Order(x*y).free_symbols == {x, y}
+    assert Order(x, x, y).free_symbols == {x, y}
+
+
+def test_simple_1():
+    o = Rational(0)
+    assert Order(2*x) == Order(x)
+    assert Order(x)*3 == Order(x)
+    assert -28*Order(x) == Order(x)
+    assert Order(Order(x)) == Order(x)
+    assert Order(Order(x), y) == Order(Order(x), x, y)
+    assert Order(-23) == Order(1)
+    assert Order(exp(x)) == Order(1, x)
+    assert Order(exp(1/x)).expr == exp(1/x)
+    assert Order(x*exp(1/x)).expr == x*exp(1/x)
+    assert Order(x**(o/3)).expr == x**(o/3)
+    assert Order(x**(o*Rational(5, 3))).expr == x**(o*Rational(5, 3))
+    assert Order(x**2 + x + y, x) == O(1, x)
+    assert Order(x**2 + x + y, y) == O(1, y)
+    raises(ValueError, lambda: Order(exp(x), x, x))
+    raises(TypeError, lambda: Order(x, 2 - x))
+
+
+def test_simple_2():
+    assert Order(2*x)*x == Order(x**2)
+    assert Order(2*x)/x == Order(1, x)
+    assert Order(2*x)*x*exp(1/x) == Order(x**2*exp(1/x))
+    assert (Order(2*x)*x*exp(1/x)/log(x)**3).expr == x**2*exp(1/x)*log(x)**-3
+
+
+def test_simple_3():
+    assert Order(x) + x == Order(x)
+    assert Order(x) + 2 == 2 + Order(x)
+    assert Order(x) + x**2 == Order(x)
+    assert Order(x) + 1/x == 1/x + Order(x)
+    assert Order(1/x) + 1/x**2 == 1/x**2 + Order(1/x)
+    assert Order(x) + exp(1/x) == Order(x) + exp(1/x)
+
+
+def test_simple_4():
+    assert Order(x)**2 == Order(x**2)
+
+
+def test_simple_5():
+    assert Order(x) + Order(x**2) == Order(x)
+    assert Order(x) + Order(x**-2) == Order(x**-2)
+    assert Order(x) + Order(1/x) == Order(1/x)
+
+
+def test_simple_6():
+    assert Order(x) - Order(x) == Order(x)
+    assert Order(x) + Order(1) == Order(1)
+    assert Order(x) + Order(x**2) == Order(x)
+    assert Order(1/x) + Order(1) == Order(1/x)
+    assert Order(x) + Order(exp(1/x)) == Order(exp(1/x))
+    assert Order(x**3) + Order(exp(2/x)) == Order(exp(2/x))
+    assert Order(x**-3) + Order(exp(2/x)) == Order(exp(2/x))
+
+
+def test_simple_7():
+    assert 1 + O(1) == O(1)
+    assert 2 + O(1) == O(1)
+    assert x + O(1) == O(1)
+    assert 1/x + O(1) == 1/x + O(1)
+
+
+def test_simple_8():
+    assert O(sqrt(-x)) == O(sqrt(x))
+    assert O(x**2*sqrt(x)) == O(x**Rational(5, 2))
+    assert O(x**3*sqrt(-(-x)**3)) == O(x**Rational(9, 2))
+    assert O(x**Rational(3, 2)*sqrt((-x)**3)) == O(x**3)
+    assert O(x*(-2*x)**(I/2)) == O(x*(-x)**(I/2))
+
+
+def test_as_expr_variables():
+    assert Order(x).as_expr_variables(None) == (x, ((x, 0),))
+    assert Order(x).as_expr_variables(((x, 0),)) == (x, ((x, 0),))
+    assert Order(y).as_expr_variables(((x, 0),)) == (y, ((x, 0), (y, 0)))
+    assert Order(y).as_expr_variables(((x, 0), (y, 0))) == (y, ((x, 0), (y, 0)))
+
+
+def test_contains_0():
+    assert Order(1, x).contains(Order(1, x))
+    assert Order(1, x).contains(Order(1))
+    assert Order(1).contains(Order(1, x)) is False
+
+
+def test_contains_1():
+    assert Order(x).contains(Order(x))
+    assert Order(x).contains(Order(x**2))
+    assert not Order(x**2).contains(Order(x))
+    assert not Order(x).contains(Order(1/x))
+    assert not Order(1/x).contains(Order(exp(1/x)))
+    assert not Order(x).contains(Order(exp(1/x)))
+    assert Order(1/x).contains(Order(x))
+    assert Order(exp(1/x)).contains(Order(x))
+    assert Order(exp(1/x)).contains(Order(1/x))
+    assert Order(exp(1/x)).contains(Order(exp(1/x)))
+    assert Order(exp(2/x)).contains(Order(exp(1/x)))
+    assert not Order(exp(1/x)).contains(Order(exp(2/x)))
+
+
+def test_contains_2():
+    assert Order(x).contains(Order(y)) is None
+    assert Order(x).contains(Order(y*x))
+    assert Order(y*x).contains(Order(x))
+    assert Order(y).contains(Order(x*y))
+    assert Order(x).contains(Order(y**2*x))
+
+
+def test_contains_3():
+    assert Order(x*y**2).contains(Order(x**2*y)) is None
+    assert Order(x**2*y).contains(Order(x*y**2)) is None
+
+
+def test_contains_4():
+    assert Order(sin(1/x**2)).contains(Order(cos(1/x**2))) is True
+    assert Order(cos(1/x**2)).contains(Order(sin(1/x**2))) is True
+
+
+def test_contains():
+    assert Order(1, x) not in Order(1)
+    assert Order(1) in Order(1, x)
+    raises(TypeError, lambda: Order(x*y**2) in Order(x**2*y))
+
+
+def test_add_1():
+    assert Order(x + x) == Order(x)
+    assert Order(3*x - 2*x**2) == Order(x)
+    assert Order(1 + x) == Order(1, x)
+    assert Order(1 + 1/x) == Order(1/x)
+    # TODO : A better output for Order(log(x) + 1/log(x))
+    # could be Order(log(x)). Currently Order for expressions
+    # where all arguments would involve a log term would fall
+    # in this category and outputs for these should be improved.
+    assert Order(log(x) + 1/log(x)) == Order((log(x)**2 + 1)/log(x))
+    assert Order(exp(1/x) + x) == Order(exp(1/x))
+    assert Order(exp(1/x) + 1/x**20) == Order(exp(1/x))
+
+
+def test_ln_args():
+    assert O(log(x)) + O(log(2*x)) == O(log(x))
+    assert O(log(x)) + O(log(x**3)) == O(log(x))
+    assert O(log(x*y)) + O(log(x) + log(y)) == O(log(x) + log(y), x, y)
+
+
+def test_multivar_0():
+    assert Order(x*y).expr == x*y
+    assert Order(x*y**2).expr == x*y**2
+    assert Order(x*y, x).expr == x
+    assert Order(x*y**2, y).expr == y**2
+    assert Order(x*y*z).expr == x*y*z
+    assert Order(x/y).expr == x/y
+    assert Order(x*exp(1/y)).expr == x*exp(1/y)
+    assert Order(exp(x)*exp(1/y)).expr == exp(x)*exp(1/y)
+
+
+def test_multivar_0a():
+    assert Order(exp(1/x)*exp(1/y)).expr == exp(1/x)*exp(1/y)
+
+
+def test_multivar_1():
+    assert Order(x + y).expr == x + y
+    assert Order(x + 2*y).expr == x + y
+    assert (Order(x + y) + x).expr == (x + y)
+    assert (Order(x + y) + x**2) == Order(x + y)
+    assert (Order(x + y) + 1/x) == 1/x + Order(x + y)
+    assert Order(x**2 + y*x).expr == x**2 + y*x
+
+
+def test_multivar_2():
+    assert Order(x**2*y + y**2*x, x, y).expr == x**2*y + y**2*x
+
+
+def test_multivar_mul_1():
+    assert Order(x + y)*x == Order(x**2 + y*x, x, y)
+
+
+def test_multivar_3():
+    assert (Order(x) + Order(y)).args in [
+        (Order(x), Order(y)),
+        (Order(y), Order(x))]
+    assert Order(x) + Order(y) + Order(x + y) == Order(x + y)
+    assert (Order(x**2*y) + Order(y**2*x)).args in [
+        (Order(x*y**2), Order(y*x**2)),
+        (Order(y*x**2), Order(x*y**2))]
+    assert (Order(x**2*y) + Order(y*x)) == Order(x*y)
+
+
+def test_issue_3468():
+    y = Symbol('y', negative=True)
+    z = Symbol('z', complex=True)
+
+    # check that Order does not modify assumptions about symbols
+    Order(x)
+    Order(y)
+    Order(z)
+
+    assert x.is_positive is None
+    assert y.is_positive is False
+    assert z.is_positive is None
+
+
+def test_leading_order():
+    assert (x + 1 + 1/x**5).extract_leading_order(x) == ((1/x**5, O(1/x**5)),)
+    assert (1 + 1/x).extract_leading_order(x) == ((1/x, O(1/x)),)
+    assert (1 + x).extract_leading_order(x) == ((1, O(1, x)),)
+    assert (1 + x**2).extract_leading_order(x) == ((1, O(1, x)),)
+    assert (2 + x**2).extract_leading_order(x) == ((2, O(1, x)),)
+    assert (x + x**2).extract_leading_order(x) == ((x, O(x)),)
+
+
+def test_leading_order2():
+    assert set((2 + pi + x**2).extract_leading_order(x)) == {(pi, O(1, x)),
+            (S(2), O(1, x))}
+    assert set((2*x + pi*x + x**2).extract_leading_order(x)) == {(2*x, O(x)),
+            (x*pi, O(x))}
+
+
+def test_order_leadterm():
+    assert O(x**2)._eval_as_leading_term(x, None, 1) == O(x**2)
+
+
+def test_order_symbols():
+    e = x*y*sin(x)*Integral(x, (x, 1, 2))
+    assert O(e) == O(x**2*y, x, y)
+    assert O(e, x) == O(x**2)
+
+
+def test_nan():
+    assert O(nan) is nan
+    assert not O(x).contains(nan)
+
+
+def test_O1():
+    assert O(1, x) * x == O(x)
+    assert O(1, y) * x == O(1, y)
+
+
+def test_getn():
+    # other lines are tested incidentally by the suite
+    assert O(x).getn() == 1
+    assert O(x/log(x)).getn() == 1
+    assert O(x**2/log(x)**2).getn() == 2
+    assert O(x*log(x)).getn() == 1
+    raises(NotImplementedError, lambda: (O(x) + O(y)).getn())
+
+
+def test_diff():
+    assert O(x**2).diff(x) == O(x)
+
+
+def test_getO():
+    assert (x).getO() is None
+    assert (x).removeO() == x
+    assert (O(x)).getO() == O(x)
+    assert (O(x)).removeO() == 0
+    assert (z + O(x) + O(y)).getO() == O(x) + O(y)
+    assert (z + O(x) + O(y)).removeO() == z
+    raises(NotImplementedError, lambda: (O(x) + O(y)).getn())
+
+
+def test_leading_term():
+    from sympy.functions.special.gamma_functions import digamma
+    assert O(1/digamma(1/x)) == O(1/log(x))
+
+
+def test_eval():
+    assert Order(x).subs(Order(x), 1) == 1
+    assert Order(x).subs(x, y) == Order(y)
+    assert Order(x).subs(y, x) == Order(x)
+    assert Order(x).subs(x, x + y) == Order(x + y, (x, -y))
+    assert (O(1)**x).is_Pow
+
+
+def test_issue_4279():
+    a, b = symbols('a b')
+    assert O(a, a, b) + O(1, a, b) == O(1, a, b)
+    assert O(b, a, b) + O(1, a, b) == O(1, a, b)
+    assert O(a + b, a, b) + O(1, a, b) == O(1, a, b)
+    assert O(1, a, b) + O(a, a, b) == O(1, a, b)
+    assert O(1, a, b) + O(b, a, b) == O(1, a, b)
+    assert O(1, a, b) + O(a + b, a, b) == O(1, a, b)
+
+
+def test_issue_4855():
+    assert 1/O(1) != O(1)
+    assert 1/O(x) != O(1/x)
+    assert 1/O(x, (x, oo)) != O(1/x, (x, oo))
+
+    f = Function('f')
+    assert 1/O(f(x)) != O(1/x)
+
+
+def test_order_conjugate_transpose():
+    x = Symbol('x', real=True)
+    y = Symbol('y', imaginary=True)
+    assert conjugate(Order(x)) == Order(conjugate(x))
+    assert conjugate(Order(y)) == Order(conjugate(y))
+    assert conjugate(Order(x**2)) == Order(conjugate(x)**2)
+    assert conjugate(Order(y**2)) == Order(conjugate(y)**2)
+    assert transpose(Order(x)) == Order(transpose(x))
+    assert transpose(Order(y)) == Order(transpose(y))
+    assert transpose(Order(x**2)) == Order(transpose(x)**2)
+    assert transpose(Order(y**2)) == Order(transpose(y)**2)
+
+
+def test_order_noncommutative():
+    A = Symbol('A', commutative=False)
+    assert Order(A + A*x, x) == Order(1, x)
+    assert (A + A*x)*Order(x) == Order(x)
+    assert (A*x)*Order(x) == Order(x**2, x)
+    assert expand((1 + Order(x))*A*A*x) == A*A*x + Order(x**2, x)
+    assert expand((A*A + Order(x))*x) == A*A*x + Order(x**2, x)
+    assert expand((A + Order(x))*A*x) == A*A*x + Order(x**2, x)
+
+
+def test_issue_6753():
+    assert (1 + x**2)**10000*O(x) == O(x)
+
+
+def test_order_at_infinity():
+    assert Order(1 + x, (x, oo)) == Order(x, (x, oo))
+    assert Order(3*x, (x, oo)) == Order(x, (x, oo))
+    assert Order(x, (x, oo))*3 == Order(x, (x, oo))
+    assert -28*Order(x, (x, oo)) == Order(x, (x, oo))
+    assert Order(Order(x, (x, oo)), (x, oo)) == Order(x, (x, oo))
+    assert Order(Order(x, (x, oo)), (y, oo)) == Order(x, (x, oo), (y, oo))
+    assert Order(3, (x, oo)) == Order(1, (x, oo))
+    assert Order(x**2 + x + y, (x, oo)) == O(x**2, (x, oo))
+    assert Order(x**2 + x + y, (y, oo)) == O(y, (y, oo))
+
+    assert Order(2*x, (x, oo))*x == Order(x**2, (x, oo))
+    assert Order(2*x, (x, oo))/x == Order(1, (x, oo))
+    assert Order(2*x, (x, oo))*x*exp(1/x) == Order(x**2*exp(1/x), (x, oo))
+    assert Order(2*x, (x, oo))*x*exp(1/x)/log(x)**3 == Order(x**2*exp(1/x)*log(x)**-3, (x, oo))
+
+    assert Order(x, (x, oo)) + 1/x == 1/x + Order(x, (x, oo)) == Order(x, (x, oo))
+    assert Order(x, (x, oo)) + 1 == 1 + Order(x, (x, oo)) == Order(x, (x, oo))
+    assert Order(x, (x, oo)) + x == x + Order(x, (x, oo)) == Order(x, (x, oo))
+    assert Order(x, (x, oo)) + x**2 == x**2 + Order(x, (x, oo))
+    assert Order(1/x, (x, oo)) + 1/x**2 == 1/x**2 + Order(1/x, (x, oo)) == Order(1/x, (x, oo))
+    assert Order(x, (x, oo)) + exp(1/x) == exp(1/x) + Order(x, (x, oo))
+
+    assert Order(x, (x, oo))**2 == Order(x**2, (x, oo))
+
+    assert Order(x, (x, oo)) + Order(x**2, (x, oo)) == Order(x**2, (x, oo))
+    assert Order(x, (x, oo)) + Order(x**-2, (x, oo)) == Order(x, (x, oo))
+    assert Order(x, (x, oo)) + Order(1/x, (x, oo)) == Order(x, (x, oo))
+
+    assert Order(x, (x, oo)) - Order(x, (x, oo)) == Order(x, (x, oo))
+    assert Order(x, (x, oo)) + Order(1, (x, oo)) == Order(x, (x, oo))
+    assert Order(x, (x, oo)) + Order(x**2, (x, oo)) == Order(x**2, (x, oo))
+    assert Order(1/x, (x, oo)) + Order(1, (x, oo)) == Order(1, (x, oo))
+    assert Order(x, (x, oo)) + Order(exp(1/x), (x, oo)) == Order(x, (x, oo))
+    assert Order(x**3, (x, oo)) + Order(exp(2/x), (x, oo)) == Order(x**3, (x, oo))
+    assert Order(x**-3, (x, oo)) + Order(exp(2/x), (x, oo)) == Order(exp(2/x), (x, oo))
+
+    # issue 7207
+    assert Order(exp(x), (x, oo)).expr == Order(2*exp(x), (x, oo)).expr == exp(x)
+    assert Order(y**x, (x, oo)).expr == Order(2*y**x, (x, oo)).expr == exp(x*log(y))
+
+    # issue 19545
+    assert Order(1/x - 3/(3*x + 2), (x, oo)).expr == x**(-2)
+
+def test_mixing_order_at_zero_and_infinity():
+    assert (Order(x, (x, 0)) + Order(x, (x, oo))).is_Add
+    assert Order(x, (x, 0)) + Order(x, (x, oo)) == Order(x, (x, oo)) + Order(x, (x, 0))
+    assert Order(Order(x, (x, oo))) == Order(x, (x, oo))
+
+    # not supported (yet)
+    raises(NotImplementedError, lambda: Order(x, (x, 0))*Order(x, (x, oo)))
+    raises(NotImplementedError, lambda: Order(x, (x, oo))*Order(x, (x, 0)))
+    raises(NotImplementedError, lambda: Order(Order(x, (x, oo)), y))
+    raises(NotImplementedError, lambda: Order(Order(x), (x, oo)))
+
+
+def test_order_at_some_point():
+    assert Order(x, (x, 1)) == Order(1, (x, 1))
+    assert Order(2*x - 2, (x, 1)) == Order(x - 1, (x, 1))
+    assert Order(-x + 1, (x, 1)) == Order(x - 1, (x, 1))
+    assert Order(x - 1, (x, 1))**2 == Order((x - 1)**2, (x, 1))
+    assert Order(x - 2, (x, 2)) - O(x - 2, (x, 2)) == Order(x - 2, (x, 2))
+
+
+def test_order_subs_limits():
+    # issue 3333
+    assert (1 + Order(x)).subs(x, 1/x) == 1 + Order(1/x, (x, oo))
+    assert (1 + Order(x)).limit(x, 0) == 1
+    # issue 5769
+    assert ((x + Order(x**2))/x).limit(x, 0) == 1
+
+    assert Order(x**2).subs(x, y - 1) == Order((y - 1)**2, (y, 1))
+    assert Order(10*x**2, (x, 2)).subs(x, y - 1) == Order(1, (y, 3))
+
+    #issue 19120
+    assert O(x).subs(x, O(x)) == O(x)
+    assert O(x**2).subs(x, x + O(x)) == O(x**2)
+    assert O(x, (x, oo)).subs(x, O(x, (x, oo))) == O(x, (x, oo))
+    assert O(x**2, (x, oo)).subs(x, x + O(x, (x, oo))) == O(x**2, (x, oo))
+    assert (x + O(x**2)).subs(x, x + O(x**2)) == x + O(x**2)
+    assert (x**2 + O(x**2) + 1/x**2).subs(x, x + O(x**2)) == (x + O(x**2))**(-2) + O(x**2)
+    assert (x**2 + O(x**2) + 1).subs(x, x + O(x**2)) == 1 + O(x**2)
+    assert O(x, (x, oo)).subs(x, x + O(x**2, (x, oo))) == O(x**2, (x, oo))
+    assert sin(x).series(n=8).subs(x,sin(x).series(n=8)).expand() == x - x**3/3 + x**5/10 - 8*x**7/315 + O(x**8)
+    assert cos(x).series(n=8).subs(x,sin(x).series(n=8)).expand() == 1 - x**2/2 + 5*x**4/24 - 37*x**6/720 + O(x**8)
+    assert O(x).subs(x, O(1/x, (x, oo))) == O(1/x, (x, oo))
+
+@XFAIL
+def test_order_failing_due_to_solveset():
+    assert O(x**3).subs(x, exp(-x**2)) == O(exp(-3*x**2), (x, -oo))
+    raises(NotImplementedError, lambda: O(x).subs(x, O(1/x))) # mixing of order at different points
+
+
+def test_issue_9351():
+    assert exp(x).series(x, 10, 1) == exp(10) + Order(x - 10, (x, 10))
+
+
+def test_issue_9192():
+    assert O(1)*O(1) == O(1)
+    assert O(1)**O(1) == O(1)
+
+
+def test_issue_9910():
+    assert O(x*log(x) + sin(x), (x, oo)) == O(x*log(x), (x, oo))
+
+
+def test_performance_of_adding_order():
+    l = [x**i for i in range(1000)]
+    l.append(O(x**1001))
+    assert Add(*l).subs(x,1) == O(1)
+
+def test_issue_14622():
+    assert (x**(-4) + x**(-3) + x**(-1) + O(x**(-6), (x, oo))).as_numer_denom() == (
+        x**4 + x**5 + x**7 + O(x**2, (x, oo)), x**8)
+    assert (x**3 + O(x**2, (x, oo))).is_Add
+    assert O(x**2, (x, oo)).contains(x**3) is False
+    assert O(x, (x, oo)).contains(O(x, (x, 0))) is None
+    assert O(x, (x, 0)).contains(O(x, (x, oo))) is None
+    raises(NotImplementedError, lambda: O(x**3).contains(x**w))
+
+
+def test_issue_15539():
+    assert O(1/x**2 + 1/x**4, (x, -oo)) == O(1/x**2, (x, -oo))
+    assert O(1/x**4 + exp(x), (x, -oo)) == O(1/x**4, (x, -oo))
+    assert O(1/x**4 + exp(-x), (x, -oo)) == O(exp(-x), (x, -oo))
+    assert O(1/x, (x, oo)).subs(x, -x) == O(-1/x, (x, -oo))
+
+def test_issue_18606():
+    assert unchanged(Order, 0)
+
+
+def test_issue_22165():
+    assert O(log(x)).contains(2)
+
+
+def test_issue_23231():
+    # This test checks Order for expressions having
+    # arguments containing variables in exponents/powers.
+    assert O(x**x + 2**x, (x, oo)) == O(exp(x*log(x)), (x, oo))
+    assert O(x**x + x**2, (x, oo)) == O(exp(x*log(x)), (x, oo))
+    assert O(x**x + 1/x**2, (x, oo)) == O(exp(x*log(x)), (x, oo))
+    assert O(2**x + 3**x , (x, oo)) == O(exp(x*log(3)), (x, oo))
+
+
+def test_issue_9917():
+    assert O(x*sin(x) + 1, (x, oo)) == O(x, (x, oo))
+
+
+def test_issue_22836():
+    assert O(2**x + factorial(x), (x, oo)) == O(factorial(x), (x, oo))
+    assert O(2**x + factorial(x) + x**x, (x, oo)) == O(exp(x*log(x)), (x, oo))
+    assert O(x + factorial(x), (x, oo)) == O(factorial(x), (x, oo))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_residues.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_residues.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f7d075a56500d008e3c8b46c1fda5db890fd76a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_residues.py
@@ -0,0 +1,101 @@
+from sympy.core.function import Function
+from sympy.core.numbers import (I, Rational, pi)
+from sympy.core.singleton import S
+from sympy.core.symbol import Symbol
+from sympy.functions.combinatorial.factorials import factorial
+from sympy.functions.elementary.exponential import (exp, log)
+from sympy.functions.elementary.hyperbolic import tanh
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import (cot, sin, tan)
+from sympy.series.residues import residue
+from sympy.testing.pytest import XFAIL, raises
+from sympy.abc import x, z, a, s, k
+
+
+def test_basic1():
+    assert residue(1/x, x, 0) == 1
+    assert residue(-2/x, x, 0) == -2
+    assert residue(81/x, x, 0) == 81
+    assert residue(1/x**2, x, 0) == 0
+    assert residue(0, x, 0) == 0
+    assert residue(5, x, 0) == 0
+    assert residue(x, x, 0) == 0
+    assert residue(x**2, x, 0) == 0
+
+
+def test_basic2():
+    assert residue(1/x, x, 1) == 0
+    assert residue(-2/x, x, 1) == 0
+    assert residue(81/x, x, -1) == 0
+    assert residue(1/x**2, x, 1) == 0
+    assert residue(0, x, 1) == 0
+    assert residue(5, x, 1) == 0
+    assert residue(x, x, 1) == 0
+    assert residue(x**2, x, 5) == 0
+
+
+def test_f():
+    f = Function("f")
+    assert residue(f(x)/x**5, x, 0) == f(x).diff(x, 4).subs(x, 0)/24
+
+
+def test_functions():
+    assert residue(1/sin(x), x, 0) == 1
+    assert residue(2/sin(x), x, 0) == 2
+    assert residue(1/sin(x)**2, x, 0) == 0
+    assert residue(1/sin(x)**5, x, 0) == Rational(3, 8)
+
+
+def test_expressions():
+    assert residue(1/(x + 1), x, 0) == 0
+    assert residue(1/(x + 1), x, -1) == 1
+    assert residue(1/(x**2 + 1), x, -1) == 0
+    assert residue(1/(x**2 + 1), x, I) == -I/2
+    assert residue(1/(x**2 + 1), x, -I) == I/2
+    assert residue(1/(x**4 + 1), x, 0) == 0
+    assert residue(1/(x**4 + 1), x, exp(I*pi/4)).equals(-(Rational(1, 4) + I/4)/sqrt(2))
+    assert residue(1/(x**2 + a**2)**2, x, a*I) == -I/4/a**3
+
+
+@XFAIL
+def test_expressions_failing():
+    n = Symbol('n', integer=True, positive=True)
+    assert residue(exp(z)/(z - pi*I/4*a)**n, z, I*pi*a) == \
+        exp(I*pi*a/4)/factorial(n - 1)
+
+
+def test_NotImplemented():
+    raises(NotImplementedError, lambda: residue(exp(1/z), z, 0))
+
+
+def test_bug():
+    assert residue(2**(z)*(s + z)*(1 - s - z)/z**2, z, 0) == \
+        1 + s*log(2) - s**2*log(2) - 2*s
+
+
+def test_issue_5654():
+    assert residue(1/(x**2 + a**2)**2, x, a*I) == -I/(4*a**3)
+    assert residue(1/s*1/(z - exp(s)), s, 0) == 1/(z - 1)
+    assert residue((1 + k)/s*1/(z - exp(s)), s, 0) == k/(z - 1) + 1/(z - 1)
+
+
+def test_issue_6499():
+    assert residue(1/(exp(z) - 1), z, 0) == 1
+
+
+def test_issue_14037():
+    assert residue(sin(x**50)/x**51, x, 0) == 1
+
+
+def test_issue_21176():
+    f = x**2*cot(pi*x)/(x**4 + 1)
+    assert residue(f, x, -sqrt(2)/2 - sqrt(2)*I/2).cancel().together(deep=True)\
+        == sqrt(2)*(1 - I)/(8*tan(sqrt(2)*pi*(1 + I)/2))
+
+
+def test_issue_21177():
+    r = -sqrt(3)*tanh(sqrt(3)*pi/2)/3
+    a = residue(cot(pi*x)/((x - 1)*(x - 2) + 1), x, S(3)/2 - sqrt(3)*I/2)
+    b = residue(cot(pi*x)/(x**2 - 3*x + 3), x, S(3)/2 - sqrt(3)*I/2)
+    assert a == r
+    assert (b - a).cancel() == 0
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_sequences.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_sequences.py
new file mode 100644
index 0000000000000000000000000000000000000000..61e276ad67982f0a9877de3548d70238976d28a5
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_sequences.py
@@ -0,0 +1,312 @@
+from sympy.core.containers import Tuple
+from sympy.core.function import Function
+from sympy.core.numbers import oo, Rational
+from sympy.core.singleton import S
+from sympy.core.symbol import symbols, Symbol
+from sympy.functions.combinatorial.numbers import tribonacci, fibonacci
+from sympy.functions.elementary.exponential import exp
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import cos, sin
+from sympy.series import EmptySequence
+from sympy.series.sequences import (SeqMul, SeqAdd, SeqPer, SeqFormula,
+    sequence)
+from sympy.sets.sets import Interval
+from sympy.tensor.indexed import Indexed, Idx
+from sympy.series.sequences import SeqExpr, SeqExprOp, RecursiveSeq
+from sympy.testing.pytest import raises, slow
+
+x, y, z = symbols('x y z')
+n, m = symbols('n m')
+
+
+def test_EmptySequence():
+    assert S.EmptySequence is EmptySequence
+
+    assert S.EmptySequence.interval is S.EmptySet
+    assert S.EmptySequence.length is S.Zero
+
+    assert list(S.EmptySequence) == []
+
+
+def test_SeqExpr():
+    #SeqExpr is a baseclass and does not take care of
+    #ensuring all arguments are Basics hence the use of
+    #Tuple(...) here.
+    s = SeqExpr(Tuple(1, n, y), Tuple(x, 0, 10))
+
+    assert isinstance(s, SeqExpr)
+    assert s.gen == (1, n, y)
+    assert s.interval == Interval(0, 10)
+    assert s.start == 0
+    assert s.stop == 10
+    assert s.length == 11
+    assert s.variables == (x,)
+
+    assert SeqExpr(Tuple(1, 2, 3), Tuple(x, 0, oo)).length is oo
+
+
+def test_SeqPer():
+    s = SeqPer((1, n, 3), (x, 0, 5))
+
+    assert isinstance(s, SeqPer)
+    assert s.periodical == Tuple(1, n, 3)
+    assert s.period == 3
+    assert s.coeff(3) == 1
+    assert s.free_symbols == {n}
+
+    assert list(s) == [1, n, 3, 1, n, 3]
+    assert s[:] == [1, n, 3, 1, n, 3]
+    assert SeqPer((1, n, 3), (x, -oo, 0))[0:6] == [1, n, 3, 1, n, 3]
+
+    raises(ValueError, lambda: SeqPer((1, 2, 3), (0, 1, 2)))
+    raises(ValueError, lambda: SeqPer((1, 2, 3), (x, -oo, oo)))
+    raises(ValueError, lambda: SeqPer(n**2, (0, oo)))
+
+    assert SeqPer((n, n**2, n**3), (m, 0, oo))[:6] == \
+        [n, n**2, n**3, n, n**2, n**3]
+    assert SeqPer((n, n**2, n**3), (n, 0, oo))[:6] == [0, 1, 8, 3, 16, 125]
+    assert SeqPer((n, m), (n, 0, oo))[:6] == [0, m, 2, m, 4, m]
+
+
+def test_SeqFormula():
+    s = SeqFormula(n**2, (n, 0, 5))
+
+    assert isinstance(s, SeqFormula)
+    assert s.formula == n**2
+    assert s.coeff(3) == 9
+
+    assert list(s) == [i**2 for i in range(6)]
+    assert s[:] == [i**2 for i in range(6)]
+    assert SeqFormula(n**2, (n, -oo, 0))[0:6] == [i**2 for i in range(6)]
+
+    assert SeqFormula(n**2, (0, oo)) == SeqFormula(n**2, (n, 0, oo))
+
+    assert SeqFormula(n**2, (0, m)).subs(m, x) == SeqFormula(n**2, (0, x))
+    assert SeqFormula(m*n**2, (n, 0, oo)).subs(m, x) == \
+        SeqFormula(x*n**2, (n, 0, oo))
+
+    raises(ValueError, lambda: SeqFormula(n**2, (0, 1, 2)))
+    raises(ValueError, lambda: SeqFormula(n**2, (n, -oo, oo)))
+    raises(ValueError, lambda: SeqFormula(m*n**2, (0, oo)))
+
+    seq = SeqFormula(x*(y**2 + z), (z, 1, 100))
+    assert seq.expand() == SeqFormula(x*y**2 + x*z, (z, 1, 100))
+    seq = SeqFormula(sin(x*(y**2 + z)),(z, 1, 100))
+    assert seq.expand(trig=True) == SeqFormula(sin(x*y**2)*cos(x*z) + sin(x*z)*cos(x*y**2), (z, 1, 100))
+    assert seq.expand() == SeqFormula(sin(x*y**2 + x*z), (z, 1, 100))
+    assert seq.expand(trig=False) == SeqFormula(sin(x*y**2 + x*z), (z, 1, 100))
+    seq = SeqFormula(exp(x*(y**2 + z)), (z, 1, 100))
+    assert seq.expand() == SeqFormula(exp(x*y**2)*exp(x*z), (z, 1, 100))
+    assert seq.expand(power_exp=False) == SeqFormula(exp(x*y**2 + x*z), (z, 1, 100))
+    assert seq.expand(mul=False, power_exp=False) == SeqFormula(exp(x*(y**2 + z)), (z, 1, 100))
+
+def test_sequence():
+    form = SeqFormula(n**2, (n, 0, 5))
+    per = SeqPer((1, 2, 3), (n, 0, 5))
+    inter = SeqFormula(n**2)
+
+    assert sequence(n**2, (n, 0, 5)) == form
+    assert sequence((1, 2, 3), (n, 0, 5)) == per
+    assert sequence(n**2) == inter
+
+
+def test_SeqExprOp():
+    form = SeqFormula(n**2, (n, 0, 10))
+    per = SeqPer((1, 2, 3), (m, 5, 10))
+
+    s = SeqExprOp(form, per)
+    assert s.gen == (n**2, (1, 2, 3))
+    assert s.interval == Interval(5, 10)
+    assert s.start == 5
+    assert s.stop == 10
+    assert s.length == 6
+    assert s.variables == (n, m)
+
+
+def test_SeqAdd():
+    per = SeqPer((1, 2, 3), (n, 0, oo))
+    form = SeqFormula(n**2)
+
+    per_bou = SeqPer((1, 2), (n, 1, 5))
+    form_bou = SeqFormula(n**2, (6, 10))
+    form_bou2 = SeqFormula(n**2, (1, 5))
+
+    assert SeqAdd() == S.EmptySequence
+    assert SeqAdd(S.EmptySequence) == S.EmptySequence
+    assert SeqAdd(per) == per
+    assert SeqAdd(per, S.EmptySequence) == per
+    assert SeqAdd(per_bou, form_bou) == S.EmptySequence
+
+    s = SeqAdd(per_bou, form_bou2, evaluate=False)
+    assert s.args == (form_bou2, per_bou)
+    assert s[:] == [2, 6, 10, 18, 26]
+    assert list(s) == [2, 6, 10, 18, 26]
+
+    assert isinstance(SeqAdd(per, per_bou, evaluate=False), SeqAdd)
+
+    s1 = SeqAdd(per, per_bou)
+    assert isinstance(s1, SeqPer)
+    assert s1 == SeqPer((2, 4, 4, 3, 3, 5), (n, 1, 5))
+    s2 = SeqAdd(form, form_bou)
+    assert isinstance(s2, SeqFormula)
+    assert s2 == SeqFormula(2*n**2, (6, 10))
+
+    assert SeqAdd(form, form_bou, per) == \
+        SeqAdd(per, SeqFormula(2*n**2, (6, 10)))
+    assert SeqAdd(form, SeqAdd(form_bou, per)) == \
+        SeqAdd(per, SeqFormula(2*n**2, (6, 10)))
+    assert SeqAdd(per, SeqAdd(form, form_bou), evaluate=False) == \
+        SeqAdd(per, SeqFormula(2*n**2, (6, 10)))
+
+    assert SeqAdd(SeqPer((1, 2), (n, 0, oo)), SeqPer((1, 2), (m, 0, oo))) == \
+        SeqPer((2, 4), (n, 0, oo))
+
+
+def test_SeqMul():
+    per = SeqPer((1, 2, 3), (n, 0, oo))
+    form = SeqFormula(n**2)
+
+    per_bou = SeqPer((1, 2), (n, 1, 5))
+    form_bou = SeqFormula(n**2, (n, 6, 10))
+    form_bou2 = SeqFormula(n**2, (1, 5))
+
+    assert SeqMul() == S.EmptySequence
+    assert SeqMul(S.EmptySequence) == S.EmptySequence
+    assert SeqMul(per) == per
+    assert SeqMul(per, S.EmptySequence) == S.EmptySequence
+    assert SeqMul(per_bou, form_bou) == S.EmptySequence
+
+    s = SeqMul(per_bou, form_bou2, evaluate=False)
+    assert s.args == (form_bou2, per_bou)
+    assert s[:] == [1, 8, 9, 32, 25]
+    assert list(s) == [1, 8, 9, 32, 25]
+
+    assert isinstance(SeqMul(per, per_bou, evaluate=False), SeqMul)
+
+    s1 = SeqMul(per, per_bou)
+    assert isinstance(s1, SeqPer)
+    assert s1 == SeqPer((1, 4, 3, 2, 2, 6), (n, 1, 5))
+    s2 = SeqMul(form, form_bou)
+    assert isinstance(s2, SeqFormula)
+    assert s2 == SeqFormula(n**4, (6, 10))
+
+    assert SeqMul(form, form_bou, per) == \
+        SeqMul(per, SeqFormula(n**4, (6, 10)))
+    assert SeqMul(form, SeqMul(form_bou, per)) == \
+        SeqMul(per, SeqFormula(n**4, (6, 10)))
+    assert SeqMul(per, SeqMul(form, form_bou2,
+                              evaluate=False), evaluate=False) == \
+        SeqMul(form, per, form_bou2, evaluate=False)
+
+    assert SeqMul(SeqPer((1, 2), (n, 0, oo)), SeqPer((1, 2), (n, 0, oo))) == \
+        SeqPer((1, 4), (n, 0, oo))
+
+
+def test_add():
+    per = SeqPer((1, 2), (n, 0, oo))
+    form = SeqFormula(n**2)
+
+    assert per + (SeqPer((2, 3))) == SeqPer((3, 5), (n, 0, oo))
+    assert form + SeqFormula(n**3) == SeqFormula(n**2 + n**3)
+
+    assert per + form == SeqAdd(per, form)
+
+    raises(TypeError, lambda: per + n)
+    raises(TypeError, lambda: n + per)
+
+
+def test_sub():
+    per = SeqPer((1, 2), (n, 0, oo))
+    form = SeqFormula(n**2)
+
+    assert per - (SeqPer((2, 3))) == SeqPer((-1, -1), (n, 0, oo))
+    assert form - (SeqFormula(n**3)) == SeqFormula(n**2 - n**3)
+
+    assert per - form == SeqAdd(per, -form)
+
+    raises(TypeError, lambda: per - n)
+    raises(TypeError, lambda: n - per)
+
+
+def test_mul__coeff_mul():
+    assert SeqPer((1, 2), (n, 0, oo)).coeff_mul(2) == SeqPer((2, 4), (n, 0, oo))
+    assert SeqFormula(n**2).coeff_mul(2) == SeqFormula(2*n**2)
+    assert S.EmptySequence.coeff_mul(100) == S.EmptySequence
+
+    assert SeqPer((1, 2), (n, 0, oo)) * (SeqPer((2, 3))) == \
+        SeqPer((2, 6), (n, 0, oo))
+    assert SeqFormula(n**2) * SeqFormula(n**3) == SeqFormula(n**5)
+
+    assert S.EmptySequence * SeqFormula(n**2) == S.EmptySequence
+    assert SeqFormula(n**2) * S.EmptySequence == S.EmptySequence
+
+    raises(TypeError, lambda: sequence(n**2) * n)
+    raises(TypeError, lambda: n * sequence(n**2))
+
+
+def test_neg():
+    assert -SeqPer((1, -2), (n, 0, oo)) == SeqPer((-1, 2), (n, 0, oo))
+    assert -SeqFormula(n**2) == SeqFormula(-n**2)
+
+
+def test_operations():
+    per = SeqPer((1, 2), (n, 0, oo))
+    per2 = SeqPer((2, 4), (n, 0, oo))
+    form = SeqFormula(n**2)
+    form2 = SeqFormula(n**3)
+
+    assert per + form + form2 == SeqAdd(per, form, form2)
+    assert per + form - form2 == SeqAdd(per, form, -form2)
+    assert per + form - S.EmptySequence == SeqAdd(per, form)
+    assert per + per2 + form == SeqAdd(SeqPer((3, 6), (n, 0, oo)), form)
+    assert S.EmptySequence - per == -per
+    assert form + form == SeqFormula(2*n**2)
+
+    assert per * form * form2 == SeqMul(per, form, form2)
+    assert form * form == SeqFormula(n**4)
+    assert form * -form == SeqFormula(-n**4)
+
+    assert form * (per + form2) == SeqMul(form, SeqAdd(per, form2))
+    assert form * (per + per) == SeqMul(form, per2)
+
+    assert form.coeff_mul(m) == SeqFormula(m*n**2, (n, 0, oo))
+    assert per.coeff_mul(m) == SeqPer((m, 2*m), (n, 0, oo))
+
+
+def test_Idx_limits():
+    i = symbols('i', cls=Idx)
+    r = Indexed('r', i)
+
+    assert SeqFormula(r, (i, 0, 5))[:] == [r.subs(i, j) for j in range(6)]
+    assert SeqPer((1, 2), (i, 0, 5))[:] == [1, 2, 1, 2, 1, 2]
+
+
+@slow
+def test_find_linear_recurrence():
+    assert sequence((0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55), \
+    (n, 0, 10)).find_linear_recurrence(11) == [1, 1]
+    assert sequence((1, 2, 4, 7, 28, 128, 582, 2745, 13021, 61699, 292521, \
+    1387138), (n, 0, 11)).find_linear_recurrence(12) == [5, -2, 6, -11]
+    assert sequence(x*n**3+y*n, (n, 0, oo)).find_linear_recurrence(10) \
+    == [4, -6, 4, -1]
+    assert sequence(x**n, (n,0,20)).find_linear_recurrence(21) == [x]
+    assert sequence((1,2,3)).find_linear_recurrence(10, 5) == [0, 0, 1]
+    assert sequence(((1 + sqrt(5))/2)**n + \
+    (-(1 + sqrt(5))/2)**(-n)).find_linear_recurrence(10) == [1, 1]
+    assert sequence(x*((1 + sqrt(5))/2)**n + y*(-(1 + sqrt(5))/2)**(-n), \
+    (n,0,oo)).find_linear_recurrence(10) == [1, 1]
+    assert sequence((1,2,3,4,6),(n, 0, 4)).find_linear_recurrence(5) == []
+    assert sequence((2,3,4,5,6,79),(n, 0, 5)).find_linear_recurrence(6,gfvar=x) \
+    == ([], None)
+    assert sequence((2,3,4,5,8,30),(n, 0, 5)).find_linear_recurrence(6,gfvar=x) \
+    == ([Rational(19, 2), -20, Rational(27, 2)], (-31*x**2 + 32*x - 4)/(27*x**3 - 40*x**2 + 19*x -2))
+    assert sequence(fibonacci(n)).find_linear_recurrence(30,gfvar=x) \
+    == ([1, 1], -x/(x**2 + x - 1))
+    assert sequence(tribonacci(n)).find_linear_recurrence(30,gfvar=x) \
+    ==  ([1, 1, 1], -x/(x**3 + x**2 + x - 1))
+
+def test_RecursiveSeq():
+    y = Function('y')
+    n = Symbol('n')
+    fib = RecursiveSeq(y(n - 1) + y(n - 2), y(n), n, [0, 1])
+    assert fib.coeff(3) == 2
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_series.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_series.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3f3c122b98c14a58c6d5c6636cbb53e1e66a75d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/series/tests/test_series.py
@@ -0,0 +1,421 @@
+from sympy.core.evalf import N
+from sympy.core.function import (Derivative, Function, PoleError, Subs)
+from sympy.core.numbers import (E, Float, Rational, oo, pi, I)
+from sympy.core.singleton import S
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.functions.elementary.exponential import (LambertW, exp, log)
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import (atan, cos, sin)
+from sympy.functions.special.gamma_functions import gamma
+from sympy.integrals.integrals import Integral, integrate
+from sympy.series.order import O
+from sympy.series.series import series
+from sympy.abc import x, y, n, k
+from sympy.testing.pytest import raises
+from sympy.core import EulerGamma
+
+
+def test_sin():
+    e1 = sin(x).series(x, 0)
+    e2 = series(sin(x), x, 0)
+    assert e1 == e2
+
+
+def test_cos():
+    e1 = cos(x).series(x, 0)
+    e2 = series(cos(x), x, 0)
+    assert e1 == e2
+
+
+def test_exp():
+    e1 = exp(x).series(x, 0)
+    e2 = series(exp(x), x, 0)
+    assert e1 == e2
+
+
+def test_exp2():
+    e1 = exp(cos(x)).series(x, 0)
+    e2 = series(exp(cos(x)), x, 0)
+    assert e1 == e2
+
+
+def test_issue_5223():
+    assert series(1, x) == 1
+    assert next(S.Zero.lseries(x)) == 0
+    assert cos(x).series() == cos(x).series(x)
+    raises(ValueError, lambda: cos(x + y).series())
+    raises(ValueError, lambda: x.series(dir=""))
+
+    assert (cos(x).series(x, 1) -
+            cos(x + 1).series(x).subs(x, x - 1)).removeO() == 0
+    e = cos(x).series(x, 1, n=None)
+    assert [next(e) for i in range(2)] == [cos(1), -((x - 1)*sin(1))]
+    e = cos(x).series(x, 1, n=None, dir='-')
+    assert [next(e) for i in range(2)] == [cos(1), (1 - x)*sin(1)]
+    # the following test is exact so no need for x -> x - 1 replacement
+    assert abs(x).series(x, 1, dir='-') == x
+    assert exp(x).series(x, 1, dir='-', n=3).removeO() == \
+        E - E*(-x + 1) + E*(-x + 1)**2/2
+
+    D = Derivative
+    assert D(x**2 + x**3*y**2, x, 2, y, 1).series(x).doit() == 12*x*y
+    assert next(D(cos(x), x).lseries()) == D(1, x)
+    assert D(
+        exp(x), x).series(n=3) == D(1, x) + D(x, x) + D(x**2/2, x) + D(x**3/6, x) + O(x**3)
+
+    assert Integral(x, (x, 1, 3), (y, 1, x)).series(x) == -4 + 4*x
+
+    assert (1 + x + O(x**2)).getn() == 2
+    assert (1 + x).getn() is None
+
+    raises(PoleError, lambda: ((1/sin(x))**oo).series())
+    logx = Symbol('logx')
+    assert ((sin(x))**y).nseries(x, n=1, logx=logx) == \
+        exp(y*logx) + O(x*exp(y*logx), x)
+
+    assert sin(1/x).series(x, oo, n=5) == 1/x - 1/(6*x**3) + O(x**(-5), (x, oo))
+    assert abs(x).series(x, oo, n=5, dir='+') == x
+    assert abs(x).series(x, -oo, n=5, dir='-') == -x
+    assert abs(-x).series(x, oo, n=5, dir='+') == x
+    assert abs(-x).series(x, -oo, n=5, dir='-') == -x
+
+    assert exp(x*log(x)).series(n=3) == \
+        1 + x*log(x) + x**2*log(x)**2/2 + O(x**3*log(x)**3)
+    # XXX is this right? If not, fix "ngot > n" handling in expr.
+    p = Symbol('p', positive=True)
+    assert exp(sqrt(p)**3*log(p)).series(n=3) == \
+        1 + p**S('3/2')*log(p) + O(p**3*log(p)**3)
+
+    assert exp(sin(x)*log(x)).series(n=2) == 1 + x*log(x) + O(x**2*log(x)**2)
+
+
+def test_issue_6350():
+    expr = integrate(exp(k*(y**3 - 3*y)), (y, 0, oo), conds='none')
+    assert expr.series(k, 0, 3) == -(-1)**(S(2)/3)*sqrt(3)*gamma(S(1)/3)**2*gamma(S(2)/3)/(6*pi*k**(S(1)/3)) - \
+        sqrt(3)*k*gamma(-S(2)/3)*gamma(-S(1)/3)/(6*pi) - \
+        (-1)**(S(1)/3)*sqrt(3)*k**(S(1)/3)*gamma(-S(1)/3)*gamma(S(1)/3)*gamma(S(2)/3)/(6*pi) - \
+        (-1)**(S(2)/3)*sqrt(3)*k**(S(5)/3)*gamma(S(1)/3)**2*gamma(S(2)/3)/(4*pi) - \
+        (-1)**(S(1)/3)*sqrt(3)*k**(S(7)/3)*gamma(-S(1)/3)*gamma(S(1)/3)*gamma(S(2)/3)/(8*pi) + O(k**3)
+
+
+def test_issue_11313():
+    assert Integral(cos(x), x).series(x) == sin(x).series(x)
+    assert Derivative(sin(x), x).series(x, n=3).doit() == cos(x).series(x, n=3)
+
+    assert Derivative(x**3, x).as_leading_term(x) == 3*x**2
+    assert Derivative(x**3, y).as_leading_term(x) == 0
+    assert Derivative(sin(x), x).as_leading_term(x) == 1
+    assert Derivative(cos(x), x).as_leading_term(x) == -x
+
+    # This result is equivalent to zero, zero is not return because
+    # `Expr.series` doesn't currently detect an `x` in its `free_symbol`s.
+    assert Derivative(1, x).as_leading_term(x) == Derivative(1, x)
+
+    assert Derivative(exp(x), x).series(x).doit() == exp(x).series(x)
+    assert 1 + Integral(exp(x), x).series(x) == exp(x).series(x)
+
+    assert Derivative(log(x), x).series(x).doit() == (1/x).series(x)
+    assert Integral(log(x), x).series(x) == Integral(log(x), x).doit().series(x).removeO()
+
+
+def test_series_of_Subs():
+    from sympy.abc import z
+
+    subs1 = Subs(sin(x), x, y)
+    subs2 = Subs(sin(x) * cos(z), x, y)
+    subs3 = Subs(sin(x * z), (x, z), (y, x))
+
+    assert subs1.series(x) == subs1
+    subs1_series = (Subs(x, x, y) + Subs(-x**3/6, x, y) +
+        Subs(x**5/120, x, y) + O(y**6))
+    assert subs1.series() == subs1_series
+    assert subs1.series(y) == subs1_series
+    assert subs1.series(z) == subs1
+    assert subs2.series(z) == (Subs(z**4*sin(x)/24, x, y) +
+        Subs(-z**2*sin(x)/2, x, y) + Subs(sin(x), x, y) + O(z**6))
+    assert subs3.series(x).doit() == subs3.doit().series(x)
+    assert subs3.series(z).doit() == sin(x*y)
+
+    raises(ValueError, lambda: Subs(x + 2*y, y, z).series())
+    assert Subs(x + y, y, z).series(x).doit() == x + z
+
+
+def test_issue_3978():
+    f = Function('f')
+    assert f(x).series(x, 0, 3, dir='-') == \
+            f(0) + x*Subs(Derivative(f(x), x), x, 0) + \
+            x**2*Subs(Derivative(f(x), x, x), x, 0)/2 + O(x**3)
+    assert f(x).series(x, 0, 3) == \
+            f(0) + x*Subs(Derivative(f(x), x), x, 0) + \
+            x**2*Subs(Derivative(f(x), x, x), x, 0)/2 + O(x**3)
+    assert f(x**2).series(x, 0, 3) == \
+            f(0) + x**2*Subs(Derivative(f(x), x), x, 0) + O(x**3)
+    assert f(x**2+1).series(x, 0, 3) == \
+            f(1) + x**2*Subs(Derivative(f(x), x), x, 1) + O(x**3)
+
+    class TestF(Function):
+        pass
+
+    assert TestF(x).series(x, 0, 3) ==  TestF(0) + \
+            x*Subs(Derivative(TestF(x), x), x, 0) + \
+            x**2*Subs(Derivative(TestF(x), x, x), x, 0)/2 + O(x**3)
+
+from sympy.series.acceleration import richardson, shanks
+from sympy.concrete.summations import Sum
+from sympy.core.numbers import Integer
+
+
+def test_acceleration():
+    e = (1 + 1/n)**n
+    assert round(richardson(e, n, 10, 20).evalf(), 10) == round(E.evalf(), 10)
+
+    A = Sum(Integer(-1)**(k + 1) / k, (k, 1, n))
+    assert round(shanks(A, n, 25).evalf(), 4) == round(log(2).evalf(), 4)
+    assert round(shanks(A, n, 25, 5).evalf(), 10) == round(log(2).evalf(), 10)
+
+
+def test_issue_5852():
+    assert series(1/cos(x/log(x)), x, 0) == 1 + x**2/(2*log(x)**2) + \
+        5*x**4/(24*log(x)**4) + O(x**6)
+
+
+def test_issue_4583():
+    assert cos(1 + x + x**2).series(x, 0, 5) == cos(1) - x*sin(1) + \
+        x**2*(-sin(1) - cos(1)/2) + x**3*(-cos(1) + sin(1)/6) + \
+        x**4*(-11*cos(1)/24 + sin(1)/2) + O(x**5)
+
+
+def test_issue_6318():
+    eq = (1/x)**Rational(2, 3)
+    assert (eq + 1).as_leading_term(x) == eq
+
+
+def test_x_is_base_detection():
+    eq = (x**2)**Rational(2, 3)
+    assert eq.series() == x**Rational(4, 3)
+
+
+def test_issue_7203():
+    assert series(cos(x), x, pi, 3) == \
+        -1 + (x - pi)**2/2 + O((x - pi)**3, (x, pi))
+
+
+def test_exp_product_positive_factors():
+    a, b = symbols('a, b', positive=True)
+    x = a * b
+    assert series(exp(x), x, n=8) == 1 + a*b + a**2*b**2/2 + \
+        a**3*b**3/6 + a**4*b**4/24 + a**5*b**5/120 + a**6*b**6/720 + \
+        a**7*b**7/5040 + O(a**8*b**8, a, b)
+
+
+def test_issue_8805():
+    assert series(1, n=8) == 1
+
+
+def test_issue_9173():
+    p0,p1,p2,p3,b0,b1,b2=symbols('p0 p1 p2 p3 b0 b1 b2')
+    Q=(p0+(p1+(p2+p3/y)/y)/y)/(1+((p3/(b0*y)+(b0*p2-b1*p3)/b0**2)/y+\
+       (b0**2*p1-b0*b1*p2-p3*(b0*b2-b1**2))/b0**3)/y)
+
+    series = Q.series(y,n=3)
+
+    assert series == y*(b0*p2/p3+b0*(-p2/p3+b1/b0))+y**2*(b0*p1/p3+b0*p2*\
+            (-p2/p3+b1/b0)/p3+b0*(-p1/p3+(p2/p3-b1/b0)**2+b1*p2/(b0*p3)+\
+            b2/b0-b1**2/b0**2))+b0+O(y**3)
+    assert series.simplify() == b2*y**2 + b1*y + b0 + O(y**3)
+
+
+def test_issue_9549():
+    y = (x**2 + x + 1) / (x**3 + x**2)
+    assert series(y, x, oo) == x**(-5) - 1/x**4 + x**(-3) + 1/x + O(x**(-6), (x, oo))
+
+
+def test_issue_10761():
+    assert series(1/(x**-2 + x**-3), x, 0) == x**3 - x**4 + x**5 + O(x**6)
+
+
+def test_issue_12578():
+    y = (1 - 1/(x/2 - 1/(2*x))**4)**(S(1)/8)
+    assert y.series(x, 0, n=17) == 1 - 2*x**4 - 8*x**6 - 34*x**8 - 152*x**10 - 714*x**12 - \
+        3472*x**14 - 17318*x**16 + O(x**17)
+
+
+def test_issue_12791():
+    beta = symbols('beta', positive=True)
+    theta, varphi = symbols('theta varphi', real=True)
+
+    expr = (-beta**2*varphi*sin(theta) + beta**2*cos(theta) + \
+        beta*varphi*sin(theta) - beta*cos(theta) - beta + 1)/(beta*cos(theta) - 1)**2
+
+    sol = (0.5/(0.5*cos(theta) - 1.0)**2 - 0.25*cos(theta)/(0.5*cos(theta) - 1.0)**2
+        + (beta - 0.5)*(-0.25*varphi*sin(2*theta) - 1.5*cos(theta)
+        + 0.25*cos(2*theta) + 1.25)/((0.5*cos(theta) - 1.0)**2*(0.5*cos(theta) - 1.0))
+        + 0.25*varphi*sin(theta)/(0.5*cos(theta) - 1.0)**2
+        + O((beta - S.Half)**2, (beta, S.Half)))
+
+    assert expr.series(beta, 0.5, 2).trigsimp() == sol
+
+
+def test_issue_14384():
+    x, a = symbols('x a')
+    assert series(x**a, x) == x**a
+    assert series(x**(-2*a), x) == x**(-2*a)
+    assert series(exp(a*log(x)), x) == exp(a*log(x))
+    raises(PoleError, lambda: series(x**I, x))
+    raises(PoleError, lambda: series(x**(I + 1), x))
+    raises(PoleError, lambda: series(exp(I*log(x)), x))
+
+
+def test_issue_14885():
+    assert series(x**Rational(-3, 2)*exp(x), x, 0) == (x**Rational(-3, 2) + 1/sqrt(x) +
+        sqrt(x)/2 + x**Rational(3, 2)/6 + x**Rational(5, 2)/24 + x**Rational(7, 2)/120 +
+        x**Rational(9, 2)/720 + x**Rational(11, 2)/5040 + O(x**6))
+
+
+def test_issue_15539():
+    assert series(atan(x), x, -oo) == (-1/(5*x**5) + 1/(3*x**3) - 1/x - pi/2
+        + O(x**(-6), (x, -oo)))
+    assert series(atan(x), x, oo) == (-1/(5*x**5) + 1/(3*x**3) - 1/x + pi/2
+        + O(x**(-6), (x, oo)))
+
+
+def test_issue_7259():
+    assert series(LambertW(x), x) == x - x**2 + 3*x**3/2 - 8*x**4/3 + 125*x**5/24 + O(x**6)
+    assert series(LambertW(x**2), x, n=8) == x**2 - x**4 + 3*x**6/2 + O(x**8)
+    assert series(LambertW(sin(x)), x, n=4) == x - x**2 + 4*x**3/3 + O(x**4)
+
+def test_issue_11884():
+    assert cos(x).series(x, 1, n=1) == cos(1) + O(x - 1, (x, 1))
+
+
+def test_issue_18008():
+    y = x*(1 + x*(1 - x))/((1 + x*(1 - x)) - (1 - x)*(1 - x))
+    assert y.series(x, oo, n=4) == -9/(32*x**3) - 3/(16*x**2) - 1/(8*x) + S(1)/4 + x/2 + \
+        O(x**(-4), (x, oo))
+
+
+def test_issue_18842():
+    f = log(x/(1 - x))
+    assert f.series(x, 0.491, n=1).removeO().nsimplify() ==  \
+        -S(180019443780011)/5000000000000000
+
+
+def test_issue_19534():
+    dt = symbols('dt', real=True)
+    expr = 16*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0)/45 + \
+            49*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \
+            0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \
+            0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
+            0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
+            0.96296296296296296296*dt + 1.0) + 0.051640768506639183825*dt + \
+            dt*(1/2 - sqrt(21)/14) + 1.0)/180 + 49*dt*(-0.23637909581542530626*dt*(2.0*dt + 1.0) - \
+            0.74817562366625959291*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
+            0.88085458023927036857*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
+            0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
+            0.96296296296296296296*dt + 1.0) + \
+            2.1165151389911680013*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \
+            0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \
+            0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
+            0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
+            0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) - \
+            1.1854881643947648988*dt + dt*(sqrt(21)/14 + 1/2) + 1.0)/180 + \
+            dt*(0.66666666666666666667*dt*(2.0*dt + 1.0) + \
+            6.0173399699313066769*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \
+            4.1117044797036320069*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
+            0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
+            0.96296296296296296296*dt + 1.0) - \
+            7.0189140975801991157*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \
+            0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \
+            0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
+            0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
+            0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) + \
+            0.94010945196161777522*dt*(-0.23637909581542530626*dt*(2.0*dt + 1.0) - \
+            0.74817562366625959291*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
+            0.88085458023927036857*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
+            0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
+            0.96296296296296296296*dt + 1.0) + \
+            2.1165151389911680013*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \
+            0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \
+            0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \
+            0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \
+            0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) - \
+            0.35816132904077632692*dt + 1.0) + 5.5065024887242400038*dt + 1.0)/20 + dt/20 + 1
+
+    assert N(expr.series(dt, 0, 8), 20) == (
+            - Float('0.00092592592592592596126289', precision=70) * dt**7
+            + Float('0.0027777777777777783174695', precision=70) * dt**6
+            + Float('0.016666666666666656027029', precision=70) * dt**5
+            + Float('0.083333333333333300951828', precision=70) * dt**4
+            + Float('0.33333333333333337034077', precision=70) * dt**3
+            + Float('1.0', precision=70) * dt**2
+            + Float('1.0', precision=70) * dt
+            + Float('1.0', precision=70)
+        )
+
+
+def test_issue_11407():
+    a, b, c, x = symbols('a b c x')
+    assert series(sqrt(a + b + c*x), x, 0, 1) == sqrt(a + b) + O(x)
+    assert series(sqrt(a + b + c + c*x), x, 0, 1) == sqrt(a + b + c) + O(x)
+
+
+def test_issue_14037():
+    assert (sin(x**50)/x**51).series(x, n=0) == 1/x + O(1, x)
+
+
+def test_issue_20551():
+    expr = (exp(x)/x).series(x, n=None)
+    terms = [ next(expr) for i in range(3) ]
+    assert terms == [1/x, 1, x/2]
+
+
+def test_issue_20697():
+    p_0, p_1, p_2, p_3, b_0, b_1, b_2 = symbols('p_0 p_1 p_2 p_3 b_0 b_1 b_2')
+    Q = (p_0 + (p_1 + (p_2 + p_3/y)/y)/y)/(1 + ((p_3/(b_0*y) + (b_0*p_2\
+        - b_1*p_3)/b_0**2)/y + (b_0**2*p_1 - b_0*b_1*p_2 - p_3*(b_0*b_2\
+        - b_1**2))/b_0**3)/y)
+    assert Q.series(y, n=3).ratsimp() == b_2*y**2 + b_1*y + b_0 + O(y**3)
+
+
+def test_issue_21245():
+    fi = (1 + sqrt(5))/2
+    assert (1/(1 - x - x**2)).series(x, 1/fi, 1).factor() == \
+        (-37*sqrt(5) - 83 + 13*sqrt(5)*x + 29*x + O((x - 2/(1 + sqrt(5)))**2, (x\
+            , 2/(1 + sqrt(5)))))/((2*sqrt(5) + 5)**2*(x + sqrt(5)*x - 2))
+
+
+
+def test_issue_21938():
+    expr = sin(1/x + exp(-x)) - sin(1/x)
+    assert expr.series(x, oo) == (1/(24*x**4) - 1/(2*x**2) + 1 + O(x**(-6), (x, oo)))*exp(-x)
+
+
+def test_issue_23432():
+    expr = 1/sqrt(1 - x**2)
+    result = expr.series(x, 0.5)
+    assert result.is_Add and len(result.args) == 7
+
+
+def test_issue_23727():
+    res = series(sqrt(1 - x**2), x, 0.1)
+    assert res.is_Add == True
+
+
+def test_issue_24266():
+    #type1: exp(f(x))
+    assert (exp(-I*pi*(2*x+1))).series(x, 0, 3) == -1 + 2*I*pi*x + 2*pi**2*x**2 + O(x**3)
+    assert (exp(-I*pi*(2*x+1))*gamma(1+x)).series(x, 0, 3) == -1 + x*(EulerGamma + 2*I*pi) + \
+        x**2*(-EulerGamma**2/2 + 23*pi**2/12 - 2*EulerGamma*I*pi) + O(x**3)
+
+    #type2: c**f(x)
+    assert ((2*I)**(-I*pi*(2*x+1))).series(x, 0, 2) == exp(pi**2/2 - I*pi*log(2)) + \
+          x*(pi**2*exp(pi**2/2 - I*pi*log(2)) - 2*I*pi*exp(pi**2/2 - I*pi*log(2))*log(2)) + O(x**2)
+    assert ((2)**(-I*pi*(2*x+1))).series(x, 0, 2) == exp(-I*pi*log(2)) - 2*I*pi*x*exp(-I*pi*log(2))*log(2) + O(x**2)
+
+    #type3: f(y)**g(x)
+    assert ((y)**(I*pi*(2*x+1))).series(x, 0, 2) == exp(I*pi*log(y)) + 2*I*pi*x*exp(I*pi*log(y))*log(y) + O(x**2)
+    assert ((I*y)**(I*pi*(2*x+1))).series(x, 0, 2) == exp(I*pi*log(I*y)) + 2*I*pi*x*exp(I*pi*log(I*y))*log(I*y) + O(x**2)
+
+
+def test_issue_26856():
+    raises(ValueError, lambda: (2**x).series(x, oo, -1))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b909c0b5ef03b1e1e76dfbf4288f61860575da7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__init__.py
@@ -0,0 +1,36 @@
+from .sets import (Set, Interval, Union, FiniteSet, ProductSet,
+        Intersection, imageset, Complement, SymmetricDifference,
+        DisjointUnion)
+
+from .fancysets import ImageSet, Range, ComplexRegion
+from .contains import Contains
+from .conditionset import ConditionSet
+from .ordinals import Ordinal, OmegaPower, ord0
+from .powerset import PowerSet
+from ..core.singleton import S
+from .handlers.comparison import _eval_is_eq  # noqa:F401
+Complexes = S.Complexes
+EmptySet = S.EmptySet
+Integers = S.Integers
+Naturals = S.Naturals
+Naturals0 = S.Naturals0
+Rationals = S.Rationals
+Reals = S.Reals
+UniversalSet = S.UniversalSet
+
+__all__ = [
+    'Set', 'Interval', 'Union', 'EmptySet', 'FiniteSet', 'ProductSet',
+    'Intersection', 'imageset', 'Complement', 'SymmetricDifference', 'DisjointUnion',
+
+    'ImageSet', 'Range', 'ComplexRegion', 'Reals',
+
+    'Contains',
+
+    'ConditionSet',
+
+    'Ordinal', 'OmegaPower', 'ord0',
+
+    'PowerSet',
+
+    'Reals', 'Naturals', 'Naturals0', 'UniversalSet', 'Integers', 'Rationals',
+]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6616bdab7e7dbae4cdb474f09395af7c0233579e
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/conditionset.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/conditionset.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d3185d71f8862f3551e4374c8f8de089a5a30609
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/conditionset.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/contains.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/contains.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a160899784cc3ee678ee179d6e0b7a7550ea253c
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/contains.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/fancysets.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/fancysets.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ab6465d69401ace713d0113d97de26eb7cd67de
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/fancysets.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/ordinals.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/ordinals.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..900271540811239fd3897a5f81297fc4c586da45
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/ordinals.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/powerset.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/powerset.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f7619f74cdda3aaad86d08ff762e98a44c356f3a
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/powerset.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/sets.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/sets.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..33fa7154739ca6371d00da524d8301e13557127a
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/__pycache__/sets.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/conditionset.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/conditionset.py
new file mode 100644
index 0000000000000000000000000000000000000000..e847e60ce97d7e9922ce907042ace941838b0ab1
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/conditionset.py
@@ -0,0 +1,246 @@
+from sympy.core.singleton import S
+from sympy.core.basic import Basic
+from sympy.core.containers import Tuple
+from sympy.core.function import Lambda, BadSignatureError
+from sympy.core.logic import fuzzy_bool
+from sympy.core.relational import Eq
+from sympy.core.symbol import Dummy
+from sympy.core.sympify import _sympify
+from sympy.logic.boolalg import And, as_Boolean
+from sympy.utilities.iterables import sift, flatten, has_dups
+from sympy.utilities.exceptions import sympy_deprecation_warning
+from .contains import Contains
+from .sets import Set, Union, FiniteSet, SetKind
+
+
+adummy = Dummy('conditionset')
+
+
+class ConditionSet(Set):
+    r"""
+    Set of elements which satisfies a given condition.
+
+    .. math:: \{x \mid \textrm{condition}(x) = \texttt{True}, x \in S\}
+
+    Examples
+    ========
+
+    >>> from sympy import Symbol, S, ConditionSet, pi, Eq, sin, Interval
+    >>> from sympy.abc import x, y, z
+
+    >>> sin_sols = ConditionSet(x, Eq(sin(x), 0), Interval(0, 2*pi))
+    >>> 2*pi in sin_sols
+    True
+    >>> pi/2 in sin_sols
+    False
+    >>> 3*pi in sin_sols
+    False
+    >>> 5 in ConditionSet(x, x**2 > 4, S.Reals)
+    True
+
+    If the value is not in the base set, the result is false:
+
+    >>> 5 in ConditionSet(x, x**2 > 4, Interval(2, 4))
+    False
+
+    Notes
+    =====
+
+    Symbols with assumptions should be avoided or else the
+    condition may evaluate without consideration of the set:
+
+    >>> n = Symbol('n', negative=True)
+    >>> cond = (n > 0); cond
+    False
+    >>> ConditionSet(n, cond, S.Integers)
+    EmptySet
+
+    Only free symbols can be changed by using `subs`:
+
+    >>> c = ConditionSet(x, x < 1, {x, z})
+    >>> c.subs(x, y)
+    ConditionSet(x, x < 1, {y, z})
+
+    To check if ``pi`` is in ``c`` use:
+
+    >>> pi in c
+    False
+
+    If no base set is specified, the universal set is implied:
+
+    >>> ConditionSet(x, x < 1).base_set
+    UniversalSet
+
+    Only symbols or symbol-like expressions can be used:
+
+    >>> ConditionSet(x + 1, x + 1 < 1, S.Integers)
+    Traceback (most recent call last):
+    ...
+    ValueError: non-symbol dummy not recognized in condition
+
+    When the base set is a ConditionSet, the symbols will be
+    unified if possible with preference for the outermost symbols:
+
+    >>> ConditionSet(x, x < y, ConditionSet(z, z + y < 2, S.Integers))
+    ConditionSet(x, (x < y) & (x + y < 2), Integers)
+
+    """
+    def __new__(cls, sym, condition, base_set=S.UniversalSet):
+        sym = _sympify(sym)
+        flat = flatten([sym])
+        if has_dups(flat):
+            raise BadSignatureError("Duplicate symbols detected")
+        base_set = _sympify(base_set)
+        if not isinstance(base_set, Set):
+            raise TypeError(
+                'base set should be a Set object, not %s' % base_set)
+        condition = _sympify(condition)
+
+        if isinstance(condition, FiniteSet):
+            condition_orig = condition
+            temp = (Eq(lhs, 0) for lhs in condition)
+            condition = And(*temp)
+            sympy_deprecation_warning(
+                f"""
+Using a set for the condition in ConditionSet is deprecated. Use a boolean
+instead.
+
+In this case, replace
+
+    {condition_orig}
+
+with
+
+    {condition}
+""",
+                deprecated_since_version='1.5',
+                active_deprecations_target="deprecated-conditionset-set",
+                )
+
+        condition = as_Boolean(condition)
+
+        if condition is S.true:
+            return base_set
+
+        if condition is S.false:
+            return S.EmptySet
+
+        if base_set is S.EmptySet:
+            return S.EmptySet
+
+        # no simple answers, so now check syms
+        for i in flat:
+            if not getattr(i, '_diff_wrt', False):
+                raise ValueError('`%s` is not symbol-like' % i)
+
+        if base_set.contains(sym) is S.false:
+            raise TypeError('sym `%s` is not in base_set `%s`' % (sym, base_set))
+
+        know = None
+        if isinstance(base_set, FiniteSet):
+            sifted = sift(
+                base_set, lambda _: fuzzy_bool(condition.subs(sym, _)))
+            if sifted[None]:
+                know = FiniteSet(*sifted[True])
+                base_set = FiniteSet(*sifted[None])
+            else:
+                return FiniteSet(*sifted[True])
+
+        if isinstance(base_set, cls):
+            s, c, b = base_set.args
+            def sig(s):
+                return cls(s, Eq(adummy, 0)).as_dummy().sym
+            sa, sb = map(sig, (sym, s))
+            if sa != sb:
+                raise BadSignatureError('sym does not match sym of base set')
+            reps = dict(zip(flatten([sym]), flatten([s])))
+            if s == sym:
+                condition = And(condition, c)
+                base_set = b
+            elif not c.free_symbols & sym.free_symbols:
+                reps = {v: k for k, v in reps.items()}
+                condition = And(condition, c.xreplace(reps))
+                base_set = b
+            elif not condition.free_symbols & s.free_symbols:
+                sym = sym.xreplace(reps)
+                condition = And(condition.xreplace(reps), c)
+                base_set = b
+
+        # flatten ConditionSet(Contains(ConditionSet())) expressions
+        if isinstance(condition, Contains) and (sym == condition.args[0]):
+            if isinstance(condition.args[1], Set):
+                return condition.args[1].intersect(base_set)
+
+        rv = Basic.__new__(cls, sym, condition, base_set)
+        return rv if know is None else Union(know, rv)
+
+    sym = property(lambda self: self.args[0])
+    condition = property(lambda self: self.args[1])
+    base_set = property(lambda self: self.args[2])
+
+    @property
+    def free_symbols(self):
+        cond_syms = self.condition.free_symbols - self.sym.free_symbols
+        return cond_syms | self.base_set.free_symbols
+
+    @property
+    def bound_symbols(self):
+        return flatten([self.sym])
+
+    def _contains(self, other):
+        def ok_sig(a, b):
+            tuples = [isinstance(i, Tuple) for i in (a, b)]
+            c = tuples.count(True)
+            if c == 1:
+                return False
+            if c == 0:
+                return True
+            return len(a) == len(b) and all(
+                ok_sig(i, j) for i, j in zip(a, b))
+        if not ok_sig(self.sym, other):
+            return S.false
+
+        # try doing base_cond first and return
+        # False immediately if it is False
+        base_cond = Contains(other, self.base_set)
+        if base_cond is S.false:
+            return S.false
+
+        # Substitute other into condition. This could raise e.g. for
+        # ConditionSet(x, 1/x >= 0, Reals).contains(0)
+        lamda = Lambda((self.sym,), self.condition)
+        try:
+            lambda_cond = lamda(other)
+        except TypeError:
+            return None
+        else:
+            return And(base_cond, lambda_cond)
+
+    def as_relational(self, other):
+        f = Lambda(self.sym, self.condition)
+        if isinstance(self.sym, Tuple):
+            f = f(*other)
+        else:
+            f = f(other)
+        return And(f, self.base_set.contains(other))
+
+    def _eval_subs(self, old, new):
+        sym, cond, base = self.args
+        dsym = sym.subs(old, adummy)
+        insym = dsym.has(adummy)
+        # prioritize changing a symbol in the base
+        newbase = base.subs(old, new)
+        if newbase != base:
+            if not insym:
+                cond = cond.subs(old, new)
+            return self.func(sym, cond, newbase)
+        if insym:
+            pass  # no change of bound symbols via subs
+        elif getattr(new, '_diff_wrt', False):
+            cond = cond.subs(old, new)
+        else:
+            pass  # let error about the symbol raise from __new__
+        return self.func(sym, cond, base)
+
+    def _kind(self):
+        return SetKind(self.sym.kind)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/contains.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/contains.py
new file mode 100644
index 0000000000000000000000000000000000000000..403d4875279d718724a898efa5cba41bc7bed6ea
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/contains.py
@@ -0,0 +1,63 @@
+from sympy.core import S
+from sympy.core.sympify import sympify
+from sympy.core.relational import Eq, Ne
+from sympy.core.parameters import global_parameters
+from sympy.logic.boolalg import Boolean
+from sympy.utilities.misc import func_name
+from .sets import Set
+
+
+class Contains(Boolean):
+    """
+    Asserts that x is an element of the set S.
+
+    Examples
+    ========
+
+    >>> from sympy import Symbol, Integer, S, Contains
+    >>> Contains(Integer(2), S.Integers)
+    True
+    >>> Contains(Integer(-2), S.Naturals)
+    False
+    >>> i = Symbol('i', integer=True)
+    >>> Contains(i, S.Naturals)
+    Contains(i, Naturals)
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Element_%28mathematics%29
+    """
+    def __new__(cls, x, s, evaluate=None):
+        x = sympify(x)
+        s = sympify(s)
+
+        if evaluate is None:
+            evaluate = global_parameters.evaluate
+
+        if not isinstance(s, Set):
+            raise TypeError('expecting Set, not %s' % func_name(s))
+
+        if evaluate:
+            # _contains can return symbolic booleans that would be returned by
+            # s.contains(x) but here for Contains(x, s) we only evaluate to
+            # true, false or return the unevaluated Contains.
+            result = s._contains(x)
+
+            if isinstance(result, Boolean):
+                if result in (S.true, S.false):
+                    return result
+            elif result is not None:
+                raise TypeError("_contains() should return Boolean or None")
+
+        return super().__new__(cls, x, s)
+
+    @property
+    def binary_symbols(self):
+        return set().union(*[i.binary_symbols
+            for i in self.args[1].args
+            if i.is_Boolean or i.is_Symbol or
+            isinstance(i, (Eq, Ne))])
+
+    def as_set(self):
+        return self.args[1]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/fancysets.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/fancysets.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0e24a2a864222d16ba1a697558b5211127fb2ad
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/fancysets.py
@@ -0,0 +1,1523 @@
+from functools import reduce
+from itertools import product
+
+from sympy.core.basic import Basic
+from sympy.core.containers import Tuple
+from sympy.core.expr import Expr
+from sympy.core.function import Lambda
+from sympy.core.logic import fuzzy_not, fuzzy_or, fuzzy_and
+from sympy.core.mod import Mod
+from sympy.core.intfunc import igcd
+from sympy.core.numbers import oo, Rational, Integer
+from sympy.core.relational import Eq, is_eq
+from sympy.core.kind import NumberKind
+from sympy.core.singleton import Singleton, S
+from sympy.core.symbol import Dummy, symbols, Symbol
+from sympy.core.sympify import _sympify, sympify, _sympy_converter
+from sympy.functions.elementary.integers import ceiling, floor
+from sympy.functions.elementary.trigonometric import sin, cos
+from sympy.logic.boolalg import And, Or
+from .sets import tfn, Set, Interval, Union, FiniteSet, ProductSet, SetKind
+from sympy.utilities.misc import filldedent
+
+
+class Rationals(Set, metaclass=Singleton):
+    """
+    Represents the rational numbers. This set is also available as
+    the singleton ``S.Rationals``.
+
+    Examples
+    ========
+
+    >>> from sympy import S
+    >>> S.Half in S.Rationals
+    True
+    >>> iterable = iter(S.Rationals)
+    >>> [next(iterable) for i in range(12)]
+    [0, 1, -1, 1/2, 2, -1/2, -2, 1/3, 3, -1/3, -3, 2/3]
+    """
+
+    is_iterable = True
+    _inf = S.NegativeInfinity
+    _sup = S.Infinity
+    is_empty = False
+    is_finite_set = False
+
+    def _contains(self, other):
+        if not isinstance(other, Expr):
+            return S.false
+        return tfn[other.is_rational]
+
+    def __iter__(self):
+        yield S.Zero
+        yield S.One
+        yield S.NegativeOne
+        d = 2
+        while True:
+            for n in range(d):
+                if igcd(n, d) == 1:
+                    yield Rational(n, d)
+                    yield Rational(d, n)
+                    yield Rational(-n, d)
+                    yield Rational(-d, n)
+            d += 1
+
+    @property
+    def _boundary(self):
+        return S.Reals
+
+    def _kind(self):
+        return SetKind(NumberKind)
+
+
+class Naturals(Set, metaclass=Singleton):
+    """
+    Represents the natural numbers (or counting numbers) which are all
+    positive integers starting from 1. This set is also available as
+    the singleton ``S.Naturals``.
+
+    Examples
+    ========
+
+    >>> from sympy import S, Interval, pprint
+    >>> 5 in S.Naturals
+    True
+    >>> iterable = iter(S.Naturals)
+    >>> next(iterable)
+    1
+    >>> next(iterable)
+    2
+    >>> next(iterable)
+    3
+    >>> pprint(S.Naturals.intersect(Interval(0, 10)))
+    {1, 2, ..., 10}
+
+    See Also
+    ========
+
+    Naturals0 : non-negative integers (i.e. includes 0, too)
+    Integers : also includes negative integers
+    """
+
+    is_iterable = True
+    _inf: Integer = S.One
+    _sup = S.Infinity
+    is_empty = False
+    is_finite_set = False
+
+    def _contains(self, other):
+        if not isinstance(other, Expr):
+            return S.false
+        elif other.is_positive and other.is_integer:
+            return S.true
+        elif other.is_integer is False or other.is_positive is False:
+            return S.false
+
+    def _eval_is_subset(self, other):
+        return Range(1, oo).is_subset(other)
+
+    def _eval_is_superset(self, other):
+        return Range(1, oo).is_superset(other)
+
+    def __iter__(self):
+        i = self._inf
+        while True:
+            yield i
+            i = i + 1
+
+    @property
+    def _boundary(self):
+        return self
+
+    def as_relational(self, x):
+        return And(Eq(floor(x), x), x >= self.inf, x < oo)
+
+    def _kind(self):
+        return SetKind(NumberKind)
+
+
+class Naturals0(Naturals):
+    """Represents the whole numbers which are all the non-negative integers,
+    inclusive of zero.
+
+    See Also
+    ========
+
+    Naturals : positive integers; does not include 0
+    Integers : also includes the negative integers
+    """
+    _inf = S.Zero
+
+    def _contains(self, other):
+        if not isinstance(other, Expr):
+            return S.false
+        elif other.is_integer and other.is_nonnegative:
+            return S.true
+        elif other.is_integer is False or other.is_nonnegative is False:
+            return S.false
+
+    def _eval_is_subset(self, other):
+        return Range(oo).is_subset(other)
+
+    def _eval_is_superset(self, other):
+        return Range(oo).is_superset(other)
+
+
+class Integers(Set, metaclass=Singleton):
+    """
+    Represents all integers: positive, negative and zero. This set is also
+    available as the singleton ``S.Integers``.
+
+    Examples
+    ========
+
+    >>> from sympy import S, Interval, pprint
+    >>> 5 in S.Naturals
+    True
+    >>> iterable = iter(S.Integers)
+    >>> next(iterable)
+    0
+    >>> next(iterable)
+    1
+    >>> next(iterable)
+    -1
+    >>> next(iterable)
+    2
+
+    >>> pprint(S.Integers.intersect(Interval(-4, 4)))
+    {-4, -3, ..., 4}
+
+    See Also
+    ========
+
+    Naturals0 : non-negative integers
+    Integers : positive and negative integers and zero
+    """
+
+    is_iterable = True
+    is_empty = False
+    is_finite_set = False
+
+    def _contains(self, other):
+        if not isinstance(other, Expr):
+            return S.false
+        return tfn[other.is_integer]
+
+    def __iter__(self):
+        yield S.Zero
+        i = S.One
+        while True:
+            yield i
+            yield -i
+            i = i + 1
+
+    @property
+    def _inf(self):
+        return S.NegativeInfinity
+
+    @property
+    def _sup(self):
+        return S.Infinity
+
+    @property
+    def _boundary(self):
+        return self
+
+    def _kind(self):
+        return SetKind(NumberKind)
+
+    def as_relational(self, x):
+        return And(Eq(floor(x), x), -oo < x, x < oo)
+
+    def _eval_is_subset(self, other):
+        return Range(-oo, oo).is_subset(other)
+
+    def _eval_is_superset(self, other):
+        return Range(-oo, oo).is_superset(other)
+
+
+class Reals(Interval, metaclass=Singleton):
+    """
+    Represents all real numbers
+    from negative infinity to positive infinity,
+    including all integer, rational and irrational numbers.
+    This set is also available as the singleton ``S.Reals``.
+
+
+    Examples
+    ========
+
+    >>> from sympy import S, Rational, pi, I
+    >>> 5 in S.Reals
+    True
+    >>> Rational(-1, 2) in S.Reals
+    True
+    >>> pi in S.Reals
+    True
+    >>> 3*I in S.Reals
+    False
+    >>> S.Reals.contains(pi)
+    True
+
+
+    See Also
+    ========
+
+    ComplexRegion
+    """
+    @property
+    def start(self):
+        return S.NegativeInfinity
+
+    @property
+    def end(self):
+        return S.Infinity
+
+    @property
+    def left_open(self):
+        return True
+
+    @property
+    def right_open(self):
+        return True
+
+    def __eq__(self, other):
+        return other == Interval(S.NegativeInfinity, S.Infinity)
+
+    def __hash__(self):
+        return hash(Interval(S.NegativeInfinity, S.Infinity))
+
+
+class ImageSet(Set):
+    """
+    Image of a set under a mathematical function. The transformation
+    must be given as a Lambda function which has as many arguments
+    as the elements of the set upon which it operates, e.g. 1 argument
+    when acting on the set of integers or 2 arguments when acting on
+    a complex region.
+
+    This function is not normally called directly, but is called
+    from ``imageset``.
+
+
+    Examples
+    ========
+
+    >>> from sympy import Symbol, S, pi, Dummy, Lambda
+    >>> from sympy import FiniteSet, ImageSet, Interval
+
+    >>> x = Symbol('x')
+    >>> N = S.Naturals
+    >>> squares = ImageSet(Lambda(x, x**2), N) # {x**2 for x in N}
+    >>> 4 in squares
+    True
+    >>> 5 in squares
+    False
+
+    >>> FiniteSet(0, 1, 2, 3, 4, 5, 6, 7, 9, 10).intersect(squares)
+    {1, 4, 9}
+
+    >>> square_iterable = iter(squares)
+    >>> for i in range(4):
+    ...     next(square_iterable)
+    1
+    4
+    9
+    16
+
+    If you want to get value for `x` = 2, 1/2 etc. (Please check whether the
+    `x` value is in ``base_set`` or not before passing it as args)
+
+    >>> squares.lamda(2)
+    4
+    >>> squares.lamda(S(1)/2)
+    1/4
+
+    >>> n = Dummy('n')
+    >>> solutions = ImageSet(Lambda(n, n*pi), S.Integers) # solutions of sin(x) = 0
+    >>> dom = Interval(-1, 1)
+    >>> dom.intersect(solutions)
+    {0}
+
+    See Also
+    ========
+
+    sympy.sets.sets.imageset
+    """
+    def __new__(cls, flambda, *sets):
+        if not isinstance(flambda, Lambda):
+            raise ValueError('First argument must be a Lambda')
+
+        signature = flambda.signature
+
+        if len(signature) != len(sets):
+            raise ValueError('Incompatible signature')
+
+        sets = [_sympify(s) for s in sets]
+
+        if not all(isinstance(s, Set) for s in sets):
+            raise TypeError("Set arguments to ImageSet should of type Set")
+
+        if not all(cls._check_sig(sg, st) for sg, st in zip(signature, sets)):
+            raise ValueError("Signature %s does not match sets %s" % (signature, sets))
+
+        if flambda is S.IdentityFunction and len(sets) == 1:
+            return sets[0]
+
+        if not set(flambda.variables) & flambda.expr.free_symbols:
+            is_empty = fuzzy_or(s.is_empty for s in sets)
+            if is_empty == True:
+                return S.EmptySet
+            elif is_empty == False:
+                return FiniteSet(flambda.expr)
+
+        return Basic.__new__(cls, flambda, *sets)
+
+    lamda = property(lambda self: self.args[0])
+    base_sets = property(lambda self: self.args[1:])
+
+    @property
+    def base_set(self):
+        # XXX: Maybe deprecate this? It is poorly defined in handling
+        # the multivariate case...
+        sets = self.base_sets
+        if len(sets) == 1:
+            return sets[0]
+        else:
+            return ProductSet(*sets).flatten()
+
+    @property
+    def base_pset(self):
+        return ProductSet(*self.base_sets)
+
+    @classmethod
+    def _check_sig(cls, sig_i, set_i):
+        if sig_i.is_symbol:
+            return True
+        elif isinstance(set_i, ProductSet):
+            sets = set_i.sets
+            if len(sig_i) != len(sets):
+                return False
+            # Recurse through the signature for nested tuples:
+            return all(cls._check_sig(ts, ps) for ts, ps in zip(sig_i, sets))
+        else:
+            # XXX: Need a better way of checking whether a set is a set of
+            # Tuples or not. For example a FiniteSet can contain Tuples
+            # but so can an ImageSet or a ConditionSet. Others like
+            # Integers, Reals etc can not contain Tuples. We could just
+            # list the possibilities here... Current code for e.g.
+            # _contains probably only works for ProductSet.
+            return True # Give the benefit of the doubt
+
+    def __iter__(self):
+        already_seen = set()
+        for i in self.base_pset:
+            val = self.lamda(*i)
+            if val in already_seen:
+                continue
+            else:
+                already_seen.add(val)
+                yield val
+
+    def _is_multivariate(self):
+        return len(self.lamda.variables) > 1
+
+    def _contains(self, other):
+        from sympy.solvers.solveset import _solveset_multi
+
+        def get_symsetmap(signature, base_sets):
+            '''Attempt to get a map of symbols to base_sets'''
+            queue = list(zip(signature, base_sets))
+            symsetmap = {}
+            for sig, base_set in queue:
+                if sig.is_symbol:
+                    symsetmap[sig] = base_set
+                elif base_set.is_ProductSet:
+                    sets = base_set.sets
+                    if len(sig) != len(sets):
+                        raise ValueError("Incompatible signature")
+                    # Recurse
+                    queue.extend(zip(sig, sets))
+                else:
+                    # If we get here then we have something like sig = (x, y) and
+                    # base_set = {(1, 2), (3, 4)}. For now we give up.
+                    return None
+
+            return symsetmap
+
+        def get_equations(expr, candidate):
+            '''Find the equations relating symbols in expr and candidate.'''
+            queue = [(expr, candidate)]
+            for e, c in queue:
+                if not isinstance(e, Tuple):
+                    yield Eq(e, c)
+                elif not isinstance(c, Tuple) or len(e) != len(c):
+                    yield False
+                    return
+                else:
+                    queue.extend(zip(e, c))
+
+        # Get the basic objects together:
+        other = _sympify(other)
+        expr = self.lamda.expr
+        sig = self.lamda.signature
+        variables = self.lamda.variables
+        base_sets = self.base_sets
+
+        # Use dummy symbols for ImageSet parameters so they don't match
+        # anything in other
+        rep = {v: Dummy(v.name) for v in variables}
+        variables = [v.subs(rep) for v in variables]
+        sig = sig.subs(rep)
+        expr = expr.subs(rep)
+
+        # Map the parts of other to those in the Lambda expr
+        equations = []
+        for eq in get_equations(expr, other):
+            # Unsatisfiable equation?
+            if eq is False:
+                return S.false
+            equations.append(eq)
+
+        # Map the symbols in the signature to the corresponding domains
+        symsetmap = get_symsetmap(sig, base_sets)
+        if symsetmap is None:
+            # Can't factor the base sets to a ProductSet
+            return None
+
+        # Which of the variables in the Lambda signature need to be solved for?
+        symss = (eq.free_symbols for eq in equations)
+        variables = set(variables) & reduce(set.union, symss, set())
+
+        # Use internal multivariate solveset
+        variables = tuple(variables)
+        base_sets = [symsetmap[v] for v in variables]
+        solnset = _solveset_multi(equations, variables, base_sets)
+        if solnset is None:
+            return None
+        return tfn[fuzzy_not(solnset.is_empty)]
+
+    @property
+    def is_iterable(self):
+        return all(s.is_iterable for s in self.base_sets)
+
+    def doit(self, **hints):
+        from sympy.sets.setexpr import SetExpr
+        f = self.lamda
+        sig = f.signature
+        if len(sig) == 1 and sig[0].is_symbol and isinstance(f.expr, Expr):
+            base_set = self.base_sets[0]
+            return SetExpr(base_set)._eval_func(f).set
+        if all(s.is_FiniteSet for s in self.base_sets):
+            return FiniteSet(*(f(*a) for a in product(*self.base_sets)))
+        return self
+
+    def _kind(self):
+        return SetKind(self.lamda.expr.kind)
+
+
+class Range(Set):
+    """
+    Represents a range of integers. Can be called as ``Range(stop)``,
+    ``Range(start, stop)``, or ``Range(start, stop, step)``; when ``step`` is
+    not given it defaults to 1.
+
+    ``Range(stop)`` is the same as ``Range(0, stop, 1)`` and the stop value
+    (just as for Python ranges) is not included in the Range values.
+
+        >>> from sympy import Range
+        >>> list(Range(3))
+        [0, 1, 2]
+
+    The step can also be negative:
+
+        >>> list(Range(10, 0, -2))
+        [10, 8, 6, 4, 2]
+
+    The stop value is made canonical so equivalent ranges always
+    have the same args:
+
+        >>> Range(0, 10, 3)
+        Range(0, 12, 3)
+
+    Infinite ranges are allowed. ``oo`` and ``-oo`` are never included in the
+    set (``Range`` is always a subset of ``Integers``). If the starting point
+    is infinite, then the final value is ``stop - step``. To iterate such a
+    range, it needs to be reversed:
+
+        >>> from sympy import oo
+        >>> r = Range(-oo, 1)
+        >>> r[-1]
+        0
+        >>> next(iter(r))
+        Traceback (most recent call last):
+        ...
+        TypeError: Cannot iterate over Range with infinite start
+        >>> next(iter(r.reversed))
+        0
+
+    Although ``Range`` is a :class:`Set` (and supports the normal set
+    operations) it maintains the order of the elements and can
+    be used in contexts where ``range`` would be used.
+
+        >>> from sympy import Interval
+        >>> Range(0, 10, 2).intersect(Interval(3, 7))
+        Range(4, 8, 2)
+        >>> list(_)
+        [4, 6]
+
+    Although slicing of a Range will always return a Range -- possibly
+    empty -- an empty set will be returned from any intersection that
+    is empty:
+
+        >>> Range(3)[:0]
+        Range(0, 0, 1)
+        >>> Range(3).intersect(Interval(4, oo))
+        EmptySet
+        >>> Range(3).intersect(Range(4, oo))
+        EmptySet
+
+    Range will accept symbolic arguments but has very limited support
+    for doing anything other than displaying the Range:
+
+        >>> from sympy import Symbol, pprint
+        >>> from sympy.abc import i, j, k
+        >>> Range(i, j, k).start
+        i
+        >>> Range(i, j, k).inf
+        Traceback (most recent call last):
+        ...
+        ValueError: invalid method for symbolic range
+
+    Better success will be had when using integer symbols:
+
+        >>> n = Symbol('n', integer=True)
+        >>> r = Range(n, n + 20, 3)
+        >>> r.inf
+        n
+        >>> pprint(r)
+        {n, n + 3, ..., n + 18}
+    """
+
+    def __new__(cls, *args):
+        if len(args) == 1:
+            if isinstance(args[0], range):
+                raise TypeError(
+                    'use sympify(%s) to convert range to Range' % args[0])
+
+        # expand range
+        slc = slice(*args)
+
+        if slc.step == 0:
+            raise ValueError("step cannot be 0")
+
+        start, stop, step = slc.start or 0, slc.stop, slc.step or 1
+        try:
+            ok = []
+            for w in (start, stop, step):
+                w = sympify(w)
+                if w in [S.NegativeInfinity, S.Infinity] or (
+                        w.has(Symbol) and w.is_integer != False):
+                    ok.append(w)
+                elif not w.is_Integer:
+                    if w.is_infinite:
+                        raise ValueError('infinite symbols not allowed')
+                    raise ValueError
+                else:
+                    ok.append(w)
+        except ValueError:
+            raise ValueError(filldedent('''
+    Finite arguments to Range must be integers; `imageset` can define
+    other cases, e.g. use `imageset(i, i/10, Range(3))` to give
+    [0, 1/10, 1/5].'''))
+        start, stop, step = ok
+
+        null = False
+        if any(i.has(Symbol) for i in (start, stop, step)):
+            dif = stop - start
+            n = dif/step
+            if n.is_Rational:
+                if dif == 0:
+                    null = True
+                else:  # (x, x + 5, 2) or (x, 3*x, x)
+                    n = floor(n)
+                    end = start + n*step
+                    if dif.is_Rational:  # (x, x + 5, 2)
+                        if (end - stop).is_negative:
+                            end += step
+                    else:  # (x, 3*x, x)
+                        if (end/stop - 1).is_negative:
+                            end += step
+            elif n.is_extended_negative:
+                null = True
+            else:
+                end = stop  # other methods like sup and reversed must fail
+        elif start.is_infinite:
+            span = step*(stop - start)
+            if span is S.NaN or span <= 0:
+                null = True
+            elif step.is_Integer and stop.is_infinite and abs(step) != 1:
+                raise ValueError(filldedent('''
+                    Step size must be %s in this case.''' % (1 if step > 0 else -1)))
+            else:
+                end = stop
+        else:
+            oostep = step.is_infinite
+            if oostep:
+                step = S.One if step > 0 else S.NegativeOne
+            n = ceiling((stop - start)/step)
+            if n <= 0:
+                null = True
+            elif oostep:
+                step = S.One  # make it canonical
+                end = start + step
+            else:
+                end = start + n*step
+        if null:
+            start = end = S.Zero
+            step = S.One
+        return Basic.__new__(cls, start, end, step)
+
+    start = property(lambda self: self.args[0])
+    stop = property(lambda self: self.args[1])
+    step = property(lambda self: self.args[2])
+
+    @property
+    def reversed(self):
+        """Return an equivalent Range in the opposite order.
+
+        Examples
+        ========
+
+        >>> from sympy import Range
+        >>> Range(10).reversed
+        Range(9, -1, -1)
+        """
+        if self.has(Symbol):
+            n = (self.stop - self.start)/self.step
+            if not n.is_extended_positive or not all(
+                    i.is_integer or i.is_infinite for i in self.args):
+                raise ValueError('invalid method for symbolic range')
+        if self.start == self.stop:
+            return self
+        return self.func(
+            self.stop - self.step, self.start - self.step, -self.step)
+
+    def _kind(self):
+        return SetKind(NumberKind)
+
+    def _contains(self, other):
+        if self.start == self.stop:
+            return S.false
+        if other.is_infinite:
+            return S.false
+        if not other.is_integer:
+            return tfn[other.is_integer]
+        if self.has(Symbol):
+            n = (self.stop - self.start)/self.step
+            if not n.is_extended_positive or not all(
+                    i.is_integer or i.is_infinite for i in self.args):
+                return
+        else:
+            n = self.size
+        if self.start.is_finite:
+            ref = self.start
+        elif self.stop.is_finite:
+            ref = self.stop
+        else:  # both infinite; step is +/- 1 (enforced by __new__)
+            return S.true
+        if n == 1:
+            return Eq(other, self[0])
+        res = (ref - other) % self.step
+        if res == S.Zero:
+            if self.has(Symbol):
+                d = Dummy('i')
+                return self.as_relational(d).subs(d, other)
+            return And(other >= self.inf, other <= self.sup)
+        elif res.is_Integer:  # off sequence
+            return S.false
+        else:  # symbolic/unsimplified residue modulo step
+            return None
+
+    def __iter__(self):
+        n = self.size  # validate
+        if not (n.has(S.Infinity) or n.has(S.NegativeInfinity) or n.is_Integer):
+            raise TypeError("Cannot iterate over symbolic Range")
+        if self.start in [S.NegativeInfinity, S.Infinity]:
+            raise TypeError("Cannot iterate over Range with infinite start")
+        elif self.start != self.stop:
+            i = self.start
+            if n.is_infinite:
+                while True:
+                    yield i
+                    i += self.step
+            else:
+                for _ in range(n):
+                    yield i
+                    i += self.step
+
+    @property
+    def is_iterable(self):
+        # Check that size can be determined, used by __iter__
+        dif = self.stop - self.start
+        n = dif/self.step
+        if not (n.has(S.Infinity) or n.has(S.NegativeInfinity) or n.is_Integer):
+            return False
+        if self.start in [S.NegativeInfinity, S.Infinity]:
+            return False
+        if not (n.is_extended_nonnegative and all(i.is_integer for i in self.args)):
+            return False
+        return True
+
+    def __len__(self):
+        rv = self.size
+        if rv is S.Infinity:
+            raise ValueError('Use .size to get the length of an infinite Range')
+        return int(rv)
+
+    @property
+    def size(self):
+        if self.start == self.stop:
+            return S.Zero
+        dif = self.stop - self.start
+        n = dif/self.step
+        if n.is_infinite:
+            return S.Infinity
+        if  n.is_extended_nonnegative and all(i.is_integer for i in self.args):
+            return abs(floor(n))
+        raise ValueError('Invalid method for symbolic Range')
+
+    @property
+    def is_finite_set(self):
+        if self.start.is_integer and self.stop.is_integer:
+            return True
+        return self.size.is_finite
+
+    @property
+    def is_empty(self):
+        try:
+            return self.size.is_zero
+        except ValueError:
+            return None
+
+    def __bool__(self):
+        # this only distinguishes between definite null range
+        # and non-null/unknown null; getting True doesn't mean
+        # that it actually is not null
+        b = is_eq(self.start, self.stop)
+        if b is None:
+            raise ValueError('cannot tell if Range is null or not')
+        return not bool(b)
+
+    def __getitem__(self, i):
+        ooslice = "cannot slice from the end with an infinite value"
+        zerostep = "slice step cannot be zero"
+        infinite = "slicing not possible on range with infinite start"
+        # if we had to take every other element in the following
+        # oo, ..., 6, 4, 2, 0
+        # we might get oo, ..., 4, 0 or oo, ..., 6, 2
+        ambiguous = "cannot unambiguously re-stride from the end " + \
+            "with an infinite value"
+        if isinstance(i, slice):
+            if self.size.is_finite:  # validates, too
+                if self.start == self.stop:
+                    return Range(0)
+                start, stop, step = i.indices(self.size)
+                n = ceiling((stop - start)/step)
+                if n <= 0:
+                    return Range(0)
+                canonical_stop = start + n*step
+                end = canonical_stop - step
+                ss = step*self.step
+                return Range(self[start], self[end] + ss, ss)
+            else:  # infinite Range
+                start = i.start
+                stop = i.stop
+                if i.step == 0:
+                    raise ValueError(zerostep)
+                step = i.step or 1
+                ss = step*self.step
+                #---------------------
+                # handle infinite Range
+                #   i.e. Range(-oo, oo) or Range(oo, -oo, -1)
+                # --------------------
+                if self.start.is_infinite and self.stop.is_infinite:
+                    raise ValueError(infinite)
+                #---------------------
+                # handle infinite on right
+                #   e.g. Range(0, oo) or Range(0, -oo, -1)
+                # --------------------
+                if self.stop.is_infinite:
+                    # start and stop are not interdependent --
+                    # they only depend on step --so we use the
+                    # equivalent reversed values
+                    return self.reversed[
+                        stop if stop is None else -stop + 1:
+                        start if start is None else -start:
+                        step].reversed
+                #---------------------
+                # handle infinite on the left
+                #   e.g. Range(oo, 0, -1) or Range(-oo, 0)
+                # --------------------
+                # consider combinations of
+                # start/stop {== None, < 0, == 0, > 0} and
+                # step {< 0, > 0}
+                if start is None:
+                    if stop is None:
+                        if step < 0:
+                            return Range(self[-1], self.start, ss)
+                        elif step > 1:
+                            raise ValueError(ambiguous)
+                        else:  # == 1
+                            return self
+                    elif stop < 0:
+                        if step < 0:
+                            return Range(self[-1], self[stop], ss)
+                        else:  # > 0
+                            return Range(self.start, self[stop], ss)
+                    elif stop == 0:
+                        if step > 0:
+                            return Range(0)
+                        else:  # < 0
+                            raise ValueError(ooslice)
+                    elif stop == 1:
+                        if step > 0:
+                            raise ValueError(ooslice)  # infinite singleton
+                        else:  # < 0
+                            raise ValueError(ooslice)
+                    else:  # > 1
+                        raise ValueError(ooslice)
+                elif start < 0:
+                    if stop is None:
+                        if step < 0:
+                            return Range(self[start], self.start, ss)
+                        else:  # > 0
+                            return Range(self[start], self.stop, ss)
+                    elif stop < 0:
+                        return Range(self[start], self[stop], ss)
+                    elif stop == 0:
+                        if step < 0:
+                            raise ValueError(ooslice)
+                        else:  # > 0
+                            return Range(0)
+                    elif stop > 0:
+                        raise ValueError(ooslice)
+                elif start == 0:
+                    if stop is None:
+                        if step < 0:
+                            raise ValueError(ooslice)  # infinite singleton
+                        elif step > 1:
+                            raise ValueError(ambiguous)
+                        else:  # == 1
+                            return self
+                    elif stop < 0:
+                        if step > 1:
+                            raise ValueError(ambiguous)
+                        elif step == 1:
+                            return Range(self.start, self[stop], ss)
+                        else:  # < 0
+                            return Range(0)
+                    else:  # >= 0
+                        raise ValueError(ooslice)
+                elif start > 0:
+                    raise ValueError(ooslice)
+        else:
+            if self.start == self.stop:
+                raise IndexError('Range index out of range')
+            if not (all(i.is_integer or i.is_infinite
+                    for i in self.args) and ((self.stop - self.start)/
+                    self.step).is_extended_positive):
+                raise ValueError('Invalid method for symbolic Range')
+            if i == 0:
+                if self.start.is_infinite:
+                    raise ValueError(ooslice)
+                return self.start
+            if i == -1:
+                if self.stop.is_infinite:
+                    raise ValueError(ooslice)
+                return self.stop - self.step
+            n = self.size  # must be known for any other index
+            rv = (self.stop if i < 0 else self.start) + i*self.step
+            if rv.is_infinite:
+                raise ValueError(ooslice)
+            val = (rv - self.start)/self.step
+            rel = fuzzy_or([val.is_infinite,
+                            fuzzy_and([val.is_nonnegative, (n-val).is_nonnegative])])
+            if rel:
+                return rv
+            if rel is None:
+                raise ValueError('Invalid method for symbolic Range')
+            raise IndexError("Range index out of range")
+
+    @property
+    def _inf(self):
+        if not self:
+            return S.EmptySet.inf
+        if self.has(Symbol):
+            if all(i.is_integer or i.is_infinite for i in self.args):
+                dif = self.stop - self.start
+                if self.step.is_positive and dif.is_positive:
+                    return self.start
+                elif self.step.is_negative and dif.is_negative:
+                    return self.stop - self.step
+            raise ValueError('invalid method for symbolic range')
+        if self.step > 0:
+            return self.start
+        else:
+            return self.stop - self.step
+
+    @property
+    def _sup(self):
+        if not self:
+            return S.EmptySet.sup
+        if self.has(Symbol):
+            if all(i.is_integer or i.is_infinite for i in self.args):
+                dif = self.stop - self.start
+                if self.step.is_positive and dif.is_positive:
+                    return self.stop - self.step
+                elif self.step.is_negative and dif.is_negative:
+                    return self.start
+            raise ValueError('invalid method for symbolic range')
+        if self.step > 0:
+            return self.stop - self.step
+        else:
+            return self.start
+
+    @property
+    def _boundary(self):
+        return self
+
+    def as_relational(self, x):
+        """Rewrite a Range in terms of equalities and logic operators. """
+        if self.start.is_infinite:
+            assert not self.stop.is_infinite  # by instantiation
+            a = self.reversed.start
+        else:
+            a = self.start
+        step = self.step
+        in_seq = Eq(Mod(x - a, step), 0)
+        ints = And(Eq(Mod(a, 1), 0), Eq(Mod(step, 1), 0))
+        n = (self.stop - self.start)/self.step
+        if n == 0:
+            return S.EmptySet.as_relational(x)
+        if n == 1:
+            return And(Eq(x, a), ints)
+        try:
+            a, b = self.inf, self.sup
+        except ValueError:
+            a = None
+        if a is not None:
+            range_cond = And(
+                x > a if a.is_infinite else x >= a,
+                x < b if b.is_infinite else x <= b)
+        else:
+            a, b = self.start, self.stop - self.step
+            range_cond = Or(
+                And(self.step >= 1, x > a if a.is_infinite else x >= a,
+                x < b if b.is_infinite else x <= b),
+                And(self.step <= -1, x < a if a.is_infinite else x <= a,
+                x > b if b.is_infinite else x >= b))
+        return And(in_seq, ints, range_cond)
+
+
+_sympy_converter[range] = lambda r: Range(r.start, r.stop, r.step)
+
+def normalize_theta_set(theta):
+    r"""
+    Normalize a Real Set `theta` in the interval `[0, 2\pi)`. It returns
+    a normalized value of theta in the Set. For Interval, a maximum of
+    one cycle $[0, 2\pi]$, is returned i.e. for theta equal to $[0, 10\pi]$,
+    returned normalized value would be $[0, 2\pi)$. As of now intervals
+    with end points as non-multiples of ``pi`` is not supported.
+
+    Raises
+    ======
+
+    NotImplementedError
+        The algorithms for Normalizing theta Set are not yet
+        implemented.
+    ValueError
+        The input is not valid, i.e. the input is not a real set.
+    RuntimeError
+        It is a bug, please report to the github issue tracker.
+
+    Examples
+    ========
+
+    >>> from sympy.sets.fancysets import normalize_theta_set
+    >>> from sympy import Interval, FiniteSet, pi
+    >>> normalize_theta_set(Interval(9*pi/2, 5*pi))
+    Interval(pi/2, pi)
+    >>> normalize_theta_set(Interval(-3*pi/2, pi/2))
+    Interval.Ropen(0, 2*pi)
+    >>> normalize_theta_set(Interval(-pi/2, pi/2))
+    Union(Interval(0, pi/2), Interval.Ropen(3*pi/2, 2*pi))
+    >>> normalize_theta_set(Interval(-4*pi, 3*pi))
+    Interval.Ropen(0, 2*pi)
+    >>> normalize_theta_set(Interval(-3*pi/2, -pi/2))
+    Interval(pi/2, 3*pi/2)
+    >>> normalize_theta_set(FiniteSet(0, pi, 3*pi))
+    {0, pi}
+
+    """
+    from sympy.functions.elementary.trigonometric import _pi_coeff
+
+    if theta.is_Interval:
+        interval_len = theta.measure
+        # one complete circle
+        if interval_len >= 2*S.Pi:
+            if interval_len == 2*S.Pi and theta.left_open and theta.right_open:
+                k = _pi_coeff(theta.start)
+                return Union(Interval(0, k*S.Pi, False, True),
+                        Interval(k*S.Pi, 2*S.Pi, True, True))
+            return Interval(0, 2*S.Pi, False, True)
+
+        k_start, k_end = _pi_coeff(theta.start), _pi_coeff(theta.end)
+
+        if k_start is None or k_end is None:
+            raise NotImplementedError("Normalizing theta without pi as coefficient is "
+                                    "not yet implemented")
+        new_start = k_start*S.Pi
+        new_end = k_end*S.Pi
+
+        if new_start > new_end:
+            return Union(Interval(S.Zero, new_end, False, theta.right_open),
+                         Interval(new_start, 2*S.Pi, theta.left_open, True))
+        else:
+            return Interval(new_start, new_end, theta.left_open, theta.right_open)
+
+    elif theta.is_FiniteSet:
+        new_theta = []
+        for element in theta:
+            k = _pi_coeff(element)
+            if k is None:
+                raise NotImplementedError('Normalizing theta without pi as '
+                                          'coefficient, is not Implemented.')
+            else:
+                new_theta.append(k*S.Pi)
+        return FiniteSet(*new_theta)
+
+    elif theta.is_Union:
+        return Union(*[normalize_theta_set(interval) for interval in theta.args])
+
+    elif theta.is_subset(S.Reals):
+        raise NotImplementedError("Normalizing theta when, it is of type %s is not "
+                                  "implemented" % type(theta))
+    else:
+        raise ValueError(" %s is not a real set" % (theta))
+
+
+class ComplexRegion(Set):
+    r"""
+    Represents the Set of all Complex Numbers. It can represent a
+    region of Complex Plane in both the standard forms Polar and
+    Rectangular coordinates.
+
+    * Polar Form
+      Input is in the form of the ProductSet or Union of ProductSets
+      of the intervals of ``r`` and ``theta``, and use the flag ``polar=True``.
+
+      .. math:: Z = \{z \in \mathbb{C} \mid z = r\times (\cos(\theta) + I\sin(\theta)), r \in [\texttt{r}], \theta \in [\texttt{theta}]\}
+
+    * Rectangular Form
+      Input is in the form of the ProductSet or Union of ProductSets
+      of interval of x and y, the real and imaginary parts of the Complex numbers in a plane.
+      Default input type is in rectangular form.
+
+    .. math:: Z = \{z \in \mathbb{C} \mid z = x + Iy, x \in [\operatorname{re}(z)], y \in [\operatorname{im}(z)]\}
+
+    Examples
+    ========
+
+    >>> from sympy import ComplexRegion, Interval, S, I, Union
+    >>> a = Interval(2, 3)
+    >>> b = Interval(4, 6)
+    >>> c1 = ComplexRegion(a*b)  # Rectangular Form
+    >>> c1
+    CartesianComplexRegion(ProductSet(Interval(2, 3), Interval(4, 6)))
+
+    * c1 represents the rectangular region in complex plane
+      surrounded by the coordinates (2, 4), (3, 4), (3, 6) and
+      (2, 6), of the four vertices.
+
+    >>> c = Interval(1, 8)
+    >>> c2 = ComplexRegion(Union(a*b, b*c))
+    >>> c2
+    CartesianComplexRegion(Union(ProductSet(Interval(2, 3), Interval(4, 6)), ProductSet(Interval(4, 6), Interval(1, 8))))
+
+    * c2 represents the Union of two rectangular regions in complex
+      plane. One of them surrounded by the coordinates of c1 and
+      other surrounded by the coordinates (4, 1), (6, 1), (6, 8) and
+      (4, 8).
+
+    >>> 2.5 + 4.5*I in c1
+    True
+    >>> 2.5 + 6.5*I in c1
+    False
+
+    >>> r = Interval(0, 1)
+    >>> theta = Interval(0, 2*S.Pi)
+    >>> c2 = ComplexRegion(r*theta, polar=True)  # Polar Form
+    >>> c2  # unit Disk
+    PolarComplexRegion(ProductSet(Interval(0, 1), Interval.Ropen(0, 2*pi)))
+
+    * c2 represents the region in complex plane inside the
+      Unit Disk centered at the origin.
+
+    >>> 0.5 + 0.5*I in c2
+    True
+    >>> 1 + 2*I in c2
+    False
+
+    >>> unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
+    >>> upper_half_unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True)
+    >>> intersection = unit_disk.intersect(upper_half_unit_disk)
+    >>> intersection
+    PolarComplexRegion(ProductSet(Interval(0, 1), Interval(0, pi)))
+    >>> intersection == upper_half_unit_disk
+    True
+
+    See Also
+    ========
+
+    CartesianComplexRegion
+    PolarComplexRegion
+    Complexes
+
+    """
+    is_ComplexRegion = True
+
+    def __new__(cls, sets, polar=False):
+        if polar is False:
+            return CartesianComplexRegion(sets)
+        elif polar is True:
+            return PolarComplexRegion(sets)
+        else:
+            raise ValueError("polar should be either True or False")
+
+    @property
+    def sets(self):
+        """
+        Return raw input sets to the self.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval, ComplexRegion, Union
+        >>> a = Interval(2, 3)
+        >>> b = Interval(4, 5)
+        >>> c = Interval(1, 7)
+        >>> C1 = ComplexRegion(a*b)
+        >>> C1.sets
+        ProductSet(Interval(2, 3), Interval(4, 5))
+        >>> C2 = ComplexRegion(Union(a*b, b*c))
+        >>> C2.sets
+        Union(ProductSet(Interval(2, 3), Interval(4, 5)), ProductSet(Interval(4, 5), Interval(1, 7)))
+
+        """
+        return self.args[0]
+
+    @property
+    def psets(self):
+        """
+        Return a tuple of sets (ProductSets) input of the self.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval, ComplexRegion, Union
+        >>> a = Interval(2, 3)
+        >>> b = Interval(4, 5)
+        >>> c = Interval(1, 7)
+        >>> C1 = ComplexRegion(a*b)
+        >>> C1.psets
+        (ProductSet(Interval(2, 3), Interval(4, 5)),)
+        >>> C2 = ComplexRegion(Union(a*b, b*c))
+        >>> C2.psets
+        (ProductSet(Interval(2, 3), Interval(4, 5)), ProductSet(Interval(4, 5), Interval(1, 7)))
+
+        """
+        if self.sets.is_ProductSet:
+            psets = ()
+            psets = psets + (self.sets, )
+        else:
+            psets = self.sets.args
+        return psets
+
+    @property
+    def a_interval(self):
+        """
+        Return the union of intervals of `x` when, self is in
+        rectangular form, or the union of intervals of `r` when
+        self is in polar form.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval, ComplexRegion, Union
+        >>> a = Interval(2, 3)
+        >>> b = Interval(4, 5)
+        >>> c = Interval(1, 7)
+        >>> C1 = ComplexRegion(a*b)
+        >>> C1.a_interval
+        Interval(2, 3)
+        >>> C2 = ComplexRegion(Union(a*b, b*c))
+        >>> C2.a_interval
+        Union(Interval(2, 3), Interval(4, 5))
+
+        """
+        a_interval = []
+        for element in self.psets:
+            a_interval.append(element.args[0])
+
+        a_interval = Union(*a_interval)
+        return a_interval
+
+    @property
+    def b_interval(self):
+        """
+        Return the union of intervals of `y` when, self is in
+        rectangular form, or the union of intervals of `theta`
+        when self is in polar form.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval, ComplexRegion, Union
+        >>> a = Interval(2, 3)
+        >>> b = Interval(4, 5)
+        >>> c = Interval(1, 7)
+        >>> C1 = ComplexRegion(a*b)
+        >>> C1.b_interval
+        Interval(4, 5)
+        >>> C2 = ComplexRegion(Union(a*b, b*c))
+        >>> C2.b_interval
+        Interval(1, 7)
+
+        """
+        b_interval = []
+        for element in self.psets:
+            b_interval.append(element.args[1])
+
+        b_interval = Union(*b_interval)
+        return b_interval
+
+    @property
+    def _measure(self):
+        """
+        The measure of self.sets.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval, ComplexRegion, S
+        >>> a, b = Interval(2, 5), Interval(4, 8)
+        >>> c = Interval(0, 2*S.Pi)
+        >>> c1 = ComplexRegion(a*b)
+        >>> c1.measure
+        12
+        >>> c2 = ComplexRegion(a*c, polar=True)
+        >>> c2.measure
+        6*pi
+
+        """
+        return self.sets._measure
+
+    def _kind(self):
+        return self.args[0].kind
+
+    @classmethod
+    def from_real(cls, sets):
+        """
+        Converts given subset of real numbers to a complex region.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval, ComplexRegion
+        >>> unit = Interval(0,1)
+        >>> ComplexRegion.from_real(unit)
+        CartesianComplexRegion(ProductSet(Interval(0, 1), {0}))
+
+        """
+        if not sets.is_subset(S.Reals):
+            raise ValueError("sets must be a subset of the real line")
+
+        return CartesianComplexRegion(sets * FiniteSet(0))
+
+    def _contains(self, other):
+        from sympy.functions import arg, Abs
+
+        isTuple = isinstance(other, Tuple)
+        if isTuple and len(other) != 2:
+            raise ValueError('expecting Tuple of length 2')
+
+        # If the other is not an Expression, and neither a Tuple
+        if not isinstance(other, (Expr, Tuple)):
+            return S.false
+
+        # self in rectangular form
+        if not self.polar:
+            re, im = other if isTuple else other.as_real_imag()
+            return tfn[fuzzy_or(fuzzy_and([
+                pset.args[0]._contains(re),
+                pset.args[1]._contains(im)])
+                for pset in self.psets)]
+
+        # self in polar form
+        elif self.polar:
+            if other.is_zero:
+                # ignore undefined complex argument
+                return tfn[fuzzy_or(pset.args[0]._contains(S.Zero)
+                    for pset in self.psets)]
+            if isTuple:
+                r, theta = other
+            else:
+                r, theta = Abs(other), arg(other)
+            if theta.is_real and theta.is_number:
+                # angles in psets are normalized to [0, 2pi)
+                theta %= 2*S.Pi
+                return tfn[fuzzy_or(fuzzy_and([
+                    pset.args[0]._contains(r),
+                    pset.args[1]._contains(theta)])
+                    for pset in self.psets)]
+
+
+class CartesianComplexRegion(ComplexRegion):
+    r"""
+    Set representing a square region of the complex plane.
+
+    .. math:: Z = \{z \in \mathbb{C} \mid z = x + Iy, x \in [\operatorname{re}(z)], y \in [\operatorname{im}(z)]\}
+
+    Examples
+    ========
+
+    >>> from sympy import ComplexRegion, I, Interval
+    >>> region = ComplexRegion(Interval(1, 3) * Interval(4, 6))
+    >>> 2 + 5*I in region
+    True
+    >>> 5*I in region
+    False
+
+    See also
+    ========
+
+    ComplexRegion
+    PolarComplexRegion
+    Complexes
+    """
+
+    polar = False
+    variables = symbols('x, y', cls=Dummy)
+
+    def __new__(cls, sets):
+
+        if sets == S.Reals*S.Reals:
+            return S.Complexes
+
+        if all(_a.is_FiniteSet for _a in sets.args) and (len(sets.args) == 2):
+
+            # ** ProductSet of FiniteSets in the Complex Plane. **
+            # For Cases like ComplexRegion({2, 4}*{3}), It
+            # would return {2 + 3*I, 4 + 3*I}
+
+            # FIXME: This should probably be handled with something like:
+            # return ImageSet(Lambda((x, y), x+I*y), sets).rewrite(FiniteSet)
+            complex_num = []
+            for x in sets.args[0]:
+                for y in sets.args[1]:
+                    complex_num.append(x + S.ImaginaryUnit*y)
+            return FiniteSet(*complex_num)
+        else:
+            return Set.__new__(cls, sets)
+
+    @property
+    def expr(self):
+        x, y = self.variables
+        return x + S.ImaginaryUnit*y
+
+
+class PolarComplexRegion(ComplexRegion):
+    r"""
+    Set representing a polar region of the complex plane.
+
+    .. math:: Z = \{z \in \mathbb{C} \mid z = r\times (\cos(\theta) + I\sin(\theta)), r \in [\texttt{r}], \theta \in [\texttt{theta}]\}
+
+    Examples
+    ========
+
+    >>> from sympy import ComplexRegion, Interval, oo, pi, I
+    >>> rset = Interval(0, oo)
+    >>> thetaset = Interval(0, pi)
+    >>> upper_half_plane = ComplexRegion(rset * thetaset, polar=True)
+    >>> 1 + I in upper_half_plane
+    True
+    >>> 1 - I in upper_half_plane
+    False
+
+    See also
+    ========
+
+    ComplexRegion
+    CartesianComplexRegion
+    Complexes
+
+    """
+
+    polar = True
+    variables = symbols('r, theta', cls=Dummy)
+
+    def __new__(cls, sets):
+
+        new_sets = []
+        # sets is Union of ProductSets
+        if not sets.is_ProductSet:
+            for k in sets.args:
+                new_sets.append(k)
+        # sets is ProductSets
+        else:
+            new_sets.append(sets)
+        # Normalize input theta
+        for k, v in enumerate(new_sets):
+            new_sets[k] = ProductSet(v.args[0],
+                                     normalize_theta_set(v.args[1]))
+        sets = Union(*new_sets)
+        return Set.__new__(cls, sets)
+
+    @property
+    def expr(self):
+        r, theta = self.variables
+        return r*(cos(theta) + S.ImaginaryUnit*sin(theta))
+
+
+class Complexes(CartesianComplexRegion, metaclass=Singleton):
+    """
+    The :class:`Set` of all complex numbers
+
+    Examples
+    ========
+
+    >>> from sympy import S, I
+    >>> S.Complexes
+    Complexes
+    >>> 1 + I in S.Complexes
+    True
+
+    See also
+    ========
+
+    Reals
+    ComplexRegion
+
+    """
+
+    is_empty = False
+    is_finite_set = False
+
+    # Override property from superclass since Complexes has no args
+    @property
+    def sets(self):
+        return ProductSet(S.Reals, S.Reals)
+
+    def __new__(cls):
+        return Set.__new__(cls)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..809f8b2690678a1177dcb7457997999193f5a2d1
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/comparison.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/comparison.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6e949c5a2d2962367ea3e483a37869e3d2dfcb95
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/comparison.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/intersection.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/intersection.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f99ce9fceeb35bb1da35af6db51686b7e31a3aa6
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/intersection.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/union.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/union.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..43993ae4e7c00c8cb5e45a018cac57beb7035b0a
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/union.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/add.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/add.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c07b25ed19d21febffd6b23a92b34b787179f44
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/add.py
@@ -0,0 +1,79 @@
+from sympy.core.numbers import oo, Infinity, NegativeInfinity
+from sympy.core.singleton import S
+from sympy.core import Basic, Expr
+from sympy.multipledispatch import Dispatcher
+from sympy.sets import Interval, FiniteSet
+
+
+
+# XXX: The functions in this module are clearly not tested and are broken in a
+# number of ways.
+
+_set_add = Dispatcher('_set_add')
+_set_sub = Dispatcher('_set_sub')
+
+
+@_set_add.register(Basic, Basic)
+def _(x, y):
+    return None
+
+
+@_set_add.register(Expr, Expr)
+def _(x, y):
+    return x+y
+
+
+@_set_add.register(Interval, Interval)
+def _(x, y):
+    """
+    Additions in interval arithmetic
+    https://en.wikipedia.org/wiki/Interval_arithmetic
+    """
+    return Interval(x.start + y.start, x.end + y.end,
+                    x.left_open or y.left_open, x.right_open or y.right_open)
+
+
+@_set_add.register(Interval, Infinity)
+def _(x, y):
+    if x.start is S.NegativeInfinity:
+        return Interval(-oo, oo)
+    return FiniteSet({S.Infinity})
+
+@_set_add.register(Interval, NegativeInfinity)
+def _(x, y):
+    if x.end is S.Infinity:
+        return Interval(-oo, oo)
+    return FiniteSet({S.NegativeInfinity})
+
+
+@_set_sub.register(Basic, Basic)
+def _(x, y):
+    return None
+
+
+@_set_sub.register(Expr, Expr)
+def _(x, y):
+    return x-y
+
+
+@_set_sub.register(Interval, Interval)
+def _(x, y):
+    """
+    Subtractions in interval arithmetic
+    https://en.wikipedia.org/wiki/Interval_arithmetic
+    """
+    return Interval(x.start - y.end, x.end - y.start,
+                    x.left_open or y.right_open, x.right_open or y.left_open)
+
+
+@_set_sub.register(Interval, Infinity)
+def _(x, y):
+    if x.start is S.NegativeInfinity:
+        return Interval(-oo, oo)
+    return FiniteSet(-oo)
+
+@_set_sub.register(Interval, NegativeInfinity)
+def _(x, y):
+    if x.start is S.NegativeInfinity:
+        return Interval(-oo, oo)
+    return FiniteSet(-oo)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/comparison.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/comparison.py
new file mode 100644
index 0000000000000000000000000000000000000000..b64d1a2a22e15d09f6f10fb4fef730163d468d45
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/comparison.py
@@ -0,0 +1,53 @@
+from sympy.core.relational import Eq, is_eq
+from sympy.core.basic import Basic
+from sympy.core.logic import fuzzy_and, fuzzy_bool
+from sympy.logic.boolalg import And
+from sympy.multipledispatch import dispatch
+from sympy.sets.sets import tfn, ProductSet, Interval, FiniteSet, Set
+
+
+@dispatch(Interval, FiniteSet) # type:ignore
+def _eval_is_eq(lhs, rhs): # noqa: F811
+    return False
+
+
+@dispatch(FiniteSet, Interval) # type:ignore
+def _eval_is_eq(lhs, rhs): # noqa: F811
+    return False
+
+
+@dispatch(Interval, Interval) # type:ignore
+def _eval_is_eq(lhs, rhs): # noqa: F811
+    return And(Eq(lhs.left, rhs.left),
+               Eq(lhs.right, rhs.right),
+               lhs.left_open == rhs.left_open,
+               lhs.right_open == rhs.right_open)
+
+@dispatch(FiniteSet, FiniteSet) # type:ignore
+def _eval_is_eq(lhs, rhs): # noqa: F811
+    def all_in_both():
+        s_set = set(lhs.args)
+        o_set = set(rhs.args)
+        yield fuzzy_and(lhs._contains(e) for e in o_set - s_set)
+        yield fuzzy_and(rhs._contains(e) for e in s_set - o_set)
+
+    return tfn[fuzzy_and(all_in_both())]
+
+
+@dispatch(ProductSet, ProductSet) # type:ignore
+def _eval_is_eq(lhs, rhs): # noqa: F811
+    if len(lhs.sets) != len(rhs.sets):
+        return False
+
+    eqs = (is_eq(x, y) for x, y in zip(lhs.sets, rhs.sets))
+    return tfn[fuzzy_and(map(fuzzy_bool, eqs))]
+
+
+@dispatch(Set, Basic) # type:ignore
+def _eval_is_eq(lhs, rhs): # noqa: F811
+    return False
+
+
+@dispatch(Set, Set) # type:ignore
+def _eval_is_eq(lhs, rhs): # noqa: F811
+    return tfn[fuzzy_and(a.is_subset(b) for a, b in [(lhs, rhs), (rhs, lhs)])]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/functions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..2529dbfd458451d7d09e91c717b170df77b1d9fe
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/functions.py
@@ -0,0 +1,262 @@
+from sympy.core.singleton import S
+from sympy.sets.sets import Set
+from sympy.calculus.singularities import singularities
+from sympy.core import Expr, Add
+from sympy.core.function import Lambda, FunctionClass, diff, expand_mul
+from sympy.core.numbers import Float, oo
+from sympy.core.symbol import Dummy, symbols, Wild
+from sympy.functions.elementary.exponential import exp, log
+from sympy.functions.elementary.miscellaneous import Min, Max
+from sympy.logic.boolalg import true
+from sympy.multipledispatch import Dispatcher
+from sympy.sets import (imageset, Interval, FiniteSet, Union, ImageSet,
+    Intersection, Range, Complement)
+from sympy.sets.sets import EmptySet, is_function_invertible_in_set
+from sympy.sets.fancysets import Integers, Naturals, Reals
+from sympy.functions.elementary.exponential import match_real_imag
+
+
+_x, _y = symbols("x y")
+
+FunctionUnion = (FunctionClass, Lambda)
+
+_set_function = Dispatcher('_set_function')
+
+
+@_set_function.register(FunctionClass, Set)
+def _(f, x):
+    return None
+
+@_set_function.register(FunctionUnion, FiniteSet)
+def _(f, x):
+    return FiniteSet(*map(f, x))
+
+@_set_function.register(Lambda, Interval)
+def _(f, x):
+    from sympy.solvers.solveset import solveset
+    from sympy.series import limit
+    # TODO: handle functions with infinitely many solutions (eg, sin, tan)
+    # TODO: handle multivariate functions
+
+    expr = f.expr
+    if len(expr.free_symbols) > 1 or len(f.variables) != 1:
+        return
+    var = f.variables[0]
+    if not var.is_real:
+        if expr.subs(var, Dummy(real=True)).is_real is False:
+            return
+
+    if expr.is_Piecewise:
+        result = S.EmptySet
+        domain_set = x
+        for (p_expr, p_cond) in expr.args:
+            if p_cond is true:
+                intrvl = domain_set
+            else:
+                intrvl = p_cond.as_set()
+                intrvl = Intersection(domain_set, intrvl)
+
+            if p_expr.is_Number:
+                image = FiniteSet(p_expr)
+            else:
+                image = imageset(Lambda(var, p_expr), intrvl)
+            result = Union(result, image)
+
+            # remove the part which has been `imaged`
+            domain_set = Complement(domain_set, intrvl)
+            if domain_set is S.EmptySet:
+                break
+        return result
+
+    if not x.start.is_comparable or not x.end.is_comparable:
+        return
+
+    try:
+        from sympy.polys.polyutils import _nsort
+        sing = list(singularities(expr, var, x))
+        if len(sing) > 1:
+            sing = _nsort(sing)
+    except NotImplementedError:
+        return
+
+    if x.left_open:
+        _start = limit(expr, var, x.start, dir="+")
+    elif x.start not in sing:
+        _start = f(x.start)
+    if x.right_open:
+        _end = limit(expr, var, x.end, dir="-")
+    elif x.end not in sing:
+        _end = f(x.end)
+
+    if len(sing) == 0:
+        soln_expr = solveset(diff(expr, var), var)
+        if not (isinstance(soln_expr, FiniteSet)
+                or soln_expr is S.EmptySet):
+            return
+        solns = list(soln_expr)
+
+        extr = [_start, _end] + [f(i) for i in solns
+                                 if i.is_real and i in x]
+        start, end = Min(*extr), Max(*extr)
+
+        left_open, right_open = False, False
+        if _start <= _end:
+            # the minimum or maximum value can occur simultaneously
+            # on both the edge of the interval and in some interior
+            # point
+            if start == _start and start not in solns:
+                left_open = x.left_open
+            if end == _end and end not in solns:
+                right_open = x.right_open
+        else:
+            if start == _end and start not in solns:
+                left_open = x.right_open
+            if end == _start and end not in solns:
+                right_open = x.left_open
+
+        return Interval(start, end, left_open, right_open)
+    else:
+        return imageset(f, Interval(x.start, sing[0],
+                                    x.left_open, True)) + \
+            Union(*[imageset(f, Interval(sing[i], sing[i + 1], True, True))
+                    for i in range(0, len(sing) - 1)]) + \
+            imageset(f, Interval(sing[-1], x.end, True, x.right_open))
+
+@_set_function.register(FunctionClass, Interval)
+def _(f, x):
+    if f == exp:
+        return Interval(exp(x.start), exp(x.end), x.left_open, x.right_open)
+    elif f == log:
+        return Interval(log(x.start), log(x.end), x.left_open, x.right_open)
+    return ImageSet(Lambda(_x, f(_x)), x)
+
+@_set_function.register(FunctionUnion, Union)
+def _(f, x):
+    return Union(*(imageset(f, arg) for arg in x.args))
+
+@_set_function.register(FunctionUnion, Intersection)
+def _(f, x):
+    # If the function is invertible, intersect the maps of the sets.
+    if is_function_invertible_in_set(f, x):
+        return Intersection(*(imageset(f, arg) for arg in x.args))
+    else:
+        return ImageSet(Lambda(_x, f(_x)), x)
+
+@_set_function.register(FunctionUnion, EmptySet)
+def _(f, x):
+    return x
+
+@_set_function.register(FunctionUnion, Set)
+def _(f, x):
+    return ImageSet(Lambda(_x, f(_x)), x)
+
+@_set_function.register(FunctionUnion, Range)
+def _(f, self):
+    if not self:
+        return S.EmptySet
+    if not isinstance(f.expr, Expr):
+        return
+    if self.size == 1:
+        return FiniteSet(f(self[0]))
+    if f is S.IdentityFunction:
+        return self
+
+    x = f.variables[0]
+    expr = f.expr
+    # handle f that is linear in f's variable
+    if x not in expr.free_symbols or x in expr.diff(x).free_symbols:
+        return
+    if self.start.is_finite:
+        F = f(self.step*x + self.start)  # for i in range(len(self))
+    else:
+        F = f(-self.step*x + self[-1])
+    F = expand_mul(F)
+    if F != expr:
+        return imageset(x, F, Range(self.size))
+
+@_set_function.register(FunctionUnion, Integers)
+def _(f, self):
+    expr = f.expr
+    if not isinstance(expr, Expr):
+        return
+
+    n = f.variables[0]
+    if expr == abs(n):
+        return S.Naturals0
+
+    # f(x) + c and f(-x) + c cover the same integers
+    # so choose the form that has the fewest negatives
+    c = f(0)
+    fx = f(n) - c
+    f_x = f(-n) - c
+    neg_count = lambda e: sum(_.could_extract_minus_sign()
+        for _ in Add.make_args(e))
+    if neg_count(f_x) < neg_count(fx):
+        expr = f_x + c
+
+    a = Wild('a', exclude=[n])
+    b = Wild('b', exclude=[n])
+    match = expr.match(a*n + b)
+    if match and match[a] and (
+            not match[a].atoms(Float) and
+            not match[b].atoms(Float)):
+        # canonical shift
+        a, b = match[a], match[b]
+        if a in [1, -1]:
+            # drop integer addends in b
+            nonint = []
+            for bi in Add.make_args(b):
+                if not bi.is_integer:
+                    nonint.append(bi)
+            b = Add(*nonint)
+        if b.is_number and a.is_real:
+            # avoid Mod for complex numbers, #11391
+            br, bi = match_real_imag(b)
+            if br and br.is_comparable and a.is_comparable:
+                br %= a
+                b = br + S.ImaginaryUnit*bi
+        elif b.is_number and a.is_imaginary:
+            br, bi = match_real_imag(b)
+            ai = a/S.ImaginaryUnit
+            if bi and bi.is_comparable and ai.is_comparable:
+                bi %= ai
+                b = br + S.ImaginaryUnit*bi
+        expr = a*n + b
+
+    if expr != f.expr:
+        return ImageSet(Lambda(n, expr), S.Integers)
+
+
+@_set_function.register(FunctionUnion, Naturals)
+def _(f, self):
+    expr = f.expr
+    if not isinstance(expr, Expr):
+        return
+
+    x = f.variables[0]
+    if not expr.free_symbols - {x}:
+        if expr == abs(x):
+            if self is S.Naturals:
+                return self
+            return S.Naturals0
+        step = expr.coeff(x)
+        c = expr.subs(x, 0)
+        if c.is_Integer and step.is_Integer and expr == step*x + c:
+            if self is S.Naturals:
+                c += step
+            if step > 0:
+                if step == 1:
+                    if c == 0:
+                        return S.Naturals0
+                    elif c == 1:
+                        return S.Naturals
+                return Range(c, oo, step)
+            return Range(c, -oo, step)
+
+
+@_set_function.register(FunctionUnion, Reals)
+def _(f, self):
+    expr = f.expr
+    if not isinstance(expr, Expr):
+        return
+    return _set_function(f, Interval(-oo, oo))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/intersection.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/intersection.py
new file mode 100644
index 0000000000000000000000000000000000000000..fcb9309ef3e9d2722ab1bfe664f1d1644f17da5d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/intersection.py
@@ -0,0 +1,533 @@
+from sympy.core.basic import _aresame
+from sympy.core.function import Lambda, expand_complex
+from sympy.core.mul import Mul
+from sympy.core.numbers import ilcm, Float
+from sympy.core.relational import Eq
+from sympy.core.singleton import S
+from sympy.core.symbol import (Dummy, symbols)
+from sympy.core.sorting import ordered
+from sympy.functions.elementary.complexes import sign
+from sympy.functions.elementary.integers import floor, ceiling
+from sympy.sets.fancysets import ComplexRegion
+from sympy.sets.sets import (FiniteSet, Intersection, Interval, Set, Union)
+from sympy.multipledispatch import Dispatcher
+from sympy.sets.conditionset import ConditionSet
+from sympy.sets.fancysets import (Integers, Naturals, Reals, Range,
+    ImageSet, Rationals)
+from sympy.sets.sets import EmptySet, UniversalSet, imageset, ProductSet
+from sympy.simplify.radsimp import numer
+
+
+intersection_sets = Dispatcher('intersection_sets')
+
+
+@intersection_sets.register(ConditionSet, ConditionSet)
+def _(a, b):
+    return None
+
+@intersection_sets.register(ConditionSet, Set)
+def _(a, b):
+    return ConditionSet(a.sym, a.condition, Intersection(a.base_set, b))
+
+@intersection_sets.register(Naturals, Integers)
+def _(a, b):
+    return a
+
+@intersection_sets.register(Naturals, Naturals)
+def _(a, b):
+    return a if a is S.Naturals else b
+
+@intersection_sets.register(Interval, Naturals)
+def _(a, b):
+    return intersection_sets(b, a)
+
+@intersection_sets.register(ComplexRegion, Set)
+def _(self, other):
+    if other.is_ComplexRegion:
+        # self in rectangular form
+        if (not self.polar) and (not other.polar):
+            return ComplexRegion(Intersection(self.sets, other.sets))
+
+        # self in polar form
+        elif self.polar and other.polar:
+            r1, theta1 = self.a_interval, self.b_interval
+            r2, theta2 = other.a_interval, other.b_interval
+            new_r_interval = Intersection(r1, r2)
+            new_theta_interval = Intersection(theta1, theta2)
+
+            # 0 and 2*Pi means the same
+            if ((2*S.Pi in theta1 and S.Zero in theta2) or
+               (2*S.Pi in theta2 and S.Zero in theta1)):
+                new_theta_interval = Union(new_theta_interval,
+                                           FiniteSet(0))
+            return ComplexRegion(new_r_interval*new_theta_interval,
+                                polar=True)
+
+
+    if other.is_subset(S.Reals):
+        new_interval = []
+        x = symbols("x", cls=Dummy, real=True)
+
+        # self in rectangular form
+        if not self.polar:
+            for element in self.psets:
+                if S.Zero in element.args[1]:
+                    new_interval.append(element.args[0])
+            new_interval = Union(*new_interval)
+            return Intersection(new_interval, other)
+
+        # self in polar form
+        elif self.polar:
+            for element in self.psets:
+                if S.Zero in element.args[1]:
+                    new_interval.append(element.args[0])
+                if S.Pi in element.args[1]:
+                    new_interval.append(ImageSet(Lambda(x, -x), element.args[0]))
+                if S.Zero in element.args[0]:
+                    new_interval.append(FiniteSet(0))
+            new_interval = Union(*new_interval)
+            return Intersection(new_interval, other)
+
+@intersection_sets.register(Integers, Reals)
+def _(a, b):
+    return a
+
+@intersection_sets.register(Range, Interval)
+def _(a, b):
+    # Check that there are no symbolic arguments
+    if not all(i.is_number for i in a.args + b.args[:2]):
+        return
+
+    # In case of null Range, return an EmptySet.
+    if a.size == 0:
+        return S.EmptySet
+
+    # trim down to self's size, and represent
+    # as a Range with step 1.
+    start = ceiling(max(b.inf, a.inf))
+    if start not in b:
+        start += 1
+    end = floor(min(b.sup, a.sup))
+    if end not in b:
+        end -= 1
+    return intersection_sets(a, Range(start, end + 1))
+
+@intersection_sets.register(Range, Naturals)
+def _(a, b):
+    return intersection_sets(a, Interval(b.inf, S.Infinity))
+
+@intersection_sets.register(Range, Range)
+def _(a, b):
+    # Check that there are no symbolic range arguments
+    if not all(all(v.is_number for v in r.args) for r in [a, b]):
+        return None
+
+    # non-overlap quick exits
+    if not b:
+        return S.EmptySet
+    if not a:
+        return S.EmptySet
+    if b.sup < a.inf:
+        return S.EmptySet
+    if b.inf > a.sup:
+        return S.EmptySet
+
+    # work with finite end at the start
+    r1 = a
+    if r1.start.is_infinite:
+        r1 = r1.reversed
+    r2 = b
+    if r2.start.is_infinite:
+        r2 = r2.reversed
+
+    # If both ends are infinite then it means that one Range is just the set
+    # of all integers (the step must be 1).
+    if r1.start.is_infinite:
+        return b
+    if r2.start.is_infinite:
+        return a
+
+    from sympy.solvers.diophantine.diophantine import diop_linear
+
+    # this equation represents the values of the Range;
+    # it's a linear equation
+    eq = lambda r, i: r.start + i*r.step
+
+    # we want to know when the two equations might
+    # have integer solutions so we use the diophantine
+    # solver
+    va, vb = diop_linear(eq(r1, Dummy('a')) - eq(r2, Dummy('b')))
+
+    # check for no solution
+    no_solution = va is None and vb is None
+    if no_solution:
+        return S.EmptySet
+
+    # there is a solution
+    # -------------------
+
+    # find the coincident point, c
+    a0 = va.as_coeff_Add()[0]
+    c = eq(r1, a0)
+
+    # find the first point, if possible, in each range
+    # since c may not be that point
+    def _first_finite_point(r1, c):
+        if c == r1.start:
+            return c
+        # st is the signed step we need to take to
+        # get from c to r1.start
+        st = sign(r1.start - c)*step
+        # use Range to calculate the first point:
+        # we want to get as close as possible to
+        # r1.start; the Range will not be null since
+        # it will at least contain c
+        s1 = Range(c, r1.start + st, st)[-1]
+        if s1 == r1.start:
+            pass
+        else:
+            # if we didn't hit r1.start then, if the
+            # sign of st didn't match the sign of r1.step
+            # we are off by one and s1 is not in r1
+            if sign(r1.step) != sign(st):
+                s1 -= st
+        if s1 not in r1:
+            return
+        return s1
+
+    # calculate the step size of the new Range
+    step = abs(ilcm(r1.step, r2.step))
+    s1 = _first_finite_point(r1, c)
+    if s1 is None:
+        return S.EmptySet
+    s2 = _first_finite_point(r2, c)
+    if s2 is None:
+        return S.EmptySet
+
+    # replace the corresponding start or stop in
+    # the original Ranges with these points; the
+    # result must have at least one point since
+    # we know that s1 and s2 are in the Ranges
+    def _updated_range(r, first):
+        st = sign(r.step)*step
+        if r.start.is_finite:
+            rv = Range(first, r.stop, st)
+        else:
+            rv = Range(r.start, first + st, st)
+        return rv
+    r1 = _updated_range(a, s1)
+    r2 = _updated_range(b, s2)
+
+    # work with them both in the increasing direction
+    if sign(r1.step) < 0:
+        r1 = r1.reversed
+    if sign(r2.step) < 0:
+        r2 = r2.reversed
+
+    # return clipped Range with positive step; it
+    # can't be empty at this point
+    start = max(r1.start, r2.start)
+    stop = min(r1.stop, r2.stop)
+    return Range(start, stop, step)
+
+
+@intersection_sets.register(Range, Integers)
+def _(a, b):
+    return a
+
+
+@intersection_sets.register(Range, Rationals)
+def _(a, b):
+    return a
+
+
+@intersection_sets.register(ImageSet, Set)
+def _(self, other):
+    from sympy.solvers.diophantine import diophantine
+
+    # Only handle the straight-forward univariate case
+    if (len(self.lamda.variables) > 1
+            or self.lamda.signature != self.lamda.variables):
+        return None
+    base_set = self.base_sets[0]
+
+    # Intersection between ImageSets with Integers as base set
+    # For {f(n) : n in Integers} & {g(m) : m in Integers} we solve the
+    # diophantine equations f(n)=g(m).
+    # If the solutions for n are {h(t) : t in Integers} then we return
+    # {f(h(t)) : t in integers}.
+    # If the solutions for n are {n_1, n_2, ..., n_k} then we return
+    # {f(n_i) : 1 <= i <= k}.
+    if base_set is S.Integers:
+        gm = None
+        if isinstance(other, ImageSet) and other.base_sets == (S.Integers,):
+            gm = other.lamda.expr
+            var = other.lamda.variables[0]
+            # Symbol of second ImageSet lambda must be distinct from first
+            m = Dummy('m')
+            gm = gm.subs(var, m)
+        elif other is S.Integers:
+            m = gm = Dummy('m')
+        if gm is not None:
+            fn = self.lamda.expr
+            n = self.lamda.variables[0]
+            try:
+                solns = list(diophantine(fn - gm, syms=(n, m), permute=True))
+            except (TypeError, NotImplementedError):
+                # TypeError if equation not polynomial with rational coeff.
+                # NotImplementedError if correct format but no solver.
+                return
+            # 3 cases are possible for solns:
+            # - empty set,
+            # - one or more parametric (infinite) solutions,
+            # - a finite number of (non-parametric) solution couples.
+            # Among those, there is one type of solution set that is
+            # not helpful here: multiple parametric solutions.
+            if len(solns) == 0:
+                return S.EmptySet
+            elif any(s.free_symbols for tupl in solns for s in tupl):
+                if len(solns) == 1:
+                    soln, solm = solns[0]
+                    (t,) = soln.free_symbols
+                    expr = fn.subs(n, soln.subs(t, n)).expand()
+                    return imageset(Lambda(n, expr), S.Integers)
+                else:
+                    return
+            else:
+                return FiniteSet(*(fn.subs(n, s[0]) for s in solns))
+
+    if other == S.Reals:
+        from sympy.solvers.solvers import denoms, solve_linear
+
+        def _solution_union(exprs, sym):
+            # return a union of linear solutions to i in expr;
+            # if i cannot be solved, use a ConditionSet for solution
+            sols = []
+            for i in exprs:
+                x, xis = solve_linear(i, 0, [sym])
+                if x == sym:
+                    sols.append(FiniteSet(xis))
+                else:
+                    sols.append(ConditionSet(sym, Eq(i, 0)))
+            return Union(*sols)
+
+        f = self.lamda.expr
+        n = self.lamda.variables[0]
+
+        n_ = Dummy(n.name, real=True)
+        f_ = f.subs(n, n_)
+
+        re, im = f_.as_real_imag()
+        im = expand_complex(im)
+
+        re = re.subs(n_, n)
+        im = im.subs(n_, n)
+        ifree = im.free_symbols
+        lam = Lambda(n, re)
+        if im.is_zero:
+            # allow re-evaluation
+            # of self in this case to make
+            # the result canonical
+            pass
+        elif im.is_zero is False:
+            return S.EmptySet
+        elif ifree != {n}:
+            return None
+        else:
+            # univarite imaginary part in same variable;
+            # use numer instead of as_numer_denom to keep
+            # this as fast as possible while still handling
+            # simple cases
+            base_set &= _solution_union(
+                Mul.make_args(numer(im)), n)
+        # exclude values that make denominators 0
+        base_set -= _solution_union(denoms(f), n)
+        return imageset(lam, base_set)
+
+    elif isinstance(other, Interval):
+        from sympy.solvers.solveset import (invert_real, invert_complex,
+                                            solveset)
+
+        f = self.lamda.expr
+        n = self.lamda.variables[0]
+        new_inf, new_sup = None, None
+        new_lopen, new_ropen = other.left_open, other.right_open
+
+        if f.is_real:
+            inverter = invert_real
+        else:
+            inverter = invert_complex
+
+        g1, h1 = inverter(f, other.inf, n)
+        g2, h2 = inverter(f, other.sup, n)
+
+        if all(isinstance(i, FiniteSet) for i in (h1, h2)):
+            if g1 == n:
+                if len(h1) == 1:
+                    new_inf = h1.args[0]
+            if g2 == n:
+                if len(h2) == 1:
+                    new_sup = h2.args[0]
+            # TODO: Design a technique to handle multiple-inverse
+            # functions
+
+            # Any of the new boundary values cannot be determined
+            if any(i is None for i in (new_sup, new_inf)):
+                return
+
+
+            range_set = S.EmptySet
+
+            if all(i.is_real for i in (new_sup, new_inf)):
+                # this assumes continuity of underlying function
+                # however fixes the case when it is decreasing
+                if new_inf > new_sup:
+                    new_inf, new_sup = new_sup, new_inf
+                new_interval = Interval(new_inf, new_sup, new_lopen, new_ropen)
+                range_set = base_set.intersect(new_interval)
+            else:
+                if other.is_subset(S.Reals):
+                    solutions = solveset(f, n, S.Reals)
+                    if not isinstance(range_set, (ImageSet, ConditionSet)):
+                        range_set = solutions.intersect(other)
+                    else:
+                        return
+
+            if range_set is S.EmptySet:
+                return S.EmptySet
+            elif isinstance(range_set, Range) and range_set.size is not S.Infinity:
+                range_set = FiniteSet(*list(range_set))
+
+            if range_set is not None:
+                return imageset(Lambda(n, f), range_set)
+            return
+        else:
+            return
+
+
+@intersection_sets.register(ProductSet, ProductSet)
+def _(a, b):
+    if len(b.args) != len(a.args):
+        return S.EmptySet
+    return ProductSet(*(i.intersect(j) for i, j in zip(a.sets, b.sets)))
+
+
+@intersection_sets.register(Interval, Interval)
+def _(a, b):
+    # handle (-oo, oo)
+    infty = S.NegativeInfinity, S.Infinity
+    if a == Interval(*infty):
+        l, r = a.left, a.right
+        if l.is_real or l in infty or r.is_real or r in infty:
+            return b
+
+    # We can't intersect [0,3] with [x,6] -- we don't know if x>0 or x<0
+    if not a._is_comparable(b):
+        return None
+
+    empty = False
+
+    if a.start <= b.end and b.start <= a.end:
+        # Get topology right.
+        if a.start < b.start:
+            start = b.start
+            left_open = b.left_open
+        elif a.start > b.start:
+            start = a.start
+            left_open = a.left_open
+        else:
+            start = a.start
+            if not _aresame(a.start, b.start):
+                # For example Integer(2) != Float(2)
+                # Prefer the Float boundary because Floats should be
+                # contagious in calculations.
+                if b.start.has(Float) and not a.start.has(Float):
+                    start = b.start
+                elif a.start.has(Float) and not b.start.has(Float):
+                    start = a.start
+                else:
+                    #this is to ensure that if Eq(a.start, b.start) but
+                    #type(a.start) != type(b.start) the order of a and b
+                    #does not matter for the result
+                    start = list(ordered([a,b]))[0].start
+            left_open = a.left_open or b.left_open
+
+        if a.end < b.end:
+            end = a.end
+            right_open = a.right_open
+        elif a.end > b.end:
+            end = b.end
+            right_open = b.right_open
+        else:
+            # see above for logic with start
+            end = a.end
+            if not _aresame(a.end, b.end):
+                if b.end.has(Float) and not a.end.has(Float):
+                    end = b.end
+                elif a.end.has(Float) and not b.end.has(Float):
+                    end = a.end
+                else:
+                    end = list(ordered([a,b]))[0].end
+            right_open = a.right_open or b.right_open
+
+        if end - start == 0 and (left_open or right_open):
+            empty = True
+    else:
+        empty = True
+
+    if empty:
+        return S.EmptySet
+
+    return Interval(start, end, left_open, right_open)
+
+@intersection_sets.register(EmptySet, Set)
+def _(a, b):
+    return S.EmptySet
+
+@intersection_sets.register(UniversalSet, Set)
+def _(a, b):
+    return b
+
+@intersection_sets.register(FiniteSet, FiniteSet)
+def _(a, b):
+    return FiniteSet(*(a._elements & b._elements))
+
+@intersection_sets.register(FiniteSet, Set)
+def _(a, b):
+    try:
+        return FiniteSet(*[el for el in a if el in b])
+    except TypeError:
+        return None  # could not evaluate `el in b` due to symbolic ranges.
+
+@intersection_sets.register(Set, Set)
+def _(a, b):
+    return None
+
+@intersection_sets.register(Integers, Rationals)
+def _(a, b):
+    return a
+
+@intersection_sets.register(Naturals, Rationals)
+def _(a, b):
+    return a
+
+@intersection_sets.register(Rationals, Reals)
+def _(a, b):
+    return a
+
+def _intlike_interval(a, b):
+    try:
+        if b._inf is S.NegativeInfinity and b._sup is S.Infinity:
+            return a
+        s = Range(max(a.inf, ceiling(b.left)), floor(b.right) + 1)
+        return intersection_sets(s, b)  # take out endpoints if open interval
+    except ValueError:
+        return None
+
+@intersection_sets.register(Integers, Interval)
+def _(a, b):
+    return _intlike_interval(a, b)
+
+@intersection_sets.register(Naturals, Interval)
+def _(a, b):
+    return _intlike_interval(a, b)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/issubset.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/issubset.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc23e8bf56f1743cd7f08452dd09a0acf981f5da
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/issubset.py
@@ -0,0 +1,144 @@
+from sympy.core.singleton import S
+from sympy.core.symbol import Symbol
+from sympy.core.logic import fuzzy_and, fuzzy_bool, fuzzy_not, fuzzy_or
+from sympy.core.relational import Eq
+from sympy.sets.sets import FiniteSet, Interval, Set, Union, ProductSet
+from sympy.sets.fancysets import Complexes, Reals, Range, Rationals
+from sympy.multipledispatch import Dispatcher
+
+
+_inf_sets = [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals, S.Complexes]
+
+
+is_subset_sets = Dispatcher('is_subset_sets')
+
+
+@is_subset_sets.register(Set, Set)
+def _(a, b):
+    return None
+
+@is_subset_sets.register(Interval, Interval)
+def _(a, b):
+    # This is correct but can be made more comprehensive...
+    if fuzzy_bool(a.start < b.start):
+        return False
+    if fuzzy_bool(a.end > b.end):
+        return False
+    if (b.left_open and not a.left_open and fuzzy_bool(Eq(a.start, b.start))):
+        return False
+    if (b.right_open and not a.right_open and fuzzy_bool(Eq(a.end, b.end))):
+        return False
+
+@is_subset_sets.register(Interval, FiniteSet)
+def _(a_interval, b_fs):
+    # An Interval can only be a subset of a finite set if it is finite
+    # which can only happen if it has zero measure.
+    if fuzzy_not(a_interval.measure.is_zero):
+        return False
+
+@is_subset_sets.register(Interval, Union)
+def _(a_interval, b_u):
+    if all(isinstance(s, (Interval, FiniteSet)) for s in b_u.args):
+        intervals = [s for s in b_u.args if isinstance(s, Interval)]
+        if all(fuzzy_bool(a_interval.start < s.start) for s in intervals):
+            return False
+        if all(fuzzy_bool(a_interval.end > s.end) for s in intervals):
+            return False
+        if a_interval.measure.is_nonzero:
+            no_overlap = lambda s1, s2: fuzzy_or([
+                    fuzzy_bool(s1.end <= s2.start),
+                    fuzzy_bool(s1.start >= s2.end),
+                    ])
+            if all(no_overlap(s, a_interval) for s in intervals):
+                return False
+
+@is_subset_sets.register(Range, Range)
+def _(a, b):
+    if a.step == b.step == 1:
+        return fuzzy_and([fuzzy_bool(a.start >= b.start),
+                          fuzzy_bool(a.stop <= b.stop)])
+
+@is_subset_sets.register(Range, Interval)
+def _(a_range, b_interval):
+    if a_range.step.is_positive:
+        if b_interval.left_open and a_range.inf.is_finite:
+            cond_left = a_range.inf > b_interval.left
+        else:
+            cond_left = a_range.inf >= b_interval.left
+        if b_interval.right_open and a_range.sup.is_finite:
+            cond_right = a_range.sup < b_interval.right
+        else:
+            cond_right = a_range.sup <= b_interval.right
+        return fuzzy_and([cond_left, cond_right])
+
+@is_subset_sets.register(Range, FiniteSet)
+def _(a_range, b_finiteset):
+    try:
+        a_size = a_range.size
+    except ValueError:
+        # symbolic Range of unknown size
+        return None
+    if a_size > len(b_finiteset):
+        return False
+    elif any(arg.has(Symbol) for arg in a_range.args):
+        return fuzzy_and(b_finiteset.contains(x) for x in a_range)
+    else:
+        # Checking A \ B == EmptySet is more efficient than repeated naive
+        # membership checks on an arbitrary FiniteSet.
+        a_set = set(a_range)
+        b_remaining = len(b_finiteset)
+        # Symbolic expressions and numbers of unknown type (integer or not) are
+        # all counted as "candidates", i.e. *potentially* matching some a in
+        # a_range.
+        cnt_candidate = 0
+        for b in b_finiteset:
+            if b.is_Integer:
+                a_set.discard(b)
+            elif fuzzy_not(b.is_integer):
+                pass
+            else:
+                cnt_candidate += 1
+            b_remaining -= 1
+            if len(a_set) > b_remaining + cnt_candidate:
+                return False
+            if len(a_set) == 0:
+                return True
+        return None
+
+@is_subset_sets.register(Interval, Range)
+def _(a_interval, b_range):
+    if a_interval.measure.is_extended_nonzero:
+        return False
+
+@is_subset_sets.register(Interval, Rationals)
+def _(a_interval, b_rationals):
+    if a_interval.measure.is_extended_nonzero:
+        return False
+
+@is_subset_sets.register(Range, Complexes)
+def _(a, b):
+    return True
+
+@is_subset_sets.register(Complexes, Interval)
+def _(a, b):
+    return False
+
+@is_subset_sets.register(Complexes, Range)
+def _(a, b):
+    return False
+
+@is_subset_sets.register(Complexes, Rationals)
+def _(a, b):
+    return False
+
+@is_subset_sets.register(Rationals, Reals)
+def _(a, b):
+    return True
+
+@is_subset_sets.register(Rationals, Range)
+def _(a, b):
+    return False
+
+@is_subset_sets.register(ProductSet, FiniteSet)
+def _(a_ps, b_fs):
+    return fuzzy_and(b_fs.contains(x) for x in a_ps)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/mul.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/mul.py
new file mode 100644
index 0000000000000000000000000000000000000000..0dedc8068b7973fd4cb6fbf2854e5fa671d188de
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/mul.py
@@ -0,0 +1,79 @@
+from sympy.core import Basic, Expr
+from sympy.core.numbers import oo
+from sympy.core.symbol import symbols
+from sympy.multipledispatch import Dispatcher
+from sympy.sets.setexpr import set_mul
+from sympy.sets.sets import Interval, Set
+
+
+_x, _y = symbols("x y")
+
+
+_set_mul = Dispatcher('_set_mul')
+_set_div = Dispatcher('_set_div')
+
+
+@_set_mul.register(Basic, Basic)
+def _(x, y):
+    return None
+
+@_set_mul.register(Set, Set)
+def _(x, y):
+    return None
+
+@_set_mul.register(Expr, Expr)
+def _(x, y):
+    return x*y
+
+@_set_mul.register(Interval, Interval)
+def _(x, y):
+    """
+    Multiplications in interval arithmetic
+    https://en.wikipedia.org/wiki/Interval_arithmetic
+    """
+    # TODO: some intervals containing 0 and oo will fail as 0*oo returns nan.
+    comvals = (
+        (x.start * y.start, bool(x.left_open or y.left_open)),
+        (x.start * y.end, bool(x.left_open or y.right_open)),
+        (x.end * y.start, bool(x.right_open or y.left_open)),
+        (x.end * y.end, bool(x.right_open or y.right_open)),
+    )
+    # TODO: handle symbolic intervals
+    minval, minopen = min(comvals)
+    maxval, maxopen = max(comvals)
+    return Interval(
+        minval,
+        maxval,
+        minopen,
+        maxopen
+    )
+
+@_set_div.register(Basic, Basic)
+def _(x, y):
+    return None
+
+@_set_div.register(Expr, Expr)
+def _(x, y):
+    return x/y
+
+@_set_div.register(Set, Set)
+def _(x, y):
+    return None
+
+@_set_div.register(Interval, Interval)
+def _(x, y):
+    """
+    Divisions in interval arithmetic
+    https://en.wikipedia.org/wiki/Interval_arithmetic
+    """
+    if (y.start*y.end).is_negative:
+        return Interval(-oo, oo)
+    if y.start == 0:
+        s2 = oo
+    else:
+        s2 = 1/y.start
+    if y.end == 0:
+        s1 = -oo
+    else:
+        s1 = 1/y.end
+    return set_mul(x, Interval(s1, s2, y.right_open, y.left_open))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/power.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/power.py
new file mode 100644
index 0000000000000000000000000000000000000000..3cad4ee49ab27770143bc121d1fbcd024bf01548
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/power.py
@@ -0,0 +1,107 @@
+from sympy.core import Basic, Expr
+from sympy.core.function import Lambda
+from sympy.core.numbers import oo, Infinity, NegativeInfinity, Zero, Integer
+from sympy.core.singleton import S
+from sympy.core.symbol import symbols
+from sympy.functions.elementary.miscellaneous import (Max, Min)
+from sympy.sets.fancysets import ImageSet
+from sympy.sets.setexpr import set_div
+from sympy.sets.sets import Set, Interval, FiniteSet, Union
+from sympy.multipledispatch import Dispatcher
+
+
+_x, _y = symbols("x y")
+
+
+_set_pow = Dispatcher('_set_pow')
+
+
+@_set_pow.register(Basic, Basic)
+def _(x, y):
+    return None
+
+@_set_pow.register(Set, Set)
+def _(x, y):
+    return ImageSet(Lambda((_x, _y), (_x ** _y)), x, y)
+
+@_set_pow.register(Expr, Expr)
+def _(x, y):
+    return x**y
+
+@_set_pow.register(Interval, Zero)
+def _(x, z):
+    return FiniteSet(S.One)
+
+@_set_pow.register(Interval, Integer)
+def _(x, exponent):
+    """
+    Powers in interval arithmetic
+    https://en.wikipedia.org/wiki/Interval_arithmetic
+    """
+    s1 = x.start**exponent
+    s2 = x.end**exponent
+    if ((s2 > s1) if exponent > 0 else (x.end > -x.start)) == True:
+        left_open = x.left_open
+        right_open = x.right_open
+        # TODO: handle unevaluated condition.
+        sleft = s2
+    else:
+        # TODO: `s2 > s1` could be unevaluated.
+        left_open = x.right_open
+        right_open = x.left_open
+        sleft = s1
+
+    if x.start.is_positive:
+        return Interval(
+            Min(s1, s2),
+            Max(s1, s2), left_open, right_open)
+    elif x.end.is_negative:
+        return Interval(
+            Min(s1, s2),
+            Max(s1, s2), left_open, right_open)
+
+    # Case where x.start < 0 and x.end > 0:
+    if exponent.is_odd:
+        if exponent.is_negative:
+            if x.start.is_zero:
+                return Interval(s2, oo, x.right_open)
+            if x.end.is_zero:
+                return Interval(-oo, s1, True, x.left_open)
+            return Union(Interval(-oo, s1, True, x.left_open), Interval(s2, oo, x.right_open))
+        else:
+            return Interval(s1, s2, x.left_open, x.right_open)
+    elif exponent.is_even:
+        if exponent.is_negative:
+            if x.start.is_zero:
+                return Interval(s2, oo, x.right_open)
+            if x.end.is_zero:
+                return Interval(s1, oo, x.left_open)
+            return Interval(0, oo)
+        else:
+            return Interval(S.Zero, sleft, S.Zero not in x, left_open)
+
+@_set_pow.register(Interval, Infinity)
+def _(b, e):
+    # TODO: add logic for open intervals?
+    if b.start.is_nonnegative:
+        if b.end < 1:
+            return FiniteSet(S.Zero)
+        if b.start > 1:
+            return FiniteSet(S.Infinity)
+        return Interval(0, oo)
+    elif b.end.is_negative:
+        if b.start > -1:
+            return FiniteSet(S.Zero)
+        if b.end < -1:
+            return FiniteSet(-oo, oo)
+        return Interval(-oo, oo)
+    else:
+        if b.start > -1:
+            if b.end < 1:
+                return FiniteSet(S.Zero)
+            return Interval(0, oo)
+        return Interval(-oo, oo)
+
+@_set_pow.register(Interval, NegativeInfinity)
+def _(b, e):
+    return _set_pow(set_div(S.One, b), oo)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/union.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/union.py
new file mode 100644
index 0000000000000000000000000000000000000000..75d867b49969ae2aeea76155dbaae7e05c1a6847
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/handlers/union.py
@@ -0,0 +1,147 @@
+from sympy.core.singleton import S
+from sympy.core.sympify import sympify
+from sympy.functions.elementary.miscellaneous import Min, Max
+from sympy.sets.sets import (EmptySet, FiniteSet, Intersection,
+    Interval, ProductSet, Set, Union, UniversalSet)
+from sympy.sets.fancysets import (ComplexRegion, Naturals, Naturals0,
+    Integers, Rationals, Reals)
+from sympy.multipledispatch import Dispatcher
+
+
+union_sets = Dispatcher('union_sets')
+
+
+@union_sets.register(Naturals0, Naturals)
+def _(a, b):
+    return a
+
+@union_sets.register(Rationals, Naturals)
+def _(a, b):
+    return a
+
+@union_sets.register(Rationals, Naturals0)
+def _(a, b):
+    return a
+
+@union_sets.register(Reals, Naturals)
+def _(a, b):
+    return a
+
+@union_sets.register(Reals, Naturals0)
+def _(a, b):
+    return a
+
+@union_sets.register(Reals, Rationals)
+def _(a, b):
+    return a
+
+@union_sets.register(Integers, Set)
+def _(a, b):
+    intersect = Intersection(a, b)
+    if intersect == a:
+        return b
+    elif intersect == b:
+        return a
+
+@union_sets.register(ComplexRegion, Set)
+def _(a, b):
+    if b.is_subset(S.Reals):
+        # treat a subset of reals as a complex region
+        b = ComplexRegion.from_real(b)
+
+    if b.is_ComplexRegion:
+        # a in rectangular form
+        if (not a.polar) and (not b.polar):
+            return ComplexRegion(Union(a.sets, b.sets))
+        # a in polar form
+        elif a.polar and b.polar:
+            return ComplexRegion(Union(a.sets, b.sets), polar=True)
+    return None
+
+@union_sets.register(EmptySet, Set)
+def _(a, b):
+    return b
+
+
+@union_sets.register(UniversalSet, Set)
+def _(a, b):
+    return a
+
+@union_sets.register(ProductSet, ProductSet)
+def _(a, b):
+    if b.is_subset(a):
+        return a
+    if len(b.sets) != len(a.sets):
+        return None
+    if len(a.sets) == 2:
+        a1, a2 = a.sets
+        b1, b2 = b.sets
+        if a1 == b1:
+            return a1 * Union(a2, b2)
+        if a2 == b2:
+            return Union(a1, b1) * a2
+    return None
+
+@union_sets.register(ProductSet, Set)
+def _(a, b):
+    if b.is_subset(a):
+        return a
+    return None
+
+@union_sets.register(Interval, Interval)
+def _(a, b):
+    if a._is_comparable(b):
+        # Non-overlapping intervals
+        end = Min(a.end, b.end)
+        start = Max(a.start, b.start)
+        if (end < start or
+           (end == start and (end not in a and end not in b))):
+            return None
+        else:
+            start = Min(a.start, b.start)
+            end = Max(a.end, b.end)
+
+            left_open = ((a.start != start or a.left_open) and
+                         (b.start != start or b.left_open))
+            right_open = ((a.end != end or a.right_open) and
+                          (b.end != end or b.right_open))
+            return Interval(start, end, left_open, right_open)
+
+@union_sets.register(Interval, UniversalSet)
+def _(a, b):
+    return S.UniversalSet
+
+@union_sets.register(Interval, Set)
+def _(a, b):
+    # If I have open end points and these endpoints are contained in b
+    # But only in case, when endpoints are finite. Because
+    # interval does not contain oo or -oo.
+    open_left_in_b_and_finite = (a.left_open and
+                                     sympify(b.contains(a.start)) is S.true and
+                                     a.start.is_finite)
+    open_right_in_b_and_finite = (a.right_open and
+                                      sympify(b.contains(a.end)) is S.true and
+                                      a.end.is_finite)
+    if open_left_in_b_and_finite or open_right_in_b_and_finite:
+        # Fill in my end points and return
+        open_left = a.left_open and a.start not in b
+        open_right = a.right_open and a.end not in b
+        new_a = Interval(a.start, a.end, open_left, open_right)
+        return {new_a, b}
+    return None
+
+@union_sets.register(FiniteSet, FiniteSet)
+def _(a, b):
+    return FiniteSet(*(a._elements | b._elements))
+
+@union_sets.register(FiniteSet, Set)
+def _(a, b):
+    # If `b` set contains one of my elements, remove it from `a`
+    if any(b.contains(x) == True for x in a):
+        return {
+            FiniteSet(*[x for x in a if b.contains(x) != True]), b}
+    return None
+
+@union_sets.register(Set, Set)
+def _(a, b):
+    return None
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/ordinals.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/ordinals.py
new file mode 100644
index 0000000000000000000000000000000000000000..cfe062354cfe58a4747998e51fa0d261e67576cc
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/ordinals.py
@@ -0,0 +1,282 @@
+from sympy.core import Basic, Integer
+import operator
+
+
+class OmegaPower(Basic):
+    """
+    Represents ordinal exponential and multiplication terms one of the
+    building blocks of the :class:`Ordinal` class.
+    In ``OmegaPower(a, b)``, ``a`` represents exponent and ``b`` represents multiplicity.
+    """
+    def __new__(cls, a, b):
+        if isinstance(b, int):
+            b = Integer(b)
+        if not isinstance(b, Integer) or b <= 0:
+            raise TypeError("multiplicity must be a positive integer")
+
+        if not isinstance(a, Ordinal):
+            a = Ordinal.convert(a)
+
+        return Basic.__new__(cls, a, b)
+
+    @property
+    def exp(self):
+        return self.args[0]
+
+    @property
+    def mult(self):
+        return self.args[1]
+
+    def _compare_term(self, other, op):
+        if self.exp == other.exp:
+            return op(self.mult, other.mult)
+        else:
+            return op(self.exp, other.exp)
+
+    def __eq__(self, other):
+        if not isinstance(other, OmegaPower):
+            try:
+                other = OmegaPower(0, other)
+            except TypeError:
+                return NotImplemented
+        return self.args == other.args
+
+    def __hash__(self):
+        return Basic.__hash__(self)
+
+    def __lt__(self, other):
+        if not isinstance(other, OmegaPower):
+            try:
+                other = OmegaPower(0, other)
+            except TypeError:
+                return NotImplemented
+        return self._compare_term(other, operator.lt)
+
+
+class Ordinal(Basic):
+    """
+    Represents ordinals in Cantor normal form.
+
+    Internally, this class is just a list of instances of OmegaPower.
+
+    Examples
+    ========
+    >>> from sympy import Ordinal, OmegaPower
+    >>> from sympy.sets.ordinals import omega
+    >>> w = omega
+    >>> w.is_limit_ordinal
+    True
+    >>> Ordinal(OmegaPower(w + 1, 1), OmegaPower(3, 2))
+    w**(w + 1) + w**3*2
+    >>> 3 + w
+    w
+    >>> (w + 1) * w
+    w**2
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Ordinal_arithmetic
+    """
+    def __new__(cls, *terms):
+        obj = super().__new__(cls, *terms)
+        powers = [i.exp for i in obj.args]
+        if not all(powers[i] >= powers[i+1] for i in range(len(powers) - 1)):
+            raise ValueError("powers must be in decreasing order")
+        return obj
+
+    @property
+    def terms(self):
+        return self.args
+
+    @property
+    def leading_term(self):
+        if self == ord0:
+            raise ValueError("ordinal zero has no leading term")
+        return self.terms[0]
+
+    @property
+    def trailing_term(self):
+        if self == ord0:
+            raise ValueError("ordinal zero has no trailing term")
+        return self.terms[-1]
+
+    @property
+    def is_successor_ordinal(self):
+        try:
+            return self.trailing_term.exp == ord0
+        except ValueError:
+            return False
+
+    @property
+    def is_limit_ordinal(self):
+        try:
+            return not self.trailing_term.exp == ord0
+        except ValueError:
+            return False
+
+    @property
+    def degree(self):
+        return self.leading_term.exp
+
+    @classmethod
+    def convert(cls, integer_value):
+        if integer_value == 0:
+            return ord0
+        return Ordinal(OmegaPower(0, integer_value))
+
+    def __eq__(self, other):
+        if not isinstance(other, Ordinal):
+            try:
+                other = Ordinal.convert(other)
+            except TypeError:
+                return NotImplemented
+        return self.terms == other.terms
+
+    def __hash__(self):
+        return hash(self.args)
+
+    def __lt__(self, other):
+        if not isinstance(other, Ordinal):
+            try:
+                other = Ordinal.convert(other)
+            except TypeError:
+                return NotImplemented
+        for term_self, term_other in zip(self.terms, other.terms):
+            if term_self != term_other:
+                return term_self < term_other
+        return len(self.terms) < len(other.terms)
+
+    def __le__(self, other):
+        return (self == other or self < other)
+
+    def __gt__(self, other):
+        return not self <= other
+
+    def __ge__(self, other):
+        return not self < other
+
+    def __str__(self):
+        net_str = ""
+        plus_count = 0
+        if self == ord0:
+            return 'ord0'
+        for i in self.terms:
+            if plus_count:
+                net_str += " + "
+
+            if i.exp == ord0:
+                net_str += str(i.mult)
+            elif i.exp == 1:
+                net_str += 'w'
+            elif len(i.exp.terms) > 1 or i.exp.is_limit_ordinal:
+                net_str += 'w**(%s)'%i.exp
+            else:
+                net_str += 'w**%s'%i.exp
+
+            if not i.mult == 1 and not i.exp == ord0:
+                net_str += '*%s'%i.mult
+
+            plus_count += 1
+        return(net_str)
+
+    __repr__ = __str__
+
+    def __add__(self, other):
+        if not isinstance(other, Ordinal):
+            try:
+                other = Ordinal.convert(other)
+            except TypeError:
+                return NotImplemented
+        if other == ord0:
+            return self
+        a_terms = list(self.terms)
+        b_terms = list(other.terms)
+        r = len(a_terms) - 1
+        b_exp = other.degree
+        while r >= 0 and a_terms[r].exp < b_exp:
+            r -= 1
+        if r < 0:
+            terms = b_terms
+        elif a_terms[r].exp == b_exp:
+            sum_term = OmegaPower(b_exp, a_terms[r].mult + other.leading_term.mult)
+            terms = a_terms[:r] + [sum_term] + b_terms[1:]
+        else:
+            terms = a_terms[:r+1] + b_terms
+        return Ordinal(*terms)
+
+    def __radd__(self, other):
+        if not isinstance(other, Ordinal):
+            try:
+                other = Ordinal.convert(other)
+            except TypeError:
+                return NotImplemented
+        return other + self
+
+    def __mul__(self, other):
+        if not isinstance(other, Ordinal):
+            try:
+                other = Ordinal.convert(other)
+            except TypeError:
+                return NotImplemented
+        if ord0 in (self, other):
+            return ord0
+        a_exp = self.degree
+        a_mult = self.leading_term.mult
+        summation = []
+        if other.is_limit_ordinal:
+            for arg in other.terms:
+                summation.append(OmegaPower(a_exp + arg.exp, arg.mult))
+
+        else:
+            for arg in other.terms[:-1]:
+                summation.append(OmegaPower(a_exp + arg.exp, arg.mult))
+            b_mult = other.trailing_term.mult
+            summation.append(OmegaPower(a_exp, a_mult*b_mult))
+            summation += list(self.terms[1:])
+        return Ordinal(*summation)
+
+    def __rmul__(self, other):
+        if not isinstance(other, Ordinal):
+            try:
+                other = Ordinal.convert(other)
+            except TypeError:
+                return NotImplemented
+        return other * self
+
+    def __pow__(self, other):
+        if not self == omega:
+            return NotImplemented
+        return Ordinal(OmegaPower(other, 1))
+
+
+class OrdinalZero(Ordinal):
+    """The ordinal zero.
+
+    OrdinalZero can be imported as ``ord0``.
+    """
+    pass
+
+
+class OrdinalOmega(Ordinal):
+    """The ordinal omega which forms the base of all ordinals in cantor normal form.
+
+    OrdinalOmega can be imported as ``omega``.
+
+    Examples
+    ========
+
+    >>> from sympy.sets.ordinals import omega
+    >>> omega + omega
+    w*2
+    """
+    def __new__(cls):
+        return Ordinal.__new__(cls)
+
+    @property
+    def terms(self):
+        return (OmegaPower(1, 1),)
+
+
+ord0 = OrdinalZero()
+omega = OrdinalOmega()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/powerset.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/powerset.py
new file mode 100644
index 0000000000000000000000000000000000000000..2eb3b41b9859281480bc9517a1cad0abe7a5683f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/powerset.py
@@ -0,0 +1,119 @@
+from sympy.core.decorators import _sympifyit
+from sympy.core.parameters import global_parameters
+from sympy.core.logic import fuzzy_bool
+from sympy.core.singleton import S
+from sympy.core.sympify import _sympify
+
+from .sets import Set, FiniteSet, SetKind
+
+
+class PowerSet(Set):
+    r"""A symbolic object representing a power set.
+
+    Parameters
+    ==========
+
+    arg : Set
+        The set to take power of.
+
+    evaluate : bool
+        The flag to control evaluation.
+
+        If the evaluation is disabled for finite sets, it can take
+        advantage of using subset test as a membership test.
+
+    Notes
+    =====
+
+    Power set `\mathcal{P}(S)` is defined as a set containing all the
+    subsets of `S`.
+
+    If the set `S` is a finite set, its power set would have
+    `2^{\left| S \right|}` elements, where `\left| S \right|` denotes
+    the cardinality of `S`.
+
+    Examples
+    ========
+
+    >>> from sympy import PowerSet, S, FiniteSet
+
+    A power set of a finite set:
+
+    >>> PowerSet(FiniteSet(1, 2, 3))
+    PowerSet({1, 2, 3})
+
+    A power set of an empty set:
+
+    >>> PowerSet(S.EmptySet)
+    PowerSet(EmptySet)
+    >>> PowerSet(PowerSet(S.EmptySet))
+    PowerSet(PowerSet(EmptySet))
+
+    A power set of an infinite set:
+
+    >>> PowerSet(S.Reals)
+    PowerSet(Reals)
+
+    Evaluating the power set of a finite set to its explicit form:
+
+    >>> PowerSet(FiniteSet(1, 2, 3)).rewrite(FiniteSet)
+    FiniteSet(EmptySet, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3})
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Power_set
+
+    .. [2] https://en.wikipedia.org/wiki/Axiom_of_power_set
+    """
+    def __new__(cls, arg, evaluate=None):
+        if evaluate is None:
+            evaluate=global_parameters.evaluate
+
+        arg = _sympify(arg)
+
+        if not isinstance(arg, Set):
+            raise ValueError('{} must be a set.'.format(arg))
+
+        return super().__new__(cls, arg)
+
+    @property
+    def arg(self):
+        return self.args[0]
+
+    def _eval_rewrite_as_FiniteSet(self, *args, **kwargs):
+        arg = self.arg
+        if arg.is_FiniteSet:
+            return arg.powerset()
+        return None
+
+    @_sympifyit('other', NotImplemented)
+    def _contains(self, other):
+        if not isinstance(other, Set):
+            return None
+
+        return fuzzy_bool(self.arg.is_superset(other))
+
+    def _eval_is_subset(self, other):
+        if isinstance(other, PowerSet):
+            return self.arg.is_subset(other.arg)
+
+    def __len__(self):
+        return 2 ** len(self.arg)
+
+    def __iter__(self):
+        found = [S.EmptySet]
+        yield S.EmptySet
+
+        for x in self.arg:
+            temp = []
+            x = FiniteSet(x)
+            for y in found:
+                new = x + y
+                yield new
+                temp.append(new)
+            found.extend(temp)
+
+    @property
+    def kind(self):
+        return SetKind(self.arg.kind)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/setexpr.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/setexpr.py
new file mode 100644
index 0000000000000000000000000000000000000000..94d77d5293617a620b70a945888987ce6cc61157
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/setexpr.py
@@ -0,0 +1,97 @@
+from sympy.core import Expr
+from sympy.core.decorators import call_highest_priority, _sympifyit
+from .fancysets import ImageSet
+from .sets import set_add, set_sub, set_mul, set_div, set_pow, set_function
+
+
+class SetExpr(Expr):
+    """An expression that can take on values of a set.
+
+    Examples
+    ========
+
+    >>> from sympy import Interval, FiniteSet
+    >>> from sympy.sets.setexpr import SetExpr
+
+    >>> a = SetExpr(Interval(0, 5))
+    >>> b = SetExpr(FiniteSet(1, 10))
+    >>> (a + b).set
+    Union(Interval(1, 6), Interval(10, 15))
+    >>> (2*a + b).set
+    Interval(1, 20)
+    """
+    _op_priority = 11.0
+
+    def __new__(cls, setarg):
+        return Expr.__new__(cls, setarg)
+
+    set = property(lambda self: self.args[0])
+
+    def _latex(self, printer):
+        return r"SetExpr\left({}\right)".format(printer._print(self.set))
+
+    @_sympifyit('other', NotImplemented)
+    @call_highest_priority('__radd__')
+    def __add__(self, other):
+        return _setexpr_apply_operation(set_add, self, other)
+
+    @_sympifyit('other', NotImplemented)
+    @call_highest_priority('__add__')
+    def __radd__(self, other):
+        return _setexpr_apply_operation(set_add, other, self)
+
+    @_sympifyit('other', NotImplemented)
+    @call_highest_priority('__rmul__')
+    def __mul__(self, other):
+        return _setexpr_apply_operation(set_mul, self, other)
+
+    @_sympifyit('other', NotImplemented)
+    @call_highest_priority('__mul__')
+    def __rmul__(self, other):
+        return _setexpr_apply_operation(set_mul, other, self)
+
+    @_sympifyit('other', NotImplemented)
+    @call_highest_priority('__rsub__')
+    def __sub__(self, other):
+        return _setexpr_apply_operation(set_sub, self, other)
+
+    @_sympifyit('other', NotImplemented)
+    @call_highest_priority('__sub__')
+    def __rsub__(self, other):
+        return _setexpr_apply_operation(set_sub, other, self)
+
+    @_sympifyit('other', NotImplemented)
+    @call_highest_priority('__rpow__')
+    def __pow__(self, other):
+        return _setexpr_apply_operation(set_pow, self, other)
+
+    @_sympifyit('other', NotImplemented)
+    @call_highest_priority('__pow__')
+    def __rpow__(self, other):
+        return _setexpr_apply_operation(set_pow, other, self)
+
+    @_sympifyit('other', NotImplemented)
+    @call_highest_priority('__rtruediv__')
+    def __truediv__(self, other):
+        return _setexpr_apply_operation(set_div, self, other)
+
+    @_sympifyit('other', NotImplemented)
+    @call_highest_priority('__truediv__')
+    def __rtruediv__(self, other):
+        return _setexpr_apply_operation(set_div, other, self)
+
+    def _eval_func(self, func):
+        # TODO: this could be implemented straight into `imageset`:
+        res = set_function(func, self.set)
+        if res is None:
+            return SetExpr(ImageSet(func, self.set))
+        return SetExpr(res)
+
+
+def _setexpr_apply_operation(op, x, y):
+    if isinstance(x, SetExpr):
+        x = x.set
+    if isinstance(y, SetExpr):
+        y = y.set
+    out = op(x, y)
+    return SetExpr(out)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/sets.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/sets.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c85ce87c515cfd4520dcc6b9265fe76d8c6163f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/sets.py
@@ -0,0 +1,2804 @@
+from __future__ import annotations
+
+from typing import Any, Callable, TYPE_CHECKING, overload
+from functools import reduce
+from collections import defaultdict
+from collections.abc import Mapping, Iterable
+import inspect
+
+from sympy.core.kind import Kind, UndefinedKind, NumberKind
+from sympy.core.basic import Basic
+from sympy.core.containers import Tuple, TupleKind
+from sympy.core.decorators import sympify_method_args, sympify_return
+from sympy.core.evalf import EvalfMixin
+from sympy.core.expr import Expr
+from sympy.core.function import Lambda
+from sympy.core.logic import (FuzzyBool, fuzzy_bool, fuzzy_or, fuzzy_and,
+    fuzzy_not)
+from sympy.core.numbers import Float, Integer
+from sympy.core.operations import LatticeOp
+from sympy.core.parameters import global_parameters
+from sympy.core.relational import Eq, Ne, is_lt
+from sympy.core.singleton import Singleton, S
+from sympy.core.sorting import ordered
+from sympy.core.symbol import symbols, Symbol, Dummy, uniquely_named_symbol
+from sympy.core.sympify import _sympify, sympify, _sympy_converter
+from sympy.functions.elementary.exponential import exp, log
+from sympy.functions.elementary.miscellaneous import Max, Min
+from sympy.logic.boolalg import And, Or, Not, Xor, true, false
+from sympy.utilities.decorator import deprecated
+from sympy.utilities.exceptions import sympy_deprecation_warning
+from sympy.utilities.iterables import (iproduct, sift, roundrobin, iterable,
+                                       subsets)
+from sympy.utilities.misc import func_name, filldedent
+
+from mpmath import mpi, mpf
+
+from mpmath.libmp.libmpf import prec_to_dps
+
+
+tfn = defaultdict(lambda: None, {
+    True: S.true,
+    S.true: S.true,
+    False: S.false,
+    S.false: S.false})
+
+
+@sympify_method_args
+class Set(Basic, EvalfMixin):
+    """
+    The base class for any kind of set.
+
+    Explanation
+    ===========
+
+    This is not meant to be used directly as a container of items. It does not
+    behave like the builtin ``set``; see :class:`FiniteSet` for that.
+
+    Real intervals are represented by the :class:`Interval` class and unions of
+    sets by the :class:`Union` class. The empty set is represented by the
+    :class:`EmptySet` class and available as a singleton as ``S.EmptySet``.
+    """
+
+    __slots__: tuple[()] = ()
+
+    is_number = False
+    is_iterable = False
+    is_interval = False
+
+    is_FiniteSet = False
+    is_Interval = False
+    is_ProductSet = False
+    is_Union = False
+    is_Intersection: FuzzyBool = None
+    is_UniversalSet: FuzzyBool = None
+    is_Complement: FuzzyBool = None
+    is_ComplexRegion = False
+
+    is_empty: FuzzyBool = None
+    is_finite_set: FuzzyBool = None
+
+    @property  # type: ignore
+    @deprecated(
+        """
+        The is_EmptySet attribute of Set objects is deprecated.
+        Use 's is S.EmptySet" or 's.is_empty' instead.
+        """,
+        deprecated_since_version="1.5",
+        active_deprecations_target="deprecated-is-emptyset",
+    )
+    def is_EmptySet(self):
+        return None
+
+    if TYPE_CHECKING:
+
+        def __new__(cls, *args: Basic | complex) -> Set:
+            ...
+
+        @overload # type: ignore
+        def subs(self, arg1: Mapping[Basic | complex, Set | complex], arg2: None=None) -> Set: ...
+        @overload
+        def subs(self, arg1: Iterable[tuple[Basic | complex, Set | complex]], arg2: None=None, **kwargs: Any) -> Set: ...
+        @overload
+        def subs(self, arg1: Set | complex, arg2: Set | complex) -> Set: ...
+        @overload
+        def subs(self, arg1: Mapping[Basic | complex, Basic | complex], arg2: None=None, **kwargs: Any) -> Basic: ...
+        @overload
+        def subs(self, arg1: Iterable[tuple[Basic | complex, Basic | complex]], arg2: None=None, **kwargs: Any) -> Basic: ...
+        @overload
+        def subs(self, arg1: Basic | complex, arg2: Basic | complex, **kwargs: Any) -> Basic: ...
+
+        def subs(self, arg1: Mapping[Basic | complex, Basic | complex] | Basic | complex, # type: ignore
+                 arg2: Basic | complex | None = None, **kwargs: Any) -> Basic:
+            ...
+
+        def simplify(self, **kwargs) -> Set:
+            assert False
+
+        def evalf(self, n: int = 15, subs: dict[Basic, Basic | float] | None = None,
+                  maxn: int = 100, chop: bool = False, strict: bool  = False,
+                  quad: str | None = None, verbose: bool = False) -> Set:
+            ...
+
+        n = evalf
+
+    @staticmethod
+    def _infimum_key(expr):
+        """
+        Return infimum (if possible) else S.Infinity.
+        """
+        try:
+            infimum = expr.inf
+            assert infimum.is_comparable
+            infimum = infimum.evalf()  # issue #18505
+        except (NotImplementedError,
+                AttributeError, AssertionError, ValueError):
+            infimum = S.Infinity
+        return infimum
+
+    def union(self, other):
+        """
+        Returns the union of ``self`` and ``other``.
+
+        Examples
+        ========
+
+        As a shortcut it is possible to use the ``+`` operator:
+
+        >>> from sympy import Interval, FiniteSet
+        >>> Interval(0, 1).union(Interval(2, 3))
+        Union(Interval(0, 1), Interval(2, 3))
+        >>> Interval(0, 1) + Interval(2, 3)
+        Union(Interval(0, 1), Interval(2, 3))
+        >>> Interval(1, 2, True, True) + FiniteSet(2, 3)
+        Union({3}, Interval.Lopen(1, 2))
+
+        Similarly it is possible to use the ``-`` operator for set differences:
+
+        >>> Interval(0, 2) - Interval(0, 1)
+        Interval.Lopen(1, 2)
+        >>> Interval(1, 3) - FiniteSet(2)
+        Union(Interval.Ropen(1, 2), Interval.Lopen(2, 3))
+
+        """
+        return Union(self, other)
+
+    def intersect(self, other):
+        """
+        Returns the intersection of 'self' and 'other'.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval
+
+        >>> Interval(1, 3).intersect(Interval(1, 2))
+        Interval(1, 2)
+
+        >>> from sympy import imageset, Lambda, symbols, S
+        >>> n, m = symbols('n m')
+        >>> a = imageset(Lambda(n, 2*n), S.Integers)
+        >>> a.intersect(imageset(Lambda(m, 2*m + 1), S.Integers))
+        EmptySet
+
+        """
+        return Intersection(self, other)
+
+    def intersection(self, other):
+        """
+        Alias for :meth:`intersect()`
+        """
+        return self.intersect(other)
+
+    def is_disjoint(self, other):
+        """
+        Returns True if ``self`` and ``other`` are disjoint.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval
+        >>> Interval(0, 2).is_disjoint(Interval(1, 2))
+        False
+        >>> Interval(0, 2).is_disjoint(Interval(3, 4))
+        True
+
+        References
+        ==========
+
+        .. [1] https://en.wikipedia.org/wiki/Disjoint_sets
+        """
+        return self.intersect(other) == S.EmptySet
+
+    def isdisjoint(self, other):
+        """
+        Alias for :meth:`is_disjoint()`
+        """
+        return self.is_disjoint(other)
+
+    def complement(self, universe):
+        r"""
+        The complement of 'self' w.r.t the given universe.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval, S
+        >>> Interval(0, 1).complement(S.Reals)
+        Union(Interval.open(-oo, 0), Interval.open(1, oo))
+
+        >>> Interval(0, 1).complement(S.UniversalSet)
+        Complement(UniversalSet, Interval(0, 1))
+
+        """
+        return Complement(universe, self)
+
+    def _complement(self, other):
+        # this behaves as other - self
+        if isinstance(self, ProductSet) and isinstance(other, ProductSet):
+            # If self and other are disjoint then other - self == self
+            if len(self.sets) != len(other.sets):
+                return other
+
+            # There can be other ways to represent this but this gives:
+            # (A x B) - (C x D) = ((A - C) x B) U (A x (B - D))
+            overlaps = []
+            pairs = list(zip(self.sets, other.sets))
+            for n in range(len(pairs)):
+                sets = (o if i != n else o-s for i, (s, o) in enumerate(pairs))
+                overlaps.append(ProductSet(*sets))
+            return Union(*overlaps)
+
+        elif isinstance(other, Interval):
+            if isinstance(self, (Interval, FiniteSet)):
+                return Intersection(other, self.complement(S.Reals))
+
+        elif isinstance(other, Union):
+            return Union(*(o - self for o in other.args))
+
+        elif isinstance(other, Complement):
+            return Complement(other.args[0], Union(other.args[1], self), evaluate=False)
+
+        elif other is S.EmptySet:
+            return S.EmptySet
+
+        elif isinstance(other, FiniteSet):
+            sifted = sift(other, lambda x: fuzzy_bool(self.contains(x)))
+            # ignore those that are contained in self
+            return Union(FiniteSet(*(sifted[False])),
+                Complement(FiniteSet(*(sifted[None])), self, evaluate=False)
+                if sifted[None] else S.EmptySet)
+
+    def symmetric_difference(self, other):
+        """
+        Returns symmetric difference of ``self`` and ``other``.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval, S
+        >>> Interval(1, 3).symmetric_difference(S.Reals)
+        Union(Interval.open(-oo, 1), Interval.open(3, oo))
+        >>> Interval(1, 10).symmetric_difference(S.Reals)
+        Union(Interval.open(-oo, 1), Interval.open(10, oo))
+
+        >>> from sympy import S, EmptySet
+        >>> S.Reals.symmetric_difference(EmptySet)
+        Reals
+
+        References
+        ==========
+        .. [1] https://en.wikipedia.org/wiki/Symmetric_difference
+
+        """
+        return SymmetricDifference(self, other)
+
+    def _symmetric_difference(self, other):
+        return Union(Complement(self, other), Complement(other, self))
+
+    @property
+    def inf(self):
+        """
+        The infimum of ``self``.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval, Union
+        >>> Interval(0, 1).inf
+        0
+        >>> Union(Interval(0, 1), Interval(2, 3)).inf
+        0
+
+        """
+        return self._inf
+
+    @property
+    def _inf(self):
+        raise NotImplementedError("(%s)._inf" % self)
+
+    @property
+    def sup(self):
+        """
+        The supremum of ``self``.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval, Union
+        >>> Interval(0, 1).sup
+        1
+        >>> Union(Interval(0, 1), Interval(2, 3)).sup
+        3
+
+        """
+        return self._sup
+
+    @property
+    def _sup(self):
+        raise NotImplementedError("(%s)._sup" % self)
+
+    def contains(self, other):
+        """
+        Returns a SymPy value indicating whether ``other`` is contained
+        in ``self``: ``true`` if it is, ``false`` if it is not, else
+        an unevaluated ``Contains`` expression (or, as in the case of
+        ConditionSet and a union of FiniteSet/Intervals, an expression
+        indicating the conditions for containment).
+
+        Examples
+        ========
+
+        >>> from sympy import Interval, S
+        >>> from sympy.abc import x
+
+        >>> Interval(0, 1).contains(0.5)
+        True
+
+        As a shortcut it is possible to use the ``in`` operator, but that
+        will raise an error unless an affirmative true or false is not
+        obtained.
+
+        >>> Interval(0, 1).contains(x)
+        (0 <= x) & (x <= 1)
+        >>> x in Interval(0, 1)
+        Traceback (most recent call last):
+        ...
+        TypeError: did not evaluate to a bool: None
+
+        The result of 'in' is a bool, not a SymPy value
+
+        >>> 1 in Interval(0, 2)
+        True
+        >>> _ is S.true
+        False
+        """
+        from .contains import Contains
+        other = sympify(other, strict=True)
+
+        c = self._contains(other)
+        if isinstance(c, Contains):
+            return c
+        if c is None:
+            return Contains(other, self, evaluate=False)
+        b = tfn[c]
+        if b is None:
+            return c
+        return b
+
+    def _contains(self, other):
+        """Test if ``other`` is an element of the set ``self``.
+
+        This is an internal method that is expected to be overridden by
+        subclasses of ``Set`` and will be called by the public
+        :func:`Set.contains` method or the :class:`Contains` expression.
+
+        Parameters
+        ==========
+
+        other: Sympified :class:`Basic` instance
+            The object whose membership in ``self`` is to be tested.
+
+        Returns
+        =======
+
+        Symbolic :class:`Boolean` or ``None``.
+
+        A return value of ``None`` indicates that it is unknown whether
+        ``other`` is contained in ``self``. Returning ``None`` from here
+        ensures that ``self.contains(other)`` or ``Contains(self, other)`` will
+        return an unevaluated :class:`Contains` expression.
+
+        If not ``None`` then the returned value is a :class:`Boolean` that is
+        logically equivalent to the statement that ``other`` is an element of
+        ``self``. Usually this would be either ``S.true`` or ``S.false`` but
+        not always.
+        """
+        raise NotImplementedError(f"{type(self).__name__}._contains")
+
+    def is_subset(self, other):
+        """
+        Returns True if ``self`` is a subset of ``other``.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval
+        >>> Interval(0, 0.5).is_subset(Interval(0, 1))
+        True
+        >>> Interval(0, 1).is_subset(Interval(0, 1, left_open=True))
+        False
+
+        """
+        if not isinstance(other, Set):
+            raise ValueError("Unknown argument '%s'" % other)
+
+        # Handle the trivial cases
+        if self == other:
+            return True
+        is_empty = self.is_empty
+        if is_empty is True:
+            return True
+        elif fuzzy_not(is_empty) and other.is_empty:
+            return False
+        if self.is_finite_set is False and other.is_finite_set:
+            return False
+
+        # Dispatch on subclass rules
+        ret = self._eval_is_subset(other)
+        if ret is not None:
+            return ret
+        ret = other._eval_is_superset(self)
+        if ret is not None:
+            return ret
+
+        # Use pairwise rules from multiple dispatch
+        from sympy.sets.handlers.issubset import is_subset_sets
+        ret = is_subset_sets(self, other)
+        if ret is not None:
+            return ret
+
+        # Fall back on computing the intersection
+        # XXX: We shouldn't do this. A query like this should be handled
+        # without evaluating new Set objects. It should be the other way round
+        # so that the intersect method uses is_subset for evaluation.
+        if self.intersect(other) == self:
+            return True
+
+    def _eval_is_subset(self, other):
+        '''Returns a fuzzy bool for whether self is a subset of other.'''
+        return None
+
+    def _eval_is_superset(self, other):
+        '''Returns a fuzzy bool for whether self is a subset of other.'''
+        return None
+
+    # This should be deprecated:
+    def issubset(self, other):
+        """
+        Alias for :meth:`is_subset()`
+        """
+        return self.is_subset(other)
+
+    def is_proper_subset(self, other):
+        """
+        Returns True if ``self`` is a proper subset of ``other``.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval
+        >>> Interval(0, 0.5).is_proper_subset(Interval(0, 1))
+        True
+        >>> Interval(0, 1).is_proper_subset(Interval(0, 1))
+        False
+
+        """
+        if isinstance(other, Set):
+            return self != other and self.is_subset(other)
+        else:
+            raise ValueError("Unknown argument '%s'" % other)
+
+    def is_superset(self, other):
+        """
+        Returns True if ``self`` is a superset of ``other``.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval
+        >>> Interval(0, 0.5).is_superset(Interval(0, 1))
+        False
+        >>> Interval(0, 1).is_superset(Interval(0, 1, left_open=True))
+        True
+
+        """
+        if isinstance(other, Set):
+            return other.is_subset(self)
+        else:
+            raise ValueError("Unknown argument '%s'" % other)
+
+    # This should be deprecated:
+    def issuperset(self, other):
+        """
+        Alias for :meth:`is_superset()`
+        """
+        return self.is_superset(other)
+
+    def is_proper_superset(self, other):
+        """
+        Returns True if ``self`` is a proper superset of ``other``.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval
+        >>> Interval(0, 1).is_proper_superset(Interval(0, 0.5))
+        True
+        >>> Interval(0, 1).is_proper_superset(Interval(0, 1))
+        False
+
+        """
+        if isinstance(other, Set):
+            return self != other and self.is_superset(other)
+        else:
+            raise ValueError("Unknown argument '%s'" % other)
+
+    def _eval_powerset(self):
+        from .powerset import PowerSet
+        return PowerSet(self)
+
+    def powerset(self):
+        """
+        Find the Power set of ``self``.
+
+        Examples
+        ========
+
+        >>> from sympy import EmptySet, FiniteSet, Interval
+
+        A power set of an empty set:
+
+        >>> A = EmptySet
+        >>> A.powerset()
+        {EmptySet}
+
+        A power set of a finite set:
+
+        >>> A = FiniteSet(1, 2)
+        >>> a, b, c = FiniteSet(1), FiniteSet(2), FiniteSet(1, 2)
+        >>> A.powerset() == FiniteSet(a, b, c, EmptySet)
+        True
+
+        A power set of an interval:
+
+        >>> Interval(1, 2).powerset()
+        PowerSet(Interval(1, 2))
+
+        References
+        ==========
+
+        .. [1] https://en.wikipedia.org/wiki/Power_set
+
+        """
+        return self._eval_powerset()
+
+    @property
+    def measure(self):
+        """
+        The (Lebesgue) measure of ``self``.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval, Union
+        >>> Interval(0, 1).measure
+        1
+        >>> Union(Interval(0, 1), Interval(2, 3)).measure
+        2
+
+        """
+        return self._measure
+
+    @property
+    def kind(self):
+        """
+        The kind of a Set
+
+        Explanation
+        ===========
+
+        Any :class:`Set` will have kind :class:`SetKind` which is
+        parametrised by the kind of the elements of the set. For example
+        most sets are sets of numbers and will have kind
+        ``SetKind(NumberKind)``. If elements of sets are different in kind than
+        their kind will ``SetKind(UndefinedKind)``. See
+        :class:`sympy.core.kind.Kind` for an explanation of the kind system.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval, Matrix, FiniteSet, EmptySet, ProductSet, PowerSet
+
+        >>> FiniteSet(Matrix([1, 2])).kind
+        SetKind(MatrixKind(NumberKind))
+
+        >>> Interval(1, 2).kind
+        SetKind(NumberKind)
+
+        >>> EmptySet.kind
+        SetKind()
+
+        A :class:`sympy.sets.powerset.PowerSet` is a set of sets:
+
+        >>> PowerSet({1, 2, 3}).kind
+        SetKind(SetKind(NumberKind))
+
+        A :class:`ProductSet` represents the set of tuples of elements of
+        other sets. Its kind is :class:`sympy.core.containers.TupleKind`
+        parametrised by the kinds of the elements of those sets:
+
+        >>> p = ProductSet(FiniteSet(1, 2), FiniteSet(3, 4))
+        >>> list(p)
+        [(1, 3), (2, 3), (1, 4), (2, 4)]
+        >>> p.kind
+        SetKind(TupleKind(NumberKind, NumberKind))
+
+        When all elements of the set do not have same kind, the kind
+        will be returned as ``SetKind(UndefinedKind)``:
+
+        >>> FiniteSet(0, Matrix([1, 2])).kind
+        SetKind(UndefinedKind)
+
+        The kind of the elements of a set are given by the ``element_kind``
+        attribute of ``SetKind``:
+
+        >>> Interval(1, 2).kind.element_kind
+        NumberKind
+
+        See Also
+        ========
+
+        NumberKind
+        sympy.core.kind.UndefinedKind
+        sympy.core.containers.TupleKind
+        MatrixKind
+        sympy.matrices.expressions.sets.MatrixSet
+        sympy.sets.conditionset.ConditionSet
+        Rationals
+        Naturals
+        Integers
+        sympy.sets.fancysets.ImageSet
+        sympy.sets.fancysets.Range
+        sympy.sets.fancysets.ComplexRegion
+        sympy.sets.powerset.PowerSet
+        sympy.sets.sets.ProductSet
+        sympy.sets.sets.Interval
+        sympy.sets.sets.Union
+        sympy.sets.sets.Intersection
+        sympy.sets.sets.Complement
+        sympy.sets.sets.EmptySet
+        sympy.sets.sets.UniversalSet
+        sympy.sets.sets.FiniteSet
+        sympy.sets.sets.SymmetricDifference
+        sympy.sets.sets.DisjointUnion
+        """
+        return self._kind()
+
+    @property
+    def boundary(self):
+        """
+        The boundary or frontier of a set.
+
+        Explanation
+        ===========
+
+        A point x is on the boundary of a set S if
+
+        1.  x is in the closure of S.
+            I.e. Every neighborhood of x contains a point in S.
+        2.  x is not in the interior of S.
+            I.e. There does not exist an open set centered on x contained
+            entirely within S.
+
+        There are the points on the outer rim of S.  If S is open then these
+        points need not actually be contained within S.
+
+        For example, the boundary of an interval is its start and end points.
+        This is true regardless of whether or not the interval is open.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval
+        >>> Interval(0, 1).boundary
+        {0, 1}
+        >>> Interval(0, 1, True, False).boundary
+        {0, 1}
+        """
+        return self._boundary
+
+    @property
+    def is_open(self):
+        """
+        Property method to check whether a set is open.
+
+        Explanation
+        ===========
+
+        A set is open if and only if it has an empty intersection with its
+        boundary. In particular, a subset A of the reals is open if and only
+        if each one of its points is contained in an open interval that is a
+        subset of A.
+
+        Examples
+        ========
+        >>> from sympy import S
+        >>> S.Reals.is_open
+        True
+        >>> S.Rationals.is_open
+        False
+        """
+        return Intersection(self, self.boundary).is_empty
+
+    @property
+    def is_closed(self):
+        """
+        A property method to check whether a set is closed.
+
+        Explanation
+        ===========
+
+        A set is closed if its complement is an open set. The closedness of a
+        subset of the reals is determined with respect to R and its standard
+        topology.
+
+        Examples
+        ========
+        >>> from sympy import Interval
+        >>> Interval(0, 1).is_closed
+        True
+        """
+        return self.boundary.is_subset(self)
+
+    @property
+    def closure(self):
+        """
+        Property method which returns the closure of a set.
+        The closure is defined as the union of the set itself and its
+        boundary.
+
+        Examples
+        ========
+        >>> from sympy import S, Interval
+        >>> S.Reals.closure
+        Reals
+        >>> Interval(0, 1).closure
+        Interval(0, 1)
+        """
+        return self + self.boundary
+
+    @property
+    def interior(self):
+        """
+        Property method which returns the interior of a set.
+        The interior of a set S consists all points of S that do not
+        belong to the boundary of S.
+
+        Examples
+        ========
+        >>> from sympy import Interval
+        >>> Interval(0, 1).interior
+        Interval.open(0, 1)
+        >>> Interval(0, 1).boundary.interior
+        EmptySet
+        """
+        return self - self.boundary
+
+    @property
+    def _boundary(self):
+        raise NotImplementedError()
+
+    @property
+    def _measure(self):
+        raise NotImplementedError("(%s)._measure" % self)
+
+    def _kind(self):
+        return SetKind(UndefinedKind)
+
+    def _eval_evalf(self, prec):
+        dps = prec_to_dps(prec)
+        return self.func(*[arg.evalf(n=dps) for arg in self.args])
+
+    @sympify_return([('other', 'Set')], NotImplemented)
+    def __add__(self, other):
+        return self.union(other)
+
+    @sympify_return([('other', 'Set')], NotImplemented)
+    def __or__(self, other):
+        return self.union(other)
+
+    @sympify_return([('other', 'Set')], NotImplemented)
+    def __and__(self, other):
+        return self.intersect(other)
+
+    @sympify_return([('other', 'Set')], NotImplemented)
+    def __mul__(self, other):
+        return ProductSet(self, other)
+
+    @sympify_return([('other', 'Set')], NotImplemented)
+    def __xor__(self, other):
+        return SymmetricDifference(self, other)
+
+    @sympify_return([('exp', Expr)], NotImplemented)
+    def __pow__(self, exp):
+        if not (exp.is_Integer and exp >= 0):
+            raise ValueError("%s: Exponent must be a positive Integer" % exp)
+        return ProductSet(*[self]*exp)
+
+    @sympify_return([('other', 'Set')], NotImplemented)
+    def __sub__(self, other):
+        return Complement(self, other)
+
+    def __contains__(self, other):
+        other = _sympify(other)
+        c = self._contains(other)
+        b = tfn[c]
+        if b is None:
+            # x in y must evaluate to T or F; to entertain a None
+            # result with Set use y.contains(x)
+            raise TypeError('did not evaluate to a bool: %r' % c)
+        return b
+
+
+class ProductSet(Set):
+    """
+    Represents a Cartesian Product of Sets.
+
+    Explanation
+    ===========
+
+    Returns a Cartesian product given several sets as either an iterable
+    or individual arguments.
+
+    Can use ``*`` operator on any sets for convenient shorthand.
+
+    Examples
+    ========
+
+    >>> from sympy import Interval, FiniteSet, ProductSet
+    >>> I = Interval(0, 5); S = FiniteSet(1, 2, 3)
+    >>> ProductSet(I, S)
+    ProductSet(Interval(0, 5), {1, 2, 3})
+
+    >>> (2, 2) in ProductSet(I, S)
+    True
+
+    >>> Interval(0, 1) * Interval(0, 1) # The unit square
+    ProductSet(Interval(0, 1), Interval(0, 1))
+
+    >>> coin = FiniteSet('H', 'T')
+    >>> set(coin**2)
+    {(H, H), (H, T), (T, H), (T, T)}
+
+    The Cartesian product is not commutative or associative e.g.:
+
+    >>> I*S == S*I
+    False
+    >>> (I*I)*I == I*(I*I)
+    False
+
+    Notes
+    =====
+
+    - Passes most operations down to the argument sets
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Cartesian_product
+    """
+    is_ProductSet = True
+
+    def __new__(cls, *sets, **assumptions):
+        if len(sets) == 1 and iterable(sets[0]) and not isinstance(sets[0], (Set, set)):
+            sympy_deprecation_warning(
+                """
+ProductSet(iterable) is deprecated. Use ProductSet(*iterable) instead.
+                """,
+                deprecated_since_version="1.5",
+                active_deprecations_target="deprecated-productset-iterable",
+            )
+            sets = tuple(sets[0])
+
+        sets = [sympify(s) for s in sets]
+
+        if not all(isinstance(s, Set) for s in sets):
+            raise TypeError("Arguments to ProductSet should be of type Set")
+
+        # Nullary product of sets is *not* the empty set
+        if len(sets) == 0:
+            return FiniteSet(())
+
+        if S.EmptySet in sets:
+            return S.EmptySet
+
+        return Basic.__new__(cls, *sets, **assumptions)
+
+    @property
+    def sets(self):
+        return self.args
+
+    def flatten(self):
+        def _flatten(sets):
+            for s in sets:
+                if s.is_ProductSet:
+                    yield from _flatten(s.sets)
+                else:
+                    yield s
+        return ProductSet(*_flatten(self.sets))
+
+
+
+    def _contains(self, element):
+        """
+        ``in`` operator for ProductSets.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval
+        >>> (2, 3) in Interval(0, 5) * Interval(0, 5)
+        True
+
+        >>> (10, 10) in Interval(0, 5) * Interval(0, 5)
+        False
+
+        Passes operation on to constituent sets
+        """
+        if element.is_Symbol:
+            return None
+
+        if not isinstance(element, Tuple) or len(element) != len(self.sets):
+            return S.false
+
+        return And(*[s.contains(e) for s, e in zip(self.sets, element)])
+
+    def as_relational(self, *symbols):
+        symbols = [_sympify(s) for s in symbols]
+        if len(symbols) != len(self.sets) or not all(
+                i.is_Symbol for i in symbols):
+            raise ValueError(
+                'number of symbols must match the number of sets')
+        return And(*[s.as_relational(i) for s, i in zip(self.sets, symbols)])
+
+    @property
+    def _boundary(self):
+        return Union(*(ProductSet(*(b + b.boundary if i != j else b.boundary
+                                for j, b in enumerate(self.sets)))
+                                for i, a in enumerate(self.sets)))
+
+    @property
+    def is_iterable(self):
+        """
+        A property method which tests whether a set is iterable or not.
+        Returns True if set is iterable, otherwise returns False.
+
+        Examples
+        ========
+
+        >>> from sympy import FiniteSet, Interval
+        >>> I = Interval(0, 1)
+        >>> A = FiniteSet(1, 2, 3, 4, 5)
+        >>> I.is_iterable
+        False
+        >>> A.is_iterable
+        True
+
+        """
+        return all(set.is_iterable for set in self.sets)
+
+    def __iter__(self):
+        """
+        A method which implements is_iterable property method.
+        If self.is_iterable returns True (both constituent sets are iterable),
+        then return the Cartesian Product. Otherwise, raise TypeError.
+        """
+        return iproduct(*self.sets)
+
+    @property
+    def is_empty(self):
+        return fuzzy_or(s.is_empty for s in self.sets)
+
+    @property
+    def is_finite_set(self):
+        all_finite = fuzzy_and(s.is_finite_set for s in self.sets)
+        return fuzzy_or([self.is_empty, all_finite])
+
+    @property
+    def _measure(self):
+        measure = 1
+        for s in self.sets:
+            measure *= s.measure
+        return measure
+
+    def _kind(self):
+        return SetKind(TupleKind(*(i.kind.element_kind for i in self.args)))
+
+    def __len__(self):
+        return reduce(lambda a, b: a*b, (len(s) for s in self.args))
+
+    def __bool__(self):
+        return all(self.sets)
+
+
+class Interval(Set):
+    """
+    Represents a real interval as a Set.
+
+    Usage:
+        Returns an interval with end points ``start`` and ``end``.
+
+        For ``left_open=True`` (default ``left_open`` is ``False``) the interval
+        will be open on the left. Similarly, for ``right_open=True`` the interval
+        will be open on the right.
+
+    Examples
+    ========
+
+    >>> from sympy import Symbol, Interval
+    >>> Interval(0, 1)
+    Interval(0, 1)
+    >>> Interval.Ropen(0, 1)
+    Interval.Ropen(0, 1)
+    >>> Interval.Ropen(0, 1)
+    Interval.Ropen(0, 1)
+    >>> Interval.Lopen(0, 1)
+    Interval.Lopen(0, 1)
+    >>> Interval.open(0, 1)
+    Interval.open(0, 1)
+
+    >>> a = Symbol('a', real=True)
+    >>> Interval(0, a)
+    Interval(0, a)
+
+    Notes
+    =====
+    - Only real end points are supported
+    - ``Interval(a, b)`` with $a > b$ will return the empty set
+    - Use the ``evalf()`` method to turn an Interval into an mpmath
+      ``mpi`` interval instance
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Interval_%28mathematics%29
+    """
+    is_Interval = True
+
+    def __new__(cls, start, end, left_open=False, right_open=False):
+
+        start = _sympify(start)
+        end = _sympify(end)
+        left_open = _sympify(left_open)
+        right_open = _sympify(right_open)
+
+        if not all(isinstance(a, (type(true), type(false)))
+            for a in [left_open, right_open]):
+            raise NotImplementedError(
+                "left_open and right_open can have only true/false values, "
+                "got %s and %s" % (left_open, right_open))
+
+        # Only allow real intervals
+        if fuzzy_not(fuzzy_and(i.is_extended_real for i in (start, end, end-start))):
+            raise ValueError("Non-real intervals are not supported")
+
+        # evaluate if possible
+        if is_lt(end, start):
+            return S.EmptySet
+        elif (end - start).is_negative:
+            return S.EmptySet
+
+        if end == start and (left_open or right_open):
+            return S.EmptySet
+        if end == start and not (left_open or right_open):
+            if start is S.Infinity or start is S.NegativeInfinity:
+                return S.EmptySet
+            return FiniteSet(end)
+
+        # Make sure infinite interval end points are open.
+        if start is S.NegativeInfinity:
+            left_open = true
+        if end is S.Infinity:
+            right_open = true
+        if start == S.Infinity or end == S.NegativeInfinity:
+            return S.EmptySet
+
+        return Basic.__new__(cls, start, end, left_open, right_open)
+
+    @property
+    def start(self):
+        """
+        The left end point of the interval.
+
+        This property takes the same value as the ``inf`` property.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval
+        >>> Interval(0, 1).start
+        0
+
+        """
+        return self._args[0]
+
+    @property
+    def end(self):
+        """
+        The right end point of the interval.
+
+        This property takes the same value as the ``sup`` property.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval
+        >>> Interval(0, 1).end
+        1
+
+        """
+        return self._args[1]
+
+    @property
+    def left_open(self):
+        """
+        True if interval is left-open.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval
+        >>> Interval(0, 1, left_open=True).left_open
+        True
+        >>> Interval(0, 1, left_open=False).left_open
+        False
+
+        """
+        return self._args[2]
+
+    @property
+    def right_open(self):
+        """
+        True if interval is right-open.
+
+        Examples
+        ========
+
+        >>> from sympy import Interval
+        >>> Interval(0, 1, right_open=True).right_open
+        True
+        >>> Interval(0, 1, right_open=False).right_open
+        False
+
+        """
+        return self._args[3]
+
+    @classmethod
+    def open(cls, a, b):
+        """Return an interval including neither boundary."""
+        return cls(a, b, True, True)
+
+    @classmethod
+    def Lopen(cls, a, b):
+        """Return an interval not including the left boundary."""
+        return cls(a, b, True, False)
+
+    @classmethod
+    def Ropen(cls, a, b):
+        """Return an interval not including the right boundary."""
+        return cls(a, b, False, True)
+
+    @property
+    def _inf(self):
+        return self.start
+
+    @property
+    def _sup(self):
+        return self.end
+
+    @property
+    def left(self):
+        return self.start
+
+    @property
+    def right(self):
+        return self.end
+
+    @property
+    def is_empty(self):
+        if self.left_open or self.right_open:
+            cond = self.start >= self.end  # One/both bounds open
+        else:
+            cond = self.start > self.end  # Both bounds closed
+        return fuzzy_bool(cond)
+
+    @property
+    def is_finite_set(self):
+        return self.measure.is_zero
+
+    def _complement(self, other):
+        if other == S.Reals:
+            a = Interval(S.NegativeInfinity, self.start,
+                         True, not self.left_open)
+            b = Interval(self.end, S.Infinity, not self.right_open, True)
+            return Union(a, b)
+
+        if isinstance(other, FiniteSet):
+            nums = [m for m in other.args if m.is_number]
+            if nums == []:
+                return None
+
+        return Set._complement(self, other)
+
+    @property
+    def _boundary(self):
+        finite_points = [p for p in (self.start, self.end)
+                         if abs(p) != S.Infinity]
+        return FiniteSet(*finite_points)
+
+    def _contains(self, other):
+        if (not isinstance(other, Expr) or other is S.NaN
+            or other.is_real is False or other.has(S.ComplexInfinity)):
+                # if an expression has zoo it will be zoo or nan
+                # and neither of those is real
+                return false
+
+        if self.start is S.NegativeInfinity and self.end is S.Infinity:
+            if other.is_real is not None:
+                return tfn[other.is_real]
+
+        d = Dummy()
+        return self.as_relational(d).subs(d, other)
+
+    def as_relational(self, x):
+        """Rewrite an interval in terms of inequalities and logic operators."""
+        x = sympify(x)
+        if self.right_open:
+            right = x < self.end
+        else:
+            right = x <= self.end
+        if self.left_open:
+            left = self.start < x
+        else:
+            left = self.start <= x
+        return And(left, right)
+
+    @property
+    def _measure(self):
+        return self.end - self.start
+
+    def _kind(self):
+        return SetKind(NumberKind)
+
+    def to_mpi(self, prec=53):
+        return mpi(mpf(self.start._eval_evalf(prec)),
+            mpf(self.end._eval_evalf(prec)))
+
+    def _eval_evalf(self, prec):
+        return Interval(self.left._evalf(prec), self.right._evalf(prec),
+            left_open=self.left_open, right_open=self.right_open)
+
+    def _is_comparable(self, other):
+        is_comparable = self.start.is_comparable
+        is_comparable &= self.end.is_comparable
+        is_comparable &= other.start.is_comparable
+        is_comparable &= other.end.is_comparable
+
+        return is_comparable
+
+    @property
+    def is_left_unbounded(self):
+        """Return ``True`` if the left endpoint is negative infinity. """
+        return self.left is S.NegativeInfinity or self.left == Float("-inf")
+
+    @property
+    def is_right_unbounded(self):
+        """Return ``True`` if the right endpoint is positive infinity. """
+        return self.right is S.Infinity or self.right == Float("+inf")
+
+    def _eval_Eq(self, other):
+        if not isinstance(other, Interval):
+            if isinstance(other, FiniteSet):
+                return false
+            elif isinstance(other, Set):
+                return None
+            return false
+
+
+class Union(Set, LatticeOp):
+    """
+    Represents a union of sets as a :class:`Set`.
+
+    Examples
+    ========
+
+    >>> from sympy import Union, Interval
+    >>> Union(Interval(1, 2), Interval(3, 4))
+    Union(Interval(1, 2), Interval(3, 4))
+
+    The Union constructor will always try to merge overlapping intervals,
+    if possible. For example:
+
+    >>> Union(Interval(1, 2), Interval(2, 3))
+    Interval(1, 3)
+
+    See Also
+    ========
+
+    Intersection
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Union_%28set_theory%29
+    """
+    is_Union = True
+
+    @property
+    def identity(self):
+        return S.EmptySet
+
+    @property
+    def zero(self):
+        return S.UniversalSet
+
+    def __new__(cls, *args, **kwargs):
+        evaluate = kwargs.get('evaluate', global_parameters.evaluate)
+
+        # flatten inputs to merge intersections and iterables
+        args = _sympify(args)
+
+        # Reduce sets using known rules
+        if evaluate:
+            args = list(cls._new_args_filter(args))
+            return simplify_union(args)
+
+        args = list(ordered(args, Set._infimum_key))
+
+        obj = Basic.__new__(cls, *args)
+        obj._argset = frozenset(args)
+        return obj
+
+    @property
+    def args(self):
+        return self._args
+
+    def _complement(self, universe):
+        # DeMorgan's Law
+        return Intersection(s.complement(universe) for s in self.args)
+
+    @property
+    def _inf(self):
+        # We use Min so that sup is meaningful in combination with symbolic
+        # interval end points.
+        return Min(*[set.inf for set in self.args])
+
+    @property
+    def _sup(self):
+        # We use Max so that sup is meaningful in combination with symbolic
+        # end points.
+        return Max(*[set.sup for set in self.args])
+
+    @property
+    def is_empty(self):
+        return fuzzy_and(set.is_empty for set in self.args)
+
+    @property
+    def is_finite_set(self):
+        return fuzzy_and(set.is_finite_set for set in self.args)
+
+    @property
+    def _measure(self):
+        # Measure of a union is the sum of the measures of the sets minus
+        # the sum of their pairwise intersections plus the sum of their
+        # triple-wise intersections minus ... etc...
+
+        # Sets is a collection of intersections and a set of elementary
+        # sets which made up those intersections (called "sos" for set of sets)
+        # An example element might of this list might be:
+        #    ( {A,B,C}, A.intersect(B).intersect(C) )
+
+        # Start with just elementary sets (  ({A}, A), ({B}, B), ... )
+        # Then get and subtract (  ({A,B}, (A int B), ... ) while non-zero
+        sets = [(FiniteSet(s), s) for s in self.args]
+        measure = 0
+        parity = 1
+        while sets:
+            # Add up the measure of these sets and add or subtract it to total
+            measure += parity * sum(inter.measure for sos, inter in sets)
+
+            # For each intersection in sets, compute the intersection with every
+            # other set not already part of the intersection.
+            sets = ((sos + FiniteSet(newset), newset.intersect(intersection))
+                    for sos, intersection in sets for newset in self.args
+                    if newset not in sos)
+
+            # Clear out sets with no measure
+            sets = [(sos, inter) for sos, inter in sets if inter.measure != 0]
+
+            # Clear out duplicates
+            sos_list = []
+            sets_list = []
+            for _set in sets:
+                if _set[0] in sos_list:
+                    continue
+                else:
+                    sos_list.append(_set[0])
+                    sets_list.append(_set)
+            sets = sets_list
+
+            # Flip Parity - next time subtract/add if we added/subtracted here
+            parity *= -1
+        return measure
+
+    def _kind(self):
+        kinds = tuple(arg.kind for arg in self.args if arg is not S.EmptySet)
+        if not kinds:
+            return SetKind()
+        elif all(i == kinds[0] for i in kinds):
+            return kinds[0]
+        else:
+            return SetKind(UndefinedKind)
+
+    @property
+    def _boundary(self):
+        def boundary_of_set(i):
+            """ The boundary of set i minus interior of all other sets """
+            b = self.args[i].boundary
+            for j, a in enumerate(self.args):
+                if j != i:
+                    b = b - a.interior
+            return b
+        return Union(*map(boundary_of_set, range(len(self.args))))
+
+    def _contains(self, other):
+        return Or(*[s.contains(other) for s in self.args])
+
+    def is_subset(self, other):
+        return fuzzy_and(s.is_subset(other) for s in self.args)
+
+    def as_relational(self, symbol):
+        """Rewrite a Union in terms of equalities and logic operators. """
+        if (len(self.args) == 2 and
+                all(isinstance(i, Interval) for i in self.args)):
+            # optimization to give 3 args as (x > 1) & (x < 5) & Ne(x, 3)
+            # instead of as 4, ((1 <= x) & (x < 3)) | ((x <= 5) & (3 < x))
+            # XXX: This should be ideally be improved to handle any number of
+            # intervals and also not to assume that the intervals are in any
+            # particular sorted order.
+            a, b = self.args
+            if a.sup == b.inf and a.right_open and b.left_open:
+                mincond = symbol > a.inf if a.left_open else symbol >= a.inf
+                maxcond = symbol < b.sup if b.right_open else symbol <= b.sup
+                necond = Ne(symbol, a.sup)
+                return And(necond, mincond, maxcond)
+        return Or(*[i.as_relational(symbol) for i in self.args])
+
+    @property
+    def is_iterable(self):
+        return all(arg.is_iterable for arg in self.args)
+
+    def __iter__(self):
+        return roundrobin(*(iter(arg) for arg in self.args))
+
+
+class Intersection(Set, LatticeOp):
+    """
+    Represents an intersection of sets as a :class:`Set`.
+
+    Examples
+    ========
+
+    >>> from sympy import Intersection, Interval
+    >>> Intersection(Interval(1, 3), Interval(2, 4))
+    Interval(2, 3)
+
+    We often use the .intersect method
+
+    >>> Interval(1,3).intersect(Interval(2,4))
+    Interval(2, 3)
+
+    See Also
+    ========
+
+    Union
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Intersection_%28set_theory%29
+    """
+    is_Intersection = True
+
+    @property
+    def identity(self):
+        return S.UniversalSet
+
+    @property
+    def zero(self):
+        return S.EmptySet
+
+    def __new__(cls, *args , evaluate=None):
+        if evaluate is None:
+            evaluate = global_parameters.evaluate
+
+        # flatten inputs to merge intersections and iterables
+        args = list(ordered(set(_sympify(args))))
+
+        # Reduce sets using known rules
+        if evaluate:
+            args = list(cls._new_args_filter(args))
+            return simplify_intersection(args)
+
+        args = list(ordered(args, Set._infimum_key))
+
+        obj = Basic.__new__(cls, *args)
+        obj._argset = frozenset(args)
+        return obj
+
+    @property
+    def args(self):
+        return self._args
+
+    @property
+    def is_iterable(self):
+        return any(arg.is_iterable for arg in self.args)
+
+    @property
+    def is_finite_set(self):
+        if fuzzy_or(arg.is_finite_set for arg in self.args):
+            return True
+
+    def _kind(self):
+        kinds = tuple(arg.kind for arg in self.args if arg is not S.UniversalSet)
+        if not kinds:
+            return SetKind(UndefinedKind)
+        elif all(i == kinds[0] for i in kinds):
+            return kinds[0]
+        else:
+            return SetKind()
+
+    @property
+    def _inf(self):
+        raise NotImplementedError()
+
+    @property
+    def _sup(self):
+        raise NotImplementedError()
+
+    def _contains(self, other):
+        return And(*[set.contains(other) for set in self.args])
+
+    def __iter__(self):
+        sets_sift = sift(self.args, lambda x: x.is_iterable)
+
+        completed = False
+        candidates = sets_sift[True] + sets_sift[None]
+
+        finite_candidates, others = [], []
+        for candidate in candidates:
+            length = None
+            try:
+                length = len(candidate)
+            except TypeError:
+                others.append(candidate)
+
+            if length is not None:
+                finite_candidates.append(candidate)
+        finite_candidates.sort(key=len)
+
+        for s in finite_candidates + others:
+            other_sets = set(self.args) - {s}
+            other = Intersection(*other_sets, evaluate=False)
+            completed = True
+            for x in s:
+                try:
+                    if x in other:
+                        yield x
+                except TypeError:
+                    completed = False
+            if completed:
+                return
+
+        if not completed:
+            if not candidates:
+                raise TypeError("None of the constituent sets are iterable")
+            raise TypeError(
+                "The computation had not completed because of the "
+                "undecidable set membership is found in every candidates.")
+
+    @staticmethod
+    def _handle_finite_sets(args):
+        '''Simplify intersection of one or more FiniteSets and other sets'''
+
+        # First separate the FiniteSets from the others
+        fs_args, others = sift(args, lambda x: x.is_FiniteSet, binary=True)
+
+        # Let the caller handle intersection of non-FiniteSets
+        if not fs_args:
+            return
+
+        # Convert to Python sets and build the set of all elements
+        fs_sets = [set(fs) for fs in fs_args]
+        all_elements = reduce(lambda a, b: a | b, fs_sets, set())
+
+        # Extract elements that are definitely in or definitely not in the
+        # intersection. Here we check contains for all of args.
+        definite = set()
+        for e in all_elements:
+            inall = fuzzy_and(s.contains(e) for s in args)
+            if inall is True:
+                definite.add(e)
+            if inall is not None:
+                for s in fs_sets:
+                    s.discard(e)
+
+        # At this point all elements in all of fs_sets are possibly in the
+        # intersection. In some cases this is because they are definitely in
+        # the intersection of the finite sets but it's not clear if they are
+        # members of others. We might have {m, n}, {m}, and Reals where we
+        # don't know if m or n is real. We want to remove n here but it is
+        # possibly in because it might be equal to m. So what we do now is
+        # extract the elements that are definitely in the remaining finite
+        # sets iteratively until we end up with {n}, {}. At that point if we
+        # get any empty set all remaining elements are discarded.
+
+        fs_elements = reduce(lambda a, b: a | b, fs_sets, set())
+
+        # Need fuzzy containment testing
+        fs_symsets = [FiniteSet(*s) for s in fs_sets]
+
+        while fs_elements:
+            for e in fs_elements:
+                infs = fuzzy_and(s.contains(e) for s in fs_symsets)
+                if infs is True:
+                    definite.add(e)
+                if infs is not None:
+                    for n, s in enumerate(fs_sets):
+                        # Update Python set and FiniteSet
+                        if e in s:
+                            s.remove(e)
+                            fs_symsets[n] = FiniteSet(*s)
+                    fs_elements.remove(e)
+                    break
+            # If we completed the for loop without removing anything we are
+            # done so quit the outer while loop
+            else:
+                break
+
+        # If any of the sets of remainder elements is empty then we discard
+        # all of them for the intersection.
+        if not all(fs_sets):
+            fs_sets = [set()]
+
+        # Here we fold back the definitely included elements into each fs.
+        # Since they are definitely included they must have been members of
+        # each FiniteSet to begin with. We could instead fold these in with a
+        # Union at the end to get e.g. {3}|({x}&{y}) rather than {3,x}&{3,y}.
+        if definite:
+            fs_sets = [fs | definite for fs in fs_sets]
+
+        if fs_sets == [set()]:
+            return S.EmptySet
+
+        sets = [FiniteSet(*s) for s in fs_sets]
+
+        # Any set in others is redundant if it contains all the elements that
+        # are in the finite sets so we don't need it in the Intersection
+        all_elements = reduce(lambda a, b: a | b, fs_sets, set())
+        is_redundant = lambda o: all(fuzzy_bool(o.contains(e)) for e in all_elements)
+        others = [o for o in others if not is_redundant(o)]
+
+        if others:
+            rest = Intersection(*others)
+            # XXX: Maybe this shortcut should be at the beginning. For large
+            # FiniteSets it could much more efficient to process the other
+            # sets first...
+            if rest is S.EmptySet:
+                return S.EmptySet
+            # Flatten the Intersection
+            if rest.is_Intersection:
+                sets.extend(rest.args)
+            else:
+                sets.append(rest)
+
+        if len(sets) == 1:
+            return sets[0]
+        else:
+            return Intersection(*sets, evaluate=False)
+
+    def as_relational(self, symbol):
+        """Rewrite an Intersection in terms of equalities and logic operators"""
+        return And(*[set.as_relational(symbol) for set in self.args])
+
+
+class Complement(Set):
+    r"""Represents the set difference or relative complement of a set with
+    another set.
+
+    $$A - B = \{x \in A \mid x \notin B\}$$
+
+
+    Examples
+    ========
+
+    >>> from sympy import Complement, FiniteSet
+    >>> Complement(FiniteSet(0, 1, 2), FiniteSet(1))
+    {0, 2}
+
+    See Also
+    =========
+
+    Intersection, Union
+
+    References
+    ==========
+
+    .. [1] https://mathworld.wolfram.com/ComplementSet.html
+    """
+
+    is_Complement = True
+
+    def __new__(cls, a, b, evaluate=True):
+        a, b = map(_sympify, (a, b))
+        if evaluate:
+            return Complement.reduce(a, b)
+
+        return Basic.__new__(cls, a, b)
+
+    @staticmethod
+    def reduce(A, B):
+        """
+        Simplify a :class:`Complement`.
+
+        """
+        if B == S.UniversalSet or A.is_subset(B):
+            return S.EmptySet
+
+        if isinstance(B, Union):
+            return Intersection(*(s.complement(A) for s in B.args))
+
+        result = B._complement(A)
+        if result is not None:
+            return result
+        else:
+            return Complement(A, B, evaluate=False)
+
+    def _contains(self, other):
+        A = self.args[0]
+        B = self.args[1]
+        return And(A.contains(other), Not(B.contains(other)))
+
+    def as_relational(self, symbol):
+        """Rewrite a complement in terms of equalities and logic
+        operators"""
+        A, B = self.args
+
+        A_rel = A.as_relational(symbol)
+        B_rel = Not(B.as_relational(symbol))
+
+        return And(A_rel, B_rel)
+
+    def _kind(self):
+        return self.args[0].kind
+
+    @property
+    def is_iterable(self):
+        if self.args[0].is_iterable:
+            return True
+
+    @property
+    def is_finite_set(self):
+        A, B = self.args
+        a_finite = A.is_finite_set
+        if a_finite is True:
+            return True
+        elif a_finite is False and B.is_finite_set:
+            return False
+
+    def __iter__(self):
+        A, B = self.args
+        for a in A:
+            if a not in B:
+                    yield a
+            else:
+                continue
+
+
+class EmptySet(Set, metaclass=Singleton):
+    """
+    Represents the empty set. The empty set is available as a singleton
+    as ``S.EmptySet``.
+
+    Examples
+    ========
+
+    >>> from sympy import S, Interval
+    >>> S.EmptySet
+    EmptySet
+
+    >>> Interval(1, 2).intersect(S.EmptySet)
+    EmptySet
+
+    See Also
+    ========
+
+    UniversalSet
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Empty_set
+    """
+    is_empty = True
+    is_finite_set = True
+    is_FiniteSet = True
+
+    @property  # type: ignore
+    @deprecated(
+        """
+        The is_EmptySet attribute of Set objects is deprecated.
+        Use 's is S.EmptySet" or 's.is_empty' instead.
+        """,
+        deprecated_since_version="1.5",
+        active_deprecations_target="deprecated-is-emptyset",
+    )
+    def is_EmptySet(self):
+        return True
+
+    @property
+    def _measure(self):
+        return 0
+
+    def _contains(self, other):
+        return false
+
+    def as_relational(self, symbol):
+        return false
+
+    def __len__(self):
+        return 0
+
+    def __iter__(self):
+        return iter([])
+
+    def _eval_powerset(self):
+        return FiniteSet(self)
+
+    @property
+    def _boundary(self):
+        return self
+
+    def _complement(self, other):
+        return other
+
+    def _kind(self):
+        return SetKind()
+
+    def _symmetric_difference(self, other):
+        return other
+
+
+class UniversalSet(Set, metaclass=Singleton):
+    """
+    Represents the set of all things.
+    The universal set is available as a singleton as ``S.UniversalSet``.
+
+    Examples
+    ========
+
+    >>> from sympy import S, Interval
+    >>> S.UniversalSet
+    UniversalSet
+
+    >>> Interval(1, 2).intersect(S.UniversalSet)
+    Interval(1, 2)
+
+    See Also
+    ========
+
+    EmptySet
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Universal_set
+    """
+
+    is_UniversalSet = True
+    is_empty = False
+    is_finite_set = False
+
+    def _complement(self, other):
+        return S.EmptySet
+
+    def _symmetric_difference(self, other):
+        return other
+
+    @property
+    def _measure(self):
+        return S.Infinity
+
+    def _kind(self):
+        return SetKind(UndefinedKind)
+
+    def _contains(self, other):
+        return true
+
+    def as_relational(self, symbol):
+        return true
+
+    @property
+    def _boundary(self):
+        return S.EmptySet
+
+
+class FiniteSet(Set):
+    """
+    Represents a finite set of Sympy expressions.
+
+    Examples
+    ========
+
+    >>> from sympy import FiniteSet, Symbol, Interval, Naturals0
+    >>> FiniteSet(1, 2, 3, 4)
+    {1, 2, 3, 4}
+    >>> 3 in FiniteSet(1, 2, 3, 4)
+    True
+    >>> FiniteSet(1, (1, 2), Symbol('x'))
+    {1, x, (1, 2)}
+    >>> FiniteSet(Interval(1, 2), Naturals0, {1, 2})
+    FiniteSet({1, 2}, Interval(1, 2), Naturals0)
+    >>> members = [1, 2, 3, 4]
+    >>> f = FiniteSet(*members)
+    >>> f
+    {1, 2, 3, 4}
+    >>> f - FiniteSet(2)
+    {1, 3, 4}
+    >>> f + FiniteSet(2, 5)
+    {1, 2, 3, 4, 5}
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Finite_set
+    """
+    is_FiniteSet = True
+    is_iterable = True
+    is_empty = False
+    is_finite_set = True
+
+    def __new__(cls, *args, **kwargs):
+        evaluate = kwargs.get('evaluate', global_parameters.evaluate)
+        if evaluate:
+            args = list(map(sympify, args))
+
+            if len(args) == 0:
+                return S.EmptySet
+        else:
+            args = list(map(sympify, args))
+
+        # keep the form of the first canonical arg
+        dargs = {}
+        for i in reversed(list(ordered(args))):
+            if i.is_Symbol:
+                dargs[i] = i
+            else:
+                try:
+                    dargs[i.as_dummy()] = i
+                except TypeError:
+                    # e.g. i = class without args like `Interval`
+                    dargs[i] = i
+        _args_set = set(dargs.values())
+        args = list(ordered(_args_set, Set._infimum_key))
+        obj = Basic.__new__(cls, *args)
+        obj._args_set = _args_set
+        return obj
+
+
+    def __iter__(self):
+        return iter(self.args)
+
+    def _complement(self, other):
+        if isinstance(other, Interval):
+            # Splitting in sub-intervals is only done for S.Reals;
+            # other cases that need splitting will first pass through
+            # Set._complement().
+            nums, syms = [], []
+            for m in self.args:
+                if m.is_number and m.is_real:
+                    nums.append(m)
+                elif m.is_real == False:
+                    pass  # drop non-reals
+                else:
+                    syms.append(m)  # various symbolic expressions
+            if other == S.Reals and nums != []:
+                nums.sort()
+                intervals = []  # Build up a list of intervals between the elements
+                intervals += [Interval(S.NegativeInfinity, nums[0], True, True)]
+                for a, b in zip(nums[:-1], nums[1:]):
+                    intervals.append(Interval(a, b, True, True))  # both open
+                intervals.append(Interval(nums[-1], S.Infinity, True, True))
+                if syms != []:
+                    return Complement(Union(*intervals, evaluate=False),
+                            FiniteSet(*syms), evaluate=False)
+                else:
+                    return Union(*intervals, evaluate=False)
+            elif nums == []:  # no splitting necessary or possible:
+                if syms:
+                    return Complement(other, FiniteSet(*syms), evaluate=False)
+                else:
+                    return other
+
+        elif isinstance(other, FiniteSet):
+            unk = []
+            for i in self:
+                c = sympify(other.contains(i))
+                if c is not S.true and c is not S.false:
+                    unk.append(i)
+            unk = FiniteSet(*unk)
+            if unk == self:
+                return
+            not_true = []
+            for i in other:
+                c = sympify(self.contains(i))
+                if c is not S.true:
+                    not_true.append(i)
+            return Complement(FiniteSet(*not_true), unk)
+
+        return Set._complement(self, other)
+
+    def _contains(self, other):
+        """
+        Tests whether an element, other, is in the set.
+
+        Explanation
+        ===========
+
+        The actual test is for mathematical equality (as opposed to
+        syntactical equality). In the worst case all elements of the
+        set must be checked.
+
+        Examples
+        ========
+
+        >>> from sympy import FiniteSet
+        >>> 1 in FiniteSet(1, 2)
+        True
+        >>> 5 in FiniteSet(1, 2)
+        False
+
+        """
+        if other in self._args_set:
+            return S.true
+        else:
+            # evaluate=True is needed to override evaluate=False context;
+            # we need Eq to do the evaluation
+            return Or(*[Eq(e, other, evaluate=True) for e in self.args])
+
+    def _eval_is_subset(self, other):
+        return fuzzy_and(other._contains(e) for e in self.args)
+
+    @property
+    def _boundary(self):
+        return self
+
+    @property
+    def _inf(self):
+        return Min(*self)
+
+    @property
+    def _sup(self):
+        return Max(*self)
+
+    @property
+    def measure(self):
+        return 0
+
+    def _kind(self):
+        if not self.args:
+            return SetKind()
+        elif all(i.kind == self.args[0].kind for i in self.args):
+            return SetKind(self.args[0].kind)
+        else:
+            return SetKind(UndefinedKind)
+
+    def __len__(self):
+        return len(self.args)
+
+    def as_relational(self, symbol):
+        """Rewrite a FiniteSet in terms of equalities and logic operators. """
+        return Or(*[Eq(symbol, elem) for elem in self])
+
+    def compare(self, other):
+        return (hash(self) - hash(other))
+
+    def _eval_evalf(self, prec):
+        dps = prec_to_dps(prec)
+        return FiniteSet(*[elem.evalf(n=dps) for elem in self])
+
+    def _eval_simplify(self, **kwargs):
+        from sympy.simplify import simplify
+        return FiniteSet(*[simplify(elem, **kwargs) for elem in self])
+
+    @property
+    def _sorted_args(self):
+        return self.args
+
+    def _eval_powerset(self):
+        return self.func(*[self.func(*s) for s in subsets(self.args)])
+
+    def _eval_rewrite_as_PowerSet(self, *args, **kwargs):
+        """Rewriting method for a finite set to a power set."""
+        from .powerset import PowerSet
+
+        is2pow = lambda n: bool(n and not n & (n - 1))
+        if not is2pow(len(self)):
+            return None
+
+        fs_test = lambda arg: isinstance(arg, Set) and arg.is_FiniteSet
+        if not all(fs_test(arg) for arg in args):
+            return None
+
+        biggest = max(args, key=len)
+        for arg in subsets(biggest.args):
+            arg_set = FiniteSet(*arg)
+            if arg_set not in args:
+                return None
+        return PowerSet(biggest)
+
+    def __ge__(self, other):
+        if not isinstance(other, Set):
+            raise TypeError("Invalid comparison of set with %s" % func_name(other))
+        return other.is_subset(self)
+
+    def __gt__(self, other):
+        if not isinstance(other, Set):
+            raise TypeError("Invalid comparison of set with %s" % func_name(other))
+        return self.is_proper_superset(other)
+
+    def __le__(self, other):
+        if not isinstance(other, Set):
+            raise TypeError("Invalid comparison of set with %s" % func_name(other))
+        return self.is_subset(other)
+
+    def __lt__(self, other):
+        if not isinstance(other, Set):
+            raise TypeError("Invalid comparison of set with %s" % func_name(other))
+        return self.is_proper_subset(other)
+
+    def __eq__(self, other):
+        if isinstance(other, (set, frozenset)):
+            return self._args_set == other
+        return super().__eq__(other)
+
+    __hash__ : Callable[[Basic], Any] = Basic.__hash__
+
+_sympy_converter[set] = lambda x: FiniteSet(*x)
+_sympy_converter[frozenset] = lambda x: FiniteSet(*x)
+
+
+class SymmetricDifference(Set):
+    """Represents the set of elements which are in either of the
+    sets and not in their intersection.
+
+    Examples
+    ========
+
+    >>> from sympy import SymmetricDifference, FiniteSet
+    >>> SymmetricDifference(FiniteSet(1, 2, 3), FiniteSet(3, 4, 5))
+    {1, 2, 4, 5}
+
+    See Also
+    ========
+
+    Complement, Union
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Symmetric_difference
+    """
+
+    is_SymmetricDifference = True
+
+    def __new__(cls, a, b, evaluate=True):
+        if evaluate:
+            return SymmetricDifference.reduce(a, b)
+
+        return Basic.__new__(cls, a, b)
+
+    @staticmethod
+    def reduce(A, B):
+        result = B._symmetric_difference(A)
+        if result is not None:
+            return result
+        else:
+            return SymmetricDifference(A, B, evaluate=False)
+
+    def as_relational(self, symbol):
+        """Rewrite a symmetric_difference in terms of equalities and
+        logic operators"""
+        A, B = self.args
+
+        A_rel = A.as_relational(symbol)
+        B_rel = B.as_relational(symbol)
+
+        return Xor(A_rel, B_rel)
+
+    @property
+    def is_iterable(self):
+        if all(arg.is_iterable for arg in self.args):
+            return True
+
+    def __iter__(self):
+
+        args = self.args
+        union = roundrobin(*(iter(arg) for arg in args))
+
+        for item in union:
+            count = 0
+            for s in args:
+                if item in s:
+                    count += 1
+
+            if count % 2 == 1:
+                yield item
+
+
+
+class DisjointUnion(Set):
+    """ Represents the disjoint union (also known as the external disjoint union)
+    of a finite number of sets.
+
+    Examples
+    ========
+
+    >>> from sympy import DisjointUnion, FiniteSet, Interval, Union, Symbol
+    >>> A = FiniteSet(1, 2, 3)
+    >>> B = Interval(0, 5)
+    >>> DisjointUnion(A, B)
+    DisjointUnion({1, 2, 3}, Interval(0, 5))
+    >>> DisjointUnion(A, B).rewrite(Union)
+    Union(ProductSet({1, 2, 3}, {0}), ProductSet(Interval(0, 5), {1}))
+    >>> C = FiniteSet(Symbol('x'), Symbol('y'), Symbol('z'))
+    >>> DisjointUnion(C, C)
+    DisjointUnion({x, y, z}, {x, y, z})
+    >>> DisjointUnion(C, C).rewrite(Union)
+    ProductSet({x, y, z}, {0, 1})
+
+    References
+    ==========
+
+    https://en.wikipedia.org/wiki/Disjoint_union
+    """
+
+    def __new__(cls, *sets):
+        dj_collection = []
+        for set_i in sets:
+            if isinstance(set_i, Set):
+                dj_collection.append(set_i)
+            else:
+                raise TypeError("Invalid input: '%s', input args \
+                    to DisjointUnion must be Sets" % set_i)
+        obj = Basic.__new__(cls, *dj_collection)
+        return obj
+
+    @property
+    def sets(self):
+        return self.args
+
+    @property
+    def is_empty(self):
+        return fuzzy_and(s.is_empty for s in self.sets)
+
+    @property
+    def is_finite_set(self):
+        all_finite = fuzzy_and(s.is_finite_set for s in self.sets)
+        return fuzzy_or([self.is_empty, all_finite])
+
+    @property
+    def is_iterable(self):
+        if self.is_empty:
+            return False
+        iter_flag = True
+        for set_i in self.sets:
+            if not set_i.is_empty:
+                iter_flag = iter_flag and set_i.is_iterable
+        return iter_flag
+
+    def _eval_rewrite_as_Union(self, *sets, **kwargs):
+        """
+        Rewrites the disjoint union as the union of (``set`` x {``i``})
+        where ``set`` is the element in ``sets`` at index = ``i``
+        """
+
+        dj_union = S.EmptySet
+        index = 0
+        for set_i in sets:
+            if isinstance(set_i, Set):
+                cross = ProductSet(set_i, FiniteSet(index))
+                dj_union = Union(dj_union, cross)
+                index = index + 1
+        return dj_union
+
+    def _contains(self, element):
+        """
+        ``in`` operator for DisjointUnion
+
+        Examples
+        ========
+
+        >>> from sympy import Interval, DisjointUnion
+        >>> D = DisjointUnion(Interval(0, 1), Interval(0, 2))
+        >>> (0.5, 0) in D
+        True
+        >>> (0.5, 1) in D
+        True
+        >>> (1.5, 0) in D
+        False
+        >>> (1.5, 1) in D
+        True
+
+        Passes operation on to constituent sets
+        """
+        if not isinstance(element, Tuple) or len(element) != 2:
+            return S.false
+
+        if not element[1].is_Integer:
+            return S.false
+
+        if element[1] >= len(self.sets) or element[1] < 0:
+            return S.false
+
+        return self.sets[element[1]]._contains(element[0])
+
+    def _kind(self):
+        if not self.args:
+            return SetKind()
+        elif all(i.kind == self.args[0].kind for i in self.args):
+            return self.args[0].kind
+        else:
+            return SetKind(UndefinedKind)
+
+    def __iter__(self):
+        if self.is_iterable:
+
+            iters = []
+            for i, s in enumerate(self.sets):
+                iters.append(iproduct(s, {Integer(i)}))
+
+            return iter(roundrobin(*iters))
+        else:
+            raise ValueError("'%s' is not iterable." % self)
+
+    def __len__(self):
+        """
+        Returns the length of the disjoint union, i.e., the number of elements in the set.
+
+        Examples
+        ========
+
+        >>> from sympy import FiniteSet, DisjointUnion, EmptySet
+        >>> D1 = DisjointUnion(FiniteSet(1, 2, 3, 4), EmptySet, FiniteSet(3, 4, 5))
+        >>> len(D1)
+        7
+        >>> D2 = DisjointUnion(FiniteSet(3, 5, 7), EmptySet, FiniteSet(3, 5, 7))
+        >>> len(D2)
+        6
+        >>> D3 = DisjointUnion(EmptySet, EmptySet)
+        >>> len(D3)
+        0
+
+        Adds up the lengths of the constituent sets.
+        """
+
+        if self.is_finite_set:
+            size = 0
+            for set in self.sets:
+                size += len(set)
+            return size
+        else:
+            raise ValueError("'%s' is not a finite set." % self)
+
+
+def imageset(*args):
+    r"""
+    Return an image of the set under transformation ``f``.
+
+    Explanation
+    ===========
+
+    If this function cannot compute the image, it returns an
+    unevaluated ImageSet object.
+
+    .. math::
+        \{ f(x) \mid x \in \mathrm{self} \}
+
+    Examples
+    ========
+
+    >>> from sympy import S, Interval, imageset, sin, Lambda
+    >>> from sympy.abc import x
+
+    >>> imageset(x, 2*x, Interval(0, 2))
+    Interval(0, 4)
+
+    >>> imageset(lambda x: 2*x, Interval(0, 2))
+    Interval(0, 4)
+
+    >>> imageset(Lambda(x, sin(x)), Interval(-2, 1))
+    ImageSet(Lambda(x, sin(x)), Interval(-2, 1))
+
+    >>> imageset(sin, Interval(-2, 1))
+    ImageSet(Lambda(x, sin(x)), Interval(-2, 1))
+    >>> imageset(lambda y: x + y, Interval(-2, 1))
+    ImageSet(Lambda(y, x + y), Interval(-2, 1))
+
+    Expressions applied to the set of Integers are simplified
+    to show as few negatives as possible and linear expressions
+    are converted to a canonical form. If this is not desirable
+    then the unevaluated ImageSet should be used.
+
+    >>> imageset(x, -2*x + 5, S.Integers)
+    ImageSet(Lambda(x, 2*x + 1), Integers)
+
+    See Also
+    ========
+
+    sympy.sets.fancysets.ImageSet
+
+    """
+    from .fancysets import ImageSet
+    from .setexpr import set_function
+
+    if len(args) < 2:
+        raise ValueError('imageset expects at least 2 args, got: %s' % len(args))
+
+    if isinstance(args[0], (Symbol, tuple)) and len(args) > 2:
+        f = Lambda(args[0], args[1])
+        set_list = args[2:]
+    else:
+        f = args[0]
+        set_list = args[1:]
+
+    if isinstance(f, Lambda):
+        pass
+    elif callable(f):
+        nargs = getattr(f, 'nargs', {})
+        if nargs:
+            if len(nargs) != 1:
+                raise NotImplementedError(filldedent('''
+                    This function can take more than 1 arg
+                    but the potentially complicated set input
+                    has not been analyzed at this point to
+                    know its dimensions. TODO
+                    '''))
+            N = nargs.args[0]
+            if N == 1:
+                s = 'x'
+            else:
+                s = [Symbol('x%i' % i) for i in range(1, N + 1)]
+        else:
+            s = inspect.signature(f).parameters
+
+        dexpr = _sympify(f(*[Dummy() for i in s]))
+        var = tuple(uniquely_named_symbol(
+            Symbol(i), dexpr) for i in s)
+        f = Lambda(var, f(*var))
+    else:
+        raise TypeError(filldedent('''
+            expecting lambda, Lambda, or FunctionClass,
+            not \'%s\'.''' % func_name(f)))
+
+    if any(not isinstance(s, Set) for s in set_list):
+        name = [func_name(s) for s in set_list]
+        raise ValueError(
+            'arguments after mapping should be sets, not %s' % name)
+
+    if len(set_list) == 1:
+        set = set_list[0]
+        try:
+            # TypeError if arg count != set dimensions
+            r = set_function(f, set)
+            if r is None:
+                raise TypeError
+            if not r:
+                return r
+        except TypeError:
+            r = ImageSet(f, set)
+        if isinstance(r, ImageSet):
+            f, set = r.args
+
+        if f.variables[0] == f.expr:
+            return set
+
+        if isinstance(set, ImageSet):
+            # XXX: Maybe this should just be:
+            # f2 = set.lambda
+            # fun = Lambda(f2.signature, f(*f2.expr))
+            # return imageset(fun, *set.base_sets)
+            if len(set.lamda.variables) == 1 and len(f.variables) == 1:
+                x = set.lamda.variables[0]
+                y = f.variables[0]
+                return imageset(
+                    Lambda(x, f.expr.subs(y, set.lamda.expr)), *set.base_sets)
+
+        if r is not None:
+            return r
+
+    return ImageSet(f, *set_list)
+
+
+def is_function_invertible_in_set(func, setv):
+    """
+    Checks whether function ``func`` is invertible when the domain is
+    restricted to set ``setv``.
+    """
+    # Functions known to always be invertible:
+    if func in (exp, log):
+        return True
+    u = Dummy("u")
+    fdiff = func(u).diff(u)
+    # monotonous functions:
+    # TODO: check subsets (`func` in `setv`)
+    if (fdiff > 0) == True or (fdiff < 0) == True:
+        return True
+    # TODO: support more
+    return None
+
+
+def simplify_union(args):
+    """
+    Simplify a :class:`Union` using known rules.
+
+    Explanation
+    ===========
+
+    We first start with global rules like 'Merge all FiniteSets'
+
+    Then we iterate through all pairs and ask the constituent sets if they
+    can simplify themselves with any other constituent.  This process depends
+    on ``union_sets(a, b)`` functions.
+    """
+    from sympy.sets.handlers.union import union_sets
+
+    # ===== Global Rules =====
+    if not args:
+        return S.EmptySet
+
+    for arg in args:
+        if not isinstance(arg, Set):
+            raise TypeError("Input args to Union must be Sets")
+
+    # Merge all finite sets
+    finite_sets = [x for x in args if x.is_FiniteSet]
+    if len(finite_sets) > 1:
+        a = (x for set in finite_sets for x in set)
+        finite_set = FiniteSet(*a)
+        args = [finite_set] + [x for x in args if not x.is_FiniteSet]
+
+    # ===== Pair-wise Rules =====
+    # Here we depend on rules built into the constituent sets
+    args = set(args)
+    new_args = True
+    while new_args:
+        for s in args:
+            new_args = False
+            for t in args - {s}:
+                new_set = union_sets(s, t)
+                # This returns None if s does not know how to intersect
+                # with t. Returns the newly intersected set otherwise
+                if new_set is not None:
+                    if not isinstance(new_set, set):
+                        new_set = {new_set}
+                    new_args = (args - {s, t}).union(new_set)
+                    break
+            if new_args:
+                args = new_args
+                break
+
+    if len(args) == 1:
+        return args.pop()
+    else:
+        return Union(*args, evaluate=False)
+
+
+def simplify_intersection(args):
+    """
+    Simplify an intersection using known rules.
+
+    Explanation
+    ===========
+
+    We first start with global rules like
+    'if any empty sets return empty set' and 'distribute any unions'
+
+    Then we iterate through all pairs and ask the constituent sets if they
+    can simplify themselves with any other constituent
+    """
+
+    # ===== Global Rules =====
+    if not args:
+        return S.UniversalSet
+
+    for arg in args:
+        if not isinstance(arg, Set):
+            raise TypeError("Input args to Union must be Sets")
+
+    # If any EmptySets return EmptySet
+    if S.EmptySet in args:
+        return S.EmptySet
+
+    # Handle Finite sets
+    rv = Intersection._handle_finite_sets(args)
+
+    if rv is not None:
+        return rv
+
+    # If any of the sets are unions, return a Union of Intersections
+    for s in args:
+        if s.is_Union:
+            other_sets = set(args) - {s}
+            if len(other_sets) > 0:
+                other = Intersection(*other_sets)
+                return Union(*(Intersection(arg, other) for arg in s.args))
+            else:
+                return Union(*s.args)
+
+    for s in args:
+        if s.is_Complement:
+            args.remove(s)
+            other_sets = args + [s.args[0]]
+            return Complement(Intersection(*other_sets), s.args[1])
+
+    from sympy.sets.handlers.intersection import intersection_sets
+
+    # At this stage we are guaranteed not to have any
+    # EmptySets, FiniteSets, or Unions in the intersection
+
+    # ===== Pair-wise Rules =====
+    # Here we depend on rules built into the constituent sets
+    args = set(args)
+    new_args = True
+    while new_args:
+        for s in args:
+            new_args = False
+            for t in args - {s}:
+                new_set = intersection_sets(s, t)
+                # This returns None if s does not know how to intersect
+                # with t. Returns the newly intersected set otherwise
+
+                if new_set is not None:
+                    new_args = (args - {s, t}).union({new_set})
+                    break
+            if new_args:
+                args = new_args
+                break
+
+    if len(args) == 1:
+        return args.pop()
+    else:
+        return Intersection(*args, evaluate=False)
+
+
+def _handle_finite_sets(op, x, y, commutative):
+    # Handle finite sets:
+    fs_args, other = sift([x, y], lambda x: isinstance(x, FiniteSet), binary=True)
+    if len(fs_args) == 2:
+        return FiniteSet(*[op(i, j) for i in fs_args[0] for j in fs_args[1]])
+    elif len(fs_args) == 1:
+        sets = [_apply_operation(op, other[0], i, commutative) for i in fs_args[0]]
+        return Union(*sets)
+    else:
+        return None
+
+
+def _apply_operation(op, x, y, commutative):
+    from .fancysets import ImageSet
+    d = Dummy('d')
+
+    out = _handle_finite_sets(op, x, y, commutative)
+    if out is None:
+        out = op(x, y)
+
+    if out is None and commutative:
+        out = op(y, x)
+    if out is None:
+        _x, _y = symbols("x y")
+        if isinstance(x, Set) and not isinstance(y, Set):
+            out = ImageSet(Lambda(d, op(d, y)), x).doit()
+        elif not isinstance(x, Set) and isinstance(y, Set):
+            out = ImageSet(Lambda(d, op(x, d)), y).doit()
+        else:
+            out = ImageSet(Lambda((_x, _y), op(_x, _y)), x, y)
+    return out
+
+
+def set_add(x, y):
+    from sympy.sets.handlers.add import _set_add
+    return _apply_operation(_set_add, x, y, commutative=True)
+
+
+def set_sub(x, y):
+    from sympy.sets.handlers.add import _set_sub
+    return _apply_operation(_set_sub, x, y, commutative=False)
+
+
+def set_mul(x, y):
+    from sympy.sets.handlers.mul import _set_mul
+    return _apply_operation(_set_mul, x, y, commutative=True)
+
+
+def set_div(x, y):
+    from sympy.sets.handlers.mul import _set_div
+    return _apply_operation(_set_div, x, y, commutative=False)
+
+
+def set_pow(x, y):
+    from sympy.sets.handlers.power import _set_pow
+    return _apply_operation(_set_pow, x, y, commutative=False)
+
+
+def set_function(f, x):
+    from sympy.sets.handlers.functions import _set_function
+    return _set_function(f, x)
+
+
+class SetKind(Kind):
+    """
+    SetKind is kind for all Sets
+
+    Every instance of Set will have kind ``SetKind`` parametrised by the kind
+    of the elements of the ``Set``. The kind of the elements might be
+    ``NumberKind``, or ``TupleKind`` or something else. When not all elements
+    have the same kind then the kind of the elements will be given as
+    ``UndefinedKind``.
+
+    Parameters
+    ==========
+
+    element_kind: Kind (optional)
+        The kind of the elements of the set. In a well defined set all elements
+        will have the same kind. Otherwise the kind should
+        :class:`sympy.core.kind.UndefinedKind`. The ``element_kind`` argument is optional but
+        should only be omitted in the case of ``EmptySet`` whose kind is simply
+        ``SetKind()``
+
+    Examples
+    ========
+
+    >>> from sympy import Interval
+    >>> Interval(1, 2).kind
+    SetKind(NumberKind)
+    >>> Interval(1,2).kind.element_kind
+    NumberKind
+
+    See Also
+    ========
+
+    sympy.core.kind.NumberKind
+    sympy.matrices.kind.MatrixKind
+    sympy.core.containers.TupleKind
+    """
+    def __new__(cls, element_kind=None):
+        obj = super().__new__(cls, element_kind)
+        obj.element_kind = element_kind
+        return obj
+
+    def __repr__(self):
+        if not self.element_kind:
+            return "SetKind()"
+        else:
+            return "SetKind(%s)" % self.element_kind
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_conditionset.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_conditionset.py
new file mode 100644
index 0000000000000000000000000000000000000000..4818246f306afd46a09a2cbea1faab858a9e7806
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_conditionset.py
@@ -0,0 +1,294 @@
+from sympy.core.expr import unchanged
+from sympy.sets import (ConditionSet, Intersection, FiniteSet,
+    EmptySet, Union, Contains, ImageSet)
+from sympy.sets.sets import SetKind
+from sympy.core.function import (Function, Lambda)
+from sympy.core.mod import Mod
+from sympy.core.kind import NumberKind
+from sympy.core.numbers import (oo, pi)
+from sympy.core.relational import (Eq, Ne)
+from sympy.core.singleton import S
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.functions.elementary.complexes import Abs
+from sympy.functions.elementary.trigonometric import (asin, sin)
+from sympy.logic.boolalg import And
+from sympy.matrices.dense import Matrix
+from sympy.matrices.expressions.matexpr import MatrixSymbol
+from sympy.sets.sets import Interval
+from sympy.testing.pytest import raises, warns_deprecated_sympy
+
+
+w = Symbol('w')
+x = Symbol('x')
+y = Symbol('y')
+z = Symbol('z')
+f = Function('f')
+
+
+def test_CondSet():
+    sin_sols_principal = ConditionSet(x, Eq(sin(x), 0),
+                                      Interval(0, 2*pi, False, True))
+    assert pi in sin_sols_principal
+    assert pi/2 not in sin_sols_principal
+    assert 3*pi not in sin_sols_principal
+    assert oo not in sin_sols_principal
+    assert 5 in ConditionSet(x, x**2 > 4, S.Reals)
+    assert 1 not in ConditionSet(x, x**2 > 4, S.Reals)
+    # in this case, 0 is not part of the base set so
+    # it can't be in any subset selected by the condition
+    assert 0 not in ConditionSet(x, y > 5, Interval(1, 7))
+    # since 'in' requires a true/false, the following raises
+    # an error because the given value provides no information
+    # for the condition to evaluate (since the condition does
+    # not depend on the dummy symbol): the result is `y > 5`.
+    # In this case, ConditionSet is just acting like
+    # Piecewise((Interval(1, 7), y > 5), (S.EmptySet, True)).
+    raises(TypeError, lambda: 6 in ConditionSet(x, y > 5,
+        Interval(1, 7)))
+
+    X = MatrixSymbol('X', 2, 2)
+    matrix_set = ConditionSet(X, Eq(X*Matrix([[1, 1], [1, 1]]), X))
+    Y = Matrix([[0, 0], [0, 0]])
+    assert matrix_set.contains(Y).doit() is S.true
+    Z = Matrix([[1, 2], [3, 4]])
+    assert matrix_set.contains(Z).doit() is S.false
+
+    assert isinstance(ConditionSet(x, x < 1, {x, y}).base_set,
+        FiniteSet)
+    raises(TypeError, lambda: ConditionSet(x, x + 1, {x, y}))
+    raises(TypeError, lambda: ConditionSet(x, x, 1))
+
+    I = S.Integers
+    U = S.UniversalSet
+    C = ConditionSet
+    assert C(x, False, I) is S.EmptySet
+    assert C(x, True, I) is I
+    assert C(x, x < 1, C(x, x < 2, I)
+        ) == C(x, (x < 1) & (x < 2), I)
+    assert C(y, y < 1, C(x, y < 2, I)
+        ) == C(x, (x < 1) & (y < 2), I), C(y, y < 1, C(x, y < 2, I))
+    assert C(y, y < 1, C(x, x < 2, I)
+        ) == C(y, (y < 1) & (y < 2), I)
+    assert C(y, y < 1, C(x, y < x, I)
+        ) == C(x, (x < 1) & (y < x), I)
+    assert unchanged(C, y, x < 1, C(x, y < x, I))
+    assert ConditionSet(x, x < 1).base_set is U
+    # arg checking is not done at instantiation but this
+    # will raise an error when containment is tested
+    assert ConditionSet((x,), x < 1).base_set is U
+
+    c = ConditionSet((x, y), x < y, I**2)
+    assert (1, 2) in c
+    assert (1, pi) not in c
+
+    raises(TypeError, lambda: C(x, x > 1, C((x, y), x > 1, I**2)))
+    # signature mismatch since only 3 args are accepted
+    raises(TypeError, lambda: C((x, y), x + y < 2, U, U))
+
+
+def test_CondSet_intersect():
+    input_conditionset = ConditionSet(x, x**2 > 4, Interval(1, 4, False,
+        False))
+    other_domain = Interval(0, 3, False, False)
+    output_conditionset = ConditionSet(x, x**2 > 4, Interval(
+        1, 3, False, False))
+    assert Intersection(input_conditionset, other_domain
+        ) == output_conditionset
+
+
+def test_issue_9849():
+    assert ConditionSet(x, Eq(x, x), S.Naturals
+        ) is S.Naturals
+    assert ConditionSet(x, Eq(Abs(sin(x)), -1), S.Naturals
+        ) == S.EmptySet
+
+
+def test_simplified_FiniteSet_in_CondSet():
+    assert ConditionSet(x, And(x < 1, x > -3), FiniteSet(0, 1, 2)
+        ) == FiniteSet(0)
+    assert ConditionSet(x, x < 0, FiniteSet(0, 1, 2)) == EmptySet
+    assert ConditionSet(x, And(x < -3), EmptySet) == EmptySet
+    y = Symbol('y')
+    assert (ConditionSet(x, And(x > 0), FiniteSet(-1, 0, 1, y)) ==
+        Union(FiniteSet(1), ConditionSet(x, And(x > 0), FiniteSet(y))))
+    assert (ConditionSet(x, Eq(Mod(x, 3), 1), FiniteSet(1, 4, 2, y)) ==
+        Union(FiniteSet(1, 4), ConditionSet(x, Eq(Mod(x, 3), 1),
+        FiniteSet(y))))
+
+
+def test_free_symbols():
+    assert ConditionSet(x, Eq(y, 0), FiniteSet(z)
+        ).free_symbols == {y, z}
+    assert ConditionSet(x, Eq(x, 0), FiniteSet(z)
+        ).free_symbols == {z}
+    assert ConditionSet(x, Eq(x, 0), FiniteSet(x, z)
+        ).free_symbols == {x, z}
+    assert ConditionSet(x, Eq(x, 0), ImageSet(Lambda(y, y**2),
+        S.Integers)).free_symbols == set()
+
+
+def test_bound_symbols():
+    assert ConditionSet(x, Eq(y, 0), FiniteSet(z)
+        ).bound_symbols == [x]
+    assert ConditionSet(x, Eq(x, 0), FiniteSet(x, y)
+        ).bound_symbols == [x]
+    assert ConditionSet(x, x < 10, ImageSet(Lambda(y, y**2), S.Integers)
+        ).bound_symbols == [x]
+    assert ConditionSet(x, x < 10, ConditionSet(y, y > 1, S.Integers)
+        ).bound_symbols == [x]
+
+
+def test_as_dummy():
+    _0, _1 = symbols('_0 _1')
+    assert ConditionSet(x, x < 1, Interval(y, oo)
+        ).as_dummy() == ConditionSet(_0, _0 < 1, Interval(y, oo))
+    assert ConditionSet(x, x < 1, Interval(x, oo)
+        ).as_dummy() == ConditionSet(_0, _0 < 1, Interval(x, oo))
+    assert ConditionSet(x, x < 1, ImageSet(Lambda(y, y**2), S.Integers)
+        ).as_dummy() == ConditionSet(
+            _0, _0 < 1, ImageSet(Lambda(_0, _0**2), S.Integers))
+    e = ConditionSet((x, y), x <= y, S.Reals**2)
+    assert e.bound_symbols == [x, y]
+    assert e.as_dummy() == ConditionSet((_0, _1), _0 <= _1, S.Reals**2)
+    assert e.as_dummy() == ConditionSet((y, x), y <= x, S.Reals**2
+        ).as_dummy()
+
+
+def test_subs_CondSet():
+    s = FiniteSet(z, y)
+    c = ConditionSet(x, x < 2, s)
+    assert c.subs(x, y) == c
+    assert c.subs(z, y) == ConditionSet(x, x < 2, FiniteSet(y))
+    assert c.xreplace({x: y}) == ConditionSet(y, y < 2, s)
+
+    assert ConditionSet(x, x < y, s
+        ).subs(y, w) == ConditionSet(x, x < w, s.subs(y, w))
+    # if the user uses assumptions that cause the condition
+    # to evaluate, that can't be helped from SymPy's end
+    n = Symbol('n', negative=True)
+    assert ConditionSet(n, 0 < n, S.Integers) is S.EmptySet
+    p = Symbol('p', positive=True)
+    assert ConditionSet(n, n < y, S.Integers
+        ).subs(n, x) == ConditionSet(n, n < y, S.Integers)
+    raises(ValueError, lambda: ConditionSet(
+        x + 1, x < 1, S.Integers))
+    assert ConditionSet(
+        p, n < x, Interval(-5, 5)).subs(x, p) == Interval(-5, 5), ConditionSet(
+        p, n < x, Interval(-5, 5)).subs(x, p)
+    assert ConditionSet(
+        n, n < x, Interval(-oo, 0)).subs(x, p
+        ) == Interval(-oo, 0)
+
+    assert ConditionSet(f(x), f(x) < 1, {w, z}
+        ).subs(f(x), y) == ConditionSet(f(x), f(x) < 1, {w, z})
+
+    # issue 17341
+    k = Symbol('k')
+    img1 = ImageSet(Lambda(k, 2*k*pi + asin(y)), S.Integers)
+    img2 = ImageSet(Lambda(k, 2*k*pi + asin(S.One/3)), S.Integers)
+    assert ConditionSet(x, Contains(
+        y, Interval(-1,1)), img1).subs(y, S.One/3).dummy_eq(img2)
+
+    assert (0, 1) in ConditionSet((x, y), x + y < 3, S.Integers**2)
+
+    raises(TypeError, lambda: ConditionSet(n, n < -10, Interval(0, 10)))
+
+
+def test_subs_CondSet_tebr():
+    with warns_deprecated_sympy():
+        assert ConditionSet((x, y), {x + 1, x + y}, S.Reals**2) == \
+            ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Reals**2)
+
+
+def test_dummy_eq():
+    C = ConditionSet
+    I = S.Integers
+    c = C(x, x < 1, I)
+    assert c.dummy_eq(C(y, y < 1, I))
+    assert c.dummy_eq(1) == False
+    assert c.dummy_eq(C(x, x < 1, S.Reals)) == False
+
+    c1 = ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Reals**2)
+    c2 = ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Reals**2)
+    c3 = ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Complexes**2)
+    assert c1.dummy_eq(c2)
+    assert c1.dummy_eq(c3) is False
+    assert c.dummy_eq(c1) is False
+    assert c1.dummy_eq(c) is False
+
+    # issue 19496
+    m = Symbol('m')
+    n = Symbol('n')
+    a = Symbol('a')
+    d1 = ImageSet(Lambda(m, m*pi), S.Integers)
+    d2 = ImageSet(Lambda(n, n*pi), S.Integers)
+    c1 = ConditionSet(x, Ne(a, 0), d1)
+    c2 = ConditionSet(x, Ne(a, 0), d2)
+    assert c1.dummy_eq(c2)
+
+
+def test_contains():
+    assert 6 in ConditionSet(x, x > 5, Interval(1, 7))
+    assert (8 in ConditionSet(x, y > 5, Interval(1, 7))) is False
+    # `in` should give True or False; in this case there is not
+    # enough information for that result
+    raises(TypeError,
+        lambda: 6 in ConditionSet(x, y > 5, Interval(1, 7)))
+    # here, there is enough information but the comparison is
+    # not defined
+    raises(TypeError, lambda: 0 in ConditionSet(x, 1/x >= 0, S.Reals))
+    assert ConditionSet(x, y > 5, Interval(1, 7)
+        ).contains(6) == (y > 5)
+    assert ConditionSet(x, y > 5, Interval(1, 7)
+        ).contains(8) is S.false
+    assert ConditionSet(x, y > 5, Interval(1, 7)
+        ).contains(w) == And(Contains(w, Interval(1, 7)), y > 5)
+    # This returns an unevaluated Contains object
+    # because 1/0 should not be defined for 1 and 0 in the context of
+    # reals.
+    assert ConditionSet(x, 1/x >= 0, S.Reals).contains(0) == \
+        Contains(0, ConditionSet(x, 1/x >= 0, S.Reals), evaluate=False)
+    c = ConditionSet((x, y), x + y > 1, S.Integers**2)
+    assert not c.contains(1)
+    assert c.contains((2, 1))
+    assert not c.contains((0, 1))
+    c = ConditionSet((w, (x, y)), w + x + y > 1, S.Integers*S.Integers**2)
+    assert not c.contains(1)
+    assert not c.contains((1, 2))
+    assert not c.contains(((1, 2), 3))
+    assert not c.contains(((1, 2), (3, 4)))
+    assert c.contains((1, (3, 4)))
+
+
+def test_as_relational():
+    assert ConditionSet((x, y), x > 1, S.Integers**2).as_relational((x, y)
+        ) == (x > 1) & Contains(x, S.Integers) & Contains(y, S.Integers)
+    assert ConditionSet(x, x > 1, S.Integers).as_relational(x
+        ) == Contains(x, S.Integers) & (x > 1)
+
+
+def test_flatten():
+    """Tests whether there is basic denesting functionality"""
+    inner = ConditionSet(x, sin(x) + x > 0)
+    outer = ConditionSet(x, Contains(x, inner), S.Reals)
+    assert outer == ConditionSet(x, sin(x) + x > 0, S.Reals)
+
+    inner = ConditionSet(y, sin(y) + y > 0)
+    outer = ConditionSet(x, Contains(y, inner), S.Reals)
+    assert outer != ConditionSet(x, sin(x) + x > 0, S.Reals)
+
+    inner = ConditionSet(x, sin(x) + x > 0).intersect(Interval(-1, 1))
+    outer = ConditionSet(x, Contains(x, inner), S.Reals)
+    assert outer == ConditionSet(x, sin(x) + x > 0, Interval(-1, 1))
+
+
+def test_duplicate():
+    from sympy.core.function import BadSignatureError
+    # test coverage for line 95 in conditionset.py, check for duplicates in symbols
+    dup = symbols('a,a')
+    raises(BadSignatureError, lambda: ConditionSet(dup, x < 0))
+
+
+def test_SetKind_ConditionSet():
+    assert ConditionSet(x, Eq(sin(x), 0), Interval(0, 2*pi)).kind is SetKind(NumberKind)
+    assert ConditionSet(x, x < 0).kind is SetKind(NumberKind)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_contains.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_contains.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb6b98940946f98bf377aad6810f5b32eb6dd069
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_contains.py
@@ -0,0 +1,52 @@
+from sympy.core.expr import unchanged
+from sympy.core.numbers import oo
+from sympy.core.relational import Eq
+from sympy.core.singleton import S
+from sympy.core.symbol import Symbol
+from sympy.sets.contains import Contains
+from sympy.sets.sets import (FiniteSet, Interval)
+from sympy.testing.pytest import raises
+
+
+def test_contains_basic():
+    raises(TypeError, lambda: Contains(S.Integers, 1))
+    assert Contains(2, S.Integers) is S.true
+    assert Contains(-2, S.Naturals) is S.false
+
+    i = Symbol('i', integer=True)
+    assert Contains(i, S.Naturals) == Contains(i, S.Naturals, evaluate=False)
+
+
+def test_issue_6194():
+    x = Symbol('x')
+    assert unchanged(Contains, x, Interval(0, 1))
+    assert Interval(0, 1).contains(x) == (S.Zero <= x) & (x <= 1)
+    assert Contains(x, FiniteSet(0)) != S.false
+    assert Contains(x, Interval(1, 1)) != S.false
+    assert Contains(x, S.Integers) != S.false
+
+
+def test_issue_10326():
+    assert Contains(oo, Interval(-oo, oo)) == False
+    assert Contains(-oo, Interval(-oo, oo)) == False
+
+
+def test_binary_symbols():
+    x = Symbol('x')
+    y = Symbol('y')
+    z = Symbol('z')
+    assert Contains(x, FiniteSet(y, Eq(z, True))
+        ).binary_symbols == {y, z}
+
+
+def test_as_set():
+    x = Symbol('x')
+    y = Symbol('y')
+    assert Contains(x, FiniteSet(y)).as_set() == FiniteSet(y)
+    assert Contains(x, S.Integers).as_set() == S.Integers
+    assert Contains(x, S.Reals).as_set() == S.Reals
+
+
+def test_type_error():
+    # Pass in a parameter not of type "set"
+    raises(TypeError, lambda: Contains(2, None))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_fancysets.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_fancysets.py
new file mode 100644
index 0000000000000000000000000000000000000000..b23c2a99fce0af5bfe7c667185465ee417de19ce
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_fancysets.py
@@ -0,0 +1,1313 @@
+
+from sympy.core.expr import unchanged
+from sympy.sets.contains import Contains
+from sympy.sets.fancysets import (ImageSet, Range, normalize_theta_set,
+                                  ComplexRegion)
+from sympy.sets.sets import (FiniteSet, Interval, Union, imageset,
+                             Intersection, ProductSet, SetKind)
+from sympy.sets.conditionset import ConditionSet
+from sympy.simplify.simplify import simplify
+from sympy.core.basic import Basic
+from sympy.core.containers import Tuple, TupleKind
+from sympy.core.function import Lambda
+from sympy.core.kind import NumberKind
+from sympy.core.numbers import (I, Rational, oo, pi)
+from sympy.core.relational import Eq
+from sympy.core.singleton import S
+from sympy.core.symbol import (Dummy, Symbol, symbols)
+from sympy.functions.elementary.complexes import Abs
+from sympy.functions.elementary.exponential import (exp, log)
+from sympy.functions.elementary.integers import floor
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import (cos, sin, tan)
+from sympy.logic.boolalg import And
+from sympy.matrices.dense import eye
+from sympy.testing.pytest import XFAIL, raises
+from sympy.abc import x, y, t, z
+from sympy.core.mod import Mod
+
+import itertools
+
+
+def test_naturals():
+    N = S.Naturals
+    assert 5 in N
+    assert -5 not in N
+    assert 5.5 not in N
+    ni = iter(N)
+    a, b, c, d = next(ni), next(ni), next(ni), next(ni)
+    assert (a, b, c, d) == (1, 2, 3, 4)
+    assert isinstance(a, Basic)
+
+    assert N.intersect(Interval(-5, 5)) == Range(1, 6)
+    assert N.intersect(Interval(-5, 5, True, True)) == Range(1, 5)
+
+    assert N.boundary == N
+    assert N.is_open == False
+    assert N.is_closed == True
+
+    assert N.inf == 1
+    assert N.sup is oo
+    assert not N.contains(oo)
+    for s in (S.Naturals0, S.Naturals):
+        assert s.intersection(S.Reals) is s
+        assert s.is_subset(S.Reals)
+
+    assert N.as_relational(x) == And(Eq(floor(x), x), x >= 1, x < oo)
+
+
+def test_naturals0():
+    N = S.Naturals0
+    assert 0 in N
+    assert -1 not in N
+    assert next(iter(N)) == 0
+    assert not N.contains(oo)
+    assert N.contains(sin(x)) == Contains(sin(x), N)
+
+
+def test_integers():
+    Z = S.Integers
+    assert 5 in Z
+    assert -5 in Z
+    assert 5.5 not in Z
+    assert not Z.contains(oo)
+    assert not Z.contains(-oo)
+
+    zi = iter(Z)
+    a, b, c, d = next(zi), next(zi), next(zi), next(zi)
+    assert (a, b, c, d) == (0, 1, -1, 2)
+    assert isinstance(a, Basic)
+
+    assert Z.intersect(Interval(-5, 5)) == Range(-5, 6)
+    assert Z.intersect(Interval(-5, 5, True, True)) == Range(-4, 5)
+    assert Z.intersect(Interval(5, S.Infinity)) == Range(5, S.Infinity)
+    assert Z.intersect(Interval.Lopen(5, S.Infinity)) == Range(6, S.Infinity)
+
+    assert Z.inf is -oo
+    assert Z.sup is oo
+
+    assert Z.boundary == Z
+    assert Z.is_open == False
+    assert Z.is_closed == True
+
+    assert Z.as_relational(x) == And(Eq(floor(x), x), -oo < x, x < oo)
+
+
+def test_ImageSet():
+    raises(ValueError, lambda: ImageSet(x, S.Integers))
+    assert ImageSet(Lambda(x, 1), S.Integers) == FiniteSet(1)
+    assert ImageSet(Lambda(x, y), S.Integers) == {y}
+    assert ImageSet(Lambda(x, 1), S.EmptySet) == S.EmptySet
+    empty = Intersection(FiniteSet(log(2)/pi), S.Integers)
+    assert unchanged(ImageSet, Lambda(x, 1), empty)  # issue #17471
+    squares = ImageSet(Lambda(x, x**2), S.Naturals)
+    assert 4 in squares
+    assert 5 not in squares
+    assert FiniteSet(*range(10)).intersect(squares) == FiniteSet(1, 4, 9)
+
+    assert 16 not in squares.intersect(Interval(0, 10))
+
+    si = iter(squares)
+    a, b, c, d = next(si), next(si), next(si), next(si)
+    assert (a, b, c, d) == (1, 4, 9, 16)
+
+    harmonics = ImageSet(Lambda(x, 1/x), S.Naturals)
+    assert Rational(1, 5) in harmonics
+    assert Rational(.25) in harmonics
+    assert harmonics.contains(.25) == Contains(
+        0.25, ImageSet(Lambda(x, 1/x), S.Naturals), evaluate=False)
+    assert Rational(.3) not in harmonics
+    assert (1, 2) not in harmonics
+
+    assert harmonics.is_iterable
+
+    assert imageset(x, -x, Interval(0, 1)) == Interval(-1, 0)
+
+    assert ImageSet(Lambda(x, x**2), Interval(0, 2)).doit() == Interval(0, 4)
+    assert ImageSet(Lambda((x, y), 2*x), {4}, {3}).doit() == FiniteSet(8)
+    assert (ImageSet(Lambda((x, y), x+y), {1, 2, 3}, {10, 20, 30}).doit() ==
+                FiniteSet(11, 12, 13, 21, 22, 23, 31, 32, 33))
+
+    c = Interval(1, 3) * Interval(1, 3)
+    assert Tuple(2, 6) in ImageSet(Lambda(((x, y),), (x, 2*y)), c)
+    assert Tuple(2, S.Half) in ImageSet(Lambda(((x, y),), (x, 1/y)), c)
+    assert Tuple(2, -2) not in ImageSet(Lambda(((x, y),), (x, y**2)), c)
+    assert Tuple(2, -2) in ImageSet(Lambda(((x, y),), (x, -2)), c)
+    c3 = ProductSet(Interval(3, 7), Interval(8, 11), Interval(5, 9))
+    assert Tuple(8, 3, 9) in ImageSet(Lambda(((t, y, x),), (y, t, x)), c3)
+    assert Tuple(Rational(1, 8), 3, 9) in ImageSet(Lambda(((t, y, x),), (1/y, t, x)), c3)
+    assert 2/pi not in ImageSet(Lambda(((x, y),), 2/x), c)
+    assert 2/S(100) not in ImageSet(Lambda(((x, y),), 2/x), c)
+    assert Rational(2, 3) in ImageSet(Lambda(((x, y),), 2/x), c)
+
+    S1 = imageset(lambda x, y: x + y, S.Integers, S.Naturals)
+    assert S1.base_pset == ProductSet(S.Integers, S.Naturals)
+    assert S1.base_sets == (S.Integers, S.Naturals)
+
+    # Passing a set instead of a FiniteSet shouldn't raise
+    assert unchanged(ImageSet, Lambda(x, x**2), {1, 2, 3})
+
+    S2 = ImageSet(Lambda(((x, y),), x+y), {(1, 2), (3, 4)})
+    assert 3 in S2.doit()
+    # FIXME: This doesn't yet work:
+    #assert 3 in S2
+    assert S2._contains(3) is None
+
+    raises(TypeError, lambda: ImageSet(Lambda(x, x**2), 1))
+
+
+def test_image_is_ImageSet():
+    assert isinstance(imageset(x, sqrt(sin(x)), Range(5)), ImageSet)
+
+
+def test_halfcircle():
+    r, th = symbols('r, theta', real=True)
+    L = Lambda(((r, th),), (r*cos(th), r*sin(th)))
+    halfcircle = ImageSet(L, Interval(0, 1)*Interval(0, pi))
+
+    assert (1, 0) in halfcircle
+    assert (0, -1) not in halfcircle
+    assert (0, 0) in halfcircle
+    assert halfcircle._contains((r, 0)) is None
+    assert not halfcircle.is_iterable
+
+
+@XFAIL
+def test_halfcircle_fail():
+    r, th = symbols('r, theta', real=True)
+    L = Lambda(((r, th),), (r*cos(th), r*sin(th)))
+    halfcircle = ImageSet(L, Interval(0, 1)*Interval(0, pi))
+    assert (r, 2*pi) not in halfcircle
+
+
+def test_ImageSet_iterator_not_injective():
+    L = Lambda(x, x - x % 2)  # produces 0, 2, 2, 4, 4, 6, 6, ...
+    evens = ImageSet(L, S.Naturals)
+    i = iter(evens)
+    # No repeats here
+    assert (next(i), next(i), next(i), next(i)) == (0, 2, 4, 6)
+
+
+def test_inf_Range_len():
+    raises(ValueError, lambda: len(Range(0, oo, 2)))
+    assert Range(0, oo, 2).size is S.Infinity
+    assert Range(0, -oo, -2).size is S.Infinity
+    assert Range(oo, 0, -2).size is S.Infinity
+    assert Range(-oo, 0, 2).size is S.Infinity
+
+
+def test_Range_set():
+    empty = Range(0)
+
+    assert Range(5) == Range(0, 5) == Range(0, 5, 1)
+
+    r = Range(10, 20, 2)
+    assert 12 in r
+    assert 8 not in r
+    assert 11 not in r
+    assert 30 not in r
+
+    assert list(Range(0, 5)) == list(range(5))
+    assert list(Range(5, 0, -1)) == list(range(5, 0, -1))
+
+
+    assert Range(5, 15).sup == 14
+    assert Range(5, 15).inf == 5
+    assert Range(15, 5, -1).sup == 15
+    assert Range(15, 5, -1).inf == 6
+    assert Range(10, 67, 10).sup == 60
+    assert Range(60, 7, -10).inf == 10
+
+    assert len(Range(10, 38, 10)) == 3
+
+    assert Range(0, 0, 5) == empty
+    assert Range(oo, oo, 1) == empty
+    assert Range(oo, 1, 1) == empty
+    assert Range(-oo, 1, -1) == empty
+    assert Range(1, oo, -1) == empty
+    assert Range(1, -oo, 1) == empty
+    assert Range(1, -4, oo) == empty
+    ip = symbols('ip', positive=True)
+    assert Range(0, ip, -1) == empty
+    assert Range(0, -ip, 1) == empty
+    assert Range(1, -4, -oo) == Range(1, 2)
+    assert Range(1, 4, oo) == Range(1, 2)
+    assert Range(-oo, oo).size == oo
+    assert Range(oo, -oo, -1).size == oo
+    raises(ValueError, lambda: Range(-oo, oo, 2))
+    raises(ValueError, lambda: Range(x, pi, y))
+    raises(ValueError, lambda: Range(x, y, 0))
+
+    assert 5 in Range(0, oo, 5)
+    assert -5 in Range(-oo, 0, 5)
+    assert oo not in Range(0, oo)
+    ni = symbols('ni', integer=False)
+    assert ni not in Range(oo)
+    u = symbols('u', integer=None)
+    assert Range(oo).contains(u) is not False
+    inf = symbols('inf', infinite=True)
+    assert inf not in Range(-oo, oo)
+    raises(ValueError, lambda: Range(0, oo, 2)[-1])
+    raises(ValueError, lambda: Range(0, -oo, -2)[-1])
+    assert Range(-oo, 1, 1)[-1] is S.Zero
+    assert Range(oo, 1, -1)[-1] == 2
+    assert inf not in Range(oo)
+    assert Range(1, 10, 1)[-1] == 9
+    assert all(i.is_Integer for i in Range(0, -1, 1))
+    it = iter(Range(-oo, 0, 2))
+    raises(TypeError, lambda: next(it))
+
+    assert empty.intersect(S.Integers) == empty
+    assert Range(-1, 10, 1).intersect(S.Complexes) == Range(-1, 10, 1)
+    assert Range(-1, 10, 1).intersect(S.Reals) == Range(-1, 10, 1)
+    assert Range(-1, 10, 1).intersect(S.Rationals) == Range(-1, 10, 1)
+    assert Range(-1, 10, 1).intersect(S.Integers) == Range(-1, 10, 1)
+    assert Range(-1, 10, 1).intersect(S.Naturals) == Range(1, 10, 1)
+    assert Range(-1, 10, 1).intersect(S.Naturals0) == Range(0, 10, 1)
+
+    # test slicing
+    assert Range(1, 10, 1)[5] == 6
+    assert Range(1, 12, 2)[5] == 11
+    assert Range(1, 10, 1)[-1] == 9
+    assert Range(1, 10, 3)[-1] == 7
+    raises(ValueError, lambda: Range(oo,0,-1)[1:3:0])
+    raises(ValueError, lambda: Range(oo,0,-1)[:1])
+    raises(ValueError, lambda: Range(1, oo)[-2])
+    raises(ValueError, lambda: Range(-oo, 1)[2])
+    raises(IndexError, lambda: Range(10)[-20])
+    raises(IndexError, lambda: Range(10)[20])
+    raises(ValueError, lambda: Range(2, -oo, -2)[2:2:0])
+    assert Range(2, -oo, -2)[2:2:2] == empty
+    assert Range(2, -oo, -2)[:2:2] == Range(2, -2, -4)
+    raises(ValueError, lambda: Range(-oo, 4, 2)[:2:2])
+    assert Range(-oo, 4, 2)[::-2] == Range(2, -oo, -4)
+    raises(ValueError, lambda: Range(-oo, 4, 2)[::2])
+    assert Range(oo, 2, -2)[::] == Range(oo, 2, -2)
+    assert Range(-oo, 4, 2)[:-2:-2] == Range(2, 0, -4)
+    assert Range(-oo, 4, 2)[:-2:2] == Range(-oo, 0, 4)
+    raises(ValueError, lambda: Range(-oo, 4, 2)[:0:-2])
+    raises(ValueError, lambda: Range(-oo, 4, 2)[:2:-2])
+    assert Range(-oo, 4, 2)[-2::-2] == Range(0, -oo, -4)
+    raises(ValueError, lambda: Range(-oo, 4, 2)[-2:0:-2])
+    raises(ValueError, lambda: Range(-oo, 4, 2)[0::2])
+    assert Range(oo, 2, -2)[0::] == Range(oo, 2, -2)
+    raises(ValueError, lambda: Range(-oo, 4, 2)[0:-2:2])
+    assert Range(oo, 2, -2)[0:-2:] == Range(oo, 6, -2)
+    raises(ValueError, lambda: Range(oo, 2, -2)[0:2:])
+    raises(ValueError, lambda: Range(-oo, 4, 2)[2::-1])
+    assert Range(-oo, 4, 2)[-2::2] == Range(0, 4, 4)
+    assert Range(oo, 0, -2)[-10:0:2] == empty
+    raises(ValueError, lambda: Range(oo, 0, -2)[0])
+    raises(ValueError, lambda: Range(oo, 0, -2)[-10:10:2])
+    raises(ValueError, lambda: Range(oo, 0, -2)[0::-2])
+    assert Range(oo, 0, -2)[0:-4:-2] == empty
+    assert Range(oo, 0, -2)[:0:2] == empty
+    raises(ValueError, lambda: Range(oo, 0, -2)[:1:-1])
+
+    # test empty Range
+    assert Range(x, x, y) == empty
+    assert empty.reversed == empty
+    assert 0 not in empty
+    assert list(empty) == []
+    assert len(empty) == 0
+    assert empty.size is S.Zero
+    assert empty.intersect(FiniteSet(0)) is S.EmptySet
+    assert bool(empty) is False
+    raises(IndexError, lambda: empty[0])
+    assert empty[:0] == empty
+    raises(NotImplementedError, lambda: empty.inf)
+    raises(NotImplementedError, lambda: empty.sup)
+    assert empty.as_relational(x) is S.false
+
+    AB = [None] + list(range(12))
+    for R in [
+            Range(1, 10),
+            Range(1, 10, 2),
+        ]:
+        r = list(R)
+        for a, b, c in itertools.product(AB, AB, [-3, -1, None, 1, 3]):
+            for reverse in range(2):
+                r = list(reversed(r))
+                R = R.reversed
+                result = list(R[a:b:c])
+                ans = r[a:b:c]
+                txt = ('\n%s[%s:%s:%s] = %s -> %s' % (
+                R, a, b, c, result, ans))
+                check = ans == result
+                assert check, txt
+
+    assert Range(1, 10, 1).boundary == Range(1, 10, 1)
+
+    for r in (Range(1, 10, 2), Range(1, oo, 2)):
+        rev = r.reversed
+        assert r.inf == rev.inf and r.sup == rev.sup
+        assert r.step == -rev.step
+
+    builtin_range = range
+
+    raises(TypeError, lambda: Range(builtin_range(1)))
+    assert S(builtin_range(10)) == Range(10)
+    assert S(builtin_range(1000000000000)) == Range(1000000000000)
+
+    # test Range.as_relational
+    assert Range(1, 4).as_relational(x) == (x >= 1) & (x <= 3)  & Eq(Mod(x, 1), 0)
+    assert Range(oo, 1, -2).as_relational(x) == (x >= 3) & (x < oo)  & Eq(Mod(x + 1, -2), 0)
+
+
+def test_Range_symbolic():
+    # symbolic Range
+    xr = Range(x, x + 4, 5)
+    sr = Range(x, y, t)
+    i = Symbol('i', integer=True)
+    ip = Symbol('i', integer=True, positive=True)
+    ipr = Range(ip)
+    inr = Range(0, -ip, -1)
+    ir = Range(i, i + 19, 2)
+    ir2 = Range(i, i*8, 3*i)
+    i = Symbol('i', integer=True)
+    inf = symbols('inf', infinite=True)
+    raises(ValueError, lambda: Range(inf))
+    raises(ValueError, lambda: Range(inf, 0, -1))
+    raises(ValueError, lambda: Range(inf, inf, 1))
+    raises(ValueError, lambda: Range(1, 1, inf))
+    # args
+    assert xr.args == (x, x + 5, 5)
+    assert sr.args == (x, y, t)
+    assert ir.args == (i, i + 20, 2)
+    assert ir2.args == (i, 10*i, 3*i)
+    # reversed
+    raises(ValueError, lambda: xr.reversed)
+    raises(ValueError, lambda: sr.reversed)
+    assert ipr.reversed.args == (ip - 1, -1, -1)
+    assert inr.reversed.args == (-ip + 1, 1, 1)
+    assert ir.reversed.args == (i + 18, i - 2, -2)
+    assert ir2.reversed.args == (7*i, -2*i, -3*i)
+    # contains
+    assert inf not in sr
+    assert inf not in ir
+    assert 0 in ipr
+    assert 0 in inr
+    raises(TypeError, lambda: 1 in ipr)
+    raises(TypeError, lambda: -1 in inr)
+    assert .1 not in sr
+    assert .1 not in ir
+    assert i + 1 not in ir
+    assert i + 2 in ir
+    raises(TypeError, lambda: x in xr)  # XXX is this what contains is supposed to do?
+    raises(TypeError, lambda: 1 in sr)  # XXX is this what contains is supposed to do?
+    # iter
+    raises(ValueError, lambda: next(iter(xr)))
+    raises(ValueError, lambda: next(iter(sr)))
+    assert next(iter(ir)) == i
+    assert next(iter(ir2)) == i
+    assert sr.intersect(S.Integers) == sr
+    assert sr.intersect(FiniteSet(x)) == Intersection({x}, sr)
+    raises(ValueError, lambda: sr[:2])
+    raises(ValueError, lambda: xr[0])
+    raises(ValueError, lambda: sr[0])
+    # len
+    assert len(ir) == ir.size == 10
+    assert len(ir2) == ir2.size == 3
+    raises(ValueError, lambda: len(xr))
+    raises(ValueError, lambda: xr.size)
+    raises(ValueError, lambda: len(sr))
+    raises(ValueError, lambda: sr.size)
+    # bool
+    assert bool(Range(0)) == False
+    assert bool(xr)
+    assert bool(ir)
+    assert bool(ipr)
+    assert bool(inr)
+    raises(ValueError, lambda: bool(sr))
+    raises(ValueError, lambda: bool(ir2))
+    # inf
+    raises(ValueError, lambda: xr.inf)
+    raises(ValueError, lambda: sr.inf)
+    assert ipr.inf == 0
+    assert inr.inf == -ip + 1
+    assert ir.inf == i
+    raises(ValueError, lambda: ir2.inf)
+    # sup
+    raises(ValueError, lambda: xr.sup)
+    raises(ValueError, lambda: sr.sup)
+    assert ipr.sup == ip - 1
+    assert inr.sup == 0
+    assert ir.inf == i
+    raises(ValueError, lambda: ir2.sup)
+    # getitem
+    raises(ValueError, lambda: xr[0])
+    raises(ValueError, lambda: sr[0])
+    raises(ValueError, lambda: sr[-1])
+    raises(ValueError, lambda: sr[:2])
+    assert ir[:2] == Range(i, i + 4, 2)
+    assert ir[0] == i
+    assert ir[-2] == i + 16
+    assert ir[-1] == i + 18
+    assert ir2[:2] == Range(i, 7*i, 3*i)
+    assert ir2[0] == i
+    assert ir2[-2] == 4*i
+    assert ir2[-1] == 7*i
+    raises(ValueError, lambda: Range(i)[-1])
+    assert ipr[0] == ipr.inf == 0
+    assert ipr[-1] == ipr.sup == ip - 1
+    assert inr[0] == inr.sup == 0
+    assert inr[-1] == inr.inf == -ip + 1
+    raises(ValueError, lambda: ipr[-2])
+    assert ir.inf == i
+    assert ir.sup == i + 18
+    raises(ValueError, lambda: Range(i).inf)
+    # as_relational
+    assert ir.as_relational(x) == ((x >= i) & (x <= i + 18) &
+        Eq(Mod(-i + x, 2), 0))
+    assert ir2.as_relational(x) == Eq(
+        Mod(-i + x, 3*i), 0) & (((x >= i) & (x <= 7*i) & (3*i >= 1)) |
+        ((x <= i) & (x >= 7*i) & (3*i <= -1)))
+    assert Range(i, i + 1).as_relational(x) == Eq(x, i)
+    assert sr.as_relational(z) == Eq(
+        Mod(t, 1), 0) & Eq(Mod(x, 1), 0) & Eq(Mod(-x + z, t), 0
+        ) & (((z >= x) & (z <= -t + y) & (t >= 1)) |
+        ((z <= x) & (z >= -t + y) & (t <= -1)))
+    assert xr.as_relational(z) == Eq(z, x) & Eq(Mod(x, 1), 0)
+    # symbols can clash if user wants (but it must be integer)
+    assert xr.as_relational(x) == Eq(Mod(x, 1), 0)
+    # contains() for symbolic values (issue #18146)
+    e = Symbol('e', integer=True, even=True)
+    o = Symbol('o', integer=True, odd=True)
+    assert Range(5).contains(i) == And(i >= 0, i <= 4)
+    assert Range(1).contains(i) == Eq(i, 0)
+    assert Range(-oo, 5, 1).contains(i) == (i <= 4)
+    assert Range(-oo, oo).contains(i) == True
+    assert Range(0, 8, 2).contains(i) == Contains(i, Range(0, 8, 2))
+    assert Range(0, 8, 2).contains(e) == And(e >= 0, e <= 6)
+    assert Range(0, 8, 2).contains(2*i) == And(2*i >= 0, 2*i <= 6)
+    assert Range(0, 8, 2).contains(o) == False
+    assert Range(1, 9, 2).contains(e) == False
+    assert Range(1, 9, 2).contains(o) == And(o >= 1, o <= 7)
+    assert Range(8, 0, -2).contains(o) == False
+    assert Range(9, 1, -2).contains(o) == And(o >= 3, o <= 9)
+    assert Range(-oo, 8, 2).contains(i) == Contains(i, Range(-oo, 8, 2))
+
+
+def test_range_range_intersection():
+    for a, b, r in [
+            (Range(0), Range(1), S.EmptySet),
+            (Range(3), Range(4, oo), S.EmptySet),
+            (Range(3), Range(-3, -1), S.EmptySet),
+            (Range(1, 3), Range(0, 3), Range(1, 3)),
+            (Range(1, 3), Range(1, 4), Range(1, 3)),
+            (Range(1, oo, 2), Range(2, oo, 2), S.EmptySet),
+            (Range(0, oo, 2), Range(oo), Range(0, oo, 2)),
+            (Range(0, oo, 2), Range(100), Range(0, 100, 2)),
+            (Range(2, oo, 2), Range(oo), Range(2, oo, 2)),
+            (Range(0, oo, 2), Range(5, 6), S.EmptySet),
+            (Range(2, 80, 1), Range(55, 71, 4), Range(55, 71, 4)),
+            (Range(0, 6, 3), Range(-oo, 5, 3), S.EmptySet),
+            (Range(0, oo, 2), Range(5, oo, 3), Range(8, oo, 6)),
+            (Range(4, 6, 2), Range(2, 16, 7), S.EmptySet),]:
+        assert a.intersect(b) == r
+        assert a.intersect(b.reversed) == r
+        assert a.reversed.intersect(b) == r
+        assert a.reversed.intersect(b.reversed) == r
+        a, b = b, a
+        assert a.intersect(b) == r
+        assert a.intersect(b.reversed) == r
+        assert a.reversed.intersect(b) == r
+        assert a.reversed.intersect(b.reversed) == r
+
+
+def test_range_interval_intersection():
+    p = symbols('p', positive=True)
+    assert isinstance(Range(3).intersect(Interval(p, p + 2)), Intersection)
+    assert Range(4).intersect(Interval(0, 3)) == Range(4)
+    assert Range(4).intersect(Interval(-oo, oo)) == Range(4)
+    assert Range(4).intersect(Interval(1, oo)) == Range(1, 4)
+    assert Range(4).intersect(Interval(1.1, oo)) == Range(2, 4)
+    assert Range(4).intersect(Interval(0.1, 3)) == Range(1, 4)
+    assert Range(4).intersect(Interval(0.1, 3.1)) == Range(1, 4)
+    assert Range(4).intersect(Interval.open(0, 3)) == Range(1, 3)
+    assert Range(4).intersect(Interval.open(0.1, 0.5)) is S.EmptySet
+    assert Interval(-1, 5).intersect(S.Complexes) == Interval(-1, 5)
+    assert Interval(-1, 5).intersect(S.Reals) == Interval(-1, 5)
+    assert Interval(-1, 5).intersect(S.Integers) == Range(-1, 6)
+    assert Interval(-1, 5).intersect(S.Naturals) == Range(1, 6)
+    assert Interval(-1, 5).intersect(S.Naturals0) == Range(0, 6)
+
+    # Null Range intersections
+    assert Range(0).intersect(Interval(0.2, 0.8)) is S.EmptySet
+    assert Range(0).intersect(Interval(-oo, oo)) is S.EmptySet
+
+
+def test_range_is_finite_set():
+    assert Range(-100, 100).is_finite_set is True
+    assert Range(2, oo).is_finite_set is False
+    assert Range(-oo, 50).is_finite_set is False
+    assert Range(-oo, oo).is_finite_set is False
+    assert Range(oo, -oo).is_finite_set is True
+    assert Range(0, 0).is_finite_set is True
+    assert Range(oo, oo).is_finite_set is True
+    assert Range(-oo, -oo).is_finite_set is True
+    n = Symbol('n', integer=True)
+    m = Symbol('m', integer=True)
+    assert Range(n, n + 49).is_finite_set is True
+    assert Range(n, 0).is_finite_set is True
+    assert Range(-3, n + 7).is_finite_set is True
+    assert Range(n, m).is_finite_set is True
+    assert Range(n + m, m - n).is_finite_set is True
+    assert Range(n, n + m + n).is_finite_set is True
+    assert Range(n, oo).is_finite_set is False
+    assert Range(-oo, n).is_finite_set is False
+    assert Range(n, -oo).is_finite_set is True
+    assert Range(oo, n).is_finite_set is True
+
+
+def test_Range_is_iterable():
+    assert Range(-100, 100).is_iterable is True
+    assert Range(2, oo).is_iterable is False
+    assert Range(-oo, 50).is_iterable is False
+    assert Range(-oo, oo).is_iterable is False
+    assert Range(oo, -oo).is_iterable is True
+    assert Range(0, 0).is_iterable is True
+    assert Range(oo, oo).is_iterable is True
+    assert Range(-oo, -oo).is_iterable is True
+    n = Symbol('n', integer=True)
+    m = Symbol('m', integer=True)
+    p = Symbol('p', integer=True, positive=True)
+    assert Range(n, n + 49).is_iterable is True
+    assert Range(n, 0).is_iterable is False
+    assert Range(-3, n + 7).is_iterable is False
+    assert Range(-3, p + 7).is_iterable is False # Should work with better __iter__
+    assert Range(n, m).is_iterable is False
+    assert Range(n + m, m - n).is_iterable is False
+    assert Range(n, n + m + n).is_iterable is False
+    assert Range(n, oo).is_iterable is False
+    assert Range(-oo, n).is_iterable is False
+    x = Symbol('x')
+    assert Range(x, x + 49).is_iterable is False
+    assert Range(x, 0).is_iterable is False
+    assert Range(-3, x + 7).is_iterable is False
+    assert Range(x, m).is_iterable is False
+    assert Range(x + m, m - x).is_iterable is False
+    assert Range(x, x + m + x).is_iterable is False
+    assert Range(x, oo).is_iterable is False
+    assert Range(-oo, x).is_iterable is False
+
+
+def test_Integers_eval_imageset():
+    ans = ImageSet(Lambda(x, 2*x + Rational(3, 7)), S.Integers)
+    im = imageset(Lambda(x, -2*x + Rational(3, 7)), S.Integers)
+    assert im == ans
+    im = imageset(Lambda(x, -2*x - Rational(11, 7)), S.Integers)
+    assert im == ans
+    y = Symbol('y')
+    L = imageset(x, 2*x + y, S.Integers)
+    assert y + 4 in L
+    a, b, c = 0.092, 0.433, 0.341
+    assert a in imageset(x, a + c*x, S.Integers)
+    assert b in imageset(x, b + c*x, S.Integers)
+
+    _x = symbols('x', negative=True)
+    eq = _x**2 - _x + 1
+    assert imageset(_x, eq, S.Integers).lamda.expr == _x**2 + _x + 1
+    eq = 3*_x - 1
+    assert imageset(_x, eq, S.Integers).lamda.expr == 3*_x + 2
+
+    assert imageset(x, (x, 1/x), S.Integers) == \
+        ImageSet(Lambda(x, (x, 1/x)), S.Integers)
+
+
+def test_Range_eval_imageset():
+    a, b, c = symbols('a b c')
+    assert imageset(x, a*(x + b) + c, Range(3)) == \
+        imageset(x, a*x + a*b + c, Range(3))
+    eq = (x + 1)**2
+    assert imageset(x, eq, Range(3)).lamda.expr == eq
+    eq = a*(x + b) + c
+    r = Range(3, -3, -2)
+    imset = imageset(x, eq, r)
+    assert imset.lamda.expr != eq
+    assert list(imset) == [eq.subs(x, i).expand() for i in list(r)]
+
+
+def test_fun():
+    assert (FiniteSet(*ImageSet(Lambda(x, sin(pi*x/4)),
+        Range(-10, 11))) == FiniteSet(-1, -sqrt(2)/2, 0, sqrt(2)/2, 1))
+
+
+def test_Range_is_empty():
+    i = Symbol('i', integer=True)
+    n = Symbol('n', negative=True, integer=True)
+    p = Symbol('p', positive=True, integer=True)
+
+    assert Range(0).is_empty
+    assert not Range(1).is_empty
+    assert Range(1, 0).is_empty
+    assert not Range(-1, 0).is_empty
+    assert Range(i).is_empty is None
+    assert Range(n).is_empty
+    assert Range(p).is_empty is False
+    assert Range(n, 0).is_empty is False
+    assert Range(n, p).is_empty is False
+    assert Range(p, n).is_empty
+    assert Range(n, -1).is_empty is None
+    assert Range(p, n, -1).is_empty is False
+
+
+def test_Reals():
+    assert 5 in S.Reals
+    assert S.Pi in S.Reals
+    assert -sqrt(2) in S.Reals
+    assert (2, 5) not in S.Reals
+    assert sqrt(-1) not in S.Reals
+    assert S.Reals == Interval(-oo, oo)
+    assert S.Reals != Interval(0, oo)
+    assert S.Reals.is_subset(Interval(-oo, oo))
+    assert S.Reals.intersect(Range(-oo, oo)) == Range(-oo, oo)
+    assert S.ComplexInfinity not in S.Reals
+    assert S.NaN not in S.Reals
+    assert x + S.ComplexInfinity not in S.Reals
+
+
+def test_Complex():
+    assert 5 in S.Complexes
+    assert 5 + 4*I in S.Complexes
+    assert S.Pi in S.Complexes
+    assert -sqrt(2) in S.Complexes
+    assert -I in S.Complexes
+    assert sqrt(-1) in S.Complexes
+    assert S.Complexes.intersect(S.Reals) == S.Reals
+    assert S.Complexes.union(S.Reals) == S.Complexes
+    assert S.Complexes == ComplexRegion(S.Reals*S.Reals)
+    assert (S.Complexes == ComplexRegion(Interval(1, 2)*Interval(3, 4))) == False
+    assert str(S.Complexes) == "Complexes"
+    assert repr(S.Complexes) == "Complexes"
+
+
+def take(n, iterable):
+    "Return first n items of the iterable as a list"
+    return list(itertools.islice(iterable, n))
+
+
+def test_intersections():
+    assert S.Integers.intersect(S.Reals) == S.Integers
+    assert 5 in S.Integers.intersect(S.Reals)
+    assert 5 in S.Integers.intersect(S.Reals)
+    assert -5 not in S.Naturals.intersect(S.Reals)
+    assert 5.5 not in S.Integers.intersect(S.Reals)
+    assert 5 in S.Integers.intersect(Interval(3, oo))
+    assert -5 in S.Integers.intersect(Interval(-oo, 3))
+    assert all(x.is_Integer
+            for x in take(10, S.Integers.intersect(Interval(3, oo)) ))
+
+
+def test_infinitely_indexed_set_1():
+    from sympy.abc import n, m
+    assert imageset(Lambda(n, n), S.Integers) == imageset(Lambda(m, m), S.Integers)
+
+    assert imageset(Lambda(n, 2*n), S.Integers).intersect(
+            imageset(Lambda(m, 2*m + 1), S.Integers)) is S.EmptySet
+
+    assert imageset(Lambda(n, 2*n), S.Integers).intersect(
+            imageset(Lambda(n, 2*n + 1), S.Integers)) is S.EmptySet
+
+    assert imageset(Lambda(m, 2*m), S.Integers).intersect(
+                imageset(Lambda(n, 3*n), S.Integers)).dummy_eq(
+            ImageSet(Lambda(t, 6*t), S.Integers))
+
+    assert imageset(x, x/2 + Rational(1, 3), S.Integers).intersect(S.Integers) is S.EmptySet
+    assert imageset(x, x/2 + S.Half, S.Integers).intersect(S.Integers) is S.Integers
+
+    # https://github.com/sympy/sympy/issues/17355
+    S53 = ImageSet(Lambda(n, 5*n + 3), S.Integers)
+    assert S53.intersect(S.Integers) == S53
+
+
+def test_infinitely_indexed_set_2():
+    from sympy.abc import n
+    a = Symbol('a', integer=True)
+    assert imageset(Lambda(n, n), S.Integers) == \
+        imageset(Lambda(n, n + a), S.Integers)
+    assert imageset(Lambda(n, n + pi), S.Integers) == \
+        imageset(Lambda(n, n + a + pi), S.Integers)
+    assert imageset(Lambda(n, n), S.Integers) == \
+        imageset(Lambda(n, -n + a), S.Integers)
+    assert imageset(Lambda(n, -6*n), S.Integers) == \
+        ImageSet(Lambda(n, 6*n), S.Integers)
+    assert imageset(Lambda(n, 2*n + pi), S.Integers) == \
+        ImageSet(Lambda(n, 2*n + pi - 2), S.Integers)
+
+
+def test_imageset_intersect_real():
+    from sympy.abc import n
+    assert imageset(Lambda(n, n + (n - 1)*(n + 1)*I), S.Integers).intersect(S.Reals) == FiniteSet(-1, 1)
+    im = (n - 1)*(n + S.Half)
+    assert imageset(Lambda(n, n + im*I), S.Integers
+        ).intersect(S.Reals) == FiniteSet(1)
+    assert imageset(Lambda(n, n + im*(n + 1)*I), S.Naturals0
+        ).intersect(S.Reals) == FiniteSet(1)
+    assert imageset(Lambda(n, n/2 + im.expand()*I), S.Integers
+        ).intersect(S.Reals) == ImageSet(Lambda(x, x/2), ConditionSet(
+        n, Eq(n**2 - n/2 - S(1)/2, 0), S.Integers))
+    assert imageset(Lambda(n, n/(1/n - 1) + im*(n + 1)*I), S.Integers
+        ).intersect(S.Reals) == FiniteSet(S.Half)
+    assert imageset(Lambda(n, n/(n - 6) +
+        (n - 3)*(n + 1)*I/(2*n + 2)), S.Integers).intersect(
+        S.Reals) == FiniteSet(-1)
+    assert imageset(Lambda(n, n/(n**2 - 9) +
+        (n - 3)*(n + 1)*I/(2*n + 2)), S.Integers).intersect(
+        S.Reals) is S.EmptySet
+    s = ImageSet(
+        Lambda(n, -I*(I*(2*pi*n - pi/4) + log(Abs(sqrt(-I))))),
+        S.Integers)
+    # s is unevaluated, but after intersection the result
+    # should be canonical
+    assert s.intersect(S.Reals) == imageset(
+        Lambda(n, 2*n*pi - pi/4), S.Integers) == ImageSet(
+        Lambda(n, 2*pi*n + pi*Rational(7, 4)), S.Integers)
+
+
+def test_imageset_intersect_interval():
+    from sympy.abc import n
+    f1 = ImageSet(Lambda(n, n*pi), S.Integers)
+    f2 = ImageSet(Lambda(n, 2*n), Interval(0, pi))
+    f3 = ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers)
+    # complex expressions
+    f4 = ImageSet(Lambda(n, n*I*pi), S.Integers)
+    f5 = ImageSet(Lambda(n, 2*I*n*pi + pi/2), S.Integers)
+    # non-linear expressions
+    f6 = ImageSet(Lambda(n, log(n)), S.Integers)
+    f7 = ImageSet(Lambda(n, n**2), S.Integers)
+    f8 = ImageSet(Lambda(n, Abs(n)), S.Integers)
+    f9 = ImageSet(Lambda(n, exp(n)), S.Naturals0)
+
+    assert f1.intersect(Interval(-1, 1)) == FiniteSet(0)
+    assert f1.intersect(Interval(0, 2*pi, False, True)) == FiniteSet(0, pi)
+    assert f2.intersect(Interval(1, 2)) == Interval(1, 2)
+    assert f3.intersect(Interval(-1, 1)) == S.EmptySet
+    assert f3.intersect(Interval(-5, 5)) == FiniteSet(pi*Rational(-3, 2), pi/2)
+    assert f4.intersect(Interval(-1, 1)) == FiniteSet(0)
+    assert f4.intersect(Interval(1, 2)) == S.EmptySet
+    assert f5.intersect(Interval(0, 1)) == S.EmptySet
+    assert f6.intersect(Interval(0, 1)) == FiniteSet(S.Zero, log(2))
+    assert f7.intersect(Interval(0, 10)) == Intersection(f7, Interval(0, 10))
+    assert f8.intersect(Interval(0, 2)) == Intersection(f8, Interval(0, 2))
+    assert f9.intersect(Interval(1, 2)) == Intersection(f9, Interval(1, 2))
+
+
+def test_imageset_intersect_diophantine():
+    from sympy.abc import m, n
+    # Check that same lambda variable for both ImageSets is handled correctly
+    img1 = ImageSet(Lambda(n, 2*n + 1), S.Integers)
+    img2 = ImageSet(Lambda(n, 4*n + 1), S.Integers)
+    assert img1.intersect(img2) == img2
+    # Empty solution set returned by diophantine:
+    assert ImageSet(Lambda(n, 2*n), S.Integers).intersect(
+            ImageSet(Lambda(n, 2*n + 1), S.Integers)) == S.EmptySet
+    # Check intersection with S.Integers:
+    assert ImageSet(Lambda(n, 9/n + 20*n/3), S.Integers).intersect(
+            S.Integers) == FiniteSet(-61, -23, 23, 61)
+    # Single solution (2, 3) for diophantine solution:
+    assert ImageSet(Lambda(n, (n - 2)**2), S.Integers).intersect(
+            ImageSet(Lambda(n, -(n - 3)**2), S.Integers)) == FiniteSet(0)
+    # Single parametric solution for diophantine solution:
+    assert ImageSet(Lambda(n, n**2 + 5), S.Integers).intersect(
+            ImageSet(Lambda(m, 2*m), S.Integers)).dummy_eq(ImageSet(
+            Lambda(n, 4*n**2 + 4*n + 6), S.Integers))
+    # 4 non-parametric solution couples for dioph. equation:
+    assert ImageSet(Lambda(n, n**2 - 9), S.Integers).intersect(
+            ImageSet(Lambda(m, -m**2), S.Integers)) == FiniteSet(-9, 0)
+    # Double parametric solution for diophantine solution:
+    assert ImageSet(Lambda(m, m**2 + 40), S.Integers).intersect(
+            ImageSet(Lambda(n, 41*n), S.Integers)).dummy_eq(Intersection(
+            ImageSet(Lambda(m, m**2 + 40), S.Integers),
+            ImageSet(Lambda(n, 41*n), S.Integers)))
+    # Check that diophantine returns *all* (8) solutions (permute=True)
+    assert ImageSet(Lambda(n, n**4 - 2**4), S.Integers).intersect(
+            ImageSet(Lambda(m, -m**4 + 3**4), S.Integers)) == FiniteSet(0, 65)
+    assert ImageSet(Lambda(n, pi/12 + n*5*pi/12), S.Integers).intersect(
+            ImageSet(Lambda(n, 7*pi/12 + n*11*pi/12), S.Integers)).dummy_eq(ImageSet(
+            Lambda(n, 55*pi*n/12 + 17*pi/4), S.Integers))
+    # TypeError raised by diophantine (#18081)
+    assert ImageSet(Lambda(n, n*log(2)), S.Integers).intersection(
+        S.Integers).dummy_eq(Intersection(ImageSet(
+        Lambda(n, n*log(2)), S.Integers), S.Integers))
+    # NotImplementedError raised by diophantine (no solver for cubic_thue)
+    assert ImageSet(Lambda(n, n**3 + 1), S.Integers).intersect(
+            ImageSet(Lambda(n, n**3), S.Integers)).dummy_eq(Intersection(
+            ImageSet(Lambda(n, n**3 + 1), S.Integers),
+            ImageSet(Lambda(n, n**3), S.Integers)))
+
+
+def test_infinitely_indexed_set_3():
+    from sympy.abc import n, m
+    assert imageset(Lambda(m, 2*pi*m), S.Integers).intersect(
+            imageset(Lambda(n, 3*pi*n), S.Integers)).dummy_eq(
+        ImageSet(Lambda(t, 6*pi*t), S.Integers))
+    assert imageset(Lambda(n, 2*n + 1), S.Integers) == \
+        imageset(Lambda(n, 2*n - 1), S.Integers)
+    assert imageset(Lambda(n, 3*n + 2), S.Integers) == \
+        imageset(Lambda(n, 3*n - 1), S.Integers)
+
+
+def test_ImageSet_simplification():
+    from sympy.abc import n, m
+    assert imageset(Lambda(n, n), S.Integers) == S.Integers
+    assert imageset(Lambda(n, sin(n)),
+                    imageset(Lambda(m, tan(m)), S.Integers)) == \
+            imageset(Lambda(m, sin(tan(m))), S.Integers)
+    assert imageset(n, 1 + 2*n, S.Naturals) == Range(3, oo, 2)
+    assert imageset(n, 1 + 2*n, S.Naturals0) == Range(1, oo, 2)
+    assert imageset(n, 1 - 2*n, S.Naturals) == Range(-1, -oo, -2)
+
+
+def test_ImageSet_contains():
+    assert (2, S.Half) in imageset(x, (x, 1/x), S.Integers)
+    assert imageset(x, x + I*3, S.Integers).intersection(S.Reals) is S.EmptySet
+    i = Dummy(integer=True)
+    q = imageset(x, x + I*y, S.Integers).intersection(S.Reals)
+    assert q.subs(y, I*i).intersection(S.Integers) is S.Integers
+    q = imageset(x, x + I*y/x, S.Integers).intersection(S.Reals)
+    assert q.subs(y, 0) is S.Integers
+    assert q.subs(y, I*i*x).intersection(S.Integers) is S.Integers
+    z = cos(1)**2 + sin(1)**2 - 1
+    q = imageset(x, x + I*z, S.Integers).intersection(S.Reals)
+    assert q is not S.EmptySet
+
+
+def test_ComplexRegion_contains():
+    r = Symbol('r', real=True)
+    # contains in ComplexRegion
+    a = Interval(2, 3)
+    b = Interval(4, 6)
+    c = Interval(7, 9)
+    c1 = ComplexRegion(a*b)
+    c2 = ComplexRegion(Union(a*b, c*a))
+    assert 2.5 + 4.5*I in c1
+    assert 2 + 4*I in c1
+    assert 3 + 4*I in c1
+    assert 8 + 2.5*I in c2
+    assert 2.5 + 6.1*I not in c1
+    assert 4.5 + 3.2*I not in c1
+    assert c1.contains(x) == Contains(x, c1, evaluate=False)
+    assert c1.contains(r) == False
+    assert c2.contains(x) == Contains(x, c2, evaluate=False)
+    assert c2.contains(r) == False
+
+    r1 = Interval(0, 1)
+    theta1 = Interval(0, 2*S.Pi)
+    c3 = ComplexRegion(r1*theta1, polar=True)
+    assert (0.5 + I*6/10) in c3
+    assert (S.Half + I*6/10) in c3
+    assert (S.Half + .6*I) in c3
+    assert (0.5 + .6*I) in c3
+    assert I in c3
+    assert 1 in c3
+    assert 0 in c3
+    assert 1 + I not in c3
+    assert 1 - I not in c3
+    assert c3.contains(x) == Contains(x, c3, evaluate=False)
+    assert c3.contains(r + 2*I) == Contains(
+        r + 2*I, c3, evaluate=False)  # is in fact False
+    assert c3.contains(1/(1 + r**2)) == Contains(
+        1/(1 + r**2), c3, evaluate=False)  # is in fact True
+
+    r2 = Interval(0, 3)
+    theta2 = Interval(pi, 2*pi, left_open=True)
+    c4 = ComplexRegion(r2*theta2, polar=True)
+    assert c4.contains(0) == True
+    assert c4.contains(2 + I) == False
+    assert c4.contains(-2 + I) == False
+    assert c4.contains(-2 - I) == True
+    assert c4.contains(2 - I) == True
+    assert c4.contains(-2) == False
+    assert c4.contains(2) == True
+    assert c4.contains(x) == Contains(x, c4, evaluate=False)
+    assert c4.contains(3/(1 + r**2)) == Contains(
+        3/(1 + r**2), c4, evaluate=False)  # is in fact True
+
+    raises(ValueError, lambda: ComplexRegion(r1*theta1, polar=2))
+
+
+def test_symbolic_Range():
+    n = Symbol('n')
+    raises(ValueError, lambda: Range(n)[0])
+    raises(IndexError, lambda: Range(n, n)[0])
+    raises(ValueError, lambda: Range(n, n+1)[0])
+    raises(ValueError, lambda: Range(n).size)
+
+    n = Symbol('n', integer=True)
+    raises(ValueError, lambda: Range(n)[0])
+    raises(IndexError, lambda: Range(n, n)[0])
+    assert Range(n, n+1)[0] == n
+    raises(ValueError, lambda: Range(n).size)
+    assert Range(n, n+1).size == 1
+
+    n = Symbol('n', integer=True, nonnegative=True)
+    raises(ValueError, lambda: Range(n)[0])
+    raises(IndexError, lambda: Range(n, n)[0])
+    assert Range(n+1)[0] == 0
+    assert Range(n, n+1)[0] == n
+    assert Range(n).size == n
+    assert Range(n+1).size == n+1
+    assert Range(n, n+1).size == 1
+
+    n = Symbol('n', integer=True, positive=True)
+    assert Range(n)[0] == 0
+    assert Range(n, n+1)[0] == n
+    assert Range(n).size == n
+    assert Range(n, n+1).size == 1
+
+    m = Symbol('m', integer=True, positive=True)
+
+    assert Range(n, n+m)[0] == n
+    assert Range(n, n+m).size == m
+    assert Range(n, n+1).size == 1
+    assert Range(n, n+m, 2).size == floor(m/2)
+
+    m = Symbol('m', integer=True, positive=True, even=True)
+    assert Range(n, n+m, 2).size == m/2
+
+
+def test_issue_18400():
+    n = Symbol('n', integer=True)
+    raises(ValueError, lambda: imageset(lambda x: x*2, Range(n)))
+
+    n = Symbol('n', integer=True, positive=True)
+    # No exception
+    assert imageset(lambda x: x*2, Range(n)) == imageset(lambda x: x*2, Range(n))
+
+
+def test_ComplexRegion_intersect():
+    # Polar form
+    X_axis = ComplexRegion(Interval(0, oo)*FiniteSet(0, S.Pi), polar=True)
+
+    unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
+    upper_half_unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True)
+    upper_half_disk = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi), polar=True)
+    lower_half_disk = ComplexRegion(Interval(0, oo)*Interval(S.Pi, 2*S.Pi), polar=True)
+    right_half_disk = ComplexRegion(Interval(0, oo)*Interval(-S.Pi/2, S.Pi/2), polar=True)
+    first_quad_disk = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi/2), polar=True)
+
+    assert upper_half_disk.intersect(unit_disk) == upper_half_unit_disk
+    assert right_half_disk.intersect(first_quad_disk) == first_quad_disk
+    assert upper_half_disk.intersect(right_half_disk) == first_quad_disk
+    assert upper_half_disk.intersect(lower_half_disk) == X_axis
+
+    c1 = ComplexRegion(Interval(0, 4)*Interval(0, 2*S.Pi), polar=True)
+    assert c1.intersect(Interval(1, 5)) == Interval(1, 4)
+    assert c1.intersect(Interval(4, 9)) == FiniteSet(4)
+    assert c1.intersect(Interval(5, 12)) is S.EmptySet
+
+    # Rectangular form
+    X_axis = ComplexRegion(Interval(-oo, oo)*FiniteSet(0))
+
+    unit_square = ComplexRegion(Interval(-1, 1)*Interval(-1, 1))
+    upper_half_unit_square = ComplexRegion(Interval(-1, 1)*Interval(0, 1))
+    upper_half_plane = ComplexRegion(Interval(-oo, oo)*Interval(0, oo))
+    lower_half_plane = ComplexRegion(Interval(-oo, oo)*Interval(-oo, 0))
+    right_half_plane = ComplexRegion(Interval(0, oo)*Interval(-oo, oo))
+    first_quad_plane = ComplexRegion(Interval(0, oo)*Interval(0, oo))
+
+    assert upper_half_plane.intersect(unit_square) == upper_half_unit_square
+    assert right_half_plane.intersect(first_quad_plane) == first_quad_plane
+    assert upper_half_plane.intersect(right_half_plane) == first_quad_plane
+    assert upper_half_plane.intersect(lower_half_plane) == X_axis
+
+    c1 = ComplexRegion(Interval(-5, 5)*Interval(-10, 10))
+    assert c1.intersect(Interval(2, 7)) == Interval(2, 5)
+    assert c1.intersect(Interval(5, 7)) == FiniteSet(5)
+    assert c1.intersect(Interval(6, 9)) is S.EmptySet
+
+    # unevaluated object
+    C1 = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
+    C2 = ComplexRegion(Interval(-1, 1)*Interval(-1, 1))
+    assert C1.intersect(C2) == Intersection(C1, C2, evaluate=False)
+
+
+def test_ComplexRegion_union():
+    # Polar form
+    c1 = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
+    c2 = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True)
+    c3 = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi), polar=True)
+    c4 = ComplexRegion(Interval(0, oo)*Interval(S.Pi, 2*S.Pi), polar=True)
+
+    p1 = Union(Interval(0, 1)*Interval(0, 2*S.Pi), Interval(0, 1)*Interval(0, S.Pi))
+    p2 = Union(Interval(0, oo)*Interval(0, S.Pi), Interval(0, oo)*Interval(S.Pi, 2*S.Pi))
+
+    assert c1.union(c2) == ComplexRegion(p1, polar=True)
+    assert c3.union(c4) == ComplexRegion(p2, polar=True)
+
+    # Rectangular form
+    c5 = ComplexRegion(Interval(2, 5)*Interval(6, 9))
+    c6 = ComplexRegion(Interval(4, 6)*Interval(10, 12))
+    c7 = ComplexRegion(Interval(0, 10)*Interval(-10, 0))
+    c8 = ComplexRegion(Interval(12, 16)*Interval(14, 20))
+
+    p3 = Union(Interval(2, 5)*Interval(6, 9), Interval(4, 6)*Interval(10, 12))
+    p4 = Union(Interval(0, 10)*Interval(-10, 0), Interval(12, 16)*Interval(14, 20))
+
+    assert c5.union(c6) == ComplexRegion(p3)
+    assert c7.union(c8) == ComplexRegion(p4)
+
+    assert c1.union(Interval(2, 4)) == Union(c1, Interval(2, 4), evaluate=False)
+    assert c5.union(Interval(2, 4)) == Union(c5, ComplexRegion.from_real(Interval(2, 4)))
+
+
+def test_ComplexRegion_from_real():
+    c1 = ComplexRegion(Interval(0, 1) * Interval(0, 2 * S.Pi), polar=True)
+
+    raises(ValueError, lambda: c1.from_real(c1))
+    assert c1.from_real(Interval(-1, 1)) == ComplexRegion(Interval(-1, 1) * FiniteSet(0), False)
+
+
+def test_ComplexRegion_measure():
+    a, b = Interval(2, 5), Interval(4, 8)
+    theta1, theta2 = Interval(0, 2*S.Pi), Interval(0, S.Pi)
+    c1 = ComplexRegion(a*b)
+    c2 = ComplexRegion(Union(a*theta1, b*theta2), polar=True)
+
+    assert c1.measure == 12
+    assert c2.measure == 9*pi
+
+
+def test_normalize_theta_set():
+    # Interval
+    assert normalize_theta_set(Interval(pi, 2*pi)) == \
+        Union(FiniteSet(0), Interval.Ropen(pi, 2*pi))
+    assert normalize_theta_set(Interval(pi*Rational(9, 2), 5*pi)) == Interval(pi/2, pi)
+    assert normalize_theta_set(Interval(pi*Rational(-3, 2), pi/2)) == Interval.Ropen(0, 2*pi)
+    assert normalize_theta_set(Interval.open(pi*Rational(-3, 2), pi/2)) == \
+        Union(Interval.Ropen(0, pi/2), Interval.open(pi/2, 2*pi))
+    assert normalize_theta_set(Interval.open(pi*Rational(-7, 2), pi*Rational(-3, 2))) == \
+        Union(Interval.Ropen(0, pi/2), Interval.open(pi/2, 2*pi))
+    assert normalize_theta_set(Interval(-pi/2, pi/2)) == \
+        Union(Interval(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi))
+    assert normalize_theta_set(Interval.open(-pi/2, pi/2)) == \
+        Union(Interval.Ropen(0, pi/2), Interval.open(pi*Rational(3, 2), 2*pi))
+    assert normalize_theta_set(Interval(-4*pi, 3*pi)) == Interval.Ropen(0, 2*pi)
+    assert normalize_theta_set(Interval(pi*Rational(-3, 2), -pi/2)) == Interval(pi/2, pi*Rational(3, 2))
+    assert normalize_theta_set(Interval.open(0, 2*pi)) == Interval.open(0, 2*pi)
+    assert normalize_theta_set(Interval.Ropen(-pi/2, pi/2)) == \
+        Union(Interval.Ropen(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi))
+    assert normalize_theta_set(Interval.Lopen(-pi/2, pi/2)) == \
+        Union(Interval(0, pi/2), Interval.open(pi*Rational(3, 2), 2*pi))
+    assert normalize_theta_set(Interval(-pi/2, pi/2)) == \
+        Union(Interval(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi))
+    assert normalize_theta_set(Interval.open(4*pi, pi*Rational(9, 2))) == Interval.open(0, pi/2)
+    assert normalize_theta_set(Interval.Lopen(4*pi, pi*Rational(9, 2))) == Interval.Lopen(0, pi/2)
+    assert normalize_theta_set(Interval.Ropen(4*pi, pi*Rational(9, 2))) == Interval.Ropen(0, pi/2)
+    assert normalize_theta_set(Interval.open(3*pi, 5*pi)) == \
+        Union(Interval.Ropen(0, pi), Interval.open(pi, 2*pi))
+
+    # FiniteSet
+    assert normalize_theta_set(FiniteSet(0, pi, 3*pi)) == FiniteSet(0, pi)
+    assert normalize_theta_set(FiniteSet(0, pi/2, pi, 2*pi)) == FiniteSet(0, pi/2, pi)
+    assert normalize_theta_set(FiniteSet(0, -pi/2, -pi, -2*pi)) == FiniteSet(0, pi, pi*Rational(3, 2))
+    assert normalize_theta_set(FiniteSet(pi*Rational(-3, 2), pi/2)) == \
+        FiniteSet(pi/2)
+    assert normalize_theta_set(FiniteSet(2*pi)) == FiniteSet(0)
+
+    # Unions
+    assert normalize_theta_set(Union(Interval(0, pi/3), Interval(pi/2, pi))) == \
+        Union(Interval(0, pi/3), Interval(pi/2, pi))
+    assert normalize_theta_set(Union(Interval(0, pi), Interval(2*pi, pi*Rational(7, 3)))) == \
+        Interval(0, pi)
+
+    # ValueError for non-real sets
+    raises(ValueError, lambda: normalize_theta_set(S.Complexes))
+
+    # NotImplementedError for subset of reals
+    raises(NotImplementedError, lambda: normalize_theta_set(Interval(0, 1)))
+
+    # NotImplementedError without pi as coefficient
+    raises(NotImplementedError, lambda: normalize_theta_set(Interval(1, 2*pi)))
+    raises(NotImplementedError, lambda: normalize_theta_set(Interval(2*pi, 10)))
+    raises(NotImplementedError, lambda: normalize_theta_set(FiniteSet(0, 3, 3*pi)))
+
+
+def test_ComplexRegion_FiniteSet():
+    x, y, z, a, b, c = symbols('x y z a b c')
+
+    # Issue #9669
+    assert ComplexRegion(FiniteSet(a, b, c)*FiniteSet(x, y, z)) == \
+        FiniteSet(a + I*x, a + I*y, a + I*z, b + I*x, b + I*y,
+                  b + I*z, c + I*x, c + I*y, c + I*z)
+    assert ComplexRegion(FiniteSet(2)*FiniteSet(3)) == FiniteSet(2 + 3*I)
+
+
+def test_union_RealSubSet():
+    assert (S.Complexes).union(Interval(1, 2)) == S.Complexes
+    assert (S.Complexes).union(S.Integers) == S.Complexes
+
+
+def test_SetKind_fancySet():
+    G = lambda *args: ImageSet(Lambda(x, x ** 2), *args)
+    assert G(Interval(1, 4)).kind is SetKind(NumberKind)
+    assert G(FiniteSet(1, 4)).kind is SetKind(NumberKind)
+    assert S.Rationals.kind is SetKind(NumberKind)
+    assert S.Naturals.kind is SetKind(NumberKind)
+    assert S.Integers.kind is SetKind(NumberKind)
+    assert Range(3).kind is SetKind(NumberKind)
+    a = Interval(2, 3)
+    b = Interval(4, 6)
+    c1 = ComplexRegion(a*b)
+    assert c1.kind is SetKind(TupleKind(NumberKind, NumberKind))
+
+
+def test_issue_9980():
+    c1 = ComplexRegion(Interval(1, 2)*Interval(2, 3))
+    c2 = ComplexRegion(Interval(1, 5)*Interval(1, 3))
+    R = Union(c1, c2)
+    assert simplify(R) == ComplexRegion(Union(Interval(1, 2)*Interval(2, 3), \
+                                    Interval(1, 5)*Interval(1, 3)), False)
+    assert c1.func(*c1.args) == c1
+    assert R.func(*R.args) == R
+
+
+def test_issue_11732():
+    interval12 = Interval(1, 2)
+    finiteset1234 = FiniteSet(1, 2, 3, 4)
+    pointComplex = Tuple(1, 5)
+
+    assert (interval12 in S.Naturals) == False
+    assert (interval12 in S.Naturals0) == False
+    assert (interval12 in S.Integers) == False
+    assert (interval12 in S.Complexes) == False
+
+    assert (finiteset1234 in S.Naturals) == False
+    assert (finiteset1234 in S.Naturals0) == False
+    assert (finiteset1234 in S.Integers) == False
+    assert (finiteset1234 in S.Complexes) == False
+
+    assert (pointComplex in S.Naturals) == False
+    assert (pointComplex in S.Naturals0) == False
+    assert (pointComplex in S.Integers) == False
+    assert (pointComplex in S.Complexes) == True
+
+
+def test_issue_11730():
+    unit = Interval(0, 1)
+    square = ComplexRegion(unit ** 2)
+
+    assert Union(S.Complexes, FiniteSet(oo)) != S.Complexes
+    assert Union(S.Complexes, FiniteSet(eye(4))) != S.Complexes
+    assert Union(unit, square) == square
+    assert Intersection(S.Reals, square) == unit
+
+
+def test_issue_11938():
+    unit = Interval(0, 1)
+    ival = Interval(1, 2)
+    cr1 = ComplexRegion(ival * unit)
+
+    assert Intersection(cr1, S.Reals) == ival
+    assert Intersection(cr1, unit) == FiniteSet(1)
+
+    arg1 = Interval(0, S.Pi)
+    arg2 = FiniteSet(S.Pi)
+    arg3 = Interval(S.Pi / 4, 3 * S.Pi / 4)
+    cp1 = ComplexRegion(unit * arg1, polar=True)
+    cp2 = ComplexRegion(unit * arg2, polar=True)
+    cp3 = ComplexRegion(unit * arg3, polar=True)
+
+    assert Intersection(cp1, S.Reals) == Interval(-1, 1)
+    assert Intersection(cp2, S.Reals) == Interval(-1, 0)
+    assert Intersection(cp3, S.Reals) == FiniteSet(0)
+
+
+def test_issue_11914():
+    a, b = Interval(0, 1), Interval(0, pi)
+    c, d = Interval(2, 3), Interval(pi, 3 * pi / 2)
+    cp1 = ComplexRegion(a * b, polar=True)
+    cp2 = ComplexRegion(c * d, polar=True)
+
+    assert -3 in cp1.union(cp2)
+    assert -3 in cp2.union(cp1)
+    assert -5 not in cp1.union(cp2)
+
+
+def test_issue_9543():
+    assert ImageSet(Lambda(x, x**2), S.Naturals).is_subset(S.Reals)
+
+
+def test_issue_16871():
+    assert ImageSet(Lambda(x, x), FiniteSet(1)) == {1}
+    assert ImageSet(Lambda(x, x - 3), S.Integers
+        ).intersection(S.Integers) is S.Integers
+
+
+@XFAIL
+def test_issue_16871b():
+    assert ImageSet(Lambda(x, x - 3), S.Integers).is_subset(S.Integers)
+
+
+def test_issue_18050():
+    assert imageset(Lambda(x, I*x + 1), S.Integers
+        ) == ImageSet(Lambda(x, I*x + 1), S.Integers)
+    assert imageset(Lambda(x, 3*I*x + 4 + 8*I), S.Integers
+        ) == ImageSet(Lambda(x, 3*I*x + 4 + 2*I), S.Integers)
+    # no 'Mod' for next 2 tests:
+    assert imageset(Lambda(x, 2*x + 3*I), S.Integers
+        ) == ImageSet(Lambda(x, 2*x + 3*I), S.Integers)
+    r = Symbol('r', positive=True)
+    assert imageset(Lambda(x, r*x + 10), S.Integers
+        ) == ImageSet(Lambda(x, r*x + 10), S.Integers)
+    # reduce real part:
+    assert imageset(Lambda(x, 3*x + 8 + 5*I), S.Integers
+        ) == ImageSet(Lambda(x, 3*x + 2 + 5*I), S.Integers)
+
+
+def test_Rationals():
+    assert S.Integers.is_subset(S.Rationals)
+    assert S.Naturals.is_subset(S.Rationals)
+    assert S.Naturals0.is_subset(S.Rationals)
+    assert S.Rationals.is_subset(S.Reals)
+    assert S.Rationals.inf is -oo
+    assert S.Rationals.sup is oo
+    it = iter(S.Rationals)
+    assert [next(it) for i in range(12)] == [
+        0, 1, -1, S.Half, 2, Rational(-1, 2), -2,
+        Rational(1, 3), 3, Rational(-1, 3), -3, Rational(2, 3)]
+    assert Basic() not in S.Rationals
+    assert S.Half in S.Rationals
+    assert S.Rationals.contains(0.5) == Contains(
+        0.5, S.Rationals, evaluate=False)
+    assert 2 in S.Rationals
+    r = symbols('r', rational=True)
+    assert r in S.Rationals
+    raises(TypeError, lambda: x in S.Rationals)
+    # issue #18134:
+    assert S.Rationals.boundary == S.Reals
+    assert S.Rationals.closure == S.Reals
+    assert S.Rationals.is_open == False
+    assert S.Rationals.is_closed == False
+
+
+def test_NZQRC_unions():
+    # check that all trivial number set unions are simplified:
+    nbrsets = (S.Naturals, S.Naturals0, S.Integers, S.Rationals,
+        S.Reals, S.Complexes)
+    unions = (Union(a, b) for a in nbrsets for b in nbrsets)
+    assert all(u.is_Union is False for u in unions)
+
+
+def test_imageset_intersection():
+    n = Dummy()
+    s = ImageSet(Lambda(n, -I*(I*(2*pi*n - pi/4) +
+        log(Abs(sqrt(-I))))), S.Integers)
+    assert s.intersect(S.Reals) == ImageSet(
+        Lambda(n, 2*pi*n + pi*Rational(7, 4)), S.Integers)
+
+
+def test_issue_17858():
+    assert 1 in Range(-oo, oo)
+    assert 0 in Range(oo, -oo, -1)
+    assert oo not in Range(-oo, oo)
+    assert -oo not in Range(-oo, oo)
+
+def test_issue_17859():
+    r = Range(-oo,oo)
+    raises(ValueError,lambda: r[::2])
+    raises(ValueError, lambda: r[::-2])
+    r = Range(oo,-oo,-1)
+    raises(ValueError,lambda: r[::2])
+    raises(ValueError, lambda: r[::-2])
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_ordinals.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_ordinals.py
new file mode 100644
index 0000000000000000000000000000000000000000..973ca329586f3e904f9377c44022c266f81c805c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_ordinals.py
@@ -0,0 +1,67 @@
+from sympy.sets.ordinals import Ordinal, OmegaPower, ord0, omega
+from sympy.testing.pytest import raises
+
+def test_string_ordinals():
+    assert str(omega) == 'w'
+    assert str(Ordinal(OmegaPower(5, 3), OmegaPower(3, 2))) == 'w**5*3 + w**3*2'
+    assert str(Ordinal(OmegaPower(5, 3), OmegaPower(0, 5))) == 'w**5*3 + 5'
+    assert str(Ordinal(OmegaPower(1, 3), OmegaPower(0, 5))) == 'w*3 + 5'
+    assert str(Ordinal(OmegaPower(omega + 1, 1), OmegaPower(3, 2))) == 'w**(w + 1) + w**3*2'
+
+def test_addition_with_integers():
+    assert 3 + Ordinal(OmegaPower(5, 3)) == Ordinal(OmegaPower(5, 3))
+    assert Ordinal(OmegaPower(5, 3))+3 == Ordinal(OmegaPower(5, 3), OmegaPower(0, 3))
+    assert Ordinal(OmegaPower(5, 3), OmegaPower(0, 2))+3 == \
+        Ordinal(OmegaPower(5, 3), OmegaPower(0, 5))
+
+
+def test_addition_with_ordinals():
+    assert Ordinal(OmegaPower(5, 3), OmegaPower(3, 2)) + Ordinal(OmegaPower(3, 3)) == \
+        Ordinal(OmegaPower(5, 3), OmegaPower(3, 5))
+    assert Ordinal(OmegaPower(5, 3), OmegaPower(3, 2)) + Ordinal(OmegaPower(4, 2)) == \
+        Ordinal(OmegaPower(5, 3), OmegaPower(4, 2))
+    assert Ordinal(OmegaPower(omega, 2), OmegaPower(3, 2)) + Ordinal(OmegaPower(4, 2)) == \
+        Ordinal(OmegaPower(omega, 2), OmegaPower(4, 2))
+
+def test_comparison():
+    assert Ordinal(OmegaPower(5, 3)) > Ordinal(OmegaPower(4, 3), OmegaPower(2, 1))
+    assert Ordinal(OmegaPower(5, 3), OmegaPower(3, 2)) < Ordinal(OmegaPower(5, 4))
+    assert Ordinal(OmegaPower(5, 4)) < Ordinal(OmegaPower(5, 5), OmegaPower(4, 1))
+
+    assert Ordinal(OmegaPower(5, 3), OmegaPower(3, 2)) == \
+        Ordinal(OmegaPower(5, 3), OmegaPower(3, 2))
+    assert not Ordinal(OmegaPower(5, 3), OmegaPower(3, 2)) == Ordinal(OmegaPower(5, 3))
+    assert Ordinal(OmegaPower(omega, 3)) > Ordinal(OmegaPower(5, 3))
+
+def test_multiplication_with_integers():
+    w = omega
+    assert 3*w == w
+    assert w*9 == Ordinal(OmegaPower(1, 9))
+
+def test_multiplication():
+    w = omega
+    assert w*(w + 1) == w*w + w
+    assert (w + 1)*(w + 1) ==  w*w + w + 1
+    assert w*1 == w
+    assert 1*w == w
+    assert w*ord0 == ord0
+    assert ord0*w == ord0
+    assert w**w == w * w**w
+    assert (w**w)*w*w == w**(w + 2)
+
+def test_exponentiation():
+    w = omega
+    assert w**2 == w*w
+    assert w**3 == w*w*w
+    assert w**(w + 1) == Ordinal(OmegaPower(omega + 1, 1))
+    assert (w**w)*(w**w) == w**(w*2)
+
+def test_comapre_not_instance():
+    w = OmegaPower(omega + 1, 1)
+    assert(not (w == None))
+    assert(not (w < 5))
+    raises(TypeError, lambda: w < 6.66)
+
+def test_is_successort():
+    w = Ordinal(OmegaPower(5, 1))
+    assert not w.is_successor_ordinal
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_powerset.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_powerset.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e3a407d565f6b9537a296af103ec0a4e137cff9
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_powerset.py
@@ -0,0 +1,141 @@
+from sympy.core.expr import unchanged
+from sympy.core.singleton import S
+from sympy.core.symbol import Symbol
+from sympy.sets.contains import Contains
+from sympy.sets.fancysets import Interval
+from sympy.sets.powerset import PowerSet
+from sympy.sets.sets import FiniteSet
+from sympy.testing.pytest import raises, XFAIL
+
+
+def test_powerset_creation():
+    assert unchanged(PowerSet, FiniteSet(1, 2))
+    assert unchanged(PowerSet, S.EmptySet)
+    raises(ValueError, lambda: PowerSet(123))
+    assert unchanged(PowerSet, S.Reals)
+    assert unchanged(PowerSet, S.Integers)
+
+
+def test_powerset_rewrite_FiniteSet():
+    assert PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet) == \
+        FiniteSet(S.EmptySet, FiniteSet(1), FiniteSet(2), FiniteSet(1, 2))
+    assert PowerSet(S.EmptySet).rewrite(FiniteSet) == FiniteSet(S.EmptySet)
+    assert PowerSet(S.Naturals).rewrite(FiniteSet) == PowerSet(S.Naturals)
+
+
+def test_finiteset_rewrite_powerset():
+    assert FiniteSet(S.EmptySet).rewrite(PowerSet) == PowerSet(S.EmptySet)
+    assert FiniteSet(
+        S.EmptySet, FiniteSet(1),
+        FiniteSet(2), FiniteSet(1, 2)).rewrite(PowerSet) == \
+            PowerSet(FiniteSet(1, 2))
+    assert FiniteSet(1, 2, 3).rewrite(PowerSet) == FiniteSet(1, 2, 3)
+
+
+def test_powerset__contains__():
+    subset_series = [
+        S.EmptySet,
+        FiniteSet(1, 2),
+        S.Naturals,
+        S.Naturals0,
+        S.Integers,
+        S.Rationals,
+        S.Reals,
+        S.Complexes]
+
+    l = len(subset_series)
+    for i in range(l):
+        for j in range(l):
+            if i <= j:
+                assert subset_series[i] in \
+                    PowerSet(subset_series[j], evaluate=False)
+            else:
+                assert subset_series[i] not in \
+                    PowerSet(subset_series[j], evaluate=False)
+
+
+@XFAIL
+def test_failing_powerset__contains__():
+    # XXX These are failing when evaluate=True,
+    # but using unevaluated PowerSet works fine.
+    assert FiniteSet(1, 2) not in PowerSet(S.EmptySet).rewrite(FiniteSet)
+    assert S.Naturals not in PowerSet(S.EmptySet).rewrite(FiniteSet)
+    assert S.Naturals not in PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet)
+    assert S.Naturals0 not in PowerSet(S.EmptySet).rewrite(FiniteSet)
+    assert S.Naturals0 not in PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet)
+    assert S.Integers not in PowerSet(S.EmptySet).rewrite(FiniteSet)
+    assert S.Integers not in PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet)
+    assert S.Rationals not in PowerSet(S.EmptySet).rewrite(FiniteSet)
+    assert S.Rationals not in PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet)
+    assert S.Reals not in PowerSet(S.EmptySet).rewrite(FiniteSet)
+    assert S.Reals not in PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet)
+    assert S.Complexes not in PowerSet(S.EmptySet).rewrite(FiniteSet)
+    assert S.Complexes not in PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet)
+
+
+def test_powerset__len__():
+    A = PowerSet(S.EmptySet, evaluate=False)
+    assert len(A) == 1
+    A = PowerSet(A, evaluate=False)
+    assert len(A) == 2
+    A = PowerSet(A, evaluate=False)
+    assert len(A) == 4
+    A = PowerSet(A, evaluate=False)
+    assert len(A) == 16
+
+
+def test_powerset__iter__():
+    a = PowerSet(FiniteSet(1, 2)).__iter__()
+    assert next(a) == S.EmptySet
+    assert next(a) == FiniteSet(1)
+    assert next(a) == FiniteSet(2)
+    assert next(a) == FiniteSet(1, 2)
+
+    a = PowerSet(S.Naturals).__iter__()
+    assert next(a) == S.EmptySet
+    assert next(a) == FiniteSet(1)
+    assert next(a) == FiniteSet(2)
+    assert next(a) == FiniteSet(1, 2)
+    assert next(a) == FiniteSet(3)
+    assert next(a) == FiniteSet(1, 3)
+    assert next(a) == FiniteSet(2, 3)
+    assert next(a) == FiniteSet(1, 2, 3)
+
+
+def test_powerset_contains():
+    A = PowerSet(FiniteSet(1), evaluate=False)
+    assert A.contains(2) == Contains(2, A)
+
+    x = Symbol('x')
+
+    A = PowerSet(FiniteSet(x), evaluate=False)
+    assert A.contains(FiniteSet(1)) == Contains(FiniteSet(1), A)
+
+
+def test_powerset_method():
+    # EmptySet
+    A = FiniteSet()
+    pset = A.powerset()
+    assert len(pset) == 1
+    assert pset ==  FiniteSet(S.EmptySet)
+
+    # FiniteSets
+    A = FiniteSet(1, 2)
+    pset = A.powerset()
+    assert len(pset) == 2**len(A)
+    assert pset == FiniteSet(FiniteSet(), FiniteSet(1),
+                             FiniteSet(2), A)
+    # Not finite sets
+    A = Interval(0, 1)
+    assert A.powerset() == PowerSet(A)
+
+def test_is_subset():
+    # covers line 101-102
+    # initialize powerset(1), which is a subset of powerset(1,2)
+    subset = PowerSet(FiniteSet(1))
+    pset = PowerSet(FiniteSet(1, 2))
+    bad_set = PowerSet(FiniteSet(2, 3))
+    # assert "subset" is subset of pset == True
+    assert subset.is_subset(pset)
+    # assert "bad_set" is subset of pset == False
+    assert not pset.is_subset(bad_set)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_setexpr.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_setexpr.py
new file mode 100644
index 0000000000000000000000000000000000000000..faab1261c8d3e86901b04d30e8bc94de31642b93
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_setexpr.py
@@ -0,0 +1,317 @@
+from sympy.sets.setexpr import SetExpr
+from sympy.sets import Interval, FiniteSet, Intersection, ImageSet, Union
+
+from sympy.core.expr import Expr
+from sympy.core.function import Lambda
+from sympy.core.numbers import (I, Rational, oo)
+from sympy.core.singleton import S
+from sympy.core.symbol import (Dummy, Symbol, symbols)
+from sympy.functions.elementary.exponential import (exp, log)
+from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
+from sympy.functions.elementary.trigonometric import cos
+from sympy.sets.sets import Set
+
+
+a, x = symbols("a, x")
+_d = Dummy("d")
+
+
+def test_setexpr():
+    se = SetExpr(Interval(0, 1))
+    assert isinstance(se.set, Set)
+    assert isinstance(se, Expr)
+
+
+def test_scalar_funcs():
+    assert SetExpr(Interval(0, 1)).set == Interval(0, 1)
+    a, b = Symbol('a', real=True), Symbol('b', real=True)
+    a, b = 1, 2
+    # TODO: add support for more functions in the future:
+    for f in [exp, log]:
+        input_se = f(SetExpr(Interval(a, b)))
+        output = input_se.set
+        expected = Interval(Min(f(a), f(b)), Max(f(a), f(b)))
+        assert output == expected
+
+
+def test_Add_Mul():
+    assert (SetExpr(Interval(0, 1)) + 1).set == Interval(1, 2)
+    assert (SetExpr(Interval(0, 1))*2).set == Interval(0, 2)
+
+
+def test_Pow():
+    assert (SetExpr(Interval(0, 2))**2).set == Interval(0, 4)
+
+
+def test_compound():
+    assert (exp(SetExpr(Interval(0, 1))*2 + 1)).set == \
+           Interval(exp(1), exp(3))
+
+
+def test_Interval_Interval():
+    assert (SetExpr(Interval(1, 2)) + SetExpr(Interval(10, 20))).set == \
+           Interval(11, 22)
+    assert (SetExpr(Interval(1, 2))*SetExpr(Interval(10, 20))).set == \
+           Interval(10, 40)
+
+
+def test_FiniteSet_FiniteSet():
+    assert (SetExpr(FiniteSet(1, 2, 3)) + SetExpr(FiniteSet(1, 2))).set == \
+           FiniteSet(2, 3, 4, 5)
+    assert (SetExpr(FiniteSet(1, 2, 3))*SetExpr(FiniteSet(1, 2))).set == \
+           FiniteSet(1, 2, 3, 4, 6)
+
+
+def test_Interval_FiniteSet():
+    assert (SetExpr(FiniteSet(1, 2)) + SetExpr(Interval(0, 10))).set == \
+           Interval(1, 12)
+
+
+def test_Many_Sets():
+    assert (SetExpr(Interval(0, 1)) +
+            SetExpr(Interval(2, 3)) +
+            SetExpr(FiniteSet(10, 11, 12))).set == Interval(12, 16)
+
+
+def test_same_setexprs_are_not_identical():
+    a = SetExpr(FiniteSet(0, 1))
+    b = SetExpr(FiniteSet(0, 1))
+    assert (a + b).set == FiniteSet(0, 1, 2)
+
+    # Cannot detect the set being the same:
+    # assert (a + a).set == FiniteSet(0, 2)
+
+
+def test_Interval_arithmetic():
+    i12cc = SetExpr(Interval(1, 2))
+    i12lo = SetExpr(Interval.Lopen(1, 2))
+    i12ro = SetExpr(Interval.Ropen(1, 2))
+    i12o = SetExpr(Interval.open(1, 2))
+
+    n23cc = SetExpr(Interval(-2, 3))
+    n23lo = SetExpr(Interval.Lopen(-2, 3))
+    n23ro = SetExpr(Interval.Ropen(-2, 3))
+    n23o = SetExpr(Interval.open(-2, 3))
+
+    n3n2cc = SetExpr(Interval(-3, -2))
+
+    assert i12cc + i12cc == SetExpr(Interval(2, 4))
+    assert i12cc - i12cc == SetExpr(Interval(-1, 1))
+    assert i12cc*i12cc == SetExpr(Interval(1, 4))
+    assert i12cc/i12cc == SetExpr(Interval(S.Half, 2))
+    assert i12cc**2 == SetExpr(Interval(1, 4))
+    assert i12cc**3 == SetExpr(Interval(1, 8))
+
+    assert i12lo + i12ro == SetExpr(Interval.open(2, 4))
+    assert i12lo - i12ro == SetExpr(Interval.Lopen(-1, 1))
+    assert i12lo*i12ro == SetExpr(Interval.open(1, 4))
+    assert i12lo/i12ro == SetExpr(Interval.Lopen(S.Half, 2))
+    assert i12lo + i12lo == SetExpr(Interval.Lopen(2, 4))
+    assert i12lo - i12lo == SetExpr(Interval.open(-1, 1))
+    assert i12lo*i12lo == SetExpr(Interval.Lopen(1, 4))
+    assert i12lo/i12lo == SetExpr(Interval.open(S.Half, 2))
+    assert i12lo + i12cc == SetExpr(Interval.Lopen(2, 4))
+    assert i12lo - i12cc == SetExpr(Interval.Lopen(-1, 1))
+    assert i12lo*i12cc == SetExpr(Interval.Lopen(1, 4))
+    assert i12lo/i12cc == SetExpr(Interval.Lopen(S.Half, 2))
+    assert i12lo + i12o == SetExpr(Interval.open(2, 4))
+    assert i12lo - i12o == SetExpr(Interval.open(-1, 1))
+    assert i12lo*i12o == SetExpr(Interval.open(1, 4))
+    assert i12lo/i12o == SetExpr(Interval.open(S.Half, 2))
+    assert i12lo**2 == SetExpr(Interval.Lopen(1, 4))
+    assert i12lo**3 == SetExpr(Interval.Lopen(1, 8))
+
+    assert i12ro + i12ro == SetExpr(Interval.Ropen(2, 4))
+    assert i12ro - i12ro == SetExpr(Interval.open(-1, 1))
+    assert i12ro*i12ro == SetExpr(Interval.Ropen(1, 4))
+    assert i12ro/i12ro == SetExpr(Interval.open(S.Half, 2))
+    assert i12ro + i12cc == SetExpr(Interval.Ropen(2, 4))
+    assert i12ro - i12cc == SetExpr(Interval.Ropen(-1, 1))
+    assert i12ro*i12cc == SetExpr(Interval.Ropen(1, 4))
+    assert i12ro/i12cc == SetExpr(Interval.Ropen(S.Half, 2))
+    assert i12ro + i12o == SetExpr(Interval.open(2, 4))
+    assert i12ro - i12o == SetExpr(Interval.open(-1, 1))
+    assert i12ro*i12o == SetExpr(Interval.open(1, 4))
+    assert i12ro/i12o == SetExpr(Interval.open(S.Half, 2))
+    assert i12ro**2 == SetExpr(Interval.Ropen(1, 4))
+    assert i12ro**3 == SetExpr(Interval.Ropen(1, 8))
+
+    assert i12o + i12lo == SetExpr(Interval.open(2, 4))
+    assert i12o - i12lo == SetExpr(Interval.open(-1, 1))
+    assert i12o*i12lo == SetExpr(Interval.open(1, 4))
+    assert i12o/i12lo == SetExpr(Interval.open(S.Half, 2))
+    assert i12o + i12ro == SetExpr(Interval.open(2, 4))
+    assert i12o - i12ro == SetExpr(Interval.open(-1, 1))
+    assert i12o*i12ro == SetExpr(Interval.open(1, 4))
+    assert i12o/i12ro == SetExpr(Interval.open(S.Half, 2))
+    assert i12o + i12cc == SetExpr(Interval.open(2, 4))
+    assert i12o - i12cc == SetExpr(Interval.open(-1, 1))
+    assert i12o*i12cc == SetExpr(Interval.open(1, 4))
+    assert i12o/i12cc == SetExpr(Interval.open(S.Half, 2))
+    assert i12o**2 == SetExpr(Interval.open(1, 4))
+    assert i12o**3 == SetExpr(Interval.open(1, 8))
+
+    assert n23cc + n23cc == SetExpr(Interval(-4, 6))
+    assert n23cc - n23cc == SetExpr(Interval(-5, 5))
+    assert n23cc*n23cc == SetExpr(Interval(-6, 9))
+    assert n23cc/n23cc == SetExpr(Interval.open(-oo, oo))
+    assert n23cc + n23ro == SetExpr(Interval.Ropen(-4, 6))
+    assert n23cc - n23ro == SetExpr(Interval.Lopen(-5, 5))
+    assert n23cc*n23ro == SetExpr(Interval.Ropen(-6, 9))
+    assert n23cc/n23ro == SetExpr(Interval.Lopen(-oo, oo))
+    assert n23cc + n23lo == SetExpr(Interval.Lopen(-4, 6))
+    assert n23cc - n23lo == SetExpr(Interval.Ropen(-5, 5))
+    assert n23cc*n23lo == SetExpr(Interval(-6, 9))
+    assert n23cc/n23lo == SetExpr(Interval.open(-oo, oo))
+    assert n23cc + n23o == SetExpr(Interval.open(-4, 6))
+    assert n23cc - n23o == SetExpr(Interval.open(-5, 5))
+    assert n23cc*n23o == SetExpr(Interval.open(-6, 9))
+    assert n23cc/n23o == SetExpr(Interval.open(-oo, oo))
+    assert n23cc**2 == SetExpr(Interval(0, 9))
+    assert n23cc**3 == SetExpr(Interval(-8, 27))
+
+    n32cc = SetExpr(Interval(-3, 2))
+    n32lo = SetExpr(Interval.Lopen(-3, 2))
+    n32ro = SetExpr(Interval.Ropen(-3, 2))
+    assert n32cc*n32lo == SetExpr(Interval.Ropen(-6, 9))
+    assert n32cc*n32cc == SetExpr(Interval(-6, 9))
+    assert n32lo*n32cc == SetExpr(Interval.Ropen(-6, 9))
+    assert n32cc*n32ro == SetExpr(Interval(-6, 9))
+    assert n32lo*n32ro == SetExpr(Interval.Ropen(-6, 9))
+    assert n32cc/n32lo == SetExpr(Interval.Ropen(-oo, oo))
+    assert i12cc/n32lo == SetExpr(Interval.Ropen(-oo, oo))
+
+    assert n3n2cc**2 == SetExpr(Interval(4, 9))
+    assert n3n2cc**3 == SetExpr(Interval(-27, -8))
+
+    assert n23cc + i12cc == SetExpr(Interval(-1, 5))
+    assert n23cc - i12cc == SetExpr(Interval(-4, 2))
+    assert n23cc*i12cc == SetExpr(Interval(-4, 6))
+    assert n23cc/i12cc == SetExpr(Interval(-2, 3))
+
+
+def test_SetExpr_Intersection():
+    x, y, z, w = symbols("x y z w")
+    set1 = Interval(x, y)
+    set2 = Interval(w, z)
+    inter = Intersection(set1, set2)
+    se = SetExpr(inter)
+    assert exp(se).set == Intersection(
+        ImageSet(Lambda(x, exp(x)), set1),
+        ImageSet(Lambda(x, exp(x)), set2))
+    assert cos(se).set == ImageSet(Lambda(x, cos(x)), inter)
+
+
+def test_SetExpr_Interval_div():
+    # TODO: some expressions cannot be calculated due to bugs (currently
+    # commented):
+    assert SetExpr(Interval(-3, -2))/SetExpr(Interval(-2, 1)) == SetExpr(Interval(-oo, oo))
+    assert SetExpr(Interval(2, 3))/SetExpr(Interval(-2, 2)) == SetExpr(Interval(-oo, oo))
+
+    assert SetExpr(Interval(-3, -2))/SetExpr(Interval(0, 4)) == SetExpr(Interval(-oo, Rational(-1, 2)))
+    assert SetExpr(Interval(2, 4))/SetExpr(Interval(-3, 0)) == SetExpr(Interval(-oo, Rational(-2, 3)))
+    assert SetExpr(Interval(2, 4))/SetExpr(Interval(0, 3)) == SetExpr(Interval(Rational(2, 3), oo))
+
+    # assert SetExpr(Interval(0, 1))/SetExpr(Interval(0, 1)) == SetExpr(Interval(0, oo))
+    # assert SetExpr(Interval(-1, 0))/SetExpr(Interval(0, 1)) == SetExpr(Interval(-oo, 0))
+    assert SetExpr(Interval(-1, 2))/SetExpr(Interval(-2, 2)) == SetExpr(Interval(-oo, oo))
+
+    assert 1/SetExpr(Interval(-1, 2)) == SetExpr(Union(Interval(-oo, -1), Interval(S.Half, oo)))
+
+    assert 1/SetExpr(Interval(0, 2)) == SetExpr(Interval(S.Half, oo))
+    assert (-1)/SetExpr(Interval(0, 2)) == SetExpr(Interval(-oo, Rational(-1, 2)))
+    assert 1/SetExpr(Interval(-oo, 0)) == SetExpr(Interval.open(-oo, 0))
+    assert 1/SetExpr(Interval(-1, 0)) == SetExpr(Interval(-oo, -1))
+    # assert (-2)/SetExpr(Interval(-oo, 0)) == SetExpr(Interval(0, oo))
+    # assert 1/SetExpr(Interval(-oo, -1)) == SetExpr(Interval(-1, 0))
+
+    # assert SetExpr(Interval(1, 2))/a == Mul(SetExpr(Interval(1, 2)), 1/a, evaluate=False)
+
+    # assert SetExpr(Interval(1, 2))/0 == SetExpr(Interval(1, 2))*zoo
+    # assert SetExpr(Interval(1, oo))/oo == SetExpr(Interval(0, oo))
+    # assert SetExpr(Interval(1, oo))/(-oo) == SetExpr(Interval(-oo, 0))
+    # assert SetExpr(Interval(-oo, -1))/oo == SetExpr(Interval(-oo, 0))
+    # assert SetExpr(Interval(-oo, -1))/(-oo) == SetExpr(Interval(0, oo))
+    # assert SetExpr(Interval(-oo, oo))/oo == SetExpr(Interval(-oo, oo))
+    # assert SetExpr(Interval(-oo, oo))/(-oo) == SetExpr(Interval(-oo, oo))
+    # assert SetExpr(Interval(-1, oo))/oo == SetExpr(Interval(0, oo))
+    # assert SetExpr(Interval(-1, oo))/(-oo) == SetExpr(Interval(-oo, 0))
+    # assert SetExpr(Interval(-oo, 1))/oo == SetExpr(Interval(-oo, 0))
+    # assert SetExpr(Interval(-oo, 1))/(-oo) == SetExpr(Interval(0, oo))
+
+
+def test_SetExpr_Interval_pow():
+    assert SetExpr(Interval(0, 2))**2 == SetExpr(Interval(0, 4))
+    assert SetExpr(Interval(-1, 1))**2 == SetExpr(Interval(0, 1))
+    assert SetExpr(Interval(1, 2))**2 == SetExpr(Interval(1, 4))
+    assert SetExpr(Interval(-1, 2))**3 == SetExpr(Interval(-1, 8))
+    assert SetExpr(Interval(-1, 1))**0 == SetExpr(FiniteSet(1))
+
+
+    assert SetExpr(Interval(1, 2))**Rational(5, 2) == SetExpr(Interval(1, 4*sqrt(2)))
+    #assert SetExpr(Interval(-1, 2))**Rational(1, 3) == SetExpr(Interval(-1, 2**Rational(1, 3)))
+    #assert SetExpr(Interval(0, 2))**S.Half == SetExpr(Interval(0, sqrt(2)))
+
+    #assert SetExpr(Interval(-4, 2))**Rational(2, 3) == SetExpr(Interval(0, 2*2**Rational(1, 3)))
+
+    #assert SetExpr(Interval(-1, 5))**S.Half == SetExpr(Interval(0, sqrt(5)))
+    #assert SetExpr(Interval(-oo, 2))**S.Half == SetExpr(Interval(0, sqrt(2)))
+    #assert SetExpr(Interval(-2, 3))**(Rational(-1, 4)) == SetExpr(Interval(0, oo))
+
+    assert SetExpr(Interval(1, 5))**(-2) == SetExpr(Interval(Rational(1, 25), 1))
+    assert SetExpr(Interval(-1, 3))**(-2) == SetExpr(Interval(0, oo))
+
+    assert SetExpr(Interval(0, 2))**(-2) == SetExpr(Interval(Rational(1, 4), oo))
+    assert SetExpr(Interval(-1, 2))**(-3) == SetExpr(Union(Interval(-oo, -1), Interval(Rational(1, 8), oo)))
+    assert SetExpr(Interval(-3, -2))**(-3) == SetExpr(Interval(Rational(-1, 8), Rational(-1, 27)))
+    assert SetExpr(Interval(-3, -2))**(-2) == SetExpr(Interval(Rational(1, 9), Rational(1, 4)))
+    #assert SetExpr(Interval(0, oo))**S.Half == SetExpr(Interval(0, oo))
+    #assert SetExpr(Interval(-oo, -1))**Rational(1, 3) == SetExpr(Interval(-oo, -1))
+    #assert SetExpr(Interval(-2, 3))**(Rational(-1, 3)) == SetExpr(Interval(-oo, oo))
+
+    assert SetExpr(Interval(-oo, 0))**(-2) == SetExpr(Interval.open(0, oo))
+    assert SetExpr(Interval(-2, 0))**(-2) == SetExpr(Interval(Rational(1, 4), oo))
+
+    assert SetExpr(Interval(Rational(1, 3), S.Half))**oo == SetExpr(FiniteSet(0))
+    assert SetExpr(Interval(0, S.Half))**oo == SetExpr(FiniteSet(0))
+    assert SetExpr(Interval(S.Half, 1))**oo == SetExpr(Interval(0, oo))
+    assert SetExpr(Interval(0, 1))**oo == SetExpr(Interval(0, oo))
+    assert SetExpr(Interval(2, 3))**oo == SetExpr(FiniteSet(oo))
+    assert SetExpr(Interval(1, 2))**oo == SetExpr(Interval(0, oo))
+    assert SetExpr(Interval(S.Half, 3))**oo == SetExpr(Interval(0, oo))
+    assert SetExpr(Interval(Rational(-1, 3), Rational(-1, 4)))**oo == SetExpr(FiniteSet(0))
+    assert SetExpr(Interval(-1, Rational(-1, 2)))**oo == SetExpr(Interval(-oo, oo))
+    assert SetExpr(Interval(-3, -2))**oo == SetExpr(FiniteSet(-oo, oo))
+    assert SetExpr(Interval(-2, -1))**oo == SetExpr(Interval(-oo, oo))
+    assert SetExpr(Interval(-2, Rational(-1, 2)))**oo == SetExpr(Interval(-oo, oo))
+    assert SetExpr(Interval(Rational(-1, 2), S.Half))**oo == SetExpr(FiniteSet(0))
+    assert SetExpr(Interval(Rational(-1, 2), 1))**oo == SetExpr(Interval(0, oo))
+    assert SetExpr(Interval(Rational(-2, 3), 2))**oo == SetExpr(Interval(0, oo))
+    assert SetExpr(Interval(-1, 1))**oo == SetExpr(Interval(-oo, oo))
+    assert SetExpr(Interval(-1, S.Half))**oo == SetExpr(Interval(-oo, oo))
+    assert SetExpr(Interval(-1, 2))**oo == SetExpr(Interval(-oo, oo))
+    assert SetExpr(Interval(-2, S.Half))**oo == SetExpr(Interval(-oo, oo))
+
+    assert (SetExpr(Interval(1, 2))**x).dummy_eq(SetExpr(ImageSet(Lambda(_d, _d**x), Interval(1, 2))))
+
+    assert SetExpr(Interval(2, 3))**(-oo) == SetExpr(FiniteSet(0))
+    assert SetExpr(Interval(0, 2))**(-oo) == SetExpr(Interval(0, oo))
+    assert (SetExpr(Interval(-1, 2))**(-oo)).dummy_eq(SetExpr(ImageSet(Lambda(_d, _d**(-oo)), Interval(-1, 2))))
+
+
+def test_SetExpr_Integers():
+    assert SetExpr(S.Integers) + 1 == SetExpr(S.Integers)
+    assert (SetExpr(S.Integers) + I).dummy_eq(
+        SetExpr(ImageSet(Lambda(_d, _d + I), S.Integers)))
+    assert SetExpr(S.Integers)*(-1) == SetExpr(S.Integers)
+    assert (SetExpr(S.Integers)*2).dummy_eq(
+        SetExpr(ImageSet(Lambda(_d, 2*_d), S.Integers)))
+    assert (SetExpr(S.Integers)*I).dummy_eq(
+        SetExpr(ImageSet(Lambda(_d, I*_d), S.Integers)))
+    # issue #18050:
+    assert SetExpr(S.Integers)._eval_func(Lambda(x, I*x + 1)).dummy_eq(
+        SetExpr(ImageSet(Lambda(_d, I*_d + 1), S.Integers)))
+    # needs improvement:
+    assert (SetExpr(S.Integers)*I + 1).dummy_eq(
+        SetExpr(ImageSet(Lambda(x, x + 1),
+        ImageSet(Lambda(_d, _d*I), S.Integers))))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_sets.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_sets.py
new file mode 100644
index 0000000000000000000000000000000000000000..657ab19a90eb88ca48f266f7a5cf050504caed43
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/sets/tests/test_sets.py
@@ -0,0 +1,1753 @@
+from sympy.concrete.summations import Sum
+from sympy.core.add import Add
+from sympy.core.containers import TupleKind
+from sympy.core.function import Lambda
+from sympy.core.kind import NumberKind, UndefinedKind
+from sympy.core.numbers import (Float, I, Rational, nan, oo, pi, zoo)
+from sympy.core.power import Pow
+from sympy.core.singleton import S
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.core.sympify import sympify
+from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.functions.elementary.trigonometric import (cos, sin)
+from sympy.logic.boolalg import (false, true)
+from sympy.matrices.kind import MatrixKind
+from sympy.matrices.dense import Matrix
+from sympy.polys.rootoftools import rootof
+from sympy.sets.contains import Contains
+from sympy.sets.fancysets import (ImageSet, Range)
+from sympy.sets.sets import (Complement, DisjointUnion, FiniteSet, Intersection, Interval, ProductSet, Set, SymmetricDifference, Union, imageset, SetKind)
+from mpmath import mpi
+
+from sympy.core.expr import unchanged
+from sympy.core.relational import Eq, Ne, Le, Lt, LessThan
+from sympy.logic import And, Or, Xor
+from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy
+from sympy.utilities.iterables import cartes
+
+from sympy.abc import x, y, z, m, n
+
+EmptySet = S.EmptySet
+
+def test_imageset():
+    ints = S.Integers
+    assert imageset(x, x - 1, S.Naturals) is S.Naturals0
+    assert imageset(x, x + 1, S.Naturals0) is S.Naturals
+    assert imageset(x, abs(x), S.Naturals0) is S.Naturals0
+    assert imageset(x, abs(x), S.Naturals) is S.Naturals
+    assert imageset(x, abs(x), S.Integers) is S.Naturals0
+    # issue 16878a
+    r = symbols('r', real=True)
+    assert imageset(x, (x, x), S.Reals)._contains((1, r)) == None
+    assert imageset(x, (x, x), S.Reals)._contains((1, 2)) == False
+    assert (r, r) in imageset(x, (x, x), S.Reals)
+    assert 1 + I in imageset(x, x + I, S.Reals)
+    assert {1} not in imageset(x, (x,), S.Reals)
+    assert (1, 1) not in imageset(x, (x,), S.Reals)
+    raises(TypeError, lambda: imageset(x, ints))
+    raises(ValueError, lambda: imageset(x, y, z, ints))
+    raises(ValueError, lambda: imageset(Lambda(x, cos(x)), y))
+    assert (1, 2) in imageset(Lambda((x, y), (x, y)), ints, ints)
+    raises(ValueError, lambda: imageset(Lambda(x, x), ints, ints))
+    assert imageset(cos, ints) == ImageSet(Lambda(x, cos(x)), ints)
+    def f(x):
+        return cos(x)
+    assert imageset(f, ints) == imageset(x, cos(x), ints)
+    f = lambda x: cos(x)
+    assert imageset(f, ints) == ImageSet(Lambda(x, cos(x)), ints)
+    assert imageset(x, 1, ints) == FiniteSet(1)
+    assert imageset(x, y, ints) == {y}
+    assert imageset((x, y), (1, z), ints, S.Reals) == {(1, z)}
+    clash = Symbol('x', integer=true)
+    assert (str(imageset(lambda x: x + clash, Interval(-2, 1)).lamda.expr)
+        in ('x0 + x', 'x + x0'))
+    x1, x2 = symbols("x1, x2")
+    assert imageset(lambda x, y:
+        Add(x, y), Interval(1, 2), Interval(2, 3)).dummy_eq(
+        ImageSet(Lambda((x1, x2), x1 + x2),
+        Interval(1, 2), Interval(2, 3)))
+
+
+def test_is_empty():
+    for s in [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals,
+            S.UniversalSet]:
+        assert s.is_empty is False
+
+    assert S.EmptySet.is_empty is True
+
+
+def test_is_finiteset():
+    for s in [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals,
+            S.UniversalSet]:
+        assert s.is_finite_set is False
+
+    assert S.EmptySet.is_finite_set is True
+
+    assert FiniteSet(1, 2).is_finite_set is True
+    assert Interval(1, 2).is_finite_set is False
+    assert Interval(x, y).is_finite_set is None
+    assert ProductSet(FiniteSet(1), FiniteSet(2)).is_finite_set is True
+    assert ProductSet(FiniteSet(1), Interval(1, 2)).is_finite_set is False
+    assert ProductSet(FiniteSet(1), Interval(x, y)).is_finite_set is None
+    assert Union(Interval(0, 1), Interval(2, 3)).is_finite_set is False
+    assert Union(FiniteSet(1), Interval(2, 3)).is_finite_set is False
+    assert Union(FiniteSet(1), FiniteSet(2)).is_finite_set is True
+    assert Union(FiniteSet(1), Interval(x, y)).is_finite_set is None
+    assert Intersection(Interval(x, y), FiniteSet(1)).is_finite_set is True
+    assert Intersection(Interval(x, y), Interval(1, 2)).is_finite_set is None
+    assert Intersection(FiniteSet(x), FiniteSet(y)).is_finite_set is True
+    assert Complement(FiniteSet(1), Interval(x, y)).is_finite_set is True
+    assert Complement(Interval(x, y), FiniteSet(1)).is_finite_set is None
+    assert Complement(Interval(1, 2), FiniteSet(x)).is_finite_set is False
+    assert DisjointUnion(Interval(-5, 3), FiniteSet(x, y)).is_finite_set is False
+    assert DisjointUnion(S.EmptySet, FiniteSet(x, y), S.EmptySet).is_finite_set is True
+
+
+def test_deprecated_is_EmptySet():
+    with warns_deprecated_sympy():
+        S.EmptySet.is_EmptySet
+
+    with warns_deprecated_sympy():
+        FiniteSet(1).is_EmptySet
+
+
+def test_interval_arguments():
+    assert Interval(0, oo) == Interval(0, oo, False, True)
+    assert Interval(0, oo).right_open is true
+    assert Interval(-oo, 0) == Interval(-oo, 0, True, False)
+    assert Interval(-oo, 0).left_open is true
+    assert Interval(oo, -oo) == S.EmptySet
+    assert Interval(oo, oo) == S.EmptySet
+    assert Interval(-oo, -oo) == S.EmptySet
+    assert Interval(oo, x) == S.EmptySet
+    assert Interval(oo, oo) == S.EmptySet
+    assert Interval(x, -oo) == S.EmptySet
+    assert Interval(x, x) == {x}
+
+    assert isinstance(Interval(1, 1), FiniteSet)
+    e = Sum(x, (x, 1, 3))
+    assert isinstance(Interval(e, e), FiniteSet)
+
+    assert Interval(1, 0) == S.EmptySet
+    assert Interval(1, 1).measure == 0
+
+    assert Interval(1, 1, False, True) == S.EmptySet
+    assert Interval(1, 1, True, False) == S.EmptySet
+    assert Interval(1, 1, True, True) == S.EmptySet
+
+
+    assert isinstance(Interval(0, Symbol('a')), Interval)
+    assert Interval(Symbol('a', positive=True), 0) == S.EmptySet
+    raises(ValueError, lambda: Interval(0, S.ImaginaryUnit))
+    raises(ValueError, lambda: Interval(0, Symbol('z', extended_real=False)))
+    raises(ValueError, lambda: Interval(x, x + S.ImaginaryUnit))
+
+    raises(NotImplementedError, lambda: Interval(0, 1, And(x, y)))
+    raises(NotImplementedError, lambda: Interval(0, 1, False, And(x, y)))
+    raises(NotImplementedError, lambda: Interval(0, 1, z, And(x, y)))
+
+
+def test_interval_symbolic_end_points():
+    a = Symbol('a', real=True)
+
+    assert Union(Interval(0, a), Interval(0, 3)).sup == Max(a, 3)
+    assert Union(Interval(a, 0), Interval(-3, 0)).inf == Min(-3, a)
+
+    assert Interval(0, a).contains(1) == LessThan(1, a)
+
+
+def test_interval_is_empty():
+    x, y = symbols('x, y')
+    r = Symbol('r', real=True)
+    p = Symbol('p', positive=True)
+    n = Symbol('n', negative=True)
+    nn = Symbol('nn', nonnegative=True)
+    assert Interval(1, 2).is_empty == False
+    assert Interval(3, 3).is_empty == False  # FiniteSet
+    assert Interval(r, r).is_empty == False  # FiniteSet
+    assert Interval(r, r + nn).is_empty == False
+    assert Interval(x, x).is_empty == False
+    assert Interval(1, oo).is_empty == False
+    assert Interval(-oo, oo).is_empty == False
+    assert Interval(-oo, 1).is_empty == False
+    assert Interval(x, y).is_empty == None
+    assert Interval(r, oo).is_empty == False  # real implies finite
+    assert Interval(n, 0).is_empty == False
+    assert Interval(n, 0, left_open=True).is_empty == False
+    assert Interval(p, 0).is_empty == True  # EmptySet
+    assert Interval(nn, 0).is_empty == None
+    assert Interval(n, p).is_empty == False
+    assert Interval(0, p, left_open=True).is_empty == False
+    assert Interval(0, p, right_open=True).is_empty == False
+    assert Interval(0, nn, left_open=True).is_empty == None
+    assert Interval(0, nn, right_open=True).is_empty == None
+
+
+def test_union():
+    assert Union(Interval(1, 2), Interval(2, 3)) == Interval(1, 3)
+    assert Union(Interval(1, 2), Interval(2, 3, True)) == Interval(1, 3)
+    assert Union(Interval(1, 3), Interval(2, 4)) == Interval(1, 4)
+    assert Union(Interval(1, 2), Interval(1, 3)) == Interval(1, 3)
+    assert Union(Interval(1, 3), Interval(1, 2)) == Interval(1, 3)
+    assert Union(Interval(1, 3, False, True), Interval(1, 2)) == \
+        Interval(1, 3, False, True)
+    assert Union(Interval(1, 3), Interval(1, 2, False, True)) == Interval(1, 3)
+    assert Union(Interval(1, 2, True), Interval(1, 3)) == Interval(1, 3)
+    assert Union(Interval(1, 2, True), Interval(1, 3, True)) == \
+        Interval(1, 3, True)
+    assert Union(Interval(1, 2, True), Interval(1, 3, True, True)) == \
+        Interval(1, 3, True, True)
+    assert Union(Interval(1, 2, True, True), Interval(1, 3, True)) == \
+        Interval(1, 3, True)
+    assert Union(Interval(1, 3), Interval(2, 3)) == Interval(1, 3)
+    assert Union(Interval(1, 3, False, True), Interval(2, 3)) == \
+        Interval(1, 3)
+    assert Union(Interval(1, 2, False, True), Interval(2, 3, True)) != \
+        Interval(1, 3)
+    assert Union(Interval(1, 2), S.EmptySet) == Interval(1, 2)
+    assert Union(S.EmptySet) == S.EmptySet
+
+    assert Union(Interval(0, 1), *[FiniteSet(1.0/n) for n in range(1, 10)]) == \
+        Interval(0, 1)
+    # issue #18241:
+    x = Symbol('x')
+    assert Union(Interval(0, 1), FiniteSet(1, x)) == Union(
+        Interval(0, 1), FiniteSet(x))
+    assert unchanged(Union, Interval(0, 1), FiniteSet(2, x))
+
+    assert Interval(1, 2).union(Interval(2, 3)) == \
+        Interval(1, 2) + Interval(2, 3)
+
+    assert Interval(1, 2).union(Interval(2, 3)) == Interval(1, 3)
+
+    assert Union(Set()) == Set()
+
+    assert FiniteSet(1) + FiniteSet(2) + FiniteSet(3) == FiniteSet(1, 2, 3)
+    assert FiniteSet('ham') + FiniteSet('eggs') == FiniteSet('ham', 'eggs')
+    assert FiniteSet(1, 2, 3) + S.EmptySet == FiniteSet(1, 2, 3)
+
+    assert FiniteSet(1, 2, 3) & FiniteSet(2, 3, 4) == FiniteSet(2, 3)
+    assert FiniteSet(1, 2, 3) | FiniteSet(2, 3, 4) == FiniteSet(1, 2, 3, 4)
+
+    assert FiniteSet(1, 2, 3) & S.EmptySet == S.EmptySet
+    assert FiniteSet(1, 2, 3) | S.EmptySet == FiniteSet(1, 2, 3)
+
+    x = Symbol("x")
+    y = Symbol("y")
+    z = Symbol("z")
+    assert S.EmptySet | FiniteSet(x, FiniteSet(y, z)) == \
+        FiniteSet(x, FiniteSet(y, z))
+
+    # Test that Intervals and FiniteSets play nicely
+    assert Interval(1, 3) + FiniteSet(2) == Interval(1, 3)
+    assert Interval(1, 3, True, True) + FiniteSet(3) == \
+        Interval(1, 3, True, False)
+    X = Interval(1, 3) + FiniteSet(5)
+    Y = Interval(1, 2) + FiniteSet(3)
+    XandY = X.intersect(Y)
+    assert 2 in X and 3 in X and 3 in XandY
+    assert XandY.is_subset(X) and XandY.is_subset(Y)
+
+    raises(TypeError, lambda: Union(1, 2, 3))
+
+    assert X.is_iterable is False
+
+    # issue 7843
+    assert Union(S.EmptySet, FiniteSet(-sqrt(-I), sqrt(-I))) == \
+        FiniteSet(-sqrt(-I), sqrt(-I))
+
+    assert Union(S.Reals, S.Integers) == S.Reals
+
+
+def test_union_iter():
+    # Use Range because it is ordered
+    u = Union(Range(3), Range(5), Range(4), evaluate=False)
+
+    # Round robin
+    assert list(u) == [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 4]
+
+
+def test_union_is_empty():
+    assert (Interval(x, y) + FiniteSet(1)).is_empty == False
+    assert (Interval(x, y) + Interval(-x, y)).is_empty == None
+
+
+def test_difference():
+    assert Interval(1, 3) - Interval(1, 2) == Interval(2, 3, True)
+    assert Interval(1, 3) - Interval(2, 3) == Interval(1, 2, False, True)
+    assert Interval(1, 3, True) - Interval(2, 3) == Interval(1, 2, True, True)
+    assert Interval(1, 3, True) - Interval(2, 3, True) == \
+        Interval(1, 2, True, False)
+    assert Interval(0, 2) - FiniteSet(1) == \
+        Union(Interval(0, 1, False, True), Interval(1, 2, True, False))
+
+    # issue #18119
+    assert S.Reals - FiniteSet(I) == S.Reals
+    assert S.Reals - FiniteSet(-I, I) == S.Reals
+    assert Interval(0, 10) - FiniteSet(-I, I) == Interval(0, 10)
+    assert Interval(0, 10) - FiniteSet(1, I) == Union(
+        Interval.Ropen(0, 1), Interval.Lopen(1, 10))
+    assert S.Reals - FiniteSet(1, 2 + I, x, y**2) == Complement(
+        Union(Interval.open(-oo, 1), Interval.open(1, oo)), FiniteSet(x, y**2),
+        evaluate=False)
+
+    assert FiniteSet(1, 2, 3) - FiniteSet(2) == FiniteSet(1, 3)
+    assert FiniteSet('ham', 'eggs') - FiniteSet('eggs') == FiniteSet('ham')
+    assert FiniteSet(1, 2, 3, 4) - Interval(2, 10, True, False) == \
+        FiniteSet(1, 2)
+    assert FiniteSet(1, 2, 3, 4) - S.EmptySet == FiniteSet(1, 2, 3, 4)
+    assert Union(Interval(0, 2), FiniteSet(2, 3, 4)) - Interval(1, 3) == \
+        Union(Interval(0, 1, False, True), FiniteSet(4))
+
+    assert -1 in S.Reals - S.Naturals
+
+
+def test_Complement():
+    A = FiniteSet(1, 3, 4)
+    B = FiniteSet(3, 4)
+    C = Interval(1, 3)
+    D = Interval(1, 2)
+
+    assert Complement(A, B, evaluate=False).is_iterable is True
+    assert Complement(A, C, evaluate=False).is_iterable is True
+    assert Complement(C, D, evaluate=False).is_iterable is None
+
+    assert FiniteSet(*Complement(A, B, evaluate=False)) == FiniteSet(1)
+    assert FiniteSet(*Complement(A, C, evaluate=False)) == FiniteSet(4)
+    raises(TypeError, lambda: FiniteSet(*Complement(C, A, evaluate=False)))
+
+    assert Complement(Interval(1, 3), Interval(1, 2)) == Interval(2, 3, True)
+    assert Complement(FiniteSet(1, 3, 4), FiniteSet(3, 4)) == FiniteSet(1)
+    assert Complement(Union(Interval(0, 2), FiniteSet(2, 3, 4)),
+                      Interval(1, 3)) == \
+        Union(Interval(0, 1, False, True), FiniteSet(4))
+
+    assert 3 not in Complement(Interval(0, 5), Interval(1, 4), evaluate=False)
+    assert -1 in Complement(S.Reals, S.Naturals, evaluate=False)
+    assert 1 not in Complement(S.Reals, S.Naturals, evaluate=False)
+
+    assert Complement(S.Integers, S.UniversalSet) == EmptySet
+    assert S.UniversalSet.complement(S.Integers) == EmptySet
+
+    assert (0 not in S.Reals.intersect(S.Integers - FiniteSet(0)))
+
+    assert S.EmptySet - S.Integers == S.EmptySet
+
+    assert (S.Integers - FiniteSet(0)) - FiniteSet(1) == S.Integers - FiniteSet(0, 1)
+
+    assert S.Reals - Union(S.Naturals, FiniteSet(pi)) == \
+            Intersection(S.Reals - S.Naturals, S.Reals - FiniteSet(pi))
+    # issue 12712
+    assert Complement(FiniteSet(x, y, 2), Interval(-10, 10)) == \
+            Complement(FiniteSet(x, y), Interval(-10, 10))
+
+    A = FiniteSet(*symbols('a:c'))
+    B = FiniteSet(*symbols('d:f'))
+    assert unchanged(Complement, ProductSet(A, A), B)
+
+    A2 = ProductSet(A, A)
+    B3 = ProductSet(B, B, B)
+    assert A2 - B3 == A2
+    assert B3 - A2 == B3
+
+
+def test_set_operations_nonsets():
+    '''Tests that e.g. FiniteSet(1) * 2 raises TypeError'''
+    ops = [
+        lambda a, b: a + b,
+        lambda a, b: a - b,
+        lambda a, b: a * b,
+        lambda a, b: a / b,
+        lambda a, b: a // b,
+        lambda a, b: a | b,
+        lambda a, b: a & b,
+        lambda a, b: a ^ b,
+        # FiniteSet(1) ** 2 gives a ProductSet
+        #lambda a, b: a ** b,
+    ]
+    Sx = FiniteSet(x)
+    Sy = FiniteSet(y)
+    sets = [
+        {1},
+        FiniteSet(1),
+        Interval(1, 2),
+        Union(Sx, Interval(1, 2)),
+        Intersection(Sx, Sy),
+        Complement(Sx, Sy),
+        ProductSet(Sx, Sy),
+        S.EmptySet,
+    ]
+    nums = [0, 1, 2, S(0), S(1), S(2)]
+
+    for si in sets:
+        for ni in nums:
+            for op in ops:
+                raises(TypeError, lambda : op(si, ni))
+                raises(TypeError, lambda : op(ni, si))
+        raises(TypeError, lambda: si ** object())
+        raises(TypeError, lambda: si ** {1})
+
+
+def test_complement():
+    assert Complement({1, 2}, {1}) == {2}
+    assert Interval(0, 1).complement(S.Reals) == \
+        Union(Interval(-oo, 0, True, True), Interval(1, oo, True, True))
+    assert Interval(0, 1, True, False).complement(S.Reals) == \
+        Union(Interval(-oo, 0, True, False), Interval(1, oo, True, True))
+    assert Interval(0, 1, False, True).complement(S.Reals) == \
+        Union(Interval(-oo, 0, True, True), Interval(1, oo, False, True))
+    assert Interval(0, 1, True, True).complement(S.Reals) == \
+        Union(Interval(-oo, 0, True, False), Interval(1, oo, False, True))
+
+    assert S.UniversalSet.complement(S.EmptySet) == S.EmptySet
+    assert S.UniversalSet.complement(S.Reals) == S.EmptySet
+    assert S.UniversalSet.complement(S.UniversalSet) == S.EmptySet
+
+    assert S.EmptySet.complement(S.Reals) == S.Reals
+
+    assert Union(Interval(0, 1), Interval(2, 3)).complement(S.Reals) == \
+        Union(Interval(-oo, 0, True, True), Interval(1, 2, True, True),
+              Interval(3, oo, True, True))
+
+    assert FiniteSet(0).complement(S.Reals) ==  \
+        Union(Interval(-oo, 0, True, True), Interval(0, oo, True, True))
+
+    assert (FiniteSet(5) + Interval(S.NegativeInfinity,
+                                    0)).complement(S.Reals) == \
+        Interval(0, 5, True, True) + Interval(5, S.Infinity, True, True)
+
+    assert FiniteSet(1, 2, 3).complement(S.Reals) == \
+        Interval(S.NegativeInfinity, 1, True, True) + \
+        Interval(1, 2, True, True) + Interval(2, 3, True, True) +\
+        Interval(3, S.Infinity, True, True)
+
+    assert FiniteSet(x).complement(S.Reals) == Complement(S.Reals, FiniteSet(x))
+
+    assert FiniteSet(0, x).complement(S.Reals) == Complement(Interval(-oo, 0, True, True) +
+                                                             Interval(0, oo, True, True)
+                                                             , FiniteSet(x), evaluate=False)
+
+    square = Interval(0, 1) * Interval(0, 1)
+    notsquare = square.complement(S.Reals*S.Reals)
+
+    assert all(pt in square for pt in [(0, 0), (.5, .5), (1, 0), (1, 1)])
+    assert not any(
+        pt in notsquare for pt in [(0, 0), (.5, .5), (1, 0), (1, 1)])
+    assert not any(pt in square for pt in [(-1, 0), (1.5, .5), (10, 10)])
+    assert all(pt in notsquare for pt in [(-1, 0), (1.5, .5), (10, 10)])
+
+
+def test_intersect1():
+    assert all(S.Integers.intersection(i) is i for i in
+        (S.Naturals, S.Naturals0))
+    assert all(i.intersection(S.Integers) is i for i in
+        (S.Naturals, S.Naturals0))
+    s =  S.Naturals0
+    assert S.Naturals.intersection(s) is S.Naturals
+    assert s.intersection(S.Naturals) is S.Naturals
+    x = Symbol('x')
+    assert Interval(0, 2).intersect(Interval(1, 2)) == Interval(1, 2)
+    assert Interval(0, 2).intersect(Interval(1, 2, True)) == \
+        Interval(1, 2, True)
+    assert Interval(0, 2, True).intersect(Interval(1, 2)) == \
+        Interval(1, 2, False, False)
+    assert Interval(0, 2, True, True).intersect(Interval(1, 2)) == \
+        Interval(1, 2, False, True)
+    assert Interval(0, 2).intersect(Union(Interval(0, 1), Interval(2, 3))) == \
+        Union(Interval(0, 1), Interval(2, 2))
+
+    assert FiniteSet(1, 2).intersect(FiniteSet(1, 2, 3)) == FiniteSet(1, 2)
+    assert FiniteSet(1, 2, x).intersect(FiniteSet(x)) == FiniteSet(x)
+    assert FiniteSet('ham', 'eggs').intersect(FiniteSet('ham')) == \
+        FiniteSet('ham')
+    assert FiniteSet(1, 2, 3, 4, 5).intersect(S.EmptySet) == S.EmptySet
+
+    assert Interval(0, 5).intersect(FiniteSet(1, 3)) == FiniteSet(1, 3)
+    assert Interval(0, 1, True, True).intersect(FiniteSet(1)) == S.EmptySet
+
+    assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(1, 2)) == \
+        Union(Interval(1, 1), Interval(2, 2))
+    assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(0, 2)) == \
+        Union(Interval(0, 1), Interval(2, 2))
+    assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(1, 2, True, True)) == \
+        S.EmptySet
+    assert Union(Interval(0, 1), Interval(2, 3)).intersect(S.EmptySet) == \
+        S.EmptySet
+    assert Union(Interval(0, 5), FiniteSet('ham')).intersect(FiniteSet(2, 3, 4, 5, 6)) == \
+        Intersection(FiniteSet(2, 3, 4, 5, 6), Union(FiniteSet('ham'), Interval(0, 5)))
+    assert Intersection(FiniteSet(1, 2, 3), Interval(2, x), Interval(3, y)) == \
+        Intersection(FiniteSet(3), Interval(2, x), Interval(3, y), evaluate=False)
+    assert Intersection(FiniteSet(1, 2), Interval(0, 3), Interval(x, y)) == \
+        Intersection({1, 2}, Interval(x, y), evaluate=False)
+    assert Intersection(FiniteSet(1, 2, 4), Interval(0, 3), Interval(x, y)) == \
+        Intersection({1, 2}, Interval(x, y), evaluate=False)
+    # XXX: Is the real=True necessary here?
+    # https://github.com/sympy/sympy/issues/17532
+    m, n = symbols('m, n', real=True)
+    assert Intersection(FiniteSet(m), FiniteSet(m, n), Interval(m, m+1)) == \
+        FiniteSet(m)
+
+    # issue 8217
+    assert Intersection(FiniteSet(x), FiniteSet(y)) == \
+        Intersection(FiniteSet(x), FiniteSet(y), evaluate=False)
+    assert FiniteSet(x).intersect(S.Reals) == \
+        Intersection(S.Reals, FiniteSet(x), evaluate=False)
+
+    # tests for the intersection alias
+    assert Interval(0, 5).intersection(FiniteSet(1, 3)) == FiniteSet(1, 3)
+    assert Interval(0, 1, True, True).intersection(FiniteSet(1)) == S.EmptySet
+
+    assert Union(Interval(0, 1), Interval(2, 3)).intersection(Interval(1, 2)) == \
+        Union(Interval(1, 1), Interval(2, 2))
+
+    # canonical boundary selected
+    a = sqrt(2*sqrt(6) + 5)
+    b = sqrt(2) + sqrt(3)
+    assert Interval(a, 4).intersection(Interval(b, 5)) == Interval(b, 4)
+    assert Interval(1, a).intersection(Interval(0, b)) == Interval(1, b)
+
+
+def test_intersection_interval_float():
+    # intersection of Intervals with mixed Rational/Float boundaries should
+    # lead to Float boundaries in all cases regardless of which Interval is
+    # open or closed.
+    typs = [
+        (Interval, Interval, Interval),
+        (Interval, Interval.open, Interval.open),
+        (Interval, Interval.Lopen, Interval.Lopen),
+        (Interval, Interval.Ropen, Interval.Ropen),
+        (Interval.open, Interval.open, Interval.open),
+        (Interval.open, Interval.Lopen, Interval.open),
+        (Interval.open, Interval.Ropen, Interval.open),
+        (Interval.Lopen, Interval.Lopen, Interval.Lopen),
+        (Interval.Lopen, Interval.Ropen, Interval.open),
+        (Interval.Ropen, Interval.Ropen, Interval.Ropen),
+    ]
+
+    as_float = lambda a1, a2: a2 if isinstance(a2, float) else a1
+
+    for t1, t2, t3 in typs:
+        for t1i, t2i in [(t1, t2), (t2, t1)]:
+            for a1, a2, b1, b2 in cartes([2, 2.0], [2, 2.0], [3, 3.0], [3, 3.0]):
+                I1 = t1(a1, b1)
+                I2 = t2(a2, b2)
+                I3 = t3(as_float(a1, a2), as_float(b1, b2))
+                assert I1.intersect(I2) == I3
+
+
+def test_intersection():
+    # iterable
+    i = Intersection(FiniteSet(1, 2, 3), Interval(2, 5), evaluate=False)
+    assert i.is_iterable
+    assert set(i) == {S(2), S(3)}
+
+    # challenging intervals
+    x = Symbol('x', real=True)
+    i = Intersection(Interval(0, 3), Interval(x, 6))
+    assert (5 in i) is False
+    raises(TypeError, lambda: 2 in i)
+
+    # Singleton special cases
+    assert Intersection(Interval(0, 1), S.EmptySet) == S.EmptySet
+    assert Intersection(Interval(-oo, oo), Interval(-oo, x)) == Interval(-oo, x)
+
+    # Products
+    line = Interval(0, 5)
+    i = Intersection(line**2, line**3, evaluate=False)
+    assert (2, 2) not in i
+    assert (2, 2, 2) not in i
+    raises(TypeError, lambda: list(i))
+
+    a = Intersection(Intersection(S.Integers, S.Naturals, evaluate=False), S.Reals, evaluate=False)
+    assert a._argset == frozenset([Intersection(S.Naturals, S.Integers, evaluate=False), S.Reals])
+
+    assert Intersection(S.Complexes, FiniteSet(S.ComplexInfinity)) == S.EmptySet
+
+    # issue 12178
+    assert Intersection() == S.UniversalSet
+
+    # issue 16987
+    assert Intersection({1}, {1}, {x}) == Intersection({1}, {x})
+
+
+def test_issue_9623():
+    n = Symbol('n')
+
+    a = S.Reals
+    b = Interval(0, oo)
+    c = FiniteSet(n)
+
+    assert Intersection(a, b, c) == Intersection(b, c)
+    assert Intersection(Interval(1, 2), Interval(3, 4), FiniteSet(n)) == EmptySet
+
+
+def test_is_disjoint():
+    assert Interval(0, 2).is_disjoint(Interval(1, 2)) == False
+    assert Interval(0, 2).is_disjoint(Interval(3, 4)) == True
+
+
+def test_ProductSet__len__():
+    A = FiniteSet(1, 2)
+    B = FiniteSet(1, 2, 3)
+    assert ProductSet(A).__len__() == 2
+    assert ProductSet(A).__len__() is not S(2)
+    assert ProductSet(A, B).__len__() == 6
+    assert ProductSet(A, B).__len__() is not S(6)
+
+
+def test_ProductSet():
+    # ProductSet is always a set of Tuples
+    assert ProductSet(S.Reals) == S.Reals ** 1
+    assert ProductSet(S.Reals, S.Reals) == S.Reals ** 2
+    assert ProductSet(S.Reals, S.Reals, S.Reals) == S.Reals ** 3
+
+    assert ProductSet(S.Reals) != S.Reals
+    assert ProductSet(S.Reals, S.Reals) == S.Reals * S.Reals
+    assert ProductSet(S.Reals, S.Reals, S.Reals) != S.Reals * S.Reals * S.Reals
+    assert ProductSet(S.Reals, S.Reals, S.Reals) == (S.Reals * S.Reals * S.Reals).flatten()
+
+    assert 1 not in ProductSet(S.Reals)
+    assert (1,) in ProductSet(S.Reals)
+
+    assert 1 not in ProductSet(S.Reals, S.Reals)
+    assert (1, 2) in ProductSet(S.Reals, S.Reals)
+    assert (1, I) not in ProductSet(S.Reals, S.Reals)
+
+    assert (1, 2, 3) in ProductSet(S.Reals, S.Reals, S.Reals)
+    assert (1, 2, 3) in S.Reals ** 3
+    assert (1, 2, 3) not in S.Reals * S.Reals * S.Reals
+    assert ((1, 2), 3) in S.Reals * S.Reals * S.Reals
+    assert (1, (2, 3)) not in S.Reals * S.Reals * S.Reals
+    assert (1, (2, 3)) in S.Reals * (S.Reals * S.Reals)
+
+    assert ProductSet() == FiniteSet(())
+    assert ProductSet(S.Reals, S.EmptySet) == S.EmptySet
+
+    # See GH-17458
+
+    for ni in range(5):
+        Rn = ProductSet(*(S.Reals,) * ni)
+        assert (1,) * ni in Rn
+        assert 1 not in Rn
+
+    assert (S.Reals * S.Reals) * S.Reals != S.Reals * (S.Reals * S.Reals)
+
+    S1 = S.Reals
+    S2 = S.Integers
+    x1 = pi
+    x2 = 3
+    assert x1 in S1
+    assert x2 in S2
+    assert (x1, x2) in S1 * S2
+    S3 = S1 * S2
+    x3 = (x1, x2)
+    assert x3 in S3
+    assert (x3, x3) in S3 * S3
+    assert x3 + x3 not in S3 * S3
+
+    raises(ValueError, lambda: S.Reals**-1)
+    with warns_deprecated_sympy():
+        ProductSet(FiniteSet(s) for s in range(2))
+    raises(TypeError, lambda: ProductSet(None))
+
+    S1 = FiniteSet(1, 2)
+    S2 = FiniteSet(3, 4)
+    S3 = ProductSet(S1, S2)
+    assert (S3.as_relational(x, y)
+            == And(S1.as_relational(x), S2.as_relational(y))
+            == And(Or(Eq(x, 1), Eq(x, 2)), Or(Eq(y, 3), Eq(y, 4))))
+    raises(ValueError, lambda: S3.as_relational(x))
+    raises(ValueError, lambda: S3.as_relational(x, 1))
+    raises(ValueError, lambda: ProductSet(Interval(0, 1)).as_relational(x, y))
+
+    Z2 = ProductSet(S.Integers, S.Integers)
+    assert Z2.contains((1, 2)) is S.true
+    assert Z2.contains((1,)) is S.false
+    assert Z2.contains(x) == Contains(x, Z2, evaluate=False)
+    assert Z2.contains(x).subs(x, 1) is S.false
+    assert Z2.contains((x, 1)).subs(x, 2) is S.true
+    assert Z2.contains((x, y)) == Contains(x, S.Integers) & Contains(y, S.Integers)
+    assert unchanged(Contains, (x, y), Z2)
+    assert Contains((1, 2), Z2) is S.true
+
+
+def test_ProductSet_of_single_arg_is_not_arg():
+    assert unchanged(ProductSet, Interval(0, 1))
+    assert unchanged(ProductSet, ProductSet(Interval(0, 1)))
+
+
+def test_ProductSet_is_empty():
+    assert ProductSet(S.Integers, S.Reals).is_empty == False
+    assert ProductSet(Interval(x, 1), S.Reals).is_empty == None
+
+
+def test_interval_subs():
+    a = Symbol('a', real=True)
+
+    assert Interval(0, a).subs(a, 2) == Interval(0, 2)
+    assert Interval(a, 0).subs(a, 2) == S.EmptySet
+
+
+def test_interval_to_mpi():
+    assert Interval(0, 1).to_mpi() == mpi(0, 1)
+    assert Interval(0, 1, True, False).to_mpi() == mpi(0, 1)
+    assert type(Interval(0, 1).to_mpi()) == type(mpi(0, 1))
+
+
+def test_set_evalf():
+    assert Interval(S(11)/64, S.Half).evalf() == Interval(
+        Float('0.171875'), Float('0.5'))
+    assert Interval(x, S.Half, right_open=True).evalf() == Interval(
+        x, Float('0.5'), right_open=True)
+    assert Interval(-oo, S.Half).evalf() == Interval(-oo, Float('0.5'))
+    assert FiniteSet(2, x).evalf() == FiniteSet(Float('2.0'), x)
+
+
+def test_measure():
+    a = Symbol('a', real=True)
+
+    assert Interval(1, 3).measure == 2
+    assert Interval(0, a).measure == a
+    assert Interval(1, a).measure == a - 1
+
+    assert Union(Interval(1, 2), Interval(3, 4)).measure == 2
+    assert Union(Interval(1, 2), Interval(3, 4), FiniteSet(5, 6, 7)).measure \
+        == 2
+
+    assert FiniteSet(1, 2, oo, a, -oo, -5).measure == 0
+
+    assert S.EmptySet.measure == 0
+
+    square = Interval(0, 10) * Interval(0, 10)
+    offsetsquare = Interval(5, 15) * Interval(5, 15)
+    band = Interval(-oo, oo) * Interval(2, 4)
+
+    assert square.measure == offsetsquare.measure == 100
+    assert (square + offsetsquare).measure == 175  # there is some overlap
+    assert (square - offsetsquare).measure == 75
+    assert (square * FiniteSet(1, 2, 3)).measure == 0
+    assert (square.intersect(band)).measure == 20
+    assert (square + band).measure is oo
+    assert (band * FiniteSet(1, 2, 3)).measure is nan
+
+
+def test_is_subset():
+    assert Interval(0, 1).is_subset(Interval(0, 2)) is True
+    assert Interval(0, 3).is_subset(Interval(0, 2)) is False
+    assert Interval(0, 1).is_subset(FiniteSet(0, 1)) is False
+
+    assert FiniteSet(1, 2).is_subset(FiniteSet(1, 2, 3, 4))
+    assert FiniteSet(4, 5).is_subset(FiniteSet(1, 2, 3, 4)) is False
+    assert FiniteSet(1).is_subset(Interval(0, 2))
+    assert FiniteSet(1, 2).is_subset(Interval(0, 2, True, True)) is False
+    assert (Interval(1, 2) + FiniteSet(3)).is_subset(
+        Interval(0, 2, False, True) + FiniteSet(2, 3))
+
+    assert Interval(3, 4).is_subset(Union(Interval(0, 1), Interval(2, 5))) is True
+    assert Interval(3, 6).is_subset(Union(Interval(0, 1), Interval(2, 5))) is False
+
+    assert FiniteSet(1, 2, 3, 4).is_subset(Interval(0, 5)) is True
+    assert S.EmptySet.is_subset(FiniteSet(1, 2, 3)) is True
+
+    assert Interval(0, 1).is_subset(S.EmptySet) is False
+    assert S.EmptySet.is_subset(S.EmptySet) is True
+
+    raises(ValueError, lambda: S.EmptySet.is_subset(1))
+
+    # tests for the issubset alias
+    assert FiniteSet(1, 2, 3, 4).issubset(Interval(0, 5)) is True
+    assert S.EmptySet.issubset(FiniteSet(1, 2, 3)) is True
+
+    assert S.Naturals.is_subset(S.Integers)
+    assert S.Naturals0.is_subset(S.Integers)
+
+    assert FiniteSet(x).is_subset(FiniteSet(y)) is None
+    assert FiniteSet(x).is_subset(FiniteSet(y).subs(y, x)) is True
+    assert FiniteSet(x).is_subset(FiniteSet(y).subs(y, x+1)) is False
+
+    assert Interval(0, 1).is_subset(Interval(0, 1, left_open=True)) is False
+    assert Interval(-2, 3).is_subset(Union(Interval(-oo, -2), Interval(3, oo))) is False
+
+    n = Symbol('n', integer=True)
+    assert Range(-3, 4, 1).is_subset(FiniteSet(-10, 10)) is False
+    assert Range(S(10)**100).is_subset(FiniteSet(0, 1, 2)) is False
+    assert Range(6, 0, -2).is_subset(FiniteSet(2, 4, 6)) is True
+    assert Range(1, oo).is_subset(FiniteSet(1, 2)) is False
+    assert Range(-oo, 1).is_subset(FiniteSet(1)) is False
+    assert Range(3).is_subset(FiniteSet(0, 1, n)) is None
+    assert Range(n, n + 2).is_subset(FiniteSet(n, n + 1)) is True
+    assert Range(5).is_subset(Interval(0, 4, right_open=True)) is False
+    #issue 19513
+    assert imageset(Lambda(n, 1/n), S.Integers).is_subset(S.Reals) is None
+
+def test_is_proper_subset():
+    assert Interval(0, 1).is_proper_subset(Interval(0, 2)) is True
+    assert Interval(0, 3).is_proper_subset(Interval(0, 2)) is False
+    assert S.EmptySet.is_proper_subset(FiniteSet(1, 2, 3)) is True
+
+    raises(ValueError, lambda: Interval(0, 1).is_proper_subset(0))
+
+
+def test_is_superset():
+    assert Interval(0, 1).is_superset(Interval(0, 2)) == False
+    assert Interval(0, 3).is_superset(Interval(0, 2))
+
+    assert FiniteSet(1, 2).is_superset(FiniteSet(1, 2, 3, 4)) == False
+    assert FiniteSet(4, 5).is_superset(FiniteSet(1, 2, 3, 4)) == False
+    assert FiniteSet(1).is_superset(Interval(0, 2)) == False
+    assert FiniteSet(1, 2).is_superset(Interval(0, 2, True, True)) == False
+    assert (Interval(1, 2) + FiniteSet(3)).is_superset(
+        Interval(0, 2, False, True) + FiniteSet(2, 3)) == False
+
+    assert Interval(3, 4).is_superset(Union(Interval(0, 1), Interval(2, 5))) == False
+
+    assert FiniteSet(1, 2, 3, 4).is_superset(Interval(0, 5)) == False
+    assert S.EmptySet.is_superset(FiniteSet(1, 2, 3)) == False
+
+    assert Interval(0, 1).is_superset(S.EmptySet) == True
+    assert S.EmptySet.is_superset(S.EmptySet) == True
+
+    raises(ValueError, lambda: S.EmptySet.is_superset(1))
+
+    # tests for the issuperset alias
+    assert Interval(0, 1).issuperset(S.EmptySet) == True
+    assert S.EmptySet.issuperset(S.EmptySet) == True
+
+
+def test_is_proper_superset():
+    assert Interval(0, 1).is_proper_superset(Interval(0, 2)) is False
+    assert Interval(0, 3).is_proper_superset(Interval(0, 2)) is True
+    assert FiniteSet(1, 2, 3).is_proper_superset(S.EmptySet) is True
+
+    raises(ValueError, lambda: Interval(0, 1).is_proper_superset(0))
+
+
+def test_contains():
+    assert Interval(0, 2).contains(1) is S.true
+    assert Interval(0, 2).contains(3) is S.false
+    assert Interval(0, 2, True, False).contains(0) is S.false
+    assert Interval(0, 2, True, False).contains(2) is S.true
+    assert Interval(0, 2, False, True).contains(0) is S.true
+    assert Interval(0, 2, False, True).contains(2) is S.false
+    assert Interval(0, 2, True, True).contains(0) is S.false
+    assert Interval(0, 2, True, True).contains(2) is S.false
+
+    assert (Interval(0, 2) in Interval(0, 2)) is False
+
+    assert FiniteSet(1, 2, 3).contains(2) is S.true
+    assert FiniteSet(1, 2, Symbol('x')).contains(Symbol('x')) is S.true
+
+    assert FiniteSet(y)._contains(x) == Eq(y, x, evaluate=False)
+    raises(TypeError, lambda: x in FiniteSet(y))
+    assert FiniteSet({x, y})._contains({x}) == Eq({x, y}, {x}, evaluate=False)
+    assert FiniteSet({x, y}).subs(y, x)._contains({x}) is S.true
+    assert FiniteSet({x, y}).subs(y, x+1)._contains({x}) is S.false
+
+    # issue 8197
+    from sympy.abc import a, b
+    assert FiniteSet(b).contains(-a) == Eq(b, -a)
+    assert FiniteSet(b).contains(a) == Eq(b, a)
+    assert FiniteSet(a).contains(1) == Eq(a, 1)
+    raises(TypeError, lambda: 1 in FiniteSet(a))
+
+    # issue 8209
+    rad1 = Pow(Pow(2, Rational(1, 3)) - 1, Rational(1, 3))
+    rad2 = Pow(Rational(1, 9), Rational(1, 3)) - Pow(Rational(2, 9), Rational(1, 3)) + Pow(Rational(4, 9), Rational(1, 3))
+    s1 = FiniteSet(rad1)
+    s2 = FiniteSet(rad2)
+    assert s1 - s2 == S.EmptySet
+
+    items = [1, 2, S.Infinity, S('ham'), -1.1]
+    fset = FiniteSet(*items)
+    assert all(item in fset for item in items)
+    assert all(fset.contains(item) is S.true for item in items)
+
+    assert Union(Interval(0, 1), Interval(2, 5)).contains(3) is S.true
+    assert Union(Interval(0, 1), Interval(2, 5)).contains(6) is S.false
+    assert Union(Interval(0, 1), FiniteSet(2, 5)).contains(3) is S.false
+
+    assert S.EmptySet.contains(1) is S.false
+    assert FiniteSet(rootof(x**3 + x - 1, 0)).contains(S.Infinity) is S.false
+
+    assert rootof(x**5 + x**3 + 1, 0) in S.Reals
+    assert not rootof(x**5 + x**3 + 1, 1) in S.Reals
+
+    # non-bool results
+    assert Union(Interval(1, 2), Interval(3, 4)).contains(x) == \
+        Or(And(S.One <= x, x <= 2), And(S(3) <= x, x <= 4))
+    assert Intersection(Interval(1, x), Interval(2, 3)).contains(y) == \
+        And(y <= 3, y <= x, S.One <= y, S(2) <= y)
+
+    assert (S.Complexes).contains(S.ComplexInfinity) == S.false
+
+
+def test_interval_symbolic():
+    x = Symbol('x')
+    e = Interval(0, 1)
+    assert e.contains(x) == And(S.Zero <= x, x <= 1)
+    raises(TypeError, lambda: x in e)
+    e = Interval(0, 1, True, True)
+    assert e.contains(x) == And(S.Zero < x, x < 1)
+    c = Symbol('c', real=False)
+    assert Interval(x, x + 1).contains(c) == False
+    e = Symbol('e', extended_real=True)
+    assert Interval(-oo, oo).contains(e) == And(
+        S.NegativeInfinity < e, e < S.Infinity)
+
+
+def test_union_contains():
+    x = Symbol('x')
+    i1 = Interval(0, 1)
+    i2 = Interval(2, 3)
+    i3 = Union(i1, i2)
+    assert i3.as_relational(x) == Or(And(S.Zero <= x, x <= 1), And(S(2) <= x, x <= 3))
+    raises(TypeError, lambda: x in i3)
+    e = i3.contains(x)
+    assert e == i3.as_relational(x)
+    assert e.subs(x, -0.5) is false
+    assert e.subs(x, 0.5) is true
+    assert e.subs(x, 1.5) is false
+    assert e.subs(x, 2.5) is true
+    assert e.subs(x, 3.5) is false
+
+    U = Interval(0, 2, True, True) + Interval(10, oo) + FiniteSet(-1, 2, 5, 6)
+    assert all(el not in U for el in [0, 4, -oo])
+    assert all(el in U for el in [2, 5, 10])
+
+
+def test_is_number():
+    assert Interval(0, 1).is_number is False
+    assert Set().is_number is False
+
+
+def test_Interval_is_left_unbounded():
+    assert Interval(3, 4).is_left_unbounded is False
+    assert Interval(-oo, 3).is_left_unbounded is True
+    assert Interval(Float("-inf"), 3).is_left_unbounded is True
+
+
+def test_Interval_is_right_unbounded():
+    assert Interval(3, 4).is_right_unbounded is False
+    assert Interval(3, oo).is_right_unbounded is True
+    assert Interval(3, Float("+inf")).is_right_unbounded is True
+
+
+def test_Interval_as_relational():
+    x = Symbol('x')
+
+    assert Interval(-1, 2, False, False).as_relational(x) == \
+        And(Le(-1, x), Le(x, 2))
+    assert Interval(-1, 2, True, False).as_relational(x) == \
+        And(Lt(-1, x), Le(x, 2))
+    assert Interval(-1, 2, False, True).as_relational(x) == \
+        And(Le(-1, x), Lt(x, 2))
+    assert Interval(-1, 2, True, True).as_relational(x) == \
+        And(Lt(-1, x), Lt(x, 2))
+
+    assert Interval(-oo, 2, right_open=False).as_relational(x) == And(Lt(-oo, x), Le(x, 2))
+    assert Interval(-oo, 2, right_open=True).as_relational(x) == And(Lt(-oo, x), Lt(x, 2))
+
+    assert Interval(-2, oo, left_open=False).as_relational(x) == And(Le(-2, x), Lt(x, oo))
+    assert Interval(-2, oo, left_open=True).as_relational(x) == And(Lt(-2, x), Lt(x, oo))
+
+    assert Interval(-oo, oo).as_relational(x) == And(Lt(-oo, x), Lt(x, oo))
+    x = Symbol('x', real=True)
+    y = Symbol('y', real=True)
+    assert Interval(x, y).as_relational(x) == (x <= y)
+    assert Interval(y, x).as_relational(x) == (y <= x)
+
+
+def test_Finite_as_relational():
+    x = Symbol('x')
+    y = Symbol('y')
+
+    assert FiniteSet(1, 2).as_relational(x) == Or(Eq(x, 1), Eq(x, 2))
+    assert FiniteSet(y, -5).as_relational(x) == Or(Eq(x, y), Eq(x, -5))
+
+
+def test_Union_as_relational():
+    x = Symbol('x')
+    assert (Interval(0, 1) + FiniteSet(2)).as_relational(x) == \
+        Or(And(Le(0, x), Le(x, 1)), Eq(x, 2))
+    assert (Interval(0, 1, True, True) + FiniteSet(1)).as_relational(x) == \
+        And(Lt(0, x), Le(x, 1))
+    assert Or(x < 0, x > 0).as_set().as_relational(x) == \
+        And((x > -oo), (x < oo), Ne(x, 0))
+    assert (Interval.Ropen(1, 3) + Interval.Lopen(3, 5)
+        ).as_relational(x) == And(Ne(x,3),(x>=1),(x<=5))
+
+
+def test_Intersection_as_relational():
+    x = Symbol('x')
+    assert (Intersection(Interval(0, 1), FiniteSet(2),
+            evaluate=False).as_relational(x)
+            == And(And(Le(0, x), Le(x, 1)), Eq(x, 2)))
+
+
+def test_Complement_as_relational():
+    x = Symbol('x')
+    expr = Complement(Interval(0, 1), FiniteSet(2), evaluate=False)
+    assert expr.as_relational(x) == \
+        And(Le(0, x), Le(x, 1), Ne(x, 2))
+
+
+@XFAIL
+def test_Complement_as_relational_fail():
+    x = Symbol('x')
+    expr = Complement(Interval(0, 1), FiniteSet(2), evaluate=False)
+    # XXX This example fails because 0 <= x changes to x >= 0
+    # during the evaluation.
+    assert expr.as_relational(x) == \
+            (0 <= x) & (x <= 1) & Ne(x, 2)
+
+
+def test_SymmetricDifference_as_relational():
+    x = Symbol('x')
+    expr = SymmetricDifference(Interval(0, 1), FiniteSet(2), evaluate=False)
+    assert expr.as_relational(x) == Xor(Eq(x, 2), Le(0, x) & Le(x, 1))
+
+
+def test_EmptySet():
+    assert S.EmptySet.as_relational(Symbol('x')) is S.false
+    assert S.EmptySet.intersect(S.UniversalSet) == S.EmptySet
+    assert S.EmptySet.boundary == S.EmptySet
+
+
+def test_finite_basic():
+    x = Symbol('x')
+    A = FiniteSet(1, 2, 3)
+    B = FiniteSet(3, 4, 5)
+    AorB = Union(A, B)
+    AandB = A.intersect(B)
+    assert A.is_subset(AorB) and B.is_subset(AorB)
+    assert AandB.is_subset(A)
+    assert AandB == FiniteSet(3)
+
+    assert A.inf == 1 and A.sup == 3
+    assert AorB.inf == 1 and AorB.sup == 5
+    assert FiniteSet(x, 1, 5).sup == Max(x, 5)
+    assert FiniteSet(x, 1, 5).inf == Min(x, 1)
+
+    # issue 7335
+    assert FiniteSet(S.EmptySet) != S.EmptySet
+    assert FiniteSet(FiniteSet(1, 2, 3)) != FiniteSet(1, 2, 3)
+    assert FiniteSet((1, 2, 3)) != FiniteSet(1, 2, 3)
+
+    # Ensure a variety of types can exist in a FiniteSet
+    assert FiniteSet((1, 2), A, -5, x, 'eggs', x**2)
+
+    assert (A > B) is False
+    assert (A >= B) is False
+    assert (A < B) is False
+    assert (A <= B) is False
+    assert AorB > A and AorB > B
+    assert AorB >= A and AorB >= B
+    assert A >= A and A <= A
+    assert A >= AandB and B >= AandB
+    assert A > AandB and B > AandB
+
+
+def test_product_basic():
+    H, T = 'H', 'T'
+    unit_line = Interval(0, 1)
+    d6 = FiniteSet(1, 2, 3, 4, 5, 6)
+    d4 = FiniteSet(1, 2, 3, 4)
+    coin = FiniteSet(H, T)
+
+    square = unit_line * unit_line
+
+    assert (0, 0) in square
+    assert 0 not in square
+    assert (H, T) in coin ** 2
+    assert (.5, .5, .5) in (square * unit_line).flatten()
+    assert ((.5, .5), .5) in square * unit_line
+    assert (H, 3, 3) in (coin * d6 * d6).flatten()
+    assert ((H, 3), 3) in coin * d6 * d6
+    HH, TT = sympify(H), sympify(T)
+    assert set(coin**2) == {(HH, HH), (HH, TT), (TT, HH), (TT, TT)}
+
+    assert (d4*d4).is_subset(d6*d6)
+
+    assert square.complement(Interval(-oo, oo)*Interval(-oo, oo)) == Union(
+        (Interval(-oo, 0, True, True) +
+         Interval(1, oo, True, True))*Interval(-oo, oo),
+         Interval(-oo, oo)*(Interval(-oo, 0, True, True) +
+                  Interval(1, oo, True, True)))
+
+    assert (Interval(-5, 5)**3).is_subset(Interval(-10, 10)**3)
+    assert not (Interval(-10, 10)**3).is_subset(Interval(-5, 5)**3)
+    assert not (Interval(-5, 5)**2).is_subset(Interval(-10, 10)**3)
+
+    assert (Interval(.2, .5)*FiniteSet(.5)).is_subset(square)  # segment in square
+
+    assert len(coin*coin*coin) == 8
+    assert len(S.EmptySet*S.EmptySet) == 0
+    assert len(S.EmptySet*coin) == 0
+    raises(TypeError, lambda: len(coin*Interval(0, 2)))
+
+
+def test_real():
+    x = Symbol('x', real=True)
+
+    I = Interval(0, 5)
+    J = Interval(10, 20)
+    A = FiniteSet(1, 2, 30, x, S.Pi)
+    B = FiniteSet(-4, 0)
+    C = FiniteSet(100)
+    D = FiniteSet('Ham', 'Eggs')
+
+    assert all(s.is_subset(S.Reals) for s in [I, J, A, B, C])
+    assert not D.is_subset(S.Reals)
+    assert all((a + b).is_subset(S.Reals) for a in [I, J, A, B, C] for b in [I, J, A, B, C])
+    assert not any((a + D).is_subset(S.Reals) for a in [I, J, A, B, C, D])
+
+    assert not (I + A + D).is_subset(S.Reals)
+
+
+def test_supinf():
+    x = Symbol('x', real=True)
+    y = Symbol('y', real=True)
+
+    assert (Interval(0, 1) + FiniteSet(2)).sup == 2
+    assert (Interval(0, 1) + FiniteSet(2)).inf == 0
+    assert (Interval(0, 1) + FiniteSet(x)).sup == Max(1, x)
+    assert (Interval(0, 1) + FiniteSet(x)).inf == Min(0, x)
+    assert FiniteSet(5, 1, x).sup == Max(5, x)
+    assert FiniteSet(5, 1, x).inf == Min(1, x)
+    assert FiniteSet(5, 1, x, y).sup == Max(5, x, y)
+    assert FiniteSet(5, 1, x, y).inf == Min(1, x, y)
+    assert FiniteSet(5, 1, x, y, S.Infinity, S.NegativeInfinity).sup == \
+        S.Infinity
+    assert FiniteSet(5, 1, x, y, S.Infinity, S.NegativeInfinity).inf == \
+        S.NegativeInfinity
+    assert FiniteSet('Ham', 'Eggs').sup == Max('Ham', 'Eggs')
+
+
+def test_universalset():
+    U = S.UniversalSet
+    x = Symbol('x')
+    assert U.as_relational(x) is S.true
+    assert U.union(Interval(2, 4)) == U
+
+    assert U.intersect(Interval(2, 4)) == Interval(2, 4)
+    assert U.measure is S.Infinity
+    assert U.boundary == S.EmptySet
+    assert U.contains(0) is S.true
+
+
+def test_Union_of_ProductSets_shares():
+    line = Interval(0, 2)
+    points = FiniteSet(0, 1, 2)
+    assert Union(line * line, line * points) == line * line
+
+
+def test_Interval_free_symbols():
+    # issue 6211
+    assert Interval(0, 1).free_symbols == set()
+    x = Symbol('x', real=True)
+    assert Interval(0, x).free_symbols == {x}
+
+
+def test_image_interval():
+    x = Symbol('x', real=True)
+    a = Symbol('a', real=True)
+    assert imageset(x, 2*x, Interval(-2, 1)) == Interval(-4, 2)
+    assert imageset(x, 2*x, Interval(-2, 1, True, False)) == \
+        Interval(-4, 2, True, False)
+    assert imageset(x, x**2, Interval(-2, 1, True, False)) == \
+        Interval(0, 4, False, True)
+    assert imageset(x, x**2, Interval(-2, 1)) == Interval(0, 4)
+    assert imageset(x, x**2, Interval(-2, 1, True, False)) == \
+        Interval(0, 4, False, True)
+    assert imageset(x, x**2, Interval(-2, 1, True, True)) == \
+        Interval(0, 4, False, True)
+    assert imageset(x, (x - 2)**2, Interval(1, 3)) == Interval(0, 1)
+    assert imageset(x, 3*x**4 - 26*x**3 + 78*x**2 - 90*x, Interval(0, 4)) == \
+        Interval(-35, 0)  # Multiple Maxima
+    assert imageset(x, x + 1/x, Interval(-oo, oo)) == Interval(-oo, -2) \
+        + Interval(2, oo)  # Single Infinite discontinuity
+    assert imageset(x, 1/x + 1/(x-1)**2, Interval(0, 2, True, False)) == \
+        Interval(Rational(3, 2), oo, False)  # Multiple Infinite discontinuities
+
+    # Test for Python lambda
+    assert imageset(lambda x: 2*x, Interval(-2, 1)) == Interval(-4, 2)
+
+    assert imageset(Lambda(x, a*x), Interval(0, 1)) == \
+            ImageSet(Lambda(x, a*x), Interval(0, 1))
+
+    assert imageset(Lambda(x, sin(cos(x))), Interval(0, 1)) == \
+            ImageSet(Lambda(x, sin(cos(x))), Interval(0, 1))
+
+
+def test_image_piecewise():
+    f = Piecewise((x, x <= -1), (1/x**2, x <= 5), (x**3, True))
+    f1 = Piecewise((0, x <= 1), (1, x <= 2), (2, True))
+    assert imageset(x, f, Interval(-5, 5)) == Union(Interval(-5, -1), Interval(Rational(1, 25), oo))
+    assert imageset(x, f1, Interval(1, 2)) == FiniteSet(0, 1)
+
+
+@XFAIL  # See: https://github.com/sympy/sympy/pull/2723#discussion_r8659826
+def test_image_Intersection():
+    x = Symbol('x', real=True)
+    y = Symbol('y', real=True)
+    assert imageset(x, x**2, Interval(-2, 0).intersect(Interval(x, y))) == \
+           Interval(0, 4).intersect(Interval(Min(x**2, y**2), Max(x**2, y**2)))
+
+
+def test_image_FiniteSet():
+    x = Symbol('x', real=True)
+    assert imageset(x, 2*x, FiniteSet(1, 2, 3)) == FiniteSet(2, 4, 6)
+
+
+def test_image_Union():
+    x = Symbol('x', real=True)
+    assert imageset(x, x**2, Interval(-2, 0) + FiniteSet(1, 2, 3)) == \
+            (Interval(0, 4) + FiniteSet(9))
+
+
+def test_image_EmptySet():
+    x = Symbol('x', real=True)
+    assert imageset(x, 2*x, S.EmptySet) == S.EmptySet
+
+
+def test_issue_5724_7680():
+    assert I not in S.Reals  # issue 7680
+    assert Interval(-oo, oo).contains(I) is S.false
+
+
+def test_boundary():
+    assert FiniteSet(1).boundary == FiniteSet(1)
+    assert all(Interval(0, 1, left_open, right_open).boundary == FiniteSet(0, 1)
+            for left_open in (true, false) for right_open in (true, false))
+
+
+def test_boundary_Union():
+    assert (Interval(0, 1) + Interval(2, 3)).boundary == FiniteSet(0, 1, 2, 3)
+    assert ((Interval(0, 1, False, True)
+           + Interval(1, 2, True, False)).boundary == FiniteSet(0, 1, 2))
+
+    assert (Interval(0, 1) + FiniteSet(2)).boundary == FiniteSet(0, 1, 2)
+    assert Union(Interval(0, 10), Interval(5, 15), evaluate=False).boundary \
+            == FiniteSet(0, 15)
+
+    assert Union(Interval(0, 10), Interval(0, 1), evaluate=False).boundary \
+            == FiniteSet(0, 10)
+    assert Union(Interval(0, 10, True, True),
+                 Interval(10, 15, True, True), evaluate=False).boundary \
+            == FiniteSet(0, 10, 15)
+
+
+@XFAIL
+def test_union_boundary_of_joining_sets():
+    """ Testing the boundary of unions is a hard problem """
+    assert Union(Interval(0, 10), Interval(10, 15), evaluate=False).boundary \
+            == FiniteSet(0, 15)
+
+
+def test_boundary_ProductSet():
+    open_square = Interval(0, 1, True, True) ** 2
+    assert open_square.boundary == (FiniteSet(0, 1) * Interval(0, 1)
+                                  + Interval(0, 1) * FiniteSet(0, 1))
+
+    second_square = Interval(1, 2, True, True) * Interval(0, 1, True, True)
+    assert (open_square + second_square).boundary == (
+                FiniteSet(0, 1) * Interval(0, 1)
+              + FiniteSet(1, 2) * Interval(0, 1)
+              + Interval(0, 1) * FiniteSet(0, 1)
+              + Interval(1, 2) * FiniteSet(0, 1))
+
+
+def test_boundary_ProductSet_line():
+    line_in_r2 = Interval(0, 1) * FiniteSet(0)
+    assert line_in_r2.boundary == line_in_r2
+
+
+def test_is_open():
+    assert Interval(0, 1, False, False).is_open is False
+    assert Interval(0, 1, True, False).is_open is False
+    assert Interval(0, 1, True, True).is_open is True
+    assert FiniteSet(1, 2, 3).is_open is False
+
+
+def test_is_closed():
+    assert Interval(0, 1, False, False).is_closed is True
+    assert Interval(0, 1, True, False).is_closed is False
+    assert FiniteSet(1, 2, 3).is_closed is True
+
+
+def test_closure():
+    assert Interval(0, 1, False, True).closure == Interval(0, 1, False, False)
+
+
+def test_interior():
+    assert Interval(0, 1, False, True).interior == Interval(0, 1, True, True)
+
+
+def test_issue_7841():
+    raises(TypeError, lambda: x in S.Reals)
+
+
+def test_Eq():
+    assert Eq(Interval(0, 1), Interval(0, 1))
+    assert Eq(Interval(0, 1), Interval(0, 2)) == False
+
+    s1 = FiniteSet(0, 1)
+    s2 = FiniteSet(1, 2)
+
+    assert Eq(s1, s1)
+    assert Eq(s1, s2) == False
+
+    assert Eq(s1*s2, s1*s2)
+    assert Eq(s1*s2, s2*s1) == False
+
+    assert unchanged(Eq, FiniteSet({x, y}), FiniteSet({x}))
+    assert Eq(FiniteSet({x, y}).subs(y, x), FiniteSet({x})) is S.true
+    assert Eq(FiniteSet({x, y}), FiniteSet({x})).subs(y, x) is S.true
+    assert Eq(FiniteSet({x, y}).subs(y, x+1), FiniteSet({x})) is S.false
+    assert Eq(FiniteSet({x, y}), FiniteSet({x})).subs(y, x+1) is S.false
+
+    assert Eq(ProductSet({1}, {2}), Interval(1, 2)) is S.false
+    assert Eq(ProductSet({1}), ProductSet({1}, {2})) is S.false
+
+    assert Eq(FiniteSet(()), FiniteSet(1)) is S.false
+    assert Eq(ProductSet(), FiniteSet(1)) is S.false
+
+    i1 = Interval(0, 1)
+    i2 = Interval(x, y)
+    assert unchanged(Eq, ProductSet(i1, i1), ProductSet(i2, i2))
+
+
+def test_SymmetricDifference():
+    A = FiniteSet(0, 1, 2, 3, 4, 5)
+    B = FiniteSet(2, 4, 6, 8, 10)
+    C = Interval(8, 10)
+
+    assert SymmetricDifference(A, B, evaluate=False).is_iterable is True
+    assert SymmetricDifference(A, C, evaluate=False).is_iterable is None
+    assert FiniteSet(*SymmetricDifference(A, B, evaluate=False)) == \
+        FiniteSet(0, 1, 3, 5, 6, 8, 10)
+    raises(TypeError,
+        lambda: FiniteSet(*SymmetricDifference(A, C, evaluate=False)))
+
+    assert SymmetricDifference(FiniteSet(0, 1, 2, 3, 4, 5), \
+            FiniteSet(2, 4, 6, 8, 10)) == FiniteSet(0, 1, 3, 5, 6, 8, 10)
+    assert SymmetricDifference(FiniteSet(2, 3, 4), FiniteSet(2, 3, 4 ,5)) \
+            == FiniteSet(5)
+    assert FiniteSet(1, 2, 3, 4, 5) ^ FiniteSet(1, 2, 5, 6) == \
+            FiniteSet(3, 4, 6)
+    assert Set(S(1), S(2), S(3)) ^ Set(S(2), S(3), S(4)) == Union(Set(S(1), S(2), S(3)) - Set(S(2), S(3), S(4)), \
+            Set(S(2), S(3), S(4)) - Set(S(1), S(2), S(3)))
+    assert Interval(0, 4) ^ Interval(2, 5) == Union(Interval(0, 4) - \
+            Interval(2, 5), Interval(2, 5) - Interval(0, 4))
+
+
+def test_issue_9536():
+    from sympy.functions.elementary.exponential import log
+    a = Symbol('a', real=True)
+    assert FiniteSet(log(a)).intersect(S.Reals) == Intersection(S.Reals, FiniteSet(log(a)))
+
+
+def test_issue_9637():
+    n = Symbol('n')
+    a = FiniteSet(n)
+    b = FiniteSet(2, n)
+    assert Complement(S.Reals, a) == Complement(S.Reals, a, evaluate=False)
+    assert Complement(Interval(1, 3), a) == Complement(Interval(1, 3), a, evaluate=False)
+    assert Complement(Interval(1, 3), b) == \
+        Complement(Union(Interval(1, 2, False, True), Interval(2, 3, True, False)), a)
+    assert Complement(a, S.Reals) == Complement(a, S.Reals, evaluate=False)
+    assert Complement(a, Interval(1, 3)) == Complement(a, Interval(1, 3), evaluate=False)
+
+
+def test_issue_9808():
+    # See https://github.com/sympy/sympy/issues/16342
+    assert Complement(FiniteSet(y), FiniteSet(1)) == Complement(FiniteSet(y), FiniteSet(1), evaluate=False)
+    assert Complement(FiniteSet(1, 2, x), FiniteSet(x, y, 2, 3)) == \
+        Complement(FiniteSet(1), FiniteSet(y), evaluate=False)
+
+
+def test_issue_9956():
+    assert Union(Interval(-oo, oo), FiniteSet(1)) == Interval(-oo, oo)
+    assert Interval(-oo, oo).contains(1) is S.true
+
+
+def test_issue_Symbol_inter():
+    i = Interval(0, oo)
+    r = S.Reals
+    mat = Matrix([0, 0, 0])
+    assert Intersection(r, i, FiniteSet(m), FiniteSet(m, n)) == \
+        Intersection(i, FiniteSet(m))
+    assert Intersection(FiniteSet(1, m, n), FiniteSet(m, n, 2), i) == \
+        Intersection(i, FiniteSet(m, n))
+    assert Intersection(FiniteSet(m, n, x), FiniteSet(m, z), r) == \
+        Intersection(Intersection({m, z}, {m, n, x}), r)
+    assert Intersection(FiniteSet(m, n, 3), FiniteSet(m, n, x), r) == \
+        Intersection(FiniteSet(3, m, n), FiniteSet(m, n, x), r, evaluate=False)
+    assert Intersection(FiniteSet(m, n, 3), FiniteSet(m, n, 2, 3), r) == \
+        Intersection(FiniteSet(3, m, n), r)
+    assert Intersection(r, FiniteSet(mat, 2, n), FiniteSet(0, mat, n)) == \
+        Intersection(r, FiniteSet(n))
+    assert Intersection(FiniteSet(sin(x), cos(x)), FiniteSet(sin(x), cos(x), 1), r) == \
+        Intersection(r, FiniteSet(sin(x), cos(x)))
+    assert Intersection(FiniteSet(x**2, 1, sin(x)), FiniteSet(x**2, 2, sin(x)), r) == \
+        Intersection(r, FiniteSet(x**2, sin(x)))
+
+
+def test_issue_11827():
+    assert S.Naturals0**4
+
+
+def test_issue_10113():
+    f = x**2/(x**2 - 4)
+    assert imageset(x, f, S.Reals) == Union(Interval(-oo, 0), Interval(1, oo, True, True))
+    assert imageset(x, f, Interval(-2, 2)) == Interval(-oo, 0)
+    assert imageset(x, f, Interval(-2, 3)) == Union(Interval(-oo, 0), Interval(Rational(9, 5), oo))
+
+
+def test_issue_10248():
+    raises(
+        TypeError, lambda: list(Intersection(S.Reals, FiniteSet(x)))
+    )
+    A = Symbol('A', real=True)
+    assert list(Intersection(S.Reals, FiniteSet(A))) == [A]
+
+
+def test_issue_9447():
+    a = Interval(0, 1) + Interval(2, 3)
+    assert Complement(S.UniversalSet, a) == Complement(
+            S.UniversalSet, Union(Interval(0, 1), Interval(2, 3)), evaluate=False)
+    assert Complement(S.Naturals, a) == Complement(
+            S.Naturals, Union(Interval(0, 1), Interval(2, 3)), evaluate=False)
+
+
+def test_issue_10337():
+    assert (FiniteSet(2) == 3) is False
+    assert (FiniteSet(2) != 3) is True
+    raises(TypeError, lambda: FiniteSet(2) < 3)
+    raises(TypeError, lambda: FiniteSet(2) <= 3)
+    raises(TypeError, lambda: FiniteSet(2) > 3)
+    raises(TypeError, lambda: FiniteSet(2) >= 3)
+
+
+def test_issue_10326():
+    bad = [
+        EmptySet,
+        FiniteSet(1),
+        Interval(1, 2),
+        S.ComplexInfinity,
+        S.ImaginaryUnit,
+        S.Infinity,
+        S.NaN,
+        S.NegativeInfinity,
+        ]
+    interval = Interval(0, 5)
+    for i in bad:
+        assert i not in interval
+
+    x = Symbol('x', real=True)
+    nr = Symbol('nr', extended_real=False)
+    assert x + 1 in Interval(x, x + 4)
+    assert nr not in Interval(x, x + 4)
+    assert Interval(1, 2) in FiniteSet(Interval(0, 5), Interval(1, 2))
+    assert Interval(-oo, oo).contains(oo) is S.false
+    assert Interval(-oo, oo).contains(-oo) is S.false
+
+
+def test_issue_2799():
+    U = S.UniversalSet
+    a = Symbol('a', real=True)
+    inf_interval = Interval(a, oo)
+    R = S.Reals
+
+    assert U + inf_interval == inf_interval + U
+    assert U + R == R + U
+    assert R + inf_interval == inf_interval + R
+
+
+def test_issue_9706():
+    assert Interval(-oo, 0).closure == Interval(-oo, 0, True, False)
+    assert Interval(0, oo).closure == Interval(0, oo, False, True)
+    assert Interval(-oo, oo).closure == Interval(-oo, oo)
+
+
+def test_issue_8257():
+    reals_plus_infinity = Union(Interval(-oo, oo), FiniteSet(oo))
+    reals_plus_negativeinfinity = Union(Interval(-oo, oo), FiniteSet(-oo))
+    assert Interval(-oo, oo) + FiniteSet(oo) == reals_plus_infinity
+    assert FiniteSet(oo) + Interval(-oo, oo) == reals_plus_infinity
+    assert Interval(-oo, oo) + FiniteSet(-oo) == reals_plus_negativeinfinity
+    assert FiniteSet(-oo) + Interval(-oo, oo) == reals_plus_negativeinfinity
+
+
+def test_issue_10931():
+    assert S.Integers - S.Integers == EmptySet
+    assert S.Integers - S.Reals == EmptySet
+
+
+def test_issue_11174():
+    soln = Intersection(Interval(-oo, oo), FiniteSet(-x), evaluate=False)
+    assert Intersection(FiniteSet(-x), S.Reals) == soln
+
+    soln = Intersection(S.Reals, FiniteSet(x), evaluate=False)
+    assert Intersection(FiniteSet(x), S.Reals) == soln
+
+
+def test_issue_18505():
+    assert ImageSet(Lambda(n, sqrt(pi*n/2 - 1 + pi/2)), S.Integers).contains(0) == \
+            Contains(0, ImageSet(Lambda(n, sqrt(pi*n/2 - 1 + pi/2)), S.Integers))
+
+
+def test_finite_set_intersection():
+    # The following should not produce recursion errors
+    # Note: some of these are not completely correct. See
+    # https://github.com/sympy/sympy/issues/16342.
+    assert Intersection(FiniteSet(-oo, x), FiniteSet(x)) == FiniteSet(x)
+    assert Intersection._handle_finite_sets([FiniteSet(-oo, x), FiniteSet(0, x)]) == FiniteSet(x)
+
+    assert Intersection._handle_finite_sets([FiniteSet(-oo, x), FiniteSet(x)]) == FiniteSet(x)
+    assert Intersection._handle_finite_sets([FiniteSet(2, 3, x, y), FiniteSet(1, 2, x)]) == \
+        Intersection._handle_finite_sets([FiniteSet(1, 2, x), FiniteSet(2, 3, x, y)]) == \
+        Intersection(FiniteSet(1, 2, x), FiniteSet(2, 3, x, y)) == \
+        Intersection(FiniteSet(1, 2, x), FiniteSet(2, x, y))
+
+    assert FiniteSet(1+x-y) & FiniteSet(1) == \
+        FiniteSet(1) & FiniteSet(1+x-y) == \
+        Intersection(FiniteSet(1+x-y), FiniteSet(1), evaluate=False)
+
+    assert FiniteSet(1) & FiniteSet(x) == FiniteSet(x) & FiniteSet(1) == \
+        Intersection(FiniteSet(1), FiniteSet(x), evaluate=False)
+
+    assert FiniteSet({x}) & FiniteSet({x, y}) == \
+        Intersection(FiniteSet({x}), FiniteSet({x, y}), evaluate=False)
+
+
+def test_union_intersection_constructor():
+    # The actual exception does not matter here, so long as these fail
+    sets = [FiniteSet(1), FiniteSet(2)]
+    raises(Exception, lambda: Union(sets))
+    raises(Exception, lambda: Intersection(sets))
+    raises(Exception, lambda: Union(tuple(sets)))
+    raises(Exception, lambda: Intersection(tuple(sets)))
+    raises(Exception, lambda: Union(i for i in sets))
+    raises(Exception, lambda: Intersection(i for i in sets))
+
+    # Python sets are treated the same as FiniteSet
+    # The union of a single set (of sets) is the set (of sets) itself
+    assert Union(set(sets)) == FiniteSet(*sets)
+    assert Intersection(set(sets)) == FiniteSet(*sets)
+
+    assert Union({1}, {2}) == FiniteSet(1, 2)
+    assert Intersection({1, 2}, {2, 3}) == FiniteSet(2)
+
+
+def test_Union_contains():
+    assert zoo not in Union(
+        Interval.open(-oo, 0), Interval.open(0, oo))
+
+
+@XFAIL
+def test_issue_16878b():
+    # in intersection_sets for (ImageSet, Set) there is no code
+    # that handles the base_set of S.Reals like there is
+    # for Integers
+    assert imageset(x, (x, x), S.Reals).is_subset(S.Reals**2) is True
+
+def test_DisjointUnion():
+    assert DisjointUnion(FiniteSet(1, 2, 3), FiniteSet(1, 2, 3), FiniteSet(1, 2, 3)).rewrite(Union) == (FiniteSet(1, 2, 3) * FiniteSet(0, 1, 2))
+    assert DisjointUnion(Interval(1, 3), Interval(2, 4)).rewrite(Union) == Union(Interval(1, 3) * FiniteSet(0), Interval(2, 4) * FiniteSet(1))
+    assert DisjointUnion(Interval(0, 5), Interval(0, 5)).rewrite(Union) == Union(Interval(0, 5) * FiniteSet(0), Interval(0, 5) * FiniteSet(1))
+    assert DisjointUnion(Interval(-1, 2), S.EmptySet, S.EmptySet).rewrite(Union) == Interval(-1, 2) * FiniteSet(0)
+    assert DisjointUnion(Interval(-1, 2)).rewrite(Union) == Interval(-1, 2) * FiniteSet(0)
+    assert DisjointUnion(S.EmptySet, Interval(-1, 2), S.EmptySet).rewrite(Union) == Interval(-1, 2) * FiniteSet(1)
+    assert DisjointUnion(Interval(-oo, oo)).rewrite(Union) == Interval(-oo, oo) * FiniteSet(0)
+    assert DisjointUnion(S.EmptySet).rewrite(Union) == S.EmptySet
+    assert DisjointUnion().rewrite(Union) == S.EmptySet
+    raises(TypeError, lambda: DisjointUnion(Symbol('n')))
+
+    x = Symbol("x")
+    y = Symbol("y")
+    z = Symbol("z")
+    assert DisjointUnion(FiniteSet(x), FiniteSet(y, z)).rewrite(Union) == (FiniteSet(x) * FiniteSet(0)) + (FiniteSet(y, z) * FiniteSet(1))
+
+def test_DisjointUnion_is_empty():
+    assert DisjointUnion(S.EmptySet).is_empty is True
+    assert DisjointUnion(S.EmptySet, S.EmptySet).is_empty is True
+    assert DisjointUnion(S.EmptySet, FiniteSet(1, 2, 3)).is_empty is False
+
+def test_DisjointUnion_is_iterable():
+    assert DisjointUnion(S.Integers, S.Naturals, S.Rationals).is_iterable is True
+    assert DisjointUnion(S.EmptySet, S.Reals).is_iterable is False
+    assert DisjointUnion(FiniteSet(1, 2, 3), S.EmptySet, FiniteSet(x, y)).is_iterable is True
+    assert DisjointUnion(S.EmptySet, S.EmptySet).is_iterable is False
+
+def test_DisjointUnion_contains():
+    assert (0, 0) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
+    assert (0, 1) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
+    assert (0, 2) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
+    assert (1, 0) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
+    assert (1, 1) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
+    assert (1, 2) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
+    assert (2, 0) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
+    assert (2, 1) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
+    assert (2, 2) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
+    assert (0, 1, 2) not in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
+    assert (0, 0.5) not in DisjointUnion(FiniteSet(0.5))
+    assert (0, 5) not in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
+    assert (x, 0) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y))
+    assert (y, 0) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y))
+    assert (z, 0) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y))
+    assert (y, 2) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y))
+    assert (0.5, 0) in DisjointUnion(Interval(0, 1), Interval(0, 2))
+    assert (0.5, 1) in DisjointUnion(Interval(0, 1), Interval(0, 2))
+    assert (1.5, 0) not in DisjointUnion(Interval(0, 1), Interval(0, 2))
+    assert (1.5, 1) in DisjointUnion(Interval(0, 1), Interval(0, 2))
+
+def test_DisjointUnion_iter():
+    D = DisjointUnion(FiniteSet(3, 5, 7, 9), FiniteSet(x, y, z))
+    it = iter(D)
+    L1 = [(x, 1), (y, 1), (z, 1)]
+    L2 = [(3, 0), (5, 0), (7, 0), (9, 0)]
+    nxt = next(it)
+    assert nxt in L2
+    L2.remove(nxt)
+    nxt = next(it)
+    assert nxt in L1
+    L1.remove(nxt)
+    nxt = next(it)
+    assert nxt in L2
+    L2.remove(nxt)
+    nxt = next(it)
+    assert nxt in L1
+    L1.remove(nxt)
+    nxt = next(it)
+    assert nxt in L2
+    L2.remove(nxt)
+    nxt = next(it)
+    assert nxt in L1
+    L1.remove(nxt)
+    nxt = next(it)
+    assert nxt in L2
+    L2.remove(nxt)
+    raises(StopIteration, lambda: next(it))
+
+    raises(ValueError, lambda: iter(DisjointUnion(Interval(0, 1), S.EmptySet)))
+
+def test_DisjointUnion_len():
+    assert len(DisjointUnion(FiniteSet(3, 5, 7, 9), FiniteSet(x, y, z))) == 7
+    assert len(DisjointUnion(S.EmptySet, S.EmptySet, FiniteSet(x, y, z), S.EmptySet)) == 3
+    raises(ValueError, lambda: len(DisjointUnion(Interval(0, 1), S.EmptySet)))
+
+def test_SetKind_ProductSet():
+    p = ProductSet(FiniteSet(Matrix([1, 2])), FiniteSet(Matrix([1, 2])))
+    mk = MatrixKind(NumberKind)
+    k = SetKind(TupleKind(mk, mk))
+    assert p.kind is k
+    assert ProductSet(Interval(1, 2), FiniteSet(Matrix([1, 2]))).kind is SetKind(TupleKind(NumberKind, mk))
+
+def test_SetKind_Interval():
+    assert Interval(1, 2).kind is SetKind(NumberKind)
+
+def test_SetKind_EmptySet_UniversalSet():
+    assert S.UniversalSet.kind is SetKind(UndefinedKind)
+    assert EmptySet.kind is SetKind()
+
+def test_SetKind_FiniteSet():
+    assert FiniteSet(1, Matrix([1, 2])).kind is SetKind(UndefinedKind)
+    assert FiniteSet(1, 2).kind is SetKind(NumberKind)
+
+def test_SetKind_Unions():
+    assert Union(FiniteSet(Matrix([1, 2])), Interval(1, 2)).kind is SetKind(UndefinedKind)
+    assert Union(Interval(1, 2), Interval(1, 7)).kind is SetKind(NumberKind)
+
+def test_SetKind_DisjointUnion():
+    A = FiniteSet(1, 2, 3)
+    B = Interval(0, 5)
+    assert DisjointUnion(A, B).kind is SetKind(NumberKind)
+
+def test_SetKind_evaluate_False():
+    U = lambda *args: Union(*args, evaluate=False)
+    assert U({1}, EmptySet).kind is SetKind(NumberKind)
+    assert U(Interval(1, 2), EmptySet).kind is SetKind(NumberKind)
+    assert U({1}, S.UniversalSet).kind is SetKind(UndefinedKind)
+    assert U(Interval(1, 2), Interval(4, 5),
+            FiniteSet(1)).kind is SetKind(NumberKind)
+    I = lambda *args: Intersection(*args, evaluate=False)
+    assert I({1}, S.UniversalSet).kind is SetKind(NumberKind)
+    assert I({1}, EmptySet).kind is SetKind()
+    C = lambda *args: Complement(*args, evaluate=False)
+    assert C(S.UniversalSet, {1, 2, 4, 5}).kind is SetKind(UndefinedKind)
+    assert C({1, 2, 3, 4, 5}, EmptySet).kind is SetKind(NumberKind)
+    assert C(EmptySet, {1, 2, 3, 4, 5}).kind is SetKind()
+
+def test_SetKind_ImageSet_Special():
+    f = ImageSet(Lambda(n, n ** 2), Interval(1, 4))
+    assert (f - FiniteSet(3)).kind is SetKind(NumberKind)
+    assert (f + Interval(16, 17)).kind is SetKind(NumberKind)
+    assert (f + FiniteSet(17)).kind is SetKind(NumberKind)
+
+def test_issue_20089():
+    B = FiniteSet(FiniteSet(1, 2), FiniteSet(1))
+    assert 1 not in B
+    assert 1.0 not in B
+    assert not Eq(1, FiniteSet(1, 2))
+    assert FiniteSet(1) in B
+    A = FiniteSet(1, 2)
+    assert A in B
+    assert B.issubset(B)
+    assert not A.issubset(B)
+    assert 1 in A
+    C = FiniteSet(FiniteSet(1, 2), FiniteSet(1), 1, 2)
+    assert A.issubset(C)
+    assert B.issubset(C)
+
+def test_issue_19378():
+    a = FiniteSet(1, 2)
+    b = ProductSet(a, a)
+    c = FiniteSet((1, 1), (1, 2), (2, 1), (2, 2))
+    assert b.is_subset(c) is True
+    d = FiniteSet(1)
+    assert b.is_subset(d) is False
+    assert Eq(c, b).simplify() is S.true
+    assert Eq(a, c).simplify() is S.false
+    assert Eq({1}, {x}).simplify() == Eq({1}, {x})
+
+def test_intersection_symbolic():
+    n = Symbol('n')
+    # These should not throw an error
+    assert isinstance(Intersection(Range(n), Range(100)), Intersection)
+    assert isinstance(Intersection(Range(n), Interval(1, 100)), Intersection)
+    assert isinstance(Intersection(Range(100), Interval(1, n)), Intersection)
+
+
+@XFAIL
+def test_intersection_symbolic_failing():
+    n = Symbol('n', integer=True, positive=True)
+    assert Intersection(Range(10, n), Range(4, 500, 5)) == Intersection(
+        Range(14, n), Range(14, 500, 5))
+    assert Intersection(Interval(10, n), Range(4, 500, 5)) == Intersection(
+        Interval(14, n), Range(14, 500, 5))
+
+
+def test_issue_20379():
+    #https://github.com/sympy/sympy/issues/20379
+    x = pi - 3.14159265358979
+    assert FiniteSet(x).evalf(2) == FiniteSet(Float('3.23108914886517e-15', 2))
+
+def test_finiteset_simplify():
+    S = FiniteSet(1, cos(1)**2 + sin(1)**2)
+    assert S.simplify() == {1}
+
+def test_issue_14336():
+    #https://github.com/sympy/sympy/issues/14336
+    U = S.Complexes
+    x = Symbol("x")
+    U -= U.intersect(Ne(x, 1).as_set())
+    U -= U.intersect(S.true.as_set())
+
+def test_issue_9855():
+    #https://github.com/sympy/sympy/issues/9855
+    x, y, z = symbols('x, y, z', real=True)
+    s1 = Interval(1, x) & Interval(y, 2)
+    s2 = Interval(1, 2)
+    assert s1.is_subset(s2) == None
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a832614b1d48e26bf01e16f040f34dd412e8e32b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/__init__.py
@@ -0,0 +1,23 @@
+"""A module to manipulate symbolic objects with indices including tensors
+
+"""
+from .indexed import IndexedBase, Idx, Indexed
+from .index_methods import get_contraction_structure, get_indices
+from .functions import shape
+from .array import (MutableDenseNDimArray, ImmutableDenseNDimArray,
+    MutableSparseNDimArray, ImmutableSparseNDimArray, NDimArray, tensorproduct,
+    tensorcontraction, tensordiagonal, derive_by_array, permutedims, Array,
+    DenseNDimArray, SparseNDimArray,)
+
+__all__ = [
+    'IndexedBase', 'Idx', 'Indexed',
+
+    'get_contraction_structure', 'get_indices',
+
+    'shape',
+
+    'MutableDenseNDimArray', 'ImmutableDenseNDimArray',
+    'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'NDimArray',
+    'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array', 'permutedims',
+    'Array', 'DenseNDimArray', 'SparseNDimArray',
+]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..374b2cdcd7521f374313b4d7048b2e0ac8b79d5d
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/__pycache__/functions.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/__pycache__/functions.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cb5a703699c02ccd21f074abf510ba264f4b0590
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/__pycache__/functions.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/__pycache__/index_methods.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/__pycache__/index_methods.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b25f304c1a648d23ef78ae891b609a3efb60bc25
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/__pycache__/index_methods.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/__pycache__/indexed.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/__pycache__/indexed.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7ce4e912ed95c0feb1ee51ddba6474f49308332c
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/__pycache__/indexed.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..eca2eb4c6c58cb113517b6e41737e9d97abbb84e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__init__.py
@@ -0,0 +1,271 @@
+r"""
+N-dim array module for SymPy.
+
+Four classes are provided to handle N-dim arrays, given by the combinations
+dense/sparse (i.e. whether to store all elements or only the non-zero ones in
+memory) and mutable/immutable (immutable classes are SymPy objects, but cannot
+change after they have been created).
+
+Examples
+========
+
+The following examples show the usage of ``Array``. This is an abbreviation for
+``ImmutableDenseNDimArray``, that is an immutable and dense N-dim array, the
+other classes are analogous. For mutable classes it is also possible to change
+element values after the object has been constructed.
+
+Array construction can detect the shape of nested lists and tuples:
+
+>>> from sympy import Array
+>>> a1 = Array([[1, 2], [3, 4], [5, 6]])
+>>> a1
+[[1, 2], [3, 4], [5, 6]]
+>>> a1.shape
+(3, 2)
+>>> a1.rank()
+2
+>>> from sympy.abc import x, y, z
+>>> a2 = Array([[[x, y], [z, x*z]], [[1, x*y], [1/x, x/y]]])
+>>> a2
+[[[x, y], [z, x*z]], [[1, x*y], [1/x, x/y]]]
+>>> a2.shape
+(2, 2, 2)
+>>> a2.rank()
+3
+
+Otherwise one could pass a 1-dim array followed by a shape tuple:
+
+>>> m1 = Array(range(12), (3, 4))
+>>> m1
+[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
+>>> m2 = Array(range(12), (3, 2, 2))
+>>> m2
+[[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]]
+>>> m2[1,1,1]
+7
+>>> m2.reshape(4, 3)
+[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
+
+Slice support:
+
+>>> m2[:, 1, 1]
+[3, 7, 11]
+
+Elementwise derivative:
+
+>>> from sympy.abc import x, y, z
+>>> m3 = Array([x**3, x*y, z])
+>>> m3.diff(x)
+[3*x**2, y, 0]
+>>> m3.diff(z)
+[0, 0, 1]
+
+Multiplication with other SymPy expressions is applied elementwisely:
+
+>>> (1+x)*m3
+[x**3*(x + 1), x*y*(x + 1), z*(x + 1)]
+
+To apply a function to each element of the N-dim array, use ``applyfunc``:
+
+>>> m3.applyfunc(lambda x: x/2)
+[x**3/2, x*y/2, z/2]
+
+N-dim arrays can be converted to nested lists by the ``tolist()`` method:
+
+>>> m2.tolist()
+[[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]]
+>>> isinstance(m2.tolist(), list)
+True
+
+If the rank is 2, it is possible to convert them to matrices with ``tomatrix()``:
+
+>>> m1.tomatrix()
+Matrix([
+[0, 1,  2,  3],
+[4, 5,  6,  7],
+[8, 9, 10, 11]])
+
+Products and contractions
+-------------------------
+
+Tensor product between arrays `A_{i_1,\ldots,i_n}` and `B_{j_1,\ldots,j_m}`
+creates the combined array `P = A \otimes B` defined as
+
+`P_{i_1,\ldots,i_n,j_1,\ldots,j_m} := A_{i_1,\ldots,i_n}\cdot B_{j_1,\ldots,j_m}.`
+
+It is available through ``tensorproduct(...)``:
+
+>>> from sympy import Array, tensorproduct
+>>> from sympy.abc import x,y,z,t
+>>> A = Array([x, y, z, t])
+>>> B = Array([1, 2, 3, 4])
+>>> tensorproduct(A, B)
+[[x, 2*x, 3*x, 4*x], [y, 2*y, 3*y, 4*y], [z, 2*z, 3*z, 4*z], [t, 2*t, 3*t, 4*t]]
+
+In case you don't want to evaluate the tensor product immediately, you can use
+``ArrayTensorProduct``, which creates an unevaluated tensor product expression:
+
+>>> from sympy.tensor.array.expressions import ArrayTensorProduct
+>>> ArrayTensorProduct(A, B)
+ArrayTensorProduct([x, y, z, t], [1, 2, 3, 4])
+
+Calling ``.as_explicit()`` on ``ArrayTensorProduct`` is equivalent to just calling
+``tensorproduct(...)``:
+
+>>> ArrayTensorProduct(A, B).as_explicit()
+[[x, 2*x, 3*x, 4*x], [y, 2*y, 3*y, 4*y], [z, 2*z, 3*z, 4*z], [t, 2*t, 3*t, 4*t]]
+
+Tensor product between a rank-1 array and a matrix creates a rank-3 array:
+
+>>> from sympy import eye
+>>> p1 = tensorproduct(A, eye(4))
+>>> p1
+[[[x, 0, 0, 0], [0, x, 0, 0], [0, 0, x, 0], [0, 0, 0, x]], [[y, 0, 0, 0], [0, y, 0, 0], [0, 0, y, 0], [0, 0, 0, y]], [[z, 0, 0, 0], [0, z, 0, 0], [0, 0, z, 0], [0, 0, 0, z]], [[t, 0, 0, 0], [0, t, 0, 0], [0, 0, t, 0], [0, 0, 0, t]]]
+
+Now, to get back `A_0 \otimes \mathbf{1}` one can access `p_{0,m,n}` by slicing:
+
+>>> p1[0,:,:]
+[[x, 0, 0, 0], [0, x, 0, 0], [0, 0, x, 0], [0, 0, 0, x]]
+
+Tensor contraction sums over the specified axes, for example contracting
+positions `a` and `b` means
+
+`A_{i_1,\ldots,i_a,\ldots,i_b,\ldots,i_n} \implies \sum_k A_{i_1,\ldots,k,\ldots,k,\ldots,i_n}`
+
+Remember that Python indexing is zero starting, to contract the a-th and b-th
+axes it is therefore necessary to specify `a-1` and `b-1`
+
+>>> from sympy import tensorcontraction
+>>> C = Array([[x, y], [z, t]])
+
+The matrix trace is equivalent to the contraction of a rank-2 array:
+
+`A_{m,n} \implies \sum_k A_{k,k}`
+
+>>> tensorcontraction(C, (0, 1))
+t + x
+
+To create an expression representing a tensor contraction that does not get
+evaluated immediately, use ``ArrayContraction``, which is equivalent to
+``tensorcontraction(...)`` if it is followed by ``.as_explicit()``:
+
+>>> from sympy.tensor.array.expressions import ArrayContraction
+>>> ArrayContraction(C, (0, 1))
+ArrayContraction([[x, y], [z, t]], (0, 1))
+>>> ArrayContraction(C, (0, 1)).as_explicit()
+t + x
+
+Matrix product is equivalent to a tensor product of two rank-2 arrays, followed
+by a contraction of the 2nd and 3rd axes (in Python indexing axes number 1, 2).
+
+`A_{m,n}\cdot B_{i,j} \implies \sum_k A_{m, k}\cdot B_{k, j}`
+
+>>> D = Array([[2, 1], [0, -1]])
+>>> tensorcontraction(tensorproduct(C, D), (1, 2))
+[[2*x, x - y], [2*z, -t + z]]
+
+One may verify that the matrix product is equivalent:
+
+>>> from sympy import Matrix
+>>> Matrix([[x, y], [z, t]])*Matrix([[2, 1], [0, -1]])
+Matrix([
+[2*x,  x - y],
+[2*z, -t + z]])
+
+or equivalently
+
+>>> C.tomatrix()*D.tomatrix()
+Matrix([
+[2*x,  x - y],
+[2*z, -t + z]])
+
+Diagonal operator
+-----------------
+
+The ``tensordiagonal`` function acts in a similar manner as ``tensorcontraction``,
+but the joined indices are not summed over, for example diagonalizing
+positions `a` and `b` means
+
+`A_{i_1,\ldots,i_a,\ldots,i_b,\ldots,i_n} \implies A_{i_1,\ldots,k,\ldots,k,\ldots,i_n}
+\implies \tilde{A}_{i_1,\ldots,i_{a-1},i_{a+1},\ldots,i_{b-1},i_{b+1},\ldots,i_n,k}`
+
+where `\tilde{A}` is the array equivalent to the diagonal of `A` at positions
+`a` and `b` moved to the last index slot.
+
+Compare the difference between contraction and diagonal operators:
+
+>>> from sympy import tensordiagonal
+>>> from sympy.abc import a, b, c, d
+>>> m = Matrix([[a, b], [c, d]])
+>>> tensorcontraction(m, [0, 1])
+a + d
+>>> tensordiagonal(m, [0, 1])
+[a, d]
+
+In short, no summation occurs with ``tensordiagonal``.
+
+
+Derivatives by array
+--------------------
+
+The usual derivative operation may be extended to support derivation with
+respect to arrays, provided that all elements in the that array are symbols or
+expressions suitable for derivations.
+
+The definition of a derivative by an array is as follows: given the array
+`A_{i_1, \ldots, i_N}` and the array `X_{j_1, \ldots, j_M}`
+the derivative of arrays will return a new array `B` defined by
+
+`B_{j_1,\ldots,j_M,i_1,\ldots,i_N} := \frac{\partial A_{i_1,\ldots,i_N}}{\partial X_{j_1,\ldots,j_M}}`
+
+The function ``derive_by_array`` performs such an operation:
+
+>>> from sympy import derive_by_array
+>>> from sympy.abc import x, y, z, t
+>>> from sympy import sin, exp
+
+With scalars, it behaves exactly as the ordinary derivative:
+
+>>> derive_by_array(sin(x*y), x)
+y*cos(x*y)
+
+Scalar derived by an array basis:
+
+>>> derive_by_array(sin(x*y), [x, y, z])
+[y*cos(x*y), x*cos(x*y), 0]
+
+Deriving array by an array basis: `B^{nm} := \frac{\partial A^m}{\partial x^n}`
+
+>>> basis = [x, y, z]
+>>> ax = derive_by_array([exp(x), sin(y*z), t], basis)
+>>> ax
+[[exp(x), 0, 0], [0, z*cos(y*z), 0], [0, y*cos(y*z), 0]]
+
+Contraction of the resulting array: `\sum_m \frac{\partial A^m}{\partial x^m}`
+
+>>> tensorcontraction(ax, (0, 1))
+z*cos(y*z) + exp(x)
+
+"""
+
+from .dense_ndim_array import MutableDenseNDimArray, ImmutableDenseNDimArray, DenseNDimArray
+from .sparse_ndim_array import MutableSparseNDimArray, ImmutableSparseNDimArray, SparseNDimArray
+from .ndim_array import NDimArray, ArrayKind
+from .arrayop import tensorproduct, tensorcontraction, tensordiagonal, derive_by_array, permutedims
+from .array_comprehension import ArrayComprehension, ArrayComprehensionMap
+
+Array = ImmutableDenseNDimArray
+
+__all__ = [
+    'MutableDenseNDimArray', 'ImmutableDenseNDimArray', 'DenseNDimArray',
+
+    'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'SparseNDimArray',
+
+    'NDimArray', 'ArrayKind',
+
+    'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array',
+
+    'permutedims', 'ArrayComprehension', 'ArrayComprehensionMap',
+
+    'Array',
+]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..98bd632f34db270d19649e4d6e25cca5e2c58d25
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/array_comprehension.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/array_comprehension.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1be8655ec69b45bc8ec4125a89b0595473854534
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/array_comprehension.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/arrayop.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/arrayop.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7656fb9ba0715a6249a46d1056e9b19dce751500
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/arrayop.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/dense_ndim_array.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/dense_ndim_array.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a75c3a1e5df6805a1a2385359bb7212967ba59dc
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/dense_ndim_array.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/mutable_ndim_array.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/mutable_ndim_array.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc63ce11352c34ff7950f43a72e7cdf80c4a0b7f
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/mutable_ndim_array.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/ndim_array.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/ndim_array.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..897a881edf780a08f76fa8b4c8dac499e958bca1
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/ndim_array.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/sparse_ndim_array.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/sparse_ndim_array.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7757a3d4f278289db951018217f824acb98f7372
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/sparse_ndim_array.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/array_comprehension.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/array_comprehension.py
new file mode 100644
index 0000000000000000000000000000000000000000..95702f499f3e40597fd0144929138ac1329962ee
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/array_comprehension.py
@@ -0,0 +1,399 @@
+import functools, itertools
+from sympy.core.sympify import _sympify, sympify
+from sympy.core.expr import Expr
+from sympy.core import Basic, Tuple
+from sympy.tensor.array import ImmutableDenseNDimArray
+from sympy.core.symbol import Symbol
+from sympy.core.numbers import Integer
+
+
+class ArrayComprehension(Basic):
+    """
+    Generate a list comprehension.
+
+    Explanation
+    ===========
+
+    If there is a symbolic dimension, for example, say [i for i in range(1, N)] where
+    N is a Symbol, then the expression will not be expanded to an array. Otherwise,
+    calling the doit() function will launch the expansion.
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.array import ArrayComprehension
+    >>> from sympy import symbols
+    >>> i, j, k = symbols('i j k')
+    >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
+    >>> a
+    ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
+    >>> a.doit()
+    [[11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43]]
+    >>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k))
+    >>> b.doit()
+    ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k))
+    """
+    def __new__(cls, function, *symbols, **assumptions):
+        if any(len(l) != 3 or None for l in symbols):
+            raise ValueError('ArrayComprehension requires values lower and upper bound'
+                              ' for the expression')
+        arglist = [sympify(function)]
+        arglist.extend(cls._check_limits_validity(function, symbols))
+        obj = Basic.__new__(cls, *arglist, **assumptions)
+        obj._limits = obj._args[1:]
+        obj._shape = cls._calculate_shape_from_limits(obj._limits)
+        obj._rank = len(obj._shape)
+        obj._loop_size = cls._calculate_loop_size(obj._shape)
+        return obj
+
+    @property
+    def function(self):
+        """The function applied across limits.
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.array import ArrayComprehension
+        >>> from sympy import symbols
+        >>> i, j = symbols('i j')
+        >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
+        >>> a.function
+        10*i + j
+        """
+        return self._args[0]
+
+    @property
+    def limits(self):
+        """
+        The list of limits that will be applied while expanding the array.
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.array import ArrayComprehension
+        >>> from sympy import symbols
+        >>> i, j = symbols('i j')
+        >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
+        >>> a.limits
+        ((i, 1, 4), (j, 1, 3))
+        """
+        return self._limits
+
+    @property
+    def free_symbols(self):
+        """
+        The set of the free_symbols in the array.
+        Variables appeared in the bounds are supposed to be excluded
+        from the free symbol set.
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.array import ArrayComprehension
+        >>> from sympy import symbols
+        >>> i, j, k = symbols('i j k')
+        >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
+        >>> a.free_symbols
+        set()
+        >>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3))
+        >>> b.free_symbols
+        {k}
+        """
+        expr_free_sym = self.function.free_symbols
+        for var, inf, sup in self._limits:
+            expr_free_sym.discard(var)
+            curr_free_syms = inf.free_symbols.union(sup.free_symbols)
+            expr_free_sym = expr_free_sym.union(curr_free_syms)
+        return expr_free_sym
+
+    @property
+    def variables(self):
+        """The tuples of the variables in the limits.
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.array import ArrayComprehension
+        >>> from sympy import symbols
+        >>> i, j, k = symbols('i j k')
+        >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
+        >>> a.variables
+        [i, j]
+        """
+        return [l[0] for l in self._limits]
+
+    @property
+    def bound_symbols(self):
+        """The list of dummy variables.
+
+        Note
+        ====
+
+        Note that all variables are dummy variables since a limit without
+        lower bound or upper bound is not accepted.
+        """
+        return [l[0] for l in self._limits if len(l) != 1]
+
+    @property
+    def shape(self):
+        """
+        The shape of the expanded array, which may have symbols.
+
+        Note
+        ====
+
+        Both the lower and the upper bounds are included while
+        calculating the shape.
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.array import ArrayComprehension
+        >>> from sympy import symbols
+        >>> i, j, k = symbols('i j k')
+        >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
+        >>> a.shape
+        (4, 3)
+        >>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3))
+        >>> b.shape
+        (4, k + 3)
+        """
+        return self._shape
+
+    @property
+    def is_shape_numeric(self):
+        """
+        Test if the array is shape-numeric which means there is no symbolic
+        dimension.
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.array import ArrayComprehension
+        >>> from sympy import symbols
+        >>> i, j, k = symbols('i j k')
+        >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
+        >>> a.is_shape_numeric
+        True
+        >>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3))
+        >>> b.is_shape_numeric
+        False
+        """
+        for _, inf, sup in self._limits:
+            if Basic(inf, sup).atoms(Symbol):
+                return False
+        return True
+
+    def rank(self):
+        """The rank of the expanded array.
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.array import ArrayComprehension
+        >>> from sympy import symbols
+        >>> i, j, k = symbols('i j k')
+        >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
+        >>> a.rank()
+        2
+        """
+        return self._rank
+
+    def __len__(self):
+        """
+        The length of the expanded array which means the number
+        of elements in the array.
+
+        Raises
+        ======
+
+        ValueError : When the length of the array is symbolic
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.array import ArrayComprehension
+        >>> from sympy import symbols
+        >>> i, j = symbols('i j')
+        >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
+        >>> len(a)
+        12
+        """
+        if self._loop_size.free_symbols:
+            raise ValueError('Symbolic length is not supported')
+        return self._loop_size
+
+    @classmethod
+    def _check_limits_validity(cls, function, limits):
+        #limits = sympify(limits)
+        new_limits = []
+        for var, inf, sup in limits:
+            var = _sympify(var)
+            inf = _sympify(inf)
+            #since this is stored as an argument, it should be
+            #a Tuple
+            if isinstance(sup, list):
+                sup = Tuple(*sup)
+            else:
+                sup = _sympify(sup)
+            new_limits.append(Tuple(var, inf, sup))
+            if any((not isinstance(i, Expr)) or i.atoms(Symbol, Integer) != i.atoms()
+                                                                for i in [inf, sup]):
+                raise TypeError('Bounds should be an Expression(combination of Integer and Symbol)')
+            if (inf > sup) == True:
+                raise ValueError('Lower bound should be inferior to upper bound')
+            if var in inf.free_symbols or var in sup.free_symbols:
+                raise ValueError('Variable should not be part of its bounds')
+        return new_limits
+
+    @classmethod
+    def _calculate_shape_from_limits(cls, limits):
+        return tuple([sup - inf + 1 for _, inf, sup in limits])
+
+    @classmethod
+    def _calculate_loop_size(cls, shape):
+        if not shape:
+            return 0
+        loop_size = 1
+        for l in shape:
+            loop_size = loop_size * l
+
+        return loop_size
+
+    def doit(self, **hints):
+        if not self.is_shape_numeric:
+            return self
+
+        return self._expand_array()
+
+    def _expand_array(self):
+        res = []
+        for values in itertools.product(*[range(inf, sup+1)
+                                        for var, inf, sup
+                                        in self._limits]):
+            res.append(self._get_element(values))
+
+        return ImmutableDenseNDimArray(res, self.shape)
+
+    def _get_element(self, values):
+        temp = self.function
+        for var, val in zip(self.variables, values):
+            temp = temp.subs(var, val)
+        return temp
+
+    def tolist(self):
+        """Transform the expanded array to a list.
+
+        Raises
+        ======
+
+        ValueError : When there is a symbolic dimension
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.array import ArrayComprehension
+        >>> from sympy import symbols
+        >>> i, j = symbols('i j')
+        >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
+        >>> a.tolist()
+        [[11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43]]
+        """
+        if self.is_shape_numeric:
+            return self._expand_array().tolist()
+
+        raise ValueError("A symbolic array cannot be expanded to a list")
+
+    def tomatrix(self):
+        """Transform the expanded array to a matrix.
+
+        Raises
+        ======
+
+        ValueError : When there is a symbolic dimension
+        ValueError : When the rank of the expanded array is not equal to 2
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.array import ArrayComprehension
+        >>> from sympy import symbols
+        >>> i, j = symbols('i j')
+        >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
+        >>> a.tomatrix()
+        Matrix([
+        [11, 12, 13],
+        [21, 22, 23],
+        [31, 32, 33],
+        [41, 42, 43]])
+        """
+        from sympy.matrices import Matrix
+
+        if not self.is_shape_numeric:
+            raise ValueError("A symbolic array cannot be expanded to a matrix")
+        if self._rank != 2:
+            raise ValueError('Dimensions must be of size of 2')
+
+        return Matrix(self._expand_array().tomatrix())
+
+
+def isLambda(v):
+    LAMBDA = lambda: 0
+    return isinstance(v, type(LAMBDA)) and v.__name__ == LAMBDA.__name__
+
+class ArrayComprehensionMap(ArrayComprehension):
+    '''
+    A subclass of ArrayComprehension dedicated to map external function lambda.
+
+    Notes
+    =====
+
+    Only the lambda function is considered.
+    At most one argument in lambda function is accepted in order to avoid ambiguity
+    in value assignment.
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.array import ArrayComprehensionMap
+    >>> from sympy import symbols
+    >>> i, j, k = symbols('i j k')
+    >>> a = ArrayComprehensionMap(lambda: 1, (i, 1, 4))
+    >>> a.doit()
+    [1, 1, 1, 1]
+    >>> b = ArrayComprehensionMap(lambda a: a+1, (j, 1, 4))
+    >>> b.doit()
+    [2, 3, 4, 5]
+
+    '''
+    def __new__(cls, function, *symbols, **assumptions):
+        if any(len(l) != 3 or None for l in symbols):
+            raise ValueError('ArrayComprehension requires values lower and upper bound'
+                              ' for the expression')
+
+        if not isLambda(function):
+            raise ValueError('Data type not supported')
+
+        arglist = cls._check_limits_validity(function, symbols)
+        obj = Basic.__new__(cls, *arglist, **assumptions)
+        obj._limits = obj._args
+        obj._shape = cls._calculate_shape_from_limits(obj._limits)
+        obj._rank = len(obj._shape)
+        obj._loop_size = cls._calculate_loop_size(obj._shape)
+        obj._lambda = function
+        return obj
+
+    @property
+    def func(self):
+        class _(ArrayComprehensionMap):
+            def __new__(cls, *args, **kwargs):
+                return ArrayComprehensionMap(self._lambda, *args, **kwargs)
+        return _
+
+    def _get_element(self, values):
+        temp = self._lambda
+        if self._lambda.__code__.co_argcount == 0:
+            temp = temp()
+        elif self._lambda.__code__.co_argcount == 1:
+            temp = temp(functools.reduce(lambda a, b: a*b, values))
+        return temp
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/array_derivatives.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/array_derivatives.py
new file mode 100644
index 0000000000000000000000000000000000000000..a38db6caefe256a8c7e1f3415b78351b3787fee9
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/array_derivatives.py
@@ -0,0 +1,129 @@
+from __future__ import annotations
+
+from sympy.core.expr import Expr
+from sympy.core.function import Derivative
+from sympy.core.numbers import Integer
+from sympy.matrices.matrixbase import MatrixBase
+from .ndim_array import NDimArray
+from .arrayop import derive_by_array
+from sympy.matrices.expressions.matexpr import MatrixExpr
+from sympy.matrices.expressions.special import ZeroMatrix
+from sympy.matrices.expressions.matexpr import _matrix_derivative
+
+
+class ArrayDerivative(Derivative):
+
+    is_scalar = False
+
+    def __new__(cls, expr, *variables, **kwargs):
+        obj = super().__new__(cls, expr, *variables, **kwargs)
+        if isinstance(obj, ArrayDerivative):
+            obj._shape = obj._get_shape()
+        return obj
+
+    def _get_shape(self):
+        shape = ()
+        for v, count in self.variable_count:
+            if hasattr(v, "shape"):
+                for i in range(count):
+                    shape += v.shape
+        if hasattr(self.expr, "shape"):
+            shape += self.expr.shape
+        return shape
+
+    @property
+    def shape(self):
+        return self._shape
+
+    @classmethod
+    def _get_zero_with_shape_like(cls, expr):
+        if isinstance(expr, (MatrixBase, NDimArray)):
+            return expr.zeros(*expr.shape)
+        elif isinstance(expr, MatrixExpr):
+            return ZeroMatrix(*expr.shape)
+        else:
+            raise RuntimeError("Unable to determine shape of array-derivative.")
+
+    @staticmethod
+    def _call_derive_scalar_by_matrix(expr: Expr, v: MatrixBase) -> Expr:
+        return v.applyfunc(lambda x: expr.diff(x))
+
+    @staticmethod
+    def _call_derive_scalar_by_matexpr(expr: Expr, v: MatrixExpr) -> Expr:
+        if expr.has(v):
+            return _matrix_derivative(expr, v)
+        else:
+            return ZeroMatrix(*v.shape)
+
+    @staticmethod
+    def _call_derive_scalar_by_array(expr: Expr, v: NDimArray) -> Expr:
+        return v.applyfunc(lambda x: expr.diff(x))
+
+    @staticmethod
+    def _call_derive_matrix_by_scalar(expr: MatrixBase, v: Expr) -> Expr:
+        return _matrix_derivative(expr, v)
+
+    @staticmethod
+    def _call_derive_matexpr_by_scalar(expr: MatrixExpr, v: Expr) -> Expr:
+        return expr._eval_derivative(v)
+
+    @staticmethod
+    def _call_derive_array_by_scalar(expr: NDimArray, v: Expr) -> Expr:
+        return expr.applyfunc(lambda x: x.diff(v))
+
+    @staticmethod
+    def _call_derive_default(expr: Expr, v: Expr) -> Expr | None:
+        if expr.has(v):
+            return _matrix_derivative(expr, v)
+        else:
+            return None
+
+    @classmethod
+    def _dispatch_eval_derivative_n_times(cls, expr, v, count):
+        # Evaluate the derivative `n` times.  If
+        # `_eval_derivative_n_times` is not overridden by the current
+        # object, the default in `Basic` will call a loop over
+        # `_eval_derivative`:
+
+        if not isinstance(count, (int, Integer)) or ((count <= 0) == True):
+            return None
+
+        # TODO: this could be done with multiple-dispatching:
+        if expr.is_scalar:
+            if isinstance(v, MatrixBase):
+                result = cls._call_derive_scalar_by_matrix(expr, v)
+            elif isinstance(v, MatrixExpr):
+                result = cls._call_derive_scalar_by_matexpr(expr, v)
+            elif isinstance(v, NDimArray):
+                result = cls._call_derive_scalar_by_array(expr, v)
+            elif v.is_scalar:
+                # scalar by scalar has a special
+                return super()._dispatch_eval_derivative_n_times(expr, v, count)
+            else:
+                return None
+        elif v.is_scalar:
+            if isinstance(expr, MatrixBase):
+                result = cls._call_derive_matrix_by_scalar(expr, v)
+            elif isinstance(expr, MatrixExpr):
+                result = cls._call_derive_matexpr_by_scalar(expr, v)
+            elif isinstance(expr, NDimArray):
+                result = cls._call_derive_array_by_scalar(expr, v)
+            else:
+                return None
+        else:
+            # Both `expr` and `v` are some array/matrix type:
+            if isinstance(expr, MatrixBase) or isinstance(v, MatrixBase):
+                result = derive_by_array(expr, v)
+            elif isinstance(expr, MatrixExpr) and isinstance(v, MatrixExpr):
+                result = cls._call_derive_default(expr, v)
+            elif isinstance(expr, MatrixExpr) or isinstance(v, MatrixExpr):
+                # if one expression is a symbolic matrix expression while the other isn't, don't evaluate:
+                return None
+            else:
+                result = derive_by_array(expr, v)
+        if result is None:
+            return None
+        if count == 1:
+            return result
+        else:
+            return cls._dispatch_eval_derivative_n_times(result, v, count - 1)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/arrayop.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/arrayop.py
new file mode 100644
index 0000000000000000000000000000000000000000..a81e6b381a8a93f0cd585278a4be0259b06406dd
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/arrayop.py
@@ -0,0 +1,528 @@
+import itertools
+from collections.abc import Iterable
+
+from sympy.core._print_helpers import Printable
+from sympy.core.containers import Tuple
+from sympy.core.function import diff
+from sympy.core.singleton import S
+from sympy.core.sympify import _sympify
+
+from sympy.tensor.array.ndim_array import NDimArray
+from sympy.tensor.array.dense_ndim_array import DenseNDimArray, ImmutableDenseNDimArray
+from sympy.tensor.array.sparse_ndim_array import SparseNDimArray
+
+
+def _arrayfy(a):
+    from sympy.matrices import MatrixBase
+
+    if isinstance(a, NDimArray):
+        return a
+    if isinstance(a, (MatrixBase, list, tuple, Tuple)):
+        return ImmutableDenseNDimArray(a)
+    return a
+
+
+def tensorproduct(*args):
+    """
+    Tensor product among scalars or array-like objects.
+
+    The equivalent operator for array expressions is ``ArrayTensorProduct``,
+    which can be used to keep the expression unevaluated.
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.array import tensorproduct, Array
+    >>> from sympy.abc import x, y, z, t
+    >>> A = Array([[1, 2], [3, 4]])
+    >>> B = Array([x, y])
+    >>> tensorproduct(A, B)
+    [[[x, y], [2*x, 2*y]], [[3*x, 3*y], [4*x, 4*y]]]
+    >>> tensorproduct(A, x)
+    [[x, 2*x], [3*x, 4*x]]
+    >>> tensorproduct(A, B, B)
+    [[[[x**2, x*y], [x*y, y**2]], [[2*x**2, 2*x*y], [2*x*y, 2*y**2]]], [[[3*x**2, 3*x*y], [3*x*y, 3*y**2]], [[4*x**2, 4*x*y], [4*x*y, 4*y**2]]]]
+
+    Applying this function on two matrices will result in a rank 4 array.
+
+    >>> from sympy import Matrix, eye
+    >>> m = Matrix([[x, y], [z, t]])
+    >>> p = tensorproduct(eye(3), m)
+    >>> p
+    [[[[x, y], [z, t]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[x, y], [z, t]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]], [[x, y], [z, t]]]]
+
+    See Also
+    ========
+
+    sympy.tensor.array.expressions.array_expressions.ArrayTensorProduct
+
+    """
+    from sympy.tensor.array import SparseNDimArray, ImmutableSparseNDimArray
+
+    if len(args) == 0:
+        return S.One
+    if len(args) == 1:
+        return _arrayfy(args[0])
+    from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
+    from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
+    from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
+    from sympy.matrices.expressions.matexpr import MatrixSymbol
+    if any(isinstance(arg, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)) for arg in args):
+        return ArrayTensorProduct(*args)
+    if len(args) > 2:
+        return tensorproduct(tensorproduct(args[0], args[1]), *args[2:])
+
+    # length of args is 2:
+    a, b = map(_arrayfy, args)
+
+    if not isinstance(a, NDimArray) or not isinstance(b, NDimArray):
+        return a*b
+
+    if isinstance(a, SparseNDimArray) and isinstance(b, SparseNDimArray):
+        lp = len(b)
+        new_array = {k1*lp + k2: v1*v2 for k1, v1 in a._sparse_array.items() for k2, v2 in b._sparse_array.items()}
+        return ImmutableSparseNDimArray(new_array, a.shape + b.shape)
+
+    product_list = [i*j for i in Flatten(a) for j in Flatten(b)]
+    return ImmutableDenseNDimArray(product_list, a.shape + b.shape)
+
+
+def _util_contraction_diagonal(array, *contraction_or_diagonal_axes):
+    array = _arrayfy(array)
+
+    # Verify contraction_axes:
+    taken_dims = set()
+    for axes_group in contraction_or_diagonal_axes:
+        if not isinstance(axes_group, Iterable):
+            raise ValueError("collections of contraction/diagonal axes expected")
+
+        dim = array.shape[axes_group[0]]
+
+        for d in axes_group:
+            if d in taken_dims:
+                raise ValueError("dimension specified more than once")
+            if dim != array.shape[d]:
+                raise ValueError("cannot contract or diagonalize between axes of different dimension")
+            taken_dims.add(d)
+
+    rank = array.rank()
+
+    remaining_shape = [dim for i, dim in enumerate(array.shape) if i not in taken_dims]
+    cum_shape = [0]*rank
+    _cumul = 1
+    for i in range(rank):
+        cum_shape[rank - i - 1] = _cumul
+        _cumul *= int(array.shape[rank - i - 1])
+
+    # DEFINITION: by absolute position it is meant the position along the one
+    # dimensional array containing all the tensor components.
+
+    # Possible future work on this module: move computation of absolute
+    # positions to a class method.
+
+    # Determine absolute positions of the uncontracted indices:
+    remaining_indices = [[cum_shape[i]*j for j in range(array.shape[i])]
+                         for i in range(rank) if i not in taken_dims]
+
+    # Determine absolute positions of the contracted indices:
+    summed_deltas = []
+    for axes_group in contraction_or_diagonal_axes:
+        lidx = []
+        for js in range(array.shape[axes_group[0]]):
+            lidx.append(sum(cum_shape[ig] * js for ig in axes_group))
+        summed_deltas.append(lidx)
+
+    return array, remaining_indices, remaining_shape, summed_deltas
+
+
+def tensorcontraction(array, *contraction_axes):
+    """
+    Contraction of an array-like object on the specified axes.
+
+    The equivalent operator for array expressions is ``ArrayContraction``,
+    which can be used to keep the expression unevaluated.
+
+    Examples
+    ========
+
+    >>> from sympy import Array, tensorcontraction
+    >>> from sympy import Matrix, eye
+    >>> tensorcontraction(eye(3), (0, 1))
+    3
+    >>> A = Array(range(18), (3, 2, 3))
+    >>> A
+    [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]], [[12, 13, 14], [15, 16, 17]]]
+    >>> tensorcontraction(A, (0, 2))
+    [21, 30]
+
+    Matrix multiplication may be emulated with a proper combination of
+    ``tensorcontraction`` and ``tensorproduct``
+
+    >>> from sympy import tensorproduct
+    >>> from sympy.abc import a,b,c,d,e,f,g,h
+    >>> m1 = Matrix([[a, b], [c, d]])
+    >>> m2 = Matrix([[e, f], [g, h]])
+    >>> p = tensorproduct(m1, m2)
+    >>> p
+    [[[[a*e, a*f], [a*g, a*h]], [[b*e, b*f], [b*g, b*h]]], [[[c*e, c*f], [c*g, c*h]], [[d*e, d*f], [d*g, d*h]]]]
+    >>> tensorcontraction(p, (1, 2))
+    [[a*e + b*g, a*f + b*h], [c*e + d*g, c*f + d*h]]
+    >>> m1*m2
+    Matrix([
+    [a*e + b*g, a*f + b*h],
+    [c*e + d*g, c*f + d*h]])
+
+    See Also
+    ========
+
+    sympy.tensor.array.expressions.array_expressions.ArrayContraction
+
+    """
+    from sympy.tensor.array.expressions.array_expressions import _array_contraction
+    from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
+    from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
+    from sympy.matrices.expressions.matexpr import MatrixSymbol
+    if isinstance(array, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)):
+        return _array_contraction(array, *contraction_axes)
+
+    array, remaining_indices, remaining_shape, summed_deltas = _util_contraction_diagonal(array, *contraction_axes)
+
+    # Compute the contracted array:
+    #
+    # 1. external for loops on all uncontracted indices.
+    #    Uncontracted indices are determined by the combinatorial product of
+    #    the absolute positions of the remaining indices.
+    # 2. internal loop on all contracted indices.
+    #    It sums the values of the absolute contracted index and the absolute
+    #    uncontracted index for the external loop.
+    contracted_array = []
+    for icontrib in itertools.product(*remaining_indices):
+        index_base_position = sum(icontrib)
+        isum = S.Zero
+        for sum_to_index in itertools.product(*summed_deltas):
+            idx = array._get_tuple_index(index_base_position + sum(sum_to_index))
+            isum += array[idx]
+
+        contracted_array.append(isum)
+
+    if len(remaining_indices) == 0:
+        assert len(contracted_array) == 1
+        return contracted_array[0]
+
+    return type(array)(contracted_array, remaining_shape)
+
+
+def tensordiagonal(array, *diagonal_axes):
+    """
+    Diagonalization of an array-like object on the specified axes.
+
+    This is equivalent to multiplying the expression by Kronecker deltas
+    uniting the axes.
+
+    The diagonal indices are put at the end of the axes.
+
+    The equivalent operator for array expressions is ``ArrayDiagonal``, which
+    can be used to keep the expression unevaluated.
+
+    Examples
+    ========
+
+    ``tensordiagonal`` acting on a 2-dimensional array by axes 0 and 1 is
+    equivalent to the diagonal of the matrix:
+
+    >>> from sympy import Array, tensordiagonal
+    >>> from sympy import Matrix, eye
+    >>> tensordiagonal(eye(3), (0, 1))
+    [1, 1, 1]
+
+    >>> from sympy.abc import a,b,c,d
+    >>> m1 = Matrix([[a, b], [c, d]])
+    >>> tensordiagonal(m1, [0, 1])
+    [a, d]
+
+    In case of higher dimensional arrays, the diagonalized out dimensions
+    are appended removed and appended as a single dimension at the end:
+
+    >>> A = Array(range(18), (3, 2, 3))
+    >>> A
+    [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]], [[12, 13, 14], [15, 16, 17]]]
+    >>> tensordiagonal(A, (0, 2))
+    [[0, 7, 14], [3, 10, 17]]
+    >>> from sympy import permutedims
+    >>> tensordiagonal(A, (0, 2)) == permutedims(Array([A[0, :, 0], A[1, :, 1], A[2, :, 2]]), [1, 0])
+    True
+
+    See Also
+    ========
+
+    sympy.tensor.array.expressions.array_expressions.ArrayDiagonal
+
+    """
+    if any(len(i) <= 1 for i in diagonal_axes):
+        raise ValueError("need at least two axes to diagonalize")
+
+    from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
+    from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
+    from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal, _array_diagonal
+    from sympy.matrices.expressions.matexpr import MatrixSymbol
+    if isinstance(array, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)):
+        return _array_diagonal(array, *diagonal_axes)
+
+    ArrayDiagonal._validate(array, *diagonal_axes)
+
+    array, remaining_indices, remaining_shape, diagonal_deltas = _util_contraction_diagonal(array, *diagonal_axes)
+
+    # Compute the diagonalized array:
+    #
+    # 1. external for loops on all undiagonalized indices.
+    #    Undiagonalized indices are determined by the combinatorial product of
+    #    the absolute positions of the remaining indices.
+    # 2. internal loop on all diagonal indices.
+    #    It appends the values of the absolute diagonalized index and the absolute
+    #    undiagonalized index for the external loop.
+    diagonalized_array = []
+    diagonal_shape = [len(i) for i in diagonal_deltas]
+    for icontrib in itertools.product(*remaining_indices):
+        index_base_position = sum(icontrib)
+        isum = []
+        for sum_to_index in itertools.product(*diagonal_deltas):
+            idx = array._get_tuple_index(index_base_position + sum(sum_to_index))
+            isum.append(array[idx])
+
+        isum = type(array)(isum).reshape(*diagonal_shape)
+        diagonalized_array.append(isum)
+
+    return type(array)(diagonalized_array, remaining_shape + diagonal_shape)
+
+
+def derive_by_array(expr, dx):
+    r"""
+    Derivative by arrays. Supports both arrays and scalars.
+
+    The equivalent operator for array expressions is ``array_derive``.
+
+    Explanation
+    ===========
+
+    Given the array `A_{i_1, \ldots, i_N}` and the array `X_{j_1, \ldots, j_M}`
+    this function will return a new array `B` defined by
+
+    `B_{j_1,\ldots,j_M,i_1,\ldots,i_N} := \frac{\partial A_{i_1,\ldots,i_N}}{\partial X_{j_1,\ldots,j_M}}`
+
+    Examples
+    ========
+
+    >>> from sympy import derive_by_array
+    >>> from sympy.abc import x, y, z, t
+    >>> from sympy import cos
+    >>> derive_by_array(cos(x*t), x)
+    -t*sin(t*x)
+    >>> derive_by_array(cos(x*t), [x, y, z, t])
+    [-t*sin(t*x), 0, 0, -x*sin(t*x)]
+    >>> derive_by_array([x, y**2*z], [[x, y], [z, t]])
+    [[[1, 0], [0, 2*y*z]], [[0, y**2], [0, 0]]]
+
+    """
+    from sympy.matrices import MatrixBase
+    from sympy.tensor.array import SparseNDimArray
+    array_types = (Iterable, MatrixBase, NDimArray)
+
+    if isinstance(dx, array_types):
+        dx = ImmutableDenseNDimArray(dx)
+        for i in dx:
+            if not i._diff_wrt:
+                raise ValueError("cannot derive by this array")
+
+    if isinstance(expr, array_types):
+        if isinstance(expr, NDimArray):
+            expr = expr.as_immutable()
+        else:
+            expr = ImmutableDenseNDimArray(expr)
+
+        if isinstance(dx, array_types):
+            if isinstance(expr, SparseNDimArray):
+                lp = len(expr)
+                new_array = {k + i*lp: v
+                             for i, x in enumerate(Flatten(dx))
+                             for k, v in expr.diff(x)._sparse_array.items()}
+            else:
+                new_array = [[y.diff(x) for y in Flatten(expr)] for x in Flatten(dx)]
+            return type(expr)(new_array, dx.shape + expr.shape)
+        else:
+            return expr.diff(dx)
+    else:
+        expr = _sympify(expr)
+        if isinstance(dx, array_types):
+            return ImmutableDenseNDimArray([expr.diff(i) for i in Flatten(dx)], dx.shape)
+        else:
+            dx = _sympify(dx)
+            return diff(expr, dx)
+
+
+def permutedims(expr, perm=None, index_order_old=None, index_order_new=None):
+    """
+    Permutes the indices of an array.
+
+    Parameter specifies the permutation of the indices.
+
+    The equivalent operator for array expressions is ``PermuteDims``, which can
+    be used to keep the expression unevaluated.
+
+    Examples
+    ========
+
+    >>> from sympy.abc import x, y, z, t
+    >>> from sympy import sin
+    >>> from sympy import Array, permutedims
+    >>> a = Array([[x, y, z], [t, sin(x), 0]])
+    >>> a
+    [[x, y, z], [t, sin(x), 0]]
+    >>> permutedims(a, (1, 0))
+    [[x, t], [y, sin(x)], [z, 0]]
+
+    If the array is of second order, ``transpose`` can be used:
+
+    >>> from sympy import transpose
+    >>> transpose(a)
+    [[x, t], [y, sin(x)], [z, 0]]
+
+    Examples on higher dimensions:
+
+    >>> b = Array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
+    >>> permutedims(b, (2, 1, 0))
+    [[[1, 5], [3, 7]], [[2, 6], [4, 8]]]
+    >>> permutedims(b, (1, 2, 0))
+    [[[1, 5], [2, 6]], [[3, 7], [4, 8]]]
+
+    An alternative way to specify the same permutations as in the previous
+    lines involves passing the *old* and *new* indices, either as a list or as
+    a string:
+
+    >>> permutedims(b, index_order_old="cba", index_order_new="abc")
+    [[[1, 5], [3, 7]], [[2, 6], [4, 8]]]
+    >>> permutedims(b, index_order_old="cab", index_order_new="abc")
+    [[[1, 5], [2, 6]], [[3, 7], [4, 8]]]
+
+    ``Permutation`` objects are also allowed:
+
+    >>> from sympy.combinatorics import Permutation
+    >>> permutedims(b, Permutation([1, 2, 0]))
+    [[[1, 5], [2, 6]], [[3, 7], [4, 8]]]
+
+    See Also
+    ========
+
+    sympy.tensor.array.expressions.array_expressions.PermuteDims
+
+    """
+    from sympy.tensor.array import SparseNDimArray
+
+    from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
+    from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
+    from sympy.tensor.array.expressions.array_expressions import _permute_dims
+    from sympy.matrices.expressions.matexpr import MatrixSymbol
+    from sympy.tensor.array.expressions import PermuteDims
+    from sympy.tensor.array.expressions.array_expressions import get_rank
+    perm = PermuteDims._get_permutation_from_arguments(perm, index_order_old, index_order_new, get_rank(expr))
+    if isinstance(expr, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)):
+        return _permute_dims(expr, perm)
+
+    if not isinstance(expr, NDimArray):
+        expr = ImmutableDenseNDimArray(expr)
+
+    from sympy.combinatorics import Permutation
+    if not isinstance(perm, Permutation):
+        perm = Permutation(list(perm))
+
+    if perm.size != expr.rank():
+        raise ValueError("wrong permutation size")
+
+    # Get the inverse permutation:
+    iperm = ~perm
+    new_shape = perm(expr.shape)
+
+    if isinstance(expr, SparseNDimArray):
+        return type(expr)({tuple(perm(expr._get_tuple_index(k))): v
+                           for k, v in expr._sparse_array.items()}, new_shape)
+
+    indices_span = perm([range(i) for i in expr.shape])
+
+    new_array = [None]*len(expr)
+    for i, idx in enumerate(itertools.product(*indices_span)):
+        t = iperm(idx)
+        new_array[i] = expr[t]
+
+    return type(expr)(new_array, new_shape)
+
+
+class Flatten(Printable):
+    """
+    Flatten an iterable object to a list in a lazy-evaluation way.
+
+    Notes
+    =====
+
+    This class is an iterator with which the memory cost can be economised.
+    Optimisation has been considered to ameliorate the performance for some
+    specific data types like DenseNDimArray and SparseNDimArray.
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.array.arrayop import Flatten
+    >>> from sympy.tensor.array import Array
+    >>> A = Array(range(6)).reshape(2, 3)
+    >>> Flatten(A)
+    Flatten([[0, 1, 2], [3, 4, 5]])
+    >>> [i for i in Flatten(A)]
+    [0, 1, 2, 3, 4, 5]
+    """
+    def __init__(self, iterable):
+        from sympy.matrices.matrixbase import MatrixBase
+        from sympy.tensor.array import NDimArray
+
+        if not isinstance(iterable, (Iterable, MatrixBase)):
+            raise NotImplementedError("Data type not yet supported")
+
+        if isinstance(iterable, list):
+            iterable = NDimArray(iterable)
+
+        self._iter = iterable
+        self._idx = 0
+
+    def __iter__(self):
+        return self
+
+    def __next__(self):
+        from sympy.matrices.matrixbase import MatrixBase
+
+        if len(self._iter) > self._idx:
+            if isinstance(self._iter, DenseNDimArray):
+                result = self._iter._array[self._idx]
+
+            elif isinstance(self._iter, SparseNDimArray):
+                if self._idx in self._iter._sparse_array:
+                    result = self._iter._sparse_array[self._idx]
+                else:
+                    result = 0
+
+            elif isinstance(self._iter, MatrixBase):
+                result = self._iter[self._idx]
+
+            elif hasattr(self._iter, '__next__'):
+                result = next(self._iter)
+
+            else:
+                result = self._iter[self._idx]
+
+        else:
+            raise StopIteration
+
+        self._idx += 1
+        return result
+
+    def next(self):
+        return self.__next__()
+
+    def _sympystr(self, printer):
+        return type(self).__name__ + '(' + printer._print(self._iter) + ')'
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/dense_ndim_array.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/dense_ndim_array.py
new file mode 100644
index 0000000000000000000000000000000000000000..576e452c55d8d374ca1f72c553f3a64de7227d43
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/dense_ndim_array.py
@@ -0,0 +1,206 @@
+import functools
+from typing import List
+
+from sympy.core.basic import Basic
+from sympy.core.containers import Tuple
+from sympy.core.singleton import S
+from sympy.core.sympify import _sympify
+from sympy.tensor.array.mutable_ndim_array import MutableNDimArray
+from sympy.tensor.array.ndim_array import NDimArray, ImmutableNDimArray, ArrayKind
+from sympy.utilities.iterables import flatten
+
+
+class DenseNDimArray(NDimArray):
+
+    _array: List[Basic]
+
+    def __new__(self, *args, **kwargs):
+        return ImmutableDenseNDimArray(*args, **kwargs)
+
+    @property
+    def kind(self) -> ArrayKind:
+        return ArrayKind._union(self._array)
+
+    def __getitem__(self, index):
+        """
+        Allows to get items from N-dim array.
+
+        Examples
+        ========
+
+        >>> from sympy import MutableDenseNDimArray
+        >>> a = MutableDenseNDimArray([0, 1, 2, 3], (2, 2))
+        >>> a
+        [[0, 1], [2, 3]]
+        >>> a[0, 0]
+        0
+        >>> a[1, 1]
+        3
+        >>> a[0]
+        [0, 1]
+        >>> a[1]
+        [2, 3]
+
+
+        Symbolic index:
+
+        >>> from sympy.abc import i, j
+        >>> a[i, j]
+        [[0, 1], [2, 3]][i, j]
+
+        Replace `i` and `j` to get element `(1, 1)`:
+
+        >>> a[i, j].subs({i: 1, j: 1})
+        3
+
+        """
+        syindex = self._check_symbolic_index(index)
+        if syindex is not None:
+            return syindex
+
+        index = self._check_index_for_getitem(index)
+
+        if isinstance(index, tuple) and any(isinstance(i, slice) for i in index):
+            sl_factors, eindices = self._get_slice_data_for_array_access(index)
+            array = [self._array[self._parse_index(i)] for i in eindices]
+            nshape = [len(el) for i, el in enumerate(sl_factors) if isinstance(index[i], slice)]
+            return type(self)(array, nshape)
+        else:
+            index = self._parse_index(index)
+            return self._array[index]
+
+    @classmethod
+    def zeros(cls, *shape):
+        list_length = functools.reduce(lambda x, y: x*y, shape, S.One)
+        return cls._new(([0]*list_length,), shape)
+
+    def tomatrix(self):
+        """
+        Converts MutableDenseNDimArray to Matrix. Can convert only 2-dim array, else will raise error.
+
+        Examples
+        ========
+
+        >>> from sympy import MutableDenseNDimArray
+        >>> a = MutableDenseNDimArray([1 for i in range(9)], (3, 3))
+        >>> b = a.tomatrix()
+        >>> b
+        Matrix([
+        [1, 1, 1],
+        [1, 1, 1],
+        [1, 1, 1]])
+
+        """
+        from sympy.matrices import Matrix
+
+        if self.rank() != 2:
+            raise ValueError('Dimensions must be of size of 2')
+
+        return Matrix(self.shape[0], self.shape[1], self._array)
+
+    def reshape(self, *newshape):
+        """
+        Returns MutableDenseNDimArray instance with new shape. Elements number
+        must be        suitable to new shape. The only argument of method sets
+        new shape.
+
+        Examples
+        ========
+
+        >>> from sympy import MutableDenseNDimArray
+        >>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3))
+        >>> a.shape
+        (2, 3)
+        >>> a
+        [[1, 2, 3], [4, 5, 6]]
+        >>> b = a.reshape(3, 2)
+        >>> b.shape
+        (3, 2)
+        >>> b
+        [[1, 2], [3, 4], [5, 6]]
+
+        """
+        new_total_size = functools.reduce(lambda x,y: x*y, newshape)
+        if new_total_size != self._loop_size:
+            raise ValueError('Expecting reshape size to %d but got prod(%s) = %d' % (
+                self._loop_size, str(newshape), new_total_size))
+
+        # there is no `.func` as this class does not subtype `Basic`:
+        return type(self)(self._array, newshape)
+
+
+class ImmutableDenseNDimArray(DenseNDimArray, ImmutableNDimArray): # type: ignore
+    def __new__(cls, iterable, shape=None, **kwargs):
+        return cls._new(iterable, shape, **kwargs)
+
+    @classmethod
+    def _new(cls, iterable, shape, **kwargs):
+        shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
+        shape = Tuple(*map(_sympify, shape))
+        cls._check_special_bounds(flat_list, shape)
+        flat_list = flatten(flat_list)
+        flat_list = Tuple(*flat_list)
+        self = Basic.__new__(cls, flat_list, shape, **kwargs)
+        self._shape = shape
+        self._array = list(flat_list)
+        self._rank = len(shape)
+        self._loop_size = functools.reduce(lambda x,y: x*y, shape, 1)
+        return self
+
+    def __setitem__(self, index, value):
+        raise TypeError('immutable N-dim array')
+
+    def as_mutable(self):
+        return MutableDenseNDimArray(self)
+
+    def _eval_simplify(self, **kwargs):
+        from sympy.simplify.simplify import simplify
+        return self.applyfunc(simplify)
+
+class MutableDenseNDimArray(DenseNDimArray, MutableNDimArray):
+
+    def __new__(cls, iterable=None, shape=None, **kwargs):
+        return cls._new(iterable, shape, **kwargs)
+
+    @classmethod
+    def _new(cls, iterable, shape, **kwargs):
+        shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
+        flat_list = flatten(flat_list)
+        self = object.__new__(cls)
+        self._shape = shape
+        self._array = list(flat_list)
+        self._rank = len(shape)
+        self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else len(flat_list)
+        return self
+
+    def __setitem__(self, index, value):
+        """Allows to set items to MutableDenseNDimArray.
+
+        Examples
+        ========
+
+        >>> from sympy import MutableDenseNDimArray
+        >>> a = MutableDenseNDimArray.zeros(2,  2)
+        >>> a[0,0] = 1
+        >>> a[1,1] = 1
+        >>> a
+        [[1, 0], [0, 1]]
+
+        """
+        if isinstance(index, tuple) and any(isinstance(i, slice) for i in index):
+            value, eindices, slice_offsets = self._get_slice_data_for_array_assignment(index, value)
+            for i in eindices:
+                other_i = [ind - j for ind, j in zip(i, slice_offsets) if j is not None]
+                self._array[self._parse_index(i)] = value[other_i]
+        else:
+            index = self._parse_index(index)
+            self._setter_iterable_check(value)
+            value = _sympify(value)
+            self._array[index] = value
+
+    def as_immutable(self):
+        return ImmutableDenseNDimArray(self)
+
+    @property
+    def free_symbols(self):
+        return {i for j in self._array for i in j.free_symbols}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1658241782cdf0e38a30c43a6d67f9811297f4c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/__init__.py
@@ -0,0 +1,178 @@
+r"""
+Array expressions are expressions representing N-dimensional arrays, without
+evaluating them. These expressions represent in a certain way abstract syntax
+trees of operations on N-dimensional arrays.
+
+Every N-dimensional array operator has a corresponding array expression object.
+
+Table of correspondences:
+
+=============================== =============================
+         Array operator           Array expression operator
+=============================== =============================
+        tensorproduct                 ArrayTensorProduct
+        tensorcontraction             ArrayContraction
+        tensordiagonal                ArrayDiagonal
+        permutedims                   PermuteDims
+=============================== =============================
+
+Examples
+========
+
+``ArraySymbol`` objects are the N-dimensional equivalent of ``MatrixSymbol``
+objects in the matrix module:
+
+>>> from sympy.tensor.array.expressions import ArraySymbol
+>>> from sympy.abc import i, j, k
+>>> A = ArraySymbol("A", (3, 2, 4))
+>>> A.shape
+(3, 2, 4)
+>>> A[i, j, k]
+A[i, j, k]
+>>> A.as_explicit()
+[[[A[0, 0, 0], A[0, 0, 1], A[0, 0, 2], A[0, 0, 3]],
+  [A[0, 1, 0], A[0, 1, 1], A[0, 1, 2], A[0, 1, 3]]],
+ [[A[1, 0, 0], A[1, 0, 1], A[1, 0, 2], A[1, 0, 3]],
+  [A[1, 1, 0], A[1, 1, 1], A[1, 1, 2], A[1, 1, 3]]],
+ [[A[2, 0, 0], A[2, 0, 1], A[2, 0, 2], A[2, 0, 3]],
+  [A[2, 1, 0], A[2, 1, 1], A[2, 1, 2], A[2, 1, 3]]]]
+
+Component-explicit arrays can be added inside array expressions:
+
+>>> from sympy import Array
+>>> from sympy import tensorproduct
+>>> from sympy.tensor.array.expressions import ArrayTensorProduct
+>>> a = Array([1, 2, 3])
+>>> b = Array([i, j, k])
+>>> expr = ArrayTensorProduct(a, b, b)
+>>> expr
+ArrayTensorProduct([1, 2, 3], [i, j, k], [i, j, k])
+>>> expr.as_explicit() == tensorproduct(a, b, b)
+True
+
+Constructing array expressions from index-explicit forms
+--------------------------------------------------------
+
+Array expressions are index-implicit. This means they do not use any indices to
+represent array operations. The function ``convert_indexed_to_array( ... )``
+may be used to convert index-explicit expressions to array expressions.
+It takes as input two parameters: the index-explicit expression and the order
+of the indices:
+
+>>> from sympy.tensor.array.expressions import convert_indexed_to_array
+>>> from sympy import Sum
+>>> A = ArraySymbol("A", (3, 3))
+>>> B = ArraySymbol("B", (3, 3))
+>>> convert_indexed_to_array(A[i, j], [i, j])
+A
+>>> convert_indexed_to_array(A[i, j], [j, i])
+PermuteDims(A, (0 1))
+>>> convert_indexed_to_array(A[i, j] + B[j, i], [i, j])
+ArrayAdd(A, PermuteDims(B, (0 1)))
+>>> convert_indexed_to_array(Sum(A[i, j]*B[j, k], (j, 0, 2)), [i, k])
+ArrayContraction(ArrayTensorProduct(A, B), (1, 2))
+
+The diagonal of a matrix in the array expression form:
+
+>>> convert_indexed_to_array(A[i, i], [i])
+ArrayDiagonal(A, (0, 1))
+
+The trace of a matrix in the array expression form:
+
+>>> convert_indexed_to_array(Sum(A[i, i], (i, 0, 2)), [i])
+ArrayContraction(A, (0, 1))
+
+Compatibility with matrices
+---------------------------
+
+Array expressions can be mixed with objects from the matrix module:
+
+>>> from sympy import MatrixSymbol
+>>> from sympy.tensor.array.expressions import ArrayContraction
+>>> M = MatrixSymbol("M", 3, 3)
+>>> N = MatrixSymbol("N", 3, 3)
+
+Express the matrix product in the array expression form:
+
+>>> from sympy.tensor.array.expressions import convert_matrix_to_array
+>>> expr = convert_matrix_to_array(M*N)
+>>> expr
+ArrayContraction(ArrayTensorProduct(M, N), (1, 2))
+
+The expression can be converted back to matrix form:
+
+>>> from sympy.tensor.array.expressions import convert_array_to_matrix
+>>> convert_array_to_matrix(expr)
+M*N
+
+Add a second contraction on the remaining axes in order to get the trace of `M \cdot N`:
+
+>>> expr_tr = ArrayContraction(expr, (0, 1))
+>>> expr_tr
+ArrayContraction(ArrayContraction(ArrayTensorProduct(M, N), (1, 2)), (0, 1))
+
+Flatten the expression by calling ``.doit()`` and remove the nested array contraction operations:
+
+>>> expr_tr.doit()
+ArrayContraction(ArrayTensorProduct(M, N), (0, 3), (1, 2))
+
+Get the explicit form of the array expression:
+
+>>> expr.as_explicit()
+[[M[0, 0]*N[0, 0] + M[0, 1]*N[1, 0] + M[0, 2]*N[2, 0], M[0, 0]*N[0, 1] + M[0, 1]*N[1, 1] + M[0, 2]*N[2, 1], M[0, 0]*N[0, 2] + M[0, 1]*N[1, 2] + M[0, 2]*N[2, 2]],
+ [M[1, 0]*N[0, 0] + M[1, 1]*N[1, 0] + M[1, 2]*N[2, 0], M[1, 0]*N[0, 1] + M[1, 1]*N[1, 1] + M[1, 2]*N[2, 1], M[1, 0]*N[0, 2] + M[1, 1]*N[1, 2] + M[1, 2]*N[2, 2]],
+ [M[2, 0]*N[0, 0] + M[2, 1]*N[1, 0] + M[2, 2]*N[2, 0], M[2, 0]*N[0, 1] + M[2, 1]*N[1, 1] + M[2, 2]*N[2, 1], M[2, 0]*N[0, 2] + M[2, 1]*N[1, 2] + M[2, 2]*N[2, 2]]]
+
+Express the trace of a matrix:
+
+>>> from sympy import Trace
+>>> convert_matrix_to_array(Trace(M))
+ArrayContraction(M, (0, 1))
+>>> convert_matrix_to_array(Trace(M*N))
+ArrayContraction(ArrayTensorProduct(M, N), (0, 3), (1, 2))
+
+Express the transposition of a matrix (will be expressed as a permutation of the axes:
+
+>>> convert_matrix_to_array(M.T)
+PermuteDims(M, (0 1))
+
+Compute the derivative array expressions:
+
+>>> from sympy.tensor.array.expressions import array_derive
+>>> d = array_derive(M, M)
+>>> d
+PermuteDims(ArrayTensorProduct(I, I), (3)(1 2))
+
+Verify that the derivative corresponds to the form computed with explicit matrices:
+
+>>> d.as_explicit()
+[[[[1, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 1, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 1], [0, 0, 0], [0, 0, 0]]], [[[0, 0, 0], [1, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 1, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 1], [0, 0, 0]]], [[[0, 0, 0], [0, 0, 0], [1, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 1, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 1]]]]
+>>> Me = M.as_explicit()
+>>> Me.diff(Me)
+[[[[1, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 1, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 1], [0, 0, 0], [0, 0, 0]]], [[[0, 0, 0], [1, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 1, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 1], [0, 0, 0]]], [[[0, 0, 0], [0, 0, 0], [1, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 1, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 1]]]]
+
+"""
+
+__all__ = [
+    "ArraySymbol", "ArrayElement", "ZeroArray", "OneArray",
+    "ArrayTensorProduct",
+    "ArrayContraction",
+    "ArrayDiagonal",
+    "PermuteDims",
+    "ArrayAdd",
+    "ArrayElementwiseApplyFunc",
+    "Reshape",
+    "convert_array_to_matrix",
+    "convert_matrix_to_array",
+    "convert_array_to_indexed",
+    "convert_indexed_to_array",
+    "array_derive",
+]
+
+from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayAdd, PermuteDims, ArrayDiagonal, \
+    ArrayContraction, Reshape, ArraySymbol, ArrayElement, ZeroArray, OneArray, ArrayElementwiseApplyFunc
+from sympy.tensor.array.expressions.arrayexpr_derivatives import array_derive
+from sympy.tensor.array.expressions.from_array_to_indexed import convert_array_to_indexed
+from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
+from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array
+from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/array_expressions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/array_expressions.py
new file mode 100644
index 0000000000000000000000000000000000000000..f062e3de4c24987d62ba0b3a19fe474fb4687940
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/array_expressions.py
@@ -0,0 +1,1969 @@
+from __future__ import annotations
+import collections.abc
+import operator
+from collections import defaultdict, Counter
+from functools import reduce
+import itertools
+from itertools import accumulate
+
+import typing
+
+from sympy.core.numbers import Integer
+from sympy.core.relational import Equality
+from sympy.functions.special.tensor_functions import KroneckerDelta
+from sympy.core.basic import Basic
+from sympy.core.containers import Tuple
+from sympy.core.expr import Expr
+from sympy.core.function import (Function, Lambda)
+from sympy.core.mul import Mul
+from sympy.core.singleton import S
+from sympy.core.sorting import default_sort_key
+from sympy.core.symbol import (Dummy, Symbol)
+from sympy.matrices.matrixbase import MatrixBase
+from sympy.matrices.expressions.diagonal import diagonalize_vector
+from sympy.matrices.expressions.matexpr import MatrixExpr
+from sympy.matrices.expressions.special import ZeroMatrix
+from sympy.tensor.array.arrayop import (permutedims, tensorcontraction, tensordiagonal, tensorproduct)
+from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
+from sympy.tensor.array.ndim_array import NDimArray
+from sympy.tensor.indexed import (Indexed, IndexedBase)
+from sympy.matrices.expressions.matexpr import MatrixElement
+from sympy.tensor.array.expressions.utils import _apply_recursively_over_nested_lists, _sort_contraction_indices, \
+    _get_mapping_from_subranks, _build_push_indices_up_func_transformation, _get_contraction_links, \
+    _build_push_indices_down_func_transformation
+from sympy.combinatorics import Permutation
+from sympy.combinatorics.permutations import _af_invert
+from sympy.core.sympify import _sympify
+
+
+class _ArrayExpr(Expr):
+    shape: tuple[Expr, ...]
+
+    def __getitem__(self, item):
+        if not isinstance(item, collections.abc.Iterable):
+            item = (item,)
+        ArrayElement._check_shape(self, item)
+        return self._get(item)
+
+    def _get(self, item):
+        return _get_array_element_or_slice(self, item)
+
+
+class ArraySymbol(_ArrayExpr):
+    """
+    Symbol representing an array expression
+    """
+
+    _iterable = False
+
+    def __new__(cls, symbol, shape: typing.Iterable) -> "ArraySymbol":
+        if isinstance(symbol, str):
+            symbol = Symbol(symbol)
+        # symbol = _sympify(symbol)
+        shape = Tuple(*map(_sympify, shape))
+        obj = Expr.__new__(cls, symbol, shape)
+        return obj
+
+    @property
+    def name(self):
+        return self._args[0]
+
+    @property
+    def shape(self):
+        return self._args[1]
+
+    def as_explicit(self):
+        if not all(i.is_Integer for i in self.shape):
+            raise ValueError("cannot express explicit array with symbolic shape")
+        data = [self[i] for i in itertools.product(*[range(j) for j in self.shape])]
+        return ImmutableDenseNDimArray(data).reshape(*self.shape)
+
+
+class ArrayElement(Expr):
+    """
+    An element of an array.
+    """
+
+    _diff_wrt = True
+    is_symbol = True
+    is_commutative = True
+
+    def __new__(cls, name, indices):
+        if isinstance(name, str):
+            name = Symbol(name)
+        name = _sympify(name)
+        if not isinstance(indices, collections.abc.Iterable):
+            indices = (indices,)
+        indices = _sympify(tuple(indices))
+        cls._check_shape(name, indices)
+        obj = Expr.__new__(cls, name, indices)
+        return obj
+
+    @classmethod
+    def _check_shape(cls, name, indices):
+        indices = tuple(indices)
+        if hasattr(name, "shape"):
+            index_error = IndexError("number of indices does not match shape of the array")
+            if len(indices) != len(name.shape):
+                raise index_error
+            if any((i >= s) == True for i, s in zip(indices, name.shape)):
+                raise ValueError("shape is out of bounds")
+        if any((i < 0) == True for i in indices):
+            raise ValueError("shape contains negative values")
+
+    @property
+    def name(self):
+        return self._args[0]
+
+    @property
+    def indices(self):
+        return self._args[1]
+
+    def _eval_derivative(self, s):
+        if not isinstance(s, ArrayElement):
+            return S.Zero
+
+        if s == self:
+            return S.One
+
+        if s.name != self.name:
+            return S.Zero
+
+        return Mul.fromiter(KroneckerDelta(i, j) for i, j in zip(self.indices, s.indices))
+
+
+class ZeroArray(_ArrayExpr):
+    """
+    Symbolic array of zeros. Equivalent to ``ZeroMatrix`` for matrices.
+    """
+
+    def __new__(cls, *shape):
+        if len(shape) == 0:
+            return S.Zero
+        shape = map(_sympify, shape)
+        obj = Expr.__new__(cls, *shape)
+        return obj
+
+    @property
+    def shape(self):
+        return self._args
+
+    def as_explicit(self):
+        if not all(i.is_Integer for i in self.shape):
+            raise ValueError("Cannot return explicit form for symbolic shape.")
+        return ImmutableDenseNDimArray.zeros(*self.shape)
+
+    def _get(self, item):
+        return S.Zero
+
+
+class OneArray(_ArrayExpr):
+    """
+    Symbolic array of ones.
+    """
+
+    def __new__(cls, *shape):
+        if len(shape) == 0:
+            return S.One
+        shape = map(_sympify, shape)
+        obj = Expr.__new__(cls, *shape)
+        return obj
+
+    @property
+    def shape(self):
+        return self._args
+
+    def as_explicit(self):
+        if not all(i.is_Integer for i in self.shape):
+            raise ValueError("Cannot return explicit form for symbolic shape.")
+        return ImmutableDenseNDimArray([S.One for i in range(reduce(operator.mul, self.shape))]).reshape(*self.shape)
+
+    def _get(self, item):
+        return S.One
+
+
+class _CodegenArrayAbstract(Basic):
+
+    @property
+    def subranks(self):
+        """
+        Returns the ranks of the objects in the uppermost tensor product inside
+        the current object.  In case no tensor products are contained, return
+        the atomic ranks.
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.array import tensorproduct, tensorcontraction
+        >>> from sympy import MatrixSymbol
+        >>> M = MatrixSymbol("M", 3, 3)
+        >>> N = MatrixSymbol("N", 3, 3)
+        >>> P = MatrixSymbol("P", 3, 3)
+
+        Important: do not confuse the rank of the matrix with the rank of an array.
+
+        >>> tp = tensorproduct(M, N, P)
+        >>> tp.subranks
+        [2, 2, 2]
+
+        >>> co = tensorcontraction(tp, (1, 2), (3, 4))
+        >>> co.subranks
+        [2, 2, 2]
+        """
+        return self._subranks[:]
+
+    def subrank(self):
+        """
+        The sum of ``subranks``.
+        """
+        return sum(self.subranks)
+
+    @property
+    def shape(self):
+        return self._shape
+
+    def doit(self, **hints):
+        deep = hints.get("deep", True)
+        if deep:
+            return self.func(*[arg.doit(**hints) for arg in self.args])._canonicalize()
+        else:
+            return self._canonicalize()
+
+class ArrayTensorProduct(_CodegenArrayAbstract):
+    r"""
+    Class to represent the tensor product of array-like objects.
+    """
+
+    def __new__(cls, *args, **kwargs):
+        args = [_sympify(arg) for arg in args]
+
+        canonicalize = kwargs.pop("canonicalize", False)
+
+        ranks = [get_rank(arg) for arg in args]
+
+        obj = Basic.__new__(cls, *args)
+        obj._subranks = ranks
+        shapes = [get_shape(i) for i in args]
+
+        if any(i is None for i in shapes):
+            obj._shape = None
+        else:
+            obj._shape = tuple(j for i in shapes for j in i)
+        if canonicalize:
+            return obj._canonicalize()
+        return obj
+
+    def _canonicalize(self):
+        args = self.args
+        args = self._flatten(args)
+
+        ranks = [get_rank(arg) for arg in args]
+
+        # Check if there are nested permutation and lift them up:
+        permutation_cycles = []
+        for i, arg in enumerate(args):
+            if not isinstance(arg, PermuteDims):
+                continue
+            permutation_cycles.extend([[k + sum(ranks[:i]) for k in j] for j in arg.permutation.cyclic_form])
+            args[i] = arg.expr
+        if permutation_cycles:
+            return _permute_dims(_array_tensor_product(*args), Permutation(sum(ranks)-1)*Permutation(permutation_cycles))
+
+        if len(args) == 1:
+            return args[0]
+
+        # If any object is a ZeroArray, return a ZeroArray:
+        if any(isinstance(arg, (ZeroArray, ZeroMatrix)) for arg in args):
+            shapes = reduce(operator.add, [get_shape(i) for i in args], ())
+            return ZeroArray(*shapes)
+
+        # If there are contraction objects inside, transform the whole
+        # expression into `ArrayContraction`:
+        contractions = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayContraction)}
+        if contractions:
+            ranks = [_get_subrank(arg) if isinstance(arg, ArrayContraction) else get_rank(arg) for arg in args]
+            cumulative_ranks = list(accumulate([0] + ranks))[:-1]
+            tp = _array_tensor_product(*[arg.expr if isinstance(arg, ArrayContraction) else arg for arg in args])
+            contraction_indices = [tuple(cumulative_ranks[i] + k for k in j) for i, arg in contractions.items() for j in arg.contraction_indices]
+            return _array_contraction(tp, *contraction_indices)
+
+        diagonals = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayDiagonal)}
+        if diagonals:
+            inverse_permutation = []
+            last_perm = []
+            ranks = [get_rank(arg) for arg in args]
+            cumulative_ranks = list(accumulate([0] + ranks))[:-1]
+            for i, arg in enumerate(args):
+                if isinstance(arg, ArrayDiagonal):
+                    i1 = get_rank(arg) - len(arg.diagonal_indices)
+                    i2 = len(arg.diagonal_indices)
+                    inverse_permutation.extend([cumulative_ranks[i] + j for j in range(i1)])
+                    last_perm.extend([cumulative_ranks[i] + j for j in range(i1, i1 + i2)])
+                else:
+                    inverse_permutation.extend([cumulative_ranks[i] + j for j in range(get_rank(arg))])
+            inverse_permutation.extend(last_perm)
+            tp = _array_tensor_product(*[arg.expr if isinstance(arg, ArrayDiagonal) else arg for arg in args])
+            ranks2 = [_get_subrank(arg) if isinstance(arg, ArrayDiagonal) else get_rank(arg) for arg in args]
+            cumulative_ranks2 = list(accumulate([0] + ranks2))[:-1]
+            diagonal_indices = [tuple(cumulative_ranks2[i] + k for k in j) for i, arg in diagonals.items() for j in arg.diagonal_indices]
+            return _permute_dims(_array_diagonal(tp, *diagonal_indices), _af_invert(inverse_permutation))
+
+        return self.func(*args, canonicalize=False)
+
+    @classmethod
+    def _flatten(cls, args):
+        args = [i for arg in args for i in (arg.args if isinstance(arg, cls) else [arg])]
+        return args
+
+    def as_explicit(self):
+        return tensorproduct(*[arg.as_explicit() if hasattr(arg, "as_explicit") else arg for arg in self.args])
+
+
+class ArrayAdd(_CodegenArrayAbstract):
+    r"""
+    Class for elementwise array additions.
+    """
+
+    def __new__(cls, *args, **kwargs):
+        args = [_sympify(arg) for arg in args]
+        ranks = [get_rank(arg) for arg in args]
+        ranks = list(set(ranks))
+        if len(ranks) != 1:
+            raise ValueError("summing arrays of different ranks")
+        shapes = [arg.shape for arg in args]
+        if len({i for i in shapes if i is not None}) > 1:
+            raise ValueError("mismatching shapes in addition")
+
+        canonicalize = kwargs.pop("canonicalize", False)
+
+        obj = Basic.__new__(cls, *args)
+        obj._subranks = ranks
+        if any(i is None for i in shapes):
+            obj._shape = None
+        else:
+            obj._shape = shapes[0]
+        if canonicalize:
+            return obj._canonicalize()
+        return obj
+
+    def _canonicalize(self):
+        args = self.args
+
+        # Flatten:
+        args = self._flatten_args(args)
+
+        shapes = [get_shape(arg) for arg in args]
+        args = [arg for arg in args if not isinstance(arg, (ZeroArray, ZeroMatrix))]
+        if len(args) == 0:
+            if any(i for i in shapes if i is None):
+                raise NotImplementedError("cannot handle addition of ZeroMatrix/ZeroArray and undefined shape object")
+            return ZeroArray(*shapes[0])
+        elif len(args) == 1:
+            return args[0]
+        return self.func(*args, canonicalize=False)
+
+    @classmethod
+    def _flatten_args(cls, args):
+        new_args = []
+        for arg in args:
+            if isinstance(arg, ArrayAdd):
+                new_args.extend(arg.args)
+            else:
+                new_args.append(arg)
+        return new_args
+
+    def as_explicit(self):
+        return reduce(
+            operator.add,
+            [arg.as_explicit() if hasattr(arg, "as_explicit") else arg for arg in self.args])
+
+
+class PermuteDims(_CodegenArrayAbstract):
+    r"""
+    Class to represent permutation of axes of arrays.
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.array import permutedims
+    >>> from sympy import MatrixSymbol
+    >>> M = MatrixSymbol("M", 3, 3)
+    >>> cg = permutedims(M, [1, 0])
+
+    The object ``cg`` represents the transposition of ``M``, as the permutation
+    ``[1, 0]`` will act on its indices by switching them:
+
+    `M_{ij} \Rightarrow M_{ji}`
+
+    This is evident when transforming back to matrix form:
+
+    >>> from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
+    >>> convert_array_to_matrix(cg)
+    M.T
+
+    >>> N = MatrixSymbol("N", 3, 2)
+    >>> cg = permutedims(N, [1, 0])
+    >>> cg.shape
+    (2, 3)
+
+    There are optional parameters that can be used as alternative to the permutation:
+
+    >>> from sympy.tensor.array.expressions import ArraySymbol, PermuteDims
+    >>> M = ArraySymbol("M", (1, 2, 3, 4, 5))
+    >>> expr = PermuteDims(M, index_order_old="ijklm", index_order_new="kijml")
+    >>> expr
+    PermuteDims(M, (0 2 1)(3 4))
+    >>> expr.shape
+    (3, 1, 2, 5, 4)
+
+    Permutations of tensor products are simplified in order to achieve a
+    standard form:
+
+    >>> from sympy.tensor.array import tensorproduct
+    >>> M = MatrixSymbol("M", 4, 5)
+    >>> tp = tensorproduct(M, N)
+    >>> tp.shape
+    (4, 5, 3, 2)
+    >>> perm1 = permutedims(tp, [2, 3, 1, 0])
+
+    The args ``(M, N)`` have been sorted and the permutation has been
+    simplified, the expression is equivalent:
+
+    >>> perm1.expr.args
+    (N, M)
+    >>> perm1.shape
+    (3, 2, 5, 4)
+    >>> perm1.permutation
+    (2 3)
+
+    The permutation in its array form has been simplified from
+    ``[2, 3, 1, 0]`` to ``[0, 1, 3, 2]``, as the arguments of the tensor
+    product `M` and `N` have been switched:
+
+    >>> perm1.permutation.array_form
+    [0, 1, 3, 2]
+
+    We can nest a second permutation:
+
+    >>> perm2 = permutedims(perm1, [1, 0, 2, 3])
+    >>> perm2.shape
+    (2, 3, 5, 4)
+    >>> perm2.permutation.array_form
+    [1, 0, 3, 2]
+    """
+
+    def __new__(cls, expr, permutation=None, index_order_old=None, index_order_new=None, **kwargs):
+        from sympy.combinatorics import Permutation
+        expr = _sympify(expr)
+        expr_rank = get_rank(expr)
+        permutation = cls._get_permutation_from_arguments(permutation, index_order_old, index_order_new, expr_rank)
+        permutation = Permutation(permutation)
+        permutation_size = permutation.size
+        if permutation_size != expr_rank:
+            raise ValueError("Permutation size must be the length of the shape of expr")
+
+        canonicalize = kwargs.pop("canonicalize", False)
+
+        obj = Basic.__new__(cls, expr, permutation)
+        obj._subranks = [get_rank(expr)]
+        shape = get_shape(expr)
+        if shape is None:
+            obj._shape = None
+        else:
+            obj._shape = tuple(shape[permutation(i)] for i in range(len(shape)))
+        if canonicalize:
+            return obj._canonicalize()
+        return obj
+
+    def _canonicalize(self):
+        expr = self.expr
+        permutation = self.permutation
+        if isinstance(expr, PermuteDims):
+            subexpr = expr.expr
+            subperm = expr.permutation
+            permutation = permutation * subperm
+            expr = subexpr
+        if isinstance(expr, ArrayContraction):
+            expr, permutation = self._PermuteDims_denestarg_ArrayContraction(expr, permutation)
+        if isinstance(expr, ArrayTensorProduct):
+            expr, permutation = self._PermuteDims_denestarg_ArrayTensorProduct(expr, permutation)
+        if isinstance(expr, (ZeroArray, ZeroMatrix)):
+            return ZeroArray(*[expr.shape[i] for i in permutation.array_form])
+        plist = permutation.array_form
+        if plist == sorted(plist):
+            return expr
+        return self.func(expr, permutation, canonicalize=False)
+
+    @property
+    def expr(self):
+        return self.args[0]
+
+    @property
+    def permutation(self):
+        return self.args[1]
+
+    @classmethod
+    def _PermuteDims_denestarg_ArrayTensorProduct(cls, expr, permutation):
+        # Get the permutation in its image-form:
+        perm_image_form = _af_invert(permutation.array_form)
+        args = list(expr.args)
+        # Starting index global position for every arg:
+        cumul = list(accumulate([0] + expr.subranks))
+        # Split `perm_image_form` into a list of list corresponding to the indices
+        # of every argument:
+        perm_image_form_in_components = [perm_image_form[cumul[i]:cumul[i+1]] for i in range(len(args))]
+        # Create an index, target-position-key array:
+        ps = [(i, sorted(comp)) for i, comp in enumerate(perm_image_form_in_components)]
+        # Sort the array according to the target-position-key:
+        # In this way, we define a canonical way to sort the arguments according
+        # to the permutation.
+        ps.sort(key=lambda x: x[1])
+        # Read the inverse-permutation (i.e. image-form) of the args:
+        perm_args_image_form = [i[0] for i in ps]
+        # Apply the args-permutation to the `args`:
+        args_sorted = [args[i] for i in perm_args_image_form]
+        # Apply the args-permutation to the array-form of the permutation of the axes (of `expr`):
+        perm_image_form_sorted_args = [perm_image_form_in_components[i] for i in perm_args_image_form]
+        new_permutation = Permutation(_af_invert([j for i in perm_image_form_sorted_args for j in i]))
+        return _array_tensor_product(*args_sorted), new_permutation
+
+    @classmethod
+    def _PermuteDims_denestarg_ArrayContraction(cls, expr, permutation):
+        if not isinstance(expr, ArrayContraction):
+            return expr, permutation
+        if not isinstance(expr.expr, ArrayTensorProduct):
+            return expr, permutation
+        args = expr.expr.args
+        subranks = [get_rank(arg) for arg in expr.expr.args]
+
+        contraction_indices = expr.contraction_indices
+        contraction_indices_flat = [j for i in contraction_indices for j in i]
+        cumul = list(accumulate([0] + subranks))
+
+        # Spread the permutation in its array form across the args in the corresponding
+        # tensor-product arguments with free indices:
+        permutation_array_blocks_up = []
+        image_form = _af_invert(permutation.array_form)
+        counter = 0
+        for i in range(len(subranks)):
+            current = []
+            for j in range(cumul[i], cumul[i+1]):
+                if j in contraction_indices_flat:
+                    continue
+                current.append(image_form[counter])
+                counter += 1
+            permutation_array_blocks_up.append(current)
+
+        # Get the map of axis repositioning for every argument of tensor-product:
+        index_blocks = [list(range(cumul[i], cumul[i+1])) for i, e in enumerate(expr.subranks)]
+        index_blocks_up = expr._push_indices_up(expr.contraction_indices, index_blocks)
+        inverse_permutation = permutation**(-1)
+        index_blocks_up_permuted = [[inverse_permutation(j) for j in i if j is not None] for i in index_blocks_up]
+
+        # Sorting key is a list of tuple, first element is the index of `args`, second element of
+        # the tuple is the sorting key to sort `args` of the tensor product:
+        sorting_keys = list(enumerate(index_blocks_up_permuted))
+        sorting_keys.sort(key=lambda x: x[1])
+
+        # Now we can get the permutation acting on the args in its image-form:
+        new_perm_image_form = [i[0] for i in sorting_keys]
+        # Apply the args-level permutation to various elements:
+        new_index_blocks = [index_blocks[i] for i in new_perm_image_form]
+        new_index_perm_array_form = _af_invert([j for i in new_index_blocks for j in i])
+        new_args = [args[i] for i in new_perm_image_form]
+        new_contraction_indices = [tuple(new_index_perm_array_form[j] for j in i) for i in contraction_indices]
+        new_expr = _array_contraction(_array_tensor_product(*new_args), *new_contraction_indices)
+        new_permutation = Permutation(_af_invert([j for i in [permutation_array_blocks_up[k] for k in new_perm_image_form] for j in i]))
+        return new_expr, new_permutation
+
+    @classmethod
+    def _check_permutation_mapping(cls, expr, permutation):
+        subranks = expr.subranks
+        index2arg = [i for i, arg in enumerate(expr.args) for j in range(expr.subranks[i])]
+        permuted_indices = [permutation(i) for i in range(expr.subrank())]
+        new_args = list(expr.args)
+        arg_candidate_index = index2arg[permuted_indices[0]]
+        current_indices = []
+        new_permutation = []
+        inserted_arg_cand_indices = set()
+        for i, idx in enumerate(permuted_indices):
+            if index2arg[idx] != arg_candidate_index:
+                new_permutation.extend(current_indices)
+                current_indices = []
+                arg_candidate_index = index2arg[idx]
+            current_indices.append(idx)
+            arg_candidate_rank = subranks[arg_candidate_index]
+            if len(current_indices) == arg_candidate_rank:
+                new_permutation.extend(sorted(current_indices))
+                local_current_indices = [j - min(current_indices) for j in current_indices]
+                i1 = index2arg[i]
+                new_args[i1] = _permute_dims(new_args[i1], Permutation(local_current_indices))
+                inserted_arg_cand_indices.add(arg_candidate_index)
+                current_indices = []
+        new_permutation.extend(current_indices)
+
+        # TODO: swap args positions in order to simplify the expression:
+        # TODO: this should be in a function
+        args_positions = list(range(len(new_args)))
+        # Get possible shifts:
+        maps = {}
+        cumulative_subranks = [0] + list(accumulate(subranks))
+        for i in range(len(subranks)):
+            s = {index2arg[new_permutation[j]] for j in range(cumulative_subranks[i], cumulative_subranks[i+1])}
+            if len(s) != 1:
+                continue
+            elem = next(iter(s))
+            if i != elem:
+                maps[i] = elem
+
+        # Find cycles in the map:
+        lines = []
+        current_line = []
+        while maps:
+            if len(current_line) == 0:
+                k, v = maps.popitem()
+                current_line.append(k)
+            else:
+                k = current_line[-1]
+                if k not in maps:
+                    current_line = []
+                    continue
+                v = maps.pop(k)
+            if v in current_line:
+                lines.append(current_line)
+                current_line = []
+                continue
+            current_line.append(v)
+        for line in lines:
+            for i, e in enumerate(line):
+                args_positions[line[(i + 1) % len(line)]] = e
+
+        # TODO: function in order to permute the args:
+        permutation_blocks = [[new_permutation[cumulative_subranks[i] + j] for j in range(e)] for i, e in enumerate(subranks)]
+        new_args = [new_args[i] for i in args_positions]
+        new_permutation_blocks = [permutation_blocks[i] for i in args_positions]
+        new_permutation2 = [j for i in new_permutation_blocks for j in i]
+        return _array_tensor_product(*new_args), Permutation(new_permutation2)  # **(-1)
+
+    @classmethod
+    def _check_if_there_are_closed_cycles(cls, expr, permutation):
+        args = list(expr.args)
+        subranks = expr.subranks
+        cyclic_form = permutation.cyclic_form
+        cumulative_subranks = [0] + list(accumulate(subranks))
+        cyclic_min = [min(i) for i in cyclic_form]
+        cyclic_max = [max(i) for i in cyclic_form]
+        cyclic_keep = []
+        for i, cycle in enumerate(cyclic_form):
+            flag = True
+            for j in range(len(cumulative_subranks) - 1):
+                if cyclic_min[i] >= cumulative_subranks[j] and cyclic_max[i] < cumulative_subranks[j+1]:
+                    # Found a sinkable cycle.
+                    args[j] = _permute_dims(args[j], Permutation([[k - cumulative_subranks[j] for k in cycle]]))
+                    flag = False
+                    break
+            if flag:
+                cyclic_keep.append(cycle)
+        return _array_tensor_product(*args), Permutation(cyclic_keep, size=permutation.size)
+
+    def nest_permutation(self):
+        r"""
+        DEPRECATED.
+        """
+        ret = self._nest_permutation(self.expr, self.permutation)
+        if ret is None:
+            return self
+        return ret
+
+    @classmethod
+    def _nest_permutation(cls, expr, permutation):
+        if isinstance(expr, ArrayTensorProduct):
+            return _permute_dims(*cls._check_if_there_are_closed_cycles(expr, permutation))
+        elif isinstance(expr, ArrayContraction):
+            # Invert tree hierarchy: put the contraction above.
+            cycles = permutation.cyclic_form
+            newcycles = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *cycles)
+            newpermutation = Permutation(newcycles)
+            new_contr_indices = [tuple(newpermutation(j) for j in i) for i in expr.contraction_indices]
+            return _array_contraction(PermuteDims(expr.expr, newpermutation), *new_contr_indices)
+        elif isinstance(expr, ArrayAdd):
+            return _array_add(*[PermuteDims(arg, permutation) for arg in expr.args])
+        return None
+
+    def as_explicit(self):
+        expr = self.expr
+        if hasattr(expr, "as_explicit"):
+            expr = expr.as_explicit()
+        return permutedims(expr, self.permutation)
+
+    @classmethod
+    def _get_permutation_from_arguments(cls, permutation, index_order_old, index_order_new, dim):
+        if permutation is None:
+            if index_order_new is None or index_order_old is None:
+                raise ValueError("Permutation not defined")
+            return PermuteDims._get_permutation_from_index_orders(index_order_old, index_order_new, dim)
+        else:
+            if index_order_new is not None:
+                raise ValueError("index_order_new cannot be defined with permutation")
+            if index_order_old is not None:
+                raise ValueError("index_order_old cannot be defined with permutation")
+            return permutation
+
+    @classmethod
+    def _get_permutation_from_index_orders(cls, index_order_old, index_order_new, dim):
+        if len(set(index_order_new)) != dim:
+            raise ValueError("wrong number of indices in index_order_new")
+        if len(set(index_order_old)) != dim:
+            raise ValueError("wrong number of indices in index_order_old")
+        if len(set.symmetric_difference(set(index_order_new), set(index_order_old))) > 0:
+            raise ValueError("index_order_new and index_order_old must have the same indices")
+        permutation = [index_order_old.index(i) for i in index_order_new]
+        return permutation
+
+
+class ArrayDiagonal(_CodegenArrayAbstract):
+    r"""
+    Class to represent the diagonal operator.
+
+    Explanation
+    ===========
+
+    In a 2-dimensional array it returns the diagonal, this looks like the
+    operation:
+
+    `A_{ij} \rightarrow A_{ii}`
+
+    The diagonal over axes 1 and 2 (the second and third) of the tensor product
+    of two 2-dimensional arrays `A \otimes B` is
+
+    `\Big[ A_{ab} B_{cd} \Big]_{abcd} \rightarrow \Big[ A_{ai} B_{id} \Big]_{adi}`
+
+    In this last example the array expression has been reduced from
+    4-dimensional to 3-dimensional. Notice that no contraction has occurred,
+    rather there is a new index `i` for the diagonal, contraction would have
+    reduced the array to 2 dimensions.
+
+    Notice that the diagonalized out dimensions are added as new dimensions at
+    the end of the indices.
+    """
+
+    def __new__(cls, expr, *diagonal_indices, **kwargs):
+        expr = _sympify(expr)
+        diagonal_indices = [Tuple(*sorted(i)) for i in diagonal_indices]
+        canonicalize = kwargs.get("canonicalize", False)
+
+        shape = get_shape(expr)
+        if shape is not None:
+            cls._validate(expr, *diagonal_indices, **kwargs)
+            # Get new shape:
+            positions, shape = cls._get_positions_shape(shape, diagonal_indices)
+        else:
+            positions = None
+        if len(diagonal_indices) == 0:
+            return expr
+        obj = Basic.__new__(cls, expr, *diagonal_indices)
+        obj._positions = positions
+        obj._subranks = _get_subranks(expr)
+        obj._shape = shape
+        if canonicalize:
+            return obj._canonicalize()
+        return obj
+
+    def _canonicalize(self):
+        expr = self.expr
+        diagonal_indices = self.diagonal_indices
+        trivial_diags = [i for i in diagonal_indices if len(i) == 1]
+        if len(trivial_diags) > 0:
+            trivial_pos = {e[0]: i for i, e in enumerate(diagonal_indices) if len(e) == 1}
+            diag_pos = {e: i for i, e in enumerate(diagonal_indices) if len(e) > 1}
+            diagonal_indices_short = [i for i in diagonal_indices if len(i) > 1]
+            rank1 = get_rank(self)
+            rank2 = len(diagonal_indices)
+            rank3 = rank1 - rank2
+            inv_permutation = []
+            counter1 = 0
+            indices_down = ArrayDiagonal._push_indices_down(diagonal_indices_short, list(range(rank1)), get_rank(expr))
+            for i in indices_down:
+                if i in trivial_pos:
+                    inv_permutation.append(rank3 + trivial_pos[i])
+                elif isinstance(i, (Integer, int)):
+                    inv_permutation.append(counter1)
+                    counter1 += 1
+                else:
+                    inv_permutation.append(rank3 + diag_pos[i])
+            permutation = _af_invert(inv_permutation)
+            if len(diagonal_indices_short) > 0:
+                return _permute_dims(_array_diagonal(expr, *diagonal_indices_short), permutation)
+            else:
+                return _permute_dims(expr, permutation)
+        if isinstance(expr, ArrayAdd):
+            return self._ArrayDiagonal_denest_ArrayAdd(expr, *diagonal_indices)
+        if isinstance(expr, ArrayDiagonal):
+            return self._ArrayDiagonal_denest_ArrayDiagonal(expr, *diagonal_indices)
+        if isinstance(expr, PermuteDims):
+            return self._ArrayDiagonal_denest_PermuteDims(expr, *diagonal_indices)
+        if isinstance(expr, (ZeroArray, ZeroMatrix)):
+            positions, shape = self._get_positions_shape(expr.shape, diagonal_indices)
+            return ZeroArray(*shape)
+        return self.func(expr, *diagonal_indices, canonicalize=False)
+
+    @staticmethod
+    def _validate(expr, *diagonal_indices, **kwargs):
+        # Check that no diagonalization happens on indices with mismatched
+        # dimensions:
+        shape = get_shape(expr)
+        for i in diagonal_indices:
+            if any(j >= len(shape) for j in i):
+                raise ValueError("index is larger than expression shape")
+            if len({shape[j] for j in i}) != 1:
+                raise ValueError("diagonalizing indices of different dimensions")
+            if not kwargs.get("allow_trivial_diags", False) and len(i) <= 1:
+                raise ValueError("need at least two axes to diagonalize")
+            if len(set(i)) != len(i):
+                raise ValueError("axis index cannot be repeated")
+
+    @staticmethod
+    def _remove_trivial_dimensions(shape, *diagonal_indices):
+        return [tuple(j for j in i) for i in diagonal_indices if shape[i[0]] != 1]
+
+    @property
+    def expr(self):
+        return self.args[0]
+
+    @property
+    def diagonal_indices(self):
+        return self.args[1:]
+
+    @staticmethod
+    def _flatten(expr, *outer_diagonal_indices):
+        inner_diagonal_indices = expr.diagonal_indices
+        all_inner = [j for i in inner_diagonal_indices for j in i]
+        all_inner.sort()
+        # TODO: add API for total rank and cumulative rank:
+        total_rank = _get_subrank(expr)
+        inner_rank = len(all_inner)
+        outer_rank = total_rank - inner_rank
+        shifts = [0 for i in range(outer_rank)]
+        counter = 0
+        pointer = 0
+        for i in range(outer_rank):
+            while pointer < inner_rank and counter >= all_inner[pointer]:
+                counter += 1
+                pointer += 1
+            shifts[i] += pointer
+            counter += 1
+        outer_diagonal_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_diagonal_indices)
+        diagonal_indices = inner_diagonal_indices + outer_diagonal_indices
+        return _array_diagonal(expr.expr, *diagonal_indices)
+
+    @classmethod
+    def _ArrayDiagonal_denest_ArrayAdd(cls, expr, *diagonal_indices):
+        return _array_add(*[_array_diagonal(arg, *diagonal_indices) for arg in expr.args])
+
+    @classmethod
+    def _ArrayDiagonal_denest_ArrayDiagonal(cls, expr, *diagonal_indices):
+        return cls._flatten(expr, *diagonal_indices)
+
+    @classmethod
+    def _ArrayDiagonal_denest_PermuteDims(cls, expr: PermuteDims, *diagonal_indices):
+        back_diagonal_indices = [[expr.permutation(j) for j in i] for i in diagonal_indices]
+        nondiag = [i for i in range(get_rank(expr)) if not any(i in j for j in diagonal_indices)]
+        back_nondiag = [expr.permutation(i) for i in nondiag]
+        remap = {e: i for i, e in enumerate(sorted(back_nondiag))}
+        new_permutation1 = [remap[i] for i in back_nondiag]
+        shift = len(new_permutation1)
+        diag_block_perm = [i + shift for i in range(len(back_diagonal_indices))]
+        new_permutation = new_permutation1 + diag_block_perm
+        return _permute_dims(
+            _array_diagonal(
+                expr.expr,
+                *back_diagonal_indices
+            ),
+            new_permutation
+        )
+
+    def _push_indices_down_nonstatic(self, indices):
+        transform = lambda x: self._positions[x] if x < len(self._positions) else None
+        return _apply_recursively_over_nested_lists(transform, indices)
+
+    def _push_indices_up_nonstatic(self, indices):
+
+        def transform(x):
+            for i, e in enumerate(self._positions):
+                if (isinstance(e, int) and x == e) or (isinstance(e, tuple) and x in e):
+                    return i
+
+        return _apply_recursively_over_nested_lists(transform, indices)
+
+    @classmethod
+    def _push_indices_down(cls, diagonal_indices, indices, rank):
+        positions, shape = cls._get_positions_shape(range(rank), diagonal_indices)
+        transform = lambda x: positions[x] if x < len(positions) else None
+        return _apply_recursively_over_nested_lists(transform, indices)
+
+    @classmethod
+    def _push_indices_up(cls, diagonal_indices, indices, rank):
+        positions, shape = cls._get_positions_shape(range(rank), diagonal_indices)
+
+        def transform(x):
+            for i, e in enumerate(positions):
+                if (isinstance(e, int) and x == e) or (isinstance(e, (tuple, Tuple)) and (x in e)):
+                    return i
+
+        return _apply_recursively_over_nested_lists(transform, indices)
+
+    @classmethod
+    def _get_positions_shape(cls, shape, diagonal_indices):
+        data1 = tuple((i, shp) for i, shp in enumerate(shape) if not any(i in j for j in diagonal_indices))
+        pos1, shp1 = zip(*data1) if data1 else ((), ())
+        data2 = tuple((i, shape[i[0]]) for i in diagonal_indices)
+        pos2, shp2 = zip(*data2) if data2 else ((), ())
+        positions = pos1 + pos2
+        shape = shp1 + shp2
+        return positions, shape
+
+    def as_explicit(self):
+        expr = self.expr
+        if hasattr(expr, "as_explicit"):
+            expr = expr.as_explicit()
+        return tensordiagonal(expr, *self.diagonal_indices)
+
+
+class ArrayElementwiseApplyFunc(_CodegenArrayAbstract):
+
+    def __new__(cls, function, element):
+
+        if not isinstance(function, Lambda):
+            d = Dummy('d')
+            function = Lambda(d, function(d))
+
+        obj = _CodegenArrayAbstract.__new__(cls, function, element)
+        obj._subranks = _get_subranks(element)
+        return obj
+
+    @property
+    def function(self):
+        return self.args[0]
+
+    @property
+    def expr(self):
+        return self.args[1]
+
+    @property
+    def shape(self):
+        return self.expr.shape
+
+    def _get_function_fdiff(self):
+        d = Dummy("d")
+        function = self.function(d)
+        fdiff = function.diff(d)
+        if isinstance(fdiff, Function):
+            fdiff = type(fdiff)
+        else:
+            fdiff = Lambda(d, fdiff)
+        return fdiff
+
+    def as_explicit(self):
+        expr = self.expr
+        if hasattr(expr, "as_explicit"):
+            expr = expr.as_explicit()
+        return expr.applyfunc(self.function)
+
+
+class ArrayContraction(_CodegenArrayAbstract):
+    r"""
+    This class is meant to represent contractions of arrays in a form easily
+    processable by the code printers.
+    """
+
+    def __new__(cls, expr, *contraction_indices, **kwargs):
+        contraction_indices = _sort_contraction_indices(contraction_indices)
+        expr = _sympify(expr)
+
+        canonicalize = kwargs.get("canonicalize", False)
+
+        obj = Basic.__new__(cls, expr, *contraction_indices)
+        obj._subranks = _get_subranks(expr)
+        obj._mapping = _get_mapping_from_subranks(obj._subranks)
+
+        free_indices_to_position = {i: i for i in range(sum(obj._subranks)) if all(i not in cind for cind in contraction_indices)}
+        obj._free_indices_to_position = free_indices_to_position
+
+        shape = get_shape(expr)
+        cls._validate(expr, *contraction_indices)
+        if shape:
+            shape = tuple(shp for i, shp in enumerate(shape) if not any(i in j for j in contraction_indices))
+        obj._shape = shape
+        if canonicalize:
+            return obj._canonicalize()
+        return obj
+
+    def _canonicalize(self):
+        expr = self.expr
+        contraction_indices = self.contraction_indices
+
+        if len(contraction_indices) == 0:
+            return expr
+
+        if isinstance(expr, ArrayContraction):
+            return self._ArrayContraction_denest_ArrayContraction(expr, *contraction_indices)
+
+        if isinstance(expr, (ZeroArray, ZeroMatrix)):
+            return self._ArrayContraction_denest_ZeroArray(expr, *contraction_indices)
+
+        if isinstance(expr, PermuteDims):
+            return self._ArrayContraction_denest_PermuteDims(expr, *contraction_indices)
+
+        if isinstance(expr, ArrayTensorProduct):
+            expr, contraction_indices = self._sort_fully_contracted_args(expr, contraction_indices)
+            expr, contraction_indices = self._lower_contraction_to_addends(expr, contraction_indices)
+            if len(contraction_indices) == 0:
+                return expr
+
+        if isinstance(expr, ArrayDiagonal):
+            return self._ArrayContraction_denest_ArrayDiagonal(expr, *contraction_indices)
+
+        if isinstance(expr, ArrayAdd):
+            return self._ArrayContraction_denest_ArrayAdd(expr, *contraction_indices)
+
+        # Check single index contractions on 1-dimensional axes:
+        contraction_indices = [i for i in contraction_indices if len(i) > 1 or get_shape(expr)[i[0]] != 1]
+        if len(contraction_indices) == 0:
+            return expr
+
+        return self.func(expr, *contraction_indices, canonicalize=False)
+
+    def __mul__(self, other):
+        if other == 1:
+            return self
+        else:
+            raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.")
+
+    def __rmul__(self, other):
+        if other == 1:
+            return self
+        else:
+            raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.")
+
+    @staticmethod
+    def _validate(expr, *contraction_indices):
+        shape = get_shape(expr)
+        if shape is None:
+            return
+
+        # Check that no contraction happens when the shape is mismatched:
+        for i in contraction_indices:
+            if len({shape[j] for j in i if shape[j] != -1}) != 1:
+                raise ValueError("contracting indices of different dimensions")
+
+    @classmethod
+    def _push_indices_down(cls, contraction_indices, indices):
+        flattened_contraction_indices = [j for i in contraction_indices for j in i]
+        flattened_contraction_indices.sort()
+        transform = _build_push_indices_down_func_transformation(flattened_contraction_indices)
+        return _apply_recursively_over_nested_lists(transform, indices)
+
+    @classmethod
+    def _push_indices_up(cls, contraction_indices, indices):
+        flattened_contraction_indices = [j for i in contraction_indices for j in i]
+        flattened_contraction_indices.sort()
+        transform = _build_push_indices_up_func_transformation(flattened_contraction_indices)
+        return _apply_recursively_over_nested_lists(transform, indices)
+
+    @classmethod
+    def _lower_contraction_to_addends(cls, expr, contraction_indices):
+        if isinstance(expr, ArrayAdd):
+            raise NotImplementedError()
+        if not isinstance(expr, ArrayTensorProduct):
+            return expr, contraction_indices
+        subranks = expr.subranks
+        cumranks = list(accumulate([0] + subranks))
+        contraction_indices_remaining = []
+        contraction_indices_args = [[] for i in expr.args]
+        backshift = set()
+        for contraction_group in contraction_indices:
+            for j in range(len(expr.args)):
+                if not isinstance(expr.args[j], ArrayAdd):
+                    continue
+                if all(cumranks[j] <= k < cumranks[j+1] for k in contraction_group):
+                    contraction_indices_args[j].append([k - cumranks[j] for k in contraction_group])
+                    backshift.update(contraction_group)
+                    break
+            else:
+                contraction_indices_remaining.append(contraction_group)
+        if len(contraction_indices_remaining) == len(contraction_indices):
+            return expr, contraction_indices
+        total_rank = get_rank(expr)
+        shifts = list(accumulate([1 if i in backshift else 0 for i in range(total_rank)]))
+        contraction_indices_remaining = [Tuple.fromiter(j - shifts[j] for j in i) for i in contraction_indices_remaining]
+        ret = _array_tensor_product(*[
+            _array_contraction(arg, *contr) for arg, contr in zip(expr.args, contraction_indices_args)
+        ])
+        return ret, contraction_indices_remaining
+
+    def split_multiple_contractions(self):
+        """
+        Recognize multiple contractions and attempt at rewriting them as paired-contractions.
+
+        This allows some contractions involving more than two indices to be
+        rewritten as multiple contractions involving two indices, thus allowing
+        the expression to be rewritten as a matrix multiplication line.
+
+        Examples:
+
+        * `A_ij b_j0 C_jk` ===> `A*DiagMatrix(b)*C`
+
+        Care for:
+        - matrix being diagonalized (i.e. `A_ii`)
+        - vectors being diagonalized (i.e. `a_i0`)
+
+        Multiple contractions can be split into matrix multiplications if
+        not more than two arguments are non-diagonals or non-vectors.
+        Vectors get diagonalized while diagonal matrices remain diagonal.
+        The non-diagonal matrices can be at the beginning or at the end
+        of the final matrix multiplication line.
+        """
+
+        editor = _EditArrayContraction(self)
+
+        contraction_indices = self.contraction_indices
+
+        onearray_insert = []
+
+        for indl, links in enumerate(contraction_indices):
+            if len(links) <= 2:
+                continue
+
+            # Check multiple contractions:
+            #
+            # Examples:
+            #
+            # * `A_ij b_j0 C_jk` ===> `A*DiagMatrix(b)*C \otimes OneArray(1)` with permutation (1 2)
+            #
+            # Care for:
+            # - matrix being diagonalized (i.e. `A_ii`)
+            # - vectors being diagonalized (i.e. `a_i0`)
+
+            # Multiple contractions can be split into matrix multiplications if
+            # not more than three arguments are non-diagonals or non-vectors.
+            #
+            # Vectors get diagonalized while diagonal matrices remain diagonal.
+            # The non-diagonal matrices can be at the beginning or at the end
+            # of the final matrix multiplication line.
+
+            positions = editor.get_mapping_for_index(indl)
+
+            # Also consider the case of diagonal matrices being contracted:
+            current_dimension = self.expr.shape[links[0]]
+
+            not_vectors = []
+            vectors = []
+            for arg_ind, rel_ind in positions:
+                arg = editor.args_with_ind[arg_ind]
+                mat = arg.element
+                abs_arg_start, abs_arg_end = editor.get_absolute_range(arg)
+                other_arg_pos = 1-rel_ind
+                other_arg_abs = abs_arg_start + other_arg_pos
+                if ((1 not in mat.shape) or
+                    ((current_dimension == 1) is True and mat.shape != (1, 1)) or
+                    any(other_arg_abs in l for li, l in enumerate(contraction_indices) if li != indl)
+                ):
+                    not_vectors.append((arg, rel_ind))
+                else:
+                    vectors.append((arg, rel_ind))
+            if len(not_vectors) > 2:
+                # If more than two arguments in the multiple contraction are
+                # non-vectors and non-diagonal matrices, we cannot find a way
+                # to split this contraction into a matrix multiplication line:
+                continue
+            # Three cases to handle:
+            # - zero non-vectors
+            # - one non-vector
+            # - two non-vectors
+            for v, rel_ind in vectors:
+                v.element = diagonalize_vector(v.element)
+            vectors_to_loop = not_vectors[:1] + vectors + not_vectors[1:]
+            first_not_vector, rel_ind = vectors_to_loop[0]
+            new_index = first_not_vector.indices[rel_ind]
+
+            for v, rel_ind in vectors_to_loop[1:-1]:
+                v.indices[rel_ind] = new_index
+                new_index = editor.get_new_contraction_index()
+                assert v.indices.index(None) == 1 - rel_ind
+                v.indices[v.indices.index(None)] = new_index
+                onearray_insert.append(v)
+
+            last_vec, rel_ind = vectors_to_loop[-1]
+            last_vec.indices[rel_ind] = new_index
+
+        for v in onearray_insert:
+            editor.insert_after(v, _ArgE(OneArray(1), [None]))
+
+        return editor.to_array_contraction()
+
+    def flatten_contraction_of_diagonal(self):
+        if not isinstance(self.expr, ArrayDiagonal):
+            return self
+        contraction_down = self.expr._push_indices_down(self.expr.diagonal_indices, self.contraction_indices)
+        new_contraction_indices = []
+        diagonal_indices = self.expr.diagonal_indices[:]
+        for i in contraction_down:
+            contraction_group = list(i)
+            for j in i:
+                diagonal_with = [k for k in diagonal_indices if j in k]
+                contraction_group.extend([l for k in diagonal_with for l in k])
+                diagonal_indices = [k for k in diagonal_indices if k not in diagonal_with]
+            new_contraction_indices.append(sorted(set(contraction_group)))
+
+        new_contraction_indices = ArrayDiagonal._push_indices_up(diagonal_indices, new_contraction_indices)
+        return _array_contraction(
+            _array_diagonal(
+                self.expr.expr,
+                *diagonal_indices
+            ),
+            *new_contraction_indices
+        )
+
+    @staticmethod
+    def _get_free_indices_to_position_map(free_indices, contraction_indices):
+        free_indices_to_position = {}
+        flattened_contraction_indices = [j for i in contraction_indices for j in i]
+        counter = 0
+        for ind in free_indices:
+            while counter in flattened_contraction_indices:
+                counter += 1
+            free_indices_to_position[ind] = counter
+            counter += 1
+        return free_indices_to_position
+
+    @staticmethod
+    def _get_index_shifts(expr):
+        """
+        Get the mapping of indices at the positions before the contraction
+        occurs.
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.array import tensorproduct, tensorcontraction
+        >>> from sympy import MatrixSymbol
+        >>> M = MatrixSymbol("M", 3, 3)
+        >>> N = MatrixSymbol("N", 3, 3)
+        >>> cg = tensorcontraction(tensorproduct(M, N), [1, 2])
+        >>> cg._get_index_shifts(cg)
+        [0, 2]
+
+        Indeed, ``cg`` after the contraction has two dimensions, 0 and 1. They
+        need to be shifted by 0 and 2 to get the corresponding positions before
+        the contraction (that is, 0 and 3).
+        """
+        inner_contraction_indices = expr.contraction_indices
+        all_inner = [j for i in inner_contraction_indices for j in i]
+        all_inner.sort()
+        # TODO: add API for total rank and cumulative rank:
+        total_rank = _get_subrank(expr)
+        inner_rank = len(all_inner)
+        outer_rank = total_rank - inner_rank
+        shifts = [0 for i in range(outer_rank)]
+        counter = 0
+        pointer = 0
+        for i in range(outer_rank):
+            while pointer < inner_rank and counter >= all_inner[pointer]:
+                counter += 1
+                pointer += 1
+            shifts[i] += pointer
+            counter += 1
+        return shifts
+
+    @staticmethod
+    def _convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices):
+        shifts = ArrayContraction._get_index_shifts(expr)
+        outer_contraction_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_contraction_indices)
+        return outer_contraction_indices
+
+    @staticmethod
+    def _flatten(expr, *outer_contraction_indices):
+        inner_contraction_indices = expr.contraction_indices
+        outer_contraction_indices = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices)
+        contraction_indices = inner_contraction_indices + outer_contraction_indices
+        return _array_contraction(expr.expr, *contraction_indices)
+
+    @classmethod
+    def _ArrayContraction_denest_ArrayContraction(cls, expr, *contraction_indices):
+        return cls._flatten(expr, *contraction_indices)
+
+    @classmethod
+    def _ArrayContraction_denest_ZeroArray(cls, expr, *contraction_indices):
+        contraction_indices_flat = [j for i in contraction_indices for j in i]
+        shape = [e for i, e in enumerate(expr.shape) if i not in contraction_indices_flat]
+        return ZeroArray(*shape)
+
+    @classmethod
+    def _ArrayContraction_denest_ArrayAdd(cls, expr, *contraction_indices):
+        return _array_add(*[_array_contraction(i, *contraction_indices) for i in expr.args])
+
+    @classmethod
+    def _ArrayContraction_denest_PermuteDims(cls, expr, *contraction_indices):
+        permutation = expr.permutation
+        plist = permutation.array_form
+        new_contraction_indices = [tuple(permutation(j) for j in i) for i in contraction_indices]
+        new_plist = [i for i in plist if not any(i in j for j in new_contraction_indices)]
+        new_plist = cls._push_indices_up(new_contraction_indices, new_plist)
+        return _permute_dims(
+            _array_contraction(expr.expr, *new_contraction_indices),
+            Permutation(new_plist)
+        )
+
+    @classmethod
+    def _ArrayContraction_denest_ArrayDiagonal(cls, expr: 'ArrayDiagonal', *contraction_indices):
+        diagonal_indices = list(expr.diagonal_indices)
+        down_contraction_indices = expr._push_indices_down(expr.diagonal_indices, contraction_indices, get_rank(expr.expr))
+        # Flatten diagonally contracted indices:
+        down_contraction_indices = [[k for j in i for k in (j if isinstance(j, (tuple, Tuple)) else [j])] for i in down_contraction_indices]
+        new_contraction_indices = []
+        for contr_indgrp in down_contraction_indices:
+            ind = contr_indgrp[:]
+            for j, diag_indgrp in enumerate(diagonal_indices):
+                if diag_indgrp is None:
+                    continue
+                if any(i in diag_indgrp for i in contr_indgrp):
+                    ind.extend(diag_indgrp)
+                    diagonal_indices[j] = None
+            new_contraction_indices.append(sorted(set(ind)))
+
+        new_diagonal_indices_down = [i for i in diagonal_indices if i is not None]
+        new_diagonal_indices = ArrayContraction._push_indices_up(new_contraction_indices, new_diagonal_indices_down)
+        return _array_diagonal(
+            _array_contraction(expr.expr, *new_contraction_indices),
+            *new_diagonal_indices
+        )
+
+    @classmethod
+    def _sort_fully_contracted_args(cls, expr, contraction_indices):
+        if expr.shape is None:
+            return expr, contraction_indices
+        cumul = list(accumulate([0] + expr.subranks))
+        index_blocks = [list(range(cumul[i], cumul[i+1])) for i in range(len(expr.args))]
+        contraction_indices_flat = {j for i in contraction_indices for j in i}
+        fully_contracted = [all(j in contraction_indices_flat for j in range(cumul[i], cumul[i+1])) for i, arg in enumerate(expr.args)]
+        new_pos = sorted(range(len(expr.args)), key=lambda x: (0, default_sort_key(expr.args[x])) if fully_contracted[x] else (1,))
+        new_args = [expr.args[i] for i in new_pos]
+        new_index_blocks_flat = [j for i in new_pos for j in index_blocks[i]]
+        index_permutation_array_form = _af_invert(new_index_blocks_flat)
+        new_contraction_indices = [tuple(index_permutation_array_form[j] for j in i) for i in contraction_indices]
+        new_contraction_indices = _sort_contraction_indices(new_contraction_indices)
+        return _array_tensor_product(*new_args), new_contraction_indices
+
+    def _get_contraction_tuples(self):
+        r"""
+        Return tuples containing the argument index and position within the
+        argument of the index position.
+
+        Examples
+        ========
+
+        >>> from sympy import MatrixSymbol
+        >>> from sympy.abc import N
+        >>> from sympy.tensor.array import tensorproduct, tensorcontraction
+        >>> A = MatrixSymbol("A", N, N)
+        >>> B = MatrixSymbol("B", N, N)
+
+        >>> cg = tensorcontraction(tensorproduct(A, B), (1, 2))
+        >>> cg._get_contraction_tuples()
+        [[(0, 1), (1, 0)]]
+
+        Notes
+        =====
+
+        Here the contraction pair `(1, 2)` meaning that the 2nd and 3rd indices
+        of the tensor product `A\otimes B` are contracted, has been transformed
+        into `(0, 1)` and `(1, 0)`, identifying the same indices in a different
+        notation. `(0, 1)` is the second index (1) of the first argument (i.e.
+                0 or `A`). `(1, 0)` is the first index (i.e. 0) of the second
+        argument (i.e. 1 or `B`).
+        """
+        mapping = self._mapping
+        return [[mapping[j] for j in i] for i in self.contraction_indices]
+
+    @staticmethod
+    def _contraction_tuples_to_contraction_indices(expr, contraction_tuples):
+        # TODO: check that `expr` has `.subranks`:
+        ranks = expr.subranks
+        cumulative_ranks = [0] + list(accumulate(ranks))
+        return [tuple(cumulative_ranks[j]+k for j, k in i) for i in contraction_tuples]
+
+    @property
+    def free_indices(self):
+        return self._free_indices[:]
+
+    @property
+    def free_indices_to_position(self):
+        return dict(self._free_indices_to_position)
+
+    @property
+    def expr(self):
+        return self.args[0]
+
+    @property
+    def contraction_indices(self):
+        return self.args[1:]
+
+    def _contraction_indices_to_components(self):
+        expr = self.expr
+        if not isinstance(expr, ArrayTensorProduct):
+            raise NotImplementedError("only for contractions of tensor products")
+        ranks = expr.subranks
+        mapping = {}
+        counter = 0
+        for i, rank in enumerate(ranks):
+            for j in range(rank):
+                mapping[counter] = (i, j)
+                counter += 1
+        return mapping
+
+    def sort_args_by_name(self):
+        """
+        Sort arguments in the tensor product so that their order is lexicographical.
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
+        >>> from sympy import MatrixSymbol
+        >>> from sympy.abc import N
+        >>> A = MatrixSymbol("A", N, N)
+        >>> B = MatrixSymbol("B", N, N)
+        >>> C = MatrixSymbol("C", N, N)
+        >>> D = MatrixSymbol("D", N, N)
+
+        >>> cg = convert_matrix_to_array(C*D*A*B)
+        >>> cg
+        ArrayContraction(ArrayTensorProduct(A, D, C, B), (0, 3), (1, 6), (2, 5))
+        >>> cg.sort_args_by_name()
+        ArrayContraction(ArrayTensorProduct(A, D, B, C), (0, 3), (1, 4), (2, 7))
+        """
+        expr = self.expr
+        if not isinstance(expr, ArrayTensorProduct):
+            return self
+        args = expr.args
+        sorted_data = sorted(enumerate(args), key=lambda x: default_sort_key(x[1]))
+        pos_sorted, args_sorted = zip(*sorted_data)
+        reordering_map = {i: pos_sorted.index(i) for i, arg in enumerate(args)}
+        contraction_tuples = self._get_contraction_tuples()
+        contraction_tuples = [[(reordering_map[j], k) for j, k in i] for i in contraction_tuples]
+        c_tp = _array_tensor_product(*args_sorted)
+        new_contr_indices = self._contraction_tuples_to_contraction_indices(
+                c_tp,
+                contraction_tuples
+        )
+        return _array_contraction(c_tp, *new_contr_indices)
+
+    def _get_contraction_links(self):
+        r"""
+        Returns a dictionary of links between arguments in the tensor product
+        being contracted.
+
+        See the example for an explanation of the values.
+
+        Examples
+        ========
+
+        >>> from sympy import MatrixSymbol
+        >>> from sympy.abc import N
+        >>> from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
+        >>> A = MatrixSymbol("A", N, N)
+        >>> B = MatrixSymbol("B", N, N)
+        >>> C = MatrixSymbol("C", N, N)
+        >>> D = MatrixSymbol("D", N, N)
+
+        Matrix multiplications are pairwise contractions between neighboring
+        matrices:
+
+        `A_{ij} B_{jk} C_{kl} D_{lm}`
+
+        >>> cg = convert_matrix_to_array(A*B*C*D)
+        >>> cg
+        ArrayContraction(ArrayTensorProduct(B, C, A, D), (0, 5), (1, 2), (3, 6))
+
+        >>> cg._get_contraction_links()
+        {0: {0: (2, 1), 1: (1, 0)}, 1: {0: (0, 1), 1: (3, 0)}, 2: {1: (0, 0)}, 3: {0: (1, 1)}}
+
+        This dictionary is interpreted as follows: argument in position 0 (i.e.
+        matrix `A`) has its second index (i.e. 1) contracted to `(1, 0)`, that
+        is argument in position 1 (matrix `B`) on the first index slot of `B`,
+        this is the contraction provided by the index `j` from `A`.
+
+        The argument in position 1 (that is, matrix `B`) has two contractions,
+        the ones provided by the indices `j` and `k`, respectively the first
+        and second indices (0 and 1 in the sub-dict).  The link `(0, 1)` and
+        `(2, 0)` respectively. `(0, 1)` is the index slot 1 (the 2nd) of
+        argument in position 0 (that is, `A_{\ldot j}`), and so on.
+        """
+        args, dlinks = _get_contraction_links([self], self.subranks, *self.contraction_indices)
+        return dlinks
+
+    def as_explicit(self):
+        expr = self.expr
+        if hasattr(expr, "as_explicit"):
+            expr = expr.as_explicit()
+        return tensorcontraction(expr, *self.contraction_indices)
+
+
+class Reshape(_CodegenArrayAbstract):
+    """
+    Reshape the dimensions of an array expression.
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.array.expressions import ArraySymbol, Reshape
+    >>> A = ArraySymbol("A", (6,))
+    >>> A.shape
+    (6,)
+    >>> Reshape(A, (3, 2)).shape
+    (3, 2)
+
+    Check the component-explicit forms:
+
+    >>> A.as_explicit()
+    [A[0], A[1], A[2], A[3], A[4], A[5]]
+    >>> Reshape(A, (3, 2)).as_explicit()
+    [[A[0], A[1]], [A[2], A[3]], [A[4], A[5]]]
+
+    """
+
+    def __new__(cls, expr, shape):
+        expr = _sympify(expr)
+        if not isinstance(shape, Tuple):
+            shape = Tuple(*shape)
+        if Equality(Mul.fromiter(expr.shape), Mul.fromiter(shape)) == False:
+            raise ValueError("shape mismatch")
+        obj = Expr.__new__(cls, expr, shape)
+        obj._shape = tuple(shape)
+        obj._expr = expr
+        return obj
+
+    @property
+    def shape(self):
+        return self._shape
+
+    @property
+    def expr(self):
+        return self._expr
+
+    def doit(self, *args, **kwargs):
+        if kwargs.get("deep", True):
+            expr = self.expr.doit(*args, **kwargs)
+        else:
+            expr = self.expr
+        if isinstance(expr, (MatrixBase, NDimArray)):
+            return expr.reshape(*self.shape)
+        return Reshape(expr, self.shape)
+
+    def as_explicit(self):
+        ee = self.expr
+        if hasattr(ee, "as_explicit"):
+            ee = ee.as_explicit()
+        if isinstance(ee, MatrixBase):
+            from sympy import Array
+            ee = Array(ee)
+        elif isinstance(ee, MatrixExpr):
+            return self
+        return ee.reshape(*self.shape)
+
+
+class _ArgE:
+    """
+    The ``_ArgE`` object contains references to the array expression
+    (``.element``) and a list containing the information about index
+    contractions (``.indices``).
+
+    Index contractions are numbered and contracted indices show the number of
+    the contraction. Uncontracted indices have ``None`` value.
+
+    For example:
+    ``_ArgE(M, [None, 3])``
+    This object means that expression ``M`` is part of an array contraction
+    and has two indices, the first is not contracted (value ``None``),
+    the second index is contracted to the 4th (i.e. number ``3``) group of the
+    array contraction object.
+    """
+    indices: list[int | None]
+
+    def __init__(self, element, indices: list[int | None] | None = None):
+        self.element = element
+        if indices is None:
+            self.indices = [None for i in range(get_rank(element))]
+        else:
+            self.indices = indices
+
+    def __str__(self):
+        return "_ArgE(%s, %s)" % (self.element, self.indices)
+
+    __repr__ = __str__
+
+
+class _IndPos:
+    """
+    Index position, requiring two integers in the constructor:
+
+    - arg: the position of the argument in the tensor product,
+    - rel: the relative position of the index inside the argument.
+    """
+    def __init__(self, arg: int, rel: int):
+        self.arg = arg
+        self.rel = rel
+
+    def __str__(self):
+        return "_IndPos(%i, %i)" % (self.arg, self.rel)
+
+    __repr__ = __str__
+
+    def __iter__(self):
+        yield from [self.arg, self.rel]
+
+
+class _EditArrayContraction:
+    """
+    Utility class to help manipulate array contraction objects.
+
+    This class takes as input an ``ArrayContraction`` object and turns it into
+    an editable object.
+
+    The field ``args_with_ind`` of this class is a list of ``_ArgE`` objects
+    which can be used to easily edit the contraction structure of the
+    expression.
+
+    Once editing is finished, the ``ArrayContraction`` object may be recreated
+    by calling the ``.to_array_contraction()`` method.
+    """
+
+    def __init__(self, base_array: typing.Union[ArrayContraction, ArrayDiagonal, ArrayTensorProduct]):
+
+        expr: Basic
+        diagonalized: tuple[tuple[int, ...], ...]
+        contraction_indices: list[tuple[int]]
+        if isinstance(base_array, ArrayContraction):
+            mapping = _get_mapping_from_subranks(base_array.subranks)
+            expr = base_array.expr
+            contraction_indices = base_array.contraction_indices
+            diagonalized = ()
+        elif isinstance(base_array, ArrayDiagonal):
+
+            if isinstance(base_array.expr, ArrayContraction):
+                mapping = _get_mapping_from_subranks(base_array.expr.subranks)
+                expr = base_array.expr.expr
+                diagonalized = ArrayContraction._push_indices_down(base_array.expr.contraction_indices, base_array.diagonal_indices)
+                contraction_indices = base_array.expr.contraction_indices
+            elif isinstance(base_array.expr, ArrayTensorProduct):
+                mapping = {}
+                expr = base_array.expr
+                diagonalized = base_array.diagonal_indices
+                contraction_indices = []
+            else:
+                mapping = {}
+                expr = base_array.expr
+                diagonalized = base_array.diagonal_indices
+                contraction_indices = []
+
+        elif isinstance(base_array, ArrayTensorProduct):
+            expr = base_array
+            contraction_indices = []
+            diagonalized = ()
+        else:
+            raise NotImplementedError()
+
+        if isinstance(expr, ArrayTensorProduct):
+            args = list(expr.args)
+        else:
+            args = [expr]
+
+        args_with_ind: list[_ArgE] = [_ArgE(arg) for arg in args]
+        for i, contraction_tuple in enumerate(contraction_indices):
+            for j in contraction_tuple:
+                arg_pos, rel_pos = mapping[j]
+                args_with_ind[arg_pos].indices[rel_pos] = i
+        self.args_with_ind: list[_ArgE] = args_with_ind
+        self.number_of_contraction_indices: int = len(contraction_indices)
+        self._track_permutation: list[list[int]] | None = None
+
+        mapping = _get_mapping_from_subranks(base_array.subranks)
+
+        # Trick: add diagonalized indices as negative indices into the editor object:
+        for i, e in enumerate(diagonalized):
+            for j in e:
+                arg_pos, rel_pos = mapping[j]
+                self.args_with_ind[arg_pos].indices[rel_pos] = -1 - i
+
+    def insert_after(self, arg: _ArgE, new_arg: _ArgE):
+        pos = self.args_with_ind.index(arg)
+        self.args_with_ind.insert(pos + 1, new_arg)
+
+    def get_new_contraction_index(self):
+        self.number_of_contraction_indices += 1
+        return self.number_of_contraction_indices - 1
+
+    def refresh_indices(self):
+        updates = {}
+        for arg_with_ind in self.args_with_ind:
+            updates.update({i: -1 for i in arg_with_ind.indices if i is not None})
+        for i, e in enumerate(sorted(updates)):
+            updates[e] = i
+        self.number_of_contraction_indices = len(updates)
+        for arg_with_ind in self.args_with_ind:
+            arg_with_ind.indices = [updates.get(i, None) for i in arg_with_ind.indices]
+
+    def merge_scalars(self):
+        scalars = []
+        for arg_with_ind in self.args_with_ind:
+            if len(arg_with_ind.indices) == 0:
+                scalars.append(arg_with_ind)
+        for i in scalars:
+            self.args_with_ind.remove(i)
+        scalar = Mul.fromiter([i.element for i in scalars])
+        if len(self.args_with_ind) == 0:
+            self.args_with_ind.append(_ArgE(scalar))
+        else:
+            from sympy.tensor.array.expressions.from_array_to_matrix import _a2m_tensor_product
+            self.args_with_ind[0].element = _a2m_tensor_product(scalar, self.args_with_ind[0].element)
+
+    def to_array_contraction(self):
+
+        # Count the ranks of the arguments:
+        counter = 0
+        # Create a collector for the new diagonal indices:
+        diag_indices = defaultdict(list)
+
+        count_index_freq = Counter()
+        for arg_with_ind in self.args_with_ind:
+            count_index_freq.update(Counter(arg_with_ind.indices))
+
+        free_index_count = count_index_freq[None]
+
+        # Construct the inverse permutation:
+        inv_perm1 = []
+        inv_perm2 = []
+        # Keep track of which diagonal indices have already been processed:
+        done = set()
+
+        # Counter for the diagonal indices:
+        counter4 = 0
+
+        for arg_with_ind in self.args_with_ind:
+            # If some diagonalization axes have been removed, they should be
+            # permuted in order to keep the permutation.
+            # Add permutation here
+            counter2 = 0  # counter for the indices
+            for i in arg_with_ind.indices:
+                if i is None:
+                    inv_perm1.append(counter4)
+                    counter2 += 1
+                    counter4 += 1
+                    continue
+                if i >= 0:
+                    continue
+                # Reconstruct the diagonal indices:
+                diag_indices[-1 - i].append(counter + counter2)
+                if count_index_freq[i] == 1 and i not in done:
+                    inv_perm1.append(free_index_count - 1 - i)
+                    done.add(i)
+                elif i not in done:
+                    inv_perm2.append(free_index_count - 1 - i)
+                    done.add(i)
+                counter2 += 1
+            # Remove negative indices to restore a proper editor object:
+            arg_with_ind.indices = [i if i is not None and i >= 0 else None for i in arg_with_ind.indices]
+            counter += len([i for i in arg_with_ind.indices if i is None or i < 0])
+
+        inverse_permutation = inv_perm1 + inv_perm2
+        permutation = _af_invert(inverse_permutation)
+
+        # Get the diagonal indices after the detection of HadamardProduct in the expression:
+        diag_indices_filtered = [tuple(v) for v in diag_indices.values() if len(v) > 1]
+
+        self.merge_scalars()
+        self.refresh_indices()
+        args = [arg.element for arg in self.args_with_ind]
+        contraction_indices = self.get_contraction_indices()
+        expr = _array_contraction(_array_tensor_product(*args), *contraction_indices)
+        expr2 = _array_diagonal(expr, *diag_indices_filtered)
+        if self._track_permutation is not None:
+            permutation2 = _af_invert([j for i in self._track_permutation for j in i])
+            expr2 = _permute_dims(expr2, permutation2)
+
+        expr3 = _permute_dims(expr2, permutation)
+        return expr3
+
+    def get_contraction_indices(self) -> list[list[int]]:
+        contraction_indices: list[list[int]] = [[] for i in range(self.number_of_contraction_indices)]
+        current_position: int = 0
+        for arg_with_ind in self.args_with_ind:
+            for j in arg_with_ind.indices:
+                if j is not None:
+                    contraction_indices[j].append(current_position)
+                current_position += 1
+        return contraction_indices
+
+    def get_mapping_for_index(self, ind) -> list[_IndPos]:
+        if ind >= self.number_of_contraction_indices:
+            raise ValueError("index value exceeding the index range")
+        positions: list[_IndPos] = []
+        for i, arg_with_ind in enumerate(self.args_with_ind):
+            for j, arg_ind in enumerate(arg_with_ind.indices):
+                if ind == arg_ind:
+                    positions.append(_IndPos(i, j))
+        return positions
+
+    def get_contraction_indices_to_ind_rel_pos(self) -> list[list[_IndPos]]:
+        contraction_indices: list[list[_IndPos]] = [[] for i in range(self.number_of_contraction_indices)]
+        for i, arg_with_ind in enumerate(self.args_with_ind):
+            for j, ind in enumerate(arg_with_ind.indices):
+                if ind is not None:
+                    contraction_indices[ind].append(_IndPos(i, j))
+        return contraction_indices
+
+    def count_args_with_index(self, index: int) -> int:
+        """
+        Count the number of arguments that have the given index.
+        """
+        counter: int = 0
+        for arg_with_ind in self.args_with_ind:
+            if index in arg_with_ind.indices:
+                counter += 1
+        return counter
+
+    def get_args_with_index(self, index: int) -> list[_ArgE]:
+        """
+        Get a list of arguments having the given index.
+        """
+        ret: list[_ArgE] = [i for i in self.args_with_ind if index in i.indices]
+        return ret
+
+    @property
+    def number_of_diagonal_indices(self):
+        data = set()
+        for arg in self.args_with_ind:
+            data.update({i for i in arg.indices if i is not None and i < 0})
+        return len(data)
+
+    def track_permutation_start(self):
+        permutation = []
+        perm_diag = []
+        counter = 0
+        counter2 = -1
+        for arg_with_ind in self.args_with_ind:
+            perm = []
+            for i in arg_with_ind.indices:
+                if i is not None:
+                    if i < 0:
+                        perm_diag.append(counter2)
+                        counter2 -= 1
+                    continue
+                perm.append(counter)
+                counter += 1
+            permutation.append(perm)
+        max_ind = max(max(i) if i else -1 for i in permutation) if permutation else -1
+        perm_diag = [max_ind - i for i in perm_diag]
+        self._track_permutation = permutation + [perm_diag]
+
+    def track_permutation_merge(self, destination: _ArgE, from_element: _ArgE):
+        index_destination = self.args_with_ind.index(destination)
+        index_element = self.args_with_ind.index(from_element)
+        self._track_permutation[index_destination].extend(self._track_permutation[index_element]) # type: ignore
+        self._track_permutation.pop(index_element) # type: ignore
+
+    def get_absolute_free_range(self, arg: _ArgE) -> typing.Tuple[int, int]:
+        """
+        Return the range of the free indices of the arg as absolute positions
+        among all free indices.
+        """
+        counter = 0
+        for arg_with_ind in self.args_with_ind:
+            number_free_indices = len([i for i in arg_with_ind.indices if i is None])
+            if arg_with_ind == arg:
+                return counter, counter + number_free_indices
+            counter += number_free_indices
+        raise IndexError("argument not found")
+
+    def get_absolute_range(self, arg: _ArgE) -> typing.Tuple[int, int]:
+        """
+        Return the absolute range of indices for arg, disregarding dummy
+        indices.
+        """
+        counter = 0
+        for arg_with_ind in self.args_with_ind:
+            number_indices = len(arg_with_ind.indices)
+            if arg_with_ind == arg:
+                return counter, counter + number_indices
+            counter += number_indices
+        raise IndexError("argument not found")
+
+
+def get_rank(expr):
+    if isinstance(expr, (MatrixExpr, MatrixElement)):
+        return 2
+    if isinstance(expr, _CodegenArrayAbstract):
+        return len(expr.shape)
+    if isinstance(expr, NDimArray):
+        return expr.rank()
+    if isinstance(expr, Indexed):
+        return expr.rank
+    if isinstance(expr, IndexedBase):
+        shape = expr.shape
+        if shape is None:
+            return -1
+        else:
+            return len(shape)
+    if hasattr(expr, "shape"):
+        return len(expr.shape)
+    return 0
+
+
+def _get_subrank(expr):
+    if isinstance(expr, _CodegenArrayAbstract):
+        return expr.subrank()
+    return get_rank(expr)
+
+
+def _get_subranks(expr):
+    if isinstance(expr, _CodegenArrayAbstract):
+        return expr.subranks
+    else:
+        return [get_rank(expr)]
+
+
+def get_shape(expr):
+    if hasattr(expr, "shape"):
+        return expr.shape
+    return ()
+
+
+def nest_permutation(expr):
+    if isinstance(expr, PermuteDims):
+        return expr.nest_permutation()
+    else:
+        return expr
+
+
+def _array_tensor_product(*args, **kwargs):
+    return ArrayTensorProduct(*args, canonicalize=True, **kwargs)
+
+
+def _array_contraction(expr, *contraction_indices, **kwargs):
+    return ArrayContraction(expr, *contraction_indices, canonicalize=True, **kwargs)
+
+
+def _array_diagonal(expr, *diagonal_indices, **kwargs):
+    return ArrayDiagonal(expr, *diagonal_indices, canonicalize=True, **kwargs)
+
+
+def _permute_dims(expr, permutation, **kwargs):
+    return PermuteDims(expr, permutation, canonicalize=True, **kwargs)
+
+
+def _array_add(*args, **kwargs):
+    return ArrayAdd(*args, canonicalize=True, **kwargs)
+
+
+def _get_array_element_or_slice(expr, indices):
+    return ArrayElement(expr, indices)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/arrayexpr_derivatives.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/arrayexpr_derivatives.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab44a6fbf715ac7f2b8c287dcc84a49289f2dd76
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/arrayexpr_derivatives.py
@@ -0,0 +1,194 @@
+import operator
+from functools import reduce, singledispatch
+
+from sympy.core.expr import Expr
+from sympy.core.singleton import S
+from sympy.matrices.expressions.hadamard import HadamardProduct
+from sympy.matrices.expressions.inverse import Inverse
+from sympy.matrices.expressions.matexpr import (MatrixExpr, MatrixSymbol)
+from sympy.matrices.expressions.special import Identity, OneMatrix
+from sympy.matrices.expressions.transpose import Transpose
+from sympy.combinatorics.permutations import _af_invert
+from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
+from sympy.tensor.array.expressions.array_expressions import (
+    _ArrayExpr, ZeroArray, ArraySymbol, ArrayTensorProduct, ArrayAdd,
+    PermuteDims, ArrayDiagonal, ArrayElementwiseApplyFunc, get_rank,
+    get_shape, ArrayContraction, _array_tensor_product, _array_contraction,
+    _array_diagonal, _array_add, _permute_dims, Reshape)
+from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
+
+
+@singledispatch
+def array_derive(expr, x):
+    """
+    Derivatives (gradients) for array expressions.
+    """
+    raise NotImplementedError(f"not implemented for type {type(expr)}")
+
+
+@array_derive.register(Expr)
+def _(expr: Expr, x: _ArrayExpr):
+    return ZeroArray(*x.shape)
+
+
+@array_derive.register(ArrayTensorProduct)
+def _(expr: ArrayTensorProduct, x: Expr):
+    args = expr.args
+    addend_list = []
+    for i, arg in enumerate(expr.args):
+        darg = array_derive(arg, x)
+        if darg == 0:
+            continue
+        args_prev = args[:i]
+        args_succ = args[i+1:]
+        shape_prev = reduce(operator.add, map(get_shape, args_prev), ())
+        shape_succ = reduce(operator.add, map(get_shape, args_succ), ())
+        addend = _array_tensor_product(*args_prev, darg, *args_succ)
+        tot1 = len(get_shape(x))
+        tot2 = tot1 + len(shape_prev)
+        tot3 = tot2 + len(get_shape(arg))
+        tot4 = tot3 + len(shape_succ)
+        perm = list(range(tot1, tot2)) + \
+               list(range(tot1)) + list(range(tot2, tot3)) + \
+               list(range(tot3, tot4))
+        addend = _permute_dims(addend, _af_invert(perm))
+        addend_list.append(addend)
+    if len(addend_list) == 1:
+        return addend_list[0]
+    elif len(addend_list) == 0:
+        return S.Zero
+    else:
+        return _array_add(*addend_list)
+
+
+@array_derive.register(ArraySymbol)
+def _(expr: ArraySymbol, x: _ArrayExpr):
+    if expr == x:
+        return _permute_dims(
+            ArrayTensorProduct.fromiter(Identity(i) for i in expr.shape),
+            [2*i for i in range(len(expr.shape))] + [2*i+1 for i in range(len(expr.shape))]
+        )
+    return ZeroArray(*(x.shape + expr.shape))
+
+
+@array_derive.register(MatrixSymbol)
+def _(expr: MatrixSymbol, x: _ArrayExpr):
+    m, n = expr.shape
+    if expr == x:
+        return _permute_dims(
+            _array_tensor_product(Identity(m), Identity(n)),
+            [0, 2, 1, 3]
+        )
+    return ZeroArray(*(x.shape + expr.shape))
+
+
+@array_derive.register(Identity)
+def _(expr: Identity, x: _ArrayExpr):
+    return ZeroArray(*(x.shape + expr.shape))
+
+
+@array_derive.register(OneMatrix)
+def _(expr: OneMatrix, x: _ArrayExpr):
+    return ZeroArray(*(x.shape + expr.shape))
+
+
+@array_derive.register(Transpose)
+def _(expr: Transpose, x: Expr):
+    # D(A.T, A) ==> (m,n,i,j) ==> D(A_ji, A_mn) = d_mj d_ni
+    # D(B.T, A) ==> (m,n,i,j) ==> D(B_ji, A_mn)
+    fd = array_derive(expr.arg, x)
+    return _permute_dims(fd, [0, 1, 3, 2])
+
+
+@array_derive.register(Inverse)
+def _(expr: Inverse, x: Expr):
+    mat = expr.I
+    dexpr = array_derive(mat, x)
+    tp = _array_tensor_product(-expr, dexpr, expr)
+    mp = _array_contraction(tp, (1, 4), (5, 6))
+    pp = _permute_dims(mp, [1, 2, 0, 3])
+    return pp
+
+
+@array_derive.register(ElementwiseApplyFunction)
+def _(expr: ElementwiseApplyFunction, x: Expr):
+    assert get_rank(expr) == 2
+    assert get_rank(x) == 2
+    fdiff = expr._get_function_fdiff()
+    dexpr = array_derive(expr.expr, x)
+    tp = _array_tensor_product(
+        ElementwiseApplyFunction(fdiff, expr.expr),
+        dexpr
+    )
+    td = _array_diagonal(
+        tp, (0, 4), (1, 5)
+    )
+    return td
+
+
+@array_derive.register(ArrayElementwiseApplyFunc)
+def _(expr: ArrayElementwiseApplyFunc, x: Expr):
+    fdiff = expr._get_function_fdiff()
+    subexpr = expr.expr
+    dsubexpr = array_derive(subexpr, x)
+    tp = _array_tensor_product(
+        dsubexpr,
+        ArrayElementwiseApplyFunc(fdiff, subexpr)
+    )
+    b = get_rank(x)
+    c = get_rank(expr)
+    diag_indices = [(b + i, b + c + i) for i in range(c)]
+    return _array_diagonal(tp, *diag_indices)
+
+
+@array_derive.register(MatrixExpr)
+def _(expr: MatrixExpr, x: Expr):
+    cg = convert_matrix_to_array(expr)
+    return array_derive(cg, x)
+
+
+@array_derive.register(HadamardProduct)
+def _(expr: HadamardProduct, x: Expr):
+    raise NotImplementedError()
+
+
+@array_derive.register(ArrayContraction)
+def _(expr: ArrayContraction, x: Expr):
+    fd = array_derive(expr.expr, x)
+    rank_x = len(get_shape(x))
+    contraction_indices = expr.contraction_indices
+    new_contraction_indices = [tuple(j + rank_x for j in i) for i in contraction_indices]
+    return _array_contraction(fd, *new_contraction_indices)
+
+
+@array_derive.register(ArrayDiagonal)
+def _(expr: ArrayDiagonal, x: Expr):
+    dsubexpr = array_derive(expr.expr, x)
+    rank_x = len(get_shape(x))
+    diag_indices = [[j + rank_x for j in i] for i in expr.diagonal_indices]
+    return _array_diagonal(dsubexpr, *diag_indices)
+
+
+@array_derive.register(ArrayAdd)
+def _(expr: ArrayAdd, x: Expr):
+    return _array_add(*[array_derive(arg, x) for arg in expr.args])
+
+
+@array_derive.register(PermuteDims)
+def _(expr: PermuteDims, x: Expr):
+    de = array_derive(expr.expr, x)
+    perm = [0, 1] + [i + 2 for i in expr.permutation.array_form]
+    return _permute_dims(de, perm)
+
+
+@array_derive.register(Reshape)
+def _(expr: Reshape, x: Expr):
+    de = array_derive(expr.expr, x)
+    return Reshape(de, get_shape(x) + expr.shape)
+
+
+def matrix_derive(expr, x):
+    from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
+    ce = convert_matrix_to_array(expr)
+    dce = array_derive(ce, x)
+    return convert_array_to_matrix(dce).doit()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/conv_array_to_indexed.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/conv_array_to_indexed.py
new file mode 100644
index 0000000000000000000000000000000000000000..1929c3401e131cca0a83080131ead9198b37bcbb
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/conv_array_to_indexed.py
@@ -0,0 +1,12 @@
+from sympy.tensor.array.expressions import from_array_to_indexed
+from sympy.utilities.decorator import deprecated
+
+
+_conv_to_from_decorator = deprecated(
+    "module has been renamed by replacing 'conv_' with 'from_' in its name",
+    deprecated_since_version="1.11",
+    active_deprecations_target="deprecated-conv-array-expr-module-names",
+)
+
+
+convert_array_to_indexed = _conv_to_from_decorator(from_array_to_indexed.convert_array_to_indexed)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/conv_array_to_matrix.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/conv_array_to_matrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..2708e74aaa98d6ee38eae46d97d4483a546e0776
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/conv_array_to_matrix.py
@@ -0,0 +1,6 @@
+from sympy.tensor.array.expressions import from_array_to_matrix
+from sympy.tensor.array.expressions.conv_array_to_indexed import _conv_to_from_decorator
+
+convert_array_to_matrix = _conv_to_from_decorator(from_array_to_matrix.convert_array_to_matrix)
+_array2matrix = _conv_to_from_decorator(from_array_to_matrix._array2matrix)
+_remove_trivial_dims = _conv_to_from_decorator(from_array_to_matrix._remove_trivial_dims)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/conv_indexed_to_array.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/conv_indexed_to_array.py
new file mode 100644
index 0000000000000000000000000000000000000000..6058b31f20778834ea23a01553d594b7965eb6bb
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/conv_indexed_to_array.py
@@ -0,0 +1,4 @@
+from sympy.tensor.array.expressions import from_indexed_to_array
+from sympy.tensor.array.expressions.conv_array_to_indexed import _conv_to_from_decorator
+
+convert_indexed_to_array = _conv_to_from_decorator(from_indexed_to_array.convert_indexed_to_array)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/conv_matrix_to_array.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/conv_matrix_to_array.py
new file mode 100644
index 0000000000000000000000000000000000000000..46469df60703c237527c0b2834235309640afe7c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/conv_matrix_to_array.py
@@ -0,0 +1,4 @@
+from sympy.tensor.array.expressions import from_matrix_to_array
+from sympy.tensor.array.expressions.conv_array_to_indexed import _conv_to_from_decorator
+
+convert_matrix_to_array = _conv_to_from_decorator(from_matrix_to_array.convert_matrix_to_array)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/from_array_to_indexed.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/from_array_to_indexed.py
new file mode 100644
index 0000000000000000000000000000000000000000..9eb86e7cfbe31ebfe7c9649803d9cb5e34b98276
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/from_array_to_indexed.py
@@ -0,0 +1,84 @@
+import collections.abc
+import operator
+from itertools import accumulate
+
+from sympy import Mul, Sum, Dummy, Add
+from sympy.tensor.array.expressions import PermuteDims, ArrayAdd, ArrayElementwiseApplyFunc, Reshape
+from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, get_rank, ArrayContraction, \
+    ArrayDiagonal, get_shape, _get_array_element_or_slice, _ArrayExpr
+from sympy.tensor.array.expressions.utils import _apply_permutation_to_list
+
+
+def convert_array_to_indexed(expr, indices):
+    return _ConvertArrayToIndexed().do_convert(expr, indices)
+
+
+class _ConvertArrayToIndexed:
+
+    def __init__(self):
+        self.count_dummies = 0
+
+    def do_convert(self, expr, indices):
+        if isinstance(expr, ArrayTensorProduct):
+            cumul = list(accumulate([0] + [get_rank(arg) for arg in expr.args]))
+            indices_grp = [indices[cumul[i]:cumul[i+1]] for i in range(len(expr.args))]
+            return Mul.fromiter(self.do_convert(arg, ind) for arg, ind in zip(expr.args, indices_grp))
+        if isinstance(expr, ArrayContraction):
+            new_indices = [None for i in range(get_rank(expr.expr))]
+            limits = []
+            bottom_shape = get_shape(expr.expr)
+            for contraction_index_grp in expr.contraction_indices:
+                d = Dummy(f"d{self.count_dummies}")
+                self.count_dummies += 1
+                dim = bottom_shape[contraction_index_grp[0]]
+                limits.append((d, 0, dim-1))
+                for i in contraction_index_grp:
+                    new_indices[i] = d
+            j = 0
+            for i in range(len(new_indices)):
+                if new_indices[i] is None:
+                    new_indices[i] = indices[j]
+                    j += 1
+            newexpr = self.do_convert(expr.expr, new_indices)
+            return Sum(newexpr, *limits)
+        if isinstance(expr, ArrayDiagonal):
+            new_indices = [None for i in range(get_rank(expr.expr))]
+            ind_pos = expr._push_indices_down(expr.diagonal_indices, list(range(len(indices))), get_rank(expr))
+            for i, index in zip(ind_pos, indices):
+                if isinstance(i, collections.abc.Iterable):
+                    for j in i:
+                        new_indices[j] = index
+                else:
+                    new_indices[i] = index
+            newexpr = self.do_convert(expr.expr, new_indices)
+            return newexpr
+        if isinstance(expr, PermuteDims):
+            permuted_indices = _apply_permutation_to_list(expr.permutation, indices)
+            return self.do_convert(expr.expr, permuted_indices)
+        if isinstance(expr, ArrayAdd):
+            return Add.fromiter(self.do_convert(arg, indices) for arg in expr.args)
+        if isinstance(expr, _ArrayExpr):
+            return expr.__getitem__(tuple(indices))
+        if isinstance(expr, ArrayElementwiseApplyFunc):
+            return expr.function(self.do_convert(expr.expr, indices))
+        if isinstance(expr, Reshape):
+            shape_up = expr.shape
+            shape_down = get_shape(expr.expr)
+            cumul = list(accumulate([1] + list(reversed(shape_up)), operator.mul))
+            one_index = Add.fromiter(i*s for i, s in zip(reversed(indices), cumul))
+            dest_indices = [None for _ in shape_down]
+            c = 1
+            for i, e in enumerate(reversed(shape_down)):
+                if c == 1:
+                    if i == len(shape_down) - 1:
+                        dest_indices[i] = one_index
+                    else:
+                        dest_indices[i] = one_index % e
+                elif i == len(shape_down) - 1:
+                    dest_indices[i] = one_index // c
+                else:
+                    dest_indices[i] = one_index // c % e
+                c *= e
+            dest_indices.reverse()
+            return self.do_convert(expr.expr, dest_indices)
+        return _get_array_element_or_slice(expr, indices)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/from_array_to_matrix.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/from_array_to_matrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..debfdd7eb5c4533996b3d72b55d679be3daf3afe
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/from_array_to_matrix.py
@@ -0,0 +1,1004 @@
+from __future__ import annotations
+import itertools
+from collections import defaultdict
+from typing import FrozenSet
+from functools import singledispatch
+from itertools import accumulate
+
+from sympy import MatMul, Basic, Wild, KroneckerProduct
+from sympy.assumptions.ask import (Q, ask)
+from sympy.core.mul import Mul
+from sympy.core.singleton import S
+from sympy.matrices.expressions.diagonal import DiagMatrix
+from sympy.matrices.expressions.hadamard import hadamard_product, HadamardPower
+from sympy.matrices.expressions.matexpr import MatrixExpr
+from sympy.matrices.expressions.special import (Identity, ZeroMatrix, OneMatrix)
+from sympy.matrices.expressions.trace import Trace
+from sympy.matrices.expressions.transpose import Transpose
+from sympy.combinatorics.permutations import _af_invert, Permutation
+from sympy.matrices.matrixbase import MatrixBase
+from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
+from sympy.matrices.expressions.matexpr import MatrixElement
+from sympy.tensor.array.expressions.array_expressions import PermuteDims, ArrayDiagonal, \
+    ArrayTensorProduct, OneArray, get_rank, _get_subrank, ZeroArray, ArrayContraction, \
+    ArrayAdd, _CodegenArrayAbstract, get_shape, ArrayElementwiseApplyFunc, _ArrayExpr, _EditArrayContraction, _ArgE, \
+    ArrayElement, _array_tensor_product, _array_contraction, _array_diagonal, _array_add, _permute_dims
+from sympy.tensor.array.expressions.utils import _get_mapping_from_subranks
+
+
+def _get_candidate_for_matmul_from_contraction(scan_indices: list[int | None], remaining_args: list[_ArgE]) -> tuple[_ArgE | None, bool, int]:
+
+    scan_indices_int: list[int] = [i for i in scan_indices if i is not None]
+    if len(scan_indices_int) == 0:
+        return None, False, -1
+
+    transpose: bool = False
+    candidate: _ArgE | None = None
+    candidate_index: int = -1
+    for arg_with_ind2 in remaining_args:
+        if not isinstance(arg_with_ind2.element, MatrixExpr):
+            continue
+        for index in scan_indices_int:
+            if candidate_index != -1 and candidate_index != index:
+                # A candidate index has already been selected, check
+                # repetitions only for that index:
+                continue
+            if index in arg_with_ind2.indices:
+                if set(arg_with_ind2.indices) == {index}:
+                    # Index repeated twice in arg_with_ind2
+                    candidate = None
+                    break
+                if candidate is None:
+                    candidate = arg_with_ind2
+                    candidate_index = index
+                    transpose = (index == arg_with_ind2.indices[1])
+                else:
+                    # Index repeated more than twice, break
+                    candidate = None
+                    break
+    return candidate, transpose, candidate_index
+
+
+def _insert_candidate_into_editor(editor: _EditArrayContraction, arg_with_ind: _ArgE, candidate: _ArgE, transpose1: bool, transpose2: bool):
+    other = candidate.element
+    other_index: int | None
+    if transpose2:
+        other = Transpose(other)
+        other_index = candidate.indices[0]
+    else:
+        other_index = candidate.indices[1]
+    new_element = (Transpose(arg_with_ind.element) if transpose1 else arg_with_ind.element) * other
+    editor.args_with_ind.remove(candidate)
+    new_arge = _ArgE(new_element)
+    return new_arge, other_index
+
+
+def _support_function_tp1_recognize(contraction_indices, args):
+    if len(contraction_indices) == 0:
+        return _a2m_tensor_product(*args)
+
+    ac = _array_contraction(_array_tensor_product(*args), *contraction_indices)
+    editor = _EditArrayContraction(ac)
+    editor.track_permutation_start()
+
+    while True:
+        flag_stop = True
+        for i, arg_with_ind in enumerate(editor.args_with_ind):
+            if not isinstance(arg_with_ind.element, MatrixExpr):
+                continue
+
+            first_index = arg_with_ind.indices[0]
+            second_index = arg_with_ind.indices[1]
+
+            first_frequency = editor.count_args_with_index(first_index)
+            second_frequency = editor.count_args_with_index(second_index)
+
+            if first_index is not None and first_frequency == 1 and first_index == second_index:
+                flag_stop = False
+                arg_with_ind.element = Trace(arg_with_ind.element)._normalize()
+                arg_with_ind.indices = []
+                break
+
+            scan_indices = []
+            if first_frequency == 2:
+                scan_indices.append(first_index)
+            if second_frequency == 2:
+                scan_indices.append(second_index)
+
+            candidate, transpose, found_index = _get_candidate_for_matmul_from_contraction(scan_indices, editor.args_with_ind[i+1:])
+            if candidate is not None:
+                flag_stop = False
+                editor.track_permutation_merge(arg_with_ind, candidate)
+                transpose1 = found_index == first_index
+                new_arge, other_index = _insert_candidate_into_editor(editor, arg_with_ind, candidate, transpose1, transpose)
+                if found_index == first_index:
+                    new_arge.indices = [second_index, other_index]
+                else:
+                    new_arge.indices = [first_index, other_index]
+                set_indices = set(new_arge.indices)
+                if len(set_indices) == 1 and set_indices != {None}:
+                    # This is a trace:
+                    new_arge.element = Trace(new_arge.element)._normalize()
+                    new_arge.indices = []
+                editor.args_with_ind[i] = new_arge
+                # TODO: is this break necessary?
+                break
+
+        if flag_stop:
+            break
+
+    editor.refresh_indices()
+    return editor.to_array_contraction()
+
+
+def _find_trivial_matrices_rewrite(expr: ArrayTensorProduct):
+    # If there are matrices of trivial shape in the tensor product (i.e. shape
+    # (1, 1)), try to check if there is a suitable non-trivial MatMul where the
+    # expression can be inserted.
+
+    # For example, if "a" has shape (1, 1) and "b" has shape (k, 1), the
+    # expressions "_array_tensor_product(a, b*b.T)" can be rewritten as
+    # "b*a*b.T"
+
+    trivial_matrices = []
+    pos: int | None = None  # must be initialized else causes UnboundLocalError
+    first: MatrixExpr | None = None  # may cause UnboundLocalError if not initialized
+    second: MatrixExpr | None = None  # may cause UnboundLocalError if not initialized
+    removed: list[int] = []
+    counter: int = 0
+    args: list[Basic | None] = list(expr.args)
+    for i, arg in enumerate(expr.args):
+        if isinstance(arg, MatrixExpr):
+            if arg.shape == (1, 1):
+                trivial_matrices.append(arg)
+                args[i] = None
+                removed.extend([counter, counter+1])
+            elif pos is None and isinstance(arg, MatMul):
+                margs = arg.args
+                for j, e in enumerate(margs):
+                    if isinstance(e, MatrixExpr) and e.shape[1] == 1:
+                        pos = i
+                        first = MatMul.fromiter(margs[:j+1])
+                        second = MatMul.fromiter(margs[j+1:])
+                        break
+        counter += get_rank(arg)
+    if pos is None:
+        return expr, []
+    args[pos] = (first*MatMul.fromiter(i for i in trivial_matrices)*second).doit()
+    return _array_tensor_product(*[i for i in args if i is not None]), removed
+
+
+def _find_trivial_kronecker_products_broadcast(expr: ArrayTensorProduct):
+    newargs: list[Basic] = []
+    removed = []
+    count_dims = 0
+    for arg in expr.args:
+        count_dims += get_rank(arg)
+        shape = get_shape(arg)
+        current_range = [count_dims-i for i in range(len(shape), 0, -1)]
+        if (shape == (1, 1) and len(newargs) > 0 and 1 not in get_shape(newargs[-1]) and
+            isinstance(newargs[-1], MatrixExpr) and isinstance(arg, MatrixExpr)):
+            # KroneckerProduct object allows the trick of broadcasting:
+            newargs[-1] = KroneckerProduct(newargs[-1], arg)
+            removed.extend(current_range)
+        elif 1 not in shape and len(newargs) > 0 and get_shape(newargs[-1]) == (1, 1):
+            # Broadcast:
+            newargs[-1] = KroneckerProduct(newargs[-1], arg)
+            prev_range = [i for i in range(min(current_range)) if i not in removed]
+            removed.extend(prev_range[-2:])
+        else:
+            newargs.append(arg)
+    return _array_tensor_product(*newargs), removed
+
+
+@singledispatch
+def _array2matrix(expr):
+    return expr
+
+
+@_array2matrix.register(ZeroArray)
+def _(expr: ZeroArray):
+    if get_rank(expr) == 2:
+        return ZeroMatrix(*expr.shape)
+    else:
+        return expr
+
+
+@_array2matrix.register(ArrayTensorProduct)
+def _(expr: ArrayTensorProduct):
+    return _a2m_tensor_product(*[_array2matrix(arg) for arg in expr.args])
+
+
+@_array2matrix.register(ArrayContraction)
+def _(expr: ArrayContraction):
+    expr = expr.flatten_contraction_of_diagonal()
+    expr = identify_removable_identity_matrices(expr)
+    expr = expr.split_multiple_contractions()
+    expr = identify_hadamard_products(expr)
+    if not isinstance(expr, ArrayContraction):
+        return _array2matrix(expr)
+    subexpr = expr.expr
+    contraction_indices: tuple[tuple[int]] = expr.contraction_indices
+    if contraction_indices == ((0,), (1,)) or (
+        contraction_indices == ((0,),) and subexpr.shape[1] == 1
+    ) or (
+        contraction_indices == ((1,),) and subexpr.shape[0] == 1
+    ):
+        shape = subexpr.shape
+        subexpr = _array2matrix(subexpr)
+        if isinstance(subexpr, MatrixExpr):
+            return OneMatrix(1, shape[0])*subexpr*OneMatrix(shape[1], 1)
+    if isinstance(subexpr, ArrayTensorProduct):
+        newexpr = _array_contraction(_array2matrix(subexpr), *contraction_indices)
+        contraction_indices = newexpr.contraction_indices
+        if any(i > 2 for i in newexpr.subranks):
+            addends = _array_add(*[_a2m_tensor_product(*j) for j in itertools.product(*[i.args if isinstance(i,
+                                                                                                                             ArrayAdd) else [i] for i in expr.expr.args])])
+            newexpr = _array_contraction(addends, *contraction_indices)
+        if isinstance(newexpr, ArrayAdd):
+            ret = _array2matrix(newexpr)
+            return ret
+        assert isinstance(newexpr, ArrayContraction)
+        ret = _support_function_tp1_recognize(contraction_indices, list(newexpr.expr.args))
+        return ret
+    elif not isinstance(subexpr, _CodegenArrayAbstract):
+        ret = _array2matrix(subexpr)
+        if isinstance(ret, MatrixExpr):
+            assert expr.contraction_indices == ((0, 1),)
+            return _a2m_trace(ret)
+        else:
+            return _array_contraction(ret, *expr.contraction_indices)
+
+
+@_array2matrix.register(ArrayDiagonal)
+def _(expr: ArrayDiagonal):
+    pexpr = _array_diagonal(_array2matrix(expr.expr), *expr.diagonal_indices)
+    pexpr = identify_hadamard_products(pexpr)
+    if isinstance(pexpr, ArrayDiagonal):
+        pexpr = _array_diag2contr_diagmatrix(pexpr)
+    if expr == pexpr:
+        return expr
+    return _array2matrix(pexpr)
+
+
+@_array2matrix.register(PermuteDims)
+def _(expr: PermuteDims):
+    if expr.permutation.array_form == [1, 0]:
+        return _a2m_transpose(_array2matrix(expr.expr))
+    elif isinstance(expr.expr, ArrayTensorProduct):
+        ranks = expr.expr.subranks
+        inv_permutation = expr.permutation**(-1)
+        newrange = [inv_permutation(i) for i in range(sum(ranks))]
+        newpos = []
+        counter = 0
+        for rank in ranks:
+            newpos.append(newrange[counter:counter+rank])
+            counter += rank
+        newargs = []
+        newperm = []
+        scalars = []
+        for pos, arg in zip(newpos, expr.expr.args):
+            if len(pos) == 0:
+                scalars.append(_array2matrix(arg))
+            elif pos == sorted(pos):
+                newargs.append((_array2matrix(arg), pos[0]))
+                newperm.extend(pos)
+            elif len(pos) == 2:
+                newargs.append((_a2m_transpose(_array2matrix(arg)), pos[0]))
+                newperm.extend(reversed(pos))
+            else:
+                raise NotImplementedError()
+        newargs = [i[0] for i in newargs]
+        return _permute_dims(_a2m_tensor_product(*scalars, *newargs), _af_invert(newperm))
+    elif isinstance(expr.expr, ArrayContraction):
+        mat_mul_lines = _array2matrix(expr.expr)
+        if not isinstance(mat_mul_lines, ArrayTensorProduct):
+            return _permute_dims(mat_mul_lines, expr.permutation)
+        # TODO: this assumes that all arguments are matrices, it may not be the case:
+        permutation = Permutation(2*len(mat_mul_lines.args)-1)*expr.permutation
+        permuted = [permutation(i) for i in range(2*len(mat_mul_lines.args))]
+        args_array = [None for i in mat_mul_lines.args]
+        for i in range(len(mat_mul_lines.args)):
+            p1 = permuted[2*i]
+            p2 = permuted[2*i+1]
+            if p1 // 2 != p2 // 2:
+                return _permute_dims(mat_mul_lines, permutation)
+            if p1 > p2:
+                args_array[i] = _a2m_transpose(mat_mul_lines.args[p1 // 2])
+            else:
+                args_array[i] = mat_mul_lines.args[p1 // 2]
+        return _a2m_tensor_product(*args_array)
+    else:
+        return expr
+
+
+@_array2matrix.register(ArrayAdd)
+def _(expr: ArrayAdd):
+    addends = [_array2matrix(arg) for arg in expr.args]
+    return _a2m_add(*addends)
+
+
+@_array2matrix.register(ArrayElementwiseApplyFunc)
+def _(expr: ArrayElementwiseApplyFunc):
+    subexpr = _array2matrix(expr.expr)
+    if isinstance(subexpr, MatrixExpr):
+        if subexpr.shape != (1, 1):
+            d = expr.function.bound_symbols[0]
+            w = Wild("w", exclude=[d])
+            p = Wild("p", exclude=[d])
+            m = expr.function.expr.match(w*d**p)
+            if m is not None:
+                return m[w]*HadamardPower(subexpr, m[p])
+        return ElementwiseApplyFunction(expr.function, subexpr)
+    else:
+        return ArrayElementwiseApplyFunc(expr.function, subexpr)
+
+
+@_array2matrix.register(ArrayElement)
+def _(expr: ArrayElement):
+    ret = _array2matrix(expr.name)
+    if isinstance(ret, MatrixExpr):
+        return MatrixElement(ret, *expr.indices)
+    return ArrayElement(ret, expr.indices)
+
+
+@singledispatch
+def _remove_trivial_dims(expr):
+    return expr, []
+
+
+@_remove_trivial_dims.register(ArrayTensorProduct)
+def _(expr: ArrayTensorProduct):
+    # Recognize expressions like [x, y] with shape (k, 1, k, 1) as `x*y.T`.
+    # The matrix expression has to be equivalent to the tensor product of the
+    # matrices, with trivial dimensions (i.e. dim=1) dropped.
+    # That is, add contractions over trivial dimensions:
+
+    removed = []
+    newargs = []
+    cumul = list(accumulate([0] + [get_rank(arg) for arg in expr.args]))
+    pending = None
+    prev_i = None
+    for i, arg in enumerate(expr.args):
+        current_range = list(range(cumul[i], cumul[i+1]))
+        if isinstance(arg, OneArray):
+            removed.extend(current_range)
+            continue
+        if not isinstance(arg, (MatrixExpr, MatrixBase)):
+            rarg, rem = _remove_trivial_dims(arg)
+            removed.extend(rem)
+            newargs.append(rarg)
+            continue
+        elif getattr(arg, "is_Identity", False) and arg.shape == (1, 1):
+            if arg.shape == (1, 1):
+                # Ignore identity matrices of shape (1, 1) - they are equivalent to scalar 1.
+                removed.extend(current_range)
+            continue
+        elif arg.shape == (1, 1):
+            arg, _ = _remove_trivial_dims(arg)
+            # Matrix is equivalent to scalar:
+            if len(newargs) == 0:
+                newargs.append(arg)
+            elif 1 in get_shape(newargs[-1]):
+                if newargs[-1].shape[1] == 1:
+                    newargs[-1] = newargs[-1]*arg
+                else:
+                    newargs[-1] = arg*newargs[-1]
+                removed.extend(current_range)
+            else:
+                newargs.append(arg)
+        elif 1 in arg.shape:
+            k = [i for i in arg.shape if i != 1][0]
+            if pending is None:
+                pending = k
+                prev_i = i
+                newargs.append(arg)
+            elif pending == k:
+                prev = newargs[-1]
+                if prev.shape[0] == 1:
+                    d1 = cumul[prev_i]  # type: ignore
+                    prev = _a2m_transpose(prev)
+                else:
+                    d1 = cumul[prev_i] + 1  # type: ignore
+                if arg.shape[1] == 1:
+                    d2 = cumul[i] + 1
+                    arg = _a2m_transpose(arg)
+                else:
+                    d2 = cumul[i]
+                newargs[-1] = prev*arg
+                pending = None
+                removed.extend([d1, d2])
+            else:
+                newargs.append(arg)
+                pending = k
+                prev_i = i
+        else:
+            newargs.append(arg)
+            pending = None
+    newexpr, newremoved = _a2m_tensor_product(*newargs), sorted(removed)
+    if isinstance(newexpr, ArrayTensorProduct):
+        newexpr, newremoved2 = _find_trivial_matrices_rewrite(newexpr)
+        newremoved = _combine_removed(-1, newremoved, newremoved2)
+    if isinstance(newexpr, ArrayTensorProduct):
+        newexpr, newremoved2 = _find_trivial_kronecker_products_broadcast(newexpr)
+        newremoved = _combine_removed(-1, newremoved, newremoved2)
+    return newexpr, newremoved
+
+
+@_remove_trivial_dims.register(ArrayAdd)
+def _(expr: ArrayAdd):
+    rec = [_remove_trivial_dims(arg) for arg in expr.args]
+    newargs, removed = zip(*rec)
+    if len({get_shape(i) for i in newargs}) > 1:
+        return expr, []
+    if len(removed) == 0:
+        return expr, removed
+    removed1 = removed[0]
+    return _a2m_add(*newargs), removed1
+
+
+@_remove_trivial_dims.register(PermuteDims)
+def _(expr: PermuteDims):
+    subexpr, subremoved = _remove_trivial_dims(expr.expr)
+    p = expr.permutation.array_form
+    pinv = _af_invert(expr.permutation.array_form)
+    shift = list(accumulate([1 if i in subremoved else 0 for i in range(len(p))]))
+    premoved = [pinv[i] for i in subremoved]
+    p2 = [e - shift[e] for e in p if e not in subremoved]
+    # TODO: check if subremoved should be permuted as well...
+    newexpr = _permute_dims(subexpr, p2)
+    premoved = sorted(premoved)
+    if newexpr != expr:
+        newexpr, removed2 = _remove_trivial_dims(_array2matrix(newexpr))
+        premoved = _combine_removed(-1, premoved, removed2)
+    return newexpr, premoved
+
+
+@_remove_trivial_dims.register(ArrayContraction)
+def _(expr: ArrayContraction):
+    new_expr, removed0 = _array_contraction_to_diagonal_multiple_identity(expr)
+    if new_expr != expr:
+        new_expr2, removed1 = _remove_trivial_dims(_array2matrix(new_expr))
+        removed = _combine_removed(-1, removed0, removed1)
+        return new_expr2, removed
+    rank1 = get_rank(expr)
+    expr, removed1 = remove_identity_matrices(expr)
+    if not isinstance(expr, ArrayContraction):
+        expr2, removed2 = _remove_trivial_dims(expr)
+        return expr2, _combine_removed(rank1, removed1, removed2)
+    newexpr, removed2 = _remove_trivial_dims(expr.expr)
+    shifts = list(accumulate([1 if i in removed2 else 0 for i in range(get_rank(expr.expr))]))
+    new_contraction_indices = [tuple(j for j in i if j not in removed2) for i in expr.contraction_indices]
+    # Remove possible empty tuples "()":
+    new_contraction_indices = [i for i in new_contraction_indices if len(i) > 0]
+    contraction_indices_flat = [j for i in expr.contraction_indices for j in i]
+    removed2 = [i for i in removed2 if i not in contraction_indices_flat]
+    new_contraction_indices = [tuple(j - shifts[j] for j in i) for i in new_contraction_indices]
+    # Shift removed2:
+    removed2 = ArrayContraction._push_indices_up(expr.contraction_indices, removed2)
+    removed = _combine_removed(rank1, removed1, removed2)
+    return _array_contraction(newexpr, *new_contraction_indices), list(removed)
+
+
+def _remove_diagonalized_identity_matrices(expr: ArrayDiagonal):
+    assert isinstance(expr, ArrayDiagonal)
+    editor = _EditArrayContraction(expr)
+    mapping = {i: {j for j in editor.args_with_ind if i in j.indices} for i in range(-1, -1-editor.number_of_diagonal_indices, -1)}
+    removed = []
+    counter: int = 0
+    for i, arg_with_ind in enumerate(editor.args_with_ind):
+        counter += len(arg_with_ind.indices)
+        if isinstance(arg_with_ind.element, Identity):
+            if None in arg_with_ind.indices and any(i is not None and (i < 0) == True for i in arg_with_ind.indices):
+                diag_ind = [j for j in arg_with_ind.indices if j is not None][0]
+                other = [j for j in mapping[diag_ind] if j != arg_with_ind][0]
+                if not isinstance(other.element, MatrixExpr):
+                    continue
+                if 1 not in other.element.shape:
+                    continue
+                if None not in other.indices:
+                    continue
+                editor.args_with_ind[i].element = None
+                none_index = other.indices.index(None)
+                other.element = DiagMatrix(other.element)
+                other_range = editor.get_absolute_range(other)
+                removed.extend([other_range[0] + none_index])
+    editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None]
+    removed = ArrayDiagonal._push_indices_up(expr.diagonal_indices, removed, get_rank(expr.expr))
+    return editor.to_array_contraction(), removed
+
+
+@_remove_trivial_dims.register(ArrayDiagonal)
+def _(expr: ArrayDiagonal):
+    newexpr, removed = _remove_trivial_dims(expr.expr)
+    shifts = list(accumulate([0] + [1 if i in removed else 0 for i in range(get_rank(expr.expr))]))
+    new_diag_indices_map = {i: tuple(j for j in i if j not in removed) for i in expr.diagonal_indices}
+    for old_diag_tuple, new_diag_tuple in new_diag_indices_map.items():
+        if len(new_diag_tuple) == 1:
+            removed = [i for i in removed if i not in old_diag_tuple]
+    new_diag_indices = [tuple(j - shifts[j] for j in i) for i in new_diag_indices_map.values()]
+    rank = get_rank(expr.expr)
+    removed = ArrayDiagonal._push_indices_up(expr.diagonal_indices, removed, rank)
+    removed = sorted(set(removed))
+    # If there are single axes to diagonalize remaining, it means that their
+    # corresponding dimension has been removed, they no longer need diagonalization:
+    new_diag_indices = [i for i in new_diag_indices if len(i) > 0]
+    if len(new_diag_indices) > 0:
+        newexpr2 = _array_diagonal(newexpr, *new_diag_indices, allow_trivial_diags=True)
+    else:
+        newexpr2 = newexpr
+    if isinstance(newexpr2, ArrayDiagonal):
+        newexpr3, removed2 = _remove_diagonalized_identity_matrices(newexpr2)
+        removed = _combine_removed(-1, removed, removed2)
+        return newexpr3, removed
+    else:
+        return newexpr2, removed
+
+
+@_remove_trivial_dims.register(ElementwiseApplyFunction)
+def _(expr: ElementwiseApplyFunction):
+    subexpr, removed = _remove_trivial_dims(expr.expr)
+    if subexpr.shape == (1, 1):
+        # TODO: move this to ElementwiseApplyFunction
+        return expr.function(subexpr), removed + [0, 1]
+    return ElementwiseApplyFunction(expr.function, subexpr), []
+
+
+@_remove_trivial_dims.register(ArrayElementwiseApplyFunc)
+def _(expr: ArrayElementwiseApplyFunc):
+    subexpr, removed = _remove_trivial_dims(expr.expr)
+    return ArrayElementwiseApplyFunc(expr.function, subexpr), removed
+
+
+def convert_array_to_matrix(expr):
+    r"""
+    Recognize matrix expressions in codegen objects.
+
+    If more than one matrix multiplication line have been detected, return a
+    list with the matrix expressions.
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array
+    >>> from sympy.tensor.array import tensorcontraction, tensorproduct
+    >>> from sympy import MatrixSymbol, Sum
+    >>> from sympy.abc import i, j, k, l, N
+    >>> from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
+    >>> from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
+    >>> A = MatrixSymbol("A", N, N)
+    >>> B = MatrixSymbol("B", N, N)
+    >>> C = MatrixSymbol("C", N, N)
+    >>> D = MatrixSymbol("D", N, N)
+
+    >>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1))
+    >>> cg = convert_indexed_to_array(expr)
+    >>> convert_array_to_matrix(cg)
+    A*B
+    >>> cg = convert_indexed_to_array(expr, first_indices=[k])
+    >>> convert_array_to_matrix(cg)
+    B.T*A.T
+
+    Transposition is detected:
+
+    >>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1))
+    >>> cg = convert_indexed_to_array(expr)
+    >>> convert_array_to_matrix(cg)
+    A.T*B
+    >>> cg = convert_indexed_to_array(expr, first_indices=[k])
+    >>> convert_array_to_matrix(cg)
+    B.T*A
+
+    Detect the trace:
+
+    >>> expr = Sum(A[i, i], (i, 0, N-1))
+    >>> cg = convert_indexed_to_array(expr)
+    >>> convert_array_to_matrix(cg)
+    Trace(A)
+
+    Recognize some more complex traces:
+
+    >>> expr = Sum(A[i, j]*B[j, i], (i, 0, N-1), (j, 0, N-1))
+    >>> cg = convert_indexed_to_array(expr)
+    >>> convert_array_to_matrix(cg)
+    Trace(A*B)
+
+    More complicated expressions:
+
+    >>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1))
+    >>> cg = convert_indexed_to_array(expr)
+    >>> convert_array_to_matrix(cg)
+    A*B.T*A.T
+
+    Expressions constructed from matrix expressions do not contain literal
+    indices, the positions of free indices are returned instead:
+
+    >>> expr = A*B
+    >>> cg = convert_matrix_to_array(expr)
+    >>> convert_array_to_matrix(cg)
+    A*B
+
+    If more than one line of matrix multiplications is detected, return
+    separate matrix multiplication factors embedded in a tensor product object:
+
+    >>> cg = tensorcontraction(tensorproduct(A, B, C, D), (1, 2), (5, 6))
+    >>> convert_array_to_matrix(cg)
+    ArrayTensorProduct(A*B, C*D)
+
+    The two lines have free indices at axes 0, 3 and 4, 7, respectively.
+    """
+    rec = _array2matrix(expr)
+    rec, removed = _remove_trivial_dims(rec)
+    return rec
+
+
+def _array_diag2contr_diagmatrix(expr: ArrayDiagonal):
+    if isinstance(expr.expr, ArrayTensorProduct):
+        args = list(expr.expr.args)
+        diag_indices = list(expr.diagonal_indices)
+        mapping = _get_mapping_from_subranks([_get_subrank(arg) for arg in args])
+        tuple_links = [[mapping[j] for j in i] for i in diag_indices]
+        contr_indices = []
+        total_rank = get_rank(expr)
+        replaced = [False for arg in args]
+        for i, (abs_pos, rel_pos) in enumerate(zip(diag_indices, tuple_links)):
+            if len(abs_pos) != 2:
+                continue
+            (pos1_outer, pos1_inner), (pos2_outer, pos2_inner) = rel_pos
+            arg1 = args[pos1_outer]
+            arg2 = args[pos2_outer]
+            if get_rank(arg1) != 2 or get_rank(arg2) != 2:
+                if replaced[pos1_outer]:
+                    diag_indices[i] = None
+                if replaced[pos2_outer]:
+                    diag_indices[i] = None
+                continue
+            pos1_in2 = 1 - pos1_inner
+            pos2_in2 = 1 - pos2_inner
+            if arg1.shape[pos1_in2] == 1:
+                if arg1.shape[pos1_inner] != 1:
+                    darg1 = DiagMatrix(arg1)
+                else:
+                    darg1 = arg1
+                args.append(darg1)
+                contr_indices.append(((pos2_outer, pos2_inner), (len(args)-1, pos1_inner)))
+                total_rank += 1
+                diag_indices[i] = None
+                args[pos1_outer] = OneArray(arg1.shape[pos1_in2])
+                replaced[pos1_outer] = True
+            elif arg2.shape[pos2_in2] == 1:
+                if arg2.shape[pos2_inner] != 1:
+                    darg2 = DiagMatrix(arg2)
+                else:
+                    darg2 = arg2
+                args.append(darg2)
+                contr_indices.append(((pos1_outer, pos1_inner), (len(args)-1, pos2_inner)))
+                total_rank += 1
+                diag_indices[i] = None
+                args[pos2_outer] = OneArray(arg2.shape[pos2_in2])
+                replaced[pos2_outer] = True
+        diag_indices_new = [i for i in diag_indices if i is not None]
+        cumul = list(accumulate([0] + [get_rank(arg) for arg in args]))
+        contr_indices2 = [tuple(cumul[a] + b for a, b in i) for i in contr_indices]
+        tc = _array_contraction(
+            _array_tensor_product(*args), *contr_indices2
+        )
+        td = _array_diagonal(tc, *diag_indices_new)
+        return td
+    return expr
+
+
+def _a2m_mul(*args):
+    if not any(isinstance(i, _CodegenArrayAbstract) for i in args):
+        from sympy.matrices.expressions.matmul import MatMul
+        return MatMul(*args).doit()
+    else:
+        return _array_contraction(
+            _array_tensor_product(*args),
+            *[(2*i-1, 2*i) for i in range(1, len(args))]
+        )
+
+
+def _a2m_tensor_product(*args):
+    scalars = []
+    arrays = []
+    for arg in args:
+        if isinstance(arg, (MatrixExpr, _ArrayExpr, _CodegenArrayAbstract)):
+            arrays.append(arg)
+        else:
+            scalars.append(arg)
+    scalar = Mul.fromiter(scalars)
+    if len(arrays) == 0:
+        return scalar
+    if scalar != 1:
+        if isinstance(arrays[0], _CodegenArrayAbstract):
+            arrays = [scalar] + arrays
+        else:
+            arrays[0] *= scalar
+    return _array_tensor_product(*arrays)
+
+
+def _a2m_add(*args):
+    if not any(isinstance(i, _CodegenArrayAbstract) for i in args):
+        from sympy.matrices.expressions.matadd import MatAdd
+        return MatAdd(*args).doit()
+    else:
+        return _array_add(*args)
+
+
+def _a2m_trace(arg):
+    if isinstance(arg, _CodegenArrayAbstract):
+        return _array_contraction(arg, (0, 1))
+    else:
+        from sympy.matrices.expressions.trace import Trace
+        return Trace(arg)
+
+
+def _a2m_transpose(arg):
+    if isinstance(arg, _CodegenArrayAbstract):
+        return _permute_dims(arg, [1, 0])
+    else:
+        from sympy.matrices.expressions.transpose import Transpose
+        return Transpose(arg).doit()
+
+
+def identify_hadamard_products(expr: ArrayContraction | ArrayDiagonal):
+
+    editor: _EditArrayContraction = _EditArrayContraction(expr)
+
+    map_contr_to_args: dict[FrozenSet, list[_ArgE]] = defaultdict(list)
+    map_ind_to_inds: dict[int | None, int] = defaultdict(int)
+    for arg_with_ind in editor.args_with_ind:
+        for ind in arg_with_ind.indices:
+            map_ind_to_inds[ind] += 1
+        if None in arg_with_ind.indices:
+            continue
+        map_contr_to_args[frozenset(arg_with_ind.indices)].append(arg_with_ind)
+
+    k: FrozenSet[int]
+    v: list[_ArgE]
+    for k, v in map_contr_to_args.items():
+        make_trace: bool = False
+        if len(k) == 1 and next(iter(k)) >= 0 and sum(next(iter(k)) in i for i in map_contr_to_args) == 1:
+            # This is a trace: the arguments are fully contracted with only one
+            # index, and the index isn't used anywhere else:
+            make_trace = True
+            first_element = S.One
+        elif len(k) != 2:
+            # Hadamard product only defined for matrices:
+            continue
+        if len(v) == 1:
+            # Hadamard product with a single argument makes no sense:
+            continue
+        for ind in k:
+            if map_ind_to_inds[ind] <= 2:
+                # There is no other contraction, skip:
+                continue
+
+        def check_transpose(x):
+            x = [i if i >= 0 else -1-i for i in x]
+            return x == sorted(x)
+
+        # Check if expression is a trace:
+        if all(map_ind_to_inds[j] == len(v) and j >= 0 for j in k) and all(j >= 0 for j in k):
+            # This is a trace
+            make_trace = True
+            first_element = v[0].element
+            if not check_transpose(v[0].indices):
+                first_element = first_element.T # type: ignore
+            hadamard_factors = v[1:]
+        else:
+            hadamard_factors = v
+
+        # This is a Hadamard product:
+
+        hp = hadamard_product(*[i.element if check_transpose(i.indices) else Transpose(i.element) for i in hadamard_factors])
+        hp_indices = v[0].indices
+        if not check_transpose(hadamard_factors[0].indices):
+            hp_indices = list(reversed(hp_indices))
+        if make_trace:
+            hp = Trace(first_element*hp.T)._normalize()
+            hp_indices = []
+        editor.insert_after(v[0], _ArgE(hp, hp_indices))
+        for i in v:
+            editor.args_with_ind.remove(i)
+
+    return editor.to_array_contraction()
+
+
+def identify_removable_identity_matrices(expr):
+    editor = _EditArrayContraction(expr)
+
+    flag = True
+    while flag:
+        flag = False
+        for arg_with_ind in editor.args_with_ind:
+            if isinstance(arg_with_ind.element, Identity):
+                k = arg_with_ind.element.shape[0]
+                # Candidate for removal:
+                if arg_with_ind.indices == [None, None]:
+                    # Free identity matrix, will be cleared by _remove_trivial_dims:
+                    continue
+                elif None in arg_with_ind.indices:
+                    ind = [j for j in arg_with_ind.indices if j is not None][0]
+                    counted = editor.count_args_with_index(ind)
+                    if counted == 1:
+                        # Identity matrix contracted only on one index with itself,
+                        # transform to a OneArray(k) element:
+                        editor.insert_after(arg_with_ind, OneArray(k))
+                        editor.args_with_ind.remove(arg_with_ind)
+                        flag = True
+                        break
+                    elif counted > 2:
+                        # Case counted = 2 is a matrix multiplication by identity matrix, skip it.
+                        # Case counted > 2 is a multiple contraction,
+                        # this is a case where the contraction becomes a diagonalization if the
+                        # identity matrix is dropped.
+                        continue
+                elif arg_with_ind.indices[0] == arg_with_ind.indices[1]:
+                    ind = arg_with_ind.indices[0]
+                    counted = editor.count_args_with_index(ind)
+                    if counted > 1:
+                        editor.args_with_ind.remove(arg_with_ind)
+                        flag = True
+                        break
+                    else:
+                        # This is a trace, skip it as it will be recognized somewhere else:
+                        pass
+            elif ask(Q.diagonal(arg_with_ind.element)):
+                if arg_with_ind.indices == [None, None]:
+                    continue
+                elif None in arg_with_ind.indices:
+                    pass
+                elif arg_with_ind.indices[0] == arg_with_ind.indices[1]:
+                    ind = arg_with_ind.indices[0]
+                    counted = editor.count_args_with_index(ind)
+                    if counted == 3:
+                        # A_ai B_bi D_ii ==> A_ai D_ij B_bj
+                        ind_new = editor.get_new_contraction_index()
+                        other_args = [j for j in editor.args_with_ind if j != arg_with_ind]
+                        other_args[1].indices = [ind_new if j == ind else j for j in other_args[1].indices]
+                        arg_with_ind.indices = [ind, ind_new]
+                        flag = True
+                        break
+
+    return editor.to_array_contraction()
+
+
+def remove_identity_matrices(expr: ArrayContraction):
+    editor = _EditArrayContraction(expr)
+    removed: list[int] = []
+
+    permutation_map = {}
+
+    free_indices = list(accumulate([0] + [sum(i is None for i in arg.indices) for arg in editor.args_with_ind]))
+    free_map = dict(zip(editor.args_with_ind, free_indices[:-1]))
+
+    update_pairs = {}
+
+    for ind in range(editor.number_of_contraction_indices):
+        args = editor.get_args_with_index(ind)
+        identity_matrices = [i for i in args if isinstance(i.element, Identity)]
+        number_identity_matrices = len(identity_matrices)
+        # If the contraction involves a non-identity matrix and multiple identity matrices:
+        if number_identity_matrices != len(args) - 1 or number_identity_matrices == 0:
+            continue
+        # Get the non-identity element:
+        non_identity = [i for i in args if not isinstance(i.element, Identity)][0]
+        # Check that all identity matrices have at least one free index
+        # (otherwise they would be contractions to some other elements)
+        if any(None not in i.indices for i in identity_matrices):
+            continue
+        # Mark the identity matrices for removal:
+        for i in identity_matrices:
+            i.element = None
+            removed.extend(range(free_map[i], free_map[i] + len([j for j in i.indices if j is None])))
+        last_removed = removed.pop(-1)
+        update_pairs[last_removed, ind] = non_identity.indices[:]
+        # Remove the indices from the non-identity matrix, as the contraction
+        # no longer exists:
+        non_identity.indices = [None if i == ind else i for i in non_identity.indices]
+
+    removed.sort()
+
+    shifts = list(accumulate([1 if i in removed else 0 for i in range(get_rank(expr))]))
+    for (last_removed, ind), non_identity_indices in update_pairs.items():
+        pos = [free_map[non_identity] + i for i, e in enumerate(non_identity_indices) if e == ind]
+        assert len(pos) == 1
+        for j in pos:
+            permutation_map[j] = last_removed
+
+    editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None]
+    ret_expr = editor.to_array_contraction()
+    permutation = []
+    counter = 0
+    counter2 = 0
+    for j in range(get_rank(expr)):
+        if j in removed:
+            continue
+        if counter2 in permutation_map:
+            target = permutation_map[counter2]
+            permutation.append(target - shifts[target])
+            counter2 += 1
+        else:
+            while counter in permutation_map.values():
+                counter += 1
+            permutation.append(counter)
+            counter += 1
+            counter2 += 1
+    ret_expr2 = _permute_dims(ret_expr, _af_invert(permutation))
+    return ret_expr2, removed
+
+
+def _combine_removed(dim: int, removed1: list[int], removed2: list[int]) -> list[int]:
+    # Concatenate two axis removal operations as performed by
+    # _remove_trivial_dims,
+    removed1 = sorted(removed1)
+    removed2 = sorted(removed2)
+    i = 0
+    j = 0
+    removed = []
+    while True:
+        if j >= len(removed2):
+            while i < len(removed1):
+                removed.append(removed1[i])
+                i += 1
+            break
+        elif i < len(removed1) and removed1[i] <= i + removed2[j]:
+            removed.append(removed1[i])
+            i += 1
+        else:
+            removed.append(i + removed2[j])
+            j += 1
+    return removed
+
+
+def _array_contraction_to_diagonal_multiple_identity(expr: ArrayContraction):
+    editor = _EditArrayContraction(expr)
+    editor.track_permutation_start()
+    removed: list[int] = []
+    diag_index_counter: int = 0
+    for i in range(editor.number_of_contraction_indices):
+        identities = []
+        args = []
+        for j, arg in enumerate(editor.args_with_ind):
+            if i not in arg.indices:
+                continue
+            if isinstance(arg.element, Identity):
+                identities.append(arg)
+            else:
+                args.append(arg)
+        if len(identities) == 0:
+            continue
+        if len(args) + len(identities) < 3:
+            continue
+        new_diag_ind = -1 - diag_index_counter
+        diag_index_counter += 1
+        # Variable "flag" to control whether to skip this contraction set:
+        flag: bool = True
+        for i1, id1 in enumerate(identities):
+            if None not in id1.indices:
+                flag = True
+                break
+            free_pos = list(range(*editor.get_absolute_free_range(id1)))[0]
+            editor._track_permutation[-1].append(free_pos) # type: ignore
+            id1.element = None
+            flag = False
+            break
+        if flag:
+            continue
+        for arg in identities[:i1] + identities[i1+1:]:
+            arg.element = None
+            removed.extend(range(*editor.get_absolute_free_range(arg)))
+        for arg in args:
+            arg.indices = [new_diag_ind if j == i else j for j in arg.indices]
+    for j, e in enumerate(editor.args_with_ind):
+        if e.element is None:
+            editor._track_permutation[j] = None # type: ignore
+    editor._track_permutation = [i for i in editor._track_permutation if i is not None] # type: ignore
+    # Renumber permutation array form in order to deal with deleted positions:
+    remap = {e: i for i, e in enumerate(sorted({k for j in editor._track_permutation for k in j}))}
+    editor._track_permutation = [[remap[j] for j in i] for i in editor._track_permutation]
+    editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None]
+    new_expr = editor.to_array_contraction()
+    return new_expr, removed
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/from_indexed_to_array.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/from_indexed_to_array.py
new file mode 100644
index 0000000000000000000000000000000000000000..c219a205c4305bd7070e5117978146224521c58c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/from_indexed_to_array.py
@@ -0,0 +1,257 @@
+from collections import defaultdict
+
+from sympy import Function
+from sympy.combinatorics.permutations import _af_invert
+from sympy.concrete.summations import Sum
+from sympy.core.add import Add
+from sympy.core.mul import Mul
+from sympy.core.numbers import Integer
+from sympy.core.power import Pow
+from sympy.core.sorting import default_sort_key
+from sympy.functions.special.tensor_functions import KroneckerDelta
+from sympy.tensor.array.expressions import ArrayElementwiseApplyFunc
+from sympy.tensor.indexed import (Indexed, IndexedBase)
+from sympy.combinatorics import Permutation
+from sympy.matrices.expressions.matexpr import MatrixElement
+from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal, \
+    get_shape, ArrayElement, _array_tensor_product, _array_diagonal, _array_contraction, _array_add, \
+    _permute_dims, OneArray, ArrayAdd
+from sympy.tensor.array.expressions.utils import _get_argindex, _get_diagonal_indices
+
+
+def convert_indexed_to_array(expr, first_indices=None):
+    r"""
+    Parse indexed expression into a form useful for code generation.
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array
+    >>> from sympy import MatrixSymbol, Sum, symbols
+
+    >>> i, j, k, d = symbols("i j k d")
+    >>> M = MatrixSymbol("M", d, d)
+    >>> N = MatrixSymbol("N", d, d)
+
+    Recognize the trace in summation form:
+
+    >>> expr = Sum(M[i, i], (i, 0, d-1))
+    >>> convert_indexed_to_array(expr)
+    ArrayContraction(M, (0, 1))
+
+    Recognize the extraction of the diagonal by using the same index `i` on
+    both axes of the matrix:
+
+    >>> expr = M[i, i]
+    >>> convert_indexed_to_array(expr)
+    ArrayDiagonal(M, (0, 1))
+
+    This function can help perform the transformation expressed in two
+    different mathematical notations as:
+
+    `\sum_{j=0}^{N-1} A_{i,j} B_{j,k} \Longrightarrow \mathbf{A}\cdot \mathbf{B}`
+
+    Recognize the matrix multiplication in summation form:
+
+    >>> expr = Sum(M[i, j]*N[j, k], (j, 0, d-1))
+    >>> convert_indexed_to_array(expr)
+    ArrayContraction(ArrayTensorProduct(M, N), (1, 2))
+
+    Specify that ``k`` has to be the starting index:
+
+    >>> convert_indexed_to_array(expr, first_indices=[k])
+    ArrayContraction(ArrayTensorProduct(N, M), (0, 3))
+    """
+
+    result, indices = _convert_indexed_to_array(expr)
+
+    if any(isinstance(i, (int, Integer)) for i in indices):
+        result = ArrayElement(result, indices)
+        indices = []
+
+    if not first_indices:
+        return result
+
+    def _check_is_in(elem, indices):
+        if elem in indices:
+            return True
+        if any(elem in i for i in indices if isinstance(i, frozenset)):
+            return True
+        return False
+
+    repl = {j: i for i in indices if isinstance(i, frozenset) for j in i}
+    first_indices = [repl.get(i, i) for i in first_indices]
+    for i in first_indices:
+        if not _check_is_in(i, indices):
+            first_indices.remove(i)
+    first_indices.extend([i for i in indices if not _check_is_in(i, first_indices)])
+
+    def _get_pos(elem, indices):
+        if elem in indices:
+            return indices.index(elem)
+        for i, e in enumerate(indices):
+            if not isinstance(e, frozenset):
+                continue
+            if elem in e:
+                return i
+        raise ValueError("not found")
+
+    permutation = _af_invert([_get_pos(i, first_indices) for i in indices])
+    if isinstance(result, ArrayAdd):
+        return _array_add(*[_permute_dims(arg, permutation) for arg in result.args])
+    else:
+        return _permute_dims(result, permutation)
+
+
+def _convert_indexed_to_array(expr):
+    if isinstance(expr, Sum):
+        function = expr.function
+        summation_indices = expr.variables
+        subexpr, subindices = _convert_indexed_to_array(function)
+        subindicessets = {j: i for i in subindices if isinstance(i, frozenset) for j in i}
+        summation_indices = sorted({subindicessets.get(i, i) for i in summation_indices}, key=default_sort_key)
+        # TODO: check that Kronecker delta is only contracted to one other element:
+        kronecker_indices = set()
+        if isinstance(function, Mul):
+            for arg in function.args:
+                if not isinstance(arg, KroneckerDelta):
+                    continue
+                arg_indices = sorted(set(arg.indices), key=default_sort_key)
+                if len(arg_indices) == 2:
+                    kronecker_indices.update(arg_indices)
+        kronecker_indices = sorted(kronecker_indices, key=default_sort_key)
+        # Check dimensional consistency:
+        shape = get_shape(subexpr)
+        if shape:
+            for ind, istart, iend in expr.limits:
+                i = _get_argindex(subindices, ind)
+                if istart != 0 or iend+1 != shape[i]:
+                    raise ValueError("summation index and array dimension mismatch: %s" % ind)
+        contraction_indices = []
+        subindices = list(subindices)
+        if isinstance(subexpr, ArrayDiagonal):
+            diagonal_indices = list(subexpr.diagonal_indices)
+            dindices = subindices[-len(diagonal_indices):]
+            subindices = subindices[:-len(diagonal_indices)]
+            for index in summation_indices:
+                if index in dindices:
+                    position = dindices.index(index)
+                    contraction_indices.append(diagonal_indices[position])
+                    diagonal_indices[position] = None
+            diagonal_indices = [i for i in diagonal_indices if i is not None]
+            for i, ind in enumerate(subindices):
+                if ind in summation_indices:
+                    pass
+            if diagonal_indices:
+                subexpr = _array_diagonal(subexpr.expr, *diagonal_indices)
+            else:
+                subexpr = subexpr.expr
+
+        axes_contraction = defaultdict(list)
+        for i, ind in enumerate(subindices):
+            include = all(j not in kronecker_indices for j in ind) if isinstance(ind, frozenset) else ind not in kronecker_indices
+            if ind in summation_indices and include:
+                axes_contraction[ind].append(i)
+                subindices[i] = None
+        for k, v in axes_contraction.items():
+            if any(i in kronecker_indices for i in k) if isinstance(k, frozenset) else k in kronecker_indices:
+                continue
+            contraction_indices.append(tuple(v))
+        free_indices = [i for i in subindices if i is not None]
+        indices_ret = list(free_indices)
+        indices_ret.sort(key=lambda x: free_indices.index(x))
+        return _array_contraction(
+                subexpr,
+                *contraction_indices,
+                free_indices=free_indices
+            ), tuple(indices_ret)
+    if isinstance(expr, Mul):
+        args, indices = zip(*[_convert_indexed_to_array(arg) for arg in expr.args])
+        # Check if there are KroneckerDelta objects:
+        kronecker_delta_repl = {}
+        for arg in args:
+            if not isinstance(arg, KroneckerDelta):
+                continue
+            # Diagonalize two indices:
+            i, j = arg.indices
+            kindices = set(arg.indices)
+            if i in kronecker_delta_repl:
+                kindices.update(kronecker_delta_repl[i])
+            if j in kronecker_delta_repl:
+                kindices.update(kronecker_delta_repl[j])
+            kindices = frozenset(kindices)
+            for index in kindices:
+                kronecker_delta_repl[index] = kindices
+        # Remove KroneckerDelta objects, their relations should be handled by
+        # ArrayDiagonal:
+        newargs = []
+        newindices = []
+        for arg, loc_indices in zip(args, indices):
+            if isinstance(arg, KroneckerDelta):
+                continue
+            newargs.append(arg)
+            newindices.append(loc_indices)
+        flattened_indices = [kronecker_delta_repl.get(j, j) for i in newindices for j in i]
+        diagonal_indices, ret_indices = _get_diagonal_indices(flattened_indices)
+        tp = _array_tensor_product(*newargs)
+        if diagonal_indices:
+            return _array_diagonal(tp, *diagonal_indices), ret_indices
+        else:
+            return tp, ret_indices
+    if isinstance(expr, MatrixElement):
+        indices = expr.args[1:]
+        diagonal_indices, ret_indices = _get_diagonal_indices(indices)
+        if diagonal_indices:
+            return _array_diagonal(expr.args[0], *diagonal_indices), ret_indices
+        else:
+            return expr.args[0], ret_indices
+    if isinstance(expr, ArrayElement):
+        indices = expr.indices
+        diagonal_indices, ret_indices = _get_diagonal_indices(indices)
+        if diagonal_indices:
+            return _array_diagonal(expr.name, *diagonal_indices), ret_indices
+        else:
+            return expr.name, ret_indices
+    if isinstance(expr, Indexed):
+        indices = expr.indices
+        diagonal_indices, ret_indices = _get_diagonal_indices(indices)
+        if diagonal_indices:
+            return _array_diagonal(expr.base, *diagonal_indices), ret_indices
+        else:
+            return expr.args[0], ret_indices
+    if isinstance(expr, IndexedBase):
+        raise NotImplementedError
+    if isinstance(expr, KroneckerDelta):
+        return expr, expr.indices
+    if isinstance(expr, Add):
+        args, indices = zip(*[_convert_indexed_to_array(arg) for arg in expr.args])
+        args = list(args)
+        # Check if all indices are compatible. Otherwise expand the dimensions:
+        index0 = []
+        shape0 = []
+        for arg, arg_indices in zip(args, indices):
+            arg_indices_set = set(arg_indices)
+            arg_indices_missing = arg_indices_set.difference(index0)
+            index0.extend([i for i in arg_indices if i in arg_indices_missing])
+            arg_shape = get_shape(arg)
+            shape0.extend([arg_shape[i] for i, e in enumerate(arg_indices) if e in arg_indices_missing])
+        for i, (arg, arg_indices) in enumerate(zip(args, indices)):
+            if len(arg_indices) < len(index0):
+                missing_indices_pos = [i for i, e in enumerate(index0) if e not in arg_indices]
+                missing_shape = [shape0[i] for i in missing_indices_pos]
+                arg_indices = tuple(index0[j] for j in missing_indices_pos) + arg_indices
+                args[i] = _array_tensor_product(OneArray(*missing_shape), args[i])
+            permutation = Permutation([arg_indices.index(j) for j in index0])
+            # Perform index permutations:
+            args[i] = _permute_dims(args[i], permutation)
+        return _array_add(*args), tuple(index0)
+    if isinstance(expr, Pow):
+        subexpr, subindices = _convert_indexed_to_array(expr.base)
+        if isinstance(expr.exp, (int, Integer)):
+            diags = zip(*[(2*i, 2*i + 1) for i in range(expr.exp)])
+            arr = _array_diagonal(_array_tensor_product(*[subexpr for i in range(expr.exp)]), *diags)
+            return arr, subindices
+    if isinstance(expr, Function):
+        subexpr, subindices = _convert_indexed_to_array(expr.args[0])
+        return ArrayElementwiseApplyFunc(type(expr), subexpr), subindices
+    return expr, ()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/from_matrix_to_array.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/from_matrix_to_array.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f66961727f6338318d65876a7768802773e4f2d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/from_matrix_to_array.py
@@ -0,0 +1,87 @@
+from sympy import KroneckerProduct
+from sympy.core.basic import Basic
+from sympy.core.function import Lambda
+from sympy.core.mul import Mul
+from sympy.core.numbers import Integer
+from sympy.core.power import Pow
+from sympy.core.singleton import S
+from sympy.core.symbol import (Dummy, symbols)
+from sympy.matrices.expressions.hadamard import (HadamardPower, HadamardProduct)
+from sympy.matrices.expressions.matadd import MatAdd
+from sympy.matrices.expressions.matmul import MatMul
+from sympy.matrices.expressions.matpow import MatPow
+from sympy.matrices.expressions.trace import Trace
+from sympy.matrices.expressions.transpose import Transpose
+from sympy.matrices.expressions.matexpr import MatrixExpr
+from sympy.tensor.array.expressions.array_expressions import \
+    ArrayElementwiseApplyFunc, _array_tensor_product, _array_contraction, \
+    _array_diagonal, _array_add, _permute_dims, Reshape
+
+
+def convert_matrix_to_array(expr: Basic) -> Basic:
+    if isinstance(expr, MatMul):
+        args_nonmat = []
+        args = []
+        for arg in expr.args:
+            if isinstance(arg, MatrixExpr):
+                args.append(arg)
+            else:
+                args_nonmat.append(convert_matrix_to_array(arg))
+        contractions = [(2*i+1, 2*i+2) for i in range(len(args)-1)]
+        scalar = _array_tensor_product(*args_nonmat) if args_nonmat else S.One
+        if scalar == 1:
+            tprod = _array_tensor_product(
+                *[convert_matrix_to_array(arg) for arg in args])
+        else:
+            tprod = _array_tensor_product(
+                scalar,
+                *[convert_matrix_to_array(arg) for arg in args])
+        return _array_contraction(
+                tprod,
+                *contractions
+        )
+    elif isinstance(expr, MatAdd):
+        return _array_add(
+                *[convert_matrix_to_array(arg) for arg in expr.args]
+        )
+    elif isinstance(expr, Transpose):
+        return _permute_dims(
+                convert_matrix_to_array(expr.args[0]), [1, 0]
+        )
+    elif isinstance(expr, Trace):
+        inner_expr: MatrixExpr = convert_matrix_to_array(expr.arg) # type: ignore
+        return _array_contraction(inner_expr, (0, len(inner_expr.shape) - 1))
+    elif isinstance(expr, Mul):
+        return _array_tensor_product(*[convert_matrix_to_array(i) for i in expr.args])
+    elif isinstance(expr, Pow):
+        base = convert_matrix_to_array(expr.base)
+        if (expr.exp > 0) == True:
+            return _array_tensor_product(*[base for i in range(expr.exp)])
+        else:
+            return expr
+    elif isinstance(expr, MatPow):
+        base = convert_matrix_to_array(expr.base)
+        if expr.exp.is_Integer != True:
+            b = symbols("b", cls=Dummy)
+            return ArrayElementwiseApplyFunc(Lambda(b, b**expr.exp), convert_matrix_to_array(base))
+        elif (expr.exp > 0) == True:
+            return convert_matrix_to_array(MatMul.fromiter(base for i in range(expr.exp)))
+        else:
+            return expr
+    elif isinstance(expr, HadamardProduct):
+        tp = _array_tensor_product(*[convert_matrix_to_array(arg) for arg in expr.args])
+        diag = [[2*i for i in range(len(expr.args))], [2*i+1 for i in range(len(expr.args))]]
+        return _array_diagonal(tp, *diag)
+    elif isinstance(expr, HadamardPower):
+        base, exp = expr.args
+        if isinstance(exp, Integer) and exp > 0:
+            return convert_matrix_to_array(HadamardProduct.fromiter(base for i in range(exp)))
+        else:
+            d = Dummy("d")
+            return ArrayElementwiseApplyFunc(Lambda(d, d**exp), base)
+    elif isinstance(expr, KroneckerProduct):
+        kp_args = [convert_matrix_to_array(arg) for arg in expr.args]
+        permutation = [2*i for i in range(len(kp_args))] + [2*i + 1 for i in range(len(kp_args))]
+        return Reshape(_permute_dims(_array_tensor_product(*kp_args), permutation), expr.shape)
+    else:
+        return expr
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_array_expressions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_array_expressions.py
new file mode 100644
index 0000000000000000000000000000000000000000..63fb79ab7ced7bff5ecb55b1764f43e29f98609d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_array_expressions.py
@@ -0,0 +1,808 @@
+import random
+
+from sympy import tensordiagonal, eye, KroneckerDelta, Array
+from sympy.core.symbol import symbols
+from sympy.functions.elementary.trigonometric import (cos, sin)
+from sympy.matrices.expressions.diagonal import DiagMatrix
+from sympy.matrices.expressions.matexpr import MatrixSymbol
+from sympy.matrices.expressions.special import ZeroMatrix
+from sympy.tensor.array.arrayop import (permutedims, tensorcontraction, tensorproduct)
+from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
+from sympy.combinatorics import Permutation
+from sympy.tensor.array.expressions.array_expressions import ZeroArray, OneArray, ArraySymbol, ArrayElement, \
+    PermuteDims, ArrayContraction, ArrayTensorProduct, ArrayDiagonal, \
+    ArrayAdd, nest_permutation, ArrayElementwiseApplyFunc, _EditArrayContraction, _ArgE, _array_tensor_product, \
+    _array_contraction, _array_diagonal, _array_add, _permute_dims, Reshape
+from sympy.testing.pytest import raises
+
+i, j, k, l, m, n = symbols("i j k l m n")
+
+
+M = ArraySymbol("M", (k, k))
+N = ArraySymbol("N", (k, k))
+P = ArraySymbol("P", (k, k))
+Q = ArraySymbol("Q", (k, k))
+
+A = ArraySymbol("A", (k, k))
+B = ArraySymbol("B", (k, k))
+C = ArraySymbol("C", (k, k))
+D = ArraySymbol("D", (k, k))
+
+X = ArraySymbol("X", (k, k))
+Y = ArraySymbol("Y", (k, k))
+
+a = ArraySymbol("a", (k, 1))
+b = ArraySymbol("b", (k, 1))
+c = ArraySymbol("c", (k, 1))
+d = ArraySymbol("d", (k, 1))
+
+
+def test_array_symbol_and_element():
+    A = ArraySymbol("A", (2,))
+    A0 = ArrayElement(A, (0,))
+    A1 = ArrayElement(A, (1,))
+    assert A[0] == A0
+    assert A[1] != A0
+    assert A.as_explicit() == ImmutableDenseNDimArray([A0, A1])
+
+    A2 = tensorproduct(A, A)
+    assert A2.shape == (2, 2)
+    # TODO: not yet supported:
+    # assert A2.as_explicit() == Array([[A[0]*A[0], A[1]*A[0]], [A[0]*A[1], A[1]*A[1]]])
+    A3 = tensorcontraction(A2, (0, 1))
+    assert A3.shape == ()
+    # TODO: not yet supported:
+    # assert A3.as_explicit() == Array([])
+
+    A = ArraySymbol("A", (2, 3, 4))
+    Ae = A.as_explicit()
+    assert Ae == ImmutableDenseNDimArray(
+        [[[ArrayElement(A, (i, j, k)) for k in range(4)] for j in range(3)] for i in range(2)])
+
+    p = _permute_dims(A, Permutation(0, 2, 1))
+    assert isinstance(p, PermuteDims)
+
+    A = ArraySymbol("A", (2,))
+    raises(IndexError, lambda: A[()])
+    raises(IndexError, lambda: A[0, 1])
+    raises(ValueError, lambda: A[-1])
+    raises(ValueError, lambda: A[2])
+
+    O = OneArray(3, 4)
+    Z = ZeroArray(m, n)
+
+    raises(IndexError, lambda: O[()])
+    raises(IndexError, lambda: O[1, 2, 3])
+    raises(ValueError, lambda: O[3, 0])
+    raises(ValueError, lambda: O[0, 4])
+
+    assert O[1, 2] == 1
+    assert Z[1, 2] == 0
+
+
+def test_zero_array():
+    assert ZeroArray() == 0
+    assert ZeroArray().is_Integer
+
+    za = ZeroArray(3, 2, 4)
+    assert za.shape == (3, 2, 4)
+    za_e = za.as_explicit()
+    assert za_e.shape == (3, 2, 4)
+
+    m, n, k = symbols("m n k")
+    za = ZeroArray(m, n, k, 2)
+    assert za.shape == (m, n, k, 2)
+    raises(ValueError, lambda: za.as_explicit())
+
+
+def test_one_array():
+    assert OneArray() == 1
+    assert OneArray().is_Integer
+
+    oa = OneArray(3, 2, 4)
+    assert oa.shape == (3, 2, 4)
+    oa_e = oa.as_explicit()
+    assert oa_e.shape == (3, 2, 4)
+
+    m, n, k = symbols("m n k")
+    oa = OneArray(m, n, k, 2)
+    assert oa.shape == (m, n, k, 2)
+    raises(ValueError, lambda: oa.as_explicit())
+
+
+def test_arrayexpr_contraction_construction():
+
+    cg = _array_contraction(A)
+    assert cg == A
+
+    cg = _array_contraction(_array_tensor_product(A, B), (1, 0))
+    assert cg == _array_contraction(_array_tensor_product(A, B), (0, 1))
+
+    cg = _array_contraction(_array_tensor_product(M, N), (0, 1))
+    indtup = cg._get_contraction_tuples()
+    assert indtup == [[(0, 0), (0, 1)]]
+    assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(0, 1)]
+
+    cg = _array_contraction(_array_tensor_product(M, N), (1, 2))
+    indtup = cg._get_contraction_tuples()
+    assert indtup == [[(0, 1), (1, 0)]]
+    assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(1, 2)]
+
+    cg = _array_contraction(_array_tensor_product(M, M, N), (1, 4), (2, 5))
+    indtup = cg._get_contraction_tuples()
+    assert indtup == [[(0, 0), (1, 1)], [(0, 1), (2, 0)]]
+    assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(0, 3), (1, 4)]
+
+    # Test removal of trivial contraction:
+    assert _array_contraction(a, (1,)) == a
+    assert _array_contraction(
+        _array_tensor_product(a, b), (0, 2), (1,), (3,)) == _array_contraction(
+        _array_tensor_product(a, b), (0, 2))
+
+
+def test_arrayexpr_array_flatten():
+
+    # Flatten nested ArrayTensorProduct objects:
+    expr1 = _array_tensor_product(M, N)
+    expr2 = _array_tensor_product(P, Q)
+    expr = _array_tensor_product(expr1, expr2)
+    assert expr == _array_tensor_product(M, N, P, Q)
+    assert expr.args == (M, N, P, Q)
+
+    # Flatten mixed ArrayTensorProduct and ArrayContraction objects:
+    cg1 = _array_contraction(expr1, (1, 2))
+    cg2 = _array_contraction(expr2, (0, 3))
+
+    expr = _array_tensor_product(cg1, cg2)
+    assert expr == _array_contraction(_array_tensor_product(M, N, P, Q), (1, 2), (4, 7))
+
+    expr = _array_tensor_product(M, cg1)
+    assert expr == _array_contraction(_array_tensor_product(M, M, N), (3, 4))
+
+    # Flatten nested ArrayContraction objects:
+    cgnested = _array_contraction(cg1, (0, 1))
+    assert cgnested == _array_contraction(_array_tensor_product(M, N), (0, 3), (1, 2))
+
+    cgnested = _array_contraction(_array_tensor_product(cg1, cg2), (0, 3))
+    assert cgnested == _array_contraction(_array_tensor_product(M, N, P, Q), (0, 6), (1, 2), (4, 7))
+
+    cg3 = _array_contraction(_array_tensor_product(M, N, P, Q), (1, 3), (2, 4))
+    cgnested = _array_contraction(cg3, (0, 1))
+    assert cgnested == _array_contraction(_array_tensor_product(M, N, P, Q), (0, 5), (1, 3), (2, 4))
+
+    cgnested = _array_contraction(cg3, (0, 3), (1, 2))
+    assert cgnested == _array_contraction(_array_tensor_product(M, N, P, Q), (0, 7), (1, 3), (2, 4), (5, 6))
+
+    cg4 = _array_contraction(_array_tensor_product(M, N, P, Q), (1, 5), (3, 7))
+    cgnested = _array_contraction(cg4, (0, 1))
+    assert cgnested == _array_contraction(_array_tensor_product(M, N, P, Q), (0, 2), (1, 5), (3, 7))
+
+    cgnested = _array_contraction(cg4, (0, 1), (2, 3))
+    assert cgnested == _array_contraction(_array_tensor_product(M, N, P, Q), (0, 2), (1, 5), (3, 7), (4, 6))
+
+    cg = _array_diagonal(cg4)
+    assert cg == cg4
+    assert isinstance(cg, type(cg4))
+
+    # Flatten nested ArrayDiagonal objects:
+    cg1 = _array_diagonal(expr1, (1, 2))
+    cg2 = _array_diagonal(expr2, (0, 3))
+    cg3 = _array_diagonal(_array_tensor_product(M, N, P, Q), (1, 3), (2, 4))
+    cg4 = _array_diagonal(_array_tensor_product(M, N, P, Q), (1, 5), (3, 7))
+
+    cgnested = _array_diagonal(cg1, (0, 1))
+    assert cgnested == _array_diagonal(_array_tensor_product(M, N), (1, 2), (0, 3))
+
+    cgnested = _array_diagonal(cg3, (1, 2))
+    assert cgnested == _array_diagonal(_array_tensor_product(M, N, P, Q), (1, 3), (2, 4), (5, 6))
+
+    cgnested = _array_diagonal(cg4, (1, 2))
+    assert cgnested == _array_diagonal(_array_tensor_product(M, N, P, Q), (1, 5), (3, 7), (2, 4))
+
+    cg = _array_add(M, N)
+    cg2 = _array_add(cg, P)
+    assert isinstance(cg2, ArrayAdd)
+    assert cg2.args == (M, N, P)
+    assert cg2.shape == (k, k)
+
+    expr = _array_tensor_product(_array_diagonal(X, (0, 1)), _array_diagonal(A, (0, 1)))
+    assert expr == _array_diagonal(_array_tensor_product(X, A), (0, 1), (2, 3))
+
+    expr1 = _array_diagonal(_array_tensor_product(X, A), (1, 2))
+    expr2 = _array_tensor_product(expr1, a)
+    assert expr2 == _permute_dims(_array_diagonal(_array_tensor_product(X, A, a), (1, 2)), [0, 1, 4, 2, 3])
+
+    expr1 = _array_contraction(_array_tensor_product(X, A), (1, 2))
+    expr2 = _array_tensor_product(expr1, a)
+    assert isinstance(expr2, ArrayContraction)
+    assert isinstance(expr2.expr, ArrayTensorProduct)
+
+    cg = _array_tensor_product(_array_diagonal(_array_tensor_product(A, X, Y), (0, 3), (1, 5)), a, b)
+    assert cg == _permute_dims(_array_diagonal(_array_tensor_product(A, X, Y, a, b), (0, 3), (1, 5)), [0, 1, 6, 7, 2, 3, 4, 5])
+
+
+def test_arrayexpr_array_diagonal():
+    cg = _array_diagonal(M, (1, 0))
+    assert cg == _array_diagonal(M, (0, 1))
+
+    cg = _array_diagonal(_array_tensor_product(M, N, P), (4, 1), (2, 0))
+    assert cg == _array_diagonal(_array_tensor_product(M, N, P), (1, 4), (0, 2))
+
+    cg = _array_diagonal(_array_tensor_product(M, N), (1, 2), (3,), allow_trivial_diags=True)
+    assert cg == _permute_dims(_array_diagonal(_array_tensor_product(M, N), (1, 2)), [0, 2, 1])
+
+    Ax = ArraySymbol("Ax", shape=(1, 2, 3, 4, 3, 5, 6, 2, 7))
+    cg = _array_diagonal(Ax, (1, 7), (3,), (2, 4), (6,), allow_trivial_diags=True)
+    assert cg == _permute_dims(_array_diagonal(Ax, (1, 7), (2, 4)), [0, 2, 4, 5, 1, 6, 3])
+
+    cg = _array_diagonal(M, (0,), allow_trivial_diags=True)
+    assert cg == _permute_dims(M, [1, 0])
+
+    raises(ValueError, lambda: _array_diagonal(M, (0, 0)))
+
+
+def test_arrayexpr_array_shape():
+    expr = _array_tensor_product(M, N, P, Q)
+    assert expr.shape == (k, k, k, k, k, k, k, k)
+    Z = MatrixSymbol("Z", m, n)
+    expr = _array_tensor_product(M, Z)
+    assert expr.shape == (k, k, m, n)
+    expr2 = _array_contraction(expr, (0, 1))
+    assert expr2.shape == (m, n)
+    expr2 = _array_diagonal(expr, (0, 1))
+    assert expr2.shape == (m, n, k)
+    exprp = _permute_dims(expr, [2, 1, 3, 0])
+    assert exprp.shape == (m, k, n, k)
+    expr3 = _array_tensor_product(N, Z)
+    expr2 = _array_add(expr, expr3)
+    assert expr2.shape == (k, k, m, n)
+
+    # Contraction along axes with discordant dimensions:
+    raises(ValueError, lambda: _array_contraction(expr, (1, 2)))
+    # Also diagonal needs the same dimensions:
+    raises(ValueError, lambda: _array_diagonal(expr, (1, 2)))
+    # Diagonal requires at least to axes to compute the diagonal:
+    raises(ValueError, lambda: _array_diagonal(expr, (1,)))
+
+
+def test_arrayexpr_permutedims_sink():
+
+    cg = _permute_dims(_array_tensor_product(M, N), [0, 1, 3, 2], nest_permutation=False)
+    sunk = nest_permutation(cg)
+    assert sunk == _array_tensor_product(M, _permute_dims(N, [1, 0]))
+
+    cg = _permute_dims(_array_tensor_product(M, N), [1, 0, 3, 2], nest_permutation=False)
+    sunk = nest_permutation(cg)
+    assert sunk == _array_tensor_product(_permute_dims(M, [1, 0]), _permute_dims(N, [1, 0]))
+
+    cg = _permute_dims(_array_tensor_product(M, N), [3, 2, 1, 0], nest_permutation=False)
+    sunk = nest_permutation(cg)
+    assert sunk == _array_tensor_product(_permute_dims(N, [1, 0]), _permute_dims(M, [1, 0]))
+
+    cg = _permute_dims(_array_contraction(_array_tensor_product(M, N), (1, 2)), [1, 0], nest_permutation=False)
+    sunk = nest_permutation(cg)
+    assert sunk == _array_contraction(_permute_dims(_array_tensor_product(M, N), [[0, 3]]), (1, 2))
+
+    cg = _permute_dims(_array_tensor_product(M, N), [1, 0, 3, 2], nest_permutation=False)
+    sunk = nest_permutation(cg)
+    assert sunk == _array_tensor_product(_permute_dims(M, [1, 0]), _permute_dims(N, [1, 0]))
+
+    cg = _permute_dims(_array_contraction(_array_tensor_product(M, N, P), (1, 2), (3, 4)), [1, 0], nest_permutation=False)
+    sunk = nest_permutation(cg)
+    assert sunk == _array_contraction(_permute_dims(_array_tensor_product(M, N, P), [[0, 5]]), (1, 2), (3, 4))
+
+
+def test_arrayexpr_push_indices_up_and_down():
+
+    indices = list(range(12))
+
+    contr_diag_indices = [(0, 6), (2, 8)]
+    assert ArrayContraction._push_indices_down(contr_diag_indices, indices) == (1, 3, 4, 5, 7, 9, 10, 11, 12, 13, 14, 15)
+    assert ArrayContraction._push_indices_up(contr_diag_indices, indices) == (None, 0, None, 1, 2, 3, None, 4, None, 5, 6, 7)
+
+    assert ArrayDiagonal._push_indices_down(contr_diag_indices, indices, 10) == (1, 3, 4, 5, 7, 9, (0, 6), (2, 8), None, None, None, None)
+    assert ArrayDiagonal._push_indices_up(contr_diag_indices, indices, 10) == (6, 0, 7, 1, 2, 3, 6, 4, 7, 5, None, None)
+
+    contr_diag_indices = [(1, 2), (7, 8)]
+    assert ArrayContraction._push_indices_down(contr_diag_indices, indices) == (0, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15)
+    assert ArrayContraction._push_indices_up(contr_diag_indices, indices) == (0, None, None, 1, 2, 3, 4, None, None, 5, 6, 7)
+
+    assert ArrayDiagonal._push_indices_down(contr_diag_indices, indices, 10) == (0, 3, 4, 5, 6, 9, (1, 2), (7, 8), None, None, None, None)
+    assert ArrayDiagonal._push_indices_up(contr_diag_indices, indices, 10) == (0, 6, 6, 1, 2, 3, 4, 7, 7, 5, None, None)
+
+
+def test_arrayexpr_split_multiple_contractions():
+    a = MatrixSymbol("a", k, 1)
+    b = MatrixSymbol("b", k, 1)
+    A = MatrixSymbol("A", k, k)
+    B = MatrixSymbol("B", k, k)
+    C = MatrixSymbol("C", k, k)
+    X = MatrixSymbol("X", k, k)
+
+    cg = _array_contraction(_array_tensor_product(A.T, a, b, b.T, (A*X*b).applyfunc(cos)), (1, 2, 8), (5, 6, 9))
+    expected = _array_contraction(_array_tensor_product(A.T, DiagMatrix(a), OneArray(1), b, b.T, (A*X*b).applyfunc(cos)), (1, 3), (2, 9), (6, 7, 10))
+    assert cg.split_multiple_contractions().dummy_eq(expected)
+
+    # Check no overlap of lines:
+
+    cg = _array_contraction(_array_tensor_product(A, a, C, a, B), (1, 2, 4), (5, 6, 8), (3, 7))
+    assert cg.split_multiple_contractions() == cg
+
+    cg = _array_contraction(_array_tensor_product(a, b, A), (0, 2, 4), (1, 3))
+    assert cg.split_multiple_contractions() == cg
+
+
+def test_arrayexpr_nested_permutations():
+
+    cg = _permute_dims(_permute_dims(M, (1, 0)), (1, 0))
+    assert cg == M
+
+    times = 3
+    plist1 = [list(range(6)) for i in range(times)]
+    plist2 = [list(range(6)) for i in range(times)]
+
+    for i in range(times):
+        random.shuffle(plist1[i])
+        random.shuffle(plist2[i])
+
+    plist1.append([2, 5, 4, 1, 0, 3])
+    plist2.append([3, 5, 0, 4, 1, 2])
+
+    plist1.append([2, 5, 4, 0, 3, 1])
+    plist2.append([3, 0, 5, 1, 2, 4])
+
+    plist1.append([5, 4, 2, 0, 3, 1])
+    plist2.append([4, 5, 0, 2, 3, 1])
+
+    Me = M.subs(k, 3).as_explicit()
+    Ne = N.subs(k, 3).as_explicit()
+    Pe = P.subs(k, 3).as_explicit()
+    cge = tensorproduct(Me, Ne, Pe)
+
+    for permutation_array1, permutation_array2 in zip(plist1, plist2):
+        p1 = Permutation(permutation_array1)
+        p2 = Permutation(permutation_array2)
+
+        cg = _permute_dims(
+            _permute_dims(
+                _array_tensor_product(M, N, P),
+                p1),
+            p2
+        )
+        result = _permute_dims(
+            _array_tensor_product(M, N, P),
+            p2*p1
+        )
+        assert cg == result
+
+        # Check that `permutedims` behaves the same way with explicit-component arrays:
+        result1 = _permute_dims(_permute_dims(cge, p1), p2)
+        result2 = _permute_dims(cge, p2*p1)
+        assert result1 == result2
+
+
+def test_arrayexpr_contraction_permutation_mix():
+
+    Me = M.subs(k, 3).as_explicit()
+    Ne = N.subs(k, 3).as_explicit()
+
+    cg1 = _array_contraction(PermuteDims(_array_tensor_product(M, N), Permutation([0, 2, 1, 3])), (2, 3))
+    cg2 = _array_contraction(_array_tensor_product(M, N), (1, 3))
+    assert cg1 == cg2
+    cge1 = tensorcontraction(permutedims(tensorproduct(Me, Ne), Permutation([0, 2, 1, 3])), (2, 3))
+    cge2 = tensorcontraction(tensorproduct(Me, Ne), (1, 3))
+    assert cge1 == cge2
+
+    cg1 = _permute_dims(_array_tensor_product(M, N), Permutation([0, 1, 3, 2]))
+    cg2 = _array_tensor_product(M, _permute_dims(N, Permutation([1, 0])))
+    assert cg1 == cg2
+
+    cg1 = _array_contraction(
+        _permute_dims(
+            _array_tensor_product(M, N, P, Q), Permutation([0, 2, 3, 1, 4, 5, 7, 6])),
+        (1, 2), (3, 5)
+    )
+    cg2 = _array_contraction(
+        _array_tensor_product(M, N, P, _permute_dims(Q, Permutation([1, 0]))),
+        (1, 5), (2, 3)
+    )
+    assert cg1 == cg2
+
+    cg1 = _array_contraction(
+        _permute_dims(
+            _array_tensor_product(M, N, P, Q), Permutation([1, 0, 4, 6, 2, 7, 5, 3])),
+        (0, 1), (2, 6), (3, 7)
+    )
+    cg2 = _permute_dims(
+        _array_contraction(
+            _array_tensor_product(M, P, Q, N),
+            (0, 1), (2, 3), (4, 7)),
+        [1, 0]
+    )
+    assert cg1 == cg2
+
+    cg1 = _array_contraction(
+        _permute_dims(
+            _array_tensor_product(M, N, P, Q), Permutation([1, 0, 4, 6, 7, 2, 5, 3])),
+        (0, 1), (2, 6), (3, 7)
+    )
+    cg2 = _permute_dims(
+        _array_contraction(
+            _array_tensor_product(_permute_dims(M, [1, 0]), N, P, Q),
+            (0, 1), (3, 6), (4, 5)
+        ),
+        Permutation([1, 0])
+    )
+    assert cg1 == cg2
+
+
+def test_arrayexpr_permute_tensor_product():
+    cg1 = _permute_dims(_array_tensor_product(M, N, P, Q), Permutation([2, 3, 1, 0, 5, 4, 6, 7]))
+    cg2 = _array_tensor_product(N, _permute_dims(M, [1, 0]),
+                                    _permute_dims(P, [1, 0]), Q)
+    assert cg1 == cg2
+
+    # TODO: reverse operation starting with `PermuteDims` and getting down to `bb`...
+    cg1 = _permute_dims(_array_tensor_product(M, N, P, Q), Permutation([2, 3, 4, 5, 0, 1, 6, 7]))
+    cg2 = _array_tensor_product(N, P, M, Q)
+    assert cg1 == cg2
+
+    cg1 = _permute_dims(_array_tensor_product(M, N, P, Q), Permutation([2, 3, 4, 6, 5, 7, 0, 1]))
+    assert cg1.expr == _array_tensor_product(N, P, Q, M)
+    assert cg1.permutation == Permutation([0, 1, 2, 4, 3, 5, 6, 7])
+
+    cg1 = _array_contraction(
+        _permute_dims(
+            _array_tensor_product(N, Q, Q, M),
+            [2, 1, 5, 4, 0, 3, 6, 7]),
+        [1, 2, 6])
+    cg2 = _permute_dims(_array_contraction(_array_tensor_product(Q, Q, N, M), (3, 5, 6)), [0, 2, 3, 1, 4])
+    assert cg1 == cg2
+
+    cg1 = _array_contraction(
+        _array_contraction(
+            _array_contraction(
+                _array_contraction(
+                    _permute_dims(
+                        _array_tensor_product(N, Q, Q, M),
+                        [2, 1, 5, 4, 0, 3, 6, 7]),
+                    [1, 2, 6]),
+                [1, 3, 4]),
+            [1]),
+        [0])
+    cg2 = _array_contraction(_array_tensor_product(M, N, Q, Q), (0, 3, 5), (1, 4, 7), (2,), (6,))
+    assert cg1 == cg2
+
+
+def test_arrayexpr_canonicalize_diagonal__permute_dims():
+    tp = _array_tensor_product(M, Q, N, P)
+    expr = _array_diagonal(
+        _permute_dims(tp, [0, 1, 2, 4, 7, 6, 3, 5]), (2, 4, 5), (6, 7),
+        (0, 3))
+    result = _array_diagonal(tp, (2, 6, 7), (3, 5), (0, 4))
+    assert expr == result
+
+    tp = _array_tensor_product(M, N, P, Q)
+    expr = _array_diagonal(_permute_dims(tp, [0, 5, 2, 4, 1, 6, 3, 7]), (1, 2, 6), (3, 4))
+    result = _array_diagonal(_array_tensor_product(M, P, N, Q), (3, 4, 5), (1, 2))
+    assert expr == result
+
+
+def test_arrayexpr_canonicalize_diagonal_contraction():
+    tp = _array_tensor_product(M, N, P, Q)
+    expr = _array_contraction(_array_diagonal(tp, (1, 3, 4)), (0, 3))
+    result = _array_diagonal(_array_contraction(_array_tensor_product(M, N, P, Q), (0, 6)), (0, 2, 3))
+    assert expr == result
+
+    expr = _array_contraction(_array_diagonal(tp, (0, 1, 2, 3, 7)), (1, 2, 3))
+    result = _array_contraction(_array_tensor_product(M, N, P, Q), (0, 1, 2, 3, 5, 6, 7))
+    assert expr == result
+
+    expr = _array_contraction(_array_diagonal(tp, (0, 2, 6, 7)), (1, 2, 3))
+    result = _array_diagonal(_array_contraction(tp, (3, 4, 5)), (0, 2, 3, 4))
+    assert expr == result
+
+    td = _array_diagonal(_array_tensor_product(M, N, P, Q), (0, 3))
+    expr = _array_contraction(td, (2, 1), (0, 4, 6, 5, 3))
+    result = _array_contraction(_array_tensor_product(M, N, P, Q), (0, 1, 3, 5, 6, 7), (2, 4))
+    assert expr == result
+
+
+def test_arrayexpr_array_wrong_permutation_size():
+    cg = _array_tensor_product(M, N)
+    raises(ValueError, lambda: _permute_dims(cg, [1, 0]))
+    raises(ValueError, lambda: _permute_dims(cg, [1, 0, 2, 3, 5, 4]))
+
+
+def test_arrayexpr_nested_array_elementwise_add():
+    cg = _array_contraction(_array_add(
+        _array_tensor_product(M, N),
+        _array_tensor_product(N, M)
+    ), (1, 2))
+    result = _array_add(
+        _array_contraction(_array_tensor_product(M, N), (1, 2)),
+        _array_contraction(_array_tensor_product(N, M), (1, 2))
+    )
+    assert cg == result
+
+    cg = _array_diagonal(_array_add(
+        _array_tensor_product(M, N),
+        _array_tensor_product(N, M)
+    ), (1, 2))
+    result = _array_add(
+        _array_diagonal(_array_tensor_product(M, N), (1, 2)),
+        _array_diagonal(_array_tensor_product(N, M), (1, 2))
+    )
+    assert cg == result
+
+
+def test_arrayexpr_array_expr_zero_array():
+    za1 = ZeroArray(k, l, m, n)
+    zm1 = ZeroMatrix(m, n)
+
+    za2 = ZeroArray(k, m, m, n)
+    zm2 = ZeroMatrix(m, m)
+    zm3 = ZeroMatrix(k, k)
+
+    assert _array_tensor_product(M, N, za1) == ZeroArray(k, k, k, k, k, l, m, n)
+    assert _array_tensor_product(M, N, zm1) == ZeroArray(k, k, k, k, m, n)
+
+    assert _array_contraction(za1, (3,)) == ZeroArray(k, l, m)
+    assert _array_contraction(zm1, (1,)) == ZeroArray(m)
+    assert _array_contraction(za2, (1, 2)) == ZeroArray(k, n)
+    assert _array_contraction(zm2, (0, 1)) == 0
+
+    assert _array_diagonal(za2, (1, 2)) == ZeroArray(k, n, m)
+    assert _array_diagonal(zm2, (0, 1)) == ZeroArray(m)
+
+    assert _permute_dims(za1, [2, 1, 3, 0]) == ZeroArray(m, l, n, k)
+    assert _permute_dims(zm1, [1, 0]) == ZeroArray(n, m)
+
+    assert _array_add(za1) == za1
+    assert _array_add(zm1) == ZeroArray(m, n)
+    tp1 = _array_tensor_product(MatrixSymbol("A", k, l), MatrixSymbol("B", m, n))
+    assert _array_add(tp1, za1) == tp1
+    tp2 = _array_tensor_product(MatrixSymbol("C", k, l), MatrixSymbol("D", m, n))
+    assert _array_add(tp1, za1, tp2) == _array_add(tp1, tp2)
+    assert _array_add(M, zm3) == M
+    assert _array_add(M, N, zm3) == _array_add(M, N)
+
+
+def test_arrayexpr_array_expr_applyfunc():
+
+    A = ArraySymbol("A", (3, k, 2))
+    aaf = ArrayElementwiseApplyFunc(sin, A)
+    assert aaf.shape == (3, k, 2)
+
+
+def test_edit_array_contraction():
+    cg = _array_contraction(_array_tensor_product(A, B, C, D), (1, 2, 5))
+    ecg = _EditArrayContraction(cg)
+    assert ecg.to_array_contraction() == cg
+
+    ecg.args_with_ind[1], ecg.args_with_ind[2] = ecg.args_with_ind[2], ecg.args_with_ind[1]
+    assert ecg.to_array_contraction() == _array_contraction(_array_tensor_product(A, C, B, D), (1, 3, 4))
+
+    ci = ecg.get_new_contraction_index()
+    new_arg = _ArgE(X)
+    new_arg.indices = [ci, ci]
+    ecg.args_with_ind.insert(2, new_arg)
+    assert ecg.to_array_contraction() == _array_contraction(_array_tensor_product(A, C, X, B, D), (1, 3, 6), (4, 5))
+
+    assert ecg.get_contraction_indices() == [[1, 3, 6], [4, 5]]
+    assert [[tuple(j) for j in i] for i in ecg.get_contraction_indices_to_ind_rel_pos()] == [[(0, 1), (1, 1), (3, 0)], [(2, 0), (2, 1)]]
+    assert [list(i) for i in ecg.get_mapping_for_index(0)] == [[0, 1], [1, 1], [3, 0]]
+    assert [list(i) for i in ecg.get_mapping_for_index(1)] == [[2, 0], [2, 1]]
+    raises(ValueError, lambda: ecg.get_mapping_for_index(2))
+
+    ecg.args_with_ind.pop(1)
+    assert ecg.to_array_contraction() == _array_contraction(_array_tensor_product(A, X, B, D), (1, 4), (2, 3))
+
+    ecg.args_with_ind[0].indices[1] = ecg.args_with_ind[1].indices[0]
+    ecg.args_with_ind[1].indices[1] = ecg.args_with_ind[2].indices[0]
+    assert ecg.to_array_contraction() == _array_contraction(_array_tensor_product(A, X, B, D), (1, 2), (3, 4))
+
+    ecg.insert_after(ecg.args_with_ind[1], _ArgE(C))
+    assert ecg.to_array_contraction() == _array_contraction(_array_tensor_product(A, X, C, B, D), (1, 2), (3, 6))
+
+
+def test_array_expressions_no_canonicalization():
+
+    tp = _array_tensor_product(M, N, P)
+
+    # ArrayTensorProduct:
+
+    expr = ArrayTensorProduct(tp, N)
+    assert str(expr) == "ArrayTensorProduct(ArrayTensorProduct(M, N, P), N)"
+    assert expr.doit() == ArrayTensorProduct(M, N, P, N)
+
+    expr = ArrayTensorProduct(ArrayContraction(M, (0, 1)), N)
+    assert str(expr) == "ArrayTensorProduct(ArrayContraction(M, (0, 1)), N)"
+    assert expr.doit() == ArrayContraction(ArrayTensorProduct(M, N), (0, 1))
+
+    expr = ArrayTensorProduct(ArrayDiagonal(M, (0, 1)), N)
+    assert str(expr) == "ArrayTensorProduct(ArrayDiagonal(M, (0, 1)), N)"
+    assert expr.doit() == PermuteDims(ArrayDiagonal(ArrayTensorProduct(M, N), (0, 1)), [2, 0, 1])
+
+    expr = ArrayTensorProduct(PermuteDims(M, [1, 0]), N)
+    assert str(expr) == "ArrayTensorProduct(PermuteDims(M, (0 1)), N)"
+    assert expr.doit() == PermuteDims(ArrayTensorProduct(M, N), [1, 0, 2, 3])
+
+    # ArrayContraction:
+
+    expr = ArrayContraction(_array_contraction(tp, (0, 2)), (0, 1))
+    assert isinstance(expr, ArrayContraction)
+    assert isinstance(expr.expr, ArrayContraction)
+    assert str(expr) == "ArrayContraction(ArrayContraction(ArrayTensorProduct(M, N, P), (0, 2)), (0, 1))"
+    assert expr.doit() == ArrayContraction(tp, (0, 2), (1, 3))
+
+    expr = ArrayContraction(ArrayContraction(ArrayContraction(tp, (0, 1)), (0, 1)), (0, 1))
+    assert expr.doit() == ArrayContraction(tp, (0, 1), (2, 3), (4, 5))
+    # assert expr._canonicalize() == ArrayContraction(ArrayContraction(tp, (0, 1)), (0, 1), (2, 3))
+
+    expr = ArrayContraction(ArrayDiagonal(tp, (0, 1)), (0, 1))
+    assert str(expr) == "ArrayContraction(ArrayDiagonal(ArrayTensorProduct(M, N, P), (0, 1)), (0, 1))"
+    assert expr.doit() == ArrayDiagonal(ArrayContraction(ArrayTensorProduct(N, M, P), (0, 1)), (0, 1))
+
+    expr = ArrayContraction(PermuteDims(M, [1, 0]), (0, 1))
+    assert str(expr) == "ArrayContraction(PermuteDims(M, (0 1)), (0, 1))"
+    assert expr.doit() == ArrayContraction(M, (0, 1))
+
+    # ArrayDiagonal:
+
+    expr = ArrayDiagonal(ArrayDiagonal(tp, (0, 2)), (0, 1))
+    assert str(expr) == "ArrayDiagonal(ArrayDiagonal(ArrayTensorProduct(M, N, P), (0, 2)), (0, 1))"
+    assert expr.doit() == ArrayDiagonal(tp, (0, 2), (1, 3))
+
+    expr = ArrayDiagonal(ArrayDiagonal(ArrayDiagonal(tp, (0, 1)), (0, 1)), (0, 1))
+    assert expr.doit() == ArrayDiagonal(tp, (0, 1), (2, 3), (4, 5))
+    assert expr._canonicalize() == expr.doit()
+
+    expr = ArrayDiagonal(ArrayContraction(tp, (0, 1)), (0, 1))
+    assert str(expr) == "ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, P), (0, 1)), (0, 1))"
+    assert expr.doit() == expr
+
+    expr = ArrayDiagonal(PermuteDims(M, [1, 0]), (0, 1))
+    assert str(expr) == "ArrayDiagonal(PermuteDims(M, (0 1)), (0, 1))"
+    assert expr.doit() == ArrayDiagonal(M, (0, 1))
+
+    # ArrayAdd:
+
+    expr = ArrayAdd(M)
+    assert isinstance(expr, ArrayAdd)
+    assert expr.doit() == M
+
+    expr = ArrayAdd(ArrayAdd(M, N), P)
+    assert str(expr) == "ArrayAdd(ArrayAdd(M, N), P)"
+    assert expr.doit() == ArrayAdd(M, N, P)
+
+    expr = ArrayAdd(M, ArrayAdd(N, ArrayAdd(P, M)))
+    assert expr.doit() == ArrayAdd(M, N, P, M)
+    assert expr._canonicalize() == ArrayAdd(M, N, ArrayAdd(P, M))
+
+    expr = ArrayAdd(M, ZeroArray(k, k), N)
+    assert str(expr) == "ArrayAdd(M, ZeroArray(k, k), N)"
+    assert expr.doit() == ArrayAdd(M, N)
+
+    # PermuteDims:
+
+    expr = PermuteDims(PermuteDims(M, [1, 0]), [1, 0])
+    assert str(expr) == "PermuteDims(PermuteDims(M, (0 1)), (0 1))"
+    assert expr.doit() == M
+
+    expr = PermuteDims(PermuteDims(PermuteDims(M, [1, 0]), [1, 0]), [1, 0])
+    assert expr.doit() == PermuteDims(M, [1, 0])
+    assert expr._canonicalize() == expr.doit()
+
+    # Reshape
+
+    expr = Reshape(A, (k**2,))
+    assert expr.shape == (k**2,)
+    assert isinstance(expr, Reshape)
+
+
+def test_array_expr_construction_with_functions():
+
+    tp = tensorproduct(M, N)
+    assert tp == ArrayTensorProduct(M, N)
+
+    expr = tensorproduct(A, eye(2))
+    assert expr == ArrayTensorProduct(A, eye(2))
+
+    # Contraction:
+
+    expr = tensorcontraction(M, (0, 1))
+    assert expr == ArrayContraction(M, (0, 1))
+
+    expr = tensorcontraction(tp, (1, 2))
+    assert expr == ArrayContraction(tp, (1, 2))
+
+    expr = tensorcontraction(tensorcontraction(tp, (1, 2)), (0, 1))
+    assert expr == ArrayContraction(tp, (0, 3), (1, 2))
+
+    # Diagonalization:
+
+    expr = tensordiagonal(M, (0, 1))
+    assert expr == ArrayDiagonal(M, (0, 1))
+
+    expr = tensordiagonal(tensordiagonal(tp, (0, 1)), (0, 1))
+    assert expr == ArrayDiagonal(tp, (0, 1), (2, 3))
+
+    # Permutation of dimensions:
+
+    expr = permutedims(M, [1, 0])
+    assert expr == PermuteDims(M, [1, 0])
+
+    expr = permutedims(PermuteDims(tp, [1, 0, 2, 3]), [0, 1, 3, 2])
+    assert expr == PermuteDims(tp, [1, 0, 3, 2])
+
+    expr = PermuteDims(tp, index_order_new=["a", "b", "c", "d"], index_order_old=["d", "c", "b", "a"])
+    assert expr == PermuteDims(tp, [3, 2, 1, 0])
+
+    arr = Array(range(32)).reshape(2, 2, 2, 2, 2)
+    expr = PermuteDims(arr, index_order_new=["a", "b", "c", "d", "e"], index_order_old=['b', 'e', 'a', 'd', 'c'])
+    assert expr == PermuteDims(arr, [2, 0, 4, 3, 1])
+    assert expr.as_explicit() == permutedims(arr, index_order_new=["a", "b", "c", "d", "e"], index_order_old=['b', 'e', 'a', 'd', 'c'])
+
+
+def test_array_element_expressions():
+    # Check commutative property:
+    assert M[0, 0]*N[0, 0] == N[0, 0]*M[0, 0]
+
+    # Check derivatives:
+    assert M[0, 0].diff(M[0, 0]) == 1
+    assert M[0, 0].diff(M[1, 0]) == 0
+    assert M[0, 0].diff(N[0, 0]) == 0
+    assert M[0, 1].diff(M[i, j]) == KroneckerDelta(i, 0)*KroneckerDelta(j, 1)
+    assert M[0, 1].diff(N[i, j]) == 0
+
+    K4 = ArraySymbol("K4", shape=(k, k, k, k))
+
+    assert K4[i, j, k, l].diff(K4[1, 2, 3, 4]) == (
+        KroneckerDelta(i, 1)*KroneckerDelta(j, 2)*KroneckerDelta(k, 3)*KroneckerDelta(l, 4)
+    )
+
+
+def test_array_expr_reshape():
+
+    A = MatrixSymbol("A", 2, 2)
+    B = ArraySymbol("B", (2, 2, 2))
+    C = Array([1, 2, 3, 4])
+
+    expr = Reshape(A, (4,))
+    assert expr.expr == A
+    assert expr.shape == (4,)
+    assert expr.as_explicit() == Array([A[0, 0], A[0, 1], A[1, 0], A[1, 1]])
+
+    expr = Reshape(B, (2, 4))
+    assert expr.expr == B
+    assert expr.shape == (2, 4)
+    ee = expr.as_explicit()
+    assert isinstance(ee, ImmutableDenseNDimArray)
+    assert ee.shape == (2, 4)
+    assert ee == Array([[B[0, 0, 0], B[0, 0, 1], B[0, 1, 0], B[0, 1, 1]], [B[1, 0, 0], B[1, 0, 1], B[1, 1, 0], B[1, 1, 1]]])
+
+    expr = Reshape(A, (k, 2))
+    assert expr.shape == (k, 2)
+
+    raises(ValueError, lambda: Reshape(A, (2, 3)))
+    raises(ValueError, lambda: Reshape(A, (3,)))
+
+    expr = Reshape(C, (2, 2))
+    assert expr.expr == C
+    assert expr.shape == (2, 2)
+    assert expr.doit() == Array([[1, 2], [3, 4]])
+
+
+def test_array_expr_as_explicit_with_explicit_component_arrays():
+    # Test if .as_explicit() works with explicit-component arrays
+    # nested in array expressions:
+    from sympy.abc import x, y, z, t
+    A = Array([[x, y], [z, t]])
+    assert ArrayTensorProduct(A, A).as_explicit() == tensorproduct(A, A)
+    assert ArrayDiagonal(A, (0, 1)).as_explicit() == tensordiagonal(A, (0, 1))
+    assert ArrayContraction(A, (0, 1)).as_explicit() == tensorcontraction(A, (0, 1))
+    assert ArrayAdd(A, A).as_explicit() == A + A
+    assert ArrayElementwiseApplyFunc(sin, A).as_explicit() == A.applyfunc(sin)
+    assert PermuteDims(A, [1, 0]).as_explicit() == permutedims(A, [1, 0])
+    assert Reshape(A, [4]).as_explicit() == A.reshape(4)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_arrayexpr_derivatives.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_arrayexpr_derivatives.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc0fcf63f2607b23feb38758e4f0994de4f0384b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_arrayexpr_derivatives.py
@@ -0,0 +1,78 @@
+from sympy.core.symbol import symbols
+from sympy.functions.elementary.trigonometric import (cos, sin)
+from sympy.matrices.expressions.matexpr import MatrixSymbol
+from sympy.matrices.expressions.special import Identity
+from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
+from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayTensorProduct, \
+    PermuteDims, ArrayDiagonal, ArrayElementwiseApplyFunc, ArrayContraction, _permute_dims, Reshape
+from sympy.tensor.array.expressions.arrayexpr_derivatives import array_derive
+
+k = symbols("k")
+
+I = Identity(k)
+X = MatrixSymbol("X", k, k)
+x = MatrixSymbol("x", k, 1)
+
+A = MatrixSymbol("A", k, k)
+B = MatrixSymbol("B", k, k)
+C = MatrixSymbol("C", k, k)
+D = MatrixSymbol("D", k, k)
+
+A1 = ArraySymbol("A", (3, 2, k))
+
+
+def test_arrayexpr_derivatives1():
+
+    res = array_derive(X, X)
+    assert res == PermuteDims(ArrayTensorProduct(I, I), [0, 2, 1, 3])
+
+    cg = ArrayTensorProduct(A, X, B)
+    res = array_derive(cg, X)
+    assert res == _permute_dims(
+        ArrayTensorProduct(I, A, I, B),
+        [0, 4, 2, 3, 1, 5, 6, 7])
+
+    cg = ArrayContraction(X, (0, 1))
+    res = array_derive(cg, X)
+    assert res == ArrayContraction(ArrayTensorProduct(I, I), (1, 3))
+
+    cg = ArrayDiagonal(X, (0, 1))
+    res = array_derive(cg, X)
+    assert res == ArrayDiagonal(ArrayTensorProduct(I, I), (1, 3))
+
+    cg = ElementwiseApplyFunction(sin, X)
+    res = array_derive(cg, X)
+    assert res.dummy_eq(ArrayDiagonal(
+        ArrayTensorProduct(
+            ElementwiseApplyFunction(cos, X),
+            I,
+            I
+        ), (0, 3), (1, 5)))
+
+    cg = ArrayElementwiseApplyFunc(sin, X)
+    res = array_derive(cg, X)
+    assert res.dummy_eq(ArrayDiagonal(
+        ArrayTensorProduct(
+            I,
+            I,
+            ArrayElementwiseApplyFunc(cos, X)
+        ), (1, 4), (3, 5)))
+
+    res = array_derive(A1, A1)
+    assert res == PermuteDims(
+        ArrayTensorProduct(Identity(3), Identity(2), Identity(k)),
+        [0, 2, 4, 1, 3, 5]
+    )
+
+    cg = ArrayElementwiseApplyFunc(sin, A1)
+    res = array_derive(cg, A1)
+    assert res.dummy_eq(ArrayDiagonal(
+        ArrayTensorProduct(
+            Identity(3), Identity(2), Identity(k),
+            ArrayElementwiseApplyFunc(cos, A1)
+        ), (1, 6), (3, 7), (5, 8)
+    ))
+
+    cg = Reshape(A, (k**2,))
+    res = array_derive(cg, A)
+    assert res == Reshape(PermuteDims(ArrayTensorProduct(I, I), [0, 2, 1, 3]), (k, k, k**2))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_as_explicit.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_as_explicit.py
new file mode 100644
index 0000000000000000000000000000000000000000..30cc61b1ee651ca032e165cd67926fa33c71354f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_as_explicit.py
@@ -0,0 +1,63 @@
+from sympy.core.symbol import Symbol
+from sympy.matrices.expressions.matexpr import MatrixSymbol
+from sympy.tensor.array.arrayop import (permutedims, tensorcontraction, tensordiagonal, tensorproduct)
+from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
+from sympy.tensor.array.expressions.array_expressions import ZeroArray, OneArray, ArraySymbol, \
+    ArrayTensorProduct, PermuteDims, ArrayDiagonal, ArrayContraction, ArrayAdd
+from sympy.testing.pytest import raises
+
+
+def test_array_as_explicit_call():
+
+    assert ZeroArray(3, 2, 4).as_explicit() == ImmutableDenseNDimArray.zeros(3, 2, 4)
+    assert OneArray(3, 2, 4).as_explicit() == ImmutableDenseNDimArray([1 for i in range(3*2*4)]).reshape(3, 2, 4)
+
+    k = Symbol("k")
+    X = ArraySymbol("X", (k, 3, 2))
+    raises(ValueError, lambda: X.as_explicit())
+    raises(ValueError, lambda: ZeroArray(k, 2, 3).as_explicit())
+    raises(ValueError, lambda: OneArray(2, k, 2).as_explicit())
+
+    A = ArraySymbol("A", (3, 3))
+    B = ArraySymbol("B", (3, 3))
+
+    texpr = tensorproduct(A, B)
+    assert isinstance(texpr, ArrayTensorProduct)
+    assert texpr.as_explicit() == tensorproduct(A.as_explicit(), B.as_explicit())
+
+    texpr = tensorcontraction(A, (0, 1))
+    assert isinstance(texpr, ArrayContraction)
+    assert texpr.as_explicit() == A[0, 0] + A[1, 1] + A[2, 2]
+
+    texpr = tensordiagonal(A, (0, 1))
+    assert isinstance(texpr, ArrayDiagonal)
+    assert texpr.as_explicit() == ImmutableDenseNDimArray([A[0, 0], A[1, 1], A[2, 2]])
+
+    texpr = permutedims(A, [1, 0])
+    assert isinstance(texpr, PermuteDims)
+    assert texpr.as_explicit() == permutedims(A.as_explicit(), [1, 0])
+
+
+def test_array_as_explicit_matrix_symbol():
+
+    A = MatrixSymbol("A", 3, 3)
+    B = MatrixSymbol("B", 3, 3)
+
+    texpr = tensorproduct(A, B)
+    assert isinstance(texpr, ArrayTensorProduct)
+    assert texpr.as_explicit() == tensorproduct(A.as_explicit(), B.as_explicit())
+
+    texpr = tensorcontraction(A, (0, 1))
+    assert isinstance(texpr, ArrayContraction)
+    assert texpr.as_explicit() == A[0, 0] + A[1, 1] + A[2, 2]
+
+    texpr = tensordiagonal(A, (0, 1))
+    assert isinstance(texpr, ArrayDiagonal)
+    assert texpr.as_explicit() == ImmutableDenseNDimArray([A[0, 0], A[1, 1], A[2, 2]])
+
+    texpr = permutedims(A, [1, 0])
+    assert isinstance(texpr, PermuteDims)
+    assert texpr.as_explicit() == permutedims(A.as_explicit(), [1, 0])
+
+    expr = ArrayAdd(ArrayTensorProduct(A, B), ArrayTensorProduct(B, A))
+    assert expr.as_explicit() == expr.args[0].as_explicit() + expr.args[1].as_explicit()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_convert_array_to_indexed.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_convert_array_to_indexed.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6b713fbec94ab7808c5a8a778b3313402d9d0c7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_convert_array_to_indexed.py
@@ -0,0 +1,61 @@
+from sympy import Sum, Dummy, sin
+from sympy.tensor.array.expressions import ArraySymbol, ArrayTensorProduct, ArrayContraction, PermuteDims, \
+    ArrayDiagonal, ArrayAdd, OneArray, ZeroArray, convert_indexed_to_array, ArrayElementwiseApplyFunc, Reshape
+from sympy.tensor.array.expressions.from_array_to_indexed import convert_array_to_indexed
+
+from sympy.abc import i, j, k, l, m, n, o
+
+
+def test_convert_array_to_indexed_main():
+    A = ArraySymbol("A", (3, 3, 3))
+    B = ArraySymbol("B", (3, 3))
+    C = ArraySymbol("C", (3, 3))
+
+    d_ = Dummy("d_")
+
+    assert convert_array_to_indexed(A, [i, j, k]) == A[i, j, k]
+
+    expr = ArrayTensorProduct(A, B, C)
+    conv = convert_array_to_indexed(expr, [i,j,k,l,m,n,o])
+    assert conv == A[i,j,k]*B[l,m]*C[n,o]
+    assert convert_indexed_to_array(conv, [i,j,k,l,m,n,o]) == expr
+
+    expr = ArrayContraction(A, (0, 2))
+    assert convert_array_to_indexed(expr, [i]).dummy_eq(Sum(A[d_, i, d_], (d_, 0, 2)))
+
+    expr = ArrayDiagonal(A, (0, 2))
+    assert convert_array_to_indexed(expr, [i, j]) == A[j, i, j]
+
+    expr = PermuteDims(A, [1, 2, 0])
+    conv = convert_array_to_indexed(expr, [i, j, k])
+    assert conv == A[k, i, j]
+    assert convert_indexed_to_array(conv, [i, j, k]) == expr
+
+    expr = ArrayAdd(B, C, PermuteDims(C, [1, 0]))
+    conv = convert_array_to_indexed(expr, [i, j])
+    assert conv == B[i, j] + C[i, j] + C[j, i]
+    assert convert_indexed_to_array(conv, [i, j]) == expr
+
+    expr = ArrayElementwiseApplyFunc(sin, A)
+    conv = convert_array_to_indexed(expr, [i, j, k])
+    assert conv == sin(A[i, j, k])
+    assert convert_indexed_to_array(conv, [i, j, k]).dummy_eq(expr)
+
+    assert convert_array_to_indexed(OneArray(3, 3), [i, j]) == 1
+    assert convert_array_to_indexed(ZeroArray(3, 3), [i, j]) == 0
+
+    expr = Reshape(A, (27,))
+    assert convert_array_to_indexed(expr, [i]) == A[i // 9, i // 3 % 3, i % 3]
+
+    X = ArraySymbol("X", (2, 3, 4, 5, 6))
+    expr = Reshape(X, (2*3*4*5*6,))
+    assert convert_array_to_indexed(expr, [i]) == X[i // 360, i // 120 % 3, i // 30 % 4, i // 6 % 5, i % 6]
+
+    expr = Reshape(X, (4, 9, 2, 2, 5))
+    one_index = 180*i + 20*j + 10*k + 5*l + m
+    expected = X[one_index // (3*4*5*6), one_index // (4*5*6) % 3, one_index // (5*6) % 4, one_index // 6 % 5, one_index % 6]
+    assert convert_array_to_indexed(expr, [i, j, k, l, m]) == expected
+
+    X = ArraySymbol("X", (2*3*5,))
+    expr = Reshape(X, (2, 3, 5))
+    assert convert_array_to_indexed(expr, [i, j, k]) == X[15*i + 5*j + k]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_convert_array_to_matrix.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_convert_array_to_matrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..26839d5e7cec0554948c6b726482f9d8ca250b1c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_convert_array_to_matrix.py
@@ -0,0 +1,689 @@
+from sympy import Lambda, S, Dummy, KroneckerProduct
+from sympy.core.symbol import symbols
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import cos, sin
+from sympy.matrices.expressions.hadamard import HadamardProduct, HadamardPower
+from sympy.matrices.expressions.special import (Identity, OneMatrix, ZeroMatrix)
+from sympy.matrices.expressions.matexpr import MatrixElement
+from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
+from sympy.tensor.array.expressions.from_array_to_matrix import _support_function_tp1_recognize, \
+    _array_diag2contr_diagmatrix, convert_array_to_matrix, _remove_trivial_dims, _array2matrix, \
+    _combine_removed, identify_removable_identity_matrices, _array_contraction_to_diagonal_multiple_identity
+from sympy.matrices.expressions.matexpr import MatrixSymbol
+from sympy.combinatorics import Permutation
+from sympy.matrices.expressions.diagonal import DiagMatrix, DiagonalMatrix
+from sympy.matrices import Trace, MatMul, Transpose
+from sympy.tensor.array.expressions.array_expressions import ZeroArray, OneArray, \
+    ArrayElement, ArraySymbol, ArrayElementwiseApplyFunc, _array_tensor_product, _array_contraction, \
+    _array_diagonal, _permute_dims, PermuteDims, ArrayAdd, ArrayDiagonal, ArrayContraction, ArrayTensorProduct
+from sympy.testing.pytest import raises
+
+
+i, j, k, l, m, n = symbols("i j k l m n")
+
+I = Identity(k)
+I1 = Identity(1)
+
+M = MatrixSymbol("M", k, k)
+N = MatrixSymbol("N", k, k)
+P = MatrixSymbol("P", k, k)
+Q = MatrixSymbol("Q", k, k)
+
+A = MatrixSymbol("A", k, k)
+B = MatrixSymbol("B", k, k)
+C = MatrixSymbol("C", k, k)
+D = MatrixSymbol("D", k, k)
+
+X = MatrixSymbol("X", k, k)
+Y = MatrixSymbol("Y", k, k)
+
+a = MatrixSymbol("a", k, 1)
+b = MatrixSymbol("b", k, 1)
+c = MatrixSymbol("c", k, 1)
+d = MatrixSymbol("d", k, 1)
+
+x = MatrixSymbol("x", k, 1)
+y = MatrixSymbol("y", k, 1)
+
+
+def test_arrayexpr_convert_array_to_matrix():
+
+    cg = _array_contraction(_array_tensor_product(M), (0, 1))
+    assert convert_array_to_matrix(cg) == Trace(M)
+
+    cg = _array_contraction(_array_tensor_product(M, N), (0, 1), (2, 3))
+    assert convert_array_to_matrix(cg) == Trace(M) * Trace(N)
+
+    cg = _array_contraction(_array_tensor_product(M, N), (0, 3), (1, 2))
+    assert convert_array_to_matrix(cg) == Trace(M * N)
+
+    cg = _array_contraction(_array_tensor_product(M, N), (0, 2), (1, 3))
+    assert convert_array_to_matrix(cg) == Trace(M * N.T)
+
+    cg = convert_matrix_to_array(M * N * P)
+    assert convert_array_to_matrix(cg) == M * N * P
+
+    cg = convert_matrix_to_array(M * N.T * P)
+    assert convert_array_to_matrix(cg) == M * N.T * P
+
+    cg = _array_contraction(_array_tensor_product(M,N,P,Q), (1, 2), (5, 6))
+    assert convert_array_to_matrix(cg) == _array_tensor_product(M * N, P * Q)
+
+    cg = _array_contraction(_array_tensor_product(-2, M, N), (1, 2))
+    assert convert_array_to_matrix(cg) == -2 * M * N
+
+    a = MatrixSymbol("a", k, 1)
+    b = MatrixSymbol("b", k, 1)
+    c = MatrixSymbol("c", k, 1)
+    cg = PermuteDims(
+        _array_contraction(
+            _array_tensor_product(
+                a,
+                ArrayAdd(
+                    _array_tensor_product(b, c),
+                    _array_tensor_product(c, b),
+                )
+            ), (2, 4)), [0, 1, 3, 2])
+    assert convert_array_to_matrix(cg) == a * (b.T * c + c.T * b)
+
+    za = ZeroArray(m, n)
+    assert convert_array_to_matrix(za) == ZeroMatrix(m, n)
+
+    cg = _array_tensor_product(3, M)
+    assert convert_array_to_matrix(cg) == 3 * M
+
+    # Partial conversion to matrix multiplication:
+    expr = _array_contraction(_array_tensor_product(M, N, P, Q), (0, 2), (1, 4, 6))
+    assert convert_array_to_matrix(expr) == _array_contraction(_array_tensor_product(M.T*N, P, Q), (0, 2, 4))
+
+    x = MatrixSymbol("x", k, 1)
+    cg = PermuteDims(
+        _array_contraction(_array_tensor_product(OneArray(1), x, OneArray(1), DiagMatrix(Identity(1))),
+                                (0, 5)), Permutation(1, 2, 3))
+    assert convert_array_to_matrix(cg) == x
+
+    expr = ArrayAdd(M, PermuteDims(M, [1, 0]))
+    assert convert_array_to_matrix(expr) == M + Transpose(M)
+
+
+def test_arrayexpr_convert_array_to_matrix2():
+    cg = _array_contraction(_array_tensor_product(M, N), (1, 3))
+    assert convert_array_to_matrix(cg) == M * N.T
+
+    cg = PermuteDims(_array_tensor_product(M, N), Permutation([0, 1, 3, 2]))
+    assert convert_array_to_matrix(cg) == _array_tensor_product(M, N.T)
+
+    cg = _array_tensor_product(M, PermuteDims(N, Permutation([1, 0])))
+    assert convert_array_to_matrix(cg) == _array_tensor_product(M, N.T)
+
+    cg = _array_contraction(
+        PermuteDims(
+            _array_tensor_product(M, N, P, Q), Permutation([0, 2, 3, 1, 4, 5, 7, 6])),
+        (1, 2), (3, 5)
+    )
+    assert convert_array_to_matrix(cg) == _array_tensor_product(M * P.T * Trace(N), Q.T)
+
+    cg = _array_contraction(
+        _array_tensor_product(M, N, P, PermuteDims(Q, Permutation([1, 0]))),
+        (1, 5), (2, 3)
+    )
+    assert convert_array_to_matrix(cg) == _array_tensor_product(M * P.T * Trace(N), Q.T)
+
+    cg = _array_tensor_product(M, PermuteDims(N, [1, 0]))
+    assert convert_array_to_matrix(cg) == _array_tensor_product(M, N.T)
+
+    cg = _array_tensor_product(PermuteDims(M, [1, 0]), PermuteDims(N, [1, 0]))
+    assert convert_array_to_matrix(cg) == _array_tensor_product(M.T, N.T)
+
+    cg = _array_tensor_product(PermuteDims(N, [1, 0]), PermuteDims(M, [1, 0]))
+    assert convert_array_to_matrix(cg) == _array_tensor_product(N.T, M.T)
+
+    cg = _array_contraction(M, (0,), (1,))
+    assert convert_array_to_matrix(cg) == OneMatrix(1, k)*M*OneMatrix(k, 1)
+
+    cg = _array_contraction(x, (0,), (1,))
+    assert convert_array_to_matrix(cg) == OneMatrix(1, k)*x
+
+    Xm = MatrixSymbol("Xm", m, n)
+    cg = _array_contraction(Xm, (0,), (1,))
+    assert convert_array_to_matrix(cg) == OneMatrix(1, m)*Xm*OneMatrix(n, 1)
+
+
+def test_arrayexpr_convert_array_to_diagonalized_vector():
+
+    # Check matrix recognition over trivial dimensions:
+
+    cg = _array_tensor_product(a, b)
+    assert convert_array_to_matrix(cg) == a * b.T
+
+    cg = _array_tensor_product(I1, a, b)
+    assert convert_array_to_matrix(cg) == a * b.T
+
+    # Recognize trace inside a tensor product:
+
+    cg = _array_contraction(_array_tensor_product(A, B, C), (0, 3), (1, 2))
+    assert convert_array_to_matrix(cg) == Trace(A * B) * C
+
+    # Transform diagonal operator to contraction:
+
+    cg = _array_diagonal(_array_tensor_product(A, a), (1, 2))
+    assert _array_diag2contr_diagmatrix(cg) == _array_contraction(_array_tensor_product(A, OneArray(1), DiagMatrix(a)), (1, 3))
+    assert convert_array_to_matrix(cg) == A * DiagMatrix(a)
+
+    cg = _array_diagonal(_array_tensor_product(a, b), (0, 2))
+    assert _array_diag2contr_diagmatrix(cg) == _permute_dims(
+        _array_contraction(_array_tensor_product(DiagMatrix(a), OneArray(1), b), (0, 3)), [1, 2, 0]
+    )
+    assert convert_array_to_matrix(cg) == b.T * DiagMatrix(a)
+
+    cg = _array_diagonal(_array_tensor_product(A, a), (0, 2))
+    assert _array_diag2contr_diagmatrix(cg) == _array_contraction(_array_tensor_product(A, OneArray(1), DiagMatrix(a)), (0, 3))
+    assert convert_array_to_matrix(cg) == A.T * DiagMatrix(a)
+
+    cg = _array_diagonal(_array_tensor_product(I, x, I1), (0, 2), (3, 5))
+    assert _array_diag2contr_diagmatrix(cg) == _array_contraction(_array_tensor_product(I, OneArray(1), I1, DiagMatrix(x)), (0, 5))
+    assert convert_array_to_matrix(cg) == DiagMatrix(x)
+
+    cg = _array_diagonal(_array_tensor_product(I, x, A, B), (1, 2), (5, 6))
+    assert _array_diag2contr_diagmatrix(cg) == _array_diagonal(_array_contraction(_array_tensor_product(I, OneArray(1), A, B, DiagMatrix(x)), (1, 7)), (5, 6))
+    # TODO: this is returning a wrong result:
+    # convert_array_to_matrix(cg)
+
+    cg = _array_diagonal(_array_tensor_product(I1, a, b), (1, 3, 5))
+    assert convert_array_to_matrix(cg) == a*b.T
+
+    cg = _array_diagonal(_array_tensor_product(I1, a, b), (1, 3))
+    assert _array_diag2contr_diagmatrix(cg) == _array_contraction(_array_tensor_product(OneArray(1), a, b, I1), (2, 6))
+    assert convert_array_to_matrix(cg) == a*b.T
+
+    cg = _array_diagonal(_array_tensor_product(x, I1), (1, 2))
+    assert isinstance(cg, ArrayDiagonal)
+    assert cg.diagonal_indices == ((1, 2),)
+    assert convert_array_to_matrix(cg) == x
+
+    cg = _array_diagonal(_array_tensor_product(x, I), (0, 2))
+    assert _array_diag2contr_diagmatrix(cg) == _array_contraction(_array_tensor_product(OneArray(1), I, DiagMatrix(x)), (1, 3))
+    assert convert_array_to_matrix(cg).doit() == DiagMatrix(x)
+
+    raises(ValueError, lambda: _array_diagonal(x, (1,)))
+
+    # Ignore identity matrices with contractions:
+
+    cg = _array_contraction(_array_tensor_product(I, A, I, I), (0, 2), (1, 3), (5, 7))
+    assert cg.split_multiple_contractions() == cg
+    assert convert_array_to_matrix(cg) == Trace(A) * I
+
+    cg = _array_contraction(_array_tensor_product(Trace(A) * I, I, I), (1, 5), (3, 4))
+    assert cg.split_multiple_contractions() == cg
+    assert convert_array_to_matrix(cg).doit() == Trace(A) * I
+
+    # Add DiagMatrix when required:
+
+    cg = _array_contraction(_array_tensor_product(A, a), (1, 2))
+    assert cg.split_multiple_contractions() == cg
+    assert convert_array_to_matrix(cg) == A * a
+
+    cg = _array_contraction(_array_tensor_product(A, a, B), (1, 2, 4))
+    assert cg.split_multiple_contractions() == _array_contraction(_array_tensor_product(A, DiagMatrix(a), OneArray(1), B), (1, 2), (3, 5))
+    assert convert_array_to_matrix(cg) == A * DiagMatrix(a) * B
+
+    cg = _array_contraction(_array_tensor_product(A, a, B), (0, 2, 4))
+    assert cg.split_multiple_contractions() == _array_contraction(_array_tensor_product(A, DiagMatrix(a), OneArray(1), B), (0, 2), (3, 5))
+    assert convert_array_to_matrix(cg) == A.T * DiagMatrix(a) * B
+
+    cg = _array_contraction(_array_tensor_product(A, a, b, a.T, B), (0, 2, 4, 7, 9))
+    assert cg.split_multiple_contractions() == _array_contraction(_array_tensor_product(A, DiagMatrix(a), OneArray(1),
+                                                DiagMatrix(b), OneArray(1), DiagMatrix(a), OneArray(1), B),
+                                               (0, 2), (3, 5), (6, 9), (8, 12))
+    assert convert_array_to_matrix(cg) == A.T * DiagMatrix(a) * DiagMatrix(b) * DiagMatrix(a) * B.T
+
+    cg = _array_contraction(_array_tensor_product(I1, I1, I1), (1, 2, 4))
+    assert cg.split_multiple_contractions() == _array_contraction(_array_tensor_product(I1, I1, OneArray(1), I1), (1, 2), (3, 5))
+    assert convert_array_to_matrix(cg) == 1
+
+    cg = _array_contraction(_array_tensor_product(I, I, I, I, A), (1, 2, 8), (5, 6, 9))
+    assert convert_array_to_matrix(cg.split_multiple_contractions()).doit() == A
+
+    cg = _array_contraction(_array_tensor_product(A, a, C, a, B), (1, 2, 4), (5, 6, 8))
+    expected = _array_contraction(_array_tensor_product(A, DiagMatrix(a), OneArray(1), C, DiagMatrix(a), OneArray(1), B), (1, 3), (2, 5), (6, 7), (8, 10))
+    assert cg.split_multiple_contractions() == expected
+    assert convert_array_to_matrix(cg) == A * DiagMatrix(a) * C * DiagMatrix(a) * B
+
+    cg = _array_contraction(_array_tensor_product(a, I1, b, I1, (a.T*b).applyfunc(cos)), (1, 2, 8), (5, 6, 9))
+    expected = _array_contraction(_array_tensor_product(a, I1, OneArray(1), b, I1, OneArray(1), (a.T*b).applyfunc(cos)),
+                                (1, 3), (2, 10), (6, 8), (7, 11))
+    assert cg.split_multiple_contractions().dummy_eq(expected)
+    assert convert_array_to_matrix(cg).doit().dummy_eq(MatMul(a, (a.T * b).applyfunc(cos), b.T))
+
+
+def test_arrayexpr_convert_array_contraction_tp_additions():
+    a = ArrayAdd(
+        _array_tensor_product(M, N),
+        _array_tensor_product(N, M)
+    )
+    tp = _array_tensor_product(P, a, Q)
+    expr = _array_contraction(tp, (3, 4))
+    expected = _array_tensor_product(
+        P,
+        ArrayAdd(
+            _array_contraction(_array_tensor_product(M, N), (1, 2)),
+            _array_contraction(_array_tensor_product(N, M), (1, 2)),
+        ),
+        Q
+    )
+    assert expr == expected
+    assert convert_array_to_matrix(expr) == _array_tensor_product(P, M * N + N * M, Q)
+
+    expr = _array_contraction(tp, (1, 2), (3, 4), (5, 6))
+    result = _array_contraction(
+        _array_tensor_product(
+            P,
+            ArrayAdd(
+                _array_contraction(_array_tensor_product(M, N), (1, 2)),
+                _array_contraction(_array_tensor_product(N, M), (1, 2)),
+            ),
+            Q
+        ), (1, 2), (3, 4))
+    assert expr == result
+    assert convert_array_to_matrix(expr) == P * (M * N + N * M) * Q
+
+
+def test_arrayexpr_convert_array_to_implicit_matmul():
+    # Trivial dimensions are suppressed, so the result can be expressed in matrix form:
+
+    cg = _array_tensor_product(a, b)
+    assert convert_array_to_matrix(cg) == a * b.T
+
+    cg = _array_tensor_product(a, b, I)
+    assert convert_array_to_matrix(cg) == _array_tensor_product(a*b.T, I)
+
+    cg = _array_tensor_product(I, a, b)
+    assert convert_array_to_matrix(cg) == _array_tensor_product(I, a*b.T)
+
+    cg = _array_tensor_product(a, I, b)
+    assert convert_array_to_matrix(cg) == _array_tensor_product(a, I, b)
+
+    cg = _array_contraction(_array_tensor_product(I, I), (1, 2))
+    assert convert_array_to_matrix(cg) == I
+
+    cg = PermuteDims(_array_tensor_product(I, Identity(1)), [0, 2, 1, 3])
+    assert convert_array_to_matrix(cg) == I
+
+
+def test_arrayexpr_convert_array_to_matrix_remove_trivial_dims():
+
+    # Tensor Product:
+    assert _remove_trivial_dims(_array_tensor_product(a, b)) == (a * b.T, [1, 3])
+    assert _remove_trivial_dims(_array_tensor_product(a.T, b)) == (a * b.T, [0, 3])
+    assert _remove_trivial_dims(_array_tensor_product(a, b.T)) == (a * b.T, [1, 2])
+    assert _remove_trivial_dims(_array_tensor_product(a.T, b.T)) == (a * b.T, [0, 2])
+
+    assert _remove_trivial_dims(_array_tensor_product(I, a.T, b.T)) == (_array_tensor_product(I, a * b.T), [2, 4])
+    assert _remove_trivial_dims(_array_tensor_product(a.T, I, b.T)) == (_array_tensor_product(a.T, I, b.T), [])
+
+    assert _remove_trivial_dims(_array_tensor_product(a, I)) == (_array_tensor_product(a, I), [])
+    assert _remove_trivial_dims(_array_tensor_product(I, a)) == (_array_tensor_product(I, a), [])
+
+    assert _remove_trivial_dims(_array_tensor_product(a.T, b.T, c, d)) == (
+        _array_tensor_product(a * b.T, c * d.T), [0, 2, 5, 7])
+    assert _remove_trivial_dims(_array_tensor_product(a.T, I, b.T, c, d, I)) == (
+        _array_tensor_product(a.T, I, b*c.T, d, I), [4, 7])
+
+    # Addition:
+
+    cg = ArrayAdd(_array_tensor_product(a, b), _array_tensor_product(c, d))
+    assert _remove_trivial_dims(cg) == (a * b.T + c * d.T, [1, 3])
+
+    # Permute Dims:
+
+    cg = PermuteDims(_array_tensor_product(a, b), Permutation(3)(1, 2))
+    assert _remove_trivial_dims(cg) == (a * b.T, [2, 3])
+
+    cg = PermuteDims(_array_tensor_product(a, I, b), Permutation(5)(1, 2, 3, 4))
+    assert _remove_trivial_dims(cg) == (cg, [])
+
+    cg = PermuteDims(_array_tensor_product(I, b, a), Permutation(5)(1, 2, 4, 5, 3))
+    assert _remove_trivial_dims(cg) == (PermuteDims(_array_tensor_product(I, b * a.T), [0, 2, 3, 1]), [4, 5])
+
+    # Diagonal:
+
+    cg = _array_diagonal(_array_tensor_product(M, a), (1, 2))
+    assert _remove_trivial_dims(cg) == (cg, [])
+
+    # Contraction:
+
+    cg = _array_contraction(_array_tensor_product(M, a), (1, 2))
+    assert _remove_trivial_dims(cg) == (cg, [])
+
+    # A few more cases to test the removal and shift of nested removed axes
+    # with array contractions and array diagonals:
+    tp = _array_tensor_product(
+        OneMatrix(1, 1),
+        M,
+        x,
+        OneMatrix(1, 1),
+        Identity(1),
+    )
+
+    expr = _array_contraction(tp, (1, 8))
+    rexpr, removed = _remove_trivial_dims(expr)
+    assert removed == [0, 5, 6, 7]
+
+    expr = _array_contraction(tp, (1, 8), (3, 4))
+    rexpr, removed = _remove_trivial_dims(expr)
+    assert removed == [0, 3, 4, 5]
+
+    expr = _array_diagonal(tp, (1, 8))
+    rexpr, removed = _remove_trivial_dims(expr)
+    assert removed == [0, 5, 6, 7, 8]
+
+    expr = _array_diagonal(tp, (1, 8), (3, 4))
+    rexpr, removed = _remove_trivial_dims(expr)
+    assert removed == [0, 3, 4, 5, 6]
+
+    expr = _array_diagonal(_array_contraction(_array_tensor_product(A, x, I, I1), (1, 2, 5)), (1, 4))
+    rexpr, removed = _remove_trivial_dims(expr)
+    assert removed == [2, 3]
+
+    cg = _array_diagonal(_array_tensor_product(PermuteDims(_array_tensor_product(x, I1), Permutation(1, 2, 3)), (x.T*x).applyfunc(sqrt)), (2, 4), (3, 5))
+    rexpr, removed = _remove_trivial_dims(cg)
+    assert removed == [1, 2]
+
+    # Contractions with identity matrices need to be followed by a permutation
+    # in order
+    cg = _array_contraction(_array_tensor_product(A, B, C, M, I), (1, 8))
+    ret, removed = _remove_trivial_dims(cg)
+    assert ret == PermuteDims(_array_tensor_product(A, B, C, M), [0, 2, 3, 4, 5, 6, 7, 1])
+    assert removed == []
+
+    cg = _array_contraction(_array_tensor_product(A, B, C, M, I), (1, 8), (3, 4))
+    ret, removed = _remove_trivial_dims(cg)
+    assert ret == PermuteDims(_array_contraction(_array_tensor_product(A, B, C, M), (3, 4)), [0, 2, 3, 4, 5, 1])
+    assert removed == []
+
+    # Trivial matrices are sometimes inserted into MatMul expressions:
+
+    cg = _array_tensor_product(b*b.T, a.T*a)
+    ret, removed = _remove_trivial_dims(cg)
+    assert ret == b*a.T*a*b.T
+    assert removed == [2, 3]
+
+    Xs = ArraySymbol("X", (3, 2, k))
+    cg = _array_tensor_product(M, Xs, b.T*c, a*a.T, b*b.T, c.T*d)
+    ret, removed = _remove_trivial_dims(cg)
+    assert ret == _array_tensor_product(M, Xs, a*b.T*c*c.T*d*a.T, b*b.T)
+    assert removed == [5, 6, 11, 12]
+
+    cg = _array_diagonal(_array_tensor_product(I, I1, x), (1, 4), (3, 5))
+    assert _remove_trivial_dims(cg) == (PermuteDims(_array_diagonal(_array_tensor_product(I, x), (1, 2)), Permutation(1, 2)), [1])
+
+    expr = _array_diagonal(_array_tensor_product(x, I, y), (0, 2))
+    assert _remove_trivial_dims(expr) == (PermuteDims(_array_tensor_product(DiagMatrix(x), y), [1, 2, 3, 0]), [0])
+
+    expr = _array_diagonal(_array_tensor_product(x, I, y), (0, 2), (3, 4))
+    assert _remove_trivial_dims(expr) == (expr, [])
+
+
+def test_arrayexpr_convert_array_to_matrix_diag2contraction_diagmatrix():
+    cg = _array_diagonal(_array_tensor_product(M, a), (1, 2))
+    res = _array_diag2contr_diagmatrix(cg)
+    assert res.shape == cg.shape
+    assert res == _array_contraction(_array_tensor_product(M, OneArray(1), DiagMatrix(a)), (1, 3))
+
+    raises(ValueError, lambda: _array_diagonal(_array_tensor_product(a, M), (1, 2)))
+
+    cg = _array_diagonal(_array_tensor_product(a.T, M), (1, 2))
+    res = _array_diag2contr_diagmatrix(cg)
+    assert res.shape == cg.shape
+    assert res == _array_contraction(_array_tensor_product(OneArray(1), M, DiagMatrix(a.T)), (1, 4))
+
+    cg = _array_diagonal(_array_tensor_product(a.T, M, N, b.T), (1, 2), (4, 7))
+    res = _array_diag2contr_diagmatrix(cg)
+    assert res.shape == cg.shape
+    assert res == _array_contraction(
+        _array_tensor_product(OneArray(1), M, N, OneArray(1), DiagMatrix(a.T), DiagMatrix(b.T)), (1, 7), (3, 9))
+
+    cg = _array_diagonal(_array_tensor_product(a, M, N, b.T), (0, 2), (4, 7))
+    res = _array_diag2contr_diagmatrix(cg)
+    assert res.shape == cg.shape
+    assert res == _array_contraction(
+        _array_tensor_product(OneArray(1), M, N, OneArray(1), DiagMatrix(a), DiagMatrix(b.T)), (1, 6), (3, 9))
+
+    cg = _array_diagonal(_array_tensor_product(a, M, N, b.T), (0, 4), (3, 7))
+    res = _array_diag2contr_diagmatrix(cg)
+    assert res.shape == cg.shape
+    assert res == _array_contraction(
+        _array_tensor_product(OneArray(1), M, N, OneArray(1), DiagMatrix(a), DiagMatrix(b.T)), (3, 6), (2, 9))
+
+    I1 = Identity(1)
+    x = MatrixSymbol("x", k, 1)
+    A = MatrixSymbol("A", k, k)
+    cg = _array_diagonal(_array_tensor_product(x, A.T, I1), (0, 2))
+    assert _array_diag2contr_diagmatrix(cg).shape == cg.shape
+    assert _array2matrix(cg).shape == cg.shape
+
+
+def test_arrayexpr_convert_array_to_matrix_support_function():
+
+    assert _support_function_tp1_recognize([], [2 * k]) == 2 * k
+
+    assert _support_function_tp1_recognize([(1, 2)], [A, 2 * k, B, 3]) == 6 * k * A * B
+
+    assert _support_function_tp1_recognize([(0, 3), (1, 2)], [A, B]) == Trace(A * B)
+
+    assert _support_function_tp1_recognize([(1, 2)], [A, B]) == A * B
+    assert _support_function_tp1_recognize([(0, 2)], [A, B]) == A.T * B
+    assert _support_function_tp1_recognize([(1, 3)], [A, B]) == A * B.T
+    assert _support_function_tp1_recognize([(0, 3)], [A, B]) == A.T * B.T
+
+    assert _support_function_tp1_recognize([(1, 2), (5, 6)], [A, B, C, D]) == _array_tensor_product(A * B, C * D)
+    assert _support_function_tp1_recognize([(1, 4), (3, 6)], [A, B, C, D]) == PermuteDims(
+        _array_tensor_product(A * C, B * D), [0, 2, 1, 3])
+
+    assert _support_function_tp1_recognize([(0, 3), (1, 4)], [A, B, C]) == B * A * C
+
+    assert _support_function_tp1_recognize([(9, 10), (1, 2), (5, 6), (3, 4), (7, 8)],
+                                           [X, Y, A, B, C, D]) == X * Y * A * B * C * D
+
+    assert _support_function_tp1_recognize([(9, 10), (1, 2), (5, 6), (3, 4)],
+                                           [X, Y, A, B, C, D]) == _array_tensor_product(X * Y * A * B, C * D)
+
+    assert _support_function_tp1_recognize([(1, 7), (3, 8), (4, 11)], [X, Y, A, B, C, D]) == PermuteDims(
+        _array_tensor_product(X * B.T, Y * C, A.T * D.T), [0, 2, 4, 1, 3, 5]
+    )
+
+    assert _support_function_tp1_recognize([(0, 1), (3, 6), (5, 8)], [X, A, B, C, D]) == PermuteDims(
+        _array_tensor_product(Trace(X) * A * C, B * D), [0, 2, 1, 3])
+
+    assert _support_function_tp1_recognize([(1, 2), (3, 4), (5, 6), (7, 8)], [A, A, B, C, D]) == A ** 2 * B * C * D
+    assert _support_function_tp1_recognize([(1, 2), (3, 4), (5, 6), (7, 8)], [X, A, B, C, D]) == X * A * B * C * D
+
+    assert _support_function_tp1_recognize([(1, 6), (3, 8), (5, 10)], [X, Y, A, B, C, D]) == PermuteDims(
+        _array_tensor_product(X * B, Y * C, A * D), [0, 2, 4, 1, 3, 5]
+    )
+
+    assert _support_function_tp1_recognize([(1, 4), (3, 6)], [A, B, C, D]) == PermuteDims(
+        _array_tensor_product(A * C, B * D), [0, 2, 1, 3])
+
+    assert _support_function_tp1_recognize([(0, 4), (1, 7), (2, 5), (3, 8)], [X, A, B, C, D]) == C*X.T*B*A*D
+
+    assert _support_function_tp1_recognize([(0, 4), (1, 7), (2, 5), (3, 8)], [X, A, B, C, D]) == C*X.T*B*A*D
+
+
+def test_convert_array_to_hadamard_products():
+
+    expr = HadamardProduct(M, N)
+    cg = convert_matrix_to_array(expr)
+    ret = convert_array_to_matrix(cg)
+    assert ret == expr
+
+    expr = HadamardProduct(M, N)*P
+    cg = convert_matrix_to_array(expr)
+    ret = convert_array_to_matrix(cg)
+    assert ret == expr
+
+    expr = Q*HadamardProduct(M, N)*P
+    cg = convert_matrix_to_array(expr)
+    ret = convert_array_to_matrix(cg)
+    assert ret == expr
+
+    expr = Q*HadamardProduct(M, N.T)*P
+    cg = convert_matrix_to_array(expr)
+    ret = convert_array_to_matrix(cg)
+    assert ret == expr
+
+    expr = HadamardProduct(M, N)*HadamardProduct(Q, P)
+    cg = convert_matrix_to_array(expr)
+    ret = convert_array_to_matrix(cg)
+    assert expr == ret
+
+    expr = P.T*HadamardProduct(M, N)*HadamardProduct(Q, P)
+    cg = convert_matrix_to_array(expr)
+    ret = convert_array_to_matrix(cg)
+    assert expr == ret
+
+    # ArrayDiagonal should be converted
+    cg = _array_diagonal(_array_tensor_product(M, N, Q), (1, 3), (0, 2, 4))
+    ret = convert_array_to_matrix(cg)
+    expected = PermuteDims(_array_diagonal(_array_tensor_product(HadamardProduct(M.T, N.T), Q), (1, 2)), [1, 0, 2])
+    assert expected == ret
+
+    # Special case that should return the same expression:
+    cg = _array_diagonal(_array_tensor_product(HadamardProduct(M, N), Q), (0, 2))
+    ret = convert_array_to_matrix(cg)
+    assert ret == cg
+
+    # Hadamard products with traces:
+
+    expr = Trace(HadamardProduct(M, N))
+    cg = convert_matrix_to_array(expr)
+    ret = convert_array_to_matrix(cg)
+    assert ret == Trace(HadamardProduct(M.T, N.T))
+
+    expr = Trace(A*HadamardProduct(M, N))
+    cg = convert_matrix_to_array(expr)
+    ret = convert_array_to_matrix(cg)
+    assert ret == Trace(HadamardProduct(M, N)*A)
+
+    expr = Trace(HadamardProduct(A, M)*N)
+    cg = convert_matrix_to_array(expr)
+    ret = convert_array_to_matrix(cg)
+    assert ret == Trace(HadamardProduct(M.T, N)*A)
+
+    # These should not be converted into Hadamard products:
+
+    cg = _array_diagonal(_array_tensor_product(M, N), (0, 1, 2, 3))
+    ret = convert_array_to_matrix(cg)
+    assert ret == cg
+
+    cg = _array_diagonal(_array_tensor_product(A), (0, 1))
+    ret = convert_array_to_matrix(cg)
+    assert ret == cg
+
+    cg = _array_diagonal(_array_tensor_product(M, N, P), (0, 2, 4), (1, 3, 5))
+    assert convert_array_to_matrix(cg) == HadamardProduct(M, N, P)
+
+    cg = _array_diagonal(_array_tensor_product(M, N, P), (0, 3, 4), (1, 2, 5))
+    assert convert_array_to_matrix(cg) == HadamardProduct(M, P, N.T)
+
+    cg = _array_diagonal(_array_tensor_product(I, I1, x), (1, 4), (3, 5))
+    assert convert_array_to_matrix(cg) == DiagMatrix(x)
+
+
+def test_identify_removable_identity_matrices():
+
+    D = DiagonalMatrix(MatrixSymbol("D", k, k))
+
+    cg = _array_contraction(_array_tensor_product(A, B, I), (1, 2, 4, 5))
+    expected = _array_contraction(_array_tensor_product(A, B), (1, 2))
+    assert identify_removable_identity_matrices(cg) == expected
+
+    cg = _array_contraction(_array_tensor_product(A, B, C, I), (1, 3, 5, 6, 7))
+    expected = _array_contraction(_array_tensor_product(A, B, C), (1, 3, 5))
+    assert identify_removable_identity_matrices(cg) == expected
+
+    # Tests with diagonal matrices:
+
+    cg = _array_contraction(_array_tensor_product(A, B, D), (1, 2, 4, 5))
+    ret = identify_removable_identity_matrices(cg)
+    expected = _array_contraction(_array_tensor_product(A, B, D), (1, 4), (2, 5))
+    assert ret == expected
+
+    cg = _array_contraction(_array_tensor_product(A, B, D, M, N), (1, 2, 4, 5, 6, 8))
+    ret = identify_removable_identity_matrices(cg)
+    assert ret == cg
+
+
+def test_combine_removed():
+
+    assert _combine_removed(6, [0, 1, 2], [0, 1, 2]) == [0, 1, 2, 3, 4, 5]
+    assert _combine_removed(8, [2, 5], [1, 3, 4]) == [1, 2, 4, 5, 6]
+    assert _combine_removed(8, [7], []) == [7]
+
+
+def test_array_contraction_to_diagonal_multiple_identities():
+
+    expr = _array_contraction(_array_tensor_product(A, B, I, C), (1, 2, 4), (5, 6))
+    assert _array_contraction_to_diagonal_multiple_identity(expr) == (expr, [])
+    assert convert_array_to_matrix(expr) == _array_contraction(_array_tensor_product(A, B, C), (1, 2, 4))
+
+    expr = _array_contraction(_array_tensor_product(A, I, I), (1, 2, 4))
+    assert _array_contraction_to_diagonal_multiple_identity(expr) == (A, [2])
+    assert convert_array_to_matrix(expr) == A
+
+    expr = _array_contraction(_array_tensor_product(A, I, I, B), (1, 2, 4), (3, 6))
+    assert _array_contraction_to_diagonal_multiple_identity(expr) == (expr, [])
+
+    expr = _array_contraction(_array_tensor_product(A, I, I, B), (1, 2, 3, 4, 6))
+    assert _array_contraction_to_diagonal_multiple_identity(expr) == (expr, [])
+
+
+def test_convert_array_element_to_matrix():
+
+    expr = ArrayElement(M, (i, j))
+    assert convert_array_to_matrix(expr) == MatrixElement(M, i, j)
+
+    expr = ArrayElement(_array_contraction(_array_tensor_product(M, N), (1, 3)), (i, j))
+    assert convert_array_to_matrix(expr) == MatrixElement(M*N.T, i, j)
+
+    expr = ArrayElement(_array_tensor_product(M, N), (i, j, m, n))
+    assert convert_array_to_matrix(expr) == expr
+
+
+def test_convert_array_elementwise_function_to_matrix():
+
+    d = Dummy("d")
+
+    expr = ArrayElementwiseApplyFunc(Lambda(d, sin(d)), x.T*y)
+    assert convert_array_to_matrix(expr) == sin(x.T*y)
+
+    expr = ArrayElementwiseApplyFunc(Lambda(d, d**2), x.T*y)
+    assert convert_array_to_matrix(expr) == (x.T*y)**2
+
+    expr = ArrayElementwiseApplyFunc(Lambda(d, sin(d)), x)
+    assert convert_array_to_matrix(expr).dummy_eq(x.applyfunc(sin))
+
+    expr = ArrayElementwiseApplyFunc(Lambda(d, 1 / (2 * sqrt(d))), x)
+    assert convert_array_to_matrix(expr) == S.Half * HadamardPower(x, -S.Half)
+
+
+def test_array2matrix():
+    # See issue https://github.com/sympy/sympy/pull/22877
+    expr = PermuteDims(ArrayContraction(ArrayTensorProduct(x, I, I1, x), (0, 3), (1, 7)), Permutation(2, 3))
+    expected = PermuteDims(ArrayTensorProduct(x*x.T, I1), Permutation(3)(1, 2))
+    assert _array2matrix(expr) == expected
+
+
+def test_recognize_broadcasting():
+    expr = ArrayTensorProduct(x.T*x, A)
+    assert _remove_trivial_dims(expr) == (KroneckerProduct(x.T*x, A), [0, 1])
+
+    expr = ArrayTensorProduct(A, x.T*x)
+    assert _remove_trivial_dims(expr) == (KroneckerProduct(A, x.T*x), [2, 3])
+
+    expr = ArrayTensorProduct(A, B, x.T*x, C)
+    assert _remove_trivial_dims(expr) == (ArrayTensorProduct(A, KroneckerProduct(B, x.T*x), C), [4, 5])
+
+    # Always prefer matrix multiplication to Kronecker product, if possible:
+    expr = ArrayTensorProduct(a, b, x.T*x)
+    assert _remove_trivial_dims(expr) == (a*x.T*x*b.T, [1, 3, 4, 5])
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_convert_indexed_to_array.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_convert_indexed_to_array.py
new file mode 100644
index 0000000000000000000000000000000000000000..258062eadeca041ae3c864dabeefd5165f1cef11
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_convert_indexed_to_array.py
@@ -0,0 +1,205 @@
+from sympy import tanh
+from sympy.concrete.summations import Sum
+from sympy.core.symbol import symbols
+from sympy.functions.special.tensor_functions import KroneckerDelta
+from sympy.matrices.expressions.matexpr import MatrixSymbol
+from sympy.matrices.expressions.special import Identity
+from sympy.tensor.array.expressions import ArrayElementwiseApplyFunc
+from sympy.tensor.indexed import IndexedBase
+from sympy.combinatorics import Permutation
+from sympy.tensor.array.expressions.array_expressions import ArrayContraction, ArrayTensorProduct, \
+    ArrayDiagonal, ArrayAdd, PermuteDims, ArrayElement, _array_tensor_product, _array_contraction, _array_diagonal, \
+    _array_add, _permute_dims, ArraySymbol, OneArray
+from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
+from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array, _convert_indexed_to_array
+from sympy.testing.pytest import raises
+
+
+A, B = symbols("A B", cls=IndexedBase)
+i, j, k, l, m, n = symbols("i j k l m n")
+d0, d1, d2, d3 = symbols("d0:4")
+
+I = Identity(k)
+
+M = MatrixSymbol("M", k, k)
+N = MatrixSymbol("N", k, k)
+P = MatrixSymbol("P", k, k)
+Q = MatrixSymbol("Q", k, k)
+
+a = MatrixSymbol("a", k, 1)
+b = MatrixSymbol("b", k, 1)
+c = MatrixSymbol("c", k, 1)
+d = MatrixSymbol("d", k, 1)
+
+
+def test_arrayexpr_convert_index_to_array_support_function():
+    expr = M[i, j]
+    assert _convert_indexed_to_array(expr) == (M, (i, j))
+    expr = M[i, j]*N[k, l]
+    assert _convert_indexed_to_array(expr) == (ArrayTensorProduct(M, N), (i, j, k, l))
+    expr = M[i, j]*N[j, k]
+    assert _convert_indexed_to_array(expr) == (ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2)), (i, k, j))
+    expr = Sum(M[i, j]*N[j, k], (j, 0, k-1))
+    assert _convert_indexed_to_array(expr) == (ArrayContraction(ArrayTensorProduct(M, N), (1, 2)), (i, k))
+    expr = M[i, j] + N[i, j]
+    assert _convert_indexed_to_array(expr) == (ArrayAdd(M, N), (i, j))
+    expr = M[i, j] + N[j, i]
+    assert _convert_indexed_to_array(expr) == (ArrayAdd(M, PermuteDims(N, Permutation([1, 0]))), (i, j))
+    expr = M[i, j] + M[j, i]
+    assert _convert_indexed_to_array(expr) == (ArrayAdd(M, PermuteDims(M, Permutation([1, 0]))), (i, j))
+    expr = (M*N*P)[i, j]
+    assert _convert_indexed_to_array(expr) == (_array_contraction(ArrayTensorProduct(M, N, P), (1, 2), (3, 4)), (i, j))
+    expr = expr.function  # Disregard summation in previous expression
+    ret1, ret2 = _convert_indexed_to_array(expr)
+    assert ret1 == ArrayDiagonal(ArrayTensorProduct(M, N, P), (1, 2), (3, 4))
+    assert str(ret2) == "(i, j, _i_1, _i_2)"
+    expr = KroneckerDelta(i, j)*M[i, k]
+    assert _convert_indexed_to_array(expr) == (M, ({i, j}, k))
+    expr = KroneckerDelta(i, j)*KroneckerDelta(j, k)*M[i, l]
+    assert _convert_indexed_to_array(expr) == (M, ({i, j, k}, l))
+    expr = KroneckerDelta(j, k)*(M[i, j]*N[k, l] + N[i, j]*M[k, l])
+    assert _convert_indexed_to_array(expr) == (_array_diagonal(_array_add(
+            ArrayTensorProduct(M, N),
+            _permute_dims(ArrayTensorProduct(M, N), Permutation(0, 2)(1, 3))
+        ), (1, 2)), (i, l, frozenset({j, k})))
+    expr = KroneckerDelta(j, m)*KroneckerDelta(m, k)*(M[i, j]*N[k, l] + N[i, j]*M[k, l])
+    assert _convert_indexed_to_array(expr) == (_array_diagonal(_array_add(
+            ArrayTensorProduct(M, N),
+            _permute_dims(ArrayTensorProduct(M, N), Permutation(0, 2)(1, 3))
+        ), (1, 2)), (i, l, frozenset({j, m, k})))
+    expr = KroneckerDelta(i, j)*KroneckerDelta(j, k)*KroneckerDelta(k,m)*M[i, 0]*KroneckerDelta(m, n)
+    assert _convert_indexed_to_array(expr) == (M, ({i, j, k, m, n}, 0))
+    expr = M[i, i]
+    assert _convert_indexed_to_array(expr) == (ArrayDiagonal(M, (0, 1)), (i,))
+
+
+def test_arrayexpr_convert_indexed_to_array_expression():
+
+    s = Sum(A[i]*B[i], (i, 0, 3))
+    cg = convert_indexed_to_array(s)
+    assert cg == ArrayContraction(ArrayTensorProduct(A, B), (0, 1))
+
+    expr = M*N
+    result = ArrayContraction(ArrayTensorProduct(M, N), (1, 2))
+    elem = expr[i, j]
+    assert convert_indexed_to_array(elem) == result
+
+    expr = M*N*M
+    elem = expr[i, j]
+    result = _array_contraction(_array_tensor_product(M, M, N), (1, 4), (2, 5))
+    cg = convert_indexed_to_array(elem)
+    assert cg == result
+
+    cg = convert_indexed_to_array((M * N * P)[i, j])
+    assert cg == _array_contraction(ArrayTensorProduct(M, N, P), (1, 2), (3, 4))
+
+    cg = convert_indexed_to_array((M * N.T * P)[i, j])
+    assert cg == _array_contraction(ArrayTensorProduct(M, N, P), (1, 3), (2, 4))
+
+    expr = -2*M*N
+    elem = expr[i, j]
+    cg = convert_indexed_to_array(elem)
+    assert cg == ArrayContraction(ArrayTensorProduct(-2, M, N), (1, 2))
+
+
+def test_arrayexpr_convert_array_element_to_array_expression():
+    A = ArraySymbol("A", (k,))
+    B = ArraySymbol("B", (k,))
+
+    s = Sum(A[i]*B[i], (i, 0, k-1))
+    cg = convert_indexed_to_array(s)
+    assert cg == ArrayContraction(ArrayTensorProduct(A, B), (0, 1))
+
+    s = A[i]*B[i]
+    cg = convert_indexed_to_array(s)
+    assert cg == ArrayDiagonal(ArrayTensorProduct(A, B), (0, 1))
+
+    s = A[i]*B[j]
+    cg = convert_indexed_to_array(s, [i, j])
+    assert cg == ArrayTensorProduct(A, B)
+    cg = convert_indexed_to_array(s, [j, i])
+    assert cg == ArrayTensorProduct(B, A)
+
+    s = tanh(A[i]*B[j])
+    cg = convert_indexed_to_array(s, [i, j])
+    assert cg.dummy_eq(ArrayElementwiseApplyFunc(tanh, ArrayTensorProduct(A, B)))
+
+
+def test_arrayexpr_convert_indexed_to_array_and_back_to_matrix():
+
+    expr = a.T*b
+    elem = expr[0, 0]
+    cg = convert_indexed_to_array(elem)
+    assert cg == ArrayElement(ArrayContraction(ArrayTensorProduct(a, b), (0, 2)), [0, 0])
+
+    expr = M[i,j] + N[i,j]
+    p1, p2 = _convert_indexed_to_array(expr)
+    assert convert_array_to_matrix(p1) == M + N
+
+    expr = M[i,j] + N[j,i]
+    p1, p2 = _convert_indexed_to_array(expr)
+    assert convert_array_to_matrix(p1) == M + N.T
+
+    expr = M[i,j]*N[k,l] + N[i,j]*M[k,l]
+    p1, p2 = _convert_indexed_to_array(expr)
+    assert convert_array_to_matrix(p1) == ArrayAdd(
+        ArrayTensorProduct(M, N),
+        ArrayTensorProduct(N, M))
+
+    expr = (M*N*P)[i, j]
+    p1, p2 = _convert_indexed_to_array(expr)
+    assert convert_array_to_matrix(p1) == M * N * P
+
+    expr = Sum(M[i,j]*(N*P)[j,m], (j, 0, k-1))
+    p1, p2 = _convert_indexed_to_array(expr)
+    assert convert_array_to_matrix(p1) == M * N * P
+
+    expr = Sum((P[j, m] + P[m, j])*(M[i,j]*N[m,n] + N[i,j]*M[m,n]), (j, 0, k-1), (m, 0, k-1))
+    p1, p2 = _convert_indexed_to_array(expr)
+    assert convert_array_to_matrix(p1) == M * P * N + M * P.T * N + N * P * M + N * P.T * M
+
+
+def test_arrayexpr_convert_indexed_to_array_out_of_bounds():
+
+    expr = Sum(M[i, i], (i, 0, 4))
+    raises(ValueError, lambda: convert_indexed_to_array(expr))
+    expr = Sum(M[i, i], (i, 0, k))
+    raises(ValueError, lambda: convert_indexed_to_array(expr))
+    expr = Sum(M[i, i], (i, 1, k-1))
+    raises(ValueError, lambda: convert_indexed_to_array(expr))
+
+    expr = Sum(M[i, j]*N[j,m], (j, 0, 4))
+    raises(ValueError, lambda: convert_indexed_to_array(expr))
+    expr = Sum(M[i, j]*N[j,m], (j, 0, k))
+    raises(ValueError, lambda: convert_indexed_to_array(expr))
+    expr = Sum(M[i, j]*N[j,m], (j, 1, k-1))
+    raises(ValueError, lambda: convert_indexed_to_array(expr))
+
+
+def test_arrayexpr_convert_indexed_to_array_broadcast():
+    A = ArraySymbol("A", (3, 3))
+    B = ArraySymbol("B", (3, 3))
+
+    expr = A[i, j] + B[k, l]
+    O2 = OneArray(3, 3)
+    expected = ArrayAdd(ArrayTensorProduct(A, O2), ArrayTensorProduct(O2, B))
+    assert convert_indexed_to_array(expr) == expected
+    assert convert_indexed_to_array(expr, [i, j, k, l]) == expected
+    assert convert_indexed_to_array(expr, [l, k, i, j]) == ArrayAdd(PermuteDims(ArrayTensorProduct(O2, A), [1, 0, 2, 3]), PermuteDims(ArrayTensorProduct(B, O2), [1, 0, 2, 3]))
+
+    expr = A[i, j] + B[j, k]
+    O1 = OneArray(3)
+    assert convert_indexed_to_array(expr, [i, j, k]) == ArrayAdd(ArrayTensorProduct(A, O1), ArrayTensorProduct(O1, B))
+
+    C = ArraySymbol("C", (d0, d1))
+    D = ArraySymbol("D", (d3, d1))
+
+    expr = C[i, j] + D[k, j]
+    assert convert_indexed_to_array(expr, [i, j, k]) == ArrayAdd(ArrayTensorProduct(C, OneArray(d3)), PermuteDims(ArrayTensorProduct(OneArray(d0), D), [0, 2, 1]))
+
+    X = ArraySymbol("X", (5, 3))
+
+    expr = X[i, n] - X[j, n]
+    assert convert_indexed_to_array(expr, [i, j, n]) == ArrayAdd(ArrayTensorProduct(-1, OneArray(5), X), PermuteDims(ArrayTensorProduct(X, OneArray(5)), [0, 2, 1]))
+
+    raises(ValueError, lambda: convert_indexed_to_array(C[i, j] + D[i, j]))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_convert_matrix_to_array.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_convert_matrix_to_array.py
new file mode 100644
index 0000000000000000000000000000000000000000..142585882588df6aa0e4648d9d8881ea755f42a0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_convert_matrix_to_array.py
@@ -0,0 +1,128 @@
+from sympy import Lambda, KroneckerProduct
+from sympy.core.symbol import symbols, Dummy
+from sympy.matrices.expressions.hadamard import (HadamardPower, HadamardProduct)
+from sympy.matrices.expressions.inverse import Inverse
+from sympy.matrices.expressions.matexpr import MatrixSymbol
+from sympy.matrices.expressions.matpow import MatPow
+from sympy.matrices.expressions.special import Identity
+from sympy.matrices.expressions.trace import Trace
+from sympy.matrices.expressions.transpose import Transpose
+from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayContraction, \
+    PermuteDims, ArrayDiagonal, ArrayElementwiseApplyFunc, _array_contraction, _array_tensor_product, Reshape
+from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
+from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
+
+i, j, k, l, m, n = symbols("i j k l m n")
+
+I = Identity(k)
+
+M = MatrixSymbol("M", k, k)
+N = MatrixSymbol("N", k, k)
+P = MatrixSymbol("P", k, k)
+Q = MatrixSymbol("Q", k, k)
+
+A = MatrixSymbol("A", k, k)
+B = MatrixSymbol("B", k, k)
+C = MatrixSymbol("C", k, k)
+D = MatrixSymbol("D", k, k)
+
+X = MatrixSymbol("X", k, k)
+Y = MatrixSymbol("Y", k, k)
+
+a = MatrixSymbol("a", k, 1)
+b = MatrixSymbol("b", k, 1)
+c = MatrixSymbol("c", k, 1)
+d = MatrixSymbol("d", k, 1)
+
+
+def test_arrayexpr_convert_matrix_to_array():
+
+    expr = M*N
+    result = ArrayContraction(ArrayTensorProduct(M, N), (1, 2))
+    assert convert_matrix_to_array(expr) == result
+
+    expr = M*N*M
+    result = _array_contraction(ArrayTensorProduct(M, N, M), (1, 2), (3, 4))
+    assert convert_matrix_to_array(expr) == result
+
+    expr = Transpose(M)
+    assert convert_matrix_to_array(expr) == PermuteDims(M, [1, 0])
+
+    expr = M*Transpose(N)
+    assert convert_matrix_to_array(expr) == _array_contraction(_array_tensor_product(M, PermuteDims(N, [1, 0])), (1, 2))
+
+    expr = 3*M*N
+    res = convert_matrix_to_array(expr)
+    rexpr = convert_array_to_matrix(res)
+    assert expr == rexpr
+
+    expr = 3*M + N*M.T*M + 4*k*N
+    res = convert_matrix_to_array(expr)
+    rexpr = convert_array_to_matrix(res)
+    assert expr == rexpr
+
+    expr = Inverse(M)*N
+    rexpr = convert_array_to_matrix(convert_matrix_to_array(expr))
+    assert expr == rexpr
+
+    expr = M**2
+    rexpr = convert_array_to_matrix(convert_matrix_to_array(expr))
+    assert expr == rexpr
+
+    expr = M*(2*N + 3*M)
+    res = convert_matrix_to_array(expr)
+    rexpr = convert_array_to_matrix(res)
+    assert expr == rexpr
+
+    expr = Trace(M)
+    result = ArrayContraction(M, (0, 1))
+    assert convert_matrix_to_array(expr) == result
+
+    expr = 3*Trace(M)
+    result = ArrayContraction(ArrayTensorProduct(3, M), (0, 1))
+    assert convert_matrix_to_array(expr) == result
+
+    expr = 3*Trace(Trace(M) * M)
+    result = ArrayContraction(ArrayTensorProduct(3, M, M), (0, 1), (2, 3))
+    assert convert_matrix_to_array(expr) == result
+
+    expr = 3*Trace(M)**2
+    result = ArrayContraction(ArrayTensorProduct(3, M, M), (0, 1), (2, 3))
+    assert convert_matrix_to_array(expr) == result
+
+    expr = HadamardProduct(M, N)
+    result = ArrayDiagonal(ArrayTensorProduct(M, N), (0, 2), (1, 3))
+    assert convert_matrix_to_array(expr) == result
+
+    expr = HadamardProduct(M*N, N*M)
+    result = ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, N, M), (1, 2), (5, 6)), (0, 2), (1, 3))
+    assert convert_matrix_to_array(expr) == result
+
+    expr = HadamardPower(M, 2)
+    result = ArrayDiagonal(ArrayTensorProduct(M, M), (0, 2), (1, 3))
+    assert convert_matrix_to_array(expr) == result
+
+    expr = HadamardPower(M*N, 2)
+    result = ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, M, N), (1, 2), (5, 6)), (0, 2), (1, 3))
+    assert convert_matrix_to_array(expr) == result
+
+    expr = HadamardPower(M, n)
+    d0 = Dummy("d0")
+    result = ArrayElementwiseApplyFunc(Lambda(d0, d0**n), M)
+    assert convert_matrix_to_array(expr).dummy_eq(result)
+
+    expr = M**2
+    assert isinstance(expr, MatPow)
+    assert convert_matrix_to_array(expr) == ArrayContraction(ArrayTensorProduct(M, M), (1, 2))
+
+    expr = a.T*b
+    cg = convert_matrix_to_array(expr)
+    assert cg == ArrayContraction(ArrayTensorProduct(a, b), (0, 2))
+
+    expr = KroneckerProduct(A, B)
+    cg = convert_matrix_to_array(expr)
+    assert cg == Reshape(PermuteDims(ArrayTensorProduct(A, B), [0, 2, 1, 3]), (k**2, k**2))
+
+    expr = KroneckerProduct(A, B, C, D)
+    cg = convert_matrix_to_array(expr)
+    assert cg == Reshape(PermuteDims(ArrayTensorProduct(A, B, C, D), [0, 2, 4, 6, 1, 3, 5, 7]), (k**4, k**4))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_deprecated_conv_modules.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_deprecated_conv_modules.py
new file mode 100644
index 0000000000000000000000000000000000000000..b41b6105410a308e7774fce760b235497d0303bb
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/tests/test_deprecated_conv_modules.py
@@ -0,0 +1,22 @@
+from sympy import MatrixSymbol, symbols, Sum
+from sympy.tensor.array.expressions import conv_array_to_indexed, from_array_to_indexed, ArrayTensorProduct, \
+    ArrayContraction, conv_array_to_matrix, from_array_to_matrix, conv_matrix_to_array, from_matrix_to_array, \
+    conv_indexed_to_array, from_indexed_to_array
+from sympy.testing.pytest import warns
+from sympy.utilities.exceptions import SymPyDeprecationWarning
+
+
+def test_deprecated_conv_module_results():
+
+    M = MatrixSymbol("M", 3, 3)
+    N = MatrixSymbol("N", 3, 3)
+    i, j, d = symbols("i j d")
+
+    x = ArrayContraction(ArrayTensorProduct(M, N), (1, 2))
+    y = Sum(M[i, d]*N[d, j], (d, 0, 2))
+
+    with warns(SymPyDeprecationWarning, test_stacklevel=False):
+        assert conv_array_to_indexed.convert_array_to_indexed(x, [i, j]).dummy_eq(from_array_to_indexed.convert_array_to_indexed(x, [i, j]))
+        assert conv_array_to_matrix.convert_array_to_matrix(x) == from_array_to_matrix.convert_array_to_matrix(x)
+        assert conv_matrix_to_array.convert_matrix_to_array(M*N) == from_matrix_to_array.convert_matrix_to_array(M*N)
+        assert conv_indexed_to_array.convert_indexed_to_array(y) == from_indexed_to_array.convert_indexed_to_array(y)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/utils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..e55c0e6ed47cdc9ff1c24cc92f006998aeb86822
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/expressions/utils.py
@@ -0,0 +1,123 @@
+import bisect
+from collections import defaultdict
+
+from sympy.combinatorics import Permutation
+from sympy.core.containers import Tuple
+from sympy.core.numbers import Integer
+
+
+def _get_mapping_from_subranks(subranks):
+    mapping = {}
+    counter = 0
+    for i, rank in enumerate(subranks):
+        for j in range(rank):
+            mapping[counter] = (i, j)
+            counter += 1
+    return mapping
+
+
+def _get_contraction_links(args, subranks, *contraction_indices):
+    mapping = _get_mapping_from_subranks(subranks)
+    contraction_tuples = [[mapping[j] for j in i] for i in contraction_indices]
+    dlinks = defaultdict(dict)
+    for links in contraction_tuples:
+        if len(links) == 2:
+            (arg1, pos1), (arg2, pos2) = links
+            dlinks[arg1][pos1] = (arg2, pos2)
+            dlinks[arg2][pos2] = (arg1, pos1)
+            continue
+
+    return args, dict(dlinks)
+
+
+def _sort_contraction_indices(pairing_indices):
+    pairing_indices = [Tuple(*sorted(i)) for i in pairing_indices]
+    pairing_indices.sort(key=lambda x: min(x))
+    return pairing_indices
+
+
+def _get_diagonal_indices(flattened_indices):
+    axes_contraction = defaultdict(list)
+    for i, ind in enumerate(flattened_indices):
+        if isinstance(ind, (int, Integer)):
+            # If the indices is a number, there can be no diagonal operation:
+            continue
+        axes_contraction[ind].append(i)
+    axes_contraction = {k: v for k, v in axes_contraction.items() if len(v) > 1}
+    # Put the diagonalized indices at the end:
+    ret_indices = [i for i in flattened_indices if i not in axes_contraction]
+    diag_indices = list(axes_contraction)
+    diag_indices.sort(key=lambda x: flattened_indices.index(x))
+    diagonal_indices = [tuple(axes_contraction[i]) for i in diag_indices]
+    ret_indices += diag_indices
+    ret_indices = tuple(ret_indices)
+    return diagonal_indices, ret_indices
+
+
+def _get_argindex(subindices, ind):
+    for i, sind in enumerate(subindices):
+        if ind == sind:
+            return i
+        if isinstance(sind, (set, frozenset)) and ind in sind:
+            return i
+    raise IndexError("%s not found in %s" % (ind, subindices))
+
+
+def _apply_recursively_over_nested_lists(func, arr):
+    if isinstance(arr, (tuple, list, Tuple)):
+        return tuple(_apply_recursively_over_nested_lists(func, i) for i in arr)
+    elif isinstance(arr, Tuple):
+        return Tuple.fromiter(_apply_recursively_over_nested_lists(func, i) for i in arr)
+    else:
+        return func(arr)
+
+
+def _build_push_indices_up_func_transformation(flattened_contraction_indices):
+    shifts = {0: 0}
+    i = 0
+    cumulative = 0
+    while i < len(flattened_contraction_indices):
+        j = 1
+        while i+j < len(flattened_contraction_indices):
+            if flattened_contraction_indices[i] + j != flattened_contraction_indices[i+j]:
+                break
+            j += 1
+        cumulative += j
+        shifts[flattened_contraction_indices[i]] = cumulative
+        i += j
+    shift_keys = sorted(shifts.keys())
+
+    def func(idx):
+        return shifts[shift_keys[bisect.bisect_right(shift_keys, idx)-1]]
+
+    def transform(j):
+        if j in flattened_contraction_indices:
+            return None
+        else:
+            return j - func(j)
+
+    return transform
+
+
+def _build_push_indices_down_func_transformation(flattened_contraction_indices):
+    N = flattened_contraction_indices[-1]+2
+
+    shifts = [i for i in range(N) if i not in flattened_contraction_indices]
+
+    def transform(j):
+        if j < len(shifts):
+            return shifts[j]
+        else:
+            return j + shifts[-1] - len(shifts) + 1
+
+    return transform
+
+
+def _apply_permutation_to_list(perm: Permutation, target_list: list):
+    """
+    Permute a list according to the given permutation.
+    """
+    new_list = [None for i in range(perm.size)]
+    for i, e in enumerate(target_list):
+        new_list[perm(i)] = e
+    return new_list
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/mutable_ndim_array.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/mutable_ndim_array.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1eaaf7241bc3b4a48234178d18da3aa5736e189
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/mutable_ndim_array.py
@@ -0,0 +1,13 @@
+from sympy.tensor.array.ndim_array import NDimArray
+
+
+class MutableNDimArray(NDimArray):
+
+    def as_immutable(self):
+        raise NotImplementedError("abstract method")
+
+    def as_mutable(self):
+        return self
+
+    def _sympy_(self):
+        return self.as_immutable()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/ndim_array.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/ndim_array.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b9a857b8cfd9ee46646c46f274636d6b9962b6e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/ndim_array.py
@@ -0,0 +1,601 @@
+from sympy.core.basic import Basic
+from sympy.core.containers import (Dict, Tuple)
+from sympy.core.expr import Expr
+from sympy.core.kind import Kind, NumberKind, UndefinedKind
+from sympy.core.numbers import Integer
+from sympy.core.singleton import S
+from sympy.core.sympify import sympify
+from sympy.external.gmpy import SYMPY_INTS
+from sympy.printing.defaults import Printable
+
+import itertools
+from collections.abc import Iterable
+
+
+class ArrayKind(Kind):
+    """
+    Kind for N-dimensional array in SymPy.
+
+    This kind represents the multidimensional array that algebraic
+    operations are defined. Basic class for this kind is ``NDimArray``,
+    but any expression representing the array can have this.
+
+    Parameters
+    ==========
+
+    element_kind : Kind
+        Kind of the element. Default is :obj:NumberKind ``,
+        which means that the array contains only numbers.
+
+    Examples
+    ========
+
+    Any instance of array class has ``ArrayKind``.
+
+    >>> from sympy import NDimArray
+    >>> NDimArray([1,2,3]).kind
+    ArrayKind(NumberKind)
+
+    Although expressions representing an array may be not instance of
+    array class, it will have ``ArrayKind`` as well.
+
+    >>> from sympy import Integral
+    >>> from sympy.tensor.array import NDimArray
+    >>> from sympy.abc import x
+    >>> intA = Integral(NDimArray([1,2,3]), x)
+    >>> isinstance(intA, NDimArray)
+    False
+    >>> intA.kind
+    ArrayKind(NumberKind)
+
+    Use ``isinstance()`` to check for ``ArrayKind` without specifying
+    the element kind. Use ``is`` with specifying the element kind.
+
+    >>> from sympy.tensor.array import ArrayKind
+    >>> from sympy.core import NumberKind
+    >>> boolA = NDimArray([True, False])
+    >>> isinstance(boolA.kind, ArrayKind)
+    True
+    >>> boolA.kind is ArrayKind(NumberKind)
+    False
+
+    See Also
+    ========
+
+    shape : Function to return the shape of objects with ``MatrixKind``.
+
+    """
+    def __new__(cls, element_kind=NumberKind):
+        obj = super().__new__(cls, element_kind)
+        obj.element_kind = element_kind
+        return obj
+
+    def __repr__(self):
+        return "ArrayKind(%s)" % self.element_kind
+
+    @classmethod
+    def _union(cls, kinds) -> 'ArrayKind':
+        elem_kinds = {e.kind for e in kinds}
+        if len(elem_kinds) == 1:
+            elemkind, = elem_kinds
+        else:
+            elemkind = UndefinedKind
+        return ArrayKind(elemkind)
+
+
+class NDimArray(Printable):
+    """N-dimensional array.
+
+    Examples
+    ========
+
+    Create an N-dim array of zeros:
+
+    >>> from sympy import MutableDenseNDimArray
+    >>> a = MutableDenseNDimArray.zeros(2, 3, 4)
+    >>> a
+    [[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]
+
+    Create an N-dim array from a list;
+
+    >>> a = MutableDenseNDimArray([[2, 3], [4, 5]])
+    >>> a
+    [[2, 3], [4, 5]]
+
+    >>> b = MutableDenseNDimArray([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]])
+    >>> b
+    [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]]
+
+    Create an N-dim array from a flat list with dimension shape:
+
+    >>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3))
+    >>> a
+    [[1, 2, 3], [4, 5, 6]]
+
+    Create an N-dim array from a matrix:
+
+    >>> from sympy import Matrix
+    >>> a = Matrix([[1,2],[3,4]])
+    >>> a
+    Matrix([
+    [1, 2],
+    [3, 4]])
+    >>> b = MutableDenseNDimArray(a)
+    >>> b
+    [[1, 2], [3, 4]]
+
+    Arithmetic operations on N-dim arrays
+
+    >>> a = MutableDenseNDimArray([1, 1, 1, 1], (2, 2))
+    >>> b = MutableDenseNDimArray([4, 4, 4, 4], (2, 2))
+    >>> c = a + b
+    >>> c
+    [[5, 5], [5, 5]]
+    >>> a - b
+    [[-3, -3], [-3, -3]]
+
+    """
+
+    _diff_wrt = True
+    is_scalar = False
+
+    def __new__(cls, iterable, shape=None, **kwargs):
+        from sympy.tensor.array import ImmutableDenseNDimArray
+        return ImmutableDenseNDimArray(iterable, shape, **kwargs)
+
+    def __getitem__(self, index):
+        raise NotImplementedError("A subclass of NDimArray should implement __getitem__")
+
+    def _parse_index(self, index):
+        if isinstance(index, (SYMPY_INTS, Integer)):
+            if index >= self._loop_size:
+                raise ValueError("Only a tuple index is accepted")
+            return index
+
+        if self._loop_size == 0:
+            raise ValueError("Index not valid with an empty array")
+
+        if len(index) != self._rank:
+            raise ValueError('Wrong number of array axes')
+
+        real_index = 0
+        # check if input index can exist in current indexing
+        for i in range(self._rank):
+            if (index[i] >= self.shape[i]) or (index[i] < -self.shape[i]):
+                raise ValueError('Index ' + str(index) + ' out of border')
+            if index[i] < 0:
+                real_index += 1
+            real_index = real_index*self.shape[i] + index[i]
+
+        return real_index
+
+    def _get_tuple_index(self, integer_index):
+        index = []
+        for sh in reversed(self.shape):
+            index.append(integer_index % sh)
+            integer_index //= sh
+        index.reverse()
+        return tuple(index)
+
+    def _check_symbolic_index(self, index):
+        # Check if any index is symbolic:
+        tuple_index = (index if isinstance(index, tuple) else (index,))
+        if any((isinstance(i, Expr) and (not i.is_number)) for i in tuple_index):
+            for i, nth_dim in zip(tuple_index, self.shape):
+                if ((i < 0) == True) or ((i >= nth_dim) == True):
+                    raise ValueError("index out of range")
+            from sympy.tensor import Indexed
+            return Indexed(self, *tuple_index)
+        return None
+
+    def _setter_iterable_check(self, value):
+        from sympy.matrices.matrixbase import MatrixBase
+        if isinstance(value, (Iterable, MatrixBase, NDimArray)):
+            raise NotImplementedError
+
+    @classmethod
+    def _scan_iterable_shape(cls, iterable):
+        def f(pointer):
+            if not isinstance(pointer, Iterable):
+                return [pointer], ()
+
+            if len(pointer) == 0:
+                return [], (0,)
+
+            result = []
+            elems, shapes = zip(*[f(i) for i in pointer])
+            if len(set(shapes)) != 1:
+                raise ValueError("could not determine shape unambiguously")
+            for i in elems:
+                result.extend(i)
+            return result, (len(shapes),)+shapes[0]
+
+        return f(iterable)
+
+    @classmethod
+    def _handle_ndarray_creation_inputs(cls, iterable=None, shape=None, **kwargs):
+        from sympy.matrices.matrixbase import MatrixBase
+        from sympy.tensor.array import SparseNDimArray
+
+        if shape is None:
+            if iterable is None:
+                shape = ()
+                iterable = ()
+            # Construction of a sparse array from a sparse array
+            elif isinstance(iterable, SparseNDimArray):
+                return iterable._shape, iterable._sparse_array
+
+            # Construct N-dim array from another N-dim array:
+            elif isinstance(iterable, NDimArray):
+                shape = iterable.shape
+
+            # Construct N-dim array from an iterable (numpy arrays included):
+            elif isinstance(iterable, Iterable):
+                iterable, shape = cls._scan_iterable_shape(iterable)
+
+            # Construct N-dim array from a Matrix:
+            elif isinstance(iterable, MatrixBase):
+                shape = iterable.shape
+
+            else:
+                shape = ()
+                iterable = (iterable,)
+
+        if isinstance(iterable, (Dict, dict)) and shape is not None:
+            new_dict = iterable.copy()
+            for k in new_dict:
+                if isinstance(k, (tuple, Tuple)):
+                    new_key = 0
+                    for i, idx in enumerate(k):
+                        new_key = new_key * shape[i] + idx
+                    iterable[new_key] = iterable[k]
+                    del iterable[k]
+
+        if isinstance(shape, (SYMPY_INTS, Integer)):
+            shape = (shape,)
+
+        if not all(isinstance(dim, (SYMPY_INTS, Integer)) for dim in shape):
+            raise TypeError("Shape should contain integers only.")
+
+        return tuple(shape), iterable
+
+    def __len__(self):
+        """Overload common function len(). Returns number of elements in array.
+
+        Examples
+        ========
+
+        >>> from sympy import MutableDenseNDimArray
+        >>> a = MutableDenseNDimArray.zeros(3, 3)
+        >>> a
+        [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
+        >>> len(a)
+        9
+
+        """
+        return self._loop_size
+
+    @property
+    def shape(self):
+        """
+        Returns array shape (dimension).
+
+        Examples
+        ========
+
+        >>> from sympy import MutableDenseNDimArray
+        >>> a = MutableDenseNDimArray.zeros(3, 3)
+        >>> a.shape
+        (3, 3)
+
+        """
+        return self._shape
+
+    def rank(self):
+        """
+        Returns rank of array.
+
+        Examples
+        ========
+
+        >>> from sympy import MutableDenseNDimArray
+        >>> a = MutableDenseNDimArray.zeros(3,4,5,6,3)
+        >>> a.rank()
+        5
+
+        """
+        return self._rank
+
+    def diff(self, *args, **kwargs):
+        """
+        Calculate the derivative of each element in the array.
+
+        Examples
+        ========
+
+        >>> from sympy import ImmutableDenseNDimArray
+        >>> from sympy.abc import x, y
+        >>> M = ImmutableDenseNDimArray([[x, y], [1, x*y]])
+        >>> M.diff(x)
+        [[1, 0], [0, y]]
+
+        """
+        from sympy.tensor.array.array_derivatives import ArrayDerivative
+        kwargs.setdefault('evaluate', True)
+        return ArrayDerivative(self.as_immutable(), *args, **kwargs)
+
+    def _eval_derivative(self, base):
+        # Types are (base: scalar, self: array)
+        return self.applyfunc(lambda x: base.diff(x))
+
+    def _eval_derivative_n_times(self, s, n):
+        return Basic._eval_derivative_n_times(self, s, n)
+
+    def applyfunc(self, f):
+        """Apply a function to each element of the N-dim array.
+
+        Examples
+        ========
+
+        >>> from sympy import ImmutableDenseNDimArray
+        >>> m = ImmutableDenseNDimArray([i*2+j for i in range(2) for j in range(2)], (2, 2))
+        >>> m
+        [[0, 1], [2, 3]]
+        >>> m.applyfunc(lambda i: 2*i)
+        [[0, 2], [4, 6]]
+        """
+        from sympy.tensor.array import SparseNDimArray
+        from sympy.tensor.array.arrayop import Flatten
+
+        if isinstance(self, SparseNDimArray) and f(S.Zero) == 0:
+            return type(self)({k: f(v) for k, v in self._sparse_array.items() if f(v) != 0}, self.shape)
+
+        return type(self)(map(f, Flatten(self)), self.shape)
+
+    def _sympystr(self, printer):
+        def f(sh, shape_left, i, j):
+            if len(shape_left) == 1:
+                return "["+", ".join([printer._print(self[self._get_tuple_index(e)]) for e in range(i, j)])+"]"
+
+            sh //= shape_left[0]
+            return "[" + ", ".join([f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh) for e in range(shape_left[0])]) + "]" # + "\n"*len(shape_left)
+
+        if self.rank() == 0:
+            return printer._print(self[()])
+        if 0 in self.shape:
+            return f"{self.__class__.__name__}([], {self.shape})"
+        return f(self._loop_size, self.shape, 0, self._loop_size)
+
+    def tolist(self):
+        """
+        Converting MutableDenseNDimArray to one-dim list
+
+        Examples
+        ========
+
+        >>> from sympy import MutableDenseNDimArray
+        >>> a = MutableDenseNDimArray([1, 2, 3, 4], (2, 2))
+        >>> a
+        [[1, 2], [3, 4]]
+        >>> b = a.tolist()
+        >>> b
+        [[1, 2], [3, 4]]
+        """
+
+        def f(sh, shape_left, i, j):
+            if len(shape_left) == 1:
+                return [self[self._get_tuple_index(e)] for e in range(i, j)]
+            result = []
+            sh //= shape_left[0]
+            for e in range(shape_left[0]):
+                result.append(f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh))
+            return result
+
+        return f(self._loop_size, self.shape, 0, self._loop_size)
+
+    def __add__(self, other):
+        from sympy.tensor.array.arrayop import Flatten
+
+        if not isinstance(other, NDimArray):
+            return NotImplemented
+
+        if self.shape != other.shape:
+            raise ValueError("array shape mismatch")
+        result_list = [i+j for i,j in zip(Flatten(self), Flatten(other))]
+
+        return type(self)(result_list, self.shape)
+
+    def __sub__(self, other):
+        from sympy.tensor.array.arrayop import Flatten
+
+        if not isinstance(other, NDimArray):
+            return NotImplemented
+
+        if self.shape != other.shape:
+            raise ValueError("array shape mismatch")
+        result_list = [i-j for i,j in zip(Flatten(self), Flatten(other))]
+
+        return type(self)(result_list, self.shape)
+
+    def __mul__(self, other):
+        from sympy.matrices.matrixbase import MatrixBase
+        from sympy.tensor.array import SparseNDimArray
+        from sympy.tensor.array.arrayop import Flatten
+
+        if isinstance(other, (Iterable, NDimArray, MatrixBase)):
+            raise ValueError("scalar expected, use tensorproduct(...) for tensorial product")
+
+        other = sympify(other)
+        if isinstance(self, SparseNDimArray):
+            if other.is_zero:
+                return type(self)({}, self.shape)
+            return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape)
+
+        result_list = [i*other for i in Flatten(self)]
+        return type(self)(result_list, self.shape)
+
+    def __rmul__(self, other):
+        from sympy.matrices.matrixbase import MatrixBase
+        from sympy.tensor.array import SparseNDimArray
+        from sympy.tensor.array.arrayop import Flatten
+
+        if isinstance(other, (Iterable, NDimArray, MatrixBase)):
+            raise ValueError("scalar expected, use tensorproduct(...) for tensorial product")
+
+        other = sympify(other)
+        if isinstance(self, SparseNDimArray):
+            if other.is_zero:
+                return type(self)({}, self.shape)
+            return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape)
+
+        result_list = [other*i for i in Flatten(self)]
+        return type(self)(result_list, self.shape)
+
+    def __truediv__(self, other):
+        from sympy.matrices.matrixbase import MatrixBase
+        from sympy.tensor.array import SparseNDimArray
+        from sympy.tensor.array.arrayop import Flatten
+
+        if isinstance(other, (Iterable, NDimArray, MatrixBase)):
+            raise ValueError("scalar expected")
+
+        other = sympify(other)
+        if isinstance(self, SparseNDimArray) and other != S.Zero:
+            return type(self)({k: v/other for (k, v) in self._sparse_array.items()}, self.shape)
+
+        result_list = [i/other for i in Flatten(self)]
+        return type(self)(result_list, self.shape)
+
+    def __rtruediv__(self, other):
+        raise NotImplementedError('unsupported operation on NDimArray')
+
+    def __neg__(self):
+        from sympy.tensor.array import SparseNDimArray
+        from sympy.tensor.array.arrayop import Flatten
+
+        if isinstance(self, SparseNDimArray):
+            return type(self)({k: -v for (k, v) in self._sparse_array.items()}, self.shape)
+
+        result_list = [-i for i in Flatten(self)]
+        return type(self)(result_list, self.shape)
+
+    def __iter__(self):
+        def iterator():
+            if self._shape:
+                for i in range(self._shape[0]):
+                    yield self[i]
+            else:
+                yield self[()]
+
+        return iterator()
+
+    def __eq__(self, other):
+        """
+        NDimArray instances can be compared to each other.
+        Instances equal if they have same shape and data.
+
+        Examples
+        ========
+
+        >>> from sympy import MutableDenseNDimArray
+        >>> a = MutableDenseNDimArray.zeros(2, 3)
+        >>> b = MutableDenseNDimArray.zeros(2, 3)
+        >>> a == b
+        True
+        >>> c = a.reshape(3, 2)
+        >>> c == b
+        False
+        >>> a[0,0] = 1
+        >>> b[0,0] = 2
+        >>> a == b
+        False
+        """
+        from sympy.tensor.array import SparseNDimArray
+        if not isinstance(other, NDimArray):
+            return False
+
+        if not self.shape == other.shape:
+            return False
+
+        if isinstance(self, SparseNDimArray) and isinstance(other, SparseNDimArray):
+            return dict(self._sparse_array) == dict(other._sparse_array)
+
+        return list(self) == list(other)
+
+    def __ne__(self, other):
+        return not self == other
+
+    def _eval_transpose(self):
+        if self.rank() != 2:
+            raise ValueError("array rank not 2")
+        from .arrayop import permutedims
+        return permutedims(self, (1, 0))
+
+    def transpose(self):
+        return self._eval_transpose()
+
+    def _eval_conjugate(self):
+        from sympy.tensor.array.arrayop import Flatten
+
+        return self.func([i.conjugate() for i in Flatten(self)], self.shape)
+
+    def conjugate(self):
+        return self._eval_conjugate()
+
+    def _eval_adjoint(self):
+        return self.transpose().conjugate()
+
+    def adjoint(self):
+        return self._eval_adjoint()
+
+    def _slice_expand(self, s, dim):
+        if not isinstance(s, slice):
+                return (s,)
+        start, stop, step = s.indices(dim)
+        return [start + i*step for i in range((stop-start)//step)]
+
+    def _get_slice_data_for_array_access(self, index):
+        sl_factors = [self._slice_expand(i, dim) for (i, dim) in zip(index, self.shape)]
+        eindices = itertools.product(*sl_factors)
+        return sl_factors, eindices
+
+    def _get_slice_data_for_array_assignment(self, index, value):
+        if not isinstance(value, NDimArray):
+            value = type(self)(value)
+        sl_factors, eindices = self._get_slice_data_for_array_access(index)
+        slice_offsets = [min(i) if isinstance(i, list) else None for i in sl_factors]
+        # TODO: add checks for dimensions for `value`?
+        return value, eindices, slice_offsets
+
+    @classmethod
+    def _check_special_bounds(cls, flat_list, shape):
+        if shape == () and len(flat_list) != 1:
+            raise ValueError("arrays without shape need one scalar value")
+        if shape == (0,) and len(flat_list) > 0:
+            raise ValueError("if array shape is (0,) there cannot be elements")
+
+    def _check_index_for_getitem(self, index):
+        if isinstance(index, (SYMPY_INTS, Integer, slice)):
+            index = (index,)
+
+        if len(index) < self.rank():
+            index = tuple(index) + \
+                          tuple(slice(None) for i in range(len(index), self.rank()))
+
+        if len(index) > self.rank():
+            raise ValueError('Dimension of index greater than rank of array')
+
+        return index
+
+
+class ImmutableNDimArray(NDimArray, Basic):
+    _op_priority = 11.0
+
+    def __hash__(self):
+        return Basic.__hash__(self)
+
+    def as_immutable(self):
+        return self
+
+    def as_mutable(self):
+        raise NotImplementedError("abstract method")
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/sparse_ndim_array.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/sparse_ndim_array.py
new file mode 100644
index 0000000000000000000000000000000000000000..f11aa95be8ec9d10a9104d48fb28f406fe43845e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/sparse_ndim_array.py
@@ -0,0 +1,196 @@
+from sympy.core.basic import Basic
+from sympy.core.containers import (Dict, Tuple)
+from sympy.core.singleton import S
+from sympy.core.sympify import _sympify
+from sympy.tensor.array.mutable_ndim_array import MutableNDimArray
+from sympy.tensor.array.ndim_array import NDimArray, ImmutableNDimArray
+from sympy.utilities.iterables import flatten
+
+import functools
+
+class SparseNDimArray(NDimArray):
+
+    def __new__(self, *args, **kwargs):
+        return ImmutableSparseNDimArray(*args, **kwargs)
+
+    def __getitem__(self, index):
+        """
+        Get an element from a sparse N-dim array.
+
+        Examples
+        ========
+
+        >>> from sympy import MutableSparseNDimArray
+        >>> a = MutableSparseNDimArray(range(4), (2, 2))
+        >>> a
+        [[0, 1], [2, 3]]
+        >>> a[0, 0]
+        0
+        >>> a[1, 1]
+        3
+        >>> a[0]
+        [0, 1]
+        >>> a[1]
+        [2, 3]
+
+        Symbolic indexing:
+
+        >>> from sympy.abc import i, j
+        >>> a[i, j]
+        [[0, 1], [2, 3]][i, j]
+
+        Replace `i` and `j` to get element `(0, 0)`:
+
+        >>> a[i, j].subs({i: 0, j: 0})
+        0
+
+        """
+        syindex = self._check_symbolic_index(index)
+        if syindex is not None:
+            return syindex
+
+        index = self._check_index_for_getitem(index)
+
+        # `index` is a tuple with one or more slices:
+        if isinstance(index, tuple) and any(isinstance(i, slice) for i in index):
+            sl_factors, eindices = self._get_slice_data_for_array_access(index)
+            array = [self._sparse_array.get(self._parse_index(i), S.Zero) for i in eindices]
+            nshape = [len(el) for i, el in enumerate(sl_factors) if isinstance(index[i], slice)]
+            return type(self)(array, nshape)
+        else:
+            index = self._parse_index(index)
+            return self._sparse_array.get(index, S.Zero)
+
+    @classmethod
+    def zeros(cls, *shape):
+        """
+        Return a sparse N-dim array of zeros.
+        """
+        return cls({}, shape)
+
+    def tomatrix(self):
+        """
+        Converts MutableDenseNDimArray to Matrix. Can convert only 2-dim array, else will raise error.
+
+        Examples
+        ========
+
+        >>> from sympy import MutableSparseNDimArray
+        >>> a = MutableSparseNDimArray([1 for i in range(9)], (3, 3))
+        >>> b = a.tomatrix()
+        >>> b
+        Matrix([
+        [1, 1, 1],
+        [1, 1, 1],
+        [1, 1, 1]])
+        """
+        from sympy.matrices import SparseMatrix
+        if self.rank() != 2:
+            raise ValueError('Dimensions must be of size of 2')
+
+        mat_sparse = {}
+        for key, value in self._sparse_array.items():
+            mat_sparse[self._get_tuple_index(key)] = value
+
+        return SparseMatrix(self.shape[0], self.shape[1], mat_sparse)
+
+    def reshape(self, *newshape):
+        new_total_size = functools.reduce(lambda x,y: x*y, newshape)
+        if new_total_size != self._loop_size:
+            raise ValueError("Invalid reshape parameters " + newshape)
+
+        return type(self)(self._sparse_array, newshape)
+
+class ImmutableSparseNDimArray(SparseNDimArray, ImmutableNDimArray): # type: ignore
+
+    def __new__(cls, iterable=None, shape=None, **kwargs):
+        shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
+        shape = Tuple(*map(_sympify, shape))
+        cls._check_special_bounds(flat_list, shape)
+        loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else len(flat_list)
+
+        # Sparse array:
+        if isinstance(flat_list, (dict, Dict)):
+            sparse_array = Dict(flat_list)
+        else:
+            sparse_array = {}
+            for i, el in enumerate(flatten(flat_list)):
+                if el != 0:
+                    sparse_array[i] = _sympify(el)
+
+        sparse_array = Dict(sparse_array)
+
+        self = Basic.__new__(cls, sparse_array, shape, **kwargs)
+        self._shape = shape
+        self._rank = len(shape)
+        self._loop_size = loop_size
+        self._sparse_array = sparse_array
+
+        return self
+
+    def __setitem__(self, index, value):
+        raise TypeError("immutable N-dim array")
+
+    def as_mutable(self):
+        return MutableSparseNDimArray(self)
+
+
+class MutableSparseNDimArray(MutableNDimArray, SparseNDimArray):
+
+    def __new__(cls, iterable=None, shape=None, **kwargs):
+        shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
+        self = object.__new__(cls)
+        self._shape = shape
+        self._rank = len(shape)
+        self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else len(flat_list)
+
+        # Sparse array:
+        if isinstance(flat_list, (dict, Dict)):
+            self._sparse_array = dict(flat_list)
+            return self
+
+        self._sparse_array = {}
+
+        for i, el in enumerate(flatten(flat_list)):
+            if el != 0:
+                self._sparse_array[i] = _sympify(el)
+
+        return self
+
+    def __setitem__(self, index, value):
+        """Allows to set items to MutableDenseNDimArray.
+
+        Examples
+        ========
+
+        >>> from sympy import MutableSparseNDimArray
+        >>> a = MutableSparseNDimArray.zeros(2, 2)
+        >>> a[0, 0] = 1
+        >>> a[1, 1] = 1
+        >>> a
+        [[1, 0], [0, 1]]
+        """
+        if isinstance(index, tuple) and any(isinstance(i, slice) for i in index):
+            value, eindices, slice_offsets = self._get_slice_data_for_array_assignment(index, value)
+            for i in eindices:
+                other_i = [ind - j for ind, j in zip(i, slice_offsets) if j is not None]
+                other_value = value[other_i]
+                complete_index = self._parse_index(i)
+                if other_value != 0:
+                    self._sparse_array[complete_index] = other_value
+                elif complete_index in self._sparse_array:
+                    self._sparse_array.pop(complete_index)
+        else:
+            index = self._parse_index(index)
+            value = _sympify(value)
+            if value == 0 and index in self._sparse_array:
+                self._sparse_array.pop(index)
+            else:
+                self._sparse_array[index] = value
+
+    def as_immutable(self):
+        return ImmutableSparseNDimArray(self)
+
+    @property
+    def free_symbols(self):
+        return {i for j in self._sparse_array.values() for i in j.free_symbols}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_array_comprehension.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_array_comprehension.py
new file mode 100644
index 0000000000000000000000000000000000000000..510e068f287fa04419712e5e9a16a314e522a62d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_array_comprehension.py
@@ -0,0 +1,78 @@
+from sympy.tensor.array.array_comprehension import ArrayComprehension, ArrayComprehensionMap
+from sympy.tensor.array import ImmutableDenseNDimArray
+from sympy.abc import i, j, k, l
+from sympy.testing.pytest import raises
+from sympy.matrices import Matrix
+
+
+def test_array_comprehension():
+    a = ArrayComprehension(i*j, (i, 1, 3), (j, 2, 4))
+    b = ArrayComprehension(i, (i, 1, j+1))
+    c = ArrayComprehension(i+j+k+l, (i, 1, 2), (j, 1, 3), (k, 1, 4), (l, 1, 5))
+    d = ArrayComprehension(k, (i, 1, 5))
+    e = ArrayComprehension(i, (j, k+1, k+5))
+    assert a.doit().tolist() == [[2, 3, 4], [4, 6, 8], [6, 9, 12]]
+    assert a.shape == (3, 3)
+    assert a.is_shape_numeric == True
+    assert a.tolist() == [[2, 3, 4], [4, 6, 8], [6, 9, 12]]
+    assert a.tomatrix() == Matrix([
+                           [2, 3, 4],
+                           [4, 6, 8],
+                           [6, 9, 12]])
+    assert len(a) == 9
+    assert isinstance(b.doit(), ArrayComprehension)
+    assert isinstance(a.doit(), ImmutableDenseNDimArray)
+    assert b.subs(j, 3) == ArrayComprehension(i, (i, 1, 4))
+    assert b.free_symbols == {j}
+    assert b.shape == (j + 1,)
+    assert b.rank() == 1
+    assert b.is_shape_numeric == False
+    assert c.free_symbols == set()
+    assert c.function == i + j + k + l
+    assert c.limits == ((i, 1, 2), (j, 1, 3), (k, 1, 4), (l, 1, 5))
+    assert c.doit().tolist() == [[[[4, 5, 6, 7, 8], [5, 6, 7, 8, 9], [6, 7, 8, 9, 10], [7, 8, 9, 10, 11]],
+                                  [[5, 6, 7, 8, 9], [6, 7, 8, 9, 10], [7, 8, 9, 10, 11], [8, 9, 10, 11, 12]],
+                                  [[6, 7, 8, 9, 10], [7, 8, 9, 10, 11], [8, 9, 10, 11, 12], [9, 10, 11, 12, 13]]],
+                                 [[[5, 6, 7, 8, 9], [6, 7, 8, 9, 10], [7, 8, 9, 10, 11], [8, 9, 10, 11, 12]],
+                                  [[6, 7, 8, 9, 10], [7, 8, 9, 10, 11], [8, 9, 10, 11, 12], [9, 10, 11, 12, 13]],
+                                  [[7, 8, 9, 10, 11], [8, 9, 10, 11, 12], [9, 10, 11, 12, 13], [10, 11, 12, 13, 14]]]]
+    assert c.free_symbols == set()
+    assert c.variables == [i, j, k, l]
+    assert c.bound_symbols == [i, j, k, l]
+    assert d.doit().tolist() == [k, k, k, k, k]
+    assert len(e) == 5
+    raises(TypeError, lambda: ArrayComprehension(i*j, (i, 1, 3), (j, 2, [1, 3, 2])))
+    raises(ValueError, lambda: ArrayComprehension(i*j, (i, 1, 3), (j, 2, 1)))
+    raises(ValueError, lambda: ArrayComprehension(i*j, (i, 1, 3), (j, 2, j+1)))
+    raises(ValueError, lambda: len(ArrayComprehension(i*j, (i, 1, 3), (j, 2, j+4))))
+    raises(TypeError, lambda: ArrayComprehension(i*j, (i, 0, i + 1.5), (j, 0, 2)))
+    raises(ValueError, lambda: b.tolist())
+    raises(ValueError, lambda: b.tomatrix())
+    raises(ValueError, lambda: c.tomatrix())
+
+def test_arraycomprehensionmap():
+    a = ArrayComprehensionMap(lambda i: i+1, (i, 1, 5))
+    assert a.doit().tolist() == [2, 3, 4, 5, 6]
+    assert a.shape == (5,)
+    assert a.is_shape_numeric
+    assert a.tolist() == [2, 3, 4, 5, 6]
+    assert len(a) == 5
+    assert isinstance(a.doit(), ImmutableDenseNDimArray)
+    expr = ArrayComprehensionMap(lambda i: i+1, (i, 1, k))
+    assert expr.doit() == expr
+    assert expr.subs(k, 4) == ArrayComprehensionMap(lambda i: i+1, (i, 1, 4))
+    assert expr.subs(k, 4).doit() == ImmutableDenseNDimArray([2, 3, 4, 5])
+    b = ArrayComprehensionMap(lambda i: i+1, (i, 1, 2), (i, 1, 3), (i, 1, 4), (i, 1, 5))
+    assert b.doit().tolist() == [[[[2, 3, 4, 5, 6], [3, 5, 7, 9, 11], [4, 7, 10, 13, 16], [5, 9, 13, 17, 21]],
+                                  [[3, 5, 7, 9, 11], [5, 9, 13, 17, 21], [7, 13, 19, 25, 31], [9, 17, 25, 33, 41]],
+                                  [[4, 7, 10, 13, 16], [7, 13, 19, 25, 31], [10, 19, 28, 37, 46], [13, 25, 37, 49, 61]]],
+                                 [[[3, 5, 7, 9, 11], [5, 9, 13, 17, 21], [7, 13, 19, 25, 31], [9, 17, 25, 33, 41]],
+                                  [[5, 9, 13, 17, 21], [9, 17, 25, 33, 41], [13, 25, 37, 49, 61], [17, 33, 49, 65, 81]],
+                                  [[7, 13, 19, 25, 31], [13, 25, 37, 49, 61], [19, 37, 55, 73, 91], [25, 49, 73, 97, 121]]]]
+
+    # tests about lambda expression
+    assert ArrayComprehensionMap(lambda: 3, (i, 1, 5)).doit().tolist() == [3, 3, 3, 3, 3]
+    assert ArrayComprehensionMap(lambda i: i+1, (i, 1, 5)).doit().tolist() == [2, 3, 4, 5, 6]
+    raises(ValueError, lambda: ArrayComprehensionMap(i*j, (i, 1, 3), (j, 2, 4)))
+    a = ArrayComprehensionMap(lambda i, j: i+j, (i, 1, 5))
+    raises(ValueError, lambda: a.doit())
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_array_derivatives.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_array_derivatives.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f6c777c55a9170704f309bf74387d140bf2ec32
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_array_derivatives.py
@@ -0,0 +1,52 @@
+from sympy.core.symbol import symbols
+from sympy.matrices.dense import Matrix
+from sympy.matrices.expressions.matexpr import MatrixSymbol
+from sympy.tensor.array.ndim_array import NDimArray
+from sympy.matrices.matrixbase import MatrixBase
+from sympy.tensor.array.array_derivatives import ArrayDerivative
+
+x, y, z, t = symbols("x y z t")
+
+m = Matrix([[x, y], [z, t]])
+
+M = MatrixSymbol("M", 3, 2)
+N = MatrixSymbol("N", 4, 3)
+
+
+def test_array_derivative_construction():
+
+    d = ArrayDerivative(x, m, evaluate=False)
+    assert d.shape == (2, 2)
+    expr = d.doit()
+    assert isinstance(expr, MatrixBase)
+    assert expr.shape == (2, 2)
+
+    d = ArrayDerivative(m, m, evaluate=False)
+    assert d.shape == (2, 2, 2, 2)
+    expr = d.doit()
+    assert isinstance(expr, NDimArray)
+    assert expr.shape == (2, 2, 2, 2)
+
+    d = ArrayDerivative(m, x, evaluate=False)
+    assert d.shape == (2, 2)
+    expr = d.doit()
+    assert isinstance(expr, MatrixBase)
+    assert expr.shape == (2, 2)
+
+    d = ArrayDerivative(M, N, evaluate=False)
+    assert d.shape == (4, 3, 3, 2)
+    expr = d.doit()
+    assert isinstance(expr, ArrayDerivative)
+    assert expr.shape == (4, 3, 3, 2)
+
+    d = ArrayDerivative(M, (N, 2), evaluate=False)
+    assert d.shape == (4, 3, 4, 3, 3, 2)
+    expr = d.doit()
+    assert isinstance(expr, ArrayDerivative)
+    assert expr.shape == (4, 3, 4, 3, 3, 2)
+
+    d = ArrayDerivative(M.as_explicit(), (N.as_explicit(), 2), evaluate=False)
+    assert d.doit().shape == (4, 3, 4, 3, 3, 2)
+    expr = d.doit()
+    assert isinstance(expr, NDimArray)
+    assert expr.shape == (4, 3, 4, 3, 3, 2)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_arrayop.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_arrayop.py
new file mode 100644
index 0000000000000000000000000000000000000000..de56e81e0064f1e303a7a58e41932d15f2d0b41e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_arrayop.py
@@ -0,0 +1,361 @@
+import itertools
+import random
+
+from sympy.combinatorics import Permutation
+from sympy.combinatorics.permutations import _af_invert
+from sympy.testing.pytest import raises
+
+from sympy.core.function import diff
+from sympy.core.symbol import symbols
+from sympy.functions.elementary.complexes import (adjoint, conjugate, transpose)
+from sympy.functions.elementary.exponential import (exp, log)
+from sympy.functions.elementary.trigonometric import (cos, sin)
+from sympy.tensor.array import Array, ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableSparseNDimArray
+
+from sympy.tensor.array.arrayop import tensorproduct, tensorcontraction, derive_by_array, permutedims, Flatten, \
+    tensordiagonal
+
+
+def test_import_NDimArray():
+    from sympy.tensor.array import NDimArray
+    del NDimArray
+
+
+def test_tensorproduct():
+    x,y,z,t = symbols('x y z t')
+    from sympy.abc import a,b,c,d
+    assert tensorproduct() == 1
+    assert tensorproduct([x]) == Array([x])
+    assert tensorproduct([x], [y]) == Array([[x*y]])
+    assert tensorproduct([x], [y], [z]) == Array([[[x*y*z]]])
+    assert tensorproduct([x], [y], [z], [t]) == Array([[[[x*y*z*t]]]])
+
+    assert tensorproduct(x) == x
+    assert tensorproduct(x, y) == x*y
+    assert tensorproduct(x, y, z) == x*y*z
+    assert tensorproduct(x, y, z, t) == x*y*z*t
+
+    for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
+        A = ArrayType([x, y])
+        B = ArrayType([1, 2, 3])
+        C = ArrayType([a, b, c, d])
+
+        assert tensorproduct(A, B, C) == ArrayType([[[a*x, b*x, c*x, d*x], [2*a*x, 2*b*x, 2*c*x, 2*d*x], [3*a*x, 3*b*x, 3*c*x, 3*d*x]],
+                                                    [[a*y, b*y, c*y, d*y], [2*a*y, 2*b*y, 2*c*y, 2*d*y], [3*a*y, 3*b*y, 3*c*y, 3*d*y]]])
+
+        assert tensorproduct([x, y], [1, 2, 3]) == tensorproduct(A, B)
+
+        assert tensorproduct(A, 2) == ArrayType([2*x, 2*y])
+        assert tensorproduct(A, [2]) == ArrayType([[2*x], [2*y]])
+        assert tensorproduct([2], A) == ArrayType([[2*x, 2*y]])
+        assert tensorproduct(a, A) == ArrayType([a*x, a*y])
+        assert tensorproduct(a, A, B) == ArrayType([[a*x, 2*a*x, 3*a*x], [a*y, 2*a*y, 3*a*y]])
+        assert tensorproduct(A, B, a) == ArrayType([[a*x, 2*a*x, 3*a*x], [a*y, 2*a*y, 3*a*y]])
+        assert tensorproduct(B, a, A) == ArrayType([[a*x, a*y], [2*a*x, 2*a*y], [3*a*x, 3*a*y]])
+
+    # tests for large scale sparse array
+    for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]:
+        a = SparseArrayType({1:2, 3:4},(1000, 2000))
+        b = SparseArrayType({1:2, 3:4},(1000, 2000))
+        assert tensorproduct(a, b) == ImmutableSparseNDimArray({2000001: 4, 2000003: 8, 6000001: 8, 6000003: 16}, (1000, 2000, 1000, 2000))
+
+
+def test_tensorcontraction():
+    from sympy.abc import a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x
+    B = Array(range(18), (2, 3, 3))
+    assert tensorcontraction(B, (1, 2)) == Array([12, 39])
+    C1 = Array([a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x], (2, 3, 2, 2))
+
+    assert tensorcontraction(C1, (0, 2)) == Array([[a + o, b + p], [e + s, f + t], [i + w, j + x]])
+    assert tensorcontraction(C1, (0, 2, 3)) == Array([a + p, e + t, i + x])
+    assert tensorcontraction(C1, (2, 3)) == Array([[a + d, e + h, i + l], [m + p, q + t, u + x]])
+
+
+def test_derivative_by_array():
+    from sympy.abc import i, j, t, x, y, z
+
+    bexpr = x*y**2*exp(z)*log(t)
+    sexpr = sin(bexpr)
+    cexpr = cos(bexpr)
+
+    a = Array([sexpr])
+
+    assert derive_by_array(sexpr, t) == x*y**2*exp(z)*cos(x*y**2*exp(z)*log(t))/t
+    assert derive_by_array(sexpr, [x, y, z]) == Array([bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr, bexpr*cexpr])
+    assert derive_by_array(a, [x, y, z]) == Array([[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr], [bexpr*cexpr]])
+
+    assert derive_by_array(sexpr, [[x, y], [z, t]]) == Array([[bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr], [bexpr*cexpr, bexpr/log(t)/t*cexpr]])
+    assert derive_by_array(a, [[x, y], [z, t]]) == Array([[[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr]], [[bexpr*cexpr], [bexpr/log(t)/t*cexpr]]])
+    assert derive_by_array([[x, y], [z, t]], [x, y]) == Array([[[1, 0], [0, 0]], [[0, 1], [0, 0]]])
+    assert derive_by_array([[x, y], [z, t]], [[x, y], [z, t]]) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]],
+                                                                         [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
+
+    assert diff(sexpr, t) == x*y**2*exp(z)*cos(x*y**2*exp(z)*log(t))/t
+    assert diff(sexpr, Array([x, y, z])) == Array([bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr, bexpr*cexpr])
+    assert diff(a, Array([x, y, z])) == Array([[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr], [bexpr*cexpr]])
+
+    assert diff(sexpr, Array([[x, y], [z, t]])) == Array([[bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr], [bexpr*cexpr, bexpr/log(t)/t*cexpr]])
+    assert diff(a, Array([[x, y], [z, t]])) == Array([[[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr]], [[bexpr*cexpr], [bexpr/log(t)/t*cexpr]]])
+    assert diff(Array([[x, y], [z, t]]), Array([x, y])) == Array([[[1, 0], [0, 0]], [[0, 1], [0, 0]]])
+    assert diff(Array([[x, y], [z, t]]), Array([[x, y], [z, t]])) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]],
+                                                                         [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
+
+    # test for large scale sparse array
+    for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]:
+        b = MutableSparseNDimArray({0:i, 1:j}, (10000, 20000))
+        assert derive_by_array(b, i) == ImmutableSparseNDimArray({0: 1}, (10000, 20000))
+        assert derive_by_array(b, (i, j)) == ImmutableSparseNDimArray({0: 1, 200000001: 1}, (2, 10000, 20000))
+
+    #https://github.com/sympy/sympy/issues/20655
+    U = Array([x, y, z])
+    E = 2
+    assert derive_by_array(E, U) ==  ImmutableDenseNDimArray([0, 0, 0])
+
+
+def test_issue_emerged_while_discussing_10972():
+    ua = Array([-1,0])
+    Fa = Array([[0, 1], [-1, 0]])
+    po = tensorproduct(Fa, ua, Fa, ua)
+    assert tensorcontraction(po, (1, 2), (4, 5)) == Array([[0, 0], [0, 1]])
+
+    sa = symbols('a0:144')
+    po = Array(sa, [2, 2, 3, 3, 2, 2])
+    assert tensorcontraction(po, (0, 1), (2, 3), (4, 5)) == sa[0] + sa[108] + sa[111] + sa[124] + sa[127] + sa[140] + sa[143] + sa[16] + sa[19] + sa[3] + sa[32] + sa[35]
+    assert tensorcontraction(po, (0, 1, 4, 5), (2, 3)) == sa[0] + sa[111] + sa[127] + sa[143] + sa[16] + sa[32]
+    assert tensorcontraction(po, (0, 1), (4, 5)) == Array([[sa[0] + sa[108] + sa[111] + sa[3], sa[112] + sa[115] + sa[4] + sa[7],
+                                                             sa[11] + sa[116] + sa[119] + sa[8]], [sa[12] + sa[120] + sa[123] + sa[15],
+                                                             sa[124] + sa[127] + sa[16] + sa[19], sa[128] + sa[131] + sa[20] + sa[23]],
+                                                            [sa[132] + sa[135] + sa[24] + sa[27], sa[136] + sa[139] + sa[28] + sa[31],
+                                                             sa[140] + sa[143] + sa[32] + sa[35]]])
+    assert tensorcontraction(po, (0, 1), (2, 3)) == Array([[sa[0] + sa[108] + sa[124] + sa[140] + sa[16] + sa[32], sa[1] + sa[109] + sa[125] + sa[141] + sa[17] + sa[33]],
+                                                           [sa[110] + sa[126] + sa[142] + sa[18] + sa[2] + sa[34], sa[111] + sa[127] + sa[143] + sa[19] + sa[3] + sa[35]]])
+
+
+def test_array_permutedims():
+    sa = symbols('a0:144')
+
+    for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
+        m1 = ArrayType(sa[:6], (2, 3))
+        assert permutedims(m1, (1, 0)) == transpose(m1)
+        assert m1.tomatrix().T == permutedims(m1, (1, 0)).tomatrix()
+
+        assert m1.tomatrix().T == transpose(m1).tomatrix()
+        assert m1.tomatrix().C == conjugate(m1).tomatrix()
+        assert m1.tomatrix().H == adjoint(m1).tomatrix()
+
+        assert m1.tomatrix().T == m1.transpose().tomatrix()
+        assert m1.tomatrix().C == m1.conjugate().tomatrix()
+        assert m1.tomatrix().H == m1.adjoint().tomatrix()
+
+        raises(ValueError, lambda: permutedims(m1, (0,)))
+        raises(ValueError, lambda: permutedims(m1, (0, 0)))
+        raises(ValueError, lambda: permutedims(m1, (1, 2, 0)))
+
+        # Some tests with random arrays:
+        dims = 6
+        shape = [random.randint(1,5) for i in range(dims)]
+        elems = [random.random() for i in range(tensorproduct(*shape))]
+        ra = ArrayType(elems, shape)
+        perm = list(range(dims))
+        # Randomize the permutation:
+        random.shuffle(perm)
+        # Test inverse permutation:
+        assert permutedims(permutedims(ra, perm), _af_invert(perm)) == ra
+        # Test that permuted shape corresponds to action by `Permutation`:
+        assert permutedims(ra, perm).shape == tuple(Permutation(perm)(shape))
+
+        z = ArrayType.zeros(4,5,6,7)
+
+        assert permutedims(z, (2, 3, 1, 0)).shape == (6, 7, 5, 4)
+        assert permutedims(z, [2, 3, 1, 0]).shape == (6, 7, 5, 4)
+        assert permutedims(z, Permutation([2, 3, 1, 0])).shape == (6, 7, 5, 4)
+
+        po = ArrayType(sa, [2, 2, 3, 3, 2, 2])
+
+        raises(ValueError, lambda: permutedims(po, (1, 1)))
+        raises(ValueError, lambda: po.transpose())
+        raises(ValueError, lambda: po.adjoint())
+
+        assert permutedims(po, reversed(range(po.rank()))) == ArrayType(
+            [[[[[[sa[0], sa[72]], [sa[36], sa[108]]], [[sa[12], sa[84]], [sa[48], sa[120]]], [[sa[24],
+                                                                                               sa[96]], [sa[60], sa[132]]]],
+               [[[sa[4], sa[76]], [sa[40], sa[112]]], [[sa[16],
+                                                        sa[88]], [sa[52], sa[124]]],
+                [[sa[28], sa[100]], [sa[64], sa[136]]]],
+               [[[sa[8],
+                  sa[80]], [sa[44], sa[116]]], [[sa[20], sa[92]], [sa[56], sa[128]]], [[sa[32],
+                                                                                        sa[104]], [sa[68], sa[140]]]]],
+              [[[[sa[2], sa[74]], [sa[38], sa[110]]], [[sa[14],
+                                                        sa[86]], [sa[50], sa[122]]], [[sa[26], sa[98]], [sa[62], sa[134]]]],
+               [[[sa[6],
+                  sa[78]], [sa[42], sa[114]]], [[sa[18], sa[90]], [sa[54], sa[126]]], [[sa[30],
+                                                                                        sa[102]], [sa[66], sa[138]]]],
+               [[[sa[10], sa[82]], [sa[46], sa[118]]], [[sa[22],
+                                                         sa[94]], [sa[58], sa[130]]],
+                [[sa[34], sa[106]], [sa[70], sa[142]]]]]],
+             [[[[[sa[1],
+                  sa[73]], [sa[37], sa[109]]], [[sa[13], sa[85]], [sa[49], sa[121]]], [[sa[25],
+                                                                                        sa[97]], [sa[61], sa[133]]]],
+               [[[sa[5], sa[77]], [sa[41], sa[113]]], [[sa[17],
+                                                        sa[89]], [sa[53], sa[125]]],
+                [[sa[29], sa[101]], [sa[65], sa[137]]]],
+               [[[sa[9],
+                  sa[81]], [sa[45], sa[117]]], [[sa[21], sa[93]], [sa[57], sa[129]]], [[sa[33],
+                                                                                        sa[105]], [sa[69], sa[141]]]]],
+              [[[[sa[3], sa[75]], [sa[39], sa[111]]], [[sa[15],
+                                                        sa[87]], [sa[51], sa[123]]], [[sa[27], sa[99]], [sa[63], sa[135]]]],
+               [[[sa[7],
+                  sa[79]], [sa[43], sa[115]]], [[sa[19], sa[91]], [sa[55], sa[127]]], [[sa[31],
+                                                                                        sa[103]], [sa[67], sa[139]]]],
+               [[[sa[11], sa[83]], [sa[47], sa[119]]], [[sa[23],
+                                                         sa[95]], [sa[59], sa[131]]],
+                [[sa[35], sa[107]], [sa[71], sa[143]]]]]]])
+
+        assert permutedims(po, (1, 0, 2, 3, 4, 5)) == ArrayType(
+            [[[[[[sa[0], sa[1]], [sa[2], sa[3]]], [[sa[4], sa[5]], [sa[6], sa[7]]], [[sa[8], sa[9]], [sa[10],
+                                                                                                      sa[11]]]],
+               [[[sa[12], sa[13]], [sa[14], sa[15]]], [[sa[16], sa[17]], [sa[18],
+                                                                          sa[19]]], [[sa[20], sa[21]], [sa[22], sa[23]]]],
+               [[[sa[24], sa[25]], [sa[26],
+                                    sa[27]]], [[sa[28], sa[29]], [sa[30], sa[31]]], [[sa[32], sa[33]], [sa[34],
+                                                                                                        sa[35]]]]],
+              [[[[sa[72], sa[73]], [sa[74], sa[75]]], [[sa[76], sa[77]], [sa[78],
+                                                                          sa[79]]], [[sa[80], sa[81]], [sa[82], sa[83]]]],
+               [[[sa[84], sa[85]], [sa[86],
+                                    sa[87]]], [[sa[88], sa[89]], [sa[90], sa[91]]], [[sa[92], sa[93]], [sa[94],
+                                                                                                        sa[95]]]],
+               [[[sa[96], sa[97]], [sa[98], sa[99]]], [[sa[100], sa[101]], [sa[102],
+                                                                            sa[103]]],
+                [[sa[104], sa[105]], [sa[106], sa[107]]]]]], [[[[[sa[36], sa[37]], [sa[38],
+                                                                                    sa[39]]],
+                                                                [[sa[40], sa[41]], [sa[42], sa[43]]],
+                                                                [[sa[44], sa[45]], [sa[46],
+                                                                                    sa[47]]]],
+                                                               [[[sa[48], sa[49]], [sa[50], sa[51]]],
+                                                                [[sa[52], sa[53]], [sa[54],
+                                                                                    sa[55]]],
+                                                                [[sa[56], sa[57]], [sa[58], sa[59]]]],
+                                                               [[[sa[60], sa[61]], [sa[62],
+                                                                                    sa[63]]],
+                                                                [[sa[64], sa[65]], [sa[66], sa[67]]],
+                                                                [[sa[68], sa[69]], [sa[70],
+                                                                                    sa[71]]]]], [
+                                                                  [[[sa[108], sa[109]], [sa[110], sa[111]]],
+                                                                   [[sa[112], sa[113]], [sa[114],
+                                                                                         sa[115]]],
+                                                                   [[sa[116], sa[117]], [sa[118], sa[119]]]],
+                                                                  [[[sa[120], sa[121]], [sa[122],
+                                                                                         sa[123]]],
+                                                                   [[sa[124], sa[125]], [sa[126], sa[127]]],
+                                                                   [[sa[128], sa[129]], [sa[130],
+                                                                                         sa[131]]]],
+                                                                  [[[sa[132], sa[133]], [sa[134], sa[135]]],
+                                                                   [[sa[136], sa[137]], [sa[138],
+                                                                                         sa[139]]],
+                                                                   [[sa[140], sa[141]], [sa[142], sa[143]]]]]]])
+
+        assert permutedims(po, (0, 2, 1, 4, 3, 5)) == ArrayType(
+            [[[[[[sa[0], sa[1]], [sa[4], sa[5]], [sa[8], sa[9]]], [[sa[2], sa[3]], [sa[6], sa[7]], [sa[10],
+                                                                                                    sa[11]]]],
+               [[[sa[36], sa[37]], [sa[40], sa[41]], [sa[44], sa[45]]], [[sa[38],
+                                                                          sa[39]], [sa[42], sa[43]], [sa[46], sa[47]]]]],
+              [[[[sa[12], sa[13]], [sa[16],
+                                    sa[17]], [sa[20], sa[21]]], [[sa[14], sa[15]], [sa[18], sa[19]], [sa[22],
+                                                                                                      sa[23]]]],
+               [[[sa[48], sa[49]], [sa[52], sa[53]], [sa[56], sa[57]]], [[sa[50],
+                                                                          sa[51]], [sa[54], sa[55]], [sa[58], sa[59]]]]],
+              [[[[sa[24], sa[25]], [sa[28],
+                                    sa[29]], [sa[32], sa[33]]], [[sa[26], sa[27]], [sa[30], sa[31]], [sa[34],
+                                                                                                      sa[35]]]],
+               [[[sa[60], sa[61]], [sa[64], sa[65]], [sa[68], sa[69]]], [[sa[62],
+                                                                          sa[63]], [sa[66], sa[67]], [sa[70], sa[71]]]]]],
+             [[[[[sa[72], sa[73]], [sa[76],
+                                    sa[77]], [sa[80], sa[81]]], [[sa[74], sa[75]], [sa[78], sa[79]], [sa[82],
+                                                                                                      sa[83]]]],
+               [[[sa[108], sa[109]], [sa[112], sa[113]], [sa[116], sa[117]]], [[sa[110],
+                                                                                sa[111]], [sa[114], sa[115]],
+                                                                               [sa[118], sa[119]]]]],
+              [[[[sa[84], sa[85]], [sa[88],
+                                    sa[89]], [sa[92], sa[93]]], [[sa[86], sa[87]], [sa[90], sa[91]], [sa[94],
+                                                                                                      sa[95]]]],
+               [[[sa[120], sa[121]], [sa[124], sa[125]], [sa[128], sa[129]]], [[sa[122],
+                                                                                sa[123]], [sa[126], sa[127]],
+                                                                               [sa[130], sa[131]]]]],
+              [[[[sa[96], sa[97]], [sa[100],
+                                    sa[101]], [sa[104], sa[105]]], [[sa[98], sa[99]], [sa[102], sa[103]], [sa[106],
+                                                                                                           sa[107]]]],
+               [[[sa[132], sa[133]], [sa[136], sa[137]], [sa[140], sa[141]]], [[sa[134],
+                                                                                sa[135]], [sa[138], sa[139]],
+                                                                               [sa[142], sa[143]]]]]]])
+
+        po2 = po.reshape(4, 9, 2, 2)
+        assert po2 == ArrayType([[[[sa[0], sa[1]], [sa[2], sa[3]]], [[sa[4], sa[5]], [sa[6], sa[7]]], [[sa[8], sa[9]], [sa[10], sa[11]]], [[sa[12], sa[13]], [sa[14], sa[15]]], [[sa[16], sa[17]], [sa[18], sa[19]]], [[sa[20], sa[21]], [sa[22], sa[23]]], [[sa[24], sa[25]], [sa[26], sa[27]]], [[sa[28], sa[29]], [sa[30], sa[31]]], [[sa[32], sa[33]], [sa[34], sa[35]]]], [[[sa[36], sa[37]], [sa[38], sa[39]]], [[sa[40], sa[41]], [sa[42], sa[43]]], [[sa[44], sa[45]], [sa[46], sa[47]]], [[sa[48], sa[49]], [sa[50], sa[51]]], [[sa[52], sa[53]], [sa[54], sa[55]]], [[sa[56], sa[57]], [sa[58], sa[59]]], [[sa[60], sa[61]], [sa[62], sa[63]]], [[sa[64], sa[65]], [sa[66], sa[67]]], [[sa[68], sa[69]], [sa[70], sa[71]]]], [[[sa[72], sa[73]], [sa[74], sa[75]]], [[sa[76], sa[77]], [sa[78], sa[79]]], [[sa[80], sa[81]], [sa[82], sa[83]]], [[sa[84], sa[85]], [sa[86], sa[87]]], [[sa[88], sa[89]], [sa[90], sa[91]]], [[sa[92], sa[93]], [sa[94], sa[95]]], [[sa[96], sa[97]], [sa[98], sa[99]]], [[sa[100], sa[101]], [sa[102], sa[103]]], [[sa[104], sa[105]], [sa[106], sa[107]]]], [[[sa[108], sa[109]], [sa[110], sa[111]]], [[sa[112], sa[113]], [sa[114], sa[115]]], [[sa[116], sa[117]], [sa[118], sa[119]]], [[sa[120], sa[121]], [sa[122], sa[123]]], [[sa[124], sa[125]], [sa[126], sa[127]]], [[sa[128], sa[129]], [sa[130], sa[131]]], [[sa[132], sa[133]], [sa[134], sa[135]]], [[sa[136], sa[137]], [sa[138], sa[139]]], [[sa[140], sa[141]], [sa[142], sa[143]]]]])
+
+        assert permutedims(po2, (3, 2, 0, 1)) == ArrayType([[[[sa[0], sa[4], sa[8], sa[12], sa[16], sa[20], sa[24], sa[28], sa[32]], [sa[36], sa[40], sa[44], sa[48], sa[52], sa[56], sa[60], sa[64], sa[68]], [sa[72], sa[76], sa[80], sa[84], sa[88], sa[92], sa[96], sa[100], sa[104]], [sa[108], sa[112], sa[116], sa[120], sa[124], sa[128], sa[132], sa[136], sa[140]]], [[sa[2], sa[6], sa[10], sa[14], sa[18], sa[22], sa[26], sa[30], sa[34]], [sa[38], sa[42], sa[46], sa[50], sa[54], sa[58], sa[62], sa[66], sa[70]], [sa[74], sa[78], sa[82], sa[86], sa[90], sa[94], sa[98], sa[102], sa[106]], [sa[110], sa[114], sa[118], sa[122], sa[126], sa[130], sa[134], sa[138], sa[142]]]], [[[sa[1], sa[5], sa[9], sa[13], sa[17], sa[21], sa[25], sa[29], sa[33]], [sa[37], sa[41], sa[45], sa[49], sa[53], sa[57], sa[61], sa[65], sa[69]], [sa[73], sa[77], sa[81], sa[85], sa[89], sa[93], sa[97], sa[101], sa[105]], [sa[109], sa[113], sa[117], sa[121], sa[125], sa[129], sa[133], sa[137], sa[141]]], [[sa[3], sa[7], sa[11], sa[15], sa[19], sa[23], sa[27], sa[31], sa[35]], [sa[39], sa[43], sa[47], sa[51], sa[55], sa[59], sa[63], sa[67], sa[71]], [sa[75], sa[79], sa[83], sa[87], sa[91], sa[95], sa[99], sa[103], sa[107]], [sa[111], sa[115], sa[119], sa[123], sa[127], sa[131], sa[135], sa[139], sa[143]]]]])
+
+    # test for large scale sparse array
+    for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]:
+        A = SparseArrayType({1:1, 10000:2}, (10000, 20000, 10000))
+        assert permutedims(A, (0, 1, 2)) == A
+        assert permutedims(A, (1, 0, 2)) == SparseArrayType({1: 1, 100000000: 2}, (20000, 10000, 10000))
+        B = SparseArrayType({1:1, 20000:2}, (10000, 20000))
+        assert B.transpose() == SparseArrayType({10000: 1, 1: 2}, (20000, 10000))
+
+
+def test_permutedims_with_indices():
+    A = Array(range(32)).reshape(2, 2, 2, 2, 2)
+    indices_new = list("abcde")
+    indices_old = list("ebdac")
+    new_A = permutedims(A, index_order_new=indices_new, index_order_old=indices_old)
+    for a, b, c, d, e in itertools.product(range(2), range(2), range(2), range(2), range(2)):
+        assert new_A[a, b, c, d, e] == A[e, b, d, a, c]
+    indices_old = list("cabed")
+    new_A = permutedims(A, index_order_new=indices_new, index_order_old=indices_old)
+    for a, b, c, d, e in itertools.product(range(2), range(2), range(2), range(2), range(2)):
+        assert new_A[a, b, c, d, e] == A[c, a, b, e, d]
+    raises(ValueError, lambda: permutedims(A, index_order_old=list("aacde"), index_order_new=list("abcde")))
+    raises(ValueError, lambda: permutedims(A, index_order_old=list("abcde"), index_order_new=list("abcce")))
+    raises(ValueError, lambda: permutedims(A, index_order_old=list("abcde"), index_order_new=list("abce")))
+    raises(ValueError, lambda: permutedims(A, index_order_old=list("abce"), index_order_new=list("abce")))
+    raises(ValueError, lambda: permutedims(A, [2, 1, 0, 3, 4], index_order_old=list("abcde")))
+    raises(ValueError, lambda: permutedims(A, [2, 1, 0, 3, 4], index_order_new=list("abcde")))
+
+
+def test_flatten():
+    from sympy.matrices.dense import Matrix
+    for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray, Matrix]:
+        A = ArrayType(range(24)).reshape(4, 6)
+        assert list(Flatten(A)) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
+
+        for i, v in enumerate(Flatten(A)):
+            assert i == v
+
+
+def test_tensordiagonal():
+    from sympy.matrices.dense import eye
+    expr = Array(range(9)).reshape(3, 3)
+    raises(ValueError, lambda: tensordiagonal(expr, [0], [1]))
+    raises(ValueError, lambda: tensordiagonal(expr, [0, 0]))
+    assert tensordiagonal(eye(3), [0, 1]) == Array([1, 1, 1])
+    assert tensordiagonal(expr, [0, 1]) == Array([0, 4, 8])
+    x, y, z = symbols("x y z")
+    expr2 = tensorproduct([x, y, z], expr)
+    assert tensordiagonal(expr2, [1, 2]) == Array([[0, 4*x, 8*x], [0, 4*y, 8*y], [0, 4*z, 8*z]])
+    assert tensordiagonal(expr2, [0, 1]) == Array([[0, 3*y, 6*z], [x, 4*y, 7*z], [2*x, 5*y, 8*z]])
+    assert tensordiagonal(expr2, [0, 1, 2]) == Array([0, 4*y, 8*z])
+    # assert tensordiagonal(expr2, [0]) == permutedims(expr2, [1, 2, 0])
+    # assert tensordiagonal(expr2, [1]) == permutedims(expr2, [0, 2, 1])
+    # assert tensordiagonal(expr2, [2]) == expr2
+    # assert tensordiagonal(expr2, [1], [2]) == expr2
+    # assert tensordiagonal(expr2, [0], [1]) == permutedims(expr2, [2, 0, 1])
+
+    a, b, c, X, Y, Z = symbols("a b c X Y Z")
+    expr3 = tensorproduct([x, y, z], [1, 2, 3], [a, b, c], [X, Y, Z])
+    assert tensordiagonal(expr3, [0, 1, 2, 3]) == Array([x*a*X, 2*y*b*Y, 3*z*c*Z])
+    assert tensordiagonal(expr3, [0, 1], [2, 3]) == tensorproduct([x, 2*y, 3*z], [a*X, b*Y, c*Z])
+
+    # assert tensordiagonal(expr3, [0], [1, 2], [3]) == tensorproduct([x, y, z], [a, 2*b, 3*c], [X, Y, Z])
+    assert tensordiagonal(tensordiagonal(expr3, [2, 3]), [0, 1]) == tensorproduct([a*X, b*Y, c*Z], [x, 2*y, 3*z])
+
+    raises(ValueError, lambda: tensordiagonal([[1, 2, 3], [4, 5, 6]], [0, 1]))
+    raises(ValueError, lambda: tensordiagonal(expr3.reshape(3, 3, 9), [1, 2]))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_immutable_ndim_array.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_immutable_ndim_array.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6bed4b605c424284b4752592b03b13a9178aac8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_immutable_ndim_array.py
@@ -0,0 +1,452 @@
+from copy import copy
+
+from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
+from sympy.core.containers import Dict
+from sympy.core.function import diff
+from sympy.core.numbers import Rational
+from sympy.core.singleton import S
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.matrices import SparseMatrix
+from sympy.tensor.indexed import (Indexed, IndexedBase)
+from sympy.matrices import Matrix
+from sympy.tensor.array.sparse_ndim_array import ImmutableSparseNDimArray
+from sympy.testing.pytest import raises
+
+
+def test_ndim_array_initiation():
+    arr_with_no_elements = ImmutableDenseNDimArray([], shape=(0,))
+    assert len(arr_with_no_elements) == 0
+    assert arr_with_no_elements.rank() == 1
+
+    raises(ValueError, lambda: ImmutableDenseNDimArray([0], shape=(0,)))
+    raises(ValueError, lambda: ImmutableDenseNDimArray([1, 2, 3], shape=(0,)))
+    raises(ValueError, lambda: ImmutableDenseNDimArray([], shape=()))
+
+    raises(ValueError, lambda: ImmutableSparseNDimArray([0], shape=(0,)))
+    raises(ValueError, lambda: ImmutableSparseNDimArray([1, 2, 3], shape=(0,)))
+    raises(ValueError, lambda: ImmutableSparseNDimArray([], shape=()))
+
+    arr_with_one_element = ImmutableDenseNDimArray([23])
+    assert len(arr_with_one_element) == 1
+    assert arr_with_one_element[0] == 23
+    assert arr_with_one_element[:] == ImmutableDenseNDimArray([23])
+    assert arr_with_one_element.rank() == 1
+
+    arr_with_symbol_element = ImmutableDenseNDimArray([Symbol('x')])
+    assert len(arr_with_symbol_element) == 1
+    assert arr_with_symbol_element[0] == Symbol('x')
+    assert arr_with_symbol_element[:] == ImmutableDenseNDimArray([Symbol('x')])
+    assert arr_with_symbol_element.rank() == 1
+
+    number5 = 5
+    vector = ImmutableDenseNDimArray.zeros(number5)
+    assert len(vector) == number5
+    assert vector.shape == (number5,)
+    assert vector.rank() == 1
+
+    vector = ImmutableSparseNDimArray.zeros(number5)
+    assert len(vector) == number5
+    assert vector.shape == (number5,)
+    assert vector._sparse_array == Dict()
+    assert vector.rank() == 1
+
+    n_dim_array = ImmutableDenseNDimArray(range(3**4), (3, 3, 3, 3,))
+    assert len(n_dim_array) == 3 * 3 * 3 * 3
+    assert n_dim_array.shape == (3, 3, 3, 3)
+    assert n_dim_array.rank() == 4
+
+    array_shape = (3, 3, 3, 3)
+    sparse_array = ImmutableSparseNDimArray.zeros(*array_shape)
+    assert len(sparse_array._sparse_array) == 0
+    assert len(sparse_array) == 3 * 3 * 3 * 3
+    assert n_dim_array.shape == array_shape
+    assert n_dim_array.rank() == 4
+
+    one_dim_array = ImmutableDenseNDimArray([2, 3, 1])
+    assert len(one_dim_array) == 3
+    assert one_dim_array.shape == (3,)
+    assert one_dim_array.rank() == 1
+    assert one_dim_array.tolist() == [2, 3, 1]
+
+    shape = (3, 3)
+    array_with_many_args = ImmutableSparseNDimArray.zeros(*shape)
+    assert len(array_with_many_args) == 3 * 3
+    assert array_with_many_args.shape == shape
+    assert array_with_many_args[0, 0] == 0
+    assert array_with_many_args.rank() == 2
+
+    shape = (int(3), int(3))
+    array_with_long_shape = ImmutableSparseNDimArray.zeros(*shape)
+    assert len(array_with_long_shape) == 3 * 3
+    assert array_with_long_shape.shape == shape
+    assert array_with_long_shape[int(0), int(0)] == 0
+    assert array_with_long_shape.rank() == 2
+
+    vector_with_long_shape = ImmutableDenseNDimArray(range(5), int(5))
+    assert len(vector_with_long_shape) == 5
+    assert vector_with_long_shape.shape == (int(5),)
+    assert vector_with_long_shape.rank() == 1
+    raises(ValueError, lambda: vector_with_long_shape[int(5)])
+
+    from sympy.abc import x
+    for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
+        rank_zero_array = ArrayType(x)
+        assert len(rank_zero_array) == 1
+        assert rank_zero_array.shape == ()
+        assert rank_zero_array.rank() == 0
+        assert rank_zero_array[()] == x
+        raises(ValueError, lambda: rank_zero_array[0])
+
+
+def test_reshape():
+    array = ImmutableDenseNDimArray(range(50), 50)
+    assert array.shape == (50,)
+    assert array.rank() == 1
+
+    array = array.reshape(5, 5, 2)
+    assert array.shape == (5, 5, 2)
+    assert array.rank() == 3
+    assert len(array) == 50
+
+
+def test_getitem():
+    for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
+        array = ArrayType(range(24)).reshape(2, 3, 4)
+        assert array.tolist() == [[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]]
+        assert array[0] == ArrayType([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])
+        assert array[0, 0] == ArrayType([0, 1, 2, 3])
+        value = 0
+        for i in range(2):
+            for j in range(3):
+                for k in range(4):
+                    assert array[i, j, k] == value
+                    value += 1
+
+    raises(ValueError, lambda: array[3, 4, 5])
+    raises(ValueError, lambda: array[3, 4, 5, 6])
+    raises(ValueError, lambda: array[3, 4, 5, 3:4])
+
+
+def test_iterator():
+    array = ImmutableDenseNDimArray(range(4), (2, 2))
+    assert array[0] == ImmutableDenseNDimArray([0, 1])
+    assert array[1] == ImmutableDenseNDimArray([2, 3])
+
+    array = array.reshape(4)
+    j = 0
+    for i in array:
+        assert i == j
+        j += 1
+
+
+def test_sparse():
+    sparse_array = ImmutableSparseNDimArray([0, 0, 0, 1], (2, 2))
+    assert len(sparse_array) == 2 * 2
+    # dictionary where all data is, only non-zero entries are actually stored:
+    assert len(sparse_array._sparse_array) == 1
+
+    assert sparse_array.tolist() == [[0, 0], [0, 1]]
+
+    for i, j in zip(sparse_array, [[0, 0], [0, 1]]):
+        assert i == ImmutableSparseNDimArray(j)
+
+    def sparse_assignment():
+        sparse_array[0, 0] = 123
+
+    assert len(sparse_array._sparse_array) == 1
+    raises(TypeError, sparse_assignment)
+    assert len(sparse_array._sparse_array) == 1
+    assert sparse_array[0, 0] == 0
+    assert sparse_array/0 == ImmutableSparseNDimArray([[S.NaN, S.NaN], [S.NaN, S.ComplexInfinity]], (2, 2))
+
+    # test for large scale sparse array
+    # equality test
+    assert ImmutableSparseNDimArray.zeros(100000, 200000) == ImmutableSparseNDimArray.zeros(100000, 200000)
+
+    # __mul__ and __rmul__
+    a = ImmutableSparseNDimArray({200001: 1}, (100000, 200000))
+    assert a * 3 == ImmutableSparseNDimArray({200001: 3}, (100000, 200000))
+    assert 3 * a == ImmutableSparseNDimArray({200001: 3}, (100000, 200000))
+    assert a * 0 == ImmutableSparseNDimArray({}, (100000, 200000))
+    assert 0 * a == ImmutableSparseNDimArray({}, (100000, 200000))
+
+    # __truediv__
+    assert a/3 == ImmutableSparseNDimArray({200001: Rational(1, 3)}, (100000, 200000))
+
+    # __neg__
+    assert -a == ImmutableSparseNDimArray({200001: -1}, (100000, 200000))
+
+
+def test_calculation():
+
+    a = ImmutableDenseNDimArray([1]*9, (3, 3))
+    b = ImmutableDenseNDimArray([9]*9, (3, 3))
+
+    c = a + b
+    for i in c:
+        assert i == ImmutableDenseNDimArray([10, 10, 10])
+
+    assert c == ImmutableDenseNDimArray([10]*9, (3, 3))
+    assert c == ImmutableSparseNDimArray([10]*9, (3, 3))
+
+    c = b - a
+    for i in c:
+        assert i == ImmutableDenseNDimArray([8, 8, 8])
+
+    assert c == ImmutableDenseNDimArray([8]*9, (3, 3))
+    assert c == ImmutableSparseNDimArray([8]*9, (3, 3))
+
+
+def test_ndim_array_converting():
+    dense_array = ImmutableDenseNDimArray([1, 2, 3, 4], (2, 2))
+    alist = dense_array.tolist()
+
+    assert alist == [[1, 2], [3, 4]]
+
+    matrix = dense_array.tomatrix()
+    assert (isinstance(matrix, Matrix))
+
+    for i in range(len(dense_array)):
+        assert dense_array[dense_array._get_tuple_index(i)] == matrix[i]
+    assert matrix.shape == dense_array.shape
+
+    assert ImmutableDenseNDimArray(matrix) == dense_array
+    assert ImmutableDenseNDimArray(matrix.as_immutable()) == dense_array
+    assert ImmutableDenseNDimArray(matrix.as_mutable()) == dense_array
+
+    sparse_array = ImmutableSparseNDimArray([1, 2, 3, 4], (2, 2))
+    alist = sparse_array.tolist()
+
+    assert alist == [[1, 2], [3, 4]]
+
+    matrix = sparse_array.tomatrix()
+    assert(isinstance(matrix, SparseMatrix))
+
+    for i in range(len(sparse_array)):
+        assert sparse_array[sparse_array._get_tuple_index(i)] == matrix[i]
+    assert matrix.shape == sparse_array.shape
+
+    assert ImmutableSparseNDimArray(matrix) == sparse_array
+    assert ImmutableSparseNDimArray(matrix.as_immutable()) == sparse_array
+    assert ImmutableSparseNDimArray(matrix.as_mutable()) == sparse_array
+
+
+def test_converting_functions():
+    arr_list = [1, 2, 3, 4]
+    arr_matrix = Matrix(((1, 2), (3, 4)))
+
+    # list
+    arr_ndim_array = ImmutableDenseNDimArray(arr_list, (2, 2))
+    assert (isinstance(arr_ndim_array, ImmutableDenseNDimArray))
+    assert arr_matrix.tolist() == arr_ndim_array.tolist()
+
+    # Matrix
+    arr_ndim_array = ImmutableDenseNDimArray(arr_matrix)
+    assert (isinstance(arr_ndim_array, ImmutableDenseNDimArray))
+    assert arr_matrix.tolist() == arr_ndim_array.tolist()
+    assert arr_matrix.shape == arr_ndim_array.shape
+
+
+def test_equality():
+    first_list = [1, 2, 3, 4]
+    second_list = [1, 2, 3, 4]
+    third_list = [4, 3, 2, 1]
+    assert first_list == second_list
+    assert first_list != third_list
+
+    first_ndim_array = ImmutableDenseNDimArray(first_list, (2, 2))
+    second_ndim_array = ImmutableDenseNDimArray(second_list, (2, 2))
+    fourth_ndim_array = ImmutableDenseNDimArray(first_list, (2, 2))
+
+    assert first_ndim_array == second_ndim_array
+
+    def assignment_attempt(a):
+        a[0, 0] = 0
+
+    raises(TypeError, lambda: assignment_attempt(second_ndim_array))
+    assert first_ndim_array == second_ndim_array
+    assert first_ndim_array == fourth_ndim_array
+
+
+def test_arithmetic():
+    a = ImmutableDenseNDimArray([3 for i in range(9)], (3, 3))
+    b = ImmutableDenseNDimArray([7 for i in range(9)], (3, 3))
+
+    c1 = a + b
+    c2 = b + a
+    assert c1 == c2
+
+    d1 = a - b
+    d2 = b - a
+    assert d1 == d2 * (-1)
+
+    e1 = a * 5
+    e2 = 5 * a
+    e3 = copy(a)
+    e3 *= 5
+    assert e1 == e2 == e3
+
+    f1 = a / 5
+    f2 = copy(a)
+    f2 /= 5
+    assert f1 == f2
+    assert f1[0, 0] == f1[0, 1] == f1[0, 2] == f1[1, 0] == f1[1, 1] == \
+    f1[1, 2] == f1[2, 0] == f1[2, 1] == f1[2, 2] == Rational(3, 5)
+
+    assert type(a) == type(b) == type(c1) == type(c2) == type(d1) == type(d2) \
+        == type(e1) == type(e2) == type(e3) == type(f1)
+
+    z0 = -a
+    assert z0 == ImmutableDenseNDimArray([-3 for i in range(9)], (3, 3))
+
+
+def test_higher_dimenions():
+    m3 = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4))
+
+    assert m3.tolist() == [[[10, 11, 12, 13],
+            [14, 15, 16, 17],
+            [18, 19, 20, 21]],
+
+           [[22, 23, 24, 25],
+            [26, 27, 28, 29],
+            [30, 31, 32, 33]]]
+
+    assert m3._get_tuple_index(0) == (0, 0, 0)
+    assert m3._get_tuple_index(1) == (0, 0, 1)
+    assert m3._get_tuple_index(4) == (0, 1, 0)
+    assert m3._get_tuple_index(12) == (1, 0, 0)
+
+    assert str(m3) == '[[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]]'
+
+    m3_rebuilt = ImmutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]])
+    assert m3 == m3_rebuilt
+
+    m3_other = ImmutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]], (2, 3, 4))
+
+    assert m3 == m3_other
+
+
+def test_rebuild_immutable_arrays():
+    sparr = ImmutableSparseNDimArray(range(10, 34), (2, 3, 4))
+    densarr = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4))
+
+    assert sparr == sparr.func(*sparr.args)
+    assert densarr == densarr.func(*densarr.args)
+
+
+def test_slices():
+    md = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4))
+
+    assert md[:] == ImmutableDenseNDimArray(range(10, 34), (2, 3, 4))
+    assert md[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]])
+    assert md[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]])
+    assert md[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]])
+    assert md[:, :, :] == md
+
+    sd = ImmutableSparseNDimArray(range(10, 34), (2, 3, 4))
+    assert sd == ImmutableSparseNDimArray(md)
+
+    assert sd[:] == ImmutableSparseNDimArray(range(10, 34), (2, 3, 4))
+    assert sd[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]])
+    assert sd[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]])
+    assert sd[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]])
+    assert sd[:, :, :] == sd
+
+
+def test_diff_and_applyfunc():
+    from sympy.abc import x, y, z
+    md = ImmutableDenseNDimArray([[x, y], [x*z, x*y*z]])
+    assert md.diff(x) == ImmutableDenseNDimArray([[1, 0], [z, y*z]])
+    assert diff(md, x) == ImmutableDenseNDimArray([[1, 0], [z, y*z]])
+
+    sd = ImmutableSparseNDimArray(md)
+    assert sd == ImmutableSparseNDimArray([x, y, x*z, x*y*z], (2, 2))
+    assert sd.diff(x) == ImmutableSparseNDimArray([[1, 0], [z, y*z]])
+    assert diff(sd, x) == ImmutableSparseNDimArray([[1, 0], [z, y*z]])
+
+    mdn = md.applyfunc(lambda x: x*3)
+    assert mdn == ImmutableDenseNDimArray([[3*x, 3*y], [3*x*z, 3*x*y*z]])
+    assert md != mdn
+
+    sdn = sd.applyfunc(lambda x: x/2)
+    assert sdn == ImmutableSparseNDimArray([[x/2, y/2], [x*z/2, x*y*z/2]])
+    assert sd != sdn
+
+    sdp = sd.applyfunc(lambda x: x+1)
+    assert sdp == ImmutableSparseNDimArray([[x + 1, y + 1], [x*z + 1, x*y*z + 1]])
+    assert sd != sdp
+
+
+def test_op_priority():
+    from sympy.abc import x
+    md = ImmutableDenseNDimArray([1, 2, 3])
+    e1 = (1+x)*md
+    e2 = md*(1+x)
+    assert e1 == ImmutableDenseNDimArray([1+x, 2+2*x, 3+3*x])
+    assert e1 == e2
+
+    sd = ImmutableSparseNDimArray([1, 2, 3])
+    e3 = (1+x)*sd
+    e4 = sd*(1+x)
+    assert e3 == ImmutableDenseNDimArray([1+x, 2+2*x, 3+3*x])
+    assert e3 == e4
+
+
+def test_symbolic_indexing():
+    x, y, z, w = symbols("x y z w")
+    M = ImmutableDenseNDimArray([[x, y], [z, w]])
+    i, j = symbols("i, j")
+    Mij = M[i, j]
+    assert isinstance(Mij, Indexed)
+    Ms = ImmutableSparseNDimArray([[2, 3*x], [4, 5]])
+    msij = Ms[i, j]
+    assert isinstance(msij, Indexed)
+    for oi, oj in [(0, 0), (0, 1), (1, 0), (1, 1)]:
+        assert Mij.subs({i: oi, j: oj}) == M[oi, oj]
+        assert msij.subs({i: oi, j: oj}) == Ms[oi, oj]
+    A = IndexedBase("A", (0, 2))
+    assert A[0, 0].subs(A, M) == x
+    assert A[i, j].subs(A, M) == M[i, j]
+    assert M[i, j].subs(M, A) == A[i, j]
+
+    assert isinstance(M[3 * i - 2, j], Indexed)
+    assert M[3 * i - 2, j].subs({i: 1, j: 0}) == M[1, 0]
+    assert isinstance(M[i, 0], Indexed)
+    assert M[i, 0].subs(i, 0) == M[0, 0]
+    assert M[0, i].subs(i, 1) == M[0, 1]
+
+    assert M[i, j].diff(x) == ImmutableDenseNDimArray([[1, 0], [0, 0]])[i, j]
+    assert Ms[i, j].diff(x) == ImmutableSparseNDimArray([[0, 3], [0, 0]])[i, j]
+
+    Mo = ImmutableDenseNDimArray([1, 2, 3])
+    assert Mo[i].subs(i, 1) == 2
+    Mos = ImmutableSparseNDimArray([1, 2, 3])
+    assert Mos[i].subs(i, 1) == 2
+
+    raises(ValueError, lambda: M[i, 2])
+    raises(ValueError, lambda: M[i, -1])
+    raises(ValueError, lambda: M[2, i])
+    raises(ValueError, lambda: M[-1, i])
+
+    raises(ValueError, lambda: Ms[i, 2])
+    raises(ValueError, lambda: Ms[i, -1])
+    raises(ValueError, lambda: Ms[2, i])
+    raises(ValueError, lambda: Ms[-1, i])
+
+
+def test_issue_12665():
+    # Testing Python 3 hash of immutable arrays:
+    arr = ImmutableDenseNDimArray([1, 2, 3])
+    # This should NOT raise an exception:
+    hash(arr)
+
+
+def test_zeros_without_shape():
+    arr = ImmutableDenseNDimArray.zeros()
+    assert arr == ImmutableDenseNDimArray(0)
+
+def test_issue_21870():
+    a0 = ImmutableDenseNDimArray(0)
+    assert a0.rank() == 0
+    a1 = ImmutableDenseNDimArray(a0)
+    assert a1.rank() == 0
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_mutable_ndim_array.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_mutable_ndim_array.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a232f399bbc0639d326217975fb0a12e645a984
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_mutable_ndim_array.py
@@ -0,0 +1,374 @@
+from copy import copy
+
+from sympy.tensor.array.dense_ndim_array import MutableDenseNDimArray
+from sympy.core.function import diff
+from sympy.core.numbers import Rational
+from sympy.core.singleton import S
+from sympy.core.symbol import Symbol
+from sympy.core.sympify import sympify
+from sympy.matrices import SparseMatrix
+from sympy.matrices import Matrix
+from sympy.tensor.array.sparse_ndim_array import MutableSparseNDimArray
+from sympy.testing.pytest import raises
+
+
+def test_ndim_array_initiation():
+    arr_with_one_element = MutableDenseNDimArray([23])
+    assert len(arr_with_one_element) == 1
+    assert arr_with_one_element[0] == 23
+    assert arr_with_one_element.rank() == 1
+    raises(ValueError, lambda: arr_with_one_element[1])
+
+    arr_with_symbol_element = MutableDenseNDimArray([Symbol('x')])
+    assert len(arr_with_symbol_element) == 1
+    assert arr_with_symbol_element[0] == Symbol('x')
+    assert arr_with_symbol_element.rank() == 1
+
+    number5 = 5
+    vector = MutableDenseNDimArray.zeros(number5)
+    assert len(vector) == number5
+    assert vector.shape == (number5,)
+    assert vector.rank() == 1
+    raises(ValueError, lambda: arr_with_one_element[5])
+
+    vector = MutableSparseNDimArray.zeros(number5)
+    assert len(vector) == number5
+    assert vector.shape == (number5,)
+    assert vector._sparse_array == {}
+    assert vector.rank() == 1
+
+    n_dim_array = MutableDenseNDimArray(range(3**4), (3, 3, 3, 3,))
+    assert len(n_dim_array) == 3 * 3 * 3 * 3
+    assert n_dim_array.shape == (3, 3, 3, 3)
+    assert n_dim_array.rank() == 4
+    raises(ValueError, lambda: n_dim_array[0, 0, 0, 3])
+    raises(ValueError, lambda: n_dim_array[3, 0, 0, 0])
+    raises(ValueError, lambda: n_dim_array[3**4])
+
+    array_shape = (3, 3, 3, 3)
+    sparse_array = MutableSparseNDimArray.zeros(*array_shape)
+    assert len(sparse_array._sparse_array) == 0
+    assert len(sparse_array) == 3 * 3 * 3 * 3
+    assert n_dim_array.shape == array_shape
+    assert n_dim_array.rank() == 4
+
+    one_dim_array = MutableDenseNDimArray([2, 3, 1])
+    assert len(one_dim_array) == 3
+    assert one_dim_array.shape == (3,)
+    assert one_dim_array.rank() == 1
+    assert one_dim_array.tolist() == [2, 3, 1]
+
+    shape = (3, 3)
+    array_with_many_args = MutableSparseNDimArray.zeros(*shape)
+    assert len(array_with_many_args) == 3 * 3
+    assert array_with_many_args.shape == shape
+    assert array_with_many_args[0, 0] == 0
+    assert array_with_many_args.rank() == 2
+
+    shape = (int(3), int(3))
+    array_with_long_shape = MutableSparseNDimArray.zeros(*shape)
+    assert len(array_with_long_shape) == 3 * 3
+    assert array_with_long_shape.shape == shape
+    assert array_with_long_shape[int(0), int(0)] == 0
+    assert array_with_long_shape.rank() == 2
+
+    vector_with_long_shape = MutableDenseNDimArray(range(5), int(5))
+    assert len(vector_with_long_shape) == 5
+    assert vector_with_long_shape.shape == (int(5),)
+    assert vector_with_long_shape.rank() == 1
+    raises(ValueError, lambda: vector_with_long_shape[int(5)])
+
+    from sympy.abc import x
+    for ArrayType in [MutableDenseNDimArray, MutableSparseNDimArray]:
+        rank_zero_array = ArrayType(x)
+        assert len(rank_zero_array) == 1
+        assert rank_zero_array.shape == ()
+        assert rank_zero_array.rank() == 0
+        assert rank_zero_array[()] == x
+        raises(ValueError, lambda: rank_zero_array[0])
+
+def test_sympify():
+    from sympy.abc import x, y, z, t
+    arr = MutableDenseNDimArray([[x, y], [1, z*t]])
+    arr_other = sympify(arr)
+    assert arr_other.shape == (2, 2)
+    assert arr_other == arr
+
+
+def test_reshape():
+    array = MutableDenseNDimArray(range(50), 50)
+    assert array.shape == (50,)
+    assert array.rank() == 1
+
+    array = array.reshape(5, 5, 2)
+    assert array.shape == (5, 5, 2)
+    assert array.rank() == 3
+    assert len(array) == 50
+
+
+def test_iterator():
+    array = MutableDenseNDimArray(range(4), (2, 2))
+    assert array[0] == MutableDenseNDimArray([0, 1])
+    assert array[1] == MutableDenseNDimArray([2, 3])
+
+    array = array.reshape(4)
+    j = 0
+    for i in array:
+        assert i == j
+        j += 1
+
+
+def test_getitem():
+    for ArrayType in [MutableDenseNDimArray, MutableSparseNDimArray]:
+        array = ArrayType(range(24)).reshape(2, 3, 4)
+        assert array.tolist() == [[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]]
+        assert array[0] == ArrayType([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])
+        assert array[0, 0] == ArrayType([0, 1, 2, 3])
+        value = 0
+        for i in range(2):
+            for j in range(3):
+                for k in range(4):
+                    assert array[i, j, k] == value
+                    value += 1
+
+    raises(ValueError, lambda: array[3, 4, 5])
+    raises(ValueError, lambda: array[3, 4, 5, 6])
+    raises(ValueError, lambda: array[3, 4, 5, 3:4])
+
+
+def test_sparse():
+    sparse_array = MutableSparseNDimArray([0, 0, 0, 1], (2, 2))
+    assert len(sparse_array) == 2 * 2
+    # dictionary where all data is, only non-zero entries are actually stored:
+    assert len(sparse_array._sparse_array) == 1
+
+    assert sparse_array.tolist() == [[0, 0], [0, 1]]
+
+    for i, j in zip(sparse_array, [[0, 0], [0, 1]]):
+        assert i == MutableSparseNDimArray(j)
+
+    sparse_array[0, 0] = 123
+    assert len(sparse_array._sparse_array) == 2
+    assert sparse_array[0, 0] == 123
+    assert sparse_array/0 == MutableSparseNDimArray([[S.ComplexInfinity, S.NaN], [S.NaN, S.ComplexInfinity]], (2, 2))
+
+    # when element in sparse array become zero it will disappear from
+    # dictionary
+    sparse_array[0, 0] = 0
+    assert len(sparse_array._sparse_array) == 1
+    sparse_array[1, 1] = 0
+    assert len(sparse_array._sparse_array) == 0
+    assert sparse_array[0, 0] == 0
+
+    # test for large scale sparse array
+    # equality test
+    a = MutableSparseNDimArray.zeros(100000, 200000)
+    b = MutableSparseNDimArray.zeros(100000, 200000)
+    assert a == b
+    a[1, 1] = 1
+    b[1, 1] = 2
+    assert a != b
+
+    # __mul__ and __rmul__
+    assert a * 3 == MutableSparseNDimArray({200001: 3}, (100000, 200000))
+    assert 3 * a == MutableSparseNDimArray({200001: 3}, (100000, 200000))
+    assert a * 0 == MutableSparseNDimArray({}, (100000, 200000))
+    assert 0 * a == MutableSparseNDimArray({}, (100000, 200000))
+
+    # __truediv__
+    assert a/3 == MutableSparseNDimArray({200001: Rational(1, 3)}, (100000, 200000))
+
+    # __neg__
+    assert -a == MutableSparseNDimArray({200001: -1}, (100000, 200000))
+
+
+def test_calculation():
+
+    a = MutableDenseNDimArray([1]*9, (3, 3))
+    b = MutableDenseNDimArray([9]*9, (3, 3))
+
+    c = a + b
+    for i in c:
+        assert i == MutableDenseNDimArray([10, 10, 10])
+
+    assert c == MutableDenseNDimArray([10]*9, (3, 3))
+    assert c == MutableSparseNDimArray([10]*9, (3, 3))
+
+    c = b - a
+    for i in c:
+        assert i == MutableSparseNDimArray([8, 8, 8])
+
+    assert c == MutableDenseNDimArray([8]*9, (3, 3))
+    assert c == MutableSparseNDimArray([8]*9, (3, 3))
+
+
+def test_ndim_array_converting():
+    dense_array = MutableDenseNDimArray([1, 2, 3, 4], (2, 2))
+    alist = dense_array.tolist()
+
+    assert alist == [[1, 2], [3, 4]]
+
+    matrix = dense_array.tomatrix()
+    assert (isinstance(matrix, Matrix))
+
+    for i in range(len(dense_array)):
+        assert dense_array[dense_array._get_tuple_index(i)] == matrix[i]
+    assert matrix.shape == dense_array.shape
+
+    assert MutableDenseNDimArray(matrix) == dense_array
+    assert MutableDenseNDimArray(matrix.as_immutable()) == dense_array
+    assert MutableDenseNDimArray(matrix.as_mutable()) == dense_array
+
+    sparse_array = MutableSparseNDimArray([1, 2, 3, 4], (2, 2))
+    alist = sparse_array.tolist()
+
+    assert alist == [[1, 2], [3, 4]]
+
+    matrix = sparse_array.tomatrix()
+    assert(isinstance(matrix, SparseMatrix))
+
+    for i in range(len(sparse_array)):
+        assert sparse_array[sparse_array._get_tuple_index(i)] == matrix[i]
+    assert matrix.shape == sparse_array.shape
+
+    assert MutableSparseNDimArray(matrix) == sparse_array
+    assert MutableSparseNDimArray(matrix.as_immutable()) == sparse_array
+    assert MutableSparseNDimArray(matrix.as_mutable()) == sparse_array
+
+
+def test_converting_functions():
+    arr_list = [1, 2, 3, 4]
+    arr_matrix = Matrix(((1, 2), (3, 4)))
+
+    # list
+    arr_ndim_array = MutableDenseNDimArray(arr_list, (2, 2))
+    assert (isinstance(arr_ndim_array, MutableDenseNDimArray))
+    assert arr_matrix.tolist() == arr_ndim_array.tolist()
+
+    # Matrix
+    arr_ndim_array = MutableDenseNDimArray(arr_matrix)
+    assert (isinstance(arr_ndim_array, MutableDenseNDimArray))
+    assert arr_matrix.tolist() == arr_ndim_array.tolist()
+    assert arr_matrix.shape == arr_ndim_array.shape
+
+
+def test_equality():
+    first_list = [1, 2, 3, 4]
+    second_list = [1, 2, 3, 4]
+    third_list = [4, 3, 2, 1]
+    assert first_list == second_list
+    assert first_list != third_list
+
+    first_ndim_array = MutableDenseNDimArray(first_list, (2, 2))
+    second_ndim_array = MutableDenseNDimArray(second_list, (2, 2))
+    third_ndim_array = MutableDenseNDimArray(third_list, (2, 2))
+    fourth_ndim_array = MutableDenseNDimArray(first_list, (2, 2))
+
+    assert first_ndim_array == second_ndim_array
+    second_ndim_array[0, 0] = 0
+    assert first_ndim_array != second_ndim_array
+    assert first_ndim_array != third_ndim_array
+    assert first_ndim_array == fourth_ndim_array
+
+
+def test_arithmetic():
+    a = MutableDenseNDimArray([3 for i in range(9)], (3, 3))
+    b = MutableDenseNDimArray([7 for i in range(9)], (3, 3))
+
+    c1 = a + b
+    c2 = b + a
+    assert c1 == c2
+
+    d1 = a - b
+    d2 = b - a
+    assert d1 == d2 * (-1)
+
+    e1 = a * 5
+    e2 = 5 * a
+    e3 = copy(a)
+    e3 *= 5
+    assert e1 == e2 == e3
+
+    f1 = a / 5
+    f2 = copy(a)
+    f2 /= 5
+    assert f1 == f2
+    assert f1[0, 0] == f1[0, 1] == f1[0, 2] == f1[1, 0] == f1[1, 1] == \
+    f1[1, 2] == f1[2, 0] == f1[2, 1] == f1[2, 2] == Rational(3, 5)
+
+    assert type(a) == type(b) == type(c1) == type(c2) == type(d1) == type(d2) \
+        == type(e1) == type(e2) == type(e3) == type(f1)
+
+    z0 = -a
+    assert z0 == MutableDenseNDimArray([-3 for i in range(9)], (3, 3))
+
+
+def test_higher_dimenions():
+    m3 = MutableDenseNDimArray(range(10, 34), (2, 3, 4))
+
+    assert m3.tolist() == [[[10, 11, 12, 13],
+            [14, 15, 16, 17],
+            [18, 19, 20, 21]],
+
+           [[22, 23, 24, 25],
+            [26, 27, 28, 29],
+            [30, 31, 32, 33]]]
+
+    assert m3._get_tuple_index(0) == (0, 0, 0)
+    assert m3._get_tuple_index(1) == (0, 0, 1)
+    assert m3._get_tuple_index(4) == (0, 1, 0)
+    assert m3._get_tuple_index(12) == (1, 0, 0)
+
+    assert str(m3) == '[[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]]'
+
+    m3_rebuilt = MutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]])
+    assert m3 == m3_rebuilt
+
+    m3_other = MutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]], (2, 3, 4))
+
+    assert m3 == m3_other
+
+
+def test_slices():
+    md = MutableDenseNDimArray(range(10, 34), (2, 3, 4))
+
+    assert md[:] == MutableDenseNDimArray(range(10, 34), (2, 3, 4))
+    assert md[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]])
+    assert md[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]])
+    assert md[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]])
+    assert md[:, :, :] == md
+
+    sd = MutableSparseNDimArray(range(10, 34), (2, 3, 4))
+    assert sd == MutableSparseNDimArray(md)
+
+    assert sd[:] == MutableSparseNDimArray(range(10, 34), (2, 3, 4))
+    assert sd[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]])
+    assert sd[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]])
+    assert sd[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]])
+    assert sd[:, :, :] == sd
+
+
+def test_slices_assign():
+    a = MutableDenseNDimArray(range(12), shape=(4, 3))
+    b = MutableSparseNDimArray(range(12), shape=(4, 3))
+
+    for i in [a, b]:
+        assert i.tolist() == [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
+        i[0, :] = [2, 2, 2]
+        assert i.tolist() == [[2, 2, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
+        i[0, 1:] = [8, 8]
+        assert i.tolist() == [[2, 8, 8], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
+        i[1:3, 1] = [20, 44]
+        assert i.tolist() == [[2, 8, 8], [3, 20, 5], [6, 44, 8], [9, 10, 11]]
+
+
+def test_diff():
+    from sympy.abc import x, y, z
+    md = MutableDenseNDimArray([[x, y], [x*z, x*y*z]])
+    assert md.diff(x) == MutableDenseNDimArray([[1, 0], [z, y*z]])
+    assert diff(md, x) == MutableDenseNDimArray([[1, 0], [z, y*z]])
+
+    sd = MutableSparseNDimArray(md)
+    assert sd == MutableSparseNDimArray([x, y, x*z, x*y*z], (2, 2))
+    assert sd.diff(x) == MutableSparseNDimArray([[1, 0], [z, y*z]])
+    assert diff(sd, x) == MutableSparseNDimArray([[1, 0], [z, y*z]])
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_ndim_array.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_ndim_array.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ff9b032631c01272c00478e4cdf0dcbc6997990
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_ndim_array.py
@@ -0,0 +1,73 @@
+from sympy.testing.pytest import raises
+from sympy.functions.elementary.trigonometric import sin, cos
+from sympy.matrices.dense import Matrix
+from sympy.simplify import simplify
+from sympy.tensor.array import Array
+from sympy.tensor.array.dense_ndim_array import (
+    ImmutableDenseNDimArray, MutableDenseNDimArray)
+from sympy.tensor.array.sparse_ndim_array import (
+    ImmutableSparseNDimArray, MutableSparseNDimArray)
+
+from sympy.abc import x, y
+
+mutable_array_types = [
+    MutableDenseNDimArray,
+    MutableSparseNDimArray
+]
+
+array_types = [
+    ImmutableDenseNDimArray,
+    ImmutableSparseNDimArray,
+    MutableDenseNDimArray,
+    MutableSparseNDimArray
+]
+
+
+def test_array_negative_indices():
+    for ArrayType in array_types:
+        test_array = ArrayType([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
+        assert test_array[:, -1] == Array([5, 10])
+        assert test_array[:, -2] == Array([4, 9])
+        assert test_array[:, -3] == Array([3, 8])
+        assert test_array[:, -4] == Array([2, 7])
+        assert test_array[:, -5] == Array([1, 6])
+        assert test_array[:, 0] == Array([1, 6])
+        assert test_array[:, 1] == Array([2, 7])
+        assert test_array[:, 2] == Array([3, 8])
+        assert test_array[:, 3] == Array([4, 9])
+        assert test_array[:, 4] == Array([5, 10])
+
+        raises(ValueError, lambda: test_array[:, -6])
+        raises(ValueError, lambda: test_array[-3, :])
+
+        assert test_array[-1, -1] == 10
+
+
+def test_issue_18361():
+    A = Array([sin(2 * x) - 2 * sin(x) * cos(x)])
+    B = Array([sin(x)**2 + cos(x)**2, 0])
+    C = Array([(x + x**2)/(x*sin(y)**2 + x*cos(y)**2), 2*sin(x)*cos(x)])
+    assert simplify(A) == Array([0])
+    assert simplify(B) == Array([1, 0])
+    assert simplify(C) == Array([x + 1, sin(2*x)])
+
+
+def test_issue_20222():
+    A = Array([[1, 2], [3, 4]])
+    B = Matrix([[1,2],[3,4]])
+    raises(TypeError, lambda: A - B)
+
+
+def test_issue_17851():
+    for array_type in array_types:
+        A = array_type([])
+        assert isinstance(A, array_type)
+        assert A.shape == (0,)
+        assert list(A) == []
+
+
+def test_issue_and_18715():
+    for array_type in mutable_array_types:
+        A = array_type([0, 1, 2])
+        A[0] += 5
+        assert A[0] == 5
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_ndim_array_conversions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_ndim_array_conversions.py
new file mode 100644
index 0000000000000000000000000000000000000000..f43260ccc636ac461ba0c06dbfcf3fe3a8d5338d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/array/tests/test_ndim_array_conversions.py
@@ -0,0 +1,22 @@
+from sympy.tensor.array import (ImmutableDenseNDimArray,
+        ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray)
+from sympy.abc import x, y, z
+
+
+def test_NDim_array_conv():
+    MD = MutableDenseNDimArray([x, y, z])
+    MS = MutableSparseNDimArray([x, y, z])
+    ID = ImmutableDenseNDimArray([x, y, z])
+    IS = ImmutableSparseNDimArray([x, y, z])
+
+    assert MD.as_immutable() == ID
+    assert MD.as_mutable() == MD
+
+    assert MS.as_immutable() == IS
+    assert MS.as_mutable() == MS
+
+    assert ID.as_immutable() == ID
+    assert ID.as_mutable() == MD
+
+    assert IS.as_immutable() == IS
+    assert IS.as_mutable() == MS
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/functions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..f14599d69152db1713f21c9dd785683901c5eeb9
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/functions.py
@@ -0,0 +1,154 @@
+from collections.abc import Iterable
+from functools import singledispatch
+
+from sympy.core.expr import Expr
+from sympy.core.mul import Mul
+from sympy.core.singleton import S
+from sympy.core.sympify import sympify
+from sympy.core.parameters import global_parameters
+
+
+class TensorProduct(Expr):
+    """
+    Generic class for tensor products.
+    """
+    is_number = False
+
+    def __new__(cls, *args, **kwargs):
+        from sympy.tensor.array import NDimArray, tensorproduct, Array
+        from sympy.matrices.expressions.matexpr import MatrixExpr
+        from sympy.matrices.matrixbase import MatrixBase
+        from sympy.strategies import flatten
+
+        args = [sympify(arg) for arg in args]
+        evaluate = kwargs.get("evaluate", global_parameters.evaluate)
+
+        if not evaluate:
+            obj = Expr.__new__(cls, *args)
+            return obj
+
+        arrays = []
+        other = []
+        scalar = S.One
+        for arg in args:
+            if isinstance(arg, (Iterable, MatrixBase, NDimArray)):
+                arrays.append(Array(arg))
+            elif isinstance(arg, (MatrixExpr,)):
+                other.append(arg)
+            else:
+                scalar *= arg
+
+        coeff = scalar*tensorproduct(*arrays)
+        if len(other) == 0:
+            return coeff
+        if coeff != 1:
+            newargs = [coeff] + other
+        else:
+            newargs = other
+        obj = Expr.__new__(cls, *newargs, **kwargs)
+        return flatten(obj)
+
+    def rank(self):
+        return len(self.shape)
+
+    def _get_args_shapes(self):
+        from sympy.tensor.array import Array
+        return [i.shape if hasattr(i, "shape") else Array(i).shape for i in self.args]
+
+    @property
+    def shape(self):
+        shape_list = self._get_args_shapes()
+        return sum(shape_list, ())
+
+    def __getitem__(self, index):
+        index = iter(index)
+        return Mul.fromiter(
+            arg.__getitem__(tuple(next(index) for i in shp))
+            for arg, shp in zip(self.args, self._get_args_shapes())
+        )
+
+
+@singledispatch
+def shape(expr):
+    """
+    Return the shape of the *expr* as a tuple. *expr* should represent
+    suitable object such as matrix or array.
+
+    Parameters
+    ==========
+
+    expr : SymPy object having ``MatrixKind`` or ``ArrayKind``.
+
+    Raises
+    ======
+
+    NoShapeError : Raised when object with wrong kind is passed.
+
+    Examples
+    ========
+
+    This function returns the shape of any object representing matrix or array.
+
+    >>> from sympy import shape, Array, ImmutableDenseMatrix, Integral
+    >>> from sympy.abc import x
+    >>> A = Array([1, 2])
+    >>> shape(A)
+    (2,)
+    >>> shape(Integral(A, x))
+    (2,)
+    >>> M = ImmutableDenseMatrix([1, 2])
+    >>> shape(M)
+    (2, 1)
+    >>> shape(Integral(M, x))
+    (2, 1)
+
+    You can support new type by dispatching.
+
+    >>> from sympy import Expr
+    >>> class NewExpr(Expr):
+    ...     pass
+    >>> @shape.register(NewExpr)
+    ... def _(expr):
+    ...     return shape(expr.args[0])
+    >>> shape(NewExpr(M))
+    (2, 1)
+
+    If unsuitable expression is passed, ``NoShapeError()`` will be raised.
+
+    >>> shape(Integral(x, x))
+    Traceback (most recent call last):
+      ...
+    sympy.tensor.functions.NoShapeError: shape() called on non-array object: Integral(x, x)
+
+    Notes
+    =====
+
+    Array-like classes (such as ``Matrix`` or ``NDimArray``) has ``shape``
+    property which returns its shape, but it cannot be used for non-array
+    classes containing array. This function returns the shape of any
+    registered object representing array.
+
+    """
+    if hasattr(expr, "shape"):
+        return expr.shape
+    raise NoShapeError(
+        "%s does not have shape, or its type is not registered to shape()." % expr)
+
+
+class NoShapeError(Exception):
+    """
+    Raised when ``shape()`` is called on non-array object.
+
+    This error can be imported from ``sympy.tensor.functions``.
+
+    Examples
+    ========
+
+    >>> from sympy import shape
+    >>> from sympy.abc import x
+    >>> shape(x)
+    Traceback (most recent call last):
+      ...
+    sympy.tensor.functions.NoShapeError: shape() called on non-array object: x
+    """
+    pass
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/index_methods.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/index_methods.py
new file mode 100644
index 0000000000000000000000000000000000000000..12f707b60b4ad0bcadc35a222d9abe0cc5e033fc
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/index_methods.py
@@ -0,0 +1,469 @@
+"""Module with functions operating on IndexedBase, Indexed and Idx objects
+
+    - Check shape conformance
+    - Determine indices in resulting expression
+
+    etc.
+
+    Methods in this module could be implemented by calling methods on Expr
+    objects instead.  When things stabilize this could be a useful
+    refactoring.
+"""
+
+from functools import reduce
+
+from sympy.core.function import Function
+from sympy.functions import exp, Piecewise
+from sympy.tensor.indexed import Idx, Indexed
+from sympy.utilities import sift
+
+from collections import OrderedDict
+
+class IndexConformanceException(Exception):
+    pass
+
+def _unique_and_repeated(inds):
+    """
+    Returns the unique and repeated indices. Also note, from the examples given below
+    that the order of indices is maintained as given in the input.
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.index_methods import _unique_and_repeated
+    >>> _unique_and_repeated([2, 3, 1, 3, 0, 4, 0])
+    ([2, 1, 4], [3, 0])
+    """
+    uniq = OrderedDict()
+    for i in inds:
+        if i in uniq:
+            uniq[i] = 0
+        else:
+            uniq[i] = 1
+    return sift(uniq, lambda x: uniq[x], binary=True)
+
+def _remove_repeated(inds):
+    """
+    Removes repeated objects from sequences
+
+    Returns a set of the unique objects and a tuple of all that have been
+    removed.
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.index_methods import _remove_repeated
+    >>> l1 = [1, 2, 3, 2]
+    >>> _remove_repeated(l1)
+    ({1, 3}, (2,))
+
+    """
+    u, r = _unique_and_repeated(inds)
+    return set(u), tuple(r)
+
+
+def _get_indices_Mul(expr, return_dummies=False):
+    """Determine the outer indices of a Mul object.
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.index_methods import _get_indices_Mul
+    >>> from sympy.tensor.indexed import IndexedBase, Idx
+    >>> i, j, k = map(Idx, ['i', 'j', 'k'])
+    >>> x = IndexedBase('x')
+    >>> y = IndexedBase('y')
+    >>> _get_indices_Mul(x[i, k]*y[j, k])
+    ({i, j}, {})
+    >>> _get_indices_Mul(x[i, k]*y[j, k], return_dummies=True)
+    ({i, j}, {}, (k,))
+
+    """
+
+    inds = list(map(get_indices, expr.args))
+    inds, syms = list(zip(*inds))
+
+    inds = list(map(list, inds))
+    inds = list(reduce(lambda x, y: x + y, inds))
+    inds, dummies = _remove_repeated(inds)
+
+    symmetry = {}
+    for s in syms:
+        for pair in s:
+            if pair in symmetry:
+                symmetry[pair] *= s[pair]
+            else:
+                symmetry[pair] = s[pair]
+
+    if return_dummies:
+        return inds, symmetry, dummies
+    else:
+        return inds, symmetry
+
+
+def _get_indices_Pow(expr):
+    """Determine outer indices of a power or an exponential.
+
+    A power is considered a universal function, so that the indices of a Pow is
+    just the collection of indices present in the expression.  This may be
+    viewed as a bit inconsistent in the special case:
+
+        x[i]**2 = x[i]*x[i]                                                      (1)
+
+    The above expression could have been interpreted as the contraction of x[i]
+    with itself, but we choose instead to interpret it as a function
+
+        lambda y: y**2
+
+    applied to each element of x (a universal function in numpy terms).  In
+    order to allow an interpretation of (1) as a contraction, we need
+    contravariant and covariant Idx subclasses.  (FIXME: this is not yet
+    implemented)
+
+    Expressions in the base or exponent are subject to contraction as usual,
+    but an index that is present in the exponent, will not be considered
+    contractable with its own base.  Note however, that indices in the same
+    exponent can be contracted with each other.
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.index_methods import _get_indices_Pow
+    >>> from sympy import Pow, exp, IndexedBase, Idx
+    >>> A = IndexedBase('A')
+    >>> x = IndexedBase('x')
+    >>> i, j, k = map(Idx, ['i', 'j', 'k'])
+    >>> _get_indices_Pow(exp(A[i, j]*x[j]))
+    ({i}, {})
+    >>> _get_indices_Pow(Pow(x[i], x[i]))
+    ({i}, {})
+    >>> _get_indices_Pow(Pow(A[i, j]*x[j], x[i]))
+    ({i}, {})
+
+    """
+    base, exp = expr.as_base_exp()
+    binds, bsyms = get_indices(base)
+    einds, esyms = get_indices(exp)
+
+    inds = binds | einds
+
+    # FIXME: symmetries from power needs to check special cases, else nothing
+    symmetries = {}
+
+    return inds, symmetries
+
+
+def _get_indices_Add(expr):
+    """Determine outer indices of an Add object.
+
+    In a sum, each term must have the same set of outer indices.  A valid
+    expression could be
+
+        x(i)*y(j) - x(j)*y(i)
+
+    But we do not allow expressions like:
+
+        x(i)*y(j) - z(j)*z(j)
+
+    FIXME: Add support for Numpy broadcasting
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.index_methods import _get_indices_Add
+    >>> from sympy.tensor.indexed import IndexedBase, Idx
+    >>> i, j, k = map(Idx, ['i', 'j', 'k'])
+    >>> x = IndexedBase('x')
+    >>> y = IndexedBase('y')
+    >>> _get_indices_Add(x[i] + x[k]*y[i, k])
+    ({i}, {})
+
+    """
+
+    inds = list(map(get_indices, expr.args))
+    inds, syms = list(zip(*inds))
+
+    # allow broadcast of scalars
+    non_scalars = [x for x in inds if x != set()]
+    if not non_scalars:
+        return set(), {}
+
+    if not all(x == non_scalars[0] for x in non_scalars[1:]):
+        raise IndexConformanceException("Indices are not consistent: %s" % expr)
+    if not reduce(lambda x, y: x != y or y, syms):
+        symmetries = syms[0]
+    else:
+        # FIXME: search for symmetries
+        symmetries = {}
+
+    return non_scalars[0], symmetries
+
+
+def get_indices(expr):
+    """Determine the outer indices of expression ``expr``
+
+    By *outer* we mean indices that are not summation indices.  Returns a set
+    and a dict.  The set contains outer indices and the dict contains
+    information about index symmetries.
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.index_methods import get_indices
+    >>> from sympy import symbols
+    >>> from sympy.tensor import IndexedBase
+    >>> x, y, A = map(IndexedBase, ['x', 'y', 'A'])
+    >>> i, j, a, z = symbols('i j a z', integer=True)
+
+    The indices of the total expression is determined, Repeated indices imply a
+    summation, for instance the trace of a matrix A:
+
+    >>> get_indices(A[i, i])
+    (set(), {})
+
+    In the case of many terms, the terms are required to have identical
+    outer indices.  Else an IndexConformanceException is raised.
+
+    >>> get_indices(x[i] + A[i, j]*y[j])
+    ({i}, {})
+
+    :Exceptions:
+
+    An IndexConformanceException means that the terms ar not compatible, e.g.
+
+    >>> get_indices(x[i] + y[j])                #doctest: +SKIP
+            (...)
+    IndexConformanceException: Indices are not consistent: x(i) + y(j)
+
+    .. warning::
+       The concept of *outer* indices applies recursively, starting on the deepest
+       level.  This implies that dummies inside parenthesis are assumed to be
+       summed first, so that the following expression is handled gracefully:
+
+       >>> get_indices((x[i] + A[i, j]*y[j])*x[j])
+       ({i, j}, {})
+
+       This is correct and may appear convenient, but you need to be careful
+       with this as SymPy will happily .expand() the product, if requested.  The
+       resulting expression would mix the outer ``j`` with the dummies inside
+       the parenthesis, which makes it a different expression.  To be on the
+       safe side, it is best to avoid such ambiguities by using unique indices
+       for all contractions that should be held separate.
+
+    """
+    # We call ourself recursively to determine indices of sub expressions.
+
+    # break recursion
+    if isinstance(expr, Indexed):
+        c = expr.indices
+        inds, dummies = _remove_repeated(c)
+        return inds, {}
+    elif expr is None:
+        return set(), {}
+    elif isinstance(expr, Idx):
+        return {expr}, {}
+    elif expr.is_Atom:
+        return set(), {}
+
+
+    # recurse via specialized functions
+    else:
+        if expr.is_Mul:
+            return _get_indices_Mul(expr)
+        elif expr.is_Add:
+            return _get_indices_Add(expr)
+        elif expr.is_Pow or isinstance(expr, exp):
+            return _get_indices_Pow(expr)
+
+        elif isinstance(expr, Piecewise):
+            # FIXME:  No support for Piecewise yet
+            return set(), {}
+        elif isinstance(expr, Function):
+            # Support ufunc like behaviour by returning indices from arguments.
+            # Functions do not interpret repeated indices across arguments
+            # as summation
+            ind0 = set()
+            for arg in expr.args:
+                ind, sym = get_indices(arg)
+                ind0 |= ind
+            return ind0, sym
+
+        # this test is expensive, so it should be at the end
+        elif not expr.has(Indexed):
+            return set(), {}
+        raise NotImplementedError(
+            "FIXME: No specialized handling of type %s" % type(expr))
+
+
+def get_contraction_structure(expr):
+    """Determine dummy indices of ``expr`` and describe its structure
+
+    By *dummy* we mean indices that are summation indices.
+
+    The structure of the expression is determined and described as follows:
+
+    1) A conforming summation of Indexed objects is described with a dict where
+       the keys are summation indices and the corresponding values are sets
+       containing all terms for which the summation applies.  All Add objects
+       in the SymPy expression tree are described like this.
+
+    2) For all nodes in the SymPy expression tree that are *not* of type Add, the
+       following applies:
+
+       If a node discovers contractions in one of its arguments, the node
+       itself will be stored as a key in the dict.  For that key, the
+       corresponding value is a list of dicts, each of which is the result of a
+       recursive call to get_contraction_structure().  The list contains only
+       dicts for the non-trivial deeper contractions, omitting dicts with None
+       as the one and only key.
+
+    .. Note:: The presence of expressions among the dictionary keys indicates
+       multiple levels of index contractions.  A nested dict displays nested
+       contractions and may itself contain dicts from a deeper level.  In
+       practical calculations the summation in the deepest nested level must be
+       calculated first so that the outer expression can access the resulting
+       indexed object.
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.index_methods import get_contraction_structure
+    >>> from sympy import default_sort_key
+    >>> from sympy.tensor import IndexedBase, Idx
+    >>> x, y, A = map(IndexedBase, ['x', 'y', 'A'])
+    >>> i, j, k, l = map(Idx, ['i', 'j', 'k', 'l'])
+    >>> get_contraction_structure(x[i]*y[i] + A[j, j])
+    {(i,): {x[i]*y[i]}, (j,): {A[j, j]}}
+    >>> get_contraction_structure(x[i]*y[j])
+    {None: {x[i]*y[j]}}
+
+    A multiplication of contracted factors results in nested dicts representing
+    the internal contractions.
+
+    >>> d = get_contraction_structure(x[i, i]*y[j, j])
+    >>> sorted(d.keys(), key=default_sort_key)
+    [None, x[i, i]*y[j, j]]
+
+    In this case, the product has no contractions:
+
+    >>> d[None]
+    {x[i, i]*y[j, j]}
+
+    Factors are contracted "first":
+
+    >>> sorted(d[x[i, i]*y[j, j]], key=default_sort_key)
+    [{(i,): {x[i, i]}}, {(j,): {y[j, j]}}]
+
+    A parenthesized Add object is also returned as a nested dictionary.  The
+    term containing the parenthesis is a Mul with a contraction among the
+    arguments, so it will be found as a key in the result.  It stores the
+    dictionary resulting from a recursive call on the Add expression.
+
+    >>> d = get_contraction_structure(x[i]*(y[i] + A[i, j]*x[j]))
+    >>> sorted(d.keys(), key=default_sort_key)
+    [(A[i, j]*x[j] + y[i])*x[i], (i,)]
+    >>> d[(i,)]
+    {(A[i, j]*x[j] + y[i])*x[i]}
+    >>> d[x[i]*(A[i, j]*x[j] + y[i])]
+    [{None: {y[i]}, (j,): {A[i, j]*x[j]}}]
+
+    Powers with contractions in either base or exponent will also be found as
+    keys in the dictionary, mapping to a list of results from recursive calls:
+
+    >>> d = get_contraction_structure(A[j, j]**A[i, i])
+    >>> d[None]
+    {A[j, j]**A[i, i]}
+    >>> nested_contractions = d[A[j, j]**A[i, i]]
+    >>> nested_contractions[0]
+    {(j,): {A[j, j]}}
+    >>> nested_contractions[1]
+    {(i,): {A[i, i]}}
+
+    The description of the contraction structure may appear complicated when
+    represented with a string in the above examples, but it is easy to iterate
+    over:
+
+    >>> from sympy import Expr
+    >>> for key in d:
+    ...     if isinstance(key, Expr):
+    ...         continue
+    ...     for term in d[key]:
+    ...         if term in d:
+    ...             # treat deepest contraction first
+    ...             pass
+    ...     # treat outermost contactions here
+
+    """
+
+    # We call ourself recursively to inspect sub expressions.
+
+    if isinstance(expr, Indexed):
+        junk, key = _remove_repeated(expr.indices)
+        return {key or None: {expr}}
+    elif expr.is_Atom:
+        return {None: {expr}}
+    elif expr.is_Mul:
+        junk, junk, key = _get_indices_Mul(expr, return_dummies=True)
+        result = {key or None: {expr}}
+        # recurse on every factor
+        nested = []
+        for fac in expr.args:
+            facd = get_contraction_structure(fac)
+            if not (None in facd and len(facd) == 1):
+                nested.append(facd)
+        if nested:
+            result[expr] = nested
+        return result
+    elif expr.is_Pow or isinstance(expr, exp):
+        # recurse in base and exp separately.  If either has internal
+        # contractions we must include ourselves as a key in the returned dict
+        b, e = expr.as_base_exp()
+        dbase = get_contraction_structure(b)
+        dexp = get_contraction_structure(e)
+
+        dicts = []
+        for d in dbase, dexp:
+            if not (None in d and len(d) == 1):
+                dicts.append(d)
+        result = {None: {expr}}
+        if dicts:
+            result[expr] = dicts
+        return result
+    elif expr.is_Add:
+        # Note: we just collect all terms with identical summation indices, We
+        # do nothing to identify equivalent terms here, as this would require
+        # substitutions or pattern matching in expressions of unknown
+        # complexity.
+        result = {}
+        for term in expr.args:
+            # recurse on every term
+            d = get_contraction_structure(term)
+            for key in d:
+                if key in result:
+                    result[key] |= d[key]
+                else:
+                    result[key] = d[key]
+        return result
+
+    elif isinstance(expr, Piecewise):
+        # FIXME:  No support for Piecewise yet
+        return {None: expr}
+    elif isinstance(expr, Function):
+        # Collect non-trivial contraction structures in each argument
+        # We do not report repeated indices in separate arguments as a
+        # contraction
+        deeplist = []
+        for arg in expr.args:
+            deep = get_contraction_structure(arg)
+            if not (None in deep and len(deep) == 1):
+                deeplist.append(deep)
+        d = {None: {expr}}
+        if deeplist:
+            d[expr] = deeplist
+        return d
+
+    # this test is expensive, so it should be at the end
+    elif not expr.has(Indexed):
+        return {None: {expr}}
+    raise NotImplementedError(
+        "FIXME: No specialized handling of type %s" % type(expr))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/indexed.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/indexed.py
new file mode 100644
index 0000000000000000000000000000000000000000..feddad21e52bbab2e1243beafdb11f30b2eded4d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/indexed.py
@@ -0,0 +1,793 @@
+r"""Module that defines indexed objects.
+
+The classes ``IndexedBase``, ``Indexed``, and ``Idx`` represent a
+matrix element ``M[i, j]`` as in the following diagram::
+
+       1) The Indexed class represents the entire indexed object.
+                  |
+               ___|___
+              '       '
+               M[i, j]
+              /   \__\______
+              |             |
+              |             |
+              |     2) The Idx class represents indices; each Idx can
+              |        optionally contain information about its range.
+              |
+        3) IndexedBase represents the 'stem' of an indexed object, here `M`.
+           The stem used by itself is usually taken to represent the entire
+           array.
+
+There can be any number of indices on an Indexed object.  No
+transformation properties are implemented in these Base objects, but
+implicit contraction of repeated indices is supported.
+
+Note that the support for complicated (i.e. non-atomic) integer
+expressions as indices is limited.  (This should be improved in
+future releases.)
+
+Examples
+========
+
+To express the above matrix element example you would write:
+
+>>> from sympy import symbols, IndexedBase, Idx
+>>> M = IndexedBase('M')
+>>> i, j = symbols('i j', cls=Idx)
+>>> M[i, j]
+M[i, j]
+
+Repeated indices in a product implies a summation, so to express a
+matrix-vector product in terms of Indexed objects:
+
+>>> x = IndexedBase('x')
+>>> M[i, j]*x[j]
+M[i, j]*x[j]
+
+If the indexed objects will be converted to component based arrays, e.g.
+with the code printers or the autowrap framework, you also need to provide
+(symbolic or numerical) dimensions.  This can be done by passing an
+optional shape parameter to IndexedBase upon construction:
+
+>>> dim1, dim2 = symbols('dim1 dim2', integer=True)
+>>> A = IndexedBase('A', shape=(dim1, 2*dim1, dim2))
+>>> A.shape
+(dim1, 2*dim1, dim2)
+>>> A[i, j, 3].shape
+(dim1, 2*dim1, dim2)
+
+If an IndexedBase object has no shape information, it is assumed that the
+array is as large as the ranges of its indices:
+
+>>> n, m = symbols('n m', integer=True)
+>>> i = Idx('i', m)
+>>> j = Idx('j', n)
+>>> M[i, j].shape
+(m, n)
+>>> M[i, j].ranges
+[(0, m - 1), (0, n - 1)]
+
+The above can be compared with the following:
+
+>>> A[i, 2, j].shape
+(dim1, 2*dim1, dim2)
+>>> A[i, 2, j].ranges
+[(0, m - 1), None, (0, n - 1)]
+
+To analyze the structure of indexed expressions, you can use the methods
+get_indices() and get_contraction_structure():
+
+>>> from sympy.tensor import get_indices, get_contraction_structure
+>>> get_indices(A[i, j, j])
+({i}, {})
+>>> get_contraction_structure(A[i, j, j])
+{(j,): {A[i, j, j]}}
+
+See the appropriate docstrings for a detailed explanation of the output.
+"""
+
+#   TODO:  (some ideas for improvement)
+#
+#   o test and guarantee numpy compatibility
+#      - implement full support for broadcasting
+#      - strided arrays
+#
+#   o more functions to analyze indexed expressions
+#      - identify standard constructs, e.g matrix-vector product in a subexpression
+#
+#   o functions to generate component based arrays (numpy and sympy.Matrix)
+#      - generate a single array directly from Indexed
+#      - convert simple sub-expressions
+#
+#   o sophisticated indexing (possibly in subclasses to preserve simplicity)
+#      - Idx with range smaller than dimension of Indexed
+#      - Idx with stepsize != 1
+#      - Idx with step determined by function call
+from collections.abc import Iterable
+
+from sympy.core.numbers import Number
+from sympy.core.assumptions import StdFactKB
+from sympy.core import Expr, Tuple, sympify, S
+from sympy.core.symbol import _filter_assumptions, Symbol
+from sympy.core.logic import fuzzy_bool, fuzzy_not
+from sympy.core.sympify import _sympify
+from sympy.functions.special.tensor_functions import KroneckerDelta
+from sympy.multipledispatch import dispatch
+from sympy.utilities.iterables import is_sequence, NotIterable
+from sympy.utilities.misc import filldedent
+
+
+class IndexException(Exception):
+    pass
+
+
+class Indexed(Expr):
+    """Represents a mathematical object with indices.
+
+    >>> from sympy import Indexed, IndexedBase, Idx, symbols
+    >>> i, j = symbols('i j', cls=Idx)
+    >>> Indexed('A', i, j)
+    A[i, j]
+
+    It is recommended that ``Indexed`` objects be created by indexing ``IndexedBase``:
+    ``IndexedBase('A')[i, j]`` instead of ``Indexed(IndexedBase('A'), i, j)``.
+
+    >>> A = IndexedBase('A')
+    >>> a_ij = A[i, j]           # Prefer this,
+    >>> b_ij = Indexed(A, i, j)  # over this.
+    >>> a_ij == b_ij
+    True
+
+    """
+    is_Indexed = True
+    is_symbol = True
+    is_Atom = True
+
+    def __new__(cls, base, *args, **kw_args):
+        from sympy.tensor.array.ndim_array import NDimArray
+        from sympy.matrices.matrixbase import MatrixBase
+
+        if not args:
+            raise IndexException("Indexed needs at least one index.")
+        if isinstance(base, (str, Symbol)):
+            base = IndexedBase(base)
+        elif not hasattr(base, '__getitem__') and not isinstance(base, IndexedBase):
+            raise TypeError(filldedent("""
+                The base can only be replaced with a string, Symbol,
+                IndexedBase or an object with a method for getting
+                items (i.e. an object with a `__getitem__` method).
+                """))
+        args = list(map(sympify, args))
+        if isinstance(base, (NDimArray, Iterable, Tuple, MatrixBase)) and all(i.is_number for i in args):
+            if len(args) == 1:
+                return base[args[0]]
+            else:
+                return base[args]
+
+        base = _sympify(base)
+
+        obj = Expr.__new__(cls, base, *args, **kw_args)
+
+        IndexedBase._set_assumptions(obj, base.assumptions0)
+
+        return obj
+
+    def _hashable_content(self):
+        return super()._hashable_content() + tuple(sorted(self.assumptions0.items()))
+
+    @property
+    def name(self):
+        return str(self)
+
+    @property
+    def _diff_wrt(self):
+        """Allow derivatives with respect to an ``Indexed`` object."""
+        return True
+
+    def _eval_derivative(self, wrt):
+        from sympy.tensor.array.ndim_array import NDimArray
+
+        if isinstance(wrt, Indexed) and wrt.base == self.base:
+            if len(self.indices) != len(wrt.indices):
+                msg = "Different # of indices: d({!s})/d({!s})".format(self,
+                                                                       wrt)
+                raise IndexException(msg)
+            result = S.One
+            for index1, index2 in zip(self.indices, wrt.indices):
+                result *= KroneckerDelta(index1, index2)
+            return result
+        elif isinstance(self.base, NDimArray):
+            from sympy.tensor.array import derive_by_array
+            return Indexed(derive_by_array(self.base, wrt), *self.args[1:])
+        else:
+            if Tuple(self.indices).has(wrt):
+                return S.NaN
+            return S.Zero
+
+    @property
+    def assumptions0(self):
+        return {k: v for k, v in self._assumptions.items() if v is not None}
+
+    @property
+    def base(self):
+        """Returns the ``IndexedBase`` of the ``Indexed`` object.
+
+        Examples
+        ========
+
+        >>> from sympy import Indexed, IndexedBase, Idx, symbols
+        >>> i, j = symbols('i j', cls=Idx)
+        >>> Indexed('A', i, j).base
+        A
+        >>> B = IndexedBase('B')
+        >>> B == B[i, j].base
+        True
+
+        """
+        return self.args[0]
+
+    @property
+    def indices(self):
+        """
+        Returns the indices of the ``Indexed`` object.
+
+        Examples
+        ========
+
+        >>> from sympy import Indexed, Idx, symbols
+        >>> i, j = symbols('i j', cls=Idx)
+        >>> Indexed('A', i, j).indices
+        (i, j)
+
+        """
+        return self.args[1:]
+
+    @property
+    def rank(self):
+        """
+        Returns the rank of the ``Indexed`` object.
+
+        Examples
+        ========
+
+        >>> from sympy import Indexed, Idx, symbols
+        >>> i, j, k, l, m = symbols('i:m', cls=Idx)
+        >>> Indexed('A', i, j).rank
+        2
+        >>> q = Indexed('A', i, j, k, l, m)
+        >>> q.rank
+        5
+        >>> q.rank == len(q.indices)
+        True
+
+        """
+        return len(self.args) - 1
+
+    @property
+    def shape(self):
+        """Returns a list with dimensions of each index.
+
+        Dimensions is a property of the array, not of the indices.  Still, if
+        the ``IndexedBase`` does not define a shape attribute, it is assumed
+        that the ranges of the indices correspond to the shape of the array.
+
+        >>> from sympy import IndexedBase, Idx, symbols
+        >>> n, m = symbols('n m', integer=True)
+        >>> i = Idx('i', m)
+        >>> j = Idx('j', m)
+        >>> A = IndexedBase('A', shape=(n, n))
+        >>> B = IndexedBase('B')
+        >>> A[i, j].shape
+        (n, n)
+        >>> B[i, j].shape
+        (m, m)
+        """
+
+        if self.base.shape:
+            return self.base.shape
+        sizes = []
+        for i in self.indices:
+            upper = getattr(i, 'upper', None)
+            lower = getattr(i, 'lower', None)
+            if None in (upper, lower):
+                raise IndexException(filldedent("""
+                    Range is not defined for all indices in: %s""" % self))
+            try:
+                size = upper - lower + 1
+            except TypeError:
+                raise IndexException(filldedent("""
+                    Shape cannot be inferred from Idx with
+                    undefined range: %s""" % self))
+            sizes.append(size)
+        return Tuple(*sizes)
+
+    @property
+    def ranges(self):
+        """Returns a list of tuples with lower and upper range of each index.
+
+        If an index does not define the data members upper and lower, the
+        corresponding slot in the list contains ``None`` instead of a tuple.
+
+        Examples
+        ========
+
+        >>> from sympy import Indexed,Idx, symbols
+        >>> Indexed('A', Idx('i', 2), Idx('j', 4), Idx('k', 8)).ranges
+        [(0, 1), (0, 3), (0, 7)]
+        >>> Indexed('A', Idx('i', 3), Idx('j', 3), Idx('k', 3)).ranges
+        [(0, 2), (0, 2), (0, 2)]
+        >>> x, y, z = symbols('x y z', integer=True)
+        >>> Indexed('A', x, y, z).ranges
+        [None, None, None]
+
+        """
+        ranges = []
+        sentinel = object()
+        for i in self.indices:
+            upper = getattr(i, 'upper', sentinel)
+            lower = getattr(i, 'lower', sentinel)
+            if sentinel not in (upper, lower):
+                ranges.append((lower, upper))
+            else:
+                ranges.append(None)
+        return ranges
+
+    def _sympystr(self, p):
+        indices = list(map(p.doprint, self.indices))
+        return "%s[%s]" % (p.doprint(self.base), ", ".join(indices))
+
+    @property
+    def free_symbols(self):
+        base_free_symbols = self.base.free_symbols
+        indices_free_symbols = {
+            fs for i in self.indices for fs in i.free_symbols}
+        if base_free_symbols:
+            return {self} | base_free_symbols | indices_free_symbols
+        else:
+            return indices_free_symbols
+
+    @property
+    def expr_free_symbols(self):
+        from sympy.utilities.exceptions import sympy_deprecation_warning
+        sympy_deprecation_warning("""
+        The expr_free_symbols property is deprecated. Use free_symbols to get
+        the free symbols of an expression.
+        """,
+            deprecated_since_version="1.9",
+            active_deprecations_target="deprecated-expr-free-symbols")
+
+        return {self}
+
+
+class IndexedBase(Expr, NotIterable):
+    """Represent the base or stem of an indexed object
+
+    The IndexedBase class represent an array that contains elements. The main purpose
+    of this class is to allow the convenient creation of objects of the Indexed
+    class.  The __getitem__ method of IndexedBase returns an instance of
+    Indexed.  Alone, without indices, the IndexedBase class can be used as a
+    notation for e.g. matrix equations, resembling what you could do with the
+    Symbol class.  But, the IndexedBase class adds functionality that is not
+    available for Symbol instances:
+
+      -  An IndexedBase object can optionally store shape information.  This can
+         be used in to check array conformance and conditions for numpy
+         broadcasting.  (TODO)
+      -  An IndexedBase object implements syntactic sugar that allows easy symbolic
+         representation of array operations, using implicit summation of
+         repeated indices.
+      -  The IndexedBase object symbolizes a mathematical structure equivalent
+         to arrays, and is recognized as such for code generation and automatic
+         compilation and wrapping.
+
+    >>> from sympy.tensor import IndexedBase, Idx
+    >>> from sympy import symbols
+    >>> A = IndexedBase('A'); A
+    A
+    >>> type(A)
+    
+
+    When an IndexedBase object receives indices, it returns an array with named
+    axes, represented by an Indexed object:
+
+    >>> i, j = symbols('i j', integer=True)
+    >>> A[i, j, 2]
+    A[i, j, 2]
+    >>> type(A[i, j, 2])
+    
+
+    The IndexedBase constructor takes an optional shape argument.  If given,
+    it overrides any shape information in the indices. (But not the index
+    ranges!)
+
+    >>> m, n, o, p = symbols('m n o p', integer=True)
+    >>> i = Idx('i', m)
+    >>> j = Idx('j', n)
+    >>> A[i, j].shape
+    (m, n)
+    >>> B = IndexedBase('B', shape=(o, p))
+    >>> B[i, j].shape
+    (o, p)
+
+    Assumptions can be specified with keyword arguments the same way as for Symbol:
+
+    >>> A_real = IndexedBase('A', real=True)
+    >>> A_real.is_real
+    True
+    >>> A != A_real
+    True
+
+    Assumptions can also be inherited if a Symbol is used to initialize the IndexedBase:
+
+    >>> I = symbols('I', integer=True)
+    >>> C_inherit = IndexedBase(I)
+    >>> C_explicit = IndexedBase('I', integer=True)
+    >>> C_inherit == C_explicit
+    True
+    """
+    is_symbol = True
+    is_Atom = True
+
+    @staticmethod
+    def _set_assumptions(obj, assumptions):
+        """Set assumptions on obj, making sure to apply consistent values."""
+        tmp_asm_copy = assumptions.copy()
+        is_commutative = fuzzy_bool(assumptions.get('commutative', True))
+        assumptions['commutative'] = is_commutative
+        obj._assumptions = StdFactKB(assumptions)
+        obj._assumptions._generator = tmp_asm_copy  # Issue #8873
+
+    def __new__(cls, label, shape=None, *, offset=S.Zero, strides=None, **kw_args):
+        from sympy.matrices.matrixbase import MatrixBase
+        from sympy.tensor.array.ndim_array import NDimArray
+
+        assumptions, kw_args = _filter_assumptions(kw_args)
+        if isinstance(label, str):
+            label = Symbol(label, **assumptions)
+        elif isinstance(label, Symbol):
+            assumptions = label._merge(assumptions)
+        elif isinstance(label, (MatrixBase, NDimArray)):
+            return label
+        elif isinstance(label, Iterable):
+            return _sympify(label)
+        else:
+            label = _sympify(label)
+
+        if is_sequence(shape):
+            shape = Tuple(*shape)
+        elif shape is not None:
+            shape = Tuple(shape)
+
+        if shape is not None:
+            obj = Expr.__new__(cls, label, shape)
+        else:
+            obj = Expr.__new__(cls, label)
+        obj._shape = shape
+        obj._offset = offset
+        obj._strides = strides
+        obj._name = str(label)
+
+        IndexedBase._set_assumptions(obj, assumptions)
+        return obj
+
+    @property
+    def name(self):
+        return self._name
+
+    def _hashable_content(self):
+        return super()._hashable_content() + tuple(sorted(self.assumptions0.items()))
+
+    @property
+    def assumptions0(self):
+        return {k: v for k, v in self._assumptions.items() if v is not None}
+
+    def __getitem__(self, indices, **kw_args):
+        if is_sequence(indices):
+            # Special case needed because M[*my_tuple] is a syntax error.
+            if self.shape and len(self.shape) != len(indices):
+                raise IndexException("Rank mismatch.")
+            return Indexed(self, *indices, **kw_args)
+        else:
+            if self.shape and len(self.shape) != 1:
+                raise IndexException("Rank mismatch.")
+            return Indexed(self, indices, **kw_args)
+
+    @property
+    def shape(self):
+        """Returns the shape of the ``IndexedBase`` object.
+
+        Examples
+        ========
+
+        >>> from sympy import IndexedBase, Idx
+        >>> from sympy.abc import x, y
+        >>> IndexedBase('A', shape=(x, y)).shape
+        (x, y)
+
+        Note: If the shape of the ``IndexedBase`` is specified, it will override
+        any shape information given by the indices.
+
+        >>> A = IndexedBase('A', shape=(x, y))
+        >>> B = IndexedBase('B')
+        >>> i = Idx('i', 2)
+        >>> j = Idx('j', 1)
+        >>> A[i, j].shape
+        (x, y)
+        >>> B[i, j].shape
+        (2, 1)
+
+        """
+        return self._shape
+
+    @property
+    def strides(self):
+        """Returns the strided scheme for the ``IndexedBase`` object.
+
+        Normally this is a tuple denoting the number of
+        steps to take in the respective dimension when traversing
+        an array. For code generation purposes strides='C' and
+        strides='F' can also be used.
+
+        strides='C' would mean that code printer would unroll
+        in row-major order and 'F' means unroll in column major
+        order.
+
+        """
+
+        return self._strides
+
+    @property
+    def offset(self):
+        """Returns the offset for the ``IndexedBase`` object.
+
+        This is the value added to the resulting index when the
+        2D Indexed object is unrolled to a 1D form. Used in code
+        generation.
+
+        Examples
+        ==========
+        >>> from sympy.printing import ccode
+        >>> from sympy.tensor import IndexedBase, Idx
+        >>> from sympy import symbols
+        >>> l, m, n, o = symbols('l m n o', integer=True)
+        >>> A = IndexedBase('A', strides=(l, m, n), offset=o)
+        >>> i, j, k = map(Idx, 'ijk')
+        >>> ccode(A[i, j, k])
+        'A[l*i + m*j + n*k + o]'
+
+        """
+        return self._offset
+
+    @property
+    def label(self):
+        """Returns the label of the ``IndexedBase`` object.
+
+        Examples
+        ========
+
+        >>> from sympy import IndexedBase
+        >>> from sympy.abc import x, y
+        >>> IndexedBase('A', shape=(x, y)).label
+        A
+
+        """
+        return self.args[0]
+
+    def _sympystr(self, p):
+        return p.doprint(self.label)
+
+
+class Idx(Expr):
+    """Represents an integer index as an ``Integer`` or integer expression.
+
+    There are a number of ways to create an ``Idx`` object.  The constructor
+    takes two arguments:
+
+    ``label``
+        An integer or a symbol that labels the index.
+    ``range``
+        Optionally you can specify a range as either
+
+        * ``Symbol`` or integer: This is interpreted as a dimension. Lower and
+          upper bounds are set to ``0`` and ``range - 1``, respectively.
+        * ``tuple``: The two elements are interpreted as the lower and upper
+          bounds of the range, respectively.
+
+    Note: bounds of the range are assumed to be either integer or infinite (oo
+    and -oo are allowed to specify an unbounded range). If ``n`` is given as a
+    bound, then ``n.is_integer`` must not return false.
+
+    For convenience, if the label is given as a string it is automatically
+    converted to an integer symbol.  (Note: this conversion is not done for
+    range or dimension arguments.)
+
+    Examples
+    ========
+
+    >>> from sympy import Idx, symbols, oo
+    >>> n, i, L, U = symbols('n i L U', integer=True)
+
+    If a string is given for the label an integer ``Symbol`` is created and the
+    bounds are both ``None``:
+
+    >>> idx = Idx('qwerty'); idx
+    qwerty
+    >>> idx.lower, idx.upper
+    (None, None)
+
+    Both upper and lower bounds can be specified:
+
+    >>> idx = Idx(i, (L, U)); idx
+    i
+    >>> idx.lower, idx.upper
+    (L, U)
+
+    When only a single bound is given it is interpreted as the dimension
+    and the lower bound defaults to 0:
+
+    >>> idx = Idx(i, n); idx.lower, idx.upper
+    (0, n - 1)
+    >>> idx = Idx(i, 4); idx.lower, idx.upper
+    (0, 3)
+    >>> idx = Idx(i, oo); idx.lower, idx.upper
+    (0, oo)
+
+    """
+
+    is_integer = True
+    is_finite = True
+    is_real = True
+    is_symbol = True
+    is_Atom = True
+    _diff_wrt = True
+
+    def __new__(cls, label, range=None, **kw_args):
+
+        if isinstance(label, str):
+            label = Symbol(label, integer=True)
+        label, range = list(map(sympify, (label, range)))
+
+        if label.is_Number:
+            if not label.is_integer:
+                raise TypeError("Index is not an integer number.")
+            return label
+
+        if not label.is_integer:
+            raise TypeError("Idx object requires an integer label.")
+
+        elif is_sequence(range):
+            if len(range) != 2:
+                raise ValueError(filldedent("""
+                    Idx range tuple must have length 2, but got %s""" % len(range)))
+            for bound in range:
+                if (bound.is_integer is False and bound is not S.Infinity
+                        and bound is not S.NegativeInfinity):
+                    raise TypeError("Idx object requires integer bounds.")
+            args = label, Tuple(*range)
+        elif isinstance(range, Expr):
+            if range is not S.Infinity and fuzzy_not(range.is_integer):
+                raise TypeError("Idx object requires an integer dimension.")
+            args = label, Tuple(0, range - 1)
+        elif range:
+            raise TypeError(filldedent("""
+                The range must be an ordered iterable or
+                integer SymPy expression."""))
+        else:
+            args = label,
+
+        obj = Expr.__new__(cls, *args, **kw_args)
+        obj._assumptions["finite"] = True
+        obj._assumptions["real"] = True
+        return obj
+
+    @property
+    def label(self):
+        """Returns the label (Integer or integer expression) of the Idx object.
+
+        Examples
+        ========
+
+        >>> from sympy import Idx, Symbol
+        >>> x = Symbol('x', integer=True)
+        >>> Idx(x).label
+        x
+        >>> j = Symbol('j', integer=True)
+        >>> Idx(j).label
+        j
+        >>> Idx(j + 1).label
+        j + 1
+
+        """
+        return self.args[0]
+
+    @property
+    def lower(self):
+        """Returns the lower bound of the ``Idx``.
+
+        Examples
+        ========
+
+        >>> from sympy import Idx
+        >>> Idx('j', 2).lower
+        0
+        >>> Idx('j', 5).lower
+        0
+        >>> Idx('j').lower is None
+        True
+
+        """
+        try:
+            return self.args[1][0]
+        except IndexError:
+            return
+
+    @property
+    def upper(self):
+        """Returns the upper bound of the ``Idx``.
+
+        Examples
+        ========
+
+        >>> from sympy import Idx
+        >>> Idx('j', 2).upper
+        1
+        >>> Idx('j', 5).upper
+        4
+        >>> Idx('j').upper is None
+        True
+
+        """
+        try:
+            return self.args[1][1]
+        except IndexError:
+            return
+
+    def _sympystr(self, p):
+        return p.doprint(self.label)
+
+    @property
+    def name(self):
+        return self.label.name if self.label.is_Symbol else str(self.label)
+
+    @property
+    def free_symbols(self):
+        return {self}
+
+
+@dispatch(Idx, Idx)
+def _eval_is_ge(lhs, rhs): # noqa:F811
+
+    other_upper = rhs if rhs.upper is None else rhs.upper
+    other_lower = rhs if rhs.lower is None else rhs.lower
+
+    if lhs.lower is not None and (lhs.lower >= other_upper) == True:
+        return True
+    if lhs.upper is not None and (lhs.upper < other_lower) == True:
+        return False
+    return None
+
+
+@dispatch(Idx, Number)  # type:ignore
+def _eval_is_ge(lhs, rhs): # noqa:F811
+
+    other_upper = rhs
+    other_lower = rhs
+
+    if lhs.lower is not None and (lhs.lower >= other_upper) == True:
+        return True
+    if lhs.upper is not None and (lhs.upper < other_lower) == True:
+        return False
+    return None
+
+
+@dispatch(Number, Idx)  # type:ignore
+def _eval_is_ge(lhs, rhs): # noqa:F811
+
+    other_upper = lhs
+    other_lower = lhs
+
+    if rhs.upper is not None and (rhs.upper <= other_lower) == True:
+        return True
+    if rhs.lower is not None and (rhs.lower > other_upper) == True:
+        return False
+    return None
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/tensor.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/tensor.py
new file mode 100644
index 0000000000000000000000000000000000000000..579e7c7a86c2a1f18ab889af32ce0053a729ff5f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/tensor.py
@@ -0,0 +1,5265 @@
+"""
+This module defines tensors with abstract index notation.
+
+The abstract index notation has been first formalized by Penrose.
+
+Tensor indices are formal objects, with a tensor type; there is no
+notion of index range, it is only possible to assign the dimension,
+used to trace the Kronecker delta; the dimension can be a Symbol.
+
+The Einstein summation convention is used.
+The covariant indices are indicated with a minus sign in front of the index.
+
+For instance the tensor ``t = p(a)*A(b,c)*q(-c)`` has the index ``c``
+contracted.
+
+A tensor expression ``t`` can be called; called with its
+indices in sorted order it is equal to itself:
+in the above example ``t(a, b) == t``;
+one can call ``t`` with different indices; ``t(c, d) == p(c)*A(d,a)*q(-a)``.
+
+The contracted indices are dummy indices, internally they have no name,
+the indices being represented by a graph-like structure.
+
+Tensors are put in canonical form using ``canon_bp``, which uses
+the Butler-Portugal algorithm for canonicalization using the monoterm
+symmetries of the tensors.
+
+If there is a (anti)symmetric metric, the indices can be raised and
+lowered when the tensor is put in canonical form.
+"""
+
+from __future__ import annotations
+from typing import Any
+from functools import reduce
+from math import prod
+
+from abc import abstractmethod, ABC
+from collections import defaultdict
+import operator
+import itertools
+
+from sympy.core.numbers import (Integer, Rational)
+from sympy.combinatorics import Permutation
+from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, \
+    bsgs_direct_product, canonicalize, riemann_bsgs
+from sympy.core import Basic, Expr, sympify, Add, Mul, S
+from sympy.core.cache import clear_cache
+from sympy.core.containers import Tuple, Dict
+from sympy.core.function import WildFunction
+from sympy.core.sorting import default_sort_key
+from sympy.core.symbol import Symbol, symbols, Wild
+from sympy.core.sympify import CantSympify, _sympify
+from sympy.core.operations import AssocOp
+from sympy.external.gmpy import SYMPY_INTS
+from sympy.matrices import eye
+from sympy.utilities.exceptions import (sympy_deprecation_warning,
+                                        SymPyDeprecationWarning,
+                                        ignore_warnings)
+from sympy.utilities.decorator import memoize_property, deprecated
+from sympy.utilities.iterables import sift
+
+
+def deprecate_data():
+    sympy_deprecation_warning(
+        """
+        The data attribute of TensorIndexType is deprecated. Use The
+        replace_with_arrays() method instead.
+        """,
+        deprecated_since_version="1.4",
+        active_deprecations_target="deprecated-tensorindextype-attrs",
+        stacklevel=4,
+    )
+
+def deprecate_fun_eval():
+    sympy_deprecation_warning(
+        """
+        The Tensor.fun_eval() method is deprecated. Use
+        Tensor.substitute_indices() instead.
+        """,
+        deprecated_since_version="1.5",
+        active_deprecations_target="deprecated-tensor-fun-eval",
+        stacklevel=4,
+    )
+
+
+def deprecate_call():
+    sympy_deprecation_warning(
+        """
+        Calling a tensor like Tensor(*indices) is deprecated. Use
+        Tensor.substitute_indices() instead.
+        """,
+        deprecated_since_version="1.5",
+        active_deprecations_target="deprecated-tensor-fun-eval",
+        stacklevel=4,
+    )
+
+
+class _IndexStructure(CantSympify):
+    """
+    This class handles the indices (free and dummy ones). It contains the
+    algorithms to manage the dummy indices replacements and contractions of
+    free indices under multiplications of tensor expressions, as well as stuff
+    related to canonicalization sorting, getting the permutation of the
+    expression and so on. It also includes tools to get the ``TensorIndex``
+    objects corresponding to the given index structure.
+    """
+
+    def __init__(self, free, dum, index_types, indices, canon_bp=False):
+        self.free = free
+        self.dum = dum
+        self.index_types = index_types
+        self.indices = indices
+        self._ext_rank = len(self.free) + 2*len(self.dum)
+        self.dum.sort(key=lambda x: x[0])
+
+    @staticmethod
+    def from_indices(*indices):
+        """
+        Create a new ``_IndexStructure`` object from a list of ``indices``.
+
+        Explanation
+        ===========
+
+        ``indices``     ``TensorIndex`` objects, the indices. Contractions are
+                        detected upon construction.
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, _IndexStructure
+        >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+        >>> m0, m1, m2, m3 = tensor_indices('m0,m1,m2,m3', Lorentz)
+        >>> _IndexStructure.from_indices(m0, m1, -m1, m3)
+        _IndexStructure([(m0, 0), (m3, 3)], [(1, 2)], [Lorentz, Lorentz, Lorentz, Lorentz])
+        """
+
+        free, dum = _IndexStructure._free_dum_from_indices(*indices)
+        index_types = [i.tensor_index_type for i in indices]
+        indices = _IndexStructure._replace_dummy_names(indices, free, dum)
+        return _IndexStructure(free, dum, index_types, indices)
+
+    @staticmethod
+    def from_components_free_dum(components, free, dum):
+        index_types = []
+        for component in components:
+            index_types.extend(component.index_types)
+        indices = _IndexStructure.generate_indices_from_free_dum_index_types(free, dum, index_types)
+        return _IndexStructure(free, dum, index_types, indices)
+
+    @staticmethod
+    def _free_dum_from_indices(*indices):
+        """
+        Convert ``indices`` into ``free``, ``dum`` for single component tensor.
+
+        Explanation
+        ===========
+
+        ``free``     list of tuples ``(index, pos, 0)``,
+                     where ``pos`` is the position of index in
+                     the list of indices formed by the component tensors
+
+        ``dum``      list of tuples ``(pos_contr, pos_cov, 0, 0)``
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, \
+            _IndexStructure
+        >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+        >>> m0, m1, m2, m3 = tensor_indices('m0,m1,m2,m3', Lorentz)
+        >>> _IndexStructure._free_dum_from_indices(m0, m1, -m1, m3)
+        ([(m0, 0), (m3, 3)], [(1, 2)])
+        """
+        n = len(indices)
+        if n == 1:
+            return [(indices[0], 0)], []
+
+        # find the positions of the free indices and of the dummy indices
+        free = [True]*len(indices)
+        index_dict = {}
+        dum = []
+        for i, index in enumerate(indices):
+            name = index.name
+            typ = index.tensor_index_type
+            contr = index.is_up
+            if (name, typ) in index_dict:
+                # found a pair of dummy indices
+                is_contr, pos = index_dict[(name, typ)]
+                # check consistency and update free
+                if is_contr:
+                    if contr:
+                        raise ValueError('two equal contravariant indices in slots %d and %d' %(pos, i))
+                    else:
+                        free[pos] = False
+                        free[i] = False
+                else:
+                    if contr:
+                        free[pos] = False
+                        free[i] = False
+                    else:
+                        raise ValueError('two equal covariant indices in slots %d and %d' %(pos, i))
+                if contr:
+                    dum.append((i, pos))
+                else:
+                    dum.append((pos, i))
+            else:
+                index_dict[(name, typ)] = index.is_up, i
+
+        free = [(index, i) for i, index in enumerate(indices) if free[i]]
+        free.sort()
+        return free, dum
+
+    def get_indices(self):
+        """
+        Get a list of indices, creating new tensor indices to complete dummy indices.
+        """
+        return self.indices[:]
+
+    @staticmethod
+    def generate_indices_from_free_dum_index_types(free, dum, index_types):
+        indices = [None]*(len(free)+2*len(dum))
+        for idx, pos in free:
+            indices[pos] = idx
+
+        generate_dummy_name = _IndexStructure._get_generator_for_dummy_indices(free)
+        for pos1, pos2 in dum:
+            typ1 = index_types[pos1]
+            indname = generate_dummy_name(typ1)
+            indices[pos1] = TensorIndex(indname, typ1, True)
+            indices[pos2] = TensorIndex(indname, typ1, False)
+
+        return _IndexStructure._replace_dummy_names(indices, free, dum)
+
+    @staticmethod
+    def _get_generator_for_dummy_indices(free):
+        cdt = defaultdict(int)
+        # if the free indices have names with dummy_name, start with an
+        # index higher than those for the dummy indices
+        # to avoid name collisions
+        for indx, ipos in free:
+            if indx.name.split('_')[0] == indx.tensor_index_type.dummy_name:
+                cdt[indx.tensor_index_type] = max(cdt[indx.tensor_index_type], int(indx.name.split('_')[1]) + 1)
+
+        def dummy_name_gen(tensor_index_type):
+            nd = str(cdt[tensor_index_type])
+            cdt[tensor_index_type] += 1
+            return tensor_index_type.dummy_name + '_' + nd
+
+        return dummy_name_gen
+
+    @staticmethod
+    def _replace_dummy_names(indices, free, dum):
+        dum.sort(key=lambda x: x[0])
+        new_indices = list(indices)
+        assert len(indices) == len(free) + 2*len(dum)
+        generate_dummy_name = _IndexStructure._get_generator_for_dummy_indices(free)
+        for ipos1, ipos2 in dum:
+            typ1 = new_indices[ipos1].tensor_index_type
+            indname = generate_dummy_name(typ1)
+            new_indices[ipos1] = TensorIndex(indname, typ1, True)
+            new_indices[ipos2] = TensorIndex(indname, typ1, False)
+        return new_indices
+
+    def get_free_indices(self) -> list[TensorIndex]:
+        """
+        Get a list of free indices.
+        """
+        # get sorted indices according to their position:
+        free = sorted(self.free, key=lambda x: x[1])
+        return [i[0] for i in free]
+
+    def __str__(self):
+        return "_IndexStructure({}, {}, {})".format(self.free, self.dum, self.index_types)
+
+    def __repr__(self):
+        return self.__str__()
+
+    def _get_sorted_free_indices_for_canon(self):
+        sorted_free = self.free[:]
+        sorted_free.sort(key=lambda x: x[0])
+        return sorted_free
+
+    def _get_sorted_dum_indices_for_canon(self):
+        return sorted(self.dum, key=lambda x: x[0])
+
+    def _get_lexicographically_sorted_index_types(self):
+        permutation = self.indices_canon_args()[0]
+        index_types = [None]*self._ext_rank
+        for i, it in enumerate(self.index_types):
+            index_types[permutation(i)] = it
+        return index_types
+
+    def _get_lexicographically_sorted_indices(self):
+        permutation = self.indices_canon_args()[0]
+        indices = [None]*self._ext_rank
+        for i, it in enumerate(self.indices):
+            indices[permutation(i)] = it
+        return indices
+
+    def perm2tensor(self, g, is_canon_bp=False):
+        """
+        Returns a ``_IndexStructure`` instance corresponding to the permutation ``g``.
+
+        Explanation
+        ===========
+
+        ``g``  permutation corresponding to the tensor in the representation
+        used in canonicalization
+
+        ``is_canon_bp``   if True, then ``g`` is the permutation
+        corresponding to the canonical form of the tensor
+        """
+        sorted_free = [i[0] for i in self._get_sorted_free_indices_for_canon()]
+        lex_index_types = self._get_lexicographically_sorted_index_types()
+        lex_indices = self._get_lexicographically_sorted_indices()
+        nfree = len(sorted_free)
+        rank = self._ext_rank
+        dum = [[None]*2 for i in range((rank - nfree)//2)]
+        free = []
+
+        index_types = [None]*rank
+        indices = [None]*rank
+        for i in range(rank):
+            gi = g[i]
+            index_types[i] = lex_index_types[gi]
+            indices[i] = lex_indices[gi]
+            if gi < nfree:
+                ind = sorted_free[gi]
+                assert index_types[i] == sorted_free[gi].tensor_index_type
+                free.append((ind, i))
+            else:
+                j = gi - nfree
+                idum, cov = divmod(j, 2)
+                if cov:
+                    dum[idum][1] = i
+                else:
+                    dum[idum][0] = i
+        dum = [tuple(x) for x in dum]
+
+        return _IndexStructure(free, dum, index_types, indices)
+
+    def indices_canon_args(self):
+        """
+        Returns ``(g, dummies, msym, v)``, the entries of ``canonicalize``
+
+        See ``canonicalize`` in ``tensor_can.py`` in combinatorics module.
+        """
+        # to be called after sorted_components
+        from sympy.combinatorics.permutations import _af_new
+        n = self._ext_rank
+        g = [None]*n + [n, n+1]
+
+        # Converts the symmetry of the metric into msym from .canonicalize()
+        # method in the combinatorics module
+        def metric_symmetry_to_msym(metric):
+            if metric is None:
+                return None
+            sym = metric.symmetry
+            if sym == TensorSymmetry.fully_symmetric(2):
+                return 0
+            if sym == TensorSymmetry.fully_symmetric(-2):
+                return 1
+            return None
+
+        # ordered indices: first the free indices, ordered by types
+        # then the dummy indices, ordered by types and contravariant before
+        # covariant
+        # g[position in tensor] = position in ordered indices
+        for i, (indx, ipos) in enumerate(self._get_sorted_free_indices_for_canon()):
+            g[ipos] = i
+        pos = len(self.free)
+        j = len(self.free)
+        dummies = []
+        prev = None
+        a = []
+        msym = []
+        for ipos1, ipos2 in self._get_sorted_dum_indices_for_canon():
+            g[ipos1] = j
+            g[ipos2] = j + 1
+            j += 2
+            typ = self.index_types[ipos1]
+            if typ != prev:
+                if a:
+                    dummies.append(a)
+                a = [pos, pos + 1]
+                prev = typ
+                msym.append(metric_symmetry_to_msym(typ.metric))
+            else:
+                a.extend([pos, pos + 1])
+            pos += 2
+        if a:
+            dummies.append(a)
+
+        return _af_new(g), dummies, msym
+
+
+def components_canon_args(components):
+    numtyp = []
+    prev = None
+    for t in components:
+        if t == prev:
+            numtyp[-1][1] += 1
+        else:
+            prev = t
+            numtyp.append([prev, 1])
+    v = []
+    for h, n in numtyp:
+        if h.comm in (0, 1):
+            comm = h.comm
+        else:
+            comm = TensorManager.get_comm(h.comm, h.comm)
+        v.append((h.symmetry.base, h.symmetry.generators, n, comm))
+    return v
+
+
+class _TensorDataLazyEvaluator(CantSympify):
+    """
+    EXPERIMENTAL: do not rely on this class, it may change without deprecation
+    warnings in future versions of SymPy.
+
+    Explanation
+    ===========
+
+    This object contains the logic to associate components data to a tensor
+    expression. Components data are set via the ``.data`` property of tensor
+    expressions, is stored inside this class as a mapping between the tensor
+    expression and the ``ndarray``.
+
+    Computations are executed lazily: whereas the tensor expressions can have
+    contractions, tensor products, and additions, components data are not
+    computed until they are accessed by reading the ``.data`` property
+    associated to the tensor expression.
+    """
+    _substitutions_dict: dict[Any, Any] = {}
+    _substitutions_dict_tensmul: dict[Any, Any] = {}
+
+    def __getitem__(self, key):
+        dat = self._get(key)
+        if dat is None:
+            return None
+
+        from .array import NDimArray
+        if not isinstance(dat, NDimArray):
+            return dat
+
+        if dat.rank() == 0:
+            return dat[()]
+        elif dat.rank() == 1 and len(dat) == 1:
+            return dat[0]
+        return dat
+
+    def _get(self, key):
+        """
+        Retrieve ``data`` associated with ``key``.
+
+        Explanation
+        ===========
+
+        This algorithm looks into ``self._substitutions_dict`` for all
+        ``TensorHead`` in the ``TensExpr`` (or just ``TensorHead`` if key is a
+        TensorHead instance). It reconstructs the components data that the
+        tensor expression should have by performing on components data the
+        operations that correspond to the abstract tensor operations applied.
+
+        Metric tensor is handled in a different manner: it is pre-computed in
+        ``self._substitutions_dict_tensmul``.
+        """
+        if key in self._substitutions_dict:
+            return self._substitutions_dict[key]
+
+        if isinstance(key, TensorHead):
+            return None
+
+        if isinstance(key, Tensor):
+            # special case to handle metrics. Metric tensors cannot be
+            # constructed through contraction by the metric, their
+            # components show if they are a matrix or its inverse.
+            signature = tuple([i.is_up for i in key.get_indices()])
+            srch = (key.component,) + signature
+            if srch in self._substitutions_dict_tensmul:
+                return self._substitutions_dict_tensmul[srch]
+            array_list = [self.data_from_tensor(key)]
+            return self.data_contract_dum(array_list, key.dum, key.ext_rank)
+
+        if isinstance(key, TensMul):
+            tensmul_args = key.args
+            if len(tensmul_args) == 1 and len(tensmul_args[0].components) == 1:
+                # special case to handle metrics. Metric tensors cannot be
+                # constructed through contraction by the metric, their
+                # components show if they are a matrix or its inverse.
+                signature = tuple([i.is_up for i in tensmul_args[0].get_indices()])
+                srch = (tensmul_args[0].components[0],) + signature
+                if srch in self._substitutions_dict_tensmul:
+                    return self._substitutions_dict_tensmul[srch]
+            #data_list = [self.data_from_tensor(i) for i in tensmul_args if isinstance(i, TensExpr)]
+            data_list = [self.data_from_tensor(i) if isinstance(i, Tensor) else i.data for i in tensmul_args if isinstance(i, TensExpr)]
+            coeff = prod([i for i in tensmul_args if not isinstance(i, TensExpr)])
+            if all(i is None for i in data_list):
+                return None
+            if any(i is None for i in data_list):
+                raise ValueError("Mixing tensors with associated components "\
+                                 "data with tensors without components data")
+            data_result = self.data_contract_dum(data_list, key.dum, key.ext_rank)
+            return coeff*data_result
+
+        if isinstance(key, TensAdd):
+            data_list = []
+            free_args_list = []
+            for arg in key.args:
+                if isinstance(arg, TensExpr):
+                    data_list.append(arg.data)
+                    free_args_list.append([x[0] for x in arg.free])
+                else:
+                    data_list.append(arg)
+                    free_args_list.append([])
+            if all(i is None for i in data_list):
+                return None
+            if any(i is None for i in data_list):
+                raise ValueError("Mixing tensors with associated components "\
+                                 "data with tensors without components data")
+
+            sum_list = []
+            from .array import permutedims
+            for data, free_args in zip(data_list, free_args_list):
+                if len(free_args) < 2:
+                    sum_list.append(data)
+                else:
+                    free_args_pos = {y: x for x, y in enumerate(free_args)}
+                    axes = [free_args_pos[arg] for arg in key.free_args]
+                    sum_list.append(permutedims(data, axes))
+            return reduce(lambda x, y: x+y, sum_list)
+
+        return None
+
+    @staticmethod
+    def data_contract_dum(ndarray_list, dum, ext_rank):
+        from .array import tensorproduct, tensorcontraction, MutableDenseNDimArray
+        arrays = list(map(MutableDenseNDimArray, ndarray_list))
+        prodarr = tensorproduct(*arrays)
+        return tensorcontraction(prodarr, *dum)
+
+    def data_tensorhead_from_tensmul(self, data, tensmul, tensorhead):
+        """
+        This method is used when assigning components data to a ``TensMul``
+        object, it converts components data to a fully contravariant ndarray,
+        which is then stored according to the ``TensorHead`` key.
+        """
+        if data is None:
+            return None
+
+        return self._correct_signature_from_indices(
+            data,
+            tensmul.get_indices(),
+            tensmul.free,
+            tensmul.dum,
+            True)
+
+    def data_from_tensor(self, tensor):
+        """
+        This method corrects the components data to the right signature
+        (covariant/contravariant) using the metric associated with each
+        ``TensorIndexType``.
+        """
+        tensorhead = tensor.component
+
+        if tensorhead.data is None:
+            return None
+
+        return self._correct_signature_from_indices(
+            tensorhead.data,
+            tensor.get_indices(),
+            tensor.free,
+            tensor.dum)
+
+    def _assign_data_to_tensor_expr(self, key, data):
+        if isinstance(key, TensAdd):
+            raise ValueError('cannot assign data to TensAdd')
+        # here it is assumed that `key` is a `TensMul` instance.
+        if len(key.components) != 1:
+            raise ValueError('cannot assign data to TensMul with multiple components')
+        tensorhead = key.components[0]
+        newdata = self.data_tensorhead_from_tensmul(data, key, tensorhead)
+        return tensorhead, newdata
+
+    def _check_permutations_on_data(self, tens, data):
+        from .array import permutedims
+        from .array.arrayop import Flatten
+
+        if isinstance(tens, TensorHead):
+            rank = tens.rank
+            generators = tens.symmetry.generators
+        elif isinstance(tens, Tensor):
+            rank = tens.rank
+            generators = tens.components[0].symmetry.generators
+        elif isinstance(tens, TensorIndexType):
+            rank = tens.metric.rank
+            generators = tens.metric.symmetry.generators
+
+        # Every generator is a permutation, check that by permuting the array
+        # by that permutation, the array will be the same, except for a
+        # possible sign change if the permutation admits it.
+        for gener in generators:
+            sign_change = +1 if (gener(rank) == rank) else -1
+            data_swapped = data
+            last_data = data
+            permute_axes = list(map(gener, range(rank)))
+            # the order of a permutation is the number of times to get the
+            # identity by applying that permutation.
+            for i in range(gener.order()-1):
+                data_swapped = permutedims(data_swapped, permute_axes)
+                # if any value in the difference array is non-zero, raise an error:
+                if any(Flatten(last_data - sign_change*data_swapped)):
+                    raise ValueError("Component data symmetry structure error")
+                last_data = data_swapped
+
+    def __setitem__(self, key, value):
+        """
+        Set the components data of a tensor object/expression.
+
+        Explanation
+        ===========
+
+        Components data are transformed to the all-contravariant form and stored
+        with the corresponding ``TensorHead`` object. If a ``TensorHead`` object
+        cannot be uniquely identified, it will raise an error.
+        """
+        data = _TensorDataLazyEvaluator.parse_data(value)
+        self._check_permutations_on_data(key, data)
+
+        # TensorHead and TensorIndexType can be assigned data directly, while
+        # TensMul must first convert data to a fully contravariant form, and
+        # assign it to its corresponding TensorHead single component.
+        if not isinstance(key, (TensorHead, TensorIndexType)):
+            key, data = self._assign_data_to_tensor_expr(key, data)
+
+        if isinstance(key, TensorHead):
+            for dim, indextype in zip(data.shape, key.index_types):
+                if indextype.data is None:
+                    raise ValueError("index type {} has no components data"\
+                    " associated (needed to raise/lower index)".format(indextype))
+                if not indextype.dim.is_number:
+                    continue
+                if dim != indextype.dim:
+                    raise ValueError("wrong dimension of ndarray")
+        self._substitutions_dict[key] = data
+
+    def __delitem__(self, key):
+        del self._substitutions_dict[key]
+
+    def __contains__(self, key):
+        return key in self._substitutions_dict
+
+    def add_metric_data(self, metric, data):
+        """
+        Assign data to the ``metric`` tensor. The metric tensor behaves in an
+        anomalous way when raising and lowering indices.
+
+        Explanation
+        ===========
+
+        A fully covariant metric is the inverse transpose of the fully
+        contravariant metric (it is meant matrix inverse). If the metric is
+        symmetric, the transpose is not necessary and mixed
+        covariant/contravariant metrics are Kronecker deltas.
+        """
+        # hard assignment, data should not be added to `TensorHead` for metric:
+        # the problem with `TensorHead` is that the metric is anomalous, i.e.
+        # raising and lowering the index means considering the metric or its
+        # inverse, this is not the case for other tensors.
+        self._substitutions_dict_tensmul[metric, True, True] = data
+        inverse_transpose = self.inverse_transpose_matrix(data)
+        # in symmetric spaces, the transpose is the same as the original matrix,
+        # the full covariant metric tensor is the inverse transpose, so this
+        # code will be able to handle non-symmetric metrics.
+        self._substitutions_dict_tensmul[metric, False, False] = inverse_transpose
+        # now mixed cases, these are identical to the unit matrix if the metric
+        # is symmetric.
+        m = data.tomatrix()
+        invt = inverse_transpose.tomatrix()
+        self._substitutions_dict_tensmul[metric, True, False] = m * invt
+        self._substitutions_dict_tensmul[metric, False, True] = invt * m
+
+    @staticmethod
+    def _flip_index_by_metric(data, metric, pos):
+        from .array import tensorproduct, tensorcontraction
+
+        mdim = metric.rank()
+        ddim = data.rank()
+
+        if pos == 0:
+            data = tensorcontraction(
+                tensorproduct(
+                    metric,
+                    data
+                ),
+                (1, mdim+pos)
+            )
+        else:
+            data = tensorcontraction(
+                tensorproduct(
+                    data,
+                    metric
+                ),
+                (pos, ddim)
+            )
+        return data
+
+    @staticmethod
+    def inverse_matrix(ndarray):
+        m = ndarray.tomatrix().inv()
+        return _TensorDataLazyEvaluator.parse_data(m)
+
+    @staticmethod
+    def inverse_transpose_matrix(ndarray):
+        m = ndarray.tomatrix().inv().T
+        return _TensorDataLazyEvaluator.parse_data(m)
+
+    @staticmethod
+    def _correct_signature_from_indices(data, indices, free, dum, inverse=False):
+        """
+        Utility function to correct the values inside the components data
+        ndarray according to whether indices are covariant or contravariant.
+
+        It uses the metric matrix to lower values of covariant indices.
+        """
+        # change the ndarray values according covariantness/contravariantness of the indices
+        # use the metric
+        for i, indx in enumerate(indices):
+            if not indx.is_up and not inverse:
+                data = _TensorDataLazyEvaluator._flip_index_by_metric(data, indx.tensor_index_type.data, i)
+            elif not indx.is_up and inverse:
+                data = _TensorDataLazyEvaluator._flip_index_by_metric(
+                    data,
+                    _TensorDataLazyEvaluator.inverse_matrix(indx.tensor_index_type.data),
+                    i
+                )
+        return data
+
+    @staticmethod
+    def _sort_data_axes(old, new):
+        from .array import permutedims
+
+        new_data = old.data.copy()
+
+        old_free = [i[0] for i in old.free]
+        new_free = [i[0] for i in new.free]
+
+        for i in range(len(new_free)):
+            for j in range(i, len(old_free)):
+                if old_free[j] == new_free[i]:
+                    old_free[i], old_free[j] = old_free[j], old_free[i]
+                    new_data = permutedims(new_data, (i, j))
+                    break
+        return new_data
+
+    @staticmethod
+    def add_rearrange_tensmul_parts(new_tensmul, old_tensmul):
+        def sorted_compo():
+            return _TensorDataLazyEvaluator._sort_data_axes(old_tensmul, new_tensmul)
+
+        _TensorDataLazyEvaluator._substitutions_dict[new_tensmul] = sorted_compo()
+
+    @staticmethod
+    def parse_data(data):
+        """
+        Transform ``data`` to array. The parameter ``data`` may
+        contain data in various formats, e.g. nested lists, SymPy ``Matrix``,
+        and so on.
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.tensor import _TensorDataLazyEvaluator
+        >>> _TensorDataLazyEvaluator.parse_data([1, 3, -6, 12])
+        [1, 3, -6, 12]
+
+        >>> _TensorDataLazyEvaluator.parse_data([[1, 2], [4, 7]])
+        [[1, 2], [4, 7]]
+        """
+        from .array import MutableDenseNDimArray
+
+        if not isinstance(data, MutableDenseNDimArray):
+            if len(data) == 2 and hasattr(data[0], '__call__'):
+                data = MutableDenseNDimArray(data[0], data[1])
+            else:
+                data = MutableDenseNDimArray(data)
+        return data
+
+_tensor_data_substitution_dict = _TensorDataLazyEvaluator()
+
+
+class _TensorManager:
+    """
+    Class to manage tensor properties.
+
+    Notes
+    =====
+
+    Tensors belong to tensor commutation groups; each group has a label
+    ``comm``; there are predefined labels:
+
+    ``0``   tensors commuting with any other tensor
+
+    ``1``   tensors anticommuting among themselves
+
+    ``2``   tensors not commuting, apart with those with ``comm=0``
+
+    Other groups can be defined using ``set_comm``; tensors in those
+    groups commute with those with ``comm=0``; by default they
+    do not commute with any other group.
+    """
+    def __init__(self):
+        self._comm_init()
+
+    def _comm_init(self):
+        self._comm = [{} for i in range(3)]
+        for i in range(3):
+            self._comm[0][i] = 0
+            self._comm[i][0] = 0
+        self._comm[1][1] = 1
+        self._comm[2][1] = None
+        self._comm[1][2] = None
+        self._comm_symbols2i = {0:0, 1:1, 2:2}
+        self._comm_i2symbol = {0:0, 1:1, 2:2}
+
+    @property
+    def comm(self):
+        return self._comm
+
+    def comm_symbols2i(self, i):
+        """
+        Get the commutation group number corresponding to ``i``.
+
+        ``i`` can be a symbol or a number or a string.
+
+        If ``i`` is not already defined its commutation group number
+        is set.
+        """
+        if i not in self._comm_symbols2i:
+            n = len(self._comm)
+            self._comm.append({})
+            self._comm[n][0] = 0
+            self._comm[0][n] = 0
+            self._comm_symbols2i[i] = n
+            self._comm_i2symbol[n] = i
+            return n
+        return self._comm_symbols2i[i]
+
+    def comm_i2symbol(self, i):
+        """
+        Returns the symbol corresponding to the commutation group number.
+        """
+        return self._comm_i2symbol[i]
+
+    def set_comm(self, i, j, c):
+        """
+        Set the commutation parameter ``c`` for commutation groups ``i, j``.
+
+        Parameters
+        ==========
+
+        i, j : symbols representing commutation groups
+
+        c  :  group commutation number
+
+        Notes
+        =====
+
+        ``i, j`` can be symbols, strings or numbers,
+        apart from ``0, 1`` and ``2`` which are reserved respectively
+        for commuting, anticommuting tensors and tensors not commuting
+        with any other group apart with the commuting tensors.
+        For the remaining cases, use this method to set the commutation rules;
+        by default ``c=None``.
+
+        The group commutation number ``c`` is assigned in correspondence
+        to the group commutation symbols; it can be
+
+        0        commuting
+
+        1        anticommuting
+
+        None     no commutation property
+
+        Examples
+        ========
+
+        ``G`` and ``GH`` do not commute with themselves and commute with
+        each other; A is commuting.
+
+        >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, TensorManager, TensorSymmetry
+        >>> Lorentz = TensorIndexType('Lorentz')
+        >>> i0,i1,i2,i3,i4 = tensor_indices('i0:5', Lorentz)
+        >>> A = TensorHead('A', [Lorentz])
+        >>> G = TensorHead('G', [Lorentz], TensorSymmetry.no_symmetry(1), 'Gcomm')
+        >>> GH = TensorHead('GH', [Lorentz], TensorSymmetry.no_symmetry(1), 'GHcomm')
+        >>> TensorManager.set_comm('Gcomm', 'GHcomm', 0)
+        >>> (GH(i1)*G(i0)).canon_bp()
+        G(i0)*GH(i1)
+        >>> (G(i1)*G(i0)).canon_bp()
+        G(i1)*G(i0)
+        >>> (G(i1)*A(i0)).canon_bp()
+        A(i0)*G(i1)
+        """
+        if c not in (0, 1, None):
+            raise ValueError('`c` can assume only the values 0, 1 or None')
+
+        i = sympify(i)
+        j = sympify(j)
+
+        if i not in self._comm_symbols2i:
+            n = len(self._comm)
+            self._comm.append({})
+            self._comm[n][0] = 0
+            self._comm[0][n] = 0
+            self._comm_symbols2i[i] = n
+            self._comm_i2symbol[n] = i
+        if j not in self._comm_symbols2i:
+            n = len(self._comm)
+            self._comm.append({})
+            self._comm[0][n] = 0
+            self._comm[n][0] = 0
+            self._comm_symbols2i[j] = n
+            self._comm_i2symbol[n] = j
+        ni = self._comm_symbols2i[i]
+        nj = self._comm_symbols2i[j]
+        self._comm[ni][nj] = c
+        self._comm[nj][ni] = c
+
+        """
+        Cached sympy functions (e.g. expand) may have cached the results of
+        expressions involving tensors, but those results may not be valid after
+        changing the commutation properties. To stay on the safe side, we clear
+        the cache of all functions.
+        """
+        clear_cache()
+
+    def set_comms(self, *args):
+        """
+        Set the commutation group numbers ``c`` for symbols ``i, j``.
+
+        Parameters
+        ==========
+
+        args : sequence of ``(i, j, c)``
+        """
+        for i, j, c in args:
+            self.set_comm(i, j, c)
+
+    def get_comm(self, i, j):
+        """
+        Return the commutation parameter for commutation group numbers ``i, j``
+
+        see ``_TensorManager.set_comm``
+        """
+        return self._comm[i].get(j, 0 if i == 0 or j == 0 else None)
+
+    def clear(self):
+        """
+        Clear the TensorManager.
+        """
+        self._comm_init()
+
+
+TensorManager = _TensorManager()
+
+
+class TensorIndexType(Basic):
+    """
+    A TensorIndexType is characterized by its name and its metric.
+
+    Parameters
+    ==========
+
+    name : name of the tensor type
+    dummy_name : name of the head of dummy indices
+    dim : dimension, it can be a symbol or an integer or ``None``
+    eps_dim : dimension of the epsilon tensor
+    metric_symmetry : integer that denotes metric symmetry or ``None`` for no metric
+    metric_name : string with the name of the metric tensor
+
+    Attributes
+    ==========
+
+    ``metric`` : the metric tensor
+    ``delta`` : ``Kronecker delta``
+    ``epsilon`` : the ``Levi-Civita epsilon`` tensor
+    ``data`` : (deprecated) a property to add ``ndarray`` values, to work in a specified basis.
+
+    Notes
+    =====
+
+    The possible values of the ``metric_symmetry`` parameter are:
+
+        ``1``   :   metric tensor is fully symmetric
+        ``0``   :   metric tensor possesses no index symmetry
+        ``-1``  :   metric tensor is fully antisymmetric
+        ``None``:   there is no metric tensor (metric equals to ``None``)
+
+    The metric is assumed to be symmetric by default. It can also be set
+    to a custom tensor by the ``.set_metric()`` method.
+
+    If there is a metric the metric is used to raise and lower indices.
+
+    In the case of non-symmetric metric, the following raising and
+    lowering conventions will be adopted:
+
+    ``psi(a) = g(a, b)*psi(-b); chi(-a) = chi(b)*g(-b, -a)``
+
+    From these it is easy to find:
+
+    ``g(-a, b) = delta(-a, b)``
+
+    where ``delta(-a, b) = delta(b, -a)`` is the ``Kronecker delta``
+    (see ``TensorIndex`` for the conventions on indices).
+    For antisymmetric metrics there is also the following equality:
+
+    ``g(a, -b) = -delta(a, -b)``
+
+    If there is no metric it is not possible to raise or lower indices;
+    e.g. the index of the defining representation of ``SU(N)``
+    is 'covariant' and the conjugate representation is
+    'contravariant'; for ``N > 2`` they are linearly independent.
+
+    ``eps_dim`` is by default equal to ``dim``, if the latter is an integer;
+    else it can be assigned (for use in naive dimensional regularization);
+    if ``eps_dim`` is not an integer ``epsilon`` is ``None``.
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.tensor import TensorIndexType
+    >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+    >>> Lorentz.metric
+    metric(Lorentz,Lorentz)
+    """
+
+    def __new__(cls, name, dummy_name=None, dim=None, eps_dim=None,
+                metric_symmetry=1, metric_name='metric', **kwargs):
+        if 'dummy_fmt' in kwargs:
+            dummy_fmt = kwargs['dummy_fmt']
+            sympy_deprecation_warning(
+                f"""
+                The dummy_fmt keyword to TensorIndexType is deprecated. Use
+                dummy_name={dummy_fmt} instead.
+                """,
+                deprecated_since_version="1.5",
+                active_deprecations_target="deprecated-tensorindextype-dummy-fmt",
+            )
+            dummy_name = dummy_fmt
+
+        if isinstance(name, str):
+            name = Symbol(name)
+
+        if dummy_name is None:
+            dummy_name = str(name)[0]
+        if isinstance(dummy_name, str):
+            dummy_name = Symbol(dummy_name)
+
+        if dim is None:
+            dim = Symbol("dim_" + dummy_name.name)
+        else:
+            dim = sympify(dim)
+
+        if eps_dim is None:
+            eps_dim = dim
+        else:
+            eps_dim = sympify(eps_dim)
+
+        metric_symmetry = sympify(metric_symmetry)
+
+        if isinstance(metric_name, str):
+            metric_name = Symbol(metric_name)
+
+        if 'metric' in kwargs:
+            SymPyDeprecationWarning(
+                """
+                The 'metric' keyword argument to TensorIndexType is
+                deprecated. Use the 'metric_symmetry' keyword argument or the
+                TensorIndexType.set_metric() method instead.
+                """,
+                deprecated_since_version="1.5",
+                active_deprecations_target="deprecated-tensorindextype-metric",
+            )
+            metric = kwargs.get('metric')
+            if metric is not None:
+                if metric in (True, False, 0, 1):
+                    metric_name = 'metric'
+                    #metric_antisym = metric
+                else:
+                    metric_name = metric.name
+                    #metric_antisym = metric.antisym
+
+                if metric:
+                    metric_symmetry = -1
+                else:
+                    metric_symmetry = 1
+
+        obj = Basic.__new__(cls, name, dummy_name, dim, eps_dim,
+                            metric_symmetry, metric_name)
+
+        obj._autogenerated = []
+        return obj
+
+    @property
+    def name(self):
+        return self.args[0].name
+
+    @property
+    def dummy_name(self):
+        return self.args[1].name
+
+    @property
+    def dim(self):
+        return self.args[2]
+
+    @property
+    def eps_dim(self):
+        return self.args[3]
+
+    @memoize_property
+    def metric(self):
+        metric_symmetry = self.args[4]
+        metric_name = self.args[5]
+        if metric_symmetry is None:
+            return None
+
+        if metric_symmetry == 0:
+            symmetry = TensorSymmetry.no_symmetry(2)
+        elif metric_symmetry == 1:
+            symmetry = TensorSymmetry.fully_symmetric(2)
+        elif metric_symmetry == -1:
+            symmetry = TensorSymmetry.fully_symmetric(-2)
+
+        return TensorHead(metric_name, [self]*2, symmetry)
+
+    @memoize_property
+    def delta(self):
+        return TensorHead('KD', [self]*2, TensorSymmetry.fully_symmetric(2))
+
+    @memoize_property
+    def epsilon(self):
+        if not isinstance(self.eps_dim, (SYMPY_INTS, Integer)):
+            return None
+        symmetry = TensorSymmetry.fully_symmetric(-self.eps_dim)
+        return TensorHead('Eps', [self]*self.eps_dim, symmetry)
+
+    def set_metric(self, tensor):
+        self._metric = tensor
+
+    def __lt__(self, other):
+        return self.name < other.name
+
+    def __str__(self):
+        return self.name
+
+    __repr__ = __str__
+
+    # Everything below this line is deprecated
+
+    @property
+    def data(self):
+        deprecate_data()
+        with ignore_warnings(SymPyDeprecationWarning):
+            return _tensor_data_substitution_dict[self]
+
+    @data.setter
+    def data(self, data):
+        deprecate_data()
+        # This assignment is a bit controversial, should metric components be assigned
+        # to the metric only or also to the TensorIndexType object? The advantage here
+        # is the ability to assign a 1D array and transform it to a 2D diagonal array.
+        from .array import MutableDenseNDimArray
+
+        data = _TensorDataLazyEvaluator.parse_data(data)
+        if data.rank() > 2:
+            raise ValueError("data have to be of rank 1 (diagonal metric) or 2.")
+        if data.rank() == 1:
+            if self.dim.is_number:
+                nda_dim = data.shape[0]
+                if nda_dim != self.dim:
+                    raise ValueError("Dimension mismatch")
+
+            dim = data.shape[0]
+            newndarray = MutableDenseNDimArray.zeros(dim, dim)
+            for i, val in enumerate(data):
+                newndarray[i, i] = val
+            data = newndarray
+        dim1, dim2 = data.shape
+        if dim1 != dim2:
+            raise ValueError("Non-square matrix tensor.")
+        if self.dim.is_number:
+            if self.dim != dim1:
+                raise ValueError("Dimension mismatch")
+        _tensor_data_substitution_dict[self] = data
+        _tensor_data_substitution_dict.add_metric_data(self.metric, data)
+        with ignore_warnings(SymPyDeprecationWarning):
+            delta = self.get_kronecker_delta()
+        i1 = TensorIndex('i1', self)
+        i2 = TensorIndex('i2', self)
+        with ignore_warnings(SymPyDeprecationWarning):
+            delta(i1, -i2).data = _TensorDataLazyEvaluator.parse_data(eye(dim1))
+
+    @data.deleter
+    def data(self):
+        deprecate_data()
+        with ignore_warnings(SymPyDeprecationWarning):
+            if self in _tensor_data_substitution_dict:
+                del _tensor_data_substitution_dict[self]
+            if self.metric in _tensor_data_substitution_dict:
+                del _tensor_data_substitution_dict[self.metric]
+
+    @deprecated(
+        """
+        The TensorIndexType.get_kronecker_delta() method is deprecated. Use
+        the TensorIndexType.delta attribute instead.
+        """,
+        deprecated_since_version="1.5",
+        active_deprecations_target="deprecated-tensorindextype-methods",
+    )
+    def get_kronecker_delta(self):
+        sym2 = TensorSymmetry(get_symmetric_group_sgs(2))
+        delta = TensorHead('KD', [self]*2, sym2)
+        return delta
+
+    @deprecated(
+        """
+        The TensorIndexType.get_epsilon() method is deprecated. Use
+        the TensorIndexType.epsilon attribute instead.
+        """,
+        deprecated_since_version="1.5",
+        active_deprecations_target="deprecated-tensorindextype-methods",
+    )
+    def get_epsilon(self):
+        if not isinstance(self._eps_dim, (SYMPY_INTS, Integer)):
+            return None
+        sym = TensorSymmetry(get_symmetric_group_sgs(self._eps_dim, 1))
+        epsilon = TensorHead('Eps', [self]*self._eps_dim, sym)
+        return epsilon
+
+    def _components_data_full_destroy(self):
+        """
+        EXPERIMENTAL: do not rely on this API method.
+
+        This destroys components data associated to the ``TensorIndexType``, if
+        any, specifically:
+
+        * metric tensor data
+        * Kronecker tensor data
+        """
+        if self in _tensor_data_substitution_dict:
+            del _tensor_data_substitution_dict[self]
+
+        def delete_tensmul_data(key):
+            if key in _tensor_data_substitution_dict._substitutions_dict_tensmul:
+                del _tensor_data_substitution_dict._substitutions_dict_tensmul[key]
+
+        # delete metric data:
+        delete_tensmul_data((self.metric, True, True))
+        delete_tensmul_data((self.metric, True, False))
+        delete_tensmul_data((self.metric, False, True))
+        delete_tensmul_data((self.metric, False, False))
+
+        # delete delta tensor data:
+        delta = self.get_kronecker_delta()
+        if delta in _tensor_data_substitution_dict:
+            del _tensor_data_substitution_dict[delta]
+
+
+class TensorIndex(Basic):
+    """
+    Represents a tensor index
+
+    Parameters
+    ==========
+
+    name : name of the index, or ``True`` if you want it to be automatically assigned
+    tensor_index_type : ``TensorIndexType`` of the index
+    is_up :  flag for contravariant index (is_up=True by default)
+
+    Attributes
+    ==========
+
+    ``name``
+    ``tensor_index_type``
+    ``is_up``
+
+    Notes
+    =====
+
+    Tensor indices are contracted with the Einstein summation convention.
+
+    An index can be in contravariant or in covariant form; in the latter
+    case it is represented prepending a ``-`` to the index name. Adding
+    ``-`` to a covariant (is_up=False) index makes it contravariant.
+
+    Dummy indices have a name with head given by
+    ``tensor_inde_type.dummy_name`` with underscore and a number.
+
+    Similar to ``symbols`` multiple contravariant indices can be created
+    at once using ``tensor_indices(s, typ)``, where ``s`` is a string
+    of names.
+
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.tensor import TensorIndexType, TensorIndex, TensorHead, tensor_indices
+    >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+    >>> mu = TensorIndex('mu', Lorentz, is_up=False)
+    >>> nu, rho = tensor_indices('nu, rho', Lorentz)
+    >>> A = TensorHead('A', [Lorentz, Lorentz])
+    >>> A(mu, nu)
+    A(-mu, nu)
+    >>> A(-mu, -rho)
+    A(mu, -rho)
+    >>> A(mu, -mu)
+    A(-L_0, L_0)
+    """
+    def __new__(cls, name, tensor_index_type, is_up=True):
+        if isinstance(name, str):
+            name_symbol = Symbol(name)
+        elif isinstance(name, Symbol):
+            name_symbol = name
+        elif name is True:
+            name = "_i{}".format(len(tensor_index_type._autogenerated))
+            name_symbol = Symbol(name)
+            tensor_index_type._autogenerated.append(name_symbol)
+        else:
+            raise ValueError("invalid name")
+
+        is_up = sympify(is_up)
+        return Basic.__new__(cls, name_symbol, tensor_index_type, is_up)
+
+    @property
+    def name(self):
+        return self.args[0].name
+
+    @property
+    def tensor_index_type(self):
+        return self.args[1]
+
+    @property
+    def is_up(self):
+        return self.args[2]
+
+    def _print(self):
+        s = self.name
+        if not self.is_up:
+            s = '-%s' % s
+        return s
+
+    def __lt__(self, other):
+        return ((self.tensor_index_type, self.name) <
+                (other.tensor_index_type, other.name))
+
+    def __neg__(self):
+        t1 = TensorIndex(self.name, self.tensor_index_type,
+                (not self.is_up))
+        return t1
+
+
+def tensor_indices(s, typ):
+    """
+    Returns list of tensor indices given their names and their types.
+
+    Parameters
+    ==========
+
+    s : string of comma separated names of indices
+
+    typ : ``TensorIndexType`` of the indices
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices
+    >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+    >>> a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
+    """
+    if isinstance(s, str):
+        a = [x.name for x in symbols(s, seq=True)]
+    else:
+        raise ValueError('expecting a string')
+
+    tilist = [TensorIndex(i, typ) for i in a]
+    if len(tilist) == 1:
+        return tilist[0]
+    return tilist
+
+
+class TensorSymmetry(Basic):
+    """
+    Monoterm symmetry of a tensor (i.e. any symmetric or anti-symmetric
+    index permutation). For the relevant terminology see ``tensor_can.py``
+    section of the combinatorics module.
+
+    Parameters
+    ==========
+
+    bsgs : tuple ``(base, sgs)`` BSGS of the symmetry of the tensor
+
+    Attributes
+    ==========
+
+    ``base`` : base of the BSGS
+    ``generators`` : generators of the BSGS
+    ``rank`` : rank of the tensor
+
+    Notes
+    =====
+
+    A tensor can have an arbitrary monoterm symmetry provided by its BSGS.
+    Multiterm symmetries, like the cyclic symmetry of the Riemann tensor
+    (i.e., Bianchi identity), are not covered. See combinatorics module for
+    information on how to generate BSGS for a general index permutation group.
+    Simple symmetries can be generated using built-in methods.
+
+    See Also
+    ========
+
+    sympy.combinatorics.tensor_can.get_symmetric_group_sgs
+
+    Examples
+    ========
+
+    Define a symmetric tensor of rank 2
+
+    >>> from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, TensorHead
+    >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+    >>> sym = TensorSymmetry(get_symmetric_group_sgs(2))
+    >>> T = TensorHead('T', [Lorentz]*2, sym)
+
+    Note, that the same can also be done using built-in TensorSymmetry methods
+
+    >>> sym2 = TensorSymmetry.fully_symmetric(2)
+    >>> sym == sym2
+    True
+    """
+    def __new__(cls, *args, **kw_args):
+        if len(args) == 1:
+            base, generators = args[0]
+        elif len(args) == 2:
+            base, generators = args
+        else:
+            raise TypeError("bsgs required, either two separate parameters or one tuple")
+
+        if not isinstance(base, Tuple):
+            base = Tuple(*base)
+        if not isinstance(generators, Tuple):
+            generators = Tuple(*generators)
+
+        return Basic.__new__(cls, base, generators, **kw_args)
+
+    @property
+    def base(self):
+        return self.args[0]
+
+    @property
+    def generators(self):
+        return self.args[1]
+
+    @property
+    def rank(self):
+        return self.generators[0].size - 2
+
+    @classmethod
+    def fully_symmetric(cls, rank):
+        """
+        Returns a fully symmetric (antisymmetric if ``rank``<0)
+        TensorSymmetry object for ``abs(rank)`` indices.
+        """
+        if rank > 0:
+            bsgs = get_symmetric_group_sgs(rank, False)
+        elif rank < 0:
+            bsgs = get_symmetric_group_sgs(-rank, True)
+        elif rank == 0:
+            bsgs = ([], [Permutation(1)])
+        return TensorSymmetry(bsgs)
+
+    @classmethod
+    def direct_product(cls, *args):
+        """
+        Returns a TensorSymmetry object that is being a direct product of
+        fully (anti-)symmetric index permutation groups.
+
+        Notes
+        =====
+
+        Some examples for different values of ``(*args)``:
+        ``(1)``         vector, equivalent to ``TensorSymmetry.fully_symmetric(1)``
+        ``(2)``         tensor with 2 symmetric indices, equivalent to ``.fully_symmetric(2)``
+        ``(-2)``        tensor with 2 antisymmetric indices, equivalent to ``.fully_symmetric(-2)``
+        ``(2, -2)``     tensor with the first 2 indices commuting and the last 2 anticommuting
+        ``(1, 1, 1)``   tensor with 3 indices without any symmetry
+        """
+        base, sgs = [], [Permutation(1)]
+        for arg in args:
+            if arg > 0:
+                bsgs2 = get_symmetric_group_sgs(arg, False)
+            elif arg < 0:
+                bsgs2 = get_symmetric_group_sgs(-arg, True)
+            else:
+                continue
+            base, sgs = bsgs_direct_product(base, sgs, *bsgs2)
+
+        return TensorSymmetry(base, sgs)
+
+    @classmethod
+    def riemann(cls):
+        """
+        Returns a monotorem symmetry of the Riemann tensor
+        """
+        return TensorSymmetry(riemann_bsgs)
+
+    @classmethod
+    def no_symmetry(cls, rank):
+        """
+        TensorSymmetry object for ``rank`` indices with no symmetry
+        """
+        return TensorSymmetry([], [Permutation(rank+1)])
+
+
+@deprecated(
+    """
+    The tensorsymmetry() function is deprecated. Use the TensorSymmetry
+    constructor instead.
+    """,
+    deprecated_since_version="1.5",
+    active_deprecations_target="deprecated-tensorsymmetry",
+)
+def tensorsymmetry(*args):
+    """
+    Returns a ``TensorSymmetry`` object. This method is deprecated, use
+    ``TensorSymmetry.direct_product()`` or ``.riemann()`` instead.
+
+    Explanation
+    ===========
+
+    One can represent a tensor with any monoterm slot symmetry group
+    using a BSGS.
+
+    ``args`` can be a BSGS
+    ``args[0]``    base
+    ``args[1]``    sgs
+
+    Usually tensors are in (direct products of) representations
+    of the symmetric group;
+    ``args`` can be a list of lists representing the shapes of Young tableaux
+
+    Notes
+    =====
+
+    For instance:
+    ``[[1]]``       vector
+    ``[[1]*n]``     symmetric tensor of rank ``n``
+    ``[[n]]``       antisymmetric tensor of rank ``n``
+    ``[[2, 2]]``    monoterm slot symmetry of the Riemann tensor
+    ``[[1],[1]]``   vector*vector
+    ``[[2],[1],[1]`` (antisymmetric tensor)*vector*vector
+
+    Notice that with the shape ``[2, 2]`` we associate only the monoterm
+    symmetries of the Riemann tensor; this is an abuse of notation,
+    since the shape ``[2, 2]`` corresponds usually to the irreducible
+    representation characterized by the monoterm symmetries and by the
+    cyclic symmetry.
+    """
+    from sympy.combinatorics import Permutation
+
+    def tableau2bsgs(a):
+        if len(a) == 1:
+            # antisymmetric vector
+            n = a[0]
+            bsgs = get_symmetric_group_sgs(n, 1)
+        else:
+            if all(x == 1 for x in a):
+                # symmetric vector
+                n = len(a)
+                bsgs = get_symmetric_group_sgs(n)
+            elif a == [2, 2]:
+                bsgs = riemann_bsgs
+            else:
+                raise NotImplementedError
+        return bsgs
+
+    if not args:
+        return TensorSymmetry(Tuple(), Tuple(Permutation(1)))
+
+    if len(args) == 2 and isinstance(args[1][0], Permutation):
+        return TensorSymmetry(args)
+    base, sgs = tableau2bsgs(args[0])
+    for a in args[1:]:
+        basex, sgsx = tableau2bsgs(a)
+        base, sgs = bsgs_direct_product(base, sgs, basex, sgsx)
+    return TensorSymmetry(Tuple(base, sgs))
+
+@deprecated(
+    "TensorType is deprecated. Use tensor_heads() instead.",
+    deprecated_since_version="1.5",
+    active_deprecations_target="deprecated-tensortype",
+)
+class TensorType(Basic):
+    """
+    Class of tensor types. Deprecated, use tensor_heads() instead.
+
+    Parameters
+    ==========
+
+    index_types : list of ``TensorIndexType`` of the tensor indices
+    symmetry : ``TensorSymmetry`` of the tensor
+
+    Attributes
+    ==========
+
+    ``index_types``
+    ``symmetry``
+    ``types`` : list of ``TensorIndexType`` without repetitions
+    """
+    is_commutative = False
+
+    def __new__(cls, index_types, symmetry, **kw_args):
+        assert symmetry.rank == len(index_types)
+        obj = Basic.__new__(cls, Tuple(*index_types), symmetry, **kw_args)
+        return obj
+
+    @property
+    def index_types(self):
+        return self.args[0]
+
+    @property
+    def symmetry(self):
+        return self.args[1]
+
+    @property
+    def types(self):
+        return sorted(set(self.index_types), key=lambda x: x.name)
+
+    def __str__(self):
+        return 'TensorType(%s)' % ([str(x) for x in self.index_types])
+
+    def __call__(self, s, comm=0):
+        """
+        Return a TensorHead object or a list of TensorHead objects.
+
+        Parameters
+        ==========
+
+        s : name or string of names.
+
+        comm : Commutation group.
+
+        see ``_TensorManager.set_comm``
+        """
+        if isinstance(s, str):
+            names = [x.name for x in symbols(s, seq=True)]
+        else:
+            raise ValueError('expecting a string')
+        if len(names) == 1:
+            return TensorHead(names[0], self.index_types, self.symmetry, comm)
+        else:
+            return [TensorHead(name, self.index_types, self.symmetry, comm) for name in names]
+
+
+@deprecated(
+    """
+    The tensorhead() function is deprecated. Use tensor_heads() instead.
+    """,
+    deprecated_since_version="1.5",
+    active_deprecations_target="deprecated-tensorhead",
+)
+def tensorhead(name, typ, sym=None, comm=0):
+    """
+    Function generating tensorhead(s). This method is deprecated,
+    use TensorHead constructor or tensor_heads() instead.
+
+    Parameters
+    ==========
+
+    name : name or sequence of names (as in ``symbols``)
+
+    typ :  index types
+
+    sym :  same as ``*args`` in ``tensorsymmetry``
+
+    comm : commutation group number
+    see ``_TensorManager.set_comm``
+    """
+    if sym is None:
+        sym = [[1] for i in range(len(typ))]
+    with ignore_warnings(SymPyDeprecationWarning):
+        sym = tensorsymmetry(*sym)
+    return TensorHead(name, typ, sym, comm)
+
+
+class TensorHead(Basic):
+    """
+    Tensor head of the tensor.
+
+    Parameters
+    ==========
+
+    name : name of the tensor
+    index_types : list of TensorIndexType
+    symmetry : TensorSymmetry of the tensor
+    comm : commutation group number
+
+    Attributes
+    ==========
+
+    ``name``
+    ``index_types``
+    ``rank`` : total number of indices
+    ``symmetry``
+    ``comm`` : commutation group
+
+    Notes
+    =====
+
+    Similar to ``symbols`` multiple TensorHeads can be created using
+    ``tensorhead(s, typ, sym=None, comm=0)`` function, where ``s``
+    is the string of names and ``sym`` is the monoterm tensor symmetry
+    (see ``tensorsymmetry``).
+
+    A ``TensorHead`` belongs to a commutation group, defined by a
+    symbol on number ``comm`` (see ``_TensorManager.set_comm``);
+    tensors in a commutation group have the same commutation properties;
+    by default ``comm`` is ``0``, the group of the commuting tensors.
+
+    Examples
+    ========
+
+    Define a fully antisymmetric tensor of rank 2:
+
+    >>> from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorSymmetry
+    >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+    >>> asym2 = TensorSymmetry.fully_symmetric(-2)
+    >>> A = TensorHead('A', [Lorentz, Lorentz], asym2)
+
+    Examples with ndarray values, the components data assigned to the
+    ``TensorHead`` object are assumed to be in a fully-contravariant
+    representation. In case it is necessary to assign components data which
+    represents the values of a non-fully covariant tensor, see the other
+    examples.
+
+    >>> from sympy.tensor.tensor import tensor_indices
+    >>> from sympy import diag
+    >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+    >>> i0, i1 = tensor_indices('i0:2', Lorentz)
+
+    Specify a replacement dictionary to keep track of the arrays to use for
+    replacements in the tensorial expression. The ``TensorIndexType`` is
+    associated to the metric used for contractions (in fully covariant form):
+
+    >>> repl = {Lorentz: diag(1, -1, -1, -1)}
+
+    Let's see some examples of working with components with the electromagnetic
+    tensor:
+
+    >>> from sympy import symbols
+    >>> Ex, Ey, Ez, Bx, By, Bz = symbols('E_x E_y E_z B_x B_y B_z')
+    >>> c = symbols('c', positive=True)
+
+    Let's define `F`, an antisymmetric tensor:
+
+    >>> F = TensorHead('F', [Lorentz, Lorentz], asym2)
+
+    Let's update the dictionary to contain the matrix to use in the
+    replacements:
+
+    >>> repl.update({F(-i0, -i1): [
+    ... [0, Ex/c, Ey/c, Ez/c],
+    ... [-Ex/c, 0, -Bz, By],
+    ... [-Ey/c, Bz, 0, -Bx],
+    ... [-Ez/c, -By, Bx, 0]]})
+
+    Now it is possible to retrieve the contravariant form of the Electromagnetic
+    tensor:
+
+    >>> F(i0, i1).replace_with_arrays(repl, [i0, i1])
+    [[0, -E_x/c, -E_y/c, -E_z/c], [E_x/c, 0, -B_z, B_y], [E_y/c, B_z, 0, -B_x], [E_z/c, -B_y, B_x, 0]]
+
+    and the mixed contravariant-covariant form:
+
+    >>> F(i0, -i1).replace_with_arrays(repl, [i0, -i1])
+    [[0, E_x/c, E_y/c, E_z/c], [E_x/c, 0, B_z, -B_y], [E_y/c, -B_z, 0, B_x], [E_z/c, B_y, -B_x, 0]]
+
+    Energy-momentum of a particle may be represented as:
+
+    >>> from sympy import symbols
+    >>> P = TensorHead('P', [Lorentz], TensorSymmetry.no_symmetry(1))
+    >>> E, px, py, pz = symbols('E p_x p_y p_z', positive=True)
+    >>> repl.update({P(i0): [E, px, py, pz]})
+
+    The contravariant and covariant components are, respectively:
+
+    >>> P(i0).replace_with_arrays(repl, [i0])
+    [E, p_x, p_y, p_z]
+    >>> P(-i0).replace_with_arrays(repl, [-i0])
+    [E, -p_x, -p_y, -p_z]
+
+    The contraction of a 1-index tensor by itself:
+
+    >>> expr = P(i0)*P(-i0)
+    >>> expr.replace_with_arrays(repl, [])
+    E**2 - p_x**2 - p_y**2 - p_z**2
+    """
+    is_commutative = False
+
+    def __new__(cls, name, index_types, symmetry=None, comm=0):
+        if isinstance(name, str):
+            name_symbol = Symbol(name)
+        elif isinstance(name, Symbol):
+            name_symbol = name
+        else:
+            raise ValueError("invalid name")
+
+        if symmetry is None:
+            symmetry = TensorSymmetry.no_symmetry(len(index_types))
+        else:
+            assert symmetry.rank == len(index_types)
+
+        obj = Basic.__new__(cls, name_symbol, Tuple(*index_types), symmetry, sympify(comm))
+        return obj
+
+    @property
+    def name(self):
+        return self.args[0].name
+
+    @property
+    def index_types(self):
+        return list(self.args[1])
+
+    @property
+    def symmetry(self):
+        return self.args[2]
+
+    @property
+    def comm(self):
+        return TensorManager.comm_symbols2i(self.args[3])
+
+    @property
+    def rank(self):
+        return len(self.index_types)
+
+    def __lt__(self, other):
+        return (self.name, self.index_types) < (other.name, other.index_types)
+
+    def commutes_with(self, other):
+        """
+        Returns ``0`` if ``self`` and ``other`` commute, ``1`` if they anticommute.
+
+        Returns ``None`` if ``self`` and ``other`` neither commute nor anticommute.
+        """
+        r = TensorManager.get_comm(self.comm, other.comm)
+        return r
+
+    def _print(self):
+        return '%s(%s)' %(self.name, ','.join([str(x) for x in self.index_types]))
+
+    def __call__(self, *indices, **kw_args):
+        """
+        Returns a tensor with indices.
+
+        Explanation
+        ===========
+
+        There is a special behavior in case of indices denoted by ``True``,
+        they are considered auto-matrix indices, their slots are automatically
+        filled, and confer to the tensor the behavior of a matrix or vector
+        upon multiplication with another tensor containing auto-matrix indices
+        of the same ``TensorIndexType``. This means indices get summed over the
+        same way as in matrix multiplication. For matrix behavior, define two
+        auto-matrix indices, for vector behavior define just one.
+
+        Indices can also be strings, in which case the attribute
+        ``index_types`` is used to convert them to proper ``TensorIndex``.
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorSymmetry, TensorHead
+        >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+        >>> a, b = tensor_indices('a,b', Lorentz)
+        >>> A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
+        >>> t = A(a, -b)
+        >>> t
+        A(a, -b)
+
+        """
+
+        updated_indices = []
+        for idx, typ in zip(indices, self.index_types):
+            if isinstance(idx, str):
+                idx = idx.strip().replace(" ", "")
+                if idx.startswith('-'):
+                    updated_indices.append(TensorIndex(idx[1:], typ,
+                                           is_up=False))
+                else:
+                    updated_indices.append(TensorIndex(idx, typ))
+            else:
+                updated_indices.append(idx)
+
+        updated_indices += indices[len(updated_indices):]
+
+        tensor = Tensor(self, updated_indices, **kw_args)
+        return tensor.doit()
+
+    # Everything below this line is deprecated
+
+    def __pow__(self, other):
+        deprecate_data()
+        with ignore_warnings(SymPyDeprecationWarning):
+            if self.data is None:
+                raise ValueError("No power on abstract tensors.")
+            from .array import tensorproduct, tensorcontraction
+            metrics = [_.data for _ in self.index_types]
+
+            marray = self.data
+            marraydim = marray.rank()
+            for metric in metrics:
+                marray = tensorproduct(marray, metric, marray)
+                marray = tensorcontraction(marray, (0, marraydim), (marraydim+1, marraydim+2))
+
+            return marray ** (other * S.Half)
+
+    @property
+    def data(self):
+        deprecate_data()
+        with ignore_warnings(SymPyDeprecationWarning):
+            return _tensor_data_substitution_dict[self]
+
+    @data.setter
+    def data(self, data):
+        deprecate_data()
+        with ignore_warnings(SymPyDeprecationWarning):
+            _tensor_data_substitution_dict[self] = data
+
+    @data.deleter
+    def data(self):
+        deprecate_data()
+        if self in _tensor_data_substitution_dict:
+            del _tensor_data_substitution_dict[self]
+
+    def __iter__(self):
+        deprecate_data()
+        with ignore_warnings(SymPyDeprecationWarning):
+            return self.data.__iter__()
+
+    def _components_data_full_destroy(self):
+        """
+        EXPERIMENTAL: do not rely on this API method.
+
+        Destroy components data associated to the ``TensorHead`` object, this
+        checks for attached components data, and destroys components data too.
+        """
+        # do not garbage collect Kronecker tensor (it should be done by
+        # ``TensorIndexType`` garbage collection)
+        deprecate_data()
+        if self.name == "KD":
+            return
+
+        # the data attached to a tensor must be deleted only by the TensorHead
+        # destructor. If the TensorHead is deleted, it means that there are no
+        # more instances of that tensor anywhere.
+        if self in _tensor_data_substitution_dict:
+            del _tensor_data_substitution_dict[self]
+
+
+def tensor_heads(s, index_types, symmetry=None, comm=0):
+    """
+    Returns a sequence of TensorHeads from a string `s`
+    """
+    if isinstance(s, str):
+        names = [x.name for x in symbols(s, seq=True)]
+    else:
+        raise ValueError('expecting a string')
+
+    thlist = [TensorHead(name, index_types, symmetry, comm) for name in names]
+    if len(thlist) == 1:
+        return thlist[0]
+    return thlist
+
+
+class TensExpr(Expr, ABC):
+    """
+    Abstract base class for tensor expressions
+
+    Notes
+    =====
+
+    A tensor expression is an expression formed by tensors;
+    currently the sums of tensors are distributed.
+
+    A ``TensExpr`` can be a ``TensAdd`` or a ``TensMul``.
+
+    ``TensMul`` objects are formed by products of component tensors,
+    and include a coefficient, which is a SymPy expression.
+
+
+    In the internal representation contracted indices are represented
+    by ``(ipos1, ipos2, icomp1, icomp2)``, where ``icomp1`` is the position
+    of the component tensor with contravariant index, ``ipos1`` is the
+    slot which the index occupies in that component tensor.
+
+    Contracted indices are therefore nameless in the internal representation.
+    """
+
+    _op_priority = 12.0
+    is_commutative = False
+
+    def __neg__(self):
+        return self*S.NegativeOne
+
+    def __abs__(self):
+        raise NotImplementedError
+
+    def __add__(self, other):
+        return TensAdd(self, other).doit(deep=False)
+
+    def __radd__(self, other):
+        return TensAdd(other, self).doit(deep=False)
+
+    def __sub__(self, other):
+        return TensAdd(self, -other).doit(deep=False)
+
+    def __rsub__(self, other):
+        return TensAdd(other, -self).doit(deep=False)
+
+    def __mul__(self, other):
+        """
+        Multiply two tensors using Einstein summation convention.
+
+        Explanation
+        ===========
+
+        If the two tensors have an index in common, one contravariant
+        and the other covariant, in their product the indices are summed
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads
+        >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+        >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz)
+        >>> g = Lorentz.metric
+        >>> p, q = tensor_heads('p,q', [Lorentz])
+        >>> t1 = p(m0)
+        >>> t2 = q(-m0)
+        >>> t1*t2
+        p(L_0)*q(-L_0)
+        """
+        return TensMul(self, other).doit(deep=False)
+
+    def __rmul__(self, other):
+        return TensMul(other, self).doit(deep=False)
+
+    def __truediv__(self, other):
+        other = _sympify(other)
+        if isinstance(other, TensExpr):
+            raise ValueError('cannot divide by a tensor')
+        return TensMul(self, S.One/other).doit(deep=False)
+
+    def __rtruediv__(self, other):
+        raise ValueError('cannot divide by a tensor')
+
+    def __pow__(self, other):
+        deprecate_data()
+        with ignore_warnings(SymPyDeprecationWarning):
+            if self.data is None:
+                raise ValueError("No power without ndarray data.")
+            from .array import tensorproduct, tensorcontraction
+            free = self.free
+            marray = self.data
+            mdim = marray.rank()
+            for metric in free:
+                marray = tensorcontraction(
+                    tensorproduct(
+                    marray,
+                    metric[0].tensor_index_type.data,
+                    marray),
+                    (0, mdim), (mdim+1, mdim+2)
+                )
+            return marray ** (other * S.Half)
+
+    def __rpow__(self, other):
+        raise NotImplementedError
+
+    @property
+    @abstractmethod
+    def nocoeff(self):
+        raise NotImplementedError("abstract method")
+
+    @property
+    @abstractmethod
+    def coeff(self):
+        raise NotImplementedError("abstract method")
+
+    @abstractmethod
+    def get_indices(self):
+        raise NotImplementedError("abstract method")
+
+    @abstractmethod
+    def get_free_indices(self) -> list[TensorIndex]:
+        raise NotImplementedError("abstract method")
+
+    @abstractmethod
+    def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr:
+        raise NotImplementedError("abstract method")
+
+    def fun_eval(self, *index_tuples):
+        deprecate_fun_eval()
+        return self.substitute_indices(*index_tuples)
+
+    def get_matrix(self):
+        """
+        DEPRECATED: do not use.
+
+        Returns ndarray components data as a matrix, if components data are
+        available and ndarray dimension does not exceed 2.
+        """
+        from sympy.matrices.dense import Matrix
+        deprecate_data()
+        with ignore_warnings(SymPyDeprecationWarning):
+            if 0 < self.rank <= 2:
+                rows = self.data.shape[0]
+                columns = self.data.shape[1] if self.rank == 2 else 1
+                if self.rank == 2:
+                    mat_list = [] * rows
+                    for i in range(rows):
+                        mat_list.append([])
+                        for j in range(columns):
+                            mat_list[i].append(self[i, j])
+                else:
+                    mat_list = [None] * rows
+                    for i in range(rows):
+                        mat_list[i] = self[i]
+                return Matrix(mat_list)
+            else:
+                raise NotImplementedError(
+                    "missing multidimensional reduction to matrix.")
+
+    @staticmethod
+    def _get_indices_permutation(indices1, indices2):
+        return [indices1.index(i) for i in indices2]
+
+    def _get_free_indices_set(self):
+        indset = set()
+        for arg in self.args:
+            if isinstance(arg, TensExpr):
+                indset.update(arg._get_free_indices_set())
+        return indset
+
+    def _get_dummy_indices_set(self):
+        indset = set()
+        for arg in self.args:
+            if isinstance(arg, TensExpr):
+                indset.update(arg._get_dummy_indices_set())
+        return indset
+
+    def _get_indices_set(self):
+        indset = set()
+        for arg in self.args:
+            if isinstance(arg, TensExpr):
+                indset.update(arg._get_indices_set())
+        return indset
+
+    @property
+    def _iterate_dummy_indices(self):
+        dummy_set = self._get_dummy_indices_set()
+
+        def recursor(expr, pos):
+            if isinstance(expr, TensorIndex):
+                if expr in dummy_set:
+                    yield (expr, pos)
+            elif isinstance(expr, (Tuple, TensExpr)):
+                for p, arg in enumerate(expr.args):
+                    yield from recursor(arg, pos+(p,))
+
+        return recursor(self, ())
+
+    @property
+    def _iterate_free_indices(self):
+        free_set = self._get_free_indices_set()
+
+        def recursor(expr, pos):
+            if isinstance(expr, TensorIndex):
+                if expr in free_set:
+                    yield (expr, pos)
+            elif isinstance(expr, (Tuple, TensExpr)):
+                for p, arg in enumerate(expr.args):
+                    yield from recursor(arg, pos+(p,))
+
+        return recursor(self, ())
+
+    @property
+    def _iterate_indices(self):
+        def recursor(expr, pos):
+            if isinstance(expr, TensorIndex):
+                yield (expr, pos)
+            elif isinstance(expr, (Tuple, TensExpr)):
+                for p, arg in enumerate(expr.args):
+                    yield from recursor(arg, pos+(p,))
+
+        return recursor(self, ())
+
+    @staticmethod
+    def _contract_and_permute_with_metric(metric, array, pos, dim):
+        # TODO: add possibility of metric after (spinors)
+        from .array import tensorcontraction, tensorproduct, permutedims
+
+        array = tensorcontraction(tensorproduct(metric, array), (1, 2+pos))
+        permu = list(range(dim))
+        permu[0], permu[pos] = permu[pos], permu[0]
+        return permutedims(array, permu)
+
+    @staticmethod
+    def _match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict):
+        from .array import permutedims
+
+        index_types1 = [i.tensor_index_type for i in free_ind1]
+
+        # Check if variance of indices needs to be fixed:
+        pos2up = []
+        pos2down = []
+        free2remaining = free_ind2[:]
+        for pos1, index1 in enumerate(free_ind1):
+            if index1 in free2remaining:
+                pos2 = free2remaining.index(index1)
+                free2remaining[pos2] = None
+                continue
+            if -index1 in free2remaining:
+                pos2 = free2remaining.index(-index1)
+                free2remaining[pos2] = None
+                free_ind2[pos2] = index1
+                if index1.is_up:
+                    pos2up.append(pos2)
+                else:
+                    pos2down.append(pos2)
+            else:
+                index2 = free2remaining[pos1]
+                if index2 is None:
+                    raise ValueError("incompatible indices: %s and %s" % (free_ind1, free_ind2))
+                free2remaining[pos1] = None
+                free_ind2[pos1] = index1
+                if index1.is_up ^ index2.is_up:
+                    if index1.is_up:
+                        pos2up.append(pos1)
+                    else:
+                        pos2down.append(pos1)
+
+        if len(set(free_ind1) & set(free_ind2)) < len(free_ind1):
+            raise ValueError("incompatible indices: %s and %s" % (free_ind1, free_ind2))
+
+        # Raise indices:
+        for pos in pos2up:
+            index_type_pos = index_types1[pos]
+            if index_type_pos not in replacement_dict:
+                raise ValueError("No metric provided to lower index")
+            metric = replacement_dict[index_type_pos]
+            metric_inverse = _TensorDataLazyEvaluator.inverse_matrix(metric)
+            array = TensExpr._contract_and_permute_with_metric(metric_inverse, array, pos, len(free_ind1))
+        # Lower indices:
+        for pos in pos2down:
+            index_type_pos = index_types1[pos]
+            if index_type_pos not in replacement_dict:
+                raise ValueError("No metric provided to lower index")
+            metric = replacement_dict[index_type_pos]
+            array = TensExpr._contract_and_permute_with_metric(metric, array, pos, len(free_ind1))
+
+        if free_ind1:
+            permutation = TensExpr._get_indices_permutation(free_ind2, free_ind1)
+            array = permutedims(array, permutation)
+
+        if hasattr(array, "rank") and array.rank() == 0:
+            array = array[()]
+
+        return free_ind2, array
+
+    def replace_with_arrays(self, replacement_dict, indices=None):
+        """
+        Replace the tensorial expressions with arrays. The final array will
+        correspond to the N-dimensional array with indices arranged according
+        to ``indices``.
+
+        Parameters
+        ==========
+
+        replacement_dict
+            dictionary containing the replacement rules for tensors.
+        indices
+            the index order with respect to which the array is read. The
+            original index order will be used if no value is passed.
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices
+        >>> from sympy.tensor.tensor import TensorHead
+        >>> from sympy import symbols, diag
+
+        >>> L = TensorIndexType("L")
+        >>> i, j = tensor_indices("i j", L)
+        >>> A = TensorHead("A", [L])
+        >>> A(i).replace_with_arrays({A(i): [1, 2]}, [i])
+        [1, 2]
+
+        Since 'indices' is optional, we can also call replace_with_arrays by
+        this way if no specific index order is needed:
+
+        >>> A(i).replace_with_arrays({A(i): [1, 2]})
+        [1, 2]
+
+        >>> expr = A(i)*A(j)
+        >>> expr.replace_with_arrays({A(i): [1, 2]})
+        [[1, 2], [2, 4]]
+
+        For contractions, specify the metric of the ``TensorIndexType``, which
+        in this case is ``L``, in its covariant form:
+
+        >>> expr = A(i)*A(-i)
+        >>> expr.replace_with_arrays({A(i): [1, 2], L: diag(1, -1)})
+        -3
+
+        Symmetrization of an array:
+
+        >>> H = TensorHead("H", [L, L])
+        >>> a, b, c, d = symbols("a b c d")
+        >>> expr = H(i, j)/2 + H(j, i)/2
+        >>> expr.replace_with_arrays({H(i, j): [[a, b], [c, d]]})
+        [[a, b/2 + c/2], [b/2 + c/2, d]]
+
+        Anti-symmetrization of an array:
+
+        >>> expr = H(i, j)/2 - H(j, i)/2
+        >>> repl = {H(i, j): [[a, b], [c, d]]}
+        >>> expr.replace_with_arrays(repl)
+        [[0, b/2 - c/2], [-b/2 + c/2, 0]]
+
+        The same expression can be read as the transpose by inverting ``i`` and
+        ``j``:
+
+        >>> expr.replace_with_arrays(repl, [j, i])
+        [[0, -b/2 + c/2], [b/2 - c/2, 0]]
+        """
+        from .array import Array
+
+        indices = indices or []
+        remap = {k.args[0] if k.is_up else -k.args[0]: k for k in self.get_free_indices()}
+        for i, index in enumerate(indices):
+            if isinstance(index, (Symbol, Mul)):
+                if index in remap:
+                    indices[i] = remap[index]
+                else:
+                    indices[i] = -remap[-index]
+
+        replacement_dict = {tensor: Array(array) for tensor, array in replacement_dict.items()}
+
+        # Check dimensions of replaced arrays:
+        for tensor, array in replacement_dict.items():
+            if isinstance(tensor, TensorIndexType):
+                expected_shape = [tensor.dim for i in range(2)]
+            else:
+                expected_shape = [index_type.dim for index_type in tensor.index_types]
+            if len(expected_shape) != array.rank() or (not all(dim1 == dim2 if
+                dim1.is_number else True for dim1, dim2 in zip(expected_shape,
+                array.shape))):
+                raise ValueError("shapes for tensor %s expected to be %s, "\
+                    "replacement array shape is %s" % (tensor, expected_shape,
+                    array.shape))
+
+        ret_indices, array = self._extract_data(replacement_dict)
+
+        last_indices, array = self._match_indices_with_other_tensor(array, indices, ret_indices, replacement_dict)
+        return array
+
+    def _check_add_Sum(self, expr, index_symbols):
+        from sympy.concrete.summations import Sum
+        indices = self.get_indices()
+        dum = self.dum
+        sum_indices = [ (index_symbols[i], 0,
+            indices[i].tensor_index_type.dim-1) for i, j in dum]
+        if sum_indices:
+            expr = Sum(expr, *sum_indices)
+        return expr
+
+    def _expand_partial_derivative(self):
+        # simply delegate the _expand_partial_derivative() to
+        # its arguments to expand a possibly found PartialDerivative
+        return self.func(*[
+                    a._expand_partial_derivative()
+                    if isinstance(a, TensExpr) else a
+                    for a in self.args])
+
+    def _matches_simple(self, expr, repl_dict=None, old=False):
+        """
+        Matches assuming there are no wild objects in self.
+        """
+        if repl_dict is None:
+            repl_dict = {}
+        else:
+            repl_dict = repl_dict.copy()
+
+        if not isinstance(expr, TensExpr):
+            if len(self.get_free_indices()) > 0:
+                #self has indices, but expr does not.
+                return None
+        elif set(self.get_free_indices()) != set(expr.get_free_indices()):
+                #If there are no wilds and the free indices are not the same, they cannot match.
+                return None
+
+        if canon_bp(self - expr) == S.Zero:
+            return repl_dict
+        else:
+            return None
+
+
+class TensAdd(TensExpr, AssocOp):
+    """
+    Sum of tensors.
+
+    Parameters
+    ==========
+
+    free_args : list of the free indices
+
+    Attributes
+    ==========
+
+    ``args`` : tuple of addends
+    ``rank`` : rank of the tensor
+    ``free_args`` : list of the free indices in sorted order
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.tensor import TensorIndexType, tensor_heads, tensor_indices
+    >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+    >>> a, b = tensor_indices('a,b', Lorentz)
+    >>> p, q = tensor_heads('p,q', [Lorentz])
+    >>> t = p(a) + q(a); t
+    p(a) + q(a)
+
+    Examples with components data added to the tensor expression:
+
+    >>> from sympy import symbols, diag
+    >>> x, y, z, t = symbols("x y z t")
+    >>> repl = {}
+    >>> repl[Lorentz] = diag(1, -1, -1, -1)
+    >>> repl[p(a)] = [1, 2, 3, 4]
+    >>> repl[q(a)] = [x, y, z, t]
+
+    The following are: 2**2 - 3**2 - 2**2 - 7**2 ==> -58
+
+    >>> expr = p(a) + q(a)
+    >>> expr.replace_with_arrays(repl, [a])
+    [x + 1, y + 2, z + 3, t + 4]
+    """
+
+    def __new__(cls, *args, **kw_args):
+        args = [_sympify(x) for x in args if x]
+        args = TensAdd._tensAdd_flatten(args)
+        args.sort(key=default_sort_key)
+        if not args:
+            return S.Zero
+        if len(args) == 1:
+            return args[0]
+
+        return Basic.__new__(cls, *args, **kw_args)
+
+    @property
+    def coeff(self):
+        return S.One
+
+    @property
+    def nocoeff(self):
+        return self
+
+    def get_free_indices(self) -> list[TensorIndex]:
+        return self.free_indices
+
+    def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr:
+        newargs = [arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg for arg in self.args]
+        return self.func(*newargs)
+
+    @memoize_property
+    def rank(self):
+        if isinstance(self.args[0], TensExpr):
+            return self.args[0].rank
+        else:
+            return 0
+
+    @memoize_property
+    def free_args(self):
+        if isinstance(self.args[0], TensExpr):
+            return self.args[0].free_args
+        else:
+            return []
+
+    @memoize_property
+    def free_indices(self):
+        if isinstance(self.args[0], TensExpr):
+            return self.args[0].get_free_indices()
+        else:
+            return set()
+
+    def doit(self, **hints) -> Expr:
+        deep = hints.get('deep', True)
+        if deep:
+            args = [arg.doit(**hints) for arg in self.args]
+        else:
+            args = self.args # type: ignore
+
+        # if any of the args are zero (after doit), drop them. Otherwise, _tensAdd_check will complain about non-matching indices, even though the TensAdd is correctly formed.
+        args = [arg for arg in args if arg != S.Zero]
+
+        if len(args) == 0:
+            return S.Zero
+        elif len(args) == 1:
+            return args[0]
+
+        # now check that all addends have the same indices:
+        TensAdd._tensAdd_check(args)
+
+        # Collect terms appearing more than once, differing by their coefficients:
+        args = TensAdd._tensAdd_collect_terms(args)
+
+        # collect canonicalized terms
+        def sort_key(t):
+            if not isinstance(t, TensExpr):
+                return [], [], []
+            if hasattr(t, "_index_structure") and hasattr(t, "components"):
+                x = get_index_structure(t)
+                return t.components, x.free, x.dum
+            return [], [], []
+        args.sort(key=sort_key)
+
+        if not args:
+            return S.Zero
+        # it there is only a component tensor return it
+        if len(args) == 1:
+            return args[0]
+
+        obj = self.func(*args)
+        return obj
+
+    @staticmethod
+    def _tensAdd_flatten(args):
+        # flatten TensAdd, coerce terms which are not tensors to tensors
+        a = []
+        for x in args:
+            if isinstance(x, (Add, TensAdd)):
+                a.extend(list(x.args))
+            else:
+                a.append(x)
+        args = [x for x in a if x.coeff]
+        return args
+
+    @staticmethod
+    def _tensAdd_check(args):
+        # check that all addends have the same free indices
+
+        def get_indices_set(x: Expr) -> set[TensorIndex]:
+            if isinstance(x, TensExpr):
+                return set(x.get_free_indices())
+            return set()
+
+        indices0 = get_indices_set(args[0])
+        list_indices = [get_indices_set(arg) for arg in args[1:]]
+        if not all(x == indices0 for x in list_indices):
+            raise ValueError('all tensors must have the same indices')
+
+    @staticmethod
+    def _tensAdd_collect_terms(args):
+        # collect TensMul terms differing at most by their coefficient
+        terms_dict = defaultdict(list)
+        scalars = S.Zero
+        if isinstance(args[0], TensExpr):
+            free_indices = set(args[0].get_free_indices())
+        else:
+            free_indices = set()
+
+        for arg in args:
+            if not isinstance(arg, TensExpr):
+                if free_indices != set():
+                    raise ValueError("wrong valence")
+                scalars += arg
+                continue
+            if free_indices != set(arg.get_free_indices()):
+                raise ValueError("wrong valence")
+            # TODO: what is the part which is not a coeff?
+            # needs an implementation similar to .as_coeff_Mul()
+            terms_dict[arg.nocoeff].append(arg.coeff)
+
+        new_args = [TensMul(Add(*coeff), t).doit(deep=False) for t, coeff in terms_dict.items() if Add(*coeff) != 0]
+        if isinstance(scalars, Add):
+            new_args = list(scalars.args) + new_args
+        elif scalars != 0:
+            new_args = [scalars] + new_args
+        return new_args
+
+    def get_indices(self):
+        indices = []
+        for arg in self.args:
+            indices.extend([i for i in get_indices(arg) if i not in indices])
+        return indices
+
+
+    def __call__(self, *indices):
+        deprecate_call()
+        free_args = self.free_args
+        indices = list(indices)
+        if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]:
+            raise ValueError('incompatible types')
+        if indices == free_args:
+            return self
+        index_tuples = list(zip(free_args, indices))
+        a = [x.func(*x.substitute_indices(*index_tuples).args) for x in self.args]
+        res = TensAdd(*a).doit(deep=False)
+        return res
+
+    def canon_bp(self):
+        """
+        Canonicalize using the Butler-Portugal algorithm for canonicalization
+        under monoterm symmetries.
+        """
+        expr = self.expand()
+        if isinstance(expr, self.func):
+            args = [canon_bp(x) for x in expr.args]
+            res = TensAdd(*args).doit(deep=False)
+            return res
+        else:
+            return canon_bp(expr)
+
+    def equals(self, other):
+        other = _sympify(other)
+        if isinstance(other, TensMul) and other.coeff == 0:
+            return all(x.coeff == 0 for x in self.args)
+        if isinstance(other, TensExpr):
+            if self.rank != other.rank:
+                return False
+        if isinstance(other, TensAdd):
+            if set(self.args) != set(other.args):
+                return False
+            else:
+                return True
+        t = self - other
+        if not isinstance(t, TensExpr):
+            return t == 0
+        else:
+            if isinstance(t, TensMul):
+                return t.coeff == 0
+            else:
+                return all(x.coeff == 0 for x in t.args)
+
+    def __getitem__(self, item):
+        deprecate_data()
+        with ignore_warnings(SymPyDeprecationWarning):
+            return self.data[item]
+
+    def contract_delta(self, delta):
+        args = [x.contract_delta(delta) if isinstance(x, TensExpr) else x for x in self.args]
+        t = TensAdd(*args).doit(deep=False)
+        return canon_bp(t)
+
+    def contract_metric(self, g):
+        """
+        Raise or lower indices with the metric ``g``.
+
+        Parameters
+        ==========
+
+        g :  metric
+
+        contract_all : if True, eliminate all ``g`` which are contracted
+
+        Notes
+        =====
+
+        see the ``TensorIndexType`` docstring for the contraction conventions
+        """
+
+        args = [contract_metric(x, g) for x in self.args]
+        t = TensAdd(*args).doit(deep=False)
+        return canon_bp(t)
+
+    def substitute_indices(self, *index_tuples):
+        new_args = []
+        for arg in self.args:
+            if isinstance(arg, TensExpr):
+                arg = arg.substitute_indices(*index_tuples)
+            new_args.append(arg)
+        return TensAdd(*new_args).doit(deep=False)
+
+    def _print(self):
+        a = []
+        args = self.args
+        for x in args:
+            a.append(str(x))
+        s = ' + '.join(a)
+        s = s.replace('+ -', '- ')
+        return s
+
+    def _extract_data(self, replacement_dict):
+        from sympy.tensor.array import Array, permutedims
+        args_indices, arrays = zip(*[
+            arg._extract_data(replacement_dict) if
+            isinstance(arg, TensExpr) else ([], arg) for arg in self.args
+        ])
+        arrays = [Array(i) for i in arrays]
+        ref_indices = args_indices[0]
+        for i in range(1, len(args_indices)):
+            indices = args_indices[i]
+            array = arrays[i]
+            permutation = TensMul._get_indices_permutation(indices, ref_indices)
+            arrays[i] = permutedims(array, permutation)
+        return ref_indices, sum(arrays, Array.zeros(*array.shape))
+
+    @property
+    def data(self):
+        deprecate_data()
+        with ignore_warnings(SymPyDeprecationWarning):
+            return _tensor_data_substitution_dict[self.expand()]
+
+    @data.setter
+    def data(self, data):
+        deprecate_data()
+        with ignore_warnings(SymPyDeprecationWarning):
+            _tensor_data_substitution_dict[self] = data
+
+    @data.deleter
+    def data(self):
+        deprecate_data()
+        with ignore_warnings(SymPyDeprecationWarning):
+            if self in _tensor_data_substitution_dict:
+                del _tensor_data_substitution_dict[self]
+
+    def __iter__(self):
+        deprecate_data()
+        if not self.data:
+            raise ValueError("No iteration on abstract tensors")
+        return self.data.flatten().__iter__()
+
+    def _eval_rewrite_as_Indexed(self, *args, **kwargs):
+        return Add.fromiter(args)
+
+    def _eval_partial_derivative(self, s):
+        # Evaluation like Add
+        list_addends = []
+        for a in self.args:
+            if isinstance(a, TensExpr):
+                list_addends.append(a._eval_partial_derivative(s))
+            # do not call diff if s is no symbol
+            elif s._diff_wrt:
+                list_addends.append(a._eval_derivative(s))
+
+        return self.func(*list_addends).doit(deep=False)
+
+    def matches(self, expr, repl_dict=None, old=False):
+        expr = sympify(expr)
+
+        if repl_dict is None:
+            repl_dict = {}
+        else:
+            repl_dict = repl_dict.copy()
+
+        if not isinstance(expr, TensAdd):
+            return None
+
+        if len(_get_wilds(self)) == 0:
+            return self._matches_simple(expr, repl_dict, old)
+
+        def siftkey(arg):
+            wildatoms = _get_wilds(arg)
+            wildatom_types = sift(wildatoms, type)
+            if len(wildatoms) == 0:
+                return "nonwild"
+            elif WildTensor in wildatom_types.keys():
+                for w in wildatom_types["WildTensor"]:
+                    if len(w.get_indices()) == 0:
+                        return "indexless_wildtensor"
+                return "wildtensor"
+            else:
+                return "otherwild"
+
+        query_sifted = sift(self.args, siftkey)
+        expr_sifted = sift(expr.args, siftkey)
+
+        #First try to match the terms without WildTensors
+        matched_e_tensors = [] #Used to make sure that the same tensor in expr is not matched with more than one tensor in self.
+        for q_tensor in query_sifted["nonwild"]:
+            matched_this_q = False
+            for e_tensor in expr_sifted["nonwild"]:
+                if e_tensor in matched_e_tensors:
+                    continue
+
+                m = q_tensor.matches(e_tensor, repl_dict=repl_dict, old=old)
+                if m is None:
+                    continue
+                else:
+                    matched_this_q = True
+                    repl_dict.update(m)
+                    matched_e_tensors.append(e_tensor)
+                    break
+
+            if not matched_this_q:
+                return None
+
+        remaining_e_tensors = [t for t in expr_sifted["nonwild"] if t not in matched_e_tensors]
+        for w in query_sifted["otherwild"]:
+            for e in remaining_e_tensors:
+                m = w.matches(e)
+                if m is not None:
+                    matched_e_tensors.append(e)
+                    if w in repl_dict.keys():
+                        repl_dict[w] += m.pop(w)
+                    repl_dict.update(m)
+
+        remaining_e_tensors = [t for t in expr_sifted["nonwild"] if t not in matched_e_tensors]
+        for w in query_sifted["wildtensor"]:
+            for e in remaining_e_tensors:
+                m = w.matches(e)
+                if m is not None:
+                    matched_e_tensors.append(e)
+                    if w.component in repl_dict.keys():
+                        repl_dict[w.component] += m.pop(w.component)
+                    repl_dict.update(m)
+
+        remaining_e_tensors = [t for t in expr_sifted["nonwild"] if t not in matched_e_tensors]
+        for w in query_sifted["indexless_wildtensor"]:
+            for e in remaining_e_tensors:
+                m = w.matches(e)
+                if m is not None:
+                    matched_e_tensors.append(e)
+                    if w.component in repl_dict.keys():
+                        repl_dict[w.component] += m.pop(w.component)
+                    repl_dict.update(m)
+
+        remaining_e_tensors = [t for t in expr_sifted["nonwild"] if t not in matched_e_tensors]
+        if len(remaining_e_tensors) > 0:
+            return None
+        else:
+            return repl_dict
+
+
+class Tensor(TensExpr):
+    """
+    Base tensor class, i.e. this represents a tensor, the single unit to be
+    put into an expression.
+
+    Explanation
+    ===========
+
+    This object is usually created from a ``TensorHead``, by attaching indices
+    to it. Indices preceded by a minus sign are considered contravariant,
+    otherwise covariant.
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead
+    >>> Lorentz = TensorIndexType("Lorentz", dummy_name="L")
+    >>> mu, nu = tensor_indices('mu nu', Lorentz)
+    >>> A = TensorHead("A", [Lorentz, Lorentz])
+    >>> A(mu, -nu)
+    A(mu, -nu)
+    >>> A(mu, -mu)
+    A(L_0, -L_0)
+
+    It is also possible to use symbols instead of inidices (appropriate indices
+    are then generated automatically).
+
+    >>> from sympy import Symbol
+    >>> x = Symbol('x')
+    >>> A(x, mu)
+    A(x, mu)
+    >>> A(x, -x)
+    A(L_0, -L_0)
+
+    """
+
+    is_commutative = False
+
+    _index_structure: _IndexStructure
+    args: tuple[TensorHead, Tuple]
+
+    def __new__(cls, tensor_head, indices, *, is_canon_bp=False, **kw_args):
+        indices = cls._parse_indices(tensor_head, indices)
+        obj = Basic.__new__(cls, tensor_head, Tuple(*indices), **kw_args)
+        obj._index_structure = _IndexStructure.from_indices(*indices)
+        obj._free = obj._index_structure.free[:]
+        obj._dum = obj._index_structure.dum[:]
+        obj._ext_rank = obj._index_structure._ext_rank
+        obj._coeff = S.One
+        obj._nocoeff = obj
+        obj._component = tensor_head
+        obj._components = [tensor_head]
+        if tensor_head.rank != len(indices):
+            raise ValueError("wrong number of indices")
+        obj.is_canon_bp = is_canon_bp
+        obj._index_map = Tensor._build_index_map(indices, obj._index_structure)
+        return obj
+
+    @property
+    def free(self):
+        return self._free
+
+    @property
+    def dum(self):
+        return self._dum
+
+    @property
+    def ext_rank(self):
+        return self._ext_rank
+
+    @property
+    def coeff(self):
+        return self._coeff
+
+    @property
+    def nocoeff(self):
+        return self._nocoeff
+
+    @property
+    def component(self):
+        return self._component
+
+    @property
+    def components(self):
+        return self._components
+
+    @property
+    def head(self):
+        return self.args[0]
+
+    @property
+    def indices(self):
+        return self.args[1]
+
+    @property
+    def free_indices(self):
+        return set(self._index_structure.get_free_indices())
+
+    @property
+    def index_types(self):
+        return self.head.index_types
+
+    @property
+    def rank(self):
+        return len(self.free_indices)
+
+    @staticmethod
+    def _build_index_map(indices, index_structure):
+        index_map = {}
+        for idx in indices:
+            index_map[idx] = (indices.index(idx),)
+        return index_map
+
+    def doit(self, **hints):
+        args, indices, free, dum = TensMul._tensMul_contract_indices([self])
+        return args[0]
+
+    @staticmethod
+    def _parse_indices(tensor_head, indices):
+        if not isinstance(indices, (tuple, list, Tuple)):
+            raise TypeError("indices should be an array, got %s" % type(indices))
+        indices = list(indices)
+        for i, index in enumerate(indices):
+            if isinstance(index, Symbol):
+                indices[i] = TensorIndex(index, tensor_head.index_types[i], True)
+            elif isinstance(index, Mul):
+                c, e = index.as_coeff_Mul()
+                if c == -1 and isinstance(e, Symbol):
+                    indices[i] = TensorIndex(e, tensor_head.index_types[i], False)
+                else:
+                    raise ValueError("index not understood: %s" % index)
+            elif not isinstance(index, TensorIndex):
+                raise TypeError("wrong type for index: %s is %s" % (index, type(index)))
+        return indices
+
+    def _set_new_index_structure(self, im, is_canon_bp=False):
+        indices = im.get_indices()
+        return self._set_indices(*indices, is_canon_bp=is_canon_bp)
+
+    def _set_indices(self, *indices, is_canon_bp=False, **kw_args):
+        if len(indices) != self.ext_rank:
+            raise ValueError("indices length mismatch")
+        return self.func(self.args[0], indices, is_canon_bp=is_canon_bp).doit()
+
+    def _get_free_indices_set(self):
+        return {i[0] for i in self._index_structure.free}
+
+    def _get_dummy_indices_set(self):
+        dummy_pos = set(itertools.chain(*self._index_structure.dum))
+        return {idx for i, idx in enumerate(self.args[1]) if i in dummy_pos}
+
+    def _get_indices_set(self):
+        return set(self.args[1].args)
+
+    @property
+    def free_in_args(self):
+        return [(ind, pos, 0) for ind, pos in self.free]
+
+    @property
+    def dum_in_args(self):
+        return [(p1, p2, 0, 0) for p1, p2 in self.dum]
+
+    @property
+    def free_args(self):
+        return sorted([x[0] for x in self.free])
+
+    def commutes_with(self, other):
+        """
+        :param other:
+        :return:
+            0  commute
+            1  anticommute
+            None  neither commute nor anticommute
+        """
+        if not isinstance(other, TensExpr):
+            return 0
+        elif isinstance(other, Tensor):
+            return self.component.commutes_with(other.component)
+        return NotImplementedError
+
+    def perm2tensor(self, g, is_canon_bp=False):
+        """
+        Returns the tensor corresponding to the permutation ``g``.
+
+        For further details, see the method in ``TIDS`` with the same name.
+        """
+        return perm2tensor(self, g, is_canon_bp)
+
+    def canon_bp(self):
+        if self.is_canon_bp:
+            return self
+        expr = self.expand()
+        g, dummies, msym = expr._index_structure.indices_canon_args()
+        v = components_canon_args([expr.component])
+        can = canonicalize(g, dummies, msym, *v)
+        if can == 0:
+            return S.Zero
+        tensor = self.perm2tensor(can, True)
+        return tensor
+
+    def split(self):
+        return [self]
+
+    def sorted_components(self):
+        return self
+
+    def get_indices(self) -> list[TensorIndex]:
+        """
+        Get a list of indices, corresponding to those of the tensor.
+        """
+        return list(self.args[1])
+
+    def get_free_indices(self) -> list[TensorIndex]:
+        """
+        Get a list of free indices, corresponding to those of the tensor.
+        """
+        return self._index_structure.get_free_indices()
+
+    def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr:
+        # TODO: this could be optimized by only swapping the indices
+        # instead of visiting the whole expression tree:
+        return self.xreplace(repl)
+
+    def as_base_exp(self):
+        return self, S.One
+
+    def substitute_indices(self, *index_tuples):
+        """
+        Return a tensor with free indices substituted according to ``index_tuples``.
+
+        ``index_types`` list of tuples ``(old_index, new_index)``.
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads, TensorSymmetry
+        >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+        >>> i, j, k, l = tensor_indices('i,j,k,l', Lorentz)
+        >>> A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
+        >>> t = A(i, k)*B(-k, -j); t
+        A(i, L_0)*B(-L_0, -j)
+        >>> t.substitute_indices((i, k),(-j, l))
+        A(k, L_0)*B(-L_0, l)
+        """
+        indices = []
+        for index in self.indices:
+            for ind_old, ind_new in index_tuples:
+                if (index.name == ind_old.name and index.tensor_index_type ==
+                                                   ind_old.tensor_index_type):
+                    if index.is_up == ind_old.is_up:
+                        indices.append(ind_new)
+                    else:
+                        indices.append(-ind_new)
+                    break
+            else:
+                indices.append(index)
+        return self.head(*indices)
+
+    def _get_symmetrized_forms(self):
+        """
+        Return a list giving all possible permutations of self that are allowed by its symmetries.
+        """
+        comp = self.component
+        gens = comp.symmetry.generators
+        rank = comp.rank
+
+        old_perms = None
+        new_perms = {self}
+        while new_perms != old_perms:
+            old_perms = new_perms.copy()
+            for tens in old_perms:
+                for gen in gens:
+                    inds = tens.get_indices()
+                    per = [gen.apply(i) for i in range(0,rank)]
+                    sign = (-1)**(gen.apply(rank) - rank)
+                    ind_map = dict(zip(inds, [inds[i] for i in per]))
+                    new_perms.add( sign * tens._replace_indices(ind_map) )
+
+        return new_perms
+
+    def matches(self, expr, repl_dict=None, old=False):
+        expr = sympify(expr)
+
+        if repl_dict is None:
+            repl_dict = {}
+        else:
+            repl_dict = repl_dict.copy()
+
+        #simple checks
+        if self == expr:
+            return repl_dict
+        if not isinstance(expr, Tensor):
+            return None
+        if self.head != expr.head:
+            return None
+
+        #Now consider all index symmetries of expr, and see if any of them allow a match.
+        for new_expr in expr._get_symmetrized_forms():
+            m = self._matches(new_expr, repl_dict, old=old)
+            if m is not None:
+                repl_dict.update(m)
+                return repl_dict
+
+        return None
+
+    def _matches(self, expr, repl_dict=None, old=False):
+        """
+        This does not account for index symmetries of expr
+        """
+        expr = sympify(expr)
+
+        if repl_dict is None:
+            repl_dict = {}
+        else:
+            repl_dict = repl_dict.copy()
+
+        #simple checks
+        if self == expr:
+            return repl_dict
+        if not isinstance(expr, Tensor):
+            return None
+        if self.head != expr.head:
+            return None
+
+        s_indices = self.get_indices()
+        e_indices = expr.get_indices()
+
+        if len(s_indices) != len(e_indices):
+            return None
+
+        for i in range(len(s_indices)):
+            s_ind = s_indices[i]
+            m = s_ind.matches(e_indices[i])
+            if m is None:
+                return None
+            elif -s_ind in repl_dict.keys() and -repl_dict[-s_ind] != m[s_ind]:
+                return None
+            else:
+                repl_dict.update(m)
+
+        return repl_dict
+
+    def __call__(self, *indices):
+        deprecate_call()
+        free_args = self.free_args
+        indices = list(indices)
+        if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]:
+            raise ValueError('incompatible types')
+        if indices == free_args:
+            return self
+        t = self.substitute_indices(*list(zip(free_args, indices)))
+
+        # object is rebuilt in order to make sure that all contracted indices
+        # get recognized as dummies, but only if there are contracted indices.
+        if len({i if i.is_up else -i for i in indices}) != len(indices):
+            return t.func(*t.args)
+        return t
+
+    # TODO: put this into TensExpr?
+    def __iter__(self):
+        deprecate_data()
+        with ignore_warnings(SymPyDeprecationWarning):
+            return self.data.__iter__()
+
+    # TODO: put this into TensExpr?
+    def __getitem__(self, item):
+        deprecate_data()
+        with ignore_warnings(SymPyDeprecationWarning):
+            return self.data[item]
+
+    def _extract_data(self, replacement_dict):
+        from .array import Array
+        for k, v in replacement_dict.items():
+            if isinstance(k, Tensor) and k.args[0] == self.args[0]:
+                other = k
+                array = v
+                break
+        else:
+            raise ValueError("%s not found in %s" % (self, replacement_dict))
+
+        # TODO: inefficient, this should be done at root level only:
+        replacement_dict = {k: Array(v) for k, v in replacement_dict.items()}
+        array = Array(array)
+
+        dum1 = self.dum
+        dum2 = other.dum
+
+        if len(dum2) > 0:
+            for pair in dum2:
+                # allow `dum2` if the contained values are also in `dum1`.
+                if pair not in dum1:
+                    raise NotImplementedError("%s with contractions is not implemented" % other)
+            # Remove elements in `dum2` from `dum1`:
+            dum1 = [pair for pair in dum1 if pair not in dum2]
+        if len(dum1) > 0:
+            indices1 = self.get_indices()
+            indices2 = other.get_indices()
+            repl = {}
+            for p1, p2 in dum1:
+                repl[indices2[p2]] = -indices2[p1]
+                for pos in (p1, p2):
+                    if indices1[pos].is_up ^ indices2[pos].is_up:
+                        metric = replacement_dict[indices1[pos].tensor_index_type]
+                        if indices1[pos].is_up:
+                            metric = _TensorDataLazyEvaluator.inverse_matrix(metric)
+                        array = self._contract_and_permute_with_metric(metric, array, pos, len(indices2))
+            other = other.xreplace(repl).doit()
+            array = _TensorDataLazyEvaluator.data_contract_dum([array], dum1, len(indices2))
+
+        free_ind1 = self.get_free_indices()
+        free_ind2 = other.get_free_indices()
+
+        return self._match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict)
+
+    @property
+    def data(self):
+        deprecate_data()
+        with ignore_warnings(SymPyDeprecationWarning):
+            return _tensor_data_substitution_dict[self]
+
+    @data.setter
+    def data(self, data):
+        deprecate_data()
+        # TODO: check data compatibility with properties of tensor.
+        with ignore_warnings(SymPyDeprecationWarning):
+            _tensor_data_substitution_dict[self] = data
+
+    @data.deleter
+    def data(self):
+        deprecate_data()
+        with ignore_warnings(SymPyDeprecationWarning):
+            if self in _tensor_data_substitution_dict:
+                del _tensor_data_substitution_dict[self]
+            if self.metric in _tensor_data_substitution_dict:
+                del _tensor_data_substitution_dict[self.metric]
+
+    def _print(self):
+        indices = [str(ind) for ind in self.indices]
+        component = self.component
+        if component.rank > 0:
+            return ('%s(%s)' % (component.name, ', '.join(indices)))
+        else:
+            return ('%s' % component.name)
+
+    def equals(self, other):
+        if other == 0:
+            return self.coeff == 0
+        other = _sympify(other)
+        if not isinstance(other, TensExpr):
+            assert not self.components
+            return S.One == other
+
+        def _get_compar_comp(self):
+            t = self.canon_bp()
+            r = (t.coeff, tuple(t.components), \
+                    tuple(sorted(t.free)), tuple(sorted(t.dum)))
+            return r
+
+        return _get_compar_comp(self) == _get_compar_comp(other)
+
+    def contract_metric(self, g):
+        # if metric is not the same, ignore this step:
+        if self.component != g:
+            return self
+        # in case there are free components, do not perform anything:
+        if len(self.free) != 0:
+            return self
+
+        #antisym = g.index_types[0].metric_antisym
+        if g.symmetry == TensorSymmetry.fully_symmetric(-2):
+            antisym = 1
+        elif g.symmetry == TensorSymmetry.fully_symmetric(2):
+            antisym = 0
+        elif g.symmetry == TensorSymmetry.no_symmetry(2):
+            antisym = None
+        else:
+            raise NotImplementedError
+        sign = S.One
+        typ = g.index_types[0]
+
+        if not antisym:
+            # g(i, -i)
+            sign = sign*typ.dim
+        else:
+            # g(i, -i)
+            sign = sign*typ.dim
+
+            dp0, dp1 = self.dum[0]
+            if dp0 < dp1:
+                # g(i, -i) = -D with antisymmetric metric
+                sign = -sign
+
+        return sign
+
+    def contract_delta(self, metric):
+        return self.contract_metric(metric)
+
+    def _eval_rewrite_as_Indexed(self, tens, indices, **kwargs):
+        from sympy.tensor.indexed import Indexed
+        # TODO: replace .args[0] with .name:
+        index_symbols = [i.args[0] for i in self.get_indices()]
+        expr = Indexed(tens.args[0], *index_symbols)
+        return self._check_add_Sum(expr, index_symbols)
+
+    def _eval_partial_derivative(self, s: Tensor) -> Expr:
+
+        if not isinstance(s, Tensor):
+            return S.Zero
+        else:
+
+            # @a_i/@a_k = delta_i^k
+            # @a_i/@a^k = g_ij delta^j_k
+            # @a^i/@a^k = delta^i_k
+            # @a^i/@a_k = g^ij delta_j^k
+            # TODO: if there is no metric present, the derivative should be zero?
+
+            if self.head != s.head:
+                return S.Zero
+
+            # if heads are the same, provide delta and/or metric products
+            # for every free index pair in the appropriate tensor
+            # assumed that the free indices are in proper order
+            # A contravariante index in the derivative becomes covariant
+            # after performing the derivative and vice versa
+
+            kronecker_delta_list = [1]
+
+            # not guarantee a correct index order
+
+            for (count, (iself, iother)) in enumerate(zip(self.get_free_indices(), s.get_free_indices())):
+                if iself.tensor_index_type != iother.tensor_index_type:
+                    raise ValueError("index types not compatible")
+                else:
+                    tensor_index_type = iself.tensor_index_type
+                    tensor_metric = tensor_index_type.metric
+                    dummy = TensorIndex("d_" + str(count), tensor_index_type,
+                                        is_up=iself.is_up)
+                    if iself.is_up == iother.is_up:
+                        kroneckerdelta = tensor_index_type.delta(iself, -iother)
+                    else:
+                        kroneckerdelta = (
+                            TensMul(tensor_metric(iself, dummy),
+                                    tensor_index_type.delta(-dummy, -iother))
+                        )
+                    kronecker_delta_list.append(kroneckerdelta)
+            return TensMul.fromiter(kronecker_delta_list).doit(deep=False)
+            # doit necessary to rename dummy indices accordingly
+
+
+class TensMul(TensExpr, AssocOp):
+    """
+    Product of tensors.
+
+    Parameters
+    ==========
+
+    coeff : SymPy coefficient of the tensor
+    args
+
+    Attributes
+    ==========
+
+    ``components`` : list of ``TensorHead`` of the component tensors
+    ``types`` : list of nonrepeated ``TensorIndexType``
+    ``free`` : list of ``(ind, ipos, icomp)``, see Notes
+    ``dum`` : list of ``(ipos1, ipos2, icomp1, icomp2)``, see Notes
+    ``ext_rank`` : rank of the tensor counting the dummy indices
+    ``rank`` : rank of the tensor
+    ``coeff`` : SymPy coefficient of the tensor
+    ``free_args`` : list of the free indices in sorted order
+    ``is_canon_bp`` : ``True`` if the tensor in in canonical form
+
+    Notes
+    =====
+
+    ``args[0]``   list of ``TensorHead`` of the component tensors.
+
+    ``args[1]``   list of ``(ind, ipos, icomp)``
+    where ``ind`` is a free index, ``ipos`` is the slot position
+    of ``ind`` in the ``icomp``-th component tensor.
+
+    ``args[2]`` list of tuples representing dummy indices.
+    ``(ipos1, ipos2, icomp1, icomp2)`` indicates that the contravariant
+    dummy index is the ``ipos1``-th slot position in the ``icomp1``-th
+    component tensor; the corresponding covariant index is
+    in the ``ipos2`` slot position in the ``icomp2``-th component tensor.
+
+    """
+    identity = S.One
+
+    _index_structure: _IndexStructure
+
+    def __new__(cls, *args, **kw_args):
+        is_canon_bp = kw_args.get('is_canon_bp', False)
+        args = list(map(_sympify, args))
+
+        """
+        If the internal dummy indices in one arg conflict with the free indices
+        of the remaining args, we need to rename those internal dummy indices.
+        """
+        free = [get_free_indices(arg) for arg in args]
+        free = set(itertools.chain(*free)) #flatten free
+        newargs = []
+        for arg in args:
+            dum_this = set(get_dummy_indices(arg))
+            dum_other = [get_dummy_indices(a) for a in newargs]
+            dum_other = set(itertools.chain(*dum_other)) #flatten dum_other
+            free_this = set(get_free_indices(arg))
+            if len(dum_this.intersection(free)) > 0:
+                exclude = free_this.union(free, dum_other)
+                newarg = TensMul._dedupe_indices(arg, exclude)
+            else:
+                newarg = arg
+            newargs.append(newarg)
+
+        args = newargs
+
+        # Flatten:
+        args = [i for arg in args for i in (arg.args if isinstance(arg, (TensMul, Mul)) else [arg])]
+
+        args, indices, free, dum = TensMul._tensMul_contract_indices(args, replace_indices=False)
+
+        # Data for indices:
+        index_types = [i.tensor_index_type for i in indices]
+        index_structure = _IndexStructure(free, dum, index_types, indices, canon_bp=is_canon_bp)
+
+        obj = TensExpr.__new__(cls, *args)
+        obj._indices = indices
+        obj._index_types = index_types.copy()
+        obj._index_structure = index_structure
+        obj._free = index_structure.free[:]
+        obj._dum = index_structure.dum[:]
+        obj._free_indices = {x[0] for x in obj.free}
+        obj._rank = len(obj.free)
+        obj._ext_rank = len(obj._index_structure.free) + 2*len(obj._index_structure.dum)
+        obj._coeff = S.One
+        obj._is_canon_bp = is_canon_bp
+        return obj
+
+    index_types = property(lambda self: self._index_types)
+    free = property(lambda self: self._free)
+    dum = property(lambda self: self._dum)
+    free_indices = property(lambda self: self._free_indices)
+    rank = property(lambda self: self._rank)
+    ext_rank = property(lambda self: self._ext_rank)
+
+    @staticmethod
+    def _indices_to_free_dum(args_indices):
+        free2pos1 = {}
+        free2pos2 = {}
+        dummy_data = []
+        indices = []
+
+        # Notation for positions (to better understand the code):
+        # `pos1`: position in the `args`.
+        # `pos2`: position in the indices.
+
+        # Example:
+        # A(i, j)*B(k, m, n)*C(p)
+        # `pos1` of `n` is 1 because it's in `B` (second `args` of TensMul).
+        # `pos2` of `n` is 4 because it's the fifth overall index.
+
+        # Counter for the index position wrt the whole expression:
+        pos2 = 0
+
+        for pos1, arg_indices in enumerate(args_indices):
+
+            for index in arg_indices:
+                if not isinstance(index, TensorIndex):
+                    raise TypeError("expected TensorIndex")
+                if -index in free2pos1:
+                    # Dummy index detected:
+                    other_pos1 = free2pos1.pop(-index)
+                    other_pos2 = free2pos2.pop(-index)
+                    if index.is_up:
+                        dummy_data.append((index, pos1, other_pos1, pos2, other_pos2))
+                    else:
+                        dummy_data.append((-index, other_pos1, pos1, other_pos2, pos2))
+                    indices.append(index)
+                elif index in free2pos1:
+                    raise ValueError("Repeated index: %s" % index)
+                else:
+                    free2pos1[index] = pos1
+                    free2pos2[index] = pos2
+                    indices.append(index)
+                pos2 += 1
+
+        free = list(free2pos2.items())
+        free_names = [i.name for i in free2pos2.keys()]
+
+        dummy_data.sort(key=lambda x: x[3])
+        return indices, free, free_names, dummy_data
+
+    @staticmethod
+    def _dummy_data_to_dum(dummy_data):
+        return [(p2a, p2b) for (i, p1a, p1b, p2a, p2b) in dummy_data]
+
+    @staticmethod
+    def _tensMul_contract_indices(args, replace_indices=True):
+        replacements = [{} for _ in args]
+
+        #_index_order = all(_has_index_order(arg) for arg in args)
+
+        args_indices = [get_indices(arg) for arg in args]
+        indices, free, free_names, dummy_data = TensMul._indices_to_free_dum(args_indices)
+
+        cdt = defaultdict(int)
+
+        def dummy_name_gen(tensor_index_type):
+            nd = str(cdt[tensor_index_type])
+            cdt[tensor_index_type] += 1
+            return tensor_index_type.dummy_name + '_' + nd
+
+        if replace_indices:
+            for old_index, pos1cov, pos1contra, pos2cov, pos2contra in dummy_data:
+                index_type = old_index.tensor_index_type
+                while True:
+                    dummy_name = dummy_name_gen(index_type)
+                    if dummy_name not in free_names:
+                        break
+                dummy = old_index.func(dummy_name, index_type, *old_index.args[2:])
+                replacements[pos1cov][old_index] = dummy
+                replacements[pos1contra][-old_index] = -dummy
+                indices[pos2cov] = dummy
+                indices[pos2contra] = -dummy
+            args = [
+                arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg
+                for arg, repl in zip(args, replacements)]
+
+            """
+            The order of indices might've changed due to the replacements (e.g. if one of the args is a TensAdd, replacing an index can change the sort order of the terms, thus changing the order of indices returned by its get_indices() method).
+            To stay on the safe side, we calculate these quantities again.
+            """
+            args_indices = [get_indices(arg) for arg in args]
+            indices, free, free_names, dummy_data = TensMul._indices_to_free_dum(args_indices)
+
+        dum = TensMul._dummy_data_to_dum(dummy_data)
+        return args, indices, free, dum
+
+    @staticmethod
+    def _get_components_from_args(args):
+        """
+        Get a list of ``Tensor`` objects having the same ``TIDS`` if multiplied
+        by one another.
+        """
+        components = []
+        for arg in args:
+            if not isinstance(arg, TensExpr):
+                continue
+            if isinstance(arg, TensAdd):
+                continue
+            components.extend(arg.components)
+        return components
+
+    @staticmethod
+    def _rebuild_tensors_list(args, index_structure):
+        indices = index_structure.get_indices()
+        #tensors = [None for i in components]  # pre-allocate list
+        ind_pos = 0
+        for i, arg in enumerate(args):
+            if not isinstance(arg, TensExpr):
+                continue
+            prev_pos = ind_pos
+            ind_pos += arg.ext_rank
+            args[i] = Tensor(arg.component, indices[prev_pos:ind_pos])
+
+    def doit(self, **hints):
+        is_canon_bp = self._is_canon_bp
+        deep = hints.get('deep', True)
+        if deep:
+            args = [arg.doit(**hints) for arg in self.args]
+
+            """
+            There may now be conflicts between dummy indices of different args
+            (each arg's doit method does not have any information about which
+            dummy indices are already used in the other args), so we
+            deduplicate them.
+            """
+            rule = dict(zip(self.args, args))
+            rule = self._dedupe_indices_in_rule(rule)
+            args = [rule[a] for a in self.args]
+
+        else:
+            args = self.args
+
+        args = [arg for arg in args if arg != self.identity]
+
+        # Extract non-tensor coefficients:
+        coeff = reduce(lambda a, b: a*b, [arg for arg in args if not isinstance(arg, TensExpr)], S.One)
+        args = [arg for arg in args if isinstance(arg, TensExpr)]
+
+        if len(args) == 0:
+            return coeff
+
+        if coeff != self.identity:
+            args = [coeff] + args
+        if coeff == 0:
+            return S.Zero
+
+        if len(args) == 1:
+            return args[0]
+
+        args, indices, free, dum = TensMul._tensMul_contract_indices(args)
+
+        # Data for indices:
+        index_types = [i.tensor_index_type for i in indices]
+        index_structure = _IndexStructure(free, dum, index_types, indices, canon_bp=is_canon_bp)
+
+        obj = self.func(*args)
+        obj._index_types = index_types
+        obj._index_structure = index_structure
+        obj._ext_rank = len(obj._index_structure.free) + 2*len(obj._index_structure.dum)
+        obj._coeff = coeff
+        obj._is_canon_bp = is_canon_bp
+        return obj
+
+    # TODO: this method should be private
+    # TODO: should this method be renamed _from_components_free_dum ?
+    @staticmethod
+    def from_data(coeff, components, free, dum, **kw_args):
+        return TensMul(coeff, *TensMul._get_tensors_from_components_free_dum(components, free, dum), **kw_args).doit(deep=False)
+
+    @staticmethod
+    def _get_tensors_from_components_free_dum(components, free, dum):
+        """
+        Get a list of ``Tensor`` objects by distributing ``free`` and ``dum`` indices on the ``components``.
+        """
+        index_structure = _IndexStructure.from_components_free_dum(components, free, dum)
+        indices = index_structure.get_indices()
+        tensors = [None for i in components]  # pre-allocate list
+
+        # distribute indices on components to build a list of tensors:
+        ind_pos = 0
+        for i, component in enumerate(components):
+            prev_pos = ind_pos
+            ind_pos += component.rank
+            tensors[i] = Tensor(component, indices[prev_pos:ind_pos])
+        return tensors
+
+    def _get_free_indices_set(self):
+        return {i[0] for i in self.free}
+
+    def _get_dummy_indices_set(self):
+        dummy_pos = set(itertools.chain(*self.dum))
+        return {idx for i, idx in enumerate(self._index_structure.get_indices()) if i in dummy_pos}
+
+    def _get_position_offset_for_indices(self):
+        arg_offset = [None for i in range(self.ext_rank)]
+        counter = 0
+        for arg in self.args:
+            if not isinstance(arg, TensExpr):
+                continue
+            for j in range(arg.ext_rank):
+                arg_offset[j + counter] = counter
+            counter += arg.ext_rank
+        return arg_offset
+
+    @property
+    def free_args(self):
+        return sorted([x[0] for x in self.free])
+
+    @property
+    def components(self):
+        return self._get_components_from_args(self.args)
+
+    @property
+    def free_in_args(self):
+        arg_offset = self._get_position_offset_for_indices()
+        argpos = self._get_indices_to_args_pos()
+        return [(ind, pos-arg_offset[pos], argpos[pos]) for (ind, pos) in self.free]
+
+    @property
+    def coeff(self):
+        # return Mul.fromiter([c for c in self.args if not isinstance(c, TensExpr)])
+        return self._coeff
+
+    @property
+    def nocoeff(self):
+        return self.func(*self.args, 1/self.coeff).doit(deep=False)
+
+    @property
+    def dum_in_args(self):
+        arg_offset = self._get_position_offset_for_indices()
+        argpos = self._get_indices_to_args_pos()
+        return [(p1-arg_offset[p1], p2-arg_offset[p2], argpos[p1], argpos[p2]) for p1, p2 in self.dum]
+
+    def equals(self, other):
+        if other == 0:
+            return self.coeff == 0
+        other = _sympify(other)
+        if not isinstance(other, TensExpr):
+            assert not self.components
+            return self.coeff == other
+
+        return self.canon_bp() == other.canon_bp()
+
+    def get_indices(self):
+        """
+        Returns the list of indices of the tensor.
+
+        Explanation
+        ===========
+
+        The indices are listed in the order in which they appear in the
+        component tensors.
+        The dummy indices are given a name which does not collide with
+        the names of the free indices.
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads
+        >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+        >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz)
+        >>> g = Lorentz.metric
+        >>> p, q = tensor_heads('p,q', [Lorentz])
+        >>> t = p(m1)*g(m0,m2)
+        >>> t.get_indices()
+        [m1, m0, m2]
+        >>> t2 = p(m1)*g(-m1, m2)
+        >>> t2.get_indices()
+        [L_0, -L_0, m2]
+        """
+        return self._indices
+
+    def get_free_indices(self) -> list[TensorIndex]:
+        """
+        Returns the list of free indices of the tensor.
+
+        Explanation
+        ===========
+
+        The indices are listed in the order in which they appear in the
+        component tensors.
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads
+        >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+        >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz)
+        >>> g = Lorentz.metric
+        >>> p, q = tensor_heads('p,q', [Lorentz])
+        >>> t = p(m1)*g(m0,m2)
+        >>> t.get_free_indices()
+        [m1, m0, m2]
+        >>> t2 = p(m1)*g(-m1, m2)
+        >>> t2.get_free_indices()
+        [m2]
+        """
+        return self._index_structure.get_free_indices()
+
+    def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr:
+        return self.func(*[arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg for arg in self.args])
+
+    def split(self):
+        """
+        Returns a list of tensors, whose product is ``self``.
+
+        Explanation
+        ===========
+
+        Dummy indices contracted among different tensor components
+        become free indices with the same name as the one used to
+        represent the dummy indices.
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads, TensorSymmetry
+        >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+        >>> a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
+        >>> A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
+        >>> t = A(a,b)*B(-b,c)
+        >>> t
+        A(a, L_0)*B(-L_0, c)
+        >>> t.split()
+        [A(a, L_0), B(-L_0, c)]
+        """
+        if self.args == ():
+            return [self]
+        splitp = []
+        res = 1
+        for arg in self.args:
+            if isinstance(arg, Tensor):
+                splitp.append(res*arg)
+                res = 1
+            else:
+                res *= arg
+        return splitp
+
+    def _eval_expand_mul(self, **hints):
+        args1 = [arg.args if isinstance(arg, (Add, TensAdd)) else (arg,) for arg in self.args]
+        return TensAdd(*[
+            TensMul(*i).doit(deep=False) for i in itertools.product(*args1)]
+        )
+
+    def __neg__(self):
+        return TensMul(S.NegativeOne, self, is_canon_bp=self._is_canon_bp).doit(deep=False)
+
+    def __getitem__(self, item):
+        deprecate_data()
+        with ignore_warnings(SymPyDeprecationWarning):
+            return self.data[item]
+
+    def _get_args_for_traditional_printer(self):
+        args = list(self.args)
+        if self.coeff.could_extract_minus_sign():
+            # expressions like "-A(a)"
+            sign = "-"
+            if args[0] == S.NegativeOne:
+                args = args[1:]
+            else:
+                args[0] = -args[0]
+        else:
+            sign = ""
+        return sign, args
+
+    def _sort_args_for_sorted_components(self):
+        """
+        Returns the ``args`` sorted according to the components commutation
+        properties.
+
+        Explanation
+        ===========
+
+        The sorting is done taking into account the commutation group
+        of the component tensors.
+        """
+        cv = [arg for arg in self.args if isinstance(arg, TensExpr)]
+        sign = 1
+        n = len(cv) - 1
+        for i in range(n):
+            for j in range(n, i, -1):
+                c = cv[j-1].commutes_with(cv[j])
+                # if `c` is `None`, it does neither commute nor anticommute, skip:
+                if c not in (0, 1):
+                    continue
+                typ1 = sorted(set(cv[j-1].component.index_types), key=lambda x: x.name)
+                typ2 = sorted(set(cv[j].component.index_types), key=lambda x: x.name)
+                if (typ1, cv[j-1].component.name) > (typ2, cv[j].component.name):
+                    cv[j-1], cv[j] = cv[j], cv[j-1]
+                    # if `c` is 1, the anticommute, so change sign:
+                    if c:
+                        sign = -sign
+
+        coeff = sign * self.coeff
+        if coeff != 1:
+            return [coeff] + cv
+        return cv
+
+    def sorted_components(self):
+        """
+        Returns a tensor product with sorted components.
+        """
+        return TensMul(*self._sort_args_for_sorted_components()).doit(deep=False)
+
+    def perm2tensor(self, g, is_canon_bp=False):
+        """
+        Returns the tensor corresponding to the permutation ``g``
+
+        For further details, see the method in ``TIDS`` with the same name.
+        """
+        return perm2tensor(self, g, is_canon_bp=is_canon_bp)
+
+    def canon_bp(self):
+        """
+        Canonicalize using the Butler-Portugal algorithm for canonicalization
+        under monoterm symmetries.
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, TensorSymmetry
+        >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+        >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz)
+        >>> A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
+        >>> t = A(m0,-m1)*A(m1,-m0)
+        >>> t.canon_bp()
+        -A(L_0, L_1)*A(-L_0, -L_1)
+        >>> t = A(m0,-m1)*A(m1,-m2)*A(m2,-m0)
+        >>> t.canon_bp()
+        0
+        """
+        if self._is_canon_bp:
+            return self
+        expr = self.expand()
+        if isinstance(expr, TensAdd):
+            return expr.canon_bp()
+        if not expr.components:
+            return expr
+        expr = expr.doit(deep=False) #make sure self.coeff is populated correctly
+        t = expr.sorted_components()
+        g, dummies, msym = t._index_structure.indices_canon_args()
+        v = components_canon_args(t.components)
+        can = canonicalize(g, dummies, msym, *v)
+        if can == 0:
+            return S.Zero
+        tmul = t.perm2tensor(can, True)
+        return tmul
+
+    def contract_delta(self, delta):
+        t = self.contract_metric(delta)
+        return t
+
+    def _get_indices_to_args_pos(self):
+        """
+        Get a dict mapping the index position to TensMul's argument number.
+        """
+        pos_map = {}
+        pos_counter = 0
+        for arg_i, arg in enumerate(self.args):
+            if not isinstance(arg, TensExpr):
+                continue
+            assert isinstance(arg, Tensor)
+            for i in range(arg.ext_rank):
+                pos_map[pos_counter] = arg_i
+                pos_counter += 1
+        return pos_map
+
+    def contract_metric(self, g):
+        """
+        Raise or lower indices with the metric ``g``.
+
+        Parameters
+        ==========
+
+        g : metric
+
+        Notes
+        =====
+
+        See the ``TensorIndexType`` docstring for the contraction conventions.
+
+        Examples
+        ========
+
+        >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads
+        >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+        >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz)
+        >>> g = Lorentz.metric
+        >>> p, q = tensor_heads('p,q', [Lorentz])
+        >>> t = p(m0)*q(m1)*g(-m0, -m1)
+        >>> t.canon_bp()
+        metric(L_0, L_1)*p(-L_0)*q(-L_1)
+        >>> t.contract_metric(g).canon_bp()
+        p(L_0)*q(-L_0)
+        """
+        expr = self.expand().doit(deep=False)
+        if self != expr:
+            expr = canon_bp(expr)
+            return contract_metric(expr, g)
+        pos_map = self._get_indices_to_args_pos()
+        args = list(self.args)
+
+        #antisym = g.index_types[0].metric_antisym
+        if g.symmetry == TensorSymmetry.fully_symmetric(-2):
+            antisym = 1
+        elif g.symmetry == TensorSymmetry.fully_symmetric(2):
+            antisym = 0
+        elif g.symmetry == TensorSymmetry.no_symmetry(2):
+            antisym = None
+        else:
+            raise NotImplementedError
+
+        # list of positions of the metric ``g`` inside ``args``
+        gpos = [i for i, x in enumerate(self.args) if isinstance(x, Tensor) and x.component == g]
+        if not gpos:
+            return self
+
+        # Sign is either 1 or -1, to correct the sign after metric contraction
+        # (for spinor indices).
+        sign = 1
+        dum = self.dum[:]
+        free = self.free[:]
+        elim = set()
+        for gposx in gpos:
+            if gposx in elim:
+                continue
+            free1 = [x for x in free if pos_map[x[1]] == gposx]
+            dum1 = [x for x in dum if pos_map[x[0]] == gposx or pos_map[x[1]] == gposx]
+            if not dum1:
+                continue
+            elim.add(gposx)
+            # subs with the multiplication neutral element, that is, remove it:
+            args[gposx] = 1
+            if len(dum1) == 2:
+                if not antisym:
+                    dum10, dum11 = dum1
+                    if pos_map[dum10[1]] == gposx:
+                        # the index with pos p0 contravariant
+                        p0 = dum10[0]
+                    else:
+                        # the index with pos p0 is covariant
+                        p0 = dum10[1]
+                    if pos_map[dum11[1]] == gposx:
+                        # the index with pos p1 is contravariant
+                        p1 = dum11[0]
+                    else:
+                        # the index with pos p1 is covariant
+                        p1 = dum11[1]
+
+                    dum.append((p0, p1))
+                else:
+                    dum10, dum11 = dum1
+                    # change the sign to bring the indices of the metric to contravariant
+                    # form; change the sign if dum10 has the metric index in position 0
+                    if pos_map[dum10[1]] == gposx:
+                        # the index with pos p0 is contravariant
+                        p0 = dum10[0]
+                        if dum10[1] == 1:
+                            sign = -sign
+                    else:
+                        # the index with pos p0 is covariant
+                        p0 = dum10[1]
+                        if dum10[0] == 0:
+                            sign = -sign
+                    if pos_map[dum11[1]] == gposx:
+                        # the index with pos p1 is contravariant
+                        p1 = dum11[0]
+                        sign = -sign
+                    else:
+                        # the index with pos p1 is covariant
+                        p1 = dum11[1]
+
+                    dum.append((p0, p1))
+
+            elif len(dum1) == 1:
+                if not antisym:
+                    dp0, dp1 = dum1[0]
+                    if pos_map[dp0] == pos_map[dp1]:
+                        # g(i, -i)
+                        typ = g.index_types[0]
+                        sign = sign*typ.dim
+
+                    else:
+                        # g(i0, i1)*p(-i1)
+                        if pos_map[dp0] == gposx:
+                            p1 = dp1
+                        else:
+                            p1 = dp0
+
+                        ind, p = free1[0]
+                        free.append((ind, p1))
+                else:
+                    dp0, dp1 = dum1[0]
+                    if pos_map[dp0] == pos_map[dp1]:
+                        # g(i, -i)
+                        typ = g.index_types[0]
+                        sign = sign*typ.dim
+
+                        if dp0 < dp1:
+                            # g(i, -i) = -D with antisymmetric metric
+                            sign = -sign
+                    else:
+                        # g(i0, i1)*p(-i1)
+                        if pos_map[dp0] == gposx:
+                            p1 = dp1
+                            if dp0 == 0:
+                                sign = -sign
+                        else:
+                            p1 = dp0
+                        ind, p = free1[0]
+                        free.append((ind, p1))
+            dum = [x for x in dum if x not in dum1]
+            free = [x for x in free if x not in free1]
+
+        # shift positions:
+        shift = 0
+        shifts = [0]*len(args)
+        for i in range(len(args)):
+            if i in elim:
+                shift += 2
+                continue
+            shifts[i] = shift
+        free = [(ind, p - shifts[pos_map[p]]) for (ind, p) in free if pos_map[p] not in elim]
+        dum = [(p0 - shifts[pos_map[p0]], p1 - shifts[pos_map[p1]]) for p0, p1 in dum if pos_map[p0] not in elim and pos_map[p1] not in elim]
+
+        res = ( sign*TensMul(*args) ).doit(deep=False)
+        if not isinstance(res, TensExpr):
+            return res
+        im = _IndexStructure.from_components_free_dum(res.components, free, dum)
+        return res._set_new_index_structure(im)
+
+    def _set_new_index_structure(self, im, is_canon_bp=False):
+        indices = im.get_indices()
+        return self._set_indices(*indices, is_canon_bp=is_canon_bp)
+
+    def _set_indices(self, *indices, is_canon_bp=False, **kw_args):
+        if len(indices) != self.ext_rank:
+            raise ValueError("indices length mismatch")
+        args = list(self.args)
+        pos = 0
+        for i, arg in enumerate(args):
+            if not isinstance(arg, TensExpr):
+                continue
+            assert isinstance(arg, Tensor)
+            ext_rank = arg.ext_rank
+            args[i] = arg._set_indices(*indices[pos:pos+ext_rank])
+            pos += ext_rank
+        return TensMul(*args, is_canon_bp=is_canon_bp).doit(deep=False)
+
+    @staticmethod
+    def _index_replacement_for_contract_metric(args, free, dum):
+        for arg in args:
+            if not isinstance(arg, TensExpr):
+                continue
+            assert isinstance(arg, Tensor)
+
+    def substitute_indices(self, *index_tuples):
+        new_args = []
+        for arg in self.args:
+            if isinstance(arg, TensExpr):
+                arg = arg.substitute_indices(*index_tuples)
+            new_args.append(arg)
+        return TensMul(*new_args).doit(deep=False)
+
+    def __call__(self, *indices):
+        deprecate_call()
+        free_args = self.free_args
+        indices = list(indices)
+        if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]:
+            raise ValueError('incompatible types')
+        if indices == free_args:
+            return self
+        t = self.substitute_indices(*list(zip(free_args, indices)))
+
+        # object is rebuilt in order to make sure that all contracted indices
+        # get recognized as dummies, but only if there are contracted indices.
+        if len({i if i.is_up else -i for i in indices}) != len(indices):
+            return t.func(*t.args)
+        return t
+
+    def _extract_data(self, replacement_dict):
+        args_indices, arrays = zip(*[arg._extract_data(replacement_dict) for arg in self.args if isinstance(arg, TensExpr)])
+        coeff = reduce(operator.mul, [a for a in self.args if not isinstance(a, TensExpr)], S.One)
+        indices, free, free_names, dummy_data = TensMul._indices_to_free_dum(args_indices)
+        dum = TensMul._dummy_data_to_dum(dummy_data)
+        ext_rank = self.ext_rank
+        free.sort(key=lambda x: x[1])
+        free_indices = [i[0] for i in free]
+        return free_indices, coeff*_TensorDataLazyEvaluator.data_contract_dum(arrays, dum, ext_rank)
+
+    @property
+    def data(self):
+        deprecate_data()
+        with ignore_warnings(SymPyDeprecationWarning):
+            dat = _tensor_data_substitution_dict[self.expand()]
+        return dat
+
+    @data.setter
+    def data(self, data):
+        deprecate_data()
+        raise ValueError("Not possible to set component data to a tensor expression")
+
+    @data.deleter
+    def data(self):
+        deprecate_data()
+        raise ValueError("Not possible to delete component data to a tensor expression")
+
+    def __iter__(self):
+        deprecate_data()
+        with ignore_warnings(SymPyDeprecationWarning):
+            if self.data is None:
+                raise ValueError("No iteration on abstract tensors")
+            return self.data.__iter__()
+
+    @staticmethod
+    def _dedupe_indices(new, exclude):
+        """
+        exclude: set
+        new: TensExpr
+
+        If ``new`` has any dummy indices that are in ``exclude``, return a version
+        of new with those indices replaced. If no replacements are needed,
+        return None
+
+        """
+        exclude = set(exclude)
+        dums_new = set(get_dummy_indices(new))
+        free_new = set(get_free_indices(new))
+
+        conflicts = dums_new.intersection(exclude)
+        if len(conflicts) == 0:
+            return None
+
+        """
+        ``exclude_for_gen`` is to be passed to ``_IndexStructure._get_generator_for_dummy_indices()``.
+        Since the latter does not use the index position for anything, we just
+        set it as ``None`` here.
+        """
+        exclude.update(dums_new)
+        exclude.update(free_new)
+        exclude_for_gen = [(i, None) for i in exclude]
+        gen = _IndexStructure._get_generator_for_dummy_indices(exclude_for_gen)
+        repl = {}
+        for d in conflicts:
+            if -d in repl.keys():
+                continue
+            newname = gen(d.tensor_index_type)
+            new_d = d.func(newname, *d.args[1:])
+            repl[d] = new_d
+            repl[-d] = -new_d
+
+        if len(repl) == 0:
+            return None
+
+        new_renamed = new._replace_indices(repl)
+        return new_renamed
+
+    def _dedupe_indices_in_rule(self, rule):
+        """
+        rule: dict
+
+        This applies TensMul._dedupe_indices on all values of rule.
+
+        """
+        index_rules = {k:v for k,v in rule.items() if isinstance(k, TensorIndex)}
+        other_rules = {k:v for k,v in rule.items() if k not in index_rules.keys()}
+        exclude = set(self.get_indices())
+
+        newrule = {}
+        newrule.update(index_rules)
+        exclude.update(index_rules.keys())
+        exclude.update(index_rules.values())
+        for old, new in other_rules.items():
+            new_renamed = TensMul._dedupe_indices(new, exclude)
+            if old == new or new_renamed is None:
+                newrule[old] = new
+            else:
+                newrule[old] = new_renamed
+                exclude.update(get_indices(new_renamed))
+        return newrule
+
+    def _eval_subs(self, old, new):
+        """
+        If new is an index which is already present in self as a dummy, the dummies in self should be renamed.
+        """
+
+        if not isinstance(new, TensorIndex):
+            return None
+
+        exclude = {new}
+        self_renamed = self._dedupe_indices(self, exclude)
+        if self_renamed is None:
+            return None
+        else:
+            return self_renamed._subs(old, new).doit(deep=False)
+
+    def _eval_rewrite_as_Indexed(self, *args, **kwargs):
+        from sympy.concrete.summations import Sum
+        index_symbols = [i.args[0] for i in self.get_indices()]
+        args = [arg.args[0] if isinstance(arg, Sum) else arg for arg in args]
+        expr = Mul.fromiter(args)
+        return self._check_add_Sum(expr, index_symbols)
+
+    def _eval_partial_derivative(self, s):
+        # Evaluation like Mul
+        terms = []
+        for i, arg in enumerate(self.args):
+            # checking whether some tensor instance is differentiated
+            # or some other thing is necessary, but ugly
+            if isinstance(arg, TensExpr):
+                d = arg._eval_partial_derivative(s)
+            else:
+                # do not call diff is s is no symbol
+                if s._diff_wrt:
+                    d = arg._eval_derivative(s)
+                else:
+                    d = S.Zero
+            if d:
+                terms.append(TensMul.fromiter(self.args[:i] + (d,) + self.args[i + 1:]).doit(deep=False))
+        return TensAdd.fromiter(terms).doit(deep=False)
+
+
+    def _matches_commutative(self, expr, repl_dict=None, old=False):
+        """
+        Match assuming all tensors commute. But note that we are not assuming anything about their symmetry under index permutations.
+        """
+        #Take care of the various possible types for expr.
+        if not isinstance(expr, TensMul):
+            if isinstance(expr, (TensExpr, Expr)):
+                expr = TensMul(expr)
+            else:
+                return None
+
+        #The code that follows assumes expr is a TensMul
+
+        if repl_dict is None:
+            repl_dict = {}
+        else:
+            repl_dict = repl_dict.copy()
+
+            #Make sure that none of the dummy indices in self, expr conflict with the values already present in repl_dict. This may happen due to automatic index relabelling when rem_query and rem_expr are formed later on in this function (it calls itself recursively).
+            indices = [k for k in repl_dict.values() if isinstance(k ,TensorIndex)]
+
+            def dedupe(expr):
+                renamed = TensMul._dedupe_indices(expr, indices)
+                if renamed is not None:
+                    return renamed
+                else:
+                    return expr
+
+            self = dedupe(self)
+            expr = dedupe(expr)
+
+        #Find the non-tensor part of expr. This need not be the same as expr.coeff when expr.doit() has not been called.
+        expr_coeff = reduce(lambda a, b: a*b, [arg for arg in expr.args if not isinstance(arg, TensExpr)], S.One)
+
+        # handle simple patterns
+        if self == expr:
+            return repl_dict
+
+        if len(_get_wilds(self)) == 0:
+            return self._matches_simple(expr, repl_dict, old)
+
+        def siftkey(arg):
+            if isinstance(arg, WildTensor):
+                return "WildTensor"
+            elif isinstance(arg, (Tensor, TensExpr)):
+                return "Tensor"
+            else:
+                return "coeff"
+
+        query_sifted = sift(self.args, siftkey)
+        expr_sifted = sift(expr.args, siftkey)
+
+        #Sanity checks
+        if "coeff" in query_sifted.keys():
+            if TensMul(*query_sifted["coeff"]).doit(deep=False) != self.coeff:
+                raise NotImplementedError(f"Found something that we do not know to handle: {query_sifted['coeff']}")
+        if "coeff" in expr_sifted.keys():
+            if TensMul(*expr_sifted["coeff"]).doit(deep=False) != expr_coeff:
+                raise NotImplementedError(f"Found something that we do not know to handle: {expr_sifted['coeff']}")
+
+        query_tens_heads = {tuple(getattr(x, "components", [])) for x in query_sifted["Tensor"]} #We use getattr because, e.g. TensAdd does not have the 'components' attribute.
+        expr_tens_heads = {tuple(getattr(x, "components", [])) for x in expr_sifted["Tensor"]}
+        if not query_tens_heads.issubset(expr_tens_heads):
+            #Some tensorheads in self are not present in the expr
+            return None
+
+        #Try to match all non-wild tensors of self with tensors that compose expr
+        if len(query_sifted["Tensor"]) > 0:
+            q_tensor = query_sifted["Tensor"][0]
+            """
+            We need to iterate over all possible symmetrized forms of q_tensor since the matches given by some of them may map dummy indices to free indices; the information about which indices are dummy/free will only be available later, when we are doing rem_q.matches(rem_e)
+            """
+            for q_tens in q_tensor._get_symmetrized_forms():
+                for e in expr_sifted["Tensor"]:
+                    if isinstance(q_tens, TensMul):
+                        #q_tensor got a minus sign due to this permutation.
+                        sign = -1
+                    else:
+                        sign = 1
+
+                    """
+                    _matches is used here since we are already iterating over index permutations of q_tensor. Also note that the sign is removed from q_tensor, and will later be put into rem_q.
+                    """
+                    m = (sign*q_tens)._matches(e)
+                    if m is None:
+                        continue
+
+                    rem_query = self.func(sign, *[a for a in self.args if a != q_tensor]).doit(deep=False)
+                    rem_expr = expr.func(*[a for a in expr.args if a != e]).doit(deep=False)
+                    tmp_repl = {}
+                    tmp_repl.update(repl_dict)
+                    tmp_repl.update(m)
+                    rem_m = rem_query.matches(rem_expr, repl_dict=tmp_repl)
+                    if rem_m is not None:
+                        #Check that contracted indices are not mapped to different indices.
+                        internally_consistent = True
+                        for k in rem_m.keys():
+                            if isinstance(k,TensorIndex):
+                                if -k in rem_m.keys() and rem_m[-k] != -rem_m[k]:
+                                    internally_consistent = False
+                                    break
+                        if internally_consistent:
+                            repl_dict.update(rem_m)
+                            return repl_dict
+
+            return None
+
+        #Try to match WildTensor instances which have indices
+        matched_e_tensors = []
+        remaining_e_tensors = expr_sifted["Tensor"]
+        indexless_wilds, wilds = sift(query_sifted["WildTensor"], lambda x: len(x.get_free_indices()) == 0, binary=True)
+
+        for w in wilds:
+            free_this_wild = set(w.get_free_indices())
+            tensors_to_try = []
+            for t in remaining_e_tensors:
+                free = t.get_free_indices()
+                shares_indices_with_wild = True
+                for i in free:
+                    if all(j.matches(i) is None for j in free_this_wild):
+                        #The index i matches none of the indices in free_this_wild
+                        shares_indices_with_wild = False
+                if shares_indices_with_wild:
+                    tensors_to_try.append(t)
+
+            m = w.matches(TensMul(*tensors_to_try).doit(deep=False) )
+            if m is None:
+                return None
+            else:
+                for tens in tensors_to_try:
+                    matched_e_tensors.append(tens)
+                repl_dict.update(m)
+
+        #Try to match indexless WildTensor instances
+        remaining_e_tensors = [t for t in expr_sifted["Tensor"] if t not in matched_e_tensors]
+        if len(indexless_wilds) > 0:
+            #If there are any remaining tensors, match them with the indexless WildTensor
+            m =  indexless_wilds[0].matches( TensMul(1,*remaining_e_tensors).doit(deep=False) )
+            if m is None:
+                return None
+            else:
+                repl_dict.update(m)
+        elif len(remaining_e_tensors) > 0:
+            return None
+
+        #Try to match the non-tensorial coefficient
+        m = self.coeff.matches(expr_coeff, old=old)
+        if m is None:
+            return None
+        else:
+            repl_dict.update(m)
+
+        return repl_dict
+
+    def matches(self, expr, repl_dict=None, old=False):
+        expr = sympify(expr)
+
+        if repl_dict is None:
+            repl_dict = {}
+        else:
+            repl_dict = repl_dict.copy()
+
+        commute = all(arg.component.comm == 0 for arg in expr.args if isinstance(arg, Tensor))
+        if commute:
+            return self._matches_commutative(expr, repl_dict, old)
+        else:
+            raise NotImplementedError("Tensor matching not implemented for non-commuting tensors")
+
+class TensorElement(TensExpr):
+    """
+    Tensor with evaluated components.
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorSymmetry
+    >>> from sympy import symbols
+    >>> L = TensorIndexType("L")
+    >>> i, j, k = symbols("i j k")
+    >>> A = TensorHead("A", [L, L], TensorSymmetry.fully_symmetric(2))
+    >>> A(i, j).get_free_indices()
+    [i, j]
+
+    If we want to set component ``i`` to a specific value, use the
+    ``TensorElement`` class:
+
+    >>> from sympy.tensor.tensor import TensorElement
+    >>> te = TensorElement(A(i, j), {i: 2})
+
+    As index ``i`` has been accessed (``{i: 2}`` is the evaluation of its 3rd
+    element), the free indices will only contain ``j``:
+
+    >>> te.get_free_indices()
+    [j]
+    """
+
+    def __new__(cls, expr, index_map):
+        if not isinstance(expr, Tensor):
+            # remap
+            if not isinstance(expr, TensExpr):
+                raise TypeError("%s is not a tensor expression" % expr)
+            return expr.func(*[TensorElement(arg, index_map) for arg in expr.args])
+        expr_free_indices = expr.get_free_indices()
+        name_translation = {i.args[0]: i for i in expr_free_indices}
+        index_map = {name_translation.get(index, index): value for index, value in index_map.items()}
+        index_map = {index: value for index, value in index_map.items() if index in expr_free_indices}
+        if len(index_map) == 0:
+            return expr
+        free_indices = [i for i in expr_free_indices if i not in index_map.keys()]
+        index_map = Dict(index_map)
+        obj = TensExpr.__new__(cls, expr, index_map)
+        obj._free_indices = free_indices
+        return obj
+
+    @property
+    def free(self):
+        return [(index, i) for i, index in enumerate(self.get_free_indices())]
+
+    @property
+    def dum(self):
+        # TODO: inherit dummies from expr
+        return []
+
+    @property
+    def expr(self):
+        return self._args[0]
+
+    @property
+    def index_map(self):
+        return self._args[1]
+
+    @property
+    def coeff(self):
+        return S.One
+
+    @property
+    def nocoeff(self):
+        return self
+
+    def get_free_indices(self):
+        return self._free_indices
+
+    def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr:
+        # TODO: can be improved:
+        return self.xreplace(repl)
+
+    def get_indices(self):
+        return self.get_free_indices()
+
+    def _extract_data(self, replacement_dict):
+        ret_indices, array = self.expr._extract_data(replacement_dict)
+        index_map = self.index_map
+        slice_tuple = tuple(index_map.get(i, slice(None)) for i in ret_indices)
+        ret_indices = [i for i in ret_indices if i not in index_map]
+        array = array.__getitem__(slice_tuple)
+        return ret_indices, array
+
+
+class WildTensorHead(TensorHead):
+    """
+    A wild object that is used to create ``WildTensor`` instances
+
+    Explanation
+    ===========
+
+    Examples
+    ========
+    >>> from sympy.tensor.tensor import TensorHead, TensorIndex, WildTensorHead, TensorIndexType
+    >>> R3 = TensorIndexType('R3', dim=3)
+    >>> p = TensorIndex('p', R3)
+    >>> q = TensorIndex('q', R3)
+
+    A WildTensorHead can be created without specifying a ``TensorIndexType``
+
+    >>> W = WildTensorHead("W")
+
+    Calling it with a ``TensorIndex`` creates a ``WildTensor`` instance.
+
+    >>> type(W(p))
+    
+
+    The ``TensorIndexType`` is automatically detected from the index that is passed
+
+    >>> W(p).component
+    W(R3)
+
+    Calling it with no indices returns an object that can match tensors with any number of indices.
+
+    >>> K = TensorHead('K', [R3])
+    >>> Q = TensorHead('Q', [R3, R3])
+    >>> W().matches(K(p))
+    {W: K(p)}
+    >>> W().matches(Q(p,q))
+    {W: Q(p, q)}
+
+    If you want to ignore the order of indices while matching, pass ``unordered_indices=True``.
+
+    >>> U = WildTensorHead("U", unordered_indices=True)
+    >>> W(p,q).matches(Q(q,p))
+    >>> U(p,q).matches(Q(q,p))
+    {U(R3,R3): _WildTensExpr(Q(q, p))}
+
+    Parameters
+    ==========
+    name : name of the tensor
+    unordered_indices : whether the order of the indices matters for matching
+        (default: False)
+
+    See also
+    ========
+    ``WildTensor``
+    ``TensorHead``
+
+    """
+    def __new__(cls, name, index_types=None, symmetry=None, comm=0,  unordered_indices=False):
+        if isinstance(name, str):
+            name_symbol = Symbol(name)
+        elif isinstance(name, Symbol):
+            name_symbol = name
+        else:
+            raise ValueError("invalid name")
+
+        if index_types is None:
+            index_types = []
+
+        if symmetry is None:
+            symmetry = TensorSymmetry.no_symmetry(len(index_types))
+        else:
+            assert symmetry.rank == len(index_types)
+
+        if symmetry != TensorSymmetry.no_symmetry(len(index_types)):
+            raise NotImplementedError("Wild matching based on symmetry is not implemented.")
+
+        obj = Basic.__new__(cls, name_symbol, Tuple(*index_types), sympify(symmetry), sympify(comm), sympify(unordered_indices))
+
+        return obj
+
+    @property
+    def unordered_indices(self):
+        return self.args[4]
+
+    def __call__(self, *indices, **kwargs):
+        tensor = WildTensor(self, indices, **kwargs)
+        return tensor.doit()
+
+
+class WildTensor(Tensor):
+    """
+    A wild object which matches ``Tensor`` instances
+
+    Explanation
+    ===========
+    This is instantiated by attaching indices to a ``WildTensorHead`` instance.
+
+    Examples
+    ========
+    >>> from sympy.tensor.tensor import TensorHead, TensorIndex, WildTensorHead, TensorIndexType
+    >>> W = WildTensorHead("W")
+    >>> R3 = TensorIndexType('R3', dim=3)
+    >>> p = TensorIndex('p', R3)
+    >>> q = TensorIndex('q', R3)
+    >>> K = TensorHead('K', [R3])
+    >>> Q = TensorHead('Q', [R3, R3])
+
+    Matching also takes the indices into account
+    >>> W(p).matches(K(p))
+    {W(R3): _WildTensExpr(K(p))}
+    >>> W(p).matches(K(q))
+    >>> W(p).matches(K(-p))
+
+    If you want to match objects with any number of indices, just use a ``WildTensor`` with no indices.
+    >>> W().matches(K(p))
+    {W: K(p)}
+    >>> W().matches(Q(p,q))
+    {W: Q(p, q)}
+
+    See Also
+    ========
+    ``WildTensorHead``
+    ``Tensor``
+
+    """
+    def __new__(cls, tensor_head, indices, **kw_args):
+        is_canon_bp = kw_args.pop("is_canon_bp", False)
+
+        if tensor_head.func == TensorHead:
+            """
+            If someone tried to call WildTensor by supplying a TensorHead (not a WildTensorHead), return a normal tensor instead. This is helpful when using subs on an expression to replace occurrences of a WildTensorHead with a TensorHead.
+            """
+            return Tensor(tensor_head, indices, is_canon_bp=is_canon_bp, **kw_args)
+        elif tensor_head.func == _WildTensExpr:
+            return tensor_head(*indices)
+
+        indices = cls._parse_indices(tensor_head, indices)
+        index_types = [ind.tensor_index_type for ind in indices]
+        tensor_head = tensor_head.func(
+            tensor_head.name,
+            index_types,
+            symmetry=None,
+            comm=tensor_head.comm,
+            unordered_indices=tensor_head.unordered_indices,
+            )
+
+        obj = Basic.__new__(cls, tensor_head, Tuple(*indices))
+        obj.name = tensor_head.name
+        obj._index_structure = _IndexStructure.from_indices(*indices)
+        obj._free = obj._index_structure.free[:]
+        obj._dum = obj._index_structure.dum[:]
+        obj._ext_rank = obj._index_structure._ext_rank
+        obj._coeff = S.One
+        obj._nocoeff = obj
+        obj._component = tensor_head
+        obj._components = [tensor_head]
+        if tensor_head.rank != len(indices):
+            raise ValueError("wrong number of indices")
+        obj.is_canon_bp = is_canon_bp
+        obj._index_map = obj._build_index_map(indices, obj._index_structure)
+
+        return obj
+
+
+    def matches(self, expr, repl_dict=None, old=False):
+        if not isinstance(expr, TensExpr) and expr != S(1):
+            return None
+
+        if repl_dict is None:
+            repl_dict = {}
+        else:
+            repl_dict = repl_dict.copy()
+
+        if len(self.indices) > 0:
+            if not hasattr(expr, "get_free_indices"):
+                return None
+            expr_indices = expr.get_free_indices()
+            if len(expr_indices) != len(self.indices):
+                return None
+            if self._component.unordered_indices:
+                m = self._match_indices_ignoring_order(expr)
+                if m is None:
+                    return None
+                else:
+                    repl_dict.update(m)
+            else:
+                for i in range(len(expr_indices)):
+                    m = self.indices[i].matches(expr_indices[i])
+                    if m is None:
+                        return None
+                    else:
+                        repl_dict.update(m)
+
+            repl_dict[self.component] = _WildTensExpr(expr)
+        else:
+            #If no indices were passed to the WildTensor, it may match tensors with any number of indices.
+            repl_dict[self] = expr
+
+        return repl_dict
+
+    def _match_indices_ignoring_order(self, expr, repl_dict=None, old=False):
+        """
+        Helper method for matches. Checks if the indices of self and expr
+        match disregarding index ordering.
+        """
+        if repl_dict is None:
+            repl_dict = {}
+        else:
+            repl_dict = repl_dict.copy()
+
+        def siftkey(ind):
+            if isinstance(ind, WildTensorIndex):
+                if ind.ignore_updown:
+                    return "wild, updown"
+                else:
+                    return "wild"
+            else:
+                return "nonwild"
+
+        indices_sifted = sift(self.indices, siftkey)
+
+        matched_indices = []
+        expr_indices_remaining = expr.get_indices()
+        for ind in indices_sifted["nonwild"]:
+            matched_this_ind = False
+            for e_ind in expr_indices_remaining:
+                if e_ind in matched_indices:
+                    continue
+                m = ind.matches(e_ind)
+                if m is not None:
+                    matched_this_ind = True
+                    repl_dict.update(m)
+                    matched_indices.append(e_ind)
+                    break
+            if not matched_this_ind:
+                return None
+
+        expr_indices_remaining = [i for i in expr_indices_remaining if i not in matched_indices]
+        for ind in indices_sifted["wild"]:
+            matched_this_ind = False
+            for e_ind in expr_indices_remaining:
+                m = ind.matches(e_ind)
+                if m is not None:
+                    if -ind in repl_dict.keys() and -repl_dict[-ind] != m[ind]:
+                        return None
+                    matched_this_ind = True
+                    repl_dict.update(m)
+                    matched_indices.append(e_ind)
+                    break
+            if not matched_this_ind:
+                return None
+
+        expr_indices_remaining = [i for i in expr_indices_remaining if i not in matched_indices]
+        for ind in indices_sifted["wild, updown"]:
+            matched_this_ind = False
+            for e_ind in expr_indices_remaining:
+                m = ind.matches(e_ind)
+                if m is not None:
+                    if -ind in repl_dict.keys() and -repl_dict[-ind] != m[ind]:
+                        return None
+                    matched_this_ind = True
+                    repl_dict.update(m)
+                    matched_indices.append(e_ind)
+                    break
+            if not matched_this_ind:
+                return None
+
+        if len(matched_indices) < len(self.indices):
+            return None
+        else:
+            return repl_dict
+
+class WildTensorIndex(TensorIndex):
+    """
+    A wild object that matches TensorIndex instances.
+
+    Examples
+    ========
+    >>> from sympy.tensor.tensor import TensorIndex, TensorIndexType, WildTensorIndex
+    >>> R3 = TensorIndexType('R3', dim=3)
+    >>> p = TensorIndex("p", R3)
+
+    By default, covariant indices only match with covariant indices (and
+    similarly for contravariant)
+
+    >>> q = WildTensorIndex("q", R3)
+    >>> (q).matches(p)
+    {q: p}
+    >>> (q).matches(-p)
+
+    If you want matching to ignore whether the index is co/contra-variant, set
+    ignore_updown=True
+
+    >>> r = WildTensorIndex("r", R3, ignore_updown=True)
+    >>> (r).matches(-p)
+    {r: -p}
+    >>> (r).matches(p)
+    {r: p}
+
+    Parameters
+    ==========
+    name : name of the index (string), or ``True`` if you want it to be
+        automatically assigned
+    tensor_index_type : ``TensorIndexType`` of the index
+    is_up :  flag for contravariant index (is_up=True by default)
+    ignore_updown : bool, Whether this should match both co- and contra-variant
+        indices (default:False)
+    """
+    def __new__(cls, name, tensor_index_type, is_up=True, ignore_updown=False):
+        if isinstance(name, str):
+            name_symbol = Symbol(name)
+        elif isinstance(name, Symbol):
+            name_symbol = name
+        elif name is True:
+            name = "_i{}".format(len(tensor_index_type._autogenerated))
+            name_symbol = Symbol(name)
+            tensor_index_type._autogenerated.append(name_symbol)
+        else:
+            raise ValueError("invalid name")
+
+        is_up = sympify(is_up)
+        ignore_updown = sympify(ignore_updown)
+        return Basic.__new__(cls, name_symbol, tensor_index_type, is_up, ignore_updown)
+
+    @property
+    def ignore_updown(self):
+        return self.args[3]
+
+    def __neg__(self):
+        t1 = WildTensorIndex(self.name, self.tensor_index_type,
+                (not self.is_up), self.ignore_updown)
+        return t1
+
+    def matches(self, expr, repl_dict=None, old=False):
+        if not isinstance(expr, TensorIndex):
+            return None
+        if self.tensor_index_type != expr.tensor_index_type:
+            return None
+        if not self.ignore_updown:
+            if self.is_up != expr.is_up:
+                return None
+
+        if repl_dict is None:
+            repl_dict = {}
+        else:
+            repl_dict = repl_dict.copy()
+
+        repl_dict[self] = expr
+        return repl_dict
+
+
+class _WildTensExpr(Basic):
+    """
+    INTERNAL USE ONLY
+
+    This is an object that helps with replacement of WildTensors in expressions.
+    When this object is set as the tensor_head of a WildTensor, it replaces the
+    WildTensor by a TensExpr (passed when initializing this object).
+
+    Examples
+    ========
+    >>> from sympy.tensor.tensor import WildTensorHead, TensorIndex, TensorHead, TensorIndexType
+    >>> W = WildTensorHead("W")
+    >>> R3 = TensorIndexType('R3', dim=3)
+    >>> p = TensorIndex('p', R3)
+    >>> q = TensorIndex('q', R3)
+    >>> K = TensorHead('K', [R3])
+    >>> print( ( K(p) ).replace( W(p), W(q)*W(-q)*W(p) ) )
+    K(R_0)*K(-R_0)*K(p)
+
+    """
+    def __init__(self, expr):
+        if not isinstance(expr, TensExpr):
+            raise TypeError("_WildTensExpr expects a TensExpr as argument")
+        self.expr = expr
+
+    def __call__(self, *indices):
+        return self.expr._replace_indices(dict(zip(self.expr.get_free_indices(), indices)))
+
+    def __neg__(self):
+        return self.func(self.expr*S.NegativeOne)
+
+    def __abs__(self):
+        raise NotImplementedError
+
+    def __add__(self, other):
+        if other.func != self.func:
+            raise TypeError(f"Cannot add {self.func} to {other.func}")
+        return self.func(self.expr+other.expr)
+
+    def __radd__(self, other):
+        if other.func != self.func:
+            raise TypeError(f"Cannot add {self.func} to {other.func}")
+        return self.func(other.expr+self.expr)
+
+    def __sub__(self, other):
+        return self + (-other)
+
+    def __rsub__(self, other):
+        return other + (-self)
+
+    def __mul__(self, other):
+        raise NotImplementedError
+
+    def __rmul__(self, other):
+        raise NotImplementedError
+
+    def __truediv__(self, other):
+        raise NotImplementedError
+
+    def __rtruediv__(self, other):
+        raise NotImplementedError
+
+    def __pow__(self, other):
+        raise NotImplementedError
+
+    def __rpow__(self, other):
+        raise NotImplementedError
+
+
+def canon_bp(p):
+    """
+    Butler-Portugal canonicalization. See ``tensor_can.py`` from the
+    combinatorics module for the details.
+    """
+    if isinstance(p, TensExpr):
+        return p.canon_bp()
+    return p
+
+
+def tensor_mul(*a):
+    """
+    product of tensors
+    """
+    if not a:
+        return TensMul.from_data(S.One, [], [], [])
+    t = a[0]
+    for tx in a[1:]:
+        t = t*tx
+    return t
+
+
+def riemann_cyclic_replace(t_r):
+    """
+    replace Riemann tensor with an equivalent expression
+
+    ``R(m,n,p,q) -> 2/3*R(m,n,p,q) - 1/3*R(m,q,n,p) + 1/3*R(m,p,n,q)``
+
+    """
+    free = sorted(t_r.free, key=lambda x: x[1])
+    m, n, p, q = [x[0] for x in free]
+    t0 = t_r*Rational(2, 3)
+    t1 = -t_r.substitute_indices((m,m),(n,q),(p,n),(q,p))*Rational(1, 3)
+    t2 = t_r.substitute_indices((m,m),(n,p),(p,n),(q,q))*Rational(1, 3)
+    t3 = t0 + t1 + t2
+    return t3
+
+def riemann_cyclic(t2):
+    """
+    Replace each Riemann tensor with an equivalent expression
+    satisfying the cyclic identity.
+
+    This trick is discussed in the reference guide to Cadabra.
+
+    Examples
+    ========
+
+    >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, riemann_cyclic, TensorSymmetry
+    >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+    >>> i, j, k, l = tensor_indices('i,j,k,l', Lorentz)
+    >>> R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
+    >>> t = R(i,j,k,l)*(R(-i,-j,-k,-l) - 2*R(-i,-k,-j,-l))
+    >>> riemann_cyclic(t)
+    0
+    """
+    t2 = t2.expand()
+    if isinstance(t2, (TensMul, Tensor)):
+        args = [t2]
+    else:
+        args = t2.args
+    a1 = [x.split() for x in args]
+    a2 = [[riemann_cyclic_replace(tx) for tx in y] for y in a1]
+    a3 = [tensor_mul(*v) for v in a2]
+    t3 = TensAdd(*a3).doit(deep=False)
+    if not t3:
+        return t3
+    else:
+        return canon_bp(t3)
+
+
+def get_lines(ex, index_type):
+    """
+    Returns ``(lines, traces, rest)`` for an index type,
+    where ``lines`` is the list of list of positions of a matrix line,
+    ``traces`` is the list of list of traced matrix lines,
+    ``rest`` is the rest of the elements of the tensor.
+    """
+    def _join_lines(a):
+        i = 0
+        while i < len(a):
+            x = a[i]
+            xend = x[-1]
+            xstart = x[0]
+            hit = True
+            while hit:
+                hit = False
+                for j in range(i + 1, len(a)):
+                    if j >= len(a):
+                        break
+                    if a[j][0] == xend:
+                        hit = True
+                        x.extend(a[j][1:])
+                        xend = x[-1]
+                        a.pop(j)
+                        continue
+                    if a[j][0] == xstart:
+                        hit = True
+                        a[i] = reversed(a[j][1:]) + x
+                        x = a[i]
+                        xstart = a[i][0]
+                        a.pop(j)
+                        continue
+                    if a[j][-1] == xend:
+                        hit = True
+                        x.extend(reversed(a[j][:-1]))
+                        xend = x[-1]
+                        a.pop(j)
+                        continue
+                    if a[j][-1] == xstart:
+                        hit = True
+                        a[i] = a[j][:-1] + x
+                        x = a[i]
+                        xstart = x[0]
+                        a.pop(j)
+                        continue
+            i += 1
+        return a
+
+    arguments = ex.args
+    dt = {}
+    for c in ex.args:
+        if not isinstance(c, TensExpr):
+            continue
+        if c in dt:
+            continue
+        index_types = c.index_types
+        a = []
+        for i in range(len(index_types)):
+            if index_types[i] is index_type:
+                a.append(i)
+        if len(a) > 2:
+            raise ValueError('at most two indices of type %s allowed' % index_type)
+        if len(a) == 2:
+            dt[c] = a
+    #dum = ex.dum
+    lines = []
+    traces = []
+    traces1 = []
+    #indices_to_args_pos = ex._get_indices_to_args_pos()
+    # TODO: add a dum_to_components_map ?
+    for p0, p1, c0, c1 in ex.dum_in_args:
+        if arguments[c0] not in dt:
+            continue
+        if c0 == c1:
+            traces.append([c0])
+            continue
+        ta0 = dt[arguments[c0]]
+        ta1 = dt[arguments[c1]]
+        if p0 not in ta0:
+            continue
+        if ta0.index(p0) == ta1.index(p1):
+            # case gamma(i,s0,-s1) in c0, gamma(j,-s0,s2) in c1;
+            # to deal with this case one could add to the position
+            # a flag for transposition;
+            # one could write [(c0, False), (c1, True)]
+            raise NotImplementedError
+        # if p0 == ta0[1] then G in pos c0 is mult on the right by G in c1
+        # if p0 == ta0[0] then G in pos c1 is mult on the right by G in c0
+        ta0 = dt[arguments[c0]]
+        b0, b1 = (c0, c1) if p0 == ta0[1]  else (c1, c0)
+        lines1 = lines.copy()
+        for line in lines:
+            if line[-1] == b0:
+                if line[0] == b1:
+                    n = line.index(min(line))
+                    traces1.append(line)
+                    traces.append(line[n:] + line[:n])
+                else:
+                    line.append(b1)
+                break
+            elif line[0] == b1:
+                line.insert(0, b0)
+                break
+        else:
+            lines1.append([b0, b1])
+
+        lines = [x for x in lines1 if x not in traces1]
+        lines = _join_lines(lines)
+    rest = []
+    for line in lines:
+        for y in line:
+            rest.append(y)
+    for line in traces:
+        for y in line:
+            rest.append(y)
+    rest = [x for x in range(len(arguments)) if x not in rest]
+
+    return lines, traces, rest
+
+
+def get_free_indices(t):
+    if not isinstance(t, TensExpr):
+        return ()
+    return t.get_free_indices()
+
+
+def get_indices(t):
+    if not isinstance(t, TensExpr):
+        return ()
+    return t.get_indices()
+
+def get_dummy_indices(t):
+    if not isinstance(t, TensExpr):
+        return ()
+    inds = t.get_indices()
+    free = t.get_free_indices()
+    return [i for i in inds if i not in free]
+
+def get_index_structure(t):
+    if isinstance(t, TensExpr):
+        return t._index_structure
+    return _IndexStructure([], [], [], [])
+
+
+def get_coeff(t):
+    if isinstance(t, Tensor):
+        return S.One
+    if isinstance(t, TensMul):
+        return t.coeff
+    if isinstance(t, TensExpr):
+        raise ValueError("no coefficient associated to this tensor expression")
+    return t
+
+def contract_metric(t, g):
+    if isinstance(t, TensExpr):
+        return t.contract_metric(g)
+    return t
+
+def perm2tensor(t, g, is_canon_bp=False):
+    """
+    Returns the tensor corresponding to the permutation ``g``
+
+    For further details, see the method in ``TIDS`` with the same name.
+    """
+    if not isinstance(t, TensExpr):
+        return t
+    elif isinstance(t, (Tensor, TensMul)):
+        nim = get_index_structure(t).perm2tensor(g, is_canon_bp=is_canon_bp)
+        res = t._set_new_index_structure(nim, is_canon_bp=is_canon_bp)
+        if g[-1] != len(g) - 1:
+            return -res
+
+        return res
+    raise NotImplementedError()
+
+
+def substitute_indices(t, *index_tuples):
+    if not isinstance(t, TensExpr):
+        return t
+    return t.substitute_indices(*index_tuples)
+
+
+def _get_wilds(expr):
+    return list(expr.atoms(Wild, WildFunction, WildTensor, WildTensorIndex, WildTensorHead))
+
+
+def get_postprocessor(cls):
+    def _postprocessor(expr):
+        tens_class = {Mul: TensMul, Add: TensAdd}[cls]
+        if any(isinstance(a, TensExpr) for a in expr.args):
+            return tens_class(*expr.args)
+        else:
+            return expr
+
+    return _postprocessor
+
+Basic._constructor_postprocessor_mapping[TensExpr] = {
+    "Mul": [get_postprocessor(Mul)],
+}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/tests/test_functions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/tests/test_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae40865d1bddffaa976dc3d94ae1ef1b6c97ca35
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/tests/test_functions.py
@@ -0,0 +1,57 @@
+from sympy.tensor.functions import TensorProduct
+from sympy.matrices.dense import Matrix
+from sympy.matrices.expressions.matexpr import MatrixSymbol
+from sympy.tensor.array import Array
+from sympy.abc import x, y, z
+from sympy.abc import i, j, k, l
+
+
+A = MatrixSymbol("A", 3, 3)
+B = MatrixSymbol("B", 3, 3)
+C = MatrixSymbol("C", 3, 3)
+
+
+def test_TensorProduct_construction():
+    assert TensorProduct(3, 4) == 12
+    assert isinstance(TensorProduct(A, A), TensorProduct)
+
+    expr = TensorProduct(TensorProduct(x, y), z)
+    assert expr == x*y*z
+
+    expr = TensorProduct(TensorProduct(A, B), C)
+    assert expr == TensorProduct(A, B, C)
+
+    expr = TensorProduct(Matrix.eye(2), Array([[0, -1], [1, 0]]))
+    assert expr == Array([
+        [
+            [[0, -1], [1, 0]],
+            [[0, 0], [0, 0]]
+        ],
+        [
+            [[0, 0], [0, 0]],
+            [[0, -1], [1, 0]]
+        ]
+    ])
+
+
+def test_TensorProduct_shape():
+
+    expr = TensorProduct(3, 4, evaluate=False)
+    assert expr.shape == ()
+    assert expr.rank() == 0
+
+    expr = TensorProduct(Array([1, 2]), Array([x, y]), evaluate=False)
+    assert expr.shape == (2, 2)
+    assert expr.rank() == 2
+    expr = TensorProduct(expr, expr, evaluate=False)
+    assert expr.shape == (2, 2, 2, 2)
+    assert expr.rank() == 4
+
+    expr = TensorProduct(Matrix.eye(2), Array([[0, -1], [1, 0]]), evaluate=False)
+    assert expr.shape == (2, 2, 2, 2)
+    assert expr.rank() == 4
+
+
+def test_TensorProduct_getitem():
+    expr = TensorProduct(A, B)
+    assert expr[i, j, k, l] == A[i, j]*B[k, l]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/tests/test_index_methods.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/tests/test_index_methods.py
new file mode 100644
index 0000000000000000000000000000000000000000..df20f7e7c1ab392321e8350b95dd07c5639c1865
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/tests/test_index_methods.py
@@ -0,0 +1,227 @@
+from sympy.core import symbols, S, Pow, Function
+from sympy.functions import exp
+from sympy.testing.pytest import raises
+from sympy.tensor.indexed import Idx, IndexedBase
+from sympy.tensor.index_methods import IndexConformanceException
+
+from sympy.tensor.index_methods import (get_contraction_structure, get_indices)
+
+
+def test_trivial_indices():
+    x, y = symbols('x y')
+    assert get_indices(x) == (set(), {})
+    assert get_indices(x*y) == (set(), {})
+    assert get_indices(x + y) == (set(), {})
+    assert get_indices(x**y) == (set(), {})
+
+
+def test_get_indices_Indexed():
+    x = IndexedBase('x')
+    i, j = Idx('i'), Idx('j')
+    assert get_indices(x[i, j]) == ({i, j}, {})
+    assert get_indices(x[j, i]) == ({j, i}, {})
+
+
+def test_get_indices_Idx():
+    f = Function('f')
+    i, j = Idx('i'), Idx('j')
+    assert get_indices(f(i)*j) == ({i, j}, {})
+    assert get_indices(f(j, i)) == ({j, i}, {})
+    assert get_indices(f(i)*i) == (set(), {})
+
+
+def test_get_indices_mul():
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i, j = Idx('i'), Idx('j')
+    assert get_indices(x[j]*y[i]) == ({i, j}, {})
+    assert get_indices(x[i]*y[j]) == ({i, j}, {})
+
+
+def test_get_indices_exceptions():
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i, j = Idx('i'), Idx('j')
+    raises(IndexConformanceException, lambda: get_indices(x[i] + y[j]))
+
+
+def test_scalar_broadcast():
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i, j = Idx('i'), Idx('j')
+    assert get_indices(x[i] + y[i, i]) == ({i}, {})
+    assert get_indices(x[i] + y[j, j]) == ({i}, {})
+
+
+def test_get_indices_add():
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    A = IndexedBase('A')
+    i, j, k = Idx('i'), Idx('j'), Idx('k')
+    assert get_indices(x[i] + 2*y[i]) == ({i}, {})
+    assert get_indices(y[i] + 2*A[i, j]*x[j]) == ({i}, {})
+    assert get_indices(y[i] + 2*(x[i] + A[i, j]*x[j])) == ({i}, {})
+    assert get_indices(y[i] + x[i]*(A[j, j] + 1)) == ({i}, {})
+    assert get_indices(
+        y[i] + x[i]*x[j]*(y[j] + A[j, k]*x[k])) == ({i}, {})
+
+
+def test_get_indices_Pow():
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    A = IndexedBase('A')
+    i, j, k = Idx('i'), Idx('j'), Idx('k')
+    assert get_indices(Pow(x[i], y[j])) == ({i, j}, {})
+    assert get_indices(Pow(x[i, k], y[j, k])) == ({i, j, k}, {})
+    assert get_indices(Pow(A[i, k], y[k] + A[k, j]*x[j])) == ({i, k}, {})
+    assert get_indices(Pow(2, x[i])) == get_indices(exp(x[i]))
+
+    # test of a design decision, this may change:
+    assert get_indices(Pow(x[i], 2)) == ({i}, {})
+
+
+def test_get_contraction_structure_basic():
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i, j = Idx('i'), Idx('j')
+    assert get_contraction_structure(x[i]*y[j]) == {None: {x[i]*y[j]}}
+    assert get_contraction_structure(x[i] + y[j]) == {None: {x[i], y[j]}}
+    assert get_contraction_structure(x[i]*y[i]) == {(i,): {x[i]*y[i]}}
+    assert get_contraction_structure(
+        1 + x[i]*y[i]) == {None: {S.One}, (i,): {x[i]*y[i]}}
+    assert get_contraction_structure(x[i]**y[i]) == {None: {x[i]**y[i]}}
+
+
+def test_get_contraction_structure_complex():
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    A = IndexedBase('A')
+    i, j, k = Idx('i'), Idx('j'), Idx('k')
+    expr1 = y[i] + A[i, j]*x[j]
+    d1 = {None: {y[i]}, (j,): {A[i, j]*x[j]}}
+    assert get_contraction_structure(expr1) == d1
+    expr2 = expr1*A[k, i] + x[k]
+    d2 = {None: {x[k]}, (i,): {expr1*A[k, i]}, expr1*A[k, i]: [d1]}
+    assert get_contraction_structure(expr2) == d2
+
+
+def test_contraction_structure_simple_Pow():
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i, j, k = Idx('i'), Idx('j'), Idx('k')
+    ii_jj = x[i, i]**y[j, j]
+    assert get_contraction_structure(ii_jj) == {
+        None: {ii_jj},
+        ii_jj: [
+            {(i,): {x[i, i]}},
+            {(j,): {y[j, j]}}
+        ]
+    }
+
+    ii_jk = x[i, i]**y[j, k]
+    assert get_contraction_structure(ii_jk) == {
+        None: {x[i, i]**y[j, k]},
+        x[i, i]**y[j, k]: [
+            {(i,): {x[i, i]}}
+        ]
+    }
+
+
+def test_contraction_structure_Mul_and_Pow():
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i, j, k = Idx('i'), Idx('j'), Idx('k')
+
+    i_ji = x[i]**(y[j]*x[i])
+    assert get_contraction_structure(i_ji) == {None: {i_ji}}
+    ij_i = (x[i]*y[j])**(y[i])
+    assert get_contraction_structure(ij_i) == {None: {ij_i}}
+    j_ij_i = x[j]*(x[i]*y[j])**(y[i])
+    assert get_contraction_structure(j_ij_i) == {(j,): {j_ij_i}}
+    j_i_ji = x[j]*x[i]**(y[j]*x[i])
+    assert get_contraction_structure(j_i_ji) == {(j,): {j_i_ji}}
+    ij_exp_kki = x[i]*y[j]*exp(y[i]*y[k, k])
+    result = get_contraction_structure(ij_exp_kki)
+    expected = {
+        (i,): {ij_exp_kki},
+        ij_exp_kki: [{
+                     None: {exp(y[i]*y[k, k])},
+                exp(y[i]*y[k, k]): [{
+                    None: {y[i]*y[k, k]},
+                    y[i]*y[k, k]: [{(k,): {y[k, k]}}]
+                }]}
+        ]
+    }
+    assert result == expected
+
+
+def test_contraction_structure_Add_in_Pow():
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i, j, k = Idx('i'), Idx('j'), Idx('k')
+    s_ii_jj_s = (1 + x[i, i])**(1 + y[j, j])
+    expected = {
+        None: {s_ii_jj_s},
+        s_ii_jj_s: [
+            {None: {S.One}, (i,): {x[i, i]}},
+            {None: {S.One}, (j,): {y[j, j]}}
+        ]
+    }
+    result = get_contraction_structure(s_ii_jj_s)
+    assert result == expected
+
+    s_ii_jk_s = (1 + x[i, i]) ** (1 + y[j, k])
+    expected_2 = {
+        None: {(x[i, i] + 1)**(y[j, k] + 1)},
+        s_ii_jk_s: [
+            {None: {S.One}, (i,): {x[i, i]}}
+        ]
+    }
+    result_2 = get_contraction_structure(s_ii_jk_s)
+    assert result_2 == expected_2
+
+
+def test_contraction_structure_Pow_in_Pow():
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    z = IndexedBase('z')
+    i, j, k = Idx('i'), Idx('j'), Idx('k')
+    ii_jj_kk = x[i, i]**y[j, j]**z[k, k]
+    expected = {
+        None: {ii_jj_kk},
+        ii_jj_kk: [
+            {(i,): {x[i, i]}},
+            {
+                None: {y[j, j]**z[k, k]},
+                y[j, j]**z[k, k]: [
+                    {(j,): {y[j, j]}},
+                    {(k,): {z[k, k]}}
+                ]
+            }
+        ]
+    }
+    assert get_contraction_structure(ii_jj_kk) == expected
+
+
+def test_ufunc_support():
+    f = Function('f')
+    g = Function('g')
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i, j = Idx('i'), Idx('j')
+    a = symbols('a')
+
+    assert get_indices(f(x[i])) == ({i}, {})
+    assert get_indices(f(x[i], y[j])) == ({i, j}, {})
+    assert get_indices(f(y[i])*g(x[i])) == (set(), {})
+    assert get_indices(f(a, x[i])) == ({i}, {})
+    assert get_indices(f(a, y[i], x[j])*g(x[i])) == ({j}, {})
+    assert get_indices(g(f(x[i]))) == ({i}, {})
+
+    assert get_contraction_structure(f(x[i])) == {None: {f(x[i])}}
+    assert get_contraction_structure(
+        f(y[i])*g(x[i])) == {(i,): {f(y[i])*g(x[i])}}
+    assert get_contraction_structure(
+        f(y[i])*g(f(x[i]))) == {(i,): {f(y[i])*g(f(x[i]))}}
+    assert get_contraction_structure(
+        f(x[j], y[i])*g(x[i])) == {(i,): {f(x[j], y[i])*g(x[i])}}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/tests/test_indexed.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/tests/test_indexed.py
new file mode 100644
index 0000000000000000000000000000000000000000..689ec932c8fcefe0a24de289dd2ffd6820c63f19
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/tests/test_indexed.py
@@ -0,0 +1,511 @@
+from sympy.core import symbols, Symbol, Tuple, oo, Dummy
+from sympy.tensor.indexed import IndexException
+from sympy.testing.pytest import raises
+from sympy.utilities.iterables import iterable
+
+# import test:
+from sympy.concrete.summations import Sum
+from sympy.core.function import Function, Subs, Derivative
+from sympy.core.relational import (StrictLessThan, GreaterThan,
+    StrictGreaterThan, LessThan)
+from sympy.core.singleton import S
+from sympy.functions.elementary.exponential import exp, log
+from sympy.functions.elementary.trigonometric import cos, sin
+from sympy.functions.special.tensor_functions import KroneckerDelta
+from sympy.series.order import Order
+from sympy.sets.fancysets import Range
+from sympy.tensor.indexed import IndexedBase, Idx, Indexed
+
+
+def test_Idx_construction():
+    i, a, b = symbols('i a b', integer=True)
+    assert Idx(i) != Idx(i, 1)
+    assert Idx(i, a) == Idx(i, (0, a - 1))
+    assert Idx(i, oo) == Idx(i, (0, oo))
+
+    x = symbols('x', integer=False)
+    raises(TypeError, lambda: Idx(x))
+    raises(TypeError, lambda: Idx(0.5))
+    raises(TypeError, lambda: Idx(i, x))
+    raises(TypeError, lambda: Idx(i, 0.5))
+    raises(TypeError, lambda: Idx(i, (x, 5)))
+    raises(TypeError, lambda: Idx(i, (2, x)))
+    raises(TypeError, lambda: Idx(i, (2, 3.5)))
+
+
+def test_Idx_properties():
+    i, a, b = symbols('i a b', integer=True)
+    assert Idx(i).is_integer
+    assert Idx(i).name == 'i'
+    assert Idx(i + 2).name == 'i + 2'
+    assert Idx('foo').name == 'foo'
+
+
+def test_Idx_bounds():
+    i, a, b = symbols('i a b', integer=True)
+    assert Idx(i).lower is None
+    assert Idx(i).upper is None
+    assert Idx(i, a).lower == 0
+    assert Idx(i, a).upper == a - 1
+    assert Idx(i, 5).lower == 0
+    assert Idx(i, 5).upper == 4
+    assert Idx(i, oo).lower == 0
+    assert Idx(i, oo).upper is oo
+    assert Idx(i, (a, b)).lower == a
+    assert Idx(i, (a, b)).upper == b
+    assert Idx(i, (1, 5)).lower == 1
+    assert Idx(i, (1, 5)).upper == 5
+    assert Idx(i, (-oo, oo)).lower is -oo
+    assert Idx(i, (-oo, oo)).upper is oo
+
+
+def test_Idx_fixed_bounds():
+    i, a, b, x = symbols('i a b x', integer=True)
+    assert Idx(x).lower is None
+    assert Idx(x).upper is None
+    assert Idx(x, a).lower == 0
+    assert Idx(x, a).upper == a - 1
+    assert Idx(x, 5).lower == 0
+    assert Idx(x, 5).upper == 4
+    assert Idx(x, oo).lower == 0
+    assert Idx(x, oo).upper is oo
+    assert Idx(x, (a, b)).lower == a
+    assert Idx(x, (a, b)).upper == b
+    assert Idx(x, (1, 5)).lower == 1
+    assert Idx(x, (1, 5)).upper == 5
+    assert Idx(x, (-oo, oo)).lower is -oo
+    assert Idx(x, (-oo, oo)).upper is oo
+
+
+def test_Idx_inequalities():
+    i14 = Idx("i14", (1, 4))
+    i79 = Idx("i79", (7, 9))
+    i46 = Idx("i46", (4, 6))
+    i35 = Idx("i35", (3, 5))
+
+    assert i14 <= 5
+    assert i14 < 5
+    assert not (i14 >= 5)
+    assert not (i14 > 5)
+
+    assert 5 >= i14
+    assert 5 > i14
+    assert not (5 <= i14)
+    assert not (5 < i14)
+
+    assert LessThan(i14, 5)
+    assert StrictLessThan(i14, 5)
+    assert not GreaterThan(i14, 5)
+    assert not StrictGreaterThan(i14, 5)
+
+    assert i14 <= 4
+    assert isinstance(i14 < 4, StrictLessThan)
+    assert isinstance(i14 >= 4, GreaterThan)
+    assert not (i14 > 4)
+
+    assert isinstance(i14 <= 1, LessThan)
+    assert not (i14 < 1)
+    assert i14 >= 1
+    assert isinstance(i14 > 1, StrictGreaterThan)
+
+    assert not (i14 <= 0)
+    assert not (i14 < 0)
+    assert i14 >= 0
+    assert i14 > 0
+
+    from sympy.abc import x
+
+    assert isinstance(i14 < x, StrictLessThan)
+    assert isinstance(i14 > x, StrictGreaterThan)
+    assert isinstance(i14 <= x, LessThan)
+    assert isinstance(i14 >= x, GreaterThan)
+
+    assert i14 < i79
+    assert i14 <= i79
+    assert not (i14 > i79)
+    assert not (i14 >= i79)
+
+    assert i14 <= i46
+    assert isinstance(i14 < i46, StrictLessThan)
+    assert isinstance(i14 >= i46, GreaterThan)
+    assert not (i14 > i46)
+
+    assert isinstance(i14 < i35, StrictLessThan)
+    assert isinstance(i14 > i35, StrictGreaterThan)
+    assert isinstance(i14 <= i35, LessThan)
+    assert isinstance(i14 >= i35, GreaterThan)
+
+    iNone1 = Idx("iNone1")
+    iNone2 = Idx("iNone2")
+
+    assert isinstance(iNone1 < iNone2, StrictLessThan)
+    assert isinstance(iNone1 > iNone2, StrictGreaterThan)
+    assert isinstance(iNone1 <= iNone2, LessThan)
+    assert isinstance(iNone1 >= iNone2, GreaterThan)
+
+
+def test_Idx_inequalities_current_fails():
+    i14 = Idx("i14", (1, 4))
+
+    assert S(5) >= i14
+    assert S(5) > i14
+    assert not (S(5) <= i14)
+    assert not (S(5) < i14)
+
+
+def test_Idx_func_args():
+    i, a, b = symbols('i a b', integer=True)
+    ii = Idx(i)
+    assert ii.func(*ii.args) == ii
+    ii = Idx(i, a)
+    assert ii.func(*ii.args) == ii
+    ii = Idx(i, (a, b))
+    assert ii.func(*ii.args) == ii
+
+
+def test_Idx_subs():
+    i, a, b = symbols('i a b', integer=True)
+    assert Idx(i, a).subs(a, b) == Idx(i, b)
+    assert Idx(i, a).subs(i, b) == Idx(b, a)
+
+    assert Idx(i).subs(i, 2) == Idx(2)
+    assert Idx(i, a).subs(a, 2) == Idx(i, 2)
+    assert Idx(i, (a, b)).subs(i, 2) == Idx(2, (a, b))
+
+
+def test_IndexedBase_sugar():
+    i, j = symbols('i j', integer=True)
+    a = symbols('a')
+    A1 = Indexed(a, i, j)
+    A2 = IndexedBase(a)
+    assert A1 == A2[i, j]
+    assert A1 == A2[(i, j)]
+    assert A1 == A2[[i, j]]
+    assert A1 == A2[Tuple(i, j)]
+    assert all(a.is_Integer for a in A2[1, 0].args[1:])
+
+
+def test_IndexedBase_subs():
+    i = symbols('i', integer=True)
+    a, b = symbols('a b')
+    A = IndexedBase(a)
+    B = IndexedBase(b)
+    assert A[i] == B[i].subs(b, a)
+    C = {1: 2}
+    assert C[1] == A[1].subs(A, C)
+
+
+def test_IndexedBase_shape():
+    i, j, m, n = symbols('i j m n', integer=True)
+    a = IndexedBase('a', shape=(m, m))
+    b = IndexedBase('a', shape=(m, n))
+    assert b.shape == Tuple(m, n)
+    assert a[i, j] != b[i, j]
+    assert a[i, j] == b[i, j].subs(n, m)
+    assert b.func(*b.args) == b
+    assert b[i, j].func(*b[i, j].args) == b[i, j]
+    raises(IndexException, lambda: b[i])
+    raises(IndexException, lambda: b[i, i, j])
+    F = IndexedBase("F", shape=m)
+    assert F.shape == Tuple(m)
+    assert F[i].subs(i, j) == F[j]
+    raises(IndexException, lambda: F[i, j])
+
+
+def test_IndexedBase_assumptions():
+    i = Symbol('i', integer=True)
+    a = Symbol('a')
+    A = IndexedBase(a, positive=True)
+    for c in (A, A[i]):
+        assert c.is_real
+        assert c.is_complex
+        assert not c.is_imaginary
+        assert c.is_nonnegative
+        assert c.is_nonzero
+        assert c.is_commutative
+        assert log(exp(c)) == c
+
+    assert A != IndexedBase(a)
+    assert A == IndexedBase(a, positive=True, real=True)
+    assert A[i] != Indexed(a, i)
+
+
+def test_IndexedBase_assumptions_inheritance():
+    I = Symbol('I', integer=True)
+    I_inherit = IndexedBase(I)
+    I_explicit = IndexedBase('I', integer=True)
+
+    assert I_inherit.is_integer
+    assert I_explicit.is_integer
+    assert I_inherit.label.is_integer
+    assert I_explicit.label.is_integer
+    assert I_inherit == I_explicit
+
+
+def test_issue_17652():
+    """Regression test issue #17652.
+
+    IndexedBase.label should not upcast subclasses of Symbol
+    """
+    class SubClass(Symbol):
+        pass
+
+    x = SubClass('X')
+    assert type(x) == SubClass
+    base = IndexedBase(x)
+    assert type(x) == SubClass
+    assert type(base.label) == SubClass
+
+
+def test_Indexed_constructor():
+    i, j = symbols('i j', integer=True)
+    A = Indexed('A', i, j)
+    assert A == Indexed(Symbol('A'), i, j)
+    assert A == Indexed(IndexedBase('A'), i, j)
+    raises(TypeError, lambda: Indexed(A, i, j))
+    raises(IndexException, lambda: Indexed("A"))
+    assert A.free_symbols == {A, A.base.label, i, j}
+
+
+def test_Indexed_func_args():
+    i, j = symbols('i j', integer=True)
+    a = symbols('a')
+    A = Indexed(a, i, j)
+    assert A == A.func(*A.args)
+
+
+def test_Indexed_subs():
+    i, j, k = symbols('i j k', integer=True)
+    a, b = symbols('a b')
+    A = IndexedBase(a)
+    B = IndexedBase(b)
+    assert A[i, j] == B[i, j].subs(b, a)
+    assert A[i, j] == A[i, k].subs(k, j)
+
+
+def test_Indexed_properties():
+    i, j = symbols('i j', integer=True)
+    A = Indexed('A', i, j)
+    assert A.name == 'A[i, j]'
+    assert A.rank == 2
+    assert A.indices == (i, j)
+    assert A.base == IndexedBase('A')
+    assert A.ranges == [None, None]
+    raises(IndexException, lambda: A.shape)
+
+    n, m = symbols('n m', integer=True)
+    assert Indexed('A', Idx(
+        i, m), Idx(j, n)).ranges == [Tuple(0, m - 1), Tuple(0, n - 1)]
+    assert Indexed('A', Idx(i, m), Idx(j, n)).shape == Tuple(m, n)
+    raises(IndexException, lambda: Indexed("A", Idx(i, m), Idx(j)).shape)
+
+
+def test_Indexed_shape_precedence():
+    i, j = symbols('i j', integer=True)
+    o, p = symbols('o p', integer=True)
+    n, m = symbols('n m', integer=True)
+    a = IndexedBase('a', shape=(o, p))
+    assert a.shape == Tuple(o, p)
+    assert Indexed(
+        a, Idx(i, m), Idx(j, n)).ranges == [Tuple(0, m - 1), Tuple(0, n - 1)]
+    assert Indexed(a, Idx(i, m), Idx(j, n)).shape == Tuple(o, p)
+    assert Indexed(
+        a, Idx(i, m), Idx(j)).ranges == [Tuple(0, m - 1), (None, None)]
+    assert Indexed(a, Idx(i, m), Idx(j)).shape == Tuple(o, p)
+
+
+def test_complex_indices():
+    i, j = symbols('i j', integer=True)
+    A = Indexed('A', i, i + j)
+    assert A.rank == 2
+    assert A.indices == (i, i + j)
+
+
+def test_not_interable():
+    i, j = symbols('i j', integer=True)
+    A = Indexed('A', i, i + j)
+    assert not iterable(A)
+
+
+def test_Indexed_coeff():
+    N = Symbol('N', integer=True)
+    len_y = N
+    i = Idx('i', len_y-1)
+    y = IndexedBase('y', shape=(len_y,))
+    a = (1/y[i+1]*y[i]).coeff(y[i])
+    b = (y[i]/y[i+1]).coeff(y[i])
+    assert a == b
+
+
+def test_differentiation():
+    from sympy.functions.special.tensor_functions import KroneckerDelta
+    i, j, k, l = symbols('i j k l', cls=Idx)
+    a = symbols('a')
+    m, n = symbols("m, n", integer=True, finite=True)
+    assert m.is_real
+    h, L = symbols('h L', cls=IndexedBase)
+    hi, hj = h[i], h[j]
+
+    expr = hi
+    assert expr.diff(hj) == KroneckerDelta(i, j)
+    assert expr.diff(hi) == KroneckerDelta(i, i)
+
+    expr = S(2) * hi
+    assert expr.diff(hj) == S(2) * KroneckerDelta(i, j)
+    assert expr.diff(hi) == S(2) * KroneckerDelta(i, i)
+    assert expr.diff(a) is S.Zero
+
+    assert Sum(expr, (i, -oo, oo)).diff(hj) == Sum(2*KroneckerDelta(i, j), (i, -oo, oo))
+    assert Sum(expr.diff(hj), (i, -oo, oo)) == Sum(2*KroneckerDelta(i, j), (i, -oo, oo))
+    assert Sum(expr, (i, -oo, oo)).diff(hj).doit() == 2
+
+    assert Sum(expr.diff(hi), (i, -oo, oo)).doit() == Sum(2, (i, -oo, oo)).doit()
+    assert Sum(expr, (i, -oo, oo)).diff(hi).doit() is oo
+
+    expr = a * hj * hj / S(2)
+    assert expr.diff(hi) == a * h[j] * KroneckerDelta(i, j)
+    assert expr.diff(a) == hj * hj / S(2)
+    assert expr.diff(a, 2) is S.Zero
+
+    assert Sum(expr, (i, -oo, oo)).diff(hi) == Sum(a*KroneckerDelta(i, j)*h[j], (i, -oo, oo))
+    assert Sum(expr.diff(hi), (i, -oo, oo)) == Sum(a*KroneckerDelta(i, j)*h[j], (i, -oo, oo))
+    assert Sum(expr, (i, -oo, oo)).diff(hi).doit() == a*h[j]
+
+    assert Sum(expr, (j, -oo, oo)).diff(hi) == Sum(a*KroneckerDelta(i, j)*h[j], (j, -oo, oo))
+    assert Sum(expr.diff(hi), (j, -oo, oo)) == Sum(a*KroneckerDelta(i, j)*h[j], (j, -oo, oo))
+    assert Sum(expr, (j, -oo, oo)).diff(hi).doit() == a*h[i]
+
+    expr = a * sin(hj * hj)
+    assert expr.diff(hi) == 2*a*cos(hj * hj) * hj * KroneckerDelta(i, j)
+    assert expr.diff(hj) == 2*a*cos(hj * hj) * hj
+
+    expr = a * L[i, j] * h[j]
+    assert expr.diff(hi) == a*L[i, j]*KroneckerDelta(i, j)
+    assert expr.diff(hj) == a*L[i, j]
+    assert expr.diff(L[i, j]) == a*h[j]
+    assert expr.diff(L[k, l]) == a*KroneckerDelta(i, k)*KroneckerDelta(j, l)*h[j]
+    assert expr.diff(L[i, l]) == a*KroneckerDelta(j, l)*h[j]
+
+    assert Sum(expr, (j, -oo, oo)).diff(L[k, l]) == Sum(a * KroneckerDelta(i, k) * KroneckerDelta(j, l) * h[j], (j, -oo, oo))
+    assert Sum(expr, (j, -oo, oo)).diff(L[k, l]).doit() == a * KroneckerDelta(i, k) * h[l]
+
+    assert h[m].diff(h[m]) == 1
+    assert h[m].diff(h[n]) == KroneckerDelta(m, n)
+    assert Sum(a*h[m], (m, -oo, oo)).diff(h[n]) == Sum(a*KroneckerDelta(m, n), (m, -oo, oo))
+    assert Sum(a*h[m], (m, -oo, oo)).diff(h[n]).doit() == a
+    assert Sum(a*h[m], (n, -oo, oo)).diff(h[n]) == Sum(a*KroneckerDelta(m, n), (n, -oo, oo))
+    assert Sum(a*h[m], (m, -oo, oo)).diff(h[m]).doit() == oo*a
+
+
+def test_indexed_series():
+    A = IndexedBase("A")
+    i = symbols("i", integer=True)
+    assert sin(A[i]).series(A[i]) == A[i] - A[i]**3/6 + A[i]**5/120 + Order(A[i]**6, A[i])
+
+
+def test_indexed_is_constant():
+    A = IndexedBase("A")
+    i, j, k = symbols("i,j,k")
+    assert not A[i].is_constant()
+    assert A[i].is_constant(j)
+    assert not A[1+2*i, k].is_constant()
+    assert not A[1+2*i, k].is_constant(i)
+    assert A[1+2*i, k].is_constant(j)
+    assert not A[1+2*i, k].is_constant(k)
+
+
+def test_issue_12533():
+    d = IndexedBase('d')
+    assert IndexedBase(range(5)) == Range(0, 5, 1)
+    assert d[0].subs(Symbol("d"), range(5)) == 0
+    assert d[0].subs(d, range(5)) == 0
+    assert d[1].subs(d, range(5)) == 1
+    assert Indexed(Range(5), 2) == 2
+
+
+def test_issue_12780():
+    n = symbols("n")
+    i = Idx("i", (0, n))
+    raises(TypeError, lambda: i.subs(n, 1.5))
+
+
+def test_issue_18604():
+    m = symbols("m")
+    assert Idx("i", m).name == 'i'
+    assert Idx("i", m).lower == 0
+    assert Idx("i", m).upper == m - 1
+    m = symbols("m", real=False)
+    raises(TypeError, lambda: Idx("i", m))
+
+def test_Subs_with_Indexed():
+    A = IndexedBase("A")
+    i, j, k = symbols("i,j,k")
+    x, y, z = symbols("x,y,z")
+    f = Function("f")
+
+    assert Subs(A[i], A[i], A[j]).diff(A[j]) == 1
+    assert Subs(A[i], A[i], x).diff(A[i]) == 0
+    assert Subs(A[i], A[i], x).diff(A[j]) == 0
+    assert Subs(A[i], A[i], x).diff(x) == 1
+    assert Subs(A[i], A[i], x).diff(y) == 0
+    assert Subs(A[i], A[i], A[j]).diff(A[k]) == KroneckerDelta(j, k)
+    assert Subs(x, x, A[i]).diff(A[j]) == KroneckerDelta(i, j)
+    assert Subs(f(A[i]), A[i], x).diff(A[j]) == 0
+    assert Subs(f(A[i]), A[i], A[k]).diff(A[j]) == Derivative(f(A[k]), A[k])*KroneckerDelta(j, k)
+    assert Subs(x, x, A[i]**2).diff(A[j]) == 2*KroneckerDelta(i, j)*A[i]
+    assert Subs(A[i], A[i], A[j]**2).diff(A[k]) == 2*KroneckerDelta(j, k)*A[j]
+
+    assert Subs(A[i]*x, x, A[i]).diff(A[i]) == 2*A[i]
+    assert Subs(A[i]*x, x, A[i]).diff(A[j]) == 2*A[i]*KroneckerDelta(i, j)
+    assert Subs(A[i]*x, x, A[j]).diff(A[i]) == A[j] + A[i]*KroneckerDelta(i, j)
+    assert Subs(A[i]*x, x, A[j]).diff(A[j]) == A[i] + A[j]*KroneckerDelta(i, j)
+    assert Subs(A[i]*x, x, A[i]).diff(A[k]) == 2*A[i]*KroneckerDelta(i, k)
+    assert Subs(A[i]*x, x, A[j]).diff(A[k]) == KroneckerDelta(i, k)*A[j] + KroneckerDelta(j, k)*A[i]
+
+    assert Subs(A[i]*x, A[i], x).diff(A[i]) == 0
+    assert Subs(A[i]*x, A[i], x).diff(A[j]) == 0
+    assert Subs(A[i]*x, A[j], x).diff(A[i]) == x
+    assert Subs(A[i]*x, A[j], x).diff(A[j]) == x*KroneckerDelta(i, j)
+    assert Subs(A[i]*x, A[i], x).diff(A[k]) == 0
+    assert Subs(A[i]*x, A[j], x).diff(A[k]) == x*KroneckerDelta(i, k)
+
+
+def test_complicated_derivative_with_Indexed():
+    x, y = symbols("x,y", cls=IndexedBase)
+    sigma = symbols("sigma")
+    i, j, k = symbols("i,j,k")
+    m0,m1,m2,m3,m4,m5 = symbols("m0:6")
+    f = Function("f")
+
+    expr = f((x[i] - y[i])**2/sigma)
+    _xi_1 = symbols("xi_1", cls=Dummy)
+    assert expr.diff(x[m0]).dummy_eq(
+        (x[i] - y[i])*KroneckerDelta(i, m0)*\
+        2*Subs(
+            Derivative(f(_xi_1), _xi_1),
+            (_xi_1,),
+            ((x[i] - y[i])**2/sigma,)
+        )/sigma
+    )
+    assert expr.diff(x[m0]).diff(x[m1]).dummy_eq(
+        2*KroneckerDelta(i, m0)*\
+        KroneckerDelta(i, m1)*Subs(
+            Derivative(f(_xi_1), _xi_1),
+            (_xi_1,),
+            ((x[i] - y[i])**2/sigma,)
+         )/sigma + \
+        4*(x[i] - y[i])**2*KroneckerDelta(i, m0)*KroneckerDelta(i, m1)*\
+        Subs(
+            Derivative(f(_xi_1), _xi_1, _xi_1),
+            (_xi_1,),
+            ((x[i] - y[i])**2/sigma,)
+        )/sigma**2
+    )
+
+
+def test_IndexedBase_commutative():
+    t = IndexedBase('t', commutative=False)
+    u = IndexedBase('u', commutative=False)
+    v = IndexedBase('v')
+    assert t[0]*v[0] == v[0]*t[0]
+    assert t[0]*u[0] != u[0]*t[0]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/tests/test_printing.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/tests/test_printing.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f3cf7f0591a7012c93354ab7b8d7e010def38bb
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/tests/test_printing.py
@@ -0,0 +1,13 @@
+from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead
+from sympy import I
+
+def test_printing_TensMul():
+    R3 = TensorIndexType('R3', dim=3)
+    p, q = tensor_indices("p q", R3)
+    K = TensorHead("K", [R3])
+
+    assert repr(2*K(p)) == "2*K(p)"
+    assert repr(-K(p)) == "-K(p)"
+    assert repr(-2*K(p)*K(q)) == "-2*K(p)*K(q)"
+    assert repr(-I*K(p)) == "-I*K(p)"
+    assert repr(I*K(p)) == "I*K(p)"
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/tests/test_tensor.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/tests/test_tensor.py
new file mode 100644
index 0000000000000000000000000000000000000000..3113f5be9bcd32224f3525b5d831b6d7476c39e3
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/tensor/tests/test_tensor.py
@@ -0,0 +1,2218 @@
+from sympy.concrete.summations import Sum
+from sympy.core.function import expand
+from sympy.core.numbers import Integer
+from sympy.matrices.dense import (Matrix, eye)
+from sympy.tensor.indexed import Indexed
+from sympy.combinatorics import Permutation
+from sympy.core import S, Rational, Symbol, Basic, Add, Wild, Function
+from sympy.core.containers import Tuple
+from sympy.core.symbol import symbols
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.integrals import integrate
+from sympy.tensor.array import Array
+from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorSymmetry, \
+    get_symmetric_group_sgs, TensorIndex, tensor_mul, TensAdd, \
+    riemann_cyclic_replace, riemann_cyclic, TensMul, tensor_heads, \
+    TensorManager, TensExpr, TensorHead, canon_bp, \
+    tensorhead, tensorsymmetry, TensorType, substitute_indices, \
+    WildTensorIndex, WildTensorHead, _WildTensExpr
+from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy
+from sympy.matrices import diag
+
+def _is_equal(arg1, arg2):
+    if isinstance(arg1, TensExpr):
+        return arg1.equals(arg2)
+    elif isinstance(arg2, TensExpr):
+        return arg2.equals(arg1)
+    return arg1 == arg2
+
+
+#################### Tests from tensor_can.py #######################
+def test_canonicalize_no_slot_sym():
+    # A_d0 * B^d0; T_c = A^d0*B_d0
+    Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+    a, b, d0, d1 = tensor_indices('a,b,d0,d1', Lorentz)
+    A, B = tensor_heads('A,B', [Lorentz], TensorSymmetry.no_symmetry(1))
+    t = A(-d0)*B(d0)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(L_0)*B(-L_0)'
+
+    # A^a * B^b;  T_c = T
+    t = A(a)*B(b)
+    tc = t.canon_bp()
+    assert tc == t
+    # B^b * A^a
+    t1 = B(b)*A(a)
+    tc = t1.canon_bp()
+    assert str(tc) == 'A(a)*B(b)'
+
+    # A symmetric
+    # A^{b}_{d0}*A^{d0, a}; T_c = A^{a d0}*A{b}_{d0}
+    A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
+    t = A(b, -d0)*A(d0, a)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(a, L_0)*A(b, -L_0)'
+
+    # A^{d1}_{d0}*B^d0*C_d1
+    # T_c = A^{d0 d1}*B_d0*C_d1
+    B, C = tensor_heads('B,C', [Lorentz], TensorSymmetry.no_symmetry(1))
+    t = A(d1, -d0)*B(d0)*C(-d1)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(L_0, L_1)*B(-L_0)*C(-L_1)'
+
+    # A without symmetry
+    # A^{d1}_{d0}*B^d0*C_d1 ord=[d0,-d0,d1,-d1]; g = [2,1,0,3,4,5]
+    # T_c = A^{d0 d1}*B_d1*C_d0; can = [0,2,3,1,4,5]
+    A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
+    t = A(d1, -d0)*B(d0)*C(-d1)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(L_0, L_1)*B(-L_1)*C(-L_0)'
+
+    # A, B without symmetry
+    # A^{d1}_{d0}*B_{d1}^{d0}
+    # T_c = A^{d0 d1}*B_{d0 d1}
+    B = TensorHead('B', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
+    t = A(d1, -d0)*B(-d1, d0)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(L_0, L_1)*B(-L_0, -L_1)'
+    # A_{d0}^{d1}*B_{d1}^{d0}
+    # T_c = A^{d0 d1}*B_{d1 d0}
+    t = A(-d0, d1)*B(-d1, d0)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(L_0, L_1)*B(-L_1, -L_0)'
+
+    # A, B, C without symmetry
+    # A^{d1 d0}*B_{a d0}*C_{d1 b}
+    # T_c=A^{d0 d1}*B_{a d1}*C_{d0 b}
+    C = TensorHead('C', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
+    t = A(d1, d0)*B(-a, -d0)*C(-d1, -b)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(L_0, L_1)*B(-a, -L_1)*C(-L_0, -b)'
+
+    # A symmetric, B and C without symmetry
+    # A^{d1 d0}*B_{a d0}*C_{d1 b}
+    # T_c = A^{d0 d1}*B_{a d0}*C_{d1 b}
+    A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
+    t = A(d1, d0)*B(-a, -d0)*C(-d1, -b)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(L_0, L_1)*B(-a, -L_0)*C(-L_1, -b)'
+
+    # A and C symmetric, B without symmetry
+    # A^{d1 d0}*B_{a d0}*C_{d1 b} ord=[a,b,d0,-d0,d1,-d1]
+    # T_c = A^{d0 d1}*B_{a d0}*C_{b d1}
+    C = TensorHead('C', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
+    t = A(d1, d0)*B(-a, -d0)*C(-d1, -b)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(L_0, L_1)*B(-a, -L_0)*C(-b, -L_1)'
+
+def test_canonicalize_no_dummies():
+    Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+    a, b, c, d = tensor_indices('a, b, c, d', Lorentz)
+
+    # A commuting
+    # A^c A^b A^a
+    # T_c = A^a A^b A^c
+    A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1))
+    t = A(c)*A(b)*A(a)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(a)*A(b)*A(c)'
+
+    # A anticommuting
+    # A^c A^b A^a
+    # T_c = -A^a A^b A^c
+    A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1), 1)
+    t = A(c)*A(b)*A(a)
+    tc = t.canon_bp()
+    assert str(tc) == '-A(a)*A(b)*A(c)'
+
+    # A commuting and symmetric
+    # A^{b,d}*A^{c,a}
+    # T_c = A^{a c}*A^{b d}
+    A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
+    t = A(b, d)*A(c, a)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(a, c)*A(b, d)'
+
+    # A anticommuting and symmetric
+    # A^{b,d}*A^{c,a}
+    # T_c = -A^{a c}*A^{b d}
+    A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2), 1)
+    t = A(b, d)*A(c, a)
+    tc = t.canon_bp()
+    assert str(tc) == '-A(a, c)*A(b, d)'
+
+    # A^{c,a}*A^{b,d}
+    # T_c = A^{a c}*A^{b d}
+    t = A(c, a)*A(b, d)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(a, c)*A(b, d)'
+
+def test_tensorhead_construction_without_symmetry():
+    L = TensorIndexType('Lorentz')
+    A1 = TensorHead('A', [L, L])
+    A2 = TensorHead('A', [L, L], TensorSymmetry.no_symmetry(2))
+    assert A1 == A2
+    A3 = TensorHead('A', [L, L], TensorSymmetry.fully_symmetric(2))  # Symmetric
+    assert A1 != A3
+
+def test_no_metric_symmetry():
+    # no metric symmetry; A no symmetry
+    # A^d1_d0 * A^d0_d1
+    # T_c = A^d0_d1 * A^d1_d0
+    Lorentz = TensorIndexType('Lorentz', dummy_name='L', metric_symmetry=0)
+    d0, d1, d2, d3 = tensor_indices('d:4', Lorentz)
+    A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
+    t = A(d1, -d0)*A(d0, -d1)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_0)'
+
+    # A^d1_d2 * A^d0_d3 * A^d2_d1 * A^d3_d0
+    # T_c = A^d0_d1 * A^d1_d0 * A^d2_d3 * A^d3_d2
+    t = A(d1, -d2)*A(d0, -d3)*A(d2, -d1)*A(d3, -d0)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_0)*A(L_2, -L_3)*A(L_3, -L_2)'
+
+    # A^d0_d2 * A^d1_d3 * A^d3_d0 * A^d2_d1
+    # T_c = A^d0_d1 * A^d1_d2 * A^d2_d3 * A^d3_d0
+    t = A(d0, -d1)*A(d1, -d2)*A(d2, -d3)*A(d3, -d0)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_2)*A(L_2, -L_3)*A(L_3, -L_0)'
+
+def test_canonicalize1():
+    Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+    a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \
+        tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Lorentz)
+
+    # A_d0*A^d0; ord = [d0,-d0]
+    # T_c = A^d0*A_d0
+    A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1))
+    t = A(-d0)*A(d0)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(L_0)*A(-L_0)'
+
+    # A commuting
+    # A_d0*A_d1*A_d2*A^d2*A^d1*A^d0
+    # T_c = A^d0*A_d0*A^d1*A_d1*A^d2*A_d2
+    t = A(-d0)*A(-d1)*A(-d2)*A(d2)*A(d1)*A(d0)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(L_0)*A(-L_0)*A(L_1)*A(-L_1)*A(L_2)*A(-L_2)'
+
+    # A anticommuting
+    # A_d0*A_d1*A_d2*A^d2*A^d1*A^d0
+    # T_c 0
+    A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1), 1)
+    t = A(-d0)*A(-d1)*A(-d2)*A(d2)*A(d1)*A(d0)
+    tc = t.canon_bp()
+    assert tc == 0
+
+    # A commuting symmetric
+    # A^{d0 b}*A^a_d1*A^d1_d0
+    # T_c = A^{a d0}*A^{b d1}*A_{d0 d1}
+    A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
+    t = A(d0, b)*A(a, -d1)*A(d1, -d0)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(a, L_0)*A(b, L_1)*A(-L_0, -L_1)'
+
+    # A, B commuting symmetric
+    # A^{d0 b}*A^d1_d0*B^a_d1
+    # T_c = A^{b d0}*A_d0^d1*B^a_d1
+    B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
+    t = A(d0, b)*A(d1, -d0)*B(a, -d1)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(b, L_0)*A(-L_0, L_1)*B(a, -L_1)'
+
+    # A commuting symmetric
+    # A^{d1 d0 b}*A^{a}_{d1 d0}; ord=[a,b, d0,-d0,d1,-d1]
+    # T_c = A^{a d0 d1}*A^{b}_{d0 d1}
+    A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3))
+    t = A(d1, d0, b)*A(a, -d1, -d0)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(a, L_0, L_1)*A(b, -L_0, -L_1)'
+
+    # A^{d3 d0 d2}*A^a0_{d1 d2}*A^d1_d3^a1*A^{a2 a3}_d0
+    # T_c = A^{a0 d0 d1}*A^a1_d0^d2*A^{a2 a3 d3}*A_{d1 d2 d3}
+    t = A(d3, d0, d2)*A(a0, -d1, -d2)*A(d1, -d3, a1)*A(a2, a3, -d0)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(a0, L_0, L_1)*A(a1, -L_0, L_2)*A(a2, a3, L_3)*A(-L_1, -L_2, -L_3)'
+
+    # A commuting symmetric, B antisymmetric
+    # A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3
+    # in this esxample and in the next three,
+    # renaming dummy indices and using symmetry of A,
+    # T = A^{d0 d1 d2} * A_{d0 d1 d3} * B_d2^d3
+    # can = 0
+    A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3))
+    B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
+    t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3)
+    tc = t.canon_bp()
+    assert tc == 0
+
+    # A anticommuting symmetric, B antisymmetric
+    # A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3
+    # T_c = A^{d0 d1 d2} * A_{d0 d1}^d3 * B_{d2 d3}
+    A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3), 1)
+    B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
+    t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(L_0, L_1, L_2)*A(-L_0, -L_1, L_3)*B(-L_2, -L_3)'
+
+    # A anticommuting symmetric, B antisymmetric commuting, antisymmetric metric
+    # A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3
+    # T_c = -A^{d0 d1 d2} * A_{d0 d1}^d3 * B_{d2 d3}
+    Spinor = TensorIndexType('Spinor', dummy_name='S', metric_symmetry=-1)
+    a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \
+        tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Spinor)
+    A = TensorHead('A', [Spinor]*3, TensorSymmetry.fully_symmetric(3), 1)
+    B = TensorHead('B', [Spinor]*2, TensorSymmetry.fully_symmetric(-2))
+    t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3)
+    tc = t.canon_bp()
+    assert str(tc) == '-A(S_0, S_1, S_2)*A(-S_0, -S_1, S_3)*B(-S_2, -S_3)'
+
+    # A anticommuting symmetric, B antisymmetric anticommuting,
+    # no metric symmetry
+    # A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3
+    # T_c = A^{d0 d1 d2} * A_{d0 d1 d3} * B_d2^d3
+    Mat = TensorIndexType('Mat', metric_symmetry=0, dummy_name='M')
+    a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \
+        tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Mat)
+    A = TensorHead('A', [Mat]*3, TensorSymmetry.fully_symmetric(3), 1)
+    B = TensorHead('B', [Mat]*2, TensorSymmetry.fully_symmetric(-2))
+    t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3)
+    tc = t.canon_bp()
+    assert str(tc) == 'A(M_0, M_1, M_2)*A(-M_0, -M_1, -M_3)*B(-M_2, M_3)'
+
+    # Gamma anticommuting
+    # Gamma_{mu nu} * gamma^rho * Gamma^{nu mu alpha}
+    # T_c = -Gamma^{mu nu} * gamma^rho * Gamma_{alpha mu nu}
+    alpha, beta, gamma, mu, nu, rho = \
+        tensor_indices('alpha,beta,gamma,mu,nu,rho', Lorentz)
+    Gamma = TensorHead('Gamma', [Lorentz],
+                       TensorSymmetry.fully_symmetric(1), 2)
+    Gamma2 = TensorHead('Gamma', [Lorentz]*2,
+                        TensorSymmetry.fully_symmetric(-2), 2)
+    Gamma3 = TensorHead('Gamma', [Lorentz]*3,
+                        TensorSymmetry.fully_symmetric(-3), 2)
+    t = Gamma2(-mu, -nu)*Gamma(rho)*Gamma3(nu, mu, alpha)
+    tc = t.canon_bp()
+    assert str(tc) == '-Gamma(L_0, L_1)*Gamma(rho)*Gamma(alpha, -L_0, -L_1)'
+
+    # Gamma_{mu nu} * Gamma^{gamma beta} * gamma_rho * Gamma^{nu mu alpha}
+    # T_c = Gamma^{mu nu} * Gamma^{beta gamma} * gamma_rho * Gamma^alpha_{mu nu}
+    t = Gamma2(mu, nu)*Gamma2(beta, gamma)*Gamma(-rho)*Gamma3(alpha, -mu, -nu)
+    tc = t.canon_bp()
+    assert str(tc) == 'Gamma(L_0, L_1)*Gamma(beta, gamma)*Gamma(-rho)*Gamma(alpha, -L_0, -L_1)'
+
+    # f^a_{b,c} antisymmetric in b,c; A_mu^a no symmetry
+    # f^c_{d a} * f_{c e b} * A_mu^d * A_nu^a * A^{nu e} * A^{mu b}
+    # g = [8,11,5, 9,13,7, 1,10, 3,4, 2,12, 0,6, 14,15]
+    # T_c = -f^{a b c} * f_a^{d e} * A^mu_b * A_{mu d} * A^nu_c * A_{nu e}
+    Flavor = TensorIndexType('Flavor', dummy_name='F')
+    a, b, c, d, e, ff = tensor_indices('a,b,c,d,e,f', Flavor)
+    mu, nu = tensor_indices('mu,nu', Lorentz)
+    f = TensorHead('f', [Flavor]*3, TensorSymmetry.direct_product(1, -2))
+    A = TensorHead('A', [Lorentz, Flavor], TensorSymmetry.no_symmetry(2))
+    t = f(c, -d, -a)*f(-c, -e, -b)*A(-mu, d)*A(-nu, a)*A(nu, e)*A(mu, b)
+    tc = t.canon_bp()
+    assert str(tc) == '-f(F_0, F_1, F_2)*f(-F_0, F_3, F_4)*A(L_0, -F_1)*A(-L_0, -F_3)*A(L_1, -F_2)*A(-L_1, -F_4)'
+
+
+def test_bug_correction_tensor_indices():
+    # to make sure that tensor_indices does not return a list if creating
+    # only one index:
+    A = TensorIndexType("A")
+    i = tensor_indices('i', A)
+    assert not isinstance(i, (tuple, list))
+    assert isinstance(i, TensorIndex)
+
+
+def test_riemann_invariants():
+    Lorentz = TensorIndexType('Lorentz', dummy_name='L')
+    d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11 = \
+        tensor_indices('d0:12', Lorentz)
+    # R^{d0 d1}_{d1 d0}; ord = [d0,-d0,d1,-d1]
+    # T_c = -R^{d0 d1}_{d0 d1}
+    R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
+    t = R(d0, d1, -d1, -d0)
+    tc = t.canon_bp()
+    assert str(tc) == '-R(L_0, L_1, -L_0, -L_1)'
+
+    # R_d11^d1_d0^d5 * R^{d6 d4 d0}_d5 * R_{d7 d2 d8 d9} *
+    # R_{d10 d3 d6 d4} * R^{d2 d7 d11}_d1 * R^{d8 d9 d3 d10}
+    # can = [0,2,4,6, 1,3,8,10, 5,7,12,14, 9,11,16,18, 13,15,20,22,
+    #        17,19,21>> from sympy.tensor.tensor import TensorIndexType, TensorHead
+    >>> from sympy.tensor.toperators import PartialDerivative
+    >>> from sympy import symbols
+    >>> L = TensorIndexType("L")
+    >>> A = TensorHead("A", [L])
+    >>> B = TensorHead("B", [L])
+    >>> i, j, k = symbols("i j k")
+
+    >>> expr = PartialDerivative(A(i), A(j))
+    >>> expr
+    PartialDerivative(A(i), A(j))
+
+    The ``PartialDerivative`` object behaves like a tensorial expression:
+
+    >>> expr.get_indices()
+    [i, -j]
+
+    Notice that the deriving variables have opposite valence than the
+    printed one: ``A(j)`` is printed as covariant, but the index of the
+    derivative is actually contravariant, i.e. ``-j``.
+
+    Indices can be contracted:
+
+    >>> expr = PartialDerivative(A(i), A(i))
+    >>> expr
+    PartialDerivative(A(L_0), A(L_0))
+    >>> expr.get_indices()
+    [L_0, -L_0]
+
+    The method ``.get_indices()`` always returns all indices (even the
+    contracted ones). If only uncontracted indices are needed, call
+    ``.get_free_indices()``:
+
+    >>> expr.get_free_indices()
+    []
+
+    Nested partial derivatives are flattened:
+
+    >>> expr = PartialDerivative(PartialDerivative(A(i), A(j)), A(k))
+    >>> expr
+    PartialDerivative(A(i), A(j), A(k))
+    >>> expr.get_indices()
+    [i, -j, -k]
+
+    Replace a derivative with array values:
+
+    >>> from sympy.abc import x, y
+    >>> from sympy import sin, log
+    >>> compA = [sin(x), log(x)*y**3]
+    >>> compB = [x, y]
+    >>> expr = PartialDerivative(A(i), B(j))
+    >>> expr.replace_with_arrays({A(i): compA, B(i): compB})
+    [[cos(x), 0], [y**3/x, 3*y**2*log(x)]]
+
+    The returned array is indexed by `(i, -j)`.
+
+    Be careful that other SymPy modules put the indices of the deriving
+    variables before the indices of the derivand in the derivative result.
+    For example:
+
+    >>> expr.get_free_indices()
+    [i, -j]
+
+    >>> from sympy import Matrix, Array
+    >>> Matrix(compA).diff(Matrix(compB)).reshape(2, 2)
+    [[cos(x), y**3/x], [0, 3*y**2*log(x)]]
+    >>> Array(compA).diff(Array(compB))
+    [[cos(x), y**3/x], [0, 3*y**2*log(x)]]
+
+    These are the transpose of the result of ``PartialDerivative``,
+    as the matrix and the array modules put the index `-j` before `i` in the
+    derivative result. An array read with index order `(-j, i)` is indeed the
+    transpose of the same array read with index order `(i, -j)`. By specifying
+    the index order to ``.replace_with_arrays`` one can get a compatible
+    expression:
+
+    >>> expr.replace_with_arrays({A(i): compA, B(i): compB}, [-j, i])
+    [[cos(x), y**3/x], [0, 3*y**2*log(x)]]
+    """
+
+    def __new__(cls, expr, *variables):
+
+        # Flatten:
+        if isinstance(expr, PartialDerivative):
+            variables = expr.variables + variables
+            expr = expr.expr
+
+        args, indices, free, dum = cls._contract_indices_for_derivative(
+            S(expr), variables)
+
+        obj = TensExpr.__new__(cls, *args)
+
+        obj._indices = indices
+        obj._free = free
+        obj._dum = dum
+        return obj
+
+    @property
+    def coeff(self):
+        return S.One
+
+    @property
+    def nocoeff(self):
+        return self
+
+    @classmethod
+    def _contract_indices_for_derivative(cls, expr, variables):
+        variables_opposite_valence = []
+
+        for i in variables:
+            if isinstance(i, Tensor):
+                i_free_indices = i.get_free_indices()
+                variables_opposite_valence.append(
+                        i.xreplace({k: -k for k in i_free_indices}))
+            elif isinstance(i, Symbol):
+                variables_opposite_valence.append(i)
+
+        args, indices, free, dum = TensMul._tensMul_contract_indices(
+            [expr] + variables_opposite_valence, replace_indices=True)
+
+        for i in range(1, len(args)):
+            args_i = args[i]
+            if isinstance(args_i, Tensor):
+                i_indices = args[i].get_free_indices()
+                args[i] = args[i].xreplace({k: -k for k in i_indices})
+
+        return args, indices, free, dum
+
+    def doit(self, **hints):
+        args, indices, free, dum = self._contract_indices_for_derivative(self.expr, self.variables)
+
+        obj = self.func(*args)
+        obj._indices = indices
+        obj._free = free
+        obj._dum = dum
+
+        return obj
+
+    def _expand_partial_derivative(self):
+        args, indices, free, dum = self._contract_indices_for_derivative(self.expr, self.variables)
+
+        obj = self.func(*args)
+        obj._indices = indices
+        obj._free = free
+        obj._dum = dum
+
+        result = obj
+
+        if not args[0].free_symbols:
+            return S.Zero
+        elif isinstance(obj.expr, TensAdd):
+            # take care of sums of multi PDs
+            result = obj.expr.func(*[
+                    self.func(a, *obj.variables)._expand_partial_derivative()
+                    for a in result.expr.args])
+        elif isinstance(obj.expr, TensMul):
+            # take care of products of multi PDs
+            if len(obj.variables) == 1:
+                # derivative with respect to single variable
+                terms = []
+                mulargs = list(obj.expr.args)
+                for ind in range(len(mulargs)):
+                    if not isinstance(sympify(mulargs[ind]), Number):
+                        # a number coefficient is not considered for
+                        # expansion of PartialDerivative
+                        d = self.func(mulargs[ind], *obj.variables)._expand_partial_derivative()
+                        terms.append(TensMul(*(mulargs[:ind]
+                                               + [d]
+                                               + mulargs[(ind + 1):])))
+                result = TensAdd.fromiter(terms)
+            else:
+                # derivative with respect to multiple variables
+                # decompose:
+                # partial(expr, (u, v))
+                # = partial(partial(expr, u).doit(), v).doit()
+                result = obj.expr  # init with expr
+                for v in obj.variables:
+                    result = self.func(result, v)._expand_partial_derivative()
+                    # then throw PD on it
+
+        return result
+
+    def _perform_derivative(self):
+        result = self.expr
+        for v in self.variables:
+            if isinstance(result, TensExpr):
+                result = result._eval_partial_derivative(v)
+            else:
+                if v._diff_wrt:
+                    result = result._eval_derivative(v)
+                else:
+                    result = S.Zero
+        return result
+
+    def get_indices(self):
+        return self._indices
+
+    def get_free_indices(self):
+        free = sorted(self._free, key=lambda x: x[1])
+        return [i[0] for i in free]
+
+    def _replace_indices(self, repl):
+        expr = self.expr.xreplace(repl)
+        mirrored = {-k: -v for k, v in repl.items()}
+        variables = [i.xreplace(mirrored) for i in self.variables]
+        return self.func(expr, *variables)
+
+    @property
+    def expr(self):
+        return self.args[0]
+
+    @property
+    def variables(self):
+        return self.args[1:]
+
+    def _extract_data(self, replacement_dict):
+        from .array import derive_by_array, tensorcontraction
+        indices, array = self.expr._extract_data(replacement_dict)
+        for variable in self.variables:
+            var_indices, var_array = variable._extract_data(replacement_dict)
+            var_indices = [-i for i in var_indices]
+            coeff_array, var_array = zip(*[i.as_coeff_Mul() for i in var_array])
+            dim_before = len(array.shape)
+            array = derive_by_array(array, var_array)
+            dim_after = len(array.shape)
+            dim_increase = dim_after - dim_before
+            array = permutedims(array, [i + dim_increase for i in range(dim_before)] + list(range(dim_increase)))
+            array = array.as_mutable()
+            varindex = var_indices[0]
+            # Remove coefficients of base vector:
+            coeff_index = [0] + [slice(None) for i in range(len(indices))]
+            for i, coeff in enumerate(coeff_array):
+                coeff_index[0] = i
+                array[tuple(coeff_index)] /= coeff
+            if -varindex in indices:
+                pos = indices.index(-varindex)
+                array = tensorcontraction(array, (0, pos+1))
+                indices.pop(pos)
+            else:
+                indices.append(varindex)
+        return indices, array
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa66402955e7d5d2b27cccc6627b42d33f4cd855
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/__init__.py
@@ -0,0 +1,10 @@
+"""This module contains code for running the tests in SymPy."""
+
+
+from .runtests import doctest
+from .runtests_pytest import test
+
+
+__all__ = [
+    'test', 'doctest',
+]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/matrices.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/matrices.py
new file mode 100644
index 0000000000000000000000000000000000000000..236a384366df7f69d0d92f43f7e007e95c12388c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/matrices.py
@@ -0,0 +1,8 @@
+def allclose(A, B, rtol=1e-05, atol=1e-08):
+    if len(A) != len(B):
+        return False
+
+    for x, y in zip(A, B):
+        if abs(x-y) > atol + rtol * max(abs(x), abs(y)):
+            return False
+    return True
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/pytest.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/pytest.py
new file mode 100644
index 0000000000000000000000000000000000000000..498515a2d3c0a167a5f7067753736898cfa64799
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/pytest.py
@@ -0,0 +1,392 @@
+"""py.test hacks to support XFAIL/XPASS"""
+
+import platform
+import sys
+import re
+import functools
+import os
+import contextlib
+import warnings
+import inspect
+import pathlib
+from typing import Any, Callable
+
+from sympy.utilities.exceptions import SymPyDeprecationWarning
+# Imported here for backwards compatibility. Note: do not import this from
+# here in library code (importing sympy.pytest in library code will break the
+# pytest integration).
+from sympy.utilities.exceptions import ignore_warnings # noqa:F401
+
+ON_CI = os.getenv('CI', None) == "true"
+
+try:
+    import pytest
+    USE_PYTEST = getattr(sys, '_running_pytest', False)
+except ImportError:
+    USE_PYTEST = False
+
+IS_WASM: bool = sys.platform == 'emscripten' or platform.machine() in ["wasm32", "wasm64"]
+
+raises: Callable[[Any, Any], Any]
+XFAIL: Callable[[Any], Any]
+skip: Callable[[Any], Any]
+SKIP: Callable[[Any], Any]
+slow: Callable[[Any], Any]
+tooslow: Callable[[Any], Any]
+nocache_fail: Callable[[Any], Any]
+
+
+if USE_PYTEST:
+    raises = pytest.raises
+    skip = pytest.skip
+    XFAIL = pytest.mark.xfail
+    SKIP = pytest.mark.skip
+    slow = pytest.mark.slow
+    tooslow = pytest.mark.tooslow
+    nocache_fail = pytest.mark.nocache_fail
+    from _pytest.outcomes import Failed
+
+else:
+    # Not using pytest so define the things that would have been imported from
+    # there.
+
+    # _pytest._code.code.ExceptionInfo
+    class ExceptionInfo:
+        def __init__(self, value):
+            self.value = value
+
+        def __repr__(self):
+            return "".format(self.value)
+
+
+    def raises(expectedException, code=None):
+        """
+        Tests that ``code`` raises the exception ``expectedException``.
+
+        ``code`` may be a callable, such as a lambda expression or function
+        name.
+
+        If ``code`` is not given or None, ``raises`` will return a context
+        manager for use in ``with`` statements; the code to execute then
+        comes from the scope of the ``with``.
+
+        ``raises()`` does nothing if the callable raises the expected exception,
+        otherwise it raises an AssertionError.
+
+        Examples
+        ========
+
+        >>> from sympy.testing.pytest import raises
+
+        >>> raises(ZeroDivisionError, lambda: 1/0)
+        
+        >>> raises(ZeroDivisionError, lambda: 1/2)
+        Traceback (most recent call last):
+        ...
+        Failed: DID NOT RAISE
+
+        >>> with raises(ZeroDivisionError):
+        ...     n = 1/0
+        >>> with raises(ZeroDivisionError):
+        ...     n = 1/2
+        Traceback (most recent call last):
+        ...
+        Failed: DID NOT RAISE
+
+        Note that you cannot test multiple statements via
+        ``with raises``:
+
+        >>> with raises(ZeroDivisionError):
+        ...     n = 1/0    # will execute and raise, aborting the ``with``
+        ...     n = 9999/0 # never executed
+
+        This is just what ``with`` is supposed to do: abort the
+        contained statement sequence at the first exception and let
+        the context manager deal with the exception.
+
+        To test multiple statements, you'll need a separate ``with``
+        for each:
+
+        >>> with raises(ZeroDivisionError):
+        ...     n = 1/0    # will execute and raise
+        >>> with raises(ZeroDivisionError):
+        ...     n = 9999/0 # will also execute and raise
+
+        """
+        if code is None:
+            return RaisesContext(expectedException)
+        elif callable(code):
+            try:
+                code()
+            except expectedException as e:
+                return ExceptionInfo(e)
+            raise Failed("DID NOT RAISE")
+        elif isinstance(code, str):
+            raise TypeError(
+                '\'raises(xxx, "code")\' has been phased out; '
+                'change \'raises(xxx, "expression")\' '
+                'to \'raises(xxx, lambda: expression)\', '
+                '\'raises(xxx, "statement")\' '
+                'to \'with raises(xxx): statement\'')
+        else:
+            raise TypeError(
+                'raises() expects a callable for the 2nd argument.')
+
+    class RaisesContext:
+        def __init__(self, expectedException):
+            self.expectedException = expectedException
+
+        def __enter__(self):
+            return None
+
+        def __exit__(self, exc_type, exc_value, traceback):
+            if exc_type is None:
+                raise Failed("DID NOT RAISE")
+            return issubclass(exc_type, self.expectedException)
+
+    class XFail(Exception):
+        pass
+
+    class XPass(Exception):
+        pass
+
+    class Skipped(Exception):
+        pass
+
+    class Failed(Exception):  # type: ignore
+        pass
+
+    def XFAIL(func):
+        def wrapper():
+            try:
+                func()
+            except Exception as e:
+                message = str(e)
+                if message != "Timeout":
+                    raise XFail(func.__name__)
+                else:
+                    raise Skipped("Timeout")
+            raise XPass(func.__name__)
+
+        wrapper = functools.update_wrapper(wrapper, func)
+        return wrapper
+
+    def skip(str):
+        raise Skipped(str)
+
+    def SKIP(reason):
+        """Similar to ``skip()``, but this is a decorator. """
+        def wrapper(func):
+            def func_wrapper():
+                raise Skipped(reason)
+
+            func_wrapper = functools.update_wrapper(func_wrapper, func)
+            return func_wrapper
+
+        return wrapper
+
+    def slow(func):
+        func._slow = True
+
+        def func_wrapper():
+            func()
+
+        func_wrapper = functools.update_wrapper(func_wrapper, func)
+        func_wrapper.__wrapped__ = func
+        return func_wrapper
+
+    def tooslow(func):
+        func._slow = True
+        func._tooslow = True
+
+        def func_wrapper():
+            skip("Too slow")
+
+        func_wrapper = functools.update_wrapper(func_wrapper, func)
+        func_wrapper.__wrapped__ = func
+        return func_wrapper
+
+    def nocache_fail(func):
+        "Dummy decorator for marking tests that fail when cache is disabled"
+        return func
+
+@contextlib.contextmanager
+def warns(warningcls, *, match='', test_stacklevel=True):
+    '''
+    Like raises but tests that warnings are emitted.
+
+    >>> from sympy.testing.pytest import warns
+    >>> import warnings
+
+    >>> with warns(UserWarning):
+    ...     warnings.warn('deprecated', UserWarning, stacklevel=2)
+
+    >>> with warns(UserWarning):
+    ...     pass
+    Traceback (most recent call last):
+    ...
+    Failed: DID NOT WARN. No warnings of type UserWarning\
+    was emitted. The list of emitted warnings is: [].
+
+    ``test_stacklevel`` makes it check that the ``stacklevel`` parameter to
+    ``warn()`` is set so that the warning shows the user line of code (the
+    code under the warns() context manager). Set this to False if this is
+    ambiguous or if the context manager does not test the direct user code
+    that emits the warning.
+
+    If the warning is a ``SymPyDeprecationWarning``, this additionally tests
+    that the ``active_deprecations_target`` is a real target in the
+    ``active-deprecations.md`` file.
+
+    '''
+    # Absorbs all warnings in warnrec
+    with warnings.catch_warnings(record=True) as warnrec:
+        # Any warning other than the one we are looking for is an error
+        warnings.simplefilter("error")
+        warnings.filterwarnings("always", category=warningcls)
+        # Now run the test
+        yield warnrec
+
+    # Raise if expected warning not found
+    if not any(issubclass(w.category, warningcls) for w in warnrec):
+        msg = ('Failed: DID NOT WARN.'
+               ' No warnings of type %s was emitted.'
+               ' The list of emitted warnings is: %s.'
+               ) % (warningcls, [w.message for w in warnrec])
+        raise Failed(msg)
+
+    # We don't include the match in the filter above because it would then
+    # fall to the error filter, so we instead manually check that it matches
+    # here
+    for w in warnrec:
+        # Should always be true due to the filters above
+        assert issubclass(w.category, warningcls)
+        if not re.compile(match, re.IGNORECASE).match(str(w.message)):
+            raise Failed(f"Failed: WRONG MESSAGE. A warning with of the correct category ({warningcls.__name__}) was issued, but it did not match the given match regex ({match!r})")
+
+    if test_stacklevel:
+        for f in inspect.stack():
+            thisfile = f.filename
+            file = os.path.split(thisfile)[1]
+            if file.startswith('test_'):
+                break
+            elif file == 'doctest.py':
+                # skip the stacklevel testing in the doctests of this
+                # function
+                return
+        else:
+            raise RuntimeError("Could not find the file for the given warning to test the stacklevel")
+        for w in warnrec:
+            if w.filename != thisfile:
+                msg = f'''\
+Failed: Warning has the wrong stacklevel. The warning stacklevel needs to be
+set so that the line of code shown in the warning message is user code that
+calls the deprecated code (the current stacklevel is showing code from
+{w.filename} (line {w.lineno}), expected {thisfile})'''.replace('\n', ' ')
+                raise Failed(msg)
+
+    if warningcls == SymPyDeprecationWarning:
+        this_file = pathlib.Path(__file__)
+        active_deprecations_file = (this_file.parent.parent.parent / 'doc' /
+                                    'src' / 'explanation' /
+                                    'active-deprecations.md')
+        if not active_deprecations_file.exists():
+            # We can only test that the active_deprecations_target works if we are
+            # in the git repo.
+            return
+        targets = []
+        for w in warnrec:
+            targets.append(w.message.active_deprecations_target)
+        text = pathlib.Path(active_deprecations_file).read_text(encoding="utf-8")
+        for target in targets:
+            if f'({target})=' not in text:
+                raise Failed(f"The active deprecations target {target!r} does not appear to be a valid target in the active-deprecations.md file ({active_deprecations_file}).")
+
+def _both_exp_pow(func):
+    """
+    Decorator used to run the test twice: the first time `e^x` is represented
+    as ``Pow(E, x)``, the second time as ``exp(x)`` (exponential object is not
+    a power).
+
+    This is a temporary trick helping to manage the elimination of the class
+    ``exp`` in favor of a replacement by ``Pow(E, ...)``.
+    """
+    from sympy.core.parameters import _exp_is_pow
+
+    def func_wrap():
+        with _exp_is_pow(True):
+            func()
+        with _exp_is_pow(False):
+            func()
+
+    wrapper = functools.update_wrapper(func_wrap, func)
+    return wrapper
+
+
+@contextlib.contextmanager
+def warns_deprecated_sympy():
+    '''
+    Shorthand for ``warns(SymPyDeprecationWarning)``
+
+    This is the recommended way to test that ``SymPyDeprecationWarning`` is
+    emitted for deprecated features in SymPy. To test for other warnings use
+    ``warns``. To suppress warnings without asserting that they are emitted
+    use ``ignore_warnings``.
+
+    .. note::
+
+       ``warns_deprecated_sympy()`` is only intended for internal use in the
+       SymPy test suite to test that a deprecation warning triggers properly.
+       All other code in the SymPy codebase, including documentation examples,
+       should not use deprecated behavior.
+
+       If you are a user of SymPy and you want to disable
+       SymPyDeprecationWarnings, use ``warnings`` filters (see
+       :ref:`silencing-sympy-deprecation-warnings`).
+
+    >>> from sympy.testing.pytest import warns_deprecated_sympy
+    >>> from sympy.utilities.exceptions import sympy_deprecation_warning
+    >>> with warns_deprecated_sympy():
+    ...     sympy_deprecation_warning("Don't use",
+    ...        deprecated_since_version="1.0",
+    ...        active_deprecations_target="active-deprecations")
+
+    >>> with warns_deprecated_sympy():
+    ...     pass
+    Traceback (most recent call last):
+    ...
+    Failed: DID NOT WARN. No warnings of type \
+    SymPyDeprecationWarning was emitted. The list of emitted warnings is: [].
+
+    .. note::
+
+       Sometimes the stacklevel test will fail because the same warning is
+       emitted multiple times. In this case, you can use
+       :func:`sympy.utilities.exceptions.ignore_warnings` in the code to
+       prevent the ``SymPyDeprecationWarning`` from being emitted again
+       recursively. In rare cases it is impossible to have a consistent
+       ``stacklevel`` for deprecation warnings because different ways of
+       calling a function will produce different call stacks.. In those cases,
+       use ``warns(SymPyDeprecationWarning)`` instead.
+
+    See Also
+    ========
+    sympy.utilities.exceptions.SymPyDeprecationWarning
+    sympy.utilities.exceptions.sympy_deprecation_warning
+    sympy.utilities.decorator.deprecated
+
+    '''
+    with warns(SymPyDeprecationWarning):
+        yield
+
+
+def skip_under_pyodide(message):
+    """Decorator to skip a test if running under Pyodide/WASM."""
+    def decorator(test_func):
+        @functools.wraps(test_func)
+        def test_wrapper():
+            if IS_WASM:
+                skip(message)
+            return test_func()
+        return test_wrapper
+    return decorator
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/quality_unicode.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/quality_unicode.py
new file mode 100644
index 0000000000000000000000000000000000000000..d43623ff5112610e377347f50c6a40a15810644b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/quality_unicode.py
@@ -0,0 +1,102 @@
+import re
+import fnmatch
+
+
+message_unicode_B = \
+    "File contains a unicode character : %s, line %s. " \
+    "But not in the whitelist. " \
+    "Add the file to the whitelist in " + __file__
+message_unicode_D = \
+    "File does not contain a unicode character : %s." \
+    "but is in the whitelist. " \
+    "Remove the file from the whitelist in " + __file__
+
+
+encoding_header_re = re.compile(
+    r'^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)')
+
+# Whitelist pattern for files which can have unicode.
+unicode_whitelist = [
+    # Author names can include non-ASCII characters
+    r'*/bin/authors_update.py',
+    r'*/bin/mailmap_check.py',
+
+    # These files have functions and test functions for unicode input and
+    # output.
+    r'*/sympy/testing/tests/test_code_quality.py',
+    r'*/sympy/physics/vector/tests/test_printing.py',
+    r'*/physics/quantum/tests/test_printing.py',
+    r'*/sympy/vector/tests/test_printing.py',
+    r'*/sympy/parsing/tests/test_sympy_parser.py',
+    r'*/sympy/printing/pretty/stringpict.py',
+    r'*/sympy/printing/pretty/tests/test_pretty.py',
+    r'*/sympy/printing/tests/test_conventions.py',
+    r'*/sympy/printing/tests/test_preview.py',
+    r'*/liealgebras/type_g.py',
+    r'*/liealgebras/weyl_group.py',
+    r'*/liealgebras/tests/test_type_G.py',
+
+    # wigner.py and polarization.py have unicode doctests. These probably
+    # don't need to be there but some of the examples that are there are
+    # pretty ugly without use_unicode (matrices need to be wrapped across
+    # multiple lines etc)
+    r'*/sympy/physics/wigner.py',
+    r'*/sympy/physics/optics/polarization.py',
+
+    # joint.py uses some unicode for variable names in the docstrings
+    r'*/sympy/physics/mechanics/joint.py',
+
+    # lll method has unicode in docstring references and author name
+    r'*/sympy/polys/matrices/domainmatrix.py',
+    r'*/sympy/matrices/repmatrix.py',
+
+    # Explanation of symbols uses greek letters
+    r'*/sympy/core/symbol.py',
+]
+
+unicode_strict_whitelist = [
+    r'*/sympy/parsing/latex/_antlr/__init__.py',
+    # test_mathematica.py uses some unicode for testing Greek characters are working #24055
+    r'*/sympy/parsing/tests/test_mathematica.py',
+]
+
+
+def _test_this_file_encoding(
+    fname, test_file,
+    unicode_whitelist=unicode_whitelist,
+    unicode_strict_whitelist=unicode_strict_whitelist):
+    """Test helper function for unicode test
+
+    The test may have to operate on filewise manner, so it had moved
+    to a separate process.
+    """
+    has_unicode = False
+
+    is_in_whitelist = False
+    is_in_strict_whitelist = False
+    for patt in unicode_whitelist:
+        if fnmatch.fnmatch(fname, patt):
+            is_in_whitelist = True
+            break
+    for patt in unicode_strict_whitelist:
+        if fnmatch.fnmatch(fname, patt):
+            is_in_strict_whitelist = True
+            is_in_whitelist = True
+            break
+
+    if is_in_whitelist:
+        for idx, line in enumerate(test_file):
+            try:
+                line.encode(encoding='ascii')
+            except (UnicodeEncodeError, UnicodeDecodeError):
+                has_unicode = True
+
+        if not has_unicode and not is_in_strict_whitelist:
+            assert False, message_unicode_D % fname
+
+    else:
+        for idx, line in enumerate(test_file):
+            try:
+                line.encode(encoding='ascii')
+            except (UnicodeEncodeError, UnicodeDecodeError):
+                assert False, message_unicode_B % (fname, idx + 1)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/randtest.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/randtest.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ce2c8c031eec1c886532daba32c96d83e9cf85c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/randtest.py
@@ -0,0 +1,19 @@
+"""
+.. deprecated:: 1.10
+
+   ``sympy.testing.randtest`` functions have been moved to
+   :mod:`sympy.core.random`.
+
+"""
+from sympy.utilities.exceptions import sympy_deprecation_warning
+
+sympy_deprecation_warning("The sympy.testing.randtest submodule is deprecated. Use sympy.core.random instead.",
+    deprecated_since_version="1.10",
+    active_deprecations_target="deprecated-sympy-testing-randtest")
+
+from sympy.core.random import (  # noqa:F401
+    random_complex_number,
+    verify_numerically,
+    test_derivative_numerically,
+    _randrange,
+    _randint)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/runtests.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/runtests.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2650e4e6dabaaa07fc25c76cce3d9d28723b0d5
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/runtests.py
@@ -0,0 +1,2409 @@
+"""
+This is our testing framework.
+
+Goals:
+
+* it should be compatible with py.test and operate very similarly
+  (or identically)
+* does not require any external dependencies
+* preferably all the functionality should be in this file only
+* no magic, just import the test file and execute the test functions, that's it
+* portable
+
+"""
+
+import os
+import sys
+import platform
+import inspect
+import traceback
+import pdb
+import re
+import linecache
+import time
+from fnmatch import fnmatch
+from timeit import default_timer as clock
+import doctest as pdoctest  # avoid clashing with our doctest() function
+from doctest import DocTestFinder, DocTestRunner
+import random
+import subprocess
+import shutil
+import signal
+import stat
+import tempfile
+import warnings
+from contextlib import contextmanager
+from inspect import unwrap
+from pathlib import Path
+
+from sympy.core.cache import clear_cache
+from sympy.external import import_module
+from sympy.external.gmpy import GROUND_TYPES
+
+IS_WINDOWS = (os.name == 'nt')
+ON_CI = os.getenv('CI', None)
+
+# empirically generated list of the proportion of time spent running
+# an even split of tests.  This should periodically be regenerated.
+# A list of [.6, .1, .3] would mean that if the tests are evenly split
+# into '1/3', '2/3', '3/3', the first split would take 60% of the time,
+# the second 10% and the third 30%.  These lists are normalized to sum
+# to 1, so [60, 10, 30] has the same behavior as [6, 1, 3] or [.6, .1, .3].
+#
+# This list can be generated with the code:
+#     from time import time
+#     import sympy
+#     import os
+#     os.environ["CI"] = 'true' # Mock CI to get more correct densities
+#     delays, num_splits = [], 30
+#     for i in range(1, num_splits + 1):
+#         tic = time()
+#         sympy.test(split='{}/{}'.format(i, num_splits), time_balance=False) # Add slow=True for slow tests
+#         delays.append(time() - tic)
+#     tot = sum(delays)
+#     print([round(x / tot, 4) for x in delays])
+SPLIT_DENSITY = [
+    0.0059, 0.0027, 0.0068, 0.0011, 0.0006,
+    0.0058, 0.0047, 0.0046, 0.004, 0.0257,
+    0.0017, 0.0026, 0.004, 0.0032, 0.0016,
+    0.0015, 0.0004, 0.0011, 0.0016, 0.0014,
+    0.0077, 0.0137, 0.0217, 0.0074, 0.0043,
+    0.0067, 0.0236, 0.0004, 0.1189, 0.0142,
+    0.0234, 0.0003, 0.0003, 0.0047, 0.0006,
+    0.0013, 0.0004, 0.0008, 0.0007, 0.0006,
+    0.0139, 0.0013, 0.0007, 0.0051, 0.002,
+    0.0004, 0.0005, 0.0213, 0.0048, 0.0016,
+    0.0012, 0.0014, 0.0024, 0.0015, 0.0004,
+    0.0005, 0.0007, 0.011, 0.0062, 0.0015,
+    0.0021, 0.0049, 0.0006, 0.0006, 0.0011,
+    0.0006, 0.0019, 0.003, 0.0044, 0.0054,
+    0.0057, 0.0049, 0.0016, 0.0006, 0.0009,
+    0.0006, 0.0012, 0.0006, 0.0149, 0.0532,
+    0.0076, 0.0041, 0.0024, 0.0135, 0.0081,
+    0.2209, 0.0459, 0.0438, 0.0488, 0.0137,
+    0.002, 0.0003, 0.0008, 0.0039, 0.0024,
+    0.0005, 0.0004, 0.003, 0.056, 0.0026]
+SPLIT_DENSITY_SLOW = [0.0086, 0.0004, 0.0568, 0.0003, 0.0032, 0.0005, 0.0004, 0.0013, 0.0016, 0.0648, 0.0198, 0.1285, 0.098, 0.0005, 0.0064, 0.0003, 0.0004, 0.0026, 0.0007, 0.0051, 0.0089, 0.0024, 0.0033, 0.0057, 0.0005, 0.0003, 0.001, 0.0045, 0.0091, 0.0006, 0.0005, 0.0321, 0.0059, 0.1105, 0.216, 0.1489, 0.0004, 0.0003, 0.0006, 0.0483]
+
+class Skipped(Exception):
+    pass
+
+class TimeOutError(Exception):
+    pass
+
+class DependencyError(Exception):
+    pass
+
+
+def _indent(s, indent=4):
+    """
+    Add the given number of space characters to the beginning of
+    every non-blank line in ``s``, and return the result.
+    If the string ``s`` is Unicode, it is encoded using the stdout
+    encoding and the ``backslashreplace`` error handler.
+    """
+    # This regexp matches the start of non-blank lines:
+    return re.sub('(?m)^(?!$)', indent*' ', s)
+
+
+pdoctest._indent = _indent  # type: ignore
+
+# override reporter to maintain windows and python3
+
+
+def _report_failure(self, out, test, example, got):
+    """
+    Report that the given example failed.
+    """
+    s = self._checker.output_difference(example, got, self.optionflags)
+    s = s.encode('raw_unicode_escape').decode('utf8', 'ignore')
+    out(self._failure_header(test, example) + s)
+
+
+if IS_WINDOWS:
+    DocTestRunner.report_failure = _report_failure  # type: ignore
+
+
+def convert_to_native_paths(lst):
+    """
+    Converts a list of '/' separated paths into a list of
+    native (os.sep separated) paths and converts to lowercase
+    if the system is case insensitive.
+    """
+    newlst = []
+    for rv in lst:
+        rv = os.path.join(*rv.split("/"))
+        # on windows the slash after the colon is dropped
+        if sys.platform == "win32":
+            pos = rv.find(':')
+            if pos != -1:
+                if rv[pos + 1] != '\\':
+                    rv = rv[:pos + 1] + '\\' + rv[pos + 1:]
+        newlst.append(os.path.normcase(rv))
+    return newlst
+
+
+def get_sympy_dir():
+    """
+    Returns the root SymPy directory and set the global value
+    indicating whether the system is case sensitive or not.
+    """
+    this_file = os.path.abspath(__file__)
+    sympy_dir = os.path.join(os.path.dirname(this_file), "..", "..")
+    sympy_dir = os.path.normpath(sympy_dir)
+    return os.path.normcase(sympy_dir)
+
+
+def setup_pprint(disable_line_wrap=True):
+    from sympy.interactive.printing import init_printing
+    from sympy.printing.pretty.pretty import pprint_use_unicode
+    import sympy.interactive.printing as interactive_printing
+    from sympy.printing.pretty import stringpict
+
+    # Prevent init_printing() in doctests from affecting other doctests
+    interactive_printing.NO_GLOBAL = True
+
+    # force pprint to be in ascii mode in doctests
+    use_unicode_prev = pprint_use_unicode(False)
+
+    # disable line wrapping for pprint() outputs
+    wrap_line_prev = stringpict._GLOBAL_WRAP_LINE
+    if disable_line_wrap:
+        stringpict._GLOBAL_WRAP_LINE = False
+
+    # hook our nice, hash-stable strprinter
+    init_printing(pretty_print=False)
+
+    return use_unicode_prev, wrap_line_prev
+
+
+@contextmanager
+def raise_on_deprecated():
+    """Context manager to make DeprecationWarning raise an error
+
+    This is to catch SymPyDeprecationWarning from library code while running
+    tests and doctests. It is important to use this context manager around
+    each individual test/doctest in case some tests modify the warning
+    filters.
+    """
+    with warnings.catch_warnings():
+        warnings.filterwarnings('error', '.*', DeprecationWarning, module='sympy.*')
+        yield
+
+
+def run_in_subprocess_with_hash_randomization(
+        function, function_args=(),
+        function_kwargs=None, command=sys.executable,
+        module='sympy.testing.runtests', force=False):
+    """
+    Run a function in a Python subprocess with hash randomization enabled.
+
+    If hash randomization is not supported by the version of Python given, it
+    returns False.  Otherwise, it returns the exit value of the command.  The
+    function is passed to sys.exit(), so the return value of the function will
+    be the return value.
+
+    The environment variable PYTHONHASHSEED is used to seed Python's hash
+    randomization.  If it is set, this function will return False, because
+    starting a new subprocess is unnecessary in that case.  If it is not set,
+    one is set at random, and the tests are run.  Note that if this
+    environment variable is set when Python starts, hash randomization is
+    automatically enabled.  To force a subprocess to be created even if
+    PYTHONHASHSEED is set, pass ``force=True``.  This flag will not force a
+    subprocess in Python versions that do not support hash randomization (see
+    below), because those versions of Python do not support the ``-R`` flag.
+
+    ``function`` should be a string name of a function that is importable from
+    the module ``module``, like "_test".  The default for ``module`` is
+    "sympy.testing.runtests".  ``function_args`` and ``function_kwargs``
+    should be a repr-able tuple and dict, respectively.  The default Python
+    command is sys.executable, which is the currently running Python command.
+
+    This function is necessary because the seed for hash randomization must be
+    set by the environment variable before Python starts.  Hence, in order to
+    use a predetermined seed for tests, we must start Python in a separate
+    subprocess.
+
+    Hash randomization was added in the minor Python versions 2.6.8, 2.7.3,
+    3.1.5, and 3.2.3, and is enabled by default in all Python versions after
+    and including 3.3.0.
+
+    Examples
+    ========
+
+    >>> from sympy.testing.runtests import (
+    ... run_in_subprocess_with_hash_randomization)
+    >>> # run the core tests in verbose mode
+    >>> run_in_subprocess_with_hash_randomization("_test",
+    ... function_args=("core",),
+    ... function_kwargs={'verbose': True}) # doctest: +SKIP
+    # Will return 0 if sys.executable supports hash randomization and tests
+    # pass, 1 if they fail, and False if it does not support hash
+    # randomization.
+
+    """
+    cwd = get_sympy_dir()
+    # Note, we must return False everywhere, not None, as subprocess.call will
+    # sometimes return None.
+
+    # First check if the Python version supports hash randomization
+    # If it does not have this support, it won't recognize the -R flag
+    p = subprocess.Popen([command, "-RV"], stdout=subprocess.PIPE,
+                         stderr=subprocess.STDOUT, cwd=cwd)
+    p.communicate()
+    if p.returncode != 0:
+        return False
+
+    hash_seed = os.getenv("PYTHONHASHSEED")
+    if not hash_seed:
+        os.environ["PYTHONHASHSEED"] = str(random.randrange(2**32))
+    else:
+        if not force:
+            return False
+
+    function_kwargs = function_kwargs or {}
+
+    # Now run the command
+    commandstring = ("import sys; from %s import %s;sys.exit(%s(*%s, **%s))" %
+                     (module, function, function, repr(function_args),
+                      repr(function_kwargs)))
+
+    try:
+        p = subprocess.Popen([command, "-R", "-c", commandstring], cwd=cwd)
+        p.communicate()
+    except KeyboardInterrupt:
+        p.wait()
+    finally:
+        # Put the environment variable back, so that it reads correctly for
+        # the current Python process.
+        if hash_seed is None:
+            del os.environ["PYTHONHASHSEED"]
+        else:
+            os.environ["PYTHONHASHSEED"] = hash_seed
+        return p.returncode
+
+
+def run_all_tests(test_args=(), test_kwargs=None,
+                  doctest_args=(), doctest_kwargs=None,
+                  examples_args=(), examples_kwargs=None):
+    """
+    Run all tests.
+
+    Right now, this runs the regular tests (bin/test), the doctests
+    (bin/doctest), and the examples (examples/all.py).
+
+    This is what ``setup.py test`` uses.
+
+    You can pass arguments and keyword arguments to the test functions that
+    support them (for now, test,  doctest, and the examples). See the
+    docstrings of those functions for a description of the available options.
+
+    For example, to run the solvers tests with colors turned off:
+
+    >>> from sympy.testing.runtests import run_all_tests
+    >>> run_all_tests(test_args=("solvers",),
+    ... test_kwargs={"colors:False"}) # doctest: +SKIP
+
+    """
+    tests_successful = True
+
+    test_kwargs = test_kwargs or {}
+    doctest_kwargs = doctest_kwargs or {}
+    examples_kwargs = examples_kwargs or {'quiet': True}
+
+    try:
+        # Regular tests
+        if not test(*test_args, **test_kwargs):
+            # some regular test fails, so set the tests_successful
+            # flag to false and continue running the doctests
+            tests_successful = False
+
+        # Doctests
+        print()
+        if not doctest(*doctest_args, **doctest_kwargs):
+            tests_successful = False
+
+        # Examples
+        print()
+        sys.path.append("examples")   # examples/all.py
+        from all import run_examples  # type: ignore
+        if not run_examples(*examples_args, **examples_kwargs):
+            tests_successful = False
+
+        if tests_successful:
+            return
+        else:
+            # Return nonzero exit code
+            sys.exit(1)
+    except KeyboardInterrupt:
+        print()
+        print("DO *NOT* COMMIT!")
+        sys.exit(1)
+
+
+def test(*paths, subprocess=True, rerun=0, **kwargs):
+    """
+    Run tests in the specified test_*.py files.
+
+    Tests in a particular test_*.py file are run if any of the given strings
+    in ``paths`` matches a part of the test file's path. If ``paths=[]``,
+    tests in all test_*.py files are run.
+
+    Notes:
+
+    - If sort=False, tests are run in random order (not default).
+    - Paths can be entered in native system format or in unix,
+      forward-slash format.
+    - Files that are on the blacklist can be tested by providing
+      their path; they are only excluded if no paths are given.
+
+    **Explanation of test results**
+
+    ======  ===============================================================
+    Output  Meaning
+    ======  ===============================================================
+    .       passed
+    F       failed
+    X       XPassed (expected to fail but passed)
+    f       XFAILed (expected to fail and indeed failed)
+    s       skipped
+    w       slow
+    T       timeout (e.g., when ``--timeout`` is used)
+    K       KeyboardInterrupt (when running the slow tests with ``--slow``,
+            you can interrupt one of them without killing the test runner)
+    ======  ===============================================================
+
+
+    Colors have no additional meaning and are used just to facilitate
+    interpreting the output.
+
+    Examples
+    ========
+
+    >>> import sympy
+
+    Run all tests:
+
+    >>> sympy.test()    # doctest: +SKIP
+
+    Run one file:
+
+    >>> sympy.test("sympy/core/tests/test_basic.py")    # doctest: +SKIP
+    >>> sympy.test("_basic")    # doctest: +SKIP
+
+    Run all tests in sympy/functions/ and some particular file:
+
+    >>> sympy.test("sympy/core/tests/test_basic.py",
+    ...        "sympy/functions")    # doctest: +SKIP
+
+    Run all tests in sympy/core and sympy/utilities:
+
+    >>> sympy.test("/core", "/util")    # doctest: +SKIP
+
+    Run specific test from a file:
+
+    >>> sympy.test("sympy/core/tests/test_basic.py",
+    ...        kw="test_equality")    # doctest: +SKIP
+
+    Run specific test from any file:
+
+    >>> sympy.test(kw="subs")    # doctest: +SKIP
+
+    Run the tests with verbose mode on:
+
+    >>> sympy.test(verbose=True)    # doctest: +SKIP
+
+    Do not sort the test output:
+
+    >>> sympy.test(sort=False)    # doctest: +SKIP
+
+    Turn on post-mortem pdb:
+
+    >>> sympy.test(pdb=True)    # doctest: +SKIP
+
+    Turn off colors:
+
+    >>> sympy.test(colors=False)    # doctest: +SKIP
+
+    Force colors, even when the output is not to a terminal (this is useful,
+    e.g., if you are piping to ``less -r`` and you still want colors)
+
+    >>> sympy.test(force_colors=False)    # doctest: +SKIP
+
+    The traceback verboseness can be set to "short" or "no" (default is
+    "short")
+
+    >>> sympy.test(tb='no')    # doctest: +SKIP
+
+    The ``split`` option can be passed to split the test run into parts. The
+    split currently only splits the test files, though this may change in the
+    future. ``split`` should be a string of the form 'a/b', which will run
+    part ``a`` of ``b``. For instance, to run the first half of the test suite:
+
+    >>> sympy.test(split='1/2')  # doctest: +SKIP
+
+    The ``time_balance`` option can be passed in conjunction with ``split``.
+    If ``time_balance=True`` (the default for ``sympy.test``), SymPy will attempt
+    to split the tests such that each split takes equal time.  This heuristic
+    for balancing is based on pre-recorded test data.
+
+    >>> sympy.test(split='1/2', time_balance=True)  # doctest: +SKIP
+
+    You can disable running the tests in a separate subprocess using
+    ``subprocess=False``.  This is done to support seeding hash randomization,
+    which is enabled by default in the Python versions where it is supported.
+    If subprocess=False, hash randomization is enabled/disabled according to
+    whether it has been enabled or not in the calling Python process.
+    However, even if it is enabled, the seed cannot be printed unless it is
+    called from a new Python process.
+
+    Hash randomization was added in the minor Python versions 2.6.8, 2.7.3,
+    3.1.5, and 3.2.3, and is enabled by default in all Python versions after
+    and including 3.3.0.
+
+    If hash randomization is not supported ``subprocess=False`` is used
+    automatically.
+
+    >>> sympy.test(subprocess=False)     # doctest: +SKIP
+
+    To set the hash randomization seed, set the environment variable
+    ``PYTHONHASHSEED`` before running the tests.  This can be done from within
+    Python using
+
+    >>> import os
+    >>> os.environ['PYTHONHASHSEED'] = '42' # doctest: +SKIP
+
+    Or from the command line using
+
+    $ PYTHONHASHSEED=42 ./bin/test
+
+    If the seed is not set, a random seed will be chosen.
+
+    Note that to reproduce the same hash values, you must use both the same seed
+    as well as the same architecture (32-bit vs. 64-bit).
+
+    """
+    # count up from 0, do not print 0
+    print_counter = lambda i : (print("rerun %d" % (rerun-i))
+                                if rerun-i else None)
+
+    if subprocess:
+        # loop backwards so last i is 0
+        for i in range(rerun, -1, -1):
+            print_counter(i)
+            ret = run_in_subprocess_with_hash_randomization("_test",
+                        function_args=paths, function_kwargs=kwargs)
+            if ret is False:
+                break
+            val = not bool(ret)
+            # exit on the first failure or if done
+            if not val or i == 0:
+                return val
+
+    # rerun even if hash randomization is not supported
+    for i in range(rerun, -1, -1):
+        print_counter(i)
+        val = not bool(_test(*paths, **kwargs))
+        if not val or i == 0:
+            return val
+
+
+def _test(*paths,
+        verbose=False, tb="short", kw=None, pdb=False, colors=True,
+        force_colors=False, sort=True, seed=None, timeout=False,
+        fail_on_timeout=False, slow=False, enhance_asserts=False, split=None,
+        time_balance=True, blacklist=(),
+        fast_threshold=None, slow_threshold=None):
+    """
+    Internal function that actually runs the tests.
+
+    All keyword arguments from ``test()`` are passed to this function except for
+    ``subprocess``.
+
+    Returns 0 if tests passed and 1 if they failed.  See the docstring of
+    ``test()`` for more information.
+    """
+    kw = kw or ()
+    # ensure that kw is a tuple
+    if isinstance(kw, str):
+        kw = (kw,)
+    post_mortem = pdb
+    if seed is None:
+        seed = random.randrange(100000000)
+    if ON_CI and timeout is False:
+        timeout = 595
+        fail_on_timeout = True
+    if ON_CI:
+        blacklist = list(blacklist) + ['sympy/plotting/pygletplot/tests']
+    blacklist = convert_to_native_paths(blacklist)
+    r = PyTestReporter(verbose=verbose, tb=tb, colors=colors,
+        force_colors=force_colors, split=split)
+    # This won't strictly run the test for the corresponding file, but it is
+    # good enough for copying and pasting the failing test.
+    _paths = []
+    for path in paths:
+        if '::' in path:
+            path, _kw = path.split('::', 1)
+            kw += (_kw,)
+        _paths.append(path)
+    paths = _paths
+
+    t = SymPyTests(r, kw, post_mortem, seed,
+                   fast_threshold=fast_threshold,
+                   slow_threshold=slow_threshold)
+
+    test_files = t.get_test_files('sympy')
+
+    not_blacklisted = [f for f in test_files
+                       if not any(b in f for b in blacklist)]
+
+    if len(paths) == 0:
+        matched = not_blacklisted
+    else:
+        paths = convert_to_native_paths(paths)
+        matched = []
+        for f in not_blacklisted:
+            basename = os.path.basename(f)
+            for p in paths:
+                if p in f or fnmatch(basename, p):
+                    matched.append(f)
+                    break
+
+    density = None
+    if time_balance:
+        if slow:
+            density = SPLIT_DENSITY_SLOW
+        else:
+            density = SPLIT_DENSITY
+
+    if split:
+        matched = split_list(matched, split, density=density)
+
+    t._testfiles.extend(matched)
+
+    return int(not t.test(sort=sort, timeout=timeout, slow=slow,
+        enhance_asserts=enhance_asserts, fail_on_timeout=fail_on_timeout))
+
+
+def doctest(*paths, subprocess=True, rerun=0, **kwargs):
+    r"""
+    Runs doctests in all \*.py files in the SymPy directory which match
+    any of the given strings in ``paths`` or all tests if paths=[].
+
+    Notes:
+
+    - Paths can be entered in native system format or in unix,
+      forward-slash format.
+    - Files that are on the blacklist can be tested by providing
+      their path; they are only excluded if no paths are given.
+
+    Examples
+    ========
+
+    >>> import sympy
+
+    Run all tests:
+
+    >>> sympy.doctest() # doctest: +SKIP
+
+    Run one file:
+
+    >>> sympy.doctest("sympy/core/basic.py") # doctest: +SKIP
+    >>> sympy.doctest("polynomial.rst") # doctest: +SKIP
+
+    Run all tests in sympy/functions/ and some particular file:
+
+    >>> sympy.doctest("/functions", "basic.py") # doctest: +SKIP
+
+    Run any file having polynomial in its name, doc/src/modules/polynomial.rst,
+    sympy/functions/special/polynomials.py, and sympy/polys/polynomial.py:
+
+    >>> sympy.doctest("polynomial") # doctest: +SKIP
+
+    The ``split`` option can be passed to split the test run into parts. The
+    split currently only splits the test files, though this may change in the
+    future. ``split`` should be a string of the form 'a/b', which will run
+    part ``a`` of ``b``. Note that the regular doctests and the Sphinx
+    doctests are split independently. For instance, to run the first half of
+    the test suite:
+
+    >>> sympy.doctest(split='1/2')  # doctest: +SKIP
+
+    The ``subprocess`` and ``verbose`` options are the same as with the function
+    ``test()`` (see the docstring of that function for more information) except
+    that ``verbose`` may also be set equal to ``2`` in order to print
+    individual doctest lines, as they are being tested.
+    """
+    # count up from 0, do not print 0
+    print_counter = lambda i : (print("rerun %d" % (rerun-i))
+                                if rerun-i else None)
+
+    if subprocess:
+        # loop backwards so last i is 0
+        for i in range(rerun, -1, -1):
+            print_counter(i)
+            ret = run_in_subprocess_with_hash_randomization("_doctest",
+                        function_args=paths, function_kwargs=kwargs)
+            if ret is False:
+                break
+            val = not bool(ret)
+            # exit on the first failure or if done
+            if not val or i == 0:
+                return val
+
+    # rerun even if hash randomization is not supported
+    for i in range(rerun, -1, -1):
+        print_counter(i)
+        val = not bool(_doctest(*paths, **kwargs))
+        if not val or i == 0:
+            return val
+
+
+def _get_doctest_blacklist():
+    '''Get the default blacklist for the doctests'''
+    blacklist = []
+
+    blacklist.extend([
+        "doc/src/modules/plotting.rst",  # generates live plots
+        "doc/src/modules/physics/mechanics/autolev_parser.rst",
+        "sympy/codegen/array_utils.py", # raises deprecation warning
+        "sympy/core/compatibility.py", # backwards compatibility shim, importing it triggers a deprecation warning
+        "sympy/core/trace.py", # backwards compatibility shim, importing it triggers a deprecation warning
+        "sympy/galgebra.py", # no longer part of SymPy
+        "sympy/parsing/autolev/_antlr/autolevlexer.py", # generated code
+        "sympy/parsing/autolev/_antlr/autolevlistener.py", # generated code
+        "sympy/parsing/autolev/_antlr/autolevparser.py", # generated code
+        "sympy/parsing/latex/_antlr/latexlexer.py", # generated code
+        "sympy/parsing/latex/_antlr/latexparser.py", # generated code
+        "sympy/plotting/pygletplot/__init__.py", # crashes on some systems
+        "sympy/plotting/pygletplot/plot.py", # crashes on some systems
+        "sympy/printing/ccode.py", # backwards compatibility shim, importing it breaks the codegen doctests
+        "sympy/printing/cxxcode.py", # backwards compatibility shim, importing it breaks the codegen doctests
+        "sympy/printing/fcode.py", # backwards compatibility shim, importing it breaks the codegen doctests
+        "sympy/testing/randtest.py", # backwards compatibility shim, importing it triggers a deprecation warning
+        "sympy/this.py", # prints text
+    ])
+    # autolev parser tests
+    num = 12
+    for i in range (1, num+1):
+        blacklist.append("sympy/parsing/autolev/test-examples/ruletest" + str(i) + ".py")
+    blacklist.extend(["sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.py",
+                      "sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py",
+                      "sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.py",
+                      "sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.py"])
+
+    if import_module('numpy') is None:
+        blacklist.extend([
+            "sympy/plotting/experimental_lambdify.py",
+            "sympy/plotting/plot_implicit.py",
+            "examples/advanced/autowrap_integrators.py",
+            "examples/advanced/autowrap_ufuncify.py",
+            "examples/intermediate/sample.py",
+            "examples/intermediate/mplot2d.py",
+            "examples/intermediate/mplot3d.py",
+            "doc/src/modules/numeric-computation.rst",
+            "doc/src/explanation/best-practices.md",
+            "doc/src/tutorials/physics/biomechanics/biomechanical-model-example.rst",
+            "doc/src/tutorials/physics/biomechanics/biomechanics.rst",
+        ])
+    else:
+        if import_module('matplotlib') is None:
+            blacklist.extend([
+                "examples/intermediate/mplot2d.py",
+                "examples/intermediate/mplot3d.py"
+            ])
+        else:
+            # Use a non-windowed backend, so that the tests work on CI
+            import matplotlib
+            matplotlib.use('Agg')
+
+    if ON_CI or import_module('pyglet') is None:
+        blacklist.extend(["sympy/plotting/pygletplot"])
+
+    if import_module('aesara') is None:
+        blacklist.extend([
+            "sympy/printing/aesaracode.py",
+            "doc/src/modules/numeric-computation.rst",
+        ])
+
+    if import_module('cupy') is None:
+        blacklist.extend([
+            "doc/src/modules/numeric-computation.rst",
+        ])
+
+    if import_module('jax') is None:
+        blacklist.extend([
+            "doc/src/modules/numeric-computation.rst",
+        ])
+
+    if import_module('antlr4') is None:
+        blacklist.extend([
+            "sympy/parsing/autolev/__init__.py",
+            "sympy/parsing/latex/_parse_latex_antlr.py",
+        ])
+
+    if import_module('lfortran') is None:
+        #throws ImportError when lfortran not installed
+        blacklist.extend([
+            "sympy/parsing/sym_expr.py",
+        ])
+
+    if import_module("scipy") is None:
+        # throws ModuleNotFoundError when scipy not installed
+        blacklist.extend([
+            "doc/src/guides/solving/solve-numerically.md",
+            "doc/src/guides/solving/solve-ode.md",
+        ])
+
+    if import_module("numpy") is None:
+        # throws ModuleNotFoundError when numpy not installed
+        blacklist.extend([
+                "doc/src/guides/solving/solve-ode.md",
+                "doc/src/guides/solving/solve-numerically.md",
+        ])
+
+    # disabled because of doctest failures in asmeurer's bot
+    blacklist.extend([
+        "sympy/utilities/autowrap.py",
+        "examples/advanced/autowrap_integrators.py",
+        "examples/advanced/autowrap_ufuncify.py"
+        ])
+
+    blacklist.extend([
+        "sympy/conftest.py", # Depends on pytest
+    ])
+
+    # These are deprecated stubs to be removed:
+    blacklist.extend([
+        "sympy/utilities/tmpfiles.py",
+        "sympy/utilities/pytest.py",
+        "sympy/utilities/runtests.py",
+        "sympy/utilities/quality_unicode.py",
+        "sympy/utilities/randtest.py",
+    ])
+
+    blacklist = convert_to_native_paths(blacklist)
+    return blacklist
+
+
+def _doctest(*paths, **kwargs):
+    """
+    Internal function that actually runs the doctests.
+
+    All keyword arguments from ``doctest()`` are passed to this function
+    except for ``subprocess``.
+
+    Returns 0 if tests passed and 1 if they failed.  See the docstrings of
+    ``doctest()`` and ``test()`` for more information.
+    """
+    from sympy.printing.pretty.pretty import pprint_use_unicode
+    from sympy.printing.pretty import stringpict
+
+    normal = kwargs.get("normal", False)
+    verbose = kwargs.get("verbose", False)
+    colors = kwargs.get("colors", True)
+    force_colors = kwargs.get("force_colors", False)
+    blacklist = kwargs.get("blacklist", [])
+    split  = kwargs.get('split', None)
+
+    blacklist.extend(_get_doctest_blacklist())
+
+    # Use a non-windowed backend, so that the tests work on CI
+    if import_module('matplotlib') is not None:
+        import matplotlib
+        matplotlib.use('Agg')
+
+    # Disable warnings for external modules
+    import sympy.external
+    sympy.external.importtools.WARN_OLD_VERSION = False
+    sympy.external.importtools.WARN_NOT_INSTALLED = False
+
+    # Disable showing up of plots
+    from sympy.plotting.plot import unset_show
+    unset_show()
+
+    r = PyTestReporter(verbose, split=split, colors=colors,\
+                       force_colors=force_colors)
+    t = SymPyDocTests(r, normal)
+
+    test_files = t.get_test_files('sympy')
+    test_files.extend(t.get_test_files('examples', init_only=False))
+
+    not_blacklisted = [f for f in test_files
+                       if not any(b in f for b in blacklist)]
+    if len(paths) == 0:
+        matched = not_blacklisted
+    else:
+        # take only what was requested...but not blacklisted items
+        # and allow for partial match anywhere or fnmatch of name
+        paths = convert_to_native_paths(paths)
+        matched = []
+        for f in not_blacklisted:
+            basename = os.path.basename(f)
+            for p in paths:
+                if p in f or fnmatch(basename, p):
+                    matched.append(f)
+                    break
+
+    matched.sort()
+
+    if split:
+        matched = split_list(matched, split)
+
+    t._testfiles.extend(matched)
+
+    # run the tests and record the result for this *py portion of the tests
+    if t._testfiles:
+        failed = not t.test()
+    else:
+        failed = False
+
+    # N.B.
+    # --------------------------------------------------------------------
+    # Here we test *.rst and *.md files at or below doc/src. Code from these
+    # must be self supporting in terms of imports since there is no importing
+    # of necessary modules by doctest.testfile. If you try to pass *.py files
+    # through this they might fail because they will lack the needed imports
+    # and smarter parsing that can be done with source code.
+    #
+    test_files_rst = t.get_test_files('doc/src', '*.rst', init_only=False)
+    test_files_md = t.get_test_files('doc/src', '*.md', init_only=False)
+    test_files = test_files_rst + test_files_md
+    test_files.sort()
+
+    not_blacklisted = [f for f in test_files
+                       if not any(b in f for b in blacklist)]
+
+    if len(paths) == 0:
+        matched = not_blacklisted
+    else:
+        # Take only what was requested as long as it's not on the blacklist.
+        # Paths were already made native in *py tests so don't repeat here.
+        # There's no chance of having a *py file slip through since we
+        # only have *rst files in test_files.
+        matched = []
+        for f in not_blacklisted:
+            basename = os.path.basename(f)
+            for p in paths:
+                if p in f or fnmatch(basename, p):
+                    matched.append(f)
+                    break
+
+    if split:
+        matched = split_list(matched, split)
+
+    first_report = True
+    for rst_file in matched:
+        if not os.path.isfile(rst_file):
+            continue
+        old_displayhook = sys.displayhook
+        try:
+            use_unicode_prev, wrap_line_prev = setup_pprint()
+            out = sympytestfile(
+                rst_file, module_relative=False, encoding='utf-8',
+                optionflags=pdoctest.ELLIPSIS | pdoctest.NORMALIZE_WHITESPACE |
+                pdoctest.IGNORE_EXCEPTION_DETAIL)
+        finally:
+            # make sure we return to the original displayhook in case some
+            # doctest has changed that
+            sys.displayhook = old_displayhook
+            # The NO_GLOBAL flag overrides the no_global flag to init_printing
+            # if True
+            import sympy.interactive.printing as interactive_printing
+            interactive_printing.NO_GLOBAL = False
+            pprint_use_unicode(use_unicode_prev)
+            stringpict._GLOBAL_WRAP_LINE = wrap_line_prev
+
+        rstfailed, tested = out
+        if tested:
+            failed = rstfailed or failed
+            if first_report:
+                first_report = False
+                msg = 'rst/md doctests start'
+                if not t._testfiles:
+                    r.start(msg=msg)
+                else:
+                    r.write_center(msg)
+                    print()
+            # use as the id, everything past the first 'sympy'
+            file_id = rst_file[rst_file.find('sympy') + len('sympy') + 1:]
+            print(file_id, end=" ")
+                # get at least the name out so it is know who is being tested
+            wid = r.terminal_width - len(file_id) - 1  # update width
+            test_file = '[%s]' % (tested)
+            report = '[%s]' % (rstfailed or 'OK')
+            print(''.join(
+                [test_file, ' '*(wid - len(test_file) - len(report)), report])
+            )
+
+    # the doctests for *py will have printed this message already if there was
+    # a failure, so now only print it if there was intervening reporting by
+    # testing the *rst as evidenced by first_report no longer being True.
+    if not first_report and failed:
+        print()
+        print("DO *NOT* COMMIT!")
+
+    return int(failed)
+
+sp = re.compile(r'([0-9]+)/([1-9][0-9]*)')
+
+def split_list(l, split, density=None):
+    """
+    Splits a list into part a of b
+
+    split should be a string of the form 'a/b'. For instance, '1/3' would give
+    the split one of three.
+
+    If the length of the list is not divisible by the number of splits, the
+    last split will have more items.
+
+    `density` may be specified as a list.  If specified,
+    tests will be balanced so that each split has as equal-as-possible
+    amount of mass according to `density`.
+
+    >>> from sympy.testing.runtests import split_list
+    >>> a = list(range(10))
+    >>> split_list(a, '1/3')
+    [0, 1, 2]
+    >>> split_list(a, '2/3')
+    [3, 4, 5]
+    >>> split_list(a, '3/3')
+    [6, 7, 8, 9]
+    """
+    m = sp.match(split)
+    if not m:
+        raise ValueError("split must be a string of the form a/b where a and b are ints")
+    i, t = map(int, m.groups())
+
+    if not density:
+        return l[(i - 1)*len(l)//t : i*len(l)//t]
+
+    # normalize density
+    tot = sum(density)
+    density = [x / tot for x in density]
+
+    def density_inv(x):
+        """Interpolate the inverse to the cumulative
+        distribution function given by density"""
+        if x <= 0:
+            return 0
+        if x >= sum(density):
+            return 1
+
+        # find the first time the cumulative sum surpasses x
+        # and linearly interpolate
+        cumm = 0
+        for i, d in enumerate(density):
+            cumm += d
+            if cumm >= x:
+                break
+        frac = (d - (cumm - x)) / d
+        return (i + frac) / len(density)
+
+    lower_frac = density_inv((i - 1) / t)
+    higher_frac = density_inv(i / t)
+    return l[int(lower_frac*len(l)) : int(higher_frac*len(l))]
+
+from collections import namedtuple
+SymPyTestResults = namedtuple('SymPyTestResults', 'failed attempted')
+
+def sympytestfile(filename, module_relative=True, name=None, package=None,
+             globs=None, verbose=None, report=True, optionflags=0,
+             extraglobs=None, raise_on_error=False,
+             parser=pdoctest.DocTestParser(), encoding=None):
+
+    """
+    Test examples in the given file.  Return (#failures, #tests).
+
+    Optional keyword arg ``module_relative`` specifies how filenames
+    should be interpreted:
+
+    - If ``module_relative`` is True (the default), then ``filename``
+      specifies a module-relative path.  By default, this path is
+      relative to the calling module's directory; but if the
+      ``package`` argument is specified, then it is relative to that
+      package.  To ensure os-independence, ``filename`` should use
+      "/" characters to separate path segments, and should not
+      be an absolute path (i.e., it may not begin with "/").
+
+    - If ``module_relative`` is False, then ``filename`` specifies an
+      os-specific path.  The path may be absolute or relative (to
+      the current working directory).
+
+    Optional keyword arg ``name`` gives the name of the test; by default
+    use the file's basename.
+
+    Optional keyword argument ``package`` is a Python package or the
+    name of a Python package whose directory should be used as the
+    base directory for a module relative filename.  If no package is
+    specified, then the calling module's directory is used as the base
+    directory for module relative filenames.  It is an error to
+    specify ``package`` if ``module_relative`` is False.
+
+    Optional keyword arg ``globs`` gives a dict to be used as the globals
+    when executing examples; by default, use {}.  A copy of this dict
+    is actually used for each docstring, so that each docstring's
+    examples start with a clean slate.
+
+    Optional keyword arg ``extraglobs`` gives a dictionary that should be
+    merged into the globals that are used to execute examples.  By
+    default, no extra globals are used.
+
+    Optional keyword arg ``verbose`` prints lots of stuff if true, prints
+    only failures if false; by default, it's true iff "-v" is in sys.argv.
+
+    Optional keyword arg ``report`` prints a summary at the end when true,
+    else prints nothing at the end.  In verbose mode, the summary is
+    detailed, else very brief (in fact, empty if all tests passed).
+
+    Optional keyword arg ``optionflags`` or's together module constants,
+    and defaults to 0.  Possible values (see the docs for details):
+
+    - DONT_ACCEPT_TRUE_FOR_1
+    - DONT_ACCEPT_BLANKLINE
+    - NORMALIZE_WHITESPACE
+    - ELLIPSIS
+    - SKIP
+    - IGNORE_EXCEPTION_DETAIL
+    - REPORT_UDIFF
+    - REPORT_CDIFF
+    - REPORT_NDIFF
+    - REPORT_ONLY_FIRST_FAILURE
+
+    Optional keyword arg ``raise_on_error`` raises an exception on the
+    first unexpected exception or failure. This allows failures to be
+    post-mortem debugged.
+
+    Optional keyword arg ``parser`` specifies a DocTestParser (or
+    subclass) that should be used to extract tests from the files.
+
+    Optional keyword arg ``encoding`` specifies an encoding that should
+    be used to convert the file to unicode.
+
+    Advanced tomfoolery:  testmod runs methods of a local instance of
+    class doctest.Tester, then merges the results into (or creates)
+    global Tester instance doctest.master.  Methods of doctest.master
+    can be called directly too, if you want to do something unusual.
+    Passing report=0 to testmod is especially useful then, to delay
+    displaying a summary.  Invoke doctest.master.summarize(verbose)
+    when you're done fiddling.
+    """
+    if package and not module_relative:
+        raise ValueError("Package may only be specified for module-"
+                         "relative paths.")
+
+    # Relativize the path
+    text, filename = pdoctest._load_testfile(
+        filename, package, module_relative, encoding)
+
+    # If no name was given, then use the file's name.
+    if name is None:
+        name = os.path.basename(filename)
+
+    # Assemble the globals.
+    if globs is None:
+        globs = {}
+    else:
+        globs = globs.copy()
+    if extraglobs is not None:
+        globs.update(extraglobs)
+    if '__name__' not in globs:
+        globs['__name__'] = '__main__'
+
+    if raise_on_error:
+        runner = pdoctest.DebugRunner(verbose=verbose, optionflags=optionflags)
+    else:
+        runner = SymPyDocTestRunner(verbose=verbose, optionflags=optionflags)
+        runner._checker = SymPyOutputChecker()
+
+    # Read the file, convert it to a test, and run it.
+    test = parser.get_doctest(text, globs, name, filename, 0)
+    runner.run(test)
+
+    if report:
+        runner.summarize()
+
+    if pdoctest.master is None:
+        pdoctest.master = runner
+    else:
+        pdoctest.master.merge(runner)
+
+    return SymPyTestResults(runner.failures, runner.tries)
+
+
+class SymPyTests:
+
+    def __init__(self, reporter, kw="", post_mortem=False,
+                 seed=None, fast_threshold=None, slow_threshold=None):
+        self._post_mortem = post_mortem
+        self._kw = kw
+        self._count = 0
+        self._root_dir = get_sympy_dir()
+        self._reporter = reporter
+        self._reporter.root_dir(self._root_dir)
+        self._testfiles = []
+        self._seed = seed if seed is not None else random.random()
+
+        # Defaults in seconds, from human / UX design limits
+        # http://www.nngroup.com/articles/response-times-3-important-limits/
+        #
+        # These defaults are *NOT* set in stone as we are measuring different
+        # things, so others feel free to come up with a better yardstick :)
+        if fast_threshold:
+            self._fast_threshold = float(fast_threshold)
+        else:
+            self._fast_threshold = 8
+        if slow_threshold:
+            self._slow_threshold = float(slow_threshold)
+        else:
+            self._slow_threshold = 10
+
+    def test(self, sort=False, timeout=False, slow=False,
+            enhance_asserts=False, fail_on_timeout=False):
+        """
+        Runs the tests returning True if all tests pass, otherwise False.
+
+        If sort=False run tests in random order.
+        """
+        if sort:
+            self._testfiles.sort()
+        elif slow:
+            pass
+        else:
+            random.seed(self._seed)
+            random.shuffle(self._testfiles)
+        self._reporter.start(self._seed)
+        for f in self._testfiles:
+            try:
+                self.test_file(f, sort, timeout, slow,
+                    enhance_asserts, fail_on_timeout)
+            except KeyboardInterrupt:
+                print(" interrupted by user")
+                self._reporter.finish()
+                raise
+        return self._reporter.finish()
+
+    def _enhance_asserts(self, source):
+        from ast import (NodeTransformer, Compare, Name, Store, Load, Tuple,
+            Assign, BinOp, Str, Mod, Assert, parse, fix_missing_locations)
+
+        ops = {"Eq": '==', "NotEq": '!=', "Lt": '<', "LtE": '<=',
+                "Gt": '>', "GtE": '>=', "Is": 'is', "IsNot": 'is not',
+                "In": 'in', "NotIn": 'not in'}
+
+        class Transform(NodeTransformer):
+            def visit_Assert(self, stmt):
+                if isinstance(stmt.test, Compare):
+                    compare = stmt.test
+                    values = [compare.left] + compare.comparators
+                    names = [ "_%s" % i for i, _ in enumerate(values) ]
+                    names_store = [ Name(n, Store()) for n in names ]
+                    names_load = [ Name(n, Load()) for n in names ]
+                    target = Tuple(names_store, Store())
+                    value = Tuple(values, Load())
+                    assign = Assign([target], value)
+                    new_compare = Compare(names_load[0], compare.ops, names_load[1:])
+                    msg_format = "\n%s " + "\n%s ".join([ ops[op.__class__.__name__] for op in compare.ops ]) + "\n%s"
+                    msg = BinOp(Str(msg_format), Mod(), Tuple(names_load, Load()))
+                    test = Assert(new_compare, msg, lineno=stmt.lineno, col_offset=stmt.col_offset)
+                    return [assign, test]
+                else:
+                    return stmt
+
+        tree = parse(source)
+        new_tree = Transform().visit(tree)
+        return fix_missing_locations(new_tree)
+
+    def test_file(self, filename, sort=True, timeout=False, slow=False,
+            enhance_asserts=False, fail_on_timeout=False):
+        reporter = self._reporter
+        funcs = []
+        try:
+            gl = {'__file__': filename}
+            try:
+                open_file = lambda: open(filename, encoding="utf8")
+
+                with open_file() as f:
+                    source = f.read()
+                    if self._kw:
+                        for l in source.splitlines():
+                            if l.lstrip().startswith('def '):
+                                if any(l.lower().find(k.lower()) != -1 for k in self._kw):
+                                    break
+                        else:
+                            return
+
+                if enhance_asserts:
+                    try:
+                        source = self._enhance_asserts(source)
+                    except ImportError:
+                        pass
+
+                code = compile(source, filename, "exec", flags=0, dont_inherit=True)
+                exec(code, gl)
+            except (SystemExit, KeyboardInterrupt):
+                raise
+            except ImportError:
+                reporter.import_error(filename, sys.exc_info())
+                return
+            except Exception:
+                reporter.test_exception(sys.exc_info())
+
+            clear_cache()
+            self._count += 1
+            random.seed(self._seed)
+            disabled = gl.get("disabled", False)
+            if not disabled:
+                # we need to filter only those functions that begin with 'test_'
+                # We have to be careful about decorated functions. As long as
+                # the decorator uses functools.wraps, we can detect it.
+                funcs = []
+                for f in gl:
+                    if (f.startswith("test_") and (inspect.isfunction(gl[f])
+                        or inspect.ismethod(gl[f]))):
+                        func = gl[f]
+                        # Handle multiple decorators
+                        while hasattr(func, '__wrapped__'):
+                            func = func.__wrapped__
+
+                        if inspect.getsourcefile(func) == filename:
+                            funcs.append(gl[f])
+                if slow:
+                    funcs = [f for f in funcs if getattr(f, '_slow', False)]
+                # Sorting of XFAILed functions isn't fixed yet :-(
+                funcs.sort(key=lambda x: inspect.getsourcelines(x)[1])
+                i = 0
+                while i < len(funcs):
+                    if inspect.isgeneratorfunction(funcs[i]):
+                    # some tests can be generators, that return the actual
+                    # test functions. We unpack it below:
+                        f = funcs.pop(i)
+                        for fg in f():
+                            func = fg[0]
+                            args = fg[1:]
+                            fgw = lambda: func(*args)
+                            funcs.insert(i, fgw)
+                            i += 1
+                    else:
+                        i += 1
+                # drop functions that are not selected with the keyword expression:
+                funcs = [x for x in funcs if self.matches(x)]
+
+            if not funcs:
+                return
+        except Exception:
+            reporter.entering_filename(filename, len(funcs))
+            raise
+
+        reporter.entering_filename(filename, len(funcs))
+        if not sort:
+            random.shuffle(funcs)
+
+        for f in funcs:
+            start = time.time()
+            reporter.entering_test(f)
+            try:
+                if getattr(f, '_slow', False) and not slow:
+                    raise Skipped("Slow")
+                with raise_on_deprecated():
+                    if timeout:
+                        self._timeout(f, timeout, fail_on_timeout)
+                    else:
+                        random.seed(self._seed)
+                        f()
+            except KeyboardInterrupt:
+                if getattr(f, '_slow', False):
+                    reporter.test_skip("KeyboardInterrupt")
+                else:
+                    raise
+            except Exception:
+                if timeout:
+                    signal.alarm(0)  # Disable the alarm. It could not be handled before.
+                t, v, tr = sys.exc_info()
+                if t is AssertionError:
+                    reporter.test_fail((t, v, tr))
+                    if self._post_mortem:
+                        pdb.post_mortem(tr)
+                elif t.__name__ == "Skipped":
+                    reporter.test_skip(v)
+                elif t.__name__ == "XFail":
+                    reporter.test_xfail()
+                elif t.__name__ == "XPass":
+                    reporter.test_xpass(v)
+                else:
+                    reporter.test_exception((t, v, tr))
+                    if self._post_mortem:
+                        pdb.post_mortem(tr)
+            else:
+                reporter.test_pass()
+            taken = time.time() - start
+            if taken > self._slow_threshold:
+                filename = os.path.relpath(filename, reporter._root_dir)
+                reporter.slow_test_functions.append(
+                    (filename + "::" + f.__name__, taken))
+            if getattr(f, '_slow', False) and slow:
+                if taken < self._fast_threshold:
+                    filename = os.path.relpath(filename, reporter._root_dir)
+                    reporter.fast_test_functions.append(
+                        (filename + "::" + f.__name__, taken))
+        reporter.leaving_filename()
+
+    def _timeout(self, function, timeout, fail_on_timeout):
+        def callback(x, y):
+            signal.alarm(0)
+            if fail_on_timeout:
+                raise TimeOutError("Timed out after %d seconds" % timeout)
+            else:
+                raise Skipped("Timeout")
+        signal.signal(signal.SIGALRM, callback)
+        signal.alarm(timeout)  # Set an alarm with a given timeout
+        function()
+        signal.alarm(0)  # Disable the alarm
+
+    def matches(self, x):
+        """
+        Does the keyword expression self._kw match "x"? Returns True/False.
+
+        Always returns True if self._kw is "".
+        """
+        if not self._kw:
+            return True
+        for kw in self._kw:
+            if x.__name__.lower().find(kw.lower()) != -1:
+                return True
+        return False
+
+    def get_test_files(self, dir, pat='test_*.py'):
+        """
+        Returns the list of test_*.py (default) files at or below directory
+        ``dir`` relative to the SymPy home directory.
+        """
+        dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0])
+
+        g = []
+        for path, folders, files in os.walk(dir):
+            g.extend([os.path.join(path, f) for f in files if fnmatch(f, pat)])
+
+        return sorted([os.path.normcase(gi) for gi in g])
+
+
+class SymPyDocTests:
+
+    def __init__(self, reporter, normal):
+        self._count = 0
+        self._root_dir = get_sympy_dir()
+        self._reporter = reporter
+        self._reporter.root_dir(self._root_dir)
+        self._normal = normal
+
+        self._testfiles = []
+
+    def test(self):
+        """
+        Runs the tests and returns True if all tests pass, otherwise False.
+        """
+        self._reporter.start()
+        for f in self._testfiles:
+            try:
+                self.test_file(f)
+            except KeyboardInterrupt:
+                print(" interrupted by user")
+                self._reporter.finish()
+                raise
+        return self._reporter.finish()
+
+    def test_file(self, filename):
+        clear_cache()
+
+        from io import StringIO
+        import sympy.interactive.printing as interactive_printing
+        from sympy.printing.pretty.pretty import pprint_use_unicode
+        from sympy.printing.pretty import stringpict
+
+        rel_name = filename[len(self._root_dir) + 1:]
+        dirname, file = os.path.split(filename)
+        module = rel_name.replace(os.sep, '.')[:-3]
+
+        if rel_name.startswith("examples"):
+            # Examples files do not have __init__.py files,
+            # So we have to temporarily extend sys.path to import them
+            sys.path.insert(0, dirname)
+            module = file[:-3]  # remove ".py"
+        try:
+            module = pdoctest._normalize_module(module)
+            tests = SymPyDocTestFinder().find(module)
+        except (SystemExit, KeyboardInterrupt):
+            raise
+        except ImportError:
+            self._reporter.import_error(filename, sys.exc_info())
+            return
+        finally:
+            if rel_name.startswith("examples"):
+                del sys.path[0]
+
+        tests = [test for test in tests if len(test.examples) > 0]
+        # By default tests are sorted by alphabetical order by function name.
+        # We sort by line number so one can edit the file sequentially from
+        # bottom to top. However, if there are decorated functions, their line
+        # numbers will be too large and for now one must just search for these
+        # by text and function name.
+        tests.sort(key=lambda x: -x.lineno)
+
+        if not tests:
+            return
+        self._reporter.entering_filename(filename, len(tests))
+        for test in tests:
+            assert len(test.examples) != 0
+
+            if self._reporter._verbose:
+                self._reporter.write("\n{} ".format(test.name))
+
+            # check if there are external dependencies which need to be met
+            if '_doctest_depends_on' in test.globs:
+                try:
+                    self._check_dependencies(**test.globs['_doctest_depends_on'])
+                except DependencyError as e:
+                    self._reporter.test_skip(v=str(e))
+                    continue
+
+            runner = SymPyDocTestRunner(verbose=self._reporter._verbose==2,
+                    optionflags=pdoctest.ELLIPSIS |
+                    pdoctest.NORMALIZE_WHITESPACE |
+                    pdoctest.IGNORE_EXCEPTION_DETAIL)
+            runner._checker = SymPyOutputChecker()
+            old = sys.stdout
+            new = old if self._reporter._verbose==2 else StringIO()
+            sys.stdout = new
+            # If the testing is normal, the doctests get importing magic to
+            # provide the global namespace. If not normal (the default) then
+            # then must run on their own; all imports must be explicit within
+            # a function's docstring. Once imported that import will be
+            # available to the rest of the tests in a given function's
+            # docstring (unless clear_globs=True below).
+            if not self._normal:
+                test.globs = {}
+                # if this is uncommented then all the test would get is what
+                # comes by default with a "from sympy import *"
+                #exec('from sympy import *') in test.globs
+            old_displayhook = sys.displayhook
+            use_unicode_prev, wrap_line_prev = setup_pprint()
+
+            try:
+                f, t = runner.run(test,
+                                  out=new.write, clear_globs=False)
+            except KeyboardInterrupt:
+                raise
+            finally:
+                sys.stdout = old
+            if f > 0:
+                self._reporter.doctest_fail(test.name, new.getvalue())
+            else:
+                self._reporter.test_pass()
+                sys.displayhook = old_displayhook
+                interactive_printing.NO_GLOBAL = False
+                pprint_use_unicode(use_unicode_prev)
+                stringpict._GLOBAL_WRAP_LINE = wrap_line_prev
+
+        self._reporter.leaving_filename()
+
+    def get_test_files(self, dir, pat='*.py', init_only=True):
+        r"""
+        Returns the list of \*.py files (default) from which docstrings
+        will be tested which are at or below directory ``dir``. By default,
+        only those that have an __init__.py in their parent directory
+        and do not start with ``test_`` will be included.
+        """
+        def importable(x):
+            """
+            Checks if given pathname x is an importable module by checking for
+            __init__.py file.
+
+            Returns True/False.
+
+            Currently we only test if the __init__.py file exists in the
+            directory with the file "x" (in theory we should also test all the
+            parent dirs).
+            """
+            init_py = os.path.join(os.path.dirname(x), "__init__.py")
+            return os.path.exists(init_py)
+
+        dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0])
+
+        g = []
+        for path, folders, files in os.walk(dir):
+            g.extend([os.path.join(path, f) for f in files
+                      if not f.startswith('test_') and fnmatch(f, pat)])
+        if init_only:
+            # skip files that are not importable (i.e. missing __init__.py)
+            g = [x for x in g if importable(x)]
+
+        return [os.path.normcase(gi) for gi in g]
+
+    def _check_dependencies(self,
+                            executables=(),
+                            modules=(),
+                            disable_viewers=(),
+                            python_version=(3, 5),
+                            ground_types=None):
+        """
+        Checks if the dependencies for the test are installed.
+
+        Raises ``DependencyError`` it at least one dependency is not installed.
+        """
+
+        for executable in executables:
+            if not shutil.which(executable):
+                raise DependencyError("Could not find %s" % executable)
+
+        for module in modules:
+            if module == 'matplotlib':
+                matplotlib = import_module(
+                    'matplotlib',
+                    import_kwargs={'fromlist':
+                                      ['pyplot', 'cm', 'collections']},
+                    min_module_version='1.0.0', catch=(RuntimeError,))
+                if matplotlib is None:
+                    raise DependencyError("Could not import matplotlib")
+            else:
+                if not import_module(module):
+                    raise DependencyError("Could not import %s" % module)
+
+        if disable_viewers:
+            tempdir = tempfile.mkdtemp()
+            os.environ['PATH'] = '%s:%s' % (tempdir, os.environ['PATH'])
+
+            vw = ('#!/usr/bin/env python3\n'
+                  'import sys\n'
+                  'if len(sys.argv) <= 1:\n'
+                  '    exit("wrong number of args")\n')
+
+            for viewer in disable_viewers:
+                Path(os.path.join(tempdir, viewer)).write_text(vw)
+
+                # make the file executable
+                os.chmod(os.path.join(tempdir, viewer),
+                         stat.S_IREAD | stat.S_IWRITE | stat.S_IXUSR)
+
+        if python_version:
+            if sys.version_info < python_version:
+                raise DependencyError("Requires Python >= " + '.'.join(map(str, python_version)))
+
+        if ground_types is not None:
+            if GROUND_TYPES not in ground_types:
+                raise DependencyError("Requires ground_types in " + str(ground_types))
+
+        if 'pyglet' in modules:
+            # monkey-patch pyglet s.t. it does not open a window during
+            # doctesting
+            import pyglet
+            class DummyWindow:
+                def __init__(self, *args, **kwargs):
+                    self.has_exit = True
+                    self.width = 600
+                    self.height = 400
+
+                def set_vsync(self, x):
+                    pass
+
+                def switch_to(self):
+                    pass
+
+                def push_handlers(self, x):
+                    pass
+
+                def close(self):
+                    pass
+
+            pyglet.window.Window = DummyWindow
+
+
+class SymPyDocTestFinder(DocTestFinder):
+    """
+    A class used to extract the DocTests that are relevant to a given
+    object, from its docstring and the docstrings of its contained
+    objects.  Doctests can currently be extracted from the following
+    object types: modules, functions, classes, methods, staticmethods,
+    classmethods, and properties.
+
+    Modified from doctest's version to look harder for code that
+    appears comes from a different module. For example, the @vectorize
+    decorator makes it look like functions come from multidimensional.py
+    even though their code exists elsewhere.
+    """
+
+    def _find(self, tests, obj, name, module, source_lines, globs, seen):
+        """
+        Find tests for the given object and any contained objects, and
+        add them to ``tests``.
+        """
+        if self._verbose:
+            print('Finding tests in %s' % name)
+
+        # If we've already processed this object, then ignore it.
+        if id(obj) in seen:
+            return
+        seen[id(obj)] = 1
+
+        # Make sure we don't run doctests for classes outside of sympy, such
+        # as in numpy or scipy.
+        if inspect.isclass(obj):
+            if obj.__module__.split('.')[0] != 'sympy':
+                return
+
+        # Find a test for this object, and add it to the list of tests.
+        test = self._get_test(obj, name, module, globs, source_lines)
+        if test is not None:
+            tests.append(test)
+
+        if not self._recurse:
+            return
+
+        # Look for tests in a module's contained objects.
+        if inspect.ismodule(obj):
+            for rawname, val in obj.__dict__.items():
+                # Recurse to functions & classes.
+                if inspect.isfunction(val) or inspect.isclass(val):
+                    # Make sure we don't run doctests functions or classes
+                    # from different modules
+                    if val.__module__ != module.__name__:
+                        continue
+
+                    assert self._from_module(module, val), \
+                        "%s is not in module %s (rawname %s)" % (val, module, rawname)
+
+                    try:
+                        valname = '%s.%s' % (name, rawname)
+                        self._find(tests, val, valname, module,
+                                   source_lines, globs, seen)
+                    except KeyboardInterrupt:
+                        raise
+
+            # Look for tests in a module's __test__ dictionary.
+            for valname, val in getattr(obj, '__test__', {}).items():
+                if not isinstance(valname, str):
+                    raise ValueError("SymPyDocTestFinder.find: __test__ keys "
+                                     "must be strings: %r" %
+                                     (type(valname),))
+                if not (inspect.isfunction(val) or inspect.isclass(val) or
+                        inspect.ismethod(val) or inspect.ismodule(val) or
+                        isinstance(val, str)):
+                    raise ValueError("SymPyDocTestFinder.find: __test__ values "
+                                     "must be strings, functions, methods, "
+                                     "classes, or modules: %r" %
+                                     (type(val),))
+                valname = '%s.__test__.%s' % (name, valname)
+                self._find(tests, val, valname, module, source_lines,
+                           globs, seen)
+
+
+        # Look for tests in a class's contained objects.
+        if inspect.isclass(obj):
+            for valname, val in obj.__dict__.items():
+                # Special handling for staticmethod/classmethod.
+                if isinstance(val, staticmethod):
+                    val = getattr(obj, valname)
+                if isinstance(val, classmethod):
+                    val = getattr(obj, valname).__func__
+
+
+                # Recurse to methods, properties, and nested classes.
+                if ((inspect.isfunction(unwrap(val)) or
+                        inspect.isclass(val) or
+                        isinstance(val, property)) and
+                    self._from_module(module, val)):
+                    # Make sure we don't run doctests functions or classes
+                    # from different modules
+                    if isinstance(val, property):
+                        if hasattr(val.fget, '__module__'):
+                            if val.fget.__module__ != module.__name__:
+                                continue
+                    else:
+                        if val.__module__ != module.__name__:
+                            continue
+
+                    assert self._from_module(module, val), \
+                        "%s is not in module %s (valname %s)" % (
+                            val, module, valname)
+
+                    valname = '%s.%s' % (name, valname)
+                    self._find(tests, val, valname, module, source_lines,
+                               globs, seen)
+
+    def _get_test(self, obj, name, module, globs, source_lines):
+        """
+        Return a DocTest for the given object, if it defines a docstring;
+        otherwise, return None.
+        """
+
+        lineno = None
+
+        # Extract the object's docstring.  If it does not have one,
+        # then return None (no test for this object).
+        if isinstance(obj, str):
+            # obj is a string in the case for objects in the polys package.
+            # Note that source_lines is a binary string (compiled polys
+            # modules), which can't be handled by _find_lineno so determine
+            # the line number here.
+
+            docstring = obj
+
+            matches = re.findall(r"line \d+", name)
+            assert len(matches) == 1, \
+                "string '%s' does not contain lineno " % name
+
+            # NOTE: this is not the exact linenumber but its better than no
+            # lineno ;)
+            lineno = int(matches[0][5:])
+
+        else:
+            docstring = getattr(obj, '__doc__', '')
+            if docstring is None:
+                docstring = ''
+            if not isinstance(docstring, str):
+                docstring = str(docstring)
+
+        # Don't bother if the docstring is empty.
+        if self._exclude_empty and not docstring:
+            return None
+
+        # check that properties have a docstring because _find_lineno
+        # assumes it
+        if isinstance(obj, property):
+            if obj.fget.__doc__ is None:
+                return None
+
+        # Find the docstring's location in the file.
+        if lineno is None:
+            obj = unwrap(obj)
+            # handling of properties is not implemented in _find_lineno so do
+            # it here
+            if hasattr(obj, 'func_closure') and obj.func_closure is not None:
+                tobj = obj.func_closure[0].cell_contents
+            elif isinstance(obj, property):
+                tobj = obj.fget
+            else:
+                tobj = obj
+            lineno = self._find_lineno(tobj, source_lines)
+
+        if lineno is None:
+            return None
+
+        # Return a DocTest for this object.
+        if module is None:
+            filename = None
+        else:
+            filename = getattr(module, '__file__', module.__name__)
+            if filename[-4:] in (".pyc", ".pyo"):
+                filename = filename[:-1]
+
+        globs['_doctest_depends_on'] = getattr(obj, '_doctest_depends_on', {})
+
+        return self._parser.get_doctest(docstring, globs, name,
+                                        filename, lineno)
+
+
+class SymPyDocTestRunner(DocTestRunner):
+    """
+    A class used to run DocTest test cases, and accumulate statistics.
+    The ``run`` method is used to process a single DocTest case.  It
+    returns a tuple ``(f, t)``, where ``t`` is the number of test cases
+    tried, and ``f`` is the number of test cases that failed.
+
+    Modified from the doctest version to not reset the sys.displayhook (see
+    issue 5140).
+
+    See the docstring of the original DocTestRunner for more information.
+    """
+
+    def run(self, test, compileflags=None, out=None, clear_globs=True):
+        """
+        Run the examples in ``test``, and display the results using the
+        writer function ``out``.
+
+        The examples are run in the namespace ``test.globs``.  If
+        ``clear_globs`` is true (the default), then this namespace will
+        be cleared after the test runs, to help with garbage
+        collection.  If you would like to examine the namespace after
+        the test completes, then use ``clear_globs=False``.
+
+        ``compileflags`` gives the set of flags that should be used by
+        the Python compiler when running the examples.  If not
+        specified, then it will default to the set of future-import
+        flags that apply to ``globs``.
+
+        The output of each example is checked using
+        ``SymPyDocTestRunner.check_output``, and the results are
+        formatted by the ``SymPyDocTestRunner.report_*`` methods.
+        """
+        self.test = test
+
+        # Remove ``` from the end of example, which may appear in Markdown
+        # files
+        for example in test.examples:
+            example.want = example.want.replace('```\n', '')
+            example.exc_msg = example.exc_msg and example.exc_msg.replace('```\n', '')
+
+
+        if compileflags is None:
+            compileflags = pdoctest._extract_future_flags(test.globs)
+
+        save_stdout = sys.stdout
+        if out is None:
+            out = save_stdout.write
+        sys.stdout = self._fakeout
+
+        # Patch pdb.set_trace to restore sys.stdout during interactive
+        # debugging (so it's not still redirected to self._fakeout).
+        # Note that the interactive output will go to *our*
+        # save_stdout, even if that's not the real sys.stdout; this
+        # allows us to write test cases for the set_trace behavior.
+        save_set_trace = pdb.set_trace
+        self.debugger = pdoctest._OutputRedirectingPdb(save_stdout)
+        self.debugger.reset()
+        pdb.set_trace = self.debugger.set_trace
+
+        # Patch linecache.getlines, so we can see the example's source
+        # when we're inside the debugger.
+        self.save_linecache_getlines = pdoctest.linecache.getlines
+        linecache.getlines = self.__patched_linecache_getlines
+
+        # Fail for deprecation warnings
+        with raise_on_deprecated():
+            try:
+                return self.__run(test, compileflags, out)
+            finally:
+                sys.stdout = save_stdout
+                pdb.set_trace = save_set_trace
+                linecache.getlines = self.save_linecache_getlines
+                if clear_globs:
+                    test.globs.clear()
+
+
+# We have to override the name mangled methods.
+monkeypatched_methods = [
+    'patched_linecache_getlines',
+    'run',
+    'record_outcome'
+]
+for method in monkeypatched_methods:
+    oldname = '_DocTestRunner__' + method
+    newname = '_SymPyDocTestRunner__' + method
+    setattr(SymPyDocTestRunner, newname, getattr(DocTestRunner, oldname))
+
+
+class SymPyOutputChecker(pdoctest.OutputChecker):
+    """
+    Compared to the OutputChecker from the stdlib our OutputChecker class
+    supports numerical comparison of floats occurring in the output of the
+    doctest examples
+    """
+
+    def __init__(self):
+        # NOTE OutputChecker is an old-style class with no __init__ method,
+        # so we can't call the base class version of __init__ here
+
+        got_floats = r'(\d+\.\d*|\.\d+)'
+
+        # floats in the 'want' string may contain ellipses
+        want_floats = got_floats + r'(\.{3})?'
+
+        front_sep = r'\s|\+|\-|\*|,'
+        back_sep = front_sep + r'|j|e'
+
+        fbeg = r'^%s(?=%s|$)' % (got_floats, back_sep)
+        fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, got_floats, back_sep)
+        self.num_got_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend))
+
+        fbeg = r'^%s(?=%s|$)' % (want_floats, back_sep)
+        fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, want_floats, back_sep)
+        self.num_want_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend))
+
+    def check_output(self, want, got, optionflags):
+        """
+        Return True iff the actual output from an example (`got`)
+        matches the expected output (`want`).  These strings are
+        always considered to match if they are identical; but
+        depending on what option flags the test runner is using,
+        several non-exact match types are also possible.  See the
+        documentation for `TestRunner` for more information about
+        option flags.
+        """
+        # Handle the common case first, for efficiency:
+        # if they're string-identical, always return true.
+        if got == want:
+            return True
+
+        # TODO parse integers as well ?
+        # Parse floats and compare them. If some of the parsed floats contain
+        # ellipses, skip the comparison.
+        matches = self.num_got_rgx.finditer(got)
+        numbers_got = [match.group(1) for match in matches] # list of strs
+        matches = self.num_want_rgx.finditer(want)
+        numbers_want = [match.group(1) for match in matches] # list of strs
+        if len(numbers_got) != len(numbers_want):
+            return False
+
+        if len(numbers_got) > 0:
+            nw_  = []
+            for ng, nw in zip(numbers_got, numbers_want):
+                if '...' in nw:
+                    nw_.append(ng)
+                    continue
+                else:
+                    nw_.append(nw)
+
+                if abs(float(ng)-float(nw)) > 1e-5:
+                    return False
+
+            got = self.num_got_rgx.sub(r'%s', got)
+            got = got % tuple(nw_)
+
+        #  can be used as a special sequence to signify a
+        # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
+        if not (optionflags & pdoctest.DONT_ACCEPT_BLANKLINE):
+            # Replace  in want with a blank line.
+            want = re.sub(r'(?m)^%s\s*?$' % re.escape(pdoctest.BLANKLINE_MARKER),
+                          '', want)
+            # If a line in got contains only spaces, then remove the
+            # spaces.
+            got = re.sub(r'(?m)^\s*?$', '', got)
+            if got == want:
+                return True
+
+        # This flag causes doctest to ignore any differences in the
+        # contents of whitespace strings.  Note that this can be used
+        # in conjunction with the ELLIPSIS flag.
+        if optionflags & pdoctest.NORMALIZE_WHITESPACE:
+            got = ' '.join(got.split())
+            want = ' '.join(want.split())
+            if got == want:
+                return True
+
+        # The ELLIPSIS flag says to let the sequence "..." in `want`
+        # match any substring in `got`.
+        if optionflags & pdoctest.ELLIPSIS:
+            if pdoctest._ellipsis_match(want, got):
+                return True
+
+        # We didn't find any match; return false.
+        return False
+
+
+class Reporter:
+    """
+    Parent class for all reporters.
+    """
+    pass
+
+
+class PyTestReporter(Reporter):
+    """
+    Py.test like reporter. Should produce output identical to py.test.
+    """
+
+    def __init__(self, verbose=False, tb="short", colors=True,
+                 force_colors=False, split=None):
+        self._verbose = verbose
+        self._tb_style = tb
+        self._colors = colors
+        self._force_colors = force_colors
+        self._xfailed = 0
+        self._xpassed = []
+        self._failed = []
+        self._failed_doctest = []
+        self._passed = 0
+        self._skipped = 0
+        self._exceptions = []
+        self._terminal_width = None
+        self._default_width = 80
+        self._split = split
+        self._active_file = ''
+        self._active_f = None
+
+        # TODO: Should these be protected?
+        self.slow_test_functions = []
+        self.fast_test_functions = []
+
+        # this tracks the x-position of the cursor (useful for positioning
+        # things on the screen), without the need for any readline library:
+        self._write_pos = 0
+        self._line_wrap = False
+
+    def root_dir(self, dir):
+        self._root_dir = dir
+
+    @property
+    def terminal_width(self):
+        if self._terminal_width is not None:
+            return self._terminal_width
+
+        def findout_terminal_width():
+            if sys.platform == "win32":
+                # Windows support is based on:
+                #
+                #  http://code.activestate.com/recipes/
+                #  440694-determine-size-of-console-window-on-windows/
+
+                from ctypes import windll, create_string_buffer
+
+                h = windll.kernel32.GetStdHandle(-12)
+                csbi = create_string_buffer(22)
+                res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
+
+                if res:
+                    import struct
+                    (_, _, _, _, _, left, _, right, _, _, _) = \
+                        struct.unpack("hhhhHhhhhhh", csbi.raw)
+                    return right - left
+                else:
+                    return self._default_width
+
+            if hasattr(sys.stdout, 'isatty') and not sys.stdout.isatty():
+                return self._default_width  # leave PIPEs alone
+
+            try:
+                process = subprocess.Popen(['stty', '-a'],
+                    stdout=subprocess.PIPE,
+                    stderr=subprocess.PIPE)
+                stdout, stderr = process.communicate()
+                stdout = stdout.decode("utf-8")
+            except OSError:
+                pass
+            else:
+                # We support the following output formats from stty:
+                #
+                # 1) Linux   -> columns 80
+                # 2) OS X    -> 80 columns
+                # 3) Solaris -> columns = 80
+
+                re_linux = r"columns\s+(?P\d+);"
+                re_osx = r"(?P\d+)\s*columns;"
+                re_solaris = r"columns\s+=\s+(?P\d+);"
+
+                for regex in (re_linux, re_osx, re_solaris):
+                    match = re.search(regex, stdout)
+
+                    if match is not None:
+                        columns = match.group('columns')
+
+                        try:
+                            width = int(columns)
+                        except ValueError:
+                            pass
+                        if width != 0:
+                            return width
+
+            return self._default_width
+
+        width = findout_terminal_width()
+        self._terminal_width = width
+
+        return width
+
+    def write(self, text, color="", align="left", width=None,
+              force_colors=False):
+        """
+        Prints a text on the screen.
+
+        It uses sys.stdout.write(), so no readline library is necessary.
+
+        Parameters
+        ==========
+
+        color : choose from the colors below, "" means default color
+        align : "left"/"right", "left" is a normal print, "right" is aligned on
+                the right-hand side of the screen, filled with spaces if
+                necessary
+        width : the screen width
+
+        """
+        color_templates = (
+            ("Black", "0;30"),
+            ("Red", "0;31"),
+            ("Green", "0;32"),
+            ("Brown", "0;33"),
+            ("Blue", "0;34"),
+            ("Purple", "0;35"),
+            ("Cyan", "0;36"),
+            ("LightGray", "0;37"),
+            ("DarkGray", "1;30"),
+            ("LightRed", "1;31"),
+            ("LightGreen", "1;32"),
+            ("Yellow", "1;33"),
+            ("LightBlue", "1;34"),
+            ("LightPurple", "1;35"),
+            ("LightCyan", "1;36"),
+            ("White", "1;37"),
+        )
+
+        colors = {}
+
+        for name, value in color_templates:
+            colors[name] = value
+        c_normal = '\033[0m'
+        c_color = '\033[%sm'
+
+        if width is None:
+            width = self.terminal_width
+
+        if align == "right":
+            if self._write_pos + len(text) > width:
+                # we don't fit on the current line, create a new line
+                self.write("\n")
+            self.write(" "*(width - self._write_pos - len(text)))
+
+        if not self._force_colors and hasattr(sys.stdout, 'isatty') and not \
+                sys.stdout.isatty():
+            # the stdout is not a terminal, this for example happens if the
+            # output is piped to less, e.g. "bin/test | less". In this case,
+            # the terminal control sequences would be printed verbatim, so
+            # don't use any colors.
+            color = ""
+        elif sys.platform == "win32":
+            # Windows consoles don't support ANSI escape sequences
+            color = ""
+        elif not self._colors:
+            color = ""
+
+        if self._line_wrap:
+            if text[0] != "\n":
+                sys.stdout.write("\n")
+
+        # Avoid UnicodeEncodeError when printing out test failures
+        if IS_WINDOWS:
+            text = text.encode('raw_unicode_escape').decode('utf8', 'ignore')
+        elif not sys.stdout.encoding.lower().startswith('utf'):
+            text = text.encode(sys.stdout.encoding, 'backslashreplace'
+                              ).decode(sys.stdout.encoding)
+
+        if color == "":
+            sys.stdout.write(text)
+        else:
+            sys.stdout.write("%s%s%s" %
+                (c_color % colors[color], text, c_normal))
+        sys.stdout.flush()
+        l = text.rfind("\n")
+        if l == -1:
+            self._write_pos += len(text)
+        else:
+            self._write_pos = len(text) - l - 1
+        self._line_wrap = self._write_pos >= width
+        self._write_pos %= width
+
+    def write_center(self, text, delim="="):
+        width = self.terminal_width
+        if text != "":
+            text = " %s " % text
+        idx = (width - len(text)) // 2
+        t = delim*idx + text + delim*(width - idx - len(text))
+        self.write(t + "\n")
+
+    def write_exception(self, e, val, tb):
+        # remove the first item, as that is always runtests.py
+        tb = tb.tb_next
+        t = traceback.format_exception(e, val, tb)
+        self.write("".join(t))
+
+    def start(self, seed=None, msg="test process starts"):
+        self.write_center(msg)
+        executable = sys.executable
+        v = tuple(sys.version_info)
+        python_version = "%s.%s.%s-%s-%s" % v
+        implementation = platform.python_implementation()
+        if implementation == 'PyPy':
+            implementation += " %s.%s.%s-%s-%s" % sys.pypy_version_info
+        self.write("executable:         %s  (%s) [%s]\n" %
+            (executable, python_version, implementation))
+        from sympy.utilities.misc import ARCH
+        self.write("architecture:       %s\n" % ARCH)
+        from sympy.core.cache import USE_CACHE
+        self.write("cache:              %s\n" % USE_CACHE)
+        version = ''
+        if GROUND_TYPES =='gmpy':
+            import gmpy2 as gmpy
+            version = gmpy.version()
+        self.write("ground types:       %s %s\n" % (GROUND_TYPES, version))
+        numpy = import_module('numpy')
+        self.write("numpy:              %s\n" % (None if not numpy else numpy.__version__))
+        if seed is not None:
+            self.write("random seed:        %d\n" % seed)
+        from sympy.utilities.misc import HASH_RANDOMIZATION
+        self.write("hash randomization: ")
+        hash_seed = os.getenv("PYTHONHASHSEED") or '0'
+        if HASH_RANDOMIZATION and (hash_seed == "random" or int(hash_seed)):
+            self.write("on (PYTHONHASHSEED=%s)\n" % hash_seed)
+        else:
+            self.write("off\n")
+        if self._split:
+            self.write("split:              %s\n" % self._split)
+        self.write('\n')
+        self._t_start = clock()
+
+    def finish(self):
+        self._t_end = clock()
+        self.write("\n")
+        global text, linelen
+        text = "tests finished: %d passed, " % self._passed
+        linelen = len(text)
+
+        def add_text(mytext):
+            global text, linelen
+            """Break new text if too long."""
+            if linelen + len(mytext) > self.terminal_width:
+                text += '\n'
+                linelen = 0
+            text += mytext
+            linelen += len(mytext)
+
+        if len(self._failed) > 0:
+            add_text("%d failed, " % len(self._failed))
+        if len(self._failed_doctest) > 0:
+            add_text("%d failed, " % len(self._failed_doctest))
+        if self._skipped > 0:
+            add_text("%d skipped, " % self._skipped)
+        if self._xfailed > 0:
+            add_text("%d expected to fail, " % self._xfailed)
+        if len(self._xpassed) > 0:
+            add_text("%d expected to fail but passed, " % len(self._xpassed))
+        if len(self._exceptions) > 0:
+            add_text("%d exceptions, " % len(self._exceptions))
+        add_text("in %.2f seconds" % (self._t_end - self._t_start))
+
+        if self.slow_test_functions:
+            self.write_center('slowest tests', '_')
+            sorted_slow = sorted(self.slow_test_functions, key=lambda r: r[1])
+            for slow_func_name, taken in sorted_slow:
+                print('%s - Took %.3f seconds' % (slow_func_name, taken))
+
+        if self.fast_test_functions:
+            self.write_center('unexpectedly fast tests', '_')
+            sorted_fast = sorted(self.fast_test_functions,
+                                 key=lambda r: r[1])
+            for fast_func_name, taken in sorted_fast:
+                print('%s - Took %.3f seconds' % (fast_func_name, taken))
+
+        if len(self._xpassed) > 0:
+            self.write_center("xpassed tests", "_")
+            for e in self._xpassed:
+                self.write("%s: %s\n" % (e[0], e[1]))
+            self.write("\n")
+
+        if self._tb_style != "no" and len(self._exceptions) > 0:
+            for e in self._exceptions:
+                filename, f, (t, val, tb) = e
+                self.write_center("", "_")
+                if f is None:
+                    s = "%s" % filename
+                else:
+                    s = "%s:%s" % (filename, f.__name__)
+                self.write_center(s, "_")
+                self.write_exception(t, val, tb)
+            self.write("\n")
+
+        if self._tb_style != "no" and len(self._failed) > 0:
+            for e in self._failed:
+                filename, f, (t, val, tb) = e
+                self.write_center("", "_")
+                self.write_center("%s::%s" % (filename, f.__name__), "_")
+                self.write_exception(t, val, tb)
+            self.write("\n")
+
+        if self._tb_style != "no" and len(self._failed_doctest) > 0:
+            for e in self._failed_doctest:
+                filename, msg = e
+                self.write_center("", "_")
+                self.write_center("%s" % filename, "_")
+                self.write(msg)
+            self.write("\n")
+
+        self.write_center(text)
+        ok = len(self._failed) == 0 and len(self._exceptions) == 0 and \
+            len(self._failed_doctest) == 0
+        if not ok:
+            self.write("DO *NOT* COMMIT!\n")
+        return ok
+
+    def entering_filename(self, filename, n):
+        rel_name = filename[len(self._root_dir) + 1:]
+        self._active_file = rel_name
+        self._active_file_error = False
+        self.write(rel_name)
+        self.write("[%d] " % n)
+
+    def leaving_filename(self):
+        self.write(" ")
+        if self._active_file_error:
+            self.write("[FAIL]", "Red", align="right")
+        else:
+            self.write("[OK]", "Green", align="right")
+        self.write("\n")
+        if self._verbose:
+            self.write("\n")
+
+    def entering_test(self, f):
+        self._active_f = f
+        if self._verbose:
+            self.write("\n" + f.__name__ + " ")
+
+    def test_xfail(self):
+        self._xfailed += 1
+        self.write("f", "Green")
+
+    def test_xpass(self, v):
+        message = str(v)
+        self._xpassed.append((self._active_file, message))
+        self.write("X", "Green")
+
+    def test_fail(self, exc_info):
+        self._failed.append((self._active_file, self._active_f, exc_info))
+        self.write("F", "Red")
+        self._active_file_error = True
+
+    def doctest_fail(self, name, error_msg):
+        # the first line contains "******", remove it:
+        error_msg = "\n".join(error_msg.split("\n")[1:])
+        self._failed_doctest.append((name, error_msg))
+        self.write("F", "Red")
+        self._active_file_error = True
+
+    def test_pass(self, char="."):
+        self._passed += 1
+        if self._verbose:
+            self.write("ok", "Green")
+        else:
+            self.write(char, "Green")
+
+    def test_skip(self, v=None):
+        char = "s"
+        self._skipped += 1
+        if v is not None:
+            message = str(v)
+            if message == "KeyboardInterrupt":
+                char = "K"
+            elif message == "Timeout":
+                char = "T"
+            elif message == "Slow":
+                char = "w"
+        if self._verbose:
+            if v is not None:
+                self.write(message + ' ', "Blue")
+            else:
+                self.write(" - ", "Blue")
+        self.write(char, "Blue")
+
+    def test_exception(self, exc_info):
+        self._exceptions.append((self._active_file, self._active_f, exc_info))
+        if exc_info[0] is TimeOutError:
+            self.write("T", "Red")
+        else:
+            self.write("E", "Red")
+        self._active_file_error = True
+
+    def import_error(self, filename, exc_info):
+        self._exceptions.append((filename, None, exc_info))
+        rel_name = filename[len(self._root_dir) + 1:]
+        self.write(rel_name)
+        self.write("[?]   Failed to import", "Red")
+        self.write(" ")
+        self.write("[FAIL]", "Red", align="right")
+        self.write("\n")
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/runtests_pytest.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/runtests_pytest.py
new file mode 100644
index 0000000000000000000000000000000000000000..635f27864ca86571128e6c9a055199dfbde1ed63
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/runtests_pytest.py
@@ -0,0 +1,461 @@
+"""Backwards compatible functions for running tests from SymPy using pytest.
+
+SymPy historically had its own testing framework that aimed to:
+- be compatible with pytest;
+- operate similarly (or identically) to pytest;
+- not require any external dependencies;
+- have all the functionality in one file only;
+- have no magic, just import the test file and execute the test functions; and
+- be portable.
+
+To reduce the maintenance burden of developing an independent testing framework
+and to leverage the benefits of existing Python testing infrastructure, SymPy
+now uses pytest (and various of its plugins) to run the test suite.
+
+To maintain backwards compatibility with the legacy testing interface of SymPy,
+which implemented functions that allowed users to run the tests on their
+installed version of SymPy, the functions in this module are implemented to
+match the existing API while thinly wrapping pytest.
+
+These two key functions are `test` and `doctest`.
+
+"""
+
+import functools
+import importlib.util
+import os
+import pathlib
+import re
+from fnmatch import fnmatch
+from typing import List, Optional, Tuple
+
+try:
+    import pytest
+except ImportError:
+
+    class NoPytestError(Exception):
+        """Raise when an internal test helper function is called with pytest."""
+
+    class pytest:  # type: ignore
+        """Shadow to support pytest features when pytest can't be imported."""
+
+        @staticmethod
+        def main(*args, **kwargs):
+            msg = 'pytest must be installed to run tests via this function'
+            raise NoPytestError(msg)
+
+from sympy.testing.runtests import test as test_sympy
+
+
+TESTPATHS_DEFAULT = (
+    pathlib.Path('sympy'),
+    pathlib.Path('doc', 'src'),
+)
+BLACKLIST_DEFAULT = (
+    'sympy/integrals/rubi/rubi_tests/tests',
+)
+
+
+class PytestPluginManager:
+    """Module names for pytest plugins used by SymPy."""
+    PYTEST: str = 'pytest'
+    RANDOMLY: str = 'pytest_randomly'
+    SPLIT: str = 'pytest_split'
+    TIMEOUT: str = 'pytest_timeout'
+    XDIST: str = 'xdist'
+
+    @functools.cached_property
+    def has_pytest(self) -> bool:
+        return bool(importlib.util.find_spec(self.PYTEST))
+
+    @functools.cached_property
+    def has_randomly(self) -> bool:
+        return bool(importlib.util.find_spec(self.RANDOMLY))
+
+    @functools.cached_property
+    def has_split(self) -> bool:
+        return bool(importlib.util.find_spec(self.SPLIT))
+
+    @functools.cached_property
+    def has_timeout(self) -> bool:
+        return bool(importlib.util.find_spec(self.TIMEOUT))
+
+    @functools.cached_property
+    def has_xdist(self) -> bool:
+        return bool(importlib.util.find_spec(self.XDIST))
+
+
+split_pattern = re.compile(r'([1-9][0-9]*)/([1-9][0-9]*)')
+
+
+@functools.lru_cache
+def sympy_dir() -> pathlib.Path:
+    """Returns the root SymPy directory."""
+    return pathlib.Path(__file__).parents[2]
+
+
+def update_args_with_paths(
+    paths: List[str],
+    keywords: Optional[Tuple[str]],
+    args: List[str],
+) -> List[str]:
+    """Appends valid paths and flags to the args `list` passed to `pytest.main`.
+
+    The are three different types of "path" that a user may pass to the `paths`
+    positional arguments, all of which need to be handled slightly differently:
+
+    1. Nothing is passed
+        The paths to the `testpaths` defined in `pytest.ini` need to be appended
+        to the arguments list.
+    2. Full, valid paths are passed
+        These paths need to be validated but can then be directly appended to
+        the arguments list.
+    3. Partial paths are passed.
+        The `testpaths` defined in `pytest.ini` need to be recursed and any
+        matches be appended to the arguments list.
+
+    """
+
+    def find_paths_matching_partial(partial_paths):
+        partial_path_file_patterns = []
+        for partial_path in partial_paths:
+            if len(partial_path) >= 4:
+                has_test_prefix = partial_path[:4] == 'test'
+                has_py_suffix = partial_path[-3:] == '.py'
+            elif len(partial_path) >= 3:
+                has_test_prefix = False
+                has_py_suffix = partial_path[-3:] == '.py'
+            else:
+                has_test_prefix = False
+                has_py_suffix = False
+            if has_test_prefix and has_py_suffix:
+                partial_path_file_patterns.append(partial_path)
+            elif has_test_prefix:
+                partial_path_file_patterns.append(f'{partial_path}*.py')
+            elif has_py_suffix:
+                partial_path_file_patterns.append(f'test*{partial_path}')
+            else:
+                partial_path_file_patterns.append(f'test*{partial_path}*.py')
+        matches = []
+        for testpath in valid_testpaths_default:
+            for path, dirs, files in os.walk(testpath, topdown=True):
+                zipped = zip(partial_paths, partial_path_file_patterns)
+                for (partial_path, partial_path_file) in zipped:
+                    if fnmatch(path, f'*{partial_path}*'):
+                        matches.append(str(pathlib.Path(path)))
+                        dirs[:] = []
+                    else:
+                        for file in files:
+                            if fnmatch(file, partial_path_file):
+                                matches.append(str(pathlib.Path(path, file)))
+        return matches
+
+    def is_tests_file(filepath: str) -> bool:
+        path = pathlib.Path(filepath)
+        if not path.is_file():
+            return False
+        if not path.parts[-1].startswith('test_'):
+            return False
+        if not path.suffix == '.py':
+            return False
+        return True
+
+    def find_tests_matching_keywords(keywords, filepath):
+        matches = []
+        source = pathlib.Path(filepath).read_text(encoding='utf-8')
+        for line in source.splitlines():
+            if line.lstrip().startswith('def '):
+                for kw in keywords:
+                    if line.lower().find(kw.lower()) != -1:
+                        test_name = line.split(' ')[1].split('(')[0]
+                        full_test_path = filepath + '::' + test_name
+                        matches.append(full_test_path)
+        return matches
+
+    valid_testpaths_default = []
+    for testpath in TESTPATHS_DEFAULT:
+        absolute_testpath = pathlib.Path(sympy_dir(), testpath)
+        if absolute_testpath.exists():
+            valid_testpaths_default.append(str(absolute_testpath))
+
+    candidate_paths = []
+    if paths:
+        full_paths = []
+        partial_paths = []
+        for path in paths:
+            if pathlib.Path(path).exists():
+                full_paths.append(str(pathlib.Path(sympy_dir(), path)))
+            else:
+                partial_paths.append(path)
+        matched_paths = find_paths_matching_partial(partial_paths)
+        candidate_paths.extend(full_paths)
+        candidate_paths.extend(matched_paths)
+    else:
+        candidate_paths.extend(valid_testpaths_default)
+
+    if keywords is not None and keywords != ():
+        matches = []
+        for path in candidate_paths:
+            if is_tests_file(path):
+                test_matches = find_tests_matching_keywords(keywords, path)
+                matches.extend(test_matches)
+            else:
+                for root, dirnames, filenames in os.walk(path):
+                    for filename in filenames:
+                        absolute_filepath = str(pathlib.Path(root, filename))
+                        if is_tests_file(absolute_filepath):
+                            test_matches = find_tests_matching_keywords(
+                                keywords,
+                                absolute_filepath,
+                            )
+                            matches.extend(test_matches)
+        args.extend(matches)
+    else:
+        args.extend(candidate_paths)
+
+    return args
+
+
+def make_absolute_path(partial_path: str) -> str:
+    """Convert a partial path to an absolute path.
+
+    A path such a `sympy/core` might be needed. However, absolute paths should
+    be used in the arguments to pytest in all cases as it avoids errors that
+    arise from nonexistent paths.
+
+    This function assumes that partial_paths will be passed in such that they
+    begin with the explicit `sympy` directory, i.e. `sympy/...`.
+
+    """
+
+    def is_valid_partial_path(partial_path: str) -> bool:
+        """Assumption that partial paths are defined from the `sympy` root."""
+        return pathlib.Path(partial_path).parts[0] == 'sympy'
+
+    if not is_valid_partial_path(partial_path):
+        msg = (
+            f'Partial path {dir(partial_path)} is invalid, partial paths are '
+            f'expected to be defined with the `sympy` directory as the root.'
+        )
+        raise ValueError(msg)
+
+    absolute_path = str(pathlib.Path(sympy_dir(), partial_path))
+    return absolute_path
+
+
+def test(*paths, subprocess=True, rerun=0, **kwargs):
+    """Interface to run tests via pytest compatible with SymPy's test runner.
+
+    Explanation
+    ===========
+
+    Note that a `pytest.ExitCode`, which is an `enum`, is returned. This is
+    different to the legacy SymPy test runner which would return a `bool`. If
+    all tests successfully pass the `pytest.ExitCode.OK` with value `0` is
+    returned, whereas the legacy SymPy test runner would return `True`. In any
+    other scenario, a non-zero `enum` value is returned, whereas the legacy
+    SymPy test runner would return `False`. Users need to, therefore, be careful
+    if treating the pytest exit codes as booleans because
+    `bool(pytest.ExitCode.OK)` evaluates to `False`, the opposite of legacy
+    behaviour.
+
+    Examples
+    ========
+
+    >>> import sympy  # doctest: +SKIP
+
+    Run one file:
+
+    >>> sympy.test('sympy/core/tests/test_basic.py')  # doctest: +SKIP
+    >>> sympy.test('_basic')  # doctest: +SKIP
+
+    Run all tests in sympy/functions/ and some particular file:
+
+    >>> sympy.test("sympy/core/tests/test_basic.py",
+    ...            "sympy/functions")  # doctest: +SKIP
+
+    Run all tests in sympy/core and sympy/utilities:
+
+    >>> sympy.test("/core", "/util")  # doctest: +SKIP
+
+    Run specific test from a file:
+
+    >>> sympy.test("sympy/core/tests/test_basic.py",
+    ...            kw="test_equality")  # doctest: +SKIP
+
+    Run specific test from any file:
+
+    >>> sympy.test(kw="subs")  # doctest: +SKIP
+
+    Run the tests using the legacy SymPy runner:
+
+    >>> sympy.test(use_sympy_runner=True)  # doctest: +SKIP
+
+    Note that this option is slated for deprecation in the near future and is
+    only currently provided to ensure users have an alternative option while the
+    pytest-based runner receives real-world testing.
+
+    Parameters
+    ==========
+    paths : first n positional arguments of strings
+        Paths, both partial and absolute, describing which subset(s) of the test
+        suite are to be run.
+    subprocess : bool, default is True
+        Legacy option, is currently ignored.
+    rerun : int, default is 0
+        Legacy option, is ignored.
+    use_sympy_runner : bool or None, default is None
+        Temporary option to invoke the legacy SymPy test runner instead of
+        `pytest.main`. Will be removed in the near future.
+    verbose : bool, default is False
+        Sets the verbosity of the pytest output. Using `True` will add the
+        `--verbose` option to the pytest call.
+    tb : str, 'auto', 'long', 'short', 'line', 'native', or 'no'
+        Sets the traceback print mode of pytest using the `--tb` option.
+    kw : str
+        Only run tests which match the given substring expression. An expression
+        is a Python evaluatable expression where all names are substring-matched
+        against test names and their parent classes. Example: -k 'test_method or
+        test_other' matches all test functions and classes whose name contains
+        'test_method' or 'test_other', while -k 'not test_method' matches those
+        that don't contain 'test_method' in their names. -k 'not test_method and
+        not test_other' will eliminate the matches. Additionally keywords are
+        matched to classes and functions containing extra names in their
+        'extra_keyword_matches' set, as well as functions which have names
+        assigned directly to them. The matching is case-insensitive.
+    pdb : bool, default is False
+        Start the interactive Python debugger on errors or `KeyboardInterrupt`.
+    colors : bool, default is True
+        Color terminal output.
+    force_colors : bool, default is False
+        Legacy option, is ignored.
+    sort : bool, default is True
+        Run the tests in sorted order. pytest uses a sorted test order by
+        default. Requires pytest-randomly.
+    seed : int
+        Seed to use for random number generation. Requires pytest-randomly.
+    timeout : int, default is 0
+        Timeout in seconds before dumping the stacks. 0 means no timeout.
+        Requires pytest-timeout.
+    fail_on_timeout : bool, default is False
+        Legacy option, is currently ignored.
+    slow : bool, default is False
+        Run the subset of tests marked as `slow`.
+    enhance_asserts : bool, default is False
+        Legacy option, is currently ignored.
+    split : string in form `/` or None, default is None
+        Used to split the tests up. As an example, if `split='2/3' is used then
+        only the middle third of tests are run. Requires pytest-split.
+    time_balance : bool, default is True
+        Legacy option, is currently ignored.
+    blacklist : iterable of test paths as strings, default is BLACKLIST_DEFAULT
+        Blacklisted test paths are ignored using the `--ignore` option. Paths
+        may be partial or absolute. If partial then they are matched against
+        all paths in the pytest tests path.
+    parallel : bool, default is False
+        Parallelize the test running using pytest-xdist. If `True` then pytest
+        will automatically detect the number of CPU cores available and use them
+        all. Requires pytest-xdist.
+    store_durations : bool, False
+        Store test durations into the file `.test_durations`. The is used by
+        `pytest-split` to help determine more even splits when more than one
+        test group is being used. Requires pytest-split.
+
+    """
+    # NOTE: to be removed alongside SymPy test runner
+    if kwargs.get('use_sympy_runner', False):
+        kwargs.pop('parallel', False)
+        kwargs.pop('store_durations', False)
+        kwargs.pop('use_sympy_runner', True)
+        if kwargs.get('slow') is None:
+            kwargs['slow'] = False
+        return test_sympy(*paths, subprocess=True, rerun=0, **kwargs)
+
+    pytest_plugin_manager = PytestPluginManager()
+    if not pytest_plugin_manager.has_pytest:
+        pytest.main()
+
+    args = []
+
+    if kwargs.get('verbose', False):
+        args.append('--verbose')
+
+    if tb := kwargs.get('tb'):
+        args.extend(['--tb', tb])
+
+    if kwargs.get('pdb'):
+        args.append('--pdb')
+
+    if not kwargs.get('colors', True):
+        args.extend(['--color', 'no'])
+
+    if seed := kwargs.get('seed'):
+        if not pytest_plugin_manager.has_randomly:
+            msg = '`pytest-randomly` plugin required to control random seed.'
+            raise ModuleNotFoundError(msg)
+        args.extend(['--randomly-seed', str(seed)])
+
+    if kwargs.get('sort', True) and pytest_plugin_manager.has_randomly:
+        args.append('--randomly-dont-reorganize')
+    elif not kwargs.get('sort', True) and not pytest_plugin_manager.has_randomly:
+        msg = '`pytest-randomly` plugin required to randomize test order.'
+        raise ModuleNotFoundError(msg)
+
+    if timeout := kwargs.get('timeout', None):
+        if not pytest_plugin_manager.has_timeout:
+            msg = '`pytest-timeout` plugin required to apply timeout to tests.'
+            raise ModuleNotFoundError(msg)
+        args.extend(['--timeout', str(int(timeout))])
+
+    # Skip slow tests by default and always skip tooslow tests
+    if kwargs.get('slow', False):
+        args.extend(['-m', 'slow and not tooslow'])
+    else:
+        args.extend(['-m', 'not slow and not tooslow'])
+
+    if (split := kwargs.get('split')) is not None:
+        if not pytest_plugin_manager.has_split:
+            msg = '`pytest-split` plugin required to run tests as groups.'
+            raise ModuleNotFoundError(msg)
+        match = split_pattern.match(split)
+        if not match:
+            msg = ('split must be a string of the form a/b where a and b are '
+                   'positive nonzero ints')
+            raise ValueError(msg)
+        group, splits = map(str, match.groups())
+        args.extend(['--group', group, '--splits', splits])
+        if group > splits:
+            msg = (f'cannot have a group number {group} with only {splits} '
+                   'splits')
+            raise ValueError(msg)
+
+    if blacklist := kwargs.get('blacklist', BLACKLIST_DEFAULT):
+        for path in blacklist:
+            args.extend(['--ignore', make_absolute_path(path)])
+
+    if kwargs.get('parallel', False):
+        if not pytest_plugin_manager.has_xdist:
+            msg = '`pytest-xdist` plugin required to run tests in parallel.'
+            raise ModuleNotFoundError(msg)
+        args.extend(['-n', 'auto'])
+
+    if kwargs.get('store_durations', False):
+        if not pytest_plugin_manager.has_split:
+            msg = '`pytest-split` plugin required to store test durations.'
+            raise ModuleNotFoundError(msg)
+        args.append('--store-durations')
+
+    if (keywords := kwargs.get('kw')) is not None:
+        keywords = tuple(str(kw) for kw in keywords)
+    else:
+        keywords = ()
+
+    args = update_args_with_paths(paths, keywords, args)
+    exit_code = pytest.main(args)
+    return exit_code
+
+
+def doctest():
+    """Interface to run doctests via pytest compatible with SymPy's test runner.
+    """
+    raise NotImplementedError
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tests/diagnose_imports.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tests/diagnose_imports.py
new file mode 100644
index 0000000000000000000000000000000000000000..a31b66c66690c082800ae36eee37dad6927e0b37
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tests/diagnose_imports.py
@@ -0,0 +1,216 @@
+#!/usr/bin/env python
+
+"""
+Import diagnostics. Run bin/diagnose_imports.py --help for details.
+"""
+
+from __future__ import annotations
+
+if __name__ == "__main__":
+
+    import sys
+    import inspect
+    import builtins
+
+    import optparse
+
+    from os.path import abspath, dirname, join, normpath
+    this_file = abspath(__file__)
+    sympy_dir = join(dirname(this_file), '..', '..', '..')
+    sympy_dir = normpath(sympy_dir)
+    sys.path.insert(0, sympy_dir)
+
+    option_parser = optparse.OptionParser(
+        usage=
+            "Usage: %prog option [options]\n"
+            "\n"
+            "Import analysis for imports between SymPy modules.")
+    option_group = optparse.OptionGroup(
+        option_parser,
+        'Analysis options',
+        'Options that define what to do. Exactly one of these must be given.')
+    option_group.add_option(
+        '--problems',
+        help=
+            'Print all import problems, that is: '
+            'If an import pulls in a package instead of a module '
+            '(e.g. sympy.core instead of sympy.core.add); ' # see ##PACKAGE##
+            'if it imports a symbol that is already present; ' # see ##DUPLICATE##
+            'if it imports a symbol '
+            'from somewhere other than the defining module.', # see ##ORIGIN##
+        action='count')
+    option_group.add_option(
+        '--origins',
+        help=
+            'For each imported symbol in each module, '
+            'print the module that defined it. '
+            '(This is useful for import refactoring.)',
+        action='count')
+    option_parser.add_option_group(option_group)
+    option_group = optparse.OptionGroup(
+        option_parser,
+        'Sort options',
+        'These options define the sort order for output lines. '
+        'At most one of these options is allowed. '
+        'Unsorted output will reflect the order in which imports happened.')
+    option_group.add_option(
+        '--by-importer',
+        help='Sort output lines by name of importing module.',
+        action='count')
+    option_group.add_option(
+        '--by-origin',
+        help='Sort output lines by name of imported module.',
+        action='count')
+    option_parser.add_option_group(option_group)
+    (options, args) = option_parser.parse_args()
+    if args:
+        option_parser.error(
+            'Unexpected arguments %s (try %s --help)' % (args, sys.argv[0]))
+    if options.problems > 1:
+        option_parser.error('--problems must not be given more than once.')
+    if options.origins > 1:
+        option_parser.error('--origins must not be given more than once.')
+    if options.by_importer > 1:
+        option_parser.error('--by-importer must not be given more than once.')
+    if options.by_origin > 1:
+        option_parser.error('--by-origin must not be given more than once.')
+    options.problems = options.problems == 1
+    options.origins = options.origins == 1
+    options.by_importer = options.by_importer == 1
+    options.by_origin = options.by_origin == 1
+    if not options.problems and not options.origins:
+        option_parser.error(
+            'At least one of --problems and --origins is required')
+    if options.problems and options.origins:
+        option_parser.error(
+            'At most one of --problems and --origins is allowed')
+    if options.by_importer and options.by_origin:
+        option_parser.error(
+            'At most one of --by-importer and --by-origin is allowed')
+    options.by_process = not options.by_importer and not options.by_origin
+
+    builtin_import = builtins.__import__
+
+    class Definition:
+        """Information about a symbol's definition."""
+        def __init__(self, name, value, definer):
+            self.name = name
+            self.value = value
+            self.definer = definer
+        def __hash__(self):
+            return hash(self.name)
+        def __eq__(self, other):
+            return self.name == other.name and self.value == other.value
+        def __ne__(self, other):
+            return not (self == other)
+        def __repr__(self):
+            return 'Definition(%s, ..., %s)' % (
+                repr(self.name), repr(self.definer))
+
+    # Maps each function/variable to name of module to define it
+    symbol_definers: dict[Definition, str] = {}
+
+    def in_module(a, b):
+        """Is a the same module as or a submodule of b?"""
+        return a == b or a != None and b != None and a.startswith(b + '.')
+
+    def relevant(module):
+        """Is module relevant for import checking?
+
+        Only imports between relevant modules will be checked."""
+        return in_module(module, 'sympy')
+
+    sorted_messages = []
+
+    def msg(msg, *args):
+        if options.by_process:
+            print(msg % args)
+        else:
+            sorted_messages.append(msg % args)
+
+    def tracking_import(module, globals=globals(), locals=[], fromlist=None, level=-1):
+        """__import__ wrapper - does not change imports at all, but tracks them.
+
+        Default order is implemented by doing output directly.
+        All other orders are implemented by collecting output information into
+        a sorted list that will be emitted after all imports are processed.
+
+        Indirect imports can only occur after the requested symbol has been
+        imported directly (because the indirect import would not have a module
+        to pick the symbol up from).
+        So this code detects indirect imports by checking whether the symbol in
+        question was already imported.
+
+        Keeps the semantics of __import__ unchanged."""
+        caller_frame = inspect.getframeinfo(sys._getframe(1))
+        importer_filename = caller_frame.filename
+        importer_module = globals['__name__']
+        if importer_filename == caller_frame.filename:
+            importer_reference = '%s line %s' % (
+                importer_filename, str(caller_frame.lineno))
+        else:
+            importer_reference = importer_filename
+        result = builtin_import(module, globals, locals, fromlist, level)
+        importee_module = result.__name__
+        # We're only interested if importer and importee are in SymPy
+        if relevant(importer_module) and relevant(importee_module):
+            for symbol in result.__dict__.iterkeys():
+                definition = Definition(
+                    symbol, result.__dict__[symbol], importer_module)
+                if definition not in symbol_definers:
+                    symbol_definers[definition] = importee_module
+            if hasattr(result, '__path__'):
+                ##PACKAGE##
+                # The existence of __path__ is documented in the tutorial on modules.
+                # Python 3.3 documents this in http://docs.python.org/3.3/reference/import.html
+                if options.by_origin:
+                    msg('Error: %s (a package) is imported by %s',
+                        module, importer_reference)
+                else:
+                    msg('Error: %s contains package import %s',
+                        importer_reference, module)
+            if fromlist != None:
+                symbol_list = fromlist
+                if '*' in symbol_list:
+                    if (importer_filename.endswith(("__init__.py", "__init__.pyc", "__init__.pyo"))):
+                        # We do not check starred imports inside __init__
+                        # That's the normal "please copy over its imports to my namespace"
+                        symbol_list = []
+                    else:
+                        symbol_list = result.__dict__.iterkeys()
+                for symbol in symbol_list:
+                    if symbol not in result.__dict__:
+                        if options.by_origin:
+                            msg('Error: %s.%s is not defined (yet), but %s tries to import it',
+                                importee_module, symbol, importer_reference)
+                        else:
+                            msg('Error: %s tries to import %s.%s, which did not define it (yet)',
+                                importer_reference, importee_module, symbol)
+                    else:
+                        definition = Definition(
+                            symbol, result.__dict__[symbol], importer_module)
+                        symbol_definer = symbol_definers[definition]
+                        if symbol_definer == importee_module:
+                            ##DUPLICATE##
+                            if options.by_origin:
+                                msg('Error: %s.%s is imported again into %s',
+                                    importee_module, symbol, importer_reference)
+                            else:
+                                msg('Error: %s imports %s.%s again',
+                                      importer_reference, importee_module, symbol)
+                        else:
+                            ##ORIGIN##
+                            if options.by_origin:
+                                msg('Error: %s.%s is imported by %s, which should import %s.%s instead',
+                                      importee_module, symbol, importer_reference, symbol_definer, symbol)
+                            else:
+                                msg('Error: %s imports %s.%s but should import %s.%s instead',
+                                      importer_reference, importee_module, symbol, symbol_definer, symbol)
+        return result
+
+    builtins.__import__ = tracking_import
+    __import__('sympy')
+
+    sorted_messages.sort()
+    for message in sorted_messages:
+        print(message)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tests/test_code_quality.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tests/test_code_quality.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a9f363f0b9a802553f8643186b7d858d1ad0694
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tests/test_code_quality.py
@@ -0,0 +1,510 @@
+# coding=utf-8
+from os import walk, sep, pardir
+from os.path import split, join, abspath, exists, isfile
+from glob import glob
+import re
+import random
+import ast
+
+from sympy.testing.pytest import raises
+from sympy.testing.quality_unicode import _test_this_file_encoding
+
+# System path separator (usually slash or backslash) to be
+# used with excluded files, e.g.
+#     exclude = set([
+#                    "%(sep)smpmath%(sep)s" % sepd,
+#                   ])
+sepd = {"sep": sep}
+
+# path and sympy_path
+SYMPY_PATH = abspath(join(split(__file__)[0], pardir, pardir))  # go to sympy/
+assert exists(SYMPY_PATH)
+
+TOP_PATH = abspath(join(SYMPY_PATH, pardir))
+BIN_PATH = join(TOP_PATH, "bin")
+EXAMPLES_PATH = join(TOP_PATH, "examples")
+
+# Error messages
+message_space = "File contains trailing whitespace: %s, line %s."
+message_implicit = "File contains an implicit import: %s, line %s."
+message_tabs = "File contains tabs instead of spaces: %s, line %s."
+message_carriage = "File contains carriage returns at end of line: %s, line %s"
+message_str_raise = "File contains string exception: %s, line %s"
+message_gen_raise = "File contains generic exception: %s, line %s"
+message_old_raise = "File contains old-style raise statement: %s, line %s, \"%s\""
+message_eof = "File does not end with a newline: %s, line %s"
+message_multi_eof = "File ends with more than 1 newline: %s, line %s"
+message_test_suite_def = "Function should start with 'test_' or '_': %s, line %s"
+message_duplicate_test = "This is a duplicate test function: %s, line %s"
+message_self_assignments = "File contains assignments to self/cls: %s, line %s."
+message_func_is = "File contains '.func is': %s, line %s."
+message_bare_expr = "File contains bare expression: %s, line %s."
+
+implicit_test_re = re.compile(r'^\s*(>>> )?(\.\.\. )?from .* import .*\*')
+str_raise_re = re.compile(
+    r'^\s*(>>> )?(\.\.\. )?raise(\s+(\'|\")|\s*(\(\s*)+(\'|\"))')
+gen_raise_re = re.compile(
+    r'^\s*(>>> )?(\.\.\. )?raise(\s+Exception|\s*(\(\s*)+Exception)')
+old_raise_re = re.compile(r'^\s*(>>> )?(\.\.\. )?raise((\s*\(\s*)|\s+)\w+\s*,')
+test_suite_def_re = re.compile(r'^def\s+(?!(_|test))[^(]*\(\s*\)\s*:$')
+test_ok_def_re = re.compile(r'^def\s+test_.*:$')
+test_file_re = re.compile(r'.*[/\\]test_.*\.py$')
+func_is_re = re.compile(r'\.\s*func\s+is')
+
+
+def tab_in_leading(s):
+    """Returns True if there are tabs in the leading whitespace of a line,
+    including the whitespace of docstring code samples."""
+    n = len(s) - len(s.lstrip())
+    if not s[n:n + 3] in ['...', '>>>']:
+        check = s[:n]
+    else:
+        smore = s[n + 3:]
+        check = s[:n] + smore[:len(smore) - len(smore.lstrip())]
+    return not (check.expandtabs() == check)
+
+
+def find_self_assignments(s):
+    """Returns a list of "bad" assignments: if there are instances
+    of assigning to the first argument of the class method (except
+    for staticmethod's).
+    """
+    t = [n for n in ast.parse(s).body if isinstance(n, ast.ClassDef)]
+
+    bad = []
+    for c in t:
+        for n in c.body:
+            if not isinstance(n, ast.FunctionDef):
+                continue
+            if any(d.id == 'staticmethod'
+                   for d in n.decorator_list if isinstance(d, ast.Name)):
+                continue
+            if n.name == '__new__':
+                continue
+            if not n.args.args:
+                continue
+            first_arg = n.args.args[0].arg
+
+            for m in ast.walk(n):
+                if isinstance(m, ast.Assign):
+                    for a in m.targets:
+                        if isinstance(a, ast.Name) and a.id == first_arg:
+                            bad.append(m)
+                        elif (isinstance(a, ast.Tuple) and
+                              any(q.id == first_arg for q in a.elts
+                                  if isinstance(q, ast.Name))):
+                            bad.append(m)
+
+    return bad
+
+
+def check_directory_tree(base_path, file_check, exclusions=set(), pattern="*.py"):
+    """
+    Checks all files in the directory tree (with base_path as starting point)
+    with the file_check function provided, skipping files that contain
+    any of the strings in the set provided by exclusions.
+    """
+    if not base_path:
+        return
+    for root, dirs, files in walk(base_path):
+        check_files(glob(join(root, pattern)), file_check, exclusions)
+
+
+def check_files(files, file_check, exclusions=set(), pattern=None):
+    """
+    Checks all files with the file_check function provided, skipping files
+    that contain any of the strings in the set provided by exclusions.
+    """
+    if not files:
+        return
+    for fname in files:
+        if not exists(fname) or not isfile(fname):
+            continue
+        if any(ex in fname for ex in exclusions):
+            continue
+        if pattern is None or re.match(pattern, fname):
+            file_check(fname)
+
+
+class _Visit(ast.NodeVisitor):
+    """return the line number corresponding to the
+    line on which a bare expression appears if it is a binary op
+    or a comparison that is not in a with block.
+
+    EXAMPLES
+    ========
+
+    >>> import ast
+    >>> class _Visit(ast.NodeVisitor):
+    ...     def visit_Expr(self, node):
+    ...         if isinstance(node.value, (ast.BinOp, ast.Compare)):
+    ...             print(node.lineno)
+    ...     def visit_With(self, node):
+    ...         pass  # no checking there
+    ...
+    >>> code='''x = 1    # line 1
+    ... for i in range(3):
+    ...     x == 2       # <-- 3
+    ... if x == 2:
+    ...     x == 3       # <-- 5
+    ...     x + 1        # <-- 6
+    ...     x = 1
+    ...     if x == 1:
+    ...         print(1)
+    ... while x != 1:
+    ...     x == 1       # <-- 11
+    ... with raises(TypeError):
+    ...     c == 1
+    ...     raise TypeError
+    ... assert x == 1
+    ... '''
+    >>> _Visit().visit(ast.parse(code))
+    3
+    5
+    6
+    11
+    """
+    def visit_Expr(self, node):
+        if isinstance(node.value, (ast.BinOp, ast.Compare)):
+            assert None, message_bare_expr % ('', node.lineno)
+    def visit_With(self, node):
+        pass
+
+
+BareExpr = _Visit()
+
+
+def line_with_bare_expr(code):
+    """return None or else 0-based line number of code on which
+    a bare expression appeared.
+    """
+    tree = ast.parse(code)
+    try:
+        BareExpr.visit(tree)
+    except AssertionError as msg:
+        assert msg.args
+        msg = msg.args[0]
+        assert msg.startswith(message_bare_expr.split(':', 1)[0])
+        return int(msg.rsplit(' ', 1)[1].rstrip('.'))  # the line number
+
+
+def test_files():
+    """
+    This test tests all files in SymPy and checks that:
+      o no lines contains a trailing whitespace
+      o no lines end with \r\n
+      o no line uses tabs instead of spaces
+      o that the file ends with a single newline
+      o there are no general or string exceptions
+      o there are no old style raise statements
+      o name of arg-less test suite functions start with _ or test_
+      o no duplicate function names that start with test_
+      o no assignments to self variable in class methods
+      o no lines contain ".func is" except in the test suite
+      o there is no do-nothing expression like `a == b` or `x + 1`
+    """
+
+    def test(fname):
+        with open(fname, encoding="utf8") as test_file:
+            test_this_file(fname, test_file)
+        with open(fname, encoding='utf8') as test_file:
+            _test_this_file_encoding(fname, test_file)
+
+    def test_this_file(fname, test_file):
+        idx = None
+        code = test_file.read()
+        test_file.seek(0)  # restore reader to head
+        py = fname if sep not in fname else fname.rsplit(sep, 1)[-1]
+        if py.startswith('test_'):
+            idx = line_with_bare_expr(code)
+        if idx is not None:
+            assert False, message_bare_expr % (fname, idx + 1)
+
+        line = None  # to flag the case where there were no lines in file
+        tests = 0
+        test_set = set()
+        for idx, line in enumerate(test_file):
+            if test_file_re.match(fname):
+                if test_suite_def_re.match(line):
+                    assert False, message_test_suite_def % (fname, idx + 1)
+                if test_ok_def_re.match(line):
+                    tests += 1
+                    test_set.add(line[3:].split('(')[0].strip())
+                    if len(test_set) != tests:
+                        assert False, message_duplicate_test % (fname, idx + 1)
+            if line.endswith((" \n", "\t\n")):
+                assert False, message_space % (fname, idx + 1)
+            if line.endswith("\r\n"):
+                assert False, message_carriage % (fname, idx + 1)
+            if tab_in_leading(line):
+                assert False, message_tabs % (fname, idx + 1)
+            if str_raise_re.search(line):
+                assert False, message_str_raise % (fname, idx + 1)
+            if gen_raise_re.search(line):
+                assert False, message_gen_raise % (fname, idx + 1)
+            if (implicit_test_re.search(line) and
+                    not list(filter(lambda ex: ex in fname, import_exclude))):
+                assert False, message_implicit % (fname, idx + 1)
+            if func_is_re.search(line) and not test_file_re.search(fname):
+                assert False, message_func_is % (fname, idx + 1)
+
+            result = old_raise_re.search(line)
+
+            if result is not None:
+                assert False, message_old_raise % (
+                    fname, idx + 1, result.group(2))
+
+        if line is not None:
+            if line == '\n' and idx > 0:
+                assert False, message_multi_eof % (fname, idx + 1)
+            elif not line.endswith('\n'):
+                # eof newline check
+                assert False, message_eof % (fname, idx + 1)
+
+
+    # Files to test at top level
+    top_level_files = [join(TOP_PATH, file) for file in [
+        "isympy.py",
+        "build.py",
+        "setup.py",
+    ]]
+    # Files to exclude from all tests
+    exclude = {
+        "%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevparser.py" % sepd,
+        "%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevlexer.py" % sepd,
+        "%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevlistener.py" % sepd,
+        "%(sep)ssympy%(sep)sparsing%(sep)slatex%(sep)s_antlr%(sep)slatexparser.py" % sepd,
+        "%(sep)ssympy%(sep)sparsing%(sep)slatex%(sep)s_antlr%(sep)slatexlexer.py" % sepd,
+    }
+    # Files to exclude from the implicit import test
+    import_exclude = {
+        # glob imports are allowed in top-level __init__.py:
+        "%(sep)ssympy%(sep)s__init__.py" % sepd,
+        # these __init__.py should be fixed:
+        # XXX: not really, they use useful import pattern (DRY)
+        "%(sep)svector%(sep)s__init__.py" % sepd,
+        "%(sep)smechanics%(sep)s__init__.py" % sepd,
+        "%(sep)squantum%(sep)s__init__.py" % sepd,
+        "%(sep)spolys%(sep)s__init__.py" % sepd,
+        "%(sep)spolys%(sep)sdomains%(sep)s__init__.py" % sepd,
+        # interactive SymPy executes ``from sympy import *``:
+        "%(sep)sinteractive%(sep)ssession.py" % sepd,
+        # isympy.py executes ``from sympy import *``:
+        "%(sep)sisympy.py" % sepd,
+        # these two are import timing tests:
+        "%(sep)sbin%(sep)ssympy_time.py" % sepd,
+        "%(sep)sbin%(sep)ssympy_time_cache.py" % sepd,
+        # Taken from Python stdlib:
+        "%(sep)sparsing%(sep)ssympy_tokenize.py" % sepd,
+        # this one should be fixed:
+        "%(sep)splotting%(sep)spygletplot%(sep)s" % sepd,
+        # False positive in the docstring
+        "%(sep)sbin%(sep)stest_external_imports.py" % sepd,
+        "%(sep)sbin%(sep)stest_submodule_imports.py" % sepd,
+        # These are deprecated stubs that can be removed at some point:
+        "%(sep)sutilities%(sep)sruntests.py" % sepd,
+        "%(sep)sutilities%(sep)spytest.py" % sepd,
+        "%(sep)sutilities%(sep)srandtest.py" % sepd,
+        "%(sep)sutilities%(sep)stmpfiles.py" % sepd,
+        "%(sep)sutilities%(sep)squality_unicode.py" % sepd,
+    }
+    check_files(top_level_files, test)
+    check_directory_tree(BIN_PATH, test, {"~", ".pyc", ".sh"}, "*")
+    check_directory_tree(SYMPY_PATH, test, exclude)
+    check_directory_tree(EXAMPLES_PATH, test, exclude)
+
+
+def _with_space(c):
+    # return c with a random amount of leading space
+    return random.randint(0, 10)*' ' + c
+
+
+def test_raise_statement_regular_expression():
+    candidates_ok = [
+        "some text # raise Exception, 'text'",
+        "raise ValueError('text') # raise Exception, 'text'",
+        "raise ValueError('text')",
+        "raise ValueError",
+        "raise ValueError('text')",
+        "raise ValueError('text') #,",
+        # Talking about an exception in a docstring
+        ''''"""This function will raise ValueError, except when it doesn't"""''',
+        "raise (ValueError('text')",
+    ]
+    str_candidates_fail = [
+        "raise 'exception'",
+        "raise 'Exception'",
+        'raise "exception"',
+        'raise "Exception"',
+        "raise 'ValueError'",
+    ]
+    gen_candidates_fail = [
+        "raise Exception('text') # raise Exception, 'text'",
+        "raise Exception('text')",
+        "raise Exception",
+        "raise Exception('text')",
+        "raise Exception('text') #,",
+        "raise Exception, 'text'",
+        "raise Exception, 'text' # raise Exception('text')",
+        "raise Exception, 'text' # raise Exception, 'text'",
+        ">>> raise Exception, 'text'",
+        ">>> raise Exception, 'text' # raise Exception('text')",
+        ">>> raise Exception, 'text' # raise Exception, 'text'",
+    ]
+    old_candidates_fail = [
+        "raise Exception, 'text'",
+        "raise Exception, 'text' # raise Exception('text')",
+        "raise Exception, 'text' # raise Exception, 'text'",
+        ">>> raise Exception, 'text'",
+        ">>> raise Exception, 'text' # raise Exception('text')",
+        ">>> raise Exception, 'text' # raise Exception, 'text'",
+        "raise ValueError, 'text'",
+        "raise ValueError, 'text' # raise Exception('text')",
+        "raise ValueError, 'text' # raise Exception, 'text'",
+        ">>> raise ValueError, 'text'",
+        ">>> raise ValueError, 'text' # raise Exception('text')",
+        ">>> raise ValueError, 'text' # raise Exception, 'text'",
+        "raise(ValueError,",
+        "raise (ValueError,",
+        "raise( ValueError,",
+        "raise ( ValueError,",
+        "raise(ValueError ,",
+        "raise (ValueError ,",
+        "raise( ValueError ,",
+        "raise ( ValueError ,",
+    ]
+
+    for c in candidates_ok:
+        assert str_raise_re.search(_with_space(c)) is None, c
+        assert gen_raise_re.search(_with_space(c)) is None, c
+        assert old_raise_re.search(_with_space(c)) is None, c
+    for c in str_candidates_fail:
+        assert str_raise_re.search(_with_space(c)) is not None, c
+    for c in gen_candidates_fail:
+        assert gen_raise_re.search(_with_space(c)) is not None, c
+    for c in old_candidates_fail:
+        assert old_raise_re.search(_with_space(c)) is not None, c
+
+
+def test_implicit_imports_regular_expression():
+    candidates_ok = [
+        "from sympy import something",
+        ">>> from sympy import something",
+        "from sympy.somewhere import something",
+        ">>> from sympy.somewhere import something",
+        "import sympy",
+        ">>> import sympy",
+        "import sympy.something.something",
+        "... import sympy",
+        "... import sympy.something.something",
+        "... from sympy import something",
+        "... from sympy.somewhere import something",
+        ">> from sympy import *",  # To allow 'fake' docstrings
+        "# from sympy import *",
+        "some text # from sympy import *",
+    ]
+    candidates_fail = [
+        "from sympy import *",
+        ">>> from sympy import *",
+        "from sympy.somewhere import *",
+        ">>> from sympy.somewhere import *",
+        "... from sympy import *",
+        "... from sympy.somewhere import *",
+    ]
+    for c in candidates_ok:
+        assert implicit_test_re.search(_with_space(c)) is None, c
+    for c in candidates_fail:
+        assert implicit_test_re.search(_with_space(c)) is not None, c
+
+
+def test_test_suite_defs():
+    candidates_ok = [
+        "    def foo():\n",
+        "def foo(arg):\n",
+        "def _foo():\n",
+        "def test_foo():\n",
+    ]
+    candidates_fail = [
+        "def foo():\n",
+        "def foo() :\n",
+        "def foo( ):\n",
+        "def  foo():\n",
+    ]
+    for c in candidates_ok:
+        assert test_suite_def_re.search(c) is None, c
+    for c in candidates_fail:
+        assert test_suite_def_re.search(c) is not None, c
+
+
+def test_test_duplicate_defs():
+    candidates_ok = [
+        "def foo():\ndef foo():\n",
+        "def test():\ndef test_():\n",
+        "def test_():\ndef test__():\n",
+    ]
+    candidates_fail = [
+        "def test_():\ndef test_ ():\n",
+        "def test_1():\ndef  test_1():\n",
+    ]
+    ok = (None, 'check')
+    def check(file):
+        tests = 0
+        test_set = set()
+        for idx, line in enumerate(file.splitlines()):
+            if test_ok_def_re.match(line):
+                tests += 1
+                test_set.add(line[3:].split('(')[0].strip())
+                if len(test_set) != tests:
+                    return False, message_duplicate_test % ('check', idx + 1)
+        return None, 'check'
+    for c in candidates_ok:
+        assert check(c) == ok
+    for c in candidates_fail:
+        assert check(c) != ok
+
+
+def test_find_self_assignments():
+    candidates_ok = [
+        "class A(object):\n    def foo(self, arg): arg = self\n",
+        "class A(object):\n    def foo(self, arg): self.prop = arg\n",
+        "class A(object):\n    def foo(self, arg): obj, obj2 = arg, self\n",
+        "class A(object):\n    @classmethod\n    def bar(cls, arg): arg = cls\n",
+        "class A(object):\n    def foo(var, arg): arg = var\n",
+    ]
+    candidates_fail = [
+        "class A(object):\n    def foo(self, arg): self = arg\n",
+        "class A(object):\n    def foo(self, arg): obj, self = arg, arg\n",
+        "class A(object):\n    def foo(self, arg):\n        if arg: self = arg",
+        "class A(object):\n    @classmethod\n    def foo(cls, arg): cls = arg\n",
+        "class A(object):\n    def foo(var, arg): var = arg\n",
+    ]
+
+    for c in candidates_ok:
+        assert find_self_assignments(c) == []
+    for c in candidates_fail:
+        assert find_self_assignments(c) != []
+
+
+def test_test_unicode_encoding():
+    unicode_whitelist = ['foo']
+    unicode_strict_whitelist = ['bar']
+
+    fname = 'abc'
+    test_file = ['α']
+    raises(AssertionError, lambda: _test_this_file_encoding(
+        fname, test_file, unicode_whitelist, unicode_strict_whitelist))
+
+    fname = 'abc'
+    test_file = ['abc']
+    _test_this_file_encoding(
+        fname, test_file, unicode_whitelist, unicode_strict_whitelist)
+
+    fname = 'foo'
+    test_file = ['abc']
+    raises(AssertionError, lambda: _test_this_file_encoding(
+        fname, test_file, unicode_whitelist, unicode_strict_whitelist))
+
+    fname = 'bar'
+    test_file = ['abc']
+    _test_this_file_encoding(
+        fname, test_file, unicode_whitelist, unicode_strict_whitelist)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tests/test_deprecated.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tests/test_deprecated.py
new file mode 100644
index 0000000000000000000000000000000000000000..696933d96d6232ea869da1002ec9ebee5309724d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tests/test_deprecated.py
@@ -0,0 +1,5 @@
+from sympy.testing.pytest import warns_deprecated_sympy
+
+def test_deprecated_testing_randtest():
+    with warns_deprecated_sympy():
+        import sympy.testing.randtest  # noqa:F401
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tests/test_module_imports.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tests/test_module_imports.py
new file mode 100644
index 0000000000000000000000000000000000000000..d16dbaa98156c287c18b46ff07c0ede5d26e069a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tests/test_module_imports.py
@@ -0,0 +1,42 @@
+"""
+Checks that SymPy does not contain indirect imports.
+
+An indirect import is importing a symbol from a module that itself imported the
+symbol from elsewhere. Such a constellation makes it harder to diagnose
+inter-module dependencies and import order problems, and is therefore strongly
+discouraged.
+
+(Indirect imports from end-user code is fine and in fact a best practice.)
+
+Implementation note: Forcing Python into actually unloading already-imported
+submodules is a tricky and partly undocumented process. To avoid these issues,
+the actual diagnostic code is in bin/diagnose_imports, which is run as a
+separate, pristine Python process.
+"""
+
+import subprocess
+import sys
+from os.path import abspath, dirname, join, normpath
+import inspect
+
+from sympy.testing.pytest import XFAIL
+
+@XFAIL
+def test_module_imports_are_direct():
+    my_filename = abspath(inspect.getfile(inspect.currentframe()))
+    my_dirname = dirname(my_filename)
+    diagnose_imports_filename = join(my_dirname, 'diagnose_imports.py')
+    diagnose_imports_filename = normpath(diagnose_imports_filename)
+
+    process = subprocess.Popen(
+        [
+            sys.executable,
+            normpath(diagnose_imports_filename),
+            '--problems',
+            '--by-importer'
+        ],
+        stdout=subprocess.PIPE,
+        stderr=subprocess.STDOUT,
+        bufsize=-1)
+    output, _ = process.communicate()
+    assert output == '', "There are import problems:\n" + output.decode()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tests/test_pytest.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tests/test_pytest.py
new file mode 100644
index 0000000000000000000000000000000000000000..7080a4ed4602707a3efb4d9025e8e9cbe23a5ef8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tests/test_pytest.py
@@ -0,0 +1,211 @@
+import warnings
+
+from sympy.testing.pytest import (raises, warns, ignore_warnings,
+                                    warns_deprecated_sympy, Failed)
+from sympy.utilities.exceptions import sympy_deprecation_warning
+
+
+
+# Test callables
+
+
+def test_expected_exception_is_silent_callable():
+    def f():
+        raise ValueError()
+    raises(ValueError, f)
+
+
+# Under pytest raises will raise Failed rather than AssertionError
+def test_lack_of_exception_triggers_AssertionError_callable():
+    try:
+        raises(Exception, lambda: 1 + 1)
+        assert False
+    except Failed as e:
+        assert "DID NOT RAISE" in str(e)
+
+
+def test_unexpected_exception_is_passed_through_callable():
+    def f():
+        raise ValueError("some error message")
+    try:
+        raises(TypeError, f)
+        assert False
+    except ValueError as e:
+        assert str(e) == "some error message"
+
+# Test with statement
+
+def test_expected_exception_is_silent_with():
+    with raises(ValueError):
+        raise ValueError()
+
+
+def test_lack_of_exception_triggers_AssertionError_with():
+    try:
+        with raises(Exception):
+            1 + 1
+        assert False
+    except Failed as e:
+        assert "DID NOT RAISE" in str(e)
+
+
+def test_unexpected_exception_is_passed_through_with():
+    try:
+        with raises(TypeError):
+            raise ValueError("some error message")
+        assert False
+    except ValueError as e:
+        assert str(e) == "some error message"
+
+# Now we can use raises() instead of try/catch
+# to test that a specific exception class is raised
+
+
+def test_second_argument_should_be_callable_or_string():
+    raises(TypeError, lambda: raises("irrelevant", 42))
+
+
+def test_warns_catches_warning():
+    with warnings.catch_warnings(record=True) as w:
+        with warns(UserWarning):
+            warnings.warn('this is the warning message')
+        assert len(w) == 0
+
+
+def test_warns_raises_without_warning():
+    with raises(Failed):
+        with warns(UserWarning):
+            pass
+
+
+def test_warns_hides_other_warnings():
+    with raises(RuntimeWarning):
+        with warns(UserWarning):
+            warnings.warn('this is the warning message', UserWarning)
+            warnings.warn('this is the other message', RuntimeWarning)
+
+
+def test_warns_continues_after_warning():
+    with warnings.catch_warnings(record=True) as w:
+        finished = False
+        with warns(UserWarning):
+            warnings.warn('this is the warning message')
+            finished = True
+        assert finished
+        assert len(w) == 0
+
+
+def test_warns_many_warnings():
+    with warns(UserWarning):
+        warnings.warn('this is the warning message', UserWarning)
+        warnings.warn('this is the other warning message', UserWarning)
+
+
+def test_warns_match_matching():
+    with warnings.catch_warnings(record=True) as w:
+        with warns(UserWarning, match='this is the warning message'):
+            warnings.warn('this is the warning message', UserWarning)
+        assert len(w) == 0
+
+
+def test_warns_match_non_matching():
+    with warnings.catch_warnings(record=True) as w:
+        with raises(Failed):
+            with warns(UserWarning, match='this is the warning message'):
+                warnings.warn('this is not the expected warning message', UserWarning)
+        assert len(w) == 0
+
+def _warn_sympy_deprecation(stacklevel=3):
+    sympy_deprecation_warning(
+        "feature",
+        active_deprecations_target="active-deprecations",
+        deprecated_since_version="0.0.0",
+        stacklevel=stacklevel,
+    )
+
+def test_warns_deprecated_sympy_catches_warning():
+    with warnings.catch_warnings(record=True) as w:
+        with warns_deprecated_sympy():
+            _warn_sympy_deprecation()
+        assert len(w) == 0
+
+
+def test_warns_deprecated_sympy_raises_without_warning():
+    with raises(Failed):
+        with warns_deprecated_sympy():
+            pass
+
+def test_warns_deprecated_sympy_wrong_stacklevel():
+    with raises(Failed):
+        with warns_deprecated_sympy():
+            _warn_sympy_deprecation(stacklevel=1)
+
+def test_warns_deprecated_sympy_doesnt_hide_other_warnings():
+    # Unlike pytest's deprecated_call, we should not hide other warnings.
+    with raises(RuntimeWarning):
+        with warns_deprecated_sympy():
+            _warn_sympy_deprecation()
+            warnings.warn('this is the other message', RuntimeWarning)
+
+
+def test_warns_deprecated_sympy_continues_after_warning():
+    with warnings.catch_warnings(record=True) as w:
+        finished = False
+        with warns_deprecated_sympy():
+            _warn_sympy_deprecation()
+            finished = True
+        assert finished
+        assert len(w) == 0
+
+def test_ignore_ignores_warning():
+    with warnings.catch_warnings(record=True) as w:
+        with ignore_warnings(UserWarning):
+            warnings.warn('this is the warning message')
+        assert len(w) == 0
+
+
+def test_ignore_does_not_raise_without_warning():
+    with warnings.catch_warnings(record=True) as w:
+        with ignore_warnings(UserWarning):
+            pass
+        assert len(w) == 0
+
+
+def test_ignore_allows_other_warnings():
+    with warnings.catch_warnings(record=True) as w:
+        # This is needed when pytest is run as -Werror
+        # the setting is reverted at the end of the catch_Warnings block.
+        warnings.simplefilter("always")
+        with ignore_warnings(UserWarning):
+            warnings.warn('this is the warning message', UserWarning)
+            warnings.warn('this is the other message', RuntimeWarning)
+        assert len(w) == 1
+        assert isinstance(w[0].message, RuntimeWarning)
+        assert str(w[0].message) == 'this is the other message'
+
+
+def test_ignore_continues_after_warning():
+    with warnings.catch_warnings(record=True) as w:
+        finished = False
+        with ignore_warnings(UserWarning):
+            warnings.warn('this is the warning message')
+            finished = True
+        assert finished
+        assert len(w) == 0
+
+
+def test_ignore_many_warnings():
+    with warnings.catch_warnings(record=True) as w:
+        # This is needed when pytest is run as -Werror
+        # the setting is reverted at the end of the catch_Warnings block.
+        warnings.simplefilter("always")
+        with ignore_warnings(UserWarning):
+            warnings.warn('this is the warning message', UserWarning)
+            warnings.warn('this is the other message', RuntimeWarning)
+            warnings.warn('this is the warning message', UserWarning)
+            warnings.warn('this is the other message', RuntimeWarning)
+            warnings.warn('this is the other message', RuntimeWarning)
+        assert len(w) == 3
+        for wi in w:
+            assert isinstance(wi.message, RuntimeWarning)
+            assert str(wi.message) == 'this is the other message'
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tests/test_runtests_pytest.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tests/test_runtests_pytest.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd56d831f3618c9dbb8a1dffe63d95a0befc6adf
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tests/test_runtests_pytest.py
@@ -0,0 +1,171 @@
+import pathlib
+from typing import List
+
+import pytest
+
+from sympy.testing.runtests_pytest import (
+    make_absolute_path,
+    sympy_dir,
+    update_args_with_paths,
+)
+
+
+class TestMakeAbsolutePath:
+
+    @staticmethod
+    @pytest.mark.parametrize(
+        'partial_path', ['sympy', 'sympy/core', 'sympy/nonexistant_directory'],
+    )
+    def test_valid_partial_path(partial_path: str):
+        """Paths that start with `sympy` are valid."""
+        _ = make_absolute_path(partial_path)
+
+    @staticmethod
+    @pytest.mark.parametrize(
+        'partial_path', ['not_sympy', 'also/not/sympy'],
+    )
+    def test_invalid_partial_path_raises_value_error(partial_path: str):
+        """A `ValueError` is raises on paths that don't start with `sympy`."""
+        with pytest.raises(ValueError):
+            _ = make_absolute_path(partial_path)
+
+
+class TestUpdateArgsWithPaths:
+
+    @staticmethod
+    def test_no_paths():
+        """If no paths are passed, only `sympy` and `doc/src` are appended.
+
+        `sympy` and `doc/src` are the `testpaths` stated in `pytest.ini`. They
+        need to be manually added as if any path-related arguments are passed
+        to `pytest.main` then the settings in `pytest.ini` may be ignored.
+
+        """
+        paths = []
+        args = update_args_with_paths(paths=paths, keywords=None, args=[])
+        expected = [
+            str(pathlib.Path(sympy_dir(), 'sympy')),
+            str(pathlib.Path(sympy_dir(), 'doc/src')),
+        ]
+        assert args == expected
+
+    @staticmethod
+    @pytest.mark.parametrize(
+        'path',
+        ['sympy/core/tests/test_basic.py', '_basic']
+    )
+    def test_one_file(path: str):
+        """Single files/paths, full or partial, are matched correctly."""
+        args = update_args_with_paths(paths=[path], keywords=None, args=[])
+        expected = [
+            str(pathlib.Path(sympy_dir(), 'sympy/core/tests/test_basic.py')),
+        ]
+        assert args == expected
+
+    @staticmethod
+    def test_partial_path_from_root():
+        """Partial paths from the root directly are matched correctly."""
+        args = update_args_with_paths(paths=['sympy/functions'], keywords=None, args=[])
+        expected = [str(pathlib.Path(sympy_dir(), 'sympy/functions'))]
+        assert args == expected
+
+    @staticmethod
+    def test_multiple_paths_from_root():
+        """Multiple paths, partial or full, are matched correctly."""
+        paths = ['sympy/core/tests/test_basic.py', 'sympy/functions']
+        args = update_args_with_paths(paths=paths, keywords=None, args=[])
+        expected = [
+            str(pathlib.Path(sympy_dir(), 'sympy/core/tests/test_basic.py')),
+            str(pathlib.Path(sympy_dir(), 'sympy/functions')),
+        ]
+        assert args == expected
+
+    @staticmethod
+    @pytest.mark.parametrize(
+        'paths, expected_paths',
+        [
+            (
+                ['/core', '/util'],
+                [
+                    'doc/src/modules/utilities',
+                    'doc/src/reference/public/utilities',
+                    'sympy/core',
+                    'sympy/logic/utilities',
+                    'sympy/utilities',
+                ]
+            ),
+        ]
+    )
+    def test_multiple_paths_from_non_root(paths: List[str], expected_paths: List[str]):
+        """Multiple partial paths are matched correctly."""
+        args = update_args_with_paths(paths=paths, keywords=None, args=[])
+        assert len(args) == len(expected_paths)
+        for arg, expected in zip(sorted(args), expected_paths):
+            assert expected in arg
+
+    @staticmethod
+    @pytest.mark.parametrize(
+        'paths',
+        [
+
+            [],
+            ['sympy/physics'],
+            ['sympy/physics/mechanics'],
+            ['sympy/physics/mechanics/tests'],
+            ['sympy/physics/mechanics/tests/test_kane3.py'],
+        ]
+    )
+    def test_string_as_keyword(paths: List[str]):
+        """String keywords are matched correctly."""
+        keywords = ('bicycle', )
+        args = update_args_with_paths(paths=paths, keywords=keywords, args=[])
+        expected_args = ['sympy/physics/mechanics/tests/test_kane3.py::test_bicycle']
+        assert len(args) == len(expected_args)
+        for arg, expected in zip(sorted(args), expected_args):
+            assert expected in arg
+
+    @staticmethod
+    @pytest.mark.parametrize(
+        'paths',
+        [
+
+            [],
+            ['sympy/core'],
+            ['sympy/core/tests'],
+            ['sympy/core/tests/test_sympify.py'],
+        ]
+    )
+    def test_integer_as_keyword(paths: List[str]):
+        """Integer keywords are matched correctly."""
+        keywords = ('3538', )
+        args = update_args_with_paths(paths=paths, keywords=keywords, args=[])
+        expected_args = ['sympy/core/tests/test_sympify.py::test_issue_3538']
+        assert len(args) == len(expected_args)
+        for arg, expected in zip(sorted(args), expected_args):
+            assert expected in arg
+
+    @staticmethod
+    def test_multiple_keywords():
+        """Multiple keywords are matched correctly."""
+        keywords = ('bicycle', '3538')
+        args = update_args_with_paths(paths=[], keywords=keywords, args=[])
+        expected_args = [
+            'sympy/core/tests/test_sympify.py::test_issue_3538',
+            'sympy/physics/mechanics/tests/test_kane3.py::test_bicycle',
+        ]
+        assert len(args) == len(expected_args)
+        for arg, expected in zip(sorted(args), expected_args):
+            assert expected in arg
+
+    @staticmethod
+    def test_keyword_match_in_multiple_files():
+        """Keywords are matched across multiple files."""
+        keywords = ('1130', )
+        args = update_args_with_paths(paths=[], keywords=keywords, args=[])
+        expected_args = [
+            'sympy/integrals/tests/test_heurisch.py::test_heurisch_symbolic_coeffs_1130',
+            'sympy/utilities/tests/test_lambdify.py::test_python_div_zero_issue_11306',
+        ]
+        assert len(args) == len(expected_args)
+        for arg, expected in zip(sorted(args), expected_args):
+            assert expected in arg
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tmpfiles.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tmpfiles.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d5c69cb58aa11f77679855f3df21f03a10d3b2b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/testing/tmpfiles.py
@@ -0,0 +1,46 @@
+"""
+This module adds context manager for temporary files generated by the tests.
+"""
+
+import shutil
+import os
+
+
+class TmpFileManager:
+    """
+    A class to track record of every temporary files created by the tests.
+    """
+    tmp_files = set('')
+    tmp_folders = set('')
+
+    @classmethod
+    def tmp_file(cls, name=''):
+        cls.tmp_files.add(name)
+        return name
+
+    @classmethod
+    def tmp_folder(cls, name=''):
+        cls.tmp_folders.add(name)
+        return name
+
+    @classmethod
+    def cleanup(cls):
+        while cls.tmp_files:
+            file = cls.tmp_files.pop()
+            if os.path.isfile(file):
+                os.remove(file)
+        while cls.tmp_folders:
+            folder = cls.tmp_folders.pop()
+            shutil.rmtree(folder)
+
+def cleanup_tmp_files(test_func):
+    """
+    A decorator to help test codes remove temporary files after the tests.
+    """
+    def wrapper_function():
+        try:
+            test_func()
+        finally:
+            TmpFileManager.cleanup()
+
+    return wrapper_function
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c166f9163785f4aa5744324eb817bef79b33525
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/__init__.py
@@ -0,0 +1,15 @@
+""" Unification in SymPy
+
+See sympy.unify.core docstring for algorithmic details
+
+See http://matthewrocklin.com/blog/work/2012/11/01/Unification/ for discussion
+"""
+
+from .usympy import unify, rebuild
+from .rewrite import rewriterule
+
+__all__ = [
+    'unify', 'rebuild',
+
+    'rewriterule',
+]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/core.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/core.py
new file mode 100644
index 0000000000000000000000000000000000000000..5359d0bbd376e9fa9efacff1d90c0bf51414cebf
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/core.py
@@ -0,0 +1,234 @@
+""" Generic Unification algorithm for expression trees with lists of children
+
+This implementation is a direct translation of
+
+Artificial Intelligence: A Modern Approach by Stuart Russel and Peter Norvig
+Second edition, section 9.2, page 276
+
+It is modified in the following ways:
+
+1.  We allow associative and commutative Compound expressions. This results in
+    combinatorial blowup.
+2.  We explore the tree lazily.
+3.  We provide generic interfaces to symbolic algebra libraries in Python.
+
+A more traditional version can be found here
+http://aima.cs.berkeley.edu/python/logic.html
+"""
+
+from sympy.utilities.iterables import kbins
+
+class Compound:
+    """ A little class to represent an interior node in the tree
+
+    This is analogous to SymPy.Basic for non-Atoms
+    """
+    def __init__(self, op, args):
+        self.op = op
+        self.args = args
+
+    def __eq__(self, other):
+        return (type(self) is type(other) and self.op == other.op and
+                self.args == other.args)
+
+    def __hash__(self):
+        return hash((type(self), self.op, self.args))
+
+    def __str__(self):
+        return "%s[%s]" % (str(self.op), ', '.join(map(str, self.args)))
+
+class Variable:
+    """ A Wild token """
+    def __init__(self, arg):
+        self.arg = arg
+
+    def __eq__(self, other):
+        return type(self) is type(other) and self.arg == other.arg
+
+    def __hash__(self):
+        return hash((type(self), self.arg))
+
+    def __str__(self):
+        return "Variable(%s)" % str(self.arg)
+
+class CondVariable:
+    """ A wild token that matches conditionally.
+
+    arg   - a wild token.
+    valid - an additional constraining function on a match.
+    """
+    def __init__(self, arg, valid):
+        self.arg = arg
+        self.valid = valid
+
+    def __eq__(self, other):
+        return (type(self) is type(other) and
+                self.arg == other.arg and
+                self.valid == other.valid)
+
+    def __hash__(self):
+        return hash((type(self), self.arg, self.valid))
+
+    def __str__(self):
+        return "CondVariable(%s)" % str(self.arg)
+
+def unify(x, y, s=None, **fns):
+    """ Unify two expressions.
+
+    Parameters
+    ==========
+
+        x, y - expression trees containing leaves, Compounds and Variables.
+        s    - a mapping of variables to subtrees.
+
+    Returns
+    =======
+
+        lazy sequence of mappings {Variable: subtree}
+
+    Examples
+    ========
+
+    >>> from sympy.unify.core import unify, Compound, Variable
+    >>> expr    = Compound("Add", ("x", "y"))
+    >>> pattern = Compound("Add", ("x", Variable("a")))
+    >>> next(unify(expr, pattern, {}))
+    {Variable(a): 'y'}
+    """
+    s = s or {}
+
+    if x == y:
+        yield s
+    elif isinstance(x, (Variable, CondVariable)):
+        yield from unify_var(x, y, s, **fns)
+    elif isinstance(y, (Variable, CondVariable)):
+        yield from unify_var(y, x, s, **fns)
+    elif isinstance(x, Compound) and isinstance(y, Compound):
+        is_commutative = fns.get('is_commutative', lambda x: False)
+        is_associative = fns.get('is_associative', lambda x: False)
+        for sop in unify(x.op, y.op, s, **fns):
+            if is_associative(x) and is_associative(y):
+                a, b = (x, y) if len(x.args) < len(y.args) else (y, x)
+                if is_commutative(x) and is_commutative(y):
+                    combs = allcombinations(a.args, b.args, 'commutative')
+                else:
+                    combs = allcombinations(a.args, b.args, 'associative')
+                for aaargs, bbargs in combs:
+                    aa = [unpack(Compound(a.op, arg)) for arg in aaargs]
+                    bb = [unpack(Compound(b.op, arg)) for arg in bbargs]
+                    yield from unify(aa, bb, sop, **fns)
+            elif len(x.args) == len(y.args):
+                yield from unify(x.args, y.args, sop, **fns)
+
+    elif is_args(x) and is_args(y) and len(x) == len(y):
+        if len(x) == 0:
+            yield s
+        else:
+            for shead in unify(x[0], y[0], s, **fns):
+                yield from unify(x[1:], y[1:], shead, **fns)
+
+def unify_var(var, x, s, **fns):
+    if var in s:
+        yield from unify(s[var], x, s, **fns)
+    elif occur_check(var, x):
+        pass
+    elif isinstance(var, CondVariable) and var.valid(x):
+        yield assoc(s, var, x)
+    elif isinstance(var, Variable):
+        yield assoc(s, var, x)
+
+def occur_check(var, x):
+    """ var occurs in subtree owned by x? """
+    if var == x:
+        return True
+    elif isinstance(x, Compound):
+        return occur_check(var, x.args)
+    elif is_args(x):
+        if any(occur_check(var, xi) for xi in x): return True
+    return False
+
+def assoc(d, key, val):
+    """ Return copy of d with key associated to val """
+    d = d.copy()
+    d[key] = val
+    return d
+
+def is_args(x):
+    """ Is x a traditional iterable? """
+    return type(x) in (tuple, list, set)
+
+def unpack(x):
+    if isinstance(x, Compound) and len(x.args) == 1:
+        return x.args[0]
+    else:
+        return x
+
+def allcombinations(A, B, ordered):
+    """
+    Restructure A and B to have the same number of elements.
+
+    Parameters
+    ==========
+
+    ordered must be either 'commutative' or 'associative'.
+
+    A and B can be rearranged so that the larger of the two lists is
+    reorganized into smaller sublists.
+
+    Examples
+    ========
+
+    >>> from sympy.unify.core import allcombinations
+    >>> for x in allcombinations((1, 2, 3), (5, 6), 'associative'): print(x)
+    (((1,), (2, 3)), ((5,), (6,)))
+    (((1, 2), (3,)), ((5,), (6,)))
+
+    >>> for x in allcombinations((1, 2, 3), (5, 6), 'commutative'): print(x)
+        (((1,), (2, 3)), ((5,), (6,)))
+        (((1, 2), (3,)), ((5,), (6,)))
+        (((1,), (3, 2)), ((5,), (6,)))
+        (((1, 3), (2,)), ((5,), (6,)))
+        (((2,), (1, 3)), ((5,), (6,)))
+        (((2, 1), (3,)), ((5,), (6,)))
+        (((2,), (3, 1)), ((5,), (6,)))
+        (((2, 3), (1,)), ((5,), (6,)))
+        (((3,), (1, 2)), ((5,), (6,)))
+        (((3, 1), (2,)), ((5,), (6,)))
+        (((3,), (2, 1)), ((5,), (6,)))
+        (((3, 2), (1,)), ((5,), (6,)))
+    """
+
+    if ordered == "commutative":
+        ordered = 11
+    if ordered == "associative":
+        ordered = None
+    sm, bg = (A, B) if len(A) < len(B) else (B, A)
+    for part in kbins(list(range(len(bg))), len(sm), ordered=ordered):
+        if bg == B:
+            yield tuple((a,) for a in A), partition(B, part)
+        else:
+            yield partition(A, part), tuple((b,) for b in B)
+
+def partition(it, part):
+    """ Partition a tuple/list into pieces defined by indices.
+
+    Examples
+    ========
+
+    >>> from sympy.unify.core import partition
+    >>> partition((10, 20, 30, 40), [[0, 1, 2], [3]])
+    ((10, 20, 30), (40,))
+    """
+    return type(it)([index(it, ind) for ind in part])
+
+def index(it, ind):
+    """ Fancy indexing into an indexable iterable (tuple, list).
+
+    Examples
+    ========
+
+    >>> from sympy.unify.core import index
+    >>> index([10, 20, 30], (1, 2, 0))
+    [20, 30, 10]
+    """
+    return type(it)([it[i] for i in ind])
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/rewrite.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/rewrite.py
new file mode 100644
index 0000000000000000000000000000000000000000..95a6fa5ffd6a3fde94d17ee845c03bb2b44cf009
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/rewrite.py
@@ -0,0 +1,55 @@
+""" Functions to support rewriting of SymPy expressions """
+
+from sympy.core.expr import Expr
+from sympy.assumptions import ask
+from sympy.strategies.tools import subs
+from sympy.unify.usympy import rebuild, unify
+
+def rewriterule(source, target, variables=(), condition=None, assume=None):
+    """ Rewrite rule.
+
+    Transform expressions that match source into expressions that match target
+    treating all ``variables`` as wilds.
+
+    Examples
+    ========
+
+    >>> from sympy.abc import w, x, y, z
+    >>> from sympy.unify.rewrite import rewriterule
+    >>> from sympy import default_sort_key
+    >>> rl = rewriterule(x + y, x**y, [x, y])
+    >>> sorted(rl(z + 3), key=default_sort_key)
+    [3**z, z**3]
+
+    Use ``condition`` to specify additional requirements.  Inputs are taken in
+    the same order as is found in variables.
+
+    >>> rl = rewriterule(x + y, x**y, [x, y], lambda x, y: x.is_integer)
+    >>> list(rl(z + 3))
+    [3**z]
+
+    Use ``assume`` to specify additional requirements using new assumptions.
+
+    >>> from sympy.assumptions import Q
+    >>> rl = rewriterule(x + y, x**y, [x, y], assume=Q.integer(x))
+    >>> list(rl(z + 3))
+    [3**z]
+
+    Assumptions for the local context are provided at rule runtime
+
+    >>> list(rl(w + z, Q.integer(z)))
+    [z**w]
+    """
+
+    def rewrite_rl(expr, assumptions=True):
+        for match in unify(source, expr, {}, variables=variables):
+            if (condition and
+                not condition(*[match.get(var, var) for var in variables])):
+                continue
+            if (assume and not ask(assume.xreplace(match), assumptions)):
+                continue
+            expr2 = subs(match)(target)
+            if isinstance(expr2, Expr):
+                expr2 = rebuild(expr2)
+            yield expr2
+    return rewrite_rl
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/tests/test_rewrite.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/tests/test_rewrite.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b73e2856d5f6380c576220fa2780324df98091a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/tests/test_rewrite.py
@@ -0,0 +1,74 @@
+from sympy.unify.rewrite import rewriterule
+from sympy.core.basic import Basic
+from sympy.core.singleton import S
+from sympy.core.symbol import Symbol
+from sympy.functions.elementary.trigonometric import sin
+from sympy.abc import x, y
+from sympy.strategies.rl import rebuild
+from sympy.assumptions import Q
+
+p, q = Symbol('p'), Symbol('q')
+
+def test_simple():
+    rl = rewriterule(Basic(p, S(1)), Basic(p, S(2)), variables=(p,))
+    assert list(rl(Basic(S(3), S(1)))) == [Basic(S(3), S(2))]
+
+    p1 = p**2
+    p2 = p**3
+    rl = rewriterule(p1, p2, variables=(p,))
+
+    expr = x**2
+    assert list(rl(expr)) == [x**3]
+
+def test_simple_variables():
+    rl = rewriterule(Basic(x, S(1)), Basic(x, S(2)), variables=(x,))
+    assert list(rl(Basic(S(3), S(1)))) == [Basic(S(3), S(2))]
+
+    rl = rewriterule(x**2, x**3, variables=(x,))
+    assert list(rl(y**2)) == [y**3]
+
+def test_moderate():
+    p1 = p**2 + q**3
+    p2 = (p*q)**4
+    rl = rewriterule(p1, p2, (p, q))
+
+    expr = x**2 + y**3
+    assert list(rl(expr)) == [(x*y)**4]
+
+def test_sincos():
+    p1 = sin(p)**2 + sin(p)**2
+    p2 = 1
+    rl = rewriterule(p1, p2, (p, q))
+
+    assert list(rl(sin(x)**2 + sin(x)**2)) == [1]
+    assert list(rl(sin(y)**2 + sin(y)**2)) == [1]
+
+def test_Exprs_ok():
+    rl = rewriterule(p+q, q+p, (p, q))
+    next(rl(x+y)).is_commutative
+    str(next(rl(x+y)))
+
+def test_condition_simple():
+    rl = rewriterule(x, x+1, [x], lambda x: x < 10)
+    assert not list(rl(S(15)))
+    assert rebuild(next(rl(S(5)))) == 6
+
+
+def test_condition_multiple():
+    rl = rewriterule(x + y, x**y, [x,y], lambda x, y: x.is_integer)
+
+    a = Symbol('a')
+    b = Symbol('b', integer=True)
+    expr = a + b
+    assert list(rl(expr)) == [b**a]
+
+    c = Symbol('c', integer=True)
+    d = Symbol('d', integer=True)
+    assert set(rl(c + d)) == {c**d, d**c}
+
+def test_assumptions():
+    rl = rewriterule(x + y, x**y, [x, y], assume=Q.integer(x))
+
+    a, b = map(Symbol, 'ab')
+    expr = a + b
+    assert list(rl(expr, Q.integer(b))) == [b**a]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/tests/test_sympy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/tests/test_sympy.py
new file mode 100644
index 0000000000000000000000000000000000000000..eca3933a91abfabdbad96f626e4da761a41b3fd2
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/tests/test_sympy.py
@@ -0,0 +1,162 @@
+from sympy.core.add import Add
+from sympy.core.basic import Basic
+from sympy.core.containers import Tuple
+from sympy.core.singleton import S
+from sympy.core.symbol import (Symbol, symbols)
+from sympy.logic.boolalg import And
+from sympy.core.symbol import Str
+from sympy.unify.core import Compound, Variable
+from sympy.unify.usympy import (deconstruct, construct, unify, is_associative,
+        is_commutative)
+from sympy.abc import x, y, z, n
+
+def test_deconstruct():
+    expr     = Basic(S(1), S(2), S(3))
+    expected = Compound(Basic, (1, 2, 3))
+    assert deconstruct(expr) == expected
+
+    assert deconstruct(1) == 1
+    assert deconstruct(x) == x
+    assert deconstruct(x, variables=(x,)) == Variable(x)
+    assert deconstruct(Add(1, x, evaluate=False)) == Compound(Add, (1, x))
+    assert deconstruct(Add(1, x, evaluate=False), variables=(x,)) == \
+              Compound(Add, (1, Variable(x)))
+
+def test_construct():
+    expr     = Compound(Basic, (S(1), S(2), S(3)))
+    expected = Basic(S(1), S(2), S(3))
+    assert construct(expr) == expected
+
+def test_nested():
+    expr = Basic(S(1), Basic(S(2)), S(3))
+    cmpd = Compound(Basic, (S(1), Compound(Basic, Tuple(2)), S(3)))
+    assert deconstruct(expr) == cmpd
+    assert construct(cmpd) == expr
+
+def test_unify():
+    expr = Basic(S(1), S(2), S(3))
+    a, b, c = map(Symbol, 'abc')
+    pattern = Basic(a, b, c)
+    assert list(unify(expr, pattern, {}, (a, b, c))) == [{a: 1, b: 2, c: 3}]
+    assert list(unify(expr, pattern, variables=(a, b, c))) == \
+            [{a: 1, b: 2, c: 3}]
+
+def test_unify_variables():
+    assert list(unify(Basic(S(1), S(2)), Basic(S(1), x), {}, variables=(x,))) == [{x: 2}]
+
+def test_s_input():
+    expr = Basic(S(1), S(2))
+    a, b = map(Symbol, 'ab')
+    pattern = Basic(a, b)
+    assert list(unify(expr, pattern, {}, (a, b))) == [{a: 1, b: 2}]
+    assert list(unify(expr, pattern, {a: 5}, (a, b))) == []
+
+def iterdicteq(a, b):
+    a = tuple(a)
+    b = tuple(b)
+    return len(a) == len(b) and all(x in b for x in a)
+
+def test_unify_commutative():
+    expr = Add(1, 2, 3, evaluate=False)
+    a, b, c = map(Symbol, 'abc')
+    pattern = Add(a, b, c, evaluate=False)
+
+    result  = tuple(unify(expr, pattern, {}, (a, b, c)))
+    expected = ({a: 1, b: 2, c: 3},
+                {a: 1, b: 3, c: 2},
+                {a: 2, b: 1, c: 3},
+                {a: 2, b: 3, c: 1},
+                {a: 3, b: 1, c: 2},
+                {a: 3, b: 2, c: 1})
+
+    assert iterdicteq(result, expected)
+
+def test_unify_iter():
+    expr = Add(1, 2, 3, evaluate=False)
+    a, b, c = map(Symbol, 'abc')
+    pattern = Add(a, c, evaluate=False)
+    assert is_associative(deconstruct(pattern))
+    assert is_commutative(deconstruct(pattern))
+
+    result   = list(unify(expr, pattern, {}, (a, c)))
+    expected = [{a: 1, c: Add(2, 3, evaluate=False)},
+                {a: 1, c: Add(3, 2, evaluate=False)},
+                {a: 2, c: Add(1, 3, evaluate=False)},
+                {a: 2, c: Add(3, 1, evaluate=False)},
+                {a: 3, c: Add(1, 2, evaluate=False)},
+                {a: 3, c: Add(2, 1, evaluate=False)},
+                {a: Add(1, 2, evaluate=False), c: 3},
+                {a: Add(2, 1, evaluate=False), c: 3},
+                {a: Add(1, 3, evaluate=False), c: 2},
+                {a: Add(3, 1, evaluate=False), c: 2},
+                {a: Add(2, 3, evaluate=False), c: 1},
+                {a: Add(3, 2, evaluate=False), c: 1}]
+
+    assert iterdicteq(result, expected)
+
+def test_hard_match():
+    from sympy.functions.elementary.trigonometric import (cos, sin)
+    expr = sin(x) + cos(x)**2
+    p, q = map(Symbol, 'pq')
+    pattern = sin(p) + cos(p)**2
+    assert list(unify(expr, pattern, {}, (p, q))) == [{p: x}]
+
+def test_matrix():
+    from sympy.matrices.expressions.matexpr import MatrixSymbol
+    X = MatrixSymbol('X', n, n)
+    Y = MatrixSymbol('Y', 2, 2)
+    Z = MatrixSymbol('Z', 2, 3)
+    assert list(unify(X, Y, {}, variables=[n, Str('X')])) == [{Str('X'): Str('Y'), n: 2}]
+    assert list(unify(X, Z, {}, variables=[n, Str('X')])) == []
+
+def test_non_frankenAdds():
+    # the is_commutative property used to fail because of Basic.__new__
+    # This caused is_commutative and str calls to fail
+    expr = x+y*2
+    rebuilt = construct(deconstruct(expr))
+    # Ensure that we can run these commands without causing an error
+    str(rebuilt)
+    rebuilt.is_commutative
+
+def test_FiniteSet_commutivity():
+    from sympy.sets.sets import FiniteSet
+    a, b, c, x, y = symbols('a,b,c,x,y')
+    s = FiniteSet(a, b, c)
+    t = FiniteSet(x, y)
+    variables = (x, y)
+    assert {x: FiniteSet(a, c), y: b} in tuple(unify(s, t, variables=variables))
+
+def test_FiniteSet_complex():
+    from sympy.sets.sets import FiniteSet
+    a, b, c, x, y, z = symbols('a,b,c,x,y,z')
+    expr = FiniteSet(Basic(S(1), x), y, Basic(x, z))
+    pattern = FiniteSet(a, Basic(x, b))
+    variables = a, b
+    expected = ({b: 1, a: FiniteSet(y, Basic(x, z))},
+                      {b: z, a: FiniteSet(y, Basic(S(1), x))})
+    assert iterdicteq(unify(expr, pattern, variables=variables), expected)
+
+
+def test_and():
+    variables = x, y
+    expected = ({x: z > 0, y: n < 3},)
+    assert iterdicteq(unify((z>0) & (n<3), And(x, y), variables=variables),
+                      expected)
+
+def test_Union():
+    from sympy.sets.sets import Interval
+    assert list(unify(Interval(0, 1) + Interval(10, 11),
+                      Interval(0, 1) + Interval(12, 13),
+                      variables=(Interval(12, 13),)))
+
+def test_is_commutative():
+    assert is_commutative(deconstruct(x+y))
+    assert is_commutative(deconstruct(x*y))
+    assert not is_commutative(deconstruct(x**y))
+
+def test_commutative_in_commutative():
+    from sympy.abc import a,b,c,d
+    from sympy.functions.elementary.trigonometric import (cos, sin)
+    eq = sin(3)*sin(4)*sin(5) + 4*cos(3)*cos(4)
+    pat = a*cos(b)*cos(c) + d*sin(b)*sin(c)
+    assert next(unify(eq, pat, variables=(a,b,c,d)))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/tests/test_unify.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/tests/test_unify.py
new file mode 100644
index 0000000000000000000000000000000000000000..31153242576e1ff55dd3097efbc985aced5d574a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/tests/test_unify.py
@@ -0,0 +1,88 @@
+from sympy.unify.core import Compound, Variable, CondVariable, allcombinations
+from sympy.unify import core
+
+a,b,c = 'a', 'b', 'c'
+w,x,y,z = map(Variable, 'wxyz')
+
+C = Compound
+
+def is_associative(x):
+    return isinstance(x, Compound) and (x.op in ('Add', 'Mul', 'CAdd', 'CMul'))
+def is_commutative(x):
+    return isinstance(x, Compound) and (x.op in ('CAdd', 'CMul'))
+
+
+def unify(a, b, s={}):
+    return core.unify(a, b, s=s, is_associative=is_associative,
+                          is_commutative=is_commutative)
+
+def test_basic():
+    assert list(unify(a, x, {})) == [{x: a}]
+    assert list(unify(a, x, {x: 10})) == []
+    assert list(unify(1, x, {})) == [{x: 1}]
+    assert list(unify(a, a, {})) == [{}]
+    assert list(unify((w, x), (y, z), {})) == [{w: y, x: z}]
+    assert list(unify(x, (a, b), {})) == [{x: (a, b)}]
+
+    assert list(unify((a, b), (x, x), {})) == []
+    assert list(unify((y, z), (x, x), {}))!= []
+    assert list(unify((a, (b, c)), (a, (x, y)), {})) == [{x: b, y: c}]
+
+def test_ops():
+    assert list(unify(C('Add', (a,b,c)), C('Add', (a,x,y)), {})) == \
+            [{x:b, y:c}]
+    assert list(unify(C('Add', (C('Mul', (1,2)), b,c)), C('Add', (x,y,c)), {})) == \
+            [{x: C('Mul', (1,2)), y:b}]
+
+def test_associative():
+    c1 = C('Add', (1,2,3))
+    c2 = C('Add', (x,y))
+    assert tuple(unify(c1, c2, {})) == ({x: 1, y: C('Add', (2, 3))},
+                                         {x: C('Add', (1, 2)), y: 3})
+
+def test_commutative():
+    c1 = C('CAdd', (1,2,3))
+    c2 = C('CAdd', (x,y))
+    result = list(unify(c1, c2, {}))
+    assert  {x: 1, y: C('CAdd', (2, 3))} in result
+    assert ({x: 2, y: C('CAdd', (1, 3))} in result or
+            {x: 2, y: C('CAdd', (3, 1))} in result)
+
+def _test_combinations_assoc():
+    assert set(allcombinations((1,2,3), (a,b), True)) == \
+        {(((1, 2), (3,)), (a, b)), (((1,), (2, 3)), (a, b))}
+
+def _test_combinations_comm():
+    assert set(allcombinations((1,2,3), (a,b), None)) == \
+        {(((1,), (2, 3)), ('a', 'b')), (((2,), (3, 1)), ('a', 'b')),
+             (((3,), (1, 2)), ('a', 'b')), (((1, 2), (3,)), ('a', 'b')),
+             (((2, 3), (1,)), ('a', 'b')), (((3, 1), (2,)), ('a', 'b'))}
+
+def test_allcombinations():
+    assert set(allcombinations((1,2), (1,2), 'commutative')) ==\
+        {(((1,),(2,)), ((1,),(2,))), (((1,),(2,)), ((2,),(1,)))}
+
+
+def test_commutativity():
+    c1 = Compound('CAdd', (a, b))
+    c2 = Compound('CAdd', (x, y))
+    assert is_commutative(c1) and is_commutative(c2)
+    assert len(list(unify(c1, c2, {}))) == 2
+
+
+def test_CondVariable():
+    expr = C('CAdd', (1, 2))
+    x = Variable('x')
+    y = CondVariable('y', lambda a: a % 2 == 0)
+    z = CondVariable('z', lambda a: a > 3)
+    pattern = C('CAdd', (x, y))
+    assert list(unify(expr, pattern, {})) == \
+            [{x: 1, y: 2}]
+
+    z = CondVariable('z', lambda a: a > 3)
+    pattern = C('CAdd', (z, y))
+
+    assert list(unify(expr, pattern, {})) == []
+
+def test_defaultdict():
+    assert next(unify(Variable('x'), 'foo')) == {Variable('x'): 'foo'}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/usympy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/usympy.py
new file mode 100644
index 0000000000000000000000000000000000000000..3942b35ec549e5dbd08a3cf1cad2b2ecea733c7a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/unify/usympy.py
@@ -0,0 +1,124 @@
+""" SymPy interface to Unification engine
+
+See sympy.unify for module level docstring
+See sympy.unify.core for algorithmic docstring """
+
+from sympy.core import Basic, Add, Mul, Pow
+from sympy.core.operations import AssocOp, LatticeOp
+from sympy.matrices import MatAdd, MatMul, MatrixExpr
+from sympy.sets.sets import Union, Intersection, FiniteSet
+from sympy.unify.core import Compound, Variable, CondVariable
+from sympy.unify import core
+
+basic_new_legal = [MatrixExpr]
+eval_false_legal = [AssocOp, Pow, FiniteSet]
+illegal = [LatticeOp]
+
+def sympy_associative(op):
+    assoc_ops = (AssocOp, MatAdd, MatMul, Union, Intersection, FiniteSet)
+    return any(issubclass(op, aop) for aop in assoc_ops)
+
+def sympy_commutative(op):
+    comm_ops = (Add, MatAdd, Union, Intersection, FiniteSet)
+    return any(issubclass(op, cop) for cop in comm_ops)
+
+def is_associative(x):
+    return isinstance(x, Compound) and sympy_associative(x.op)
+
+def is_commutative(x):
+    if not isinstance(x, Compound):
+        return False
+    if sympy_commutative(x.op):
+        return True
+    if issubclass(x.op, Mul):
+        return all(construct(arg).is_commutative for arg in x.args)
+
+def mk_matchtype(typ):
+    def matchtype(x):
+        return (isinstance(x, typ) or
+                isinstance(x, Compound) and issubclass(x.op, typ))
+    return matchtype
+
+def deconstruct(s, variables=()):
+    """ Turn a SymPy object into a Compound """
+    if s in variables:
+        return Variable(s)
+    if isinstance(s, (Variable, CondVariable)):
+        return s
+    if not isinstance(s, Basic) or s.is_Atom:
+        return s
+    return Compound(s.__class__,
+                    tuple(deconstruct(arg, variables) for arg in s.args))
+
+def construct(t):
+    """ Turn a Compound into a SymPy object """
+    if isinstance(t, (Variable, CondVariable)):
+        return t.arg
+    if not isinstance(t, Compound):
+        return t
+    if any(issubclass(t.op, cls) for cls in eval_false_legal):
+        return t.op(*map(construct, t.args), evaluate=False)
+    elif any(issubclass(t.op, cls) for cls in basic_new_legal):
+        return Basic.__new__(t.op, *map(construct, t.args))
+    else:
+        return t.op(*map(construct, t.args))
+
+def rebuild(s):
+    """ Rebuild a SymPy expression.
+
+    This removes harm caused by Expr-Rules interactions.
+    """
+    return construct(deconstruct(s))
+
+def unify(x, y, s=None, variables=(), **kwargs):
+    """ Structural unification of two expressions/patterns.
+
+    Examples
+    ========
+
+    >>> from sympy.unify.usympy import unify
+    >>> from sympy import Basic, S
+    >>> from sympy.abc import x, y, z, p, q
+
+    >>> next(unify(Basic(S(1), S(2)), Basic(S(1), x), variables=[x]))
+    {x: 2}
+
+    >>> expr = 2*x + y + z
+    >>> pattern = 2*p + q
+    >>> next(unify(expr, pattern, {}, variables=(p, q)))
+    {p: x, q: y + z}
+
+    Unification supports commutative and associative matching
+
+    >>> expr = x + y + z
+    >>> pattern = p + q
+    >>> len(list(unify(expr, pattern, {}, variables=(p, q))))
+    12
+
+    Symbols not indicated to be variables are treated as literal,
+    else they are wild-like and match anything in a sub-expression.
+
+    >>> expr = x*y*z + 3
+    >>> pattern = x*y + 3
+    >>> next(unify(expr, pattern, {}, variables=[x, y]))
+    {x: y, y: x*z}
+
+    The x and y of the pattern above were in a Mul and matched factors
+    in the Mul of expr. Here, a single symbol matches an entire term:
+
+    >>> expr = x*y + 3
+    >>> pattern = p + 3
+    >>> next(unify(expr, pattern, {}, variables=[p]))
+    {p: x*y}
+
+    """
+    decons = lambda x: deconstruct(x, variables)
+    s = s or {}
+    s = {decons(k): decons(v) for k, v in s.items()}
+
+    ds = core.unify(decons(x), decons(y), s,
+                                     is_associative=is_associative,
+                                     is_commutative=is_commutative,
+                                     **kwargs)
+    for d in ds:
+        yield {construct(k): construct(v) for k, v in d.items()}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f35da4a84396618a33a12c3c6b5cf58e9d4742c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__init__.py
@@ -0,0 +1,30 @@
+"""This module contains some general purpose utilities that are used across
+SymPy.
+"""
+from .iterables import (flatten, group, take, subsets,
+    variations, numbered_symbols, cartes, capture, dict_merge,
+    prefixes, postfixes, sift, topological_sort, unflatten,
+    has_dups, has_variety, reshape, rotations)
+
+from .misc import filldedent
+
+from .lambdify import lambdify
+
+from .decorator import threaded, xthreaded, public, memoize_property
+
+from .timeutils import timed
+
+__all__ = [
+    'flatten', 'group', 'take', 'subsets', 'variations', 'numbered_symbols',
+    'cartes', 'capture', 'dict_merge', 'prefixes', 'postfixes', 'sift',
+    'topological_sort', 'unflatten', 'has_dups', 'has_variety', 'reshape',
+    'rotations',
+
+    'filldedent',
+
+    'lambdify',
+
+    'threaded', 'xthreaded', 'public', 'memoize_property',
+
+    'timed',
+]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b5a18fd159ca4519e6e66534b278393903c4c2c4
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/decorator.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/decorator.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6da898c4fbd198174ededc56e6666c73990d2c52
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/decorator.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/enumerative.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/enumerative.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8fcd3e549f7ed5dacc04fb301ae55ae07f0d30be
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/enumerative.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/exceptions.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/exceptions.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8f9b09e9790610e459ca33655cc623bc6277369a
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/exceptions.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/iterables.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/iterables.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fd121f1128c64bf5cc955218b92b66e30e97b62c
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/iterables.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/lambdify.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/lambdify.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..445d1a78dac4e59c236df2b1e8830da5450cffb3
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/lambdify.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/magic.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/magic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..beea5fe0aec4b75ff3d8e213d719144b3b1dea37
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/magic.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/memoization.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/memoization.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b30c8fea16e05ee1a7803a060d2b5e18e2a1b356
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/memoization.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/misc.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/misc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b642f3ce90cd17e862efa8d2f3a95661d7b2c963
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/misc.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/source.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/source.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4e59886ba6750dfbf7d871987c8597f7cfc19ba3
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/source.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/timeutils.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/timeutils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2b5f3d283bf4ba999920f4d64b325302d1b37994
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/__pycache__/timeutils.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/_compilation/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/_compilation/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d2c05ad48a93493bb5434256c88dfd614ac47b2d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/_compilation/__init__.py
@@ -0,0 +1,22 @@
+""" This sub-module is private, i.e. external code should not depend on it.
+
+These functions are used by tests run as part of continuous integration.
+Once the implementation is mature (it should support the major
+platforms: Windows, OS X & Linux) it may become official API which
+ may be relied upon by downstream libraries. Until then API may break
+without prior notice.
+
+TODO:
+- (optionally) clean up after tempfile.mkdtemp()
+- cross-platform testing
+- caching of compiler choice and intermediate files
+
+"""
+
+from .compilation import compile_link_import_strings, compile_run_strings
+from .availability import has_fortran, has_c, has_cxx
+
+__all__ = [
+    'compile_link_import_strings', 'compile_run_strings',
+    'has_fortran', 'has_c', 'has_cxx',
+]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/_compilation/availability.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/_compilation/availability.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc97b3e7b8c7e7307c6c21352ed4035d977aabb3
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/_compilation/availability.py
@@ -0,0 +1,77 @@
+import os
+from .compilation import compile_run_strings
+from .util import CompilerNotFoundError
+
+def has_fortran():
+    if not hasattr(has_fortran, 'result'):
+        try:
+            (stdout, stderr), info = compile_run_strings(
+                [('main.f90', (
+                    'program foo\n'
+                    'print *, "hello world"\n'
+                    'end program'
+                ))], clean=True
+            )
+        except CompilerNotFoundError:
+            has_fortran.result = False
+            if os.environ.get('SYMPY_STRICT_COMPILER_CHECKS', '0') == '1':
+                raise
+        else:
+            if info['exit_status'] != os.EX_OK or 'hello world' not in stdout:
+                if os.environ.get('SYMPY_STRICT_COMPILER_CHECKS', '0') == '1':
+                    raise ValueError("Failed to compile test program:\n%s\n%s\n" % (stdout, stderr))
+                has_fortran.result = False
+            else:
+                has_fortran.result = True
+    return has_fortran.result
+
+
+def has_c():
+    if not hasattr(has_c, 'result'):
+        try:
+            (stdout, stderr), info = compile_run_strings(
+                [('main.c', (
+                    '#include \n'
+                    'int main(){\n'
+                    'printf("hello world\\n");\n'
+                    'return 0;\n'
+                    '}'
+                ))], clean=True
+            )
+        except CompilerNotFoundError:
+            has_c.result = False
+            if os.environ.get('SYMPY_STRICT_COMPILER_CHECKS', '0') == '1':
+                raise
+        else:
+            if info['exit_status'] != os.EX_OK or 'hello world' not in stdout:
+                if os.environ.get('SYMPY_STRICT_COMPILER_CHECKS', '0') == '1':
+                    raise ValueError("Failed to compile test program:\n%s\n%s\n" % (stdout, stderr))
+                has_c.result = False
+            else:
+                has_c.result = True
+    return has_c.result
+
+
+def has_cxx():
+    if not hasattr(has_cxx, 'result'):
+        try:
+            (stdout, stderr), info = compile_run_strings(
+                [('main.cxx', (
+                    '#include \n'
+                    'int main(){\n'
+                    'std::cout << "hello world" << std::endl;\n'
+                    '}'
+                ))], clean=True
+            )
+        except CompilerNotFoundError:
+            has_cxx.result = False
+            if os.environ.get('SYMPY_STRICT_COMPILER_CHECKS', '0') == '1':
+                raise
+        else:
+            if info['exit_status'] != os.EX_OK or 'hello world' not in stdout:
+                if os.environ.get('SYMPY_STRICT_COMPILER_CHECKS', '0') == '1':
+                    raise ValueError("Failed to compile test program:\n%s\n%s\n" % (stdout, stderr))
+                has_cxx.result = False
+            else:
+                has_cxx.result = True
+    return has_cxx.result
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/_compilation/compilation.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/_compilation/compilation.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d50a20467c08086d6cb5fb5b0d478e7a953d720
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/_compilation/compilation.py
@@ -0,0 +1,657 @@
+import glob
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import warnings
+from pathlib import Path
+from sysconfig import get_config_var, get_config_vars, get_path
+
+from .runners import (
+    CCompilerRunner,
+    CppCompilerRunner,
+    FortranCompilerRunner
+)
+from .util import (
+    get_abspath, make_dirs, copy, Glob, ArbitraryDepthGlob,
+    glob_at_depth, import_module_from_file, pyx_is_cplus,
+    sha256_of_string, sha256_of_file, CompileError
+)
+
+if os.name == 'posix':
+    objext = '.o'
+elif os.name == 'nt':
+    objext = '.obj'
+else:
+    warnings.warn("Unknown os.name: {}".format(os.name))
+    objext = '.o'
+
+
+def compile_sources(files, Runner=None, destdir=None, cwd=None, keep_dir_struct=False,
+                    per_file_kwargs=None, **kwargs):
+    """ Compile source code files to object files.
+
+    Parameters
+    ==========
+
+    files : iterable of str
+        Paths to source files, if ``cwd`` is given, the paths are taken as relative.
+    Runner: CompilerRunner subclass (optional)
+        Could be e.g. ``FortranCompilerRunner``. Will be inferred from filename
+        extensions if missing.
+    destdir: str
+        Output directory, if cwd is given, the path is taken as relative.
+    cwd: str
+        Working directory. Specify to have compiler run in other directory.
+        also used as root of relative paths.
+    keep_dir_struct: bool
+        Reproduce directory structure in `destdir`. default: ``False``
+    per_file_kwargs: dict
+        Dict mapping instances in ``files`` to keyword arguments.
+    \\*\\*kwargs: dict
+        Default keyword arguments to pass to ``Runner``.
+
+    Returns
+    =======
+    List of strings (paths of object files).
+    """
+    _per_file_kwargs = {}
+
+    if per_file_kwargs is not None:
+        for k, v in per_file_kwargs.items():
+            if isinstance(k, Glob):
+                for path in glob.glob(k.pathname):
+                    _per_file_kwargs[path] = v
+            elif isinstance(k, ArbitraryDepthGlob):
+                for path in glob_at_depth(k.filename, cwd):
+                    _per_file_kwargs[path] = v
+            else:
+                _per_file_kwargs[k] = v
+
+    # Set up destination directory
+    destdir = destdir or '.'
+    if not os.path.isdir(destdir):
+        if os.path.exists(destdir):
+            raise OSError("{} is not a directory".format(destdir))
+        else:
+            make_dirs(destdir)
+    if cwd is None:
+        cwd = '.'
+        for f in files:
+            copy(f, destdir, only_update=True, dest_is_dir=True)
+
+    # Compile files and return list of paths to the objects
+    dstpaths = []
+    for f in files:
+        if keep_dir_struct:
+            name, ext = os.path.splitext(f)
+        else:
+            name, ext = os.path.splitext(os.path.basename(f))
+        file_kwargs = kwargs.copy()
+        file_kwargs.update(_per_file_kwargs.get(f, {}))
+        dstpaths.append(src2obj(f, Runner, cwd=cwd, **file_kwargs))
+    return dstpaths
+
+
+def get_mixed_fort_c_linker(vendor=None, cplus=False, cwd=None):
+    vendor = vendor or os.environ.get('SYMPY_COMPILER_VENDOR', 'gnu')
+
+    if vendor.lower() == 'intel':
+        if cplus:
+            return (FortranCompilerRunner,
+                    {'flags': ['-nofor_main', '-cxxlib']}, vendor)
+        else:
+            return (FortranCompilerRunner,
+                    {'flags': ['-nofor_main']}, vendor)
+    elif vendor.lower() == 'gnu' or 'llvm':
+        if cplus:
+            return (CppCompilerRunner,
+                    {'lib_options': ['fortran']}, vendor)
+        else:
+            return (FortranCompilerRunner,
+                    {}, vendor)
+    else:
+        raise ValueError("No vendor found.")
+
+
+def link(obj_files, out_file=None, shared=False, Runner=None,
+         cwd=None, cplus=False, fort=False, extra_objs=None, **kwargs):
+    """ Link object files.
+
+    Parameters
+    ==========
+
+    obj_files: iterable of str
+        Paths to object files.
+    out_file: str (optional)
+        Path to executable/shared library, if ``None`` it will be
+        deduced from the last item in obj_files.
+    shared: bool
+        Generate a shared library?
+    Runner: CompilerRunner subclass (optional)
+        If not given the ``cplus`` and ``fort`` flags will be inspected
+        (fallback is the C compiler).
+    cwd: str
+        Path to the root of relative paths and working directory for compiler.
+    cplus: bool
+        C++ objects? default: ``False``.
+    fort: bool
+        Fortran objects? default: ``False``.
+    extra_objs: list
+        List of paths to extra object files / static libraries.
+    \\*\\*kwargs: dict
+        Keyword arguments passed to ``Runner``.
+
+    Returns
+    =======
+
+    The absolute path to the generated shared object / executable.
+
+    """
+    if out_file is None:
+        out_file, ext = os.path.splitext(os.path.basename(obj_files[-1]))
+        if shared:
+            out_file += get_config_var('EXT_SUFFIX')
+
+    if not Runner:
+        if fort:
+            Runner, extra_kwargs, vendor = \
+                get_mixed_fort_c_linker(
+                    vendor=kwargs.get('vendor', None),
+                    cplus=cplus,
+                    cwd=cwd,
+                )
+            for k, v in extra_kwargs.items():
+                if k in kwargs:
+                    kwargs[k].expand(v)
+                else:
+                    kwargs[k] = v
+        else:
+            if cplus:
+                Runner = CppCompilerRunner
+            else:
+                Runner = CCompilerRunner
+
+    flags = kwargs.pop('flags', [])
+    if shared:
+        if '-shared' not in flags:
+            flags.append('-shared')
+    run_linker = kwargs.pop('run_linker', True)
+    if not run_linker:
+        raise ValueError("run_linker was set to False (nonsensical).")
+
+    out_file = get_abspath(out_file, cwd=cwd)
+    runner = Runner(obj_files+(extra_objs or []), out_file, flags, cwd=cwd, **kwargs)
+    runner.run()
+    return out_file
+
+
+def link_py_so(obj_files, so_file=None, cwd=None, libraries=None,
+               cplus=False, fort=False, extra_objs=None, **kwargs):
+    """ Link Python extension module (shared object) for importing
+
+    Parameters
+    ==========
+
+    obj_files: iterable of str
+        Paths to object files to be linked.
+    so_file: str
+        Name (path) of shared object file to create. If not specified it will
+        have the basname of the last object file in `obj_files` but with the
+        extension '.so' (Unix).
+    cwd: path string
+        Root of relative paths and working directory of linker.
+    libraries: iterable of strings
+        Libraries to link against, e.g. ['m'].
+    cplus: bool
+        Any C++ objects? default: ``False``.
+    fort: bool
+        Any Fortran objects? default: ``False``.
+    extra_objs: list
+        List of paths of extra object files / static libraries to link against.
+    kwargs**: dict
+        Keyword arguments passed to ``link(...)``.
+
+    Returns
+    =======
+
+    Absolute path to the generate shared object.
+    """
+    libraries = libraries or []
+
+    include_dirs = kwargs.pop('include_dirs', [])
+    library_dirs = kwargs.pop('library_dirs', [])
+
+    # Add Python include and library directories
+    # PY_LDFLAGS does not available on all python implementations
+    # e.g. when with pypy, so it's LDFLAGS we need to use
+    if sys.platform == "win32":
+        warnings.warn("Windows not yet supported.")
+    elif sys.platform == 'darwin':
+        cfgDict = get_config_vars()
+        kwargs['linkline'] = kwargs.get('linkline', []) + [cfgDict['LDFLAGS']]
+        library_dirs += [cfgDict['LIBDIR']]
+
+        # In macOS, linker needs to compile frameworks
+        # e.g. "-framework CoreFoundation"
+        is_framework = False
+        for opt in cfgDict['LIBS'].split():
+            if is_framework:
+                kwargs['linkline'] = kwargs.get('linkline', []) + ['-framework', opt]
+                is_framework = False
+            elif opt.startswith('-l'):
+                libraries.append(opt[2:])
+            elif opt.startswith('-framework'):
+                is_framework = True
+        # The python library is not included in LIBS
+        libfile = cfgDict['LIBRARY']
+        libname = ".".join(libfile.split('.')[:-1])[3:]
+        libraries.append(libname)
+
+    elif sys.platform[:3] == 'aix':
+        # Don't use the default code below
+        pass
+    else:
+        if get_config_var('Py_ENABLE_SHARED'):
+            cfgDict = get_config_vars()
+            kwargs['linkline'] = kwargs.get('linkline', []) + [cfgDict['LDFLAGS']]
+            library_dirs += [cfgDict['LIBDIR']]
+            for opt in cfgDict['BLDLIBRARY'].split():
+                if opt.startswith('-l'):
+                    libraries += [opt[2:]]
+        else:
+            pass
+
+    flags = kwargs.pop('flags', [])
+    needed_flags = ('-pthread',)
+    for flag in needed_flags:
+        if flag not in flags:
+            flags.append(flag)
+
+    return link(obj_files, shared=True, flags=flags, cwd=cwd, cplus=cplus, fort=fort,
+                include_dirs=include_dirs, libraries=libraries,
+                library_dirs=library_dirs, extra_objs=extra_objs, **kwargs)
+
+
+def simple_cythonize(src, destdir=None, cwd=None, **cy_kwargs):
+    """ Generates a C file from a Cython source file.
+
+    Parameters
+    ==========
+
+    src: str
+        Path to Cython source.
+    destdir: str (optional)
+        Path to output directory (default: '.').
+    cwd: path string (optional)
+        Root of relative paths (default: '.').
+    **cy_kwargs:
+        Second argument passed to cy_compile. Generates a .cpp file if ``cplus=True`` in ``cy_kwargs``,
+        else a .c file.
+    """
+    from Cython.Compiler.Main import (
+        default_options, CompilationOptions
+    )
+    from Cython.Compiler.Main import compile as cy_compile
+
+    assert src.lower().endswith('.pyx') or src.lower().endswith('.py')
+    cwd = cwd or '.'
+    destdir = destdir or '.'
+
+    ext = '.cpp' if cy_kwargs.get('cplus', False) else '.c'
+    c_name = os.path.splitext(os.path.basename(src))[0] + ext
+
+    dstfile = os.path.join(destdir, c_name)
+
+    if cwd:
+        ori_dir = os.getcwd()
+    else:
+        ori_dir = '.'
+    os.chdir(cwd)
+    try:
+        cy_options = CompilationOptions(default_options)
+        cy_options.__dict__.update(cy_kwargs)
+        # Set language_level if not set by cy_kwargs
+        # as not setting it is deprecated
+        if 'language_level' not in cy_kwargs:
+            cy_options.__dict__['language_level'] = 3
+        cy_result = cy_compile([src], cy_options)
+        if cy_result.num_errors > 0:
+            raise ValueError("Cython compilation failed.")
+
+        # Move generated C file to destination
+        # In macOS, the generated C file is in the same directory as the source
+        # but the /var is a symlink to /private/var, so we need to use realpath
+        if os.path.realpath(os.path.dirname(src)) != os.path.realpath(destdir):
+            if os.path.exists(dstfile):
+                os.unlink(dstfile)
+            shutil.move(os.path.join(os.path.dirname(src), c_name), destdir)
+    finally:
+        os.chdir(ori_dir)
+    return dstfile
+
+
+extension_mapping = {
+    '.c': (CCompilerRunner, None),
+    '.cpp': (CppCompilerRunner, None),
+    '.cxx': (CppCompilerRunner, None),
+    '.f': (FortranCompilerRunner, None),
+    '.for': (FortranCompilerRunner, None),
+    '.ftn': (FortranCompilerRunner, None),
+    '.f90': (FortranCompilerRunner, None),  # ifort only knows about .f90
+    '.f95': (FortranCompilerRunner, 'f95'),
+    '.f03': (FortranCompilerRunner, 'f2003'),
+    '.f08': (FortranCompilerRunner, 'f2008'),
+}
+
+
+def src2obj(srcpath, Runner=None, objpath=None, cwd=None, inc_py=False, **kwargs):
+    """ Compiles a source code file to an object file.
+
+    Files ending with '.pyx' assumed to be cython files and
+    are dispatched to pyx2obj.
+
+    Parameters
+    ==========
+
+    srcpath: str
+        Path to source file.
+    Runner: CompilerRunner subclass (optional)
+        If ``None``: deduced from extension of srcpath.
+    objpath : str (optional)
+        Path to generated object. If ``None``: deduced from ``srcpath``.
+    cwd: str (optional)
+        Working directory and root of relative paths. If ``None``: current dir.
+    inc_py: bool
+        Add Python include path to kwarg "include_dirs". Default: False
+    \\*\\*kwargs: dict
+        keyword arguments passed to Runner or pyx2obj
+
+    """
+    name, ext = os.path.splitext(os.path.basename(srcpath))
+    if objpath is None:
+        if os.path.isabs(srcpath):
+            objpath = '.'
+        else:
+            objpath = os.path.dirname(srcpath)
+            objpath = objpath or '.'  # avoid objpath == ''
+
+    if os.path.isdir(objpath):
+        objpath = os.path.join(objpath, name + objext)
+
+    include_dirs = kwargs.pop('include_dirs', [])
+    if inc_py:
+        py_inc_dir = get_path('include')
+        if py_inc_dir not in include_dirs:
+            include_dirs.append(py_inc_dir)
+
+    if ext.lower() == '.pyx':
+        return pyx2obj(srcpath, objpath=objpath, include_dirs=include_dirs, cwd=cwd,
+                       **kwargs)
+
+    if Runner is None:
+        Runner, std = extension_mapping[ext.lower()]
+        if 'std' not in kwargs:
+            kwargs['std'] = std
+
+    flags = kwargs.pop('flags', [])
+    needed_flags = ('-fPIC',)
+    for flag in needed_flags:
+        if flag not in flags:
+            flags.append(flag)
+
+    # src2obj implies not running the linker...
+    run_linker = kwargs.pop('run_linker', False)
+    if run_linker:
+        raise CompileError("src2obj called with run_linker=True")
+
+    runner = Runner([srcpath], objpath, include_dirs=include_dirs,
+                    run_linker=run_linker, cwd=cwd, flags=flags, **kwargs)
+    runner.run()
+    return objpath
+
+
+def pyx2obj(pyxpath, objpath=None, destdir=None, cwd=None,
+            include_dirs=None, cy_kwargs=None, cplus=None, **kwargs):
+    """
+    Convenience function
+
+    If cwd is specified, pyxpath and dst are taken to be relative
+    If only_update is set to `True` the modification time is checked
+    and compilation is only run if the source is newer than the
+    destination
+
+    Parameters
+    ==========
+
+    pyxpath: str
+        Path to Cython source file.
+    objpath: str (optional)
+        Path to object file to generate.
+    destdir: str (optional)
+        Directory to put generated C file. When ``None``: directory of ``objpath``.
+    cwd: str (optional)
+        Working directory and root of relative paths.
+    include_dirs: iterable of path strings (optional)
+        Passed onto src2obj and via cy_kwargs['include_path']
+        to simple_cythonize.
+    cy_kwargs: dict (optional)
+        Keyword arguments passed onto `simple_cythonize`
+    cplus: bool (optional)
+        Indicate whether C++ is used. default: auto-detect using ``.util.pyx_is_cplus``.
+    compile_kwargs: dict
+        keyword arguments passed onto src2obj
+
+    Returns
+    =======
+
+    Absolute path of generated object file.
+
+    """
+    assert pyxpath.endswith('.pyx')
+    cwd = cwd or '.'
+    objpath = objpath or '.'
+    destdir = destdir or os.path.dirname(objpath)
+
+    abs_objpath = get_abspath(objpath, cwd=cwd)
+
+    if os.path.isdir(abs_objpath):
+        pyx_fname = os.path.basename(pyxpath)
+        name, ext = os.path.splitext(pyx_fname)
+        objpath = os.path.join(objpath, name + objext)
+
+    cy_kwargs = cy_kwargs or {}
+    cy_kwargs['output_dir'] = cwd
+    if cplus is None:
+        cplus = pyx_is_cplus(pyxpath)
+    cy_kwargs['cplus'] = cplus
+
+    interm_c_file = simple_cythonize(pyxpath, destdir=destdir, cwd=cwd, **cy_kwargs)
+
+    include_dirs = include_dirs or []
+    flags = kwargs.pop('flags', [])
+    needed_flags = ('-fwrapv', '-pthread', '-fPIC')
+    for flag in needed_flags:
+        if flag not in flags:
+            flags.append(flag)
+
+    options = kwargs.pop('options', [])
+
+    if kwargs.pop('strict_aliasing', False):
+        raise CompileError("Cython requires strict aliasing to be disabled.")
+
+    # Let's be explicit about standard
+    if cplus:
+        std = kwargs.pop('std', 'c++98')
+    else:
+        std = kwargs.pop('std', 'c99')
+
+    return src2obj(interm_c_file, objpath=objpath, cwd=cwd,
+                   include_dirs=include_dirs, flags=flags, std=std,
+                   options=options, inc_py=True, strict_aliasing=False,
+                   **kwargs)
+
+
+def _any_X(srcs, cls):
+    for src in srcs:
+        name, ext = os.path.splitext(src)
+        key = ext.lower()
+        if key in extension_mapping:
+            if extension_mapping[key][0] == cls:
+                return True
+    return False
+
+
+def any_fortran_src(srcs):
+    return _any_X(srcs, FortranCompilerRunner)
+
+
+def any_cplus_src(srcs):
+    return _any_X(srcs, CppCompilerRunner)
+
+
+def compile_link_import_py_ext(sources, extname=None, build_dir='.', compile_kwargs=None,
+                               link_kwargs=None, extra_objs=None):
+    """ Compiles sources to a shared object (Python extension) and imports it
+
+    Sources in ``sources`` which is imported. If shared object is newer than the sources, they
+    are not recompiled but instead it is imported.
+
+    Parameters
+    ==========
+
+    sources : list of strings
+        List of paths to sources.
+    extname : string
+        Name of extension (default: ``None``).
+        If ``None``: taken from the last file in ``sources`` without extension.
+    build_dir: str
+        Path to directory in which objects files etc. are generated.
+    compile_kwargs: dict
+        keyword arguments passed to ``compile_sources``
+    link_kwargs: dict
+        keyword arguments passed to ``link_py_so``
+    extra_objs: list
+        List of paths to (prebuilt) object files / static libraries to link against.
+
+    Returns
+    =======
+
+    The imported module from of the Python extension.
+    """
+    if extname is None:
+        extname = os.path.splitext(os.path.basename(sources[-1]))[0]
+
+    compile_kwargs = compile_kwargs or {}
+    link_kwargs = link_kwargs or {}
+
+    try:
+        mod = import_module_from_file(os.path.join(build_dir, extname), sources)
+    except ImportError:
+        objs = compile_sources(list(map(get_abspath, sources)), destdir=build_dir,
+                               cwd=build_dir, **compile_kwargs)
+        so = link_py_so(objs, cwd=build_dir, fort=any_fortran_src(sources),
+                        cplus=any_cplus_src(sources), extra_objs=extra_objs, **link_kwargs)
+        mod = import_module_from_file(so)
+    return mod
+
+
+def _write_sources_to_build_dir(sources, build_dir):
+    build_dir = build_dir or tempfile.mkdtemp()
+    if not os.path.isdir(build_dir):
+        raise OSError("Non-existent directory: ", build_dir)
+
+    source_files = []
+    for name, src in sources:
+        dest = os.path.join(build_dir, name)
+        differs = True
+        sha256_in_mem = sha256_of_string(src.encode('utf-8')).hexdigest()
+        if os.path.exists(dest):
+            if os.path.exists(dest + '.sha256'):
+                sha256_on_disk = Path(dest + '.sha256').read_text()
+            else:
+                sha256_on_disk = sha256_of_file(dest).hexdigest()
+
+            differs = sha256_on_disk != sha256_in_mem
+        if differs:
+            with open(dest, 'wt') as fh:
+                fh.write(src)
+            with open(dest + '.sha256', 'wt') as fh:
+                fh.write(sha256_in_mem)
+        source_files.append(dest)
+    return source_files, build_dir
+
+
+def compile_link_import_strings(sources, build_dir=None, **kwargs):
+    """ Compiles, links and imports extension module from source.
+
+    Parameters
+    ==========
+
+    sources : iterable of name/source pair tuples
+    build_dir : string (default: None)
+        Path. ``None`` implies use a temporary directory.
+    **kwargs:
+        Keyword arguments passed onto `compile_link_import_py_ext`.
+
+    Returns
+    =======
+
+    mod : module
+        The compiled and imported extension module.
+    info : dict
+        Containing ``build_dir`` as 'build_dir'.
+
+    """
+    source_files, build_dir = _write_sources_to_build_dir(sources, build_dir)
+    mod = compile_link_import_py_ext(source_files, build_dir=build_dir, **kwargs)
+    info = {"build_dir": build_dir}
+    return mod, info
+
+
+def compile_run_strings(sources, build_dir=None, clean=False, compile_kwargs=None, link_kwargs=None):
+    """ Compiles, links and runs a program built from sources.
+
+    Parameters
+    ==========
+
+    sources : iterable of name/source pair tuples
+    build_dir : string (default: None)
+        Path. ``None`` implies use a temporary directory.
+    clean : bool
+        Whether to remove build_dir after use. This will only have an
+        effect if ``build_dir`` is ``None`` (which creates a temporary directory).
+        Passing ``clean == True`` and ``build_dir != None`` raises a ``ValueError``.
+        This will also set ``build_dir`` in returned info dictionary to ``None``.
+    compile_kwargs: dict
+        Keyword arguments passed onto ``compile_sources``
+    link_kwargs: dict
+        Keyword arguments passed onto ``link``
+
+    Returns
+    =======
+
+    (stdout, stderr): pair of strings
+    info: dict
+        Containing exit status as 'exit_status' and ``build_dir`` as 'build_dir'
+
+    """
+    if clean and build_dir is not None:
+        raise ValueError("Automatic removal of build_dir is only available for temporary directory.")
+    try:
+        source_files, build_dir = _write_sources_to_build_dir(sources, build_dir)
+        objs = compile_sources(list(map(get_abspath, source_files)), destdir=build_dir,
+                               cwd=build_dir, **(compile_kwargs or {}))
+        prog = link(objs, cwd=build_dir,
+                    fort=any_fortran_src(source_files),
+                    cplus=any_cplus_src(source_files), **(link_kwargs or {}))
+        p = subprocess.Popen([prog], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+        exit_status = p.wait()
+        stdout, stderr = [txt.decode('utf-8') for txt in p.communicate()]
+    finally:
+        if clean and os.path.isdir(build_dir):
+            shutil.rmtree(build_dir)
+            build_dir = None
+    info = {"exit_status": exit_status, "build_dir": build_dir}
+    return (stdout, stderr), info
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/_compilation/runners.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/_compilation/runners.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f37d6cf8ac47807da7f3f00dfc5cd847c03fa8d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/_compilation/runners.py
@@ -0,0 +1,301 @@
+from __future__ import annotations
+from typing import Callable, Optional
+
+from collections import OrderedDict
+import os
+import re
+import subprocess
+import warnings
+
+from .util import (
+    find_binary_of_command, unique_list, CompileError
+)
+
+
+class CompilerRunner:
+    """ CompilerRunner base class.
+
+    Parameters
+    ==========
+
+    sources : list of str
+        Paths to sources.
+    out : str
+    flags : iterable of str
+        Compiler flags.
+    run_linker : bool
+    compiler_name_exe : (str, str) tuple
+        Tuple of compiler name &  command to call.
+    cwd : str
+        Path of root of relative paths.
+    include_dirs : list of str
+        Include directories.
+    libraries : list of str
+        Libraries to link against.
+    library_dirs : list of str
+        Paths to search for shared libraries.
+    std : str
+        Standard string, e.g. ``'c++11'``, ``'c99'``, ``'f2003'``.
+    define: iterable of strings
+        macros to define
+    undef : iterable of strings
+        macros to undefine
+    preferred_vendor : string
+        name of preferred vendor e.g. 'gnu' or 'intel'
+
+    Methods
+    =======
+
+    run():
+        Invoke compilation as a subprocess.
+
+    """
+
+    environ_key_compiler: str  # e.g. 'CC', 'CXX', ...
+    environ_key_flags: str  # e.g. 'CFLAGS', 'CXXFLAGS', ...
+    environ_key_ldflags: str = "LDFLAGS"  # typically 'LDFLAGS'
+
+    # Subclass to vendor/binary dict
+    compiler_dict: dict[str, str]
+
+    # Standards should be a tuple of supported standards
+    # (first one will be the default)
+    standards: tuple[None | str, ...]
+
+    # Subclass to dict of binary/formater-callback
+    std_formater: dict[str, Callable[[Optional[str]], str]]
+
+    # subclass to be e.g. {'gcc': 'gnu', ...}
+    compiler_name_vendor_mapping: dict[str, str]
+
+    def __init__(self, sources, out, flags=None, run_linker=True, compiler=None, cwd='.',
+                 include_dirs=None, libraries=None, library_dirs=None, std=None, define=None,
+                 undef=None, strict_aliasing=None, preferred_vendor=None, linkline=None, **kwargs):
+        if isinstance(sources, str):
+            raise ValueError("Expected argument sources to be a list of strings.")
+        self.sources = list(sources)
+        self.out = out
+        self.flags = flags or []
+        if os.environ.get(self.environ_key_flags):
+            self.flags += os.environ[self.environ_key_flags].split()
+        self.cwd = cwd
+        if compiler:
+            self.compiler_name, self.compiler_binary = compiler
+        elif os.environ.get(self.environ_key_compiler):
+            self.compiler_binary = os.environ[self.environ_key_compiler]
+            for k, v in self.compiler_dict.items():
+                if k in self.compiler_binary:
+                    self.compiler_vendor = k
+                    self.compiler_name = v
+                    break
+            else:
+                self.compiler_vendor, self.compiler_name = list(self.compiler_dict.items())[0]
+                warnings.warn("failed to determine what kind of compiler %s is, assuming %s" %
+                              (self.compiler_binary, self.compiler_name))
+        else:
+            # Find a compiler
+            if preferred_vendor is None:
+                preferred_vendor = os.environ.get('SYMPY_COMPILER_VENDOR', None)
+            self.compiler_name, self.compiler_binary, self.compiler_vendor = self.find_compiler(preferred_vendor)
+            if self.compiler_binary is None:
+                raise ValueError("No compiler found (searched: {})".format(', '.join(self.compiler_dict.values())))
+        self.define = define or []
+        self.undef = undef or []
+        self.include_dirs = include_dirs or []
+        self.libraries = libraries or []
+        self.library_dirs = library_dirs or []
+        self.std = std or self.standards[0]
+        self.run_linker = run_linker
+        if self.run_linker:
+            # both gnu and intel compilers use '-c' for disabling linker
+            self.flags = list(filter(lambda x: x != '-c', self.flags))
+        else:
+            if '-c' not in self.flags:
+                self.flags.append('-c')
+
+        if self.std:
+            self.flags.append(self.std_formater[
+                self.compiler_name](self.std))
+
+        self.linkline = (linkline or []) + [lf for lf in map(
+            str.strip, os.environ.get(self.environ_key_ldflags, "").split()
+        ) if lf != ""]
+
+        if strict_aliasing is not None:
+            nsa_re = re.compile("no-strict-aliasing$")
+            sa_re = re.compile("strict-aliasing$")
+            if strict_aliasing is True:
+                if any(map(nsa_re.match, flags)):
+                    raise CompileError("Strict aliasing cannot be both enforced and disabled")
+                elif any(map(sa_re.match, flags)):
+                    pass  # already enforced
+                else:
+                    flags.append('-fstrict-aliasing')
+            elif strict_aliasing is False:
+                if any(map(nsa_re.match, flags)):
+                    pass  # already disabled
+                else:
+                    if any(map(sa_re.match, flags)):
+                        raise CompileError("Strict aliasing cannot be both enforced and disabled")
+                    else:
+                        flags.append('-fno-strict-aliasing')
+            else:
+                msg = "Expected argument strict_aliasing to be True/False, got {}"
+                raise ValueError(msg.format(strict_aliasing))
+
+    @classmethod
+    def find_compiler(cls, preferred_vendor=None):
+        """ Identify a suitable C/fortran/other compiler. """
+        candidates = list(cls.compiler_dict.keys())
+        if preferred_vendor:
+            if preferred_vendor in candidates:
+                candidates = [preferred_vendor]+candidates
+            else:
+                raise ValueError("Unknown vendor {}".format(preferred_vendor))
+        name, path = find_binary_of_command([cls.compiler_dict[x] for x in candidates])
+        return name, path, cls.compiler_name_vendor_mapping[name]
+
+    def cmd(self):
+        """ List of arguments (str) to be passed to e.g. ``subprocess.Popen``. """
+        cmd = (
+            [self.compiler_binary] +
+            self.flags +
+            ['-U'+x for x in self.undef] +
+            ['-D'+x for x in self.define] +
+            ['-I'+x for x in self.include_dirs] +
+            self.sources
+        )
+        if self.run_linker:
+            cmd += (['-L'+x for x in self.library_dirs] +
+                    ['-l'+x for x in self.libraries] +
+                    self.linkline)
+        counted = []
+        for envvar in re.findall(r'\$\{(\w+)\}', ' '.join(cmd)):
+            if os.getenv(envvar) is None:
+                if envvar not in counted:
+                    counted.append(envvar)
+                    msg = "Environment variable '{}' undefined.".format(envvar)
+                    raise CompileError(msg)
+        return cmd
+
+    def run(self):
+        self.flags = unique_list(self.flags)
+
+        # Append output flag and name to tail of flags
+        self.flags.extend(['-o', self.out])
+        env = os.environ.copy()
+        env['PWD'] = self.cwd
+
+        # NOTE: intel compilers seems to need shell=True
+        p = subprocess.Popen(' '.join(self.cmd()),
+                             shell=True,
+                             cwd=self.cwd,
+                             stdin=subprocess.PIPE,
+                             stdout=subprocess.PIPE,
+                             stderr=subprocess.STDOUT,
+                             env=env)
+        comm = p.communicate()
+        try:
+            self.cmd_outerr = comm[0].decode('utf-8')
+        except UnicodeDecodeError:
+            self.cmd_outerr = comm[0].decode('iso-8859-1')  # win32
+        self.cmd_returncode = p.returncode
+
+        # Error handling
+        if self.cmd_returncode != 0:
+            msg = "Error executing '{}' in {} (exited status {}):\n {}\n".format(
+                ' '.join(self.cmd()), self.cwd, str(self.cmd_returncode), self.cmd_outerr
+            )
+            raise CompileError(msg)
+
+        return self.cmd_outerr, self.cmd_returncode
+
+
+class CCompilerRunner(CompilerRunner):
+
+    environ_key_compiler = 'CC'
+    environ_key_flags = 'CFLAGS'
+
+    compiler_dict = OrderedDict([
+        ('gnu', 'gcc'),
+        ('intel', 'icc'),
+        ('llvm', 'clang'),
+    ])
+
+    standards = ('c89', 'c90', 'c99', 'c11')  # First is default
+
+    std_formater = {
+        'gcc': '-std={}'.format,
+        'icc': '-std={}'.format,
+        'clang': '-std={}'.format,
+    }
+
+    compiler_name_vendor_mapping = {
+        'gcc': 'gnu',
+        'icc': 'intel',
+        'clang': 'llvm'
+    }
+
+
+def _mk_flag_filter(cmplr_name):  # helper for class initialization
+    not_welcome = {'g++': ("Wimplicit-interface",)}  # "Wstrict-prototypes",)}
+    if cmplr_name in not_welcome:
+        def fltr(x):
+            for nw in not_welcome[cmplr_name]:
+                if nw in x:
+                    return False
+            return True
+    else:
+        def fltr(x):
+            return True
+    return fltr
+
+
+class CppCompilerRunner(CompilerRunner):
+
+    environ_key_compiler = 'CXX'
+    environ_key_flags = 'CXXFLAGS'
+
+    compiler_dict = OrderedDict([
+        ('gnu', 'g++'),
+        ('intel', 'icpc'),
+        ('llvm', 'clang++'),
+    ])
+
+    # First is the default, c++0x == c++11
+    standards = ('c++98', 'c++0x')
+
+    std_formater = {
+        'g++': '-std={}'.format,
+        'icpc': '-std={}'.format,
+        'clang++': '-std={}'.format,
+    }
+
+    compiler_name_vendor_mapping = {
+        'g++': 'gnu',
+        'icpc': 'intel',
+        'clang++': 'llvm'
+    }
+
+
+class FortranCompilerRunner(CompilerRunner):
+
+    environ_key_compiler = 'FC'
+    environ_key_flags = 'FFLAGS'
+
+    standards = (None, 'f77', 'f95', 'f2003', 'f2008')
+
+    std_formater = {
+        'gfortran': lambda x: '-std=gnu' if x is None else '-std=legacy' if x == 'f77' else '-std={}'.format(x),
+        'ifort': lambda x: '-stand f08' if x is None else '-stand f{}'.format(x[-2:]),  # f2008 => f08
+    }
+
+    compiler_dict = OrderedDict([
+        ('gnu', 'gfortran'),
+        ('intel', 'ifort'),
+    ])
+
+    compiler_name_vendor_mapping = {
+        'gfortran': 'gnu',
+        'ifort': 'intel',
+    }
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/_compilation/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/_compilation/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/_compilation/tests/test_compilation.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/_compilation/tests/test_compilation.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff7cf86644a9645665e62b49cfc4e7ea73b2c1ab
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/_compilation/tests/test_compilation.py
@@ -0,0 +1,104 @@
+import shutil
+import os
+import subprocess
+import tempfile
+from sympy.external import import_module
+from sympy.testing.pytest import skip, skip_under_pyodide
+
+from sympy.utilities._compilation.compilation import compile_link_import_py_ext, compile_link_import_strings, compile_sources, get_abspath
+
+numpy = import_module('numpy')
+cython = import_module('cython')
+
+_sources1 = [
+    ('sigmoid.c', r"""
+#include 
+
+void sigmoid(int n, const double * const restrict in,
+             double * const restrict out, double lim){
+    for (int i=0; i 0:
+        if not os.path.exists(parent):
+            make_dirs(parent)
+
+    if not os.path.exists(path):
+        os.mkdir(path, 0o777)
+    else:
+        assert os.path.isdir(path)
+
+def missing_or_other_newer(path, other_path, cwd=None):
+    """
+    Investigate if path is non-existent or older than provided reference
+    path.
+
+    Parameters
+    ==========
+    path: string
+        path to path which might be missing or too old
+    other_path: string
+        reference path
+    cwd: string
+        working directory (root of relative paths)
+
+    Returns
+    =======
+    True if path is older or missing.
+    """
+    cwd = cwd or '.'
+    path = get_abspath(path, cwd=cwd)
+    other_path = get_abspath(other_path, cwd=cwd)
+    if not os.path.exists(path):
+        return True
+    if os.path.getmtime(other_path) - 1e-6 >= os.path.getmtime(path):
+        # 1e-6 is needed because http://stackoverflow.com/questions/17086426/
+        return True
+    return False
+
+def copy(src, dst, only_update=False, copystat=True, cwd=None,
+         dest_is_dir=False, create_dest_dirs=False):
+    """ Variation of ``shutil.copy`` with extra options.
+
+    Parameters
+    ==========
+
+    src : str
+        Path to source file.
+    dst : str
+        Path to destination.
+    only_update : bool
+        Only copy if source is newer than destination
+        (returns None if it was newer), default: ``False``.
+    copystat : bool
+        See ``shutil.copystat``. default: ``True``.
+    cwd : str
+        Path to working directory (root of relative paths).
+    dest_is_dir : bool
+        Ensures that dst is treated as a directory. default: ``False``
+    create_dest_dirs : bool
+        Creates directories if needed.
+
+    Returns
+    =======
+
+    Path to the copied file.
+
+    """
+    if cwd:  # Handle working directory
+        if not os.path.isabs(src):
+            src = os.path.join(cwd, src)
+        if not os.path.isabs(dst):
+            dst = os.path.join(cwd, dst)
+
+    if not os.path.exists(src):  # Make sure source file exists
+        raise FileNotFoundError("Source: `{}` does not exist".format(src))
+
+    # We accept both (re)naming destination file _or_
+    # passing a (possible non-existent) destination directory
+    if dest_is_dir:
+        if not dst[-1] == '/':
+            dst = dst+'/'
+    else:
+        if os.path.exists(dst) and os.path.isdir(dst):
+            dest_is_dir = True
+
+    if dest_is_dir:
+        dest_dir = dst
+        dest_fname = os.path.basename(src)
+        dst = os.path.join(dest_dir, dest_fname)
+    else:
+        dest_dir = os.path.dirname(dst)
+
+    if not os.path.exists(dest_dir):
+        if create_dest_dirs:
+            make_dirs(dest_dir)
+        else:
+            raise FileNotFoundError("You must create directory first.")
+
+    if only_update:
+        if not missing_or_other_newer(dst, src):
+            return
+
+    if os.path.islink(dst):
+        dst = os.path.abspath(os.path.realpath(dst), cwd=cwd)
+
+    shutil.copy(src, dst)
+    if copystat:
+        shutil.copystat(src, dst)
+
+    return dst
+
+Glob = namedtuple('Glob', 'pathname')
+ArbitraryDepthGlob = namedtuple('ArbitraryDepthGlob', 'filename')
+
+def glob_at_depth(filename_glob, cwd=None):
+    if cwd is not None:
+        cwd = '.'
+    globbed = []
+    for root, dirs, filenames in os.walk(cwd):
+        for fn in filenames:
+            # This is not tested:
+            if fnmatch.fnmatch(fn, filename_glob):
+                globbed.append(os.path.join(root, fn))
+    return globbed
+
+def sha256_of_file(path, nblocks=128):
+    """ Computes the SHA256 hash of a file.
+
+    Parameters
+    ==========
+
+    path : string
+        Path to file to compute hash of.
+    nblocks : int
+        Number of blocks to read per iteration.
+
+    Returns
+    =======
+
+    hashlib sha256 hash object. Use ``.digest()`` or ``.hexdigest()``
+    on returned object to get binary or hex encoded string.
+    """
+    sh = sha256()
+    with open(path, 'rb') as f:
+        for chunk in iter(lambda: f.read(nblocks*sh.block_size), b''):
+            sh.update(chunk)
+    return sh
+
+
+def sha256_of_string(string):
+    """ Computes the SHA256 hash of a string. """
+    sh = sha256()
+    sh.update(string)
+    return sh
+
+
+def pyx_is_cplus(path):
+    """
+    Inspect a Cython source file (.pyx) and look for comment line like:
+
+    # distutils: language = c++
+
+    Returns True if such a file is present in the file, else False.
+    """
+    with open(path) as fh:
+        for line in fh:
+            if line.startswith('#') and '=' in line:
+                splitted = line.split('=')
+                if len(splitted) != 2:
+                    continue
+                lhs, rhs = splitted
+                if lhs.strip().split()[-1].lower() == 'language' and \
+                       rhs.strip().split()[0].lower() == 'c++':
+                            return True
+    return False
+
+def import_module_from_file(filename, only_if_newer_than=None):
+    """ Imports Python extension (from shared object file)
+
+    Provide a list of paths in `only_if_newer_than` to check
+    timestamps of dependencies. import_ raises an ImportError
+    if any is newer.
+
+    Word of warning: The OS may cache shared objects which makes
+    reimporting same path of an shared object file very problematic.
+
+    It will not detect the new time stamp, nor new checksum, but will
+    instead silently use old module. Use unique names for this reason.
+
+    Parameters
+    ==========
+
+    filename : str
+        Path to shared object.
+    only_if_newer_than : iterable of strings
+        Paths to dependencies of the shared object.
+
+    Raises
+    ======
+
+    ``ImportError`` if any of the files specified in ``only_if_newer_than`` are newer
+    than the file given by filename.
+    """
+    path, name = os.path.split(filename)
+    name, ext = os.path.splitext(name)
+    name = name.split('.')[0]
+    if sys.version_info[0] == 2:
+        from imp import find_module, load_module
+        fobj, filename, data = find_module(name, [path])
+        if only_if_newer_than:
+            for dep in only_if_newer_than:
+                if os.path.getmtime(filename) < os.path.getmtime(dep):
+                    raise ImportError("{} is newer than {}".format(dep, filename))
+        mod = load_module(name, fobj, filename, data)
+    else:
+        import importlib.util
+        spec = importlib.util.spec_from_file_location(name, filename)
+        if spec is None:
+            raise ImportError("Failed to import: '%s'" % filename)
+        mod = importlib.util.module_from_spec(spec)
+        spec.loader.exec_module(mod)
+    return mod
+
+
+def find_binary_of_command(candidates):
+    """ Finds binary first matching name among candidates.
+
+    Calls ``which`` from shutils for provided candidates and returns
+    first hit.
+
+    Parameters
+    ==========
+
+    candidates : iterable of str
+        Names of candidate commands
+
+    Raises
+    ======
+
+    CompilerNotFoundError if no candidates match.
+    """
+    from shutil import which
+    for c in candidates:
+        binary_path = which(c)
+        if c and binary_path:
+            return c, binary_path
+
+    raise CompilerNotFoundError('No binary located for candidates: {}'.format(candidates))
+
+
+def unique_list(l):
+    """ Uniquify a list (skip duplicate items). """
+    result = []
+    for x in l:
+        if x not in result:
+            result.append(x)
+    return result
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/autowrap.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/autowrap.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6c33b2f0f72f89b5680f910929618a821e924c3
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/autowrap.py
@@ -0,0 +1,1178 @@
+"""Module for compiling codegen output, and wrap the binary for use in
+python.
+
+.. note:: To use the autowrap module it must first be imported
+
+   >>> from sympy.utilities.autowrap import autowrap
+
+This module provides a common interface for different external backends, such
+as f2py, fwrap, Cython, SWIG(?) etc. (Currently only f2py and Cython are
+implemented) The goal is to provide access to compiled binaries of acceptable
+performance with a one-button user interface, e.g.,
+
+    >>> from sympy.abc import x,y
+    >>> expr = (x - y)**25
+    >>> flat = expr.expand()
+    >>> binary_callable = autowrap(flat)
+    >>> binary_callable(2, 3)
+    -1.0
+
+Although a SymPy user might primarily be interested in working with
+mathematical expressions and not in the details of wrapping tools
+needed to evaluate such expressions efficiently in numerical form,
+the user cannot do so without some understanding of the
+limits in the target language. For example, the expanded expression
+contains large coefficients which result in loss of precision when
+computing the expression:
+
+    >>> binary_callable(3, 2)
+    0.0
+    >>> binary_callable(4, 5), binary_callable(5, 4)
+    (-22925376.0, 25165824.0)
+
+Wrapping the unexpanded expression gives the expected behavior:
+
+    >>> e = autowrap(expr)
+    >>> e(4, 5), e(5, 4)
+    (-1.0, 1.0)
+
+The callable returned from autowrap() is a binary Python function, not a
+SymPy object.  If it is desired to use the compiled function in symbolic
+expressions, it is better to use binary_function() which returns a SymPy
+Function object.  The binary callable is attached as the _imp_ attribute and
+invoked when a numerical evaluation is requested with evalf(), or with
+lambdify().
+
+    >>> from sympy.utilities.autowrap import binary_function
+    >>> f = binary_function('f', expr)
+    >>> 2*f(x, y) + y
+    y + 2*f(x, y)
+    >>> (2*f(x, y) + y).evalf(2, subs={x: 1, y:2})
+    0.e-110
+
+When is this useful?
+
+    1) For computations on large arrays, Python iterations may be too slow,
+       and depending on the mathematical expression, it may be difficult to
+       exploit the advanced index operations provided by NumPy.
+
+    2) For *really* long expressions that will be called repeatedly, the
+       compiled binary should be significantly faster than SymPy's .evalf()
+
+    3) If you are generating code with the codegen utility in order to use
+       it in another project, the automatic Python wrappers let you test the
+       binaries immediately from within SymPy.
+
+    4) To create customized ufuncs for use with numpy arrays.
+       See *ufuncify*.
+
+When is this module NOT the best approach?
+
+    1) If you are really concerned about speed or memory optimizations,
+       you will probably get better results by working directly with the
+       wrapper tools and the low level code.  However, the files generated
+       by this utility may provide a useful starting point and reference
+       code. Temporary files will be left intact if you supply the keyword
+       tempdir="path/to/files/".
+
+    2) If the array computation can be handled easily by numpy, and you
+       do not need the binaries for another project.
+
+"""
+
+import sys
+import os
+import shutil
+import tempfile
+from pathlib import Path
+from subprocess import STDOUT, CalledProcessError, check_output
+from string import Template
+from warnings import warn
+
+from sympy.core.cache import cacheit
+from sympy.core.function import Lambda
+from sympy.core.relational import Eq
+from sympy.core.symbol import Dummy, Symbol
+from sympy.tensor.indexed import Idx, IndexedBase
+from sympy.utilities.codegen import (make_routine, get_code_generator,
+                                     OutputArgument, InOutArgument,
+                                     InputArgument, CodeGenArgumentListError,
+                                     Result, ResultBase, C99CodeGen)
+from sympy.utilities.iterables import iterable
+from sympy.utilities.lambdify import implemented_function
+from sympy.utilities.decorator import doctest_depends_on
+
+_doctest_depends_on = {'exe': ('f2py', 'gfortran', 'gcc'),
+                       'modules': ('numpy',)}
+
+
+class CodeWrapError(Exception):
+    pass
+
+
+class CodeWrapper:
+    """Base Class for code wrappers"""
+    _filename = "wrapped_code"
+    _module_basename = "wrapper_module"
+    _module_counter = 0
+
+    @property
+    def filename(self):
+        return "%s_%s" % (self._filename, CodeWrapper._module_counter)
+
+    @property
+    def module_name(self):
+        return "%s_%s" % (self._module_basename, CodeWrapper._module_counter)
+
+    def __init__(self, generator, filepath=None, flags=[], verbose=False):
+        """
+        generator -- the code generator to use
+        """
+        self.generator = generator
+        self.filepath = filepath
+        self.flags = flags
+        self.quiet = not verbose
+
+    @property
+    def include_header(self):
+        return bool(self.filepath)
+
+    @property
+    def include_empty(self):
+        return bool(self.filepath)
+
+    def _generate_code(self, main_routine, routines):
+        routines.append(main_routine)
+        self.generator.write(
+            routines, self.filename, True, self.include_header,
+            self.include_empty)
+
+    def wrap_code(self, routine, helpers=None):
+        helpers = helpers or []
+        if self.filepath:
+            workdir = os.path.abspath(self.filepath)
+        else:
+            workdir = tempfile.mkdtemp("_sympy_compile")
+        if not os.access(workdir, os.F_OK):
+            os.mkdir(workdir)
+        oldwork = os.getcwd()
+        os.chdir(workdir)
+        try:
+            sys.path.append(workdir)
+            self._generate_code(routine, helpers)
+            self._prepare_files(routine)
+            self._process_files(routine)
+            mod = __import__(self.module_name)
+        finally:
+            sys.path.remove(workdir)
+            CodeWrapper._module_counter += 1
+            os.chdir(oldwork)
+            if not self.filepath:
+                try:
+                    shutil.rmtree(workdir)
+                except OSError:
+                    # Could be some issues on Windows
+                    pass
+
+        return self._get_wrapped_function(mod, routine.name)
+
+    def _process_files(self, routine):
+        command = self.command
+        command.extend(self.flags)
+        try:
+            retoutput = check_output(command, stderr=STDOUT)
+        except CalledProcessError as e:
+            raise CodeWrapError(
+                "Error while executing command: %s. Command output is:\n%s" % (
+                    " ".join(command), e.output.decode('utf-8')))
+        if not self.quiet:
+            print(retoutput)
+
+
+class DummyWrapper(CodeWrapper):
+    """Class used for testing independent of backends """
+
+    template = """# dummy module for testing of SymPy
+def %(name)s():
+    return "%(expr)s"
+%(name)s.args = "%(args)s"
+%(name)s.returns = "%(retvals)s"
+"""
+
+    def _prepare_files(self, routine):
+        return
+
+    def _generate_code(self, routine, helpers):
+        with open('%s.py' % self.module_name, 'w') as f:
+            printed = ", ".join(
+                [str(res.expr) for res in routine.result_variables])
+            # convert OutputArguments to return value like f2py
+            args = filter(lambda x: not isinstance(
+                x, OutputArgument), routine.arguments)
+            retvals = []
+            for val in routine.result_variables:
+                if isinstance(val, Result):
+                    retvals.append('nameless')
+                else:
+                    retvals.append(val.result_var)
+
+            print(DummyWrapper.template % {
+                'name': routine.name,
+                'expr': printed,
+                'args': ", ".join([str(a.name) for a in args]),
+                'retvals': ", ".join([str(val) for val in retvals])
+            }, end="", file=f)
+
+    def _process_files(self, routine):
+        return
+
+    @classmethod
+    def _get_wrapped_function(cls, mod, name):
+        return getattr(mod, name)
+
+
+class CythonCodeWrapper(CodeWrapper):
+    """Wrapper that uses Cython"""
+
+    setup_template = """\
+from setuptools import setup
+from setuptools import Extension
+from Cython.Build import cythonize
+cy_opts = {cythonize_options}
+{np_import}
+ext_mods = [Extension(
+    {ext_args},
+    include_dirs={include_dirs},
+    library_dirs={library_dirs},
+    libraries={libraries},
+    extra_compile_args={extra_compile_args},
+    extra_link_args={extra_link_args}
+)]
+setup(ext_modules=cythonize(ext_mods, **cy_opts))
+"""
+
+    _cythonize_options = {'compiler_directives':{'language_level' : "3"}}
+
+    pyx_imports = (
+        "import numpy as np\n"
+        "cimport numpy as np\n\n")
+
+    pyx_header = (
+        "cdef extern from '{header_file}.h':\n"
+        "    {prototype}\n\n")
+
+    pyx_func = (
+        "def {name}_c({arg_string}):\n"
+        "\n"
+        "{declarations}"
+        "{body}")
+
+    std_compile_flag = '-std=c99'
+
+    def __init__(self, *args, **kwargs):
+        """Instantiates a Cython code wrapper.
+
+        The following optional parameters get passed to ``setuptools.Extension``
+        for building the Python extension module. Read its documentation to
+        learn more.
+
+        Parameters
+        ==========
+        include_dirs : [list of strings]
+            A list of directories to search for C/C++ header files (in Unix
+            form for portability).
+        library_dirs : [list of strings]
+            A list of directories to search for C/C++ libraries at link time.
+        libraries : [list of strings]
+            A list of library names (not filenames or paths) to link against.
+        extra_compile_args : [list of strings]
+            Any extra platform- and compiler-specific information to use when
+            compiling the source files in 'sources'.  For platforms and
+            compilers where "command line" makes sense, this is typically a
+            list of command-line arguments, but for other platforms it could be
+            anything. Note that the attribute ``std_compile_flag`` will be
+            appended to this list.
+        extra_link_args : [list of strings]
+            Any extra platform- and compiler-specific information to use when
+            linking object files together to create the extension (or to create
+            a new static Python interpreter). Similar interpretation as for
+            'extra_compile_args'.
+        cythonize_options : [dictionary]
+            Keyword arguments passed on to cythonize.
+
+        """
+
+        self._include_dirs = kwargs.pop('include_dirs', [])
+        self._library_dirs = kwargs.pop('library_dirs', [])
+        self._libraries = kwargs.pop('libraries', [])
+        self._extra_compile_args = kwargs.pop('extra_compile_args', [])
+        self._extra_compile_args.append(self.std_compile_flag)
+        self._extra_link_args = kwargs.pop('extra_link_args', [])
+        self._cythonize_options = kwargs.pop('cythonize_options', self._cythonize_options)
+
+        self._need_numpy = False
+
+        super().__init__(*args, **kwargs)
+
+    @property
+    def command(self):
+        command = [sys.executable, "setup.py", "build_ext", "--inplace"]
+        return command
+
+    def _prepare_files(self, routine, build_dir=os.curdir):
+        # NOTE : build_dir is used for testing purposes.
+        pyxfilename = self.module_name + '.pyx'
+        codefilename = "%s.%s" % (self.filename, self.generator.code_extension)
+
+        # pyx
+        with open(os.path.join(build_dir, pyxfilename), 'w') as f:
+            self.dump_pyx([routine], f, self.filename)
+
+        # setup.py
+        ext_args = [repr(self.module_name), repr([pyxfilename, codefilename])]
+        if self._need_numpy:
+            np_import = 'import numpy as np\n'
+            self._include_dirs.append('np.get_include()')
+        else:
+            np_import = ''
+
+        includes = str(self._include_dirs).replace("'np.get_include()'",
+                                                    'np.get_include()')
+        code = self.setup_template.format(
+                ext_args=", ".join(ext_args),
+                np_import=np_import,
+                include_dirs=includes,
+                library_dirs=self._library_dirs,
+                libraries=self._libraries,
+                extra_compile_args=self._extra_compile_args,
+                extra_link_args=self._extra_link_args,
+                cythonize_options=self._cythonize_options)
+        Path(os.path.join(build_dir, 'setup.py')).write_text(code)
+
+    @classmethod
+    def _get_wrapped_function(cls, mod, name):
+        return getattr(mod, name + '_c')
+
+    def dump_pyx(self, routines, f, prefix):
+        """Write a Cython file with Python wrappers
+
+        This file contains all the definitions of the routines in c code and
+        refers to the header file.
+
+        Arguments
+        ---------
+        routines
+            List of Routine instances
+        f
+            File-like object to write the file to
+        prefix
+            The filename prefix, used to refer to the proper header file.
+            Only the basename of the prefix is used.
+        """
+        headers = []
+        functions = []
+        for routine in routines:
+            prototype = self.generator.get_prototype(routine)
+
+            # C Function Header Import
+            headers.append(self.pyx_header.format(header_file=prefix,
+                                                  prototype=prototype))
+
+            # Partition the C function arguments into categories
+            py_rets, py_args, py_loc, py_inf = self._partition_args(routine.arguments)
+
+            # Function prototype
+            name = routine.name
+            arg_string = ", ".join(self._prototype_arg(arg) for arg in py_args)
+
+            # Local Declarations
+            local_decs = []
+            for arg, val in py_inf.items():
+                proto = self._prototype_arg(arg)
+                mat, ind = [self._string_var(v) for v in val]
+                local_decs.append("    cdef {} = {}.shape[{}]".format(proto, mat, ind))
+            local_decs.extend(["    cdef {}".format(self._declare_arg(a)) for a in py_loc])
+            declarations = "\n".join(local_decs)
+            if declarations:
+                declarations = declarations + "\n"
+
+            # Function Body
+            args_c = ", ".join([self._call_arg(a) for a in routine.arguments])
+            rets = ", ".join([self._string_var(r.name) for r in py_rets])
+            if routine.results:
+                body = '    return %s(%s)' % (routine.name, args_c)
+                if rets:
+                    body = body + ', ' + rets
+            else:
+                body = '    %s(%s)\n' % (routine.name, args_c)
+                body = body + '    return ' + rets
+
+            functions.append(self.pyx_func.format(name=name, arg_string=arg_string,
+                    declarations=declarations, body=body))
+
+        # Write text to file
+        if self._need_numpy:
+            # Only import numpy if required
+            f.write(self.pyx_imports)
+        f.write('\n'.join(headers))
+        f.write('\n'.join(functions))
+
+    def _partition_args(self, args):
+        """Group function arguments into categories."""
+        py_args = []
+        py_returns = []
+        py_locals = []
+        py_inferred = {}
+        for arg in args:
+            if isinstance(arg, OutputArgument):
+                py_returns.append(arg)
+                py_locals.append(arg)
+            elif isinstance(arg, InOutArgument):
+                py_returns.append(arg)
+                py_args.append(arg)
+            else:
+                py_args.append(arg)
+        # Find arguments that are array dimensions. These can be inferred
+        # locally in the Cython code.
+            if isinstance(arg, (InputArgument, InOutArgument)) and arg.dimensions:
+                dims = [d[1] + 1 for d in arg.dimensions]
+                sym_dims = [(i, d) for (i, d) in enumerate(dims) if
+                            isinstance(d, Symbol)]
+                for (i, d) in sym_dims:
+                    py_inferred[d] = (arg.name, i)
+        for arg in args:
+            if arg.name in py_inferred:
+                py_inferred[arg] = py_inferred.pop(arg.name)
+        # Filter inferred arguments from py_args
+        py_args = [a for a in py_args if a not in py_inferred]
+        return py_returns, py_args, py_locals, py_inferred
+
+    def _prototype_arg(self, arg):
+        mat_dec = "np.ndarray[{mtype}, ndim={ndim}] {name}"
+        np_types = {'double': 'np.double_t',
+                    'int': 'np.int_t'}
+        t = arg.get_datatype('c')
+        if arg.dimensions:
+            self._need_numpy = True
+            ndim = len(arg.dimensions)
+            mtype = np_types[t]
+            return mat_dec.format(mtype=mtype, ndim=ndim, name=self._string_var(arg.name))
+        else:
+            return "%s %s" % (t, self._string_var(arg.name))
+
+    def _declare_arg(self, arg):
+        proto = self._prototype_arg(arg)
+        if arg.dimensions:
+            shape = '(' + ','.join(self._string_var(i[1] + 1) for i in arg.dimensions) + ')'
+            return proto + " = np.empty({shape})".format(shape=shape)
+        else:
+            return proto + " = 0"
+
+    def _call_arg(self, arg):
+        if arg.dimensions:
+            t = arg.get_datatype('c')
+            return "<{}*> {}.data".format(t, self._string_var(arg.name))
+        elif isinstance(arg, ResultBase):
+            return "&{}".format(self._string_var(arg.name))
+        else:
+            return self._string_var(arg.name)
+
+    def _string_var(self, var):
+        printer = self.generator.printer.doprint
+        return printer(var)
+
+
+class F2PyCodeWrapper(CodeWrapper):
+    """Wrapper that uses f2py"""
+
+    def __init__(self, *args, **kwargs):
+
+        ext_keys = ['include_dirs', 'library_dirs', 'libraries',
+                    'extra_compile_args', 'extra_link_args']
+        msg = ('The compilation option kwarg {} is not supported with the f2py '
+               'backend.')
+
+        for k in ext_keys:
+            if k in kwargs.keys():
+                warn(msg.format(k))
+            kwargs.pop(k, None)
+
+        super().__init__(*args, **kwargs)
+
+    @property
+    def command(self):
+        filename = self.filename + '.' + self.generator.code_extension
+        args = ['-c', '-m', self.module_name, filename]
+        command = [sys.executable, "-c", "import numpy.f2py as f2py2e;f2py2e.main()"]+args
+        return command
+
+    def _prepare_files(self, routine):
+        pass
+
+    @classmethod
+    def _get_wrapped_function(cls, mod, name):
+        return getattr(mod, name)
+
+
+# Here we define a lookup of backends -> tuples of languages. For now, each
+# tuple is of length 1, but if a backend supports more than one language,
+# the most preferable language is listed first.
+_lang_lookup = {'CYTHON': ('C99', 'C89', 'C'),
+                'F2PY': ('F95',),
+                'NUMPY': ('C99', 'C89', 'C'),
+                'DUMMY': ('F95',)}     # Dummy here just for testing
+
+
+def _infer_language(backend):
+    """For a given backend, return the top choice of language"""
+    langs = _lang_lookup.get(backend.upper(), False)
+    if not langs:
+        raise ValueError("Unrecognized backend: " + backend)
+    return langs[0]
+
+
+def _validate_backend_language(backend, language):
+    """Throws error if backend and language are incompatible"""
+    langs = _lang_lookup.get(backend.upper(), False)
+    if not langs:
+        raise ValueError("Unrecognized backend: " + backend)
+    if language.upper() not in langs:
+        raise ValueError(("Backend {} and language {} are "
+                          "incompatible").format(backend, language))
+
+
+@cacheit
+@doctest_depends_on(exe=('f2py', 'gfortran'), modules=('numpy',))
+def autowrap(expr, language=None, backend='f2py', tempdir=None, args=None,
+             flags=None, verbose=False, helpers=None, code_gen=None, **kwargs):
+    """Generates Python callable binaries based on the math expression.
+
+    Parameters
+    ==========
+
+    expr
+        The SymPy expression that should be wrapped as a binary routine.
+    language : string, optional
+        If supplied, (options: 'C' or 'F95'), specifies the language of the
+        generated code. If ``None`` [default], the language is inferred based
+        upon the specified backend.
+    backend : string, optional
+        Backend used to wrap the generated code. Either 'f2py' [default],
+        or 'cython'.
+    tempdir : string, optional
+        Path to directory for temporary files. If this argument is supplied,
+        the generated code and the wrapper input files are left intact in the
+        specified path.
+    args : iterable, optional
+        An ordered iterable of symbols. Specifies the argument sequence for the
+        function.
+    flags : iterable, optional
+        Additional option flags that will be passed to the backend.
+    verbose : bool, optional
+        If True, autowrap will not mute the command line backends. This can be
+        helpful for debugging.
+    helpers : 3-tuple or iterable of 3-tuples, optional
+        Used to define auxiliary functions needed for the main expression.
+        Each tuple should be of the form (name, expr, args) where:
+
+        - name : str, the function name
+        - expr : sympy expression, the function
+        - args : iterable, the function arguments (can be any iterable of symbols)
+
+    code_gen : CodeGen instance
+        An instance of a CodeGen subclass. Overrides ``language``.
+    include_dirs : [string]
+        A list of directories to search for C/C++ header files (in Unix form
+        for portability).
+    library_dirs : [string]
+        A list of directories to search for C/C++ libraries at link time.
+    libraries : [string]
+        A list of library names (not filenames or paths) to link against.
+    extra_compile_args : [string]
+        Any extra platform- and compiler-specific information to use when
+        compiling the source files in 'sources'.  For platforms and compilers
+        where "command line" makes sense, this is typically a list of
+        command-line arguments, but for other platforms it could be anything.
+    extra_link_args : [string]
+        Any extra platform- and compiler-specific information to use when
+        linking object files together to create the extension (or to create a
+        new static Python interpreter).  Similar interpretation as for
+        'extra_compile_args'.
+
+    Examples
+    ========
+
+    Basic usage:
+
+    >>> from sympy.abc import x, y, z
+    >>> from sympy.utilities.autowrap import autowrap
+    >>> expr = ((x - y + z)**(13)).expand()
+    >>> binary_func = autowrap(expr)
+    >>> binary_func(1, 4, 2)
+    -1.0
+
+    Using helper functions:
+
+    >>> from sympy.abc import x, t
+    >>> from sympy import Function
+    >>> helper_func = Function('helper_func')  # Define symbolic function
+    >>> expr = 3*x + helper_func(t)  # Main expression using helper function
+    >>> # Define helper_func(x) = 4*x using f2py backend
+    >>> binary_func = autowrap(expr, args=[x, t],
+    ...                       helpers=('helper_func', 4*x, [x]))
+    >>> binary_func(2, 5)  # 3*2 + helper_func(5) = 6 + 20
+    26.0
+    >>> # Same example using cython backend
+    >>> binary_func = autowrap(expr, args=[x, t], backend='cython',
+    ...                       helpers=[('helper_func', 4*x, [x])])
+    >>> binary_func(2, 5)  # 3*2 + helper_func(5) = 6 + 20
+    26.0
+
+    Type handling example:
+
+    >>> import numpy as np
+    >>> expr = x + y
+    >>> f_cython = autowrap(expr, backend='cython')
+    >>> f_cython(1, 2)  # doctest: +ELLIPSIS
+    Traceback (most recent call last):
+      ...
+    TypeError: Argument '_x' has incorrect type (expected numpy.ndarray, got int)
+    >>> f_cython(np.array([1.0]), np.array([2.0]))
+    array([ 3.])
+
+    """
+    if language:
+        if not isinstance(language, type):
+            _validate_backend_language(backend, language)
+    else:
+        language = _infer_language(backend)
+
+    # two cases 1) helpers is an iterable of 3-tuples and 2) helpers is a
+    # 3-tuple
+    if iterable(helpers) and len(helpers) != 0 and iterable(helpers[0]):
+        helpers = helpers if helpers else ()
+    else:
+        helpers = [helpers] if helpers else ()
+    args = list(args) if iterable(args, exclude=set) else args
+
+    if code_gen is None:
+        code_gen = get_code_generator(language, "autowrap")
+
+    CodeWrapperClass = {
+        'F2PY': F2PyCodeWrapper,
+        'CYTHON': CythonCodeWrapper,
+        'DUMMY': DummyWrapper
+    }[backend.upper()]
+    code_wrapper = CodeWrapperClass(code_gen, tempdir, flags if flags else (),
+                                    verbose, **kwargs)
+
+    helps = []
+    for name_h, expr_h, args_h in helpers:
+        helps.append(code_gen.routine(name_h, expr_h, args_h))
+
+    for name_h, expr_h, args_h in helpers:
+        if expr.has(expr_h):
+            name_h = binary_function(name_h, expr_h, backend='dummy')
+            expr = expr.subs(expr_h, name_h(*args_h))
+    try:
+        routine = code_gen.routine('autofunc', expr, args)
+    except CodeGenArgumentListError as e:
+        # if all missing arguments are for pure output, we simply attach them
+        # at the end and try again, because the wrappers will silently convert
+        # them to return values anyway.
+        new_args = []
+        for missing in e.missing_args:
+            if not isinstance(missing, OutputArgument):
+                raise
+            new_args.append(missing.name)
+        routine = code_gen.routine('autofunc', expr, args + new_args)
+
+    return code_wrapper.wrap_code(routine, helpers=helps)
+
+
+@doctest_depends_on(exe=('f2py', 'gfortran'), modules=('numpy',))
+def binary_function(symfunc, expr, **kwargs):
+    """Returns a SymPy function with expr as binary implementation
+
+    This is a convenience function that automates the steps needed to
+    autowrap the SymPy expression and attaching it to a Function object
+    with implemented_function().
+
+    Parameters
+    ==========
+
+    symfunc : SymPy Function
+        The function to bind the callable to.
+    expr : SymPy Expression
+        The expression used to generate the function.
+    kwargs : dict
+        Any kwargs accepted by autowrap.
+
+    Examples
+    ========
+
+    >>> from sympy.abc import x, y
+    >>> from sympy.utilities.autowrap import binary_function
+    >>> expr = ((x - y)**(25)).expand()
+    >>> f = binary_function('f', expr)
+    >>> type(f)
+    
+    >>> 2*f(x, y)
+    2*f(x, y)
+    >>> f(x, y).evalf(2, subs={x: 1, y: 2})
+    -1.0
+
+    """
+    binary = autowrap(expr, **kwargs)
+    return implemented_function(symfunc, binary)
+
+#################################################################
+#                           UFUNCIFY                            #
+#################################################################
+
+_ufunc_top = Template("""\
+#include "Python.h"
+#include "math.h"
+#include "numpy/ndarraytypes.h"
+#include "numpy/ufuncobject.h"
+#include "numpy/halffloat.h"
+#include ${include_file}
+
+static PyMethodDef ${module}Methods[] = {
+        {NULL, NULL, 0, NULL}
+};""")
+
+_ufunc_outcalls = Template("*((double *)out${outnum}) = ${funcname}(${call_args});")
+
+_ufunc_body = Template("""\
+#ifdef NPY_1_19_API_VERSION
+static void ${funcname}_ufunc(char **args, const npy_intp *dimensions, const npy_intp* steps, void* data)
+#else
+static void ${funcname}_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data)
+#endif
+{
+    npy_intp i;
+    npy_intp n = dimensions[0];
+    ${declare_args}
+    ${declare_steps}
+    for (i = 0; i < n; i++) {
+        ${outcalls}
+        ${step_increments}
+    }
+}
+PyUFuncGenericFunction ${funcname}_funcs[1] = {&${funcname}_ufunc};
+static char ${funcname}_types[${n_types}] = ${types}
+static void *${funcname}_data[1] = {NULL};""")
+
+_ufunc_bottom = Template("""\
+#if PY_VERSION_HEX >= 0x03000000
+static struct PyModuleDef moduledef = {
+    PyModuleDef_HEAD_INIT,
+    "${module}",
+    NULL,
+    -1,
+    ${module}Methods,
+    NULL,
+    NULL,
+    NULL,
+    NULL
+};
+
+PyMODINIT_FUNC PyInit_${module}(void)
+{
+    PyObject *m, *d;
+    ${function_creation}
+    m = PyModule_Create(&moduledef);
+    if (!m) {
+        return NULL;
+    }
+    import_array();
+    import_umath();
+    d = PyModule_GetDict(m);
+    ${ufunc_init}
+    return m;
+}
+#else
+PyMODINIT_FUNC init${module}(void)
+{
+    PyObject *m, *d;
+    ${function_creation}
+    m = Py_InitModule("${module}", ${module}Methods);
+    if (m == NULL) {
+        return;
+    }
+    import_array();
+    import_umath();
+    d = PyModule_GetDict(m);
+    ${ufunc_init}
+}
+#endif\
+""")
+
+_ufunc_init_form = Template("""\
+ufunc${ind} = PyUFunc_FromFuncAndData(${funcname}_funcs, ${funcname}_data, ${funcname}_types, 1, ${n_in}, ${n_out},
+            PyUFunc_None, "${module}", ${docstring}, 0);
+    PyDict_SetItemString(d, "${funcname}", ufunc${ind});
+    Py_DECREF(ufunc${ind});""")
+
+_ufunc_setup = Template("""\
+from setuptools.extension import Extension
+from setuptools import setup
+
+from numpy import get_include
+
+if __name__ == "__main__":
+    setup(ext_modules=[
+        Extension('${module}',
+                  sources=['${module}.c', '${filename}.c'],
+                  include_dirs=[get_include()])])
+""")
+
+
+class UfuncifyCodeWrapper(CodeWrapper):
+    """Wrapper for Ufuncify"""
+
+    def __init__(self, *args, **kwargs):
+
+        ext_keys = ['include_dirs', 'library_dirs', 'libraries',
+                    'extra_compile_args', 'extra_link_args']
+        msg = ('The compilation option kwarg {} is not supported with the numpy'
+               ' backend.')
+
+        for k in ext_keys:
+            if k in kwargs.keys():
+                warn(msg.format(k))
+            kwargs.pop(k, None)
+
+        super().__init__(*args, **kwargs)
+
+    @property
+    def command(self):
+        command = [sys.executable, "setup.py", "build_ext", "--inplace"]
+        return command
+
+    def wrap_code(self, routines, helpers=None):
+        # This routine overrides CodeWrapper because we can't assume funcname == routines[0].name
+        # Therefore we have to break the CodeWrapper private API.
+        # There isn't an obvious way to extend multi-expr support to
+        # the other autowrap backends, so we limit this change to ufuncify.
+        helpers = helpers if helpers is not None else []
+        # We just need a consistent name
+        funcname = 'wrapped_' + str(id(routines) + id(helpers))
+
+        workdir = self.filepath or tempfile.mkdtemp("_sympy_compile")
+        if not os.access(workdir, os.F_OK):
+            os.mkdir(workdir)
+        oldwork = os.getcwd()
+        os.chdir(workdir)
+        try:
+            sys.path.append(workdir)
+            self._generate_code(routines, helpers)
+            self._prepare_files(routines, funcname)
+            self._process_files(routines)
+            mod = __import__(self.module_name)
+        finally:
+            sys.path.remove(workdir)
+            CodeWrapper._module_counter += 1
+            os.chdir(oldwork)
+            if not self.filepath:
+                try:
+                    shutil.rmtree(workdir)
+                except OSError:
+                    # Could be some issues on Windows
+                    pass
+
+        return self._get_wrapped_function(mod, funcname)
+
+    def _generate_code(self, main_routines, helper_routines):
+        all_routines = main_routines + helper_routines
+        self.generator.write(
+            all_routines, self.filename, True, self.include_header,
+            self.include_empty)
+
+    def _prepare_files(self, routines, funcname):
+
+        # C
+        codefilename = self.module_name + '.c'
+        with open(codefilename, 'w') as f:
+            self.dump_c(routines, f, self.filename, funcname=funcname)
+
+        # setup.py
+        with open('setup.py', 'w') as f:
+            self.dump_setup(f)
+
+    @classmethod
+    def _get_wrapped_function(cls, mod, name):
+        return getattr(mod, name)
+
+    def dump_setup(self, f):
+        setup = _ufunc_setup.substitute(module=self.module_name,
+                                        filename=self.filename)
+        f.write(setup)
+
+    def dump_c(self, routines, f, prefix, funcname=None):
+        """Write a C file with Python wrappers
+
+        This file contains all the definitions of the routines in c code.
+
+        Arguments
+        ---------
+        routines
+            List of Routine instances
+        f
+            File-like object to write the file to
+        prefix
+            The filename prefix, used to name the imported module.
+        funcname
+            Name of the main function to be returned.
+        """
+        if funcname is None:
+            if len(routines) == 1:
+                funcname = routines[0].name
+            else:
+                msg = 'funcname must be specified for multiple output routines'
+                raise ValueError(msg)
+        functions = []
+        function_creation = []
+        ufunc_init = []
+        module = self.module_name
+        include_file = "\"{}.h\"".format(prefix)
+        top = _ufunc_top.substitute(include_file=include_file, module=module)
+
+        name = funcname
+
+        # Partition the C function arguments into categories
+        # Here we assume all routines accept the same arguments
+        r_index = 0
+        py_in, _ = self._partition_args(routines[0].arguments)
+        n_in = len(py_in)
+        n_out = len(routines)
+
+        # Declare Args
+        form = "char *{0}{1} = args[{2}];"
+        arg_decs = [form.format('in', i, i) for i in range(n_in)]
+        arg_decs.extend([form.format('out', i, i+n_in) for i in range(n_out)])
+        declare_args = '\n    '.join(arg_decs)
+
+        # Declare Steps
+        form = "npy_intp {0}{1}_step = steps[{2}];"
+        step_decs = [form.format('in', i, i) for i in range(n_in)]
+        step_decs.extend([form.format('out', i, i+n_in) for i in range(n_out)])
+        declare_steps = '\n    '.join(step_decs)
+
+        # Call Args
+        form = "*(double *)in{0}"
+        call_args = ', '.join([form.format(a) for a in range(n_in)])
+
+        # Step Increments
+        form = "{0}{1} += {0}{1}_step;"
+        step_incs = [form.format('in', i) for i in range(n_in)]
+        step_incs.extend([form.format('out', i, i) for i in range(n_out)])
+        step_increments = '\n        '.join(step_incs)
+
+        # Types
+        n_types = n_in + n_out
+        types = "{" + ', '.join(["NPY_DOUBLE"]*n_types) + "};"
+
+        # Docstring
+        docstring = '"Created in SymPy with Ufuncify"'
+
+        # Function Creation
+        function_creation.append("PyObject *ufunc{};".format(r_index))
+
+        # Ufunc initialization
+        init_form = _ufunc_init_form.substitute(module=module,
+                                                funcname=name,
+                                                docstring=docstring,
+                                                n_in=n_in, n_out=n_out,
+                                                ind=r_index)
+        ufunc_init.append(init_form)
+
+        outcalls = [_ufunc_outcalls.substitute(
+            outnum=i, call_args=call_args, funcname=routines[i].name) for i in
+            range(n_out)]
+
+        body = _ufunc_body.substitute(module=module, funcname=name,
+                                      declare_args=declare_args,
+                                      declare_steps=declare_steps,
+                                      call_args=call_args,
+                                      step_increments=step_increments,
+                                      n_types=n_types, types=types,
+                                      outcalls='\n        '.join(outcalls))
+        functions.append(body)
+
+        body = '\n\n'.join(functions)
+        ufunc_init = '\n    '.join(ufunc_init)
+        function_creation = '\n    '.join(function_creation)
+        bottom = _ufunc_bottom.substitute(module=module,
+                                          ufunc_init=ufunc_init,
+                                          function_creation=function_creation)
+        text = [top, body, bottom]
+        f.write('\n\n'.join(text))
+
+    def _partition_args(self, args):
+        """Group function arguments into categories."""
+        py_in = []
+        py_out = []
+        for arg in args:
+            if isinstance(arg, OutputArgument):
+                py_out.append(arg)
+            elif isinstance(arg, InOutArgument):
+                raise ValueError("Ufuncify doesn't support InOutArguments")
+            else:
+                py_in.append(arg)
+        return py_in, py_out
+
+
+@cacheit
+@doctest_depends_on(exe=('f2py', 'gfortran', 'gcc'), modules=('numpy',))
+def ufuncify(args, expr, language=None, backend='numpy', tempdir=None,
+             flags=None, verbose=False, helpers=None, **kwargs):
+    """Generates a binary function that supports broadcasting on numpy arrays.
+
+    Parameters
+    ==========
+
+    args : iterable
+        Either a Symbol or an iterable of symbols. Specifies the argument
+        sequence for the function.
+    expr
+        A SymPy expression that defines the element wise operation.
+    language : string, optional
+        If supplied, (options: 'C' or 'F95'), specifies the language of the
+        generated code. If ``None`` [default], the language is inferred based
+        upon the specified backend.
+    backend : string, optional
+        Backend used to wrap the generated code. Either 'numpy' [default],
+        'cython', or 'f2py'.
+    tempdir : string, optional
+        Path to directory for temporary files. If this argument is supplied,
+        the generated code and the wrapper input files are left intact in
+        the specified path.
+    flags : iterable, optional
+        Additional option flags that will be passed to the backend.
+    verbose : bool, optional
+        If True, autowrap will not mute the command line backends. This can
+        be helpful for debugging.
+    helpers : 3-tuple or iterable of 3-tuples, optional
+        Used to define auxiliary functions needed for the main expression.
+        Each tuple should be of the form (name, expr, args) where:
+
+        - name : str, the function name
+        - expr : sympy expression, the function
+        - args : iterable, the function arguments (can be any iterable of symbols)
+
+    kwargs : dict
+        These kwargs will be passed to autowrap if the `f2py` or `cython`
+        backend is used and ignored if the `numpy` backend is used.
+
+    Notes
+    =====
+
+    The default backend ('numpy') will create actual instances of
+    ``numpy.ufunc``. These support ndimensional broadcasting, and implicit type
+    conversion. Use of the other backends will result in a "ufunc-like"
+    function, which requires equal length 1-dimensional arrays for all
+    arguments, and will not perform any type conversions.
+
+    References
+    ==========
+
+    .. [1] https://numpy.org/doc/stable/reference/ufuncs.html
+
+    Examples
+    ========
+
+    Basic usage:
+
+    >>> from sympy.utilities.autowrap import ufuncify
+    >>> from sympy.abc import x, y
+    >>> import numpy as np
+    >>> f = ufuncify((x, y), y + x**2)
+    >>> type(f)
+    
+    >>> f([1, 2, 3], 2)
+    array([  3.,   6.,  11.])
+    >>> f(np.arange(5), 3)
+    array([  3.,   4.,   7.,  12.,  19.])
+
+    Using helper functions:
+
+    >>> from sympy import Function
+    >>> helper_func = Function('helper_func')  # Define symbolic function
+    >>> expr = x**2 + y*helper_func(x)  # Main expression using helper function
+    >>> # Define helper_func(x) = x**3
+    >>> f = ufuncify((x, y), expr, helpers=[('helper_func', x**3, [x])])
+    >>> f([1, 2], [3, 4])
+    array([  4.,  36.])
+
+    Type handling with different backends:
+
+    For the 'f2py' and 'cython' backends, inputs are required to be equal length
+    1-dimensional arrays. The 'f2py' backend will perform type conversion, but
+    the Cython backend will error if the inputs are not of the expected type.
+
+    >>> f_fortran = ufuncify((x, y), y + x**2, backend='f2py')
+    >>> f_fortran(1, 2)
+    array([ 3.])
+    >>> f_fortran(np.array([1, 2, 3]), np.array([1.0, 2.0, 3.0]))
+    array([  2.,   6.,  12.])
+    >>> f_cython = ufuncify((x, y), y + x**2, backend='Cython')
+    >>> f_cython(1, 2)  # doctest: +ELLIPSIS
+    Traceback (most recent call last):
+      ...
+    TypeError: Argument '_x' has incorrect type (expected numpy.ndarray, got int)
+    >>> f_cython(np.array([1.0]), np.array([2.0]))
+    array([ 3.])
+
+    """
+
+    if isinstance(args, Symbol):
+        args = (args,)
+    else:
+        args = tuple(args)
+
+    if language:
+        _validate_backend_language(backend, language)
+    else:
+        language = _infer_language(backend)
+
+    helpers = helpers if helpers else ()
+    flags = flags if flags else ()
+
+    if backend.upper() == 'NUMPY':
+        # maxargs is set by numpy compile-time constant NPY_MAXARGS
+        # If a future version of numpy modifies or removes this restriction
+        # this variable should be changed or removed
+        maxargs = 32
+        helps = []
+        for name, expr, args in helpers:
+            helps.append(make_routine(name, expr, args))
+        code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify"), tempdir,
+                                           flags, verbose)
+        if not isinstance(expr, (list, tuple)):
+            expr = [expr]
+        if len(expr) == 0:
+            raise ValueError('Expression iterable has zero length')
+        if len(expr) + len(args) > maxargs:
+            msg = ('Cannot create ufunc with more than {0} total arguments: '
+                   'got {1} in, {2} out')
+            raise ValueError(msg.format(maxargs, len(args), len(expr)))
+        routines = [make_routine('autofunc{}'.format(idx), exprx, args) for
+                    idx, exprx in enumerate(expr)]
+        return code_wrapper.wrap_code(routines, helpers=helps)
+    else:
+        # Dummies are used for all added expressions to prevent name clashes
+        # within the original expression.
+        y = IndexedBase(Dummy('y'))
+        m = Dummy('m', integer=True)
+        i = Idx(Dummy('i', integer=True), m)
+        f_dummy = Dummy('f')
+        f = implemented_function('%s_%d' % (f_dummy.name, f_dummy.dummy_index), Lambda(args, expr))
+        # For each of the args create an indexed version.
+        indexed_args = [IndexedBase(Dummy(str(a))) for a in args]
+        # Order the arguments (out, args, dim)
+        args = [y] + indexed_args + [m]
+        args_with_indices = [a[i] for a in indexed_args]
+        return autowrap(Eq(y[i], f(*args_with_indices)), language, backend,
+                        tempdir, args, flags, verbose, helpers, **kwargs)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/codegen.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/codegen.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ac8772fc000d707ae33c67eaa44b4c281157ab0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/codegen.py
@@ -0,0 +1,2237 @@
+"""
+module for generating C, C++, Fortran77, Fortran90, Julia, Rust
+and Octave/Matlab routines that evaluate SymPy expressions.
+This module is work in progress.
+Only the milestones with a '+' character in the list below have been completed.
+
+--- How is sympy.utilities.codegen different from sympy.printing.ccode? ---
+
+We considered the idea to extend the printing routines for SymPy functions in
+such a way that it prints complete compilable code, but this leads to a few
+unsurmountable issues that can only be tackled with dedicated code generator:
+
+- For C, one needs both a code and a header file, while the printing routines
+  generate just one string. This code generator can be extended to support
+  .pyf files for f2py.
+
+- SymPy functions are not concerned with programming-technical issues, such
+  as input, output and input-output arguments. Other examples are contiguous
+  or non-contiguous arrays, including headers of other libraries such as gsl
+  or others.
+
+- It is highly interesting to evaluate several SymPy functions in one C
+  routine, eventually sharing common intermediate results with the help
+  of the cse routine. This is more than just printing.
+
+- From the programming perspective, expressions with constants should be
+  evaluated in the code generator as much as possible. This is different
+  for printing.
+
+--- Basic assumptions ---
+
+* A generic Routine data structure describes the routine that must be
+  translated into C/Fortran/... code. This data structure covers all
+  features present in one or more of the supported languages.
+
+* Descendants from the CodeGen class transform multiple Routine instances
+  into compilable code. Each derived class translates into a specific
+  language.
+
+* In many cases, one wants a simple workflow. The friendly functions in the
+  last part are a simple api on top of the Routine/CodeGen stuff. They are
+  easier to use, but are less powerful.
+
+--- Milestones ---
+
++ First working version with scalar input arguments, generating C code,
+  tests
++ Friendly functions that are easier to use than the rigorous
+  Routine/CodeGen workflow.
++ Integer and Real numbers as input and output
++ Output arguments
++ InputOutput arguments
++ Sort input/output arguments properly
++ Contiguous array arguments (numpy matrices)
++ Also generate .pyf code for f2py (in autowrap module)
++ Isolate constants and evaluate them beforehand in double precision
++ Fortran 90
++ Octave/Matlab
+
+- Common Subexpression Elimination
+- User defined comments in the generated code
+- Optional extra include lines for libraries/objects that can eval special
+  functions
+- Test other C compilers and libraries: gcc, tcc, libtcc, gcc+gsl, ...
+- Contiguous array arguments (SymPy matrices)
+- Non-contiguous array arguments (SymPy matrices)
+- ccode must raise an error when it encounters something that cannot be
+  translated into c. ccode(integrate(sin(x)/x, x)) does not make sense.
+- Complex numbers as input and output
+- A default complex datatype
+- Include extra information in the header: date, user, hostname, sha1
+  hash, ...
+- Fortran 77
+- C++
+- Python
+- Julia
+- Rust
+- ...
+
+"""
+
+import os
+import textwrap
+from io import StringIO
+
+from sympy import __version__ as sympy_version
+from sympy.core import Symbol, S, Tuple, Equality, Function, Basic
+from sympy.printing.c import c_code_printers
+from sympy.printing.codeprinter import AssignmentError
+from sympy.printing.fortran import FCodePrinter
+from sympy.printing.julia import JuliaCodePrinter
+from sympy.printing.octave import OctaveCodePrinter
+from sympy.printing.rust import RustCodePrinter
+from sympy.tensor import Idx, Indexed, IndexedBase
+from sympy.matrices import (MatrixSymbol, ImmutableMatrix, MatrixBase,
+                            MatrixExpr, MatrixSlice)
+from sympy.utilities.iterables import is_sequence
+
+
+__all__ = [
+    # description of routines
+    "Routine", "DataType", "default_datatypes", "get_default_datatype",
+    "Argument", "InputArgument", "OutputArgument", "Result",
+    # routines -> code
+    "CodeGen", "CCodeGen", "FCodeGen", "JuliaCodeGen", "OctaveCodeGen",
+    "RustCodeGen",
+    # friendly functions
+    "codegen", "make_routine",
+]
+
+
+#
+# Description of routines
+#
+
+
+class Routine:
+    """Generic description of evaluation routine for set of expressions.
+
+    A CodeGen class can translate instances of this class into code in a
+    particular language.  The routine specification covers all the features
+    present in these languages.  The CodeGen part must raise an exception
+    when certain features are not present in the target language.  For
+    example, multiple return values are possible in Python, but not in C or
+    Fortran.  Another example: Fortran and Python support complex numbers,
+    while C does not.
+
+    """
+
+    def __init__(self, name, arguments, results, local_vars, global_vars):
+        """Initialize a Routine instance.
+
+        Parameters
+        ==========
+
+        name : string
+            Name of the routine.
+
+        arguments : list of Arguments
+            These are things that appear in arguments of a routine, often
+            appearing on the right-hand side of a function call.  These are
+            commonly InputArguments but in some languages, they can also be
+            OutputArguments or InOutArguments (e.g., pass-by-reference in C
+            code).
+
+        results : list of Results
+            These are the return values of the routine, often appearing on
+            the left-hand side of a function call.  The difference between
+            Results and OutputArguments and when you should use each is
+            language-specific.
+
+        local_vars : list of Results
+            These are variables that will be defined at the beginning of the
+            function.
+
+        global_vars : list of Symbols
+            Variables which will not be passed into the function.
+
+        """
+
+        # extract all input symbols and all symbols appearing in an expression
+        input_symbols = set()
+        symbols = set()
+        for arg in arguments:
+            if isinstance(arg, OutputArgument):
+                symbols.update(arg.expr.free_symbols - arg.expr.atoms(Indexed))
+            elif isinstance(arg, InputArgument):
+                input_symbols.add(arg.name)
+            elif isinstance(arg, InOutArgument):
+                input_symbols.add(arg.name)
+                symbols.update(arg.expr.free_symbols - arg.expr.atoms(Indexed))
+            else:
+                raise ValueError("Unknown Routine argument: %s" % arg)
+
+        for r in results:
+            if not isinstance(r, Result):
+                raise ValueError("Unknown Routine result: %s" % r)
+            symbols.update(r.expr.free_symbols - r.expr.atoms(Indexed))
+
+        local_symbols = set()
+        for r in local_vars:
+            if isinstance(r, Result):
+                symbols.update(r.expr.free_symbols - r.expr.atoms(Indexed))
+                local_symbols.add(r.name)
+            else:
+                local_symbols.add(r)
+
+        symbols = {s.label if isinstance(s, Idx) else s for s in symbols}
+
+        # Check that all symbols in the expressions are covered by
+        # InputArguments/InOutArguments---subset because user could
+        # specify additional (unused) InputArguments or local_vars.
+        notcovered = symbols.difference(
+            input_symbols.union(local_symbols).union(global_vars))
+        if notcovered != set():
+            raise ValueError("Symbols needed for output are not in input " +
+                             ", ".join([str(x) for x in notcovered]))
+
+        self.name = name
+        self.arguments = arguments
+        self.results = results
+        self.local_vars = local_vars
+        self.global_vars = global_vars
+
+    def __str__(self):
+        return self.__class__.__name__ + "({name!r}, {arguments}, {results}, {local_vars}, {global_vars})".format(**self.__dict__)
+
+    __repr__ = __str__
+
+    @property
+    def variables(self):
+        """Returns a set of all variables possibly used in the routine.
+
+        For routines with unnamed return values, the dummies that may or
+        may not be used will be included in the set.
+
+        """
+        v = set(self.local_vars)
+        v.update(arg.name for arg in self.arguments)
+        v.update(res.result_var for res in self.results)
+        return v
+
+    @property
+    def result_variables(self):
+        """Returns a list of OutputArgument, InOutArgument and Result.
+
+        If return values are present, they are at the end of the list.
+        """
+        args = [arg for arg in self.arguments if isinstance(
+            arg, (OutputArgument, InOutArgument))]
+        args.extend(self.results)
+        return args
+
+
+class DataType:
+    """Holds strings for a certain datatype in different languages."""
+    def __init__(self, cname, fname, pyname, jlname, octname, rsname):
+        self.cname = cname
+        self.fname = fname
+        self.pyname = pyname
+        self.jlname = jlname
+        self.octname = octname
+        self.rsname = rsname
+
+
+default_datatypes = {
+    "int": DataType("int", "INTEGER*4", "int", "", "", "i32"),
+    "float": DataType("double", "REAL*8", "float", "", "", "f64"),
+    "complex": DataType("double", "COMPLEX*16", "complex", "", "", "float") #FIXME:
+       # complex is only supported in fortran, python, julia, and octave.
+       # So to not break c or rust code generation, we stick with double or
+       # float, respectively (but actually should raise an exception for
+       # explicitly complex variables (x.is_complex==True))
+}
+
+
+COMPLEX_ALLOWED = False
+def get_default_datatype(expr, complex_allowed=None):
+    """Derives an appropriate datatype based on the expression."""
+    if complex_allowed is None:
+        complex_allowed = COMPLEX_ALLOWED
+    if complex_allowed:
+        final_dtype = "complex"
+    else:
+        final_dtype = "float"
+    if expr.is_integer:
+        return default_datatypes["int"]
+    elif expr.is_real:
+        return default_datatypes["float"]
+    elif isinstance(expr, MatrixBase):
+        #check all entries
+        dt = "int"
+        for element in expr:
+            if dt == "int" and not element.is_integer:
+                dt = "float"
+            if dt == "float" and not element.is_real:
+                return default_datatypes[final_dtype]
+        return default_datatypes[dt]
+    else:
+        return default_datatypes[final_dtype]
+
+
+class Variable:
+    """Represents a typed variable."""
+
+    def __init__(self, name, datatype=None, dimensions=None, precision=None):
+        """Return a new variable.
+
+        Parameters
+        ==========
+
+        name : Symbol or MatrixSymbol
+
+        datatype : optional
+            When not given, the data type will be guessed based on the
+            assumptions on the symbol argument.
+
+        dimensions : sequence containing tuples, optional
+            If present, the argument is interpreted as an array, where this
+            sequence of tuples specifies (lower, upper) bounds for each
+            index of the array.
+
+        precision : int, optional
+            Controls the precision of floating point constants.
+
+        """
+        if not isinstance(name, (Symbol, MatrixSymbol)):
+            raise TypeError("The first argument must be a SymPy symbol.")
+        if datatype is None:
+            datatype = get_default_datatype(name)
+        elif not isinstance(datatype, DataType):
+            raise TypeError("The (optional) `datatype' argument must be an "
+                            "instance of the DataType class.")
+        if dimensions and not isinstance(dimensions, (tuple, list)):
+            raise TypeError(
+                "The dimensions argument must be a sequence of tuples")
+
+        self._name = name
+        self._datatype = {
+            'C': datatype.cname,
+            'FORTRAN': datatype.fname,
+            'JULIA': datatype.jlname,
+            'OCTAVE': datatype.octname,
+            'PYTHON': datatype.pyname,
+            'RUST': datatype.rsname,
+        }
+        self.dimensions = dimensions
+        self.precision = precision
+
+    def __str__(self):
+        return "%s(%r)" % (self.__class__.__name__, self.name)
+
+    __repr__ = __str__
+
+    @property
+    def name(self):
+        return self._name
+
+    def get_datatype(self, language):
+        """Returns the datatype string for the requested language.
+
+        Examples
+        ========
+
+        >>> from sympy import Symbol
+        >>> from sympy.utilities.codegen import Variable
+        >>> x = Variable(Symbol('x'))
+        >>> x.get_datatype('c')
+        'double'
+        >>> x.get_datatype('fortran')
+        'REAL*8'
+
+        """
+        try:
+            return self._datatype[language.upper()]
+        except KeyError:
+            raise CodeGenError("Has datatypes for languages: %s" %
+                    ", ".join(self._datatype))
+
+
+class Argument(Variable):
+    """An abstract Argument data structure: a name and a data type.
+
+    This structure is refined in the descendants below.
+
+    """
+    pass
+
+
+class InputArgument(Argument):
+    pass
+
+
+class ResultBase:
+    """Base class for all "outgoing" information from a routine.
+
+    Objects of this class stores a SymPy expression, and a SymPy object
+    representing a result variable that will be used in the generated code
+    only if necessary.
+
+    """
+    def __init__(self, expr, result_var):
+        self.expr = expr
+        self.result_var = result_var
+
+    def __str__(self):
+        return "%s(%r, %r)" % (self.__class__.__name__, self.expr,
+            self.result_var)
+
+    __repr__ = __str__
+
+
+class OutputArgument(Argument, ResultBase):
+    """OutputArgument are always initialized in the routine."""
+
+    def __init__(self, name, result_var, expr, datatype=None, dimensions=None, precision=None):
+        """Return a new variable.
+
+        Parameters
+        ==========
+
+        name : Symbol, MatrixSymbol
+            The name of this variable.  When used for code generation, this
+            might appear, for example, in the prototype of function in the
+            argument list.
+
+        result_var : Symbol, Indexed
+            Something that can be used to assign a value to this variable.
+            Typically the same as `name` but for Indexed this should be e.g.,
+            "y[i]" whereas `name` should be the Symbol "y".
+
+        expr : object
+            The expression that should be output, typically a SymPy
+            expression.
+
+        datatype : optional
+            When not given, the data type will be guessed based on the
+            assumptions on the symbol argument.
+
+        dimensions : sequence containing tuples, optional
+            If present, the argument is interpreted as an array, where this
+            sequence of tuples specifies (lower, upper) bounds for each
+            index of the array.
+
+        precision : int, optional
+            Controls the precision of floating point constants.
+
+        """
+
+        Argument.__init__(self, name, datatype, dimensions, precision)
+        ResultBase.__init__(self, expr, result_var)
+
+    def __str__(self):
+        return "%s(%r, %r, %r)" % (self.__class__.__name__, self.name, self.result_var, self.expr)
+
+    __repr__ = __str__
+
+
+class InOutArgument(Argument, ResultBase):
+    """InOutArgument are never initialized in the routine."""
+
+    def __init__(self, name, result_var, expr, datatype=None, dimensions=None, precision=None):
+        if not datatype:
+            datatype = get_default_datatype(expr)
+        Argument.__init__(self, name, datatype, dimensions, precision)
+        ResultBase.__init__(self, expr, result_var)
+    __init__.__doc__ = OutputArgument.__init__.__doc__
+
+
+    def __str__(self):
+        return "%s(%r, %r, %r)" % (self.__class__.__name__, self.name, self.expr,
+            self.result_var)
+
+    __repr__ = __str__
+
+
+class Result(Variable, ResultBase):
+    """An expression for a return value.
+
+    The name result is used to avoid conflicts with the reserved word
+    "return" in the Python language.  It is also shorter than ReturnValue.
+
+    These may or may not need a name in the destination (e.g., "return(x*y)"
+    might return a value without ever naming it).
+
+    """
+
+    def __init__(self, expr, name=None, result_var=None, datatype=None,
+                 dimensions=None, precision=None):
+        """Initialize a return value.
+
+        Parameters
+        ==========
+
+        expr : SymPy expression
+
+        name : Symbol, MatrixSymbol, optional
+            The name of this return variable.  When used for code generation,
+            this might appear, for example, in the prototype of function in a
+            list of return values.  A dummy name is generated if omitted.
+
+        result_var : Symbol, Indexed, optional
+            Something that can be used to assign a value to this variable.
+            Typically the same as `name` but for Indexed this should be e.g.,
+            "y[i]" whereas `name` should be the Symbol "y".  Defaults to
+            `name` if omitted.
+
+        datatype : optional
+            When not given, the data type will be guessed based on the
+            assumptions on the expr argument.
+
+        dimensions : sequence containing tuples, optional
+            If present, this variable is interpreted as an array,
+            where this sequence of tuples specifies (lower, upper)
+            bounds for each index of the array.
+
+        precision : int, optional
+            Controls the precision of floating point constants.
+
+        """
+        # Basic because it is the base class for all types of expressions
+        if not isinstance(expr, (Basic, MatrixBase)):
+            raise TypeError("The first argument must be a SymPy expression.")
+
+        if name is None:
+            name = 'result_%d' % abs(hash(expr))
+
+        if datatype is None:
+            #try to infer data type from the expression
+            datatype = get_default_datatype(expr)
+
+        if isinstance(name, str):
+            if isinstance(expr, (MatrixBase, MatrixExpr)):
+                name = MatrixSymbol(name, *expr.shape)
+            else:
+                name = Symbol(name)
+
+        if result_var is None:
+            result_var = name
+
+        Variable.__init__(self, name, datatype=datatype,
+                          dimensions=dimensions, precision=precision)
+        ResultBase.__init__(self, expr, result_var)
+
+    def __str__(self):
+        return "%s(%r, %r, %r)" % (self.__class__.__name__, self.expr, self.name,
+            self.result_var)
+
+    __repr__ = __str__
+
+
+#
+# Transformation of routine objects into code
+#
+
+class CodeGen:
+    """Abstract class for the code generators."""
+
+    printer = None  # will be set to an instance of a CodePrinter subclass
+
+    def _indent_code(self, codelines):
+        return self.printer.indent_code(codelines)
+
+    def _printer_method_with_settings(self, method, settings=None, *args, **kwargs):
+        settings = settings or {}
+        ori = {k: self.printer._settings[k] for k in settings}
+        for k, v in settings.items():
+            self.printer._settings[k] = v
+        result = getattr(self.printer, method)(*args, **kwargs)
+        for k, v in ori.items():
+            self.printer._settings[k] = v
+        return result
+
+    def _get_symbol(self, s):
+        """Returns the symbol as fcode prints it."""
+        if self.printer._settings['human']:
+            expr_str = self.printer.doprint(s)
+        else:
+            constants, not_supported, expr_str = self.printer.doprint(s)
+            if constants or not_supported:
+                raise ValueError("Failed to print %s" % str(s))
+        return expr_str.strip()
+
+    def __init__(self, project="project", cse=False):
+        """Initialize a code generator.
+
+        Derived classes will offer more options that affect the generated
+        code.
+
+        """
+        self.project = project
+        self.cse = cse
+
+    def routine(self, name, expr, argument_sequence=None, global_vars=None):
+        """Creates an Routine object that is appropriate for this language.
+
+        This implementation is appropriate for at least C/Fortran.  Subclasses
+        can override this if necessary.
+
+        Here, we assume at most one return value (the l-value) which must be
+        scalar.  Additional outputs are OutputArguments (e.g., pointers on
+        right-hand-side or pass-by-reference).  Matrices are always returned
+        via OutputArguments.  If ``argument_sequence`` is None, arguments will
+        be ordered alphabetically, but with all InputArguments first, and then
+        OutputArgument and InOutArguments.
+
+        """
+
+        if self.cse:
+            from sympy.simplify.cse_main import cse
+
+            if is_sequence(expr) and not isinstance(expr, (MatrixBase, MatrixExpr)):
+                if not expr:
+                    raise ValueError("No expression given")
+                for e in expr:
+                    if not e.is_Equality:
+                        raise CodeGenError("Lists of expressions must all be Equalities. {} is not.".format(e))
+
+                # create a list of right hand sides and simplify them
+                rhs = [e.rhs for e in expr]
+                common, simplified = cse(rhs)
+
+                # pack the simplified expressions back up with their left hand sides
+                expr = [Equality(e.lhs, rhs) for e, rhs in zip(expr, simplified)]
+            else:
+                if isinstance(expr, Equality):
+                    common, simplified = cse(expr.rhs) #, ignore=in_out_args)
+                    expr = Equality(expr.lhs, simplified[0])
+                else:
+                    common, simplified = cse(expr)
+                    expr = simplified
+
+            local_vars = [Result(b,a) for a,b in common]
+            local_symbols = {a for a,_ in common}
+            local_expressions = Tuple(*[b for _,b in common])
+        else:
+            local_expressions = Tuple()
+
+        if is_sequence(expr) and not isinstance(expr, (MatrixBase, MatrixExpr)):
+            if not expr:
+                raise ValueError("No expression given")
+            expressions = Tuple(*expr)
+        else:
+            expressions = Tuple(expr)
+
+        if self.cse:
+            if {i.label for i in expressions.atoms(Idx)} != set():
+                raise CodeGenError("CSE and Indexed expressions do not play well together yet")
+        else:
+            # local variables for indexed expressions
+            local_vars = {i.label for i in expressions.atoms(Idx)}
+            local_symbols = local_vars
+
+        # global variables
+        global_vars = set() if global_vars is None else set(global_vars)
+
+        # symbols that should be arguments
+        symbols = (expressions.free_symbols | local_expressions.free_symbols) - local_symbols - global_vars
+        new_symbols = set()
+        new_symbols.update(symbols)
+
+        for symbol in symbols:
+            if isinstance(symbol, Idx):
+                new_symbols.remove(symbol)
+                new_symbols.update(symbol.args[1].free_symbols)
+            if isinstance(symbol, Indexed):
+                new_symbols.remove(symbol)
+        symbols = new_symbols
+
+        # Decide whether to use output argument or return value
+        return_val = []
+        output_args = []
+        for expr in expressions:
+            if isinstance(expr, Equality):
+                out_arg = expr.lhs
+                expr = expr.rhs
+                if isinstance(out_arg, Indexed):
+                    dims = tuple([ (S.Zero, dim - 1) for dim in out_arg.shape])
+                    symbol = out_arg.base.label
+                elif isinstance(out_arg, Symbol):
+                    dims = []
+                    symbol = out_arg
+                elif isinstance(out_arg, MatrixSymbol):
+                    dims = tuple([ (S.Zero, dim - 1) for dim in out_arg.shape])
+                    symbol = out_arg
+                else:
+                    raise CodeGenError("Only Indexed, Symbol, or MatrixSymbol "
+                                       "can define output arguments.")
+
+                if expr.has(symbol):
+                    output_args.append(
+                        InOutArgument(symbol, out_arg, expr, dimensions=dims))
+                else:
+                    output_args.append(
+                        OutputArgument(symbol, out_arg, expr, dimensions=dims))
+
+                # remove duplicate arguments when they are not local variables
+                if symbol not in local_vars:
+                    # avoid duplicate arguments
+                    symbols.remove(symbol)
+            elif isinstance(expr, (ImmutableMatrix, MatrixSlice)):
+                # Create a "dummy" MatrixSymbol to use as the Output arg
+                out_arg = MatrixSymbol('out_%s' % abs(hash(expr)), *expr.shape)
+                dims = tuple([(S.Zero, dim - 1) for dim in out_arg.shape])
+                output_args.append(
+                    OutputArgument(out_arg, out_arg, expr, dimensions=dims))
+            else:
+                return_val.append(Result(expr))
+
+        arg_list = []
+
+        # setup input argument list
+
+        # helper to get dimensions for data for array-like args
+        def dimensions(s):
+            return [(S.Zero, dim - 1) for dim in s.shape]
+
+        array_symbols = {}
+        for array in expressions.atoms(Indexed) | local_expressions.atoms(Indexed):
+            array_symbols[array.base.label] = array
+        for array in expressions.atoms(MatrixSymbol) | local_expressions.atoms(MatrixSymbol):
+            array_symbols[array] = array
+
+        for symbol in sorted(symbols, key=str):
+            if symbol in array_symbols:
+                array = array_symbols[symbol]
+                metadata = {'dimensions': dimensions(array)}
+            else:
+                metadata = {}
+
+            arg_list.append(InputArgument(symbol, **metadata))
+
+        output_args.sort(key=lambda x: str(x.name))
+        arg_list.extend(output_args)
+
+        if argument_sequence is not None:
+            # if the user has supplied IndexedBase instances, we'll accept that
+            new_sequence = []
+            for arg in argument_sequence:
+                if isinstance(arg, IndexedBase):
+                    new_sequence.append(arg.label)
+                else:
+                    new_sequence.append(arg)
+            argument_sequence = new_sequence
+
+            missing = [x for x in arg_list if x.name not in argument_sequence]
+            if missing:
+                msg = "Argument list didn't specify: {0} "
+                msg = msg.format(", ".join([str(m.name) for m in missing]))
+                raise CodeGenArgumentListError(msg, missing)
+
+            # create redundant arguments to produce the requested sequence
+            name_arg_dict = {x.name: x for x in arg_list}
+            new_args = []
+            for symbol in argument_sequence:
+                try:
+                    new_args.append(name_arg_dict[symbol])
+                except KeyError:
+                    if isinstance(symbol, (IndexedBase, MatrixSymbol)):
+                        metadata = {'dimensions': dimensions(symbol)}
+                    else:
+                        metadata = {}
+                    new_args.append(InputArgument(symbol, **metadata))
+            arg_list = new_args
+
+        return Routine(name, arg_list, return_val, local_vars, global_vars)
+
+    def write(self, routines, prefix, to_files=False, header=True, empty=True):
+        """Writes all the source code files for the given routines.
+
+        The generated source is returned as a list of (filename, contents)
+        tuples, or is written to files (see below).  Each filename consists
+        of the given prefix, appended with an appropriate extension.
+
+        Parameters
+        ==========
+
+        routines : list
+            A list of Routine instances to be written
+
+        prefix : string
+            The prefix for the output files
+
+        to_files : bool, optional
+            When True, the output is written to files.  Otherwise, a list
+            of (filename, contents) tuples is returned.  [default: False]
+
+        header : bool, optional
+            When True, a header comment is included on top of each source
+            file. [default: True]
+
+        empty : bool, optional
+            When True, empty lines are included to structure the source
+            files. [default: True]
+
+        """
+        if to_files:
+            for dump_fn in self.dump_fns:
+                filename = "%s.%s" % (prefix, dump_fn.extension)
+                with open(filename, "w") as f:
+                    dump_fn(self, routines, f, prefix, header, empty)
+        else:
+            result = []
+            for dump_fn in self.dump_fns:
+                filename = "%s.%s" % (prefix, dump_fn.extension)
+                contents = StringIO()
+                dump_fn(self, routines, contents, prefix, header, empty)
+                result.append((filename, contents.getvalue()))
+            return result
+
+    def dump_code(self, routines, f, prefix, header=True, empty=True):
+        """Write the code by calling language specific methods.
+
+        The generated file contains all the definitions of the routines in
+        low-level code and refers to the header file if appropriate.
+
+        Parameters
+        ==========
+
+        routines : list
+            A list of Routine instances.
+
+        f : file-like
+            Where to write the file.
+
+        prefix : string
+            The filename prefix, used to refer to the proper header file.
+            Only the basename of the prefix is used.
+
+        header : bool, optional
+            When True, a header comment is included on top of each source
+            file.  [default : True]
+
+        empty : bool, optional
+            When True, empty lines are included to structure the source
+            files.  [default : True]
+
+        """
+
+        code_lines = self._preprocessor_statements(prefix)
+
+        for routine in routines:
+            if empty:
+                code_lines.append("\n")
+            code_lines.extend(self._get_routine_opening(routine))
+            code_lines.extend(self._declare_arguments(routine))
+            code_lines.extend(self._declare_globals(routine))
+            code_lines.extend(self._declare_locals(routine))
+            if empty:
+                code_lines.append("\n")
+            code_lines.extend(self._call_printer(routine))
+            if empty:
+                code_lines.append("\n")
+            code_lines.extend(self._get_routine_ending(routine))
+
+        code_lines = self._indent_code(''.join(code_lines))
+
+        if header:
+            code_lines = ''.join(self._get_header() + [code_lines])
+
+        if code_lines:
+            f.write(code_lines)
+
+
+class CodeGenError(Exception):
+    pass
+
+
+class CodeGenArgumentListError(Exception):
+    @property
+    def missing_args(self):
+        return self.args[1]
+
+
+header_comment = """Code generated with SymPy %(version)s
+
+See http://www.sympy.org/ for more information.
+
+This file is part of '%(project)s'
+"""
+
+
+class CCodeGen(CodeGen):
+    """Generator for C code.
+
+    The .write() method inherited from CodeGen will output a code file and
+    an interface file, .c and .h respectively.
+
+    """
+
+    code_extension = "c"
+    interface_extension = "h"
+    standard = 'c99'
+
+    def __init__(self, project="project", printer=None,
+                 preprocessor_statements=None, cse=False):
+        super().__init__(project=project, cse=cse)
+        self.printer = printer or c_code_printers[self.standard.lower()]()
+
+        self.preprocessor_statements = preprocessor_statements
+        if preprocessor_statements is None:
+            self.preprocessor_statements = ['#include ']
+
+    def _get_header(self):
+        """Writes a common header for the generated files."""
+        code_lines = []
+        code_lines.append("/" + "*"*78 + '\n')
+        tmp = header_comment % {"version": sympy_version,
+                                "project": self.project}
+        for line in tmp.splitlines():
+            code_lines.append(" *%s*\n" % line.center(76))
+        code_lines.append(" " + "*"*78 + "/\n")
+        return code_lines
+
+    def get_prototype(self, routine):
+        """Returns a string for the function prototype of the routine.
+
+        If the routine has multiple result objects, an CodeGenError is
+        raised.
+
+        See: https://en.wikipedia.org/wiki/Function_prototype
+
+        """
+        if len(routine.results) > 1:
+            raise CodeGenError("C only supports a single or no return value.")
+        elif len(routine.results) == 1:
+            ctype = routine.results[0].get_datatype('C')
+        else:
+            ctype = "void"
+
+        type_args = []
+        for arg in routine.arguments:
+            name = self.printer.doprint(arg.name)
+            if arg.dimensions or isinstance(arg, ResultBase):
+                type_args.append((arg.get_datatype('C'), "*%s" % name))
+            else:
+                type_args.append((arg.get_datatype('C'), name))
+        arguments = ", ".join([ "%s %s" % t for t in type_args])
+        return "%s %s(%s)" % (ctype, routine.name, arguments)
+
+    def _preprocessor_statements(self, prefix):
+        code_lines = []
+        code_lines.append('#include "{}.h"'.format(os.path.basename(prefix)))
+        code_lines.extend(self.preprocessor_statements)
+        code_lines = ['{}\n'.format(l) for l in code_lines]
+        return code_lines
+
+    def _get_routine_opening(self, routine):
+        prototype = self.get_prototype(routine)
+        return ["%s {\n" % prototype]
+
+    def _declare_arguments(self, routine):
+        # arguments are declared in prototype
+        return []
+
+    def _declare_globals(self, routine):
+        # global variables are not explicitly declared within C functions
+        return []
+
+    def _declare_locals(self, routine):
+
+        # Compose a list of symbols to be dereferenced in the function
+        # body. These are the arguments that were passed by a reference
+        # pointer, excluding arrays.
+        dereference = []
+        for arg in routine.arguments:
+            if isinstance(arg, ResultBase) and not arg.dimensions:
+                dereference.append(arg.name)
+
+        code_lines = []
+        for result in routine.local_vars:
+
+            # local variables that are simple symbols such as those used as indices into
+            # for loops are defined declared elsewhere.
+            if not isinstance(result, Result):
+                continue
+
+            if result.name != result.result_var:
+                raise CodeGen("Result variable and name should match: {}".format(result))
+            assign_to = result.name
+            t = result.get_datatype('c')
+            if isinstance(result.expr, (MatrixBase, MatrixExpr)):
+                dims = result.expr.shape
+                code_lines.append("{} {}[{}];\n".format(t, str(assign_to), dims[0]*dims[1]))
+                prefix = ""
+            else:
+                prefix = "const {} ".format(t)
+
+            constants, not_c, c_expr = self._printer_method_with_settings(
+                'doprint', {"human": False, "dereference": dereference, "strict": False},
+                result.expr, assign_to=assign_to)
+
+            for name, value in sorted(constants, key=str):
+                code_lines.append("double const %s = %s;\n" % (name, value))
+
+            code_lines.append("{}{}\n".format(prefix, c_expr))
+
+        return code_lines
+
+    def _call_printer(self, routine):
+        code_lines = []
+
+        # Compose a list of symbols to be dereferenced in the function
+        # body. These are the arguments that were passed by a reference
+        # pointer, excluding arrays.
+        dereference = []
+        for arg in routine.arguments:
+            if isinstance(arg, ResultBase) and not arg.dimensions:
+                dereference.append(arg.name)
+
+        return_val = None
+        for result in routine.result_variables:
+            if isinstance(result, Result):
+                assign_to = routine.name + "_result"
+                t = result.get_datatype('c')
+                code_lines.append("{} {};\n".format(t, str(assign_to)))
+                return_val = assign_to
+            else:
+                assign_to = result.result_var
+
+            try:
+                constants, not_c, c_expr = self._printer_method_with_settings(
+                    'doprint', {"human": False, "dereference": dereference, "strict": False},
+                    result.expr, assign_to=assign_to)
+            except AssignmentError:
+                assign_to = result.result_var
+                code_lines.append(
+                    "%s %s;\n" % (result.get_datatype('c'), str(assign_to)))
+                constants, not_c, c_expr = self._printer_method_with_settings(
+                    'doprint', {"human": False, "dereference": dereference, "strict": False},
+                    result.expr, assign_to=assign_to)
+
+            for name, value in sorted(constants, key=str):
+                code_lines.append("double const %s = %s;\n" % (name, value))
+            code_lines.append("%s\n" % c_expr)
+
+        if return_val:
+            code_lines.append("   return %s;\n" % return_val)
+        return code_lines
+
+    def _get_routine_ending(self, routine):
+        return ["}\n"]
+
+    def dump_c(self, routines, f, prefix, header=True, empty=True):
+        self.dump_code(routines, f, prefix, header, empty)
+    dump_c.extension = code_extension  # type: ignore
+    dump_c.__doc__ = CodeGen.dump_code.__doc__
+
+    def dump_h(self, routines, f, prefix, header=True, empty=True):
+        """Writes the C header file.
+
+        This file contains all the function declarations.
+
+        Parameters
+        ==========
+
+        routines : list
+            A list of Routine instances.
+
+        f : file-like
+            Where to write the file.
+
+        prefix : string
+            The filename prefix, used to construct the include guards.
+            Only the basename of the prefix is used.
+
+        header : bool, optional
+            When True, a header comment is included on top of each source
+            file.  [default : True]
+
+        empty : bool, optional
+            When True, empty lines are included to structure the source
+            files.  [default : True]
+
+        """
+        if header:
+            print(''.join(self._get_header()), file=f)
+        guard_name = "%s__%s__H" % (self.project.replace(
+            " ", "_").upper(), prefix.replace("/", "_").upper())
+        # include guards
+        if empty:
+            print(file=f)
+        print("#ifndef %s" % guard_name, file=f)
+        print("#define %s" % guard_name, file=f)
+        if empty:
+            print(file=f)
+        # declaration of the function prototypes
+        for routine in routines:
+            prototype = self.get_prototype(routine)
+            print("%s;" % prototype, file=f)
+        # end if include guards
+        if empty:
+            print(file=f)
+        print("#endif", file=f)
+        if empty:
+            print(file=f)
+    dump_h.extension = interface_extension  # type: ignore
+
+    # This list of dump functions is used by CodeGen.write to know which dump
+    # functions it has to call.
+    dump_fns = [dump_c, dump_h]
+
+class C89CodeGen(CCodeGen):
+    standard = 'C89'
+
+class C99CodeGen(CCodeGen):
+    standard = 'C99'
+
+class FCodeGen(CodeGen):
+    """Generator for Fortran 95 code
+
+    The .write() method inherited from CodeGen will output a code file and
+    an interface file, .f90 and .h respectively.
+
+    """
+
+    code_extension = "f90"
+    interface_extension = "h"
+
+    def __init__(self, project='project', printer=None):
+        super().__init__(project)
+        self.printer = printer or FCodePrinter()
+
+    def _get_header(self):
+        """Writes a common header for the generated files."""
+        code_lines = []
+        code_lines.append("!" + "*"*78 + '\n')
+        tmp = header_comment % {"version": sympy_version,
+            "project": self.project}
+        for line in tmp.splitlines():
+            code_lines.append("!*%s*\n" % line.center(76))
+        code_lines.append("!" + "*"*78 + '\n')
+        return code_lines
+
+    def _preprocessor_statements(self, prefix):
+        return []
+
+    def _get_routine_opening(self, routine):
+        """Returns the opening statements of the fortran routine."""
+        code_list = []
+        if len(routine.results) > 1:
+            raise CodeGenError(
+                "Fortran only supports a single or no return value.")
+        elif len(routine.results) == 1:
+            result = routine.results[0]
+            code_list.append(result.get_datatype('fortran'))
+            code_list.append("function")
+        else:
+            code_list.append("subroutine")
+
+        args = ", ".join("%s" % self._get_symbol(arg.name)
+                        for arg in routine.arguments)
+
+        call_sig = "{}({})\n".format(routine.name, args)
+        # Fortran 95 requires all lines be less than 132 characters, so wrap
+        # this line before appending.
+        call_sig = ' &\n'.join(textwrap.wrap(call_sig,
+                                             width=60,
+                                             break_long_words=False)) + '\n'
+        code_list.append(call_sig)
+        code_list = [' '.join(code_list)]
+        code_list.append('implicit none\n')
+        return code_list
+
+    def _declare_arguments(self, routine):
+        # argument type declarations
+        code_list = []
+        array_list = []
+        scalar_list = []
+        for arg in routine.arguments:
+
+            if isinstance(arg, InputArgument):
+                typeinfo = "%s, intent(in)" % arg.get_datatype('fortran')
+            elif isinstance(arg, InOutArgument):
+                typeinfo = "%s, intent(inout)" % arg.get_datatype('fortran')
+            elif isinstance(arg, OutputArgument):
+                typeinfo = "%s, intent(out)" % arg.get_datatype('fortran')
+            else:
+                raise CodeGenError("Unknown Argument type: %s" % type(arg))
+
+            fprint = self._get_symbol
+
+            if arg.dimensions:
+                # fortran arrays start at 1
+                dimstr = ", ".join(["%s:%s" % (
+                    fprint(dim[0] + 1), fprint(dim[1] + 1))
+                    for dim in arg.dimensions])
+                typeinfo += ", dimension(%s)" % dimstr
+                array_list.append("%s :: %s\n" % (typeinfo, fprint(arg.name)))
+            else:
+                scalar_list.append("%s :: %s\n" % (typeinfo, fprint(arg.name)))
+
+        # scalars first, because they can be used in array declarations
+        code_list.extend(scalar_list)
+        code_list.extend(array_list)
+
+        return code_list
+
+    def _declare_globals(self, routine):
+        # Global variables not explicitly declared within Fortran 90 functions.
+        # Note: a future F77 mode may need to generate "common" blocks.
+        return []
+
+    def _declare_locals(self, routine):
+        code_list = []
+        for var in sorted(routine.local_vars, key=str):
+            typeinfo = get_default_datatype(var)
+            code_list.append("%s :: %s\n" % (
+                typeinfo.fname, self._get_symbol(var)))
+        return code_list
+
+    def _get_routine_ending(self, routine):
+        """Returns the closing statements of the fortran routine."""
+        if len(routine.results) == 1:
+            return ["end function\n"]
+        else:
+            return ["end subroutine\n"]
+
+    def get_interface(self, routine):
+        """Returns a string for the function interface.
+
+        The routine should have a single result object, which can be None.
+        If the routine has multiple result objects, a CodeGenError is
+        raised.
+
+        See: https://en.wikipedia.org/wiki/Function_prototype
+
+        """
+        prototype = [ "interface\n" ]
+        prototype.extend(self._get_routine_opening(routine))
+        prototype.extend(self._declare_arguments(routine))
+        prototype.extend(self._get_routine_ending(routine))
+        prototype.append("end interface\n")
+
+        return "".join(prototype)
+
+    def _call_printer(self, routine):
+        declarations = []
+        code_lines = []
+        for result in routine.result_variables:
+            if isinstance(result, Result):
+                assign_to = routine.name
+            elif isinstance(result, (OutputArgument, InOutArgument)):
+                assign_to = result.result_var
+
+            constants, not_fortran, f_expr = self._printer_method_with_settings(
+                'doprint', {"human": False, "source_format": 'free', "standard": 95, "strict": False},
+                result.expr, assign_to=assign_to)
+
+            for obj, v in sorted(constants, key=str):
+                t = get_default_datatype(obj)
+                declarations.append(
+                    "%s, parameter :: %s = %s\n" % (t.fname, obj, v))
+            for obj in sorted(not_fortran, key=str):
+                t = get_default_datatype(obj)
+                if isinstance(obj, Function):
+                    name = obj.func
+                else:
+                    name = obj
+                declarations.append("%s :: %s\n" % (t.fname, name))
+
+            code_lines.append("%s\n" % f_expr)
+        return declarations + code_lines
+
+    def _indent_code(self, codelines):
+        return self._printer_method_with_settings(
+            'indent_code', {"human": False, "source_format": 'free', "strict": False}, codelines)
+
+    def dump_f95(self, routines, f, prefix, header=True, empty=True):
+        # check that symbols are unique with ignorecase
+        for r in routines:
+            lowercase = {str(x).lower() for x in r.variables}
+            orig_case = {str(x) for x in r.variables}
+            if len(lowercase) < len(orig_case):
+                raise CodeGenError("Fortran ignores case. Got symbols: %s" %
+                        (", ".join([str(var) for var in r.variables])))
+        self.dump_code(routines, f, prefix, header, empty)
+    dump_f95.extension = code_extension  # type: ignore
+    dump_f95.__doc__ = CodeGen.dump_code.__doc__
+
+    def dump_h(self, routines, f, prefix, header=True, empty=True):
+        """Writes the interface to a header file.
+
+        This file contains all the function declarations.
+
+        Parameters
+        ==========
+
+        routines : list
+            A list of Routine instances.
+
+        f : file-like
+            Where to write the file.
+
+        prefix : string
+            The filename prefix.
+
+        header : bool, optional
+            When True, a header comment is included on top of each source
+            file.  [default : True]
+
+        empty : bool, optional
+            When True, empty lines are included to structure the source
+            files.  [default : True]
+
+        """
+        if header:
+            print(''.join(self._get_header()), file=f)
+        if empty:
+            print(file=f)
+        # declaration of the function prototypes
+        for routine in routines:
+            prototype = self.get_interface(routine)
+            f.write(prototype)
+        if empty:
+            print(file=f)
+    dump_h.extension = interface_extension  # type: ignore
+
+    # This list of dump functions is used by CodeGen.write to know which dump
+    # functions it has to call.
+    dump_fns = [dump_f95, dump_h]
+
+
+class JuliaCodeGen(CodeGen):
+    """Generator for Julia code.
+
+    The .write() method inherited from CodeGen will output a code file
+    .jl.
+
+    """
+
+    code_extension = "jl"
+
+    def __init__(self, project='project', printer=None):
+        super().__init__(project)
+        self.printer = printer or JuliaCodePrinter()
+
+    def routine(self, name, expr, argument_sequence, global_vars):
+        """Specialized Routine creation for Julia."""
+
+        if is_sequence(expr) and not isinstance(expr, (MatrixBase, MatrixExpr)):
+            if not expr:
+                raise ValueError("No expression given")
+            expressions = Tuple(*expr)
+        else:
+            expressions = Tuple(expr)
+
+        # local variables
+        local_vars = {i.label for i in expressions.atoms(Idx)}
+
+        # global variables
+        global_vars = set() if global_vars is None else set(global_vars)
+
+        # symbols that should be arguments
+        old_symbols = expressions.free_symbols - local_vars - global_vars
+        symbols = set()
+        for s in old_symbols:
+            if isinstance(s, Idx):
+                symbols.update(s.args[1].free_symbols)
+            elif not isinstance(s, Indexed):
+                symbols.add(s)
+
+        # Julia supports multiple return values
+        return_vals = []
+        output_args = []
+        for (i, expr) in enumerate(expressions):
+            if isinstance(expr, Equality):
+                out_arg = expr.lhs
+                expr = expr.rhs
+                symbol = out_arg
+                if isinstance(out_arg, Indexed):
+                    dims = tuple([ (S.One, dim) for dim in out_arg.shape])
+                    symbol = out_arg.base.label
+                    output_args.append(InOutArgument(symbol, out_arg, expr, dimensions=dims))
+                if not isinstance(out_arg, (Indexed, Symbol, MatrixSymbol)):
+                    raise CodeGenError("Only Indexed, Symbol, or MatrixSymbol "
+                                       "can define output arguments.")
+
+                return_vals.append(Result(expr, name=symbol, result_var=out_arg))
+                if not expr.has(symbol):
+                    # this is a pure output: remove from the symbols list, so
+                    # it doesn't become an input.
+                    symbols.remove(symbol)
+
+            else:
+                # we have no name for this output
+                return_vals.append(Result(expr, name='out%d' % (i+1)))
+
+        # setup input argument list
+        output_args.sort(key=lambda x: str(x.name))
+        arg_list = list(output_args)
+        array_symbols = {}
+        for array in expressions.atoms(Indexed):
+            array_symbols[array.base.label] = array
+        for array in expressions.atoms(MatrixSymbol):
+            array_symbols[array] = array
+
+        for symbol in sorted(symbols, key=str):
+            arg_list.append(InputArgument(symbol))
+
+        if argument_sequence is not None:
+            # if the user has supplied IndexedBase instances, we'll accept that
+            new_sequence = []
+            for arg in argument_sequence:
+                if isinstance(arg, IndexedBase):
+                    new_sequence.append(arg.label)
+                else:
+                    new_sequence.append(arg)
+            argument_sequence = new_sequence
+
+            missing = [x for x in arg_list if x.name not in argument_sequence]
+            if missing:
+                msg = "Argument list didn't specify: {0} "
+                msg = msg.format(", ".join([str(m.name) for m in missing]))
+                raise CodeGenArgumentListError(msg, missing)
+
+            # create redundant arguments to produce the requested sequence
+            name_arg_dict = {x.name: x for x in arg_list}
+            new_args = []
+            for symbol in argument_sequence:
+                try:
+                    new_args.append(name_arg_dict[symbol])
+                except KeyError:
+                    new_args.append(InputArgument(symbol))
+            arg_list = new_args
+
+        return Routine(name, arg_list, return_vals, local_vars, global_vars)
+
+    def _get_header(self):
+        """Writes a common header for the generated files."""
+        code_lines = []
+        tmp = header_comment % {"version": sympy_version,
+            "project": self.project}
+        for line in tmp.splitlines():
+            if line == '':
+                code_lines.append("#\n")
+            else:
+                code_lines.append("#   %s\n" % line)
+        return code_lines
+
+    def _preprocessor_statements(self, prefix):
+        return []
+
+    def _get_routine_opening(self, routine):
+        """Returns the opening statements of the routine."""
+        code_list = []
+        code_list.append("function ")
+
+        # Inputs
+        args = []
+        for arg in routine.arguments:
+            if isinstance(arg, OutputArgument):
+                raise CodeGenError("Julia: invalid argument of type %s" %
+                                   str(type(arg)))
+            if isinstance(arg, (InputArgument, InOutArgument)):
+                args.append("%s" % self._get_symbol(arg.name))
+        args = ", ".join(args)
+        code_list.append("%s(%s)\n" % (routine.name, args))
+        code_list = [ "".join(code_list) ]
+
+        return code_list
+
+    def _declare_arguments(self, routine):
+        return []
+
+    def _declare_globals(self, routine):
+        return []
+
+    def _declare_locals(self, routine):
+        return []
+
+    def _get_routine_ending(self, routine):
+        outs = []
+        for result in routine.results:
+            if isinstance(result, Result):
+                # Note: name not result_var; want `y` not `y[i]` for Indexed
+                s = self._get_symbol(result.name)
+            else:
+                raise CodeGenError("unexpected object in Routine results")
+            outs.append(s)
+        return ["return " + ", ".join(outs) + "\nend\n"]
+
+    def _call_printer(self, routine):
+        declarations = []
+        code_lines = []
+        for result in routine.results:
+            if isinstance(result, Result):
+                assign_to = result.result_var
+            else:
+                raise CodeGenError("unexpected object in Routine results")
+
+            constants, not_supported, jl_expr = self._printer_method_with_settings(
+                'doprint', {"human": False, "strict": False}, result.expr, assign_to=assign_to)
+
+            for obj, v in sorted(constants, key=str):
+                declarations.append(
+                    "%s = %s\n" % (obj, v))
+            for obj in sorted(not_supported, key=str):
+                if isinstance(obj, Function):
+                    name = obj.func
+                else:
+                    name = obj
+                declarations.append(
+                    "# unsupported: %s\n" % (name))
+            code_lines.append("%s\n" % (jl_expr))
+        return declarations + code_lines
+
+    def _indent_code(self, codelines):
+        # Note that indenting seems to happen twice, first
+        # statement-by-statement by JuliaPrinter then again here.
+        p = JuliaCodePrinter({'human': False, "strict": False})
+        return p.indent_code(codelines)
+
+    def dump_jl(self, routines, f, prefix, header=True, empty=True):
+        self.dump_code(routines, f, prefix, header, empty)
+
+    dump_jl.extension = code_extension  # type: ignore
+    dump_jl.__doc__ = CodeGen.dump_code.__doc__
+
+    # This list of dump functions is used by CodeGen.write to know which dump
+    # functions it has to call.
+    dump_fns = [dump_jl]
+
+
+class OctaveCodeGen(CodeGen):
+    """Generator for Octave code.
+
+    The .write() method inherited from CodeGen will output a code file
+    .m.
+
+    Octave .m files usually contain one function.  That function name should
+    match the filename (``prefix``).  If you pass multiple ``name_expr`` pairs,
+    the latter ones are presumed to be private functions accessed by the
+    primary function.
+
+    You should only pass inputs to ``argument_sequence``: outputs are ordered
+    according to their order in ``name_expr``.
+
+    """
+
+    code_extension = "m"
+
+    def __init__(self, project='project', printer=None):
+        super().__init__(project)
+        self.printer = printer or OctaveCodePrinter()
+
+    def routine(self, name, expr, argument_sequence, global_vars):
+        """Specialized Routine creation for Octave."""
+
+        # FIXME: this is probably general enough for other high-level
+        # languages, perhaps its the C/Fortran one that is specialized!
+
+        if is_sequence(expr) and not isinstance(expr, (MatrixBase, MatrixExpr)):
+            if not expr:
+                raise ValueError("No expression given")
+            expressions = Tuple(*expr)
+        else:
+            expressions = Tuple(expr)
+
+        # local variables
+        local_vars = {i.label for i in expressions.atoms(Idx)}
+
+        # global variables
+        global_vars = set() if global_vars is None else set(global_vars)
+
+        # symbols that should be arguments
+        old_symbols = expressions.free_symbols - local_vars - global_vars
+        symbols = set()
+        for s in old_symbols:
+            if isinstance(s, Idx):
+                symbols.update(s.args[1].free_symbols)
+            elif not isinstance(s, Indexed):
+                symbols.add(s)
+
+        # Octave supports multiple return values
+        return_vals = []
+        for (i, expr) in enumerate(expressions):
+            if isinstance(expr, Equality):
+                out_arg = expr.lhs
+                expr = expr.rhs
+                symbol = out_arg
+                if isinstance(out_arg, Indexed):
+                    symbol = out_arg.base.label
+                if not isinstance(out_arg, (Indexed, Symbol, MatrixSymbol)):
+                    raise CodeGenError("Only Indexed, Symbol, or MatrixSymbol "
+                                       "can define output arguments.")
+
+                return_vals.append(Result(expr, name=symbol, result_var=out_arg))
+                if not expr.has(symbol):
+                    # this is a pure output: remove from the symbols list, so
+                    # it doesn't become an input.
+                    symbols.remove(symbol)
+
+            else:
+                # we have no name for this output
+                return_vals.append(Result(expr, name='out%d' % (i+1)))
+
+        # setup input argument list
+        arg_list = []
+        array_symbols = {}
+        for array in expressions.atoms(Indexed):
+            array_symbols[array.base.label] = array
+        for array in expressions.atoms(MatrixSymbol):
+            array_symbols[array] = array
+
+        for symbol in sorted(symbols, key=str):
+            arg_list.append(InputArgument(symbol))
+
+        if argument_sequence is not None:
+            # if the user has supplied IndexedBase instances, we'll accept that
+            new_sequence = []
+            for arg in argument_sequence:
+                if isinstance(arg, IndexedBase):
+                    new_sequence.append(arg.label)
+                else:
+                    new_sequence.append(arg)
+            argument_sequence = new_sequence
+
+            missing = [x for x in arg_list if x.name not in argument_sequence]
+            if missing:
+                msg = "Argument list didn't specify: {0} "
+                msg = msg.format(", ".join([str(m.name) for m in missing]))
+                raise CodeGenArgumentListError(msg, missing)
+
+            # create redundant arguments to produce the requested sequence
+            name_arg_dict = {x.name: x for x in arg_list}
+            new_args = []
+            for symbol in argument_sequence:
+                try:
+                    new_args.append(name_arg_dict[symbol])
+                except KeyError:
+                    new_args.append(InputArgument(symbol))
+            arg_list = new_args
+
+        return Routine(name, arg_list, return_vals, local_vars, global_vars)
+
+    def _get_header(self):
+        """Writes a common header for the generated files."""
+        code_lines = []
+        tmp = header_comment % {"version": sympy_version,
+            "project": self.project}
+        for line in tmp.splitlines():
+            if line == '':
+                code_lines.append("%\n")
+            else:
+                code_lines.append("%%   %s\n" % line)
+        return code_lines
+
+    def _preprocessor_statements(self, prefix):
+        return []
+
+    def _get_routine_opening(self, routine):
+        """Returns the opening statements of the routine."""
+        code_list = []
+        code_list.append("function ")
+
+        # Outputs
+        outs = []
+        for result in routine.results:
+            if isinstance(result, Result):
+                # Note: name not result_var; want `y` not `y(i)` for Indexed
+                s = self._get_symbol(result.name)
+            else:
+                raise CodeGenError("unexpected object in Routine results")
+            outs.append(s)
+        if len(outs) > 1:
+            code_list.append("[" + (", ".join(outs)) + "]")
+        else:
+            code_list.append("".join(outs))
+        code_list.append(" = ")
+
+        # Inputs
+        args = []
+        for arg in routine.arguments:
+            if isinstance(arg, (OutputArgument, InOutArgument)):
+                raise CodeGenError("Octave: invalid argument of type %s" %
+                                   str(type(arg)))
+            if isinstance(arg, InputArgument):
+                args.append("%s" % self._get_symbol(arg.name))
+        args = ", ".join(args)
+        code_list.append("%s(%s)\n" % (routine.name, args))
+        code_list = [ "".join(code_list) ]
+
+        return code_list
+
+    def _declare_arguments(self, routine):
+        return []
+
+    def _declare_globals(self, routine):
+        if not routine.global_vars:
+            return []
+        s = " ".join(sorted([self._get_symbol(g) for g in routine.global_vars]))
+        return ["global " + s + "\n"]
+
+    def _declare_locals(self, routine):
+        return []
+
+    def _get_routine_ending(self, routine):
+        return ["end\n"]
+
+    def _call_printer(self, routine):
+        declarations = []
+        code_lines = []
+        for result in routine.results:
+            if isinstance(result, Result):
+                assign_to = result.result_var
+            else:
+                raise CodeGenError("unexpected object in Routine results")
+
+            constants, not_supported, oct_expr = self._printer_method_with_settings(
+                'doprint', {"human": False, "strict": False}, result.expr, assign_to=assign_to)
+
+            for obj, v in sorted(constants, key=str):
+                declarations.append(
+                    "  %s = %s;  %% constant\n" % (obj, v))
+            for obj in sorted(not_supported, key=str):
+                if isinstance(obj, Function):
+                    name = obj.func
+                else:
+                    name = obj
+                declarations.append(
+                    "  %% unsupported: %s\n" % (name))
+            code_lines.append("%s\n" % (oct_expr))
+        return declarations + code_lines
+
+    def _indent_code(self, codelines):
+        return self._printer_method_with_settings(
+            'indent_code', {"human": False, "strict": False}, codelines)
+
+    def dump_m(self, routines, f, prefix, header=True, empty=True, inline=True):
+        # Note used to call self.dump_code() but we need more control for header
+
+        code_lines = self._preprocessor_statements(prefix)
+
+        for i, routine in enumerate(routines):
+            if i > 0:
+                if empty:
+                    code_lines.append("\n")
+            code_lines.extend(self._get_routine_opening(routine))
+            if i == 0:
+                if routine.name != prefix:
+                    raise ValueError('Octave function name should match prefix')
+                if header:
+                    code_lines.append("%" + prefix.upper() +
+                                      "  Autogenerated by SymPy\n")
+                    code_lines.append(''.join(self._get_header()))
+            code_lines.extend(self._declare_arguments(routine))
+            code_lines.extend(self._declare_globals(routine))
+            code_lines.extend(self._declare_locals(routine))
+            if empty:
+                code_lines.append("\n")
+            code_lines.extend(self._call_printer(routine))
+            if empty:
+                code_lines.append("\n")
+            code_lines.extend(self._get_routine_ending(routine))
+
+        code_lines = self._indent_code(''.join(code_lines))
+
+        if code_lines:
+            f.write(code_lines)
+
+    dump_m.extension = code_extension  # type: ignore
+    dump_m.__doc__ = CodeGen.dump_code.__doc__
+
+    # This list of dump functions is used by CodeGen.write to know which dump
+    # functions it has to call.
+    dump_fns = [dump_m]
+
+class RustCodeGen(CodeGen):
+    """Generator for Rust code.
+
+    The .write() method inherited from CodeGen will output a code file
+    .rs
+
+    """
+
+    code_extension = "rs"
+
+    def __init__(self, project="project", printer=None):
+        super().__init__(project=project)
+        self.printer = printer or RustCodePrinter()
+
+    def routine(self, name, expr, argument_sequence, global_vars):
+        """Specialized Routine creation for Rust."""
+
+        if is_sequence(expr) and not isinstance(expr, (MatrixBase, MatrixExpr)):
+            if not expr:
+                raise ValueError("No expression given")
+            expressions = Tuple(*expr)
+        else:
+            expressions = Tuple(expr)
+
+        # local variables
+        local_vars = {i.label for i in expressions.atoms(Idx)}
+
+        # global variables
+        global_vars = set() if global_vars is None else set(global_vars)
+
+        # symbols that should be arguments
+        symbols = expressions.free_symbols - local_vars - global_vars - expressions.atoms(Indexed)
+
+        # Rust supports multiple return values
+        return_vals = []
+        output_args = []
+        for (i, expr) in enumerate(expressions):
+            if isinstance(expr, Equality):
+                out_arg = expr.lhs
+                expr = expr.rhs
+                symbol = out_arg
+                if isinstance(out_arg, Indexed):
+                    dims = tuple([ (S.One, dim) for dim in out_arg.shape])
+                    symbol = out_arg.base.label
+                    output_args.append(InOutArgument(symbol, out_arg, expr, dimensions=dims))
+                if not isinstance(out_arg, (Indexed, Symbol, MatrixSymbol)):
+                    raise CodeGenError("Only Indexed, Symbol, or MatrixSymbol "
+                                       "can define output arguments.")
+
+                return_vals.append(Result(expr, name=symbol, result_var=out_arg))
+                if not expr.has(symbol):
+                    # this is a pure output: remove from the symbols list, so
+                    # it doesn't become an input.
+                    symbols.remove(symbol)
+
+            else:
+                # we have no name for this output
+                return_vals.append(Result(expr, name='out%d' % (i+1)))
+
+        # setup input argument list
+        output_args.sort(key=lambda x: str(x.name))
+        arg_list = list(output_args)
+        array_symbols = {}
+        for array in expressions.atoms(Indexed):
+            array_symbols[array.base.label] = array
+        for array in expressions.atoms(MatrixSymbol):
+            array_symbols[array] = array
+
+        for symbol in sorted(symbols, key=str):
+            arg_list.append(InputArgument(symbol))
+
+        if argument_sequence is not None:
+            # if the user has supplied IndexedBase instances, we'll accept that
+            new_sequence = []
+            for arg in argument_sequence:
+                if isinstance(arg, IndexedBase):
+                    new_sequence.append(arg.label)
+                else:
+                    new_sequence.append(arg)
+            argument_sequence = new_sequence
+
+            missing = [x for x in arg_list if x.name not in argument_sequence]
+            if missing:
+                msg = "Argument list didn't specify: {0} "
+                msg = msg.format(", ".join([str(m.name) for m in missing]))
+                raise CodeGenArgumentListError(msg, missing)
+
+            # create redundant arguments to produce the requested sequence
+            name_arg_dict = {x.name: x for x in arg_list}
+            new_args = []
+            for symbol in argument_sequence:
+                try:
+                    new_args.append(name_arg_dict[symbol])
+                except KeyError:
+                    new_args.append(InputArgument(symbol))
+            arg_list = new_args
+
+        return Routine(name, arg_list, return_vals, local_vars, global_vars)
+
+
+    def _get_header(self):
+        """Writes a common header for the generated files."""
+        code_lines = []
+        code_lines.append("/*\n")
+        tmp = header_comment % {"version": sympy_version,
+                                "project": self.project}
+        for line in tmp.splitlines():
+            code_lines.append((" *%s" % line.center(76)).rstrip() + "\n")
+        code_lines.append(" */\n")
+        return code_lines
+
+    def get_prototype(self, routine):
+        """Returns a string for the function prototype of the routine.
+
+        If the routine has multiple result objects, an CodeGenError is
+        raised.
+
+        See: https://en.wikipedia.org/wiki/Function_prototype
+
+        """
+        results = [i.get_datatype('Rust') for i in routine.results]
+
+        if len(results) == 1:
+            rstype = " -> " + results[0]
+        elif len(routine.results) > 1:
+            rstype = " -> (" + ", ".join(results) + ")"
+        else:
+            rstype = ""
+
+        type_args = []
+        for arg in routine.arguments:
+            name = self.printer.doprint(arg.name)
+            if arg.dimensions or isinstance(arg, ResultBase):
+                type_args.append(("*%s" % name, arg.get_datatype('Rust')))
+            else:
+                type_args.append((name, arg.get_datatype('Rust')))
+        arguments = ", ".join([ "%s: %s" % t for t in type_args])
+        return "fn %s(%s)%s" % (routine.name, arguments, rstype)
+
+    def _preprocessor_statements(self, prefix):
+        code_lines = []
+        # code_lines.append("use std::f64::consts::*;\n")
+        return code_lines
+
+    def _get_routine_opening(self, routine):
+        prototype = self.get_prototype(routine)
+        return ["%s {\n" % prototype]
+
+    def _declare_arguments(self, routine):
+        # arguments are declared in prototype
+        return []
+
+    def _declare_globals(self, routine):
+        # global variables are not explicitly declared within C functions
+        return []
+
+    def _declare_locals(self, routine):
+        # loop variables are declared in loop statement
+        return []
+
+    def _call_printer(self, routine):
+
+        code_lines = []
+        declarations = []
+        returns = []
+
+        # Compose a list of symbols to be dereferenced in the function
+        # body. These are the arguments that were passed by a reference
+        # pointer, excluding arrays.
+        dereference = []
+        for arg in routine.arguments:
+            if isinstance(arg, ResultBase) and not arg.dimensions:
+                dereference.append(arg.name)
+
+        for result in routine.results:
+            if isinstance(result, Result):
+                assign_to = result.result_var
+                returns.append(str(result.result_var))
+            else:
+                raise CodeGenError("unexpected object in Routine results")
+
+            constants, not_supported, rs_expr = self._printer_method_with_settings(
+                'doprint', {"human": False, "strict": False}, result.expr, assign_to=assign_to)
+
+            for name, value in sorted(constants, key=str):
+                declarations.append("const %s: f64 = %s;\n" % (name, value))
+
+            for obj in sorted(not_supported, key=str):
+                if isinstance(obj, Function):
+                    name = obj.func
+                else:
+                    name = obj
+                declarations.append("// unsupported: %s\n" % (name))
+
+            code_lines.append("let %s\n" % rs_expr)
+
+        if len(returns) > 1:
+            returns = ['(' + ', '.join(returns) + ')']
+
+        returns.append('\n')
+
+        return declarations + code_lines + returns
+
+    def _get_routine_ending(self, routine):
+        return ["}\n"]
+
+    def dump_rs(self, routines, f, prefix, header=True, empty=True):
+        self.dump_code(routines, f, prefix, header, empty)
+
+    dump_rs.extension = code_extension  # type: ignore
+    dump_rs.__doc__ = CodeGen.dump_code.__doc__
+
+    # This list of dump functions is used by CodeGen.write to know which dump
+    # functions it has to call.
+    dump_fns = [dump_rs]
+
+
+
+
+def get_code_generator(language, project=None, standard=None, printer = None):
+    if language == 'C':
+        if standard is None:
+            pass
+        elif standard.lower() == 'c89':
+            language = 'C89'
+        elif standard.lower() == 'c99':
+            language = 'C99'
+    CodeGenClass = {"C": CCodeGen, "C89": C89CodeGen, "C99": C99CodeGen,
+                    "F95": FCodeGen, "JULIA": JuliaCodeGen,
+                    "OCTAVE": OctaveCodeGen,
+                    "RUST": RustCodeGen}.get(language.upper())
+    if CodeGenClass is None:
+        raise ValueError("Language '%s' is not supported." % language)
+    return CodeGenClass(project, printer)
+
+
+#
+# Friendly functions
+#
+
+
+def codegen(name_expr, language=None, prefix=None, project="project",
+            to_files=False, header=True, empty=True, argument_sequence=None,
+            global_vars=None, standard=None, code_gen=None, printer=None):
+    """Generate source code for expressions in a given language.
+
+    Parameters
+    ==========
+
+    name_expr : tuple, or list of tuples
+        A single (name, expression) tuple or a list of (name, expression)
+        tuples.  Each tuple corresponds to a routine.  If the expression is
+        an equality (an instance of class Equality) the left hand side is
+        considered an output argument.  If expression is an iterable, then
+        the routine will have multiple outputs.
+
+    language : string,
+        A string that indicates the source code language.  This is case
+        insensitive.  Currently, 'C', 'F95' and 'Octave' are supported.
+        'Octave' generates code compatible with both Octave and Matlab.
+
+    prefix : string, optional
+        A prefix for the names of the files that contain the source code.
+        Language-dependent suffixes will be appended.  If omitted, the name
+        of the first name_expr tuple is used.
+
+    project : string, optional
+        A project name, used for making unique preprocessor instructions.
+        [default: "project"]
+
+    to_files : bool, optional
+        When True, the code will be written to one or more files with the
+        given prefix, otherwise strings with the names and contents of
+        these files are returned. [default: False]
+
+    header : bool, optional
+        When True, a header is written on top of each source file.
+        [default: True]
+
+    empty : bool, optional
+        When True, empty lines are used to structure the code.
+        [default: True]
+
+    argument_sequence : iterable, optional
+        Sequence of arguments for the routine in a preferred order.  A
+        CodeGenError is raised if required arguments are missing.
+        Redundant arguments are used without warning.  If omitted,
+        arguments will be ordered alphabetically, but with all input
+        arguments first, and then output or in-out arguments.
+
+    global_vars : iterable, optional
+        Sequence of global variables used by the routine.  Variables
+        listed here will not show up as function arguments.
+
+    standard : string, optional
+
+    code_gen : CodeGen instance, optional
+        An instance of a CodeGen subclass. Overrides ``language``.
+
+    printer : Printer instance, optional
+        An instance of a Printer subclass.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.codegen import codegen
+    >>> from sympy.abc import x, y, z
+    >>> [(c_name, c_code), (h_name, c_header)] = codegen(
+    ...     ("f", x+y*z), "C89", "test", header=False, empty=False)
+    >>> print(c_name)
+    test.c
+    >>> print(c_code)
+    #include "test.h"
+    #include 
+    double f(double x, double y, double z) {
+       double f_result;
+       f_result = x + y*z;
+       return f_result;
+    }
+    
+    >>> print(h_name)
+    test.h
+    >>> print(c_header)
+    #ifndef PROJECT__TEST__H
+    #define PROJECT__TEST__H
+    double f(double x, double y, double z);
+    #endif
+    
+
+    Another example using Equality objects to give named outputs.  Here the
+    filename (prefix) is taken from the first (name, expr) pair.
+
+    >>> from sympy.abc import f, g
+    >>> from sympy import Eq
+    >>> [(c_name, c_code), (h_name, c_header)] = codegen(
+    ...      [("myfcn", x + y), ("fcn2", [Eq(f, 2*x), Eq(g, y)])],
+    ...      "C99", header=False, empty=False)
+    >>> print(c_name)
+    myfcn.c
+    >>> print(c_code)
+    #include "myfcn.h"
+    #include 
+    double myfcn(double x, double y) {
+       double myfcn_result;
+       myfcn_result = x + y;
+       return myfcn_result;
+    }
+    void fcn2(double x, double y, double *f, double *g) {
+       (*f) = 2*x;
+       (*g) = y;
+    }
+    
+
+    If the generated function(s) will be part of a larger project where various
+    global variables have been defined, the 'global_vars' option can be used
+    to remove the specified variables from the function signature
+
+    >>> from sympy.utilities.codegen import codegen
+    >>> from sympy.abc import x, y, z
+    >>> [(f_name, f_code), header] = codegen(
+    ...     ("f", x+y*z), "F95", header=False, empty=False,
+    ...     argument_sequence=(x, y), global_vars=(z,))
+    >>> print(f_code)
+    REAL*8 function f(x, y)
+    implicit none
+    REAL*8, intent(in) :: x
+    REAL*8, intent(in) :: y
+    f = x + y*z
+    end function
+    
+
+    """
+
+    # Initialize the code generator.
+    if language is None:
+        if code_gen is None:
+            raise ValueError("Need either language or code_gen")
+    else:
+        if code_gen is not None:
+            raise ValueError("You cannot specify both language and code_gen.")
+        code_gen = get_code_generator(language, project, standard, printer)
+
+    if isinstance(name_expr[0], str):
+        # single tuple is given, turn it into a singleton list with a tuple.
+        name_expr = [name_expr]
+
+    if prefix is None:
+        prefix = name_expr[0][0]
+
+    # Construct Routines appropriate for this code_gen from (name, expr) pairs.
+    routines = []
+    for name, expr in name_expr:
+        routines.append(code_gen.routine(name, expr, argument_sequence,
+                                         global_vars))
+
+    # Write the code.
+    return code_gen.write(routines, prefix, to_files, header, empty)
+
+
+def make_routine(name, expr, argument_sequence=None,
+                 global_vars=None, language="F95"):
+    """A factory that makes an appropriate Routine from an expression.
+
+    Parameters
+    ==========
+
+    name : string
+        The name of this routine in the generated code.
+
+    expr : expression or list/tuple of expressions
+        A SymPy expression that the Routine instance will represent.  If
+        given a list or tuple of expressions, the routine will be
+        considered to have multiple return values and/or output arguments.
+
+    argument_sequence : list or tuple, optional
+        List arguments for the routine in a preferred order.  If omitted,
+        the results are language dependent, for example, alphabetical order
+        or in the same order as the given expressions.
+
+    global_vars : iterable, optional
+        Sequence of global variables used by the routine.  Variables
+        listed here will not show up as function arguments.
+
+    language : string, optional
+        Specify a target language.  The Routine itself should be
+        language-agnostic but the precise way one is created, error
+        checking, etc depend on the language.  [default: "F95"].
+
+    Notes
+    =====
+
+    A decision about whether to use output arguments or return values is made
+    depending on both the language and the particular mathematical expressions.
+    For an expression of type Equality, the left hand side is typically made
+    into an OutputArgument (or perhaps an InOutArgument if appropriate).
+    Otherwise, typically, the calculated expression is made a return values of
+    the routine.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.codegen import make_routine
+    >>> from sympy.abc import x, y, f, g
+    >>> from sympy import Eq
+    >>> r = make_routine('test', [Eq(f, 2*x), Eq(g, x + y)])
+    >>> [arg.result_var for arg in r.results]
+    []
+    >>> [arg.name for arg in r.arguments]
+    [x, y, f, g]
+    >>> [arg.name for arg in r.result_variables]
+    [f, g]
+    >>> r.local_vars
+    set()
+
+    Another more complicated example with a mixture of specified and
+    automatically-assigned names.  Also has Matrix output.
+
+    >>> from sympy import Matrix
+    >>> r = make_routine('fcn', [x*y, Eq(f, 1), Eq(g, x + g), Matrix([[x, 2]])])
+    >>> [arg.result_var for arg in r.results]  # doctest: +SKIP
+    [result_5397460570204848505]
+    >>> [arg.expr for arg in r.results]
+    [x*y]
+    >>> [arg.name for arg in r.arguments]  # doctest: +SKIP
+    [x, y, f, g, out_8598435338387848786]
+
+    We can examine the various arguments more closely:
+
+    >>> from sympy.utilities.codegen import (InputArgument, OutputArgument,
+    ...                                      InOutArgument)
+    >>> [a.name for a in r.arguments if isinstance(a, InputArgument)]
+    [x, y]
+
+    >>> [a.name for a in r.arguments if isinstance(a, OutputArgument)]  # doctest: +SKIP
+    [f, out_8598435338387848786]
+    >>> [a.expr for a in r.arguments if isinstance(a, OutputArgument)]
+    [1, Matrix([[x, 2]])]
+
+    >>> [a.name for a in r.arguments if isinstance(a, InOutArgument)]
+    [g]
+    >>> [a.expr for a in r.arguments if isinstance(a, InOutArgument)]
+    [g + x]
+
+    """
+
+    # initialize a new code generator
+    code_gen = get_code_generator(language)
+
+    return code_gen.routine(name, expr, argument_sequence, global_vars)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/decorator.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/decorator.py
new file mode 100644
index 0000000000000000000000000000000000000000..82636c35e9f235a1d23aa7df5182418db3ef6b4f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/decorator.py
@@ -0,0 +1,339 @@
+"""Useful utility decorators. """
+
+from typing import TypeVar
+import sys
+import types
+import inspect
+from functools import wraps, update_wrapper
+
+from sympy.utilities.exceptions import sympy_deprecation_warning
+
+
+T = TypeVar('T')
+"""A generic type"""
+
+
+def threaded_factory(func, use_add):
+    """A factory for ``threaded`` decorators. """
+    from sympy.core import sympify
+    from sympy.matrices import MatrixBase
+    from sympy.utilities.iterables import iterable
+
+    @wraps(func)
+    def threaded_func(expr, *args, **kwargs):
+        if isinstance(expr, MatrixBase):
+            return expr.applyfunc(lambda f: func(f, *args, **kwargs))
+        elif iterable(expr):
+            try:
+                return expr.__class__([func(f, *args, **kwargs) for f in expr])
+            except TypeError:
+                return expr
+        else:
+            expr = sympify(expr)
+
+            if use_add and expr.is_Add:
+                return expr.__class__(*[ func(f, *args, **kwargs) for f in expr.args ])
+            elif expr.is_Relational:
+                return expr.__class__(func(expr.lhs, *args, **kwargs),
+                                      func(expr.rhs, *args, **kwargs))
+            else:
+                return func(expr, *args, **kwargs)
+
+    return threaded_func
+
+
+def threaded(func):
+    """Apply ``func`` to sub--elements of an object, including :class:`~.Add`.
+
+    This decorator is intended to make it uniformly possible to apply a
+    function to all elements of composite objects, e.g. matrices, lists, tuples
+    and other iterable containers, or just expressions.
+
+    This version of :func:`threaded` decorator allows threading over
+    elements of :class:`~.Add` class. If this behavior is not desirable
+    use :func:`xthreaded` decorator.
+
+    Functions using this decorator must have the following signature::
+
+      @threaded
+      def function(expr, *args, **kwargs):
+
+    """
+    return threaded_factory(func, True)
+
+
+def xthreaded(func):
+    """Apply ``func`` to sub--elements of an object, excluding :class:`~.Add`.
+
+    This decorator is intended to make it uniformly possible to apply a
+    function to all elements of composite objects, e.g. matrices, lists, tuples
+    and other iterable containers, or just expressions.
+
+    This version of :func:`threaded` decorator disallows threading over
+    elements of :class:`~.Add` class. If this behavior is not desirable
+    use :func:`threaded` decorator.
+
+    Functions using this decorator must have the following signature::
+
+      @xthreaded
+      def function(expr, *args, **kwargs):
+
+    """
+    return threaded_factory(func, False)
+
+
+def conserve_mpmath_dps(func):
+    """After the function finishes, resets the value of ``mpmath.mp.dps`` to
+    the value it had before the function was run."""
+    import mpmath
+
+    def func_wrapper(*args, **kwargs):
+        dps = mpmath.mp.dps
+        try:
+            return func(*args, **kwargs)
+        finally:
+            mpmath.mp.dps = dps
+
+    func_wrapper = update_wrapper(func_wrapper, func)
+    return func_wrapper
+
+
+class no_attrs_in_subclass:
+    """Don't 'inherit' certain attributes from a base class
+
+    >>> from sympy.utilities.decorator import no_attrs_in_subclass
+
+    >>> class A(object):
+    ...     x = 'test'
+
+    >>> A.x = no_attrs_in_subclass(A, A.x)
+
+    >>> class B(A):
+    ...     pass
+
+    >>> hasattr(A, 'x')
+    True
+    >>> hasattr(B, 'x')
+    False
+
+    """
+    def __init__(self, cls, f):
+        self.cls = cls
+        self.f = f
+
+    def __get__(self, instance, owner=None):
+        if owner == self.cls:
+            if hasattr(self.f, '__get__'):
+                return self.f.__get__(instance, owner)
+            return self.f
+        raise AttributeError
+
+
+def doctest_depends_on(exe=None, modules=None, disable_viewers=None,
+                       python_version=None, ground_types=None):
+    """
+    Adds metadata about the dependencies which need to be met for doctesting
+    the docstrings of the decorated objects.
+
+    ``exe`` should be a list of executables
+
+    ``modules`` should be a list of modules
+
+    ``disable_viewers`` should be a list of viewers for :func:`~sympy.printing.preview.preview` to disable
+
+    ``python_version`` should be the minimum Python version required, as a tuple
+    (like ``(3, 0)``)
+    """
+    dependencies = {}
+    if exe is not None:
+        dependencies['executables'] = exe
+    if modules is not None:
+        dependencies['modules'] = modules
+    if disable_viewers is not None:
+        dependencies['disable_viewers'] = disable_viewers
+    if python_version is not None:
+        dependencies['python_version'] = python_version
+    if ground_types is not None:
+        dependencies['ground_types'] = ground_types
+
+    def skiptests():
+        from sympy.testing.runtests import DependencyError, SymPyDocTests, PyTestReporter # lazy import
+        r = PyTestReporter()
+        t = SymPyDocTests(r, None)
+        try:
+            t._check_dependencies(**dependencies)
+        except DependencyError:
+            return True  # Skip doctests
+        else:
+            return False # Run doctests
+
+    def depends_on_deco(fn):
+        fn._doctest_depends_on = dependencies
+        fn.__doctest_skip__ = skiptests
+
+        if inspect.isclass(fn):
+            fn._doctest_depdends_on = no_attrs_in_subclass(
+                fn, fn._doctest_depends_on)
+            fn.__doctest_skip__ = no_attrs_in_subclass(
+                fn, fn.__doctest_skip__)
+        return fn
+
+    return depends_on_deco
+
+
+def public(obj: T) -> T:
+    """
+    Append ``obj``'s name to global ``__all__`` variable (call site).
+
+    By using this decorator on functions or classes you achieve the same goal
+    as by filling ``__all__`` variables manually, you just do not have to repeat
+    yourself (object's name). You also know if object is public at definition
+    site, not at some random location (where ``__all__`` was set).
+
+    Note that in multiple decorator setup (in almost all cases) ``@public``
+    decorator must be applied before any other decorators, because it relies
+    on the pointer to object's global namespace. If you apply other decorators
+    first, ``@public`` may end up modifying the wrong namespace.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.decorator import public
+
+    >>> __all__ # noqa: F821
+    Traceback (most recent call last):
+    ...
+    NameError: name '__all__' is not defined
+
+    >>> @public
+    ... def some_function():
+    ...     pass
+
+    >>> __all__ # noqa: F821
+    ['some_function']
+
+    """
+    if isinstance(obj, types.FunctionType):
+        ns = obj.__globals__
+        name = obj.__name__
+    elif isinstance(obj, (type(type), type)):
+        ns = sys.modules[obj.__module__].__dict__
+        name = obj.__name__
+    else:
+        raise TypeError("expected a function or a class, got %s" % obj)
+
+    if "__all__" not in ns:
+        ns["__all__"] = [name]
+    else:
+        ns["__all__"].append(name)
+
+    return obj
+
+
+def memoize_property(propfunc):
+    """Property decorator that caches the value of potentially expensive
+    ``propfunc`` after the first evaluation. The cached value is stored in
+    the corresponding property name with an attached underscore."""
+    attrname = '_' + propfunc.__name__
+    sentinel = object()
+
+    @wraps(propfunc)
+    def accessor(self):
+        val = getattr(self, attrname, sentinel)
+        if val is sentinel:
+            val = propfunc(self)
+            setattr(self, attrname, val)
+        return val
+
+    return property(accessor)
+
+
+def deprecated(message, *, deprecated_since_version,
+               active_deprecations_target, stacklevel=3):
+    '''
+    Mark a function as deprecated.
+
+    This decorator should be used if an entire function or class is
+    deprecated. If only a certain functionality is deprecated, you should use
+    :func:`~.warns_deprecated_sympy` directly. This decorator is just a
+    convenience. There is no functional difference between using this
+    decorator and calling ``warns_deprecated_sympy()`` at the top of the
+    function.
+
+    The decorator takes the same arguments as
+    :func:`~.warns_deprecated_sympy`. See its
+    documentation for details on what the keywords to this decorator do.
+
+    See the :ref:`deprecation-policy` document for details on when and how
+    things should be deprecated in SymPy.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.decorator import deprecated
+    >>> from sympy import simplify
+    >>> @deprecated("""\
+    ... The simplify_this(expr) function is deprecated. Use simplify(expr)
+    ... instead.""", deprecated_since_version="1.1",
+    ... active_deprecations_target='simplify-this-deprecation')
+    ... def simplify_this(expr):
+    ...     """
+    ...     Simplify ``expr``.
+    ...
+    ...     .. deprecated:: 1.1
+    ...
+    ...        The ``simplify_this`` function is deprecated. Use :func:`simplify`
+    ...        instead. See its documentation for more information. See
+    ...        :ref:`simplify-this-deprecation` for details.
+    ...
+    ...     """
+    ...     return simplify(expr)
+    >>> from sympy.abc import x
+    >>> simplify_this(x*(x + 1) - x**2) # doctest: +SKIP
+    :1: SymPyDeprecationWarning:
+    
+    The simplify_this(expr) function is deprecated. Use simplify(expr)
+    instead.
+    
+    See https://docs.sympy.org/latest/explanation/active-deprecations.html#simplify-this-deprecation
+    for details.
+    
+    This has been deprecated since SymPy version 1.1. It
+    will be removed in a future version of SymPy.
+    
+      simplify_this(x)
+    x
+
+    See Also
+    ========
+    sympy.utilities.exceptions.SymPyDeprecationWarning
+    sympy.utilities.exceptions.sympy_deprecation_warning
+    sympy.utilities.exceptions.ignore_warnings
+    sympy.testing.pytest.warns_deprecated_sympy
+
+    '''
+    decorator_kwargs = {"deprecated_since_version": deprecated_since_version,
+               "active_deprecations_target": active_deprecations_target}
+    def deprecated_decorator(wrapped):
+        if hasattr(wrapped, '__mro__'):  # wrapped is actually a class
+            class wrapper(wrapped):
+                __doc__ = wrapped.__doc__
+                __module__ = wrapped.__module__
+                _sympy_deprecated_func = wrapped
+                if '__new__' in wrapped.__dict__:
+                    def __new__(cls, *args, **kwargs):
+                        sympy_deprecation_warning(message, **decorator_kwargs, stacklevel=stacklevel)
+                        return super().__new__(cls, *args, **kwargs)
+                else:
+                    def __init__(self, *args, **kwargs):
+                        sympy_deprecation_warning(message, **decorator_kwargs, stacklevel=stacklevel)
+                        super().__init__(*args, **kwargs)
+            wrapper.__name__ = wrapped.__name__
+        else:
+            @wraps(wrapped)
+            def wrapper(*args, **kwargs):
+                sympy_deprecation_warning(message, **decorator_kwargs, stacklevel=stacklevel)
+                return wrapped(*args, **kwargs)
+            wrapper._sympy_deprecated_func = wrapped
+        return wrapper
+    return deprecated_decorator
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/enumerative.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/enumerative.py
new file mode 100644
index 0000000000000000000000000000000000000000..dcdabf064ad6291282b5905e7aed0ba9eb412d1a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/enumerative.py
@@ -0,0 +1,1155 @@
+"""
+Algorithms and classes to support enumerative combinatorics.
+
+Currently just multiset partitions, but more could be added.
+
+Terminology (following Knuth, algorithm 7.1.2.5M TAOCP)
+*multiset* aaabbcccc has a *partition* aaabc | bccc
+
+The submultisets, aaabc and bccc of the partition are called
+*parts*, or sometimes *vectors*.  (Knuth notes that multiset
+partitions can be thought of as partitions of vectors of integers,
+where the ith element of the vector gives the multiplicity of
+element i.)
+
+The values a, b and c are *components* of the multiset.  These
+correspond to elements of a set, but in a multiset can be present
+with a multiplicity greater than 1.
+
+The algorithm deserves some explanation.
+
+Think of the part aaabc from the multiset above.  If we impose an
+ordering on the components of the multiset, we can represent a part
+with a vector, in which the value of the first element of the vector
+corresponds to the multiplicity of the first component in that
+part. Thus, aaabc can be represented by the vector [3, 1, 1].  We
+can also define an ordering on parts, based on the lexicographic
+ordering of the vector (leftmost vector element, i.e., the element
+with the smallest component number, is the most significant), so
+that [3, 1, 1] > [3, 1, 0] and [3, 1, 1] > [2, 1, 4].  The ordering
+on parts can be extended to an ordering on partitions: First, sort
+the parts in each partition, left-to-right in decreasing order. Then
+partition A is greater than partition B if A's leftmost/greatest
+part is greater than B's leftmost part.  If the leftmost parts are
+equal, compare the second parts, and so on.
+
+In this ordering, the greatest partition of a given multiset has only
+one part.  The least partition is the one in which the components
+are spread out, one per part.
+
+The enumeration algorithms in this file yield the partitions of the
+argument multiset in decreasing order.  The main data structure is a
+stack of parts, corresponding to the current partition.  An
+important invariant is that the parts on the stack are themselves in
+decreasing order.  This data structure is decremented to find the
+next smaller partition.  Most often, decrementing the partition will
+only involve adjustments to the smallest parts at the top of the
+stack, much as adjacent integers *usually* differ only in their last
+few digits.
+
+Knuth's algorithm uses two main operations on parts:
+
+Decrement - change the part so that it is smaller in the
+  (vector) lexicographic order, but reduced by the smallest amount possible.
+  For example, if the multiset has vector [5,
+  3, 1], and the bottom/greatest part is [4, 2, 1], this part would
+  decrement to [4, 2, 0], while [4, 0, 0] would decrement to [3, 3,
+  1].  A singleton part is never decremented -- [1, 0, 0] is not
+  decremented to [0, 3, 1].  Instead, the decrement operator needs
+  to fail for this case.  In Knuth's pseudocode, the decrement
+  operator is step m5.
+
+Spread unallocated multiplicity - Once a part has been decremented,
+  it cannot be the rightmost part in the partition.  There is some
+  multiplicity that has not been allocated, and new parts must be
+  created above it in the stack to use up this multiplicity.  To
+  maintain the invariant that the parts on the stack are in
+  decreasing order, these new parts must be less than or equal to
+  the decremented part.
+  For example, if the multiset is [5, 3, 1], and its most
+  significant part has just been decremented to [5, 3, 0], the
+  spread operation will add a new part so that the stack becomes
+  [[5, 3, 0], [0, 0, 1]].  If the most significant part (for the
+  same multiset) has been decremented to [2, 0, 0] the stack becomes
+  [[2, 0, 0], [2, 0, 0], [1, 3, 1]].  In the pseudocode, the spread
+  operation for one part is step m2.  The complete spread operation
+  is a loop of steps m2 and m3.
+
+In order to facilitate the spread operation, Knuth stores, for each
+component of each part, not just the multiplicity of that component
+in the part, but also the total multiplicity available for this
+component in this part or any lesser part above it on the stack.
+
+One added twist is that Knuth does not represent the part vectors as
+arrays. Instead, he uses a sparse representation, in which a
+component of a part is represented as a component number (c), plus
+the multiplicity of the component in that part (v) as well as the
+total multiplicity available for that component (u).  This saves
+time that would be spent skipping over zeros.
+
+"""
+
+class PartComponent:
+    """Internal class used in support of the multiset partitions
+    enumerators and the associated visitor functions.
+
+    Represents one component of one part of the current partition.
+
+    A stack of these, plus an auxiliary frame array, f, represents a
+    partition of the multiset.
+
+    Knuth's pseudocode makes c, u, and v separate arrays.
+    """
+
+    __slots__ = ('c', 'u', 'v')
+
+    def __init__(self):
+        self.c = 0   # Component number
+        self.u = 0   # The as yet unpartitioned amount in component c
+                     # *before* it is allocated by this triple
+        self.v = 0   # Amount of c component in the current part
+                     # (v<=u).  An invariant of the representation is
+                     # that the next higher triple for this component
+                     # (if there is one) will have a value of u-v in
+                     # its u attribute.
+
+    def __repr__(self):
+        "for debug/algorithm animation purposes"
+        return 'c:%d u:%d v:%d' % (self.c, self.u, self.v)
+
+    def __eq__(self, other):
+        """Define  value oriented equality, which is useful for testers"""
+        return (isinstance(other, self.__class__) and
+                self.c == other.c and
+                self.u == other.u and
+                self.v == other.v)
+
+    def __ne__(self, other):
+        """Defined for consistency with __eq__"""
+        return not self == other
+
+
+# This function tries to be a faithful implementation of algorithm
+# 7.1.2.5M in Volume 4A, Combinatoral Algorithms, Part 1, of The Art
+# of Computer Programming, by Donald Knuth.  This includes using
+# (mostly) the same variable names, etc.  This makes for rather
+# low-level Python.
+
+# Changes from Knuth's pseudocode include
+# - use PartComponent struct/object instead of 3 arrays
+# - make the function a generator
+# - map (with some difficulty) the GOTOs to Python control structures.
+# - Knuth uses 1-based numbering for components, this code is 0-based
+# - renamed variable l to lpart.
+# - flag variable x takes on values True/False instead of 1/0
+#
+def multiset_partitions_taocp(multiplicities):
+    """Enumerates partitions of a multiset.
+
+    Parameters
+    ==========
+
+    multiplicities
+         list of integer multiplicities of the components of the multiset.
+
+    Yields
+    ======
+
+    state
+        Internal data structure which encodes a particular partition.
+        This output is then usually processed by a visitor function
+        which combines the information from this data structure with
+        the components themselves to produce an actual partition.
+
+        Unless they wish to create their own visitor function, users will
+        have little need to look inside this data structure.  But, for
+        reference, it is a 3-element list with components:
+
+        f
+            is a frame array, which is used to divide pstack into parts.
+
+        lpart
+            points to the base of the topmost part.
+
+        pstack
+            is an array of PartComponent objects.
+
+        The ``state`` output offers a peek into the internal data
+        structures of the enumeration function.  The client should
+        treat this as read-only; any modification of the data
+        structure will cause unpredictable (and almost certainly
+        incorrect) results.  Also, the components of ``state`` are
+        modified in place at each iteration.  Hence, the visitor must
+        be called at each loop iteration.  Accumulating the ``state``
+        instances and processing them later will not work.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.enumerative import list_visitor
+    >>> from sympy.utilities.enumerative import multiset_partitions_taocp
+    >>> # variables components and multiplicities represent the multiset 'abb'
+    >>> components = 'ab'
+    >>> multiplicities = [1, 2]
+    >>> states = multiset_partitions_taocp(multiplicities)
+    >>> list(list_visitor(state, components) for state in states)
+    [[['a', 'b', 'b']],
+    [['a', 'b'], ['b']],
+    [['a'], ['b', 'b']],
+    [['a'], ['b'], ['b']]]
+
+    See Also
+    ========
+
+    sympy.utilities.iterables.multiset_partitions: Takes a multiset
+        as input and directly yields multiset partitions.  It
+        dispatches to a number of functions, including this one, for
+        implementation.  Most users will find it more convenient to
+        use than multiset_partitions_taocp.
+
+    """
+
+    # Important variables.
+    # m is the number of components, i.e., number of distinct elements
+    m = len(multiplicities)
+    # n is the cardinality, total number of elements whether or not distinct
+    n = sum(multiplicities)
+
+    # The main data structure, f segments pstack into parts.  See
+    # list_visitor() for example code indicating how this internal
+    # state corresponds to a partition.
+
+    # Note: allocation of space for stack is conservative.  Knuth's
+    # exercise 7.2.1.5.68 gives some indication of how to tighten this
+    # bound, but this is not implemented.
+    pstack = [PartComponent() for i in range(n * m + 1)]
+    f = [0] * (n + 1)
+
+    # Step M1 in Knuth (Initialize)
+    # Initial state - entire multiset in one part.
+    for j in range(m):
+        ps = pstack[j]
+        ps.c = j
+        ps.u = multiplicities[j]
+        ps.v = multiplicities[j]
+
+    # Other variables
+    f[0] = 0
+    a = 0
+    lpart = 0
+    f[1] = m
+    b = m  # in general, current stack frame is from a to b - 1
+
+    while True:
+        while True:
+            # Step M2 (Subtract v from u)
+            k = b
+            x = False
+            for j in range(a, b):
+                pstack[k].u = pstack[j].u - pstack[j].v
+                if pstack[k].u == 0:
+                    x = True
+                elif not x:
+                    pstack[k].c = pstack[j].c
+                    pstack[k].v = min(pstack[j].v, pstack[k].u)
+                    x = pstack[k].u < pstack[j].v
+                    k = k + 1
+                else:  # x is True
+                    pstack[k].c = pstack[j].c
+                    pstack[k].v = pstack[k].u
+                    k = k + 1
+                # Note: x is True iff v has changed
+
+            # Step M3 (Push if nonzero.)
+            if k > b:
+                a = b
+                b = k
+                lpart = lpart + 1
+                f[lpart + 1] = b
+                # Return to M2
+            else:
+                break  # Continue to M4
+
+        # M4  Visit a partition
+        state = [f, lpart, pstack]
+        yield state
+
+        # M5 (Decrease v)
+        while True:
+            j = b-1
+            while (pstack[j].v == 0):
+                j = j - 1
+            if j == a and pstack[j].v == 1:
+                # M6 (Backtrack)
+                if lpart == 0:
+                    return
+                lpart = lpart - 1
+                b = a
+                a = f[lpart]
+                # Return to M5
+            else:
+                pstack[j].v = pstack[j].v - 1
+                for k in range(j + 1, b):
+                    pstack[k].v = pstack[k].u
+                break  # GOTO M2
+
+# --------------- Visitor functions for multiset partitions ---------------
+# A visitor takes the partition state generated by
+# multiset_partitions_taocp or other enumerator, and produces useful
+# output (such as the actual partition).
+
+
+def factoring_visitor(state, primes):
+    """Use with multiset_partitions_taocp to enumerate the ways a
+    number can be expressed as a product of factors.  For this usage,
+    the exponents of the prime factors of a number are arguments to
+    the partition enumerator, while the corresponding prime factors
+    are input here.
+
+    Examples
+    ========
+
+    To enumerate the factorings of a number we can think of the elements of the
+    partition as being the prime factors and the multiplicities as being their
+    exponents.
+
+    >>> from sympy.utilities.enumerative import factoring_visitor
+    >>> from sympy.utilities.enumerative import multiset_partitions_taocp
+    >>> from sympy import factorint
+    >>> primes, multiplicities = zip(*factorint(24).items())
+    >>> primes
+    (2, 3)
+    >>> multiplicities
+    (3, 1)
+    >>> states = multiset_partitions_taocp(multiplicities)
+    >>> list(factoring_visitor(state, primes) for state in states)
+    [[24], [8, 3], [12, 2], [4, 6], [4, 2, 3], [6, 2, 2], [2, 2, 2, 3]]
+    """
+    f, lpart, pstack = state
+    factoring = []
+    for i in range(lpart + 1):
+        factor = 1
+        for ps in pstack[f[i]: f[i + 1]]:
+            if ps.v > 0:
+                factor *= primes[ps.c] ** ps.v
+        factoring.append(factor)
+    return factoring
+
+
+def list_visitor(state, components):
+    """Return a list of lists to represent the partition.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.enumerative import list_visitor
+    >>> from sympy.utilities.enumerative import multiset_partitions_taocp
+    >>> states = multiset_partitions_taocp([1, 2, 1])
+    >>> s = next(states)
+    >>> list_visitor(s, 'abc')  # for multiset 'a b b c'
+    [['a', 'b', 'b', 'c']]
+    >>> s = next(states)
+    >>> list_visitor(s, [1, 2, 3])  # for multiset '1 2 2 3
+    [[1, 2, 2], [3]]
+    """
+    f, lpart, pstack = state
+
+    partition = []
+    for i in range(lpart+1):
+        part = []
+        for ps in pstack[f[i]:f[i+1]]:
+            if ps.v > 0:
+                part.extend([components[ps.c]] * ps.v)
+        partition.append(part)
+
+    return partition
+
+
+class MultisetPartitionTraverser():
+    """
+    Has methods to ``enumerate`` and ``count`` the partitions of a multiset.
+
+    This implements a refactored and extended version of Knuth's algorithm
+    7.1.2.5M [AOCP]_."
+
+    The enumeration methods of this class are generators and return
+    data structures which can be interpreted by the same visitor
+    functions used for the output of ``multiset_partitions_taocp``.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.enumerative import MultisetPartitionTraverser
+    >>> m = MultisetPartitionTraverser()
+    >>> m.count_partitions([4,4,4,2])
+    127750
+    >>> m.count_partitions([3,3,3])
+    686
+
+    See Also
+    ========
+
+    multiset_partitions_taocp
+    sympy.utilities.iterables.multiset_partitions
+
+    References
+    ==========
+
+    .. [AOCP] Algorithm 7.1.2.5M in Volume 4A, Combinatoral Algorithms,
+           Part 1, of The Art of Computer Programming, by Donald Knuth.
+
+    .. [Factorisatio] On a Problem of Oppenheim concerning
+           "Factorisatio Numerorum" E. R. Canfield, Paul Erdos, Carl
+           Pomerance, JOURNAL OF NUMBER THEORY, Vol. 17, No. 1. August
+           1983.  See section 7 for a description of an algorithm
+           similar to Knuth's.
+
+    .. [Yorgey] Generating Multiset Partitions, Brent Yorgey, The
+           Monad.Reader, Issue 8, September 2007.
+
+    """
+
+    def __init__(self):
+        self.debug = False
+        # TRACING variables.  These are useful for gathering
+        # statistics on the algorithm itself, but have no particular
+        # benefit to a user of the code.
+        self.k1 = 0
+        self.k2 = 0
+        self.p1 = 0
+        self.pstack = None
+        self.f = None
+        self.lpart = 0
+        self.discarded = 0
+        # dp_stack is list of lists of (part_key, start_count) pairs
+        self.dp_stack = []
+
+        # dp_map is map part_key-> count, where count represents the
+        # number of multiset which are descendants of a part with this
+        # key, **or any of its decrements**
+
+        # Thus, when we find a part in the map, we add its count
+        # value to the running total, cut off the enumeration, and
+        # backtrack
+
+        if not hasattr(self, 'dp_map'):
+            self.dp_map = {}
+
+    def db_trace(self, msg):
+        """Useful for understanding/debugging the algorithms.  Not
+        generally activated in end-user code."""
+        if self.debug:
+            # XXX: animation_visitor is undefined... Clearly this does not
+            # work and was not tested. Previous code in comments below.
+            raise RuntimeError
+            #letters = 'abcdefghijklmnopqrstuvwxyz'
+            #state = [self.f, self.lpart, self.pstack]
+            #print("DBG:", msg,
+            #      ["".join(part) for part in list_visitor(state, letters)],
+            #      animation_visitor(state))
+
+    #
+    # Helper methods for enumeration
+    #
+    def _initialize_enumeration(self, multiplicities):
+        """Allocates and initializes the partition stack.
+
+        This is called from the enumeration/counting routines, so
+        there is no need to call it separately."""
+
+        num_components = len(multiplicities)
+        # cardinality is the total number of elements, whether or not distinct
+        cardinality = sum(multiplicities)
+
+        # pstack is the partition stack, which is segmented by
+        # f into parts.
+        self.pstack = [PartComponent() for i in
+                       range(num_components * cardinality + 1)]
+        self.f = [0] * (cardinality + 1)
+
+        # Initial state - entire multiset in one part.
+        for j in range(num_components):
+            ps = self.pstack[j]
+            ps.c = j
+            ps.u = multiplicities[j]
+            ps.v = multiplicities[j]
+
+        self.f[0] = 0
+        self.f[1] = num_components
+        self.lpart = 0
+
+    # The decrement_part() method corresponds to step M5 in Knuth's
+    # algorithm.  This is the base version for enum_all().  Modified
+    # versions of this method are needed if we want to restrict
+    # sizes of the partitions produced.
+    def decrement_part(self, part):
+        """Decrements part (a subrange of pstack), if possible, returning
+        True iff the part was successfully decremented.
+
+        If you think of the v values in the part as a multi-digit
+        integer (least significant digit on the right) this is
+        basically decrementing that integer, but with the extra
+        constraint that the leftmost digit cannot be decremented to 0.
+
+        Parameters
+        ==========
+
+        part
+           The part, represented as a list of PartComponent objects,
+           which is to be decremented.
+
+        """
+        plen = len(part)
+        for j in range(plen - 1, -1, -1):
+            if j == 0 and part[j].v > 1 or j > 0 and part[j].v > 0:
+                # found val to decrement
+                part[j].v -= 1
+                # Reset trailing parts back to maximum
+                for k in range(j + 1, plen):
+                    part[k].v = part[k].u
+                return True
+        return False
+
+    # Version to allow number of parts to be bounded from above.
+    # Corresponds to (a modified) step M5.
+    def decrement_part_small(self, part, ub):
+        """Decrements part (a subrange of pstack), if possible, returning
+        True iff the part was successfully decremented.
+
+        Parameters
+        ==========
+
+        part
+            part to be decremented (topmost part on the stack)
+
+        ub
+            the maximum number of parts allowed in a partition
+            returned by the calling traversal.
+
+        Notes
+        =====
+
+        The goal of this modification of the ordinary decrement method
+        is to fail (meaning that the subtree rooted at this part is to
+        be skipped) when it can be proved that this part can only have
+        child partitions which are larger than allowed by ``ub``. If a
+        decision is made to fail, it must be accurate, otherwise the
+        enumeration will miss some partitions.  But, it is OK not to
+        capture all the possible failures -- if a part is passed that
+        should not be, the resulting too-large partitions are filtered
+        by the enumeration one level up.  However, as is usual in
+        constrained enumerations, failing early is advantageous.
+
+        The tests used by this method catch the most common cases,
+        although this implementation is by no means the last word on
+        this problem.  The tests include:
+
+        1) ``lpart`` must be less than ``ub`` by at least 2.  This is because
+           once a part has been decremented, the partition
+           will gain at least one child in the spread step.
+
+        2) If the leading component of the part is about to be
+           decremented, check for how many parts will be added in
+           order to use up the unallocated multiplicity in that
+           leading component, and fail if this number is greater than
+           allowed by ``ub``.  (See code for the exact expression.)  This
+           test is given in the answer to Knuth's problem 7.2.1.5.69.
+
+        3) If there is *exactly* enough room to expand the leading
+           component by the above test, check the next component (if
+           it exists) once decrementing has finished.  If this has
+           ``v == 0``, this next component will push the expansion over the
+           limit by 1, so fail.
+        """
+        if self.lpart >= ub - 1:
+            self.p1 += 1  # increment to keep track of usefulness of tests
+            return False
+        plen = len(part)
+        for j in range(plen - 1, -1, -1):
+            # Knuth's mod, (answer to problem 7.2.1.5.69)
+            if j == 0 and (part[0].v - 1)*(ub - self.lpart) < part[0].u:
+                self.k1 += 1
+                return False
+
+            if j == 0 and part[j].v > 1 or j > 0 and part[j].v > 0:
+                # found val to decrement
+                part[j].v -= 1
+                # Reset trailing parts back to maximum
+                for k in range(j + 1, plen):
+                    part[k].v = part[k].u
+
+                # Have now decremented part, but are we doomed to
+                # failure when it is expanded?  Check one oddball case
+                # that turns out to be surprisingly common - exactly
+                # enough room to expand the leading component, but no
+                # room for the second component, which has v=0.
+                if (plen > 1 and part[1].v == 0 and
+                    (part[0].u - part[0].v) ==
+                        ((ub - self.lpart - 1) * part[0].v)):
+                    self.k2 += 1
+                    self.db_trace("Decrement fails test 3")
+                    return False
+                return True
+        return False
+
+    def decrement_part_large(self, part, amt, lb):
+        """Decrements part, while respecting size constraint.
+
+        A part can have no children which are of sufficient size (as
+        indicated by ``lb``) unless that part has sufficient
+        unallocated multiplicity.  When enforcing the size constraint,
+        this method will decrement the part (if necessary) by an
+        amount needed to ensure sufficient unallocated multiplicity.
+
+        Returns True iff the part was successfully decremented.
+
+        Parameters
+        ==========
+
+        part
+            part to be decremented (topmost part on the stack)
+
+        amt
+            Can only take values 0 or 1.  A value of 1 means that the
+            part must be decremented, and then the size constraint is
+            enforced.  A value of 0 means just to enforce the ``lb``
+            size constraint.
+
+        lb
+            The partitions produced by the calling enumeration must
+            have more parts than this value.
+
+        """
+
+        if amt == 1:
+            # In this case we always need to decrement, *before*
+            # enforcing the "sufficient unallocated multiplicity"
+            # constraint.  Easiest for this is just to call the
+            # regular decrement method.
+            if not self.decrement_part(part):
+                return False
+
+        # Next, perform any needed additional decrementing to respect
+        # "sufficient unallocated multiplicity" (or fail if this is
+        # not possible).
+        min_unalloc = lb - self.lpart
+        if min_unalloc <= 0:
+            return True
+        total_mult = sum(pc.u for pc in part)
+        total_alloc = sum(pc.v for pc in part)
+        if total_mult <= min_unalloc:
+            return False
+
+        deficit = min_unalloc - (total_mult - total_alloc)
+        if deficit <= 0:
+            return True
+
+        for i in range(len(part) - 1, -1, -1):
+            if i == 0:
+                if part[0].v > deficit:
+                    part[0].v -= deficit
+                    return True
+                else:
+                    return False  # This shouldn't happen, due to above check
+            else:
+                if part[i].v >= deficit:
+                    part[i].v -= deficit
+                    return True
+                else:
+                    deficit -= part[i].v
+                    part[i].v = 0
+
+    def decrement_part_range(self, part, lb, ub):
+        """Decrements part (a subrange of pstack), if possible, returning
+        True iff the part was successfully decremented.
+
+        Parameters
+        ==========
+
+        part
+            part to be decremented (topmost part on the stack)
+
+        ub
+            the maximum number of parts allowed in a partition
+            returned by the calling traversal.
+
+        lb
+            The partitions produced by the calling enumeration must
+            have more parts than this value.
+
+        Notes
+        =====
+
+        Combines the constraints of _small and _large decrement
+        methods.  If returns success, part has been decremented at
+        least once, but perhaps by quite a bit more if needed to meet
+        the lb constraint.
+        """
+
+        # Constraint in the range case is just enforcing both the
+        # constraints from _small and _large cases.  Note the 0 as the
+        # second argument to the _large call -- this is the signal to
+        # decrement only as needed to for constraint enforcement.  The
+        # short circuiting and left-to-right order of the 'and'
+        # operator is important for this to work correctly.
+        return self.decrement_part_small(part, ub) and \
+            self.decrement_part_large(part, 0, lb)
+
+    def spread_part_multiplicity(self):
+        """Returns True if a new part has been created, and
+        adjusts pstack, f and lpart as needed.
+
+        Notes
+        =====
+
+        Spreads unallocated multiplicity from the current top part
+        into a new part created above the current on the stack.  This
+        new part is constrained to be less than or equal to the old in
+        terms of the part ordering.
+
+        This call does nothing (and returns False) if the current top
+        part has no unallocated multiplicity.
+
+        """
+        j = self.f[self.lpart]  # base of current top part
+        k = self.f[self.lpart + 1]  # ub of current; potential base of next
+        base = k  # save for later comparison
+
+        changed = False  # Set to true when the new part (so far) is
+                         # strictly less than (as opposed to less than
+                         # or equal) to the old.
+        for j in range(self.f[self.lpart], self.f[self.lpart + 1]):
+            self.pstack[k].u = self.pstack[j].u - self.pstack[j].v
+            if self.pstack[k].u == 0:
+                changed = True
+            else:
+                self.pstack[k].c = self.pstack[j].c
+                if changed:  # Put all available multiplicity in this part
+                    self.pstack[k].v = self.pstack[k].u
+                else:  # Still maintaining ordering constraint
+                    if self.pstack[k].u < self.pstack[j].v:
+                        self.pstack[k].v = self.pstack[k].u
+                        changed = True
+                    else:
+                        self.pstack[k].v = self.pstack[j].v
+                k = k + 1
+        if k > base:
+            # Adjust for the new part on stack
+            self.lpart = self.lpart + 1
+            self.f[self.lpart + 1] = k
+            return True
+        return False
+
+    def top_part(self):
+        """Return current top part on the stack, as a slice of pstack.
+
+        """
+        return self.pstack[self.f[self.lpart]:self.f[self.lpart + 1]]
+
+    # Same interface and functionality as multiset_partitions_taocp(),
+    # but some might find this refactored version easier to follow.
+    def enum_all(self, multiplicities):
+        """Enumerate the partitions of a multiset.
+
+        Examples
+        ========
+
+        >>> from sympy.utilities.enumerative import list_visitor
+        >>> from sympy.utilities.enumerative import MultisetPartitionTraverser
+        >>> m = MultisetPartitionTraverser()
+        >>> states = m.enum_all([2,2])
+        >>> list(list_visitor(state, 'ab') for state in states)
+        [[['a', 'a', 'b', 'b']],
+        [['a', 'a', 'b'], ['b']],
+        [['a', 'a'], ['b', 'b']],
+        [['a', 'a'], ['b'], ['b']],
+        [['a', 'b', 'b'], ['a']],
+        [['a', 'b'], ['a', 'b']],
+        [['a', 'b'], ['a'], ['b']],
+        [['a'], ['a'], ['b', 'b']],
+        [['a'], ['a'], ['b'], ['b']]]
+
+        See Also
+        ========
+
+        multiset_partitions_taocp:
+            which provides the same result as this method, but is
+            about twice as fast.  Hence, enum_all is primarily useful
+            for testing.  Also see the function for a discussion of
+            states and visitors.
+
+        """
+        self._initialize_enumeration(multiplicities)
+        while True:
+            while self.spread_part_multiplicity():
+                pass
+
+            # M4  Visit a partition
+            state = [self.f, self.lpart, self.pstack]
+            yield state
+
+            # M5 (Decrease v)
+            while not self.decrement_part(self.top_part()):
+                # M6 (Backtrack)
+                if self.lpart == 0:
+                    return
+                self.lpart -= 1
+
+    def enum_small(self, multiplicities, ub):
+        """Enumerate multiset partitions with no more than ``ub`` parts.
+
+        Equivalent to enum_range(multiplicities, 0, ub)
+
+        Parameters
+        ==========
+
+        multiplicities
+             list of multiplicities of the components of the multiset.
+
+        ub
+            Maximum number of parts
+
+        Examples
+        ========
+
+        >>> from sympy.utilities.enumerative import list_visitor
+        >>> from sympy.utilities.enumerative import MultisetPartitionTraverser
+        >>> m = MultisetPartitionTraverser()
+        >>> states = m.enum_small([2,2], 2)
+        >>> list(list_visitor(state, 'ab') for state in states)
+        [[['a', 'a', 'b', 'b']],
+        [['a', 'a', 'b'], ['b']],
+        [['a', 'a'], ['b', 'b']],
+        [['a', 'b', 'b'], ['a']],
+        [['a', 'b'], ['a', 'b']]]
+
+        The implementation is based, in part, on the answer given to
+        exercise 69, in Knuth [AOCP]_.
+
+        See Also
+        ========
+
+        enum_all, enum_large, enum_range
+
+        """
+
+        # Keep track of iterations which do not yield a partition.
+        # Clearly, we would like to keep this number small.
+        self.discarded = 0
+        if ub <= 0:
+            return
+        self._initialize_enumeration(multiplicities)
+        while True:
+            while self.spread_part_multiplicity():
+                self.db_trace('spread 1')
+                if self.lpart >= ub:
+                    self.discarded += 1
+                    self.db_trace('  Discarding')
+                    self.lpart = ub - 2
+                    break
+            else:
+                # M4  Visit a partition
+                state = [self.f, self.lpart, self.pstack]
+                yield state
+
+            # M5 (Decrease v)
+            while not self.decrement_part_small(self.top_part(), ub):
+                self.db_trace("Failed decrement, going to backtrack")
+                # M6 (Backtrack)
+                if self.lpart == 0:
+                    return
+                self.lpart -= 1
+                self.db_trace("Backtracked to")
+            self.db_trace("decrement ok, about to expand")
+
+    def enum_large(self, multiplicities, lb):
+        """Enumerate the partitions of a multiset with lb < num(parts)
+
+        Equivalent to enum_range(multiplicities, lb, sum(multiplicities))
+
+        Parameters
+        ==========
+
+        multiplicities
+            list of multiplicities of the components of the multiset.
+
+        lb
+            Number of parts in the partition must be greater than
+            this lower bound.
+
+
+        Examples
+        ========
+
+        >>> from sympy.utilities.enumerative import list_visitor
+        >>> from sympy.utilities.enumerative import MultisetPartitionTraverser
+        >>> m = MultisetPartitionTraverser()
+        >>> states = m.enum_large([2,2], 2)
+        >>> list(list_visitor(state, 'ab') for state in states)
+        [[['a', 'a'], ['b'], ['b']],
+        [['a', 'b'], ['a'], ['b']],
+        [['a'], ['a'], ['b', 'b']],
+        [['a'], ['a'], ['b'], ['b']]]
+
+        See Also
+        ========
+
+        enum_all, enum_small, enum_range
+
+        """
+        self.discarded = 0
+        if lb >= sum(multiplicities):
+            return
+        self._initialize_enumeration(multiplicities)
+        self.decrement_part_large(self.top_part(), 0, lb)
+        while True:
+            good_partition = True
+            while self.spread_part_multiplicity():
+                if not self.decrement_part_large(self.top_part(), 0, lb):
+                    # Failure here should be rare/impossible
+                    self.discarded += 1
+                    good_partition = False
+                    break
+
+            # M4  Visit a partition
+            if good_partition:
+                state = [self.f, self.lpart, self.pstack]
+                yield state
+
+            # M5 (Decrease v)
+            while not self.decrement_part_large(self.top_part(), 1, lb):
+                # M6 (Backtrack)
+                if self.lpart == 0:
+                    return
+                self.lpart -= 1
+
+    def enum_range(self, multiplicities, lb, ub):
+
+        """Enumerate the partitions of a multiset with
+        ``lb < num(parts) <= ub``.
+
+        In particular, if partitions with exactly ``k`` parts are
+        desired, call with ``(multiplicities, k - 1, k)``.  This
+        method generalizes enum_all, enum_small, and enum_large.
+
+        Examples
+        ========
+
+        >>> from sympy.utilities.enumerative import list_visitor
+        >>> from sympy.utilities.enumerative import MultisetPartitionTraverser
+        >>> m = MultisetPartitionTraverser()
+        >>> states = m.enum_range([2,2], 1, 2)
+        >>> list(list_visitor(state, 'ab') for state in states)
+        [[['a', 'a', 'b'], ['b']],
+        [['a', 'a'], ['b', 'b']],
+        [['a', 'b', 'b'], ['a']],
+        [['a', 'b'], ['a', 'b']]]
+
+        """
+        # combine the constraints of the _large and _small
+        # enumerations.
+        self.discarded = 0
+        if ub <= 0 or lb >= sum(multiplicities):
+            return
+        self._initialize_enumeration(multiplicities)
+        self.decrement_part_large(self.top_part(), 0, lb)
+        while True:
+            good_partition = True
+            while self.spread_part_multiplicity():
+                self.db_trace("spread 1")
+                if not self.decrement_part_large(self.top_part(), 0, lb):
+                    # Failure here - possible in range case?
+                    self.db_trace("  Discarding (large cons)")
+                    self.discarded += 1
+                    good_partition = False
+                    break
+                elif self.lpart >= ub:
+                    self.discarded += 1
+                    good_partition = False
+                    self.db_trace("  Discarding small cons")
+                    self.lpart = ub - 2
+                    break
+
+            # M4  Visit a partition
+            if good_partition:
+                state = [self.f, self.lpart, self.pstack]
+                yield state
+
+            # M5 (Decrease v)
+            while not self.decrement_part_range(self.top_part(), lb, ub):
+                self.db_trace("Failed decrement, going to backtrack")
+                # M6 (Backtrack)
+                if self.lpart == 0:
+                    return
+                self.lpart -= 1
+                self.db_trace("Backtracked to")
+            self.db_trace("decrement ok, about to expand")
+
+    def count_partitions_slow(self, multiplicities):
+        """Returns the number of partitions of a multiset whose elements
+        have the multiplicities given in ``multiplicities``.
+
+        Primarily for comparison purposes.  It follows the same path as
+        enumerate, and counts, rather than generates, the partitions.
+
+        See Also
+        ========
+
+        count_partitions
+            Has the same calling interface, but is much faster.
+
+        """
+        # number of partitions so far in the enumeration
+        self.pcount = 0
+        self._initialize_enumeration(multiplicities)
+        while True:
+            while self.spread_part_multiplicity():
+                pass
+
+            # M4  Visit (count) a partition
+            self.pcount += 1
+
+            # M5 (Decrease v)
+            while not self.decrement_part(self.top_part()):
+                # M6 (Backtrack)
+                if self.lpart == 0:
+                    return self.pcount
+                self.lpart -= 1
+
+    def count_partitions(self, multiplicities):
+        """Returns the number of partitions of a multiset whose components
+        have the multiplicities given in ``multiplicities``.
+
+        For larger counts, this method is much faster than calling one
+        of the enumerators and counting the result.  Uses dynamic
+        programming to cut down on the number of nodes actually
+        explored.  The dictionary used in order to accelerate the
+        counting process is stored in the ``MultisetPartitionTraverser``
+        object and persists across calls.  If the user does not
+        expect to call ``count_partitions`` for any additional
+        multisets, the object should be cleared to save memory.  On
+        the other hand, the cache built up from one count run can
+        significantly speed up subsequent calls to ``count_partitions``,
+        so it may be advantageous not to clear the object.
+
+        Examples
+        ========
+
+        >>> from sympy.utilities.enumerative import MultisetPartitionTraverser
+        >>> m = MultisetPartitionTraverser()
+        >>> m.count_partitions([9,8,2])
+        288716
+        >>> m.count_partitions([2,2])
+        9
+        >>> del m
+
+        Notes
+        =====
+
+        If one looks at the workings of Knuth's algorithm M [AOCP]_, it
+        can be viewed as a traversal of a binary tree of parts.  A
+        part has (up to) two children, the left child resulting from
+        the spread operation, and the right child from the decrement
+        operation.  The ordinary enumeration of multiset partitions is
+        an in-order traversal of this tree, and with the partitions
+        corresponding to paths from the root to the leaves. The
+        mapping from paths to partitions is a little complicated,
+        since the partition would contain only those parts which are
+        leaves or the parents of a spread link, not those which are
+        parents of a decrement link.
+
+        For counting purposes, it is sufficient to count leaves, and
+        this can be done with a recursive in-order traversal.  The
+        number of leaves of a subtree rooted at a particular part is a
+        function only of that part itself, so memoizing has the
+        potential to speed up the counting dramatically.
+
+        This method follows a computational approach which is similar
+        to the hypothetical memoized recursive function, but with two
+        differences:
+
+        1) This method is iterative, borrowing its structure from the
+           other enumerations and maintaining an explicit stack of
+           parts which are in the process of being counted.  (There
+           may be multisets which can be counted reasonably quickly by
+           this implementation, but which would overflow the default
+           Python recursion limit with a recursive implementation.)
+
+        2) Instead of using the part data structure directly, a more
+           compact key is constructed.  This saves space, but more
+           importantly coalesces some parts which would remain
+           separate with physical keys.
+
+        Unlike the enumeration functions, there is currently no _range
+        version of count_partitions.  If someone wants to stretch
+        their brain, it should be possible to construct one by
+        memoizing with a histogram of counts rather than a single
+        count, and combining the histograms.
+        """
+        # number of partitions so far in the enumeration
+        self.pcount = 0
+
+        # dp_stack is list of lists of (part_key, start_count) pairs
+        self.dp_stack = []
+
+        self._initialize_enumeration(multiplicities)
+        pkey = part_key(self.top_part())
+        self.dp_stack.append([(pkey, 0), ])
+        while True:
+            while self.spread_part_multiplicity():
+                pkey = part_key(self.top_part())
+                if pkey in self.dp_map:
+                    # Already have a cached value for the count of the
+                    # subtree rooted at this part.  Add it to the
+                    # running counter, and break out of the spread
+                    # loop.  The -1 below is to compensate for the
+                    # leaf that this code path would otherwise find,
+                    # and which gets incremented for below.
+
+                    self.pcount += (self.dp_map[pkey] - 1)
+                    self.lpart -= 1
+                    break
+                else:
+                    self.dp_stack.append([(pkey, self.pcount), ])
+
+            # M4  count a leaf partition
+            self.pcount += 1
+
+            # M5 (Decrease v)
+            while not self.decrement_part(self.top_part()):
+                # M6 (Backtrack)
+                for key, oldcount in self.dp_stack.pop():
+                    self.dp_map[key] = self.pcount - oldcount
+                if self.lpart == 0:
+                    return self.pcount
+                self.lpart -= 1
+
+            # At this point have successfully decremented the part on
+            # the stack and it does not appear in the cache.  It needs
+            # to be added to the list at the top of dp_stack
+            pkey = part_key(self.top_part())
+            self.dp_stack[-1].append((pkey, self.pcount),)
+
+
+def part_key(part):
+    """Helper for MultisetPartitionTraverser.count_partitions that
+    creates a key for ``part``, that only includes information which can
+    affect the count for that part.  (Any irrelevant information just
+    reduces the effectiveness of dynamic programming.)
+
+    Notes
+    =====
+
+    This member function is a candidate for future exploration. There
+    are likely symmetries that can be exploited to coalesce some
+    ``part_key`` values, and thereby save space and improve
+    performance.
+
+    """
+    # The component number is irrelevant for counting partitions, so
+    # leave it out of the memo key.
+    rval = []
+    for ps in part:
+        rval.append(ps.u)
+        rval.append(ps.v)
+    return tuple(rval)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/exceptions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..f764a31371ed109d69102777bd9ec0dfb3d75380
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/exceptions.py
@@ -0,0 +1,271 @@
+"""
+General SymPy exceptions and warnings.
+"""
+
+import warnings
+import contextlib
+
+from textwrap import dedent
+
+
+class SymPyDeprecationWarning(DeprecationWarning):
+    r"""
+    A warning for deprecated features of SymPy.
+
+    See the :ref:`deprecation-policy` document for details on when and how
+    things should be deprecated in SymPy.
+
+    Note that simply constructing this class will not cause a warning to be
+    issued. To do that, you must call the :func`sympy_deprecation_warning`
+    function. For this reason, it is not recommended to ever construct this
+    class directly.
+
+    Explanation
+    ===========
+
+    The ``SymPyDeprecationWarning`` class is a subclass of
+    ``DeprecationWarning`` that is used for all deprecations in SymPy. A
+    special subclass is used so that we can automatically augment the warning
+    message with additional metadata about the version the deprecation was
+    introduced in and a link to the documentation. This also allows users to
+    explicitly filter deprecation warnings from SymPy using ``warnings``
+    filters (see :ref:`silencing-sympy-deprecation-warnings`).
+
+    Additionally, ``SymPyDeprecationWarning`` is enabled to be shown by
+    default, unlike normal ``DeprecationWarning``\s, which are only shown by
+    default in interactive sessions. This ensures that deprecation warnings in
+    SymPy will actually be seen by users.
+
+    See the documentation of :func:`sympy_deprecation_warning` for a
+    description of the parameters to this function.
+
+    To mark a function as deprecated, you can use the :func:`@deprecated
+    ` decorator.
+
+    See Also
+    ========
+    sympy.utilities.exceptions.sympy_deprecation_warning
+    sympy.utilities.exceptions.ignore_warnings
+    sympy.utilities.decorator.deprecated
+    sympy.testing.pytest.warns_deprecated_sympy
+
+    """
+    def __init__(self, message, *, deprecated_since_version, active_deprecations_target):
+
+        super().__init__(message, deprecated_since_version,
+                     active_deprecations_target)
+        self.message = message
+        if not isinstance(deprecated_since_version, str):
+            raise TypeError(f"'deprecated_since_version' should be a string, got {deprecated_since_version!r}")
+        self.deprecated_since_version = deprecated_since_version
+        self.active_deprecations_target = active_deprecations_target
+        if any(i in active_deprecations_target for i in '()='):
+            raise ValueError("active_deprecations_target be the part inside of the '(...)='")
+
+        self.full_message = f"""
+
+{dedent(message).strip()}
+
+See https://docs.sympy.org/latest/explanation/active-deprecations.html#{active_deprecations_target}
+for details.
+
+This has been deprecated since SymPy version {deprecated_since_version}. It
+will be removed in a future version of SymPy.
+"""
+
+    def __str__(self):
+        return self.full_message
+
+    def __repr__(self):
+        return f"{self.__class__.__name__}({self.message!r}, deprecated_since_version={self.deprecated_since_version!r}, active_deprecations_target={self.active_deprecations_target!r})"
+
+    def __eq__(self, other):
+        return isinstance(other, SymPyDeprecationWarning) and self.args == other.args
+
+    # Make pickling work. The by default, it tries to recreate the expression
+    # from its args, but this doesn't work because of our keyword-only
+    # arguments.
+    @classmethod
+    def _new(cls, message, deprecated_since_version,
+              active_deprecations_target):
+        return cls(message, deprecated_since_version=deprecated_since_version, active_deprecations_target=active_deprecations_target)
+
+    def __reduce__(self):
+        return (self._new, (self.message, self.deprecated_since_version, self.active_deprecations_target))
+
+# Python by default hides DeprecationWarnings, which we do not want.
+warnings.simplefilter("once", SymPyDeprecationWarning)
+
+def sympy_deprecation_warning(message, *, deprecated_since_version,
+                              active_deprecations_target, stacklevel=3):
+    r'''
+    Warn that a feature is deprecated in SymPy.
+
+    See the :ref:`deprecation-policy` document for details on when and how
+    things should be deprecated in SymPy.
+
+    To mark an entire function or class as deprecated, you can use the
+    :func:`@deprecated ` decorator.
+
+    Parameters
+    ==========
+
+    message : str
+         The deprecation message. This may span multiple lines and contain
+         code examples. Messages should be wrapped to 80 characters. The
+         message is automatically dedented and leading and trailing whitespace
+         stripped. Messages may include dynamic content based on the user
+         input, but avoid using ``str(expression)`` if an expression can be
+         arbitrary, as it might be huge and make the warning message
+         unreadable.
+
+    deprecated_since_version : str
+         The version of SymPy the feature has been deprecated since. For new
+         deprecations, this should be the version in `sympy/release.py
+         `_
+         without the ``.dev``. If the next SymPy version ends up being
+         different from this, the release manager will need to update any
+         ``SymPyDeprecationWarning``\s using the incorrect version. This
+         argument is required and must be passed as a keyword argument.
+         (example:  ``deprecated_since_version="1.10"``).
+
+    active_deprecations_target : str
+        The Sphinx target corresponding to the section for the deprecation in
+        the :ref:`active-deprecations` document (see
+        ``doc/src/explanation/active-deprecations.md``). This is used to
+        automatically generate a URL to the page in the warning message. This
+        argument is required and must be passed as a keyword argument.
+        (example: ``active_deprecations_target="deprecated-feature-abc"``)
+
+    stacklevel : int, default: 3
+        The ``stacklevel`` parameter that is passed to ``warnings.warn``. If
+        you create a wrapper that calls this function, this should be
+        increased so that the warning message shows the user line of code that
+        produced the warning. Note that in some cases there will be multiple
+        possible different user code paths that could result in the warning.
+        In that case, just choose the smallest common stacklevel.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.exceptions import sympy_deprecation_warning
+    >>> def is_this_zero(x, y=0):
+    ...     """
+    ...     Determine if x = 0.
+    ...
+    ...     Parameters
+    ...     ==========
+    ...
+    ...     x : Expr
+    ...       The expression to check.
+    ...
+    ...     y : Expr, optional
+    ...       If provided, check if x = y.
+    ...
+    ...       .. deprecated:: 1.1
+    ...
+    ...          The ``y`` argument to ``is_this_zero`` is deprecated. Use
+    ...          ``is_this_zero(x - y)`` instead.
+    ...
+    ...     """
+    ...     from sympy import simplify
+    ...
+    ...     if y != 0:
+    ...         sympy_deprecation_warning("""
+    ...     The y argument to is_zero() is deprecated. Use is_zero(x - y) instead.""",
+    ...             deprecated_since_version="1.1",
+    ...             active_deprecations_target='is-this-zero-y-deprecation')
+    ...     return simplify(x - y) == 0
+    >>> is_this_zero(0)
+    True
+    >>> is_this_zero(1, 1) # doctest: +SKIP
+    :1: SymPyDeprecationWarning:
+    
+    The y argument to is_zero() is deprecated. Use is_zero(x - y) instead.
+    
+    See https://docs.sympy.org/latest/explanation/active-deprecations.html#is-this-zero-y-deprecation
+    for details.
+    
+    This has been deprecated since SymPy version 1.1. It
+    will be removed in a future version of SymPy.
+    
+      is_this_zero(1, 1)
+    True
+
+    See Also
+    ========
+
+    sympy.utilities.exceptions.SymPyDeprecationWarning
+    sympy.utilities.exceptions.ignore_warnings
+    sympy.utilities.decorator.deprecated
+    sympy.testing.pytest.warns_deprecated_sympy
+
+    '''
+    w = SymPyDeprecationWarning(message,
+                            deprecated_since_version=deprecated_since_version,
+                                active_deprecations_target=active_deprecations_target)
+    warnings.warn(w, stacklevel=stacklevel)
+
+
+@contextlib.contextmanager
+def ignore_warnings(warningcls):
+    '''
+    Context manager to suppress warnings during tests.
+
+    .. note::
+
+       Do not use this with SymPyDeprecationWarning in the tests.
+       warns_deprecated_sympy() should be used instead.
+
+    This function is useful for suppressing warnings during tests. The warns
+    function should be used to assert that a warning is raised. The
+    ignore_warnings function is useful in situation when the warning is not
+    guaranteed to be raised (e.g. on importing a module) or if the warning
+    comes from third-party code.
+
+    This function is also useful to prevent the same or similar warnings from
+    being issue twice due to recursive calls.
+
+    When the warning is coming (reliably) from SymPy the warns function should
+    be preferred to ignore_warnings.
+
+    >>> from sympy.utilities.exceptions import ignore_warnings
+    >>> import warnings
+
+    Here's a warning:
+
+    >>> with warnings.catch_warnings():  # reset warnings in doctest
+    ...     warnings.simplefilter('error')
+    ...     warnings.warn('deprecated', UserWarning)
+    Traceback (most recent call last):
+      ...
+    UserWarning: deprecated
+
+    Let's suppress it with ignore_warnings:
+
+    >>> with warnings.catch_warnings():  # reset warnings in doctest
+    ...     warnings.simplefilter('error')
+    ...     with ignore_warnings(UserWarning):
+    ...         warnings.warn('deprecated', UserWarning)
+
+    (No warning emitted)
+
+    See Also
+    ========
+    sympy.utilities.exceptions.SymPyDeprecationWarning
+    sympy.utilities.exceptions.sympy_deprecation_warning
+    sympy.utilities.decorator.deprecated
+    sympy.testing.pytest.warns_deprecated_sympy
+
+    '''
+    # Absorbs all warnings in warnrec
+    with warnings.catch_warnings(record=True) as warnrec:
+        # Make sure our warning doesn't get filtered
+        warnings.simplefilter("always", warningcls)
+        # Now run the test
+        yield
+
+    # Reissue any warnings that we aren't testing for
+    for w in warnrec:
+        if not issubclass(w.category, warningcls):
+            warnings.warn_explicit(w.message, w.category, w.filename, w.lineno)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/iterables.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/iterables.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc5c1152f03b10f62f9dd04c842b6fc74b0b9242
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/iterables.py
@@ -0,0 +1,3179 @@
+from collections import Counter, defaultdict, OrderedDict
+from itertools import (
+    chain, combinations, combinations_with_replacement, cycle, islice,
+    permutations, product, groupby
+)
+# For backwards compatibility
+from itertools import product as cartes # noqa: F401
+from operator import gt
+
+
+
+# this is the logical location of these functions
+from sympy.utilities.enumerative import (
+    multiset_partitions_taocp, list_visitor, MultisetPartitionTraverser)
+
+from sympy.utilities.misc import as_int
+from sympy.utilities.decorator import deprecated
+
+
+def is_palindromic(s, i=0, j=None):
+    """
+    Return True if the sequence is the same from left to right as it
+    is from right to left in the whole sequence (default) or in the
+    Python slice ``s[i: j]``; else False.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import is_palindromic
+    >>> is_palindromic([1, 0, 1])
+    True
+    >>> is_palindromic('abcbb')
+    False
+    >>> is_palindromic('abcbb', 1)
+    False
+
+    Normal Python slicing is performed in place so there is no need to
+    create a slice of the sequence for testing:
+
+    >>> is_palindromic('abcbb', 1, -1)
+    True
+    >>> is_palindromic('abcbb', -4, -1)
+    True
+
+    See Also
+    ========
+
+    sympy.ntheory.digits.is_palindromic: tests integers
+
+    """
+    i, j, _ = slice(i, j).indices(len(s))
+    m = (j - i)//2
+    # if length is odd, middle element will be ignored
+    return all(s[i + k] == s[j - 1 - k] for k in range(m))
+
+
+def flatten(iterable, levels=None, cls=None):  # noqa: F811
+    """
+    Recursively denest iterable containers.
+
+    >>> from sympy import flatten
+
+    >>> flatten([1, 2, 3])
+    [1, 2, 3]
+    >>> flatten([1, 2, [3]])
+    [1, 2, 3]
+    >>> flatten([1, [2, 3], [4, 5]])
+    [1, 2, 3, 4, 5]
+    >>> flatten([1.0, 2, (1, None)])
+    [1.0, 2, 1, None]
+
+    If you want to denest only a specified number of levels of
+    nested containers, then set ``levels`` flag to the desired
+    number of levels::
+
+    >>> ls = [[(-2, -1), (1, 2)], [(0, 0)]]
+
+    >>> flatten(ls, levels=1)
+    [(-2, -1), (1, 2), (0, 0)]
+
+    If cls argument is specified, it will only flatten instances of that
+    class, for example:
+
+    >>> from sympy import Basic, S
+    >>> class MyOp(Basic):
+    ...     pass
+    ...
+    >>> flatten([MyOp(S(1), MyOp(S(2), S(3)))], cls=MyOp)
+    [1, 2, 3]
+
+    adapted from https://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks
+    """
+    from sympy.tensor.array import NDimArray
+    if levels is not None:
+        if not levels:
+            return iterable
+        elif levels > 0:
+            levels -= 1
+        else:
+            raise ValueError(
+                "expected non-negative number of levels, got %s" % levels)
+
+    if cls is None:
+        def reducible(x):
+            return is_sequence(x, set)
+    else:
+        def reducible(x):
+            return isinstance(x, cls)
+
+    result = []
+
+    for el in iterable:
+        if reducible(el):
+            if hasattr(el, 'args') and not isinstance(el, NDimArray):
+                el = el.args
+            result.extend(flatten(el, levels=levels, cls=cls))
+        else:
+            result.append(el)
+
+    return result
+
+
+def unflatten(iter, n=2):
+    """Group ``iter`` into tuples of length ``n``. Raise an error if
+    the length of ``iter`` is not a multiple of ``n``.
+    """
+    if n < 1 or len(iter) % n:
+        raise ValueError('iter length is not a multiple of %i' % n)
+    return list(zip(*(iter[i::n] for i in range(n))))
+
+
+def reshape(seq, how):
+    """Reshape the sequence according to the template in ``how``.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities import reshape
+    >>> seq = list(range(1, 9))
+
+    >>> reshape(seq, [4]) # lists of 4
+    [[1, 2, 3, 4], [5, 6, 7, 8]]
+
+    >>> reshape(seq, (4,)) # tuples of 4
+    [(1, 2, 3, 4), (5, 6, 7, 8)]
+
+    >>> reshape(seq, (2, 2)) # tuples of 4
+    [(1, 2, 3, 4), (5, 6, 7, 8)]
+
+    >>> reshape(seq, (2, [2])) # (i, i, [i, i])
+    [(1, 2, [3, 4]), (5, 6, [7, 8])]
+
+    >>> reshape(seq, ((2,), [2])) # etc....
+    [((1, 2), [3, 4]), ((5, 6), [7, 8])]
+
+    >>> reshape(seq, (1, [2], 1))
+    [(1, [2, 3], 4), (5, [6, 7], 8)]
+
+    >>> reshape(tuple(seq), ([[1], 1, (2,)],))
+    (([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],))
+
+    >>> reshape(tuple(seq), ([1], 1, (2,)))
+    (([1], 2, (3, 4)), ([5], 6, (7, 8)))
+
+    >>> reshape(list(range(12)), [2, [3], {2}, (1, (3,), 1)])
+    [[0, 1, [2, 3, 4], {5, 6}, (7, (8, 9, 10), 11)]]
+
+    """
+    m = sum(flatten(how))
+    n, rem = divmod(len(seq), m)
+    if m < 0 or rem:
+        raise ValueError('template must sum to positive number '
+        'that divides the length of the sequence')
+    i = 0
+    container = type(how)
+    rv = [None]*n
+    for k in range(len(rv)):
+        _rv = []
+        for hi in how:
+            if isinstance(hi, int):
+                _rv.extend(seq[i: i + hi])
+                i += hi
+            else:
+                n = sum(flatten(hi))
+                hi_type = type(hi)
+                _rv.append(hi_type(reshape(seq[i: i + n], hi)[0]))
+                i += n
+        rv[k] = container(_rv)
+    return type(seq)(rv)
+
+
+def group(seq, multiple=True):
+    """
+    Splits a sequence into a list of lists of equal, adjacent elements.
+
+    Examples
+    ========
+
+    >>> from sympy import group
+
+    >>> group([1, 1, 1, 2, 2, 3])
+    [[1, 1, 1], [2, 2], [3]]
+    >>> group([1, 1, 1, 2, 2, 3], multiple=False)
+    [(1, 3), (2, 2), (3, 1)]
+    >>> group([1, 1, 3, 2, 2, 1], multiple=False)
+    [(1, 2), (3, 1), (2, 2), (1, 1)]
+
+    See Also
+    ========
+
+    multiset
+
+    """
+    if multiple:
+        return [(list(g)) for _, g in groupby(seq)]
+    return [(k, len(list(g))) for k, g in groupby(seq)]
+
+
+def _iproduct2(iterable1, iterable2):
+    '''Cartesian product of two possibly infinite iterables'''
+
+    it1 = iter(iterable1)
+    it2 = iter(iterable2)
+
+    elems1 = []
+    elems2 = []
+
+    sentinel = object()
+    def append(it, elems):
+        e = next(it, sentinel)
+        if e is not sentinel:
+            elems.append(e)
+
+    n = 0
+    append(it1, elems1)
+    append(it2, elems2)
+
+    while n <= len(elems1) + len(elems2):
+        for m in range(n-len(elems1)+1, len(elems2)):
+            yield (elems1[n-m], elems2[m])
+        n += 1
+        append(it1, elems1)
+        append(it2, elems2)
+
+
+def iproduct(*iterables):
+    '''
+    Cartesian product of iterables.
+
+    Generator of the Cartesian product of iterables. This is analogous to
+    itertools.product except that it works with infinite iterables and will
+    yield any item from the infinite product eventually.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import iproduct
+    >>> sorted(iproduct([1,2], [3,4]))
+    [(1, 3), (1, 4), (2, 3), (2, 4)]
+
+    With an infinite iterator:
+
+    >>> from sympy import S
+    >>> (3,) in iproduct(S.Integers)
+    True
+    >>> (3, 4) in iproduct(S.Integers, S.Integers)
+    True
+
+    .. seealso::
+
+       `itertools.product
+       `_
+    '''
+    if len(iterables) == 0:
+        yield ()
+        return
+    elif len(iterables) == 1:
+        for e in iterables[0]:
+            yield (e,)
+    elif len(iterables) == 2:
+        yield from _iproduct2(*iterables)
+    else:
+        first, others = iterables[0], iterables[1:]
+        for ef, eo in _iproduct2(first, iproduct(*others)):
+            yield (ef,) + eo
+
+
+def multiset(seq):
+    """Return the hashable sequence in multiset form with values being the
+    multiplicity of the item in the sequence.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import multiset
+    >>> multiset('mississippi')
+    {'i': 4, 'm': 1, 'p': 2, 's': 4}
+
+    See Also
+    ========
+
+    group
+
+    """
+    return dict(Counter(seq).items())
+
+
+
+
+def ibin(n, bits=None, str=False):
+    """Return a list of length ``bits`` corresponding to the binary value
+    of ``n`` with small bits to the right (last). If bits is omitted, the
+    length will be the number required to represent ``n``. If the bits are
+    desired in reversed order, use the ``[::-1]`` slice of the returned list.
+
+    If a sequence of all bits-length lists starting from ``[0, 0,..., 0]``
+    through ``[1, 1, ..., 1]`` are desired, pass a non-integer for bits, e.g.
+    ``'all'``.
+
+    If the bit *string* is desired pass ``str=True``.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import ibin
+    >>> ibin(2)
+    [1, 0]
+    >>> ibin(2, 4)
+    [0, 0, 1, 0]
+
+    If all lists corresponding to 0 to 2**n - 1, pass a non-integer
+    for bits:
+
+    >>> bits = 2
+    >>> for i in ibin(2, 'all'):
+    ...     print(i)
+    (0, 0)
+    (0, 1)
+    (1, 0)
+    (1, 1)
+
+    If a bit string is desired of a given length, use str=True:
+
+    >>> n = 123
+    >>> bits = 10
+    >>> ibin(n, bits, str=True)
+    '0001111011'
+    >>> ibin(n, bits, str=True)[::-1]  # small bits left
+    '1101111000'
+    >>> list(ibin(3, 'all', str=True))
+    ['000', '001', '010', '011', '100', '101', '110', '111']
+
+    """
+    if n < 0:
+        raise ValueError("negative numbers are not allowed")
+    n = as_int(n)
+
+    if bits is None:
+        bits = 0
+    else:
+        try:
+            bits = as_int(bits)
+        except ValueError:
+            bits = -1
+        else:
+            if n.bit_length() > bits:
+                raise ValueError(
+                    "`bits` must be >= {}".format(n.bit_length()))
+
+    if not str:
+        if bits >= 0:
+            return [1 if i == "1" else 0 for i in bin(n)[2:].rjust(bits, "0")]
+        else:
+            return variations(range(2), n, repetition=True)
+    else:
+        if bits >= 0:
+            return bin(n)[2:].rjust(bits, "0")
+        else:
+            return (bin(i)[2:].rjust(n, "0") for i in range(2**n))
+
+
+def variations(seq, n, repetition=False):
+    r"""Returns an iterator over the n-sized variations of ``seq`` (size N).
+    ``repetition`` controls whether items in ``seq`` can appear more than once;
+
+    Examples
+    ========
+
+    ``variations(seq, n)`` will return `\frac{N!}{(N - n)!}` permutations without
+    repetition of ``seq``'s elements:
+
+        >>> from sympy import variations
+        >>> list(variations([1, 2], 2))
+        [(1, 2), (2, 1)]
+
+    ``variations(seq, n, True)`` will return the `N^n` permutations obtained
+    by allowing repetition of elements:
+
+        >>> list(variations([1, 2], 2, repetition=True))
+        [(1, 1), (1, 2), (2, 1), (2, 2)]
+
+    If you ask for more items than are in the set you get the empty set unless
+    you allow repetitions:
+
+        >>> list(variations([0, 1], 3, repetition=False))
+        []
+        >>> list(variations([0, 1], 3, repetition=True))[:4]
+        [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1)]
+
+    .. seealso::
+
+       `itertools.permutations
+       `_,
+       `itertools.product
+       `_
+    """
+    if not repetition:
+        seq = tuple(seq)
+        if len(seq) < n:
+            return iter(())  # 0 length iterator
+        return permutations(seq, n)
+    else:
+        if n == 0:
+            return iter(((),))  # yields 1 empty tuple
+        else:
+            return product(seq, repeat=n)
+
+
+def subsets(seq, k=None, repetition=False):
+    r"""Generates all `k`-subsets (combinations) from an `n`-element set, ``seq``.
+
+    A `k`-subset of an `n`-element set is any subset of length exactly `k`. The
+    number of `k`-subsets of an `n`-element set is given by ``binomial(n, k)``,
+    whereas there are `2^n` subsets all together. If `k` is ``None`` then all
+    `2^n` subsets will be returned from shortest to longest.
+
+    Examples
+    ========
+
+    >>> from sympy import subsets
+
+    ``subsets(seq, k)`` will return the
+    `\frac{n!}{k!(n - k)!}` `k`-subsets (combinations)
+    without repetition, i.e. once an item has been removed, it can no
+    longer be "taken":
+
+        >>> list(subsets([1, 2], 2))
+        [(1, 2)]
+        >>> list(subsets([1, 2]))
+        [(), (1,), (2,), (1, 2)]
+        >>> list(subsets([1, 2, 3], 2))
+        [(1, 2), (1, 3), (2, 3)]
+
+
+    ``subsets(seq, k, repetition=True)`` will return the
+    `\frac{(n - 1 + k)!}{k!(n - 1)!}`
+    combinations *with* repetition:
+
+        >>> list(subsets([1, 2], 2, repetition=True))
+        [(1, 1), (1, 2), (2, 2)]
+
+    If you ask for more items than are in the set you get the empty set unless
+    you allow repetitions:
+
+        >>> list(subsets([0, 1], 3, repetition=False))
+        []
+        >>> list(subsets([0, 1], 3, repetition=True))
+        [(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)]
+
+    """
+    if k is None:
+        if not repetition:
+            return chain.from_iterable((combinations(seq, k)
+                                        for k in range(len(seq) + 1)))
+        else:
+            return chain.from_iterable((combinations_with_replacement(seq, k)
+                                        for k in range(len(seq) + 1)))
+    else:
+        if not repetition:
+            return combinations(seq, k)
+        else:
+            return combinations_with_replacement(seq, k)
+
+
+def filter_symbols(iterator, exclude):
+    """
+    Only yield elements from `iterator` that do not occur in `exclude`.
+
+    Parameters
+    ==========
+
+    iterator : iterable
+        iterator to take elements from
+
+    exclude : iterable
+        elements to exclude
+
+    Returns
+    =======
+
+    iterator : iterator
+        filtered iterator
+    """
+    exclude = set(exclude)
+    for s in iterator:
+        if s not in exclude:
+            yield s
+
+def numbered_symbols(prefix='x', cls=None, start=0, exclude=(), *args, **assumptions):
+    """
+    Generate an infinite stream of Symbols consisting of a prefix and
+    increasing subscripts provided that they do not occur in ``exclude``.
+
+    Parameters
+    ==========
+
+    prefix : str, optional
+        The prefix to use. By default, this function will generate symbols of
+        the form "x0", "x1", etc.
+
+    cls : class, optional
+        The class to use. By default, it uses ``Symbol``, but you can also use ``Wild``
+        or ``Dummy``.
+
+    start : int, optional
+        The start number.  By default, it is 0.
+
+    exclude : list, tuple, set of cls, optional
+        Symbols to be excluded.
+
+    *args, **kwargs
+        Additional positional and keyword arguments are passed to the *cls* class.
+
+    Returns
+    =======
+
+    sym : Symbol
+        The subscripted symbols.
+    """
+    exclude = set(exclude or [])
+    if cls is None:
+        # We can't just make the default cls=Symbol because it isn't
+        # imported yet.
+        from sympy.core import Symbol
+        cls = Symbol
+
+    while True:
+        name = '%s%s' % (prefix, start)
+        s = cls(name, *args, **assumptions)
+        if s not in exclude:
+            yield s
+        start += 1
+
+
+def capture(func):
+    """Return the printed output of func().
+
+    ``func`` should be a function without arguments that produces output with
+    print statements.
+
+    >>> from sympy.utilities.iterables import capture
+    >>> from sympy import pprint
+    >>> from sympy.abc import x
+    >>> def foo():
+    ...     print('hello world!')
+    ...
+    >>> 'hello' in capture(foo) # foo, not foo()
+    True
+    >>> capture(lambda: pprint(2/x))
+    '2\\n-\\nx\\n'
+
+    """
+    from io import StringIO
+    import sys
+
+    stdout = sys.stdout
+    sys.stdout = file = StringIO()
+    try:
+        func()
+    finally:
+        sys.stdout = stdout
+    return file.getvalue()
+
+
+def sift(seq, keyfunc, binary=False):
+    """
+    Sift the sequence, ``seq`` according to ``keyfunc``.
+
+    Returns
+    =======
+
+    When ``binary`` is ``False`` (default), the output is a dictionary
+    where elements of ``seq`` are stored in a list keyed to the value
+    of keyfunc for that element. If ``binary`` is True then a tuple
+    with lists ``T`` and ``F`` are returned where ``T`` is a list
+    containing elements of seq for which ``keyfunc`` was ``True`` and
+    ``F`` containing those elements for which ``keyfunc`` was ``False``;
+    a ValueError is raised if the ``keyfunc`` is not binary.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities import sift
+    >>> from sympy.abc import x, y
+    >>> from sympy import sqrt, exp, pi, Tuple
+
+    >>> sift(range(5), lambda x: x % 2)
+    {0: [0, 2, 4], 1: [1, 3]}
+
+    sift() returns a defaultdict() object, so any key that has no matches will
+    give [].
+
+    >>> sift([x], lambda x: x.is_commutative)
+    {True: [x]}
+    >>> _[False]
+    []
+
+    Sometimes you will not know how many keys you will get:
+
+    >>> sift([sqrt(x), exp(x), (y**x)**2],
+    ...      lambda x: x.as_base_exp()[0])
+    {E: [exp(x)], x: [sqrt(x)], y: [y**(2*x)]}
+
+    Sometimes you expect the results to be binary; the
+    results can be unpacked by setting ``binary`` to True:
+
+    >>> sift(range(4), lambda x: x % 2, binary=True)
+    ([1, 3], [0, 2])
+    >>> sift(Tuple(1, pi), lambda x: x.is_rational, binary=True)
+    ([1], [pi])
+
+    A ValueError is raised if the predicate was not actually binary
+    (which is a good test for the logic where sifting is used and
+    binary results were expected):
+
+    >>> unknown = exp(1) - pi  # the rationality of this is unknown
+    >>> args = Tuple(1, pi, unknown)
+    >>> sift(args, lambda x: x.is_rational, binary=True)
+    Traceback (most recent call last):
+    ...
+    ValueError: keyfunc gave non-binary output
+
+    The non-binary sifting shows that there were 3 keys generated:
+
+    >>> set(sift(args, lambda x: x.is_rational).keys())
+    {None, False, True}
+
+    If you need to sort the sifted items it might be better to use
+    ``ordered`` which can economically apply multiple sort keys
+    to a sequence while sorting.
+
+    See Also
+    ========
+
+    ordered
+
+    """
+    if not binary:
+        m = defaultdict(list)
+        for i in seq:
+            m[keyfunc(i)].append(i)
+        return m
+    sift = F, T = [], []
+    for i in seq:
+        try:
+            sift[keyfunc(i)].append(i)
+        except (IndexError, TypeError):
+            raise ValueError('keyfunc gave non-binary output')
+    return T, F
+
+
+def take(iter, n):
+    """Return ``n`` items from ``iter`` iterator. """
+    return [ value for _, value in zip(range(n), iter) ]
+
+
+def dict_merge(*dicts):
+    """Merge dictionaries into a single dictionary. """
+    merged = {}
+
+    for dict in dicts:
+        merged.update(dict)
+
+    return merged
+
+
+def common_prefix(*seqs):
+    """Return the subsequence that is a common start of sequences in ``seqs``.
+
+    >>> from sympy.utilities.iterables import common_prefix
+    >>> common_prefix(list(range(3)))
+    [0, 1, 2]
+    >>> common_prefix(list(range(3)), list(range(4)))
+    [0, 1, 2]
+    >>> common_prefix([1, 2, 3], [1, 2, 5])
+    [1, 2]
+    >>> common_prefix([1, 2, 3], [1, 3, 5])
+    [1]
+    """
+    if not all(seqs):
+        return []
+    elif len(seqs) == 1:
+        return seqs[0]
+    i = 0
+    for i in range(min(len(s) for s in seqs)):
+        if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))):
+            break
+    else:
+        i += 1
+    return seqs[0][:i]
+
+
+def common_suffix(*seqs):
+    """Return the subsequence that is a common ending of sequences in ``seqs``.
+
+    >>> from sympy.utilities.iterables import common_suffix
+    >>> common_suffix(list(range(3)))
+    [0, 1, 2]
+    >>> common_suffix(list(range(3)), list(range(4)))
+    []
+    >>> common_suffix([1, 2, 3], [9, 2, 3])
+    [2, 3]
+    >>> common_suffix([1, 2, 3], [9, 7, 3])
+    [3]
+    """
+
+    if not all(seqs):
+        return []
+    elif len(seqs) == 1:
+        return seqs[0]
+    i = 0
+    for i in range(-1, -min(len(s) for s in seqs) - 1, -1):
+        if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))):
+            break
+    else:
+        i -= 1
+    if i == -1:
+        return []
+    else:
+        return seqs[0][i + 1:]
+
+
+def prefixes(seq):
+    """
+    Generate all prefixes of a sequence.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import prefixes
+
+    >>> list(prefixes([1,2,3,4]))
+    [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
+
+    """
+    n = len(seq)
+
+    for i in range(n):
+        yield seq[:i + 1]
+
+
+def postfixes(seq):
+    """
+    Generate all postfixes of a sequence.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import postfixes
+
+    >>> list(postfixes([1,2,3,4]))
+    [[4], [3, 4], [2, 3, 4], [1, 2, 3, 4]]
+
+    """
+    n = len(seq)
+
+    for i in range(n):
+        yield seq[n - i - 1:]
+
+
+def topological_sort(graph, key=None):
+    r"""
+    Topological sort of graph's vertices.
+
+    Parameters
+    ==========
+
+    graph : tuple[list, list[tuple[T, T]]
+        A tuple consisting of a list of vertices and a list of edges of
+        a graph to be sorted topologically.
+
+    key : callable[T] (optional)
+        Ordering key for vertices on the same level. By default the natural
+        (e.g. lexicographic) ordering is used (in this case the base type
+        must implement ordering relations).
+
+    Examples
+    ========
+
+    Consider a graph::
+
+        +---+     +---+     +---+
+        | 7 |\    | 5 |     | 3 |
+        +---+ \   +---+     +---+
+          |   _\___/ ____   _/ |
+          |  /  \___/    \ /   |
+          V  V           V V   |
+         +----+         +---+  |
+         | 11 |         | 8 |  |
+         +----+         +---+  |
+          | | \____   ___/ _   |
+          | \      \ /    / \  |
+          V  \     V V   /  V  V
+        +---+ \   +---+ |  +----+
+        | 2 |  |  | 9 | |  | 10 |
+        +---+  |  +---+ |  +----+
+               \________/
+
+    where vertices are integers. This graph can be encoded using
+    elementary Python's data structures as follows::
+
+        >>> V = [2, 3, 5, 7, 8, 9, 10, 11]
+        >>> E = [(7, 11), (7, 8), (5, 11), (3, 8), (3, 10),
+        ...      (11, 2), (11, 9), (11, 10), (8, 9)]
+
+    To compute a topological sort for graph ``(V, E)`` issue::
+
+        >>> from sympy.utilities.iterables import topological_sort
+
+        >>> topological_sort((V, E))
+        [3, 5, 7, 8, 11, 2, 9, 10]
+
+    If specific tie breaking approach is needed, use ``key`` parameter::
+
+        >>> topological_sort((V, E), key=lambda v: -v)
+        [7, 5, 11, 3, 10, 8, 9, 2]
+
+    Only acyclic graphs can be sorted. If the input graph has a cycle,
+    then ``ValueError`` will be raised::
+
+        >>> topological_sort((V, E + [(10, 7)]))
+        Traceback (most recent call last):
+        ...
+        ValueError: cycle detected
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Topological_sorting
+
+    """
+    V, E = graph
+
+    L = []
+    S = set(V)
+    E = list(E)
+
+    S.difference_update(u for v, u in E)
+
+    if key is None:
+        def key(value):
+            return value
+
+    S = sorted(S, key=key, reverse=True)
+
+    while S:
+        node = S.pop()
+        L.append(node)
+
+        for u, v in list(E):
+            if u == node:
+                E.remove((u, v))
+
+                for _u, _v in E:
+                    if v == _v:
+                        break
+                else:
+                    kv = key(v)
+
+                    for i, s in enumerate(S):
+                        ks = key(s)
+
+                        if kv > ks:
+                            S.insert(i, v)
+                            break
+                    else:
+                        S.append(v)
+
+    if E:
+        raise ValueError("cycle detected")
+    else:
+        return L
+
+
+def strongly_connected_components(G):
+    r"""
+    Strongly connected components of a directed graph in reverse topological
+    order.
+
+
+    Parameters
+    ==========
+
+    G : tuple[list, list[tuple[T, T]]
+        A tuple consisting of a list of vertices and a list of edges of
+        a graph whose strongly connected components are to be found.
+
+
+    Examples
+    ========
+
+    Consider a directed graph (in dot notation)::
+
+        digraph {
+            A -> B
+            A -> C
+            B -> C
+            C -> B
+            B -> D
+        }
+
+    .. graphviz::
+
+        digraph {
+            A -> B
+            A -> C
+            B -> C
+            C -> B
+            B -> D
+        }
+
+    where vertices are the letters A, B, C and D. This graph can be encoded
+    using Python's elementary data structures as follows::
+
+        >>> V = ['A', 'B', 'C', 'D']
+        >>> E = [('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'B'), ('B', 'D')]
+
+    The strongly connected components of this graph can be computed as
+
+        >>> from sympy.utilities.iterables import strongly_connected_components
+
+        >>> strongly_connected_components((V, E))
+        [['D'], ['B', 'C'], ['A']]
+
+    This also gives the components in reverse topological order.
+
+    Since the subgraph containing B and C has a cycle they must be together in
+    a strongly connected component. A and D are connected to the rest of the
+    graph but not in a cyclic manner so they appear as their own strongly
+    connected components.
+
+
+    Notes
+    =====
+
+    The vertices of the graph must be hashable for the data structures used.
+    If the vertices are unhashable replace them with integer indices.
+
+    This function uses Tarjan's algorithm to compute the strongly connected
+    components in `O(|V|+|E|)` (linear) time.
+
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Strongly_connected_component
+    .. [2] https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
+
+
+    See Also
+    ========
+
+    sympy.utilities.iterables.connected_components
+
+    """
+    # Map from a vertex to its neighbours
+    V, E = G
+    Gmap = {vi: [] for vi in V}
+    for v1, v2 in E:
+        Gmap[v1].append(v2)
+    return _strongly_connected_components(V, Gmap)
+
+
+def _strongly_connected_components(V, Gmap):
+    """More efficient internal routine for strongly_connected_components"""
+    #
+    # Here V is an iterable of vertices and Gmap is a dict mapping each vertex
+    # to a list of neighbours e.g.:
+    #
+    #   V = [0, 1, 2, 3]
+    #   Gmap = {0: [2, 3], 1: [0]}
+    #
+    # For a large graph these data structures can often be created more
+    # efficiently then those expected by strongly_connected_components() which
+    # in this case would be
+    #
+    #   V = [0, 1, 2, 3]
+    #   Gmap = [(0, 2), (0, 3), (1, 0)]
+    #
+    # XXX: Maybe this should be the recommended function to use instead...
+    #
+
+    # Non-recursive Tarjan's algorithm:
+    lowlink = {}
+    indices = {}
+    stack = OrderedDict()
+    callstack = []
+    components = []
+    nomore = object()
+
+    def start(v):
+        index = len(stack)
+        indices[v] = lowlink[v] = index
+        stack[v] = None
+        callstack.append((v, iter(Gmap[v])))
+
+    def finish(v1):
+        # Finished a component?
+        if lowlink[v1] == indices[v1]:
+            component = [stack.popitem()[0]]
+            while component[-1] is not v1:
+                component.append(stack.popitem()[0])
+            components.append(component[::-1])
+        v2, _ = callstack.pop()
+        if callstack:
+            v1, _ = callstack[-1]
+            lowlink[v1] = min(lowlink[v1], lowlink[v2])
+
+    for v in V:
+        if v in indices:
+            continue
+        start(v)
+        while callstack:
+            v1, it1 = callstack[-1]
+            v2 = next(it1, nomore)
+            # Finished children of v1?
+            if v2 is nomore:
+                finish(v1)
+            # Recurse on v2
+            elif v2 not in indices:
+                start(v2)
+            elif v2 in stack:
+                lowlink[v1] = min(lowlink[v1], indices[v2])
+
+    # Reverse topological sort order:
+    return components
+
+
+def connected_components(G):
+    r"""
+    Connected components of an undirected graph or weakly connected components
+    of a directed graph.
+
+
+    Parameters
+    ==========
+
+    G : tuple[list, list[tuple[T, T]]
+        A tuple consisting of a list of vertices and a list of edges of
+        a graph whose connected components are to be found.
+
+
+    Examples
+    ========
+
+
+    Given an undirected graph::
+
+        graph {
+            A -- B
+            C -- D
+        }
+
+    .. graphviz::
+
+        graph {
+            A -- B
+            C -- D
+        }
+
+    We can find the connected components using this function if we include
+    each edge in both directions::
+
+        >>> from sympy.utilities.iterables import connected_components
+
+        >>> V = ['A', 'B', 'C', 'D']
+        >>> E = [('A', 'B'), ('B', 'A'), ('C', 'D'), ('D', 'C')]
+        >>> connected_components((V, E))
+        [['A', 'B'], ['C', 'D']]
+
+    The weakly connected components of a directed graph can found the same
+    way.
+
+
+    Notes
+    =====
+
+    The vertices of the graph must be hashable for the data structures used.
+    If the vertices are unhashable replace them with integer indices.
+
+    This function uses Tarjan's algorithm to compute the connected components
+    in `O(|V|+|E|)` (linear) time.
+
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Component_%28graph_theory%29
+    .. [2] https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
+
+
+    See Also
+    ========
+
+    sympy.utilities.iterables.strongly_connected_components
+
+    """
+    # Duplicate edges both ways so that the graph is effectively undirected
+    # and return the strongly connected components:
+    V, E = G
+    E_undirected = []
+    for v1, v2 in E:
+        E_undirected.extend([(v1, v2), (v2, v1)])
+    return strongly_connected_components((V, E_undirected))
+
+
+def rotate_left(x, y):
+    """
+    Left rotates a list x by the number of steps specified
+    in y.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import rotate_left
+    >>> a = [0, 1, 2]
+    >>> rotate_left(a, 1)
+    [1, 2, 0]
+    """
+    if len(x) == 0:
+        return []
+    y = y % len(x)
+    return x[y:] + x[:y]
+
+
+def rotate_right(x, y):
+    """
+    Right rotates a list x by the number of steps specified
+    in y.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import rotate_right
+    >>> a = [0, 1, 2]
+    >>> rotate_right(a, 1)
+    [2, 0, 1]
+    """
+    if len(x) == 0:
+        return []
+    y = len(x) - y % len(x)
+    return x[y:] + x[:y]
+
+
+def least_rotation(x, key=None):
+    '''
+    Returns the number of steps of left rotation required to
+    obtain lexicographically minimal string/list/tuple, etc.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import least_rotation, rotate_left
+    >>> a = [3, 1, 5, 1, 2]
+    >>> least_rotation(a)
+    3
+    >>> rotate_left(a, _)
+    [1, 2, 3, 1, 5]
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Lexicographically_minimal_string_rotation
+
+    '''
+    from sympy.functions.elementary.miscellaneous import Id
+    if key is None: key = Id
+    S = x + x      # Concatenate string to it self to avoid modular arithmetic
+    f = [-1] * len(S)     # Failure function
+    k = 0       # Least rotation of string found so far
+    for j in range(1,len(S)):
+        sj = S[j]
+        i = f[j-k-1]
+        while i != -1 and sj != S[k+i+1]:
+            if key(sj) < key(S[k+i+1]):
+                k = j-i-1
+            i = f[i]
+        if sj != S[k+i+1]:
+            if key(sj) < key(S[k]):
+                k = j
+            f[j-k] = -1
+        else:
+            f[j-k] = i+1
+    return k
+
+
+def multiset_combinations(m, n, g=None):
+    """
+    Return the unique combinations of size ``n`` from multiset ``m``.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import multiset_combinations
+    >>> from itertools import combinations
+    >>> [''.join(i) for i in  multiset_combinations('baby', 3)]
+    ['abb', 'aby', 'bby']
+
+    >>> def count(f, s): return len(list(f(s, 3)))
+
+    The number of combinations depends on the number of letters; the
+    number of unique combinations depends on how the letters are
+    repeated.
+
+    >>> s1 = 'abracadabra'
+    >>> s2 = 'banana tree'
+    >>> count(combinations, s1), count(multiset_combinations, s1)
+    (165, 23)
+    >>> count(combinations, s2), count(multiset_combinations, s2)
+    (165, 54)
+
+    """
+    from sympy.core.sorting import ordered
+    if g is None:
+        if isinstance(m, dict):
+            if any(as_int(v) < 0 for v in m.values()):
+                raise ValueError('counts cannot be negative')
+            N = sum(m.values())
+            if n > N:
+                return
+            g = [[k, m[k]] for k in ordered(m)]
+        else:
+            m = list(m)
+            N = len(m)
+            if n > N:
+                return
+            try:
+                m = multiset(m)
+                g = [(k, m[k]) for k in ordered(m)]
+            except TypeError:
+                m = list(ordered(m))
+                g = [list(i) for i in group(m, multiple=False)]
+        del m
+    else:
+        # not checking counts since g is intended for internal use
+        N = sum(v for k, v in g)
+    if n > N or not n:
+        yield []
+    else:
+        for i, (k, v) in enumerate(g):
+            if v >= n:
+                yield [k]*n
+                v = n - 1
+            for v in range(min(n, v), 0, -1):
+                for j in multiset_combinations(None, n - v, g[i + 1:]):
+                    rv = [k]*v + j
+                    if len(rv) == n:
+                        yield rv
+
+def multiset_permutations(m, size=None, g=None):
+    """
+    Return the unique permutations of multiset ``m``.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import multiset_permutations
+    >>> from sympy import factorial
+    >>> [''.join(i) for i in multiset_permutations('aab')]
+    ['aab', 'aba', 'baa']
+    >>> factorial(len('banana'))
+    720
+    >>> len(list(multiset_permutations('banana')))
+    60
+    """
+    from sympy.core.sorting import ordered
+    if g is None:
+        if isinstance(m, dict):
+            if any(as_int(v) < 0 for v in m.values()):
+                raise ValueError('counts cannot be negative')
+            g = [[k, m[k]] for k in ordered(m)]
+        else:
+            m = list(ordered(m))
+            g = [list(i) for i in group(m, multiple=False)]
+        del m
+    do = [gi for gi in g if gi[1] > 0]
+    SUM = sum(gi[1] for gi in do)
+    if not do or size is not None and (size > SUM or size < 1):
+        if not do and size is None or size == 0:
+            yield []
+        return
+    elif size == 1:
+        for k, v in do:
+            yield [k]
+    elif len(do) == 1:
+        k, v = do[0]
+        v = v if size is None else (size if size <= v else 0)
+        yield [k for i in range(v)]
+    elif all(v == 1 for k, v in do):
+        for p in permutations([k for k, v in do], size):
+            yield list(p)
+    else:
+        size = size if size is not None else SUM
+        for i, (k, v) in enumerate(do):
+            do[i][1] -= 1
+            for j in multiset_permutations(None, size - 1, do):
+                if j:
+                    yield [k] + j
+            do[i][1] += 1
+
+
+def _partition(seq, vector, m=None):
+    """
+    Return the partition of seq as specified by the partition vector.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import _partition
+    >>> _partition('abcde', [1, 0, 1, 2, 0])
+    [['b', 'e'], ['a', 'c'], ['d']]
+
+    Specifying the number of bins in the partition is optional:
+
+    >>> _partition('abcde', [1, 0, 1, 2, 0], 3)
+    [['b', 'e'], ['a', 'c'], ['d']]
+
+    The output of _set_partitions can be passed as follows:
+
+    >>> output = (3, [1, 0, 1, 2, 0])
+    >>> _partition('abcde', *output)
+    [['b', 'e'], ['a', 'c'], ['d']]
+
+    See Also
+    ========
+
+    combinatorics.partitions.Partition.from_rgs
+
+    """
+    if m is None:
+        m = max(vector) + 1
+    elif isinstance(vector, int):  # entered as m, vector
+        vector, m = m, vector
+    p = [[] for i in range(m)]
+    for i, v in enumerate(vector):
+        p[v].append(seq[i])
+    return p
+
+
+def _set_partitions(n):
+    """Cycle through all partitions of n elements, yielding the
+    current number of partitions, ``m``, and a mutable list, ``q``
+    such that ``element[i]`` is in part ``q[i]`` of the partition.
+
+    NOTE: ``q`` is modified in place and generally should not be changed
+    between function calls.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import _set_partitions, _partition
+    >>> for m, q in _set_partitions(3):
+    ...     print('%s %s %s' % (m, q, _partition('abc', q, m)))
+    1 [0, 0, 0] [['a', 'b', 'c']]
+    2 [0, 0, 1] [['a', 'b'], ['c']]
+    2 [0, 1, 0] [['a', 'c'], ['b']]
+    2 [0, 1, 1] [['a'], ['b', 'c']]
+    3 [0, 1, 2] [['a'], ['b'], ['c']]
+
+    Notes
+    =====
+
+    This algorithm is similar to, and solves the same problem as,
+    Algorithm 7.2.1.5H, from volume 4A of Knuth's The Art of Computer
+    Programming.  Knuth uses the term "restricted growth string" where
+    this code refers to a "partition vector". In each case, the meaning is
+    the same: the value in the ith element of the vector specifies to
+    which part the ith set element is to be assigned.
+
+    At the lowest level, this code implements an n-digit big-endian
+    counter (stored in the array q) which is incremented (with carries) to
+    get the next partition in the sequence.  A special twist is that a
+    digit is constrained to be at most one greater than the maximum of all
+    the digits to the left of it.  The array p maintains this maximum, so
+    that the code can efficiently decide when a digit can be incremented
+    in place or whether it needs to be reset to 0 and trigger a carry to
+    the next digit.  The enumeration starts with all the digits 0 (which
+    corresponds to all the set elements being assigned to the same 0th
+    part), and ends with 0123...n, which corresponds to each set element
+    being assigned to a different, singleton, part.
+
+    This routine was rewritten to use 0-based lists while trying to
+    preserve the beauty and efficiency of the original algorithm.
+
+    References
+    ==========
+
+    .. [1] Nijenhuis, Albert and Wilf, Herbert. (1978) Combinatorial Algorithms,
+        2nd Ed, p 91, algorithm "nexequ". Available online from
+        https://www.math.upenn.edu/~wilf/website/CombAlgDownld.html (viewed
+        November 17, 2012).
+
+    """
+    p = [0]*n
+    q = [0]*n
+    nc = 1
+    yield nc, q
+    while nc != n:
+        m = n
+        while 1:
+            m -= 1
+            i = q[m]
+            if p[i] != 1:
+                break
+            q[m] = 0
+        i += 1
+        q[m] = i
+        m += 1
+        nc += m - n
+        p[0] += n - m
+        if i == nc:
+            p[nc] = 0
+            nc += 1
+        p[i - 1] -= 1
+        p[i] += 1
+        yield nc, q
+
+
+def multiset_partitions(multiset, m=None):
+    """
+    Return unique partitions of the given multiset (in list form).
+    If ``m`` is None, all multisets will be returned, otherwise only
+    partitions with ``m`` parts will be returned.
+
+    If ``multiset`` is an integer, a range [0, 1, ..., multiset - 1]
+    will be supplied.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import multiset_partitions
+    >>> list(multiset_partitions([1, 2, 3, 4], 2))
+    [[[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 2], [3, 4]],
+    [[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]],
+    [[1], [2, 3, 4]]]
+    >>> list(multiset_partitions([1, 2, 3, 4], 1))
+    [[[1, 2, 3, 4]]]
+
+    Only unique partitions are returned and these will be returned in a
+    canonical order regardless of the order of the input:
+
+    >>> a = [1, 2, 2, 1]
+    >>> ans = list(multiset_partitions(a, 2))
+    >>> a.sort()
+    >>> list(multiset_partitions(a, 2)) == ans
+    True
+    >>> a = range(3, 1, -1)
+    >>> (list(multiset_partitions(a)) ==
+    ...  list(multiset_partitions(sorted(a))))
+    True
+
+    If m is omitted then all partitions will be returned:
+
+    >>> list(multiset_partitions([1, 1, 2]))
+    [[[1, 1, 2]], [[1, 1], [2]], [[1, 2], [1]], [[1], [1], [2]]]
+    >>> list(multiset_partitions([1]*3))
+    [[[1, 1, 1]], [[1], [1, 1]], [[1], [1], [1]]]
+
+    Counting
+    ========
+
+    The number of partitions of a set is given by the bell number:
+
+    >>> from sympy import bell
+    >>> len(list(multiset_partitions(5))) == bell(5) == 52
+    True
+
+    The number of partitions of length k from a set of size n is given by the
+    Stirling Number of the 2nd kind:
+
+    >>> from sympy.functions.combinatorial.numbers import stirling
+    >>> stirling(5, 2) == len(list(multiset_partitions(5, 2))) == 15
+    True
+
+    These comments on counting apply to *sets*, not multisets.
+
+    Notes
+    =====
+
+    When all the elements are the same in the multiset, the order
+    of the returned partitions is determined by the ``partitions``
+    routine. If one is counting partitions then it is better to use
+    the ``nT`` function.
+
+    See Also
+    ========
+
+    partitions
+    sympy.combinatorics.partitions.Partition
+    sympy.combinatorics.partitions.IntegerPartition
+    sympy.functions.combinatorial.numbers.nT
+
+    """
+    # This function looks at the supplied input and dispatches to
+    # several special-case routines as they apply.
+    if isinstance(multiset, int):
+        n = multiset
+        if m and m > n:
+            return
+        multiset = list(range(n))
+        if m == 1:
+            yield [multiset[:]]
+            return
+
+        # If m is not None, it can sometimes be faster to use
+        # MultisetPartitionTraverser.enum_range() even for inputs
+        # which are sets.  Since the _set_partitions code is quite
+        # fast, this is only advantageous when the overall set
+        # partitions outnumber those with the desired number of parts
+        # by a large factor.  (At least 60.)  Such a switch is not
+        # currently implemented.
+        for nc, q in _set_partitions(n):
+            if m is None or nc == m:
+                rv = [[] for i in range(nc)]
+                for i in range(n):
+                    rv[q[i]].append(multiset[i])
+                yield rv
+        return
+
+    if len(multiset) == 1 and isinstance(multiset, str):
+        multiset = [multiset]
+
+    if not has_variety(multiset):
+        # Only one component, repeated n times.  The resulting
+        # partitions correspond to partitions of integer n.
+        n = len(multiset)
+        if m and m > n:
+            return
+        if m == 1:
+            yield [multiset[:]]
+            return
+        x = multiset[:1]
+        for size, p in partitions(n, m, size=True):
+            if m is None or size == m:
+                rv = []
+                for k in sorted(p):
+                    rv.extend([x*k]*p[k])
+                yield rv
+    else:
+        from sympy.core.sorting import ordered
+        multiset = list(ordered(multiset))
+        n = len(multiset)
+        if m and m > n:
+            return
+        if m == 1:
+            yield [multiset[:]]
+            return
+
+        # Split the information of the multiset into two lists -
+        # one of the elements themselves, and one (of the same length)
+        # giving the number of repeats for the corresponding element.
+        elements, multiplicities = zip(*group(multiset, False))
+
+        if len(elements) < len(multiset):
+            # General case - multiset with more than one distinct element
+            # and at least one element repeated more than once.
+            if m:
+                mpt = MultisetPartitionTraverser()
+                for state in mpt.enum_range(multiplicities, m-1, m):
+                    yield list_visitor(state, elements)
+            else:
+                for state in multiset_partitions_taocp(multiplicities):
+                    yield list_visitor(state, elements)
+        else:
+            # Set partitions case - no repeated elements. Pretty much
+            # same as int argument case above, with same possible, but
+            # currently unimplemented optimization for some cases when
+            # m is not None
+            for nc, q in _set_partitions(n):
+                if m is None or nc == m:
+                    rv = [[] for i in range(nc)]
+                    for i in range(n):
+                        rv[q[i]].append(i)
+                    yield [[multiset[j] for j in i] for i in rv]
+
+
+def partitions(n, m=None, k=None, size=False):
+    """Generate all partitions of positive integer, n.
+
+    Each partition is represented as a dictionary, mapping an integer
+    to the number of copies of that integer in the partition.  For example,
+    the first partition of 4 returned is {4: 1}, "4: one of them".
+
+    Parameters
+    ==========
+    n : int
+    m : int, optional
+        limits number of parts in partition (mnemonic: m, maximum parts)
+    k : int, optional
+        limits the numbers that are kept in the partition (mnemonic: k, keys)
+    size : bool, default: False
+        If ``True``, (M, P) is returned where M is the sum of the
+        multiplicities and P is the generated partition.
+        If ``False``, only the generated partition is returned.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import partitions
+
+    The numbers appearing in the partition (the key of the returned dict)
+    are limited with k:
+
+    >>> for p in partitions(6, k=2):  # doctest: +SKIP
+    ...     print(p)
+    {2: 3}
+    {1: 2, 2: 2}
+    {1: 4, 2: 1}
+    {1: 6}
+
+    The maximum number of parts in the partition (the sum of the values in
+    the returned dict) are limited with m (default value, None, gives
+    partitions from 1 through n):
+
+    >>> for p in partitions(6, m=2):  # doctest: +SKIP
+    ...     print(p)
+    ...
+    {6: 1}
+    {1: 1, 5: 1}
+    {2: 1, 4: 1}
+    {3: 2}
+
+    References
+    ==========
+
+    .. [1] modified from Tim Peter's version to allow for k and m values:
+           https://code.activestate.com/recipes/218332-generator-for-integer-partitions/
+
+    See Also
+    ========
+
+    sympy.combinatorics.partitions.Partition
+    sympy.combinatorics.partitions.IntegerPartition
+
+    """
+    if (n <= 0 or
+        m is not None and m < 1 or
+        k is not None and k < 1 or
+        m and k and m*k < n):
+        # the empty set is the only way to handle these inputs
+        # and returning {} to represent it is consistent with
+        # the counting convention, e.g. nT(0) == 1.
+        if size:
+            yield 0, {}
+        else:
+            yield {}
+        return
+
+    if m is None:
+        m = n
+    else:
+        m = min(m, n)
+    k = min(k or n, n)
+
+    n, m, k = as_int(n), as_int(m), as_int(k)
+    q, r = divmod(n, k)
+    ms = {k: q}
+    keys = [k]  # ms.keys(), from largest to smallest
+    if r:
+        ms[r] = 1
+        keys.append(r)
+    room = m - q - bool(r)
+    if size:
+        yield sum(ms.values()), ms.copy()
+    else:
+        yield ms.copy()
+
+    while keys != [1]:
+        # Reuse any 1's.
+        if keys[-1] == 1:
+            del keys[-1]
+            reuse = ms.pop(1)
+            room += reuse
+        else:
+            reuse = 0
+
+        while 1:
+            # Let i be the smallest key larger than 1.  Reuse one
+            # instance of i.
+            i = keys[-1]
+            newcount = ms[i] = ms[i] - 1
+            reuse += i
+            if newcount == 0:
+                del keys[-1], ms[i]
+            room += 1
+
+            # Break the remainder into pieces of size i-1.
+            i -= 1
+            q, r = divmod(reuse, i)
+            need = q + bool(r)
+            if need > room:
+                if not keys:
+                    return
+                continue
+
+            ms[i] = q
+            keys.append(i)
+            if r:
+                ms[r] = 1
+                keys.append(r)
+            break
+        room -= need
+        if size:
+            yield sum(ms.values()), ms.copy()
+        else:
+            yield ms.copy()
+
+
+def ordered_partitions(n, m=None, sort=True):
+    """Generates ordered partitions of integer *n*.
+
+    Parameters
+    ==========
+    n : int
+    m : int, optional
+        The default value gives partitions of all sizes else only
+        those with size m. In addition, if *m* is not None then
+        partitions are generated *in place* (see examples).
+    sort : bool, default: True
+        Controls whether partitions are
+        returned in sorted order when *m* is not None; when False,
+        the partitions are returned as fast as possible with elements
+        sorted, but when m|n the partitions will not be in
+        ascending lexicographical order.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import ordered_partitions
+
+    All partitions of 5 in ascending lexicographical:
+
+    >>> for p in ordered_partitions(5):
+    ...     print(p)
+    [1, 1, 1, 1, 1]
+    [1, 1, 1, 2]
+    [1, 1, 3]
+    [1, 2, 2]
+    [1, 4]
+    [2, 3]
+    [5]
+
+    Only partitions of 5 with two parts:
+
+    >>> for p in ordered_partitions(5, 2):
+    ...     print(p)
+    [1, 4]
+    [2, 3]
+
+    When ``m`` is given, a given list objects will be used more than
+    once for speed reasons so you will not see the correct partitions
+    unless you make a copy of each as it is generated:
+
+    >>> [p for p in ordered_partitions(7, 3)]
+    [[1, 1, 1], [1, 1, 1], [1, 1, 1], [2, 2, 2]]
+    >>> [list(p) for p in ordered_partitions(7, 3)]
+    [[1, 1, 5], [1, 2, 4], [1, 3, 3], [2, 2, 3]]
+
+    When ``n`` is a multiple of ``m``, the elements are still sorted
+    but the partitions themselves will be *unordered* if sort is False;
+    the default is to return them in ascending lexicographical order.
+
+    >>> for p in ordered_partitions(6, 2):
+    ...     print(p)
+    [1, 5]
+    [2, 4]
+    [3, 3]
+
+    But if speed is more important than ordering, sort can be set to
+    False:
+
+    >>> for p in ordered_partitions(6, 2, sort=False):
+    ...     print(p)
+    [1, 5]
+    [3, 3]
+    [2, 4]
+
+    References
+    ==========
+
+    .. [1] Generating Integer Partitions, [online],
+        Available: https://jeromekelleher.net/generating-integer-partitions.html
+    .. [2] Jerome Kelleher and Barry O'Sullivan, "Generating All
+        Partitions: A Comparison Of Two Encodings", [online],
+        Available: https://arxiv.org/pdf/0909.2331v2.pdf
+    """
+    if n < 1 or m is not None and m < 1:
+        # the empty set is the only way to handle these inputs
+        # and returning {} to represent it is consistent with
+        # the counting convention, e.g. nT(0) == 1.
+        yield []
+        return
+
+    if m is None:
+        # The list `a`'s leading elements contain the partition in which
+        # y is the biggest element and x is either the same as y or the
+        # 2nd largest element; v and w are adjacent element indices
+        # to which x and y are being assigned, respectively.
+        a = [1]*n
+        y = -1
+        v = n
+        while v > 0:
+            v -= 1
+            x = a[v] + 1
+            while y >= 2 * x:
+                a[v] = x
+                y -= x
+                v += 1
+            w = v + 1
+            while x <= y:
+                a[v] = x
+                a[w] = y
+                yield a[:w + 1]
+                x += 1
+                y -= 1
+            a[v] = x + y
+            y = a[v] - 1
+            yield a[:w]
+    elif m == 1:
+        yield [n]
+    elif n == m:
+        yield [1]*n
+    else:
+        # recursively generate partitions of size m
+        for b in range(1, n//m + 1):
+            a = [b]*m
+            x = n - b*m
+            if not x:
+                if sort:
+                    yield a
+            elif not sort and x <= m:
+                for ax in ordered_partitions(x, sort=False):
+                    mi = len(ax)
+                    a[-mi:] = [i + b for i in ax]
+                    yield a
+                    a[-mi:] = [b]*mi
+            else:
+                for mi in range(1, m):
+                    for ax in ordered_partitions(x, mi, sort=True):
+                        a[-mi:] = [i + b for i in ax]
+                        yield a
+                        a[-mi:] = [b]*mi
+
+
+def binary_partitions(n):
+    """
+    Generates the binary partition of *n*.
+
+    A binary partition consists only of numbers that are
+    powers of two. Each step reduces a `2^{k+1}` to `2^k` and
+    `2^k`. Thus 16 is converted to 8 and 8.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import binary_partitions
+    >>> for i in binary_partitions(5):
+    ...     print(i)
+    ...
+    [4, 1]
+    [2, 2, 1]
+    [2, 1, 1, 1]
+    [1, 1, 1, 1, 1]
+
+    References
+    ==========
+
+    .. [1] TAOCP 4, section 7.2.1.5, problem 64
+
+    """
+    from math import ceil, log2
+    power = int(2**(ceil(log2(n))))
+    acc = 0
+    partition = []
+    while power:
+        if acc + power <= n:
+            partition.append(power)
+            acc += power
+        power >>= 1
+
+    last_num = len(partition) - 1 - (n & 1)
+    while last_num >= 0:
+        yield partition
+        if partition[last_num] == 2:
+            partition[last_num] = 1
+            partition.append(1)
+            last_num -= 1
+            continue
+        partition.append(1)
+        partition[last_num] >>= 1
+        x = partition[last_num + 1] = partition[last_num]
+        last_num += 1
+        while x > 1:
+            if x <= len(partition) - last_num - 1:
+                del partition[-x + 1:]
+                last_num += 1
+                partition[last_num] = x
+            else:
+                x >>= 1
+    yield [1]*n
+
+
+def has_dups(seq):
+    """Return True if there are any duplicate elements in ``seq``.
+
+    Examples
+    ========
+
+    >>> from sympy import has_dups, Dict, Set
+    >>> has_dups((1, 2, 1))
+    True
+    >>> has_dups(range(3))
+    False
+    >>> all(has_dups(c) is False for c in (set(), Set(), dict(), Dict()))
+    True
+    """
+    from sympy.core.containers import Dict
+    from sympy.sets.sets import Set
+    if isinstance(seq, (dict, set, Dict, Set)):
+        return False
+    unique = set()
+    try:
+        return any(True for s in seq if s in unique or unique.add(s))
+    except TypeError:
+        return len(seq) != len(list(uniq(seq)))
+
+
+def has_variety(seq):
+    """Return True if there are any different elements in ``seq``.
+
+    Examples
+    ========
+
+    >>> from sympy import has_variety
+
+    >>> has_variety((1, 2, 1))
+    True
+    >>> has_variety((1, 1, 1))
+    False
+    """
+    for i, s in enumerate(seq):
+        if i == 0:
+            sentinel = s
+        else:
+            if s != sentinel:
+                return True
+    return False
+
+
+def uniq(seq, result=None):
+    """
+    Yield unique elements from ``seq`` as an iterator. The second
+    parameter ``result``  is used internally; it is not necessary
+    to pass anything for this.
+
+    Note: changing the sequence during iteration will raise a
+    RuntimeError if the size of the sequence is known; if you pass
+    an iterator and advance the iterator you will change the
+    output of this routine but there will be no warning.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import uniq
+    >>> dat = [1, 4, 1, 5, 4, 2, 1, 2]
+    >>> type(uniq(dat)) in (list, tuple)
+    False
+
+    >>> list(uniq(dat))
+    [1, 4, 5, 2]
+    >>> list(uniq(x for x in dat))
+    [1, 4, 5, 2]
+    >>> list(uniq([[1], [2, 1], [1]]))
+    [[1], [2, 1]]
+    """
+    try:
+        n = len(seq)
+    except TypeError:
+        n = None
+    def check():
+        # check that size of seq did not change during iteration;
+        # if n == None the object won't support size changing, e.g.
+        # an iterator can't be changed
+        if n is not None and len(seq) != n:
+            raise RuntimeError('sequence changed size during iteration')
+    try:
+        seen = set()
+        result = result or []
+        for i, s in enumerate(seq):
+            if not (s in seen or seen.add(s)):
+                yield s
+                check()
+    except TypeError:
+        if s not in result:
+            yield s
+            check()
+            result.append(s)
+        if hasattr(seq, '__getitem__'):
+            yield from uniq(seq[i + 1:], result)
+        else:
+            yield from uniq(seq, result)
+
+
+def generate_bell(n):
+    """Return permutations of [0, 1, ..., n - 1] such that each permutation
+    differs from the last by the exchange of a single pair of neighbors.
+    The ``n!`` permutations are returned as an iterator. In order to obtain
+    the next permutation from a random starting permutation, use the
+    ``next_trotterjohnson`` method of the Permutation class (which generates
+    the same sequence in a different manner).
+
+    Examples
+    ========
+
+    >>> from itertools import permutations
+    >>> from sympy.utilities.iterables import generate_bell
+    >>> from sympy import zeros, Matrix
+
+    This is the sort of permutation used in the ringing of physical bells,
+    and does not produce permutations in lexicographical order. Rather, the
+    permutations differ from each other by exactly one inversion, and the
+    position at which the swapping occurs varies periodically in a simple
+    fashion. Consider the first few permutations of 4 elements generated
+    by ``permutations`` and ``generate_bell``:
+
+    >>> list(permutations(range(4)))[:5]
+    [(0, 1, 2, 3), (0, 1, 3, 2), (0, 2, 1, 3), (0, 2, 3, 1), (0, 3, 1, 2)]
+    >>> list(generate_bell(4))[:5]
+    [(0, 1, 2, 3), (0, 1, 3, 2), (0, 3, 1, 2), (3, 0, 1, 2), (3, 0, 2, 1)]
+
+    Notice how the 2nd and 3rd lexicographical permutations have 3 elements
+    out of place whereas each "bell" permutation always has only two
+    elements out of place relative to the previous permutation (and so the
+    signature (+/-1) of a permutation is opposite of the signature of the
+    previous permutation).
+
+    How the position of inversion varies across the elements can be seen
+    by tracing out where the largest number appears in the permutations:
+
+    >>> m = zeros(4, 24)
+    >>> for i, p in enumerate(generate_bell(4)):
+    ...     m[:, i] = Matrix([j - 3 for j in list(p)])  # make largest zero
+    >>> m.print_nonzero('X')
+    [XXX  XXXXXX  XXXXXX  XXX]
+    [XX XX XXXX XX XXXX XX XX]
+    [X XXXX XX XXXX XX XXXX X]
+    [ XXXXXX  XXXXXX  XXXXXX ]
+
+    See Also
+    ========
+
+    sympy.combinatorics.permutations.Permutation.next_trotterjohnson
+
+    References
+    ==========
+
+    .. [1] https://en.wikipedia.org/wiki/Method_ringing
+
+    .. [2] https://stackoverflow.com/questions/4856615/recursive-permutation/4857018
+
+    .. [3] https://web.archive.org/web/20160313023044/http://programminggeeks.com/bell-algorithm-for-permutation/
+
+    .. [4] https://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm
+
+    .. [5] Generating involutions, derangements, and relatives by ECO
+           Vincent Vajnovszki, DMTCS vol 1 issue 12, 2010
+
+    """
+    n = as_int(n)
+    if n < 1:
+        raise ValueError('n must be a positive integer')
+    if n == 1:
+        yield (0,)
+    elif n == 2:
+        yield (0, 1)
+        yield (1, 0)
+    elif n == 3:
+        yield from [(0, 1, 2), (0, 2, 1), (2, 0, 1), (2, 1, 0), (1, 2, 0), (1, 0, 2)]
+    else:
+        m = n - 1
+        op = [0] + [-1]*m
+        l = list(range(n))
+        while True:
+            yield tuple(l)
+            # find biggest element with op
+            big = None, -1  # idx, value
+            for i in range(n):
+                if op[i] and l[i] > big[1]:
+                    big = i, l[i]
+            i, _ = big
+            if i is None:
+                break  # there are no ops left
+            # swap it with neighbor in the indicated direction
+            j = i + op[i]
+            l[i], l[j] = l[j], l[i]
+            op[i], op[j] = op[j], op[i]
+            # if it landed at the end or if the neighbor in the same
+            # direction is bigger then turn off op
+            if j == 0 or j == m or l[j + op[j]] > l[j]:
+                op[j] = 0
+            # any element bigger to the left gets +1 op
+            for i in range(j):
+                if l[i] > l[j]:
+                    op[i] = 1
+            # any element bigger to the right gets -1 op
+            for i in range(j + 1, n):
+                if l[i] > l[j]:
+                    op[i] = -1
+
+
+def generate_involutions(n):
+    """
+    Generates involutions.
+
+    An involution is a permutation that when multiplied
+    by itself equals the identity permutation. In this
+    implementation the involutions are generated using
+    Fixed Points.
+
+    Alternatively, an involution can be considered as
+    a permutation that does not contain any cycles with
+    a length that is greater than two.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import generate_involutions
+    >>> list(generate_involutions(3))
+    [(0, 1, 2), (0, 2, 1), (1, 0, 2), (2, 1, 0)]
+    >>> len(list(generate_involutions(4)))
+    10
+
+    References
+    ==========
+
+    .. [1] https://mathworld.wolfram.com/PermutationInvolution.html
+
+    """
+    idx = list(range(n))
+    for p in permutations(idx):
+        for i in idx:
+            if p[p[i]] != i:
+                break
+        else:
+            yield p
+
+
+def multiset_derangements(s):
+    """Generate derangements of the elements of s *in place*.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import multiset_derangements, uniq
+
+    Because the derangements of multisets (not sets) are generated
+    in place, copies of the return value must be made if a collection
+    of derangements is desired or else all values will be the same:
+
+    >>> list(uniq([i for i in multiset_derangements('1233')]))
+    [[None, None, None, None]]
+    >>> [i.copy() for i in multiset_derangements('1233')]
+    [['3', '3', '1', '2'], ['3', '3', '2', '1']]
+    >>> [''.join(i) for i in multiset_derangements('1233')]
+    ['3312', '3321']
+    """
+    from sympy.core.sorting import ordered
+    # create multiset dictionary of hashable elements or else
+    # remap elements to integers
+    try:
+        ms = multiset(s)
+    except TypeError:
+        # give each element a canonical integer value
+        key = dict(enumerate(ordered(uniq(s))))
+        h = []
+        for si in s:
+            for k in key:
+                if key[k] == si:
+                    h.append(k)
+                    break
+        for i in multiset_derangements(h):
+            yield [key[j] for j in i]
+        return
+
+    mx = max(ms.values())  # max repetition of any element
+    n = len(s)  # the number of elements
+
+    ## special cases
+
+    # 1) one element has more than half the total cardinality of s: no
+    # derangements are possible.
+    if mx*2 > n:
+        return
+
+    # 2) all elements appear once: singletons
+    if len(ms) == n:
+        yield from _set_derangements(s)
+        return
+
+    # find the first element that is repeated the most to place
+    # in the following two special cases where the selection
+    # is unambiguous: either there are two elements with multiplicity
+    # of mx or else there is only one with multiplicity mx
+    for M in ms:
+        if ms[M] == mx:
+            break
+
+    inonM = [i for i in range(n) if s[i] != M]  # location of non-M
+    iM = [i for i in range(n) if s[i] == M]  # locations of M
+    rv = [None]*n
+
+    # 3) half are the same
+    if 2*mx == n:
+        # M goes into non-M locations
+        for i in inonM:
+            rv[i] = M
+        # permutations of non-M go to M locations
+        for p in multiset_permutations([s[i] for i in inonM]):
+            for i, pi in zip(iM, p):
+                rv[i] = pi
+            yield rv
+        # clean-up (and encourages proper use of routine)
+        rv[:] = [None]*n
+        return
+
+    # 4) single repeat covers all but 1 of the non-repeats:
+    # if there is one repeat then the multiset of the values
+    # of ms would be {mx: 1, 1: n - mx}, i.e. there would
+    # be n - mx + 1 values with the condition that n - 2*mx = 1
+    if n - 2*mx == 1 and len(ms.values()) == n - mx + 1:
+        for i, i1 in enumerate(inonM):
+            ifill = inonM[:i] + inonM[i+1:]
+            for j in ifill:
+                rv[j] = M
+            for p in permutations([s[j] for j in ifill]):
+                rv[i1] = s[i1]
+                for j, pi in zip(iM, p):
+                    rv[j] = pi
+                k = i1
+                for j in iM:
+                    rv[j], rv[k] = rv[k], rv[j]
+                    yield rv
+                    k = j
+        # clean-up (and encourages proper use of routine)
+        rv[:] = [None]*n
+        return
+
+    ## general case is handled with 3 helpers:
+    #    1) `finish_derangements` will place the last two elements
+    #       which have arbitrary multiplicities, e.g. for multiset
+    #       {c: 3, a: 2, b: 2}, the last two elements are a and b
+    #    2) `iopen` will tell where a given element can be placed
+    #    3) `do` will recursively place elements into subsets of
+    #        valid locations
+
+    def finish_derangements():
+        """Place the last two elements into the partially completed
+        derangement, and yield the results.
+        """
+
+        a = take[1][0]  # penultimate element
+        a_ct = take[1][1]
+        b = take[0][0]  # last element to be placed
+        b_ct = take[0][1]
+
+        # split the indexes of the not-already-assigned elements of rv into
+        # three categories
+        forced_a = []  # positions which must have an a
+        forced_b = []  # positions which must have a b
+        open_free = []  # positions which could take either
+        for i in range(len(s)):
+            if rv[i] is None:
+                if s[i] == a:
+                    forced_b.append(i)
+                elif s[i] == b:
+                    forced_a.append(i)
+                else:
+                    open_free.append(i)
+
+        if len(forced_a) > a_ct or len(forced_b) > b_ct:
+            # No derangement possible
+            return
+
+        for i in forced_a:
+            rv[i] = a
+        for i in forced_b:
+            rv[i] = b
+        for a_place in combinations(open_free, a_ct - len(forced_a)):
+            for a_pos in a_place:
+                rv[a_pos] = a
+            for i in open_free:
+                if rv[i] is None:  # anything not in the subset is set to b
+                    rv[i] = b
+            yield rv
+            # Clean up/undo the final placements
+            for i in open_free:
+                rv[i] = None
+
+        # additional cleanup - clear forced_a, forced_b
+        for i in forced_a:
+            rv[i] = None
+        for i in forced_b:
+            rv[i] = None
+
+    def iopen(v):
+        # return indices at which element v can be placed in rv:
+        # locations which are not already occupied if that location
+        # does not already contain v in the same location of s
+        return [i for i in range(n) if rv[i] is None and s[i] != v]
+
+    def do(j):
+        if j == 1:
+            # handle the last two elements (regardless of multiplicity)
+            # with a special method
+            yield from finish_derangements()
+        else:
+            # place the mx elements of M into a subset of places
+            # into which it can be replaced
+            M, mx = take[j]
+            for i in combinations(iopen(M), mx):
+                # place M
+                for ii in i:
+                    rv[ii] = M
+                # recursively place the next element
+                yield from do(j - 1)
+                # mark positions where M was placed as once again
+                # open for placement of other elements
+                for ii in i:
+                    rv[ii] = None
+
+    # process elements in order of canonically decreasing multiplicity
+    take = sorted(ms.items(), key=lambda x:(x[1], x[0]))
+    yield from do(len(take) - 1)
+    rv[:] = [None]*n
+
+
+def random_derangement(t, choice=None, strict=True):
+    """Return a list of elements in which none are in the same positions
+    as they were originally. If an element fills more than half of the positions
+    then an error will be raised since no derangement is possible. To obtain
+    a derangement of as many items as possible--with some of the most numerous
+    remaining in their original positions--pass `strict=False`. To produce a
+    pseudorandom derangment, pass a pseudorandom selector like `choice` (see
+    below).
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import random_derangement
+    >>> t = 'SymPy: a CAS in pure Python'
+    >>> d = random_derangement(t)
+    >>> all(i != j for i, j in zip(d, t))
+    True
+
+    A predictable result can be obtained by using a pseudorandom
+    generator for the choice:
+
+    >>> from sympy.core.random import seed, choice as c
+    >>> seed(1)
+    >>> d = [''.join(random_derangement(t, c)) for i in range(5)]
+    >>> assert len(set(d)) != 1  # we got different values
+
+    By reseeding, the same sequence can be obtained:
+
+    >>> seed(1)
+    >>> d2 = [''.join(random_derangement(t, c)) for i in range(5)]
+    >>> assert d == d2
+    """
+    if choice is None:
+        import secrets
+        choice = secrets.choice
+    def shuffle(rv):
+        '''Knuth shuffle'''
+        for i in range(len(rv) - 1, 0, -1):
+            x = choice(rv[:i + 1])
+            j = rv.index(x)
+            rv[i], rv[j] = rv[j], rv[i]
+    def pick(rv, n):
+        '''shuffle rv and return the first n values
+        '''
+        shuffle(rv)
+        return rv[:n]
+    ms = multiset(t)
+    tot = len(t)
+    ms = sorted(ms.items(), key=lambda x: x[1])
+  # if there are not enough spaces for the most
+  # plentiful element to move to then some of them
+  # will have to stay in place
+    M, mx = ms[-1]
+    n = len(t)
+    xs = 2*mx - tot
+    if xs > 0:
+        if strict:
+            raise ValueError('no derangement possible')
+        opts = [i for (i, c) in enumerate(t) if c == ms[-1][0]]
+        pick(opts, xs)
+        stay = sorted(opts[:xs])
+        rv = list(t)
+        for i in reversed(stay):
+            rv.pop(i)
+        rv = random_derangement(rv, choice)
+        for i in stay:
+            rv.insert(i, ms[-1][0])
+        return ''.join(rv) if type(t) is str else rv
+  # the normal derangement calculated from here
+    if n == len(ms):
+      # approx 1/3 will succeed
+        rv = list(t)
+        while True:
+            shuffle(rv)
+            if all(i != j for i,j in zip(rv, t)):
+                break
+    else:
+      # general case
+        rv = [None]*n
+        while True:
+            j = 0
+            while j > -len(ms):  # do most numerous first
+                j -= 1
+                e, c = ms[j]
+                opts = [i for i in range(n) if rv[i] is None and t[i] != e]
+                if len(opts) < c:
+                    for i in range(n):
+                        rv[i] = None
+                    break # try again
+                pick(opts, c)
+                for i in range(c):
+                    rv[opts[i]] = e
+            else:
+                return rv
+    return rv
+
+
+def _set_derangements(s):
+    """
+    yield derangements of items in ``s`` which are assumed to contain
+    no repeated elements
+    """
+    if len(s) < 2:
+        return
+    if len(s) == 2:
+        yield [s[1], s[0]]
+        return
+    if len(s) == 3:
+        yield [s[1], s[2], s[0]]
+        yield [s[2], s[0], s[1]]
+        return
+    for p in permutations(s):
+        if not any(i == j for i, j in zip(p, s)):
+            yield list(p)
+
+
+def generate_derangements(s):
+    """
+    Return unique derangements of the elements of iterable ``s``.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import generate_derangements
+    >>> list(generate_derangements([0, 1, 2]))
+    [[1, 2, 0], [2, 0, 1]]
+    >>> list(generate_derangements([0, 1, 2, 2]))
+    [[2, 2, 0, 1], [2, 2, 1, 0]]
+    >>> list(generate_derangements([0, 1, 1]))
+    []
+
+    See Also
+    ========
+
+    sympy.functions.combinatorial.factorials.subfactorial
+
+    """
+    if not has_dups(s):
+        yield from _set_derangements(s)
+    else:
+        for p in multiset_derangements(s):
+            yield list(p)
+
+
+def necklaces(n, k, free=False):
+    """
+    A routine to generate necklaces that may (free=True) or may not
+    (free=False) be turned over to be viewed. The "necklaces" returned
+    are comprised of ``n`` integers (beads) with ``k`` different
+    values (colors). Only unique necklaces are returned.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import necklaces, bracelets
+    >>> def show(s, i):
+    ...     return ''.join(s[j] for j in i)
+
+    The "unrestricted necklace" is sometimes also referred to as a
+    "bracelet" (an object that can be turned over, a sequence that can
+    be reversed) and the term "necklace" is used to imply a sequence
+    that cannot be reversed. So ACB == ABC for a bracelet (rotate and
+    reverse) while the two are different for a necklace since rotation
+    alone cannot make the two sequences the same.
+
+    (mnemonic: Bracelets can be viewed Backwards, but Not Necklaces.)
+
+    >>> B = [show('ABC', i) for i in bracelets(3, 3)]
+    >>> N = [show('ABC', i) for i in necklaces(3, 3)]
+    >>> set(N) - set(B)
+    {'ACB'}
+
+    >>> list(necklaces(4, 2))
+    [(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 1),
+     (0, 1, 0, 1), (0, 1, 1, 1), (1, 1, 1, 1)]
+
+    >>> [show('.o', i) for i in bracelets(4, 2)]
+    ['....', '...o', '..oo', '.o.o', '.ooo', 'oooo']
+
+    References
+    ==========
+
+    .. [1] https://mathworld.wolfram.com/Necklace.html
+
+    .. [2] Frank Ruskey, Carla Savage, and Terry Min Yih Wang,
+        Generating necklaces, Journal of Algorithms 13 (1992), 414-430;
+        https://doi.org/10.1016/0196-6774(92)90047-G
+
+    """
+    # The FKM algorithm
+    if k == 0 and n > 0:
+        return
+    a = [0]*n
+    yield tuple(a)
+    if n == 0:
+        return
+    while True:
+        i = n - 1
+        while a[i] == k - 1:
+            i -= 1
+            if i == -1:
+                return
+        a[i] += 1
+        for j in range(n - i - 1):
+            a[j + i + 1] = a[j]
+        if n % (i + 1) == 0 and (not free or all(a <= a[j::-1] + a[-1:j:-1] for j in range(n - 1))):
+            # No need to test j = n - 1.
+            yield tuple(a)
+
+
+def bracelets(n, k):
+    """Wrapper to necklaces to return a free (unrestricted) necklace."""
+    return necklaces(n, k, free=True)
+
+
+def generate_oriented_forest(n):
+    """
+    This algorithm generates oriented forests.
+
+    An oriented graph is a directed graph having no symmetric pair of directed
+    edges. A forest is an acyclic graph, i.e., it has no cycles. A forest can
+    also be described as a disjoint union of trees, which are graphs in which
+    any two vertices are connected by exactly one simple path.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import generate_oriented_forest
+    >>> list(generate_oriented_forest(4))
+    [[0, 1, 2, 3], [0, 1, 2, 2], [0, 1, 2, 1], [0, 1, 2, 0], \
+    [0, 1, 1, 1], [0, 1, 1, 0], [0, 1, 0, 1], [0, 1, 0, 0], [0, 0, 0, 0]]
+
+    References
+    ==========
+
+    .. [1] T. Beyer and S.M. Hedetniemi: constant time generation of
+           rooted trees, SIAM J. Computing Vol. 9, No. 4, November 1980
+
+    .. [2] https://stackoverflow.com/questions/1633833/oriented-forest-taocp-algorithm-in-python
+
+    """
+    P = list(range(-1, n))
+    while True:
+        yield P[1:]
+        if P[n] > 0:
+            P[n] = P[P[n]]
+        else:
+            for p in range(n - 1, 0, -1):
+                if P[p] != 0:
+                    target = P[p] - 1
+                    for q in range(p - 1, 0, -1):
+                        if P[q] == target:
+                            break
+                    offset = p - q
+                    for i in range(p, n + 1):
+                        P[i] = P[i - offset]
+                    break
+            else:
+                break
+
+
+def minlex(seq, directed=True, key=None):
+    r"""
+    Return the rotation of the sequence in which the lexically smallest
+    elements appear first, e.g. `cba \rightarrow acb`.
+
+    The sequence returned is a tuple, unless the input sequence is a string
+    in which case a string is returned.
+
+    If ``directed`` is False then the smaller of the sequence and the
+    reversed sequence is returned, e.g. `cba \rightarrow abc`.
+
+    If ``key`` is not None then it is used to extract a comparison key from each element in iterable.
+
+    Examples
+    ========
+
+    >>> from sympy.combinatorics.polyhedron import minlex
+    >>> minlex((1, 2, 0))
+    (0, 1, 2)
+    >>> minlex((1, 0, 2))
+    (0, 2, 1)
+    >>> minlex((1, 0, 2), directed=False)
+    (0, 1, 2)
+
+    >>> minlex('11010011000', directed=True)
+    '00011010011'
+    >>> minlex('11010011000', directed=False)
+    '00011001011'
+
+    >>> minlex(('bb', 'aaa', 'c', 'a'))
+    ('a', 'bb', 'aaa', 'c')
+    >>> minlex(('bb', 'aaa', 'c', 'a'), key=len)
+    ('c', 'a', 'bb', 'aaa')
+
+    """
+    from sympy.functions.elementary.miscellaneous import Id
+    if key is None: key = Id
+    best = rotate_left(seq, least_rotation(seq, key=key))
+    if not directed:
+        rseq = seq[::-1]
+        rbest = rotate_left(rseq, least_rotation(rseq, key=key))
+        best = min(best, rbest, key=key)
+
+    # Convert to tuple, unless we started with a string.
+    return tuple(best) if not isinstance(seq, str) else best
+
+
+def runs(seq, op=gt):
+    """Group the sequence into lists in which successive elements
+    all compare the same with the comparison operator, ``op``:
+    op(seq[i + 1], seq[i]) is True from all elements in a run.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import runs
+    >>> from operator import ge
+    >>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2])
+    [[0, 1, 2], [2], [1, 4], [3], [2], [2]]
+    >>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2], op=ge)
+    [[0, 1, 2, 2], [1, 4], [3], [2, 2]]
+    """
+    cycles = []
+    seq = iter(seq)
+    try:
+        run = [next(seq)]
+    except StopIteration:
+        return []
+    while True:
+        try:
+            ei = next(seq)
+        except StopIteration:
+            break
+        if op(ei, run[-1]):
+            run.append(ei)
+            continue
+        else:
+            cycles.append(run)
+            run = [ei]
+    if run:
+        cycles.append(run)
+    return cycles
+
+
+def sequence_partitions(l, n, /):
+    r"""Returns the partition of sequence $l$ into $n$ bins
+
+    Explanation
+    ===========
+
+    Given the sequence $l_1 \cdots l_m \in V^+$ where
+    $V^+$ is the Kleene plus of $V$
+
+    The set of $n$ partitions of $l$ is defined as:
+
+    .. math::
+        \{(s_1, \cdots, s_n) | s_1 \in V^+, \cdots, s_n \in V^+,
+        s_1 \cdots s_n = l_1 \cdots l_m\}
+
+    Parameters
+    ==========
+
+    l : Sequence[T]
+        A nonempty sequence of any Python objects
+
+    n : int
+        A positive integer
+
+    Yields
+    ======
+
+    out : list[Sequence[T]]
+        A list of sequences with concatenation equals $l$.
+        This should conform with the type of $l$.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import sequence_partitions
+    >>> for out in sequence_partitions([1, 2, 3, 4], 2):
+    ...     print(out)
+    [[1], [2, 3, 4]]
+    [[1, 2], [3, 4]]
+    [[1, 2, 3], [4]]
+
+    Notes
+    =====
+
+    This is modified version of EnricoGiampieri's partition generator
+    from https://stackoverflow.com/questions/13131491/partition-n-items-into-k-bins-in-python-lazily
+
+    See Also
+    ========
+
+    sequence_partitions_empty
+    """
+    # Asserting l is nonempty is done only for sanity check
+    if n == 1 and l:
+        yield [l]
+        return
+    for i in range(1, len(l)):
+        for part in sequence_partitions(l[i:], n - 1):
+            yield [l[:i]] + part
+
+
+def sequence_partitions_empty(l, n, /):
+    r"""Returns the partition of sequence $l$ into $n$ bins with
+    empty sequence
+
+    Explanation
+    ===========
+
+    Given the sequence $l_1 \cdots l_m \in V^*$ where
+    $V^*$ is the Kleene star of $V$
+
+    The set of $n$ partitions of $l$ is defined as:
+
+    .. math::
+        \{(s_1, \cdots, s_n) | s_1 \in V^*, \cdots, s_n \in V^*,
+        s_1 \cdots s_n = l_1 \cdots l_m\}
+
+    There are more combinations than :func:`sequence_partitions` because
+    empty sequence can fill everywhere, so we try to provide different
+    utility for this.
+
+    Parameters
+    ==========
+
+    l : Sequence[T]
+        A sequence of any Python objects (can be possibly empty)
+
+    n : int
+        A positive integer
+
+    Yields
+    ======
+
+    out : list[Sequence[T]]
+        A list of sequences with concatenation equals $l$.
+        This should conform with the type of $l$.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import sequence_partitions_empty
+    >>> for out in sequence_partitions_empty([1, 2, 3, 4], 2):
+    ...     print(out)
+    [[], [1, 2, 3, 4]]
+    [[1], [2, 3, 4]]
+    [[1, 2], [3, 4]]
+    [[1, 2, 3], [4]]
+    [[1, 2, 3, 4], []]
+
+    See Also
+    ========
+
+    sequence_partitions
+    """
+    if n < 1:
+        return
+    if n == 1:
+        yield [l]
+        return
+    for i in range(0, len(l) + 1):
+        for part in sequence_partitions_empty(l[i:], n - 1):
+            yield [l[:i]] + part
+
+
+def kbins(l, k, ordered=None):
+    """
+    Return sequence ``l`` partitioned into ``k`` bins.
+
+    Examples
+    ========
+
+    The default is to give the items in the same order, but grouped
+    into k partitions without any reordering:
+
+    >>> from sympy.utilities.iterables import kbins
+    >>> for p in kbins(list(range(5)), 2):
+    ...     print(p)
+    ...
+    [[0], [1, 2, 3, 4]]
+    [[0, 1], [2, 3, 4]]
+    [[0, 1, 2], [3, 4]]
+    [[0, 1, 2, 3], [4]]
+
+    The ``ordered`` flag is either None (to give the simple partition
+    of the elements) or is a 2 digit integer indicating whether the order of
+    the bins and the order of the items in the bins matters. Given::
+
+        A = [[0], [1, 2]]
+        B = [[1, 2], [0]]
+        C = [[2, 1], [0]]
+        D = [[0], [2, 1]]
+
+    the following values for ``ordered`` have the shown meanings::
+
+        00 means A == B == C == D
+        01 means A == B
+        10 means A == D
+        11 means A == A
+
+    >>> for ordered_flag in [None, 0, 1, 10, 11]:
+    ...     print('ordered = %s' % ordered_flag)
+    ...     for p in kbins(list(range(3)), 2, ordered=ordered_flag):
+    ...         print('     %s' % p)
+    ...
+    ordered = None
+         [[0], [1, 2]]
+         [[0, 1], [2]]
+    ordered = 0
+         [[0, 1], [2]]
+         [[0, 2], [1]]
+         [[0], [1, 2]]
+    ordered = 1
+         [[0], [1, 2]]
+         [[0], [2, 1]]
+         [[1], [0, 2]]
+         [[1], [2, 0]]
+         [[2], [0, 1]]
+         [[2], [1, 0]]
+    ordered = 10
+         [[0, 1], [2]]
+         [[2], [0, 1]]
+         [[0, 2], [1]]
+         [[1], [0, 2]]
+         [[0], [1, 2]]
+         [[1, 2], [0]]
+    ordered = 11
+         [[0], [1, 2]]
+         [[0, 1], [2]]
+         [[0], [2, 1]]
+         [[0, 2], [1]]
+         [[1], [0, 2]]
+         [[1, 0], [2]]
+         [[1], [2, 0]]
+         [[1, 2], [0]]
+         [[2], [0, 1]]
+         [[2, 0], [1]]
+         [[2], [1, 0]]
+         [[2, 1], [0]]
+
+    See Also
+    ========
+
+    partitions, multiset_partitions
+
+    """
+    if ordered is None:
+        yield from sequence_partitions(l, k)
+    elif ordered == 11:
+        for pl in multiset_permutations(l):
+            pl = list(pl)
+            yield from sequence_partitions(pl, k)
+    elif ordered == 00:
+        yield from multiset_partitions(l, k)
+    elif ordered == 10:
+        for p in multiset_partitions(l, k):
+            for perm in permutations(p):
+                yield list(perm)
+    elif ordered == 1:
+        for kgot, p in partitions(len(l), k, size=True):
+            if kgot != k:
+                continue
+            for li in multiset_permutations(l):
+                rv = []
+                i = j = 0
+                li = list(li)
+                for size, multiplicity in sorted(p.items()):
+                    for m in range(multiplicity):
+                        j = i + size
+                        rv.append(li[i: j])
+                        i = j
+                yield rv
+    else:
+        raise ValueError(
+            'ordered must be one of 00, 01, 10 or 11, not %s' % ordered)
+
+
+def permute_signs(t):
+    """Return iterator in which the signs of non-zero elements
+    of t are permuted.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import permute_signs
+    >>> list(permute_signs((0, 1, 2)))
+    [(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2)]
+    """
+    for signs in product(*[(1, -1)]*(len(t) - t.count(0))):
+        signs = list(signs)
+        yield type(t)([i*signs.pop() if i else i for i in t])
+
+
+def signed_permutations(t):
+    """Return iterator in which the signs of non-zero elements
+    of t and the order of the elements are permuted and all
+    returned values are unique.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import signed_permutations
+    >>> list(signed_permutations((0, 1, 2)))
+    [(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2), (0, 2, 1),
+    (0, -2, 1), (0, 2, -1), (0, -2, -1), (1, 0, 2), (-1, 0, 2),
+    (1, 0, -2), (-1, 0, -2), (1, 2, 0), (-1, 2, 0), (1, -2, 0),
+    (-1, -2, 0), (2, 0, 1), (-2, 0, 1), (2, 0, -1), (-2, 0, -1),
+    (2, 1, 0), (-2, 1, 0), (2, -1, 0), (-2, -1, 0)]
+    """
+    return (type(t)(i) for j in multiset_permutations(t)
+        for i in permute_signs(j))
+
+
+def rotations(s, dir=1):
+    """Return a generator giving the items in s as list where
+    each subsequent list has the items rotated to the left (default)
+    or right (``dir=-1``) relative to the previous list.
+
+    Examples
+    ========
+
+    >>> from sympy import rotations
+    >>> list(rotations([1,2,3]))
+    [[1, 2, 3], [2, 3, 1], [3, 1, 2]]
+    >>> list(rotations([1,2,3], -1))
+    [[1, 2, 3], [3, 1, 2], [2, 3, 1]]
+    """
+    seq = list(s)
+    for i in range(len(seq)):
+        yield seq
+        seq = rotate_left(seq, dir)
+
+
+def roundrobin(*iterables):
+    """roundrobin recipe taken from itertools documentation:
+    https://docs.python.org/3/library/itertools.html#itertools-recipes
+
+    roundrobin('ABC', 'D', 'EF') --> A D E B F C
+
+    Recipe credited to George Sakkis
+    """
+    nexts = cycle(iter(it).__next__ for it in iterables)
+
+    pending = len(iterables)
+    while pending:
+        try:
+            for nxt in nexts:
+                yield nxt()
+        except StopIteration:
+            pending -= 1
+            nexts = cycle(islice(nexts, pending))
+
+
+
+class NotIterable:
+    """
+    Use this as mixin when creating a class which is not supposed to
+    return true when iterable() is called on its instances because
+    calling list() on the instance, for example, would result in
+    an infinite loop.
+    """
+    pass
+
+
+def iterable(i, exclude=(str, dict, NotIterable)):
+    """
+    Return a boolean indicating whether ``i`` is SymPy iterable.
+    True also indicates that the iterator is finite, e.g. you can
+    call list(...) on the instance.
+
+    When SymPy is working with iterables, it is almost always assuming
+    that the iterable is not a string or a mapping, so those are excluded
+    by default. If you want a pure Python definition, make exclude=None. To
+    exclude multiple items, pass them as a tuple.
+
+    You can also set the _iterable attribute to True or False on your class,
+    which will override the checks here, including the exclude test.
+
+    As a rule of thumb, some SymPy functions use this to check if they should
+    recursively map over an object. If an object is technically iterable in
+    the Python sense but does not desire this behavior (e.g., because its
+    iteration is not finite, or because iteration might induce an unwanted
+    computation), it should disable it by setting the _iterable attribute to False.
+
+    See also: is_sequence
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import iterable
+    >>> from sympy import Tuple
+    >>> things = [[1], (1,), set([1]), Tuple(1), (j for j in [1, 2]), {1:2}, '1', 1]
+    >>> for i in things:
+    ...     print('%s %s' % (iterable(i), type(i)))
+    True <... 'list'>
+    True <... 'tuple'>
+    True <... 'set'>
+    True 
+    True <... 'generator'>
+    False <... 'dict'>
+    False <... 'str'>
+    False <... 'int'>
+
+    >>> iterable({}, exclude=None)
+    True
+    >>> iterable({}, exclude=str)
+    True
+    >>> iterable("no", exclude=str)
+    False
+
+    """
+    if hasattr(i, '_iterable'):
+        return i._iterable
+    try:
+        iter(i)
+    except TypeError:
+        return False
+    if exclude:
+        return not isinstance(i, exclude)
+    return True
+
+
+def is_sequence(i, include=None):
+    """
+    Return a boolean indicating whether ``i`` is a sequence in the SymPy
+    sense. If anything that fails the test below should be included as
+    being a sequence for your application, set 'include' to that object's
+    type; multiple types should be passed as a tuple of types.
+
+    Note: although generators can generate a sequence, they often need special
+    handling to make sure their elements are captured before the generator is
+    exhausted, so these are not included by default in the definition of a
+    sequence.
+
+    See also: iterable
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.iterables import is_sequence
+    >>> from types import GeneratorType
+    >>> is_sequence([])
+    True
+    >>> is_sequence(set())
+    False
+    >>> is_sequence('abc')
+    False
+    >>> is_sequence('abc', include=str)
+    True
+    >>> generator = (c for c in 'abc')
+    >>> is_sequence(generator)
+    False
+    >>> is_sequence(generator, include=(str, GeneratorType))
+    True
+
+    """
+    return (hasattr(i, '__getitem__') and
+            iterable(i) or
+            bool(include) and
+            isinstance(i, include))
+
+
+@deprecated(
+    """
+    Using postorder_traversal from the sympy.utilities.iterables submodule is
+    deprecated.
+
+    Instead, use postorder_traversal from the top-level sympy namespace, like
+
+        sympy.postorder_traversal
+    """,
+    deprecated_since_version="1.10",
+    active_deprecations_target="deprecated-traversal-functions-moved")
+def postorder_traversal(node, keys=None):
+    from sympy.core.traversal import postorder_traversal as _postorder_traversal
+    return _postorder_traversal(node, keys=keys)
+
+
+@deprecated(
+    """
+    Using interactive_traversal from the sympy.utilities.iterables submodule
+    is deprecated.
+
+    Instead, use interactive_traversal from the top-level sympy namespace,
+    like
+
+        sympy.interactive_traversal
+    """,
+    deprecated_since_version="1.10",
+    active_deprecations_target="deprecated-traversal-functions-moved")
+def interactive_traversal(expr):
+    from sympy.interactive.traversal import interactive_traversal as _interactive_traversal
+    return _interactive_traversal(expr)
+
+
+@deprecated(
+    """
+    Importing default_sort_key from sympy.utilities.iterables is deprecated.
+    Use from sympy import default_sort_key instead.
+    """,
+    deprecated_since_version="1.10",
+active_deprecations_target="deprecated-sympy-core-compatibility",
+)
+def default_sort_key(*args, **kwargs):
+    from sympy import default_sort_key as _default_sort_key
+    return _default_sort_key(*args, **kwargs)
+
+
+@deprecated(
+    """
+    Importing default_sort_key from sympy.utilities.iterables is deprecated.
+    Use from sympy import default_sort_key instead.
+    """,
+    deprecated_since_version="1.10",
+active_deprecations_target="deprecated-sympy-core-compatibility",
+)
+def ordered(*args, **kwargs):
+    from sympy import ordered as _ordered
+    return _ordered(*args, **kwargs)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/lambdify.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/lambdify.py
new file mode 100644
index 0000000000000000000000000000000000000000..6807fdaec10963a60ba88d6e1ec6b2951c19241e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/lambdify.py
@@ -0,0 +1,1592 @@
+"""
+This module provides convenient functions to transform SymPy expressions to
+lambda functions which can be used to calculate numerical values very fast.
+"""
+
+from __future__ import annotations
+from typing import Any
+
+import builtins
+import inspect
+import keyword
+import textwrap
+import linecache
+import weakref
+
+# Required despite static analysis claiming it is not used
+from sympy.external import import_module # noqa:F401
+from sympy.utilities.exceptions import sympy_deprecation_warning
+from sympy.utilities.decorator import doctest_depends_on
+from sympy.utilities.iterables import (is_sequence, iterable,
+    NotIterable, flatten)
+from sympy.utilities.misc import filldedent
+
+
+__doctest_requires__ = {('lambdify',): ['numpy', 'tensorflow']}
+
+
+# Default namespaces, letting us define translations that can't be defined
+# by simple variable maps, like I => 1j
+MATH_DEFAULT: dict[str, Any] = {}
+CMATH_DEFAULT: dict[str,Any] = {}
+MPMATH_DEFAULT: dict[str, Any] = {}
+NUMPY_DEFAULT: dict[str, Any] = {"I": 1j}
+SCIPY_DEFAULT: dict[str, Any] = {"I": 1j}
+CUPY_DEFAULT: dict[str, Any] = {"I": 1j}
+JAX_DEFAULT: dict[str, Any] = {"I": 1j}
+TENSORFLOW_DEFAULT: dict[str, Any] = {}
+TORCH_DEFAULT: dict[str, Any] = {"I": 1j}
+SYMPY_DEFAULT: dict[str, Any] = {}
+NUMEXPR_DEFAULT: dict[str, Any] = {}
+
+# These are the namespaces the lambda functions will use.
+# These are separate from the names above because they are modified
+# throughout this file, whereas the defaults should remain unmodified.
+
+MATH = MATH_DEFAULT.copy()
+CMATH = CMATH_DEFAULT.copy()
+MPMATH = MPMATH_DEFAULT.copy()
+NUMPY = NUMPY_DEFAULT.copy()
+SCIPY = SCIPY_DEFAULT.copy()
+CUPY = CUPY_DEFAULT.copy()
+JAX = JAX_DEFAULT.copy()
+TENSORFLOW = TENSORFLOW_DEFAULT.copy()
+TORCH = TORCH_DEFAULT.copy()
+SYMPY = SYMPY_DEFAULT.copy()
+NUMEXPR = NUMEXPR_DEFAULT.copy()
+
+
+# Mappings between SymPy and other modules function names.
+MATH_TRANSLATIONS = {
+    "ceiling": "ceil",
+    "E": "e",
+    "ln": "log",
+}
+
+CMATH_TRANSLATIONS: dict[str, str] = {}
+
+# NOTE: This dictionary is reused in Function._eval_evalf to allow subclasses
+# of Function to automatically evalf.
+MPMATH_TRANSLATIONS = {
+    "Abs": "fabs",
+    "elliptic_k": "ellipk",
+    "elliptic_f": "ellipf",
+    "elliptic_e": "ellipe",
+    "elliptic_pi": "ellippi",
+    "ceiling": "ceil",
+    "chebyshevt": "chebyt",
+    "chebyshevu": "chebyu",
+    "assoc_legendre": "legenp",
+    "E": "e",
+    "I": "j",
+    "ln": "log",
+    #"lowergamma":"lower_gamma",
+    "oo": "inf",
+    #"uppergamma":"upper_gamma",
+    "LambertW": "lambertw",
+    "MutableDenseMatrix": "matrix",
+    "ImmutableDenseMatrix": "matrix",
+    "conjugate": "conj",
+    "dirichlet_eta": "altzeta",
+    "Ei": "ei",
+    "Shi": "shi",
+    "Chi": "chi",
+    "Si": "si",
+    "Ci": "ci",
+    "RisingFactorial": "rf",
+    "FallingFactorial": "ff",
+    "betainc_regularized": "betainc",
+}
+
+NUMPY_TRANSLATIONS: dict[str, str] = {
+    "Heaviside": "heaviside",
+}
+SCIPY_TRANSLATIONS: dict[str, str] = {
+    "jn" : "spherical_jn",
+    "yn" : "spherical_yn"
+}
+CUPY_TRANSLATIONS: dict[str, str] = {}
+JAX_TRANSLATIONS: dict[str, str] = {}
+
+TENSORFLOW_TRANSLATIONS: dict[str, str] = {}
+TORCH_TRANSLATIONS: dict[str, str] = {}
+
+NUMEXPR_TRANSLATIONS: dict[str, str] = {}
+
+# Available modules:
+MODULES = {
+    "math": (MATH, MATH_DEFAULT, MATH_TRANSLATIONS, ("from math import *",)),
+    "cmath": (CMATH, CMATH_DEFAULT, CMATH_TRANSLATIONS, ("import cmath; from cmath import *",)),
+    "mpmath": (MPMATH, MPMATH_DEFAULT, MPMATH_TRANSLATIONS, ("from mpmath import *",)),
+    "numpy": (NUMPY, NUMPY_DEFAULT, NUMPY_TRANSLATIONS, ("import numpy; from numpy import *; from numpy.linalg import *",)),
+    "scipy": (SCIPY, SCIPY_DEFAULT, SCIPY_TRANSLATIONS, ("import scipy; import numpy; from scipy.special import *",)),
+    "cupy": (CUPY, CUPY_DEFAULT, CUPY_TRANSLATIONS, ("import cupy",)),
+    "jax": (JAX, JAX_DEFAULT, JAX_TRANSLATIONS, ("import jax",)),
+    "tensorflow": (TENSORFLOW, TENSORFLOW_DEFAULT, TENSORFLOW_TRANSLATIONS, ("import tensorflow",)),
+    "torch": (TORCH, TORCH_DEFAULT, TORCH_TRANSLATIONS, ("import torch",)),
+    "sympy": (SYMPY, SYMPY_DEFAULT, {}, (
+        "from sympy.functions import *",
+        "from sympy.matrices import *",
+        "from sympy import Integral, pi, oo, nan, zoo, E, I",)),
+    "numexpr" : (NUMEXPR, NUMEXPR_DEFAULT, NUMEXPR_TRANSLATIONS,
+                 ("import_module('numexpr')", )),
+}
+
+
+def _import(module, reload=False):
+    """
+    Creates a global translation dictionary for module.
+
+    The argument module has to be one of the following strings: "math","cmath"
+    "mpmath", "numpy", "sympy", "tensorflow", "jax".
+    These dictionaries map names of Python functions to their equivalent in
+    other modules.
+    """
+    try:
+        namespace, namespace_default, translations, import_commands = MODULES[
+            module]
+    except KeyError:
+        raise NameError(
+            "'%s' module cannot be used for lambdification" % module)
+
+    # Clear namespace or exit
+    if namespace != namespace_default:
+        # The namespace was already generated, don't do it again if not forced.
+        if reload:
+            namespace.clear()
+            namespace.update(namespace_default)
+        else:
+            return
+
+    for import_command in import_commands:
+        if import_command.startswith('import_module'):
+            module = eval(import_command)
+
+            if module is not None:
+                namespace.update(module.__dict__)
+                continue
+        else:
+            try:
+                exec(import_command, {}, namespace)
+                continue
+            except ImportError:
+                pass
+
+        raise ImportError(
+            "Cannot import '%s' with '%s' command" % (module, import_command))
+
+    # Add translated names to namespace
+    for sympyname, translation in translations.items():
+        namespace[sympyname] = namespace[translation]
+
+    # For computing the modulus of a SymPy expression we use the builtin abs
+    # function, instead of the previously used fabs function for all
+    # translation modules. This is because the fabs function in the math
+    # module does not accept complex valued arguments. (see issue 9474). The
+    # only exception, where we don't use the builtin abs function is the
+    # mpmath translation module, because mpmath.fabs returns mpf objects in
+    # contrast to abs().
+    if 'Abs' not in namespace:
+        namespace['Abs'] = abs
+
+# Used for dynamically generated filenames that are inserted into the
+# linecache.
+_lambdify_generated_counter = 1
+
+
+@doctest_depends_on(modules=('numpy', 'scipy', 'tensorflow',), python_version=(3,))
+def lambdify(args, expr, modules=None, printer=None, use_imps=True,
+             dummify=False, cse=False, docstring_limit=1000):
+    """Convert a SymPy expression into a function that allows for fast
+    numeric evaluation.
+
+    .. warning::
+       This function uses ``exec``, and thus should not be used on
+       unsanitized input.
+
+    .. deprecated:: 1.7
+       Passing a set for the *args* parameter is deprecated as sets are
+       unordered. Use an ordered iterable such as a list or tuple.
+
+    Explanation
+    ===========
+
+    For example, to convert the SymPy expression ``sin(x) + cos(x)`` to an
+    equivalent NumPy function that numerically evaluates it:
+
+    >>> from sympy import sin, cos, symbols, lambdify
+    >>> import numpy as np
+    >>> x = symbols('x')
+    >>> expr = sin(x) + cos(x)
+    >>> expr
+    sin(x) + cos(x)
+    >>> f = lambdify(x, expr, 'numpy')
+    >>> a = np.array([1, 2])
+    >>> f(a)
+    [1.38177329 0.49315059]
+
+    The primary purpose of this function is to provide a bridge from SymPy
+    expressions to numerical libraries such as NumPy, SciPy, NumExpr, mpmath,
+    and tensorflow. In general, SymPy functions do not work with objects from
+    other libraries, such as NumPy arrays, and functions from numeric
+    libraries like NumPy or mpmath do not work on SymPy expressions.
+    ``lambdify`` bridges the two by converting a SymPy expression to an
+    equivalent numeric function.
+
+    The basic workflow with ``lambdify`` is to first create a SymPy expression
+    representing whatever mathematical function you wish to evaluate. This
+    should be done using only SymPy functions and expressions. Then, use
+    ``lambdify`` to convert this to an equivalent function for numerical
+    evaluation. For instance, above we created ``expr`` using the SymPy symbol
+    ``x`` and SymPy functions ``sin`` and ``cos``, then converted it to an
+    equivalent NumPy function ``f``, and called it on a NumPy array ``a``.
+
+    Parameters
+    ==========
+
+    args : List[Symbol]
+        A variable or a list of variables whose nesting represents the
+        nesting of the arguments that will be passed to the function.
+
+        Variables can be symbols, undefined functions, or matrix symbols.
+
+        >>> from sympy import Eq
+        >>> from sympy.abc import x, y, z
+
+        The list of variables should match the structure of how the
+        arguments will be passed to the function. Simply enclose the
+        parameters as they will be passed in a list.
+
+        To call a function like ``f(x)`` then ``[x]``
+        should be the first argument to ``lambdify``; for this
+        case a single ``x`` can also be used:
+
+        >>> f = lambdify(x, x + 1)
+        >>> f(1)
+        2
+        >>> f = lambdify([x], x + 1)
+        >>> f(1)
+        2
+
+        To call a function like ``f(x, y)`` then ``[x, y]`` will
+        be the first argument of the ``lambdify``:
+
+        >>> f = lambdify([x, y], x + y)
+        >>> f(1, 1)
+        2
+
+        To call a function with a single 3-element tuple like
+        ``f((x, y, z))`` then ``[(x, y, z)]`` will be the first
+        argument of the ``lambdify``:
+
+        >>> f = lambdify([(x, y, z)], Eq(z**2, x**2 + y**2))
+        >>> f((3, 4, 5))
+        True
+
+        If two args will be passed and the first is a scalar but
+        the second is a tuple with two arguments then the items
+        in the list should match that structure:
+
+        >>> f = lambdify([x, (y, z)], x + y + z)
+        >>> f(1, (2, 3))
+        6
+
+    expr : Expr
+        An expression, list of expressions, or matrix to be evaluated.
+
+        Lists may be nested.
+        If the expression is a list, the output will also be a list.
+
+        >>> f = lambdify(x, [x, [x + 1, x + 2]])
+        >>> f(1)
+        [1, [2, 3]]
+
+        If it is a matrix, an array will be returned (for the NumPy module).
+
+        >>> from sympy import Matrix
+        >>> f = lambdify(x, Matrix([x, x + 1]))
+        >>> f(1)
+        [[1]
+        [2]]
+
+        Note that the argument order here (variables then expression) is used
+        to emulate the Python ``lambda`` keyword. ``lambdify(x, expr)`` works
+        (roughly) like ``lambda x: expr``
+        (see :ref:`lambdify-how-it-works` below).
+
+    modules : str, optional
+        Specifies the numeric library to use.
+
+        If not specified, *modules* defaults to:
+
+        - ``["scipy", "numpy"]`` if SciPy is installed
+        - ``["numpy"]`` if only NumPy is installed
+        - ``["math","cmath", "mpmath", "sympy"]`` if neither is installed.
+
+        That is, SymPy functions are replaced as far as possible by
+        either ``scipy`` or ``numpy`` functions if available, and Python's
+        standard library ``math`` and ``cmath``, or ``mpmath`` functions otherwise.
+
+        *modules* can be one of the following types:
+
+        - The strings ``"math"``, ``"cmath"``, ``"mpmath"``, ``"numpy"``, ``"numexpr"``,
+          ``"scipy"``, ``"sympy"``, or ``"tensorflow"`` or ``"jax"``. This uses the
+          corresponding printer and namespace mapping for that module.
+        - A module (e.g., ``math``). This uses the global namespace of the
+          module. If the module is one of the above known modules, it will
+          also use the corresponding printer and namespace mapping
+          (i.e., ``modules=numpy`` is equivalent to ``modules="numpy"``).
+        - A dictionary that maps names of SymPy functions to arbitrary
+          functions
+          (e.g., ``{'sin': custom_sin}``).
+        - A list that contains a mix of the arguments above, with higher
+          priority given to entries appearing first
+          (e.g., to use the NumPy module but override the ``sin`` function
+          with a custom version, you can use
+          ``[{'sin': custom_sin}, 'numpy']``).
+
+    dummify : bool, optional
+        Whether or not the variables in the provided expression that are not
+        valid Python identifiers are substituted with dummy symbols.
+
+        This allows for undefined functions like ``Function('f')(t)`` to be
+        supplied as arguments. By default, the variables are only dummified
+        if they are not valid Python identifiers.
+
+        Set ``dummify=True`` to replace all arguments with dummy symbols
+        (if ``args`` is not a string) - for example, to ensure that the
+        arguments do not redefine any built-in names.
+
+    cse : bool, or callable, optional
+        Large expressions can be computed more efficiently when
+        common subexpressions are identified and precomputed before
+        being used multiple time. Finding the subexpressions will make
+        creation of the 'lambdify' function slower, however.
+
+        When ``True``, ``sympy.simplify.cse`` is used, otherwise (the default)
+        the user may pass a function matching the ``cse`` signature.
+
+    docstring_limit : int or None
+        When lambdifying large expressions, a significant proportion of the time
+        spent inside ``lambdify`` is spent producing a string representation of
+        the expression for use in the automatically generated docstring of the
+        returned function. For expressions containing hundreds or more nodes the
+        resulting docstring often becomes so long and dense that it is difficult
+        to read. To reduce the runtime of lambdify, the rendering of the full
+        expression inside the docstring can be disabled.
+
+        When ``None``, the full expression is rendered in the docstring. When
+        ``0`` or a negative ``int``, an ellipsis is rendering in the docstring
+        instead of the expression. When a strictly positive ``int``, if the
+        number of nodes in the expression exceeds ``docstring_limit`` an
+        ellipsis is rendered in the docstring, otherwise a string representation
+        of the expression is rendered as normal. The default is ``1000``.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.lambdify import implemented_function
+    >>> from sympy import sqrt, sin, Matrix
+    >>> from sympy import Function
+    >>> from sympy.abc import w, x, y, z
+
+    >>> f = lambdify(x, x**2)
+    >>> f(2)
+    4
+    >>> f = lambdify((x, y, z), [z, y, x])
+    >>> f(1,2,3)
+    [3, 2, 1]
+    >>> f = lambdify(x, sqrt(x))
+    >>> f(4)
+    2.0
+    >>> f = lambdify((x, y), sin(x*y)**2)
+    >>> f(0, 5)
+    0.0
+    >>> row = lambdify((x, y), Matrix((x, x + y)).T, modules='sympy')
+    >>> row(1, 2)
+    Matrix([[1, 3]])
+
+    ``lambdify`` can be used to translate SymPy expressions into mpmath
+    functions. This may be preferable to using ``evalf`` (which uses mpmath on
+    the backend) in some cases.
+
+    >>> f = lambdify(x, sin(x), 'mpmath')
+    >>> f(1)
+    0.8414709848078965
+
+    Tuple arguments are handled and the lambdified function should
+    be called with the same type of arguments as were used to create
+    the function:
+
+    >>> f = lambdify((x, (y, z)), x + y)
+    >>> f(1, (2, 4))
+    3
+
+    The ``flatten`` function can be used to always work with flattened
+    arguments:
+
+    >>> from sympy.utilities.iterables import flatten
+    >>> args = w, (x, (y, z))
+    >>> vals = 1, (2, (3, 4))
+    >>> f = lambdify(flatten(args), w + x + y + z)
+    >>> f(*flatten(vals))
+    10
+
+    Functions present in ``expr`` can also carry their own numerical
+    implementations, in a callable attached to the ``_imp_`` attribute. This
+    can be used with undefined functions using the ``implemented_function``
+    factory:
+
+    >>> f = implemented_function(Function('f'), lambda x: x+1)
+    >>> func = lambdify(x, f(x))
+    >>> func(4)
+    5
+
+    ``lambdify`` always prefers ``_imp_`` implementations to implementations
+    in other namespaces, unless the ``use_imps`` input parameter is False.
+
+    Usage with Tensorflow:
+
+    >>> import tensorflow as tf
+    >>> from sympy import Max, sin, lambdify
+    >>> from sympy.abc import x
+
+    >>> f = Max(x, sin(x))
+    >>> func = lambdify(x, f, 'tensorflow')
+
+    After tensorflow v2, eager execution is enabled by default.
+    If you want to get the compatible result across tensorflow v1 and v2
+    as same as this tutorial, run this line.
+
+    >>> tf.compat.v1.enable_eager_execution()
+
+    If you have eager execution enabled, you can get the result out
+    immediately as you can use numpy.
+
+    If you pass tensorflow objects, you may get an ``EagerTensor``
+    object instead of value.
+
+    >>> result = func(tf.constant(1.0))
+    >>> print(result)
+    tf.Tensor(1.0, shape=(), dtype=float32)
+    >>> print(result.__class__)
+    
+
+    You can use ``.numpy()`` to get the numpy value of the tensor.
+
+    >>> result.numpy()
+    1.0
+
+    >>> var = tf.Variable(2.0)
+    >>> result = func(var) # also works for tf.Variable and tf.Placeholder
+    >>> result.numpy()
+    2.0
+
+    And it works with any shape array.
+
+    >>> tensor = tf.constant([[1.0, 2.0], [3.0, 4.0]])
+    >>> result = func(tensor)
+    >>> result.numpy()
+    [[1. 2.]
+     [3. 4.]]
+
+    Notes
+    =====
+
+    - For functions involving large array calculations, numexpr can provide a
+      significant speedup over numpy. Please note that the available functions
+      for numexpr are more limited than numpy but can be expanded with
+      ``implemented_function`` and user defined subclasses of Function. If
+      specified, numexpr may be the only option in modules. The official list
+      of numexpr functions can be found at:
+      https://numexpr.readthedocs.io/en/latest/user_guide.html#supported-functions
+
+    - In the above examples, the generated functions can accept scalar
+      values or numpy arrays as arguments.  However, in some cases
+      the generated function relies on the input being a numpy array:
+
+      >>> import numpy
+      >>> from sympy import Piecewise
+      >>> from sympy.testing.pytest import ignore_warnings
+      >>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "numpy")
+
+      >>> with ignore_warnings(RuntimeWarning):
+      ...     f(numpy.array([-1, 0, 1, 2]))
+      [-1.   0.   1.   0.5]
+
+      >>> f(0)
+      Traceback (most recent call last):
+          ...
+      ZeroDivisionError: division by zero
+
+      In such cases, the input should be wrapped in a numpy array:
+
+      >>> with ignore_warnings(RuntimeWarning):
+      ...     float(f(numpy.array([0])))
+      0.0
+
+      Or if numpy functionality is not required another module can be used:
+
+      >>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "math")
+      >>> f(0)
+      0
+
+    .. _lambdify-how-it-works:
+
+    How it works
+    ============
+
+    When using this function, it helps a great deal to have an idea of what it
+    is doing. At its core, lambdify is nothing more than a namespace
+    translation, on top of a special printer that makes some corner cases work
+    properly.
+
+    To understand lambdify, first we must properly understand how Python
+    namespaces work. Say we had two files. One called ``sin_cos_sympy.py``,
+    with
+
+    .. code:: python
+
+        # sin_cos_sympy.py
+
+        from sympy.functions.elementary.trigonometric import (cos, sin)
+
+        def sin_cos(x):
+            return sin(x) + cos(x)
+
+
+    and one called ``sin_cos_numpy.py`` with
+
+    .. code:: python
+
+        # sin_cos_numpy.py
+
+        from numpy import sin, cos
+
+        def sin_cos(x):
+            return sin(x) + cos(x)
+
+    The two files define an identical function ``sin_cos``. However, in the
+    first file, ``sin`` and ``cos`` are defined as the SymPy ``sin`` and
+    ``cos``. In the second, they are defined as the NumPy versions.
+
+    If we were to import the first file and use the ``sin_cos`` function, we
+    would get something like
+
+    >>> from sin_cos_sympy import sin_cos # doctest: +SKIP
+    >>> sin_cos(1) # doctest: +SKIP
+    cos(1) + sin(1)
+
+    On the other hand, if we imported ``sin_cos`` from the second file, we
+    would get
+
+    >>> from sin_cos_numpy import sin_cos # doctest: +SKIP
+    >>> sin_cos(1) # doctest: +SKIP
+    1.38177329068
+
+    In the first case we got a symbolic output, because it used the symbolic
+    ``sin`` and ``cos`` functions from SymPy. In the second, we got a numeric
+    result, because ``sin_cos`` used the numeric ``sin`` and ``cos`` functions
+    from NumPy. But notice that the versions of ``sin`` and ``cos`` that were
+    used was not inherent to the ``sin_cos`` function definition. Both
+    ``sin_cos`` definitions are exactly the same. Rather, it was based on the
+    names defined at the module where the ``sin_cos`` function was defined.
+
+    The key point here is that when function in Python references a name that
+    is not defined in the function, that name is looked up in the "global"
+    namespace of the module where that function is defined.
+
+    Now, in Python, we can emulate this behavior without actually writing a
+    file to disk using the ``exec`` function. ``exec`` takes a string
+    containing a block of Python code, and a dictionary that should contain
+    the global variables of the module. It then executes the code "in" that
+    dictionary, as if it were the module globals. The following is equivalent
+    to the ``sin_cos`` defined in ``sin_cos_sympy.py``:
+
+    >>> import sympy
+    >>> module_dictionary = {'sin': sympy.sin, 'cos': sympy.cos}
+    >>> exec('''
+    ... def sin_cos(x):
+    ...     return sin(x) + cos(x)
+    ... ''', module_dictionary)
+    >>> sin_cos = module_dictionary['sin_cos']
+    >>> sin_cos(1)
+    cos(1) + sin(1)
+
+    and similarly with ``sin_cos_numpy``:
+
+    >>> import numpy
+    >>> module_dictionary = {'sin': numpy.sin, 'cos': numpy.cos}
+    >>> exec('''
+    ... def sin_cos(x):
+    ...     return sin(x) + cos(x)
+    ... ''', module_dictionary)
+    >>> sin_cos = module_dictionary['sin_cos']
+    >>> sin_cos(1)
+    1.38177329068
+
+    So now we can get an idea of how ``lambdify`` works. The name "lambdify"
+    comes from the fact that we can think of something like ``lambdify(x,
+    sin(x) + cos(x), 'numpy')`` as ``lambda x: sin(x) + cos(x)``, where
+    ``sin`` and ``cos`` come from the ``numpy`` namespace. This is also why
+    the symbols argument is first in ``lambdify``, as opposed to most SymPy
+    functions where it comes after the expression: to better mimic the
+    ``lambda`` keyword.
+
+    ``lambdify`` takes the input expression (like ``sin(x) + cos(x)``) and
+
+    1. Converts it to a string
+    2. Creates a module globals dictionary based on the modules that are
+       passed in (by default, it uses the NumPy module)
+    3. Creates the string ``"def func({vars}): return {expr}"``, where ``{vars}`` is the
+       list of variables separated by commas, and ``{expr}`` is the string
+       created in step 1., then ``exec``s that string with the module globals
+       namespace and returns ``func``.
+
+    In fact, functions returned by ``lambdify`` support inspection. So you can
+    see exactly how they are defined by using ``inspect.getsource``, or ``??`` if you
+    are using IPython or the Jupyter notebook.
+
+    >>> f = lambdify(x, sin(x) + cos(x))
+    >>> import inspect
+    >>> print(inspect.getsource(f))
+    def _lambdifygenerated(x):
+        return sin(x) + cos(x)
+
+    This shows us the source code of the function, but not the namespace it
+    was defined in. We can inspect that by looking at the ``__globals__``
+    attribute of ``f``:
+
+    >>> f.__globals__['sin']
+    
+    >>> f.__globals__['cos']
+    
+    >>> f.__globals__['sin'] is numpy.sin
+    True
+
+    This shows us that ``sin`` and ``cos`` in the namespace of ``f`` will be
+    ``numpy.sin`` and ``numpy.cos``.
+
+    Note that there are some convenience layers in each of these steps, but at
+    the core, this is how ``lambdify`` works. Step 1 is done using the
+    ``LambdaPrinter`` printers defined in the printing module (see
+    :mod:`sympy.printing.lambdarepr`). This allows different SymPy expressions
+    to define how they should be converted to a string for different modules.
+    You can change which printer ``lambdify`` uses by passing a custom printer
+    in to the ``printer`` argument.
+
+    Step 2 is augmented by certain translations. There are default
+    translations for each module, but you can provide your own by passing a
+    list to the ``modules`` argument. For instance,
+
+    >>> def mysin(x):
+    ...     print('taking the sin of', x)
+    ...     return numpy.sin(x)
+    ...
+    >>> f = lambdify(x, sin(x), [{'sin': mysin}, 'numpy'])
+    >>> f(1)
+    taking the sin of 1
+    0.8414709848078965
+
+    The globals dictionary is generated from the list by merging the
+    dictionary ``{'sin': mysin}`` and the module dictionary for NumPy. The
+    merging is done so that earlier items take precedence, which is why
+    ``mysin`` is used above instead of ``numpy.sin``.
+
+    If you want to modify the way ``lambdify`` works for a given function, it
+    is usually easiest to do so by modifying the globals dictionary as such.
+    In more complicated cases, it may be necessary to create and pass in a
+    custom printer.
+
+    Finally, step 3 is augmented with certain convenience operations, such as
+    the addition of a docstring.
+
+    Understanding how ``lambdify`` works can make it easier to avoid certain
+    gotchas when using it. For instance, a common mistake is to create a
+    lambdified function for one module (say, NumPy), and pass it objects from
+    another (say, a SymPy expression).
+
+    For instance, say we create
+
+    >>> from sympy.abc import x
+    >>> f = lambdify(x, x + 1, 'numpy')
+
+    Now if we pass in a NumPy array, we get that array plus 1
+
+    >>> import numpy
+    >>> a = numpy.array([1, 2])
+    >>> f(a)
+    [2 3]
+
+    But what happens if you make the mistake of passing in a SymPy expression
+    instead of a NumPy array:
+
+    >>> f(x + 1)
+    x + 2
+
+    This worked, but it was only by accident. Now take a different lambdified
+    function:
+
+    >>> from sympy import sin
+    >>> g = lambdify(x, x + sin(x), 'numpy')
+
+    This works as expected on NumPy arrays:
+
+    >>> g(a)
+    [1.84147098 2.90929743]
+
+    But if we try to pass in a SymPy expression, it fails
+
+    >>> g(x + 1)
+    Traceback (most recent call last):
+    ...
+    TypeError: loop of ufunc does not support argument 0 of type Add which has
+               no callable sin method
+
+    Now, let's look at what happened. The reason this fails is that ``g``
+    calls ``numpy.sin`` on the input expression, and ``numpy.sin`` does not
+    know how to operate on a SymPy object. **As a general rule, NumPy
+    functions do not know how to operate on SymPy expressions, and SymPy
+    functions do not know how to operate on NumPy arrays. This is why lambdify
+    exists: to provide a bridge between SymPy and NumPy.**
+
+    However, why is it that ``f`` did work? That's because ``f`` does not call
+    any functions, it only adds 1. So the resulting function that is created,
+    ``def _lambdifygenerated(x): return x + 1`` does not depend on the globals
+    namespace it is defined in. Thus it works, but only by accident. A future
+    version of ``lambdify`` may remove this behavior.
+
+    Be aware that certain implementation details described here may change in
+    future versions of SymPy. The API of passing in custom modules and
+    printers will not change, but the details of how a lambda function is
+    created may change. However, the basic idea will remain the same, and
+    understanding it will be helpful to understanding the behavior of
+    lambdify.
+
+    **In general: you should create lambdified functions for one module (say,
+    NumPy), and only pass it input types that are compatible with that module
+    (say, NumPy arrays).** Remember that by default, if the ``module``
+    argument is not provided, ``lambdify`` creates functions using the NumPy
+    and SciPy namespaces.
+    """
+    from sympy.core.symbol import Symbol
+    from sympy.core.expr import Expr
+
+    # If the user hasn't specified any modules, use what is available.
+    if modules is None:
+        try:
+            _import("scipy")
+        except ImportError:
+            try:
+                _import("numpy")
+            except ImportError:
+                # Use either numpy (if available) or python.math where possible.
+                # XXX: This leads to different behaviour on different systems and
+                #      might be the reason for irreproducible errors.
+                modules = ["math", "mpmath", "sympy"]
+            else:
+                modules = ["numpy"]
+        else:
+            modules = ["numpy", "scipy"]
+
+    # Get the needed namespaces.
+    namespaces = []
+    # First find any function implementations
+    if use_imps:
+        namespaces.append(_imp_namespace(expr))
+    # Check for dict before iterating
+    if isinstance(modules, (dict, str)) or not hasattr(modules, '__iter__'):
+        namespaces.append(modules)
+    else:
+        # consistency check
+        if _module_present('numexpr', modules) and len(modules) > 1:
+            raise TypeError("numexpr must be the only item in 'modules'")
+        namespaces += list(modules)
+    # fill namespace with first having highest priority
+    namespace = {}
+    for m in namespaces[::-1]:
+        buf = _get_namespace(m)
+        namespace.update(buf)
+
+    if hasattr(expr, "atoms"):
+        #Try if you can extract symbols from the expression.
+        #Move on if expr.atoms in not implemented.
+        syms = expr.atoms(Symbol)
+        for term in syms:
+            namespace.update({str(term): term})
+
+    if printer is None:
+        if _module_present('mpmath', namespaces):
+            from sympy.printing.pycode import MpmathPrinter as Printer # type: ignore
+        elif _module_present('scipy', namespaces):
+            from sympy.printing.numpy import SciPyPrinter as Printer # type: ignore
+        elif _module_present('numpy', namespaces):
+            from sympy.printing.numpy import NumPyPrinter as Printer # type: ignore
+        elif _module_present('cupy', namespaces):
+            from sympy.printing.numpy import CuPyPrinter as Printer # type: ignore
+        elif _module_present('jax', namespaces):
+            from sympy.printing.numpy import JaxPrinter as Printer # type: ignore
+        elif _module_present('numexpr', namespaces):
+            from sympy.printing.lambdarepr import NumExprPrinter as Printer # type: ignore
+        elif _module_present('tensorflow', namespaces):
+            from sympy.printing.tensorflow import TensorflowPrinter as Printer # type: ignore
+        elif _module_present('torch', namespaces):
+            from sympy.printing.pytorch import TorchPrinter as Printer  # type: ignore
+        elif _module_present('sympy', namespaces):
+            from sympy.printing.pycode import SymPyPrinter as Printer # type: ignore
+        elif _module_present('cmath', namespaces):
+            from sympy.printing.pycode import CmathPrinter as Printer # type: ignore
+        else:
+            from sympy.printing.pycode import PythonCodePrinter as Printer # type: ignore
+        user_functions = {}
+        for m in namespaces[::-1]:
+            if isinstance(m, dict):
+                for k in m:
+                    user_functions[k] = k
+        printer = Printer({'fully_qualified_modules': False, 'inline': True,
+                           'allow_unknown_functions': True,
+                           'user_functions': user_functions})
+
+    if isinstance(args, set):
+        sympy_deprecation_warning(
+            """
+Passing the function arguments to lambdify() as a set is deprecated. This
+leads to unpredictable results since sets are unordered. Instead, use a list
+or tuple for the function arguments.
+            """,
+            deprecated_since_version="1.6.3",
+            active_deprecations_target="deprecated-lambdify-arguments-set",
+                )
+
+    # Get the names of the args, for creating a docstring
+    iterable_args = (args,) if isinstance(args, Expr) else args
+    names = []
+
+    # Grab the callers frame, for getting the names by inspection (if needed)
+    callers_local_vars = inspect.currentframe().f_back.f_locals.items() # type: ignore
+    for n, var in enumerate(iterable_args):
+        if hasattr(var, 'name'):
+            names.append(var.name)
+        else:
+            # It's an iterable. Try to get name by inspection of calling frame.
+            name_list = [var_name for var_name, var_val in callers_local_vars
+                    if var_val is var]
+            if len(name_list) == 1:
+                names.append(name_list[0])
+            else:
+                # Cannot infer name with certainty. arg_# will have to do.
+                names.append('arg_' + str(n))
+
+    # Create the function definition code and execute it
+    funcname = '_lambdifygenerated'
+    if _module_present('tensorflow', namespaces):
+        funcprinter = _TensorflowEvaluatorPrinter(printer, dummify)
+    else:
+        funcprinter = _EvaluatorPrinter(printer, dummify)
+
+    if cse == True:
+        from sympy.simplify.cse_main import cse as _cse
+        cses, _expr = _cse(expr, list=False)
+    elif callable(cse):
+        cses, _expr = cse(expr)
+    else:
+        cses, _expr = (), expr
+    funcstr = funcprinter.doprint(funcname, iterable_args, _expr, cses=cses)
+
+    # Collect the module imports from the code printers.
+    imp_mod_lines = []
+    for mod, keys in (getattr(printer, 'module_imports', None) or {}).items():
+        for k in keys:
+            if k not in namespace:
+                ln = "from %s import %s" % (mod, k)
+                try:
+                    exec(ln, {}, namespace)
+                except ImportError:
+                    # Tensorflow 2.0 has issues with importing a specific
+                    # function from its submodule.
+                    # https://github.com/tensorflow/tensorflow/issues/33022
+                    ln = "%s = %s.%s" % (k, mod, k)
+                    exec(ln, {}, namespace)
+                imp_mod_lines.append(ln)
+
+    # Provide lambda expression with builtins, and compatible implementation of range
+    namespace.update({'builtins':builtins, 'range':range})
+
+    funclocals = {}
+    global _lambdify_generated_counter
+    filename = '' % _lambdify_generated_counter
+    _lambdify_generated_counter += 1
+    c = compile(funcstr, filename, 'exec')
+    exec(c, namespace, funclocals)
+    # mtime has to be None or else linecache.checkcache will remove it
+    linecache.cache[filename] = (len(funcstr), None, funcstr.splitlines(True), filename) # type: ignore
+
+    # Remove the entry from the linecache when the object is garbage collected
+    def cleanup_linecache(filename):
+        def _cleanup():
+            if filename in linecache.cache:
+                del linecache.cache[filename]
+        return _cleanup
+
+    func = funclocals[funcname]
+
+    weakref.finalize(func, cleanup_linecache(filename))
+
+    # Apply the docstring
+    sig = "func({})".format(", ".join(str(i) for i in names))
+    sig = textwrap.fill(sig, subsequent_indent=' '*8)
+    if _too_large_for_docstring(expr, docstring_limit):
+        expr_str = "EXPRESSION REDACTED DUE TO LENGTH, (see lambdify's `docstring_limit`)"
+        src_str = "SOURCE CODE REDACTED DUE TO LENGTH, (see lambdify's `docstring_limit`)"
+    else:
+        expr_str = str(expr)
+        if len(expr_str) > 78:
+            expr_str = textwrap.wrap(expr_str, 75)[0] + '...'
+        src_str = funcstr
+    func.__doc__ = (
+        "Created with lambdify. Signature:\n\n"
+        "{sig}\n\n"
+        "Expression:\n\n"
+        "{expr}\n\n"
+        "Source code:\n\n"
+        "{src}\n\n"
+        "Imported modules:\n\n"
+        "{imp_mods}"
+        ).format(sig=sig, expr=expr_str, src=src_str, imp_mods='\n'.join(imp_mod_lines))
+    return func
+
+def _module_present(modname, modlist):
+    if modname in modlist:
+        return True
+    for m in modlist:
+        if hasattr(m, '__name__') and m.__name__ == modname:
+            return True
+    return False
+
+def _get_namespace(m):
+    """
+    This is used by _lambdify to parse its arguments.
+    """
+    if isinstance(m, str):
+        _import(m)
+        return MODULES[m][0]
+    elif isinstance(m, dict):
+        return m
+    elif hasattr(m, "__dict__"):
+        return m.__dict__
+    else:
+        raise TypeError("Argument must be either a string, dict or module but it is: %s" % m)
+
+
+def _recursive_to_string(doprint, arg):
+    """Functions in lambdify accept both SymPy types and non-SymPy types such as python
+    lists and tuples. This method ensures that we only call the doprint method of the
+    printer with SymPy types (so that the printer safely can use SymPy-methods)."""
+    from sympy.matrices.matrixbase import MatrixBase
+    from sympy.core.basic import Basic
+
+    if isinstance(arg, (Basic, MatrixBase)):
+        return doprint(arg)
+    elif iterable(arg):
+        if isinstance(arg, list):
+            left, right = "[", "]"
+        elif isinstance(arg, tuple):
+            left, right = "(", ",)"
+            if not arg:
+                return "()"
+        else:
+            raise NotImplementedError("unhandled type: %s, %s" % (type(arg), arg))
+        return left +', '.join(_recursive_to_string(doprint, e) for e in arg) + right
+    elif isinstance(arg, str):
+        return arg
+    else:
+        return doprint(arg)
+
+
+def lambdastr(args, expr, printer=None, dummify=None):
+    """
+    Returns a string that can be evaluated to a lambda function.
+
+    Examples
+    ========
+
+    >>> from sympy.abc import x, y, z
+    >>> from sympy.utilities.lambdify import lambdastr
+    >>> lambdastr(x, x**2)
+    'lambda x: (x**2)'
+    >>> lambdastr((x,y,z), [z,y,x])
+    'lambda x,y,z: ([z, y, x])'
+
+    Although tuples may not appear as arguments to lambda in Python 3,
+    lambdastr will create a lambda function that will unpack the original
+    arguments so that nested arguments can be handled:
+
+    >>> lambdastr((x, (y, z)), x + y)
+    'lambda _0,_1: (lambda x,y,z: (x + y))(_0,_1[0],_1[1])'
+    """
+    # Transforming everything to strings.
+    from sympy.matrices import DeferredVector
+    from sympy.core.basic import Basic
+    from sympy.core.function import (Derivative, Function)
+    from sympy.core.symbol import (Dummy, Symbol)
+    from sympy.core.sympify import sympify
+
+    if printer is not None:
+        if inspect.isfunction(printer):
+            lambdarepr = printer
+        else:
+            if inspect.isclass(printer):
+                lambdarepr = lambda expr: printer().doprint(expr)
+            else:
+                lambdarepr = lambda expr: printer.doprint(expr)
+    else:
+        #XXX: This has to be done here because of circular imports
+        from sympy.printing.lambdarepr import lambdarepr
+
+    def sub_args(args, dummies_dict):
+        if isinstance(args, str):
+            return args
+        elif isinstance(args, DeferredVector):
+            return str(args)
+        elif iterable(args):
+            dummies = flatten([sub_args(a, dummies_dict) for a in args])
+            return ",".join(str(a) for a in dummies)
+        else:
+            # replace these with Dummy symbols
+            if isinstance(args, (Function, Symbol, Derivative)):
+                dummies = Dummy()
+                dummies_dict.update({args : dummies})
+                return str(dummies)
+            else:
+                return str(args)
+
+    def sub_expr(expr, dummies_dict):
+        expr = sympify(expr)
+        # dict/tuple are sympified to Basic
+        if isinstance(expr, Basic):
+            expr = expr.xreplace(dummies_dict)
+        # list is not sympified to Basic
+        elif isinstance(expr, list):
+            expr = [sub_expr(a, dummies_dict) for a in expr]
+        return expr
+
+    # Transform args
+    def isiter(l):
+        return iterable(l, exclude=(str, DeferredVector, NotIterable))
+
+    def flat_indexes(iterable):
+        n = 0
+
+        for el in iterable:
+            if isiter(el):
+                for ndeep in flat_indexes(el):
+                    yield (n,) + ndeep
+            else:
+                yield (n,)
+
+            n += 1
+
+    if dummify is None:
+        dummify = any(isinstance(a, Basic) and
+            a.atoms(Function, Derivative) for a in (
+            args if isiter(args) else [args]))
+
+    if isiter(args) and any(isiter(i) for i in args):
+        dum_args = [str(Dummy(str(i))) for i in range(len(args))]
+
+        indexed_args = ','.join([
+            dum_args[ind[0]] + ''.join(["[%s]" % k for k in ind[1:]])
+                    for ind in flat_indexes(args)])
+
+        lstr = lambdastr(flatten(args), expr, printer=printer, dummify=dummify)
+
+        return 'lambda %s: (%s)(%s)' % (','.join(dum_args), lstr, indexed_args)
+
+    dummies_dict = {}
+    if dummify:
+        args = sub_args(args, dummies_dict)
+    else:
+        if isinstance(args, str):
+            pass
+        elif iterable(args, exclude=DeferredVector):
+            args = ",".join(str(a) for a in args)
+
+    # Transform expr
+    if dummify:
+        if isinstance(expr, str):
+            pass
+        else:
+            expr = sub_expr(expr, dummies_dict)
+    expr = _recursive_to_string(lambdarepr, expr)
+    return "lambda %s: (%s)" % (args, expr)
+
+class _EvaluatorPrinter:
+    def __init__(self, printer=None, dummify=False):
+        self._dummify = dummify
+
+        #XXX: This has to be done here because of circular imports
+        from sympy.printing.lambdarepr import LambdaPrinter
+
+        if printer is None:
+            printer = LambdaPrinter()
+
+        if inspect.isfunction(printer):
+            self._exprrepr = printer
+        else:
+            if inspect.isclass(printer):
+                printer = printer()
+
+            self._exprrepr = printer.doprint
+
+            #if hasattr(printer, '_print_Symbol'):
+            #    symbolrepr = printer._print_Symbol
+
+            #if hasattr(printer, '_print_Dummy'):
+            #    dummyrepr = printer._print_Dummy
+
+        # Used to print the generated function arguments in a standard way
+        self._argrepr = LambdaPrinter().doprint
+
+    def doprint(self, funcname, args, expr, *, cses=()):
+        """
+        Returns the function definition code as a string.
+        """
+        from sympy.core.symbol import Dummy
+
+        funcbody = []
+
+        if not iterable(args):
+            args = [args]
+
+        if cses:
+            cses = list(cses)
+            subvars, subexprs = zip(*cses)
+            exprs = [expr] + list(subexprs)
+            argstrs, exprs = self._preprocess(args, exprs, cses=cses)
+            expr, subexprs = exprs[0], exprs[1:]
+            cses = zip(subvars, subexprs)
+        else:
+            argstrs, expr = self._preprocess(args, expr)
+
+        # Generate argument unpacking and final argument list
+        funcargs = []
+        unpackings = []
+
+        for argstr in argstrs:
+            if iterable(argstr):
+                funcargs.append(self._argrepr(Dummy()))
+                unpackings.extend(self._print_unpacking(argstr, funcargs[-1]))
+            else:
+                funcargs.append(argstr)
+
+        funcsig = 'def {}({}):'.format(funcname, ', '.join(funcargs))
+
+        # Wrap input arguments before unpacking
+        funcbody.extend(self._print_funcargwrapping(funcargs))
+
+        funcbody.extend(unpackings)
+
+        for s, e in cses:
+            if e is None:
+                funcbody.append('del {}'.format(self._exprrepr(s)))
+            else:
+                funcbody.append('{} = {}'.format(self._exprrepr(s), self._exprrepr(e)))
+
+        # Subs may appear in expressions generated by .diff()
+        subs_assignments = []
+        expr = self._handle_Subs(expr, out=subs_assignments)
+        for lhs, rhs in subs_assignments:
+            funcbody.append('{} = {}'.format(self._exprrepr(lhs), self._exprrepr(rhs)))
+
+        str_expr = _recursive_to_string(self._exprrepr, expr)
+
+        if '\n' in str_expr:
+            str_expr = '({})'.format(str_expr)
+        funcbody.append('return {}'.format(str_expr))
+
+        funclines = [funcsig]
+        funclines.extend(['    ' + line for line in funcbody])
+
+        return '\n'.join(funclines) + '\n'
+
+    @classmethod
+    def _is_safe_ident(cls, ident):
+        return isinstance(ident, str) and ident.isidentifier() \
+                and not keyword.iskeyword(ident)
+
+    def _preprocess(self, args, expr, cses=(), _dummies_dict=None):
+        """Preprocess args, expr to replace arguments that do not map
+        to valid Python identifiers.
+
+        Returns string form of args, and updated expr.
+        """
+        from sympy.core.basic import Basic
+        from sympy.core.sorting import ordered
+        from sympy.core.function import (Derivative, Function)
+        from sympy.core.symbol import Dummy, uniquely_named_symbol
+        from sympy.matrices import DeferredVector
+        from sympy.core.expr import Expr
+
+        # Args of type Dummy can cause name collisions with args
+        # of type Symbol.  Force dummify of everything in this
+        # situation.
+        dummify = self._dummify or any(
+            isinstance(arg, Dummy) for arg in flatten(args))
+
+        argstrs = [None]*len(args)
+        if _dummies_dict is None:
+            _dummies_dict = {}
+
+        def update_dummies(arg, dummy):
+            _dummies_dict[arg] = dummy
+            for repl, sub in cses:
+                arg = arg.xreplace({sub: repl})
+                _dummies_dict[arg] = dummy
+
+        for arg, i in reversed(list(ordered(zip(args, range(len(args)))))):
+            if iterable(arg):
+                s, expr = self._preprocess(arg, expr, cses=cses, _dummies_dict=_dummies_dict)
+            elif isinstance(arg, DeferredVector):
+                s = str(arg)
+            elif isinstance(arg, Basic) and arg.is_symbol:
+                s = str(arg)
+                if dummify or not self._is_safe_ident(s):
+                    dummy = Dummy()
+                    if isinstance(expr, Expr):
+                        dummy = uniquely_named_symbol(
+                            dummy.name, expr, modify=lambda s: '_' + s)
+                    s = self._argrepr(dummy)
+                    update_dummies(arg, dummy)
+                    expr = self._subexpr(expr, _dummies_dict)
+            elif dummify or isinstance(arg, (Function, Derivative)):
+                dummy = Dummy()
+                s = self._argrepr(dummy)
+                update_dummies(arg, dummy)
+                expr = self._subexpr(expr, _dummies_dict)
+            else:
+                s = str(arg)
+            argstrs[i] = s
+        return argstrs, expr
+
+    def _subexpr(self, expr, dummies_dict):
+        from sympy.matrices import DeferredVector
+        from sympy.core.sympify import sympify
+
+        expr = sympify(expr)
+        xreplace = getattr(expr, 'xreplace', None)
+        if xreplace is not None:
+            expr = xreplace(dummies_dict)
+        else:
+            if isinstance(expr, DeferredVector):
+                pass
+            elif isinstance(expr, dict):
+                k = [self._subexpr(sympify(a), dummies_dict) for a in expr.keys()]
+                v = [self._subexpr(sympify(a), dummies_dict) for a in expr.values()]
+                expr = dict(zip(k, v))
+            elif isinstance(expr, tuple):
+                expr = tuple(self._subexpr(sympify(a), dummies_dict) for a in expr)
+            elif isinstance(expr, list):
+                expr = [self._subexpr(sympify(a), dummies_dict) for a in expr]
+        return expr
+
+    def _print_funcargwrapping(self, args):
+        """Generate argument wrapping code.
+
+        args is the argument list of the generated function (strings).
+
+        Return value is a list of lines of code that will be inserted  at
+        the beginning of the function definition.
+        """
+        return []
+
+    def _print_unpacking(self, unpackto, arg):
+        """Generate argument unpacking code.
+
+        arg is the function argument to be unpacked (a string), and
+        unpackto is a list or nested lists of the variable names (strings) to
+        unpack to.
+        """
+        def unpack_lhs(lvalues):
+            return '[{}]'.format(', '.join(
+                unpack_lhs(val) if iterable(val) else val for val in lvalues))
+
+        return ['{} = {}'.format(unpack_lhs(unpackto), arg)]
+
+    def _handle_Subs(self, expr, out):
+        """Any instance of Subs is extracted and returned as assignment pairs."""
+        from sympy.core.basic import Basic
+        from sympy.core.function import Subs
+        from sympy.core.symbol import Dummy
+        from sympy.matrices.matrixbase import MatrixBase
+
+        def _replace(ex, variables, point):
+            safe = {}
+            for lhs, rhs in zip(variables, point):
+                dummy = Dummy()
+                safe[lhs] = dummy
+                out.append((dummy, rhs))
+            return ex.xreplace(safe)
+
+        if isinstance(expr, (Basic, MatrixBase)):
+            expr = expr.replace(Subs, _replace)
+        elif iterable(expr):
+            expr = type(expr)([self._handle_Subs(e, out) for e in expr])
+        return expr
+
+class _TensorflowEvaluatorPrinter(_EvaluatorPrinter):
+    def _print_unpacking(self, lvalues, rvalue):
+        """Generate argument unpacking code.
+
+        This method is used when the input value is not iterable,
+        but can be indexed (see issue #14655).
+        """
+
+        def flat_indexes(elems):
+            n = 0
+
+            for el in elems:
+                if iterable(el):
+                    for ndeep in flat_indexes(el):
+                        yield (n,) + ndeep
+                else:
+                    yield (n,)
+
+                n += 1
+
+        indexed = ', '.join('{}[{}]'.format(rvalue, ']['.join(map(str, ind)))
+                                for ind in flat_indexes(lvalues))
+
+        return ['[{}] = [{}]'.format(', '.join(flatten(lvalues)), indexed)]
+
+def _imp_namespace(expr, namespace=None):
+    """ Return namespace dict with function implementations
+
+    We need to search for functions in anything that can be thrown at
+    us - that is - anything that could be passed as ``expr``.  Examples
+    include SymPy expressions, as well as tuples, lists and dicts that may
+    contain SymPy expressions.
+
+    Parameters
+    ----------
+    expr : object
+       Something passed to lambdify, that will generate valid code from
+       ``str(expr)``.
+    namespace : None or mapping
+       Namespace to fill.  None results in new empty dict
+
+    Returns
+    -------
+    namespace : dict
+       dict with keys of implemented function names within ``expr`` and
+       corresponding values being the numerical implementation of
+       function
+
+    Examples
+    ========
+
+    >>> from sympy.abc import x
+    >>> from sympy.utilities.lambdify import implemented_function, _imp_namespace
+    >>> from sympy import Function
+    >>> f = implemented_function(Function('f'), lambda x: x+1)
+    >>> g = implemented_function(Function('g'), lambda x: x*10)
+    >>> namespace = _imp_namespace(f(g(x)))
+    >>> sorted(namespace.keys())
+    ['f', 'g']
+    """
+    # Delayed import to avoid circular imports
+    from sympy.core.function import FunctionClass
+    if namespace is None:
+        namespace = {}
+    # tuples, lists, dicts are valid expressions
+    if is_sequence(expr):
+        for arg in expr:
+            _imp_namespace(arg, namespace)
+        return namespace
+    elif isinstance(expr, dict):
+        for key, val in expr.items():
+            # functions can be in dictionary keys
+            _imp_namespace(key, namespace)
+            _imp_namespace(val, namespace)
+        return namespace
+    # SymPy expressions may be Functions themselves
+    func = getattr(expr, 'func', None)
+    if isinstance(func, FunctionClass):
+        imp = getattr(func, '_imp_', None)
+        if imp is not None:
+            name = expr.func.__name__
+            if name in namespace and namespace[name] != imp:
+                raise ValueError('We found more than one '
+                                 'implementation with name '
+                                 '"%s"' % name)
+            namespace[name] = imp
+    # and / or they may take Functions as arguments
+    if hasattr(expr, 'args'):
+        for arg in expr.args:
+            _imp_namespace(arg, namespace)
+    return namespace
+
+
+def implemented_function(symfunc, implementation):
+    """ Add numerical ``implementation`` to function ``symfunc``.
+
+    ``symfunc`` can be an ``UndefinedFunction`` instance, or a name string.
+    In the latter case we create an ``UndefinedFunction`` instance with that
+    name.
+
+    Be aware that this is a quick workaround, not a general method to create
+    special symbolic functions. If you want to create a symbolic function to be
+    used by all the machinery of SymPy you should subclass the ``Function``
+    class.
+
+    Parameters
+    ----------
+    symfunc : ``str`` or ``UndefinedFunction`` instance
+       If ``str``, then create new ``UndefinedFunction`` with this as
+       name.  If ``symfunc`` is an Undefined function, create a new function
+       with the same name and the implemented function attached.
+    implementation : callable
+       numerical implementation to be called by ``evalf()`` or ``lambdify``
+
+    Returns
+    -------
+    afunc : sympy.FunctionClass instance
+       function with attached implementation
+
+    Examples
+    ========
+
+    >>> from sympy.abc import x
+    >>> from sympy.utilities.lambdify import implemented_function
+    >>> from sympy import lambdify
+    >>> f = implemented_function('f', lambda x: x+1)
+    >>> lam_f = lambdify(x, f(x))
+    >>> lam_f(4)
+    5
+    """
+    # Delayed import to avoid circular imports
+    from sympy.core.function import UndefinedFunction
+    # if name, create function to hold implementation
+    kwargs = {}
+    if isinstance(symfunc, UndefinedFunction):
+        kwargs = symfunc._kwargs
+        symfunc = symfunc.__name__
+    if isinstance(symfunc, str):
+        # Keyword arguments to UndefinedFunction are added as attributes to
+        # the created class.
+        symfunc = UndefinedFunction(
+            symfunc, _imp_=staticmethod(implementation), **kwargs)
+    elif not isinstance(symfunc, UndefinedFunction):
+        raise ValueError(filldedent('''
+            symfunc should be either a string or
+            an UndefinedFunction instance.'''))
+    return symfunc
+
+
+def _too_large_for_docstring(expr, limit):
+    """Decide whether an ``Expr`` is too large to be fully rendered in a
+    ``lambdify`` docstring.
+
+    This is a fast alternative to ``count_ops``, which can become prohibitively
+    slow for large expressions, because in this instance we only care whether
+    ``limit`` is exceeded rather than counting the exact number of nodes in the
+    expression.
+
+    Parameters
+    ==========
+    expr : ``Expr``, (nested) ``list`` of ``Expr``, or ``Matrix``
+        The same objects that can be passed to the ``expr`` argument of
+        ``lambdify``.
+    limit : ``int`` or ``None``
+        The threshold above which an expression contains too many nodes to be
+        usefully rendered in the docstring. If ``None`` then there is no limit.
+
+    Returns
+    =======
+    bool
+        ``True`` if the number of nodes in the expression exceeds the limit,
+        ``False`` otherwise.
+
+    Examples
+    ========
+
+    >>> from sympy.abc import x, y, z
+    >>> from sympy.utilities.lambdify import _too_large_for_docstring
+    >>> expr = x
+    >>> _too_large_for_docstring(expr, None)
+    False
+    >>> _too_large_for_docstring(expr, 100)
+    False
+    >>> _too_large_for_docstring(expr, 1)
+    False
+    >>> _too_large_for_docstring(expr, 0)
+    True
+    >>> _too_large_for_docstring(expr, -1)
+    True
+
+    Does this split it?
+
+    >>> expr = [x, y, z]
+    >>> _too_large_for_docstring(expr, None)
+    False
+    >>> _too_large_for_docstring(expr, 100)
+    False
+    >>> _too_large_for_docstring(expr, 1)
+    True
+    >>> _too_large_for_docstring(expr, 0)
+    True
+    >>> _too_large_for_docstring(expr, -1)
+    True
+
+    >>> expr = [x, [y], z, [[x+y], [x*y*z, [x+y+z]]]]
+    >>> _too_large_for_docstring(expr, None)
+    False
+    >>> _too_large_for_docstring(expr, 100)
+    False
+    >>> _too_large_for_docstring(expr, 1)
+    True
+    >>> _too_large_for_docstring(expr, 0)
+    True
+    >>> _too_large_for_docstring(expr, -1)
+    True
+
+    >>> expr = ((x + y + z)**5).expand()
+    >>> _too_large_for_docstring(expr, None)
+    False
+    >>> _too_large_for_docstring(expr, 100)
+    True
+    >>> _too_large_for_docstring(expr, 1)
+    True
+    >>> _too_large_for_docstring(expr, 0)
+    True
+    >>> _too_large_for_docstring(expr, -1)
+    True
+
+    >>> from sympy import Matrix
+    >>> expr = Matrix([[(x + y + z), ((x + y + z)**2).expand(),
+    ...                 ((x + y + z)**3).expand(), ((x + y + z)**4).expand()]])
+    >>> _too_large_for_docstring(expr, None)
+    False
+    >>> _too_large_for_docstring(expr, 1000)
+    False
+    >>> _too_large_for_docstring(expr, 100)
+    True
+    >>> _too_large_for_docstring(expr, 1)
+    True
+    >>> _too_large_for_docstring(expr, 0)
+    True
+    >>> _too_large_for_docstring(expr, -1)
+    True
+
+    """
+    # Must be imported here to avoid a circular import error
+    from sympy.core.traversal import postorder_traversal
+
+    if limit is None:
+        return False
+
+    i = 0
+    for _ in postorder_traversal(expr):
+        i += 1
+        if i > limit:
+            return True
+    return False
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/magic.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/magic.py
new file mode 100644
index 0000000000000000000000000000000000000000..e853a0ad9a85bc252dcb24e8a1ecbfca422ac3fd
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/magic.py
@@ -0,0 +1,12 @@
+"""Functions that involve magic. """
+
+def pollute(names, objects):
+    """Pollute the global namespace with symbols -> objects mapping. """
+    from inspect import currentframe
+    frame = currentframe().f_back.f_back
+
+    try:
+        for name, obj in zip(names, objects):
+            frame.f_globals[name] = obj
+    finally:
+        del frame  # break cyclic dependencies as stated in inspect docs
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/matchpy_connector.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/matchpy_connector.py
new file mode 100644
index 0000000000000000000000000000000000000000..35aa013294b93bbcfe4a1bf4ec96b629ea5a468f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/matchpy_connector.py
@@ -0,0 +1,340 @@
+"""
+The objects in this module allow the usage of the MatchPy pattern matching
+library on SymPy expressions.
+"""
+import re
+from typing import List, Callable, NamedTuple, Any, Dict
+
+from sympy.core.sympify import _sympify
+from sympy.external import import_module
+from sympy.functions import (log, sin, cos, tan, cot, csc, sec, erf, gamma, uppergamma)
+from sympy.functions.elementary.hyperbolic import acosh, asinh, atanh, acoth, acsch, asech, cosh, sinh, tanh, coth, sech, csch
+from sympy.functions.elementary.trigonometric import atan, acsc, asin, acot, acos, asec
+from sympy.functions.special.error_functions import fresnelc, fresnels, erfc, erfi, Ei
+from sympy.core.add import Add
+from sympy.core.basic import Basic
+from sympy.core.expr import Expr
+from sympy.core.mul import Mul
+from sympy.core.power import Pow
+from sympy.core.relational import (Equality, Unequality)
+from sympy.core.symbol import Symbol
+from sympy.functions.elementary.exponential import exp
+from sympy.integrals.integrals import Integral
+from sympy.printing.repr import srepr
+from sympy.utilities.decorator import doctest_depends_on
+
+
+matchpy = import_module("matchpy")
+
+
+__doctest_requires__ = {('*',): ['matchpy']}
+
+
+if matchpy:
+    from matchpy import Operation, CommutativeOperation, AssociativeOperation, OneIdentityOperation
+    from matchpy.expressions.functions import op_iter, create_operation_expression, op_len
+
+    Operation.register(Integral)
+    Operation.register(Pow)
+    OneIdentityOperation.register(Pow)
+
+    Operation.register(Add)
+    OneIdentityOperation.register(Add)
+    CommutativeOperation.register(Add)
+    AssociativeOperation.register(Add)
+
+    Operation.register(Mul)
+    OneIdentityOperation.register(Mul)
+    CommutativeOperation.register(Mul)
+    AssociativeOperation.register(Mul)
+
+    Operation.register(Equality)
+    CommutativeOperation.register(Equality)
+    Operation.register(Unequality)
+    CommutativeOperation.register(Unequality)
+
+    Operation.register(exp)
+    Operation.register(log)
+    Operation.register(gamma)
+    Operation.register(uppergamma)
+    Operation.register(fresnels)
+    Operation.register(fresnelc)
+    Operation.register(erf)
+    Operation.register(Ei)
+    Operation.register(erfc)
+    Operation.register(erfi)
+    Operation.register(sin)
+    Operation.register(cos)
+    Operation.register(tan)
+    Operation.register(cot)
+    Operation.register(csc)
+    Operation.register(sec)
+    Operation.register(sinh)
+    Operation.register(cosh)
+    Operation.register(tanh)
+    Operation.register(coth)
+    Operation.register(csch)
+    Operation.register(sech)
+    Operation.register(asin)
+    Operation.register(acos)
+    Operation.register(atan)
+    Operation.register(acot)
+    Operation.register(acsc)
+    Operation.register(asec)
+    Operation.register(asinh)
+    Operation.register(acosh)
+    Operation.register(atanh)
+    Operation.register(acoth)
+    Operation.register(acsch)
+    Operation.register(asech)
+
+    @op_iter.register(Integral)  # type: ignore
+    def _(operation):
+        return iter((operation._args[0],) + operation._args[1])
+
+    @op_iter.register(Basic)  # type: ignore
+    def _(operation):
+        return iter(operation._args)
+
+    @op_len.register(Integral)  # type: ignore
+    def _(operation):
+        return 1 + len(operation._args[1])
+
+    @op_len.register(Basic)  # type: ignore
+    def _(operation):
+        return len(operation._args)
+
+    @create_operation_expression.register(Basic)
+    def sympy_op_factory(old_operation, new_operands, variable_name=True):
+        return type(old_operation)(*new_operands)
+
+
+if matchpy:
+    from matchpy import Wildcard
+else:
+    class Wildcard: # type: ignore
+        def __init__(self, min_length, fixed_size, variable_name, optional):
+            self.min_count = min_length
+            self.fixed_size = fixed_size
+            self.variable_name = variable_name
+            self.optional = optional
+
+
+@doctest_depends_on(modules=('matchpy',))
+class _WildAbstract(Wildcard, Symbol):
+    min_length: int  # abstract field required in subclasses
+    fixed_size: bool  # abstract field required in subclasses
+
+    def __init__(self, variable_name=None, optional=None, **assumptions):
+        min_length = self.min_length
+        fixed_size = self.fixed_size
+        if optional is not None:
+            optional = _sympify(optional)
+        Wildcard.__init__(self, min_length, fixed_size, str(variable_name), optional)
+
+    def __getstate__(self):
+        return {
+            "min_length": self.min_length,
+            "fixed_size": self.fixed_size,
+            "min_count": self.min_count,
+            "variable_name": self.variable_name,
+            "optional": self.optional,
+        }
+
+    def __new__(cls, variable_name=None, optional=None, **assumptions):
+        cls._sanitize(assumptions, cls)
+        return _WildAbstract.__xnew__(cls, variable_name, optional, **assumptions)
+
+    def __getnewargs__(self):
+        return self.variable_name, self.optional
+
+    @staticmethod
+    def __xnew__(cls, variable_name=None, optional=None, **assumptions):
+        obj = Symbol.__xnew__(cls, variable_name, **assumptions)
+        return obj
+
+    def _hashable_content(self):
+        if self.optional:
+            return super()._hashable_content() + (self.min_count, self.fixed_size, self.variable_name, self.optional)
+        else:
+            return super()._hashable_content() + (self.min_count, self.fixed_size, self.variable_name)
+
+    def __copy__(self) -> '_WildAbstract':
+        return type(self)(variable_name=self.variable_name, optional=self.optional)
+
+    def __repr__(self):
+        return str(self)
+
+    def __str__(self):
+        return self.name
+
+
+@doctest_depends_on(modules=('matchpy',))
+class WildDot(_WildAbstract):
+    min_length = 1
+    fixed_size = True
+
+
+@doctest_depends_on(modules=('matchpy',))
+class WildPlus(_WildAbstract):
+    min_length = 1
+    fixed_size = False
+
+
+@doctest_depends_on(modules=('matchpy',))
+class WildStar(_WildAbstract):
+    min_length = 0
+    fixed_size = False
+
+
+def _get_srepr(expr):
+    s = srepr(expr)
+    s = re.sub(r"WildDot\('(\w+)'\)", r"\1", s)
+    s = re.sub(r"WildPlus\('(\w+)'\)", r"*\1", s)
+    s = re.sub(r"WildStar\('(\w+)'\)", r"*\1", s)
+    return s
+
+
+class ReplacementInfo(NamedTuple):
+    replacement: Any
+    info: Any
+
+
+@doctest_depends_on(modules=('matchpy',))
+class Replacer:
+    """
+    Replacer object to perform multiple pattern matching and subexpression
+    replacements in SymPy expressions.
+
+    Examples
+    ========
+
+    Example to construct a simple first degree equation solver:
+
+    >>> from sympy.utilities.matchpy_connector import WildDot, Replacer
+    >>> from sympy import Equality, Symbol
+    >>> x = Symbol("x")
+    >>> a_ = WildDot("a_", optional=1)
+    >>> b_ = WildDot("b_", optional=0)
+
+    The lines above have defined two wildcards, ``a_`` and ``b_``, the
+    coefficients of the equation `a x + b = 0`. The optional values specified
+    indicate which expression to return in case no match is found, they are
+    necessary in equations like `a x = 0` and `x + b = 0`.
+
+    Create two constraints to make sure that ``a_`` and ``b_`` will not match
+    any expression containing ``x``:
+
+    >>> from matchpy import CustomConstraint
+    >>> free_x_a = CustomConstraint(lambda a_: not a_.has(x))
+    >>> free_x_b = CustomConstraint(lambda b_: not b_.has(x))
+
+    Now create the rule replacer with the constraints:
+
+    >>> replacer = Replacer(common_constraints=[free_x_a, free_x_b])
+
+    Add the matching rule:
+
+    >>> replacer.add(Equality(a_*x + b_, 0), -b_/a_)
+
+    Let's try it:
+
+    >>> replacer.replace(Equality(3*x + 4, 0))
+    -4/3
+
+    Notice that it will not match equations expressed with other patterns:
+
+    >>> eq = Equality(3*x, 4)
+    >>> replacer.replace(eq)
+    Eq(3*x, 4)
+
+    In order to extend the matching patterns, define another one (we also need
+    to clear the cache, because the previous result has already been memorized
+    and the pattern matcher will not iterate again if given the same expression)
+
+    >>> replacer.add(Equality(a_*x, b_), b_/a_)
+    >>> replacer._matcher.clear()
+    >>> replacer.replace(eq)
+    4/3
+    """
+
+    def __init__(self, common_constraints: list = [], lambdify: bool = False, info: bool = False):
+        self._matcher = matchpy.ManyToOneMatcher()
+        self._common_constraint = common_constraints
+        self._lambdify = lambdify
+        self._info = info
+        self._wildcards: Dict[str, Wildcard] = {}
+
+    def _get_lambda(self, lambda_str: str) -> Callable[..., Expr]:
+        exec("from sympy import *")
+        return eval(lambda_str, locals())
+
+    def _get_custom_constraint(self, constraint_expr: Expr, condition_template: str) -> Callable[..., Expr]:
+        wilds = [x.name for x in constraint_expr.atoms(_WildAbstract)]
+        lambdaargs = ', '.join(wilds)
+        fullexpr = _get_srepr(constraint_expr)
+        condition = condition_template.format(fullexpr)
+        return matchpy.CustomConstraint(
+            self._get_lambda(f"lambda {lambdaargs}: ({condition})"))
+
+    def _get_custom_constraint_nonfalse(self, constraint_expr: Expr) -> Callable[..., Expr]:
+        return self._get_custom_constraint(constraint_expr, "({}) != False")
+
+    def _get_custom_constraint_true(self, constraint_expr: Expr) -> Callable[..., Expr]:
+        return self._get_custom_constraint(constraint_expr, "({}) == True")
+
+    def add(self, expr: Expr, replacement, conditions_true: List[Expr] = [],
+            conditions_nonfalse: List[Expr] = [], info: Any = None) -> None:
+        expr = _sympify(expr)
+        replacement = _sympify(replacement)
+        constraints = self._common_constraint[:]
+        constraint_conditions_true = [
+            self._get_custom_constraint_true(cond) for cond in conditions_true]
+        constraint_conditions_nonfalse = [
+            self._get_custom_constraint_nonfalse(cond) for cond in conditions_nonfalse]
+        constraints.extend(constraint_conditions_true)
+        constraints.extend(constraint_conditions_nonfalse)
+        pattern = matchpy.Pattern(expr, *constraints)
+        if self._lambdify:
+            lambda_str = f"lambda {', '.join((x.name for x in expr.atoms(_WildAbstract)))}: {_get_srepr(replacement)}"
+            lambda_expr = self._get_lambda(lambda_str)
+            replacement = lambda_expr
+        else:
+            self._wildcards.update({str(i): i for i in expr.atoms(Wildcard)})
+        if self._info:
+            replacement = ReplacementInfo(replacement, info)
+        self._matcher.add(pattern, replacement)
+
+    def replace(self, expression, max_count: int = -1):
+        # This method partly rewrites the .replace method of ManyToOneReplacer
+        # in MatchPy.
+        # License: https://github.com/HPAC/matchpy/blob/master/LICENSE
+        infos = []
+        replaced = True
+        replace_count = 0
+        while replaced and (max_count < 0 or replace_count < max_count):
+            replaced = False
+            for subexpr, pos in matchpy.preorder_iter_with_position(expression):
+                try:
+                    replacement_data, subst = next(iter(self._matcher.match(subexpr)))
+                    if self._info:
+                        replacement = replacement_data.replacement
+                        infos.append(replacement_data.info)
+                    else:
+                        replacement = replacement_data
+
+                    if self._lambdify:
+                        result = replacement(**subst)
+                    else:
+                        result = replacement.xreplace({self._wildcards[k]: v for k, v in subst.items()})
+
+                    expression = matchpy.functions.replace(expression, pos, result)
+                    replaced = True
+                    break
+                except StopIteration:
+                    pass
+            replace_count += 1
+        if self._info:
+            return expression, infos
+        else:
+            return expression
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/mathml/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/mathml/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..eded44ee3c0f34ad1324765ba06ee9d6eb5e9899
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/mathml/__init__.py
@@ -0,0 +1,122 @@
+"""Module with some functions for MathML, like transforming MathML
+content in MathML presentation.
+
+To use this module, you will need lxml.
+"""
+
+from pathlib import Path
+
+from sympy.utilities.decorator import doctest_depends_on
+
+
+__doctest_requires__ = {('apply_xsl', 'c2p'): ['lxml']}
+
+
+def add_mathml_headers(s):
+    return """""" + s + ""
+
+
+def _read_binary(pkgname, filename):
+    import sys
+
+    if sys.version_info >= (3, 10):
+        # files was added in Python 3.9 but only seems to work here in 3.10+
+        from importlib.resources import files
+        return files(pkgname).joinpath(filename).read_bytes()
+    else:
+        # read_binary was deprecated in Python 3.11
+        from importlib.resources import read_binary
+        return read_binary(pkgname, filename)
+
+
+def _read_xsl(xsl):
+    # Previously these values were allowed:
+    if xsl == 'mathml/data/simple_mmlctop.xsl':
+        xsl = 'simple_mmlctop.xsl'
+    elif xsl == 'mathml/data/mmlctop.xsl':
+        xsl = 'mmlctop.xsl'
+    elif xsl == 'mathml/data/mmltex.xsl':
+        xsl = 'mmltex.xsl'
+
+    if xsl in ['simple_mmlctop.xsl', 'mmlctop.xsl', 'mmltex.xsl']:
+        xslbytes = _read_binary('sympy.utilities.mathml.data', xsl)
+    else:
+        xslbytes = Path(xsl).read_bytes()
+
+    return xslbytes
+
+
+@doctest_depends_on(modules=('lxml',))
+def apply_xsl(mml, xsl):
+    """Apply a xsl to a MathML string.
+
+    Parameters
+    ==========
+
+    mml
+        A string with MathML code.
+    xsl
+        A string giving the name of an xsl (xml stylesheet) file which can be
+        found in sympy/utilities/mathml/data. The following files are supplied
+        with SymPy:
+
+        - mmlctop.xsl
+        - mmltex.xsl
+        - simple_mmlctop.xsl
+
+        Alternatively, a full path to an xsl file can be given.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.mathml import apply_xsl
+    >>> xsl = 'simple_mmlctop.xsl'
+    >>> mml = '  a b '
+    >>> res = apply_xsl(mml,xsl)
+    >>> print(res)
+    
+    
+      a
+       + 
+      b
+    
+    """
+    from lxml import etree
+
+    parser = etree.XMLParser(resolve_entities=False)
+    ac = etree.XSLTAccessControl.DENY_ALL
+
+    s = etree.XML(_read_xsl(xsl), parser=parser)
+    transform = etree.XSLT(s, access_control=ac)
+    doc = etree.XML(mml, parser=parser)
+    result = transform(doc)
+    s = str(result)
+    return s
+
+
+@doctest_depends_on(modules=('lxml',))
+def c2p(mml, simple=False):
+    """Transforms a document in MathML content (like the one that sympy produces)
+    in one document in MathML presentation, more suitable for printing, and more
+    widely accepted
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.mathml import c2p
+    >>> mml = '  2 '
+    >>> c2p(mml,simple=True) != c2p(mml,simple=False)
+    True
+
+    """
+
+    if not mml.startswith('
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+  
+    
+    
+  
+
+
+
+
+
+
+
+  
+    
+    
+      
+        
+          
+            
+          
+          
+            
+          
+        
+      
+      
+        
+      
+    
+  
+
+
+
+
+
+
+
+
+
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+        
+        
+        
+      
+    
+    
+      
+        
+        
+        
+        
+        
+      
+        
+      
+    
+    
+      
+        
+          
+            
+              
+              
+              
+              
+            
+            
+          
+          
+            
+              
+              
+              
+              
+            
+            
+              
+            
+          
+        
+      
+    
+    
+      
+        
+          
+            
+            
+              
+            
+            
+            
+          
+        
+        
+          
+            
+            
+            
+            
+          
+        
+      
+    
+    
+      
+        
+        
+        
+        
+      
+    
+  
+
+
+
+
+  
+
+
+
+
+
+
+
+  
+  
+  
+  
+    
+      
+        
+      
+    
+    
+      
+    
+  
+
+
+
+  
+    
+      
+        
+          
+            
+          
+        
+          
+          
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+          
+         e 
+          
+      
+    
+    
+      
+        
+          
+            
+          
+        
+          
+        
+           - 
+            
+        
+        
+           + 
+            
+        
+         &#x2062; 
+         &#x2148; 
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+            
+          
+             - 
+              
+          
+          
+             + 
+              
+          
+           &#x2062; 
+           &#x2148; 
+        
+          
+      
+    
+    
+      
+        
+          
+            
+          
+        
+          
+          
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+              
+              
+          
+        
+          
+      
+    
+    
+      
+        
+          
+            
+          
+        
+         Polar 
+         &#x2062; 
+        
+            
+            
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+           Polar 
+           &#x2062; 
+          
+              
+              
+          
+        
+          
+      
+   
+    
+        
+    
+  
+
+
+
+
+  
+    
+      
+        
+          
+            
+          
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+      
+    
+    
+      
+        
+          
+            
+              
+            
+          
+          
+        
+      
+      
+        
+      
+    
+  
+
+
+
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+  
+
+
+
+
+
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+      
+    
+    
+      
+      
+      
+    
+     &#x2061; 
+    
+      
+        
+        
+        
+      
+    
+ 
+
+
+
+
+
+  
+  
+  
+  
+  
+    
+    
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+       [ 
+    
+    
+       ] 
+    
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+		
+          
+            
+            
+            
+          
+		
+		
+           -1 
+        
+      
+    
+  
+
+
+
+  
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+  
+
+
+
+
+
+
+
+  
+    
+      
+        
+      
+    
+     &#x03BB; 
+     &#x2061; 
+    
+      
+        
+          
+            
+          
+          
+            
+              
+            
+          
+        
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+        
+           &#x2218; 
+          
+            
+            
+            
+          
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+        
+           &#x2218; 
+          
+            
+            
+            
+          
+        
+      
+	
+  
+
+
+
+
+  
+    
+      id
+    
+    
+      id
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+	
+      domain
+	
+	
+      codomain
+	
+	
+      image
+	
+     &#x2061; 
+    
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+     { 
+    
+      
+        
+          
+            
+          
+          
+            if 
+            
+          
+        
+      
+      
+        
+          
+            
+          
+          
+            otherwise
+          
+        
+      
+    
+  
+
+
+
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+      
+    
+     &#x230A; 
+    
+      
+        
+          
+          
+          
+          
+        
+      
+      
+        
+          
+          
+          
+          
+        
+      
+    
+     &#x230B; 
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+     &#x2147; 
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+      
+    
+     ! 
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+          
+             max 
+          
+          
+             min 
+          
+          
+        
+      
+      
+        
+           max 
+        
+        
+           min 
+        
+      
+	
+    
+      
+        
+        
+          
+            
+              
+            
+          
+           | 
+        
+        
+      
+      
+        
+          
+        
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+     - 
+    
+      
+      
+      
+    
+  
+  
+    
+      
+      
+      
+      
+    
+     - 
+    
+      
+      
+      
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+    
+      
+      
+      
+      
+    
+    
+      
+        
+           - 
+            
+        
+        
+          
+            
+            
+            
+          
+        
+        
+           + 
+          
+            
+            
+            
+          
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+        
+        
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+    
+      
+        
+        
+        
+        
+      
+    
+    
+      
+        
+        
+        
+        
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+    
+    
+    
+    
+  
+    
+  
+    
+    
+    
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+    
+    
+    
+    
+  
+  
+    
+       &#x2062; 
+      
+        
+        
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+      
+    
+    
+  
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+         gcd 
+      
+      
+         lcm 
+      
+    
+    
+      
+      
+         gcd 
+      
+      
+         lcm 
+      
+        
+      
+    
+     &#x2061; 
+    
+      
+        
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+    
+    
+    
+    
+  
+  
+     &#x2227; 
+     &#x2061; 
+    
+      
+      
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+    
+    
+    
+    
+  
+  
+     &#x2228; 
+     &#x2061; 
+    
+      
+      
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+    
+      
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+    
+    
+    
+    
+  
+  
+     &#x22BB; 
+     &#x2061; 
+    
+      
+      
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+         &#x00AC; 
+         &#x2061; 
+        
+          
+          
+          
+        
+	  
+    
+    
+      
+        
+          
+            
+          
+        
+         &#x00AC; 
+         &#x2061; 
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+     &#x2200; 
+    
+      
+    
+    
+      
+        
+          
+        
+      
+    
+	
+       : 
+      
+    
+	
+       , 
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+     &#x2203; 
+    
+      
+        
+          
+        
+      
+    
+    
+      
+    
+    
+       : 
+      
+    
+    
+       , 
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+          
+        
+      
+      
+    
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+      
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+    
+     &#x00AF; 
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+      
+      
+        &#x211C;
+      
+      
+        &#x2111;
+      
+    
+     &#x2061; 
+    
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        &#x230A;
+      
+      
+        &#x2308;
+      
+    
+    
+    
+      
+        &#x230B;
+      
+      
+        &#x2309;
+      
+    
+  
+
+
+
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+  
+
+
+
+  
+    
+    
+      
+        &#x2260;
+      
+      
+        &#x2248;
+      
+      
+        &#x2223;
+      
+      
+        
+          
+            &#x2198;
+          
+          
+            &#x2197;
+          
+		  
+            &#x2192;
+          
+        
+      
+      
+        &#x21D2;
+      
+      
+        &#x2208;
+      
+      
+        &#x2209;
+      
+      
+        &#x2284;
+      
+      
+        &#x2288;
+      
+    
+    
+  
+  
+    
+    
+      
+        
+          &#x2286;
+        
+        
+         &#x2282;
+        
+        
+          
+        
+        
+          
+        
+        
+          
+        
+        
+         &#x2265;
+        
+        
+         &#x2264;
+        
+        
+         &#x2261;
+        
+      
+      
+    
+  
+
+
+
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+           ln 
+          
+        
+      
+      
+         ln 
+      
+    
+    
+      
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+          
+             log 
+            
+          
+        
+        
+          
+             log 
+            
+            
+          
+        
+      
+      
+        
+           log 
+        
+        
+          
+             log 
+            
+          
+        
+      
+    
+    
+      
+        
+        
+      
+    
+    
+      
+        
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+	
+      
+        
+          
+             &#x2146; 
+            
+               &#x2146; 
+              
+            
+          
+        
+        
+          
+            
+               &#x2146; 
+              
+            
+            
+               &#x2146; 
+              
+                
+                
+              
+            
+          
+        
+        
+          
+          
+        
+      
+      
+        
+          
+          
+        
+         &#x2032; 
+	  
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+           &#x2145; 
+          
+        
+      
+      
+        
+		  
+            
+               &#x2202; 
+              
+            
+            
+              
+                 &#x2202; 
+                
+                  
+                    
+                    
+                  
+                
+                
+                  
+                
+              
+            
+		  
+		
+        
+          
+            
+              
+                
+                   &#x2202; 
+                  
+                
+                
+                   &#x2202; 
+                  
+                    
+                    
+                  
+                
+              
+            
+            
+              
+                 &#x2202; 
+                
+                   &#x2202; 
+                  
+                
+              
+            
+          
+		
+	  
+	
+	
+      
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+      
+      
+        
+      
+      
+        
+      
+    
+    
+    
+      
+        
+      
+      
+        
+          
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+       &#x2207; 
+       2 
+    
+     &#x2061; 
+    
+      
+      
+    
+  
+
+
+
+
+
+
+
+  
+    
+      
+        
+      
+    
+	
+      
+        
+      
+      
+        
+      
+    
+	
+      
+        
+      
+      
+        
+      
+    
+    
+      
+        
+      
+      
+        
+        
+         | 
+        
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+    
+    
+    
+    
+  
+  
+     &#x222A; 
+    
+      
+      
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+    
+    
+    
+    
+  
+  
+     &#x2229; 
+    
+      
+      
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+    
+    
+    
+    
+  
+  \
+  
+    
+    
+    
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+    
+    
+    
+    
+  
+  
+    &#x00D7;
+    
+      
+      
+      
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+    
+  
+
+
+
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+          
+            
+             &#x2211;
+            
+            
+             &#x220F;
+            
+          
+          
+            
+             = 
+            
+          
+          
+        
+        
+      
+      
+        
+          
+            
+             &#x2211;
+            
+            
+             &#x220F;
+            
+          
+          
+        
+        
+      
+      
+        
+          
+            
+              &#x2211;
+            
+            
+              &#x220F;
+            
+          
+          
+        
+        
+          
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+	
+	  
+        
+           &#x222B; 
+          
+        
+      
+	  
+        
+           &#x222B; 
+          
+        
+      
+      
+        
+           &#x222B; 
+          
+            
+          
+          
+            
+            
+          
+		
+      
+      
+        
+           &#x222B; 
+          
+          
+            
+            
+          
+        
+      
+	  
+         &#x222B; 
+      
+    
+    
+      
+      
+    
+	
+      
+         &#x2146; 
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+       lim 
+      
+        
+            
+             &#x2192; 
+            
+        
+        
+          
+        
+      
+    
+    
+  
+
+
+
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+    
+    
+      
+        
+        
+      
+    
+    
+    
+      
+      
+    
+  
+
+
+
+  
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+    
+  
+
+
+
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+     &#x03C3; 
+    
+      
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+     &#x03C3; 
+    
+      
+        
+          
+        
+      
+       2 
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+     median 
+    
+      
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+     mode 
+    
+      
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+        
+      
+    
+    
+      
+        
+        
+      
+    
+    
+      
+        
+      
+    
+    
+      
+        
+      
+    
+  
+
+
+
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+            
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+     det 
+    
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+     T 
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+    
+      
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+    
+      
+        &#x00D7;
+      
+      
+        &#x22C5;
+      
+      
+        &#x2297;
+      
+    
+    
+  
+
+
+
+
+
+
+
+   &#x2124; 
+
+
+
+   &#x211D; 
+
+
+
+   &#x211A; 
+
+
+
+   &#x2115; 
+
+
+
+   &#x2102; 
+
+
+
+   &#x2119; 
+
+
+
+   &#x2147; 
+
+
+
+   &#x2148; 
+
+
+
+   NaN 
+
+
+
+   true 
+
+
+
+   false 
+
+
+
+   &#x2205; 
+
+
+
+   &#x03C0; 
+
+
+
+   &#x213D; 
+
+
+
+   &#x221E; 
+
+
+
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/mathml/data/mmltex.xsl b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/mathml/data/mmltex.xsl
new file mode 100644
index 0000000000000000000000000000000000000000..5e6b85e02efd5196fe76b6ce4e10def27b9a8497
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/mathml/data/mmltex.xsl
@@ -0,0 +1,2360 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+	
+	
+		
+		
+			
+		
+	
+	
+		
+	
+
+
+
+
+
+	$
+	
+	$
+
+
+
+
+
+
+
+
+
+
+
+	
+  	+
+	
+	i
+
+
+
+	
+	/
+	
+
+
+
+		
+		_{}
+
+
+
+	
+	e^{i 
+	
+	}
+
+
+
+    
+    E
+    
+
+
+
+
+	
+		
+			\mathrm{}
+		
+		
+	
+
+
+
+
+	
+	
+		
+	
+	
+ 	(
+	
+		
+		, 
+	
+ 	)
+
+
+
+ 
+	()
+
+
+
+
+	
+		
+			\left(
+		
+		\left[
+	
+	
+	 , 
+	
+	
+		
+			\right)
+		
+		\right]
+	
+
+
+
+	\left\{\right\}
+
+
+
+
+	^{(-1)}
+
+
+
+
+
+
+
+	\mathrm{lambda}\: 
+  	
+  	.\: 
+  
+
+
+
+
+	
+	
+		
+		
+		\circ 
+	
+
+
+
+\mathrm{id}
+
+
+
+	\mathop{\mathrm{
+	
+	}}
+
+
+
+
+
+
+
+	\begin{cases}
+	
+	
+	\end{cases}
+
+
+
+		
+		 & \text{if $
+		
+		$}
+		\\ 
+
+
+
+	
+	 & \text{otherwise}
+
+
+
+
+	\left\lfloor\frac{
+	
+	}{
+	
+	}\right\rfloor 
+
+
+
+
+	
+		
+	
+	!
+
+
+
+
+	
+  
+  \left(
+  \frac{
+	
+
+	}{
+	
+
+	}
+	\right)
+
+
+
+
+	\
+	
+	\{
+   
+		
+   		
+   		, 
+			
+		
+		
+			
+				
+				 , 
+			
+		
+   
+	\}
+
+
+
+
+	-
+	
+		
+	
+
+
+
+	
+	
+		-
+		
+		
+	
+
+
+
+
+  
+  
+		(
+	
+  
+   
+    
+      -
+      +
+    
+   
+    
+      
+			
+			
+		     
+		     
+		   
+       
+      
+				
+				
+					
+					
+				
+			
+			
+				
+					
+				
+			
+		
+	
+	
+		)
+	
+
+
+
+
+	
+		
+	
+	^{
+	
+		
+	
+	}
+
+
+
+
+	
+	
+		\mod 
+		
+		
+	
+
+
+
+
+  
+  
+  (
+  
+		
+			
+				\times 
+				
+			
+		
+		
+			
+				
+			
+		
+	
+  )
+
+
+
+
+	\sqrt
+	
+		[
+		
+		]
+	
+	{
+	
+	}
+
+
+
+\gcd 
+
+
+
+	
+	
+		
+		
+		\land 
+	
+
+
+
+
+	
+	
+		
+		
+		\lor 
+	
+
+
+
+
+	
+	
+		
+		
+		\mathop{\mathrm{xor}}
+	
+
+
+
+
+	\neg 
+	
+		
+	
+
+
+
+
+	
+	
+		\implies 
+		
+		
+	
+
+
+
+
+	\
+	
+	 
+	
+	
+		, 
+	
+	
+		\colon 
+	  
+  
+
+
+
+
+	\left|
+	
+	\right|
+
+
+
+
+	\overline{}
+
+
+
+\Re 
+
+
+\Im 
+
+
+
+	\left\lfloor 
+	
+	\right\rfloor 
+
+
+
+
+	\left\lceil 
+	
+	\right\rceil 
+
+
+
+
+	
+	
+		
+		
+		=
+	
+
+
+
+
+	
+	
+		
+		
+		\neq 
+	
+
+
+
+
+
+
+	
+	
+	> 
+
+
+
+
+
+
+
+	
+	
+	< 
+
+
+
+
+
+	
+	
+		
+		
+		\ge 
+	
+
+
+
+
+	
+	
+		
+		
+		\le 
+	
+
+
+
+
+	
+	
+		
+		
+		\equiv 
+	
+
+
+
+
+	
+	
+		
+		
+		\approx 
+	
+
+
+
+
+	
+	
+		 | 
+		
+		
+	
+
+
+
+
+	\int
+	
+		_{
+		
+		}
+	
+	
+		^{
+		
+		}
+	
+	 
+	
+	\,d 
+	
+
+
+
+
+	
+	^\prime 
+
+
+
+	\frac{
+	
+		
+			d^{
+			
+			}
+			
+			}{d
+			
+			^{
+			
+			}
+		
+		
+			d 
+			
+			}{d 
+			
+			}
+		
+	
+	}
+
+
+
+
+	D_{
+	
+		
+		, 
+	
+	}
+	
+
+
+
+	\frac{\partial^{
+	
+		
+			
+		
+		
+			
+				
+				+
+			
+			
+				+
+				
+			
+		
+		
+			
+		
+	
+	}
+	
+	}{
+	
+		\partial 
+		
+		
+			^{
+			
+			}
+		
+	
+	}
+
+
+
+
+
+
+
+	
+	, 
+
+
+
+\mathop{\mathrm{div}}
+
+
+\nabla^2 
+
+
+
+	\{\}
+
+
+
+
+	\left[\right]
+
+
+
+   
+		
+   		
+   		\colon 
+			
+		
+		
+			
+				
+				, 
+			
+		
+   
+
+
+
+
+	
+	
+		
+		
+		\cup 
+	
+
+
+
+
+	
+	
+		
+		
+		\cap 
+	
+
+
+
+
+	
+	
+		\in 
+		
+		
+	
+
+
+
+
+	
+	
+		\notin 
+		
+		
+	
+
+
+
+
+	
+	
+		
+		
+		\subseteq 
+	
+
+
+
+
+	
+	
+		
+		
+		\subset 
+	
+
+
+
+
+	
+	
+		
+		
+		\nsubseteq 
+	
+
+
+
+
+	
+	
+		
+		
+		\not\subset 
+	
+
+
+
+
+	
+	
+		
+		
+		\setminus 
+	
+
+
+
+
+	|
+	
+	|
+
+
+
+
+	
+	
+		
+		
+		\times 
+	
+
+
+
+	
+		
+	
+	^{
+	
+	}
+
+
+
+
+	\sum
+
+
+
+
+	\prod
+
+
+
+	
+		_{
+		
+			
+			=
+		
+		
+		}
+	
+	
+		^{
+		
+		}
+	
+	 
+	
+
+
+
+
+	\lim_{
+	
+	}
+	
+
+
+
+	
+	\to 
+	
+
+
+
+
+	
+	
+		
+		
+		
+			
+				\searrow 
+				\nearrow 
+				\rightarrow 
+				\to 
+			
+		
+	
+
+
+
+
+	\
+	
+	 
+	
+		
+	
+
+
+
+	\
+	
+	 
+
+
+
+	\mathrm{
+	
+	\,}
+	
+		
+	
+
+
+
+	\mathrm{
+	
+	}
+
+
+
+
+	e^{}
+
+
+
+
+	\lg 
+	
+		
+	
+
+
+
+	\log_{
+	
+	}
+	
+		
+	
+
+
+
+
+	\left\langle 
+	
+		
+		, 
+	
+	\right\rangle 
+
+
+
+\sigma 
+
+
+
+	\sigma(
+	
+	)^2
+
+
+
+
+	\left\langle 
+	
+	^{
+	
+	}\right\rangle
+	
+		_{
+		
+		}
+	
+	 
+
+
+
+
+	\left(\begin{array}{c}
+	
+		
+		\\ 
+	
+	\end{array}\right)
+
+
+
+
+	\begin{pmatrix}
+	
+	\end{pmatrix}
+
+
+
+
+	
+		
+		 & 
+	
+	\\ 
+
+
+
+
+	\det 
+	
+		
+	
+
+
+
+	\begin{vmatrix}
+	
+	\end{vmatrix}
+
+
+
+
+	
+		
+	
+	^T
+
+
+
+
+	
+		
+	
+	_{
+	
+		
+		, 
+	
+	}
+
+
+
+
+	
+	
+		
+		
+		\dot 
+	
+
+
+
+
+
+
+	
+
+
+
+\mathbb{Z}
+
+
+\mathbb{R}
+
+
+\mathbb{Q}
+
+
+\mathbb{N}
+
+
+\mathbb{C}
+
+
+\mathbb{P}
+
+
+e
+
+
+i
+
+
+NaN
+
+
+\mbox{true}
+
+
+\mbox{false}
+
+
+\emptyset 
+
+
+\pi 
+
+
+\gamma 
+
+
+\infty 
+
+
+
+  
+  
+  
+  (
+  
+		
+			
+		
+		
+			
+		
+	
+  )
+
+
+
+  
+  
+  
+  (
+	
+		
+	
+	
+	
+    	
+	
+	)
+
+
+
+
+
+
+
+
+	
+	
+	
+			
+
+
+
+
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+			
+				
+			
+			
+
+
+								
+		
+				
+								
+								
+
+
+
+			
+			 
+				
+				
+				
+				
+				
+				
+				 
+				 
+			 
+				
+				
+				
+				
+
+
+				
+
+
+
+
+			
+			 
+			
+			
+			 
+			
+			 
+
+				
+				
+				
+				
+			
+				
+			
+				
+				
+				
+			 
+
+			
+				
+				
+		
+				
+			
+				
+
+				
+				
+			
+				
+			 
+				 
+			
+			 
+			 
+				
+				
+				
+				
+				
+				 
+					
+				
+
+
+
+
+
+			 
+			 
+			
+		
+			
+
+
+
+				
+			 
+
+
+				
+				 
+				 
+				
+			
+				
+
+				 
+			
+
+			
+			 
+
+
+				
+			 
+			 
+				
+			 
+			 
+			 
+
+
+			 
+			 
+	
+		
+		
+		
+			 
+	
+	
+		
+
+				
+
+				
+			
+
+				
+				
+				 
+				 
+				 
+				 
+
+
+				
+
+
+				
+			 
+		
+				 
+				 
+			 
+				 
+			 
+				 
+			 
+			 
+			 
+			 
+			 
+			 
+			 
+			 
+				
+				
+			 
+			 
+			 
+			 
+				 
+				 
+			
+			
+			
+			
+			
+			
+				
+				
+				
+				
+			
+			
+			
+			 
+			 
+				
+				
+				
+				 
+			
+			 
+			
+			
+			
+			
+			
+				
+				
+			 
+			
+			 
+				
+
+				
+
+
+			 
+			 
+
+		
+		
+		
+		
+		
+		
+		
+
+
+		
+			
+			
+				
+			
+		
+	
+
+
+
+	
+	
+		
+		
+			
+		
+	
+		
+		
+			
+		
+	
+	
+		
+	
+	
+
+
+
+
+
+
+
+
+	\multicolumn{
+	
+	}{c}{
+	
+	}
+	
+		& 
+	
+
+
+
+
+	
+		\hfill 
+	
+	
+	
+		\hfill 
+	
+	
+
+		& 
+	
+
+
+
+	
+	
+		\\ 
+	
+
+
+
+	\begin{array}{
+	
+		|
+	
+	
+	
+		
+			
+				
+					
+				
+			
+			
+				
+					
+				
+				
+					
+					
+						
+						
+					
+				
+				
+					
+				
+			
+		
+		
+			
+				
+				
+			
+		
+	
+	
+		|
+	
+	}
+	
+		\hline 
+	
+	
+	
+		\\ \hline
+	
+	\end{array}
+
+
+
+	
+	
+		
+			
+			
+				
+			
+		
+		
+			
+		
+	
+
+
+
+
+    
+    
+
+    
+      
+
+      
+	
+	
+	  
+	  
+	
+      
+    
+
+
+
+
+
+
+
+
+	
+		
+			
+		
+	
+	
+		
+			
+		
+	
+	
+		
+			
+		
+	
+
+	
+			
+			\overline{
+			
+				
+				
+			
+			}
+		
+			
+			\overbrace{
+			
+				
+				
+			
+			}
+		
+			
+			\underline{
+			
+				
+				
+				
+			
+			}
+		
+			
+			\underbrace{
+			
+				
+				
+				
+			
+			}
+		
+		
+
+			
+			_{
+			
+			}^{
+			
+			}
+		
+		
+			\underset{
+			
+			}{\overset{
+			
+			}{
+			
+			}}
+		
+	
+
+
+
+	
+		
+			
+				
+			
+		
+		
+			
+				
+			
+		
+	
+
+
+
+	
+		
+			
+				
+			
+		
+		
+			
+				
+			
+		
+	
+
+
+
+	
+	
+	
+	
+			
+			\overline{
+			
+			}
+		
+			
+			\overbrace{
+			
+			}
+		
+		
+
+			
+			^{
+			
+			}
+		
+		
+			\stackrel{
+			
+			}{
+			
+			}
+			
+		
+	
+
+
+
+	
+	
+	
+			
+			\underline{
+			
+			}
+		
+			
+			\underbrace{
+			
+			}
+		
+		
+
+			
+			_{
+			
+			}
+		
+		
+			\underset{		
+			
+			}{
+			
+			}
+		
+	
+
+
+
+	{
+	
+	}_{
+	
+	}^{
+	
+	}
+
+
+
+	{
+	
+	}^{
+	
+	}
+
+
+
+	{
+	
+	}_{
+	
+	}
+
+
+
+	
+		
+			{}_{
+			
+			}
+		
+		
+			{}^{
+			
+			}
+		
+	
+	
+	
+		
+			{}
+		
+		
+			_{
+			
+			}
+		
+		
+			^{
+			
+			}
+		
+	
+
+
+
+	
+		
+			
+		
+		
+			
+			
+				
+					{}
+				
+				
+					_{
+					
+					}
+				
+				
+					^{
+					
+					}
+				
+			
+		
+	
+
+
+
+
+
+
+
+
+	
+		
+
+		
+		
+			\genfrac{}{}{
+			
+				
+					
+					ex
+				
+				
+					.05ex
+				
+				
+				
+					.2ex
+				
+				
+					
+				
+			
+			}{}{
+		
+		
+			\frac{
+		
+	
+	
+		\hfill 
+	
+	
+	
+		\hfill 
+	
+	}{
+	
+		\hfill 
+	
+	
+		
+		\hfill 
+	
+	}
+
+
+
+	
+		
+			\sqrt[
+			
+			]{
+			
+			}
+		
+		
+		
+			exception 25:
+			\text{exception 25:}
+		
+	
+
+
+
+	\sqrt{
+	
+	}
+
+
+
+	
+		
+			
+				\left
+			
+			
+				\
+			
+			
+		
+		\left(
+	
+	
+		
+			
+				
+					
+						
+							
+						
+					
+					,
+				
+			
+			
+				
+				
+					
+						
+							
+						
+						
+							
+						
+					
+				
+			
+		
+		
+			
+		
+	
+	
+		
+			
+				\right
+			
+			
+				\
+			
+			
+		
+		\right)
+	
+
+
+
+	\phantom{
+	
+	}
+
+
+
+	
+		
+			\overline{
+			
+			\hspace{.2em}|}
+		
+		
+			\sqrt{
+			
+			}
+		
+		
+			\overline{)
+			
+			}
+		
+	
+
+
+
+	
+
+
+
+	
+		\colorbox[rgb]{
+		
+			
+		
+		}{$
+	
+	
+		\textcolor[rgb]{
+		
+			
+		
+		}{
+	
+	
+	
+		}
+	
+	
+		$}
+	
+
+
+
+
+	
+
+
+
+
+
+
+
+
+	
+
+
+
+	
+		
+			\mathrm{
+				
+			}
+		
+		
+			
+		
+	
+
+
+
+	
+
+
+
+	
+
+
+
+	
+		
+			
+		
+	
+	\text{
+	
+	}
+
+
+
+	\phantom{\rule
+	
+		[-
+		
+		]
+	
+	{
+	
+		0ex
+	
+	
+	}{
+	
+		0ex
+	
+	
+	}}
+
+
+
+	
+		
+		"
+	
+		
+		"
+	
+
+
+
+	
+		\colorbox[rgb]{
+		
+			
+		
+		}{$
+	
+	 
+		\textcolor[rgb]{
+		
+			
+		
+		}{
+	
+	
+		
+			
+				\mathrm{
+			
+			
+				\mathbf{
+			
+			
+				\mathit{
+			
+				
+				\mathbit{
+			
+				
+				\mathbb{
+			
+				
+				{
+			
+			
+				\mathcal{
+			
+				
+				\mathsc{
+			
+				
+				\mathfrak{
+			
+			
+				\mathsf{
+			
+			 
+				\mathbsf{
+			
+			 
+				\mathsfit{
+			
+				
+				\mathbsfit{
+			
+			
+				\mathtt{
+			
+			
+				{
+			
+		
+	
+	
+	
+		}
+	
+	
+		}
+	
+	
+		$}
+	
+
+
+
+
+	
+		
+			
+		
+		
+			
+		
+		
+			
+		
+		
+			
+		
+		
+			
+		
+	
+
+
+
+
+	
+	
+	
+	
+		
+			
+				
+			
+		
+		,
+		
+			
+				
+			
+		
+		,
+		
+			
+				
+			
+		
+		
+	
+	
+		
+			
+				
+			
+		
+		
+			
+				
+			
+		
+		,
+		
+			
+				
+			
+		
+		
+			
+				
+			
+		
+		,
+		
+			
+				
+			
+		
+		
+			
+				
+			
+		
+		
+	
+
+	0,1,1
+	0,0,0
+	0,0,1
+	1,0,1
+	.5,.5,.5
+	0,.5,0
+	0,1,0
+	.5,0,0
+	0,0,.5
+	.5,.5,0
+	.5,0,.5
+	1,0,0
+	.75,.75,.75
+	0,.5,.5
+	1,1,1
+	1,1,0
+	
+		Exception at color template
+	
+	
+
+
+
+	
+	
+		
+			
+		
+		
+			
+		
+		
+			
+		
+		
+			
+		
+		
+			
+		
+		
+			
+		
+		 
+			
+		
+		
+			Exception at Hex2Decimal template
+		
+	
+
+
+
+	
+		
+	
+
+
+
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/mathml/data/simple_mmlctop.xsl b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/mathml/data/simple_mmlctop.xsl
new file mode 100644
index 0000000000000000000000000000000000000000..0cd73bccc24c963ed9c6c4121cc410997b94261c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/mathml/data/simple_mmlctop.xsl
@@ -0,0 +1,3166 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+  
+    
+    
+  
+
+
+
+
+
+
+
+  
+    
+    
+      
+        
+          
+            
+          
+          
+            
+          
+        
+      
+      
+        
+      
+    
+  
+
+
+
+
+
+
+
+
+
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+        
+        
+        
+      
+    
+    
+      
+        
+        
+        
+        
+        
+      
+        
+      
+    
+    
+      
+        
+          
+            
+              
+              
+              
+              
+            
+            
+          
+          
+            
+              
+              
+              
+              
+            
+            
+              
+            
+          
+        
+      
+    
+    
+      
+        
+          
+            
+            
+              
+            
+            
+            
+          
+        
+        
+          
+            
+            
+            
+            
+          
+        
+      
+    
+    
+      
+        
+        
+        
+        
+      
+    
+  
+
+
+
+
+  
+
+
+
+
+
+
+
+  
+  
+  
+  
+    
+      
+        
+      
+    
+    
+      
+    
+  
+
+
+
+  
+    
+      
+        
+          
+            
+          
+        
+          
+          
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+          
+         e 
+          
+      
+    
+    
+      
+        
+          
+            
+          
+        
+          
+        
+           - 
+            
+        
+        
+           + 
+            
+        
+         &#x2062; 
+         &#x2148; 
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+            
+          
+             - 
+              
+          
+          
+             + 
+              
+          
+           &#x2062; 
+           &#x2148; 
+        
+          
+      
+    
+    
+      
+        
+          
+            
+          
+        
+          
+          
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+              
+              
+          
+        
+          
+      
+    
+    
+      
+        
+          
+            
+          
+        
+         Polar 
+         &#x2062; 
+        
+            
+            
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+           Polar 
+           &#x2062; 
+          
+              
+              
+          
+        
+          
+      
+   
+    
+        
+    
+  
+
+
+
+
+  
+    
+      
+        
+          
+            
+          
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+      
+    
+    
+      
+        
+          
+            
+              
+            
+          
+          
+        
+      
+      
+        
+      
+    
+  
+
+
+
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+  
+
+
+
+
+
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+      
+    
+    
+      
+      
+      
+    
+     &#x2061; 
+    
+      
+        
+        
+        
+      
+    
+ 
+
+
+
+
+
+  
+  
+  
+  
+  
+    
+    
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+       [ 
+    
+    
+       ] 
+    
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+		
+          
+            
+            
+            
+          
+		
+		
+           -1 
+        
+      
+    
+  
+
+
+
+  
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+    
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+  
+
+
+
+
+
+
+
+  
+    
+      
+        
+      
+    
+     &#x03BB; 
+     &#x2061; 
+    
+      
+        
+          
+            
+          
+          
+            
+              
+            
+          
+        
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+        
+           &#x2218; 
+          
+            
+            
+            
+          
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+        
+           &#x2218; 
+          
+            
+            
+            
+          
+        
+      
+	
+  
+
+
+
+
+  
+    
+      id
+    
+    
+      id
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+	
+      domain
+	
+	
+      codomain
+	
+	
+      image
+	
+     &#x2061; 
+    
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+     { 
+    
+      
+        
+          
+            
+          
+          
+            if 
+            
+          
+        
+      
+      
+        
+          
+            
+          
+          
+            otherwise
+          
+        
+      
+    
+  
+
+
+
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+      
+    
+     &#x230A; 
+    
+      
+        
+          
+          
+          
+          
+        
+      
+      
+        
+          
+          
+          
+          
+        
+      
+    
+     &#x230B; 
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+     e 
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+      
+    
+     ! 
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+          
+             max 
+          
+          
+             min 
+          
+          
+        
+      
+      
+        
+           max 
+        
+        
+           min 
+        
+      
+	
+    
+      
+        
+        
+          
+            
+              
+            
+          
+           | 
+        
+        
+      
+      
+        
+          
+        
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+     - 
+    
+      
+      
+      
+    
+  
+  
+    
+      
+      
+      
+      
+    
+     - 
+    
+      
+      
+      
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+    
+      
+      
+      
+      
+    
+    
+      
+        
+           - 
+            
+        
+        
+          
+            
+            
+            
+          
+        
+        
+           + 
+          
+            
+            
+            
+          
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+        
+        
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+    
+      
+        
+        
+        
+        
+      
+    
+    
+      
+        
+        
+        
+        
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+    
+    
+    
+    
+  
+    
+  
+    
+    
+    
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+    
+    
+    
+    
+  
+  
+    
+       &#x2062; 
+      
+        
+        
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+      
+    
+    
+  
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+         gcd 
+      
+      
+         lcm 
+      
+    
+    
+      
+      
+         gcd 
+      
+      
+         lcm 
+      
+        
+      
+    
+     &#x2061; 
+    
+      
+        
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+    
+    
+    
+    
+  
+  
+     &#x2227; 
+     &#x2061; 
+    
+      
+      
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+    
+    
+    
+    
+  
+  
+     &#x2228; 
+     &#x2061; 
+    
+      
+      
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+    
+      
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+    
+    
+    
+    
+  
+  
+     &#x22BB; 
+     &#x2061; 
+    
+      
+      
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+         &#x00AC; 
+         &#x2061; 
+        
+          
+          
+          
+        
+	  
+    
+    
+      
+        
+          
+            
+          
+        
+         &#x00AC; 
+         &#x2061; 
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+     &#x2200; 
+    
+      
+    
+    
+      
+        
+          
+        
+      
+    
+	
+       : 
+      
+    
+	
+       , 
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+     &#x2203; 
+    
+      
+        
+          
+        
+      
+    
+    
+      
+    
+    
+       : 
+      
+    
+    
+       , 
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+          
+        
+      
+      
+    
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+      
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+    
+     &#x00AF; 
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+      
+      
+        &#x211C;
+      
+      
+        &#x2111;
+      
+    
+     &#x2061; 
+    
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        &#x230A;
+      
+      
+        &#x2308;
+      
+    
+    
+    
+      
+        &#x230B;
+      
+      
+        &#x2309;
+      
+    
+  
+
+
+
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+  
+
+
+
+  
+    
+    
+      
+        &#x2260;
+      
+      
+        &#x2248;
+      
+      
+        &#x2223;
+      
+      
+        
+          
+            &#x2198;
+          
+          
+            &#x2197;
+          
+		  
+            &#x2192;
+          
+        
+      
+      
+        &#x21D2;
+      
+      
+        &#x2208;
+      
+      
+        &#x2209;
+      
+      
+        &#x2284;
+      
+      
+        &#x2288;
+      
+    
+    
+  
+  
+    
+    
+      
+        
+          &#x2286;
+        
+        
+         &#x2282;
+        
+        
+          
+        
+        
+          
+        
+        
+          
+        
+        
+         &#x2265;
+        
+        
+         &#x2264;
+        
+        
+         &#x2261;
+        
+      
+      
+    
+  
+
+
+
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+           ln 
+          
+        
+      
+      
+         ln 
+      
+    
+    
+      
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+          
+             log 
+            
+          
+        
+        
+          
+             log 
+            
+            
+          
+        
+      
+      
+        
+           log 
+        
+        
+          
+             log 
+            
+          
+        
+      
+    
+    
+      
+        
+        
+      
+    
+    
+      
+        
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+	
+      
+        
+          
+             d 
+            
+               d 
+              
+            
+          
+        
+        
+          
+            
+               d 
+              
+            
+            
+               d 
+              
+                
+                
+              
+            
+          
+        
+        
+          
+          
+        
+      
+      
+        
+          
+          
+        
+         &#x2032; 
+	  
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+           &#x2145; 
+          
+        
+      
+      
+        
+		  
+            
+               &#x2202; 
+              
+            
+            
+              
+                 &#x2202; 
+                
+                  
+                    
+                    
+                  
+                
+                
+                  
+                
+              
+            
+		  
+		
+        
+          
+            
+              
+                
+                   &#x2202; 
+                  
+                
+                
+                   &#x2202; 
+                  
+                    
+                    
+                  
+                
+              
+            
+            
+              
+                 &#x2202; 
+                
+                   &#x2202; 
+                  
+                
+              
+            
+          
+		
+	  
+	
+	
+      
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+      
+      
+        
+      
+      
+        
+      
+    
+    
+    
+      
+        
+      
+      
+        
+          
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+       &#x2207; 
+       2 
+    
+     &#x2061; 
+    
+      
+      
+    
+  
+
+
+
+
+
+
+
+  
+    
+      
+        
+      
+    
+	
+      
+        
+      
+      
+        
+      
+    
+	
+      
+        
+      
+      
+        
+      
+    
+    
+      
+        
+      
+      
+        
+        
+         | 
+        
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+    
+    
+    
+    
+  
+  
+     &#x222A; 
+    
+      
+      
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+    
+    
+    
+    
+  
+  
+     &#x2229; 
+    
+      
+      
+      
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+    
+    
+    
+    
+  
+  \
+  
+    
+    
+    
+    
+  
+
+
+
+
+  
+  
+  
+  
+  
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+    
+      
+        
+        
+        
+      
+    
+    
+      
+        
+          
+            
+          
+        
+        
+          
+          
+          
+        
+      
+    
+  
+
+
+
+  
+  
+  
+  
+    
+    
+    
+    
+  
+  
+    &#x00D7;
+    
+      
+      
+      
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+    
+  
+
+
+
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+          
+            
+             &#x2211;
+            
+            
+             &#x220F;
+            
+          
+          
+            
+             = 
+            
+          
+          
+        
+        
+      
+      
+        
+          
+            
+             &#x2211;
+            
+            
+             &#x220F;
+            
+          
+          
+        
+        
+      
+      
+        
+          
+            
+              &#x2211;
+            
+            
+              &#x220F;
+            
+          
+          
+        
+        
+          
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+	
+	  
+        
+           &#x222B; 
+          
+        
+      
+	  
+        
+           &#x222B; 
+          
+        
+      
+      
+        
+           &#x222B; 
+          
+            
+          
+          
+            
+            
+          
+		
+      
+      
+        
+           &#x222B; 
+          
+          
+            
+            
+          
+        
+      
+	  
+         &#x222B; 
+      
+    
+    
+      
+      
+    
+	
+      
+         d 
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+       lim 
+      
+        
+            
+             &#x2192; 
+            
+        
+        
+          
+        
+      
+    
+    
+  
+
+
+
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+    
+    
+      
+        
+        
+      
+    
+    
+    
+      
+      
+    
+  
+
+
+
+  
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+      
+        
+      
+    
+  
+
+
+
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+     &#x03C3; 
+    
+      
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+     &#x03C3; 
+    
+      
+        
+          
+        
+      
+       2 
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+     median 
+    
+      
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+     mode 
+    
+      
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+        
+      
+    
+    
+      
+        
+        
+      
+    
+    
+      
+        
+      
+    
+    
+      
+        
+      
+    
+  
+
+
+
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+            
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+      
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+     det 
+    
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+     T 
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+    
+      
+        
+      
+    
+  
+
+
+
+
+  
+    
+      
+        
+      
+    
+    
+    
+      
+        &#x00D7;
+      
+      
+        &#x22C5;
+      
+      
+        &#x2297;
+      
+    
+    
+  
+
+
+
+
+
+
+
+   &#x2124; 
+
+
+
+   &#x211D; 
+
+
+
+   &#x211A; 
+
+
+
+   &#x2115; 
+
+
+
+   &#x2102; 
+
+
+
+   &#x2119; 
+
+
+
+   e 
+
+
+
+   &#x2148; 
+
+
+
+   NaN 
+
+
+
+   true 
+
+
+
+   false 
+
+
+
+   &#x2205; 
+
+
+
+   &#x03C0; 
+
+
+
+   &#x213D; 
+
+
+
+   &#x221E; 
+
+
+
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/memoization.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/memoization.py
new file mode 100644
index 0000000000000000000000000000000000000000..b638dfe244628096108ea689b664782f6538b7b8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/memoization.py
@@ -0,0 +1,76 @@
+from functools import wraps
+
+
+def recurrence_memo(initial):
+    """
+    Memo decorator for sequences defined by recurrence
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.memoization import recurrence_memo
+    >>> @recurrence_memo([1]) # 0! = 1
+    ... def factorial(n, prev):
+    ...     return n * prev[-1]
+    >>> factorial(4)
+    24
+    >>> factorial(3) # use cache values
+    6
+    >>> factorial.cache_length() # cache length can be obtained
+    5
+    >>> factorial.fetch_item(slice(2, 4))
+    [2, 6]
+
+    """
+    cache = initial
+
+    def decorator(f):
+        @wraps(f)
+        def g(n):
+            L = len(cache)
+            if n < L:
+                return cache[n]
+            for i in range(L, n + 1):
+                cache.append(f(i, cache))
+            return cache[-1]
+        g.cache_length = lambda: len(cache)
+        g.fetch_item = lambda x: cache[x]
+        return g
+    return decorator
+
+
+def assoc_recurrence_memo(base_seq):
+    """
+    Memo decorator for associated sequences defined by recurrence starting from base
+
+    base_seq(n) -- callable to get base sequence elements
+
+    XXX works only for Pn0 = base_seq(0) cases
+    XXX works only for m <= n cases
+    """
+
+    cache = []
+
+    def decorator(f):
+        @wraps(f)
+        def g(n, m):
+            L = len(cache)
+            if n < L:
+                return cache[n][m]
+
+            for i in range(L, n + 1):
+                # get base sequence
+                F_i0 = base_seq(i)
+                F_i_cache = [F_i0]
+                cache.append(F_i_cache)
+
+                # XXX only works for m <= n cases
+                # generate assoc sequence
+                for j in range(1, i + 1):
+                    F_ij = f(i, j, cache)
+                    F_i_cache.append(F_ij)
+
+            return cache[n][m]
+
+        return g
+    return decorator
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/misc.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..741b983f03272890b22f2545f67b141767507634
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/misc.py
@@ -0,0 +1,564 @@
+"""Miscellaneous stuff that does not really fit anywhere else."""
+
+from __future__ import annotations
+
+import operator
+import sys
+import os
+import re as _re
+import struct
+from textwrap import fill, dedent
+
+
+class Undecidable(ValueError):
+    # an error to be raised when a decision cannot be made definitively
+    # where a definitive answer is needed
+    pass
+
+
+def filldedent(s, w=70, **kwargs):
+    """
+    Strips leading and trailing empty lines from a copy of ``s``, then dedents,
+    fills and returns it.
+
+    Empty line stripping serves to deal with docstrings like this one that
+    start with a newline after the initial triple quote, inserting an empty
+    line at the beginning of the string.
+
+    Additional keyword arguments will be passed to ``textwrap.fill()``.
+
+    See Also
+    ========
+    strlines, rawlines
+
+    """
+    return '\n' + fill(dedent(str(s)).strip('\n'), width=w, **kwargs)
+
+
+def strlines(s, c=64, short=False):
+    """Return a cut-and-pastable string that, when printed, is
+    equivalent to the input.  The lines will be surrounded by
+    parentheses and no line will be longer than c (default 64)
+    characters. If the line contains newlines characters, the
+    `rawlines` result will be returned.  If ``short`` is True
+    (default is False) then if there is one line it will be
+    returned without bounding parentheses.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.misc import strlines
+    >>> q = 'this is a long string that should be broken into shorter lines'
+    >>> print(strlines(q, 40))
+    (
+    'this is a long string that should be b'
+    'roken into shorter lines'
+    )
+    >>> q == (
+    ... 'this is a long string that should be b'
+    ... 'roken into shorter lines'
+    ... )
+    True
+
+    See Also
+    ========
+    filldedent, rawlines
+    """
+    if not isinstance(s, str):
+        raise ValueError('expecting string input')
+    if '\n' in s:
+        return rawlines(s)
+    q = '"' if repr(s).startswith('"') else "'"
+    q = (q,)*2
+    if '\\' in s:  # use r-string
+        m = '(\nr%s%%s%s\n)' % q
+        j = '%s\nr%s' % q
+        c -= 3
+    else:
+        m = '(\n%s%%s%s\n)' % q
+        j = '%s\n%s' % q
+        c -= 2
+    out = []
+    while s:
+        out.append(s[:c])
+        s=s[c:]
+    if short and len(out) == 1:
+        return (m % out[0]).splitlines()[1]  # strip bounding (\n...\n)
+    return m % j.join(out)
+
+
+def rawlines(s):
+    """Return a cut-and-pastable string that, when printed, is equivalent
+    to the input. Use this when there is more than one line in the
+    string. The string returned is formatted so it can be indented
+    nicely within tests; in some cases it is wrapped in the dedent
+    function which has to be imported from textwrap.
+
+    Examples
+    ========
+
+    Note: because there are characters in the examples below that need
+    to be escaped because they are themselves within a triple quoted
+    docstring, expressions below look more complicated than they would
+    be if they were printed in an interpreter window.
+
+    >>> from sympy.utilities.misc import rawlines
+    >>> from sympy import TableForm
+    >>> s = str(TableForm([[1, 10]], headings=(None, ['a', 'bee'])))
+    >>> print(rawlines(s))
+    (
+        'a bee\\n'
+        '-----\\n'
+        '1 10 '
+    )
+    >>> print(rawlines('''this
+    ... that'''))
+    dedent('''\\
+        this
+        that''')
+
+    >>> print(rawlines('''this
+    ... that
+    ... '''))
+    dedent('''\\
+        this
+        that
+        ''')
+
+    >>> s = \"\"\"this
+    ... is a triple '''
+    ... \"\"\"
+    >>> print(rawlines(s))
+    dedent(\"\"\"\\
+        this
+        is a triple '''
+        \"\"\")
+
+    >>> print(rawlines('''this
+    ... that
+    ...     '''))
+    (
+        'this\\n'
+        'that\\n'
+        '    '
+    )
+
+    See Also
+    ========
+    filldedent, strlines
+    """
+    lines = s.split('\n')
+    if len(lines) == 1:
+        return repr(lines[0])
+    triple = ["'''" in s, '"""' in s]
+    if any(li.endswith(' ') for li in lines) or '\\' in s or all(triple):
+        rv = []
+        # add on the newlines
+        trailing = s.endswith('\n')
+        last = len(lines) - 1
+        for i, li in enumerate(lines):
+            if i != last or trailing:
+                rv.append(repr(li + '\n'))
+            else:
+                rv.append(repr(li))
+        return '(\n    %s\n)' % '\n    '.join(rv)
+    else:
+        rv = '\n    '.join(lines)
+        if triple[0]:
+            return 'dedent("""\\\n    %s""")' % rv
+        else:
+            return "dedent('''\\\n    %s''')" % rv
+
+ARCH = str(struct.calcsize('P') * 8) + "-bit"
+
+
+# XXX: PyPy does not support hash randomization
+HASH_RANDOMIZATION = getattr(sys.flags, 'hash_randomization', False)
+
+_debug_tmp: list[str] = []
+_debug_iter = 0
+
+def debug_decorator(func):
+    """If SYMPY_DEBUG is True, it will print a nice execution tree with
+    arguments and results of all decorated functions, else do nothing.
+    """
+    from sympy import SYMPY_DEBUG
+
+    if not SYMPY_DEBUG:
+        return func
+
+    def maketree(f, *args, **kw):
+        global _debug_tmp, _debug_iter
+        oldtmp = _debug_tmp
+        _debug_tmp = []
+        _debug_iter += 1
+
+        def tree(subtrees):
+            def indent(s, variant=1):
+                x = s.split("\n")
+                r = "+-%s\n" % x[0]
+                for a in x[1:]:
+                    if a == "":
+                        continue
+                    if variant == 1:
+                        r += "| %s\n" % a
+                    else:
+                        r += "  %s\n" % a
+                return r
+            if len(subtrees) == 0:
+                return ""
+            f = []
+            for a in subtrees[:-1]:
+                f.append(indent(a))
+            f.append(indent(subtrees[-1], 2))
+            return ''.join(f)
+
+        # If there is a bug and the algorithm enters an infinite loop, enable the
+        # following lines. It will print the names and parameters of all major functions
+        # that are called, *before* they are called
+        #from functools import reduce
+        #print("%s%s %s%s" % (_debug_iter, reduce(lambda x, y: x + y, \
+        #    map(lambda x: '-', range(1, 2 + _debug_iter))), f.__name__, args))
+
+        r = f(*args, **kw)
+
+        _debug_iter -= 1
+        s = "%s%s = %s\n" % (f.__name__, args, r)
+        if _debug_tmp != []:
+            s += tree(_debug_tmp)
+        _debug_tmp = oldtmp
+        _debug_tmp.append(s)
+        if _debug_iter == 0:
+            print(_debug_tmp[0])
+            _debug_tmp = []
+        return r
+
+    def decorated(*args, **kwargs):
+        return maketree(func, *args, **kwargs)
+
+    return decorated
+
+
+def debug(*args):
+    """
+    Print ``*args`` if SYMPY_DEBUG is True, else do nothing.
+    """
+    from sympy import SYMPY_DEBUG
+    if SYMPY_DEBUG:
+        print(*args, file=sys.stderr)
+
+
+def debugf(string, args):
+    """
+    Print ``string%args`` if SYMPY_DEBUG is True, else do nothing. This is
+    intended for debug messages using formatted strings.
+    """
+    from sympy import SYMPY_DEBUG
+    if SYMPY_DEBUG:
+        print(string%args, file=sys.stderr)
+
+
+def find_executable(executable, path=None):
+    """Try to find 'executable' in the directories listed in 'path' (a
+    string listing directories separated by 'os.pathsep'; defaults to
+    os.environ['PATH']).  Returns the complete filename or None if not
+    found
+    """
+    from .exceptions import sympy_deprecation_warning
+    sympy_deprecation_warning(
+        """
+        sympy.utilities.misc.find_executable() is deprecated. Use the standard
+        library shutil.which() function instead.
+        """,
+        deprecated_since_version="1.7",
+        active_deprecations_target="deprecated-find-executable",
+    )
+    if path is None:
+        path = os.environ['PATH']
+    paths = path.split(os.pathsep)
+    extlist = ['']
+    if os.name == 'os2':
+        (base, ext) = os.path.splitext(executable)
+        # executable files on OS/2 can have an arbitrary extension, but
+        # .exe is automatically appended if no dot is present in the name
+        if not ext:
+            executable = executable + ".exe"
+    elif sys.platform == 'win32':
+        pathext = os.environ['PATHEXT'].lower().split(os.pathsep)
+        (base, ext) = os.path.splitext(executable)
+        if ext.lower() not in pathext:
+            extlist = pathext
+    for ext in extlist:
+        execname = executable + ext
+        if os.path.isfile(execname):
+            return execname
+        else:
+            for p in paths:
+                f = os.path.join(p, execname)
+                if os.path.isfile(f):
+                    return f
+
+    return None
+
+
+def func_name(x, short=False):
+    """Return function name of `x` (if defined) else the `type(x)`.
+    If short is True and there is a shorter alias for the result,
+    return the alias.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.misc import func_name
+    >>> from sympy import Matrix
+    >>> from sympy.abc import x
+    >>> func_name(Matrix.eye(3))
+    'MutableDenseMatrix'
+    >>> func_name(x < 1)
+    'StrictLessThan'
+    >>> func_name(x < 1, short=True)
+    'Lt'
+    """
+    alias = {
+    'GreaterThan': 'Ge',
+    'StrictGreaterThan': 'Gt',
+    'LessThan': 'Le',
+    'StrictLessThan': 'Lt',
+    'Equality': 'Eq',
+    'Unequality': 'Ne',
+    }
+    typ = type(x)
+    if str(typ).startswith(">> from sympy.utilities.misc import _replace
+    >>> f = _replace(dict(foo='bar', d='t'))
+    >>> f('food')
+    'bart'
+    >>> f = _replace({})
+    >>> f('food')
+    'food'
+    """
+    if not reps:
+        return lambda x: x
+    D = lambda match: reps[match.group(0)]
+    pattern = _re.compile("|".join(
+        [_re.escape(k) for k, v in reps.items()]), _re.MULTILINE)
+    return lambda string: pattern.sub(D, string)
+
+
+def replace(string, *reps):
+    """Return ``string`` with all keys in ``reps`` replaced with
+    their corresponding values, longer strings first, irrespective
+    of the order they are given.  ``reps`` may be passed as tuples
+    or a single mapping.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.misc import replace
+    >>> replace('foo', {'oo': 'ar', 'f': 'b'})
+    'bar'
+    >>> replace("spamham sha", ("spam", "eggs"), ("sha","md5"))
+    'eggsham md5'
+
+    There is no guarantee that a unique answer will be
+    obtained if keys in a mapping overlap (i.e. are the same
+    length and have some identical sequence at the
+    beginning/end):
+
+    >>> reps = [
+    ...     ('ab', 'x'),
+    ...     ('bc', 'y')]
+    >>> replace('abc', *reps) in ('xc', 'ay')
+    True
+
+    References
+    ==========
+
+    .. [1] https://stackoverflow.com/questions/6116978/how-to-replace-multiple-substrings-of-a-string
+    """
+    if len(reps) == 1:
+        kv = reps[0]
+        if isinstance(kv, dict):
+            reps = kv
+        else:
+            return string.replace(*kv)
+    else:
+        reps = dict(reps)
+    return _replace(reps)(string)
+
+
+def translate(s, a, b=None, c=None):
+    """Return ``s`` where characters have been replaced or deleted.
+
+    SYNTAX
+    ======
+
+    translate(s, None, deletechars):
+        all characters in ``deletechars`` are deleted
+    translate(s, map [,deletechars]):
+        all characters in ``deletechars`` (if provided) are deleted
+        then the replacements defined by map are made; if the keys
+        of map are strings then the longer ones are handled first.
+        Multicharacter deletions should have a value of ''.
+    translate(s, oldchars, newchars, deletechars)
+        all characters in ``deletechars`` are deleted
+        then each character in ``oldchars`` is replaced with the
+        corresponding character in ``newchars``
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.misc import translate
+    >>> abc = 'abc'
+    >>> translate(abc, None, 'a')
+    'bc'
+    >>> translate(abc, {'a': 'x'}, 'c')
+    'xb'
+    >>> translate(abc, {'abc': 'x', 'a': 'y'})
+    'x'
+
+    >>> translate('abcd', 'ac', 'AC', 'd')
+    'AbC'
+
+    There is no guarantee that a unique answer will be
+    obtained if keys in a mapping overlap are the same
+    length and have some identical sequences at the
+    beginning/end:
+
+    >>> translate(abc, {'ab': 'x', 'bc': 'y'}) in ('xc', 'ay')
+    True
+    """
+
+    mr = {}
+    if a is None:
+        if c is not None:
+            raise ValueError('c should be None when a=None is passed, instead got %s' % c)
+        if b is None:
+            return s
+        c = b
+        a = b = ''
+    else:
+        if isinstance(a, dict):
+            short = {}
+            for k in list(a.keys()):
+                if len(k) == 1 and len(a[k]) == 1:
+                    short[k] = a.pop(k)
+            mr = a
+            c = b
+            if short:
+                a, b = [''.join(i) for i in list(zip(*short.items()))]
+            else:
+                a = b = ''
+        elif len(a) != len(b):
+            raise ValueError('oldchars and newchars have different lengths')
+
+    if c:
+        val = str.maketrans('', '', c)
+        s = s.translate(val)
+    s = replace(s, mr)
+    n = str.maketrans(a, b)
+    return s.translate(n)
+
+
+def ordinal(num):
+    """Return ordinal number string of num, e.g. 1 becomes 1st.
+    """
+    # modified from https://codereview.stackexchange.com/questions/41298/producing-ordinal-numbers
+    n = as_int(num)
+    k = abs(n) % 100
+    if 11 <= k <= 13:
+        suffix = 'th'
+    elif k % 10 == 1:
+        suffix = 'st'
+    elif k % 10 == 2:
+        suffix = 'nd'
+    elif k % 10 == 3:
+        suffix = 'rd'
+    else:
+        suffix = 'th'
+    return str(n) + suffix
+
+
+def as_int(n, strict=True):
+    """
+    Convert the argument to a builtin integer.
+
+    The return value is guaranteed to be equal to the input. ValueError is
+    raised if the input has a non-integral value. When ``strict`` is True, this
+    uses `__index__ `_
+    and when it is False it uses ``int``.
+
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.misc import as_int
+    >>> from sympy import sqrt, S
+
+    The function is primarily concerned with sanitizing input for
+    functions that need to work with builtin integers, so anything that
+    is unambiguously an integer should be returned as an int:
+
+    >>> as_int(S(3))
+    3
+
+    Floats, being of limited precision, are not assumed to be exact and
+    will raise an error unless the ``strict`` flag is False. This
+    precision issue becomes apparent for large floating point numbers:
+
+    >>> big = 1e23
+    >>> type(big) is float
+    True
+    >>> big == int(big)
+    True
+    >>> as_int(big)
+    Traceback (most recent call last):
+    ...
+    ValueError: ... is not an integer
+    >>> as_int(big, strict=False)
+    99999999999999991611392
+
+    Input that might be a complex representation of an integer value is
+    also rejected by default:
+
+    >>> one = sqrt(3 + 2*sqrt(2)) - sqrt(2)
+    >>> int(one) == 1
+    True
+    >>> as_int(one)
+    Traceback (most recent call last):
+    ...
+    ValueError: ... is not an integer
+    """
+    if strict:
+        try:
+            if isinstance(n, bool):
+                raise TypeError
+            return operator.index(n)
+        except TypeError:
+            raise ValueError('%s is not an integer' % (n,))
+    else:
+        try:
+            result = int(n)
+        except TypeError:
+            raise ValueError('%s is not an integer' % (n,))
+        if n - result:
+            raise ValueError('%s is not an integer' % (n,))
+        return result
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/pkgdata.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/pkgdata.py
new file mode 100644
index 0000000000000000000000000000000000000000..8bf2065759362ee09a252d4736bd612b8d271e72
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/pkgdata.py
@@ -0,0 +1,33 @@
+# This module is deprecated and will be removed.
+
+import sys
+import os
+from io import StringIO
+
+from sympy.utilities.decorator import deprecated
+
+
+@deprecated(
+    """
+    The sympy.utilities.pkgdata module and its get_resource function are
+    deprecated. Use the stdlib importlib.resources module instead.
+    """,
+    deprecated_since_version="1.12",
+    active_deprecations_target="pkgdata",
+)
+def get_resource(identifier, pkgname=__name__):
+
+    mod = sys.modules[pkgname]
+    fn = getattr(mod, '__file__', None)
+    if fn is None:
+        raise OSError("%r has no __file__!")
+    path = os.path.join(os.path.dirname(fn), identifier)
+    loader = getattr(mod, '__loader__', None)
+    if loader is not None:
+        try:
+            data = loader.get_data(path)
+        except (OSError, AttributeError):
+            pass
+        else:
+            return StringIO(data.decode('utf-8'))
+    return open(os.path.normpath(path), 'rb')
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/pytest.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/pytest.py
new file mode 100644
index 0000000000000000000000000000000000000000..75494c8e987c7b89bddf18febe09fdc3df2b194e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/pytest.py
@@ -0,0 +1,12 @@
+"""
+.. deprecated:: 1.6
+
+   sympy.utilities.pytest has been renamed to sympy.testing.pytest.
+"""
+from sympy.utilities.exceptions import sympy_deprecation_warning
+
+sympy_deprecation_warning("The sympy.utilities.pytest submodule is deprecated. Use sympy.testing.pytest instead.",
+    deprecated_since_version="1.6",
+    active_deprecations_target="deprecated-sympy-utilities-submodules")
+
+from sympy.testing.pytest import *  # noqa:F401,F403
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/randtest.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/randtest.py
new file mode 100644
index 0000000000000000000000000000000000000000..1bd3472ed8a89198d9e78e125f16dae1a56f6bad
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/randtest.py
@@ -0,0 +1,12 @@
+"""
+.. deprecated:: 1.6
+
+   sympy.utilities.randtest has been renamed to sympy.core.random.
+"""
+from sympy.utilities.exceptions import sympy_deprecation_warning
+
+sympy_deprecation_warning("The sympy.utilities.randtest submodule is deprecated. Use sympy.core.random instead.",
+    deprecated_since_version="1.6",
+    active_deprecations_target="deprecated-sympy-utilities-submodules")
+
+from sympy.core.random import *  # noqa:F401,F403
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/runtests.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/runtests.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb9f760f070be528e8cd51ab38e00bc944dda9ac
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/runtests.py
@@ -0,0 +1,13 @@
+"""
+.. deprecated:: 1.6
+
+   sympy.utilities.runtests has been renamed to sympy.testing.runtests.
+"""
+
+from sympy.utilities.exceptions import sympy_deprecation_warning
+
+sympy_deprecation_warning("The sympy.utilities.runtests submodule is deprecated. Use sympy.testing.runtests instead.",
+    deprecated_since_version="1.6",
+    active_deprecations_target="deprecated-sympy-utilities-submodules")
+
+from sympy.testing.runtests import * # noqa: F401,F403
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/source.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/source.py
new file mode 100644
index 0000000000000000000000000000000000000000..71692b4aaad07df70b63d7e1eaa86c402ad03c4f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/source.py
@@ -0,0 +1,40 @@
+"""
+This module adds several functions for interactive source code inspection.
+"""
+
+
+def get_class(lookup_view):
+    """
+    Convert a string version of a class name to the object.
+
+    For example, get_class('sympy.core.Basic') will return
+    class Basic located in module sympy.core
+    """
+    if isinstance(lookup_view, str):
+        mod_name, func_name = get_mod_func(lookup_view)
+        if func_name != '':
+            lookup_view = getattr(
+                __import__(mod_name, {}, {}, ['*']), func_name)
+            if not callable(lookup_view):
+                raise AttributeError(
+                    "'%s.%s' is not a callable." % (mod_name, func_name))
+    return lookup_view
+
+
+def get_mod_func(callback):
+    """
+    splits the string path to a class into a string path to the module
+    and the name of the class.
+
+    Examples
+    ========
+
+    >>> from sympy.utilities.source import get_mod_func
+    >>> get_mod_func('sympy.core.basic.Basic')
+    ('sympy.core.basic', 'Basic')
+
+    """
+    dot = callback.rfind('.')
+    if dot == -1:
+        return callback, ''
+    return callback[:dot], callback[dot + 1:]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_autowrap.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_autowrap.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5a33d77adb46710cfa3cfeb1ea39402e35c76cf
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_autowrap.py
@@ -0,0 +1,467 @@
+# Tests that require installed backends go into
+# sympy/test_external/test_autowrap
+
+import os
+import tempfile
+import shutil
+from io import StringIO
+from pathlib import Path
+
+from sympy.core import symbols, Eq
+from sympy.utilities.autowrap import (autowrap, binary_function,
+            CythonCodeWrapper, UfuncifyCodeWrapper, CodeWrapper)
+from sympy.utilities.codegen import (
+    CCodeGen, C99CodeGen, CodeGenArgumentListError, make_routine
+)
+from sympy.testing.pytest import raises
+from sympy.testing.tmpfiles import TmpFileManager
+
+
+def get_string(dump_fn, routines, prefix="file", **kwargs):
+    """Wrapper for dump_fn. dump_fn writes its results to a stream object and
+       this wrapper returns the contents of that stream as a string. This
+       auxiliary function is used by many tests below.
+
+       The header and the empty lines are not generator to facilitate the
+       testing of the output.
+    """
+    output = StringIO()
+    dump_fn(routines, output, prefix, **kwargs)
+    source = output.getvalue()
+    output.close()
+    return source
+
+
+def test_cython_wrapper_scalar_function():
+    x, y, z = symbols('x,y,z')
+    expr = (x + y)*z
+    routine = make_routine("test", expr)
+    code_gen = CythonCodeWrapper(CCodeGen())
+    source = get_string(code_gen.dump_pyx, [routine])
+
+    expected = (
+        "cdef extern from 'file.h':\n"
+        "    double test(double x, double y, double z)\n"
+        "\n"
+        "def test_c(double x, double y, double z):\n"
+        "\n"
+        "    return test(x, y, z)")
+    assert source == expected
+
+
+def test_cython_wrapper_outarg():
+    from sympy.core.relational import Equality
+    x, y, z = symbols('x,y,z')
+    code_gen = CythonCodeWrapper(C99CodeGen())
+
+    routine = make_routine("test", Equality(z, x + y))
+    source = get_string(code_gen.dump_pyx, [routine])
+    expected = (
+        "cdef extern from 'file.h':\n"
+        "    void test(double x, double y, double *z)\n"
+        "\n"
+        "def test_c(double x, double y):\n"
+        "\n"
+        "    cdef double z = 0\n"
+        "    test(x, y, &z)\n"
+        "    return z")
+    assert source == expected
+
+
+def test_cython_wrapper_inoutarg():
+    from sympy.core.relational import Equality
+    x, y, z = symbols('x,y,z')
+    code_gen = CythonCodeWrapper(C99CodeGen())
+    routine = make_routine("test", Equality(z, x + y + z))
+    source = get_string(code_gen.dump_pyx, [routine])
+    expected = (
+        "cdef extern from 'file.h':\n"
+        "    void test(double x, double y, double *z)\n"
+        "\n"
+        "def test_c(double x, double y, double z):\n"
+        "\n"
+        "    test(x, y, &z)\n"
+        "    return z")
+    assert source == expected
+
+
+def test_cython_wrapper_compile_flags():
+    from sympy.core.relational import Equality
+    x, y, z = symbols('x,y,z')
+    routine = make_routine("test", Equality(z, x + y))
+
+    code_gen = CythonCodeWrapper(CCodeGen())
+
+    expected = """\
+from setuptools import setup
+from setuptools import Extension
+from Cython.Build import cythonize
+cy_opts = {'compiler_directives': {'language_level': '3'}}
+
+ext_mods = [Extension(
+    'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'],
+    include_dirs=[],
+    library_dirs=[],
+    libraries=[],
+    extra_compile_args=['-std=c99'],
+    extra_link_args=[]
+)]
+setup(ext_modules=cythonize(ext_mods, **cy_opts))
+""" % {'num': CodeWrapper._module_counter}
+
+    temp_dir = tempfile.mkdtemp()
+    TmpFileManager.tmp_folder(temp_dir)
+    setup_file_path = os.path.join(temp_dir, 'setup.py')
+
+    code_gen._prepare_files(routine, build_dir=temp_dir)
+    setup_text = Path(setup_file_path).read_text()
+    assert setup_text == expected
+
+    code_gen = CythonCodeWrapper(CCodeGen(),
+                                 include_dirs=['/usr/local/include', '/opt/booger/include'],
+                                 library_dirs=['/user/local/lib'],
+                                 libraries=['thelib', 'nilib'],
+                                 extra_compile_args=['-slow-math'],
+                                 extra_link_args=['-lswamp', '-ltrident'],
+                                 cythonize_options={'compiler_directives': {'boundscheck': False}}
+                                 )
+    expected = """\
+from setuptools import setup
+from setuptools import Extension
+from Cython.Build import cythonize
+cy_opts = {'compiler_directives': {'boundscheck': False}}
+
+ext_mods = [Extension(
+    'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'],
+    include_dirs=['/usr/local/include', '/opt/booger/include'],
+    library_dirs=['/user/local/lib'],
+    libraries=['thelib', 'nilib'],
+    extra_compile_args=['-slow-math', '-std=c99'],
+    extra_link_args=['-lswamp', '-ltrident']
+)]
+setup(ext_modules=cythonize(ext_mods, **cy_opts))
+""" % {'num': CodeWrapper._module_counter}
+
+    code_gen._prepare_files(routine, build_dir=temp_dir)
+    setup_text = Path(setup_file_path).read_text()
+    assert setup_text == expected
+
+    expected = """\
+from setuptools import setup
+from setuptools import Extension
+from Cython.Build import cythonize
+cy_opts = {'compiler_directives': {'boundscheck': False}}
+import numpy as np
+
+ext_mods = [Extension(
+    'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'],
+    include_dirs=['/usr/local/include', '/opt/booger/include', np.get_include()],
+    library_dirs=['/user/local/lib'],
+    libraries=['thelib', 'nilib'],
+    extra_compile_args=['-slow-math', '-std=c99'],
+    extra_link_args=['-lswamp', '-ltrident']
+)]
+setup(ext_modules=cythonize(ext_mods, **cy_opts))
+""" % {'num': CodeWrapper._module_counter}
+
+    code_gen._need_numpy = True
+    code_gen._prepare_files(routine, build_dir=temp_dir)
+    setup_text = Path(setup_file_path).read_text()
+    assert setup_text == expected
+
+    TmpFileManager.cleanup()
+
+def test_cython_wrapper_unique_dummyvars():
+    from sympy.core.relational import Equality
+    from sympy.core.symbol import Dummy
+    x, y, z = Dummy('x'), Dummy('y'), Dummy('z')
+    x_id, y_id, z_id = [str(d.dummy_index) for d in [x, y, z]]
+    expr = Equality(z, x + y)
+    routine = make_routine("test", expr)
+    code_gen = CythonCodeWrapper(CCodeGen())
+    source = get_string(code_gen.dump_pyx, [routine])
+    expected_template = (
+        "cdef extern from 'file.h':\n"
+        "    void test(double x_{x_id}, double y_{y_id}, double *z_{z_id})\n"
+        "\n"
+        "def test_c(double x_{x_id}, double y_{y_id}):\n"
+        "\n"
+        "    cdef double z_{z_id} = 0\n"
+        "    test(x_{x_id}, y_{y_id}, &z_{z_id})\n"
+        "    return z_{z_id}")
+    expected = expected_template.format(x_id=x_id, y_id=y_id, z_id=z_id)
+    assert source == expected
+
+def test_autowrap_dummy():
+    x, y, z = symbols('x y z')
+
+    # Uses DummyWrapper to test that codegen works as expected
+
+    f = autowrap(x + y, backend='dummy')
+    assert f() == str(x + y)
+    assert f.args == "x, y"
+    assert f.returns == "nameless"
+    f = autowrap(Eq(z, x + y), backend='dummy')
+    assert f() == str(x + y)
+    assert f.args == "x, y"
+    assert f.returns == "z"
+    f = autowrap(Eq(z, x + y + z), backend='dummy')
+    assert f() == str(x + y + z)
+    assert f.args == "x, y, z"
+    assert f.returns == "z"
+
+
+def test_autowrap_args():
+    x, y, z = symbols('x y z')
+
+    raises(CodeGenArgumentListError, lambda: autowrap(Eq(z, x + y),
+           backend='dummy', args=[x]))
+    f = autowrap(Eq(z, x + y), backend='dummy', args=[y, x])
+    assert f() == str(x + y)
+    assert f.args == "y, x"
+    assert f.returns == "z"
+
+    raises(CodeGenArgumentListError, lambda: autowrap(Eq(z, x + y + z),
+           backend='dummy', args=[x, y]))
+    f = autowrap(Eq(z, x + y + z), backend='dummy', args=[y, x, z])
+    assert f() == str(x + y + z)
+    assert f.args == "y, x, z"
+    assert f.returns == "z"
+
+    f = autowrap(Eq(z, x + y + z), backend='dummy', args=(y, x, z))
+    assert f() == str(x + y + z)
+    assert f.args == "y, x, z"
+    assert f.returns == "z"
+
+def test_autowrap_store_files():
+    x, y = symbols('x y')
+    tmp = tempfile.mkdtemp()
+    TmpFileManager.tmp_folder(tmp)
+
+    f = autowrap(x + y, backend='dummy', tempdir=tmp)
+    assert f() == str(x + y)
+    assert os.access(tmp, os.F_OK)
+
+    TmpFileManager.cleanup()
+
+def test_autowrap_store_files_issue_gh12939():
+    x, y = symbols('x y')
+    tmp = './tmp'
+    saved_cwd = os.getcwd()
+    temp_cwd = tempfile.mkdtemp()
+    try:
+        os.chdir(temp_cwd)
+        f = autowrap(x + y, backend='dummy', tempdir=tmp)
+        assert f() == str(x + y)
+        assert os.access(tmp, os.F_OK)
+    finally:
+        os.chdir(saved_cwd)
+        shutil.rmtree(temp_cwd)
+
+
+def test_binary_function():
+    x, y = symbols('x y')
+    f = binary_function('f', x + y, backend='dummy')
+    assert f._imp_() == str(x + y)
+
+
+def test_ufuncify_source():
+    x, y, z = symbols('x,y,z')
+    code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify"))
+    routine = make_routine("test", x + y + z)
+    source = get_string(code_wrapper.dump_c, [routine])
+    expected = """\
+#include "Python.h"
+#include "math.h"
+#include "numpy/ndarraytypes.h"
+#include "numpy/ufuncobject.h"
+#include "numpy/halffloat.h"
+#include "file.h"
+
+static PyMethodDef wrapper_module_%(num)sMethods[] = {
+        {NULL, NULL, 0, NULL}
+};
+
+#ifdef NPY_1_19_API_VERSION
+static void test_ufunc(char **args, const npy_intp *dimensions, const npy_intp* steps, void* data)
+#else
+static void test_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data)
+#endif
+{
+    npy_intp i;
+    npy_intp n = dimensions[0];
+    char *in0 = args[0];
+    char *in1 = args[1];
+    char *in2 = args[2];
+    char *out0 = args[3];
+    npy_intp in0_step = steps[0];
+    npy_intp in1_step = steps[1];
+    npy_intp in2_step = steps[2];
+    npy_intp out0_step = steps[3];
+    for (i = 0; i < n; i++) {
+        *((double *)out0) = test(*(double *)in0, *(double *)in1, *(double *)in2);
+        in0 += in0_step;
+        in1 += in1_step;
+        in2 += in2_step;
+        out0 += out0_step;
+    }
+}
+PyUFuncGenericFunction test_funcs[1] = {&test_ufunc};
+static char test_types[4] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE};
+static void *test_data[1] = {NULL};
+
+#if PY_VERSION_HEX >= 0x03000000
+static struct PyModuleDef moduledef = {
+    PyModuleDef_HEAD_INIT,
+    "wrapper_module_%(num)s",
+    NULL,
+    -1,
+    wrapper_module_%(num)sMethods,
+    NULL,
+    NULL,
+    NULL,
+    NULL
+};
+
+PyMODINIT_FUNC PyInit_wrapper_module_%(num)s(void)
+{
+    PyObject *m, *d;
+    PyObject *ufunc0;
+    m = PyModule_Create(&moduledef);
+    if (!m) {
+        return NULL;
+    }
+    import_array();
+    import_umath();
+    d = PyModule_GetDict(m);
+    ufunc0 = PyUFunc_FromFuncAndData(test_funcs, test_data, test_types, 1, 3, 1,
+            PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0);
+    PyDict_SetItemString(d, "test", ufunc0);
+    Py_DECREF(ufunc0);
+    return m;
+}
+#else
+PyMODINIT_FUNC initwrapper_module_%(num)s(void)
+{
+    PyObject *m, *d;
+    PyObject *ufunc0;
+    m = Py_InitModule("wrapper_module_%(num)s", wrapper_module_%(num)sMethods);
+    if (m == NULL) {
+        return;
+    }
+    import_array();
+    import_umath();
+    d = PyModule_GetDict(m);
+    ufunc0 = PyUFunc_FromFuncAndData(test_funcs, test_data, test_types, 1, 3, 1,
+            PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0);
+    PyDict_SetItemString(d, "test", ufunc0);
+    Py_DECREF(ufunc0);
+}
+#endif""" % {'num': CodeWrapper._module_counter}
+    assert source == expected
+
+
+def test_ufuncify_source_multioutput():
+    x, y, z = symbols('x,y,z')
+    var_symbols = (x, y, z)
+    expr = x + y**3 + 10*z**2
+    code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify"))
+    routines = [make_routine("func{}".format(i), expr.diff(var_symbols[i]), var_symbols) for i in range(len(var_symbols))]
+    source = get_string(code_wrapper.dump_c, routines, funcname='multitest')
+    expected = """\
+#include "Python.h"
+#include "math.h"
+#include "numpy/ndarraytypes.h"
+#include "numpy/ufuncobject.h"
+#include "numpy/halffloat.h"
+#include "file.h"
+
+static PyMethodDef wrapper_module_%(num)sMethods[] = {
+        {NULL, NULL, 0, NULL}
+};
+
+#ifdef NPY_1_19_API_VERSION
+static void multitest_ufunc(char **args, const npy_intp *dimensions, const npy_intp* steps, void* data)
+#else
+static void multitest_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data)
+#endif
+{
+    npy_intp i;
+    npy_intp n = dimensions[0];
+    char *in0 = args[0];
+    char *in1 = args[1];
+    char *in2 = args[2];
+    char *out0 = args[3];
+    char *out1 = args[4];
+    char *out2 = args[5];
+    npy_intp in0_step = steps[0];
+    npy_intp in1_step = steps[1];
+    npy_intp in2_step = steps[2];
+    npy_intp out0_step = steps[3];
+    npy_intp out1_step = steps[4];
+    npy_intp out2_step = steps[5];
+    for (i = 0; i < n; i++) {
+        *((double *)out0) = func0(*(double *)in0, *(double *)in1, *(double *)in2);
+        *((double *)out1) = func1(*(double *)in0, *(double *)in1, *(double *)in2);
+        *((double *)out2) = func2(*(double *)in0, *(double *)in1, *(double *)in2);
+        in0 += in0_step;
+        in1 += in1_step;
+        in2 += in2_step;
+        out0 += out0_step;
+        out1 += out1_step;
+        out2 += out2_step;
+    }
+}
+PyUFuncGenericFunction multitest_funcs[1] = {&multitest_ufunc};
+static char multitest_types[6] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE};
+static void *multitest_data[1] = {NULL};
+
+#if PY_VERSION_HEX >= 0x03000000
+static struct PyModuleDef moduledef = {
+    PyModuleDef_HEAD_INIT,
+    "wrapper_module_%(num)s",
+    NULL,
+    -1,
+    wrapper_module_%(num)sMethods,
+    NULL,
+    NULL,
+    NULL,
+    NULL
+};
+
+PyMODINIT_FUNC PyInit_wrapper_module_%(num)s(void)
+{
+    PyObject *m, *d;
+    PyObject *ufunc0;
+    m = PyModule_Create(&moduledef);
+    if (!m) {
+        return NULL;
+    }
+    import_array();
+    import_umath();
+    d = PyModule_GetDict(m);
+    ufunc0 = PyUFunc_FromFuncAndData(multitest_funcs, multitest_data, multitest_types, 1, 3, 3,
+            PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0);
+    PyDict_SetItemString(d, "multitest", ufunc0);
+    Py_DECREF(ufunc0);
+    return m;
+}
+#else
+PyMODINIT_FUNC initwrapper_module_%(num)s(void)
+{
+    PyObject *m, *d;
+    PyObject *ufunc0;
+    m = Py_InitModule("wrapper_module_%(num)s", wrapper_module_%(num)sMethods);
+    if (m == NULL) {
+        return;
+    }
+    import_array();
+    import_umath();
+    d = PyModule_GetDict(m);
+    ufunc0 = PyUFunc_FromFuncAndData(multitest_funcs, multitest_data, multitest_types, 1, 3, 3,
+            PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0);
+    PyDict_SetItemString(d, "multitest", ufunc0);
+    Py_DECREF(ufunc0);
+}
+#endif""" % {'num': CodeWrapper._module_counter}
+    assert source == expected
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_codegen.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_codegen.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ccc6f9a90fb0a0bec39cea22420da8091ede740
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_codegen.py
@@ -0,0 +1,1632 @@
+from io import StringIO
+
+from sympy.core import symbols, Eq, pi, Catalan, Lambda, Dummy
+from sympy.core.relational import Equality
+from sympy.core.symbol import Symbol
+from sympy.functions.special.error_functions import erf
+from sympy.integrals.integrals import Integral
+from sympy.matrices import Matrix, MatrixSymbol
+from sympy.utilities.codegen import (
+    codegen, make_routine, CCodeGen, C89CodeGen, C99CodeGen, InputArgument,
+    CodeGenError, FCodeGen, CodeGenArgumentListError, OutputArgument,
+    InOutArgument)
+from sympy.testing.pytest import raises
+from sympy.utilities.lambdify import implemented_function
+
+#FIXME: Fails due to circular import in with core
+# from sympy import codegen
+
+
+def get_string(dump_fn, routines, prefix="file", header=False, empty=False):
+    """Wrapper for dump_fn. dump_fn writes its results to a stream object and
+       this wrapper returns the contents of that stream as a string. This
+       auxiliary function is used by many tests below.
+
+       The header and the empty lines are not generated to facilitate the
+       testing of the output.
+    """
+    output = StringIO()
+    dump_fn(routines, output, prefix, header, empty)
+    source = output.getvalue()
+    output.close()
+    return source
+
+
+def test_Routine_argument_order():
+    a, x, y, z = symbols('a x y z')
+    expr = (x + y)*z
+    raises(CodeGenArgumentListError, lambda: make_routine("test", expr,
+           argument_sequence=[z, x]))
+    raises(CodeGenArgumentListError, lambda: make_routine("test", Eq(a,
+           expr), argument_sequence=[z, x, y]))
+    r = make_routine('test', Eq(a, expr), argument_sequence=[z, x, a, y])
+    assert [ arg.name for arg in r.arguments ] == [z, x, a, y]
+    assert [ type(arg) for arg in r.arguments ] == [
+        InputArgument, InputArgument, OutputArgument, InputArgument  ]
+    r = make_routine('test', Eq(z, expr), argument_sequence=[z, x, y])
+    assert [ type(arg) for arg in r.arguments ] == [
+        InOutArgument, InputArgument, InputArgument ]
+
+    from sympy.tensor import IndexedBase, Idx
+    A, B = map(IndexedBase, ['A', 'B'])
+    m = symbols('m', integer=True)
+    i = Idx('i', m)
+    r = make_routine('test', Eq(A[i], B[i]), argument_sequence=[B, A, m])
+    assert [ arg.name for arg in r.arguments ] == [B.label, A.label, m]
+
+    expr = Integral(x*y*z, (x, 1, 2), (y, 1, 3))
+    r = make_routine('test', Eq(a, expr), argument_sequence=[z, x, a, y])
+    assert [ arg.name for arg in r.arguments ] == [z, x, a, y]
+
+
+def test_empty_c_code():
+    code_gen = C89CodeGen()
+    source = get_string(code_gen.dump_c, [])
+    assert source == "#include \"file.h\"\n#include \n"
+
+
+def test_empty_c_code_with_comment():
+    code_gen = C89CodeGen()
+    source = get_string(code_gen.dump_c, [], header=True)
+    assert source[:82] == (
+        "/******************************************************************************\n *"
+    )
+          #   "                    Code generated with SymPy 0.7.2-git                    "
+    assert source[158:] == (                                                              "*\n"
+            " *                                                                            *\n"
+            " *              See http://www.sympy.org/ for more information.               *\n"
+            " *                                                                            *\n"
+            " *                       This file is part of 'project'                       *\n"
+            " ******************************************************************************/\n"
+            "#include \"file.h\"\n"
+            "#include \n"
+            )
+
+
+def test_empty_c_header():
+    code_gen = C99CodeGen()
+    source = get_string(code_gen.dump_h, [])
+    assert source == "#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n#endif\n"
+
+
+def test_simple_c_code():
+    x, y, z = symbols('x,y,z')
+    expr = (x + y)*z
+    routine = make_routine("test", expr)
+    code_gen = C89CodeGen()
+    source = get_string(code_gen.dump_c, [routine])
+    expected = (
+        "#include \"file.h\"\n"
+        "#include \n"
+        "double test(double x, double y, double z) {\n"
+        "   double test_result;\n"
+        "   test_result = z*(x + y);\n"
+        "   return test_result;\n"
+        "}\n"
+    )
+    assert source == expected
+
+
+def test_c_code_reserved_words():
+    x, y, z = symbols('if, typedef, while')
+    expr = (x + y) * z
+    routine = make_routine("test", expr)
+    code_gen = C99CodeGen()
+    source = get_string(code_gen.dump_c, [routine])
+    expected = (
+        "#include \"file.h\"\n"
+        "#include \n"
+        "double test(double if_, double typedef_, double while_) {\n"
+        "   double test_result;\n"
+        "   test_result = while_*(if_ + typedef_);\n"
+        "   return test_result;\n"
+        "}\n"
+    )
+    assert source == expected
+
+
+def test_numbersymbol_c_code():
+    routine = make_routine("test", pi**Catalan)
+    code_gen = C89CodeGen()
+    source = get_string(code_gen.dump_c, [routine])
+    expected = (
+        "#include \"file.h\"\n"
+        "#include \n"
+        "double test() {\n"
+        "   double test_result;\n"
+        "   double const Catalan = %s;\n"
+        "   test_result = pow(M_PI, Catalan);\n"
+        "   return test_result;\n"
+        "}\n"
+    ) % Catalan.evalf(17)
+    assert source == expected
+
+
+def test_c_code_argument_order():
+    x, y, z = symbols('x,y,z')
+    expr = x + y
+    routine = make_routine("test", expr, argument_sequence=[z, x, y])
+    code_gen = C89CodeGen()
+    source = get_string(code_gen.dump_c, [routine])
+    expected = (
+        "#include \"file.h\"\n"
+        "#include \n"
+        "double test(double z, double x, double y) {\n"
+        "   double test_result;\n"
+        "   test_result = x + y;\n"
+        "   return test_result;\n"
+        "}\n"
+    )
+    assert source == expected
+
+
+def test_simple_c_header():
+    x, y, z = symbols('x,y,z')
+    expr = (x + y)*z
+    routine = make_routine("test", expr)
+    code_gen = C89CodeGen()
+    source = get_string(code_gen.dump_h, [routine])
+    expected = (
+        "#ifndef PROJECT__FILE__H\n"
+        "#define PROJECT__FILE__H\n"
+        "double test(double x, double y, double z);\n"
+        "#endif\n"
+    )
+    assert source == expected
+
+
+def test_simple_c_codegen():
+    x, y, z = symbols('x,y,z')
+    expr = (x + y)*z
+    expected = [
+        ("file.c",
+        "#include \"file.h\"\n"
+        "#include \n"
+        "double test(double x, double y, double z) {\n"
+        "   double test_result;\n"
+        "   test_result = z*(x + y);\n"
+        "   return test_result;\n"
+        "}\n"),
+        ("file.h",
+        "#ifndef PROJECT__FILE__H\n"
+        "#define PROJECT__FILE__H\n"
+        "double test(double x, double y, double z);\n"
+        "#endif\n")
+    ]
+    result = codegen(("test", expr), "C", "file", header=False, empty=False)
+    assert result == expected
+
+
+def test_multiple_results_c():
+    x, y, z = symbols('x,y,z')
+    expr1 = (x + y)*z
+    expr2 = (x - y)*z
+    routine = make_routine(
+        "test",
+        [expr1, expr2]
+    )
+    code_gen = C99CodeGen()
+    raises(CodeGenError, lambda: get_string(code_gen.dump_h, [routine]))
+
+
+def test_no_results_c():
+    raises(ValueError, lambda: make_routine("test", []))
+
+
+def test_ansi_math1_codegen():
+    # not included: log10
+    from sympy.functions.elementary.complexes import Abs
+    from sympy.functions.elementary.exponential import log
+    from sympy.functions.elementary.hyperbolic import (cosh, sinh, tanh)
+    from sympy.functions.elementary.integers import (ceiling, floor)
+    from sympy.functions.elementary.miscellaneous import sqrt
+    from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, tan)
+    x = symbols('x')
+    name_expr = [
+        ("test_fabs", Abs(x)),
+        ("test_acos", acos(x)),
+        ("test_asin", asin(x)),
+        ("test_atan", atan(x)),
+        ("test_ceil", ceiling(x)),
+        ("test_cos", cos(x)),
+        ("test_cosh", cosh(x)),
+        ("test_floor", floor(x)),
+        ("test_log", log(x)),
+        ("test_ln", log(x)),
+        ("test_sin", sin(x)),
+        ("test_sinh", sinh(x)),
+        ("test_sqrt", sqrt(x)),
+        ("test_tan", tan(x)),
+        ("test_tanh", tanh(x)),
+    ]
+    result = codegen(name_expr, "C89", "file", header=False, empty=False)
+    assert result[0][0] == "file.c"
+    assert result[0][1] == (
+        '#include "file.h"\n#include \n'
+        'double test_fabs(double x) {\n   double test_fabs_result;\n   test_fabs_result = fabs(x);\n   return test_fabs_result;\n}\n'
+        'double test_acos(double x) {\n   double test_acos_result;\n   test_acos_result = acos(x);\n   return test_acos_result;\n}\n'
+        'double test_asin(double x) {\n   double test_asin_result;\n   test_asin_result = asin(x);\n   return test_asin_result;\n}\n'
+        'double test_atan(double x) {\n   double test_atan_result;\n   test_atan_result = atan(x);\n   return test_atan_result;\n}\n'
+        'double test_ceil(double x) {\n   double test_ceil_result;\n   test_ceil_result = ceil(x);\n   return test_ceil_result;\n}\n'
+        'double test_cos(double x) {\n   double test_cos_result;\n   test_cos_result = cos(x);\n   return test_cos_result;\n}\n'
+        'double test_cosh(double x) {\n   double test_cosh_result;\n   test_cosh_result = cosh(x);\n   return test_cosh_result;\n}\n'
+        'double test_floor(double x) {\n   double test_floor_result;\n   test_floor_result = floor(x);\n   return test_floor_result;\n}\n'
+        'double test_log(double x) {\n   double test_log_result;\n   test_log_result = log(x);\n   return test_log_result;\n}\n'
+        'double test_ln(double x) {\n   double test_ln_result;\n   test_ln_result = log(x);\n   return test_ln_result;\n}\n'
+        'double test_sin(double x) {\n   double test_sin_result;\n   test_sin_result = sin(x);\n   return test_sin_result;\n}\n'
+        'double test_sinh(double x) {\n   double test_sinh_result;\n   test_sinh_result = sinh(x);\n   return test_sinh_result;\n}\n'
+        'double test_sqrt(double x) {\n   double test_sqrt_result;\n   test_sqrt_result = sqrt(x);\n   return test_sqrt_result;\n}\n'
+        'double test_tan(double x) {\n   double test_tan_result;\n   test_tan_result = tan(x);\n   return test_tan_result;\n}\n'
+        'double test_tanh(double x) {\n   double test_tanh_result;\n   test_tanh_result = tanh(x);\n   return test_tanh_result;\n}\n'
+    )
+    assert result[1][0] == "file.h"
+    assert result[1][1] == (
+        '#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n'
+        'double test_fabs(double x);\ndouble test_acos(double x);\n'
+        'double test_asin(double x);\ndouble test_atan(double x);\n'
+        'double test_ceil(double x);\ndouble test_cos(double x);\n'
+        'double test_cosh(double x);\ndouble test_floor(double x);\n'
+        'double test_log(double x);\ndouble test_ln(double x);\n'
+        'double test_sin(double x);\ndouble test_sinh(double x);\n'
+        'double test_sqrt(double x);\ndouble test_tan(double x);\n'
+        'double test_tanh(double x);\n#endif\n'
+    )
+
+
+def test_ansi_math2_codegen():
+    # not included: frexp, ldexp, modf, fmod
+    from sympy.functions.elementary.trigonometric import atan2
+    x, y = symbols('x,y')
+    name_expr = [
+        ("test_atan2", atan2(x, y)),
+        ("test_pow", x**y),
+    ]
+    result = codegen(name_expr, "C89", "file", header=False, empty=False)
+    assert result[0][0] == "file.c"
+    assert result[0][1] == (
+        '#include "file.h"\n#include \n'
+        'double test_atan2(double x, double y) {\n   double test_atan2_result;\n   test_atan2_result = atan2(x, y);\n   return test_atan2_result;\n}\n'
+        'double test_pow(double x, double y) {\n   double test_pow_result;\n   test_pow_result = pow(x, y);\n   return test_pow_result;\n}\n'
+    )
+    assert result[1][0] == "file.h"
+    assert result[1][1] == (
+        '#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n'
+        'double test_atan2(double x, double y);\n'
+        'double test_pow(double x, double y);\n'
+        '#endif\n'
+    )
+
+
+def test_complicated_codegen():
+    from sympy.functions.elementary.trigonometric import (cos, sin, tan)
+    x, y, z = symbols('x,y,z')
+    name_expr = [
+        ("test1", ((sin(x) + cos(y) + tan(z))**7).expand()),
+        ("test2", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))),
+    ]
+    result = codegen(name_expr, "C89", "file", header=False, empty=False)
+    assert result[0][0] == "file.c"
+    assert result[0][1] == (
+        '#include "file.h"\n#include \n'
+        'double test1(double x, double y, double z) {\n'
+        '   double test1_result;\n'
+        '   test1_result = '
+        'pow(sin(x), 7) + '
+        '7*pow(sin(x), 6)*cos(y) + '
+        '7*pow(sin(x), 6)*tan(z) + '
+        '21*pow(sin(x), 5)*pow(cos(y), 2) + '
+        '42*pow(sin(x), 5)*cos(y)*tan(z) + '
+        '21*pow(sin(x), 5)*pow(tan(z), 2) + '
+        '35*pow(sin(x), 4)*pow(cos(y), 3) + '
+        '105*pow(sin(x), 4)*pow(cos(y), 2)*tan(z) + '
+        '105*pow(sin(x), 4)*cos(y)*pow(tan(z), 2) + '
+        '35*pow(sin(x), 4)*pow(tan(z), 3) + '
+        '35*pow(sin(x), 3)*pow(cos(y), 4) + '
+        '140*pow(sin(x), 3)*pow(cos(y), 3)*tan(z) + '
+        '210*pow(sin(x), 3)*pow(cos(y), 2)*pow(tan(z), 2) + '
+        '140*pow(sin(x), 3)*cos(y)*pow(tan(z), 3) + '
+        '35*pow(sin(x), 3)*pow(tan(z), 4) + '
+        '21*pow(sin(x), 2)*pow(cos(y), 5) + '
+        '105*pow(sin(x), 2)*pow(cos(y), 4)*tan(z) + '
+        '210*pow(sin(x), 2)*pow(cos(y), 3)*pow(tan(z), 2) + '
+        '210*pow(sin(x), 2)*pow(cos(y), 2)*pow(tan(z), 3) + '
+        '105*pow(sin(x), 2)*cos(y)*pow(tan(z), 4) + '
+        '21*pow(sin(x), 2)*pow(tan(z), 5) + '
+        '7*sin(x)*pow(cos(y), 6) + '
+        '42*sin(x)*pow(cos(y), 5)*tan(z) + '
+        '105*sin(x)*pow(cos(y), 4)*pow(tan(z), 2) + '
+        '140*sin(x)*pow(cos(y), 3)*pow(tan(z), 3) + '
+        '105*sin(x)*pow(cos(y), 2)*pow(tan(z), 4) + '
+        '42*sin(x)*cos(y)*pow(tan(z), 5) + '
+        '7*sin(x)*pow(tan(z), 6) + '
+        'pow(cos(y), 7) + '
+        '7*pow(cos(y), 6)*tan(z) + '
+        '21*pow(cos(y), 5)*pow(tan(z), 2) + '
+        '35*pow(cos(y), 4)*pow(tan(z), 3) + '
+        '35*pow(cos(y), 3)*pow(tan(z), 4) + '
+        '21*pow(cos(y), 2)*pow(tan(z), 5) + '
+        '7*cos(y)*pow(tan(z), 6) + '
+        'pow(tan(z), 7);\n'
+        '   return test1_result;\n'
+        '}\n'
+        'double test2(double x, double y, double z) {\n'
+        '   double test2_result;\n'
+        '   test2_result = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))));\n'
+        '   return test2_result;\n'
+        '}\n'
+    )
+    assert result[1][0] == "file.h"
+    assert result[1][1] == (
+        '#ifndef PROJECT__FILE__H\n'
+        '#define PROJECT__FILE__H\n'
+        'double test1(double x, double y, double z);\n'
+        'double test2(double x, double y, double z);\n'
+        '#endif\n'
+    )
+
+
+def test_loops_c():
+    from sympy.tensor import IndexedBase, Idx
+    from sympy.core.symbol import symbols
+    n, m = symbols('n m', integer=True)
+    A = IndexedBase('A')
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i = Idx('i', m)
+    j = Idx('j', n)
+
+    (f1, code), (f2, interface) = codegen(
+        ('matrix_vector', Eq(y[i], A[i, j]*x[j])), "C99", "file", header=False, empty=False)
+
+    assert f1 == 'file.c'
+    expected = (
+        '#include "file.h"\n'
+        '#include \n'
+        'void matrix_vector(double *A, int m, int n, double *x, double *y) {\n'
+        '   for (int i=0; i\n'
+        'void test_dummies(int m_%(mno)i, double *x, double *y) {\n'
+        '   for (int i_%(ino)i=0; i_%(ino)i\n'
+        'void matrix_vector(double *A, int m, int n, int o, int p, double *x, double *y) {\n'
+        '   for (int i=o; i<%(upperi)s; i++){\n'
+        '      y[i] = 0;\n'
+        '   }\n'
+        '   for (int i=o; i<%(upperi)s; i++){\n'
+        '      for (int j=0; j\n'
+        'double foo(double x, double *y) {\n'
+        '   (*y) = sin(x);\n'
+        '   double foo_result;\n'
+        '   foo_result = cos(x);\n'
+        '   return foo_result;\n'
+        '}\n'
+    )
+    assert result[0][1] == expected
+
+
+def test_output_arg_c_reserved_words():
+    from sympy.core.relational import Equality
+    from sympy.functions.elementary.trigonometric import (cos, sin)
+    x, y, z = symbols("if, while, z")
+    r = make_routine("foo", [Equality(y, sin(x)), cos(x)])
+    c = C89CodeGen()
+    result = c.write([r], "test", header=False, empty=False)
+    assert result[0][0] == "test.c"
+    expected = (
+        '#include "test.h"\n'
+        '#include \n'
+        'double foo(double if_, double *while_) {\n'
+        '   (*while_) = sin(if_);\n'
+        '   double foo_result;\n'
+        '   foo_result = cos(if_);\n'
+        '   return foo_result;\n'
+        '}\n'
+    )
+    assert result[0][1] == expected
+
+
+def test_multidim_c_argument_cse():
+    A_sym = MatrixSymbol('A', 3, 3)
+    b_sym = MatrixSymbol('b', 3, 1)
+    A = Matrix(A_sym)
+    b = Matrix(b_sym)
+    c = A*b
+    cgen = CCodeGen(project="test", cse=True)
+    r = cgen.routine("c", c)
+    r.arguments[-1].result_var = "out"
+    r.arguments[-1]._name = "out"
+    code = get_string(cgen.dump_c, [r], prefix="test")
+    expected = (
+        '#include "test.h"\n'
+        "#include \n"
+        "void c(double *A, double *b, double *out) {\n"
+        "   out[0] = A[0]*b[0] + A[1]*b[1] + A[2]*b[2];\n"
+        "   out[1] = A[3]*b[0] + A[4]*b[1] + A[5]*b[2];\n"
+        "   out[2] = A[6]*b[0] + A[7]*b[1] + A[8]*b[2];\n"
+        "}\n"
+    )
+    assert code == expected
+
+
+def test_ccode_results_named_ordered():
+    x, y, z = symbols('x,y,z')
+    B, C = symbols('B,C')
+    A = MatrixSymbol('A', 1, 3)
+    expr1 = Equality(A, Matrix([[1, 2, x]]))
+    expr2 = Equality(C, (x + y)*z)
+    expr3 = Equality(B, 2*x)
+    name_expr = ("test", [expr1, expr2, expr3])
+    expected = (
+        '#include "test.h"\n'
+        '#include \n'
+        'void test(double x, double *C, double z, double y, double *A, double *B) {\n'
+        '   (*C) = z*(x + y);\n'
+        '   A[0] = 1;\n'
+        '   A[1] = 2;\n'
+        '   A[2] = x;\n'
+        '   (*B) = 2*x;\n'
+        '}\n'
+    )
+
+    result = codegen(name_expr, "c", "test", header=False, empty=False,
+                     argument_sequence=(x, C, z, y, A, B))
+    source = result[0][1]
+    assert source == expected
+
+
+def test_ccode_matrixsymbol_slice():
+    A = MatrixSymbol('A', 5, 3)
+    B = MatrixSymbol('B', 1, 3)
+    C = MatrixSymbol('C', 1, 3)
+    D = MatrixSymbol('D', 5, 1)
+    name_expr = ("test", [Equality(B, A[0, :]),
+                          Equality(C, A[1, :]),
+                          Equality(D, A[:, 2])])
+    result = codegen(name_expr, "c99", "test", header=False, empty=False)
+    source = result[0][1]
+    expected = (
+        '#include "test.h"\n'
+        '#include \n'
+        'void test(double *A, double *B, double *C, double *D) {\n'
+        '   B[0] = A[0];\n'
+        '   B[1] = A[1];\n'
+        '   B[2] = A[2];\n'
+        '   C[0] = A[3];\n'
+        '   C[1] = A[4];\n'
+        '   C[2] = A[5];\n'
+        '   D[0] = A[2];\n'
+        '   D[1] = A[5];\n'
+        '   D[2] = A[8];\n'
+        '   D[3] = A[11];\n'
+        '   D[4] = A[14];\n'
+        '}\n'
+    )
+    assert source == expected
+
+def test_ccode_cse():
+    a, b, c, d = symbols('a b c d')
+    e = MatrixSymbol('e', 3, 1)
+    name_expr = ("test", [Equality(e, Matrix([[a*b], [a*b + c*d], [a*b*c*d]]))])
+    generator = CCodeGen(cse=True)
+    result = codegen(name_expr, code_gen=generator, header=False, empty=False)
+    source = result[0][1]
+    expected = (
+        '#include "test.h"\n'
+        '#include \n'
+        'void test(double a, double b, double c, double d, double *e) {\n'
+        '   const double x0 = a*b;\n'
+        '   const double x1 = c*d;\n'
+        '   e[0] = x0;\n'
+        '   e[1] = x0 + x1;\n'
+        '   e[2] = x0*x1;\n'
+        '}\n'
+    )
+    assert source == expected
+
+def test_ccode_unused_array_arg():
+    x = MatrixSymbol('x', 2, 1)
+    # x does not appear in output
+    name_expr = ("test", 1.0)
+    generator = CCodeGen()
+    result = codegen(name_expr, code_gen=generator, header=False, empty=False, argument_sequence=(x,))
+    source = result[0][1]
+    # note: x should appear as (double *)
+    expected = (
+        '#include "test.h"\n'
+        '#include \n'
+        'double test(double *x) {\n'
+        '   double test_result;\n'
+        '   test_result = 1.0;\n'
+        '   return test_result;\n'
+        '}\n'
+    )
+    assert source == expected
+
+def test_ccode_unused_array_arg_func():
+    # issue 16689
+    X = MatrixSymbol('X',3,1)
+    Y = MatrixSymbol('Y',3,1)
+    z = symbols('z',integer = True)
+    name_expr = ('testBug', X[0] + X[1])
+    result = codegen(name_expr, language='C', header=False, empty=False, argument_sequence=(X, Y, z))
+    source = result[0][1]
+    expected = (
+        '#include "testBug.h"\n'
+        '#include \n'
+        'double testBug(double *X, double *Y, int z) {\n'
+        '   double testBug_result;\n'
+        '   testBug_result = X[0] + X[1];\n'
+        '   return testBug_result;\n'
+        '}\n'
+    )
+    assert source == expected
+
+def test_empty_f_code():
+    code_gen = FCodeGen()
+    source = get_string(code_gen.dump_f95, [])
+    assert source == ""
+
+
+def test_empty_f_code_with_header():
+    code_gen = FCodeGen()
+    source = get_string(code_gen.dump_f95, [], header=True)
+    assert source[:82] == (
+        "!******************************************************************************\n!*"
+    )
+          #   "                    Code generated with SymPy 0.7.2-git                    "
+    assert source[158:] == (                                                              "*\n"
+            "!*                                                                            *\n"
+            "!*              See http://www.sympy.org/ for more information.               *\n"
+            "!*                                                                            *\n"
+            "!*                       This file is part of 'project'                       *\n"
+            "!******************************************************************************\n"
+            )
+
+
+def test_empty_f_header():
+    code_gen = FCodeGen()
+    source = get_string(code_gen.dump_h, [])
+    assert source == ""
+
+
+def test_simple_f_code():
+    x, y, z = symbols('x,y,z')
+    expr = (x + y)*z
+    routine = make_routine("test", expr)
+    code_gen = FCodeGen()
+    source = get_string(code_gen.dump_f95, [routine])
+    expected = (
+        "REAL*8 function test(x, y, z)\n"
+        "implicit none\n"
+        "REAL*8, intent(in) :: x\n"
+        "REAL*8, intent(in) :: y\n"
+        "REAL*8, intent(in) :: z\n"
+        "test = z*(x + y)\n"
+        "end function\n"
+    )
+    assert source == expected
+
+
+def test_numbersymbol_f_code():
+    routine = make_routine("test", pi**Catalan)
+    code_gen = FCodeGen()
+    source = get_string(code_gen.dump_f95, [routine])
+    expected = (
+        "REAL*8 function test()\n"
+        "implicit none\n"
+        "REAL*8, parameter :: Catalan = %sd0\n"
+        "REAL*8, parameter :: pi = %sd0\n"
+        "test = pi**Catalan\n"
+        "end function\n"
+    ) % (Catalan.evalf(17), pi.evalf(17))
+    assert source == expected
+
+def test_erf_f_code():
+    x = symbols('x')
+    routine = make_routine("test", erf(x) - erf(-2 * x))
+    code_gen = FCodeGen()
+    source = get_string(code_gen.dump_f95, [routine])
+    expected = (
+        "REAL*8 function test(x)\n"
+        "implicit none\n"
+        "REAL*8, intent(in) :: x\n"
+        "test = erf(x) + erf(2.0d0*x)\n"
+        "end function\n"
+    )
+    assert source == expected, source
+
+def test_f_code_argument_order():
+    x, y, z = symbols('x,y,z')
+    expr = x + y
+    routine = make_routine("test", expr, argument_sequence=[z, x, y])
+    code_gen = FCodeGen()
+    source = get_string(code_gen.dump_f95, [routine])
+    expected = (
+        "REAL*8 function test(z, x, y)\n"
+        "implicit none\n"
+        "REAL*8, intent(in) :: z\n"
+        "REAL*8, intent(in) :: x\n"
+        "REAL*8, intent(in) :: y\n"
+        "test = x + y\n"
+        "end function\n"
+    )
+    assert source == expected
+
+
+def test_simple_f_header():
+    x, y, z = symbols('x,y,z')
+    expr = (x + y)*z
+    routine = make_routine("test", expr)
+    code_gen = FCodeGen()
+    source = get_string(code_gen.dump_h, [routine])
+    expected = (
+        "interface\n"
+        "REAL*8 function test(x, y, z)\n"
+        "implicit none\n"
+        "REAL*8, intent(in) :: x\n"
+        "REAL*8, intent(in) :: y\n"
+        "REAL*8, intent(in) :: z\n"
+        "end function\n"
+        "end interface\n"
+    )
+    assert source == expected
+
+
+def test_simple_f_codegen():
+    x, y, z = symbols('x,y,z')
+    expr = (x + y)*z
+    result = codegen(
+        ("test", expr), "F95", "file", header=False, empty=False)
+    expected = [
+        ("file.f90",
+        "REAL*8 function test(x, y, z)\n"
+        "implicit none\n"
+        "REAL*8, intent(in) :: x\n"
+        "REAL*8, intent(in) :: y\n"
+        "REAL*8, intent(in) :: z\n"
+        "test = z*(x + y)\n"
+        "end function\n"),
+        ("file.h",
+        "interface\n"
+        "REAL*8 function test(x, y, z)\n"
+        "implicit none\n"
+        "REAL*8, intent(in) :: x\n"
+        "REAL*8, intent(in) :: y\n"
+        "REAL*8, intent(in) :: z\n"
+        "end function\n"
+        "end interface\n")
+    ]
+    assert result == expected
+
+
+def test_multiple_results_f():
+    x, y, z = symbols('x,y,z')
+    expr1 = (x + y)*z
+    expr2 = (x - y)*z
+    routine = make_routine(
+        "test",
+        [expr1, expr2]
+    )
+    code_gen = FCodeGen()
+    raises(CodeGenError, lambda: get_string(code_gen.dump_h, [routine]))
+
+
+def test_no_results_f():
+    raises(ValueError, lambda: make_routine("test", []))
+
+
+def test_intrinsic_math_codegen():
+    # not included: log10
+    from sympy.functions.elementary.complexes import Abs
+    from sympy.functions.elementary.exponential import log
+    from sympy.functions.elementary.hyperbolic import (cosh, sinh, tanh)
+    from sympy.functions.elementary.miscellaneous import sqrt
+    from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, tan)
+    x = symbols('x')
+    name_expr = [
+        ("test_abs", Abs(x)),
+        ("test_acos", acos(x)),
+        ("test_asin", asin(x)),
+        ("test_atan", atan(x)),
+        ("test_cos", cos(x)),
+        ("test_cosh", cosh(x)),
+        ("test_log", log(x)),
+        ("test_ln", log(x)),
+        ("test_sin", sin(x)),
+        ("test_sinh", sinh(x)),
+        ("test_sqrt", sqrt(x)),
+        ("test_tan", tan(x)),
+        ("test_tanh", tanh(x)),
+    ]
+    result = codegen(name_expr, "F95", "file", header=False, empty=False)
+    assert result[0][0] == "file.f90"
+    expected = (
+        'REAL*8 function test_abs(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'test_abs = abs(x)\n'
+        'end function\n'
+        'REAL*8 function test_acos(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'test_acos = acos(x)\n'
+        'end function\n'
+        'REAL*8 function test_asin(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'test_asin = asin(x)\n'
+        'end function\n'
+        'REAL*8 function test_atan(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'test_atan = atan(x)\n'
+        'end function\n'
+        'REAL*8 function test_cos(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'test_cos = cos(x)\n'
+        'end function\n'
+        'REAL*8 function test_cosh(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'test_cosh = cosh(x)\n'
+        'end function\n'
+        'REAL*8 function test_log(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'test_log = log(x)\n'
+        'end function\n'
+        'REAL*8 function test_ln(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'test_ln = log(x)\n'
+        'end function\n'
+        'REAL*8 function test_sin(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'test_sin = sin(x)\n'
+        'end function\n'
+        'REAL*8 function test_sinh(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'test_sinh = sinh(x)\n'
+        'end function\n'
+        'REAL*8 function test_sqrt(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'test_sqrt = sqrt(x)\n'
+        'end function\n'
+        'REAL*8 function test_tan(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'test_tan = tan(x)\n'
+        'end function\n'
+        'REAL*8 function test_tanh(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'test_tanh = tanh(x)\n'
+        'end function\n'
+    )
+    assert result[0][1] == expected
+
+    assert result[1][0] == "file.h"
+    expected = (
+        'interface\n'
+        'REAL*8 function test_abs(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'end function\n'
+        'end interface\n'
+        'interface\n'
+        'REAL*8 function test_acos(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'end function\n'
+        'end interface\n'
+        'interface\n'
+        'REAL*8 function test_asin(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'end function\n'
+        'end interface\n'
+        'interface\n'
+        'REAL*8 function test_atan(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'end function\n'
+        'end interface\n'
+        'interface\n'
+        'REAL*8 function test_cos(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'end function\n'
+        'end interface\n'
+        'interface\n'
+        'REAL*8 function test_cosh(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'end function\n'
+        'end interface\n'
+        'interface\n'
+        'REAL*8 function test_log(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'end function\n'
+        'end interface\n'
+        'interface\n'
+        'REAL*8 function test_ln(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'end function\n'
+        'end interface\n'
+        'interface\n'
+        'REAL*8 function test_sin(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'end function\n'
+        'end interface\n'
+        'interface\n'
+        'REAL*8 function test_sinh(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'end function\n'
+        'end interface\n'
+        'interface\n'
+        'REAL*8 function test_sqrt(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'end function\n'
+        'end interface\n'
+        'interface\n'
+        'REAL*8 function test_tan(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'end function\n'
+        'end interface\n'
+        'interface\n'
+        'REAL*8 function test_tanh(x)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'end function\n'
+        'end interface\n'
+    )
+    assert result[1][1] == expected
+
+
+def test_intrinsic_math2_codegen():
+    # not included: frexp, ldexp, modf, fmod
+    from sympy.functions.elementary.trigonometric import atan2
+    x, y = symbols('x,y')
+    name_expr = [
+        ("test_atan2", atan2(x, y)),
+        ("test_pow", x**y),
+    ]
+    result = codegen(name_expr, "F95", "file", header=False, empty=False)
+    assert result[0][0] == "file.f90"
+    expected = (
+        'REAL*8 function test_atan2(x, y)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'REAL*8, intent(in) :: y\n'
+        'test_atan2 = atan2(x, y)\n'
+        'end function\n'
+        'REAL*8 function test_pow(x, y)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'REAL*8, intent(in) :: y\n'
+        'test_pow = x**y\n'
+        'end function\n'
+    )
+    assert result[0][1] == expected
+
+    assert result[1][0] == "file.h"
+    expected = (
+        'interface\n'
+        'REAL*8 function test_atan2(x, y)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'REAL*8, intent(in) :: y\n'
+        'end function\n'
+        'end interface\n'
+        'interface\n'
+        'REAL*8 function test_pow(x, y)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'REAL*8, intent(in) :: y\n'
+        'end function\n'
+        'end interface\n'
+    )
+    assert result[1][1] == expected
+
+
+def test_complicated_codegen_f95():
+    from sympy.functions.elementary.trigonometric import (cos, sin, tan)
+    x, y, z = symbols('x,y,z')
+    name_expr = [
+        ("test1", ((sin(x) + cos(y) + tan(z))**7).expand()),
+        ("test2", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))),
+    ]
+    result = codegen(name_expr, "F95", "file", header=False, empty=False)
+    assert result[0][0] == "file.f90"
+    expected = (
+        'REAL*8 function test1(x, y, z)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'REAL*8, intent(in) :: y\n'
+        'REAL*8, intent(in) :: z\n'
+        'test1 = sin(x)**7 + 7*sin(x)**6*cos(y) + 7*sin(x)**6*tan(z) + 21*sin(x) &\n'
+        '      **5*cos(y)**2 + 42*sin(x)**5*cos(y)*tan(z) + 21*sin(x)**5*tan(z) &\n'
+        '      **2 + 35*sin(x)**4*cos(y)**3 + 105*sin(x)**4*cos(y)**2*tan(z) + &\n'
+        '      105*sin(x)**4*cos(y)*tan(z)**2 + 35*sin(x)**4*tan(z)**3 + 35*sin( &\n'
+        '      x)**3*cos(y)**4 + 140*sin(x)**3*cos(y)**3*tan(z) + 210*sin(x)**3* &\n'
+        '      cos(y)**2*tan(z)**2 + 140*sin(x)**3*cos(y)*tan(z)**3 + 35*sin(x) &\n'
+        '      **3*tan(z)**4 + 21*sin(x)**2*cos(y)**5 + 105*sin(x)**2*cos(y)**4* &\n'
+        '      tan(z) + 210*sin(x)**2*cos(y)**3*tan(z)**2 + 210*sin(x)**2*cos(y) &\n'
+        '      **2*tan(z)**3 + 105*sin(x)**2*cos(y)*tan(z)**4 + 21*sin(x)**2*tan &\n'
+        '      (z)**5 + 7*sin(x)*cos(y)**6 + 42*sin(x)*cos(y)**5*tan(z) + 105* &\n'
+        '      sin(x)*cos(y)**4*tan(z)**2 + 140*sin(x)*cos(y)**3*tan(z)**3 + 105 &\n'
+        '      *sin(x)*cos(y)**2*tan(z)**4 + 42*sin(x)*cos(y)*tan(z)**5 + 7*sin( &\n'
+        '      x)*tan(z)**6 + cos(y)**7 + 7*cos(y)**6*tan(z) + 21*cos(y)**5*tan( &\n'
+        '      z)**2 + 35*cos(y)**4*tan(z)**3 + 35*cos(y)**3*tan(z)**4 + 21*cos( &\n'
+        '      y)**2*tan(z)**5 + 7*cos(y)*tan(z)**6 + tan(z)**7\n'
+        'end function\n'
+        'REAL*8 function test2(x, y, z)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'REAL*8, intent(in) :: y\n'
+        'REAL*8, intent(in) :: z\n'
+        'test2 = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))\n'
+        'end function\n'
+    )
+    assert result[0][1] == expected
+    assert result[1][0] == "file.h"
+    expected = (
+        'interface\n'
+        'REAL*8 function test1(x, y, z)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'REAL*8, intent(in) :: y\n'
+        'REAL*8, intent(in) :: z\n'
+        'end function\n'
+        'end interface\n'
+        'interface\n'
+        'REAL*8 function test2(x, y, z)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'REAL*8, intent(in) :: y\n'
+        'REAL*8, intent(in) :: z\n'
+        'end function\n'
+        'end interface\n'
+    )
+    assert result[1][1] == expected
+
+
+def test_loops():
+    from sympy.tensor import IndexedBase, Idx
+    from sympy.core.symbol import symbols
+
+    n, m = symbols('n,m', integer=True)
+    A, x, y = map(IndexedBase, 'Axy')
+    i = Idx('i', m)
+    j = Idx('j', n)
+
+    (f1, code), (f2, interface) = codegen(
+        ('matrix_vector', Eq(y[i], A[i, j]*x[j])), "F95", "file", header=False, empty=False)
+
+    assert f1 == 'file.f90'
+    expected = (
+        'subroutine matrix_vector(A, m, n, x, y)\n'
+        'implicit none\n'
+        'INTEGER*4, intent(in) :: m\n'
+        'INTEGER*4, intent(in) :: n\n'
+        'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n'
+        'REAL*8, intent(in), dimension(1:n) :: x\n'
+        'REAL*8, intent(out), dimension(1:m) :: y\n'
+        'INTEGER*4 :: i\n'
+        'INTEGER*4 :: j\n'
+        'do i = 1, m\n'
+        '   y(i) = 0\n'
+        'end do\n'
+        'do i = 1, m\n'
+        '   do j = 1, n\n'
+        '      y(i) = %(rhs)s + y(i)\n'
+        '   end do\n'
+        'end do\n'
+        'end subroutine\n'
+    )
+
+    assert code == expected % {'rhs': 'A(i, j)*x(j)'} or\
+        code == expected % {'rhs': 'x(j)*A(i, j)'}
+    assert f2 == 'file.h'
+    assert interface == (
+        'interface\n'
+        'subroutine matrix_vector(A, m, n, x, y)\n'
+        'implicit none\n'
+        'INTEGER*4, intent(in) :: m\n'
+        'INTEGER*4, intent(in) :: n\n'
+        'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n'
+        'REAL*8, intent(in), dimension(1:n) :: x\n'
+        'REAL*8, intent(out), dimension(1:m) :: y\n'
+        'end subroutine\n'
+        'end interface\n'
+    )
+
+
+def test_dummy_loops_f95():
+    from sympy.tensor import IndexedBase, Idx
+    i, m = symbols('i m', integer=True, cls=Dummy)
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i = Idx(i, m)
+    expected = (
+        'subroutine test_dummies(m_%(mcount)i, x, y)\n'
+        'implicit none\n'
+        'INTEGER*4, intent(in) :: m_%(mcount)i\n'
+        'REAL*8, intent(in), dimension(1:m_%(mcount)i) :: x\n'
+        'REAL*8, intent(out), dimension(1:m_%(mcount)i) :: y\n'
+        'INTEGER*4 :: i_%(icount)i\n'
+        'do i_%(icount)i = 1, m_%(mcount)i\n'
+        '   y(i_%(icount)i) = x(i_%(icount)i)\n'
+        'end do\n'
+        'end subroutine\n'
+    ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index}
+    r = make_routine('test_dummies', Eq(y[i], x[i]))
+    c = FCodeGen()
+    code = get_string(c.dump_f95, [r])
+    assert code == expected
+
+
+def test_loops_InOut():
+    from sympy.tensor import IndexedBase, Idx
+    from sympy.core.symbol import symbols
+
+    i, j, n, m = symbols('i,j,n,m', integer=True)
+    A, x, y = symbols('A,x,y')
+    A = IndexedBase(A)[Idx(i, m), Idx(j, n)]
+    x = IndexedBase(x)[Idx(j, n)]
+    y = IndexedBase(y)[Idx(i, m)]
+
+    (f1, code), (f2, interface) = codegen(
+        ('matrix_vector', Eq(y, y + A*x)), "F95", "file", header=False, empty=False)
+
+    assert f1 == 'file.f90'
+    expected = (
+        'subroutine matrix_vector(A, m, n, x, y)\n'
+        'implicit none\n'
+        'INTEGER*4, intent(in) :: m\n'
+        'INTEGER*4, intent(in) :: n\n'
+        'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n'
+        'REAL*8, intent(in), dimension(1:n) :: x\n'
+        'REAL*8, intent(inout), dimension(1:m) :: y\n'
+        'INTEGER*4 :: i\n'
+        'INTEGER*4 :: j\n'
+        'do i = 1, m\n'
+        '   do j = 1, n\n'
+        '      y(i) = %(rhs)s + y(i)\n'
+        '   end do\n'
+        'end do\n'
+        'end subroutine\n'
+    )
+
+    assert (code == expected % {'rhs': 'A(i, j)*x(j)'} or
+            code == expected % {'rhs': 'x(j)*A(i, j)'})
+    assert f2 == 'file.h'
+    assert interface == (
+        'interface\n'
+        'subroutine matrix_vector(A, m, n, x, y)\n'
+        'implicit none\n'
+        'INTEGER*4, intent(in) :: m\n'
+        'INTEGER*4, intent(in) :: n\n'
+        'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n'
+        'REAL*8, intent(in), dimension(1:n) :: x\n'
+        'REAL*8, intent(inout), dimension(1:m) :: y\n'
+        'end subroutine\n'
+        'end interface\n'
+    )
+
+
+def test_partial_loops_f():
+    # check that loop boundaries are determined by Idx, and array strides
+    # determined by shape of IndexedBase object.
+    from sympy.tensor import IndexedBase, Idx
+    from sympy.core.symbol import symbols
+    n, m, o, p = symbols('n m o p', integer=True)
+    A = IndexedBase('A', shape=(m, p))
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i = Idx('i', (o, m - 5))  # Note: bounds are inclusive
+    j = Idx('j', n)          # dimension n corresponds to bounds (0, n - 1)
+
+    (f1, code), (f2, interface) = codegen(
+        ('matrix_vector', Eq(y[i], A[i, j]*x[j])), "F95", "file", header=False, empty=False)
+
+    expected = (
+        'subroutine matrix_vector(A, m, n, o, p, x, y)\n'
+        'implicit none\n'
+        'INTEGER*4, intent(in) :: m\n'
+        'INTEGER*4, intent(in) :: n\n'
+        'INTEGER*4, intent(in) :: o\n'
+        'INTEGER*4, intent(in) :: p\n'
+        'REAL*8, intent(in), dimension(1:m, 1:p) :: A\n'
+        'REAL*8, intent(in), dimension(1:n) :: x\n'
+        'REAL*8, intent(out), dimension(1:%(iup-ilow)s) :: y\n'
+        'INTEGER*4 :: i\n'
+        'INTEGER*4 :: j\n'
+        'do i = %(ilow)s, %(iup)s\n'
+        '   y(i) = 0\n'
+        'end do\n'
+        'do i = %(ilow)s, %(iup)s\n'
+        '   do j = 1, n\n'
+        '      y(i) = %(rhs)s + y(i)\n'
+        '   end do\n'
+        'end do\n'
+        'end subroutine\n'
+    ) % {
+        'rhs': '%(rhs)s',
+        'iup': str(m - 4),
+        'ilow': str(1 + o),
+        'iup-ilow': str(m - 4 - o)
+    }
+
+    assert code == expected % {'rhs': 'A(i, j)*x(j)'} or\
+        code == expected % {'rhs': 'x(j)*A(i, j)'}
+
+
+def test_output_arg_f():
+    from sympy.core.relational import Equality
+    from sympy.functions.elementary.trigonometric import (cos, sin)
+    x, y, z = symbols("x,y,z")
+    r = make_routine("foo", [Equality(y, sin(x)), cos(x)])
+    c = FCodeGen()
+    result = c.write([r], "test", header=False, empty=False)
+    assert result[0][0] == "test.f90"
+    assert result[0][1] == (
+        'REAL*8 function foo(x, y)\n'
+        'implicit none\n'
+        'REAL*8, intent(in) :: x\n'
+        'REAL*8, intent(out) :: y\n'
+        'y = sin(x)\n'
+        'foo = cos(x)\n'
+        'end function\n'
+    )
+
+
+def test_inline_function():
+    from sympy.tensor import IndexedBase, Idx
+    from sympy.core.symbol import symbols
+    n, m = symbols('n m', integer=True)
+    A, x, y = map(IndexedBase, 'Axy')
+    i = Idx('i', m)
+    p = FCodeGen()
+    func = implemented_function('func', Lambda(n, n*(n + 1)))
+    routine = make_routine('test_inline', Eq(y[i], func(x[i])))
+    code = get_string(p.dump_f95, [routine])
+    expected = (
+        'subroutine test_inline(m, x, y)\n'
+        'implicit none\n'
+        'INTEGER*4, intent(in) :: m\n'
+        'REAL*8, intent(in), dimension(1:m) :: x\n'
+        'REAL*8, intent(out), dimension(1:m) :: y\n'
+        'INTEGER*4 :: i\n'
+        'do i = 1, m\n'
+        '   y(i) = %s*%s\n'
+        'end do\n'
+        'end subroutine\n'
+    )
+    args = ('x(i)', '(x(i) + 1)')
+    assert code == expected % args or\
+        code == expected % args[::-1]
+
+
+def test_f_code_call_signature_wrap():
+    # Issue #7934
+    x = symbols('x:20')
+    expr = 0
+    for sym in x:
+        expr += sym
+    routine = make_routine("test", expr)
+    code_gen = FCodeGen()
+    source = get_string(code_gen.dump_f95, [routine])
+    expected = """\
+REAL*8 function test(x0, x1, x10, x11, x12, x13, x14, x15, x16, x17, x18, &
+      x19, x2, x3, x4, x5, x6, x7, x8, x9)
+implicit none
+REAL*8, intent(in) :: x0
+REAL*8, intent(in) :: x1
+REAL*8, intent(in) :: x10
+REAL*8, intent(in) :: x11
+REAL*8, intent(in) :: x12
+REAL*8, intent(in) :: x13
+REAL*8, intent(in) :: x14
+REAL*8, intent(in) :: x15
+REAL*8, intent(in) :: x16
+REAL*8, intent(in) :: x17
+REAL*8, intent(in) :: x18
+REAL*8, intent(in) :: x19
+REAL*8, intent(in) :: x2
+REAL*8, intent(in) :: x3
+REAL*8, intent(in) :: x4
+REAL*8, intent(in) :: x5
+REAL*8, intent(in) :: x6
+REAL*8, intent(in) :: x7
+REAL*8, intent(in) :: x8
+REAL*8, intent(in) :: x9
+test = x0 + x1 + x10 + x11 + x12 + x13 + x14 + x15 + x16 + x17 + x18 + &
+      x19 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9
+end function
+"""
+    assert source == expected
+
+
+def test_check_case():
+    x, X = symbols('x,X')
+    raises(CodeGenError, lambda: codegen(('test', x*X), 'f95', 'prefix'))
+
+
+def test_check_case_false_positive():
+    # The upper case/lower case exception should not be triggered by SymPy
+    # objects that differ only because of assumptions.  (It may be useful to
+    # have a check for that as well, but here we only want to test against
+    # false positives with respect to case checking.)
+    x1 = symbols('x')
+    x2 = symbols('x', my_assumption=True)
+    try:
+        codegen(('test', x1*x2), 'f95', 'prefix')
+    except CodeGenError as e:
+        if e.args[0].startswith("Fortran ignores case."):
+            raise AssertionError("This exception should not be raised!")
+
+
+def test_c_fortran_omit_routine_name():
+    x, y = symbols("x,y")
+    name_expr = [("foo", 2*x)]
+    result = codegen(name_expr, "F95", header=False, empty=False)
+    expresult = codegen(name_expr, "F95", "foo", header=False, empty=False)
+    assert result[0][1] == expresult[0][1]
+
+    name_expr = ("foo", x*y)
+    result = codegen(name_expr, "F95", header=False, empty=False)
+    expresult = codegen(name_expr, "F95", "foo", header=False, empty=False)
+    assert result[0][1] == expresult[0][1]
+
+    name_expr = ("foo", Matrix([[x, y], [x+y, x-y]]))
+    result = codegen(name_expr, "C89", header=False, empty=False)
+    expresult = codegen(name_expr, "C89", "foo", header=False, empty=False)
+    assert result[0][1] == expresult[0][1]
+
+
+def test_fcode_matrix_output():
+    x, y, z = symbols('x,y,z')
+    e1 = x + y
+    e2 = Matrix([[x, y], [z, 16]])
+    name_expr = ("test", (e1, e2))
+    result = codegen(name_expr, "f95", "test", header=False, empty=False)
+    source = result[0][1]
+    expected = (
+        "REAL*8 function test(x, y, z, out_%(hash)s)\n"
+        "implicit none\n"
+        "REAL*8, intent(in) :: x\n"
+        "REAL*8, intent(in) :: y\n"
+        "REAL*8, intent(in) :: z\n"
+        "REAL*8, intent(out), dimension(1:2, 1:2) :: out_%(hash)s\n"
+        "out_%(hash)s(1, 1) = x\n"
+        "out_%(hash)s(2, 1) = z\n"
+        "out_%(hash)s(1, 2) = y\n"
+        "out_%(hash)s(2, 2) = 16\n"
+        "test = x + y\n"
+        "end function\n"
+    )
+    # look for the magic number
+    a = source.splitlines()[5]
+    b = a.split('_')
+    out = b[1]
+    expected = expected % {'hash': out}
+    assert source == expected
+
+
+def test_fcode_results_named_ordered():
+    x, y, z = symbols('x,y,z')
+    B, C = symbols('B,C')
+    A = MatrixSymbol('A', 1, 3)
+    expr1 = Equality(A, Matrix([[1, 2, x]]))
+    expr2 = Equality(C, (x + y)*z)
+    expr3 = Equality(B, 2*x)
+    name_expr = ("test", [expr1, expr2, expr3])
+    result = codegen(name_expr, "f95", "test", header=False, empty=False,
+                     argument_sequence=(x, z, y, C, A, B))
+    source = result[0][1]
+    expected = (
+        "subroutine test(x, z, y, C, A, B)\n"
+        "implicit none\n"
+        "REAL*8, intent(in) :: x\n"
+        "REAL*8, intent(in) :: z\n"
+        "REAL*8, intent(in) :: y\n"
+        "REAL*8, intent(out) :: C\n"
+        "REAL*8, intent(out) :: B\n"
+        "REAL*8, intent(out), dimension(1:1, 1:3) :: A\n"
+        "C = z*(x + y)\n"
+        "A(1, 1) = 1\n"
+        "A(1, 2) = 2\n"
+        "A(1, 3) = x\n"
+        "B = 2*x\n"
+        "end subroutine\n"
+    )
+    assert source == expected
+
+
+def test_fcode_matrixsymbol_slice():
+    A = MatrixSymbol('A', 2, 3)
+    B = MatrixSymbol('B', 1, 3)
+    C = MatrixSymbol('C', 1, 3)
+    D = MatrixSymbol('D', 2, 1)
+    name_expr = ("test", [Equality(B, A[0, :]),
+                          Equality(C, A[1, :]),
+                          Equality(D, A[:, 2])])
+    result = codegen(name_expr, "f95", "test", header=False, empty=False)
+    source = result[0][1]
+    expected = (
+        "subroutine test(A, B, C, D)\n"
+        "implicit none\n"
+        "REAL*8, intent(in), dimension(1:2, 1:3) :: A\n"
+        "REAL*8, intent(out), dimension(1:1, 1:3) :: B\n"
+        "REAL*8, intent(out), dimension(1:1, 1:3) :: C\n"
+        "REAL*8, intent(out), dimension(1:2, 1:1) :: D\n"
+        "B(1, 1) = A(1, 1)\n"
+        "B(1, 2) = A(1, 2)\n"
+        "B(1, 3) = A(1, 3)\n"
+        "C(1, 1) = A(2, 1)\n"
+        "C(1, 2) = A(2, 2)\n"
+        "C(1, 3) = A(2, 3)\n"
+        "D(1, 1) = A(1, 3)\n"
+        "D(2, 1) = A(2, 3)\n"
+        "end subroutine\n"
+    )
+    assert source == expected
+
+
+def test_fcode_matrixsymbol_slice_autoname():
+    # see issue #8093
+    A = MatrixSymbol('A', 2, 3)
+    name_expr = ("test", A[:, 1])
+    result = codegen(name_expr, "f95", "test", header=False, empty=False)
+    source = result[0][1]
+    expected = (
+        "subroutine test(A, out_%(hash)s)\n"
+        "implicit none\n"
+        "REAL*8, intent(in), dimension(1:2, 1:3) :: A\n"
+        "REAL*8, intent(out), dimension(1:2, 1:1) :: out_%(hash)s\n"
+        "out_%(hash)s(1, 1) = A(1, 2)\n"
+        "out_%(hash)s(2, 1) = A(2, 2)\n"
+        "end subroutine\n"
+    )
+    # look for the magic number
+    a = source.splitlines()[3]
+    b = a.split('_')
+    out = b[1]
+    expected = expected % {'hash': out}
+    assert source == expected
+
+
+def test_global_vars():
+    x, y, z, t = symbols("x y z t")
+    result = codegen(('f', x*y), "F95", header=False, empty=False,
+                     global_vars=(y,))
+    source = result[0][1]
+    expected = (
+        "REAL*8 function f(x)\n"
+        "implicit none\n"
+        "REAL*8, intent(in) :: x\n"
+        "f = x*y\n"
+        "end function\n"
+        )
+    assert source == expected
+
+    expected = (
+        '#include "f.h"\n'
+        '#include \n'
+        'double f(double x, double y) {\n'
+        '   double f_result;\n'
+        '   f_result = x*y + z;\n'
+        '   return f_result;\n'
+        '}\n'
+    )
+    result = codegen(('f', x*y+z), "C", header=False, empty=False,
+                     global_vars=(z, t))
+    source = result[0][1]
+    assert source == expected
+
+def test_custom_codegen():
+    from sympy.printing.c import C99CodePrinter
+    from sympy.functions.elementary.exponential import exp
+
+    printer = C99CodePrinter(settings={'user_functions': {'exp': 'fastexp'}})
+
+    x, y = symbols('x y')
+    expr = exp(x + y)
+
+    # replace math.h with a different header
+    gen = C99CodeGen(printer=printer,
+                     preprocessor_statements=['#include "fastexp.h"'])
+
+    expected = (
+        '#include "expr.h"\n'
+        '#include "fastexp.h"\n'
+        'double expr(double x, double y) {\n'
+        '   double expr_result;\n'
+        '   expr_result = fastexp(x + y);\n'
+        '   return expr_result;\n'
+        '}\n'
+    )
+
+    result = codegen(('expr', expr), header=False, empty=False, code_gen=gen)
+    source = result[0][1]
+    assert source == expected
+
+    # use both math.h and an external header
+    gen = C99CodeGen(printer=printer)
+    gen.preprocessor_statements.append('#include "fastexp.h"')
+
+    expected = (
+        '#include "expr.h"\n'
+        '#include \n'
+        '#include "fastexp.h"\n'
+        'double expr(double x, double y) {\n'
+        '   double expr_result;\n'
+        '   expr_result = fastexp(x + y);\n'
+        '   return expr_result;\n'
+        '}\n'
+    )
+
+    result = codegen(('expr', expr), header=False, empty=False, code_gen=gen)
+    source = result[0][1]
+    assert source == expected
+
+def test_c_with_printer():
+    # issue 13586
+    from sympy.printing.c import C99CodePrinter
+    class CustomPrinter(C99CodePrinter):
+        def _print_Pow(self, expr):
+            return "fastpow({}, {})".format(self._print(expr.base),
+                                            self._print(expr.exp))
+
+    x = symbols('x')
+    expr = x**3
+    expected =[
+        ("file.c",
+        "#include \"file.h\"\n"
+        "#include \n"
+        "double test(double x) {\n"
+        "   double test_result;\n"
+        "   test_result = fastpow(x, 3);\n"
+        "   return test_result;\n"
+        "}\n"),
+        ("file.h",
+        "#ifndef PROJECT__FILE__H\n"
+        "#define PROJECT__FILE__H\n"
+        "double test(double x);\n"
+        "#endif\n")
+    ]
+    result = codegen(("test", expr), "C","file", header=False, empty=False, printer = CustomPrinter())
+    assert result == expected
+
+
+def test_fcode_complex():
+    import sympy.utilities.codegen
+    sympy.utilities.codegen.COMPLEX_ALLOWED = True
+    x = Symbol('x', real=True)
+    y = Symbol('y',real=True)
+    result = codegen(('test',x+y), 'f95', 'test', header=False, empty=False)
+    source = (result[0][1])
+    expected = (
+        "REAL*8 function test(x, y)\n"
+        "implicit none\n"
+        "REAL*8, intent(in) :: x\n"
+        "REAL*8, intent(in) :: y\n"
+        "test = x + y\n"
+        "end function\n")
+    assert source == expected
+    x = Symbol('x')
+    y = Symbol('y',real=True)
+    result = codegen(('test',x+y), 'f95', 'test', header=False, empty=False)
+    source = (result[0][1])
+    expected = (
+        "COMPLEX*16 function test(x, y)\n"
+        "implicit none\n"
+        "COMPLEX*16, intent(in) :: x\n"
+        "REAL*8, intent(in) :: y\n"
+        "test = x + y\n"
+        "end function\n"
+        )
+    assert source==expected
+    sympy.utilities.codegen.COMPLEX_ALLOWED = False
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_codegen_julia.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_codegen_julia.py
new file mode 100644
index 0000000000000000000000000000000000000000..12841cb7d476107e3866d91b998bed1f997f3901
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_codegen_julia.py
@@ -0,0 +1,620 @@
+from io import StringIO
+
+from sympy.core import S, symbols, Eq, pi, Catalan, EulerGamma, Function
+from sympy.core.relational import Equality
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.matrices import Matrix, MatrixSymbol
+from sympy.utilities.codegen import JuliaCodeGen, codegen, make_routine
+from sympy.testing.pytest import XFAIL
+import sympy
+
+
+x, y, z = symbols('x,y,z')
+
+
+def test_empty_jl_code():
+    code_gen = JuliaCodeGen()
+    output = StringIO()
+    code_gen.dump_jl([], output, "file", header=False, empty=False)
+    source = output.getvalue()
+    assert source == ""
+
+
+def test_jl_simple_code():
+    name_expr = ("test", (x + y)*z)
+    result, = codegen(name_expr, "Julia", header=False, empty=False)
+    assert result[0] == "test.jl"
+    source = result[1]
+    expected = (
+        "function test(x, y, z)\n"
+        "    out1 = z .* (x + y)\n"
+        "    return out1\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_jl_simple_code_with_header():
+    name_expr = ("test", (x + y)*z)
+    result, = codegen(name_expr, "Julia", header=True, empty=False)
+    assert result[0] == "test.jl"
+    source = result[1]
+    expected = (
+        "#   Code generated with SymPy " + sympy.__version__ + "\n"
+        "#\n"
+        "#   See http://www.sympy.org/ for more information.\n"
+        "#\n"
+        "#   This file is part of 'project'\n"
+        "function test(x, y, z)\n"
+        "    out1 = z .* (x + y)\n"
+        "    return out1\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_jl_simple_code_nameout():
+    expr = Equality(z, (x + y))
+    name_expr = ("test", expr)
+    result, = codegen(name_expr, "Julia", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function test(x, y)\n"
+        "    z = x + y\n"
+        "    return z\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_jl_numbersymbol():
+    name_expr = ("test", pi**Catalan)
+    result, = codegen(name_expr, "Julia", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function test()\n"
+        "    out1 = pi ^ catalan\n"
+        "    return out1\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+@XFAIL
+def test_jl_numbersymbol_no_inline():
+    # FIXME: how to pass inline=False to the JuliaCodePrinter?
+    name_expr = ("test", [pi**Catalan, EulerGamma])
+    result, = codegen(name_expr, "Julia", header=False,
+                      empty=False, inline=False)
+    source = result[1]
+    expected = (
+        "function test()\n"
+        "    Catalan = 0.915965594177219\n"
+        "    EulerGamma = 0.5772156649015329\n"
+        "    out1 = pi ^ Catalan\n"
+        "    out2 = EulerGamma\n"
+        "    return out1, out2\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_jl_code_argument_order():
+    expr = x + y
+    routine = make_routine("test", expr, argument_sequence=[z, x, y], language="julia")
+    code_gen = JuliaCodeGen()
+    output = StringIO()
+    code_gen.dump_jl([routine], output, "test", header=False, empty=False)
+    source = output.getvalue()
+    expected = (
+        "function test(z, x, y)\n"
+        "    out1 = x + y\n"
+        "    return out1\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_multiple_results_m():
+    # Here the output order is the input order
+    expr1 = (x + y)*z
+    expr2 = (x - y)*z
+    name_expr = ("test", [expr1, expr2])
+    result, = codegen(name_expr, "Julia", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function test(x, y, z)\n"
+        "    out1 = z .* (x + y)\n"
+        "    out2 = z .* (x - y)\n"
+        "    return out1, out2\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_results_named_unordered():
+    # Here output order is based on name_expr
+    A, B, C = symbols('A,B,C')
+    expr1 = Equality(C, (x + y)*z)
+    expr2 = Equality(A, (x - y)*z)
+    expr3 = Equality(B, 2*x)
+    name_expr = ("test", [expr1, expr2, expr3])
+    result, = codegen(name_expr, "Julia", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function test(x, y, z)\n"
+        "    C = z .* (x + y)\n"
+        "    A = z .* (x - y)\n"
+        "    B = 2 * x\n"
+        "    return C, A, B\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_results_named_ordered():
+    A, B, C = symbols('A,B,C')
+    expr1 = Equality(C, (x + y)*z)
+    expr2 = Equality(A, (x - y)*z)
+    expr3 = Equality(B, 2*x)
+    name_expr = ("test", [expr1, expr2, expr3])
+    result = codegen(name_expr, "Julia", header=False, empty=False,
+                     argument_sequence=(x, z, y))
+    assert result[0][0] == "test.jl"
+    source = result[0][1]
+    expected = (
+        "function test(x, z, y)\n"
+        "    C = z .* (x + y)\n"
+        "    A = z .* (x - y)\n"
+        "    B = 2 * x\n"
+        "    return C, A, B\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_complicated_jl_codegen():
+    from sympy.functions.elementary.trigonometric import (cos, sin, tan)
+    name_expr = ("testlong",
+            [ ((sin(x) + cos(y) + tan(z))**3).expand(),
+            cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))
+    ])
+    result = codegen(name_expr, "Julia", header=False, empty=False)
+    assert result[0][0] == "testlong.jl"
+    source = result[0][1]
+    expected = (
+        "function testlong(x, y, z)\n"
+        "    out1 = sin(x) .^ 3 + 3 * sin(x) .^ 2 .* cos(y) + 3 * sin(x) .^ 2 .* tan(z)"
+        " + 3 * sin(x) .* cos(y) .^ 2 + 6 * sin(x) .* cos(y) .* tan(z) + 3 * sin(x) .* tan(z) .^ 2"
+        " + cos(y) .^ 3 + 3 * cos(y) .^ 2 .* tan(z) + 3 * cos(y) .* tan(z) .^ 2 + tan(z) .^ 3\n"
+        "    out2 = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))\n"
+        "    return out1, out2\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_jl_output_arg_mixed_unordered():
+    # named outputs are alphabetical, unnamed output appear in the given order
+    from sympy.functions.elementary.trigonometric import (cos, sin)
+    a = symbols("a")
+    name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))])
+    result, = codegen(name_expr, "Julia", header=False, empty=False)
+    assert result[0] == "foo.jl"
+    source = result[1]
+    expected = (
+        'function foo(x)\n'
+        '    out1 = cos(2 * x)\n'
+        '    y = sin(x)\n'
+        '    out3 = cos(x)\n'
+        '    a = sin(2 * x)\n'
+        '    return out1, y, out3, a\n'
+        'end\n'
+    )
+    assert source == expected
+
+
+def test_jl_piecewise_():
+    pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True), evaluate=False)
+    name_expr = ("pwtest", pw)
+    result, = codegen(name_expr, "Julia", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function pwtest(x)\n"
+        "    out1 = ((x < -1) ? (0) :\n"
+        "    (x <= 1) ? (x .^ 2) :\n"
+        "    (x > 1) ? (2 - x) : (1))\n"
+        "    return out1\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+@XFAIL
+def test_jl_piecewise_no_inline():
+    # FIXME: how to pass inline=False to the JuliaCodePrinter?
+    pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True))
+    name_expr = ("pwtest", pw)
+    result, = codegen(name_expr, "Julia", header=False, empty=False,
+                      inline=False)
+    source = result[1]
+    expected = (
+        "function pwtest(x)\n"
+        "    if (x < -1)\n"
+        "        out1 = 0\n"
+        "    elseif (x <= 1)\n"
+        "        out1 = x .^ 2\n"
+        "    elseif (x > 1)\n"
+        "        out1 = -x + 2\n"
+        "    else\n"
+        "        out1 = 1\n"
+        "    end\n"
+        "    return out1\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_jl_multifcns_per_file():
+    name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
+    result = codegen(name_expr, "Julia", header=False, empty=False)
+    assert result[0][0] == "foo.jl"
+    source = result[0][1]
+    expected = (
+        "function foo(x, y)\n"
+        "    out1 = 2 * x\n"
+        "    out2 = 3 * y\n"
+        "    return out1, out2\n"
+        "end\n"
+        "function bar(y)\n"
+        "    out1 = y .^ 2\n"
+        "    out2 = 4 * y\n"
+        "    return out1, out2\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_jl_multifcns_per_file_w_header():
+    name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
+    result = codegen(name_expr, "Julia", header=True, empty=False)
+    assert result[0][0] == "foo.jl"
+    source = result[0][1]
+    expected = (
+        "#   Code generated with SymPy " + sympy.__version__ + "\n"
+        "#\n"
+        "#   See http://www.sympy.org/ for more information.\n"
+        "#\n"
+        "#   This file is part of 'project'\n"
+        "function foo(x, y)\n"
+        "    out1 = 2 * x\n"
+        "    out2 = 3 * y\n"
+        "    return out1, out2\n"
+        "end\n"
+        "function bar(y)\n"
+        "    out1 = y .^ 2\n"
+        "    out2 = 4 * y\n"
+        "    return out1, out2\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_jl_filename_match_prefix():
+    name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
+    result, = codegen(name_expr, "Julia", prefix="baz", header=False,
+                     empty=False)
+    assert result[0] == "baz.jl"
+
+
+def test_jl_matrix_named():
+    e2 = Matrix([[x, 2*y, pi*z]])
+    name_expr = ("test", Equality(MatrixSymbol('myout1', 1, 3), e2))
+    result = codegen(name_expr, "Julia", header=False, empty=False)
+    assert result[0][0] == "test.jl"
+    source = result[0][1]
+    expected = (
+        "function test(x, y, z)\n"
+        "    myout1 = [x 2 * y pi * z]\n"
+        "    return myout1\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_jl_matrix_named_matsym():
+    myout1 = MatrixSymbol('myout1', 1, 3)
+    e2 = Matrix([[x, 2*y, pi*z]])
+    name_expr = ("test", Equality(myout1, e2, evaluate=False))
+    result, = codegen(name_expr, "Julia", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function test(x, y, z)\n"
+        "    myout1 = [x 2 * y pi * z]\n"
+        "    return myout1\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_jl_matrix_output_autoname():
+    expr = Matrix([[x, x+y, 3]])
+    name_expr = ("test", expr)
+    result, = codegen(name_expr, "Julia", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function test(x, y)\n"
+        "    out1 = [x x + y 3]\n"
+        "    return out1\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_jl_matrix_output_autoname_2():
+    e1 = (x + y)
+    e2 = Matrix([[2*x, 2*y, 2*z]])
+    e3 = Matrix([[x], [y], [z]])
+    e4 = Matrix([[x, y], [z, 16]])
+    name_expr = ("test", (e1, e2, e3, e4))
+    result, = codegen(name_expr, "Julia", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function test(x, y, z)\n"
+        "    out1 = x + y\n"
+        "    out2 = [2 * x 2 * y 2 * z]\n"
+        "    out3 = [x, y, z]\n"
+        "    out4 = [x  y;\n"
+        "    z 16]\n"
+        "    return out1, out2, out3, out4\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_jl_results_matrix_named_ordered():
+    B, C = symbols('B,C')
+    A = MatrixSymbol('A', 1, 3)
+    expr1 = Equality(C, (x + y)*z)
+    expr2 = Equality(A, Matrix([[1, 2, x]]))
+    expr3 = Equality(B, 2*x)
+    name_expr = ("test", [expr1, expr2, expr3])
+    result, = codegen(name_expr, "Julia", header=False, empty=False,
+                     argument_sequence=(x, z, y))
+    source = result[1]
+    expected = (
+        "function test(x, z, y)\n"
+        "    C = z .* (x + y)\n"
+        "    A = [1 2 x]\n"
+        "    B = 2 * x\n"
+        "    return C, A, B\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_jl_matrixsymbol_slice():
+    A = MatrixSymbol('A', 2, 3)
+    B = MatrixSymbol('B', 1, 3)
+    C = MatrixSymbol('C', 1, 3)
+    D = MatrixSymbol('D', 2, 1)
+    name_expr = ("test", [Equality(B, A[0, :]),
+                          Equality(C, A[1, :]),
+                          Equality(D, A[:, 2])])
+    result, = codegen(name_expr, "Julia", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function test(A)\n"
+        "    B = A[1,:]\n"
+        "    C = A[2,:]\n"
+        "    D = A[:,3]\n"
+        "    return B, C, D\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_jl_matrixsymbol_slice2():
+    A = MatrixSymbol('A', 3, 4)
+    B = MatrixSymbol('B', 2, 2)
+    C = MatrixSymbol('C', 2, 2)
+    name_expr = ("test", [Equality(B, A[0:2, 0:2]),
+                          Equality(C, A[0:2, 1:3])])
+    result, = codegen(name_expr, "Julia", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function test(A)\n"
+        "    B = A[1:2,1:2]\n"
+        "    C = A[1:2,2:3]\n"
+        "    return B, C\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_jl_matrixsymbol_slice3():
+    A = MatrixSymbol('A', 8, 7)
+    B = MatrixSymbol('B', 2, 2)
+    C = MatrixSymbol('C', 4, 2)
+    name_expr = ("test", [Equality(B, A[6:, 1::3]),
+                          Equality(C, A[::2, ::3])])
+    result, = codegen(name_expr, "Julia", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function test(A)\n"
+        "    B = A[7:end,2:3:end]\n"
+        "    C = A[1:2:end,1:3:end]\n"
+        "    return B, C\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_jl_matrixsymbol_slice_autoname():
+    A = MatrixSymbol('A', 2, 3)
+    B = MatrixSymbol('B', 1, 3)
+    name_expr = ("test", [Equality(B, A[0,:]), A[1,:], A[:,0], A[:,1]])
+    result, = codegen(name_expr, "Julia", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function test(A)\n"
+        "    B = A[1,:]\n"
+        "    out2 = A[2,:]\n"
+        "    out3 = A[:,1]\n"
+        "    out4 = A[:,2]\n"
+        "    return B, out2, out3, out4\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_jl_loops():
+    # Note: an Julia programmer would probably vectorize this across one or
+    # more dimensions.  Also, size(A) would be used rather than passing in m
+    # and n.  Perhaps users would expect us to vectorize automatically here?
+    # Or is it possible to represent such things using IndexedBase?
+    from sympy.tensor import IndexedBase, Idx
+    from sympy.core.symbol import symbols
+    n, m = symbols('n m', integer=True)
+    A = IndexedBase('A')
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i = Idx('i', m)
+    j = Idx('j', n)
+    result, = codegen(('mat_vec_mult', Eq(y[i], A[i, j]*x[j])), "Julia",
+                      header=False, empty=False)
+    source = result[1]
+    expected = (
+        'function mat_vec_mult(y, A, m, n, x)\n'
+        '    for i = 1:m\n'
+        '        y[i] = 0\n'
+        '    end\n'
+        '    for i = 1:m\n'
+        '        for j = 1:n\n'
+        '            y[i] = %(rhs)s + y[i]\n'
+        '        end\n'
+        '    end\n'
+        '    return y\n'
+        'end\n'
+    )
+    assert (source == expected % {'rhs': 'A[%s,%s] .* x[j]' % (i, j)} or
+            source == expected % {'rhs': 'x[j] .* A[%s,%s]' % (i, j)})
+
+
+def test_jl_tensor_loops_multiple_contractions():
+    # see comments in previous test about vectorizing
+    from sympy.tensor import IndexedBase, Idx
+    from sympy.core.symbol import symbols
+    n, m, o, p = symbols('n m o p', integer=True)
+    A = IndexedBase('A')
+    B = IndexedBase('B')
+    y = IndexedBase('y')
+    i = Idx('i', m)
+    j = Idx('j', n)
+    k = Idx('k', o)
+    l = Idx('l', p)
+    result, = codegen(('tensorthing', Eq(y[i], B[j, k, l]*A[i, j, k, l])),
+                      "Julia", header=False, empty=False)
+    source = result[1]
+    expected = (
+        'function tensorthing(y, A, B, m, n, o, p)\n'
+        '    for i = 1:m\n'
+        '        y[i] = 0\n'
+        '    end\n'
+        '    for i = 1:m\n'
+        '        for j = 1:n\n'
+        '            for k = 1:o\n'
+        '                for l = 1:p\n'
+        '                    y[i] = A[i,j,k,l] .* B[j,k,l] + y[i]\n'
+        '                end\n'
+        '            end\n'
+        '        end\n'
+        '    end\n'
+        '    return y\n'
+        'end\n'
+    )
+    assert source == expected
+
+
+def test_jl_InOutArgument():
+    expr = Equality(x, x**2)
+    name_expr = ("mysqr", expr)
+    result, = codegen(name_expr, "Julia", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function mysqr(x)\n"
+        "    x = x .^ 2\n"
+        "    return x\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_jl_InOutArgument_order():
+    # can specify the order as (x, y)
+    expr = Equality(x, x**2 + y)
+    name_expr = ("test", expr)
+    result, = codegen(name_expr, "Julia", header=False,
+                      empty=False, argument_sequence=(x,y))
+    source = result[1]
+    expected = (
+        "function test(x, y)\n"
+        "    x = x .^ 2 + y\n"
+        "    return x\n"
+        "end\n"
+    )
+    assert source == expected
+    # make sure it gives (x, y) not (y, x)
+    expr = Equality(x, x**2 + y)
+    name_expr = ("test", expr)
+    result, = codegen(name_expr, "Julia", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function test(x, y)\n"
+        "    x = x .^ 2 + y\n"
+        "    return x\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_jl_not_supported():
+    f = Function('f')
+    name_expr = ("test", [f(x).diff(x), S.ComplexInfinity])
+    result, = codegen(name_expr, "Julia", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function test(x)\n"
+        "    # unsupported: Derivative(f(x), x)\n"
+        "    # unsupported: zoo\n"
+        "    out1 = Derivative(f(x), x)\n"
+        "    out2 = zoo\n"
+        "    return out1, out2\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_global_vars_octave():
+    x, y, z, t = symbols("x y z t")
+    result = codegen(('f', x*y), "Julia", header=False, empty=False,
+                     global_vars=(y,))
+    source = result[0][1]
+    expected = (
+        "function f(x)\n"
+        "    out1 = x .* y\n"
+        "    return out1\n"
+        "end\n"
+        )
+    assert source == expected
+
+    result = codegen(('f', x*y+z), "Julia", header=False, empty=False,
+                     argument_sequence=(x, y), global_vars=(z, t))
+    source = result[0][1]
+    expected = (
+        "function f(x, y)\n"
+        "    out1 = x .* y + z\n"
+        "    return out1\n"
+        "end\n"
+    )
+    assert source == expected
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_codegen_octave.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_codegen_octave.py
new file mode 100644
index 0000000000000000000000000000000000000000..77aaef7dd0d81d6855024e49fbb3d6d4c09f3384
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_codegen_octave.py
@@ -0,0 +1,589 @@
+from io import StringIO
+
+from sympy.core import S, symbols, Eq, pi, Catalan, EulerGamma, Function
+from sympy.core.relational import Equality
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.matrices import Matrix, MatrixSymbol
+from sympy.utilities.codegen import OctaveCodeGen, codegen, make_routine
+from sympy.testing.pytest import raises
+from sympy.testing.pytest import XFAIL
+import sympy
+
+
+x, y, z = symbols('x,y,z')
+
+
+def test_empty_m_code():
+    code_gen = OctaveCodeGen()
+    output = StringIO()
+    code_gen.dump_m([], output, "file", header=False, empty=False)
+    source = output.getvalue()
+    assert source == ""
+
+
+def test_m_simple_code():
+    name_expr = ("test", (x + y)*z)
+    result, = codegen(name_expr, "Octave", header=False, empty=False)
+    assert result[0] == "test.m"
+    source = result[1]
+    expected = (
+        "function out1 = test(x, y, z)\n"
+        "  out1 = z.*(x + y);\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_m_simple_code_with_header():
+    name_expr = ("test", (x + y)*z)
+    result, = codegen(name_expr, "Octave", header=True, empty=False)
+    assert result[0] == "test.m"
+    source = result[1]
+    expected = (
+        "function out1 = test(x, y, z)\n"
+        "  %TEST  Autogenerated by SymPy\n"
+        "  %   Code generated with SymPy " + sympy.__version__ + "\n"
+        "  %\n"
+        "  %   See http://www.sympy.org/ for more information.\n"
+        "  %\n"
+        "  %   This file is part of 'project'\n"
+        "  out1 = z.*(x + y);\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_m_simple_code_nameout():
+    expr = Equality(z, (x + y))
+    name_expr = ("test", expr)
+    result, = codegen(name_expr, "Octave", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function z = test(x, y)\n"
+        "  z = x + y;\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_m_numbersymbol():
+    name_expr = ("test", pi**Catalan)
+    result, = codegen(name_expr, "Octave", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function out1 = test()\n"
+        "  out1 = pi^%s;\n"
+        "end\n"
+    ) % Catalan.evalf(17)
+    assert source == expected
+
+
+@XFAIL
+def test_m_numbersymbol_no_inline():
+    # FIXME: how to pass inline=False to the OctaveCodePrinter?
+    name_expr = ("test", [pi**Catalan, EulerGamma])
+    result, = codegen(name_expr, "Octave", header=False,
+                      empty=False, inline=False)
+    source = result[1]
+    expected = (
+        "function [out1, out2] = test()\n"
+        "  Catalan = 0.915965594177219;  % constant\n"
+        "  EulerGamma = 0.5772156649015329;  % constant\n"
+        "  out1 = pi^Catalan;\n"
+        "  out2 = EulerGamma;\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_m_code_argument_order():
+    expr = x + y
+    routine = make_routine("test", expr, argument_sequence=[z, x, y], language="octave")
+    code_gen = OctaveCodeGen()
+    output = StringIO()
+    code_gen.dump_m([routine], output, "test", header=False, empty=False)
+    source = output.getvalue()
+    expected = (
+        "function out1 = test(z, x, y)\n"
+        "  out1 = x + y;\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_multiple_results_m():
+    # Here the output order is the input order
+    expr1 = (x + y)*z
+    expr2 = (x - y)*z
+    name_expr = ("test", [expr1, expr2])
+    result, = codegen(name_expr, "Octave", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function [out1, out2] = test(x, y, z)\n"
+        "  out1 = z.*(x + y);\n"
+        "  out2 = z.*(x - y);\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_results_named_unordered():
+    # Here output order is based on name_expr
+    A, B, C = symbols('A,B,C')
+    expr1 = Equality(C, (x + y)*z)
+    expr2 = Equality(A, (x - y)*z)
+    expr3 = Equality(B, 2*x)
+    name_expr = ("test", [expr1, expr2, expr3])
+    result, = codegen(name_expr, "Octave", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function [C, A, B] = test(x, y, z)\n"
+        "  C = z.*(x + y);\n"
+        "  A = z.*(x - y);\n"
+        "  B = 2*x;\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_results_named_ordered():
+    A, B, C = symbols('A,B,C')
+    expr1 = Equality(C, (x + y)*z)
+    expr2 = Equality(A, (x - y)*z)
+    expr3 = Equality(B, 2*x)
+    name_expr = ("test", [expr1, expr2, expr3])
+    result = codegen(name_expr, "Octave", header=False, empty=False,
+                     argument_sequence=(x, z, y))
+    assert result[0][0] == "test.m"
+    source = result[0][1]
+    expected = (
+        "function [C, A, B] = test(x, z, y)\n"
+        "  C = z.*(x + y);\n"
+        "  A = z.*(x - y);\n"
+        "  B = 2*x;\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_complicated_m_codegen():
+    from sympy.functions.elementary.trigonometric import (cos, sin, tan)
+    name_expr = ("testlong",
+            [ ((sin(x) + cos(y) + tan(z))**3).expand(),
+            cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))
+    ])
+    result = codegen(name_expr, "Octave", header=False, empty=False)
+    assert result[0][0] == "testlong.m"
+    source = result[0][1]
+    expected = (
+        "function [out1, out2] = testlong(x, y, z)\n"
+        "  out1 = sin(x).^3 + 3*sin(x).^2.*cos(y) + 3*sin(x).^2.*tan(z)"
+        " + 3*sin(x).*cos(y).^2 + 6*sin(x).*cos(y).*tan(z) + 3*sin(x).*tan(z).^2"
+        " + cos(y).^3 + 3*cos(y).^2.*tan(z) + 3*cos(y).*tan(z).^2 + tan(z).^3;\n"
+        "  out2 = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))));\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_m_output_arg_mixed_unordered():
+    # named outputs are alphabetical, unnamed output appear in the given order
+    from sympy.functions.elementary.trigonometric import (cos, sin)
+    a = symbols("a")
+    name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))])
+    result, = codegen(name_expr, "Octave", header=False, empty=False)
+    assert result[0] == "foo.m"
+    source = result[1]
+    expected = (
+        'function [out1, y, out3, a] = foo(x)\n'
+        '  out1 = cos(2*x);\n'
+        '  y = sin(x);\n'
+        '  out3 = cos(x);\n'
+        '  a = sin(2*x);\n'
+        'end\n'
+    )
+    assert source == expected
+
+
+def test_m_piecewise_():
+    pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True), evaluate=False)
+    name_expr = ("pwtest", pw)
+    result, = codegen(name_expr, "Octave", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function out1 = pwtest(x)\n"
+        "  out1 = ((x < -1).*(0) + (~(x < -1)).*( ...\n"
+        "  (x <= 1).*(x.^2) + (~(x <= 1)).*( ...\n"
+        "  (x > 1).*(2 - x) + (~(x > 1)).*(1))));\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+@XFAIL
+def test_m_piecewise_no_inline():
+    # FIXME: how to pass inline=False to the OctaveCodePrinter?
+    pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True))
+    name_expr = ("pwtest", pw)
+    result, = codegen(name_expr, "Octave", header=False, empty=False,
+                      inline=False)
+    source = result[1]
+    expected = (
+        "function out1 = pwtest(x)\n"
+        "  if (x < -1)\n"
+        "    out1 = 0;\n"
+        "  elseif (x <= 1)\n"
+        "    out1 = x.^2;\n"
+        "  elseif (x > 1)\n"
+        "    out1 = -x + 2;\n"
+        "  else\n"
+        "    out1 = 1;\n"
+        "  end\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_m_multifcns_per_file():
+    name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
+    result = codegen(name_expr, "Octave", header=False, empty=False)
+    assert result[0][0] == "foo.m"
+    source = result[0][1]
+    expected = (
+        "function [out1, out2] = foo(x, y)\n"
+        "  out1 = 2*x;\n"
+        "  out2 = 3*y;\n"
+        "end\n"
+        "function [out1, out2] = bar(y)\n"
+        "  out1 = y.^2;\n"
+        "  out2 = 4*y;\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_m_multifcns_per_file_w_header():
+    name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
+    result = codegen(name_expr, "Octave", header=True, empty=False)
+    assert result[0][0] == "foo.m"
+    source = result[0][1]
+    expected = (
+        "function [out1, out2] = foo(x, y)\n"
+        "  %FOO  Autogenerated by SymPy\n"
+        "  %   Code generated with SymPy " + sympy.__version__ + "\n"
+        "  %\n"
+        "  %   See http://www.sympy.org/ for more information.\n"
+        "  %\n"
+        "  %   This file is part of 'project'\n"
+        "  out1 = 2*x;\n"
+        "  out2 = 3*y;\n"
+        "end\n"
+        "function [out1, out2] = bar(y)\n"
+        "  out1 = y.^2;\n"
+        "  out2 = 4*y;\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_m_filename_match_first_fcn():
+    name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
+    raises(ValueError, lambda: codegen(name_expr,
+                        "Octave", prefix="bar", header=False, empty=False))
+
+
+def test_m_matrix_named():
+    e2 = Matrix([[x, 2*y, pi*z]])
+    name_expr = ("test", Equality(MatrixSymbol('myout1', 1, 3), e2))
+    result = codegen(name_expr, "Octave", header=False, empty=False)
+    assert result[0][0] == "test.m"
+    source = result[0][1]
+    expected = (
+        "function myout1 = test(x, y, z)\n"
+        "  myout1 = [x 2*y pi*z];\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_m_matrix_named_matsym():
+    myout1 = MatrixSymbol('myout1', 1, 3)
+    e2 = Matrix([[x, 2*y, pi*z]])
+    name_expr = ("test", Equality(myout1, e2, evaluate=False))
+    result, = codegen(name_expr, "Octave", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function myout1 = test(x, y, z)\n"
+        "  myout1 = [x 2*y pi*z];\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_m_matrix_output_autoname():
+    expr = Matrix([[x, x+y, 3]])
+    name_expr = ("test", expr)
+    result, = codegen(name_expr, "Octave", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function out1 = test(x, y)\n"
+        "  out1 = [x x + y 3];\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_m_matrix_output_autoname_2():
+    e1 = (x + y)
+    e2 = Matrix([[2*x, 2*y, 2*z]])
+    e3 = Matrix([[x], [y], [z]])
+    e4 = Matrix([[x, y], [z, 16]])
+    name_expr = ("test", (e1, e2, e3, e4))
+    result, = codegen(name_expr, "Octave", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function [out1, out2, out3, out4] = test(x, y, z)\n"
+        "  out1 = x + y;\n"
+        "  out2 = [2*x 2*y 2*z];\n"
+        "  out3 = [x; y; z];\n"
+        "  out4 = [x y; z 16];\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_m_results_matrix_named_ordered():
+    B, C = symbols('B,C')
+    A = MatrixSymbol('A', 1, 3)
+    expr1 = Equality(C, (x + y)*z)
+    expr2 = Equality(A, Matrix([[1, 2, x]]))
+    expr3 = Equality(B, 2*x)
+    name_expr = ("test", [expr1, expr2, expr3])
+    result, = codegen(name_expr, "Octave", header=False, empty=False,
+                     argument_sequence=(x, z, y))
+    source = result[1]
+    expected = (
+        "function [C, A, B] = test(x, z, y)\n"
+        "  C = z.*(x + y);\n"
+        "  A = [1 2 x];\n"
+        "  B = 2*x;\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_m_matrixsymbol_slice():
+    A = MatrixSymbol('A', 2, 3)
+    B = MatrixSymbol('B', 1, 3)
+    C = MatrixSymbol('C', 1, 3)
+    D = MatrixSymbol('D', 2, 1)
+    name_expr = ("test", [Equality(B, A[0, :]),
+                          Equality(C, A[1, :]),
+                          Equality(D, A[:, 2])])
+    result, = codegen(name_expr, "Octave", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function [B, C, D] = test(A)\n"
+        "  B = A(1, :);\n"
+        "  C = A(2, :);\n"
+        "  D = A(:, 3);\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_m_matrixsymbol_slice2():
+    A = MatrixSymbol('A', 3, 4)
+    B = MatrixSymbol('B', 2, 2)
+    C = MatrixSymbol('C', 2, 2)
+    name_expr = ("test", [Equality(B, A[0:2, 0:2]),
+                          Equality(C, A[0:2, 1:3])])
+    result, = codegen(name_expr, "Octave", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function [B, C] = test(A)\n"
+        "  B = A(1:2, 1:2);\n"
+        "  C = A(1:2, 2:3);\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_m_matrixsymbol_slice3():
+    A = MatrixSymbol('A', 8, 7)
+    B = MatrixSymbol('B', 2, 2)
+    C = MatrixSymbol('C', 4, 2)
+    name_expr = ("test", [Equality(B, A[6:, 1::3]),
+                          Equality(C, A[::2, ::3])])
+    result, = codegen(name_expr, "Octave", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function [B, C] = test(A)\n"
+        "  B = A(7:end, 2:3:end);\n"
+        "  C = A(1:2:end, 1:3:end);\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_m_matrixsymbol_slice_autoname():
+    A = MatrixSymbol('A', 2, 3)
+    B = MatrixSymbol('B', 1, 3)
+    name_expr = ("test", [Equality(B, A[0,:]), A[1,:], A[:,0], A[:,1]])
+    result, = codegen(name_expr, "Octave", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function [B, out2, out3, out4] = test(A)\n"
+        "  B = A(1, :);\n"
+        "  out2 = A(2, :);\n"
+        "  out3 = A(:, 1);\n"
+        "  out4 = A(:, 2);\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_m_loops():
+    # Note: an Octave programmer would probably vectorize this across one or
+    # more dimensions.  Also, size(A) would be used rather than passing in m
+    # and n.  Perhaps users would expect us to vectorize automatically here?
+    # Or is it possible to represent such things using IndexedBase?
+    from sympy.tensor import IndexedBase, Idx
+    from sympy.core.symbol import symbols
+    n, m = symbols('n m', integer=True)
+    A = IndexedBase('A')
+    x = IndexedBase('x')
+    y = IndexedBase('y')
+    i = Idx('i', m)
+    j = Idx('j', n)
+    result, = codegen(('mat_vec_mult', Eq(y[i], A[i, j]*x[j])), "Octave",
+                      header=False, empty=False)
+    source = result[1]
+    expected = (
+        'function y = mat_vec_mult(A, m, n, x)\n'
+        '  for i = 1:m\n'
+        '    y(i) = 0;\n'
+        '  end\n'
+        '  for i = 1:m\n'
+        '    for j = 1:n\n'
+        '      y(i) = %(rhs)s + y(i);\n'
+        '    end\n'
+        '  end\n'
+        'end\n'
+    )
+    assert (source == expected % {'rhs': 'A(%s, %s).*x(j)' % (i, j)} or
+            source == expected % {'rhs': 'x(j).*A(%s, %s)' % (i, j)})
+
+
+def test_m_tensor_loops_multiple_contractions():
+    # see comments in previous test about vectorizing
+    from sympy.tensor import IndexedBase, Idx
+    from sympy.core.symbol import symbols
+    n, m, o, p = symbols('n m o p', integer=True)
+    A = IndexedBase('A')
+    B = IndexedBase('B')
+    y = IndexedBase('y')
+    i = Idx('i', m)
+    j = Idx('j', n)
+    k = Idx('k', o)
+    l = Idx('l', p)
+    result, = codegen(('tensorthing', Eq(y[i], B[j, k, l]*A[i, j, k, l])),
+                      "Octave", header=False, empty=False)
+    source = result[1]
+    expected = (
+        'function y = tensorthing(A, B, m, n, o, p)\n'
+        '  for i = 1:m\n'
+        '    y(i) = 0;\n'
+        '  end\n'
+        '  for i = 1:m\n'
+        '    for j = 1:n\n'
+        '      for k = 1:o\n'
+        '        for l = 1:p\n'
+        '          y(i) = A(i, j, k, l).*B(j, k, l) + y(i);\n'
+        '        end\n'
+        '      end\n'
+        '    end\n'
+        '  end\n'
+        'end\n'
+    )
+    assert source == expected
+
+
+def test_m_InOutArgument():
+    expr = Equality(x, x**2)
+    name_expr = ("mysqr", expr)
+    result, = codegen(name_expr, "Octave", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function x = mysqr(x)\n"
+        "  x = x.^2;\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_m_InOutArgument_order():
+    # can specify the order as (x, y)
+    expr = Equality(x, x**2 + y)
+    name_expr = ("test", expr)
+    result, = codegen(name_expr, "Octave", header=False,
+                      empty=False, argument_sequence=(x,y))
+    source = result[1]
+    expected = (
+        "function x = test(x, y)\n"
+        "  x = x.^2 + y;\n"
+        "end\n"
+    )
+    assert source == expected
+    # make sure it gives (x, y) not (y, x)
+    expr = Equality(x, x**2 + y)
+    name_expr = ("test", expr)
+    result, = codegen(name_expr, "Octave", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function x = test(x, y)\n"
+        "  x = x.^2 + y;\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_m_not_supported():
+    f = Function('f')
+    name_expr = ("test", [f(x).diff(x), S.ComplexInfinity])
+    result, = codegen(name_expr, "Octave", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "function [out1, out2] = test(x)\n"
+        "  % unsupported: Derivative(f(x), x)\n"
+        "  % unsupported: zoo\n"
+        "  out1 = Derivative(f(x), x);\n"
+        "  out2 = zoo;\n"
+        "end\n"
+    )
+    assert source == expected
+
+
+def test_global_vars_octave():
+    x, y, z, t = symbols("x y z t")
+    result = codegen(('f', x*y), "Octave", header=False, empty=False,
+                     global_vars=(y,))
+    source = result[0][1]
+    expected = (
+        "function out1 = f(x)\n"
+        "  global y\n"
+        "  out1 = x.*y;\n"
+        "end\n"
+        )
+    assert source == expected
+
+    result = codegen(('f', x*y+z), "Octave", header=False, empty=False,
+                     argument_sequence=(x, y), global_vars=(z, t))
+    source = result[0][1]
+    expected = (
+        "function out1 = f(x, y)\n"
+        "  global t z\n"
+        "  out1 = x.*y + z;\n"
+        "end\n"
+    )
+    assert source == expected
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_codegen_rust.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_codegen_rust.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc7f82158ae8fa7dfe34bf909aa695b119fb9526
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_codegen_rust.py
@@ -0,0 +1,401 @@
+from io import StringIO
+
+from sympy.core import S, symbols, pi, Catalan, EulerGamma, Function
+from sympy.core.relational import Equality
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.utilities.codegen import RustCodeGen, codegen, make_routine
+from sympy.testing.pytest import XFAIL
+import sympy
+
+
+x, y, z = symbols('x,y,z')
+
+
+def test_empty_rust_code():
+    code_gen = RustCodeGen()
+    output = StringIO()
+    code_gen.dump_rs([], output, "file", header=False, empty=False)
+    source = output.getvalue()
+    assert source == ""
+
+
+def test_simple_rust_code():
+    name_expr = ("test", (x + y)*z)
+    result, = codegen(name_expr, "Rust", header=False, empty=False)
+    assert result[0] == "test.rs"
+    source = result[1]
+    expected = (
+        "fn test(x: f64, y: f64, z: f64) -> f64 {\n"
+        "    let out1 = z*(x + y);\n"
+        "    out1\n"
+        "}\n"
+    )
+    assert source == expected
+
+
+def test_simple_code_with_header():
+    name_expr = ("test", (x + y)*z)
+    result, = codegen(name_expr, "Rust", header=True, empty=False)
+    assert result[0] == "test.rs"
+    source = result[1]
+    version_str = "Code generated with SymPy %s" % sympy.__version__
+    version_line = version_str.center(76).rstrip()
+    expected = (
+        "/*\n"
+        " *%(version_line)s\n"
+        " *\n"
+        " *              See http://www.sympy.org/ for more information.\n"
+        " *\n"
+        " *                       This file is part of 'project'\n"
+        " */\n"
+        "fn test(x: f64, y: f64, z: f64) -> f64 {\n"
+        "    let out1 = z*(x + y);\n"
+        "    out1\n"
+        "}\n"
+    ) % {'version_line': version_line}
+    assert source == expected
+
+
+def test_simple_code_nameout():
+    expr = Equality(z, (x + y))
+    name_expr = ("test", expr)
+    result, = codegen(name_expr, "Rust", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "fn test(x: f64, y: f64) -> f64 {\n"
+        "    let z = x + y;\n"
+        "    z\n"
+        "}\n"
+    )
+    assert source == expected
+
+
+def test_numbersymbol():
+    name_expr = ("test", pi**Catalan)
+    result, = codegen(name_expr, "Rust", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "fn test() -> f64 {\n"
+        "    const Catalan: f64 = %s;\n"
+        "    let out1 = PI.powf(Catalan);\n"
+        "    out1\n"
+        "}\n"
+    ) % Catalan.evalf(17)
+    assert source == expected
+
+
+@XFAIL
+def test_numbersymbol_inline():
+    # FIXME: how to pass inline to the RustCodePrinter?
+    name_expr = ("test", [pi**Catalan, EulerGamma])
+    result, = codegen(name_expr, "Rust", header=False,
+                      empty=False, inline=True)
+    source = result[1]
+    expected = (
+        "fn test() -> (f64, f64) {\n"
+        "    const Catalan: f64 = %s;\n"
+        "    const EulerGamma: f64 = %s;\n"
+        "    let out1 = PI.powf(Catalan);\n"
+        "    let out2 = EulerGamma);\n"
+        "    (out1, out2)\n"
+        "}\n"
+    ) % (Catalan.evalf(17), EulerGamma.evalf(17))
+    assert source == expected
+
+
+def test_argument_order():
+    expr = x + y
+    routine = make_routine("test", expr, argument_sequence=[z, x, y], language="rust")
+    code_gen = RustCodeGen()
+    output = StringIO()
+    code_gen.dump_rs([routine], output, "test", header=False, empty=False)
+    source = output.getvalue()
+    expected = (
+        "fn test(z: f64, x: f64, y: f64) -> f64 {\n"
+        "    let out1 = x + y;\n"
+        "    out1\n"
+        "}\n"
+    )
+    assert source == expected
+
+
+def test_multiple_results_rust():
+    # Here the output order is the input order
+    expr1 = (x + y)*z
+    expr2 = (x - y)*z
+    name_expr = ("test", [expr1, expr2])
+    result, = codegen(name_expr, "Rust", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "fn test(x: f64, y: f64, z: f64) -> (f64, f64) {\n"
+        "    let out1 = z*(x + y);\n"
+        "    let out2 = z*(x - y);\n"
+        "    (out1, out2)\n"
+        "}\n"
+    )
+    assert source == expected
+
+
+def test_results_named_unordered():
+    # Here output order is based on name_expr
+    A, B, C = symbols('A,B,C')
+    expr1 = Equality(C, (x + y)*z)
+    expr2 = Equality(A, (x - y)*z)
+    expr3 = Equality(B, 2*x)
+    name_expr = ("test", [expr1, expr2, expr3])
+    result, = codegen(name_expr, "Rust", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "fn test(x: f64, y: f64, z: f64) -> (f64, f64, f64) {\n"
+        "    let C = z*(x + y);\n"
+        "    let A = z*(x - y);\n"
+        "    let B = 2*x;\n"
+        "    (C, A, B)\n"
+        "}\n"
+    )
+    assert source == expected
+
+
+def test_results_named_ordered():
+    A, B, C = symbols('A,B,C')
+    expr1 = Equality(C, (x + y)*z)
+    expr2 = Equality(A, (x - y)*z)
+    expr3 = Equality(B, 2*x)
+    name_expr = ("test", [expr1, expr2, expr3])
+    result = codegen(name_expr, "Rust", header=False, empty=False,
+                     argument_sequence=(x, z, y))
+    assert result[0][0] == "test.rs"
+    source = result[0][1]
+    expected = (
+        "fn test(x: f64, z: f64, y: f64) -> (f64, f64, f64) {\n"
+        "    let C = z*(x + y);\n"
+        "    let A = z*(x - y);\n"
+        "    let B = 2*x;\n"
+        "    (C, A, B)\n"
+        "}\n"
+    )
+    assert source == expected
+
+
+def test_complicated_rs_codegen():
+    from sympy.functions.elementary.trigonometric import (cos, sin, tan)
+    name_expr = ("testlong",
+            [ ((sin(x) + cos(y) + tan(z))**3).expand(),
+            cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))
+    ])
+    result = codegen(name_expr, "Rust", header=False, empty=False)
+    assert result[0][0] == "testlong.rs"
+    source = result[0][1]
+    expected = (
+        "fn testlong(x: f64, y: f64, z: f64) -> (f64, f64) {\n"
+        "    let out1 = x.sin().powi(3) + 3*x.sin().powi(2)*y.cos()"
+        " + 3*x.sin().powi(2)*z.tan() + 3*x.sin()*y.cos().powi(2)"
+        " + 6*x.sin()*y.cos()*z.tan() + 3*x.sin()*z.tan().powi(2)"
+        " + y.cos().powi(3) + 3*y.cos().powi(2)*z.tan()"
+        " + 3*y.cos()*z.tan().powi(2) + z.tan().powi(3);\n"
+        "    let out2 = (x + y + z).cos().cos().cos().cos()"
+        ".cos().cos().cos().cos();\n"
+        "    (out1, out2)\n"
+        "}\n"
+    )
+    assert source == expected
+
+
+def test_output_arg_mixed_unordered():
+    # named outputs are alphabetical, unnamed output appear in the given order
+    from sympy.functions.elementary.trigonometric import (cos, sin)
+    a = symbols("a")
+    name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))])
+    result, = codegen(name_expr, "Rust", header=False, empty=False)
+    assert result[0] == "foo.rs"
+    source = result[1]
+    expected = (
+        "fn foo(x: f64) -> (f64, f64, f64, f64) {\n"
+        "    let out1 = (2*x).cos();\n"
+        "    let y = x.sin();\n"
+        "    let out3 = x.cos();\n"
+        "    let a = (2*x).sin();\n"
+        "    (out1, y, out3, a)\n"
+        "}\n"
+    )
+    assert source == expected
+
+
+def test_piecewise_():
+    pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True), evaluate=False)
+    name_expr = ("pwtest", pw)
+    result, = codegen(name_expr, "Rust", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "fn pwtest(x: f64) -> f64 {\n"
+        "    let out1 = if (x < -1.0) {\n"
+        "        0\n"
+        "    } else if (x <= 1.0) {\n"
+        "        x.powi(2)\n"
+        "    } else if (x > 1.0) {\n"
+        "        2 - x\n"
+        "    } else {\n"
+        "        1\n"
+        "    };\n"
+        "    out1\n"
+        "}\n"
+    )
+    assert source == expected
+
+
+@XFAIL
+def test_piecewise_inline():
+    # FIXME: how to pass inline to the RustCodePrinter?
+    pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True))
+    name_expr = ("pwtest", pw)
+    result, = codegen(name_expr, "Rust", header=False, empty=False,
+                      inline=True)
+    source = result[1]
+    expected = (
+        "fn pwtest(x: f64) -> f64 {\n"
+        "    let out1 = if (x < -1) { 0 } else if (x <= 1) { x.powi(2) }"
+        " else if (x > 1) { -x + 2 } else { 1 };\n"
+        "    out1\n"
+        "}\n"
+    )
+    assert source == expected
+
+
+def test_multifcns_per_file():
+    name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
+    result = codegen(name_expr, "Rust", header=False, empty=False)
+    assert result[0][0] == "foo.rs"
+    source = result[0][1]
+    expected = (
+        "fn foo(x: f64, y: f64) -> (f64, f64) {\n"
+        "    let out1 = 2*x;\n"
+        "    let out2 = 3*y;\n"
+        "    (out1, out2)\n"
+        "}\n"
+        "fn bar(y: f64) -> (f64, f64) {\n"
+        "    let out1 = y.powi(2);\n"
+        "    let out2 = 4*y;\n"
+        "    (out1, out2)\n"
+        "}\n"
+    )
+    assert source == expected
+
+
+def test_multifcns_per_file_w_header():
+    name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
+    result = codegen(name_expr, "Rust", header=True, empty=False)
+    assert result[0][0] == "foo.rs"
+    source = result[0][1]
+    version_str = "Code generated with SymPy %s" % sympy.__version__
+    version_line = version_str.center(76).rstrip()
+    expected = (
+        "/*\n"
+        " *%(version_line)s\n"
+        " *\n"
+        " *              See http://www.sympy.org/ for more information.\n"
+        " *\n"
+        " *                       This file is part of 'project'\n"
+        " */\n"
+        "fn foo(x: f64, y: f64) -> (f64, f64) {\n"
+        "    let out1 = 2*x;\n"
+        "    let out2 = 3*y;\n"
+        "    (out1, out2)\n"
+        "}\n"
+        "fn bar(y: f64) -> (f64, f64) {\n"
+        "    let out1 = y.powi(2);\n"
+        "    let out2 = 4*y;\n"
+        "    (out1, out2)\n"
+        "}\n"
+    ) % {'version_line': version_line}
+    assert source == expected
+
+
+def test_filename_match_prefix():
+    name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ]
+    result, = codegen(name_expr, "Rust", prefix="baz", header=False,
+                     empty=False)
+    assert result[0] == "baz.rs"
+
+
+def test_InOutArgument():
+    expr = Equality(x, x**2)
+    name_expr = ("mysqr", expr)
+    result, = codegen(name_expr, "Rust", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "fn mysqr(x: f64) -> f64 {\n"
+        "    let x = x.powi(2);\n"
+        "    x\n"
+        "}\n"
+    )
+    assert source == expected
+
+
+def test_InOutArgument_order():
+    # can specify the order as (x, y)
+    expr = Equality(x, x**2 + y)
+    name_expr = ("test", expr)
+    result, = codegen(name_expr, "Rust", header=False,
+                      empty=False, argument_sequence=(x,y))
+    source = result[1]
+    expected = (
+        "fn test(x: f64, y: f64) -> f64 {\n"
+        "    let x = x.powi(2) + y;\n"
+        "    x\n"
+        "}\n"
+    )
+    assert source == expected
+    # make sure it gives (x, y) not (y, x)
+    expr = Equality(x, x**2 + y)
+    name_expr = ("test", expr)
+    result, = codegen(name_expr, "Rust", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "fn test(x: f64, y: f64) -> f64 {\n"
+        "    let x = x.powi(2) + y;\n"
+        "    x\n"
+        "}\n"
+    )
+    assert source == expected
+
+
+def test_not_supported():
+    f = Function('f')
+    name_expr = ("test", [f(x).diff(x), S.ComplexInfinity])
+    result, = codegen(name_expr, "Rust", header=False, empty=False)
+    source = result[1]
+    expected = (
+        "fn test(x: f64) -> (f64, f64) {\n"
+        "    // unsupported: Derivative(f(x), x)\n"
+        "    // unsupported: zoo\n"
+        "    let out1 = Derivative(f(x), x);\n"
+        "    let out2 = zoo;\n"
+        "    (out1, out2)\n"
+        "}\n"
+    )
+    assert source == expected
+
+
+def test_global_vars_rust():
+    x, y, z, t = symbols("x y z t")
+    result = codegen(('f', x*y), "Rust", header=False, empty=False,
+                     global_vars=(y,))
+    source = result[0][1]
+    expected = (
+        "fn f(x: f64) -> f64 {\n"
+        "    let out1 = x*y;\n"
+        "    out1\n"
+        "}\n"
+        )
+    assert source == expected
+
+    result = codegen(('f', x*y+z), "Rust", header=False, empty=False,
+                     argument_sequence=(x, y), global_vars=(z, t))
+    source = result[0][1]
+    expected = (
+        "fn f(x: f64, y: f64) -> f64 {\n"
+        "    let out1 = x*y + z;\n"
+        "    out1\n"
+        "}\n"
+    )
+    assert source == expected
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_decorator.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_decorator.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1870d4db8f719fdabfeab14120bfb3ce10131a9
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_decorator.py
@@ -0,0 +1,129 @@
+from functools import wraps
+
+from sympy.utilities.decorator import threaded, xthreaded, memoize_property, deprecated
+from sympy.testing.pytest import warns_deprecated_sympy
+
+from sympy.core.basic import Basic
+from sympy.core.relational import Eq
+from sympy.matrices.dense import Matrix
+
+from sympy.abc import x, y
+
+
+def test_threaded():
+    @threaded
+    def function(expr, *args):
+        return 2*expr + sum(args)
+
+    assert function(Matrix([[x, y], [1, x]]), 1, 2) == \
+        Matrix([[2*x + 3, 2*y + 3], [5, 2*x + 3]])
+
+    assert function(Eq(x, y), 1, 2) == Eq(2*x + 3, 2*y + 3)
+
+    assert function([x, y], 1, 2) == [2*x + 3, 2*y + 3]
+    assert function((x, y), 1, 2) == (2*x + 3, 2*y + 3)
+
+    assert function({x, y}, 1, 2) == {2*x + 3, 2*y + 3}
+
+    @threaded
+    def function(expr, n):
+        return expr**n
+
+    assert function(x + y, 2) == x**2 + y**2
+    assert function(x, 2) == x**2
+
+
+def test_xthreaded():
+    @xthreaded
+    def function(expr, n):
+        return expr**n
+
+    assert function(x + y, 2) == (x + y)**2
+
+
+def test_wraps():
+    def my_func(x):
+        """My function. """
+
+    my_func.is_my_func = True
+
+    new_my_func = threaded(my_func)
+    new_my_func = wraps(my_func)(new_my_func)
+
+    assert new_my_func.__name__ == 'my_func'
+    assert new_my_func.__doc__ == 'My function. '
+    assert hasattr(new_my_func, 'is_my_func')
+    assert new_my_func.is_my_func is True
+
+
+def test_memoize_property():
+    class TestMemoize(Basic):
+        @memoize_property
+        def prop(self):
+            return Basic()
+
+    member = TestMemoize()
+    obj1 = member.prop
+    obj2 = member.prop
+    assert obj1 is obj2
+
+def test_deprecated():
+    @deprecated('deprecated_function is deprecated',
+                deprecated_since_version='1.10',
+                # This is the target at the top of the file, which will never
+                # go away.
+                active_deprecations_target='active-deprecations')
+    def deprecated_function(x):
+        return x
+
+    with warns_deprecated_sympy():
+        assert deprecated_function(1) == 1
+
+    @deprecated('deprecated_class is deprecated',
+                deprecated_since_version='1.10',
+                active_deprecations_target='active-deprecations')
+    class deprecated_class:
+        pass
+
+    with warns_deprecated_sympy():
+        assert isinstance(deprecated_class(), deprecated_class)
+
+    # Ensure the class decorator works even when the class never returns
+    # itself
+    @deprecated('deprecated_class_new is deprecated',
+                deprecated_since_version='1.10',
+                active_deprecations_target='active-deprecations')
+    class deprecated_class_new:
+        def __new__(cls, arg):
+            return arg
+
+    with warns_deprecated_sympy():
+        assert deprecated_class_new(1) == 1
+
+    @deprecated('deprecated_class_init is deprecated',
+                deprecated_since_version='1.10',
+                active_deprecations_target='active-deprecations')
+    class deprecated_class_init:
+        def __init__(self, arg):
+            self.arg = 1
+
+    with warns_deprecated_sympy():
+        assert deprecated_class_init(1).arg == 1
+
+    @deprecated('deprecated_class_new_init is deprecated',
+                deprecated_since_version='1.10',
+                active_deprecations_target='active-deprecations')
+    class deprecated_class_new_init:
+        def __new__(cls, arg):
+            if arg == 0:
+                return arg
+            return object.__new__(cls)
+
+        def __init__(self, arg):
+            self.arg = 1
+
+    with warns_deprecated_sympy():
+        assert deprecated_class_new_init(0) == 0
+
+    with warns_deprecated_sympy():
+        assert deprecated_class_new_init(1).arg == 1
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_deprecated.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_deprecated.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd4534ef1abc38ff368011b3ef9d11c497f3675b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_deprecated.py
@@ -0,0 +1,13 @@
+from sympy.testing.pytest import warns_deprecated_sympy
+
+# See https://github.com/sympy/sympy/pull/18095
+
+def test_deprecated_utilities():
+    with warns_deprecated_sympy():
+        import sympy.utilities.pytest  # noqa:F401
+    with warns_deprecated_sympy():
+        import sympy.utilities.runtests  # noqa:F401
+    with warns_deprecated_sympy():
+        import sympy.utilities.randtest  # noqa:F401
+    with warns_deprecated_sympy():
+        import sympy.utilities.tmpfiles  # noqa:F401
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_enumerative.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_enumerative.py
new file mode 100644
index 0000000000000000000000000000000000000000..357499d5fd400b14e2bcad067f3015b74b0e9003
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_enumerative.py
@@ -0,0 +1,179 @@
+import string
+from itertools import zip_longest
+
+from sympy.utilities.enumerative import (
+    list_visitor,
+    MultisetPartitionTraverser,
+    multiset_partitions_taocp
+    )
+from sympy.utilities.iterables import _set_partitions
+
+# first some functions only useful as test scaffolding - these provide
+# straightforward, but slow reference implementations against which to
+# compare the real versions, and also a comparison to verify that
+# different versions are giving identical results.
+
+def part_range_filter(partition_iterator, lb, ub):
+    """
+    Filters (on the number of parts) a multiset partition enumeration
+
+    Arguments
+    =========
+
+    lb, and ub are a range (in the Python slice sense) on the lpart
+    variable returned from a multiset partition enumeration.  Recall
+    that lpart is 0-based (it points to the topmost part on the part
+    stack), so if you want to return parts of sizes 2,3,4,5 you would
+    use lb=1 and ub=5.
+    """
+    for state in partition_iterator:
+        f, lpart, pstack = state
+        if lpart >= lb and lpart < ub:
+            yield state
+
+def multiset_partitions_baseline(multiplicities, components):
+    """Enumerates partitions of a multiset
+
+    Parameters
+    ==========
+
+    multiplicities
+         list of integer multiplicities of the components of the multiset.
+
+    components
+         the components (elements) themselves
+
+    Returns
+    =======
+
+    Set of partitions.  Each partition is tuple of parts, and each
+    part is a tuple of components (with repeats to indicate
+    multiplicity)
+
+    Notes
+    =====
+
+    Multiset partitions can be created as equivalence classes of set
+    partitions, and this function does just that.  This approach is
+    slow and memory intensive compared to the more advanced algorithms
+    available, but the code is simple and easy to understand.  Hence
+    this routine is strictly for testing -- to provide a
+    straightforward baseline against which to regress the production
+    versions.  (This code is a simplified version of an earlier
+    production implementation.)
+    """
+
+    canon = []                  # list of components with repeats
+    for ct, elem in zip(multiplicities, components):
+        canon.extend([elem]*ct)
+
+    # accumulate the multiset partitions in a set to eliminate dups
+    cache = set()
+    n = len(canon)
+    for nc, q in _set_partitions(n):
+        rv = [[] for i in range(nc)]
+        for i in range(n):
+            rv[q[i]].append(canon[i])
+        canonical = tuple(
+            sorted([tuple(p) for p in rv]))
+        cache.add(canonical)
+    return cache
+
+
+def compare_multiset_w_baseline(multiplicities):
+    """
+    Enumerates the partitions of multiset with AOCP algorithm and
+    baseline implementation, and compare the results.
+
+    """
+    letters = string.ascii_lowercase
+    bl_partitions = multiset_partitions_baseline(multiplicities, letters)
+
+    # The partitions returned by the different algorithms may have
+    # their parts in different orders.  Also, they generate partitions
+    # in different orders.  Hence the sorting, and set comparison.
+
+    aocp_partitions = set()
+    for state in multiset_partitions_taocp(multiplicities):
+        p1 = tuple(sorted(
+                [tuple(p) for p in list_visitor(state, letters)]))
+        aocp_partitions.add(p1)
+
+    assert bl_partitions == aocp_partitions
+
+def compare_multiset_states(s1, s2):
+    """compare for equality two instances of multiset partition states
+
+    This is useful for comparing different versions of the algorithm
+    to verify correctness."""
+    # Comparison is physical, the only use of semantics is to ignore
+    # trash off the top of the stack.
+    f1, lpart1, pstack1 = s1
+    f2, lpart2, pstack2 = s2
+
+    if (lpart1 == lpart2) and (f1[0:lpart1+1] == f2[0:lpart2+1]):
+        if pstack1[0:f1[lpart1+1]] == pstack2[0:f2[lpart2+1]]:
+            return True
+    return False
+
+def test_multiset_partitions_taocp():
+    """Compares the output of multiset_partitions_taocp with a baseline
+    (set partition based) implementation."""
+
+    # Test cases should not be too large, since the baseline
+    # implementation is fairly slow.
+    multiplicities = [2,2]
+    compare_multiset_w_baseline(multiplicities)
+
+    multiplicities = [4,3,1]
+    compare_multiset_w_baseline(multiplicities)
+
+def test_multiset_partitions_versions():
+    """Compares Knuth-based versions of multiset_partitions"""
+    multiplicities = [5,2,2,1]
+    m = MultisetPartitionTraverser()
+    for s1, s2 in zip_longest(m.enum_all(multiplicities),
+                              multiset_partitions_taocp(multiplicities)):
+        assert compare_multiset_states(s1, s2)
+
+def subrange_exercise(mult, lb, ub):
+    """Compare filter-based and more optimized subrange implementations
+
+    Helper for tests, called with both small and larger multisets.
+    """
+    m = MultisetPartitionTraverser()
+    assert m.count_partitions(mult) == \
+        m.count_partitions_slow(mult)
+
+    # Note - multiple traversals from the same
+    # MultisetPartitionTraverser object cannot execute at the same
+    # time, hence make several instances here.
+    ma = MultisetPartitionTraverser()
+    mc = MultisetPartitionTraverser()
+    md = MultisetPartitionTraverser()
+
+    #  Several paths to compute just the size two partitions
+    a_it = ma.enum_range(mult, lb, ub)
+    b_it = part_range_filter(multiset_partitions_taocp(mult), lb, ub)
+    c_it = part_range_filter(mc.enum_small(mult, ub), lb, sum(mult))
+    d_it = part_range_filter(md.enum_large(mult, lb), 0, ub)
+
+    for sa, sb, sc, sd in zip_longest(a_it, b_it, c_it, d_it):
+        assert compare_multiset_states(sa, sb)
+        assert compare_multiset_states(sa, sc)
+        assert compare_multiset_states(sa, sd)
+
+def test_subrange():
+    # Quick, but doesn't hit some of the corner cases
+    mult = [4,4,2,1] # mississippi
+    lb = 1
+    ub = 2
+    subrange_exercise(mult, lb, ub)
+
+
+def test_subrange_large():
+    # takes a second or so, depending on cpu, Python version, etc.
+    mult = [6,3,2,1]
+    lb = 4
+    ub = 7
+    subrange_exercise(mult, lb, ub)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_exceptions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..d91e55e95d0ae4ac57cdd1989e0b3d39a55cd07d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_exceptions.py
@@ -0,0 +1,12 @@
+from sympy.testing.pytest import raises
+from sympy.utilities.exceptions import sympy_deprecation_warning
+
+# Only test exceptions here because the other cases are tested in the
+# warns_deprecated_sympy tests
+def test_sympy_deprecation_warning():
+    raises(TypeError, lambda: sympy_deprecation_warning('test',
+                                                        deprecated_since_version=1.10,
+                                                        active_deprecations_target='active-deprecations'))
+
+    raises(ValueError, lambda: sympy_deprecation_warning('test',
+                                                            deprecated_since_version="1.10", active_deprecations_target='(active-deprecations)='))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_iterables.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_iterables.py
new file mode 100644
index 0000000000000000000000000000000000000000..1003522bcd556c6f63e04de7da57b43498575fee
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_iterables.py
@@ -0,0 +1,945 @@
+from textwrap import dedent
+from itertools import islice, product
+
+from sympy.core.basic import Basic
+from sympy.core.numbers import Integer
+from sympy.core.sorting import ordered
+from sympy.core.symbol import (Dummy, symbols)
+from sympy.functions.combinatorial.factorials import factorial
+from sympy.matrices.dense import Matrix
+from sympy.combinatorics import RGS_enum, RGS_unrank, Permutation
+from sympy.utilities.iterables import (
+    _partition, _set_partitions, binary_partitions, bracelets, capture,
+    cartes, common_prefix, common_suffix, connected_components, dict_merge,
+    filter_symbols, flatten, generate_bell, generate_derangements,
+    generate_involutions, generate_oriented_forest, group, has_dups, ibin,
+    iproduct, kbins, minlex, multiset, multiset_combinations,
+    multiset_partitions, multiset_permutations, necklaces, numbered_symbols,
+    partitions, permutations, postfixes,
+    prefixes, reshape, rotate_left, rotate_right, runs, sift,
+    strongly_connected_components, subsets, take, topological_sort, unflatten,
+    uniq, variations, ordered_partitions, rotations, is_palindromic, iterable,
+    NotIterable, multiset_derangements, signed_permutations,
+    sequence_partitions, sequence_partitions_empty)
+from sympy.utilities.enumerative import (
+    factoring_visitor, multiset_partitions_taocp )
+
+from sympy.core.singleton import S
+from sympy.testing.pytest import raises, warns_deprecated_sympy
+
+w, x, y, z = symbols('w,x,y,z')
+
+
+def test_deprecated_iterables():
+    from sympy.utilities.iterables import default_sort_key, ordered
+    with warns_deprecated_sympy():
+        assert list(ordered([y, x])) == [x, y]
+    with warns_deprecated_sympy():
+        assert sorted([y, x], key=default_sort_key) == [x, y]
+
+
+def test_is_palindromic():
+    assert is_palindromic('')
+    assert is_palindromic('x')
+    assert is_palindromic('xx')
+    assert is_palindromic('xyx')
+    assert not is_palindromic('xy')
+    assert not is_palindromic('xyzx')
+    assert is_palindromic('xxyzzyx', 1)
+    assert not is_palindromic('xxyzzyx', 2)
+    assert is_palindromic('xxyzzyx', 2, -1)
+    assert is_palindromic('xxyzzyx', 2, 6)
+    assert is_palindromic('xxyzyx', 1)
+    assert not is_palindromic('xxyzyx', 2)
+    assert is_palindromic('xxyzyx', 2, 2 + 3)
+
+
+def test_flatten():
+    assert flatten((1, (1,))) == [1, 1]
+    assert flatten((x, (x,))) == [x, x]
+
+    ls = [[(-2, -1), (1, 2)], [(0, 0)]]
+
+    assert flatten(ls, levels=0) == ls
+    assert flatten(ls, levels=1) == [(-2, -1), (1, 2), (0, 0)]
+    assert flatten(ls, levels=2) == [-2, -1, 1, 2, 0, 0]
+    assert flatten(ls, levels=3) == [-2, -1, 1, 2, 0, 0]
+
+    raises(ValueError, lambda: flatten(ls, levels=-1))
+
+    class MyOp(Basic):
+        pass
+
+    assert flatten([MyOp(x, y), z]) == [MyOp(x, y), z]
+    assert flatten([MyOp(x, y), z], cls=MyOp) == [x, y, z]
+
+    assert flatten({1, 11, 2}) == list({1, 11, 2})
+
+
+def test_iproduct():
+    assert list(iproduct()) == [()]
+    assert list(iproduct([])) == []
+    assert list(iproduct([1,2,3])) == [(1,),(2,),(3,)]
+    assert sorted(iproduct([1, 2], [3, 4, 5])) == [
+        (1,3),(1,4),(1,5),(2,3),(2,4),(2,5)]
+    assert sorted(iproduct([0,1],[0,1],[0,1])) == [
+        (0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)]
+    assert iterable(iproduct(S.Integers)) is True
+    assert iterable(iproduct(S.Integers, S.Integers)) is True
+    assert (3,) in iproduct(S.Integers)
+    assert (4, 5) in iproduct(S.Integers, S.Integers)
+    assert (1, 2, 3) in iproduct(S.Integers, S.Integers, S.Integers)
+    triples  = set(islice(iproduct(S.Integers, S.Integers, S.Integers), 1000))
+    for n1, n2, n3 in triples:
+        assert isinstance(n1, Integer)
+        assert isinstance(n2, Integer)
+        assert isinstance(n3, Integer)
+    for t in set(product(*([range(-2, 3)]*3))):
+        assert t in iproduct(S.Integers, S.Integers, S.Integers)
+
+
+def test_group():
+    assert group([]) == []
+    assert group([], multiple=False) == []
+
+    assert group([1]) == [[1]]
+    assert group([1], multiple=False) == [(1, 1)]
+
+    assert group([1, 1]) == [[1, 1]]
+    assert group([1, 1], multiple=False) == [(1, 2)]
+
+    assert group([1, 1, 1]) == [[1, 1, 1]]
+    assert group([1, 1, 1], multiple=False) == [(1, 3)]
+
+    assert group([1, 2, 1]) == [[1], [2], [1]]
+    assert group([1, 2, 1], multiple=False) == [(1, 1), (2, 1), (1, 1)]
+
+    assert group([1, 1, 2, 2, 2, 1, 3, 3]) == [[1, 1], [2, 2, 2], [1], [3, 3]]
+    assert group([1, 1, 2, 2, 2, 1, 3, 3], multiple=False) == [(1, 2),
+                 (2, 3), (1, 1), (3, 2)]
+
+
+def test_subsets():
+    # combinations
+    assert list(subsets([1, 2, 3], 0)) == [()]
+    assert list(subsets([1, 2, 3], 1)) == [(1,), (2,), (3,)]
+    assert list(subsets([1, 2, 3], 2)) == [(1, 2), (1, 3), (2, 3)]
+    assert list(subsets([1, 2, 3], 3)) == [(1, 2, 3)]
+    l = list(range(4))
+    assert list(subsets(l, 0, repetition=True)) == [()]
+    assert list(subsets(l, 1, repetition=True)) == [(0,), (1,), (2,), (3,)]
+    assert list(subsets(l, 2, repetition=True)) == [(0, 0), (0, 1), (0, 2),
+                                                    (0, 3), (1, 1), (1, 2),
+                                                    (1, 3), (2, 2), (2, 3),
+                                                    (3, 3)]
+    assert list(subsets(l, 3, repetition=True)) == [(0, 0, 0), (0, 0, 1),
+                                                    (0, 0, 2), (0, 0, 3),
+                                                    (0, 1, 1), (0, 1, 2),
+                                                    (0, 1, 3), (0, 2, 2),
+                                                    (0, 2, 3), (0, 3, 3),
+                                                    (1, 1, 1), (1, 1, 2),
+                                                    (1, 1, 3), (1, 2, 2),
+                                                    (1, 2, 3), (1, 3, 3),
+                                                    (2, 2, 2), (2, 2, 3),
+                                                    (2, 3, 3), (3, 3, 3)]
+    assert len(list(subsets(l, 4, repetition=True))) == 35
+
+    assert list(subsets(l[:2], 3, repetition=False)) == []
+    assert list(subsets(l[:2], 3, repetition=True)) == [(0, 0, 0),
+                                                        (0, 0, 1),
+                                                        (0, 1, 1),
+                                                        (1, 1, 1)]
+    assert list(subsets([1, 2], repetition=True)) == \
+        [(), (1,), (2,), (1, 1), (1, 2), (2, 2)]
+    assert list(subsets([1, 2], repetition=False)) == \
+        [(), (1,), (2,), (1, 2)]
+    assert list(subsets([1, 2, 3], 2)) == \
+        [(1, 2), (1, 3), (2, 3)]
+    assert list(subsets([1, 2, 3], 2, repetition=True)) == \
+        [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
+
+
+def test_variations():
+    # permutations
+    l = list(range(4))
+    assert list(variations(l, 0, repetition=False)) == [()]
+    assert list(variations(l, 1, repetition=False)) == [(0,), (1,), (2,), (3,)]
+    assert list(variations(l, 2, repetition=False)) == [(0, 1), (0, 2), (0, 3), (1, 0), (1, 2), (1, 3), (2, 0), (2, 1), (2, 3), (3, 0), (3, 1), (3, 2)]
+    assert list(variations(l, 3, repetition=False)) == [(0, 1, 2), (0, 1, 3), (0, 2, 1), (0, 2, 3), (0, 3, 1), (0, 3, 2), (1, 0, 2), (1, 0, 3), (1, 2, 0), (1, 2, 3), (1, 3, 0), (1, 3, 2), (2, 0, 1), (2, 0, 3), (2, 1, 0), (2, 1, 3), (2, 3, 0), (2, 3, 1), (3, 0, 1), (3, 0, 2), (3, 1, 0), (3, 1, 2), (3, 2, 0), (3, 2, 1)]
+    assert list(variations(l, 0, repetition=True)) == [()]
+    assert list(variations(l, 1, repetition=True)) == [(0,), (1,), (2,), (3,)]
+    assert list(variations(l, 2, repetition=True)) == [(0, 0), (0, 1), (0, 2),
+                                                       (0, 3), (1, 0), (1, 1),
+                                                       (1, 2), (1, 3), (2, 0),
+                                                       (2, 1), (2, 2), (2, 3),
+                                                       (3, 0), (3, 1), (3, 2),
+                                                       (3, 3)]
+    assert len(list(variations(l, 3, repetition=True))) == 64
+    assert len(list(variations(l, 4, repetition=True))) == 256
+    assert list(variations(l[:2], 3, repetition=False)) == []
+    assert list(variations(l[:2], 3, repetition=True)) == [
+        (0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
+        (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)
+    ]
+
+
+def test_cartes():
+    assert list(cartes([1, 2], [3, 4, 5])) == \
+        [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]
+    assert list(cartes()) == [()]
+    assert list(cartes('a')) == [('a',)]
+    assert list(cartes('a', repeat=2)) == [('a', 'a')]
+    assert list(cartes(list(range(2)))) == [(0,), (1,)]
+
+
+def test_filter_symbols():
+    s = numbered_symbols()
+    filtered = filter_symbols(s, symbols("x0 x2 x3"))
+    assert take(filtered, 3) == list(symbols("x1 x4 x5"))
+
+
+def test_numbered_symbols():
+    s = numbered_symbols(cls=Dummy)
+    assert isinstance(next(s), Dummy)
+    assert next(numbered_symbols('C', start=1, exclude=[symbols('C1')])) == \
+        symbols('C2')
+
+
+def test_sift():
+    assert sift(list(range(5)), lambda _: _ % 2) == {1: [1, 3], 0: [0, 2, 4]}
+    assert sift([x, y], lambda _: _.has(x)) == {False: [y], True: [x]}
+    assert sift([S.One], lambda _: _.has(x)) == {False: [1]}
+    assert sift([0, 1, 2, 3], lambda x: x % 2, binary=True) == (
+        [1, 3], [0, 2])
+    assert sift([0, 1, 2, 3], lambda x: x % 3 == 1, binary=True) == (
+        [1], [0, 2, 3])
+    raises(ValueError, lambda:
+        sift([0, 1, 2, 3], lambda x: x % 3, binary=True))
+
+
+def test_take():
+    X = numbered_symbols()
+
+    assert take(X, 5) == list(symbols('x0:5'))
+    assert take(X, 5) == list(symbols('x5:10'))
+
+    assert take([1, 2, 3, 4, 5], 5) == [1, 2, 3, 4, 5]
+
+
+def test_dict_merge():
+    assert dict_merge({}, {1: x, y: z}) == {1: x, y: z}
+    assert dict_merge({1: x, y: z}, {}) == {1: x, y: z}
+
+    assert dict_merge({2: z}, {1: x, y: z}) == {1: x, 2: z, y: z}
+    assert dict_merge({1: x, y: z}, {2: z}) == {1: x, 2: z, y: z}
+
+    assert dict_merge({1: y, 2: z}, {1: x, y: z}) == {1: x, 2: z, y: z}
+    assert dict_merge({1: x, y: z}, {1: y, 2: z}) == {1: y, 2: z, y: z}
+
+
+def test_prefixes():
+    assert list(prefixes([])) == []
+    assert list(prefixes([1])) == [[1]]
+    assert list(prefixes([1, 2])) == [[1], [1, 2]]
+
+    assert list(prefixes([1, 2, 3, 4, 5])) == \
+        [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
+
+
+def test_postfixes():
+    assert list(postfixes([])) == []
+    assert list(postfixes([1])) == [[1]]
+    assert list(postfixes([1, 2])) == [[2], [1, 2]]
+
+    assert list(postfixes([1, 2, 3, 4, 5])) == \
+        [[5], [4, 5], [3, 4, 5], [2, 3, 4, 5], [1, 2, 3, 4, 5]]
+
+
+def test_topological_sort():
+    V = [2, 3, 5, 7, 8, 9, 10, 11]
+    E = [(7, 11), (7, 8), (5, 11),
+         (3, 8), (3, 10), (11, 2),
+         (11, 9), (11, 10), (8, 9)]
+
+    assert topological_sort((V, E)) == [3, 5, 7, 8, 11, 2, 9, 10]
+    assert topological_sort((V, E), key=lambda v: -v) == \
+        [7, 5, 11, 3, 10, 8, 9, 2]
+
+    raises(ValueError, lambda: topological_sort((V, E + [(10, 7)])))
+
+
+def test_strongly_connected_components():
+    assert strongly_connected_components(([], [])) == []
+    assert strongly_connected_components(([1, 2, 3], [])) == [[1], [2], [3]]
+
+    V = [1, 2, 3]
+    E = [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1)]
+    assert strongly_connected_components((V, E)) == [[1, 2, 3]]
+
+    V = [1, 2, 3, 4]
+    E = [(1, 2), (2, 3), (3, 2), (3, 4)]
+    assert strongly_connected_components((V, E)) == [[4], [2, 3], [1]]
+
+    V = [1, 2, 3, 4]
+    E = [(1, 2), (2, 1), (3, 4), (4, 3)]
+    assert strongly_connected_components((V, E)) == [[1, 2], [3, 4]]
+
+
+def test_connected_components():
+    assert connected_components(([], [])) == []
+    assert connected_components(([1, 2, 3], [])) == [[1], [2], [3]]
+
+    V = [1, 2, 3]
+    E = [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1)]
+    assert connected_components((V, E)) == [[1, 2, 3]]
+
+    V = [1, 2, 3, 4]
+    E = [(1, 2), (2, 3), (3, 2), (3, 4)]
+    assert connected_components((V, E)) == [[1, 2, 3, 4]]
+
+    V = [1, 2, 3, 4]
+    E = [(1, 2), (3, 4)]
+    assert connected_components((V, E)) == [[1, 2], [3, 4]]
+
+
+def test_rotate():
+    A = [0, 1, 2, 3, 4]
+
+    assert rotate_left(A, 2) == [2, 3, 4, 0, 1]
+    assert rotate_right(A, 1) == [4, 0, 1, 2, 3]
+    A = []
+    B = rotate_right(A, 1)
+    assert B == []
+    B.append(1)
+    assert A == []
+    B = rotate_left(A, 1)
+    assert B == []
+    B.append(1)
+    assert A == []
+
+
+def test_multiset_partitions():
+    A = [0, 1, 2, 3, 4]
+
+    assert list(multiset_partitions(A, 5)) == [[[0], [1], [2], [3], [4]]]
+    assert len(list(multiset_partitions(A, 4))) == 10
+    assert len(list(multiset_partitions(A, 3))) == 25
+
+    assert list(multiset_partitions([1, 1, 1, 2, 2], 2)) == [
+        [[1, 1, 1, 2], [2]], [[1, 1, 1], [2, 2]], [[1, 1, 2, 2], [1]],
+        [[1, 1, 2], [1, 2]], [[1, 1], [1, 2, 2]]]
+
+    assert list(multiset_partitions([1, 1, 2, 2], 2)) == [
+        [[1, 1, 2], [2]], [[1, 1], [2, 2]], [[1, 2, 2], [1]],
+        [[1, 2], [1, 2]]]
+
+    assert list(multiset_partitions([1, 2, 3, 4], 2)) == [
+        [[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 2], [3, 4]],
+        [[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]],
+        [[1], [2, 3, 4]]]
+
+    assert list(multiset_partitions([1, 2, 2], 2)) == [
+        [[1, 2], [2]], [[1], [2, 2]]]
+
+    assert list(multiset_partitions(3)) == [
+        [[0, 1, 2]], [[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]],
+        [[0], [1], [2]]]
+    assert list(multiset_partitions(3, 2)) == [
+        [[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]]]
+    assert list(multiset_partitions([1] * 3, 2)) == [[[1], [1, 1]]]
+    assert list(multiset_partitions([1] * 3)) == [
+        [[1, 1, 1]], [[1], [1, 1]], [[1], [1], [1]]]
+    a = [3, 2, 1]
+    assert list(multiset_partitions(a)) == \
+        list(multiset_partitions(sorted(a)))
+    assert list(multiset_partitions(a, 5)) == []
+    assert list(multiset_partitions(a, 1)) == [[[1, 2, 3]]]
+    assert list(multiset_partitions(a + [4], 5)) == []
+    assert list(multiset_partitions(a + [4], 1)) == [[[1, 2, 3, 4]]]
+    assert list(multiset_partitions(2, 5)) == []
+    assert list(multiset_partitions(2, 1)) == [[[0, 1]]]
+    assert list(multiset_partitions('a')) == [[['a']]]
+    assert list(multiset_partitions('a', 2)) == []
+    assert list(multiset_partitions('ab')) == [[['a', 'b']], [['a'], ['b']]]
+    assert list(multiset_partitions('ab', 1)) == [[['a', 'b']]]
+    assert list(multiset_partitions('aaa', 1)) == [['aaa']]
+    assert list(multiset_partitions([1, 1], 1)) == [[[1, 1]]]
+    ans = [('mpsyy',), ('mpsy', 'y'), ('mps', 'yy'), ('mps', 'y', 'y'),
+           ('mpyy', 's'), ('mpy', 'sy'), ('mpy', 's', 'y'), ('mp', 'syy'),
+           ('mp', 'sy', 'y'), ('mp', 's', 'yy'), ('mp', 's', 'y', 'y'),
+           ('msyy', 'p'), ('msy', 'py'), ('msy', 'p', 'y'), ('ms', 'pyy'),
+           ('ms', 'py', 'y'), ('ms', 'p', 'yy'), ('ms', 'p', 'y', 'y'),
+           ('myy', 'ps'), ('myy', 'p', 's'), ('my', 'psy'), ('my', 'ps', 'y'),
+           ('my', 'py', 's'), ('my', 'p', 'sy'), ('my', 'p', 's', 'y'),
+           ('m', 'psyy'), ('m', 'psy', 'y'), ('m', 'ps', 'yy'),
+           ('m', 'ps', 'y', 'y'), ('m', 'pyy', 's'), ('m', 'py', 'sy'),
+           ('m', 'py', 's', 'y'), ('m', 'p', 'syy'),
+           ('m', 'p', 'sy', 'y'), ('m', 'p', 's', 'yy'),
+           ('m', 'p', 's', 'y', 'y')]
+    assert [tuple("".join(part) for part in p)
+                for p in multiset_partitions('sympy')] == ans
+    factorings = [[24], [8, 3], [12, 2], [4, 6], [4, 2, 3],
+                  [6, 2, 2], [2, 2, 2, 3]]
+    assert [factoring_visitor(p, [2,3]) for
+                p in multiset_partitions_taocp([3, 1])] == factorings
+
+
+def test_multiset_combinations():
+    ans = ['iii', 'iim', 'iip', 'iis', 'imp', 'ims', 'ipp', 'ips',
+           'iss', 'mpp', 'mps', 'mss', 'pps', 'pss', 'sss']
+    assert [''.join(i) for i in
+            list(multiset_combinations('mississippi', 3))] == ans
+    M = multiset('mississippi')
+    assert [''.join(i) for i in
+            list(multiset_combinations(M, 3))] == ans
+    assert [''.join(i) for i in multiset_combinations(M, 30)] == []
+    assert list(multiset_combinations([[1], [2, 3]], 2)) == [[[1], [2, 3]]]
+    assert len(list(multiset_combinations('a', 3))) == 0
+    assert len(list(multiset_combinations('a', 0))) == 1
+    assert list(multiset_combinations('abc', 1)) == [['a'], ['b'], ['c']]
+    raises(ValueError, lambda: list(multiset_combinations({0: 3, 1: -1}, 2)))
+
+
+def test_multiset_permutations():
+    ans = ['abby', 'abyb', 'aybb', 'baby', 'bayb', 'bbay', 'bbya', 'byab',
+           'byba', 'yabb', 'ybab', 'ybba']
+    assert [''.join(i) for i in multiset_permutations('baby')] == ans
+    assert [''.join(i) for i in multiset_permutations(multiset('baby'))] == ans
+    assert list(multiset_permutations([0, 0, 0], 2)) == [[0, 0]]
+    assert list(multiset_permutations([0, 2, 1], 2)) == [
+        [0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]]
+    assert len(list(multiset_permutations('a', 0))) == 1
+    assert len(list(multiset_permutations('a', 3))) == 0
+    for nul in ([], {}, ''):
+        assert list(multiset_permutations(nul)) == [[]]
+    assert list(multiset_permutations(nul, 0)) == [[]]
+    # impossible requests give no result
+    assert list(multiset_permutations(nul, 1)) == []
+    assert list(multiset_permutations(nul, -1)) == []
+
+    def test():
+        for i in range(1, 7):
+            print(i)
+            for p in multiset_permutations([0, 0, 1, 0, 1], i):
+                print(p)
+    assert capture(lambda: test()) == dedent('''\
+        1
+        [0]
+        [1]
+        2
+        [0, 0]
+        [0, 1]
+        [1, 0]
+        [1, 1]
+        3
+        [0, 0, 0]
+        [0, 0, 1]
+        [0, 1, 0]
+        [0, 1, 1]
+        [1, 0, 0]
+        [1, 0, 1]
+        [1, 1, 0]
+        4
+        [0, 0, 0, 1]
+        [0, 0, 1, 0]
+        [0, 0, 1, 1]
+        [0, 1, 0, 0]
+        [0, 1, 0, 1]
+        [0, 1, 1, 0]
+        [1, 0, 0, 0]
+        [1, 0, 0, 1]
+        [1, 0, 1, 0]
+        [1, 1, 0, 0]
+        5
+        [0, 0, 0, 1, 1]
+        [0, 0, 1, 0, 1]
+        [0, 0, 1, 1, 0]
+        [0, 1, 0, 0, 1]
+        [0, 1, 0, 1, 0]
+        [0, 1, 1, 0, 0]
+        [1, 0, 0, 0, 1]
+        [1, 0, 0, 1, 0]
+        [1, 0, 1, 0, 0]
+        [1, 1, 0, 0, 0]
+        6\n''')
+    raises(ValueError, lambda: list(multiset_permutations({0: 3, 1: -1})))
+
+
+def test_partitions():
+    ans = [[{}], [(0, {})]]
+    for i in range(2):
+        assert list(partitions(0, size=i)) == ans[i]
+        assert list(partitions(1, 0, size=i)) == ans[i]
+        assert list(partitions(6, 2, 2, size=i)) == ans[i]
+        assert list(partitions(6, 2, None, size=i)) != ans[i]
+        assert list(partitions(6, None, 2, size=i)) != ans[i]
+        assert list(partitions(6, 2, 0, size=i)) == ans[i]
+
+    assert list(partitions(6, k=2)) == [
+        {2: 3}, {1: 2, 2: 2}, {1: 4, 2: 1}, {1: 6}]
+
+    assert list(partitions(6, k=3)) == [
+        {3: 2}, {1: 1, 2: 1, 3: 1}, {1: 3, 3: 1}, {2: 3}, {1: 2, 2: 2},
+        {1: 4, 2: 1}, {1: 6}]
+
+    assert list(partitions(8, k=4, m=3)) == [
+        {4: 2}, {1: 1, 3: 1, 4: 1}, {2: 2, 4: 1}, {2: 1, 3: 2}] == [
+        i for i in partitions(8, k=4, m=3) if all(k <= 4 for k in i)
+        and sum(i.values()) <=3]
+
+    assert list(partitions(S(3), m=2)) == [
+        {3: 1}, {1: 1, 2: 1}]
+
+    assert list(partitions(4, k=3)) == [
+        {1: 1, 3: 1}, {2: 2}, {1: 2, 2: 1}, {1: 4}] == [
+        i for i in partitions(4) if all(k <= 3 for k in i)]
+
+
+    # Consistency check on output of _partitions and RGS_unrank.
+    # This provides a sanity test on both routines.  Also verifies that
+    # the total number of partitions is the same in each case.
+    #    (from pkrathmann2)
+
+    for n in range(2, 6):
+        i  = 0
+        for m, q  in _set_partitions(n):
+            assert  q == RGS_unrank(i, n)
+            i += 1
+        assert i == RGS_enum(n)
+
+
+def test_binary_partitions():
+    assert [i[:] for i in binary_partitions(10)] == [[8, 2], [8, 1, 1],
+        [4, 4, 2], [4, 4, 1, 1], [4, 2, 2, 2], [4, 2, 2, 1, 1],
+        [4, 2, 1, 1, 1, 1], [4, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2],
+        [2, 2, 2, 2, 1, 1], [2, 2, 2, 1, 1, 1, 1], [2, 2, 1, 1, 1, 1, 1, 1],
+        [2, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
+
+    assert len([j[:] for j in binary_partitions(16)]) == 36
+
+
+def test_bell_perm():
+    assert [len(set(generate_bell(i))) for i in range(1, 7)] == [
+        factorial(i) for i in range(1, 7)]
+    assert list(generate_bell(3)) == [
+        (0, 1, 2), (0, 2, 1), (2, 0, 1), (2, 1, 0), (1, 2, 0), (1, 0, 2)]
+    # generate_bell and trotterjohnson are advertised to return the same
+    # permutations; this is not technically necessary so this test could
+    # be removed
+    for n in range(1, 5):
+        p = Permutation(range(n))
+        b = generate_bell(n)
+        for bi in b:
+            assert bi == tuple(p.array_form)
+            p = p.next_trotterjohnson()
+    raises(ValueError, lambda: list(generate_bell(0)))  # XXX is this consistent with other permutation algorithms?
+
+
+def test_involutions():
+    lengths = [1, 2, 4, 10, 26, 76]
+    for n, N in enumerate(lengths):
+        i = list(generate_involutions(n + 1))
+        assert len(i) == N
+        assert len({Permutation(j)**2 for j in i}) == 1
+
+
+def test_derangements():
+    assert len(list(generate_derangements(list(range(6))))) == 265
+    assert ''.join(''.join(i) for i in generate_derangements('abcde')) == (
+    'badecbaecdbcaedbcdeabceadbdaecbdeacbdecabeacdbedacbedcacabedcadebcaebd'
+    'cdaebcdbeacdeabcdebaceabdcebadcedabcedbadabecdaebcdaecbdcaebdcbeadceab'
+    'dcebadeabcdeacbdebacdebcaeabcdeadbceadcbecabdecbadecdabecdbaedabcedacb'
+    'edbacedbca')
+    assert list(generate_derangements([0, 1, 2, 3])) == [
+        [1, 0, 3, 2], [1, 2, 3, 0], [1, 3, 0, 2], [2, 0, 3, 1],
+        [2, 3, 0, 1], [2, 3, 1, 0], [3, 0, 1, 2], [3, 2, 0, 1], [3, 2, 1, 0]]
+    assert list(generate_derangements([0, 1, 2, 2])) == [
+        [2, 2, 0, 1], [2, 2, 1, 0]]
+    assert list(generate_derangements('ba')) == [list('ab')]
+    # multiset_derangements
+    D = multiset_derangements
+    assert list(D('abb')) == []
+    assert [''.join(i) for i in D('ab')] == ['ba']
+    assert [''.join(i) for i in D('abc')] == ['bca', 'cab']
+    assert [''.join(i) for i in D('aabb')] == ['bbaa']
+    assert [''.join(i) for i in D('aabbcccc')] == [
+        'ccccaabb', 'ccccabab', 'ccccabba', 'ccccbaab', 'ccccbaba',
+        'ccccbbaa']
+    assert [''.join(i) for i in D('aabbccc')] == [
+        'cccabba', 'cccabab', 'cccaabb', 'ccacbba', 'ccacbab',
+        'ccacabb', 'cbccbaa', 'cbccaba', 'cbccaab', 'bcccbaa',
+        'bcccaba', 'bcccaab']
+    assert [''.join(i) for i in D('books')] == ['kbsoo', 'ksboo',
+        'sbkoo', 'skboo', 'oksbo', 'oskbo', 'okbso', 'obkso', 'oskob',
+        'oksob', 'osbok', 'obsok']
+    assert list(generate_derangements([[3], [2], [2], [1]])) == [
+        [[2], [1], [3], [2]], [[2], [3], [1], [2]]]
+
+
+def test_necklaces():
+    def count(n, k, f):
+        return len(list(necklaces(n, k, f)))
+    m = []
+    for i in range(1, 8):
+        m.append((
+        i, count(i, 2, 0), count(i, 2, 1), count(i, 3, 1)))
+    assert Matrix(m) == Matrix([
+        [1,   2,   2,   3],
+        [2,   3,   3,   6],
+        [3,   4,   4,  10],
+        [4,   6,   6,  21],
+        [5,   8,   8,  39],
+        [6,  14,  13,  92],
+        [7,  20,  18, 198]])
+
+
+def test_bracelets():
+    bc = list(bracelets(2, 4))
+    assert Matrix(bc) == Matrix([
+        [0, 0],
+        [0, 1],
+        [0, 2],
+        [0, 3],
+        [1, 1],
+        [1, 2],
+        [1, 3],
+        [2, 2],
+        [2, 3],
+        [3, 3]
+        ])
+    bc = list(bracelets(4, 2))
+    assert Matrix(bc) == Matrix([
+        [0, 0, 0, 0],
+        [0, 0, 0, 1],
+        [0, 0, 1, 1],
+        [0, 1, 0, 1],
+        [0, 1, 1, 1],
+        [1, 1, 1, 1]
+    ])
+
+
+def test_generate_oriented_forest():
+    assert list(generate_oriented_forest(5)) == [[0, 1, 2, 3, 4],
+        [0, 1, 2, 3, 3], [0, 1, 2, 3, 2], [0, 1, 2, 3, 1], [0, 1, 2, 3, 0],
+        [0, 1, 2, 2, 2], [0, 1, 2, 2, 1], [0, 1, 2, 2, 0], [0, 1, 2, 1, 2],
+        [0, 1, 2, 1, 1], [0, 1, 2, 1, 0], [0, 1, 2, 0, 1], [0, 1, 2, 0, 0],
+        [0, 1, 1, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 1], [0, 1, 1, 0, 0],
+        [0, 1, 0, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 0]]
+    assert len(list(generate_oriented_forest(10))) == 1842
+
+
+def test_unflatten():
+    r = list(range(10))
+    assert unflatten(r) == list(zip(r[::2], r[1::2]))
+    assert unflatten(r, 5) == [tuple(r[:5]), tuple(r[5:])]
+    raises(ValueError, lambda: unflatten(list(range(10)), 3))
+    raises(ValueError, lambda: unflatten(list(range(10)), -2))
+
+
+def test_common_prefix_suffix():
+    assert common_prefix([], [1]) == []
+    assert common_prefix(list(range(3))) == [0, 1, 2]
+    assert common_prefix(list(range(3)), list(range(4))) == [0, 1, 2]
+    assert common_prefix([1, 2, 3], [1, 2, 5]) == [1, 2]
+    assert common_prefix([1, 2, 3], [1, 3, 5]) == [1]
+
+    assert common_suffix([], [1]) == []
+    assert common_suffix(list(range(3))) == [0, 1, 2]
+    assert common_suffix(list(range(3)), list(range(3))) == [0, 1, 2]
+    assert common_suffix(list(range(3)), list(range(4))) == []
+    assert common_suffix([1, 2, 3], [9, 2, 3]) == [2, 3]
+    assert common_suffix([1, 2, 3], [9, 7, 3]) == [3]
+
+
+def test_minlex():
+    assert minlex([1, 2, 0]) == (0, 1, 2)
+    assert minlex((1, 2, 0)) == (0, 1, 2)
+    assert minlex((1, 0, 2)) == (0, 2, 1)
+    assert minlex((1, 0, 2), directed=False) == (0, 1, 2)
+    assert minlex('aba') == 'aab'
+    assert minlex(('bb', 'aaa', 'c', 'a'), key=len) == ('c', 'a', 'bb', 'aaa')
+
+
+def test_ordered():
+    assert list(ordered((x, y), hash, default=False)) in [[x, y], [y, x]]
+    assert list(ordered((x, y), hash, default=False)) == \
+        list(ordered((y, x), hash, default=False))
+    assert list(ordered((x, y))) == [x, y]
+
+    seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]],
+                 (lambda x: len(x), lambda x: sum(x))]
+    assert list(ordered(seq, keys, default=False, warn=False)) == \
+        [[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]]
+    raises(ValueError, lambda:
+           list(ordered(seq, keys, default=False, warn=True)))
+
+
+def test_runs():
+    assert runs([]) == []
+    assert runs([1]) == [[1]]
+    assert runs([1, 1]) == [[1], [1]]
+    assert runs([1, 1, 2]) == [[1], [1, 2]]
+    assert runs([1, 2, 1]) == [[1, 2], [1]]
+    assert runs([2, 1, 1]) == [[2], [1], [1]]
+    from operator import lt
+    assert runs([2, 1, 1], lt) == [[2, 1], [1]]
+
+
+def test_reshape():
+    seq = list(range(1, 9))
+    assert reshape(seq, [4]) == \
+        [[1, 2, 3, 4], [5, 6, 7, 8]]
+    assert reshape(seq, (4,)) == \
+        [(1, 2, 3, 4), (5, 6, 7, 8)]
+    assert reshape(seq, (2, 2)) == \
+        [(1, 2, 3, 4), (5, 6, 7, 8)]
+    assert reshape(seq, (2, [2])) == \
+        [(1, 2, [3, 4]), (5, 6, [7, 8])]
+    assert reshape(seq, ((2,), [2])) == \
+        [((1, 2), [3, 4]), ((5, 6), [7, 8])]
+    assert reshape(seq, (1, [2], 1)) == \
+        [(1, [2, 3], 4), (5, [6, 7], 8)]
+    assert reshape(tuple(seq), ([[1], 1, (2,)],)) == \
+        (([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],))
+    assert reshape(tuple(seq), ([1], 1, (2,))) == \
+        (([1], 2, (3, 4)), ([5], 6, (7, 8)))
+    assert reshape(list(range(12)), [2, [3], {2}, (1, (3,), 1)]) == \
+        [[0, 1, [2, 3, 4], {5, 6}, (7, (8, 9, 10), 11)]]
+    raises(ValueError, lambda: reshape([0, 1], [-1]))
+    raises(ValueError, lambda: reshape([0, 1], [3]))
+
+
+def test_uniq():
+    assert list(uniq(p for p in partitions(4))) == \
+        [{4: 1}, {1: 1, 3: 1}, {2: 2}, {1: 2, 2: 1}, {1: 4}]
+    assert list(uniq(x % 2 for x in range(5))) == [0, 1]
+    assert list(uniq('a')) == ['a']
+    assert list(uniq('ababc')) == list('abc')
+    assert list(uniq([[1], [2, 1], [1]])) == [[1], [2, 1]]
+    assert list(uniq(permutations(i for i in [[1], 2, 2]))) == \
+        [([1], 2, 2), (2, [1], 2), (2, 2, [1])]
+    assert list(uniq([2, 3, 2, 4, [2], [1], [2], [3], [1]])) == \
+        [2, 3, 4, [2], [1], [3]]
+    f = [1]
+    raises(RuntimeError, lambda: [f.remove(i) for i in uniq(f)])
+    f = [[1]]
+    raises(RuntimeError, lambda: [f.remove(i) for i in uniq(f)])
+
+
+def test_kbins():
+    assert len(list(kbins('1123', 2, ordered=1))) == 24
+    assert len(list(kbins('1123', 2, ordered=11))) == 36
+    assert len(list(kbins('1123', 2, ordered=10))) == 10
+    assert len(list(kbins('1123', 2, ordered=0))) == 5
+    assert len(list(kbins('1123', 2, ordered=None))) == 3
+
+    def test1():
+        for orderedval in [None, 0, 1, 10, 11]:
+            print('ordered =', orderedval)
+            for p in kbins([0, 0, 1], 2, ordered=orderedval):
+                print('   ', p)
+    assert capture(lambda : test1()) == dedent('''\
+        ordered = None
+            [[0], [0, 1]]
+            [[0, 0], [1]]
+        ordered = 0
+            [[0, 0], [1]]
+            [[0, 1], [0]]
+        ordered = 1
+            [[0], [0, 1]]
+            [[0], [1, 0]]
+            [[1], [0, 0]]
+        ordered = 10
+            [[0, 0], [1]]
+            [[1], [0, 0]]
+            [[0, 1], [0]]
+            [[0], [0, 1]]
+        ordered = 11
+            [[0], [0, 1]]
+            [[0, 0], [1]]
+            [[0], [1, 0]]
+            [[0, 1], [0]]
+            [[1], [0, 0]]
+            [[1, 0], [0]]\n''')
+
+    def test2():
+        for orderedval in [None, 0, 1, 10, 11]:
+            print('ordered =', orderedval)
+            for p in kbins(list(range(3)), 2, ordered=orderedval):
+                print('   ', p)
+    assert capture(lambda : test2()) == dedent('''\
+        ordered = None
+            [[0], [1, 2]]
+            [[0, 1], [2]]
+        ordered = 0
+            [[0, 1], [2]]
+            [[0, 2], [1]]
+            [[0], [1, 2]]
+        ordered = 1
+            [[0], [1, 2]]
+            [[0], [2, 1]]
+            [[1], [0, 2]]
+            [[1], [2, 0]]
+            [[2], [0, 1]]
+            [[2], [1, 0]]
+        ordered = 10
+            [[0, 1], [2]]
+            [[2], [0, 1]]
+            [[0, 2], [1]]
+            [[1], [0, 2]]
+            [[0], [1, 2]]
+            [[1, 2], [0]]
+        ordered = 11
+            [[0], [1, 2]]
+            [[0, 1], [2]]
+            [[0], [2, 1]]
+            [[0, 2], [1]]
+            [[1], [0, 2]]
+            [[1, 0], [2]]
+            [[1], [2, 0]]
+            [[1, 2], [0]]
+            [[2], [0, 1]]
+            [[2, 0], [1]]
+            [[2], [1, 0]]
+            [[2, 1], [0]]\n''')
+
+
+def test_has_dups():
+    assert has_dups(set()) is False
+    assert has_dups(list(range(3))) is False
+    assert has_dups([1, 2, 1]) is True
+    assert has_dups([[1], [1]]) is True
+    assert has_dups([[1], [2]]) is False
+
+
+def test__partition():
+    assert _partition('abcde', [1, 0, 1, 2, 0]) == [
+        ['b', 'e'], ['a', 'c'], ['d']]
+    assert _partition('abcde', [1, 0, 1, 2, 0], 3) == [
+        ['b', 'e'], ['a', 'c'], ['d']]
+    output = (3, [1, 0, 1, 2, 0])
+    assert _partition('abcde', *output) == [['b', 'e'], ['a', 'c'], ['d']]
+
+
+def test_ordered_partitions():
+    from sympy.functions.combinatorial.numbers import nT
+    f = ordered_partitions
+    assert list(f(0, 1)) == [[]]
+    assert list(f(1, 0)) == [[]]
+    for i in range(1, 7):
+        for j in [None] + list(range(1, i)):
+            assert (
+                sum(1 for p in f(i, j, 1)) ==
+                sum(1 for p in f(i, j, 0)) ==
+                nT(i, j))
+
+
+def test_rotations():
+    assert list(rotations('ab')) == [['a', 'b'], ['b', 'a']]
+    assert list(rotations(range(3))) == [[0, 1, 2], [1, 2, 0], [2, 0, 1]]
+    assert list(rotations(range(3), dir=-1)) == [[0, 1, 2], [2, 0, 1], [1, 2, 0]]
+
+
+def test_ibin():
+    assert ibin(3) == [1, 1]
+    assert ibin(3, 3) == [0, 1, 1]
+    assert ibin(3, str=True) == '11'
+    assert ibin(3, 3, str=True) == '011'
+    assert list(ibin(2, 'all')) == [(0, 0), (0, 1), (1, 0), (1, 1)]
+    assert list(ibin(2, '', str=True)) == ['00', '01', '10', '11']
+    raises(ValueError, lambda: ibin(-.5))
+    raises(ValueError, lambda: ibin(2, 1))
+
+
+def test_iterable():
+    assert iterable(0) is False
+    assert iterable(1) is False
+    assert iterable(None) is False
+
+    class Test1(NotIterable):
+        pass
+
+    assert iterable(Test1()) is False
+
+    class Test2(NotIterable):
+        _iterable = True
+
+    assert iterable(Test2()) is True
+
+    class Test3:
+        pass
+
+    assert iterable(Test3()) is False
+
+    class Test4:
+        _iterable = True
+
+    assert iterable(Test4()) is True
+
+    class Test5:
+        def __iter__(self):
+            yield 1
+
+    assert iterable(Test5()) is True
+
+    class Test6(Test5):
+        _iterable = False
+
+    assert iterable(Test6()) is False
+
+
+def test_sequence_partitions():
+    assert list(sequence_partitions([1], 1)) == [[[1]]]
+    assert list(sequence_partitions([1, 2], 1)) == [[[1, 2]]]
+    assert list(sequence_partitions([1, 2], 2)) == [[[1], [2]]]
+    assert list(sequence_partitions([1, 2, 3], 1)) == [[[1, 2, 3]]]
+    assert list(sequence_partitions([1, 2, 3], 2)) == \
+        [[[1], [2, 3]], [[1, 2], [3]]]
+    assert list(sequence_partitions([1, 2, 3], 3)) == [[[1], [2], [3]]]
+
+    # Exceptional cases
+    assert list(sequence_partitions([], 0)) == []
+    assert list(sequence_partitions([], 1)) == []
+    assert list(sequence_partitions([1, 2], 0)) == []
+    assert list(sequence_partitions([1, 2], 3)) == []
+
+
+def test_sequence_partitions_empty():
+    assert list(sequence_partitions_empty([], 1)) == [[[]]]
+    assert list(sequence_partitions_empty([], 2)) == [[[], []]]
+    assert list(sequence_partitions_empty([], 3)) == [[[], [], []]]
+    assert list(sequence_partitions_empty([1], 1)) == [[[1]]]
+    assert list(sequence_partitions_empty([1], 2)) == [[[], [1]], [[1], []]]
+    assert list(sequence_partitions_empty([1], 3)) == \
+        [[[], [], [1]], [[], [1], []], [[1], [], []]]
+    assert list(sequence_partitions_empty([1, 2], 1)) == [[[1, 2]]]
+    assert list(sequence_partitions_empty([1, 2], 2)) == \
+        [[[], [1, 2]], [[1], [2]], [[1, 2], []]]
+    assert list(sequence_partitions_empty([1, 2], 3)) == [
+        [[], [], [1, 2]], [[], [1], [2]], [[], [1, 2], []],
+        [[1], [], [2]], [[1], [2], []], [[1, 2], [], []]
+    ]
+    assert list(sequence_partitions_empty([1, 2, 3], 1)) == [[[1, 2, 3]]]
+    assert list(sequence_partitions_empty([1, 2, 3], 2)) == \
+        [[[], [1, 2, 3]], [[1], [2, 3]], [[1, 2], [3]], [[1, 2, 3], []]]
+    assert list(sequence_partitions_empty([1, 2, 3], 3)) == [
+        [[], [], [1, 2, 3]], [[], [1], [2, 3]],
+        [[], [1, 2], [3]], [[], [1, 2, 3], []],
+        [[1], [], [2, 3]], [[1], [2], [3]],
+        [[1], [2, 3], []], [[1, 2], [], [3]],
+        [[1, 2], [3], []], [[1, 2, 3], [], []]
+    ]
+
+    # Exceptional cases
+    assert list(sequence_partitions([], 0)) == []
+    assert list(sequence_partitions([1], 0)) == []
+    assert list(sequence_partitions([1, 2], 0)) == []
+
+
+def test_signed_permutations():
+    ans = [(0, 1, 1), (0, -1, 1), (0, 1, -1), (0, -1, -1),
+    (1, 0, 1), (-1, 0, 1), (1, 0, -1), (-1, 0, -1),
+    (1, 1, 0), (-1, 1, 0), (1, -1, 0), (-1, -1, 0)]
+    assert list(signed_permutations((0, 1, 1))) == ans
+    assert list(signed_permutations((1, 0, 1))) == ans
+    assert list(signed_permutations((1, 1, 0))) == ans
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_lambdify.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_lambdify.py
new file mode 100644
index 0000000000000000000000000000000000000000..b094c67d39f09c24bcb9abc1e755cb5328e143e7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_lambdify.py
@@ -0,0 +1,2263 @@
+from itertools import product
+import math
+import inspect
+import linecache
+import gc
+
+import mpmath
+import cmath
+
+from sympy.testing.pytest import raises, warns_deprecated_sympy
+from sympy.concrete.summations import Sum
+from sympy.core.function import (Function, Lambda, diff)
+from sympy.core.numbers import (E, Float, I, Rational, all_close, oo, pi)
+from sympy.core.relational import Eq
+from sympy.core.singleton import S
+from sympy.core.symbol import (Dummy, symbols)
+from sympy.functions.combinatorial.factorials import (RisingFactorial, factorial)
+from sympy.functions.combinatorial.numbers import bernoulli, harmonic
+from sympy.functions.elementary.complexes import Abs, sign
+from sympy.functions.elementary.exponential import exp, log
+from sympy.functions.elementary.hyperbolic import asinh,acosh,atanh
+from sympy.functions.elementary.integers import floor
+from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.functions.elementary.trigonometric import (asin, acos, atan, cos, cot, sin,
+                                                      sinc, tan)
+from sympy.functions import sinh,cosh,tanh
+from sympy.functions.special.bessel import (besseli, besselj, besselk, bessely, jn, yn)
+from sympy.functions.special.beta_functions import (beta, betainc, betainc_regularized)
+from sympy.functions.special.delta_functions import (Heaviside)
+from sympy.functions.special.error_functions import (Ei, erf, erfc, fresnelc, fresnels, Si, Ci)
+from sympy.functions.special.gamma_functions import (digamma, gamma, loggamma, polygamma)
+from sympy.functions.special.zeta_functions import zeta
+from sympy.integrals.integrals import Integral
+from sympy.logic.boolalg import (And, false, ITE, Not, Or, true)
+from sympy.matrices.expressions.dotproduct import DotProduct
+from sympy.simplify.cse_main import cse
+from sympy.tensor.array import derive_by_array, Array
+from sympy.tensor.array.expressions import ArraySymbol
+from sympy.tensor.indexed import IndexedBase, Idx
+from sympy.utilities.lambdify import lambdify
+from sympy.utilities.iterables import numbered_symbols
+from sympy.vector import CoordSys3D
+from sympy.core.expr import UnevaluatedExpr
+from sympy.codegen.cfunctions import expm1, log1p, exp2, log2, log10, hypot, isnan, isinf
+from sympy.codegen.numpy_nodes import logaddexp, logaddexp2, amin, amax, minimum, maximum
+from sympy.codegen.scipy_nodes import cosm1, powm1
+from sympy.functions.elementary.complexes import re, im, arg
+from sympy.functions.special.polynomials import \
+    chebyshevt, chebyshevu, legendre, hermite, laguerre, gegenbauer, \
+    assoc_legendre, assoc_laguerre, jacobi
+from sympy.matrices import Matrix, MatrixSymbol, SparseMatrix
+from sympy.printing.codeprinter import PrintMethodNotImplementedError
+from sympy.printing.lambdarepr import LambdaPrinter
+from sympy.printing.numpy import NumPyPrinter
+from sympy.utilities.lambdify import implemented_function, lambdastr
+from sympy.testing.pytest import skip
+from sympy.utilities.decorator import conserve_mpmath_dps
+from sympy.utilities.exceptions import ignore_warnings
+from sympy.external import import_module
+from sympy.functions.special.gamma_functions import uppergamma, lowergamma
+
+
+import sympy
+
+
+MutableDenseMatrix = Matrix
+
+numpy = import_module('numpy')
+scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
+numexpr = import_module('numexpr')
+tensorflow = import_module('tensorflow')
+cupy = import_module('cupy')
+jax = import_module('jax')
+numba = import_module('numba')
+
+if tensorflow:
+    # Hide Tensorflow warnings
+    import os
+    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
+
+w, x, y, z = symbols('w,x,y,z')
+
+#================== Test different arguments =======================
+
+
+def test_no_args():
+    f = lambdify([], 1)
+    raises(TypeError, lambda: f(-1))
+    assert f() == 1
+
+
+def test_single_arg():
+    f = lambdify(x, 2*x)
+    assert f(1) == 2
+
+
+def test_list_args():
+    f = lambdify([x, y], x + y)
+    assert f(1, 2) == 3
+
+
+def test_nested_args():
+    f1 = lambdify([[w, x]], [w, x])
+    assert f1([91, 2]) == [91, 2]
+    raises(TypeError, lambda: f1(1, 2))
+
+    f2 = lambdify([(w, x), (y, z)], [w, x, y, z])
+    assert f2((18, 12), (73, 4)) == [18, 12, 73, 4]
+    raises(TypeError, lambda: f2(3, 4))
+
+    f3 = lambdify([w, [[[x]], y], z], [w, x, y, z])
+    assert f3(10, [[[52]], 31], 44) == [10, 52, 31, 44]
+
+
+def test_str_args():
+    f = lambdify('x,y,z', 'z,y,x')
+    assert f(3, 2, 1) == (1, 2, 3)
+    assert f(1.0, 2.0, 3.0) == (3.0, 2.0, 1.0)
+    # make sure correct number of args required
+    raises(TypeError, lambda: f(0))
+
+
+def test_own_namespace_1():
+    myfunc = lambda x: 1
+    f = lambdify(x, sin(x), {"sin": myfunc})
+    assert f(0.1) == 1
+    assert f(100) == 1
+
+
+def test_own_namespace_2():
+    def myfunc(x):
+        return 1
+    f = lambdify(x, sin(x), {'sin': myfunc})
+    assert f(0.1) == 1
+    assert f(100) == 1
+
+
+def test_own_module():
+    f = lambdify(x, sin(x), math)
+    assert f(0) == 0.0
+
+    p, q, r = symbols("p q r", real=True)
+    ae = abs(exp(p+UnevaluatedExpr(q+r)))
+    f = lambdify([p, q, r], [ae, ae], modules=math)
+    results = f(1.0, 1e18, -1e18)
+    refvals = [math.exp(1.0)]*2
+    for res, ref in zip(results, refvals):
+        assert abs((res-ref)/ref) < 1e-15
+
+
+def test_bad_args():
+    # no vargs given
+    raises(TypeError, lambda: lambdify(1))
+    # same with vector exprs
+    raises(TypeError, lambda: lambdify([1, 2]))
+
+
+def test_atoms():
+    # Non-Symbol atoms should not be pulled out from the expression namespace
+    f = lambdify(x, pi + x, {"pi": 3.14})
+    assert f(0) == 3.14
+    f = lambdify(x, I + x, {"I": 1j})
+    assert f(1) == 1 + 1j
+
+#================== Test different modules =========================
+
+# high precision output of sin(0.2*pi) is used to detect if precision is lost unwanted
+
+
+@conserve_mpmath_dps
+def test_sympy_lambda():
+    mpmath.mp.dps = 50
+    sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
+    f = lambdify(x, sin(x), "sympy")
+    assert f(x) == sin(x)
+    prec = 1e-15
+    assert -prec < f(Rational(1, 5)).evalf() - Float(str(sin02)) < prec
+    # arctan is in numpy module and should not be available
+    # The arctan below gives NameError. What is this supposed to test?
+    # raises(NameError, lambda: lambdify(x, arctan(x), "sympy"))
+
+
+@conserve_mpmath_dps
+def test_math_lambda():
+    mpmath.mp.dps = 50
+    sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
+    f = lambdify(x, sin(x), "math")
+    prec = 1e-15
+    assert -prec < f(0.2) - sin02 < prec
+    raises(TypeError, lambda: f(x))
+           # if this succeeds, it can't be a Python math function
+
+
+@conserve_mpmath_dps
+def test_mpmath_lambda():
+    mpmath.mp.dps = 50
+    sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
+    f = lambdify(x, sin(x), "mpmath")
+    prec = 1e-49  # mpmath precision is around 50 decimal places
+    assert -prec < f(mpmath.mpf("0.2")) - sin02 < prec
+    raises(TypeError, lambda: f(x))
+           # if this succeeds, it can't be a mpmath function
+
+    ref2 = (mpmath.mpf("1e-30")
+            - mpmath.mpf("1e-45")/2
+            + 5*mpmath.mpf("1e-60")/6
+            - 3*mpmath.mpf("1e-75")/4
+            + 33*mpmath.mpf("1e-90")/40
+            )
+    f2a = lambdify((x, y), x**y - 1, "mpmath")
+    f2b = lambdify((x, y), powm1(x, y), "mpmath")
+    f2c = lambdify((x,), expm1(x*log1p(x)), "mpmath")
+    ans2a = f2a(mpmath.mpf("1")+mpmath.mpf("1e-15"), mpmath.mpf("1e-15"))
+    ans2b = f2b(mpmath.mpf("1")+mpmath.mpf("1e-15"), mpmath.mpf("1e-15"))
+    ans2c = f2c(mpmath.mpf("1e-15"))
+    assert abs(ans2a - ref2) < 1e-51
+    assert abs(ans2b - ref2) < 1e-67
+    assert abs(ans2c - ref2) < 1e-80
+
+
+@conserve_mpmath_dps
+def test_number_precision():
+    mpmath.mp.dps = 50
+    sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020")
+    f = lambdify(x, sin02, "mpmath")
+    prec = 1e-49  # mpmath precision is around 50 decimal places
+    assert -prec < f(0) - sin02 < prec
+
+@conserve_mpmath_dps
+def test_mpmath_precision():
+    mpmath.mp.dps = 100
+    assert str(lambdify((), pi.evalf(100), 'mpmath')()) == str(pi.evalf(100))
+
+#================== Test Translations ==============================
+# We can only check if all translated functions are valid. It has to be checked
+# by hand if they are complete.
+
+
+def test_math_transl():
+    from sympy.utilities.lambdify import MATH_TRANSLATIONS
+    for sym, mat in MATH_TRANSLATIONS.items():
+        assert sym in sympy.__dict__
+        assert mat in math.__dict__
+
+
+def test_mpmath_transl():
+    from sympy.utilities.lambdify import MPMATH_TRANSLATIONS
+    for sym, mat in MPMATH_TRANSLATIONS.items():
+        assert sym in sympy.__dict__ or sym == 'Matrix'
+        assert mat in mpmath.__dict__
+
+
+def test_numpy_transl():
+    if not numpy:
+        skip("numpy not installed.")
+
+    from sympy.utilities.lambdify import NUMPY_TRANSLATIONS
+    for sym, nump in NUMPY_TRANSLATIONS.items():
+        assert sym in sympy.__dict__
+        assert nump in numpy.__dict__
+
+
+def test_scipy_transl():
+    if not scipy:
+        skip("scipy not installed.")
+
+    from sympy.utilities.lambdify import SCIPY_TRANSLATIONS
+    for sym, scip in SCIPY_TRANSLATIONS.items():
+        assert sym in sympy.__dict__
+        assert scip in scipy.__dict__ or scip in scipy.special.__dict__
+
+
+def test_numpy_translation_abs():
+    if not numpy:
+        skip("numpy not installed.")
+
+    f = lambdify(x, Abs(x), "numpy")
+    assert f(-1) == 1
+    assert f(1) == 1
+
+
+def test_numexpr_printer():
+    if not numexpr:
+        skip("numexpr not installed.")
+
+    # if translation/printing is done incorrectly then evaluating
+    # a lambdified numexpr expression will throw an exception
+    from sympy.printing.lambdarepr import NumExprPrinter
+
+    blacklist = ('where', 'complex', 'contains')
+    arg_tuple = (x, y, z) # some functions take more than one argument
+    for sym in NumExprPrinter._numexpr_functions.keys():
+        if sym in blacklist:
+            continue
+        ssym = S(sym)
+        if hasattr(ssym, '_nargs'):
+            nargs = ssym._nargs[0]
+        else:
+            nargs = 1
+        args = arg_tuple[:nargs]
+        f = lambdify(args, ssym(*args), modules='numexpr')
+        assert f(*(1, )*nargs) is not None
+
+
+def test_cmath_sqrt():
+    f = lambdify(x, sqrt(x), "cmath")
+    assert f(0) == 0
+    assert f(1) == 1
+    assert f(4) == 2
+    assert abs(f(2) - 1.414) < 0.001
+    assert f(-1) == 1j
+    assert f(-4) == 2j
+
+
+def test_cmath_log():
+    f = lambdify(x, log(x), "cmath")
+    assert abs(f(1) - 0) < 1e-15
+    assert abs(f(cmath.e) - 1) < 1e-15
+    assert abs(f(-1) - cmath.log(-1)) < 1e-15
+
+
+def test_cmath_sinh():
+    f = lambdify(x, sinh(x), "cmath")
+    assert abs(f(0) - cmath.sinh(0)) < 1e-15
+    assert abs(f(pi) - cmath.sinh(pi)) < 1e-15
+    assert abs(f(-pi) - cmath.sinh(-pi)) < 1e-15
+    assert abs(f(1j) - cmath.sinh(1j)) < 1e-15
+
+
+def test_cmath_cosh():
+    f = lambdify(x, cosh(x), "cmath")
+    assert abs(f(0) - cmath.cosh(0)) < 1e-15
+    assert abs(f(pi) - cmath.cosh(pi)) < 1e-15
+    assert abs(f(-pi) - cmath.cosh(-pi)) < 1e-15
+    assert abs(f(1j) - cmath.cosh(1j)) < 1e-15
+
+
+def test_cmath_tanh():
+    f = lambdify(x, tanh(x), "cmath")
+    assert abs(f(0) - cmath.tanh(0)) < 1e-15
+    assert abs(f(pi) - cmath.tanh(pi)) < 1e-15
+    assert abs(f(-pi) - cmath.tanh(-pi)) < 1e-15
+    assert abs(f(1j) - cmath.tanh(1j)) < 1e-15
+
+
+def test_cmath_sin():
+    f = lambdify(x, sin(x), "cmath")
+    assert abs(f(0) - cmath.sin(0)) < 1e-15
+    assert abs(f(pi) - cmath.sin(pi)) < 1e-15
+    assert abs(f(-pi) - cmath.sin(-pi)) < 1e-15
+    assert abs(f(1j) - cmath.sin(1j)) < 1e-15
+
+
+def test_cmath_cos():
+    f = lambdify(x, cos(x), "cmath")
+    assert abs(f(0) - cmath.cos(0)) < 1e-15
+    assert abs(f(pi) - cmath.cos(pi)) < 1e-15
+    assert abs(f(-pi) - cmath.cos(-pi)) < 1e-15
+    assert abs(f(1j) - cmath.cos(1j)) < 1e-15
+
+
+def test_cmath_tan():
+    f = lambdify(x, tan(x), "cmath")
+    assert abs(f(0) - cmath.tan(0)) < 1e-15
+    assert abs(f(1j) - cmath.tan(1j)) < 1e-15
+
+
+def test_cmath_asin():
+    f = lambdify(x, asin(x), "cmath")
+    assert abs(f(0) - cmath.asin(0)) < 1e-15
+    assert abs(f(1) - cmath.asin(1)) < 1e-15
+    assert abs(f(-1) - cmath.asin(-1)) < 1e-15
+    assert abs(f(2) - cmath.asin(2)) < 1e-15
+    assert abs(f(1j) - cmath.asin(1j)) < 1e-15
+
+
+def test_cmath_acos():
+    f = lambdify(x, acos(x), "cmath")
+    assert abs(f(1) - cmath.acos(1)) < 1e-15
+    assert abs(f(-1) - cmath.acos(-1)) < 1e-15
+    assert abs(f(2) - cmath.acos(2)) < 1e-15
+    assert abs(f(1j) - cmath.acos(1j)) < 1e-15
+
+
+def test_cmath_atan():
+    f = lambdify(x, atan(x), "cmath")
+    assert abs(f(0) - cmath.atan(0)) < 1e-15
+    assert abs(f(1) - cmath.atan(1)) < 1e-15
+    assert abs(f(-1) - cmath.atan(-1)) < 1e-15
+    assert abs(f(2) - cmath.atan(2)) < 1e-15
+    assert abs(f(2j) - cmath.atan(2j)) < 1e-15
+
+
+def test_cmath_asinh():
+    f = lambdify(x, asinh(x), "cmath")
+    assert abs(f(0) - cmath.asinh(0)) < 1e-15
+    assert abs(f(1) - cmath.asinh(1)) < 1e-15
+    assert abs(f(-1) - cmath.asinh(-1)) < 1e-15
+    assert abs(f(2) - cmath.asinh(2)) < 1e-15
+    assert abs(f(2j) - cmath.asinh(2j)) < 1e-15
+
+
+def test_cmath_acosh():
+    f = lambdify(x, acosh(x), "cmath")
+    assert abs(f(1) - cmath.acosh(1)) < 1e-15
+    assert abs(f(2) - cmath.acosh(2)) < 1e-15
+    assert abs(f(-1) - cmath.acosh(-1)) < 1e-15
+    assert abs(f(2j) - cmath.acosh(2j)) < 1e-15
+
+
+def test_cmath_atanh():
+    f = lambdify(x, atanh(x), "cmath")
+    assert abs(f(0) - cmath.atanh(0)) < 1e-15
+    assert abs(f(0.5) - cmath.atanh(0.5)) < 1e-15
+    assert abs(f(-0.5) - cmath.atanh(-0.5)) < 1e-15
+    assert abs(f(2) - cmath.atanh(2)) < 1e-15
+    assert abs(f(-2) - cmath.atanh(-2)) < 1e-15
+    assert abs(f(2j) - cmath.atanh(2j)) < 1e-15
+
+
+def test_cmath_complex_identities():
+    # Define symbol
+    z = symbols('z')
+
+    # Trigonometric identity using re(z) and im(z)
+    expr = cos(z) - cos(re(z)) * cosh(im(z)) + I * sin(re(z)) * sinh(im(z))
+    func = lambdify([z], expr, modules=["cmath", "math"])
+    hpi = math.pi / 2
+    assert abs(func(hpi + 1j * hpi)) < 4e-16
+
+    # Euler's Formula: e^(i*z) = cos(z) + i*sin(z)
+    func = lambdify([z], exp(I * z) - (cos(z) + I * sin(z)), modules=["cmath", "math"])
+    assert abs(func(hpi)) < 4e-16
+
+    # Exponential Identity: e^z = e^(Re(z)) * (cos(Im(z)) + i*sin(Im(z)))
+    func_exp = lambdify([z], exp(z) - exp(re(z)) * (cos(im(z)) + I * sin(im(z))),
+                        modules=["cmath", "math"])
+    assert abs(func_exp(hpi + 1j * hpi)) < 4e-16
+
+    # Complex Cosine Identity: cos(z) = cos(Re(z)) * cosh(Im(z)) - i*sin(Re(z)) * sinh(Im(z))
+    func_cos = lambdify([z], cos(z) - (cos(re(z)) * cosh(im(z)) - I * sin(re(z)) * sinh(im(z))),
+                        modules=["cmath", "math"])
+    assert abs(func_cos(hpi + 1j * hpi)) < 4e-16
+
+    # Complex Sine Identity: sin(z) = sin(Re(z)) * cosh(Im(z)) + i*cos(Re(z)) * sinh(Im(z))
+    func_sin = lambdify([z], sin(z) - (sin(re(z)) * cosh(im(z)) + I * cos(re(z)) * sinh(im(z))),
+                        modules=["cmath", "math"])
+    assert abs(func_sin(hpi + 1j * hpi)) < 4e-16
+
+    # Complex Hyperbolic Cosine Identity: cosh(z) = cosh(Re(z)) * cos(Im(z)) + i*sinh(Re(z)) * sin(Im(z))
+    func_cosh_1 = lambdify([z], cosh(z) - (cosh(re(z)) * cos(im(z)) + I * sinh(re(z)) * sin(im(z))),
+                         modules=["cmath", "math"])
+    assert abs(func_cosh_1(hpi + 1j * hpi)) < 4e-16
+
+    # Complex Hyperbolic Sine Identity: sinh(z) = sinh(Re(z)) * cos(Im(z)) + i*cosh(Re(z)) * sin(Im(z))
+    func_sinh = lambdify([z], sinh(z) - (sinh(re(z)) * cos(im(z)) + I * cosh(re(z)) * sin(im(z))),
+                         modules=["cmath", "math"])
+    assert abs(func_sinh(hpi + 1j * hpi)) < 4e-16
+
+    # cosh(z) = (e^z + e^(-z)) / 2
+    func_cosh_2 = lambdify([z], cosh(z) - (exp(z) + exp(-z)) / 2, modules=["cmath", "math"])
+    assert abs(func_cosh_2(hpi)) < 4e-16
+
+    # Additional expressions testing log and exp with real and imaginary parts
+    expr1 = log(re(z)) + log(im(z)) - log(re(z) * im(z))
+    expr2 = exp(re(z)) * exp(im(z) * I) - exp(z)
+    expr3 = log(exp(re(z))) - re(z)
+    expr4 = exp(log(re(z))) - re(z)
+    expr5 = log(exp(re(z) + im(z))) - (re(z) + im(z))
+    expr6 = exp(log(re(z) + im(z))) - (re(z) + im(z))
+    func1 = lambdify([z], expr1, modules=["cmath", "math"])
+    func2 = lambdify([z], expr2, modules=["cmath", "math"])
+    func3 = lambdify([z], expr3, modules=["cmath", "math"])
+    func4 = lambdify([z], expr4, modules=["cmath", "math"])
+    func5 = lambdify([z], expr5, modules=["cmath", "math"])
+    func6 = lambdify([z], expr6, modules=["cmath", "math"])
+    test_value = 3 + 4j
+    assert abs(func1(test_value)) < 4e-16
+    assert abs(func2(test_value)) < 4e-16
+    assert abs(func3(test_value)) < 4e-16
+    assert abs(func4(test_value)) < 4e-16
+    assert abs(func5(test_value)) < 4e-16
+    assert abs(func6(test_value)) < 4e-16
+
+
+def test_issue_9334():
+    if not numexpr:
+        skip("numexpr not installed.")
+    if not numpy:
+        skip("numpy not installed.")
+    expr = S('b*a - sqrt(a**2)')
+    a, b = sorted(expr.free_symbols, key=lambda s: s.name)
+    func_numexpr = lambdify((a,b), expr, modules=[numexpr], dummify=False)
+    foo, bar = numpy.random.random((2, 4))
+    func_numexpr(foo, bar)
+
+
+def test_issue_12984():
+    if not numexpr:
+        skip("numexpr not installed.")
+    func_numexpr = lambdify((x,y,z), Piecewise((y, x >= 0), (z, x > -1)), numexpr)
+    with ignore_warnings(RuntimeWarning):
+        assert func_numexpr(1, 24, 42) == 24
+        assert str(func_numexpr(-1, 24, 42)) == 'nan'
+
+
+def test_empty_modules():
+    x, y = symbols('x y')
+    expr = -(x % y)
+
+    no_modules = lambdify([x, y], expr)
+    empty_modules = lambdify([x, y], expr, modules=[])
+    assert no_modules(3, 7) == empty_modules(3, 7)
+    assert no_modules(3, 7) == -3
+
+
+def test_exponentiation():
+    f = lambdify(x, x**2)
+    assert f(-1) == 1
+    assert f(0) == 0
+    assert f(1) == 1
+    assert f(-2) == 4
+    assert f(2) == 4
+    assert f(2.5) == 6.25
+
+
+def test_sqrt():
+    f = lambdify(x, sqrt(x))
+    assert f(0) == 0.0
+    assert f(1) == 1.0
+    assert f(4) == 2.0
+    assert abs(f(2) - 1.414) < 0.001
+    assert f(6.25) == 2.5
+
+
+def test_trig():
+    f = lambdify([x], [cos(x), sin(x)], 'math')
+    d = f(pi)
+    prec = 1e-11
+    assert -prec < d[0] + 1 < prec
+    assert -prec < d[1] < prec
+    d = f(3.14159)
+    prec = 1e-5
+    assert -prec < d[0] + 1 < prec
+    assert -prec < d[1] < prec
+
+
+def test_integral():
+    if numpy and not scipy:
+        skip("scipy not installed.")
+    f = Lambda(x, exp(-x**2))
+    l = lambdify(y, Integral(f(x), (x, y, oo)))
+    d = l(-oo)
+    assert 1.77245385 < d < 1.772453851
+
+
+def test_double_integral():
+    if numpy and not scipy:
+        skip("scipy not installed.")
+    # example from http://mpmath.org/doc/current/calculus/integration.html
+    i = Integral(1/(1 - x**2*y**2), (x, 0, 1), (y, 0, z))
+    l = lambdify([z], i)
+    d = l(1)
+    assert 1.23370055 < d < 1.233700551
+
+def test_spherical_bessel():
+    if numpy and not scipy:
+        skip("scipy not installed.")
+    test_point = 4.2 #randomly selected
+    x = symbols("x")
+    jtest = jn(2, x)
+    assert abs(lambdify(x,jtest)(test_point) -
+            jtest.subs(x,test_point).evalf()) < 1e-8
+    ytest = yn(2, x)
+    assert abs(lambdify(x,ytest)(test_point) -
+            ytest.subs(x,test_point).evalf()) < 1e-8
+
+
+#================== Test vectors ===================================
+
+
+def test_vector_simple():
+    f = lambdify((x, y, z), (z, y, x))
+    assert f(3, 2, 1) == (1, 2, 3)
+    assert f(1.0, 2.0, 3.0) == (3.0, 2.0, 1.0)
+    # make sure correct number of args required
+    raises(TypeError, lambda: f(0))
+
+
+def test_vector_discontinuous():
+    f = lambdify(x, (-1/x, 1/x))
+    raises(ZeroDivisionError, lambda: f(0))
+    assert f(1) == (-1.0, 1.0)
+    assert f(2) == (-0.5, 0.5)
+    assert f(-2) == (0.5, -0.5)
+
+
+def test_trig_symbolic():
+    f = lambdify([x], [cos(x), sin(x)], 'math')
+    d = f(pi)
+    assert abs(d[0] + 1) < 0.0001
+    assert abs(d[1] - 0) < 0.0001
+
+
+def test_trig_float():
+    f = lambdify([x], [cos(x), sin(x)])
+    d = f(3.14159)
+    assert abs(d[0] + 1) < 0.0001
+    assert abs(d[1] - 0) < 0.0001
+
+
+def test_docs():
+    f = lambdify(x, x**2)
+    assert f(2) == 4
+    f = lambdify([x, y, z], [z, y, x])
+    assert f(1, 2, 3) == [3, 2, 1]
+    f = lambdify(x, sqrt(x))
+    assert f(4) == 2.0
+    f = lambdify((x, y), sin(x*y)**2)
+    assert f(0, 5) == 0
+
+
+def test_math():
+    f = lambdify((x, y), sin(x), modules="math")
+    assert f(0, 5) == 0
+
+
+def test_sin():
+    f = lambdify(x, sin(x)**2)
+    assert isinstance(f(2), float)
+    f = lambdify(x, sin(x)**2, modules="math")
+    assert isinstance(f(2), float)
+
+
+def test_matrix():
+    A = Matrix([[x, x*y], [sin(z) + 4, x**z]])
+    sol = Matrix([[1, 2], [sin(3) + 4, 1]])
+    f = lambdify((x, y, z), A, modules="sympy")
+    assert f(1, 2, 3) == sol
+    f = lambdify((x, y, z), (A, [A]), modules="sympy")
+    assert f(1, 2, 3) == (sol, [sol])
+    J = Matrix((x, x + y)).jacobian((x, y))
+    v = Matrix((x, y))
+    sol = Matrix([[1, 0], [1, 1]])
+    assert lambdify(v, J, modules='sympy')(1, 2) == sol
+    assert lambdify(v.T, J, modules='sympy')(1, 2) == sol
+
+
+def test_numpy_matrix():
+    if not numpy:
+        skip("numpy not installed.")
+    A = Matrix([[x, x*y], [sin(z) + 4, x**z]])
+    sol_arr = numpy.array([[1, 2], [numpy.sin(3) + 4, 1]])
+    #Lambdify array first, to ensure return to array as default
+    f = lambdify((x, y, z), A, ['numpy'])
+    numpy.testing.assert_allclose(f(1, 2, 3), sol_arr)
+    #Check that the types are arrays and matrices
+    assert isinstance(f(1, 2, 3), numpy.ndarray)
+
+    # gh-15071
+    class dot(Function):
+        pass
+    x_dot_mtx = dot(x, Matrix([[2], [1], [0]]))
+    f_dot1 = lambdify(x, x_dot_mtx)
+    inp = numpy.zeros((17, 3))
+    assert numpy.all(f_dot1(inp) == 0)
+
+    strict_kw = {"allow_unknown_functions": False, "inline": True, "fully_qualified_modules": False}
+    p2 = NumPyPrinter(dict(user_functions={'dot': 'dot'}, **strict_kw))
+    f_dot2 = lambdify(x, x_dot_mtx, printer=p2)
+    assert numpy.all(f_dot2(inp) == 0)
+
+    p3 = NumPyPrinter(strict_kw)
+    # The line below should probably fail upon construction (before calling with "(inp)"):
+    raises(Exception, lambda: lambdify(x, x_dot_mtx, printer=p3)(inp))
+
+
+def test_numpy_transpose():
+    if not numpy:
+        skip("numpy not installed.")
+    A = Matrix([[1, x], [0, 1]])
+    f = lambdify((x), A.T, modules="numpy")
+    numpy.testing.assert_array_equal(f(2), numpy.array([[1, 0], [2, 1]]))
+
+
+def test_numpy_dotproduct():
+    if not numpy:
+        skip("numpy not installed")
+    A = Matrix([x, y, z])
+    f1 = lambdify([x, y, z], DotProduct(A, A), modules='numpy')
+    f2 = lambdify([x, y, z], DotProduct(A, A.T), modules='numpy')
+    f3 = lambdify([x, y, z], DotProduct(A.T, A), modules='numpy')
+    f4 = lambdify([x, y, z], DotProduct(A, A.T), modules='numpy')
+
+    assert f1(1, 2, 3) == \
+           f2(1, 2, 3) == \
+           f3(1, 2, 3) == \
+           f4(1, 2, 3) == \
+           numpy.array([14])
+
+
+def test_numpy_inverse():
+    if not numpy:
+        skip("numpy not installed.")
+    A = Matrix([[1, x], [0, 1]])
+    f = lambdify((x), A**-1, modules="numpy")
+    numpy.testing.assert_array_equal(f(2), numpy.array([[1, -2], [0,  1]]))
+
+
+def test_numpy_old_matrix():
+    if not numpy:
+        skip("numpy not installed.")
+    A = Matrix([[x, x*y], [sin(z) + 4, x**z]])
+    sol_arr = numpy.array([[1, 2], [numpy.sin(3) + 4, 1]])
+    f = lambdify((x, y, z), A, [{'ImmutableDenseMatrix': numpy.matrix}, 'numpy'])
+    with ignore_warnings(PendingDeprecationWarning):
+        numpy.testing.assert_allclose(f(1, 2, 3), sol_arr)
+        assert isinstance(f(1, 2, 3), numpy.matrix)
+
+
+def test_scipy_sparse_matrix():
+    if not scipy:
+        skip("scipy not installed.")
+    A = SparseMatrix([[x, 0], [0, y]])
+    f = lambdify((x, y), A, modules="scipy")
+    B = f(1, 2)
+    assert isinstance(B, scipy.sparse.coo_matrix)
+
+
+def test_python_div_zero_issue_11306():
+    if not numpy:
+        skip("numpy not installed.")
+    p = Piecewise((1 / x, y < -1), (x, y < 1), (1 / x, True))
+    f = lambdify([x, y], p, modules='numpy')
+    with numpy.errstate(divide='ignore'):
+        assert float(f(numpy.array(0), numpy.array(0.5))) == 0
+        assert float(f(numpy.array(0), numpy.array(1))) == float('inf')
+
+
+def test_issue9474():
+    mods = [None, 'math']
+    if numpy:
+        mods.append('numpy')
+    if mpmath:
+        mods.append('mpmath')
+    for mod in mods:
+        f = lambdify(x, S.One/x, modules=mod)
+        assert f(2) == 0.5
+        f = lambdify(x, floor(S.One/x), modules=mod)
+        assert f(2) == 0
+
+    for absfunc, modules in product([Abs, abs], mods):
+        f = lambdify(x, absfunc(x), modules=modules)
+        assert f(-1) == 1
+        assert f(1) == 1
+        assert f(3+4j) == 5
+
+
+def test_issue_9871():
+    if not numexpr:
+        skip("numexpr not installed.")
+    if not numpy:
+        skip("numpy not installed.")
+
+    r = sqrt(x**2 + y**2)
+    expr = diff(1/r, x)
+
+    xn = yn = numpy.linspace(1, 10, 16)
+    # expr(xn, xn) = -xn/(sqrt(2)*xn)^3
+    fv_exact = -numpy.sqrt(2.)**-3 * xn**-2
+
+    fv_numpy = lambdify((x, y), expr, modules='numpy')(xn, yn)
+    fv_numexpr = lambdify((x, y), expr, modules='numexpr')(xn, yn)
+    numpy.testing.assert_allclose(fv_numpy, fv_exact, rtol=1e-10)
+    numpy.testing.assert_allclose(fv_numexpr, fv_exact, rtol=1e-10)
+
+
+def test_numpy_piecewise():
+    if not numpy:
+        skip("numpy not installed.")
+    pieces = Piecewise((x, x < 3), (x**2, x > 5), (0, True))
+    f = lambdify(x, pieces, modules="numpy")
+    numpy.testing.assert_array_equal(f(numpy.arange(10)),
+                                     numpy.array([0, 1, 2, 0, 0, 0, 36, 49, 64, 81]))
+    # If we evaluate somewhere all conditions are False, we should get back NaN
+    nodef_func = lambdify(x, Piecewise((x, x > 0), (-x, x < 0)))
+    numpy.testing.assert_array_equal(nodef_func(numpy.array([-1, 0, 1])),
+                                     numpy.array([1, numpy.nan, 1]))
+
+
+def test_numpy_logical_ops():
+    if not numpy:
+        skip("numpy not installed.")
+    and_func = lambdify((x, y), And(x, y), modules="numpy")
+    and_func_3 = lambdify((x, y, z), And(x, y, z), modules="numpy")
+    or_func = lambdify((x, y), Or(x, y), modules="numpy")
+    or_func_3 = lambdify((x, y, z), Or(x, y, z), modules="numpy")
+    not_func = lambdify((x), Not(x), modules="numpy")
+    arr1 = numpy.array([True, True])
+    arr2 = numpy.array([False, True])
+    arr3 = numpy.array([True, False])
+    numpy.testing.assert_array_equal(and_func(arr1, arr2), numpy.array([False, True]))
+    numpy.testing.assert_array_equal(and_func_3(arr1, arr2, arr3), numpy.array([False, False]))
+    numpy.testing.assert_array_equal(or_func(arr1, arr2), numpy.array([True, True]))
+    numpy.testing.assert_array_equal(or_func_3(arr1, arr2, arr3), numpy.array([True, True]))
+    numpy.testing.assert_array_equal(not_func(arr2), numpy.array([True, False]))
+
+
+def test_numpy_matmul():
+    if not numpy:
+        skip("numpy not installed.")
+    xmat = Matrix([[x, y], [z, 1+z]])
+    ymat = Matrix([[x**2], [Abs(x)]])
+    mat_func = lambdify((x, y, z), xmat*ymat, modules="numpy")
+    numpy.testing.assert_array_equal(mat_func(0.5, 3, 4), numpy.array([[1.625], [3.5]]))
+    numpy.testing.assert_array_equal(mat_func(-0.5, 3, 4), numpy.array([[1.375], [3.5]]))
+    # Multiple matrices chained together in multiplication
+    f = lambdify((x, y, z), xmat*xmat*xmat, modules="numpy")
+    numpy.testing.assert_array_equal(f(0.5, 3, 4), numpy.array([[72.125, 119.25],
+                                                                [159, 251]]))
+
+
+def test_numpy_numexpr():
+    if not numpy:
+        skip("numpy not installed.")
+    if not numexpr:
+        skip("numexpr not installed.")
+    a, b, c = numpy.random.randn(3, 128, 128)
+    # ensure that numpy and numexpr return same value for complicated expression
+    expr = sin(x) + cos(y) + tan(z)**2 + Abs(z-y)*acos(sin(y*z)) + \
+           Abs(y-z)*acosh(2+exp(y-x))- sqrt(x**2+I*y**2)
+    npfunc = lambdify((x, y, z), expr, modules='numpy')
+    nefunc = lambdify((x, y, z), expr, modules='numexpr')
+    assert numpy.allclose(npfunc(a, b, c), nefunc(a, b, c))
+
+
+def test_numexpr_userfunctions():
+    if not numpy:
+        skip("numpy not installed.")
+    if not numexpr:
+        skip("numexpr not installed.")
+    a, b = numpy.random.randn(2, 10)
+    uf = type('uf', (Function, ),
+              {'eval' : classmethod(lambda x, y : y**2+1)})
+    func = lambdify(x, 1-uf(x), modules='numexpr')
+    assert numpy.allclose(func(a), -(a**2))
+
+    uf = implemented_function(Function('uf'), lambda x, y : 2*x*y+1)
+    func = lambdify((x, y), uf(x, y), modules='numexpr')
+    assert numpy.allclose(func(a, b), 2*a*b+1)
+
+
+def test_tensorflow_basic_math():
+    if not tensorflow:
+        skip("tensorflow not installed.")
+    expr = Max(sin(x), Abs(1/(x+2)))
+    func = lambdify(x, expr, modules="tensorflow")
+
+    with tensorflow.compat.v1.Session() as s:
+        a = tensorflow.constant(0, dtype=tensorflow.float32)
+        assert func(a).eval(session=s) == 0.5
+
+
+def test_tensorflow_placeholders():
+    if not tensorflow:
+        skip("tensorflow not installed.")
+    expr = Max(sin(x), Abs(1/(x+2)))
+    func = lambdify(x, expr, modules="tensorflow")
+
+    with tensorflow.compat.v1.Session() as s:
+        a = tensorflow.compat.v1.placeholder(dtype=tensorflow.float32)
+        assert func(a).eval(session=s, feed_dict={a: 0}) == 0.5
+
+
+def test_tensorflow_variables():
+    if not tensorflow:
+        skip("tensorflow not installed.")
+    expr = Max(sin(x), Abs(1/(x+2)))
+    func = lambdify(x, expr, modules="tensorflow")
+
+    with tensorflow.compat.v1.Session() as s:
+        a = tensorflow.Variable(0, dtype=tensorflow.float32)
+        s.run(a.initializer)
+        assert func(a).eval(session=s, feed_dict={a: 0}) == 0.5
+
+
+def test_tensorflow_logical_operations():
+    if not tensorflow:
+        skip("tensorflow not installed.")
+    expr = Not(And(Or(x, y), y))
+    func = lambdify([x, y], expr, modules="tensorflow")
+
+    with tensorflow.compat.v1.Session() as s:
+        assert func(False, True).eval(session=s) == False
+
+
+def test_tensorflow_piecewise():
+    if not tensorflow:
+        skip("tensorflow not installed.")
+    expr = Piecewise((0, Eq(x,0)), (-1, x < 0), (1, x > 0))
+    func = lambdify(x, expr, modules="tensorflow")
+
+    with tensorflow.compat.v1.Session() as s:
+        assert func(-1).eval(session=s) == -1
+        assert func(0).eval(session=s) == 0
+        assert func(1).eval(session=s) == 1
+
+
+def test_tensorflow_multi_max():
+    if not tensorflow:
+        skip("tensorflow not installed.")
+    expr = Max(x, -x, x**2)
+    func = lambdify(x, expr, modules="tensorflow")
+
+    with tensorflow.compat.v1.Session() as s:
+        assert func(-2).eval(session=s) == 4
+
+
+def test_tensorflow_multi_min():
+    if not tensorflow:
+        skip("tensorflow not installed.")
+    expr = Min(x, -x, x**2)
+    func = lambdify(x, expr, modules="tensorflow")
+
+    with tensorflow.compat.v1.Session() as s:
+        assert func(-2).eval(session=s) == -2
+
+
+def test_tensorflow_relational():
+    if not tensorflow:
+        skip("tensorflow not installed.")
+    expr = x >= 0
+    func = lambdify(x, expr, modules="tensorflow")
+
+    with tensorflow.compat.v1.Session() as s:
+        assert func(1).eval(session=s) == True
+
+
+def test_tensorflow_complexes():
+    if not tensorflow:
+        skip("tensorflow not installed")
+
+    func1 = lambdify(x, re(x), modules="tensorflow")
+    func2 = lambdify(x, im(x), modules="tensorflow")
+    func3 = lambdify(x, Abs(x), modules="tensorflow")
+    func4 = lambdify(x, arg(x), modules="tensorflow")
+
+    with tensorflow.compat.v1.Session() as s:
+        # For versions before
+        # https://github.com/tensorflow/tensorflow/issues/30029
+        # resolved, using Python numeric types may not work
+        a = tensorflow.constant(1+2j)
+        assert func1(a).eval(session=s) == 1
+        assert func2(a).eval(session=s) == 2
+
+        tensorflow_result = func3(a).eval(session=s)
+        sympy_result = Abs(1 + 2j).evalf()
+        assert abs(tensorflow_result-sympy_result) < 10**-6
+
+        tensorflow_result = func4(a).eval(session=s)
+        sympy_result = arg(1 + 2j).evalf()
+        assert abs(tensorflow_result-sympy_result) < 10**-6
+
+
+def test_tensorflow_array_arg():
+    # Test for issue 14655 (tensorflow part)
+    if not tensorflow:
+        skip("tensorflow not installed.")
+
+    f = lambdify([[x, y]], x*x + y, 'tensorflow')
+
+    with tensorflow.compat.v1.Session() as s:
+        fcall = f(tensorflow.constant([2.0, 1.0]))
+        assert fcall.eval(session=s) == 5.0
+
+
+#================== Test symbolic ==================================
+
+
+def test_sym_single_arg():
+    f = lambdify(x, x * y)
+    assert f(z) == z * y
+
+
+def test_sym_list_args():
+    f = lambdify([x, y], x + y + z)
+    assert f(1, 2) == 3 + z
+
+
+def test_sym_integral():
+    f = Lambda(x, exp(-x**2))
+    l = lambdify(x, Integral(f(x), (x, -oo, oo)), modules="sympy")
+    assert l(y) == Integral(exp(-y**2), (y, -oo, oo))
+    assert l(y).doit() == sqrt(pi)
+
+
+def test_namespace_order():
+    # lambdify had a bug, such that module dictionaries or cached module
+    # dictionaries would pull earlier namespaces into themselves.
+    # Because the module dictionaries form the namespace of the
+    # generated lambda, this meant that the behavior of a previously
+    # generated lambda function could change as a result of later calls
+    # to lambdify.
+    n1 = {'f': lambda x: 'first f'}
+    n2 = {'f': lambda x: 'second f',
+          'g': lambda x: 'function g'}
+    f = sympy.Function('f')
+    g = sympy.Function('g')
+    if1 = lambdify(x, f(x), modules=(n1, "sympy"))
+    assert if1(1) == 'first f'
+    if2 = lambdify(x, g(x), modules=(n2, "sympy"))
+    # previously gave 'second f'
+    assert if1(1) == 'first f'
+
+    assert if2(1) == 'function g'
+
+
+def test_imps():
+    # Here we check if the default returned functions are anonymous - in
+    # the sense that we can have more than one function with the same name
+    f = implemented_function('f', lambda x: 2*x)
+    g = implemented_function('f', lambda x: math.sqrt(x))
+    l1 = lambdify(x, f(x))
+    l2 = lambdify(x, g(x))
+    assert str(f(x)) == str(g(x))
+    assert l1(3) == 6
+    assert l2(3) == math.sqrt(3)
+    # check that we can pass in a Function as input
+    func = sympy.Function('myfunc')
+    assert not hasattr(func, '_imp_')
+    my_f = implemented_function(func, lambda x: 2*x)
+    assert hasattr(my_f, '_imp_')
+    # Error for functions with same name and different implementation
+    f2 = implemented_function("f", lambda x: x + 101)
+    raises(ValueError, lambda: lambdify(x, f(f2(x))))
+
+
+def test_imps_errors():
+    # Test errors that implemented functions can return, and still be able to
+    # form expressions.
+    # See: https://github.com/sympy/sympy/issues/10810
+    #
+    # XXX: Removed AttributeError here. This test was added due to issue 10810
+    # but that issue was about ValueError. It doesn't seem reasonable to
+    # "support" catching AttributeError in the same context...
+    for val, error_class in product((0, 0., 2, 2.0), (TypeError, ValueError)):
+
+        def myfunc(a):
+            if a == 0:
+                raise error_class
+            return 1
+
+        f = implemented_function('f', myfunc)
+        expr = f(val)
+        assert expr == f(val)
+
+
+def test_imps_wrong_args():
+    raises(ValueError, lambda: implemented_function(sin, lambda x: x))
+
+
+def test_lambdify_imps():
+    # Test lambdify with implemented functions
+    # first test basic (sympy) lambdify
+    f = sympy.cos
+    assert lambdify(x, f(x))(0) == 1
+    assert lambdify(x, 1 + f(x))(0) == 2
+    assert lambdify((x, y), y + f(x))(0, 1) == 2
+    # make an implemented function and test
+    f = implemented_function("f", lambda x: x + 100)
+    assert lambdify(x, f(x))(0) == 100
+    assert lambdify(x, 1 + f(x))(0) == 101
+    assert lambdify((x, y), y + f(x))(0, 1) == 101
+    # Can also handle tuples, lists, dicts as expressions
+    lam = lambdify(x, (f(x), x))
+    assert lam(3) == (103, 3)
+    lam = lambdify(x, [f(x), x])
+    assert lam(3) == [103, 3]
+    lam = lambdify(x, [f(x), (f(x), x)])
+    assert lam(3) == [103, (103, 3)]
+    lam = lambdify(x, {f(x): x})
+    assert lam(3) == {103: 3}
+    lam = lambdify(x, {f(x): x})
+    assert lam(3) == {103: 3}
+    lam = lambdify(x, {x: f(x)})
+    assert lam(3) == {3: 103}
+    # Check that imp preferred to other namespaces by default
+    d = {'f': lambda x: x + 99}
+    lam = lambdify(x, f(x), d)
+    assert lam(3) == 103
+    # Unless flag passed
+    lam = lambdify(x, f(x), d, use_imps=False)
+    assert lam(3) == 102
+
+
+def test_dummification():
+    t = symbols('t')
+    F = Function('F')
+    G = Function('G')
+    #"\alpha" is not a valid Python variable name
+    #lambdify should sub in a dummy for it, and return
+    #without a syntax error
+    alpha = symbols(r'\alpha')
+    some_expr = 2 * F(t)**2 / G(t)
+    lam = lambdify((F(t), G(t)), some_expr)
+    assert lam(3, 9) == 2
+    lam = lambdify(sin(t), 2 * sin(t)**2)
+    assert lam(F(t)) == 2 * F(t)**2
+    #Test that \alpha was properly dummified
+    lam = lambdify((alpha, t), 2*alpha + t)
+    assert lam(2, 1) == 5
+    raises(SyntaxError, lambda: lambdify(F(t) * G(t), F(t) * G(t) + 5))
+    raises(SyntaxError, lambda: lambdify(2 * F(t), 2 * F(t) + 5))
+    raises(SyntaxError, lambda: lambdify(2 * F(t), 4 * F(t) + 5))
+
+
+def test_lambdify__arguments_with_invalid_python_identifiers():
+    # see sympy/sympy#26690
+    N = CoordSys3D('N')
+    xn, yn, zn = N.base_scalars()
+    expr = xn + yn
+    f = lambdify([xn, yn], expr)
+    res = f(0.2, 0.3)
+    ref = 0.2 + 0.3
+    assert abs(res-ref) < 1e-15
+
+
+def test_curly_matrix_symbol():
+    # Issue #15009
+    curlyv = sympy.MatrixSymbol("{v}", 2, 1)
+    lam = lambdify(curlyv, curlyv)
+    assert lam(1)==1
+    lam = lambdify(curlyv, curlyv, dummify=True)
+    assert lam(1)==1
+
+
+def test_python_keywords():
+    # Test for issue 7452. The automatic dummification should ensure use of
+    # Python reserved keywords as symbol names will create valid lambda
+    # functions. This is an additional regression test.
+    python_if = symbols('if')
+    expr = python_if / 2
+    f = lambdify(python_if, expr)
+    assert f(4.0) == 2.0
+
+
+def test_lambdify_docstring():
+    func = lambdify((w, x, y, z), w + x + y + z)
+    ref = (
+        "Created with lambdify. Signature:\n\n"
+        "func(w, x, y, z)\n\n"
+        "Expression:\n\n"
+        "w + x + y + z"
+    ).splitlines()
+    assert func.__doc__.splitlines()[:len(ref)] == ref
+    syms = symbols('a1:26')
+    func = lambdify(syms, sum(syms))
+    ref = (
+        "Created with lambdify. Signature:\n\n"
+        "func(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15,\n"
+        "        a16, a17, a18, a19, a20, a21, a22, a23, a24, a25)\n\n"
+        "Expression:\n\n"
+        "a1 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a2 + a20 +..."
+    ).splitlines()
+    assert func.__doc__.splitlines()[:len(ref)] == ref
+
+
+def test_lambdify_linecache():
+    func = lambdify(x, x + 1)
+    source = 'def _lambdifygenerated(x):\n    return x + 1\n'
+    assert inspect.getsource(func) == source
+    filename = inspect.getsourcefile(func)
+    assert filename.startswith('= (1, 10)
+
+    if have_scipy_1_10plus:
+        cm2 = lambdify((x, y), powm1(x, y), modules='scipy')
+        assert abs(cm2(1.2, 1e-9) - 1.82321557e-10)  < 1e-17
+
+
+def test_scipy_bernoulli():
+    if not scipy:
+        skip("scipy not installed")
+
+    bern = lambdify((x,), bernoulli(x), modules='scipy')
+    assert bern(1) == 0.5
+
+
+def test_scipy_harmonic():
+    if not scipy:
+        skip("scipy not installed")
+
+    hn = lambdify((x,), harmonic(x), modules='scipy')
+    assert hn(2) == 1.5
+    hnm = lambdify((x, y), harmonic(x, y), modules='scipy')
+    assert hnm(2, 2) == 1.25
+
+
+def test_cupy_array_arg():
+    if not cupy:
+        skip("CuPy not installed")
+
+    f = lambdify([[x, y]], x*x + y, 'cupy')
+    result = f(cupy.array([2.0, 1.0]))
+    assert result == 5
+    assert "cupy" in str(type(result))
+
+
+def test_cupy_array_arg_using_numpy():
+    # numpy functions can be run on cupy arrays
+    # unclear if we can "officially" support this,
+    # depends on numpy __array_function__ support
+    if not cupy:
+        skip("CuPy not installed")
+
+    f = lambdify([[x, y]], x*x + y, 'numpy')
+    result = f(cupy.array([2.0, 1.0]))
+    assert result == 5
+    assert "cupy" in str(type(result))
+
+def test_cupy_dotproduct():
+    if not cupy:
+        skip("CuPy not installed")
+
+    A = Matrix([x, y, z])
+    f1 = lambdify([x, y, z], DotProduct(A, A), modules='cupy')
+    f2 = lambdify([x, y, z], DotProduct(A, A.T), modules='cupy')
+    f3 = lambdify([x, y, z], DotProduct(A.T, A), modules='cupy')
+    f4 = lambdify([x, y, z], DotProduct(A, A.T), modules='cupy')
+
+    assert f1(1, 2, 3) == \
+        f2(1, 2, 3) == \
+        f3(1, 2, 3) == \
+        f4(1, 2, 3) == \
+        cupy.array([14])
+
+
+def test_jax_array_arg():
+    if not jax:
+        skip("JAX not installed")
+
+    f = lambdify([[x, y]], x*x + y, 'jax')
+    result = f(jax.numpy.array([2.0, 1.0]))
+    assert result == 5
+    assert "jax" in str(type(result))
+
+
+def test_jax_array_arg_using_numpy():
+    if not jax:
+        skip("JAX not installed")
+
+    f = lambdify([[x, y]], x*x + y, 'numpy')
+    result = f(jax.numpy.array([2.0, 1.0]))
+    assert result == 5
+    assert "jax" in str(type(result))
+
+
+def test_jax_dotproduct():
+    if not jax:
+        skip("JAX not installed")
+
+    A = Matrix([x, y, z])
+    f1 = lambdify([x, y, z], DotProduct(A, A), modules='jax')
+    f2 = lambdify([x, y, z], DotProduct(A, A.T), modules='jax')
+    f3 = lambdify([x, y, z], DotProduct(A.T, A), modules='jax')
+    f4 = lambdify([x, y, z], DotProduct(A, A.T), modules='jax')
+
+    assert f1(1, 2, 3) == \
+        f2(1, 2, 3) == \
+        f3(1, 2, 3) == \
+        f4(1, 2, 3) == \
+        jax.numpy.array([14])
+
+
+def test_lambdify_cse():
+    def no_op_cse(exprs):
+        return (), exprs
+
+    def dummy_cse(exprs):
+        from sympy.simplify.cse_main import cse
+        return cse(exprs, symbols=numbered_symbols(cls=Dummy))
+
+    def minmem(exprs):
+        from sympy.simplify.cse_main import cse_release_variables, cse
+        return cse(exprs, postprocess=cse_release_variables)
+
+    class Case:
+        def __init__(self, *, args, exprs, num_args, requires_numpy=False):
+            self.args = args
+            self.exprs = exprs
+            self.num_args = num_args
+            subs_dict = dict(zip(self.args, self.num_args))
+            self.ref = [e.subs(subs_dict).evalf() for e in exprs]
+            self.requires_numpy = requires_numpy
+
+        def lambdify(self, *, cse):
+            return lambdify(self.args, self.exprs, cse=cse)
+
+        def assertAllClose(self, result, *, abstol=1e-15, reltol=1e-15):
+            if self.requires_numpy:
+                assert all(numpy.allclose(result[i], numpy.asarray(r, dtype=float),
+                                          rtol=reltol, atol=abstol)
+                           for i, r in enumerate(self.ref))
+                return
+
+            for i, r in enumerate(self.ref):
+                abs_err = abs(result[i] - r)
+                if r == 0:
+                    assert abs_err < abstol
+                else:
+                    assert abs_err/abs(r) < reltol
+
+    cases = [
+        Case(
+            args=(x, y, z),
+            exprs=[
+             x + y + z,
+             x + y - z,
+             2*x + 2*y - z,
+             (x+y)**2 + (y+z)**2,
+            ],
+            num_args=(2., 3., 4.)
+        ),
+        Case(
+            args=(x, y, z),
+            exprs=[
+            x + sympy.Heaviside(x),
+            y + sympy.Heaviside(x),
+            z + sympy.Heaviside(x, 1),
+            z/sympy.Heaviside(x, 1)
+            ],
+            num_args=(0., 3., 4.)
+        ),
+        Case(
+            args=(x, y, z),
+            exprs=[
+            x + sinc(y),
+            y + sinc(y),
+            z - sinc(y)
+            ],
+            num_args=(0.1, 0.2, 0.3)
+        ),
+        Case(
+            args=(x, y, z),
+            exprs=[
+                Matrix([[x, x*y], [sin(z) + 4, x**z]]),
+                x*y+sin(z)-x**z,
+                Matrix([x*x, sin(z), x**z])
+            ],
+            num_args=(1.,2.,3.),
+            requires_numpy=True
+        ),
+        Case(
+            args=(x, y),
+            exprs=[(x + y - 1)**2, x, x + y,
+            (x + y)/(2*x + 1) + (x + y - 1)**2, (2*x + 1)**(x + y)],
+            num_args=(1,2)
+        )
+    ]
+    for case in cases:
+        if not numpy and case.requires_numpy:
+            continue
+        for _cse in [False, True, minmem, no_op_cse, dummy_cse]:
+            f = case.lambdify(cse=_cse)
+            result = f(*case.num_args)
+            case.assertAllClose(result)
+
+def test_issue_25288():
+    syms = numbered_symbols(cls=Dummy)
+    ok = lambdify(x, [x**2, sin(x**2)], cse=lambda e: cse(e, symbols=syms))(2)
+    assert ok
+
+
+def test_deprecated_set():
+    with warns_deprecated_sympy():
+        lambdify({x, y}, x + y)
+
+def test_issue_13881():
+    if not numpy:
+        skip("numpy not installed.")
+
+    X = MatrixSymbol('X', 3, 1)
+
+    f = lambdify(X, X.T*X, 'numpy')
+    assert f(numpy.array([1, 2, 3])) == 14
+    assert f(numpy.array([3, 2, 1])) == 14
+
+    f = lambdify(X, X*X.T, 'numpy')
+    assert f(numpy.array([1, 2, 3])) == 14
+    assert f(numpy.array([3, 2, 1])) == 14
+
+    f = lambdify(X, (X*X.T)*X, 'numpy')
+    arr1 = numpy.array([[1], [2], [3]])
+    arr2 = numpy.array([[14],[28],[42]])
+
+    assert numpy.array_equal(f(arr1), arr2)
+
+
+def test_23536_lambdify_cse_dummy():
+
+    f = Function('x')(y)
+    g = Function('w')(y)
+    expr = z + (f**4 + g**5)*(f**3 + (g*f)**3)
+    expr = expr.expand()
+    eval_expr = lambdify(((f, g), z), expr, cse=True)
+    ans = eval_expr((1.0, 2.0), 3.0)  # shouldn't raise NameError
+    assert ans == 300.0  # not a list and value is 300
+
+
+class LambdifyDocstringTestCase:
+    SIGNATURE = None
+    EXPR = None
+    SRC = None
+
+    def __init__(self, docstring_limit, expected_redacted):
+        self.docstring_limit = docstring_limit
+        self.expected_redacted = expected_redacted
+
+    @property
+    def expected_expr(self):
+        expr_redacted_msg = "EXPRESSION REDACTED DUE TO LENGTH, (see lambdify's `docstring_limit`)"
+        return self.EXPR if not self.expected_redacted else expr_redacted_msg
+
+    @property
+    def expected_src(self):
+        src_redacted_msg = "SOURCE CODE REDACTED DUE TO LENGTH, (see lambdify's `docstring_limit`)"
+        return self.SRC if not self.expected_redacted else src_redacted_msg
+
+    @property
+    def expected_docstring(self):
+        expected_docstring = (
+            f'Created with lambdify. Signature:\n\n'
+            f'func({self.SIGNATURE})\n\n'
+            f'Expression:\n\n'
+            f'{self.expected_expr}\n\n'
+            f'Source code:\n\n'
+            f'{self.expected_src}\n\n'
+            f'Imported modules:\n\n'
+        )
+        return expected_docstring
+
+    def __len__(self):
+        return len(self.expected_docstring)
+
+    def __repr__(self):
+        return (
+            f'{self.__class__.__name__}('
+            f'docstring_limit={self.docstring_limit}, '
+            f'expected_redacted={self.expected_redacted})'
+        )
+
+
+def test_lambdify_docstring_size_limit_simple_symbol():
+
+    class SimpleSymbolTestCase(LambdifyDocstringTestCase):
+        SIGNATURE = 'x'
+        EXPR = 'x'
+        SRC = (
+            'def _lambdifygenerated(x):\n'
+            '    return x\n'
+        )
+
+    x = symbols('x')
+
+    test_cases = (
+        SimpleSymbolTestCase(docstring_limit=None, expected_redacted=False),
+        SimpleSymbolTestCase(docstring_limit=100, expected_redacted=False),
+        SimpleSymbolTestCase(docstring_limit=1, expected_redacted=False),
+        SimpleSymbolTestCase(docstring_limit=0, expected_redacted=True),
+        SimpleSymbolTestCase(docstring_limit=-1, expected_redacted=True),
+    )
+    for test_case in test_cases:
+        lambdified_expr = lambdify(
+            [x],
+            x,
+            'sympy',
+            docstring_limit=test_case.docstring_limit,
+        )
+        assert lambdified_expr.__doc__ == test_case.expected_docstring
+
+
+def test_lambdify_docstring_size_limit_nested_expr():
+
+    class ExprListTestCase(LambdifyDocstringTestCase):
+        SIGNATURE = 'x, y, z'
+        EXPR = (
+            '[x, [y], z, x**3 + 3*x**2*y + 3*x**2*z + 3*x*y**2 + 6*x*y*z '
+            '+ 3*x*z**2 +...'
+        )
+        SRC = (
+            'def _lambdifygenerated(x, y, z):\n'
+            '    return [x, [y], z, x**3 + 3*x**2*y + 3*x**2*z + 3*x*y**2 '
+            '+ 6*x*y*z + 3*x*z**2 + y**3 + 3*y**2*z + 3*y*z**2 + z**3]\n'
+        )
+
+    x, y, z = symbols('x, y, z')
+    expr = [x, [y], z, ((x + y + z)**3).expand()]
+
+    test_cases = (
+        ExprListTestCase(docstring_limit=None, expected_redacted=False),
+        ExprListTestCase(docstring_limit=200, expected_redacted=False),
+        ExprListTestCase(docstring_limit=50, expected_redacted=True),
+        ExprListTestCase(docstring_limit=0, expected_redacted=True),
+        ExprListTestCase(docstring_limit=-1, expected_redacted=True),
+    )
+    for test_case in test_cases:
+        lambdified_expr = lambdify(
+            [x, y, z],
+            expr,
+            'sympy',
+            docstring_limit=test_case.docstring_limit,
+        )
+        assert lambdified_expr.__doc__ == test_case.expected_docstring
+
+
+def test_lambdify_docstring_size_limit_matrix():
+
+    class MatrixTestCase(LambdifyDocstringTestCase):
+        SIGNATURE = 'x, y, z'
+        EXPR = (
+            'Matrix([[0, x], [x + y + z, x**3 + 3*x**2*y + 3*x**2*z + 3*x*y**2 '
+            '+ 6*x*y*z...'
+        )
+        SRC = (
+            'def _lambdifygenerated(x, y, z):\n'
+            '    return ImmutableDenseMatrix([[0, x], [x + y + z, x**3 '
+            '+ 3*x**2*y + 3*x**2*z + 3*x*y**2 + 6*x*y*z + 3*x*z**2 + y**3 '
+            '+ 3*y**2*z + 3*y*z**2 + z**3]])\n'
+        )
+
+    x, y, z = symbols('x, y, z')
+    expr = Matrix([[S.Zero, x], [x + y + z, ((x + y + z)**3).expand()]])
+
+    test_cases = (
+        MatrixTestCase(docstring_limit=None, expected_redacted=False),
+        MatrixTestCase(docstring_limit=200, expected_redacted=False),
+        MatrixTestCase(docstring_limit=50, expected_redacted=True),
+        MatrixTestCase(docstring_limit=0, expected_redacted=True),
+        MatrixTestCase(docstring_limit=-1, expected_redacted=True),
+    )
+    for test_case in test_cases:
+        lambdified_expr = lambdify(
+            [x, y, z],
+            expr,
+            'sympy',
+            docstring_limit=test_case.docstring_limit,
+        )
+        assert lambdified_expr.__doc__ == test_case.expected_docstring
+
+
+def test_lambdify_empty_tuple():
+    a = symbols("a")
+    expr = ((), (a,))
+    f = lambdify(a, expr)
+    result = f(1)
+    assert result == ((), (1,)), "Lambdify did not handle the empty tuple correctly."
+
+
+def test_assoc_legendre_numerical_evaluation():
+
+    tol = 1e-10
+
+    sympy_result_integer = assoc_legendre(1, 1/2, 0.1).evalf()
+    sympy_result_complex = assoc_legendre(2, 1, 3).evalf()
+    mpmath_result_integer = -0.474572528387641
+    mpmath_result_complex = -25.45584412271571*I
+
+    assert all_close(sympy_result_integer, mpmath_result_integer, tol)
+    assert all_close(sympy_result_complex, mpmath_result_complex, tol)
+
+
+def test_Piecewise():
+
+    modules = [math]
+    if numpy:
+        modules.append('numpy')
+
+    for mod in modules:
+        # test isinf
+        f = lambdify(x, Piecewise((7.0, isinf(x)), (3.0, True)), mod)
+        assert f(+float('inf')) == +7.0
+        assert f(-float('inf')) == +7.0
+        assert f(42.) == 3.0
+
+        f2 = lambdify(x, Piecewise((7.0*sign(x), isinf(x)), (3.0, True)), mod)
+        assert f2(+float('inf')) == +7.0
+        assert f2(-float('inf')) == -7.0
+        assert f2(42.) == 3.0
+
+        # test isnan (gh-26784)
+        g = lambdify(x, Piecewise((7.0, isnan(x)), (3.0, True)), mod)
+        assert g(float('nan')) == 7.0
+        assert g(42.) == 3.0
+
+
+def test_array_symbol():
+    if not numpy:
+        skip("numpy not installed.")
+    a = ArraySymbol('a', (3,))
+    f = lambdify((a), a)
+    assert numpy.all(f(numpy.array([1,2,3])) == numpy.array([1,2,3]))
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_matchpy_connector.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_matchpy_connector.py
new file mode 100644
index 0000000000000000000000000000000000000000..3648bd49f9e56ca20fbf428ed46c01429dbe8b15
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_matchpy_connector.py
@@ -0,0 +1,164 @@
+import pickle
+
+from sympy.core.relational import (Eq, Ne)
+from sympy.core.singleton import S
+from sympy.core.symbol import symbols
+from sympy.functions.elementary.miscellaneous import sqrt
+from sympy.functions.elementary.trigonometric import (cos, sin)
+from sympy.external import import_module
+from sympy.testing.pytest import skip
+from sympy.utilities.matchpy_connector import WildDot, WildPlus, WildStar, Replacer
+
+matchpy = import_module("matchpy")
+
+x, y, z = symbols("x y z")
+
+
+def _get_first_match(expr, pattern):
+    from matchpy import ManyToOneMatcher, Pattern
+
+    matcher = ManyToOneMatcher()
+    matcher.add(Pattern(pattern))
+    return next(iter(matcher.match(expr)))
+
+
+def test_matchpy_connector():
+    if matchpy is None:
+        skip("matchpy not installed")
+
+    from multiset import Multiset
+    from matchpy import Pattern, Substitution
+
+    w_ = WildDot("w_")
+    w__ = WildPlus("w__")
+    w___ = WildStar("w___")
+
+    expr = x + y
+    pattern = x + w_
+    p, subst = _get_first_match(expr, pattern)
+    assert p == Pattern(pattern)
+    assert subst == Substitution({'w_': y})
+
+    expr = x + y + z
+    pattern = x + w__
+    p, subst = _get_first_match(expr, pattern)
+    assert p == Pattern(pattern)
+    assert subst == Substitution({'w__': Multiset([y, z])})
+
+    expr = x + y + z
+    pattern = x + y + z + w___
+    p, subst = _get_first_match(expr, pattern)
+    assert p == Pattern(pattern)
+    assert subst == Substitution({'w___': Multiset()})
+
+
+def test_matchpy_optional():
+    if matchpy is None:
+        skip("matchpy not installed")
+
+    from matchpy import Pattern, Substitution
+    from matchpy import ManyToOneReplacer, ReplacementRule
+
+    p = WildDot("p", optional=1)
+    q = WildDot("q", optional=0)
+
+    pattern = p*x + q
+
+    expr1 = 2*x
+    pa, subst = _get_first_match(expr1, pattern)
+    assert pa == Pattern(pattern)
+    assert subst == Substitution({'p': 2, 'q': 0})
+
+    expr2 = x + 3
+    pa, subst = _get_first_match(expr2, pattern)
+    assert pa == Pattern(pattern)
+    assert subst == Substitution({'p': 1, 'q': 3})
+
+    expr3 = x
+    pa, subst = _get_first_match(expr3, pattern)
+    assert pa == Pattern(pattern)
+    assert subst == Substitution({'p': 1, 'q': 0})
+
+    expr4 = x*y + z
+    pa, subst = _get_first_match(expr4, pattern)
+    assert pa == Pattern(pattern)
+    assert subst == Substitution({'p': y, 'q': z})
+
+    replacer = ManyToOneReplacer()
+    replacer.add(ReplacementRule(Pattern(pattern), lambda p, q: sin(p)*cos(q)))
+    assert replacer.replace(expr1) == sin(2)*cos(0)
+    assert replacer.replace(expr2) == sin(1)*cos(3)
+    assert replacer.replace(expr3) == sin(1)*cos(0)
+    assert replacer.replace(expr4) == sin(y)*cos(z)
+
+
+def test_replacer():
+    if matchpy is None:
+        skip("matchpy not installed")
+
+    for info in [True, False]:
+        for lambdify in [True, False]:
+            _perform_test_replacer(info, lambdify)
+
+
+def _perform_test_replacer(info, lambdify):
+
+    x1_ = WildDot("x1_")
+    x2_ = WildDot("x2_")
+
+    a_ = WildDot("a_", optional=S.One)
+    b_ = WildDot("b_", optional=S.One)
+    c_ = WildDot("c_", optional=S.Zero)
+
+    replacer = Replacer(common_constraints=[
+        matchpy.CustomConstraint(lambda a_: not a_.has(x)),
+        matchpy.CustomConstraint(lambda b_: not b_.has(x)),
+        matchpy.CustomConstraint(lambda c_: not c_.has(x)),
+    ], lambdify=lambdify, info=info)
+
+    # Rewrite the equation into implicit form, unless it's already solved:
+    replacer.add(Eq(x1_, x2_), Eq(x1_ - x2_, 0), conditions_nonfalse=[Ne(x2_, 0), Ne(x1_, 0), Ne(x1_, x), Ne(x2_, x)], info=1)
+
+    # Simple equation solver for real numbers:
+    replacer.add(Eq(a_*x + b_, 0), Eq(x, -b_/a_), info=2)
+    disc = b_**2 - 4*a_*c_
+    replacer.add(
+        Eq(a_*x**2 + b_*x + c_, 0),
+        Eq(x, (-b_ - sqrt(disc))/(2*a_)) | Eq(x, (-b_ + sqrt(disc))/(2*a_)),
+        conditions_nonfalse=[disc >= 0],
+        info=3
+    )
+    replacer.add(
+        Eq(a_*x**2 + c_, 0),
+        Eq(x, sqrt(-c_/a_)) | Eq(x, -sqrt(-c_/a_)),
+        conditions_nonfalse=[-c_*a_ > 0],
+        info=4
+    )
+
+    g = lambda expr, infos: (expr, infos) if info else expr
+
+    assert replacer.replace(Eq(3*x, y)) == g(Eq(x, y/3), [1, 2])
+    assert replacer.replace(Eq(x**2 + 1, 0)) == g(Eq(x**2 + 1, 0), [])
+    assert replacer.replace(Eq(x**2, 4)) == g((Eq(x, 2) | Eq(x, -2)), [1, 4])
+    assert replacer.replace(Eq(x**2 + 4*y*x + 4*y**2, 0)) == g(Eq(x, -2*y), [3])
+
+
+def test_matchpy_object_pickle():
+    if matchpy is None:
+        return
+
+    a1 = WildDot("a")
+    a2 = pickle.loads(pickle.dumps(a1))
+    assert a1 == a2
+
+    a1 = WildDot("a", S(1))
+    a2 = pickle.loads(pickle.dumps(a1))
+    assert a1 == a2
+
+    a1 = WildPlus("a", S(1))
+    a2 = pickle.loads(pickle.dumps(a1))
+    assert a1 == a2
+
+    a1 = WildStar("a", S(1))
+    a2 = pickle.loads(pickle.dumps(a1))
+    assert a1 == a2
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_mathml.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_mathml.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4a7598f175be34f8bb34c0bd9c003d1c0238c7b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_mathml.py
@@ -0,0 +1,33 @@
+import os
+from textwrap import dedent
+from sympy.external import import_module
+from sympy.testing.pytest import skip
+from sympy.utilities.mathml import apply_xsl
+
+
+
+lxml = import_module('lxml')
+
+path = os.path.abspath(os.path.join(os.path.dirname(__file__), "test_xxe.py"))
+
+
+def test_xxe():
+    assert os.path.isfile(path)
+    if not lxml:
+        skip("lxml not installed.")
+
+    mml = dedent(
+        rf"""
+        
+         ]>
+        
+        John
+        &ent;
+        
+        """
+    )
+    xsl = 'mathml/data/simple_mmlctop.xsl'
+
+    res = apply_xsl(mml, xsl)
+    assert res == \
+        '\n\nJohn\n\n\n'
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_misc.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a3e059419303c33cbd7b770679b5efc1b03486d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_misc.py
@@ -0,0 +1,148 @@
+from textwrap import dedent
+import sys
+from subprocess import Popen, PIPE
+import os
+
+from sympy.core.singleton import S
+from sympy.testing.pytest import (raises, warns_deprecated_sympy,
+                                  skip_under_pyodide)
+from sympy.utilities.misc import (translate, replace, ordinal, rawlines,
+                                  strlines, as_int, find_executable)
+
+
+def test_translate():
+    abc = 'abc'
+    assert translate(abc, None, 'a') == 'bc'
+    assert translate(abc, None, '') == 'abc'
+    assert translate(abc, {'a': 'x'}, 'c') == 'xb'
+    assert translate(abc, {'a': 'bc'}, 'c') == 'bcb'
+    assert translate(abc, {'ab': 'x'}, 'c') == 'x'
+    assert translate(abc, {'ab': ''}, 'c') == ''
+    assert translate(abc, {'bc': 'x'}, 'c') == 'ab'
+    assert translate(abc, {'abc': 'x', 'a': 'y'}) == 'x'
+    u = chr(4096)
+    assert translate(abc, 'a', 'x', u) == 'xbc'
+    assert (u in translate(abc, 'a', u, u)) is True
+
+
+def test_replace():
+    assert replace('abc', ('a', 'b')) == 'bbc'
+    assert replace('abc', {'a': 'Aa'}) == 'Aabc'
+    assert replace('abc', ('a', 'b'), ('c', 'C')) == 'bbC'
+
+
+def test_ordinal():
+    assert ordinal(-1) == '-1st'
+    assert ordinal(0) == '0th'
+    assert ordinal(1) == '1st'
+    assert ordinal(2) == '2nd'
+    assert ordinal(3) == '3rd'
+    assert all(ordinal(i).endswith('th') for i in range(4, 21))
+    assert ordinal(100) == '100th'
+    assert ordinal(101) == '101st'
+    assert ordinal(102) == '102nd'
+    assert ordinal(103) == '103rd'
+    assert ordinal(104) == '104th'
+    assert ordinal(200) == '200th'
+    assert all(ordinal(i) == str(i) + 'th' for i in range(-220, -203))
+
+
+def test_rawlines():
+    assert rawlines('a a\na') == "dedent('''\\\n    a a\n    a''')"
+    assert rawlines('a a') == "'a a'"
+    assert rawlines(strlines('\\le"ft')) == (
+        '(\n'
+        "    '(\\n'\n"
+        '    \'r\\\'\\\\le"ft\\\'\\n\'\n'
+        "    ')'\n"
+        ')')
+
+
+def test_strlines():
+    q = 'this quote (") is in the middle'
+    # the following assert rhs was prepared with
+    # print(rawlines(strlines(q, 10)))
+    assert strlines(q, 10) == dedent('''\
+        (
+        'this quo'
+        'te (") i'
+        's in the'
+        ' middle'
+        )''')
+    assert q == (
+        'this quo'
+        'te (") i'
+        's in the'
+        ' middle'
+        )
+    q = "this quote (') is in the middle"
+    assert strlines(q, 20) == dedent('''\
+        (
+        "this quote (') is "
+        "in the middle"
+        )''')
+    assert strlines('\\left') == (
+        '(\n'
+        "r'\\left'\n"
+        ')')
+    assert strlines('\\left', short=True) == r"r'\left'"
+    assert strlines('\\le"ft') == (
+        '(\n'
+        'r\'\\le"ft\'\n'
+        ')')
+    q = 'this\nother line'
+    assert strlines(q) == rawlines(q)
+
+
+def test_translate_args():
+    try:
+        translate(None, None, None, 'not_none')
+    except ValueError:
+        pass # Exception raised successfully
+    else:
+        assert False
+
+    assert translate('s', None, None, None) == 's'
+
+    try:
+        translate('s', 'a', 'bc')
+    except ValueError:
+        pass # Exception raised successfully
+    else:
+        assert False
+
+
+@skip_under_pyodide("Cannot create subprocess under pyodide.")
+def test_debug_output():
+    env = os.environ.copy()
+    env['SYMPY_DEBUG'] = 'True'
+    cmd = 'from sympy import *; x = Symbol("x"); print(integrate((1-cos(x))/x, x))'
+    cmdline = [sys.executable, '-c', cmd]
+    proc = Popen(cmdline, env=env, stdout=PIPE, stderr=PIPE)
+    out, err = proc.communicate()
+    out = out.decode('ascii') # utf-8?
+    err = err.decode('ascii')
+    expected = 'substituted: -x*(1 - cos(x)), u: 1/x, u_var: _u'
+    assert expected in err, err
+
+
+def test_as_int():
+    raises(ValueError, lambda : as_int(True))
+    raises(ValueError, lambda : as_int(1.1))
+    raises(ValueError, lambda : as_int([]))
+    raises(ValueError, lambda : as_int(S.NaN))
+    raises(ValueError, lambda : as_int(S.Infinity))
+    raises(ValueError, lambda : as_int(S.NegativeInfinity))
+    raises(ValueError, lambda : as_int(S.ComplexInfinity))
+    # for the following, limited precision makes int(arg) == arg
+    # but the int value is not necessarily what a user might have
+    # expected; Q.prime is more nuanced in its response for
+    # expressions which might be complex representations of an
+    # integer. This is not -- by design -- as_ints role.
+    raises(ValueError, lambda : as_int(1e23))
+    raises(ValueError, lambda : as_int(S('1.'+'0'*20+'1')))
+    assert as_int(True, strict=False) == 1
+
+def test_deprecated_find_executable():
+    with warns_deprecated_sympy():
+        find_executable('python')
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_pickling.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_pickling.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ea2d062286cbcf802eb0f42f2d7d130123599af
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_pickling.py
@@ -0,0 +1,723 @@
+import inspect
+import copy
+import pickle
+
+from sympy.physics.units import meter
+
+from sympy.testing.pytest import XFAIL, raises, ignore_warnings
+
+from sympy.core.basic import Atom, Basic
+from sympy.core.singleton import SingletonRegistry
+from sympy.core.symbol import Str, Dummy, Symbol, Wild
+from sympy.core.numbers import (E, I, pi, oo, zoo, nan, Integer,
+        Rational, Float, AlgebraicNumber)
+from sympy.core.relational import (Equality, GreaterThan, LessThan, Relational,
+        StrictGreaterThan, StrictLessThan, Unequality)
+from sympy.core.add import Add
+from sympy.core.mul import Mul
+from sympy.core.power import Pow
+from sympy.core.function import Derivative, Function, FunctionClass, Lambda, \
+    WildFunction
+from sympy.sets.sets import Interval
+from sympy.core.multidimensional import vectorize
+
+from sympy.external.gmpy import gmpy as _gmpy
+from sympy.utilities.exceptions import SymPyDeprecationWarning
+
+from sympy.core.singleton import S
+from sympy.core.symbol import symbols
+
+from sympy.external import import_module
+cloudpickle = import_module('cloudpickle')
+
+
+not_equal_attrs = {
+    '_assumptions',  # This is a local cache that isn't automatically filled on creation
+    '_mhash',   # Cached after __hash__ is called but set to None after creation
+}
+
+
+deprecated_attrs = {
+    'is_EmptySet',  # Deprecated from SymPy 1.5. This can be removed when is_EmptySet is removed.
+    'expr_free_symbols',  # Deprecated from SymPy 1.9. This can be removed when exr_free_symbols is removed.
+}
+
+dont_check_attrs = {
+    '_sage_',  # Fails because Sage is not installed
+}
+
+
+def check(a, exclude=[], check_attr=True, deprecated=()):
+    """ Check that pickling and copying round-trips.
+    """
+    # Pickling with protocols 0 and 1 is disabled for Basic instances:
+    if isinstance(a, Basic):
+        for protocol in [0, 1]:
+            raises(NotImplementedError, lambda: pickle.dumps(a, protocol))
+
+    protocols = [2, copy.copy, copy.deepcopy, 3, 4]
+    if cloudpickle:
+        protocols.extend([cloudpickle])
+
+    for protocol in protocols:
+        if protocol in exclude:
+            continue
+
+        if callable(protocol):
+            if isinstance(a, type):
+                # Classes can't be copied, but that's okay.
+                continue
+            b = protocol(a)
+        elif inspect.ismodule(protocol):
+            b = protocol.loads(protocol.dumps(a))
+        else:
+            b = pickle.loads(pickle.dumps(a, protocol))
+
+        d1 = dir(a)
+        d2 = dir(b)
+        assert set(d1) == set(d2)
+
+        if not check_attr:
+            continue
+
+        def c(a, b, d):
+            for i in d:
+                if i in dont_check_attrs:
+                    continue
+                elif i in not_equal_attrs:
+                    if hasattr(a, i):
+                        assert hasattr(b, i), i
+                elif i in deprecated_attrs or i in deprecated:
+                    with ignore_warnings(SymPyDeprecationWarning):
+                        assert getattr(a, i) == getattr(b, i), i
+                elif not hasattr(a, i):
+                    continue
+                else:
+                    attr = getattr(a, i)
+                    if not hasattr(attr, "__call__"):
+                        assert hasattr(b, i), i
+                        assert getattr(b, i) == attr, "%s != %s, protocol: %s" % (getattr(b, i), attr, protocol)
+
+        c(a, b, d1)
+        c(b, a, d2)
+
+
+
+#================== core =========================
+
+
+def test_core_basic():
+    for c in (Atom, Atom(), Basic, Basic(), SingletonRegistry, S):
+        check(c)
+
+def test_core_Str():
+    check(Str('x'))
+
+def test_core_symbol():
+    # make the Symbol a unique name that doesn't class with any other
+    # testing variable in this file since after this test the symbol
+    # having the same name will be cached as noncommutative
+    for c in (Dummy, Dummy("x", commutative=False), Symbol,
+            Symbol("_issue_3130", commutative=False), Wild, Wild("x")):
+        check(c)
+
+
+def test_core_numbers():
+    for c in (Integer(2), Rational(2, 3), Float("1.2")):
+        check(c)
+    for c in (AlgebraicNumber, AlgebraicNumber(sqrt(3))):
+        check(c, check_attr=False)
+
+
+def test_core_float_copy():
+    # See gh-7457
+    y = Symbol("x") + 1.0
+    check(y)  # does not raise TypeError ("argument is not an mpz")
+
+
+def test_core_relational():
+    x = Symbol("x")
+    y = Symbol("y")
+    for c in (Equality, Equality(x, y), GreaterThan, GreaterThan(x, y),
+              LessThan, LessThan(x, y), Relational, Relational(x, y),
+              StrictGreaterThan, StrictGreaterThan(x, y), StrictLessThan,
+              StrictLessThan(x, y), Unequality, Unequality(x, y)):
+        check(c)
+
+
+def test_core_add():
+    x = Symbol("x")
+    for c in (Add, Add(x, 4)):
+        check(c)
+
+
+def test_core_mul():
+    x = Symbol("x")
+    for c in (Mul, Mul(x, 4)):
+        check(c)
+
+
+def test_core_power():
+    x = Symbol("x")
+    for c in (Pow, Pow(x, 4)):
+        check(c)
+
+
+def test_core_function():
+    x = Symbol("x")
+    for f in (Derivative, Derivative(x), Function, FunctionClass, Lambda,
+              WildFunction):
+        check(f)
+
+
+def test_core_undefinedfunctions():
+    f = Function("f")
+    check(f)
+
+
+def test_core_appliedundef():
+    x = Symbol("_long_unique_name_1")
+    f = Function("_long_unique_name_2")
+    check(f(x))
+
+
+def test_core_interval():
+    for c in (Interval, Interval(0, 2)):
+        check(c)
+
+
+def test_core_multidimensional():
+    for c in (vectorize, vectorize(0)):
+        check(c)
+
+
+def test_Singletons():
+    protocols = [0, 1, 2, 3, 4]
+    copiers = [copy.copy, copy.deepcopy]
+    copiers += [lambda x: pickle.loads(pickle.dumps(x, proto))
+            for proto in protocols]
+    if cloudpickle:
+        copiers += [lambda x: cloudpickle.loads(cloudpickle.dumps(x))]
+
+    for obj in (Integer(-1), Integer(0), Integer(1), Rational(1, 2), pi, E, I,
+            oo, -oo, zoo, nan, S.GoldenRatio, S.TribonacciConstant,
+            S.EulerGamma, S.Catalan, S.EmptySet, S.IdentityFunction):
+        for func in copiers:
+            assert func(obj) is obj
+
+#================== combinatorics ===================
+from sympy.combinatorics.free_groups import FreeGroup
+
+def test_free_group():
+    check(FreeGroup("x, y, z"), check_attr=False)
+
+#================== functions ===================
+from sympy.functions import (Piecewise, lowergamma, acosh, chebyshevu,
+        chebyshevt, ln, chebyshevt_root, legendre, Heaviside, bernoulli, coth,
+        tanh, assoc_legendre, sign, arg, asin, DiracDelta, re, rf, Abs,
+        uppergamma, binomial, sinh, cos, cot, acos, acot, gamma, bell,
+        hermite, harmonic, LambertW, zeta, log, factorial, asinh, acoth, cosh,
+        dirichlet_eta, Eijk, loggamma, erf, ceiling, im, fibonacci,
+        tribonacci, conjugate, tan, chebyshevu_root, floor, atanh, sqrt, sin,
+        atan, ff, lucas, atan2, polygamma, exp)
+
+
+def test_functions():
+    one_var = (acosh, ln, Heaviside, factorial, bernoulli, coth, tanh,
+            sign, arg, asin, DiracDelta, re, Abs, sinh, cos, cot, acos, acot,
+            gamma, bell, harmonic, LambertW, zeta, log, factorial, asinh,
+            acoth, cosh, dirichlet_eta, loggamma, erf, ceiling, im, fibonacci,
+            tribonacci, conjugate, tan, floor, atanh, sin, atan, lucas, exp)
+    two_var = (rf, ff, lowergamma, chebyshevu, chebyshevt, binomial,
+            atan2, polygamma, hermite, legendre, uppergamma)
+    x, y, z = symbols("x,y,z")
+    others = (chebyshevt_root, chebyshevu_root, Eijk(x, y, z),
+            Piecewise( (0, x < -1), (x**2, x <= 1), (x**3, True)),
+            assoc_legendre)
+    for cls in one_var:
+        check(cls)
+        c = cls(x)
+        check(c)
+    for cls in two_var:
+        check(cls)
+        c = cls(x, y)
+        check(c)
+    for cls in others:
+        check(cls)
+
+#================== geometry ====================
+from sympy.geometry.entity import GeometryEntity
+from sympy.geometry.point import Point
+from sympy.geometry.ellipse import Circle, Ellipse
+from sympy.geometry.line import Line, LinearEntity, Ray, Segment
+from sympy.geometry.polygon import Polygon, RegularPolygon, Triangle
+
+
+def test_geometry():
+    p1 = Point(1, 2)
+    p2 = Point(2, 3)
+    p3 = Point(0, 0)
+    p4 = Point(0, 1)
+    for c in (
+        GeometryEntity, GeometryEntity(), Point, p1, Circle, Circle(p1, 2),
+        Ellipse, Ellipse(p1, 3, 4), Line, Line(p1, p2), LinearEntity,
+        LinearEntity(p1, p2), Ray, Ray(p1, p2), Segment, Segment(p1, p2),
+        Polygon, Polygon(p1, p2, p3, p4), RegularPolygon,
+            RegularPolygon(p1, 4, 5), Triangle, Triangle(p1, p2, p3)):
+        check(c, check_attr=False)
+
+#================== integrals ====================
+from sympy.integrals.integrals import Integral
+
+
+def test_integrals():
+    x = Symbol("x")
+    for c in (Integral, Integral(x)):
+        check(c)
+
+#==================== logic =====================
+from sympy.core.logic import Logic
+
+
+def test_logic():
+    for c in (Logic, Logic(1)):
+        check(c)
+
+#================== matrices ====================
+from sympy.matrices import Matrix, SparseMatrix
+
+
+def test_matrices():
+    for c in (Matrix, Matrix([1, 2, 3]), SparseMatrix, SparseMatrix([[1, 2], [3, 4]])):
+        check(c, deprecated=['_smat', '_mat'])
+
+#================== ntheory =====================
+from sympy.ntheory.generate import Sieve
+
+
+def test_ntheory():
+    for c in (Sieve, Sieve()):
+        check(c)
+
+#================== physics =====================
+from sympy.physics.paulialgebra import Pauli
+from sympy.physics.units import Unit
+
+
+def test_physics():
+    for c in (Unit, meter, Pauli, Pauli(1)):
+        check(c)
+
+#================== plotting ====================
+# XXX: These tests are not complete, so XFAIL them
+
+
+@XFAIL
+def test_plotting():
+    from sympy.plotting.pygletplot.color_scheme import ColorGradient, ColorScheme
+    from sympy.plotting.pygletplot.managed_window import ManagedWindow
+    from sympy.plotting.plot import Plot, ScreenShot
+    from sympy.plotting.pygletplot.plot_axes import PlotAxes, PlotAxesBase, PlotAxesFrame, PlotAxesOrdinate
+    from sympy.plotting.pygletplot.plot_camera import PlotCamera
+    from sympy.plotting.pygletplot.plot_controller import PlotController
+    from sympy.plotting.pygletplot.plot_curve import PlotCurve
+    from sympy.plotting.pygletplot.plot_interval import PlotInterval
+    from sympy.plotting.pygletplot.plot_mode import PlotMode
+    from sympy.plotting.pygletplot.plot_modes import Cartesian2D, Cartesian3D, Cylindrical, \
+        ParametricCurve2D, ParametricCurve3D, ParametricSurface, Polar, Spherical
+    from sympy.plotting.pygletplot.plot_object import PlotObject
+    from sympy.plotting.pygletplot.plot_surface import PlotSurface
+    from sympy.plotting.pygletplot.plot_window import PlotWindow
+    for c in (
+        ColorGradient, ColorGradient(0.2, 0.4), ColorScheme, ManagedWindow,
+        ManagedWindow, Plot, ScreenShot, PlotAxes, PlotAxesBase,
+        PlotAxesFrame, PlotAxesOrdinate, PlotCamera, PlotController,
+        PlotCurve, PlotInterval, PlotMode, Cartesian2D, Cartesian3D,
+        Cylindrical, ParametricCurve2D, ParametricCurve3D,
+        ParametricSurface, Polar, Spherical, PlotObject, PlotSurface,
+            PlotWindow):
+        check(c)
+
+
+@XFAIL
+def test_plotting2():
+    #from sympy.plotting.color_scheme import ColorGradient
+    from sympy.plotting.pygletplot.color_scheme import ColorScheme
+    #from sympy.plotting.managed_window import ManagedWindow
+    from sympy.plotting.plot import Plot
+    #from sympy.plotting.plot import ScreenShot
+    from sympy.plotting.pygletplot.plot_axes import PlotAxes
+    #from sympy.plotting.plot_axes import PlotAxesBase, PlotAxesFrame, PlotAxesOrdinate
+    #from sympy.plotting.plot_camera import PlotCamera
+    #from sympy.plotting.plot_controller import PlotController
+    #from sympy.plotting.plot_curve import PlotCurve
+    #from sympy.plotting.plot_interval import PlotInterval
+    #from sympy.plotting.plot_mode import PlotMode
+    #from sympy.plotting.plot_modes import Cartesian2D, Cartesian3D, Cylindrical, \
+    #    ParametricCurve2D, ParametricCurve3D, ParametricSurface, Polar, Spherical
+    #from sympy.plotting.plot_object import PlotObject
+    #from sympy.plotting.plot_surface import PlotSurface
+    # from sympy.plotting.plot_window import PlotWindow
+    check(ColorScheme("rainbow"))
+    check(Plot(1, visible=False))
+    check(PlotAxes())
+
+#================== polys =======================
+from sympy.polys.domains.integerring import ZZ
+from sympy.polys.domains.rationalfield import QQ
+from sympy.polys.orderings import lex
+from sympy.polys.polytools import Poly
+
+def test_pickling_polys_polytools():
+    from sympy.polys.polytools import PurePoly
+    # from sympy.polys.polytools import GroebnerBasis
+    x = Symbol('x')
+
+    for c in (Poly, Poly(x, x)):
+        check(c)
+
+    for c in (PurePoly, PurePoly(x)):
+        check(c)
+
+    # TODO: fix pickling of Options class (see GroebnerBasis._options)
+    # for c in (GroebnerBasis, GroebnerBasis([x**2 - 1], x, order=lex)):
+    #     check(c)
+
+def test_pickling_polys_polyclasses():
+    from sympy.polys.polyclasses import DMP, DMF, ANP
+
+    for c in (DMP, DMP([[ZZ(1)], [ZZ(2)], [ZZ(3)]], ZZ)):
+        check(c, deprecated=['rep'])
+    for c in (DMF, DMF(([ZZ(1), ZZ(2)], [ZZ(1), ZZ(3)]), ZZ)):
+        check(c)
+    for c in (ANP, ANP([QQ(1), QQ(2)], [QQ(1), QQ(2), QQ(3)], QQ)):
+        check(c)
+
+@XFAIL
+def test_pickling_polys_rings():
+    # NOTE: can't use protocols < 2 because we have to execute __new__ to
+    # make sure caching of rings works properly.
+
+    from sympy.polys.rings import PolyRing
+
+    ring = PolyRing("x,y,z", ZZ, lex)
+
+    for c in (PolyRing, ring):
+        check(c, exclude=[0, 1])
+
+    for c in (ring.dtype, ring.one):
+        check(c, exclude=[0, 1], check_attr=False) # TODO: Py3k
+
+def test_pickling_polys_fields():
+    pass
+    # NOTE: can't use protocols < 2 because we have to execute __new__ to
+    # make sure caching of fields works properly.
+
+    # from sympy.polys.fields import FracField
+
+    # field = FracField("x,y,z", ZZ, lex)
+
+    # TODO: AssertionError: assert id(obj) not in self.memo
+    # for c in (FracField, field):
+    #     check(c, exclude=[0, 1])
+
+    # TODO: AssertionError: assert id(obj) not in self.memo
+    # for c in (field.dtype, field.one):
+    #     check(c, exclude=[0, 1])
+
+def test_pickling_polys_elements():
+    from sympy.polys.domains.pythonrational import PythonRational
+    #from sympy.polys.domains.pythonfinitefield import PythonFiniteField
+    #from sympy.polys.domains.mpelements import MPContext
+
+    for c in (PythonRational, PythonRational(1, 7)):
+        check(c)
+
+    #gf = PythonFiniteField(17)
+
+    # TODO: fix pickling of ModularInteger
+    # for c in (gf.dtype, gf(5)):
+    #     check(c)
+
+    #mp = MPContext()
+
+    # TODO: fix pickling of RealElement
+    # for c in (mp.mpf, mp.mpf(1.0)):
+    #     check(c)
+
+    # TODO: fix pickling of ComplexElement
+    # for c in (mp.mpc, mp.mpc(1.0, -1.5)):
+    #     check(c)
+
+def test_pickling_polys_domains():
+    # from sympy.polys.domains.pythonfinitefield import PythonFiniteField
+    from sympy.polys.domains.pythonintegerring import PythonIntegerRing
+    from sympy.polys.domains.pythonrationalfield import PythonRationalField
+
+    # TODO: fix pickling of ModularInteger
+    # for c in (PythonFiniteField, PythonFiniteField(17)):
+    #     check(c)
+
+    for c in (PythonIntegerRing, PythonIntegerRing()):
+        check(c, check_attr=False)
+
+    for c in (PythonRationalField, PythonRationalField()):
+        check(c, check_attr=False)
+
+    if _gmpy is not None:
+        # from sympy.polys.domains.gmpyfinitefield import GMPYFiniteField
+        from sympy.polys.domains.gmpyintegerring import GMPYIntegerRing
+        from sympy.polys.domains.gmpyrationalfield import GMPYRationalField
+
+        # TODO: fix pickling of ModularInteger
+        # for c in (GMPYFiniteField, GMPYFiniteField(17)):
+        #     check(c)
+
+        for c in (GMPYIntegerRing, GMPYIntegerRing()):
+            check(c, check_attr=False)
+
+        for c in (GMPYRationalField, GMPYRationalField()):
+            check(c, check_attr=False)
+
+    #from sympy.polys.domains.realfield import RealField
+    #from sympy.polys.domains.complexfield import ComplexField
+    from sympy.polys.domains.algebraicfield import AlgebraicField
+    #from sympy.polys.domains.polynomialring import PolynomialRing
+    #from sympy.polys.domains.fractionfield import FractionField
+    from sympy.polys.domains.expressiondomain import ExpressionDomain
+
+    # TODO: fix pickling of RealElement
+    # for c in (RealField, RealField(100)):
+    #     check(c)
+
+    # TODO: fix pickling of ComplexElement
+    # for c in (ComplexField, ComplexField(100)):
+    #     check(c)
+
+    for c in (AlgebraicField, AlgebraicField(QQ, sqrt(3))):
+        check(c, check_attr=False)
+
+    # TODO: AssertionError
+    # for c in (PolynomialRing, PolynomialRing(ZZ, "x,y,z")):
+    #     check(c)
+
+    # TODO: AttributeError: 'PolyElement' object has no attribute 'ring'
+    # for c in (FractionField, FractionField(ZZ, "x,y,z")):
+    #     check(c)
+
+    for c in (ExpressionDomain, ExpressionDomain()):
+        check(c, check_attr=False)
+
+
+def test_pickling_polys_orderings():
+    from sympy.polys.orderings import (LexOrder, GradedLexOrder,
+        ReversedGradedLexOrder, InverseOrder)
+    # from sympy.polys.orderings import ProductOrder
+
+    for c in (LexOrder, LexOrder()):
+        check(c)
+
+    for c in (GradedLexOrder, GradedLexOrder()):
+        check(c)
+
+    for c in (ReversedGradedLexOrder, ReversedGradedLexOrder()):
+        check(c)
+
+    # TODO: Argh, Python is so naive. No lambdas nor inner function support in
+    # pickling module. Maybe someone could figure out what to do with this.
+    #
+    # for c in (ProductOrder, ProductOrder((LexOrder(),       lambda m: m[:2]),
+    #                                      (GradedLexOrder(), lambda m: m[2:]))):
+    #     check(c)
+
+    for c in (InverseOrder, InverseOrder(LexOrder())):
+        check(c)
+
+def test_pickling_polys_monomials():
+    from sympy.polys.monomials import MonomialOps, Monomial
+    x, y, z = symbols("x,y,z")
+
+    for c in (MonomialOps, MonomialOps(3)):
+        check(c)
+
+    for c in (Monomial, Monomial((1, 2, 3), (x, y, z))):
+        check(c)
+
+def test_pickling_polys_errors():
+    from sympy.polys.polyerrors import (HeuristicGCDFailed,
+        HomomorphismFailed, IsomorphismFailed, ExtraneousFactors,
+        EvaluationFailed, RefinementFailed, CoercionFailed, NotInvertible,
+        NotReversible, NotAlgebraic, DomainError, PolynomialError,
+        UnificationFailed, GeneratorsError, GeneratorsNeeded,
+        UnivariatePolynomialError, MultivariatePolynomialError, OptionError,
+        FlagError)
+    # from sympy.polys.polyerrors import (ExactQuotientFailed,
+    #         OperationNotSupported, ComputationFailed, PolificationFailed)
+
+    # x = Symbol('x')
+
+    # TODO: TypeError: __init__() takes at least 3 arguments (1 given)
+    # for c in (ExactQuotientFailed, ExactQuotientFailed(x, 3*x, ZZ)):
+    #    check(c)
+
+    # TODO: TypeError: can't pickle instancemethod objects
+    # for c in (OperationNotSupported, OperationNotSupported(Poly(x), Poly.gcd)):
+    #    check(c)
+
+    for c in (HeuristicGCDFailed, HeuristicGCDFailed()):
+        check(c)
+
+    for c in (HomomorphismFailed, HomomorphismFailed()):
+        check(c)
+
+    for c in (IsomorphismFailed, IsomorphismFailed()):
+        check(c)
+
+    for c in (ExtraneousFactors, ExtraneousFactors()):
+        check(c)
+
+    for c in (EvaluationFailed, EvaluationFailed()):
+        check(c)
+
+    for c in (RefinementFailed, RefinementFailed()):
+        check(c)
+
+    for c in (CoercionFailed, CoercionFailed()):
+        check(c)
+
+    for c in (NotInvertible, NotInvertible()):
+        check(c)
+
+    for c in (NotReversible, NotReversible()):
+        check(c)
+
+    for c in (NotAlgebraic, NotAlgebraic()):
+        check(c)
+
+    for c in (DomainError, DomainError()):
+        check(c)
+
+    for c in (PolynomialError, PolynomialError()):
+        check(c)
+
+    for c in (UnificationFailed, UnificationFailed()):
+        check(c)
+
+    for c in (GeneratorsError, GeneratorsError()):
+        check(c)
+
+    for c in (GeneratorsNeeded, GeneratorsNeeded()):
+        check(c)
+
+    # TODO: PicklingError: Can't pickle  at 0x38578c0>: it's not found as __main__.
+    # for c in (ComputationFailed, ComputationFailed(lambda t: t, 3, None)):
+    #    check(c)
+
+    for c in (UnivariatePolynomialError, UnivariatePolynomialError()):
+        check(c)
+
+    for c in (MultivariatePolynomialError, MultivariatePolynomialError()):
+        check(c)
+
+    # TODO: TypeError: __init__() takes at least 3 arguments (1 given)
+    # for c in (PolificationFailed, PolificationFailed({}, x, x, False)):
+    #    check(c)
+
+    for c in (OptionError, OptionError()):
+        check(c)
+
+    for c in (FlagError, FlagError()):
+        check(c)
+
+#def test_pickling_polys_options():
+    #from sympy.polys.polyoptions import Options
+
+    # TODO: fix pickling of `symbols' flag
+    # for c in (Options, Options((), dict(domain='ZZ', polys=False))):
+    #    check(c)
+
+# TODO: def test_pickling_polys_rootisolation():
+#    RealInterval
+#    ComplexInterval
+
+def test_pickling_polys_rootoftools():
+    from sympy.polys.rootoftools import CRootOf, RootSum
+
+    x = Symbol('x')
+    f = x**3 + x + 3
+
+    for c in (CRootOf, CRootOf(f, 0)):
+        check(c)
+
+    for c in (RootSum, RootSum(f, exp)):
+        check(c)
+
+#================== printing ====================
+from sympy.printing.latex import LatexPrinter
+from sympy.printing.mathml import MathMLContentPrinter, MathMLPresentationPrinter
+from sympy.printing.pretty.pretty import PrettyPrinter
+from sympy.printing.pretty.stringpict import prettyForm, stringPict
+from sympy.printing.printer import Printer
+from sympy.printing.python import PythonPrinter
+
+
+def test_printing():
+    for c in (LatexPrinter, LatexPrinter(), MathMLContentPrinter,
+              MathMLPresentationPrinter, PrettyPrinter, prettyForm, stringPict,
+              stringPict("a"), Printer, Printer(), PythonPrinter,
+              PythonPrinter()):
+        check(c)
+
+
+@XFAIL
+def test_printing1():
+    check(MathMLContentPrinter())
+
+
+@XFAIL
+def test_printing2():
+    check(MathMLPresentationPrinter())
+
+
+@XFAIL
+def test_printing3():
+    check(PrettyPrinter())
+
+#================== series ======================
+from sympy.series.limits import Limit
+from sympy.series.order import Order
+
+
+def test_series():
+    e = Symbol("e")
+    x = Symbol("x")
+    for c in (Limit, Limit(e, x, 1), Order, Order(e)):
+        check(c)
+
+#================== concrete ==================
+from sympy.concrete.products import Product
+from sympy.concrete.summations import Sum
+
+
+def test_concrete():
+    x = Symbol("x")
+    for c in (Product, Product(x, (x, 2, 4)), Sum, Sum(x, (x, 2, 4))):
+        check(c)
+
+def test_deprecation_warning():
+    w = SymPyDeprecationWarning("message", deprecated_since_version='1.0', active_deprecations_target="active-deprecations")
+    check(w)
+
+def test_issue_18438():
+    assert pickle.loads(pickle.dumps(S.Half)) == S.Half
+
+
+#================= old pickles =================
+def test_unpickle_from_older_versions():
+    data = (
+        b'\x80\x04\x95^\x00\x00\x00\x00\x00\x00\x00\x8c\x10sympy.core.power'
+        b'\x94\x8c\x03Pow\x94\x93\x94\x8c\x12sympy.core.numbers\x94\x8c'
+        b'\x07Integer\x94\x93\x94K\x02\x85\x94R\x94}\x94bh\x03\x8c\x04Half'
+        b'\x94\x93\x94)R\x94}\x94b\x86\x94R\x94}\x94b.'
+    )
+    assert pickle.loads(data) == sqrt(2)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_source.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_source.py
new file mode 100644
index 0000000000000000000000000000000000000000..468185bc579fc325aee21024dfa15ebf14287b5f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_source.py
@@ -0,0 +1,11 @@
+from sympy.utilities.source import get_mod_func, get_class
+
+
+def test_get_mod_func():
+    assert get_mod_func(
+        'sympy.core.basic.Basic') == ('sympy.core.basic', 'Basic')
+
+
+def test_get_class():
+    _basic = get_class('sympy.core.basic.Basic')
+    assert _basic.__name__ == 'Basic'
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_timeutils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_timeutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..14edfd089c7315ee9f39a4298af0289f8919da6b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_timeutils.py
@@ -0,0 +1,10 @@
+"""Tests for simple tools for timing functions' execution. """
+
+from sympy.utilities.timeutils import timed
+
+def test_timed():
+    result = timed(lambda: 1 + 1, limit=100000)
+    assert result[0] == 100000 and result[3] == "ns", str(result)
+
+    result = timed("1 + 1", limit=100000)
+    assert result[0] == 100000 and result[3] == "ns"
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_wester.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_wester.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5699a4eb0824e507967ecd4ff8f7a5f32cc9a54
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_wester.py
@@ -0,0 +1,3104 @@
+""" Tests from Michael Wester's 1999 paper "Review of CAS mathematical
+capabilities".
+
+http://www.math.unm.edu/~wester/cas/book/Wester.pdf
+See also http://math.unm.edu/~wester/cas_review.html for detailed output of
+each tested system.
+"""
+
+from sympy.assumptions.ask import Q, ask
+from sympy.assumptions.refine import refine
+from sympy.concrete.products import product
+from sympy.core import EulerGamma
+from sympy.core.evalf import N
+from sympy.core.function import (Derivative, Function, Lambda, Subs,
+    diff, expand, expand_func)
+from sympy.core.mul import Mul
+from sympy.core.intfunc import igcd
+from sympy.core.numbers import (AlgebraicNumber, E, I, Rational,
+    nan, oo, pi, zoo)
+from sympy.core.relational import Eq, Lt
+from sympy.core.singleton import S
+from sympy.core.symbol import Dummy, Symbol, symbols
+from sympy.functions.combinatorial.factorials import (rf, binomial,
+    factorial, factorial2)
+from sympy.functions.combinatorial.numbers import bernoulli, fibonacci, totient, partition
+from sympy.functions.elementary.complexes import (conjugate, im, re,
+    sign)
+from sympy.functions.elementary.exponential import LambertW, exp, log
+from sympy.functions.elementary.hyperbolic import (asinh, cosh, sinh,
+    tanh)
+from sympy.functions.elementary.integers import ceiling, floor
+from sympy.functions.elementary.miscellaneous import Max, Min, sqrt
+from sympy.functions.elementary.piecewise import Piecewise
+from sympy.functions.elementary.trigonometric import (acos, acot, asin,
+    atan, cos, cot, csc, sec, sin, tan)
+from sympy.functions.special.bessel import besselj
+from sympy.functions.special.delta_functions import DiracDelta
+from sympy.functions.special.elliptic_integrals import (elliptic_e,
+    elliptic_f)
+from sympy.functions.special.gamma_functions import gamma, polygamma
+from sympy.functions.special.hyper import hyper
+from sympy.functions.special.polynomials import (assoc_legendre,
+    chebyshevt)
+from sympy.functions.special.zeta_functions import polylog
+from sympy.geometry.util import idiff
+from sympy.logic.boolalg import And
+from sympy.matrices.dense import hessian, wronskian
+from sympy.matrices.expressions.matmul import MatMul
+from sympy.ntheory.continued_fraction import (
+    continued_fraction_convergents as cf_c,
+    continued_fraction_iterator as cf_i, continued_fraction_periodic as
+    cf_p, continued_fraction_reduce as cf_r)
+from sympy.ntheory.factor_ import factorint
+from sympy.ntheory.generate import primerange
+from sympy.polys.domains.integerring import ZZ
+from sympy.polys.orthopolys import legendre_poly
+from sympy.polys.partfrac import apart
+from sympy.polys.polytools import Poly, factor, gcd, resultant
+from sympy.series.limits import limit
+from sympy.series.order import O
+from sympy.series.residues import residue
+from sympy.series.series import series
+from sympy.sets.fancysets import ImageSet
+from sympy.sets.sets import FiniteSet, Intersection, Interval, Union
+from sympy.simplify.combsimp import combsimp
+from sympy.simplify.hyperexpand import hyperexpand
+from sympy.simplify.powsimp import powdenest, powsimp
+from sympy.simplify.radsimp import radsimp
+from sympy.simplify.simplify import logcombine, simplify
+from sympy.simplify.sqrtdenest import sqrtdenest
+from sympy.simplify.trigsimp import trigsimp
+from sympy.solvers.solvers import solve
+
+import mpmath
+from sympy.functions.combinatorial.numbers import stirling
+from sympy.functions.special.delta_functions import Heaviside
+from sympy.functions.special.error_functions import Ci, Si, erf
+from sympy.functions.special.zeta_functions import zeta
+from sympy.testing.pytest import (XFAIL, slow, SKIP, tooslow, raises)
+from sympy.utilities.iterables import partitions
+from mpmath import mpi, mpc
+from sympy.matrices import Matrix, GramSchmidt, eye
+from sympy.matrices.expressions.blockmatrix import BlockMatrix, block_collapse
+from sympy.matrices.expressions import MatrixSymbol, ZeroMatrix
+from sympy.physics.quantum import Commutator
+from sympy.polys.rings import PolyRing
+from sympy.polys.fields import FracField
+from sympy.polys.solvers import solve_lin_sys
+from sympy.concrete import Sum
+from sympy.concrete.products import Product
+from sympy.integrals import integrate
+from sympy.integrals.transforms import laplace_transform,\
+    inverse_laplace_transform, LaplaceTransform, fourier_transform,\
+    mellin_transform, laplace_correspondence, laplace_initial_conds
+from sympy.solvers.recurr import rsolve
+from sympy.solvers.solveset import solveset, solveset_real, linsolve
+from sympy.solvers.ode import dsolve
+from sympy.core.relational import Equality
+from itertools import islice, takewhile
+from sympy.series.formal import fps
+from sympy.series.fourier import fourier_series
+from sympy.calculus.util import minimum
+
+
+EmptySet = S.EmptySet
+R = Rational
+x, y, z = symbols('x y z')
+i, j, k, l, m, n = symbols('i j k l m n', integer=True)
+f = Function('f')
+g = Function('g')
+
+# A. Boolean Logic and Quantifier Elimination
+#   Not implemented.
+
+# B. Set Theory
+
+
+def test_B1():
+    assert (FiniteSet(i, j, j, k, k, k) | FiniteSet(l, k, j) |
+            FiniteSet(j, m, j)) == FiniteSet(i, j, k, l, m)
+
+
+def test_B2():
+    assert (FiniteSet(i, j, j, k, k, k) & FiniteSet(l, k, j) &
+            FiniteSet(j, m, j)) == Intersection({j, m}, {i, j, k}, {j, k, l})
+    # Previous output below. Not sure why that should be the expected output.
+    # There should probably be a way to rewrite Intersections that way but I
+    # don't see why an Intersection should evaluate like that:
+    #
+    # == Union({j}, Intersection({m}, Union({j, k}, Intersection({i}, {l}))))
+
+
+def test_B3():
+    assert (FiniteSet(i, j, k, l, m) - FiniteSet(j) ==
+            FiniteSet(i, k, l, m))
+
+
+def test_B4():
+    assert (FiniteSet(*(FiniteSet(i, j)*FiniteSet(k, l))) ==
+            FiniteSet((i, k), (i, l), (j, k), (j, l)))
+
+
+# C. Numbers
+
+
+def test_C1():
+    assert (factorial(50) ==
+        30414093201713378043612608166064768844377641568960512000000000000)
+
+
+def test_C2():
+    assert (factorint(factorial(50)) == {2: 47, 3: 22, 5: 12, 7: 8,
+        11: 4, 13: 3, 17: 2, 19: 2, 23: 2, 29: 1, 31: 1, 37: 1,
+        41: 1, 43: 1, 47: 1})
+
+
+def test_C3():
+    assert (factorial2(10), factorial2(9)) == (3840, 945)
+
+
+# Base conversions; not really implemented by SymPy
+# Whatever. Take credit!
+def test_C4():
+    assert 0xABC == 2748
+
+
+def test_C5():
+    assert 123 == int('234', 7)
+
+
+def test_C6():
+    assert int('677', 8) == int('1BF', 16) == 447
+
+
+def test_C7():
+    assert log(32768, 8) == 5
+
+
+def test_C8():
+    # Modular multiplicative inverse. Would be nice if divmod could do this.
+    assert ZZ.invert(5, 7) == 3
+    assert ZZ.invert(5, 6) == 5
+
+
+def test_C9():
+    assert igcd(igcd(1776, 1554), 5698) == 74
+
+
+def test_C10():
+    x = 0
+    for n in range(2, 11):
+        x += R(1, n)
+    assert x == R(4861, 2520)
+
+
+def test_C11():
+    assert R(1, 7) == S('0.[142857]')
+
+
+def test_C12():
+    assert R(7, 11) * R(22, 7) == 2
+
+
+def test_C13():
+    test = R(10, 7) * (1 + R(29, 1000)) ** R(1, 3)
+    good = 3 ** R(1, 3)
+    assert test == good
+
+
+def test_C14():
+    assert sqrtdenest(sqrt(2*sqrt(3) + 4)) == 1 + sqrt(3)
+
+
+def test_C15():
+    test = sqrtdenest(sqrt(14 + 3*sqrt(3 + 2*sqrt(5 - 12*sqrt(3 - 2*sqrt(2))))))
+    good = sqrt(2) + 3
+    assert test == good
+
+
+def test_C16():
+    test = sqrtdenest(sqrt(10 + 2*sqrt(6) + 2*sqrt(10) + 2*sqrt(15)))
+    good = sqrt(2) + sqrt(3) + sqrt(5)
+    assert test == good
+
+
+def test_C17():
+    test = radsimp((sqrt(3) + sqrt(2)) / (sqrt(3) - sqrt(2)))
+    good = 5 + 2*sqrt(6)
+    assert test == good
+
+
+def test_C18():
+    assert simplify((sqrt(-2 + sqrt(-5)) * sqrt(-2 - sqrt(-5))).expand(complex=True)) == 3
+
+
+@XFAIL
+def test_C19():
+    assert radsimp(simplify((90 + 34*sqrt(7)) ** R(1, 3))) == 3 + sqrt(7)
+
+
+def test_C20():
+    inside = (135 + 78*sqrt(3))
+    test = AlgebraicNumber((inside**R(2, 3) + 3) * sqrt(3) / inside**R(1, 3))
+    assert simplify(test) == AlgebraicNumber(12)
+
+
+def test_C21():
+    assert simplify(AlgebraicNumber((41 + 29*sqrt(2)) ** R(1, 5))) == \
+        AlgebraicNumber(1 + sqrt(2))
+
+
+@XFAIL
+def test_C22():
+    test = simplify(((6 - 4*sqrt(2))*log(3 - 2*sqrt(2)) + (3 - 2*sqrt(2))*log(17
+        - 12*sqrt(2)) + 32 - 24*sqrt(2)) / (48*sqrt(2) - 72))
+    good = sqrt(2)/3 - log(sqrt(2) - 1)/3
+    assert test == good
+
+
+def test_C23():
+    assert 2 * oo - 3 is oo
+
+
+@XFAIL
+def test_C24():
+    raise NotImplementedError("2**aleph_null == aleph_1")
+
+# D. Numerical Analysis
+
+
+def test_D1():
+    assert 0.0 / sqrt(2) == 0
+
+
+def test_D2():
+    assert str(exp(-1000000).evalf()) == '3.29683147808856e-434295'
+
+
+def test_D3():
+    assert exp(pi*sqrt(163)).evalf(50).num.ae(262537412640768744)
+
+
+def test_D4():
+    assert floor(R(-5, 3)) == -2
+    assert ceiling(R(-5, 3)) == -1
+
+
+@XFAIL
+def test_D5():
+    raise NotImplementedError("cubic_spline([1, 2, 4, 5], [1, 4, 2, 3], x)(3) == 27/8")
+
+
+@XFAIL
+def test_D6():
+    raise NotImplementedError("translate sum(a[i]*x**i, (i,1,n)) to FORTRAN")
+
+
+@XFAIL
+def test_D7():
+    raise NotImplementedError("translate sum(a[i]*x**i, (i,1,n)) to C")
+
+
+@XFAIL
+def test_D8():
+    # One way is to cheat by converting the sum to a string,
+    # and replacing the '[' and ']' with ''.
+    # E.g., horner(S(str(_).replace('[','').replace(']','')))
+    raise NotImplementedError("apply Horner's rule to sum(a[i]*x**i, (i,1,5))")
+
+
+@XFAIL
+def test_D9():
+    raise NotImplementedError("translate D8 to FORTRAN")
+
+
+@XFAIL
+def test_D10():
+    raise NotImplementedError("translate D8 to C")
+
+
+@XFAIL
+def test_D11():
+    #Is there a way to use count_ops?
+    raise NotImplementedError("flops(sum(product(f[i][k], (i,1,k)), (k,1,n)))")
+
+
+@XFAIL
+def test_D12():
+    assert (mpi(-4, 2) * x + mpi(1, 3)) ** 2 == mpi(-8, 16)*x**2 + mpi(-24, 12)*x + mpi(1, 9)
+
+
+@XFAIL
+def test_D13():
+    raise NotImplementedError("discretize a PDE: diff(f(x,t),t) == diff(diff(f(x,t),x),x)")
+
+# E. Statistics
+#   See scipy; all of this is numerical.
+
+# F. Combinatorial Theory.
+
+
+def test_F1():
+    assert rf(x, 3) == x*(1 + x)*(2 + x)
+
+
+def test_F2():
+    assert expand_func(binomial(n, 3)) == n*(n - 1)*(n - 2)/6
+
+
+@XFAIL
+def test_F3():
+    assert combsimp(2**n * factorial(n) * factorial2(2*n - 1)) == factorial(2*n)
+
+
+@XFAIL
+def test_F4():
+    assert combsimp(2**n * factorial(n) * product(2*k - 1, (k, 1, n))) == factorial(2*n)
+
+
+@XFAIL
+def test_F5():
+    assert gamma(n + R(1, 2)) / sqrt(pi) / factorial(n) == factorial(2*n)/2**(2*n)/factorial(n)**2
+
+
+def test_F6():
+    partTest = [p.copy() for p in partitions(4)]
+    partDesired = [{4: 1}, {1: 1, 3: 1}, {2: 2}, {1: 2, 2:1}, {1: 4}]
+    assert partTest == partDesired
+
+
+def test_F7():
+    assert partition(4) == 5
+
+
+def test_F8():
+    assert stirling(5, 2, signed=True) == -50  # if signed, then kind=1
+
+
+def test_F9():
+    assert totient(1776) == 576
+
+# G. Number Theory
+
+
+def test_G1():
+    assert list(primerange(999983, 1000004)) == [999983, 1000003]
+
+
+@XFAIL
+def test_G2():
+    raise NotImplementedError("find the primitive root of 191 == 19")
+
+
+@XFAIL
+def test_G3():
+    raise NotImplementedError("(a+b)**p mod p == a**p + b**p mod p; p prime")
+
+# ... G14 Modular equations are not implemented.
+
+def test_G15():
+    assert Rational(sqrt(3).evalf()).limit_denominator(15) == R(26, 15)
+    assert list(takewhile(lambda x: x.q <= 15, cf_c(cf_i(sqrt(3)))))[-1] == \
+        R(26, 15)
+
+
+def test_G16():
+    assert list(islice(cf_i(pi),10)) == [3, 7, 15, 1, 292, 1, 1, 1, 2, 1]
+
+
+def test_G17():
+    assert cf_p(0, 1, 23) == [4, [1, 3, 1, 8]]
+
+
+def test_G18():
+    assert cf_p(1, 2, 5) == [[1]]
+    assert cf_r([[1]]).expand() == S.Half + sqrt(5)/2
+
+
+@XFAIL
+def test_G19():
+    s = symbols('s', integer=True, positive=True)
+    it = cf_i((exp(1/s) - 1)/(exp(1/s) + 1))
+    assert list(islice(it, 5)) == [0, 2*s, 6*s, 10*s, 14*s]
+
+
+def test_G20():
+    s = symbols('s', integer=True, positive=True)
+    # Wester erroneously has this as -s + sqrt(s**2 + 1)
+    assert cf_r([[2*s]]) == s + sqrt(s**2 + 1)
+
+
+@XFAIL
+def test_G20b():
+    s = symbols('s', integer=True, positive=True)
+    assert cf_p(s, 1, s**2 + 1) == [[2*s]]
+
+
+# H. Algebra
+
+
+def test_H1():
+    assert simplify(2*2**n) == simplify(2**(n + 1))
+    assert powdenest(2*2**n) == simplify(2**(n + 1))
+
+
+def test_H2():
+    assert powsimp(4 * 2**n) == 2**(n + 2)
+
+
+def test_H3():
+    assert (-1)**(n*(n + 1)) == 1
+
+
+def test_H4():
+    expr = factor(6*x - 10)
+    assert type(expr) is Mul
+    assert expr.args[0] == 2
+    assert expr.args[1] == 3*x - 5
+
+p1 = 64*x**34 - 21*x**47 - 126*x**8 - 46*x**5 - 16*x**60 - 81
+p2 = 72*x**60 - 25*x**25 - 19*x**23 - 22*x**39 - 83*x**52 + 54*x**10 + 81
+q = 34*x**19 - 25*x**16 + 70*x**7 + 20*x**3 - 91*x - 86
+
+
+def test_H5():
+    assert gcd(p1, p2, x) == 1
+
+
+def test_H6():
+    assert gcd(expand(p1 * q), expand(p2 * q)) == q
+
+
+def test_H7():
+    p1 = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5
+    p2 = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z
+    assert gcd(p1, p2, x, y, z) == 1
+
+
+def test_H8():
+    p1 = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5
+    p2 = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z
+    q = 11*x**12*y**7*z**13 - 23*x**2*y**8*z**10 + 47*x**17*y**5*z**8
+    assert gcd(p1 * q, p2 * q, x, y, z) == q
+
+
+def test_H9():
+    x = Symbol('x', zero=False)
+    p1 = 2*x**(n + 4) - x**(n + 2)
+    p2 = 4*x**(n + 1) + 3*x**n
+    assert gcd(p1, p2) == x**n
+
+
+def test_H10():
+    p1 = 3*x**4 + 3*x**3 + x**2 - x - 2
+    p2 = x**3 - 3*x**2 + x + 5
+    assert resultant(p1, p2, x) == 0
+
+
+def test_H11():
+    assert resultant(p1 * q, p2 * q, x) == 0
+
+
+def test_H12():
+    num = x**2 - 4
+    den = x**2 + 4*x + 4
+    assert simplify(num/den) == (x - 2)/(x + 2)
+
+
+@XFAIL
+def test_H13():
+    assert simplify((exp(x) - 1) / (exp(x/2) + 1)) == exp(x/2) - 1
+
+
+def test_H14():
+    p = (x + 1) ** 20
+    ep = expand(p)
+    assert ep == (1 + 20*x + 190*x**2 + 1140*x**3 + 4845*x**4 + 15504*x**5
+        + 38760*x**6 + 77520*x**7 + 125970*x**8 + 167960*x**9 + 184756*x**10
+        + 167960*x**11 + 125970*x**12 + 77520*x**13 + 38760*x**14 + 15504*x**15
+        + 4845*x**16 + 1140*x**17 + 190*x**18 + 20*x**19 + x**20)
+    dep = diff(ep, x)
+    assert dep == (20 + 380*x + 3420*x**2 + 19380*x**3 + 77520*x**4
+        + 232560*x**5 + 542640*x**6 + 1007760*x**7 + 1511640*x**8 + 1847560*x**9
+        + 1847560*x**10 + 1511640*x**11 + 1007760*x**12 + 542640*x**13
+        + 232560*x**14 + 77520*x**15 + 19380*x**16 + 3420*x**17 + 380*x**18
+        + 20*x**19)
+    assert factor(dep) == 20*(1 + x)**19
+
+
+def test_H15():
+    assert simplify(Mul(*[x - r for r in solveset(x**3 + x**2 - 7)])) == x**3 + x**2 - 7
+
+
+def test_H16():
+    assert factor(x**100 - 1) == ((x - 1)*(x + 1)*(x**2 + 1)*(x**4 - x**3
+        + x**2 - x + 1)*(x**4 + x**3 + x**2 + x + 1)*(x**8 - x**6 + x**4
+        - x**2 + 1)*(x**20 - x**15 + x**10 - x**5 + 1)*(x**20 + x**15 + x**10
+        + x**5 + 1)*(x**40 - x**30 + x**20 - x**10 + 1))
+
+
+def test_H17():
+    assert simplify(factor(expand(p1 * p2)) - p1*p2) == 0
+
+
+@XFAIL
+def test_H18():
+    # Factor over complex rationals.
+    test = factor(4*x**4 + 8*x**3 + 77*x**2 + 18*x + 153)
+    good = (2*x + 3*I)*(2*x - 3*I)*(x + 1 - 4*I)*(x + 1 + 4*I)
+    assert test == good
+
+
+def test_H19():
+    a = symbols('a')
+    # The idea is to let a**2 == 2, then solve 1/(a-1). Answer is a+1")
+    assert Poly(a - 1).invert(Poly(a**2 - 2)) == a + 1
+
+
+@XFAIL
+def test_H20():
+    raise NotImplementedError("let a**2==2; (x**3 + (a-2)*x**2 - "
+        + "(2*a+3)*x - 3*a) / (x**2-2) = (x**2 - 2*x - 3) / (x-a)")
+
+
+@XFAIL
+def test_H21():
+    raise NotImplementedError("evaluate (b+c)**4 assuming b**3==2, c**2==3. \
+                              Answer is 2*b + 8*c + 18*b**2 + 12*b*c + 9")
+
+
+def test_H22():
+    assert factor(x**4 - 3*x**2 + 1, modulus=5) == (x - 2)**2 * (x + 2)**2
+
+
+def test_H23():
+    f = x**11 + x + 1
+    g = (x**2 + x + 1) * (x**9 - x**8 + x**6 - x**5 + x**3 - x**2 + 1)
+    assert factor(f, modulus=65537) == g
+
+
+def test_H24():
+    phi = AlgebraicNumber(S.GoldenRatio.expand(func=True), alias='phi')
+    assert factor(x**4 - 3*x**2 + 1, extension=phi) == \
+        (x - phi)*(x + 1 - phi)*(x - 1 + phi)*(x + phi)
+
+
+def test_H25():
+    e = (x - 2*y**2 + 3*z**3) ** 20
+    assert factor(expand(e)) == e
+
+
+def test_H26():
+    g = expand((sin(x) - 2*cos(y)**2 + 3*tan(z)**3)**20)
+    assert factor(g, expand=False) == (-sin(x) + 2*cos(y)**2 - 3*tan(z)**3)**20
+
+
+def test_H27():
+    f = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5
+    g = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z
+    h = -2*z*y**7 \
+        *(6*x**9*y**9*z**3 + 10*x**7*z**6 + 17*y*x**5*z**12 + 40*y**7) \
+        *(3*x**22 + 47*x**17*y**5*z**8 - 6*x**15*y**9*z**2 - 24*x*y**19*z**8 - 5)
+    assert factor(expand(f*g)) == h
+
+
+@XFAIL
+def test_H28():
+    raise NotImplementedError("expand ((1 - c**2)**5 * (1 - s**2)**5 * "
+        + "(c**2 + s**2)**10) with c**2 + s**2 = 1. Answer is c**10*s**10.")
+
+
+@XFAIL
+def test_H29():
+    assert factor(4*x**2 - 21*x*y + 20*y**2, modulus=3) == (x + y)*(x - y)
+
+
+def test_H30():
+    test = factor(x**3 + y**3, extension=sqrt(-3))
+    answer = (x + y)*(x + y*(-R(1, 2) - sqrt(3)/2*I))*(x + y*(-R(1, 2) + sqrt(3)/2*I))
+    assert answer == test
+
+
+def test_H31():
+    f = (x**2 + 2*x + 3)/(x**3 + 4*x**2 + 5*x + 2)
+    g = 2 / (x + 1)**2 - 2 / (x + 1) + 3 / (x + 2)
+    assert apart(f) == g
+
+
+@XFAIL
+def test_H32():  # issue 6558
+    raise NotImplementedError("[A*B*C - (A*B*C)**(-1)]*A*C*B (product \
+                              of a non-commuting product and its inverse)")
+
+
+def test_H33():
+    A, B, C = symbols('A, B, C', commutative=False)
+    assert (Commutator(A, Commutator(B, C))
+        + Commutator(B, Commutator(C, A))
+        + Commutator(C, Commutator(A, B))).doit().expand() == 0
+
+
+# I. Trigonometry
+
+def test_I1():
+    assert tan(pi*R(7, 10)) == -sqrt(1 + 2/sqrt(5))
+
+
+@XFAIL
+def test_I2():
+    assert sqrt((1 + cos(6))/2) == -cos(3)
+
+
+def test_I3():
+    assert cos(n*pi) + sin((4*n - 1)*pi/2) == (-1)**n - 1
+
+
+def test_I4():
+    assert refine(cos(pi*cos(n*pi)) + sin(pi/2*cos(n*pi)), Q.integer(n)) == (-1)**n - 1
+
+
+@XFAIL
+def test_I5():
+    assert sin((n**5/5 + n**4/2 + n**3/3 - n/30) * pi) == 0
+
+
+@XFAIL
+def test_I6():
+    raise NotImplementedError("assuming -3*pi pi**E)
+
+
+@XFAIL
+def test_N2():
+    x = symbols('x', real=True)
+    assert ask(x**4 - x + 1 > 0) is True
+    assert ask(x**4 - x + 1 > 1) is False
+
+
+@XFAIL
+def test_N3():
+    x = symbols('x', real=True)
+    assert ask(And(Lt(-1, x), Lt(x, 1)), abs(x) < 1 )
+
+@XFAIL
+def test_N4():
+    x, y = symbols('x y', real=True)
+    assert ask(2*x**2 > 2*y**2, (x > y) & (y > 0)) is True
+
+
+@XFAIL
+def test_N5():
+    x, y, k = symbols('x y k', real=True)
+    assert ask(k*x**2 > k*y**2, (x > y) & (y > 0) & (k > 0)) is True
+
+
+@slow
+@XFAIL
+def test_N6():
+    x, y, k, n = symbols('x y k n', real=True)
+    assert ask(k*x**n > k*y**n, (x > y) & (y > 0) & (k > 0) & (n > 0)) is True
+
+
+@XFAIL
+def test_N7():
+    x, y = symbols('x y', real=True)
+    assert ask(y > 0, (x > 1) & (y >= x - 1)) is True
+
+
+@XFAIL
+@slow
+def test_N8():
+    x, y, z = symbols('x y z', real=True)
+    assert ask(Eq(x, y) & Eq(y, z),
+               (x >= y) & (y >= z) & (z >= x))
+
+
+def test_N9():
+    x = Symbol('x')
+    assert solveset(abs(x - 1) > 2, domain=S.Reals) == Union(Interval(-oo, -1, False, True),
+                                             Interval(3, oo, True))
+
+
+def test_N10():
+    x = Symbol('x')
+    p = (x - 1)*(x - 2)*(x - 3)*(x - 4)*(x - 5)
+    assert solveset(expand(p) < 0, domain=S.Reals) == Union(Interval(-oo, 1, True, True),
+                                            Interval(2, 3, True, True),
+                                            Interval(4, 5, True, True))
+
+
+def test_N11():
+    x = Symbol('x')
+    assert solveset(6/(x - 3) <= 3, domain=S.Reals) == Union(Interval(-oo, 3, True, True), Interval(5, oo))
+
+
+def test_N12():
+    x = Symbol('x')
+    assert solveset(sqrt(x) < 2, domain=S.Reals) == Interval(0, 4, False, True)
+
+
+def test_N13():
+    x = Symbol('x')
+    assert solveset(sin(x) < 2, domain=S.Reals) == S.Reals
+
+
+@XFAIL
+def test_N14():
+    x = Symbol('x')
+    # Gives 'Union(Interval(Integer(0), Mul(Rational(1, 2), pi), false, true),
+    #        Interval(Mul(Rational(1, 2), pi), Mul(Integer(2), pi), true, false))'
+    # which is not the correct answer, but the provided also seems wrong.
+    assert solveset(sin(x) < 1, x, domain=S.Reals) == Union(Interval(-oo, pi/2, True, True),
+                                         Interval(pi/2, oo, True, True))
+
+
+def test_N15():
+    r, t = symbols('r t')
+    # raises NotImplementedError: only univariate inequalities are supported
+    solveset(abs(2*r*(cos(t) - 1) + 1) <= 1, r, S.Reals)
+
+
+def test_N16():
+    r, t = symbols('r t')
+    solveset((r**2)*((cos(t) - 4)**2)*sin(t)**2 < 9, r, S.Reals)
+
+
+@XFAIL
+def test_N17():
+    # currently only univariate inequalities are supported
+    assert solveset((x + y > 0, x - y < 0), (x, y)) == (abs(x) < y)
+
+
+def test_O1():
+    M = Matrix((1 + I, -2, 3*I))
+    assert sqrt(expand(M.dot(M.H))) == sqrt(15)
+
+
+def test_O2():
+    assert Matrix((2, 2, -3)).cross(Matrix((1, 3, 1))) == Matrix([[11],
+                                                                  [-5],
+                                                                  [4]])
+
+# The vector module has no way of representing vectors symbolically (without
+# respect to a basis)
+@XFAIL
+def test_O3():
+    # assert (va ^ vb) | (vc ^ vd) == -(va | vc)*(vb | vd) + (va | vd)*(vb | vc)
+    raise NotImplementedError("""The vector module has no way of representing
+        vectors symbolically (without respect to a basis)""")
+
+def test_O4():
+    from sympy.vector import CoordSys3D, Del
+    N = CoordSys3D("N")
+    delop = Del()
+    i, j, k = N.base_vectors()
+    x, y, z = N.base_scalars()
+    F = i*(x*y*z) + j*((x*y*z)**2) + k*((y**2)*(z**3))
+    assert delop.cross(F).doit() == (-2*x**2*y**2*z + 2*y*z**3)*i + x*y*j + (2*x*y**2*z**2 - x*z)*k
+
+@XFAIL
+def test_O5():
+    #assert grad|(f^g)-g|(grad^f)+f|(grad^g)  == 0
+    raise NotImplementedError("""The vector module has no way of representing
+        vectors symbolically (without respect to a basis)""")
+
+#testO8-O9 MISSING!!
+
+
+def test_O10():
+    L = [Matrix([2, 3, 5]), Matrix([3, 6, 2]), Matrix([8, 3, 6])]
+    assert GramSchmidt(L) == [Matrix([
+                              [2],
+                              [3],
+                              [5]]),
+                              Matrix([
+                              [R(23, 19)],
+                              [R(63, 19)],
+                              [R(-47, 19)]]),
+                              Matrix([
+                              [R(1692, 353)],
+                              [R(-1551, 706)],
+                              [R(-423, 706)]])]
+
+
+def test_P1():
+    assert Matrix(3, 3, lambda i, j: j - i).diagonal(-1) == Matrix(
+        1, 2, [-1, -1])
+
+
+def test_P2():
+    M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+    M.row_del(1)
+    M.col_del(2)
+    assert M == Matrix([[1, 2],
+                        [7, 8]])
+
+
+def test_P3():
+    A = Matrix([
+        [11, 12, 13, 14],
+        [21, 22, 23, 24],
+        [31, 32, 33, 34],
+        [41, 42, 43, 44]])
+
+    A11 = A[0:3, 1:4]
+    A12 = A[(0, 1, 3), (2, 0, 3)]
+    A21 = A
+    A221 = -A[0:2, 2:4]
+    A222 = -A[(3, 0), (2, 1)]
+    A22 = BlockMatrix([[A221, A222]]).T
+    rows = [[-A11, A12], [A21, A22]]
+    raises(ValueError, lambda: BlockMatrix(rows))
+    B = Matrix(rows)
+    assert B == Matrix([
+        [-12, -13, -14, 13, 11, 14],
+        [-22, -23, -24, 23, 21, 24],
+        [-32, -33, -34, 43, 41, 44],
+        [11, 12, 13, 14, -13, -23],
+        [21, 22, 23, 24, -14, -24],
+        [31, 32, 33, 34, -43, -13],
+        [41, 42, 43, 44, -42, -12]])
+
+
+@XFAIL
+def test_P4():
+    raise NotImplementedError("Block matrix diagonalization not supported")
+
+
+def test_P5():
+    M = Matrix([[7, 11],
+                [3, 8]])
+    assert  M % 2 == Matrix([[1, 1],
+                             [1, 0]])
+
+
+def test_P6():
+    M = Matrix([[cos(x), sin(x)],
+                [-sin(x), cos(x)]])
+    assert M.diff(x, 2) == Matrix([[-cos(x), -sin(x)],
+                                   [sin(x), -cos(x)]])
+
+
+def test_P7():
+    M = Matrix([[x, y]])*(
+        z*Matrix([[1, 3, 5],
+                  [2, 4, 6]]) + Matrix([[7, -9, 11],
+                                        [-8, 10, -12]]))
+    assert M == Matrix([[x*(z + 7) + y*(2*z - 8), x*(3*z - 9) + y*(4*z + 10),
+                         x*(5*z + 11) + y*(6*z - 12)]])
+
+
+def test_P8():
+    M = Matrix([[1, -2*I],
+                [-3*I, 4]])
+    assert M.norm(ord=S.Infinity) == 7
+
+
+def test_P9():
+    a, b, c = symbols('a b c', nonzero=True)
+    M = Matrix([[a/(b*c), 1/c, 1/b],
+                [1/c, b/(a*c), 1/a],
+                [1/b, 1/a, c/(a*b)]])
+    assert factor(M.norm('fro')) == (a**2 + b**2 + c**2)/(abs(a)*abs(b)*abs(c))
+
+
+@XFAIL
+def test_P10():
+    M = Matrix([[1, 2 + 3*I],
+                [f(4 - 5*I), 6]])
+    # conjugate(f(4 - 5*i)) is not simplified to f(4+5*I)
+    assert M.H == Matrix([[1, f(4 + 5*I)],
+                          [2 + 3*I, 6]])
+
+
+@XFAIL
+def test_P11():
+    # raises NotImplementedError("Matrix([[x,y],[1,x*y]]).inv()
+    #   not simplifying to extract common factor")
+    assert Matrix([[x, y],
+                   [1, x*y]]).inv() == (1/(x**2 - 1))*Matrix([[x, -1],
+                                                              [-1/y, x/y]])
+
+
+def test_P11_workaround():
+    # This test was changed to inverse method ADJ because it depended on the
+    # specific form of inverse returned from the 'GE' method which has changed.
+    M = Matrix([[x, y], [1, x*y]]).inv('ADJ')
+    c = gcd(tuple(M))
+    assert MatMul(c, M/c, evaluate=False) == MatMul(c, Matrix([
+        [x*y, -y],
+        [ -1,  x]]), evaluate=False)
+
+
+def test_P12():
+    A11 = MatrixSymbol('A11', n, n)
+    A12 = MatrixSymbol('A12', n, n)
+    A22 = MatrixSymbol('A22', n, n)
+    B = BlockMatrix([[A11, A12],
+                     [ZeroMatrix(n, n), A22]])
+    assert block_collapse(B.I) == BlockMatrix([[A11.I, (-1)*A11.I*A12*A22.I],
+                                               [ZeroMatrix(n, n), A22.I]])
+
+
+def test_P13():
+    M = Matrix([[1,     x - 2,                         x - 3],
+                [x - 1, x**2 - 3*x + 6,       x**2 - 3*x - 2],
+                [x - 2, x**2 - 8,       2*(x**2) - 12*x + 14]])
+    L, U, _ = M.LUdecomposition()
+    assert simplify(L) == Matrix([[1,     0,     0],
+                                  [x - 1, 1,     0],
+                                  [x - 2, x - 3, 1]])
+    assert simplify(U) == Matrix([[1, x - 2, x - 3],
+                                  [0,     4, x - 5],
+                                  [0,     0, x - 7]])
+
+
+def test_P14():
+    M = Matrix([[1, 2, 3, 1, 3],
+                [3, 2, 1, 1, 7],
+                [0, 2, 4, 1, 1],
+                [1, 1, 1, 1, 4]])
+    R, _ = M.rref()
+    assert R == Matrix([[1, 0, -1, 0,  2],
+                        [0, 1,  2, 0, -1],
+                        [0, 0,  0, 1,  3],
+                        [0, 0,  0, 0,  0]])
+
+
+def test_P15():
+    M = Matrix([[-1, 3,  7, -5],
+                [4, -2,  1,  3],
+                [2,  4, 15, -7]])
+    assert M.rank() == 2
+
+
+def test_P16():
+    M = Matrix([[2*sqrt(2), 8],
+                [6*sqrt(6), 24*sqrt(3)]])
+    assert M.rank() == 1
+
+
+def test_P17():
+    t = symbols('t', real=True)
+    M=Matrix([
+        [sin(2*t), cos(2*t)],
+        [2*(1 - (cos(t)**2))*cos(t), (1 - 2*(sin(t)**2))*sin(t)]])
+    assert M.rank() == 1
+
+
+def test_P18():
+    M = Matrix([[1,  0, -2, 0],
+                [-2, 1,  0, 3],
+                [-1, 2, -6, 6]])
+    assert M.nullspace() == [Matrix([[2],
+                                     [4],
+                                     [1],
+                                     [0]]),
+                             Matrix([[0],
+                                     [-3],
+                                     [0],
+                                     [1]])]
+
+
+def test_P19():
+    w = symbols('w')
+    M = Matrix([[1,    1,    1,    1],
+                [w,    x,    y,    z],
+                [w**2, x**2, y**2, z**2],
+                [w**3, x**3, y**3, z**3]])
+    assert M.det() == (w**3*x**2*y   - w**3*x**2*z - w**3*x*y**2 + w**3*x*z**2
+                       + w**3*y**2*z - w**3*y*z**2 - w**2*x**3*y + w**2*x**3*z
+                       + w**2*x*y**3 - w**2*x*z**3 - w**2*y**3*z + w**2*y*z**3
+                       + w*x**3*y**2 - w*x**3*z**2 - w*x**2*y**3 + w*x**2*z**3
+                       + w*y**3*z**2 - w*y**2*z**3 - x**3*y**2*z + x**3*y*z**2
+                       + x**2*y**3*z - x**2*y*z**3 - x*y**3*z**2 + x*y**2*z**3
+                       )
+
+
+@XFAIL
+def test_P20():
+    raise NotImplementedError("Matrix minimal polynomial not supported")
+
+
+def test_P21():
+    M = Matrix([[5, -3, -7],
+                [-2, 1,  2],
+                [2, -3, -4]])
+    assert M.charpoly(x).as_expr() == x**3 - 2*x**2 - 5*x + 6
+
+
+def test_P22():
+    d = 100
+    M = (2 - x)*eye(d)
+    assert M.eigenvals() == {-x + 2: d}
+
+
+def test_P23():
+    M = Matrix([
+        [2, 1, 0, 0, 0],
+        [1, 2, 1, 0, 0],
+        [0, 1, 2, 1, 0],
+        [0, 0, 1, 2, 1],
+        [0, 0, 0, 1, 2]])
+    assert M.eigenvals() == {
+        S('1'): 1,
+        S('2'): 1,
+        S('3'): 1,
+        S('sqrt(3) + 2'): 1,
+        S('-sqrt(3) + 2'): 1}
+
+
+def test_P24():
+    M = Matrix([[611,  196, -192,  407,   -8,  -52,  -49,   29],
+                [196,  899,  113, -192,  -71,  -43,   -8,  -44],
+                [-192,  113,  899,  196,   61,   49,    8,   52],
+                [ 407, -192,  196,  611,    8,   44,   59,  -23],
+                [  -8,  -71,   61,    8,  411, -599,  208,  208],
+                [ -52,  -43,   49,   44, -599,  411,  208,  208],
+                [ -49,   -8,    8,   59,  208,  208,   99, -911],
+                [  29,  -44,   52,  -23,  208,  208, -911,   99]])
+    assert M.eigenvals() == {
+        S('0'): 1,
+        S('10*sqrt(10405)'): 1,
+        S('100*sqrt(26) + 510'): 1,
+        S('1000'): 2,
+        S('-100*sqrt(26) + 510'): 1,
+        S('-10*sqrt(10405)'): 1,
+        S('1020'): 1}
+
+
+def test_P25():
+    MF = N(Matrix([[ 611,  196, -192,  407,   -8,  -52,  -49,   29],
+                   [ 196,  899,  113, -192,  -71,  -43,   -8,  -44],
+                   [-192,  113,  899,  196,   61,   49,    8,   52],
+                   [ 407, -192,  196,  611,    8,   44,   59,  -23],
+                   [  -8,  -71,   61,    8,  411, -599,  208,  208],
+                   [ -52,  -43,   49,   44, -599,  411,  208,  208],
+                   [ -49,   -8,    8,   59,  208,  208,   99, -911],
+                   [  29,  -44,   52,  -23,  208,  208, -911,   99]]))
+
+    ev_1 = sorted(MF.eigenvals(multiple=True))
+    ev_2 = sorted(
+        [-1020.0490184299969, 0.0, 0.09804864072151699, 1000.0, 1000.0,
+        1019.9019513592784, 1020.0, 1020.0490184299969])
+
+    for x, y in zip(ev_1, ev_2):
+        assert abs(x - y) < 1e-12
+
+
+def test_P26():
+    a0, a1, a2, a3, a4 = symbols('a0 a1 a2 a3 a4')
+    M = Matrix([[-a4, -a3, -a2, -a1, -a0,  0,  0,  0,  0],
+                [  1,   0,   0,   0,   0,  0,  0,  0,  0],
+                [  0,   1,   0,   0,   0,  0,  0,  0,  0],
+                [  0,   0,   1,   0,   0,  0,  0,  0,  0],
+                [  0,   0,   0,   1,   0,  0,  0,  0,  0],
+                [  0,   0,   0,   0,   0, -1, -1,  0,  0],
+                [  0,   0,   0,   0,   0,  1,  0,  0,  0],
+                [  0,   0,   0,   0,   0,  0,  1, -1, -1],
+                [  0,   0,   0,   0,   0,  0,  0,  1,  0]])
+    assert M.eigenvals(error_when_incomplete=False) == {
+        S('-1/2 - sqrt(3)*I/2'): 2,
+        S('-1/2 + sqrt(3)*I/2'): 2}
+
+
+def test_P27():
+    a = symbols('a')
+    M = Matrix([[a,  0, 0, 0, 0],
+                [0,  0, 0, 0, 1],
+                [0,  0, a, 0, 0],
+                [0,  0, 0, a, 0],
+                [0, -2, 0, 0, 2]])
+
+    assert M.eigenvects() == [
+        (a, 3, [
+            Matrix([1, 0, 0, 0, 0]),
+            Matrix([0, 0, 1, 0, 0]),
+            Matrix([0, 0, 0, 1, 0])
+        ]),
+        (1 - I, 1, [
+            Matrix([0, (1 + I)/2, 0, 0, 1])
+        ]),
+        (1 + I, 1, [
+            Matrix([0, (1 - I)/2, 0, 0, 1])
+        ]),
+    ]
+
+
+@XFAIL
+def test_P28():
+    raise NotImplementedError("Generalized eigenvectors not supported \
+https://github.com/sympy/sympy/issues/5293")
+
+
+@XFAIL
+def test_P29():
+    raise NotImplementedError("Generalized eigenvectors not supported \
+https://github.com/sympy/sympy/issues/5293")
+
+
+def test_P30():
+    M = Matrix([[1,  0,  0,  1, -1],
+                [0,  1, -2,  3, -3],
+                [0,  0, -1,  2, -2],
+                [1, -1,  1,  0,  1],
+                [1, -1,  1, -1,  2]])
+    _, J = M.jordan_form()
+    assert J == Matrix([[-1, 0, 0, 0, 0],
+                        [0,  1, 1, 0, 0],
+                        [0,  0, 1, 0, 0],
+                        [0,  0, 0, 1, 1],
+                        [0,  0, 0, 0, 1]])
+
+
+@XFAIL
+def test_P31():
+    raise NotImplementedError("Smith normal form not implemented")
+
+
+def test_P32():
+    M = Matrix([[1, -2],
+                [2, 1]])
+    assert exp(M).rewrite(cos).simplify() == Matrix([[E*cos(2), -E*sin(2)],
+                                                     [E*sin(2),  E*cos(2)]])
+
+
+def test_P33():
+    w, t = symbols('w t')
+    M = Matrix([[0,    1,      0,   0],
+                [0,    0,      0, 2*w],
+                [0,    0,      0,   1],
+                [0, -2*w, 3*w**2,   0]])
+    assert exp(M*t).rewrite(cos).expand() == Matrix([
+        [1, -3*t + 4*sin(t*w)/w,  6*t*w - 6*sin(t*w), -2*cos(t*w)/w + 2/w],
+        [0,      4*cos(t*w) - 3, -6*w*cos(t*w) + 6*w,          2*sin(t*w)],
+        [0,  2*cos(t*w)/w - 2/w,     -3*cos(t*w) + 4,          sin(t*w)/w],
+        [0,         -2*sin(t*w),        3*w*sin(t*w),            cos(t*w)]])
+
+
+@XFAIL
+def test_P34():
+    a, b, c = symbols('a b c', real=True)
+    M = Matrix([[a, 1, 0, 0, 0, 0],
+                [0, a, 0, 0, 0, 0],
+                [0, 0, b, 0, 0, 0],
+                [0, 0, 0, c, 1, 0],
+                [0, 0, 0, 0, c, 1],
+                [0, 0, 0, 0, 0, c]])
+    # raises exception, sin(M) not supported. exp(M*I) also not supported
+    # https://github.com/sympy/sympy/issues/6218
+    assert sin(M) == Matrix([[sin(a), cos(a), 0, 0, 0, 0],
+                             [0, sin(a), 0, 0, 0, 0],
+                             [0, 0, sin(b), 0, 0, 0],
+                             [0, 0, 0, sin(c), cos(c), -sin(c)/2],
+                             [0, 0, 0, 0, sin(c), cos(c)],
+                             [0, 0, 0, 0, 0, sin(c)]])
+
+
+@XFAIL
+def test_P35():
+    M = pi/2*Matrix([[2, 1, 1],
+                     [2, 3, 2],
+                     [1, 1, 2]])
+    # raises exception, sin(M) not supported. exp(M*I) also not supported
+    # https://github.com/sympy/sympy/issues/6218
+    assert sin(M) == eye(3)
+
+
+@XFAIL
+def test_P36():
+    M = Matrix([[10, 7],
+                [7, 17]])
+    assert sqrt(M) == Matrix([[3, 1],
+                              [1, 4]])
+
+
+def test_P37():
+    M = Matrix([[1, 1, 0],
+                [0, 1, 0],
+                [0, 0, 1]])
+    assert M**S.Half == Matrix([[1, R(1, 2), 0],
+                                        [0, 1,       0],
+                                        [0, 0,       1]])
+
+
+@XFAIL
+def test_P38():
+    M=Matrix([[0, 1, 0],
+              [0, 0, 0],
+              [0, 0, 0]])
+
+    with raises(AssertionError):
+        # raises ValueError: Matrix det == 0; not invertible
+        M**S.Half
+        # if it doesn't raise then this assertion will be
+        # raised and the test will be flagged as not XFAILing
+        assert None
+
+@XFAIL
+def test_P39():
+    """
+    M=Matrix([
+        [1, 1],
+        [2, 2],
+        [3, 3]])
+    M.SVD()
+    """
+    raise NotImplementedError("Singular value decomposition not implemented")
+
+
+def test_P40():
+    r, t = symbols('r t', real=True)
+    M = Matrix([r*cos(t), r*sin(t)])
+    assert M.jacobian(Matrix([r, t])) == Matrix([[cos(t), -r*sin(t)],
+                                                 [sin(t),  r*cos(t)]])
+
+
+def test_P41():
+    r, t = symbols('r t', real=True)
+    assert hessian(r**2*sin(t),(r,t)) == Matrix([[  2*sin(t),   2*r*cos(t)],
+                                                 [2*r*cos(t), -r**2*sin(t)]])
+
+
+def test_P42():
+    assert wronskian([cos(x), sin(x)], x).simplify() == 1
+
+
+def test_P43():
+    def __my_jacobian(M, Y):
+        return Matrix([M.diff(v).T for v in Y]).T
+    r, t = symbols('r t', real=True)
+    M = Matrix([r*cos(t), r*sin(t)])
+    assert __my_jacobian(M,[r,t]) == Matrix([[cos(t), -r*sin(t)],
+                                             [sin(t),  r*cos(t)]])
+
+
+def test_P44():
+    def __my_hessian(f, Y):
+        V = Matrix([diff(f, v) for v in Y])
+        return  Matrix([V.T.diff(v) for v in Y])
+    r, t = symbols('r t', real=True)
+    assert __my_hessian(r**2*sin(t), (r, t)) == Matrix([
+                                            [  2*sin(t),   2*r*cos(t)],
+                                            [2*r*cos(t), -r**2*sin(t)]])
+
+
+def test_P45():
+    def __my_wronskian(Y, v):
+        M = Matrix([Matrix(Y).T.diff(x, n) for n in range(0, len(Y))])
+        return  M.det()
+    assert __my_wronskian([cos(x), sin(x)], x).simplify() == 1
+
+# Q1-Q6  Tensor tests missing
+
+
+@XFAIL
+def test_R1():
+    i, j, n = symbols('i j n', integer=True, positive=True)
+    xn = MatrixSymbol('xn', n, 1)
+    Sm = Sum((xn[i, 0] - Sum(xn[j, 0], (j, 0, n - 1))/n)**2, (i, 0, n - 1))
+    # sum does not calculate
+    # Unknown result
+    Sm.doit()
+    raise NotImplementedError('Unknown result')
+
+@XFAIL
+def test_R2():
+    m, b = symbols('m b')
+    i, n = symbols('i n', integer=True, positive=True)
+    xn = MatrixSymbol('xn', n, 1)
+    yn = MatrixSymbol('yn', n, 1)
+    f = Sum((yn[i, 0] - m*xn[i, 0] - b)**2, (i, 0, n - 1))
+    f1 = diff(f, m)
+    f2 = diff(f, b)
+    # raises TypeError: solveset() takes at most 2 arguments (3 given)
+    solveset((f1, f2), (m, b), domain=S.Reals)
+
+
+@XFAIL
+def test_R3():
+    n, k = symbols('n k', integer=True, positive=True)
+    sk = ((-1)**k) * (binomial(2*n, k))**2
+    Sm = Sum(sk, (k, 1, oo))
+    T = Sm.doit()
+    T2 = T.combsimp()
+    # returns -((-1)**n*factorial(2*n)
+    #           - (factorial(n))**2)*exp_polar(-I*pi)/(factorial(n))**2
+    assert T2 == (-1)**n*binomial(2*n, n)
+
+
+@XFAIL
+def test_R4():
+# Macsyma indefinite sum test case:
+#(c15) /* Check whether the full Gosper algorithm is implemented
+#   => 1/2^(n + 1) binomial(n, k - 1) */
+#closedform(indefsum(binomial(n, k)/2^n - binomial(n + 1, k)/2^(n + 1), k));
+#Time= 2690 msecs
+#                      (- n + k - 1) binomial(n + 1, k)
+#(d15)               - --------------------------------
+#                                     n
+#                                   2 2  (n + 1)
+#
+#(c16) factcomb(makefact(%));
+#Time= 220 msecs
+#                                 n!
+#(d16)                     ----------------
+#                                n
+#                          2 k! 2  (n - k)!
+# Might be possible after fixing https://github.com/sympy/sympy/pull/1879
+    raise NotImplementedError("Indefinite sum not supported")
+
+
+@XFAIL
+def test_R5():
+    a, b, c, n, k = symbols('a b c n k', integer=True, positive=True)
+    sk = ((-1)**k)*(binomial(a + b, a + k)
+                    *binomial(b + c, b + k)*binomial(c + a, c + k))
+    Sm = Sum(sk, (k, 1, oo))
+    T = Sm.doit()  # hypergeometric series not calculated
+    assert T == factorial(a+b+c)/(factorial(a)*factorial(b)*factorial(c))
+
+
+def test_R6():
+    n, k = symbols('n k', integer=True, positive=True)
+    gn = MatrixSymbol('gn', n + 2, 1)
+    Sm = Sum(gn[k, 0] - gn[k - 1, 0], (k, 1, n + 1))
+    assert Sm.doit() == -gn[0, 0] + gn[n + 1, 0]
+
+
+def test_R7():
+    n, k = symbols('n k', integer=True, positive=True)
+    T = Sum(k**3,(k,1,n)).doit()
+    assert T.factor() == n**2*(n + 1)**2/4
+
+@XFAIL
+def test_R8():
+    n, k = symbols('n k', integer=True, positive=True)
+    Sm = Sum(k**2*binomial(n, k), (k, 1, n))
+    T = Sm.doit() #returns Piecewise function
+    assert T.combsimp() == n*(n + 1)*2**(n - 2)
+
+
+def test_R9():
+    n, k = symbols('n k', integer=True, positive=True)
+    Sm = Sum(binomial(n, k - 1)/k, (k, 1, n + 1))
+    assert Sm.doit().simplify() == (2**(n + 1) - 1)/(n + 1)
+
+
+@XFAIL
+def test_R10():
+    n, m, r, k = symbols('n m r k', integer=True, positive=True)
+    Sm = Sum(binomial(n, k)*binomial(m, r - k), (k, 0, r))
+    T = Sm.doit()
+    T2 = T.combsimp().rewrite(factorial)
+    assert T2 == factorial(m + n)/(factorial(r)*factorial(m + n - r))
+    assert T2 == binomial(m + n, r).rewrite(factorial)
+    # rewrite(binomial) is not working.
+    # https://github.com/sympy/sympy/issues/7135
+    T3 = T2.rewrite(binomial)
+    assert T3 == binomial(m + n, r)
+
+
+@XFAIL
+def test_R11():
+    n, k = symbols('n k', integer=True, positive=True)
+    sk = binomial(n, k)*fibonacci(k)
+    Sm = Sum(sk, (k, 0, n))
+    T = Sm.doit()
+    # Fibonacci simplification not implemented
+    # https://github.com/sympy/sympy/issues/7134
+    assert T == fibonacci(2*n)
+
+
+@XFAIL
+def test_R12():
+    n, k = symbols('n k', integer=True, positive=True)
+    Sm = Sum(fibonacci(k)**2, (k, 0, n))
+    T = Sm.doit()
+    assert T == fibonacci(n)*fibonacci(n + 1)
+
+
+@XFAIL
+def test_R13():
+    n, k = symbols('n k', integer=True, positive=True)
+    Sm = Sum(sin(k*x), (k, 1, n))
+    T = Sm.doit()  # Sum is not calculated
+    assert T.simplify() == cot(x/2)/2 - cos(x*(2*n + 1)/2)/(2*sin(x/2))
+
+
+@XFAIL
+def test_R14():
+    n, k = symbols('n k', integer=True, positive=True)
+    Sm = Sum(sin((2*k - 1)*x), (k, 1, n))
+    T = Sm.doit()  # Sum is not calculated
+    assert T.simplify() == sin(n*x)**2/sin(x)
+
+
+@XFAIL
+def test_R15():
+    n, k = symbols('n k', integer=True, positive=True)
+    Sm = Sum(binomial(n - k, k), (k, 0, floor(n/2)))
+    T = Sm.doit()  # Sum is not calculated
+    assert T.simplify() == fibonacci(n + 1)
+
+
+def test_R16():
+    k = symbols('k', integer=True, positive=True)
+    Sm = Sum(1/k**2 + 1/k**3, (k, 1, oo))
+    assert Sm.doit() == zeta(3) + pi**2/6
+
+
+def test_R17():
+    k = symbols('k', integer=True, positive=True)
+    assert abs(float(Sum(1/k**2 + 1/k**3, (k, 1, oo)))
+               - 2.8469909700078206) < 1e-15
+
+
+def test_R18():
+    k = symbols('k', integer=True, positive=True)
+    Sm = Sum(1/(2**k*k**2), (k, 1, oo))
+    T = Sm.doit()
+    assert T.simplify() == -log(2)**2/2 + pi**2/12
+
+
+@slow
+@XFAIL
+def test_R19():
+    k = symbols('k', integer=True, positive=True)
+    Sm = Sum(1/((3*k + 1)*(3*k + 2)*(3*k + 3)), (k, 0, oo))
+    T = Sm.doit()
+    # assert fails, T not  simplified
+    assert T.simplify() == -log(3)/4 + sqrt(3)*pi/12
+
+
+@XFAIL
+def test_R20():
+    n, k = symbols('n k', integer=True, positive=True)
+    Sm = Sum(binomial(n, 4*k), (k, 0, oo))
+    T = Sm.doit()
+    # assert fails, T not  simplified
+    assert T.simplify() == 2**(n/2)*cos(pi*n/4)/2 + 2**(n - 1)/2
+
+
+@XFAIL
+def test_R21():
+    k = symbols('k', integer=True, positive=True)
+    Sm = Sum(1/(sqrt(k*(k + 1)) * (sqrt(k) + sqrt(k + 1))), (k, 1, oo))
+    T = Sm.doit()  # Sum not calculated
+    assert T.simplify() == 1
+
+
+# test_R22 answer not available in Wester samples
+# Sum(Sum(binomial(n, k)*binomial(n - k, n - 2*k)*x**n*y**(n - 2*k),
+#                 (k, 0, floor(n/2))), (n, 0, oo)) with abs(x*y)<1?
+
+
+@XFAIL
+def test_R23():
+    n, k = symbols('n k', integer=True, positive=True)
+    Sm = Sum(Sum((factorial(n)/(factorial(k)**2*factorial(n - 2*k)))*
+                 (x/y)**k*(x*y)**(n - k), (n, 2*k, oo)), (k, 0, oo))
+    # Missing how to express constraint abs(x*y)<1?
+    T = Sm.doit()  # Sum not calculated
+    assert T == -1/sqrt(x**2*y**2 - 4*x**2 - 2*x*y + 1)
+
+
+def test_R24():
+    m, k = symbols('m k', integer=True, positive=True)
+    Sm = Sum(Product(k/(2*k - 1), (k, 1, m)), (m, 2, oo))
+    assert Sm.doit() == pi/2
+
+
+def test_S1():
+    k = symbols('k', integer=True, positive=True)
+    Pr = Product(gamma(k/3), (k, 1, 8))
+    assert Pr.doit().simplify() == 640*sqrt(3)*pi**3/6561
+
+
+def test_S2():
+    n, k = symbols('n k', integer=True, positive=True)
+    assert Product(k, (k, 1, n)).doit() == factorial(n)
+
+
+def test_S3():
+    n, k = symbols('n k', integer=True, positive=True)
+    assert Product(x**k, (k, 1, n)).doit().simplify() == x**(n*(n + 1)/2)
+
+
+def test_S4():
+    n, k = symbols('n k', integer=True, positive=True)
+    assert Product(1 + 1/k, (k, 1, n -1)).doit().simplify() == n
+
+
+def test_S5():
+    n, k = symbols('n k', integer=True, positive=True)
+    assert (Product((2*k - 1)/(2*k), (k, 1, n)).doit().gammasimp() ==
+            gamma(n + S.Half)/(sqrt(pi)*gamma(n + 1)))
+
+
+@XFAIL
+def test_S6():
+    n, k = symbols('n k', integer=True, positive=True)
+    # Product does not evaluate
+    assert (Product(x**2 -2*x*cos(k*pi/n) + 1, (k, 1, n - 1)).doit().simplify()
+            == (x**(2*n) - 1)/(x**2 - 1))
+
+
+@XFAIL
+def test_S7():
+    k = symbols('k', integer=True, positive=True)
+    Pr = Product((k**3 - 1)/(k**3 + 1), (k, 2, oo))
+    T = Pr.doit()     # Product does not evaluate
+    assert T.simplify() == R(2, 3)
+
+
+@XFAIL
+def test_S8():
+    k = symbols('k', integer=True, positive=True)
+    Pr = Product(1 - 1/(2*k)**2, (k, 1, oo))
+    T = Pr.doit()
+    # Product does not evaluate
+    assert T.simplify() == 2/pi
+
+
+@XFAIL
+def test_S9():
+    k = symbols('k', integer=True, positive=True)
+    Pr = Product(1 + (-1)**(k + 1)/(2*k - 1), (k, 1, oo))
+    T = Pr.doit()
+    # Product produces 0
+    # https://github.com/sympy/sympy/issues/7133
+    assert T.simplify() == sqrt(2)
+
+
+@XFAIL
+def test_S10():
+    k = symbols('k', integer=True, positive=True)
+    Pr = Product((k*(k + 1) + 1 + I)/(k*(k + 1) + 1 - I), (k, 0, oo))
+    T = Pr.doit()
+    # Product does not evaluate
+    assert T.simplify() == -1
+
+
+def test_T1():
+    assert limit((1 + 1/n)**n, n, oo) == E
+    assert limit((1 - cos(x))/x**2, x, 0) == S.Half
+
+
+def test_T2():
+    assert limit((3**x + 5**x)**(1/x), x, oo) == 5
+
+
+def test_T3():
+    assert limit(log(x)/(log(x) + sin(x)), x, oo) == 1
+
+
+def test_T4():
+    assert limit((exp(x*exp(-x)/(exp(-x) + exp(-2*x**2/(x + 1))))
+                 - exp(x))/x, x, oo) == -exp(2)
+
+
+def test_T5():
+    assert  limit(x*log(x)*log(x*exp(x) - x**2)**2/log(log(x**2
+                  + 2*exp(exp(3*x**3*log(x))))), x, oo) == R(1, 3)
+
+
+def test_T6():
+    assert limit(1/n * factorial(n)**(1/n), n, oo) == exp(-1)
+
+
+def test_T7():
+    limit(1/n * gamma(n + 1)**(1/n), n, oo)
+
+
+def test_T8():
+    a, z = symbols('a z', positive=True)
+    assert limit(gamma(z + a)/gamma(z)*exp(-a*log(z)), z, oo) == 1
+
+
+@XFAIL
+def test_T9():
+    z, k = symbols('z k', positive=True)
+    # raises NotImplementedError:
+    #           Don't know how to calculate the mrv of '(1, k)'
+    assert limit(hyper((1, k), (1,), z/k), k, oo) == exp(z)
+
+
+@XFAIL
+def test_T10():
+    # No longer raises PoleError, but should return euler-mascheroni constant
+    assert limit(zeta(x) - 1/(x - 1), x, 1) == integrate(-1/x + 1/floor(x), (x, 1, oo))
+
+@XFAIL
+def test_T11():
+    n, k = symbols('n k', integer=True, positive=True)
+    # evaluates to 0
+    assert limit(n**x/(x*product((1 + x/k), (k, 1, n))), n, oo) == gamma(x)
+
+
+def test_T12():
+    x, t = symbols('x t', real=True)
+    # Does not evaluate the limit but returns an expression with erf
+    assert limit(x * integrate(exp(-t**2), (t, 0, x))/(1 - exp(-x**2)),
+                 x, 0) == 1
+
+
+def test_T13():
+    x = symbols('x', real=True)
+    assert [limit(x/abs(x), x, 0, dir='-'),
+            limit(x/abs(x), x, 0, dir='+')] == [-1, 1]
+
+
+def test_T14():
+    x = symbols('x', real=True)
+    assert limit(atan(-log(x)), x, 0, dir='+') == pi/2
+
+
+def test_U1():
+    x = symbols('x', real=True)
+    assert diff(abs(x), x) == sign(x)
+
+
+def test_U2():
+    f = Lambda(x, Piecewise((-x, x < 0), (x, x >= 0)))
+    assert diff(f(x), x) == Piecewise((-1, x < 0), (1, x >= 0))
+
+
+def test_U3():
+    f = Lambda(x, Piecewise((x**2 - 1, x == 1), (x**3, x != 1)))
+    f1 = Lambda(x, diff(f(x), x))
+    assert f1(x) == 3*x**2
+    assert f1(1) == 3
+
+
+@XFAIL
+def test_U4():
+    n = symbols('n', integer=True, positive=True)
+    x = symbols('x', real=True)
+    d = diff(x**n, x, n)
+    assert d.rewrite(factorial) == factorial(n)
+
+
+def test_U5():
+    # issue 6681
+    t = symbols('t')
+    ans = (
+        Derivative(f(g(t)), g(t))*Derivative(g(t), (t, 2)) +
+        Derivative(f(g(t)), (g(t), 2))*Derivative(g(t), t)**2)
+    assert f(g(t)).diff(t, 2) == ans
+    assert ans.doit() == ans
+
+
+def test_U6():
+    h = Function('h')
+    T = integrate(f(y), (y, h(x), g(x)))
+    assert T.diff(x) == (
+        f(g(x))*Derivative(g(x), x) - f(h(x))*Derivative(h(x), x))
+
+
+@XFAIL
+def test_U7():
+    p, t = symbols('p t', real=True)
+    # Exact differential => d(V(P, T)) => dV/dP DP + dV/dT DT
+    # raises ValueError:  Since there is more than one variable in the
+    # expression, the variable(s) of differentiation must be supplied to
+    # differentiate f(p,t)
+    diff(f(p, t))
+
+
+def test_U8():
+    x, y = symbols('x y', real=True)
+    eq = cos(x*y) + x
+    #  If SymPy had implicit_diff() function this hack could be avoided
+    # TODO: Replace solve with solveset, current test fails for solveset
+    assert idiff(y - eq, y, x) == (-y*sin(x*y) + 1)/(x*sin(x*y) + 1)
+
+
+def test_U9():
+    # Wester sample case for Maple:
+    # O29 := diff(f(x, y), x) + diff(f(x, y), y);
+    #                      /d         \   /d         \
+    #                      |-- f(x, y)| + |-- f(x, y)|
+    #                      \dx        /   \dy        /
+    #
+    # O30 := factor(subs(f(x, y) = g(x^2 + y^2), %));
+    #                                2    2
+    #                        2 D(g)(x  + y ) (x + y)
+    x, y = symbols('x y', real=True)
+    su = diff(f(x, y), x) + diff(f(x, y), y)
+    s2 = su.subs(f(x, y), g(x**2 + y**2))
+    s3 = s2.doit().factor()
+    # Subs not performed, s3 = 2*(x + y)*Subs(Derivative(
+    #   g(_xi_1), _xi_1), _xi_1, x**2 + y**2)
+    # Derivative(g(x*2 + y**2), x**2 + y**2) is not valid in SymPy,
+    # and probably will remain that way. You can take derivatives with respect
+    # to other expressions only if they are atomic, like a symbol or a
+    # function.
+    # D operator should be added to SymPy
+    # See https://github.com/sympy/sympy/issues/4719.
+    assert s3 == (x + y)*Subs(Derivative(g(x), x), x, x**2 + y**2)*2
+
+
+def test_U10():
+    # see issue 2519:
+    assert residue((z**3 + 5)/((z**4 - 1)*(z + 1)), z, -1) == R(-9, 4)
+
+@XFAIL
+def test_U11():
+    # assert (2*dx + dz) ^ (3*dx + dy + dz) ^ (dx + dy + 4*dz) == 8*dx ^ dy ^dz
+    raise NotImplementedError
+
+
+@XFAIL
+def test_U12():
+    # Wester sample case:
+    # (c41) /* d(3 x^5 dy /\ dz + 5 x y^2 dz /\ dx + 8 z dx /\ dy)
+    #    => (15 x^4 + 10 x y + 8) dx /\ dy /\ dz */
+    # factor(ext_diff(3*x^5 * dy ~ dz + 5*x*y^2 * dz ~ dx + 8*z * dx ~ dy));
+    #                      4
+    # (d41)              (10 x y + 15 x  + 8) dx dy dz
+    raise NotImplementedError(
+        "External diff of differential form not supported")
+
+
+def test_U13():
+    assert minimum(x**4 - x + 1, x) == -3*2**R(1,3)/8 + 1
+
+
+@XFAIL
+def test_U14():
+    #f = 1/(x**2 + y**2 + 1)
+    #assert [minimize(f), maximize(f)] == [0,1]
+    raise NotImplementedError("minimize(), maximize() not supported")
+
+
+@XFAIL
+def test_U15():
+    raise NotImplementedError("minimize() not supported and also solve does \
+not support multivariate inequalities")
+
+
+@XFAIL
+def test_U16():
+    raise NotImplementedError("minimize() not supported in SymPy and also \
+solve does not support multivariate inequalities")
+
+
+@XFAIL
+def test_U17():
+    raise NotImplementedError("Linear programming, symbolic simplex not \
+supported in SymPy")
+
+
+def test_V1():
+    x = symbols('x', real=True)
+    assert integrate(abs(x), x) == Piecewise((-x**2/2, x <= 0), (x**2/2, True))
+
+
+def test_V2():
+    assert integrate(Piecewise((-x, x < 0), (x, x >= 0)), x
+        ) == Piecewise((-x**2/2, x < 0), (x**2/2, True))
+
+
+def test_V3():
+    assert integrate(1/(x**3 + 2),x).diff().simplify() == 1/(x**3 + 2)
+
+
+def test_V4():
+    assert integrate(2**x/sqrt(1 + 4**x), x) == asinh(2**x)/log(2)
+
+
+@XFAIL
+def test_V5():
+    # Returns (-45*x**2 + 80*x - 41)/(5*sqrt(2*x - 1)*(4*x**2 - 4*x + 1))
+    assert (integrate((3*x - 5)**2/(2*x - 1)**R(7, 2), x).simplify() ==
+            (-41 + 80*x - 45*x**2)/(5*(2*x - 1)**R(5, 2)))
+
+
+@XFAIL
+def test_V6():
+    # returns RootSum(40*_z**2 - 1, Lambda(_i, _i*log(-4*_i + exp(-m*x))))/m
+    assert (integrate(1/(2*exp(m*x) - 5*exp(-m*x)), x) == sqrt(10)*(
+            log(2*exp(m*x) - sqrt(10)) - log(2*exp(m*x) + sqrt(10)))/(20*m))
+
+
+def test_V7():
+    r1 = integrate(sinh(x)**4/cosh(x)**2)
+    assert r1.simplify() == x*R(-3, 2) + sinh(x)**3/(2*cosh(x)) + 3*tanh(x)/2
+
+
+@XFAIL
+def test_V8_V9():
+#Macsyma test case:
+#(c27) /* This example involves several symbolic parameters
+#   => 1/sqrt(b^2 - a^2) log([sqrt(b^2 - a^2) tan(x/2) + a + b]/
+#                            [sqrt(b^2 - a^2) tan(x/2) - a - b])   (a^2 < b^2)
+#      [Gradshteyn and Ryzhik 2.553(3)] */
+#assume(b^2 > a^2)$
+#(c28) integrate(1/(a + b*cos(x)), x);
+#(c29) trigsimp(ratsimp(diff(%, x)));
+#                        1
+#(d29)             ------------
+#                  b cos(x) + a
+    raise NotImplementedError(
+        "Integrate with assumption not supported")
+
+
+def test_V10():
+    assert integrate(1/(3 + 3*cos(x) + 4*sin(x)), x) == log(4*tan(x/2) + 3)/4
+
+
+def test_V11():
+    r1 = integrate(1/(4 + 3*cos(x) + 4*sin(x)), x)
+    r2 = factor(r1)
+    assert (logcombine(r2, force=True) ==
+            log(((tan(x/2) + 1)/(tan(x/2) + 7))**R(1, 3)))
+
+
+def test_V12():
+    r1 = integrate(1/(5 + 3*cos(x) + 4*sin(x)), x)
+    assert r1 == -1/(tan(x/2) + 2)
+
+
+@XFAIL
+def test_V13():
+    r1 = integrate(1/(6 + 3*cos(x) + 4*sin(x)), x)
+    # expression not simplified, returns: -sqrt(11)*I*log(tan(x/2) + 4/3
+    #   - sqrt(11)*I/3)/11 + sqrt(11)*I*log(tan(x/2) + 4/3 + sqrt(11)*I/3)/11
+    assert r1.simplify() == 2*sqrt(11)*atan(sqrt(11)*(3*tan(x/2) + 4)/11)/11
+
+
+@slow
+@XFAIL
+def test_V14():
+    r1 = integrate(log(abs(x**2 - y**2)), x)
+    # Piecewise result does not simplify to the desired result.
+    assert (r1.simplify() == x*log(abs(x**2  - y**2))
+                            + y*log(x + y) - y*log(x - y) - 2*x)
+
+
+def test_V15():
+    r1 = integrate(x*acot(x/y), x)
+    assert simplify(r1 - (x*y + (x**2 + y**2)*acot(x/y))/2) == 0
+
+
+@XFAIL
+def test_V16():
+    # Integral not calculated
+    assert integrate(cos(5*x)*Ci(2*x), x) == Ci(2*x)*sin(5*x)/5 - (Si(3*x) + Si(7*x))/10
+
+@XFAIL
+def test_V17():
+    r1 = integrate((diff(f(x), x)*g(x)
+                   - f(x)*diff(g(x), x))/(f(x)**2 - g(x)**2), x)
+    # integral not calculated
+    assert simplify(r1 - (f(x) - g(x))/(f(x) + g(x))/2) == 0
+
+
+@XFAIL
+def test_W1():
+    # The function has a pole at y.
+    # The integral has a Cauchy principal value of zero but SymPy returns -I*pi
+    # https://github.com/sympy/sympy/issues/7159
+    assert integrate(1/(x - y), (x, y - 1, y + 1)) == 0
+
+
+@XFAIL
+def test_W2():
+    # The function has a pole at y.
+    # The integral is divergent but SymPy returns -2
+    # https://github.com/sympy/sympy/issues/7160
+    # Test case in Macsyma:
+    # (c6) errcatch(integrate(1/(x - a)^2, x, a - 1, a + 1));
+    # Integral is divergent
+    assert integrate(1/(x - y)**2, (x, y - 1, y + 1)) is zoo
+
+
+@XFAIL
+@slow
+def test_W3():
+    # integral is not  calculated
+    # https://github.com/sympy/sympy/issues/7161
+    assert integrate(sqrt(x + 1/x - 2), (x, 0, 1)) == R(4, 3)
+
+
+@XFAIL
+@slow
+def test_W4():
+    # integral is not  calculated
+    assert integrate(sqrt(x + 1/x - 2), (x, 1, 2)) == -2*sqrt(2)/3 + R(4, 3)
+
+
+@XFAIL
+@slow
+def test_W5():
+    # integral is not  calculated
+    assert integrate(sqrt(x + 1/x - 2), (x, 0, 2)) == -2*sqrt(2)/3 + R(8, 3)
+
+
+@XFAIL
+@slow
+def test_W6():
+    # integral is not  calculated
+    assert integrate(sqrt(2 - 2*cos(2*x))/2, (x, pi*R(-3, 4), -pi/4)) == sqrt(2)
+
+
+def test_W7():
+    a = symbols('a', positive=True)
+    r1 = integrate(cos(x)/(x**2 + a**2), (x, -oo, oo))
+    assert r1.simplify() == pi*exp(-a)/a
+
+
+@XFAIL
+def test_W8():
+    # Test case in Mathematica:
+    # In[19]:= Integrate[t^(a - 1)/(1 + t), {t, 0, Infinity},
+    #                    Assumptions -> 0 < a < 1]
+    # Out[19]= Pi Csc[a Pi]
+    raise NotImplementedError(
+        "Integrate with assumption 0 < a < 1 not supported")
+
+
+@XFAIL
+@slow
+def test_W9():
+    # Integrand with a residue at infinity => -2 pi [sin(pi/5) + sin(2pi/5)]
+    # (principal value)   [Levinson and Redheffer, p. 234] *)
+    r1 = integrate(5*x**3/(1 + x + x**2 + x**3 + x**4), (x, -oo, oo))
+    r2 = r1.doit()
+    assert r2 == -2*pi*(sqrt(-sqrt(5)/8 + 5/8) + sqrt(sqrt(5)/8 + 5/8))
+
+
+@XFAIL
+def test_W10():
+    # integrate(1/[1 + x + x^2 + ... + x^(2 n)], x = -infinity..infinity) =
+    #        2 pi/(2 n + 1) [1 + cos(pi/[2 n + 1])] csc(2 pi/[2 n + 1])
+    # [Levinson and Redheffer, p. 255] => 2 pi/5 [1 + cos(pi/5)] csc(2 pi/5) */
+    r1 = integrate(x/(1 + x + x**2 + x**4), (x, -oo, oo))
+    r2 = r1.doit()
+    assert r2 == 2*pi*(sqrt(5)/4 + 5/4)*csc(pi*R(2, 5))/5
+
+
+@XFAIL
+def test_W11():
+    # integral not calculated
+    assert (integrate(sqrt(1 - x**2)/(1 + x**2), (x, -1, 1)) ==
+            pi*(-1 + sqrt(2)))
+
+
+def test_W12():
+    p = symbols('p', positive=True)
+    q = symbols('q', real=True)
+    r1 = integrate(x*exp(-p*x**2 + 2*q*x), (x, -oo, oo))
+    assert r1.simplify() == sqrt(pi)*q*exp(q**2/p)/p**R(3, 2)
+
+
+@XFAIL
+def test_W13():
+    # Integral not calculated. Expected result is 2*(Euler_mascheroni_constant)
+    r1 = integrate(1/log(x) + 1/(1 - x) - log(log(1/x)), (x, 0, 1))
+    assert r1 == 2*EulerGamma
+
+
+def test_W14():
+    assert integrate(sin(x)/x*exp(2*I*x), (x, -oo, oo)) == 0
+
+
+@XFAIL
+def test_W15():
+    # integral not calculated
+    assert integrate(log(gamma(x))*cos(6*pi*x), (x, 0, 1)) == R(1, 12)
+
+
+def test_W16():
+    assert integrate((1 + x)**3*legendre_poly(1, x)*legendre_poly(2, x),
+                     (x, -1, 1)) == R(36, 35)
+
+
+def test_W17():
+    a, b = symbols('a b', positive=True)
+    assert integrate(exp(-a*x)*besselj(0, b*x),
+                 (x, 0, oo)) == 1/(b*sqrt(a**2/b**2 + 1))
+
+
+def test_W18():
+    assert integrate((besselj(1, x)/x)**2, (x, 0, oo)) == 4/(3*pi)
+
+
+@XFAIL
+def test_W19():
+    # Integral not calculated
+    # Expected result is (cos 7 - 1)/7   [Gradshteyn and Ryzhik 6.782(3)]
+    assert integrate(Ci(x)*besselj(0, 2*sqrt(7*x)), (x, 0, oo)) == (cos(7) - 1)/7
+
+
+@XFAIL
+def test_W20():
+    # integral not calculated
+    assert (integrate(x**2*polylog(3, 1/(x + 1)), (x, 0, 1)) ==
+            -pi**2/36 - R(17, 108) + zeta(3)/4 +
+            (-pi**2/2 - 4*log(2) + log(2)**2 + 35/3)*log(2)/9)
+
+
+def test_W21():
+    assert abs(N(integrate(x**2*polylog(3, 1/(x + 1)), (x, 0, 1)))
+        - 0.210882859565594) < 1e-15
+
+
+def test_W22():
+    t, u = symbols('t u', real=True)
+    s = Lambda(x, Piecewise((1, And(x >= 1, x <= 2)), (0, True)))
+    assert integrate(s(t)*cos(t), (t, 0, u)) == Piecewise(
+        (0, u < 0),
+        (-sin(Min(1, u)) + sin(Min(2, u)), True))
+
+
+@slow
+def test_W23():
+    a, b = symbols('a b', positive=True)
+    r1 = integrate(integrate(x/(x**2 + y**2), (x, a, b)), (y, -oo, oo))
+    assert r1.collect(pi).cancel() == -pi*a + pi*b
+
+
+def test_W23b():
+    # like W23 but limits are reversed
+    a, b = symbols('a b', positive=True)
+    r2 = integrate(integrate(x/(x**2 + y**2), (y, -oo, oo)), (x, a, b))
+    assert r2.collect(pi) == pi*(-a + b)
+
+
+@XFAIL
+@tooslow
+def test_W24():
+    # Not that slow, but does not fully evaluate so simplify is slow.
+    # Maybe also require doit()
+    x, y = symbols('x y', real=True)
+    r1 = integrate(integrate(sqrt(x**2 + y**2), (x, 0, 1)), (y, 0, 1))
+    assert (r1 - (sqrt(2) + asinh(1))/3).simplify() == 0
+
+
+@XFAIL
+@tooslow
+def test_W25():
+    a, x, y = symbols('a x y', real=True)
+    i1 = integrate(
+        sin(a)*sin(y)/sqrt(1 - sin(a)**2*sin(x)**2*sin(y)**2),
+        (x, 0, pi/2))
+    i2 = integrate(i1, (y, 0, pi/2))
+    assert (i2 - pi*a/2).simplify() == 0
+
+
+def test_W26():
+    x, y = symbols('x y', real=True)
+    assert integrate(integrate(abs(y - x**2), (y, 0, 2)),
+                     (x, -1, 1)) == R(46, 15)
+
+
+def test_W27():
+    a, b, c = symbols('a b c')
+    assert integrate(integrate(integrate(1, (z, 0, c*(1 - x/a - y/b))),
+                               (y, 0, b*(1 - x/a))),
+                     (x, 0, a)) == a*b*c/6
+
+
+def test_X1():
+    v, c = symbols('v c', real=True)
+    assert (series(1/sqrt(1 - (v/c)**2), v, x0=0, n=8) ==
+            5*v**6/(16*c**6) + 3*v**4/(8*c**4) + v**2/(2*c**2) + 1 + O(v**8))
+
+
+def test_X2():
+    v, c = symbols('v c', real=True)
+    s1 = series(1/sqrt(1 - (v/c)**2), v, x0=0, n=8)
+    assert (1/s1**2).series(v, x0=0, n=8) == -v**2/c**2 + 1 + O(v**8)
+
+
+def test_X3():
+    s1 = (sin(x).series()/cos(x).series()).series()
+    s2 = tan(x).series()
+    assert s2 == x + x**3/3 + 2*x**5/15 + O(x**6)
+    assert s1 == s2
+
+
+def test_X4():
+    s1 = log(sin(x)/x).series()
+    assert s1 == -x**2/6 - x**4/180 + O(x**6)
+    assert log(series(sin(x)/x)).series() == s1
+
+
+@XFAIL
+def test_X5():
+    # test case in Mathematica syntax:
+    # In[21]:= (* => [a f'(a d) + g(b d) + integrate(h(c y), y = 0..d)]
+    #       + [a^2 f''(a d) + b g'(b d) + h(c d)] (x - d) *)
+    # In[22]:= D[f[a*x], x] + g[b*x] + Integrate[h[c*y], {y, 0, x}]
+    # Out[22]= g[b x] + Integrate[h[c y], {y, 0, x}] + a f'[a x]
+    # In[23]:= Series[%, {x, d, 1}]
+    # Out[23]= (g[b d] + Integrate[h[c y], {y, 0, d}] + a f'[a d]) +
+    #                                    2                               2
+    #             (h[c d] + b g'[b d] + a  f''[a d]) (-d + x) + O[-d + x]
+    h = Function('h')
+    a, b, c, d = symbols('a b c d', real=True)
+    # series() raises NotImplementedError:
+    # The _eval_nseries method should be added to  to give terms up to O(x**n) at x=0
+    series(diff(f(a*x), x) + g(b*x) + integrate(h(c*y), (y, 0, x)),
+           x, x0=d, n=2)
+    # assert missing, until exception is removed
+
+
+def test_X6():
+    # Taylor series of nonscalar objects (noncommutative multiplication)
+    # expected result => (B A - A B) t^2/2 + O(t^3)   [Stanly Steinberg]
+    a, b = symbols('a b', commutative=False, scalar=False)
+    assert (series(exp((a + b)*x) - exp(a*x) * exp(b*x), x, x0=0, n=3) ==
+              x**2*(-a*b/2 + b*a/2) + O(x**3))
+
+
+def test_X7():
+    # => sum( Bernoulli[k]/k! x^(k - 2), k = 1..infinity )
+    #    = 1/x^2 - 1/(2 x) + 1/12 - x^2/720 + x^4/30240 + O(x^6)
+    #    [Levinson and Redheffer, p. 173]
+    assert (series(1/(x*(exp(x) - 1)), x, 0, 7) == x**(-2) - 1/(2*x) +
+            R(1, 12) - x**2/720 + x**4/30240 - x**6/1209600 + O(x**7))
+
+
+def test_X8():
+    # Puiseux series (terms with fractional degree):
+    # => 1/sqrt(x - 3/2 pi) + (x - 3/2 pi)^(3/2) / 12 + O([x - 3/2 pi]^(7/2))
+
+    # see issue 7167:
+    x = symbols('x', real=True)
+    assert (series(sqrt(sec(x)), x, x0=pi*3/2, n=4) ==
+            1/sqrt(x - pi*R(3, 2)) + (x - pi*R(3, 2))**R(3, 2)/12 +
+            (x - pi*R(3, 2))**R(7, 2)/160 + O((x - pi*R(3, 2))**4, (x, pi*R(3, 2))))
+
+
+def test_X9():
+    assert (series(x**x, x, x0=0, n=4) == 1 + x*log(x) + x**2*log(x)**2/2 +
+            x**3*log(x)**3/6 + O(x**4*log(x)**4))
+
+
+def test_X10():
+    z, w = symbols('z w')
+    assert (series(log(sinh(z)) + log(cosh(z + w)), z, x0=0, n=2) ==
+            log(cosh(w)) + log(z) + z*sinh(w)/cosh(w) + O(z**2))
+
+
+def test_X11():
+    z, w = symbols('z w')
+    assert (series(log(sinh(z) * cosh(z + w)), z, x0=0, n=2) ==
+            log(cosh(w)) + log(z) + z*sinh(w)/cosh(w) + O(z**2))
+
+
+@XFAIL
+def test_X12():
+    # Look at the generalized Taylor series around x = 1
+    # Result => (x - 1)^a/e^b [1 - (a + 2 b) (x - 1) / 2 + O((x - 1)^2)]
+    a, b, x = symbols('a b x', real=True)
+    # series returns O(log(x-1)**2)
+    # https://github.com/sympy/sympy/issues/7168
+    assert (series(log(x)**a*exp(-b*x), x, x0=1, n=2) ==
+            (x - 1)**a/exp(b)*(1 - (a + 2*b)*(x - 1)/2 + O((x - 1)**2)))
+
+
+def test_X13():
+    assert series(sqrt(2*x**2 + 1), x, x0=oo, n=1) == sqrt(2)*x + O(1/x, (x, oo))
+
+
+@XFAIL
+def test_X14():
+    # Wallis' product => 1/sqrt(pi n) + ...   [Knopp, p. 385]
+    assert series(1/2**(2*n)*binomial(2*n, n),
+                  n, x==oo, n=1) == 1/(sqrt(pi)*sqrt(n)) + O(1/x, (x, oo))
+
+
+@SKIP("https://github.com/sympy/sympy/issues/7164")
+def test_X15():
+    # => 0!/x - 1!/x^2 + 2!/x^3 - 3!/x^4 + O(1/x^5)   [Knopp, p. 544]
+    x, t = symbols('x t', real=True)
+    # raises RuntimeError: maximum recursion depth exceeded
+    # https://github.com/sympy/sympy/issues/7164
+    # 2019-02-17: Raises
+    # PoleError:
+    # Asymptotic expansion of Ei around [-oo] is not implemented.
+    e1 = integrate(exp(-t)/t, (t, x, oo))
+    assert (series(e1, x, x0=oo, n=5) ==
+            6/x**4 + 2/x**3 - 1/x**2 + 1/x + O(x**(-5), (x, oo)))
+
+
+def test_X16():
+    # Multivariate Taylor series expansion => 1 - (x^2 + 2 x y + y^2)/2 + O(x^4)
+    assert (series(cos(x + y), x + y, x0=0, n=4) == 1 - (x + y)**2/2 +
+            O(x**4 + x**3*y + x**2*y**2 + x*y**3 + y**4, x, y))
+
+
+@XFAIL
+def test_X17():
+    # Power series (compute the general formula)
+    # (c41) powerseries(log(sin(x)/x), x, 0);
+    # /aquarius/data2/opt/local/macsyma_422/library1/trgred.so being loaded.
+    #              inf
+    #              ====     i1  2 i1          2 i1
+    #              \        (- 1)   2      bern(2 i1) x
+    # (d41)         >        ------------------------------
+    #              /             2 i1 (2 i1)!
+    #              ====
+    #              i1 = 1
+    # fps does not calculate
+    assert fps(log(sin(x)/x)) == \
+        Sum((-1)**k*2**(2*k - 1)*bernoulli(2*k)*x**(2*k)/(k*factorial(2*k)), (k, 1, oo))
+
+
+@XFAIL
+def test_X18():
+    # Power series (compute the general formula). Maple FPS:
+    # > FormalPowerSeries(exp(-x)*sin(x), x = 0);
+    #                        infinity
+    #                         -----    (1/2 k)                k
+    #                          \      2        sin(3/4 k Pi) x
+    #                           )     -------------------------
+    #                          /                 k!
+    #                         -----
+    #
+    # Now, SymPy returns
+    #      oo
+    #    _____
+    #    \    `
+    #     \        /          k             k\
+    #      \     k |I*(-1 - I)    I*(-1 + I) |
+    #       \   x *|----------- - -----------|
+    #       /      \     2             2     /
+    #      /    ------------------------------
+    #     /                   k!
+    #    /____,
+    #    k = 0
+    k = Dummy('k')
+    assert fps(exp(-x)*sin(x)) == \
+        Sum(2**(S.Half*k)*sin(R(3, 4)*k*pi)*x**k/factorial(k), (k, 0, oo))
+
+
+@XFAIL
+def test_X19():
+    # (c45) /* Derive an explicit Taylor series solution of y as a function of
+    # x from the following implicit relation:
+    #    y = x - 1 + (x - 1)^2/2 + 2/3 (x - 1)^3 + (x - 1)^4 +
+    #        17/10 (x - 1)^5 + ...
+    #    */
+    # x = sin(y) + cos(y);
+    # Time= 0 msecs
+    # (d45)                   x = sin(y) + cos(y)
+    #
+    # (c46) taylor_revert(%, y, 7);
+    raise NotImplementedError("Solve using series not supported. \
+Inverse Taylor series expansion also not supported")
+
+
+@XFAIL
+def test_X20():
+    # Pade (rational function) approximation => (2 - x)/(2 + x)
+    # > numapprox[pade](exp(-x), x = 0, [1, 1]);
+    # bytes used=9019816, alloc=3669344, time=13.12
+    #                                    1 - 1/2 x
+    #                                    ---------
+    #                                    1 + 1/2 x
+    # mpmath support numeric Pade approximant but there is
+    # no symbolic implementation in SymPy
+    # https://en.wikipedia.org/wiki/Pad%C3%A9_approximant
+    raise NotImplementedError("Symbolic Pade approximant not supported")
+
+
+def test_X21():
+    """
+    Test whether `fourier_series` of x periodical on the [-p, p] interval equals
+    `- (2 p / pi) sum( (-1)^n / n sin(n pi x / p), n = 1..infinity )`.
+    """
+    p = symbols('p', positive=True)
+    n = symbols('n', positive=True, integer=True)
+    s = fourier_series(x, (x, -p, p))
+
+    # All cosine coefficients are equal to 0
+    assert s.an.formula == 0
+
+    # Check for sine coefficients
+    assert s.bn.formula.subs(s.bn.variables[0], 0) == 0
+    assert s.bn.formula.subs(s.bn.variables[0], n) == \
+        -2*p/pi * (-1)**n / n * sin(n*pi*x/p)
+
+
+@XFAIL
+def test_X22():
+    # (c52) /* => p / 2
+    #    - (2 p / pi^2) sum( [1 - (-1)^n] cos(n pi x / p) / n^2,
+    #                        n = 1..infinity ) */
+    # fourier_series(abs(x), x, p);
+    #                       p
+    # (e52)                      a  = -
+    #                       0      2
+    #
+    #                       %nn
+    #                   (2 (- 1)    - 2) p
+    # (e53)                a    = ------------------
+    #                 %nn         2    2
+    #                       %pi  %nn
+    #
+    # (e54)                     b    = 0
+    #                      %nn
+    #
+    # Time= 5290 msecs
+    #            inf           %nn            %pi %nn x
+    #            ====       (2 (- 1)    - 2) cos(---------)
+    #            \                    p
+    #          p  >       -------------------------------
+    #            /               2
+    #            ====                %nn
+    #            %nn = 1                     p
+    # (d54)          ----------------------------------------- + -
+    #                       2                 2
+    #                    %pi
+    raise NotImplementedError("Fourier series not supported")
+
+
+def test_Y1():
+    t = symbols('t', positive=True)
+    w = symbols('w', real=True)
+    s = symbols('s')
+    F, _, _ = laplace_transform(cos((w - 1)*t), t, s)
+    assert F == s/(s**2 + (w - 1)**2)
+
+
+def test_Y2():
+    t = symbols('t', positive=True)
+    w = symbols('w', real=True)
+    s = symbols('s')
+    f = inverse_laplace_transform(s/(s**2 + (w - 1)**2), s, t, simplify=True)
+    assert f == cos(t*(w - 1))
+
+
+def test_Y3():
+    t = symbols('t', positive=True)
+    w = symbols('w', real=True)
+    s = symbols('s')
+    F, _, _ = laplace_transform(sinh(w*t)*cosh(w*t), t, s, simplify=True)
+    assert F == w/(s**2 - 4*w**2)
+
+
+def test_Y4():
+    t = symbols('t', positive=True)
+    s = symbols('s')
+    F, _, _ = laplace_transform(erf(3/sqrt(t)), t, s, simplify=True)
+    assert F == 1/s - exp(-6*sqrt(s))/s
+
+
+def test_Y5_Y6():
+# Solve y'' + y = 4 [H(t - 1) - H(t - 2)], y(0) = 1, y'(0) = 0 where H is the
+# Heaviside (unit step) function (the RHS describes a pulse of magnitude 4 and
+# duration 1).  See David A. Sanchez, Richard C. Allen, Jr. and Walter T.
+# Kyner, _Differential Equations: An Introduction_, Addison-Wesley Publishing
+# Company, 1983, p. 211.  First, take the Laplace transform of the ODE
+# => s^2 Y(s) - s + Y(s) = 4/s [e^(-s) - e^(-2 s)]
+# where Y(s) is the Laplace transform of y(t)
+    t = symbols('t', real=True)
+    s = symbols('s')
+    y = Function('y')
+    Y = Function('Y')
+    F = laplace_correspondence(laplace_transform(diff(y(t), t, 2) + y(t)
+                                - 4*(Heaviside(t - 1) - Heaviside(t - 2)),
+                                t, s, noconds=True), {y: Y})
+    D = (
+        -F + s**2*Y(s) - s*y(0) + Y(s) - Subs(Derivative(y(t), t), t, 0) -
+        4*exp(-s)/s + 4*exp(-2*s)/s)
+    assert D == 0
+# Now, solve for Y(s) and then take the inverse Laplace transform
+#   => Y(s) = s/(s^2 + 1) + 4 [1/s - s/(s^2 + 1)] [e^(-s) - e^(-2 s)]
+#   => y(t) = cos t + 4 {[1 - cos(t - 1)] H(t - 1) - [1 - cos(t - 2)] H(t - 2)}
+    Yf = solve(F, Y(s))[0]
+    Yf = laplace_initial_conds(Yf, t, {y: [1, 0]})
+    assert Yf == (s**2*exp(2*s) + 4*exp(s) - 4)*exp(-2*s)/(s*(s**2 + 1))
+    yf = inverse_laplace_transform(Yf, s, t)
+    yf = yf.collect(Heaviside(t-1)).collect(Heaviside(t-2))
+    assert yf == (
+        (4 - 4*cos(t - 1))*Heaviside(t - 1) +
+        (4*cos(t - 2) - 4)*Heaviside(t - 2) +
+        cos(t)*Heaviside(t))
+
+
+@XFAIL
+def test_Y7():
+    # What is the Laplace transform of an infinite square wave?
+    # => 1/s + 2 sum( (-1)^n e^(- s n a)/s, n = 1..infinity )
+    #    [Sanchez, Allen and Kyner, p. 213]
+    t = symbols('t', positive=True)
+    a = symbols('a', real=True)
+    s = symbols('s')
+    F, _, _ = laplace_transform(1 + 2*Sum((-1)**n*Heaviside(t - n*a),
+                                          (n, 1, oo)), t, s)
+    # returns 2*LaplaceTransform(Sum((-1)**n*Heaviside(-a*n + t),
+    #                                (n, 1, oo)), t, s) + 1/s
+    # https://github.com/sympy/sympy/issues/7177
+    assert F == 2*Sum((-1)**n*exp(-a*n*s)/s, (n, 1, oo)) + 1/s
+
+
+@XFAIL
+def test_Y8():
+    assert fourier_transform(1, x, z) == DiracDelta(z)
+
+
+def test_Y9():
+    assert (fourier_transform(exp(-9*x**2), x, z) ==
+            sqrt(pi)*exp(-pi**2*z**2/9)/3)
+
+
+def test_Y10():
+    assert (fourier_transform(abs(x)*exp(-3*abs(x)), x, z).cancel() ==
+            (-8*pi**2*z**2 + 18)/(16*pi**4*z**4 + 72*pi**2*z**2 + 81))
+
+
+@SKIP("https://github.com/sympy/sympy/issues/7181")
+@slow
+def test_Y11():
+    # => pi cot(pi s)   (0 < Re s < 1)   [Gradshteyn and Ryzhik 17.43(5)]
+    x, s = symbols('x s')
+    # raises RuntimeError: maximum recursion depth exceeded
+    # https://github.com/sympy/sympy/issues/7181
+    # Update 2019-02-17 raises:
+    # TypeError: cannot unpack non-iterable MellinTransform object
+    F, _, _ =  mellin_transform(1/(1 - x), x, s)
+    assert F == pi*cot(pi*s)
+
+
+@XFAIL
+def test_Y12():
+    # => 2^(s - 4) gamma(s/2)/gamma(4 - s/2)   (0 < Re s < 1)
+    # [Gradshteyn and Ryzhik 17.43(16)]
+    x, s = symbols('x s')
+    # returns Wrong value -2**(s - 4)*gamma(s/2 - 3)/gamma(-s/2 + 1)
+    # https://github.com/sympy/sympy/issues/7182
+    F, _, _ = mellin_transform(besselj(3, x)/x**3, x, s)
+    assert F == -2**(s - 4)*gamma(s/2)/gamma(-s/2 + 4)
+
+
+@XFAIL
+def test_Y13():
+# Z[H(t - m T)] => z/[z^m (z - 1)]   (H is the Heaviside (unit step) function)                                                 z
+    raise NotImplementedError("z-transform not supported")
+
+
+@XFAIL
+def test_Y14():
+# Z[H(t - m T)] => z/[z^m (z - 1)]   (H is the Heaviside (unit step) function)
+    raise NotImplementedError("z-transform not supported")
+
+
+def test_Z1():
+    r = Function('r')
+    assert (rsolve(r(n + 2) - 2*r(n + 1) + r(n) - 2, r(n),
+                   {r(0): 1, r(1): m}).simplify() == n**2 + n*(m - 2) + 1)
+
+
+def test_Z2():
+    r = Function('r')
+    assert (rsolve(r(n) - (5*r(n - 1) - 6*r(n - 2)), r(n), {r(0): 0, r(1): 1})
+            == -2**n + 3**n)
+
+
+def test_Z3():
+    # => r(n) = Fibonacci[n + 1]   [Cohen, p. 83]
+    r = Function('r')
+    # recurrence solution is correct, Wester expects it to be simplified to
+    # fibonacci(n+1), but that is quite hard
+    expected = ((S(1)/2 - sqrt(5)/2)**n*(S(1)/2 - sqrt(5)/10)
+              + (S(1)/2 + sqrt(5)/2)**n*(sqrt(5)/10 + S(1)/2))
+    sol = rsolve(r(n) - (r(n - 1) + r(n - 2)), r(n), {r(1): 1, r(2): 2})
+    assert sol == expected
+
+
+@XFAIL
+def test_Z4():
+# => [c^(n+1) [c^(n+1) - 2 c - 2] + (n+1) c^2 + 2 c - n] / [(c-1)^3 (c+1)]
+#    [Joan Z. Yu and Robert Israel in sci.math.symbolic]
+    r = Function('r')
+    c = symbols('c')
+    # raises ValueError: Polynomial or rational function expected,
+    #     got '(c**2 - c**n)/(c - c**n)
+    s = rsolve(r(n) - ((1 + c - c**(n-1) - c**(n+1))/(1 - c**n)*r(n - 1)
+                   - c*(1 - c**(n-2))/(1 - c**(n-1))*r(n - 2) + 1),
+           r(n), {r(1): 1, r(2): (2 + 2*c + c**2)/(1 + c)})
+    assert (s - (c*(n + 1)*(c*(n + 1) - 2*c - 2) +
+             (n + 1)*c**2 + 2*c - n)/((c-1)**3*(c+1)) == 0)
+
+
+@XFAIL
+def test_Z5():
+    # Second order ODE with initial conditions---solve directly
+    # transform: f(t) = sin(2 t)/8 - t cos(2 t)/4
+    C1, C2 = symbols('C1 C2')
+    # initial conditions not supported, this is a manual workaround
+    # https://github.com/sympy/sympy/issues/4720
+    eq = Derivative(f(x), x, 2) + 4*f(x) - sin(2*x)
+    sol = dsolve(eq, f(x))
+    f0 = Lambda(x, sol.rhs)
+    assert f0(x) == C2*sin(2*x) + (C1 - x/4)*cos(2*x)
+    f1 = Lambda(x, diff(f0(x), x))
+    # TODO: Replace solve with solveset, when it works for solveset
+    const_dict = solve((f0(0), f1(0)))
+    result = f0(x).subs(C1, const_dict[C1]).subs(C2, const_dict[C2])
+    assert result == -x*cos(2*x)/4 + sin(2*x)/8
+    # Result is OK, but ODE solving with initial conditions should be
+    # supported without all this manual work
+    raise NotImplementedError('ODE solving with initial conditions \
+not supported')
+
+
+@XFAIL
+def test_Z6():
+    # Second order ODE with initial conditions---solve  using Laplace
+    # transform: f(t) = sin(2 t)/8 - t cos(2 t)/4
+    t = symbols('t', positive=True)
+    s = symbols('s')
+    eq = Derivative(f(t), t, 2) + 4*f(t) - sin(2*t)
+    F, _, _ = laplace_transform(eq, t, s)
+    # Laplace transform for diff() not calculated
+    # https://github.com/sympy/sympy/issues/7176
+    assert (F == s**2*LaplaceTransform(f(t), t, s) +
+            4*LaplaceTransform(f(t), t, s) - 2/(s**2 + 4))
+    # rest of test case not implemented
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_xxe.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_xxe.py
new file mode 100644
index 0000000000000000000000000000000000000000..3936e8aa135dde5f22c71548e2f90ed58ac25cb8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tests/test_xxe.py
@@ -0,0 +1,3 @@
+# A test file for XXE injection
+# Username: Test
+# Password: Test
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/timeutils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/timeutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..1caae825103335f3e8afedeaf741cff2b0414fb2
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/timeutils.py
@@ -0,0 +1,75 @@
+"""Simple tools for timing functions' execution, when IPython is not available. """
+
+
+import timeit
+import math
+
+
+_scales = [1e0, 1e3, 1e6, 1e9]
+_units = ['s', 'ms', '\N{GREEK SMALL LETTER MU}s', 'ns']
+
+
+def timed(func, setup="pass", limit=None):
+    """Adaptively measure execution time of a function. """
+    timer = timeit.Timer(func, setup=setup)
+    repeat, number = 3, 1
+
+    for i in range(1, 10):
+        if timer.timeit(number) >= 0.2:
+            break
+        elif limit is not None and number >= limit:
+            break
+        else:
+            number *= 10
+
+    time = min(timer.repeat(repeat, number)) / number
+
+    if time > 0.0:
+        order = min(-int(math.floor(math.log10(time)) // 3), 3)
+    else:
+        order = 3
+
+    return (number, time, time*_scales[order], _units[order])
+
+
+# Code for doing inline timings of recursive algorithms.
+
+def __do_timings():
+    import os
+    res = os.getenv('SYMPY_TIMINGS', '')
+    res = [x.strip() for x in res.split(',')]
+    return set(res)
+
+_do_timings = __do_timings()
+_timestack = None
+
+
+def _print_timestack(stack, level=1):
+    print('-'*level, '%.2f %s%s' % (stack[2], stack[0], stack[3]))
+    for s in stack[1]:
+        _print_timestack(s, level + 1)
+
+
+def timethis(name):
+    def decorator(func):
+        if name not in _do_timings:
+            return func
+
+        def wrapper(*args, **kwargs):
+            from time import time
+            global _timestack
+            oldtimestack = _timestack
+            _timestack = [func.func_name, [], 0, args]
+            t1 = time()
+            r = func(*args, **kwargs)
+            t2 = time()
+            _timestack[2] = t2 - t1
+            if oldtimestack is not None:
+                oldtimestack[1].append(_timestack)
+                _timestack = oldtimestack
+            else:
+                _print_timestack(_timestack)
+                _timestack = None
+            return r
+        return wrapper
+    return decorator
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tmpfiles.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tmpfiles.py
new file mode 100644
index 0000000000000000000000000000000000000000..81c97efbf9d67cc20f25ff251abc94c2f5bafe06
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/sympy/utilities/tmpfiles.py
@@ -0,0 +1,12 @@
+"""
+.. deprecated:: 1.6
+
+   sympy.utilities.tmpfiles has been renamed to sympy.testing.tmpfiles.
+"""
+from sympy.utilities.exceptions import sympy_deprecation_warning
+
+sympy_deprecation_warning("The sympy.utilities.tmpfiles submodule is deprecated. Use sympy.testing.tmpfiles instead.",
+    deprecated_since_version="1.6",
+    active_deprecations_target="deprecated-sympy-utilities-submodules")
+
+from sympy.testing.tmpfiles import *  # noqa:F401,F403
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d5dbf0667a022caa07ec30bb10db5b4f83159dd
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/__init__.py
@@ -0,0 +1,10 @@
+"""torchgen
+
+This module contains codegeneration utilities for PyTorch. It is used to
+build PyTorch from source, but may also be used for out-of-tree projects
+that extend PyTorch.
+
+Note well that we provide no BC guarantees for torchgen. If you're interested
+in using torchgen and want the PyTorch team to be aware, please reach out
+on GitHub.
+"""
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7ad66ea752a43e9b1e7a87b84e8e689f05a1bd5f
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/__pycache__/code_template.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/__pycache__/code_template.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..883edcb96f7dfe05c09c073e557942c812c94f57
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/__pycache__/code_template.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/__pycache__/model.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/__pycache__/model.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..68c92da9b587af941c745bb3b9effac9e407b4e5
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/__pycache__/model.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/__pycache__/utils.cpython-310.pyc b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/__pycache__/utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..20bbacc29f9853904bbdc23ab7754f32aec02aba
Binary files /dev/null and b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/__pycache__/utils.cpython-310.pyc differ
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/aoti/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/aoti/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/aoti/fallback_ops.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/aoti/fallback_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..611400d271d96e1afc290fb9ea4dc751e686dcee
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/aoti/fallback_ops.py
@@ -0,0 +1,191 @@
+# Be extra careful when you edit this file, because it affects AOTInductor ABI compatibility. See
+# https://github.com/pytorch/pytorch/blob/7e86a7c0155295539996e0cf422883571126073e/torchgen/gen.py#L2424-L2436
+# for details.
+#
+# The inductor_fallback_ops list is based on the fallback ops from torch/_inductor/lowering.py.
+#
+# Generally speaking, it is ok to add a new op to the list, but you need to run
+# `python torchgen/gen.py --update-aoti-c-shim` in order to regenerate C shim header files.
+# But it is NOT ok to remove an existing fallback op from the list, since that will break
+# some existing AOTInductor-compiled models.
+#
+# A fallback op version defaults to 1. If you want to extend an existing fallback op by adding
+# a new argument with a default value, while it is fine in the Python world, it will be BC-breaking
+# when generating C shim. Thus you need to bump up the version number of that fallback op by
+# updating the entry in the inductor_fallback_ops list, adding a new version number with a list
+# of new arguments, and then run `python torchgen/gen.py --update-aoti-c-shim` to regenerate.
+
+inductor_fallback_ops: dict[str, dict[str, list[str]]] = {
+    "aten._adaptive_avg_pool2d_backward.default": {},
+    "aten._adaptive_avg_pool2d.default": {},
+    "aten._adaptive_avg_pool3d_backward.default": {},
+    "aten._adaptive_avg_pool3d.default": {},
+    "aten._addmm_activation.default": {},
+    "aten._cdist_backward.default": {},
+    "aten._cdist_forward.default": {},
+    "aten._cudnn_rnn.default": {},
+    "aten._dyn_quant_matmul_4bit.default": {},
+    "aten._dyn_quant_pack_4bit_weight.default": {},
+    "aten._efficient_attention_backward.default": {},
+    "aten._efficient_attention_forward.default": {},
+    "aten._efficientzerotensor.default": {},
+    "aten._embedding_bag_dense_backward.default": {},
+    "aten._embedding_bag_forward_only.default": {},
+    "aten._embedding_bag_per_sample_weights_backward.default": {},
+    "aten._embedding_bag.default": {},
+    "aten._fft_c2c.default": {},
+    "aten._fft_r2c.default": {},
+    "aten._flash_attention_backward.default": {},
+    "aten._flash_attention_forward.default": {},
+    "aten._fused_moving_avg_obs_fq_helper_functional.default": {},
+    "aten._fused_moving_avg_obs_fq_helper.default": {},
+    "aten._fused_rms_norm.default": {},
+    "aten._histogramdd_from_bin_cts.default": {},
+    "aten._int_mm.out": {},
+    "aten._pdist_backward.default": {},
+    "aten._pdist_forward.default": {},
+    "aten._scaled_dot_product_attention_math_for_mps.default": {},
+    "aten._scaled_dot_product_cudnn_attention_backward.default": {},
+    "aten._scaled_dot_product_cudnn_attention.default": {},
+    "aten._scaled_dot_product_efficient_attention_backward.default": {},
+    "aten._scaled_dot_product_efficient_attention.default": {},
+    "aten._scaled_dot_product_flash_attention_backward.default": {},
+    "aten._scaled_dot_product_flash_attention_for_cpu_backward.default": {},
+    "aten._scaled_dot_product_flash_attention_for_cpu.default": {},
+    "aten._scaled_dot_product_flash_attention.default": {},
+    "aten._scaled_dot_product_fused_attention_overrideable_backward.default": {},
+    "aten._scaled_dot_product_fused_attention_overrideable.default": {},
+    "aten._scaled_mm.default": {},
+    "aten._scaled_mm.out": {},
+    "aten._segment_reduce_backward.default": {},
+    "aten._thnn_fused_lstm_cell.default": {},
+    "aten._to_sparse.default": {},
+    "aten._trilinear.default": {},
+    "aten._weight_int4pack_mm.default": {},
+    "aten._weight_int8pack_mm.default": {},
+    "aten.abs.default": {},
+    "aten.adaptive_max_pool2d_backward.default": {},
+    "aten.adaptive_max_pool2d.default": {},
+    "aten.adaptive_max_pool3d_backward.default": {},
+    "aten.adaptive_max_pool3d.default": {},
+    "aten.add.Scalar": {},
+    "aten.add.Tensor": {},
+    "aten.addbmm.default": {},
+    "aten.addmm.out": {},
+    "aten.addmv.default": {},
+    "aten.angle.default": {},
+    "aten.avg_pool2d_backward.default": {},
+    "aten.avg_pool2d.default": {},
+    "aten.avg_pool3d_backward.default": {},
+    "aten.avg_pool3d.default": {},
+    "aten.baddbmm.out": {},
+    "aten.bernoulli_.float": {},
+    "aten.bernoulli_.Tensor": {},
+    "aten.bmm.out": {},
+    "aten.bucketize.Tensor": {},
+    "aten.cat.default": {},
+    "aten.cholesky_inverse.default": {},
+    "aten.cholesky_solve.default": {},
+    "aten.convolution_backward.default": {},
+    "aten.convolution.default": {},
+    "aten.cummax.default": {},
+    "aten.cummin.default": {},
+    "aten.cumprod.default": {},
+    "aten.cumsum.default": {},
+    "aten.exponential.default": {},
+    "aten.fill_.Scalar": {},
+    "aten.fractional_max_pool2d_backward.default": {},
+    "aten.fractional_max_pool2d.default": {},
+    "aten.fractional_max_pool3d_backward.default": {},
+    "aten.fractional_max_pool3d.default": {},
+    "aten.gcd.default": {},
+    "aten.geqrf.default": {},
+    "aten.grid_sampler_2d_backward.default": {},
+    "aten.hann_window.default": {},
+    "aten.histc.default": {},
+    "aten.histogram.bin_ct": {},
+    "aten.index_put.default": {},
+    "aten.index_reduce.default": {},
+    "aten.index.Tensor": {},
+    "aten.kthvalue.default": {},
+    "aten.logcumsumexp.default": {},
+    "aten.lu_unpack.default": {},
+    "aten.masked_scatter_backward.default": {},
+    "aten.masked_scatter.default": {},
+    "aten.masked_select.default": {},
+    "aten.max_pool2d_with_indices_backward.default": {},
+    "aten.max_pool2d_with_indices.default": {},
+    "aten.max_pool3d_with_indices_backward.default": {},
+    "aten.max_pool3d_with_indices.default": {},
+    "aten.max_unpool2d.default": {},
+    "aten.max_unpool3d.default": {},
+    "aten.median.default": {},
+    "aten.mm.out": {},
+    "aten.mode.default": {},
+    "aten.mul.Scalar": {},
+    "aten.mul.Tensor": {},
+    "aten.nanmedian.default": {},
+    "aten.narrow.default": {},
+    "aten.native_dropout.default": {},
+    "aten.nonzero.default": {},
+    "aten.normal_functional.default": {},
+    "aten.ormqr.default": {},
+    "aten.pad.default": {},
+    "aten.permute.default": {},
+    "aten.polar.default": {},
+    "aten.pow.Scalar": {},
+    "aten.pow.Tensor_Scalar": {},
+    "aten.pow.Tensor_Tensor": {},
+    "aten.rand.default": {},
+    "aten.rand.generator": {},
+    "aten.randint.default": {},
+    "aten.randint.generator": {},
+    "aten.randint.low_out": {},
+    "aten.randint.low": {},
+    "aten.randn.default": {},
+    "aten.randn.generator": {},
+    "aten.randperm.default": {},
+    "aten.repeat_interleave.Tensor": {},
+    "aten.replication_pad1d_backward.default": {},
+    "aten.replication_pad2d_backward.default": {},
+    "aten.reshape.default": {},
+    "aten.resize_.default": {},
+    "aten.resize_as_.default": {},
+    "aten.scatter_reduce.two_out": {},
+    "aten.scatter.src_out": {},
+    "aten.scatter.value_out": {},
+    "aten.searchsorted.Scalar": {},
+    "aten.searchsorted.Tensor": {},
+    "aten.segment_reduce.default": {},
+    "aten.set_.source_Tensor": {},
+    "aten.slice.Tensor": {},
+    "aten.soft_margin_loss_backward.default": {},
+    "aten.sort.default": {},
+    "aten.sort.stable": {},
+    "aten.squeeze.dim": {},
+    "aten.to_sparse.default": {},
+    "aten.topk.default": {},
+    "aten.triangular_solve.default": {},
+    "aten.uniform.default": {},
+    "aten.upsample_bicubic2d_backward.default": {},
+    "aten.upsample_linear1d_backward.default": {},
+    "aten.upsample_trilinear3d_backward.default": {},
+    "aten.view_as_complex.default": {},
+    "aten.view_as_real.default": {},
+    "aten.view.dtype": {},
+    "aten._weight_int4pack_mm_with_scales_and_zeros.default": {},
+}
+
+# `python torchgen/gen.py --update-aoti-c-shim` will automatically generate
+# c_shim_aten.{h/cpp} based on the list below.
+# Operators in this list are intended to be used in torch/csrc/stable/ops.h
+# Unlike other c_shims, operators in this file do not bypass the dispatcher.
+# The same BC rules apply as inductor_fallback_ops.
+aten_shimified_ops: dict[str, dict[str, list[str]]] = {
+    "aten.fill_.Scalar": {},
+    "aten.pad.default": {},
+    "aten.narrow.default": {},
+    "aten.amax.default": {},
+    "aten.new_empty.default": {},
+    "aten.new_zeros.default": {},
+}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/autograd.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/autograd.py
new file mode 100644
index 0000000000000000000000000000000000000000..96e192d3a48a9c72202e28117409ed99bc7377f5
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/autograd.py
@@ -0,0 +1,874 @@
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from typing import cast, TYPE_CHECKING
+
+from torchgen import local
+from torchgen.api import cpp
+from torchgen.api.types import BaseCType, Binding, NamedCType, tensorListT
+from torchgen.model import (
+    BaseTy,
+    BaseType,
+    FunctionSchema,
+    ListType,
+    NativeFunction,
+    NativeFunctionsViewGroup,
+    SchemaKind,
+    Type,
+)
+from torchgen.utils import IDENT_REGEX
+
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+
+
+# Represents a saved attribute involved in backward calculation.
+# Note that it can be a derived property of an input argument, e.g.:
+# we could save `other.scalar_type()` instead of the entire `other` tensor.
+@dataclass(frozen=True)
+class SavedAttribute:
+    # The NamedCType holds the updated name and cpp type of the attribute
+    # for the name, Suffix is appended if it's derived property, e.g.: `other_scalar_type`
+    nctype: NamedCType
+
+    # The expression to read the derived property at save time, e.g.:
+    # `other.scalar_type()`.
+    expr: str
+
+
+# Represents a backward formula that calculates derivatives for one
+# or more tensors.
+@dataclass(frozen=True)
+class Derivative:
+    # The formula string (legit C++ expression).
+    # Note that expressions against input arguments have been replaced with the
+    # corresponding saved attributes.
+    # E.g.:
+    #  raw formula: `mul_tensor_backward(grad, self, other.scalar_type())`
+    #         here: `mul_tensor_backward(grad, self, other_scalar_type)`
+    formula: str
+
+    # The formula string before input argument replacement
+    original_formula: str
+
+    # Names of the arguments for which this formula calculates derivatives.
+    var_names: tuple[str, ...]
+
+    # Saved inputs that are referenced by the formula.
+    saved_inputs: tuple[SavedAttribute, ...]
+
+    # Saved outputs that are referenced by the formula.
+    saved_outputs: tuple[SavedAttribute, ...]
+
+    # Gradients that are referenced by name in the formula.
+    named_gradients: set[str]
+
+
+# Represents a forward formula that calculates forward derivatives
+# for one tensor.
+@dataclass(frozen=True)
+class ForwardDerivative:
+    # The formula string (legit C++ expression).
+    # Note that special keywords such as "linear" or "element_wise" have been
+    # replaced by the automatically generated formula.
+    formula: str
+
+    # Name of the output arguments for which this formula calculates forward
+    # derivatives
+    var_names: tuple[str, ...]
+
+    # Type of the output arguments for which this formula calculates forward
+    # derivatives
+    var_types: tuple[Type, ...]
+
+    # Inputs for which the forward derivatives are required for this formula
+    required_inputs_fw_grad: tuple[str, ...] | None
+
+    # Inputs for which the primal is required for this formula
+    required_inputs_primal: tuple[str, ...] | None
+
+    # Flag to specify if this formula requires the original value of self
+    # This is only used by inplace operations
+    required_original_self_value: bool
+
+    # If this formula is specified in derivatives.yaml or if we are reusing the
+    # out of place formula for inplace
+    is_reusing_outplace_formula: bool
+
+
+# Represents differentiability info for a NativeFunction.
+@dataclass(frozen=True)
+class DifferentiabilityInfo:
+    # The base name read from derivatives.yaml.
+    name: str
+
+    # The matching native function.
+    #
+    # There can be multiple NativeFunction having the same base name:
+    #  - different overloads with different types of input arguments;
+    #  - in-place/out/functional variants of the same function;
+    #
+    # We first use the schema string (under the 'name' key) in derivatives.yaml
+    # to find the NativeFunction having the same schema string.
+    # Then we find the in-place/out/functional variants of the matching function.
+    # Among these variants, we choose the one having the same name as the
+    # derivatives.yaml entry. If there is no exact match, then we choose the
+    # in-place variant.
+    # TODO: maybe the logic to search for all variants is no longer necessary?
+    func: NativeFunction
+
+    # The name of the generated autograd function.
+    # It's set only if we will calculate a derivative, i.e.
+    # 'args_with_derivatives' is not empty.
+    op: str | None
+
+    # The derivatives formulae for this function.
+    # Note that the length of this sequence is the number of differentiable inputs
+    derivatives: Sequence[Derivative]
+
+    # The forward derivatives formulae for this function.
+    # Note that the length of this sequence is the number of differentiable outputs
+    forward_derivatives: Sequence[ForwardDerivative]
+
+    # The union of 'saved_inputs' of all 'derivatives'.
+    all_saved_inputs: Sequence[SavedAttribute]
+
+    # The union of 'saved_outputs' of all 'derivatives'.
+    all_saved_outputs: Sequence[SavedAttribute]
+
+    # All named gradients that are available for use, in the same
+    # order as in the grads vector.
+    available_named_gradients: Sequence[str]
+
+    # The named gradients that are used in any of the derivatives.
+    # Invariant: all(name in available_named_gradients for name in used_named_gradients)
+    used_named_gradients: set[str]
+
+    # The function's input arguments for which it calculates derivatives.
+    # It's the union of 'var_names' of all 'derivatives', sorted by the
+    # argument order in the function schema.
+    args_with_derivatives: Sequence[Binding]
+
+    # Names of arguments whose derivative formula is 'non_differentiable'.
+    non_differentiable_arg_names: Sequence[str]
+
+    # Raw data read from derivatives.yaml.
+    output_differentiability: list[bool] | None
+
+    # output_differentiability in derivatives.yaml can be a list of
+    # conditions that express if the output is differentiable. In this case,
+    # the number of conditions must match the number of outputs
+    # (NB: we only support one condition right now).
+    # output_differentiability gets populated with True for each condition,
+    # while output_differentiability_conditions gets populated with the conditions
+    output_differentiability_conditions: list[str] | None
+
+    @property
+    def has_derivatives(self) -> bool:
+        return len(self.args_with_derivatives) > 0
+
+    # Generates a new DifferentiabilityInfo using the exact same set of derivative information,
+    # but with a new operator name.
+    # This is used when generating "copy" variants of view ops,
+    # which are able to use the exact same derivative formula as the original view op
+    # See Note [Codegen'd {view}_copy Operators]
+    def create_view_copy_from_view_derivative(
+        self, g: NativeFunctionsViewGroup
+    ) -> DifferentiabilityInfo | None:
+        if g.view_copy is None:
+            return None
+        f = g.view_copy
+
+        name_split_by_period = self.name.split(".", maxsplit=2)
+        # Append a "_copy" to the base name of the operator (but keep the overload name the same)
+        view_copy_name = f"{name_split_by_period[0]}_copy." + ".".join(
+            name_split_by_period[1:]
+        )
+        view_copy_op_name = None if self.op is None else f"{self.op}_copy"
+
+        return DifferentiabilityInfo(
+            # Use the "_copy" version of name/func/op
+            name=view_copy_name,
+            func=f,
+            op=view_copy_op_name,
+            # But keep all derivative info the same
+            derivatives=self.derivatives,
+            forward_derivatives=self.forward_derivatives,
+            all_saved_inputs=self.all_saved_inputs,
+            all_saved_outputs=self.all_saved_outputs,
+            available_named_gradients=self.available_named_gradients,
+            used_named_gradients=self.used_named_gradients,
+            args_with_derivatives=self.args_with_derivatives,
+            non_differentiable_arg_names=self.non_differentiable_arg_names,
+            output_differentiability=self.output_differentiability,
+            output_differentiability_conditions=self.output_differentiability_conditions,
+        )
+
+
+def uses_ident(info: DifferentiabilityInfo | None, ident: str) -> bool:
+    if info is None:
+        return False
+    for derivative in info.derivatives:
+        formula = derivative.formula
+        if re.search(IDENT_REGEX.format(ident), formula):
+            return True
+    return False
+
+
+def uses_retain_variables(info: DifferentiabilityInfo | None) -> bool:
+    return uses_ident(info, "retain_variables")
+
+
+def uses_single_grad(info: DifferentiabilityInfo | None) -> bool:
+    return uses_ident(info, "grad")
+
+
+# Represents a differentiable `Argument`.
+# How is it different from the `Argument` type?
+# - It's processed Arguments which are differentiable and only used in the
+#   context of the autograd codegen;
+# - It can represent SelfArgument or regular Argument but not TensorOptionsArgument;
+@dataclass(frozen=True)
+class DifferentiableInput:
+    name: str
+    type: Type
+
+    # TODO: only to keep it byte-for-byte compatible with the old codegen, should remove.
+    cpp_type: str
+
+
+# Represents a differentiable `Return`.
+# How it it different from the `Return` type?
+# - The name in `Return` is optional. Here it is always populated using the same
+#   `cpp.return_names()` method.
+#   TODO: some cpp naming logic (e.g. resolving name conflict) might be irrelevant?
+# - It's processed Returns which are differentiable, in compliance with the
+#   `output_differentiability` field defined in derivatives.yaml (if specified),
+#   and are only used in the context of the autograd codegen;
+@dataclass(frozen=True)
+class DifferentiableOutput:
+    name: str
+    type: Type
+
+    # TODO: only to keep it byte-for-byte compatible with the old codegen, should remove.
+    cpp_type: str
+
+
+@dataclass(frozen=True)
+class NativeFunctionWithDifferentiabilityInfo:
+    func: NativeFunction
+    info: dict[str, DifferentiabilityInfo] | None
+    fw_derivatives: dict[str, Sequence[ForwardDerivative]] | None
+
+
+# TODO: Update comment below since it is out of date.
+def dispatch_strategy(fn: NativeFunctionWithDifferentiabilityInfo) -> str:
+    """How are we going to call the underlying implementation of a
+    declaration?  There are two strategies:
+        - use_derived: we want to call the implementation on CPUDoubleType
+          (or a similar, derived Type instance).  Because these derived
+          instances deal in Tensors, not Variables (it's a completely different
+          object, so it doesn't dispatch back to VariableType), code on
+          this dispatch path needs to wrap/unwrap tensors.  If the
+          derived implementation takes and returns tensors, the
+          implementation is usually differentiable (although we also use
+          the derived dispatch path for non-differentiable functions
+          that we still want to dispatch on the derived Type instance;
+          e.g., size())
+        - use_type: we want to call the implementation on Type, because
+          it is implemented concretely, and the functions it invokes will
+          get dispatched back to VariableType (which will ensure that they
+          are differentiable.)
+    """
+    # fn is derived as long as any of its per-key differentiability infos
+    # has_derivatives. dispatch_strategy() is used to guard generation of fns in VariableType
+    # and ADInplaceOrViewType. We want to generate these functions as long as a
+    # derivative is defined for ANY dispatch key.
+    if fn.func.is_abstract or (
+        fn.info is not None and any(info.has_derivatives for info in fn.info.values())
+    ):
+        # If the function is abstract (not implemented on at::Type), we must
+        # call the implementation on the derived type with unpacked tensors.
+
+        # If the function has a derivative specified and is concrete, we could
+        # call either implementation. We prefer the calling the derived
+        # type's implementation with unpacked tensors because it is more
+        # performant in some cases: any internal calls to other ATen functions
+        # won't have the history tracked.
+
+        # If the function has a type dispatched argument (i.e. is a factory),
+        # we prefer calling the derived type's implementation both because it is
+        # more performant and to ensure factory functions return tensors with _version
+        # of 0 (probably not strictly necessary, but nice to have to keeps versions simple
+        # to understand.
+
+        return "use_derived"
+    else:
+        # If the function is concrete (we don't have to override it) and we
+        # didn't declare it in derivatives.yaml, we'll assume that it is
+        # actually implemented out of differentiable functions. (This
+        # assumption might not hold, but then you'll see gradcheck fail.)
+        return "use_type"
+
+
+def is_foreach_func(f: NativeFunction) -> bool:
+    return f.func.name.name.base.startswith("_foreach_")
+
+
+# note(crcrpar): Most foreach functions can reference an out-place `torch` function whose schema kind
+# is functional for their backward derivatives (and forward derivatives in the future), i.e.,
+# they would find such one in `functional_info_by_signature`. There however are some exceptions:
+_foreach_with_inplace_ref = {"_foreach_zero_"}
+_foreach_with_tensor_overload = {
+    "_foreach_add.Tensor",
+    "_foreach_mul.Tensor",
+    "_foreach_div.Tensor",
+}
+# The following do not support the alpha kwarg, which the nonforeach versions support.
+_skip_argument_len_check = {
+    "_foreach_add.Scalar",
+    "_foreach_add_.Scalar",
+    "_foreach_add.ScalarList",
+    "_foreach_add_.ScalarList",
+    "_foreach_sub.Scalar",
+    "_foreach_sub_.Scalar",
+    "_foreach_sub.ScalarList",
+    "_foreach_sub_.ScalarList",
+}
+
+
+# Checks if `function_schema` is a native, non-foreach function which `f`, a foreach function
+# reference to generate derivatives.
+def is_reference_for_foreach(
+    f: NativeFunction,
+    function_schema: FunctionSchema,
+) -> bool:
+    return (
+        f.func.name.name.base.split("_foreach_")[-1] == function_schema.name.name.base
+        and (
+            not function_schema.name.name.inplace
+            or str(f.func.name) in _foreach_with_inplace_ref
+        )
+        and (
+            str(f.func.name) in _skip_argument_len_check
+            or len(f.func.arguments.flat_non_out)
+            == len(function_schema.arguments.flat_non_out)
+        )
+        and all(
+            ref_arg.type in (arg.type, getattr(arg.type, "elem", None))
+            for arg, ref_arg in zip(
+                f.func.arguments.flat_non_out,
+                function_schema.arguments.flat_non_out,
+            )
+        )
+    )
+
+
+# TODO(crcrpar): Avoid hard coding "Default" ideally.
+def gen_foreach_derivativeinfo(
+    foreach_function: NativeFunction,
+    functional_info_by_signature: dict[
+        FunctionSchema, dict[str, DifferentiabilityInfo]
+    ],
+    non_functional_info_by_signature: dict[
+        FunctionSchema, dict[str, DifferentiabilityInfo]
+    ],
+    dispatch_key: str = "Default",
+) -> tuple[DifferentiabilityInfo | None, bool]:
+    """Generate DifferentiabilityInfo for out-place foreach function, return the existing one for in-place.
+
+    The second return value indicates whether the info is generated in this function.
+    """
+    ref_diff_info: DifferentiabilityInfo | None = None
+
+    for function_schema, diff_info in functional_info_by_signature.items():
+        if not is_reference_for_foreach(foreach_function, function_schema):
+            continue
+        ref_diff_info = diff_info[dispatch_key]
+        if ref_diff_info is not None:
+            break
+    # note(crcrpar): It seems like `zero`'s info isn't available in functional_info_by_signature
+    # while the info of `zero_` is in non_functional_info_by_signature
+    if (
+        ref_diff_info is None
+        and foreach_function.func.kind() == SchemaKind.inplace
+        and str(foreach_function.func.name) in _foreach_with_inplace_ref
+    ):
+        for function_schema, diff_info in non_functional_info_by_signature.items():
+            if not is_reference_for_foreach(foreach_function, function_schema):
+                continue
+            ref_diff_info = diff_info[dispatch_key]
+            if ref_diff_info is not None:
+                break
+    if ref_diff_info is None:
+        return None, False
+
+    # non out-place uses the existing Derivative.
+    if foreach_function.func.kind() == SchemaKind.inplace:
+        return ref_diff_info, False
+
+    map_refarg2foreacharg, map_name2arg = {}, {}
+    for i, (arg, ref_arg) in enumerate(
+        zip(
+            foreach_function.func.arguments.flat_non_out,
+            function_schema.arguments.flat_non_out,
+        )
+    ):
+        map_refarg2foreacharg[ref_arg.name] = arg.name
+        map_name2arg[arg.name] = arg
+
+    all_saved_inputs, all_saved_outputs, all_var_names = [], [], []
+    modified_derivative_formulas = []
+    for i, derivative in enumerate(ref_diff_info.derivatives):
+        modified_formula = derivative.formula.replace("grad", "grads[i]").replace(
+            "result", "result[i]"
+        )
+        saved_inputs, saved_outputs = [], []
+        # note(crcrpar): This context seems necessary to call `cpp.argument_type`
+        with local.parametrize(
+            use_const_ref_for_mutable_tensors=foreach_function.use_const_ref_for_mutable_tensors,
+            use_ilistref_for_tensor_lists=foreach_function.part_of_structured_group,
+        ):
+            for ref_input in derivative.saved_inputs:
+                ref_input_jit_name = ref_input.expr.split(".")[0]
+                mapped_name = map_refarg2foreacharg[ref_input_jit_name]
+                if isinstance(map_name2arg[mapped_name].type, ListType):
+                    mapped_expr = mapped_name + "[i]"
+                else:
+                    mapped_expr = mapped_name
+                new_expr = ref_input.expr.replace(ref_input_jit_name, mapped_expr)
+                modified_formula = modified_formula.replace(
+                    cast(str, ref_input.nctype.name), new_expr
+                )
+
+                nctype = cpp.argument_type(map_name2arg[mapped_name], binds=mapped_name)
+                canonical_nctype = NamedCType(
+                    nctype.name, nctype.type.remove_const_ref()
+                )
+                saved_inputs.append(
+                    SavedAttribute(nctype=canonical_nctype, expr=mapped_name)
+                )
+            for ref_output in derivative.saved_outputs:
+                if ref_output.nctype.name == "result":
+                    saved_outputs.append(
+                        SavedAttribute(
+                            nctype=NamedCType(
+                                name="result", type=BaseCType(tensorListT)
+                            ),
+                            expr="result",
+                        )
+                    )
+                else:
+                    raise RuntimeError("")
+        var_names = [map_refarg2foreacharg[var] for var in derivative.var_names]
+        all_var_names.extend(var_names)
+        all_saved_inputs.extend(saved_inputs)
+        all_saved_outputs.extend(saved_outputs)
+        modified_derivative = Derivative(
+            formula=modified_formula,
+            original_formula=derivative.formula,
+            var_names=tuple(var_names),
+            saved_inputs=tuple(saved_inputs),
+            saved_outputs=tuple(saved_outputs),
+            named_gradients=set(),
+        )
+        modified_derivative_formulas.append(modified_derivative)
+
+    with local.parametrize(
+        use_const_ref_for_mutable_tensors=foreach_function.use_const_ref_for_mutable_tensors,
+        use_ilistref_for_tensor_lists=foreach_function.part_of_structured_group,
+    ):
+        args_with_derivatives = [
+            Binding(
+                name=arg.name,
+                nctype=cpp.argument_type(arg, binds=arg.name),
+                argument=arg,
+                default=None,
+            )
+            for arg in foreach_function.func.arguments.flat_non_out
+            if arg.name in all_var_names
+        ]
+
+    forward_derivatives: list[ForwardDerivative] = []
+    fw_derivative: ForwardDerivative
+    for fw_derivative in ref_diff_info.forward_derivatives:
+        var_names: list[str] = list(fw_derivative.var_names)  # type: ignore[no-redef]
+        var_types: list[Type] = list(fw_derivative.var_types)
+        required_inputs_fw_grad: list[str] = []
+        required_inputs_primal: list[str] = []
+        if fw_derivative.required_inputs_fw_grad is not None:
+            required_inputs_fw_grad = list(fw_derivative.required_inputs_fw_grad)
+        if fw_derivative.required_inputs_primal:
+            required_inputs_primal = list(fw_derivative.required_inputs_primal)
+        modified_formula = fw_derivative.formula
+
+        # Foreach's result is TensorList
+        if "result" in modified_formula:
+            modified_formula = fw_derivative.formula.replace("result", "result[i]")
+
+        for foreach_arg, ref_arg in zip(
+            foreach_function.func.arguments.flat_non_out,
+            ref_diff_info.func.func.arguments.flat_non_out,
+        ):
+            # Modify reference forward formula
+            if (
+                isinstance(foreach_arg.type, ListType)
+                and not foreach_arg.type.is_tensor_like()
+            ):
+                # Assuming ScalarList
+                modified_formula = modified_formula.replace(
+                    ref_arg.name, foreach_arg.name + "[i]"
+                )
+            elif foreach_arg.type.is_tensor_like():
+                # Assuming TensorList / Tensor
+                # assert isinstance(foreach_arg.type, ListType), f"{foreach_function.func.name}, {foreach_arg.type}"
+                assert isinstance(foreach_arg.type, ListType) or (
+                    foreach_arg.type == BaseType(BaseTy.Tensor)
+                    and str(foreach_function.func.name) in _foreach_with_tensor_overload
+                ), f"{foreach_function.func.name}, {foreach_arg.type}"
+                for suffix in ("_p", "_t"):
+                    curr_expr = ref_arg.name + suffix
+                    if curr_expr in modified_formula:
+                        new_expr = foreach_arg.name + suffix
+                        modified_formula = modified_formula.replace(curr_expr, new_expr)
+            else:
+                # Assuming Scalar
+                if foreach_arg.name != ref_arg.name:
+                    modified_formula = modified_formula.replace(
+                        ref_arg.name, foreach_arg.name
+                    )
+
+            # note(crcrpar): there should exist a cooler way...
+            for i, name in enumerate(var_names):
+                if name == ref_arg.name:
+                    var_names[i] = foreach_arg.name
+                    var_types[i] = foreach_arg.type
+            for i, name in enumerate(required_inputs_fw_grad):
+                if name == ref_arg.name:
+                    required_inputs_fw_grad[i] = foreach_arg.name
+            for i, name in enumerate(required_inputs_primal):
+                if name == ref_arg.name:
+                    required_inputs_primal[i] = foreach_arg.name
+        forward_derivatives.append(
+            ForwardDerivative(
+                formula=modified_formula,
+                var_names=tuple(var_names),
+                var_types=tuple(var_types),
+                required_inputs_fw_grad=tuple(required_inputs_fw_grad),
+                required_inputs_primal=tuple(required_inputs_primal),
+                required_original_self_value=fw_derivative.required_original_self_value,
+                is_reusing_outplace_formula=fw_derivative.is_reusing_outplace_formula,
+            )
+        )
+
+    return (
+        DifferentiabilityInfo(
+            name=foreach_function.func.name.name.base,
+            func=foreach_function,
+            op=f"Foreach{ref_diff_info.op}{foreach_function.func.name.overload_name}",
+            derivatives=modified_derivative_formulas,
+            forward_derivatives=forward_derivatives,
+            all_saved_inputs=tuple(set(all_saved_inputs)),
+            all_saved_outputs=tuple(set(all_saved_outputs)),
+            available_named_gradients=(),
+            used_named_gradients=set(),
+            args_with_derivatives=args_with_derivatives,
+            non_differentiable_arg_names=[],
+            output_differentiability=None,
+            output_differentiability_conditions=None,
+        ),
+        True,
+    )
+
+
+def match_differentiability_info(
+    native_functions: list[NativeFunction],
+    differentiability_infos: dict[FunctionSchema, dict[str, DifferentiabilityInfo]],
+) -> list[NativeFunctionWithDifferentiabilityInfo]:
+    """Sets the "derivative" key on declarations to matching autograd function
+    In-place functions will use the out-of-place derivative definition if there
+    is no in-place specific derivative.
+    """
+
+    functional_info_by_signature = {
+        schema.signature(strip_default=True): info_dict
+        for schema, info_dict in differentiability_infos.items()
+        if schema.kind() == SchemaKind.functional
+    }
+    non_functional_info_by_signature = {
+        schema.signature(strip_default=True): info_dict
+        for schema, info_dict in differentiability_infos.items()
+        if schema.kind() != SchemaKind.functional
+    }
+
+    def find_info(
+        f: NativeFunction,
+    ) -> tuple[dict[str, DifferentiabilityInfo] | None, bool]:
+        # Don't bother matching info to generated out= variants
+        if "generated" in f.tags and f.func.kind() == SchemaKind.out:
+            return None, False
+
+        # (1) Check for an exact match
+        if f.func in differentiability_infos:
+            return differentiability_infos[f.func], True
+
+        # (2) If no exact match, check if the out-of-place variant
+        # of this operator has a match.
+        # i.e mul() for mul_() or mul_out()
+        # note(crcrpar): Check foreach or not because in-place foreach functions use backward defined for the existing
+        # native functions instead of the out-place counterparts.
+        f_sig = f.func.signature(strip_default=True)
+        if f_sig in functional_info_by_signature and not is_foreach_func(f):
+            return functional_info_by_signature[f_sig], False
+
+        # (3) Some operators have a derivative explicitly defined for the mutable
+        # variant, but get a code-generated out-of-place variant which does *not*
+        # come with a derivative formula.
+        # For the generated out-of-place variant, use the mutable variant's formula
+        # if it exists.
+        if "generated" in f.tags and f_sig in non_functional_info_by_signature:
+            info_dict = non_functional_info_by_signature[f_sig]
+            # See https://github.com/pytorch/pytorch/pull/76320/files#r874816389
+            assert not any(
+                any("self" in str(input.nctype.name) for input in info.all_saved_inputs)
+                for info in info_dict.values()
+            ), f"""\
+Attempted to convert a derivative formula for a mutable operator
+ to be used by automatically by its functional variant ("{str(f.func)}").
+ this is not currently supported (we'd need to fix up the formula in the codegen)."""
+            return info_dict, False
+
+        # (4) Generate derivative information of foreach functions if none is defined in `derivatives.yaml`
+        if is_foreach_func(f):
+            assert f.func not in differentiability_infos
+            diff_info, is_generated = gen_foreach_derivativeinfo(
+                f,
+                functional_info_by_signature,
+                non_functional_info_by_signature,
+            )
+            if diff_info is None:
+                return None, False
+            # TODO(crcrpar): Avoid hard coding "Default" ideally.
+            diff_info_dict = {"Default": diff_info}
+            if is_generated:
+                differentiability_infos[f.func] = diff_info_dict
+                functional_info_by_signature[f.func] = diff_info_dict
+            return diff_info_dict, is_generated
+
+        return None, False
+
+    result: list[NativeFunctionWithDifferentiabilityInfo] = []
+    for f in native_functions:
+        info_dict, is_exact_match = find_info(f)
+
+        # Currently, the '.strides()' to 'strides_or_error' replacement does not support
+        # 'self' derivatives of an inplace function, so we must check for this case.
+        if f.func.kind() == SchemaKind.inplace and (info_dict is not None):
+            for info in info_dict.values():
+                for derivative in info.derivatives:
+                    if "self" in derivative.var_names:
+                        for saved_input in derivative.saved_inputs:
+                            assert "strides_or_error" not in saved_input.expr, (
+                                "Calling '.strides()' in the 'self' derivative formula of an "
+                                f"in-place function is not supported: {f.func}"
+                            )
+
+        if not info_dict:
+            result.append(
+                NativeFunctionWithDifferentiabilityInfo(
+                    func=f, info=None, fw_derivatives=None
+                )
+            )
+            continue
+
+        fw_derivative_dict: dict[str, Sequence[ForwardDerivative]] = {}
+        for key, info in info_dict.items():
+            if not info.forward_derivatives:
+                fw_derivative_dict[key] = []
+                continue
+
+            forward_derivatives = info.forward_derivatives
+
+            # For functions that have a single def for out-of-place and inplace (like abs())
+            if f.func.kind() == SchemaKind.inplace:
+                # For inplace functions there is a little bit of work to do:
+                #  1) Validate the formula and make sure the input that is modified in not used:
+                #    - If there is a formula for the inplace variant of the function (is_exact_match == True) then
+                #      we make sure that the original value of the input that is being modified inplace (self_p) is
+                #      not used in the formula. Note that the formula can use "original_self_p" here and that would
+                #      trigger a clone of the original input.
+                #    - If we are reusing the out of place formula (is_exact_match == False) then we replace every
+                #      occurrence of self_p and self_t by original_self_p and original_self_t. These will be
+                #      populated by cloned version of the original input (either the clone done by the backward AD
+                #      logic if self is also used in a backward formula or a special clone that we add).
+                #  2) At this point, there cannot be a self_p in the formula.
+                #  3) Change "result" into "self_p" as by design, in the inplace function codegen, the result is
+                #     simply called self (as it is modified inplace).
+                #  4) Update the required primals data in case it used to contain "result" but should now contain
+                #     "self"
+                #  5) If it is not an exact match, the user formula is not modifying the existing forward grad
+                #     inplace as it should. So add some code that makes sure that we do so if the forward grad
+                #     already exists.
+
+                assert (
+                    len(info.forward_derivatives) == 1
+                )  # Only single output inplace should exist
+                fw_info = info.forward_derivatives[0]
+                formula = fw_info.formula
+
+                def replace_self_with_original_self(formula: str, postfix: str) -> str:
+                    def repl(m: re.Match[str]) -> str:
+                        return f"{m.group(1)}original_self{postfix}{m.group(2)}"
+
+                    return re.sub(IDENT_REGEX.format(f"self{postfix}"), repl, formula)
+
+                if re.search(IDENT_REGEX.format("self_p"), formula):
+                    if is_exact_match:
+                        # For manually defined formulas, don't allow the original value to be used
+                        raise RuntimeError(
+                            f'The formula for "{f.func.name}" is using the original value of self '
+                            "that is being modified inplace. This would lead to wrong forward gradients. "
+                            'Please use "result" in the formula only.'
+                        )
+                    else:
+                        # When the original formula is out of place, we save a clone of the primal
+                        # value to be able to access this value if needed
+                        # replace "self_p"/"self_t" from the formula by "original_self_p"/"original_self_t"
+                        formula = replace_self_with_original_self(formula, "_p")
+                        formula = replace_self_with_original_self(formula, "_t")
+
+                # replace "result" from the formula by "self_p"
+                def repl(m: re.Match[str]) -> str:
+                    return f"{m.group(1)}self_p{m.group(2)}"
+
+                formula = re.sub(IDENT_REGEX.format("result"), repl, formula)
+
+                required_primals = fw_info.required_inputs_primal
+                if re.search(IDENT_REGEX.format("self_p"), formula):
+                    required_primals = (
+                        required_primals + ("self",) if required_primals else ("self",)
+                    )
+
+                if not is_exact_match:
+                    # NOTE [In-place forward AD formula Optimization]
+                    #
+                    # This optimization transforms the formula to directly do inplace, i.e.
+                    # instead of self_t.copy_(self_t.op()) we do self_t.op_() when the following are met:
+                    #
+                    # 1) the formula satisfies the pattern: "self_t.op(*args)"
+                    # 2) "op" in (1) needs to be the same as the op the derivative is for
+                    #
+                    # (2) may seem too strict, but currently the only ops that satisfy (1) also satisfy (2)
+                    # If there is a need, we can relax (2) to allow any op that has an in-place variant
+                    is_single_method_on_self_t = False
+                    directly_do_inplace = False
+                    op_name: str | None = None
+                    between_parens: str | None = None
+                    match = re.fullmatch(r"self_t.([\w]*)\((.*)\)", formula)
+                    if match:
+                        op_name, between_parens = match.group(1), match.group(2)
+
+                        # We want to...
+                        #   Match: self_t.op1(other_p.op2(arg))
+                        #   Avoid: self_t.op1(args) + self_t.op2(args)
+                        #   Avoid: self_t.op1(other_p.op2(arg)) + self_t.op2(args)
+                        def check_parens_nest_level_gt_zero(s: str) -> bool:
+                            level = 1
+                            for ch in s:
+                                if ch == ")":
+                                    level -= 1
+                                    if level == 0:
+                                        return False
+                                if ch == "(":
+                                    level += 1
+                            return True
+
+                        is_single_method_on_self_t = check_parens_nest_level_gt_zero(
+                            between_parens
+                        )
+                        directly_do_inplace = (
+                            is_single_method_on_self_t and op_name == info.name
+                        )
+
+                    if directly_do_inplace:
+                        assert op_name is not None
+                        assert between_parens is not None
+                        formula = f"self_t_raw.defined() ? self_t_raw.{op_name}_({between_parens}) : {formula}"
+                    else:
+                        # Make sure that the forward grad is modified inplace when the original formula
+                        # is out of place
+                        formula = f"self_t_raw.defined() ? self_t_raw.copy_({formula}) : {formula}"
+
+                required_original_self_value = bool(
+                    re.search(IDENT_REGEX.format("original_self_p"), formula)
+                ) or bool(re.search(IDENT_REGEX.format("original_self_t"), formula))
+
+                forward_derivatives = [
+                    ForwardDerivative(
+                        formula=formula,
+                        var_names=("self",),
+                        var_types=fw_info.var_types,
+                        required_inputs_fw_grad=fw_info.required_inputs_fw_grad,
+                        required_inputs_primal=required_primals,
+                        required_original_self_value=required_original_self_value,
+                        is_reusing_outplace_formula=not is_exact_match,
+                    ),
+                ]
+
+            fw_derivative_dict[key] = forward_derivatives
+
+        result.append(
+            NativeFunctionWithDifferentiabilityInfo(
+                func=f, info=info_dict, fw_derivatives=fw_derivative_dict
+            )
+        )
+
+    return result
+
+
+def is_differentiable(
+    name: str, type: Type, info: DifferentiabilityInfo | None
+) -> bool:
+    return type.is_tensor_like() and (
+        info is None or name not in info.non_differentiable_arg_names
+    )
+
+
+def gen_differentiable_outputs(
+    fn: NativeFunctionWithDifferentiabilityInfo, key: str = "Default"
+) -> list[DifferentiableOutput]:
+    f = fn.func
+    info = fn.info[key] if fn.info else None
+    outputs: list[DifferentiableOutput] = [
+        DifferentiableOutput(
+            name=name,
+            type=ret.type,
+            cpp_type=cpp.return_type(ret, symint=True).cpp_type(),
+        )
+        for name, ret in zip(cpp.return_names(f), f.func.returns)
+    ]
+    output_differentiability = info.output_differentiability if info else None
+    if output_differentiability is not None:
+        if len(output_differentiability) != len(outputs):
+            raise RuntimeError(
+                f"The length of output_differentiability ({len(output_differentiability)}), "
+                f"does not match the number of outputs ({len(outputs)})."
+            )
+        differentiable_outputs: list[DifferentiableOutput] = []
+        if False in output_differentiability and f.func.kind() == SchemaKind.inplace:
+            raise RuntimeError(
+                "output_differentiability=False for inplace operation (version_counter won't get updated)"
+            )
+        for differentiable, output in zip(output_differentiability, outputs):
+            if differentiable:
+                differentiable_outputs.append(output)
+        return differentiable_outputs
+    candidate_differentiable_outputs = list(
+        filter(lambda r: is_differentiable(r.name, r.type, info), outputs)
+    )
+    if uses_single_grad(info):
+        return candidate_differentiable_outputs[:1]
+    else:
+        return candidate_differentiable_outputs
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/cpp.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/cpp.py
new file mode 100644
index 0000000000000000000000000000000000000000..862cef30dba49f4341a3c980845fdb7a2c1cbcd5
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/cpp.py
@@ -0,0 +1,469 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+from typing_extensions import assert_never
+
+from torchgen import local
+from torchgen.api.types import (
+    ArgName,
+    ArrayCType,
+    ArrayRefCType,
+    BaseCType,
+    BaseTypeToCppMapping,
+    Binding,
+    boolT,
+    ConstRefCType,
+    CType,
+    dimnameListT,
+    intArrayRefT,
+    iTensorListRefT,
+    ListCType,
+    longT,
+    MutRefCType,
+    NamedCType,
+    OptionalCType,
+    optionalIntArrayRefT,
+    optionalSymIntArrayRefT,
+    scalarT,
+    SpecialArgName,
+    symIntArrayRefT,
+    SymIntT,
+    tensorListT,
+    tensorOptionsT,
+    tensorT,
+    TupleCType,
+    VectorCType,
+    voidT,
+)
+from torchgen.model import (
+    Argument,
+    Arguments,
+    BaseTy,
+    BaseType,
+    FunctionSchema,
+    ListType,
+    NativeFunction,
+    OptionalType,
+    Return,
+    SelfArgument,
+    TensorOptionsArguments,
+    Type,
+)
+
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+
+
+# This file describes the translation of JIT schema to the public C++
+# API, which is what people use when they call functions like at::add.
+#
+# Prominent characteristics of the C++ API:
+#
+#   - dtype, layout, device and pin_memory are collected into
+#     a single C++ type TensorOptions  (the native functions API
+#     also has this, but tensor options is really most relevant
+#     for the C++ API; it makes calling kwarg factory functions
+#     pleasant)
+#
+#   - defaulting lives here (in fact, the dispatcher is completely
+#     oblivious of defaults!)
+#
+# BTW: policy on name collisions: we try not to have types with
+# collisions, but functions are fair game to collide
+
+
+def name(
+    func: FunctionSchema,
+    *,
+    faithful_name_for_out_overloads: bool = False,
+    symint_overload: bool = False,
+) -> str:
+    name = str(func.name.name)
+    if symint_overload:
+        name += "_symint"
+    if func.is_out_fn():
+        if faithful_name_for_out_overloads:
+            name += "_outf"
+        else:
+            name += "_out"
+
+    return name
+
+
+# Translation of "value types" in JIT schema to C++ API type.  Value
+# types look the same no matter if they are argument types or return
+# types.  Returns None if the type in question is not a value type.
+def valuetype_type(
+    t: Type,
+    *,
+    binds: ArgName,
+    mutable: bool = True,
+    symint: bool = False,
+) -> NamedCType | None:
+    if isinstance(t, BaseType):
+        if t.name in (BaseTy.Tensor, BaseTy.Scalar):
+            return None
+        elif str(t) == "SymInt":
+            if symint:
+                return NamedCType(binds, BaseCType(SymIntT))
+            else:
+                return NamedCType(binds, BaseCType(longT))
+        # All other BaseType currently map directly to BaseCppTypes.
+        return NamedCType(binds, BaseCType(BaseTypeToCppMapping[t.name]))
+    elif isinstance(t, OptionalType):
+        elem = valuetype_type(t.elem, binds=binds, mutable=mutable, symint=symint)
+        if elem is None:
+            return None
+        return NamedCType(binds, OptionalCType(elem.type))
+    elif isinstance(t, ListType):
+        if str(t.elem) == "bool":
+            assert t.size is not None
+            return NamedCType(binds, ArrayCType(BaseCType(boolT), t.size))
+        else:
+            return None
+    else:
+        raise AssertionError(f"unrecognized type {repr(t)}")
+
+
+# Translation of types occurring in JIT arguments to a C++ argument type.
+# If remove_non_owning_ref_types is set, we'll guarantee that the output CType is not a non-owning reference type.
+# For example, we'll return std::vector instead of IntArrayRef.
+# See Note [translation from C++ reference to value types]
+def argumenttype_type(
+    t: Type,
+    *,
+    mutable: bool,
+    binds: ArgName,
+    remove_non_owning_ref_types: bool = False,
+    symint: bool = False,
+) -> NamedCType:
+    # If it's a value type, do the value type translation
+    r = valuetype_type(
+        t,
+        binds=binds,
+        mutable=mutable,
+        symint=symint,
+    )
+    if r is not None:
+        return r
+
+    if isinstance(t, BaseType):
+        if t.name == BaseTy.Tensor:
+            if mutable and not local.use_const_ref_for_mutable_tensors():
+                return NamedCType(binds, MutRefCType(BaseCType(tensorT)))
+            else:
+                return NamedCType(binds, ConstRefCType(BaseCType(tensorT)))
+        elif t.name == BaseTy.Scalar:
+            return NamedCType(binds, ConstRefCType(BaseCType(scalarT)))
+        else:
+            raise AssertionError(f"base type should have been value type {t}")
+    elif isinstance(t, OptionalType):
+        if str(t.elem) == "Tensor":
+            if mutable and not local.use_const_ref_for_mutable_tensors():
+                return NamedCType(
+                    binds, MutRefCType(BaseCType(tensorT))
+                )  # TODO: fix this discrepancy
+            else:
+                return NamedCType(
+                    binds, ConstRefCType(OptionalCType(BaseCType(tensorT)))
+                )
+        elif str(t.elem) == "Scalar":
+            return NamedCType(binds, ConstRefCType(OptionalCType(BaseCType(scalarT))))
+        elif isinstance(t.elem, ListType) and str(t.elem.elem) == "int":
+            return NamedCType(binds, BaseCType(optionalIntArrayRefT))
+        elif isinstance(t.elem, ListType) and str(t.elem.elem) == "SymInt":
+            if symint:
+                return NamedCType(binds, BaseCType(optionalSymIntArrayRefT))
+            else:
+                return NamedCType(binds, BaseCType(optionalIntArrayRefT))
+        elem = argumenttype_type(t.elem, mutable=mutable, binds=binds, symint=symint)
+        return NamedCType(binds, OptionalCType(elem.type))
+    elif isinstance(t, ListType):
+        # TODO: remove these special cases, ArrayRef fallthrough works fine
+        if str(t.elem) == "int":
+            if remove_non_owning_ref_types:
+                return NamedCType(binds, VectorCType(BaseCType(longT)))
+            else:
+                return NamedCType(binds, BaseCType(intArrayRefT))
+        if str(t.elem) == "SymInt":
+            if remove_non_owning_ref_types:
+                if symint:
+                    return NamedCType(binds, VectorCType(BaseCType(SymIntT)))
+                else:
+                    return NamedCType(binds, VectorCType(BaseCType(longT)))
+            else:
+                if symint:
+                    return NamedCType(binds, BaseCType(symIntArrayRefT))
+                else:
+                    return NamedCType(binds, BaseCType(intArrayRefT))
+        if str(t.elem) == "Tensor":
+            if local.use_ilistref_for_tensor_lists():
+                return NamedCType(binds, ConstRefCType(BaseCType(iTensorListRefT)))
+            else:
+                return NamedCType(binds, BaseCType(tensorListT))
+        elif str(t.elem) == "Scalar":
+            return NamedCType(binds, ArrayRefCType(BaseCType(scalarT)))
+        elif str(t.elem) == "Dimname":
+            return NamedCType(binds, BaseCType(dimnameListT))
+        elif str(t.elem) == "Tensor?":
+            return NamedCType(
+                binds, ConstRefCType(ListCType(OptionalCType(BaseCType(tensorT))))
+            )
+        elem = argumenttype_type(t.elem, mutable=mutable, binds=binds, symint=symint)
+        return NamedCType(binds, ArrayRefCType(elem.type))
+    else:
+        raise AssertionError(f"unrecognized type {repr(t)}")
+
+
+# Translate a JIT argument into its C++ type
+def argument_type(a: Argument, *, binds: ArgName, symint: bool = False) -> NamedCType:
+    return argumenttype_type(a.type, mutable=a.is_write, symint=symint, binds=binds)
+
+
+# Translation of a (non-multi) return type from JIT to C++
+# N.B: returntype_type returns a CType, not a NamedCType.
+# This is mostly because of the mismatch between return types and return names.
+# e.g. a function with a return type of 'void' has 0 return names,
+# and a function with a return type of 'std::tuple' has >1 return name.
+def returntype_type(t: Type, *, mutable: bool, symint: bool = False) -> CType:
+    # placeholder is ignored
+    # NB: symint is ALWAYS respected for return types.  So symint argument
+    # here is IGNORED
+    r = valuetype_type(t, binds="__placeholder__", mutable=mutable, symint=True)
+    if r is not None:
+        return r.type
+
+    if isinstance(t, BaseType):
+        if t.name == BaseTy.Tensor:
+            if mutable:
+                if local.use_const_ref_for_mutable_tensors():
+                    return ConstRefCType(BaseCType(tensorT))
+                else:
+                    return MutRefCType(BaseCType(tensorT))
+            else:
+                # Note [Tensor Copy Returns]
+                # Currently, we use "Argument.is_write" to determine
+                # whether or not Tensor return types should be copies or references.
+                # If that ever changes, take a look at other locations of this note!
+                return BaseCType(tensorT)
+        elif t.name == BaseTy.Scalar:
+            return BaseCType(scalarT)
+    elif isinstance(t, ListType):
+        assert not mutable, (
+            "Native functions should never return a mutable tensor list. They should return void."
+        )
+        elem = returntype_type(t.elem, mutable=False)
+        assert t.size is None, f"fixed size list returns not supported: {t}"
+        return VectorCType(elem)
+    elif isinstance(t, OptionalType):
+        elem = returntype_type(t.elem, mutable=mutable)
+        if str(t.elem) == "Tensor":
+            return OptionalCType(elem)
+
+    raise AssertionError(f"unrecognized return type {t}")
+
+
+# Translation of a single return to its C++ type
+def return_type(r: Return, *, symint: bool = False) -> CType:
+    return returntype_type(r.type, mutable=r.is_write, symint=symint)
+
+
+# Translation of a full (possibly multi) return from JIT to its C++ type
+def returns_type(rs: Sequence[Return], *, symint: bool = False) -> CType:
+    if len(rs) == 0:
+        return BaseCType(voidT)
+    elif len(rs) == 1:
+        return return_type(rs[0], symint=symint)
+    else:
+        return TupleCType([return_type(r, symint=symint) for r in rs])
+
+
+def return_names(f: NativeFunction, *, fallback_name: str = "result") -> Sequence[str]:
+    returns: list[str] = []
+    for i, r in enumerate(f.func.returns):
+        # If we have an inplace function, the return argument is
+        # implicitly named self.
+        # TODO: Consider incorporating this into the data model
+        if f.func.name.name.inplace:
+            assert i == 0, "illegal inplace function with multiple returns"
+            name = "self"
+        # If we are out function, the name is the name of the
+        # corresponding output function (r.name will get recorded
+        # in field_name later.)
+        elif f.func.is_out_fn():
+            name = f.func.arguments.out[i].name
+        # If the return argument is explicitly named...
+        elif r.name:
+            name_conflict = any(
+                r.name == a.name for a in f.func.schema_order_arguments()
+            )
+            if name_conflict and not f.func.is_out_fn():
+                name = f"{r.name}_return"
+            else:
+                name = r.name
+        # If there is no explicit name and no fallback name was passed in, we just name the output result,
+        # unless it's a multi-return, in which case it's result0,
+        # result1, etc (zero-indexed)
+        else:
+            name = fallback_name if len(f.func.returns) == 1 else f"{fallback_name}{i}"
+        returns.append(name)
+    return returns
+
+
+JIT_TO_CPP_DEFAULT = {
+    "False": "false",
+    "True": "true",
+    "None": "::std::nullopt",  # UGH this one is type directed
+    "Mean": "at::Reduction::Mean",
+    "[]": "{}",
+    "contiguous_format": "c10::MemoryFormat::Contiguous",
+    "long": "at::kLong",
+}
+
+
+# Convert a JIT default into C++ expression representing the default
+def default_expr(d: str, t: Type, *, symint: bool) -> str:
+    if d == "None" and str(t) == "Tensor?":
+        return "{}"
+    if isinstance(t, BaseType) and t.name is BaseTy.str:
+        # Schema allows single quotes but C++ needs double
+        if len(d) >= 2 and d[0] == "'" and d[-1] == "'":
+            s = ""
+            i = 1
+            while i + 1 < len(d):
+                if d[i] != "\\":
+                    if d[i] == '"':
+                        s += '\\"'
+                    else:
+                        s += d[i]
+                    i += 1
+                else:
+                    if d[i + 1] == "'":
+                        s += "'"
+                    else:
+                        s += d[i : i + 2]
+                    i += 2
+
+            return f'"{s}"'
+
+    if isinstance(t, OptionalType):
+        if d == "None":
+            return "::std::nullopt"
+
+        return default_expr(d, t.elem, symint=symint)
+
+    if isinstance(t, ListType):
+        if d.startswith("[") and d.endswith("]"):
+            return "{" + d[1:-1] + "}"
+        elif symint and d.isdigit() and str(t.elem) == "SymInt":
+            return f"c10::SymInt({d})"
+        elif t.size is None:
+            # NOTE: Sized lists can have scalar defaults
+            raise ValueError(f"Expected a list default '[...]' but found: '{d}'")
+
+    return JIT_TO_CPP_DEFAULT.get(d, d)
+
+
+# Convert an argument into its C++ API form
+
+
+def argument(
+    a: Argument | TensorOptionsArguments | SelfArgument,
+    *,
+    cpp_no_default_args: set[str],
+    method: bool,
+    faithful: bool,
+    symint: bool = False,
+    has_tensor_options: bool,
+) -> list[Binding]:
+    def sub_argument(
+        a: Argument | TensorOptionsArguments | SelfArgument,
+    ) -> list[Binding]:
+        return argument(
+            a,
+            cpp_no_default_args=cpp_no_default_args,
+            method=method,
+            faithful=faithful,
+            symint=symint,
+            has_tensor_options=has_tensor_options,
+        )
+
+    if isinstance(a, Argument):
+        binds: ArgName
+        if a.name == "memory_format" and has_tensor_options:
+            binds = SpecialArgName.possibly_redundant_memory_format
+        else:
+            binds = a.name
+        default: str | None = None
+        if a.name not in cpp_no_default_args and a.default is not None:
+            default = default_expr(a.default, a.type, symint=symint)
+        return [
+            Binding(
+                nctype=argument_type(a, binds=binds, symint=symint),
+                name=a.name,
+                default=default,
+                argument=a,
+            )
+        ]
+    elif isinstance(a, TensorOptionsArguments):
+        if faithful:
+            return (
+                sub_argument(a.dtype)
+                + sub_argument(a.layout)
+                + sub_argument(a.device)
+                + sub_argument(a.pin_memory)
+            )
+        else:
+            default = None
+            # Enforced by NativeFunction.__post_init__
+            assert "options" not in cpp_no_default_args
+            if all(x.default == "None" for x in a.all()):
+                default = "{}"
+            elif a.dtype.default == "long":
+                default = "at::kLong"  # TODO: this is wrong
+            return [
+                Binding(
+                    nctype=NamedCType("options", BaseCType(tensorOptionsT)),
+                    name="options",
+                    default=default,
+                    argument=a,
+                )
+            ]
+    elif isinstance(a, SelfArgument):
+        if method:
+            # Caller is responsible for installing implicit this in context!
+            return []
+        else:
+            return sub_argument(a.argument)
+    else:
+        assert_never(a)
+
+
+def arguments(
+    arguments: Arguments,
+    *,
+    faithful: bool,
+    symint: bool = False,
+    method: bool,
+    cpp_no_default_args: set[str],
+) -> list[Binding]:
+    args: list[Argument | TensorOptionsArguments | SelfArgument] = []
+    if faithful:
+        args.extend(arguments.non_out)
+        args.extend(arguments.out)
+    else:
+        args.extend(arguments.out)
+        args.extend(arguments.non_out)
+    return [
+        r.no_default() if faithful else r
+        for a in args
+        for r in argument(
+            a,
+            faithful=faithful,
+            symint=symint,
+            method=method,
+            has_tensor_options=arguments.tensor_options is not None,
+            cpp_no_default_args=cpp_no_default_args,
+        )
+    ]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/dispatcher.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/dispatcher.py
new file mode 100644
index 0000000000000000000000000000000000000000..fcca7a60fec1829c5783197055733467fcdd63fe
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/dispatcher.py
@@ -0,0 +1,125 @@
+from __future__ import annotations
+
+import itertools
+from typing import TYPE_CHECKING
+from typing_extensions import assert_never
+
+from torchgen.api import cpp
+from torchgen.api.types import ArgName, Binding, CType, NamedCType
+from torchgen.model import (
+    Argument,
+    FunctionSchema,
+    Return,
+    SelfArgument,
+    TensorOptionsArguments,
+    Type,
+)
+from torchgen.utils import concatMap
+
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+
+
+# This file describes the translation of JIT schema to the dispatcher
+# API, the *unboxed* calling convention by which invocations through
+# the dispatcher are made.  Historically, the dispatcher API matched
+# the C++ API, but with the establishment of the boxed API, we've
+# made changes to the dispatcher API to so that the unboxed API
+# better aligns with the boxed API.  The dispatcher API hooks heavily
+# into our template based boxing/unboxing machinery, so changes
+# to this convention will usually need template updates too.
+#
+# Prominent characteristics of the dispatcher API:
+#
+#   - dtype, layout, device and pin_memory are represented as separate
+#     arguments.
+#
+
+
+def name(func: FunctionSchema) -> str:
+    return cpp.name(func)
+
+
+def argumenttype_type(
+    t: Type,
+    *,
+    mutable: bool,
+    binds: ArgName,
+    remove_non_owning_ref_types: bool = False,
+    symint: bool = True,
+) -> NamedCType:
+    # This is a faux amis.  If it makes sense in the future to add
+    # more special cases here, or invert things so cpp.argument_type
+    # calls this, or just completely inline the function, please do
+    # it.
+    return cpp.argumenttype_type(
+        t,
+        mutable=mutable,
+        binds=binds,
+        symint=symint,
+        remove_non_owning_ref_types=remove_non_owning_ref_types,
+    )
+
+
+def argument_type(
+    a: Argument,
+    *,
+    binds: ArgName,
+    remove_non_owning_ref_types: bool = False,
+    symint: bool = True,
+) -> NamedCType:
+    return argumenttype_type(
+        a.type,
+        mutable=a.is_write,
+        binds=binds,
+        remove_non_owning_ref_types=remove_non_owning_ref_types,
+        symint=symint,
+    )
+
+
+def returns_type(rs: Sequence[Return], *, symint: bool = True) -> CType:
+    # At present, there is no difference. But there could be!
+    return cpp.returns_type(rs, symint=symint)
+
+
+def jit_arguments(func: FunctionSchema) -> list[Argument]:
+    def to_argument(
+        a: Argument | TensorOptionsArguments | SelfArgument,
+    ) -> list[Argument]:
+        if isinstance(a, Argument):
+            return [a]
+        elif isinstance(a, SelfArgument):
+            return [a.argument]
+        elif isinstance(a, TensorOptionsArguments):
+            return [a.dtype, a.layout, a.device, a.pin_memory]
+        else:
+            assert_never(a)
+
+    return list(
+        concatMap(
+            to_argument,
+            itertools.chain(
+                func.arguments.positional, func.arguments.kwarg_only, func.arguments.out
+            ),
+        )
+    )
+
+
+def argument(
+    a: Argument, *, remove_non_owning_ref_types: bool = False, symint: bool = True
+) -> Binding:
+    return Binding(
+        nctype=argument_type(
+            a,
+            binds=a.name,
+            remove_non_owning_ref_types=remove_non_owning_ref_types,
+            symint=symint,
+        ),
+        name=a.name,
+        argument=a,
+    )
+
+
+def arguments(func: FunctionSchema, *, symint: bool = True) -> list[Binding]:
+    return [argument(a, symint=symint) for a in jit_arguments(func)]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/functionalization.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/functionalization.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4b46b5f14760b2eca447536a1795ade807f89d5
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/functionalization.py
@@ -0,0 +1,215 @@
+from __future__ import annotations
+
+from torchgen.api import dispatcher
+from torchgen.api.types import (
+    BaseCppType,
+    BaseCType,
+    Binding,
+    boolT,
+    ConstRefCType,
+    CType,
+    longT,
+    NamedCType,
+    tensorT,
+)
+from torchgen.model import (
+    Argument,
+    BaseTy,
+    BaseType,
+    FunctionSchema,
+    NativeFunction,
+    NativeFunctionsViewGroup,
+)
+
+
+# This file describes the translation of JIT schema to API's used
+# when creating `ViewMeta` specializations that are used by the functionalization pass.
+# These API's mostly follow the dispatcher API, with one difference:
+# - While the forward function just directly calls into the at::_ops API
+#   (following the dispatcher convention), the logic here for the reverse function
+#   is responsible for generating both the call-site, and the declarations
+#   (which are implemented manually in the at::functionalization::impl namespace).
+
+# Define some specific lambda input arguments.
+base_binding = Binding(
+    name="base",
+    nctype=NamedCType(name="base", type=ConstRefCType(BaseCType(tensorT))),
+    argument=Argument(
+        name="base", type=BaseType(BaseTy.Tensor), default=None, annotation=None
+    ),
+    default=None,
+)
+
+has_symbolic_inputs_binding = Binding(
+    name="has_symbolic_inputs",
+    nctype=NamedCType(name="has_symbolic_inputs", type=BaseCType(boolT)),
+    argument=Argument(
+        name="has_symbolic_inputs",
+        type=BaseType(BaseTy.bool),
+        default=None,
+        annotation=None,
+    ),
+    default=None,
+)
+mutated_view_binding = Binding(
+    name="mutated_view",
+    nctype=NamedCType(name="mutated_view", type=ConstRefCType(BaseCType(tensorT))),
+    argument=Argument(
+        name="base", type=BaseType(BaseTy.Tensor), default=None, annotation=None
+    ),
+    default=None,
+)
+out_index_binding = Binding(
+    name="out_index",
+    nctype=NamedCType(name="out_index", type=BaseCType(longT)),
+    argument=Argument(
+        name="out_index", type=BaseType(BaseTy.int), default=None, annotation=None
+    ),
+    default=None,
+)
+reapply_views_binding = Binding(
+    name="reapply_views",
+    nctype=NamedCType(name="reapply_views", type=BaseCType(boolT)),
+    argument=Argument(
+        name="reapply_views", type=BaseType(BaseTy.bool), default=None, annotation=None
+    ),
+    default=None,
+)
+
+InverseReturnModeT = BaseCppType("at::functionalization", "InverseReturnMode")
+inverse_return_mode_binding = Binding(
+    name="inverse_return_mode",
+    nctype=NamedCType(name="inverse_return_mode", type=BaseCType(InverseReturnModeT)),
+    argument=Argument(
+        name="inverse_return_mode",
+        # NB: not actually a bool but it doesn't matter because this isn't used
+        type=BaseType(BaseTy.bool),
+        default=None,
+        annotation=None,
+    ),
+    default=None,
+)
+
+
+# Name of the `ViewMeta` specialization class created.
+def classname(func: FunctionSchema, with_namespace: bool = False) -> str:
+    namespace = "at::functionalization::" if with_namespace else ""
+    return f"{namespace}{func.name.unambiguous_name()}_ViewMeta"
+
+
+# Name of the operation called inside the `forward`/`reverse` implementations.
+def name(
+    g: NativeFunctionsViewGroup,
+    *,
+    is_reverse: bool,
+    include_namespace: bool,
+    reapply_views: bool | None = None,
+) -> str:
+    if reapply_views is None:
+        # reapply_views is only important for the fwd lambda,
+        # since we always plumb the runtime "reapply_views" argument into the reverse function.
+        assert is_reverse
+    if is_reverse:
+        return reverse_name(g.view, include_namespace)
+    # in the forward case, we just directly call into the at::_ops API (so we always need the namespace)
+    assert include_namespace
+    assert g.view_copy is not None
+    api_name = (
+        g.view.func.name.unambiguous_name()
+        if reapply_views
+        else g.view_copy.func.name.unambiguous_name()
+    )
+    return f"at::_ops::{api_name}::call"
+
+
+def reverse_name(f: NativeFunction, include_namespace: bool) -> str:
+    # for the reverse: we plumb the "reapply_views" flag into that function and support
+    # both copy and non-copy variants. (We could avoid doing that, but that would require
+    # writing out twice as many view inverse functions).
+    api_name = f.func.name.unambiguous_name()
+    # in the reverse case, we codegen both the call-sites (which need the full namespace) and the declarations (which don't)
+    if include_namespace:
+        return f"at::functionalization::FunctionalInverses::{api_name}_inverse"
+    else:
+        return f"{api_name}_inverse"
+
+
+def returns_type(func: FunctionSchema) -> CType:
+    # Assertion: all view ops return tensor-like outputs
+    assert len(func.returns) >= 1
+    for ret in func.returns:
+        assert ret.type.is_tensor_like()
+    # However, the return type of the lambda is always an individual tensor.
+    # For multi-tensor outputs, each tensor needs to be tracked individually.
+    return BaseCType(tensorT)
+
+
+# Checks whether `func` might return more than one value.
+def is_multi_output(func: FunctionSchema) -> bool:
+    return len(func.returns) > 1 or (
+        len(func.returns) == 1 and func.returns[0].type.is_list_like() is not None
+    )
+
+
+# `ViewMeta` specialization constructor parameters.
+def base_ctor_arguments(func: FunctionSchema) -> list[Binding]:
+    # All specializations are parematerized by `has_symbolic_inputs` flag.
+    arguments = [has_symbolic_inputs_binding]
+
+    # If `func` might return more than 1 value, we also parameterize this specialization
+    # with the output index.
+    if is_multi_output(func):
+        arguments.append(out_index_binding)
+
+    return arguments
+
+
+# `ViewMeta` specialized class' constructor arguments.
+#
+# Values needed specifically by this specialization, that the base class does not need.
+# Same as the class' attributes, but non-owning.
+def extra_ctor_arguments(func: FunctionSchema) -> list[Binding]:
+    return attributes(func, owning=False)
+
+
+# `ViewMeta` specialized class' non-static member data.
+#
+# Essential data for calling the instance's `forward` and `reverse functions. You can
+# think of them as values that should be captured from the functionalization kernel.
+def attributes(func: FunctionSchema, owning: bool = True) -> list[Binding]:
+    args = func.arguments.flat_all
+    assert args[0].type == BaseType(BaseTy.Tensor)
+    return [
+        reapply_views_binding,
+        inverse_return_mode_binding,
+        *[dispatcher.argument(a, remove_non_owning_ref_types=owning) for a in args[1:]],
+    ]
+
+
+def op_arguments(func: FunctionSchema, is_reverse: bool) -> list[Binding]:
+    args = func.arguments.flat_all
+    assert args[0].type == BaseType(BaseTy.Tensor)
+    non_self_args = args[1:]
+    # The forward lambda calls the at::_ops API, while the reverse lambda calls the view inverse API.
+    # Both of these follow the dispatcher API.
+    non_self_bindings = [dispatcher.argument(a) for a in non_self_args]
+    if not is_reverse:
+        # the forward lambda swaps out the original tensor argument with the lambd arg "base"
+        return [base_binding] + non_self_bindings
+    else:
+        # the reverse lambda does the same, but with an additional "mutated_view" arg
+        # additionally, we have a calling convention: for view ops that return multiple tensor outputs
+        # their corresponding view_inverse function takes in an additional index argument.
+        if is_multi_output(func):
+            return [
+                base_binding,
+                mutated_view_binding,
+                inverse_return_mode_binding,
+                out_index_binding,
+            ] + non_self_bindings
+        else:
+            return [
+                base_binding,
+                mutated_view_binding,
+                inverse_return_mode_binding,
+            ] + non_self_bindings
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/lazy.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/lazy.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d308afd8136a4e4d3c0b5eb1b89fcbd00c0a5c5
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/lazy.py
@@ -0,0 +1,468 @@
+from __future__ import annotations
+
+from typing import Any
+
+from torchgen.api.types import (
+    BaseCppType,
+    BaseCType,
+    boolT,
+    CType,
+    deviceT,
+    doubleT,
+    generatorT,
+    layoutT,
+    ListCType,
+    longT,
+    memoryFormatT,
+    NamedCType,
+    OptionalCType,
+    scalarT,
+    scalarTypeT,
+    stringT,
+    SymIntT,
+    VectorCType,
+)
+from torchgen.model import (
+    Argument,
+    BaseTy,
+    BaseType,
+    FunctionSchema,
+    ListType,
+    OperatorName,
+    OptionalType,
+    Return,
+    TensorOptionsArguments,
+    Type,
+)
+
+
+_valueT: BaseCppType | None = None
+
+
+# A ValueT is an IR type which represents the computation of a Tensor.  In other
+# words, a PyTorch user will do operations on lazy tensors, and each output lazy
+# tensor internally tracks a ValueT representing the IR node that would have
+# actually produced the value of this tensor for real.
+#
+# This is configurable because different lazy tensor backends (LTC vs XLA) will
+# have different IR representations.  (Though, arguably, after unification they
+# shouldn't!)
+def getValueT() -> BaseCppType:
+    global _valueT
+    if not _valueT:
+        raise NotImplementedError(
+            "The value type needs to be set with setValueT() in run_gen_lazy_tensor()"
+        )
+
+    return _valueT
+
+
+def setValueT(val: BaseCppType) -> None:
+    global _valueT
+    _valueT = val
+
+
+# this is a bad hack. I need to refactor the data model to represent each arg in the schema as an object,
+# making it easier to represent special properties of an arg.
+tensorListValueT = BaseCppType("torch::lazy", "Value")
+
+
+def process_ir_type(
+    typ: Type, properties: LazyIrProperties, *, symint: bool
+) -> BaseCType | VectorCType | OptionalCType | ListCType:
+    """
+    This function takes a type from NativeFunctions and converts it for use with
+    lazy tensor codegen.
+
+    Type conversion for lazy currently consists of
+     (1) changing at::Tensors into lazy::Values
+     (2) wrapping everything in a BaseCType
+     (3) making cpp-reference types into cpp-value types (e.g. vector instead of IntArrayRef)
+
+    (1) converts at::Tensors to lazy::Values (which wrap lazy::Nodes, with which Lazy IR represents tensors.)
+    There is special handling for Optional[Tensor] or list[Tensor], etc- hence 'tensor-like'
+
+    This is incomplete- there are assertions in places that it's expected to need to add
+    more types as the codegen is used with more operators.
+    """
+    if isinstance(typ, BaseType):
+        if typ.name == BaseTy.Tensor:
+            return BaseCType(getValueT())
+        elif typ.name == BaseTy.Scalar:
+            if properties.TreatScalarsAsConstants:
+                return BaseCType(scalarT)
+            # at::scalar has special handling,
+            # and is wrapped in an lazy::Value just like at::tensor
+            return BaseCType(getValueT())
+        elif typ.name == BaseTy.ScalarType:
+            return BaseCType(scalarTypeT)
+        elif typ.name == BaseTy.int:
+            return BaseCType(longT)
+        elif typ.name == BaseTy.SymInt:
+            if symint:
+                return BaseCType(getValueT())
+            else:
+                return BaseCType(longT)
+        elif typ.name == BaseTy.bool:
+            return BaseCType(boolT)
+        elif typ.name == BaseTy.float:
+            return BaseCType(doubleT)
+        elif typ.name == BaseTy.str:
+            return BaseCType(stringT)
+        elif typ.name == BaseTy.Device:
+            return BaseCType(deviceT)
+        elif typ.name == BaseTy.Generator:
+            return BaseCType(generatorT)
+        elif typ.name == BaseTy.Layout:
+            return BaseCType(layoutT)
+        elif typ.name == BaseTy.MemoryFormat:
+            return BaseCType(memoryFormatT)
+        else:
+            raise AssertionError(f"TODO add support for type {repr(typ)}")
+    elif isinstance(typ, OptionalType):
+        return OptionalCType(process_ir_type(typ.elem, properties, symint=symint))
+    elif isinstance(typ, ListType):
+        if str(typ.elem) == "Tensor?":
+            # TODO(whc) is this actually correct? or should it use a Vector like above
+            return ListCType(OptionalCType(BaseCType(getValueT())))
+        elif str(typ.elem) == "Tensor":
+            # this is a TensorList which comes in from GetTensorList as a Value
+            return BaseCType(tensorListValueT)
+        elif typ.elem == BaseType(BaseTy.SymInt):
+            # TODO: return a value type.  The problem here is analogous to
+            # the problem with tensorListValueT: if you have SymInt[] you
+            # cannot conveniently save the list of Value directly, as nodes
+            # expect to save values as a vector for ALL arguments.  So you
+            # need a separate IR node that represents all of the size nodes
+            # assembled into a list.  I'm not an LTC dev so I don't want to
+            # figure it out right now.  Y'all figure it out...
+            return VectorCType(BaseCType(longT))
+
+        else:
+            return VectorCType(process_ir_type(typ.elem, properties, symint=symint))
+    else:
+        raise AssertionError(f"unrecognized type {repr(typ)}")
+
+
+# TODO: Determining this based off of CType is bad; this should be computed
+# from Type directly; then the same logic as process_ir_type can be used
+#
+# Invariant: passed typ should be an *owning* CType (e.g., we will report
+# that ArrayRef is NOT a value type)
+def isValueType(typ: CType, properties: LazyIrProperties | None = None) -> bool:
+    """
+    Given a type, determine if it is a Value-like type.  This is equivalent to
+    being Tensor-like, but assumes the type has already been transformed.
+    """
+    if isinstance(typ, BaseCType):
+        # I am regretting my naming conventions, but now we are wrapping at::scalar in
+        # lazy value, while preserving other 'scalar' types as scalars in the IR
+        treat_scalars_as_constants = properties and properties.TreatScalarsAsConstants
+        return (
+            typ.type == getValueT()
+            or (typ.type == scalarT and not treat_scalars_as_constants)
+            or typ.type == SymIntT
+        )
+    elif typ == VectorCType(BaseCType(SymIntT)):
+        # TODO: report True for this
+        return False
+    elif isinstance(typ, (OptionalCType, ListCType, VectorCType)):
+        return isValueType(typ.elem, properties)
+    return False
+
+
+def isSymIntType(typ: Type) -> bool:
+    return isinstance(typ, BaseType) and typ.name == BaseTy.SymInt
+
+
+def isWrappedScalarType(typ: Type) -> bool:
+    """
+    Given a type, determine if it is a c10::scalar which we will wrap in a lazy Value.
+    Since we literally change the type from scalarT to valueT, information is lost.
+    This function helps build a list of wrapped scalars to save that information
+    """
+    if isinstance(typ, BaseType):
+        # I am regretting my naming conventions, but now we are wrapping at::scalar in
+        # lazy value, while preserving other 'scalar' types as scalars in the IR
+        return typ.name == BaseTy.Scalar
+    elif isinstance(typ, (OptionalType, ListType)):
+        return isWrappedScalarType(typ.elem)
+    return False
+
+
+# TODO: dedupe with Type.is_generator_like
+def isGeneratorType(typ: Type) -> bool:
+    if isinstance(typ, BaseType):
+        return typ.name == BaseTy.Generator
+    elif isinstance(typ, (OptionalType)):
+        return isGeneratorType(typ.elem)
+    return False
+
+
+# This class caches a few derived properties computed from an Argument
+# and LazyIrProperties
+class LazyArgument:
+    name: str
+    orig_type: Type
+    lazy_type_: CType | None
+    is_wrapped_scalar: bool
+    is_generator: bool
+    # TODO: this is lies, it is false for symint list
+    is_symint_or_list: bool
+
+    # Whether or not we are treating this as symint or not
+    symint: bool
+
+    # true if this argument is or contains a lazy IR value
+    is_lazy_value: bool
+
+    def __init__(
+        self, arg: Argument, properties: LazyIrProperties, *, symint: bool
+    ) -> None:
+        self.name = arg.name
+        self.orig_type = arg.type
+        self.symint = symint
+        self.is_optional = isinstance(arg.type, OptionalType)
+        self.is_generator = isGeneratorType(arg.type)
+        self.lazy_type_ = process_ir_type(arg.type, properties, symint=symint)
+        self.is_wrapped_scalar = isWrappedScalarType(arg.type)
+        self.is_symint_or_list = symint and (
+            isSymIntType(arg.type)
+            or (isinstance(arg.type, OptionalType) and isSymIntType(arg.type.elem))
+            # TODO: lists of symints are not currently treated as value types
+            # or (isinstance(arg.type, ListType) and isSymIntType(arg.type.elem))
+        )
+
+        self.is_lazy_value = isValueType(self.lazy_type, properties)
+
+    @property
+    def lazy_type(self) -> CType:
+        assert self.lazy_type_ is not None, (
+            f"Attempted to access lazy_type for invalid argument {self.name}"
+        )
+        return self.lazy_type_
+
+
+class LazyIrProperties:
+    """Collection of properties for an IR node
+
+    The property groups are listed below. Each group is mutually
+    exclusive, meaning that only one property from each group can be True
+    at any one time. The properties can be accessed as if they were normal
+    attributes. The mutual exclusivity is automatically handled.
+    """
+
+    Properties: tuple[tuple[str, ...], ...] = (
+        (
+            "ShapePrecompute",  # Assume shape has been precomputed
+            "ShapeCompute",  # Need to compute the shape on construction
+            "ShapeCache",  # Utilize the shape cache to defer computation
+        ),
+        (
+            "Lower",  # Codegen full lower function
+            "LowerDeclOnly",  # Codegen only lower function declaration
+        ),
+        (
+            "CanBeReused",  # Codegen full reuse function
+            "CanBeReusedDeclOnly",  # Codegen only reuse function declaration
+        ),
+        (
+            "CreateFn",  # Codegen full create function
+            "CreateFnDeclOnly",  # Codegen only create function declaration
+        ),
+        (
+            "TreatScalarsAsConstants",  # Treat Scalars as constants instead of handling like values
+        ),
+    )
+
+    def __init__(self, *default_properties: str) -> None:
+        properties: dict[tuple[str, ...], str | None] = dict.fromkeys(
+            LazyIrProperties.Properties
+        )
+        self.__dict__["properties"] = properties
+        for p in default_properties:
+            setattr(self, p, True)
+
+    def __getattr__(self, key: str) -> Any:
+        properties = self.__dict__["properties"]
+        for values in LazyIrProperties.Properties:
+            if key in values:
+                return properties[values] == key
+
+        return self.__getattribute__(key)
+
+    def __setattr__(self, key: str, value: Any) -> Any:
+        properties = self.__dict__["properties"]
+        for values in LazyIrProperties.Properties:
+            if key in values:
+                properties[values] = key if value else None
+                return value
+
+        raise KeyError(f"Invalid property: {key}")
+
+
+# Inspired by a FunctionSchema object, a LazyIrSchema holds the schema of a Lazy IR node.
+# Unlike a FunctionSchema, it has no round-trippable string form (relating to the YAML),
+# but carries type information from a native FunctionSchema modified for use with IR nodes,
+# and preserving original argument names.
+#
+# TODO: This is not idiomatic with how other torchgen APIs transform on schema.
+class LazyIrSchema:
+    # The name of the operator this function schema describes.
+    name: OperatorName
+
+    positional_args: tuple[LazyArgument, ...]
+    keyword_args: tuple[LazyArgument, ...]
+
+    # TODO: Need to handle collisions with argument names at some point
+    returns: tuple[Return, ...]
+
+    # if this schema has a Generator arg, list its orig ctype/name but don't
+    # build a LazyArgument since lazy IR doesn't support it
+    generator_arg: NamedCType | None = None
+
+    # original function schema
+    func: FunctionSchema
+
+    # Whether or not we are code-genning for SymInt or not
+    symint: bool
+
+    properties: LazyIrProperties = LazyIrProperties(
+        # default properties
+        "ShapePrecompute",
+        "Lower",
+        "CanBeReused",
+    )
+    opkind: str | None = None
+
+    def __init__(
+        self,
+        func: FunctionSchema,
+        properties: LazyIrProperties | None = None,
+        *,
+        symint: bool,
+    ) -> None:
+        if properties:
+            self.properties = properties
+
+        self.func = func
+        self.symint = symint
+        positional_args: list[LazyArgument] = []
+        for arg_field in ["pre_self_positional", "self_arg", "post_self_positional"]:
+            if arg_field == "self_arg" and func.arguments.self_arg is not None:
+                arg = func.arguments.self_arg.argument
+                positional_args.append(
+                    LazyArgument(arg, self.properties, symint=symint)
+                )
+            elif getattr(func.arguments, arg_field) is not None:
+                positional_args.extend(
+                    LazyArgument(arg, self.properties, symint=symint)
+                    for arg in getattr(func.arguments, arg_field)
+                )
+        self.positional_args = tuple(positional_args)
+
+        keyword_args: list[LazyArgument] = []
+        for arg_field in [
+            "pre_tensor_options_kwarg_only",
+            "tensor_options",
+            "post_tensor_options_kwarg_only",
+            "out",
+        ]:
+            curr_args = getattr(func.arguments, arg_field)
+            if curr_args is not None:
+                if isinstance(curr_args, TensorOptionsArguments):
+                    curr_args = curr_args.all()
+                for arg in curr_args:
+                    if isGeneratorType(arg.type):
+                        assert self.generator_arg is None, (
+                            "We expect there is only one generator arg"
+                        )
+                        self.generator_arg = NamedCType(
+                            arg.name,
+                            arg.type,  # type:ignore[arg-type]
+                        )
+                keyword_args.extend(
+                    LazyArgument(arg, self.properties, symint=symint)
+                    for arg in curr_args
+                )
+        self.keyword_args = tuple(keyword_args)
+        self.name = func.name
+        self.returns = func.returns
+
+    @property
+    def node_name(self) -> str:
+        """
+        Return camel-case version of op in node.
+
+        Note: This function also appends any `overload_name` in the operation.
+        For example, if the op is `bitwise_and.Tensor`, the returned name
+        will be `BitwiseAndTensor`.
+        """
+        op_name = f"{self.name.name}_{self.name.overload_name}".lower()
+        return "".join(word.capitalize() or "" for word in op_name.split("_"))
+
+    @property
+    def aten_name(self) -> str:
+        return str(self.name.name)
+
+    @property
+    def base_name(self) -> str:
+        return f"{self.name.name.base}"
+
+    def filtered_args(
+        self,
+        positional: bool = True,
+        keyword: bool = True,
+        values: bool = True,
+        scalars: bool = True,
+        generator: bool = True,
+    ) -> list[LazyArgument]:
+        # This function maintains the sorted order of arguments but provides different filtered views.
+        # Some parts of the code care about kwargs vs args (TS lowerings),
+        # other parts care about whether they need to wrap the arg in a lazy value or leave it alone.
+        # Generators are special cased, as they are needed for fallback/shape-inference but not supported
+        # in TS lowerings and therefore also omitted from lazy IR.
+        args: list[LazyArgument] = []
+        if positional:
+            args.extend(self.positional_args)
+        if keyword:
+            args.extend(self.keyword_args)
+
+        if values and scalars and generator:
+            return args
+        elif values and scalars:
+            return [a for a in args if not a.is_generator]
+        elif values:
+            return [a for a in args if a.is_lazy_value]
+        elif scalars:
+            return [
+                a
+                for a in args
+                if not a.is_lazy_value and (generator or not a.is_generator)
+            ]
+
+        return []
+
+    @property
+    def positional_values(self) -> list[LazyArgument]:
+        return self.filtered_args(
+            positional=True, keyword=False, values=True, scalars=False
+        )
+
+    @property
+    def positional_scalars(self) -> list[LazyArgument]:
+        return self.filtered_args(
+            positional=True, keyword=False, values=False, scalars=True
+        )
+
+    @property
+    def keyword_values(self) -> list[LazyArgument]:
+        return self.filtered_args(
+            positional=False, keyword=True, values=True, scalars=False
+        )
+
+    @property
+    def keyword_scalars(self) -> list[LazyArgument]:
+        return self.filtered_args(
+            positional=False, keyword=True, values=False, scalars=True
+        )
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/meta.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/meta.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e99d151faeaccea7ca47f372fd26f9985ce7249
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/meta.py
@@ -0,0 +1,13 @@
+from torchgen.model import NativeFunctionsGroup
+
+
+# Follows dispatcher calling convention, but:
+#   - Mutable arguments not allowed.  Meta functions are always
+#     written in functional form.  Look at FunctionSchema.signature()
+#   - No tensor returns; instead we return a TensorMeta describing
+#     the tensor in question
+
+
+def name(g: NativeFunctionsGroup) -> str:
+    # use the overload name from the functional version
+    return str(g.functional.func.name).replace(".", "_")
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/native.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/native.py
new file mode 100644
index 0000000000000000000000000000000000000000..632216704d2d47606b977d487335ca196e2e1842
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/native.py
@@ -0,0 +1,159 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+from typing_extensions import assert_never
+
+from torchgen import local
+from torchgen.api import cpp
+from torchgen.api.types import (
+    ArgName,
+    BaseCType,
+    Binding,
+    boolT,
+    ConstRefCType,
+    CType,
+    deviceT,
+    layoutT,
+    ListCType,
+    MutRefCType,
+    NamedCType,
+    OptionalCType,
+    scalarT,
+    scalarTypeT,
+    tensorT,
+)
+from torchgen.model import (
+    Argument,
+    FunctionSchema,
+    Return,
+    SelfArgument,
+    TensorOptionsArguments,
+    Type,
+)
+
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+
+
+# This file describes the translation of JIT schema to the native functions API.
+# This looks a lot like the C++ API (which makes historical sense, because the
+# idea was you wrote native functions to implement functions in the C++ API),
+# but over time we have evolved the C++ API without actually changing our
+# native:: kernels.  The intention is to make native API and dispatcher API
+# line up as closely as possible, since this results in the least overhead
+# (no translation is needed from dispatcher API to native API).
+#
+# NB: this is symint aware, you will get the non-SymInt variant for some
+# dispatch entries and SymInt for others.
+
+
+def name(func: FunctionSchema) -> str:
+    name = str(func.name.name)
+    # TODO: delete this!
+    if func.is_out_fn():
+        name += "_out"
+    if func.name.overload_name:
+        name += f"_{func.name.overload_name}"
+    return name
+
+
+def argumenttype_type(
+    t: Type, *, mutable: bool, binds: ArgName, symint: bool
+) -> NamedCType:
+    if str(t) == "Tensor?":
+        tensor_type: OptionalCType = OptionalCType(BaseCType(tensorT))
+        if mutable and not local.use_const_ref_for_mutable_tensors():
+            return NamedCType(binds, MutRefCType(tensor_type))
+        else:
+            return NamedCType(binds, ConstRefCType(tensor_type))
+    elif str(t) == "Tensor?[]":
+        return NamedCType(
+            binds, ConstRefCType(ListCType(OptionalCType(BaseCType(tensorT))))
+        )
+    elif str(t) == "Scalar":
+        return NamedCType(binds, ConstRefCType(BaseCType(scalarT)))
+    elif str(t) == "Scalar?":
+        return NamedCType(binds, ConstRefCType(OptionalCType(BaseCType(scalarT))))
+    return cpp.argumenttype_type(t, mutable=mutable, binds=binds, symint=symint)
+
+
+def returns_type(rs: Sequence[Return], *, symint: bool) -> CType:
+    return cpp.returns_type(rs, symint=symint)
+
+
+def argument_type(a: Argument, *, binds: ArgName, symint: bool) -> NamedCType:
+    return argumenttype_type(a.type, mutable=a.is_write, binds=binds, symint=symint)
+
+
+def argument(
+    a: Argument | SelfArgument | TensorOptionsArguments,
+    *,
+    is_out: bool,
+    symint: bool,
+) -> list[Binding]:
+    # Ideally, we NEVER default native functions.  However, there are a number
+    # of functions that call native:: directly and rely on the defaulting
+    # existing.  So for BC, we generate defaults for non-out variants (but not
+    # for out variants, where it is impossible to generate an appropriate
+    # default)
+    should_default = not is_out
+    if isinstance(a, Argument):
+        default: str | None = None
+        if should_default and a.default is not None:
+            default = cpp.default_expr(a.default, a.type, symint=symint)
+        return [
+            Binding(
+                nctype=argument_type(a, binds=a.name, symint=symint),
+                name=a.name,
+                default=default,
+                argument=a,
+            )
+        ]
+    elif isinstance(a, SelfArgument):
+        # Erase SelfArgument from the distinction
+        return argument(a.argument, is_out=is_out, symint=symint)
+    elif isinstance(a, TensorOptionsArguments):
+        default = None
+        if should_default:
+            default = "{}"
+        # TODO: Not sure why the arguments assigned here are for
+        # TensorOptionsArguments and not the constituent pieces.  It seems
+        # to matter
+        return [
+            Binding(
+                nctype=NamedCType("dtype", OptionalCType(BaseCType(scalarTypeT))),
+                name="dtype",
+                default=default,
+                argument=a,
+            ),
+            Binding(
+                nctype=NamedCType("layout", OptionalCType(BaseCType(layoutT))),
+                name="layout",
+                default=default,
+                argument=a,
+            ),
+            Binding(
+                nctype=NamedCType("device", OptionalCType(BaseCType(deviceT))),
+                name="device",
+                default=default,
+                argument=a,
+            ),
+            Binding(
+                nctype=NamedCType("pin_memory", OptionalCType(BaseCType(boolT))),
+                name="pin_memory",
+                default=default,
+                argument=a,
+            ),
+        ]
+    else:
+        assert_never(a)
+
+
+def arguments(func: FunctionSchema, *, symint: bool) -> list[Binding]:
+    args: list[Argument | TensorOptionsArguments | SelfArgument] = []
+    args.extend(func.arguments.non_out)
+    args.extend(func.arguments.out)
+    return [
+        r for arg in args for r in argument(arg, symint=symint, is_out=func.is_out_fn())
+    ]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/python.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/python.py
new file mode 100644
index 0000000000000000000000000000000000000000..dbfa73060163057e979d231c06f63bb29ea87daa
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/python.py
@@ -0,0 +1,1548 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+from torchgen.api import cpp
+from torchgen.api.types import Binding, CppSignature, CppSignatureGroup
+from torchgen.gen import pythonify_default
+from torchgen.model import (
+    Argument,
+    BaseTy,
+    BaseType,
+    FunctionSchema,
+    ListType,
+    NativeFunction,
+    OptionalType,
+    Return,
+    Type,
+    Variant,
+)
+
+
+if TYPE_CHECKING:
+    from collections.abc import Iterable, Sequence
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                           Data Models
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+# [Notes] python binding codegen
+#
+# The Python binding codegen produces code that takes the input list of
+# PyObjects, finds the matching ATen C++ function using PythonArgParser,
+# converts the PyObjects into C++ types and calls the ATen C++ function:
+#
+# +--------+  parsing   +------------------------+  binding   +-----------------------+
+# | PyObjs | ---------> | PythonArgParser Output | ---------> | Cpp Function Dispatch |
+# +--------+            +------------------------+            +-----------------------+
+#
+# The following examples demonstrate the data models the Python binding
+# codegen needs to deal with and the tasks it needs to accomplish. It
+# helps understand the purpose of the new data types we introduced below.
+#
+#  - Function Schema (source of truth)
+#
+#      aten::empty.names(int[] size, *, Dimname[]? names,
+#                        ScalarType? dtype=None, Layout? layout=None,
+#                        Device? device=None, bool? pin_memory=None,
+#                        MemoryFormat? memory_format=None) -> Tensor
+#
+#  - Python Signature
+#
+#    It's used to generate input schema string for PythonArgParser.
+#    Note: TensorOptions fields are reordered and the additional
+#    'requires_grad' field is added:
+#
+#      empty(IntArrayRef size, *, DimnameList? names,
+#            MemoryFormat? memory_format=None, ScalarType dtype=None,
+#            Layout layout=torch.strided, Device device=None,
+#            bool pin_memory=False, bool requires_grad=False)
+#
+#  - C++ Signature
+#
+#    It's used to generate C++ lambda formals & dispatch call.
+#    Note: the scattered TensorOptions fields are packed into 'options'.
+#
+#      auto dispatch_empty =
+#          [](IntArrayRef size, std::optional names,
+#             const TensorOptions & options,
+#             std::optional memory_format) -> Tensor {
+#          pybind11::gil_scoped_release no_gil;
+#          return torch::empty(size, names, options, memory_format);
+#      };
+#
+#  - Binding between Python Arguments and C++ Arguments
+#
+#    Given a set of Python Arguments in scope, we need produce the
+#    binding expressions that translate the Python API into C++ API:
+#
+#            Python Args               Cpp Args       Binding Exprs
+#     -----------------------------------------------------------------
+#         0: size                      size           '_r.intlist(0)'
+#         1: names                     names          'names' [special init]
+#         2: memory_format -------+
+#         3: dtype         -----+-|--> options        'options' [special packing]
+#         4: layout            /  |
+#         5: device           /   +--> memory_format  '_r.memoryformatOptional(2)'
+#         6: pin_memory      /
+#         7: requires_grad -+
+#
+#    So the full dispatch expression would look like:
+#
+#      dispatch_empty(_r.intlist(0), names, options,
+#                     _r.memoryformatOptional(2))
+#
+#    Where does 'names' come from? It involves special local init:
+#
+#      auto __names = _r.toDimnameListOptional(1);
+#      std::optional names =
+#          __names ? std::make_optional(DimnameList(__names.value()))
+#                  : std::nullopt;
+#
+#    Where does 'options' come from? It involves special local init
+#    for TensorOptions. Note that Python side has the additional
+#    'requires_grad' field:
+#
+#      const auto options = TensorOptions()
+#          .dtype(_r.scalartype(3))
+#          .device(_r.device(5))
+#          .layout(_r.layoutOptional(4))
+#          .requires_grad(_r.toBool(7))
+#          .pinned_memory(_r.toBool(6));
+#
+#    In some other cases one Python Argument can map to multiple C++
+#    Arguments. For example:
+#
+#     aten::max.names_dim(Tensor self, Dimname dim, bool keepdim=False)
+#       -> (Tensor values, Tensor indices)
+#
+#            Python Args               Cpp Args          Binding Exprs
+#     ---------------------------------------------------------------------
+#                               +----> max               'out[0]'
+#                              /-----> max_values        'out[1]
+#         0: input            /        self              '_r.tensor(0)'
+#         1: dim             /         dim               '_r.dimname(1)'
+#         2: keepdim        /          keepdim           '_r.toBool(2)'
+#         3: out      -----+           [local init] out  '_r.tensorlist_n<2>(3)'
+#
+#    As demonstrated above, the binding can involve reordering,
+#    packing, unpacking and special local inits.
+#
+#
+#  Let's look at a concrete example:
+#
+#      static PythonArgParser parser({
+#        "abs(Tensor input, *, Tensor out=None)",
+#        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#         ^
+#         +--- Python Schema, represented by PythonSignature and PythonArgument
+#
+#      }, /*traceable=*/true);
+#
+#      ParsedArgs<2> parsed_args;
+#      auto _r = parser.parse(nullptr, args, kwargs, parsed_args);
+#
+#      ...
+#
+#      if (_r.isNone(1)) {
+#          ~~~~~~~~~~~~  <--- Scattered PythonArgParser output (arg name = 'out')
+#                             represented by PythonArgParserOutputExpr
+#
+#        // aten::abs(Tensor self) -> Tensor
+#        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#         ^
+#         +--- NativeFunction schema, base version
+#
+#        auto dispatch_abs = [](const Tensor & self) -> Tensor {
+#                            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#                             ^
+#                             +--- dispatch_lambda_args / dispatch_lambda_return_str
+#                                  generated from NativeFunction / CppSignature
+#                                  (deprecated PythonSignature is special)
+#                                  arguments are represented by DispatchLambdaArgument
+#
+#          pybind11::gil_scoped_release no_gil;
+#          return self.abs();
+#                 ~~~~~~~~~~~  <--- cpp_dispatch_target / cpp_dispatch_exprs
+#                                   generated from NativeFunction / CppSignature
+#        };
+#        return wrap(dispatch_abs(_r.tensor(0)));
+#                                 ~~~~~~~~~~~~~
+#                                  ^
+#                                  +--- dispatch_lambda_exprs
+#                                       binding PythonArgParserOutputExpr (python args)
+#                                       and DispatchLambdaArgument (c++ args)
+#
+#      } else {
+#        // aten::abs.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+#        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#         ^
+#         +--- NativeFunction schema, out-variant
+#
+#        auto dispatch_abs_out = [](Tensor out, const Tensor & self) -> Tensor {
+#          pybind11::gil_scoped_release no_gil;
+#          return at::abs_out(out, self);
+#        };
+#        return wrap(dispatch_abs_out(_r.tensor(1), _r.tensor(0)));
+#      }
+#
+#
+# [Notes] python interface codegen
+# The python dataclasses below are used used to generate both python binding code
+# and pyi type hint signatures.
+# In theory these two should look very similar, but there are number of differences
+# in how pyi signatures vs. python_arg_parser signatures are generated.
+# These differences have been encapsulated in signature_str() vs. signature_str_pyi()
+# to display the full signatures, and argument_str() vs argument_str_pyi() to display arguments.
+# For examples, only pyi signatures include return types.
+
+
+def format_function_signature(
+    name: str, arguments: Iterable[str] = (), return_type: str | None = None
+) -> str:
+    if not isinstance(arguments, (list, tuple)):
+        arguments = tuple(arguments)
+    return_type = f" -> {return_type}" if return_type is not None else ""
+
+    sig = f"def {name}({', '.join(arguments)}){return_type}: ..."
+    if len(sig) <= 80 or len(arguments) == 0 or tuple(arguments) == ("self",):
+        return sig
+
+    lines = [
+        f"def {name}(",
+        *(f"    {arg}," for arg in arguments),
+        f"){return_type}: ...",
+    ]
+    sig = "\n".join(lines)
+    if all(len(line) <= 80 for line in lines):
+        return sig
+    # ruff format bug for compound statements: https://github.com/astral-sh/ruff/issues/18658
+    # use `skip` instead of `on` + `off`
+    return sig.removesuffix(" ...") + "  # fmt: skip\n    ..."
+
+
+@dataclass(frozen=True)
+class PythonReturns:
+    returns: tuple[Return, ...]
+
+
+@dataclass(frozen=True)
+class PythonArgument:
+    name: str
+    type: Type
+    default: str | None
+
+    # Used to generate the default init expr for some PythonArgParser outputs, e.g.:
+    #
+    #   _r.layoutWithDefault(3, layout_from_backend(self.options().backend())))
+    #                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+    #                            ^
+    #                            +--- default_init str
+    default_init: str | None
+
+    # Compute argument formal for python argument parsing.
+    # Needs to be consistent with torch/csrc/utils/python_arg_parser.h.
+    def argument_str(self, *, method: bool = False, symint: bool = True) -> str:
+        type_str = (
+            argument_type_str(self.type, symint=symint)
+            .replace("const ", "")
+            .replace(" &", "")
+        )
+
+        name = self.name
+        # s/self/input/ outside method bindings
+        # [old codegen] TODO: remove this? doesn't rename in codegen, it's just
+        # for the parse string
+        if name == "self" and type_str in ["Tensor", "Number"] and not method:
+            name = "input"
+
+        # add default
+        if self.default is not None:
+            default = {
+                "nullptr": "None",
+                "::std::nullopt": "None",
+                "std::nullopt": "None",
+                "{}": "None",
+            }.get(self.default, self.default)
+            return f"{type_str} {name}={default}"
+        else:
+            return f"{type_str} {name}"
+
+    def argument_str_pyi(
+        self, *, method: bool = False, deprecated: bool = False
+    ) -> str:
+        type_str = argument_type_str_pyi(self.type)
+
+        name = self.name
+        # s/self/input/ outside method bindings
+        # [old codegen] TODO: remove this? doesn't rename in codegen, it's just
+        # for the parse string
+        if name == "self" and type_str == "Tensor" and not method and not deprecated:
+            name = "input"
+
+        if name == "from":  # from is a Python keyword...
+            name += "_"
+
+        # pyi merges the _out and functional variants into the same signature, with an optional out arg
+        if name == "out" and type_str == "Tensor" and not deprecated:
+            type_str = f"{type_str} | None".replace(" | None | None", " | None")
+
+        # pyi deprecated signatures don't get defaults for their out arg
+        treat_as_no_default = (
+            deprecated
+            and isinstance(self, PythonOutArgument)
+            and self.default == "None"
+        )
+
+        # add default
+        if self.default is not None and not treat_as_no_default:
+            if (
+                isinstance(self.type, ListType)
+                and self.type.elem == BaseType(BaseTy.int)
+                and self.default.startswith("{")
+                and self.default.endswith("}")
+            ):
+                default = (
+                    "(" + ", ".join(map(str.strip, self.default[1:-1].split(","))) + ")"
+                )
+            else:
+                default = {
+                    "nullptr": "None",
+                    "::std::nullopt": "None",
+                    "std::nullopt": "None",
+                    "{}": "None",
+                    "c10::MemoryFormat::Contiguous": "contiguous_format",
+                    "QScheme::PER_TENSOR_AFFINE": "per_tensor_affine",
+                }.get(self.default, self.default)
+            return f"{name}: {type_str} = {default}"
+        else:
+            return f"{name}: {type_str}"
+
+
+@dataclass(frozen=True)
+class PythonOutArgument(PythonArgument):
+    # In Python signature multiple output fields are packed into one 'out' argument.
+    # When binding to C++, it's first binded to a local 'out' variable:
+    #   'auto out = _r.tensorlist_n<2>(2);',
+    # then binded to scattered C++ output arguments as 'out[0]', 'out[1]', and etc.
+    # TODO: maybe don't need keep scattered out fields for python signature?
+    outputs: tuple[PythonArgument, ...]
+
+    @staticmethod
+    def from_outputs(outputs: tuple[PythonArgument, ...]) -> PythonOutArgument | None:
+        if not outputs:
+            return None
+
+        size = len(outputs)
+        if size == 1:
+            return PythonOutArgument(
+                name=outputs[0].name,
+                type=outputs[0].type,
+                default="None",
+                default_init=None,
+                outputs=outputs,
+            )
+        elif size > 1:
+            if any(not a.type.is_tensor_like() for a in outputs):
+                raise RuntimeError(f"Unsupported output type: {outputs}")
+            return PythonOutArgument(
+                name="out",
+                # TODO: shouldn't this be OptionalType[ListType[...]], since it defaults to None?
+                type=ListType(BaseType(BaseTy.Tensor), size),
+                default="None",
+                default_init=None,
+                outputs=outputs,
+            )
+        raise AssertionError(r"Unexpected PythonOutArgument size")
+
+
+@dataclass(frozen=True)
+class PythonSignature:
+    # Base operator name, without inplace/outplace suffix.
+    name: str
+
+    # Positional arguments.
+    # TODO: create a dedicated SelfArgument type for 'self'?
+    input_args: tuple[PythonArgument, ...]
+
+    # Keyword arguments excluding the 'out' argument and scattered kwargs belonging
+    # to TensorOptions (dtype, layout, device, pin_memory, requires_grad, etc).
+    input_kwargs: tuple[PythonArgument, ...]
+
+    output_args: PythonOutArgument | None
+
+    # Return types, which are only used by pyi
+    returns: PythonReturns
+
+    # These are scattered kwargs arguments belonging to TensorOptions.
+    # When binding to C++, they are packed into a TensorOptions object 'options'.
+    # It's possible that the C++ signature doesn't take TensorOptions object (e.g.
+    # for out variant), in which case they will be used as scattered fields without
+    # being packed into 'options'.
+    # TODO: maybe create a PythonTensorOptionsArgument?
+    tensor_options_args: tuple[PythonArgument, ...]
+
+    # method or function signature?
+    method: bool
+
+    @property
+    def deprecated(self) -> bool:
+        return False
+
+    def arguments(
+        self, *, skip_outputs: bool = False, skip_tensor_options: bool = False
+    ) -> tuple[PythonArgument | PythonOutArgument, ...]:
+        result: list[PythonArgument | PythonOutArgument] = []
+        result.extend(self.input_args)
+        result.extend(self.input_kwargs)
+        if self.output_args is not None and not skip_outputs:
+            result.append(self.output_args)
+        if not skip_tensor_options:
+            result.extend(self.tensor_options_args)
+        return tuple(result)
+
+    def arguments_count(self) -> int:
+        return len(self.arguments())
+
+    def output_idx(self) -> int:
+        return len(self.input_args) + len(self.input_kwargs)
+
+    # [old codegen] Compute the Python function signature for argument parsing,
+    # as specified in torch/csrc/utils/python_arg_parser.h.  WARNING:
+    # this is NOT the same type signature as specified by PEP 484
+    # as understood by mypy; our format was independently developed
+    # and has some quirks to make it more suitable specifically
+    # for error parsing.
+    #
+    # For a translation to mypy-valid type signatures, see
+    # signature_str_pyi().
+    def signature_str(self, *, skip_outputs: bool = False, symint: bool = True) -> str:
+        args = self.arguments(skip_outputs=skip_outputs)
+        schema_formals: list[str] = [
+            a.argument_str(method=self.method, symint=symint) for a in args
+        ]
+        positional_argc = len(self.input_args)
+        if len(schema_formals) > positional_argc:
+            schema_formals.insert(positional_argc, "*")
+
+        return f"{self.name}({', '.join(schema_formals)})"
+
+    def signature_str_pyi(self, *, skip_outputs: bool = False) -> str:
+        args = self.arguments(skip_outputs=skip_outputs)
+        schema_formals: list[str] = [
+            a.argument_str_pyi(method=self.method) for a in args
+        ]
+        positional_argc = len(self.input_args)
+        if len(schema_formals) > positional_argc:
+            schema_formals.insert(positional_argc, "*")
+
+        # only pyi signatures include returns
+        returns_str = returns_str_pyi(self)
+        # pyi also includes self (with no typing/defaults) for methods
+        if self.method:
+            schema_formals.insert(0, "self")
+        return format_function_signature(self.name, schema_formals, returns_str)
+
+    def signature_str_pyi_vararg(self, *, skip_outputs: bool = False) -> str | None:
+        # only pyi uses vararg signatures
+        args = self.arguments(skip_outputs=skip_outputs)
+        schema_formals: list[str] = [
+            a.argument_str_pyi(method=self.method) for a in args
+        ]
+        # vararg only applies to pyi signatures. vararg variants are not generated for all signatures
+        num_args = self.arguments_count()
+        if num_args == 0:
+            return None
+
+        num_positionalargs = len(self.input_args)
+
+        vararg_type = args[0].type
+        if not (
+            isinstance(vararg_type, ListType)
+            and str(vararg_type.elem) in ["int", "SymInt"]
+            and num_positionalargs == 1
+        ):
+            return None
+
+        # Below are the major changes in vararg vs. regular pyi signatures
+        # vararg signatures also omit the asterix
+        assert isinstance(vararg_type, ListType)
+        schema_formals[0] = (
+            "*" + args[0].name + ": " + argument_type_str_pyi(vararg_type.elem)
+        )
+
+        returns_str = returns_str_pyi(self)
+        # pyi also includes self (with no typing/defaults) for methods
+        if self.method:
+            schema_formals.insert(0, "self")
+        return format_function_signature(self.name, schema_formals, returns_str)
+
+
+# The deprecated python signature involves some special logic, so create a
+# dedicated data model to store these extra properties.
+@dataclass(frozen=True)
+class PythonSignatureDeprecated(PythonSignature):
+    # Schema for the deprecated function
+    deprecated_schema: FunctionSchema
+
+    # The deprecated signature might miss some arguments that the corresponding
+    # C++ signature expects. We need store the constant default values to pass in.
+    # For example:
+    #   [deprecate signature]: addmm(Scalar beta, Tensor self, Tensor mat1, Tensor mat2)
+    #   [func schema]: aten::addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+    #   [func call]: self.addmm(mat1, mat2, beta, 1)
+    # We store ['self', 'mat1', 'mat2', 'beta', '1'] in this case.
+    deprecated_args_exprs: tuple[str, ...]
+
+    @property
+    def deprecated(self) -> bool:
+        return True
+
+    def signature_str(self, *, skip_outputs: bool = False, symint: bool = True) -> str:
+        return (
+            PythonSignature.signature_str(
+                self, skip_outputs=skip_outputs, symint=symint
+            )
+            + "|deprecated"
+        )
+
+    def signature_str_pyi(self, *, skip_outputs: bool = False) -> str:
+        args = self.arguments(skip_outputs=skip_outputs)
+        schema_formals: list[str] = [
+            a.argument_str_pyi(method=self.method, deprecated=True) for a in args
+        ]
+        positional_argc = len(self.input_args)
+        if len(schema_formals) > positional_argc:
+            schema_formals.insert(positional_argc, "*")
+
+        returns_str = returns_str_pyi(self)
+        return format_function_signature(self.name, schema_formals, returns_str)
+
+    def signature_str_pyi_vararg(self, *, skip_outputs: bool = False) -> str | None:
+        # the codegen doesn't include vararg variants for deprecated signatures
+        return None
+
+
+# This struct is used to hold the PythonSignature and its corresponding
+# NativeFunction BEFORE grouping base and out-variant functions.
+# Why not store NativeFunction in PythonSignature or construct PythonSignature
+# from NativeFunction? Because they are not 1-1 mapped.
+# One native function could have both deprecated and non-deprecated python
+# signatures - NativeFunction doesn't contain information to construct the
+# deprecated python signature.
+# One python signature is used to handle both the base and the out-variant
+# function - see 'PythonSignatureGroup'.
+@dataclass(frozen=True)
+class PythonSignatureNativeFunctionPair:
+    signature: PythonSignature
+    function: NativeFunction
+
+
+# We merge pairs of functions with signatures that are equivalent mod
+# output arguments, and use a single entry in the python_arg_parser sig
+# list for both (output arguments become optional).
+@dataclass(frozen=True)
+class PythonSignatureGroup:
+    # The signature used for Python argument parsing. The outplace signature
+    # is preferred if exists, because it can be used to parse inputs for both
+    # the out-place variant and the base version (with output omitted).
+    signature: PythonSignature
+
+    # The regular ATen declaration (e.g. conv2d)
+    base: NativeFunction
+
+    # The out variant (e.g. conv2d_out)
+    outplace: NativeFunction | None
+
+    @classmethod
+    def from_pairs(
+        cls,
+        functional: PythonSignatureNativeFunctionPair,
+        out: PythonSignatureNativeFunctionPair | None,
+    ) -> PythonSignatureGroup:
+        if out is None:
+            return PythonSignatureGroup(
+                signature=functional.signature,
+                base=functional.function,
+                outplace=None,
+            )
+
+        # prefer the signature with optional out=... arguments because it's the
+        # superset that can be used to parse input for both base and outplace.
+        signature_kwargs = out.signature.__dict__.copy()
+
+        # Out overloads in C++ don't have TensorOptions arguments,
+        # so take these from the functional variant
+        signature_kwargs["tensor_options_args"] = (
+            functional.signature.tensor_options_args
+        )
+
+        return PythonSignatureGroup(
+            signature=type(out.signature)(**signature_kwargs),
+            base=functional.function,
+            outplace=out.function,
+        )
+
+
+# C++ function dispatch is wrapped in a lambda function. The lambda function
+# has almost the same signature as the C++ function, only with some small
+# variants - see details below.
+# This data model is used to represent arguments of the lambda function
+# signature.
+@dataclass(frozen=True)
+class DispatchLambdaArgument:
+    name: str
+    type_str: str
+    is_out_arg: bool
+
+
+# To pass PyObjects arguments to C++ function (via the lambda wrapper),
+# we need first convert PyObjects into simple C++ objects. This work
+# is done by PythonArgParser.
+# This data model is used to represent the output of PythonArgParser.
+# It has 1-1 mapping with PythonArgument in PythonSignature.
+@dataclass(frozen=True)
+class PythonArgParserOutputExpr:
+    # argument name
+    name: str
+
+    # RHS expression to reference PythonArgParser output.
+    expr: str
+
+    # In some special cases we need create different expr, e.g.:
+    # '_r.isNone(1)' instead of '_r.tensor(1)'.
+    index: int
+
+    # The python argument it maps to.
+    argument: PythonArgument
+
+    @property
+    def is_none_expr(self) -> str:
+        return f"_r.isNone({self.index})"
+
+
+# To pass PythonArgParser output to the lambda wrapper, we need bind
+# PythonArgParserOutputExpr to DispatchLambdaArgument.
+# They are not always 1-1 mapped, e.g. scattered TensorOptions fields
+# need be packed into a TensorOptions object, which is the argument
+# that the lambda function wrapper takes.
+@dataclass(frozen=True)
+class DispatchLambdaArgumentExprs:
+    # The exprs that provide the binding for lambda arguments, e.g.:
+    #
+    #   'self' -> '_r.tensor(0)'
+    #   'min' -> 'out[0]' / 'min_indices' -> 'out[1]'
+    #   'options' -> 'options'
+    #
+    # It has 1-1 mapping with DispatchLambdaArgument.
+    exprs: Sequence[str]
+
+    # Special local inits, which might introduce new variables that
+    # the 'exprs' above reference, e.g.:
+    #
+    #   'auto out = _r.tensorlist_n<2>(2);'
+    #
+    inits: Sequence[str]
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                          Helper Functions
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+def _cpp_signature(f: NativeFunction, *, method: bool = False) -> CppSignature:
+    return CppSignatureGroup.from_native_function(f, method=method).signature
+
+
+def has_tensor_options(f: NativeFunction) -> bool:
+    return f.func.arguments.tensor_options is not None
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                          Python Signature
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+# 'simple_type' was introduced by the old codegen, which is slightly
+# different from the python schema type, e.g.: doesn't have '?' suffix
+# for optional Tensor/TensorList; doesn't have '[size]' suffix for list type.
+def argument_type_str(
+    t: Type, *, simple_type: bool = False, symint: bool = True
+) -> str:
+    if isinstance(t, BaseType):
+        if t.name == BaseTy.int:
+            return "int64_t"
+        elif t.name == BaseTy.float:
+            return "double"
+        elif t.name == BaseTy.str:
+            return "c10::string_view"
+        elif t.name in [
+            BaseTy.Tensor,
+            BaseTy.bool,
+            BaseTy.QScheme,
+            BaseTy.Scalar,
+            BaseTy.ScalarType,
+            BaseTy.Generator,
+            BaseTy.Storage,
+            BaseTy.Layout,
+            BaseTy.Device,
+            BaseTy.DeviceIndex,
+            BaseTy.MemoryFormat,
+            BaseTy.Dimname,
+            BaseTy.Stream,
+            BaseTy.SymInt,
+        ]:
+            # These python schema type names line up with their function schema names
+            return t.name.name
+
+    elif isinstance(t, OptionalType):
+        elem = argument_type_str(t.elem, simple_type=simple_type, symint=symint)
+        return f"{elem}?"
+    elif isinstance(t, ListType):
+        size = t.size if not simple_type else None
+        if str(t.elem) == "bool":
+            assert t.size is not None
+            return f"::std::array"
+        elif str(t.elem) == "int":
+            return f"IntArrayRef[{size}]" if size is not None else "IntArrayRef"
+        elif str(t.elem) == "SymInt":
+            if symint:
+                return (
+                    f"SymIntArrayRef[{size}]" if size is not None else "SymIntArrayRef"
+                )
+            else:
+                return f"IntArrayRef[{size}]" if size is not None else "IntArrayRef"
+        elif str(t.elem) == "Tensor":
+            return f"TensorList[{size}]" if size is not None else "TensorList"
+        elif str(t.elem) == "Scalar":
+            return f"ScalarList[{size}]" if size is not None else "ScalarList"
+        elif str(t.elem) == "Tensor?":
+            if simple_type:
+                return "c10::List<::std::optional>"
+            else:
+                return "const c10::List<::std::optional> &"
+        elif str(t.elem) == "Dimname":
+            return f"DimnameList[{size}]" if size is not None else "DimnameList"
+        elem = argument_type_str(t.elem, simple_type=simple_type, symint=symint)
+        return f"ArrayRef<{elem}>"
+
+    raise RuntimeError(f"unrecognized type {repr(t)}")
+
+
+def argument_type_size(t: Type) -> int | None:
+    l = t.is_list_like()
+    if l is not None and str(l.elem) != "bool":
+        return l.size
+    else:
+        return None
+
+
+def argument(a: Argument) -> PythonArgument:
+    return PythonArgument(
+        name=a.name,
+        type=a.type,
+        # TODO: directly translate a.default to python default
+        default=(
+            str(pythonify_default(cpp.default_expr(a.default, a.type, symint=False)))
+            if a.default is not None
+            else None
+        ),
+        default_init=None,
+    )
+
+
+# Generates a PythonSignature that can be used for either .pyi or PythonArgParser codegen
+def signature(
+    f: NativeFunction, *, method: bool = False, pyi: bool = False
+) -> PythonSignature:
+    return signature_from_schema(
+        f.func, category_override=f.category_override, method=method, pyi=pyi
+    )
+
+
+def signature_from_schema(
+    func: FunctionSchema,
+    *,
+    category_override: str | None,
+    method: bool = False,
+    pyi: bool = False,
+) -> PythonSignature:
+    args: list[Argument] = []
+    args.extend(func.arguments.pre_self_positional)
+    # Skip SelfArgument if this is method.
+    if not method and func.arguments.self_arg is not None:
+        args.append(func.arguments.self_arg.argument)
+    args.extend(func.arguments.post_self_positional)
+    args.extend(func.arguments.pre_tensor_options_kwarg_only)
+    # Skip TensorOptionsArguments. Python side TensorOptions
+    # arguments are created based on different rules - see below.
+    args.extend(func.arguments.post_tensor_options_kwarg_only)
+    args.extend(func.arguments.out)
+
+    input_arg_set = {a.name for a in func.arguments.flat_positional}
+    kwarg_only_set = {a.name for a in func.arguments.flat_kwarg_only}
+    out_arg_set = {a.name for a in func.arguments.out}
+
+    input_args = tuple(map(argument, filter(lambda a: a.name in input_arg_set, args)))
+    input_kwargs = tuple(
+        map(argument, filter(lambda a: a.name in kwarg_only_set, args))
+    )
+    outputs = tuple(map(argument, filter(lambda a: a.name in out_arg_set, args)))
+
+    # Reintroduce the scattered fields of TensorOptions for Python.
+    # Compared to the cpp counterpart, the python arguments have new property
+    # (default_init) and a new argument 'requires_grad', which require some
+    # special handlings.
+    # [old codegen] TODO: because these aren't guaranteed to be 100% faithful
+    # to the original versions in the yaml, this recreation is a potential
+    # source of drift between eager and JIT. Pull this logic out to a shared place.
+
+    has_tensor_input_arg = any(
+        a.type.is_tensor_like() for a in func.arguments.flat_non_out
+    )
+    if any(a.name == "requires_grad" for a in func.schema_order_arguments()):
+        raise ValueError(
+            "argument named requires_grad is reserved, should not explicitly add it in the schema"
+        )
+
+    # [old codegen] this probably won't work if one of the returns is not a tensor,
+    # but it will produce a compile-time error that is obvious.
+    has_tensor_return = any(r.type.is_tensor_like() for r in func.returns)
+
+    name: str = cpp.name(func)
+    is_factory_function = category_override == "factory" or (
+        has_tensor_return and not has_tensor_input_arg
+    )
+    is_like_or_new_function = (
+        category_override in ("new", "like")
+        or name.startswith("new_")
+        or name.endswith("_like")
+    )
+    is_dummy_function = category_override == "dummy"
+
+    tensor_options_args: list[PythonArgument] = []
+    if (is_factory_function or is_like_or_new_function) and not is_dummy_function:
+
+        def topt_default_init(name: str) -> str | None:
+            topt_args = func.arguments.tensor_options
+            if topt_args is None:
+                return None
+            a = getattr(topt_args, name)
+            if a.default is None or a.default == "None":
+                return None
+            return cpp.default_expr(a.default, a.type, symint=False)
+
+        tensor_options_args.append(
+            PythonArgument(
+                name="dtype",
+                type=OptionalType(BaseType(BaseTy.ScalarType)),
+                default="None",
+                default_init=(
+                    None if is_like_or_new_function else topt_default_init("dtype")
+                ),
+            )
+        )
+        tensor_options_args.append(
+            PythonArgument(
+                name="layout",
+                type=OptionalType(BaseType(BaseTy.Layout)),
+                default="None",
+                default_init=(
+                    None if is_like_or_new_function else topt_default_init("layout")
+                ),
+            )
+        )
+        tensor_options_args.append(
+            PythonArgument(
+                name="device",
+                type=OptionalType(BaseType(BaseTy.Device)),
+                default="None",
+                default_init=(
+                    None
+                    if is_like_or_new_function
+                    else (
+                        topt_default_init("device")
+                        or "torch::tensors::get_default_device()"
+                    )
+                ),
+            )
+        )
+        tensor_options_args.append(
+            PythonArgument(
+                name="pin_memory",
+                type=OptionalType(BaseType(BaseTy.bool)),
+                default="False",
+                default_init=None,
+            )
+        )
+        tensor_options_args.append(
+            PythonArgument(
+                name="requires_grad",
+                type=OptionalType(BaseType(BaseTy.bool)),
+                default="False",
+                default_init=None,
+            )
+        )
+
+    returns = PythonReturns(returns=func.returns)
+
+    return PythonSignature(
+        name=str(func.name.name),
+        input_args=input_args,
+        input_kwargs=input_kwargs,
+        output_args=PythonOutArgument.from_outputs(outputs),
+        tensor_options_args=tuple(tensor_options_args),
+        returns=returns,
+        method=method,
+    )
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                          Python Interface
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+def structseq_fieldnames(returns: tuple[Return, ...]) -> list[str]:
+    if len(returns) <= 1 or all(r.name is None for r in returns):
+        return []
+    else:
+        if any(r.name is None for r in returns):
+            # When building on Windows, `PyStructSequence_UnnamedField` could not be
+            # resolved by the linker for some reason, which cause error in building:
+            #
+            # python_nn_functions.cpp.obj : error LNK2001: unresolved external symbol
+            # PyStructSequence_UnnamedField
+            #
+            # Thus, at this point in time, we do not support unnamed
+            # fields in structseq; you must either name all fields,
+            # or none of them.
+            raise ValueError("Unnamed field is not supported by codegen")
+
+        return [str(r.name) for r in returns]
+
+
+def argument_type_str_pyi(t: Type) -> str:
+    add_optional = False
+    if isinstance(t, OptionalType):
+        t = t.elem
+        add_optional = True
+
+    ret = ""
+    if isinstance(t, BaseType):
+        if t.name in [BaseTy.int, BaseTy.DeviceIndex]:
+            ret = "_int"
+        if t.name == BaseTy.SymInt:
+            ret = "_int | SymInt"
+        elif t.name == BaseTy.float:
+            ret = "_float"
+        elif t.name == BaseTy.str:
+            ret = "str"
+        elif t.name == BaseTy.Scalar:
+            ret = "Number | _complex"
+        elif t.name == BaseTy.ScalarType:
+            ret = "_dtype"
+        elif t.name == BaseTy.bool:
+            ret = "_bool"
+        elif t.name == BaseTy.QScheme:
+            ret = "_qscheme"
+        elif t.name == BaseTy.Layout:
+            ret = "_layout"
+        elif t.name == BaseTy.Device:
+            ret = "DeviceLikeType | None"
+        elif t.name == BaseTy.MemoryFormat:
+            ret = "memory_format"
+        elif t.name == BaseTy.Dimname:
+            ret = "str | EllipsisType | None"
+        elif t.name == BaseTy.Storage:
+            ret = "Storage | UntypedStorage"
+        elif t.name in [BaseTy.Tensor, BaseTy.Generator, BaseTy.Stream]:
+            # These python schema type names line up with their function schema names
+            ret = t.name.name
+
+    elif isinstance(t, ListType):
+        if str(t.elem) == "int":
+            ret = "_int | _size" if t.size is not None else "_size"
+        elif t.is_tensor_like():
+            # TODO: this doesn't seem right...
+            # Tensor?[] currently translates to tuple[Tensor, ...] | list[Tensor] | None
+            # It should probably translate to   tuple[Tensor | None, ...] | list[Tensor | None]
+            add_optional = True
+            ret = (
+                "Tensor | tuple[Tensor, ...] | list[Tensor]"
+                if t.size is not None
+                else "tuple[Tensor, ...] | list[Tensor]"
+            )
+        elif str(t.elem) == "float":
+            ret = "Sequence[_float]"
+        elif str(t.elem) == "SymInt" and t.size is not None:
+            elem = argument_type_str_pyi(t.elem)
+            ret = f"{elem} | Sequence[{elem}]"
+        else:
+            elem = argument_type_str_pyi(t.elem)
+            ret = f"Sequence[{elem}]"
+
+    else:
+        raise RuntimeError(f"unrecognized type {repr(t)}")
+
+    if add_optional:
+        ret = f"{ret} | None".replace(" | None | None", " | None")
+
+    return ret
+
+
+def return_type_str_pyi(t: Type) -> str:
+    # Where arguments are open to accepting Union, return types should return
+    # concrete types
+
+    if isinstance(t, OptionalType):
+        inner = return_type_str_pyi(t.elem)
+        return f"{inner} | None".replace(" | None | None", " | None")
+
+    if isinstance(t, BaseType):
+        if t.name == BaseTy.Device:
+            return "_device"
+        elif t.name == BaseTy.Dimname:
+            return "str | None"
+        else:
+            return argument_type_str_pyi(t)
+
+    if isinstance(t, ListType):
+        inner = return_type_str_pyi(t.elem)
+        return f"tuple[{inner}, ...]"
+
+    return argument_type_str_pyi(t)
+
+
+def returns_structseq_pyi(signature: PythonSignature) -> tuple[str, str] | None:
+    python_returns = [return_type_str_pyi(r.type) for r in signature.returns.returns]
+    structseq_name = signature.name
+    field_names = structseq_fieldnames(signature.returns.returns)
+    if field_names:
+        # These types are structseq objects which act like named NamedTuples, but
+        # the constructor acts like the constructor of tuple. Using typing.NamedTuple
+        # does not allow us to override __init__.
+        seq_type = f"tuple[{', '.join(python_returns)}]"
+        structseq_def_lines = [
+            f"class {structseq_name}({seq_type}):  # fmt: skip",
+        ]
+        for name, ret_type in zip(field_names, python_returns):
+            structseq_def_lines.extend(
+                [
+                    "    @property",
+                    f"    def {name}(self) -> {ret_type}: ...",
+                ]
+            )
+        structseq_def_lines.extend(
+            [
+                "    def __new__(",
+                "        cls,",
+                f"        sequence: {seq_type},",
+                "    ) -> Self:  # fmt: skip",
+                "        ...",
+                f"    n_fields: Final[_int] = {len(field_names)}",
+                f"    n_sequence_fields: Final[_int] = {len(field_names)}",
+                "    n_unnamed_fields: Final[_int] = 0",
+                "    def __init_subclass__(cls) -> NoReturn: ...  # prohibit subclassing",
+                "",  # add an extra newline
+            ]
+        )
+        structseq_def = "\n".join(structseq_def_lines)
+        # Example:
+        # structseq_def = (
+        #     "class max(tuple[Tensor, Tensor]):  # fmt: skip\n"
+        #     "    @property\n"
+        #     "    def values(self) -> Tensor: ...\n"
+        #     "    @property\n"
+        #     "    def indices(self) -> Tensor: ...\n"
+        #     "    def __new__(\n"
+        #     "        cls,\n"
+        #     "        sequence: tuple[Tensor, Tensor],\n"
+        #     "    ) -> Self:  # fmt: skip\n"
+        #     "        ...\n"
+        #     "    n_fields: Final[_int] = 2",
+        #     "    n_sequence_fields: Final[_int] = 2",
+        #     "    n_unnamed_fields: Final[_int] = 0",
+        #     "    def __init_subclass__(cls) -> NoReturn: ...  # prohibit subclassing",
+        # )
+        return structseq_name, structseq_def
+    return None
+
+
+def returns_str_pyi(signature: PythonSignature) -> str:
+    field_names = structseq_fieldnames(signature.returns.returns)
+    if field_names:
+        return f"torch.return_types.{signature.name}"
+
+    python_returns = [return_type_str_pyi(r.type) for r in signature.returns.returns]
+    if len(python_returns) > 1:
+        return "tuple[" + ", ".join(python_returns) + "]"
+    if len(python_returns) == 1:
+        return python_returns[0]
+    return "None"
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                        C++ Function Dispatch
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+# This section provides APIs to generate the code that does C++ function
+# dispatch. The C++ function call is wrapped by a lambda function.
+# For example:
+#
+#    // aten::selu_(Tensor(a!) self) -> Tensor(a!)
+#    auto dispatch_selu_ = [](Tensor self) -> Tensor {
+#      pybind11::gil_scoped_release no_gil;
+#      return at::selu_(self);
+#    };
+#
+# The lambda function's signature follows the C++ signature in common
+# cases, e.g.:
+#
+#   // aten::add.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor
+#   [](const Tensor & self, const Tensor & other, Scalar alpha) -> Tensor
+#
+# For out variant the 'out' argument's type is changed from 'Tensor &'
+# to 'Tensor'. It's because when calling the lambda it passes in the
+# PythonArgParser output '_r.tensor(3)', which is stack allocated object
+# and needs to pass by value. Also see comments in 'dispatch_lambda_return_str()'.
+#
+#   // aten::add.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+#   [](Tensor out, const Tensor & self, const Tensor & other, Scalar alpha) -> Tensor
+#
+# For multi-output case it can keep using reference type because the
+# PythonArgParser output has been unpacked to local variables, e.g.:
+#
+#   // aten::max.names_dim_max(Tensor self, Dimname dim, bool keepdim=False, *,
+#   //     Tensor(a!) max, Tensor(b!) max_values) -> (Tensor(a!) values, Tensor(b!) indices)
+#   [](Tensor & max, Tensor & max_values, const Tensor & self, Dimname dim, bool keepdim) -> std::tuple
+#
+# For deprecated python signature, it should follow deprecated python arg order.
+# TODO: This is to keep same byte-for-byte result as the old codegen - maybe unnecessary?
+
+
+def dispatch_lambda_args(
+    ps: PythonSignature, f: NativeFunction, symint: bool = True
+) -> tuple[DispatchLambdaArgument, ...]:
+    if isinstance(ps, PythonSignatureDeprecated):
+        schema = ps.deprecated_schema
+    else:
+        schema = f.func
+
+    # Start with cpp arguments - dispatch lambda signature always include 'self'
+    cpp_args = cpp.arguments(
+        arguments=schema.arguments,
+        faithful=False,
+        symint=symint,
+        method=False,
+        cpp_no_default_args=f.cpp_no_default_args,
+    )
+    out_args: set[str] = {a.name for a in schema.arguments.out}
+
+    # Convert from cpp argument to lambda argument
+    def dispatch_lambda_arg(cpp_arg: Binding) -> DispatchLambdaArgument:
+        type_str = cpp_arg.type
+        is_out_arg = cpp_arg.name in out_args
+        if ps.method and cpp_arg.name == "self":
+            # For method's 'self', we can use 'const Tensor &' and simply ignore mutability!
+            type_str = "const at::Tensor &"
+        else:
+            # For other cases we need prevent dangling refs to temps (unless it's
+            # unpacked scattered output)
+            # The reason is explained in the comments above and in 'dispatch_lambda_return_str()'.
+            # TODO: avoid this special handling?
+            ensure_temp_safe = len(out_args) <= 1 or not is_out_arg
+            if ensure_temp_safe:
+                type_str = {
+                    "at::Tensor &": "at::Tensor",
+                }.get(type_str, type_str)
+        return DispatchLambdaArgument(
+            name=cpp_arg.name,
+            type_str=type_str,
+            is_out_arg=is_out_arg,
+        )
+
+    return tuple(map(dispatch_lambda_arg, cpp_args))
+
+
+# [old codegen] XXX: if you got here because of an assertion failure, it doesn't mean
+# it's enough to just extend the list here. Before you do this, make sure
+# to add an appropriate wrap() overload in torch/csrc/autograd/utils/wrap_outputs.h.
+SUPPORTED_RETURN_TYPES = {
+    "at::Tensor",
+    "::std::tuple",
+    "::std::tuple",
+    "::std::tuple",
+    "::std::tuple",
+    "::std::tuple",
+    "::std::tuple",
+    "::std::tuple",
+    "::std::tuple",
+    "::std::tuple",
+    "::std::tuple",
+    "::std::tuple>",
+    "::std::vector",
+    # Needed for flash attention forw/backward
+    "::std::tuple",
+    "at::Scalar",
+    "bool",
+    "int64_t",
+    "void*",
+    "void",
+    "at::QScheme",
+    "double",
+    "at::IntArrayRef",
+    "at::ScalarType",
+    "at::Stream",
+}
+
+
+def dispatch_lambda_return_str(f: NativeFunction) -> str:
+    # [old codegen] Remove type annotation (e.g. 'Tensor' rather than 'Tensor &')
+    # because the dispatch lambdas take mutable arguments *by value*, not
+    # by reference. If you then return a reference to such an argument, you
+    # will now have a pointer to a dangling stack entry. Not good.
+    #
+    # You want:
+    #
+    #   auto dispatch_selu_ = [](Tensor self) -> Tensor { ...; return at::selu_(self); };
+    #                                            ^^^^^^
+    #
+    # *not*
+    #
+    #   auto dispatch_selu_ = [](Tensor self) -> Tensor& { ...; return at::selu_(self); };
+    #                                            ^^^^^^^
+    #
+    # (NB: We can't make dispatch_selu_ take Tensor&, because the enclosing
+    # codegen looks like dispatch_selu_(_r.tensor(0)), and you can't take a
+    # mutable reference to temporary.  Maybe we could assign it to a
+    # variable itself.)
+    returns_without_annotation = tuple(
+        Return(r.name, r.type, None) for r in f.func.returns
+    )
+    return_str = cpp.returns_type(returns_without_annotation, symint=True).cpp_type()
+    if return_str not in SUPPORTED_RETURN_TYPES:
+        raise RuntimeError(f"{f.func.name} returns unsupported type {return_str}")
+    return return_str
+
+
+def cpp_dispatch_target(f: NativeFunction) -> str:
+    symint = f.func.has_symint()
+    name = cpp.name(f.func, symint_overload=symint)
+    if Variant.method in f.variants:
+        return f"self.{name}"
+    if Variant.function in f.variants:
+        if has_tensor_options(f) or f.func.name.name.base.endswith("_like"):
+            namespace = "torch"
+        else:
+            namespace = "at"
+        return f"{namespace}::{name}"
+    raise RuntimeError(f"could not dispatch, neither function nor method: {f.func}")
+
+
+def cpp_dispatch_exprs(
+    f: NativeFunction,
+    *,
+    python_signature: PythonSignature | None = None,
+) -> tuple[str, ...]:
+    cpp_args: Sequence[Binding] = _cpp_signature(f, method=False).arguments()
+
+    exprs: tuple[str, ...] = ()
+    if not isinstance(python_signature, PythonSignatureDeprecated):
+        # By default the exprs are consistent with the C++ signature.
+        exprs = tuple(a.name for a in cpp_args)
+    else:
+        # For deprecated python signature we may need fill in some constants.
+        exprs = tuple(
+            filter(
+                lambda n: n != "out" or f.func.is_out_fn(),
+                python_signature.deprecated_args_exprs,
+            )
+        )
+
+    if Variant.method in f.variants:
+        exprs = tuple(filter("self".__ne__, exprs))
+
+    return exprs
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                     Python / C++ Args Binding
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+# We explicitly enumerate the PythonArgParser unpacking methods for all
+# supported types. This might be more verbose than necessary, partially
+# because of the irregularity of unpacking method naming, partially
+# because we want to mimic the old codegen behavior - to reject
+# unexpected and/or unsupported cases which the old codegen rejects.
+# For certain cases it is intentionally more restrictive than necessary,
+# e.g.: it doesn't accepts doublelist with definite size.
+def arg_parser_unpack_method(
+    t: Type, default: str | None, default_init: str | None, *, symint: bool = True
+) -> str:
+    has_default_init = default_init is not None
+    if has_default_init and str(t) not in (
+        "ScalarType?",
+        "ScalarType",
+        "Device",
+        "Device?",
+        "Layout",
+        "Layout?",
+        "bool",
+        "bool?",
+    ):
+        raise RuntimeError(f"type '{t}' does not supported unpacking with default")
+
+    if isinstance(t, BaseType):
+        if t.name in [
+            BaseTy.Tensor,
+            BaseTy.Stream,
+            BaseTy.Storage,
+            BaseTy.Scalar,
+            BaseTy.Dimname,
+        ]:
+            # These unpack methods line up with their schema names
+            return t.name.name.lower()
+        elif t.name == BaseTy.ScalarType:
+            return "scalartypeWithDefault" if has_default_init else "scalartype"
+        elif t.name == BaseTy.Device:
+            return "deviceWithDefault" if has_default_init else "device"
+        elif t.name == BaseTy.DeviceIndex:
+            return "toInt64"
+        elif t.name == BaseTy.int:
+            return "toInt64"
+        elif t.name == BaseTy.SymInt:
+            return "toSymInt" if symint else "toInt64"
+        elif t.name == BaseTy.bool:
+            return "toBoolWithDefault" if has_default_init else "toBool"
+        elif t.name == BaseTy.float:
+            return "toDouble"
+        elif t.name == BaseTy.str:
+            return "stringView"
+        elif t.name == BaseTy.Layout:
+            return "layoutWithDefault" if has_default_init else "layout"
+        elif t.name == BaseTy.MemoryFormat:
+            return "memoryformat"
+
+    elif isinstance(t, OptionalType):
+        if str(t.elem) == "Tensor":
+            return "optionalTensor"
+        elif str(t.elem) == "Generator":
+            return "generator"
+        elif str(t.elem) == "Dimname[]":
+            return "toDimnameListOptional"
+        elif not has_default_init and default in (
+            None,
+            "None",
+            "::std::nullopt",
+            "std::nullopt",
+        ):
+            # If default is None: append 'Optional' to elem's unpacking method
+            return (
+                arg_parser_unpack_method(t.elem, None, None, symint=symint) + "Optional"
+            )
+        else:
+            # Otherwise, load as underlying type with default
+            return arg_parser_unpack_method(
+                t.elem, default, default_init, symint=symint
+            )
+
+    elif isinstance(t, ListType):
+        if str(t.elem) == "Tensor":
+            # accept and use definite size
+            return f"tensorlist_n<{t.size}>" if t.size is not None else "tensorlist"
+        elif str(t.elem) == "Tensor?":
+            return "list_of_optional_tensors"
+        elif str(t.elem) == "Dimname":
+            # accept definite size
+            return "dimnamelist"
+        elif str(t.elem) == "int":
+            # accept definite size
+            return "intlist"
+        elif str(t.elem) == "float":
+            return "doublelist"
+        elif str(t.elem) == "SymInt":
+            # accept definite size
+            return "symintlist" if symint else "intlist"
+        elif str(t.elem) == "Scalar":
+            return "scalarlist"
+    raise RuntimeError(f"type '{t}' is not supported by PythonArgParser")
+
+
+# Return RHS expression for python argument using PythonArgParser output.
+# e.g. for arg name 'foo', arg type 'bool', arg_index = 2, returns '_r.toBool(2)'
+def arg_parser_output_expr(
+    arg_index: int, a: PythonArgument, *, symint: bool = True
+) -> PythonArgParserOutputExpr:
+    has_default = a.default_init is not None
+    unpack_method = arg_parser_unpack_method(
+        t=a.type, default=a.default, default_init=a.default_init, symint=symint
+    )
+    default = f", {a.default_init}" if has_default else ""
+    expr = f"_r.{unpack_method}({arg_index}{default})"
+
+    return PythonArgParserOutputExpr(
+        name=a.name,
+        expr=expr,
+        index=arg_index,
+        argument=a,
+    )
+
+
+# Returns a map with key = arg_name and value = PythonArgParserOutputExpr.
+def arg_parser_output_exprs(
+    ps: PythonSignature, f: NativeFunction, *, symint: bool = True
+) -> dict[str, PythonArgParserOutputExpr]:
+    return {
+        e.name: e
+        for i, a in enumerate(ps.arguments())
+        for e in (arg_parser_output_expr(i, a, symint=symint),)
+    }
+
+
+# argument name to type for scattered tensor options fields
+TENSOR_OPTIONS_FIELDS = {
+    "dtype": "ScalarType?",
+    "device": "Device?",
+    "layout": "Layout?",
+    "pin_memory": "bool?",
+    "requires_grad": "bool?",
+}
+
+
+# bind arg parser outputs (python args) with dispatch lambda arguments (c++ args).
+def dispatch_lambda_exprs(
+    ps: PythonSignature, f: NativeFunction, *, symint: bool = True
+) -> DispatchLambdaArgumentExprs:
+    # This method is to bind 'arg_parser_outputs' and 'lambda_args' by producing
+    # 'inits' and 'lambda_args_exprs' for each lambda argument using arg parser
+    # outputs.
+    arg_parser_outputs = arg_parser_output_exprs(ps, f, symint=symint)
+    lambda_args = dispatch_lambda_args(ps, f, symint=symint)
+    inits: list[str] = []
+    lambda_args_exprs: dict[str, str] = {}
+
+    has_toptions = has_tensor_options(f)
+
+    # 1. special inits/unpacking to provide binding exprs for lambda arguments.
+    for a in ps.arguments(skip_tensor_options=True):
+        name = a.name
+        arg_parser_expr = arg_parser_outputs[a.name].expr
+
+        if has_toptions and name == "self":
+            # TODO: why this needs to be special case?
+            inits.extend(
+                [
+                    f"auto self = {arg_parser_expr};",
+                ]
+            )
+            lambda_args_exprs[name] = name
+        elif (
+            isinstance(a, PythonOutArgument)
+            and len(a.outputs) > 1
+            and f.func.is_out_fn()
+        ):
+            inits.extend(
+                [
+                    f"auto out = {arg_parser_expr};",
+                ]
+            )
+            for i, out_arg in enumerate(a.outputs):
+                lambda_args_exprs[out_arg.name] = f"out[{i}]"
+        elif str(a.type) == "Dimname[]?":
+            # [old codegen]
+            # TODO: make this part of something more general, or get rid of it.
+            # optional> are special. The PythonArgParser returns an
+            # optional>, which cannot be implicitly converted to
+            # optional>. One needs to unwrap the optional and rewrap.
+            inits.extend(
+                [
+                    f"auto __{name} = {arg_parser_expr};",
+                    f"::std::optional {name} = __{name} ? ::std::make_optional(DimnameList(__{name}.value())) : ::std::nullopt;",  # noqa: B950
+                ]
+            )
+            lambda_args_exprs[name] = name
+        else:
+            # default case - directly using PythonArgParser output expr
+            lambda_args_exprs[name] = arg_parser_expr
+
+    # method's self is passed directly to python binding, rather than parsed
+    if ps.method:
+        lambda_args_exprs["self"] = "self"
+
+    # 2. special packing/checking for TensorOptions.
+    tensor_options_args_names = [a.name for a in ps.tensor_options_args]
+    if has_toptions:
+        if f.func.is_out_fn():
+            raise RuntimeError(f"{f.func}: tensor options with output arg")
+        for a in ps.tensor_options_args:
+            if a.name not in TENSOR_OPTIONS_FIELDS:
+                raise RuntimeError(
+                    f"{f.func}: unrecognized tensor options field '{a.name}' in python binding arguments"
+                )
+            if str(a.type) != TENSOR_OPTIONS_FIELDS.get(a.name):
+                raise RuntimeError(
+                    f"{f.func}: unrecognized type '{str(a.type)}' for tensor options field '{a.name}'"
+                )
+        if not all(a in tensor_options_args_names for a in TENSOR_OPTIONS_FIELDS):
+            raise RuntimeError(
+                f"{f.func}: incomplete tensor options args: {tensor_options_args_names}"
+            )
+
+        inits.append(
+            f"""\
+const auto options = TensorOptions()
+    .dtype({arg_parser_outputs["dtype"].expr})
+    .device({arg_parser_outputs["device"].expr})
+    .layout({arg_parser_outputs["layout"].expr})
+    .requires_grad({arg_parser_outputs["requires_grad"].expr})
+    .pinned_memory({arg_parser_outputs["pin_memory"].expr});
+torch::utils::maybe_initialize_device(options);
+"""
+        )
+        lambda_args_exprs["options"] = "options"
+
+    # 3. special case - access scattered TensorOptions fields without packing
+    # TODO: maybe move to the generator side as it's not related to binding.
+    if not has_toptions and tensor_options_args_names:
+        if "dtype" in tensor_options_args_names:
+            # we're an output-arg variant, check these args against output tensor
+            if not f.func.is_out_fn():
+                raise RuntimeError(
+                    f"{f.func}: dtype in tensor_options_args without output arg, {ps} {ps.arguments}"
+                )
+            if not all(a in tensor_options_args_names for a in ("layout", "device")):
+                raise RuntimeError(
+                    f"{f.func}: incomplete tensor options for output check"
+                )
+
+            inits.append(
+                f"""\
+check_out_type_matches({arg_parser_outputs["out"].expr}, {arg_parser_outputs["dtype"].expr},
+                       {arg_parser_outputs["dtype"].is_none_expr}, {arg_parser_outputs["layout"].expr},
+                       {arg_parser_outputs["device"].expr}, {arg_parser_outputs["device"].is_none_expr});
+"""
+            )
+        # we'll set requires_grad on outgoing tensor
+        if "requires_grad" not in tensor_options_args_names:
+            raise RuntimeError(
+                f'{f.func}: expected "requires_grad" in tensor_options_args absent, but found [{tensor_options_args_names}]'
+            )
+
+    return DispatchLambdaArgumentExprs(
+        exprs=tuple(lambda_args_exprs[a.name] for a in lambda_args),
+        inits=inits,
+    )
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/structured.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/structured.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0e14e5b69e6421fce5ddd247958876061d72b2c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/structured.py
@@ -0,0 +1,158 @@
+from __future__ import annotations
+
+from typing_extensions import assert_never
+
+from torchgen.api import cpp
+from torchgen.api.types import (
+    ArgName,
+    ArrayRefCType,
+    BaseCType,
+    Binding,
+    ConstRefCType,
+    dimnameListT,
+    intArrayRefT,
+    iOptTensorListRefT,
+    iTensorListRefT,
+    NamedCType,
+    OptionalCType,
+    optionalIntArrayRefT,
+    optionalScalarRefT,
+    optionalTensorRefT,
+    scalarT,
+    tensorT,
+)
+from torchgen.model import (
+    Argument,
+    BaseTy,
+    BaseType,
+    ListType,
+    NativeFunctionsGroup,
+    OptionalType,
+    SelfArgument,
+    TensorOptionsArguments,
+    Type,
+)
+
+
+# This file describes the translation of JIT schema to the structured functions API.
+# This is similar to native API, but a number of historical problems with native
+# API have been fixed.
+
+
+# Translation of types occurring in JIT arguments to a C++ argument type.
+# NB: For now, mutable doesn't do anything; but it could if we make
+# some more nominal types
+def argumenttype_type(t: Type, *, mutable: bool, binds: ArgName) -> NamedCType:
+    # If it's a value type, do the value type translation
+    # NB: structured kernels ALWAYS have symint off, since they involve actual
+    # kernels that require real ints.  The one exception is the
+    # CompositeExplicitAutograd and the meta function (which could
+    # hypothetically be SymInt), but for simplicity we plan for these to just
+    # be handled in Python
+    r = cpp.valuetype_type(t, symint=False, binds=binds, mutable=mutable)
+    if r is not None:
+        return r
+
+    if isinstance(t, BaseType):
+        if t.name == BaseTy.Tensor:
+            return NamedCType(binds, ConstRefCType(BaseCType(tensorT)))
+        elif t.name == BaseTy.Scalar:
+            return NamedCType(binds, ConstRefCType(BaseCType(scalarT)))
+        else:
+            raise AssertionError(f"base type should have been value type {t}")
+    elif isinstance(t, OptionalType):
+        if t.elem == BaseType(BaseTy.Tensor):
+            return NamedCType(binds, BaseCType(optionalTensorRefT))
+        elif t.elem == BaseType(BaseTy.Scalar):
+            return NamedCType(binds, BaseCType(optionalScalarRefT))
+        elif isinstance(t.elem, ListType) and str(t.elem.elem) == "int":
+            return NamedCType(binds, BaseCType(optionalIntArrayRefT))
+        elem = argumenttype_type(t.elem, mutable=mutable, binds=binds)
+        return NamedCType(binds, OptionalCType(elem.type))
+    elif isinstance(t, ListType):
+        if t.elem == BaseType(BaseTy.Tensor):
+            return NamedCType(binds, ConstRefCType(BaseCType(iTensorListRefT)))
+        elif t.elem == OptionalType(BaseType(BaseTy.Tensor)):
+            return NamedCType(binds, BaseCType(iOptTensorListRefT))
+        # TODO: delete these special cases; see torchgen.api.cpp--these
+        # must be changed in tandem, but there are problems; see
+        # https://github.com/pytorch/pytorch/pull/51485
+        elif str(t.elem) == "int":
+            return NamedCType(binds, BaseCType(intArrayRefT))
+        elif str(t.elem) == "Dimname":
+            return NamedCType(binds, BaseCType(dimnameListT))
+        elem = argumenttype_type(t.elem, mutable=mutable, binds=binds)
+        return NamedCType(binds, ArrayRefCType(elem.type))
+    else:
+        raise AssertionError(f"unrecognized type {repr(t)}")
+
+
+def argument_type(a: Argument, *, binds: ArgName) -> NamedCType:
+    return argumenttype_type(a.type, mutable=a.is_write, binds=binds)
+
+
+# returns_type intentionally omitted, because structured kernels never "return";
+# instead, they always indirectly report their outputs (in the case of a meta
+# function, by calling set_output; in the case of an impl function, by writing
+# directly into the provided out argument).
+
+
+# Structured kernels are never defaulted
+def argument(a: Argument | SelfArgument | TensorOptionsArguments) -> list[Binding]:
+    if isinstance(a, Argument):
+        return [
+            Binding(
+                nctype=argument_type(a, binds=a.name),
+                name=a.name,
+                default=None,
+                argument=a,
+            )
+        ]
+    elif isinstance(a, SelfArgument):
+        return argument(a.argument)
+    elif isinstance(a, TensorOptionsArguments):
+        raise AssertionError("structured kernels don't support TensorOptions yet")
+    else:
+        assert_never(a)
+
+
+def impl_arguments(g: NativeFunctionsGroup) -> list[Binding]:
+    args: list[Argument | TensorOptionsArguments | SelfArgument] = []
+
+    if g.out.precomputed:
+        # A list of parameters for the impl function with
+        # certain parameters replaced with precomputed counterparts
+        # as specified in native_functions.yaml.
+        non_out_args_replaced: list[
+            Argument | TensorOptionsArguments | SelfArgument
+        ] = []
+        for a in g.out.func.arguments.non_out:
+            if isinstance(a, Argument) and a.name in g.out.precomputed.replace:
+                # If a is in precompute.replace, append the parameters
+                # that should replace it onto non_out_args_replaced.
+                non_out_args_replaced.extend(g.out.precomputed.replace[a.name])
+            else:
+                # If not, push a as it is.
+                non_out_args_replaced.append(a)
+
+        args.extend(non_out_args_replaced)
+        # g.out.precomputed.add is the list of parameters that are added
+        # without replacement after the non out args and just before the out args
+        args.extend(g.out.precomputed.add)
+    else:
+        args.extend(g.out.func.arguments.non_out)
+
+    args.extend(g.out.func.arguments.out)
+    return [r for arg in args for r in argument(arg)]
+
+
+def meta_arguments(g: NativeFunctionsGroup) -> list[Binding]:
+    args: list[Argument | TensorOptionsArguments | SelfArgument] = []
+    args.extend(g.functional.func.arguments.non_out)
+    return [r for arg in args for r in argument(arg)]
+
+
+def out_arguments(g: NativeFunctionsGroup) -> list[Binding]:
+    args: list[Argument | TensorOptionsArguments | SelfArgument] = []
+    args.extend(g.out.func.arguments.out)
+    return [r for arg in args for r in argument(arg)]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/translate.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/translate.py
new file mode 100644
index 0000000000000000000000000000000000000000..f98ce09bbfafb875a619ea01eae7b6f82d76ef71
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/translate.py
@@ -0,0 +1,437 @@
+from __future__ import annotations
+
+from typing import NoReturn, TYPE_CHECKING
+
+from torchgen.api.types import (
+    ArrayRefCType,
+    BaseCType,
+    Binding,
+    boolT,
+    ConstRefCType,
+    deviceT,
+    Expr,
+    intArrayRefT,
+    iOptTensorListRefT,
+    layoutT,
+    ListCType,
+    longT,
+    memoryFormatT,
+    MutRefCType,
+    NamedCType,
+    opmath_t,
+    OptionalCType,
+    optionalIntArrayRefT,
+    optionalScalarRefT,
+    optionalSymIntArrayRefT,
+    optionalTensorRefT,
+    scalar_t,
+    scalarT,
+    scalarTypeT,
+    SpecialArgName,
+    symIntArrayRefT,
+    SymIntT,
+    tensorOptionsT,
+    tensorT,
+    VectorCType,
+)
+
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+
+
+# This file implements a small program synthesis engine that implements
+# conversions between one API to another.
+#
+# The key data type in this file in NamedCType, short for Named C++ semantic type.  A NamedCType
+# represents a C++ type, plus semantic information about what it represents.
+# For example, consider the argument "bool pin_memory"; its normal C++ type is
+# "bool", but its C++ semantic type also keeps track that this represents a
+# "pin_memory"; you can't just use a random other boolean in a context where you
+# need a "pin_memory"!
+#
+# The translator takes a list of needed NamedCTypes, and then figures out how
+# to construct expressions with these NamedCTypes from the given bindings.  Many
+# of these expressions are trivial (I need a Tensor other; there's a Tensor
+# other scope); others are more nontrivial and may require packing/unpacking.
+# Some examples of non-trivial action:
+#
+#   - Need the "dtype" binding?  Well, maybe "dtype" isn't available
+#     in the context, instead, "options" is, and you need to extract
+#     it from there.  (Gather)
+#
+#   - Need the "context" binding?  Well, maybe "context" isn't available
+#     in the context, and you need to construct it from "dtype", "device",
+#     etc.  (Scatter)
+#
+#   - Need the "memory_format" binding?  Well, actually, it's available
+#     from both "memory_format" and "options", so you had better make sure
+#     they are consistent.  (Join)
+
+options_ctype = NamedCType("options", ConstRefCType(BaseCType(tensorOptionsT)))
+
+out_tensor_ctype = NamedCType("out", ConstRefCType(BaseCType(tensorT)))
+
+longVec_ctype = VectorCType(BaseCType(longT))
+longSymVec_ctype = VectorCType(BaseCType(SymIntT))
+optionalLongVec_ctype = OptionalCType(VectorCType(BaseCType(longT)))
+optionalScalar_ctype = OptionalCType(BaseCType(scalarT))
+optionalTensor_ctype = OptionalCType(BaseCType(tensorT))
+
+
+class UnsatError(RuntimeError):
+    pass
+
+
+# Given a set of in-scope bindings and a set of target bindings, synthesize
+# a list of expressions that uses only the in-scope bindings (bindings) that
+# have all of the types of goals.  You may want to use this function if
+# you're generating code for a function like:
+#
+#   void f({args}) {
+#     g({exprs}); // g is a different API
+#   }
+#
+# and you need to generate "exprs".
+#
+# Typically, a list of Bindings is convenient to get (you usually call something
+# like arguments() to get them); but technically you only need less information:
+# for 'bindings' an (un-ordered) list of Exprs is sufficient; similarly, for
+# 'goals', an (ordered) list of NamedCType goals is sufficient.  If you are doing
+# something more complicated, e.g., tracking the set of bindings in a context,
+# you may find using these smaller types more convenient.
+def translate(
+    bindings: Sequence[Expr | Binding],
+    goals: Sequence[NamedCType | Binding],
+    *,
+    method: bool = False,
+    allow_expensive_conversions: bool = False,
+) -> list[Expr]:
+    binding_exprs: list[Expr] = []
+    for b in bindings:
+        if isinstance(b, Binding):
+            binding_exprs.append(
+                Expr(
+                    expr=b.name,
+                    type=b.nctype,
+                )
+            )
+        else:
+            binding_exprs.append(b)
+
+    goal_ctypes: list[NamedCType] = []
+    for g in goals:
+        if isinstance(g, Binding):
+            goal_ctypes.append(g.nctype)
+        else:
+            goal_ctypes.append(g)
+
+    # Add all the bindings to the context
+    ctx: dict[NamedCType, str] = {}
+    for b in binding_exprs:
+        ctx[b.type] = b.expr
+
+        # While we're at it, do some simple forward inference, looking through
+        # constructors.
+        #
+        # NB: When should you do forward inference versus backward inference?
+        # The general idea:
+        #
+        #   - Backward inference WHEN the goal gets smaller
+        #   - Forward inference WHEN the hypothesis gets smaller
+        #
+        # This helps ensure termination: backward inference starts with a goal
+        # and tries to make it simpler and simpler until it's trivial; if the
+        # goal can grow in size, we blow up to a really huge goal size.
+        # Similarly, with forward inference we take hypotheses and decompose
+        # them into simpler hypotheses; if hypotheses could expand in size,
+        # we also have potential nontermination.  (In the code below, forward
+        # inference is only ever carried out at a single step, but you could
+        # imagine repeated application of forward inference being profitable.)
+        #
+        # A good starting point in the literature for exploring more about proof
+        # search are these lecture notes
+        # https://www.cs.cmu.edu/~fp/courses/oregon-m10/04-focusing.pdf
+        #
+        # TODO: My kingdom for a pattern matcher
+        # https://www.python.org/dev/peps/pep-0634/
+        #
+        # TODO: This could get us in recomputation trouble if b.expr is nontrivial.
+        # Fix this by implementing some sort of sharing so that if multiple
+        # goals share the same expression, we only compute it once.  This seems
+        # to matter in practice as compiler is often unwilling to CSE nontrivial
+        # expressions like scalar.to()
+        t = b.type
+        if (
+            isinstance(t, ConstRefCType)
+            and isinstance(t.elem, OptionalCType)
+            and isinstance(t.elem.elem, BaseCType)
+            and str(t.elem.elem.type) == "at::Tensor"
+        ):
+            ctx[NamedCType(t.elem.elem.name, ConstRefCType(BaseCType(tensorT)))] = (
+                f"({b.expr}.has_value() ? *{b.expr} : at::Tensor())"
+            )
+
+        if t.type == ConstRefCType(OptionalCType(BaseCType(tensorT))):
+            ctx[NamedCType(t.name, BaseCType(optionalTensorRefT))] = (
+                f"(({b.expr}.has_value() && (*{b.expr}).defined()) ? at::OptionalTensorRef(*{b.expr}) : at::OptionalTensorRef())"
+            )
+
+        if t.type == ConstRefCType(BaseCType(scalarT)):
+            ctx[NamedCType(t.name, BaseCType(opmath_t))] = f"({b.expr}).to()"
+
+        if t.type == ConstRefCType(OptionalCType(BaseCType(scalarT))):
+            ctx[NamedCType(t.name, BaseCType(optionalScalarRefT))] = (
+                f"({b.expr}.has_value() ? at::OptionalScalarRef(&({b.expr}.value())) : at::OptionalScalarRef())"
+            )
+
+        if t.type == BaseCType(scalar_t):
+            ctx[NamedCType(t.name, BaseCType(opmath_t))] = (
+                f"static_cast({b.expr})"
+            )
+
+        # [Note: IOptTensorListRef]
+        if t.type == ConstRefCType(ListCType(OptionalCType(BaseCType(tensorT)))):
+            ctx[NamedCType(t.name, BaseCType(iOptTensorListRefT))] = (
+                f"at::IOptTensorListRef({b.expr})"
+            )
+
+    # Add implicit bindings if the generated code is inside a Tensor method
+    if method:
+        ctx[NamedCType("self", MutRefCType(BaseCType(tensorT)))] = (
+            "const_cast(*this)"
+        )
+        ctx[NamedCType("self", ConstRefCType(BaseCType(tensorT)))] = (
+            "const_cast(*this)"
+        )
+        # This is better!  Byte-for-byte compat
+        # ctx[NamedCType("self", ConstRefCType(BaseCType(tensorT)))] = "*this"
+
+    def unsat(goal: NamedCType) -> NoReturn:
+        ctx_desc = "\n".join(
+            f"  {t.cpp_type()} {t.name}; // {e}" for t, e in ctx.items()
+        )
+        raise UnsatError(
+            f"""
+Failed to synthesize the expression "{goal.cpp_type()} {goal.name}".
+When I failed, the following bindings were available in the context:
+
+{ctx_desc}
+
+This probably means there is a missing rule in the rules of torchgen.api.translate.
+Check this module for more information.
+"""
+        )
+
+    # A shitty backtracking search implementation.  It's shitty because it
+    # does backtracking via stack (bad idea!) and for the most part tries to
+    # avoid backtracking.  In particular, if
+    # direct=True, we won't try to do any fancy synthesis, just trivial
+    # conversions (e.g., "T a" is OK for "const T& a").  So all of the
+    # existing rules in this function simply try to solve immediately,
+    # and bail if things don't work out.
+    def solve(goal: NamedCType, *, direct: bool) -> str:
+        def direct_solve(goal: NamedCType) -> str:
+            return solve(goal, direct=True)
+
+        if goal in ctx:
+            # Trivial
+            return ctx[goal]
+
+        # const & is satisfied with mutable &
+        if isinstance(goal.type, ConstRefCType):
+            try:
+                # WARNING: not strictly decreasing; be careful not
+                # to add a direct conversion that goes satisfies
+                # mutable& with const&
+                return solve(
+                    NamedCType(goal.name, MutRefCType(goal.type.elem)), direct=direct
+                )
+            except UnsatError:
+                pass
+
+        # mutable & is satisfied with value
+        if isinstance(goal.type, MutRefCType):
+            try:
+                return solve(NamedCType(goal.name, goal.type.elem), direct=direct)
+            except UnsatError:
+                pass
+
+        # TODO: These are referentially equal, shouldn't have to do this;
+        # ensuring we don't use type synonym IntArrayRef in codegen would
+        # help
+        if goal.type == ArrayRefCType(BaseCType(longT)):
+            return solve(NamedCType(goal.name, BaseCType(intArrayRefT)), direct=direct)
+
+        if direct:
+            unsat(goal)
+
+        # For now, all of these rules are mutually exclusive.
+        if goal == NamedCType("memory_format", OptionalCType(BaseCType(memoryFormatT))):
+            memory_format = direct_solve(
+                NamedCType(
+                    SpecialArgName.possibly_redundant_memory_format,
+                    OptionalCType(BaseCType(memoryFormatT)),
+                )
+            )
+            # No need to join "memory_format" and "options" if the target API takes "options" directly.
+            # Otherwise it will cause the redundant memory_format error.
+            if options_ctype in goal_ctypes:
+                return memory_format
+            try:
+                options = direct_solve(options_ctype)
+                return f"c10::impl::check_tensor_options_and_extract_memory_format({options}, {memory_format})"
+            except UnsatError:
+                return memory_format
+        elif goal == NamedCType("options", BaseCType(tensorOptionsT)):
+            dtype = direct_solve(
+                NamedCType("dtype", OptionalCType(BaseCType(scalarTypeT)))
+            )
+            pin_memory = direct_solve(
+                NamedCType("pin_memory", OptionalCType(BaseCType(boolT)))
+            )
+            device = direct_solve(
+                NamedCType("device", OptionalCType(BaseCType(deviceT)))
+            )
+            layout = direct_solve(
+                NamedCType("layout", OptionalCType(BaseCType(layoutT)))
+            )
+            return f"TensorOptions().dtype({dtype}).layout({layout}).device({device}).pinned_memory({pin_memory})"
+
+        elif goal == NamedCType("dtype", OptionalCType(BaseCType(scalarTypeT))):
+            try:
+                options = direct_solve(options_ctype)
+                return f"c10::optTypeMetaToScalarType({options}.dtype_opt())"
+            except UnsatError:
+                out_tensor = direct_solve(out_tensor_ctype)
+                return f"{out_tensor}.scalar_type()"
+
+        elif goal == NamedCType("layout", OptionalCType(BaseCType(layoutT))):
+            try:
+                options = direct_solve(options_ctype)
+                return f"{options}.layout_opt()"
+            except UnsatError:
+                out_tensor = direct_solve(out_tensor_ctype)
+                return f"{out_tensor}.layout()"
+
+        elif goal == NamedCType("device", OptionalCType(BaseCType(deviceT))):
+            try:
+                options = direct_solve(options_ctype)
+                return f"{options}.device_opt()"
+            except UnsatError:
+                out_tensor = direct_solve(out_tensor_ctype)
+                return f"{out_tensor}.device()"
+
+        elif goal == NamedCType("pin_memory", OptionalCType(BaseCType(boolT))):
+            try:
+                options = direct_solve(options_ctype)
+                return f"{options}.pinned_memory_opt()"
+            except UnsatError:
+                # If we're calling a factory op from its out= variant,
+                # We don't actually care about the value of pin_memory.
+                out_tensor = direct_solve(out_tensor_ctype)
+                return "::std::nullopt"
+
+        # We can always do translations from value types to reference types, like vector -> IntArrayRef
+        elif goal.type == BaseCType(intArrayRefT):
+            try:
+                return direct_solve(NamedCType(goal.name, longVec_ctype))
+            except UnsatError:
+                # We can also go SymIntArrayRef -> IntArrayRef
+                symIntArrayRef_type = direct_solve(
+                    NamedCType(goal.name, BaseCType(symIntArrayRefT))
+                )
+                return f"C10_AS_INTARRAYREF_SLOW({symIntArrayRef_type})"
+        elif goal.type == BaseCType(symIntArrayRefT):
+            try:
+                r = direct_solve(NamedCType(goal.name, BaseCType(intArrayRefT)))
+                return f"c10::fromIntArrayRefSlow({r})"
+            except UnsatError:
+                return direct_solve(NamedCType(goal.name, longSymVec_ctype))
+        elif goal.type == BaseCType(SymIntT):
+            return direct_solve(NamedCType(goal.name, BaseCType(longT)))
+        elif goal.type == OptionalCType(BaseCType(SymIntT)):
+            argname = direct_solve(
+                NamedCType(goal.name, OptionalCType(BaseCType(longT)))
+            )
+            return f"{argname}.has_value() ? ::std::make_optional(c10::SymInt(*{argname})) : ::std::nullopt"
+        elif goal.type == BaseCType(longT):
+            symInt_type = direct_solve(NamedCType(goal.name, BaseCType(SymIntT)))
+            return f"{symInt_type}.guard_int(__FILE__, __LINE__)"
+        elif goal.type == OptionalCType(BaseCType(longT)):
+            argname = direct_solve(
+                NamedCType(goal.name, OptionalCType(BaseCType(SymIntT)))
+            )
+            return f"{argname}.has_value() ? ::std::make_optional({argname}->guard_int(__FILE__, __LINE__)) : ::std::nullopt"
+        elif goal.type == BaseCType(optionalIntArrayRefT):
+            try:
+                return direct_solve(NamedCType(goal.name, optionalLongVec_ctype))
+            except UnsatError:
+                argname = direct_solve(
+                    NamedCType(goal.name, BaseCType(optionalSymIntArrayRefT))
+                )
+                return f"{argname}.has_value() ? ::std::make_optional(C10_AS_INTARRAYREF_SLOW(*{argname})) : ::std::nullopt"
+        elif goal.type == BaseCType(optionalSymIntArrayRefT):
+            # TODO: You might also want to solve this from longSymVec_ctype or
+            # an optional version of it
+            argname = direct_solve(
+                NamedCType(goal.name, BaseCType(optionalIntArrayRefT))
+            )
+            return f"{argname}.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*{argname})) : ::std::nullopt"
+        elif goal.type == BaseCType(optionalScalarRefT):
+            return direct_solve(NamedCType(goal.name, optionalScalar_ctype))
+        elif goal.type == BaseCType(optionalTensorRefT):
+            return direct_solve(NamedCType(goal.name, optionalTensor_ctype))
+
+        # Note [translation from C++ reference to value types]
+        # The below cases are all for when we have an argument with a reference type,
+        # and a corresponding goal with a value type.
+        # These are needed when we populate the inputs to a lambda capture and we need
+        # to guarantee the lifetime of each captured argument.
+        # We guard it with an explicit kwarg because converting to a value type is expensive
+        # (O(n)) to convert from IntArrayRef to vector),
+        # so the caller of translate() should be explicit that they need it.
+        if allow_expensive_conversions:
+            if goal.type == VectorCType(BaseCType(longT)):
+                intArrayRef_ctype = NamedCType(goal.name, BaseCType(intArrayRefT))
+                argname = direct_solve(intArrayRef_ctype)
+                return f"{argname}.vec()"
+            if goal.type == VectorCType(BaseCType(SymIntT)):
+                symIntArrayRef_ctype = NamedCType(goal.name, BaseCType(symIntArrayRefT))
+                argname = direct_solve(symIntArrayRef_ctype)
+                return f"{argname}.vec()"
+            elif goal.type == OptionalCType(VectorCType(BaseCType(longT))):
+                optionalIntArrayRef_ctype = NamedCType(
+                    goal.name, BaseCType(optionalIntArrayRefT)
+                )
+                argname = direct_solve(optionalIntArrayRef_ctype)
+                return f"{argname}.has_value() ? ::std::make_optional({argname}->vec()) : ::std::nullopt"
+            elif goal.type == OptionalCType(BaseCType(scalarT)):
+                optionalScalarRef_ctype = NamedCType(
+                    goal.name, BaseCType(optionalScalarRefT)
+                )
+                argname = direct_solve(optionalScalarRef_ctype)
+                return f"{argname}.has_value() ? ::std::make_optional({argname}) : ::std::nullopt"
+            elif goal.type == OptionalCType(BaseCType(scalarT)):
+                optionalTensorRef_ctype = NamedCType(
+                    goal.name, BaseCType(optionalTensorRefT)
+                )
+                argname = direct_solve(optionalTensorRef_ctype)
+                return f"{argname}.has_value() ? ::std::make_optional({argname}) : ::std::nullopt"
+            # Technically, we also need to handle cases of C++ containers holding reference types.
+            # But there currently aren't any ops that require lambda capture codegen
+            # With arguments like ::std::vector.
+            # If that changes, we'll have to add the translation here.
+
+        # We allow const casting on tensors, since const-correctness is a bit broken for at::Tensor.
+        # We could probably generalize this to non-tensor types too.
+        if goal.type == MutRefCType(BaseCType(tensorT)):
+            const_ref_tensor_ctype = NamedCType(
+                goal.name, ConstRefCType(BaseCType(tensorT))
+            )
+            argname = direct_solve(const_ref_tensor_ctype)
+            return f"const_cast({argname})"
+
+        unsat(goal)
+
+    return [Expr(solve(g, direct=False), g) for g in goal_ctypes]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/types/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/types/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e98bb8df493f2375b514e6c6aeb897cebe8ec7d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/types/__init__.py
@@ -0,0 +1,5 @@
+from torchgen.api.types.types import *
+from torchgen.api.types.types_base import *
+
+
+from torchgen.api.types.signatures import *  # usort: skip
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/types/signatures.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/types/signatures.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4a47536dd1ff213bc8bd8aceee2bd22531088a6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/types/signatures.py
@@ -0,0 +1,356 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+from torchgen.api.types.types_base import Binding, CType, Expr
+
+
+if TYPE_CHECKING:
+    from collections.abc import Iterator, Sequence
+
+    from torchgen.model import (
+        BackendIndex,
+        FunctionSchema,
+        NativeFunction,
+        NativeFunctionsGroup,
+        NativeFunctionsViewGroup,
+    )
+
+
+@dataclass(frozen=True)
+class CppSignature:
+    """
+    A CppSignature represents a single overload in the C++ API.  For
+    any given function schema, there may be multiple CppSignatures
+    corresponding to it, based on how we desugar to C++.  See also
+    CppSignatureGroup.
+    """
+
+    # The schema this signature is derived from
+    func: FunctionSchema
+
+    # Is this a C++ signature for a method, i.e. Tensor::my_op(...)?
+    method: bool
+
+    # Is this a faithful C++ signature (i.e. following the JIT schema) or a convenience API
+    # (i.e. with a potential TensorOptions argument and out arguments in the front)
+    faithful: bool
+
+    # Is this a symint C++ signature.  For BC reasons, functions that take
+    # SymInts still present as int64_t in C++, and the SymInt variant is
+    # offered at a different overload name
+    #
+    # NB: If a function RETURNS a SymInt, this is ALWAYS false
+    symint: bool
+
+    # The set of C++ arguments which should not have defaults applied to them
+    cpp_no_default_args: set[str]
+
+    # Is this a fallback C++ binding?  Fallback bindings are enabled by
+    # manual_cpp_binding: True and are alternate, non-public API that
+    # lets manual C++ binding implementers access the binding that would
+    # have been automatically generated
+    fallback_binding: bool = False
+
+    # Return the unpacked argument structure of this signature,
+    # discarding information about which arguments are semantically
+    # related to each other.
+    def arguments(self) -> Sequence[Binding]:
+        return cpp.arguments(
+            self.func.arguments,
+            faithful=self.faithful,
+            symint=self.symint,
+            method=self.method,
+            cpp_no_default_args=self.cpp_no_default_args,
+        )
+
+    def name(self, *, suppress_symint_suffix: bool = False) -> str:
+        n = cpp.name(
+            self.func,
+            faithful_name_for_out_overloads=self.faithful,
+            symint_overload=False if suppress_symint_suffix else self.symint,
+        )
+        if self.fallback_binding:
+            n = f"__dispatch_{n}"
+        return n
+
+    # Render the C++ declaration for this signature
+    def decl(
+        self,
+        *,
+        name: str | None = None,
+        prefix: str = "",
+        is_redispatching_fn: bool = False,
+        suppress_symint_suffix: bool = False,
+    ) -> str:
+        returns_type = cpp.returns_type(
+            self.func.returns, symint=self.symint
+        ).cpp_type()
+        cpp_args = [a.decl() for a in self.arguments()]
+        if is_redispatching_fn:
+            cpp_args = ["c10::DispatchKeySet dispatchKeySet"] + cpp_args
+        cpp_args_str = ", ".join(cpp_args)
+        if name is None:
+            name = prefix + self.name(suppress_symint_suffix=suppress_symint_suffix)
+        return f"{returns_type} {name}({cpp_args_str})"
+
+    # Render the C++ definition for this signature, not including
+    # the body (with curly braces)
+    def defn(
+        self,
+        *,
+        name: str | None = None,
+        prefix: str = "",
+        is_redispatching_fn: bool = False,
+    ) -> str:
+        returns_type = cpp.returns_type(
+            self.func.returns, symint=self.symint
+        ).cpp_type()
+        cpp_args = [a.defn() for a in self.arguments()]
+        if is_redispatching_fn:
+            cpp_args = ["c10::DispatchKeySet dispatchKeySet"] + cpp_args
+        cpp_args_str = ", ".join(cpp_args)
+        if name is None:
+            name = prefix + self.name()
+        return f"{returns_type} {name}({cpp_args_str})"
+
+    def ptr_type(self) -> str:
+        args_types_str = ", ".join(a.type for a in self.arguments())
+        return f"{cpp.returns_type(self.func.returns, symint=self.symint).cpp_type()} (*)({args_types_str})"
+
+    # Return the C++ function type, e.g., something like int(bool)
+    def type(self) -> str:
+        args_types_str = ", ".join(a.type for a in self.arguments())
+        return f"{cpp.returns_type(self.func.returns, symint=self.symint).cpp_type()} ({args_types_str})"
+
+
+# Represents group of all CppSignatures associated with a
+# FunctionSchema.  Right now, that's the regular, user-visible
+# signature, as well as a "faithful" signature which doesn't
+# have grouping.
+@dataclass(frozen=True)
+class CppSignatureGroup:
+    func: FunctionSchema
+    signature: CppSignature
+    faithful_signature: CppSignature | None
+    symint_signature: CppSignature | None
+    symint_faithful_signature: CppSignature | None
+
+    def most_faithful_signature(self) -> CppSignature:
+        if self.faithful_signature:
+            return self.faithful_signature
+        else:
+            return self.signature
+
+    def signatures(self, *, symint: bool = True) -> Iterator[CppSignature]:
+        yield self.signature
+        if self.faithful_signature:
+            yield self.faithful_signature
+        if symint:
+            if self.symint_signature:
+                yield self.symint_signature
+            if self.symint_faithful_signature:
+                yield self.symint_faithful_signature
+
+    @staticmethod
+    def from_native_function(
+        f: NativeFunction, *, method: bool, fallback_binding: bool = False
+    ) -> CppSignatureGroup:
+        func = f.func
+
+        def make_sig(*, faithful: bool, symint: bool) -> CppSignature:
+            return CppSignature(
+                func=func,
+                faithful=faithful,
+                symint=symint,
+                method=method,
+                fallback_binding=fallback_binding,
+                cpp_no_default_args=f.cpp_no_default_args,
+            )
+
+        def make_sigs(*, symint: bool) -> tuple[CppSignature, CppSignature | None]:
+            faithful_signature: CppSignature | None = None
+            if func.arguments.tensor_options is not None or len(func.arguments.out) > 0:
+                faithful_signature = make_sig(faithful=True, symint=symint)
+            signature = make_sig(faithful=False, symint=symint)
+            return signature, faithful_signature
+
+        signature, faithful_signature = make_sigs(symint=False)
+        symint_signature: CppSignature | None = None
+        symint_faithful_signature: CppSignature | None = None
+        if func.has_symint():
+            symint_signature, symint_faithful_signature = make_sigs(symint=True)
+
+        return CppSignatureGroup(
+            func=func,
+            signature=signature,
+            faithful_signature=faithful_signature,
+            symint_signature=symint_signature,
+            symint_faithful_signature=symint_faithful_signature,
+        )
+
+
+@dataclass(frozen=True)
+class DispatcherSignature:
+    # The schema this signature is derived from
+    func: FunctionSchema
+
+    # Allows you to prepend an arbitrary prefix to the signature name.
+    # This is useful for parts of the codegen that generate wrappers around kernels,
+    # and need to avoid naming collisions.
+    prefix: str = ""
+
+    symint: bool = True
+
+    def arguments(self) -> list[Binding]:
+        return dispatcher.arguments(self.func, symint=self.symint)
+
+    def name(self) -> str:
+        return self.prefix + dispatcher.name(self.func)
+
+    def decl(self, name: str | None = None) -> str:
+        args_str = ", ".join(a.decl() for a in self.arguments())
+        if name is None:
+            name = self.name()
+        return f"{self.returns_type().cpp_type()} {name}({args_str})"
+
+    def defn(
+        self, name: str | None = None, *, is_redispatching_fn: bool = False
+    ) -> str:
+        args = [a.defn() for a in self.arguments()]
+        if is_redispatching_fn:
+            args = ["c10::DispatchKeySet dispatchKeySet"] + args
+        args_str = ", ".join(args)
+        if name is None:
+            name = self.name()
+        return f"{self.returns_type().cpp_type()} {name}({args_str})"
+
+    def exprs(self) -> list[Expr]:
+        return [Expr(a.name, a.nctype) for a in self.arguments()]
+
+    def returns_type(self) -> CType:
+        return dispatcher.returns_type(self.func.returns, symint=self.symint)
+
+    def ptr_type(self) -> str:
+        dispatcher_args_types_str = ", ".join(a.type for a in self.arguments())
+        return f"{self.returns_type().cpp_type()} (*)({dispatcher_args_types_str})"
+
+    # Return the C++ function type, e.g., something like int(bool)
+    def type(self) -> str:
+        dispatcher_args_types_str = ", ".join(a.type for a in self.arguments())
+        return f"{self.returns_type().cpp_type()} ({dispatcher_args_types_str})"
+
+    @staticmethod
+    def from_schema(
+        func: FunctionSchema, *, prefix: str = "", symint: bool = True
+    ) -> DispatcherSignature:
+        return DispatcherSignature(func, prefix, symint)
+
+
+@dataclass(frozen=True)
+class NativeSignature:
+    # The schema this signature is derived from
+    func: FunctionSchema
+
+    symint: bool
+
+    prefix: str = ""
+
+    def name(self) -> str:
+        return self.prefix + native.name(self.func)
+
+    def decl(self, name: str | None = None) -> str:
+        args_str = ", ".join(a.decl() for a in self.arguments())
+        if name is None:
+            name = self.name()
+        return f"{native.returns_type(self.func.returns, symint=self.symint).cpp_type()} {name}({args_str})"
+
+    def defn(self, name: str | None = None) -> str:
+        args_str = ", ".join(a.defn() for a in self.arguments())
+        if name is None:
+            name = self.name()
+        return f"{native.returns_type(self.func.returns, symint=self.symint).cpp_type()} {name}({args_str})"
+
+    def ptr_type(self) -> str:
+        # don't include defaults in type signature!
+        args_str = ", ".join(a.defn() for a in self.arguments())
+        return f"{native.returns_type(self.func.returns, symint=self.symint).cpp_type()} (*)({args_str})"
+
+    def arguments(self) -> list[Binding]:
+        return native.arguments(self.func, symint=self.symint)
+
+    def returns_type(self) -> CType:
+        return native.returns_type(self.func.returns, symint=self.symint)
+
+    def dispatcher_exprs(self) -> list[Expr]:
+        return translate.translate(
+            self.arguments(), dispatcher.arguments(self.func), method=False
+        )
+
+
+@dataclass(frozen=True)
+class ViewInverseSignature:
+    g: NativeFunctionsViewGroup
+
+    def name(self) -> str:
+        return functionalization.reverse_name(self.g.view, include_namespace=False)
+
+    def decl(self) -> str:
+        return_type = functionalization.returns_type(self.g.view.func)
+        decls = [
+            a.decl()
+            for a in functionalization.op_arguments(self.g.view.func, is_reverse=True)
+        ]
+        return f"static {return_type.cpp_type()} {self.name()}({', '.join(decls)});"
+
+
+@dataclass(frozen=True)
+class StructuredImplSignature:
+    g: NativeFunctionsGroup
+    name: str
+
+    def defn(self, name: str | None = None) -> str:
+        args_str = ", ".join(a.defn() for a in self.arguments())
+        return f"TORCH_IMPL_FUNC({self.name})({args_str})"
+
+    def arguments(self) -> list[Binding]:
+        return structured.impl_arguments(self.g)
+
+
+# Helper functions
+
+
+def kernel_signature(
+    f: NativeFunction, backend_index: BackendIndex, *, prefix: str = ""
+) -> NativeSignature | DispatcherSignature:
+    # Note [External Backends Follow Dispatcher API]
+    # Kernel signatures for in-tree backends follow the "native" API,
+    # while kernels for out-of-tree backends follow the dispatcher API.
+    # See the comments in `native.py` for details, but historically there have been
+    # some small differences in schema convention between them and the Dispatcher API.
+    # Any differences that require translating between the two will results in a runtime cost,
+    # so we'd like to keep the differences as small as possible.
+    # With external backends, we'd like to enforce that they write their kernels with schemas
+    # that match the Dispatcher API directly, if they can.
+    meta = backend_index.get_kernel(f)
+    symint = meta is not None and meta.supports_symint()
+    if symint:
+        assert f.func.has_symint(), (
+            f"attempted to define symint kernel for {backend_index.dispatch_key} without SymInt in schema"
+        )
+    if backend_index.external:
+        return DispatcherSignature.from_schema(f.func, prefix=prefix, symint=symint)
+    else:
+        return NativeSignature(f.func, prefix=prefix, symint=symint)
+
+
+# Functions only, no types
+from torchgen.api import (
+    cpp,
+    dispatcher,
+    functionalization,
+    native,
+    structured,
+    translate,
+)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/types/types.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/types/types.py
new file mode 100644
index 0000000000000000000000000000000000000000..41c05653fffdf3d04fc7078e7df142124ed96e00
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/types/types.py
@@ -0,0 +1,183 @@
+"""
+Where should I add a new type? `types_base.py` vs `types.py`
+
+This file defines data model classes for torchgen typing system, as well as some base types such as int32_t.
+
+`types.py` defines ATen Tensor type and some c10 types, along with signatures that use these types.
+
+The difference between these two files, is `types_base.py` should be implementation-agnostic, meaning it shouldn't
+contain any type definition that is tight to a specific C++ library (e.g., ATen), so that it can be easily reused
+if we want to generate code for another C++ library.
+
+Add new types to `types.py` if these types are ATen/c10 related.
+Add new types to `types_base.py` if they are basic and not attached to ATen/c10.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from torchgen.api.types.types_base import (
+    BaseCppType,
+    BaseCType,
+    boolT,
+    byteT,
+    charT,
+    CType,
+    doubleT,
+    floatT,
+    int32T,
+    longT,
+    shortT,
+)
+from torchgen.model import BaseTy, ScalarType
+
+
+TENSOR_LIST_LIKE_CTYPES = [
+    "at::TensorList",
+    "const c10::List<::std::optional> &",
+    "const at::ITensorListRef &",
+]
+
+
+halfT = BaseCppType("at", "Half")
+complexHalfT = BaseCppType(
+    "c10", "complex"
+)  # stuffing template param here is an abuse
+complexFloatT = BaseCppType("c10", "complex")
+complexDoubleT = BaseCppType("c10", "complex")
+bfloat16T = BaseCppType("at", "BFloat16")
+float8_e5m2T = BaseCppType("at", "Float8_e5m2")
+float8_e5m2fnuzT = BaseCppType("at", "Float8_e5m2fnuz")
+float8_e4m3fnT = BaseCppType("at", "Float8_e4m3fn")
+float8_e4m3fnuzT = BaseCppType("at", "Float8_e4m3fnuz")
+float8_e8m0fnuT = BaseCppType("at", "Float8_e8m0fnu")
+stringT = BaseCppType("c10", "string_view")
+generatorT = BaseCppType("at", "Generator")
+scalarTypeT = BaseCppType("at", "ScalarType")
+tensorT = BaseCppType("at", "Tensor")
+optionalTensorRefT = BaseCppType("at", "OptionalTensorRef")
+tensorListT = BaseCppType("at", "TensorList")
+iTensorListRefT = BaseCppType("at", "ITensorListRef")
+iOptTensorListRefT = BaseCppType("at", "IOptTensorListRef")
+dimnameT = BaseCppType("at", "Dimname")
+dimnameListT = BaseCppType("at", "DimnameList")
+dimVectorT = BaseCppType("at", "DimVector")
+layoutT = BaseCppType("at", "Layout")
+deviceT = BaseCppType("at", "Device")
+deviceIndexT = BaseCppType("at", "DeviceIndex")
+scalarT = BaseCppType("at", "Scalar")
+optionalScalarRefT = BaseCppType("at", "OptionalScalarRef")
+memoryFormatT = BaseCppType("at", "MemoryFormat")
+qschemeT = BaseCppType("at", "QScheme")
+storageT = BaseCppType("at", "Storage")
+streamT = BaseCppType("at", "Stream")
+intArrayRefT = BaseCppType("at", "IntArrayRef")
+optionalIntArrayRefT = BaseCppType("at", "OptionalIntArrayRef")
+optionalSymIntArrayRefT = BaseCppType("at", "OptionalSymIntArrayRef")
+tensorOptionsT = BaseCppType("at", "TensorOptions")
+typeAndSizeT = BaseCppType("torch::autograd::generated", "TypeAndSize")
+tensorGeometryT = BaseCppType("at", "TensorGeometry")
+SymIntT = BaseCppType("c10", "SymInt")
+SymBoolT = BaseCppType("c10", "SymBool")
+symIntArrayRefT = BaseCppType("c10", "SymIntArrayRef")
+
+# Types representing template parameters.  Technically, we probably shouldn't
+# represent them this way in codegen, but it was pretty convenient.
+scalar_t = BaseCppType("", "scalar_t")
+opmath_t = BaseCppType("", "opmath_t")
+
+ScalarTypeToCppMapping: dict[ScalarType, BaseCppType] = {
+    ScalarType.Byte: byteT,
+    ScalarType.Char: charT,
+    ScalarType.Short: shortT,
+    ScalarType.Int: int32T,
+    ScalarType.Long: longT,
+    ScalarType.Half: halfT,
+    ScalarType.Float: floatT,
+    ScalarType.Double: doubleT,
+    ScalarType.ComplexHalf: complexHalfT,
+    ScalarType.ComplexFloat: complexFloatT,
+    ScalarType.ComplexDouble: complexDoubleT,
+    ScalarType.Bool: boolT,
+    ScalarType.Float8_e5m2: float8_e5m2T,
+    ScalarType.Float8_e5m2fnuz: float8_e5m2fnuzT,
+    ScalarType.Float8_e4m3fn: float8_e4m3fnT,
+    ScalarType.Float8_e4m3fnuz: float8_e4m3fnuzT,
+    ScalarType.Float8_e8m0fnu: float8_e8m0fnuT,
+}
+
+BaseTypeToCppMapping: dict[BaseTy, BaseCppType] = {
+    BaseTy.int: longT,
+    BaseTy.float: doubleT,
+    BaseTy.bool: boolT,
+    BaseTy.str: stringT,
+    BaseTy.Generator: generatorT,
+    BaseTy.ScalarType: scalarTypeT,
+    BaseTy.Tensor: tensorT,
+    BaseTy.Dimname: dimnameT,
+    BaseTy.DimVector: dimVectorT,
+    BaseTy.Layout: layoutT,
+    BaseTy.Device: deviceT,
+    BaseTy.DeviceIndex: deviceIndexT,
+    BaseTy.Scalar: scalarT,
+    BaseTy.MemoryFormat: memoryFormatT,
+    BaseTy.QScheme: qschemeT,
+    BaseTy.Storage: storageT,
+    BaseTy.Stream: streamT,
+    BaseTy.SymInt: SymIntT,
+    BaseTy.SymBool: SymBoolT,
+}
+
+# CTypes encode C++ type structure as needed for translation.
+
+
+@dataclass(frozen=True)
+class OptionalCType(CType):
+    elem: CType
+
+    def cpp_type(self, *, strip_ref: bool = False) -> str:
+        # Do not pass `strip_ref` recursively.
+        return f"::std::optional<{self.elem.cpp_type()}>"
+
+    def remove_const_ref(self) -> CType:
+        return OptionalCType(self.elem.remove_const_ref())
+
+
+@dataclass(frozen=True)
+class ListCType(CType):
+    elem: CType
+
+    def cpp_type(self, *, strip_ref: bool = False) -> str:
+        # Do not pass `strip_ref` recursively.
+        return f"c10::List<{self.elem.cpp_type()}>"
+
+    def remove_const_ref(self) -> CType:
+        return ListCType(self.elem.remove_const_ref())
+
+
+@dataclass(frozen=True)
+class ArrayRefCType(CType):
+    elem: CType
+
+    def cpp_type(self, *, strip_ref: bool = False) -> str:
+        # Do not pass `strip_ref` recursively.
+        return f"at::ArrayRef<{self.elem.cpp_type()}>"
+
+    def remove_const_ref(self) -> CType:
+        return ArrayRefCType(self.elem.remove_const_ref())
+
+
+@dataclass(frozen=True)
+class VectorizedCType(CType):
+    # This template is explicitly specialized, so the only valid
+    # elems are those we have specializations for (e.g., float, double, ...)
+    # scalar_t is also a common argument here (when we are codegen in
+    # a templated context)
+    elem: BaseCType
+
+    def cpp_type(self, *, strip_ref: bool = False) -> str:
+        return f"at::vec::Vectorized<{self.elem.cpp_type()}>"
+
+    def remove_const_ref(self) -> CType:
+        return self
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/types/types_base.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/types/types_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..08085fa0fa2bf04b3be6d9a9b8c411c9bbfed6d8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/types/types_base.py
@@ -0,0 +1,238 @@
+"""
+Where should I add a new type? `types_base.py` vs `types.py`
+
+This file defines data model classes for torchgen typing system, as well as some base types such as int32_t.
+
+`types.py` defines ATen Tensor type and some c10 types, along with signatures that use these types.
+
+The difference between these two files, is `types_base.py` should be implementation-agnostic, meaning it shouldn't
+contain any type definition that is tight to a specific C++ library (e.g., ATen), so that it can be easily reused
+if we want to generate code for another C++ library.
+
+Add new types to `types.py` if these types are ATen/c10 related.
+Add new types to `types_base.py` if they are basic and not attached to ATen/c10.
+"""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from enum import auto, Enum
+from typing import TYPE_CHECKING, Union
+
+
+if TYPE_CHECKING:
+    from torchgen.model import Argument, SelfArgument, TensorOptionsArguments
+
+
+# An ArgName is just the str name of the argument in schema;
+# but in some special circumstances, we may add a little extra
+# context.  The Enum SpecialArgName covers all of these cases;
+# grep for their construction sites to see when they can occur.
+
+
+class SpecialArgName(Enum):
+    possibly_redundant_memory_format = auto()
+
+
+ArgName = Union[str, SpecialArgName]
+
+
+# This class shouldn't be created directly; instead, use/create one of the singletons below.
+@dataclass(frozen=True)
+class BaseCppType:
+    ns: str | None
+    name: str
+
+    def __str__(self) -> str:
+        if self.ns is None or self.ns == "":
+            return self.name
+        return f"{self.ns}::{self.name}"
+
+
+# The set of all non-templated, valid, fully-qualified names of C++ types that are used in the codegen.
+# Templated types get their own dataclass, mainly to make namespace parsing easier.
+byteT = BaseCppType("", "uint8_t")
+charT = BaseCppType("", "int8_t")
+shortT = BaseCppType("", "int16_t")
+# It would be more symmetric for this to be called intT, but it easy to mix
+# this up with JIT int (which is int64_t in C++), so we intentionally don't
+# define intT to make it obvious when you've stuffed it up
+int32T = BaseCppType("", "int32_t")
+longT = BaseCppType("", "int64_t")
+doubleT = BaseCppType("", "double")
+floatT = BaseCppType("", "float")
+boolT = BaseCppType("", "bool")
+voidT = BaseCppType("", "void")
+
+
+class CType(ABC):
+    @abstractmethod
+    def cpp_type(self, *, strip_ref: bool = False) -> str:
+        raise NotImplementedError
+
+    @abstractmethod
+    def remove_const_ref(self) -> CType:
+        return self
+
+
+@dataclass(frozen=True)
+class BaseCType(CType):
+    type: BaseCppType
+
+    def cpp_type(self, *, strip_ref: bool = False) -> str:
+        return str(self.type)
+
+    def remove_const_ref(self) -> CType:
+        return self
+
+
+@dataclass(frozen=True)
+class ConstRefCType(CType):
+    elem: CType
+
+    def cpp_type(self, *, strip_ref: bool = False) -> str:
+        if strip_ref:
+            return self.elem.cpp_type(strip_ref=strip_ref)
+        return f"const {self.elem.cpp_type()} &"
+
+    def remove_const_ref(self) -> CType:
+        return self.elem.remove_const_ref()
+
+
+@dataclass(frozen=True)
+class VectorCType(CType):
+    elem: CType
+
+    def cpp_type(self, *, strip_ref: bool = False) -> str:
+        # Do not pass `strip_ref` recursively.
+        return f"::std::vector<{self.elem.cpp_type()}>"
+
+    def remove_const_ref(self) -> CType:
+        return VectorCType(self.elem.remove_const_ref())
+
+
+@dataclass(frozen=True)
+class ArrayCType(CType):
+    elem: CType
+    size: int
+
+    def cpp_type(self, *, strip_ref: bool = False) -> str:
+        # Do not pass `strip_ref` recursively.
+        return f"::std::array<{self.elem.cpp_type()},{self.size}>"
+
+    def remove_const_ref(self) -> CType:
+        return ArrayCType(self.elem.remove_const_ref(), self.size)
+
+
+@dataclass(frozen=True)
+class TupleCType(CType):
+    elems: list[CType]
+
+    def cpp_type(self, *, strip_ref: bool = False) -> str:
+        # Do not pass `strip_ref` recursively.
+        return f"::std::tuple<{','.join([e.cpp_type() for e in self.elems])}>"
+
+    def remove_const_ref(self) -> CType:
+        return TupleCType([e.remove_const_ref() for e in self.elems])
+
+
+@dataclass(frozen=True)
+class MutRefCType(CType):
+    elem: CType
+
+    def cpp_type(self, *, strip_ref: bool = False) -> str:
+        if strip_ref:
+            return self.elem.cpp_type(strip_ref=strip_ref)
+        return f"{self.elem.cpp_type()} &"
+
+    def remove_const_ref(self) -> CType:
+        return self.elem.remove_const_ref()
+
+
+# A NamedCType is short for Named C++ semantic type.  A NamedCType represents a C++ type, plus
+# semantic information about what it represents.  For example, consider the
+# argument "bool pin_memory"; its normal C++ type is "bool", but its C++
+# semantic type also keeps track that this represents a "pin_memory"; you can't
+# just use a random other boolean in a context where you need a "pin_memory"!
+#
+
+
+@dataclass(frozen=True)
+class NamedCType:
+    name: ArgName
+    type: CType
+
+    def cpp_type(self, *, strip_ref: bool = False) -> str:
+        return self.type.cpp_type(strip_ref=strip_ref)
+
+    def remove_const_ref(self) -> NamedCType:
+        return NamedCType(self.name, self.type.remove_const_ref())
+
+    def with_name(self, name: str) -> NamedCType:
+        return NamedCType(name, self.type)
+
+
+# A binding represents any C++ binding site for a formal parameter.
+# We don't distinguish between binding sites for different APIs;
+# instead, all of the important distinctions are encoded in CType,
+# which you can use to figure out if a given Binding is appropriate
+# for use in another context.  (See torchgen.api.translate)
+
+
+@dataclass(frozen=True)
+class Binding:
+    name: str
+    nctype: NamedCType
+    argument: Argument | TensorOptionsArguments | SelfArgument
+    # TODO: maybe don't represent default here
+    default: str | None = None
+
+    def rename(self, name: str) -> Binding:
+        return Binding(
+            name=name,
+            nctype=self.nctype,
+            argument=self.argument,
+            default=self.default,
+        )
+
+    @property
+    def type(self) -> str:
+        return self.nctype.cpp_type()
+
+    def no_default(self) -> Binding:
+        return Binding(
+            name=self.name,
+            nctype=self.nctype,
+            default=None,
+            argument=self.argument,
+        )
+
+    def decl(self, *, func_ptr_cast: bool = False) -> str:
+        mb_default = ""
+        if self.default is not None:
+            mb_default = f"={self.default}"
+
+        # casting only needs to know the type
+        if func_ptr_cast:
+            return f"{self.type}"
+        else:
+            return f"{self.type} {self.name}{mb_default}"
+
+    def defn(self) -> str:
+        return f"{self.type} {self.name}"
+
+    def with_name(self, name: str) -> Binding:
+        return Binding(
+            name=name, nctype=self.nctype, argument=self.argument, default=self.default
+        )
+
+
+# An Expr is a C++ expression.  It has a C++ string representing its syntax,
+# as well as a CType saying what it provides.
+
+
+@dataclass(frozen=True)
+class Expr:
+    expr: str
+    type: NamedCType
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/ufunc.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/ufunc.py
new file mode 100644
index 0000000000000000000000000000000000000000..17adcccecab563b6a4003215c778a00d5e1399c4
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/ufunc.py
@@ -0,0 +1,209 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import torchgen.api.types as api_types
+from torchgen.api import cpp, structured
+from torchgen.api.types import (
+    ArgName,
+    BaseCppType,
+    BaseCType,
+    Binding,
+    ConstRefCType,
+    CType,
+    NamedCType,
+    scalarT,
+)
+from torchgen.model import (
+    Argument,
+    BaseTy,
+    BaseType,
+    DispatchKey,
+    FunctionSchema,
+    NativeFunctionsGroup,
+    Type,
+)
+
+
+def schema_kernel_name(func: FunctionSchema, dispatch_key: DispatchKey) -> str:
+    assert func.is_out_fn(), "ufunc.kernel_name should only be invoked on out schemas"
+    return f"ufunc_{func.name.name}_{dispatch_key}"
+
+
+def kernel_name(g: NativeFunctionsGroup, dispatch_key: DispatchKey) -> str:
+    return schema_kernel_name(g.out.func, dispatch_key)
+
+
+# Tensors are omitted (as they are stored in TensorIterator), everything else is
+# passed along  (technically, we can pass tensors along too, it just wastes
+# argument registers)
+#
+# NB: used for CPU only
+def dispatchstub_type(t: Type, *, binds: ArgName) -> NamedCType | None:
+    # Dispatch stubs are always plain ints
+    r = cpp.valuetype_type(t, binds=binds, symint=False)
+    if r is not None:
+        return r
+
+    if t == BaseType(BaseTy.Scalar):
+        return NamedCType(binds, ConstRefCType(BaseCType(scalarT)))
+    elif t == BaseType(BaseTy.Tensor):
+        return None
+    else:
+        raise AssertionError(f"unrecognized type {repr(t)}")
+
+
+def opmath_type(scalar_t: BaseCppType) -> BaseCppType:
+    if scalar_t == api_types.scalar_t:
+        return api_types.opmath_t
+    raise NotImplementedError
+
+
+# NB: Tensors in constructor are stored in opmath_t, not scalar_t
+# because Tensor in constructor = its a scalar tensor partially applied =
+# it can be higher precision and we want to compute in that higher precision
+#
+# NB: CUDA only
+def ufunctor_ctor_type(t: Type, *, binds: ArgName, scalar_t: BaseCppType) -> NamedCType:
+    r = cpp.valuetype_type(t, binds=binds, symint=False)
+    if r is not None:
+        return r
+
+    if t == BaseType(BaseTy.Scalar):
+        return NamedCType(binds, BaseCType(opmath_type(scalar_t)))
+    elif t == BaseType(BaseTy.Tensor):
+        return NamedCType(binds, BaseCType(opmath_type(scalar_t)))
+    else:
+        raise AssertionError(f"unrecognized type {repr(t)}")
+
+
+# Only Tensors ever get passed directly to operator()
+#
+# NB: CUDA only
+# (Actually, this works for CPU too)
+def ufunctor_apply_type(
+    t: Type, *, binds: ArgName, scalar_t: BaseCppType
+) -> NamedCType:
+    if t == BaseType(BaseTy.Tensor):
+        return NamedCType(binds, BaseCType(scalar_t))
+    else:
+        raise AssertionError(f"unrecognized type {repr(t)}")
+
+
+# The actual ufunc template function the user writes.  Everything here
+# is done in the computation type.  compute_t is opmath_t in CUDA and scalar_t
+# in CPU
+def ufunc_type(t: Type, *, binds: ArgName, compute_t: CType) -> NamedCType:
+    r = cpp.valuetype_type(t, binds=binds, symint=False)
+    if r is not None:
+        return r
+
+    if t == BaseType(BaseTy.Scalar):
+        return NamedCType(binds, compute_t)
+    elif t == BaseType(BaseTy.Tensor):
+        return NamedCType(binds, compute_t)
+    else:
+        raise AssertionError(f"unrecognized type {repr(t)}")
+
+
+def ufunctor_ctor_argument(a: Argument, scalar_t: BaseCppType) -> Binding:
+    return Binding(
+        nctype=ufunctor_ctor_type(a.type, binds=a.name, scalar_t=scalar_t),
+        name=a.name,
+        default=None,
+        argument=a,
+    )
+
+
+def ufunctor_apply_argument(a: Argument, scalar_t: BaseCppType) -> Binding:
+    return Binding(
+        nctype=ufunctor_apply_type(a.type, binds=a.name, scalar_t=scalar_t),
+        name=a.name,
+        default=None,
+        argument=a,
+    )
+
+
+def ufunc_argument(a: Argument, compute_t: CType) -> Binding:
+    return Binding(
+        nctype=ufunc_type(a.type, binds=a.name, compute_t=compute_t),
+        name=a.name,
+        default=None,
+        argument=a,
+    )
+
+
+@dataclass(frozen=True)
+class UfunctorBindings:
+    ctor: list[Binding]
+    apply: list[Binding]
+
+
+# ufunctors are a CUDA-only concept representing functors that take some of
+# their arguments on a host-side constructor, and the rest in the device-side
+# apply.  E.g.,
+#
+# template 
+# struct CUDAFunctorOnSelf_add {
+#   using opmath_t = at::opmath_type;
+#   opmath_t other_;
+#   opmath_t alpha_;
+#   CUDAFunctorOnSelf_add(opmath_t other, opmath_t alpha) : other_(other), alpha_(alpha) {}
+#   __device__ scalar_t operator()(scalar_t self) {
+#     return ufunc::add(static_cast(self), other_, alpha_);
+#   }
+# };
+#
+# The ctor refers to the constructor CUDAFunctorOnSelf_add, while apply refers
+# to the operator() definition
+def ufunctor_arguments(
+    g: NativeFunctionsGroup, *, scalar_tensor_idx: int | None, scalar_t: BaseCppType
+) -> UfunctorBindings:
+    ctor = []
+    apply = []
+    for a in g.functional.func.arguments.flat_non_out:
+        if a.type.is_tensor_like():
+            if scalar_tensor_idx == 0:
+                # put it in the ctor anyway
+                ctor.append(ufunctor_ctor_argument(a, scalar_t=scalar_t))
+                scalar_tensor_idx = None
+            else:
+                if scalar_tensor_idx is not None:
+                    scalar_tensor_idx -= 1
+                apply.append(ufunctor_apply_argument(a, scalar_t=scalar_t))
+        else:
+            ctor.append(ufunctor_ctor_argument(a, scalar_t=scalar_t))
+    assert scalar_tensor_idx is None
+    return UfunctorBindings(ctor=ctor, apply=apply)
+
+
+# ufuncs are the inner loop template functions that you wrote in ufunc/add.h
+# which do the actual computation in question.  E.g.,
+#
+# template 
+# C10_HOST_DEVICE T add(T self, T other, T alpha) __ubsan_ignore_undefined__ {
+#   return self + alpha * other;
+# }
+#
+# In this file, we refer to T as compute_t which is bound by caller
+def ufunc_arguments(g: NativeFunctionsGroup, *, compute_t: CType) -> list[Binding]:
+    return [
+        ufunc_argument(a, compute_t=compute_t)
+        for a in g.functional.func.arguments.flat_non_out
+    ]
+
+
+# Stubs are the DispatchStub trampolines that CPU kernels use to get to their
+# vectorized versions.  E.g.,
+#
+# using structured_binary_fn_alpha = void(*)(TensorIteratorBase&, const Scalar& alpha);
+# DECLARE_DISPATCH(structured_binary_fn_alpha, add_stub);
+def stub_arguments(g: NativeFunctionsGroup) -> list[Binding]:
+    # stubs drop all tensor arguments (they are implicit in the TensorIterator
+    # argument and keep everything else)
+    return [
+        r
+        for a in g.out.func.arguments.flat_non_out
+        if not a.type.is_tensor_like()
+        for r in structured.argument(a)
+    ]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/unboxing.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/unboxing.py
new file mode 100644
index 0000000000000000000000000000000000000000..edb48ec5d172a7063b4003536506ed33f0f293fa
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/api/unboxing.py
@@ -0,0 +1,241 @@
+from __future__ import annotations
+
+from torchgen.api import cpp
+from torchgen.api.types import Binding, CppSignatureGroup, CType
+from torchgen.model import (
+    Argument,
+    BaseTy,
+    BaseType,
+    ListType,
+    NativeFunction,
+    OptionalType,
+    Type,
+)
+
+
+# This file generates the code for unboxing wrappers, i.e., the glue logic to unbox a boxed operator and convert the
+# ivalues from stack to correct arguments to the unboxed kernel, based on corresponding JIT schema. This codegen is
+# an alternative way to generate unboxing wrappers similar to the existing C++ metaprogramming approach but gets the
+# job done statically. These generated unboxing wrappers will be useful under the scenario where we need to register
+# a fixed set of operators known at compile time and thus can save some time in runtime initialization phase.
+#
+# Here's an example on how the codegen works:
+#
+# - Function Schema (source of truth)
+#
+#      aten::empty.names(int[] size, *, Dimname[]? names,
+#                        ScalarType? dtype=None, Layout? layout=None,
+#                        Device? device=None, bool? pin_memory=None,
+#                        MemoryFormat? memory_format=None) -> Tensor
+# - Argument Conversion
+#       Generates C++ code to convert an ivalue (from stack) to its underlying C++ type.
+#    - int[] size
+#        ```cpp
+#           const c10::List size_list_in = (std::move(peek(stack, 0, 7))).toList();
+#
+#           std::vector size_vec;
+#           for (c10::IValue size_elem: size_list_in) {
+#               int64_t size_base = size_elem.to();
+#               size_vec.push_back(size_base);
+#           }
+#           at::ArrayRef size_list_out(size_vec);
+#                                 ~~~~~~~~~~~~~ <-- The converted argument from ivalues in the stack.
+#                                                   Will be passed to unboxed kernel.
+#       ```
+#    - Dimname[]? names
+#       ```cpp
+#           ::std::optional names_opt = (std::move(peek(stack, 1, 7))).toOptional();
+#           ::std::optional> names_opt_out;
+#           if (names_opt.has_value()) {
+#                         ~~~~~~~~~~~ <-- Unwrapping optional shell
+#               const c10::IValue names_opt_in = names_opt.value();
+#               const c10::List names_list_in = names_opt_in.toList();
+#
+#               std::vector names_vec;
+#               for (c10::IValue names_elem: names_list_in) {
+#                                ~~~~~~~~~~~~~~~~~~~~~~~~~ <-- Unrolling list, then convert elements one by one.
+#                   at::Dimname names_base = names_elem.to();
+#                   names_vec.push_back(names_base);
+#               }
+#               at::ArrayRef names_list_out(names_vec);
+#
+#               names_opt_out = ::std::optional>(names_list_out);
+#           } else {
+#               names_opt_out = ::std::optional>();
+#           }
+#       ```
+#    - ScalarType? dtype (similarly for the rest of the arguments)
+#       ```cpp
+#           ::std::optional dtype_opt = (std::move(peek(stack, 2, 7))).toOptional();
+#           ::std::optional dtype_opt_out;
+#           if (dtype_opt.has_value()) {
+#               const c10::IValue dtype_opt_in = dtype_opt.value();
+#               at::ScalarType dtype_base = dtype_opt_in.to();
+#                                                        ~~~~~~~~~~~~~~~~~~~~ <-- For base types, convert ivalue to it
+#                                                                                 directly using ".to()" API.
+#               dtype_opt_out = ::std::optional(dtype_base);
+#           } else {
+#               dtype_opt_out = ::std::optional();
+#           }
+#       ```
+#
+# - Unboxed Kernel Call
+#   ```cpp
+#       auto result_ = torch::empty(
+#           size_list_out,
+#           names_opt_out,
+#           options,
+#           memory_format_opt_out
+#       );
+#   ```
+#
+# - Push Result Back to Stack
+#   ```cpp
+#       drop(stack, 7);
+#       pack(stack, std::move(result_));
+#   ```
+connector = "\n\t"
+
+
+# Return unboxing function name for a NativeFunction
+def name(f: NativeFunction) -> str:
+    return f.func.name.unambiguous_name()
+
+
+# Convert all the arguments in a NativeFunction to C++ code
+def convert_arguments(f: NativeFunction) -> tuple[list[Binding], list[str]]:
+    # we need the 'self' argument so method needs to be False
+    args = (
+        CppSignatureGroup.from_native_function(f, method=False)
+        .most_faithful_signature()
+        .arguments()
+    )
+    code_list = [
+        f"c10::IValue {args[i].name} = std::move(peek(stack, {i}, {len(args)}));"
+        for i in range(len(args))
+    ] + [""]
+    binding_list = []
+    for arg in args:
+        # expecting only Argument
+        if not isinstance(arg.argument, Argument):
+            raise Exception(  # noqa: TRY002
+                f"Unexpected argument type, expecting `Argument` but got {arg}"
+            )
+        argument: Argument = arg.argument
+        unboxed_name, _, code, decl = argumenttype_ivalue_convert(
+            argument.type,
+            argument.name,
+            mutable=argument.is_write,
+        )
+        code_list.extend(decl)
+        code_list.extend(code)
+        binding_list.append(arg.with_name(unboxed_name))
+    return binding_list, code_list
+
+
+# Takes in the type, name and mutability corresponding to an argument, and generates a tuple of:
+# (1) the C++ code necessary to unbox the argument
+# (2) A Binding corresponding to the newly created unboxed variable, including variable name and its CType
+def argumenttype_ivalue_convert(
+    t: Type, arg_name: str, *, mutable: bool = False
+) -> tuple[str, CType, list[str], list[str]]:
+    # Unboxing is for mobile, which doesn't care about SymInts
+    ctype = cpp.argumenttype_type(
+        t=t, mutable=mutable, binds=arg_name, symint=False
+    ).type
+
+    if isinstance(t, BaseType):
+        out_name = f"{arg_name}_base"
+        code, decl = _gen_code_base_type(
+            arg_name=arg_name, out_name=out_name, ctype=ctype
+        )
+    elif isinstance(t, OptionalType):
+        out_name = f"{arg_name}_opt_out"
+        code, decl = _gen_code_optional_type(
+            arg_name=arg_name,
+            out_name=out_name,
+            t=t,
+            ctype=ctype,
+        )
+    elif isinstance(t, ListType):
+        out_name = f"{arg_name}_list_out"
+        code, decl = _gen_code_list_type(
+            arg_name=arg_name,
+            out_name=out_name,
+            t=t,
+            ctype=ctype,
+        )
+    else:
+        raise Exception(f"Cannot handle type {t}. arg_name: {arg_name}")  # noqa: TRY002
+    return out_name, ctype, code, decl
+
+
+def _gen_code_base_type(
+    arg_name: str, out_name: str, ctype: CType
+) -> tuple[list[str], list[str]]:
+    return [
+        f"{ctype.cpp_type(strip_ref=True)} {out_name} = {arg_name}.to<{ctype.cpp_type(strip_ref=True)}>();"
+    ], []
+
+
+def _gen_code_optional_type(
+    arg_name: str, out_name: str, t: OptionalType, ctype: CType
+) -> tuple[list[str], list[str]]:
+    in_name = f"{arg_name}_opt_in"
+    res_name, _, res_code, decl = argumenttype_ivalue_convert(t.elem, in_name)
+    return (
+        f"""
+auto {arg_name}_opt = {arg_name}.toOptional();
+{ctype.cpp_type(strip_ref=True)} {out_name};
+if ({arg_name}_opt.has_value()) {{
+    const c10::IValue {in_name} = {arg_name}_opt.value();
+    {connector.join(res_code)}
+    {out_name} = {ctype.cpp_type(strip_ref=True)}({res_name});
+}} else {{
+    {out_name} = {ctype.cpp_type(strip_ref=True)}();
+}}
+        """.split("\n"),
+        decl,
+    )
+
+
+def _gen_code_list_type(
+    arg_name: str, out_name: str, t: ListType, ctype: CType
+) -> tuple[list[str], list[str]]:
+    in_name = f"{arg_name}_list_in"
+    elem_name = f"{arg_name}_elem"
+    code = [f"const c10::List {in_name} = {arg_name}.toList();"]
+    res_name, res_ctype, res_code, decl = argumenttype_ivalue_convert(t.elem, elem_name)
+    # handle list type with size, e.g., bool[4]
+    if isinstance(t.elem, BaseType) and t.elem.name == BaseTy.bool and t.size:
+        code.extend(
+            f"""
+{ctype.cpp_type(strip_ref=True)} {out_name} = as_array<{res_ctype.cpp_type(strip_ref=True)}, {t.size}>({in_name});
+            """.split("\n")
+        )
+    # we have to use c10::List for optional element. e.g., Tensor?[] -> c10::List<::std::optional>
+    elif isinstance(t.elem, OptionalType):
+        code.extend(
+            f"""
+{ctype.cpp_type(strip_ref=True)} {out_name};
+for (c10::IValue {elem_name}: {in_name}) {{
+    {connector.join(res_code)}
+    {out_name}.push_back({res_name});
+}}
+            """.split("\n")
+        )
+    else:
+        # use ArrayRef as default.
+        vec_name = arg_name + "_vec"
+        # need to bring vector instantiation out of scope so that ArrayRef has valid data
+        decl.append(f"std::vector<{res_ctype.cpp_type(strip_ref=True)}> {vec_name};")
+        code.extend(
+            f"""
+for (c10::IValue {elem_name}: {in_name}) {{
+    {connector.join(res_code)}
+    {vec_name}.push_back({res_name});
+}}
+{ctype.cpp_type(strip_ref=True)} {out_name}({vec_name});
+            """.split("\n")
+        )
+    return code, decl
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/code_template.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/code_template.py
new file mode 100644
index 0000000000000000000000000000000000000000..bafe1fa7568ec2b0625e23407cc3d815aaf29838
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/code_template.py
@@ -0,0 +1,108 @@
+from __future__ import annotations
+
+import itertools
+import re
+import textwrap
+from typing import TYPE_CHECKING
+
+
+if TYPE_CHECKING:
+    from collections.abc import Mapping, Sequence
+
+
+# match $identifier or ${identifier} and replace with value in env
+# If this identifier is at the beginning of whitespace on a line
+# and its value is a list then it is treated as
+# block substitution by indenting to that depth and putting each element
+# of the list on its own line
+# if the identifier is on a line starting with non-whitespace and a list
+# then it is comma separated ${,foo} will insert a comma before the list
+# if this list is not empty and ${foo,} will insert one after.
+
+
+class CodeTemplate:
+    substitution_str = r"(^[^\n\S]*)?\$([^\d\W]\w*|\{,?[^\d\W]\w*\,?})"
+    substitution = re.compile(substitution_str, re.MULTILINE)
+
+    pattern: str
+    filename: str
+
+    @staticmethod
+    def from_file(filename: str) -> CodeTemplate:
+        with open(filename) as f:
+            return CodeTemplate(f.read(), filename)
+
+    def __init__(self, pattern: str, filename: str = "") -> None:
+        self.pattern = pattern
+        self.filename = filename
+
+    def substitute(
+        self, env: Mapping[str, object] | None = None, **kwargs: object
+    ) -> str:
+        if env is None:
+            env = {}
+
+        def lookup(v: str) -> object:
+            assert env is not None
+            return kwargs[v] if v in kwargs else env[v]
+
+        def indent_lines(indent: str, v: Sequence[object]) -> str:
+            content = "\n".join(
+                itertools.chain.from_iterable(str(e).splitlines() for e in v)
+            )
+            content = textwrap.indent(content, prefix=indent)
+            # Remove trailing whitespace on each line
+            return "\n".join(map(str.rstrip, content.splitlines())).rstrip()
+
+        def replace(match: re.Match[str]) -> str:
+            indent = match.group(1)
+            key = match.group(2)
+            comma_before = ""
+            comma_after = ""
+            if key[0] == "{":
+                key = key[1:-1]
+                if key[0] == ",":
+                    comma_before = ", "
+                    key = key[1:]
+                if key[-1] == ",":
+                    comma_after = ", "
+                    key = key[:-1]
+            v = lookup(key)
+            if indent is not None:
+                if not isinstance(v, list):
+                    v = [v]
+                return indent_lines(indent, v)
+            elif isinstance(v, list):
+                middle = ", ".join([str(x) for x in v])
+                if len(v) == 0:
+                    return middle
+                return comma_before + middle + comma_after
+            else:
+                return str(v)
+
+        return self.substitution.sub(replace, self.pattern)
+
+
+if __name__ == "__main__":
+    c = CodeTemplate(
+        """\
+    int foo($args) {
+
+        $bar
+            $bar
+        $a+$b
+    }
+    int commatest(int a${,stuff})
+    int notest(int a${,empty,})
+    """
+    )
+    print(
+        c.substitute(
+            args=["hi", 8],
+            bar=["what", 7],
+            a=3,
+            b=4,
+            stuff=["things...", "others"],
+            empty=[],
+        )
+    )
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/context.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/context.py
new file mode 100644
index 0000000000000000000000000000000000000000..a482a59eeb707750242554fdbddf5250d95c3bcc
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/context.py
@@ -0,0 +1,134 @@
+from __future__ import annotations
+
+import contextlib
+import functools
+from typing import Any, Callable, Optional, TYPE_CHECKING, TypeVar, Union
+
+import torchgen.local as local
+from torchgen.model import (
+    BackendIndex,
+    DispatchKey,
+    NativeFunction,
+    NativeFunctionsGroup,
+    NativeFunctionsViewGroup,
+)
+from torchgen.utils import context, S, T
+
+
+if TYPE_CHECKING:
+    from collections.abc import Iterator
+
+
+# Helper functions for defining generators on things in the model
+
+F = TypeVar(
+    "F",
+    NativeFunction,
+    NativeFunctionsGroup,
+    NativeFunctionsViewGroup,
+    Union[NativeFunction, NativeFunctionsGroup],
+    Union[NativeFunction, NativeFunctionsViewGroup],
+)
+
+F2 = TypeVar(
+    "F2",
+    NativeFunction,
+    NativeFunctionsGroup,
+    Optional[NativeFunction],
+    bool,
+    str,
+)
+
+F3 = TypeVar("F3", tuple[NativeFunction, Any], list[NativeFunction])
+
+
+@contextlib.contextmanager
+def native_function_manager(
+    g: NativeFunctionsGroup | NativeFunctionsViewGroup | NativeFunction,
+) -> Iterator[None]:
+    if isinstance(g, NativeFunctionsGroup):
+        # By default, we associate all errors with structured native functions
+        # with the out variant.  In some cases, it might be better to have
+        # a more specific place to hang things; if so, use
+        # native_function_manager again on the inside
+        f = g.out
+    elif isinstance(g, NativeFunctionsViewGroup):
+        # We associate errors with the view operator
+        f = g.view
+    else:
+        f = g
+    with context(lambda: f"in native_functions.yaml line {f.loc}:\n  {f.func}"):
+        with local.parametrize(
+            use_const_ref_for_mutable_tensors=f.use_const_ref_for_mutable_tensors,
+            use_ilistref_for_tensor_lists=f.part_of_structured_group,
+        ):
+            yield
+
+
+# Given a function that operates on NativeFunction, wrap it into a new function
+# that sets some appropriate context managers for that native function.
+# YOU MUST WRAP FUNCTIONS IN THIS for calls to api modules to be sound
+# (you will get an error if we try to access the local variables without having
+# set them).
+def with_native_function(func: Callable[[F], T]) -> Callable[[F], T]:
+    @functools.wraps(func)
+    def wrapper(f: F) -> T:
+        with native_function_manager(f):
+            return func(f)
+
+    return wrapper
+
+
+def with_native_function_and(func: Callable[[F, F2], T]) -> Callable[[F, F2], T]:
+    @functools.wraps(func)
+    def wrapper(f: F, f2: F2) -> T:
+        # The first native_function is assumed to be the one with the appropriate context.
+        with native_function_manager(f):
+            return func(f, f2)
+
+    return wrapper
+
+
+def method_with_native_function(func: Callable[[S, F], T]) -> Callable[[S, F], T]:
+    @functools.wraps(func)
+    def wrapper(slf: S, f: F) -> T:
+        with native_function_manager(f):
+            return func(slf, f)
+
+    return wrapper
+
+
+def method_with_nested_native_function(
+    func: Callable[[S, F3], T],
+) -> Callable[[S, F3], T]:
+    @functools.wraps(func)
+    def wrapper(slf: S, f: F3) -> T:
+        with native_function_manager(f[0]):
+            return func(slf, f)
+
+    return wrapper
+
+
+# Convenience decorator for functions that explicitly take in a BackendIndex,
+# instead of indirectly taking one in as a closure
+def with_native_function_and_index(
+    func: Callable[[F, BackendIndex], T],
+) -> Callable[[F, BackendIndex], T]:
+    @functools.wraps(func)
+    def wrapper(f: F, backend_index: BackendIndex) -> T:
+        with native_function_manager(f):
+            return func(f, backend_index)
+
+    return wrapper
+
+
+# Convenience decorator for functions that explicitly take in a Dict of BackendIndices
+def with_native_function_and_indices(
+    func: Callable[[F, dict[DispatchKey, BackendIndex]], T],
+) -> Callable[[F, dict[DispatchKey, BackendIndex]], T]:
+    @functools.wraps(func)
+    def wrapper(f: F, backend_indices: dict[DispatchKey, BackendIndex]) -> T:
+        with native_function_manager(f):
+            return func(f, backend_indices)
+
+    return wrapper
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/dest/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/dest/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f08a743ae2dc766530fd8f93be9ebb8b7733f21
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/dest/__init__.py
@@ -0,0 +1,19 @@
+from torchgen.dest.lazy_ir import (
+    generate_non_native_lazy_ir_nodes as generate_non_native_lazy_ir_nodes,
+    GenLazyIR as GenLazyIR,
+    GenLazyNativeFuncDefinition as GenLazyNativeFuncDefinition,
+    GenLazyShapeInferenceDefinition as GenLazyShapeInferenceDefinition,
+)
+from torchgen.dest.native_functions import (
+    compute_native_function_declaration as compute_native_function_declaration,
+)
+from torchgen.dest.register_dispatch_key import (
+    gen_registration_headers as gen_registration_headers,
+    gen_registration_helpers as gen_registration_helpers,
+    RegisterDispatchKey as RegisterDispatchKey,
+)
+from torchgen.dest.ufunc import (
+    compute_ufunc_cpu as compute_ufunc_cpu,
+    compute_ufunc_cpu_kernel as compute_ufunc_cpu_kernel,
+    compute_ufunc_cuda as compute_ufunc_cuda,
+)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/dest/lazy_ir.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/dest/lazy_ir.py
new file mode 100644
index 0000000000000000000000000000000000000000..b912b8f2427f8848b1a65736f9b36b71b85c06ad
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/dest/lazy_ir.py
@@ -0,0 +1,707 @@
+from __future__ import annotations
+
+import itertools
+from abc import ABC
+from dataclasses import dataclass
+from typing import Any
+
+import torchgen.api.dispatcher as dispatcher
+from torchgen.api.lazy import (
+    getValueT,
+    isValueType,
+    LazyArgument,
+    LazyIrProperties,
+    LazyIrSchema,
+    tensorListValueT,
+)
+from torchgen.api.translate import translate
+from torchgen.api.types import (
+    BaseCType,
+    Binding,
+    deviceT,
+    DispatcherSignature,
+    kernel_signature,
+    NativeSignature,
+    OptionalCType,
+    VectorCType,
+)
+from torchgen.context import method_with_native_function
+from torchgen.dest.lazy_ts_lowering import ts_lowering_body
+from torchgen.model import (
+    Argument,
+    BackendIndex,
+    BackendMetadata,
+    BaseTy,
+    BaseType,
+    FunctionSchema,
+    ListType,
+    NativeFunction,
+    NativeFunctionsGroup,
+)
+
+
+def node_ctor_arg_rvalue_string(arg: LazyArgument) -> str:
+    """
+    Given a LazyArgument,
+    generate a c++ string for materializing an rvalue of that arg for passing into
+    a lazy Node constructor.
+    """
+
+    # TODO: Matching on CType seems wrong; should be matching on Type
+    if isValueType(arg.lazy_type):
+        if isinstance(arg.lazy_type, BaseCType):
+            if arg.is_wrapped_scalar:
+                return f"node_{arg.name}"
+            elif arg.lazy_type.type is tensorListValueT:
+                return f"lazy_{arg.name}_tensorlist"
+            elif arg.is_symint_or_list:
+                return f"GetSymIntValue({arg.name})"
+            return f"lazy_{arg.name}->GetIrValue()"
+        elif isinstance(arg.lazy_type, OptionalCType):
+            if arg.is_symint_or_list:
+                # TODO: I don't understand when you should put lazy_ in the name
+                # or not
+                return f"{arg.name} ? std::make_optional(GetSymIntValue(*{arg.name})) : ::std::nullopt"
+            elif arg.is_wrapped_scalar:
+                return f"node_{arg.name}"
+            return (
+                f"lazy_{arg.name} ? "
+                f"std::make_optional(lazy_{arg.name}->GetIrValue()) : "
+                "::std::nullopt"
+            )
+        else:
+            raise AssertionError(
+                f"TODO not sure if there are other valid types to handle here ({arg.lazy_type})"
+            )
+    else:
+        # NB: this is here because right now we aren't treating SymInt[] as a
+        # value type; when we do this needs to move above
+        # NB: we cannot test arg.lazy_type as we've already specified it is an
+        # int64_t and so we cannot distinguish between SymInt and int64_t
+        if isinstance(arg.orig_type, ListType) and arg.orig_type.elem == BaseType(
+            BaseTy.SymInt
+        ):
+            if arg.symint:
+                return f"GetSymIntArrayRefValue({arg.name})"
+            else:
+                return f"std::vector({arg.name}.begin(), {arg.name}.end())"
+        elif isinstance(arg.lazy_type, VectorCType) and isinstance(
+            arg.lazy_type.elem, BaseCType
+        ):
+            return f"std::vector<{arg.lazy_type.elem.type}>({arg.name}.begin(), {arg.name}.end())"
+        elif (
+            isinstance(arg.lazy_type, OptionalCType)
+            and isinstance(arg.lazy_type.elem, VectorCType)
+            and isinstance(arg.lazy_type.elem.elem, BaseCType)
+        ):
+            return f"torch::lazy::ToOptionalVector<{arg.lazy_type.elem.elem.type}>({arg.name})"
+        else:
+            return f"{arg.name}"
+
+
+def node_ctor_inputs(schema: LazyIrSchema) -> str:
+    """
+    Produce a formatted string with the arguments as passed into the constructor of a node class.
+    """
+    node_ctor_values = [
+        node_ctor_arg_rvalue_string(arg) for arg in schema.filtered_args()
+    ]
+    return ", ".join(node_ctor_values)
+
+
+def gen_fallback_code(
+    schema: LazyIrSchema,
+    sig: DispatcherSignature | NativeSignature,
+    overload_name: str,
+) -> str:
+    """
+    Generate code that falls back to eager conditioned on a predicate
+    """
+    dispatcher_sig = DispatcherSignature.from_schema(schema.func)
+    exprs = translate(sig.arguments(), dispatcher_sig.arguments())
+    fallback_args = ",\n                ".join([a.expr for a in exprs])
+    if len(overload_name):
+        aten_op_str = f"ATEN_OP2({schema.aten_name}, {overload_name})"
+    else:
+        aten_op_str = f"ATEN_OP({schema.aten_name})"
+    return f"""
+        if (force_eager_fallback({aten_symbol(schema)})) {{
+            return at::native::call_fallback_fn_symint<<c_eager_fallback, {aten_op_str}>::call(
+                {fallback_args}
+            );
+        }}
+"""
+
+
+def aten_symbol(schema: LazyIrSchema) -> str:
+    missing_interned_strings = {
+        "sigmoid_backward",
+    }
+    if schema.aten_name in missing_interned_strings:
+        return f'c10::Symbol::fromQualString("aten::{schema.aten_name}")'
+
+    if not schema.aten_name.startswith("at::"):
+        return f"at::aten::{schema.aten_name}"
+    else:
+        return schema.aten_name
+
+
+# converts  all tensor-like arguments to meta tensors. Returns:
+# (1) a string containing all of the logic that does the conversions.
+# (2) a context, to be used by translate(), with all of the relevant bindings.
+def convert_to_meta_tensors(sig: DispatcherSignature) -> tuple[str, list[Binding]]:
+    context: list[Binding] = []
+    unwrapped_tensor_args: list[str] = []
+    for arg in sig.arguments():
+        if isinstance(arg.argument, Argument) and arg.argument.type.is_tensor_like():
+            unwrapped_name = f"{arg.name}_meta"
+            unwrapped_tensor_args.append(
+                f"auto {unwrapped_name} = to_meta({arg.name});"
+            )
+            context.append(arg.with_name(unwrapped_name))
+        else:
+            context.append(arg)
+    unwrap_tensor_args_str = "\n        ".join(unwrapped_tensor_args)
+    return unwrap_tensor_args_str, context
+
+
+@dataclass(frozen=True)
+class GenLazyIR(ABC):
+    backend_index: BackendIndex
+    backend_name: str
+    node_base: str
+    use_lazy_shape: bool
+
+    @method_with_native_function
+    def __call__(self, f: NativeFunctionsGroup | NativeFunction) -> list[str]:
+        func = f.functional.func if isinstance(f, NativeFunctionsGroup) else f.func
+        metadata = self.backend_index.get_kernel(
+            f.functional if isinstance(f, NativeFunctionsGroup) else f
+        )
+        schema = LazyIrSchema(
+            func, symint=metadata is not None and metadata.supports_symint()
+        )
+        return self.gen(schema)
+
+    # there is no lowering functionality generated unless this IR base class is subclassed and
+    # implemented as a backend-specific node
+    def lowering_function(self, schema: LazyIrSchema) -> str:
+        return ""
+
+    def create_function(self, schema: LazyIrSchema, node_ctor_args: str) -> str:
+        return ""
+
+    def can_be_reused_function(self, schema: LazyIrSchema, node_ctor_args: str) -> str:
+        return f"""bool CanBeReused({node_ctor_args}) const {{
+    return false;
+    }}"""
+
+    def node_base_ctor_call(self, schema: LazyIrSchema) -> str:
+        value_args = schema.filtered_args(values=True, scalars=False)
+        # backends can customize the way the node base class constructor is called,
+        # as long as all of its arguments can be generated from information available from the schema
+        base_ctor_value_args_list = []
+        for arg in value_args:
+            if isinstance(arg.lazy_type, (BaseCType, VectorCType)):
+                base_ctor_value_args_list.append(f"{arg.name}")
+            elif isinstance(arg.lazy_type, OptionalCType):
+                base_ctor_value_args_list.append(f"{arg.name}.value_or(kNullValue)")
+            else:
+                raise AssertionError(
+                    f"Unsupported type ({arg.lazy_type}) - add support if necessary"
+                )
+        base_ctor_value_args = ", ".join(base_ctor_value_args_list)
+
+        scalar_args = schema.filtered_args(values=False, scalars=True)
+
+        # Shape construction.
+        # Conditionally build shape depending on specified shape property
+        if schema.properties.ShapePrecompute:
+            shape_ctor_arg = "std::move(shapes),"
+        elif schema.properties.ShapeCompute:
+            shape_args = [a.name for a in value_args]
+            shape_args.extend(a.name for a in scalar_args)
+            shape_ctor_arg = f"compute_shape_{schema.name}({', '.join(shape_args)}),"
+        elif schema.properties.ShapeCache:
+            shape_args = [f"operand({i})" for i in range(len(value_args))]
+            shape_args.extend(a.name for a in scalar_args)
+            shape_ctor_arg = f"[&](){{ return compute_shape_{schema.name}({', '.join(shape_args)})[0]; }},"
+        else:
+            shape_ctor_arg = ""
+
+        scalar_hashes = ", ".join(f"{a.name}" for a in scalar_args)
+
+        return f"""{self.node_base}(
+              {schema.node_name}::ClassOpKind(),
+              OpList{{{base_ctor_value_args}}},
+              {shape_ctor_arg}
+              /* num_outputs */ {len(schema.returns)},
+              torch::lazy::MHash({scalar_hashes}))"""
+
+    def gen(self, schema: LazyIrSchema) -> list[str]:
+        opkind = schema.opkind or aten_symbol(schema)
+
+        # for now, we just want one IR class decl and soon after also the method defs
+        # and we use the functional version not out/inplace.
+        all_args = schema.filtered_args()
+        scalar_args = schema.filtered_args(values=False, scalars=True)
+
+        ctor_args = [f"const {i.lazy_type.cpp_type()}& {i.name}" for i in all_args]
+        reuse_ctor_args = ", ".join(ctor_args)
+        if self.use_lazy_shape and schema.properties.ShapePrecompute:
+            ctor_args.append("std::vector&& shapes")
+        node_ctor_args = ", ".join(ctor_args)
+
+        scalar_initializers = ",\n        ".join(
+            [
+                # This code is just special casing the mapping from string_view -> strings
+                f"{a.name}({a.name}.has_value() ? ::std::make_optional(std::string(*{a.name})) : ::std::nullopt)"
+                if a.lazy_type.cpp_type() == "::std::optional"
+                else f"{a.name}({a.name})"
+                for a in scalar_args
+            ]
+        )
+        if len(scalar_initializers):
+            scalar_initializers = f",\n        {scalar_initializers}"
+        scalar_decls = "\n  ".join(
+            [
+                f"std::string {a.name};"
+                if a.lazy_type.cpp_type() == "c10::string_view"
+                else f"::std::optional {a.name};"
+                if a.lazy_type.cpp_type() == "::std::optional"
+                else f"{a.lazy_type.cpp_type()} {a.name};"
+                for a in scalar_args
+            ]
+        )
+        optional_values = [
+            arg.name
+            for arg in schema.filtered_args(values=True, scalars=False)
+            if isinstance(arg.lazy_type, OptionalCType)
+        ]
+        has_optional_decls = "\n  ".join(
+            [f"bool has_{value}: 1;" for value in optional_values]
+        )
+        has_optional_defs = "\n    ".join(
+            [f"has_{value} = !!{value};" for value in optional_values]
+        )
+        members_to_string = []
+        for arg in scalar_args:
+            if isinstance(arg.lazy_type, OptionalCType):
+                value = f"{arg.name}.value()"
+                if arg.is_generator:
+                    value = '"torch.Generator()"'
+                members_to_string.append(
+                    f"""if ({arg.name}.has_value()) {{
+      ss << ", {arg.name}=" << {value};
+    }} else {{
+      ss << ", {arg.name}=null";
+    }}"""
+                )
+            else:
+                members_to_string.append(f'ss << ", {arg.name}=" << {arg.name};')
+        members_to_string_str = "\n    ".join(members_to_string)
+
+        return [
+            f"""\
+class {schema.node_name} : public {self.node_base} {{
+ public:
+  static torch::lazy::OpKind ClassOpKind() {{
+    return torch::lazy::OpKind({opkind});
+  }}
+
+  {schema.node_name}({node_ctor_args})
+      : {self.node_base_ctor_call(schema)}{scalar_initializers}
+  {{
+    {has_optional_defs}
+  }}
+
+  std::string ToString() const override {{
+    std::stringstream ss;
+    ss << {self.node_base}::ToString();
+    {members_to_string_str}
+    return ss.str();
+  }}
+
+  {self.create_function(schema, reuse_ctor_args)}
+
+  {self.can_be_reused_function(schema, reuse_ctor_args)}
+
+  {self.lowering_function(schema)}
+
+  {scalar_decls}
+  {has_optional_decls}
+
+}};
+
+""",
+        ]
+
+
+@dataclass(frozen=True)
+class GenTSLazyIR(GenLazyIR):
+    def lowering_function(self, schema: LazyIrSchema) -> str:
+        signature = """
+  torch::lazy::TSOpVector Lower(
+      std::shared_ptr function,
+      torch::lazy::TSLoweringContext* loctx) const override"""
+
+        if schema.properties.LowerDeclOnly:
+            return f"{signature};"
+        elif schema.properties.Lower:
+            return f"""{signature} {{
+    {ts_lowering_body(schema)}
+  }}
+            """
+        else:
+            return ""
+
+    def create_function(self, schema: LazyIrSchema, node_ctor_args: str) -> str:
+        signature = f"static NodePtr Create({node_ctor_args})"
+        if schema.properties.CreateFnDeclOnly:
+            return f"{signature};"
+        elif not schema.properties.CreateFn:
+            return ""
+        return f"""{signature} {{
+    return ReuseOrMakeNode<{schema.node_name}>(data);
+  }}"""
+
+    def can_be_reused_function(self, schema: LazyIrSchema, node_ctor_args: str) -> str:
+        signature = f"bool CanBeReused({node_ctor_args}) const"
+        if schema.properties.CanBeReusedDeclOnly:
+            return f"{signature};"
+        elif not schema.properties.CanBeReused:
+            return ""
+        value_comparison = []
+        for arg in itertools.chain(schema.positional_values, schema.keyword_values):
+            if isinstance(arg.lazy_type, OptionalCType):
+                value_comparison.append(
+                    f"nullable_operand(i++) == {arg.name}.value_or(kNullValue)"
+                )
+            else:
+                value_comparison.append(f"operand(i++) == {arg.name}")
+        for arg in itertools.chain(schema.positional_scalars, schema.keyword_scalars):
+            if isinstance(arg.lazy_type, OptionalCType):
+                value_comparison.append(
+                    f"((!this->{arg.name}&&!{arg.name}) || (this->{arg.name}&&{arg.name} && *(this->{arg.name}) == *{arg.name}))"
+                )
+            else:
+                value_comparison.append(f"this->{arg.name} == {arg.name}")
+        value_comparison_str = " &&\n        ".join(value_comparison)
+
+        return f"""{signature} {{
+    size_t i = 0;
+    return ({value_comparison_str});
+  }}"""
+
+
+@dataclass(frozen=True)
+class GenLazyNativeFuncDefinition:
+    class_method_name: str
+    backend_index: BackendIndex
+    tensor_class: str
+    gen_forced_fallback_code: bool
+    backend_namespace: str
+    get_tensorlist: str
+    get_tensor_or_wrap_number: str
+    try_get_tensor: str
+    metrics_counter: str
+    create_tensor: str
+    create_from_first_tensor: bool
+    create_aten_from_ltc_tensor: str
+    tuple_aten_from_ltc_tensors: str
+    lazy_tensor_ptr: str
+    get_device_fn: str
+
+    def lazy_tensor_decls(self, func: NativeFunction, schema: LazyIrSchema) -> str:
+        value_args = schema.filtered_args(values=True, scalars=False)
+        # Generates lazy_{name} variables for LazyTensors wrapping input tensors
+        lazy_tensor_decls: list[str] = []
+        for arg in value_args:
+            if arg.is_wrapped_scalar:
+                if isinstance(arg.lazy_type, OptionalCType):
+                    lazy_tensor_decls.append(
+                        f"""auto node_{arg.name} = {arg.name} ?
+                std::make_optional(torch::lazy::LazyGraphExecutor::Get()->
+                    GetIrValueForScalarFromCodegen(*{arg.name}, *common_device)):
+                ::std::nullopt;"""
+                    )
+                else:
+                    lazy_tensor_decls.append(
+                        f"""auto node_{arg.name} = torch::lazy::LazyGraphExecutor::Get()->
+                            GetIrValueForScalarFromCodegen({arg.name}, *common_device);"""
+                    )
+            elif arg.is_symint_or_list:
+                continue  # values are extracted in isValueType
+            elif isinstance(arg.lazy_type, BaseCType):
+                if arg.lazy_type.type is tensorListValueT:
+                    lazy_tensor_decls.append(
+                        f"auto lazy_{arg.name}_tensorlist = "
+                        f"{self.backend_namespace}::{self.get_tensorlist}({arg.name});"
+                    )
+                else:
+                    lazy_tensor_decls.append(
+                        f"{self.lazy_tensor_ptr} lazy_{arg.name} = "
+                        f"{self.backend_namespace}::{self.get_tensor_or_wrap_number}({arg.name}, *common_device);"
+                    )
+            elif isinstance(arg.lazy_type, OptionalCType):
+                assert arg.lazy_type.elem == BaseCType(getValueT()), arg.lazy_type.elem
+                # TODO(alanwaketan): Maybe we want to apply GetLtcTensorOrCreateForWrappedNumber here, but hold it
+                # until we encounter a real world example.
+                lazy_tensor_decls.append(
+                    f"{self.lazy_tensor_ptr} lazy_{arg.name} = "
+                    f"{self.backend_namespace}::{self.try_get_tensor}({arg.name}.value_or(at::Tensor()));"
+                )
+            else:
+                raise AssertionError(
+                    f"TODO not sure if there are other valid types to handle here ({arg.lazy_type})"
+                )
+        return ("\n        ").join(lazy_tensor_decls)
+
+    def force_eager_fallback(
+        self,
+        func: NativeFunction,
+        schema: LazyIrSchema,
+        metadata: BackendMetadata,
+        sig: DispatcherSignature | NativeSignature,
+    ) -> str:
+        if self.gen_forced_fallback_code:
+            return gen_fallback_code(
+                schema, sig, overload_name=func.func.name.overload_name
+            )
+        return ""
+
+    def metrics(self, func: NativeFunction, schema: LazyIrSchema) -> str:
+        return f"{self.metrics_counter};"
+
+    def get_device(self, func: NativeFunction, schema: LazyIrSchema) -> str:
+        value_args = schema.filtered_args(values=True, scalars=False)
+        scalar_args = schema.filtered_args(values=False, scalars=True)
+        value_types_names = [f"{a.name}" for a in value_args if not a.is_wrapped_scalar]
+        optional_device = OptionalCType(BaseCType(deviceT))
+        optional_devices = [
+            a.name for a in scalar_args if a.lazy_type == optional_device
+        ]
+        assert len(value_types_names) > 0 or len(optional_devices) > 0, (
+            "Expected at least one Value or Device type"
+        )
+        get_device_str = (
+            f"{self.get_device_fn}({', '.join(value_types_names + optional_devices)})"
+        )
+        return f"""auto common_device = {get_device_str};
+        TORCH_INTERNAL_ASSERT(common_device);
+        """
+
+    def shape_inference(self, func: NativeFunction, schema: LazyIrSchema) -> str:
+        metadata = self.backend_index.get_kernel(func)
+        assert metadata is not None
+        all_args = schema.filtered_args()
+        returns_length = len(schema.returns)
+        # call the meta kernel if it exists, to compute output shape/dtype for our IR
+        # Note [Generated LTC Shape Functions]
+        # LTC uses meta tensors from core to do shape inference when possible, and otherwise
+        # we generate a shape function declaration that needs to be manually implemented.
+        # How do we detect which ops are eligible to use meta tensors?
+        # In general we should be able to use meta tensors not just on structured operators,
+        # but also on composite operators that are implemented in terms of structured kernels.
+        # We don't currently have a way of knowing at codegen time which ops are implemented that way.
+        # This is the case for all view and view_copy operators however, so we're going to
+        # use them specifically for all of the view_copy ops (instead of manually writing shape rules for all of them).
+        is_view_copy_op = "view_copy" in func.tags
+        is_structured = func.structured or func.structured_delegate is not None
+        if is_structured or is_view_copy_op:
+            meta_out = """
+std::vector shapes{torch::lazy::Shape(out_meta.scalar_type(), out_meta.sizes().vec())};"""
+            if returns_length > 1:
+
+                def this_shape(i: int) -> str:
+                    return f"torch::lazy::Shape(std::get<{i}>(out_meta).scalar_type(), std::get<{i}>(out_meta).sizes().vec())"
+
+                shapes_str = ",".join([this_shape(i) for i in range(returns_length)])
+                meta_out = "std::vector shapes{" + shapes_str + "};"
+
+            # Convert tensor args to the meta device and call it.
+            # (We can't pass in the input tensors directly, because they are "functional wrappers".
+            # If any of the meta kernels call a tensor op and redispatch, we don't want to hit the functionalize kernels.)
+            # Even at::meta:: functions might redispatch, e.g. if they call into view ops.
+            dispatcher_sig = DispatcherSignature.from_schema(func.func)
+            meta_conversion_str, meta_call_ctx = convert_to_meta_tensors(dispatcher_sig)
+            meta_call_args = [
+                e.expr
+                for e in translate(
+                    meta_call_ctx, dispatcher_sig.arguments(), method=False
+                )
+            ]
+            if is_view_copy_op:
+                # view_copy ops always have a CompositeExplicitAutogradNonFunctional kernel
+                assert func.has_composite_explicit_autograd_non_functional_kernel
+                dispatch_ns = "compositeexplicitautogradnonfunctional"
+            else:
+                dispatch_ns = "meta"
+            aten_name = schema.aten_name
+            # TODO: this is trolling
+            if func.func.has_symint() and metadata.supports_symint():
+                aten_name += "_symint"
+            shape_str = f"""\
+        {meta_conversion_str}
+        auto out_meta = at::{dispatch_ns}::{aten_name}({", ".join(meta_call_args)});
+        {meta_out}"""
+        else:
+            shape_sig = ComputeShapeSignature(
+                metadata.kernel, func, symint=metadata.supports_symint()
+            )
+            shape_str = f"""
+            auto shapes = {shape_sig.shape_call};"""
+
+        shape_str += f"""
+            TORCH_INTERNAL_ASSERT(shapes.size() == {returns_length});"""
+
+        # Calculating which dimensions are symbolic
+        func_schema_str = "aten::" + str(func.func)
+        shape_str += f"""
+            if(torch::lazy::symbolicShapeEnabled()){{
+                std::vector inputs = {{ {", ".join(str(a.name) for a in all_args)} }};
+                const char* schema_str = "{func_schema_str}";
+                applySymbolicShapesOnLT(schema_str, inputs, shapes);
+            }}
+        """
+        return shape_str
+
+    def build_ir_node(self, func: NativeFunction, schema: LazyIrSchema) -> str:
+        node_ctor_input_str = node_ctor_inputs(schema)
+        return f"""torch::lazy::NodePtr node = torch::lazy::ReuseNode<{schema.node_name}>({node_ctor_input_str});
+        if (!node) {{
+            {self.shape_inference(func, schema)}
+            node = torch::lazy::MakeNode<{schema.node_name}>({node_ctor_input_str}, std::move(shapes));
+            CacheNode(node);
+        }}
+        """
+
+    def create_lazy_tensor(self, first_tensor_name: str | None = None) -> str:
+        # xla uses an instance method for tensor creation, for the time being
+        if self.create_from_first_tensor:
+            # TODO(whc) remove this if XLA switches to using static method for creation
+            assert first_tensor_name is not None, (
+                "Requires first tensor to create lazy tensor"
+            )
+            return f"{first_tensor_name}.{self.create_tensor}"
+        return f"{self.backend_namespace}::{self.create_tensor}"
+
+    def return_aten_tensor(self, func: NativeFunction, schema: LazyIrSchema) -> str:
+        returns_length = len(schema.returns)
+        value_args = schema.filtered_args(values=True, scalars=False)
+        value_types_names = [f"{a.name}" for a in value_args if not a.is_wrapped_scalar]
+        first_tensor_name = value_types_names[0] if len(value_types_names) > 0 else None
+        bridge_str = f"""auto result = {self.create_aten_from_ltc_tensor}(
+                {self.create_lazy_tensor(first_tensor_name)}(std::move(node), *common_device));"""
+
+        if returns_length > 1:
+            assert len(value_types_names) > 0, (
+                "Code below assumes there is at least one tensor arg"
+            )
+            bridge_str = f"""std::vector<{self.lazy_tensor_ptr}> lazy_tensors;
+        for (int i = 0; i < {returns_length}; i++) {{
+            lazy_tensors.push_back({self.create_lazy_tensor(first_tensor_name)}({getValueT()}(node, i), *common_device));
+        }}
+        auto result = {self.tuple_aten_from_ltc_tensors}<{returns_length}>(lazy_tensors);"""
+
+        if schema.name.name.inplace or func.func.is_out_fn():
+            assert returns_length == 1, (
+                "We assumed there was no such case where an op is an in-place variant "
+                f"and has tuple outputs, but got tuple of len {returns_length}."
+            )
+            bridge_str = f"""lazy_{first_tensor_name}->SetInPlaceIrValue(node);
+        auto& result = {first_tensor_name};"""
+
+        bridge_str += """
+        return result;"""
+        return bridge_str
+
+    @method_with_native_function
+    def __call__(self, func: NativeFunction) -> list[str]:
+        sig = kernel_signature(func, self.backend_index)
+        metadata = self.backend_index.get_kernel(func)
+        assert metadata is not None
+        schema = LazyIrSchema(func.func, symint=metadata.supports_symint())
+        return [
+            f"""\
+    {sig.decl(name=f"{self.class_method_name}::{metadata.kernel}")} {{
+        {self.force_eager_fallback(func, schema, metadata, sig)}
+        {self.metrics(func, schema)}
+        {self.get_device(func, schema)}
+        {self.lazy_tensor_decls(func, schema)}
+        {self.build_ir_node(func, schema)}
+        {self.return_aten_tensor(func, schema)}
+    }}\n
+    """
+        ]
+
+
+class ComputeShapeSignature:
+    """
+    Here we use the base name as the suffix of the signature to avoid generating for in-place variants.
+    """
+
+    def __init__(self, kernel_name: str, f: NativeFunction, *, symint: bool) -> None:
+        self.__schema = LazyIrSchema(f.func, symint=symint)
+        self.__dispatch_args = ", ".join(
+            [a.decl() for a in dispatcher.arguments(f.func, symint=symint)]
+        )
+        self.__call_args = ", ".join(
+            [f"{arg.name}" for arg in self.__schema.filtered_args(generator=True)]
+        )
+        self.__kernel_name = kernel_name
+
+    def __decl_suffix(self) -> str:
+        return f"{self.__kernel_name}({self.__dispatch_args})"
+
+    def __call_suffix(self) -> str:
+        return f"{self.__kernel_name}({self.__call_args})"
+
+    @property
+    def shape_decl(self) -> str:
+        return f"TORCH_API std::vector compute_shape_{self.__decl_suffix()}"
+
+    @property
+    def shape_call(self) -> str:
+        return f"torch::lazy::compute_shape_{self.__call_suffix()}"
+
+
+@dataclass(frozen=True)
+class GenLazyShapeInferenceDefinition:
+    backend_index: BackendIndex
+    tensor_class: str
+
+    @method_with_native_function
+    def __call__(self, f: NativeFunction) -> list[str]:
+        metadata = self.backend_index.get_kernel(f)
+        assert metadata is not None
+
+        # See Note [Generated LTC Shape Functions]
+        is_view_copy_op = "view_copy" in f.tags
+        is_structured = f.structured or f.structured_delegate is not None
+        if is_structured or is_view_copy_op:
+            return []
+        else:
+            shape_sig = ComputeShapeSignature(
+                metadata.kernel, f, symint=metadata.supports_symint()
+            )
+            return ["\n".join([f"{shape_sig.shape_decl};"])]
+
+
+def generate_non_native_lazy_ir_nodes(
+    non_native: list[dict[str, Any]], gen_lazy_ir: GenLazyIR
+) -> list[str]:
+    """Generate the non-native lazy IR node classes"""
+    nodes = []
+    for op in non_native:
+        # Set default properties for Non-Native IRs
+        properties = LazyIrProperties("ShapeCache", "CanBeReused", "LowerDeclOnly")
+        for p in op.get("properties", []):
+            setattr(properties, p, True)
+
+        # non-native is assumed to want symint bindings if you wrote symint
+        schema = LazyIrSchema(FunctionSchema.parse(op["func"]), properties, symint=True)
+        schema.opkind = op.get("opkind")
+        nodes.append(gen_lazy_ir.gen(schema)[0])
+
+    return nodes
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/dest/lazy_ts_lowering.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/dest/lazy_ts_lowering.py
new file mode 100644
index 0000000000000000000000000000000000000000..70161216d8e7c95e194b0d89b345e0da886ef989
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/dest/lazy_ts_lowering.py
@@ -0,0 +1,48 @@
+from torchgen.api.lazy import LazyArgument, LazyIrSchema
+from torchgen.api.types import OptionalCType
+
+
+def ts_lowering_body(schema: LazyIrSchema) -> str:
+    # for now, we just want one IR class decl and soon after also the method defs
+    # and we use the functional version not out/inplace.
+    emplace_arguments = []
+
+    def get_value(arg: LazyArgument) -> str:
+        if isinstance(arg.lazy_type, OptionalCType):
+            return f"has_{arg.name} ? loctx->GetOutputOp(operand(i++)) : nullptr"
+        return "loctx->GetOutputOp(operand(i++))"
+
+    for arg in schema.positional_args:
+        if arg.is_lazy_value:
+            emplace_arguments.append(get_value(arg))
+            continue
+        emplace_arguments.append(f'"{arg.name}", {arg.name}')
+
+    emplace_arguments_str = "\n    ".join(
+        [f"arguments.emplace_back({a});" for a in emplace_arguments]
+    )
+    emplace_kwarg_values = [
+        f'"{arg.name}", {get_value(arg)}' for arg in schema.keyword_values
+    ]
+    emplace_kwarg_scalars = [
+        f'"{arg.name}", {arg.name}' for arg in schema.keyword_scalars
+    ]
+    emplace_kwarguments = "\n    ".join(
+        [
+            f"kwarguments.emplace_back({a});"
+            for a in emplace_kwarg_values + emplace_kwarg_scalars
+        ]
+    )
+    return f"""\
+    std::vector arguments;
+    std::vector kwarguments;
+    arguments.reserve({len(emplace_arguments)});
+    kwarguments.reserve({len(emplace_kwarg_values + emplace_kwarg_scalars)});
+    size_t i = 0;
+    {emplace_arguments_str}
+    {emplace_kwarguments}
+    torch::lazy::TSOpVector {schema.aten_name}_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments);
+    TORCH_CHECK_EQ({schema.aten_name}_out.size(), {len(schema.returns)});
+
+    return {schema.aten_name}_out;
+"""
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/dest/native_functions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/dest/native_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..05e252d09f9c16888dec66045a92b8aefa19b667
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/dest/native_functions.py
@@ -0,0 +1,84 @@
+from __future__ import annotations
+
+import torchgen.api.meta as meta
+import torchgen.api.structured as structured
+from torchgen.api.types import kernel_signature
+from torchgen.context import with_native_function_and_index
+from torchgen.model import BackendIndex, NativeFunction, NativeFunctionsGroup
+from torchgen.utils import mapMaybe
+
+
+def torch_api_key_word_prefix(bankend_index: BackendIndex) -> str:
+    if bankend_index.external:
+        return ""
+
+    # Although Intel GPU ATen library is out-of-tree, it still utilizes torchgen to produce structured
+    # kernels. Regarding these produced structured kernels, they should be visible for the Intel GPU ATen
+    # library. Therefore, we need to add "TORCH_XPU_API" prefix to these structured kernels,
+    # rather than "TORCH_API". Because the semantic of "TORCH_API" is "hidden" for out-of-tree backends.
+    # For other in-tree backends like cpu and cuda, they still use "TORCH_API" prefix with "visible" semantic.
+    device_torch_api_key_word_mapping = {
+        "XPU": "TORCH_XPU_API",
+    }
+
+    return (
+        device_torch_api_key_word_mapping.get(
+            bankend_index.dispatch_key.name, "TORCH_API"
+        )
+        + " "
+    )
+
+
+@with_native_function_and_index
+def gen_unstructured(f: NativeFunction, backend_index: BackendIndex) -> str | None:
+    sig = kernel_signature(f, backend_index)
+    metadata = backend_index.get_kernel(f)
+    if metadata is None:
+        return None
+    if "legacy::" in metadata.kernel:
+        return None
+    else:
+        prefix = "static" if backend_index.external else "TORCH_API"
+        return f"{prefix} {sig.decl(name=metadata.kernel)};"
+
+
+@with_native_function_and_index
+def gen_structured(g: NativeFunctionsGroup, backend_index: BackendIndex) -> list[str]:
+    meta_name = meta.name(g)
+    out_args = structured.impl_arguments(g)
+    metadata = backend_index.get_kernel(g)
+    if metadata is None:
+        return []
+    prefix = torch_api_key_word_prefix(backend_index)
+    return [
+        f"""\
+struct {prefix}structured_{metadata.kernel} : public at::meta::structured_{meta_name} {{
+void impl({", ".join(a.decl() for a in out_args)});
+}};
+"""
+    ]
+
+
+# Generates NativeFunctions.h, a list of forward declarations of all
+# actual kernel definitions we keep in aten/src/ATen/native/
+@with_native_function_and_index
+def compute_native_function_declaration(
+    g: NativeFunctionsGroup | NativeFunction, backend_index: BackendIndex
+) -> list[str]:
+    metadata = backend_index.get_kernel(g)
+    if isinstance(g, NativeFunctionsGroup):
+        if metadata is not None and metadata.structured:
+            if backend_index.external:
+                # Structured hasn't been tested with external backends yet.
+                raise AssertionError(
+                    "Structured external backend functions are not implemented yet."
+                )
+            else:
+                return gen_structured(g, backend_index)
+        else:
+            return list(
+                mapMaybe(lambda f: gen_unstructured(f, backend_index), g.functions())
+            )
+    else:
+        x = gen_unstructured(g, backend_index)
+        return [] if x is None else [x]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/dest/register_dispatch_key.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/dest/register_dispatch_key.py
new file mode 100644
index 0000000000000000000000000000000000000000..52bb9602a73f050301e7f4953364d242e2722e54
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/dest/register_dispatch_key.py
@@ -0,0 +1,1016 @@
+from __future__ import annotations
+
+import itertools
+import textwrap
+from dataclasses import dataclass
+from typing import Literal, TYPE_CHECKING
+from typing_extensions import assert_never
+
+import torchgen.api.cpp as cpp
+import torchgen.api.meta as meta
+import torchgen.api.structured as structured
+from torchgen.api.translate import translate
+from torchgen.api.types import (
+    BaseCType,
+    Binding,
+    ConstRefCType,
+    CppSignature,
+    CppSignatureGroup,
+    DispatcherSignature,
+    Expr,
+    kernel_signature,
+    MutRefCType,
+    NamedCType,
+    NativeSignature,
+    tensorT,
+)
+from torchgen.context import method_with_native_function, native_function_manager
+from torchgen.model import (
+    Argument,
+    BackendIndex,
+    DeviceCheckType,
+    DispatchKey,
+    gets_generated_out_inplace_wrapper,
+    is_cuda_dispatch_key,
+    NativeFunction,
+    NativeFunctionsGroup,
+    SchemaKind,
+    TensorOptionsArguments,
+)
+from torchgen.utils import mapMaybe, Target
+
+
+if TYPE_CHECKING:
+    from torchgen.selective_build.selector import SelectiveBuilder
+
+
+def gen_registration_headers(
+    backend_index: BackendIndex,
+    per_operator_headers: bool,
+    rocm: bool,
+) -> list[str]:
+    if per_operator_headers:
+        headers = ["#include "]
+    else:
+        headers = ["#include "]
+
+    if backend_index.dispatch_key in (DispatchKey.CPU, DispatchKey.Meta):
+        headers.append("#include ")
+    elif backend_index.dispatch_key == DispatchKey.CUDA:
+        if rocm:
+            headers.append("#include ")
+        else:
+            headers.append("#include ")
+    elif backend_index.dispatch_key == DispatchKey.MPS:
+        headers.append("#include ")
+    elif backend_index.dispatch_key == DispatchKey.XPU:
+        # XPU specific, this header resides in third_party/torch-xpu-ops
+        headers.append("#include ")
+    elif backend_index.dispatch_key == DispatchKey.MTIA:
+        headers.append("#include ")
+    elif per_operator_headers:
+        headers += [
+            "#include ",
+            "#include ",
+            "#include ",
+            "#include ",
+        ]
+    else:
+        headers.append("#include ")
+
+    headers.append("#include ")
+    return headers
+
+
+def gen_empty_impl_names(
+    backend_index: BackendIndex,
+) -> tuple[str | None, str | None]:
+    empty_impl = None
+    empty_strided_impl = None
+
+    if backend_index.dispatch_key in (
+        DispatchKey.Meta,
+        DispatchKey.CPU,
+        DispatchKey.CUDA,
+        DispatchKey.MPS,
+        DispatchKey.XPU,
+        DispatchKey.MTIA,
+    ):
+        dispatch = str(backend_index.dispatch_key).lower()
+        empty_impl = f"at::detail::empty_{dispatch}"
+        empty_strided_impl = f"at::detail::empty_strided_{dispatch}"
+    elif backend_index.dispatch_key in (
+        DispatchKey.CompositeExplicitAutogradNonFunctional,
+        DispatchKey.QuantizedCPU,
+        DispatchKey.QuantizedCUDA,
+        DispatchKey.XPU,
+    ):
+        empty_impl = "at::empty"
+        empty_strided_impl = "at::empty_strided"
+
+    return empty_impl, empty_strided_impl
+
+
+def gen_create_out_helper(backend_index: BackendIndex) -> list[str]:
+    if backend_index.dispatch_key == DispatchKey.Meta:
+        empty_options = "options.device(at::kMeta)"
+    else:
+        empty_options = "options"
+
+    empty_impl, empty_strided_impl = gen_empty_impl_names(backend_index)
+    if empty_impl is None:
+        return []
+
+    return [
+        f"""
+Tensor create_out(IntArrayRef sizes, IntArrayRef strides, const TensorOptions &options) {{
+  if (strides.empty()) {{
+      return {empty_impl}(sizes, {empty_options});
+  }} else {{
+      return {empty_strided_impl}(sizes, strides, {empty_options});
+  }}
+}}
+"""
+    ]
+
+
+def gen_maybe_create_proxy_helper(backend_index: BackendIndex) -> list[str]:
+    _, empty_strided_impl = gen_empty_impl_names(backend_index)
+    return (
+        []
+        if empty_strided_impl is None
+        else [
+            f"""
+std::optional maybe_create_proxy(const Tensor &out, IntArrayRef sizes, IntArrayRef strides, const TensorOptions &options) {{
+  if (out.strides() != strides) {{
+    return {empty_strided_impl}(sizes, strides, options);
+  }}
+  return std::nullopt;
+}}
+"""
+        ]
+    )
+
+
+def gen_resize_out_helper(backend_index: BackendIndex) -> list[str]:
+    if backend_index.dispatch_key == DispatchKey.CompositeExplicitAutogradNonFunctional:
+        # The function isn't used by this key (since only functional ops have a kernel for this key),
+        # so we need to not include it to avoid a defined-but-not-used error.
+        return []
+    return [
+        """
+void resize_out(const Tensor &out, IntArrayRef sizes, IntArrayRef strides, const TensorOptions &options) {
+  TORCH_CHECK(options.dtype() == out.dtype(),
+      "Expected out tensor to have dtype ", options.dtype(), ", but got ", out.dtype(), " instead");
+  TORCH_CHECK(options.device() == out.device(),
+      "Expected out tensor to have device ", options.device(), ", but got ", out.device(), " instead");
+  const bool resized = at::native::resize_output(out, sizes);
+  // Only restride if a resize occurred; otherwise we ignore the (advisory)
+  // strides from the meta function and directly use the output tensor's
+  // preexisting strides
+  if (resized) {
+    if (!strides.empty()) {
+      TORCH_INTERNAL_ASSERT(!options.memory_format_opt().has_value());
+      // TODO: avoid the redispatch here
+      out.as_strided_(sizes, strides);
+    } else if (options.memory_format_opt().has_value()) {
+      out.unsafeGetTensorImpl()->empty_tensor_restride(*options.memory_format_opt());
+    }
+  }
+}
+"""
+    ]
+
+
+def gen_check_inplace_helper(backend_index: BackendIndex) -> list[str]:
+    return [
+        """
+void check_inplace(const Tensor &self, IntArrayRef sizes, const TensorOptions &options) {
+  // These checks are needed on those operators that:
+  //   1) don't use 'TensorIterator' (e.g. 'addmm' and 'baddbmm')
+  //   2) have particular typing rules (e.g. 'cumsum' and 'cumprod')
+  // For other operators (e.g. 'add'), 'TensorIterator' already checks
+  // these things separately.
+  TORCH_CHECK(options.dtype() == self.dtype(),
+      "Bad in-place call: ",
+      "input tensor dtype ", self.dtype(), " and output tensor dtype ", options.dtype(), " should match");
+  TORCH_CHECK(options.device() == self.device(),
+      "Bad in-place call: ",
+      "input tensor device ", self.device(), " and output tensor device ", options.device(), " should match");
+  TORCH_CHECK(sizes == self.sizes(),
+      "Bad in-place call: ",
+      "input tensor size ", self.sizes(), " and output tensor size ", sizes, " should match");
+}
+"""
+    ]
+
+
+def gen_registration_helpers(backend_index: BackendIndex) -> list[str]:
+    return [
+        'C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wunused-function")',
+        *gen_create_out_helper(backend_index),
+        *gen_resize_out_helper(backend_index),
+        *gen_check_inplace_helper(backend_index),
+        *gen_maybe_create_proxy_helper(backend_index),
+        "C10_DIAGNOSTIC_POP()",
+    ]
+
+
+# Generates Register{dispatch}.cpp (e.g., RegisterCPU.cpp).
+#
+#   - The primary function of this file is to register all of the
+#     implementations for the given dispatch key to the dispatcher,
+#     so they are available for use in PyTorch.  If dispatch is
+#     None, we generate schema (def) registrations and catchall
+#     registrations.
+#   - The secondary function of this file is to generate a wrapper
+#     around functions.  In CPUType these wrappers do nothing
+#     (and should be removed), but in other cases they handle
+#     DeviceGuard. A small extra benefit of wrappers is they
+#     are not overloaded, so they can be used in the registration
+#     API without having to disambiguate which overload you want
+#     (as would be the case if you directly registered native::
+#     functions).
+#   - The tertiary function of this file is to generate *static*
+#     cpp API bindings which can be used to bypass dispatcher
+#     directly to kernels, but with user-friendly cpp-style API
+@dataclass(frozen=True)
+class RegisterDispatchKey:
+    backend_index: BackendIndex
+
+    target: Literal[
+        Target.ANONYMOUS_DEFINITION,
+        Target.NAMESPACED_DEFINITION,
+        Target.NAMESPACED_DECLARATION,
+        Target.REGISTRATION,
+    ]
+
+    # Selector object to determine which operators to generate
+    # registration code for.
+    selector: SelectiveBuilder
+
+    # Whether or not we are actually code-genning for ROCm
+    rocm: bool
+
+    # Whether or not to generate symint registrations or not.  External users
+    # of codegen who don't care about symints can set this to false to get
+    # non-SymInt codegen
+    symint: bool
+
+    # The class that all unstructured native functions live under. This is used to improve
+    # compiler error messages when a kernel writer adds a native function with the wrong signature.
+    # This is only used in unstructured kernels, since structured kernels already live in a class.
+    # Finally, this field is currently Optional because it is only used by external backends.
+    # It would be nice if we can add the same logic to in-tree kernels too, but that requires updating
+    # all of the existing kernel signatures scattered across aten/src/ATen/native.
+    class_method_name: str | None
+
+    # Only set to true in lightweight dispatch. If lightweight dispatch is enabled we are registering
+    # operators into JIT op registry, thus we need to avoid generating code to register into the dispatcher.
+    skip_dispatcher_op_registration: bool
+
+    @staticmethod
+    def gen_device_check(
+        type: DeviceCheckType, args: list[Argument], method_name: str
+    ) -> str:
+        if type == DeviceCheckType.NoCheck:
+            return "  // No device check\n"
+
+        device_check = "std::optional common_device = std::nullopt;\n"
+        device_check += "(void)common_device; // Suppress unused variable warning\n"
+        for arg in args:
+            # Only tensor like arguments are eligible
+            if arg.type.is_tensor_like():
+                device_check += f"""
+  c10::impl::check_and_update_common_device(common_device, {arg.name}, "{method_name}", "{arg.name}");"""
+        return device_check
+
+    @method_with_native_function
+    def __call__(self, f: NativeFunctionsGroup | NativeFunction) -> list[str]:
+        if isinstance(f, NativeFunctionsGroup):
+            g: NativeFunctionsGroup = f
+            # Note: We call gen_structured() if the operator is marked structured, regardless of the backend.
+            # gen_structured() has special logic to handle auto-generated kernels.
+            if g.structured:
+                return self.gen_structured(g)
+            else:
+                return list(
+                    mapMaybe(lambda f: self.gen_unstructured(f, g), g.functions())
+                )
+        elif isinstance(f, NativeFunction):
+            r = self.gen_unstructured(f)
+            return [] if r is None else [r]
+        else:
+            assert_never(f)
+
+    def wrapper_kernel_sig(
+        self, f: NativeFunction
+    ) -> NativeSignature | DispatcherSignature:
+        # The prefix is just to ensure uniqueness. The Dispatcher API doesn't guarantee unique kernel names.
+        return DispatcherSignature.from_schema(
+            f.func,
+            prefix=f"wrapper_{self.backend_index.dispatch_key}_{f.func.name.overload_name}_",
+            symint=self.symint,
+        )
+
+    def gen_out_inplace_wrapper(
+        self, f: NativeFunction, g: NativeFunctionsGroup | None
+    ) -> str | None:
+        if g is None:
+            return None
+        k = f.func.kind()
+        if k is SchemaKind.inplace:
+            copy_op = "at::_copy_from"
+        elif k is SchemaKind.out:
+            copy_op = "at::_copy_from_and_resize"
+        else:
+            raise AssertionError("gen_out_inplace_wrapper called on a functional op")
+
+        sig = self.wrapper_kernel_sig(f)
+        name = sig.name()
+
+        func_res = f"{name}_tmp"
+        return_names = cpp.return_names(f)
+        if len(return_names) > 1:
+            updates = "\n  ".join(
+                f"{copy_op}(std::get<{i}>({func_res}), {ret_name});"
+                for i, ret_name in enumerate(return_names)
+            )
+            returns = f"{sig.returns_type().cpp_type()}({', '.join(return_names)})"
+        elif len(return_names) == 1:
+            ret_name = return_names[0]
+            updates = f"{copy_op}({func_res}, {ret_name});"
+            returns = ret_name
+        else:
+            assert len(f.func.arguments.out) == 1
+            returns = ""
+            out_arg = f.func.arguments.out[0]
+            if out_arg.type.is_list_like():
+                updates = f"""\
+    for (int64_t i = 0; i < {func_res}.size(); ++i) {{
+        {copy_op}({func_res}[i], {out_arg.name}[i]);
+    }}"""
+            else:
+                updates = f"{copy_op}({func_res}, {out_arg.name});"
+
+        functional_sig = self.wrapper_kernel_sig(g.functional)
+        wrapper_name = sig.name()
+
+        return f"""\
+{sig.defn(name=wrapper_name)} {{
+  auto {func_res} = {functional_sig.name()}({", ".join(e.expr for e in translate(sig.arguments(), functional_sig.arguments()))});
+  {updates}
+  return {returns};
+}}
+"""
+
+    def gen_structured(self, g: NativeFunctionsGroup) -> list[str]:
+        metadata = self.backend_index.get_kernel(g)
+        if self.backend_index.dispatch_key == DispatchKey.Meta:
+            assert not self.backend_index.has_kernel(g.out), (
+                "Do not explicitly specify Meta dispatch key on structured "
+                "functions, they will be automatically generated for you"
+            )
+        elif (
+            self.backend_index.dispatch_key
+            == DispatchKey.CompositeExplicitAutogradNonFunctional
+        ):
+            assert not self.backend_index.has_kernel(g.out), (
+                "Do not explicitly specify CompositeExplicitAutograd dispatch key on structured "
+                "functions, they will be automatically generated for you"
+            )
+        elif metadata is None or not metadata.structured:
+            return list(mapMaybe(lambda f: self.gen_unstructured(f, g), g.functions()))
+        structured_gen = StructuredRegisterDispatchKey(
+            self.backend_index,
+            self.target,
+            self.selector,
+            self.rocm,
+            self.symint,
+            self.class_method_name,
+            self.skip_dispatcher_op_registration,
+            g,
+        )
+        return list(mapMaybe(structured_gen.gen_one, g.functions()))
+
+    def gen_unstructured(
+        self, f: NativeFunction, g: NativeFunctionsGroup | None = None
+    ) -> str | None:
+        with native_function_manager(f):
+            inplace_meta = False
+            gets_out_inplace_wrapper = False
+            if not self.backend_index.has_kernel(f):
+                if (
+                    self.backend_index.dispatch_key == DispatchKey.Meta
+                    and f.func.kind() is SchemaKind.inplace
+                    and
+                    # Defer to composites for meta implementation
+                    not f.has_composite_kernel
+                    and
+                    # Inplace list operations are not supported
+                    len(f.func.returns) == 1
+                ):
+                    inplace_meta = True
+                elif (
+                    not self.backend_index.use_out_as_primary
+                    and g is not None
+                    and gets_generated_out_inplace_wrapper(f, g, self.backend_index)
+                ):
+                    # We want to generate inplace/out wrappers, that don't have a kernel for the backend.
+                    gets_out_inplace_wrapper = True
+                else:
+                    return None
+            if f.manual_kernel_registration:
+                return None
+
+            if (
+                self.target is Target.REGISTRATION
+                and not self.selector.is_native_function_selected(f)
+            ):
+                return None
+
+            sig = self.wrapper_kernel_sig(f)
+
+            name = sig.name()
+            returns_type = sig.returns_type().cpp_type()
+            args = sig.arguments()
+            args_str = ", ".join(a.defn() for a in args)
+
+            # See Note [Direct dispatch bindings]
+            cpp_sig_group = CppSignatureGroup.from_native_function(
+                f, method=False, fallback_binding=False
+            )
+
+            # TODO: dedupe this with the structured codegen
+            if self.target is Target.NAMESPACED_DECLARATION:
+                result = ""
+                for cpp_sig in cpp_sig_group.signatures(symint=self.symint):
+                    result += f"TORCH_API {cpp_sig.decl()};\n"
+                return result
+            elif self.target is Target.NAMESPACED_DEFINITION:
+
+                def generate_defn(cpp_sig: CppSignature) -> str:
+                    return f"""
+{cpp_sig.defn()} {{
+return {sig.name()}({", ".join(e.expr for e in translate(cpp_sig.arguments(), sig.arguments()))});
+}}
+"""
+
+                result = ""
+                for cpp_sig in cpp_sig_group.signatures(symint=self.symint):
+                    result += generate_defn(cpp_sig)
+                return result
+
+            elif self.target is Target.ANONYMOUS_DEFINITION:
+                # short circuit for inplace_meta
+                if inplace_meta:
+                    assert f.func.arguments.self_arg is not None
+                    self_arg_name = f.func.arguments.self_arg.argument.name
+                    # TODO: handle in place on tensor list
+                    return f"""
+{returns_type} {name}({args_str}) {{
+  TORCH_CHECK_NOT_IMPLEMENTED({self_arg_name}.is_meta(),
+    "Cannot inplace into non-meta tensor with meta tensor argument");
+  return {self_arg_name};
+}}
+"""
+
+                # short circuit for generated inplace/out wrappers
+                if gets_out_inplace_wrapper:
+                    return self.gen_out_inplace_wrapper(f, g)
+
+                metadata = self.backend_index.get_kernel(f)
+                if metadata is None:
+                    return None
+                if self.class_method_name is None:
+                    impl_name = f"{metadata.cpp_namespace}::{metadata.kernel}"
+                else:
+                    impl_name = f"{metadata.cpp_namespace}::{self.class_method_name}::{metadata.kernel}"
+
+                kernel_sig = kernel_signature(f, self.backend_index)
+
+                args_exprs_str = ", ".join(
+                    e.expr
+                    for e in translate(
+                        sig.arguments(), kernel_sig.arguments(), method=False
+                    )
+                )
+
+                device_check = "  // No device check\n"
+                # Backends that require device guards presumably also require device checks.
+                if self.backend_index.device_guard:
+                    device_check_args = itertools.chain(
+                        f.func.arguments.out, f.func.arguments.flat_positional
+                    )
+                    device_check = RegisterDispatchKey.gen_device_check(
+                        f.device_check, list(device_check_args), name
+                    )
+
+                device_guard = "// DeviceGuard omitted"  # default
+                if f.device_guard and self.backend_index.device_guard:
+                    has_tensor_options = any(
+                        isinstance(a, TensorOptionsArguments)
+                        for a in f.func.arguments.non_out
+                    )
+                    if has_tensor_options:
+                        # kernel is creating a tensor
+                        device_guard = """
+  const DeviceGuard device_guard(device_or_default(device));"""
+
+                        # CUDA requires special handling
+                        if is_cuda_dispatch_key(self.backend_index.dispatch_key):
+                            device_guard = f"globalContext().lazyInitDevice(c10::DeviceType::CUDA);\n{device_guard}"
+                    else:
+                        # kernel is operating on existing tensors
+
+                        # There is precedence for which argument we use to do
+                        # device guard.  This describes the precedence order.
+                        self_arg = (
+                            [f.func.arguments.self_arg.argument]
+                            if f.func.arguments.self_arg is not None
+                            else []
+                        )
+                        candidate_args = itertools.chain(
+                            self_arg,
+                            f.func.arguments.out,
+                            f.func.arguments.flat_positional,
+                        )
+
+                        # Only tensor like arguments are eligible
+                        device_of = next(
+                            (
+                                f"{a.name}"
+                                for a in candidate_args
+                                if a.type.is_tensor_like()
+                            ),
+                            None,
+                        )
+                        if device_of is not None:
+                            device_guard = f"const OptionalDeviceGuard device_guard(device_of({device_of}));"
+
+                return f"""\
+namespace {{
+
+{returns_type} {name}({args_str}) {{
+  {device_check}
+
+  {device_guard}
+  return {impl_name}({args_exprs_str});
+}}
+
+}} // anonymous namespace
+"""
+
+            elif self.target is Target.REGISTRATION:
+                if f.manual_kernel_registration or self.skip_dispatcher_op_registration:
+                    return None
+                else:
+                    payload = f"TORCH_FN({name})"
+                    return f'm.impl("{f.func.name}",\n{payload});\n'
+            else:
+                assert_never(self.target)
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                           STRUCTURED
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+@dataclass(frozen=True)
+class StructuredRegisterDispatchKey(RegisterDispatchKey):
+    g: NativeFunctionsGroup
+
+    def gen_class_set_output_functions(
+        self, k: SchemaKind, parent_class: str, generate_super: bool
+    ) -> str:
+        if generate_super:
+            set_output_super = f"{parent_class}::set_output_raw_strided(output_idx, sizes, strides, options, names);"
+        else:
+            set_output_super = ""
+
+        def gen_set_output_function(name: str, maybe_create_proxy: bool) -> str:
+            return f"""
+void set_output_{name}(
+    int64_t output_idx, IntArrayRef sizes, IntArrayRef strides,
+    TensorOptions options, DimnameList names
+) override {{
+{textwrap.indent(self.gen_class_set_output_body(k, maybe_create_proxy), "    ")}
+    if (!names.empty()) {{
+      namedinference::propagate_names(outputs_[output_idx], names);
+    }}
+    // super must happen after, so that downstream can use maybe_get_output
+    // to retrieve the output
+{textwrap.indent(set_output_super, "    ")}
+}}
+"""
+
+        return f"""
+{gen_set_output_function("strided", maybe_create_proxy=True)}
+{gen_set_output_function("raw_strided", maybe_create_proxy=False)}
+"""
+
+    def gen_class_set_output_body(self, k: SchemaKind, maybe_create_proxy: bool) -> str:
+        if self.backend_index.dispatch_key in [
+            DispatchKey.CUDA,
+            DispatchKey.MPS,
+            DispatchKey.XPU,
+            DispatchKey.CompositeExplicitAutogradNonFunctional,
+        ]:
+            maybe_set_guard = """
+auto current_device = guard_.current_device();
+if (C10_UNLIKELY(current_device.has_value())) {
+  TORCH_INTERNAL_ASSERT(*current_device == options.device(),
+    "structured kernels don't support multi-device outputs");
+} else {
+  guard_.reset_device(options.device());
+}
+"""
+            maybe_set_guard_line = maybe_set_guard + "\n"
+        else:
+            maybe_set_guard_line = maybe_set_guard = ""
+
+        if maybe_create_proxy:
+            create_proxy = """
+auto maybe_proxy = maybe_create_proxy(out, sizes, strides, options);
+if (C10_UNLIKELY(maybe_proxy.has_value())) {
+    proxy_outputs_[output_idx] = std::move(maybe_proxy).value();
+}
+"""
+        else:
+            create_proxy = ""
+
+        if k is SchemaKind.functional:
+            assert self.backend_index.dispatch_key in (
+                DispatchKey.Meta,
+                DispatchKey.CPU,
+                DispatchKey.CUDA,
+                DispatchKey.MPS,
+                DispatchKey.XPU,
+                DispatchKey.MTIA,
+                DispatchKey.CompositeExplicitAutogradNonFunctional,
+            )
+            return f"""{maybe_set_guard_line}
+outputs_[output_idx] = create_out(sizes, strides, options);"""
+        elif k is SchemaKind.inplace:
+            return f"""{maybe_set_guard_line}
+const auto& out = outputs_[output_idx].get();
+check_inplace(out, sizes, options);
+{create_proxy}"""
+        elif k is SchemaKind.out:
+            return f"""{maybe_set_guard_line}
+const auto& out = outputs_[output_idx].get();
+resize_out(out, sizes, strides, options);
+{create_proxy}"""
+        elif k is SchemaKind.mutable or k is SchemaKind.scratch:
+            raise AssertionError(
+                f"{k} structured operators are currently not supported"
+            )
+        else:
+            assert_never(k)
+
+    # returns the definition of a ctor, as well as how to construct
+    # this class to a variable named op
+    def gen_class_ctor(self, k: SchemaKind, class_name: str, returns: int) -> str:
+        if k is SchemaKind.functional:
+            return ""
+        elif k is SchemaKind.inplace:
+            # TODO: Make sure out argument is guaranteed to be self
+            return f"{class_name}(Tensor& self) : outputs_{{std::ref(self)}} {{}}"
+        elif k is SchemaKind.out:
+            out_args = ", ".join(f"Tensor& out{i}" for i in range(returns))
+            out_refs = ", ".join(f"std::ref(out{i})" for i in range(returns))
+            return f"{class_name}({out_args}) : outputs_{{ {out_refs} }} {{}}"
+        elif k is SchemaKind.mutable or k is SchemaKind.scratch:
+            raise AssertionError(
+                f"{k} structured operators are currently not supported"
+            )
+        else:
+            assert_never(k)
+
+    def gen_class(
+        self,
+        f: NativeFunction,
+        k: SchemaKind,
+        *,
+        class_name: str,
+        parent_class: str,
+        generate_super: bool,
+    ) -> str:
+        if k is SchemaKind.functional:
+            output_type = "Tensor"
+            output_value = "outputs_[output_idx]"
+            proxy_field = ""
+        elif k is SchemaKind.inplace:
+            output_type = "std::reference_wrapper"
+            output_value = "proxy_outputs_[output_idx].has_value() ? *proxy_outputs_[output_idx] : outputs_[output_idx].get()"
+            proxy_field = f"std::array<::std::optional, {len(f.func.returns)}> proxy_outputs_;"
+        elif k is SchemaKind.out:
+            output_type = "std::reference_wrapper"
+            output_value = "proxy_outputs_[output_idx].has_value() ? *proxy_outputs_[output_idx] : outputs_[output_idx].get()"
+            proxy_field = f"std::array<::std::optional, {len(f.func.returns)}> proxy_outputs_;"
+        else:
+            raise RuntimeError(f"Unsupported SchemaKind {k}")
+
+        if self.backend_index.dispatch_key == DispatchKey.CUDA:
+            if self.rocm:
+                guard_field = "c10::hip::OptionalHIPGuardMasqueradingAsCUDA guard_;"
+            else:
+                guard_field = "c10::cuda::OptionalCUDAGuard guard_;"
+        elif (
+            self.backend_index.dispatch_key
+            == DispatchKey.CompositeExplicitAutogradNonFunctional
+        ):
+            guard_field = "c10::OptionalDeviceGuard guard_;"
+        elif self.backend_index.dispatch_key == DispatchKey.MPS:
+            # TODO: Move to OptionalMPSGuard.
+            guard_field = "c10::OptionalDeviceGuard guard_;"
+        elif self.backend_index.dispatch_key == DispatchKey.XPU:
+            guard_field = "c10::OptionalDeviceGuard guard_;"
+        elif self.backend_index.dispatch_key == DispatchKey.MTIA:
+            guard_field = "c10::OptionalDeviceGuard guard_;"
+        else:
+            guard_field = ""
+
+        indent = " " * 4
+        class_ctor_str = self.gen_class_ctor(k, class_name, len(f.func.returns))
+        lines = (
+            f"struct {class_name} final : public {parent_class} {{",
+            f"{textwrap.indent(class_ctor_str, indent)}",
+            f"{textwrap.indent(self.gen_class_set_output_functions(k, parent_class, generate_super), indent)}",
+            "    const Tensor& maybe_get_output(int64_t output_idx) override {",
+            f"      return {output_value};\n",  # type: ignore[possibly-undefined]  # TODO: audit
+            "    }",
+            # type: ignore[possibly-undefined]  # TODO: audit
+            f"    std::array<{output_type}, {len(f.func.returns)}> outputs_;",
+            f"{textwrap.indent(proxy_field, indent)}",  # type: ignore[possibly-undefined]  # TODO: audit
+            f"{textwrap.indent(guard_field, indent)}",
+            "};",
+        )
+        return "\n".join(line for line in lines if line)
+
+    @method_with_native_function
+    def gen_one(self, f: NativeFunction) -> str | None:
+        assert not f.manual_kernel_registration
+
+        if (
+            self.target is Target.REGISTRATION
+            and not self.selector.is_native_function_selected(f)
+        ):
+            return None
+
+        # TODO: Now, there is something interesting going on here.  In the code below,
+        # we generate CompositeExplicitAutogradNonFunctional implementations of functional and inplace
+        # based on the out implementation.  But in fact, out is definable by
+        # functional too (just not very efficiently), and this is honestly the
+        # MORE likely situation for a backend implementer.  How do we pick?
+        # Well, taking a page from Haskell type classes and default methods,
+        # we could conceivably register a circular definition (out in terms
+        # of functional, and functional in terms of out) and just require
+        # someone to implement one or the other.  We'd have to do a little bit
+        # of work to not register one of these "weak" definitions unless there
+        # is a strong definition somewhere in the DAG!  So it's not implemented yet.
+        if (
+            self.backend_index.dispatch_key
+            == DispatchKey.CompositeExplicitAutogradNonFunctional
+            and f.func.kind() is SchemaKind.out
+        ):
+            # Never generate a default implementation for out, that's what you
+            # have to define as a backend implementer
+            return None
+
+        # Note [Direct dispatch bindings]
+        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        # Signature of the non-dispatched function we'll expose in a header
+        # (e.g., at::cpu::add).  We don't generate methods (TODO: do this
+        # when CPUTensor class is a thing); nor do we generate fallback
+        # bindings for manual_cpp_binding functions.
+        cpp_sig_group = CppSignatureGroup.from_native_function(
+            f, method=False, fallback_binding=False
+        )
+
+        # Signature of the wrapper function we'll register to the dispatcher
+        kern = self.backend_index.get_kernel(f)
+        sig = NativeSignature(
+            f.func,
+            prefix=f"wrapper_{self.backend_index.dispatch_key}_",
+            symint=kern is not None and kern.supports_symint(),
+        )
+
+        if self.target is Target.NAMESPACED_DECLARATION:
+            result = ""
+            for cpp_sig in cpp_sig_group.signatures(symint=self.symint):
+                result += f"TORCH_API {cpp_sig.decl()};\n"
+            return result
+
+        elif self.target is Target.NAMESPACED_DEFINITION:
+
+            def generate_defn(cpp_sig: CppSignature) -> str:
+                return f"""
+{cpp_sig.defn()} {{
+return {sig.name()}({", ".join(e.expr for e in translate(cpp_sig.arguments(), sig.arguments()))});
+}}
+"""
+
+            result = ""
+            for cpp_sig in cpp_sig_group.signatures(symint=self.symint):
+                result += generate_defn(cpp_sig)
+            return result
+
+        elif self.target is Target.ANONYMOUS_DEFINITION:
+            k = f.func.kind()
+
+            # Construct the body of the wrapper function with signature sig
+            sig_body = []
+            # We'll use context to keep track of any variables we've brought
+            # into scope while generating code
+            context: list[Binding | Expr] = list(sig.arguments())
+
+            # Initialize the class corresponding to this structured
+            # operator; feeding it the output argument(s) if it is known
+            if self.backend_index.dispatch_key is DispatchKey.Meta:
+                class_name = f"structured_{meta.name(self.g)}_meta_{k.name}"
+                parent_class = f"at::meta::structured_{meta.name(self.g)}"
+            elif (
+                self.backend_index.dispatch_key
+                is DispatchKey.CompositeExplicitAutogradNonFunctional
+            ):
+                # TODO: dedup this branch
+                class_name = f"structured_{meta.name(self.g)}_default_backend_{k.name}"
+                parent_class = f"at::meta::structured_{meta.name(self.g)}"
+            else:
+                metadata = self.backend_index.get_kernel(self.g)
+                assert metadata is not None
+                class_name = f"structured_{metadata.kernel}_{k.name}"
+                parent_class = f"{metadata.cpp_namespace}::structured_{metadata.kernel}"
+
+            if self.backend_index.device_guard:
+                device_check_args = itertools.chain(
+                    f.func.arguments.out, f.func.arguments.flat_positional
+                )
+                sig_body.append(
+                    RegisterDispatchKey.gen_device_check(
+                        f.device_check, list(device_check_args), sig.name()
+                    )
+                )
+
+            if k is SchemaKind.functional:
+                sig_body.append(f"{class_name} op;")
+            elif k is SchemaKind.inplace:
+                sig_body.append(f"{class_name} op(self);")
+            elif k is SchemaKind.out:
+                out_args_str = ", ".join(a.name for a in f.func.arguments.out)
+                sig_body.append(f"{class_name} op({out_args_str});")
+
+            # Translate the input native arguments into structured
+            # arguments for the meta call
+            meta_exprs = ", ".join(
+                e.expr
+                for e in translate(
+                    context, structured.meta_arguments(self.g), method=False
+                )
+            )
+
+            if self.g.out.precomputed:
+                # If this function group has precomputed elements, the meta function
+                # returns a struct containing them which must be saved so that it
+                # can be unpacked when generating code to call the impl.
+                sig_body.append(f"auto precompute = op.meta({meta_exprs});")
+
+                # Put all of the contents of the precompute struct into the context
+                # so that translate will be able to return the correct args for the
+                # call to the impl.
+                precomputed_values = [
+                    *self.g.out.precomputed.replace.values(),
+                    self.g.out.precomputed.add,
+                ]
+                for precomputed_elems in precomputed_values:
+                    context.extend(
+                        Expr(
+                            expr=f"precompute.{arg.name}",
+                            type=structured.argument_type(arg, binds=arg.name),
+                        )
+                        for arg in precomputed_elems
+                    )
+
+                # Add a use of the precompute struct so FB internal compilers don't
+                # complain that there is an unused variable.
+                sig_body.append("(void)precompute;")
+            else:
+                sig_body.append(f"op.meta({meta_exprs});")
+
+            # After running meta, op.outputs_ is guaranteed to be valid;
+            # add it to the context
+            out_args = structured.out_arguments(self.g)
+            for i, out_arg in enumerate(out_args):
+                assert ConstRefCType(BaseCType(tensorT)) == out_arg.nctype.type
+
+                if k is SchemaKind.out:
+                    expr = f"op.maybe_get_output({i})"
+                else:
+                    expr = f"op.outputs_[{i}]"
+
+                context.append(
+                    Expr(
+                        expr=expr,
+                        # TODO: Stop hardcoding that the output type is a Tensor.  Note
+                        # that for the codegen here this is fine because outputs_ is
+                        # hardcoded to be tensor already
+                        type=NamedCType(
+                            out_arg.nctype.name, MutRefCType(BaseCType(tensorT))
+                        ),
+                    )
+                )
+
+            # With the expanded context, do the impl call (if not a meta
+            # function)
+            if (
+                self.backend_index.dispatch_key
+                == DispatchKey.CompositeExplicitAutogradNonFunctional
+            ):
+                # TODO: https://github.com/pytorch/pytorch/issues/53023
+                out_sig_group = CppSignatureGroup.from_native_function(
+                    self.g.out, method=False, fallback_binding=f.manual_cpp_binding
+                )
+                out_sig = out_sig_group.most_faithful_signature()
+                api_name = out_sig.name()
+                out_exprs = ", ".join(
+                    e.expr
+                    for e in translate(context, out_sig.arguments(), method=False)
+                )
+                # TODO: I think this means structured won't work with method
+                # only functions (but maybe you're saved by faithful? iunno.)
+                # NB: Originally I wrote this as an at::redispatch call, but
+                # I got in trouble because that meant I needed a DispatchKeySet
+                # in the wrapper function, which meant I needed a DispatchKeySet
+                # in the DispatchKeyFunctions declarations, but the defined API
+                # there does NOT permit a dispatch key set.  I think you can
+                # probably unwind this by calling some function to do the TLS
+                # fetch and get the DispatchKeySet when you don't have it, but
+                # I didn't do it for this version
+                sig_body.append(f"at::{api_name}({out_exprs});")
+            elif self.backend_index.dispatch_key != DispatchKey.Meta:
+                impl_exprs = ", ".join(
+                    e.expr
+                    for e in translate(
+                        context, structured.impl_arguments(self.g), method=False
+                    )
+                )
+                sig_body.append(f"op.impl({impl_exprs});")
+
+            # Go over each output, and check if there is a proxy created for it.
+            # If so, copy it over to the original output.
+            if k is SchemaKind.out or k is SchemaKind.inplace:
+                for i in range(len(f.func.returns)):
+                    sig_body.append(
+                        f"if (op.proxy_outputs_[{i}].has_value()) op.outputs_[{i}].get().copy_(*op.proxy_outputs_[{i}]);"
+                    )
+
+            # Destructively return the final tensors
+            # TODO: Do this in translate instead
+            if k is SchemaKind.functional:
+                if len(f.func.returns) == 1:
+                    ret_expr = "std::move(op.outputs_[0])"  # small optimization
+                else:
+                    moved = ", ".join(
+                        f"std::move(op.outputs_[{i}])"
+                        for i in range(len(f.func.returns))
+                    )
+                    ret_expr = f"std::make_tuple({moved})"
+            elif k is SchemaKind.inplace:
+                ret_expr = "self"
+            elif k is SchemaKind.out:
+                if len(f.func.returns) == 1:
+                    ret_expr = f.func.arguments.out[0].name
+                else:
+                    refs = ", ".join(a.name for a in f.func.arguments.out)
+                    ret_expr = f"std::forward_as_tuple({refs})"
+            sig_body.append(f"return {ret_expr};")  # type: ignore[possibly-undefined]  # TODO: audit
+
+            sig_body_str = "\n".join(sig_body)
+
+            # For an overview of what this template code looks like, see
+            # https://github.com/pytorch/rfcs/pull/9
+            return f"""\
+{
+                self.gen_class(
+                    f,
+                    k,
+                    class_name=class_name,
+                    parent_class=parent_class,
+                    generate_super=self.g.out.structured_inherits is not None,
+                )
+            }
+
+{sig.defn()} {{
+{sig_body_str}
+}}
+"""
+
+        elif self.target is Target.REGISTRATION:
+            return f'm.impl("{f.func.name}", TORCH_FN({sig.name()}));'
+        else:
+            assert_never(self.target)
+            # Silence mypy's "Missing return statement" error
+            return None
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/dest/ufunc.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/dest/ufunc.py
new file mode 100644
index 0000000000000000000000000000000000000000..045d8de110e7442d0732aee483f0aab7015140d7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/dest/ufunc.py
@@ -0,0 +1,553 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+import torchgen.api.ufunc as ufunc
+from torchgen.api.translate import translate
+from torchgen.api.types import (
+    BaseCType,
+    Binding,
+    CType,
+    Expr,
+    NamedCType,
+    opmath_t,
+    scalar_t,
+    StructuredImplSignature,
+    VectorizedCType,
+)
+from torchgen.context import with_native_function
+from torchgen.model import (
+    Argument,
+    BaseTy,
+    BaseType,
+    DispatchKey,
+    NativeFunctionsGroup,
+    ScalarType,
+    UfuncKey,
+)
+from torchgen.utils import OrderedSet
+
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+
+    from torchgen.api.ufunc import UfunctorBindings
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                                  CUDA STUFF
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+# NB: not bothering to generate dispatch stub forward declaration in header,
+# we can just paste it wherever necessary
+
+# TODO: use BackendIndex
+# dispatch_key: DispatchKey  # only CPU/CUDA right now
+
+
+# Represents functors for implementing CUDA ufuncs.
+# Functors are templated by scalar_t because when USERS instantiate functors
+# they are templated.  A functor looks something like this:
+#
+#   template 
+#   struct CUDAFunctorOnSelf_add {
+#     using opmath_t = at::opmath_type;
+#     opmath_t other_;
+#     opmath_t alpha_;
+#     CUDAFunctorOnSelf_add(opmath_t other, opmath_t alpha)
+#         : other_(other), alpha_(alpha) {}
+#     __device__ scalar_t operator()(scalar_t self) {
+#       return ufunc::add(static_cast(self), other_, alpha_);
+#     }
+#   };
+#
+@dataclass(frozen=True)
+class UfunctorSignature:
+    g: NativeFunctionsGroup
+    scalar_tensor_idx: int | None
+    name: str
+
+    def arguments(self) -> UfunctorBindings:
+        return ufunc.ufunctor_arguments(
+            self.g, scalar_tensor_idx=self.scalar_tensor_idx, scalar_t=scalar_t
+        )
+
+    def fields(self) -> list[Binding]:
+        # fields are renamed to have a trailing underscore, as is conventional
+        return [b.rename(f"{b.name}_") for b in self.arguments().ctor]
+
+    def returns_type(self) -> CType:
+        # TODO: don't hardcode; return type will be inferred based on tags on
+        # the native function
+        return BaseCType(scalar_t)
+
+    def decl_fields(self) -> str:
+        return "\n".join(f"{f.type} {f.name};" for f in self.fields())
+
+    def inline_defn_ctor(self) -> str:
+        args_str = ", ".join(a.decl() for a in self.arguments().ctor)
+        # NB: hypothetically could do this with translate but the
+        # transition here is very regular
+        init_str = ", ".join(f"{a.name}_({a.name})" for a in self.arguments().ctor)
+        return f"{self.name}({args_str}) : {init_str} {{}}"
+
+    def decl_apply(self) -> str:
+        args_str = ", ".join(a.decl() for a in self.arguments().apply)
+        return f"{self.returns_type().cpp_type()} operator()({args_str}) const"
+
+
+@dataclass(frozen=True)
+class UfuncSignature:
+    g: NativeFunctionsGroup
+    name: str
+    compute_t: CType
+
+    def arguments(self) -> list[Binding]:
+        return ufunc.ufunc_arguments(self.g, compute_t=self.compute_t)
+
+    def call(self, ctx: Sequence[Binding | Expr]) -> str:
+        return f"{self.name}({', '.join(a.expr for a in translate(ctx, self.arguments()))})"
+
+
+# steps:
+#   1. take the functional signature
+#   2. use api.ufunc to convert it to template signature.  this establishes
+#      the type of the template function
+#   3. use api.ufunc (II) to generate a split struct / operator() signature.
+#      this establish context in which we call the template signature
+#
+# StructuredImplSignature context
+#   ~> functor constructor sig
+#
+# Functor constructor context
+#   ~> functor fields sig
+#
+# Functor apply context (functor fields + functor apply sig)
+#   ~> template sig
+#
+
+
+def eligible_for_binary_scalar_specialization(g: NativeFunctionsGroup) -> bool:
+    num_tensors = sum(
+        1 for a in g.functional.func.arguments.flat_non_out if a.type.is_tensor_like()
+    )
+    return num_tensors == 2
+
+
+def compute_ufunc_cuda_functors(
+    g: NativeFunctionsGroup,
+) -> tuple[dict[ScalarType, dict[UfuncKey, UfunctorSignature]], str]:
+    # First, build the functors.
+    ufunctor_sigs: dict[ScalarType, dict[UfuncKey, UfunctorSignature]] = {}
+    ufunctors: list[str] = []
+    loops = g.out.ufunc_inner_loop
+    scalar_tensor_idx_lookup = {
+        UfuncKey.CUDAFunctorOnSelf: 1,
+        UfuncKey.CUDAFunctorOnOther: 0,
+        UfuncKey.CUDAFunctor: None,
+    }
+    if eligible_for_binary_scalar_specialization(g):
+        keys = [
+            UfuncKey.CUDAFunctorOnSelf,
+            UfuncKey.CUDAFunctorOnOther,
+            UfuncKey.CUDAFunctor,
+        ]
+    else:
+        keys = [UfuncKey.CUDAFunctor]
+        for k in [UfuncKey.CUDAFunctorOnSelf, UfuncKey.CUDAFunctorOnOther]:
+            assert k not in loops, f"cannot use {k} on non-binary function"
+    for k in keys:
+        # If the key was directly defined, skip functor codegen; we assume the
+        # user already done it for us
+        if k in loops:
+            ufunctor_sig = UfunctorSignature(
+                g, scalar_tensor_idx=scalar_tensor_idx_lookup[k], name=loops[k].name
+            )
+            for dtype in loops[k].supported_dtypes:
+                ufunctor_sigs.setdefault(dtype, {})[k] = ufunctor_sig
+            continue
+
+        # Note [ScalarOnly and Generic must match names for CUDA]
+        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+        # Otherwise, look in ANY of the generic entries.  For simplicity of
+        # codegen, both ScalarOnly and Generic are defined, the ufunc name
+        # must match  (if they didn't match, we'd have to generate distinct
+        # functors per dtype, which is awful, so we're not going to do it unless
+        # someone really forces us to)
+        ufunc_name = None
+        supported_dtypes: OrderedSet[ScalarType] = OrderedSet()
+        for lk in [UfuncKey.ScalarOnly, UfuncKey.Generic]:
+            if lk not in loops:
+                continue
+            if ufunc_name is None:
+                ufunc_name = loops[lk].name
+            else:
+                # See Note [ScalarOnly and Generic must match names for CUDA]
+                assert ufunc_name == loops[lk].name, (
+                    "ScalarOnly and Generic must have same ufunc name"
+                )
+            supported_dtypes |= loops[lk].supported_dtypes
+        assert ufunc_name is not None
+
+        name = f"{k}_{ufunc_name}"
+        ufunctor_sig = UfunctorSignature(
+            g, scalar_tensor_idx=scalar_tensor_idx_lookup[k], name=name
+        )
+        for dtype in supported_dtypes:
+            ufunctor_sigs.setdefault(dtype, {})[k] = ufunctor_sig
+
+        ufunc_sig = UfuncSignature(
+            g, name=f"ufunc::{ufunc_name}", compute_t=BaseCType(opmath_t)
+        )
+        apply_ctx = ufunctor_sig.fields() + ufunctor_sig.arguments().apply
+        ufunctors.append(
+            f"""
+template 
+struct {ufunctor_sig.name} {{
+  using opmath_t = at::opmath_type;
+  {ufunctor_sig.decl_fields()}
+  {ufunctor_sig.inline_defn_ctor()}
+  __device__ {ufunctor_sig.decl_apply()} {{
+    return {ufunc_sig.call(apply_ctx)};
+  }}
+}};
+"""
+        )
+
+    return ufunctor_sigs, "\n".join(ufunctors)
+
+
+@dataclass(frozen=True)
+class BinaryScalarSpecializationConfig:
+    scalar_idx: int
+    ctor_tensor: str
+    ufunc_key: UfuncKey
+
+
+BinaryScalarSpecializationConfigs = [
+    BinaryScalarSpecializationConfig(
+        scalar_idx=0,
+        ctor_tensor="self",
+        ufunc_key=UfuncKey.CUDAFunctorOnOther,
+    ),
+    BinaryScalarSpecializationConfig(
+        scalar_idx=1,
+        ctor_tensor="other",
+        ufunc_key=UfuncKey.CUDAFunctorOnSelf,
+    ),
+]
+
+
+def compute_ufunc_cuda_dtype_body(
+    g: NativeFunctionsGroup,
+    dtype: ScalarType,
+    inner_loops: dict[UfuncKey, UfunctorSignature],
+    parent_ctx: Sequence[Binding],
+) -> str:
+    body = "using opmath_t = at::opmath_type;"
+    body += "if (false) {}\n"  # for ease of codegen
+    for config in BinaryScalarSpecializationConfigs:
+        if config.ufunc_key not in inner_loops:
+            continue
+        ufunctor_sig = inner_loops[config.ufunc_key]
+        scalar_idx = config.scalar_idx + 1
+        # Make a copy and at the same time widen the type (not permissible
+        # without copy; we don't want to mutate the input argument anyway)
+        ctx: list[Expr | Binding] = list(parent_ctx)
+        ctx.append(
+            Expr(
+                expr=f"iter.scalar_value({scalar_idx})",
+                type=NamedCType(config.ctor_tensor, BaseCType(opmath_t)),
+            )
+        )
+        ufunctor_ctor_exprs_str = ", ".join(
+            a.expr for a in translate(ctx, ufunctor_sig.arguments().ctor)
+        )
+
+        # NB: ufunctor must be allocated before iter.remove_operand is called,
+        # as it relies on iter
+        body += f"""\
+else if (iter.is_cpu_scalar({scalar_idx})) {{
+  {ufunctor_sig.name} ufunctor({ufunctor_ctor_exprs_str});
+  iter.remove_operand({scalar_idx});
+  gpu_kernel(iter, ufunctor);
+}}"""
+
+    ufunctor_sig = inner_loops[UfuncKey.CUDAFunctor]
+    ufunctor_ctor_exprs_str = ", ".join(
+        a.expr for a in translate(parent_ctx, ufunctor_sig.arguments().ctor)
+    )
+    body += f"""
+else {{
+  gpu_kernel(iter, {ufunctor_sig.name}({ufunctor_ctor_exprs_str}));
+}}
+    """
+    return body
+
+
+@with_native_function
+def compute_ufunc_cuda(g: NativeFunctionsGroup) -> str:
+    # First, build the functors, indexing them by dtype
+    ufunctor_sigs, ufunctors = compute_ufunc_cuda_functors(g)
+
+    # Next, build the conditionals
+    sig = StructuredImplSignature(g, ufunc.kernel_name(g, DispatchKey.CUDA))
+    dtype_cases = []
+    for dtype, inner_ufunc_sigs in ufunctor_sigs.items():
+        dtype_cases.append(
+            f"""
+AT_DISPATCH_CASE(at::ScalarType::{dtype},
+  [&]() {{
+    {compute_ufunc_cuda_dtype_body(g, dtype, inner_ufunc_sigs, sig.arguments())}
+  }}
+)
+"""
+        )
+
+    dtype_cases_str = "\n".join(dtype_cases)
+
+    stub_sig = StubSignature(g)
+
+    return f"""
+{ufunctors}
+
+{stub_sig.type_defn()};
+{stub_sig.dispatch_decl()}
+
+{stub_sig.kernel_defn()} {{
+  AT_DISPATCH_SWITCH(iter.common_dtype(), "{sig.name}",
+    {dtype_cases_str}
+  );
+}}
+REGISTER_DISPATCH({stub_sig.name}, &{stub_sig.kernel_name})
+
+{sig.defn()} {{
+  {stub_sig.direct_call(sig.arguments())};
+}}
+"""
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                                   CPU STUFF
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+@dataclass(frozen=True)
+class StubSignature:
+    g: NativeFunctionsGroup
+
+    @property
+    def name(self) -> str:
+        return f"{str(self.g.functional.func.name.name)}_stub"
+
+    @property
+    def kernel_name(self) -> str:
+        return f"{str(self.g.functional.func.name.name)}_kernel"
+
+    @property
+    def type_name(self) -> str:
+        return f"{str(self.g.functional.func.name.name)}_fn"
+
+    def arguments(self) -> list[Binding]:
+        return ufunc.stub_arguments(self.g)
+
+    def type(self) -> str:
+        cpp_args = self.arguments()
+        return f"void(*)(TensorIteratorBase&, {', '.join(a.type for a in cpp_args)})"
+
+    def dispatch_decl(self) -> str:
+        return f"DECLARE_DISPATCH({self.type_name}, {self.name})"
+
+    def dispatch_defn(self) -> str:
+        return f"DEFINE_DISPATCH({self.name})"
+
+    def kernel_defn(self) -> str:
+        return f"void {self.kernel_name}(TensorIteratorBase& iter, {', '.join(a.defn() for a in self.arguments())})"
+
+    def type_defn(self) -> str:
+        return f"using {self.type_name} = {self.type()}"
+
+    # must be called from context where this is TensorIteratorBase*
+    def call(self, ctx: Sequence[Binding]) -> str:
+        return f"{self.name}(device_type(), *this, {', '.join(a.expr for a in translate(ctx, self.arguments()))})"
+
+    # used in CUDA to skip the unnecessary dynamic dispatch
+    def direct_call(self, ctx: Sequence[Binding]) -> str:
+        return f"{self.kernel_name}(*this, {', '.join(a.expr for a in translate(ctx, self.arguments()))})"
+
+
+@with_native_function
+def compute_ufunc_cpu(g: NativeFunctionsGroup) -> str:
+    stub_sig = StubSignature(g)
+    sig = StructuredImplSignature(g, ufunc.kernel_name(g, DispatchKey.CPU))
+
+    return f"""
+{stub_sig.type_defn()};
+{stub_sig.dispatch_decl()}
+{stub_sig.dispatch_defn()};
+
+{sig.defn()} {{
+  {stub_sig.call(sig.arguments())};
+}}
+"""
+
+
+def compute_ufunc_cpu_dtype_body(
+    g: NativeFunctionsGroup,
+    dtype: ScalarType,
+    inner_loops: dict[UfuncKey, UfuncSignature],
+    parent_ctx: Sequence[Binding],
+) -> str:
+    assert UfuncKey.CPUScalar in inner_loops, f"{dtype}, {inner_loops.keys()}"
+    assert inner_loops.keys() <= {UfuncKey.CPUScalar, UfuncKey.CPUVector}
+    scalar_loop = inner_loops[UfuncKey.CPUScalar]
+    vec_loop = None
+    if UfuncKey.CPUVector in inner_loops:
+        vec_loop = inner_loops[UfuncKey.CPUVector]
+
+    # NB: We DON'T use translate here, because translate is
+    # incapable of CSE'ing the scalar accesses in case it is also
+    # used by Vectorized; also, the unpacking here is very simple
+    # and only affects Scalar; everything else is implicitly captured
+    # by the lambda
+
+    # Setup scalar in scope
+    body = []
+    ctx = []
+    for b in parent_ctx:
+        if isinstance(b.argument, Argument) and b.argument.type != BaseType(
+            BaseTy.Scalar
+        ):
+            continue
+        body.append(f"auto _s_{b.name} = {b.name}.to();")
+        ctx.append(Expr(f"_s_{b.name}", NamedCType(b.nctype.name, BaseCType(scalar_t))))
+    if vec_loop is not None:
+        for b in parent_ctx:
+            if isinstance(b.argument, Argument) and b.argument.type != BaseType(
+                BaseTy.Scalar
+            ):
+                continue
+            body.append(
+                f"auto _v_{b.name} = at::vec::Vectorized(_s_{b.name});"
+            )
+            ctx.append(
+                Expr(
+                    f"_v_{b.name}",
+                    NamedCType(b.nctype.name, VectorizedCType(BaseCType(scalar_t))),
+                )
+            )
+
+    # Setup lambda signature
+    # NB: simplified version of ufunctor_arguments
+    scalar_bindings = []
+    vec_bindings = []
+    for a in g.functional.func.arguments.flat_non_out:
+        if not a.type.is_tensor_like():
+            continue
+        assert a.type == BaseType(BaseTy.Tensor)
+        scalar_bindings.append(
+            Binding(
+                name=a.name,
+                nctype=NamedCType(a.name, BaseCType(scalar_t)),
+                argument=a,
+            )
+        )
+        if vec_loop is not None:
+            vec_bindings.append(
+                Binding(
+                    name=a.name,
+                    nctype=NamedCType(a.name, VectorizedCType(BaseCType(scalar_t))),
+                    argument=a,
+                )
+            )
+
+    def with_ctx(b: Sequence[Binding]) -> list[Expr | Binding]:
+        r: list[Expr | Binding] = []
+        r.extend(ctx)
+        r.extend(b)
+        return r
+
+    body_str = "\n".join(body)
+    if vec_loop is not None:
+        return f"""
+{body_str}
+cpu_kernel_vec(iter,
+  [=]({", ".join(b.decl() for b in scalar_bindings)}) {{ return {scalar_loop.call(with_ctx(scalar_bindings))}; }},
+  [=]({", ".join(b.decl() for b in vec_bindings)}) {{ return {vec_loop.call(with_ctx(vec_bindings))}; }}
+);
+"""
+    else:
+        return f"""
+{body_str}
+cpu_kernel(iter,
+  [=]({", ".join(b.decl() for b in scalar_bindings)}) {{ return {scalar_loop.call(with_ctx(scalar_bindings))}; }}
+);
+"""
+
+
+@with_native_function
+def compute_ufunc_cpu_kernel(g: NativeFunctionsGroup) -> str:
+    stub_sig = StubSignature(g)
+
+    # Reindex the ufunc by dtypes; processing generic/scalaronly as well
+    loops = g.out.ufunc_inner_loop
+    ufunc_sigs: dict[ScalarType, dict[UfuncKey, UfuncSignature]] = {}
+    for k in [UfuncKey.CPUScalar, UfuncKey.CPUVector]:
+        lks = []
+        # ORDER MATTERS: this specifies overriding precedence
+        if k in loops:  # should happen rarely
+            lks.append(k)
+        if UfuncKey.ScalarOnly in loops and k is UfuncKey.CPUScalar:
+            lks.append(UfuncKey.ScalarOnly)
+        if UfuncKey.Generic in loops:
+            lks.append(UfuncKey.Generic)
+        # TODO: don't hardcode ufunc:: namespace here, should be centralized smh
+        for lk in lks:
+            for dtype in loops[lk].supported_dtypes:
+                compute_t: CType
+                if k is UfuncKey.CPUScalar:
+                    compute_t = BaseCType(scalar_t)
+                elif k is UfuncKey.CPUVector:
+                    compute_t = VectorizedCType(BaseCType(scalar_t))
+                else:
+                    raise AssertionError
+                inner_ufunc_sigs = ufunc_sigs.setdefault(dtype, {})
+                if k not in inner_ufunc_sigs:
+                    inner_ufunc_sigs[k] = UfuncSignature(
+                        g, name=f"ufunc::{loops[lk].name}", compute_t=compute_t
+                    )
+
+    # Build the conditionals
+    dtype_cases = []
+    for dtype, inner_ufunc_sigs in ufunc_sigs.items():
+        dtype_cases.append(
+            f"""
+AT_DISPATCH_CASE(at::ScalarType::{dtype},
+  [&]() {{
+    {compute_ufunc_cpu_dtype_body(g, dtype, inner_ufunc_sigs, stub_sig.arguments())}
+  }}
+)
+"""
+        )
+
+    dtype_cases_str = "\n".join(dtype_cases)
+    return f"""
+namespace {{
+
+{stub_sig.kernel_defn()} {{
+  AT_DISPATCH_SWITCH(iter.common_dtype(), "{stub_sig.name}",
+    {dtype_cases_str}
+  );
+}}
+
+}} // anonymous namespace
+
+{stub_sig.type_defn()};
+{stub_sig.dispatch_decl()}
+REGISTER_DISPATCH({stub_sig.name}, &{stub_sig.kernel_name})
+"""
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen.py
new file mode 100644
index 0000000000000000000000000000000000000000..7bbdd4a7a741f71c50b8e710519ef26e827e92e1
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen.py
@@ -0,0 +1,3033 @@
+from __future__ import annotations
+
+import argparse
+import functools
+import json
+import keyword
+import os
+from collections import defaultdict, namedtuple, OrderedDict
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Callable, Literal, TYPE_CHECKING, TypeVar
+from typing_extensions import assert_never
+
+import yaml
+
+import torchgen.api.dispatcher as dispatcher
+import torchgen.api.meta as meta
+import torchgen.api.native as native
+import torchgen.api.structured as structured
+import torchgen.dest as dest
+from torchgen.api import cpp
+from torchgen.api.translate import translate
+from torchgen.api.types import (
+    Binding,
+    CppSignature,
+    CppSignatureGroup,
+    DispatcherSignature,
+    NamedCType,
+    NativeSignature,
+    SpecialArgName,
+)
+from torchgen.context import (
+    method_with_native_function,
+    native_function_manager,
+    with_native_function,
+    with_native_function_and_indices,
+)
+from torchgen.gen_aoti_c_shim import (
+    gen_aoti_c_shim_files,
+    gen_static_dispatch_backend_call_signature,
+)
+from torchgen.gen_functionalization_type import (
+    gen_functionalization_definition,
+    gen_functionalization_registration,
+    gen_functionalization_view_inverse_declaration,
+    gen_functionalization_view_meta_classes_decl,
+    gen_functionalization_view_meta_classes_impl,
+    GenCompositeViewCopyKernel,
+)
+from torchgen.gen_vmap_plumbing import gen_all_vmap_plumbing
+from torchgen.model import (
+    Argument,
+    BackendIndex,
+    BackendMetadata,
+    BaseOperatorName,
+    DEFAULT_KERNEL_NAMESPACE,
+    dispatch_device_map,
+    DispatchKey,
+    FRAGMENT_NAMESPACES,
+    FunctionSchema,
+    is_cuda_dispatch_key,
+    is_generic_dispatch_key,
+    is_ufunc_dispatch_key,
+    is_xpu_dispatch_key,
+    Location,
+    NativeFunction,
+    NativeFunctionsGroup,
+    NativeFunctionsViewGroup,
+    OperatorName,
+    OptionalType,
+    SchemaKind,
+    SelfArgument,
+    STRUCTURED_DISPATCH_KEYS,
+    TensorOptionsArguments,
+    Type,
+    Variant,
+    ViewSchemaKind,
+)
+from torchgen.native_function_generation import (
+    add_generated_native_functions,
+    gen_composite_functional_kernel,
+    gen_composite_out_kernel,
+    pre_group_native_functions,
+)
+from torchgen.selective_build.selector import SelectiveBuilder
+from torchgen.utils import (
+    concatMap,
+    context,
+    FileManager,
+    make_file_manager,
+    mapMaybe,
+    NamespaceHelper,
+    Target,
+)
+from torchgen.yaml_utils import YamlDumper, YamlLoader
+
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+    from typing import Optional
+
+
+T = TypeVar("T")
+
+# Welcome to the ATen code generator v2!  The ATen code generator is
+# responsible for parsing native_functions.yaml and then generating
+# various generated files (e.g., TypeDefault.cpp) based on the operators
+# defined in this file.  This means that the code generator knows how to
+# parse function schema, and then translate this into various C++ types
+# and boilerplate code.
+#
+# Some things to know about this file when you modify it:
+#
+# - This file has STRICT mypy typechecking.  Typecheck it with
+#   `mypy --config mypy-strict.ini` in the root source directory
+#
+# - Most of the heavy lifting lives in external modules:
+#   - 'model' has the data model for native_functions.yaml.  The classes
+#     in those file represent what you see when you look at
+#     a native_functions.yaml
+#   - 'api' has conversions for how to translate JIT schema into
+#     the various C++ APIs that the codegen interacts with.  There
+#     are in fact THREE different C++ APIs: the public C++ API,
+#     the dispatcher API, and the legacy dispatcher API.  See each
+#     of these respective files for more information
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                         HELPER FUNCTIONS
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+# A custom loader for YAML to let us also keep track of line numbers
+# of each entry in the YAML file
+class LineLoader(YamlLoader):
+    def construct_mapping(self, node, deep=False):  # type: ignore[no-untyped-def]
+        mapping = super().construct_mapping(node, deep=deep)  # type: ignore[no-untyped-call]
+        # Add 1 so line numbering starts at 1
+        mapping["__line__"] = node.start_mark.line + 1
+        return mapping
+
+
+# Parse native_functions.yaml into a sequence of NativeFunctions and Backend Indices.
+ParsedYaml = namedtuple("ParsedYaml", ["native_functions", "backend_indices"])
+
+
+_GLOBAL_PARSE_NATIVE_YAML_CACHE: dict[str, ParsedYaml] = {}
+_GLOBAL_PARSE_TAGS_YAML_CACHE: dict[str, set[str]] = {}
+
+
+def file_manager_from_dispatch_key(
+    dispatch_key: DispatchKey,
+    device_fms: dict[str, FileManager],
+    default_fm: FileManager,
+) -> FileManager:
+    fm = device_fms.get(
+        next(
+            (
+                device
+                for check, device in dispatch_device_map.items()
+                if check(dispatch_key)
+            ),
+            "",
+        ),
+        default_fm,
+    )
+    return fm
+
+
+def parse_native_yaml_struct(
+    es: object,
+    valid_tags: set[str],
+    ignore_keys: set[DispatchKey] | None = None,
+    path: str = "",
+    skip_native_fns_gen: bool = False,
+) -> ParsedYaml:
+    assert isinstance(es, list)
+    rs: list[NativeFunction] = []
+    bs: dict[DispatchKey, dict[OperatorName, BackendMetadata]] = defaultdict(dict)
+    for e in es:
+        assert isinstance(e, dict), f"expected to be dict: {e}"
+        assert isinstance(e.get("__line__"), int), e
+        loc = Location(path, e["__line__"])
+        funcs = e.get("func")
+        assert funcs is not None, f"missed 'func' in {e}"
+        with context(lambda: f"in {loc}:\n  {funcs}"):
+            func, m = NativeFunction.from_yaml(e, loc, valid_tags, ignore_keys)
+            rs.append(func)
+            BackendIndex.grow_index(bs, m)
+    error_check_native_functions(rs)
+    # Default dict is to prevent the codegen from barfing when we have a dispatch key that has no kernels yet.
+    indices: dict[DispatchKey, BackendIndex] = defaultdict(
+        lambda: BackendIndex(
+            dispatch_key=DispatchKey.Undefined,
+            use_out_as_primary=True,
+            external=False,
+            device_guard=False,
+            # I'm actually not sure about this; undefined could be hit on
+            # empty TensorList, hypothetically that could have sizes in it
+            index={},
+        )
+    )
+    if not skip_native_fns_gen:
+        add_generated_native_functions(rs, bs)
+    for k, v in bs.items():
+        # All structured in-tree operators are implemented in terms of their out operator.
+        indices[k] = BackendIndex(
+            dispatch_key=k,
+            use_out_as_primary=True,
+            external=False,
+            # Only cuda-like devices in tree require device guards
+            device_guard=is_cuda_dispatch_key(k) or is_xpu_dispatch_key(k),
+            index=v,
+        )
+    return ParsedYaml(rs, indices)
+
+
+def parse_tags_yaml_struct(es: object, path: str = "") -> set[str]:
+    assert isinstance(es, list)
+    rs: set[str] = set()
+    for e in es:
+        assert isinstance(e.get("__line__"), int), e
+        loc = Location(path, e["__line__"])
+        tags = e.get("tag")
+        with context(lambda: f"in {loc}:\n  {tags}"):
+            e_i = e.copy()
+            name = e_i.pop("tag")
+            desc = e_i.pop("desc", "")
+            # ensure that each tag has a non-empty description
+            assert desc != ""
+            rs.add(name)
+    return rs
+
+
+@functools.cache
+def parse_tags_yaml(path: str) -> set[str]:
+    global _GLOBAL_PARSE_TAGS_YAML_CACHE
+    if path not in _GLOBAL_PARSE_TAGS_YAML_CACHE:
+        with open(path) as f:
+            es = yaml.load(f, Loader=LineLoader)
+            _GLOBAL_PARSE_TAGS_YAML_CACHE[path] = parse_tags_yaml_struct(es, path=path)
+
+    return _GLOBAL_PARSE_TAGS_YAML_CACHE[path]
+
+
+def parse_native_yaml(
+    path: str,
+    tags_yaml_path: str,
+    ignore_keys: set[DispatchKey] | None = None,
+    *,
+    skip_native_fns_gen: bool = False,
+    loaded_yaml: object | None = None,
+) -> ParsedYaml:
+    global _GLOBAL_PARSE_NATIVE_YAML_CACHE
+    if path not in _GLOBAL_PARSE_NATIVE_YAML_CACHE:
+        valid_tags = parse_tags_yaml(tags_yaml_path)
+
+        # if a loaded yaml is provided, use that instead of reading from path
+        if loaded_yaml is None:
+            with open(path) as f:
+                es = yaml.load(f, Loader=LineLoader)
+        else:
+            es = loaded_yaml
+
+        _GLOBAL_PARSE_NATIVE_YAML_CACHE[path] = parse_native_yaml_struct(
+            es,
+            valid_tags,
+            ignore_keys,
+            path=path,
+            skip_native_fns_gen=skip_native_fns_gen,
+        )
+
+    return _GLOBAL_PARSE_NATIVE_YAML_CACHE[path]
+
+
+# Some assertions are already performed during parsing, but those are only within a single NativeFunction.
+# Assertions here are meant to be performed across NativeFunctions.
+def error_check_native_functions(funcs: Sequence[NativeFunction]) -> None:
+    func_map: dict[OperatorName, NativeFunction] = {}
+    base_func_map: dict[BaseOperatorName, list[NativeFunction]] = defaultdict(list)
+    for f in funcs:
+        func_map[f.func.name] = f
+        base_func_map[f.func.name.name].append(f)
+    for f in funcs:
+        if f.structured_delegate is not None:
+            delegate_func = func_map.get(f.structured_delegate)
+            assert delegate_func is not None, (
+                f"{f.func.name} is marked as a structured_delegate pointing to "
+                f"{f.structured_delegate}, but {f.structured_delegate} is missing."
+            )
+            assert delegate_func.structured, (
+                f"{f.func.name} is marked as a structured_delegate pointing to "
+                f"{f.structured_delegate}, but {f.structured_delegate} is not marked as structured. "
+                f"Consider adding 'structured=True' to the delegated operator"
+            )
+
+        # Check for reserved Python keywords
+        PYTHON_RESERVED_KEYWORDS = set(keyword.kwlist)
+        # List of pre-existing operators that are known to have reserved keywords
+        # Exclusion list is used to suppress the assertion for these operators
+        EXCLUSION_LIST = {
+            ("_has_compatible_shallow_copy_type", "from"),
+            ("random_.from", "from"),
+            ("uniform_", "from"),
+        }
+
+        for arg in f.func.arguments.flat_all:
+            if arg.name in PYTHON_RESERVED_KEYWORDS:
+                if (str(f.func.name), arg.name) not in EXCLUSION_LIST:
+                    raise AssertionError(
+                        f"Argument name '{arg.name}' in function '{f.func.name}' is a reserved Python keyword."
+                    )
+        # See Note [resize_ in Functionalization]
+        # resize_() is technically an inplace view op (and therefore needs the tag),
+        # but it would be overkill to add a true "view" variant of resize.
+        # Instead, resize_() gets special treatment in functionalization,
+        # and we have a resize() op that is non-aliasing + functional.
+        if (
+            "inplace_view" in f.tags
+            and str(f.func.name) != "resize_"
+            and str(f.func.name) != "resize_as_"
+            and str(f.func.name.name) != "set_"
+        ):
+            base_name = f.func.name.name
+            assert base_name.inplace, (
+                f"{f.func.name} is marked with tag: inplace_view, but it doesn't follow the naming "
+                "convention for inplace ops - the codegen expects the base name to have a trailing underscore. "
+            )
+            out_of_place_base_name = BaseOperatorName(
+                base_name.base, False, base_name.dunder_method
+            )
+            assert len(base_func_map[out_of_place_base_name]) > 0, (
+                f"{f.func.name} is marked with tag: inplace_view. The codegen expects there to be a corresponding "
+                f"out-of-place view op with the name '{base_name}' and matching schema, but it didn't find one. "
+            )
+
+
+def cpp_string(s: str) -> str:
+    """Convert a python string into a c++ string literal"""
+    s = s.replace("\\", "\\\\")
+    s = s.replace('"', '\\"')
+    s = s.replace("\a", "\\a")
+    s = s.replace("\b", "\\b")
+    s = s.replace("\f", "\\f")
+    s = s.replace("\n", "\\n")
+    s = s.replace("\v", "\\v")
+    s = s.replace("\t", "\\t")
+    return f'"{s}"'
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                        C++ CODE GENERATION
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+# Most functions in this section are curried: they consist of a function
+# that takes some parameters (e.g., what is to be generated) which itself
+# returns a function that actually maps NativeFunction to the code
+# to be generated.  This pattern makes it convenient to use map, concatMap
+# and similar functional combinators.
+
+
+def static_dispatch_keys(backends: list[BackendIndex]) -> list[DispatchKey]:
+    if len(backends) == 0:
+        return []
+    else:
+        return [backend.dispatch_key for backend in backends] + [
+            DispatchKey.CompositeImplicitAutograd,
+            DispatchKey.CompositeImplicitAutogradNestedTensor,
+            DispatchKey.CompositeExplicitAutograd,
+            DispatchKey.CompositeExplicitAutogradNonFunctional,
+        ]
+
+
+def get_static_dispatch_backend(
+    f: NativeFunction, backend_index: BackendIndex
+) -> DispatchKey | None:
+    if f.structured_delegate is not None or backend_index.has_kernel(f):
+        # TODO: for ops with structured_delegate it should check the dispatch table of
+        # the out variant instead. For now, these structured ops all have CPU/CUDA kernels
+        # so we always dispatch to the `backend`, but this could be wrong when we
+        # migrate math/default_backend ops to use structured delegate.
+        return backend_index.dispatch_key
+    elif f.has_composite_explicit_autograd_kernel:
+        return DispatchKey.CompositeExplicitAutograd
+    elif f.has_composite_explicit_autograd_non_functional_kernel:
+        return DispatchKey.CompositeExplicitAutogradNonFunctional
+    elif f.has_composite_implicit_autograd_kernel:
+        return DispatchKey.CompositeImplicitAutograd
+    elif f.has_composite_implicit_autograd_nested_tensor_kernel:
+        return DispatchKey.CompositeImplicitAutogradNestedTensor
+    return None
+
+
+def static_dispatch_ops_header(
+    f: NativeFunction, backend_index: list[BackendIndex]
+) -> str | None:
+    if backend_index is None or f.manual_kernel_registration:
+        return None
+
+    output = []
+    for index in backend_index:
+        dispatch_key = get_static_dispatch_backend(f, index)
+        if dispatch_key is not None:
+            output.append(
+                f"#include "
+            )
+    return "\n".join(output)
+
+
+def static_dispatch_extra_headers(backends: list[BackendIndex]) -> list[str]:
+    return [
+        f"#include "
+        for dispatch_key in static_dispatch_keys(backends)
+    ]
+
+
+# Translates arguments of `sig` to CppSignature bindings.
+# Note that we have a special case for `memory_format` argument and this case is not covered by
+# tools.codegen.api.translate() yet as its application is limited to static dispatch.
+def translate_args(
+    sig: CppSignature | DispatcherSignature,
+    cpp_sig: CppSignature,
+) -> str:
+    # Adds SpecialArgName.possibly_redundant_memory_format NamedCType for memory_format bindings
+    def add_spl_memory_format_binding(input_bindings: list[Binding]) -> list[Binding]:
+        output_bindings: list[Binding] = []
+        for binding in input_bindings:
+            if binding.name == "memory_format":
+                spl_mem_format_binding = Binding(
+                    nctype=NamedCType(
+                        SpecialArgName.possibly_redundant_memory_format,
+                        binding.nctype.type,
+                    ),
+                    name=binding.name,
+                    default=binding.default,
+                    argument=binding.argument,
+                )
+                output_bindings.append(spl_mem_format_binding)
+            else:
+                output_bindings.append(binding)
+        return output_bindings
+
+    src_bindings = list(sig.arguments())
+    goal_bindings = list(cpp_sig.arguments())
+    # When last argument of CPP signature has SpecialArgName.possibly_redundant_memory_format NCType,
+    # get memory_format bindings of dispatcher signature to have the same NCType as well
+    for arg in goal_bindings:
+        if arg.nctype.name == SpecialArgName.possibly_redundant_memory_format:
+            src_bindings = add_spl_memory_format_binding(src_bindings)
+            break
+    exprs = translate(src_bindings, goal_bindings)
+    return ", ".join(a.expr for a in exprs)
+
+
+def generate_static_dispatch_backend_call(
+    sig: CppSignature | DispatcherSignature,
+    f: NativeFunction,
+    backend_index: BackendIndex,
+) -> str:
+    cpp_sig = gen_static_dispatch_backend_call_signature(sig, f)
+    name = cpp_sig.name()
+    exprs = translate_args(sig, cpp_sig)
+    backend_metadata = backend_index.get_kernel(f)
+    kernel_ns = (
+        backend_metadata.cpp_namespace
+        if backend_metadata and backend_metadata.cpp_namespace
+        else DEFAULT_KERNEL_NAMESPACE
+    )
+    ns = kernel_ns.replace("::native", "")
+    return f"return {ns}::{backend_index.dispatch_key.lower()}::{name}({exprs});"
+
+
+def generate_static_dispatch_fallback_call(
+    sig: CppSignature | DispatcherSignature,
+    f: NativeFunction,
+    backend_indices: list[BackendIndex],
+) -> str:
+    cpp_sigs = CppSignatureGroup.from_native_function(
+        f, method=False, fallback_binding=False
+    )
+    if sig.symint and f.func.has_symint():
+        cpp_sig = cpp_sigs.symint_signature
+    else:
+        cpp_sig = cpp_sigs.signature
+    assert cpp_sig is not None
+    name = cpp_sig.name()
+    exprs = translate_args(sig, cpp_sig)
+    ns = DEFAULT_KERNEL_NAMESPACE.replace("::native", "")
+    if f.has_composite_explicit_autograd_kernel:
+        return f"return {ns}::{DispatchKey.CompositeExplicitAutograd.lower()}::{name}({exprs});"
+    elif f.has_composite_explicit_autograd_non_functional_kernel:
+        return f"return {ns}::{DispatchKey.CompositeExplicitAutogradNonFunctional.lower()}::{name}({exprs});"
+    elif f.has_composite_implicit_autograd_kernel:
+        return f"return {ns}::{DispatchKey.CompositeImplicitAutograd.lower()}::{name}({exprs});"
+    elif f.has_composite_implicit_autograd_nested_tensor_kernel:
+        return f"return {ns}::{DispatchKey.CompositeImplicitAutogradNestedTensor.lower()}::{name}({exprs});"
+    else:
+        return f"""TORCH_CHECK(false, "Static dispatch does not support {name} for\
+{", ".join([str(index.dispatch_key) for index in backend_indices])} ");"""
+
+
+def static_dispatch(
+    sig: CppSignature | DispatcherSignature,
+    f: NativeFunction,
+    backend_indices: list[BackendIndex],
+) -> str:
+    """
+    For a given `NativeFunction`, find out the corresponding backend and dispatch to it. If more than one
+    backends exist, fallback to static dispatch by determining dispatch key from inputs.
+    Arguments:
+        sig: A CppSignature or DispatcherSignature for this native function we want to use.
+        f: NativeFunction to generate static dispatch.
+        backend_indices: All available backends.
+    Return:
+        C++ code to call backend-specific functions, e.g., "return at::cpu::add(self, other, scale);"
+    """
+    if len(backend_indices) == 0 or f.manual_kernel_registration:
+        return ""
+
+    keys = [
+        b
+        for b in backend_indices
+        if b.has_kernel(f)
+        or (
+            f.structured_delegate is not None
+            and b.dispatch_key in STRUCTURED_DISPATCH_KEYS
+        )
+    ]
+    if len(keys) == 1:
+        return generate_static_dispatch_backend_call(sig, f, keys[0])
+    elif len(keys) == 0:
+        return generate_static_dispatch_fallback_call(sig, f, backend_indices)
+
+    native_tensor_args = [
+        a.name
+        for a in sig.arguments()
+        if isinstance(a.argument, SelfArgument)
+        or isinstance(a.argument, Argument)
+        and a.argument.type.is_tensor_like()
+    ]
+    tensor_args = ", ".join(native_tensor_args)
+    tensor_opts = f.func.arguments.tensor_options
+
+    stmts = []
+    subexprs: list[str] = []
+    if tensor_opts is not None:
+        subexprs.append(
+            "DispatchKeySet(c10::computeDispatchKey(dtype, layout, device))"
+        )
+    if tensor_args != "":
+        subexprs.append(f"c10::detail::multi_dispatch_key_set({tensor_args})")
+    stmts.append(f"""DispatchKeySet _dk_set = {" | ".join(subexprs)};""")
+    stmts.append("DispatchKey _dk = c10::highestPriorityBackendTypeId(_dk_set);")
+
+    dispatch_code = []
+    for index in keys:
+        dispatch_code.append(f"""case DispatchKey::{index.dispatch_key}:""")
+        dispatch_code.append(
+            f"""\t{generate_static_dispatch_backend_call(sig, f, index)};"""
+        )
+
+    fallback = generate_static_dispatch_fallback_call(sig, f, backend_indices)
+    connector = "\n\t\t"
+
+    return f"""
+    {connector.join(stmts)}
+    switch (_dk) {{
+        {connector.join(dispatch_code)}
+        default:
+            {fallback}
+    }}
+    """
+
+
+# Generates RegisterSchema.cpp.  Depending on the selector, either
+# all schemas are registered, or only some are (in the case of
+# selective build)
+@dataclass(frozen=True)
+class RegisterSchema:
+    selector: SelectiveBuilder
+    known_tags: dict[str, int] = field(default_factory=dict)
+
+    @method_with_native_function
+    def __call__(self, f: NativeFunction) -> str | None:
+        if not self.selector.is_native_function_selected(f):
+            return None
+        tags = "{" + ", ".join(f"at::Tag::{tag}" for tag in sorted(f.tags)) + "}"
+        if tags == "{}":
+            return f"m.def({cpp_string(str(f.func))}, {{}});\n"
+        maybe_tags = ""
+        if tags not in self.known_tags:
+            idx = len(self.known_tags)
+            self.known_tags[tags] = idx
+            maybe_tags = f"const std::vector tags_{idx} = {tags};\n"
+        return f"{maybe_tags}m.def({cpp_string(str(f.func))}, tags_{self.known_tags[tags]});\n"
+
+
+# Generates Operators.h and Operators.cpp.
+# These provide macros that, given an operator and overload name, allow users
+# to access an "un-overloaded" function version of the operator. This
+# is useful for extension writers who want to (1) want to decltype the operator
+# and (2) don't want to worry about method-only operators.
+@dataclass(frozen=True)
+class ComputeOperators:
+    target: Literal[Target.DECLARATION, Target.DEFINITION]
+    static_dispatch_backend_indices: list[BackendIndex]
+
+    @method_with_native_function
+    def __call__(self, f: NativeFunction) -> str:
+        sig = DispatcherSignature.from_schema(f.func)
+        name = f.func.name.unambiguous_name()
+
+        if self.target is Target.DECLARATION:
+            # Note [The ATen Operators API]
+            # The ATen Operators API lives in the at::_ops namespace, and contains compile-time
+            # metadata about each operator + entry points into the Dispatcher.
+            # The C++ function, method, and redispatch API's are all implemented as wrappers
+            # into various bits of the structs defined here.
+            #
+            # Important characteristics about the Operators API:
+            # (1) It follows the Dispatcher API.
+            #     This is kind of necessary to avoid overhead.
+            #     For example: if it followed the C++ API, then all of the faithful C++ factory functions
+            #     would need to wrap their arguments into TensorOptions only to unwrap them again.
+            # (2) Overload names are disambiguated.
+            #     This is helpful for pytorch extenders who would like to decltype() an aten operator,
+            #     that has overloads, e.g. decltype(at::_ops::mul_Tensor::call)
+            # (3) No argument defaulting is allowed.
+            #     This is more of an implementation detail to avoid #include cycles,
+            #     since TensorBody.h (which defines the Tensor class) needs to include this file.
+            # (4) manual_cpp_bindings and faithful names are not included in the API.
+            #     This applies to stuff like __dispatch__is_complex(), and add_outf().
+            #     These aren't "real aten ops", they're just additional functions provided by the C++ API.
+            #     They're implemented as wrappers in Functions.h that call into the actual operators
+            #     defined here, i.e. at::_ops::is_complex::call() and at::_ops::add_out::call().
+            #     This means that ATEN_OP(is_complex) will not fastpath, and will go through the dispatcher.
+            return f"""
+struct TORCH_API {name} {{
+  using schema = {sig.type()};
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  static constexpr const char* name = "aten::{f.func.name.name}";
+  static constexpr const char* overload_name = "{f.func.name.overload_name}";
+  static constexpr const char* schema_str = {cpp_string(str(f.func))};
+  static {sig.defn(name="call", is_redispatching_fn=False)};
+  static {sig.defn(name="redispatch", is_redispatching_fn=True)};
+}};"""
+
+        elif self.target is Target.DEFINITION:
+            defns = f"""
+// aten::{f.func}
+static C10_NOINLINE c10::TypedOperatorHandle<{name}::schema> create_{name}_typed_handle() {{
+  return c10::Dispatcher::singleton()
+      .findSchemaOrThrow({name}::name, {name}::overload_name)
+      .typed<{name}::schema>();
+}}
+"""
+            for is_redispatching_fn in [False, True]:
+                if is_redispatching_fn:
+                    dispatcher_exprs_str = ", ".join(
+                        ["dispatchKeySet"] + [a.name for a in sig.arguments()]
+                    )
+                    method_base = "redispatch"
+                else:
+                    dispatcher_exprs_str = ", ".join([a.name for a in sig.arguments()])
+                    method_base = "call"
+
+                dispatcher_call = method_base
+                method_name = f"{name}::{method_base}"
+
+                fn_body = f"""
+    static auto op = create_{name}_typed_handle();
+    return op.{dispatcher_call}({dispatcher_exprs_str});"""
+
+                if (
+                    not is_redispatching_fn
+                    and len(self.static_dispatch_backend_indices) > 0
+                ):
+                    # call() should go through static dispatch
+                    fn_body = static_dispatch(
+                        sig, f, backend_indices=self.static_dispatch_backend_indices
+                    )
+                defns += f"""
+// aten::{f.func}
+{sig.defn(name=method_name, is_redispatching_fn=is_redispatching_fn)} {{
+    {fn_body}
+}}
+"""
+            return defns
+        else:
+            assert_never(self.target)
+
+
+# Generates Functions.h, which provides the functional public C++ API,
+# and the scaffolding to call into the dispatcher from these functions.
+@dataclass(frozen=True)
+class ComputeFunction:
+    @method_with_native_function
+    def __call__(self, f: NativeFunction) -> str | None:
+        sig_group = CppSignatureGroup.from_native_function(
+            f, method=False, fallback_binding=f.manual_cpp_binding
+        )
+        has_symint = f.func.has_symint()
+
+        result = ""
+        for sig in sig_group.signatures():
+            # See Note [The ATen Operators API]
+            target_sig = DispatcherSignature.from_schema(f.func)
+            exprs = translate(sig.arguments(), target_sig.arguments())
+            exprs_str = ", ".join([e.expr for e in exprs])
+
+            if sig.symint:
+                intlike_t = "c10::SymInt"
+            else:
+                intlike_t = "int64_t"
+
+            if Variant.function in f.variants:
+                result += f"""
+// aten::{f.func}
+inline {sig.decl()} {{
+    return at::_ops::{f.func.name.unambiguous_name()}::call({exprs_str});
+}}"""
+
+            # The template function can be used from template situations
+            # where you want to switch between the symint or not version
+            # depending on a template argument
+            #
+            # NB: we ALWAYS generate this even for methods.  But we put it in
+            # this header so it can take advantage of per-op headers
+            if has_symint:
+                result += f"""
+namespace symint {{
+  template >>
+  {sig.decl(suppress_symint_suffix=True)} {{
+    return at::_ops::{f.func.name.unambiguous_name()}::call({exprs_str});
+  }}
+}}
+"""
+        return result
+
+
+# Generates TensorBody.h. This file provides the object-oriented (method-based)
+# public C++ API, and the scaffolding to call into the dispatcher from these functions.
+@dataclass(frozen=True)
+class ComputeTensorMethod:
+    target: Literal[Target.DECLARATION, Target.DEFINITION]
+    static_dispatch_backend_indices: list[BackendIndex]
+
+    @method_with_native_function
+    def __call__(self, f: NativeFunction) -> str | None:
+        if Variant.method not in f.variants:
+            return None
+
+        assert not f.func.is_out_fn()
+        assert f.func.arguments.self_arg is not None
+
+        sig_group = CppSignatureGroup.from_native_function(
+            f, method=True, fallback_binding=f.manual_cpp_binding
+        )
+
+        if self.target is Target.DECLARATION:
+            result = ""
+            for sig in sig_group.signatures():
+                result += f"{sig.decl()} const;\n"
+            return result
+
+        if self.target is not Target.DEFINITION:
+            assert_never(self.target)
+
+        result = ""
+
+        for sig in sig_group.signatures():
+            target_sig = DispatcherSignature.from_schema(f.func)
+            exprs = translate(sig.arguments(), target_sig.arguments(), method=True)
+            exprs_str = ", ".join([e.expr for e in exprs])
+
+            result += f"""
+// aten::{f.func}
+inline {sig.defn(prefix="Tensor::")} const {{
+    return at::_ops::{f.func.name.unambiguous_name()}::call({exprs_str});
+}}
+"""
+
+        return result
+
+
+# Generates RedispatchFunctions.h.
+# This is similar to the C++ API defined in Functions.h, but provides access
+# to the dispatcher's redispatch API.
+@dataclass(frozen=True)
+class ComputeRedispatchFunction:
+    @method_with_native_function
+    def __call__(self, f: NativeFunction) -> str | None:
+        # We unconditionally generate function variants of the redispatch API.
+        # This is mainly because we can namespace functions separately, but not methods,
+        sig_group = CppSignatureGroup.from_native_function(
+            f, method=False, fallback_binding=f.manual_cpp_binding
+        )
+
+        result = ""
+        for sig in sig_group.signatures():
+            target_sig = DispatcherSignature.from_schema(f.func)
+            exprs = translate(sig.arguments(), target_sig.arguments())
+            exprs_str = ", ".join(["dispatchKeySet"] + [a.expr for a in exprs])
+
+            result += f"""
+// aten::{f.func}
+inline {sig.decl(is_redispatching_fn=True)} {{
+    return at::_ops::{f.func.name.unambiguous_name()}::redispatch({exprs_str});
+}}
+"""
+
+        return result
+
+
+# Generates ATenOpList.cpp, a runtime accessible list of all aten
+# operators.
+# TODO: This was historically used to help some JIT interop code
+# figure out whether or not to treat aten namespace'd operators
+# one way or another, we should reevaluate if this is actually needed.
+@with_native_function
+def compute_aten_op(f: NativeFunction) -> str:
+    return f'{{"aten::{f.func.name.name}", "{f.func.name.overload_name}"}},'
+
+
+# Generates MetaFunctions.h
+def compute_meta_function_declaration(g: NativeFunctionsGroup) -> str | None:
+    if not g.structured:
+        return None
+    with native_function_manager(g.out):
+        name = meta.name(g)
+        args = structured.meta_arguments(g)
+        args_str = ", ".join(a.decl() for a in args)
+        parent_class = g.out.structured_inherits
+        if parent_class is None:
+            parent_class = "at::impl::MetaBase"
+        meta_return = "void"
+        precomputed = g.out.precomputed if g.structured else None
+
+        if precomputed:
+            # Generate the template declaration with one bool parameter for each
+            # precomputed element. Each parameter is true if the corresponding (in
+            # terms of position) precomputed element has been set.
+            precomputed_values = [*precomputed.replace.values(), precomputed.add]
+            precomputed_elements = [
+                elem for replace_list in precomputed_values for elem in replace_list
+            ]
+            precomputed_template_parameters = [
+                elem.name.upper() for elem in precomputed_elements
+            ]
+            precomputed_template_params_str = ", ".join(
+                f"bool {param} = false" for param in precomputed_template_parameters
+            )
+            precompute_template_decl = f"template <{precomputed_template_params_str}>"
+
+            # Generate a string containing declarations of all precomputed elements.
+            precomputed_elements_with_cpp_types = [
+                structured.argument_type(elem, binds=elem.name)
+                for elem in precomputed_elements
+            ]
+
+            precomputed_elements_decl = ";\n".join(
+                f"{elem.cpp_type(strip_ref=True)} {elem.name}"
+                for elem in precomputed_elements_with_cpp_types
+            )
+
+            # Generate "setter" methods for each precomputed element. Each method will return
+            # a new instance of precompute_out with the template parameter that corresponds to
+            # the member set by the method to true (to indicate that it has been set).
+            setter_methods = []
+            for i, elem in enumerate(precomputed_elements):
+                # Generate the signature. The return type will be the same
+                # as the type of `this` but with the template parameter
+                # corresponding to the element set by this method set to true.
+                # The assert generated below will ensure that this template
+                # parameter is false on the type of `this`.
+                return_ty_templates = ", ".join(
+                    precomputed_template_parameters[:i]
+                    + ["true"]
+                    + precomputed_template_parameters[i + 1 :]
+                )
+                return_ty = f"precompute_out<{return_ty_templates}>"
+                elem_cpp_ty = precomputed_elements_with_cpp_types[i].cpp_type(
+                    strip_ref=True
+                )
+                signature = f"{return_ty} set_{elem.name}({elem_cpp_ty} value)"
+
+                # Generate an assert which checks that the
+                # template parameter corresponding to the precomputed
+                # element that is set by this method is false on the
+                # class corresponding to the object that `this` points to.
+                # This ensures that each element can be set only once.
+                assert_msg = f'"{elem.name} already set"'
+                assert_stmt = f"static_assert({precomputed_template_parameters[i]} == false, {assert_msg});"
+
+                # Generate the new object construction block. All state
+                # except the element that this method sets is copied from the
+                # object that `this` points to. The value for the element that
+                # the method sets is taken from a method parameter.
+                construction_stmts = []
+                construction_stmts.append(f"{return_ty} ret;")
+
+                for j, elem in enumerate(precomputed_elements):
+                    if i == j:
+                        construction_stmts.append(f"ret.{elem.name} = value;")
+                    else:
+                        construction_stmts.append(
+                            f"ret.{elem.name} = this->{elem.name};"
+                        )
+
+                construction_stmts.append("return ret;")
+                construction_block = "\n".join(construction_stmts)
+
+                setter_methods.append(
+                    f"""
+                    {signature} {{
+                        {assert_stmt}
+                        {construction_block}
+                    }}
+                """
+                )
+            setter_methods_decl = "\n".join(setter_methods)
+
+            # Meta should return an instance of the struct containing the precomputed elements.
+            meta_return_template_params = ", ".join(
+                ["true"] * len(precomputed_template_parameters)
+            )
+            # This typedef (actually a using statement) is needed so that TORCH_META_FUNC can reuse the return
+            # type (which has a variable number of template parameters).
+            meta_return_typedef = f"using meta_return_ty = precompute_out <{meta_return_template_params}>;"
+            meta_return = "meta_return_ty"
+            precomputed_decl = f"""
+                {precompute_template_decl}
+                struct TORCH_API precompute_out {{
+                    {setter_methods_decl}
+                    {precomputed_elements_decl};
+            }};"""
+        else:
+            meta_return_typedef = ""
+            precomputed_decl = ""
+
+        return f"""\
+struct TORCH_API structured_{name} : public {parent_class} {{
+    {precomputed_decl}
+    {meta_return_typedef}
+    {meta_return} meta({args_str});
+}};
+"""
+
+
+def needs_backend_select(f: NativeFunction, selector: SelectiveBuilder) -> bool:
+    name = str(f.func.name.name)
+    if name.endswith("_like") or name.startswith("new_"):
+        return False
+    if f.func.arguments.tensor_options is None:
+        return False
+    return selector.is_native_function_selected(f)
+
+
+# Generates RegisterBackendSelect.cpp, a series of kernels which provide
+# specialized computation of dispatch key for operator signatures which cannot
+# be easily done automatically using templating.
+@dataclass(frozen=True)
+class ComputeBackendSelect:
+    target: Literal[Target.DEFINITION, Target.REGISTRATION]
+
+    # Selector object to determine which operators to generate
+    # registration code for.
+    selector: SelectiveBuilder
+
+    @method_with_native_function
+    def __call__(self, f: NativeFunction) -> str | None:
+        if not needs_backend_select(f, self.selector):
+            return None
+
+        name = native.name(f.func)
+        # BackendSelect can go to Meta, so it must preserve symints
+        native_sig = NativeSignature(f.func, symint=True)
+
+        native_tensor_args = [
+            a
+            for a in native_sig.arguments()
+            if isinstance(a.argument, Argument) and a.argument.type.is_tensor_like()
+        ]
+
+        dispatcher_sig = DispatcherSignature.from_schema(f.func)
+
+        sig: NativeSignature | DispatcherSignature
+        sig = dispatcher_sig
+        dispatcher_exprs = dispatcher_sig.exprs()
+        dispatch_key = "c10::computeDispatchKey(dtype, layout, device)"
+
+        if self.target is Target.DEFINITION:
+            # I don't think there's actually a good reason to generate
+            # these two cases differently
+            # The first case could probably be improved though- it calls computeDispatchKeySet(),
+            # which looks at TLS dispatch keys- there should not be any by the time we reach backend select.
+            if native_tensor_args:
+                assert f.func.arguments.has_tensor_arg()
+                tensor_args = ", ".join(a.name for a in native_tensor_args)
+                compute_dk = f"""\
+DispatchKeySet _dk_set = c10::DispatchKeySet({dispatch_key}) | c10::detail::multi_dispatch_key_set({tensor_args});
+DispatchKeySet _dk_mask = c10::DispatchKeySet(DispatchKeySet::FULL_AFTER, DispatchKey::BackendSelect);
+DispatchKeySet _dk = c10::impl::computeDispatchKeySet(_dk_set, _dk_mask);"""
+            else:
+                assert not f.func.arguments.has_tensor_arg()
+                compute_dk = (
+                    f"DispatchKeySet _dk = c10::DispatchKeySet({dispatch_key});"
+                )
+            return f"""\
+// aten::{f.func}
+C10_ALWAYS_INLINE
+{sig.defn(name)} {{
+  {compute_dk}
+  return at::_ops::{f.func.name.unambiguous_name()}::redispatch(
+      _dk, {", ".join(a.expr for a in dispatcher_exprs)});
+}}
+"""
+        elif self.target is Target.REGISTRATION:
+            return f"""m.impl("aten::{f.func.name}", TORCH_FN({name}));"""
+        else:
+            assert_never(self.target)
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                       YAML CODE GENERATION
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+def format_yaml(data: object) -> str:
+    # Ignore alias in Dumper
+    YamlDumper.ignore_aliases = lambda self, data: True  # type: ignore[assignment]
+
+    # Support serializing OrderedDict
+    def dict_representer(dumper: Any, data: Any) -> Any:
+        return dumper.represent_dict(data.items())
+
+    YamlDumper.add_representer(OrderedDict, dict_representer)  # type: ignore[no-untyped-call]
+    # Some yaml parsers (e.g. Haskell's) don't understand line breaks.
+    # width=1e9 turns off optional line breaks and improves
+    # the portability of the outputted yaml.
+    return yaml.dump(data, default_flow_style=False, Dumper=YamlDumper, width=1e9)  # type: ignore[no-any-return, call-overload]
+
+
+# For some reason, some defaults we write to YAML are written as native
+# YAML objects, rather than doing them uniformly as strings.  This
+# function detects those cases and converts them into native Python
+# objects.
+def pythonify_default(s: str) -> object:
+    if s == "true":
+        return True
+    elif s == "false":
+        return False
+
+    try:
+        return int(s)
+    except ValueError:
+        try:
+            return float(s)
+        except ValueError:
+            return s
+
+
+# What is a dynamic type?  Over time, the semantic meaning of
+# dynamic type has degraded to meaninglessness (in the old days,
+# it captured dtype-ness of types, but that has gone away with
+# the removal of TH).  These days, it's mostly the same thing as
+# the C++ API argument type, except that Tensor and Tensor?
+# arguments simply present as Tensor.
+#
+# TODO: Get rid of dynamic_type, after getting tools/autograd
+# to use the new codegen framework
+def dynamic_type(t: Type) -> str:
+    if isinstance(t, OptionalType):
+        return dynamic_type(t.elem)
+    # Note we don't use t.is_tensor_like() here because it would
+    # also include Tensor[]
+    if str(t) == "Tensor":
+        return "at::Tensor"
+    # This is a legacy concept, so never report SymInt
+    return cpp.argumenttype_type(
+        t, mutable=False, binds="__placeholder__", symint=False
+    ).cpp_type()
+
+
+def compute_method_of_yaml(variants: set[Variant]) -> list[str]:
+    # This is written out explicitly to ensure that Tensor and
+    # namespace are put into the list in the right order
+    method_of = ["Type"]
+    if Variant.method in variants:
+        method_of.append("Tensor")
+    if Variant.function in variants:
+        method_of.append("namespace")
+    return method_of
+
+
+def compute_returns_yaml(
+    f: NativeFunction,
+) -> tuple[list[dict[str, str]], dict[str, str]]:
+    # Note [name and field_name]
+    # ~~~~~~~~~~~~~~~~~~~~~~~~~~
+    # To understand name_to_field_name, we must first talk about this
+    # schema:
+    #
+    #   lstsq.X(Tensor self, Tensor A, *, Tensor(a!) X, Tensor(b!) qr) -> (Tensor(a!) solution, Tensor(b!) QR)
+    #
+    # There is something very odd about this schema: it is an out
+    # variant of the function (that is to say, it will convert into
+    # at::lstsq_out() in the C++ API), but the names of the output
+    # return arguments don't match the keyword argument names of
+    # the inputs.  It TURNS OUT that in this situation, the historical
+    # Declarations.yaml we want to output is this (abbreviated to
+    # only show relevant fields):
+    #
+    #   arguments:
+    #     ...
+    #   - field_name: solution
+    #     name: X
+    #   - field_name: QR
+    #     name: qr
+    #     ...
+    #
+    #   returns:
+    #   - field_name: solution
+    #     name: X
+    #   - field_name: QR
+    #     name: qr
+    #
+    # The name of the return fields is stored in 'field_name', and the
+    # name of the arguments is stored in 'name'.  So when we process
+    # arguments, we need a way to get at the corresponding return.  At
+    # the moment, this is most conveniently done by constructing a
+    # mapping from name (the argument concept) to field_name (the
+    # return concept) while processing return arguments, since we don't
+    # directly maintain this correspondence in the modeling of function
+    # schema itself.
+    #
+    # See also https://github.com/pytorch/pytorch/issues/43114
+    name_to_field_name: dict[str, str] = {}
+
+    # Compute the returns field of the YAML entry
+    names = cpp.return_names(f)
+    returns = []
+    for i, (r, name) in enumerate(zip(f.func.returns, names)):
+        ret = {
+            "dynamic_type": dynamic_type(r.type),
+            "name": name,
+            # legacy, report ints
+            "type": cpp.return_type(r, symint=False).cpp_type(),
+        }
+
+        if r.name:
+            # See Note [name and field_name]
+            ret["field_name"] = r.name
+            if f.func.is_out_fn():
+                name_to_field_name[f.func.arguments.out[i].name] = r.name
+
+        returns.append(ret)
+
+    return returns, name_to_field_name
+
+
+# arguments in yaml roughly corresponds to the public C++ API
+def compute_cpp_argument_yaml(
+    cpp_a: Binding,
+    *,
+    schema_order: bool,
+    kwarg_only_set: set[str],
+    out_arg_set: set[str],
+    name_to_field_name: dict[str, str],
+) -> object:
+    if isinstance(cpp_a.argument, TensorOptionsArguments):
+        arg: dict[str, object] = {
+            "annotation": None,
+            "dynamic_type": "at::TensorOptions",
+            "is_nullable": False,
+            "name": cpp_a.name,
+            "type": cpp_a.type,
+            "kwarg_only": True,
+        }
+        if cpp_a.default is not None:
+            arg["default"] = cpp_a.default
+        return arg
+    elif isinstance(cpp_a.argument, SelfArgument):
+        raise AssertionError
+    elif isinstance(cpp_a.argument, Argument):
+        return compute_argument_yaml(
+            cpp_a.argument,
+            schema_order=schema_order,
+            kwarg_only_set=kwarg_only_set,
+            out_arg_set=out_arg_set,
+            name_to_field_name=name_to_field_name,
+        )
+
+
+def compute_argument_yaml(
+    a: Argument,
+    *,
+    schema_order: bool,
+    kwarg_only_set: set[str],
+    out_arg_set: set[str],
+    name_to_field_name: dict[str, str],
+) -> object:
+    arg: dict[str, object] = {
+        "annotation": str(a.annotation) if a.annotation else None,
+        "dynamic_type": dynamic_type(a.type),
+        "is_nullable": a.type.is_nullable(),
+        "name": a.name,
+        # legacy, report ints
+        "type": cpp.argument_type(a, binds="__placeholder__", symint=False).cpp_type(),
+    }
+    if a.default is not None:
+        arg["default"] = pythonify_default(
+            cpp.default_expr(a.default, a.type, symint=False)
+        )
+    if a.name in kwarg_only_set:
+        arg["kwarg_only"] = True
+    if a.name in out_arg_set:
+        arg["output"] = True
+        arg["allocate"] = True
+        # See Note [name and field_name]
+        if a.name in name_to_field_name:
+            arg["field_name"] = name_to_field_name[a.name]
+    # Historically, booleans don't get their size recorded, because it
+    # is already built into the cpp type (e.g., std::array)
+    l = a.type.is_list_like()
+    if l is not None and l.size is not None and str(l.elem) != "bool":
+        arg["size"] = l.size
+    return arg
+
+
+@with_native_function
+def compute_declaration_yaml(f: NativeFunction) -> object:
+    returns, name_to_field_name = compute_returns_yaml(f)
+
+    # These sets are used to conveniently test if an argument is a
+    # kwarg-only or out argument
+    kwarg_only_set = {a.name for a in f.func.arguments.flat_kwarg_only}
+    out_arg_set = {a.name for a in f.func.arguments.out}
+
+    sig_group = CppSignatureGroup.from_native_function(
+        f, method=False, fallback_binding=False
+    )
+    cpp_args = sig_group.signature.arguments()
+    arguments = [
+        compute_cpp_argument_yaml(
+            cpp_a,
+            schema_order=False,
+            kwarg_only_set=kwarg_only_set,
+            out_arg_set=out_arg_set,
+            name_to_field_name=name_to_field_name,
+        )
+        for cpp_a in cpp_args
+    ]
+
+    schema_order_jit_arguments = list(f.func.schema_order_arguments())
+
+    schema_order_arguments = [
+        compute_argument_yaml(
+            a,
+            schema_order=True,
+            kwarg_only_set=kwarg_only_set,
+            out_arg_set=out_arg_set,
+            name_to_field_name=name_to_field_name,
+        )
+        for a in schema_order_jit_arguments
+    ]
+
+    cpp_schema_order_types = [
+        # NB: method here doesn't matter
+        r.type
+        for a in schema_order_jit_arguments
+        for r in cpp.argument(
+            a,
+            method=False,
+            cpp_no_default_args=set(),
+            faithful=False,
+            symint=False,
+            has_tensor_options=False,
+        )
+    ]
+
+    # legacy, report ints
+    cpp_returns = cpp.returns_type(f.func.returns, symint=False).cpp_type()
+    schema_order_cpp_signature = f"{cpp_returns} ({', '.join(cpp_schema_order_types)})"
+
+    is_factory_method = (
+        any(isinstance(a.argument, TensorOptionsArguments) for a in cpp_args)
+        and Variant.method not in f.variants
+    )
+
+    return OrderedDict(
+        [
+            ("name", cpp.name(f.func)),
+            ("operator_name", str(f.func.name.name)),
+            ("overload_name", str(f.func.name.overload_name)),
+            ("manual_kernel_registration", f.manual_kernel_registration),
+            (
+                "category_override",
+                f.category_override if f.category_override is not None else "",
+            ),
+            ("schema_string", f"aten::{f.func}"),
+            ("arguments", arguments),
+            ("schema_order_cpp_signature", schema_order_cpp_signature),
+            ("schema_order_arguments", schema_order_arguments),
+            ("method_of", compute_method_of_yaml(f.variants)),
+            ("mode", "native"),
+            ("python_module", "" if f.python_module is None else f.python_module),
+            ("returns", returns),
+            ("inplace", f.func.name.name.inplace),
+            ("is_factory_method", is_factory_method),
+            ("abstract", f.is_abstract),
+            ("device_guard", f.device_guard),
+            ("with_gil", False),
+            ("deprecated", False),
+            ("has_math_kernel", f.has_composite_implicit_autograd_kernel),
+        ]
+    )
+
+
+# See Note [Auto generated composite kernels]
+def has_autogenerated_composite_kernel(f: NativeFunction) -> bool:
+    return (f.structured or f.structured_delegate is not None) and (
+        f.func.kind() == SchemaKind.functional or f.func.kind() == SchemaKind.inplace
+    )
+
+
+@with_native_function_and_indices
+def compute_registration_declarations(
+    f: NativeFunction, backend_indices: dict[DispatchKey, BackendIndex]
+) -> str:
+    name = dispatcher.name(f.func)
+    returns_type = dispatcher.returns_type(f.func.returns).cpp_type()
+    args = dispatcher.arguments(f.func)
+    args_str = ", ".join(a.no_default().decl() for a in args)
+    comment_data: dict[str, str] = {
+        "schema": f"aten::{f.func}",
+        # TODO: What exactly is the semantics of the 'dispatch' field?
+        "dispatch": str(
+            {k for k, v in backend_indices.items() if v.has_kernel(f)}
+            != {DispatchKey.CompositeImplicitAutograd}
+            and {k for k, v in backend_indices.items() if v.has_kernel(f)}
+            != {
+                DispatchKey.CompositeImplicitAutograd,
+                DispatchKey.CompositeImplicitAutogradNestedTensor,
+            }
+        ),
+        "default": str(f.has_composite_kernel or has_autogenerated_composite_kernel(f)),
+    }
+    return f"""{returns_type} {name}({args_str}); // {json.dumps(comment_data)}
+"""
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                           RUN IT ALL
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+def get_custom_build_selector(
+    provided_op_registration_allowlist: list[str] | None,
+    op_selection_yaml_path: str | None,
+) -> SelectiveBuilder:
+    assert not (
+        provided_op_registration_allowlist is not None
+        and op_selection_yaml_path is not None
+    ), (
+        "Both provided_op_registration_allowlist and "
+        + "op_selection_yaml_path can NOT be provided at the "
+        + "same time."
+    )
+
+    op_registration_allowlist: set[str] | None = None
+    if provided_op_registration_allowlist is not None:
+        op_registration_allowlist = set(provided_op_registration_allowlist)
+
+    if op_registration_allowlist is not None:
+        selector = SelectiveBuilder.from_legacy_op_registration_allow_list(
+            op_registration_allowlist,
+            True,
+            False,
+        )
+    elif op_selection_yaml_path is not None:
+        selector = SelectiveBuilder.from_yaml_path(op_selection_yaml_path)
+    else:
+        selector = SelectiveBuilder.get_nop_selector()
+
+    return selector
+
+
+def get_grouped_by_view_native_functions(
+    native_functions: Sequence[NativeFunction],
+) -> Sequence[NativeFunction | NativeFunctionsViewGroup]:
+    def maybe_create_view_group(
+        d: dict[ViewSchemaKind | SchemaKind, NativeFunction],
+    ) -> list[NativeFunction | NativeFunctionsViewGroup]:
+        funcs: list[NativeFunction | NativeFunctionsViewGroup] = []
+        if ViewSchemaKind.aliasing in d:
+            view = d.pop(ViewSchemaKind.aliasing)
+            view_inplace = d.pop(ViewSchemaKind.aliasing_inplace, None)
+            view_copy = d.pop(SchemaKind.functional, None)
+
+            funcs.append(
+                NativeFunctionsViewGroup(
+                    view=view,
+                    view_copy=view_copy,
+                    view_inplace=view_inplace,
+                )
+            )
+        # Take the remaining functions that weren't part of the view group
+        # and emit them separately
+        funcs.extend(d.values())
+        return funcs
+
+    grouped_by_views: dict[
+        FunctionSchema, dict[SchemaKind | ViewSchemaKind, NativeFunction]
+    ] = defaultdict(dict)
+    for f in native_functions:
+        schema = f.func.view_signature()
+        view_kind: ViewSchemaKind = f.view_schema_kind
+        # We need to group up ops relevant to the same "view", consisting of:
+        # view op (ViewSchemaKind.aliasing)
+        # view_inplace op (ViewSchemaKind.aliasing_inplace)
+        # view_copy op (SchemaKind.functional)
+        if view_kind == ViewSchemaKind.non_aliasing:
+            kind = f.func.kind()
+            assert kind not in grouped_by_views[schema]
+            grouped_by_views[schema][kind] = f
+        else:
+            assert view_kind not in grouped_by_views[schema], (
+                f"{view_kind} already in {grouped_by_views[schema].keys()}"
+            )
+            grouped_by_views[schema][view_kind] = f
+
+    return list(concatMap(maybe_create_view_group, grouped_by_views.values()))
+
+
+def get_grouped_native_functions(
+    native_functions: Sequence[NativeFunction],
+) -> Sequence[NativeFunction | NativeFunctionsGroup]:
+    def flatten_pre_group(
+        d: dict[SchemaKind, NativeFunction],
+    ) -> Sequence[NativeFunction | NativeFunctionsGroup]:
+        r = NativeFunctionsGroup.from_dict(d)
+        if r is None:
+            # Invariant: any NativeFunctions that are code-generated
+            # should have been grouped into NativeFunctionsGroup objects
+            assert not any("generated" in f.tags for f in d.values())
+            return list(d.values())
+        else:
+            return [r]
+
+    # TODO: how come ValuesView isn't a Sequence lol
+    pre_grouped_native_functions = pre_group_native_functions(native_functions)
+    return list(
+        concatMap(flatten_pre_group, list(pre_grouped_native_functions.values()))
+    )
+
+
+def get_ns_grouped_kernels(
+    *,
+    grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
+    backend_indices: dict[DispatchKey, BackendIndex],
+    native_function_decl_gen: Callable[
+        [NativeFunctionsGroup | NativeFunction, BackendIndex], list[str]
+    ] = dest.compute_native_function_declaration,
+) -> dict[str, list[str]]:
+    ns_grouped_kernels: dict[str, list[str]] = defaultdict(list)
+    for f in grouped_native_functions:
+        native_function_namespaces = set()
+        dispatch_keys = set()
+        for dispatch_key, backend_idx in backend_indices.items():
+            backend_metadata = backend_idx.get_kernel(f)
+            if backend_metadata:
+                namespace = backend_metadata.cpp_namespace
+                dispatch_keys.add(dispatch_key)
+                native_function_namespaces.add(namespace)
+            else:
+                namespace = DEFAULT_KERNEL_NAMESPACE
+            assert len(native_function_namespaces) <= 1, (
+                f"Codegen only supports one namespace per operator, got {native_function_namespaces} from {dispatch_keys}"
+            )
+            ns_grouped_kernels[namespace].extend(
+                native_function_decl_gen(f, backend_idx)
+            )
+    return ns_grouped_kernels
+
+
+def get_native_function_declarations_from_ns_grouped_kernels(
+    *,
+    ns_grouped_kernels: dict[str, list[str]],
+) -> list[str]:
+    declarations: list[str] = []
+    newline = "\n"
+    for namespace, kernels in ns_grouped_kernels.items():
+        ns_helper = NamespaceHelper(
+            namespace_str=namespace,
+            entity_name="",
+            max_level=4,
+        )
+        # Convert to a set first to remove duplicate kernel names. Backends are
+        # allowed to repeat kernel names; only generate the declaration once!
+        ordered_kernels = list(OrderedDict.fromkeys(kernels))
+        declarations.extend(
+            f"""
+{ns_helper.prologue}
+{newline.join(ordered_kernels)}
+{ns_helper.epilogue}
+        """.split(newline)
+        )
+    return declarations
+
+
+# Return native function declarations grouped by their namespaces.
+def get_native_function_declarations(
+    *,
+    grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
+    backend_indices: dict[DispatchKey, BackendIndex],
+    native_function_decl_gen: Callable[
+        [NativeFunctionsGroup | NativeFunction, BackendIndex], list[str]
+    ] = dest.compute_native_function_declaration,
+) -> list[str]:
+    """
+    Generate kernel declarations, in `NativeFunction(s).h`.
+    :param grouped_native_functions: a sequence of `NativeFunction` or `NativeFunctionGroup`.
+    :param backend_indices: kernel collections grouped by dispatch key.
+    :param native_function_decl_gen: callable to generate kernel declaration for each `NativeFunction`.
+    :return: a list of string, from the string with all declarations, grouped by namespaces, split by newline.
+    """
+
+    ns_grouped_kernels = get_ns_grouped_kernels(
+        grouped_native_functions=grouped_native_functions,
+        backend_indices=backend_indices,
+        native_function_decl_gen=native_function_decl_gen,
+    )
+    return get_native_function_declarations_from_ns_grouped_kernels(
+        ns_grouped_kernels=ns_grouped_kernels
+    )
+
+
+def get_kernel_namespace(
+    *, f: NativeFunction | NativeFunctionsGroup, backend_idx: BackendIndex
+) -> str:
+    backend_metadata = backend_idx.get_kernel(f)
+    assert not backend_metadata or "::native" in backend_metadata.cpp_namespace, (
+        f"The kernel for function {f.func.name if isinstance(f, NativeFunction) else f.functional.func.name} "
+        f"with dispatch key {backend_idx.dispatch_key}"
+        f" has a namespace {backend_metadata.cpp_namespace} and it's not ending with '::native'."
+    )
+    return (
+        backend_metadata.cpp_namespace if backend_metadata else DEFAULT_KERNEL_NAMESPACE
+    )
+
+
+# Return native function definitions grouped by dispatch key and custom namespace.
+# Used in RegisterDispatchKey.cpp and etc.
+def get_native_function_definitions(
+    *,
+    fm: FileManager,
+    grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
+    dispatch_key: DispatchKey,
+    backend_idx: BackendIndex,
+    selector: SelectiveBuilder,
+    rocm: bool,
+    symint: bool,
+    skip_dispatcher_op_registration: bool,
+    gen_dispatch_helpers: bool,
+) -> list[str]:
+    definitions: list[str] = []
+    ns_definitions: dict[str, list[str]] = defaultdict(list)
+    anonymous_definitions: dict[str, list[str]] = defaultdict(list)
+    registrations: dict[str, dict[str, list[str]]] = defaultdict(dict)
+    newline = "\n"
+    ns_gen = dest.RegisterDispatchKey(
+        backend_idx,
+        Target.NAMESPACED_DEFINITION,
+        selector,
+        rocm=rocm,
+        symint=symint,
+        class_method_name=None,
+        skip_dispatcher_op_registration=skip_dispatcher_op_registration,
+    )
+    anonymous_gen = dest.RegisterDispatchKey(
+        backend_idx,
+        Target.ANONYMOUS_DEFINITION,
+        selector,
+        rocm=rocm,
+        symint=symint,
+        class_method_name=None,
+        skip_dispatcher_op_registration=skip_dispatcher_op_registration,
+    )
+    reg_gen = dest.RegisterDispatchKey(
+        backend_idx,
+        Target.REGISTRATION,
+        selector,
+        rocm=rocm,
+        symint=symint,
+        class_method_name=None,
+        skip_dispatcher_op_registration=skip_dispatcher_op_registration,
+    )
+    for f in grouped_native_functions:
+        kernel_namespace = get_kernel_namespace(f=f, backend_idx=backend_idx).replace(
+            "::native", ""
+        )
+
+        ns_definitions[kernel_namespace].extend(
+            ns_gen(f),
+        )
+        anonymous_definitions[kernel_namespace].extend(
+            anonymous_gen(f),
+        )
+        namespace = (
+            f.namespace if isinstance(f, NativeFunction) else f.functional.namespace
+        )
+        if namespace not in registrations[kernel_namespace]:
+            registrations[kernel_namespace] = defaultdict(list)
+        registrations[kernel_namespace][namespace].extend(
+            reg_gen(f),
+        )
+
+    for kernel_namespace in ns_definitions:
+        if len(ns_definitions[kernel_namespace]) == 0:
+            continue
+        ns_helper = NamespaceHelper(namespace_str=kernel_namespace)
+        registration_body = ""
+        for namespace in registrations[kernel_namespace]:
+            if not registrations[kernel_namespace][namespace]:
+                continue
+            registration_body += f"""
+TORCH_LIBRARY_IMPL({namespace}, {dispatch_key}, m) {{
+    {newline.join(registrations[kernel_namespace][namespace])}
+}}"""
+        definitions.extend(
+            fm.substitute_with_template(
+                "RegisterDispatchDefinitions.ini",
+                lambda: {
+                    "ns_prologue": ns_helper.prologue,
+                    "ns_epilogue": ns_helper.epilogue,
+                    "dispatch_anonymous_definitions": anonymous_definitions[
+                        kernel_namespace
+                    ],
+                    "static_init_dispatch_registrations": ""
+                    if skip_dispatcher_op_registration
+                    else registration_body,
+                    "deferred_dispatch_registrations": "",
+                    "dispatch_namespace": dispatch_key.lower(),
+                    "dispatch_namespaced_definitions": ns_definitions[kernel_namespace],
+                },
+            ).split(newline)
+        )
+
+    return definitions
+
+
+# Return native function declarations grouped by dispatch key and custom namespace.
+# Used in CPUFunctions_inl.h and etc.
+def get_namespaced_declaration(
+    *,
+    grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
+    dispatch_key: DispatchKey,
+    backend_idx: BackendIndex,
+    selector: SelectiveBuilder,
+    rocm: bool,
+    symint: bool,
+) -> list[str]:
+    declarations: list[str] = []
+    ns_grouped_kernels: dict[str, list[str]] = defaultdict(list)
+    newline = "\n"
+    func = dest.RegisterDispatchKey(
+        backend_idx,
+        Target.NAMESPACED_DECLARATION,
+        selector,
+        rocm=rocm,
+        class_method_name=None,
+        skip_dispatcher_op_registration=False,
+        symint=symint,
+    )
+    for f in grouped_native_functions:
+        namespace = get_kernel_namespace(f=f, backend_idx=backend_idx).replace(
+            "native", dispatch_key.lower()
+        )
+
+        ns_grouped_kernels[namespace].extend(
+            func(f),
+        )
+
+    for namespace, kernels in ns_grouped_kernels.items():
+        if len(kernels) == 0:
+            continue
+        ns_helper = NamespaceHelper(
+            namespace_str=namespace, entity_name="", max_level=3
+        )
+        ordered_kernels = list(OrderedDict.fromkeys(kernels))
+        declarations.extend(
+            f"""
+{ns_helper.prologue}
+{newline.join(ordered_kernels)}
+{ns_helper.epilogue}
+        """.split(newline)
+        )
+    return declarations
+
+
+# Return native function schema registration code for aten and other namespaces.
+def get_native_function_schema_registrations(
+    *,
+    native_functions: Sequence[NativeFunction],
+    schema_selector: SelectiveBuilder,
+) -> tuple[list[str], str]:
+    ns_native_functions: dict[str, list[NativeFunction]] = defaultdict(list)
+    for native_function in native_functions:
+        ns_native_functions[native_function.namespace].append(native_function)
+    schema_registrations = ""
+    aten_schema_registrations = []
+    custom_namespace = None
+    for namespace, funcs in ns_native_functions.items():
+        schema_registrations_body = list(
+            mapMaybe(RegisterSchema(schema_selector), funcs)
+        )
+        # NB: we have to separate aten namespace registration from other namespaces,
+        # because in the template we hardcoded an operator for ATen already.
+        if namespace == "aten":
+            aten_schema_registrations = schema_registrations_body
+        else:
+            custom_namespace = namespace
+            tab = "\t"
+            # if the namespace is predefined, we should use define a library fragment
+            # instead of a new library
+            torch_library_macro = (
+                "TORCH_LIBRARY_FRAGMENT"
+                if namespace in FRAGMENT_NAMESPACES
+                else "TORCH_LIBRARY"
+            )
+            schema_registrations += f"""
+{torch_library_macro}({custom_namespace}, m) {{
+  {tab.join(schema_registrations_body)}
+}};"""
+    return (aten_schema_registrations, schema_registrations)
+
+
+def gen_aggregated_headers(
+    *,
+    native_functions: Sequence[NativeFunction],
+    grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
+    structured_native_functions: Sequence[NativeFunctionsGroup],
+    static_dispatch_idx: list[BackendIndex],
+    selector: SelectiveBuilder,
+    backend_indices: dict[DispatchKey, BackendIndex],
+    cpu_fm: FileManager,
+    device_fms: dict[str, FileManager],
+    functions_keys: set[DispatchKey],
+    dispatch_keys: Sequence[DispatchKey],
+    rocm: bool,
+) -> None:
+    # Buck doesn't support dynamic output files, so we aggregate all operator
+    # headers into a single file
+    cpu_fm.write(
+        "NativeMetaFunctions.h",
+        lambda: {
+            "NativeMetaFunctions_includes": [],
+            "NativeMetaFunctions_declarations": list(
+                mapMaybe(compute_meta_function_declaration, structured_native_functions)
+            ),
+        },
+    )
+    method_native_functions = [
+        fn for fn in native_functions if Variant.method in fn.variants
+    ]
+    non_method_native_functions = [
+        fn for fn in native_functions if fn not in method_native_functions
+    ]
+    cpu_fm.write(
+        "MethodOperators.h",
+        lambda: {
+            "MethodOperators_includes": [],
+            "MethodOperators_declarations": list(
+                mapMaybe(
+                    ComputeOperators(
+                        Target.DECLARATION,
+                        static_dispatch_backend_indices=static_dispatch_idx,
+                    ),
+                    method_native_functions,
+                )
+            ),
+        },
+    )
+    cpu_fm.write(
+        "Operators.h",
+        lambda: {
+            "Operators_includes": ["#include "],
+            "Operators_declarations": list(
+                mapMaybe(
+                    ComputeOperators(
+                        Target.DECLARATION,
+                        static_dispatch_backend_indices=static_dispatch_idx,
+                    ),
+                    non_method_native_functions,
+                )
+            ),
+        },
+    )
+    cpu_fm.write(
+        "Functions.h",
+        lambda: {
+            "static_dispatch_extra_headers": static_dispatch_extra_headers(
+                static_dispatch_idx
+            ),
+            "Functions_includes": ["#include "],
+            "Functions_declarations": list(
+                mapMaybe(
+                    ComputeFunction(),
+                    native_functions,
+                )
+            ),
+        },
+    )
+    declarations = get_native_function_declarations(
+        grouped_native_functions=grouped_native_functions,
+        backend_indices=backend_indices,
+    )
+    cpu_fm.write(
+        "NativeFunctions.h",
+        lambda: {
+            "NativeFunctions_includes": ["#include "],
+            "NativeFunctions_declarations": declarations,
+        },
+    )
+
+    for dispatch_key in dispatch_keys:
+        fm = file_manager_from_dispatch_key(dispatch_key, device_fms, cpu_fm)
+        if dispatch_key in functions_keys:
+            inl_headers = f"#include "
+
+            fm.write_with_template(
+                f"{dispatch_key}Functions.h",
+                "DispatchKeyFunctions.h",
+                lambda: {
+                    "dispatch_key": str(dispatch_key),
+                    "inline_headers": inl_headers,
+                },
+            )
+            fm.write_with_template(
+                f"{dispatch_key}Functions_inl.h",
+                "DispatchKeyFunctions_inl.h",
+                lambda: {
+                    "DispatchKeyFunctions_inl_includes": [],
+                    "dispatch_namespace": dispatch_key.lower(),
+                    "dispatch_namespaced_declarations": get_namespaced_declaration(
+                        grouped_native_functions=grouped_native_functions,
+                        dispatch_key=dispatch_key,
+                        backend_idx=backend_indices[dispatch_key],
+                        selector=selector,
+                        rocm=rocm,
+                        symint=True,
+                    ),
+                },
+            )
+
+        del fm
+
+
+def gen_per_operator_headers(
+    *,
+    native_functions: Sequence[NativeFunction],
+    grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
+    static_dispatch_idx: list[BackendIndex],
+    selector: SelectiveBuilder,
+    backend_indices: dict[DispatchKey, BackendIndex],
+    cpu_fm: FileManager,
+    device_fms: dict[str, FileManager],
+    ops_fm: FileManager,
+    functions_keys: set[DispatchKey],
+    dispatch_keys: Sequence[DispatchKey],
+    rocm: bool,
+) -> None:
+    # For CMake builds, split operator declarations into separate headers in
+    # the ATen/ops folder to split up header dependencies
+    functions_by_root_name: dict[str, list[NativeFunction]] = defaultdict(list)
+    for fn in native_functions:
+        functions_by_root_name[fn.root_name].append(fn)
+
+    grouped_functions_by_root_name: dict[
+        str, list[NativeFunction | NativeFunctionsGroup]
+    ] = defaultdict(list)
+    for group in grouped_native_functions:
+        name = group.root_name
+        grouped_functions_by_root_name[name].append(group)
+
+    for name, functions in functions_by_root_name.items():
+        ops_fm.write_with_template(
+            f"{name}_ops.h",
+            "Operator.h",
+            lambda: {
+                "declarations": list(
+                    mapMaybe(
+                        ComputeOperators(
+                            Target.DECLARATION,
+                            static_dispatch_backend_indices=static_dispatch_idx,
+                        ),
+                        functions,
+                    )
+                ),
+            },
+        )
+
+        ops_fm.write_with_template(
+            f"{name}.h",
+            "Function.h",
+            lambda: {
+                "static_dispatch_ops_headers": list(
+                    mapMaybe(
+                        lambda fn: static_dispatch_ops_header(
+                            fn, backend_index=static_dispatch_idx
+                        ),
+                        functions,
+                    )
+                ),
+                "operator_includes": f"#include ",
+                "function_definitions": list(
+                    mapMaybe(
+                        ComputeFunction(),
+                        functions,
+                    )
+                ),
+            },
+        )
+
+        grouped_functions = grouped_functions_by_root_name.get(name, [])
+        structured_functions = [
+            fn
+            for fn in grouped_functions
+            if isinstance(fn, NativeFunctionsGroup) and fn.structured
+        ]
+        is_structured = len(structured_functions) > 0
+
+        if is_structured:
+            ops_fm.write_with_template(
+                f"{name}_meta.h",
+                "NativeMetaFunction.h",
+                lambda: {
+                    "meta_function_declarations": list(
+                        mapMaybe(
+                            compute_meta_function_declaration, structured_functions
+                        )
+                    ),
+                },
+            )
+        declarations = get_native_function_declarations(
+            grouped_native_functions=grouped_functions,
+            backend_indices=backend_indices,
+            native_function_decl_gen=dest.compute_native_function_declaration,
+        )
+        ops_fm.write_with_template(
+            f"{name}_native.h",
+            "NativeFunction.h",
+            lambda: {
+                "extra_includes": (
+                    f"#include " if is_structured else []
+                ),
+                "native_function_declarations": declarations,
+            },
+        )
+
+    for category, suffix in [
+        ("Functions", ""),
+        ("Operators", "_ops"),
+        ("NativeMetaFunctions", "_meta"),
+        ("NativeFunctions", "_native"),
+    ]:
+        cpu_fm.write(
+            f"{category}.h",
+            lambda: {
+                f"{category}_includes": [
+                    f"#include "
+                    for name in sorted(functions_by_root_name.keys())
+                ],
+                f"{category}_declarations": [],
+            },
+        )
+
+    for dispatch_key in dispatch_keys:
+        if dispatch_key not in functions_keys:
+            continue
+
+        dispatch_namespace = dispatch_key.lower()
+        dispatch_names = []
+
+        for name, functions in functions_by_root_name.items():
+            grouped_functions = grouped_functions_by_root_name.get(name, [])
+            declarations = list(
+                concatMap(
+                    dest.RegisterDispatchKey(
+                        backend_indices[dispatch_key],
+                        Target.NAMESPACED_DECLARATION,
+                        selector,
+                        rocm=rocm,
+                        symint=True,
+                        class_method_name=None,
+                        skip_dispatcher_op_registration=False,
+                    ),
+                    grouped_functions,
+                )
+            )
+
+            if len(declarations) == 0:
+                continue
+
+            dispatch_names.append(name)
+            ops_fm.write_with_template(
+                f"{name}_{dispatch_namespace}_dispatch.h",
+                "DispatchKeyFunction.h",
+                lambda: {
+                    "dispatch_namespace": dispatch_namespace,
+                    "dispatch_namespaced_declarations": declarations,
+                },
+            )
+
+        fm = file_manager_from_dispatch_key(dispatch_key, device_fms, cpu_fm)
+        inl_headers = f"#include "
+
+        fm.write_with_template(
+            f"{dispatch_key}Functions.h",
+            "DispatchKeyFunctions.h",
+            lambda: {
+                "dispatch_key": str(dispatch_key),
+                "inline_headers": inl_headers,
+            },
+        )
+        fm.write_with_template(
+            f"{dispatch_key}Functions_inl.h",
+            "DispatchKeyFunctions_inl.h",
+            lambda: {
+                "dispatch_namespace": dispatch_namespace,
+                "DispatchKeyFunctions_inl_includes": [
+                    f"#include "
+                    for name in sorted(dispatch_names)
+                ],
+                "dispatch_namespaced_declarations": [],
+            },
+        )
+        del fm
+
+    cpu_fm.write(
+        "MethodOperators.h",
+        lambda: {
+            "MethodOperators_includes": sorted(
+                f"#include "
+                for name, functions in functions_by_root_name.items()
+                if any(Variant.method in fn.variants for fn in functions)
+            ),
+            "MethodOperators_declarations": [],
+        },
+    )
+
+
+def gen_headers(
+    *,
+    native_functions: Sequence[NativeFunction],
+    valid_tags: set[str],
+    grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
+    structured_native_functions: Sequence[NativeFunctionsGroup],
+    static_dispatch_idx: list[BackendIndex],
+    selector: SelectiveBuilder,
+    backend_indices: dict[DispatchKey, BackendIndex],
+    core_fm: FileManager,
+    cpu_fm: FileManager,
+    device_fms: dict[str, FileManager],
+    ops_fm: FileManager,
+    dispatch_keys: Sequence[DispatchKey],
+    functions_keys: set[DispatchKey],
+    rocm: bool,
+    per_operator_headers: bool,
+) -> None:
+    if per_operator_headers:
+        gen_per_operator_headers(
+            native_functions=native_functions,
+            grouped_native_functions=grouped_native_functions,
+            static_dispatch_idx=static_dispatch_idx,
+            selector=selector,
+            backend_indices=backend_indices,
+            cpu_fm=cpu_fm,
+            device_fms=device_fms,
+            ops_fm=ops_fm,
+            dispatch_keys=dispatch_keys,
+            functions_keys=functions_keys,
+            rocm=rocm,
+        )
+    else:
+        gen_aggregated_headers(
+            native_functions=native_functions,
+            grouped_native_functions=grouped_native_functions,
+            structured_native_functions=structured_native_functions,
+            static_dispatch_idx=static_dispatch_idx,
+            selector=selector,
+            backend_indices=backend_indices,
+            cpu_fm=cpu_fm,
+            device_fms=device_fms,
+            dispatch_keys=dispatch_keys,
+            functions_keys=functions_keys,
+            rocm=rocm,
+        )
+
+    core_fm.write(
+        "TensorBody.h",
+        lambda: {
+            "tensor_method_declarations": list(
+                mapMaybe(
+                    ComputeTensorMethod(
+                        target=Target.DECLARATION,
+                        static_dispatch_backend_indices=static_dispatch_idx,
+                    ),
+                    native_functions,
+                )
+            ),
+            "tensor_method_definitions": list(
+                mapMaybe(
+                    ComputeTensorMethod(
+                        target=Target.DEFINITION,
+                        static_dispatch_backend_indices=static_dispatch_idx,
+                    ),
+                    native_functions,
+                )
+            ),
+        },
+    )
+
+    cpu_fm.write(
+        "RedispatchFunctions.h",
+        lambda: {
+            "function_redispatch_definitions": list(
+                mapMaybe(ComputeRedispatchFunction(), native_functions)
+            ),
+        },
+    )
+
+    cpu_fm.write(
+        "RegistrationDeclarations.h",
+        lambda: {
+            "registration_declarations": [
+                compute_registration_declarations(f, backend_indices)
+                for f in native_functions
+            ],
+        },
+    )
+
+    cpu_fm.write(
+        "VmapGeneratedPlumbing.h", lambda: gen_all_vmap_plumbing(native_functions)
+    )
+
+    def gen_aten_interned_strings() -> dict[str, str]:
+        attrs: set[str] = set()  # All function argument names
+        names = set()  # All ATen function names
+        for func in native_functions:
+            names.add(str(func.func.name.name))
+            # Some operators don't have a functional variant but we still create a
+            # symbol without the underscore
+            names.add(func.func.name.name.base)
+
+            attrs.update(arg.name for arg in func.func.schema_order_arguments())
+
+        # These are keywords in C++, so aren't valid symbol names
+        # https://en.cppreference.com/w/cpp/language/operator_alternative
+        names -= {
+            "and",
+            "and_eq",
+            "bitand",
+            "bitor",
+            "compl",
+            "not",
+            "not_eq",
+            "or",
+            "or_eq",
+            "xor",
+            "xor_eq",
+        }
+
+        return {
+            "aten_symbols": " \\\n".join(
+                [f"_(aten, {name})" for name in sorted(names)]
+            ),
+            "attr_symbols": " \\\n".join(
+                [f"_(attr, {name})" for name in sorted(attrs)]
+            ),
+        }
+
+    core_fm.write("aten_interned_strings.h", gen_aten_interned_strings)
+
+    def gen_tags_enum() -> dict[str, str]:
+        return {"enum_of_valid_tags": (",\n".join(sorted(valid_tags)))}
+
+    core_fm.write("enum_tag.h", gen_tags_enum)
+
+
+def gen_source_files(
+    *,
+    native_functions: Sequence[NativeFunction],
+    grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
+    structured_native_functions: Sequence[NativeFunctionsGroup],
+    view_groups: Sequence[NativeFunctionsViewGroup],
+    selector: SelectiveBuilder,
+    static_dispatch_idx: list[BackendIndex],
+    backend_indices: dict[DispatchKey, BackendIndex],
+    aoti_fm: FileManager,
+    core_fm: FileManager,
+    cpu_vec_fm: FileManager,
+    cpu_fm: FileManager,
+    device_fms: dict[str, FileManager],
+    dispatch_keys: Sequence[DispatchKey],
+    functions_keys: set[DispatchKey],
+    rocm: bool,
+    force_schema_registration: bool,
+    per_operator_headers: bool,
+    skip_dispatcher_op_registration: bool,
+    update_aoti_c_shim: bool,
+    aoti_backends: set[Optional[DispatchKey]],
+    extend_aoti_c_shim: bool,
+) -> None:
+    extra_cuda_headers = """\
+#include 
+#include 
+#include 
+#include """
+    if rocm:
+        extra_cuda_headers = """\
+#include 
+#include 
+#include 
+#include """
+
+    for dispatch_key in dispatch_keys:
+        fm = file_manager_from_dispatch_key(dispatch_key, device_fms, cpu_fm)
+        if per_operator_headers:
+
+            def operator_headers() -> list[str]:
+                headers = []
+                for g in grouped_native_functions:
+                    is_registered = False
+                    if backend_index.has_kernel(g):
+                        is_registered = True
+                    # The above has_kernel test on a group will only test for
+                    # the existence of out dispatch, because that's how
+                    # structured kernels work. But sometimes functions can be
+                    # grouped but not be structured, and then you need to check
+                    # each individual piece, as they may have manual dispatch
+                    # entries.
+                    elif isinstance(g, NativeFunctionsGroup) and any(
+                        backend_index.has_kernel(fn) for fn in g.functions()
+                    ):
+                        is_registered = True
+                    # TODO: this condition is a bit questionable
+                    # (It has to do with the fact that structured kernels get generated kernels
+                    # to the Meta + CompositeExplicitAutogradNonFunctional keys).
+                    elif g.structured and dispatch_key in (
+                        DispatchKey.Meta,
+                        DispatchKey.CompositeExplicitAutogradNonFunctional,
+                    ):
+                        is_registered = True
+                    if not is_registered:
+                        continue
+
+                    headers.append(f"#include ")
+                    if (
+                        dispatch_key
+                        == DispatchKey.CompositeExplicitAutogradNonFunctional
+                    ):
+                        headers.append(f"#include ")
+                    if dispatch_key in functions_keys:
+                        headers.append(
+                            f"#include "
+                        )
+
+                return sorted(set(headers))
+
+        else:
+
+            def operator_headers() -> list[str]:
+                headers = ["#include "]
+                if dispatch_key == DispatchKey.CompositeExplicitAutogradNonFunctional:
+                    headers.append("#include ")
+                if dispatch_key in functions_keys:
+                    headers.append(f"#include ")
+                return headers
+
+        backend_index = backend_indices[dispatch_key]
+        ns_grouped_native_functions = defaultdict(list)
+        for grouped_native_function in grouped_native_functions:
+            namespace = (
+                grouped_native_function.namespace
+                if isinstance(grouped_native_function, NativeFunction)
+                else grouped_native_function.functional.namespace
+            )
+            ns_grouped_native_functions[namespace].append(grouped_native_function)
+
+        dispatch_namespace = str(dispatch_key).lower()
+
+        # CompositeImplicitAutogradNestdTensor does not currently user the helpers generated
+        # compilation will fail when `-Werror=unused-function` flag is set
+        gen_dispatch_helpers: bool = (
+            dispatch_key != DispatchKey.CompositeImplicitAutogradNestedTensor
+        )
+
+        register_dispatch_key_base_env = {
+            "extra_cuda_headers": extra_cuda_headers
+            if is_cuda_dispatch_key(dispatch_key)
+            else "",
+            "external_backend_headers": "",
+            "dispatch_headers": dest.gen_registration_headers(
+                backend_index, per_operator_headers, rocm
+            ),
+            # ops_headers *could* be sharded, but doesn't seem necessary?
+            "ops_headers": operator_headers(),
+            "dispatch_helpers": (
+                dest.gen_registration_helpers(backend_index)
+                if gen_dispatch_helpers
+                else []
+            ),
+        }
+
+        def register_dispatch_key_env_callable(
+            gnf: NativeFunction | NativeFunctionsGroup,
+        ) -> dict[str, list[str]]:
+            return {
+                "dispatch_definitions": get_native_function_definitions(
+                    fm=fm,  # noqa: F821
+                    grouped_native_functions=[gnf],
+                    dispatch_key=dispatch_key,
+                    backend_idx=backend_index,
+                    selector=selector,
+                    rocm=rocm,
+                    symint=True,
+                    skip_dispatcher_op_registration=skip_dispatcher_op_registration,
+                    gen_dispatch_helpers=gen_dispatch_helpers,
+                )
+            }
+
+        fm.write_sharded_with_template(
+            f"Register{dispatch_key}.cpp",
+            "RegisterDispatchKey.cpp",
+            grouped_native_functions,
+            key_fn=lambda x: x.root_name,
+            env_callable=register_dispatch_key_env_callable,
+            num_shards=4 if dispatch_key == DispatchKey.CPU else 1,
+            base_env=register_dispatch_key_base_env,
+            sharded_keys={"dispatch_definitions"},
+        )
+
+        for g in structured_native_functions:
+            if not g.out.ufunc_inner_loop or not is_ufunc_dispatch_key(dispatch_key):
+                continue
+            name = g.functional.func.name.name
+            if dispatch_key is DispatchKey.CPU:
+                assert fm is cpu_fm
+                fm.write_with_template(
+                    f"UfuncCPU_{name}.cpp",
+                    "UfuncCPU.cpp",
+                    lambda: {
+                        "meta_declaration": compute_meta_function_declaration(g),
+                        "native_declaration": dest.compute_native_function_declaration(
+                            g, backend_indices[dispatch_key]
+                        ),
+                        "native_definitions": dest.compute_ufunc_cpu(g),
+                    },
+                )
+                cpu_vec_fm.write_with_template(
+                    f"UfuncCPUKernel_{name}.cpp",
+                    "UfuncCPUKernel.cpp",
+                    lambda: {
+                        "name": name,
+                        "native_definitions": dest.compute_ufunc_cpu_kernel(g),
+                    },
+                )
+            elif dispatch_key is DispatchKey.CUDA:
+                cuda_headers = "#include "
+                if rocm:
+                    cuda_headers = "#include "
+                fm.write_with_template(
+                    f"UfuncCUDA_{name}.cu",
+                    "UfuncCUDA.cu",
+                    lambda: {
+                        "name": name,
+                        "cuda_headers": cuda_headers,
+                        "meta_declaration": compute_meta_function_declaration(g),
+                        "native_declaration": dest.compute_native_function_declaration(
+                            g, backend_indices[dispatch_key]
+                        ),
+                        "native_definitions": dest.compute_ufunc_cuda(g),
+                    },
+                )
+            else:
+                raise AssertionError(f"unrecognized {dispatch_key} for ufunc")
+
+        del fm
+
+    gen_aoti_c_shim_files(
+        aoti_fm=aoti_fm,
+        aoti_backends=aoti_backends,
+        native_functions=native_functions,
+        backend_indices=backend_indices,
+        structured_native_functions=structured_native_functions,
+        extra_cuda_headers=extra_cuda_headers,
+        update_aoti_c_shim=update_aoti_c_shim,
+        extend_aoti_c_shim=extend_aoti_c_shim,
+    )
+
+    # BackendSelect is generated specially
+    def gen_backend_select() -> dict[str, list[str]]:
+        relevant_fns = [
+            fn for fn in native_functions if needs_backend_select(fn, selector)
+        ]
+        return {
+            "ops_headers": [
+                f"#include " for fn in relevant_fns
+            ],
+            "backend_select_method_definitions": list(
+                mapMaybe(
+                    ComputeBackendSelect(Target.DEFINITION, selector), relevant_fns
+                )
+            ),
+            "backend_select_function_registrations": list(
+                mapMaybe(
+                    ComputeBackendSelect(Target.REGISTRATION, selector), relevant_fns
+                )
+            ),
+        }
+
+    cpu_fm.write("RegisterBackendSelect.cpp", gen_backend_select)
+
+    schema_selector = selector
+    if force_schema_registration:
+        schema_selector = SelectiveBuilder.get_nop_selector()
+
+    (
+        aten_schema_registrations,
+        schema_registrations,
+    ) = get_native_function_schema_registrations(
+        native_functions=native_functions, schema_selector=schema_selector
+    )
+    cpu_fm.write(
+        "RegisterSchema.cpp",
+        lambda: {
+            "aten_schema_registrations": []
+            if skip_dispatcher_op_registration
+            else aten_schema_registrations,
+            "schema_registrations": []
+            if skip_dispatcher_op_registration
+            else schema_registrations,
+        },
+    )
+
+    def key_func(
+        fn: NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup,
+    ) -> str:
+        return fn.root_name
+
+    cpu_fm.write_sharded(
+        "Operators.cpp",
+        native_functions,
+        key_fn=key_func,
+        env_callable=lambda fn: {
+            "operator_headers": [f"#include "],
+            "definitions": [
+                ComputeOperators(
+                    Target.DEFINITION,
+                    static_dispatch_backend_indices=static_dispatch_idx,
+                )(fn)
+            ],
+        },
+        base_env={
+            "static_dispatch_extra_headers": static_dispatch_extra_headers(
+                static_dispatch_idx
+            ),
+        },
+        num_shards=5,
+        sharded_keys={
+            "operator_headers",
+            "definitions",
+            "static_dispatch_extra_headers",
+        },
+    )
+
+    cpu_fm.write("Functions.cpp", dict)
+
+    core_fm.write("TensorMethods.cpp", dict)
+
+    core_fm.write(
+        "ATenOpList.cpp",
+        lambda: {
+            "aten_ops": list(mapMaybe(compute_aten_op, native_functions)),
+        },
+    )
+
+    def gen_op_headers(
+        g: NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup,
+    ) -> list[str]:
+        if isinstance(g, NativeFunctionsViewGroup):
+            # view ops always get a functionalization kernel
+            headers = [
+                f"#include ",
+                f"#include ",
+            ]
+            if g.view_copy is not None:
+                headers += [
+                    f"#include ",
+                    f"#include ",
+                ]
+            return headers
+        elif isinstance(g, NativeFunctionsGroup):
+            headers = [
+                f"#include ",
+                f"#include ",
+                f"#include ",
+                f"#include ",
+            ]
+            if g.inplace is not None:
+                headers += [
+                    f"#include ",
+                    f"#include ",
+                ]
+            if g.mutable is not None:
+                headers += [
+                    f"#include ",
+                    f"#include ",
+                ]
+            return headers
+        else:
+            return [
+                f"#include ",
+                f"#include ",
+            ]
+
+    def functionalization_env_callable(
+        g: NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup,
+    ) -> dict[str, list[str]]:
+        return {
+            "ops_headers": gen_op_headers(g),
+            "func_definitions": gen_functionalization_definition(
+                selector,
+                g,
+            ),
+            "func_registrations": gen_functionalization_registration(
+                selector,
+                g,
+                backend_indices[DispatchKey.CompositeImplicitAutograd],
+            ),
+        }
+
+    all_groups: list[
+        NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup
+    ] = list(structured_native_functions) + list(
+        view_groups  # type: ignore[assignment, arg-type, operator]
+    )
+    # Note: all operators that functionalization needs to handle (mutable and aliasing ops) should be grouped properly.
+    # The only reason we really need to deal with direct NativeFunctions here (instead of the groups) is because:
+    # (1) We can provide better error checking (error out if someone introduces a mutable op that doesn't obey the grouping logic)
+    # (2) functionalization needs to manually register CompositeImplicitAutograd kernels, which might not be grouped.
+    #     Although this could go away long-term if we add a dedicated dispatch key for decompositions.
+    structured_map: dict[OperatorName, NativeFunction] = {
+        f.func.name: f
+        for f in concatMap(lambda g: list(g.functions()), structured_native_functions)
+    }
+    view_map: dict[OperatorName, NativeFunction] = {
+        f.func.name: f for f in concatMap(lambda g: list(g.functions()), view_groups)
+    }
+    all_groups.extend(
+        f
+        for f in native_functions
+        if f.func.name not in structured_map and f.func.name not in view_map
+    )
+
+    cpu_fm.write_sharded(
+        "RegisterFunctionalization.cpp",
+        all_groups,
+        key_fn=key_func,
+        env_callable=functionalization_env_callable,
+        num_shards=4,
+        sharded_keys={
+            "ops_headers",
+            "func_definitions",
+            "func_registrations",
+            "func_add_back_views_definitions",
+            "func_add_back_views_registrations",
+        },
+    )
+
+    cpu_fm.write(
+        "FunctionalInverses.h",
+        lambda: {
+            "view_inverse_declarations": list(
+                mapMaybe(
+                    lambda g: gen_functionalization_view_inverse_declaration(
+                        selector, g
+                    ),
+                    view_groups,
+                )
+            )
+        },
+    )
+
+    cpu_fm.write(
+        "ViewMetaClasses.h",
+        lambda: {
+            "view_meta_declarations": list(
+                concatMap(
+                    lambda g: gen_functionalization_view_meta_classes_decl(selector, g),
+                    view_groups,
+                )
+            )
+        },
+    )
+
+    cpu_fm.write(
+        "ViewMetaClasses.cpp",
+        lambda: {
+            "view_meta_implementations": list(
+                concatMap(
+                    lambda g: gen_functionalization_view_meta_classes_impl(selector, g),
+                    view_groups,
+                )
+            ),
+            "op_headers": list(concatMap(gen_op_headers, view_groups)),
+        },
+    )
+
+    # Note [view_copy NativeFunctions]
+    # Every view operator in native_functions.yaml that is not CompositeImplicitAutograd
+    # needs to have a corresponding non-aliasing {view}_copy variant.
+    # Backends that use functionalization and don't know how to handle aliasing ops
+    # are expected to implement kernels for these {view}_copy kernels instead.
+    # The code for {view}_copy operators in core is pretty boilerplate-heavy however,
+    # so we codegen the following:
+    # (1) A CompositeExplicitAutogradNonFunctional kernel for every {view}_copy operator.
+    #     These are never explicitly invoked by the functionalization pass,
+    #     but they could theoretically be called from user code (I added these kernels for completeness,
+    #     since the ops are part of the public API).
+    # (2) A derivative formula for every {view}_copy operator
+    #     {view}_copy operators can reuse the same derivative formulas as their {view} op counterparts,
+    #     so rather than stamping all of the entries out in derivatives.yaml,
+    #     we codegen them in.
+    #     This is similar to how autograd codegen doesn't require inplace ops to have a derivatives.yaml entry.
+    cpu_fm.write(
+        "CompositeViewCopyKernels.cpp",
+        lambda: {
+            "ops_headers": [
+                "\n".join(
+                    f"#include \n"
+                    # NB: this include is important as it ensures we
+                    # set the visibility on generated view_copy kernels
+                    # correctly
+                    f"#include "
+                    for f in (
+                        [g.view] if g.view_copy is None else [g.view, g.view_copy]
+                    )
+                )
+                for g in view_groups
+            ]
+            + [
+                "\n".join(
+                    f"#include \n"
+                    # NB: this include is also important for correct visibility
+                    f"#include "
+                    for f in [g.inplace, g.mutable, g.functional]
+                    if f is not None and "generated" not in f.tags
+                )
+                for g in structured_native_functions
+            ],
+            "CompositeViewCopyKernel_Definitions": list(
+                mapMaybe(
+                    GenCompositeViewCopyKernel(
+                        backend_indices[
+                            DispatchKey.CompositeExplicitAutogradNonFunctional
+                        ]
+                    ),
+                    view_groups,
+                )
+            ),
+            "GeneratedCompositeFunctional_Definitions": list(
+                mapMaybe(
+                    gen_composite_functional_kernel,
+                    structured_native_functions,
+                )
+            ),
+            "GeneratedCompositeOut_Definitions": list(
+                mapMaybe(
+                    gen_composite_out_kernel,
+                    structured_native_functions,
+                )
+            ),
+        },
+    )
+
+
+def gen_declarations_yaml(
+    cpu_fm: FileManager, native_functions: Sequence[NativeFunction]
+) -> None:
+    cpu_fm.write(
+        "Declarations.yaml",
+        lambda: format_yaml([compute_declaration_yaml(f) for f in native_functions]),
+    )
+
+
+def get_torchgen_root() -> Path:
+    """
+    If you're depending on torchgen out-of-tree, you can use the root to figure
+    out the path to native_functions.yaml
+    """
+    return Path(__file__).parent.resolve()
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(description="Generate ATen source files")
+    parser.add_argument(
+        "-s",
+        "--source-path",
+        help="path to source directory for ATen",
+        default="aten/src/ATen",
+    )
+    parser.add_argument(
+        "-o",
+        "--output-dependencies",
+        help="output a list of dependencies into the given file and exit",
+    )
+    parser.add_argument(
+        "--dry-run",
+        action="store_true",
+        help="run without writing any files (still updates outputs)",
+    )
+    parser.add_argument(
+        "--per-operator-headers",
+        action="store_true",
+        help="generate separate headers per operator in ATen/ops",
+    )
+    parser.add_argument(
+        "-d",
+        "--install-dir",
+        "--install_dir",
+        help="output directory",
+        default="build/aten/src/ATen",
+    )
+    parser.add_argument(
+        "--aoti-install-dir",
+        "--aoti_install_dir",
+        help="output directory for AOTInductor shim",
+        default="torch/csrc/inductor/aoti_torch/generated",
+    )
+    parser.add_argument(
+        "--rocm",
+        action="store_true",
+        help="reinterpret CUDA as ROCm/HIP and adjust filepaths accordingly",
+    )
+    parser.add_argument(
+        "--mps",
+        action="store_true",
+        help="Generate MPS registration code when set",
+    )
+    parser.add_argument(
+        "--xpu",
+        action="store_true",
+        help="Generate XPU registration code when set",
+    )
+    parser.add_argument(
+        "--mtia",
+        action="store_true",
+        help="Generate MTIA registration code when set",
+    )
+
+    # TODO: --op-registration-whitelist will be removed when all call-sites
+    # for gen.py are moved over to using the operator YAML file for mobile
+    # custom build.
+    parser.add_argument(
+        "--op-registration-whitelist",
+        "--op_registration_whitelist",
+        nargs="*",
+        help="filter op registrations by the whitelist (if set); "
+        "each item is `namespace`::`operator name` without overload name; "
+        "e.g.: aten::empty aten::conv2d ...",
+    )
+    parser.add_argument(
+        "--op-selection-yaml-path",
+        "--op_selection_yaml_path",
+        help="Provide a path to the operator selection (for custom build) YAML "
+        "that contains the information about the set of selected operators "
+        "and their categories (training, ...). Each operator is either a "
+        "full operator name with overload or just a bare operator name. "
+        "The operator names also contain the namespace prefix (e.g. aten::)",
+    )
+    parser.add_argument(
+        "--backend-whitelist",
+        "--backend_whitelist",
+        nargs="*",
+        help="filter dispatch backend by the whitelist (if set), "
+        "e.g.: CPU CUDA QuantizedCPU ...",
+    )
+    parser.add_argument(
+        "--static-dispatch-backend",
+        "--static_dispatch_backend",
+        nargs="*",
+        help="generate static dispatch code for the specific backend (if set)",
+    )
+    parser.add_argument(
+        "--skip-dispatcher-op-registration",
+        "--skip_dispatcher_op_registration",
+        action="store_true",
+        help="Avoid registering operators into the dispatcher.",
+    )
+    parser.add_argument(
+        "--force-schema-registration",
+        "--force_schema_registration",
+        action="store_true",
+        help="force it to generate schema-only registrations for all ops, including"
+        "those that are not listed on --op-registration-whitelist",
+    )
+    parser.add_argument(
+        "--generate",
+        type=str,
+        nargs="*",
+        choices=["headers", "sources", "declarations_yaml"],
+        default=["headers", "sources", "declarations_yaml"],
+        help="Generate only a subset of files",
+    )
+    parser.add_argument(
+        "--update-aoti-c-shim",
+        action="store_true",
+        help="Update AOTInductor C shim after adding an entry to inductor_fallback_ops in torchgen/aoti/fallback_ops.py. "
+        "WARNING: Do not use this unless you are sure what you are doing!!!",
+    )
+    parser.add_argument(
+        "--extend-aoti-c-shim",
+        action="store_true",
+        help="This Flag indicates the generation of c shims for out-of-tree ATen ops,"
+        "which is an extension to the In-tree ATen op c shims. This flag needs to be combined with"
+        "---source-path="
+        "--aoti-install-dir=/extend"
+        "   default is torch/csrc/inductor/aoti_torch/generated/extend"
+        "WARNING: Do not use this unless you are sure what you are doing!!!",
+    )
+
+    options = parser.parse_args()
+
+    selector = get_custom_build_selector(
+        options.op_registration_whitelist,
+        options.op_selection_yaml_path,
+    )
+
+    native_yaml_path = os.path.join(options.source_path, "native/native_functions.yaml")
+    tags_yaml_path = os.path.join(options.source_path, "native/tags.yaml")
+
+    from torchgen.model import dispatch_keys
+
+    # Only a limited set of dispatch keys get CPUFunctions.h headers generated
+    # for them; this is the set
+    functions_keys = {
+        DispatchKey.CPU,
+        DispatchKey.CUDA,
+        DispatchKey.CompositeImplicitAutograd,
+        DispatchKey.CompositeImplicitAutogradNestedTensor,
+        DispatchKey.CompositeExplicitAutograd,
+        DispatchKey.CompositeExplicitAutogradNonFunctional,
+        DispatchKey.Meta,
+        DispatchKey.MTIA,
+    }
+
+    aoti_backends = {
+        DispatchKey.CPU,
+        DispatchKey.CUDA,
+        # None will generate the aten shim based on aten_shimified_ops
+        # which does not bypass the dispatcher
+        None,
+    }
+
+    # TODO: stop generating CUDA kernels for non-CUDA builds
+    ignore_keys = set()
+
+    MPS_KEYS = {DispatchKey.MPS, DispatchKey.SparseMPS, DispatchKey.SparseCsrMPS}
+    if options.mps or options.update_aoti_c_shim:
+        functions_keys.update(MPS_KEYS)
+        aoti_backends.add(DispatchKey.MPS)
+    else:
+        ignore_keys.update(MPS_KEYS)
+        dispatch_keys[:] = [k for k in dispatch_keys if k not in MPS_KEYS]
+
+    if options.xpu or options.update_aoti_c_shim:
+        functions_keys.add(DispatchKey.XPU)
+        aoti_backends.add(DispatchKey.XPU)
+    else:
+        ignore_keys.add(DispatchKey.XPU)
+
+        if DispatchKey.XPU in dispatch_keys:
+            del dispatch_keys[dispatch_keys.index(DispatchKey.XPU)]
+
+    if not options.mtia:
+        ignore_keys.add(DispatchKey.MTIA)
+
+        if DispatchKey.MTIA in dispatch_keys:
+            del dispatch_keys[dispatch_keys.index(DispatchKey.MTIA)]
+
+    if options.backend_whitelist:
+        dispatch_keys = [
+            k
+            for k in dispatch_keys
+            if is_generic_dispatch_key(k) or str(k) in options.backend_whitelist
+        ]
+
+    parsed_yaml = parse_native_yaml(native_yaml_path, tags_yaml_path, ignore_keys)
+    valid_tags = _GLOBAL_PARSE_TAGS_YAML_CACHE[tags_yaml_path]
+    native_functions, backend_indices = (
+        parsed_yaml.native_functions,
+        parsed_yaml.backend_indices,
+    )
+
+    grouped_native_functions = get_grouped_native_functions(native_functions)
+
+    structured_native_functions = [
+        g for g in grouped_native_functions if isinstance(g, NativeFunctionsGroup)
+    ]
+    native_functions_with_view_groups = get_grouped_by_view_native_functions(
+        native_functions
+    )
+    view_groups = [
+        g
+        for g in native_functions_with_view_groups
+        if isinstance(g, NativeFunctionsViewGroup)
+    ]
+
+    # NB: It is mandatory to NOT use os.path.join here, as the install directory
+    # will eventually be ingested by cmake, which does not respect Windows style
+    # path slashes.  If you switch this to use os.path.join, you'll get an error
+    # like:
+    #
+    #   Syntax error in cmake code when parsing string
+    #
+    #     C:/Jenkins/workspace/pytorch-builds/pytorch-win-ws2016-cuda9-cudnn7-py3-build/build/aten/src/ATen\core/TensorMethods.h
+    #
+    #   Invalid character escape '\c'.
+    core_install_dir = f"{options.install_dir}/core"
+    Path(core_install_dir).mkdir(parents=True, exist_ok=True)
+    ops_install_dir = f"{options.install_dir}/ops"
+    Path(ops_install_dir).mkdir(parents=True, exist_ok=True)
+
+    aoti_install_dir = f"{options.aoti_install_dir}"
+    Path(aoti_install_dir).mkdir(parents=True, exist_ok=True)
+
+    core_fm = make_file_manager(options=options, install_dir=core_install_dir)
+    cpu_fm = make_file_manager(options=options)
+    cpu_vec_fm = make_file_manager(options=options)
+    cuda_fm = make_file_manager(options=options)
+    ops_fm = make_file_manager(options=options, install_dir=ops_install_dir)
+    aoti_fm = make_file_manager(options=options, install_dir=aoti_install_dir)
+    device_fms = {"cuda": cuda_fm}
+    if options.xpu:
+        device_fms["xpu"] = make_file_manager(options=options)
+
+    static_dispatch_idx: list[BackendIndex] = []
+    if options.static_dispatch_backend:
+        static_dispatch_idx = [
+            backend_indices[DispatchKey.parse(key)]
+            for key in options.static_dispatch_backend
+        ]
+        for key in options.static_dispatch_backend:
+            dp_key = DispatchKey.parse(key)
+            if dp_key not in functions_keys:
+                functions_keys.add(dp_key)
+
+    if "sources" in options.generate:
+        gen_source_files(
+            native_functions=native_functions,
+            grouped_native_functions=grouped_native_functions,
+            structured_native_functions=structured_native_functions,
+            view_groups=view_groups,
+            selector=selector,
+            static_dispatch_idx=static_dispatch_idx,
+            backend_indices=backend_indices,
+            aoti_fm=aoti_fm,
+            core_fm=core_fm,
+            cpu_vec_fm=cpu_vec_fm,
+            cpu_fm=cpu_fm,
+            device_fms=device_fms,
+            dispatch_keys=dispatch_keys,
+            functions_keys=functions_keys,
+            rocm=options.rocm,
+            force_schema_registration=options.force_schema_registration,
+            per_operator_headers=options.per_operator_headers,
+            skip_dispatcher_op_registration=options.skip_dispatcher_op_registration,
+            update_aoti_c_shim=options.update_aoti_c_shim,
+            aoti_backends=aoti_backends,
+            extend_aoti_c_shim=options.extend_aoti_c_shim,
+        )
+
+    if "headers" in options.generate:
+        gen_headers(
+            native_functions=native_functions,
+            valid_tags=valid_tags,
+            grouped_native_functions=grouped_native_functions,
+            structured_native_functions=structured_native_functions,
+            static_dispatch_idx=static_dispatch_idx,
+            selector=selector,
+            backend_indices=backend_indices,
+            core_fm=core_fm,
+            cpu_fm=cpu_fm,
+            device_fms=device_fms,
+            ops_fm=ops_fm,
+            dispatch_keys=dispatch_keys,
+            functions_keys=functions_keys,
+            rocm=options.rocm,
+            per_operator_headers=options.per_operator_headers,
+        )
+
+    if "declarations_yaml" in options.generate:
+        gen_declarations_yaml(native_functions=native_functions, cpu_fm=cpu_fm)
+
+    if options.output_dependencies:
+        depfile_path = Path(options.output_dependencies).resolve()
+        depfile_name = depfile_path.name
+        depfile_stem = depfile_path.stem
+
+        for fm, prefix in [
+            (cpu_fm, ""),
+            (cpu_vec_fm, "cpu_vec_"),
+            (core_fm, "core_"),
+            (ops_fm, "ops_"),
+        ] + [(device_fm, f"{device}_") for device, device_fm in device_fms.items()]:
+            varname = prefix + depfile_stem
+            path = depfile_path.parent / (prefix + depfile_name)
+            fm.write_outputs(varname, str(path))
+
+
+if __name__ == "__main__":
+    main()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen_aoti_c_shim.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen_aoti_c_shim.py
new file mode 100644
index 0000000000000000000000000000000000000000..65161200256e557c3eb3572439013a152e2ecb7b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen_aoti_c_shim.py
@@ -0,0 +1,771 @@
+from __future__ import annotations
+
+import difflib
+import os
+import textwrap
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+from torchgen.aoti.fallback_ops import aten_shimified_ops, inductor_fallback_ops
+from torchgen.api.types import DispatcherSignature
+from torchgen.api.types.signatures import CppSignature, CppSignatureGroup
+from torchgen.context import method_with_native_function
+from torchgen.model import (
+    Argument,
+    BackendIndex,
+    BaseTy,
+    BaseType,
+    DispatchKey,
+    FunctionSchema,
+    is_cuda_dispatch_key,
+    ListType,
+    NativeFunction,
+    NativeFunctionsGroup,
+    OperatorName,
+    OptionalType,
+    Type,
+    Variant,
+)
+from torchgen.utils import FileManager, mapMaybe
+
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+    from typing import Optional
+
+
+base_type_to_c_type = {
+    BaseTy.Tensor: "AtenTensorHandle",
+    BaseTy.bool: "int32_t",  # Use int to pass bool
+    BaseTy.int: "int64_t",
+    BaseTy.SymInt: "int64_t",  # Inductor-generated code won't see a SymInt
+    BaseTy.Scalar: "double",  # Use double to pass both integer and floating point
+    BaseTy.float: "double",  # TODO: how about other floating point types?
+    BaseTy.str: "const char*",
+    BaseTy.DeviceIndex: "int32_t",
+    BaseTy.Layout: "int32_t",  # Represent enum as int
+    BaseTy.MemoryFormat: "int32_t",  # Represent enum as int
+    BaseTy.ScalarType: "int32_t",  # Represent enum as int
+    BaseTy.Generator: "AtenGeneratorHandle",
+}
+
+base_type_to_aten_type = {
+    BaseTy.Tensor: "at::Tensor",
+    BaseTy.bool: "bool",
+    BaseTy.int: "int64_t",
+    BaseTy.SymInt: "c10::SymInt",
+    BaseTy.Scalar: "c10::Scalar",
+    BaseTy.float: "double",
+    BaseTy.str: "::std::string_view",
+    BaseTy.DeviceIndex: "c10::DeviceIndex",
+    BaseTy.Layout: "c10::Layout",
+    BaseTy.MemoryFormat: "c10::MemoryFormat",
+    BaseTy.ScalarType: "c10::ScalarType",
+    BaseTy.Generator: "at::Generator",
+}
+
+base_type_to_callsite_expr = {
+    BaseTy.Tensor: "resolve_tensor_dispatch_flags",
+    BaseTy.bool: "",
+    BaseTy.int: "",
+    BaseTy.SymInt: "",
+    BaseTy.Scalar: "",
+    BaseTy.float: "",
+    BaseTy.str: "",
+    BaseTy.DeviceIndex: "static_cast",
+    BaseTy.Layout: "static_cast",
+    BaseTy.MemoryFormat: "static_cast",
+    BaseTy.ScalarType: "static_cast",
+    BaseTy.Generator: "*generator_handle_to_generator_pointer",
+}
+
+
+# convert args to C types, names in declarations, and expressions in function bodies
+def convert_arg_type_and_name(
+    typ: Type,
+    name: str,
+    is_write: bool = False,
+) -> tuple[list[str], list[str], list[str], list[str]]:
+    if isinstance(typ, BaseType):
+        if typ.name in base_type_to_c_type:
+            if typ.name == BaseTy.Tensor and is_write:
+                # For output tensors, our normal call to resolve_tensor_dispatch_flags
+                # results in an rvalue tensor, which can't be passed to at::Tensor&.
+                # Override this case specifically.
+                callsite_expr = [f"*tensor_handle_to_tensor_pointer({name})"]
+            else:
+                callsite_expr = [
+                    f"{base_type_to_callsite_expr[typ.name]}({name})"
+                    if base_type_to_callsite_expr[typ.name]
+                    else name
+                ]
+
+            return (
+                [base_type_to_c_type[typ.name]],
+                [name],
+                [base_type_to_aten_type[typ.name]],
+                callsite_expr,
+            )
+        elif typ.name == BaseTy.Device:
+            return (
+                ["int32_t", "int32_t"],
+                [name, name + "_index_"],
+                ["c10::Device"],
+                [
+                    f"c10::Device(static_cast({name}), static_cast({name}_index_))"
+                ],
+            )
+        else:
+            # TODO: BaseTy.Dimname, etc.
+            raise NotImplementedError(f"TODO: add support for arg type {repr(typ)}")
+    elif isinstance(typ, OptionalType):
+        c_types, names, aten_types, callsite_exprs = convert_arg_type_and_name(
+            typ.elem, name
+        )
+        j = 0  # index for names
+        new_aten_types = []
+        new_callsite_exprs = []
+        for aten_type in aten_types:
+            # Use pointer to denote optional type
+            c_types[j] = c_types[j] + "*"
+            if aten_type.startswith("c10::ArrayRef<"):
+                # ArrayRef is passed as pointer + size, but no need to add "*" to the size argument
+                new_aten_types.append(f"::std::optional<{aten_type}>")
+                base_type = aten_type[len("c10::ArrayRef<") : -1]
+                new_callsite_exprs.append(
+                    f"pointer_to_optional_list<{base_type}>({names[j]}, {names[j + 1]})"
+                )
+                j += 2
+            elif aten_type == "c10::Device":
+                # Device is passed as device_type + device_index
+                new_aten_types.append("::std::optional")
+                new_callsite_exprs.append(
+                    f"pointer_to_optional_device({names[j]}, {names[j + 1]})"
+                )
+                j += 2
+            elif aten_type == "at::Tensor":
+                new_aten_types.append(f"::std::optional<{aten_type}>")
+                new_callsite_exprs.append(f"resolve_tensor_dispatch_flags({names[j]})")
+                j += 1
+            else:
+                new_aten_types.append(f"::std::optional<{aten_type}>")
+                new_callsite_exprs.append(
+                    f"pointer_to_optional<{aten_type}>({names[j]})"
+                )
+                j += 1
+
+        return (
+            c_types,
+            names,
+            new_aten_types,
+            new_callsite_exprs,
+        )
+    elif isinstance(typ, ListType):
+        # Need to explicitly pass the list as pointer + length
+        c_types, names, aten_types, _ = convert_arg_type_and_name(typ.elem, name)
+        assert len(c_types) == 1, "ListType with unsupported element type " + repr(typ)
+
+        # The list content should never be modified
+        c_types[0] = f"const {c_types[0]}*"
+        c_types.append("int64_t")
+        name = names[0]
+        names.append(name + "_len_")
+
+        atype = aten_types[0]
+        callsite_exprs = []
+        if atype == "bool":
+            # no converter from std::vector to c10::ArrayRef
+            # construct std::array instead
+            assert typ.size is not None
+            callsite_exprs.append(f"pointer_to_list<{typ.size}>({name})")
+        elif atype == "at::Tensor" and not is_write:
+            callsite_exprs.append(
+                f"resolve_tensor_list_dispatch_flags({name}, {name}_len_)"
+            )
+        elif atype == "::std::optional":
+            # convert from std::vector<::std::optional> to c10::List<::std::optional>
+            callsite_exprs.append(
+                f"c10::List<{atype}>(c10::ArrayRef<{atype}>(resolve_tensor_list_dispatch_flags({name}, {name}_len_)))"
+            )
+        else:
+            callsite_exprs.append(f"pointer_to_list<{atype}>({name}, {name}_len_)")
+
+        aten_types = [f"c10::ArrayRef<{t}>" for t in aten_types]
+        return (
+            c_types,
+            names,
+            aten_types,
+            callsite_exprs,
+        )
+    raise NotImplementedError(f"Argument type {repr(typ)} not supported!")
+
+
+def zip_type_and_name(types: list[str], names: list[str]) -> list[str]:
+    return [typ + " " + name for typ, name in zip(types, names)]
+
+
+# Generate argument declarations and callsite expressions
+def gen_arguments(
+    flat_arguments: Sequence[Argument], skipped_args: set[str]
+) -> tuple[list[str], list[str]]:
+    types: list[str] = []
+    new_names: list[str] = []
+    callsite_exprs: list[str] = []
+    for arg in flat_arguments:
+        if arg.name in skipped_args:
+            callsite_exprs.append("std::nullopt")
+            continue
+        new_types, names, _, new_callsite_exprs = convert_arg_type_and_name(
+            arg.type, arg.name, arg.is_write
+        )
+        types.extend(new_types)
+        new_names.extend(names)
+        callsite_exprs.extend(new_callsite_exprs)
+    return zip_type_and_name(types, new_names), callsite_exprs
+
+
+# Return values are passed out as pointer arguments because all the C shim functions
+# are expected to return AOTITorchError.
+# Generate returns as declarations and callsite expressions
+def gen_returns(schema: FunctionSchema) -> tuple[list[str], list[str]]:
+    types = []
+    names = []
+    for idx, ret in enumerate(schema.returns):
+        names.append(f"ret{idx}")
+        if isinstance(ret.type, BaseType) and ret.type.name in base_type_to_c_type:
+            types.append(base_type_to_c_type[ret.type.name] + "*")
+        else:
+            raise NotImplementedError(
+                f"TODO: add support for return type {repr(ret.type)}"
+            )
+
+    def convert_return(typ: BaseType, val: str) -> str:
+        if typ.name == BaseTy.Tensor:
+            return f"new_tensor_handle(std::move({val}))"
+        elif typ.name == BaseTy.SymInt:
+            return f"{val}.expect_int()"
+        elif typ.name == BaseTy.Scalar:
+            return f"{val}.toDouble()"
+        else:
+            return val
+
+    ret_pointer_can_be_null = False
+    unambiguous_name = schema.name.unambiguous_name()
+    for name in (
+        "_functional_sym_constrain_range",
+        "_scaled_dot_product_cudnn_attention",
+        "_scaled_dot_product_efficient_attention_backward",
+        "_scaled_dot_product_efficient_attention",
+        "_scaled_dot_product_flash_attention",
+        "_scaled_dot_product_fused_attention_overrideable",
+        "_thhn_fused_lstm_cell_backward_impl",
+        "convolution_backward",
+        "grid_sampler_2d_backward",
+        "grid_sampler_3d_backward",
+        "linear_backward",
+    ):
+        if name in unambiguous_name:
+            ret_pointer_can_be_null = True
+            break
+
+    callsite_exprs: list[str] = []
+    for idx, ret in enumerate(schema.returns):
+        tmp = "tmp_result" if len(names) == 1 else f"std::get<{idx}>(tmp_result)"
+        assert isinstance(ret.type, BaseType)
+        rval = convert_return(ret.type, tmp)
+        if ret_pointer_can_be_null:
+            callsite_exprs.append(f"if ({names[idx]}) {{ *{names[idx]} = {rval}; }}")
+        else:
+            callsite_exprs.append(f"*{names[idx]} = {rval};")
+
+    return zip_type_and_name(types, names), callsite_exprs
+
+
+# gen.py generates header first and then src, so caching the result here to avoid duplicate work
+declaration_definition_cache: dict[tuple[str, str, str], tuple[str, str]] = {}
+
+
+def gen_declaration_and_definition(
+    schema: FunctionSchema,
+    device: str,
+    backend_call: str,
+    version_info: dict[str, list[str]],
+) -> tuple[str, str]:
+    base_name = schema.name.unambiguous_name()
+
+    global declaration_definition_cache
+    if (base_name, device, backend_call) in declaration_definition_cache:
+        return declaration_definition_cache[(base_name, device, backend_call)]
+
+    # Check the validity of version_info. The format should look like
+    # {"v2" : ["new_arg1"], "v3": ["new_arg2, new_arg3"]}.
+    indexed_version_info: dict[int, list[str]] = {1: []}
+    for ver_str, new_args in sorted(version_info.items()):
+        assert ver_str.startswith("v"), (
+            f"Version number for {base_name} is {ver_str}, not starting with 'v'"
+        )
+        try:
+            ver_id = int(ver_str[1:])
+        except ValueError as e:
+            raise AssertionError(
+                f"Version number for {base_name} is {ver_str}, not a valid integer after 'v'"
+            ) from e
+        assert ver_id not in indexed_version_info, (
+            f"{ver_str} for {base_name} has already been defined"
+        )
+        indexed_version_info[ver_id] = new_args
+
+    declarations: list[str] = []
+    definitions: list[str] = []
+    skipped_args: set[str] = set()
+
+    for ver_id, new_args in sorted(indexed_version_info.items(), reverse=True):
+        # Iterate in the reverse order, so the latest version of an op will get generated first
+        # with all the arguments included, while a set of to-be-trimmed args is carried down
+        # to generate earlier version of the op.
+        func_name = base_name if ver_id == 1 else f"{base_name}_v{ver_id}"
+        if schema.is_out_fn():
+            # out_variant has out arguments in the front, and it's ok to ignore return values
+            # because C shim functions only return AOTITorchError
+            args, callsite_exprs = gen_arguments(
+                [*schema.arguments.out, *schema.arguments.flat_non_out], skipped_args
+            )
+            ret_assignments: list[str] = []
+        else:
+            args, callsite_exprs = gen_arguments(
+                schema.arguments.flat_all, skipped_args
+            )
+            # ignore return values for inplace ops
+            ret_declarations, ret_assignments = (
+                ([], []) if schema.name.name.inplace else gen_returns(schema)
+            )
+            args.extend(ret_declarations)
+
+        declaration = textwrap.dedent(
+            f"AOTITorchError aoti_torch_{device}_{func_name}({', '.join(args)})"
+        )
+
+        tmp_result = "auto tmp_result = " if ret_assignments else ""
+        indent = "\t\t"
+        ret_assignments_str = (
+            "\n".join(indent + r for r in ret_assignments) if ret_assignments else ""
+        )
+        definition = (
+            textwrap.dedent(f"""
+        {declaration} {{
+            AOTI_TORCH_CONVERT_EXCEPTION_TO_ERROR_CODE({{
+                {tmp_result}{backend_call}(
+                    {", ".join(callsite_exprs)}
+                );
+        """)
+            + ret_assignments_str
+            + textwrap.dedent("""
+            });
+        }
+        """)
+        )
+        skipped_args.update(new_args)
+        declarations.append(f"AOTI_TORCH_EXPORT {declaration};")
+        definitions.append(definition)
+
+    declaration_definition_cache[(base_name, device, backend_call)] = (
+        "\n".join(declarations),
+        "\n".join(definitions),
+    )
+    return declaration_definition_cache[(base_name, device, backend_call)]
+
+
+def gen_static_dispatch_backend_call_signature(
+    sig: CppSignature | DispatcherSignature,
+    f: NativeFunction,
+) -> CppSignature:
+    sig = DispatcherSignature.from_schema(f.func)
+    cpp_sigs = CppSignatureGroup.from_native_function(
+        f, method=False, fallback_binding=False
+    )
+    if sig.symint and f.func.has_symint():
+        cpp_sig = cpp_sigs.symint_signature
+    else:
+        cpp_sig = cpp_sigs.signature
+    assert cpp_sig is not None
+    return cpp_sig
+
+
+def gen_static_dispatch_backend_call(
+    f: NativeFunction,
+    backend_index: Optional[BackendIndex] = None,
+) -> str:
+    sig = DispatcherSignature.from_schema(f.func)
+    cpp_sig = gen_static_dispatch_backend_call_signature(sig, f)
+
+    if backend_index is None:
+        # Check if this is a symint function and if the function only has method variants
+        if sig.symint and f.func.has_symint():
+            has_function_variant = Variant.function in f.variants
+
+            if not has_function_variant:
+                # Functions with both function and method variants can use the at::{*}_symint version
+                # (e.g., narrow -> at::narrow_symint), BUT
+                # Method-only functions with symint parameters should use at::symint:: namespace
+                # Remove the _symint suffix since at::symint:: namespace uses the base name
+                # (e.g., new_empty -> at::symint::new_empty)
+                base_name = cpp_sig.name()
+                base_name = base_name.removesuffix("_symint")  # Remove "_symint" suffix
+                return f"at::symint::{base_name}"
+
+        return f"at::{cpp_sig.name()}"
+    else:
+        return f"at::{backend_index.dispatch_key.lower()}::{cpp_sig.name()}"
+
+
+def get_backend_index_for_aoti(
+    func: NativeFunction,
+    func_group_mapping: dict[OperatorName, NativeFunctionsGroup],
+    dispatch_key: Optional[DispatchKey],
+    backend_indices: dict[DispatchKey, BackendIndex],
+    extend_aoti_c_shim: bool,
+) -> BackendIndex | None:
+    backend_index = None
+
+    if dispatch_key is None:
+        return backend_index
+
+    if backend_indices[dispatch_key].has_kernel(func) or (
+        func.structured_delegate is not None
+        and func.structured_delegate in func_group_mapping
+        and backend_indices[dispatch_key].has_kernel(
+            func_group_mapping[func.structured_delegate]
+        )
+    ):
+        backend_index = backend_indices[dispatch_key]
+    else:
+        # for the extend out-of-tree kernels, we don't need to
+        # duplicatly create C shim wrappers for other dispatch keys
+        if extend_aoti_c_shim:
+            return backend_index
+
+        elif backend_indices[DispatchKey.CompositeExplicitAutograd].has_kernel(func):
+            # We need to create C shim wrappers for CompositeExplicitAutograd kernels
+            backend_index = backend_indices[DispatchKey.CompositeExplicitAutograd]
+        elif backend_indices[
+            DispatchKey.CompositeExplicitAutogradNonFunctional
+        ].has_kernel(func):
+            # We need to create C shim wrappers for CompositeExplicitAutogradNonFunctional kernels
+            backend_index = backend_indices[
+                DispatchKey.CompositeExplicitAutogradNonFunctional
+            ]
+        elif backend_indices[DispatchKey.CompositeImplicitAutograd].has_kernel(func):
+            backend_index = backend_indices[DispatchKey.CompositeImplicitAutograd]
+
+    return backend_index
+
+
+def get_header_for_aoti(
+    func: NativeFunction,
+    func_group_mapping: dict[OperatorName, NativeFunctionsGroup],
+    dispatch_key: Optional[DispatchKey],
+    backend_indices: dict[DispatchKey, BackendIndex],
+    extend_aoti_c_shim: bool,
+) -> str | None:
+    backend_index = get_backend_index_for_aoti(
+        func, func_group_mapping, dispatch_key, backend_indices, extend_aoti_c_shim
+    )
+    if backend_index is None:
+        if dispatch_key is None:
+            return f"#include "
+        return None
+
+    return f"#include "
+
+
+def get_fallback_op_name(func: NativeFunction) -> str:
+    return (
+        f"{func.namespace}.{func.func.name.name}.{func.func.name.overload_name}"
+        if func.func.name.overload_name
+        else f"{func.namespace}.{func.func.name.name}.default"
+    )
+
+
+def gen_c_shim(
+    func: NativeFunction,
+    version_info: dict[str, list[str]],
+    func_group_mapping: dict[OperatorName, NativeFunctionsGroup],
+    dispatch_key: Optional[DispatchKey],
+    backend_indices: dict[DispatchKey, BackendIndex],
+    header: bool,
+    extend_aoti_c_shim: bool,
+) -> str | None:
+    backend_index = get_backend_index_for_aoti(
+        func, func_group_mapping, dispatch_key, backend_indices, extend_aoti_c_shim
+    )
+    if backend_index is None and dispatch_key is not None:
+        return None
+
+    schema = func.func
+    device = "aten" if dispatch_key is None else dispatch_key.lower()
+    backend_call = gen_static_dispatch_backend_call(
+        func,
+        backend_index,
+    )
+
+    try:
+        if header:
+            declaration, _ = gen_declaration_and_definition(
+                schema, device, backend_call, version_info
+            )
+            return declaration
+        else:
+            _, definition = gen_declaration_and_definition(
+                schema, device, backend_call, version_info
+            )
+            return definition
+
+    except NotImplementedError:
+        return None
+
+
+@dataclass(frozen=True)
+class ShimGenerator:
+    inductor_fallback_ops: dict[str, dict[str, list[str]]]
+    func_group_mapping: dict[OperatorName, NativeFunctionsGroup]
+    dispatch_key: Optional[DispatchKey]
+    backend_indices: dict[DispatchKey, BackendIndex]
+    header: bool  # True to generate .h and False to generate .cpp
+    extend_aoti_c_shim: bool
+
+    @method_with_native_function
+    def __call__(
+        self,
+        func: NativeFunction,
+    ) -> str | None:
+        version_info = self.inductor_fallback_ops[get_fallback_op_name(func)]
+        result = gen_c_shim(
+            func,
+            version_info,
+            self.func_group_mapping,
+            self.dispatch_key,
+            self.backend_indices,
+            self.header,
+            self.extend_aoti_c_shim,
+        )
+        return result
+
+
+def gen_aoti_c_shim(
+    native_functions: Sequence[NativeFunction],
+    inductor_fallback_ops: dict[str, dict[str, list[str]]],
+    func_group_mapping: dict[OperatorName, NativeFunctionsGroup],
+    dispatch_key: Optional[DispatchKey],
+    backend_indices: dict[DispatchKey, BackendIndex],
+    header: bool,
+    extend_aoti_c_shim: bool,
+    includes: str = "",
+) -> str:
+    body = "\n".join(
+        list(
+            mapMaybe(
+                ShimGenerator(
+                    inductor_fallback_ops,
+                    func_group_mapping,
+                    dispatch_key,
+                    backend_indices,
+                    header,
+                    extend_aoti_c_shim,
+                ),
+                native_functions,
+            )
+        )
+    )
+    device = "aten" if dispatch_key is None else dispatch_key.lower()
+    include_device_functions = (
+        "#include "
+        if dispatch_key is None
+        else f"#include "
+    )
+    aten_warning = (
+        (
+            "\n\n// This file corresponds to the aten_shimified_ops list in torchgen/aoti/fallback_ops.py\n"
+        )
+        if dispatch_key is None
+        else ""
+    )
+    warning = """
+
+// WARNING: THIS FILE IS AUTOGENERATED BY torchgen. DO NOT MODIFY BY HAND.
+// See https://github.com/pytorch/pytorch/blob/7e86a7c0155295539996e0cf422883571126073e/torchgen/gen.py#L2424-L2436 for details"""
+
+    if header:
+        return (
+            warning
+            + aten_warning
+            + textwrap.dedent("""
+
+            #pragma once
+
+            #include 
+
+            #ifdef __cplusplus
+            extern "C" {
+            #endif
+
+            """)
+            + body
+            + textwrap.dedent("""
+
+            #ifdef __cplusplus
+            } // extern "C"
+            #endif
+            """)
+        )
+    else:
+        return (
+            warning
+            + aten_warning
+            + textwrap.dedent(f"""
+
+            #include 
+            #include 
+
+            #ifndef AT_PER_OPERATOR_HEADERS
+            {include_device_functions}
+            #include 
+            #include 
+            #include 
+            #else
+            """)
+            + includes
+            + textwrap.dedent("""
+            #endif // AT_PER_OPERATOR_HEADERS
+
+            using namespace torch::aot_inductor;
+
+            """)
+            + body
+        )
+
+
+def gen_aoti_c_shim_files(
+    aoti_fm: FileManager,
+    aoti_backends: set[Optional[DispatchKey]],
+    native_functions: Sequence[NativeFunction],
+    backend_indices: dict[DispatchKey, BackendIndex],
+    structured_native_functions: Sequence[NativeFunctionsGroup],
+    extra_cuda_headers: str,
+    extend_aoti_c_shim: bool,
+    update_aoti_c_shim: bool,
+) -> None:
+    structured_func_group_dict = {}
+    for func_group in structured_native_functions:
+        for func in func_group.functions():
+            if func.structured_delegate is not None:
+                structured_func_group_dict[func.structured_delegate] = func_group
+                break
+
+    for dispatch_key in aoti_backends:
+        # Use aten_shimified_ops for the aten backend, inductor_fallback_ops for others
+        fallback_ops_dict = (
+            aten_shimified_ops if dispatch_key is None else inductor_fallback_ops
+        )
+        fallbacks = {}
+        for func in native_functions:
+            op_name = get_fallback_op_name(func)
+            if op_name in fallback_ops_dict:
+                fallbacks[op_name] = func
+        fallback_native_functions = tuple(
+            value for _, value in sorted(fallbacks.items())
+        )
+
+        # Use "aten" as the device name when dispatch_key is Generic
+        device_name = "aten" if dispatch_key is None else dispatch_key.lower()
+
+        # header files were checked in for ABI-compatiblilty checking
+        header_file_name = f"c_shim_{device_name}.h"
+        new_header = gen_aoti_c_shim(
+            fallback_native_functions,
+            fallback_ops_dict,
+            structured_func_group_dict,
+            dispatch_key,
+            backend_indices,
+            header=True,
+            extend_aoti_c_shim=extend_aoti_c_shim,
+            includes="",
+        )
+        if update_aoti_c_shim:
+            aoti_fm.write(
+                header_file_name,
+                lambda: new_header,
+            )
+        else:
+            try:
+                with open(
+                    os.path.join(aoti_fm.install_dir, header_file_name)
+                ) as old_file:
+                    old_header = old_file.read()
+
+                    if old_header != new_header:
+                        diff = "\n".join(
+                            difflib.unified_diff(
+                                old_header.splitlines(),
+                                new_header.splitlines(),
+                                fromfile="expected",
+                                tofile="actual",
+                                lineterm="",
+                            )
+                        )
+
+                        raise RuntimeError(f"""
+The generated AOTInductor C shim header files have unexpectedly changed. This
+indicates an AOTInductor fallback operator ABI backward compatibility breakage!!!
+Only in a limited number of situations, this is allowed:
+
+1. You added a fallback op to the inductor_fallback_ops list in torchgen/aoti/fallback_ops.py.
+If that's the case, run `python torchgen/gen.py --update-aoti-c-shim` to add a new entry to
+existing C shim header files.
+
+2. You added a new default argument to an existing fallback op. This is clearly a BC breaking
+change in the AOTInductor land. You need to annotate the new default argument in
+torchgen/aoti/fallback_ops.py, and then run `python torchgen/gen.py --update-aoti-c-shim` to
+update the C shim header files by creating different versions of the fallback op. See
+https://github.com/pytorch/pytorch/pull/154848 as an example.
+
+{diff}
+                    """)
+            except FileNotFoundError:
+                print(
+                    f"{os.path.join(aoti_fm.install_dir, header_file_name)} not found"
+                )
+
+        # cpp files are always generated on-the-fly
+        def headers_for_aoti() -> str:
+            headers = []
+            for func in fallback_native_functions:
+                header = get_header_for_aoti(
+                    func,
+                    structured_func_group_dict,
+                    dispatch_key,
+                    backend_indices,
+                    extend_aoti_c_shim=extend_aoti_c_shim,
+                )
+                if header is not None:
+                    headers.append(header)
+            return "\n".join(sorted(set(headers)))
+
+        extra_headers = (
+            extra_cuda_headers
+            if dispatch_key is not None and is_cuda_dispatch_key(dispatch_key)
+            else ""
+        )
+
+        aoti_fm.write(
+            f"c_shim_{device_name}.cpp",
+            lambda: gen_aoti_c_shim(
+                fallback_native_functions,
+                fallback_ops_dict,
+                structured_func_group_dict,
+                dispatch_key,
+                backend_indices,
+                header=False,
+                extend_aoti_c_shim=extend_aoti_c_shim,
+                includes=headers_for_aoti() + "\n" + extra_headers,
+            ),
+        )
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen_backend_stubs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen_backend_stubs.py
new file mode 100644
index 0000000000000000000000000000000000000000..07097010f8f28f8eaba72064d2fe0338510ad84c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen_backend_stubs.py
@@ -0,0 +1,615 @@
+from __future__ import annotations
+
+import argparse
+import os
+import re
+from collections import Counter, defaultdict, namedtuple
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+import yaml
+
+import torchgen.api.dispatcher as dispatcher
+import torchgen.dest as dest
+from torchgen.api.types import DispatcherSignature
+from torchgen.code_template import CodeTemplate
+from torchgen.context import native_function_manager
+from torchgen.gen import get_grouped_native_functions, parse_native_yaml
+from torchgen.model import (
+    BackendIndex,
+    BackendMetadata,
+    DispatchKey,
+    NativeFunction,
+    NativeFunctionsGroup,
+    OperatorName,
+)
+from torchgen.selective_build.selector import SelectiveBuilder
+from torchgen.utils import concatMap, context, FileManager, NamespaceHelper, Target
+from torchgen.yaml_utils import YamlLoader
+
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+
+
+# Parses the external backend's yaml, and adds a new BackendIndex for the backend's dispatch key.
+# Returns a Tuple of (backend_key, autograd_key, cpp_namespace, updated BackendIndex mapping)
+ParsedExternalYaml = namedtuple(
+    "ParsedExternalYaml",
+    ["backend_key", "autograd_key", "class_name", "cpp_namespace", "backend_indices"],
+)
+
+
+def parse_backend_yaml(
+    backend_yaml_path: str,
+    grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
+    backend_indices: dict[DispatchKey, BackendIndex],
+) -> ParsedExternalYaml:
+    native_functions_map: dict[OperatorName, NativeFunction] = {
+        f.func.name: f
+        for f in concatMap(
+            lambda f: [f] if isinstance(f, NativeFunction) else list(f.functions()),
+            grouped_native_functions,
+        )
+    }
+
+    with open(backend_yaml_path) as f:
+        yaml_values = yaml.load(f, Loader=YamlLoader)
+    assert isinstance(yaml_values, dict)
+
+    valid_keys = [
+        "backend",
+        "class_name",
+        "cpp_namespace",
+        "extra_headers",
+        "supported",
+        "autograd",
+        "full_codegen",
+        "non_native",
+        "ir_gen",
+        "symint",
+    ]
+
+    backend = yaml_values.pop("backend", None)
+    assert backend is not None, 'You must provide a value for "backend"'
+
+    class_name = yaml_values.pop("class_name", None)
+
+    cpp_namespace = yaml_values.pop("cpp_namespace", None)
+    assert cpp_namespace is not None, 'You must provide a value for "cpp_namespace"'
+
+    # Mostly just defaulting to false to stick with LazyTensor convention.
+    use_out_as_primary = yaml_values.pop("use_out_as_primary", False)
+    assert isinstance(use_out_as_primary, bool), (
+        f"You must provide either True or False for use_out_as_primary. Provided: {use_out_as_primary}"
+    )
+
+    use_device_guard = yaml_values.pop("device_guard", False)
+    assert isinstance(use_device_guard, bool), (
+        f"You must provide either True or False for device_guard. Provided: {use_device_guard}"
+    )
+
+    supported = yaml_values.pop("supported", [])
+    if supported is None:
+        supported = []  # Allow an empty list of supported ops
+    assert isinstance(supported, list), (
+        f'expected "supported" to be a list, but got: {supported} (of type {type(supported)})'
+    )
+
+    symint = yaml_values.pop("symint", [])
+    if symint is None:
+        symint = []  # Allow an empty list of symint ops
+    assert isinstance(symint, list), (
+        f'expected "symint" to be a list, but got: {supported} (of type {type(supported)})'
+    )
+    symint_set = set(symint)
+
+    supported_autograd = yaml_values.pop("autograd", [])
+    assert isinstance(supported_autograd, list), (
+        f'expected "autograd" to be a list, but got: {supported_autograd}'
+    )
+
+    # full_codegen is ignored by parse_backend_yaml, and re-parsed in gen_lazy_tensor.py
+    full_codegen = yaml_values.pop("full_codegen", [])
+    supported.extend(full_codegen)
+
+    # non_native is ignored by parse_backend_yaml, and re-parsed in gen_lazy_tensor.py
+    yaml_values.pop("non_native", {})
+
+    # ir_gen is ignored by parse_backend_yaml, and re-parsed in gen_lazy_tensor.py
+    yaml_values.pop("ir_gen", {})
+
+    assert len(yaml_values.keys()) == 0, (
+        f"{backend_yaml_path} contains unexpected keys: {', '.join(yaml_values.keys())}. "
+        f"Only the following keys are supported: {', '.join(valid_keys)}"
+    )
+
+    def create_backend_index(
+        backend_ops: list[str],
+        symint_ops: set[str],
+        dispatch_key: DispatchKey,
+        *,
+        use_out_as_primary: bool,
+        use_device_guard: bool,
+    ) -> BackendIndex:
+        metadata: dict[OperatorName, BackendMetadata] = {}
+        for op in backend_ops:
+            op_name = OperatorName.parse(op)
+            assert op_name in native_functions_map, (
+                f"Found an invalid operator name: {op_name}"
+            )
+            # See Note [External Backends Follow Dispatcher API]
+            kernel_name = dispatcher.name(native_functions_map[op_name].func)
+            if op in symint_ops:
+                kernel_name += "_symint"
+            # TODO: allow structured external backends later.
+            m = BackendMetadata(
+                kernel=kernel_name, structured=False, cpp_namespace=cpp_namespace
+            )
+            metadata[op_name] = m
+        return BackendIndex(
+            dispatch_key=dispatch_key,
+            use_out_as_primary=use_out_as_primary,
+            external=True,
+            device_guard=use_device_guard,
+            index=metadata,
+        )
+
+    backend_key: DispatchKey | None = None
+    if len(supported) > 0:
+        with context(
+            lambda: f'The provided value for "backend" must be a valid DispatchKey, but got {backend}.'
+        ):
+            backend_key = DispatchKey.parse(backend)
+
+        backend_idx = create_backend_index(
+            supported,
+            symint_set,
+            backend_key,
+            use_out_as_primary=use_out_as_primary,
+            use_device_guard=use_device_guard,
+        )
+        assert backend_key not in backend_indices
+        backend_indices[backend_key] = backend_idx
+
+    autograd_key: DispatchKey | None = None
+    if len(supported_autograd) > 0:
+        with context(
+            lambda: f'The "autograd" key was specified, which indicates that you would like to override \
+the behavior of autograd for some operators on your backend. However "Autograd{backend}" is not a valid DispatchKey.'
+        ):
+            autograd_key = DispatchKey.parse(f"Autograd{backend}")
+
+        autograd_idx = create_backend_index(
+            supported_autograd,
+            symint_set,
+            autograd_key,
+            use_out_as_primary=use_out_as_primary,
+            use_device_guard=use_device_guard,
+        )
+        assert autograd_key not in backend_indices
+        backend_indices[autograd_key] = autograd_idx
+
+    for g in grouped_native_functions:
+        if isinstance(g, NativeFunction):
+            forward_kernels = (
+                []
+                if backend_key is None
+                else [
+                    m
+                    for m in [backend_indices[backend_key].get_kernel(g)]
+                    if m is not None
+                ]
+            )
+            backward_kernels = (
+                []
+                if autograd_key is None
+                else [
+                    m
+                    for m in [backend_indices[autograd_key].get_kernel(g)]
+                    if m is not None
+                ]
+            )
+        else:
+            forward_kernels = (
+                []
+                if backend_key is None
+                else [
+                    m
+                    for m in [
+                        backend_indices[backend_key].get_kernel(f)
+                        for f in g.functions()
+                    ]
+                    if m is not None
+                ]
+            )
+            backward_kernels = (
+                []
+                if autograd_key is None
+                else [
+                    m
+                    for m in [
+                        backend_indices[autograd_key].get_kernel(f)
+                        for f in g.functions()
+                    ]
+                    if m is not None
+                ]
+            )
+
+        forward_kernels = [f for f in forward_kernels if f is not None]
+        backward_kernels = [f for f in backward_kernels if f is not None]
+        assert len(forward_kernels) == 0 or len(backward_kernels) == 0, (
+            f'Currently, all variants of an op must either be registered to a backend key, or to a backend\'s \
+autograd key. They cannot be mix and matched. If this is something you need, feel free to create an issue! \
+{forward_kernels[0].kernel} is listed under "supported", but {backward_kernels[0].kernel} is listed under "autograd".'
+        )
+
+    return ParsedExternalYaml(
+        backend_key, autograd_key, class_name, cpp_namespace, backend_indices
+    )
+
+
+def error_on_missing_kernels(
+    native_functions: Sequence[NativeFunction],
+    backend_indices: dict[DispatchKey, BackendIndex],
+    backend_key: DispatchKey,
+    autograd_key: DispatchKey | None,
+    class_name: str,
+    kernel_defn_file_path: str,
+    full_codegen: list[OperatorName] | None = None,
+) -> None:
+    try:
+        with open(kernel_defn_file_path) as f:
+            backend_defns = f.read()
+    except OSError as e:
+        raise AssertionError(
+            f"Unable to read from the specified impl_path file: {kernel_defn_file_path}"
+        ) from e
+
+    if full_codegen is None:
+        full_codegen = []
+
+    indices = [backend_indices[backend_key].index] + (
+        [] if autograd_key is None else [backend_indices[autograd_key].index]
+    )
+    # Quick mapping from each OperatorName used by the external backend
+    # to its backend kernel name
+    expected_backend_op_names: dict[OperatorName, str] = dict(
+        list(
+            concatMap(
+                lambda index: [
+                    (op_name, metadata.kernel) for op_name, metadata in index.items()
+                ],
+                indices,
+            )
+        )
+    )
+    expected_backend_native_funcs: list[NativeFunction] = [
+        f
+        for f in native_functions
+        if f.func.name in expected_backend_op_names.keys()
+        and f.func.name not in full_codegen
+    ]
+    expected_backend_kernel_name_counts: dict[str, list[NativeFunction]] = defaultdict(
+        list
+    )
+    for native_f in expected_backend_native_funcs:
+        expected_backend_kernel_name_counts[
+            expected_backend_op_names[native_f.func.name]
+        ].append(native_f)
+
+    # This just looks for lines containing "foo(", and assumes that the kernel foo has been implemented.
+    # It might cause false negatives (we won't catch all cases), but that's ok - if we catch a missing kernel
+    # here, then we get a nicer error message. If we miss it, you get a linker error.
+    kernel_defn_regex = rf"(.*){class_name}::\s*([\w\d]*)\("
+    actual_backend_kernel_name_counts = Counter(
+        # A bit unwieldy (this could probably be moved into regex),
+        # but we don't want to include kernel names that come from function calls,
+        # like "return torch_xla::XLANativeFunctions::empty_strided_symint(...)".
+        # Easy check is to ignore any lines with colons before the class name.
+        [
+            y
+            for (x, y) in re.findall(kernel_defn_regex, backend_defns)
+            if not x.endswith(":")
+        ]
+    )
+
+    missing_kernels_err_msg = ""
+    for expected_name, funcs in expected_backend_kernel_name_counts.items():
+        expected_overload_count = len(funcs)
+        actual_overload_count = actual_backend_kernel_name_counts[expected_name]
+        if expected_overload_count != actual_overload_count:
+
+            def create_decl(f: NativeFunction) -> str:
+                with native_function_manager(f):
+                    return DispatcherSignature.from_schema(f.func).decl()
+
+            expected_schemas_str = "\n".join([create_decl(f) for f in funcs])
+            missing_kernels_err_msg += f"""
+{class_name} is missing a kernel definition for {expected_name}. We found {actual_overload_count} kernel(s) with that name,
+but expected {expected_overload_count} kernel(s). The expected function schemas for the missing operator are:
+{expected_schemas_str}
+
+"""
+    assert missing_kernels_err_msg == "", missing_kernels_err_msg
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(description="Generate backend stub files")
+    parser.add_argument(
+        "-s",
+        "--source-yaml",
+        "--source_yaml",
+        help="path to source yaml file containing operator external definitions",
+    )
+    parser.add_argument("-o", "--output-dir", "--output_dir", help="output directory")
+    parser.add_argument(
+        "--dry-run", "--dry_run", type=bool, default=False, help="output directory"
+    )
+    parser.add_argument(
+        "--impl-path",
+        "--impl_path",
+        type=str,
+        default=None,
+        help="path to the source C++ file containing kernel definitions",
+    )
+    options = parser.parse_args()
+
+    run(options.source_yaml, options.output_dir, options.dry_run, options.impl_path)
+
+
+def gen_dispatchkey_nativefunc_headers(
+    fm: FileManager,
+    class_name: str,
+    cpp_namespace: str,
+    backend_indices: dict[DispatchKey, BackendIndex],
+    grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
+    backend_dispatch_key: DispatchKey,
+    autograd_dispatch_key: DispatchKey | None,
+    backend_name: str = "",
+) -> None:
+    assert class_name is not None
+    generated_comment = (
+        "Autogenerated file by gen_backend_stubs.py. Do not edit directly!"
+    )
+
+    # Convert to a set first to remove duplicate kernel names.
+    # Backends are allowed to repeat kernel names; only generate the declaration once!
+    # Sort for deterministic output.
+    backend_declarations = sorted(
+        set(
+            concatMap(
+                lambda f: dest.compute_native_function_declaration(
+                    f, backend_indices[backend_dispatch_key]
+                ),
+                grouped_native_functions,
+            )
+        )
+    )
+    autograd_declarations = sorted(
+        set(
+            concatMap(
+                lambda f: []
+                if autograd_dispatch_key is None
+                else dest.compute_native_function_declaration(
+                    f, backend_indices[autograd_dispatch_key]
+                ),
+                grouped_native_functions,
+            )
+        )
+    )
+
+    ns_helper = NamespaceHelper(cpp_namespace)
+    fm.write_with_template(
+        f"{backend_dispatch_key}NativeFunctions.h",
+        "DispatchKeyNativeFunctions.h",
+        lambda: {
+            "generated_comment": generated_comment,
+            "namespace_prologue": ns_helper.prologue,
+            "class_name": class_name,
+            "namespace_epilogue": ns_helper.epilogue,
+            "dispatch_declarations": backend_declarations + autograd_declarations,
+            "BackendName": backend_name,
+            "DispatchKey": backend_dispatch_key,
+        },
+    )
+
+
+def gen_dispatcher_registrations(
+    fm: FileManager,
+    output_dir: str,
+    class_name: str,
+    backend_indices: dict[DispatchKey, BackendIndex],
+    grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
+    backend_dispatch_key: DispatchKey,
+    dispatch_key: DispatchKey,
+    selector: SelectiveBuilder,
+    # build_in_tree is true for lazy TS backend and affects include paths, not used for external backends
+    build_in_tree: bool = False,
+    per_operator_headers: bool = False,
+    backend_name: str = "",
+    eager_registration: bool = True,
+) -> None:
+    headers = [
+        f"{output_dir}/{backend_dispatch_key}NativeFunctions.h",
+    ]
+    if build_in_tree:
+        external_backend_headers_str = "\n".join(f"#include <{h}>" for h in headers)
+    else:
+        external_backend_headers_str = "\n".join(f'#include "{h}"' for h in headers)
+
+    assert class_name is not None
+    backend_index = backend_indices[dispatch_key]
+
+    dispatch_registrations_body = list(
+        concatMap(
+            dest.RegisterDispatchKey(
+                backend_index,
+                Target.REGISTRATION,
+                selector,
+                rocm=False,
+                symint=True,
+                class_method_name=f"{class_name}",
+                skip_dispatcher_op_registration=False,
+            ),
+            grouped_native_functions,
+        )
+    )
+    newline = "\n"
+    ns_helper = NamespaceHelper(namespace_str="at")
+    deferred_dispatch_registrations = ""
+    static_init_dispatch_registrations = ""
+    if eager_registration:
+        static_template = CodeTemplate(
+            """\
+TORCH_LIBRARY_IMPL(aten, $dispatch_key, m) {
+    $dispatch_registrations_body
+}"""
+        )
+        static_init_dispatch_registrations = static_template.substitute(
+            dispatch_key=dispatch_key,
+            dispatch_registrations_body=dispatch_registrations_body,
+        )
+    else:
+        deferred_template = CodeTemplate(
+            """\
+TORCH_API void Register${backend_name}${dispatch_key}NativeFunctions();
+TORCH_API void Register${backend_name}${dispatch_key}NativeFunctions() {
+    static auto m = MAKE_TORCH_LIBRARY_IMPL(aten, $dispatch_key);
+    $dispatch_registrations_body
+}"""
+        )
+        deferred_dispatch_registrations = deferred_template.substitute(
+            backend_name=backend_name,
+            dispatch_key=dispatch_key,
+            dispatch_registrations_body=dispatch_registrations_body,
+        )
+
+    fm.write_with_template(
+        f"Register{dispatch_key}.cpp",
+        "RegisterDispatchKey.cpp",
+        lambda: {
+            "extra_cuda_headers": "",
+            "external_backend_headers": external_backend_headers_str,
+            "ops_headers": "#include "
+            if not per_operator_headers
+            else "",
+            "DispatchKey": dispatch_key,
+            "dispatch_namespace": dispatch_key.lower(),
+            "dispatch_headers": dest.gen_registration_headers(
+                backend_index, per_operator_headers=per_operator_headers, rocm=False
+            ),
+            "dispatch_helpers": dest.gen_registration_helpers(backend_index),
+            "dispatch_definitions": fm.substitute_with_template(
+                "RegisterDispatchDefinitions.ini",
+                lambda: {
+                    "ns_prologue": ns_helper.prologue,
+                    "ns_epilogue": ns_helper.epilogue,
+                    "static_init_dispatch_registrations": static_init_dispatch_registrations,
+                    "deferred_dispatch_registrations": deferred_dispatch_registrations,
+                    "dispatch_namespace": dispatch_key.lower(),
+                    "dispatch_namespaced_definitions": "",
+                    "dispatch_anonymous_definitions": list(
+                        concatMap(
+                            dest.RegisterDispatchKey(
+                                backend_index,
+                                Target.ANONYMOUS_DEFINITION,
+                                selector,
+                                rocm=False,
+                                symint=True,
+                                class_method_name=f"{class_name}",
+                                skip_dispatcher_op_registration=False,
+                            ),
+                            grouped_native_functions,
+                        )
+                    ),
+                },
+            ).split(newline),
+        },
+    )
+
+
+def run(
+    source_yaml: str, output_dir: str, dry_run: bool, impl_path: str | None = None
+) -> None:
+    # Assumes that this file lives at PYTORCH_ROOT/torchgen/gen_backend_stubs.py
+    pytorch_root = Path(__file__).absolute().parent.parent
+    template_dir = os.path.join(pytorch_root, "aten/src/ATen/templates")
+
+    def make_file_manager(install_dir: str) -> FileManager:
+        return FileManager(
+            install_dir=install_dir, template_dir=template_dir, dry_run=dry_run
+        )
+
+    fm = make_file_manager(output_dir)
+
+    native_yaml_path = os.path.join(
+        pytorch_root, "aten/src/ATen/native/native_functions.yaml"
+    )
+    tags_yaml_path = os.path.join(pytorch_root, "aten/src/ATen/native/tags.yaml")
+    parsed_yaml = parse_native_yaml(native_yaml_path, tags_yaml_path)
+    native_functions, backend_indices = (
+        parsed_yaml.native_functions,
+        parsed_yaml.backend_indices,
+    )
+    grouped_native_functions = get_grouped_native_functions(native_functions)
+    parsed_backend_yaml = parse_backend_yaml(
+        source_yaml, grouped_native_functions, backend_indices
+    )
+    backend_key = parsed_backend_yaml.backend_key
+    autograd_key = parsed_backend_yaml.autograd_key
+    cpp_namespace = parsed_backend_yaml.cpp_namespace
+    class_name = parsed_backend_yaml.class_name
+    backend_indices = parsed_backend_yaml.backend_indices
+
+    selector = SelectiveBuilder.get_nop_selector()
+
+    if backend_key is None:
+        # This could be useful if a backend wants to quickly set up a noop yaml file but doesn't have any kernels ready yet.
+        return
+
+    if class_name is None:
+        # class_name is an optional argument to backend yaml file.
+        # if specified it allows an external backend to override
+        # the name of the class that all generated kernel definitions live under.
+        # if not specified, its value is given as native_function_class_name.
+        class_name = backend_indices[backend_key].native_function_class_name()
+    assert class_name is not None
+
+    if impl_path is not None:
+        error_on_missing_kernels(
+            native_functions,
+            backend_indices,
+            backend_key,
+            autograd_key,
+            class_name,
+            impl_path,
+        )
+
+    gen_dispatchkey_nativefunc_headers(
+        fm,
+        class_name,
+        cpp_namespace,
+        backend_indices,
+        grouped_native_functions,
+        backend_key,
+        autograd_key,
+    )
+
+    for dispatch_key in (
+        [backend_key] if autograd_key is None else [backend_key, autograd_key]
+    ):
+        gen_dispatcher_registrations(
+            fm,
+            output_dir,
+            class_name,
+            backend_indices,
+            grouped_native_functions,
+            backend_key,
+            dispatch_key,
+            selector,
+        )
+
+
+if __name__ == "__main__":
+    main()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen_functionalization_type.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen_functionalization_type.py
new file mode 100644
index 0000000000000000000000000000000000000000..f47985837eac666ce9a27fd6addbda5b6f914912
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen_functionalization_type.py
@@ -0,0 +1,1148 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Callable, Optional, TYPE_CHECKING
+
+from torchgen.api import cpp, dispatcher, functionalization
+from torchgen.api.translate import translate
+from torchgen.api.types import (
+    BaseCType,
+    Binding,
+    CType,
+    DispatcherSignature,
+    iTensorListRefT,
+    NativeSignature,
+    OptionalCType,
+    optionalSymIntArrayRefT,
+    symIntArrayRefT,
+    SymIntT,
+    tensorListT,
+    tensorT,
+    VectorCType,
+    ViewInverseSignature,
+)
+from torchgen.context import (
+    method_with_native_function,
+    native_function_manager,
+    with_native_function,
+    with_native_function_and,
+)
+from torchgen.model import (
+    Argument,
+    BackendIndex,
+    BaseTy,
+    BaseType,
+    FunctionSchema,
+    ListType,
+    NativeFunction,
+    NativeFunctionsGroup,
+    NativeFunctionsViewGroup,
+    Return,
+    SchemaKind,
+    SelfArgument,
+    TensorOptionsArguments,
+)
+from torchgen.native_function_generation import (
+    INPLACE_OPS_THAT_DONT_GET_GROUPED_PROPERLY,
+    MUTABLE_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT,
+    OUT_OPS_THAT_DONT_GET_GROUPED_PROPERLY,
+)
+from torchgen.utils import concatMap, dataclass_repr, FileManager
+
+
+if TYPE_CHECKING:
+    from torchgen.selective_build.selector import SelectiveBuilder
+
+
+# Note: [Mutable Ops Not Using Functionalization]
+# Ops in this list currently do not work with functionalization and should be fixed.
+MUTABLE_OPS_NOT_USING_FUNCTIONALIZATION = (
+    OUT_OPS_THAT_DONT_GET_GROUPED_PROPERLY
+    + MUTABLE_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT
+    + INPLACE_OPS_THAT_DONT_GET_GROUPED_PROPERLY
+    + [
+        # It will be BC-breaking, but we should fix their schemas.
+        # should be inplace?
+        "record_stream",
+        # See Note [resize_ in Functionalization]
+        "resize_",
+        "resize_as_",
+        # This function is used as for testing purposes only.
+        "_fill_mem_eff_dropout_mask_",
+    ]
+)
+
+# This file contains codegen that relates to the functionalization pass.
+# It includes:
+# - gen_functionalization_definition
+#     Generates dispatcher kernel definitions for the functionalization pass.
+# - gen_functionalization_registration
+#     Generates dispatcher kernel registrations for the functionalization pass.
+# - gen_functionalization_view_inverse_declaration
+#     Generates a declaration for an "inverse view", for every view op
+#     that is needed in functionalization. We manually implement their definitions.
+# - gen_composite_view_copy_kernel
+#     Generates view_copy() composite kernels for all view_copy operators.
+
+
+# Generates the body of the default composite C++ kernel for a {view}_copy NativeFunction
+# See Note [view_copy NativeFunctions]
+@dataclass(frozen=True)
+class GenCompositeViewCopyKernel:
+    backend_index: BackendIndex
+
+    @method_with_native_function
+    def __call__(self, g: NativeFunctionsViewGroup) -> str | None:
+        if g.view_copy is None:
+            return None
+        elif g.view_copy.func.name.name.base != f"{g.view.func.name.name}_copy":
+            # If the view_copy doesn't match the standard naming scheme of _copy,
+            # assume it already exists and doesn't need to be generated.
+            # Example: slice_inverse() with the copy variant named slice_scatter()
+            # instead of slice_inverse_copy()
+            return None
+
+        metadata = self.backend_index.get_kernel(g.view_copy)
+        assert metadata is not None
+
+        # We can make view_copy work in more cases by using reshape()
+        # when a normal view call would ordinarily fail.
+        # This also makes LTC more efficient, because they don't need to include
+        # clone() calls in their graph (which is normally needed by reshape).
+        if str(g.view_copy.func.name) == "view_copy":
+            assert metadata.kernel == "view_copy_symint"
+            return """\
+at::Tensor view_copy_symint(const at::Tensor & self, at::SymIntArrayRef size) {
+  c10::SymDimVector shape = infer_size_dv(size, self.sym_numel());
+  if (!at::detail::computeStride(self.sym_sizes(), self.sym_strides(), shape).has_value()) {
+    return self.reshape_symint(size);
+  } else {
+    auto output = at::_ops::view::call(self, size);
+    return output.clone(/*memory_format=*/at::MemoryFormat::Contiguous);
+  }
+}
+"""
+        # view_copy is a native signature, since we're generating an at::native:: kernel
+        # Functionalization always operates on symints though
+        view_copy_sig = NativeSignature(
+            g.view_copy.func, symint=metadata.supports_symint()
+        )
+
+        # view is a dispatcher signature, since we're calling into the at::_ops API
+        view_sig = DispatcherSignature(g.view.func)
+
+        view_api_name = g.view.func.name.unambiguous_name()
+        exprs = ", ".join(
+            [e.expr for e in translate(view_copy_sig.arguments(), view_sig.arguments())]
+        )
+
+        # view ops today always return either a Tensor or a list of Tensors
+        assert len(g.view.func.returns) == 1
+        assert g.view.func.returns[0].type == BaseType(
+            BaseTy.Tensor
+        ) or g.view.func.returns[0].type == ListType(BaseType(BaseTy.Tensor), None)
+
+        if g.view.func.returns[0].type == BaseType(BaseTy.Tensor):
+            return_cloned_output = """\
+  return output.clone(/*memory_format=*/at::MemoryFormat::Contiguous);"""
+        else:
+            # If the return type is a list, we need to clone each tensor in the list.
+            return_cloned_output = f"""\
+  {view_copy_sig.returns_type().cpp_type()} out_clone;
+  for (const auto i : c10::irange(output.size())) {{
+    out_clone.push_back(output[i].clone(/*memory_format=*/at::MemoryFormat::Contiguous));
+  }}
+  return out_clone;"""
+
+        # The default generated composite kernel for {view}_copy() operators just clones
+        # the input tensor, and runs the underlying view on the clone.
+        return f"""
+{view_copy_sig.defn(name=metadata.kernel)} {{
+  auto output = at::_ops::{view_api_name}::call({exprs});
+  {return_cloned_output}
+}}
+"""
+
+
+def return_str(rets: tuple[Return, ...], names: list[str]) -> str:
+    assert len(rets) == len(names)
+    if len(rets) == 0:
+        return ""
+    elif len(rets) == 1:
+        return f"return {names[0]};"
+    else:
+        return f"return {dispatcher.returns_type(rets).cpp_type()}({', '.join(names)});"
+
+
+def modifies_arguments(f: NativeFunction) -> bool:
+    return any(
+        a.annotation is not None and a.annotation.is_write
+        for a in f.func.arguments.flat_all
+    )
+
+
+def wrapper_name(func: FunctionSchema) -> str:
+    if func.name.overload_name:
+        return f"{cpp.name(func)}_{func.name.overload_name}"
+    else:
+        return cpp.name(func)
+
+
+def is_tensor_like(a: Argument | TensorOptionsArguments | SelfArgument) -> bool:
+    return isinstance(a, SelfArgument) or (
+        isinstance(a, Argument) and a.type.is_tensor_like()
+    )
+
+
+# We need to wrap / unwrap various arguments from the op in the functionalization kernels.
+# Some op schemas include non-owning types though (like TensorList),
+# and when we unwrap them we expect to get out an owning type!.
+# We also return a lambda that tells you how to convert the non-owning type argument into the owning type.
+def get_owning_type(t: CType) -> tuple[CType, Callable[[str], str]]:
+    if t == BaseCType(tensorListT):
+        return VectorCType(BaseCType(tensorT)), lambda x: f"{x}.vec()"
+    if t == BaseCType(iTensorListRefT):
+        return VectorCType(BaseCType(tensorT)), lambda x: f"{{{x}.begin(), {x}.end()}}"
+    # There are technically other non-owning types out there (like IntArrayRef),
+    # but functionalization only actually cares about the ones involving tensors.
+    return t, lambda x: x
+
+
+# unwraps all tensor-like arguments, returning:
+# (1) a string containing all of the logic that does the unwrapping
+# (2) a context, to be used by translate(), with all of the relevant bindings.
+def unwrap_tensor_args(
+    sig: DispatcherSignature, *, is_view_op: bool
+) -> tuple[str, list[Binding]]:
+    context: list[Binding] = []
+    unwrapped_tensor_args: list[str] = []
+    for arg in sig.arguments():
+        if is_tensor_like(arg.argument):
+            # for tensor inputs, we want to unwrap them before passing them into the redispatch calls.
+            unwrapped_name = f"{arg.name}_"
+            # For most ops, the functionalization needs to sync any pending updates on the input tensors
+            # before calling the operator, since otherwise the operator will act on stale data.
+            # For view ops though, we can continue to defer syncing until the tensor is used by
+            # a non-view operator.
+            maybe_sync_input = (
+                "" if is_view_op else f"at::functionalization::impl::sync({arg.name});"
+            )
+            unwrapped_type, conversion_fn = get_owning_type(
+                arg.nctype.remove_const_ref().type
+            )
+            unwrapped_tensor_args.append(
+                f"""
+      {unwrapped_type.cpp_type()} {unwrapped_name};
+      if (at::functionalization::impl::isFunctionalTensor({arg.name})) {{
+        {maybe_sync_input}
+        {unwrapped_name} = at::functionalization::impl::from_functional_tensor({arg.name});
+      }} else {{
+        {unwrapped_name} = {conversion_fn(arg.name)};
+      }}"""
+            )
+            context.append(arg.with_name(unwrapped_name))
+        else:
+            # for non-tensor inputs, we want to pass them directly into the redispatch calls.
+            context.append(arg)
+    unwrap_tensor_args_str = "\n      ".join(unwrapped_tensor_args)
+    return unwrap_tensor_args_str, context
+
+
+# converts  all tensor-like arguments to meta tensors, which are used to compute stride info. Returns:
+# (1) a string containing all of the logic that does the conversions.
+# (2) a context, to be used by translate(), with all of the relevant bindings.
+def convert_to_meta_tensors(sig: DispatcherSignature) -> tuple[str, list[Binding]]:
+    context: list[Binding] = []
+    unwrapped_tensor_args: list[str] = []
+    for arg in sig.arguments():
+        if is_tensor_like(arg.argument):
+            # for tensor inputs, we want to unwrap them before passing them into the redispatch calls.
+            a_ = arg.name
+            unwrapped_name = f"{arg.name}_meta"
+            unwrapped_tensor_args.append(f"auto {unwrapped_name} = to_meta({a_});")
+            context.append(arg.with_name(unwrapped_name))
+        else:
+            # for non-tensor inputs, we want to pass them directly into the redispatch calls.
+            context.append(arg)
+    unwrap_tensor_args_str = "\n        ".join(unwrapped_tensor_args)
+    return unwrap_tensor_args_str, context
+
+
+# The functionalization codegen currently expects view op schemas to have this form:
+# foo(Tensor(a), ...) -> Tensor(a) (e.g. transpose)
+# foo(Tensor(a!), ...) -> Tensor(a!) (e.g. transpose_)
+def assert_view_op_properties(func: FunctionSchema) -> None:
+    def is_alias(a: Argument) -> bool:
+        return a.annotation is not None
+
+    args = func.arguments.flat_non_out
+    # The first argument is a tensor with an alias semantics (annotations)
+    assert (
+        len(args) > 0 and args[0].type == BaseType(BaseTy.Tensor)
+    ), f"""In the functionalization codegen, we expect the first argument of every view operator to be a tensor,
+but found an argument of type {str(args[0].type)} for operator: {str(func.name)}."""
+    # No other arguments have aliasing semantics
+    assert (
+        is_alias(args[0]) and not any(is_alias(a) for a in args[1:])
+    ), """In the functionalization codegen, we expect the first argument of every view operator to alias the output.
+View operators with multiple aliasing inputs aren't supported yet. Found an operator that doesn't satisfy this constraint"""
+
+
+# One-liner expression for checking if an expression expr of type type has any
+# symbolic values.
+def emit_expr_has_symbolic_values(expr: str, type: CType) -> str:
+    if type == BaseCType(SymIntT):
+        return f"{expr}.is_symbolic()"
+
+    if isinstance(type, OptionalCType):
+        innerexpr = f"(*{expr})"
+        return f"{expr}.has_value() ? {emit_expr_has_symbolic_values(innerexpr, type.elem)} : false"
+
+    if type == BaseCType(optionalSymIntArrayRefT):
+        return emit_expr_has_symbolic_values(
+            expr, OptionalCType(BaseCType(symIntArrayRefT))
+        )
+
+    if type in (BaseCType(symIntArrayRefT), VectorCType(BaseCType(SymIntT))):
+        argname = "arg"
+        lambda_check = emit_expr_has_symbolic_values(argname, BaseCType(SymIntT))
+        return (
+            "std::any_of("
+            f"{expr}.begin(), {expr}.end(), "
+            f"[=](auto& {argname}) {{ return {lambda_check}; }})"
+        )
+
+    raise ValueError(
+        "unsupported type for has_symbolic_values check. "
+        "It should be a SymInt or a collection of those. "
+        f"Got: {type.cpp_type()}"
+    )
+
+
+# Detects whether any of the SymInt arguments are, in fact, symbolic values.
+# This is used in the constructor of ViewMeta.
+def emit_has_symbolic_inputs(sig: DispatcherSignature) -> tuple[str, str]:
+    name = "has_symbolic_inputs"
+    statements = [
+        f"{name} = {name} | ({emit_expr_has_symbolic_values(binding.name, binding.nctype.type)});"
+        for binding in sig.arguments()
+        if (
+            isinstance(binding.argument, Argument)
+            and binding.argument.type.is_symint_like()
+        )
+    ]
+    body = "\n      ".join(statements)
+    return (
+        name,
+        f"""
+      bool {name} = false;
+      {body}""",
+    )
+
+
+# Generates the Functionalization kernel for:
+# - ops that create aliases (e.g. transpose())
+# - ops that are views AND mutations (e.g. transpose_())
+def emit_view_functionalization_body(
+    g: NativeFunctionsViewGroup, *, view_inplace: bool
+) -> str:
+    if view_inplace:
+        # This op is both an inplace op AND a view op.
+        # See Note [Functionalization Pass - Inplace View Ops] for details.
+        # I currently have the view meta call into the out-of-place variant of the view, to avoid
+        # having to define an extra ~20 inplace {view}_inverse_ functions.
+        # Most view ops don't have NativeFunctionGroup's both, because we don't define out= variants for view ops.
+        # I'm assuming that every inplace-view op has a corresponding out-of-place view op,
+        # with the same name but the trailing underscore removed.
+        # This is currently asserted at parse time in gen.py (see error_check_native_functions).
+        assert g.view_inplace is not None
+        f = g.view_inplace
+    else:
+        f = g.view
+
+    assert g.view_copy is not None
+    with native_function_manager(f):
+        call_sig = DispatcherSignature.from_schema(g.view_copy.func)
+
+        spec = ViewMetaSpecialization(g, f=f)
+
+        # the "view_copy" op name that the functionalization kernels need to call
+        api_name = g.view_copy.func.name.unambiguous_name()
+        # Sometimes the functionalization pass needs to no-op (e.g. if it was passed non-functional tensors)
+        # "no-op"ing in this context is just redispatching to the original op.
+        noop_api_name = f.func.name.unambiguous_name()
+
+        dispatcher_sig = DispatcherSignature.from_schema(f.func)
+        assert_view_op_properties(f.func)
+        view_tensor_name = dispatcher_sig.arguments()[0].name
+
+        return_type = dispatcher_sig.returns_type().remove_const_ref().cpp_type()
+
+        unwrap_tensor_args_str, unwrapped_args_ctx = unwrap_tensor_args(
+            dispatcher_sig, is_view_op=True
+        )
+        view_redispatch_args = [
+            e.expr
+            for e in translate(unwrapped_args_ctx, call_sig.arguments(), method=False)
+        ]
+
+        # The meta API call should use the same arguments, but convert all tensors to meta tensors first.
+        meta_conversion_str, meta_call_ctx = convert_to_meta_tensors(dispatcher_sig)
+        meta_call_args = [
+            e.expr for e in translate(meta_call_ctx, call_sig.arguments(), method=False)
+        ]
+
+        (
+            symbolic_inputs_varname,
+            symbolic_inputs_check,
+        ) = emit_has_symbolic_inputs(call_sig)
+
+        if "inplace_view" in f.tags:
+            # See Note [Functionalization Pass - Inplace View Ops] for more details
+            return f"""
+    {dispatcher_sig.defn(name=wrapper_name(f.func), is_redispatching_fn=True)} {{
+      if (!at::functionalization::impl::isFunctionalTensor({view_tensor_name})) {{
+        // functionalization is re-entrant, but will no-op if it wasn't passed a FunctionalTensorWrapper.
+        {unwrap_tensor_args_str}
+        at::AutoDispatchSkipFunctionalize guard;
+        return at::_ops::{noop_api_name}::call({", ".join(view_redispatch_args)});
+      }}
+      auto reapply_views = at::functionalization::impl::getFunctionalizationReapplyViewsTLS();
+      auto inverse_return_mode = (
+          reapply_views ? at::functionalization::InverseReturnMode::ViewOrScatterInverse
+            : at::functionalization::InverseReturnMode::NeverView
+      );
+      {symbolic_inputs_check}
+      auto view_meta = {spec.new()};
+      auto compute_reference_meta =
+        {view_tensor_name}.key_set().has_backend(c10::BackendComponent::XLABit) ||
+        {view_tensor_name}.key_set().has_backend(c10::BackendComponent::LazyBit);
+      {return_type} reference_tensor_output;
+      if (compute_reference_meta && !disable_meta_reference()) {{
+        {meta_conversion_str}
+        at::AutoDispatchSkipFunctionalize func_guard;
+        c10::impl::ExcludeDispatchKeyGuard guard(exclude_keys_for_meta_dispatch);
+        reference_tensor_output = at::_ops::{noop_api_name}::call({", ".join(meta_call_args)});
+      }}
+      // This function adds the above view meta to the current tensor and replays them off the base,
+      // mutating the size/stride info of the current FunctionalTensorWrapper.
+      // Because of this, we need to make sure to run the reference shape function above,
+      // BEFORE doing this (otherwise we'll end up running the reference function using the wrong sizes/strides)
+      at::functionalization::impl::mutate_view_meta({view_tensor_name}, view_meta);
+      // See  Note [Propagating strides in the functionalization pass]
+      // XLA/LTC don't implement the logic to propagate strides correctly, so we need to rely
+      // on a reference implementation here (instead of relying on the output from the forward lambda
+      // having the correct stride info)
+      if (compute_reference_meta && !disable_meta_reference()) {{
+        at::functionalization::impl::set_sizes_strides_offset({view_tensor_name}, reference_tensor_output);
+      }}
+      return {view_tensor_name};
+    }}
+"""
+
+        else:
+            return f"""
+    {dispatcher_sig.defn(name=wrapper_name(f.func), is_redispatching_fn=True)} {{
+      {unwrap_tensor_args_str}
+      if (!at::functionalization::impl::isFunctionalTensor({view_tensor_name})) {{
+        // functionalization is re-entrant, but will no-op if it wasn't passed a FunctionalTensorWrapper.
+        at::AutoDispatchSkipFunctionalize guard;
+        return at::_ops::{noop_api_name}::call({", ".join(view_redispatch_args)});
+      }}
+      auto reapply_views = at::functionalization::impl::getFunctionalizationReapplyViewsTLS();
+      auto inverse_return_mode = (
+          reapply_views ? at::functionalization::InverseReturnMode::ViewOrScatterInverse
+            : at::functionalization::InverseReturnMode::NeverView
+      );
+      auto compute_reference_meta =
+        {view_tensor_name}.key_set().has_backend(c10::BackendComponent::XLABit) ||
+        {view_tensor_name}.key_set().has_backend(c10::BackendComponent::LazyBit);
+      {return_type} reference_tensor_output;
+      if (compute_reference_meta && !disable_meta_reference()) {{
+        {meta_conversion_str}
+        at::AutoDispatchSkipFunctionalize func_guard;
+        c10::impl::ExcludeDispatchKeyGuard guard(exclude_keys_for_meta_dispatch);
+        reference_tensor_output = at::_ops::{noop_api_name}::call({", ".join(meta_call_args)});
+      }}
+      {return_type} tmp_output;
+      {{
+        at::AutoDispatchSkipFunctionalize guard;
+        if (reapply_views) {{
+          tmp_output = at::_ops::{noop_api_name}::call({", ".join(view_redispatch_args)});
+        }} else {{
+          tmp_output = at::_ops::{api_name}::call({", ".join(view_redispatch_args)});
+        }}
+      }}
+      {symbolic_inputs_check}
+      auto view_meta = {spec.new()};
+      auto out = at::functionalization::impl::create_functional_tensor_with_view_meta(tmp_output, {view_tensor_name}, view_meta);
+      // See  Note [Propagating strides in the functionalization pass]
+      if (compute_reference_meta && !disable_meta_reference()) {{
+        at::functionalization::impl::set_sizes_strides_offset(out, reference_tensor_output);
+      }}
+      return out;
+    }}
+"""
+
+
+def maybe_create_output(f: NativeFunction, var_name: str) -> str:
+    if len(f.func.returns) == 0:
+        return ""
+    return_type = dispatcher.returns_type(f.func.returns).remove_const_ref().cpp_type()
+    return f"{return_type} {var_name} = "
+
+
+# Given a NativeFunction, and a variable name corresponding to the output of redispatching on the function,
+# this returns two lists of names, consisting of:
+# - the names of returns corresponding to the original (mutable) inputs of the outer function
+# - the names of returns corresponding to the (immutable) outputs of the inner redispatched function
+def get_mutable_redispatch_return_names(
+    f: NativeFunction, inner_return_var: str
+) -> tuple[list[str], list[str]]:
+    aliased_returns = []
+    non_aliased_returns = []
+    for i, name in enumerate(f.func.aliased_return_names()):
+        if name is not None:
+            aliased_returns.append(name)
+        else:
+            non_aliased_returns.append(
+                inner_return_var
+                if len(f.func.returns) == 1
+                else f"std::get<{i}>({inner_return_var})"
+            )
+    return aliased_returns, non_aliased_returns
+
+
+# When functionalization "no-op's" and redispatches on a mutable operator, we need to take care so that:
+#  - For fresh outputs, we return the result of the redispatch (without wrapping outputs)
+#  - For outputs that were aliased to inputs, we return the inputs directly (since some of them might have been wrapped)
+def return_from_mutable_noop_redispatch(
+    f: NativeFunction, inner_return_var: str
+) -> str:
+    aliased, non_aliased = get_mutable_redispatch_return_names(f, inner_return_var)
+    # Just get all of the return names, and immediately return them
+    return return_str(f.func.returns, aliased + non_aliased)
+
+
+def wrap_propagate_mutations_and_return(
+    f: NativeFunction, functional_op: NativeFunction, inner_return_var: str
+) -> str:
+    mutable_arg_names = f.func.arguments.mutable_arg_names()
+    (
+        aliased_outer_rets,
+        non_aliased_outer_rets,
+    ) = get_mutable_redispatch_return_names(f, inner_return_var)
+    _, non_aliased_inner_rets = get_mutable_redispatch_return_names(
+        functional_op, inner_return_var
+    )
+    # The outer function may have a mix of aliased and non-aliased outputs,
+    # But the inner functional op that we're transforming to should only have non-aliased outputs
+    assert len(mutable_arg_names) + len(non_aliased_outer_rets) == len(
+        non_aliased_inner_rets
+    )
+
+    # First, take all of the newly created outputs from the inner call and wrap them into functional tensors
+    updates = []
+    non_aliased_wrapped_ret_names = []
+    for i, inner_ret in enumerate(
+        non_aliased_inner_rets[: len(non_aliased_outer_rets)]
+    ):
+        ret_name = f"output_{i}"
+        updates.append(
+            f"""\
+  auto output_{i} = at::functionalization::impl::to_functional_tensor({inner_ret});"""
+        )
+        non_aliased_wrapped_ret_names.append(ret_name)
+
+    # Next, take all of the mutated outputs from the inner call corresponding to mutated inputs,
+    # and propagate the mutations
+    for outer_arg, inner_ret in zip(
+        mutable_arg_names, non_aliased_inner_rets[len(non_aliased_outer_rets) :]
+    ):
+        updates.append(
+            f"""\
+  auto {outer_arg}_inner = at::functionalization::impl::from_functional_tensor({outer_arg});
+  at::functionalization::impl::replace_({outer_arg}, {inner_ret});
+  at::functionalization::impl::commit_update({outer_arg});
+  at::functionalization::impl::sync({outer_arg});
+  auto {outer_arg}_inner_updated = at::functionalization::impl::from_functional_tensor({outer_arg});
+  at::functionalization::impl::propagate_xla_data_direct({outer_arg}_inner, {outer_arg}_inner_updated);"""
+        )
+
+    # Finally, we return:
+    # - Any mutable arguments that also returns
+    # - Any immutable returns that were created wrapping the output from the inner call
+    returns_str = return_str(
+        f.func.returns, aliased_outer_rets + non_aliased_wrapped_ret_names
+    )
+    updates_str = "\n".join(updates)
+    return f"""\
+{updates_str}
+    {returns_str}"""
+
+
+# Generates the Functionalization kernel for:
+# - mutation ops (inplace and out= ops)
+@with_native_function_and
+def emit_inplace_functionalization_body(
+    f: NativeFunction, g: NativeFunctionsGroup
+) -> str:
+    # mutation case
+    assert modifies_arguments(f)
+
+    dispatcher_sig = DispatcherSignature.from_schema(f.func)
+
+    unwrap_tensor_args_str, unwrapped_args_ctx = unwrap_tensor_args(
+        dispatcher_sig, is_view_op=False
+    )
+
+    mutated_names = [
+        a.name
+        for a in f.func.arguments.flat_all
+        if a.type.is_tensor_like() and a.annotation is not None
+    ]
+    non_mutated_names = [
+        a.name
+        for a in f.func.arguments.flat_all
+        if a.type.is_tensor_like() and a.annotation is None
+    ]
+    non_mutated_tensor_names = [
+        a.name
+        for a in f.func.arguments.flat_all
+        if a.type == BaseType(BaseTy.Tensor) and a.annotation is None
+    ]
+    # all mutable inputs must be functional tensors in order to participate in functionalization
+    check_all_mutated_args_are_functional = " && ".join(
+        ["true"]
+        + [
+            f"at::functionalization::impl::isFunctionalTensor({a})"
+            for a in mutated_names
+        ]
+    )
+    check_any_non_mutated_args_are_functional = " || ".join(
+        ["false"]
+        + [
+            f"at::functionalization::impl::isFunctionalTensor({a})"
+            for a in non_mutated_names
+        ]
+    )
+
+    check_any_non_mutated_tensors_are_xla = " || ".join(
+        ["false"]
+        + [
+            f"{a}.device().type() == c10::DeviceType::XLA"
+            for a in non_mutated_tensor_names
+        ]
+    )
+    # These are used in the cases where we don't functionalize and redispatch to the inplace op
+    # case 1: we hit an inplace op that doesn't have an out-of-place equivalent
+    # case 2: we hit an inplace ops but our inputs are not functional tensors (in which case our kernel just no-ops)
+    inplace_exprs = [
+        e.expr
+        for e in translate(unwrapped_args_ctx, dispatcher_sig.arguments(), method=False)
+    ]
+
+    # call the out-of-place variant of the op
+    return_type = (
+        dispatcher.returns_type(g.functional.func.returns).remove_const_ref().cpp_type()
+    )
+    functional_sig = DispatcherSignature.from_schema(g.functional.func)
+    functional_exprs = [
+        e.expr
+        for e in translate(unwrapped_args_ctx, functional_sig.arguments(), method=False)
+    ]
+
+    if f.func.is_out_fn():
+        mutable_input_post_processing = "\n".join(
+            [
+                f"""
+      at::functionalization::impl::replace_(
+        {a.name}, {"std::get<" + str(i) + ">(tmp_output)" if len(f.func.returns) > 1 else "tmp_output"});
+      at::functionalization::impl::commit_update({a.name});"""
+                for (i, a) in enumerate(f.func.arguments.out)
+                if a.annotation and a.annotation.is_write and a.type.is_tensor_like()
+            ]
+        )
+    else:
+        mutable_input_post_processing = "\n".join(  # noqa: F841
+            [
+                f"""
+      at::functionalization::impl::replace_({a.name}, tmp_output);
+      at::functionalization::impl::commit_update({a.name});"""
+                for a in f.func.arguments.flat_all
+                if a.annotation and a.annotation.is_write and a.type.is_tensor_like()
+            ]
+        )
+
+    meta_conversion_str, meta_call_ctx = convert_to_meta_tensors(dispatcher_sig)
+    # We don't want to run the inplace meta func for ops like .set_(), because:
+    # (1) they're unnecessary: inplace meta checks are only useful for ops like add_(),
+    #     where broadcasting will work for the out-of-place case but should fail on the inplace call
+    # (2) They'll also fail without adding extra infra: we'd need to convert the input storage argument
+    #     into a meta storage
+    any_storage_args = any(
+        a.type == BaseType(BaseTy.Storage) for a in f.func.arguments.flat_all
+    )
+
+    return f"""
+    {dispatcher_sig.defn(name=wrapper_name(f.func), is_redispatching_fn=True)} {{
+      if ({str(not any_storage_args and f.func.kind() == SchemaKind.inplace).lower()} && !disable_meta_reference()) {{
+        // Before converting the mutable op to its functional variant, run meta tensors through the original op.
+        // This will help us catch shape errors that apply to inplace ops that wouldn't apply to their functional variants.
+        // (We can only do this for inplace ops today though, because they technically all support meta tensors).
+        {meta_conversion_str}
+        at::AutoDispatchSkipFunctionalize func_guard;
+        c10::impl::ExcludeDispatchKeyGuard guard(exclude_keys_for_meta_dispatch);
+        at::_ops::{f.func.name.unambiguous_name()}::call({", ".join(a.name for a in meta_call_ctx)});
+      }}
+      {unwrap_tensor_args_str}
+      if (!({check_all_mutated_args_are_functional})) {{
+        // We want to disable this check if there are any XLA tensors.
+        // cpu_tensor.copy_(xla_tensor) is valid code.
+        if (!({check_any_non_mutated_tensors_are_xla}) && ({check_any_non_mutated_args_are_functional})) {{
+         // case 1: trying to mutate a non functional tensor with a functional tensor is an error
+         TORCH_INTERNAL_ASSERT(false,
+           "mutating a non-functional tensor with a functional tensor is not allowed.",
+           " Please ensure that all of your inputs are wrapped inside of a functionalize() call.");
+        }} else {{
+         // case 2: arguments are not functional tensors, so we no-op and redispatch.
+         at::AutoDispatchSkipFunctionalize guard;
+         {maybe_create_output(f, "tmp_output")}at::_ops::{f.func.name.unambiguous_name()}::call({", ".join(inplace_exprs)});
+         {return_from_mutable_noop_redispatch(f, "tmp_output")}
+        }}
+      }} else {{
+        {return_type} tmp_output;
+        {{
+          at::AutoDispatchSkipFunctionalize guard;
+          tmp_output = at::_ops::{g.functional.func.name.unambiguous_name()}::call({", ".join(functional_exprs)});
+        }}
+        {wrap_propagate_mutations_and_return(f, g.functional, "tmp_output")}
+      }}
+    }}"""
+
+
+# The below functions generate RegisterFunctionalization.cpp
+# These files provide the kernels that run the functionalization pass, which can be opted into
+# per backend (e.g. XLA or Vulkan), or as a composable transform (functionalize() in functorch).
+
+
+# See Note [Functionalization Pass: View Inverses].
+def gen_functionalization_view_inverse_declaration(
+    selector: SelectiveBuilder, g: NativeFunctionsViewGroup
+) -> str | None:
+    # For every (non-composite) view op, we need a corresponding "inverse view" function.
+    # This generates the declarations so we get a good compiler error when someone adds a new view.
+    @with_native_function
+    def emit_decl_helper(g: NativeFunctionsViewGroup) -> str | None:
+        if g.view.has_composite_implicit_autograd_kernel:
+            return None
+        view_inverse_sig = ViewInverseSignature(g)
+        return view_inverse_sig.decl()
+
+    return emit_decl_helper(g)
+
+
+# Helper class for generating `ViewMeta` specializations.
+@dataclass
+class ViewMetaSpecialization:
+    g: NativeFunctionsViewGroup
+    f: NativeFunction
+
+    @property
+    def is_multi_output(self) -> bool:
+        return functionalization.is_multi_output(self.f.func)
+
+    @property
+    def is_as_strided(self) -> bool:
+        return str(self.f.func.name) == "as_strided"
+
+    @property
+    def out_index(self) -> str:
+        if self.is_multi_output:
+            return functionalization.out_index_binding.name
+        return "0"
+
+    @property
+    def classname(self) -> str:
+        return functionalization.classname(self.f.func)
+
+    def decl(self) -> list[str]:
+        base_ctor_arguments = functionalization.base_ctor_arguments(self.f.func)
+        extra_ctor_arguments = functionalization.extra_ctor_arguments(self.f.func)
+        attributes = functionalization.attributes(self.f.func)
+
+        # List of types for declaring the `SerializableTuple` type.
+        serializable_tuple_args = ",\n".join(
+            f"      {binding.type} /* {binding.name} */"
+            for binding in (base_ctor_arguments + attributes)
+        )
+
+        # Arguments used for forwarding the tuple elements to the constructor.
+        destructure_tuple_args = ", ".join(
+            f"std::get<{i}>(tpl)"
+            for i in range(len(base_ctor_arguments) + len(extra_ctor_arguments))
+        )
+
+        # List of constructor parameters
+        ctor_parameters = ", ".join(
+            binding.decl() for binding in (base_ctor_arguments + extra_ctor_arguments)
+        )
+
+        # Call the base class `ViewMeta` constructor.
+        #
+        # Both of `is_multi_output` and `is_as_strided` are known values, given the
+        # operation schema.
+        is_multi_output_str = str(self.is_multi_output).lower()
+        is_as_strided_str = str(self.is_as_strided).lower()
+
+        base_ctor_bindings = ", ".join(
+            [
+                # `has_symbolic_inputs` is always taken as parameter.
+                functionalization.has_symbolic_inputs_binding.name,
+                f"/*is_multi_output=*/{is_multi_output_str}",
+                f"/*is_as_strided=*/{is_as_strided_str}",
+                # `out_index` is know if the operation returns only one value. Otherwise,
+                # we also take it as parameter.
+                f"/*out_index=*/{self.out_index}",
+            ]
+        )
+
+        # Assignments of `extra_ctor_arguments` to their corresponding fields.
+        # These are extra fields to-be-declared in this specialization.
+        #
+        # We need to set `allow_expensive_conversions`, since we are storing owned versions
+        # of the non-owning arguments.
+        ctor_assignments = ",\n".join(
+            f"        {e.type.name}({e.expr})"
+            for e in translate(
+                extra_ctor_arguments,
+                attributes,
+                method=False,
+                allow_expensive_conversions=True,
+            )
+        )
+
+        # List of arguments for constructing the `SerializableTuple` from an instance.
+        tuple_arguments = ", ".join(
+            binding.name for binding in (base_ctor_arguments + attributes)
+        )
+
+        # List of field declarations.
+        attr_declarations = "\n".join(f"  {binding.decl()};" for binding in attributes)
+
+        # Override `to_out_index` if this operation returns more than 1 value.
+        to_out_index_decl = ""
+        if self.is_multi_output:
+            to_out_index_decl = (
+                "  std::shared_ptr to_out_index(int64_t out_idx) override;"
+            )
+
+        return [
+            f"""
+struct TORCH_API {self.classname} : public ViewMeta {{
+  FUNCTIONALIZATION_VIEWMETA_NAME({self.classname})
+  FUNCTIONALIZATION_VIEWMETA_SERIALIZABLE_TUPLE(\n{serializable_tuple_args});
+
+  {self.classname}(const SerializableTuple& tpl)
+      : {self.classname}({destructure_tuple_args}) {{}}
+
+  {self.classname}({ctor_parameters})
+      : at::functionalization::ViewMeta({base_ctor_bindings}),
+{ctor_assignments} {{}}
+
+  Tensor forward(const Tensor& base) override;
+  Tensor reverse(const Tensor& base, const Tensor& mutated_view) override;
+{to_out_index_decl}
+
+  SerializableTuple to_serializable_tuple() {{
+    return std::make_tuple({tuple_arguments});
+  }}
+
+{attr_declarations}
+}};
+"""
+        ]
+
+    # Generate a call to the actual operation.
+    def opcall(self, is_reverse: bool, reapply_views: bool) -> str:
+        opname = functionalization.name(
+            self.g,
+            is_reverse=is_reverse,
+            include_namespace=True,
+            reapply_views=reapply_views,
+        )
+
+        # Expected arguments for the operation.
+        assert self.g.view_copy is not None
+        op_arguments = functionalization.op_arguments(self.g.view_copy.func, is_reverse)
+
+        # The context is composed by the constructor arguments (which are also
+        # the field variables stored in the instance), and the `base` tensor.
+        context = [functionalization.base_binding]
+        context += functionalization.base_ctor_arguments(self.f.func)
+        context += functionalization.attributes(self.f.func)
+
+        # If we are generating the call for the reverse function, we also have
+        # access to `mutated_view` argument.
+        if is_reverse:
+            context.append(functionalization.mutated_view_binding)
+
+        arguments = ", ".join(
+            [e.expr for e in translate(context, op_arguments, method=False)]
+        )
+
+        # Index the result if this operation returns multiple values.
+        maybe_index = ""
+        if not is_reverse and self.is_multi_output:
+            maybe_index = f"[{self.out_index}]"
+
+        return f"{opname}({arguments}){maybe_index}"
+
+    def impl(self) -> list[str]:
+        functions = [
+            f"""
+at::Tensor {self.classname}::forward(const at::Tensor& base) {{
+  if (reapply_views) {{
+    return {self.opcall(is_reverse=False, reapply_views=True)};
+  }} else {{
+    return {self.opcall(is_reverse=False, reapply_views=False)};
+  }}
+}}""",
+            f"""
+at::Tensor {self.classname}::reverse(const at::Tensor& base, const Tensor& mutated_view) {{
+  return {self.opcall(is_reverse=True, reapply_views=True)};
+}}""",
+        ]
+
+        # If this operation returns multiple values, also generate a `to_out_index`
+        # implementation.
+        if self.is_multi_output:
+            functions.append(f"""
+std::shared_ptr {self.classname}::to_out_index(int64_t out_index) {{
+  return {self.new("out_index")};
+}}
+""")
+
+        return functions
+
+    # Create the Python binding for this specialized class.
+    def binding(self) -> list[str]:
+        name = functionalization.classname(self.f.func, with_namespace=True)
+        return [f"  create_binding_with_pickle<{name}>(functionalization);"]
+
+    # Generate an instantiation of this specialized class.
+    def new(self, out_index: str = "0") -> str:
+        name = functionalization.classname(self.f.func, with_namespace=True)
+        ctor_arguments = functionalization.base_ctor_arguments(
+            self.f.func
+        ) + functionalization.extra_ctor_arguments(self.f.func)
+        # Replace the `out_index` parameter with the given `out_index`.
+        arguments = ", ".join(
+            binding.name if binding.name != "out_index" else out_index
+            for binding in ctor_arguments
+        )
+        return f"std::make_shared<{name}>({arguments})"
+
+    # Run the function `run` for both: `view` and `view_inplace` functions.
+    @staticmethod
+    def map(
+        g: NativeFunctionsViewGroup, run: Callable[[ViewMetaSpecialization], list[str]]
+    ) -> list[str]:
+        def maybe_run(f: Optional[NativeFunction]) -> list[str]:
+            if f is None:
+                return []
+            with native_function_manager(f):
+                return run(ViewMetaSpecialization(g, f))
+
+        return list(concatMap(maybe_run, (g.view, g.view_inplace)))
+
+
+def gen_functionalization_view_meta_classes_base(
+    selector: SelectiveBuilder,
+    g: NativeFunctionsViewGroup,
+    run: Callable[[ViewMetaSpecialization], list[str]],
+) -> list[str]:
+    if not selector.include_all_operators:
+        return []
+
+    if g.composite:
+        return []
+
+    return ViewMetaSpecialization.map(g, run)
+
+
+def gen_functionalization_view_meta_classes_decl(
+    selector: SelectiveBuilder, g: NativeFunctionsViewGroup
+) -> list[str]:
+    return gen_functionalization_view_meta_classes_base(
+        selector, g, ViewMetaSpecialization.decl
+    )
+
+
+def gen_functionalization_view_meta_classes_impl(
+    selector: SelectiveBuilder, g: NativeFunctionsViewGroup
+) -> list[str]:
+    return gen_functionalization_view_meta_classes_base(
+        selector, g, ViewMetaSpecialization.impl
+    )
+
+
+def gen_functionalization_view_meta_classes_binding(
+    selector: SelectiveBuilder, g: NativeFunctionsViewGroup
+) -> list[str]:
+    return gen_functionalization_view_meta_classes_base(
+        selector, g, ViewMetaSpecialization.binding
+    )
+
+
+# Generates the Python bindings for the `ViewMeta` specialized classes.
+def gen_functionalization_view_meta_classes(
+    native_functions_path: str,
+    tags_path: str,
+    selector: SelectiveBuilder,
+    install_dir: str,
+    template_dir: str,
+) -> None:
+    from torchgen.gen import get_grouped_by_view_native_functions, parse_native_yaml
+
+    # Parse the native_functions.yaml.
+    # Then, group them into `NativeFunctionsViewGroup`.
+    #
+    # This is the same steps we do in gen.py (ATen codegen).
+    native_functions = parse_native_yaml(
+        native_functions_path, tags_path
+    ).native_functions
+    native_functions_with_view_groups = get_grouped_by_view_native_functions(
+        native_functions
+    )
+    view_groups = [
+        g
+        for g in native_functions_with_view_groups
+        if isinstance(g, NativeFunctionsViewGroup)
+    ]
+
+    fm = FileManager(install_dir=install_dir, template_dir=template_dir, dry_run=False)
+    fm.write(
+        "ViewMetaClassesPythonBinding.cpp",
+        lambda: {
+            "view_meta_bindings": list(
+                concatMap(
+                    lambda g: gen_functionalization_view_meta_classes_binding(
+                        selector, g
+                    ),
+                    view_groups,
+                )
+            ),
+        },
+    )
+
+
+def gen_functionalization_registration(
+    selector: SelectiveBuilder,
+    g: NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup,
+    composite_implicit_autograd_index: BackendIndex,
+) -> list[str]:
+    @with_native_function
+    def emit_registration_helper(f: NativeFunction) -> str:
+        assert not f.has_composite_implicit_autograd_kernel
+        registration_str = f"TORCH_FN(functionalization::{wrapper_name(f.func)})"
+        return f'm.impl("{f.func.name}", {registration_str});'
+
+    # Don't generate kernels in mobile build
+    if not selector.include_all_operators:
+        return []
+
+    if isinstance(g, NativeFunctionsViewGroup):
+        # functionalization needs to register kernels for view + view_inplace ops
+        # See Note [Functionalization <> torch.Tensor constructor]
+        if str(g.view.func.name) == "lift_fresh":
+            return []
+        view_str = []
+        if not g.view.has_composite_implicit_autograd_kernel:
+            view_str.append(emit_registration_helper(g.view))
+        if (
+            g.view_inplace is not None
+            and not g.view_inplace.has_composite_implicit_autograd_kernel
+        ):
+            assert g.view_inplace.is_view_op
+            view_str.append(emit_registration_helper(g.view_inplace))
+        return view_str
+
+    elif isinstance(g, NativeFunctionsGroup):
+        # Gets a hand-written functionalization kernel
+        if g.inplace is not None and str(g.inplace.func.name) == "set_.source_Tensor":
+            fns = []
+        else:
+            fns = list(g.functions())
+    else:
+        if str(g.func.name) in MUTABLE_OPS_NOT_USING_FUNCTIONALIZATION:
+            return []
+        fns = [g]
+
+    registrations = []
+    for f in fns:
+        if f.has_composite_implicit_autograd_kernel:
+            continue
+        if str(f.func.name) == "lift":
+            # See Note [Functionalization <> torch.Tensor constructor]
+            return []
+        if str(f.func.name) == "resize_":
+            # See Note [resize_ in Functionalization]
+            return []
+        if str(f.func.name.name) != "set_":
+            assert not f.is_view_op
+        # functionalization needs to generate and register kernels for inplace ops.
+        # We *also* need to directly register CompositeImplicitAUtograd kernels
+        # so that they decompose properly before functioanlization.
+        if modifies_arguments(f):
+            registrations.append(emit_registration_helper(f))
+    return registrations
+
+
+def gen_functionalization_definition(
+    selector: SelectiveBuilder,
+    # Note: Ideally this code should never have to look at NativeFunction
+    # (and instead only need to operate on grouped NativeFunctions).
+    # The only reason currently is because we need to emit direct dispatch registrations
+    # For CompositeImplicitAutograd operators, which are potentially ungrouped.
+    g: NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup,
+) -> list[str]:
+    # Don't generate kernels in mobile build
+    if not selector.include_all_operators:
+        return []
+
+    if isinstance(g, NativeFunctionsViewGroup):
+        # Case 1: emit view -> view_copy kernels for the functionalization pass
+        view_defs = []
+        if not g.composite:
+            # invariant: NativeFunctionsViewGroup's always have a view_copy operator
+            # if the view is not composite (implicit autograd)
+            assert g.view_copy is not None, dataclass_repr(g, indent=1)
+            view_defs.append(emit_view_functionalization_body(g, view_inplace=False))
+            if g.view_inplace is not None:
+                view_defs.append(emit_view_functionalization_body(g, view_inplace=True))
+        return view_defs
+    elif isinstance(g, NativeFunction):
+        # Invariant: all mutable operators that we need to handle in functionalization
+        # should have been properly grouped up.
+        # TODO: The below ops all have "problematic" schemas that prevent them from
+        # getting functionalized. Instead of bending over backwards to get things to work,
+        # I think we should either:
+        # (1) fix their schemas (BC-breaking)
+        # (2) hand-write their functionalization kernels
+        if (
+            str(g.func.name) not in MUTABLE_OPS_NOT_USING_FUNCTIONALIZATION
+            and str(g.func.name.name) not in MUTABLE_OPS_NOT_USING_FUNCTIONALIZATION
+        ):
+            assert g.has_composite_implicit_autograd_kernel or not modifies_arguments(g)
+        return []
+    else:
+        # Case 2: emit inplace -> out-of-place kernels for the functionalization pass
+        mutation_defs = []
+        mutation_defs.append(emit_inplace_functionalization_body(g.out, g))
+        if g.inplace is not None:
+            mutation_defs.append(emit_inplace_functionalization_body(g.inplace, g))
+        if g.mutable is not None:
+            mutation_defs.append(emit_inplace_functionalization_body(g.mutable, g))
+        return mutation_defs
+    return []
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen_lazy_tensor.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen_lazy_tensor.py
new file mode 100644
index 0000000000000000000000000000000000000000..e397561d378e2f75274e90eb39aa6313719521d4
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen_lazy_tensor.py
@@ -0,0 +1,585 @@
+from __future__ import annotations
+
+import argparse
+import os
+from collections import namedtuple
+from pathlib import Path
+from typing import Any, Callable, TYPE_CHECKING
+
+import yaml
+
+import torchgen.dest as dest
+from torchgen.api.lazy import setValueT
+from torchgen.api.types import BaseCppType
+from torchgen.dest.lazy_ir import GenLazyIR, GenLazyNativeFuncDefinition, GenTSLazyIR
+from torchgen.gen import get_grouped_native_functions, parse_native_yaml
+from torchgen.gen_backend_stubs import (
+    error_on_missing_kernels,
+    gen_dispatcher_registrations,
+    gen_dispatchkey_nativefunc_headers,
+    parse_backend_yaml,
+)
+from torchgen.model import NativeFunction, NativeFunctionsGroup, OperatorName
+from torchgen.selective_build.selector import SelectiveBuilder
+from torchgen.utils import FileManager, NamespaceHelper
+from torchgen.yaml_utils import YamlLoader
+
+
+if TYPE_CHECKING:
+    from collections.abc import Iterable, Iterator, Sequence
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                        Lazy Tensor Codegen
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+# Overview
+# ~~~~~~~~
+#
+# This codegen script builds on existing data models and helpers used
+# by all ATen backends, and adds new functionality specific to lazy
+# tensor backends.
+#
+# Inputs:
+# - _native_functions.yaml: controls which operators are
+#   supported by the backend.
+#
+# Outputs:
+# (for all backends)
+# Ir.h defines Lazy IR classes to be constructed during tracing
+# - opt-in: also generate 'lowering' methods for the TorchScript backend only
+# NativeFunctions.cpp defines implementations of native functions which perform lazy tracing
+# - opt-in: 'full_codegen' section of backend yaml; 'supported' section omits these implementations
+# NativeFunctions.h declares implementations of native functions for both 'supported' and 'full_codegen'
+# ops
+#
+# Register.cpp registers all op implementations with the dispatcher
+# RegisterAutograd.cpp registers all autograd implementations with the dispatcher
+#
+# Validation Helpers:
+# - Shape Inference: errs if any ops in backend yaml require shape inference not provided by meta kernels or
+#   implementations in torch/csrc/lazy/core/shape_inference.*
+# - native function impls: errs if any 'supported' ops do not have an implementation defined in the backend
+#   (non-codegen) implementation file
+#
+#
+# About the Data Model
+# ~~~~~~~~~~~~~~~~~~~~
+#
+# Modeled after ATen codegen, the first step is to parse yaml and build a data model for the operators
+# we care about.  In this case, the _native_functions yaml defines a subset of the core operators
+# (defined in more detail in the main native_functions.yaml), which will be supported by your backend.
+# Backends can list ops in two categories:
+#  - `supported` ops require hand-implementations but still get codegenned declarations and registrations
+#  - `full_codegen` ops get implementations (and IR classes) generated too
+#
+# Each native function is modeled as an object with a schema, and each schema has objects representing their
+# arguments.  Much of the codegen is manipulation of the arguments and their types.  For example, lazy tensor
+# backends need to transform 'at::Tensor' arguments into 'lazy::Value' objects, as well as replacing reference
+# types (stringref) with actual string objects, and this is done by manipulating the data model objects.
+# - see api/lazy.py for the lazy data model
+#
+# Once the data model is set up, the rest of this script processes a number of templates for output CPP file
+# and fills in the template values using helpers in `dest/lazy_ir.py` and `dest/lazy_ts_lowering.py`.  These
+# helpers mostly iterate over functions and their arguments, outputting different c++ snippets.
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+# Parses the external backend's yaml, and adds a new BackendIndex for the backend's dispatch key.
+# Returns a Tuple of (backend_key, autograd_key, cpp_namespace, updated BackendIndex mapping, full_codegen)
+ParsedExternalYaml = namedtuple(
+    "ParsedExternalYaml",
+    ["backend_key", "autograd_key", "cpp_namespace", "backend_indices", "full_codegen"],
+)
+
+
+def parse_native_functions_keys(
+    backend_yaml_path: str,
+    grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup],
+) -> tuple[list[OperatorName], list[Any], list[OperatorName]]:
+    with open(backend_yaml_path) as f:
+        yaml_values = yaml.load(f, Loader=YamlLoader)
+    assert isinstance(yaml_values, dict)
+
+    full_codegen = yaml_values.pop("full_codegen", [])
+    non_native = yaml_values.pop("non_native", [])
+    ir_gen = yaml_values.pop("ir_gen", [])
+    assert isinstance(full_codegen, list)
+    assert isinstance(non_native, list)
+    assert isinstance(ir_gen, list)
+    full_codegen_opnames = [OperatorName.parse(name) for name in full_codegen]
+    ir_gen_opnames = [OperatorName.parse(name) for name in ir_gen]
+    return full_codegen_opnames, non_native, ir_gen_opnames
+
+
+def validate_shape_inference_header(
+    shape_inference_hdr: str, expected_shape_infr_decls: list[str]
+) -> None:
+    try:
+        with open(shape_inference_hdr) as f:
+            shape_infr_decls = f.read()
+            shape_infr_decl_lines = set(shape_infr_decls.split("\n"))
+    except OSError as e:
+        raise AssertionError(
+            f"Unable to read from the specified shape_inference_hdr file: {shape_inference_hdr}"
+        ) from e
+
+    # TODO(whc) add a check for shape inference functions that have meta kernels implement and should be retired.
+
+    missing_decls = [
+        decl for decl in expected_shape_infr_decls if decl not in shape_infr_decl_lines
+    ]
+    if missing_decls:
+        raise Exception(  # noqa: TRY002
+            f"""Missing shape inference function.\n
+Please add declare this function in {shape_inference_hdr}:\n
+and implement it in the corresponding shape_inference.cpp file.\n
+{os.linesep.join(missing_decls)}"""
+        )
+
+
+# Some helper functions for the codegen.
+def get_ltc_helper_fns() -> str:
+    return """\
+at::Tensor to_meta(const at::Tensor& tensor) {
+  // undefined tensors can't be converted to the meta device, since they don't have sizes/strides
+  if (!tensor.defined()) return tensor;
+  auto out = at::native::empty_strided_meta_symint(tensor.sym_sizes(), tensor.sym_strides(), \
+/*dtype=*/tensor.scalar_type(), /*layout=*/tensor.layout(), \
+/*device=*/c10::Device(c10::kMeta), /*pin_memory=*/std::nullopt);
+  // needs to handle wrapped numbers, so dtype promotion works properly.
+  if (tensor.unsafeGetTensorImpl()->is_wrapped_number()) {
+    out.unsafeGetTensorImpl()->set_wrapped_number(true);
+  }
+  return out;
+}
+std::optional to_meta(const std::optional& tensor) {
+  if (tensor.has_value()) {
+    return to_meta(*tensor);
+  }
+  return std::nullopt;
+}
+
+std::vector to_meta(at::ITensorListRef t_list) {
+  std::vector outs;
+  outs.reserve(t_list.size());
+  for (const auto& tensor : t_list) {
+    outs.push_back(to_meta(tensor));
+  }
+  return outs;
+}
+"""
+
+
+class default_args:
+    node_base: str = "Node"
+    node_base_hdr: str | None = None
+    shape_inference_hdr: str = "torch/csrc/lazy/core/shape_inference.h"
+    tensor_class: str = "torch::lazy::LazyTensor"
+    tensor_class_hdr: str = "torch/csrc/lazy/core/tensor.h"
+    lazy_ir_generator: type[GenLazyIR] = GenLazyIR
+    native_func_definition_generator: type[GenLazyNativeFuncDefinition] = (
+        GenLazyNativeFuncDefinition
+    )
+    backend_name: str = "TorchScript"
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(description="Generate Lazy Tensor backend files")
+    parser.add_argument(
+        "-s",
+        "--source-yaml",
+        "--source_yaml",
+        help="path to source yaml file containing operator external definitions",
+    )
+    parser.add_argument("-o", "--output-dir", "--output_dir", help="output directory")
+    parser.add_argument(
+        "--dry-run", "--dry_run", type=bool, default=False, help="output directory"
+    )
+    parser.add_argument(
+        "--impl-path",
+        "--impl_path",
+        type=str,
+        default=None,
+        help="path to the source C++ file containing kernel definitions",
+    )
+    parser.add_argument(
+        "--gen-ts-lowerings",
+        "--gen_ts_lowerings",
+        action="store_true",
+        help="Generate TorchScript lowerings in addition to Lazy IR and NativeFunctions",
+    )
+    parser.add_argument(
+        "--node-base",
+        "--node_base",
+        type=str,
+        default=default_args.node_base,
+        help="Name of backend specific custom Lazy IR Node base class",
+    )
+    parser.add_argument(
+        "--node-base-hdr",
+        "--node_base_hdr",
+        type=str,
+        default=default_args.node_base_hdr,
+        help="Path to header file defining custom Lazy IR Node base class",
+    )
+    parser.add_argument(
+        "--shape-inference-hdr",
+        "--shape_inference_hdr",
+        type=str,
+        default=default_args.shape_inference_hdr,
+        help="Path to header file defining custom Lazy shape inference functions",
+    )
+    parser.add_argument(
+        "--tensor-class",
+        "--tensor_class",
+        type=str,
+        default=default_args.tensor_class,
+        help="Name of backend specific custom Lazy Tensor class",
+    )
+    parser.add_argument(
+        "--tensor-class-hdr",
+        "--tensor_class_hdr",
+        type=str,
+        default=default_args.tensor_class_hdr,
+        help="Path to header file defining custom Lazy Tensor class",
+    )
+    parser.add_argument(
+        "--backend-name",
+        "--backend_name",
+        type=str,
+        default=default_args.backend_name,
+        help="Name of the backend to generate",
+    )
+    options = parser.parse_args()
+
+    # Assumes that this file lives at PYTORCH_ROOT/torchgen/gen_backend_stubs.py
+    torch_root = Path(__file__).absolute().parents[2]
+    aten_path = str(torch_root / "aten" / "src" / "ATen")
+    lazy_ir_generator: type[GenLazyIR] = default_args.lazy_ir_generator
+    if options.gen_ts_lowerings:
+        lazy_ir_generator = GenTSLazyIR
+    native_func_definition_generator: type[GenLazyNativeFuncDefinition] = (
+        default_args.native_func_definition_generator
+    )
+
+    run_gen_lazy_tensor(
+        aten_path,
+        options.source_yaml,
+        options.output_dir,
+        options.dry_run,
+        options.impl_path,
+        options.node_base,
+        options.node_base_hdr,
+        options.tensor_class,
+        options.tensor_class_hdr,
+        options.shape_inference_hdr,
+        lazy_ir_generator,
+        native_func_definition_generator,
+        options.backend_name,
+    )
+
+
+def run_gen_lazy_tensor(
+    aten_path: str,
+    source_yaml: str,
+    output_dir: str,
+    dry_run: bool,
+    impl_path: str | None,
+    node_base: str = default_args.node_base,
+    node_base_hdr: str | None = default_args.node_base_hdr,
+    tensor_class: str = default_args.tensor_class,
+    tensor_class_hdr: str = default_args.tensor_class_hdr,
+    shape_inference_hdr: str = default_args.shape_inference_hdr,
+    lazy_ir_generator: type[GenLazyIR] = default_args.lazy_ir_generator,
+    native_func_definition_generator: type[
+        GenLazyNativeFuncDefinition
+    ] = default_args.native_func_definition_generator,
+    # build_in_tree is true for TS backend and affects include paths
+    build_in_tree: bool = False,
+    # per_operator_headers changes whether ATen/Functions.h or individual operator headers are used
+    # it must match how ATen was built
+    per_operator_headers: bool = False,
+    backend_name: str = default_args.backend_name,
+    gen_forced_fallback_code: bool = False,
+    use_lazy_shape: bool = True,
+    # the following arguments are temporary customization points for xla backend migration.
+    # do not rely on them otherwise, they should be removed once migration is complete
+    backend_namespace: str = "torch::lazy",
+    get_tensorlist: str = "GetTensorList",
+    get_tensor_or_wrap_number: str = "GetLtcTensorOrCreateForWrappedNumber",
+    try_get_tensor: str = "TryGetLtcTensor",
+    metrics_counter: str = 'TORCH_LAZY_FN_COUNTER("lazy::")',
+    create_tensor: str = "LazyTensor::Create",
+    create_from_first_tensor: bool = False,
+    create_aten_from_ltc_tensor: str = "torch::lazy::CreateAtenFromLtcTensor",
+    tuple_aten_from_ltc_tensors: str = "torch::lazy::TupleAtenFromLtcTensors",
+    lazy_value_class: str = "torch::lazy::Value",
+    lazy_tensor_ptr: str = "LazyTensorPtr",
+    get_device_fn: str = "torch::lazy::GetBackendDevice",
+) -> None:
+    lv_tokens = lazy_value_class.split("::")
+    lv_class = lv_tokens[-1]
+    lv_ns = "::".join(lv_tokens[:-1])
+    setValueT(BaseCppType(lv_ns, lv_class))
+    template_dir = os.path.join(aten_path, "templates")
+
+    def make_file_manager(install_dir: str) -> FileManager:
+        return FileManager(
+            install_dir=install_dir, template_dir=template_dir, dry_run=dry_run
+        )
+
+    fm = make_file_manager(output_dir)
+
+    native_yaml_path = os.path.join(aten_path, "native/native_functions.yaml")
+    tags_yaml_path = os.path.join(aten_path, "native/tags.yaml")
+    parsed_yaml = parse_native_yaml(native_yaml_path, tags_yaml_path)
+    native_functions, backend_indices = (
+        parsed_yaml.native_functions,
+        parsed_yaml.backend_indices,
+    )
+    grouped_native_functions = get_grouped_native_functions(native_functions)
+
+    def sort_native_function(f: NativeFunctionsGroup | NativeFunction) -> str:
+        """
+        We sort the native function because of the note in concat_map_codegen.
+        TODO(alanwaketan): Remove this sorting hack once all ops are grouped properly.
+        """
+        func = f.functional.func if isinstance(f, NativeFunctionsGroup) else f.func
+        return str(func.name.name)
+
+    grouped_native_functions = sorted(
+        grouped_native_functions, key=sort_native_function
+    )
+
+    parsed_backend_yaml = parse_backend_yaml(
+        source_yaml, grouped_native_functions, backend_indices
+    )
+    backend_key = parsed_backend_yaml.backend_key
+    autograd_key = parsed_backend_yaml.autograd_key
+    cpp_namespace = parsed_backend_yaml.cpp_namespace
+    backend_indices = parsed_backend_yaml.backend_indices
+    # the following 3 keys are all processed differently
+    # for full_codegen, we generate IR, kernels, etc
+    # for ir_gen, we generate only IR
+    # non_native is used to register kernels not declared in
+    # native_functions.yaml
+    full_codegen, non_native, ir_gen = parse_native_functions_keys(
+        source_yaml, grouped_native_functions
+    )
+
+    def concat_map_codegen(
+        func: Callable[[NativeFunction], Sequence[str]],
+        xs: Iterable[NativeFunctionsGroup | NativeFunction],
+        ops_list: list[OperatorName] = full_codegen,
+    ) -> Iterator[str]:
+        """
+        We code-gen for the functional variant, which is all we need for IR classes/lowerings/shape inferences, but we
+        only code-gen additional entries for the inplace variant for the native functions.
+        """
+
+        for x in xs:
+            fs = list(x.functions()) if isinstance(x, NativeFunctionsGroup) else [x]
+            for f in fs:
+                if f.func.name in ops_list:
+                    yield from func(f)
+
+    selector = SelectiveBuilder.get_nop_selector()
+
+    assert backend_key is not None
+    class_name = backend_indices[backend_key].native_function_class_name()
+
+    if impl_path is not None:
+        error_on_missing_kernels(
+            native_functions,
+            backend_indices,
+            backend_key,
+            autograd_key,
+            class_name,
+            impl_path,
+            full_codegen,
+        )
+
+    """ Validate Shape Inference Definitions
+
+    Generated lazy native functions all perform shape inference, by first using a meta:: kernel
+    if available for that op, and otherwise using a 'compute_shape_{op}' function instead.  The generator
+    knows the call signature for compute_shape_{op} because it matches the nativefunction (and meta::) signature,
+    so it just has to check whether the op is structured and generate a call for one or the other.  It's up to the dev
+    to supply the missing compute_shape_{op} function, but the codegen at least warns you about this and provides
+    the expected signature which can be copy-pasted into shape_inference.h.
+
+    compute_shape_{op} functions are handwritten and should be replaced over time as ops get ported
+    to structured kernels.
+
+    See torch/csrc/lazy/core/shape_inference.cpp #READ THIS! for more information.
+    """
+    if shape_inference_hdr is not None:
+        expected_shape_infr_decls = list(
+            concat_map_codegen(
+                dest.GenLazyShapeInferenceDefinition(
+                    backend_indices[backend_key], tensor_class
+                ),
+                grouped_native_functions,
+            )
+        )
+
+        validate_shape_inference_header(shape_inference_hdr, expected_shape_infr_decls)
+    assert class_name is not None
+
+    # Generate nativefunction declarations
+    # Note, eager registrations is set to False for the lazy TS backend as another LTC backend
+    # may want to register their own lazy kernels instead of registering the TS ones.
+    # The registration will lazily happen when init_ts_backend is called.
+    gen_dispatchkey_nativefunc_headers(
+        fm,
+        class_name,
+        cpp_namespace,
+        backend_indices,
+        grouped_native_functions,
+        backend_key,
+        autograd_key,
+        backend_name,
+    )
+
+    # Generate Dispatcher registrations which hook up the nativefunctions
+    for dispatch_key in (
+        [backend_key] if autograd_key is None else [backend_key, autograd_key]
+    ):
+        gen_dispatcher_registrations(
+            fm,
+            output_dir,
+            class_name,
+            backend_indices,
+            grouped_native_functions,
+            backend_key,
+            dispatch_key,
+            selector,
+            build_in_tree=build_in_tree,
+            per_operator_headers=per_operator_headers,
+            backend_name=backend_name,
+            eager_registration=False,
+        )
+
+    # Generate native function impls that build IR nodes
+    ns_helper = NamespaceHelper(cpp_namespace)
+    fm.write_with_template(
+        f"{backend_key}NativeFunctions.cpp",
+        "DispatchKeyNativeFunctions.cpp",
+        lambda: {
+            "includes": [
+                f"#include <{path}>"
+                for path in [
+                    tensor_class_hdr,
+                    shape_inference_hdr,
+                    "ATen/Functions.h",
+                    "ATen/native/TensorConversions.h",
+                    "ATen/NativeFunctions.h",
+                    "ATen/CompositeExplicitAutogradNonFunctionalFunctions.h",
+                    "ATen/MetaFunctions.h",
+                    "ATen/Operators.h",
+                    "ATen/native/CPUFallback.h",
+                    "torch/csrc/lazy/core/ir_builder.h",
+                    "torch/csrc/lazy/core/lazy_graph_executor.h",
+                    "torch/csrc/lazy/core/metrics.h",
+                    "torch/csrc/lazy/core/shape.h",
+                    f"{output_dir}/{backend_key}NativeFunctions.h",
+                    f"{output_dir}/LazyIr.h",
+                ]
+                + (
+                    ["torch/csrc/lazy/ts_backend/ts_eager_fallback.h"]
+                    if gen_forced_fallback_code
+                    else []
+                )
+            ],
+            "helper_fns": get_ltc_helper_fns(),
+            "native_functions_include": "",
+            "namespace_prologue": ns_helper.prologue,
+            "namespace_epilogue": ns_helper.epilogue,
+            "native_function_definitions": list(
+                concat_map_codegen(
+                    native_func_definition_generator(
+                        f"{backend_key}NativeFunctions",
+                        backend_indices[backend_key],
+                        tensor_class,
+                        gen_forced_fallback_code,
+                        backend_namespace,
+                        get_tensorlist,
+                        get_tensor_or_wrap_number,
+                        try_get_tensor,
+                        metrics_counter,
+                        create_tensor,
+                        create_from_first_tensor,
+                        create_aten_from_ltc_tensor,
+                        tuple_aten_from_ltc_tensors,
+                        lazy_tensor_ptr,
+                        get_device_fn,
+                    ),
+                    grouped_native_functions,
+                )
+            ),
+        },
+    )
+    # Generate IR node classes
+    lazy_ir_obj = lazy_ir_generator(
+        backend_indices[backend_key], backend_name, node_base, use_lazy_shape
+    )
+
+    fm.write_with_template(
+        "LazyIr.h",
+        "LazyIr.h",
+        lambda: {
+            "lazy_ir_sysinc": [
+                f"#include <{path}>"
+                for path in [
+                    "ATen/core/Formatting.h",
+                    "c10/core/ScalarType.h",
+                    "torch/csrc/lazy/core/hash.h",
+                    "torch/csrc/lazy/core/ir.h",
+                    "torch/csrc/lazy/core/shape.h",
+                    "optional",
+                    "vector",
+                ]
+            ],
+            "lazy_ir_inc": [f'#include "{node_base_hdr}"']
+            if node_base_hdr is not None
+            else [],
+            "ir_declarations": list(
+                concat_map_codegen(
+                    lazy_ir_obj, grouped_native_functions, full_codegen + ir_gen
+                )
+            ),
+            "namespace_prologue": ns_helper.prologue,
+            "namespace_epilogue": ns_helper.epilogue,
+        },
+    )
+
+    # Generate Non Native IR Node classes
+    fm.write_with_template(
+        "LazyNonNativeIr.h",
+        "LazyNonNativeIr.h",
+        lambda: {
+            "lazy_non_native_ir_inc": [
+                f"#include <{path}>"
+                for path in [
+                    "torch/csrc/lazy/core/ir.h",
+                    "torch/csrc/lazy/core/ir_builder.h",
+                    "torch/csrc/lazy/core/internal_ops/ltc_ops.h",
+                    "torch/csrc/lazy/core/shape_inference.h",
+                ]
+                + ([node_base_hdr] if node_base_hdr else [])
+                if path
+            ],
+            "non_native_ir_nodes": dest.generate_non_native_lazy_ir_nodes(
+                non_native, lazy_ir_obj
+            ),
+            "namespace_prologue": ns_helper.prologue,
+            "namespace_epilogue": ns_helper.epilogue,
+        },
+    )
+
+
+if __name__ == "__main__":
+    main()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen_schema_utils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen_schema_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..b81c91527baa187467acd5851178106d3e3d4111
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen_schema_utils.py
@@ -0,0 +1,97 @@
+from typing import Any, Optional, Union
+
+from torchgen.model import (
+    Annotation,
+    Argument,
+    Arguments,
+    BaseOperatorName,
+    BaseTy,
+    BaseType,
+    CustomClassType,
+    FunctionSchema,
+    ListType,
+    OperatorName,
+    Return,
+)
+
+
+# Note: These aren't actually used in torchgen, they're some utilities for generating a schema
+# from real arguments. For example, this is used to generate HigherOrderOperators' schema since
+# their schemas can vary for different instances of the same HOP.
+
+
+class TypeGen:
+    convert_to_base_ty = {
+        int: BaseTy.int,
+        float: BaseTy.float,
+        str: BaseTy.str,
+        bool: BaseTy.bool,
+    }
+
+    @staticmethod
+    def from_example(obj: Any) -> Union[BaseType, ListType, CustomClassType]:
+        import torch
+
+        if isinstance(obj, torch.fx.GraphModule):
+            return BaseType(BaseTy.GraphModule)
+        elif isinstance(obj, torch.Tensor):
+            return BaseType(BaseTy.Tensor)
+        elif isinstance(obj, torch.SymInt):
+            return BaseType(BaseTy.SymInt)
+        elif isinstance(obj, torch.SymBool):
+            return BaseType(BaseTy.SymBool)
+        elif isinstance(obj, torch.ScriptObject):
+            return CustomClassType(obj._type().name())  # type: ignore[attr-defined]
+        elif isinstance(obj, (list, tuple)):
+            assert len(obj) > 0
+            all_base_tys = [TypeGen.from_example(x) for x in obj]
+            if len(set(all_base_tys)) > 1:
+                raise RuntimeError(
+                    f"Cannot generate schema for a sequence of args of heterogeneous types: {all_base_tys}. "
+                    "Consider unpacking the argument and give proper names to them if possible "
+                    "instead of using *args."
+                )
+            return ListType(all_base_tys[0], len(obj))
+        tp = type(obj)
+        if tp not in TypeGen.convert_to_base_ty:
+            raise RuntimeError(f"unsupported type {tp}")
+        return BaseType(TypeGen.convert_to_base_ty[tp])
+
+
+class ReturnGen:
+    @staticmethod
+    def from_example(
+        name: Optional[str], obj: Any, annotation: Optional[Annotation]
+    ) -> Return:
+        return Return(name, TypeGen.from_example(obj), annotation)
+
+
+class ArgumentGen:
+    @staticmethod
+    def from_example(
+        name: str, obj: Any, default: Optional[str], annotation: Optional[Annotation]
+    ) -> Argument:
+        return Argument(
+            name, TypeGen.from_example(obj), default=default, annotation=annotation
+        )
+
+
+class FunctionSchemaGen:
+    @staticmethod
+    def from_example(
+        op_name: str,
+        example_inputs: tuple[tuple[str, Any], ...],
+        example_outputs: tuple[Any, ...],
+    ) -> FunctionSchema:
+        args = []
+        for name, inp in example_inputs:
+            args.append(ArgumentGen.from_example(name, inp, None, None))
+        # ignore the annotations and other attributes for now, we could add more when needed.
+        arguments = Arguments(
+            tuple(), None, tuple(args), tuple(), None, tuple(), tuple()
+        )
+        returns = tuple(
+            ReturnGen.from_example(None, out, None) for out in example_outputs
+        )
+        op_name = OperatorName(BaseOperatorName(op_name, False, False, False), "")
+        return FunctionSchema(op_name, arguments, returns)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen_vmap_plumbing.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen_vmap_plumbing.py
new file mode 100644
index 0000000000000000000000000000000000000000..0632e7c4b96985313b9b01297f9f128b07331551
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/gen_vmap_plumbing.py
@@ -0,0 +1,275 @@
+from __future__ import annotations
+
+import textwrap
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+from torchgen.api.translate import translate
+from torchgen.api.types import DispatcherSignature
+from torchgen.context import method_with_native_function
+from torchgen.model import (
+    Argument,
+    BaseTy,
+    BaseType,
+    FunctionSchema,
+    ListType,
+    NativeFunction,
+    OptionalType,
+    Return,
+    SchemaKind,
+    Type,
+)
+from torchgen.utils import mapMaybe
+
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+
+
+def is_tensor(typ: Type) -> bool:
+    return isinstance(typ, BaseType) and typ.name == BaseTy.Tensor
+
+
+def is_optional_tensor(typ: Type) -> bool:
+    return isinstance(typ, OptionalType) and is_tensor(typ.elem)
+
+
+def is_tensor_list(typ: Type) -> bool:
+    return isinstance(typ, ListType) and is_tensor(typ.elem)
+
+
+def unwrap_tensor(name: str, cur_level_var: str) -> list[str]:
+    result = f"""\
+    auto [{name}_value, {name}_bdim] = unwrapTensorAtLevel({name}, {cur_level_var});"""
+    return textwrap.dedent(result).split("\n")
+
+
+def unwrap_optional_tensor(name: str, cur_level_var: str) -> list[str]:
+    result = f"""\
+    std::optional {name}_value;
+    std::optional {name}_bdim;
+    if ({name}) {{
+        std::tie({name}_value, {name}_bdim) = unwrapTensorAtLevel({name}.value(), {cur_level_var});
+    }}"""
+    return textwrap.dedent(result).split("\n")
+
+
+def gen_unwraps(
+    flat_arguments: Sequence[Argument], cur_level_var: str
+) -> tuple[str, list[str]]:
+    arg_names = [a.name for a in flat_arguments]
+    arg_types = [a.type for a in flat_arguments]
+
+    tensors = [name for typ, name in zip(arg_types, arg_names) if is_tensor(typ)]
+    optional_tensors = [
+        name for typ, name in zip(arg_types, arg_names) if is_optional_tensor(typ)
+    ]
+
+    unwraps = []
+    for tensor in tensors:
+        unwraps += unwrap_tensor(tensor, cur_level_var)
+
+    for opt_tensor in optional_tensors:
+        unwraps += unwrap_optional_tensor(opt_tensor, cur_level_var)
+    unwrap_code = "\n".join(unwraps)
+
+    unwrapped_arg_list = []
+    for arg in arg_names:
+        if arg in tensors or arg in optional_tensors:
+            unwrapped_arg_list += [f"{arg}_value", f"{arg}_bdim"]
+        else:
+            unwrapped_arg_list.append(arg)
+    return unwrap_code, unwrapped_arg_list
+
+
+def gen_case_where_all_bdims_are_none(
+    outer_sig: DispatcherSignature, schema: FunctionSchema, cur_level_var: str
+) -> str:
+    conditions = []
+    flat_args = schema.arguments.flat_all
+    for arg in flat_args:
+        if not arg.type.is_tensor_like():
+            continue
+        conditions.append(f"!isBatchedAtLevel({arg.name}, {cur_level_var})")
+
+    sig = DispatcherSignature.from_schema(schema)
+    translated_args = ", ".join(
+        e.expr for e in translate(outer_sig.arguments(), sig.arguments())
+    )
+    return f"""\
+if ({" && ".join(conditions)}) {{
+  return at::_ops::{sig.func.name.unambiguous_name()}::call({translated_args});
+}}"""
+
+
+def gen_returns(
+    returns: tuple[Return, ...], cur_level_var: str, results_var: str
+) -> str:
+    idx = 0
+    wrapped_returns = []
+    for ret in returns:
+        if is_tensor(ret.type):
+            wrapped_returns.append(
+                f"makeBatched(std::get<{idx}>({results_var}), std::get<{idx + 1}>({results_var}), {cur_level_var})"
+            )
+            idx += 2
+        elif is_tensor_list(ret.type):
+            wrapped_returns.append(
+                f"makeBatchedVector(std::get<{idx}>({results_var}), std::get<{idx + 1}>({results_var}), {cur_level_var})"
+            )
+            idx += 2
+        else:
+            wrapped_returns.append(f"std::get<{idx}>({results_var})")
+            idx += 1
+    if len(wrapped_returns) == 1:
+        result = f"return {wrapped_returns[0]};"
+    else:
+        result = f"return std::make_tuple({', '.join(wrapped_returns)});"
+    return result
+
+
+def accepts_at_least_one_tensor_input(schema: FunctionSchema) -> bool:
+    return any(a.type.is_tensor_like() for a in schema.arguments.flat_all)
+
+
+def is_mutated_arg(argument: Argument) -> bool:
+    return argument.annotation is not None and argument.annotation.is_write
+
+
+def gen_vmap_inplace_plumbing(native_function: NativeFunction) -> str | None:
+    # Assumptions:
+    # - only one argument is being modified in-place
+    # - the argument that is being modified in-place is the first argument
+    # - all returns are either Tensor, tuple of Tensor, or TensorList
+    schema = native_function.func
+    sig = DispatcherSignature.from_schema(schema)
+    returns = schema.returns
+
+    # Check assumptions. If these are invalid we return None
+    # and punt the work to handle them to the future.
+    assert schema.kind() == SchemaKind.inplace
+    if not is_mutated_arg(schema.arguments.flat_all[0]):
+        return None
+    if not len([arg for arg in schema.arguments.flat_all if is_mutated_arg(arg)]) == 1:
+        return None
+
+    # Only support cases where all returns are Tensors or vector
+    if len(returns) == 0:
+        return None
+    if not all(is_tensor(ret.type) or is_tensor_list(ret.type) for ret in returns):
+        return None
+    if not accepts_at_least_one_tensor_input(schema):
+        return None
+
+    cur_level_var = "cur_level"
+
+    unwraps, unwrapped_arg_list = gen_unwraps(schema.arguments.flat_all, cur_level_var)
+    bdims_all_none_case = gen_case_where_all_bdims_are_none(sig, schema, cur_level_var)
+
+    return f"""\
+template 
+{sig.decl(name=schema.name.unambiguous_name() + "_generated_plumbing")} {{
+  c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched);
+  auto maybe_layer = maybeCurrentDynamicLayer();
+  vmap_check_escaped(maybe_layer, "gen_vmap_inplace_plumbing");
+  int64_t {cur_level_var} = maybe_layer->layerId();
+{textwrap.indent(bdims_all_none_case, "  ")}
+{textwrap.indent(unwraps, "  ")}
+  batch_rule({", ".join(unwrapped_arg_list)});
+  return {schema.arguments.flat_all[0].name};
+}}"""
+
+
+def gen_vmap_plumbing_no_returns(native_function: NativeFunction) -> str:
+    schema = native_function.func
+    sig = DispatcherSignature.from_schema(schema)
+    cur_level_var = "cur_level"
+
+    unwraps, unwrapped_arg_list = gen_unwraps(schema.arguments.flat_all, cur_level_var)
+    bdims_all_none_case = gen_case_where_all_bdims_are_none(sig, schema, cur_level_var)
+
+    return f"""\
+template 
+{sig.decl(name=schema.name.unambiguous_name() + "_generated_plumbing")} {{
+  c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched);
+  auto maybe_layer = maybeCurrentDynamicLayer();
+  vmap_check_escaped(maybe_layer, "gen_vmap_plumbing_no_returns");
+  int64_t {cur_level_var} = maybe_layer->layerId();
+{textwrap.indent(bdims_all_none_case, "  ")}
+{textwrap.indent(unwraps, "  ")}
+  batch_rule({", ".join(unwrapped_arg_list)});
+}}"""
+
+
+def gen_vmap_plumbing(native_function: NativeFunction) -> str | None:
+    schema = native_function.func
+    sig = DispatcherSignature.from_schema(schema)
+    returns = schema.returns
+
+    # Only support cases where all returns are Tensors or vector
+    if not accepts_at_least_one_tensor_input(schema):
+        return None
+    if len(returns) == 0:
+        return gen_vmap_plumbing_no_returns(native_function)
+    return_symint_overrides = [
+        "_scaled_dot_product_flash_attention",
+        "_scaled_dot_product_cudnn_attention",
+    ]
+    if (
+        not all(ret.type.is_tensor_like() for ret in returns)
+        and schema.name.unambiguous_name() not in return_symint_overrides
+    ):
+        return None
+    # in-place views need special handling
+    if "inplace_view" in native_function.tags:
+        return None
+
+    if schema.kind() == SchemaKind.inplace:
+        return gen_vmap_inplace_plumbing(native_function)
+
+    # Don't support these (mutable, out, scratch)
+    if schema.kind() != SchemaKind.functional:
+        return None
+
+    results_var = "results"
+    cur_level_var = "cur_level"
+
+    unwraps, unwrapped_arg_list = gen_unwraps(schema.arguments.flat_all, cur_level_var)
+    bdims_all_none_case = gen_case_where_all_bdims_are_none(sig, schema, cur_level_var)
+
+    wrapped_returns = gen_returns(returns, cur_level_var, results_var)
+    return f"""\
+template 
+{sig.decl(name=schema.name.unambiguous_name() + "_generated_plumbing")} {{
+  c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched);
+  auto maybe_layer = maybeCurrentDynamicLayer();
+  vmap_check_escaped(maybe_layer, "gen_vmap_plumbing");
+  int64_t {cur_level_var} = maybe_layer->layerId();
+{textwrap.indent(bdims_all_none_case, "  ")}
+{textwrap.indent(unwraps, "  ")}
+  auto {results_var} = batch_rule({", ".join(unwrapped_arg_list)});
+  {wrapped_returns}
+}}"""
+
+
+@dataclass(frozen=True)
+class ComputeBatchRulePlumbing:
+    @method_with_native_function
+    def __call__(self, f: NativeFunction) -> str | None:
+        result = gen_vmap_plumbing(f)
+        return result
+
+
+def gen_all_vmap_plumbing(native_functions: Sequence[NativeFunction]) -> str:
+    body = "\n".join(list(mapMaybe(ComputeBatchRulePlumbing(), native_functions)))
+    return f"""
+#pragma once
+#include 
+#include 
+
+namespace at {{ namespace functorch {{
+
+{body}
+
+}}}} // namespace at::functorch
+"""
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/local.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/local.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d7016bbfaf67286885ef3e95ec6a3a4af9abf93
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/local.py
@@ -0,0 +1,62 @@
+from __future__ import annotations
+
+import threading
+from contextlib import contextmanager
+from typing import TYPE_CHECKING
+
+
+if TYPE_CHECKING:
+    from collections.abc import Iterator
+
+
+# Simple dynamic scoping implementation.  The name "parametrize" comes
+# from Racket.
+#
+# WARNING WARNING: LOOKING TO EDIT THIS FILE?  Think carefully about
+# why you need to add a toggle to the global behavior of code
+# generation.  The parameters here should really only be used
+# for "temporary" situations, where we need to temporarily change
+# the codegen in some cases because we cannot conveniently update
+# all call sites, and are slated to be eliminated once all call
+# sites are eliminated.  If you don't have a plan for how to get there,
+# DON'T add a new entry here.
+
+
+class Locals(threading.local):
+    use_const_ref_for_mutable_tensors: bool | None = None
+    use_ilistref_for_tensor_lists: bool | None = None
+
+
+_locals = Locals()
+
+
+def use_const_ref_for_mutable_tensors() -> bool:
+    assert _locals.use_const_ref_for_mutable_tensors is not None, (
+        "need to initialize local.use_const_ref_for_mutable_tensors with "
+        "local.parametrize"
+    )
+    return _locals.use_const_ref_for_mutable_tensors
+
+
+def use_ilistref_for_tensor_lists() -> bool:
+    assert _locals.use_ilistref_for_tensor_lists is not None, (
+        "need to initialize local.use_ilistref_for_tensor_lists with local.parametrize"
+    )
+    return _locals.use_ilistref_for_tensor_lists
+
+
+@contextmanager
+def parametrize(
+    *, use_const_ref_for_mutable_tensors: bool, use_ilistref_for_tensor_lists: bool
+) -> Iterator[None]:
+    old_use_const_ref_for_mutable_tensors = _locals.use_const_ref_for_mutable_tensors
+    old_use_ilistref_for_tensor_lists = _locals.use_ilistref_for_tensor_lists
+    try:
+        _locals.use_const_ref_for_mutable_tensors = use_const_ref_for_mutable_tensors
+        _locals.use_ilistref_for_tensor_lists = use_ilistref_for_tensor_lists
+        yield
+    finally:
+        _locals.use_const_ref_for_mutable_tensors = (
+            old_use_const_ref_for_mutable_tensors
+        )
+        _locals.use_ilistref_for_tensor_lists = old_use_ilistref_for_tensor_lists
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/model.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/model.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb3a80dffe6a0db8e0ba51ebfed74fdda93460a2
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/model.py
@@ -0,0 +1,2887 @@
+from __future__ import annotations
+
+import dataclasses
+import itertools
+import re
+from dataclasses import dataclass
+from enum import auto, Enum
+from typing import Callable, Optional, TYPE_CHECKING
+from typing_extensions import assert_never
+
+from torchgen.utils import NamespaceHelper, OrderedSet
+
+
+if TYPE_CHECKING:
+    from collections.abc import Iterator, Sequence
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                           DATA MODEL
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+# Some general principles for our data model.
+#
+# - Stop using C++ data types as the internal data representation
+#   format.  Instead, the internal data structures are centered
+#   around JIT schema representation.  This avoid a big problem
+#   with the old codegen where we read in all the types from
+#   native_functions.yaml and then immediately had to retranslate
+#   them into C++ types.
+#
+# - More semantic data representation.  Instead of representing
+#   everything as dicts and strings, we define dataclasses for
+#   every interesting entity the code generation has to deal with.
+#   These dataclasses have strong semantic invariants: for example,
+#   we generally require them to roundtrip losslessly into the
+#   form they were parsed from.  These structures are immutable
+#   and you're expected to populate information once during
+#   construction.
+
+
+# Represent a source location; used for better error reporting
+@dataclass(frozen=True)
+class Location:
+    file: str
+    line: int
+
+    def __str__(self) -> str:
+        return f"{self.file}:{self.line}"
+
+
+# Valid values of the 'variants' field in native_functions.yaml
+class Variant(Enum):
+    function = auto()
+    method = auto()
+
+
+# Default kernel namespace
+DEFAULT_KERNEL_NAMESPACE = "at::native"
+
+# NOTE: Keep the list in sync with `DispatchKey` in c10/core/DispatchKey.h
+BACKEND_COMPONENTS = "CPU CUDA HIP XLA MTIA MPS IPU XPU HPU VE Lazy Meta PrivateUse1 PrivateUse2 PrivateUse3".split()
+FUNCTIONALITY_KEYS = [
+    "",
+    "Quantized",
+    "Sparse",
+    "SparseCsr",
+    "NestedTensor",
+    "Autograd",
+]
+
+# This list guards dispatches that can be used in derivatives.yaml
+# For now we omit AutogradFunctionality and AutogradOther
+AUTOGRAD_KEYS = ["AutogradNestedTensor"] + [
+    "Autograd" + component for component in BACKEND_COMPONENTS
+]
+
+FRAGMENT_NAMESPACES = {"quantized", "quantized_decomposed"}
+
+
+# This doesn't have to be in sync with the header, it only needs to contain
+# entries that we actually use in the codegen or want pyi entries for
+class DispatchKey(Enum):
+    Undefined = 0
+    CatchAll = Undefined
+
+    FPGA = auto()
+    MAIA = auto()
+    Vulkan = auto()
+    Metal = auto()
+    MKLDNN = auto()
+    OpenGL = auto()
+    OpenCL = auto()
+    IDEEP = auto()
+    CustomRNGKeyId = auto()
+    MkldnnCPU = auto()
+    Sparse = auto()
+    SparseCsr = auto()
+    NestedTensor = auto()
+    Dense = auto()
+
+    PythonTLSSnapshot = auto()
+    PreDispatch = auto()
+    PythonDispatcher = auto()
+    Python = auto()
+    FuncTorchDynamicLayerBackMode = auto()
+    ZeroTensor = auto()
+    Conjugate = auto()
+    Negative = auto()
+    BackendSelect = auto()
+    Named = auto()
+    AutogradOther = auto()
+    AutogradFunctionality = auto()
+    AutogradNestedTensor = auto()
+    Tracer = auto()
+    Autocast = auto()
+    AutocastCPU = auto()
+    AutocastCUDA = auto()
+    Batched = auto()
+    VmapMode = auto()
+    FuncTorchGradWrapper = auto()
+    FuncTorchBatched = auto()
+    BatchedNestedTensor = auto()
+    FuncTorchVmapMode = auto()
+    FuncTorchDynamicLayerFrontMode = auto()
+    Functionalize = auto()
+    TESTING_ONLY_GenericWrapper = auto()
+    TESTING_ONLY_GenericMode = auto()
+
+    ADInplaceOrView = auto()
+    Autograd = auto()
+    CompositeImplicitAutograd = auto()
+    CompositeImplicitAutogradNestedTensor = auto()
+    CompositeExplicitAutograd = auto()
+    CompositeExplicitAutogradNonFunctional = auto()
+    FuncTorchBatchedDecomposition = auto()
+
+    # BEGIN autogenerated
+    CPU = auto()
+    CUDA = auto()
+    HIP = auto()
+    XLA = auto()
+    MTIA = auto()
+    MPS = auto()
+    IPU = auto()
+    XPU = auto()
+    HPU = auto()
+    VE = auto()
+    Lazy = auto()
+    Meta = auto()
+    PrivateUse1 = auto()
+    PrivateUse2 = auto()
+    PrivateUse3 = auto()
+    QuantizedCPU = auto()
+    QuantizedCUDA = auto()
+    QuantizedHIP = auto()
+    QuantizedXLA = auto()
+    QuantizedMTIA = auto()
+    QuantizedMPS = auto()
+    QuantizedIPU = auto()
+    QuantizedXPU = auto()
+    QuantizedHPU = auto()
+    QuantizedVE = auto()
+    QuantizedLazy = auto()
+    QuantizedMeta = auto()
+    QuantizedPrivateUse1 = auto()
+    QuantizedPrivateUse2 = auto()
+    QuantizedPrivateUse3 = auto()
+    SparseCPU = auto()
+    SparseCUDA = auto()
+    SparseHIP = auto()
+    SparseXLA = auto()
+    SparseMTIA = auto()
+    SparseMPS = auto()
+    SparseIPU = auto()
+    SparseXPU = auto()
+    SparseHPU = auto()
+    SparseVE = auto()
+    SparseLazy = auto()
+    SparseMeta = auto()
+    SparsePrivateUse1 = auto()
+    SparsePrivateUse2 = auto()
+    SparsePrivateUse3 = auto()
+    SparseCsrCPU = auto()
+    SparseCsrCUDA = auto()
+    SparseCsrHIP = auto()
+    SparseCsrXLA = auto()
+    SparseCsrMTIA = auto()
+    SparseCsrMPS = auto()
+    SparseCsrIPU = auto()
+    SparseCsrXPU = auto()
+    SparseCsrHPU = auto()
+    SparseCsrVE = auto()
+    SparseCsrLazy = auto()
+    SparseCsrMeta = auto()
+    SparseCsrPrivateUse1 = auto()
+    SparseCsrPrivateUse2 = auto()
+    SparseCsrPrivateUse3 = auto()
+    NestedTensorCPU = auto()
+    NestedTensorCUDA = auto()
+    NestedTensorHIP = auto()
+    NestedTensorXLA = auto()
+    NestedTensorMTIA = auto()
+    NestedTensorMPS = auto()
+    NestedTensorIPU = auto()
+    NestedTensorXPU = auto()
+    NestedTensorHPU = auto()
+    NestedTensorVE = auto()
+    NestedTensorLazy = auto()
+    NestedTensorMeta = auto()
+    NestedTensorPrivateUse1 = auto()
+    NestedTensorPrivateUse2 = auto()
+    NestedTensorPrivateUse3 = auto()
+    AutogradCPU = auto()
+    AutogradCUDA = auto()
+    AutogradHIP = auto()
+    AutogradXLA = auto()
+    AutogradMTIA = auto()
+    AutogradMPS = auto()
+    AutogradIPU = auto()
+    AutogradXPU = auto()
+    AutogradHPU = auto()
+    AutogradVE = auto()
+    AutogradLazy = auto()
+    AutogradMeta = auto()
+    AutogradPrivateUse1 = auto()
+    AutogradPrivateUse2 = auto()
+    AutogradPrivateUse3 = auto()
+    # END autogenerated
+
+    def __str__(self) -> str:
+        return self.name
+
+    def lower(self) -> str:
+        return str(self).lower()
+
+    @staticmethod
+    def parse(value: str) -> DispatchKey:
+        for k, v in DispatchKey.__members__.items():
+            if k == value:
+                return v
+        raise AssertionError(f"unknown dispatch key {value}")
+
+
+class _TorchDispatchModeKey(Enum):
+    FAKE = auto()
+    PROXY = auto()
+    FUNCTIONAL = auto()
+
+
+def codegen_per_backend_entries() -> str:
+    r: list[str] = []
+    for fk in FUNCTIONALITY_KEYS:
+        r.extend(f"    {fk}{bc} = auto()" for bc in BACKEND_COMPONENTS)
+    return "\n".join(r)
+
+
+for fk in FUNCTIONALITY_KEYS:
+    for bc in BACKEND_COMPONENTS:
+        if not hasattr(DispatchKey, fk + bc):
+            r = codegen_per_backend_entries()
+            print(r)
+            raise RuntimeError(
+                f"Missing {fk}{bc} from DispatchKey enum.  Here is the autogenerated list we expect to have:\n\n{r}"
+            )
+
+
+STRUCTURED_DISPATCH_KEYS = {
+    DispatchKey.MPS,
+    DispatchKey.CUDA,
+    DispatchKey.CPU,
+    DispatchKey.XPU,
+    DispatchKey.MTIA,
+}
+UFUNC_DISPATCH_KEYS = {DispatchKey.CUDA, DispatchKey.CPU}
+
+# Set of supported dispatch keys
+dispatch_keys = [
+    DispatchKey.CPU,
+    DispatchKey.SparseCPU,
+    DispatchKey.SparseCsrCPU,
+    DispatchKey.MkldnnCPU,
+    DispatchKey.CUDA,
+    DispatchKey.MPS,
+    DispatchKey.XPU,
+    DispatchKey.SparseXPU,
+    DispatchKey.SparseCsrXPU,
+    DispatchKey.SparseCUDA,
+    DispatchKey.SparseCsrCUDA,
+    DispatchKey.SparseMPS,
+    DispatchKey.SparseCsrMPS,
+    DispatchKey.QuantizedCPU,
+    DispatchKey.QuantizedCUDA,
+    DispatchKey.CompositeImplicitAutograd,
+    DispatchKey.CompositeImplicitAutogradNestedTensor,
+    DispatchKey.CompositeExplicitAutograd,
+    DispatchKey.CompositeExplicitAutogradNonFunctional,
+    DispatchKey.NestedTensorCPU,
+    DispatchKey.NestedTensorCUDA,
+    DispatchKey.NestedTensorXPU,
+    DispatchKey.NestedTensorHPU,
+    # Meta is a magic key: it is automatically generated for structured
+    # kernels
+    DispatchKey.Meta,
+    DispatchKey.SparseMeta,
+    DispatchKey.SparseCsrMeta,
+    DispatchKey.QuantizedMeta,
+    DispatchKey.NestedTensorMeta,
+    DispatchKey.ZeroTensor,
+    DispatchKey.MTIA,
+]
+
+
+# Dispatch keys that "support all backends".  These codegen slightly differently
+# then backend specific keys.
+def is_generic_dispatch_key(dk: DispatchKey) -> bool:
+    return dk in {
+        DispatchKey.CompositeExplicitAutograd,
+        DispatchKey.CompositeExplicitAutogradNonFunctional,
+        DispatchKey.CompositeImplicitAutograd,
+        DispatchKey.CompositeImplicitAutogradNestedTensor,
+    }
+
+
+# CUDA specific dispatch keys
+def is_cuda_dispatch_key(dk: DispatchKey) -> bool:
+    return dk in {
+        DispatchKey.CUDA,
+        DispatchKey.QuantizedCUDA,
+        DispatchKey.SparseCUDA,
+        DispatchKey.SparseCsrCUDA,
+        DispatchKey.NestedTensorCUDA,
+        DispatchKey.AutogradCUDA,
+    }
+
+
+# XPU specific dispatcy keys
+def is_xpu_dispatch_key(dk: DispatchKey) -> bool:
+    return dk in {
+        DispatchKey.XPU,
+        DispatchKey.QuantizedXPU,
+        DispatchKey.SparseXPU,
+        DispatchKey.SparseCsrXPU,
+        DispatchKey.NestedTensorXPU,
+        DispatchKey.AutogradXPU,
+    }
+
+
+# Structured kernel generation is only supported for certain key types;
+# otherwise use old-style
+def is_structured_dispatch_key(dk: DispatchKey) -> bool:
+    return dk in STRUCTURED_DISPATCH_KEYS
+
+
+def is_ufunc_dispatch_key(dk: DispatchKey) -> bool:
+    # For now, ufunc dispatch keys coincide with structured keys
+    return dk in UFUNC_DISPATCH_KEYS
+
+
+dispatch_device_map = {is_cuda_dispatch_key: "cuda", is_xpu_dispatch_key: "xpu"}
+
+
+# This is oddly named ScalarType and not DType for symmetry with C++
+class ScalarType(Enum):
+    Byte = auto()
+    Char = auto()
+    Short = auto()
+    Int = auto()
+    Long = auto()
+    Half = auto()
+    Float = auto()
+    Double = auto()
+    ComplexHalf = auto()
+    ComplexFloat = auto()
+    ComplexDouble = auto()
+    Bool = auto()
+    BFloat16 = auto()
+    Float8_e5m2 = auto()
+    Float8_e5m2fnuz = auto()
+    Float8_e4m3fn = auto()
+    Float8_e4m3fnuz = auto()
+    Float8_e8m0fnu = auto()
+
+    def __str__(self) -> str:
+        return self.name
+
+    @staticmethod
+    def maybe_parse(value: str) -> ScalarType | None:
+        for k, v in ScalarType.__members__.items():
+            if k == value:
+                return v
+        return None
+
+    @staticmethod
+    def parse(value: str) -> ScalarType:
+        mb_r = ScalarType.maybe_parse(value)
+        assert mb_r is not None, f"unknown dtype {value}"
+        return mb_r
+
+    @staticmethod
+    def parse_set(values: str) -> OrderedSet[ScalarType]:
+        dtypes: OrderedSet[ScalarType] = OrderedSet()
+        for value in values.split(", "):
+            if value in DTYPE_CLASSES:
+                dtypes.update(DTYPE_CLASSES[value])
+            else:
+                dtypes.add(ScalarType.parse(value))
+        return dtypes
+
+
+DTYPE_CLASSES: dict[str, OrderedSet[ScalarType]] = {}
+# NB: Integral doesn't include boolean
+DTYPE_CLASSES["Integral"] = OrderedSet(
+    [
+        ScalarType.Byte,
+        ScalarType.Char,
+        ScalarType.Int,
+        ScalarType.Long,
+        ScalarType.Short,
+    ]
+)
+# NB: Floating doesn't include low precision types
+DTYPE_CLASSES["Floating"] = OrderedSet([ScalarType.Float, ScalarType.Double])
+DTYPE_CLASSES["Complex"] = OrderedSet(
+    [ScalarType.ComplexFloat, ScalarType.ComplexDouble]
+)
+DTYPE_CLASSES["All"] = DTYPE_CLASSES["Integral"] | DTYPE_CLASSES["Floating"]
+DTYPE_CLASSES["AllAndComplex"] = DTYPE_CLASSES["All"] | DTYPE_CLASSES["Complex"]
+DTYPE_CLASSES["FloatingAndComplex"] = (
+    DTYPE_CLASSES["Floating"] | DTYPE_CLASSES["Complex"]
+)
+
+
+# Represents the valid entries for ufunc_inner_loop in native_functions.yaml.
+# NB: if you add a new UfuncKey, you will teach torchgen.dest.ufunc how
+# to process it.  Most logic will ignore keys they don't understand, so your
+# new key will get silently ignored until you hook in logic to deal with it.
+class UfuncKey(Enum):
+    # These are low level keys that represent exactly one particular
+    # instantiation of the kernel produced by codegen
+    CUDAFunctor = auto()
+    CUDAFunctorOnOther = auto()
+    CUDAFunctorOnSelf = auto()
+
+    CPUScalar = auto()
+    CPUVector = auto()
+
+    # These are the ones users will usually specify, and
+    # implicitly "fill in" the low level keys
+    ScalarOnly = auto()  # CUDA*, CPUScalar
+    Generic = auto()  # CUDA*, CPU*
+
+    def __str__(self) -> str:
+        return self.name
+
+    @staticmethod
+    def parse(value: str) -> UfuncKey:
+        for k, v in UfuncKey.__members__.items():
+            if k == value:
+                return v
+        raise AssertionError(f"unknown ufunc key {value}")
+
+
+class DeviceCheckType(Enum):
+    NoCheck = 0
+    ExactSame = 1
+
+
+class ViewSchemaKind(Enum):
+    aliasing = auto()
+    aliasing_inplace = auto()
+    non_aliasing = auto()
+
+
+# The basic input to the code generation is native_functions.yaml.
+# The name "native", BTW, comes from the distinction between native
+# functions and legacy TH functions.  The legacy TH functions are gone,
+# but the "native" descriptor has stuck.
+#
+# NativeFunction models a single entry in native_functions.yaml.  Its
+# fields roughly correspond to what you would see in the YAML itself,
+# but after canonicalization and parsing has occurred.
+#
+# You can see some of the overall design patterns for how we setup
+# dataclasses in this class, but we will defer a complete discussion
+# of this at FunctionSchema.
+@dataclass(frozen=True)
+class NativeFunction:
+    # The namespace for this operator. For example, if we have "at::add"
+    # then the namespace would be "at". This enables ops to be registered
+    # through the same DSL with a custom namespace. If not specified, the
+    # default namespace would be "at".
+    namespace: str
+
+    # The function schema of the operator in question.  This schema
+    # has been parsed; see FunctionSchema for more about its structure.
+    # (This type is quoted as we are forward referencing a type
+    # defined later in the file.  I opted for this ordering of the
+    # classes for expository clarity.)
+    func: FunctionSchema
+
+    # Whether or not to generate mutable tensor arguments like regular
+    # ones
+    use_const_ref_for_mutable_tensors: bool
+
+    # Whether or not to omit automatic generation of a DeviceGuard
+    device_guard: bool
+
+    # How to emit automatic generation of device check
+    device_check: DeviceCheckType
+
+    # What python module to put the function in
+    python_module: str | None
+
+    # TODO: figure out what this does
+    category_override: str | None
+
+    # If no variants are specified in native_functions.yaml, this is
+    # assumed to be {'function'}.
+    variants: set[Variant]
+
+    # Whether or not we should skip generating registrations for
+    # this kernel.  This is a bit of a double-edged sword, as manual
+    # registrations don't participate in codegen-based selective build!
+    manual_kernel_registration: bool
+
+    # Whether or not to skip generating TensorMethod/Functions bindings
+    # for this kernel.  Technically, this doesn't actually skip generating
+    # the binding; instead, the binding gets generated to __dispatch_{funcname}
+    # so you can make use of the normal binding if you need it.
+    manual_cpp_binding: bool
+
+    # The location in the YAML file were this native function entry was
+    # defined.  This is for conveniently reporting error messages!
+    loc: Location
+
+    # A list of operators that are expected to be auto-generated for this NativeFunction.
+    # Note: This list isn't actually directly used by the codegen to generate anything.
+    # Instead, the codegen figures out what operators to generate purely based off of
+    # function schema, and uses the autogen declarations to error check.
+    # We expect every NativeFunction that gets auto-generated be explicitly called out
+    # in native_functions.yaml
+    autogen: list[OperatorName]
+
+    # If non-empty, this kernel is subject to ufunc codegen.
+    # Sorted by ufunc_key
+    ufunc_inner_loop: dict[UfuncKey, UfuncInnerLoop]
+
+    # Whether or not this out functions is a "structured kernel".  Structured
+    # kernels are defined a little differently from normal kernels; in
+    # particular, their shape checking logic is defined separately from
+    # the kernel.  Only out functions can be structured; other functions
+    # delegate to the out function using the structured_delegate keyword.
+    # Every structured kernel must have at least an out and a functional
+    # variant.
+    structured: bool
+
+    # Whether or not this non-out function is a structured kernel, defined
+    # in terms of the out kernel referenced by the string here.
+    structured_delegate: OperatorName | None
+
+    # Only valid for structured kernels.  Specifies alternative of what
+    # to inherit from when defining the meta class for the structured
+    # operator.  This will usually be TensorIteratorBase.  This also
+    # changes the semantics of set_output to call the parent class.
+    structured_inherits: str | None
+
+    # Structured kernels can declare elements as "precomputed". These elements
+    # are returned by the meta function in one struct and passed to the impl
+    # function in lieu of certain kernel arguments that these precomputed
+    # elements supersede. Information about the names and types of these
+    # precomputed elements and how they correspond to kernel arguments is stored
+    # in this member, if applicable.
+    precomputed: Precompute | None
+
+    # Argument names whose default  should be excluded from the C++ interface.
+    # Intended for resolving overload ambiguities between signatures.
+    cpp_no_default_args: set[str]
+
+    # Note [Abstract ATen methods]
+    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+    # An abstract ATen method is one whose dispatch differs between
+    # types.  These are implemented in derived types (with a
+    # standard (throwing) definition in Type).  A concrete ATen
+    # method is one which has the same dispatch for all types;
+    # we just implement it in the base Type.  This is exposed
+    # in Declarations.yaml via a field named 'abstract'.
+    is_abstract: bool
+
+    # Whether or not the NativeFunction contains a backend-agnostic kernel
+    has_composite_implicit_autograd_kernel: bool
+    has_composite_implicit_autograd_nested_tensor_kernel: bool
+    has_composite_explicit_autograd_kernel: bool
+    has_composite_explicit_autograd_non_functional_kernel: bool
+
+    # Tags are used to describe semantic information about (groups of) operators,
+    # That aren't easily inferable directly from the operator's schema.
+    tags: set[str]
+
+    # NB: The benefit of defining a dataclass is that we automatically get
+    # a constructor defined for all the fields we specify.  No need
+    # to explicitly write it out.
+
+    # We parse both the NativeFunction + backend-specific information about it, which it stored in a corresponding BackendIndex.
+    @staticmethod
+    def from_yaml(
+        ei: dict[str, object],
+        loc: Location,
+        valid_tags: set[str],
+        ignore_keys: set[DispatchKey] | None = None,
+    ) -> tuple[NativeFunction, dict[DispatchKey, dict[OperatorName, BackendMetadata]]]:
+        """
+        Parse a NativeFunction from a dictionary as directly parsed
+        from native_functions.yaml
+        """
+        e = ei.copy()
+
+        funcs = e.pop("func")
+        assert isinstance(funcs, str), f"not a str: {funcs}"
+        # only support one level of namespace. E.g., aten::add
+        namespace_helper = NamespaceHelper.from_namespaced_entity(
+            namespaced_entity=funcs, max_level=1
+        )
+        namespace = namespace_helper.get_cpp_namespace(default="aten")
+        func = FunctionSchema.parse(namespace_helper.entity_name)
+
+        cpp_no_default_args_list = e.pop("cpp_no_default_args", [])
+        assert isinstance(cpp_no_default_args_list, list)
+        cpp_no_default_args = set(cpp_no_default_args_list)
+
+        use_const_ref_for_mutable_tensors = e.pop(
+            "use_const_ref_for_mutable_tensors", False
+        )
+        assert isinstance(use_const_ref_for_mutable_tensors, bool)
+
+        if use_const_ref_for_mutable_tensors:
+            assert not func.arguments.out, (
+                "see https://github.com/pytorch/pytorch/issues/145522"
+            )
+
+        variants_s = e.pop("variants", "function")
+        assert isinstance(variants_s, str)
+        variants: set[Variant] = set()
+        for v in variants_s.split(", "):
+            if v == "function":
+                variants.add(Variant.function)
+            elif v == "method":
+                variants.add(Variant.method)
+            else:
+                raise AssertionError(f"illegal variant {v}")
+
+        manual_kernel_registration = e.pop("manual_kernel_registration", False)
+        assert isinstance(manual_kernel_registration, bool), (
+            f"not a bool: {manual_kernel_registration}"
+        )
+
+        manual_cpp_binding = e.pop("manual_cpp_binding", False)
+        assert isinstance(manual_cpp_binding, bool), f"not a bool: {manual_cpp_binding}"
+
+        device_guard = e.pop("device_guard", True)
+        assert isinstance(device_guard, bool), f"not a bool: {device_guard}"
+
+        device_check_s = e.pop("device_check", None)
+        assert device_check_s is None or isinstance(device_check_s, str), (
+            f"not a str: {device_check_s}"
+        )
+        assert (
+            device_check_s is None or device_check_s in DeviceCheckType.__members__
+        ), f"illegal device_check: {device_check_s}"
+        device_check: DeviceCheckType
+        if device_check_s is None:
+            device_check = DeviceCheckType.ExactSame
+        else:
+            device_check = DeviceCheckType[device_check_s]
+
+        structured = e.pop("structured", False)
+        assert isinstance(structured, bool), f"not a bool: {structured}"
+
+        structured_delegate_s = e.pop("structured_delegate", None)
+        assert structured_delegate_s is None or isinstance(
+            structured_delegate_s, str
+        ), f"not a str: {structured_delegate_s}"
+        assert structured_delegate_s is None or "::" not in structured_delegate_s, (
+            "namespace is not supported in structured delegate,"
+            " using the same namespace as the native function"
+        )
+        structured_delegate: OperatorName | None = None
+        if structured_delegate_s is not None:
+            structured_delegate = OperatorName.parse(structured_delegate_s)
+
+        structured_inherits = e.pop("structured_inherits", None)
+        assert structured_inherits is None or isinstance(structured_inherits, str), (
+            f"not a str: {structured_inherits}"
+        )
+        assert structured_inherits is None or "::" not in structured_inherits, (
+            "namespace is not supported in structured inherits,"
+            " using the same namespace as the native function"
+        )
+
+        python_module = e.pop("python_module", None)
+        assert python_module is None or isinstance(python_module, str), (
+            f"not a str: {python_module}"
+        )
+        assert python_module is None or Variant.method not in variants, (
+            "functions in modules cannot be methods"
+        )
+
+        category_override = e.pop("category_override", None)
+        assert category_override is None or isinstance(category_override, str), (
+            f"not a str: {category_override}"
+        )
+
+        precomputed_dict = e.pop("precomputed", None)
+        assert precomputed_dict is None or structured is True
+        precomputed = Precompute.parse(precomputed_dict) if precomputed_dict else None
+
+        tags_inp = e.pop("tags", [])
+        if isinstance(tags_inp, str):
+            tags_inp = [tags_inp]
+        assert isinstance(tags_inp, list)
+
+        # All aten ops generated by torchgen receive the pt2_compliant tag.
+        if namespace == "aten" and "pt2_compliant_tag" in valid_tags:
+            tags_inp.append("pt2_compliant_tag")
+
+        tags: set[str] = set()
+        for t in tags_inp:
+            assert len(valid_tags) > 0
+            # TODO: verify that the tag is valid and has an entry in tags.yaml
+            if t in valid_tags:
+                tags.add(t)
+            else:
+                raise AssertionError(f"illegal tag {t}")
+
+        from torchgen.api import cpp
+
+        raw_dispatch = e.pop("dispatch", None)
+        assert raw_dispatch is None or isinstance(raw_dispatch, dict), e
+        dispatch: dict[DispatchKey, BackendMetadata] = {}
+        num_dispatch_keys: int = 0
+        if raw_dispatch is not None:
+            assert not manual_kernel_registration, (
+                "cannot specify both manual_kernel_registration and dispatch; with "
+                "manual registration, dispatch has no effect!"
+            )
+            redundant_composite_implicit_autograd = False
+            for ks, v in raw_dispatch.items():
+                if ks == "__line__":
+                    continue  # not worth tracking line numbers for dispatch entries
+                assert isinstance(ks, str), (
+                    f"illegal dispatch key '{ks}' in {raw_dispatch}"
+                )
+                assert isinstance(v, str), (
+                    f"illegal dispatch value '{v}' in {raw_dispatch}"
+                )
+                for k in ks.split(","):
+                    dispatch_key = DispatchKey.parse(k.strip())
+                    num_dispatch_keys += 1
+
+                    if ignore_keys and dispatch_key in ignore_keys:
+                        continue
+                    assert dispatch_key in dispatch_keys, (
+                        f"Dispatch key {dispatch_key} of kernel {v} "
+                        "is not a supported dispatch key."
+                    )
+                    # We only allow at most 3 levels of namespace for kernels.
+                    # We will append "native" to a custom kernel namespace.
+                    namespace_helper = NamespaceHelper.from_namespaced_entity(
+                        v, max_level=3
+                    )
+                    kernel_namespace = namespace_helper.get_cpp_namespace(default="at")
+                    # Why is 'structured' included? External backends (e.g.
+                    # XLA) opt into which ops are structured independently
+                    # of which in-tree ops are structured
+                    dispatch[dispatch_key] = BackendMetadata(
+                        kernel=namespace_helper.entity_name,
+                        structured=structured
+                        and is_structured_dispatch_key(dispatch_key),
+                        cpp_namespace=(kernel_namespace + "::native"),
+                    )
+                    if (
+                        dispatch_key is DispatchKey.CompositeImplicitAutograd
+                        and v == cpp.name(func)
+                    ):
+                        redundant_composite_implicit_autograd = True
+
+            # We count the number of dispatch keys which have not been ignored to prevent a dispatch table
+            # in which all backend keys are ignored but necessarily kept, remaining compositeimplicit,
+            # from being treated as redundant.
+            assert not (
+                num_dispatch_keys == 1 and redundant_composite_implicit_autograd
+            ), (
+                "unnecessary dispatch table for this function; just delete the dispatch "
+                "key entirely"
+            )
+            # if a function is a structured delegate, deleting the dispatch
+            # table is NOT semantics preserving
+            assert (
+                structured_delegate
+                or dispatch.keys() != {DispatchKey.CompositeImplicitAutograd}
+                or dispatch[DispatchKey.CompositeImplicitAutograd].supports_symint()
+                or num_dispatch_keys != 1
+            ), (
+                f"unexpected name for singleton CompositeImplicitAutograd dispatch entry: expected {cpp.name(func)} "
+                f"but got {dispatch[DispatchKey.CompositeImplicitAutograd]}.  Rename your implementation to the expected "
+                "name, then delete the dispatch table"
+            )
+        elif not structured and structured_delegate is None:
+            name = str(func.name.name)
+            assert not (
+                name.startswith("new_")
+                or name.endswith("_like")
+                # TODO: maybe it's better to test the return
+                or (
+                    func.arguments.tensor_options
+                    and not func.arguments.has_tensor_arg()
+                )
+            ), (
+                f"expected {name} to have a CompositeExplicitAutograd "
+                "dispatch entry, but there was no dispatch table.  Factory functions "
+                "should not have implicit dispatch as they should not be decomposed "
+                "for __torch_dispatch__"
+            )
+            dispatch[DispatchKey.CompositeImplicitAutograd] = BackendMetadata(
+                cpp.name(func), structured=False, cpp_namespace=DEFAULT_KERNEL_NAMESPACE
+            )
+
+        composites_in_dispatch = [
+            d
+            for d in dispatch
+            if d == DispatchKey.CompositeExplicitAutograd
+            or d == DispatchKey.CompositeExplicitAutogradNonFunctional
+            or d == DispatchKey.CompositeImplicitAutograd
+            or d == DispatchKey.CompositeImplicitAutogradNestedTensor
+        ]
+
+        assert len(composites_in_dispatch) <= 1 or (
+            len(composites_in_dispatch) == 2
+            and (
+                DispatchKey.CompositeExplicitAutogradNonFunctional
+                not in composites_in_dispatch
+            )
+            and (
+                DispatchKey.CompositeImplicitAutogradNestedTensor
+                in composites_in_dispatch
+            )
+        ), (
+            "cannot specify more than one of CompositeExplicitAutograd, CompositeExplicitAutogradNonFunctional, "
+            "or CompositeImplicitAutograd on a single kernel; each "
+            "strictly subsumes the other.  If you wanted to provide an explicit autograd "
+            "implementation, specify CompositeExplicitAutograd; otherwise specify CompositeImplicitAutograd only"
+        )
+
+        autogen_str = e.pop("autogen", "")
+        assert isinstance(autogen_str, str)
+        autogen = (
+            []
+            if autogen_str == ""
+            else [OperatorName.parse(x) for x in autogen_str.split(", ")]
+        )
+
+        raw_ufunc_inner_loop = e.pop("ufunc_inner_loop", {})
+        ufunc_inner_loop = {}
+        if isinstance(raw_ufunc_inner_loop, str):
+            ufunc_inner_loop[UfuncKey.Generic] = UfuncInnerLoop.parse(
+                raw_ufunc_inner_loop, UfuncKey.Generic
+            )
+        elif isinstance(raw_ufunc_inner_loop, dict):
+            for k, vo in raw_ufunc_inner_loop.items():
+                if k == "__line__":
+                    continue
+                assert isinstance(k, str), f"ufunc_inner_loop key is not a str: {k}"
+                assert isinstance(vo, str), f"ufunc_inner_loop value is not a str: {v}"
+                ufunc_key = UfuncKey.parse(k)
+                ufunc_inner_loop[ufunc_key] = UfuncInnerLoop.parse(vo, ufunc_key)
+        else:
+            raise AssertionError(
+                f"ufunc_inner_loop not str or dict: {raw_ufunc_inner_loop}"
+            )
+        # Program the BackendIndex for the implicit dispatch entry from ufunc
+        if ufunc_inner_loop:
+            assert structured, "ufunc must be structured"
+
+            # Delay import ufunc here to avoid circular import issue
+            # See: https://github.com/pytorch/pytorch/issues/81294
+            import torchgen.api.ufunc as ufunc
+
+            for dispatch_key in UFUNC_DISPATCH_KEYS:
+                assert dispatch_key not in dispatch, (
+                    f"ufunc should not have explicit dispatch entry for {dispatch_key}"
+                )
+                dispatch[dispatch_key] = BackendMetadata(
+                    kernel=ufunc.schema_kernel_name(func, dispatch_key),
+                    structured=True,
+                    cpp_namespace=DEFAULT_KERNEL_NAMESPACE,
+                )
+
+        if structured_delegate:
+            # Structured functions MUST have a dispatch table
+            is_abstract = True
+        else:
+            is_abstract = (
+                dispatch.keys() != {DispatchKey.CompositeImplicitAutograd}
+                and dispatch.keys()
+                != {DispatchKey.CompositeImplicitAutogradNestedTensor}
+                and dispatch.keys()
+                != {
+                    DispatchKey.CompositeImplicitAutograd,
+                    DispatchKey.CompositeImplicitAutogradNestedTensor,
+                }
+            )
+
+        has_composite_implicit_autograd_kernel = (
+            DispatchKey.CompositeImplicitAutograd in dispatch
+        )
+        has_composite_implicit_autograd_nested_tensor_kernel = (
+            DispatchKey.CompositeImplicitAutogradNestedTensor in dispatch
+        )
+        has_composite_explicit_autograd_kernel = (
+            DispatchKey.CompositeExplicitAutograd in dispatch
+        )
+        has_composite_explicit_autograd_non_functional_kernel = (
+            DispatchKey.CompositeExplicitAutogradNonFunctional in dispatch
+        )
+
+        # We aren't going to store dispatch metadata inline in NativeFunctions;
+        # instead it is separately indexed by backend (so other backends can
+        # add more dispatch entries after the fact).  Reindex the individual
+        # metadata by OperatorName!
+        backend_metadata = {k: {func.name: v} for k, v in dispatch.items()}
+
+        # don't care if it exists or not; make it easier to use this function
+        # with other yaml parsers that aren't setting __line__ in the dict
+        e.pop("__line__", None)
+        assert not e, f"leftover entries: {e}"
+
+        # Asserts that we can't do in post_init, because they rely on backend-specific info
+        if structured_delegate is not None:
+            for key in STRUCTURED_DISPATCH_KEYS:
+                assert key not in dispatch, (
+                    f"if structured_delegate, then must not have {key} in dispatch dictionary "
+                    "(it is delegated!)"
+                )
+
+        return (
+            NativeFunction(
+                func=func,
+                use_const_ref_for_mutable_tensors=use_const_ref_for_mutable_tensors,
+                variants=variants,
+                structured=structured,
+                structured_delegate=structured_delegate,
+                structured_inherits=structured_inherits,
+                precomputed=precomputed,
+                autogen=autogen,
+                ufunc_inner_loop=ufunc_inner_loop,
+                manual_kernel_registration=manual_kernel_registration,
+                manual_cpp_binding=manual_cpp_binding,
+                python_module=python_module,
+                category_override=category_override,
+                device_guard=device_guard,
+                device_check=device_check,
+                loc=loc,
+                cpp_no_default_args=cpp_no_default_args,
+                is_abstract=is_abstract,
+                has_composite_implicit_autograd_kernel=has_composite_implicit_autograd_kernel,
+                has_composite_implicit_autograd_nested_tensor_kernel=has_composite_implicit_autograd_nested_tensor_kernel,
+                has_composite_explicit_autograd_kernel=has_composite_explicit_autograd_kernel,
+                has_composite_explicit_autograd_non_functional_kernel=has_composite_explicit_autograd_non_functional_kernel,
+                tags=tags,
+                namespace=namespace,
+            ),
+            backend_metadata,
+        )
+
+    def validate_unstructured(self) -> None:
+        # TODO: probably better to accumulate these errors and report them all
+        # at once
+        assert not self.structured, (
+            "This function is structured, but there was "
+            "no valid functional variant of it."
+        )
+        assert self.structured_delegate, (
+            "This function delegates to another structured out function, "
+            "but no valid function was found (the delegate may not exist, or it has the wrong type)"
+        )
+
+    # __post_init__ functions in dataclasses can be used to do extra
+    # validation after construction.
+    #
+    # Notice that we don't do any type validation here.  In fact, we
+    # rely exclusively on mypy to check if you've done types correctly!
+    # Validation is for nontrivial invariants that cannot be (conveniently)
+    # encoded in the type system.
+    def __post_init__(self) -> None:
+        if self.func.arguments.out:
+            assert self.variants == {Variant.function}, (
+                "Native functions with out arguments MUST "
+                "be declared with only function variant; e.g., variants: function; "
+                "otherwise you will tickle a Python argument binding bug "
+                "(which usually manifests itself as the result variable being undefined.)"
+            )
+        if self.structured:
+            assert self.func.kind() == SchemaKind.out, (
+                "Put structured field on the out= "
+                "variant of a function; did you mean structured_delegate?"
+            )
+            assert self.device_guard, (
+                "device_guard: False is not respected by structured kernels"
+            )
+        if self.structured_delegate:
+            assert self.func.kind() != SchemaKind.out, (
+                "structured_delegate field not allowed "
+                "on out= functions; did you mean structured?"
+            )
+            assert self.device_guard, (
+                "device_guard: False is not respected by structured kernels"
+            )
+        # Technically, with the asserts above, this assert is impossible to
+        # happen
+        assert not (self.structured and self.structured_delegate), (
+            "Cannot have both structured and structured_delegate on function"
+        )
+        defaulted_arguments = {
+            a.name for a in self.func.schema_order_arguments() if a.default is not None
+        }
+        invalid_args = set.difference(self.cpp_no_default_args, defaulted_arguments)
+        assert len(invalid_args) == 0, f"Invalid cpp_no_default_args: {invalid_args}"
+        if self.structured_inherits is not None:
+            assert self.structured, (
+                "structured_inherits must also imply structured: True"
+            )
+        if str(self.func.name).startswith("_foreach"):
+            assert self.device_check == DeviceCheckType.NoCheck, (
+                "foreach kernels fall back to slow path when tensor are on different devices, "
+                "device_check not allowed to be enabled"
+            )
+
+        # NB: if your function accidentally has rand/dropout/... in its name
+        # but is not actually random, feel free to amend this to special case
+        if (
+            "rand" in str(self.func.name)
+            or (
+                (
+                    "dropout" in str(self.func.name)
+                    or any(
+                        "dropout" in arg.name for arg in self.func.arguments.flat_all
+                    )
+                )
+                # Backwards of dropout is typically deterministic
+                and "backward" not in str(self.func.name)
+                and str(self.func.name.name) not in ["_cudnn_init_dropout_state"]
+            )
+            or self.func.arguments.has_generator_arg()
+        ):
+            assert "nondeterministic_seeded" in self.tags, str(self.func.name)
+
+    @property
+    def has_composite_kernel(self) -> bool:
+        return (
+            self.has_composite_implicit_autograd_kernel
+            or self.has_composite_explicit_autograd_kernel
+            or self.has_composite_explicit_autograd_non_functional_kernel
+        ) or (
+            self.has_composite_implicit_autograd_kernel
+            and self.has_composite_implicit_autograd_nested_tensor_kernel
+        )
+
+    @property
+    def is_view_op(self) -> bool:
+        rets = self.func.returns
+        is_non_mutating_view = len(rets) > 0 and any(
+            r.annotation is not None and not r.annotation.is_write for r in rets
+        )
+        # See Note [resize_ in Functionalization] for more dtails
+        is_inplace_view = (
+            "inplace_view" in self.tags
+            and str(self.func.name) != "resize_"
+            and str(self.func.name) != "resize_as_"
+        )
+        is_wildcard_view = any(
+            inp.annotation is not None and "*" in inp.annotation.alias_set_after
+            for inp in self.func.schema_order_arguments()
+        )
+        return is_non_mutating_view or is_inplace_view or is_wildcard_view
+
+    @property
+    def view_schema_kind(self) -> ViewSchemaKind:
+        if self.is_view_op and self.func.name.name.inplace:
+            assert "inplace_view" in self.tags
+            return ViewSchemaKind.aliasing_inplace
+        if self.is_view_op:
+            return ViewSchemaKind.aliasing
+        else:
+            return ViewSchemaKind.non_aliasing
+
+    @property
+    def root_name(self) -> str:
+        return self.func.name.name.base
+
+    @property
+    def part_of_structured_group(self) -> bool:
+        return self.structured or self.structured_delegate is not None
+
+
+class SchemaKind(Enum):
+    functional = auto()
+    inplace = auto()
+    out = auto()
+    mutable = auto()
+    scratch = auto()
+
+
+# A structured kernel is guaranteed to have a functional and out variant, and
+# optionally an inplace variant.
+#
+# NB: we create NativeFunctionsGroup *even if* the function is not
+# actually annotated structured.  Test the structured boolean to see if it
+# actually is structured or not.
+@dataclass(frozen=True)
+class NativeFunctionsGroup:
+    functional: NativeFunction
+    inplace: NativeFunction | None
+    mutable: NativeFunction | None
+    out: NativeFunction
+
+    @property
+    def structured(self) -> bool:
+        # Whether or not the operator has a meta() function. This information is backend-agnostic.
+        return self.out.structured
+
+    def __post_init__(self) -> None:
+        test_sig: FunctionSchema = self.functional.func.signature()
+        for f in self.functions():
+            if test_sig != f.func.signature():
+                raise AssertionError(
+                    "NativeFunctionsGroup constructed from two NativeFunctions "
+                    f"that don't have matching signatures: {test_sig} != {f.func.signature()}"
+                )
+
+            if self.structured != f.part_of_structured_group:
+                raise AssertionError(
+                    "NativeFunctionsGroup constructed from structured and unstructured "
+                    f"functions: {self.out.func.name} and {f.func.name}"
+                )
+        assert self.functional.func.kind() == SchemaKind.functional
+        assert self.out.func.kind() == SchemaKind.out
+        assert self.functional.namespace == self.out.namespace
+        if self.inplace is not None:
+            assert self.inplace.func.kind() == SchemaKind.inplace
+            assert self.inplace.namespace == self.functional.namespace
+
+        if self.mutable is not None:
+            assert self.mutable.func.kind() == SchemaKind.mutable
+            assert self.mutable.namespace == self.functional.namespace
+            # See Note [Overload Ambiguity With Functional Variants]
+            assert self.functional.func.name.name.functional_overload
+
+        if self.structured:
+            # For now, structured composite kernels are not supported (need some
+            # design work to figure out how to make the composite case work)
+            assert (
+                not self.out.has_composite_implicit_autograd_kernel
+                and not self.out.has_composite_implicit_autograd_nested_tensor_kernel
+            )
+
+            assert self.functional.structured_delegate == self.out.func.name, (
+                f"{self.functional.func.name} delegates to {self.functional.structured_delegate} "
+                f"but its actual delegate is {self.out.func.name}"
+            )
+            if self.inplace is not None:
+                assert self.inplace.structured_delegate == self.out.func.name
+
+        generated_fns = sorted(
+            [str(f.func.name) for f in self.functions() if "generated" in f.tags]
+        )
+        generated_fns_str = ", ".join(str(x) for x in generated_fns)
+        expected_generated_fns: set[str] = set()
+        for f in self.functions():
+            expected_generated_fns.update(str(op) for op in f.autogen)
+        expected_generated_fns_str = ", ".join(
+            str(x) for x in sorted(expected_generated_fns)
+        )
+        if len(expected_generated_fns) == 0 and len(generated_fns) > 0:
+            raise RuntimeError(
+                f"The codegen expects to be able to generate '{generated_fns_str}'."
+                " In order to generate them however, we expect them to be called out explicitly in the yaml."
+                f" Please add an 'autogen: {generated_fns_str}' line to the entry for {str(f.func.name)}"
+            )
+        if expected_generated_fns_str != generated_fns_str:
+            raise RuntimeError(
+                f"The codegen expects to be able to generate '{generated_fns_str}'."
+                f" To do so, it expects a line: 'autogen: {generated_fns_str}'."
+                f" Instead, it found 'autogen: {expected_generated_fns_str}'"
+            )
+
+    def signature(self) -> FunctionSchema:
+        return self.out.func.signature()
+
+    def functions(self) -> Iterator[NativeFunction]:
+        yield self.functional
+        yield self.out
+        if self.inplace is not None:
+            yield self.inplace
+        if self.mutable is not None:
+            yield self.mutable
+
+    @property
+    def root_name(self) -> str:
+        return self.functional.root_name
+
+    @staticmethod
+    def from_dict(d: dict[SchemaKind, NativeFunction]) -> NativeFunctionsGroup | None:
+        assert d
+        if len(d) == 1:
+            return None
+        d = dict(d)  # non-destructive updates please
+        functional = d.pop(SchemaKind.functional, None)
+        inplace = d.pop(SchemaKind.inplace, None)
+        mutable = d.pop(SchemaKind.mutable, None)
+        out = d.pop(SchemaKind.out, None)
+        assert not d
+        assert functional is not None
+        # There are a few operators which only have functional/inplace variants;
+        # these don't count as structured for our purposes here
+        if out is None:
+            return None
+        # assuming all variants have the same namespace
+        return NativeFunctionsGroup(
+            functional=functional,
+            inplace=inplace,
+            mutable=mutable,
+            out=out,
+        )
+
+
+@dataclass(frozen=True)
+class BackendMetadata:
+    # The name of the backend kernel, for a given operator
+    # for in-tree backends. These names come directly from the 'dispatch" field
+    # in native_functions.yaml. The dispatch entry is optional; in that
+    # case, that is equivalent to having written:
+    #
+    #   dispatch:
+    #       CompositeImplicitAutograd: $operator_name
+    kernel: str
+    # Whether or not the operator has a structured kernel implemented, for this particular backend.
+    # For in-tree backends, they all have the same value for structured- this is listed
+    # in native_functions.yaml.
+    # However, external backends like XLA can indendently toggle which ops are structured.
+    structured: bool
+
+    # The namespace for kernels, default value: DEFAULT_KERNEL_NAMESPACE
+    cpp_namespace: str
+
+    def supports_symint(self) -> bool:
+        return "_symint" in self.kernel
+
+
+@dataclass(frozen=True)
+class UfuncInnerLoop:
+    name: str
+    supported_dtypes: OrderedSet[ScalarType]
+    # key is stored here because it affects the semantics of name,
+    # so its helpful to have them together for further processing
+    ufunc_key: UfuncKey
+
+    @staticmethod
+    def parse(value: str, ufunc_key: UfuncKey) -> UfuncInnerLoop:
+        name, supported_dtypes_str = value.split(" ", 1)
+        assert supported_dtypes_str[0] == "("
+        assert supported_dtypes_str[-1] == ")"
+        supported_dtypes: OrderedSet[ScalarType] = OrderedSet()
+        for k in supported_dtypes_str[1:-1].split(", "):
+            supported_dtypes |= ScalarType.parse_set(k)
+        return UfuncInnerLoop(
+            name=name, supported_dtypes=supported_dtypes, ufunc_key=ufunc_key
+        )
+
+
+# BackendIndex represents a backend.
+# The BackendIndex encodes per-operator information that is potentially different
+# for each backend. The most obvious example is the name of the kernel
+# (the 'dispatch' entry in native_functions.yaml).
+# However, there can be other examples of different backends having different information.
+# External backends can choose to opt their kernels to be structured independently from in-tree backends,
+# which means that this information isn't inherently tied to a NativeFunction- it's different per backend.
+@dataclass(frozen=True)
+class BackendIndex:
+    dispatch_key: DispatchKey
+    # Mainly important for structured kernels, this determines which variant in the operator group is used to implement the others.
+    # All in-tree ops use out kernels, while XLA uses functional kernels.
+    use_out_as_primary: bool
+    # Whether the backend requires a device guard, and device checks.
+    # For in-tree backends, this is currently just CUDA/HIP
+    # For out-of-tree backends, this is currently just Intel XPU
+    device_guard: bool
+    # Whether the backend is in-tree (CPU/CUDA) or out-of-tree (XLA)
+    external: bool
+    # Other backend-specific information that is on a per-operator basis
+    index: dict[OperatorName, BackendMetadata]
+
+    @staticmethod
+    def grow_index(
+        parent_index: dict[DispatchKey, dict[OperatorName, BackendMetadata]],
+        child_index: dict[DispatchKey, dict[OperatorName, BackendMetadata]],
+    ) -> None:
+        for k, v in child_index.items():
+            for op_name, metadata in v.items():
+                assert op_name not in parent_index[k], (
+                    f"duplicate operator {op_name} for dispatch key {k}"
+                )
+                parent_index[k][op_name] = metadata
+
+    def primary(self, g: NativeFunctionsGroup) -> NativeFunction:
+        if self.use_out_as_primary:
+            return g.out
+        else:
+            return g.functional
+
+    def has_kernel(self, g: NativeFunction | NativeFunctionsGroup) -> bool:
+        m = self.get_kernel(g)
+        return m is not None
+
+    def get_kernel(
+        self, g: NativeFunction | NativeFunctionsGroup
+    ) -> BackendMetadata | None:
+        if isinstance(g, NativeFunction):
+            f = g
+        elif isinstance(g, NativeFunctionsGroup):
+            f = self.primary(g)
+        else:
+            assert_never(g)
+        if f.func.name not in self.index:
+            return None
+        return self.index[f.func.name]
+
+    def native_function_class_name(self) -> str | None:
+        if self.external:
+            return f"{str(self.dispatch_key)}NativeFunctions"
+        else:
+            # TODO: This discrepancy isn't required; we could also generated
+            # a class for in-tree kernels. It'll just require carefully
+            # updating every kernel definition + callsite of every in-tree aten kernel.
+            return None
+
+
+# The function schema is undoubtedly the most important data structure
+# in all of the codegen, as it defines the type signature for operators,
+# and most of the code generation we do is type directed (e.g., look at
+# the types, decide what to do.  Think about how we code generate
+# C++ function stubs!)
+#
+# We will also see in this class the general structure for how we model
+# data in this code generation.  A few notable properties to point out
+# ahead of time:
+#
+#   - These dataclasses are a *lossless* representation of the strings
+#     they are parsed from.  In fact, we assert that given the
+#     information stored in the dataclass, we can exactly reconstruct
+#     the string we parsed from (and assert this inside the parse
+#     definition).  There are a few reasons for this:
+#
+#       - If you find that it is difficult to reconstruct the string
+#         given a dataclass, that is a clue that you are data
+#         representation is wrong.
+#
+#       - It helps ensure that all relevant information is present
+#         in the dataclass, so that downstream users aren't tempted
+#         to reparse the original string to get some information
+#         that was omitted.
+#
+#       - It forces you to represent the data in-memory in the same way
+#         it is recorded textually, which makes the dataclasses easier
+#         to understand for someone who is familiar with the
+#         textual format.  (As a tradeoff, it means you have to model
+#         the syntax, even when it is inconvenient.  But maybe that means
+#         the syntax is bad!)  If you don't understand the internal
+#         representation, go look at the printing code to see how
+#         it maps onto the surface syntax!
+#
+#       - It makes it easy to test the parsing code, as parsing code
+#         that is inconsistent with the string code will fail early
+#         and loudly.  (As a tradeoff, it makes the parsing code a bit
+#         brittle (in particular, with trivial whitespace changes you
+#         are likely to trigger an assert error).
+#
+#     In general, try to make the __str__ code as simple as possible
+#     (even at the cost of more complex parsing logic.)  Additionally,
+#     try to minimize redundancy in data representation.  (Precomputed
+#     fields are OK though: they are defined as a simple function on
+#     the canonical representation in question.)
+#
+#   - These dataclasses are all frozen; once constructed their
+#     values never change.  This makes it easy to tell where any
+#     given data came from: just look to the constructor.  As a
+#     tradeoff, you can't easily "decorate" a schema with extra
+#     information from a post-facto analysis.  We impose this
+#     restriction to make these structures more understandable.
+#
+@dataclass(frozen=True)
+class FunctionSchema:
+    # The name of the operator this function schema describes.
+    name: OperatorName
+
+    arguments: Arguments
+
+    # TODO: Need to handle collisions with argument names at some point
+    returns: tuple[Return, ...]
+
+    @property
+    def is_mutable(self) -> bool:
+        def is_write(arg: Argument) -> bool:
+            if arg.annotation is None:
+                return False
+            return arg.annotation.is_write
+
+        # Corresponds to torch._C._FunctionSchema.is_mutable
+        # See aten/src/ATen/core/function_schema.h (keep these in sync)
+        return any(is_write(a) for a in self.arguments.flat_all)
+
+    def schema_order_arguments(self) -> Iterator[Argument]:
+        return itertools.chain(
+            self.arguments.flat_positional,
+            self.arguments.flat_kwarg_only,
+            self.arguments.out,
+        )
+
+    decl_re = re.compile(r"(?P[^\(]+)\((?P.*)\) -> (?P.*)")
+
+    @staticmethod
+    def parse(func: str) -> FunctionSchema:
+        # We should probably get a proper parser here
+        decls = FunctionSchema.decl_re.findall(func)
+        assert len(decls) == 1, f"Invalid function schema: {func}"
+        ops, args, return_decl = decls[0]
+        name = OperatorName.parse(ops)
+        arguments = Arguments.parse(args)
+        returns = parse_returns(return_decl)
+        r = FunctionSchema(name=name, arguments=arguments, returns=returns)
+        assert str(r) == func, f"{str(r)} != {func}"
+        return r
+
+    def returns_are_aliased(self) -> bool:
+        # We assert earlier that schemas can't have a mix of aliased and non-aliased returns
+        return any(
+            r
+            for r in self.returns
+            if r.annotation is not None and r.annotation.is_write
+        )
+
+    def __post_init__(self) -> None:
+        for arg, ret in zip(self.arguments.out, self.returns):
+            assert arg.annotation == ret.annotation, (
+                "Out arguments must have matching return Tensor; furthermore, "
+                "the ith-argument needs to correspond to the ith return"
+            )
+        # We also enforce that if you have any mutable, positional args, then they are not returned.
+        # This makes it easier to group these functions properly with their functional/out= counterparts.
+        for a in self.arguments.post_self_positional_mutable:
+            assert not any(a.annotation == r.annotation for r in self.returns), (
+                f"If you have a schema with mutable positional args, we expect them to not be returned. schema: {str(self)}"
+            )
+        # Invariant: we expect out arguments to appear as keyword arguments in the schema.
+        # This means that all mutable returns should be aliased to a keyword argument
+        # (except for "self", which we explicitly don't treat as an out argument because of its use in methods)
+        # See Note [is_out_fn]
+        out_and_self = list(self.arguments.out) + [
+            arg for arg in self.arguments.flat_positional if arg.name == "self"
+        ]
+        mutable_returns = [
+            ret
+            for ret in self.returns
+            if ret.annotation is not None and ret.annotation.is_write
+        ]
+        immutable_returns = [
+            ret
+            for ret in self.returns
+            if ret.annotation is None or not ret.annotation.is_write
+        ]
+        # Some assertions: We don't want any functions with a return type of "-> (Tensor(a!), Tensor)",
+        # because:
+        # (1) It's more annoying to handle properly
+        # (2) It's unnecessary - you can't method-chain on the first (mutated) output because it's part of a tuple.
+        # Instead, we expect the (a!) argument to not be returned.
+        assert len(mutable_returns) == 0 or len(immutable_returns) == 0, (
+            f"NativeFunctions must have either only mutable returns, or only immutable returns. Found: {str(self)}"
+        )
+        for ret in mutable_returns:
+            assert any(ret.annotation == arg.annotation for arg in out_and_self), (
+                'All mutable returns must be aliased either to a keyword argument, or to "self". '
+                "Did you forget to mark an out argument as keyword-only?"
+            )
+        if self.arguments.out:
+            # out= ops that return their mutable inputs are only really useful for method chaining.
+            # And method chaining is only really useful if the thing you're returning is a plain Tensor.
+            # So ideally, we'd enforce that out= ops with a single plain mutable tensor should return the tensor,
+            # and all other types of out= op schemas should return void.
+            # There are a bunch of existing out= ops that return tuples of tensors though, so we're stuck with allowing that.
+            if any(a.type != BaseType(BaseTy.Tensor) for a in self.arguments.out):
+                assert len(self.returns) == 0, (
+                    "out= ops that accept tensor lists as out arguments "
+                )
+                "are expected to have no return type (since you can't do method chaining on them)"
+            else:
+                # mutable keyword arguments whose name has _scratch_ prefix are
+                # scratch tensors for memory planning and should not be returned
+                assert len(
+                    [
+                        arg
+                        for arg in self.arguments.out
+                        if not arg.name.startswith("_scratch_")
+                    ]
+                ) == len(self.returns), (
+                    "Must return as many arguments as there are out arguments, or no return at all"
+                )
+
+        if self.name.name.inplace:
+            self_a = self.arguments.self_arg
+            assert (
+                self_a
+                and self_a.argument.annotation
+                and self_a.argument.annotation.is_write
+            )
+            if self_a.argument.type == BaseType(BaseTy.Tensor):
+                # All inplace ops with an ordinary `Tensor self` argument should return self,
+                # to allow for method chaining.
+                assert (
+                    len(self.returns) == 1
+                    and self.returns[0].annotation == self_a.argument.annotation
+                )
+            else:
+                # You can't method chain on non-tensor self arguments though (like a list[Tensor])
+                # so in all other cases we expect the return type to be none.
+                assert len(self.returns) == 0
+
+        if self.arguments.tensor_options is not None:
+            assert self.kind() == SchemaKind.functional, (
+                "Found an operator that is not functional or out variant, but has tensor options arguments."
+                "This is not allowed- tensor options arguments are only allowed for factory functions."
+                f"schema: {str(self)}"
+            )
+        if self.is_functional_fn():
+            assert self.kind() == SchemaKind.functional, (
+                "Found an operator that is not functional, but its overload contains the string 'functional'."
+                "This is a special keyword in the codegen, please use a different overload name."
+                f"schema: {str(self)}"
+            )
+
+    def is_functional_fn(self) -> bool:
+        return "functional" in self.name.overload_name
+
+    def is_out_fn(self) -> bool:
+        # Note [is_out_fn]
+        #
+        # out functions are the variants which take an explicit out= argument
+        # to populate into.  We need to know if a schema corresponds to an
+        # out function for several reasons:
+        #
+        #   - They codegen differently in C++ API
+        #       - codegen to at::add_out rather than at::add
+        #       - out argument is moved to front of C++ argument list
+        #
+        # out functions are DEFINED to be any function with a keyword-only
+        # argument that is mutable.  In principle, this could lead to a
+        # false positive if you define a function that mutates a
+        # kwarg only argument, but this isn't the "true" output of this
+        # function.  A more robust definition that would work in this
+        # case would also look at:
+        #
+        #   - The output types.  Out functions take in the arguments
+        #     they mutate and then return them again; this is sort
+        #     of "definitionally" what makes something an out function.
+        #     Historically, we DO check this for consistency.
+        #   - Correspondence with pure variant.  An out function
+        #     should have a signature equivalent to its pure variant,
+        #     but just with extra kwargs for the output elements.  This
+        #     is difficult to actually check for and historically
+        #     we only do this check in tools/
+        return bool(self.arguments.out)
+
+    def kind(self) -> SchemaKind:
+        """
+        What kind of schema is this?  A functional schema is one
+        that returns a newly allocated output; an inplace schema
+        modifies the self argument inplace; an out schema writes
+        the result into an explicitly provided out argument.
+        """
+        is_out = bool(self.arguments.out)
+        is_scratch = bool(
+            [arg for arg in self.arguments.out if arg.name.startswith("_scratch_")]
+        )
+        is_inplace = self.name.name.inplace
+        is_mutable = any(
+            a.annotation is not None and a.annotation.is_write
+            for a in self.arguments.post_self_positional
+        )
+        assert not (is_out and is_inplace)
+        # out= and inplace schemas can also have post_self_positional mutable args,
+        # but we give precedence to out= and inplace when deciding the schema kind.
+        # Tradeoff: we probably don't want to have to teach codegen that looks at inplace ops
+        # to also worry about mutable post_self_positional arguments,
+        # but it seems like a much bigger lift to classify them has having a new schema kind.
+        # The number of ops that fit in this strange category is small enough that
+        # we can probably manually write code for them instead of forcing the codegen to handle them.
+        if is_inplace:
+            return SchemaKind.inplace
+        elif is_scratch:
+            assert is_out, (
+                "invariant: all scratch operators are expected to be out= operators too"
+            )
+            return SchemaKind.scratch
+        elif is_out:
+            assert not is_scratch, (
+                "We should not categorize a scratch op as an out variant. Check if the order of if statements are expected!"
+            )  # noqa: B950
+            return SchemaKind.out
+        elif is_mutable:
+            return SchemaKind.mutable
+        else:
+            return SchemaKind.functional
+
+    # For every return:
+    # - If the return aliases an input, we return the input name
+    # - Otherwise, we return None.
+    # If return names were enforced to be consistent with aliasing information, then we wouldn't need this.
+    def aliased_return_names(self) -> list[str | None]:
+        outs: list[str | None] = []
+        for r in self.returns:
+            aliased_args = [
+                a
+                for a in self.arguments.flat_all
+                if a.annotation is not None and a.annotation == r.annotation
+            ]
+            if len(aliased_args) == 0:
+                outs.append(None)
+            elif len(aliased_args) == 1:
+                outs.append(aliased_args[0].name)
+            else:
+                aliased_names = ", ".join(a.name for a in aliased_args)
+                raise AssertionError(
+                    f"Found a return ({r.name})that aliases multiple inputs ({aliased_names})"
+                )
+        return outs
+
+    def signature(
+        self,
+        *,
+        strip_default: bool = False,
+        strip_view_copy_name: bool = False,
+        keep_return_names: bool = False,
+    ) -> FunctionSchema:
+        """
+                Certain schemas are 'related', in that they are simply
+                inplace/out/functional versions of the same function.  This method
+                factors these schemas into the "core" functional signature which
+                is equal across all versions.
+
+                Here is what normalization happens to the schema to convert
+                it to a signature:
+                - The overload name is stripped (name is retained, since
+                  it expresses semantic content about what the function does)
+                - Inplace is set False
+                - Out arguments are stripped
+                - Mutable post_self_positional args are converted to returns
+                - Mutability annotations are stripped  (this is sound
+                  because you cannot overload on mutability annotation)
+                - Return names are stripped since they are not overloadable and
+                  some variants have return names but some not
+                - TensorOptions are dropped
+                  because out= variants of factory functions don't include them
+                  (and we want to be able to pair up factory functions with their out variants)
+
+                Finally, we want to be able to pair up related "view" and their
+                corresponding "view_copy" operators. We do this by optionally
+                stripping the trailing "_copy" from the base name.
+
+                Example of a mutable op before and after:
+
+                f.func (Mutable operator):
+        _fused_moving_avg_obs_fq_helper(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor output, Tensor mask)  # noqa: B950
+
+                f.func (Corresponding functional operator):
+        _fused_moving_avg_obs_fq_helper.functional(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor running_min, Tensor running_max, Tensor scale, Tensor zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor output, Tensor mask, Tensor running_min_out, Tensor running_max_out, Tensor scale_out, Tensor zero_point_out)  # noqa: B950
+
+                f.func.signature() output:
+        _fused_moving_avg_obs_fq_helper(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor running_min, Tensor running_max, Tensor scale, Tensor zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor)  # noqa: B950
+        """
+
+        def strip_ret_annotation(r: Return) -> Return:
+            return Return(
+                name=r.name if keep_return_names else None,
+                type=r.type,
+                annotation=None,
+            )
+
+        base_name = self.name.name.base
+        if strip_view_copy_name:
+            if base_name.endswith("_copy"):
+                base_name = base_name.replace("_copy", "")
+            elif base_name.endswith("_scatter"):
+                base_name = base_name.replace("scatter", "inverse")
+
+        # find mutable inputs that are not originally returned, and convert them to returns
+        returns_from_mutable_inputs = tuple(
+            # When we're grouping functions we strip the return names,
+            # but when we're generating the actual functional variants then we follow
+            # a convention for what to name the returns
+            Return(
+                name=f"{a.name}_out" if keep_return_names else None,
+                type=a.type,
+                annotation=None,
+            )
+            for a in itertools.chain(
+                # Order is important here (otherwise e.g. inplace with mutable args
+                # and out= with mutable args won't have the same signature)
+                (
+                    [self.arguments.self_arg.argument]
+                    if self.arguments.self_arg is not None
+                    else []
+                ),
+                self.arguments.out,
+                self.arguments.post_self_positional,
+            )
+            if a.annotation is not None
+            and a.annotation.is_write
+            and not any(a.annotation == r.annotation for r in self.returns)
+        )
+        original_returns = tuple(map(strip_ret_annotation, self.returns))
+        # Ordering is important here. We expect the "mutable input" returns to come last.
+        returns = original_returns + returns_from_mutable_inputs
+
+        args_sig = self.arguments.signature(strip_default=strip_default)
+        # See Note [bernoulli.p schema]
+        if str(self.name) == "bernoulli.p":
+            args_sig = Arguments.parse(str(args_sig).replace("float p", "float p=0.5"))
+
+        return FunctionSchema(
+            name=OperatorName(
+                name=BaseOperatorName(
+                    base=base_name,
+                    inplace=False,
+                    dunder_method=self.name.name.dunder_method,
+                ),
+                overload_name="",  # stripped
+            ),
+            arguments=args_sig,
+            returns=returns,
+        )
+
+    def view_signature(self) -> FunctionSchema:
+        return self.signature(strip_view_copy_name=True)
+
+    def with_name(self, name: OperatorName) -> FunctionSchema:
+        return FunctionSchema(
+            name=name,
+            arguments=self.arguments,
+            returns=self.returns,
+        )
+
+    @property
+    def modifies_arguments(self) -> bool:
+        return self.kind() in [SchemaKind.inplace, SchemaKind.out, SchemaKind.mutable]
+
+    def has_symint(self) -> bool:
+        return self.arguments.has_symint_arg()
+
+    def __str__(self) -> str:
+        all_arguments_str = str(self.arguments)
+        if len(self.returns) == 1:
+            returns = str(self.returns[0])  # omit parentheses
+        else:
+            returns = "(" + ", ".join(map(str, self.returns)) + ")"
+        return f"{self.name}({all_arguments_str}) -> {returns}"
+
+
+# Here is the rest of the data model, described more briefly.
+
+
+# Simplified version for what actually shows up in built-ins.
+# Look at alias_info.h for expanded syntax.  If you need the structure,
+# you also need to make this structure recursive so it can be lined
+# up with the type components too.  For primitives this isn't really
+# necessary
+@dataclass(frozen=True)
+class Annotation:
+    # Typically only has one element.  Not actually a set so
+    # we can conveniently assume it is canonically ordered
+    alias_set: tuple[str, ...]
+    is_write: bool
+    alias_set_after: tuple[str, ...]
+
+    @staticmethod
+    def parse(ann: str) -> Annotation:
+        # TODO: implement a proper parser if this gets more ugly
+        # Regex Explanation:
+        # Example: "a! -> a|b"
+        # Group #1: alias before optional '|', required. Matches the first
+        #   character 'a' in the example
+        # Group #2: optional alias set after optional '|', matches empty string
+        #   in the example
+        # Group #3: optional "is write" flag, matches '!' in the example.
+        # Group #4: optional section containing arrow, matches " -> a|b" in the
+        #   example.
+        # Group #5: optional alias after set, supports wildcard, matches "a|b"
+        #   in the example.
+        # Group #6: optional sub-section of alias after set, matches "|b" in the
+        #   example.
+        m = re.match(r"^([a-z])(\|[a-z])*(!?)( -> (\*|[a-z](\|[a-z])*))?$", ann)
+
+        assert m is not None, f"unrecognized alias annotation {ann}"
+        before_alias = m.group(1) + (m.group(2) if m.group(2) else "")
+        alias_set = tuple(before_alias.split("|"))
+        is_write = m.group(3) == "!"
+        assert not (is_write and len(alias_set) > 1), (
+            f"alias set larger than 1 is not mutable, got {ann} instead."
+        )
+        after_set = tuple(m.group(5).split("|")) if m.group(5) else ()
+        assert not (len(before_alias) > 1 and len(after_set) > 1), (
+            f"before alias set and after alias set cannot be larger than 1 at the same time, got {ann} instead."
+        )
+        r = Annotation(
+            alias_set=alias_set, is_write=is_write, alias_set_after=after_set
+        )
+        assert str(r) == ann, f"{r} != {ann}"
+        return r
+
+    def __str__(self) -> str:
+        alias_set = "|".join(self.alias_set)
+        if self.is_write:
+            alias_set = f"{alias_set}!"
+        alias_set_after = "|".join(self.alias_set_after)
+        if alias_set_after:
+            alias_set = f"{alias_set} -> {alias_set_after}"
+        return alias_set
+
+
+# The base class for the type system.  This is also loosely modeled
+# off of jit_type.h, but we've simplified the hierarchy to focus
+# in on the aspects of the type system that matter for code generation
+# (for example, there's no SingleElementType subclass anymore).
+# You never actually construct a Type; usually it's going to be one
+# of the subclasses.  If Python had ADTs this would be one!
+@dataclass(frozen=True)
+class Type:
+    @staticmethod
+    def parse(t: str) -> Type:
+        r = Type._parse(t)
+        assert str(r) == t, f"{r} != {t}"
+        return r
+
+    @staticmethod
+    def _parse(t: str) -> Type:
+        m = re.match(r"^(.+)\?$", t)
+        if m is not None:
+            return OptionalType(Type.parse(m.group(1)))
+        m = re.match(r"^(.+)\[([0-9]+)?\]$", t)
+        if m is not None:
+            size = int(m.group(2)) if m.group(2) is not None else None
+            return ListType(elem=Type.parse(m.group(1)), size=size)
+
+        # '__torch__.torch.classes.' is the prefix for custom class
+        m = re.match(r"^__torch__\.torch\.classes\.([a-zA-Z0-9_.]+)$", t)
+        if m is not None:
+            return CustomClassType(m.group(1))
+        try:
+            return BaseType(BaseTy[t])
+        except KeyError as e:
+            raise RuntimeError(f"unrecognized type {t}") from e
+
+    def __str__(self) -> str:
+        raise NotImplementedError
+
+    # WARNING: These concepts are not very well-defined.  For example,
+    # is "int?" nullable? How about "int?[]".  They are defined
+    # so we can conveniently generate legacy Declarations.yaml but
+    # really we should probably just remove these at some point
+
+    def is_base_ty_like(self, base_ty: BaseTy) -> bool:
+        raise NotImplementedError
+
+    def is_tensor_like(self) -> bool:
+        return self.is_base_ty_like(BaseTy.Tensor)
+
+    def is_generator_like(self) -> bool:
+        return self.is_base_ty_like(BaseTy.Generator)
+
+    def is_symint_like(self) -> bool:
+        return self.is_base_ty_like(BaseTy.SymInt)
+
+    def is_nullable(self) -> bool:
+        raise NotImplementedError
+
+    def is_list_like(self) -> ListType | None:
+        raise NotImplementedError
+
+
+# Base types are simple, atomic types with no further structure
+class BaseTy(Enum):
+    Generator = auto()
+    ScalarType = auto()
+    Tensor = auto()
+    int = auto()
+    Dimname = auto()
+    DimVector = auto()
+    float = auto()
+    str = auto()
+    bool = auto()
+    Layout = auto()
+    Device = auto()
+    DeviceIndex = auto()
+    Scalar = auto()
+    MemoryFormat = auto()
+    QScheme = auto()
+    Storage = auto()
+    Stream = auto()
+    SymInt = auto()
+    SymBool = auto()
+    GraphModule = auto()
+
+
+@dataclass(frozen=True)
+class BaseType(Type):
+    name: BaseTy
+
+    def __str__(self) -> str:
+        return f"{self.name.name}"
+
+    def is_base_ty_like(self, base_ty: BaseTy) -> bool:
+        return self.name == base_ty
+
+    def is_nullable(self) -> bool:
+        return False
+
+    def is_list_like(self) -> ListType | None:
+        return None
+
+    def is_symint_like(self) -> bool:
+        return self.name == BaseTy.SymInt
+
+
+# Optional types may be specified, or may also be validly given None
+@dataclass(frozen=True)
+class OptionalType(Type):
+    elem: Type
+
+    def __str__(self) -> str:
+        return f"{self.elem}?"
+
+    def is_base_ty_like(self, base_ty: BaseTy) -> bool:
+        return self.elem.is_base_ty_like(base_ty)
+
+    def is_symint_like(self) -> bool:
+        return self.elem.is_symint_like()
+
+    def is_nullable(self) -> bool:
+        return True
+
+    def is_list_like(self) -> ListType | None:
+        return self.elem.is_list_like()
+
+
+# A type representing a PyTorch custom class
+@dataclass(frozen=True)
+class CustomClassType(Type):
+    class_name: str
+
+    def __str__(self) -> str:
+        """
+        Return the class name will prefix __torch__.torch.classes
+        """
+        return f"__torch__.torch.classes.{self.class_name}"
+
+    def is_base_ty_like(self, base_ty: BaseTy) -> bool:
+        return False
+
+    def is_symint_like(self) -> bool:
+        return False
+
+    def is_nullable(self) -> bool:
+        """
+        Assume a custom class is not nullable.
+        """
+        return False
+
+    def is_list_like(self) -> ListType | None:
+        return None
+
+
+# List types specify that we may have multiples of an element.  We
+# also support explicit sizes on list types, but these have
+# some nontrivial semantics!  (However, for C++ API purposes, explicit
+# sizes are mostly erased from the type system.)
+#
+# DANGER WILL ROBINSON: C++ elaboration depends on elem type; e.g.,
+# int[] elaborates differently than bool[3]!
+@dataclass(frozen=True)
+class ListType(Type):
+    elem: Type
+    size: int | None
+
+    def __str__(self) -> str:
+        size = f"{self.size}" if self.size else ""
+        return f"{self.elem}[{size}]"
+
+    def is_base_ty_like(self, base_ty: BaseTy) -> bool:
+        return self.elem.is_base_ty_like(base_ty)
+
+    def is_symint_like(self) -> bool:
+        return self.elem.is_symint_like()
+
+    def is_nullable(self) -> bool:
+        return self.elem.is_nullable()
+
+    def is_list_like(self) -> ListType | None:
+        return self
+
+
+@dataclass(frozen=True)
+class Argument:
+    # NB: I didn't put kwarg_only as a boolean field here, unlike
+    # c10::Argument, so that printing works correctly
+
+    name: str
+    type: Type
+    default: str | None
+
+    # The semantics of the annotation field are a little strange.
+    #
+    # Alias annotations parametrize Tensors (since Tensors are the only things
+    # that can alias.)  This motivates why I write Tensor(a!)?  (and not, for
+    # example, Tensor?(a!)), because the (a!) describes aliasing on the tensor,
+    # which may be optional (i.e., the alias annotation should bind first to
+    # Tensor, before the optional postfix annotation).
+    #
+    # However, despite being a property of Tensor, we (and c10::Argument)
+    # store the annotation at the top level of the Argument, rather than
+    # inside the embedded Tensor type.  In the C++ version of this
+    # class, we then go through great lengths to mimic the type
+    # structure in the annotation structure so we can correlate
+    # annotations with types.
+    #
+    # Now, it turns out, in all applications in code generation, the
+    # structure of annotated types is very simple.  So we just hard
+    # code it here.  But if we ever do get anything more complex, this
+    # model will have to change!
+    annotation: Annotation | None
+
+    @property
+    def alias_info(self) -> Annotation | None:
+        return self.annotation
+
+    @staticmethod
+    def parse(arg: str) -> Argument:
+        name: str
+        default: str | None
+        assert " " in arg, f"illegal argument '{arg}'"
+        if "=" in arg:
+            assert arg.count("=") == 1, f"illegal argument with default value: '{arg}'"
+            type_and_annot_and_name, default = arg.split("=")
+            type_and_annot, name = type_and_annot_and_name.rsplit(" ", 1)
+            name_and_default = f"{name}={default}"
+        else:
+            type_and_annot, name_and_default = arg.rsplit(" ", 1)
+            name = name_and_default
+            default = None
+        # TODO: deduplicate annotation matching with Return
+        match = re.match(r"Tensor\((.+)\)(.*)", type_and_annot)
+        annotation: Annotation | None
+        if match:
+            # If you update this, make sure the __str__ still works too
+            assert match.group(2) in [
+                "",
+                "?",
+                "[]",
+            ], "unrecognized alias analysis form with Tensor"
+            type_s = "Tensor" + match.group(2)
+            annotation = Annotation.parse(match.group(1))
+        else:
+            type_s = type_and_annot
+            annotation = None
+        type = Type.parse(type_s)
+        r = Argument(
+            name=name,
+            type=type,
+            default=default,
+            annotation=annotation,
+        )
+        assert str(r) == arg, f"{str(r)} != {arg}"
+        return r
+
+    @property
+    def is_write(self) -> bool:
+        return self.annotation is not None and self.annotation.is_write
+
+    def __str__(self) -> str:
+        type = f"{self.type}"
+        if self.annotation:
+            assert type in ["Tensor", "Tensor?", "Tensor[]"]
+            type = type.replace("Tensor", f"Tensor({self.annotation})")
+        if self.name is None:
+            return type
+        else:
+            mb_default = ""
+            if self.default:
+                mb_default = f"={self.default}"
+            return f"{type} {self.name}{mb_default}"
+
+
+@dataclass(frozen=True)
+class Return:
+    name: str | None
+    type: Type
+    annotation: Annotation | None
+
+    @property
+    def alias_info(self) -> Annotation | None:
+        return self.annotation
+
+    @staticmethod
+    def parse(arg: str) -> Return:
+        name: str | None
+        if " " in arg:
+            type_and_annot, name = arg.rsplit(" ", 1)
+        else:
+            type_and_annot = arg
+            name = None
+        match = re.match(r"Tensor\((.+)\)(.*)", type_and_annot)
+        annotation: Annotation | None
+        if match:
+            # If you update this, make sure the __str__ still works too
+            assert match.group(2) in [
+                "",
+                "?",
+                "[]",
+            ], "unrecognized alias analysis form with Tensor"
+            type_s = "Tensor" + match.group(2)
+            annotation = Annotation.parse(match.group(1))
+        else:
+            type_s = type_and_annot
+            annotation = None
+        type = Type.parse(type_s)
+        r = Return(
+            name=name,
+            type=type,
+            annotation=annotation,
+        )
+        assert str(r) == arg, f"{str(r)} != {arg}"
+        return r
+
+    @property
+    def is_write(self) -> bool:
+        return self.annotation is not None and self.annotation.is_write
+
+    def __str__(self) -> str:
+        type = f"{self.type}"
+        if self.annotation:
+            assert type in ["Tensor", "Tensor?", "Tensor[]"]
+            type = type.replace("Tensor", f"Tensor({self.annotation})")
+        if self.name is None:
+            return type
+        else:
+            return f"{type} {self.name}"
+
+
+# Represents the self argument for functions that may be methods
+@dataclass(frozen=True)
+class SelfArgument:
+    argument: Argument
+
+
+# Bundle of arguments that represent a TensorOptions.  This is mostly
+# relevant for the public C++ API but we bake it into the core data
+# model because other APIs often have to interact with it
+@dataclass(frozen=True)
+class TensorOptionsArguments:
+    dtype: Argument
+    layout: Argument
+    device: Argument
+    pin_memory: Argument
+
+    def all(self) -> Sequence[Argument]:
+        return [self.dtype, self.layout, self.device, self.pin_memory]
+
+
+@dataclass(frozen=True)
+class Arguments:
+    # pre_self_positional is usually empty, but is notably non-empty
+    # for where.self, where the condition argument comes before the
+    # self argument
+    pre_self_positional: tuple[Argument, ...]
+    self_arg: SelfArgument | None
+    post_self_positional: tuple[Argument, ...]
+
+    pre_tensor_options_kwarg_only: tuple[Argument, ...]
+    tensor_options: TensorOptionsArguments | None
+    # post_tensor_options is typically memory format, which should be
+    # part of tensor options but isn't right now, and is usually
+    # placed after the tensor options arguments
+    post_tensor_options_kwarg_only: tuple[Argument, ...]
+
+    # Unlike in the previous codegen, we have factored out 'out' arguments
+    # in the canonical representation, removing them from kwarg
+    # arguments.  This choice is justified by numerous downstream
+    # transformations which treat out arguments specially; additionally,
+    # you can see that canonicity is not violated!
+    out: tuple[Argument, ...]  # these are also kwarg-only
+
+    @property
+    def flat_non_out(self) -> Sequence[Argument]:
+        ret: list[Argument] = []
+        ret.extend(self.flat_positional)
+        ret.extend(self.flat_kwarg_only)
+        return ret
+
+    @property
+    def flat_positional(self) -> Sequence[Argument]:
+        ret: list[Argument] = []
+        ret.extend(self.pre_self_positional)
+        if self.self_arg is not None:
+            ret.append(self.self_arg.argument)
+        ret.extend(self.post_self_positional)
+        return ret
+
+    @property
+    def post_self_positional_mutable(self) -> Sequence[Argument]:
+        return [a for a in self.post_self_positional if a.is_write]
+
+    # NB: doesn't contain out arguments
+    @property
+    def flat_kwarg_only(self) -> Sequence[Argument]:
+        ret: list[Argument] = []
+        ret.extend(self.pre_tensor_options_kwarg_only)
+        if self.tensor_options is not None:
+            ret.extend(self.tensor_options.all())
+        ret.extend(self.post_tensor_options_kwarg_only)
+        return ret
+
+    @property
+    def flat_all(self) -> Sequence[Argument]:
+        ret: list[Argument] = []
+        ret.extend(self.flat_positional)
+        ret.extend(self.flat_kwarg_only)
+        ret.extend(self.out)
+        return ret
+
+    @property
+    def non_out(
+        self,
+    ) -> Sequence[Argument | SelfArgument | TensorOptionsArguments]:
+        ret: list[Argument | SelfArgument | TensorOptionsArguments] = []
+        ret.extend(self.positional)
+        ret.extend(self.kwarg_only)
+        return ret
+
+    @property
+    def positional(self) -> Sequence[Argument | SelfArgument]:
+        ret: list[Argument | SelfArgument] = []
+        ret.extend(self.pre_self_positional)
+        if self.self_arg is not None:
+            ret.append(self.self_arg)
+        ret.extend(self.post_self_positional)
+        return ret
+
+    @property
+    def kwarg_only(self) -> Sequence[Argument | TensorOptionsArguments]:
+        ret: list[Argument | TensorOptionsArguments] = []
+        ret.extend(self.pre_tensor_options_kwarg_only)
+        if self.tensor_options is not None:
+            ret.append(self.tensor_options)
+        ret.extend(self.post_tensor_options_kwarg_only)
+        return ret
+
+    @property
+    def all(self) -> Sequence[Argument | SelfArgument | TensorOptionsArguments]:
+        ret: list[Argument | SelfArgument | TensorOptionsArguments] = []
+        ret.extend(self.positional)
+        ret.extend(self.kwarg_only)
+        ret.extend(self.out)
+        return ret
+
+    def mutable_arg_names(self) -> list[str]:
+        return [
+            a.name
+            for a in self.flat_all
+            if a.annotation is not None and a.annotation.is_write
+        ]
+
+    def has_tensor_arg(self) -> bool:
+        return any(a.type.is_tensor_like() for a in self.flat_non_out)
+
+    def has_symint_arg(self) -> bool:
+        return any(a.type.is_symint_like() for a in self.flat_non_out)
+
+    def has_generator_arg(self) -> bool:
+        return any(a.type.is_generator_like() for a in self.flat_non_out)
+
+    def signature(self, *, strip_default: bool = False) -> Arguments:
+        # dataclasses.replace could be used here, but it is less
+        # type safe so for now I've opted to type everything out
+        def strip_arg_annotation(a: Argument) -> Argument:
+            return Argument(
+                name=a.name,
+                type=a.type,
+                default=a.default if not strip_default else None,
+                annotation=None,
+            )
+
+        return Arguments(
+            pre_self_positional=tuple(
+                map(strip_arg_annotation, self.pre_self_positional)
+            ),
+            self_arg=(
+                SelfArgument(strip_arg_annotation(self.self_arg.argument))
+                if self.self_arg is not None
+                else None
+            ),
+            post_self_positional=tuple(
+                map(strip_arg_annotation, self.post_self_positional)
+            ),
+            # Since TensorOptions are dropped, the post_tensor_options_kwargs are
+            # converted to pre_tensor_options_kwargs
+            pre_tensor_options_kwarg_only=tuple(
+                map(strip_arg_annotation, self.pre_tensor_options_kwarg_only)
+            )
+            + tuple(map(strip_arg_annotation, self.post_tensor_options_kwarg_only)),
+            # TensorOptions are dropped in signature,
+            # so we can pair factory functions with their out= variants.
+            tensor_options=None,
+            post_tensor_options_kwarg_only=(),
+            # out arguments are dropped in signature
+            out=(),
+        )
+
+    def remove_self_annotation(self) -> Arguments:
+        assert self.self_arg is not None
+        return dataclasses.replace(
+            self,
+            self_arg=SelfArgument(
+                dataclasses.replace(self.self_arg.argument, annotation=None)
+            ),
+        )
+
+    def with_out_args(self, outs: list[Argument]) -> Arguments:
+        assert len(self.out) == 0
+        return dataclasses.replace(
+            self,
+            out=tuple(outs),
+        )
+
+    @staticmethod
+    def _preparse(args: str) -> tuple[list[Argument], list[Argument], list[Argument]]:
+        positional: list[Argument] = []
+        kwarg_only: list[Argument] = []
+        out: list[Argument] = []
+        arguments_acc = positional
+
+        # TODO: Use a real parser here; this will get bamboozled
+        # by signatures that contain things like std::array (note the space)
+        for arg in args.split(", "):
+            if not arg:
+                continue
+            if arg == "*":
+                assert arguments_acc is positional, (
+                    "invalid syntax: kwarg-only specifier * can only occur once"
+                )
+                arguments_acc = kwarg_only
+                continue
+            parg = Argument.parse(arg)
+            # Currently, we rely directly on the invariant that there are NO
+            # kwarg-only mutating arguments.  If you want to relax this,
+            # we will need a more semantic way of matching that takes
+            # into account return arguments.  In that case, you will have
+            # to manage out computation a level up, in FunctionSchema.  See Note
+            # [is_out_fn]
+            if parg.annotation is not None and parg.annotation.is_write:
+                if arguments_acc is positional:
+                    pass  # do nothing
+                elif arguments_acc is kwarg_only:
+                    arguments_acc = out
+            else:
+                assert arguments_acc is not out
+            arguments_acc.append(parg)
+
+        return positional, kwarg_only, out
+
+    @staticmethod
+    def parse(args: str) -> Arguments:
+        """
+        Input: 'int x, int y, int z'
+        """
+
+        # We do this in two phases.  First we parse into three
+        # main categories: positional, kwarg_only, out.
+        # Then, we reparse positional and kwarg_only to separate
+        # out the self argument and tensor options arguments.
+
+        positional, kwarg_only, out = Arguments._preparse(args)
+
+        # Split self argument
+        self_ix = None
+        for i, a in enumerate(positional):
+            if a.name == "self":
+                self_ix = i
+                break
+        pre_self_positional: list[Argument]
+        self_arg: SelfArgument | None
+        post_self_positional: list[Argument]
+        if self_ix is not None:
+            pre_self_positional = positional[:self_ix]
+            self_arg = SelfArgument(positional[self_ix])
+            post_self_positional = positional[self_ix + 1 :]
+        else:
+            pre_self_positional = []
+            self_arg = None
+            post_self_positional = positional
+
+        # Group tensor options arguments
+        pre_tensor_options_kwarg_only: list[Argument] = []
+        tensor_options: TensorOptionsArguments | None = None
+        post_tensor_options_kwarg_only: list[Argument] = []
+        kwarg_only_acc = pre_tensor_options_kwarg_only
+
+        def pred(name: str, ty: Type) -> Callable[[Argument], bool]:
+            return lambda a: a.name == name and a.type in [ty, OptionalType(ty)]
+
+        predicates = [  # order matters
+            pred("dtype", Type.parse("ScalarType")),
+            pred("layout", Type.parse("Layout")),
+            pred("device", Type.parse("Device")),
+            pred("pin_memory", Type.parse("bool")),
+        ]
+
+        i = 0
+        while i < len(kwarg_only):
+            # If there is enough space...
+            if i <= len(kwarg_only) - len(predicates):
+                # And the next len(predicates) arguments look like TensorOptions arguments
+                if all(
+                    p(a)
+                    for p, a in zip(predicates, kwarg_only[i : i + len(predicates)])
+                ):
+                    assert kwarg_only_acc is pre_tensor_options_kwarg_only
+                    # Group them together as one argument
+                    tensor_options = TensorOptionsArguments(
+                        dtype=kwarg_only[i],
+                        layout=kwarg_only[i + 1],
+                        device=kwarg_only[i + 2],
+                        pin_memory=kwarg_only[i + 3],
+                    )
+                    i += len(predicates)
+                    kwarg_only_acc = post_tensor_options_kwarg_only
+                    continue
+            kwarg_only_acc.append(kwarg_only[i])
+            i += 1
+
+        return Arguments(
+            pre_self_positional=tuple(pre_self_positional),
+            self_arg=self_arg,
+            post_self_positional=tuple(post_self_positional),
+            pre_tensor_options_kwarg_only=tuple(pre_tensor_options_kwarg_only),
+            tensor_options=tensor_options,
+            post_tensor_options_kwarg_only=tuple(post_tensor_options_kwarg_only),
+            out=tuple(out),
+        )
+
+    def __str__(self) -> str:
+        all_arguments: list[str] = []
+        all_arguments.extend(map(str, self.flat_positional))
+        if self.flat_kwarg_only or self.out:
+            all_arguments.append("*")
+        all_arguments.extend(map(str, self.flat_kwarg_only))
+        all_arguments.extend(map(str, self.out))
+        return ", ".join(all_arguments)
+
+    def __post_init__(self) -> None:
+        # TODO: These invariants are weirdly asymmetric?
+        # TODO: Fancier types?
+        if self.self_arg is None:
+            assert not self.pre_self_positional
+        if self.tensor_options is None:
+            assert not self.post_tensor_options_kwarg_only
+
+        # We don't allow any of the following to have argument annotations,
+        # to keep things simple.
+        mutable_pre_self_positionals = [
+            a
+            for a in self.pre_self_positional
+            if a.annotation is not None and a.annotation.is_write
+        ]
+        assert len(mutable_pre_self_positionals) == 0, (
+            "mutable pre_self_positional arguments are not currently supported in the schema"
+        )
+
+
+# Names that validly are __iXXX__ indicating inplace operations.
+# Taken from https://www.python.org/dev/peps/pep-0203/#new-methods
+# NB: PyTorch hasn't actually implemented all of these
+AUGMENTED_ASSIGNMENT_NAMES = [
+    "add",
+    "sub",
+    "mul",
+    "div",
+    "mod",
+    "pow",
+    "lshift",
+    "rshift",
+    "and",
+    "xor",
+    "or",
+]
+
+
+# A BaseOperatorName is what we think of the operator name, without
+# the overload name.  Unusually, we don't represent this as just a
+# string; instead, we directly represent a few important semantic
+# bits of information we derive from the string: namely whether
+# or not it's inplace (add_) and whether or not it's a double-underscore
+# method (__add__)
+@dataclass(frozen=True)
+class BaseOperatorName:
+    base: str
+    inplace: bool
+    dunder_method: bool
+    # Note [Overload Ambiguity With Functional Variants]
+    # A handful of operators have both a "mutable" and a "functional" variant.
+    # (native_batch_norm is a good example, although this isn't the case today).
+    # For those operators, the mutable and functional variant take in the same set of
+    # arguments, but have different alias annotations.
+    # this makes it ambiguous when you try to resolve an OverloadPacket into an overload,
+    # given a set of input arguments.
+    #
+    # So instead of making the "functional" variant in this case a real overload, e.g:
+    #   native_batch_norm (mutable variant)
+    #   native_batch_norm.functional (functional variant)
+    # we make it a new base operator,
+    #   native_batch_norm_functional (functional variant)
+    #
+    # In an ideal world, we would probably invert this so the operators were:
+    #   native_batch_norm.mutable (mutable variant)
+    #   native_batch_norm (functional variant)
+    #
+    # Doing that is BC-breaking though, so we're stuck with the above modeling.
+    functional_overload: bool = False
+
+    # NB: We don't officially support namespace in FunctionSchema, we treat this prefix
+    # as part of the base operator name, for __str__() to consume.
+    # The canonical input (from the rest of the infra) will not contain namespace, but
+    # we have a usecase in ExecuTorch where we want to support BaseOperatorName with namespace.
+    namespace: Optional[str] = None
+
+    @staticmethod
+    def parse(op: str) -> BaseOperatorName:
+        assert op != ""
+        assert not op.endswith("_out"), (
+            "_out suffix is reserved and not permitted for operator names; "
+            "did you mean to specify an out overload name instead?"
+        )
+        # Extract namespace out. Base operator name may or may not contain namespace.
+        # E.g., aten::__lshift__ is a valid base operator name, __lshift__ is also valid.
+        # We want to split the namespace out from the base operator name.
+        match = re.match(r"^(?:(.*)::)?(.*)$", op)
+        namespace = match.group(1) if match else ""
+        op_without_ns = match.group(2) if match else op
+        m = re.match(r"^__([^_]+)__$", op_without_ns)
+        if m is not None:
+            dunder_method = True
+            base = m.group(1)
+            if any(base == f"i{n}" for n in AUGMENTED_ASSIGNMENT_NAMES):
+                inplace = True
+                base = base[1:]
+            else:
+                inplace = False
+                # temporary, this is not intrinsically true but
+                # has been historically true for dunder methods
+                # we support  (but, if we ever got, say, __int__, this would
+                # be wrong!)
+                assert base[0] != "i"
+        else:
+            dunder_method = False
+            base = op_without_ns
+            if base[-1] == "_":
+                inplace = True
+                base = base[:-1]
+            else:
+                inplace = False
+
+        # See Note [Overload Ambiguity With Functional Variants]
+        functional_suffix = "_functional"
+        if base.endswith(functional_suffix):
+            functional_overload = True
+            base = base[: -len(functional_suffix)]
+            # This seems complicated and unnecessary, so banning dunder methods
+            # for now on ops that have a functional + mutable variant (like native_batch_norm).
+            assert not dunder_method and not inplace
+        else:
+            functional_overload = False
+
+        r = BaseOperatorName(
+            base=base,
+            inplace=inplace,
+            dunder_method=dunder_method,
+            functional_overload=functional_overload,
+            namespace=namespace,
+        )
+        assert str(r) == op, f"{str(r)} != {op}"
+        return r
+
+    def __str__(self) -> str:
+        namespace_prefix = f"{self.namespace}::" if self.namespace else ""
+        if self.dunder_method:
+            i = "i" if self.inplace else ""
+            return f"{namespace_prefix}__{i}{self.base}__"
+        else:
+            i = (
+                "_"
+                if self.inplace
+                else "_functional"
+                if self.functional_overload
+                else ""
+            )
+            return f"{namespace_prefix}{self.base}{i}"
+
+
+# Operator name is the base operator name along with the (typically not
+# user visible) overload string.
+@dataclass(frozen=True)
+class OperatorName:
+    name: BaseOperatorName
+    overload_name: str
+
+    @staticmethod
+    def parse(op_name: str) -> OperatorName:
+        if "." in op_name:
+            name, overload_name = op_name.split(".", 1)
+        else:
+            name = op_name
+            overload_name = ""
+        r = OperatorName(name=BaseOperatorName.parse(name), overload_name=overload_name)
+        assert str(r) == op_name, f"{str(r)} != {op_name}"
+        return r
+
+    def __str__(self) -> str:
+        if self.overload_name:
+            return f"{self.name}.{self.overload_name}"
+        else:
+            return f"{self.name}"
+
+    # NB: This must be synchronized with the naming scheme in
+    # aten/src/ATen/templates/Operators.h
+    # Given a function schema "aten::op.overload(...)",
+    # If there is no overload name, this returns f"{op}"
+    # If there is an overload name, this returns f"{op}_{overload}"
+    def unambiguous_name(self) -> str:
+        if self.overload_name:
+            return f"{self.name}_{self.overload_name}"
+        else:
+            return f"{self.name}"
+
+    def remove_inplace(self) -> OperatorName:
+        return OperatorName(
+            name=BaseOperatorName(
+                base=self.name.base,
+                inplace=False,
+                dunder_method=self.name.dunder_method,
+            ),
+            overload_name=self.overload_name,
+        )
+
+    def with_overload(self, overload: str) -> OperatorName:
+        return OperatorName(
+            name=BaseOperatorName(
+                base=self.name.base,
+                inplace=False,
+                dunder_method=self.name.dunder_method,
+            ),
+            overload_name=overload,
+        )
+
+
+def gets_generated_out_inplace_wrapper(
+    f: NativeFunction, g: NativeFunctionsGroup, b: BackendIndex
+) -> bool:
+    return (
+        f.func.kind() is not SchemaKind.functional
+        and not b.has_kernel(f)
+        and b.has_kernel(g.functional)
+    )
+
+
+# NativeFunction objects that are views (f.is_view_op returns True)
+# are added into a `NativeFunctionsViewGroup`, which we can use to
+# easily access the generated (optional) view_copy NativeFunction.
+# It's convenient to group them together, so we pair them up in NativeFunctionsViewGroup.
+# See Note [Codegen'd {view}_copy Operators]
+#
+# One property of this representation is that in order for a view-like op to be part of
+# a NativeFunctionsViewGroup, the "aliasing" version of that view op must exist.
+# There's one case where that doesn't happen: we have a non-aliasing `narrow_copy.out` op,
+# but don't have corresponding aliasing `narrow.out` op.
+# This means that `narrow_copy.out` won't appear as a NativeFunctionsViewGroup.
+@dataclass(frozen=True)
+class NativeFunctionsViewGroup:
+    view: NativeFunction
+    # Note: the {view}_copy operator is optional because we currently don't generate copy variants
+    # for all view ops. Notably, we don't generate them for CompositeImplicitAutograd views
+    # (we already get them "for free" through decomposition)
+    view_copy: NativeFunction | None
+    # view_inplace ops are also optional, but every view_inplace op should have out-of-place variant.
+    view_inplace: NativeFunction | None
+
+    def __post_init__(self) -> None:
+        assert self.view.is_view_op
+        if self.view_copy is None:
+            assert not gets_generated_view_copy(self.view), (
+                f"{str(self.view.func.name)} appears to be a new operator that aliases its inputs."
+                " The codegen expects you to add a corresponding operator to native_functions.yaml:"
+                f" {get_view_copy_name(self.view)!s}."
+                " See Note [view_copy NativeFunctions] for details."
+            )
+        else:
+            assert self.view_copy.func.name.name.base.endswith(("_copy", "_scatter"))
+            assert self.view.func.signature() == self.view_copy.func.signature(
+                strip_view_copy_name=True,
+            )
+            assert "view_copy" in self.view_copy.tags, (
+                f"{str(self.view_copy.func.name), str(self.view.tags)} appears to be a view_copy operator. The codegen expects"
+                " view_copy operators to be annotated with the 'view_copy' tag in native_functions.yaml."
+                " See Note [view_copy NativeFunction] for details."
+            )
+        if self.view_inplace is not None:
+            assert self.view.func.signature() == self.view_inplace.func.signature()
+
+        if self.view.has_composite_implicit_autograd_kernel:
+            if self.view_inplace is not None:
+                assert self.view_inplace.has_composite_implicit_autograd_kernel, (
+                    f"{str(self.view.func.name)} and {str(self.view_inplace.func.name)} must either"
+                    " both have CompositeImplicitAutograd kernels, or both not have composite kernels."
+                )
+        if self.view.has_composite_implicit_autograd_nested_tensor_kernel:
+            if self.view_inplace is not None:
+                assert self.view_inplace.has_composite_implicit_autograd_nested_tensor_kernel, (
+                    f"{str(self.view.func.name)} and {str(self.view_inplace.func.name)} must either"
+                    " both have CompositeImplicitAutogradNestedTensor kernels, or both not have composite kernels."
+                )
+
+    def functions(self, *, include_copy: bool = True) -> Iterator[NativeFunction]:
+        yield self.view
+        if self.view_inplace is not None:
+            yield self.view_inplace
+        if self.view_copy is not None and include_copy:
+            yield self.view_copy
+
+    @property
+    def root_name(self) -> str:
+        return self.view.root_name
+
+    @property
+    def composite(self) -> bool:
+        # We currently assert that the "group" is consistent.
+        # If the view op is composite, then its view_inplace op is too.
+        return self.view.has_composite_implicit_autograd_kernel
+
+
+def gets_generated_view_copy(f: NativeFunction) -> bool:
+    # Only aliasing (view) operators get a copy variant.
+    if not f.is_view_op:
+        return False
+    # We don't need to bother generating copy variants for CompositeImplicitAutograd ops,
+    # because we can let them decompose into base view ops.
+    if f.has_composite_implicit_autograd_kernel:
+        return False
+    # We also don't need to generate copy variants for inplace views.
+    if "inplace_view" in f.tags:
+        return False
+    # Assume ops ending in _inverse have manually-defined copy variants
+    # (e.g. slice_inverse() has the copy variant slice_scatter()).
+    # We -could- probably generate these as well, but the codegen will be
+    # slightly different, and hand-writing these few kernels keeps codegen
+    # complexity lower.
+    if f.func.name.name.base.endswith("_inverse"):
+        return False
+    return True
+
+
+# Given a NativeFunction that corresponds to a view op,
+# returns the OperatorName of the corresponding "copy" variant of the op.
+def get_view_copy_name(f: NativeFunction) -> OperatorName:
+    # Right now, when asking for a view op's corresponding "view_copy" name
+    # we assert for sanity that the op is allowed to have a generated view_copy variant.
+    # (We can do this because "gets_generated_view_copy()" tell us which ops get a generated view_copy op).
+    # However, narrow_copy() already exists as an op directly in native_functions.yaml.
+    # I'm hardcoding narrow_copy here for now to maintain the assert,
+    # But we could also just get rid of the assert.
+    list_of_ops_with_explicit_view_copy_operators = ["narrow"]
+    if str(f.func.name) not in list_of_ops_with_explicit_view_copy_operators:
+        assert gets_generated_view_copy(f)
+
+    base_name = f"{f.func.name.name.base}_copy"
+    view_copy_name = OperatorName(
+        name=BaseOperatorName(
+            base=base_name, inplace=False, dunder_method=f.func.name.name.dunder_method
+        ),
+        overload_name=f.func.name.overload_name,
+    )
+    return view_copy_name
+
+
+# Helper functions for parsing argument lists (both inputs and returns)
+
+
+def parse_returns(return_decl: str) -> tuple[Return, ...]:
+    """
+    Input: '()'
+    Output: []
+    """
+    if return_decl == "()":
+        return ()
+    if return_decl[0] == "(" and return_decl[-1] == ")":
+        return_decl = return_decl[1:-1]
+    return tuple(Return.parse(arg) for arg in return_decl.split(", "))
+
+
+# A Precompute instance consists of a map from kernel argument name
+# to the list of Argument instances that should replace that
+# kernel argument in the impl function.
+@dataclass(frozen=True)
+class Precompute:
+    # A map from kernel argument name -> a list of precomputed
+    # elements that replaces/supersedes it.
+    replace: dict[str, list[Argument]]
+    # List of precomputed args added without replacement
+    add: list[Argument]
+
+    @staticmethod
+    def parse(src: object) -> Precompute:
+        assert isinstance(src, list)
+
+        # src is a list of strings of the format:
+        #   {kernel param name} -> {replacement decl}[, {replacement decl}, ...]
+        #   [{add decl}[, {add decl}, ...]]
+        # The last line is optional and contains the precomputed parameters that are
+        # added without replacement.
+        # The other lines are parsed to get the names of which precomputed elements
+        # should replace which kernel arguments.
+        add_args = []
+        if " -> " not in src[-1]:
+            add_list = src[-1].split(",")
+            add_args = [Argument.parse(name.strip()) for name in add_list]
+            src = src[:-1]
+
+        replace = {}
+        for raw_replace_item in src:
+            assert isinstance(raw_replace_item, str)
+            assert " -> " in raw_replace_item, (
+                "precomputed parameters without replacement"
+                " are allowed only in the last line"
+            )
+
+            arg, with_list_raw = raw_replace_item.split(" -> ")
+            assert " " not in arg, (
+                f"illegal kernel param name '{arg}' in precomputed parameters'"
+            )
+            with_list = with_list_raw.split(",")
+            with_list_args = [Argument.parse(name.strip()) for name in with_list]
+            replace[arg] = with_list_args
+
+        r = Precompute(replace=replace, add=add_args)
+        assert r.to_list() == src, "r.to_list() != src"
+        return r
+
+    def __post_init__(self) -> None:
+        # the template parameters are upper so if these are the
+        # same then it is ambiguous
+        for a in self.add:
+            assert a.name.upper() != a.name
+        for args in self.replace.values():
+            for a in args:
+                assert a.name.upper() != a.name
+
+    def to_list(self) -> list[str]:
+        replace_list = []
+        for kernel_param, replacement_params in self.replace.items():
+            replacements = ", ".join(str(param) for param in replacement_params)
+            replace_list.append(f"{kernel_param} -> {replacements}")
+
+        return replace_list
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/native_function_generation.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/native_function_generation.py
new file mode 100644
index 0000000000000000000000000000000000000000..f986c77f8faaaeb5d961082a044ca5f595851136
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/native_function_generation.py
@@ -0,0 +1,651 @@
+from __future__ import annotations
+
+import string
+from collections import defaultdict
+from typing import TYPE_CHECKING
+
+import torchgen.api.dispatcher as dispatcher
+from torchgen.api.translate import translate
+from torchgen.api.types import Binding, DispatcherSignature, Expr
+from torchgen.context import with_native_function
+from torchgen.model import (
+    Annotation,
+    Argument,
+    BackendIndex,
+    BackendMetadata,
+    BaseOperatorName,
+    BaseTy,
+    BaseType,
+    DEFAULT_KERNEL_NAMESPACE,
+    DeviceCheckType,
+    DispatchKey,
+    FunctionSchema,
+    NativeFunction,
+    NativeFunctionsGroup,
+    OperatorName,
+    Return,
+    SchemaKind,
+    Variant,
+)
+from torchgen.utils import concatMap
+
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+
+
+# See Note: [Out ops with functional variants that don't get grouped properly]
+OUT_OPS_THAT_DONT_GET_GROUPED_PROPERLY = [
+    # This has a functional variant, but it's currently marked private.
+    # This function should be marked private as well (*_backward ops aren't exposed to python anyway).
+    "adaptive_avg_pool3d_backward.grad_input",
+    # There's a functional variant, _slow_conv2d_backward.output_mask, that isn't grouped properly.
+    # Maybe we can kill this operator in favor of convolution_backward?
+    "_slow_conv2d_backward.grad_input",
+]
+
+
+# See Note: [Mutable ops that cannot get an out variant]
+MUTABLE_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT = [
+    # should be out=?
+    "_cummax_helper",
+    # should be out=?
+    "_cummin_helper",
+]
+
+# All of these operators don't have any tensor like returns
+FUNCTIONAL_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT = [
+    "_assert_async",  # no return
+    "_assert_async.msg",  # no return
+    "_assert_tensor_metadata",  # no return
+    "_cslt_sparse_mm_search",  # returns an int
+    "_assert_scalar",  # no return
+    "_dimI",  # returns an int
+    "_dimV",  # returns an int
+    "_has_same_storage_numel",  # returns a boolean
+    "_linalg_check_errors",  # no return
+    "_local_scalar_dense",  # returns a Scalar
+    "_nested_tensor_from_mask_left_aligned",  # returns a boolean
+    "_nnz",  # returns an int
+    "_use_cudnn_ctc_loss",  # returns a boolean
+    "_use_cudnn_ctc_loss.Tensor",  # returns a boolean
+    "_validate_compressed_sparse_indices",  # no return
+    "allclose",  # returns a boolean
+    "dense_dim",  # returns an int
+    "equal",  # returns a boolean
+    "is_coalesced",  # returns an boolean
+    "is_pinned",  # returns a boolean
+    "is_same_size",  # returns a boolean
+    "is_set_to",  # returns a boolean
+    "q_per_channel_axis",  # returns an int
+    "q_scale",  # returns a float
+    "q_zero_point",  # returns an int
+    "qscheme",  # returns a QScheme
+    "record_stream",  # no return
+    "sparse_dim",  # returns an int
+    "sym_constrain_range",  # no return
+    "sym_constrain_range_for_size",  # no return
+    "_nested_tensor_storage_offsets",  # returns a vector of ints
+    "_chunk_grad_outputs_efficient_attention",  # returns a bool
+    "_fused_sdp_choice",  # returns an int
+    "_print",  # no return
+    "_sink_tokens",  # no return
+    "_nested_get_ragged_idx",  # returns an int
+]
+
+INPLACE_OPS_THAT_DONT_GET_GROUPED_PROPERLY = [
+    # polygamma and polygamma.out both exist, but have a
+    # pre-self arg (while polygamma_ does not)
+    # We should either fix this schema so it can be grouped properly,
+    # or allow the codegen to generate new functional/out= NativeFunctions for this op
+    # (which would require changing its overload name to prevent overload ambiguity).
+    "polygamma_"
+]
+
+
+# Groups "similar" NativeFunctions together
+# example add.Tensor, add_.Tensor, add.out
+# "similar" NativeFunctions are all expected to have an identical `signature()`,
+# But have differing SchemaKinds.
+def pre_group_native_functions(
+    native_functions: Sequence[NativeFunction],
+) -> dict[FunctionSchema, dict[SchemaKind, NativeFunction]]:
+    pre_grouped_native_functions: dict[
+        FunctionSchema, dict[SchemaKind, NativeFunction]
+    ] = defaultdict(dict)
+    for f in native_functions:
+        d = pre_grouped_native_functions[f.func.signature()]
+        assert f.func.kind() not in d
+        d[f.func.kind()] = f
+    return pre_grouped_native_functions
+
+
+# Returns the out variant overload name given a base function overload name
+def get_expected_out_variant_overload_name(overload_name: str | None) -> str:
+    return "out" if not overload_name else f"{overload_name}_out"
+
+
+# Helper function: given an inplace FunctionSchema, generate its corresponding out= variant
+# Example before:
+#   _add_relu_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!)
+# Example after:
+#   _add_relu.Scalar_out(Tensor self, Scalar other, Scalar alpha=1, *, Tensor(a!) out)
+def self_to_out_signature(func: FunctionSchema) -> FunctionSchema:
+    # Generating an out= schema from an inplace schema.
+    assert func.kind() == SchemaKind.inplace
+    assert func.arguments.self_arg is not None
+    # The new out= schema has:
+    # - a new out argument with the same type as "func" (but with a mutable annotation)
+    # - The returns (if any) now alias the out= argument instead of "func"
+    # - an "out" overload name
+    return FunctionSchema(
+        name=func.name.remove_inplace().with_overload(
+            get_expected_out_variant_overload_name(func.name.overload_name)
+        ),
+        arguments=func.arguments.remove_self_annotation().with_out_args(
+            [
+                Argument(
+                    name="out",
+                    type=func.arguments.self_arg.argument.type,
+                    default=None,
+                    annotation=func.arguments.self_arg.argument.annotation,
+                )
+            ]
+        ),
+        returns=func.returns,
+    )
+
+
+# Helper function: given a functional FunctionSchema, generate its corresponding out= variant
+# Example before:
+#   _to_copy(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None,
+#       bool? pin_memory=None, bool non_blocking=False, MemoryFormat? memory_format=None) -> Tensor
+# Example after:
+#   _to_copy._out(Tensor self, *, bool non_blocking=False, MemoryFormat? memory_format=None,
+#       Tensor(a!) out) -> Tensor(a!)
+def functional_to_out_signature(func: FunctionSchema) -> FunctionSchema:
+    # Generating an out= schema from a functional schema.
+    assert func.kind() == SchemaKind.functional
+
+    new_returns, new_out_args = generate_out_args_from_schema(func)
+    # The new out= schema has:
+    # - one or more new out argument(s) with the same type as returns (but with a mutable annotation)
+    # - The returns now alias the out= arguments
+    # - an "_out" overload name
+    return FunctionSchema(
+        name=func.name.with_overload(
+            get_expected_out_variant_overload_name(func.name.overload_name)
+        ),
+        arguments=func.arguments.signature().with_out_args(
+            new_out_args,
+        ),
+        returns=tuple(new_returns),
+    )
+
+
+# Helper function: given a function schema, generate corresponding out arguments, also the updated return annotations.
+def generate_out_args_from_schema(
+    func: FunctionSchema,
+) -> tuple[list[Return], list[Argument]]:
+    # More of a sanity check - our existing restrictions on schemas should enforce that
+    # mutable schema kinds never return their mutable arguments.
+    assert not any(
+        r.annotation is not None and r.annotation.is_write for r in func.returns
+    )
+
+    tensorlike_rets = [r for r in func.returns if r.type.is_tensor_like()]
+    assert len(tensorlike_rets) > 0
+
+    used_annotations = concatMap(
+        lambda a: [] if a.annotation is None else a.annotation.alias_set,
+        func.arguments.flat_all,
+    )
+    valid_annotations = [x for x in string.ascii_lowercase if x not in used_annotations]
+
+    all_rets_are_tensors = all(r.type == BaseType(BaseTy.Tensor) for r in func.returns)
+
+    new_out_args: list[Argument] = []
+    # The end result of new_returns is that:
+    # - If every return is a plain tensor, then the new returns == the old returns, but with the out= alias annotations added.
+    # - Otherwise, none of the out arguments show up in the returns (and we're only left with non-tensor-like returns, if any).
+    new_returns: list[Return] = []
+    for i, r in enumerate(func.returns):
+        if r.type.is_tensor_like():
+            new_out = Argument(
+                name="out" if len(func.returns) == 1 else f"out{i}",
+                type=r.type,
+                default=None,
+                annotation=Annotation.parse(f"{valid_annotations[i]}!"),
+            )
+            new_out_args.append(new_out)
+            if all_rets_are_tensors:
+                # The convention for out= schemas is that they only return their out arguments
+                # if the return is a plain Tensor (or if it's a tuple of plain Tensors)
+                new_ret = Return(
+                    name=None, type=new_out.type, annotation=new_out.annotation
+                )
+                new_returns.append(new_ret)
+        else:
+            new_returns.append(r)
+    return new_returns, new_out_args
+
+
+# Helper function: given a mutable FunctionSchema, generate its corresponding out= variant
+# Example before:
+#   _fused_moving_avg_obs_fq_helper(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor output, Tensor mask)  # noqa: B950
+# Example after:
+#   _fused_moving_avg_obs_fq_helper._out(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False, *, Tensor(e!) out0, Tensor(f!) out1) -> (Tensor(e!), Tensor(f!))  # noqa: B950
+def mutable_to_out_signature(func: FunctionSchema) -> FunctionSchema:
+    # Generating an out= schema from a mutable schema.
+    assert func.kind() == SchemaKind.mutable
+    # The new out= schema has:
+    # - Any non-aliased tensor-like returns are converted to mutable, aliased out= arguments
+    #   (if the argument is a tensor then we also return it for method chaining,
+    #   otherwise we return nothing)
+    # - an "out" overload name
+    #
+    # Note that:
+    # (1) This also means that we can *only* generate an out= variant from a mutable schema
+    #     if the mutable schema has at least one tensor-like non-aliasing return.
+    # (2) The generated out= variant still has mutable positional arguments,
+    #     but if necessary we could probably add another out= variant that also
+    #     functionalizes the mutable arguments (a functional_out variant)
+
+    new_returns, new_out_args = generate_out_args_from_schema(func)
+
+    return FunctionSchema(
+        name=func.name.remove_inplace().with_overload(
+            get_expected_out_variant_overload_name(func.name.overload_name)
+        ),
+        arguments=func.arguments.with_out_args(new_out_args),
+        returns=tuple(new_returns),
+    )
+
+
+# This function, given function of one SchemaKind, as well as a target SchemaKind,
+# generates a new NativeFunction with the same properties, but using the target SchemaKind.
+# We only actually generate functions for either functional or out= SchemaKinds.
+# This function returns a tuple, with:
+# - The generated NativeFunction
+# - a dictionary of `BackendIndex` objects, describing which dispatch keys
+#   we will generate kernels for, for the new NativeFunction.
+#   Details are in the function, but we only generate composite kernels (in some cases) today.
+def generate_function(
+    f: NativeFunction, k: SchemaKind
+) -> tuple[NativeFunction, dict[DispatchKey, dict[OperatorName, BackendMetadata]]]:
+    from torchgen.api import cpp
+
+    if k == SchemaKind.functional:
+        assert f.func.kind() != SchemaKind.functional
+        # The new "functional" NativeFunction has:
+        # - any mutable arguments have been converted into (immutable) returns.
+        #   (if a mutable argument was not also a return, it gets converted to one)
+        # - "_functional" appended to the base name, ONLY IF this op has a mutable variant.
+        #   See Note [Overload Ambiguity With Functional Variants]
+        # The default grouping logic in signature() actually already does this,
+        # so we can piggy-back off it (but we still want return names)
+        func = f.func.signature(keep_return_names=True).with_name(
+            OperatorName(
+                name=BaseOperatorName(
+                    base=f.func.name.name.base,
+                    inplace=False,
+                    dunder_method=f.func.name.name.dunder_method,
+                    # See Note [Overload Ambiguity With Functional Variants]
+                    functional_overload=f.func.kind() == SchemaKind.mutable,
+                ),
+                overload_name=f.func.name.overload_name,
+            )
+        )
+    elif k == SchemaKind.out:
+        # We generate out= ops mostly just so that we can pair up NativeFunctions into groups easily,
+        # but at least today, there is no good reason to actually use them.
+        # we'll generate a dispatcher entry for them, but won't actually register any kernels for them.
+        if f.func.kind() == SchemaKind.inplace:
+            func = self_to_out_signature(f.func)
+        elif f.func.kind() == SchemaKind.mutable:
+            func = mutable_to_out_signature(f.func)
+        elif f.func.kind() == SchemaKind.functional:
+            func = functional_to_out_signature(f.func)
+        else:
+            raise AssertionError(
+                "We only bother generating out= functions from either inplace or mutable or functional variants"
+            )
+    else:
+        raise AssertionError(
+            "We currently only generate either functional or out= NativeFunctions"
+        )
+
+    # Generated kernel naming convention for out: _. The reason for this is to
+    # disambiguate operator with the same name but different overload name, e.g., `randn.names_out` and
+    # `randn.generator_with_names_out`.
+    kernel_name = (
+        func.name.unambiguous_name()
+        if func.kind() == SchemaKind.out
+        else cpp.name(func)
+    )
+    if f.func.has_symint():
+        kernel_name += "_symint"
+    backend_metadata = {
+        DispatchKey.CompositeExplicitAutograd: {
+            func.name: BackendMetadata(
+                kernel=kernel_name,
+                structured=False,
+                cpp_namespace=DEFAULT_KERNEL_NAMESPACE,
+            )
+        }
+    }
+    tags = {"generated"} | set(
+        f.tags & {"nondeterministic_seeded", "view_copy", "pt2_compliant_tag"}
+    )
+
+    return (
+        NativeFunction(
+            func=func,
+            use_const_ref_for_mutable_tensors=f.use_const_ref_for_mutable_tensors,
+            # These generated fn's aren't meant to be user friendly- don't generate methods.
+            variants={Variant.function},
+            structured=False,
+            structured_delegate=None,
+            structured_inherits=None,
+            precomputed=None,
+            autogen=[],
+            ufunc_inner_loop={},
+            manual_kernel_registration=False,
+            manual_cpp_binding=False,
+            python_module=None,
+            category_override=None,
+            device_guard=False,
+            device_check=DeviceCheckType.NoCheck,
+            loc=f.loc,
+            cpp_no_default_args=set(),
+            is_abstract=f.is_abstract,
+            has_composite_implicit_autograd_kernel=False,
+            has_composite_implicit_autograd_nested_tensor_kernel=False,
+            has_composite_explicit_autograd_kernel=True,
+            has_composite_explicit_autograd_non_functional_kernel=False,
+            # Every generated NativeFunction gets a "generated" tag, so it's easy to tell
+            # which NativeFunction objects did not come directly from native_functions.yaml.
+            tags=tags,
+            namespace=f.namespace,
+        ),
+        backend_metadata,
+    )
+
+
+# This function is responsible for adding generated NativeFunctions which don't appear
+# explicitly in the codegen.
+# You can inspect the full list of NativeFunctions yourself with the torchgen package, by running
+# torchgen.parse_native_yaml("aten/src/ATen/native/native_functions.yaml", "aten/src/ATen/native/tags.yaml")
+# (Maybe we should make a friendly API for this)
+#
+# Note: this function *mutates* its two inputs,
+# adding the new NativeFunctions / BackendMetadata to them
+def add_generated_native_functions(
+    rs: list[NativeFunction],
+    indices: dict[DispatchKey, dict[OperatorName, BackendMetadata]],
+) -> None:
+    # The main code for generating new NativeFunctions
+    # First we group of NativeFunctions by schema kind,
+    # then we detect which ones are missing and generate them.
+    pre_grouped_native_functions = pre_group_native_functions(rs)
+    for d in pre_grouped_native_functions.values():
+        has_functional = SchemaKind.functional in d
+        has_inplace = SchemaKind.inplace in d
+        has_mutable = SchemaKind.mutable in d
+        has_out = SchemaKind.out in d
+        is_core = any("core" in variant.tags for variant in d.values())
+
+        # We automatically generate a few native functions that don't exist in the yaml, for a few reasons:
+        # (1) If an operator has an inplace/out= variant but no functional variant, we can generate
+        #     a simple functional variant that the functionalization pass can consume.
+        # (2) If an operator has an inplace or functional but no out= variant, we generate an out=
+        #     variant, mostly so we can easily pair up functions into NativeFunctionsGroup,
+        #     while maintaining the constraint that the out= variant is "required".
+        if has_mutable or has_inplace or has_out or has_functional:
+            # Don't bother generating functions trio's for native functions that bypass the dispatcher.
+            are_manual = all(f.manual_cpp_binding for f in d.values())
+            # Don't bother generating functional + out= variants for view operators
+            # set_ is technically an inplace_view, but for now it is treated
+            # as a normal inplace op in the codegen
+            has_view_ops = any(
+                f.is_view_op and str(f.func.name.name) != "set_" for f in d.values()
+            )
+            # Don't generate the other variants for non-core CompositeImplicitAutograd operators.
+            # We could probably do this, but the main benefit of generating the function triplets
+            # is for transforms that need them, and transforms don't need to act directly
+            # on CompositeImplicitAutograd operators (since we let them decompose).
+            are_composite_implicit = all(
+                f.has_composite_implicit_autograd_kernel for f in d.values()
+            )
+            if are_manual or has_view_ops or are_composite_implicit and not is_core:
+                continue
+            if has_out and len(d.values()) == 1:
+                # Note: [Out ops with functional variants that don't get grouped properly]
+                # In theory we could validly have an out= operator in native_functions.yaml
+                # that has no other variants.
+                # But today, all of the operators where that's the case actually do have
+                # functional variants, that we are just unable to pair up properly.
+                # I think banning this all together is probably safer
+                # (you can always add a functional variant yourself if you want to add a new out= operator).
+                #
+                # We should probably fix the existing cases; this check is to prevent us from adding more over time.
+                if (
+                    str(d[SchemaKind.out].func.name)
+                    not in OUT_OPS_THAT_DONT_GET_GROUPED_PROPERLY
+                ):
+                    raise AssertionError(
+                        f"Found an out= operator that we could not find any other variants of: {str(d[SchemaKind.out].func)}"
+                    )
+                continue
+
+            # Some inplace ops that have problematic schemas (that we should fix), which prevent us
+            # from generating out= and functional variants
+            if (
+                has_inplace
+                and str(d[SchemaKind.inplace].func.name)
+                in INPLACE_OPS_THAT_DONT_GET_GROUPED_PROPERLY
+            ):
+                continue
+
+            base_fn = (
+                d[SchemaKind.mutable]
+                if has_mutable
+                else d[SchemaKind.inplace]
+                if has_inplace
+                else d[SchemaKind.out]
+                if has_out
+                else d[SchemaKind.functional]
+            )
+
+            # Note: [Mutable ops that cannot get an out variant]
+            # We can only generate an out= variant if either:
+            # - the original function has tensor-like returns (since we can convert them to out kwargs)
+            # - or it's inplace (since we can convert `self` to an out kwarg)
+            # There are only two functions that don't fit this criteria today though,
+            # and they both look like they should be fixed to be out= variants,
+            # so if feels safer to ban this schema all-together
+            base_fn_valid = base_fn.func.kind() == SchemaKind.inplace or any(
+                r.type.is_tensor_like() for r in base_fn.func.returns
+            )
+            # Note: [Loosen the assertion that all functional should have out variant]
+            # By design all functional operators should have our variants. The needs_out check
+            # is loosening this requirement, changing it to only generate out variant if there's
+            # an `autogen` block in the native function, in the long run it should be removed.
+            # FIXME: Remove this after figuring out CI job failures related to min, max, mean
+            needs_out = any("out" in str(op_name) for op_name in base_fn.autogen)
+            gets_out_variant = not has_out and base_fn_valid and needs_out
+            if not has_out and not base_fn_valid:
+                if (
+                    str(base_fn.func.name)
+                    not in MUTABLE_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT
+                    and str(base_fn.func.name)
+                    not in FUNCTIONAL_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT
+                ):
+                    raise AssertionError(
+                        f"""Found an operator that we could not generate an out= variant for: {str(base_fn.func)}.
+This type of operators don't have tensor-like return, making it difficult to generate a proper out= variant. If
+out= variant is not needed, please add the function name into FUNCTIONAL_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT list."""
+                    )
+
+            # Generate an out= variant
+            if gets_out_variant:
+                fn, metadata = generate_function(base_fn, SchemaKind.out)
+                d[SchemaKind.out] = fn
+                BackendIndex.grow_index(indices, metadata)
+                rs.append(fn)
+
+            # Generate a functional variant, but only do it if the operator got an out= variant
+            # (Functional variants are only useful if we can group up the variants,
+            # which we can only do if they have an out= variant)
+            if not has_functional and (has_out or gets_out_variant):
+                fn, metadata = generate_function(base_fn, SchemaKind.functional)
+                d[SchemaKind.functional] = fn
+                BackendIndex.grow_index(indices, metadata)
+                rs.append(fn)
+
+
+def return_str(rets: tuple[Return, ...], names: list[str]) -> str:
+    assert len(rets) == len(names)
+    if len(rets) == 0:
+        return ""
+    elif len(rets) == 1:
+        return f"return {names[0]};"
+    else:
+        return f"return {dispatcher.returns_type(rets).cpp_type()}({', '.join(names)});"
+
+
+# Given a function, and the name of a variable corresponding to the output of that function,
+# gather up all of the individual returns that are not aliased
+def gather_nonaliased_inner_rets(func: FunctionSchema, out_var: str) -> list[str]:
+    aliased_rets = func.aliased_return_names()
+    non_aliased_names = []
+    is_out_var_a_tuple = len(func.returns) > 1
+    for i, r in enumerate(aliased_rets):
+        if r is None:
+            non_aliased_names.append(
+                f"std::get<{i}>({out_var})" if is_out_var_a_tuple else out_var
+            )
+    return non_aliased_names
+
+
+# Generates functional kernels in terms of their inplace.mutable counterparts.
+# We only do this for "generated" NativeFunctions
+@with_native_function
+def gen_composite_functional_kernel(g: NativeFunctionsGroup) -> str | None:
+    # We should only be generating these for code-generated NativeFunctions
+    if "generated" not in g.functional.tags:
+        return None
+    # And we always write the kernel for a generated op in terms of a non-generated op.
+    if g.inplace is not None and "generated" not in g.inplace.tags:
+        target_f = g.inplace
+    elif g.mutable is not None and "generated" not in g.mutable.tags:
+        target_f = g.mutable
+    else:
+        # We should be guaranteed to have a valid inplace/mutable variant to call into.
+        # See Note: [Mutable Ops Not Using Functionalization]
+        raise AssertionError(str(g.functional.func))
+
+    sig = DispatcherSignature(g.functional.func)
+    target_sig = DispatcherSignature(target_f.func)
+
+    context: list[Binding | Expr] = []
+    clone_mutable_inputs = []
+    cloned_return_names = []
+    # We can't just directly pass all of the arguments from the functional op into the mutating op.
+    # We need to check for which inputs to the mutating operator are mutable,
+    # and clone those inputs first.
+    for a_curr, a_tgt in zip(
+        dispatcher.jit_arguments(g.functional.func),
+        dispatcher.jit_arguments(target_f.func),
+    ):
+        if a_tgt.annotation is not None and a_tgt.annotation.is_write:
+            clone_mutable_inputs.append(
+                f"auto {a_curr.name}_clone = clone_arg({a_curr.name});"
+            )
+            context.append(
+                Expr(
+                    expr=f"{a_curr.name}_clone",
+                    type=dispatcher.argument_type(a_curr, binds=a_curr.name),
+                )
+            )
+            # Invariant: mutable arguments on the inner mutable op are always returns on the functional op.
+            cloned_return_names.append(f"{a_curr.name}_clone")
+        else:
+            context.append(dispatcher.argument(a_curr))
+    exprs = ", ".join([e.expr for e in translate(context, target_sig.arguments())])
+
+    out_name = "output"
+    maybe_assign = f"auto {out_name} = " if len(target_f.func.returns) > 0 else ""
+    inner_return_names = gather_nonaliased_inner_rets(target_f.func, out_name)
+    ret_str = return_str(
+        g.functional.func.returns, inner_return_names + cloned_return_names
+    )
+
+    clone_mutable_inputs_str = "\n".join(clone_mutable_inputs)
+    return f"""
+{sig.defn(name=sig.name() + ("_symint" if g.out.func.has_symint() else ""))} {{
+  {clone_mutable_inputs_str}
+  {maybe_assign}at::_ops::{target_f.func.name.unambiguous_name()}::call({exprs});
+  {ret_str}
+}}
+"""
+
+
+# Generates out= kernels in terms of their functional counterparts.
+# We only do this for "generated" NativeFunctions
+@with_native_function
+def gen_composite_out_kernel(g: NativeFunctionsGroup) -> str | None:
+    # We should only be generating these for code-generated NativeFunctions
+    if "generated" not in g.out.tags:
+        return None
+    # And we always write the kernel for the out= op in terms of the functional.
+    # Note that the functional op might have also been generated, but we don't have to
+    # worry about cycles, because the generated functional kernels are always implemented
+    # in terms of non-generated kernels (see gen_composite_functional_kernel).
+
+    sig = DispatcherSignature(g.out.func)
+    target_sig = DispatcherSignature(g.functional.func)
+
+    exprs = ", ".join(
+        [e.expr for e in translate(sig.arguments(), target_sig.arguments())]
+    )
+
+    copy_outs = []
+    out_name = "tmp_output"
+    for i, out_arg in enumerate(g.out.func.arguments.out):
+        functional_return_name = (
+            out_name
+            if len(g.functional.func.returns) == 1
+            else f"std::get<{i}>({out_name})"
+        )
+        copy_outs.append(
+            f"""\
+  resize_out_helper({out_arg.name}, {functional_return_name});
+  copy_arg({out_arg.name}, {functional_return_name});"""
+        )
+
+    rets = []
+    # For each return arg in the calling (out=) operator,
+    # If it corresponds to an aliased input, return the input.
+    # Otherwise, return the corresponding output from calling the functional operator.
+    for i, ret_name in enumerate(g.out.func.aliased_return_names()):
+        if ret_name is not None:
+            rets.append(ret_name)
+        else:
+            functional_return_name = (
+                out_name
+                if len(g.functional.func.returns) == 1
+                else f"std::get<{i}>({out_name})"
+            )
+            rets.append(functional_return_name)
+
+    copy_outs_str = "\n".join(copy_outs)
+
+    # Kernel name needs to follow the naming convention defined in `generate_function()`
+    return f"""
+{sig.defn(name=g.out.func.name.unambiguous_name() + ("_symint" if g.out.func.has_symint() else ""))} {{
+  auto {out_name} = at::_ops::{g.functional.func.name.unambiguous_name()}::call({exprs});
+  {copy_outs_str}
+  {return_str(g.out.func.returns, rets)}
+}}
+"""
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/operator_versions/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/operator_versions/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/operator_versions/gen_mobile_upgraders.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/operator_versions/gen_mobile_upgraders.py
new file mode 100644
index 0000000000000000000000000000000000000000..d29b274f71bd2f7f9dd886151e4d8c94e12d0585
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/operator_versions/gen_mobile_upgraders.py
@@ -0,0 +1,386 @@
+#!/usr/bin/env python3
+
+from __future__ import annotations
+
+import os
+from enum import Enum
+from operator import itemgetter
+from pathlib import Path
+from typing import Any
+
+import torch
+from torch.jit.generate_bytecode import generate_upgraders_bytecode
+from torchgen.code_template import CodeTemplate
+from torchgen.operator_versions.gen_mobile_upgraders_constant import (
+    MOBILE_UPGRADERS_HEADER_DESCRIPTION,
+)
+
+
+class ByteCode(Enum):
+    instructions = 1
+    constants = 2
+    types = 3
+    operators = 4
+    register_size = 5
+
+
+EXCLUDED_OP_SET = [
+    "aten::full.names",
+    "aten::full.out",
+    "aten::full",
+]
+
+EXCLUE_UPGRADER_SET = ["full_0_4", "full_out_0_4"]
+
+ONE_INSTRUCTION = CodeTemplate(
+    """
+    Instruction{OpCode::${operator_name}, ${X}, ${N}},"""
+)
+
+INSTRUCTION_LIST = CodeTemplate(
+    """std::vector({
+        ${instruction_list}
+    }), // instructions list"""
+)
+
+ONE_CONSTANT = CodeTemplate(
+    """
+    c10::IValue(${constant}),"""
+)
+
+CONSTANT_LIST = CodeTemplate(
+    """std::vector({
+        ${constant_list}
+    }), // constants list"""
+)
+
+CONSTANTS_LIST_EMPTY = """std::vector(), // constants list"""
+
+ONE_TYPE = CodeTemplate("""c10::parseType("${type_str}"),""")
+
+TYPE_LIST = CodeTemplate(
+    """std::vector({
+        ${type_list}
+    }), // types list"""
+)
+
+TYPE_LIST_EMPTY = """std::vector(), // types list"""
+
+ONE_OPERATOTR_STRING = CodeTemplate(
+    """
+    OperatorString({"${operator_name}", "${overload_name}", ${num_of_args}}),"""
+)
+
+OPERATOR_STRING_LIST = CodeTemplate(
+    """
+    std::vector({
+        ${operator_string_list}
+    }), // operators list"""
+)
+
+ONE_UPGRADER_FUNCTION = CodeTemplate(
+    """
+    mobile::Function::registerFunc(
+        "${upgrader_name}",
+        ${instruction_list},
+        ${constant_list},
+        ${type_list},
+        ${register_size}
+    )"""
+)
+
+ONE_UPGRADER_SRC = CodeTemplate(
+    """
+    ByteCodeFunctionWithOperator({
+        ${bytecode_function},
+        ${operator_string_list}
+    }),"""
+)
+
+
+ONE_UPGRADER_IN_VERSION_MAP = CodeTemplate(
+    """Upgrader({${upgrader_min_version}, ${upgrader_max_version}, "${upgrader_name}", ${bytecode_func_index}})"""
+)  # noqa: E501
+
+ONE_OPERATOR_IN_VERSION_MAP = CodeTemplate(
+    """
+    {std::string("${operator_name}"),
+        std::vector({
+            ${upgrader_list_in_version_map}
+        })},"""
+)
+
+
+OPERATOR_VERSION_MAP = CodeTemplate(
+    """
+const std::unordered_map>
+getOperatorVersionMapForMobile() {
+  static std::unordered_map>
+        operatorVersionMapForMobile({
+            ${operator_list_in_version_map}
+      });
+  return operatorVersionMapForMobile;
+}
+"""
+)
+
+
+UPGRADER_CPP_SRC = CodeTemplate(
+    MOBILE_UPGRADERS_HEADER_DESCRIPTION
+    + """
+#include 
+#include 
+#include 
+
+namespace torch {
+namespace jit {
+
+// clang-format off
+
+// From operator_versions_map
+${operator_version_map}
+
+const std::vector& getUpgraderBytecodeList() {
+  auto generate_upgrader_bytecode_list = []() {
+    std::vector upgrader_function_list({
+               ${upgrader_bytecode}
+            });
+    for (const auto& upgrader_function : upgrader_function_list) {
+      for (const auto& op : upgrader_function.operators) {
+        upgrader_function.function.append_operator(
+            op.name,
+            op.overload_name,
+            op.num_specified_args);
+      }
+    }
+    return upgrader_function_list;
+  };
+  static std::vector upgraderBytecodeList =
+      generate_upgrader_bytecode_list();
+  return upgraderBytecodeList;
+}
+
+// clang-format on
+
+} // namespace jit
+} // namespace torch
+"""
+)
+
+UPGRADER_MOBILE_FILE_NAME = "upgrader_mobile.cpp"
+
+UPGRADER_ELEMENT = CodeTemplate(
+    """\
+Upgrader({${min_version}, ${max_version}, ${operator_name}, ${index}}),
+"""
+)
+
+PER_OPERATOR_UPGRADER_LIST = CodeTemplate(
+    """\
+{
+  std::string(${operator_name}),
+  std::vector({${upgrader_list}});
+}
+"""
+)
+
+
+def construct_instruction(instruction_list_from_yaml: list[Any]) -> str:
+    instruction_list_part = [
+        ONE_INSTRUCTION.substitute(
+            operator_name=instruction[0],
+            X=instruction[1],
+            N=instruction[2],
+        )
+        for instruction in instruction_list_from_yaml
+    ]
+    return INSTRUCTION_LIST.substitute(
+        instruction_list="".join(instruction_list_part).lstrip("\n")
+    )
+
+
+def construct_constants(constants_list_from_yaml: list[Any]) -> str:
+    constants_list_part = []
+    for constant_from_yaml in constants_list_from_yaml:
+        convert_constant = None
+        if isinstance(constant_from_yaml, str):
+            # Add quotes if it's string
+            convert_constant = f'"{constant_from_yaml}"'
+        elif isinstance(constant_from_yaml, bool):
+            convert_constant = "true" if constant_from_yaml else "false"
+        elif constant_from_yaml is None:
+            convert_constant = ""
+        elif isinstance(constant_from_yaml, int):
+            convert_constant = str(constant_from_yaml)
+        else:
+            raise ValueError(
+                f"The type of {constant_from_yaml} is {type(constant_from_yaml)}. "
+                "Please add change in construct_constants function in gen_mobile_upgraders.py."
+            )
+        constants_list_part.append(ONE_CONSTANT.substitute(constant=convert_constant))
+    if len(constants_list_part) == 0:
+        return CONSTANTS_LIST_EMPTY
+    return CONSTANT_LIST.substitute(
+        constant_list="".join(constants_list_part).lstrip("\n")
+    )
+
+
+def construct_operators(operator_list_from_yaml: list[Any]) -> str:
+    operator_list_part = [
+        ONE_OPERATOTR_STRING.substitute(
+            operator_name=operator[0],
+            overload_name=operator[1],
+            num_of_args=operator[2],
+        )
+        for operator in operator_list_from_yaml
+    ]
+    return OPERATOR_STRING_LIST.substitute(
+        operator_string_list="".join(operator_list_part).lstrip("\n")
+    )
+
+
+def construct_types(types_tr_list_from_yaml: list[Any]) -> str:
+    types_tr_list_part = [
+        ONE_TYPE.substitute(type_str=types_tr) for types_tr in types_tr_list_from_yaml
+    ]
+    if len(types_tr_list_part) == 0:
+        return TYPE_LIST_EMPTY
+    return TYPE_LIST.substitute(type_list="".join(types_tr_list_part).lstrip("\n"))
+
+
+def construct_register_size(register_size_from_yaml: int) -> str:
+    if not isinstance(register_size_from_yaml, int):
+        raise ValueError(
+            f"Input register size is {register_size_from_yaml} and"
+            "it's type is {type(register_size_from_yaml)}. An int type is expected."
+        )
+    return str(register_size_from_yaml)
+
+
+def construct_version_maps(
+    upgrader_bytecode_function_to_index_map: dict[str, Any],
+) -> str:
+    version_map = torch._C._get_operator_version_map()
+    sorted_version_map_ = sorted(version_map.items(), key=itemgetter(0))  # type: ignore[no-any-return]
+    sorted_version_map = dict(sorted_version_map_)
+
+    operator_list_in_version_map_part = []
+    for op_name in sorted_version_map:
+        upgraders_in_version_map_part = []
+        # TODO: remove the skip after these two operators schemas are fixed
+        if op_name in EXCLUDED_OP_SET:
+            continue
+        upgrader_ranges = torch._C._get_upgrader_ranges(op_name)
+        upgrader_entries = sorted_version_map[op_name]
+        assert len(upgrader_ranges) == len(upgrader_entries)
+        for idx, upgrader_entry in enumerate(upgrader_entries):
+            upgrader_name = upgrader_entry.upgrader_name
+            bytecode_function_index = upgrader_bytecode_function_to_index_map[
+                upgrader_name
+            ]
+            upgraders_in_version_map_part.append(
+                ONE_UPGRADER_IN_VERSION_MAP.substitute(
+                    upgrader_min_version=upgrader_ranges[idx].min_version,
+                    upgrader_max_version=upgrader_ranges[idx].max_version,
+                    upgrader_name=upgrader_name,
+                    bytecode_func_index=bytecode_function_index,
+                )
+            )
+        operator_list_in_version_map_part.append(
+            ONE_OPERATOR_IN_VERSION_MAP.substitute(
+                operator_name=op_name,
+                upgrader_list_in_version_map="".join(upgraders_in_version_map_part),
+            )
+        )
+    return OPERATOR_VERSION_MAP.substitute(
+        operator_list_in_version_map="".join(operator_list_in_version_map_part).lstrip(
+            "\n"
+        )
+    )
+
+
+def get_upgrader_bytecode_function_to_index_map(
+    upgrader_dict: list[dict[str, Any]],
+) -> dict[str, Any]:
+    upgrader_bytecode_function_to_index_map = {}
+    index = 0
+    for upgrader_bytecode in upgrader_dict:
+        for upgrader_name in upgrader_bytecode.keys():
+            if upgrader_name in EXCLUE_UPGRADER_SET:
+                continue
+            upgrader_bytecode_function_to_index_map[upgrader_name] = index
+            index += 1
+    return upgrader_bytecode_function_to_index_map
+
+
+def write_cpp(cpp_path: str, upgrader_dict: list[dict[str, Any]]) -> None:
+    upgrader_bytecode_function_to_index_map = (
+        get_upgrader_bytecode_function_to_index_map(upgrader_dict)
+    )
+    version_map_src = construct_version_maps(upgrader_bytecode_function_to_index_map)
+    all_upgrader_src_string = []
+    for upgrader_bytecode in upgrader_dict:
+        for upgrader_name, bytecode in upgrader_bytecode.items():
+            # TODO: remove the skip after these two operators schemas are fixed
+            if upgrader_name in EXCLUE_UPGRADER_SET:
+                continue
+            instruction_list_str = ""
+            constant_list_str = ""
+            type_list_str = ""
+            register_size_str = ""
+            operator_list_str = ""
+            for table_name, contents in bytecode.items():
+                element = ByteCode[table_name]
+                if element is ByteCode.instructions:
+                    instruction_list_str = construct_instruction(contents)
+                elif element is ByteCode.constants:
+                    constant_list_str = construct_constants(contents)
+                elif element is ByteCode.operators:
+                    operator_list_str = construct_operators(contents)
+                elif element is ByteCode.types:
+                    type_list_str = construct_types(contents)
+                elif element is ByteCode.register_size:
+                    register_size_str = construct_register_size(contents)
+
+            one_upgrader_function_string = ONE_UPGRADER_FUNCTION.substitute(
+                upgrader_name=upgrader_name,
+                instruction_list=instruction_list_str,
+                constant_list=constant_list_str,
+                type_list=type_list_str,
+                register_size=register_size_str,
+            )
+            one_upgrader_src_string = ONE_UPGRADER_SRC.substitute(
+                bytecode_function=one_upgrader_function_string.lstrip("\n"),
+                operator_string_list=operator_list_str.lstrip("\n"),
+            )
+            all_upgrader_src_string.append(one_upgrader_src_string)
+
+    upgrader_file_content = UPGRADER_CPP_SRC.substitute(
+        operator_version_map=version_map_src,
+        upgrader_bytecode="".join(all_upgrader_src_string).lstrip("\n"),
+    )
+    print("writing file to : ", cpp_path + "/" + UPGRADER_MOBILE_FILE_NAME)
+    with open(os.path.join(cpp_path, UPGRADER_MOBILE_FILE_NAME), "wb") as out_file:
+        out_file.write(upgrader_file_content.encode("utf-8"))
+
+
+def sort_upgrader(upgrader_list: list[dict[str, Any]]) -> list[dict[str, Any]]:
+    sorted_upgrader_list = sorted(
+        upgrader_list, key=lambda one_upgrader: next(iter(one_upgrader))
+    )
+    return sorted_upgrader_list
+
+
+def main() -> None:
+    upgrader_list = generate_upgraders_bytecode()
+    sorted_upgrader_list = sort_upgrader(upgrader_list)
+    for up in sorted_upgrader_list:
+        print("after sort upgrader : ", next(iter(up)))
+
+    pytorch_dir = Path(__file__).resolve().parents[2]
+    upgrader_path = pytorch_dir / "torch" / "csrc" / "jit" / "mobile"
+    write_cpp(str(upgrader_path), sorted_upgrader_list)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/operator_versions/gen_mobile_upgraders_constant.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/operator_versions/gen_mobile_upgraders_constant.py
new file mode 100644
index 0000000000000000000000000000000000000000..04b5ad887e54153115eeca7b6686d7c2de8dfc06
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/operator_versions/gen_mobile_upgraders_constant.py
@@ -0,0 +1,7 @@
+MOBILE_UPGRADERS_HEADER_DESCRIPTION = """/**
+ * @generated
+ * This is an auto-generated file. Please do not modify it by hand.
+ * To re-generate, please run:
+ * cd ~/pytorch && python torchgen/operator_versions/gen_mobile_upgraders.py
+ */
+"""
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/native/native_functions.yaml b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/native/native_functions.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..abb061afc5c9574815bb5530cf2815ea5b8af115
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/native/native_functions.yaml
@@ -0,0 +1,15942 @@
+# See README.md in this directory for more guidance
+
+# *********NB: _cast_* operators are DEPRECATED and will be removed
+# eventually. These were previously used before TorchScript IR supported
+# representing ScalarType's. They are now superseded by usage of
+# `aten::to()`. The ops remain here for backward compatibility purposes.
+
+# DEPRECATED. DO NOT USE
+- func: _cast_Byte(Tensor self, bool non_blocking=False) -> Tensor
+  variants: function
+
+# DEPRECATED. DO NOT USE
+- func: _cast_Char(Tensor self, bool non_blocking=False) -> Tensor
+  variants: function
+
+# DEPRECATED. DO NOT USE
+- func: _cast_Double(Tensor self, bool non_blocking=False) -> Tensor
+  variants: function
+
+# DEPRECATED. DO NOT USE
+- func: _cast_Float(Tensor self, bool non_blocking=False) -> Tensor
+  variants: function
+
+# DEPRECATED. DO NOT USE
+- func: _cast_Int(Tensor self, bool non_blocking=False) -> Tensor
+  variants: function
+
+# DEPRECATED. DO NOT USE
+- func: _cast_Long(Tensor self, bool non_blocking=False) -> Tensor
+  variants: function
+
+# DEPRECATED. DO NOT USE
+- func: _cast_Short(Tensor self, bool non_blocking=False) -> Tensor
+  variants: function
+
+# DEPRECATED. DO NOT USE
+- func: _cast_Half(Tensor self, bool non_blocking=False) -> Tensor
+  variants: function
+
+# Computes the gradient of current tensor w.r.t. graph leaves.
+- func: _backward(Tensor self, Tensor[] inputs, Tensor? gradient=None, bool? retain_graph=None, bool create_graph=False) -> ()
+  manual_cpp_binding: True
+  variants: method
+
+# DEPRECATED. Sets the tensor data held by this `Variable` to be the same as
+# `new_data`.  It requires that `new_data` and `Variable` have compatible tensor
+# type, by checking `_has_compatible_shallow_copy_type(this, new_data)`.
+#
+# This function is deprecated because it doesn't really make sense in a world
+# where Variables *are* Tensors (as opposed to them containing tensors, which
+# is what the previous interpretation was.)
+- func: set_data(Tensor(a!) self, Tensor new_data) -> ()
+  manual_cpp_binding: True
+  variants: method
+
+- func: data(Tensor self) -> Tensor
+  manual_cpp_binding: True
+  variants: method
+
+# True if this `Variable` is a leaf and thus does not have a `grad_fn`.
+- func: is_leaf(Tensor self) -> bool
+  manual_cpp_binding: True
+  variants: method
+
+# Returns the output index of this variable from the forward operation that
+# produced it.  Conversely, it returns the input index of the gradient `Node` to
+# which this `Variable` is connected (because in the gradient computation,
+# inputs and outputs switch meaning).  For example:
+#
+#   y0, y1, y2 = f(x)
+#   assert y0.output_nr == 0
+#   assert y1.output_nr == 1
+#   assert y2.output_nr == 2
+#
+- func: output_nr(Tensor self) -> int
+  manual_cpp_binding: True
+  variants: method
+
+- func: _version(Tensor self) -> int
+  manual_cpp_binding: True
+  variants: method
+
+- func: requires_grad_(Tensor(a!) self, bool requires_grad=True) -> Tensor(a!)
+  manual_cpp_binding: True
+  variants: method
+
+# Enables .grad attribute for non-leaf Tensors.
+- func: retain_grad(Tensor(a!) self) -> ()
+  manual_cpp_binding: True
+  variants: method
+
+- func: retains_grad(Tensor self) -> bool
+  manual_cpp_binding: True
+  variants: method
+
+- func: _fw_primal(Tensor(a) self, int level) -> Tensor(a)
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: _fw_primal
+
+- func: _make_dual(Tensor(a) primal, Tensor tangent, int level) -> Tensor(a)
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: _make_dual
+
+- func: _unpack_dual(Tensor(a) dual, int level) -> (Tensor(a) primal, Tensor tangent)
+  variants: function
+
+# NOTE: [_new_zeros_with_same_feature_meta]
+# This function creates a new tensor with the layout and TensorOptions
+# of `other` but also takes into account the batch dimensions of `self`
+#
+# This function has a couple extra constraints because it is also used for `jvp`
+# in functorch.
+# - is used for forward AD because there is the restriction
+#   that the primal and tangent must have the same layout
+# - We cannot assume that `self` and `other` have the same sizes or even dim
+#   because in the inplace over view case, `other` is the base tensor, and
+#   `self` is the forward grad with respect to the view, which can have an
+#   entirely different shape
+# - takes the number of batch dims for `self` because we also handle
+#   some batching logic. We handle that here instead of a batching rule because
+#   we'd like to avoid calling as_strided in the batching rule (as to enable
+#   nested vmap in functorch).
+# - needs to be CompositeExplicitAutograd for jvp support in functorch.
+#   functorch currently relies on TensorWrapper which does not have storage
+#   CompositeExplicitAutograd makes sure the TensorWrapper is unwrapped.
+# - this function may eventually take on another int argument to store the
+#   the number of batch dims for other once we support that use case
+- func: _new_zeros_with_same_feature_meta(Tensor self, Tensor other, *, int self_num_batch_dims=0) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: _new_zeros_with_same_feature_meta
+  autogen: _new_zeros_with_same_feature_meta.out
+
+# This function compares the storage numel of self with that of other, where
+# storage numel is computed as: `other.storage().nbytes() / other.itemsize()`.
+# We create this function for composite compliance purposes. The batching rule
+# always returns true because vmapped as_strided does not support accessing
+# storage locations not indexable by the input tensor.
+# See the note above for more information.
+- func: _has_same_storage_numel(Tensor self, Tensor other) -> bool
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: _has_same_storage_numel
+
+- func: rename_(Tensor(a!) self, Dimname[]? names) -> Tensor(a!)
+  variants: method
+  tags: inplace_view
+
+- func: rename(Tensor(a) self, Dimname[]? names) -> Tensor(a)
+  variants: method
+
+- func: align_to(Tensor(a) self, Dimname[] names) -> Tensor(a)
+  variants: method
+
+- func: align_to.ellipsis_idx(Tensor(a) self, Dimname[] order, int ellipsis_idx) -> Tensor(a)
+  variants: method
+
+- func: align_as(Tensor self, Tensor other) -> Tensor
+  variants: method
+
+- func: align_tensors(Tensor[] tensors) -> Tensor[]
+
+# Not assert because it's a keyword; not Assert because FX already
+# took that syntax
+# TODO: need to specify this is side-effectful somehow
+- func: _assert_async(Tensor self) -> ()
+  dispatch:
+    CPU: _assert_async_cpu
+    CUDA: _assert_async_cuda
+
+- func: _assert_async.msg(Tensor self, str assert_msg) -> ()
+  dispatch:
+    CPU: _assert_async_msg_cpu
+    CUDA: _assert_async_msg_cuda
+
+- func: _assert_scalar(Scalar self, str assert_msg) -> ()
+  dispatch:
+    CompositeExplicitAutograd: _assert_scalar
+
+- func: _functional_assert_scalar(Scalar self, str assert_msg, Tensor dep_token) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: _functional_assert_scalar
+
+- func: _functional_assert_async.msg(Tensor self, str assert_msg, Tensor dep_token) -> Tensor
+  dispatch:
+    CPU: _functional_assert_async_msg_cpu
+
+- func: _assert_tensor_metadata(Tensor a, SymInt[]? size=None, SymInt[]? stride=None, ScalarType? dtype=None, *, Device? device=None, Layout? layout=None) -> ()
+  dispatch:
+    CompositeExplicitAutograd: _assert_tensor_metadata
+    Meta: _assert_tensor_metadata_meta_symint
+
+- func: _print(str s) -> ()
+  dispatch:
+    CompositeExplicitAutograd: _print
+
+- func: sym_constrain_range(Scalar size, *, int? min=None, int? max=None) -> ()
+  dispatch:
+    CompositeExplicitAutograd: sym_constrain_range
+
+- func: sym_constrain_range_for_size(Scalar size, *, int? min=None, int? max=None) -> ()
+  dispatch:
+    CompositeExplicitAutograd: sym_constrain_range_for_size
+
+- func: _functional_sym_constrain_range(Scalar size, int? min, int? max, Tensor dep_token) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: _functional_sym_constrain_range
+
+- func: _functional_sym_constrain_range_for_size(Scalar size, int? min, int? max, Tensor dep_token) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: _functional_sym_constrain_range_for_size
+
+- func: _make_dep_token(*, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+  dispatch:
+    CPU: _make_dep_token_cpu
+
+- func: refine_names(Tensor(a) self, Dimname[] names) -> Tensor(a)
+  variants: method
+
+- func: _use_cudnn_ctc_loss(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank) -> bool
+  device_check: NoCheck  # Tensor arguments allowed to be on different devices, see also _cudnn_ctc_loss
+  dispatch:
+    CUDA: _use_cudnn_ctc_loss
+
+- func: _use_cudnn_ctc_loss.Tensor(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank) -> bool
+  device_check: NoCheck  # Tensor arguments allowed to be on different devices, see also _cudnn_ctc_loss
+  dispatch:
+    CUDA: _use_cudnn_ctc_loss_tensor
+
+- func: _cudnn_ctc_loss(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank, bool deterministic, bool zero_infinity) -> (Tensor, Tensor)
+  device_check: NoCheck  # log_probs is expected to be on CUDA while targets is expected to be on CPU
+  dispatch:
+    CUDA: _cudnn_ctc_loss
+  autogen: _cudnn_ctc_loss.out
+
+- func: _cudnn_ctc_loss.Tensor(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank, bool deterministic, bool zero_infinity) -> (Tensor, Tensor)
+  device_check: NoCheck  # log_probs is expected to be on CUDA while targets is expected to be on CPU
+  dispatch:
+    CUDA: _cudnn_ctc_loss_tensor
+
+- func: _use_cudnn_rnn_flatten_weight() -> bool
+
+- func: _cudnn_rnn_flatten_weight(Tensor[] weight_arr, int weight_stride0, SymInt input_size, int mode, SymInt hidden_size, SymInt proj_size, int num_layers, bool batch_first, bool bidirectional) -> Tensor
+  dispatch:
+    CUDA: _cudnn_rnn_flatten_weight
+  autogen: _cudnn_rnn_flatten_weight.out
+
+- func: _cudnn_rnn(Tensor input, Tensor[] weight, int weight_stride0, Tensor? weight_buf, Tensor hx, Tensor? cx, int mode, SymInt hidden_size, SymInt proj_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, SymInt[] batch_sizes, Tensor? dropout_state) -> (Tensor, Tensor, Tensor, Tensor, Tensor)
+  # rnn_tanh may or may not redispatch to _cudnn_rnn based on algorithm and build. Thus it might hit dispatch or kernel device check.
+  # Disable dispatch time device check for consistent behavior.
+  device_check: NoCheck
+  dispatch:
+    CUDA: _cudnn_rnn
+  autogen: _cudnn_rnn.out
+  tags: nondeterministic_seeded
+
+- func: _cudnn_rnn_backward(Tensor input, Tensor[] weight, int weight_stride0, Tensor weight_buf, Tensor hx, Tensor? cx, Tensor output, Tensor? grad_output, Tensor? grad_hy, Tensor? grad_cy, int mode, SymInt hidden_size, SymInt proj_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, SymInt[] batch_sizes, Tensor? dropout_state, Tensor reserve, bool[4] output_mask) -> (Tensor, Tensor, Tensor, Tensor[])
+  dispatch:
+    CUDA: _cudnn_rnn_backward
+  autogen: _cudnn_rnn_backward.out
+
+- func: _cudnn_init_dropout_state(float dropout, bool train, int dropout_seed, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+  dispatch:
+    CUDA: _cudnn_init_dropout_state
+  autogen: _cudnn_init_dropout_state.out
+  tags: nondeterministic_seeded
+
+- func: _debug_has_internal_overlap(Tensor self) -> int
+  variants: function
+
+- func: _fused_dropout(Tensor self, float p, Generator? generator=None) -> (Tensor, Tensor)
+  variants: function
+  dispatch:
+    CUDA: fused_dropout_cuda
+  tags: nondeterministic_seeded
+  autogen: _fused_dropout.out
+
+- func: _masked_scale(Tensor self, Tensor mask, float scale) -> Tensor
+  variants: function
+  dispatch:
+    CUDA: masked_scale_cuda
+  autogen: _masked_scale.out
+
+- func: native_dropout(Tensor input, float p, bool? train) -> (Tensor, Tensor)
+  variants: function
+  dispatch:
+    CPU: native_dropout_cpu
+    CUDA: native_dropout_cuda
+    MPS: native_dropout_mps
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: native_dropout_nested
+  tags: [nondeterministic_seeded, core]
+  autogen: native_dropout.out
+
+- func: native_dropout_backward(Tensor grad_output, Tensor mask, float scale) -> Tensor
+  dispatch:
+    CPU, NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: native_dropout_backward
+    CUDA: native_dropout_backward_cuda
+    MPS: native_dropout_backward_mps
+  autogen: native_dropout_backward.out
+  tags: pointwise
+
+- func: _sobol_engine_draw(Tensor quasi, int n, Tensor sobolstate, int dimension, int num_generated, ScalarType? dtype) -> (Tensor, Tensor)
+
+- func: _sobol_engine_ff_(Tensor(a!) self, int n, Tensor sobolstate, int dimension, int num_generated) -> Tensor(a!)
+
+- func: _sobol_engine_scramble_(Tensor(a!) self, Tensor ltm, int dimension) -> Tensor(a!)
+
+- func: _sobol_engine_initialize_state_(Tensor(a!) self, int dimension) -> Tensor(a!)
+
+- func: _reshape_from_tensor(Tensor self, Tensor shape) -> Tensor
+
+- func: _shape_as_tensor(Tensor self) -> Tensor
+
+- func: dropout(Tensor input, float p, bool train) -> Tensor
+  tags: [nondeterministic_seeded, maybe_aliasing_or_mutating]
+
+- func: dropout_(Tensor(a!) self, float p, bool train) -> Tensor(a!)
+  tags: nondeterministic_seeded
+
+- func: feature_dropout(Tensor input, float p, bool train) -> Tensor
+  tags: [nondeterministic_seeded, maybe_aliasing_or_mutating]
+
+- func: feature_dropout_(Tensor(a!) self, float p, bool train) -> Tensor(a!)
+  tags: nondeterministic_seeded
+
+- func: alpha_dropout(Tensor input, float p, bool train) -> Tensor
+  tags: [nondeterministic_seeded, maybe_aliasing_or_mutating]
+
+- func: alpha_dropout_(Tensor(a!) self, float p, bool train) -> Tensor(a!)
+  tags: nondeterministic_seeded
+
+- func: feature_alpha_dropout(Tensor input, float p, bool train) -> Tensor
+  tags: [nondeterministic_seeded, maybe_aliasing_or_mutating]
+
+- func: feature_alpha_dropout_(Tensor(a!) self, float p, bool train) -> Tensor(a!)
+  tags: nondeterministic_seeded
+
+- func: abs(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: abs
+    SparseCPU, SparseCUDA, SparseMPS: abs_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta: abs_sparse_csr
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_abs
+  tags: [core, pointwise]
+
+- func: abs_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: abs_
+    SparseCPU, SparseCUDA, SparseMPS: abs_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta: abs_sparse_csr_
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_abs_
+
+- func: abs.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MPS, MTIA: abs_out
+    SparseCPU, SparseCUDA, SparseMPS: abs_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta: abs_sparse_csr_out
+  tags: pointwise
+
+# Note [Adding an alias]
+# To add an alias do the following:
+#
+# 1) Copy the original functions native_functions.yaml entry, but replace the
+#      original function's name with their own and delete any dispatch
+#      keys for the aliases. Specifying a dispatch key will prevent
+#      autograd from recording the operations the alias performs, which
+#      will stop it from "inheriting" the original operation's autograd behavior.
+# 2) Implement the corresponding functions and have them redispatch to the
+#      original function.
+# 3) Add docstrings to the new function that reference the original function,
+#      and document the method as usual (if it exists.)
+#    (See torch/_torch_docs.py and docs/source/torch.rst if adding a function,
+#     torch/_tensor_docs.py and docs/source/tensors.rst if adding a method,
+#     or module-specific doc bindings (like torch/linalg/__init__.py) if
+#     adding an alias in a namespace.)
+# 4) Update torch/overrides.py consistent with the original function.
+# 5) Update the alias_map in torch/csrc/jit/passes/normalize_ops.cpp.
+# 6) Add aliases argument to existing OpInfo/UnaryUfuncInfo or create new OpInfo/UnaryUfuncInfo entry
+# in op_db list in torch/testing/_internal/common_methods_invocations.py
+#
+# See torch.absolute, an alias for torch.abs, as an example.
+# Absolute, alias for abs
+
+- func: absolute(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: absolute_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+- func: absolute.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+
+- func: angle(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CPU, CUDA: angle
+    MPS: angle_mps
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: angle_sparse_csr
+  tags: pointwise
+
+- func: angle.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA: angle_out
+    MPS: angle_out_mps
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: angle_sparse_csr_out
+  tags: pointwise
+
+- func: view_as_real(Tensor(a) self) -> Tensor(a)
+  variants: function
+  dispatch:
+    CPU, CUDA, MPS, Meta: view_as_real
+
+- func: view_as_complex(Tensor(a) self) -> Tensor(a)
+  variants: function
+  dispatch:
+    CPU, CUDA, MPS, Meta: view_as_complex
+
+- func: sgn(Tensor self) -> Tensor
+  variants: function, method
+  structured_delegate: sgn.out
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: sgn_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sgn_sparse_csr
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_sgn
+  tags: pointwise
+
+- func: sgn_(Tensor(a!) self) -> Tensor(a!)
+  variants: method
+  structured_delegate: sgn.out
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: sgn_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sgn_sparse_csr_
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_sgn_
+  tags: pointwise
+
+- func: sgn.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: sgn_out
+    MPS: sgn_out_mps
+    SparseCPU, SparseCUDA, SparseMPS: sgn_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sgn_sparse_csr_out
+  tags: pointwise
+
+- func: chalf(Tensor self, *, MemoryFormat? memory_format=None) -> Tensor
+  variants: method
+
+- func: real(Tensor(a) self) -> Tensor(a)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+
+- func: imag(Tensor(a) self) -> Tensor(a)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+
+- func: _conj(Tensor(a) self) -> Tensor(a)
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: _conj
+
+- func: conj(Tensor(a) self) -> Tensor(a)
+  variants: function, method
+  manual_cpp_binding: True
+
+- func: _conj_physical(Tensor self) -> Tensor
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: _conj_physical
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta: conj_physical_sparse_csr
+  autogen: _conj_physical.out
+
+- func: conj_physical(Tensor self) -> Tensor
+  variants: function, method
+  tags: [pointwise, maybe_aliasing_or_mutating]
+
+- func: conj_physical.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA: conj_physical_out
+    MPS: conj_physical_out_mps
+    SparseCPU, SparseCUDA, SparseMPS: conj_physical_out_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta: conj_physical_sparse_csr_out
+  tags: pointwise
+
+- func: conj_physical_(Tensor(a!) self) -> Tensor(a!)
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: conj_physical_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: conj_physical_sparse_csr_
+  tags: pointwise
+
+- func: resolve_conj(Tensor(a) self) -> Tensor(a)
+  variants: function, method
+
+- func: resolve_neg(Tensor(a) self) -> Tensor(a)
+  variants: function, method
+
+- func: _neg_view(Tensor(a) self) -> Tensor(a)
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: _neg_view
+
+- func: acos(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  structured_delegate: acos.out
+  tags: [core, pointwise]
+
+- func: acos_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  structured_delegate: acos.out
+  tags: pointwise
+
+- func: acos.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: acos_out
+  tags: pointwise
+
+# arccos, alias of acos
+- func: arccos(Tensor self) -> Tensor
+  variants: function, method
+
+- func: arccos_(Tensor(a!) self) -> Tensor(a!)
+  variants: function, method
+
+- func: arccos.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: avg_pool1d(Tensor self, int[1] kernel_size, int[1] stride=[], int[1] padding=0, bool ceil_mode=False, bool count_include_pad=True) -> Tensor
+  tags: core
+  autogen: avg_pool1d.out
+
+- func: adaptive_avg_pool1d(Tensor self, int[1] output_size) -> Tensor
+  tags: core
+  autogen: adaptive_avg_pool1d.out
+
+# Return: (Tensor output, Tensor indices)
+- func: adaptive_max_pool1d(Tensor self, int[1] output_size) -> (Tensor, Tensor)
+
+- func: add.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: add.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS, SparseMeta: add_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: add_sparse_csr
+    MkldnnCPU: mkldnn_add
+    ZeroTensor: add_zerotensor
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_add_Tensor
+  tags: [core, pointwise]
+
+- func: add_.Tensor(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  structured_delegate: add.out
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS, SparseMeta: add_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: add_sparse_csr_
+    MkldnnCPU: mkldnn_add_
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_add__Tensor
+  tags: pointwise
+
+- func: add.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  ufunc_inner_loop:
+    Generic: add (AllAndComplex, BFloat16, Half, ComplexHalf)
+    ScalarOnly: add (Bool)
+  dispatch:
+    SparseCPU, SparseMeta: add_out_sparse_cpu
+    SparseCUDA: add_out_sparse_cuda
+    SparseMPS: add_out_sparse_mps
+    SparseCsrCPU, SparseCsrMeta: add_out_sparse_compressed_cpu
+    SparseCsrCUDA: add_out_sparse_compressed_cuda
+    MkldnnCPU: mkldnn_add_out
+    MPS: add_out_mps
+    MTIA: add_out_mtia
+  tags: pointwise
+
+- func: _add_relu.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor
+  variants: function
+  dispatch:
+    CPU: add_relu
+
+- func: _add_relu_.Tensor(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!)
+  variants: function
+  dispatch:
+    CPU: add_relu_
+
+- func: _add_relu.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+  variants: function
+  dispatch:
+    CPU: add_relu_out
+
+- func: _add_relu.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor
+  variants: function
+  dispatch:
+    CPU: add_relu
+
+- func: _add_relu_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!)
+  variants: function
+  dispatch:
+    CPU: add_relu_
+  autogen: _add_relu.Scalar_out
+
+# For C++ only, until we have conversion from C++ numbers to Tensor
+- func: add.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: add
+  tags: [core, pointwise]
+
+- func: add_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: add_
+  autogen: add.Scalar_out
+  tags: pointwise
+
+- func: addmv(Tensor self, Tensor mat, Tensor vec, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+  structured_delegate: addmv.out
+  variants: function, method
+
+- func: addmv_(Tensor(a!) self, Tensor mat, Tensor vec, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!)
+  structured_delegate: addmv.out
+  variants: function, method
+
+- func: addmv.out(Tensor self, Tensor mat, Tensor vec, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  dispatch:
+    CPU: addmv_out_cpu
+    CUDA: addmv_out_cuda
+    MPS: addmv_out_mps
+    XPU: addmv_out_xpu
+    SparseCsrCPU: addmv_out_sparse_compressed
+    SparseCsrCUDA: addmv_out_sparse_compressed_cuda
+
+- func: addr(Tensor self, Tensor vec1, Tensor vec2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+  variants: function, method
+  dispatch:
+    CPU, CUDA: addr
+    MPS: addr_mps
+    CompositeExplicitAutograd: math_addr
+
+- func: addr_(Tensor(a!) self, Tensor vec1, Tensor vec2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!)
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: addr_
+
+- func: addr.out(Tensor self, Tensor vec1, Tensor vec2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA: addr_out
+    MPS: addr_out_mps
+    CompositeExplicitAutograd: math_addr_out
+
+- func: affine_grid_generator(Tensor theta, SymInt[] size, bool align_corners) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: affine_grid_generator
+  autogen: affine_grid_generator.out
+
+- func: affine_grid_generator_backward(Tensor grad, SymInt[] size, bool align_corners) -> Tensor
+  variants: function
+
+- func: _is_all_true(Tensor self) -> Tensor
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: _is_all_true
+
+- func: _is_any_true(Tensor self) -> Tensor
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: _is_any_true
+
+# Note: this function is only for testing.
+- func: _test_check_tensor(Tensor self) -> Tensor
+  variants: function
+
+# Note; this function is only for testing
+- func: _test_functorch_fallback(Tensor self, Tensor other) -> Tensor
+  variants: function
+  dispatch:
+    CPU: _test_functorch_fallback
+  autogen: _test_functorch_fallback.out
+
+- func: all.dim(Tensor self, int dim, bool keepdim=False) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: all.out
+  variants: function, method
+  dispatch:
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_all
+
+
+- func: all.dims(Tensor self, int[]? dim=None, bool keepdim=False) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: all.dims_out
+  variants: function, method
+  cpp_no_default_args: ['dim']
+  dispatch:
+    CompositeExplicitAutograd: all_dims_default
+
+- func: all.out(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  dispatch:
+    CPU, CUDA: all_out
+    MPS: all_out_mps
+    MTIA: all_out_mtia
+
+- func: all.dims_out(Tensor self, int[]? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  dispatch:
+    CPU, CUDA: all_dims_out
+    CompositeExplicitAutograd: all_dims_out_default
+  cpp_no_default_args: ['dim']
+
+- func: all.dimname(Tensor self, Dimname dim, bool keepdim=False) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: all.dimname_out(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+
+- func: allclose(Tensor self, Tensor other, float rtol=1e-05, float atol=1e-08, bool equal_nan=False) -> bool
+  variants: function, method
+  tags: data_dependent_output
+  dispatch:
+    CompositeExplicitAutograd: allclose
+
+- func: any.dim(Tensor self, int dim, bool keepdim=False) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: any.out
+  variants: function, method
+  tags: core
+
+- func: any.dims(Tensor self, int[]? dim=None, bool keepdim=False) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: any.dims_out
+  variants: function, method
+  cpp_no_default_args: ['dim']
+  tags: core
+  dispatch:
+    CompositeExplicitAutograd: any_dims_default
+
+- func: any.out(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  dispatch:
+    CPU, CUDA: any_out
+    MPS: any_out_mps
+
+- func: any.dims_out(Tensor self, int[]? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  dispatch:
+    CPU, CUDA: any_dims_out
+    CompositeExplicitAutograd: any_dims_out_default
+  cpp_no_default_args: ['dim']
+
+- func: any.dimname(Tensor self, Dimname dim, bool keepdim=False) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: any.dimname_out(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+
+- func: arange(Scalar end, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: arange
+
+- func: arange.start(Scalar start, Scalar end, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: arange
+
+# This operator should be named `arange.start_out` if following the naming convention. However that
+# name is already taken. Disabled because of CI job failures.
+# FIXME: enable this
+#- func: arange.start_out_(Scalar start, Scalar end, *, Tensor(a!) out) -> Tensor(a!)
+#  dispatch:
+#    CompositeExplicitAutograd: arange_start_out
+
+- func: arange.start_step(Scalar start, Scalar end, Scalar step=1, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: arange
+  cpp_no_default_args: ['step']
+  tags: core
+
+- func: arange.out(Scalar end, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: arange_out
+
+- func: arange.start_out(Scalar start, Scalar end, Scalar step=1, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, Meta: arange_out
+    CUDA: arange_cuda_out
+    MPS: arange_mps_out
+    MTIA: arange_mtia_out
+  cpp_no_default_args: ['step']
+
+# This function is a temporary hack to allow tracing of arange like constructs with dynamic
+# bounds on arange.  Normal arange is not traceable because it does not take any tensor inputs;
+# if the range you need is based on another tensor, calling this function directly will
+# preserve tracing.  Get rid of this when arange can directly take tensors for bounds
+# (so that it can be traced directly).
+- func: _dim_arange(Tensor like, int dim) -> Tensor
+
+- func: argmax(Tensor self, int? dim=None, bool keepdim=False) -> Tensor
+  structured_delegate: argmax.out
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  tags: core
+
+- func: argmax.out(Tensor self, int? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  dispatch:
+    CPU, CUDA: argmax_out
+    MPS: argmax_out_mps
+
+- func: argmin(Tensor self, int? dim=None, bool keepdim=False) -> Tensor
+  structured_delegate: argmin.out
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  tags: core
+
+- func: argmin.out(Tensor self, int? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  dispatch:
+    CPU, CUDA: argmin_out
+    MPS: argmin_out_mps
+
+- func: acosh(Tensor self) -> Tensor
+  variants: function, method
+  structured_delegate: acosh.out
+  tags: [core, pointwise]
+
+- func: acosh_(Tensor(a!) self) -> Tensor(a!)
+  variants: function, method
+  structured_delegate: acosh.out
+  tags: pointwise
+
+- func: acosh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: acosh_out
+    MPS: acosh_out_mps
+  tags: pointwise
+# arccosh, alias for acosh
+
+- func: arccosh(Tensor self) -> Tensor
+  variants: function, method
+
+- func: arccosh_(Tensor(a!) self) -> Tensor(a!)
+  variants: function, method
+
+- func: arccosh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: asinh(Tensor self) -> Tensor
+  variants: function, method
+  structured_delegate: asinh.out
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: asinh_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: asinh_sparse_csr
+  tags: [core, pointwise]
+
+- func: asinh_(Tensor(a!) self) -> Tensor(a!)
+  variants: function, method
+  structured_delegate: asinh.out
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: asinh_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: asinh_sparse_csr_
+  tags: pointwise
+
+- func: asinh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: asinh_out
+    MPS: asinh_out_mps
+    SparseCPU, SparseCUDA, SparseMPS: asinh_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: asinh_sparse_csr_out
+  tags: pointwise
+
+# arcsinh, alias for asinh
+- func: arcsinh(Tensor self) -> Tensor
+  variants: function, method
+
+- func: arcsinh_(Tensor(a!) self) -> Tensor(a!)
+  variants: function, method
+
+- func: arcsinh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: atanh(Tensor self) -> Tensor
+  structured_delegate: atanh.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: atanh_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: atanh_sparse_csr
+  tags: [core, pointwise]
+
+- func: atanh_(Tensor(a!) self) -> Tensor(a!)
+  structured_delegate: atanh.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: atanh_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: atanh_sparse_csr_
+  tags: pointwise
+
+- func: atanh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: atanh_out
+    MPS: atanh_out_mps
+    SparseCPU, SparseCUDA, SparseMPS: atanh_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: atanh_sparse_csr_out
+  tags: pointwise
+# arctanh, alias for atanh
+
+- func: arctanh(Tensor self) -> Tensor
+  variants: function, method
+
+- func: arctanh_(Tensor(a!) self) -> Tensor(a!)
+  variants: function, method
+
+- func: arctanh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: as_strided(Tensor(a) self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor(a)
+  variants: function, method
+  dispatch:
+    ZeroTensor, CPU, CUDA, MTIA, MPS: as_strided_tensorimpl
+    Meta: as_strided_tensorimpl_meta_symint
+    QuantizedCPU, QuantizedCUDA: as_strided_qtensorimpl
+  device_check: NoCheck
+  device_guard: False
+  tags: core
+
+- func: as_strided_(Tensor(a!) self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor(a!)
+  use_const_ref_for_mutable_tensors: True
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  tags: inplace_view
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: as_strided__symint
+
+- func: asin(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  structured_delegate: asin.out
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: asin_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: asin_sparse_csr
+  tags: [core, pointwise]
+
+- func: asin_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  structured_delegate: asin.out
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: asin_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: asin_sparse_csr_
+  tags: pointwise
+
+- func: asin.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: asin_out
+    SparseCPU, SparseCUDA, SparseMPS: asin_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: asin_sparse_csr_out
+  tags: pointwise
+
+# arcsin, alias of asin
+- func: arcsin(Tensor self) -> Tensor
+  variants: function, method
+
+- func: arcsin_(Tensor(a!) self) -> Tensor(a!)
+  variants: function, method
+
+- func: arcsin.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: atan(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: atan.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: atan_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: atan_sparse_csr
+  tags: [core, pointwise]
+
+- func: atan_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: atan.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: atan_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: atan_sparse_csr_
+  tags: pointwise
+
+- func: atan.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: atan_out
+    SparseCPU, SparseCUDA, SparseMPS: atan_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: atan_sparse_csr_out
+  tags: pointwise
+
+# arctan, alias of atan
+- func: arctan(Tensor self) -> Tensor
+  variants: function, method
+
+- func: arctan_(Tensor(a!) self) -> Tensor(a!)
+  variants: function, method
+
+- func: arctan.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: atleast_1d(Tensor self) -> Tensor
+  variants: function
+  tags: maybe_aliasing_or_mutating
+
+- func: atleast_1d.Sequence(Tensor[] tensors) -> Tensor[]
+
+- func: atleast_2d(Tensor self) -> Tensor
+  variants: function
+  tags: maybe_aliasing_or_mutating
+
+- func: atleast_2d.Sequence(Tensor[] tensors) -> Tensor[]
+  variants: function
+
+- func: atleast_3d(Tensor self) -> Tensor
+  variants: function
+  tags: maybe_aliasing_or_mutating
+
+- func: atleast_3d.Sequence(Tensor[] tensors) -> Tensor[]
+  variants: function
+
+- func: baddbmm(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+  variants: function, method
+  structured_delegate: baddbmm.out
+
+- func: baddbmm_(Tensor(a!) self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!)
+  variants: method
+  structured_delegate: baddbmm.out
+
+- func: baddbmm.out(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  variants: function
+  dispatch:
+    CPU: baddbmm_out_cpu
+    CUDA: baddbmm_out_cuda
+    MPS: baddbmm_out_mps
+    XPU: baddbmm_out_xpu
+    MTIA: baddbmm_out_mtia
+    SparseCsrCUDA: baddbmm_out_sparse_csr_cuda
+
+- func: baddbmm.dtype(Tensor self, Tensor batch1, Tensor batch2, ScalarType out_dtype, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+  variants: function
+  dispatch:
+    CUDA: _baddbmm_dtype_cuda
+
+- func: baddbmm.dtype_out(Tensor self, Tensor batch1, Tensor batch2, ScalarType out_dtype, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+  variants: function
+  dispatch:
+    CUDA: _baddbmm_out_dtype_cuda
+
+- func: bartlett_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: bartlett_window
+  autogen: bartlett_window.out
+
+- func: bartlett_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: bartlett_window
+  autogen: bartlett_window.periodic_out
+
+- func: batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps, bool cudnn_enabled) -> Tensor
+  tags: maybe_aliasing_or_mutating
+
+- func: quantized_batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor mean, Tensor var, float eps, float output_scale, int output_zero_point) -> Tensor
+  dispatch:
+    QuantizedCPU: quantized_batch_norm
+  autogen: quantized_batch_norm.out
+
+- func: _batch_norm_impl_index(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps, bool cudnn_enabled) -> (Tensor, Tensor, Tensor, Tensor, int)
+  tags: maybe_aliasing_or_mutating
+
+- func: _batch_norm_impl_index_backward(int impl_index, Tensor input, Tensor grad_output, Tensor? weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var_transform, bool train, float eps, bool[3] output_mask, Tensor reservedSpace) -> (Tensor, Tensor, Tensor)
+
+# Sample bernoulli with values in `self` as probability.
+- func: bernoulli(Tensor self, *, Generator? generator=None) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: bernoulli
+  tags: nondeterministic_seeded
+
+- func: bernoulli.out(Tensor self, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  tags: nondeterministic_seeded
+  dispatch:
+    CPU, CUDA: bernoulli_out
+    MPS: bernoulli_out_mps
+
+- func: bernoulli_.Tensor(Tensor(a!) self, Tensor p, *, Generator? generator=None) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  tags: nondeterministic_seeded
+  dispatch:
+    CPU, CUDA: bernoulli_
+    MPS: bernoulli_mps_
+  autogen: bernoulli.Tensor, bernoulli.Tensor_out
+
+- func: bernoulli_.float(Tensor(a!) self, float p=0.5, *, Generator? generator=None) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  tags: nondeterministic_seeded
+  dispatch:
+    CPU, CUDA: bernoulli_
+    MPS: bernoulli_mps_
+  autogen: bernoulli.float_out
+
+# Note [bernoulli.p schema]
+# We should probably just fix the overload ambiguity by appending a _functional to the C++ API name (BC breaking)
+# This out-of-place version isn't used explicitly, but needed by jit.
+# There is no default valid on `p` here because it would introduce ambiguity
+# with `bernoulli(Tensor self, *, Generator? generator=None)` declaration.
+- func: bernoulli.p(Tensor self, float p, *, Generator? generator=None) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  tags: nondeterministic_seeded
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: bernoulli
+
+- func: bilinear(Tensor input1, Tensor input2, Tensor weight, Tensor? bias=None) -> Tensor
+
+- func: binary_cross_entropy(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  variants: function
+  dispatch:
+    CPU: binary_cross_entropy_cpu
+    CUDA: binary_cross_entropy_cuda
+    MPS: binary_cross_entropy_mps
+
+- func: binary_cross_entropy.out(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  variants: function
+  dispatch:
+    CPU: binary_cross_entropy_out_cpu
+    CUDA: binary_cross_entropy_out_cuda
+    MPS: binary_cross_entropy_out_mps
+
+- func: binary_cross_entropy_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean) -> Tensor
+  python_module: nn
+  variants: function
+  dispatch:
+    CPU: binary_cross_entropy_backward_cpu
+    CUDA: binary_cross_entropy_backward_cuda
+    MPS: binary_cross_entropy_backward_mps
+
+- func: binary_cross_entropy_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  variants: function
+  dispatch:
+    CPU: binary_cross_entropy_backward_out_cpu
+    CUDA: binary_cross_entropy_backward_out_cuda
+    MPS: binary_cross_entropy_backward_out_mps
+
+- func: binary_cross_entropy_with_logits(Tensor self, Tensor target, Tensor? weight=None, Tensor? pos_weight=None, int reduction=Mean) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: binary_cross_entropy_with_logits
+  autogen: binary_cross_entropy_with_logits.out
+
+- func: bincount(Tensor self, Tensor? weights=None, SymInt minlength=0) -> Tensor
+  variants: function, method
+  dispatch:
+    CPU: _bincount_cpu
+    CUDA: _bincount_cuda
+    MPS: _bincount_mps
+  tags: dynamic_output_shape
+  autogen: bincount.out
+
+- func: bitwise_not(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: bitwise_not.out
+  variants: function, method
+  tags: [core, pointwise]
+
+- func: bitwise_not_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: bitwise_not.out
+  variants: method
+  tags: pointwise
+
+- func: bitwise_not.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS, MTIA: bitwise_not_out
+  tags: pointwise
+
+- func: copysign.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: copysign_out
+  tags: pointwise
+
+- func: copysign.Tensor(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  structured_delegate: copysign.out
+  tags: pointwise
+
+- func: copysign_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  structured_delegate: copysign.out
+
+- func: copysign.Scalar(Tensor self, Scalar other) -> Tensor
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: copysign
+  tags: pointwise
+
+- func: copysign_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: copysign_
+
+- func: copysign.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: copysign_out
+  tags: pointwise
+
+- func: _lazy_clone(Tensor self) -> Tensor
+  # Like clone, but the copy takes place lazily, only if either the
+  # input or the output are written.
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: _lazy_clone
+
+- func: logical_not(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: logical_not
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_logical_not
+  tags: [core, pointwise]
+
+- func: logical_not_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: logical_not_
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_logical_not_
+  tags: pointwise
+
+- func: logical_not.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MTIA: logical_not_out
+    MPS: logical_not_out_mps
+  tags: pointwise
+
+- func: logical_xor(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: logical_xor
+  tags: [core, pointwise]
+
+- func: logical_xor_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: logical_xor_
+  tags: pointwise
+
+- func: logical_xor.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA: logical_xor_out
+    MPS: logical_xor_out_mps
+  tags: pointwise
+
+- func: logical_and(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: logical_and
+  tags: [core, pointwise]
+
+- func: logical_and_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: logical_and_
+  tags: pointwise
+
+- func: logical_and.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MTIA: logical_and_out
+    MPS: logical_and_out_mps
+  tags: pointwise
+
+- func: logical_or(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: logical_or
+  tags: [core, pointwise]
+
+- func: logical_or_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: logical_or_
+  tags: pointwise
+
+- func: logical_or.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MTIA: logical_or_out
+    MPS: logical_or_out_mps
+  tags: pointwise
+
+- func: blackman_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: blackman_window
+  autogen: blackman_window.out
+
+- func: blackman_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: blackman_window
+  autogen: blackman_window.periodic_out
+
+- func: bmm(Tensor self, Tensor mat2) -> Tensor
+  structured_delegate: bmm.out
+  variants: function, method
+  dispatch:
+    SparseCPU: bmm_sparse_cpu
+    SparseCUDA: bmm_sparse_cuda
+    NestedTensorCPU: bmm_nested
+    NestedTensorCUDA: bmm_nested_cuda
+  tags: core
+
+- func: bmm.out(Tensor self, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  variants: function
+  dispatch:
+    CPU: bmm_out_cpu
+    CUDA: bmm_out_cuda
+    MPS: bmm_out_mps
+    XPU: bmm_out_xpu
+    MTIA: bmm_out_mtia
+    SparseCPU: bmm_out_sparse_cpu
+    SparseCUDA: bmm_out_sparse_cuda
+    SparseCsrCUDA: bmm_out_sparse_csr_cuda
+
+- func: bmm.dtype(Tensor self, Tensor mat2, ScalarType out_dtype) -> Tensor
+  variants: function
+  dispatch:
+    CUDA: _bmm_dtype_cuda
+
+- func: bmm.dtype_out(Tensor self, Tensor mat2, ScalarType out_dtype, *, Tensor(a!) out) -> Tensor(a!)
+  variants: function
+  dispatch:
+    CUDA: _bmm_out_dtype_cuda
+
+- func: broadcast_tensors(Tensor[] tensors) -> Tensor[]
+  device_check: NoCheck
+  device_guard: False
+
+- func: broadcast_to(Tensor(a) self, SymInt[] size) -> Tensor(a)
+  variants: function, method
+  dispatch:
+    CompositeImplicitAutograd: broadcast_to_symint
+
+- func: _sparse_broadcast_to(Tensor(a) self, int[] size) -> Tensor(a)
+  variants: function
+  dispatch:
+    SparseCPU, SparseCUDA: sparse_broadcast_to
+
+- func: cat(Tensor[] tensors, int dim=0) -> Tensor
+  structured_delegate: cat.out
+  dispatch:
+    SparseCPU, SparseCUDA: cat_sparse
+    QuantizedCPU: cat_quantized_cpu
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: cat_nested
+  tags: core
+
+- func: cat.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  precomputed:
+  - dim -> int dim, int valid, bool all_contiguous, bool all_same_dtype, bool all_same_sizes_and_stride, MemoryFormat memory_format
+  dispatch:
+    CPU: cat_out_cpu
+    CUDA: cat_out_cuda
+    MPS: cat_out_mps
+    QuantizedCPU: cat_out_quantized_cpu
+
+- func: cat.names(Tensor[] tensors, Dimname dim) -> Tensor
+
+- func: cat.names_out(Tensor[] tensors, Dimname dim, *, Tensor(a!) out) -> Tensor(a!)
+
+# alias for torch.cat
+- func: concat(Tensor[] tensors, int dim=0) -> Tensor
+
+- func: concat.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: concat.names(Tensor[] tensors, Dimname dim) -> Tensor
+
+- func: concat.names_out(Tensor[] tensors, Dimname dim, *, Tensor(a!) out) -> Tensor(a!)
+
+# alias for torch.cat
+- func: concatenate(Tensor[] tensors, int dim=0) -> Tensor
+
+- func: concatenate.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: concatenate.names(Tensor[] tensors, Dimname dim) -> Tensor
+
+- func: concatenate.names_out(Tensor[] tensors, Dimname dim, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: block_diag(Tensor[] tensors) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: block_diag
+  autogen: block_diag.out
+
+- func: ceil(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: ceil.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: ceil_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: ceil_sparse_csr
+  tags: [core, pointwise]
+
+- func: ceil_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: ceil.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: ceil_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: ceil_sparse_csr_
+  tags: pointwise
+
+- func: ceil.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: ceil_out
+    SparseCPU, SparseCUDA, SparseMPS: ceil_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: ceil_sparse_csr_out
+  tags: pointwise
+
+# alias for torch.linalg.multi_dot
+- func: chain_matmul(Tensor[] matrices) -> Tensor
+  variants: function
+
+# alias for torch.linalg.multi_dot
+- func: chain_matmul.out(Tensor[] matrices, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: unsafe_chunk(Tensor self, int chunks, int dim=0) -> Tensor[]
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  tags: maybe_aliasing_or_mutating
+
+- func: chunk(Tensor(a -> *) self, int chunks, int dim=0) -> Tensor(a)[]
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeImplicitAutograd: chunk
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: chunk_nested_tensor
+
+- func: tensor_split.sections(Tensor(a -> *) self, SymInt sections, int dim=0) -> Tensor(a)[]
+  variants: function, method
+  dispatch:
+    CompositeImplicitAutograd: tensor_split_sections_symint
+
+- func: tensor_split.indices(Tensor(a -> *) self, SymInt[] indices, int dim=0) -> Tensor(a)[]
+  variants: function, method
+  dispatch:
+    CompositeImplicitAutograd: tensor_split_indices_symint
+
+- func: tensor_split.tensor_indices_or_sections(Tensor(a -> *) self, Tensor tensor_indices_or_sections, int dim=0) -> Tensor(a)[]
+  variants: function, method
+
+- func: clamp(Tensor self, Scalar? min=None, Scalar? max=None) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  cpp_no_default_args: ['min']
+  structured_delegate: clamp.out
+  dispatch:
+    QuantizedCPU: clamp_quantized_cpu
+  tags: [core, pointwise]
+
+- func: clamp.Tensor(Tensor self, Tensor? min=None, Tensor? max=None) -> Tensor
+  variants: function, method
+  structured_delegate: clamp.Tensor_out
+  tags: [core, pointwise]
+
+- func: clamp_(Tensor(a!) self, Scalar? min=None, Scalar? max=None) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  cpp_no_default_args: ['min']
+  structured_delegate: clamp.out
+  tags: pointwise
+
+- func: clamp_.Tensor(Tensor(a!) self, Tensor? min=None, Tensor? max=None) -> Tensor(a!)
+  variants: function, method
+  structured_delegate: clamp.Tensor_out
+  tags: pointwise
+
+- func: clamp.out(Tensor self, Scalar? min=None, Scalar? max=None, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  cpp_no_default_args: ['min']
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MTIA: clamp_out
+    MPS: clamp_out_mps
+  tags: pointwise
+
+- func: clamp.Tensor_out(Tensor self, Tensor? min=None, Tensor? max=None, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: clamp_Tensor_out
+    MPS: clamp_Tensor_out_mps
+  tags: pointwise
+
+- func: clamp_max(Tensor self, Scalar max) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  structured_delegate: clamp_max.out
+  tags: pointwise
+
+- func: clamp_max.Tensor(Tensor self, Tensor max) -> Tensor
+  variants: function, method
+  structured_delegate: clamp_max.Tensor_out
+  tags: pointwise
+
+- func: clamp_max_(Tensor(a!) self, Scalar max) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  structured_delegate: clamp_max.out
+  tags: pointwise
+
+- func: clamp_max_.Tensor(Tensor(a!) self, Tensor max) -> Tensor(a!)
+  variants: function, method
+  structured_delegate: clamp_max.Tensor_out
+  tags: pointwise
+
+- func: clamp_max.out(Tensor self, Scalar max, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MTIA: clamp_max_out
+    MPS: clamp_max_out_mps
+  tags: pointwise
+
+- func: clamp_max.Tensor_out(Tensor self, Tensor max, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: clamp_max_Tensor_out
+    MPS: clamp_max_Tensor_out_mps
+  tags: pointwise
+
+- func: clamp_min(Tensor self, Scalar min) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  structured_delegate: clamp_min.out
+  tags: pointwise
+
+- func: clamp_min.Tensor(Tensor self, Tensor min) -> Tensor
+  variants: function, method
+  structured_delegate: clamp_min.Tensor_out
+  tags: pointwise
+
+- func: clamp_min_(Tensor(a!) self, Scalar min) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  structured_delegate: clamp_min.out
+  tags: pointwise
+
+- func: clamp_min_.Tensor(Tensor(a!) self, Tensor min) -> Tensor(a!)
+  variants: function, method
+  structured_delegate: clamp_min.Tensor_out
+  tags: pointwise
+
+- func: clamp_min.out(Tensor self, Scalar min, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MTIA: clamp_min_out
+    MPS: clamp_min_out_mps
+  tags: pointwise
+
+- func: clamp_min.Tensor_out(Tensor self, Tensor min, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: clamp_min_Tensor_out
+    MPS: clamp_min_Tensor_out_mps
+  tags: pointwise
+
+# clip is an alias for clamp
+- func: clip(Tensor self, Scalar? min=None, Scalar? max=None) -> Tensor
+  cpp_no_default_args: ['min']
+  variants: function, method
+  tags: pointwise
+
+- func: clip.Tensor(Tensor self, Tensor? min=None, Tensor? max=None) -> Tensor
+  variants: function, method
+  tags: pointwise
+
+- func: clip_(Tensor(a!) self, Scalar? min=None, Scalar? max=None) -> Tensor(a!)
+  cpp_no_default_args: ['min']
+  variants: function, method
+  tags: pointwise
+
+- func: clip_.Tensor(Tensor(a!) self, Tensor? min=None, Tensor? max=None) -> Tensor(a!)
+  variants: function, method
+  tags: pointwise
+
+- func: clip.out(Tensor self, Scalar? min=None, Scalar? max=None, *, Tensor(a!) out) -> Tensor(a!)
+  cpp_no_default_args: ['min']
+  tags: pointwise
+
+- func: clip.Tensor_out(Tensor self, Tensor? min=None, Tensor? max=None, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: cudnn_is_acceptable(Tensor self) -> bool
+  device_check: NoCheck
+  device_guard: False
+
+- func: complex(Tensor real, Tensor imag) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: complex
+
+- func: complex.out(Tensor real, Tensor imag, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA, MPS: complex_out
+
+- func: polar(Tensor abs, Tensor angle) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: polar
+
+- func: polar.out(Tensor abs, Tensor angle, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA, MPS: polar_out
+
+- func: constant_pad_nd(Tensor self, SymInt[] pad, Scalar value=0) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: constant_pad_nd
+    MPS: constant_pad_nd_mps
+  autogen: constant_pad_nd.out
+  tags: core
+
+- func: contiguous(Tensor(a) self, *, MemoryFormat memory_format=contiguous_format) -> Tensor(a)
+  variants: method
+  manual_cpp_binding: True
+
+- func: convolution(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: convolution
+  autogen: convolution.out
+  tags: core
+
+- func: convolution_backward(Tensor grad_output, Tensor input, Tensor weight, SymInt[]? bias_sizes, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    CompositeExplicitAutograd, CUDA: convolution_backward
+  autogen: convolution_backward.out
+  tags: core
+
+- func: convolution_overrideable(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: convolution_overrideable
+  autogen: convolution_overrideable.out
+
+- func: convolution_backward_overrideable(Tensor grad_output, Tensor input, Tensor weight, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias)
+  dispatch:
+    CompositeExplicitAutograd: convolution_backward_overrideable
+  autogen: convolution_backward_overrideable.out
+
+- func: _convolution(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool benchmark, bool deterministic, bool cudnn_enabled, bool allow_tf32) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: _convolution
+  autogen: _convolution.out
+
+- func: _convolution.deprecated(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, int[] output_padding, SymInt groups, bool benchmark, bool deterministic, bool cudnn_enabled) -> Tensor
+
+- func: _convolution_mode(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, str padding, SymInt[] dilation, SymInt groups) -> Tensor
+  dispatch:
+    CompositeImplicitAutograd: _convolution_mode_symint
+
+- func: _convolution_double_backward(Tensor? ggI, Tensor? ggW, Tensor? ggb, Tensor gO, Tensor weight, Tensor self, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+
+- func: conv1d(Tensor input, Tensor weight, Tensor? bias=None, SymInt[1] stride=1, SymInt[1] padding=0, SymInt[1] dilation=1, SymInt groups=1) -> Tensor
+  dispatch:
+    CompositeImplicitAutograd: conv1d_symint
+
+- func: conv2d(Tensor input, Tensor weight, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] dilation=1, SymInt groups=1) -> Tensor
+  dispatch:
+    CompositeImplicitAutograd: conv2d_symint
+
+- func: conv3d(Tensor input, Tensor weight, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] dilation=1, SymInt groups=1) -> Tensor
+  dispatch:
+    CompositeImplicitAutograd: conv3d_symint
+
+- func: conv1d.padding(Tensor input, Tensor weight, Tensor? bias=None, SymInt[1] stride=1, str padding="valid", SymInt[1] dilation=1, SymInt groups=1) -> Tensor
+  cpp_no_default_args: ['bias', 'stride', 'padding']
+  dispatch:
+    CompositeImplicitAutograd: conv1d_padding_symint
+
+- func: conv2d.padding(Tensor input, Tensor weight, Tensor? bias=None, SymInt[2] stride=1, str padding="valid", SymInt[2] dilation=1, SymInt groups=1) -> Tensor
+  cpp_no_default_args: ['bias', 'stride', 'padding']
+  dispatch:
+    CompositeImplicitAutograd: conv2d_padding_symint
+
+- func: conv3d.padding(Tensor input, Tensor weight, Tensor? bias=None, SymInt[3] stride=1, str padding="valid", SymInt[3] dilation=1, SymInt groups=1) -> Tensor
+  cpp_no_default_args: ['bias', 'stride', 'padding']
+  dispatch:
+    CompositeImplicitAutograd: conv3d_padding_symint
+
+- func: conv_tbc(Tensor self, Tensor weight, Tensor bias, int pad=0) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: conv_tbc
+  autogen: conv_tbc.out
+
+- func: conv_tbc_backward(Tensor self, Tensor input, Tensor weight, Tensor bias, int pad) -> (Tensor, Tensor, Tensor)
+
+# NB: we inherit the goofy argument order from PyTorch torch.nn.functional
+- func: conv_transpose1d(Tensor input, Tensor weight, Tensor? bias=None, SymInt[1] stride=1, SymInt[1] padding=0, SymInt[1] output_padding=0, SymInt groups=1, SymInt[1] dilation=1) -> Tensor
+  dispatch:
+    CompositeImplicitAutograd: conv_transpose1d_symint
+
+- func: conv_transpose2d.input(Tensor input, Tensor weight, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] output_padding=0, SymInt groups=1, SymInt[2] dilation=1) -> Tensor
+  dispatch:
+    CompositeImplicitAutograd: conv_transpose2d_symint
+
+- func: conv_transpose3d.input(Tensor input, Tensor weight, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] output_padding=0, SymInt groups=1, SymInt[3] dilation=1) -> Tensor
+  dispatch:
+    CompositeImplicitAutograd: conv_transpose3d_symint
+
+- func: copy(Tensor self, Tensor src, bool non_blocking=False) -> Tensor
+  variants: function
+  dispatch:
+    Meta: copy_meta
+    CompositeExplicitAutogradNonFunctional: copy
+  tags: core
+
+- func: copy_(Tensor(a!) self, Tensor src, bool non_blocking=False) -> Tensor(a!)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    MkldnnCPU: copy_mkldnn_
+    SparseCPU, SparseCUDA: copy_sparse_wrapper_
+    CompositeExplicitAutograd: copy_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: copy_sparse_compressed_
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: copy_nested_
+  autogen: copy.out
+
+- func: _copy_from(Tensor self, Tensor dst, bool non_blocking=False) -> Tensor
+  dispatch:
+    MPS: _copy_from_mps
+  autogen: _copy_from.out
+
+# We need this to be able to properly copy from a CPU to an XLA tensor with different sizes.
+# See https://github.com/pytorch/xla/issues/2881
+- func: _copy_from_and_resize(Tensor self, Tensor dst) -> Tensor
+  dispatch:
+    MPS: _copy_from_and_resize_mps
+  autogen: _copy_from_and_resize.out
+
+- func: cos(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  structured_delegate: cos.out
+  dispatch:
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_cos
+  tags: [core, pointwise]
+
+- func: cos_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  structured_delegate: cos.out
+  tags: pointwise
+
+- func: cos.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS, MTIA: cos_out
+  tags: pointwise
+
+- func: cosh(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  structured_delegate: cosh.out
+  tags: [core, pointwise]
+
+- func: cosh_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  structured_delegate: cosh.out
+  tags: pointwise
+
+- func: cosh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: cosh_out
+  tags: pointwise
+
+- func: cosine_embedding_loss(Tensor input1, Tensor input2, Tensor target, float margin=0.0, int reduction=Mean) -> Tensor
+
+- func: count_nonzero.dim_IntList(Tensor self, int[] dim) -> Tensor
+  variants: function, method
+  dispatch:
+    CPU: count_nonzero_cpu
+    CUDA: count_nonzero_cuda
+    MPS: count_nonzero_mps
+  autogen: count_nonzero.dim_IntList_out
+
+- func: count_nonzero(Tensor self, int? dim=None) -> Tensor
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: count_nonzero
+  autogen: count_nonzero.out
+
+- func: cov(Tensor self, *, int correction=1, Tensor? fweights=None, Tensor? aweights=None) -> Tensor
+  variants: function, method
+
+- func: corrcoef(Tensor self) -> Tensor
+  variants: function, method
+
+- func: cudnn_affine_grid_generator(Tensor theta, int N, int C, int H, int W) -> Tensor grid
+  dispatch:
+    CUDA: cudnn_affine_grid_generator_forward
+  autogen: cudnn_affine_grid_generator.out
+
+# TODO: Why do I have to call this grad?!
+- func: cudnn_affine_grid_generator_backward(Tensor grad, int N, int C, int H, int W) -> Tensor grad_theta
+  dispatch:
+    CUDA: cudnn_affine_grid_generator_backward
+  autogen: cudnn_affine_grid_generator_backward.out
+
+- func: cudnn_batch_norm(Tensor input, Tensor weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float exponential_average_factor, float epsilon) -> (Tensor, Tensor, Tensor, Tensor)
+  dispatch:
+    CUDA: cudnn_batch_norm
+
+- func: cudnn_batch_norm.out(Tensor input, Tensor weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float exponential_average_factor, float epsilon, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2, Tensor(d!) out3) -> (Tensor(a!), Tensor(b!), Tensor(c!), Tensor(d!))
+  dispatch:
+    CUDA: cudnn_batch_norm_out
+
+# NB: You can only use this if you used cudnn_batch_norm training=True
+- func: cudnn_batch_norm_backward(Tensor input, Tensor grad_output, Tensor weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var, float epsilon, Tensor reserveSpace) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    CUDA: cudnn_batch_norm_backward
+  autogen: cudnn_batch_norm_backward.out
+
+- func: cudnn_convolution(Tensor self, Tensor weight, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic, bool allow_tf32) -> Tensor
+  dispatch:
+    CUDA: cudnn_convolution
+
+- func: cudnn_convolution.out(Tensor self, Tensor weight, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic, bool allow_tf32, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CUDA: cudnn_convolution_out
+
+- func: cudnn_convolution_transpose(Tensor self, Tensor weight, SymInt[] padding, SymInt[] output_padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic, bool allow_tf32) -> Tensor
+  dispatch:
+    CUDA: cudnn_convolution_transpose
+  autogen: cudnn_convolution_transpose.out
+
+- func: _mps_convolution_transpose(Tensor self, Tensor weight, SymInt[] padding, SymInt[] output_padding, SymInt[] stride, SymInt[] dilation, SymInt groups) -> Tensor
+  dispatch:
+    MPS: _mps_convolution_transpose
+  autogen: _mps_convolution_transpose.out
+
+- func: mps_convolution_transpose_backward(Tensor self, Tensor grad_output, Tensor weight, SymInt[] padding, SymInt[] output_padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool[2] output_mask) -> (Tensor, Tensor)
+  dispatch:
+    MPS: mps_convolution_transpose_backward
+  autogen: mps_convolution_transpose_backward.out
+
+- func: cudnn_convolution_relu(Tensor self, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups) -> Tensor
+  dispatch:
+    CUDA: cudnn_convolution_relu
+  autogen: cudnn_convolution_relu.out
+
+- func: cudnn_convolution_add_relu(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups) -> Tensor
+  dispatch:
+    CUDA: cudnn_convolution_add_relu
+  autogen: cudnn_convolution_add_relu.out
+
+# NB: input is special cased in a way I don't quite understand
+- func: cudnn_grid_sampler(Tensor self, Tensor grid) -> Tensor output
+  dispatch:
+    CUDA: cudnn_grid_sampler_forward
+  autogen: cudnn_grid_sampler.out
+
+- func: cudnn_grid_sampler_backward(Tensor self, Tensor grid, Tensor grad_output) -> (Tensor grad_self, Tensor grad_grid)
+  dispatch:
+    CUDA: cudnn_grid_sampler_backward
+  autogen: cudnn_grid_sampler_backward.out
+
+- func: cummax(Tensor self, int dim) -> (Tensor values, Tensor indices)
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: cummax
+
+- func: cummax.out(Tensor self, int dim, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CompositeExplicitAutograd: cummax_out
+
+- func: cummax.dimname(Tensor self, Dimname dim) -> (Tensor values, Tensor indices)
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: cummax.dimname_out(Tensor self, Dimname dim, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+  device_check: NoCheck   # TensorIterator
+
+- func: _cummax_helper(Tensor self, Tensor(a!) values, Tensor(b!) indices, int dim) -> ()
+  variants: function
+  dispatch:
+    CPU: cummax_helper_cpu
+    CUDA: cummax_helper_cuda
+    MPS: cummax_helper_mps
+
+- func: cummin(Tensor self, int dim) -> (Tensor values, Tensor indices)
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: cummin
+
+- func: cummin.out(Tensor self, int dim, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CompositeExplicitAutograd: cummin_out
+
+- func: cummin.dimname(Tensor self, Dimname dim) -> (Tensor values, Tensor indices)
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: cummin.dimname_out(Tensor self, Dimname dim, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+  device_check: NoCheck   # TensorIterator
+
+- func: _cummin_helper(Tensor self, Tensor(a!) values, Tensor(b!) indices, int dim) -> ()
+  variants: function
+  dispatch:
+    CPU: cummin_helper_cpu
+    CUDA: cummin_helper_cuda
+    MPS: cummin_helper_mps
+
+- func: cummaxmin_backward(Tensor grad, Tensor input, Tensor indices, int dim) -> Tensor
+  variants: function
+  device_check: NoCheck
+  device_guard: False
+
+- func: cumprod(Tensor self, int dim, *, ScalarType? dtype=None) -> Tensor
+  structured_delegate: cumprod.out
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: cumprod_(Tensor(a!) self, int dim, *, ScalarType? dtype=None) -> Tensor(a!)
+  structured_delegate: cumprod.out
+  variants: method
+
+- func: cumprod.out(Tensor self, int dim, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA: cumprod_out
+    MPS: cumprod_out_mps
+
+- func: cumprod.dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: cumprod_.dimname(Tensor(a!) self, Dimname dim, *, ScalarType? dtype=None) -> Tensor(a!)
+  variants: method
+
+- func: cumprod.dimname_out(Tensor self, Dimname dim, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+
+- func: cumprod_backward(Tensor grad, Tensor input, int dim, Tensor output) -> Tensor
+  variants: function
+  device_check: NoCheck
+  device_guard: False
+
+- func: cumsum(Tensor self, int dim, *, ScalarType? dtype=None) -> Tensor
+  structured_delegate: cumsum.out
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  tags: core
+
+- func: cumsum_(Tensor(a!) self, int dim, *, ScalarType? dtype=None) -> Tensor(a!)
+  structured_delegate: cumsum.out
+  variants: method
+
+- func: cumsum.out(Tensor self, int dim, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA: cumsum_out
+    MPS: cumsum_out_mps
+
+- func: cumsum.dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: cumsum_.dimname(Tensor(a!) self, Dimname dim, *, ScalarType? dtype=None) -> Tensor(a!)
+  variants: method
+
+- func: cumsum.dimname_out(Tensor self, Dimname dim, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+
+- func: cumulative_trapezoid.x(Tensor y, Tensor x, *, int dim=-1) -> Tensor
+
+- func: cumulative_trapezoid.dx(Tensor y, *, Scalar dx=1, int dim=-1) -> Tensor
+
+- func: ctc_loss.IntList(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank=0, int reduction=Mean, bool zero_infinity=False) -> Tensor
+
+# convenience function that converts to intlists for you
+- func: ctc_loss.Tensor(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank=0, int reduction=Mean, bool zero_infinity=False) -> Tensor
+
+- func: _ctc_loss(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank=0, bool zero_infinity=False) -> (Tensor, Tensor)
+  dispatch:
+    CPU: ctc_loss_cpu
+    CUDA: ctc_loss_gpu
+    Meta: ctc_loss_meta
+  autogen: _ctc_loss.out
+  tags: dynamic_output_shape  # the shape of second output is data dependent
+
+- func: _ctc_loss.Tensor(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank=0, bool zero_infinity=False) -> (Tensor, Tensor)
+  dispatch:
+    CPU, CUDA: ctc_loss_tensor
+  autogen: _ctc_loss.Tensor_out
+  tags: dynamic_output_shape  # the shape of second output is data dependent
+
+- func: _ctc_loss_backward(Tensor grad, Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, Tensor neg_log_likelihood, Tensor log_alpha, int blank, bool zero_infinity=False) -> Tensor
+  dispatch:
+    CPU: ctc_loss_backward_cpu
+    CUDA: ctc_loss_backward_gpu
+  autogen: _ctc_loss_backward.out
+
+- func: _ctc_loss_backward.Tensor(Tensor grad, Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, Tensor neg_log_likelihood, Tensor log_alpha, int blank, bool zero_infinity=False) -> Tensor
+  dispatch:
+    CPU, CUDA: ctc_loss_backward_tensor
+
+- func: diag_embed(Tensor self, int offset=0, int dim1=-2, int dim2=-1) -> Tensor
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: diag_embed
+  autogen: diag_embed.out
+
+- func: diagflat(Tensor self, int offset=0) -> Tensor
+  variants: function, method
+
+- func: diagonal(Tensor(a) self, int offset=0, int dim1=0, int dim2=1) -> Tensor(a)
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: diagonal
+  tags: core
+
+- func: linalg_diagonal(Tensor(a) A, *, int offset=0, int dim1=-2, int dim2=-1) -> Tensor(a)
+  python_module: linalg
+  variants: function
+
+- func: diagonal.Dimname(Tensor(a) self, *, Dimname outdim, Dimname dim1, Dimname dim2, int offset=0) -> Tensor(a)
+  variants: function, method
+
+- func: diagonal_backward(Tensor grad_output, SymInt[] input_sizes, int offset, int dim1, int dim2) -> Tensor
+  variants: function
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: diagonal_backward_symint
+  autogen: diagonal_backward.out
+
+- func: fill_diagonal_(Tensor(a!) self, Scalar fill_value, bool wrap=False) -> Tensor(a!)
+  variants: method
+
+- func: diff(Tensor self, int n=1, int dim=-1, Tensor? prepend=None, Tensor? append=None) -> Tensor
+  variants: function, method
+
+- func: diff.out(Tensor self, int n=1, int dim=-1, Tensor? prepend=None, Tensor? append=None, *, Tensor(a!) out) -> Tensor(a!)
+  variants: function
+
+- func: gradient.scalarint(Tensor self, *, Scalar? spacing=None, int? dim=None, int edge_order=1) -> Tensor[]
+  variants: function
+
+- func: gradient.scalararray(Tensor self, *, Scalar spacing, int[] dim, int edge_order=1) -> Tensor[]
+  variants: function
+
+- func: gradient.array(Tensor self, *, int[] dim, int edge_order=1) -> Tensor[]
+  variants: function
+
+- func: gradient.scalarrayint(Tensor self, *, Scalar[] spacing, int? dim=None, int edge_order=1) -> Tensor[]
+  variants: function
+
+- func: gradient.scalarrayarray(Tensor self, *, Scalar[] spacing, int[] dim, int edge_order=1) -> Tensor[]
+  variants: function
+
+- func: gradient.tensorarrayint(Tensor self, *, Tensor[] spacing, int? dim=None, int edge_order=1) -> Tensor[]
+  variants: function
+
+- func: gradient.tensorarray(Tensor self, *, Tensor[] spacing, int[] dim, int edge_order=1) -> Tensor[]
+  variants: function
+
+- func: div.Tensor(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  structured_delegate: div.out
+  dispatch:
+    SparseCPU, SparseCUDA: div_sparse
+    ZeroTensor: div_zerotensor
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_div_Tensor
+  tags: [core, pointwise]
+
+- func: div_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  structured_delegate: div.out
+  dispatch:
+    SparseCPU, SparseCUDA: div_sparse_
+  tags: pointwise
+
+- func: div.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS, MTIA: div_out
+    SparseCPU, SparseCUDA: div_out_sparse_zerodim
+  tags: pointwise
+
+- func: div.Tensor_mode(Tensor self, Tensor other, *, str? rounding_mode) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  structured_delegate: div.out_mode
+  dispatch:
+    SparseCPU, SparseCUDA: div_sparse
+  tags: [core, pointwise]
+
+- func: div_.Tensor_mode(Tensor(a!) self, Tensor other, *, str? rounding_mode) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  structured_delegate: div.out_mode
+  dispatch:
+    SparseCPU, SparseCUDA: div_sparse_
+  tags: pointwise
+
+- func: div.out_mode(Tensor self, Tensor other, *, str? rounding_mode, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: div_out_mode
+    SparseCPU, SparseCUDA: div_out_sparse_zerodim
+  tags: pointwise
+
+# For C++ only, until we have conversion from C++ numbers to Tensor
+- func: div.Scalar(Tensor self, Scalar other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: div
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_div_Scalar
+  tags: [core, pointwise]
+
+- func: div_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: div_
+  autogen: div.Scalar_out
+  tags: pointwise
+
+- func: div.Scalar_mode(Tensor self, Scalar other, *, str? rounding_mode) -> Tensor
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: div
+  tags: [core, pointwise]
+
+- func: div_.Scalar_mode(Tensor(a!) self, Scalar other, *, str? rounding_mode) -> Tensor(a!)
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: div_
+  autogen: div.Scalar_mode_out
+  tags: pointwise
+
+# divide, alias for div
+- func: divide.Tensor(Tensor self, Tensor other) -> Tensor
+  variants: function, method
+
+- func: divide_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  variants: method
+
+- func: divide.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: divide.Scalar(Tensor self, Scalar other) -> Tensor
+  variants: function, method
+
+- func: divide_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  variants: method
+
+- func: divide.Tensor_mode(Tensor self, Tensor other, *, str? rounding_mode) -> Tensor
+  variants: function, method
+
+- func: divide_.Tensor_mode(Tensor(a!) self, Tensor other, *, str? rounding_mode) -> Tensor(a!)
+  variants: method
+
+- func: divide.out_mode(Tensor self, Tensor other, *, str? rounding_mode, Tensor(a!) out) -> Tensor(a!)
+
+- func: divide.Scalar_mode(Tensor self, Scalar other, *, str? rounding_mode) -> Tensor
+  variants: function, method
+
+- func: divide_.Scalar_mode(Tensor(a!) self, Scalar other, *, str? rounding_mode) -> Tensor(a!)
+  variants: method
+
+  # true_divide, an alias for div
+- func: true_divide.Tensor(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  tags: pointwise
+
+- func: true_divide_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+- func: true_divide.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+
+- func: true_divide.Scalar(Tensor self, Scalar other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: true_divide_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+- func: dot(Tensor self, Tensor tensor) -> Tensor
+  variants: function, method
+  dispatch:
+    CPU: dot
+    CUDA: dot_cuda
+    MPS: dot_mps
+
+- func: dot.out(Tensor self, Tensor tensor, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: dot_out
+
+- func: vdot(Tensor self, Tensor other) -> Tensor
+  variants: function, method
+  dispatch:
+    CPU: vdot
+    CUDA: vdot_cuda
+
+- func: vdot.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: vdot_out
+
+- func: einsum(str equation, Tensor[] tensors, *, int[]? path=None) -> Tensor
+
+- func: embedding(Tensor weight, Tensor indices, SymInt padding_idx=-1, bool scale_grad_by_freq=False, bool sparse=False) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: embedding_symint
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_embedding
+  autogen: embedding.out
+  tags: core
+
+- func: embedding_backward(Tensor grad, Tensor indices, SymInt num_weights, SymInt padding_idx, bool scale_grad_by_freq, bool sparse) -> Tensor
+  dispatch:
+    CompositeImplicitAutograd: embedding_backward_symint
+
+- func: embedding_dense_backward(Tensor grad_output, Tensor indices, SymInt num_weights, SymInt padding_idx, bool scale_grad_by_freq) -> Tensor
+  dispatch:
+    CPU: embedding_dense_backward_cpu
+    CUDA: embedding_dense_backward_cuda
+    MPS: embedding_dense_backward_mps
+  autogen: embedding_dense_backward.out
+  tags: core
+
+- func: embedding_renorm_(Tensor(a!) self, Tensor indices, float max_norm, float norm_type) -> Tensor(a!)
+  dispatch:
+    CPU: embedding_renorm_cpu_
+    CUDA: embedding_renorm_cuda_
+  autogen: embedding_renorm, embedding_renorm.out
+
+- func: embedding_sparse_backward(Tensor grad, Tensor indices, int num_weights, int padding_idx, bool scale_grad_by_freq) -> Tensor
+
+# NOTE [ embedding_bag Native Functions ]
+# The `_embedding_bag.*` variants assume that input tensors except for `weight`,
+# e.g. `indices` and `offsets` (and `offset2bag`), are contiguous.
+# We really only need to enforce this for `_embedding_bag` (the forward) because
+# the backward inputs are the same as forward ones.
+# The above `embedding_bag` wrapper is created to achieve this, e.g.,
+# applying indices = indices.contiguous().
+# The backward functions apply a check that these input tensors are contiguous.
+
+
+- func: _embedding_bag_forward_only(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False, int padding_idx=-1) -> (Tensor, Tensor, Tensor, Tensor)
+  dispatch:
+    CPU: _embedding_bag_forward_only_cpu
+    CUDA: _embedding_bag_forward_only_cuda
+  autogen: _embedding_bag_forward_only.out
+
+- func: _rowwise_prune(Tensor weight, Tensor mask, ScalarType compressed_indices_dtype) -> (Tensor, Tensor)
+
+# row_stack is the alias of vstack
+- func: row_stack(Tensor[] tensors) -> Tensor
+
+- func: row_stack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: embedding_bag(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False) -> (Tensor, Tensor, Tensor, Tensor)
+
+# To keep backward and forward compatibility, and to avoid ambiguity with the
+# original signature above, scale_grad_by_freq, mode, sparse,
+# per_sample_weights, and include_last_offset parameters do not have default
+# values. Once the original signature is removed, default values can be added.
+- func: embedding_bag.padding_idx(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq, int mode, bool sparse, Tensor? per_sample_weights, bool include_last_offset, int? padding_idx) -> (Tensor, Tensor, Tensor, Tensor)
+
+- func: _embedding_bag(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False, int padding_idx=-1) -> (Tensor, Tensor, Tensor, Tensor)
+  dispatch:
+    CPU: _embedding_bag_cpu
+    CUDA: _embedding_bag_cuda
+  autogen: _embedding_bag.out
+  tags: core
+
+- func: _embedding_bag_backward(Tensor grad, Tensor indices, Tensor offsets, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, SymInt num_weights, bool scale_grad_by_freq, int mode, bool sparse, Tensor? per_sample_weights, int padding_idx=-1) -> Tensor
+  dispatch:
+    CPU, CUDA: _embedding_bag_backward_symint
+
+- func: _embedding_bag_sparse_backward(Tensor grad, Tensor indices, Tensor offsets, Tensor offset2bag, Tensor bag_size, SymInt num_weights, bool scale_grad_by_freq, int mode, Tensor? per_sample_weights, int padding_idx=-1) -> Tensor
+  dispatch:
+    CompositeImplicitAutograd: _embedding_bag_sparse_backward_symint
+
+- func: _embedding_bag_dense_backward(Tensor grad, Tensor indices, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, SymInt num_weights, bool scale_grad_by_freq, int mode, Tensor? per_sample_weights, int padding_idx=-1) -> Tensor
+  dispatch:
+    CPU: _embedding_bag_dense_backward_cpu
+    CUDA: _embedding_bag_dense_backward_cuda
+  autogen: _embedding_bag_dense_backward.out
+
+- func: _embedding_bag_per_sample_weights_backward(Tensor grad, Tensor weight, Tensor indices, Tensor offsets, Tensor offset2bag, int mode, int padding_idx=-1) -> Tensor
+  dispatch:
+    CPU: _embedding_bag_per_sample_weights_backward_cpu
+    CUDA: _embedding_bag_per_sample_weights_backward_cuda
+  autogen: _embedding_bag_per_sample_weights_backward.out
+
+- func: empty.names(int[] size, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: empty_names
+  autogen: empty.names_out
+
+- func: empty.memory_format(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+  dispatch:
+    CPU: empty_cpu
+    CUDA: empty_cuda
+    MPS: empty_mps
+    Meta: empty_meta_symint
+    MkldnnCPU: empty_mkldnn
+    SparseCPU, SparseCUDA, SparseMPS: empty_sparse
+    SparseMeta: empty_sparse_symint
+    SparseCsrCPU, SparseCsrCUDA: empty_sparse_compressed
+    SparseCsrMeta: empty_sparse_compressed_symint
+    QuantizedCPU, QuantizedCUDA, QuantizedMeta: empty_unknown_quantized
+  tags: core
+
+- func: empty_permuted(SymInt[] size, int[] physical_layout, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: empty_permuted_symint
+  autogen: empty_permuted.out
+
+# We do not make new_empty a composite that calls into new_empty_strided, as the strided version
+# is significantly more difficult to implement by different backends
+- func: new_empty(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: new_empty_symint
+  autogen: new_empty.out
+
+- func: new_empty_strided(Tensor self, SymInt[] size, SymInt[] stride, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  variants: method
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: new_empty_strided_symint
+  autogen: new_empty_strided.out
+
+- func: new_full(Tensor self, SymInt[] size, Scalar fill_value, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  variants: method
+  dispatch:
+    # NB: Although this composite mutates on the inside, it is
+    # non-differentiable so NonFunctional doesn't apply
+    CompositeExplicitAutograd: new_full
+  autogen: new_full.out
+
+- func: new_zeros(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  variants: method
+  dispatch:
+    # NB: Although this composite mutates on the inside, it is
+    # non-differentiable so NonFunctional doesn't apply
+    CompositeExplicitAutograd: new_zeros
+  autogen: new_zeros.out
+
+- func: new_ones(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  variants: method
+  dispatch:
+    # NB: Although this composite mutates on the inside, it is
+    # non-differentiable so NonFunctional doesn't apply
+    CompositeExplicitAutograd: new_ones
+  autogen: new_ones.out
+
+# other overrides are to provide a more helpful error message that dtype is required
+- func: _empty_affine_quantized(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, float scale=1, int zero_point=0, MemoryFormat? memory_format=contiguous_format) -> Tensor
+  dispatch:
+    CPU: empty_affine_quantized_other_backends_stub
+    QuantizedCPU, QuantizedCUDA: empty_affine_quantized
+  autogen: _empty_affine_quantized.out
+
+# it's a factory function receiving a tensor argument, thus overriding explicitly
+# other overrides are to provide a more helpful error message that dtype is required
+- func: _empty_per_channel_affine_quantized(SymInt[] size, *, Tensor scales, Tensor zero_points, int axis, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=contiguous_format) -> Tensor
+  category_override: factory
+  dispatch:
+    CPU: empty_per_channel_affine_quantized_other_backends_stub
+    QuantizedCPU, QuantizedCUDA: empty_per_channel_affine_quantized
+  autogen: _empty_per_channel_affine_quantized.out
+
+- func: resize_(Tensor(a!) self, SymInt[] size, *, MemoryFormat? memory_format=None) -> Tensor(a!)
+  use_const_ref_for_mutable_tensors: True
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+  tags: [core, inplace_view]
+  dispatch:
+    Meta: resize__symint
+    CPU: resize_
+    CUDA: resize_cuda_
+    MPS: resize_mps_
+    QuantizedCPU: quantized_resize_cpu_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: resize_sparse_csr_
+  autogen: resize, resize.out
+
+# This is a utility function to enable users to resize out tensor while registering kernels for out variants.
+# Eventually, we can consider exposing `resize_output` as a public API to ship it with python op registration
+# to make it easy to register out variants for ops.
+- func: _resize_output_(Tensor(a!) self, SymInt[] size, Device device) -> Tensor(a!)
+  use_const_ref_for_mutable_tensors: True
+  variants: function
+  dispatch:
+    Meta: _resize_output_
+  autogen: _resize_output, _resize_output.out
+
+- func: empty_quantized(int[] size, Tensor qtensor, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+  category_override: factory
+  variants: function
+  dispatch:
+    QuantizedCPU, QuantizedCUDA: empty_quantized
+  autogen: empty_quantized.out
+
+- func: empty.out(SymInt[] size, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck
+  device_guard: False
+
+- func: empty_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: empty_like
+    QuantizedCPU, QuantizedCUDA: empty_like_quantized
+    SparseCPU, SparseCUDA, SparseMeta: empty_like_sparse_coo
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: empty_like_sparse_csr
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: empty_like_nested
+  autogen: empty_like.out
+
+- func: empty_strided(SymInt[] size, SymInt[] stride, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CPU: empty_strided_cpu
+    CUDA: empty_strided_cuda
+    MPS: empty_strided_mps
+    Meta: empty_strided_meta_symint
+    QuantizedCPU, QuantizedCUDA: empty_strided_unknown_quantized
+  autogen: empty_strided.out
+  tags: core
+
+- func: erf(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: erf.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: erf_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: erf_sparse_csr
+  tags: [core, pointwise]
+
+- func: erf_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: erf.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: erf_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: erf_sparse_csr_
+  tags: pointwise
+
+- func: erf.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS, MTIA: erf_out
+    SparseCPU, SparseCUDA, SparseMPS: erf_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: erf_sparse_csr_out
+  tags: pointwise
+
+- func: erfc(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: erfc.out
+  variants: function, method
+  tags: pointwise
+
+- func: erfc_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: erfc.out
+  variants: function, method
+  tags: pointwise
+
+- func: erfc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: erfc_out
+  tags: pointwise
+
+- func: exp(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: exp.out
+  variants: function, method
+  tags: [core, pointwise]
+
+- func: exp_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: exp.out
+  variants: function, method
+  tags: pointwise
+
+- func: exp.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS, MTIA: exp_out
+  tags: pointwise
+
+- func: exp2(Tensor self) -> Tensor
+  structured_delegate: exp2.out
+  variants: function, method
+  tags: pointwise
+
+- func: exp2_(Tensor(a!) self) -> Tensor(a!)
+  structured_delegate: exp2.out
+  variants: function, method
+  tags: pointwise
+
+- func: exp2.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: exp2_out
+  tags: pointwise
+
+- func: expm1(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: expm1.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: expm1_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: expm1_sparse_csr
+  tags: [core, pointwise]
+
+- func: expm1_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: expm1.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: expm1_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: expm1_sparse_csr_
+  tags: pointwise
+
+- func: expm1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: expm1_out
+    SparseCPU, SparseCUDA, SparseMPS: expm1_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: expm1_sparse_csr_out
+  tags: pointwise
+
+- func: expand(Tensor(a) self, SymInt[] size, *, bool implicit=False) -> Tensor(a)
+  variants: method  # This is method-only to match the previous tensor API. In the future we could make this a function too.
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: expand
+  tags: core
+
+- func: expand_as(Tensor(a) self, Tensor other) -> Tensor(a)
+  variants: method  # This is method-only to match the previous tensor API. In the future we could make this a function too.
+  device_check: NoCheck
+  device_guard: False
+
+# decomposes to eye.m
+- func: eye(SymInt n, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: eye
+
+- func: eye.m(SymInt n, SymInt m, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: eye
+
+- func: eye.out(SymInt n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, Meta: eye_out_cpu
+    CUDA: eye_out_cuda
+    MPS: eye_out_mps
+
+- func: eye.m_out(SymInt n, SymInt m, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, Meta: eye_out_cpu
+    CUDA: eye_out_cuda
+    MPS: eye_out_mps
+
+- func: flatten.using_ints(Tensor(a) self, int start_dim=0, int end_dim=-1) -> Tensor(a)
+  variants: function, method
+
+- func: flatten.named_out_dim(Tensor(a) self, int start_dim, int end_dim, Dimname out_dim) -> Tensor(a)
+  variants: function, method
+
+- func: flatten.using_names(Tensor(a) self, Dimname start_dim, Dimname end_dim, Dimname out_dim) -> Tensor(a)
+  variants: function, method
+
+- func: flatten.DimnameList(Tensor(a) self, Dimname[] dims, Dimname out_dim) -> Tensor(a)
+  variants: function, method
+
+- func: unflatten.int(Tensor(a) self, int dim, SymInt[] sizes) -> Tensor(a)
+  variants: function, method
+  dispatch:
+    CompositeImplicitAutograd: unflatten_symint
+
+- func: unflatten.Dimname(Tensor(a) self, Dimname dim, SymInt[] sizes, Dimname[] names) -> Tensor(a)
+  variants: function, method
+  dispatch:
+    CompositeImplicitAutograd: unflatten_dimname_symint
+
+- func: fill.Scalar(Tensor self, Scalar value) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: fill
+  tags: core
+
+- func: fill.Tensor(Tensor self, Tensor value) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: fill
+
+- func: fill_.Scalar(Tensor(a!) self, Scalar value) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CPU, CUDA: fill_
+    MPS: fill_scalar_mps
+    QuantizedCPU, QuantizedCUDA: fill_quantized_
+    Meta: fill_meta_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: fill_sparse_csr_
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: fill_nested_
+  autogen: fill.Scalar_out
+
+- func: fill_.Tensor(Tensor(a!) self, Tensor value) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CPU, CUDA: fill_
+    MPS: fill_tensor_mps_
+    QuantizedCPU, QuantizedCUDA: fill_quantized_
+    Meta: fill_meta_
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: fill_nested_
+  autogen: fill.Tensor_out
+
+- func: floor(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: floor.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: floor_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: floor_sparse_csr
+  tags: [core, pointwise]
+
+- func: floor_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: floor.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: floor_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: floor_sparse_csr_
+  tags: pointwise
+
+- func: floor.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: floor_out
+    SparseCPU, SparseCUDA, SparseMPS: floor_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: floor_sparse_csr_out
+  tags: pointwise
+
+- func: floor_divide(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CPU, CUDA, MPS, MTIA: floor_divide
+    SparseCPU, SparseCUDA: floor_divide_sparse
+
+- func: floor_divide_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CPU, CUDA, MPS: floor_divide_
+    SparseCPU, SparseCUDA: floor_divide_sparse_
+
+- func: floor_divide.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MPS: floor_divide_out
+    SparseCPU, SparseCUDA: floor_divide_out_sparse_zerodim
+
+- func: floor_divide.Scalar(Tensor self, Scalar other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: floor_divide
+
+- func: floor_divide_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: floor_divide_
+  autogen: floor_divide.Scalar_out
+
+- func: frac(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: frac.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: frac_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: frac_sparse_csr
+  tags: pointwise
+
+- func: frac_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: frac.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: frac_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: frac_sparse_csr_
+  tags: pointwise
+
+- func: frac.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: frac_out
+    MPS: frac_out_mps
+    SparseCPU, SparseCUDA, SparseMPS: frac_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: frac_sparse_csr_out
+  tags: pointwise
+
+- func: full.names(int[] size, Scalar fill_value, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: full
+  autogen: full.names_out
+
+- func: full(SymInt[] size, Scalar fill_value, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: full
+  tags: core
+
+- func: full.out(SymInt[] size, Scalar fill_value, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: full_out
+
+- func: full_like(Tensor self, Scalar fill_value, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+  dispatch:
+    # NB: Although this composite mutates on the inside, it is
+    # non-differentiable so NonFunctional doesn't apply
+    CompositeExplicitAutograd: full_like
+  autogen: full_like.out
+  tags: core
+
+- func: from_file(str filename, bool? shared=None, int? size=0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CPU: from_file
+  autogen: from_file.out
+
+- func: gcd.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: gcd_out
+  tags: pointwise
+
+- func: gcd(Tensor self, Tensor other) -> Tensor
+  structured_delegate: gcd.out
+  variants: function, method
+  tags: pointwise
+
+- func: gcd_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  structured_delegate: gcd.out
+  variants: function, method
+
+- func: lcm.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: lcm_out
+  tags: pointwise
+
+- func: lcm(Tensor self, Tensor other) -> Tensor
+  structured_delegate: lcm.out
+  variants: function, method
+  tags: pointwise
+
+- func: lcm_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  structured_delegate: lcm.out
+  variants: function, method
+
+# NOTE [ grid_sampler Native Functions ]
+# `grid_sampler` is _supposed to_ do all the shape checking and then dispatch to
+# one of `cudnn_grid_sampler`, `grid_sampler_2d`, or `grid_sampler_3d`, each of
+# which has the corresponding backward defined as native functions as well.
+# However, we do shape checking everywhere for now since each of the mentioned
+# functions can be called directly, which will lead to crashes otherwise.
+# See https://github.com/pytorch/pytorch/issues/73187 for more information.
+#
+# There is also _grid_sampler_2d_backward_cpu_fallback which is an
+# implementation detail of grid_sampler_2d and is only exposed here for testing
+# purposes.
+#
+# Additionally, arguments `padding_mode` and `interpolation_mode` are cast to
+# enums defined in `native/GridSampler.h`. `cudnn_grid_sampler` doesn't take in
+# `interpolation_mode` because it only supports Bilinear interpolation mode.
+# Nor does it take in `align_corners` because it only supports the mode
+# `align_corners = True`.
+- func: grid_sampler(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor
+
+- func: grid_sampler_2d(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor
+  dispatch:
+    CPU, QuantizedCPU: grid_sampler_2d_cpu
+    CUDA: grid_sampler_2d_cuda
+    MPS: grid_sampler_2d_mps
+  autogen: grid_sampler_2d.out
+  tags: core
+
+# `grid_sampler_2d_backward` takes in `output_mask` to optimize performance for
+# the case where `input` doesn't require gradient. Gradient for `grid` is always
+# computed (only `output_mask[0]` is checked by the implementations).
+- func: grid_sampler_2d_backward(Tensor grad_output, Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners, bool[2] output_mask) -> (Tensor, Tensor)
+  dispatch:
+    CPU: grid_sampler_2d_backward_cpu
+    CUDA: grid_sampler_2d_backward_cuda
+  autogen: grid_sampler_2d_backward.out
+
+# See NOTE [ grid_sample CPU fallback ]
+- func: _grid_sampler_2d_cpu_fallback(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: _grid_sampler_2d_cpu_fallback
+  autogen: _grid_sampler_2d_cpu_fallback.out
+
+- func: _grid_sampler_2d_cpu_fallback_backward(Tensor grad_output, Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> (Tensor, Tensor)
+
+- func: grid_sampler_3d(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor
+  dispatch:
+    CPU: grid_sampler_3d_cpu
+    CUDA: grid_sampler_3d_cuda
+    MPS: grid_sampler_3d_mps
+  autogen: grid_sampler_3d.out
+
+# `grid_sampler_3d_backward` takes in `output_mask` to optimize performance for
+# the case where `input` doesn't require gradient. Gradient for `grid` is always
+# computed (only `output_mask[0]` is checked by the implementations).
+- func: grid_sampler_3d_backward(Tensor grad_output, Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners, bool[2] output_mask) -> (Tensor, Tensor)
+  dispatch:
+    CPU: grid_sampler_3d_backward_cpu
+    CUDA: grid_sampler_3d_backward_cuda
+  autogen: grid_sampler_3d_backward.out
+
+- func: hann_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: hann_window
+  autogen: hann_window.out
+
+- func: hann_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: hann_window
+  autogen: hann_window.periodic_out
+
+- func: hamming_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: hamming_window
+  autogen: hamming_window.out
+
+- func: hamming_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: hamming_window
+  autogen: hamming_window.periodic_out
+
+- func: hamming_window.periodic_alpha(int window_length, bool periodic, float alpha, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: hamming_window
+  autogen: hamming_window.periodic_alpha_out
+
+- func: hamming_window.periodic_alpha_beta(int window_length, bool periodic, float alpha, float beta, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: hamming_window
+  autogen: hamming_window.periodic_alpha_beta_out
+
+- func: kaiser_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: kaiser_window
+  autogen: kaiser_window.out
+
+- func: kaiser_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: kaiser_window
+  autogen: kaiser_window.periodic_out
+
+- func: kaiser_window.beta(int window_length, bool periodic, float beta, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: kaiser_window
+  autogen: kaiser_window.beta_out
+
+- func: hinge_embedding_loss(Tensor self, Tensor target, float margin=1.0, int reduction=Mean) -> Tensor
+
+- func: group_norm(Tensor input, int num_groups, Tensor? weight=None, Tensor? bias=None, float eps=1e-05, bool cudnn_enabled=True) -> Tensor
+
+- func: native_group_norm(Tensor input, Tensor? weight, Tensor? bias, SymInt N, SymInt C, SymInt HxW, int group, float eps) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    CPU, CUDA: native_group_norm
+    CompositeExplicitAutograd: math_group_norm
+  autogen: native_group_norm.out
+  tags: core
+
+- func: native_group_norm_backward(Tensor grad_out, Tensor input, Tensor mean, Tensor rstd, Tensor? weight, SymInt N, SymInt C, SymInt HxW, int group, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    CPU, CUDA: native_group_norm_backward
+  autogen: native_group_norm_backward.out
+  tags: core
+
+# Real to complex forward FFT
+- func: _fft_r2c(Tensor self, int[] dim, int normalization, bool onesided) -> Tensor
+  variants: function
+  dispatch:
+    CPU: _fft_r2c_mkl
+    CUDA: _fft_r2c_cufft
+    MPS: _fft_r2c_mps
+  tags: core
+
+- func: _fft_r2c.out(Tensor self, int[] dim, int normalization, bool onesided, *, Tensor(a!) out) -> Tensor(a!)
+  variants: function
+  dispatch:
+    CPU: _fft_r2c_mkl_out
+    CUDA: _fft_r2c_cufft_out
+    MPS: _fft_r2c_mps_out
+
+# Complex to real inverse FFT
+- func: _fft_c2r(Tensor self, int[] dim, int normalization, SymInt last_dim_size) -> Tensor
+  variants: function
+  dispatch:
+    CPU: _fft_c2r_mkl
+    CUDA: _fft_c2r_cufft
+    MPS: _fft_c2r_mps
+
+- func: _fft_c2r.out(Tensor self, int[] dim, int normalization, SymInt last_dim_size, *, Tensor(a!) out) -> Tensor(a!)
+  variants: function
+  dispatch:
+    CPU: _fft_c2r_mkl_out
+    CUDA: _fft_c2r_cufft_out
+    MPS: _fft_c2r_mps_out
+
+# Standard complex to complex FFT (forward or backward)
+- func: _fft_c2c(Tensor self, SymInt[] dim, int normalization, bool forward) -> Tensor
+  variants: function
+  dispatch:
+    CPU: _fft_c2c_mkl
+    CUDA: _fft_c2c_cufft
+    MPS: _fft_c2c_mps
+
+- func: _fft_c2c.out(Tensor self, SymInt[] dim, int normalization, bool forward, *, Tensor(a!) out) -> Tensor(a!)
+  variants: function
+  dispatch:
+    CPU: _fft_c2c_mkl_out
+    CUDA: _fft_c2c_cufft_out
+    MPS: _fft_c2c_mps_out
+
+- func: _validate_compressed_sparse_indices(bool is_crow, Tensor compressed_idx, Tensor plain_idx, int cdim, int dim, int nnz) -> ()
+  device_check: NoCheck
+  variants: function
+  dispatch:
+    CPU: _validate_compressed_sparse_indices_cpu
+    CUDA: _validate_compressed_sparse_indices_cuda
+
+- func: _cufft_get_plan_cache_size(DeviceIndex device_index) -> int
+
+- func: _cufft_get_plan_cache_max_size(DeviceIndex device_index) -> int
+
+- func: _cufft_set_plan_cache_max_size(DeviceIndex device_index, int max_size) -> ()
+
+- func: _cufft_clear_plan_cache(DeviceIndex device_index) -> ()
+
+- func: index.Tensor(Tensor self, Tensor?[] indices) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: index.Tensor_out
+  variants: function, method
+  dispatch:
+    QuantizedCPU: quantized_index
+  tags: [core, dynamic_output_shape]
+  # NB: This function is special-cased in tools/autograd/gen_variable_type.py
+  # NB: The following functions are declared in aten/src/ATen/templates/TensorBody.h and defined in aten/src/ATen/TensorIndexing.cpp:
+  # - Tensor Tensor::index(ArrayRef indices)
+  # - Tensor Tensor::index(std::initializer_list indices)
+
+- func: index.Tensor_out(Tensor self, Tensor?[] indices, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck
+  structured: True
+  structured_inherits: TensorIteratorBase
+  precomputed:
+  - indices -> DimVector sizes, DimVector strides
+  dispatch:
+    CPU, CUDA, MPS: index_out
+
+# Used by inductor to signal indexing without bounds checks
+# Note that we don't support boolean indexing, to avoid dynamic output shapes
+- func: _unsafe_index.Tensor(Tensor self, Tensor?[] indices) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: _unsafe_index
+
+# Used by inductor to generate masked loads
+# Note that we don't support boolean indexing, to avoid dynamic output shapes
+- func: _unsafe_masked_index(Tensor self, Tensor mask, Tensor?[] indices, Scalar fill) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: _unsafe_masked_index
+
+- func: _unsafe_masked_index_put_accumulate(Tensor self, Tensor mask, Tensor?[] indices, Tensor values) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: _unsafe_masked_index_put_accumulate
+
+- func: index_copy.out(Tensor self, int dim, Tensor index, Tensor source, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  variants: function
+  precomputed:
+  - dim -> int dim
+  dispatch:
+    CPU, CUDA: index_copy_out
+    MPS: index_copy_out_mps
+
+- func: index_copy_(Tensor(a!) self, int dim, Tensor index, Tensor source) -> Tensor(a!)
+  variants: method
+  structured_delegate: index_copy.out
+
+- func: index_copy(Tensor self, int dim, Tensor index, Tensor source) -> Tensor
+  variants: function, method
+  structured_delegate: index_copy.out
+
+- func: index_copy_.dimname(Tensor(a!) self, Dimname dim, Tensor index, Tensor source) -> Tensor(a!)
+  variants: method
+
+- func: index_copy.dimname(Tensor self, Dimname dim, Tensor index, Tensor source) -> Tensor
+  variants: function, method
+
+- func: index_put_(Tensor(a!) self, Tensor?[] indices, Tensor values, bool accumulate=False) -> Tensor(a!)
+  device_check: NoCheck   # delegate to _index_put_impl_, which leverages TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: index_put_
+  autogen: index_put.out
+  # NB: The following functions are declared in aten/src/ATen/templates/TensorBody.h and defined in aten/src/ATen/TensorIndexing.cpp:
+  # - Tensor & Tensor::index_put_(ArrayRef indices, Tensor const & rhs)
+  # - Tensor & Tensor::index_put_(ArrayRef indices, Scalar v)
+  # - Tensor & Tensor::index_put_(std::initializer_list indices, Tensor const & rhs)
+  # - Tensor & Tensor::index_put_(std::initializer_list indices, Scalar v)
+
+- func: index_put(Tensor self, Tensor?[] indices, Tensor values, bool accumulate=False) -> Tensor
+  device_check: NoCheck   # delegate to _index_put_impl_ after clone, which leverages TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: index_put
+  tags: core
+
+- func: _unsafe_index_put(Tensor self, Tensor?[] indices, Tensor values, bool accumulate=False) -> Tensor
+  device_check: NoCheck   # delegate to _index_put_impl_ after clone, which leverages TensorIterator
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: _unsafe_index_put
+
+- func: _index_put_impl_(Tensor(a!) self, Tensor?[] indices, Tensor values, bool accumulate=False, bool unsafe=False) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  dispatch:
+    CPU, CUDA, MPS: _index_put_impl_
+    QuantizedCPU: _index_put_impl_quantized_cpu_
+    QuantizedCUDA: _index_put_impl_quantized_cuda_
+  autogen: _index_put_impl, _index_put_impl.out
+
+- func: instance_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool use_input_stats, float momentum, float eps, bool cudnn_enabled) -> Tensor
+  variants: function
+
+- func: isclose(Tensor self, Tensor other, float rtol=1e-05, float atol=1e-08, bool equal_nan=False) -> Tensor
+  variants: function, method
+
+- func: isin.Tensor_Tensor_out(Tensor elements, Tensor test_elements, *, bool assume_unique=False, bool invert=False, Tensor(a!) out) -> Tensor(a!)
+  variants: function
+  structured: True
+  dispatch:
+    CPU, CUDA: isin_Tensor_Tensor_out
+    MPS: isin_Tensor_Tensor_out_mps
+
+- func: isin.Tensor_Tensor(Tensor elements, Tensor test_elements, *, bool assume_unique=False, bool invert=False) -> Tensor
+  variants: function
+  structured_delegate: isin.Tensor_Tensor_out
+
+- func: isin.Tensor_Scalar_out(Tensor elements, Scalar test_element, *, bool assume_unique=False, bool invert=False, Tensor(a!) out) -> Tensor(a!)
+  variants: function
+  structured: True
+  dispatch:
+    CPU, CUDA, MPS: isin_Tensor_Scalar_out
+
+- func: isin.Tensor_Scalar(Tensor elements, Scalar test_element, *, bool assume_unique=False, bool invert=False) -> Tensor
+  variants: function
+  structured_delegate: isin.Tensor_Scalar_out
+
+- func: isin.Scalar_Tensor_out(Scalar element, Tensor test_elements, *, bool assume_unique=False, bool invert=False, Tensor(a!) out) -> Tensor(a!)
+  variants: function
+  structured: True
+  dispatch:
+    CPU, CUDA: isin_Scalar_Tensor_out
+    MPS: isin_Scalar_Tensor_out_mps
+
+- func: isin.Scalar_Tensor(Scalar element, Tensor test_elements, *, bool assume_unique=False, bool invert=False) -> Tensor
+  variants: function
+  structured_delegate: isin.Scalar_Tensor_out
+
+- func: isnan(Tensor self) -> Tensor
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CPU, CUDA, MPS, MTIA: isnan
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_isnan
+    SparseCPU, SparseCUDA, SparseMPS: isnan_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: isnan_sparse_csr
+  autogen: isnan.out
+  tags: [core, pointwise]
+
+- func: is_distributed(Tensor self) -> bool
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+
+- func: is_floating_point(Tensor self) -> bool
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  manual_cpp_binding: True
+
+- func: is_complex(Tensor self) -> bool
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  manual_cpp_binding: True
+
+- func: is_conj(Tensor self) -> bool
+  variants: function, method
+  device_guard: False
+  manual_cpp_binding: True
+
+- func: _is_zerotensor(Tensor self) -> bool
+  variants: function, method
+  device_guard: False
+  manual_cpp_binding: True
+
+- func: is_neg(Tensor self) -> bool
+  variants: function, method
+  device_guard: False
+  manual_cpp_binding: True
+
+- func: isreal(Tensor self) -> Tensor
+  variants: function, method
+
+- func: is_nonzero(Tensor self) -> bool
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+
+- func: is_same_size(Tensor self, Tensor other) -> bool
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: nested_is_same_size
+    CompositeExplicitAutograd: is_same_size
+
+- func: is_signed(Tensor self) -> bool
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  manual_cpp_binding: True
+
+- func: is_inference(Tensor self) -> bool
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  manual_cpp_binding: True
+
+- func: kl_div(Tensor self, Tensor target, int reduction=Mean, *, bool log_target=False) -> Tensor
+
+- func: kron(Tensor self, Tensor other) -> Tensor
+  variants: function, method
+
+- func: kron.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: kthvalue(Tensor self, SymInt k, int dim=-1, bool keepdim=False) -> (Tensor values, Tensor indices)
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: kthvalue
+
+- func: kthvalue.values(Tensor self, SymInt k, int dim=-1, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+  dispatch:
+    CPU: kthvalue_out_cpu
+    CUDA: kthvalue_out_cuda
+    MPS: kthvalue_out_mps
+
+- func: kthvalue.dimname(Tensor self, SymInt k, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+  variants: function, method
+
+- func: kthvalue.dimname_out(Tensor self, SymInt k, Dimname dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+
+- func: layer_norm(Tensor input, SymInt[] normalized_shape, Tensor? weight=None, Tensor? bias=None, float eps=1e-05, bool cudnn_enable=True) -> Tensor
+  dispatch:
+    CompositeImplicitAutograd: layer_norm_symint
+
+- func: native_layer_norm(Tensor input, SymInt[] normalized_shape, Tensor? weight, Tensor? bias, float eps) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    CPU: layer_norm_cpu
+    CUDA: layer_norm_cuda
+    MPS: layer_norm_mps
+    CompositeExplicitAutograd: math_native_layer_norm
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: nested_layer_norm
+  autogen: native_layer_norm.out
+  tags: core
+
+- func: native_layer_norm_backward(Tensor grad_out, Tensor input, SymInt[] normalized_shape, Tensor mean, Tensor rstd, Tensor? weight, Tensor? bias, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    CPU: layer_norm_backward_cpu
+    CUDA: layer_norm_backward_cuda
+    MPS: layer_norm_backward_mps
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: layer_norm_backward_nested
+  autogen: native_layer_norm_backward.out
+  tags: core
+
+- func: rms_norm(Tensor input, SymInt[] normalized_shape, Tensor? weight=None, float? eps=None) -> Tensor
+  dispatch:
+    CompositeImplicitAutograd: rms_norm_symint
+
+- func: _fused_rms_norm(Tensor input, int[] normalized_shape, Tensor? weight, float? eps) -> (Tensor, Tensor)
+  dispatch:
+    CUDA: _fused_rms_norm_cuda
+    MPS: _fused_rms_norm_mps
+    CompositeImplicitAutograd: rms_norm_composite
+
+- func: _fused_rms_norm_backward(Tensor grad_out, Tensor input, int[] normalized_shape, Tensor rstd, Tensor? weight, bool[2] output_mask) -> (Tensor, Tensor)
+  dispatch:
+    CUDA: _fused_rms_norm_backward_cuda
+
+- func: nan_to_num(Tensor self, float? nan=None, float? posinf=None, float? neginf=None) -> Tensor
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: nan_to_num
+    SparseCPU, SparseCUDA, SparseMPS: nan_to_num_sparse
+  tags: pointwise
+
+- func: nan_to_num_(Tensor(a!) self, float? nan=None, float? posinf=None, float? neginf=None) -> Tensor(a!)
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: nan_to_num_
+    SparseCPU, SparseCUDA, SparseMPS: nan_to_num_sparse_
+  tags: pointwise
+
+- func: nan_to_num.out(Tensor self, float? nan=None, float? posinf=None, float? neginf=None, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA, MTIA: nan_to_num_out
+    MPS: nan_to_num_out_mps
+    SparseCPU, SparseCUDA, SparseMPS: nan_to_num_sparse_out
+  tags: pointwise
+
+- func: linear(Tensor input, Tensor weight, Tensor? bias=None) -> Tensor
+  python_module: nn
+  dispatch:
+    CompositeImplicitAutograd: linear
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: nested_linear
+    MPS: _mps_linear
+
+- func: linear_backward(Tensor self, Tensor grad_output, Tensor weight, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: nested_linear_backward
+    MPS: mps_linear_backward
+  autogen: linear_backward.out
+
+- func: linear.out(Tensor input, Tensor weight, Tensor? bias=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CompositeExplicitAutograd: linear_out
+
+- func: mkldnn_linear(Tensor self, Tensor weight, Tensor? bias=None) -> Tensor
+  python_module: nn
+  dispatch:
+    MkldnnCPU: mkldnn_linear
+  autogen: mkldnn_linear.out
+
+- func: mkldnn_linear_backward_input(int[] input_size, Tensor grad_output, Tensor weight) -> Tensor
+  dispatch:
+    MkldnnCPU: mkldnn_linear_backward_input
+  autogen: mkldnn_linear_backward_input.out
+
+- func: mkldnn_linear_backward_weights(Tensor grad_output, Tensor input, Tensor weight, bool bias_defined) -> (Tensor, Tensor)
+  dispatch:
+    MkldnnCPU: mkldnn_linear_backward_weights
+  autogen: mkldnn_linear_backward_weights.out
+
+- func: mkldnn_linear_backward(Tensor self, Tensor grad_output, Tensor weight, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    MkldnnCPU: mkldnn_linear_backward
+  autogen: mkldnn_linear_backward.out
+
+- func: _cslt_compress(Tensor input) -> Tensor
+  dispatch:
+    CUDA: _cslt_compress
+
+- func: _cslt_sparse_mm(Tensor compressed_A, Tensor dense_B, Tensor? bias=None, Tensor? alpha=None, ScalarType? out_dtype=None, bool transpose_result=False, int alg_id=0, int split_k=1, int split_k_mode=-1) -> Tensor
+  dispatch:
+    CUDA: _cslt_sparse_mm
+  tags: needs_fixed_stride_order
+
+- func: _cslt_sparse_mm_search(Tensor compressed_A, Tensor dense_B, Tensor? bias=None, Tensor? alpha=None, ScalarType? out_dtype=None, bool transpose_result=False) -> int
+  dispatch:
+    CUDA: _cslt_sparse_mm_search
+
+- func: _sparse_semi_structured_tile(Tensor input, str algorithm="", bool use_cutlass=True) -> (Tensor, Tensor, Tensor, Tensor, Tensor)
+  dispatch:
+    CUDA: _sparse_semi_structured_tile
+
+- func: _sparse_semi_structured_apply(Tensor input, Tensor thread_masks) -> (Tensor, Tensor)
+  dispatch:
+    CUDA: _sparse_semi_structured_apply
+
+- func: _sparse_semi_structured_apply_dense(Tensor input, Tensor thread_masks) -> Tensor
+  dispatch:
+    CUDA: _sparse_semi_structured_apply_dense
+
+# DEPRECATED: Use torch.__sparse_semi_structured_mm/torch._sparse_semi_structured_addmm instead
+- func: _sparse_semi_structured_linear(Tensor input, Tensor weight, Tensor meta, *, Tensor? bias=None, str? activation=None, ScalarType? out_dtype=None) -> Tensor
+  dispatch:
+    CUDA: _sparse_semi_structured_linear
+
+- func: _sparse_semi_structured_mm(Tensor mat1, Tensor mat1_meta, Tensor mat2, *, ScalarType? out_dtype=None) -> Tensor
+  dispatch:
+    CUDA: _sparse_semi_structured_mm
+
+- func: _sparse_semi_structured_addmm(Tensor input, Tensor mat1, Tensor mat1_meta, Tensor mat2, *, Scalar alpha=1, Scalar beta=1, ScalarType? out_dtype=None) -> Tensor
+  dispatch:
+    CUDA: _sparse_semi_structured_addmm
+
+- func: _mixed_dtypes_linear(Tensor input, Tensor weight, Tensor scale, *, Tensor? bias=None, str? activation=None) -> Tensor
+  dispatch:
+    CUDA: _mixed_dtypes_linear
+
+- func: fbgemm_linear_int8_weight_fp32_activation(Tensor input, Tensor weight, Tensor packed, Tensor col_offsets, Scalar weight_scale, Scalar weight_zero_point, Tensor bias) -> Tensor
+
+- func: fbgemm_linear_int8_weight(Tensor input, Tensor weight, Tensor packed, Tensor col_offsets, Scalar weight_scale, Scalar weight_zero_point, Tensor bias) -> Tensor
+
+- func: fbgemm_linear_quantize_weight(Tensor input) -> (Tensor, Tensor, float, int)
+
+- func: fbgemm_pack_gemm_matrix_fp16(Tensor input) -> Tensor
+
+- func: _wrapped_linear_prepack(Tensor weight, Tensor weight_scale, Tensor weight_zero_point, Tensor bias) -> Tensor
+
+- func: _wrapped_quantized_linear_prepacked(Tensor input, Tensor input_scale, Tensor input_zero_point, Tensor packed_weight, Tensor output_scale, Tensor output_zero_point, int out_channel) -> Tensor
+
+- func: fbgemm_linear_fp16_weight_fp32_activation(Tensor input, Tensor packed_weight, Tensor? bias) -> Tensor
+
+- func: fbgemm_linear_fp16_weight_fp32_activation.out(Tensor input, Tensor packed_weight, Tensor? bias, Tensor(a!) output) -> Tensor
+
+- func: fbgemm_linear_fp16_weight(Tensor input, Tensor packed_weight, Tensor bias) -> Tensor
+
+- func: fbgemm_linear_fp16_weight.out(Tensor input, Tensor packed_weight, Tensor bias, Tensor(a!) output) -> Tensor
+
+- func: fbgemm_pack_quantized_matrix(Tensor input) -> Tensor
+
+- func: fbgemm_pack_quantized_matrix.KN(Tensor input, int K, int N) -> Tensor
+
+- func: ldexp.Tensor(Tensor self, Tensor other) -> Tensor
+  variants: function, method
+
+- func: ldexp_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  variants: function, method
+  tags: pointwise
+
+- func: ldexp.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  tags: pointwise
+
+- func: linspace(Scalar start, Scalar end, int steps, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: linspace
+
+- func: linspace.Tensor_Tensor(Tensor start, Tensor end, int steps, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  category_override: factory
+  dispatch:
+    CompositeExplicitAutograd: linspace
+
+- func: linspace.Tensor_Scalar(Tensor start, Scalar end, int steps, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  category_override: factory
+  dispatch:
+    CompositeExplicitAutograd: linspace
+
+- func: linspace.Scalar_Tensor(Scalar start, Tensor end, int steps, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  category_override: factory
+  dispatch:
+    CompositeExplicitAutograd: linspace
+
+- func: linspace.out(Scalar start, Scalar end, int steps, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, Meta: linspace_out
+    CUDA: linspace_cuda_out
+    MPS: linspace_out_mps
+
+- func: linspace.Tensor_Tensor_out(Tensor start, Tensor end, int steps, *, Tensor(a!) out) -> Tensor(a!)
+  category_override: factory
+  dispatch:
+    CompositeExplicitAutograd: linspace_out
+
+- func: linspace.Tensor_Scalar_out(Tensor start, Scalar end, int steps, *, Tensor(a!) out) -> Tensor(a!)
+  category_override: factory
+  dispatch:
+    CompositeExplicitAutograd: linspace_out
+
+- func: linspace.Scalar_Tensor_out(Scalar start, Tensor end, int steps, *, Tensor(a!) out) -> Tensor(a!)
+  category_override: factory
+  dispatch:
+    CompositeExplicitAutograd: linspace_out
+
+- func: log(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: log.out
+  variants: function, method
+  tags: [core, pointwise]
+
+- func: log_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: log.out
+  variants: function, method
+  tags: pointwise
+
+- func: log.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS, MTIA: log_out
+  tags: pointwise
+
+- func: log10(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: log10.out
+  variants: function, method
+  tags: [core, pointwise]
+
+- func: log10_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: log10.out
+  variants: function, method
+  tags: pointwise
+
+- func: log10.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: log10_out
+  tags: pointwise
+
+- func: log1p(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: log1p.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: log1p_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: log1p_sparse_csr
+  tags: [core, pointwise]
+
+- func: log1p_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: log1p.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: log1p_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: log1p_sparse_csr_
+  tags: pointwise
+
+- func: log1p.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: log1p_out
+    SparseCPU, SparseCUDA, SparseMPS: log1p_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: log1p_sparse_csr_out
+  tags: pointwise
+
+- func: log2(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: log2.out
+  variants: function, method
+  tags: [core, pointwise]
+
+- func: log2_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: log2.out
+  variants: function, method
+  tags: pointwise
+
+- func: log2.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS, MTIA: log2_out
+  tags: pointwise
+
+- func: logaddexp.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: logaddexp_out
+    MPS: logaddexp_out_mps
+  tags: pointwise
+
+- func: logaddexp(Tensor self, Tensor other) -> Tensor
+  variants: method, function
+  structured_delegate: logaddexp.out
+  tags: pointwise
+
+- func: logaddexp2.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: logaddexp2_out
+    MPS: logaddexp2_out_mps
+  tags: pointwise
+
+- func: logaddexp2(Tensor self, Tensor other) -> Tensor
+  variants: method, function
+  structured_delegate: logaddexp2.out
+  tags: pointwise
+
+- func: xlogy.Tensor(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: xlogy.OutTensor
+  variants: function, method
+  tags: pointwise
+
+- func: xlogy.Scalar_Self(Scalar self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: xlogy
+  tags: pointwise
+
+- func: xlogy.Scalar_Other(Tensor self, Scalar other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: xlogy
+  tags: pointwise
+
+# xlogy: inplace variant
+- func: xlogy_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  structured_delegate: xlogy.OutTensor
+  tags: pointwise
+
+- func: xlogy_.Scalar_Other(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: xlogy_
+
+# xlogy: out variant
+- func: xlogy.OutTensor(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  variants: function
+  dispatch:
+    CPU, CUDA: xlogy_out
+    MPS: xlogy_out_mps
+  tags: pointwise
+
+- func: xlogy.OutScalar_Self(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: xlogy_out
+  tags: pointwise
+
+- func: xlogy.OutScalar_Other(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: xlogy_out
+  tags: pointwise
+
+- func: logspace(Scalar start, Scalar end, int steps, float base=10.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: logspace
+
+- func: logspace.Tensor_Tensor(Tensor start, Tensor end, int steps, float base=10.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  category_override: factory
+  dispatch:
+    CompositeExplicitAutograd: logspace
+
+- func: logspace.Tensor_Scalar(Tensor start, Scalar end, int steps, float base=10.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  category_override: factory
+  dispatch:
+    CompositeExplicitAutograd: logspace
+
+- func: logspace.Scalar_Tensor(Scalar start, Tensor end, int steps, float base=10.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  category_override: factory
+  dispatch:
+    CompositeExplicitAutograd: logspace
+
+- func: logspace.out(Scalar start, Scalar end, int steps, float base=10.0, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, Meta: logspace_out
+    CUDA: logspace_cuda_out
+
+- func: logspace.Tensor_Tensor_out(Tensor start, Tensor end, int steps, float base=10.0, *, Tensor(a!) out) -> Tensor(a!)
+  category_override: factory
+  dispatch:
+    CompositeExplicitAutograd: logspace_out
+
+- func: logspace.Tensor_Scalar_out(Tensor start, Scalar end, int steps, float base=10.0, *, Tensor(a!) out) -> Tensor(a!)
+  category_override: factory
+  dispatch:
+    CompositeExplicitAutograd: logspace_out
+
+- func: logspace.Scalar_Tensor_out(Scalar start, Tensor end, int steps, float base=10.0, *, Tensor(a!) out) -> Tensor(a!)
+  category_override: factory
+  dispatch:
+    CompositeExplicitAutograd: logspace_out
+
+# log_softmax allows positional dtype, unlike most operators, because kwonly is BC-breaking when loading jit models.
+- func: log_softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor
+  variants: function, method
+
+- func: log_softmax.int_out(Tensor self, int dim, ScalarType? dtype=None, *, Tensor(a!) out) -> Tensor(a!)
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: log_softmax_out
+
+- func: log_softmax.Dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor
+  variants: function, method
+
+- func: _log_softmax(Tensor self, int dim, bool half_to_float) -> Tensor
+  structured_delegate: _log_softmax.out
+  tags: core
+
+- func: _log_softmax.out(Tensor self, int dim, bool half_to_float, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  dispatch:
+    CPU: log_softmax_cpu_out
+    CUDA: log_softmax_cuda_out
+    MTIA: log_softmax_mtia_out
+    MPS: log_softmax_mps_out
+
+- func: _log_softmax_backward_data(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype) -> Tensor
+  structured_delegate: _log_softmax_backward_data.out
+
+- func: _log_softmax_backward_data.out(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  dispatch:
+    CPU: log_softmax_backward_cpu_out
+    CUDA: log_softmax_backward_cuda_out
+    MTIA: log_softmax_backward_mtia_out
+    MPS: log_softmax_backward_mps_out
+
+- func: _logcumsumexp(Tensor self, int dim) -> Tensor
+  dispatch:
+    CPU: _logcumsumexp_cpu
+    CUDA: _logcumsumexp_cuda
+    MPS: _logcumsumexp_mps
+
+- func: _logcumsumexp.out(Tensor self, int dim, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU: _logcumsumexp_out_cpu
+    CUDA: _logcumsumexp_out_cuda
+    MPS: _logcumsumexp_out_mps
+
+- func: logcumsumexp(Tensor self, int dim) -> Tensor
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: logcumsumexp
+
+- func: logcumsumexp.out(Tensor self, int dim, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: logcumsumexp_out
+
+- func: logcumsumexp.dimname(Tensor self, Dimname dim) -> Tensor
+  variants: function, method
+
+- func: logcumsumexp.dimname_out(Tensor self, Dimname dim, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: logsumexp(Tensor self, int[1] dim, bool keepdim=False) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: logsumexp
+
+- func: logsumexp.out(Tensor self, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    # calls squeeze
+    CompositeExplicitAutogradNonFunctional: logsumexp_out
+
+- func: logsumexp.names(Tensor self, Dimname[1] dim, bool keepdim=False) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: logsumexp.names_out(Tensor self, Dimname[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+
+- func: margin_ranking_loss(Tensor input1, Tensor input2, Tensor target, float margin=0.0, int reduction=Mean) -> Tensor
+
+- func: matmul(Tensor self, Tensor other) -> Tensor
+  variants: function, method
+  dispatch:
+    CompositeImplicitAutograd: matmul
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: matmul_nested
+
+- func: matmul_backward(Tensor grad, Tensor self, Tensor other, bool[2] mask) -> (Tensor, Tensor)
+  dispatch:
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: matmul_backward_nested
+  autogen: matmul_backward.out
+
+- func: matmul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeImplicitAutograd: matmul_out
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: matmul_out_nested
+
+# Alias to linalg.matrix_power
+- func: matrix_power(Tensor self, int n) -> Tensor
+  variants: function, method
+
+# Alias to linalg.matrix_power
+- func: matrix_power.out(Tensor self, int n, *, Tensor(a!) out) -> Tensor(a!)
+
+# Alias to linalg.matrix_exp
+- func: matrix_exp(Tensor self) -> Tensor
+  variants: function, method
+
+# This function should be deprecated in favor of differential_analytic_matrix_function in FunctionsManual.cpp
+- func: matrix_exp_backward(Tensor self, Tensor grad) -> Tensor
+
+# DEPRECATED: Use torch.aminmax instead
+- func: _aminmax(Tensor self) -> (Tensor, Tensor)
+  dispatch:
+    CPU, CUDA: _aminmax_all
+  autogen: _aminmax.out
+
+# DEPRECATED: Use torch.aminmax instead
+- func: _aminmax.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor, Tensor)
+  dispatch:
+    CPU, CUDA: _aminmax
+  autogen: _aminmax.dim_out
+
+- func: aminmax(Tensor self, *, int? dim=None, bool keepdim=False) -> (Tensor min, Tensor max)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: aminmax.out
+  variants: function, method
+
+- func: aminmax.out(Tensor self, *, int? dim=None, bool keepdim=False, Tensor(a!) min, Tensor(b!) max) -> (Tensor(a!) min, Tensor(b!) max)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  dispatch:
+    CPU, CUDA: aminmax_out
+    MPS: aminmax_out_mps
+
+- func: _compute_linear_combination(Tensor input, Tensor coefficients) -> Tensor
+  dispatch:
+    CPU, CUDA: _compute_linear_combination
+
+- func: _compute_linear_combination.out(Tensor input, Tensor coefficients, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA: _compute_linear_combination_out
+
+- func: max.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: max.dim_max
+  variants: function, method
+  dispatch:
+    QuantizedCPU, QuantizedCUDA: qmax
+  tags: core
+
+- func: max.dim_max(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) max, Tensor(b!) max_values) -> (Tensor(a!) values, Tensor(b!) indices)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  precomputed:
+  - dim -> int dim
+  dispatch:
+    CPU, CUDA, MTIA: max_out
+    MPS: max_out_mps
+
+- func: max.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: max.names_dim_max(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) max, Tensor(b!) max_values) -> (Tensor(a!) values, Tensor(b!) indices)
+  device_check: NoCheck   # TensorIterator
+
+- func: value_selecting_reduction_backward(Tensor grad, int dim, Tensor indices, SymInt[] sizes, bool keepdim) -> Tensor
+  variants: function
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeImplicitAutograd: value_selecting_reduction_backward_symint
+    NestedTensorCPU, NestedTensorCUDA: value_selecting_reduction_backward_nested_symint
+
+- func: amax(Tensor self, int[1] dim=[], bool keepdim=False) -> Tensor
+  variants: function, method
+  structured_delegate: amax.out
+  tags: core
+
+- func: amax.out(Tensor self, int[1] dim=[], bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  dispatch:
+    CPU, CUDA: amax_out
+    MPS: amax_out_mps
+
+# Return: (Tensor output, Tensor indices)
+- func: max_pool1d_with_indices(Tensor self, int[1] kernel_size, int[1] stride=[], int[1] padding=0, int[1] dilation=1, bool ceil_mode=False) -> (Tensor, Tensor)
+
+- func: max_pool1d(Tensor self, int[1] kernel_size, int[1] stride=[], int[1] padding=0, int[1] dilation=1, bool ceil_mode=False) -> Tensor
+
+- func: max_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor
+  dispatch:
+    CompositeImplicitAutograd: max_pool2d
+    MPS: mps_max_pool2d
+
+- func: max_pool2d_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor
+  dispatch:
+    MPS: mps_max_pool2d_backward
+  autogen: max_pool2d_backward.out
+
+- func: mkldnn_max_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor
+  dispatch:
+    MkldnnCPU: mkldnn_max_pool2d
+  autogen: mkldnn_max_pool2d.out
+
+- func: mkldnn_max_pool2d_backward(Tensor grad_output, Tensor output, Tensor input, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor
+  dispatch:
+    MkldnnCPU: mkldnn_max_pool2d_backward
+  autogen: mkldnn_max_pool2d_backward.out
+
+- func: mkldnn_max_pool3d(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> Tensor
+  dispatch:
+    MkldnnCPU: mkldnn_max_pool3d
+  autogen: mkldnn_max_pool3d.out
+
+- func: mkldnn_max_pool3d_backward(Tensor grad_output, Tensor output, Tensor input, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> Tensor
+  dispatch:
+    MkldnnCPU: mkldnn_max_pool3d_backward
+  autogen: mkldnn_max_pool3d_backward.out
+
+- func: quantized_max_pool1d(Tensor self, int[1] kernel_size, int[1] stride=[], int[1] padding=0, int[1] dilation=1, bool ceil_mode=False) -> Tensor
+  dispatch:
+    QuantizedCPU: quantized_max_pool1d
+  autogen: quantized_max_pool1d.out
+
+- func: quantized_max_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor
+  dispatch:
+    QuantizedCPU: quantized_max_pool2d
+    QuantizedCUDA: quantized_max_pool2d_cudnn
+  autogen: quantized_max_pool2d.out
+
+- func: quantized_max_pool3d(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> Tensor
+  dispatch:
+    QuantizedCPU: quantized_max_pool3d
+  autogen: quantized_max_pool3d.out
+
+- func: max_pool3d(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> Tensor
+
+# The CPU and GPU dispatch variants are named weirdly here because otherwise there
+# are namespacing issues in C++
+- func: mean(Tensor self, *, ScalarType? dtype=None) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: mean
+  tags: core
+
+# For normal naming convention this should be `mean.out`. However since we already have `mean.out` we have to rename this.
+- func: mean.dtype_out(Tensor self, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CompositeExplicitAutograd: mean_dtype_out
+
+- func: mean.dim(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+  structured_delegate: mean.out
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    QuantizedCPU: mean_quantized_cpu
+  tags: core
+
+- func: mean.out(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA: mean_out
+    MPS: mean_out_mps
+    QuantizedCPU: mean_out_quantized_cpu
+
+- func: mean.names_dim(Tensor self, Dimname[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: mean.names_out(Tensor self, Dimname[1] dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+
+- func: nanmean(Tensor self, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+  device_check: NoCheck   # Composite
+  variants: function, method
+
+- func: nanmean.out(Tensor self, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # Composite
+
+- func: median(Tensor self) -> Tensor
+  variants: function, method
+  dispatch:
+    CPU: median_cpu
+    CUDA: median_cuda
+    MPS: median_mps
+  autogen: median.out
+
+- func: median.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: median
+
+- func: median.dim_values(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+  dispatch:
+    CPU: median_out_cpu
+    CUDA: median_out_cuda
+    MPS: median_out_mps
+
+- func: median.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+  variants: function, method
+
+- func: median.names_dim_values(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+
+- func: nanmedian(Tensor self) -> Tensor
+  variants: function, method
+  dispatch:
+    CPU: nanmedian_cpu
+    CUDA: nanmedian_cuda
+    MPS: nanmedian_mps
+  autogen: nanmedian.out
+
+- func: nanmedian.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: nanmedian
+
+- func: nanmedian.dim_values(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+  dispatch:
+    CPU: nanmedian_out_cpu
+    CUDA: nanmedian_out_cuda
+    MPS: nanmedian_out_mps
+
+- func: nanmedian.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+  variants: function, method
+
+- func: nanmedian.names_dim_values(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+
+- func: min.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: min.dim_min
+  variants: function, method
+  dispatch:
+    QuantizedCPU, QuantizedCUDA: qmin
+  tags: core
+
+- func: min.dim_min(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) min, Tensor(b!) min_indices) -> (Tensor(a!) values, Tensor(b!) indices)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  precomputed:
+  - dim -> int dim
+  dispatch:
+    CPU, CUDA, MTIA: min_out
+    MPS: min_out_mps
+
+- func: min.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: min.names_dim_min(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) min, Tensor(b!) min_indices) -> (Tensor(a!) values, Tensor(b!) indices)
+  device_check: NoCheck   # TensorIterator
+
+- func: amin(Tensor self, int[1] dim=[], bool keepdim=False) -> Tensor
+  variants: function, method
+  structured_delegate: amin.out
+  tags: core
+
+- func: amin.out(Tensor self, int[1] dim=[], bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  dispatch:
+    CPU, CUDA: amin_out
+    MPS: amin_out_mps
+
+# TODO: Add this function to MPS dispatch key so that we avoid declaring it in
+# native_functions.yaml
+# https://github.com/pytorch/pytorch/issues/77394
+- func: _mps_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups) -> Tensor
+  dispatch:
+    MPS: _mps_convolution
+  autogen: _mps_convolution.out
+
+- func: mps_convolution_backward(Tensor self, Tensor grad_output, Tensor weight, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    MPS: mps_convolution_backward
+  autogen: mps_convolution_backward.out
+
+- func: mkldnn_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: mkldnn_convolution
+  autogen: mkldnn_convolution.out
+
+- func: mkldnn_rnn_layer(Tensor input, Tensor weight0, Tensor weight1, Tensor weight2, Tensor weight3, Tensor hx_, Tensor cx_, bool reverse, int[] batch_sizes, int mode, int hidden_size, int num_layers, bool has_biases, bool bidirectional, bool batch_first, bool train) -> (Tensor, Tensor, Tensor, Tensor)
+  dispatch:
+    CPU: mkldnn_rnn_layer
+    MkldnnCPU: mkldnn_rnn_layer
+  autogen: mkldnn_rnn_layer.out
+
+- func: mkldnn_rnn_layer_backward(Tensor input, Tensor weight1, Tensor weight2, Tensor weight3, Tensor weight4, Tensor hx_, Tensor cx_tmp, Tensor output, Tensor hy_, Tensor cy_, Tensor? grad_output, Tensor? grad_hy, Tensor? grad_cy, bool reverse, int mode, int hidden_size, int num_layers, bool has_biases, bool train, bool bidirectional, int[] batch_sizes, bool batch_first, Tensor workspace) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor)
+  dispatch:
+    CPU: mkldnn_rnn_layer_backward
+  autogen: mkldnn_rnn_layer_backward.out
+
+- func: miopen_batch_norm(Tensor input, Tensor weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float exponential_average_factor, float epsilon) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    CUDA: miopen_batch_norm
+  autogen: miopen_batch_norm.out
+
+- func: miopen_batch_norm_backward(Tensor input, Tensor grad_output, Tensor weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var, float epsilon) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    CUDA: miopen_batch_norm_backward
+  autogen: miopen_batch_norm_backward.out
+
+- func: miopen_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic) -> Tensor
+  dispatch:
+    CUDA: miopen_convolution
+  autogen: miopen_convolution.out
+
+- func: miopen_convolution_transpose(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] output_padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic) -> Tensor
+  dispatch:
+    CUDA: miopen_convolution_transpose
+  autogen: miopen_convolution_transpose.out
+
+- func: miopen_depthwise_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic) -> Tensor
+  dispatch:
+    CUDA: miopen_depthwise_convolution
+  autogen: miopen_depthwise_convolution.out
+
+- func: miopen_convolution_relu(Tensor self, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups) -> Tensor
+  dispatch:
+    CUDA: miopen_convolution_relu
+
+- func: miopen_convolution_add_relu(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups) -> Tensor
+  dispatch:
+    CUDA: miopen_convolution_add_relu
+
+- func: miopen_rnn(Tensor input, Tensor[] weight, int weight_stride0, Tensor hx, Tensor? cx, int mode, int hidden_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, int[] batch_sizes, Tensor? dropout_state) -> (Tensor, Tensor, Tensor, Tensor, Tensor)
+  dispatch:
+    CUDA: miopen_rnn
+  autogen: miopen_rnn.out
+  tags: nondeterministic_seeded
+
+
+- func: miopen_rnn_backward(Tensor input, Tensor[] weight, int weight_stride0, Tensor weight_buf, Tensor hx, Tensor? cx, Tensor output, Tensor? grad_output, Tensor? grad_hy, Tensor? grad_cy, int mode, int hidden_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, int[] batch_sizes, Tensor? dropout_state, Tensor reserve, bool[4] output_mask) -> (Tensor, Tensor, Tensor, Tensor[])
+  dispatch:
+    CUDA: miopen_rnn_backward
+  autogen: miopen_rnn_backward.out
+
+- func: mm(Tensor self, Tensor mat2) -> Tensor
+  structured_delegate: mm.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA: _sparse_mm
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: _sparse_csr_mm
+  tags: core
+
+- func: mm.out(Tensor self, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  dispatch:
+    CPU: mm_out_cpu
+    CUDA: mm_out_cuda
+    MTIA: mm_out_mtia
+    MPS: mm_out_mps
+    XPU: mm_out_xpu
+    SparseCPU, SparseCUDA: _sparse_mm_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: _sparse_csr_mm_out
+
+- func: mm.dtype(Tensor self, Tensor mat2, ScalarType out_dtype) -> Tensor
+  dispatch:
+    CUDA: _mm_dtype_cuda
+
+- func: mm.dtype_out(Tensor self, Tensor mat2, ScalarType out_dtype, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CUDA: _mm_dtype_out_cuda
+
+- func: _int_mm(Tensor self, Tensor mat2) -> Tensor
+  dispatch:
+    CPU: _int_mm_cpu
+    CUDA: _int_mm_cuda
+    XPU: _int_mm_xpu
+
+- func: _int_mm.out(Tensor self, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU: _int_mm_out_cpu
+    CUDA: _int_mm_out_cuda
+    XPU: _int_mm_out_xpu
+
+- func: _convert_weight_to_int4pack(Tensor self, int innerKTiles) -> Tensor
+  dispatch:
+    CUDA: _convert_weight_to_int4pack_cuda
+    MPS: _convert_weight_to_int4pack_mps
+
+- func: _weight_int4pack_mm(Tensor self, Tensor mat2, int qGroupSize, Tensor qScaleAndZeros) -> Tensor
+  dispatch:
+    MPS: _weight_int4pack_mm_mps
+    CUDA: _weight_int4pack_mm_cuda
+
+- func: _weight_int4pack_mm_with_scales_and_zeros(Tensor self, Tensor mat2, int qGroupSize, Tensor qScale, Tensor qZeros) -> Tensor
+  dispatch:
+    XPU: _weight_int4pack_mm_xpu
+
+# Split int4 pack weight between cpu and other devices due to
+# https://github.com/pytorch/ao/issues/1117#issuecomment-2451252756.
+- func: _convert_weight_to_int4pack_for_cpu(Tensor self, int innerKTiles) -> Tensor
+  dispatch:
+    CPU: _convert_weight_to_int4pack_cpu
+
+- func: _weight_int4pack_mm_for_cpu(Tensor self, Tensor mat2, int qGroupSize, Tensor qScaleAndZeros) -> Tensor
+  dispatch:
+    CPU: _weight_int4pack_mm_cpu
+
+- func: _dyn_quant_pack_4bit_weight(Tensor weights, Tensor scales_zeros, Tensor? bias, int block_size, int in_features, int out_features) -> Tensor
+  dispatch:
+    CPU: _dyn_quant_pack_4bit_weight_cpu
+
+- func: _dyn_quant_matmul_4bit(Tensor inp, Tensor packed_weights, int block_size, int in_features, int out_features) -> Tensor
+  dispatch:
+    CPU: _dyn_quant_matmul_4bit_cpu
+
+- func: _weight_int8pack_mm(Tensor self, Tensor mat2, Tensor scales) -> Tensor
+  dispatch:
+    CPU: _weight_int8pack_mm_cpu
+    CUDA: _weight_int8pack_mm_cuda
+    MPS: _weight_int8pack_mm_mps
+
+- func: _sparse_mm(Tensor sparse, Tensor dense) -> Tensor
+  python_module: sparse
+
+- func: _sparse_mm.reduce(Tensor sparse, Tensor dense, str reduce) -> Tensor
+  python_module: sparse
+
+- func: _sparse_sparse_matmul(Tensor self, Tensor other) -> Tensor
+  dispatch:
+    SparseCPU: sparse_sparse_matmul_cpu
+    SparseCUDA: sparse_sparse_matmul_cuda
+  autogen: _sparse_sparse_matmul.out
+
+- func: mode(Tensor self, int dim=-1, bool keepdim=False) -> (Tensor values, Tensor indices)
+  variants: function, method
+  dispatch:
+    CPU, CUDA: mode
+
+- func: mode.values(Tensor self, int dim=-1, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+  dispatch:
+    CompositeExplicitAutograd: mode_out
+
+- func: mode.dimname(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+  variants: function, method
+
+- func: mode.dimname_out(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+
+- func: mul.Tensor(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: mul.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA: mul_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: mul_sparse_csr
+    MkldnnCPU: mkldnn_mul
+    ZeroTensor: mul_zerotensor
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_mul_Tensor
+  tags: [core, pointwise]
+
+- func: mul_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: mul.out
+  variants: method
+  dispatch:
+    SparseCPU, SparseCUDA: mul_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: mul_sparse_csr_
+    MkldnnCPU: mkldnn_mul_
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_mul__Tensor
+  tags: pointwise
+
+- func: mul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS, MTIA: mul_out
+    SparseCPU: mul_out_sparse_cpu
+    SparseCUDA: mul_out_sparse_cuda
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: mul_out_sparse_csr
+    MkldnnCPU: mkldnn_mul_out
+  tags: pointwise
+  # For C++ only, until we have conversion from C++ numbers to Tensor
+
+- func: mul.Scalar(Tensor self, Scalar other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: mul
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: mul_scalar_sparse_csr
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_mul_Scalar
+  tags: [core, pointwise]
+
+- func: mul_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: mul_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: mul__scalar_sparse_csr
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_mul__Scalar
+  autogen: mul.Scalar_out
+  tags: pointwise
+# multiply, alias for mul
+
+- func: multiply.Tensor(Tensor self, Tensor other) -> Tensor
+  variants: function, method
+
+- func: multiply_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  variants: method
+
+- func: multiply.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: multiply.Scalar(Tensor self, Scalar other) -> Tensor
+  variants: function, method
+
+- func: multiply_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  variants: method
+
+- func: mv(Tensor self, Tensor vec) -> Tensor
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: mv
+    SparseCPU, SparseCUDA: mv_sparse
+
+- func: mv.out(Tensor self, Tensor vec, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: mv_out
+
+- func: mvlgamma.out(Tensor self, int p, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA: mvlgamma_out
+  tags: pointwise
+
+- func: mvlgamma(Tensor self, int p) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: mvlgamma
+  tags: pointwise
+
+- func: mvlgamma_(Tensor(a!) self, int p) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: mvlgamma_
+  tags: pointwise
+
+- func: narrow_copy(Tensor self, int dim, SymInt start, SymInt length) -> Tensor
+  variants: function, method
+  dispatch:
+    CPU: narrow_copy_dense_cpu
+    SparseCPU, SparseCUDA: narrow_copy_sparse
+    CompositeExplicitAutogradNonFunctional: narrow_copy_dense_symint
+  tags: view_copy
+
+- func: narrow_copy.out(Tensor self, int dim, SymInt start, SymInt length, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU: narrow_copy_dense_cpu_out
+
+- func: narrow(Tensor(a) self, int dim, SymInt start, SymInt length) -> Tensor(a)
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeImplicitAutograd: narrow_symint
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: narrow_nested_symint
+
+- func: narrow.Tensor(Tensor(a) self, int dim, Tensor start, SymInt length) -> Tensor(a)
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeImplicitAutograd: narrow_tensor_symint
+
+- func: native_batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    CPU: batch_norm_cpu
+    CUDA: batch_norm_cuda
+    MPS: batch_norm_mps
+    MkldnnCPU: mkldnn_batch_norm
+
+- func: native_batch_norm.out(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps, *, Tensor(a!) out, Tensor(b!) save_mean, Tensor(c!) save_invstd) -> (Tensor(a!), Tensor(b!), Tensor(c!))
+  dispatch:
+    CUDA: batch_norm_cuda_out
+    MPS: batch_norm_mps_out
+    CPU: batch_norm_cpu_out
+
+# TODO: In 2 weeks, we should make native_batch_norm composite implicit so that this correct schema percolates correctly through our dispatching
+- func: _native_batch_norm_legit(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    CPU: _batch_norm_legit_cpu
+    CUDA: _batch_norm_legit_cuda
+    MPS: _batch_norm_legit_mps
+    MkldnnCPU: _mkldnn_batch_norm_legit
+  autogen: _native_batch_norm_legit_functional
+  tags: core
+
+# HACK: identical to _native_batch_norm_legit, but training is known to be False,
+# So we known that running stats will not be mutated.
+# The real fix here is batch norm consolidation.
+- func: _native_batch_norm_legit_no_training(Tensor input, Tensor? weight, Tensor? bias, Tensor running_mean, Tensor running_var, float momentum, float eps) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    CompositeExplicitAutograd: _batch_norm_legit_no_training
+  autogen: _native_batch_norm_legit_no_training.out
+  tags: core
+
+- func: _native_batch_norm_legit.out(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, bool training, float momentum, float eps, *, Tensor(d!) out, Tensor(e!) save_mean, Tensor(f!) save_invstd) -> (Tensor(d!), Tensor(e!), Tensor(f!))
+  dispatch:
+    CPU: _batch_norm_legit_cpu_out
+    CUDA: _batch_norm_legit_cuda_out
+    MPS: _batch_norm_legit_mps_out
+
+- func: _native_batch_norm_legit.no_stats(Tensor input, Tensor? weight, Tensor? bias, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    CPU: _batch_norm_legit_no_stats_cpu
+    CUDA: _batch_norm_legit_no_stats_cuda
+    MPS: _batch_norm_legit_no_stats_mps
+    MkldnnCPU: _mkldnn_batch_norm_legit_no_stats
+  tags: core
+
+- func: _native_batch_norm_legit.no_stats_out(Tensor input, Tensor? weight, Tensor? bias, bool training, float momentum, float eps, *, Tensor(a!) out, Tensor(b!) save_mean, Tensor(c!) save_invstd) -> (Tensor(a!), Tensor(b!), Tensor(c!))
+  dispatch:
+    CPU: _batch_norm_legit_no_stats_cpu_out
+    CUDA: _batch_norm_legit_no_stats_cuda_out
+    MPS: _batch_norm_legit_no_stats_mps_out
+
+- func: batch_norm_stats(Tensor input, float eps) -> (Tensor, Tensor)
+  dispatch:
+    CUDA: batch_norm_stats_cuda
+  autogen: batch_norm_stats.out
+
+- func: batch_norm_elemt(Tensor input, Tensor? weight, Tensor? bias, Tensor mean, Tensor invstd, float eps) -> Tensor
+  dispatch:
+    CUDA: batch_norm_elemt_cuda
+
+- func: batch_norm_elemt.out(Tensor input, Tensor? weight, Tensor? bias, Tensor mean, Tensor invstd, float eps, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CUDA: batch_norm_elemt_cuda_out
+
+# for backward compatibility
+- func: batch_norm_gather_stats(Tensor input, Tensor mean, Tensor invstd, Tensor? running_mean, Tensor? running_var, float momentum, float eps, int count) -> (Tensor, Tensor)
+  dispatch:
+    CUDA: batch_norm_gather_stats_cuda
+  autogen: batch_norm_gather_stats.out
+
+- func: batch_norm_gather_stats_with_counts(Tensor input, Tensor mean, Tensor invstd, Tensor? running_mean, Tensor? running_var, float momentum, float eps, Tensor counts) -> (Tensor, Tensor)
+  dispatch:
+    CUDA: batch_norm_gather_stats_with_counts_cuda
+  autogen: batch_norm_gather_stats_with_counts.out
+
+- func: native_batch_norm_backward(Tensor grad_out, Tensor input, Tensor? weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_invstd, bool train, float eps, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    CPU: batch_norm_backward_cpu
+    CUDA: batch_norm_backward_cuda
+    MPS: batch_norm_backward_mps
+    MkldnnCPU: mkldnn_batch_norm_backward
+  autogen: native_batch_norm_backward.out
+
+- func: batch_norm_backward_reduce(Tensor grad_out, Tensor input, Tensor mean, Tensor invstd, Tensor? weight, bool input_g, bool weight_g, bool bias_g) -> (Tensor, Tensor, Tensor, Tensor)
+  dispatch:
+    CUDA: batch_norm_backward_reduce_cuda
+  autogen: batch_norm_backward_reduce.out
+
+- func: batch_norm_backward_elemt(Tensor grad_out, Tensor input, Tensor mean, Tensor invstd, Tensor? weight, Tensor sum_dy, Tensor sum_dy_xmu, Tensor count) -> Tensor
+  dispatch:
+    CUDA: batch_norm_backward_elemt_cuda
+  autogen: batch_norm_backward_elemt.out
+
+- func: batch_norm_update_stats(Tensor input, Tensor? running_mean, Tensor? running_var, float momentum) -> (Tensor, Tensor)
+  dispatch:
+    CPU: batch_norm_update_stats_cpu
+    CUDA: batch_norm_update_stats_cuda
+  autogen: batch_norm_update_stats.out
+
+- func: is_vulkan_available() -> bool
+
+- func: _nnpack_available() -> bool
+
+- func: _nnpack_spatial_convolution(Tensor input, Tensor weight, Tensor? bias, SymInt[2] padding, SymInt[2] stride=1) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: _nnpack_spatial_convolution
+  autogen: _nnpack_spatial_convolution.out
+
+- func: ones.names(int[] size, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: ones
+  autogen: ones.names_out
+
+- func: ones(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: ones
+
+- func: ones.out(SymInt[] size, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: ones_out
+
+- func: ones_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+  dispatch:
+    # NB: Although this composite mutates on the inside, it is
+    # non-differentiable so NonFunctional doesn't apply
+    CompositeExplicitAutograd: ones_like
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: ones_like
+  autogen: ones_like.out
+
+- func: pairwise_distance(Tensor x1, Tensor x2, float p=2, float eps=1e-06, bool keepdim=False) -> Tensor
+
+- func: cdist(Tensor x1, Tensor x2, float p=2, int? compute_mode=None) -> Tensor
+
+- func: _euclidean_dist(Tensor x1, Tensor x2) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: _euclidean_dist
+  autogen: _euclidean_dist.out
+
+- func: _cdist_forward(Tensor x1, Tensor x2, float p, int? compute_mode) -> Tensor
+  dispatch:
+    CPU, CUDA: _cdist_forward
+    MPS: _cdist_forward_mps
+  autogen: _cdist_forward.out
+  tags: core
+
+- func: _cdist_backward(Tensor grad, Tensor x1, Tensor x2, float p, Tensor cdist) -> Tensor
+  dispatch:
+    CPU, CUDA: _cdist_backward
+  autogen: _cdist_backward.out
+
+- func: pdist(Tensor self, float p=2) -> Tensor
+
+- func: _pdist_forward(Tensor self, float p=2) -> Tensor
+  dispatch:
+    CPU, CUDA: _pdist_forward
+  autogen: _pdist_forward.out
+  tags: core
+
+- func: _pdist_backward(Tensor grad, Tensor self, float p, Tensor pdist) -> Tensor
+  dispatch:
+    CPU, CUDA: _pdist_backward
+  autogen: _pdist_backward.out
+
+- func: cosine_similarity(Tensor x1, Tensor x2, int dim=1, float eps=1e-08) -> Tensor
+  variants: function
+
+- func: permute(Tensor(a) self, int[] dims) -> Tensor(a)
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: permute
+    MPS: permute_mps
+    SparseCPU, SparseCUDA: permute_sparse_coo
+  tags: core
+
+- func: movedim.intlist(Tensor(a) self, int[] source, int[] destination) -> Tensor(a)
+  variants: function, method
+
+- func: movedim.int(Tensor(a) self, int source, int destination) -> Tensor(a)
+  variants: function, method
+
+# moveaxis, alias for movedim
+- func: moveaxis.intlist(Tensor(a) self, int[] source, int[] destination) -> Tensor(a)
+  variants: function, method
+
+- func: moveaxis.int(Tensor(a) self, int source, int destination) -> Tensor(a)
+  variants: function, method
+
+# Only exposed from C++ -- in Python,
+# we expose it as an attribute `T`, not a function.
+#
+# I'd like to name this "T" in C++ too, but
+# calling a native function "T" causes undefined
+# behavior on Windows, for reasons I don't understand
+# (maybe related to capital letter collation somehow...)
+- func: numpy_T(Tensor(a) self) -> Tensor(a)
+  variants: method
+
+# Exposed on Python as an attribute 'H'
+- func: matrix_H(Tensor(a) self) -> Tensor(a)
+  variants: method
+
+# Exposed on Python as an attribute 'mT'
+- func: mT(Tensor(a) self) -> Tensor(a)
+  variants: method
+
+# Exposed on Python as an attribute 'mH'
+- func: mH(Tensor(a) self) -> Tensor(a)
+  variants: method
+
+- func: adjoint(Tensor(a) self) -> Tensor(a)
+  variants: function, method
+
+- func: pixel_shuffle(Tensor self, int upscale_factor) -> Tensor
+  dispatch:
+    CPU: pixel_shuffle_cpu
+    MPS: pixel_shuffle_mps
+    CompositeExplicitAutogradNonFunctional: math_pixel_shuffle
+  autogen: pixel_shuffle.out
+
+- func: pixel_unshuffle(Tensor self, int downscale_factor) -> Tensor
+  dispatch:
+    CPU: pixel_unshuffle_cpu
+    MPS: pixel_unshuffle_mps
+    CompositeExplicitAutogradNonFunctional: math_pixel_unshuffle
+  autogen: pixel_unshuffle.out
+
+- func: channel_shuffle(Tensor self, SymInt groups) -> Tensor
+  dispatch:
+    CPU, CUDA: channel_shuffle
+    QuantizedCPU: channel_shuffle_quantized_cpu
+  autogen: channel_shuffle.out
+
+- func: native_channel_shuffle(Tensor self, SymInt groups) -> Tensor
+  dispatch:
+    CPU: channel_shuffle_cpu
+    CompositeImplicitAutograd: math_channel_shuffle
+
+- func: is_pinned(Tensor self, Device? device=None) -> bool
+  variants: method
+  dispatch:
+    # the NestedTensor keys are necessary because NestedTensor has been removed
+    # from the CompositeExplicitAutograd keyset see Note [NestedTensor Not Included in Backend Keys]
+    CompositeExplicitAutograd, NestedTensorCPU: is_pinned
+    SparseCsrCPU: is_pinned_sparse_compressed
+    SparseCPU: is_pinned_sparse_coo
+
+# TODO: add a copy kwarg that guarantees that the tensor is put into fresh
+# pinned memory
+- func: pin_memory(Tensor(a) self, Device? device=None) -> Tensor(a)
+  variants: method
+
+# Unlike pin_memory, this is guaranteed to give a new non-aliasing tensor
+- func: _pin_memory(Tensor self, Device? device=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: _pin_memory
+    NestedTensorCPU: _pin_memory_nested
+    SparseCPU: _pin_memory_sparse_coo
+    SparseCsrCPU: _pin_memory_sparse_compressed
+  autogen: _pin_memory.out
+
+- func: pinverse(Tensor self, float rcond=1e-15) -> Tensor
+  variants: function, method
+
+- func: poisson_nll_loss(Tensor input, Tensor target, bool log_input, bool full, float eps, int reduction) -> Tensor
+  variants: function
+
+- func: rad2deg(Tensor self) -> Tensor
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: rad2deg
+    SparseCPU, SparseCUDA, SparseMPS: rad2deg_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: rad2deg_sparse_csr
+  tags: pointwise
+
+- func: rad2deg_(Tensor(a!) self) -> Tensor(a!)
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: rad2deg_
+    SparseCPU, SparseCUDA, SparseMPS: rad2deg_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: rad2deg_sparse_csr_
+  tags: pointwise
+
+- func: rad2deg.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: rad2deg_out
+    SparseCPU, SparseCUDA, SparseMPS: rad2deg_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: rad2deg_sparse_csr_out
+  tags: pointwise
+
+- func: deg2rad(Tensor self) -> Tensor
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: deg2rad
+    SparseCPU, SparseCUDA, SparseMPS: deg2rad_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: deg2rad_sparse_csr
+  tags: pointwise
+
+- func: deg2rad_(Tensor(a!) self) -> Tensor(a!)
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: deg2rad_
+    SparseCPU, SparseCUDA, SparseMPS: deg2rad_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: deg2rad_sparse_csr_
+  tags: pointwise
+
+- func: deg2rad.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: deg2rad_out
+    SparseCPU, SparseCUDA, SparseMPS: deg2rad_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: deg2rad_sparse_csr_out
+  tags: pointwise
+
+- func: scalar_tensor(Scalar s, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: scalar_tensor
+  autogen: scalar_tensor.out
+  tags: core
+
+- func: rand.names(SymInt[] size, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: rand
+  autogen: rand.names_out
+  tags: nondeterministic_seeded
+
+- func: rand.generator_with_names(SymInt[] size, *, Generator? generator, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  device_check: NoCheck
+  device_guard: False
+  tags: nondeterministic_seeded
+  dispatch:
+    CompositeExplicitAutograd: rand
+  autogen: rand.generator_with_names_out
+
+- func: rand(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  tags: [core, nondeterministic_seeded]
+  dispatch:
+    CompositeExplicitAutograd: rand
+
+- func: rand.generator(SymInt[] size, *, Generator? generator, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  tags: nondeterministic_seeded
+  dispatch:
+    CompositeExplicitAutograd: rand
+
+- func: rand.out(SymInt[] size, *, Tensor(a!) out) -> Tensor(a!)
+  tags: nondeterministic_seeded
+  dispatch:
+    CompositeExplicitAutograd: rand_out
+
+- func: rand.generator_out(SymInt[] size, *, Generator? generator, Tensor(a!) out) -> Tensor(a!)
+  tags: nondeterministic_seeded
+
+- func: rand_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+  tags: nondeterministic_seeded
+  dispatch:
+    # NB: Although this composite mutates on the inside, it is
+    # non-differentiable so NonFunctional doesn't apply
+    CompositeExplicitAutograd: rand_like
+  autogen: rand_like.out
+
+- func: randint(SymInt high, SymInt[] size, *, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  tags: nondeterministic_seeded
+  dispatch:
+    CompositeExplicitAutograd: randint
+
+- func: randint.generator(SymInt high, SymInt[] size, *, Generator? generator, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  tags: nondeterministic_seeded
+  dispatch:
+    CompositeExplicitAutograd: randint
+
+- func: randint.low(SymInt low, SymInt high, SymInt[] size, *, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  tags: nondeterministic_seeded
+  dispatch:
+    CompositeExplicitAutograd: randint
+
+- func: randint.low_generator(SymInt low, SymInt high, SymInt[] size, *, Generator? generator, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  tags: nondeterministic_seeded
+  dispatch:
+    CompositeExplicitAutograd: randint
+
+- func: randint.out(SymInt high, SymInt[] size, *, Tensor(a!) out) -> Tensor(a!)
+  tags: nondeterministic_seeded
+  dispatch:
+    CompositeExplicitAutograd: randint_out
+
+- func: randint.generator_out(SymInt high, SymInt[] size, *, Generator? generator, Tensor(a!) out) -> Tensor(a!)
+  tags: nondeterministic_seeded
+  dispatch:
+    CompositeExplicitAutograd: randint_out
+
+- func: randint.low_out(SymInt low, SymInt high, SymInt[] size, *, Tensor(a!) out) -> Tensor(a!)
+  tags: nondeterministic_seeded
+  dispatch:
+    CompositeExplicitAutograd: randint_out
+
+- func: randint.low_generator_out(SymInt low, SymInt high, SymInt[] size, *, Generator? generator, Tensor(a!) out) -> Tensor(a!)
+  tags: nondeterministic_seeded
+  dispatch:
+    CompositeExplicitAutograd: randint_out
+
+- func: randint_like(Tensor self, SymInt high, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+  tags: nondeterministic_seeded
+  dispatch:
+    # NB: Although this composite mutates on the inside, it is
+    # non-differentiable so NonFunctional doesn't apply
+    CompositeExplicitAutograd: randint_like
+  autogen: randint_like.out
+
+- func: randint_like.Tensor(Tensor self, Tensor high, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+  tags: nondeterministic_seeded
+  dispatch:
+    # NB: Although this composite mutates on the inside, it is
+    # non-differentiable so NonFunctional doesn't apply
+    CompositeExplicitAutograd: randint_like
+  autogen: randint_like.Tensor_out
+
+- func: randint_like.low_dtype(Tensor self, SymInt low, SymInt high, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+  tags: nondeterministic_seeded
+  dispatch:
+    # NB: Although this composite mutates on the inside, it is
+    # non-differentiable so NonFunctional doesn't apply
+    CompositeExplicitAutograd: randint_like
+  autogen: randint_like.low_dtype_out
+
+- func: randn(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  tags: [core, nondeterministic_seeded]
+  dispatch:
+    CompositeExplicitAutograd: randn
+
+- func: randn.generator(SymInt[] size, *, Generator? generator, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  tags: nondeterministic_seeded
+  dispatch:
+    CompositeExplicitAutograd: randn
+
+- func: randn.names(SymInt[] size, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  tags: nondeterministic_seeded
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: randn
+  autogen: randn.names_out
+
+- func: randn.generator_with_names(SymInt[] size, *, Generator? generator, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  tags: nondeterministic_seeded
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: randn
+  autogen: randn.generator_with_names_out
+
+- func: randn.out(SymInt[] size, *, Tensor(a!) out) -> Tensor(a!)
+  tags: nondeterministic_seeded
+
+- func: randn.generator_out(SymInt[] size, *, Generator? generator, Tensor(a!) out) -> Tensor(a!)
+  tags: nondeterministic_seeded
+
+- func: randn_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+  tags: nondeterministic_seeded
+  dispatch:
+    # NB: Although this composite mutates on the inside, it is
+    # non-differentiable so NonFunctional doesn't apply
+    CompositeExplicitAutograd, CompositeImplicitAutogradNestedTensor: randn_like
+  autogen: randn_like.out
+
+- func: randperm(SymInt n, *, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  tags: [core, nondeterministic_seeded]
+  dispatch:
+    CompositeExplicitAutograd: randperm
+
+- func: randperm.generator(SymInt n, *, Generator? generator, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  tags: nondeterministic_seeded
+  dispatch:
+    CompositeExplicitAutograd: randperm
+
+- func: randperm.out(SymInt n, *, Tensor(a!) out) -> Tensor(a!)
+  tags: nondeterministic_seeded
+  dispatch:
+    CompositeExplicitAutograd: randperm_out
+
+- func: randperm.generator_out(SymInt n, *, Generator? generator, Tensor(a!) out) -> Tensor(a!)
+  tags: nondeterministic_seeded
+  dispatch:
+    CPU: randperm_out_cpu
+    CUDA: randperm_out_cuda
+    MPS: randperm_out_mps
+
+- func: range.step(Scalar start, Scalar end, Scalar step=1, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: range
+
+- func: range(Scalar start, Scalar end, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: range
+
+- func: range.out_(Scalar start, Scalar end, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: range_out_no_step
+
+- func: range.out(Scalar start, Scalar end, Scalar step=1, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, Meta: range_out
+    CUDA: range_cuda_out
+    MPS: range_mps_out
+  cpp_no_default_args: ['step']
+
+- func: ravel(Tensor(a) self) -> Tensor(a)
+  variants: function, method
+
+- func: reciprocal(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: reciprocal.out
+  variants: function, method
+  tags: [core, pointwise]
+
+- func: reciprocal_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: reciprocal.out
+  variants: function, method
+  tags: pointwise
+
+- func: reciprocal.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MTIA: reciprocal_out
+    MPS: reciprocal_out_mps
+  tags: pointwise
+
+- func: neg(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: neg.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: neg_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: neg_sparse_csr
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_neg
+  tags: [core, pointwise]
+
+- func: neg_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: neg.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: neg_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: neg_sparse_csr_
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_neg_
+  tags: pointwise
+
+- func: neg.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS, MTIA: neg_out
+    SparseCPU, SparseCUDA, SparseMPS: neg_out_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: neg_sparse_csr_out
+  tags: pointwise
+# Alias for neg
+
+- func: negative(Tensor self) -> Tensor
+  variants: function, method
+
+- func: negative_(Tensor(a!) self) -> Tensor(a!)
+  variants: function, method
+
+- func: negative.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: repeat(Tensor self, SymInt[] repeats) -> Tensor
+  variants: method  # This is method-only to match the previous tensor API. In the future we could make this a function too.
+  dispatch:
+    CompositeExplicitAutograd: repeat
+    MPS: repeat_mps
+  autogen: repeat.out
+  tags: core
+
+- func: repeat_interleave.Tensor(Tensor repeats, *, SymInt? output_size=None) -> Tensor
+  variants: function
+  dispatch:
+    CPU: repeat_interleave_cpu
+    CUDA: repeat_interleave_cuda
+    MPS: repeat_interleave_mps
+  tags: dynamic_output_shape
+  autogen: repeat_interleave.Tensor_out
+
+- func: repeat_interleave.self_Tensor(Tensor self, Tensor repeats, int? dim=None, *, SymInt? output_size=None) -> Tensor
+  variants: function, method
+  dispatch:
+    CompositeImplicitAutograd: repeat_interleave_symint
+
+- func: repeat_interleave.self_int(Tensor self, SymInt repeats, int? dim=None, *, SymInt? output_size=None) -> Tensor
+  variants: function, method
+  dispatch:
+    CompositeImplicitAutograd: repeat_interleave_symint
+
+- func: reshape(Tensor(a) self, SymInt[] shape) -> Tensor(a)
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeImplicitAutograd: reshape_symint
+    CompositeImplicitAutogradNestedTensor: reshape_nested_symint
+
+- func: _reshape_copy(Tensor self, SymInt[] size) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: _reshape_copy_symint
+
+# NOTE [ _reshape_alias ] is meant to be used in the implementation of reshape.
+# They are not user-facing, hence the leading underscore. Please don't use it
+# anywhere else.
+- func: _reshape_alias(Tensor(a) self, SymInt[] size, SymInt[] stride) -> Tensor(a)
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CPU, CUDA, Meta, QuantizedCPU, QuantizedCUDA, ZeroTensor, MPS, MTIA: _reshape_alias
+    # We don't need to support mkldnn since this is handled explicitly by the reshape operator.
+
+- func: _mkldnn_reshape(Tensor self, int[] shape) -> Tensor
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    MkldnnCPU: mkldnn_reshape
+  autogen: _mkldnn_reshape.out
+
+- func: reshape_as(Tensor(a) self, Tensor other) -> Tensor(a)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeImplicitAutograd: reshape_as
+    CompositeImplicitAutogradNestedTensor: reshape_as_nested
+
+- func: round(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: round.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: round_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: round_sparse_csr
+  tags: [core, pointwise]
+
+- func: round_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: round.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: round_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: round_sparse_csr_
+  tags: pointwise
+
+- func: round.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: round_out
+    SparseCPU, SparseCUDA, SparseMPS: round_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: round_sparse_csr_out
+  tags: pointwise
+
+- func: round.decimals(Tensor self, *, int decimals) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: round.decimals_out
+  variants: function, method
+  tags: pointwise
+
+- func: round_.decimals(Tensor(a!) self, *, int decimals) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: round.decimals_out
+  variants: function, method
+  tags: pointwise
+
+- func: round.decimals_out(Tensor self, *, int decimals, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: round_decimals_out
+  tags: pointwise
+
+- func: rrelu(Tensor self, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  tags: [pointwise, nondeterministic_seeded]
+
+- func: rrelu_(Tensor(a!) self, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor(a!)
+  tags: nondeterministic_seeded
+  device_check: NoCheck   # TensorIterator
+
+- func: relu(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CPU, CUDA: relu
+    MPS: relu_mps
+    MTIA: relu_mtia
+    MkldnnCPU: mkldnn_relu
+    QuantizedCPU: relu_quantized_cpu
+    QuantizedCUDA: relu_quantized_cuda
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_relu
+    SparseCPU, SparseCUDA, SparseMPS: relu_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: relu_sparse_csr
+  tags: [core, pointwise]
+
+- func: relu_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CPU, CUDA: relu_
+    MPS: relu_mps_
+    MTIA: relu_mtia_
+    MkldnnCPU: mkldnn_relu_
+    QuantizedCPU: relu_quantized_cpu_
+    QuantizedCUDA: relu_quantized_cuda_
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_relu_
+    SparseCPU, SparseCUDA, SparseMPS: relu_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: relu_sparse_csr_
+  autogen: relu.out
+  tags: pointwise
+
+- func: relu6(Tensor self) -> Tensor
+  python_module: nn
+  tags: pointwise
+
+- func: relu6_(Tensor(a!) self) -> Tensor(a!)
+  python_module: nn
+
+- func: prelu(Tensor self, Tensor weight) -> Tensor
+  variants: function, method
+  autogen: prelu.out
+
+- func: _prelu_kernel(Tensor self, Tensor weight) -> Tensor
+  dispatch:
+    CPU, CUDA: _prelu_kernel
+    QuantizedCPU: _prelu_kernel_quantized_cpu
+    MkldnnCPU: mkldnn_prelu
+    MPS: prelu_mps
+
+- func: _prelu_kernel_backward(Tensor grad_output, Tensor self, Tensor weight) -> (Tensor, Tensor)
+  dispatch:
+    CPU, CUDA: _prelu_kernel_backward
+    MkldnnCPU: mkldnn_prelu_backward
+    MPS: prelu_backward_mps
+
+- func: gelu.out(Tensor self, *, str approximate='none', Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  dispatch:
+    CPU: gelu_out_cpu
+    CUDA: gelu_out_cuda
+    MPS: gelu_out_mps
+
+- func: gelu_(Tensor(a!) self, *, str approximate='none') -> Tensor(a!)
+  structured_delegate: gelu.out
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  dispatch:
+    QuantizedCPU: gelu_quantized_cpu_
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_gelu_
+
+- func: gelu(Tensor self, *, str approximate='none') -> Tensor
+  structured_delegate: gelu.out
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  dispatch:
+    MkldnnCPU: mkldnn_gelu
+    QuantizedCPU: gelu_quantized_cpu
+    QuantizedCUDA: gelu_quantized_cuda
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_gelu
+  tags: [core, pointwise]
+
+- func: gelu_backward.grad_input(Tensor grad_output, Tensor self, *, str approximate='none', Tensor(a!) grad_input) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  python_module: nn
+  dispatch:
+    CPU: gelu_backward_out_cpu
+    CUDA: gelu_backward_out_cuda
+    MPS: gelu_backward_out_mps
+
+- func: gelu_backward(Tensor grad_output, Tensor self, *, str approximate='none') -> Tensor
+  structured_delegate: gelu_backward.grad_input
+  python_module: nn
+  dispatch:
+    MkldnnCPU: mkldnn_gelu_backward
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: gelu_backwards_nested
+  tags: pointwise
+
+- func: infinitely_differentiable_gelu_backward(Tensor grad, Tensor self) -> Tensor
+  variants: function
+  python_module: nn
+  device_check: NoCheck
+  device_guard: False
+
+- func: hardshrink.out(Tensor self, Scalar lambd=0.5, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MPS: hardshrink_out
+
+- func: hardshrink(Tensor self, Scalar lambd=0.5) -> Tensor
+  structured_delegate: hardshrink.out
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  tags: pointwise
+
+- func: hardshrink_backward.grad_input(Tensor grad_out, Tensor self, Scalar lambd, *, Tensor(a!) grad_input) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: hardshrink_backward_out
+
+- func: hardshrink_backward(Tensor grad_out, Tensor self, Scalar lambd) -> Tensor
+  structured_delegate: hardshrink_backward.grad_input
+  variants: function, method
+
+- func: rsqrt(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: rsqrt.out
+  variants: function, method
+  tags: [core, pointwise]
+
+- func: rsqrt_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: rsqrt.out
+  variants: function, method
+  tags: pointwise
+
+- func: rsqrt.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS, MTIA: rsqrt_out
+  tags: pointwise
+
+- func: select.Dimname(Tensor(a) self, Dimname dim, int index) -> Tensor(a)
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+
+- func: select.int(Tensor(a) self, int dim, SymInt index) -> Tensor(a)
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: select_symint
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: select_sparse_csr
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: select_nested
+  tags: core
+
+- func: select_backward(Tensor grad_output, SymInt[] input_sizes, int dim, SymInt index) -> Tensor
+  variants: function
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: select_backward_symint
+  autogen: select_backward.out
+
+- func: _nested_select_backward(Tensor grad_output, Tensor self, int dim, SymInt index) -> Tensor
+  variants: function
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: _nested_select_backward_symint
+
+- func: selu(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  tags: pointwise
+
+- func: selu_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+
+- func: celu(Tensor self, Scalar alpha=1.0) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CompositeExplicitAutograd: celu
+  tags: pointwise
+
+- func: celu_(Tensor(a!) self, Scalar alpha=1.0) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CompositeExplicitAutograd: celu_
+  autogen: celu.out
+
+- func: silu(Tensor self) -> Tensor
+  structured_delegate: silu.out
+  python_module: nn
+  dispatch:
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_silu
+  tags: pointwise
+
+- func: silu_(Tensor(a!) self) -> Tensor(a!)
+  structured_delegate: silu.out
+  python_module: nn
+  dispatch:
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_silu_
+  tags: pointwise
+
+- func: silu.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  python_module: nn
+  dispatch:
+    CPU, CUDA, MTIA: silu_out
+    MPS: silu_out_mps
+  tags: pointwise
+
+- func: silu_backward.grad_input(Tensor grad_output, Tensor self, *, Tensor(a!) grad_input) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  python_module: nn
+  dispatch:
+    CPU, CUDA: silu_backward_out
+    MPS: silu_backward_out_mps
+  tags: pointwise
+
+- func: silu_backward(Tensor grad_output, Tensor self) -> Tensor
+  structured_delegate: silu_backward.grad_input
+  python_module: nn
+  dispatch:
+    CompositeImplicitAutograd: math_silu_backward
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: silu_backward_nested
+  tags: pointwise
+
+- func: mish(Tensor self) -> Tensor
+  structured_delegate: mish.out
+  python_module: nn
+  tags: pointwise
+
+- func: mish_(Tensor(a!) self) -> Tensor(a!)
+  structured_delegate: mish.out
+  python_module: nn
+
+- func: mish.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  python_module: nn
+  dispatch:
+    CPU, CUDA: mish_out
+    MPS: mish_out_mps
+
+- func: mish_backward(Tensor grad_output, Tensor self) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU, CUDA: mish_backward
+    MPS: mish_backward_mps
+    CompositeImplicitAutograd: math_mish_backward
+
+- func: sigmoid(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: sigmoid.out
+  variants: function, method
+  dispatch:
+    QuantizedCPU: sigmoid_quantized_cpu
+    MkldnnCPU: mkldnn_sigmoid
+  tags: [core, pointwise]
+
+- func: sigmoid_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: sigmoid.out
+  variants: function, method
+  dispatch:
+    MkldnnCPU: mkldnn_sigmoid_
+  tags: pointwise
+
+- func: sigmoid.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: sigmoid_out
+  tags: pointwise
+
+- func: logit(Tensor self, float? eps=None) -> Tensor
+  variants: function, method
+  dispatch:
+    CPU, CUDA, MTIA: logit
+    MPS: logit_mps
+  tags: pointwise
+
+- func: logit_(Tensor(a!) self, float? eps=None) -> Tensor(a!)
+  variants: function, method
+  dispatch:
+    CPU, CUDA: logit_
+  tags: pointwise
+
+- func: logit.out(Tensor self, float? eps=None, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA: logit_out
+    MPS: logit_out_mps
+  tags: pointwise
+
+- func: sin(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: sin.out
+  variants: function, method
+  dispatch:
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sin_sparse_csr
+    SparseCPU, SparseCUDA, SparseMPS: sin_sparse
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_sin
+  tags: [core, pointwise]
+
+- func: sin_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: sin.out
+  variants: function, method
+  dispatch:
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sin_sparse_csr_
+    SparseCPU, SparseCUDA, SparseMPS: sin_sparse_
+  tags: pointwise
+
+- func: sin.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS, MTIA: sin_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sin_sparse_csr_out
+    SparseCPU, SparseCUDA, SparseMPS: sin_sparse_out
+  tags: pointwise
+
+- func: sinc(Tensor self) -> Tensor
+  structured_delegate: sinc.out
+  variants: function, method
+  tags: pointwise
+
+- func: sinc_(Tensor(a!) self) -> Tensor(a!)
+  structured_delegate: sinc.out
+  variants: function, method
+  tags: pointwise
+
+- func: sinc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: sinc_out
+  tags: pointwise
+
+- func: sinh(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: sinh.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: sinh_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sinh_sparse_csr
+  tags: [core, pointwise]
+
+- func: sinh_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: sinh.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: sinh_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sinh_sparse_csr_
+  tags: pointwise
+
+- func: sinh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: sinh_out
+    SparseCPU, SparseCUDA, SparseMPS: sinh_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sinh_sparse_csr_out
+
+# Returns a copy of this `Variable` that is detached from its autograd graph.
+# This method is OK to call if the `Variable` is a view.
+#
+# NOTE: Previously, if we change the tensor metadata (e.g. sizes / strides /
+# storage / storage_offset) of a tensor created from `detach()`, those metadata
+# in the original tensor will also be updated. However, the new behavior is that
+# those metadata changes to the detached tensor will not update the original tensor
+# anymore, and in the `detach()` function we need to set `allow_tensor_metadata_change_`
+# to false to make such changes explicitly illegal, in order to prevent users from
+# changing metadata of the detached tensor and expecting the original tensor to also
+# be updated.
+  tags: pointwise
+- func: detach(Tensor(a) self) -> Tensor(a)
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: detach
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: detach
+
+# Like `detach()`, but modifies this `Variable` in-place. This method may
+# only be called on non-view `Variable`s. You can use `is_view()` to check
+# this. If this `Variable` is a view, throws an `std::runtime_error()`.
+- func: detach_(Tensor(a!) self) -> Tensor(a!)
+  variants: function, method
+  tags: inplace_view
+  dispatch:
+    CompositeExplicitAutograd: detach_
+
+- func: size.int(Tensor self, int dim) -> int
+  variants: function
+  device_check: NoCheck
+  device_guard: False
+  manual_cpp_binding: True
+
+- func: size.Dimname(Tensor self, Dimname dim) -> int
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+
+- func: sym_size.int(Tensor self, int dim) -> SymInt
+  variants: function
+  device_check: NoCheck
+  device_guard: False
+  tags: core
+  manual_cpp_binding: True
+
+- func: sym_is_contiguous(Tensor self, MemoryFormat memory_format=contiguous_format) -> SymBool
+  variants: function
+  device_check: NoCheck
+  device_guard: False
+  tags: core
+  manual_cpp_binding: True
+
+- func: sym_numel(Tensor self) -> SymInt
+  variants: function
+  device_check: NoCheck
+  device_guard: False
+  tags: core
+  manual_cpp_binding: True
+
+- func: sym_storage_offset(Tensor self) -> SymInt
+  variants: function
+  device_check: NoCheck
+  device_guard: False
+  tags: core
+  manual_cpp_binding: True
+
+- func: slice.Tensor(Tensor(a) self, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor(a)
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: slice
+  tags: core
+
+# NOTE: The implementation of split_with_sizes bypasses the dispatcher to call this; undo
+# that if adding specific implementations here!
+
+- func: slice_backward(Tensor grad_output, SymInt[] input_sizes, int dim, SymInt start, SymInt end, SymInt step) -> Tensor
+  variants: function
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: slice_backward
+  autogen: slice_backward.out
+
+# NB: This op exists to back the implementation of reverse view_funcs for various views (chunk,
+# slice.Tensor, split_with_sizes, et al.). Currently, these are only used during fake-ification
+# of PT2 graph input subclass instances that are views. This means:
+# * This op shouldn't really show up in eager mode (so e.g. XLA shouldn't have to implement it)
+# * This op shouldn't show up in a PT2 graph (so a PT2 backend shouldn't have to implement it)
+# * A subclass will have to implement this to work in PT2 if a subclass view is used as a graph
+#   input AND the view utilizes this op in its inverse. The idea is that slice_inverse() is
+#   easier to implement for a subclass than as_strided()
+- func: slice_inverse(Tensor(a) self, Tensor src, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor(a)
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: slice_inverse_symint
+
+- func: slice_scatter(Tensor self, Tensor src, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: slice_scatter
+  autogen: slice_scatter.out
+  tags: [core, view_copy]
+
+- func: select_scatter(Tensor self, Tensor src, int dim, SymInt index) -> Tensor
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: select_scatter_symint
+  autogen: select_scatter.out
+  tags: core
+
+- func: diagonal_scatter(Tensor self, Tensor src, int offset=0, int dim1=0, int dim2=1) -> Tensor
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: diagonal_scatter
+  autogen: diagonal_scatter.out
+
+- func: as_strided_scatter(Tensor self, Tensor src, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: as_strided_scatter_symint
+  autogen: as_strided_scatter.out
+
+- func: smm(Tensor self, Tensor mat2) -> Tensor
+  variants: function, method
+
+# softmax allows positional dtype, unlike most operators, because kwonly is BC-breaking when loading jit models.
+- func: softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor
+  variants: function, method
+
+- func: softmax.int_out(Tensor self, int dim, ScalarType? dtype=None, *, Tensor(a!) out) -> Tensor(a!)
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: softmax_out
+
+- func: softmax.Dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor
+  variants: function, method
+
+- func: _softmax(Tensor self, int dim, bool half_to_float) -> Tensor
+  structured_delegate: _softmax.out
+  dispatch:
+    MkldnnCPU: mkldnn_softmax
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: softmax_nested
+  tags: core
+
+- func: _softmax.out(Tensor self, int dim, bool half_to_float, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  dispatch:
+    CPU: softmax_cpu_out
+    CUDA: softmax_cuda_out
+    MPS: softmax_mps_out
+
+- func: _softmax_backward_data(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype) -> Tensor
+  structured_delegate: _softmax_backward_data.out
+  dispatch:
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: nested_softmax_backward
+
+- func: _softmax_backward_data.out(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype, *, Tensor(a!) grad_input) -> Tensor(a!)
+  structured: True
+  dispatch:
+    CPU: softmax_backward_cpu_out
+    CUDA: softmax_backward_cuda_out
+    MPS: softmax_backward_mps_out
+
+- func: unsafe_split.Tensor(Tensor self, SymInt split_size, int dim=0) -> Tensor[]
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: unsafe_split
+  autogen: unsafe_split.Tensor_out
+
+- func: split.Tensor(Tensor(a -> *) self, SymInt split_size, int dim=0) -> Tensor(a)[]
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: split
+
+- func: split.sizes(Tensor(a -> *) self, SymInt[] split_size, int dim=0) -> Tensor(a)[]
+  variants: function, method
+  device_guard: False
+  dispatch:
+    CompositeImplicitAutograd: split_symint
+
+- func: unsafe_split_with_sizes(Tensor self, SymInt[] split_sizes, int dim=0) -> Tensor[]
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: unsafe_split_with_sizes
+  autogen: unsafe_split_with_sizes.out
+
+- func: split_with_sizes(Tensor(a -> *) self, SymInt[] split_sizes, int dim=0) -> Tensor(a)[]
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: split_with_sizes
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: split_with_sizes_nested
+  tags: core
+
+- func: hsplit.int(Tensor(a -> *) self, int sections) -> Tensor(a)[]
+  variants: function, method
+
+- func: hsplit.array(Tensor(a -> *) self, int[] indices) -> Tensor(a)[]
+  variants: function, method
+
+- func: vsplit.int(Tensor(a -> *) self, int sections) -> Tensor(a)[]
+  variants: function, method
+
+- func: vsplit.array(Tensor(a -> *) self, int[] indices) -> Tensor(a)[]
+  variants: function, method
+
+- func: dsplit.int(Tensor(a -> *) self, int sections) -> Tensor(a)[]
+  variants: function, method
+
+- func: dsplit.array(Tensor(a -> *) self, int[] indices) -> Tensor(a)[]
+  variants: function, method
+
+- func: squeeze(Tensor(a) self) -> Tensor(a)
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: squeeze
+    QuantizedCPU, QuantizedCUDA: squeeze_quantized
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: squeeze_nested
+
+- func: squeeze.dim(Tensor(a) self, int dim) -> Tensor(a)
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: squeeze
+    QuantizedCPU, QuantizedCUDA: squeeze_quantized
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: squeeze_dim_nested
+  tags: core
+
+- func: squeeze.dimname(Tensor(a) self, Dimname dim) -> Tensor(a)
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+
+
+- func: squeeze.dims(Tensor(a) self, int[] dim) -> Tensor(a)
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: squeeze
+    QuantizedCPU, QuantizedCUDA: squeeze_quantized
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: squeeze_dim_nested
+  tags: core
+
+- func: squeeze_(Tensor(a!) self) -> Tensor(a!)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+  tags: inplace_view
+  dispatch:
+    CompositeExplicitAutograd: squeeze_
+
+- func: squeeze_.dim(Tensor(a!) self, int dim) -> Tensor(a!)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+  tags: inplace_view
+  dispatch:
+    CompositeExplicitAutograd: squeeze_
+
+- func: squeeze_.dims(Tensor(a!) self, int[] dim) -> Tensor(a!)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+  tags: inplace_view
+  dispatch:
+    CompositeExplicitAutograd: squeeze_
+
+- func: squeeze_.dimname(Tensor(a!) self, Dimname dim) -> Tensor(a!)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+  tags: inplace_view
+
+- func: sspaddmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+  variants: function, method
+
+- func: sspaddmm.out(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU: _sspaddmm_out_only_sparse
+    CUDA: _sspaddmm_out_only_sparse_cuda
+    SparseCPU: _sspaddmm_out_cpu
+    SparseCUDA: _sspaddmm_out_cuda
+
+- func: _chunk_cat(Tensor[] tensors, int dim, int num_chunks) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: _chunk_cat
+    CUDA: _chunk_cat_cuda
+
+- func: _chunk_cat.out(Tensor[] tensors, int dim, int num_chunks, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: _chunk_cat_out
+    CUDA: _chunk_cat_out_cuda
+
+- func: stack(Tensor[] tensors, int dim=0) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: stack
+
+- func: stack.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: stack_out
+
+- func: _stack(Tensor[] tensors, int dim=0) -> Tensor
+  dispatch: # match the backends supported by _cat
+    CPU: _stack_cpu
+    CompositeExplicitAutograd: _stack
+
+- func: _stack.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch: # match the backends supported by _cat_out
+    CPU: _stack_out_cpu
+    CompositeExplicitAutograd: _stack_out
+
+- func: hstack(Tensor[] tensors) -> Tensor
+
+- func: hstack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: vstack(Tensor[] tensors) -> Tensor
+
+- func: vstack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: dstack(Tensor[] tensors) -> Tensor
+
+- func: dstack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!)
+
+# Overload without center & pad mode, needed for forward-compatibility
+- func: stft(Tensor self, int n_fft, int? hop_length=None, int? win_length=None, Tensor? window=None, bool normalized=False, bool? onesided=None, bool? return_complex=None, bool? align_to_window=None) -> Tensor
+  variants: function, method
+  cpp_no_default_args: ['hop_length', 'win_length', 'window', 'normalized']
+
+- func: stft.center(Tensor self, int n_fft, int? hop_length=None, int? win_length=None, Tensor? window=None, bool center=True, str pad_mode="reflect", bool normalized=False, bool? onesided=None, bool? return_complex=None, bool? align_to_window=None) -> Tensor
+  variants: function, method
+
+- func: istft(Tensor self, int n_fft, int? hop_length=None, int? win_length=None, Tensor? window=None, bool center=True, bool normalized=False, bool? onesided=None, int? length=None, bool return_complex=False) -> Tensor
+  variants: function, method
+
+- func: stride.int(Tensor self, int dim) -> int
+  variants: function
+  device_check: NoCheck
+  device_guard: False
+  manual_cpp_binding: True
+
+- func: stride.Dimname(Tensor self, Dimname dim) -> int
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+
+- func: sym_stride.int(Tensor self, int dim) -> SymInt
+  variants: function
+  device_check: NoCheck
+  device_guard: False
+  tags: core
+  manual_cpp_binding: True
+
+- func: sum(Tensor self, *, ScalarType? dtype=None) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: sum
+    SparseCPU, SparseCUDA, SparseMeta: sum_coo
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sum_csr
+  autogen: sum.out
+
+- func: sum.dim_IntList(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+  # TODO: Align the signature of sum.dim_IntList and _sparse_csr_sum.dim_dtype
+  structured_delegate: sum.IntList_out
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    NestedTensorCPU: NestedTensor_sum_dim_CPU
+    SparseCPU, SparseCUDA: sum_sparse_coo
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sum_sparse_compressed
+  tags: core
+
+- func: sum.dim_DimnameList(Tensor self, Dimname[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: sum.IntList_out(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA: sum_out
+    MPS: sum_out_mps
+
+- func: sum.DimnameList_out(Tensor self, Dimname[1] dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+
+# TODO: this function will be replaced once nested expand semantics have been settled on
+- func: _nested_sum_backward(Tensor grad, Tensor self, int[1]? dim, bool keepdim=False) -> Tensor
+  dispatch:
+    NestedTensorCPU: _nested_sum_backward_cpu
+
+- func: nansum(Tensor self, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+  variants: function, method
+  dispatch:
+    CPU, CUDA: nansum
+    MPS: nansum_mps
+
+- func: nansum.out(Tensor self, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA: nansum_out
+    MPS: nansum_out_mps
+
+- func: hash_tensor(Tensor self, int[1] dim=[], *, bool keepdim=False, int mode=0) -> Tensor
+  variants: function, method
+  structured_delegate: hash_tensor.out
+
+- func: hash_tensor.out(Tensor self, int[1] dim=[], *, bool keepdim=False, int mode=0, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  dispatch:
+    CPU, CUDA: hash_tensor_out
+
+- func: sum_to_size(Tensor self, SymInt[] size) -> Tensor
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeImplicitAutograd: sum_to_size_symint
+
+- func: sqrt(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: sqrt.out
+  variants: function, method
+  dispatch:
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_sqrt
+    SparseCPU, SparseCUDA, SparseMPS: sqrt_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sqrt_sparse_csr
+  tags: [core, pointwise]
+
+- func: sqrt_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: sqrt.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: sqrt_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sqrt_sparse_csr_
+  tags: pointwise
+
+- func: sqrt.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS, MTIA: sqrt_out
+    SparseCPU, SparseCUDA, SparseMPS: sqrt_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sqrt_sparse_csr_out
+  tags: pointwise
+
+- func: square(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  tags: pointwise
+
+- func: square_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  tags: pointwise
+
+- func: square.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  tags: pointwise
+
+- func: std(Tensor self, bool unbiased=True) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  cpp_no_default_args: ["unbiased"]
+
+- func: std.dim(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  cpp_no_default_args: ["unbiased"]
+
+- func: std.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CPU, CUDA: std
+    MPS: std_mps
+    QuantizedCPU: std_quantized_cpu
+
+- func: std_mean(Tensor self, bool unbiased=True) -> (Tensor, Tensor)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  cpp_no_default_args: ["unbiased"]
+
+- func: std_mean.dim(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False) -> (Tensor, Tensor)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  cpp_no_default_args: ["unbiased"]
+
+- func: std_mean.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> (Tensor, Tensor)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  dispatch:
+    CPU, CUDA: std_mean
+    MPS: std_mean_mps
+  autogen: std_mean.correction_out
+
+- func: std_mean.names_dim(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False) -> (Tensor, Tensor)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  cpp_no_default_args: ["unbiased"]
+
+- func: std_mean.correction_names(Tensor self, Dimname[1] dim, *, Scalar? correction=None, bool keepdim=False) -> (Tensor, Tensor)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+
+- func: std.out(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  cpp_no_default_args: ["unbiased"]
+
+- func: std.correction_out(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA: std_out
+    QuantizedCPU: std_out_quantized_cpu
+
+- func: std.names_dim(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  cpp_no_default_args: ["unbiased"]
+
+- func: std.names_out(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  cpp_no_default_args: ["unbiased"]
+
+- func: std.correction_names(Tensor self, Dimname[1] dim, *, Scalar? correction=None, bool keepdim=False) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: std.correction_names_out(Tensor self, Dimname[1] dim, *, Scalar? correction=None, bool keepdim=False, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+
+- func: prod(Tensor self, *, ScalarType? dtype=None) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CPU, CUDA: prod
+    MPS: prod_mps
+  autogen: prod.out
+  tags: core
+
+- func: prod.dim_int(Tensor self, int dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+  structured_delegate: prod.int_out
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  tags: core
+
+- func: prod.int_out(Tensor self, int dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA: prod_out
+    MPS: prod_out_mps
+
+- func: prod.dim_Dimname(Tensor self, Dimname dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: prod.Dimname_out(Tensor self, Dimname dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+
+- func: t(Tensor(a) self) -> Tensor(a)
+  device_check: NoCheck
+  device_guard: False
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: t
+
+- func: t_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck
+  device_guard: False
+  variants: method
+  tags: inplace_view
+  dispatch:
+    CompositeExplicitAutograd: t_
+
+- func: tan(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: tan.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: tan_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: tan_sparse_csr
+  tags: [core, pointwise]
+
+- func: tan_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: tan.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: tan_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: tan_sparse_csr_
+  tags: pointwise
+
+- func: tan.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: tan_out
+    SparseCPU, SparseCUDA, SparseMPS: tan_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: tan_sparse_csr_out
+  tags: pointwise
+
+- func: tanh(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: tanh.out
+  variants: function, method
+  dispatch:
+    QuantizedCPU: tanh_quantized_cpu
+    MkldnnCPU: mkldnn_tanh
+    SparseCPU, SparseCUDA, SparseMPS: tanh_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: tanh_sparse_csr
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_tanh
+  tags: [core, pointwise]
+
+- func: tanh_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: tanh.out
+  variants: function, method
+  dispatch:
+    MkldnnCPU: mkldnn_tanh_
+    SparseCPU, SparseCUDA, SparseMPS: tanh_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: tanh_sparse_csr_
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_tanh_
+  tags: pointwise
+
+- func: tanh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS, MTIA: tanh_out
+    SparseCPU, SparseCUDA, SparseMPS: tanh_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: tanh_sparse_csr_out
+  tags: pointwise
+
+- func: tensordot(Tensor self, Tensor other, int[] dims_self, int[] dims_other) -> Tensor
+  variants: function
+
+- func: tensordot.out(Tensor self, Tensor other, int[] dims_self, int[] dims_other, *, Tensor(a!) out) -> Tensor(a!)
+  variants: function
+
+# TODO: namespace threshold in 'nn'
+- func: threshold(Tensor self, Scalar threshold, Scalar value) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  structured_delegate: threshold.out
+  dispatch:
+    QuantizedCPU: threshold_quantized_cpu
+  tags: pointwise
+
+- func: threshold_(Tensor(a!) self, Scalar threshold, Scalar value) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  structured_delegate: threshold.out
+
+- func: threshold.out(Tensor self, Scalar threshold, Scalar value, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: threshold_out
+    MPS: threshold_out_mps
+
+- func: threshold_backward.grad_input(Tensor grad_output, Tensor self, Scalar threshold, *, Tensor(a!) grad_input) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: threshold_backward_out
+    MPS: threshold_backward_out_mps
+    SparseCPU, SparseCUDA: threshold_backward_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: threshold_backward_sparse_compressed_out
+
+- func: threshold_backward(Tensor grad_output, Tensor self, Scalar threshold) -> Tensor
+  variants: function
+  structured_delegate: threshold_backward.grad_input
+  dispatch:
+    MkldnnCPU: mkldnn_relu_backward
+    SparseCPU, SparseCUDA: threshold_backward_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: threshold_backward_sparse_compressed
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: threshold_backwards_nested
+  tags: pointwise
+
+- func: tile(Tensor self, SymInt[] dims) -> Tensor
+  variants: function, method
+  dispatch:
+    CompositeImplicitAutograd: tile_symint
+
+- func: transpose.int(Tensor(a) self, int dim0, int dim1) -> Tensor(a)
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: transpose
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: transpose_nested
+
+- func: transpose.Dimname(Tensor(a) self, Dimname dim0, Dimname dim1) -> Tensor(a)
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+
+- func: _mkldnn_transpose(Tensor self, int dim0, int dim1) -> Tensor
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    MkldnnCPU: mkldnn_transpose
+
+- func: transpose_(Tensor(a!) self, int dim0, int dim1) -> Tensor(a!)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+  tags: inplace_view
+  dispatch:
+    CompositeExplicitAutograd: transpose_
+
+- func: _mkldnn_transpose_(Tensor(a!) self, int dim0, int dim1) -> Tensor(a!)
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    MkldnnCPU: mkldnn_transpose_
+  autogen: _mkldnn_transpose.out
+
+- func: one_hot(Tensor self, int num_classes=-1) -> Tensor
+  python_module: nn
+  variants: function
+  tags: dynamic_output_shape
+
+- func: flip(Tensor self, int[] dims) -> Tensor
+  variants: function, method
+  dispatch:
+    CPU, QuantizedCPU, CUDA, QuantizedCUDA: flip
+    MPS: flip_mps
+  autogen: flip.out
+  tags: core
+
+- func: fliplr(Tensor self) -> Tensor
+  variants: function, method
+
+- func: flipud(Tensor self) -> Tensor
+  variants: function, method
+
+- func: roll(Tensor self, SymInt[1] shifts, int[1] dims=[]) -> Tensor
+  variants: function, method
+  dispatch:
+    CPU, MPS: roll
+    CUDA: roll_cuda
+  autogen: roll.out
+
+# default int[] value [0,1] should not add space after comma, since codegen parser uses ', ' to split args
+
+- func: rot90(Tensor self, int k=1, int[] dims=[0,1]) -> Tensor
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: rot90
+  autogen: rot90.out
+
+- func: trapezoid.x(Tensor y, Tensor x, *, int dim=-1) -> Tensor
+
+- func: trapezoid.dx(Tensor y, *, Scalar dx=1, int dim=-1) -> Tensor
+
+- func: trapz.x(Tensor y, Tensor x, *, int dim=-1) -> Tensor
+
+- func: trapz.dx(Tensor y, *, float dx=1, int dim=-1) -> Tensor
+
+# Fused implementation detail for transformers. Adds in-projection bias to QKV and divides Q by sqrt(D/num_heads).
+- func: _transform_bias_rescale_qkv(Tensor qkv, Tensor qkv_bias, int num_heads) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    CPU, NestedTensorCPU: transform_bias_rescale_qkv_cpu
+    CUDA, NestedTensorCUDA: transform_bias_rescale_qkv_cuda
+  autogen: _transform_bias_rescale_qkv.out
+
+- func: _nested_tensor_from_mask(Tensor t, Tensor mask, bool mask_check=True) -> Tensor
+  dispatch:
+    CPU, CUDA: NestedTensor_nested_tensor_from_mask
+  autogen: _nested_tensor_from_mask.out
+
+- func: _nested_tensor_from_mask_left_aligned(Tensor t, Tensor mask) -> bool
+  dispatch:
+    CPU, CUDA: NestedTensor_nested_tensor_from_mask_left_aligned
+
+- func: _nested_from_padded(Tensor padded, Tensor cpu_nested_shape_example, bool fuse_transform_0213=False) -> Tensor
+  device_check: NoCheck # cpu_nested_shape_example will always be on CPU
+  dispatch:
+    CPU: nested_from_padded_generic
+    CUDA: nested_from_padded_cuda
+  autogen: _nested_from_padded.out
+
+# These private functions are temporary. They will be updated/deleted when nested tensors switch to using SymInts for their metadata representation
+- func: _nested_tensor_size(Tensor self) -> Tensor
+  variants: method
+  dispatch:
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: _nested_tensor_size
+  autogen: _nested_tensor_size.out
+
+- func: _nested_tensor_strides(Tensor self) -> Tensor
+  variants: method
+  dispatch:
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: _nested_tensor_strides
+  autogen: _nested_tensor_strides.out
+
+- func: _nested_tensor_storage_offsets(Tensor self) -> Tensor
+  variants: method
+  dispatch:
+    NestedTensorCPU, NestedTensorCUDA, NestedTensorMeta: _nested_tensor_storage_offsets
+  autogen: _nested_tensor_storage_offsets.out
+
+# _nested_from_padded is not usable from Python, so
+# _nested_from_padded_and_nested_example is available for testing.
+- func: _nested_from_padded_and_nested_example(Tensor padded, Tensor nt_example) -> Tensor
+  dispatch:
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_from_padded_and_nested_example
+  autogen: _nested_from_padded_and_nested_example.out
+
+# The input arguments' types to this functions are temporary. When nested tensors switch to using SymInts for their metadata representation
+# this will need to be updated
+- func: _nested_view_from_buffer(Tensor(a) self, Tensor nested_size, Tensor nested_strides, Tensor offsets) -> Tensor(a)
+  variants: function
+  device_check: NoCheck
+  dispatch:
+    CPU, CUDA: _nested_view_from_buffer
+
+- func: _nested_view_from_buffer_copy(Tensor self, Tensor nested_size, Tensor nested_strides, Tensor offsets) -> Tensor
+  variants: function
+  device_check: NoCheck
+  tags: view_copy
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: _nested_view_from_buffer_copy
+  autogen: _nested_view_from_buffer_copy.out
+
+- func: _nested_view_from_jagged(Tensor(a) self, Tensor offsets, Tensor dummy, Tensor? lengths=None, int ragged_idx=1, Tensor? min_seqlen=None, Tensor? max_seqlen=None) -> Tensor(a)
+  variants: function
+  device_check: NoCheck
+  dispatch: {}
+
+- func: _nested_view_from_jagged_copy(Tensor self, Tensor offsets, Tensor dummy, Tensor? lengths=None, int ragged_idx=1, Tensor? min_seqlen=None, Tensor? max_seqlen=None) -> Tensor
+  variants: function
+  device_check: NoCheck
+  tags: view_copy
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: _nested_view_from_jagged_copy
+  autogen: _nested_view_from_jagged_copy.out
+
+- func: _nested_get_values(Tensor(a) self) -> Tensor(a)
+  variants: function
+  device_check: NoCheck
+  dispatch: {}
+
+- func: _nested_get_values_copy(Tensor self) -> Tensor
+  variants: function
+  device_check: NoCheck
+  tags: view_copy
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: _nested_get_values_copy
+  autogen: _nested_get_values_copy.out
+
+- func: _nested_get_offsets(Tensor self) -> Tensor
+  variants: function
+  device_check: NoCheck
+  dispatch: {}
+
+# returns undefined Tensor if no lengths present
+- func: _nested_get_lengths(Tensor self) -> Tensor
+  variants: function
+  device_check: NoCheck
+  dispatch: {}
+
+- func: _nested_get_ragged_idx(Tensor self) -> int
+  variants: function
+  device_check: NoCheck
+  dispatch: {}
+
+- func: _nested_get_min_seqlen(Tensor self) -> Tensor
+  variants: function
+  device_check: NoCheck
+  dispatch: {}
+
+- func: _nested_get_max_seqlen(Tensor self) -> Tensor
+  variants: function
+  device_check: NoCheck
+  dispatch: {}
+
+- func: _nested_get_jagged_dummy(Tensor any) -> Tensor
+  category_override: dummy
+  dispatch: {}
+
+- func: _nested_compute_contiguous_strides_offsets(Tensor nested_size) -> (Tensor, Tensor)
+  variants: function
+  device_check: NoCheck
+  dispatch:
+    CPU, CUDA: _nested_compute_contiguous_strides_offsets
+
+- func: _trilinear(Tensor i1, Tensor i2, Tensor i3, int[] expand1, int[] expand2, int[] expand3, int[] sumdim, int unroll_dim=1) -> Tensor
+  dispatch:
+    # calls unsqueeze
+    CompositeExplicitAutogradNonFunctional: _trilinear
+  autogen: _trilinear.out
+
+- func: triplet_margin_loss(Tensor anchor, Tensor positive, Tensor negative, float margin=1.0, float p=2, float eps=1e-06, bool swap=False, int reduction=Mean) -> Tensor
+
+- func: trunc(Tensor self) -> Tensor
+  structured_delegate: trunc.out
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: trunc_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta: trunc_sparse_csr
+  tags: [core, pointwise]
+
+- func: trunc_(Tensor(a!) self) -> Tensor(a!)
+  structured_delegate: trunc.out
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: trunc_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta: trunc_sparse_csr_
+  tags: pointwise
+
+- func: trunc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MPS: trunc_out
+    SparseCPU, SparseCUDA, SparseMPS: trunc_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta: trunc_sparse_csr_out
+  tags: pointwise
+# Alias for trunc
+
+- func: fix(Tensor self) -> Tensor
+  variants: function, method
+
+- func: fix_(Tensor(a!) self) -> Tensor(a!)
+  variants: function, method
+
+- func: fix.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: type_as(Tensor self, Tensor other) -> Tensor
+  variants: method
+
+- func: _has_compatible_shallow_copy_type(Tensor self, Tensor from) -> bool
+  variants: function
+
+- func: _unique(Tensor self, bool sorted=True, bool return_inverse=False) -> (Tensor, Tensor)
+  variants: function
+  dispatch:
+    CPU: _unique_cpu
+    CUDA: _unique_cuda
+  autogen: _unique.out
+
+- func: unique_dim(Tensor self, int dim, bool sorted=True, bool return_inverse=False, bool return_counts=False) -> (Tensor, Tensor, Tensor)
+  variants: function
+  dispatch:
+    CPU: unique_dim_cpu
+    CUDA: unique_dim_cuda
+  tags: dynamic_output_shape
+  autogen: unique_dim.out
+
+- func: unique_consecutive(Tensor self, bool return_inverse=False, bool return_counts=False, int? dim=None) -> (Tensor, Tensor, Tensor)
+  variants: function
+  dispatch:
+    CPU: unique_consecutive_cpu
+    CUDA: unique_consecutive_cuda
+    MPS: unique_consecutive_mps
+  tags: dynamic_output_shape
+  autogen: unique_consecutive.out
+
+- func: unique_dim_consecutive(Tensor self, int dim, bool return_inverse=False, bool return_counts=False) -> (Tensor, Tensor, Tensor)
+  variants: function
+  dispatch:
+    CPU: unique_dim_consecutive_cpu
+    CUDA: unique_dim_consecutive_cuda
+    MPS: unique_dim_consecutive_mps
+  tags: dynamic_output_shape
+  autogen: unique_dim_consecutive.out
+
+# _unique and _unique_dim are fragile and modifying them easily cause internal break
+# the below operator is a temporary hack for adding return_counts support
+# Please don't rely on these two operators, they will be removed soon
+
+- func: _unique2(Tensor self, bool sorted=True, bool return_inverse=False, bool return_counts=False) -> (Tensor, Tensor, Tensor)
+  variants: function
+  dispatch:
+    CPU: _unique2_cpu
+    CUDA: _unique2_cuda
+    MPS: _unique2_mps
+  tags: dynamic_output_shape
+  autogen: _unique2.out
+
+- func: _unsafe_view(Tensor self, SymInt[] size) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: _unsafe_view
+  autogen: _unsafe_view.out
+
+- func: unsqueeze(Tensor(a) self, int dim) -> Tensor(a)
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: unsqueeze
+    SparseCPU, SparseCUDA: unsqueeze_sparse
+    QuantizedCPU, QuantizedCUDA: unsqueeze_quantized
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: unsqueeze_nested
+  tags: core
+
+- func: unsqueeze_(Tensor(a!) self, int dim) -> Tensor(a!)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+  tags: inplace_view
+  dispatch:
+    CompositeExplicitAutograd: unsqueeze_
+
+- func: vander(Tensor x, int? N=None, bool increasing=False) -> Tensor
+
+- func: var(Tensor self, bool unbiased=True) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  cpp_no_default_args: ["unbiased"]
+
+- func: var.dim(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  tags: core
+  cpp_no_default_args: ["unbiased"]
+
+- func: var.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CPU, CUDA: var
+    MPS: var_mps
+  tags: core
+
+- func: var.out(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  cpp_no_default_args: ["unbiased"]
+
+- func: var.correction_out(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA: var_out
+
+- func: var.names_dim(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  cpp_no_default_args: ["unbiased"]
+
+- func: var.names_out(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  cpp_no_default_args: ["unbiased"]
+
+- func: var.correction_names(Tensor self, Dimname[1] dim, *, Scalar? correction=None, bool keepdim=False) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: var.correction_names_out(Tensor self, Dimname[1] dim, *, Scalar? correction=None, bool keepdim=False, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+
+- func: var_mean(Tensor self, bool unbiased=True) -> (Tensor, Tensor)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  cpp_no_default_args: ["unbiased"]
+
+- func: var_mean.dim(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False) -> (Tensor, Tensor)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  cpp_no_default_args: ["unbiased"]
+
+- func: var_mean.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> (Tensor, Tensor)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  dispatch:
+    CPU, CUDA: var_mean
+    MPS: var_mean_mps
+  autogen: var_mean.correction_out
+
+- func: var_mean.names_dim(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False) -> (Tensor, Tensor)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  cpp_no_default_args: ["unbiased"]
+
+- func: var_mean.correction_names(Tensor self, Dimname[1] dim, *, Scalar? correction=None, bool keepdim=False) -> (Tensor, Tensor)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+
+- func: view_as(Tensor(a) self, Tensor other) -> Tensor(a)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+
+- func: where.self(Tensor condition, Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CPU, CUDA, MPS, MTIA: where
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_where
+  tags: [core, pointwise]
+
+- func: where.self_out(Tensor condition, Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MPS, MTIA: where_self_out
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_where_out
+
+- func: where.ScalarSelf(Tensor condition, Scalar self, Tensor other) -> Tensor
+  variants: function
+
+- func: where.ScalarOther(Tensor condition, Tensor self, Scalar other) -> Tensor
+  variants: function, method
+
+- func: where.Scalar(Tensor condition, Scalar self, Scalar other) -> Tensor
+  variants: function
+
+- func: where(Tensor condition) -> Tensor[]
+  device_check: NoCheck   # TensorIterator
+  variants: function
+
+- func: norm_except_dim(Tensor v, int pow=2, int dim=0) -> Tensor
+  variants: function
+
+# VariableType::_weight_norm does not want to be given a gap in the autograd graph,
+# so we don't define "dispatch" variants for it.
+- func: _weight_norm(Tensor v, Tensor g, int dim=0) -> Tensor
+  variants: function
+
+- func: _weight_norm_interface(Tensor v, Tensor g, int dim=0) -> (Tensor, Tensor)
+  variants: function
+  dispatch:
+    CPU: weight_norm_cpu
+    CUDA: weight_norm_cuda
+    MPS: weight_norm_mps
+  autogen: _weight_norm_interface.out
+
+- func: _weight_norm_interface_backward(Tensor grad_w, Tensor saved_v, Tensor saved_g, Tensor saved_norms, int dim) -> (Tensor, Tensor)
+  variants: function
+  dispatch:
+    CPU: weight_norm_backward_cpu
+    CUDA: weight_norm_backward_cuda
+    MPS: weight_norm_backward_mps
+  autogen: _weight_norm_interface_backward.out
+
+- func: _weight_norm_differentiable_backward(Tensor grad_w, Tensor saved_v, Tensor saved_g, Tensor saved_norms, int dim) -> (Tensor, Tensor)
+  variants: function
+
+- func: zeros.names(int[] size, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: zeros
+  autogen: zeros.names_out
+
+- func: _efficientzerotensor(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CPU: _efficientzerotensor
+    CUDA: _efficientzerotensor_cuda
+    MPS: _efficientzerotensor_mps
+    Meta: _efficientzerotensor_meta_symint
+  autogen: _efficientzerotensor.out
+
+- func: zeros(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: zeros_symint
+
+- func: zeros.out(SymInt[] size, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: zeros_out
+    SparseCPU, SparseCUDA, SparseMeta: zeros_sparse_out
+
+- func: zeros_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+  dispatch:
+    # NB: Although this composite mutates on the inside, it is
+    # non-differentiable so NonFunctional doesn't apply
+    CompositeExplicitAutograd, CompositeImplicitAutogradNestedTensor: zeros_like
+  autogen: zeros_like.out
+
+- func: _standard_gamma_grad(Tensor self, Tensor output) -> Tensor
+  variants: function
+  dispatch:
+    CPU: _standard_gamma_grad_cpu
+    CUDA: _standard_gamma_grad_cuda
+  autogen: _standard_gamma_grad.out
+
+- func: _standard_gamma(Tensor self, Generator? generator=None) -> Tensor
+  variants: function
+  dispatch:
+    CPU: _s_gamma_cpu
+    CUDA: _s_gamma_cuda
+  tags: nondeterministic_seeded
+  autogen: _standard_gamma.out
+
+- func: _dirichlet_grad(Tensor x, Tensor alpha, Tensor total) -> Tensor
+  dispatch:
+    CPU: _dirichlet_grad_cpu
+    CUDA: _dirichlet_grad_cuda
+  autogen: _dirichlet_grad.out
+
+- func: _sample_dirichlet(Tensor self, Generator? generator=None) -> Tensor
+  tags: nondeterministic_seeded
+  variants: function
+  dispatch:
+    CPU: _s_dirichlet_cpu
+    CUDA: _s_dirichlet_cuda
+  autogen: _sample_dirichlet.out
+
+- func: poisson(Tensor self, Generator? generator=None) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU: _s_poisson_cpu
+    CUDA: _s_poisson_cuda
+  tags: nondeterministic_seeded
+  autogen: poisson.out
+
+- func: binomial(Tensor count, Tensor prob, Generator? generator=None) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU: _s_binomial_cpu
+    CUDA: _s_binomial_cuda
+  tags: nondeterministic_seeded
+  autogen: binomial.out
+
+# When more variants get ported to native, this dispatch will get more
+# complicated
+
+- func: native_norm(Tensor self, Scalar p=2) -> Tensor
+  dispatch:
+    SparseCPU, SparseCUDA: norm_sparse
+  autogen: native_norm.out
+
+- func: native_norm.ScalarOpt_dim_dtype(Tensor self, Scalar? p, int[1] dim, bool keepdim, ScalarType? dtype) -> Tensor
+  dispatch:
+    SparseCPU, SparseCUDA: norm_sparse
+  autogen: native_norm.ScalarOpt_dim_dtype_out
+
+- func: _batch_norm_with_update(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, float momentum, float eps) -> (Tensor, Tensor, Tensor, Tensor)
+  dispatch:
+    CPU: _batch_norm_with_update_cpu
+    CUDA: _batch_norm_with_update_cuda
+    MPS: _batch_norm_with_update_mps
+    MkldnnCPU: _batch_norm_with_update_mkldnn
+  autogen: _batch_norm_with_update_functional
+
+- func: _batch_norm_with_update.out(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, float momentum, float eps, *, Tensor(d!) out, Tensor(e!) save_mean, Tensor(f!) save_invstd, Tensor(g!) reserve) -> (Tensor(d!), Tensor(e!), Tensor(f!), Tensor(g!))
+  dispatch:
+    CPU: _batch_norm_with_update_cpu_out
+    CUDA: _batch_norm_with_update_cuda_out
+    MPS: _batch_norm_with_update_mps_out
+
+- func: _batch_norm_no_update(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, float momentum, float eps) -> (Tensor, Tensor, Tensor, Tensor)
+  dispatch:
+    CompositeExplicitAutograd: _batch_norm_no_update
+  autogen: _batch_norm_no_update.out
+
+- func: batch_norm_backward(Tensor grad_out, Tensor input, Tensor weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var, bool update, float eps, bool[3] output_mask, Tensor reserve) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    CPU: _new_batch_norm_backward_cpu
+    CUDA: _new_batch_norm_backward_cuda
+    MPS: _new_batch_norm_backward_mps
+    MkldnnCPU: _new_batch_norm_backward_mkldnn
+
+# TODO: reduce signatures down to one when optional args is available
+- func: _sparse_sum(Tensor self) -> Tensor
+
+- func: _sparse_sum.dtype(Tensor self, *, ScalarType dtype) -> Tensor
+
+- func: _sparse_sum.dim(Tensor self, int[1] dim) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: _sparse_sum
+  autogen: _sparse_sum.dim_out
+
+- func: _sparse_sum.dim_dtype(Tensor self, int[1] dim, *, ScalarType dtype) -> Tensor
+
+- func: _sparse_sum_backward(Tensor grad, Tensor self, int[] dim) -> Tensor
+  dispatch:
+    SparseCPU: _sparse_sum_backward_cpu
+    SparseCUDA: _sparse_sum_backward_cuda
+  autogen: _sparse_sum_backward.out
+
+- func: _sparse_csr_sum.dim_dtype(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+  dispatch:
+    SparseCsrCPU: _sparse_csr_sum_cpu
+    SparseCsrCUDA: _sparse_csr_sum_cuda
+  autogen: _sparse_csr_sum.dim_dtype_out
+
+- func: _sparse_csr_prod.dim_dtype(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+  dispatch:
+    SparseCsrCPU: _sparse_csr_prod_cpu
+    SparseCsrCUDA: _sparse_csr_prod_cuda
+  autogen: _sparse_csr_prod.dim_dtype_out
+
+- func: _sparse_softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor
+  python_module: sparse
+  variants: function
+
+- func: _sparse_softmax.Dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor
+  python_module: sparse
+  variants: function
+
+- func: _sparse_softmax(Tensor self, int dim, bool half_to_float) -> Tensor
+  python_module: sparse
+  dispatch:
+    SparseCPU: softmax_sparse_cpu
+    SparseCUDA: softmax_sparse_cuda
+  autogen: _sparse_softmax.out
+
+- func: _sparse_softmax_backward_data(Tensor grad_output, Tensor output, int dim, Tensor self) -> Tensor
+  dispatch:
+    SparseCPU: softmax_backward_sparse_cpu
+    SparseCUDA: softmax_backward_sparse_cuda
+  autogen: _sparse_softmax_backward_data.out
+
+- func: _sparse_log_softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor
+  python_module: sparse
+  variants: function
+
+- func: _sparse_log_softmax.Dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor
+  python_module: sparse
+  variants: function
+
+- func: _sparse_log_softmax(Tensor self, int dim, bool half_to_float) -> Tensor
+  python_module: sparse
+  dispatch:
+    SparseCPU: log_softmax_sparse_cpu
+    SparseCUDA: log_softmax_sparse_cuda
+  autogen: _sparse_log_softmax.out
+
+- func: _sparse_log_softmax_backward_data(Tensor grad_output, Tensor output, int dim, Tensor self) -> Tensor
+  dispatch:
+    SparseCPU: log_softmax_backward_sparse_cpu
+    SparseCUDA: log_softmax_backward_sparse_cuda
+  autogen: _sparse_log_softmax_backward_data.out
+
+- func: _spdiags(Tensor diagonals, Tensor offsets, int[] shape, Layout? layout=None) -> Tensor
+  python_module: sparse
+  dispatch:
+    CPU: spdiags
+  autogen: _spdiags.out
+
+- func: norm.ScalarOpt_dtype(Tensor self, Scalar? p, *, ScalarType dtype) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: norm
+  autogen: norm.ScalarOpt_dtype_out
+
+- func: norm.Scalar(Tensor self, Scalar p=2) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: norm
+  autogen: norm.Scalar_out
+
+- func: norm.ScalarOpt_dim_dtype(Tensor self, Scalar? p, int[1] dim, bool keepdim, *, ScalarType dtype) -> Tensor
+  structured_delegate: norm.dtype_out
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA: sparse_dtype_norm
+
+- func: norm.ScalarOpt_dim(Tensor self, Scalar? p, int[1] dim, bool keepdim=False) -> Tensor
+  structured_delegate: norm.out
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA: sparse_norm
+
+- func: norm.dtype_out(Tensor self, Scalar? p, int[1] dim, bool keepdim, *, ScalarType dtype, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA: norm_dtype_out
+    MPS: norm_dtype_out_mps
+
+- func: norm.out(Tensor self, Scalar? p, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA: norm_out
+    MPS: norm_out_mps
+
+# These four redispatch in their implementation, so OK to be CompositeImplicitAutograd
+- func: norm.names_ScalarOpt_dim_dtype(Tensor self, Scalar? p, Dimname[1] dim, bool keepdim, *, ScalarType dtype) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: norm.names_ScalarOpt_dim(Tensor self, Scalar? p, Dimname[1] dim, bool keepdim=False) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: norm.names_dtype_out(Tensor self, Scalar? p, Dimname[1] dim, bool keepdim, *, ScalarType dtype, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+
+- func: norm.names_out(Tensor self, Scalar? p, Dimname[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+
+- func: frexp.Tensor(Tensor self) -> (Tensor mantissa, Tensor exponent)
+  variants: method, function
+  dispatch:
+    CompositeExplicitAutograd: frexp
+  tags: pointwise
+
+- func: frexp.Tensor_out(Tensor self, *, Tensor(a!) mantissa, Tensor(b!) exponent) -> (Tensor(a!) mantissa, Tensor(b!) exponent)
+  dispatch:
+    CPU, CUDA: frexp_out
+  tags: pointwise
+
+# Deprecated (v.1.12)
+- func: frobenius_norm.dim(Tensor self, int[1] dim, bool keepdim=False) -> Tensor
+  variants: function
+
+# Deprecated (v.1.12)
+- func: frobenius_norm.out(Tensor self, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  variants: function
+
+# Deprecated (v.1.12)
+- func: nuclear_norm(Tensor self, bool keepdim=False) -> Tensor
+  variants: function
+
+# Deprecated (v.1.12)
+- func: nuclear_norm.out(Tensor self, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  variants: function
+
+# Deprecated (v.1.12)
+- func: nuclear_norm.dim(Tensor self, int[2] dim, bool keepdim=False) -> Tensor
+  variants: function
+
+# Deprecated (v.1.12)
+- func: nuclear_norm.dim_out(Tensor self, int[2] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  variants: function
+
+- func: clone(Tensor self, *, MemoryFormat? memory_format=None) -> Tensor
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: clone
+    SparseCPU, SparseCUDA, SparseMPS: clone_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: clone_sparse_compressed
+    MkldnnCPU: mkldnn_clone
+    QuantizedCPU, QuantizedCUDA: quantized_clone
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: clone_nested
+  autogen: clone.out
+  tags: [core, pointwise]
+
+- func: positive(Tensor(a) self) -> Tensor(a)
+  variants: function, method
+  tags: pointwise
+
+- func: resize_as_(Tensor(a!) self, Tensor the_template, *, MemoryFormat? memory_format=None) -> Tensor(a!)
+  use_const_ref_for_mutable_tensors: True
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: resize_as_
+  autogen: resize_as, resize_as.out
+  tags: inplace_view
+
+- func: resize_as_sparse_(Tensor(a!) self, Tensor the_template) -> Tensor(a!)
+  use_const_ref_for_mutable_tensors: True
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA: resize_as_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: resize_as_sparse_compressed_
+  autogen: resize_as_sparse, resize_as_sparse.out
+
+- func: zero_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    CPU, CUDA: zero_
+    MPS: zero_mps_
+    Meta: zero_meta_
+    SparseCPU, SparseCUDA, SparseMPS, SparseMeta: zero_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: zero_sparse_csr_
+    MkldnnCPU: mkldnn_zero_
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: zero_nested_
+  autogen: zero, zero.out
+
+- func: sub.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: sub_out
+    MPS: sub_out_mps
+    MTIA: sub_out_mtia
+    SparseCPU, SparseCUDA: sub_out_sparse
+  tags: pointwise
+
+- func: sub.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  structured_delegate: sub.out
+  dispatch:
+    SparseCPU, SparseCUDA: sub_sparse
+    ZeroTensor: sub_zerotensor
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_sub_Tensor
+  tags: [core, pointwise]
+
+- func: sub_.Tensor(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  structured_delegate: sub.out
+  dispatch:
+    SparseCPU, SparseCUDA: sub_sparse_
+  tags: pointwise
+# For C++ only, until we have conversion from C++ numbers to Tensor
+
+- func: sub.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: sub
+  tags: [core, pointwise]
+
+- func: sub_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: sub_
+  autogen: sub.Scalar_out
+  tags: pointwise
+# subtract, alias for sub
+
+- func: subtract.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+
+- func: subtract.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor
+  variants: function, method
+
+- func: subtract_.Tensor(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!)
+  variants: method
+
+# For C++ only, until we have conversion from C++ numbers to Tensor
+- func: subtract.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor
+  variants: function, method
+
+- func: subtract_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!)
+  variants: method
+
+- func: rsub.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  dispatch:
+    CPU, CUDA, MPS, MTIA: rsub
+  autogen: rsub.Tensor_out
+
+- func: heaviside.out(Tensor self, Tensor values, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA: heaviside_out
+  tags: pointwise
+
+- func: heaviside(Tensor self, Tensor values) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  structured_delegate: heaviside.out
+  tags: pointwise
+
+- func: heaviside_(Tensor(a!) self, Tensor values) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  structured_delegate: heaviside.out
+
+# For C++ only, until we have conversion from C++ numbers to Tensor
+- func: rsub.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: rsub
+  autogen: rsub.Scalar_out
+
+# Functionally the same as addmm, but we give it a different derivative formula
+# that doesn't propagate gradients to non-present entries on sparse.
+  tags: pointwise
+- func: _sparse_addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+  python_module: sparse
+  dispatch:
+    CompositeExplicitAutograd: _sparse_addmm
+  autogen: _sparse_addmm.out
+
+- func: sparse_sampled_addmm.out(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+  python_module: sparse
+  dispatch:
+    SparseCsrCUDA: sparse_sampled_addmm_out_sparse_csr_cuda
+    SparseCsrCPU: sparse_sampled_addmm_out_sparse_csr_cpu
+
+- func: sparse_sampled_addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+  python_module: sparse
+  dispatch:
+    SparseCsrCUDA: sparse_sampled_addmm_sparse_csr_cuda
+    SparseCsrCPU: sparse_sampled_addmm_sparse_csr_cpu
+
+- func: _sparse_mm_reduce_impl(Tensor self, Tensor other, str reduce) -> (Tensor, Tensor)
+  python_module: sparse
+  dispatch:
+    SparseCsrCPU: _sparse_mm_reduce_impl_sparse_csr_cpu
+
+- func: _sparse_mm_reduce_impl_backward(Tensor self, Tensor grad_out, Tensor weight, str reduce, Tensor arg_out, bool[2] output_mask) -> (Tensor, Tensor)
+  python_module: sparse
+  dispatch:
+    SparseCsrCPU: _sparse_mm_reduce_impl_backward_sparse_csr_cpu
+
+- func: addmm.out(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  dispatch:
+    CPU: addmm_out_cpu
+    CUDA: addmm_out_cuda
+    MPS: addmm_out_mps
+    XPU: addmm_out_xpu
+    MTIA: addmm_out_mtia
+    SparseCPU: addmm_out_sparse_dense_cpu
+    SparseCUDA: addmm_out_sparse_dense_cuda
+    SparseCsrCPU: addmm_out_sparse_compressed_cpu
+    SparseCsrCUDA: addmm_out_sparse_compressed_cuda
+
+- func: addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+  structured_delegate: addmm.out
+  variants: function, method
+  dispatch:
+    SparseCPU: addmm_sparse_dense_cpu
+    SparseCUDA: addmm_sparse_dense_cuda
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: addmm_sparse_compressed_dense
+  tags: core
+
+- func: addmm.dtype(Tensor self, Tensor mat1, Tensor mat2, ScalarType out_dtype, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+  dispatch:
+    CUDA: _addmm_dtype_cuda
+
+- func: addmm.dtype_out(Tensor self, Tensor mat1, Tensor mat2, ScalarType out_dtype, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CUDA: _addmm_dtype_out_cuda
+
+- func: addmm_(Tensor(a!) self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!)
+  structured_delegate: addmm.out
+  variants: method
+  dispatch:
+    # Warning!  For whatever reason, the inplace sparse addmm is NON
+    # broadcasting
+    SparseCPU: s_addmm_sparse_dense_cpu_
+    SparseCUDA: s_addmm_sparse_dense_cuda_
+
+- func: _addmm_activation.out(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, bool use_gelu=False, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  dispatch:
+    CPU: addmm_activation_out_cpu
+    CUDA: addmm_activation_out_cuda
+    XPU: addmm_activation_out_xpu
+
+- func: _addmm_activation(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, bool use_gelu=False) -> Tensor
+  structured_delegate: _addmm_activation.out
+  variants: function, method
+
+- func: _scaled_mm(Tensor self, Tensor mat2, Tensor scale_a, Tensor scale_b, Tensor? bias=None, Tensor? scale_result=None, ScalarType? out_dtype=None, bool use_fast_accum=False) -> Tensor
+  variants: function
+  dispatch:
+    CPU: _scaled_mm_cpu
+    CUDA: _scaled_mm_cuda
+  tags: needs_exact_strides
+
+- func: _scaled_mm.out(Tensor self, Tensor mat2, Tensor scale_a, Tensor scale_b, Tensor? bias=None, Tensor? scale_result=None, ScalarType? out_dtype=None, bool use_fast_accum=False, *, Tensor(a!) out) -> Tensor(a!)
+  variants: function
+  dispatch:
+    CPU: _scaled_mm_out_cpu
+    CUDA: _scaled_mm_out_cuda
+  tags: needs_exact_strides
+
+
+- func: _scaled_grouped_mm(Tensor self, Tensor mat2, Tensor scale_a, Tensor scale_b, Tensor? offs=None, Tensor? bias=None, Tensor? scale_result=None, ScalarType? out_dtype=None, bool use_fast_accum=False) -> Tensor
+  variants: function
+  dispatch:
+    CUDA: _scaled_grouped_mm_cuda
+  tags: needs_exact_strides
+
+- func: _grouped_mm(Tensor self, Tensor mat2, Tensor? offs=None, Tensor? bias=None, ScalarType? out_dtype=None) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: _grouped_mm
+    CUDA: _grouped_mm_cuda
+
+# NOTE [ Sparse: autograd and API ]
+#
+#
+# Sparse Tensor Constructors
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~
+#
+# The API entry points to sparse tensor construction should be
+# `sparse_coo tensor` and `_sparse_coo_tensor_unsafe`. Depending on whether the
+# indices and values tensors are given, they eventually dispatch to either
+# `sparse_coo_tensor_with_dims` or `sparse_coo_tensor_with_dims_and_tensors`.
+#
+# The autograd support for ctor is implement on `sparse_coo_tensor_with_dims_and_tensors`.
+#
+# The API methods `sparse_coo tensor` and `_sparse_coo_tensor_unsafe`
+# **must not** have specific type dispatches because otherwise codegen will
+# consider them as abstract methods (see Note [Abstract ATen methods]), dispatch
+# using **Tensor** type, and thus lose autograd tracking on the actual method
+# they dispatch to, e.g., `sparse_coo_tensor_with_dims_and_tensors`.
+#
+#
+# Sparse Methods API Design
+# ~~~~~~~~~~~~~~~~~~~~~~~~~
+#
+# Goals: 1. Flexible API for users to write custom sparse ops
+#        2. ctor and member accessor with autograd support
+#
+# To achieve 1, we need to provide a set of *dangerous* APIs (dangerous in the
+# sense that misusing them will break sparse tensor invariant and may out in
+# unexpected behavior, e.g., crash). These methods are all prefixed with
+# underscore "_" to indicate that they should be used with care. We provide:
+#
+#   + `_indices()`: returns the *raw* indices within the sparse tensor (not just
+#                   sharing storage). Any inplace operation will change the
+#                   actual indices, including t_, set_, as_strided_, resize_,
+#                   etc.
+#   + `_values()`: returns the *raw* values within the sparse tensor. Similar
+#                  semantics as `_indices()`
+#   + `_nnz()`: returns the number of non-zero entries. This will always be
+#               determined by the shapes of indices and values.
+#   + `_coalesced_(bool)`: inplace sets whether the tensor is coalesced, and
+#                          returns itself.
+#
+# These methods are very useful in writing new operations, e.g., a custom
+# autograd Function.
+#
+# We also provide other public *safe* APIs:
+#   + `indices()`: returns a **view** of the indices tensor if the sparse tensor
+#                  is **coalesced**.
+#   + `values()`: returns a **view** of the values tensor if the containing
+#                 sparse tensor is **coalesced**.
+#   + `sparse_dim()`: number of sparse dimensions
+#   + `dense_dim()`: number of dense dimensions
+#   + `is_coalesced()`: whether the sparse tensor is coalesced
+#
+# `_indices()` and `_values()` should returns the raw indices and values dense
+# tensors within a sparse tensor. They can be quite unsafe with inplace
+# operations like `t_()`, and exposes uncoalesced indices and values. The public
+# recommended API is `indices()` and `values()`, both of which first check that
+# the tensor is coalesced and return views on those tensors.
+#
+#
+# Autograd Support
+# ~~~~~~~~~~~~~~~~
+#
+# Autograd is supported on `values()` and sparse tensor ctor with indices and
+# values tensors. E.g., `torch.sparse_coo_tensor(i, v).values().sum()` is
+# differentiable w.r.t. `v`.
+#
+# NB: The `values()` and `_values()` operators are special in that they are
+# layout-aware, i.e., the output depends not just on the data it represents, but
+# also on the input layout details (in this case, the `indices` tensor). See
+# NOTE [ as_strided Backward and layout-aware/agnostic autograd ] in Functions.cpp
+# for discussion on layout-aware vs layout-agnostic autograd. Since PyTorch ops
+# operate in the layout-agnostic mode, similar to `as_strided`, backward of
+# these two operators need to consider them in a layout-agnostic way:
+#   + `values()`:
+#     Input is coalesced.
+#     We just pretend having `input.indices()` as an additional argument
+#     `input_indices`, then forward is similar to
+#     `input.to(kStrided).index_select(input_indices)` regardless of the layout.
+#     Note that `values()` normally is layout-aware even if we constrain
+#     ourselves on sparse inputs since it may include all zeros values entries
+#     as "present" entries.
+#   + `_values()`:
+#     Input may be uncoalesced.
+#     It is not straightforward to construct a layout-agnostic version because
+#     duplicate indices entries may exist and additional parameterization is
+#     needed to distribute the value into different values entries. Furthermore,
+#     this op is intended to provide ways to write custom sparse ops, rather
+#     than being used in autograd graph, so it is marked as *non-differentiable*
+#     in derivatives.yaml.
+#
+# Before reading the following, see NOTE [ Autograd Variable Views ] in
+# variable.h for details on views that are tracked by autograd, and views that
+# are not.
+#
+# Moreover, these methods return tensors that share storage with inputs, so we
+# mark these methods as view ops to support autograd history tracking.
+# The sparse tensor ctor output should technically be view of both input indices
+# and values tensors, but currently we only support setting as view of a single
+# Variable, so it is only view of the values tensor.
+# TODO: clone indices in sparse tensor ctor.
+#
+# For other methods that return outputs that share storage with inputs, i.e.,
+# `indices()` and `_indices()`. We mark their outputs as non-differentiable, so
+# the view relation is not tracked by autograd, but the version counter is still
+# shared. In other words, their outputs are non-differentiable views of the
+# sparse tensor.
+# FIXME: would be nicer if TensorOptions was optional based; not adding default arguments for options given
+# the default would never make sense.
+
+- func: _sparse_compressed_tensor_with_dims(int nnz, int dense_dim, int[] size, int[] blocksize, ScalarType index_dtype, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: sparse_compressed_tensor_with_dims
+
+- func: sparse_compressed_tensor.comp_plain_value_size(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: sparse_compressed_tensor
+
+- func: sparse_csr_tensor.crow_col_value_size(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+- func: sparse_csc_tensor.ccol_row_value_size(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+- func: sparse_bsr_tensor.crow_col_value_size(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+- func: sparse_bsc_tensor.ccol_row_value_size(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+
+- func: sparse_compressed_tensor.comp_plain_value(Tensor compressed_indices, Tensor plain_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: sparse_compressed_tensor
+- func: sparse_csr_tensor.crow_col_value(Tensor crow_indices, Tensor col_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+- func: sparse_csc_tensor.ccol_row_value(Tensor ccol_indices, Tensor row_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+- func: sparse_bsr_tensor.crow_col_value(Tensor crow_indices, Tensor col_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+- func: sparse_bsc_tensor.ccol_row_value(Tensor ccol_indices, Tensor row_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+
+- func: _sparse_compressed_tensor_unsafe(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeImplicitAutograd: _sparse_compressed_tensor_unsafe_symint
+
+- func: _sparse_csr_tensor_unsafe(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+- func: _sparse_csc_tensor_unsafe(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+- func: _sparse_bsr_tensor_unsafe(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+- func: _sparse_bsc_tensor_unsafe(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+
+- func: sparse_coo_tensor.size(int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: sparse_coo_tensor
+  autogen: sparse_coo_tensor.size_out
+
+- func: sparse_coo_tensor.indices(Tensor indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool? is_coalesced=None) -> Tensor
+
+- func: sparse_coo_tensor.indices_size(Tensor indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool? is_coalesced=None) -> Tensor
+
+- func: _sparse_coo_tensor_unsafe(Tensor indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool? is_coalesced=None) -> Tensor
+  dispatch:
+    CompositeImplicitAutograd: _sparse_coo_tensor_unsafe_symint
+
+- func: _validate_sparse_coo_tensor_args(Tensor indices, Tensor values, int[] size, bool? is_coalesced=None, bool? check_pinning=None) -> ()
+
+- func: _validate_sparse_compressed_tensor_args(Tensor compressed_indices, Tensor plain_indices, Tensor values, int[] size, Layout layout, bool? check_pinning=None) -> ()
+- func: _validate_sparse_csr_tensor_args(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size, bool? check_pinning=None) -> ()
+- func: _validate_sparse_csc_tensor_args(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, bool? check_pinning=None) -> ()
+- func: _validate_sparse_bsr_tensor_args(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size, bool? check_pinning=None) -> ()
+- func: _validate_sparse_bsc_tensor_args(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, bool? check_pinning=None) -> ()
+
+- func: _sparse_coo_tensor_with_dims(int sparse_dim, int dense_dim, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMeta, SparseMPS, Meta: new_with_dims_sparse
+  autogen: _sparse_coo_tensor_with_dims.out
+
+- func: _sparse_coo_tensor_with_dims_and_tensors(int sparse_dim, int dense_dim, SymInt[] size, Tensor indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False, bool? is_coalesced=None) -> Tensor
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMeta, SparseMPS, Meta: new_with_dims_and_tensor_sparse_symint
+  autogen: _sparse_coo_tensor_with_dims_and_tensors.out
+
+- func: sparse_resize_(Tensor(a!) self, int[] size, int sparse_dim, int dense_dim) -> Tensor(a!)
+  use_const_ref_for_mutable_tensors: True
+  variants: method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS, SparseMeta: sparse_resize_
+  autogen: sparse_resize, sparse_resize.out
+
+- func: sparse_resize_and_clear_(Tensor(a!) self, int[] size, int sparse_dim, int dense_dim) -> Tensor(a!)
+  use_const_ref_for_mutable_tensors: True
+  variants: method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS, SparseMeta: sparse_resize_and_clear_
+  autogen: sparse_resize_and_clear, sparse_resize_and_clear.out
+
+- func: sparse_mask(Tensor self, Tensor mask) -> Tensor
+  variants: method
+  dispatch:
+    SparseCPU, SparseCUDA: sparse_mask
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sparse_mask_sparse_compressed
+  autogen: sparse_mask.out
+
+- func: _sparse_mask_projection(Tensor self, Tensor mask, bool accumulate_matches=False) -> Tensor
+  variants: method
+  dispatch:
+    SparseCPU, SparseCUDA: sparse_mask_projection
+  autogen: _sparse_mask_projection.out
+
+- func: _to_cpu(Tensor[] tensors) -> Tensor[]
+  variants: function
+
+- func: to_dense(Tensor self, ScalarType? dtype=None, *, bool? masked_grad=None) -> Tensor
+  variants: method
+
+# Special case of to_dense with custom derivative
+- func: _to_dense(Tensor self, ScalarType? dtype=None, bool? masked_grad=None) -> Tensor
+  variants: method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: sparse_to_dense
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta: sparse_compressed_to_dense
+    MkldnnCPU: mkldnn_to_dense
+  autogen: _to_dense.out
+
+- func: to_dense_backward(Tensor grad, Tensor input, bool? masked_grad=None) -> Tensor
+
+- func: sparse_dim(Tensor self) -> int
+  variants: method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS, SparseMeta: sparse_dim_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta: sparse_dim_sparse_csr
+    CompositeExplicitAutograd: sparse_dim_default
+  device_check: NoCheck
+  device_guard: False
+
+# legacy method
+- func: _dimI(Tensor self) -> int
+  variants: method
+  dispatch:
+    SparseCPU, SparseCUDA: sparse_dim_sparse
+  device_check: NoCheck
+  device_guard: False
+
+- func: dense_dim(Tensor self) -> int
+  variants: method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS, SparseMeta: dense_dim_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta: dense_dim_sparse_csr
+    CompositeExplicitAutograd: dense_dim_default
+  device_check: NoCheck
+  device_guard: False
+
+# legacy method
+- func: _dimV(Tensor self) -> int
+  variants: method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMeta: dense_dim_sparse
+  device_check: NoCheck
+  device_guard: False
+
+- func: _nnz(Tensor self) -> int
+  variants: method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS, SparseMeta: _nnz_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta: _nnz_sparse_csr
+  device_check: NoCheck
+  device_guard: False
+
+# NOTE: [ coalesce autograd ]
+# coalesce returns self directly for already coalesced sparse tensors.
+# This means coalesce cannot have a derivative registered, otherwise it creates
+# circular references in the autograd graph (see gh-52874).
+# Instead, the derivative is registered on the slow-path "_coalesce"
+- func: coalesce(Tensor(a) self) -> Tensor(a)
+  variants: method
+
+- func: _coalesce(Tensor self) -> Tensor
+  dispatch:
+    SparseCPU: _coalesce_sparse_cpu
+    SparseCUDA: _coalesce_sparse_cuda
+    SparseMPS: _coalesce_sparse_mps
+  autogen: _coalesce.out
+
+- func: is_coalesced(Tensor self) -> bool
+  variants: method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS, SparseMeta: is_coalesced_sparse
+    CompositeExplicitAutograd: is_coalesced_default
+  device_check: NoCheck
+  device_guard: False
+
+- func: _indices(Tensor(a) self) -> Tensor(a)
+  variants: method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS, SparseMeta: _indices_sparse
+  device_check: NoCheck
+  device_guard: False
+
+- func: _values(Tensor(a) self) -> Tensor(a)
+  variants: method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS, SparseMeta: _values_sparse
+  device_check: NoCheck
+  device_guard: False
+
+# This method doesn't do any check but only directly sets the flag. So it can be
+# a bit unsafe. Similar to _indices and _values, this is useful for implementing
+# custom sparse operations in Python/C++ extension.
+- func: _coalesced_(Tensor(a!) self, bool coalesced) -> Tensor(a!)
+  variants: method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS, SparseMeta: _coalesced_sparse_
+  device_check: NoCheck
+  device_guard: False
+  autogen: _coalesced, _coalesced.out
+
+- func: indices(Tensor(a) self) -> Tensor(a)
+  variants: method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS, SparseMeta: indices_sparse
+    CompositeExplicitAutograd: indices_default
+  device_check: NoCheck
+  device_guard: False
+
+- func: values(Tensor(a) self) -> Tensor(a)
+  variants: method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS, SparseMeta: values_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: values_sparse_csr
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: values_nested
+    CompositeExplicitAutograd: values_default
+  device_check: NoCheck
+  device_guard: False
+
+- func: crow_indices(Tensor(a) self) -> Tensor(a)
+  variants: method
+  dispatch:
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: crow_indices_sparse_csr
+    CompositeExplicitAutograd: crow_indices_default
+  device_check: NoCheck
+  device_guard: False
+
+- func: col_indices(Tensor(a) self) -> Tensor(a)
+  variants: method
+  dispatch:
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: col_indices_sparse_csr
+    CompositeExplicitAutograd: col_indices_default
+  device_check: NoCheck
+  device_guard: False
+
+- func: ccol_indices(Tensor(a) self) -> Tensor(a)
+  variants: method
+  dispatch:
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: ccol_indices_sparse_csr
+    CompositeExplicitAutograd: ccol_indices_default
+  device_check: NoCheck
+  device_guard: False
+
+- func: row_indices(Tensor(a) self) -> Tensor(a)
+  variants: method
+  dispatch:
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: row_indices_sparse_csr
+    CompositeExplicitAutograd: row_indices_default
+  device_check: NoCheck
+  device_guard: False
+
+- func: hspmm.out(Tensor mat1, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    SparseCPU: hspmm_out_sparse_cpu
+    SparseCUDA: hspmm_out_sparse_cuda
+
+- func: hspmm(Tensor mat1, Tensor mat2) -> Tensor
+  dispatch:
+    SparseCPU: hspmm_sparse_cpu
+    SparseCUDA: hspmm_sparse_cuda
+
+- func: copy_sparse_to_sparse_(Tensor(a!) self, Tensor src, bool non_blocking=False) -> Tensor(a!)
+  device_check: NoCheck  # Allows copy into different device
+  variants: function
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS, SparseMeta: copy_sparse_
+  autogen: copy_sparse_to_sparse, copy_sparse_to_sparse.out
+
+# By adding the AutogradNestedTensor this makes this function CompositeImplicit-like for nested tensors
+- func: unbind.int(Tensor(a -> *) self, int dim=0) -> Tensor(a)[]
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: unbind
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_unbind
+
+- func: unbind.Dimname(Tensor(a -> *) self, Dimname dim) -> Tensor(a)[]
+  variants: function, method
+
+- func: to_sparse.sparse_dim(Tensor self, int sparse_dim) -> Tensor
+  variants: method
+
+# Special case of to_sparse.sparse_dim with custom derivative
+- func: _to_sparse.sparse_dim(Tensor self, int sparse_dim) -> Tensor
+  variants: method
+  dispatch:
+    CPU, CUDA, MPS: dense_to_sparse
+    SparseCPU, SparseCUDA, SparseMPS: sparse_coo_to_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrMPS: sparse_compressed_to_sparse
+  autogen: _to_sparse.sparse_dim_out
+
+- func: to_sparse(Tensor self, *, Layout? layout=None, int[2]? blocksize=None, int? dense_dim=None) -> Tensor
+  variants: method
+
+# Special case of to_sparse with custom derivative
+- func: _to_sparse(Tensor self, *, Layout? layout=None, int[2]? blocksize=None, int? dense_dim=None) -> Tensor
+  variants: method
+  dispatch:
+    CPU, CUDA, MPS: dense_to_sparse
+    SparseCPU, SparseCUDA, SparseMPS: sparse_coo_to_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sparse_compressed_to_sparse
+  autogen: _to_sparse.out
+
+- func: to_sparse_csr(Tensor self, int? dense_dim=None) -> Tensor
+  variants: method
+
+# Special case of to_sparse_csr with custom derivative
+- func: _to_sparse_csr(Tensor self, int? dense_dim=None) -> Tensor
+  variants: method
+  dispatch:
+    CPU, CUDA: dense_to_sparse_csr
+    SparseCPU, SparseCUDA: coo_to_sparse_csr
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sparse_compressed_to_sparse_csr
+  autogen: _to_sparse_csr.out
+
+- func: to_sparse_csc(Tensor self, int? dense_dim=None) -> Tensor
+  variants: method
+
+# Special case of to_sparse_csc with custom derivative
+- func: _to_sparse_csc(Tensor self, int? dense_dim=None) -> Tensor
+  variants: method
+  dispatch:
+    CPU, CUDA: dense_to_sparse_csc
+    SparseCPU, SparseCUDA: coo_to_sparse_csc
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sparse_compressed_to_sparse_csc
+  autogen: _to_sparse_csc.out
+
+- func: to_sparse_bsr(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor
+  variants: method
+
+# Special case of to_sparse_bsr with custom derivative
+- func: _to_sparse_bsr(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor
+  variants: method
+  dispatch:
+    CPU, CUDA: dense_to_sparse_bsr
+    SparseCPU, SparseCUDA: coo_to_sparse_bsr
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sparse_compressed_to_sparse_bsr
+  autogen: _to_sparse_bsr.out
+
+- func: to_sparse_bsc(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor
+  variants: method
+
+# Special case of to_sparse_bsc with custom derivative
+- func: _to_sparse_bsc(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor
+  variants: method
+  dispatch:
+    CPU, CUDA: dense_to_sparse_bsc
+    SparseCPU, SparseCUDA: coo_to_sparse_bsc
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sparse_compressed_to_sparse_bsc
+  autogen: _to_sparse_bsc.out
+
+- func: _to_sparse_semi_structured(Tensor dense) -> (Tensor, Tensor)
+  variants: function
+  dispatch:
+    CUDA: _to_sparse_semi_structured
+
+- func: to_mkldnn(Tensor self, ScalarType? dtype=None) -> Tensor
+  variants: method
+  dispatch:
+    CPU: dense_to_mkldnn
+  autogen: to_mkldnn.out
+
+- func: mkldnn_reorder_conv2d_weight(Tensor self, SymInt[2] padding=0, SymInt[2] stride=1, SymInt[2] dilation=1, SymInt groups=1, SymInt[]? input_size=None) -> Tensor
+  variants: function
+  python_module: nn
+  dispatch:
+    MkldnnCPU: mkldnn_reorder_conv2d_weight
+  autogen: mkldnn_reorder_conv2d_weight.out
+
+- func: mkldnn_reorder_conv3d_weight(Tensor self, SymInt[3] padding=0, SymInt[3] stride=1, SymInt[3] dilation=1, SymInt groups=1, SymInt[]? input_size=None) -> Tensor
+  variants: function
+  python_module: nn
+  dispatch:
+    MkldnnCPU: mkldnn_reorder_conv3d_weight
+  autogen: mkldnn_reorder_conv3d_weight.out
+
+- func: to_mkldnn_backward(Tensor grad, Tensor input) -> Tensor
+
+- func: quantize_per_tensor_dynamic(Tensor self, ScalarType dtype, bool reduce_range) -> Tensor
+  variants: function
+  dispatch:
+    CPU, CUDA: quantize_per_tensor_dynamic
+  autogen: quantize_per_tensor_dynamic.out
+
+- func: quantize_per_tensor(Tensor self, float scale, int zero_point, ScalarType dtype) -> Tensor
+  variants: function
+  dispatch:
+    CPU, CUDA: quantize_per_tensor
+  autogen: quantize_per_tensor.out
+
+- func: quantize_per_tensor.tensor_qparams(Tensor self, Tensor scale, Tensor zero_point, ScalarType dtype) -> Tensor
+  variants: function
+  dispatch:
+    CPU, CUDA: quantize_per_tensor_tensor_qparams
+  autogen: quantize_per_tensor.tensor_qparams_out
+
+- func: quantize_per_tensor.tensors(Tensor[] tensors, Tensor scales, Tensor zero_points, ScalarType dtype) -> Tensor[]
+  variants: function
+  dispatch:
+    CPU: quantize_per_tensor_list_cpu
+  autogen: quantize_per_tensor.tensors_out
+
+- func: quantize_per_channel(Tensor self, Tensor scales, Tensor zero_points, int axis, ScalarType dtype) -> Tensor
+  variants: function
+  dispatch:
+    CPU, CUDA: quantize_per_channel
+  autogen: quantize_per_channel.out
+
+- func: dequantize.self(Tensor self) -> Tensor
+  variants: function, method
+  dispatch:
+    CPU, CUDA: dequantize_cpu_or_cuda
+    QuantizedCPU, QuantizedCUDA: dequantize_quantized
+  autogen: dequantize.self_out
+
+- func: dequantize.tensors(Tensor[] tensors) -> Tensor[]
+  variants: function
+  dispatch:
+    QuantizedCPU: dequantize_tensors_quantized_cpu
+  autogen: dequantize.tensors_out
+
+- func: q_scale(Tensor self) -> float
+  variants: function, method
+  dispatch:
+    QuantizedCPU, QuantizedCUDA: q_scale_quant
+
+- func: q_zero_point(Tensor self) -> int
+  variants: function, method
+  dispatch:
+    QuantizedCPU, QuantizedCUDA: q_zero_point_quant
+
+- func: q_per_channel_scales(Tensor self) -> Tensor
+  variants: function, method
+  dispatch:
+    QuantizedCPU, QuantizedCUDA: q_per_channel_scales
+  autogen: q_per_channel_scales.out
+
+- func: q_per_channel_zero_points(Tensor self) -> Tensor
+  variants: function, method
+  dispatch:
+    QuantizedCPU, QuantizedCUDA: q_per_channel_zero_points
+  autogen: q_per_channel_zero_points.out
+
+- func: q_per_channel_axis(Tensor self) -> int
+  variants: function, method
+  dispatch:
+    QuantizedCPU, QuantizedCUDA: q_per_channel_axis
+
+- func: int_repr(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    QuantizedCPU: int_repr_quantized_cpu
+    QuantizedCUDA: int_repr_quantized_cuda
+  autogen: int_repr.out
+
+- func: _make_per_tensor_quantized_tensor(Tensor self, float scale, int zero_point) -> Tensor
+  dispatch:
+    CPU: make_per_tensor_quantized_tensor_cpu
+    CUDA: make_per_tensor_quantized_tensor_cuda
+  autogen: _make_per_tensor_quantized_tensor.out
+
+- func: _make_per_channel_quantized_tensor(Tensor self, Tensor scale, Tensor zero_point, int axis) -> Tensor
+  dispatch:
+    CPU: make_per_channel_quantized_tensor_cpu
+    CUDA: make_per_channel_quantized_tensor_cuda
+  autogen: _make_per_channel_quantized_tensor.out
+
+- func: qscheme(Tensor self) -> QScheme
+  variants: method
+  dispatch:
+    QuantizedCPU, QuantizedCUDA: qscheme_quant
+
+- func: fake_quantize_per_tensor_affine(Tensor self, float scale, int zero_point, int quant_min, int quant_max) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function
+
+- func: fake_quantize_per_tensor_affine.tensor_qparams(Tensor self, Tensor scale, Tensor zero_point, int quant_min, int quant_max) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function
+
+- func: fake_quantize_per_tensor_affine_cachemask(Tensor self, float scale, int zero_point, int quant_min, int quant_max) -> (Tensor output, Tensor mask)
+  variants: function
+  dispatch:
+    CPU, CUDA: fake_quantize_per_tensor_affine_cachemask
+  autogen: fake_quantize_per_tensor_affine_cachemask.out
+
+- func: _fake_quantize_per_tensor_affine_cachemask_tensor_qparams(Tensor self, Tensor scale, Tensor zero_point, Tensor fake_quant_enabled, int quant_min, int quant_max) -> (Tensor output, Tensor mask)
+  variants: function
+  dispatch:
+    CPU, CUDA: _fake_quantize_per_tensor_affine_cachemask_tensor_qparams
+  autogen: _fake_quantize_per_tensor_affine_cachemask_tensor_qparams.out
+
+- func: fake_quantize_per_tensor_affine_cachemask_backward(Tensor grad, Tensor mask) -> Tensor
+  variants: function
+
+- func: _fake_quantize_learnable_per_tensor_affine(Tensor self, Tensor scale, Tensor zero_point, int quant_min, int quant_max, float grad_factor=1.0) -> Tensor
+  variants: function
+  dispatch:
+    CPU, CUDA: _fake_quantize_learnable_per_tensor_affine
+  autogen: _fake_quantize_learnable_per_tensor_affine.out
+
+- func: _fake_quantize_learnable_per_tensor_affine_backward(Tensor grad, Tensor self, Tensor scale, Tensor zero_point, int quant_min, int quant_max, float grad_factor=1.0) -> (Tensor, Tensor, Tensor)
+  variants: function
+  dispatch:
+    CPU, CUDA: _fake_quantize_learnable_per_tensor_affine_backward
+
+- func: fake_quantize_per_channel_affine(Tensor self, Tensor scale, Tensor zero_point, int axis, int quant_min, int quant_max) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function
+
+- func: fake_quantize_per_channel_affine_cachemask(Tensor self, Tensor scale, Tensor zero_point, int axis, int quant_min, int quant_max) -> (Tensor output, Tensor mask)
+  variants: function
+  dispatch:
+    CPU, CUDA: fake_quantize_per_channel_affine_cachemask
+  autogen: fake_quantize_per_channel_affine_cachemask.out
+
+- func: fake_quantize_per_channel_affine_cachemask_backward(Tensor grad, Tensor mask) -> Tensor
+  variants: function
+
+- func: _fake_quantize_learnable_per_channel_affine(Tensor self, Tensor scale, Tensor zero_point, int axis, int quant_min, int quant_max, float grad_factor=1.0) -> Tensor
+  variants: function
+  dispatch:
+    CPU, CUDA: _fake_quantize_learnable_per_channel_affine
+  autogen: _fake_quantize_learnable_per_channel_affine.out
+
+- func: _fake_quantize_learnable_per_channel_affine_backward(Tensor grad, Tensor self, Tensor scale, Tensor zero_point, int axis, int quant_min, int quant_max, float grad_factor=1.0) -> (Tensor, Tensor, Tensor)
+  variants: function
+  dispatch:
+    CPU, CUDA: _fake_quantize_learnable_per_channel_affine_backward
+
+- func: fused_moving_avg_obs_fake_quant(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> Tensor
+  variants: function
+
+- func: _fused_moving_avg_obs_fq_helper(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor output, Tensor mask)
+  dispatch:
+    CPU: fused_moving_avg_obs_fake_quant_cpu
+    CUDA: fused_moving_avg_obs_fake_quant_cuda
+  autogen: _fused_moving_avg_obs_fq_helper_functional, _fused_moving_avg_obs_fq_helper.out
+
+- func: _choose_qparams_per_tensor(Tensor self, bool reduce_range=False) -> (float, int)
+  variants: function
+
+- func: _saturate_weight_to_fp16(Tensor weight) -> Tensor
+  variants: function
+
+- func: choose_qparams_optimized(Tensor input, int numel, int n_bins, float ratio, int bit_width) -> (Tensor, Tensor)
+  variants: function
+
+- func: _autocast_to_reduced_precision(Tensor(a) self, bool cuda_enabled, bool cpu_enabled, ScalarType cuda_dtype, ScalarType cpu_dtype) -> Tensor(a)
+  variants: method
+  device_guard: False
+
+- func: _autocast_to_full_precision(Tensor(a) self, bool cuda_enabled, bool cpu_enabled) -> Tensor(a)
+  variants: method
+  device_guard: False
+
+- func: _to_copy(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool non_blocking=False, MemoryFormat? memory_format=None) -> Tensor
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: _to_copy
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: _to_copy_nested
+  autogen: _to_copy.out
+  tags: core
+
+# to(Device) must not exist because all constructors of Device also works for
+# TensorOptions. Otherwise, an ambiguity error is thrown.
+# See NOTE [ TensorOptions Constructors ].
+- func: to.dtype_layout(Tensor(a) self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+
+- func: to.device(Tensor(a) self, Device device, ScalarType dtype, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+
+- func: to.dtype(Tensor(a) self, ScalarType dtype, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+
+- func: to.other(Tensor(a) self, Tensor other, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+
+- func: meshgrid(Tensor[] tensors) -> Tensor[]
+
+# TODO: Two weeks after this lands, combine these two overloads,
+#       making "indexing" optional. These are temporarily distinct for
+#       forward-compatibility reasons.
+- func: meshgrid.indexing(Tensor[] tensors, *, str indexing) -> Tensor[]
+
+- func: cartesian_prod(Tensor[] tensors) -> Tensor
+  variants: function
+  tags: maybe_aliasing_or_mutating
+
+- func: combinations(Tensor self, int r=2, bool with_replacement=False) -> Tensor
+  variants: function
+
+- func: item(Tensor self) -> Scalar
+  tags: data_dependent_output
+  variants: method
+
+- func: result_type.Tensor(Tensor tensor, Tensor other) -> ScalarType
+  variants: function
+
+- func: result_type.Scalar(Tensor tensor, Scalar other) -> ScalarType
+  variants: function
+
+- func: result_type.Scalar_Tensor(Scalar scalar, Tensor tensor) -> ScalarType
+  variants: function
+
+- func: result_type.Scalar_Scalar(Scalar scalar1, Scalar scalar2) -> ScalarType
+
+- func: can_cast(ScalarType from_, ScalarType to) -> bool
+  variants: function
+
+- func: promote_types(ScalarType type1, ScalarType type2) -> ScalarType
+  variants: function
+
+# NB: Does NOT check precondition that numel == 1
+- func: _local_scalar_dense(Tensor self) -> Scalar
+  tags: [core, data_dependent_output]
+  dispatch:
+    CPU: _local_scalar_dense_cpu
+    CUDA: _local_scalar_dense_cuda
+    MPS: _local_scalar_dense_mps
+  variants: function
+
+# MPS LSTM implementation
+
+- func: _lstm_mps(Tensor input, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor)
+  dispatch:
+    MPS: _lstm_mps
+  autogen: _lstm_mps.out
+  tags: nondeterministic_seeded
+
+- func: lstm_mps_backward(Tensor? grad_y, Tensor? grad_hy, Tensor? grad_cy, Tensor z_state, Tensor cell_state_fwd, Tensor input, Tensor layersOutputs, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor[], Tensor[])
+  dispatch:
+    MPS: lstm_mps_backward
+  autogen: lstm_mps_backward.out
+
+
+# Fused RNN kernels
+- func: _thnn_fused_lstm_cell(Tensor input_gates, Tensor hidden_gates, Tensor cx, Tensor? input_bias=None, Tensor? hidden_bias=None) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    CUDA: _thnn_fused_lstm_cell_cuda
+  autogen: _thnn_fused_lstm_cell.out
+
+# NB: The composite version of this function below is a simple wrapper that duplicates some of the outputs
+#     It is necessary to avoid triggering TensorImpl use count checks in debug mode
+# NB: this is function is NOT differentiable
+- func: _thnn_fused_lstm_cell_backward_impl(Tensor? grad_hy, Tensor? grad_cy, Tensor cx, Tensor cy, Tensor workspace, bool has_bias) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    CUDA: _thnn_fused_lstm_cell_backward_impl_cuda
+  autogen: _thnn_fused_lstm_cell_backward_impl.out
+
+- func: _thnn_fused_lstm_cell_backward(Tensor? grad_hy, Tensor? grad_cy, Tensor cx, Tensor cy, Tensor workspace, bool has_bias) -> (Tensor, Tensor, Tensor, Tensor, Tensor)
+
+- func: _thnn_differentiable_lstm_cell_backward(Tensor? grad_hy, Tensor? grad_cy, Tensor input_gates, Tensor hidden_gates, Tensor? input_bias, Tensor? hidden_bias, Tensor cx, Tensor cy) -> (Tensor, Tensor, Tensor, Tensor, Tensor)
+
+- func: _thnn_fused_gru_cell(Tensor input_gates, Tensor hidden_gates, Tensor hx, Tensor? input_bias=None, Tensor? hidden_bias=None) -> (Tensor, Tensor)
+  dispatch:
+    CUDA: _thnn_fused_gru_cell_cuda
+  autogen: _thnn_fused_gru_cell.out
+
+- func: _thnn_fused_gru_cell_backward(Tensor grad_hy, Tensor workspace, bool has_bias) -> (Tensor, Tensor, Tensor, Tensor, Tensor)
+  dispatch:
+    CUDA: _thnn_fused_gru_cell_backward_cuda
+  autogen: _thnn_fused_gru_cell_backward.out
+
+- func: _thnn_differentiable_gru_cell_backward(Tensor grad_hy, Tensor input_gates, Tensor hidden_gates, Tensor hx, Tensor? input_bias, Tensor? hidden_bias) -> (Tensor, Tensor, Tensor, Tensor, Tensor)
+
+# RNN cells and layers
+- func: lstm.input(Tensor input, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor, Tensor)
+  tags: nondeterministic_seeded
+
+- func: lstm.data(Tensor data, Tensor batch_sizes, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor, Tensor)
+  tags: nondeterministic_seeded
+
+- func: gru.input(Tensor input, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor)
+  tags: nondeterministic_seeded
+
+- func: gru.data(Tensor data, Tensor batch_sizes, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor)
+  tags: nondeterministic_seeded
+
+- func: rnn_tanh.input(Tensor input, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor)
+  tags: nondeterministic_seeded
+
+- func: rnn_tanh.data(Tensor data, Tensor batch_sizes, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor)
+  tags: nondeterministic_seeded
+
+- func: rnn_relu.input(Tensor input, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor)
+  tags: nondeterministic_seeded
+
+- func: rnn_relu.data(Tensor data, Tensor batch_sizes, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor)
+  tags: nondeterministic_seeded
+
+- func: lstm_cell(Tensor input, Tensor[] hx, Tensor w_ih, Tensor w_hh, Tensor? b_ih=None, Tensor? b_hh=None) -> (Tensor, Tensor)
+
+- func: gru_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor? b_ih=None, Tensor? b_hh=None) -> Tensor
+
+- func: rnn_tanh_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor? b_ih=None, Tensor? b_hh=None) -> Tensor
+
+- func: rnn_relu_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor? b_ih=None, Tensor? b_hh=None) -> Tensor
+
+# Quantized RNN layer registration has been moved to C10 dispatch in `RNN.cpp`
+
+# Quantized RNN layers
+# - func: quantized_lstm(Tensor input, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first, *, ScalarType? dtype=None, bool use_dynamic=False) -> (Tensor, Tensor, Tensor)
+
+
+# - func: quantized_lstm.data(Tensor data, Tensor batch_sizes, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, *, ScalarType? dtype=None, bool use_dynamic=False) -> (Tensor, Tensor, Tensor)
+
+
+# Quantized GRU layers
+
+# - func: quantized_gru.input(Tensor input, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor)
+#
+
+# - func: quantized_gru.data(Tensor data, Tensor batch_sizes, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor)
+#
+
+# Quantized RNN cells
+- func: quantized_lstm_cell(Tensor input, Tensor[] hx, Tensor w_ih, Tensor w_hh, Tensor b_ih, Tensor b_hh, Tensor packed_ih, Tensor packed_hh, Tensor col_offsets_ih, Tensor col_offsets_hh, Scalar scale_ih, Scalar scale_hh, Scalar zero_point_ih, Scalar zero_point_hh) -> (Tensor, Tensor)
+
+- func: quantized_gru_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor b_ih, Tensor b_hh, Tensor packed_ih, Tensor packed_hh, Tensor col_offsets_ih, Tensor col_offsets_hh, Scalar scale_ih, Scalar scale_hh, Scalar zero_point_ih, Scalar zero_point_hh) -> Tensor
+
+- func: quantized_rnn_relu_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor b_ih, Tensor b_hh, Tensor packed_ih, Tensor packed_hh, Tensor col_offsets_ih, Tensor col_offsets_hh, Scalar scale_ih, Scalar scale_hh, Scalar zero_point_ih, Scalar zero_point_hh) -> Tensor
+
+- func: quantized_rnn_tanh_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor b_ih, Tensor b_hh, Tensor packed_ih, Tensor packed_hh, Tensor col_offsets_ih, Tensor col_offsets_hh, Scalar scale_ih, Scalar scale_hh, Scalar zero_point_ih, Scalar zero_point_hh) -> Tensor
+
+# PackedSequence utilities
+- func: _pack_padded_sequence(Tensor input, Tensor lengths, bool batch_first) -> (Tensor, Tensor)
+  dispatch:
+    CompositeExplicitAutograd: _pack_padded_sequence
+  autogen: _pack_padded_sequence.out
+
+- func: _pack_padded_sequence_backward(Tensor grad, SymInt[] input_size, Tensor batch_sizes, bool batch_first) -> Tensor
+  dispatch:
+    CompositeImplicitAutograd: _pack_padded_sequence_backward_symint
+
+- func: _pad_packed_sequence(Tensor data, Tensor batch_sizes, bool batch_first, Scalar padding_value, int total_length) -> (Tensor, Tensor)
+
+# wrappers for legacy TH methods
+
+- func: set_.source_Storage(Tensor(a!) self, Storage source) -> Tensor(a!)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CPU, CUDA, Meta, MPS: set_
+  autogen: set.source_Storage, set.source_Storage_out
+  tags: inplace_view
+
+- func: set_.source_Storage_storage_offset(Tensor(a!) self, Storage source, SymInt storage_offset, SymInt[] size, SymInt[] stride=[]) -> Tensor(a!)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CPU: set_storage_cpu_
+    Meta: set_storage_meta__symint
+    CUDA: set_storage_cuda_
+    MPS: set_storage_mps_
+    QuantizedCPU, QuantizedCUDA: set_storage_quantized_
+  autogen: set.source_Storage_storage_offset, set.source_Storage_storage_offset_out
+  tags: inplace_view
+
+- func: set_.source_Tensor_storage_offset(Tensor(a!) self, Tensor source, SymInt storage_offset, SymInt[] size, SymInt[] stride=[]) -> Tensor(a!)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeImplicitAutograd: set__symint
+  tags: inplace_view
+
+- func: set_.source_Tensor(Tensor(a!) self, Tensor source) -> Tensor(a!)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CPU, CUDA, Meta, MPS: set_tensor_
+  autogen: set.source_Tensor, set.source_Tensor_out
+  tags: inplace_view
+
+- func: set_(Tensor(a!) self) -> Tensor(a!)
+  variants: method
+  dispatch:
+    CPU: set_cpu_
+    CUDA: set_cuda_
+    Meta: set_meta_
+    MPS: set_mps_
+  autogen: set, set.out
+  tags: inplace_view
+
+# Not making it CompositeImplicitAutograd because lift
+# should be a primitive w.r.t. functorch
+
+# TODO: this should have a view annotation
+# TODO: shouldn't be a method
+- func: lift(Tensor self) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: lift
+  autogen: lift.out
+
+# lift_fresh is called with an argument that is guaranteed to be
+# fresh (i.e., newly allocated).  This is ONLY called from a
+# torch.tensor call; if you FX trace a lift_fresh, you are obligated
+# to convert this into a lift_fresh_copy (because FX will violate the
+# freshness invariant when tracing).
+- func: lift_fresh(Tensor(a) self) -> Tensor(a)
+  dispatch:
+    CompositeExplicitAutograd: lift_fresh
+
+# Like lift, but it clones the input.
+- func: lift_fresh_copy(Tensor self) -> Tensor
+  tags: view_copy
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: lift_fresh_copy
+  autogen: lift_fresh_copy.out
+
+- func: is_set_to(Tensor self, Tensor tensor) -> bool
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CPU, CUDA, MPS: is_set_to
+
+- func: masked_fill_.Scalar(Tensor(a!) self, Tensor mask, Scalar value) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CPU: masked_fill__cpu
+    CUDA: masked_fill__cuda
+    QuantizedCPU: masked_fill__quantized_cpu
+    QuantizedCUDA: masked_fill__quantized_cuda
+    MPS: masked_fill__mps
+  autogen: masked_fill.Scalar_out
+
+- func: masked_fill.Scalar(Tensor self, Tensor mask, Scalar value) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: masked_fill
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_masked_fill
+  tags: pointwise
+
+- func: masked_fill_.Tensor(Tensor(a!) self, Tensor mask, Tensor value) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CPU: masked_fill__cpu
+    CUDA: masked_fill__cuda
+    QuantizedCPU: masked_fill__quantized_cpu
+    QuantizedCUDA: masked_fill__quantized_cuda
+    MPS: masked_fill__mps
+  autogen: masked_fill.Tensor_out
+
+- func: masked_fill.Tensor(Tensor self, Tensor mask, Tensor value) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: masked_fill
+
+- func: masked_scatter_(Tensor(a!) self, Tensor mask, Tensor source) -> Tensor(a!)
+  variants: method
+  dispatch:
+    CPU: masked_scatter__cpu
+    CUDA: masked_scatter__cuda
+    MPS: masked_scatter__mps
+  autogen: masked_scatter.out
+
+- func: masked_scatter(Tensor self, Tensor mask, Tensor source) -> Tensor
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: masked_scatter
+  tags: core
+
+- func: masked_scatter_backward(Tensor grad_output, Tensor mask, SymInt[] sizes) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: masked_scatter_backward_symint
+
+- func: _masked_softmax(Tensor self, Tensor mask, int? dim=None, int? mask_type=None) -> Tensor
+  dispatch:
+    CUDA: masked_softmax_cuda
+    CPU: masked_softmax_cpu
+  autogen: _masked_softmax.out
+
+- func: _masked_softmax_backward(Tensor grad_output, Tensor output, Tensor mask, int? dim=None) -> Tensor
+  dispatch:
+    CUDA: masked_softmax_backward_cuda
+    CPU: masked_softmax_backward_cpu
+  autogen: _masked_softmax_backward.out
+
+- func: view(Tensor(a) self, SymInt[] size) -> Tensor(a)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    ZeroTensor, Meta, CPU, CUDA, QuantizedCPU, QuantizedCUDA, MPS, MTIA: view
+    MkldnnCPU: mkldnn_view
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: view_nested
+  tags: core
+
+# Warning: If you want to change the name or overload name of this
+# operator, you might also want to change the `isBlockListedSchema`
+# function in `torch/csrc/jit/frontend/schema_catching.cpp`.
+# The name and overload name of this operator is hardcoded in that
+# function in order to workaround a bug:
+# https://github.com/pytorch/pytorch/issues/47964
+- func: view.dtype(Tensor(a) self, ScalarType dtype) -> Tensor(a)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: view_dtype
+
+- func: put_(Tensor(a!) self, Tensor index, Tensor source, bool accumulate=False) -> Tensor(a!)
+  variants: method
+  dispatch:
+    CPU, CUDA: put_
+  autogen: put.out
+
+- func: put(Tensor self, Tensor index, Tensor source, bool accumulate=False) -> Tensor
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: put
+
+- func: index_add.out(Tensor self, int dim, Tensor index, Tensor source, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  variants: function
+  precomputed:
+  - dim -> int dim
+  dispatch:
+    CPU: index_add_cpu_out
+    CUDA: index_add_cuda_out
+    MPS: index_add_mps_out
+
+- func: index_add_(Tensor(a!) self, int dim, Tensor index, Tensor source, *, Scalar alpha=1) -> Tensor(a!)
+  structured_delegate: index_add.out
+  variants: method
+
+- func: index_add(Tensor self, int dim, Tensor index, Tensor source, *, Scalar alpha=1) -> Tensor
+  structured_delegate: index_add.out
+  variants: function, method
+
+- func: index_add.dimname(Tensor self, Dimname dim, Tensor index, Tensor source, *, Scalar alpha=1) -> Tensor
+  variants: function, method
+
+- func: index_reduce.out(Tensor self, int dim, Tensor index, Tensor source, str reduce, *, bool include_self=True, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  variants: function
+  precomputed:
+  - dim -> int dim
+  dispatch:
+    CPU: index_reduce_cpu_out
+    CUDA: index_reduce_cuda_out
+
+- func: index_reduce_(Tensor(a!) self, int dim, Tensor index, Tensor source, str reduce, *, bool include_self=True) -> Tensor(a!)
+  structured_delegate: index_reduce.out
+  variants: method
+
+- func: index_reduce(Tensor self, int dim, Tensor index, Tensor source, str reduce, *, bool include_self=True) -> Tensor
+  structured_delegate: index_reduce.out
+  variants: function, method
+
+- func: index_fill_.int_Scalar(Tensor(a!) self, int dim, Tensor index, Scalar value) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CPU: index_fill_
+    CUDA: index_fill_
+    MPS: index_fill_mps_
+  autogen: index_fill.int_Scalar_out
+
+- func: index_fill.int_Scalar(Tensor self, int dim, Tensor index, Scalar value) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: index_fill
+
+- func: index_fill_.int_Tensor(Tensor(a!) self, int dim, Tensor index, Tensor value) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CPU, CUDA: index_fill_
+    MPS: index_fill_mps_
+  autogen: index_fill.int_Tensor_out
+
+- func: index_fill.int_Tensor(Tensor self, int dim, Tensor index, Tensor value) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  dispatch:
+    CompositeExplicitAutograd: index_fill
+
+- func: index_fill_.Dimname_Scalar(Tensor(a!) self, Dimname dim, Tensor index, Scalar value) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+- func: index_fill_.Dimname_Tensor(Tensor(a!) self, Dimname dim, Tensor index, Tensor value) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+- func: index_fill.Dimname_Scalar(Tensor self, Dimname dim, Tensor index, Scalar value) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: index_fill.Dimname_Tensor(Tensor self, Dimname dim, Tensor index, Tensor value) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+
+- func: scatter.src(Tensor self, int dim, Tensor index, Tensor src) -> Tensor
+  structured_delegate: scatter.src_out
+  variants: function, method
+  tags: core
+
+- func: scatter_.src(Tensor(a!) self, int dim, Tensor index, Tensor src) -> Tensor(a!)
+  structured_delegate: scatter.src_out
+  variants: method
+
+- func: scatter.src_out(Tensor self, int dim, Tensor index, Tensor src, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  variants: function
+  dispatch:
+    CPU, CUDA: scatter_src_out
+    MPS: scatter_src_out_mps
+
+- func: scatter.value(Tensor self, int dim, Tensor index, Scalar value) -> Tensor
+  structured_delegate: scatter.value_out
+  variants: function, method
+  tags: core
+
+- func: scatter_.value(Tensor(a!) self, int dim, Tensor index, Scalar value) -> Tensor(a!)
+  structured_delegate: scatter.value_out
+  variants: method
+
+- func: scatter.value_out(Tensor self, int dim, Tensor index, Scalar value, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  variants: function
+  dispatch:
+    CPU, CUDA: scatter_value_out
+    MPS: scatter_value_out_mps
+
+- func: scatter.reduce(Tensor self, int dim, Tensor index, Tensor src, *, str reduce) -> Tensor
+  structured_delegate: scatter.reduce_out
+  variants: function, method
+
+- func: scatter_.reduce(Tensor(a!) self, int dim, Tensor index, Tensor src, *, str reduce) -> Tensor(a!)
+  structured_delegate: scatter.reduce_out
+  variants: method
+
+- func: scatter.reduce_out(Tensor self, int dim, Tensor index, Tensor src, *, str reduce, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  variants: function
+  dispatch:
+    CPU, CUDA: scatter_reduce_out
+    MPS: scatter_reduce_out_mps
+
+- func: scatter.value_reduce(Tensor self, int dim, Tensor index, Scalar value, *, str reduce) -> Tensor
+  structured_delegate: scatter.value_reduce_out
+  variants: function, method
+
+- func: scatter_.value_reduce(Tensor(a!) self, int dim, Tensor index, Scalar value, *, str reduce) -> Tensor(a!)
+  structured_delegate: scatter.value_reduce_out
+  variants: method
+
+- func: scatter.value_reduce_out(Tensor self, int dim, Tensor index, Scalar value, *, str reduce, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  variants: function
+  dispatch:
+    CPU, CUDA: scatter_value_reduce_out
+    MPS: scatter_value_reduce_out_mps
+
+- func: scatter.dimname_src(Tensor self, Dimname dim, Tensor index, Tensor src) -> Tensor
+  variants: function, method
+
+- func: scatter.dimname_value(Tensor self, Dimname dim, Tensor index, Scalar value) -> Tensor
+  variants: function, method
+
+- func: scatter_add(Tensor self, int dim, Tensor index, Tensor src) -> Tensor
+  structured_delegate: scatter_add.out
+  variants: function, method
+  tags: core
+
+- func: scatter_add_(Tensor(a!) self, int dim, Tensor index, Tensor src) -> Tensor(a!)
+  structured_delegate: scatter_add.out
+  variants: method
+
+- func: scatter_add.out(Tensor self, int dim, Tensor index, Tensor src, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  variants: function
+  dispatch:
+    CPU, CUDA: scatter_add
+    MPS: scatter_add_mps_out
+
+- func: scatter_add.dimname(Tensor self, Dimname dim, Tensor index, Tensor src) -> Tensor
+  variants: function, method
+
+- func: scatter_reduce.two(Tensor self, int dim, Tensor index, Tensor src, str reduce, *, bool include_self=True) -> Tensor
+  structured_delegate: scatter_reduce.two_out
+  variants: function, method
+  tags: core
+
+- func: scatter_reduce_.two(Tensor(a!) self, int dim, Tensor index, Tensor src, str reduce, *, bool include_self=True) -> Tensor(a!)
+  structured_delegate: scatter_reduce.two_out
+  variants: method
+
+- func: scatter_reduce.two_out(Tensor self, int dim, Tensor index, Tensor src, str reduce, *, bool include_self=True, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  variants: function
+  dispatch:
+    CPU, CUDA, MPS: scatter_reduce_two
+
+- func: eq_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  structured_delegate: eq.Scalar_out
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+- func: eq_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  structured_delegate: eq.Tensor_out
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+- func: bitwise_and.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  variants: function
+  dispatch:
+    CPU, CUDA, MTIA: bitwise_and_out
+    MPS: bitwise_and_out_mps
+  tags: pointwise
+
+- func: bitwise_and.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: bitwise_and_out
+  tags: pointwise
+
+- func: bitwise_and.Scalar(Tensor self, Scalar other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    CompositeExplicitAutograd: bitwise_and
+  tags: [core, pointwise]
+
+- func: bitwise_and.Scalar_Tensor(Scalar self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: bitwise_and
+  autogen: bitwise_and.Scalar_Tensor_out
+  tags: pointwise
+
+- func: bitwise_and.Tensor(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  structured_delegate: bitwise_and.Tensor_out
+  tags: [core, pointwise]
+
+- func: bitwise_and_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: bitwise_and_
+  tags: pointwise
+
+- func: bitwise_and_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  structured_delegate: bitwise_and.Tensor_out
+  tags: pointwise
+
+- func: __and__.Scalar(Tensor self, Scalar other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+
+- func: __and__.Tensor(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+
+- func: __iand__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+- func: __iand__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+- func: bitwise_or.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  variants: function
+  dispatch:
+    CPU, CUDA, MTIA: bitwise_or_out
+    MPS: bitwise_or_out_mps
+  tags: pointwise
+
+- func: bitwise_or.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: bitwise_or_out
+  tags: pointwise
+
+- func: bitwise_or.Scalar(Tensor self, Scalar other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    CompositeExplicitAutograd: bitwise_or
+  tags: [core, pointwise]
+
+- func: bitwise_or.Scalar_Tensor(Scalar self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: bitwise_or
+  autogen: bitwise_or.Scalar_Tensor_out
+  tags: pointwise
+
+- func: bitwise_or.Tensor(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  structured_delegate: bitwise_or.Tensor_out
+  tags: [core, pointwise]
+
+- func: bitwise_or_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: bitwise_or_
+  tags: pointwise
+
+- func: bitwise_or_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  structured_delegate: bitwise_or.Tensor_out
+  tags: pointwise
+
+- func: __or__.Scalar(Tensor self, Scalar other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+
+- func: __or__.Tensor(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+
+- func: __ior__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+- func: __ior__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+- func: bitwise_xor.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  variants: function
+  dispatch:
+    CPU, CUDA: bitwise_xor_out
+    MPS: bitwise_xor_out_mps
+  tags: pointwise
+
+- func: bitwise_xor.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: bitwise_xor_out
+  tags: pointwise
+
+- func: bitwise_xor.Scalar(Tensor self, Scalar other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    CompositeExplicitAutograd: bitwise_xor
+  tags: [core, pointwise]
+
+- func: bitwise_xor.Scalar_Tensor(Scalar self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: bitwise_xor
+  autogen: bitwise_xor.Scalar_Tensor_out
+  tags: pointwise
+
+- func: bitwise_xor.Tensor(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  structured_delegate: bitwise_xor.Tensor_out
+  tags: [core, pointwise]
+
+- func: bitwise_xor_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: bitwise_xor_
+  tags: pointwise
+
+- func: bitwise_xor_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  structured_delegate: bitwise_xor.Tensor_out
+  tags: pointwise
+
+- func: __xor__.Scalar(Tensor self, Scalar other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  tags: pointwise
+
+- func: __xor__.Tensor(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  tags: pointwise
+
+- func: __ixor__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  tags: pointwise
+
+- func: __ixor__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  tags: pointwise
+
+- func: __lshift__.Scalar(Tensor self, Scalar other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    CPU, CUDA, MPS: __lshift__
+  tags: pointwise
+
+- func: __lshift__.Tensor(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    CPU, CUDA, MPS: __lshift__
+  tags: pointwise
+
+- func: __ilshift__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CPU, CUDA, MPS: __ilshift__
+  autogen: __lshift__.Scalar_out
+  tags: pointwise
+
+- func: __ilshift__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CPU, CUDA, MPS: __ilshift__
+  autogen: __lshift__.Tensor_out
+  tags: pointwise
+
+- func: bitwise_left_shift.Tensor(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  structured_delegate: bitwise_left_shift.Tensor_out
+  tags: pointwise
+
+- func: bitwise_left_shift_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  structured_delegate: bitwise_left_shift.Tensor_out
+  tags: pointwise
+
+- func: bitwise_left_shift.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: bitwise_left_shift_out
+  tags: pointwise
+
+- func: bitwise_left_shift.Tensor_Scalar(Tensor self, Scalar other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    CompositeExplicitAutograd: bitwise_left_shift
+  tags: pointwise
+
+- func: bitwise_left_shift_.Tensor_Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: bitwise_left_shift_
+  tags: pointwise
+
+- func: bitwise_left_shift.Tensor_Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: bitwise_left_shift_out
+  tags: pointwise
+
+- func: bitwise_left_shift.Scalar_Tensor(Scalar self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: bitwise_left_shift
+  autogen: bitwise_left_shift.Scalar_Tensor_out
+  tags: pointwise
+
+- func: __rshift__.Scalar(Tensor self, Scalar other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    CPU, CUDA, MPS: __rshift__
+  tags: pointwise
+
+- func: __rshift__.Tensor(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    CPU, CUDA, MPS: __rshift__
+  tags: pointwise
+
+- func: __irshift__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CPU, CUDA, MPS: __irshift__
+  autogen: __rshift__.Scalar_out
+
+- func: __irshift__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CPU, CUDA, MPS: __irshift__
+  autogen: __rshift__.Tensor_out
+
+- func: bitwise_right_shift.Tensor(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function, method
+  structured_delegate: bitwise_right_shift.Tensor_out
+  tags: pointwise
+
+- func: bitwise_right_shift_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  structured_delegate: bitwise_right_shift.Tensor_out
+  tags: pointwise
+
+- func: bitwise_right_shift.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: bitwise_right_shift_out
+  tags: pointwise
+
+- func: bitwise_right_shift.Tensor_Scalar(Tensor self, Scalar other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    CompositeExplicitAutograd: bitwise_right_shift
+  tags: pointwise
+
+- func: bitwise_right_shift_.Tensor_Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: bitwise_right_shift_
+  tags: pointwise
+
+- func: bitwise_right_shift.Tensor_Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: bitwise_right_shift_out
+  tags: pointwise
+
+- func: bitwise_right_shift.Scalar_Tensor(Scalar self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: bitwise_right_shift
+  autogen: bitwise_right_shift.Scalar_Tensor_out
+  tags: pointwise
+
+- func: tril_(Tensor(a!) self, int diagonal=0) -> Tensor(a!)
+  structured_delegate: tril.out
+  variants: method
+
+- func: triu_(Tensor(a!) self, int diagonal=0) -> Tensor(a!)
+  structured_delegate: triu.out
+  variants: method
+
+- func: digamma_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: digamma.out
+  variants: method
+  tags: pointwise
+
+- func: lerp_.Scalar(Tensor(a!) self, Tensor end, Scalar weight) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  structured_delegate: lerp.Scalar_out
+  tags: pointwise
+
+- func: lerp_.Tensor(Tensor(a!) self, Tensor end, Tensor weight) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  structured_delegate: lerp.Tensor_out
+  tags: pointwise
+
+- func: addbmm_(Tensor(a!) self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!)
+  variants: method
+  dispatch:
+    CPU, CUDA, XPU: addbmm_
+    MPS: addbmm_mps_
+
+- func: addbmm.out(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA, XPU: addbmm_out
+    MPS: addbmm_out_mps
+
+- func: addbmm(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+  variants: method, function
+  dispatch:
+    CPU, CUDA, XPU: addbmm
+    MPS: addbmm_mps
+
+- func: random_.from(Tensor(a!) self, int from, int? to, *, Generator? generator=None) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  tags: nondeterministic_seeded
+  dispatch:
+    CPU, CUDA: random_
+    Meta: random_meta_
+    MPS: random_mps_
+  autogen: random.from, random.from_out
+
+- func: random_.to(Tensor(a!) self, int to, *, Generator? generator=None) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  tags: nondeterministic_seeded
+  variants: method
+  dispatch:
+    CPU, CUDA: random_
+    Meta: random_meta_
+    MPS: random_mps_
+  autogen: random.to, random.to_out
+
+- func: random_(Tensor(a!) self, *, Generator? generator=None) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  tags: nondeterministic_seeded
+  variants: method
+  dispatch:
+    CPU, CUDA: random_
+    MPS: random_mps_
+    Meta: random_meta_
+  autogen: random, random.out
+
+- func: uniform_(Tensor(a!) self, float from=0, float to=1, *, Generator? generator=None) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  tags: nondeterministic_seeded
+  variants: method
+  dispatch:
+    CPU, CUDA: uniform_
+    MPS: uniform_mps_
+    Meta: uniform_meta_
+  autogen: uniform, uniform.out
+
+- func: cauchy_(Tensor(a!) self, float median=0, float sigma=1, *, Generator? generator=None) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  tags: nondeterministic_seeded
+  dispatch:
+    CPU, CUDA: cauchy_
+  autogen: cauchy, cauchy.out
+
+- func: log_normal_(Tensor(a!) self, float mean=1, float std=2, *, Generator? generator=None) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  tags: nondeterministic_seeded
+  variants: method
+  dispatch:
+    CPU, CUDA: log_normal_
+  autogen: log_normal, log_normal.out
+
+- func: exponential_(Tensor(a!) self, float lambd=1, *, Generator? generator=None) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  tags: nondeterministic_seeded
+  variants: method
+  dispatch:
+    CPU, CUDA: exponential_
+    MPS: exponential_mps_
+  autogen: exponential, exponential.out
+
+- func: geometric_(Tensor(a!) self, float p, *, Generator? generator=None) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  tags: nondeterministic_seeded
+  variants: method
+  dispatch:
+    CPU, CUDA: geometric_
+
+  # wrappers for TH functions
+  autogen: geometric, geometric.out
+
+- func: diag.out(Tensor self, int diagonal=0, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: diag(Tensor self, int diagonal=0) -> Tensor
+  variants: method, function
+
+- func: cross.out(Tensor self, Tensor other, int? dim=None, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: cross(Tensor self, Tensor other, int? dim=None) -> Tensor
+  variants: method, function
+
+- func: triu.out(Tensor self, int diagonal=0, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  dispatch:
+    CPU: triu_cpu
+    CUDA: triu_cuda
+    MPS: triu_mps_out
+
+- func: triu(Tensor self, int diagonal=0) -> Tensor
+  structured_delegate: triu.out
+  variants: method, function
+
+- func: tril.out(Tensor self, int diagonal=0, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  dispatch:
+    CPU: tril_cpu
+    CUDA: tril_cuda
+    MPS: tril_mps_out
+
+- func: tril(Tensor self, int diagonal=0) -> Tensor
+  structured_delegate: tril.out
+  variants: method, function
+
+- func: tril_indices(int row, int col, int offset=0, *, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CPU: tril_indices_cpu
+    CUDA: tril_indices_cuda
+    MPS: tril_indices_mps
+  autogen: tril_indices.out
+
+- func: triu_indices(int row, int col, int offset=0, *, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CPU: triu_indices_cpu
+    CUDA: triu_indices_cuda
+    MPS: triu_indices_mps
+  autogen: triu_indices.out
+
+- func: trace(Tensor self) -> Tensor
+  variants: method, function
+  dispatch:
+    CPU: trace_cpu
+    CUDA: trace_cuda
+    MPS: trace_mps
+  autogen: trace.out
+
+- func: trace_backward(Tensor grad, SymInt[] sizes) -> Tensor
+  variants: function
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeImplicitAutograd: trace_backward_symint
+
+- func: ne.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MTIA: ne_Scalar_out
+    MPS: ne_scalar_out_mps
+    QuantizedCPU: ne_out_quantized_cpu
+  tags: pointwise
+
+- func: ne.Scalar(Tensor self, Scalar other) -> Tensor
+  structured_delegate: ne.Scalar_out
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    QuantizedCPU: ne_quantized_cpu
+  tags: [core, pointwise]
+
+- func: ne.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MTIA: ne_Tensor_out
+    MPS: ne_tensor_out_mps
+    QuantizedCPU: ne_out_quantized_cpu
+  tags: pointwise
+
+- func: ne.Tensor(Tensor self, Tensor other) -> Tensor
+  structured_delegate: ne.Tensor_out
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    QuantizedCPU: ne_quantized_cpu
+  tags: [core, pointwise]
+
+- func: ne_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  structured_delegate: ne.Scalar_out
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+- func: ne_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  structured_delegate: ne.Tensor_out
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+# not_equal, alias for torch.ne
+- func: not_equal.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: not_equal.Scalar(Tensor self, Scalar other) -> Tensor
+  variants: method, function
+
+- func: not_equal.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: not_equal.Tensor(Tensor self, Tensor other) -> Tensor
+  variants: method, function
+
+- func: not_equal_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  variants: method
+
+- func: not_equal_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  variants: method
+
+- func: eq.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MTIA: eq_Scalar_out
+    MPS: eq_scalar_out_mps
+    QuantizedCPU: eq_out_quantized_cpu
+  tags: pointwise
+
+- func: eq.Scalar(Tensor self, Scalar other) -> Tensor
+  structured_delegate: eq.Scalar_out
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    QuantizedCPU: eq_quantized_cpu
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: eq_scalar_nested
+  tags: [core, pointwise]
+
+- func: eq.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MTIA: eq_Tensor_out
+    MPS: eq_tensor_out_mps
+    QuantizedCPU: eq_out_quantized_cpu
+  tags: pointwise
+
+- func: eq.Tensor(Tensor self, Tensor other) -> Tensor
+  structured_delegate: eq.Tensor_out
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    QuantizedCPU: eq_quantized_cpu
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: eq_tensor_nested
+  tags: [core, pointwise]
+
+- func: ge.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MTIA: ge_Scalar_out
+    MPS: ge_scalar_out_mps
+    QuantizedCPU: ge_out_quantized_cpu
+  tags: pointwise
+
+- func: ge.Scalar(Tensor self, Scalar other) -> Tensor
+  structured_delegate: ge.Scalar_out
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    QuantizedCPU: ge_quantized_cpu
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: ge_scalar_nested
+  tags: [core, pointwise]
+
+- func: ge.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MTIA: ge_Tensor_out
+    MPS: ge_tensor_out_mps
+    QuantizedCPU: ge_out_quantized_cpu
+  tags: pointwise
+
+- func: ge.Tensor(Tensor self, Tensor other) -> Tensor
+  structured_delegate: ge.Tensor_out
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    QuantizedCPU: ge_quantized_cpu
+  tags: [core, pointwise]
+
+- func: ge_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  structured_delegate: ge.Scalar_out
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+- func: ge_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  structured_delegate: ge.Tensor_out
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+# greater_equal, alias for torch.ge
+- func: greater_equal.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: greater_equal.Scalar(Tensor self, Scalar other) -> Tensor
+  variants: method, function
+
+- func: greater_equal.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: greater_equal.Tensor(Tensor self, Tensor other) -> Tensor
+  variants: method, function
+
+- func: greater_equal_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  variants: method
+
+- func: greater_equal_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  variants: method
+
+- func: le.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MTIA: le_Scalar_out
+    MPS: le_scalar_out_mps
+    QuantizedCPU: le_out_quantized_cpu
+  tags: pointwise
+
+- func: le.Scalar(Tensor self, Scalar other) -> Tensor
+  structured_delegate: le.Scalar_out
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    QuantizedCPU: le_quantized_cpu
+  tags: [core, pointwise]
+
+- func: le.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MTIA: le_Tensor_out
+    MPS: le_tensor_out_mps
+    QuantizedCPU: le_out_quantized_cpu
+  tags: pointwise
+
+- func: le.Tensor(Tensor self, Tensor other) -> Tensor
+  structured_delegate: le.Tensor_out
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    QuantizedCPU: le_quantized_cpu
+  tags: [core, pointwise]
+
+- func: le_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  structured_delegate: le.Scalar_out
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+- func: le_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  structured_delegate: le.Tensor_out
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+# less_equal, alias for torch.le
+- func: less_equal.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: less_equal.Scalar(Tensor self, Scalar other) -> Tensor
+  variants: method, function
+
+- func: less_equal.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: less_equal.Tensor(Tensor self, Tensor other) -> Tensor
+  variants: method, function
+
+- func: less_equal_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  variants: method
+
+- func: less_equal_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  variants: method
+
+- func: gt.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA,MTIA: gt_Scalar_out
+    MPS: gt_scalar_out_mps
+    QuantizedCPU: gt_out_quantized_cpu
+  tags: pointwise
+
+- func: gt.Scalar(Tensor self, Scalar other) -> Tensor
+  structured_delegate: gt.Scalar_out
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    QuantizedCPU: gt_quantized_cpu
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: gt_scalar_nested
+  tags: [core, pointwise]
+
+- func: gt.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MTIA: gt_Tensor_out
+    MPS: gt_tensor_out_mps
+    QuantizedCPU: gt_out_quantized_cpu
+  tags: pointwise
+
+- func: gt.Tensor(Tensor self, Tensor other) -> Tensor
+  structured_delegate: gt.Tensor_out
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    QuantizedCPU: gt_quantized_cpu
+  tags: [core, pointwise]
+
+- func: gt_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  structured_delegate: gt.Scalar_out
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+- func: gt_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  structured_delegate: gt.Tensor_out
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+#  greater, alias for torch.gt
+- func: greater.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: greater.Scalar(Tensor self, Scalar other) -> Tensor
+  variants: method, function
+
+- func: greater.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: greater.Tensor(Tensor self, Tensor other) -> Tensor
+  variants: method, function
+
+- func: greater_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  variants: method
+
+- func: greater_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  variants: method
+
+- func: lt.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MTIA: lt_Scalar_out
+    MPS: lt_scalar_out_mps
+    QuantizedCPU: lt_out_quantized_cpu
+  tags: pointwise
+
+- func: lt.Scalar(Tensor self, Scalar other) -> Tensor
+  structured_delegate: lt.Scalar_out
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    QuantizedCPU: lt_quantized_cpu
+  tags: [core, pointwise]
+
+- func: lt.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MTIA: lt_Tensor_out
+    MPS: lt_tensor_out_mps
+    QuantizedCPU: lt_out_quantized_cpu
+  tags: pointwise
+
+- func: lt.Tensor(Tensor self, Tensor other) -> Tensor
+  structured_delegate: lt.Tensor_out
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    QuantizedCPU: lt_quantized_cpu
+  tags: [core, pointwise]
+
+- func: lt_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  structured_delegate: lt.Scalar_out
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+- func: lt_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  structured_delegate: lt.Tensor_out
+  device_check: NoCheck   # TensorIterator
+  variants: method
+
+#  less, alias for torch.lt
+- func: less.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: less.Scalar(Tensor self, Scalar other) -> Tensor
+  variants: method, function
+
+- func: less.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: less.Tensor(Tensor self, Tensor other) -> Tensor
+  variants: method, function
+
+- func: less_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  variants: method
+
+- func: less_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  variants: method
+
+- func: take.out(Tensor self, Tensor index, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA: take_out
+
+- func: take(Tensor self, Tensor index) -> Tensor
+  variants: method, function
+  dispatch:
+    CPU, CUDA: take
+
+- func: take_along_dim.out(Tensor self, Tensor indices, int? dim=None, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: take_along_dim(Tensor self, Tensor indices, int? dim=None) -> Tensor
+  variants: method, function
+
+- func: index_select.out(Tensor self, int dim, Tensor index, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, QuantizedCPU: index_select_out_cpu_
+    CUDA, QuantizedCUDA: index_select_out_cuda
+    MPS: index_select_out_mps
+
+- func: index_select(Tensor self, int dim, Tensor index) -> Tensor
+  variants: method, function
+  dispatch:
+    CPU: index_select_cpu_
+    QuantizedCPU: index_select_quantized_cpu_
+    CUDA: index_select_cuda
+    QuantizedCUDA: index_select_quantized_cuda
+    SparseCPU: index_select_sparse_cpu
+    SparseCUDA: index_select_sparse_cuda
+    MPS: index_select_mps
+  tags: core
+
+- func: index_select.dimname_out(Tensor self, Dimname dim, Tensor index, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: index_select.dimname(Tensor self, Dimname dim, Tensor index) -> Tensor
+  variants: method, function
+
+- func: index_select_backward(Tensor grad, SymInt[] self_sizes, int dim, Tensor index) -> Tensor
+  variants: function
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeImplicitAutograd: index_select_backward_symint
+
+- func: masked_select.out(Tensor self, Tensor mask, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU: masked_select_out_cpu
+    CUDA: masked_select_out_cuda
+    MPS: masked_select_out_mps
+  tags: dynamic_output_shape
+
+- func: masked_select(Tensor self, Tensor mask) -> Tensor
+  variants: method, function
+  dispatch:
+    CPU: masked_select_cpu
+    CUDA: masked_select_cuda
+    MPS: masked_select_mps
+  tags: dynamic_output_shape
+
+- func: masked_select_backward(Tensor grad, Tensor input, Tensor mask) -> Tensor
+  variants: function
+  device_check: NoCheck
+  device_guard: False
+
+- func: nonzero.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU: nonzero_out_cpu
+    CUDA: nonzero_out_cuda
+    MPS: nonzero_out_mps
+  tags: dynamic_output_shape
+
+- func: nonzero(Tensor self) -> Tensor
+  variants: method, function
+  dispatch:
+    CPU: nonzero_cpu
+    CUDA: nonzero_cuda
+    MPS: nonzero_mps
+  tags: [dynamic_output_shape, core]
+
+- func: nonzero_static.out(Tensor self, *, SymInt size, int fill_value=-1, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU: nonzero_static_out_cpu
+    CUDA: nonzero_static_out_cuda
+
+- func: nonzero_static(Tensor self, *, SymInt size, int fill_value=-1) -> Tensor
+  variants: method, function
+  dispatch:
+    CPU: nonzero_static_cpu
+    CUDA: nonzero_static_cuda
+
+- func: nonzero_numpy(Tensor self) -> Tensor[]
+  variants: method, function
+
+- func: argwhere(Tensor self) -> Tensor
+  variants: method, function
+  tags: dynamic_output_shape
+
+- func: gather.out(Tensor self, int dim, Tensor index, *, bool sparse_grad=False, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  dispatch:
+    CPU, CUDA: gather_out
+    MPS: gather_out_mps
+
+- func: gather(Tensor self, int dim, Tensor index, *, bool sparse_grad=False) -> Tensor
+  variants: method, function
+  structured_delegate: gather.out
+  tags: core
+
+- func: gather_backward(Tensor grad, Tensor self, int dim, Tensor index, bool sparse_grad) -> Tensor
+  variants: function
+  device_check: NoCheck
+  device_guard: False
+
+- func: gather.dimname_out(Tensor self, Dimname dim, Tensor index, *, bool sparse_grad=False, Tensor(a!) out) -> Tensor(a!)
+
+- func: gather.dimname(Tensor self, Dimname dim, Tensor index, *, bool sparse_grad=False) -> Tensor
+  variants: method, function
+
+- func: _gather_sparse_backward(Tensor self, int dim, Tensor index, Tensor grad) -> Tensor
+
+- func: addcmul.out(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MTIA: addcmul_out
+    MPS: addcmul_out_mps
+  tags: pointwise
+
+- func: addcmul(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor
+  structured_delegate: addcmul.out
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  tags: pointwise
+
+- func: addcmul_(Tensor(a!) self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor(a!)
+  structured_delegate: addcmul.out
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  tags: pointwise
+
+- func: addcdiv.out(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MTIA: addcdiv_out
+    MPS: addcdiv_out_mps
+  tags: pointwise
+
+- func: addcdiv(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor
+  structured_delegate: addcdiv.out
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  tags: pointwise
+
+- func: addcdiv_(Tensor(a!) self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor(a!)
+  structured_delegate: addcdiv.out
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  tags: pointwise
+
+- func: cross_entropy_loss(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100, float label_smoothing=0.0) -> Tensor
+  python_module: nn
+  dispatch:
+    CompositeImplicitAutograd: cross_entropy_loss_symint
+
+- func: triangular_solve.X(Tensor self, Tensor A, bool upper=True, bool transpose=False, bool unitriangular=False, *, Tensor(a!) X, Tensor(b!) M) -> (Tensor(a!) solution, Tensor(b!) cloned_coefficient)
+  structured: True
+  dispatch:
+    CPU, CUDA: triangular_solve_out
+    MPS: triangular_solve_mps_out
+    SparseCsrCPU: triangular_solve_out_sparse_csr_cpu
+    SparseCsrCUDA: triangular_solve_out_sparse_csr_cuda
+
+- func: triangular_solve(Tensor self, Tensor A, bool upper=True, bool transpose=False, bool unitriangular=False) -> (Tensor solution, Tensor cloned_coefficient)
+  structured_delegate: triangular_solve.X
+  variants: method, function
+
+- func: _linalg_check_errors(Tensor info, str api_name, *, bool is_matrix) -> ()
+  dispatch:
+    CompositeExplicitAutograd: _linalg_check_errors
+
+- func: linalg_solve_triangular.out(Tensor self, Tensor B, *, bool upper, bool left=True, bool unitriangular=False, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+  dispatch:
+    CPU, CUDA: linalg_solve_triangular_out
+    MPS: linalg_solve_triangular_mps_out
+
+- func: linalg_solve_triangular(Tensor self, Tensor B, *, bool upper, bool left=True, bool unitriangular=False) -> Tensor
+  python_module: linalg
+  variants: function
+  dispatch:
+    CPU, CUDA: linalg_solve_triangular
+    MPS: linalg_solve_triangular_mps
+
+- func: linalg_vander(Tensor x, *, SymInt? N=None) -> Tensor
+  python_module: linalg
+  dispatch:
+    CompositeImplicitAutograd: linalg_vander_symint
+
+- func: svd.U(Tensor self, bool some=True, bool compute_uv=True, *, Tensor(a!) U, Tensor(b!) S, Tensor(c!) V) -> (Tensor(a!) U, Tensor(b!) S, Tensor(c!) V)
+
+- func: svd(Tensor self, bool some=True, bool compute_uv=True) -> (Tensor U, Tensor S, Tensor V)
+  variants: method, function
+
+# swapaxes, alias for transpose
+- func: swapaxes(Tensor(a) self, int axis0, int axis1) -> Tensor(a)
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+
+- func: swapaxes_(Tensor(a!) self, int axis0, int axis1) -> Tensor(a!)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+  tags: inplace_view
+
+# swapdims, alias for transpose
+- func: swapdims(Tensor(a) self, int dim0, int dim1) -> Tensor(a)
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+
+- func: swapdims_(Tensor(a!) self, int dim0, int dim1) -> Tensor(a!)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+  tags: inplace_view
+
+- func: cholesky.out(Tensor self, bool upper=False, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA, MPS: cholesky_out
+
+- func: cholesky(Tensor self, bool upper=False) -> Tensor
+  variants: method, function
+  dispatch:
+    CPU, CUDA, MPS: cholesky
+
+- func: cholesky_solve.out(Tensor self, Tensor input2, bool upper=False, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: cholesky_solve_out
+
+- func: cholesky_solve(Tensor self, Tensor input2, bool upper=False) -> Tensor
+  variants: method, function
+  dispatch:
+    CompositeExplicitAutograd: cholesky_solve
+
+- func: _cholesky_solve_helper(Tensor self, Tensor A, bool upper) -> Tensor
+  variants: function
+  dispatch:
+    CPU: _cholesky_solve_helper_cpu
+    CUDA: _cholesky_solve_helper_cuda
+  autogen: _cholesky_solve_helper.out
+
+- func: cholesky_inverse(Tensor self, bool upper=False) -> Tensor
+  variants: method, function
+  dispatch:
+    CPU, CUDA: cholesky_inverse
+
+- func: cholesky_inverse.out(Tensor self, bool upper=False, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA: cholesky_inverse_out
+
+- func: qr.Q(Tensor self, bool some=True, *, Tensor(a!) Q, Tensor(b!) R) -> (Tensor(a!) Q, Tensor(b!) R)
+
+- func: qr(Tensor self, bool some=True) -> (Tensor Q, Tensor R)
+  variants: method, function
+
+- func: geqrf.a(Tensor self, *, Tensor(a!) a, Tensor(b!) tau) -> (Tensor(a!) a, Tensor(b!) tau)
+  dispatch:
+    CPU, CUDA: geqrf_out
+
+- func: geqrf(Tensor self) -> (Tensor a, Tensor tau)
+  variants: method, function
+  dispatch:
+    CPU, CUDA: geqrf
+
+# orgqr, alias for linalg_householder_product
+- func: orgqr(Tensor self, Tensor input2) -> Tensor
+  variants: method, function
+
+- func: orgqr.out(Tensor self, Tensor input2, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: ormqr.out(Tensor self, Tensor input2, Tensor input3, bool left=True, bool transpose=False, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA: ormqr_out
+
+- func: ormqr(Tensor self, Tensor input2, Tensor input3, bool left=True, bool transpose=False) -> Tensor
+  variants: method, function
+  dispatch:
+    CPU, CUDA: ormqr
+
+- func: _lu_with_info(Tensor self, bool pivot=True, bool check_errors=True) -> (Tensor LU, Tensor pivots, Tensor info)
+  variants: function
+
+- func: lu_solve.out(Tensor self, Tensor LU_data, Tensor LU_pivots, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: lu_solve(Tensor self, Tensor LU_data, Tensor LU_pivots) -> Tensor
+  variants: method, function
+
+# lu_unpack
+- func: lu_unpack(Tensor LU_data, Tensor LU_pivots, bool unpack_data=True, bool unpack_pivots=True) -> (Tensor P, Tensor L, Tensor U)
+  structured_delegate: lu_unpack.out
+  variants: function
+
+- func: lu_unpack.out(Tensor LU_data, Tensor LU_pivots, bool unpack_data=True, bool unpack_pivots=True, *, Tensor(a!) P, Tensor(b!) L, Tensor(c!) U) -> (Tensor(a!) P, Tensor(b!) L, Tensor(c!) U)
+  variants: function
+  structured: True
+  dispatch:
+    CPU, CUDA: lu_unpack_out
+    MPS: lu_unpack_out_mps
+
+# TODO: remove dispatch section when porting TH CUDA to ATen
+- func: multinomial.out(Tensor self, SymInt num_samples, bool replacement=False, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!)
+  tags: nondeterministic_seeded
+  dispatch:
+    CPU, CUDA: multinomial_out
+    MPS: multinomial_out_mps
+
+- func: multinomial(Tensor self, SymInt num_samples, bool replacement=False, *, Generator? generator=None) -> Tensor
+  variants: method, function
+  dispatch:
+    CPU, CUDA: multinomial
+    MPS: multinomial_mps
+  tags: nondeterministic_seeded
+
+- func: lgamma.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: lgamma_out
+    MPS: lgamma_out_mps
+  tags: pointwise
+
+- func: lgamma_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: lgamma.out
+  variants: method
+  tags: pointwise
+
+- func: lgamma(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: lgamma.out
+  variants: method, function
+  tags: pointwise
+
+- func: digamma.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: digamma_out
+    MPS: digamma_out_mps
+  tags: pointwise
+
+- func: digamma(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: digamma.out
+  variants: method, function
+  tags: pointwise
+
+- func: polygamma.out(int n, Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: polygamma_out
+    MPS: polygamma_out_mps
+  tags: pointwise
+
+- func: polygamma(int n, Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: polygamma.out
+  variants: method, function
+  tags: pointwise
+
+- func: polygamma_(Tensor(a!) self, int n) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: polygamma_
+  tags: pointwise
+
+- func: erfinv(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: erfinv.out
+  variants: method, function
+  dispatch:
+    SparseCPU, SparseCUDA: erfinv_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: erfinv_sparse_csr
+  tags: pointwise
+
+- func: erfinv_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: erfinv.out
+  variants: method
+  dispatch:
+    SparseCPU, SparseCUDA: erfinv_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: erfinv_sparse_csr_
+  tags: pointwise
+
+- func: erfinv.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: erfinv_out
+    SparseCPU, SparseCUDA: erfinv_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: erfinv_sparse_csr_out
+  tags: pointwise
+
+- func: i0(Tensor self) -> Tensor
+  structured_delegate: i0.out
+  variants: function, method
+  tags: pointwise
+
+- func: i0_(Tensor(a!) self) -> Tensor(a!)
+  structured_delegate: i0.out
+  variants: function, method
+  tags: pointwise
+
+- func: i0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: i0_out
+  tags: pointwise
+
+- func: sign(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: sign.out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: sign_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sign_sparse_csr
+  tags: [core, pointwise]
+
+- func: sign_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: sign.out
+  variants: method
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: sign_sparse_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sign_sparse_csr_
+  tags: pointwise
+
+- func: sign.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: sign_out
+    MPS: sign_out_mps
+    SparseCPU, SparseCUDA, SparseMPS: sign_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sign_sparse_csr_out
+  tags: pointwise
+
+- func: signbit(Tensor self) -> Tensor
+  variants: function, method
+  structured_delegate: signbit.out
+  dispatch:
+    SparseCPU, SparseCUDA, SparseMPS: signbit_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: signbit_sparse_csr
+  tags: pointwise
+
+- func: signbit.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU: signbit_out
+    CUDA: signbit_out
+    MPS: signbit_out_mps
+    SparseCPU, SparseCUDA, SparseMPS: signbit_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: signbit_sparse_csr_out
+  tags: pointwise
+
+- func: dist(Tensor self, Tensor other, Scalar p=2) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    CompositeExplicitAutograd: dist
+  autogen: dist.out
+
+- func: atan2.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: atan2_out
+    MPS: atan2_out_mps
+  tags: [core, pointwise]
+
+- func: atan2_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: atan2.out
+  variants: method
+  tags: pointwise
+
+- func: atan2(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: atan2.out
+  variants: method, function
+  tags: [core, pointwise]
+# arctan2, alias of atan2
+
+- func: arctan2(Tensor self, Tensor other) -> Tensor
+  variants: method, function
+
+- func: arctan2.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+
+- func: arctan2_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  variants: method
+
+- func: lerp.Scalar_out(Tensor self, Tensor end, Scalar weight, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: lerp_Scalar
+  tags: pointwise
+
+- func: lerp.Tensor_out(Tensor self, Tensor end, Tensor weight, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: lerp_Tensor
+    MPS: lerp_Tensor_mps
+  tags: pointwise
+
+- func: lerp.Scalar(Tensor self, Tensor end, Scalar weight) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  structured_delegate: lerp.Scalar_out
+  tags: pointwise
+
+- func: lerp.Tensor(Tensor self, Tensor end, Tensor weight) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  structured_delegate: lerp.Tensor_out
+  tags: pointwise
+
+- func: histc.out(Tensor self, int bins=100, Scalar min=0, Scalar max=0, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, MPS: histogram_histc_out
+    CUDA: _histc_out_cuda
+
+- func: histc(Tensor self, int bins=100, Scalar min=0, Scalar max=0) -> Tensor
+  variants: method, function
+  dispatch:
+    CPU, MPS: histogram_histc
+    CUDA: _histc_cuda
+
+- func: histogram.bins_tensor_out(Tensor self, Tensor bins, *, Tensor? weight=None, bool density=False, Tensor(a!) hist, Tensor(b!) bin_edges) -> (Tensor(a!) hist, Tensor(b!) bin_edges)
+  dispatch:
+    CPU, MPS: histogram_out
+
+- func: histogram.bins_tensor(Tensor self, Tensor bins, *, Tensor? weight=None, bool density=False) -> (Tensor hist, Tensor bin_edges)
+  variants: method, function
+  dispatch:
+    CPU, MPS: histogram
+
+- func: histogram.bin_ct_out(Tensor self, int bins=100, *, float[]? range=None, Tensor? weight=None, bool density=False, Tensor(a!) hist, Tensor(b!) bin_edges) -> (Tensor(a!) hist, Tensor(b!) bin_edges)
+  dispatch:
+    CPU, MPS: histogram_out
+
+- func: histogram.bin_ct(Tensor self, int bins=100, *, float[]? range=None, Tensor? weight=None, bool density=False) -> (Tensor hist, Tensor bin_edges)
+  variants: method, function
+  dispatch:
+    CPU, MPS: histogram
+
+- func: _histogramdd_bin_edges(Tensor self, int[] bins, *, float[]? range=None, Tensor? weight=None, bool density=False) -> Tensor[]
+  dispatch:
+    CPU, MPS: histogramdd_bin_edges
+  autogen: _histogramdd_bin_edges.out
+
+- func: _histogramdd_from_bin_cts(Tensor self, int[] bins, *, float[]? range=None, Tensor? weight=None, bool density=False) -> Tensor
+  dispatch:
+    CPU, MPS: _histogramdd
+  autogen: _histogramdd_from_bin_cts.out
+
+- func: _histogramdd_from_bin_tensors(Tensor self, Tensor[] bins, *, Tensor? weight=None, bool density=False) -> Tensor
+  dispatch:
+    CPU, MPS: _histogramdd
+  autogen: _histogramdd_from_bin_tensors.out
+
+- func: histogramdd(Tensor self, int[] bins, float[]? range=None, Tensor? weight=None, bool density=False) -> (Tensor hist, Tensor[] bin_edges)
+
+- func: histogramdd.int_bins(Tensor self, int bins, float[]? range=None, Tensor? weight=None, bool density=False) -> (Tensor hist, Tensor[] bin_edges)
+
+- func: histogramdd.TensorList_bins(Tensor self, Tensor[] bins, float[]? range=None, Tensor? weight=None, bool density=False) -> (Tensor hist, Tensor[] bin_edges)
+
+- func: fmod.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CompositeExplicitAutograd: fmod_out
+  tags: pointwise
+
+- func: fmod.Scalar(Tensor self, Scalar other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    CompositeExplicitAutograd: fmod
+  tags: [core, pointwise]
+
+- func: fmod_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: fmod_
+  tags: pointwise
+
+- func: fmod.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS, MTIA: fmod_out
+  tags: pointwise
+
+- func: fmod.Tensor(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: fmod.Tensor_out
+  variants: method, function
+  tags: [core, pointwise]
+
+- func: fmod_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  structured_delegate: fmod.Tensor_out
+  tags: pointwise
+
+- func: hypot.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: hypot_out
+    MPS: hypot_out_mps
+  tags: pointwise
+
+- func: hypot(Tensor self, Tensor other) -> Tensor
+  structured_delegate: hypot.out
+  variants: method, function
+  tags: pointwise
+
+- func: hypot_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  structured_delegate: hypot.out
+  variants: method
+  tags: pointwise
+
+- func: igamma.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: igamma_out
+  tags: pointwise
+
+- func: igamma(Tensor self, Tensor other) -> Tensor
+  structured_delegate: igamma.out
+  variants: method, function
+  tags: pointwise
+
+- func: igamma_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  structured_delegate: igamma.out
+  variants: method
+  tags: pointwise
+
+- func: igammac.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: igammac_out
+  tags: pointwise
+
+- func: igammac(Tensor self, Tensor other) -> Tensor
+  structured_delegate: igammac.out
+  variants: method, function
+  tags: pointwise
+
+- func: igammac_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  structured_delegate: igammac.out
+  variants: method
+  tags: pointwise
+
+- func: nextafter.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: nextafter_out
+  tags: pointwise
+
+- func: nextafter(Tensor self, Tensor other) -> Tensor
+  structured_delegate: nextafter.out
+  variants: method, function
+  tags: pointwise
+
+- func: nextafter_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  structured_delegate: nextafter.out
+  variants: method
+  tags: pointwise
+
+- func: remainder.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: remainder_out
+  tags: pointwise
+
+- func: remainder.Scalar(Tensor self, Scalar other) -> Tensor
+  variants: method, function
+  dispatch:
+    CompositeExplicitAutograd: remainder
+  tags: [core, pointwise]
+
+- func: remainder_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  variants: method
+  dispatch:
+    CompositeExplicitAutograd: remainder_
+  tags: pointwise
+
+- func: remainder.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS, MTIA: remainder_out
+  tags: pointwise
+
+- func: remainder.Tensor(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: remainder.Tensor_out
+  variants: method, function
+  tags: [core, pointwise]
+
+- func: remainder_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: remainder.Tensor_out
+  variants: method
+  tags: pointwise
+
+- func: remainder.Scalar_Tensor(Scalar self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: function
+  dispatch:
+    CPU, CUDA, MPS: remainder
+  autogen: remainder.Scalar_Tensor_out
+  tags: pointwise
+
+- func: min(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    CPU, CUDA: min
+    MPS: min_mps
+    QuantizedCPU: min_quantized_cpu
+
+- func: min.unary_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA: min_unary_out
+    QuantizedCPU: min_quantized_unary_out
+
+- func: fmin(Tensor self, Tensor other) -> Tensor
+  structured_delegate: fmin.out
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  tags: pointwise
+
+- func: fmin.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MPS: fmin_out
+  tags: pointwise
+
+- func: max(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    CPU, CUDA: max
+    MPS: max_mps
+    QuantizedCPU: max_quantized_cpu
+
+- func: fmax(Tensor self, Tensor other) -> Tensor
+  structured_delegate: fmax.out
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  tags: pointwise
+
+- func: fmax.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MPS: fmax_out
+  tags: pointwise
+
+- func: maximum(Tensor self, Tensor other) -> Tensor
+  structured_delegate: maximum.out
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  tags: [core, pointwise]
+
+- func: maximum.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MTIA: maximum_out
+    MPS: maximum_out_mps
+  tags: pointwise
+
+# binary max, alias of maximum
+# NOTE: max is not an alias for maximum, since there is also unary max
+- func: max.other(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  tags: pointwise
+
+- func: max.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  tags: pointwise
+
+- func: max.unary_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA: max_unary_out
+    QuantizedCPU: max_quantized_unary_out
+
+- func: minimum(Tensor self, Tensor other) -> Tensor
+  structured_delegate: minimum.out
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  tags: [core, pointwise]
+
+- func: minimum.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CPU, CUDA, MTIA: minimum_out
+    MPS: minimum_out_mps
+  tags: pointwise
+
+# binary min, alias for minimum
+# NOTE: min is not an alias for minimum, since there is also unary min
+- func: min.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  tags: pointwise
+
+- func: min.other(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  tags: pointwise
+
+- func: quantile(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor
+  variants: method, function
+
+- func: quantile.out(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, str interpolation='linear', Tensor(a!) out) -> Tensor(a!)
+
+- func: quantile.scalar(Tensor self, float q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor
+  variants: method, function
+
+- func: quantile.scalar_out(Tensor self, float q, int? dim=None, bool keepdim=False, *, str interpolation='linear', Tensor(a!) out) -> Tensor(a!)
+
+- func: nanquantile(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor
+  variants: method, function
+
+- func: nanquantile.out(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, str interpolation='linear', Tensor(a!) out) -> Tensor(a!)
+
+- func: nanquantile.scalar(Tensor self, float q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor
+  variants: method, function
+
+- func: nanquantile.scalar_out(Tensor self, float q, int? dim=None, bool keepdim=False, *, str interpolation='linear', Tensor(a!) out) -> Tensor(a!)
+
+- func: sort.values(Tensor self, int dim=-1, bool descending=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+  device_check: NoCheck   # TensorIterator
+  dispatch:
+    CompositeExplicitAutograd: sort_out
+
+- func: sort.values_stable(Tensor self, *, bool? stable, int dim=-1, bool descending=False, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+  structured: True
+  dispatch:
+    CPU, CUDA: sort_stable_out
+    MPS: sort_stable_out_mps
+
+- func: sort(Tensor self, int dim=-1, bool descending=False) -> (Tensor values, Tensor indices)
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  dispatch:
+    CompositeExplicitAutograd: sort
+  tags: core
+
+- func: sort.stable(Tensor self, *, bool? stable, int dim=-1, bool descending=False) -> (Tensor values, Tensor indices)
+  structured_delegate: sort.values_stable
+  variants: method, function
+  dispatch:
+    QuantizedCPU: sort_quantized_cpu_stable
+
+- func: sort.dimname_values(Tensor self, Dimname dim, bool descending=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+
+- func: sort.dimname_values_stable(Tensor self, *, bool? stable, Dimname dim, bool descending=False, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+
+- func: sort.dimname(Tensor self, Dimname dim, bool descending=False) -> (Tensor values, Tensor indices)
+  variants: method, function
+
+- func: sort.dimname_stable(Tensor self, *, bool? stable, Dimname dim, bool descending=False) -> (Tensor values, Tensor indices)
+  variants: method, function
+
+- func: msort.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: msort(Tensor self) -> Tensor
+  variants: method, function
+
+- func: argsort(Tensor self, int dim=-1, bool descending=False) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+
+- func: argsort.stable(Tensor self, *, bool stable, int dim=-1, bool descending=False) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+
+- func: argsort.stable_out(Tensor self, *, bool stable, int dim=-1, bool descending=False, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: function
+
+- func: argsort.dimname(Tensor self, Dimname dim, bool descending=False) -> Tensor
+  variants: method, function
+
+- func: topk.values(Tensor self, SymInt k, int dim=-1, bool largest=True, bool sorted=True, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+  structured: True
+  dispatch:
+    CPU: topk_out_cpu
+    CUDA: topk_out_cuda
+    MPS: topk_out_mps
+
+- func: topk(Tensor self, SymInt k, int dim=-1, bool largest=True, bool sorted=True) -> (Tensor values, Tensor indices)
+  variants: method, function
+  structured_delegate: topk.values
+  dispatch:
+    QuantizedCPU: topk_quantized_cpu
+  tags: core
+
+- func: all(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: all.all_out
+  variants: method, function
+
+- func: all.all_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck
+  structured: True
+  dispatch:
+    CPU, CUDA: all_all_out
+    MPS: all_all_out_mps
+
+- func: any(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: any.all_out
+  variants: method, function
+  dispatch:
+    SparseCPU, SparseCUDA: any_sparse
+  tags: core
+
+- func: any.all_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck
+  structured: True
+  dispatch:
+    CPU, CUDA: any_all_out
+    MPS: any_all_out_mps
+
+- func: renorm.out(Tensor self, Scalar p, int dim, Scalar maxnorm, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  dispatch:
+    CPU, CUDA: renorm_out
+    MPS: renorm_out_mps
+
+- func: renorm(Tensor self, Scalar p, int dim, Scalar maxnorm) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  variants: method, function
+  structured_delegate: renorm.out
+
+- func: renorm_(Tensor(a!) self, Scalar p, int dim, Scalar maxnorm) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  variants: method
+  structured_delegate: renorm.out
+
+- func: unfold(Tensor(a) self, int dimension, int size, int step) -> Tensor(a)
+  variants: method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CPU, CUDA, Meta, MPS, MTIA: unfold
+    QuantizedCPU, QuantizedCUDA: unfold
+
+- func: unfold_backward(Tensor grad_in, SymInt[] input_sizes, int dim, int size, int step) -> Tensor
+  variants: function
+  dispatch:
+    CPU, CUDA, MPS: unfold_backward
+  autogen: unfold_backward.out
+
+- func: equal(Tensor self, Tensor other) -> bool
+  tags: [data_dependent_output, pointwise]
+  variants: method, function
+  dispatch:
+    CPU: cpu_equal
+    CUDA: cuda_equal
+    MPS: mps_equal
+    QuantizedCPU: equal_quantized_cpu
+
+- func: pow.Tensor_Tensor_out(Tensor self, Tensor exponent, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: pow_Tensor_Tensor_out
+    MPS: pow_tensor_tensor_out_mps
+  tags: pointwise
+
+- func: pow.Tensor_Tensor(Tensor self, Tensor exponent) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: pow.Tensor_Tensor_out
+  variants: method, function
+  tags: [core, pointwise]
+
+- func: pow.Scalar_out(Scalar self, Tensor exponent, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  dispatch:
+    CPU, CUDA: pow_Scalar_out
+    MPS: pow_Scalar_out_mps
+  tags: pointwise
+
+- func: pow.Scalar(Scalar self, Tensor exponent) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: pow.Scalar_out
+  tags: [core, pointwise]
+
+- func: pow.Tensor_Scalar_out(Tensor self, Scalar exponent, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: pow_Tensor_Scalar_out
+    SparseCPU, SparseCUDA: pow_out_sparse_scalar
+    MPS: pow_tensor_scalar_out_mps
+  tags: pointwise
+
+- func: pow.Tensor_Scalar(Tensor self, Scalar exponent) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: pow.Tensor_Scalar_out
+  variants: function, method
+  dispatch:
+    SparseCPU, SparseCUDA: pow_sparse_scalar
+  tags: [core, pointwise]
+
+- func: pow_.Scalar(Tensor(a!) self, Scalar exponent) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: pow.Tensor_Scalar_out
+  variants: method
+  tags: pointwise
+
+- func: pow_.Tensor(Tensor(a!) self, Tensor exponent) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: pow.Tensor_Tensor_out
+  variants: method
+  tags: pointwise
+
+- func: float_power.Tensor_Tensor_out(Tensor self, Tensor exponent, *, Tensor(a!) out) -> Tensor(a!)
+  tags: pointwise
+
+- func: float_power.Tensor_Tensor(Tensor self, Tensor exponent) -> Tensor
+  variants: function, method
+  tags: pointwise
+
+- func: float_power.Scalar_out(Scalar self, Tensor exponent, *, Tensor(a!) out) -> Tensor(a!)
+  tags: pointwise
+
+- func: float_power.Scalar(Scalar self, Tensor exponent) -> Tensor
+  tags: pointwise
+
+- func: float_power.Tensor_Scalar_out(Tensor self, Scalar exponent, *, Tensor(a!) out) -> Tensor(a!)
+  tags: pointwise
+
+- func: float_power.Tensor_Scalar(Tensor self, Scalar exponent) -> Tensor
+  variants: function, method
+  tags: pointwise
+
+- func: float_power_.Scalar(Tensor(a!) self, Scalar exponent) -> Tensor(a!)
+  variants: method
+  tags: pointwise
+
+- func: float_power_.Tensor(Tensor(a!) self, Tensor exponent) -> Tensor(a!)
+  variants: method
+  tags: pointwise
+
+- func: normal_(Tensor(a!) self, float mean=0, float std=1, *, Generator? generator=None) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  tags: nondeterministic_seeded
+  variants: method
+  dispatch:
+    CPU, CUDA: normal_
+    MPS: normal_mps_
+    Meta: normal_meta_
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: normal_sparse_csr_
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: normal_nested_
+  autogen: normal.out
+
+# Only used by the functionalization pass.
+# Normally, the codegen would be able to generate a normal() NativeFunction,
+# but we can't due to overload ambiguity with normal.Tensor_float.
+- func: normal_functional(Tensor self, float mean=0, float std=1, *, Generator? generator=None) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  tags: nondeterministic_seeded
+  dispatch:
+    CompositeExplicitAutograd: normal_functional
+
+- func: normal.Tensor_float_out(Tensor mean, float std=1, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!)
+  tags: nondeterministic_seeded
+  dispatch:
+    CPU, CUDA: normal_out
+    MPS: normal_mps_out
+    Meta: normal_out_meta
+
+- func: normal.Tensor_float(Tensor mean, float std=1, *, Generator? generator=None) -> Tensor
+  dispatch:
+    CPU, CUDA: normal
+    MPS: normal_mps
+    Meta: normal_meta
+  tags: nondeterministic_seeded
+
+- func: normal.float_Tensor_out(float mean, Tensor std, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA: normal_out
+    Meta: normal_out_meta
+    MPS: normal_mps_out
+  tags: nondeterministic_seeded
+
+- func: normal.float_Tensor(float mean, Tensor std, *, Generator? generator=None) -> Tensor
+  dispatch:
+    CPU, CUDA: normal
+    MPS: normal_mps
+    Meta: normal_meta
+  tags: nondeterministic_seeded
+
+- func: normal.Tensor_Tensor_out(Tensor mean, Tensor std, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA: normal_out
+    Meta: normal_out_meta
+    MPS: normal_mps_out
+  tags: nondeterministic_seeded
+
+- func: normal.Tensor_Tensor(Tensor mean, Tensor std, *, Generator? generator=None) -> Tensor
+  dispatch:
+    CPU, CUDA: normal
+    MPS: normal_mps
+    Meta: normal_meta
+  tags: nondeterministic_seeded
+
+- func: normal.float_float(float mean, float std, SymInt[] size, *, Generator? generator=None, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: normal
+  tags: nondeterministic_seeded
+
+- func: normal.float_float_out(float mean, float std, SymInt[] size, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: normal_out
+  tags: nondeterministic_seeded
+
+- func: alias(Tensor(a) self) -> Tensor(a)
+  variants: method, function
+  dispatch:
+    CompositeExplicitAutograd: alias
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: alias_nested
+  tags: core
+
+- func: _amp_foreach_non_finite_check_and_unscale_(Tensor(a!)[] self, Tensor(b!) found_inf, Tensor inv_scale) -> ()
+  variants: function
+  dispatch:
+    CUDA: _amp_foreach_non_finite_check_and_unscale_cuda_
+    CPU: _amp_foreach_non_finite_check_and_unscale_cpu_
+    MPS: _amp_foreach_non_finite_check_and_unscale_mps_
+  autogen: _amp_foreach_non_finite_check_and_unscale, _amp_foreach_non_finite_check_and_unscale.out
+
+- func: _amp_update_scale_(Tensor(a!) self, Tensor(b!) growth_tracker, Tensor found_inf, float scale_growth_factor, float scale_backoff_factor, int growth_interval) -> Tensor(a!)
+  variants: function
+  dispatch:
+    CUDA: _amp_update_scale_cuda_
+    CPU: _amp_update_scale_cpu_
+    MPS: _amp_update_scale_mps_
+  autogen: _amp_update_scale, _amp_update_scale.out
+
+    #- func: _cat(Tensor[] tensors, int dim=0) -> Tensor
+    #dispatch:
+    #CPU: _cat_cpu
+    #CUDA: cat_cuda
+    #MPS: cat_mps
+    #QuantizedCPU: cat_quantized_cpu
+
+    #- func: _cat.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!)
+    #dispatch:
+    #CPU: _cat_out_cpu
+  #CUDA: cat_out_cuda
+  #QuantizedCPU: cat_out_quantized_cpu
+
+- func: _foreach_add.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_add_scalar_kernel_slow
+    CUDA: foreach_tensor_add_scalar_kernel_cuda
+
+- func: _foreach_add_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_add_scalar_kernel_slow_
+    CUDA: foreach_tensor_add_scalar_kernel_cuda_
+    MTIA: foreach_tensor_add_scalar_kernel_mtia_
+  autogen: _foreach_add.Scalar_out
+
+- func: _foreach_add.List(Tensor[] self, Tensor[] other, *, Scalar alpha=1) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_add_list_kernel_slow
+    CUDA: foreach_tensor_add_list_kernel_cuda
+    MTIA: foreach_tensor_add_list_kernel_mtia
+
+- func: _foreach_add_.List(Tensor(a!)[] self, Tensor[] other, *, Scalar alpha=1) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_add_list_kernel_slow_
+    CUDA: foreach_tensor_add_list_kernel_cuda_
+    MTIA: foreach_tensor_add_list_kernel_mtia_
+  autogen: _foreach_add.List_out
+
+- func: _foreach_add.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_add_scalarlist_kernel_slow
+    CUDA: foreach_tensor_add_scalarlist_kernel_cuda
+
+- func: _foreach_add_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_add_scalarlist_kernel_slow_
+    CUDA: foreach_tensor_add_scalarlist_kernel_cuda_
+  autogen: _foreach_add.ScalarList_out
+
+- func: _foreach_add.Tensor(Tensor[] self, Tensor other, *, Scalar alpha=1) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_add_tensor_kernel_slow
+    CUDA: foreach_tensor_add_tensor_kernel_cuda
+
+- func: _foreach_add_.Tensor(Tensor(a!)[] self, Tensor other, *, Scalar alpha=1) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_add_tensor_kernel_slow_
+    CUDA: foreach_tensor_add_tensor_kernel_cuda_
+    MTIA: foreach_tensor_add_tensor_kernel_mtia_
+  autogen: _foreach_add.Tensor_out
+
+- func: _foreach_sub.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_sub_scalar_kernel_slow
+    CUDA: foreach_tensor_sub_scalar_kernel_cuda
+
+- func: _foreach_sub_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_sub_scalar_kernel_slow_
+    CUDA: foreach_tensor_sub_scalar_kernel_cuda_
+  autogen: _foreach_sub.Scalar_out
+
+- func: _foreach_sub.List(Tensor[] self, Tensor[] other, *, Scalar alpha=1) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_sub_list_kernel_slow
+    CUDA: foreach_tensor_sub_list_kernel_cuda
+
+- func: _foreach_sub_.List(Tensor(a!)[] self, Tensor[] other, *, Scalar alpha=1) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_sub_list_kernel_slow_
+    CUDA: foreach_tensor_sub_list_kernel_cuda_
+  autogen: _foreach_sub.List_out
+
+- func: _foreach_sub.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_sub_scalarlist_kernel_slow
+    CUDA: foreach_tensor_sub_scalarlist_kernel_cuda
+
+- func: _foreach_sub_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_sub_scalarlist_kernel_slow_
+    CUDA: foreach_tensor_sub_scalarlist_kernel_cuda_
+  autogen: _foreach_sub.ScalarList_out
+
+- func: _foreach_mul.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_mul_scalar_kernel_slow
+    CUDA: foreach_tensor_mul_scalar_kernel_cuda
+
+- func: _foreach_mul_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_mul_scalar_kernel_slow_
+    CUDA: foreach_tensor_mul_scalar_kernel_cuda_
+    MTIA: foreach_tensor_mul_scalar_kernel_mtia_
+  autogen: _foreach_mul.Scalar_out
+
+- func: _foreach_mul.List(Tensor[] self, Tensor[] other) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_mul_list_kernel_slow
+    CUDA: foreach_tensor_mul_list_kernel_cuda
+    MTIA: foreach_tensor_mul_list_kernel_mtia
+
+- func: _foreach_mul_.List(Tensor(a!)[] self, Tensor[] other) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_mul_list_kernel_slow_
+    CUDA: foreach_tensor_mul_list_kernel_cuda_
+    MTIA: foreach_tensor_mul_list_kernel_mtia_
+  autogen: _foreach_mul.List_out
+
+- func: _foreach_mul.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_mul_scalarlist_kernel_slow
+    CUDA: foreach_tensor_mul_scalarlist_kernel_cuda
+
+- func: _foreach_mul_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_mul_scalarlist_kernel_slow_
+    CUDA: foreach_tensor_mul_scalarlist_kernel_cuda_
+  autogen: _foreach_mul.ScalarList_out
+
+- func: _foreach_mul.Tensor(Tensor[] self, Tensor other) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_mul_tensor_kernel_slow
+    CUDA: foreach_tensor_mul_tensor_kernel_cuda
+    MTIA: foreach_tensor_mul_tensor_kernel_mtia
+
+- func: _foreach_mul_.Tensor(Tensor(a!)[] self, Tensor other) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_mul_tensor_kernel_slow_
+    CUDA: foreach_tensor_mul_tensor_kernel_cuda_
+    MTIA: foreach_tensor_mul_tensor_kernel_mtia_
+  autogen: _foreach_mul.Tensor_out
+
+- func: _foreach_div.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_div_scalar_kernel_slow
+    CUDA: foreach_tensor_div_scalar_kernel_cuda
+
+- func: _foreach_div_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_div_scalar_kernel_slow_
+    CUDA: foreach_tensor_div_scalar_kernel_cuda_
+  autogen: _foreach_div.Scalar_out
+
+- func: _foreach_div.List(Tensor[] self, Tensor[] other) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_div_list_kernel_slow
+    CUDA: foreach_tensor_div_list_kernel_cuda
+
+- func: _foreach_div_.List(Tensor(a!)[] self, Tensor[] other) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_div_list_kernel_slow_
+    CUDA: foreach_tensor_div_list_kernel_cuda_
+  autogen: _foreach_div.List_out
+
+- func: _foreach_div.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_div_scalarlist_kernel_slow
+    CUDA: foreach_tensor_div_scalarlist_kernel_cuda
+
+- func: _foreach_div_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_div_scalarlist_kernel_slow_
+    CUDA: foreach_tensor_div_scalarlist_kernel_cuda_
+  autogen: _foreach_div.ScalarList_out
+
+- func: _foreach_div.Tensor(Tensor[] self, Tensor other) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_div_tensor_kernel_slow
+    CUDA: foreach_tensor_div_tensor_kernel_cuda
+
+- func: _foreach_div_.Tensor(Tensor(a!)[] self, Tensor other) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_div_tensor_kernel_slow_
+    CUDA: foreach_tensor_div_tensor_kernel_cuda_
+  autogen: _foreach_div.Tensor_out
+
+- func: _foreach_clamp_max.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_max_scalar_kernel_slow
+    CUDA: foreach_tensor_clamp_max_scalar_kernel_cuda
+
+- func: _foreach_clamp_max_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_max_scalar_kernel_slow_
+    CUDA: foreach_tensor_clamp_max_scalar_kernel_cuda_
+  autogen: _foreach_clamp_max.Scalar_out
+
+- func: _foreach_clamp_max.List(Tensor[] self, Tensor[] other) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_max_list_kernel_slow
+    CUDA: foreach_tensor_clamp_max_list_kernel_cuda
+
+- func: _foreach_clamp_max_.List(Tensor(a!)[] self, Tensor[] other) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_max_list_kernel_slow_
+    CUDA: foreach_tensor_clamp_max_list_kernel_cuda_
+  autogen: _foreach_clamp_max.List_out
+
+- func: _foreach_clamp_max.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_max_scalarlist_kernel_slow
+    CUDA: foreach_tensor_clamp_max_scalarlist_kernel_cuda
+
+- func: _foreach_clamp_max_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_max_scalarlist_kernel_slow_
+    CUDA: foreach_tensor_clamp_max_scalarlist_kernel_cuda_
+  autogen: _foreach_clamp_max.ScalarList_out
+
+- func: _foreach_clamp_min.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_min_scalar_kernel_slow
+    CUDA: foreach_tensor_clamp_min_scalar_kernel_cuda
+
+- func: _foreach_clamp_min_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_min_scalar_kernel_slow_
+    CUDA: foreach_tensor_clamp_min_scalar_kernel_cuda_
+  autogen: _foreach_clamp_min.Scalar_out
+
+- func: _foreach_clamp_min.List(Tensor[] self, Tensor[] other) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_min_list_kernel_slow
+    CUDA: foreach_tensor_clamp_min_list_kernel_cuda
+
+- func: _foreach_clamp_min_.List(Tensor(a!)[] self, Tensor[] other) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_min_list_kernel_slow_
+    CUDA: foreach_tensor_clamp_min_list_kernel_cuda_
+  autogen: _foreach_clamp_min.List_out
+
+- func: _foreach_clamp_min.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_min_scalarlist_kernel_slow
+    CUDA: foreach_tensor_clamp_min_scalarlist_kernel_cuda
+
+- func: _foreach_clamp_min_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_min_scalarlist_kernel_slow_
+    CUDA: foreach_tensor_clamp_min_scalarlist_kernel_cuda_
+  autogen: _foreach_clamp_min.ScalarList_out
+
+# foreach_minimum/maximum dispatches to clamp_max/min
+- func: _foreach_maximum.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_min_scalar_kernel_slow
+    CUDA: foreach_tensor_clamp_min_scalar_kernel_cuda
+
+- func: _foreach_maximum_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_min_scalar_kernel_slow_
+    CUDA: foreach_tensor_clamp_min_scalar_kernel_cuda_
+  autogen: _foreach_maximum.Scalar_out
+
+# foreach_minimum/maximum dispatches to clamp_max/min
+- func: _foreach_maximum.List(Tensor[] self, Tensor[] other) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_min_list_kernel_slow
+    CUDA: foreach_tensor_clamp_min_list_kernel_cuda
+
+- func: _foreach_maximum_.List(Tensor(a!)[] self, Tensor[] other) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_min_list_kernel_slow_
+    CUDA: foreach_tensor_clamp_min_list_kernel_cuda_
+  autogen: _foreach_maximum.List_out
+
+# foreach_minimum/maximum dispatches to clamp_max/min
+- func: _foreach_maximum.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_min_scalarlist_kernel_slow
+    CUDA: foreach_tensor_clamp_min_scalarlist_kernel_cuda
+
+- func: _foreach_maximum_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_min_scalarlist_kernel_slow_
+    CUDA: foreach_tensor_clamp_min_scalarlist_kernel_cuda_
+  autogen: _foreach_maximum.ScalarList_out
+
+- func: _foreach_minimum.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_max_scalar_kernel_slow
+    CUDA: foreach_tensor_clamp_max_scalar_kernel_cuda
+
+- func: _foreach_minimum_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_max_scalar_kernel_slow_
+    CUDA: foreach_tensor_clamp_max_scalar_kernel_cuda_
+  autogen: _foreach_minimum.Scalar_out
+
+- func: _foreach_minimum.List(Tensor[] self, Tensor[] other) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_max_list_kernel_slow
+    CUDA: foreach_tensor_clamp_max_list_kernel_cuda
+
+- func: _foreach_minimum_.List(Tensor(a!)[] self, Tensor[] other) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_max_list_kernel_slow_
+    CUDA: foreach_tensor_clamp_max_list_kernel_cuda_
+  autogen: _foreach_minimum.List_out
+
+- func: _foreach_minimum.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_max_scalarlist_kernel_slow
+    CUDA: foreach_tensor_clamp_max_scalarlist_kernel_cuda
+
+- func: _foreach_minimum_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_clamp_max_scalarlist_kernel_slow_
+    CUDA: foreach_tensor_clamp_max_scalarlist_kernel_cuda_
+  autogen: _foreach_minimum.ScalarList_out
+
+- func: _foreach_addcdiv.Scalar(Tensor[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar value=1) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_addcdiv_scalar_slow
+    CUDA: foreach_tensor_addcdiv_scalar_cuda
+
+- func: _foreach_addcdiv.ScalarList(Tensor[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar[] scalars) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_addcdiv_scalarlist_slow
+    CUDA: foreach_tensor_addcdiv_scalarlist_cuda
+
+- func: _foreach_addcdiv.Tensor(Tensor[] self, Tensor[] tensor1, Tensor[] tensor2, Tensor scalars) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_addcdiv_tensor_slow
+    CUDA: foreach_tensor_addcdiv_tensor_cuda
+
+- func: _foreach_addcdiv_.Scalar(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar value=1) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_addcdiv_scalar_slow_
+    CUDA: foreach_tensor_addcdiv_scalar_cuda_
+  autogen: _foreach_addcdiv.Scalar_out
+
+- func: _foreach_addcdiv_.ScalarList(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar[] scalars) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_addcdiv_scalarlist_slow_
+    CUDA: foreach_tensor_addcdiv_scalarlist_cuda_
+  autogen: _foreach_addcdiv.ScalarList_out
+
+- func: _foreach_addcdiv_.Tensor(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Tensor scalars) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_addcdiv_tensor_slow_
+    CUDA: foreach_tensor_addcdiv_tensor_cuda_
+  autogen: _foreach_addcdiv.Tensor_out
+
+- func: _foreach_addcmul.Scalar(Tensor[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar value=1) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_addcmul_scalar_slow
+    CUDA: foreach_tensor_addcmul_scalar_cuda
+    MTIA: foreach_tensor_addcmul_scalar_mtia
+
+- func: _foreach_addcmul.ScalarList(Tensor[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar[] scalars) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_addcmul_scalarlist_slow
+    CUDA: foreach_tensor_addcmul_scalarlist_cuda
+
+- func: _foreach_addcmul.Tensor(Tensor[] self, Tensor[] tensor1, Tensor[] tensor2, Tensor scalars) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_addcmul_tensor_slow
+    CUDA: foreach_tensor_addcmul_tensor_cuda
+
+- func: _foreach_addcmul_.Scalar(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar value=1) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_addcmul_scalar_slow_
+    CUDA: foreach_tensor_addcmul_scalar_cuda_
+    MTIA: foreach_tensor_addcmul_scalar_mtia_
+  autogen: _foreach_addcmul.Scalar_out
+
+- func: _foreach_addcmul_.ScalarList(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar[] scalars) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_addcmul_scalarlist_slow_
+    CUDA: foreach_tensor_addcmul_scalarlist_cuda_
+  autogen: _foreach_addcmul.ScalarList_out
+
+- func: _foreach_addcmul_.Tensor(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Tensor scalars) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_addcmul_tensor_slow_
+    CUDA: foreach_tensor_addcmul_tensor_cuda_
+  autogen: _foreach_addcmul.Tensor_out
+
+- func: _foreach_abs(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_abs_slow
+    CUDA: foreach_tensor_abs_cuda
+    MTIA: foreach_tensor_abs_mtia
+
+- func: _foreach_abs_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_abs_slow_
+    CUDA: foreach_tensor_abs_cuda_
+    MTIA: foreach_tensor_abs_mtia_
+  autogen: _foreach_abs.out
+
+- func: _foreach_acos(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_acos_slow
+    CUDA: foreach_tensor_acos_cuda
+
+- func: _foreach_acos_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_acos_slow_
+    CUDA: foreach_tensor_acos_cuda_
+  autogen: _foreach_acos.out
+
+- func: _foreach_asin(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_asin_slow
+    CUDA: foreach_tensor_asin_cuda
+
+- func: _foreach_asin_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_asin_slow_
+    CUDA: foreach_tensor_asin_cuda_
+  autogen: _foreach_asin.out
+
+- func: _foreach_atan(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_atan_slow
+    CUDA: foreach_tensor_atan_cuda
+
+- func: _foreach_atan_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_atan_slow_
+    CUDA: foreach_tensor_atan_cuda_
+  autogen: _foreach_atan.out
+
+- func: _foreach_ceil(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_ceil_slow
+    CUDA: foreach_tensor_ceil_cuda
+
+- func: _foreach_ceil_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_ceil_slow_
+    CUDA: foreach_tensor_ceil_cuda_
+  autogen: _foreach_ceil.out
+
+- func: _foreach_cos(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_cos_slow
+    CUDA: foreach_tensor_cos_cuda
+
+- func: _foreach_cos_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_cos_slow_
+    CUDA: foreach_tensor_cos_cuda_
+  autogen: _foreach_cos.out
+
+- func: _foreach_cosh(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_cosh_slow
+    CUDA: foreach_tensor_cosh_cuda
+
+- func: _foreach_cosh_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_cosh_slow_
+    CUDA: foreach_tensor_cosh_cuda_
+  autogen: _foreach_cosh.out
+
+- func: _foreach_erf(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_erf_slow
+    CUDA: foreach_tensor_erf_cuda
+
+- func: _foreach_erf_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_erf_slow_
+    CUDA: foreach_tensor_erf_cuda_
+  autogen: _foreach_erf.out
+
+- func: _foreach_erfc(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_erfc_slow
+    CUDA: foreach_tensor_erfc_cuda
+
+- func: _foreach_erfc_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_erfc_slow_
+    CUDA: foreach_tensor_erfc_cuda_
+  autogen: _foreach_erfc.out
+
+- func: _foreach_exp(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_exp_slow
+    CUDA: foreach_tensor_exp_cuda
+
+- func: _foreach_exp_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_exp_slow_
+    CUDA: foreach_tensor_exp_cuda_
+  autogen: _foreach_exp.out
+
+- func: _foreach_expm1(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_expm1_slow
+    CUDA: foreach_tensor_expm1_cuda
+
+- func: _foreach_expm1_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_expm1_slow_
+    CUDA: foreach_tensor_expm1_cuda_
+  autogen: _foreach_expm1.out
+
+- func: _foreach_floor(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_floor_slow
+    CUDA: foreach_tensor_floor_cuda
+
+- func: _foreach_floor_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_floor_slow_
+    CUDA: foreach_tensor_floor_cuda_
+  autogen: _foreach_floor.out
+
+- func: _foreach_frac(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_frac_slow
+    CUDA: foreach_tensor_frac_cuda
+
+- func: _foreach_frac_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_frac_slow_
+    CUDA: foreach_tensor_frac_cuda_
+  autogen: _foreach_frac.out
+
+- func: _foreach_lerp.List(Tensor[] self, Tensor[] tensors1, Tensor[] weights) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensors are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_ternary_lerp_slow
+    CUDA: foreach_tensor_lerp_ternary_cuda
+  autogen: _foreach_lerp.List_out
+
+- func: _foreach_lerp_.List(Tensor(a!)[] self, Tensor[] tensors1, Tensor[] weights) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensors are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_ternary_lerp_slow_
+    CUDA: foreach_tensor_lerp_ternary_cuda_
+  autogen: _foreach_lerp.List_out
+
+- func: _foreach_lerp.Scalar(Tensor[] self, Tensor[] tensors1, Scalar weight) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensors are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_lerp_list_kernel_slow
+    CUDA: foreach_tensor_lerp_list_cuda
+  autogen: _foreach_lerp.Scalar_out
+
+- func: _foreach_lerp_.Scalar(Tensor(a!)[] self, Tensor[] tensors1, Scalar weight) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensors are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_lerp_list_kernel_slow_
+    CUDA: foreach_tensor_lerp_list_cuda_
+  autogen: _foreach_lerp.Scalar_out
+
+- func: _foreach_lerp.ScalarList(Tensor[] self, Tensor[] tensors1, Scalar[] weight) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensors are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_lerp_scalarlist_kernel_slow
+    CUDA: foreach_tensor_lerp_scalarlist_cuda
+  autogen: _foreach_lerp.ScalarList_out
+
+- func: _foreach_lerp_.ScalarList(Tensor(a!)[] self, Tensor[] tensors1, Scalar[] weight) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensors are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_lerp_scalarlist_kernel_slow_
+    CUDA: foreach_tensor_lerp_scalarlist_cuda_
+  autogen: _foreach_lerp.ScalarList_out
+
+- func: _foreach_lgamma(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_lgamma_slow
+    CUDA: foreach_tensor_lgamma_cuda
+
+- func: _foreach_lgamma_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_lgamma_slow_
+    CUDA: foreach_tensor_lgamma_cuda_
+  autogen: _foreach_lgamma.out
+
+- func: _foreach_log(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_log_slow
+    CUDA: foreach_tensor_log_cuda
+
+- func: _foreach_log_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_log_slow_
+    CUDA: foreach_tensor_log_cuda_
+  autogen: _foreach_log.out
+
+- func: _foreach_log10(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_log10_slow
+    CUDA: foreach_tensor_log10_cuda
+
+- func: _foreach_log10_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_log10_slow_
+    CUDA: foreach_tensor_log10_cuda_
+  autogen: _foreach_log10.out
+
+- func: _foreach_log1p(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_log1p_slow
+    CUDA: foreach_tensor_log1p_cuda
+
+- func: _foreach_log1p_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_log1p_slow_
+    CUDA: foreach_tensor_log1p_cuda_
+  autogen: _foreach_log1p.out
+
+- func: _foreach_log2(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_log2_slow
+    CUDA: foreach_tensor_log2_cuda
+
+- func: _foreach_log2_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_log2_slow_
+    CUDA: foreach_tensor_log2_cuda_
+  autogen: _foreach_log2.out
+
+- func: _foreach_max(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_max_slow
+    CUDA: foreach_tensor_max_cuda
+  autogen: _foreach_max.out
+
+- func: _foreach_neg(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_neg_slow
+    CUDA: foreach_tensor_neg_cuda
+
+- func: _foreach_neg_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_neg_slow_
+    CUDA: foreach_tensor_neg_cuda_
+  autogen: _foreach_neg.out
+
+- func: _foreach_norm.Scalar(Tensor[] self, Scalar ord=2, ScalarType? dtype=None) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_norm_slow
+    CUDA: foreach_tensor_norm_cuda
+    MTIA: foreach_tensor_norm_mtia
+  autogen: _foreach_norm.Scalar_out
+
+- func: _foreach_pow.List(Tensor[] self, Tensor[] exponent) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_pow_list_kernel_slow
+    CUDA: foreach_tensor_pow_list_kernel_cuda
+
+- func: _foreach_pow.Scalar(Tensor[] self, Scalar exponent) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_pow_scalar_kernel_slow
+    CUDA: foreach_tensor_pow_scalar_kernel_cuda
+
+- func: _foreach_pow.ScalarList(Tensor[] self, Scalar[] exponent) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_pow_scalarlist_kernel_slow
+    CUDA: foreach_tensor_pow_scalarlist_kernel_cuda
+
+- func: _foreach_pow.ScalarAndTensor(Scalar self, Tensor[] exponent) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_scalar_pow_list_kernel_slow
+    CUDA: foreach_scalar_pow_list_kernel_cuda
+
+- func: _foreach_pow_.List(Tensor(a!)[] self, Tensor[] exponent) -> ()
+  device_check: NoCheck
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_pow_list_kernel_slow_
+    CUDA: foreach_tensor_pow_list_kernel_cuda_
+  autogen: _foreach_pow.List_out
+
+- func: _foreach_pow_.Scalar(Tensor(a!)[] self, Scalar exponent) -> ()
+  device_check: NoCheck
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_pow_scalar_kernel_slow_
+    CUDA: foreach_tensor_pow_scalar_kernel_cuda_
+  autogen: _foreach_pow.Scalar_out
+
+- func: _foreach_pow_.ScalarList(Tensor(a!)[] self, Scalar[] exponent) -> ()
+  device_check: NoCheck
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_pow_scalarlist_kernel_slow_
+    CUDA: foreach_tensor_pow_scalarlist_kernel_cuda_
+  autogen: _foreach_pow.ScalarList_out
+
+- func: _foreach_reciprocal(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_reciprocal_slow
+    CUDA: foreach_tensor_reciprocal_cuda
+
+- func: _foreach_reciprocal_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_reciprocal_slow_
+    CUDA: foreach_tensor_reciprocal_cuda_
+  autogen: _foreach_reciprocal.out
+
+- func: _foreach_round(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_round_slow
+    CUDA: foreach_tensor_round_cuda
+
+- func: _foreach_round_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_round_slow_
+    CUDA: foreach_tensor_round_cuda_
+  autogen: _foreach_round.out
+
+- func: _foreach_rsqrt(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_rsqrt_slow
+    CUDA: foreach_tensor_rsqrt_cuda
+
+- func: _foreach_rsqrt_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_rsqrt_slow_
+    CUDA: foreach_tensor_rsqrt_cuda_
+  autogen: _foreach_rsqrt.out
+
+- func: _foreach_sigmoid(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_sigmoid_slow
+    CUDA: foreach_tensor_sigmoid_cuda
+
+- func: _foreach_sigmoid_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_sigmoid_slow_
+    CUDA: foreach_tensor_sigmoid_cuda_
+  autogen: _foreach_sigmoid.out
+
+- func: _foreach_sign(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_sign_slow
+    CUDA: foreach_tensor_sign_cuda
+
+- func: _foreach_sign_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_sign_slow_
+    CUDA: foreach_tensor_sign_cuda_
+  autogen: _foreach_sign.out
+
+- func: _foreach_sin(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_sin_slow
+    CUDA: foreach_tensor_sin_cuda
+
+- func: _foreach_sin_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_sin_slow_
+    CUDA: foreach_tensor_sin_cuda_
+  autogen: _foreach_sin.out
+
+- func: _foreach_sinh(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_sinh_slow
+    CUDA: foreach_tensor_sinh_cuda
+
+- func: _foreach_sinh_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_sinh_slow_
+    CUDA: foreach_tensor_sinh_cuda_
+  autogen: _foreach_sinh.out
+
+- func: _foreach_sqrt(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_sqrt_slow
+    CUDA: foreach_tensor_sqrt_cuda
+
+- func: _foreach_sqrt_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_sqrt_slow_
+    CUDA: foreach_tensor_sqrt_cuda_
+    MTIA: foreach_tensor_sqrt_mtia_
+  autogen: _foreach_sqrt.out
+
+- func: _foreach_tan(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_tan_slow
+    CUDA: foreach_tensor_tan_cuda
+
+- func: _foreach_tan_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_tan_slow_
+    CUDA: foreach_tensor_tan_cuda_
+  autogen: _foreach_tan.out
+
+- func: _foreach_tanh(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_tanh_slow
+    CUDA: foreach_tensor_tanh_cuda
+
+- func: _foreach_tanh_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_tanh_slow_
+    CUDA: foreach_tensor_tanh_cuda_
+  autogen: _foreach_tanh.out
+
+- func: _foreach_trunc(Tensor[] self) -> Tensor[]
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_trunc_slow
+    CUDA: foreach_tensor_trunc_cuda
+
+- func: _foreach_trunc_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_trunc_slow_
+    CUDA: foreach_tensor_trunc_cuda_
+  autogen: _foreach_trunc.out
+
+- func: _foreach_zero_(Tensor(a!)[] self) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_zero_slow_
+    CUDA: foreach_tensor_zero_cuda_
+  autogen: _foreach_zero, _foreach_zero.out
+
+- func: _foreach_copy_(Tensor(a!)[] self, Tensor[] src, bool non_blocking=False) -> ()
+  device_check: NoCheck   # foreach kernels fall back to slow path when tensor are on different devices
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: foreach_tensor_copy_list_kernel_slow_
+    CUDA: foreach_tensor_copy_list_kernel_cuda_
+    MTIA: foreach_tensor_copy_list_kernel_mtia_
+  autogen: _foreach_copy.out
+
+- func: _foreach_copy(Tensor[] self, Tensor[] src, bool non_blocking=False) -> Tensor[] self_out
+  device_check: NoCheck
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: _foreach_copy
+    MTIA: foreach_tensor_copy_list_kernel_mtia
+
+- func: bucketize.Tensor(Tensor self, Tensor boundaries, *, bool out_int32=False, bool right=False) -> Tensor
+  dispatch:
+    CPU: bucketize_cpu
+    CUDA: bucketize_cuda
+    MPS: bucketize_mps
+
+- func: bucketize.Tensor_out(Tensor self, Tensor boundaries, *, bool out_int32=False, bool right=False, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU: bucketize_out_cpu
+    CUDA: bucketize_out_cuda
+    MPS: bucketize_out_mps
+
+- func: bucketize.Scalar(Scalar self, Tensor boundaries, *, bool out_int32=False, bool right=False) -> Tensor
+  dispatch:
+    CPU: bucketize_cpu
+    CUDA: bucketize_cuda
+    MPS: bucketize_mps
+  autogen: bucketize.Scalar_out
+
+- func: searchsorted.Tensor(Tensor sorted_sequence, Tensor self, *, bool out_int32=False, bool right=False, str? side=None, Tensor? sorter=None) -> Tensor
+  dispatch:
+    CPU: searchsorted_cpu
+    CUDA: searchsorted_cuda
+    MPS: searchsorted_mps
+
+- func: searchsorted.Tensor_out(Tensor sorted_sequence, Tensor self, *, bool out_int32=False, bool right=False, str? side=None, Tensor? sorter=None, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU: searchsorted_out_cpu
+    CUDA: searchsorted_out_cuda
+    MPS: searchsorted_out_mps
+
+- func: searchsorted.Scalar(Tensor sorted_sequence, Scalar self, *, bool out_int32=False, bool right=False, str? side=None, Tensor? sorter=None) -> Tensor
+  dispatch:
+    CPU: searchsorted_cpu
+    CUDA: searchsorted_cuda
+    MPS: searchsorted_mps
+
+- func: searchsorted.Scalar_out(Tensor sorted_sequence, Scalar self, *, bool out_int32=False, bool right=False, str? side=None, Tensor? sorter=None, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU: searchsorted_out_cpu
+    CUDA: searchsorted_out_cuda
+    MPS: searchsorted_out_mps
+
+- func: _convert_indices_from_coo_to_csr(Tensor self, int size, *, bool out_int32=False) -> Tensor
+  structured_delegate: _convert_indices_from_coo_to_csr.out
+
+- func: _convert_indices_from_coo_to_csr.out(Tensor self, int size, *, bool out_int32=False, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  dispatch:
+    CPU: _convert_indices_from_coo_to_csr_structured_cpu
+    CUDA: _convert_indices_from_coo_to_csr_structured_cuda
+
+- func: _convert_indices_from_csr_to_coo(Tensor crow_indices, Tensor col_indices, *, bool out_int32=False, bool transpose=False) -> Tensor
+  structured_delegate: _convert_indices_from_csr_to_coo.out
+
+- func: _convert_indices_from_csr_to_coo.out(Tensor crow_indices, Tensor col_indices, *, bool out_int32=False, bool transpose=False, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  dispatch:
+    CPU: _convert_indices_from_csr_to_coo_structured_cpu
+    CUDA: _convert_indices_from_csr_to_coo_structured_cuda
+
+## NN wrappers
+
+- func: mse_loss.out(Tensor self, Tensor target, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  python_module: nn
+  dispatch:
+    CPU, CUDA: mse_loss_out
+    MPS: mse_loss_out_mps
+
+- func: mse_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: mse_loss.out
+  python_module: nn
+
+- func: mse_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, int reduction, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU, CUDA: mse_loss_backward_out
+    MPS: mse_loss_backward_out_mps
+
+- func: mse_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU, CUDA: mse_loss_backward
+    MPS: mse_loss_backward_mps
+
+- func: l1_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor
+  python_module: nn
+
+- func: multi_margin_loss.out(Tensor self, Tensor target, Scalar p=1, Scalar margin=1, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: multi_margin_loss_cpu_out
+    CUDA: multi_margin_loss_cuda_out
+
+- func: multi_margin_loss(Tensor self, Tensor target, Scalar p=1, Scalar margin=1, Tensor? weight=None, int reduction=Mean) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: multi_margin_loss_cpu
+    CUDA: multi_margin_loss_cuda
+
+- func: multi_margin_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Scalar p, Scalar margin, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: multi_margin_loss_cpu_backward_out
+    CUDA: multi_margin_loss_cuda_backward_out
+
+- func: multi_margin_loss_backward(Tensor grad_output, Tensor self, Tensor target, Scalar p, Scalar margin, Tensor? weight=None, int reduction=Mean) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: multi_margin_loss_cpu_backward
+    CUDA: multi_margin_loss_cuda_backward
+
+- func: multilabel_margin_loss.out(Tensor self, Tensor target, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+
+- func: multilabel_margin_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor
+  python_module: nn
+
+- func: multilabel_margin_loss_forward.output(Tensor self, Tensor target, int reduction, *, Tensor(a!) output, Tensor(b!) is_target) -> (Tensor(a!), Tensor(b!))
+  python_module: nn
+  dispatch:
+    CPU: multilabel_margin_loss_forward_out_cpu
+    CUDA: multilabel_margin_loss_forward_out_cuda
+
+- func: multilabel_margin_loss_forward(Tensor self, Tensor target, int reduction) -> (Tensor output, Tensor is_target)
+  python_module: nn
+  dispatch:
+    CPU: multilabel_margin_loss_forward_cpu
+    CUDA: multilabel_margin_loss_forward_cuda
+
+- func: multilabel_margin_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, int reduction, Tensor is_target, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: multilabel_margin_loss_backward_cpu_out
+    CUDA: multilabel_margin_loss_backward_cuda_out
+
+- func: multilabel_margin_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction, Tensor is_target) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: multilabel_margin_loss_backward_cpu
+    CUDA: multilabel_margin_loss_backward_cuda
+
+- func: nll_loss.out(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+
+- func: nll_loss_nd(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100) -> Tensor
+  python_module: nn
+  dispatch:
+    CompositeImplicitAutograd: nll_loss_nd_symint
+
+- func: nll_loss(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100) -> Tensor
+  python_module: nn
+  dispatch:
+    CompositeImplicitAutograd: nll_loss_symint
+
+- func: nll_loss_forward.output(Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, *, Tensor(a!) output, Tensor(b!) total_weight) -> (Tensor(a!), Tensor(b!))
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: nll_loss_forward_out_cpu
+    CUDA: nll_loss_forward_out_cuda
+    MPS: nll_loss_forward_out_mps
+
+- func: nll_loss_forward(Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index) -> (Tensor output, Tensor total_weight)
+  python_module: nn
+  structured_delegate: nll_loss_forward.output
+
+- func: nll_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: nll_loss_backward_out_cpu
+    CUDA: nll_loss_backward_out_cuda
+    MPS: nll_loss_backward_out_mps
+
+- func: nll_loss_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight) -> Tensor
+  python_module: nn
+  structured_delegate: nll_loss_backward.grad_input
+
+- func: nll_loss2d.out(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+
+- func: nll_loss2d(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100) -> Tensor
+  python_module: nn
+  dispatch:
+    CompositeImplicitAutograd: nll_loss2d_symint
+
+- func: nll_loss2d_forward.output(Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, *, Tensor(a!) output, Tensor(b!) total_weight) -> (Tensor(a!), Tensor(b!))
+  python_module: nn
+  dispatch:
+    CPU: nll_loss2d_forward_out_cpu
+    CUDA: nll_loss2d_forward_out_cuda
+    MPS: nll_loss2d_forward_out_mps
+
+- func: nll_loss2d_forward(Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index) -> (Tensor output, Tensor total_weight)
+  python_module: nn
+  dispatch:
+    CPU: nll_loss2d_forward_cpu
+    CUDA: nll_loss2d_forward_cuda
+    MPS: nll_loss2d_forward_mps
+
+- func: nll_loss2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: nll_loss2d_backward_out_cpu
+    CUDA: nll_loss2d_backward_out_cuda
+    MPS: nll_loss2d_backward_out_mps
+
+- func: nll_loss2d_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: nll_loss2d_backward_cpu
+    CUDA: nll_loss2d_backward_cuda
+    MPS: nll_loss2d_backward_mps
+
+- func: smooth_l1_loss.out(Tensor self, Tensor target, int reduction=Mean, float beta=1.0, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  python_module: nn
+  dispatch:
+    CPU, CUDA: smooth_l1_loss_out
+    MPS: smooth_l1_loss_out_mps
+
+- func: smooth_l1_loss(Tensor self, Tensor target, int reduction=Mean, float beta=1.0) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  structured_delegate: smooth_l1_loss.out
+  python_module: nn
+
+- func: smooth_l1_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, int reduction, float beta, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: smooth_l1_loss_backward_out
+    CUDA: smooth_l1_loss_backward_out
+    MPS: smooth_l1_loss_backward_out_mps
+
+- func: smooth_l1_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction, float beta) -> Tensor
+  python_module: nn
+  dispatch:
+    CompositeExplicitAutograd: smooth_l1_loss_backward
+
+- func: huber_loss.out(Tensor self, Tensor target, int reduction=Mean, float delta=1.0, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU, CUDA: huber_loss_out
+    MPS: huber_loss_out_mps
+
+- func: huber_loss(Tensor self, Tensor target, int reduction=Mean, float delta=1.0) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU, CUDA: huber_loss
+    MPS: huber_loss_mps
+
+- func: huber_loss_backward.out(Tensor grad_output, Tensor self, Tensor target, int reduction, float delta, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU, CUDA: huber_loss_backward_out
+    MPS: huber_loss_backward_out_mps
+
+- func: huber_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction, float delta) -> Tensor
+  python_module: nn
+  dispatch:
+    CompositeExplicitAutograd: huber_loss_backward
+
+- func: soft_margin_loss.out(Tensor self, Tensor target, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CompositeExplicitAutograd: soft_margin_loss_out
+
+- func: soft_margin_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor
+  python_module: nn
+  dispatch:
+    CompositeExplicitAutograd: soft_margin_loss
+
+- func: soft_margin_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, int reduction, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CompositeExplicitAutograd: soft_margin_loss_backward_out
+
+- func: soft_margin_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction) -> Tensor
+  python_module: nn
+  dispatch:
+    CompositeExplicitAutograd: soft_margin_loss_backward
+
+- func: elu.out(Tensor self, Scalar alpha=1, Scalar scale=1, Scalar input_scale=1, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  dispatch:
+    CPU, CUDA: elu_out
+    MPS: elu_out_mps
+
+- func: elu(Tensor self, Scalar alpha=1, Scalar scale=1, Scalar input_scale=1) -> Tensor
+  structured_delegate: elu.out
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  tags: [core, pointwise]
+
+- func: elu_backward.grad_input(Tensor grad_output, Scalar alpha, Scalar scale, Scalar input_scale, bool is_result, Tensor self_or_result, *, Tensor(a!) grad_input) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  python_module: nn
+  dispatch:
+    CPU, CUDA: elu_backward_out
+    MPS: elu_backward_out_mps
+
+- func: elu_backward(Tensor grad_output, Scalar alpha, Scalar scale, Scalar input_scale, bool is_result, Tensor self_or_result) -> Tensor
+  structured_delegate: elu_backward.grad_input
+  python_module: nn
+
+- func: elu_(Tensor(a!) self, Scalar alpha=1, Scalar scale=1, Scalar input_scale=1) -> Tensor(a!)
+  structured_delegate: elu.out
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+
+- func: glu.out(Tensor self, int dim=-1, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  python_module: nn
+  dispatch:
+    CPU, CUDA: glu_out
+    MPS: glu_out_mps
+
+- func: glu(Tensor self, int dim=-1) -> Tensor
+  structured_delegate: glu.out
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+
+- func: glu_backward.grad_input(Tensor grad_output, Tensor self, int dim, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: glu_backward_cpu_out
+    CUDA: glu_backward_cuda_out
+    MPS: glu_backward_mps_out
+
+- func: glu_backward(Tensor grad_output, Tensor self, int dim) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: glu_backward_cpu
+    CUDA: glu_backward_cuda
+    MPS: glu_backward_mps
+
+- func: glu_jvp(Tensor glu, Tensor x, Tensor dx, int dim) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU, CUDA: glu_jvp
+  autogen: glu_jvp.out
+
+- func: glu_backward_jvp(Tensor grad_x, Tensor grad_glu, Tensor x, Tensor dgrad_glu, Tensor dx, int dim) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU, CUDA: glu_backward_jvp
+  autogen: glu_backward_jvp.out
+
+- func: hardsigmoid.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  dispatch:
+    CPU, CUDA, MPS: hardsigmoid_out
+    QuantizedCPU: hardsigmoid_out_quantized_cpu
+
+- func: hardsigmoid(Tensor self) -> Tensor
+  structured_delegate: hardsigmoid.out
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  dispatch:
+    QuantizedCPU: hardsigmoid_quantized_cpu
+  tags: pointwise
+
+- func: hardsigmoid_(Tensor(a!) self) -> Tensor(a!)
+  structured_delegate: hardsigmoid.out
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+
+- func: hardsigmoid_backward.grad_input(Tensor grad_output, Tensor self, *, Tensor(a!) grad_input) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  python_module: nn
+  dispatch:
+    CPU, CUDA, MPS: hardsigmoid_backward_out
+
+- func: hardsigmoid_backward(Tensor grad_output, Tensor self) -> Tensor
+  structured_delegate: hardsigmoid_backward.grad_input
+  python_module: nn
+
+- func: hardtanh.out(Tensor self, Scalar min_val=-1, Scalar max_val=1, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  dispatch:
+    CPU, CUDA, MPS: hardtanh_out
+    QuantizedCPU: hardtanh_out_quantized_cpu
+
+- func: hardtanh(Tensor self, Scalar min_val=-1, Scalar max_val=1) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  dispatch:
+    CPU, CUDA, MPS: hardtanh
+    QuantizedCPU: hardtanh_quantized_cpu
+  tags: [pointwise, core]
+
+- func: hardtanh_backward.grad_input(Tensor grad_output, Tensor self, Scalar min_val, Scalar max_val, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU, CUDA: hardtanh_backward_out
+    MPS: hardtanh_backward_out_mps
+
+- func: hardtanh_backward(Tensor grad_output, Tensor self, Scalar min_val, Scalar max_val) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU, CUDA: hardtanh_backward
+    MPS: hardtanh_backward_mps
+
+- func: hardtanh_(Tensor(a!) self, Scalar min_val=-1, Scalar max_val=1) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  dispatch:
+    CPU, CUDA, MPS: hardtanh_
+    QuantizedCPU: hardtanh_quantized_cpu_
+
+- func: hardswish.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  dispatch:
+    CPU, CUDA, MPS: hardswish_out
+
+- func: hardswish(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  dispatch:
+    CPU, CUDA, MPS: hardswish
+
+- func: hardswish_(Tensor(a!) self) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  dispatch:
+    CPU, CUDA, MPS: hardswish_
+
+- func: hardswish_backward(Tensor grad_output, Tensor self) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU, CUDA, MPS: hardswish_backward
+  autogen: hardswish_backward.out
+
+- func: leaky_relu.out(Tensor self, Scalar negative_slope=0.01, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  dispatch:
+    CPU, CUDA, MPS: leaky_relu_out
+    QuantizedCPU: leaky_relu_out_quantized_cpu
+
+- func: leaky_relu(Tensor self, Scalar negative_slope=0.01) -> Tensor
+  structured_delegate: leaky_relu.out
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  dispatch:
+    QuantizedCPU: leaky_relu_quantized_cpu
+  tags: core
+
+- func: leaky_relu_backward.grad_input(Tensor grad_output, Tensor self, Scalar negative_slope, bool self_is_result, *, Tensor(a!) grad_input) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  python_module: nn
+  dispatch:
+    CPU, CUDA, MPS: leaky_relu_backward_out
+
+- func: leaky_relu_backward(Tensor grad_output, Tensor self, Scalar negative_slope, bool self_is_result) -> Tensor
+  structured_delegate: leaky_relu_backward.grad_input
+  python_module: nn
+
+- func: leaky_relu_(Tensor(a!) self, Scalar negative_slope=0.01) -> Tensor(a!)
+  structured_delegate: leaky_relu.out
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  dispatch:
+    QuantizedCPU: leaky_relu_quantized_cpu_
+
+- func: log_sigmoid.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+
+- func: log_sigmoid(Tensor self) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+
+- func: log_sigmoid_forward.output(Tensor self, *, Tensor(a!) output, Tensor(b!) buffer) -> (Tensor(a!), Tensor(b!))
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  dispatch:
+    CPU: log_sigmoid_forward_out_cpu
+    CUDA: log_sigmoid_forward_out_cuda
+    MPS: log_sigmoid_forward_out_mps
+
+- func: log_sigmoid_forward(Tensor self) -> (Tensor output, Tensor buffer)
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  dispatch:
+    CPU: log_sigmoid_forward_cpu
+    CUDA: log_sigmoid_forward_cuda
+    MPS: log_sigmoid_forward_mps
+
+- func: log_sigmoid_backward.grad_input(Tensor grad_output, Tensor self, Tensor buffer, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: log_sigmoid_backward_cpu_out
+    CUDA: log_sigmoid_backward_cuda_out
+    MPS: log_sigmoid_backward_mps_out
+
+- func: log_sigmoid_backward(Tensor grad_output, Tensor self, Tensor buffer) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: log_sigmoid_backward_cpu
+    CUDA: log_sigmoid_backward_cuda
+    MPS: log_sigmoid_backward_mps
+
+- func: rrelu_with_noise.out(Tensor self, Tensor(b!) noise, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  tags: nondeterministic_seeded
+  dispatch:
+    CPU: rrelu_with_noise_out_cpu
+    CUDA: rrelu_with_noise_out_cuda
+
+- func: rrelu_with_noise(Tensor self, Tensor(b!) noise, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: rrelu_with_noise_cpu
+    CUDA: rrelu_with_noise_cuda
+  tags: nondeterministic_seeded
+  autogen: rrelu_with_noise_functional
+
+- func: rrelu_with_noise_backward(Tensor grad_output, Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, bool self_is_result) -> Tensor
+  python_module: nn
+  dispatch:
+    CompositeExplicitAutograd: rrelu_with_noise_backward
+  autogen: rrelu_with_noise_backward.out
+
+- func: rrelu_with_noise_(Tensor(a!) self, Tensor(b!) noise, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor(a!)
+  python_module: nn
+  tags: nondeterministic_seeded
+  dispatch:
+    CPU: rrelu_with_noise_cpu_
+    CUDA: rrelu_with_noise_cuda_
+
+- func: softplus.out(Tensor self, Scalar beta=1, Scalar threshold=20, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  dispatch:
+    CPU, CUDA: softplus_out
+    MPS: softplus_out_mps
+
+- func: softplus(Tensor self, Scalar beta=1, Scalar threshold=20) -> Tensor
+  structured_delegate: softplus.out
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  tags: pointwise
+
+- func: softplus_backward.grad_input(Tensor grad_output, Tensor self, Scalar beta, Scalar threshold, *, Tensor(a!) grad_input) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  python_module: nn
+  dispatch:
+    CPU, CUDA: softplus_backward_out
+    MPS: softplus_backward_out_mps
+
+- func: softplus_backward(Tensor grad_output, Tensor self, Scalar beta, Scalar threshold) -> Tensor
+  structured_delegate: softplus_backward.grad_input
+  python_module: nn
+
+- func: softshrink.out(Tensor self, Scalar lambd=0.5, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  dispatch:
+    CPU, CUDA, MPS: softshrink_out
+
+- func: softshrink(Tensor self, Scalar lambd=0.5) -> Tensor
+  structured_delegate: softshrink.out
+  device_check: NoCheck   # TensorIterator
+  python_module: nn
+  tags: pointwise
+
+- func: softshrink_backward.grad_input(Tensor grad_output, Tensor self, Scalar lambd, *, Tensor(a!) grad_input) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  python_module: nn
+  dispatch:
+    CPU, CUDA, MPS: softshrink_backward_out
+
+- func: softshrink_backward(Tensor grad_output, Tensor self, Scalar lambd) -> Tensor
+  structured_delegate: softshrink_backward.grad_input
+  python_module: nn
+
+- func: adaptive_avg_pool2d.out(Tensor self, SymInt[2] output_size, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: adaptive_avg_pool2d_out_cpu
+    CUDA: adaptive_avg_pool2d_out_cuda
+    MPS: adaptive_avg_pool2d_out_mps
+    MkldnnCPU: mkldnn_adaptive_avg_pool2d_out_stub
+
+- func: adaptive_avg_pool2d(Tensor self, SymInt[2] output_size) -> Tensor
+  python_module: nn
+  dispatch:
+    CompositeImplicitAutograd: adaptive_avg_pool2d_symint
+
+- func: mkldnn_adaptive_avg_pool2d(Tensor self, int[2] output_size) -> Tensor
+  dispatch:
+    MkldnnCPU: mkldnn_adaptive_avg_pool2d
+
+- func: mkldnn_adaptive_avg_pool2d.out(Tensor self, int[2] output_size, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    MkldnnCPU: mkldnn_adaptive_avg_pool2d_out
+
+- func: mkldnn_adaptive_avg_pool2d_backward(Tensor grad_output, Tensor self) -> Tensor
+  dispatch:
+    MkldnnCPU: mkldnn_adaptive_avg_pool2d_backward
+  autogen: mkldnn_adaptive_avg_pool2d_backward.out
+
+- func: _adaptive_avg_pool2d(Tensor self, SymInt[2] output_size) -> Tensor
+  dispatch:
+    CPU: adaptive_avg_pool2d_cpu
+    CUDA: adaptive_avg_pool2d_cuda
+    MPS: adaptive_avg_pool2d_mps
+    QuantizedCPU: adaptive_avg_pool2d_quantized_cpu
+    QuantizedCUDA: adaptive_avg_pool2d_quantized_cuda
+  autogen: _adaptive_avg_pool2d.out
+  tags: core
+
+- func: _adaptive_avg_pool2d_backward(Tensor grad_output, Tensor self) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: adaptive_avg_pool2d_backward_cpu
+    CUDA: adaptive_avg_pool2d_backward_cuda
+    MPS: adaptive_avg_pool2d_backward_mps
+  autogen: _adaptive_avg_pool2d_backward.out
+  tags: core
+
+- func: adaptive_avg_pool3d.out(Tensor self, SymInt[3] output_size, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: adaptive_avg_pool3d_out_cpu
+    CUDA: adaptive_avg_pool3d_out_cuda
+    QuantizedCPU: adaptive_avg_pool3d_out_quantized_cpu
+
+- func: adaptive_avg_pool3d(Tensor self, SymInt[3] output_size) -> Tensor
+  python_module: nn
+  dispatch:
+    CompositeImplicitAutograd: adaptive_avg_pool3d_symint
+
+- func: _adaptive_avg_pool3d(Tensor self, SymInt[3] output_size) -> Tensor
+  dispatch:
+    CPU: adaptive_avg_pool3d_cpu
+    CUDA: adaptive_avg_pool3d_cuda
+    QuantizedCPU: adaptive_avg_pool3d_quantized_cpu
+  autogen: _adaptive_avg_pool3d.out
+  tags: core
+
+- func: adaptive_avg_pool3d_backward.grad_input(Tensor grad_output, Tensor self, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: adaptive_avg_pool3d_backward_out_cpu
+    CUDA: adaptive_avg_pool3d_backward_out_cuda
+
+- func: _adaptive_avg_pool3d_backward(Tensor grad_output, Tensor self) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: adaptive_avg_pool3d_backward_cpu
+    CUDA: adaptive_avg_pool3d_backward_cuda
+  autogen: _adaptive_avg_pool3d_backward.out
+
+# Return: (Tensor output, Tensor indices)
+- func: adaptive_max_pool2d.out(Tensor self, int[2] output_size, *, Tensor(a!) out, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!))
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: adaptive_max_pool2d_out_cpu
+    CUDA: adaptive_max_pool2d_out_cuda
+    MPS: adaptive_max_pool2d_out_mps
+
+# Return: (Tensor output, Tensor indices)
+- func: adaptive_max_pool2d(Tensor self, int[2] output_size) -> (Tensor, Tensor)
+  python_module: nn
+  structured_delegate: adaptive_max_pool2d.out
+
+- func: adaptive_max_pool2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: adaptive_max_pool2d_backward_out_cpu
+    CUDA: adaptive_max_pool2d_backward_out_cuda
+    MPS: adaptive_max_pool2d_backward_out_mps
+
+- func: adaptive_max_pool2d_backward(Tensor grad_output, Tensor self, Tensor indices) -> Tensor
+  python_module: nn
+  structured_delegate: adaptive_max_pool2d_backward.grad_input
+
+# Return: (Tensor output, Tensor indices)
+- func: adaptive_max_pool3d.out(Tensor self, int[3] output_size, *, Tensor(a!) out, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!))
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: adaptive_max_pool3d_out_cpu
+    CUDA: adaptive_max_pool3d_out_cuda
+
+# Return: (Tensor output, Tensor indices)
+- func: adaptive_max_pool3d(Tensor self, int[3] output_size) -> (Tensor, Tensor)
+  python_module: nn
+  structured_delegate: adaptive_max_pool3d.out
+
+- func: adaptive_max_pool3d_backward.grad_input(Tensor grad_output, Tensor self, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: adaptive_max_pool3d_backward_out_cpu
+    CUDA: adaptive_max_pool3d_backward_out_cuda
+
+- func: adaptive_max_pool3d_backward(Tensor grad_output, Tensor self, Tensor indices) -> Tensor
+  python_module: nn
+  structured_delegate: adaptive_max_pool3d_backward.grad_input
+
+- func: avg_pool2d.out(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  precomputed:
+  - kernel_size -> int kH, int kW
+  - stride -> int dH, int dW
+  - padding -> int padH, int padW
+  dispatch:
+    CPU: avg_pool2d_out_cpu
+    CUDA: avg_pool2d_out_cuda
+    MPS: avg_pool2d_out_mps
+    MkldnnCPU: mkldnn_avg_pool2d_out
+
+- func: avg_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None) -> Tensor
+  python_module: nn
+  structured_delegate: avg_pool2d.out
+  dispatch:
+    MkldnnCPU: mkldnn_avg_pool2d
+    QuantizedCPU: avg_pool2d_quantized_cpu
+  tags: core
+
+- func: avg_pool2d_backward.grad_input(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, bool ceil_mode, bool count_include_pad, int? divisor_override, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: avg_pool2d_backward_out_cpu
+    CUDA: avg_pool2d_backward_out_cuda
+    MPS: avg_pool2d_backward_out_mps
+    MkldnnCPU: mkldnn_avg_pool2d_backward_out
+
+- func: avg_pool2d_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, bool ceil_mode, bool count_include_pad, int? divisor_override) -> Tensor
+  python_module: nn
+  structured_delegate: avg_pool2d_backward.grad_input
+  dispatch:
+    MkldnnCPU: mkldnn_avg_pool2d_backward
+  tags: core
+
+- func: avg_pool3d.out(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: avg_pool3d_out_cpu
+    CUDA: avg_pool3d_out_cuda
+    MPS: avg_pool3d_out_mps
+    MkldnnCPU: mkldnn_avg_pool3d_out
+
+- func: avg_pool3d(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None) -> Tensor
+  python_module: nn
+  structured_delegate: avg_pool3d.out
+  dispatch:
+    MkldnnCPU: mkldnn_avg_pool3d
+    QuantizedCPU: avg_pool3d_quantized_cpu
+  tags: core
+
+- func: avg_pool3d_backward.grad_input(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] stride, int[3] padding, bool ceil_mode, bool count_include_pad, int? divisor_override, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: avg_pool3d_backward_out_cpu
+    CUDA: avg_pool3d_backward_out_cuda
+    MPS: avg_pool3d_backward_out_mps
+    MkldnnCPU: mkldnn_avg_pool3d_backward_out
+
+- func: avg_pool3d_backward(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] stride, int[3] padding, bool ceil_mode, bool count_include_pad, int? divisor_override) -> Tensor
+  python_module: nn
+  structured_delegate: avg_pool3d_backward.grad_input
+  dispatch:
+    MkldnnCPU: mkldnn_avg_pool3d_backward
+
+# Return: (Tensor output, Tensor indices)
+- func: fractional_max_pool2d.output(Tensor self, int[2] kernel_size, int[2] output_size, Tensor random_samples, *, Tensor(a!) output, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!))
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: fractional_max_pool2d_out_cpu
+    CUDA: fractional_max_pool2d_out_cuda
+
+# Return: (Tensor output, Tensor indices)
+- func: fractional_max_pool2d(Tensor self, int[2] kernel_size, int[2] output_size, Tensor random_samples) -> (Tensor, Tensor)
+  python_module: nn
+  structured_delegate: fractional_max_pool2d.output
+
+- func: fractional_max_pool2d_backward.grad_input(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] output_size, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: fractional_max_pool2d_backward_cpu
+    CUDA: fractional_max_pool2d_backward_cuda
+
+- func: fractional_max_pool2d_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] output_size, Tensor indices) -> Tensor
+  python_module: nn
+  structured_delegate: fractional_max_pool2d_backward.grad_input
+
+# Return: (Tensor output, Tensor indices)
+- func: fractional_max_pool3d.output(Tensor self, int[3] kernel_size, int[3] output_size, Tensor random_samples, *, Tensor(a!) output, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!))
+  python_module: nn
+  structured: True
+  precomputed:
+  - kernel_size -> int poolSizeT, int poolSizeH, int poolSizeW
+  - output_size -> int outputT, int outputH, int outputW
+  - int numBatch, int numPlanes, int inputT, int inputH, int inputW
+  dispatch:
+    CPU: fractional_max_pool3d_out_cpu
+    CUDA: fractional_max_pool3d_out_cuda
+
+# Return: (Tensor output, Tensor indices)
+- func: fractional_max_pool3d(Tensor self, int[3] kernel_size, int[3] output_size, Tensor random_samples) -> (Tensor, Tensor)
+  python_module: nn
+  structured_delegate: fractional_max_pool3d.output
+
+- func: fractional_max_pool3d_backward.grad_input(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] output_size, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: fractional_max_pool3d_backward_out_cpu
+    CUDA: fractional_max_pool3d_backward_out_cuda
+
+- func: fractional_max_pool3d_backward(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] output_size, Tensor indices) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: fractional_max_pool3d_backward_cpu
+    CUDA: fractional_max_pool3d_backward_cuda
+
+# Return: (Tensor output, Tensor indices)
+- func: max_pool2d_with_indices.out(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False, *, Tensor(a!) out, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!))
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: max_pool2d_with_indices_out_cpu
+    CUDA: max_pool2d_with_indices_out_cuda
+    MPS: max_pool2d_with_indices_out_mps
+
+# Return: (Tensor output, Tensor indices)
+- func: max_pool2d_with_indices(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> (Tensor, Tensor)
+  python_module: nn
+  structured_delegate: max_pool2d_with_indices.out
+  tags: core
+
+- func: max_pool2d_with_indices_backward.grad_input(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, int[2] dilation, bool ceil_mode, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: max_pool2d_with_indices_backward_out_cpu
+    CUDA: max_pool2d_with_indices_backward_out_cuda
+    MPS: max_pool2d_with_indices_backward_out_mps
+
+- func: max_pool2d_with_indices_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, int[2] dilation, bool ceil_mode, Tensor indices) -> Tensor
+  python_module: nn
+  structured_delegate: max_pool2d_with_indices_backward.grad_input
+  tags: core
+
+# Return: (Tensor output, Tensor indices)
+- func: max_pool3d_with_indices.out(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False, *, Tensor(a!) out, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!))
+  python_module: nn
+  dispatch:
+    CPU: max_pool3d_with_indices_out_cpu
+    CUDA: max_pool3d_with_indices_out_cuda
+    MPS: max_pool3d_with_indices_out_mps
+
+# Return: (Tensor output, Tensor indices)
+- func: max_pool3d_with_indices(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> (Tensor, Tensor)
+  python_module: nn
+  dispatch:
+    CPU: max_pool3d_with_indices_cpu
+    CUDA: max_pool3d_with_indices_cuda
+    MPS: max_pool3d_with_indices_mps
+  tags: core
+
+- func: max_pool3d_with_indices_backward.grad_input(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] stride, int[3] padding, int[3] dilation, bool ceil_mode, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: max_pool3d_with_indices_backward_out_cpu
+    CUDA: max_pool3d_with_indices_backward_out_cuda
+    MPS: max_pool3d_with_indices_backward_out_mps
+
+- func: max_pool3d_with_indices_backward(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] stride, int[3] padding, int[3] dilation, bool ceil_mode, Tensor indices) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: max_pool3d_with_indices_backward_cpu
+    CUDA: max_pool3d_with_indices_backward_cuda
+    MPS: max_pool3d_with_indices_backward_mps
+
+- func: max_unpool2d.out(Tensor self, Tensor indices, SymInt[2] output_size, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: max_unpooling2d_forward_out_cpu
+    CUDA: max_unpooling2d_forward_out_cuda
+    MPS: max_unpooling2d_forward_out_mps
+
+- func: max_unpool2d(Tensor self, Tensor indices, SymInt[2] output_size) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: max_unpooling2d_forward_cpu
+    CUDA: max_unpooling2d_forward_cuda
+    MPS: max_unpooling2d_forward_mps
+
+- func: max_unpool3d.out(Tensor self, Tensor indices, SymInt[3] output_size, int[3] stride, int[3] padding, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: max_unpooling3d_forward_out_cpu
+    CUDA: max_unpooling3d_forward_out_cuda
+    MPS: max_unpooling3d_forward_out_mps
+
+- func: max_unpool3d(Tensor self, Tensor indices, SymInt[3] output_size, int[3] stride, int[3] padding) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: max_unpooling3d_forward_cpu
+    CUDA: max_unpooling3d_forward_cuda
+    MPS: max_unpooling3d_forward_mps
+
+- func: reflection_pad1d.out(Tensor self, SymInt[2] padding, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: reflection_pad1d_out_cpu
+    QuantizedCPU: reflection_pad1d_out_quantized_cpu
+    CUDA: reflection_pad1d_out_cuda
+    MPS: reflection_pad1d_out_mps
+
+- func: reflection_pad1d(Tensor self, SymInt[2] padding) -> Tensor
+  python_module: nn
+  structured_delegate: reflection_pad1d.out
+  tags: core
+
+- func: reflection_pad1d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[2] padding, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: reflection_pad1d_backward_out_cpu
+    CUDA: reflection_pad1d_backward_out_cuda
+    MPS: reflection_pad1d_backward_out_mps
+
+- func: reflection_pad1d_backward(Tensor grad_output, Tensor self, SymInt[2] padding) -> Tensor
+  python_module: nn
+  structured_delegate: reflection_pad1d_backward.grad_input
+
+- func: reflection_pad2d.out(Tensor self, SymInt[4] padding, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU, QuantizedCPU: reflection_pad2d_out_cpu
+    CUDA: reflection_pad2d_out_cuda
+    MPS: reflection_pad2d_out_mps
+
+- func: reflection_pad2d(Tensor self, SymInt[4] padding) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: reflection_pad2d_cpu
+    QuantizedCPU: reflection_pad2d_quantized_cpu
+    CUDA: reflection_pad2d_cuda
+    MPS: reflection_pad2d_mps
+  tags: core
+
+- func: reflection_pad2d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[4] padding, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: reflection_pad2d_backward_out_cpu
+    CUDA: reflection_pad2d_backward_out_cuda
+    MPS: reflection_pad2d_backward_out_mps
+
+- func: reflection_pad2d_backward(Tensor grad_output, Tensor self, SymInt[4] padding) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: reflection_pad2d_backward_cpu
+    CUDA: reflection_pad2d_backward_cuda
+    MPS: reflection_pad2d_backward_mps
+
+- func: reflection_pad3d.out(Tensor self, SymInt[6] padding, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: reflection_pad3d_out_cpu
+    CUDA: reflection_pad3d_out_cuda
+    MPS: reflection_pad3d_out_mps
+
+- func: reflection_pad3d(Tensor self, SymInt[6] padding) -> Tensor
+  python_module: nn
+  structured_delegate: reflection_pad3d.out
+  tags: core
+
+- func: reflection_pad3d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[6] padding, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: reflection_pad3d_backward_out_cpu
+    CUDA: reflection_pad3d_backward_out_cuda
+    MPS: reflection_pad3d_backward_out_mps
+
+- func: reflection_pad3d_backward(Tensor grad_output, Tensor self, SymInt[6] padding) -> Tensor
+  python_module: nn
+  structured_delegate: reflection_pad3d_backward.grad_input
+
+- func: replication_pad1d.out(Tensor self, SymInt[2] padding, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: replication_pad1d_out_cpu
+    CUDA: replication_pad1d_out_cuda
+    MPS: replication_pad1d_out_mps
+
+- func: replication_pad1d(Tensor self, SymInt[2] padding) -> Tensor
+  python_module: nn
+  structured_delegate: replication_pad1d.out
+
+- func: replication_pad1d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[2] padding, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: replication_pad1d_backward_out_cpu
+    CUDA: replication_pad1d_backward_out_cuda
+    MPS: replication_pad1d_backward_out_mps
+
+- func: replication_pad1d_backward(Tensor grad_output, Tensor self, SymInt[2] padding) -> Tensor
+  python_module: nn
+  structured_delegate: replication_pad1d_backward.grad_input
+
+- func: replication_pad2d.out(Tensor self, SymInt[4] padding, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: replication_pad2d_out_cpu
+    CUDA: replication_pad2d_out_cuda
+    MPS: replication_pad2d_out_mps
+
+- func: replication_pad2d(Tensor self, SymInt[4] padding) -> Tensor
+  python_module: nn
+  structured_delegate: replication_pad2d.out
+  tags: core
+
+- func: replication_pad2d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[4] padding, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: replication_pad2d_backward_out_cpu
+    CUDA: replication_pad2d_backward_out_cuda
+    MPS: replication_pad2d_backward_out_mps
+
+- func: replication_pad2d_backward(Tensor grad_output, Tensor self, SymInt[4] padding) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: replication_pad2d_backward_cpu
+    CUDA: replication_pad2d_backward_cuda
+    MPS: replication_pad2d_backward_mps
+
+- func: replication_pad3d.out(Tensor self, SymInt[6] padding, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: replication_pad3d_out_cpu
+    CUDA: replication_pad3d_out_cuda
+    MPS: replication_pad3d_out_mps
+
+- func: replication_pad3d(Tensor self, SymInt[6] padding) -> Tensor
+  python_module: nn
+  structured_delegate: replication_pad3d.out
+  tags: core
+
+
+- func: replication_pad3d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[6] padding, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: replication_pad3d_backward_out_cpu
+    CUDA: replication_pad3d_backward_out_cuda
+    MPS: replication_pad3d_backward_out_mps
+
+- func: replication_pad3d_backward(Tensor grad_output, Tensor self, SymInt[6] padding) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: replication_pad3d_backward_cpu
+    CUDA: replication_pad3d_backward_cuda
+    MPS: replication_pad3d_backward_mps
+
+- func: _pad_circular(Tensor self, SymInt[] pad) -> Tensor
+  python_module: nn
+  dispatch:
+    CompositeImplicitAutograd: _pad_circular_symint
+
+- func: _pad_enum(Tensor self, SymInt[] pad, int mode, float? value=None) -> Tensor
+  python_module: nn
+  dispatch:
+    CompositeImplicitAutograd: _pad_enum_symint
+
+- func: pad(Tensor self, SymInt[] pad, str mode="constant", float? value=None) -> Tensor
+  python_module: nn
+  dispatch:
+    CompositeImplicitAutograd: pad_symint
+
+- func: upsample_linear1d.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor
+  python_module: nn
+  autogen: upsample_linear1d.vec_out
+
+- func: upsample_bilinear2d.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor
+  python_module: nn
+  autogen: upsample_bilinear2d.vec_out
+  tags: core
+
+- func: _upsample_bilinear2d_aa.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor
+  python_module: nn
+  autogen: _upsample_bilinear2d_aa.vec_out
+
+- func: upsample_trilinear3d.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor
+  python_module: nn
+  autogen: upsample_trilinear3d.vec_out
+
+- func: upsample_bicubic2d.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor
+  python_module: nn
+  autogen: upsample_bicubic2d.vec_out
+
+- func: _upsample_bicubic2d_aa.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor
+  python_module: nn
+  autogen: _upsample_bicubic2d_aa.vec_out
+
+- func: upsample_nearest1d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor
+  python_module: nn
+  autogen: upsample_nearest1d.vec_out
+
+- func: _upsample_nearest_exact1d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor
+  python_module: nn
+  autogen: _upsample_nearest_exact1d.vec_out
+
+- func: upsample_nearest2d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor
+  python_module: nn
+  autogen: upsample_nearest2d.vec_out
+  tags: core
+
+- func: _upsample_nearest_exact2d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor
+  python_module: nn
+  autogen: _upsample_nearest_exact2d.vec_out
+
+- func: upsample_nearest3d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor
+  python_module: nn
+  autogen: upsample_nearest3d.vec_out
+
+- func: _upsample_nearest_exact3d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor
+  python_module: nn
+  autogen: _upsample_nearest_exact3d.vec_out
+
+# NOTE: all of the non-"vec" upsample overloads are only kept for backward compatibility.
+- func: upsample_linear1d.out(Tensor self, SymInt[1] output_size, bool align_corners, float? scales=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: upsample_linear1d_out_cpu
+    CUDA: upsample_linear1d_out_cuda
+    MPS: upsample_linear1d_out_mps
+
+- func: upsample_linear1d(Tensor self, SymInt[1] output_size, bool align_corners, float? scales=None) -> Tensor
+  python_module: nn
+  structured_delegate: upsample_linear1d.out
+
+- func: upsample_linear1d_backward.grad_input(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, bool align_corners, float? scales=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: upsample_linear1d_backward_out_cpu
+    CUDA: upsample_linear1d_backward_out_cuda
+    MPS: upsample_linear1d_backward_out_mps
+
+- func: upsample_linear1d_backward(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, bool align_corners, float? scales=None) -> Tensor
+  python_module: nn
+  structured_delegate: upsample_linear1d_backward.grad_input
+
+- func: upsample_bilinear2d.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: upsample_bilinear2d_out_cpu
+    CUDA: upsample_bilinear2d_out_cuda
+    MPS: upsample_bilinear2d_out_mps
+
+- func: upsample_bilinear2d(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+  python_module: nn
+  structured_delegate: upsample_bilinear2d.out
+  dispatch:
+    QuantizedCPU: upsample_bilinear2d_quantized_cpu
+
+- func: upsample_bilinear2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: upsample_bilinear2d_backward_out_cpu
+    CUDA: upsample_bilinear2d_backward_out_cuda
+    MPS: upsample_bilinear2d_backward_out_mps
+
+- func: upsample_bilinear2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+  python_module: nn
+  structured_delegate: upsample_bilinear2d_backward.grad_input
+
+- func: _upsample_bilinear2d_aa.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: _upsample_bilinear2d_aa_out_cpu
+    CUDA: _upsample_bilinear2d_aa_out_cuda
+    MPS: _upsample_bilinear2d_aa_out_mps
+
+- func: _upsample_bilinear2d_aa(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+  python_module: nn
+  structured_delegate: _upsample_bilinear2d_aa.out
+
+- func: _upsample_bilinear2d_aa_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: _upsample_bilinear2d_aa_backward_out_cpu
+    CUDA: _upsample_bilinear2d_aa_backward_out_cuda
+
+- func: _upsample_bilinear2d_aa_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+  python_module: nn
+  structured_delegate: _upsample_bilinear2d_aa_backward.grad_input
+
+- func: upsample_bicubic2d.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: upsample_bicubic2d_out_cpu
+    CUDA: upsample_bicubic2d_out_cuda
+    MPS: upsample_bicubic2d_out_mps
+
+- func: upsample_bicubic2d(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+  python_module: nn
+  structured_delegate: upsample_bicubic2d.out
+
+- func: upsample_bicubic2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: upsample_bicubic2d_backward_out_cpu
+    CUDA: upsample_bicubic2d_backward_out_cuda
+    MPS: upsample_bicubic2d_backward_out_mps
+
+- func: upsample_bicubic2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+  python_module: nn
+  structured_delegate: upsample_bicubic2d_backward.grad_input
+
+- func: _upsample_bicubic2d_aa.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: _upsample_bicubic2d_aa_out_cpu
+    CUDA: _upsample_bicubic2d_aa_out_cuda
+    MPS: _upsample_bicubic2d_aa_out_mps
+
+- func: _upsample_bicubic2d_aa(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+  python_module: nn
+  structured_delegate: _upsample_bicubic2d_aa.out
+
+- func: _upsample_bicubic2d_aa_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: _upsample_bicubic2d_aa_backward_out_cpu
+    CUDA: _upsample_bicubic2d_aa_backward_out_cuda
+
+- func: _upsample_bicubic2d_aa_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+  python_module: nn
+  structured_delegate: _upsample_bicubic2d_aa_backward.grad_input
+
+- func: upsample_trilinear3d.out(Tensor self, SymInt[3] output_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: upsample_trilinear3d_out_cpu
+    CUDA: upsample_trilinear3d_out_cuda
+    MPS: upsample_trilinear3d_out_mps
+
+- func: upsample_trilinear3d(Tensor self, SymInt[3] output_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor
+  python_module: nn
+  structured_delegate: upsample_trilinear3d.out
+
+- func: upsample_trilinear3d_backward.grad_input(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: upsample_trilinear3d_backward_out_cpu
+    CUDA: upsample_trilinear3d_backward_out_cuda
+    MPS: upsample_trilinear3d_backward_out_mps
+
+- func: upsample_trilinear3d_backward(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor
+  python_module: nn
+  structured_delegate: upsample_trilinear3d_backward.grad_input
+
+- func: upsample_nearest1d.out(Tensor self, SymInt[1] output_size, float? scales=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: upsample_nearest1d_out_cpu
+    CUDA: upsample_nearest1d_out_cuda
+    MPS: upsample_nearest1d_out_mps
+
+- func: _upsample_nearest_exact1d.out(Tensor self, SymInt[1] output_size, float? scales=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: _upsample_nearest_exact1d_out_cpu
+    CUDA: _upsample_nearest_exact1d_out_cuda
+    MPS: _upsample_nearest_exact1d_out_mps
+
+- func: upsample_nearest1d(Tensor self, SymInt[1] output_size, float? scales=None) -> Tensor
+  python_module: nn
+  structured_delegate: upsample_nearest1d.out
+
+- func: _upsample_nearest_exact1d(Tensor self, SymInt[1] output_size, float? scales=None) -> Tensor
+  python_module: nn
+  structured_delegate: _upsample_nearest_exact1d.out
+
+- func: upsample_nearest1d_backward.grad_input(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: upsample_nearest1d_backward_out_cpu
+    CUDA: upsample_nearest1d_backward_out_cuda
+    MPS: upsample_nearest1d_backward_out_mps
+
+- func: _upsample_nearest_exact1d_backward.grad_input(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: _upsample_nearest_exact1d_backward_out_cpu
+    CUDA: _upsample_nearest_exact1d_backward_out_cuda
+    MPS: _upsample_nearest_exact1d_backward_out_mps
+
+- func: upsample_nearest1d_backward(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None) -> Tensor
+  python_module: nn
+  structured_delegate: upsample_nearest1d_backward.grad_input
+
+- func: _upsample_nearest_exact1d_backward(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None) -> Tensor
+  python_module: nn
+  structured_delegate: _upsample_nearest_exact1d_backward.grad_input
+
+- func: upsample_nearest2d.out(Tensor self, SymInt[2] output_size, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: upsample_nearest2d_out_cpu
+    CUDA: upsample_nearest2d_out_cuda
+    MPS: upsample_nearest2d_out_mps
+
+- func: _upsample_nearest_exact2d.out(Tensor self, SymInt[2] output_size, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: _upsample_nearest_exact2d_out_cpu
+    CUDA: _upsample_nearest_exact2d_out_cuda
+    MPS: _upsample_nearest_exact2d_out_mps
+
+- func: upsample_nearest2d(Tensor self, SymInt[2] output_size, float? scales_h=None, float? scales_w=None) -> Tensor
+  python_module: nn
+  structured_delegate: upsample_nearest2d.out
+  dispatch:
+    QuantizedCPU: upsample_nearest2d_quantized_cpu
+
+- func: _upsample_nearest_exact2d(Tensor self, SymInt[2] output_size, float? scales_h=None, float? scales_w=None) -> Tensor
+  python_module: nn
+  structured_delegate: _upsample_nearest_exact2d.out
+  dispatch:
+    QuantizedCPU: _upsample_nearest_exact2d_quantized_cpu
+
+- func: upsample_nearest2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: upsample_nearest2d_backward_out_cpu
+    CUDA: upsample_nearest2d_backward_out_cuda
+    MPS: upsample_nearest2d_backward_out_mps
+
+- func: _upsample_nearest_exact2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: _upsample_nearest_exact2d_backward_out_cpu
+    CUDA: _upsample_nearest_exact2d_backward_out_cuda
+    MPS: _upsample_nearest_exact2d_backward_out_mps
+
+- func: upsample_nearest2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, float? scales_h=None, float? scales_w=None) -> Tensor
+  python_module: nn
+  structured_delegate: upsample_nearest2d_backward.grad_input
+
+- func: _upsample_nearest_exact2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, float? scales_h=None, float? scales_w=None) -> Tensor
+  python_module: nn
+  structured_delegate: _upsample_nearest_exact2d_backward.grad_input
+
+- func: upsample_nearest3d.out(Tensor self, SymInt[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: upsample_nearest3d_out_cpu
+    CUDA: upsample_nearest3d_out_cuda
+    MPS: upsample_nearest3d_out_mps
+
+- func: _upsample_nearest_exact3d.out(Tensor self, SymInt[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: _upsample_nearest_exact3d_out_cpu
+    CUDA: _upsample_nearest_exact3d_out_cuda
+    MPS: _upsample_nearest_exact3d_out_mps
+
+- func: upsample_nearest3d(Tensor self, SymInt[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor
+  python_module: nn
+  structured_delegate: upsample_nearest3d.out
+  dispatch:
+    QuantizedCPU: upsample_nearest3d_quantized_cpu
+
+- func: _upsample_nearest_exact3d(Tensor self, SymInt[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor
+  python_module: nn
+  structured_delegate: _upsample_nearest_exact3d.out
+  dispatch:
+    QuantizedCPU: _upsample_nearest_exact3d_quantized_cpu
+
+- func: upsample_nearest3d_backward.grad_input(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: upsample_nearest3d_backward_out_cpu
+    CUDA: upsample_nearest3d_backward_out_cuda
+    MPS: upsample_nearest3d_backward_out_mps
+
+- func: _upsample_nearest_exact3d_backward.grad_input(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: _upsample_nearest_exact3d_backward_out_cpu
+    CUDA: _upsample_nearest_exact3d_backward_out_cuda
+    MPS: _upsample_nearest_exact3d_backward_out_mps
+
+- func: upsample_nearest3d_backward(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor
+  python_module: nn
+  structured_delegate: upsample_nearest3d_backward.grad_input
+
+- func: _upsample_nearest_exact3d_backward(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor
+  python_module: nn
+  structured_delegate: _upsample_nearest_exact3d_backward.grad_input
+
+- func: sigmoid_backward.grad_input(Tensor grad_output, Tensor output, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: sigmoid_backward_out
+    MPS: sigmoid_backward_out_mps
+  tags: pointwise
+
+- func: sigmoid_backward(Tensor grad_output, Tensor output) -> Tensor
+  python_module: nn
+  structured_delegate: sigmoid_backward.grad_input
+  tags: pointwise
+
+- func: logit_backward.grad_input(Tensor grad_output, Tensor self, float? eps=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: logit_backward_out
+    MPS: logit_backward_out_mps
+  tags: pointwise
+
+- func: logit_backward(Tensor grad_output, Tensor self, float? eps=None) -> Tensor
+  python_module: nn
+  structured_delegate: logit_backward.grad_input
+  tags: pointwise
+
+- func: tanh_backward.grad_input(Tensor grad_output, Tensor output, *, Tensor(a!) grad_input) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MTIA: tanh_backward_out
+    MPS: tanh_backward_out_mps
+  tags: pointwise
+
+- func: tanh_backward(Tensor grad_output, Tensor output) -> Tensor
+  python_module: nn
+  structured_delegate: tanh_backward.grad_input
+
+# What's a thnn_conv_ versus a slow_conv_?
+#
+# Historically, we have inefficient implementations of convolutions
+# coming from the THNN/THCUNN library.  These convolutions typically
+# operated by computing the Toeplitz matrix and then doing a matrix
+# multiply with the input; this is very memory inefficient!  However,
+# occasionally, we really don't have anything better, so it's helpful
+# to have these fallbacks when there is no more optimized implementation
+# in cudnn or mkldnn, etc.  Both thnn_ and slow_ convolutions fall
+# into this bucket.
+#
+# The difference between these two designations, is that thnn_ refers
+# to a convolution that is still written in the "legacy" style; that is,
+# C code in the THNN/ or THCUNN/ directory.  A slow_ convolution is
+# one that is written in the native style: modern C++.  Algorithmically,
+# these are the same thing, but we give them different prefixes to
+# make the operational distinction clear.
+  tags: pointwise
+
+- func: slow_conv_transpose2d.out(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] output_padding=0, SymInt[2] dilation=1, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  structured: True
+  dispatch:
+    CPU: slow_conv_transpose2d_structured_cpu
+    CUDA: slow_conv_transpose2d_structured_cuda
+
+- func: slow_conv_transpose2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] output_padding=0, SymInt[2] dilation=1) -> Tensor
+  python_module: nn
+  structured_delegate: slow_conv_transpose2d.out
+
+- func: slow_conv_transpose3d.out(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] output_padding=0, SymInt[3] dilation=1, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: slow_conv_transpose3d_out_cpu
+    CUDA: slow_conv_transpose3d_out_cuda
+
+- func: slow_conv_transpose3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] output_padding=0, SymInt[3] dilation=1) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: slow_conv_transpose3d_cpu
+    CUDA: slow_conv_transpose3d_cuda
+
+- func: thnn_conv2d.out(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+
+- func: thnn_conv2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0) -> Tensor
+  python_module: nn
+
+- func: _slow_conv2d_forward.output(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding, *, Tensor(a!) output) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: slow_conv2d_forward_out_cpu
+    CUDA: slow_conv2d_forward_out_cuda
+
+- func: _slow_conv2d_forward(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: slow_conv2d_forward_cpu
+    CUDA: slow_conv2d_forward_cuda
+
+- func: _slow_conv2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, *, Tensor(a!) grad_input, Tensor(b!) grad_weight, Tensor(c!) grad_bias) -> (Tensor(a!), Tensor(b!), Tensor(c!))
+  python_module: nn
+  dispatch:
+    CPU: slow_conv2d_backward_out_cpu
+    CUDA: slow_conv2d_backward_out_cuda
+
+- func: _slow_conv2d_backward.output_mask(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias)
+  python_module: nn
+  dispatch:
+    CPU: slow_conv2d_backward_cpu
+    CUDA: slow_conv2d_backward_cuda
+  autogen: _slow_conv2d_backward.output_mask_out
+
+- func: _conv_depthwise2d.out(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding, SymInt[2] dilation, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CUDA: conv_depthwise2d_cuda_out
+
+- func: _conv_depthwise2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding, SymInt[2] dilation) -> Tensor
+  python_module: nn
+  dispatch:
+    CUDA: conv_depthwise2d_cuda
+
+- func: conv_depthwise3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias, SymInt[3] stride, SymInt[3] padding, SymInt[3] dilation) -> Tensor
+  python_module: nn
+  dispatch:
+    CUDA: conv_depthwise3d_cuda
+  autogen: conv_depthwise3d.out
+
+- func: slow_conv3d.out(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+
+- func: slow_conv3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0) -> Tensor
+  python_module: nn
+
+- func: slow_conv3d_forward.output(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias, SymInt[3] stride, SymInt[3] padding, *, Tensor(a!) output) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: slow_conv3d_forward_out_cpu
+
+- func: slow_conv3d_forward(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias, SymInt[3] stride, SymInt[3] padding) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: slow_conv3d_forward_cpu
+
+- func: slow_conv_dilated2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] dilation=1) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: slow_conv_dilated2d_cpu
+    CUDA: slow_conv_dilated2d_cuda
+  autogen: slow_conv_dilated2d.out
+
+- func: slow_conv_dilated3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] dilation=1) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: slow_conv_dilated3d_cpu
+    CUDA: slow_conv_dilated3d_cuda
+  autogen: slow_conv_dilated3d.out
+
+- func: col2im.out(Tensor self, SymInt[2] output_size, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: col2im_out_cpu
+    CUDA: col2im_out_cuda
+    MPS: col2im_out_mps
+
+- func: col2im(Tensor self, SymInt[2] output_size, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: col2im_cpu
+    CUDA: col2im_cuda
+    MPS: col2im_mps
+  tags: core
+
+- func: column_stack(Tensor[] tensors) -> Tensor
+
+- func: column_stack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: im2col.out(Tensor self, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: nn
+  dispatch:
+    CPU: im2col_out_cpu
+    CUDA: im2col_out_cuda
+    MPS: im2col_out_mps
+
+- func: im2col(Tensor self, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: im2col_cpu
+    CUDA: im2col_cuda
+    MPS: im2col_mps
+
+- func: isfinite(Tensor self) -> Tensor
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  tags: pointwise
+
+- func: isinf(Tensor self) -> Tensor
+  variants: function, method
+  device_check: NoCheck
+  device_guard: False
+  dispatch:
+    CompositeExplicitAutograd: isinf
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_isinf
+    SparseCPU, SparseCUDA, SparseMPS: isinf_sparse
+    SparseMeta: isinf_sparse_meta
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: isinf_sparse_csr
+  autogen: isinf.out
+  tags: [core, pointwise]
+
+- func: record_stream(Tensor(a!) self, Stream s) -> ()
+  variants: method
+  dispatch:
+    CUDA: record_stream_cuda
+
+- func: isposinf(Tensor self) -> Tensor
+  variants: function, method
+  structured_delegate: isposinf.out
+  dispatch:
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_isposinf
+    SparseCPU, SparseCUDA, SparseMPS: isposinf_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: isposinf_sparse_csr
+  tags: pointwise
+
+- func: isposinf.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: isposinf_out
+    SparseCPU, SparseCUDA, SparseMPS: isposinf_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: isposinf_sparse_csr_out
+  tags: pointwise
+
+- func: isneginf(Tensor self) -> Tensor
+  variants: function, method
+  structured_delegate: isneginf.out
+  dispatch:
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: NestedTensor_isneginf
+    SparseCPU, SparseCUDA, SparseMPS: isneginf_sparse
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: isneginf_sparse_csr
+  tags: pointwise
+
+- func: isneginf.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: isneginf_out
+    SparseCPU, SparseCUDA, SparseMPS: isneginf_sparse_out
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: isneginf_sparse_csr_out
+  tags: pointwise
+
+# NOTE [_add_batch_dim and _remove_batch_dim]
+# _add_batch_dim and _remove_batch_dim are meant to be used in the implementation
+# of the vmap frontend API (see torch/_vmap_internals.py). They are not
+# user-facing, hence the leading underscore. Please don't use them them anywhere else.
+- func: _add_batch_dim(Tensor self, int batch_dim, int level) -> Tensor
+  variants: function
+
+# See NOTE [_add_batch_dim and _remove_batch_dim]
+- func: _remove_batch_dim(Tensor self, int level, SymInt batch_size, int out_dim) -> Tensor
+  variants: function
+
+## Functions related to the `torch.special` namespace
+# Note [special namespace binding]
+# Functions in the special python module should have their names start with
+#   "special_" underscore and be bound to the desired Python name in
+#   torch/special/__init__.py, and the desired C++ name in torch/csrc/api/include/torch/special.h.
+#   The "special_" names should be hidden from the user and not documented.
+
+- func: special_entr(Tensor self) -> Tensor
+  structured_delegate: special_entr.out
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_entr.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  python_module: special
+  variants: function
+  dispatch:
+    CPU, CUDA, MPS: special_entr_out
+  tags: pointwise
+
+- func: special_ndtri(Tensor self) -> Tensor
+  structured_delegate: special_ndtri.out
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_ndtri.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  python_module: special
+  variants: function
+  dispatch:
+    CPU, CUDA: special_ndtri_out
+  tags: pointwise
+
+- func: special_log_ndtr(Tensor self) -> Tensor
+  structured_delegate: special_log_ndtr.out
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_log_ndtr.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  structured_inherits: TensorIteratorBase
+  python_module: special
+  variants: function
+  dispatch:
+    CPU, CUDA: special_log_ndtr_out
+  tags: pointwise
+
+- func: special_expm1(Tensor self) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_expm1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+  variants: function
+
+- func: special_exp2(Tensor self) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_exp2.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+  variants: function
+
+- func: special_psi(Tensor self) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_psi.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+  variants: function
+
+- func: special_digamma(Tensor self) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_digamma.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+  variants: function
+
+- func: special_gammaln(Tensor self) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_gammaln.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+  variants: function
+
+- func: special_erf(Tensor self) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_erf.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+  variants: function
+
+- func: special_erfc(Tensor self) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_erfc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+
+- func: special_erfcx(Tensor self) -> Tensor
+  python_module: special
+  variants: function
+  structured_delegate: special_erfcx.out
+  tags: pointwise
+
+- func: special_erfcx.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA: special_erfcx_out
+  tags: pointwise
+
+- func: special_erfinv(Tensor self) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_erfinv.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+
+- func: special_ndtr(Tensor self) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_ndtr.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+  variants: function
+
+- func: special_xlog1py(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  python_module: special
+  variants: function
+  structured_delegate: special_xlog1py.out
+  tags: pointwise
+
+- func: special_xlog1py.self_scalar(Scalar self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  python_module: special
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: special_xlog1py
+  tags: pointwise
+
+- func: special_xlog1py.other_scalar(Tensor self, Scalar other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  python_module: special
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: special_xlog1py
+  tags: pointwise
+
+- func: special_xlog1py.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  python_module: special
+  variants: function
+  dispatch:
+    CPU, CUDA, MPS: special_xlog1py_out
+  tags: pointwise
+
+- func: special_xlog1py.self_scalar_out(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  python_module: special
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: special_xlog1py_out
+  tags: pointwise
+
+- func: special_xlog1py.other_scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  python_module: special
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: special_xlog1py_out
+  tags: pointwise
+
+- func: special_xlogy(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  python_module: special
+  variants: function
+
+- func: special_xlogy.self_scalar(Scalar self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  python_module: special
+  variants: function
+
+- func: special_xlogy.other_scalar(Tensor self, Scalar other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  python_module: special
+  variants: function
+
+- func: special_xlogy.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  python_module: special
+  variants: function
+
+- func: special_xlogy.self_scalar_out(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  python_module: special
+  variants: function
+
+- func: special_xlogy.other_scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  python_module: special
+  variants: function
+
+- func: special_zeta(Tensor self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  python_module: special
+  variants: function
+  structured_delegate: special_zeta.out
+  tags: pointwise
+
+- func: special_zeta.self_scalar(Scalar self, Tensor other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  python_module: special
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: special_zeta
+  tags: pointwise
+
+- func: special_zeta.other_scalar(Tensor self, Scalar other) -> Tensor
+  device_check: NoCheck   # TensorIterator
+  python_module: special
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: special_zeta
+  tags: pointwise
+
+- func: special_zeta.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  structured: True
+  structured_inherits: TensorIteratorBase
+  python_module: special
+  variants: function
+  dispatch:
+    CPU, CUDA, MPS: special_zeta_out
+  tags: pointwise
+
+- func: special_zeta.self_scalar_out(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  python_module: special
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: special_zeta_out
+  tags: pointwise
+
+- func: special_zeta.other_scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck   # TensorIterator
+  python_module: special
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: special_zeta_out
+  tags: pointwise
+
+- func: special_i0(Tensor self) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_i0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+  variants: function
+
+- func: special_i0e(Tensor self) -> Tensor
+  python_module: special
+  variants: function
+  structured_delegate: special_i0e.out
+  tags: pointwise
+
+- func: special_i0e.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: special_i0e_out
+  tags: pointwise
+
+- func: special_i1(Tensor self) -> Tensor
+  python_module: special
+  variants: function
+  structured_delegate: special_i1.out
+  tags: pointwise
+
+- func: special_i1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: special_i1_out
+  tags: pointwise
+
+- func: special_i1e(Tensor self) -> Tensor
+  python_module: special
+  variants: function
+  structured_delegate: special_i1e.out
+  tags: pointwise
+
+- func: special_i1e.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+  structured: True
+  structured_inherits: TensorIteratorBase
+  dispatch:
+    CPU, CUDA, MPS: special_i1e_out
+  tags: pointwise
+
+- func: special_logit(Tensor self, float? eps=None) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_logit.out(Tensor self, float? eps=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+
+- func: special_polygamma(int n, Tensor self) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_polygamma.out(int n, Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+
+- func: special_logsumexp(Tensor self, int[1] dim, bool keepdim=False) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_logsumexp.out(Tensor self, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+
+- func: special_expit(Tensor self) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_expit.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+  variants: function
+
+- func: special_sinc(Tensor self) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_sinc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+  variants: function
+
+- func: special_round(Tensor self, *, int decimals=0) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_round.out(Tensor self, *, int decimals=0, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+  variants: function
+
+- func: special_log1p(Tensor self) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_log1p.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+  variants: function
+
+- func: special_log_softmax(Tensor self, int dim, *, ScalarType? dtype=None) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_gammainc.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+  variants: function
+
+- func: special_gammainc(Tensor self, Tensor other) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_gammaincc.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+  variants: function
+
+- func: special_gammaincc(Tensor self, Tensor other) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_multigammaln(Tensor self, int p) -> Tensor
+  python_module: special
+  variants: function
+
+- func: special_multigammaln.out(Tensor self, int p, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: special
+  variants: function
+
+- func: special_softmax(Tensor self, int dim, ScalarType? dtype=None) -> Tensor
+  python_module: special
+  variants: function
+
+## Functions related to the fast Fourier transform and the torch.fft namespace
+# Note [FFT namespace binding]
+# Functions in the fft python module should have their names start with
+#   "fft_" underscore and be bound to the desired Python name in
+#   torch/fft/__init__.py, and the desired C++ name in torch/csrc/api/include/torch/fft.h.
+#   The "fft_" names should be hidden from the user and not documented.
+#
+# See fft_fft as an example.
+
+# torch.fft.fft
+# NOTE: NOT an alias for torch.fft, which has different semantics
+- func: fft_fft(Tensor self, SymInt? n=None, int dim=-1, str? norm=None) -> Tensor
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_fft_symint
+
+- func: fft_fft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_fft_symint_out
+
+- func: fft_ifft(Tensor self, SymInt? n=None, int dim=-1, str? norm=None) -> Tensor
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_ifft_symint
+
+- func: fft_ifft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_ifft_symint_out
+
+- func: fft_rfft(Tensor self, SymInt? n=None, int dim=-1, str? norm=None) -> Tensor
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_rfft_symint
+
+- func: fft_rfft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_rfft_symint_out
+
+- func: fft_irfft(Tensor self, SymInt? n=None, int dim=-1, str? norm=None) -> Tensor
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_irfft_symint
+
+- func: fft_irfft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_irfft_symint_out
+
+- func: fft_hfft(Tensor self, SymInt? n=None, int dim=-1, str? norm=None) -> Tensor
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_hfft_symint
+
+- func: fft_hfft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_hfft_symint_out
+
+- func: fft_ihfft(Tensor self, SymInt? n=None, int dim=-1, str? norm=None) -> Tensor
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_ihfft_symint
+
+- func: fft_ihfft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_ihfft_symint_out
+
+- func: fft_fft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_fft2_symint
+
+- func: fft_fft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_fft2_symint_out
+
+- func: fft_ifft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_ifft2_symint
+
+- func: fft_ifft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_ifft2_symint_out
+
+- func: fft_rfft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_rfft2_symint
+
+- func: fft_rfft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_rfft2_symint_out
+
+- func: fft_irfft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_irfft2_symint
+
+- func: fft_irfft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_irfft2_symint_out
+
+- func: fft_hfft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor
+  use_const_ref_for_mutable_tensors: True
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_hfft2_symint
+
+- func: fft_hfft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_hfft2_symint_out
+
+- func: fft_ihfft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor
+  use_const_ref_for_mutable_tensors: True
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_ihfft2_symint
+
+- func: fft_ihfft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_ihfft2_symint_out
+
+- func: fft_fftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_fftn_symint
+
+- func: fft_fftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_fftn_symint_out
+
+- func: fft_ifftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_ifftn_symint
+
+- func: fft_ifftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_ifftn_symint_out
+
+- func: fft_rfftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_rfftn_symint
+
+- func: fft_rfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_rfftn_symint_out
+
+- func: fft_irfftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_irfftn_symint
+
+- func: fft_irfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_irfftn_symint_out
+
+- func: fft_hfftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor
+  use_const_ref_for_mutable_tensors: True
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_hfftn_symint
+
+- func: fft_hfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_hfftn_symint_out
+
+- func: fft_ihfftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor
+  use_const_ref_for_mutable_tensors: True
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_ihfftn_symint
+
+- func: fft_ihfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: fft_ihfftn_symint_out
+
+- func: fft_fftfreq(int n, float d=1.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: fft_fftfreq
+
+- func: fft_fftfreq.out(int n, float d=1.0, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: fft_fftfreq_out
+
+- func: fft_rfftfreq(int n, float d=1.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: fft_rfftfreq
+
+- func: fft_rfftfreq.out(int n, float d=1.0, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: fft
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: fft_rfftfreq_out
+
+- func: fft_fftshift(Tensor self, int[1]? dim=None) -> Tensor
+  python_module: fft
+  variants: function
+
+- func: fft_ifftshift(Tensor self, int[1]? dim=None) -> Tensor
+  python_module: fft
+  variants: function
+
+## Functions for linear algebra and the torch.linalg namespace
+# Note [linalg namespace binding]
+# Functions in the linalg python module should have their names start with
+#   "linalg_" and be bound to the desired Python name in
+#   torch/linalg/__init__.py, and the desired C++ name in torch/csrc/api/include/torch/linalg.h.
+#   The "linalg_" names should be hidden from the user and not documented.
+#
+# See linalg_det as an example.
+
+# "_ex" stands for experimental
+- func: linalg_cholesky_ex(Tensor self, *, bool upper=False, bool check_errors=False) -> (Tensor L, Tensor info)
+  python_module: linalg
+  structured_delegate: linalg_cholesky_ex.L
+
+- func: linalg_cholesky_ex.L(Tensor self, *, bool upper=False, bool check_errors=False, Tensor(a!) L, Tensor(b!) info) -> (Tensor(a!) L, Tensor(b!) info)
+  python_module: linalg
+  structured: True
+  dispatch:
+    CPU, CUDA, MPS: linalg_cholesky_ex_out
+
+- func: linalg_cholesky(Tensor self, *, bool upper=False) -> Tensor
+  python_module: linalg
+
+- func: linalg_cholesky.out(Tensor self, *, bool upper=False, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+
+- func: linalg_cross(Tensor self, Tensor other, *, int dim=-1) -> Tensor
+  python_module: linalg
+  variants: function
+  structured_delegate: linalg_cross.out
+  dispatch:
+    ZeroTensor: linalg_cross_zerotensor
+
+- func: linalg_cross.out(Tensor self, Tensor other, *, int dim=-1, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+  structured: True
+  dispatch:
+    CPU, CUDA, MPS: linalg_cross_out
+
+# linalg.lu_factor
+- func: linalg_lu_factor(Tensor A, *, bool pivot=True) -> (Tensor LU, Tensor pivots)
+  python_module: linalg
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: linalg_lu_factor
+    MPS: linalg_lu_factor_mps
+
+- func: linalg_lu_factor.out(Tensor A, *, bool pivot=True, Tensor(a!) LU, Tensor(b!) pivots) -> (Tensor(a!) LU, Tensor(b!) pivots)
+  python_module: linalg
+  variants: function
+  dispatch:
+    CompositeImplicitAutograd: linalg_lu_factor_out
+    MPS: linalg_lu_factor_out_mps
+
+- func: linalg_lu_factor_ex(Tensor A, *, bool pivot=True, bool check_errors=False) -> (Tensor LU, Tensor pivots, Tensor info)
+  python_module: linalg
+  structured_delegate: linalg_lu_factor_ex.out
+  variants: function
+
+- func: linalg_lu_factor_ex.out(Tensor A, *, bool pivot=True, bool check_errors=False, Tensor(a!) LU, Tensor(b!) pivots, Tensor(c!) info) -> (Tensor(a!) LU, Tensor(b!) pivots, Tensor(c!) info)
+  python_module: linalg
+  variants: function
+  structured: True
+  dispatch:
+    CPU, CUDA: linalg_lu_factor_ex_out
+    MPS: linalg_lu_factor_ex_out_mps
+
+# linalg.lu
+- func: linalg_lu(Tensor A, *, bool pivot=True) -> (Tensor P, Tensor L, Tensor U)
+  python_module: linalg
+  structured_delegate: linalg_lu.out
+  variants: function
+
+- func: linalg_lu.out(Tensor A, *, bool pivot=True, Tensor(a!) P, Tensor(b!) L, Tensor(c!) U) -> (Tensor(a!) P, Tensor(b!) L, Tensor(c!) U)
+  python_module: linalg
+  variants: function
+  structured: True
+  dispatch:
+    CPU, CUDA: linalg_lu_out
+
+# linalg.lu_solve
+- func: linalg_lu_solve(Tensor LU, Tensor pivots, Tensor B, *, bool left=True, bool adjoint=False) -> Tensor
+  python_module: linalg
+  structured_delegate: linalg_lu_solve.out
+  variants: function
+
+- func: linalg_lu_solve.out(Tensor LU, Tensor pivots, Tensor B, *, bool left=True, bool adjoint=False, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+  variants: function
+  structured: True
+  dispatch:
+    CPU, CUDA: linalg_lu_solve_out
+
+# linalg.det
+- func: _linalg_det(Tensor A) -> (Tensor result, Tensor LU, Tensor pivots)
+  structured_delegate: _linalg_det.result
+
+- func: _linalg_det.result(Tensor A, *, Tensor(a!) result, Tensor(b!) LU, Tensor(c!) pivots) -> (Tensor(a!) result, Tensor(b!) LU, Tensor(c!) pivots)
+  structured: True
+  dispatch:
+    CPU, CUDA, MPS: _linalg_det_out
+
+- func: linalg_det(Tensor A) -> Tensor
+  python_module: linalg
+  variants: function
+
+- func: linalg_det.out(Tensor A, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+
+# torch.det, alias for torch.linalg.det
+- func: det(Tensor self) -> Tensor
+  variants: function, method
+
+- func: linalg_ldl_factor_ex(Tensor self, *, bool hermitian=False, bool check_errors=False) -> (Tensor LD, Tensor pivots, Tensor info)
+  structured_delegate: linalg_ldl_factor_ex.out
+  python_module: linalg
+  variants: function
+
+- func: linalg_ldl_factor_ex.out(Tensor self, *, bool hermitian=False, bool check_errors=False, Tensor(a!) LD, Tensor(b!) pivots, Tensor(c!) info) -> (Tensor(a!) LD, Tensor(b!) pivots, Tensor(c!) info)
+  structured: True
+  python_module: linalg
+  variants: function
+  dispatch:
+    CPU, CUDA: linalg_ldl_factor_ex_out
+
+- func: linalg_ldl_factor(Tensor self, *, bool hermitian=False) -> (Tensor LD, Tensor pivots)
+  python_module: linalg
+  variants: function
+
+- func: linalg_ldl_factor.out(Tensor self, *, bool hermitian=False, Tensor(a!) LD, Tensor(b!) pivots) -> (Tensor(a!) LD, Tensor(b!) pivots)
+  python_module: linalg
+  variants: function
+
+- func: linalg_ldl_solve(Tensor LD, Tensor pivots, Tensor B, *, bool hermitian=False) -> Tensor
+  structured_delegate: linalg_ldl_solve.out
+  python_module: linalg
+  variants: function
+
+- func: linalg_ldl_solve.out(Tensor LD, Tensor pivots, Tensor B, *, bool hermitian=False, Tensor(a!) out) -> Tensor(a!)
+  structured: True
+  python_module: linalg
+  variants: function
+  dispatch:
+    CPU, CUDA: linalg_ldl_solve_out
+
+- func: linalg_lstsq(Tensor self, Tensor b, float? rcond=None, *, str? driver=None) -> (Tensor solution, Tensor residuals, Tensor rank, Tensor singular_values)
+  python_module: linalg
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: linalg_lstsq
+  tags: dynamic_output_shape
+
+- func: linalg_lstsq.out(Tensor self, Tensor b, float? rcond=None, *, str? driver=None, Tensor(a!) solution, Tensor(b!) residuals, Tensor(c!) rank, Tensor(d!) singular_values) -> (Tensor(a!) solution, Tensor(b!) residuals, Tensor(c!) rank, Tensor(d!) singular_values)
+  python_module: linalg
+  variants: function
+  dispatch:
+    CPU, CUDA: linalg_lstsq_out
+  tags: dynamic_output_shape
+
+# torch.linalg.matmul, alias for torch.matmul
+- func: linalg_matmul(Tensor self, Tensor other) -> Tensor
+  python_module: linalg
+  variants: function
+
+- func: linalg_matmul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+
+- func: linalg_vecdot(Tensor x, Tensor y, *, int dim=-1) -> Tensor
+  python_module: linalg
+  variants: function
+
+- func: linalg_vecdot.out(Tensor x, Tensor y, *, int dim=-1, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+
+- func: linalg_matrix_exp(Tensor self) -> Tensor
+  python_module: linalg
+  variants: function
+  dispatch:
+    CPU, CUDA: linalg_matrix_exp
+  autogen: linalg_matrix_exp.out
+
+- func: _linalg_slogdet(Tensor A) -> (Tensor sign, Tensor logabsdet, Tensor LU, Tensor pivots)
+  structured_delegate: _linalg_slogdet.sign
+
+- func: _linalg_slogdet.sign(Tensor A, *, Tensor(a!) sign, Tensor(b!) logabsdet, Tensor(c!) LU, Tensor(d!) pivots) -> (Tensor(a!) sign, Tensor(b!) logabsdet, Tensor(c!) LU, Tensor(d!) pivots)
+  structured: True
+  dispatch:
+    CPU, CUDA, MPS: _linalg_slogdet_out
+
+- func: linalg_slogdet(Tensor A) -> (Tensor sign, Tensor logabsdet)
+  python_module: linalg
+
+- func: linalg_slogdet.out(Tensor A, *, Tensor(a!) sign, Tensor(b!) logabsdet) -> (Tensor(a!) sign, Tensor(b!) logabsdet)
+  python_module: linalg
+
+- func: slogdet(Tensor self) -> (Tensor sign, Tensor logabsdet)
+  variants: function, method
+
+- func: slogdet.out(Tensor self, *, Tensor(a!) sign, Tensor(b!) logabsdet) -> (Tensor(a!) sign, Tensor(b!) logabsdet)
+  variants: function
+
+- func: logdet(Tensor self) -> Tensor
+  variants: function, method
+
+- func: linalg_eig(Tensor self) -> (Tensor eigenvalues, Tensor eigenvectors)
+  python_module: linalg
+  variants: function
+  dispatch:
+    CPU, CUDA: linalg_eig
+
+- func: linalg_eig.out(Tensor self, *, Tensor(a!) eigenvalues, Tensor(b!) eigenvectors) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors)
+  python_module: linalg
+  dispatch:
+    CPU, CUDA: linalg_eig_out
+
+- func: _linalg_eigvals(Tensor self) -> Tensor
+  python_module: linalg
+  dispatch:
+    CPU, CUDA: _linalg_eigvals
+
+- func: linalg_eigvals(Tensor self) -> Tensor
+  python_module: linalg
+
+- func: linalg_eigvals.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+  dispatch:
+    CPU, CUDA: linalg_eigvals_out
+
+# This function is exposes the `compute_v` flag, which is then used to implement `linalg.eigh` and
+# `linalg.eigvalsh` as composite functions that call this one
+- func: _linalg_eigh(Tensor A, str UPLO="L", bool compute_v=True) -> (Tensor eigenvalues, Tensor eigenvectors)
+  structured_delegate: _linalg_eigh.eigenvalues
+
+- func: _linalg_eigh.eigenvalues(Tensor A, str UPLO="L", bool compute_v=True, *, Tensor(a!) eigenvalues, Tensor(b!) eigenvectors) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors)
+  structured: True
+  dispatch:
+    CPU, CUDA: _linalg_eigh_out
+
+- func: linalg_eigh(Tensor self, str UPLO="L") -> (Tensor eigenvalues, Tensor eigenvectors)
+  python_module: linalg
+
+- func: linalg_eigh.eigvals(Tensor self, str UPLO="L", *, Tensor(a!) eigvals, Tensor(b!) eigvecs) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors)
+  python_module: linalg
+
+- func: linalg_eigvalsh(Tensor self, str UPLO="L") -> Tensor
+  python_module: linalg
+
+- func: linalg_eigvalsh.out(Tensor self, str UPLO="L", *, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+
+- func: linalg_householder_product(Tensor input, Tensor tau) -> Tensor
+  python_module: linalg
+  variants: function
+  dispatch:
+    CPU, CUDA: linalg_householder_product
+
+- func: linalg_householder_product.out(Tensor input, Tensor tau, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+  dispatch:
+    CPU, CUDA: linalg_householder_product_out
+
+- func: linalg_inv_ex(Tensor A, *, bool check_errors=False) -> (Tensor inverse, Tensor info)
+  python_module: linalg
+  structured_delegate: linalg_inv_ex.inverse
+
+- func: linalg_inv_ex.inverse(Tensor A, *, bool check_errors=False, Tensor(a!) inverse, Tensor(b!) info) -> (Tensor(a!) inverse, Tensor(b!) info)
+  python_module: linalg
+  structured: True
+  dispatch:
+    CPU, CUDA: linalg_inv_ex_out
+    MPS: linalg_inv_ex_out_mps
+
+- func: linalg_inv(Tensor A) -> Tensor
+  python_module: linalg
+
+- func: linalg_inv.out(Tensor A, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+
+- func: inverse(Tensor self) -> Tensor
+  variants: function, method
+
+- func: inverse.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: inner(Tensor self, Tensor other) -> Tensor
+  variants: function, method
+
+- func: inner.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: outer(Tensor self, Tensor vec2) -> Tensor
+  variants: function, method
+
+- func: outer.out(Tensor self, Tensor vec2, *, Tensor(a!) out) -> Tensor(a!)
+
+# torch.ger, alias for torch.outer
+- func: ger(Tensor self, Tensor vec2) -> Tensor
+  variants: function, method
+
+- func: ger.out(Tensor self, Tensor vec2, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: linalg_norm(Tensor self, Scalar? ord=None, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+  python_module: linalg
+  variants: function
+
+- func: linalg_norm.ord_str(Tensor self, str ord, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+  python_module: linalg
+  variants: function
+
+- func: linalg_norm.out(Tensor self, Scalar? ord=None, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+  variants: function
+
+- func: linalg_norm.ord_str_out(Tensor self, str ord, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+  variants: function
+
+- func: linalg_vector_norm(Tensor self, Scalar ord=2, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+  python_module: linalg
+  variants: function
+  structured_delegate: linalg_vector_norm.out
+
+- func: linalg_vector_norm.out(Tensor self, Scalar ord=2, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+  structured: True
+  dispatch:
+    CPU, CUDA: linalg_vector_norm_out
+    MPS: linalg_vector_norm_out_mps
+
+- func: linalg_matrix_norm(Tensor self, Scalar ord, int[] dim=[-2,-1], bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+  python_module: linalg
+
+- func: linalg_matrix_norm.out(Tensor self, Scalar ord, int[] dim=[-2,-1], bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+
+- func: linalg_matrix_norm.str_ord(Tensor self, str ord='fro', int[] dim=[-2,-1], bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+  python_module: linalg
+
+- func: linalg_matrix_norm.str_ord_out(Tensor self, str ord='fro', int[] dim=[-2,-1], bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+
+# This function is exposes the `compute_uv` flag, which is then used to implement `linalg.svd` and
+# `linalg.svdvals` as composite functions that call this one
+- func: _linalg_svd(Tensor A, bool full_matrices=False, bool compute_uv=True, *, str? driver=None) -> (Tensor U, Tensor S, Tensor Vh)
+  variants: function
+  structured_delegate: _linalg_svd.U
+
+- func: _linalg_svd.U(Tensor A, bool full_matrices=False, bool compute_uv=True, *, str? driver=None, Tensor(a!) U, Tensor(b!) S, Tensor(c!) Vh) -> (Tensor(a!) U, Tensor(b!) S, Tensor(c!) Vh)
+  structured: True
+  dispatch:
+    CPU, CUDA: _linalg_svd_out
+
+- func: linalg_svd(Tensor A, bool full_matrices=True, *, str? driver=None) -> (Tensor U, Tensor S, Tensor Vh)
+  python_module: linalg
+  variants: function
+
+- func: linalg_svd.U(Tensor A, bool full_matrices=True, *, str? driver=None, Tensor(a!) U, Tensor(b!) S, Tensor(c!) Vh) -> (Tensor(a!) U, Tensor(b!) S, Tensor(c!) Vh)
+  python_module: linalg
+  variants: function
+
+- func: linalg_svdvals(Tensor A, *, str? driver=None) -> Tensor
+  python_module: linalg
+  variants: function
+
+- func: linalg_svdvals.out(Tensor A, *, str? driver=None, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+  variants: function
+
+- func: linalg_cond(Tensor self, Scalar? p=None) -> Tensor
+  python_module: linalg
+  variants: function
+
+- func: linalg_cond.out(Tensor self, Scalar? p=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+  variants: function
+
+- func: linalg_cond.p_str(Tensor self, str p) -> Tensor
+  python_module: linalg
+  variants: function
+
+- func: linalg_cond.p_str_out(Tensor self, str p, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+  variants: function
+
+- func: linalg_pinv.atol_rtol_tensor(Tensor self, *, Tensor? atol=None, Tensor? rtol=None, bool hermitian=False) -> Tensor
+  python_module: linalg
+  variants: function
+  dispatch:
+    # calls svd, which calls mH() (view op)
+    # also calls narrow()
+    CompositeExplicitAutogradNonFunctional: linalg_pinv
+
+- func: linalg_pinv.atol_rtol_tensor_out(Tensor self, *, Tensor? atol=None, Tensor? rtol=None, bool hermitian=False, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: linalg_pinv_out
+
+- func: linalg_pinv.atol_rtol_float(Tensor self, *, float? atol=None, float? rtol=None, bool hermitian=False) -> Tensor
+  cpp_no_default_args: ['atol', 'rtol']
+  python_module: linalg
+  variants: function
+
+- func: linalg_pinv.atol_rtol_float_out(Tensor self, *, float? atol=None, float? rtol=None, bool hermitian=False, Tensor(a!) out) -> Tensor(a!)
+  cpp_no_default_args: ['atol', 'rtol']
+  python_module: linalg
+  variants: function
+
+- func: linalg_pinv(Tensor self, float rcond, bool hermitian=False) -> Tensor
+  python_module: linalg
+  variants: function
+
+- func: linalg_pinv.rcond_tensor(Tensor self, Tensor rcond, bool hermitian=False) -> Tensor
+  python_module: linalg
+  variants: function
+
+- func: linalg_pinv.out(Tensor self, float rcond, bool hermitian=False, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+  variants: function
+
+- func: linalg_pinv.out_rcond_tensor(Tensor self, Tensor rcond, bool hermitian=False, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+  variants: function
+
+- func: _linalg_solve_ex(Tensor A, Tensor B, *, bool left=True, bool check_errors=False) -> (Tensor result, Tensor LU, Tensor pivots, Tensor info)
+  structured_delegate: _linalg_solve_ex.result
+
+- func: _linalg_solve_ex.result(Tensor A, Tensor B, *, bool left=True, bool check_errors=False, Tensor(a!) result, Tensor(b!) LU, Tensor(c!) pivots, Tensor(d!) info) -> (Tensor(a!) result, Tensor(b!) LU, Tensor(c!) pivots, Tensor(d!) info)
+  structured: True
+  dispatch:
+    CPU, CUDA: _linalg_solve_ex_out
+    MPS: _linalg_solve_ex_out_mps
+
+- func: linalg_solve_ex(Tensor A, Tensor B, *, bool left=True, bool check_errors=False) -> (Tensor result, Tensor info)
+  python_module: linalg
+
+- func: linalg_solve_ex.out(Tensor A, Tensor B, *, bool left=True, bool check_errors=False, Tensor(a!) result, Tensor(b!) info) -> (Tensor(a!) result, Tensor(b!) info)
+  python_module: linalg
+
+- func: linalg_solve(Tensor A, Tensor B, *, bool left=True) -> Tensor
+  python_module: linalg
+
+- func: _spsolve(Tensor A, Tensor B, *, bool left=True) -> Tensor
+  python_module: sparse
+  dispatch:
+    SparseCsrCUDA: _sparse_csr_linear_solve
+
+- func: linalg_solve.out(Tensor A, Tensor B, *, bool left=True, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+
+- func: linalg_tensorinv(Tensor self, int ind=2) -> Tensor
+  python_module: linalg
+  variants: function
+
+- func: linalg_tensorinv.out(Tensor self, int ind=2, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+  variants: function
+
+- func: linalg_tensorsolve(Tensor self, Tensor other, int[]? dims=None) -> Tensor
+  python_module: linalg
+  variants: function
+
+- func: linalg_tensorsolve.out(Tensor self, Tensor other, int[]? dims=None, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+  variants: function
+
+- func: linalg_qr(Tensor A, str mode='reduced') -> (Tensor Q, Tensor R)
+  python_module: linalg
+  variants: function
+  structured_delegate: linalg_qr.out
+
+- func: linalg_qr.out(Tensor A, str mode='reduced', *, Tensor(a!) Q, Tensor(b!) R) -> (Tensor(a!) Q, Tensor(b!) R)
+  python_module: linalg
+  structured: True
+  dispatch:
+    CPU, CUDA: linalg_qr_out
+
+- func: linalg_matrix_power(Tensor self, int n) -> Tensor
+  python_module: linalg
+
+- func: linalg_matrix_power.out(Tensor self, int n, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+
+- func: linalg_matrix_rank.atol_rtol_tensor(Tensor input, *, Tensor? atol=None, Tensor? rtol=None, bool hermitian=False) -> Tensor
+  python_module: linalg
+  variants: function
+
+- func: linalg_matrix_rank.atol_rtol_tensor_out(Tensor input, *, Tensor? atol=None, Tensor? rtol=None, bool hermitian=False, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+  variants: function
+
+- func: linalg_matrix_rank.atol_rtol_float(Tensor self, *, float? atol=None, float? rtol=None, bool hermitian=False) -> Tensor
+  cpp_no_default_args: ['atol', 'rtol']
+  python_module: linalg
+  variants: function
+
+- func: linalg_matrix_rank.atol_rtol_float_out(Tensor self, *, float? atol=None, float? rtol=None, bool hermitian=False, Tensor(a!) out) -> Tensor(a!)
+  cpp_no_default_args: ['atol', 'rtol']
+  python_module: linalg
+  variants: function
+
+- func: linalg_matrix_rank(Tensor self, float tol, bool hermitian=False) -> Tensor
+  python_module: linalg
+  variants: function
+
+- func: linalg_matrix_rank.out(Tensor self, float tol, bool hermitian=False, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+  variants: function
+
+- func: linalg_matrix_rank.tol_tensor(Tensor input, Tensor tol, bool hermitian=False) -> Tensor
+  python_module: linalg
+  variants: function
+
+- func: linalg_matrix_rank.out_tol_tensor(Tensor input, Tensor tol, bool hermitian=False, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+  variants: function
+
+- func: linalg_multi_dot(Tensor[] tensors) -> Tensor
+  python_module: linalg
+
+- func: linalg_multi_dot.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!)
+  python_module: linalg
+
+## Functions related to the `torch.nested` namespace
+# Note [nested namespace binding]
+# Functions in the nested python module should have their names start with
+#   "nested_" underscore and be bound to the desired Python name in
+#   torch/nested/__init__.py, and the desired C++ name in torch/csrc/api/include/torch/nested.h.
+#   The "nested_" names should be hidden from the user and not documented.
+
+- func: nested_to_padded_tensor(Tensor self, float padding, int[]? output_size=None) -> Tensor
+  python_module: nested
+  variants: function
+
+## Functions that are only for testing
+# It is undocumented and should not be used outside of tests.
+- func: _test_serialization_subcmul(Tensor self, Tensor other, Scalar alpha=1) -> Tensor
+
+# Note: for testing COW materialization within `at::parallel_for` loop function
+- func: _test_parallel_materialize(Tensor self, int num_parallel, bool skip_first=False) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: _test_parallel_materialize
+
+# Note: this function is only for testing.
+- func: _test_optional_intlist(Tensor values, int[]? addends) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: _test_optional_intlist
+  autogen: _test_optional_intlist.out
+
+# Note: this function is only for testing.
+- func: _test_optional_filled_intlist(Tensor values, int[2]? addends) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: _test_optional_intlist
+  autogen: _test_optional_filled_intlist.out
+
+# Note: this function is only for testing.
+- func: _test_optional_floatlist(Tensor values, float[]? addends) -> Tensor
+  python_module: nn
+  dispatch:
+    CPU: _test_optional_floatlist
+  autogen: _test_optional_floatlist.out
+
+# Note: this function is only for testing.
+- func: _test_string_default(Tensor dummy, str a="\"'\\", str b='"\'\\') -> Tensor
+  python_module: nn
+
+# Note: this function is only for testing.
+- func: _test_ambiguous_defaults.a(Tensor dummy, int a=1, int b=1) -> Tensor
+  python_module: nn
+
+# Note: this function is only for testing.
+- func: _test_ambiguous_defaults.b(Tensor dummy, int a=2, str b="2") -> Tensor
+  cpp_no_default_args: ['a', 'b']
+  python_module: nn
+
+# Note: this function is only for testing.
+- func: _test_warn_in_autograd(Tensor self) -> Tensor
+  python_module: nn
+  dispatch:
+    CompositeExplicitAutograd: _test_warn_in_autograd
+  autogen: _test_warn_in_autograd.out
+
+# Note: this function is only for testing.
+- func: _test_autograd_multiple_dispatch.fullcoverage(Tensor self) -> Tensor
+  dispatch:
+    # the NestedTensor keys are necessary because NestedTensor has been removed
+    # from the CompositeExplicitAutograd keyset see Note [NestedTensor Not Included in Backend Keys]
+    CompositeExplicitAutograd, NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: _test_autograd_multiple_dispatch_fullcoverage
+  autogen: _test_autograd_multiple_dispatch.fullcoverage_out
+
+# Note: this function is only for testing.
+- func: _test_autograd_multiple_dispatch.ntonly(Tensor self, bool b) -> Tensor
+  dispatch:
+    CompositeImplicitAutograd, NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: _test_autograd_multiple_dispatch_ntonly
+
+# Note: this function is only for testing.
+- func: _test_autograd_multiple_dispatch_view(Tensor(a) self) -> Tensor(a)
+  dispatch:
+    CompositeExplicitAutograd: _test_autograd_multiple_dispatch_view
+
+# Note: this function is only for testing.
+- func: _test_autograd_multiple_dispatch_view_copy(Tensor self) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: _test_autograd_multiple_dispatch_view_copy
+  tags: view_copy
+  autogen: _test_autograd_multiple_dispatch_view_copy.out
+
+- func: segment_reduce(Tensor data, str reduce, *, Tensor? lengths=None, Tensor? indices=None, Tensor? offsets=None, int axis=0, bool unsafe=False, Scalar? initial=None) -> Tensor
+  variants: function
+  dispatch:
+    CPU, CUDA: segment_reduce_kernel
+  autogen: segment_reduce.out
+
+- func: _segment_reduce_backward(Tensor grad, Tensor output, Tensor data, str reduce, *, Tensor? lengths=None, Tensor? offsets=None, int axis=0, Scalar? initial=None) -> Tensor
+  variants: function
+  dispatch:
+    CPU, CUDA: _segment_reduce_backward_kernel
+  autogen: _segment_reduce_backward.out
+
+- func: pad_sequence(Tensor[] sequences, bool batch_first=False, float padding_value=0.0, str padding_side="right") -> Tensor
+  python_module: nn
+  variants: function
+
+- func: flatten_dense_tensors(Tensor[] tensors) -> Tensor
+  variants: function
+  python_module: nn
+
+- func: unflatten_dense_tensors(Tensor flat, Tensor[] tensors) -> Tensor[]
+  variants: function
+  python_module: nn
+
+- func: _nested_tensor_from_tensor_list(Tensor[] list, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: _nested_tensor_from_tensor_list
+  autogen: _nested_tensor_from_tensor_list.out
+
+- func: _fw_primal_copy(Tensor self, int level) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: _fw_primal_copy
+  tags: view_copy
+  autogen: _fw_primal_copy.out
+
+- func: _make_dual_copy(Tensor primal, Tensor tangent, int level) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: _make_dual_copy
+  tags: view_copy
+  autogen: _make_dual_copy.out
+
+- func: view_as_real_copy(Tensor self) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: view_as_real_copy
+  tags: view_copy
+  autogen: view_as_real_copy.out
+
+- func: view_as_complex_copy(Tensor self) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: view_as_complex_copy
+  tags: view_copy
+  autogen: view_as_complex_copy.out
+
+- func: _conj_copy(Tensor self) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: _conj_copy
+  tags: view_copy
+  autogen: _conj_copy.out
+
+- func: _neg_view_copy(Tensor self) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: _neg_view_copy
+  tags: view_copy
+  autogen: _neg_view_copy.out
+
+- func: as_strided_copy(Tensor self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: as_strided_copy_symint
+  tags: view_copy
+  autogen: as_strided_copy.out
+
+- func: _sparse_broadcast_to_copy(Tensor self, int[] size) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: _sparse_broadcast_to_copy
+  tags: view_copy
+  autogen: _sparse_broadcast_to_copy.out
+
+- func: diagonal_copy(Tensor self, int offset=0, int dim1=0, int dim2=1) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: diagonal_copy
+  tags: view_copy
+  autogen: diagonal_copy.out
+
+- func: expand_copy(Tensor self, SymInt[] size, *, bool implicit=False) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: expand_copy_symint
+  tags: view_copy
+  autogen: expand_copy.out
+
+- func: permute_copy(Tensor self, int[] dims) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: permute_copy
+  tags: view_copy
+  autogen: permute_copy.out
+
+- func: _reshape_alias_copy(Tensor self, SymInt[] size, SymInt[] stride) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: _reshape_alias_copy_symint
+  tags: view_copy
+  autogen: _reshape_alias_copy.out
+
+- func: select_copy.int(Tensor self, int dim, SymInt index) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: select_copy_symint
+    SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: select_copy_sparse_csr
+  tags: view_copy
+  autogen: select_copy.int_out
+
+- func: detach_copy(Tensor self) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: detach_copy
+  tags: view_copy
+  autogen: detach_copy.out
+
+- func: slice_copy.Tensor(Tensor self, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: slice_copy_Tensor_symint
+  tags: view_copy
+  autogen: slice_copy.Tensor_out
+
+- func: split_copy.Tensor(Tensor self, SymInt split_size, int dim=0) -> Tensor[]
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: split_copy_Tensor_symint
+  tags: view_copy
+
+- func: split_with_sizes_copy(Tensor self, SymInt[] split_sizes, int dim=0) -> Tensor[]
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: split_with_sizes_copy_symint
+  tags: view_copy
+
+- func: squeeze_copy(Tensor self) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: squeeze_copy
+  tags: view_copy
+  autogen: squeeze_copy.out
+
+- func: squeeze_copy.dim(Tensor self, int dim) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: squeeze_copy_dim
+  tags: view_copy
+  autogen: squeeze_copy.dim_out
+
+- func: squeeze_copy.dims(Tensor self, int[] dim) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: squeeze_copy_dims
+  tags: view_copy
+  autogen: squeeze_copy.dims_out
+
+- func: t_copy(Tensor self) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: t_copy
+  tags: view_copy
+  autogen: t_copy.out
+
+- func: transpose_copy.int(Tensor self, int dim0, int dim1) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: transpose_copy_int
+  tags: view_copy
+  autogen: transpose_copy.int_out
+
+- func: unsqueeze_copy(Tensor self, int dim) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: unsqueeze_copy
+  tags: view_copy
+  autogen: unsqueeze_copy.out
+
+- func: _indices_copy(Tensor self) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: _indices_copy
+  tags: view_copy
+  autogen: _indices_copy.out
+
+- func: _values_copy(Tensor self) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: _values_copy
+  tags: view_copy
+  autogen: _values_copy.out
+
+- func: indices_copy(Tensor self) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: indices_copy
+  tags: view_copy
+  autogen: indices_copy.out
+
+- func: values_copy(Tensor self) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: values_copy
+  tags: view_copy
+  autogen: values_copy.out
+
+- func: crow_indices_copy(Tensor self) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: crow_indices_copy
+  tags: view_copy
+  autogen: crow_indices_copy.out
+
+- func: col_indices_copy(Tensor self) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: col_indices_copy
+  tags: view_copy
+  autogen: col_indices_copy.out
+
+- func: ccol_indices_copy(Tensor self) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: ccol_indices_copy
+  tags: view_copy
+  autogen: ccol_indices_copy.out
+
+- func: row_indices_copy(Tensor self) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: row_indices_copy
+  tags: view_copy
+  autogen: row_indices_copy.out
+
+- func: unbind_copy.int(Tensor self, int dim=0) -> Tensor[]
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: unbind_copy_int
+  tags: view_copy
+
+- func: unbind_copy.int_out(Tensor self, int dim=0, *, Tensor(a!)[] out) -> ()
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: unbind_copy_int_out
+
+- func: split_copy.Tensor_out(Tensor self, SymInt split_size, int dim=0, *, Tensor(a!)[] out) -> ()
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: split_copy_Tensor_out
+
+
+- func: split_with_sizes_copy.out(Tensor self, SymInt[] split_sizes, int dim=0, *, Tensor(a!)[] out) -> ()
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: split_with_sizes_copy_out
+    CUDA: split_with_sizes_copy_out_cuda
+
+- func: view_copy(Tensor self, SymInt[] size) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: view_copy_symint
+  tags: view_copy
+  autogen: view_copy.out
+
+- func: view_copy.dtype(Tensor self, ScalarType dtype) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: view_copy_dtype
+  tags: view_copy
+  autogen: view_copy.dtype_out
+
+- func: unfold_copy(Tensor self, int dimension, int size, int step) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: unfold_copy
+  tags: view_copy
+  autogen: unfold_copy.out
+
+- func: alias_copy(Tensor self) -> Tensor
+  variants: function
+  dispatch:
+    CompositeExplicitAutogradNonFunctional: alias_copy
+  tags: view_copy
+  autogen: alias_copy.out
+
+- func: to_padded_tensor(Tensor self, float padding, SymInt[]? output_size=None) -> Tensor
+  variants: method
+  dispatch:
+    NestedTensorCPU: NestedTensor_to_padded_tensor_generic
+    NestedTensorCUDA: NestedTensor_to_padded_tensor_cuda
+  autogen: to_padded_tensor.out
+
+- func: _jagged_to_padded_dense_forward(Tensor values, Tensor[] offsets, SymInt[] max_lengths, float padding_value=0.0) -> Tensor
+  variants: function
+  dispatch:
+    CUDA: _fbgemm_jagged_to_padded_dense_forward
+    CPU: _jagged_to_padded_dense_forward_cpu
+
+- func: _padded_dense_to_jagged_forward(Tensor dense, Tensor[] offsets, SymInt? total_L=None) -> Tensor
+  variants: function
+  dispatch:
+    CUDA: _fbgemm_dense_to_jagged_forward_symint
+    CPU: _padded_dense_to_jagged_forward_cpu
+
+- func: _nested_from_padded_tensor(Tensor padded, Tensor offsets, Tensor dummy, int ragged_idx=1, Tensor? min_seqlen=None, Tensor? max_seqlen=None, SymInt? sum_S=None) -> Tensor
+  variants: function
+  device_check: NoCheck
+  dispatch: {}
+
+- func: _nested_tensor_softmax_with_shape(Tensor self, Tensor query) -> Tensor
+  dispatch:
+    NestedTensorCPU: NestedTensor_softmax_dropout
+    NestedTensorCUDA: NestedTensor_softmax_dropout_cuda
+  tags: nondeterministic_seeded
+
+- func: _safe_softmax(Tensor self, int dim, ScalarType? dtype=None) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: _safe_softmax
+    NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: _safe_softmax
+
+# Apparently, putting "forward" in the name will cause Python bindings to be skipped, so "fwd" it is.
+- func: _transformer_encoder_layer_fwd(Tensor src, int embed_dim, int num_heads, Tensor qkv_weight, Tensor qkv_bias, Tensor proj_weight, Tensor proj_bias, bool use_gelu, bool norm_first, float eps, Tensor norm_weight_1, Tensor norm_bias_1, Tensor norm_weight_2, Tensor norm_bias_2, Tensor ffn_weight_1, Tensor ffn_bias_1, Tensor ffn_weight_2, Tensor ffn_bias_2, Tensor? mask=None, int? mask_type=None) -> Tensor
+  variants: function
+  dispatch:
+    CPU, CUDA, NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA: transformer_encoder_layer_forward
+  autogen: _transformer_encoder_layer_fwd.out
+
+- func: _native_multi_head_attention(Tensor query, Tensor key, Tensor value, int embed_dim, int num_head, Tensor qkv_weight, Tensor qkv_bias, Tensor proj_weight, Tensor proj_bias, Tensor? mask=None, bool need_weights=True, bool average_attn_weights=True, int? mask_type=None) -> (Tensor, Tensor)
+  variants: function
+  dispatch:
+    CPU, NestedTensorCPU: native_multi_head_attention_cpu
+    CUDA, NestedTensorCUDA: native_multi_head_attention_cuda
+  autogen: _native_multi_head_attention.out
+
+- func: scaled_dot_product_attention(Tensor query, Tensor key, Tensor value, Tensor? attn_mask=None, float dropout_p=0.0, bool is_causal=False, *, float? scale=None, bool enable_gqa=False) -> Tensor
+  python_module: nn
+  variants: function
+  autogen: scaled_dot_product_attention.out
+  tags: nondeterministic_seeded
+
+# This aten function is kept so that we can test the choice function from Python
+- func: _fused_sdp_choice(Tensor query, Tensor key, Tensor value, Tensor? attn_mask=None, float dropout_p=0.0, bool is_causal=False, *, float? scale=None, bool enable_gqa=False) -> int
+  dispatch:
+    Meta: _fused_sdp_choice_meta
+    CPU, NestedTensorCPU: _fused_sdp_choice_cpp
+    CUDA, NestedTensorCUDA: _fused_sdp_choice_cuda
+    XPU: _fused_sdp_choice_xpu
+  tags: nondeterministic_seeded
+
+- func: _scaled_dot_product_attention_math(Tensor query, Tensor key, Tensor value, Tensor? attn_mask=None, float dropout_p=0.0, bool is_causal=False, Tensor? dropout_mask=None, *, float? scale=None, bool enable_gqa=False) -> (Tensor, Tensor)
+  variants: function
+  tags: nondeterministic_seeded
+
+- func: _scaled_dot_product_attention_math_for_mps(Tensor query, Tensor key, Tensor value, Tensor? attn_mask=None, float dropout_p=0.0, bool is_causal=False, Tensor? dropout_mask=None, *, float? scale=None) -> (Tensor, Tensor)
+  dispatch:
+    MPS: _scaled_dot_product_attention_math_mps
+  tags: nondeterministic_seeded
+
+- func: _scaled_dot_product_flash_attention(Tensor query, Tensor key, Tensor value, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor rng_state, Tensor unused, Tensor debug_attn_mask)
+  dispatch:
+    CUDA: _scaled_dot_product_flash_attention_cuda
+    NestedTensorCUDA: _scaled_dot_product_flash_attention_nestedtensor_cuda
+  tags: nondeterministic_seeded
+
+- func: _scaled_dot_product_flash_attention_for_cpu(Tensor query, Tensor key, Tensor value, float dropout_p=0.0, bool is_causal=False, *, Tensor? attn_mask=None, float? scale=None) -> (Tensor output, Tensor logsumexp)
+  dispatch:
+    CPU: _scaled_dot_product_flash_attention_cpu
+  tags: nondeterministic_seeded
+
+- func: _scaled_dot_product_fused_attention_overrideable(Tensor query, Tensor key, Tensor value, Tensor? attn_bias=None, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor philox_seed, Tensor philox_offset, Tensor debug_attn_mask)
+  dispatch:
+    CompositeExplicitAutograd: _scaled_dot_product_fused_attention_overrideable
+    XPU: _scaled_dot_product_fused_attention_overrideable_xpu
+  tags: nondeterministic_seeded
+
+- func: _scaled_dot_product_flash_attention_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, Tensor philox_seed, Tensor philox_offset, *, float? scale=None) -> (Tensor grad_query, Tensor grad_key, Tensor grad_value)
+  device_check: NoCheck
+  variants: function
+  dispatch:
+    CUDA: _scaled_dot_product_flash_attention_backward_cuda
+    NestedTensorCUDA: _scaled_dot_product_flash_attention_backward_nested
+
+- func: _scaled_dot_product_flash_attention_for_cpu_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, float dropout_p, bool is_causal, *, Tensor? attn_mask=None, float? scale=None) -> (Tensor grad_query, Tensor grad_key, Tensor grad_value)
+  device_check: NoCheck
+  variants: function
+  dispatch:
+    CPU: _scaled_dot_product_flash_attention_cpu_backward
+
+- func: _scaled_dot_product_fused_attention_overrideable_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor attn_bias, bool[4] grad_input_mask, Tensor out, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, Tensor philox_seed, Tensor philox_offset, *, float? scale=None) -> (Tensor grad_query, Tensor grad_key, Tensor grad_value, Tensor grad_attn_bias)
+  device_check: NoCheck
+  variants: function
+  dispatch:
+    CompositeExplicitAutograd: _scaled_dot_product_fused_attention_overrideable_backward
+
+- func: _scaled_dot_product_efficient_attention(Tensor query, Tensor key, Tensor value, Tensor? attn_bias, bool compute_log_sumexp, float dropout_p=0.0, bool is_causal=False, *, float? scale=None) -> (Tensor output, Tensor log_sumexp, Tensor philox_seed, Tensor philox_offset)
+  dispatch:
+    CUDA: _scaled_dot_product_efficient_attention_cuda
+    NestedTensorCUDA: _scaled_dot_product_efficient_attention_nestedtensor_cuda
+  tags: nondeterministic_seeded
+
+- func: _scaled_dot_product_efficient_attention_backward(Tensor grad_out_, Tensor query, Tensor key, Tensor value, Tensor attn_bias, Tensor out, Tensor logsumexp, Tensor philox_seed, Tensor philox_offset, float dropout_p, bool[4] grad_input_mask, bool is_causal=False, *, float? scale=None) -> (Tensor, Tensor, Tensor, Tensor)
+  device_check: NoCheck
+  dispatch:
+    CUDA: _scaled_dot_product_efficient_attention_backward_cuda
+  tags: nondeterministic_seeded
+
+- func: _scaled_dot_product_cudnn_attention(Tensor query, Tensor key, Tensor value, Tensor? attn_bias, bool compute_log_sumexp, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor philox_seed, Tensor philox_offset, Tensor debug_attn_mask)
+  dispatch:
+    CUDA: _scaled_dot_product_cudnn_attention_cuda
+    NestedTensorCUDA: _scaled_dot_product_cudnn_attention_nestedtensor_cuda
+  tags: nondeterministic_seeded
+
+- func: _scaled_dot_product_cudnn_attention_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, Tensor philox_seed, Tensor philox_offset, Tensor attn_bias, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, *, float? scale=None) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    CUDA: _scaled_dot_product_cudnn_attention_backward_cuda
+    NestedTensorCUDA: _scaled_dot_product_cudnn_attention_nestedtensor_backward_cuda
+  tags: nondeterministic_seeded
+
+- func: _flash_attention_forward(Tensor query, Tensor key, Tensor value, Tensor? cum_seq_q, Tensor? cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, bool return_debug_mask, *, float? scale=None, SymInt? window_size_left=None, SymInt? window_size_right=None, Tensor? seqused_k=None, Tensor? alibi_slopes=None) -> (Tensor output, Tensor softmax_logsumexp, Tensor rng_state, Tensor unused, Tensor debug_attn_mask)
+  variants: function
+  dispatch:
+    CUDA: _flash_attention_forward
+  tags: nondeterministic_seeded
+
+- func: _flash_attention_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, Tensor rng_state, Tensor unused, *, float? scale=None, SymInt? window_size_left=None, SymInt? window_size_right=None) -> (Tensor, Tensor, Tensor)
+  device_check: NoCheck
+  variants: function
+  dispatch:
+    CUDA: _flash_attention_backward
+
+# Returns output, logsumexp if compute_logsumexp
+- func: _efficient_attention_forward(Tensor query, Tensor key, Tensor value, Tensor? bias, Tensor? cu_seqlens_q, Tensor? cu_seqlens_k, SymInt? max_seqlen_q, SymInt? max_seqlen_k, float dropout_p, int custom_mask_type, bool compute_log_sumexp=False, *, float? scale=None, Tensor? seqlen_k=None, int? window_size=None) -> (Tensor output, Tensor logsumexp, Tensor philox_seed, Tensor philox_offset, SymInt max_seqlen_batch_q, SymInt max_seqlen_batch_k)
+  variants: function
+  dispatch:
+    CUDA: _efficient_attention_forward
+  tags: nondeterministic_seeded
+
+- func: _efficient_attention_backward(Tensor grad_out_, Tensor query, Tensor key, Tensor value, Tensor? bias, Tensor out, Tensor? cu_seqlens_q, Tensor? cu_seqlens_k, SymInt max_seqlen_q, SymInt max_seqlen_k, Tensor logsumexp, float dropout_p, Tensor philox_seed, Tensor philox_offset, int custom_mask_type, bool bias_requires_grad, *, float? scale=None, int? num_splits_key=None, int? window_size=None, bool shared_storage_dqdkdv=False) -> (Tensor, Tensor, Tensor, Tensor)
+  device_check: NoCheck
+  variants: function
+  dispatch:
+    CUDA: _efficient_attention_backward
+
+- func: _cudnn_attention_forward(Tensor query, Tensor key, Tensor value, Tensor? attn_bias, Tensor? cum_seq_q, Tensor? cum_seq_k, SymInt max_q, SymInt max_k, bool compute_log_sumexp, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor philox_seed, Tensor philox_offset, Tensor debug_attn_mask)
+  dispatch:
+    CUDA: _cudnn_attention_forward
+  tags: nondeterministic_seeded
+
+- func: _cudnn_attention_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, Tensor philox_seed, Tensor philox_offset, Tensor attn_bias, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, *, float? scale=None) -> (Tensor, Tensor, Tensor)
+  dispatch:
+    CUDA: _cudnn_attention_backward
+  tags: nondeterministic_seeded
+
+- func: _triton_scaled_dot_attention(Tensor q, Tensor k, Tensor v, float dropout_p=0.0) -> Tensor
+  variants: function
+  dispatch:
+    CUDA: triton_scaled_dot_attention
+  tags: nondeterministic_seeded
+  autogen: _triton_scaled_dot_attention.out
+
+- func: _fill_mem_eff_dropout_mask_(Tensor(a!) self, float dropout_p, int seed, int offset) -> Tensor(a!)
+  variants: function
+  dispatch:
+    CUDA: _fill_mem_eff_dropout_mask_
+  tags: nondeterministic_seeded
+
+- func: _triton_multi_head_attention(Tensor query, Tensor key, Tensor value, int embed_dim, int num_head, Tensor qkv_weight, Tensor qkv_bias, Tensor proj_weight, Tensor proj_bias, Tensor? mask=None) -> Tensor
+  variants: function
+  dispatch:
+    CUDA: triton_multi_head_attention
+  autogen: _triton_multi_head_attention.out
+
+- func: special_airy_ai(Tensor x) -> Tensor
+  python_module: special
+  structured_delegate: special_airy_ai.out
+  variants: function
+  tags: pointwise
+
+- func: special_airy_ai.out(Tensor x, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA: special_airy_ai_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_bessel_j0(Tensor self) -> Tensor
+  python_module: special
+  structured_delegate: special_bessel_j0.out
+  variants: function
+  tags: pointwise
+
+- func: special_bessel_j0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA, MPS: special_bessel_j0_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_bessel_j1(Tensor self) -> Tensor
+  python_module: special
+  structured_delegate: special_bessel_j1.out
+  variants: function
+  tags: pointwise
+
+- func: special_bessel_j1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA, MPS: special_bessel_j1_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_bessel_y0(Tensor self) -> Tensor
+  python_module: special
+  structured_delegate: special_bessel_y0.out
+  variants: function
+  tags: pointwise
+
+- func: special_bessel_y0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA, MPS: special_bessel_y0_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_bessel_y1(Tensor self) -> Tensor
+  python_module: special
+  structured_delegate: special_bessel_y1.out
+  variants: function
+  tags: pointwise
+
+- func: special_bessel_y1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA, MPS: special_bessel_y1_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_t(Tensor x, Tensor n) -> Tensor
+  device_check: NoCheck
+  python_module: special
+  structured_delegate: special_chebyshev_polynomial_t.out
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_t.x_scalar(Scalar x, Tensor n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_chebyshev_polynomial_t
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_t.n_scalar(Tensor x, Scalar n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_chebyshev_polynomial_t
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_t.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck
+  dispatch:
+    CPU, CUDA, MPS: special_chebyshev_polynomial_t_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_t.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_chebyshev_polynomial_t_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_t.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_chebyshev_polynomial_t_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_u(Tensor x, Tensor n) -> Tensor
+  device_check: NoCheck
+  python_module: special
+  structured_delegate: special_chebyshev_polynomial_u.out
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_u.x_scalar(Scalar x, Tensor n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_chebyshev_polynomial_u
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_u.n_scalar(Tensor x, Scalar n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_chebyshev_polynomial_u
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_u.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck
+  dispatch:
+    CPU, CUDA, MPS: special_chebyshev_polynomial_u_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_u.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_chebyshev_polynomial_u_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_u.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_chebyshev_polynomial_u_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_v(Tensor x, Tensor n) -> Tensor
+  device_check: NoCheck
+  python_module: special
+  structured_delegate: special_chebyshev_polynomial_v.out
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_v.x_scalar(Scalar x, Tensor n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_chebyshev_polynomial_v
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_v.n_scalar(Tensor x, Scalar n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_chebyshev_polynomial_v
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_v.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck
+  dispatch:
+    CPU, CUDA, MPS: special_chebyshev_polynomial_v_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_v.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_chebyshev_polynomial_v_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_v.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_chebyshev_polynomial_v_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_w(Tensor x, Tensor n) -> Tensor
+  device_check: NoCheck
+  python_module: special
+  structured_delegate: special_chebyshev_polynomial_w.out
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_w.x_scalar(Scalar x, Tensor n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_chebyshev_polynomial_w
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_w.n_scalar(Tensor x, Scalar n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_chebyshev_polynomial_w
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_w.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck
+  dispatch:
+    CPU, CUDA, MPS: special_chebyshev_polynomial_w_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_w.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_chebyshev_polynomial_w_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_chebyshev_polynomial_w.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_chebyshev_polynomial_w_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_hermite_polynomial_h(Tensor x, Tensor n) -> Tensor
+  device_check: NoCheck
+  python_module: special
+  structured_delegate: special_hermite_polynomial_h.out
+  variants: function
+  tags: pointwise
+
+- func: special_hermite_polynomial_h.x_scalar(Scalar x, Tensor n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_hermite_polynomial_h
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_hermite_polynomial_h.n_scalar(Tensor x, Scalar n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_hermite_polynomial_h
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_hermite_polynomial_h.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck
+  dispatch:
+    CPU, CUDA, MPS: special_hermite_polynomial_h_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_hermite_polynomial_h.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_hermite_polynomial_h_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_hermite_polynomial_h.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_hermite_polynomial_h_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_hermite_polynomial_he(Tensor x, Tensor n) -> Tensor
+  device_check: NoCheck
+  python_module: special
+  structured_delegate: special_hermite_polynomial_he.out
+  variants: function
+  tags: pointwise
+
+- func: special_hermite_polynomial_he.x_scalar(Scalar x, Tensor n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_hermite_polynomial_he
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_hermite_polynomial_he.n_scalar(Tensor x, Scalar n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_hermite_polynomial_he
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_hermite_polynomial_he.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck
+  dispatch:
+    CPU, CUDA, MPS: special_hermite_polynomial_he_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_hermite_polynomial_he.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_hermite_polynomial_he_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_hermite_polynomial_he.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_hermite_polynomial_he_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_laguerre_polynomial_l(Tensor x, Tensor n) -> Tensor
+  device_check: NoCheck
+  python_module: special
+  structured_delegate: special_laguerre_polynomial_l.out
+  variants: function
+  tags: pointwise
+
+- func: special_laguerre_polynomial_l.x_scalar(Scalar x, Tensor n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_laguerre_polynomial_l
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_laguerre_polynomial_l.n_scalar(Tensor x, Scalar n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_laguerre_polynomial_l
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_laguerre_polynomial_l.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck
+  dispatch:
+    CPU, CUDA: special_laguerre_polynomial_l_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_laguerre_polynomial_l.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_laguerre_polynomial_l_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_laguerre_polynomial_l.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_laguerre_polynomial_l_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_legendre_polynomial_p(Tensor x, Tensor n) -> Tensor
+  device_check: NoCheck
+  python_module: special
+  structured_delegate: special_legendre_polynomial_p.out
+  variants: function
+  tags: pointwise
+
+- func: special_legendre_polynomial_p.x_scalar(Scalar x, Tensor n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_legendre_polynomial_p
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_legendre_polynomial_p.n_scalar(Tensor x, Scalar n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_legendre_polynomial_p
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_legendre_polynomial_p.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck
+  dispatch:
+    CPU, CUDA: special_legendre_polynomial_p_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_legendre_polynomial_p.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_legendre_polynomial_p_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_legendre_polynomial_p.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_legendre_polynomial_p_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_modified_bessel_i0(Tensor self) -> Tensor
+  python_module: special
+  structured_delegate: special_modified_bessel_i0.out
+  variants: function
+  tags: pointwise
+
+- func: special_modified_bessel_i0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA, MPS: special_modified_bessel_i0_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_modified_bessel_i1(Tensor self) -> Tensor
+  python_module: special
+  structured_delegate: special_modified_bessel_i1.out
+  variants: function
+  tags: pointwise
+
+- func: special_modified_bessel_i1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA, MPS: special_modified_bessel_i1_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_modified_bessel_k0(Tensor self) -> Tensor
+  python_module: special
+  structured_delegate: special_modified_bessel_k0.out
+  variants: function
+  tags: pointwise
+
+- func: special_modified_bessel_k0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA, MPS: special_modified_bessel_k0_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_modified_bessel_k1(Tensor self) -> Tensor
+  python_module: special
+  structured_delegate: special_modified_bessel_k1.out
+  variants: function
+  tags: pointwise
+
+- func: special_modified_bessel_k1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA, MPS: special_modified_bessel_k1_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_scaled_modified_bessel_k0(Tensor x) -> Tensor
+  python_module: special
+  structured_delegate: special_scaled_modified_bessel_k0.out
+  variants: function
+  tags: pointwise
+
+- func: special_scaled_modified_bessel_k0.out(Tensor x, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA, MPS: special_scaled_modified_bessel_k0_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_scaled_modified_bessel_k1(Tensor x) -> Tensor
+  python_module: special
+  structured_delegate: special_scaled_modified_bessel_k1.out
+  variants: function
+  tags: pointwise
+
+- func: special_scaled_modified_bessel_k1.out(Tensor x, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA, MPS: special_scaled_modified_bessel_k1_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_t(Tensor x, Tensor n) -> Tensor
+  device_check: NoCheck
+  python_module: special
+  structured_delegate: special_shifted_chebyshev_polynomial_t.out
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_t.x_scalar(Scalar x, Tensor n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_t
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_t.n_scalar(Tensor x, Scalar n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_t
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_t.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck
+  dispatch:
+    CPU, CUDA, MPS: special_shifted_chebyshev_polynomial_t_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_t.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_t_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_t.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_t_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_u(Tensor x, Tensor n) -> Tensor
+  device_check: NoCheck
+  python_module: special
+  structured_delegate: special_shifted_chebyshev_polynomial_u.out
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_u.x_scalar(Scalar x, Tensor n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_u
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_u.n_scalar(Tensor x, Scalar n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_u
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_u.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck
+  dispatch:
+    CPU, CUDA, MPS: special_shifted_chebyshev_polynomial_u_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_u.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_u_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_u.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_u_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_v(Tensor x, Tensor n) -> Tensor
+  device_check: NoCheck
+  python_module: special
+  structured_delegate: special_shifted_chebyshev_polynomial_v.out
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_v.x_scalar(Scalar x, Tensor n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_v
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_v.n_scalar(Tensor x, Scalar n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_v
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_v.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck
+  dispatch:
+    CPU, CUDA, MPS: special_shifted_chebyshev_polynomial_v_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_v.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_v_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_v.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_v_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_w(Tensor x, Tensor n) -> Tensor
+  device_check: NoCheck
+  python_module: special
+  structured_delegate: special_shifted_chebyshev_polynomial_w.out
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_w.x_scalar(Scalar x, Tensor n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_w
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_w.n_scalar(Tensor x, Scalar n) -> Tensor
+  dispatch:
+    CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_w
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_w.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  device_check: NoCheck
+  dispatch:
+    CPU, CUDA, MPS: special_shifted_chebyshev_polynomial_w_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_w.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_w_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_w.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_w_out
+  device_check: NoCheck
+  python_module: special
+  variants: function
+  tags: pointwise
+
+- func: special_spherical_bessel_j0(Tensor x) -> Tensor
+  python_module: special
+  structured_delegate: special_spherical_bessel_j0.out
+  variants: function
+  tags: pointwise
+
+- func: special_spherical_bessel_j0.out(Tensor x, *, Tensor(a!) out) -> Tensor(a!)
+  dispatch:
+    CPU, CUDA, MPS: special_spherical_bessel_j0_out
+  python_module: special
+  structured_inherits: TensorIteratorBase
+  structured: True
+  variants: function
+  tags: pointwise
+
+# Aux function used in the test TestPythonDispatch.test_kwarg_only_and_positional_default
+# within test/test_python_dispatch.py
+- func: _foobar(Tensor self, bool arg1=True, bool arg2=True, *, bool arg3=True) -> Tensor
+  dispatch:
+    CPU: foobar
+  autogen: _foobar.out
+
+- func: _fused_adam_(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, float lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> ()
+  # Unlike "foreach" functions, lists of tensors should be guaranteed to be on the same device (for now).
+  variants: function
+  dispatch:
+    CPU: _fused_adam_kernel_cpu_
+    CUDA: _fused_adam_kernel_cuda_
+    MPS: _fused_adam_kernel_mps_
+  autogen: _fused_adam, _fused_adam.out
+
+- func: _fused_adam_.tensor_lr(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, Tensor lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> ()
+  # Unlike "foreach" functions, lists of tensors should be guaranteed to be on the same device (for now),
+  # but still skip the device check as the Tensor LR can be on CPU
+  device_check: NoCheck
+  variants: function
+  dispatch:
+    CPU: _fused_adam_kernel_cpu_
+    CUDA: _fused_adam_kernel_cuda_
+    MPS: _fused_adam_kernel_mps_
+  autogen: _fused_adam.tensor_lr, _fused_adam.tensor_lr_out
+
+- func: _fused_adamw_(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, float lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> ()
+  # Unlike "foreach" functions, lists of tensors should be guaranteed to be on the same device (for now).
+  variants: function
+  dispatch:
+    CPU: _fused_adamw_kernel_cpu_
+    CUDA: _fused_adamw_kernel_cuda_
+    MPS: _fused_adamw_kernel_mps_
+  autogen: _fused_adamw, _fused_adamw.out
+
+- func: _fused_adamw_.tensor_lr(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, Tensor lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> ()
+  # Unlike "foreach" functions, lists of tensors should be guaranteed to be on the same device (for now),
+  # but still skip the device check as the Tensor LR can be on CPU
+  device_check: NoCheck
+  variants: function
+  dispatch:
+    CPU: _fused_adamw_kernel_cpu_
+    CUDA: _fused_adamw_kernel_cuda_
+    MPS: _fused_adamw_kernel_mps_
+  autogen: _fused_adamw.tensor_lr, _fused_adamw.tensor_lr_out
+
+- func: _fused_sgd_(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] momentum_buffer_list, *, float weight_decay, float momentum, float lr, float dampening, bool nesterov, bool maximize, bool is_first_step, Tensor? grad_scale=None, Tensor? found_inf=None) -> ()
+  # Unlike "foreach" functions, lists of tensors should be guaranteed to be on the same device (for now).
+  variants: function
+  dispatch:
+    CPU: _fused_sgd_kernel_cpu_
+    CUDA: _fused_sgd_kernel_cuda_
+    MPS: _fused_sgd_kernel_mps_
+  autogen: _fused_sgd, _fused_sgd.out
+
+- func: _fused_sgd_.tensor_lr(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] momentum_buffer_list, *, float weight_decay, float momentum, Tensor lr, float dampening, bool nesterov, bool maximize, bool is_first_step, Tensor? grad_scale=None, Tensor? found_inf=None) -> ()
+  # Unlike "foreach" functions, lists of tensors should be guaranteed to be on the same device (for now).
+  # but still skip the device check as the Tensor LR can be on CPU
+  device_check: NoCheck
+  variants: function
+  dispatch:
+    CPU: _fused_sgd_kernel_cpu_
+    CUDA: _fused_sgd_kernel_cuda_
+    MPS: _fused_sgd_kernel_mps_
+  autogen: _fused_sgd.tensor_lr, _fused_sgd.tensor_lr_out
+
+- func: _fused_adagrad_(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] state_sums, Tensor(d!)[] state_steps, *, float lr, float lr_decay, float weight_decay, float eps, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> ()
+  variants: function
+  dispatch:
+    CPU: _fused_adagrad_kernel_cpu_
+    CUDA: _fused_adagrad_kernel_cuda_
+  autogen: _fused_adagrad, _fused_adagrad.out
+
+- func: _fused_adagrad_.tensor_lr(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] state_sums, Tensor[] state_steps, *, Tensor lr, float lr_decay, float weight_decay, float eps, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> ()
+  device_check: NoCheck
+  variants: function
+  dispatch:
+    CPU: _fused_adagrad_kernel_cpu_
+    CUDA: _fused_adagrad_kernel_cuda_
+  autogen: _fused_adagrad.tensor_lr, _fused_adagrad.tensor_lr_out
+
+# This op is ONLY used by pytorch/XLA in functionalization, and should never show up in vanilla eager mode or in any pytorch tracing contexts.
+- func: _propagate_xla_data(Tensor input, Tensor output) -> ()
+  variants: function
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/native/tags.yaml b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/native/tags.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..101e18ae84280f8ac35fae779b54577ebed99253
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/native/tags.yaml
@@ -0,0 +1,95 @@
+# This yaml file contains all the possible tags that can be defined in `tags` in `native_functions.yaml`
+
+- tag: inplace_view
+  desc: |
+          This tag indicates if an operator *only* modifies the tensor metadata
+- tag: pt2_compliant_tag
+  desc: |
+          This tag indicates if the operator is guaranteed to
+          work with the PT2 compilation APIs (torch.compile,
+          torch.export, etc). If you add this tag to an
+          operator, please use
+          `torch.testing._internal.optest.opcheck` to test that
+          the operator has been registered correctly and
+          works with torch.compile
+- tag: view_copy
+  desc: |
+          This tag indicates operators that are *_copy* variants
+          of view/aliasing operators. If an operator has a view_copy tag,
+          then it should have the name {op}_copy, where {op} is a view operator.
+- tag: dynamic_output_shape
+  desc: |
+          This tag indicates if an operator's output's shape depends on input Tensor
+          data.
+- tag: data_dependent_output
+  desc: |
+          Operator has a non-Tensor output whose value is dependent on the data
+          of Tensor inputs.  Among other things, this implies that this operator
+          cannot be run with meta tensor (since data is not available), nor
+          can it be symbolically traced.
+- tag: generated
+  desc: |
+          This tag indicates that the operator doesn't have an explicit entry in
+          native_functions.yaml, and instead was generated automatically by the codegen.
+- tag: nondeterministic_seeded
+  desc: |
+          This tag indicates if an operator is nondeterministically seeded
+          (i.e., is random) such that the operator intentionally produces
+          different results when run twice on the same inputs, but this randomness
+          is controlled by a Generator which, if reseeded would give you the
+          same result.
+- tag: nondeterministic_bitwise
+  desc: |
+          This tag indicates if an operator doesn't guarantee bitwise equivalence
+          across different runs of an operator with identical inputs.
+- tag: needs_exact_strides
+  desc: |
+          This tag indicates that the operator should be passed Tensors following
+          the same strides as observed in eager when compiled in inductor.
+          Only one of {needs_exact_strides, needs_contiguous_strides, needs_fixed_stride_order, flexible_layout}
+          can apply; if multiple are assigned then we assume the most restrictive one.
+- tag: needs_contiguous_strides
+  desc: |
+          This tag indicates that the operator should be passed contiguous Tensors.
+          Failure to do so will result in undefined behavior.
+- tag: needs_fixed_stride_order
+  desc: |
+          This tag indicates that the operator should be passed Tensors following
+          the same stride permutation as observed in eager when compiled in inductor.
+          Only one of {needs_exact_strides, needs_contiguous_strides, needs_fixed_stride_order, flexible_layout}
+          can apply; if multiple are assigned then we assume the most restrictive one.
+- tag: flexible_layout
+  desc: |
+          This tag indicates that the custom operator can accept inputs with varying
+          strides/storage_offset and that when compiled, Inductor is allowed to change
+          the strides/storage_offset of inputs to the custom operator.
+          Only one of {needs_exact_strides, needs_contiguous_strides, needs_fixed_stride_order, flexible_layout}
+          can apply; if multiple are assigned then we assume the most restrictive one.
+
+# NOTE [Core ATen Ops]
+- tag: core
+  desc: |
+          Core aten ops is a subset of aten ops that remains after aten-to-aten decomposition and
+          functionalization pass. Core aten ops are fully functional and adhere to single static
+          assignment (SSA): this implies there will be no `inplace` or `_out` variants in this opset.
+          This opset is designed to serve as the functional IR to interface with compiler backends.
+          In contrast to primTorch, core aten opset doesn't decompose ops into explicit
+          type promotion and broadcasting ops.
+          Core aten ops is also effectively the opset produced by torchdynamo.export(aten_graph=True),
+          and thus can be used as an opset for export purpose.
+- tag: pointwise
+  desc: |
+          Pointwise operators are operators where each element of the output is computed only by accessing
+          the corresponding element of all the broadcasted inputs. The output shape will be the broadcasted
+          shape of the inputs.
+- tag: maybe_aliasing_or_mutating
+  desc: |
+          For some ops, we can't statically determine whether the op is functional or not. Note that this is only
+          relevant to CIA ops that decompose before functionalization/autograd. It is useful to
+          know this information for export as we would want to decompose these ops as they are unsafe to be
+          preserved.
+- tag: cudagraph_unsafe
+  desc: |
+          This operator does not support cudagraphs. The presence of this tag on an operator will cause
+          Inductor to split the graph around this operator. Note that operators without this tag may still
+          not support CUDAGraphs. Inductor may have other hardcoded lists around that.
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/ATenOpList.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/ATenOpList.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..5de3424857e236917eb68940e7904446de59f586
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/ATenOpList.cpp
@@ -0,0 +1,36 @@
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+// ${generated_comment}
+
+namespace at {
+
+namespace {
+struct OpNameEquals final {
+  bool operator()(const std::pair& lhs, const std::pair& rhs) const {
+      return 0 == strcmp(lhs.first, rhs.first) && 0 == strcmp(lhs.second, rhs.second);
+  }
+};
+
+struct OpNameHash final {
+  size_t operator()(const std::pair& p) const {
+      // use std::hash because std::hash would hash pointers and not pointed-to strings
+      return std::hash()(p.first) ^ (~ std::hash()(p.second));
+  }
+};
+}
+
+bool is_custom_op(const c10::OperatorName& opName) {
+  static std::unordered_set, OpNameHash, OpNameEquals> ops {
+    ${aten_ops}
+    {"", ""}
+  };
+  return ops.count(std::make_pair(
+             opName.name.c_str(), opName.overload_name.c_str())) == 0;
+}
+}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/CompositeViewCopyKernels.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/CompositeViewCopyKernels.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..47097d7aa4320674bec4bddbb5ac861309334f0c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/CompositeViewCopyKernels.cpp
@@ -0,0 +1,73 @@
+#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
+// ${generated_comment}
+
+#include 
+#include 
+#include 
+
+#ifndef AT_PER_OPERATOR_HEADERS
+#include 
+#else
+#include 
+$ops_headers
+#endif
+
+namespace at {
+namespace native {
+
+// This file contains a number of kernels for aten functions that are fully code-generated.
+// TODO: rename this file to something more generic.
+
+namespace {
+at::Tensor clone_arg(const at::Tensor& t) {
+    return t.clone();
+}
+
+std::vector clone_arg(const at::TensorList& t_list) {
+    std::vector out(t_list.size());
+    for (const auto& i : c10::irange(t_list.size())) {
+        out[i] = t_list[i].clone();
+    }
+    return out;
+}
+
+// duped with gen_resize_out_helper from structured kernels
+void copy_arg(const at::Tensor& dst, const at::Tensor& src) {
+    TORCH_CHECK(src.dtype() == dst.dtype(),
+        "Expected out tensor to have dtype ", src.dtype(), ", but got ", dst.dtype(), " instead");
+    TORCH_CHECK(src.device() == dst.device(),
+        "Expected out tensor to have device ", src.device(), ", but got ", dst.device(), " instead");
+    dst.copy_(src);
+}
+
+void copy_arg(const at::TensorList& dst, const at::TensorList& src) {
+    TORCH_INTERNAL_ASSERT(dst.size() == src.size());
+    for (const auto& i : c10::irange(dst.size())) {
+        copy_arg(dst[i], src[i]);
+    }
+}
+
+// TODO: this doesn't handle restriding empty tensors correctly; see
+// gen_resize_out_helper for the correct algorithm
+
+void resize_out_helper(const at::Tensor& dst, const at::Tensor& src) {
+    at::native::resize_output(dst, src.sizes());
+}
+
+void resize_out_helper(const at::TensorList& dst, const at::TensorList& src) {
+    TORCH_INTERNAL_ASSERT(dst.size() == src.size());
+    for (const auto& i : c10::irange(dst.size())) {
+        at::native::resize_output(dst[i], src[i].sizes());
+    }
+}
+}
+
+
+${CompositeViewCopyKernel_Definitions}
+
+${GeneratedCompositeFunctional_Definitions}
+
+${GeneratedCompositeOut_Definitions}
+
+} // namespace native
+} // namespace at
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunction.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunction.h
new file mode 100644
index 0000000000000000000000000000000000000000..c92d5eb3898ecea0fb9e1f79c2725d1bc6dfa7fb
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunction.h
@@ -0,0 +1,23 @@
+#pragma once
+// ${generated_comment}
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+
+namespace ${dispatch_namespace} {
+
+${dispatch_namespaced_declarations}
+
+} // namespace ${dispatch_namespace}
+} // namespace at
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunctions.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunctions.h
new file mode 100644
index 0000000000000000000000000000000000000000..35f43297fdd9ca9f932c8c53b5b773f1b9b8a427
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunctions.h
@@ -0,0 +1,29 @@
+#include 
+
+// TODO Undo all logic introduced for Note [Avoiding Include Cycles In Static Dispatch]
+// Code introduced to avoid cyclic dependency in static dispatch is no longer
+// needed as static dispatch logic is moved from TensorBody.h, which caused cycles in the first place,
+// to Operators.cpp for supporting multiple backends with multiple kernels.
+//
+// Note [Avoiding Include Cycles In Static Dispatch]
+// In order to avoid #include cycles in the static dispatch build, we've carefully split out
+// the static function definition files into {DispatchKey}Functions.h and {DispatchKey}Functions_inl.h.
+//
+// Without this split, the include cycle looks like TensorBody.h -> CPUFunctions.h -> TensorBody.h.
+// - TensorBody.h #includes CPUFunctions.h in the static dispatch build, because the tensor methods
+//   all need to call into the fastpath C++ API defined in CPUFunctions.h. The methods are also all
+//   directly inlined into TensorBody.h.
+// - CPUFunctions.h #includes TensorBody.h because it contains function declarations for the entire C++ API,
+//   which include functions that have defaultable std::optional arguments.
+//   That requires knowing the full Tensor class definition.
+//
+// We break the cycle by doing the following:
+// - Split out CPUFunction.h into two files: CPUFunctions.h and CPUFunctions_inl.h
+// - CPUFunction.h is a dummy file that just includes the Tensor class and includes CPUFunctions_inl.,
+// - CPUFunctions_inl.h includes everything else
+// - (only in the static dispatch build) TensorBody.h makes sure to finish defining the Tensor class,
+//   and then it includes CPUFunctions_inl.h.
+// - All other files that want the cpu fastpath functions can include CPUFunctions.h directly.
+// - This also means that static dispatch build, CPUFunctions.h only needs to
+//   #include TensorBody.h, and it will automatically bring in CPUFunctions_inl.h.
+${inline_headers}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunctions_inl.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunctions_inl.h
new file mode 100644
index 0000000000000000000000000000000000000000..fbb71c2cb123cb21fb57ec32341d86bff06f6a17
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunctions_inl.h
@@ -0,0 +1,22 @@
+#pragma once
+// ${generated_comment}
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+#if defined(AT_PER_OPERATOR_HEADERS) && defined(TORCH_ASSERT_ONLY_METHOD_OPERATORS)
+#error This change adds a dependency on all pytorch operators, meaning the     \
+  file will need to be re-compiled every time an operator is changed or added. \
+  Consider including a specific operator from                                  \
+  .                   \
+  See NOTE [TORCH_ASSERT_ONLY_METHOD_OPERATORS].
+#endif
+
+${DispatchKeyFunctions_inl_includes}
+
+
+${dispatch_namespaced_declarations}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..7647f459a744b2eacfac6aaea4f49b86babbb234
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.cpp
@@ -0,0 +1,13 @@
+// ${generated_comment}
+${includes}
+${native_functions_include}
+
+namespace {
+${helper_fns}
+} // namespace
+
+${namespace_prologue}
+
+${native_function_definitions}
+
+${namespace_epilogue}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.h
new file mode 100644
index 0000000000000000000000000000000000000000..b45a17b5922f8a0b76e0237616914ce9969efca5
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.h
@@ -0,0 +1,19 @@
+#pragma once
+
+// an external backend might generate file within its code tree
+// and check all the source files within the tree with clang-format.
+// so, disable it since the backend might have a different config.
+// clang-format off
+
+// ${generated_comment}
+
+#include 
+
+${namespace_prologue}
+
+struct ${class_name} {
+
+${dispatch_declarations}
+
+};
+${namespace_epilogue}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Function.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Function.h
new file mode 100644
index 0000000000000000000000000000000000000000..73096afbf11571cbe4147bb63f035a054ca842db
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Function.h
@@ -0,0 +1,27 @@
+#pragma once
+
+// ${generated_comment}
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+${static_dispatch_ops_headers}
+
+${operator_includes}
+
+namespace at {
+
+${function_definitions}
+
+}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/FunctionalInverses.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/FunctionalInverses.h
new file mode 100644
index 0000000000000000000000000000000000000000..b15cd09a6c65da3127be8245b87bff2f8c795a3d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/FunctionalInverses.h
@@ -0,0 +1,23 @@
+#pragma once
+
+// ${generated_comment}
+
+#include 
+#include 
+
+namespace at {
+namespace functionalization {
+
+struct FunctionalInverses {
+
+${view_inverse_declarations}
+
+// NB: These are not generated! They're manually implemented in the template.
+// TODO: Change codegen to generate these. See the following link:
+// https://github.com/pytorch/pytorch/blob/main/torchgen/model.py#L2583-L2585
+static at::Tensor chunk_inverse(const at::Tensor & base, const at::Tensor & mutated_view, InverseReturnMode inverse_return_mode, int64_t mutated_view_idx, int chunks, int dim);
+static at::Tensor narrow_inverse(const at::Tensor & base, const at::Tensor & mutated_view, InverseReturnMode inverse_return_mode, int dim, c10::SymInt start, c10::SymInt length);
+
+};
+}
+}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Functions.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Functions.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..f210402e543aa2de27ea0f510bb869e0c7010e22
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Functions.cpp
@@ -0,0 +1,105 @@
+#include 
+
+#include 
+#include 
+#include 
+
+namespace at {
+
+Tensor TensorMaker::make_tensor() {
+   AutoDispatchBelowADInplaceOrView guard{}; // TODO: Remove.
+   tracer::impl::NoTracerDispatchMode tracer_guard{};
+
+   check_size_nonnegative(sizes_);
+
+   TORCH_CHECK_VALUE(
+       !deleter_ || !ctx_,
+       "The deleter and context arguments are mutually exclusive.");
+
+   if (device_ == std::nullopt) {
+     device_ = globalContext().getDeviceFromPtr(data_, opts_.device().type());
+   }
+
+   if (opts_.device().has_index()) {
+     // clang-format off
+     TORCH_CHECK_VALUE(
+         opts_.device() == *device_,
+         "Specified device ", opts_.device(), " does not match device of data ", *device_);
+     // clang-format on
+   }
+
+   std::size_t size_bytes = computeStorageSize();
+
+   DataPtr data_ptr{};
+   if (deleter_) {
+     data_ptr = makeDataPtrFromDeleter();
+   } else {
+     data_ptr = makeDataPtrFromContext();
+   }
+
+   TORCH_CHECK(!resizeable_ || allocator_ != nullptr, "Must specify an allocator with allocator() if you want to use resizeable_storage()");
+   Storage storage{Storage::use_byte_size_t{}, size_bytes, std::move(data_ptr), /*allocator=*/allocator_, /*resizable=*/resizeable_};
+
+   Tensor tensor = detail::make_tensor(
+       std::move(storage), opts_.computeDispatchKey(), opts_.dtype());
+
+  TensorImpl* tensor_impl = tensor.unsafeGetTensorImpl();
+  if (strides_) {
+    tensor_impl->set_sizes_and_strides(sizes_, *strides_);
+  } else {
+    tensor_impl->set_sizes_contiguous(sizes_);
+  }
+  if (storage_offset_) {
+    tensor_impl->set_storage_offset(*storage_offset_);
+  }
+
+  tensor_impl->set_requires_grad(opts_.requires_grad());
+
+  return tensor;
+ }
+
+ std::size_t TensorMaker::computeStorageSize() const noexcept {
+   std::size_t itemsize = opts_.dtype().itemsize();
+
+   if (strides_) {
+     auto storage_size = detail::computeStorageNbytes(sizes_, *strides_, itemsize);
+     if (storage_offset_) {
+       storage_size += storage_offset_.value() * itemsize;
+     }
+     return storage_size;
+   }
+
+   std::size_t size = 1;
+   for (std::int64_t s : sizes_) {
+     size *= static_cast(s);
+   }
+   auto storage_size = size * itemsize;
+   if (storage_offset_) {
+     storage_size += storage_offset_.value() * itemsize;
+   }
+   return storage_size;
+ }
+
+ inline DataPtr TensorMaker::makeDataPtrFromDeleter() noexcept {
+   return InefficientStdFunctionContext::makeDataPtr(data_, std::move(deleter_), *device_);
+ }
+
+ inline DataPtr TensorMaker::makeDataPtrFromContext() noexcept {
+   return DataPtr{data_, ctx_.release(), ctx_.get_deleter(), *device_};
+ }
+
+ IntArrayRef TensorMaker::makeTempSizes() const noexcept {
+   static std::int64_t zeros[5] = {0, 0, 0, 0, 0};
+   if (opts_.has_memory_format()) {
+     MemoryFormat format = *opts_.memory_format_opt();
+     if (format == MemoryFormat::ChannelsLast) {
+       return IntArrayRef(zeros, 4);
+     }
+     if (format == MemoryFormat::ChannelsLast3d) {
+       return IntArrayRef(zeros, 5);
+     }
+   }
+   return IntArrayRef(zeros, 1);
+ }
+
+} // namespace at
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Functions.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Functions.h
new file mode 100644
index 0000000000000000000000000000000000000000..b1feaf9d4daa9786359c97434e4c59d3c75778c7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Functions.h
@@ -0,0 +1,143 @@
+#pragma once
+
+// ${generated_comment}
+
+#ifdef TORCH_ASSERT_NO_OPERATORS
+#error This change adds a dependency on native_functions.yaml,            \
+  meaning the file will need to be re-compiled every time an operator     \
+  is changed or added. Consider if your change would be better placed in  \
+  another file, or if a more specific header might achieve the same goal. \
+  See NOTE: [Tensor vs. TensorBase]
+#endif
+
+#if defined(AT_PER_OPERATOR_HEADERS) && defined(TORCH_ASSERT_ONLY_METHOD_OPERATORS)
+#error This change adds a dependency on all pytorch operators, meaning the     \
+  file will need to be re-compiled every time an operator is changed or added. \
+  Consider including a specific operator from  and   \
+  see NOTE [TORCH_ASSERT_ONLY_METHOD_OPERATORS].
+#endif
+
+// NOTE: [TORCH_ASSERT_ONLY_METHOD_OPERATORS]
+//
+// In ATen, certain generated headers files include the definitions of
+// every single operator in PyTorch. Unfortunately this means every
+// time an operator signature is updated or changed in
+// native_functions.yaml, you (and every other PyTorch developer) need
+// to recompile every source file that includes any of these headers.
+//
+// To break up these header dependencies, and improve incremental
+// build times for all PyTorch developers. These headers are split
+// into per-operator headers in the `ATen/ops` folder. This limits
+// incremental builds to only changes to methods of `Tensor`, or files
+// that use the specific operator being changed. With `at::sum` as an
+// example, you should include
+//
+//                  // instead of ATen/Functions.h
+//           // instead of ATen/NativeFunctions.h
+//              // instead of ATen/Operators.h
+//     // instead of ATen/CPUFunctions.h
+//
+// However, even if you're careful to use this in your own code.
+// `Functions.h` might be included indirectly through another header
+// without you realising. To avoid this, you can add
+//
+//   #define TORCH_ASSERT_ONLY_METHOD_OPERATORS
+//
+// to the top of your source file. This way any time the non-specific
+// headers are included, the compiler will error out.
+//
+// Also, be aware that `ops` are not available in all build
+// configurations (namely fb-internal) so you must guard these
+// includes with `#ifdef AT_PER_OPERATOR_HEADERS`. e.g.
+//
+//   #ifndef AT_PER_OPERATOR_HEADERS
+//   #include 
+//   #else
+//   #include 
+//   #endif
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+
+${Functions_includes}
+
+namespace at {
+
+${Functions_declarations}
+
+// Special C++ only overloads for std()-like functions (See gh-40287)
+// These are needed because int -> bool conversion takes precedence over int -> IntArrayRef
+// So, for example std(0) would select the std(unbiased=False) overload
+inline Tensor var(const Tensor& self, int dim) {
+  return at::var(self, IntArrayRef{dim});
+}
+inline std::tuple var_mean(const Tensor& self, int dim) {
+  return at::var_mean(self, IntArrayRef{dim});
+}
+inline Tensor std(const Tensor& self, int dim) {
+  return at::std(self, IntArrayRef{dim});
+}
+inline std::tuple std_mean(const Tensor& self, int dim) {
+  return at::std_mean(self, IntArrayRef{dim});
+}
+
+inline int64_t numel(const Tensor& tensor) {
+  return tensor.numel();
+}
+
+inline int64_t size(const Tensor& tensor, int64_t dim) {
+  return tensor.size(dim);
+}
+
+inline int64_t stride(const Tensor& tensor, int64_t dim) {
+  return tensor.stride(dim);
+}
+
+inline bool is_complex(const Tensor& tensor) {
+  return tensor.is_complex();
+}
+
+inline bool is_floating_point(const Tensor& tensor) {
+  return tensor.is_floating_point();
+}
+
+inline bool is_signed(const Tensor& tensor) {
+  return tensor.is_signed();
+}
+
+inline bool is_inference(const Tensor& tensor) {
+  return tensor.is_inference();
+}
+
+inline bool _is_zerotensor(const Tensor& tensor) {
+  return tensor._is_zerotensor();
+}
+
+inline bool is_conj(const Tensor& tensor) {
+  return tensor.is_conj();
+}
+
+inline Tensor conj(const Tensor& tensor) {
+  return tensor.conj();
+}
+
+inline bool is_neg(const Tensor& tensor) {
+  return tensor.is_neg();
+}
+
+}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/LazyIr.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/LazyIr.h
new file mode 100644
index 0000000000000000000000000000000000000000..9190ff8243d316fd2bd472bb3f0603701761bdb7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/LazyIr.h
@@ -0,0 +1,19 @@
+#pragma once
+
+// This file contains autogenerated LazyTensor IR nodes
+${lazy_ir_sysinc}
+${lazy_ir_inc}
+
+${namespace_prologue}
+using at::operator<<;
+
+// kNullValue is used to contribute a static hash value any time
+// a node has an Optional input that is nullopt.  It is important
+// to differentiate between HASH(std::nullopt, something) and HASH(something, std::nullopt),
+// and using kNullValue in the hash function in the order of arguments
+// serves this purpose.
+static const torch::lazy::Value kNullValue = torch::lazy::Value();
+
+${ir_declarations}
+
+${namespace_epilogue}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/LazyNonNativeIr.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/LazyNonNativeIr.h
new file mode 100644
index 0000000000000000000000000000000000000000..18eaf6da52e4b3654becac6cc89849bc0806ae09
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/LazyNonNativeIr.h
@@ -0,0 +1,11 @@
+#pragma once
+
+${lazy_non_native_ir_inc}
+
+// This file contains autogenerated LazyTensor Non Native IR nodes
+
+${namespace_prologue}
+
+${non_native_ir_nodes}
+
+${namespace_epilogue}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/MethodOperators.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/MethodOperators.h
new file mode 100644
index 0000000000000000000000000000000000000000..0e192cd05ef3c78fa74848c93de32150c1e3fd8b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/MethodOperators.h
@@ -0,0 +1,24 @@
+#pragma once
+
+// ${generated_comment}
+
+#ifdef TORCH_ASSERT_NO_OPERATORS
+#error This change adds a dependency on native_functions.yaml,             \
+  meaning the file will need to be re-compiled every time an operator      \
+  is changed or added. Consider if your change would be better placed in   \
+  another file, or if a more specific header might achieve the same goal.  \
+  See NOTE: [Tensor vs. TensorBase]
+#endif
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+${MethodOperators_includes}
+
+namespace at {
+namespace _ops {
+${MethodOperators_declarations}
+} // namespace _ops
+} // namespace at
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/NativeFunction.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/NativeFunction.h
new file mode 100644
index 0000000000000000000000000000000000000000..a5441ad85d1d5e28c4e31dd3f0dc7f66dfbff9e7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/NativeFunction.h
@@ -0,0 +1,17 @@
+#pragma once
+
+// ${generated_comment}
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+${extra_includes}
+
+${native_function_declarations}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/NativeFunctions.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/NativeFunctions.h
new file mode 100644
index 0000000000000000000000000000000000000000..9dc972495ca038bddb7b887c39c2e0507e487213
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/NativeFunctions.h
@@ -0,0 +1,33 @@
+#pragma once
+
+// ${generated_comment}
+
+#ifdef TORCH_ASSERT_NO_OPERATORS
+#error This change adds a dependency on native_functions.yaml,            \
+  meaning the file will need to be re-compiled every time an operator     \
+  is changed or added. Consider if your change would be better placed in  \
+  another file, or if a more specific header might achieve the same goal. \
+  See NOTE: [Tensor vs. TensorBase]
+#endif
+
+#if defined(AT_PER_OPERATOR_HEADERS) && defined(TORCH_ASSERT_ONLY_METHOD_OPERATORS)
+#error This change adds a dependency on all pytorch operators, meaning the      \
+  file will need to be re-compiled every time an operator is changed or added.  \
+  Consider including a specific operator from  \
+  and see NOTE [TORCH_ASSERT_ONLY_METHOD_OPERATORS].
+#endif
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+${NativeFunctions_includes}
+
+${NativeFunctions_declarations}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/NativeMetaFunction.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/NativeMetaFunction.h
new file mode 100644
index 0000000000000000000000000000000000000000..6522c97546d0498e4b3825fb4eafefbb34c71911
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/NativeMetaFunction.h
@@ -0,0 +1,23 @@
+#pragma once
+
+// ${generated_comment}
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+namespace meta {
+
+${meta_function_declarations}
+
+} // namespace native
+} // namespace at
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/NativeMetaFunctions.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/NativeMetaFunctions.h
new file mode 100644
index 0000000000000000000000000000000000000000..89989e2121c9aa34a4583205c3541a04edd36700
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/NativeMetaFunctions.h
@@ -0,0 +1,19 @@
+#pragma once
+
+// ${generated_comment}
+
+#include 
+#include 
+#include 
+#include 
+
+${NativeMetaFunctions_includes}
+
+namespace at {
+
+namespace meta {
+
+${NativeMetaFunctions_declarations}
+
+} // namespace meta
+} // namespace at
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Operator.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Operator.h
new file mode 100644
index 0000000000000000000000000000000000000000..ed220f917290c2062481eb53dca232b47d180e2d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Operator.h
@@ -0,0 +1,19 @@
+#pragma once
+
+// ${generated_comment}
+
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+${declarations}
+
+}} // namespace at::_ops
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Operators.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Operators.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..082bb67c3e2043f2c36b29345f57048ec2e9eea7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Operators.cpp
@@ -0,0 +1,19 @@
+#include 
+#include 
+
+// ${generated_comment}
+// NOTE See [Sharded File] comment in VariableType
+
+#ifndef AT_PER_OPERATOR_HEADERS
+#include 
+#else
+${operator_headers}
+#endif
+
+${static_dispatch_extra_headers}
+
+namespace at { namespace _ops {
+
+${definitions}
+
+}} // namespace at::_ops
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Operators.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Operators.h
new file mode 100644
index 0000000000000000000000000000000000000000..e74b96ef3d5c6b6d50fe63eac4dca51f0655daa5
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Operators.h
@@ -0,0 +1,74 @@
+#pragma once
+
+// ${generated_comment}
+
+#ifdef TORCH_ASSERT_NO_OPERATORS
+#error This change adds a dependency on native_functions.yaml,             \
+  meaning the file will need to be re-compiled every time an operator      \
+  is changed or added. Consider if your change would be better placed in   \
+  another file, or if a more specific header might achieve the same goal.  \
+  See NOTE: [Tensor vs. TensorBase]
+#endif
+
+#if defined(AT_PER_OPERATOR_HEADERS) && defined(TORCH_ASSERT_ONLY_METHOD_OPERATORS)
+#error This change adds a dependency on all pytorch operators, meaning the     \
+  file will need to be re-compiled every time an operator is changed or added. \
+  Consider including a specific operator from    \
+  and see NOTE [TORCH_ASSERT_ONLY_METHOD_OPERATORS].
+#endif
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+${Operators_includes}
+
+// Extension writers: do you write wrapper functions? Are you frustrated with
+// resolving overloads of operators? Are you frustrated with dealing with
+// pointer-to-methods and resolving overloads of pointer-to-methods?? Look no
+// further, this is the utility for you.
+//
+// Given an operator schema: aten::op.overload(...
+//
+// Use ATEN_FN2(op, overload) to get a *function* version of the operator
+// that is guaranteed to not be overloaded. This means that you can safely
+// decltype(&ATEN_FN2(op, overload)) it. NB: the 2 means this macro takes 2 args.
+//
+// Given an operator schema without an overload name: aten::op(...
+//
+// Use ATEN_FN(op) to get an unambiguous *function* version of the operator.
+//
+// There is some interesting behavior for out= operations.
+// ATEN_FN2(sin, out) gives a function that is *faithful* to the schema;
+// that is, the order of arguments is exactly what it looks like in the schema.
+
+#define ATEN_FN2(op_name, overload) at::_ops::op_name##_##overload::call
+#define ATEN_FN(op_name) at::_ops::op_name::call
+
+// Separately, ATEN_OP(op) and ATEN_OP2(op, overload) define a class containing compile-time
+// metadata about a given aten operator.
+// Notable data on the class includes:
+// - ATEN_OP2(add, Tensor)::name // returns the string name: "add"
+// - ATEN_OP2(add, Tensor)::overload_name // returns the string overload name: "Tensor"
+// - ATEN_OP2(add, Tensor)::schema // returns the C++ schema type: at::Tensor (const at::Tensor &, const at::Tensor &, const at::Scalar &)
+// - ATEN_OP2(add, Tensor)::schema_str // returns the string jit type: "add.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor"
+
+#define ATEN_OP2(op_name, overload) at::_ops::op_name##_##overload
+#define ATEN_OP(op_name) at::_ops::op_name
+
+// WARNING: Please do not call any of the ops in the _ops namespace directly.
+// Use the ATEN_FN macros. We do not guarantee stability of the naming
+// scheme for the functions in at::_ops
+
+// See Note [The ATen Operators API] for details of the at::_ops namespace
+
+namespace at {
+namespace _ops {
+${Operators_declarations}
+} // namespace _ops
+} // namespace at
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RedispatchFunctions.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RedispatchFunctions.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..58102bd97fca4eaef477818b0b0a92b7995e38b1
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RedispatchFunctions.cpp
@@ -0,0 +1,15 @@
+// ${generated_comment}
+
+#include 
+#include 
+
+#include 
+#include 
+
+namespace at {
+
+namespace redispatch {
+    ${function_redispatch_definitions}
+} // namespace redispatch
+
+} // namespace at
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RedispatchFunctions.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RedispatchFunctions.h
new file mode 100644
index 0000000000000000000000000000000000000000..2422cdd409cfdd59c2a05df27d28bb25ee610463
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RedispatchFunctions.h
@@ -0,0 +1,32 @@
+#pragma once
+
+// ${generated_comment}
+
+#ifdef TORCH_ASSERT_ONLY_METHOD_OPERATORS
+#error This change adds a dependency on all pytorch operators, meaning the     \
+  file will need to be re-compiled every time an operator is changed or added. \
+  Consider using the at::_ops::{name}::redispatch() interface by including     \
+  the specific operator from 
+#endif
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+
+namespace redispatch {
+    ${function_redispatch_definitions}
+} // namespace redispatch
+
+}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterBackendSelect.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterBackendSelect.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..018cf358f11237d5bdc9bca01aa8d09d1462f574
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterBackendSelect.cpp
@@ -0,0 +1,29 @@
+// We register ops with a higher priority dispatch key (BackendSelect) than the usual backend-specific keys (e.g. CPU)
+// which makes calls to the factory functions dispatch to here.
+// We then 'manually' compute a lower-priority to re-dispatch to (e.g. CPU) to get to the eventually correct backend.
+// ${generated_comment}
+
+#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
+#include 
+#include 
+#include 
+
+#ifndef AT_PER_OPERATOR_HEADERS
+#include 
+#else
+
+${ops_headers}
+#endif
+
+namespace at {
+
+namespace {
+
+${backend_select_method_definitions}
+
+TORCH_LIBRARY_IMPL(aten, BackendSelect, m) {
+  ${backend_select_function_registrations};
+}
+
+} // namespace
+} // at
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterCodegenUnboxedKernels.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterCodegenUnboxedKernels.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..279f987c66a26c2eb5d11c664c85b3604b67684b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterCodegenUnboxedKernels.cpp
@@ -0,0 +1,41 @@
+#include 
+#include 
+#include 
+
+#include 
+
+// ${generated_comment}
+
+// NOTE [Sharded File]: This file is generated in a sharded fashion to speed up
+// incremental rebuilds. See the comment at the top of
+// templates/VariableType.cpp for an analogous, in-depth discussion.
+//
+// Generated by tools/jit/gen_unboxing.py. This file registers all ATen ops into JIT op registry instead of c10
+// dispatcher. JIT op registry only takes boxed kernels, so we are calling unboxing functions in UnboxingFunctions.h
+// to cast arguments into C++ types (instead of IValue) and delegate to unboxed kernels.
+
+namespace torch { namespace jit {
+
+using autograd::Variable;
+using autograd::variable_list;
+using at::Scalar;
+using at::ScalarType;
+using at::Tensor;
+using at::TensorOptions;
+using at::DeviceGuard;
+
+using ::c10::fmap;
+using ::c10::filter;
+
+namespace {
+
+RegisterOperators reg({
+
+    // Generated operators
+    ${unboxed_ops}
+});
+
+} // anon namespace
+
+
+}} // namespace torch::jit
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterDispatchDefinitions.ini b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterDispatchDefinitions.ini
new file mode 100644
index 0000000000000000000000000000000000000000..97c921de18f62832d1ca09c245f2466541fe908d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterDispatchDefinitions.ini
@@ -0,0 +1,22 @@
+${ns_prologue}
+
+// NB: TORCH_LIBRARY_IMPL must be in an anonymous namespace to avoid
+// ambiguity with conflicting identifiers that may have been defined in
+// at namespace already.
+namespace {
+
+${dispatch_anonymous_definitions}
+
+${static_init_dispatch_registrations}
+
+} // anonymous namespace
+
+${deferred_dispatch_registrations}
+
+namespace ${dispatch_namespace} {
+
+${dispatch_namespaced_definitions}
+
+} // namespace ${dispatch_namespace}
+
+${ns_epilogue}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterDispatchKey.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterDispatchKey.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..39c85b00d7a1be5471b496b7871aae825b39df9e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterDispatchKey.cpp
@@ -0,0 +1,52 @@
+// an external backend might generate file within its code tree
+// and check all the source files within the tree with clang-format.
+// so, disable it since the backend might have a different config.
+// clang-format off
+
+// NOTE: This condition is true for all PyTorch internal libraries, it
+//       just excludes external projects such as torch_xla which
+//       reuse some of the PyTorch codegen machinery.
+#if defined(CAFFE2_BUILD_MAIN_LIB)        || \
+    defined(TORCH_CUDA_BUILD_MAIN_LIB)    || \
+    defined(TORCH_HIP_BUILD_MAIN_LIB)     || \
+    defined(TORCH_XPU_BUILD_MAIN_LIB)
+#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
+#endif
+
+// ${generated_comment}
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+$extra_cuda_headers
+$external_backend_headers
+$dispatch_headers
+$ops_headers
+
+namespace at {
+namespace {
+$dispatch_helpers
+} // namespace
+} // namespace at
+
+// See template file RegisterDispatchDefinitions.ini
+$dispatch_definitions
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterFunctionalization.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterFunctionalization.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..408aff0cdab40461a7ba731bab216a7b7435331e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterFunctionalization.cpp
@@ -0,0 +1,116 @@
+#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
+// ${generated_comment}
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#ifndef AT_PER_OPERATOR_HEADERS
+#include 
+#include 
+#else
+// needed for the meta tensor calls to get stride info in functionalization
+#include 
+// needed for special handling of copy_().
+// See Note [functionalizating copy_() and not preserving strides]
+#include 
+#include 
+
+$ops_headers
+#endif
+
+namespace at {
+namespace functionalization {
+
+// This keyset is used by functionalization when it calls into meta kernels
+// to accurately propagate stride metadata.
+// Exclude any modes: the purpose of calling into meta kernels is only as an implementation
+// detail to perform shape inference, and we don't want any modal keys to run.
+// Specifically, we want to prevent functionalization and Python modes from running.
+constexpr auto exclude_keys_for_meta_dispatch =
+    c10::functorch_transforms_ks |
+    c10::DispatchKeySet({
+        c10::DispatchKey::FuncTorchDynamicLayerBackMode,
+        c10::DispatchKey::FuncTorchDynamicLayerFrontMode,
+        c10::DispatchKey::Python,
+        c10::DispatchKey::PreDispatch,
+
+    });
+
+// Helper around at::has_internal_overlap.
+// The ATen util is used in hot-path eager mode: it's always fast,
+// but might return TOO_HARD sometimes.
+// During functionalization, we're ok taking a bit longer
+// to detect memory overlap.
+inline bool has_internal_overlap_helper(const at::Tensor t) {
+  auto has_overlap = at::has_internal_overlap(t);
+  if (has_overlap == at::MemOverlap::Yes) return true;
+  if (has_overlap == at::MemOverlap::No) return false;
+  return false;
+}
+
+
+inline Tensor to_meta(const Tensor& t) {
+    if (!t.defined()) return t;
+    return at::native::empty_strided_meta_symint(t.sym_sizes(), t.sym_strides(),
+/*dtype=*/t.scalar_type(), /*layout=*/t.layout(),
+/*device=*/c10::Device(kMeta), /*pin_memory=*/std::nullopt);
+}
+
+inline std::optional to_meta(const std::optional& t) {
+  if (t.has_value()) {
+    return to_meta(*t);
+  }
+  return std::nullopt;
+}
+
+inline std::vector to_meta(at::ITensorListRef t_list) {
+  std::vector outputs;
+  outputs.reserve(t_list.size());
+  for (const auto& tensor : t_list) {
+    outputs.push_back(to_meta(tensor));
+  }
+  return outputs;
+}
+
+inline c10::List to_meta(const c10::List& t_list) {
+  c10::List outputs;
+  outputs.reserve(t_list.size());
+  for (const auto i : c10::irange(t_list.size())) {
+    outputs.push_back(to_meta(t_list[i]));
+  }
+  return outputs;
+}
+
+inline c10::List<::std::optional> to_meta(const c10::List<::std::optional>& t_list) {
+  c10::List<::std::optional> outputs;
+  outputs.reserve(t_list.size());
+  for (const auto i : c10::irange(t_list.size())) {
+    outputs.push_back(to_meta(t_list[i]));
+  }
+  return outputs;
+}
+
+static bool disable_meta_reference() {
+  static auto env = c10::utils::get_env("TORCH_DISABLE_FUNCTIONALIZATION_META_REFERENCE");
+  return env == "1";
+}
+
+
+${func_definitions}
+
+}  // namespace functionalization
+
+namespace {
+
+TORCH_LIBRARY_IMPL(aten, Functionalize, m) {
+  ${func_registrations};
+}
+
+}  // namespace
+
+} // namespace at
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterSchema.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterSchema.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..029796d3e575b2bde85cfd44af9e6fcbb56466cd
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterSchema.cpp
@@ -0,0 +1,13 @@
+// ${generated_comment}
+#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
+#include 
+
+namespace at {
+TORCH_LIBRARY(aten, m) {
+  ${aten_schema_registrations};
+  // Distributed Ops
+  // Implementations located in torch/csrc/jit/runtime/register_distributed_ops.cpp
+  m.def("get_gradients(int context_id) -> Dict(Tensor, Tensor)");
+}
+${schema_registrations}
+}  // namespace at
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegistrationDeclarations.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegistrationDeclarations.h
new file mode 100644
index 0000000000000000000000000000000000000000..5a0f0d0c7b44dabb60061d32ced243fe607069d8
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegistrationDeclarations.h
@@ -0,0 +1,4 @@
+// This file contains all native_functions that can be registered to
+// and the schema string that they should be registered with
+
+${registration_declarations}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/TensorBody.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/TensorBody.h
new file mode 100644
index 0000000000000000000000000000000000000000..8ae2dee1ce50cdf3f2c518042ab02d03288dac98
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/TensorBody.h
@@ -0,0 +1,753 @@
+#pragma once
+
+#ifdef TORCH_ASSERT_NO_OPERATORS
+#error This change adds a dependency on native_functions.yaml,            \
+  meaning the file will need to be re-compiled every time an operator     \
+  is changed or added. Consider if your change would be better placed in  \
+  another file, or if a more specific header might achieve the same goal. \
+  See NOTE: [Tensor vs. TensorBase]
+#endif
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+#include 
+
+namespace c10{
+template class List;
+template class IListRef;
+}
+namespace at {
+struct Generator;
+struct Type;
+class DeprecatedTypeProperties;
+class Tensor;
+} // namespace at
+namespace at {
+namespace indexing {
+struct TensorIndex;
+} // namespace indexing
+} // namespace at
+
+namespace torch { namespace autograd {
+
+struct Node;
+
+}} // namespace torch::autograd
+
+namespace at {
+
+class OptionalTensorRef;
+class TensorRef;
+class Tensor;
+using TensorList = ArrayRef;
+using ITensorList = c10::IListRef;
+
+using Stream = c10::Stream;
+
+// Tensor is a "generic" object holding a pointer to the underlying TensorImpl object, which
+// has an embedded reference count. In this way, Tensor is similar to boost::intrusive_ptr.
+//
+// For example:
+//
+// void func(Tensor a) {
+//   Tensor b = a;
+//   ...
+// }
+//
+// In this example, when we say Tensor b = a, we are creating a new object that points to the
+// same underlying TensorImpl, and bumps its reference count. When b goes out of scope, the
+// destructor decrements the reference count by calling release() on the TensorImpl it points to.
+// The existing constructors, operator overloads, etc. take care to implement the correct semantics.
+//
+// Note that Tensor can also be NULL, i.e. it is not associated with any underlying TensorImpl, and
+// special care must be taken to handle this.
+class TORCH_API Tensor: public TensorBase {
+ protected:
+  // Create a Tensor with a +0 reference count. Special care must be
+  // taken to avoid decrementing this reference count at destruction
+  // time. Intended to support MaybeOwnedTraits.
+  explicit Tensor(unsafe_borrow_t, const TensorBase& rhs): TensorBase(unsafe_borrow_t{}, rhs) {}
+  friend MaybeOwnedTraits;
+  friend OptionalTensorRef;
+  friend TensorRef;
+
+ public:
+  Tensor() = default;
+  // This constructor should not be used by end users and is an implementation
+  // detail invoked by autogenerated code.
+  explicit Tensor(
+      c10::intrusive_ptr tensor_impl)
+      : TensorBase(std::move(tensor_impl)) {}
+  Tensor(const Tensor &tensor) = default;
+  Tensor(Tensor &&tensor) = default;
+
+  // Implicitly move-constructible from TensorBase, but must be explicit to increase refcount
+  explicit Tensor(const TensorBase &base): TensorBase(base) {}
+  /*implicit*/ Tensor(TensorBase &&base): TensorBase(std::move(base)) {}
+
+  // Creates a new wrapper from TensorImpl. Intentionally a free method because
+  // it should be used with care. Checks necessary invariants
+  static Tensor wrap_tensor_impl(
+      c10::intrusive_ptr tensor_impl) {
+    return TensorBase::wrap_tensor_impl(std::move(tensor_impl));
+  }
+
+  Tensor contiguous(MemoryFormat memory_format=MemoryFormat::Contiguous) const {
+    return TensorBase::contiguous(memory_format);
+  }
+
+  Tensor conj() const {
+    if (!this->is_complex()) {
+      return *this;
+    }
+
+    switch (this->layout()) {
+      case at::kSparse:
+      case at::kSparseCsr:
+      case at::kSparseCsc:
+      case at::kSparseBsr:
+      case at::kSparseBsc:
+        return this->conj_physical();
+      default:
+        return this->_conj();
+    }
+  }
+
+  // Aliased by Dimname overloads, so need explicit using
+  using TensorBase::size;
+  using TensorBase::sym_size;
+  using TensorBase::stride;
+
+  /// Should be used if *this can reasonably be expected to be contiguous and
+  /// performance is important.
+  /// Compared to contiguous, it saves a reference count
+  /// increment/decrement if *this is already contiguous, at the cost
+  /// in all cases of an extra pointer of stack usage, an extra branch
+  /// to access, and an extra branch at destruction time.
+  c10::MaybeOwned expect_contiguous(MemoryFormat memory_format=MemoryFormat::Contiguous) const &;
+
+  // Use .contiguous() instead. Trying to borrow from a prvalue Tensor
+  // will only lead to trouble and dangling references.
+  c10::MaybeOwned expect_contiguous(MemoryFormat memory_format=MemoryFormat::Contiguous) && = delete;
+
+  // The following overloads are very intruiging.  Consider the following
+  // program:
+  //
+  //    x[1] = 3;
+  //
+  // We would expect that the first entry of x is written to 3.  But how can we
+  // actually achieve this?  x[1] evaluates to a tensor...
+  //
+  // The answer is, using a ref-qualifier.  x[1] is an rvalue, which cannot be
+  // (profitably) assigned to in the traditional sense, so we overload
+  // assignment to mean, "Actually, copy 3 into the tensor data."  This is done
+  // with an rvalue-reference ref-qualified overload (the methods with && at the
+  // end of their type.)
+  //
+  // There's one more fly in the ointment: We also want
+  //
+  //    Tensor x = y;
+  //
+  // to work, and we want it NOT to copy.  So we need a traditional operator=
+  // overload.  But we MUST specify a mutable lvalue ref-qualifier, to
+  // disambiguate the traditional overload from the rvalue-reference
+  // ref-qualified overload.  Otherwise, it will be ambiguous, because
+  // a non ref-qualified method is eligible for all situations.
+
+  // Unfortunately, we have to write these constructors out manually
+  // to work around an MSVC bug:
+  //    error C2580: 'at::Tensor &at::Tensor::operator =(const at::Tensor &) &':
+  //    multiple versions of a defaulted special member functions are not allowed
+  // Tensor& operator=(const Tensor&) & = default;
+  // Tensor& operator=(Tensor&&) & = default;
+
+  // Also MSVC will wrongly issue the following warning with the aforementioned fix
+  //    warning C4522: 'at::Tensor': multiple assignment operators specified
+  // Let's just skip the warning.
+  //
+  // TODO: temporarily disabled
+
+  Tensor& operator=(const TensorBase& x) & noexcept {
+    impl_ = x.getIntrusivePtr();
+    return *this;
+  }
+  Tensor& operator=(TensorBase&& x) & noexcept {
+    impl_ = x.unsafeReleaseIntrusivePtr();
+    return *this;
+  }
+
+  Tensor& operator=(const Tensor &x) & noexcept {
+    return operator=(static_cast(x));
+  }
+  Tensor& operator=(Tensor &&x) & noexcept {
+    return operator=(static_cast(x));
+  }
+
+  Tensor& operator=(const Scalar &v) && {
+    return fill_(v);
+  }
+  Tensor& operator=(const Tensor &rhs) && {
+    return copy_(rhs);
+  }
+  Tensor& operator=(Tensor&& rhs) && {
+    return copy_(rhs);
+  }
+
+  C10_DEPRECATED_MESSAGE("Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device().")
+  DeprecatedTypeProperties & type() const {
+    return globalDeprecatedTypePropertiesRegistry().getDeprecatedTypeProperties(
+        dispatchKeyToBackend(legacyExtractDispatchKey(key_set())),
+        scalar_type());
+  }
+
+  Tensor toType(ScalarType t) const {
+    return to(options().dtype(t), /*non_blocking*/ false, /*copy*/ false);
+  }
+
+  // TODO: Deprecate me
+  Tensor toBackend(Backend b) const {
+    return to(options().device(backendToDeviceType(b)).layout(layout_from_backend(b)), /*non_blocking*/ false, /*copy*/ false);
+  }
+
+  C10_DEPRECATED_MESSAGE("Tensor.is_variable() is deprecated; everything is a variable now. (If you want to assert that variable has been appropriately handled already, use at::impl::variable_excluded_from_dispatch())")
+  bool is_variable() const noexcept {
+    return !at::impl::variable_excluded_from_dispatch();
+  }
+
+  template
+  C10_DEPRECATED_MESSAGE("Tensor.data() is deprecated. Please use Tensor.data_ptr() instead.")
+  T * data() const {
+    return data_ptr();
+  }
+
+  template 
+  T item() const;
+
+  template class PtrTraits = DefaultPtrTraits, typename index_t = int64_t>
+  C10_DEPRECATED_MESSAGE("packed_accessor is deprecated, use packed_accessor32 or packed_accessor64 instead")
+  GenericPackedTensorAccessor packed_accessor() const & {
+    return generic_packed_accessor();
+  }
+  template class PtrTraits = DefaultPtrTraits, typename index_t = int64_t>
+  C10_DEPRECATED_MESSAGE("packed_accessor is deprecated, use packed_accessor32 or packed_accessor64 instead")
+  GenericPackedTensorAccessor packed_accessor() && = delete;
+
+  Tensor operator~() const {
+    return bitwise_not();
+  }
+  Tensor operator-() const {
+    return neg();
+  }
+  Tensor& operator+=(const Tensor & other) {
+    return add_(other);
+  }
+  Tensor& operator+=(const Scalar & other) {
+    return add_(other);
+  }
+  Tensor& operator-=(const Tensor & other) {
+    return sub_(other);
+  }
+  Tensor& operator-=(const Scalar & other) {
+    return sub_(other);
+  }
+  Tensor& operator*=(const Tensor & other) {
+    return mul_(other);
+  }
+  Tensor& operator*=(const Scalar & other) {
+    return mul_(other);
+  }
+  Tensor& operator/=(const Tensor & other) {
+    return div_(other);
+  }
+  Tensor& operator/=(const Scalar & other) {
+    return div_(other);
+  }
+  Tensor& operator&=(const Tensor & other) {
+    return bitwise_and_(other);
+  }
+  Tensor& operator|=(const Tensor & other) {
+    return bitwise_or_(other);
+  }
+  Tensor& operator^=(const Tensor & other) {
+    return bitwise_xor_(other);
+  }
+  Tensor operator[](const Scalar & index) const {
+    if (!index.isIntegral(false)) {
+      TORCH_CHECK_INDEX(false, "Can only index tensors with integral scalars");
+    }
+    return this->operator[](index.toLong());
+  }
+  Tensor operator[](const Tensor & index) const {
+    // These properties are checked in the Scalar constructor, but we already
+    // check them here to provide more useful diagnostics for the user.
+    if (!index.defined()) {
+      TORCH_CHECK_INDEX(false, "Can only index with tensors that are defined");
+    }
+    if (index.dim() != 0) {
+      TORCH_CHECK_INDEX(false,
+                        "Can only index with tensors that are scalars (zero-dim)");
+    }
+    // The Scalar(Tensor) constructor is explicit, so we need to call it.
+    return this->operator[](index.item());
+  }
+  Tensor operator[](int64_t index) const {
+    return select(0, index);
+  }
+
+  Tensor index(ArrayRef indices) const;
+  Tensor index(std::initializer_list indices) const;
+
+  Tensor & index_put_(ArrayRef indices, Tensor const & rhs);
+  Tensor & index_put_(ArrayRef indices, const Scalar& v);
+  Tensor & index_put_(std::initializer_list indices, Tensor const & rhs);
+  Tensor & index_put_(std::initializer_list indices, const Scalar& v);
+
+  Tensor cpu() const {
+    return to(options().device(c10::DeviceType::CPU), /*non_blocking*/ false, /*copy*/ false);
+  }
+
+  // TODO: The Python version also accepts arguments
+  Tensor cuda() const {
+    return to(options().device(c10::DeviceType::CUDA), /*non_blocking*/ false, /*copy*/ false);
+  }
+
+  Tensor hip() const {
+    return to(options().device(c10::DeviceType::HIP), /*non_blocking*/ false, /*copy*/ false);
+  }
+
+  Tensor ve() const {
+    return to(options().device(c10::DeviceType::VE), /*non_blocking*/ false, /*copy*/ false);
+  }
+
+  Tensor vulkan() const {
+    return to(options().device(c10::DeviceType::Vulkan), /*non_blocking*/ false, /*copy*/ false);
+  }
+
+  Tensor metal() const {
+    return to(options().device(c10::DeviceType::Metal), /*non_blocking*/ false, /*copy*/ false);
+  }
+
+  Tensor meta() const {
+    return to(options().device(c10::DeviceType::Meta), /*non_blocking*/ false, /*copy*/ false);
+  }
+
+  // ~~~~~ Autograd API ~~~~~
+
+  /// \fn bool is_leaf() const;
+  ///
+  /// All Tensors that have `requires_grad()` which is ``false`` will be leaf Tensors by convention.
+  ///
+  /// For Tensors that have `requires_grad()` which is ``true``, they will be leaf Tensors if they were
+  /// created by the user. This means that they are not the result of an operation and so
+  /// `grad_fn()` is `nullptr`.
+  ///
+  /// Only leaf Tensors will have their `grad()` populated during a call to `backward()`.
+  /// To get `grad()` populated for non-leaf Tensors, you can use `retain_grad()`.
+  ///
+  /// Example:
+  /// @code
+  /// auto a = torch::rand(10, torch::requires_grad());
+  /// std::cout << a.is_leaf() << std::endl; // prints `true`
+  ///
+  /// auto b = torch::rand(10, torch::requires_grad()).to(torch::kCUDA);
+  /// std::cout << b.is_leaf() << std::endl; // prints `false`
+  /// // b was created by the operation that cast a cpu Tensor into a cuda Tensor
+  ///
+  /// auto c = torch::rand(10, torch::requires_grad()) + 2;
+  /// std::cout << c.is_leaf() << std::endl; // prints `false`
+  /// // c was created by the addition operation
+  ///
+  /// auto d = torch::rand(10).cuda();
+  /// std::cout << d.is_leaf() << std::endl; // prints `true`
+  /// // d does not require gradients and so has no operation creating it (that is tracked by the autograd engine)
+  ///
+  /// auto e = torch::rand(10).cuda().requires_grad_();
+  /// std::cout << e.is_leaf() << std::endl; // prints `true`
+  /// // e requires gradients and has no operations creating it
+  ///
+  /// auto f = torch::rand(10, torch::device(torch::kCUDA).requires_grad(true));
+  /// std::cout << f.is_leaf() << std::endl; // prints `true`
+  /// // f requires grad, has no operation creating it
+  /// @endcode
+
+  /// \fn void backward(const Tensor & gradient={}, std::optional retain_graph=std::nullopt, bool create_graph=false, std::optional inputs=std::nullopt) const;
+  ///
+  /// Computes the gradient of current tensor with respect to graph leaves.
+  ///
+  /// The graph is differentiated using the chain rule. If the tensor is
+  /// non-scalar (i.e. its data has more than one element) and requires
+  /// gradient, the function additionally requires specifying ``gradient``.
+  /// It should be a tensor of matching type and location, that contains
+  /// the gradient of the differentiated function w.r.t. this Tensor.
+  ///
+  /// This function accumulates gradients in the leaves - you might need to
+  /// zero them before calling it.
+  ///
+  /// \param gradient Gradient w.r.t. the
+  ///     tensor. If it is a tensor, it will be automatically converted
+  ///     to a Tensor that does not require grad unless ``create_graph`` is True.
+  ///     None values can be specified for scalar Tensors or ones that
+  ///     don't require grad. If a None value would be acceptable then
+  ///     this argument is optional.
+  /// \param retain_graph If ``false``, the graph used to compute
+  ///     the grads will be freed. Note that in nearly all cases setting
+  ///     this option to True is not needed and often can be worked around
+  ///     in a much more efficient way. Defaults to the value of
+  ///     ``create_graph``.
+  /// \param create_graph If ``true``, graph of the derivative will
+  ///     be constructed, allowing to compute higher order derivative
+  ///     products. Defaults to ``false``.
+  /// \param inputs Inputs w.r.t. which the gradient will be accumulated into
+  ///     ``at::Tensor::grad``. All other Tensors will be ignored. If not
+  ///     provided, the gradient is accumulated into all the leaf Tensors
+  ///     that were used to compute the current tensor.
+  ///     When inputs are provided and a given input is not a leaf,
+  ///     the current implementation will call its grad_fn (even though it is not strictly needed to get this gradients).
+  ///     It is an implementation detail on which the user should not rely.
+  ///     See https://github.com/pytorch/pytorch/pull/60521#issuecomment-867061780 for more details.
+  void backward(const Tensor & gradient={}, std::optional retain_graph=std::nullopt, bool create_graph=false, std::optional inputs=std::nullopt) const {
+    // NB: Adding this wrapper to _backward here because we'd like our
+    // 'backwards' api to accept the 'inputs' argument optionally. Since code gen
+    // currently does not support optional of TensorList our approach is to replace
+    // backward in native_functions.yaml with _backward and call it here instead.
+    if (inputs.has_value()) {
+      TORCH_CHECK(inputs.value().size() > 0, "'inputs' argument to backward cannot be empty")
+      this->_backward(inputs.value(), gradient, retain_graph, create_graph);
+    } else {
+      this->_backward({}, gradient, retain_graph, create_graph);
+    }
+  }
+
+  /// \fn Tensor detach() const;
+  ///
+  /// Returns a new Tensor, detached from the current graph.
+  /// The result will never require gradient.
+
+  /// \fn Tensor & detach_() const;
+  ///
+  /// Detaches the Tensor from the graph that created it, making it a leaf.
+  /// Views cannot be detached in-place.
+
+  /// \fn void retain_grad() const;
+  ///
+  /// Enables this Tensor to have their :attr:`grad` populated during
+  /// :func:`backward`. This is a no-op for leaf tensors.
+
+  /// \fn bool retains_grad() const;
+  ///
+  /// Is ``true`` if this Tensor is non-leaf and its :attr:`grad` is enabled to be
+  /// populated during :func:`backward`, ``false`` otherwise.
+
+  const Tensor& set_requires_grad(bool requires_grad) const {
+    TensorBase::set_requires_grad(requires_grad);
+    return *this;
+  }
+
+  /// Return a mutable reference to the gradient. This is conventionally
+  /// used as `t.grad() = x` to set a gradient to a completely new tensor.
+  /// Note that this function work with a non-const Tensor and is not
+  /// thread safe.
+  Tensor& mutable_grad() const {
+    return impl_->mutable_grad();
+  }
+
+  /// This function returns an undefined tensor by default and returns a defined tensor
+  /// the first time a call to `backward()` computes gradients for this Tensor.
+  /// The attribute will then contain the gradients computed and future calls
+  /// to `backward()` will accumulate (add) gradients into it.
+  const Tensor& grad() const {
+    const Tensor& maybe_grad = impl_->grad();
+    if (!is_leaf() && !retains_grad() && !maybe_grad.defined()) {
+      TORCH_WARN(
+        "The .grad attribute of a Tensor that is not a leaf Tensor is being accessed. Its .grad "
+        "attribute won't be populated during autograd.backward(). If you indeed want the .grad "
+        "field to be populated for a non-leaf Tensor, use .retain_grad() on the non-leaf Tensor. "
+        "If you access the non-leaf Tensor by mistake, make sure you access the leaf Tensor "
+        "instead. See github.com/pytorch/pytorch/pull/30531 for more information.");
+    }
+    return maybe_grad;
+  }
+
+  // The Forward AD API functions below are low level and are not to be used by end
+  // users who should use the API provided in torch/csrc/autograd.h
+
+  /// This function returns the forward gradient for this Tensor at the given level.
+  const Tensor& _fw_grad(uint64_t level) const {
+    return impl_->_fw_grad(level, *this);
+  }
+
+  /// This function can be used to set the value of the forward grad.
+  /// Note that the given new_grad might not be used directly if it has different
+  /// metadata (size/stride/storage offset) compared to this Tensor. In that case,
+  /// new_grad content will be copied into a new Tensor
+  void _set_fw_grad(const TensorBase& new_grad, uint64_t level, bool is_inplace_op) const {
+    impl_->_set_fw_grad(new_grad, *this, level, is_inplace_op);
+  }
+
+
+  // STOP.  Thinking of adding a method here, which only makes use
+  // of other ATen methods?  Define it in native_functions.yaml.
+
+  //example
+  //Tensor * add(Tensor & b);
+  ${tensor_method_declarations}
+
+  // Special C++ only overloads for std()-like functions (See gh-40287)
+  // These are needed because int -> bool conversion takes precedence over int -> IntArrayRef
+  // So, for example std(0) would select the std(unbiased=False) overload
+
+  Tensor var(int dim) const {
+    return var(IntArrayRef{dim});
+  }
+
+  Tensor std(int dim) const {
+    return std(IntArrayRef{dim});
+  }
+
+  // We changed .dtype() to return a TypeMeta in #12766. Ideally, we want the
+  // at::kDouble and its friends to be TypeMeta's, but that hasn't happened yet.
+  // Before that change, we make this method to maintain BC for C++ usage like
+  // `x.to(y.dtype)`.
+  // TODO: remove following two after at::kDouble and its friends are TypeMeta's.
+  inline Tensor to(caffe2::TypeMeta type_meta, bool non_blocking=false, bool copy=false) const {
+    return this->to(/*scalar_type=*/typeMetaToScalarType(type_meta), non_blocking, copy);
+  }
+  inline Tensor to(Device device, caffe2::TypeMeta type_meta, bool non_blocking=false, bool copy=false) const {
+    return this->to(device, /*scalar_type=*/typeMetaToScalarType(type_meta), non_blocking, copy);
+  }
+
+  template 
+  decltype(auto) m(F func, Args&&... params) const {
+    return func(*this, std::forward(params)...);
+  }
+
+  /// NOTE: This is similar to the legacy `.data()` function on `Variable`, and is intended
+  /// to be used from functions that need to access the `Variable`'s equivalent `Tensor`
+  /// (i.e. `Tensor` that shares the same storage and tensor metadata with the `Variable`).
+  ///
+  /// One notable difference with the legacy `.data()` function is that changes to the
+  /// returned `Tensor`'s tensor metadata (e.g. sizes / strides / storage / storage_offset)
+  /// will not update the original `Variable`, due to the fact that this function
+  /// shallow-copies the `Variable`'s underlying TensorImpl.
+  at::Tensor tensor_data() const {
+    return TensorBase::tensor_data();
+  }
+
+  /// NOTE: `var.variable_data()` in C++ has the same semantics as `tensor.data`
+  /// in Python, which create a new `Variable` that shares the same storage and
+  /// tensor metadata with the original `Variable`, but with a completely new
+  /// autograd history.
+  ///
+  /// NOTE: If we change the tensor metadata (e.g. sizes / strides /
+  /// storage / storage_offset) of a variable created from `var.variable_data()`, those
+  /// changes will not update the original variable `var`. In `.variable_data()`, we set
+  /// `allow_tensor_metadata_change_` to false to make such changes explicitly illegal,
+  /// in order to prevent users from changing metadata of `var.variable_data()`
+  /// and expecting the original variable `var` to also be updated.
+  at::Tensor variable_data() const {
+    return TensorBase::variable_data();
+  }
+
+  // Hooks
+  //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+  template 
+  using hook_return_void_t = std::enable_if_t>::value, unsigned>;
+  template 
+  using hook_return_var_t = std::enable_if_t, Tensor>, unsigned>;
+
+  /// Registers a backward hook.
+  ///
+  /// The hook will be called every time a gradient with respect to the Tensor is computed.
+  /// The hook should have one of the following signature:
+  /// ```
+  /// hook(Tensor grad) -> Tensor
+  /// ```
+  /// ```
+  /// hook(Tensor grad) -> void
+  /// ```
+  /// The hook should not modify its argument, but it can optionally return a new gradient
+  /// which will be used in place of `grad`.
+  ///
+  /// This function returns the index of the hook in the list which can be used to remove hook.
+  ///
+  /// Example:
+  /// @code
+  /// auto v = torch::tensor({0., 0., 0.}, torch::requires_grad());
+  /// auto h = v.register_hook([](torch::Tensor grad){ return grad * 2; }); // double the gradient
+  /// v.backward(torch::tensor({1., 2., 3.}));
+  /// // This prints:
+  /// // ```
+  /// //  2
+  /// //  4
+  /// //  6
+  /// // [ CPUFloatType{3} ]
+  /// // ```
+  /// std::cout << v.grad() << std::endl;
+  /// v.remove_hook(h);  // removes the hook
+  /// @endcode
+  template 
+  hook_return_void_t register_hook(T&& hook) const;
+  template 
+  hook_return_var_t register_hook(T&& hook) const;
+
+  // Variable methods
+  //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+  Tensor data() const {
+    return TensorBase::data();
+  }
+
+  void _backward(TensorList inputs, const std::optional& gradient, std::optional keep_graph, bool create_graph) const;
+
+  const Tensor& requires_grad_(bool _requires_grad=true) const {
+    TensorBase::requires_grad_(_requires_grad);
+    return *this;
+  }
+};
+
+namespace detail {
+// Helper creator for Tensor class which doesn't requires the users to pass
+// in an intrusive_ptr instead it just converts the argument passed to
+// requested intrusive_ptr type.
+template 
+Tensor make_tensor(Args&&... args) {
+  return Tensor(c10::make_intrusive(std::forward(args)...));
+}
+
+} // namespace detail
+
+} // namespace at
+
+
+namespace at {
+${tensor_method_definitions}
+} // namespace at
+
+
+namespace c10 {
+template <>
+struct MaybeOwnedTraits {
+  using owned_type = at::Tensor;
+  using borrow_type = at::Tensor;
+
+  static borrow_type createBorrow(const owned_type& from) {
+    // NOTE: this can be implemented without the special
+    // unsafe_borrow_t Tensor constructor as
+    //
+    // return borrow_type(c10::intrusive_ptr::reclaim(from.unsafeGetTensorImpl()));
+    //
+    // but that hurts inlining due to the nullptr check in the
+    // Tensor(c10::intrusive_ptr<...>) constructor. We already know
+    // that from.impl_ isn't null because from is a valid Tensor, so
+    // we needn't do the check again. (using __builtin_assume can
+    // avoid this, but wouldn't be portable to MSVC.)
+    return borrow_type(borrow_type::unsafe_borrow_t{}, from);
+  }
+
+  static void assignBorrow(borrow_type& lhs, const borrow_type& rhs) {
+    lhs.unsafeReleaseTensorImpl();
+    // See above note: this can be implemented with public API
+    // similarly to createBorrow(), but that would hurt inlining.
+    lhs = borrow_type(borrow_type::unsafe_borrow_t{}, rhs);
+  }
+
+  static void destroyBorrow(borrow_type& toDestroy) {
+    toDestroy.unsafeReleaseTensorImpl(); // "leak" it, but it was already +0.
+  }
+
+  static const owned_type& referenceFromBorrow(const borrow_type& borrow) {
+    return borrow;
+  }
+
+  static const owned_type* pointerFromBorrow(const borrow_type& borrow) {
+    return &borrow;
+  }
+
+  static bool debugBorrowIsValid(const borrow_type& /*borrow*/) {
+    return true;
+  }
+};
+
+template <>
+struct ExclusivelyOwnedTraits {
+  using repr_type = at::Tensor;
+  using pointer_type = at::Tensor*;
+  using const_pointer_type = const at::Tensor*;
+
+  static repr_type nullRepr() {
+    return at::Tensor();
+  }
+
+  template 
+  static repr_type createInPlace(Args&&... args) {
+    return at::Tensor(std::forward(args)...);
+  }
+
+  static repr_type moveToRepr(at::Tensor&& x) {
+    return std::move(x);
+  }
+
+  static void destroyOwned(at::Tensor& x) {
+    return ExclusivelyOwnedTraits::destroyOwned(x);
+  }
+
+  static at::Tensor take(at::Tensor& x) {
+    return std::move(x);
+  }
+
+  static pointer_type getImpl(repr_type& x) {
+    return &x;
+  }
+
+  static const_pointer_type getImpl(const repr_type& x) {
+    return &x;
+  }
+};
+} // namespace c10
+
+namespace at {
+
+inline c10::MaybeOwned borrow_from_optional_tensor(
+    const std::optional& opt) {
+  return opt.has_value()
+    ? c10::MaybeOwned::borrowed(*opt)
+    : c10::MaybeOwned::owned(std::in_place);
+}
+
+inline c10::MaybeOwned Tensor::expect_contiguous(MemoryFormat memory_format) const & {
+  if (is_contiguous(memory_format)) {
+    return c10::MaybeOwned::borrowed(*this);
+  } else {
+    return c10::MaybeOwned::owned(__dispatch_contiguous(memory_format));
+  }
+}
+} // namespace at
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/TensorMethods.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/TensorMethods.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..0504dccc385c9f3ad6ae3755df21aee1f476939b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/TensorMethods.cpp
@@ -0,0 +1,61 @@
+#include 
+#include 
+
+#include 
+
+namespace at {
+
+namespace {
+
+// Verifies the requested type is the same as the Tensor's type.
+void check_type(const TensorBase& tensor, ScalarType type, std::string_view type_name) {
+  TORCH_CHECK(
+      tensor.scalar_type() == type
+      || (isQIntType(tensor.scalar_type())
+          && toUnderlying(tensor.scalar_type()) == type),
+      "expected scalar type ", type_name, " but found ", tensor.scalar_type());
+}
+
+} // namespace
+
+#define DEFINE_CAST(T, name)                                         \
+   template <>                                                       \
+   TORCH_API const T* TensorBase::const_data_ptr() const {           \
+     check_type(*this, ScalarType::name, #name);                     \
+     return this->unsafeGetTensorImpl()->data_ptr_impl();         \
+   }                                                                 \
+                                                                     \
+   template <>                                                       \
+   TORCH_API const T* TensorBase::const_data_ptr() const {  \
+     check_type(*this, ScalarType::name, #name);                     \
+     return this->unsafeGetTensorImpl()->data_ptr_impl>(); \
+   }                                                                 \
+                                                                     \
+   template <>                                                       \
+   TORCH_API T* TensorBase::mutable_data_ptr() const {               \
+     check_type(*this, ScalarType::name, #name);                     \
+     return this->unsafeGetTensorImpl()->mutable_data_ptr_impl(); \
+   }                                                                 \
+                                                                     \
+   template <>                                                       \
+   TORCH_API T* TensorBase::data_ptr() const {                       \
+     return mutable_data_ptr();                                   \
+   }                                                                 \
+
+ AT_FORALL_SCALAR_TYPES_WITH_COMPLEX(DEFINE_CAST)
+ AT_FORALL_QINT_TYPES(DEFINE_CAST)
+ DEFINE_CAST(uint16_t, UInt16)
+ DEFINE_CAST(uint32_t, UInt32)
+ DEFINE_CAST(uint64_t, UInt64)
+ #undef DEFINE_CAST
+
+ #define DEFINE_ITEM(T, name)      \
+   template <>                     \
+   TORCH_API T Tensor::item() const { \
+     return item().to##name();     \
+   }
+
+ AT_FORALL_SCALAR_TYPES_WITH_COMPLEX(DEFINE_ITEM)
+ #undef DEFINE_ITEM
+
+ } //namespace at
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/UfuncCPU.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/UfuncCPU.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..6b363a508907cc064e41794720657541fc28c301
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/UfuncCPU.cpp
@@ -0,0 +1,19 @@
+#define TORCH_ASSERT_NO_OPERATORS
+
+#include 
+#include 
+#include 
+
+namespace at {
+
+// NB: this is explicitly copied here (via codegen) rather than
+// included via NativeFunctions.h to avoid recompiling this file when
+// NativeFunctions.h changes
+namespace meta {
+${meta_declaration}
+}
+
+namespace native {
+${native_declaration}
+${native_definitions}
+}} // namespace at::native
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/UfuncCPUKernel.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/UfuncCPUKernel.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..0cac55664d6125287bdee0bd94c150462b81d5b9
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/UfuncCPUKernel.cpp
@@ -0,0 +1,14 @@
+#define TORCH_ASSERT_NO_OPERATORS
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace at {
+namespace native {
+${native_definitions}
+}} // namespace at::native
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/UfuncCUDA.cu b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/UfuncCUDA.cu
new file mode 100644
index 0000000000000000000000000000000000000000..e75d82d9cc84bd8fddfd303f610412e5d0a98729
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/UfuncCUDA.cu
@@ -0,0 +1,21 @@
+#define TORCH_ASSERT_NO_OPERATORS
+
+#include 
+#include 
+#include 
+#include 
+${cuda_headers}
+
+namespace at {
+
+// NB: this is explicitly copied here (via codegen) rather than
+// included via NativeFunctions.h to avoid recompiling this file when
+// NativeFunctions.h changes
+namespace meta {
+${meta_declaration}
+}
+
+namespace native {
+${native_declaration}
+${native_definitions}
+}} // namespace at::native
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/UnboxingFunctions.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/UnboxingFunctions.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..86c13235d8623964d734e743f5f15cf68a8df63c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/UnboxingFunctions.cpp
@@ -0,0 +1,35 @@
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+namespace at {
+namespace unboxing {
+
+using ::c10::fmap;
+using ::c10::filter;
+using torch::jit::peek;
+using torch::jit::drop;
+using torch::jit::pack;
+using torch::jit::pop;
+
+// Generated function declaration
+${definitions}
+
+} // namespace unboxing
+} // namespace at
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/UnboxingFunctions.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/UnboxingFunctions.h
new file mode 100644
index 0000000000000000000000000000000000000000..a65469a9b0123cbfd4075ff3c263276aa47f137f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/UnboxingFunctions.h
@@ -0,0 +1,32 @@
+// ${generated_comment}
+
+// Generated by tools/jit/gen_unboxing.py. This file declares code generated boxed C++ functions for operators,
+// base off of native_functions.yaml (or similar yaml file with the same syntax). The definition of such a boxed
+// function will pop out IValues from the stack then convert them into the correct C++ types based on given schema. This
+// unboxing logic is an alternative to template-based metaprogramming unboxing.
+
+#pragma once
+
+#include 
+namespace at {
+namespace unboxing {
+namespace {
+
+template
+std::array as_array(const c10::List& list) {
+    std::array res;
+    AT_ASSERT(list.size() == N);
+    std::vector vec;
+    for (c10::IValue elem : list) {
+        vec.push_back(elem.to());
+    }
+    std::copy(vec.begin(), vec.end(), res.begin());
+    return res;
+}
+}  // namespace 
+using Stack = std::vector;
+// Generated function declaration
+${declarations}
+
+} // namespace unboxing
+} // namespace at
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/ViewMetaClasses.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/ViewMetaClasses.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..0fd53171935f9147ba54bcd39a886e2f4dda6b2f
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/ViewMetaClasses.cpp
@@ -0,0 +1,19 @@
+// ${generated_comment}
+
+#include 
+#include 
+
+#ifndef AT_PER_OPERATOR_HEADERS
+#include 
+#include 
+#else
+${op_headers}
+#endif
+
+namespace at {
+namespace functionalization {
+
+${view_meta_implementations}
+
+} // namespace functionalization
+} // namespace at
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/ViewMetaClasses.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/ViewMetaClasses.h
new file mode 100644
index 0000000000000000000000000000000000000000..be2dee2a871b35258864377fbac83e3037108b2b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/ViewMetaClasses.h
@@ -0,0 +1,12 @@
+#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
+// ${generated_comment}
+
+#include 
+
+namespace at {
+namespace functionalization {
+
+${view_meta_declarations}
+
+} // namespace functionalization
+} // namespace at
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/ViewMetaClassesPythonBinding.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/ViewMetaClassesPythonBinding.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..c784e5abe5c88dfb5bc418e60d48b28391274718
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/ViewMetaClassesPythonBinding.cpp
@@ -0,0 +1,11 @@
+#include 
+#include 
+
+namespace torch::functionalization {
+
+void initGenerated(PyObject* module) {
+  auto functionalization = py::handle(module).cast();
+  $view_meta_bindings
+}
+
+} // namespace torch::functionalization
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/aten_interned_strings.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/aten_interned_strings.h
new file mode 100644
index 0000000000000000000000000000000000000000..326d4622334a776f4f1f94fb49a70f2c53c7e6eb
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/aten_interned_strings.h
@@ -0,0 +1,22 @@
+#pragma once
+
+// ${generated_comment}
+
+#if defined(TORCH_ASSERT_NO_OPERATORS) || defined(TORCH_ASSERT_ONLY_METHOD_OPERATORS)
+#error This change adds a dependency on native_functions.yaml,          \
+  meaning the file will need to be re-compiled every time an operator   \
+  is changed or added. Consider if including  for   \
+  the c10::Symbol class would be sufficient, or if your change would be \
+  better placed in another file.
+#endif
+
+// ATen symbols correspond exactly to operators defined in ATen. Every
+// symbol here corresponds exactly to an ATen operation defined in
+// native_functions.yaml; attributes are in one-to-one correspondence
+// with their ATen name.
+
+#define FORALL_ATEN_BASE_SYMBOLS(_) \
+${aten_symbols}
+
+#define FORALL_ATTR_BASE_SYMBOLS(_) \
+${attr_symbols}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/enum_tag.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/enum_tag.h
new file mode 100644
index 0000000000000000000000000000000000000000..1320fbc28ab8f7d72655816292f49a4c9a9b727d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/enum_tag.h
@@ -0,0 +1,10 @@
+#pragma once
+
+// ${generated_comment}
+
+namespace at {
+    // Enum of valid tags obtained from the entries in tags.yaml
+    enum class Tag {
+        ${enum_of_valid_tags}
+    };
+}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/BUILD.bazel b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/BUILD.bazel
new file mode 100644
index 0000000000000000000000000000000000000000..d1a0db360d230fe0f027c19869c6307f17010503
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/BUILD.bazel
@@ -0,0 +1,4 @@
+load("//:tools/bazel.bzl", "rules")
+load(":build.bzl", "define_targets")
+
+define_targets(rules = rules)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/README.md b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..bfa43899cc590959c2bfd74e38662ec03aaee3d6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/README.md
@@ -0,0 +1,3 @@
+If you add a file to this directory, you **MUST** update
+`torch/CMakeLists.txt` and add the file as a dependency to
+the `add_custom_command` call.
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/build.bzl b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/build.bzl
new file mode 100644
index 0000000000000000000000000000000000000000..c5ddf7a20b800a714431fdc9feb57679783410f4
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/build.bzl
@@ -0,0 +1,20 @@
+def define_targets(rules):
+    rules.py_library(
+        name = "autograd",
+        srcs = rules.glob(["*.py"]),
+        data = rules.glob([
+            "*.yaml",
+            "templates/*",
+        ]),
+        visibility = ["//:__subpackages__"],
+        deps = [
+            rules.requirement("PyYAML"),
+            "//torchgen",
+        ],
+    )
+
+    rules.filegroup(
+        name = "deprecated_yaml",
+        srcs = ["deprecated.yaml"],
+        visibility = ["//:__subpackages__"],
+    )
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/context.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/context.py
new file mode 100644
index 0000000000000000000000000000000000000000..146cf571d304184e95fedd87c42f572c2cb23500
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/context.py
@@ -0,0 +1,31 @@
+import functools
+from typing import Callable
+
+from torchgen.api.autograd import NativeFunctionWithDifferentiabilityInfo as NFWDI
+from torchgen.context import native_function_manager
+from torchgen.utils import T
+
+
+# Like tools.api.context.with_native_function, but for
+# NativeFunctionWithDifferentiabilityInfo.
+def with_native_function_with_differentiability_info(
+    func: Callable[[NFWDI], T],
+) -> Callable[[NFWDI], T]:
+    @functools.wraps(func)
+    def wrapper(f: NFWDI) -> T:
+        with native_function_manager(f.func):
+            return func(f)
+
+    return wrapper
+
+
+# Like the above but with an additional dispatch key string argument
+def with_native_function_with_differentiability_info_and_key(
+    func: Callable[[NFWDI, str], T],
+) -> Callable[[NFWDI, str], T]:
+    @functools.wraps(func)
+    def wrapper(f: NFWDI, key: str) -> T:
+        with native_function_manager(f.func):
+            return func(f, key)
+
+    return wrapper
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/deprecated.yaml b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/deprecated.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..52f7ec50b6ea15dae1c3308358997950d295c924
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/deprecated.yaml
@@ -0,0 +1,134 @@
+# Deprecated function signatures. These are exposed in Python, but not included
+# in the error message suggestions.
+
+- name: add(Tensor self, Scalar alpha, Tensor other) -> Tensor
+  aten: add(self, other, alpha)
+
+- name: add_(Tensor(a!) self, Scalar alpha, Tensor other) -> Tensor(a!)
+  aten: add_(self, other, alpha)
+
+- name: add(Tensor self, Scalar alpha, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  aten: add_out(out, self, other, alpha)
+
+- name: addbmm(Scalar beta, Tensor self, Scalar alpha, Tensor batch1, Tensor batch2) -> Tensor
+  aten: addbmm(self, batch1, batch2, beta, alpha)
+
+- name: addbmm_(Scalar beta, Tensor(a!) self, Scalar alpha, Tensor batch1, Tensor batch2) -> Tensor(a!)
+  aten: addbmm_(self, batch1, batch2, beta, alpha)
+
+- name: addbmm(Scalar beta, Tensor self, Scalar alpha, Tensor batch1, Tensor batch2, *, Tensor(a!) out) -> Tensor(a!)
+  aten: addbmm_out(out, self, batch1, batch2, beta, alpha)
+
+- name: addbmm(Scalar beta, Tensor self, Tensor batch1, Tensor batch2) -> Tensor
+  aten: addbmm(self, batch1, batch2, beta, 1)
+
+- name: addbmm_(Scalar beta, Tensor(a!) self, Tensor batch1, Tensor batch2) -> Tensor(a!)
+  aten: addbmm_(self, batch1, batch2, beta, 1)
+
+- name: addbmm(Scalar beta, Tensor self, Tensor batch1, Tensor batch2, *, Tensor(a!) out) -> Tensor(a!)
+  aten: addbmm_out(out, self, batch1, batch2, beta, 1)
+
+- name: addcdiv(Tensor self, Scalar value, Tensor tensor1, Tensor tensor2) -> Tensor
+  aten: addcdiv(self, tensor1, tensor2, value)
+
+- name: addcdiv_(Tensor(a!) self, Scalar value, Tensor tensor1, Tensor tensor2) -> Tensor(a!)
+  aten: addcdiv_(self, tensor1, tensor2, value)
+
+- name: addcdiv(Tensor self, Scalar value, Tensor tensor1, Tensor tensor2, *, Tensor(a!) out) -> Tensor(a!)
+  aten: addcdiv_out(out, self, tensor1, tensor2, value)
+
+- name: addcmul(Tensor self, Scalar value, Tensor tensor1, Tensor tensor2) -> Tensor
+  aten: addcmul(self, tensor1, tensor2, value)
+
+- name: addcmul_(Tensor(a!) self, Scalar value, Tensor tensor1, Tensor tensor2) -> Tensor(a!)
+  aten: addcmul_(self, tensor1, tensor2, value)
+
+- name: addcmul(Tensor self, Scalar value, Tensor tensor1, Tensor tensor2, *, Tensor(a!) out) -> Tensor(a!)
+  aten: addcmul_out(out, self, tensor1, tensor2, value)
+
+- name: addmm(Scalar beta, Tensor self, Scalar alpha, Tensor mat1, Tensor mat2) -> Tensor
+  aten: addmm(self, mat1, mat2, beta, alpha)
+
+- name: addmm_(Scalar beta, Tensor(a!) self, Scalar alpha, Tensor mat1, Tensor mat2) -> Tensor(a!)
+  aten: addmm_(self, mat1, mat2, beta, alpha)
+
+- name: addmm(Scalar beta, Tensor self, Scalar alpha, Tensor mat1, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!)
+  aten: addmm_out(out, self, mat1, mat2, beta, alpha)
+
+- name: addmm(Scalar beta, Tensor self, Tensor mat1, Tensor mat2) -> Tensor
+  aten: addmm(self, mat1, mat2, beta, 1)
+
+- name: addmm_(Scalar beta, Tensor(a!) self, Tensor mat1, Tensor mat2) -> Tensor(a!)
+  aten: addmm_(self, mat1, mat2, beta, 1)
+
+- name: addmm(Scalar beta, Tensor self, Tensor mat1, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!)
+  aten: addmm_out(out, self, mat1, mat2, beta, 1)
+
+- name: sspaddmm(Scalar beta, Tensor self, Scalar alpha, Tensor mat1, Tensor mat2) -> Tensor
+  aten: sspaddmm(self, mat1, mat2, beta, alpha)
+
+- name: sspaddmm(Scalar beta, Tensor self, Tensor mat1, Tensor mat2) -> Tensor
+  aten: sspaddmm(self, mat1, mat2, beta, 1)
+
+- name: addmv(Scalar beta, Tensor self, Scalar alpha, Tensor mat, Tensor vec) -> Tensor
+  aten: addmv(self, mat, vec, beta, alpha)
+
+- name: addmv_(Scalar beta, Tensor(a!) self, Scalar alpha, Tensor mat, Tensor vec) -> Tensor(a!)
+  aten: addmv_(self, mat, vec, beta, alpha)
+
+- name: addmv(Scalar beta, Tensor self, Scalar alpha, Tensor mat, Tensor vec, *, Tensor(a!) out) -> Tensor(a!)
+  aten: addmv_out(out, self, mat, vec, beta, alpha)
+
+- name: addmv(Scalar beta, Tensor self, Tensor mat, Tensor vec) -> Tensor
+  aten: addmv(self, mat, vec, beta, 1)
+
+- name: addmv_(Scalar beta, Tensor(a!) self, Tensor mat, Tensor vec) -> Tensor(a!)
+  aten: addmv_(self, mat, vec, beta, 1)
+
+- name: addmv(Scalar beta, Tensor self, Tensor mat, Tensor vec, *, Tensor(a!) out) -> Tensor(a!)
+  aten: addmv_out(out, self, mat, vec, beta, 1)
+
+- name: addr(Scalar beta, Tensor self, Scalar alpha, Tensor vec1, Tensor vec2) -> Tensor
+  aten: addr(self, vec1, vec2, beta, alpha)
+
+- name: addr_(Scalar beta, Tensor(a!) self, Scalar alpha, Tensor vec1, Tensor vec2) -> Tensor(a!)
+  aten: addr_(self, vec1, vec2, beta, alpha)
+
+- name: addr(Scalar beta, Tensor self, Scalar alpha, Tensor vec1, Tensor vec2, *, Tensor(a!) out) -> Tensor(a!)
+  aten: addr_out(out, self, vec1, vec2, beta, alpha)
+
+- name: addr(Scalar beta, Tensor self, Tensor vec1, Tensor vec2) -> Tensor
+  aten: addr(self, vec1, vec2, beta, 1)
+
+- name: addr_(Scalar beta, Tensor(a!) self, Tensor vec1, Tensor vec2) -> Tensor(a!)
+  aten: addr_(self, vec1, vec2, beta, 1)
+
+- name: addr(Scalar beta, Tensor self, Tensor vec1, Tensor vec2, *, Tensor(a!) out) -> Tensor(a!)
+  aten: addr_out(out, self, vec1, vec2, beta, 1)
+
+- name: baddbmm(Scalar beta, Tensor self, Scalar alpha, Tensor batch1, Tensor batch2) -> Tensor
+  aten: baddbmm(self, batch1, batch2, beta, alpha)
+
+- name: baddbmm_(Scalar beta, Tensor(a!) self, Scalar alpha, Tensor batch1, Tensor batch2) -> Tensor(a!)
+  aten: baddbmm_(self, batch1, batch2, beta, alpha)
+
+- name: baddbmm(Scalar beta, Tensor self, Scalar alpha, Tensor batch1, Tensor batch2, *, Tensor(a!) out) -> Tensor(a!)
+  aten: baddbmm_out(out, self, batch1, batch2, beta, alpha)
+
+- name: baddbmm(Scalar beta, Tensor self, Tensor batch1, Tensor batch2) -> Tensor
+  aten: baddbmm(self, batch1, batch2, beta, 1)
+
+- name: baddbmm_(Scalar beta, Tensor(a!) self, Tensor batch1, Tensor batch2) -> Tensor(a!)
+  aten: baddbmm_(self, batch1, batch2, beta, 1)
+
+- name: baddbmm(Scalar beta, Tensor self, Tensor batch1, Tensor batch2, *, Tensor(a!) out) -> Tensor(a!)
+  aten: baddbmm_out(out, self, batch1, batch2, beta, 1)
+
+- name: sub(Tensor self, Scalar alpha, Tensor other) -> Tensor
+  aten: sub(self, other, alpha)
+
+- name: sub_(Tensor(a!) self, Scalar alpha, Tensor other) -> Tensor(a!)
+  aten: sub_(self, other, alpha)
+
+- name: sub(Tensor self, Scalar alpha, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+  aten: sub_out(out, self, other, alpha)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/derivatives.yaml b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/derivatives.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..c050c6cbdc4c319563b69d27136d3381ad695afe
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/derivatives.yaml
@@ -0,0 +1,3247 @@
+# Defines derivative formulas and Python signatures of methods on Variable
+#
+# Note about possibly confusing nomenclature: An 'output gradient' is the
+# gradient of an output of a forward function. Output gradients are used as
+# the inputs to backward functions. `grads` is a vector of output gradients,
+# and `grad == grads[0]`, in all the derivative formulas in this file.
+# An 'input gradient' is the gradient of an input to a forward function.
+# Input gradients are the outputs of backward functions, corresponding to the
+# input names included in the derivative formulas defined in this file.
+# Also, every time we talk computing "gradient" we actually mean computing
+# the vector jacobian product using the given 'output gradient' as the vector.
+#
+# Each entry consists of:
+#   - A 'name', which specifies the ATen name of the function you
+#     are defining derivatives for, and an argument specification.
+#   - An optional 'dispatch' entry which can be used to specify
+#     per-autograd dispatch key derivatives. If this entry is not
+#     specified, then the gradient entries will be taken as the
+#     default gradients (i.e. registered for every backward dispatch
+#     key). (see _test_autograd_multiple_dispatch for an example
+#     of how to register separate derivates for different dispatch keys).
+#     The list of allowed dispatch keys (in addition to 'Default' which
+#     represents the Autograd alias key) is torchgen/model.py:AUTOGRAD_KEYS.
+#   - One or more gradients entries, mapping differentiable input
+#     names to a formula specifying how to compute its gradient.
+#     Note that a single gradient entry can specify the gradient
+#     formula for multiple input names, by specifying a key
+#     "input1, input2" (see atan2 for an example).
+#   - An argument can be flagged as 'non_differentiable'.
+#   - Optional entry with key 'output_differentiability' and value a list of the
+#     same length as the number of outputs from the forward function. The list
+#     should contain only booleans, specifying whether each of the output Tensor
+#     is differentiable.
+#     If it is not specified for a function that returns multiple elements but
+#     uses `grad` instead of `grads[idx]`, then all but the first output will
+#     be marked as non-differentiable.
+#     If None of the output is differentiable, you can also add the function
+#     name to `gen_variable_type.py`'s `DONT_REQUIRE_DERIVATIVE` list.
+#
+# There are two cases for Tensor and TensorList arguments here:
+#   - If that argument is differentiable, in the sense that a gradient with respect
+#     to that argument could exist. You should either:
+#       - Specify the formula for that gradient
+#       - Specify not_implemented("function_name") as a formula to say that this is not
+#         implemented yet (but might be in the future and the user can request that on an issue)
+#   - If that argument is not differentiable, because it is not a floating point dtype or the
+#     function is not differentiable with respect to that argument  for
+#     example. You should either:
+#       - Do not specify any formula for this argument
+#       - Specify explicitly that this argument is "non_differentiable". Note that in this case,
+#         we trust you that this argument will never have requires_grad=True and it will be silently
+#         ignored if it does.
+#
+# If a function has out-of-place and in-place variants, then the derivative
+# definition for the in-place variant is optional. It will default to the
+# definition for the out-of-place variant. Note that _out variants are never
+# differentiable.
+#
+# Gradient expressions are standard C++ expressions operating on ATen
+# variables.  In a gradient expression, the following variables/functions
+# are in scope:
+#
+#   - 'grad', the gradient of the output (often spelled grad_output
+#     in Python) which we are going to left-multiply.
+#
+#     When a function returns multiple *differentiable* outputs,
+#     you can refer to the gradients of each outputs using 'grads',
+#     e.g., 'grads[0]', 'grads[1]'.
+#
+#     When a function returns multiple *differentiable* outputs that
+#     are named, you can refer to the gradients of each outputs using
+#     'grad_{name}', e.g., 'grad_x', 'grad_y'.
+#
+#     When a function returns *one* differentiable output (the
+#     first output) and some more nondifferentiable outputs,
+#     you MUST refer to the gradient of the differentiable output with
+#     'grad' (this case is special-cased in our code generation).
+#
+#     Note that the number of differentiable outputs can be modified by the
+#     'output_differentiability' entry (see above).
+#
+#     Across a differentiable function's derivatives set, it is not
+#     permitted to mix the use of "grad", "grads", and
+#     "grad_{name}". You must be consistent for that differentiable
+#     function.
+#
+#   - Any of the input arguments, tensor or non-tensor, including
+#     argument names that only appear in Declarations.yaml, e.g. 'output'.
+#
+#   - 'result', representing the result of evaluating the forward
+#     expression for ATen native function declarations. If the forward
+#     expression outputs a tuple, use 'resultX' instead to access the
+#     X-th entry
+#
+#   - 'grad_input_mask', a std::array, specifies which input
+#     gradients are actually needed.  For example, in the entry
+#     `input0, input1: foo(grad_input_mask)`, `grad_input_mask` is a size
+#     two array, where `grad_input_mask[0]` is true if `input0` requires
+#     grad, and `grad_input_mask[1]` is true if `input1` requires grad.
+#
+#     (NB: if your function computes gradient for a list of tensors,
+#     the `grad_input_mask` will only have a single entry for the list
+#     specifying if either zero or at least one tensor from the list requires
+#     grad.  If we want to support more fine-grained signalling,
+#     we'll need some alternate variable which is not a std::array)
+#
+#   - 'retain_variables', a bool which is true if a user has specified
+#     that saved variables should be retained in case the backwards is
+#     run again later.  This allows an optimization where we can
+#     destroy saved buffers if we know variables are not going to be retained,
+#     e.g., it is used by _cudnn_rnn
+#
+#   - `wrap_opt_if`, is a 2-argument function that accepts a tensor
+#     variable and a boolean condition that dictates whether to save that
+#     variable in a graph. The result of this function is `std::optional`,
+#     and it is `::std::nullopt` when the condition evaluates to `false`,
+#     otherwise it is the variable wrapped in `std::optional`.
+#     For example, wrap_opt_if(var_0, grad_input_mask[1] || grad_input_mask[2])
+#     would mean that `var_0` is saved as long as the second (grad_input_mask[1])
+#     or the third (grad_input_mask[2]) argument requires gradients.
+#     Another interpretation of this expression would read as `var_0` is needed
+#     in the backward computation of the second or the third argument.
+#     NOTE: the usage of `var_i.requires_grad()` in the conditional expression
+#     is not supported, use `grad_input_mask[i]` instead.
+#     NOTE: `wrap_opt_if` could be used to prevent saving redundant variables
+#     with multi-output backward formulas.
+#     See https://github.com/pytorch/pytorch/issues/97575 for more details
+#     on the issue.
+#
+# If you need a complex expression, e.g., with local variables,
+# write a _backward function in torch/csrc/autograd/FunctionsManual.cpp
+# and invoke it from here.  By the way, go read
+# https://github.com/zdevito/ATen/issues/163; this describes an
+# important hazard that occurs when porting backwards from Python to C++
+#
+# Double backwards gradient expressions can be somewhat confusing;
+# the most important thing to remember is: (1) you need to define a
+# derivative formula for every input, including inputs named things
+# like 'grad_output', and (2) the gradient to multiply with is always
+# called 'grad' (even though it really is a grad-grad).
+#
+# You can also add forward derivative definition by defining a formula for
+# a returned value (in general "result" if the name is not specified). This
+# formula works the same way as the backward one and advanced implementations
+# should also be placed in the FunctionsManual file.
+# This formula should compute a single Jacobian vector product using the (primal)
+# value of the argument "foo_p", its forward grad "foo_t" and the result of the
+# function as "result".
+# Note that the forward derivative can be automatically generated in two cases:
+#     - if your function is linear (NOT affine or multi-linear), then you can
+#       specify so by just using the string "auto_linear" for the formula.
+#     - if your function is applied element wise (and has a single input), you
+#       can specify so by just using the string "auto_element_wise" for the formula.
+#
+# Note that to avoid unpacking overhead, functions taking TensorList as inputs
+# will always have their forward grad formula called. This function is responsible
+# to check if any computation is needed and should return an undefined Tensor when
+# there is nothing to do. You can check "cat_forward" for a full example.
+#
+# NB: There are a number of gradient definitions in here which are bogus
+# (implemented using zeros_like).  These gradients are (hopefully) not
+# used by our frontend.  You MUST check the frontend code; search for
+# OpName.apply to see if it's still using a legacy Python style API.
+#
+# Note: Returning views.
+# The following cases exist:
+#     - If a function returns no view, it can have arbitrary outputs.
+#     - If a function return at least one Tensor that is a differentiable view
+#       of one of its input:
+#         - If there is only one differentiable output, this Tensor is marked as a
+#           differentiable view. (alias or transpose for example)
+#         - If there are more than one differentiable output, by default all the views are
+#           marked as differentiable views and created with allow_rebase_history=false.
+#           Meaning that any inplace operation on it will raise an error. (unbind for example)
+#
+#  Notes about undefined output gradients:
+#     All backward functions must support all combinations of undefined output
+#     gradient Tensors, where `grad[i].defined() == false`. Depending on the
+#     number of input and output grads your derivative formula uses, code
+#     generation may automatically add some level of undefined grad support,
+#     according to these three cases:
+#
+#       * 1 input grad and 1 output grad:
+#           Complete undefined grad support is automatically added, so you
+#           shouldn't have to think about it, unless there is a bug in the code
+#           generation.
+#
+#       * 1 input grad and multiple output grads:
+#           Undefined grad support is automatically added ONLY in the case where
+#           all output grads are undefined. You will have to add explicit support
+#           for cases where a subset of output grads is undefined.
+#
+#       * multiple input grads:
+#           No automatic support, so you will need to add it.
+#
+#     If your derivative formula uses more than one output grad, it is usually
+#     preferable to add undefined grad support in the backward function itself
+#     (if you're using one), rather than in the derivative formula in this file.
+#
+#     Undefined Tensors are created with the default constructor `at::Tensor()`.
+#     It is an efficient way to represent a Tensor filled with zeros because
+#     the Tensor holds no sizing information and no Storage data is allocated.
+#     But consequently, Tensor operations cannot be performed on them.
+#     Therefore, your backward function should treat an undefined output grad as
+#     a zero, and it needs to be a special case.
+#
+#     If all output grads are undefined, then it should be correct for the
+#     backward function to return undefined input grads. Since we use the chain
+#     rule, output grads equal to zero should result in input grads equal to zero,
+#     unless there is some rare special case.
+#
+#     If a subset of output grads is undefined, then it may be acceptable for
+#     the backward function to return undefined input grads--it depends on the
+#     specific function, so you'll have to determine that yourself. If returning
+#     an undefined Tensor is correct for a given input grad, it is also logically
+#     correct to return a defined grad full of zeros, but that would not be
+#     preferable since it would be less efficient.
+#
+# NB: The parameter names here MUST be consistent with the parameter names
+# in native_functions.yaml
+- name: abs(Tensor self) -> Tensor
+  self: grad * self.sgn()
+  result: handle_r_to_c(result.scalar_type(), self_t.conj() * self_p.sgn())
+
+- name: acos(Tensor self) -> Tensor
+  self: grad * -((-self * self + 1).rsqrt()).conj()
+  result: auto_element_wise
+
+- name: add.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor
+  self: handle_r_to_c(self.scalar_type(), grad)
+  other: handle_r_to_c(other.scalar_type(), maybe_multiply(grad, alpha.conj()))
+  result: self_t + maybe_multiply(other_t, alpha)
+
+- name: add.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor
+  self: handle_r_to_c(self.scalar_type(), grad)
+  result: self_t.clone()
+
+- name: addbmm(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+  self: maybe_multiply(grad, beta.conj())
+  batch1: maybe_multiply(grad.unsqueeze(0).expand_symint({ batch1.sym_size(0), batch1.sym_size(1), batch2.sym_size(2) }).bmm(batch2.transpose(1, 2).conj()), alpha.conj())
+  batch2: maybe_multiply(batch1.transpose(1, 2).conj().bmm(grad.unsqueeze(0).expand_symint({ batch1.sym_size(0), batch1.sym_size(1), batch2.sym_size(2) })), alpha.conj())
+  result: maybe_multiply(self_t, beta) + maybe_multiply(batch1_t.bmm(batch2_p).sum(0), alpha) + maybe_multiply(batch1_p.bmm(batch2_t).sum(0), alpha)
+
+- name: addcdiv(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor
+  self: handle_r_to_c(self.scalar_type(), grad)
+  tensor1: handle_r_to_c(tensor1.scalar_type(), grad * (value / tensor2).conj())
+  tensor2: handle_r_to_c(tensor2.scalar_type(), -grad * (value * tensor1 / (tensor2 * tensor2)).conj())
+  result: self_t + maybe_multiply(tensor1_t / tensor2_p, value) - maybe_multiply(tensor2_t * (tensor1_p / tensor2_p) / tensor2_p, value)
+
+- name: addcmul(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor
+  self: handle_r_to_c(self.scalar_type(), grad)
+  tensor1: handle_r_to_c(tensor1.scalar_type(), grad * (tensor2 * value).conj())
+  tensor2: handle_r_to_c(tensor2.scalar_type(), grad * (tensor1 * value).conj())
+  result: self_t + maybe_multiply(tensor1_t * tensor2_p, value) + maybe_multiply(tensor2_t * tensor1_p, value)
+
+- name: addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+  self: maybe_multiply(grad, beta.conj())
+  mat1: mm_mat1_backward(grad, mat2, mat1.sym_sizes(), mat1.sym_strides(), mat1.layout(), alpha)
+  mat2: mm_mat2_backward(grad, mat1, mat2.sym_sizes(), mat2.sym_strides(), mat2.layout(), alpha)
+  result: maybe_multiply(self_t, beta) + maybe_multiply(mat1_t.mm(mat2_p), alpha) + maybe_multiply(mat1_p.mm(mat2_t), alpha)
+
+- name: _sparse_addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+  self: maybe_multiply(grad, beta)
+  mat1: mm_mat1_sparse_backward(grad, mat1, mat2, alpha)
+  mat2: mm_mat2_backward(grad, mat1, mat2.sym_sizes(), mat2.sym_strides(), mat2.layout(), alpha)
+
+- name: addmv(Tensor self, Tensor mat, Tensor vec, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+  self: maybe_multiply(grad, beta.conj())
+  mat: maybe_multiply(grad.ger(vec.conj()), alpha.conj())
+  vec: maybe_multiply(mat.t().conj().mv(grad), alpha.conj())
+  result: maybe_multiply(self_t, beta) + maybe_multiply(mat_t.mv(vec_p), alpha) + maybe_multiply(mat_p.mv(vec_t), alpha)
+
+- name: addr(Tensor self, Tensor vec1, Tensor vec2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+  self: maybe_multiply(grad, beta.conj())
+  vec1: maybe_multiply(grad.mv(vec2.conj()), alpha.conj())
+  vec2: maybe_multiply(grad.t().mv(vec1.conj()), alpha.conj())
+  result: maybe_multiply(self_t, beta) + maybe_multiply(vec1_t.outer(vec2_p), alpha) + maybe_multiply(vec1_p.outer(vec2_t), alpha)
+
+- name: affine_grid_generator(Tensor theta, SymInt[] size, bool align_corners) -> Tensor
+  theta: affine_grid_generator_backward_symint(grad, size, align_corners)
+  result: auto_linear
+
+- name: alias(Tensor(a) self) -> Tensor(a)
+  self: grad
+  result: self_t
+
+- name: angle(Tensor self) -> Tensor
+  self: angle_backward(grad, self)
+  result: handle_r_to_c(result.scalar_type(), angle_backward(self_t.conj(), self_p).conj())
+
+# The four items below are necessary because TensorIterator doesn't work on
+# Variables (codegen does not unwrap the input Tensor for all() and any() ).
+- name: any(Tensor self) -> Tensor
+  output_differentiability: [False]
+
+- name: any.dim(Tensor self, int dim, bool keepdim=False) -> Tensor
+  output_differentiability: [False]
+
+- name: any.dims(Tensor self, int[]? dim=None, bool keepdim=False) -> Tensor
+  output_differentiability: [False]
+
+- name: _is_all_true(Tensor self) -> Tensor
+  self: non_differentiable
+
+- name: _is_any_true(Tensor self) -> Tensor
+  self: non_differentiable
+
+- name: all(Tensor self) -> Tensor
+  output_differentiability: [False]
+
+- name: all.dim(Tensor self, int dim, bool keepdim=False) -> Tensor
+  output_differentiability: [False]
+
+- name: all.dims(Tensor self, int[]? dim=None, bool keepdim=False) -> Tensor
+  output_differentiability: [False]
+
+- name: acosh(Tensor self) -> Tensor
+# Save one rsqrt in the real case by using that for x real and positive sqrt(x*y) = sqrt(x)*sqrt(y) (not true in the complex case)
+  self: "self.is_complex() ? grad * ((self + 1).rsqrt() * (self - 1).rsqrt()).conj() : grad * (self * self - 1).rsqrt()"
+  result: auto_element_wise
+
+- name: acosh_(Tensor(a!) self) -> Tensor(a!)
+  self: not_implemented("inplace version of acosh")
+
+- name: asinh(Tensor self) -> Tensor
+  self: grad * (self.pow(2) + 1).rsqrt().conj()
+  result: auto_element_wise
+
+- name: asinh_(Tensor(a!) self) -> Tensor(a!)
+  self: not_implemented("inplace version of asinh")
+
+- name: atanh(Tensor self) -> Tensor
+  self: grad * 1 / (1 - self.pow(2)).conj()
+  result: auto_element_wise
+
+- name: atanh_(Tensor(a!) self) -> Tensor(a!)
+  self: not_implemented("inplace version of atanh")
+
+- name: as_strided(Tensor(a) self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor(a)
+  self: as_strided_backward(grad, TensorGeometry(self), size, stride, storage_offset)
+  result: auto_linear
+
+- name: as_strided_(Tensor(a!) self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor(a!)
+  self: as_strided_backward(grad, TensorGeometry(self), size, stride, storage_offset)
+  result: auto_linear
+
+- name: asin(Tensor self) -> Tensor
+  self: grad * (-self * self + 1).rsqrt().conj()
+  result: auto_element_wise
+
+- name: atan(Tensor self) -> Tensor
+  self: grad / (self * self + 1).conj()
+  result: auto_element_wise
+
+- name: atan2(Tensor self, Tensor other) -> Tensor
+  self, other: atan2_backward(grad, self, other, grad_input_mask)
+  result: (-self_p * other_t + other_p * self_t) / (self_p.pow(2) + other_p.pow(2))
+
+- name: baddbmm(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+  self: maybe_multiply(grad, beta.conj())
+  batch1: maybe_multiply(grad.bmm(batch2.transpose(1, 2).conj()), alpha.conj())
+  batch2: maybe_multiply(batch1.transpose(1, 2).conj().bmm(grad), alpha.conj())
+  result: maybe_multiply(self_t, beta) + maybe_multiply(batch1_t.bmm(batch2_p), alpha) + maybe_multiply(batch1_p.bmm(batch2_t), alpha)
+
+- name: bernoulli(Tensor self, *, Generator? generator=None) -> Tensor
+  self: zeros_like(grad)
+  result: auto_element_wise
+
+- name: bernoulli_.Tensor(Tensor(a!) self, Tensor p, *, Generator? generator=None) -> Tensor(a!)
+  self: zeros_like(grad)
+  p: zeros_like(p)
+  result: self_t.zero_()
+
+- name: bernoulli_.float(Tensor(a!) self, float p=0.5, *, Generator? generator=None) -> Tensor(a!)
+  self: zeros_like(grad)
+  result: self_t.zero_()
+
+- name: bmm(Tensor self, Tensor mat2) -> Tensor
+  self: grad.bmm(mat2.transpose(1, 2).conj())
+  mat2: self.transpose(1, 2).conj().bmm(grad)
+  result: self_t.bmm(mat2_p) + self_p.bmm(mat2_t)
+
+- name: matmul(Tensor self, Tensor other) -> Tensor
+  self, other: matmul_backward(grad, self, other, grad_input_mask)
+
+- name: cat(Tensor[] tensors, int dim=0) -> Tensor
+  tensors: cat_tensors_backward(grad, to_args_sizes_symint(tensors), to_args_scalartypes(tensors), dim)
+  result: cat_jvp(tensors, dim)
+
+- name: cauchy_(Tensor(a!) self, float median=0, float sigma=1, *, Generator? generator=None) -> Tensor(a!)
+  self: zeros_like(grad)
+  result: self_t.zero_()
+
+- name: ceil(Tensor self) -> Tensor
+  self: zeros_like(grad)
+  result: auto_element_wise
+
+- name: cholesky(Tensor self, bool upper=False) -> Tensor
+  self: cholesky_backward(grad, upper, result)
+
+- name: chunk(Tensor(a -> *) self, int chunks, int dim=0) -> Tensor(a)[]
+  dispatch:
+    Default:
+      # the default case will use the CompositeImplicitAutograd
+      self: not_implemented("chunk")
+    AutogradNestedTensor:
+      self: chunk_backward_nested(grads, self, chunks, dim)
+
+- name: linalg_cholesky_ex(Tensor self, *, bool upper=False, bool check_errors=False) -> (Tensor L, Tensor info)
+  self: cholesky_backward(grad, upper, L)
+  L: cholesky_jvp(self_t, L, upper)
+
+- name: cholesky_solve(Tensor self, Tensor input2, bool upper=False) -> Tensor
+  self, input2: cholesky_solve_backward(grad, self, input2, result, upper, grad_input_mask)
+  result: cholesky_solve_jvp(result, input2_p, input2_t, self_t, upper)
+
+- name: cholesky_inverse(Tensor self, bool upper=False) -> Tensor
+  self: cholesky_inverse_backward(grad, self, upper, result)
+  result: cholesky_inverse_jvp(self_p, self_t, result, upper)
+
+# For clamp, gradient is not defined at the boundaries. But empirically it's helpful
+# to be able to get gradient on min and max, so we return the subgradient 1 for these cases.
+- name: clamp.Tensor(Tensor self, Tensor? min=None, Tensor? max=None) -> Tensor
+  self: clamp_backward(grad, self, min, max)
+  min, max: clamp_backward_min_max(grad, self, min, max, grad_input_mask)
+  result: clamp_jvp(self_p, self_t, min_p, min_t, max_p, max_t)
+
+- name: clamp(Tensor self, Scalar? min=None, Scalar? max=None) -> Tensor
+  self: clamp_backward(grad, self, min, max)
+  result: auto_element_wise
+
+- name: clamp_min(Tensor self, Scalar min) -> Tensor
+  self: where(self >= min, grad, at::scalar_tensor(0., grad.options()))
+  result: auto_element_wise
+
+- name: clamp_min.Tensor(Tensor self, Tensor min) -> Tensor
+  self: where(self >= min, grad, at::scalar_tensor(0., grad.options()))
+  min: where(self < min, grad, at::scalar_tensor(0., grad.options()))
+  result: where(self_p >= min_p, self_t, min_t)
+
+- name: clamp_max(Tensor self, Scalar max) -> Tensor
+  self: where(self <= max, grad, at::scalar_tensor(0., grad.options()))
+  result: auto_element_wise
+
+- name: clamp_max.Tensor(Tensor self, Tensor max) -> Tensor
+  self: where(self <= max, grad, at::scalar_tensor(0., grad.options()))
+  max: where(self > max, grad, at::scalar_tensor(0., grad.options()))
+  result: where(self_p <= max_p, self_t, max_t)
+
+- name: clone(Tensor self, *, MemoryFormat? memory_format=None) -> Tensor
+  self: grad
+  result: auto_linear
+
+- name: _lazy_clone(Tensor self) -> Tensor
+  self: grad
+  result: auto_linear
+
+- name: _to_copy(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool non_blocking=False, MemoryFormat? memory_format=None) -> Tensor
+  self: _to_copy_backward(grad, self.options())
+  result: _to_copy(self_t, dtype, layout, device, pin_memory, non_blocking, memory_format)
+  # The condition is: if dtype is not nullopt, then isDifferentiableType(*dtype)
+  # (If dtype IS nullopt, we rely on the regular check that any input requires grad).
+  output_differentiability: ["!dtype || isDifferentiableType(*dtype)"]
+
+- name: _coalesce(Tensor self) -> Tensor
+  self: grad
+
+- name: complex(Tensor real, Tensor imag) -> Tensor
+  real: at::real(grad)
+  imag: at::imag(grad)
+  result: at::complex(real_t, imag_t)
+
+- name: polar(Tensor abs, Tensor angle) -> Tensor
+  abs, angle: polar_backward(grad, result)
+  result: at::complex(abs_t*angle_p.cos() - angle_t*abs_p*angle_p.sin(), abs_t*angle_p.sin() + angle_t*abs_p*angle_p.cos())
+
+- name: _conj(Tensor(a) self) -> Tensor(a)
+  self: grad.conj()
+  result: self_t.conj()
+
+- name: _neg_view(Tensor(a) self) -> Tensor(a)
+  self: grad.neg()
+  result: self_t._neg_view()
+
+- name: _conj_physical(Tensor self) -> Tensor
+  self: grad.conj_physical()
+  result: self_t.conj_physical()
+
+- name: conj_physical_(Tensor(a!) self) -> Tensor(a!)
+  self: grad.conj_physical()
+  result: self_t.conj_physical_()
+
+- name: copysign.Tensor(Tensor self, Tensor other) -> Tensor
+  self: copysign_tensor_self_backward(grad, self, result)
+  other: zeros_like(other)
+  result: copysign_tensor_self_backward(self_t, self_p, result)
+
+- name: copysign.Scalar(Tensor self, Scalar other) -> Tensor
+  self: copysign_tensor_self_backward(grad, self, result)
+  result: auto_element_wise
+
+- name: cos(Tensor self) -> Tensor
+  self: grad * -self.sin().conj()
+  result: auto_element_wise
+
+- name: cosh(Tensor self) -> Tensor
+  self: grad * self.sinh().conj()
+  result: auto_element_wise
+
+- name: count_nonzero.dim_IntList(Tensor self, int[] dim) -> Tensor
+  output_differentiability: [False]
+
+- name: count_nonzero(Tensor self, int? dim=None) -> Tensor
+  output_differentiability: [False]
+
+- name: linalg_cross(Tensor self, Tensor other, *, int dim=-1) -> Tensor
+  self: at::linalg_cross(other.conj(), grad, dim)
+  other: at::linalg_cross(grad, self.conj(), dim)
+  result: "at::linalg_cross(self_t, other_p, dim) + at::linalg_cross(self_p, other_t, dim)"
+
+- name: logcumsumexp(Tensor self, int dim) -> Tensor
+  self: logcumsumexp_backward(grad, self, result, dim)
+  result: logcumsumexp_jvp(self_p, self_t, dim)
+
+- name: cumprod(Tensor self, int dim, *, ScalarType? dtype=None) -> Tensor
+  self: cumprod_backward(grad.to(self.scalar_type()), self, dim, result)
+  result: "cumprod_jvp(self_t, self_p, result, dim).to(dtype.has_value() ? *dtype : self_p.scalar_type())"
+
+- name: cumsum(Tensor self, int dim, *, ScalarType? dtype=None) -> Tensor
+  self: cumsum_backward(grad.to(self.scalar_type()), dim)
+  result: auto_linear
+
+- name: cummax(Tensor self, int dim) -> (Tensor values, Tensor indices)
+  self: cummaxmin_backward(grad, self, indices, dim)
+  values: self_t.gather(dim, indices)
+
+- name: cummin(Tensor self, int dim) -> (Tensor values, Tensor indices)
+  self: cummaxmin_backward(grad, self, indices, dim)
+  values: self_t.gather(dim, indices)
+
+- name: conv_tbc(Tensor self, Tensor weight, Tensor bias, int pad=0) -> Tensor
+  self, weight, bias: "grad.defined() ? conv_tbc_backward(grad, self, weight, bias, pad) : std::tuple()"
+
+- name: _ctc_loss(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank=0, bool zero_infinity=False) -> (Tensor, Tensor)
+  log_probs: _ctc_loss_backward(grad, log_probs, targets, input_lengths, target_lengths, result0, result1, blank, zero_infinity)
+
+- name: _ctc_loss.Tensor(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank=0, bool zero_infinity=False) -> (Tensor, Tensor)
+  log_probs: _ctc_loss_backward(grad, log_probs, targets, input_lengths, target_lengths, result0, result1, blank, zero_infinity)
+
+- name: deg2rad(Tensor self) -> Tensor
+  self: deg2rad_backward(grad)
+  result: auto_element_wise
+
+- name: _linalg_det(Tensor A) -> (Tensor result, Tensor LU, Tensor pivots)
+  A: linalg_det_backward(grad, result, A, LU, pivots)
+  result: linalg_det_jvp(A_t, result, LU, pivots, A_p.is_contiguous() && !A_p.is_complex())
+  output_differentiability: [True, False, False]
+
+- name: _linalg_slogdet(Tensor A) -> (Tensor sign, Tensor logabsdet, Tensor LU, Tensor pivots)
+  A: slogdet_backward(grad_sign, grad_logabsdet, A, sign, LU, pivots)
+  sign, logabsdet: slogdet_jvp(LU, pivots, A_t, sign, A_p.is_contiguous() && !A_p.is_complex())
+  output_differentiability: [True, True, False, False]
+
+- name: block_diag(Tensor[] tensors) -> Tensor
+  tensors: block_diag_backward(grad, to_args_sizes(tensors), to_args_scalartypes(tensors))
+  result: block_diag_jvp(tensors)
+
+- name: diag_embed(Tensor self, int offset=0, int dim1=-2, int dim2=-1) -> Tensor
+  self: grad.diagonal(offset, dim1, dim2)
+  result: auto_linear
+
+- name: diagonal(Tensor(a) self, int offset=0, int dim1=0, int dim2=1) -> Tensor(a)
+  self: diagonal_backward_symint(grad, self.sym_sizes(), offset, dim1, dim2)
+  result: auto_linear
+
+- name: diagonal_backward(Tensor grad_output, SymInt[] input_sizes, int offset, int dim1, int dim2) -> Tensor
+  grad_output: grad.diagonal(offset, dim1, dim2)
+  result: auto_linear
+
+- name: dist(Tensor self, Tensor other, Scalar p=2) -> Tensor
+  self: norm_backward(grad, self - other, p, result)
+  other: -norm_backward(grad, self - other, p, result)
+  result: norm_jvp(self_p - other_p, self_t - other_t, p, result, {}, false)
+
+# The backward formula is done in this order to improve numerical stability
+# of the higher order derivatives, see https://github.com/pytorch/pytorch/issues/43414
+# Note that we don't use "result" because saving it would be BC-breaking when it is used in an inplace operation later
+- name: div.Tensor(Tensor self, Tensor other) -> Tensor
+  self: div_tensor_self_backward(grad, other, self.scalar_type())
+  other: div_tensor_other_backward(grad, self, other)
+  result: (self_t - other_t * result) / other_p
+
+- name: div.Scalar(Tensor self, Scalar other) -> Tensor
+  self: div_tensor_self_backward(grad, other, self.scalar_type())
+  result: self_t / other
+
+- name: div.Tensor_mode(Tensor self, Tensor other, *, str? rounding_mode) -> Tensor
+  self: div_tensor_self_backward(grad, other, self.scalar_type(), rounding_mode)
+  other: div_tensor_other_backward(grad, self, other, rounding_mode)
+  result: "rounding_mode.has_value() ? result.new_zeros_symint(result.sym_sizes()) : self_t / other_p - other_t * (self_p / other_p) / other_p"
+
+- name: div.Scalar_mode(Tensor self, Scalar other, *, str? rounding_mode) -> Tensor
+  self: div_tensor_self_backward(grad, other, self.scalar_type(), rounding_mode)
+  result: "rounding_mode.has_value() ? result.new_zeros_symint(result.sym_sizes()) : self_t / other"
+
+- name: dot(Tensor self, Tensor tensor) -> Tensor
+  self: grad * tensor.conj()
+  tensor: grad * self.conj()
+  result: at::dot(self_t, tensor_p) + at::dot(self_p, tensor_t)
+
+- name: vdot(Tensor self, Tensor other) -> Tensor
+  self: grad.conj() * other
+  other: grad * self
+  result: at::vdot(self_t, other_p) + at::vdot(self_p, other_t)
+
+- name: _fused_dropout(Tensor self, float p, Generator? generator=None) -> (Tensor, Tensor)
+  self: _fused_dropout_backward(grad, result1, p)
+
+- name: native_dropout(Tensor input, float p, bool? train) -> (Tensor, Tensor)
+  input: "GradMode::is_enabled() ? infinitely_differentiable_native_dropout_backward(grad, result1, (!train.has_value() || !train.value() ? 1 : (p == 1 ? 0.0 : 1.0 / (1.0 - p)))) : native_dropout_backward(grad, result1, (!train.has_value() || !train.value() ? 1 : (p == 1 ? 0.0 : 1.0 / (1.0 - p))))"
+  result0: "(!train.has_value() || train.value()) ? (p == 1 ? 0.0 : 1.0 / (1.0 - p)) * input_t * result1 : input_t"
+
+- name: native_dropout_backward(Tensor grad_output, Tensor mask, float scale) -> Tensor
+  grad_output: "native_dropout_double_backward(grad, grad_output, mask, scale)"
+  mask: 'not_implemented("native_dropout_backward: mask")'
+
+- name: eq_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  self: zeros_like(self)
+  result: self_t.zero_()
+
+- name: eq_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  self: zeros_like(self)
+  other: zeros_like(other)
+  result: self_t.zero_()
+
+- name: erf(Tensor self) -> Tensor
+  self: 2.0 / sqrt(M_PI) * exp(-(self.pow(2))) * grad
+  result: auto_element_wise
+
+- name: erfc(Tensor self) -> Tensor
+  self: -2.0 / sqrt(M_PI) * exp(-(self.pow(2))) * grad
+  result: auto_element_wise
+
+- name: special_erfcx(Tensor self) -> Tensor
+  self: (2.0 * self * result - 2.0 / sqrt(M_PI)) * grad
+  result: auto_element_wise
+
+- name: erfinv(Tensor self) -> Tensor
+  self: 0.5 * sqrt(M_PI) * exp(self.erfinv().pow(2)) * grad
+  result: auto_element_wise
+
+- name: exp(Tensor self) -> Tensor
+  self: grad * result.conj()
+  result: auto_element_wise
+
+- name: exp2(Tensor self) -> Tensor
+  self: grad * result.conj() * M_LN2
+  result: auto_element_wise
+
+- name: expm1(Tensor self) -> Tensor
+  self: grad * (result.conj() + 1)
+  result: auto_element_wise
+
+# TODO: this derivative is not SymInt safe, need sum_to support
+- name: expand(Tensor(a) self, SymInt[] size, *, bool implicit=False) -> Tensor(a)
+  self: at::sum_to(grad, self.sym_sizes())
+  result: auto_linear
+
+- name: exponential_(Tensor(a!) self, float lambd=1, *, Generator? generator=None) -> Tensor(a!)
+  self: zeros_like(grad)
+  result: self_t.zero_()
+
+- name: fake_quantize_per_tensor_affine_cachemask(Tensor self, float scale, int zero_point, int quant_min, int quant_max) -> (Tensor output, Tensor mask)
+  self: fake_quantize_per_tensor_affine_cachemask_backward(grad, mask)
+
+- name: _fake_quantize_per_tensor_affine_cachemask_tensor_qparams(Tensor self, Tensor scale, Tensor zero_point, Tensor fake_quant_enabled, int quant_min, int quant_max) -> (Tensor output, Tensor mask)
+  self: fake_quantize_per_tensor_affine_cachemask_backward(grad, mask)
+
+- name: _fake_quantize_learnable_per_tensor_affine(Tensor self, Tensor scale, Tensor zero_point, int quant_min, int quant_max, float grad_factor=1.0) -> Tensor
+  self, scale, zero_point: "grad.defined() ? _fake_quantize_learnable_per_tensor_affine_backward(grad, self, scale, zero_point, quant_min, quant_max, grad_factor) : std::tuple()"
+
+- name: fake_quantize_per_channel_affine_cachemask(Tensor self, Tensor scale, Tensor zero_point, int axis, int quant_min, int quant_max) -> (Tensor output, Tensor mask)
+  self: fake_quantize_per_channel_affine_cachemask_backward(grad, mask)
+
+- name: _fake_quantize_learnable_per_channel_affine(Tensor self, Tensor scale, Tensor zero_point, int axis, int quant_min, int quant_max, float grad_factor=1.0) -> Tensor
+  self, scale, zero_point: "grad.defined() ? _fake_quantize_learnable_per_channel_affine_backward(grad, self, scale, zero_point, axis, quant_min, quant_max, grad_factor) : std::tuple()"
+
+- name: _fused_moving_avg_obs_fq_helper(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor output, Tensor mask)
+  self: fake_quantize_per_tensor_affine_cachemask_backward(grad, mask)
+
+- name: fill.Scalar(Tensor self, Scalar value) -> Tensor
+  self: zeros_like(grad)
+  result: at::fill(self_t, 0)
+
+- name: fill.Tensor(Tensor self, Tensor value) -> Tensor
+  self: zeros_like(grad)
+  value: grad.sum()
+  result: at::fill(self_t, value_t)
+
+- name: fill_.Scalar(Tensor(a!) self, Scalar value) -> Tensor(a!)
+  self: zeros_like(grad)
+  result: self_t.fill_(0)
+
+- name: fill_.Tensor(Tensor(a!) self, Tensor value) -> Tensor(a!)
+  self: zeros_like(grad)
+  value: grad.sum()
+  result: self_t.fill_(value_t)
+
+- name: floor(Tensor self) -> Tensor
+  self: zeros_like(grad)
+  result: auto_element_wise
+
+- name: fmod.Scalar(Tensor self, Scalar other) -> Tensor
+  self: grad
+  result: auto_element_wise
+
+- name: fmod.Tensor(Tensor self, Tensor other) -> Tensor
+  self: grad
+  other: -grad * self.div(other, /*rounding_mode=*/"trunc")
+  result: self_t - other_t * self_p.div(other_p, /*rounding_mode=*/"trunc")
+
+- name: frac(Tensor self) -> Tensor
+  self: grad
+  result: self_t
+
+- name: frexp.Tensor(Tensor self) -> (Tensor mantissa, Tensor exponent)
+  self: grad / exponent.exp2()
+  mantissa: self_t / exponent.exp2()
+
+- name: gather(Tensor self, int dim, Tensor index, *, bool sparse_grad=False) -> Tensor
+  self: gather_backward(grad, self, dim, index, sparse_grad)
+  index: non_differentiable
+  result: auto_linear
+
+- name: ge_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  self: zeros_like(self)
+  result: self_t.zero_()
+
+- name: ge_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  self: zeros_like(self)
+  other: zeros_like(other)
+  result: self_t.zero_()
+
+- name: geometric_(Tensor(a!) self, float p, *, Generator? generator=None) -> Tensor(a!)
+  self: zeros_like(grad)
+  result: self_t.zero_()
+
+- name: geqrf(Tensor self) -> (Tensor a, Tensor tau)
+  self: not_implemented("geqrf")
+
+- name: indices(Tensor(a) self) -> Tensor(a)
+  output_differentiability: [False]
+
+- name: _indices(Tensor(a) self) -> Tensor(a)
+  output_differentiability: [False]
+
+- name: crow_indices(Tensor(a) self) -> Tensor(a)
+  output_differentiability: [False]
+
+- name: col_indices(Tensor(a) self) -> Tensor(a)
+  output_differentiability: [False]
+
+- name: ccol_indices(Tensor(a) self) -> Tensor(a)
+  output_differentiability: [False]
+
+- name: row_indices(Tensor(a) self) -> Tensor(a)
+  output_differentiability: [False]
+
+- name: grid_sampler_2d(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor
+  input, grid: "grad.defined() ? grid_sampler_2d_backward(grad, input, grid, interpolation_mode, padding_mode, align_corners, grad_input_mask) : std::tuple()"
+
+- name: grid_sampler_3d(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor
+  input, grid: "grad.defined() ? grid_sampler_3d_backward(grad, input, grid, interpolation_mode, padding_mode, align_corners, grad_input_mask) : std::tuple()"
+
+# See NOTE [ grid_sample CPU fallback ]
+- name: _grid_sampler_2d_cpu_fallback(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor
+  input, grid: "grad.defined() ? _grid_sampler_2d_cpu_fallback_backward(grad, input, grid, interpolation_mode, padding_mode, align_corners) : std::tuple()"
+
+- name: gt_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  self: zeros_like(self)
+  result: self_t.zero_()
+
+- name: gt_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  self: zeros_like(self)
+  other: zeros_like(other)
+  result: self_t.zero_()
+
+- name: hardsigmoid(Tensor self) -> Tensor
+  self: hardsigmoid_backward(grad, self)
+  result: auto_element_wise
+
+- name: histc(Tensor self, int bins=100, Scalar min=0, Scalar max=0) -> Tensor
+  output_differentiability: [False]
+
+- name: hardswish(Tensor self) -> Tensor
+  self: hardswish_backward(grad, self)
+  result: auto_element_wise
+
+- name: hardswish_backward(Tensor grad_output, Tensor self) -> Tensor
+  grad_output: hardswish_backward(grad, self)
+  self: at::where(at::logical_and(-3.0 < self, self < 3.0), grad * grad_output / 3.0, at::zeros({}, self.options()))
+  result: "hardswish_backward(grad_output_t, self_p)
+         + at::where(at::logical_and(-3.0 < self_p, self_p < 3.0), self_t * grad_output_p / 3.0, at::zeros({}, self_p.options()))"
+
+- name: hypot(Tensor self, Tensor other) -> Tensor
+  self: grad * self / result
+  other: grad * other / result
+  result: self_t * self_p / result + other_t * other_p / result
+
+- name: i0(Tensor self) -> Tensor
+  self: grad * at::special_i1(self)
+  result: auto_element_wise
+
+- name: special_i0e(Tensor self) -> Tensor
+  self: grad * (at::special_i1e(self) - self.sgn() * result)
+  result: auto_element_wise
+
+- name: special_i1(Tensor self) -> Tensor
+  self: i1_backward(grad, self, result)
+  result: auto_element_wise
+
+- name: special_i1e(Tensor self) -> Tensor
+  self: i1e_backward(grad, self, result)
+  result: auto_element_wise
+
+- name: igamma(Tensor self, Tensor other) -> Tensor
+  self: 'not_implemented("igamma: input")'
+  other: grad * exp((self - 1) * log(other) - other - lgamma(self))
+
+- name: igammac(Tensor self, Tensor other) -> Tensor
+  self: 'not_implemented("igammac: input")'
+  other: -grad * exp((self - 1) * log(other) - other - lgamma(self))
+
+- name: index.Tensor(Tensor self, Tensor?[] indices) -> Tensor
+  self: index_backward(grad.new_zeros_symint(self.sym_sizes(), self.options()), indices, grad)
+  result: auto_linear
+
+- name: _unsafe_index.Tensor(Tensor self, Tensor?[] indices) -> Tensor
+  self: at::_unsafe_index_put(grad.new_zeros_symint(self.sym_sizes(), self.options()), indices, grad, true)
+  result: auto_linear
+
+- name: _unsafe_masked_index(Tensor self, Tensor mask, Tensor?[] indices, Scalar fill) -> Tensor
+  self: at::_unsafe_masked_index_put_accumulate(grad.new_zeros_symint(self.sym_sizes(), self.options()), mask, indices, grad)
+  mask: non_differentiable
+  result: _unsafe_masked_index(self_t, mask, indices, 0)
+
+- name: _unsafe_masked_index_put_accumulate(Tensor self, Tensor mask, Tensor?[] indices, Tensor values) -> Tensor
+  self: grad
+  mask: non_differentiable
+  values: at::_unsafe_masked_index(grad, mask, indices, 0)
+  result: at::_unsafe_masked_index_put_accumulate(self_t, mask, indices, values_t)
+
+- name: index_add(Tensor self, int dim, Tensor index, Tensor source, *, Scalar alpha=1) -> Tensor
+  self: grad
+  # The case source.dim() == 0  is necessary to support scalar tensors of the form
+  # source.dim() == 0 and index.dim() == 1 and index.size() == (1,),
+  # This is because source is not broadcastable to index, as source.dim() < index.dim()
+  source: "maybe_multiply(source.dim() > 0 ? grad.index_select(dim, index).expand_as(source) : grad.index_select(dim, index.squeeze(0)), alpha)"
+  index: non_differentiable
+  result: at::index_add(self_t, dim, index, maybe_multiply(source_t, alpha))
+
+- name: index_reduce(Tensor self, int dim, Tensor index, Tensor source, str reduce, *, bool include_self=True) -> Tensor
+  self, source: index_reduce_backward(grad, self, dim, index, source, reduce, include_self, result)
+  index: non_differentiable
+
+- name: index_copy(Tensor self, int dim, Tensor index, Tensor source) -> Tensor
+  self: grad.index_fill(dim, index, 0)
+  # The case source.dim() == 0 is necessary to support scalar tensors of the form
+  # source.dim() == 0 and index.dim() == 1 and index.size() == (1,),
+  # This is because source is not broadcastable to index, as source.dim() < index.dim()
+  source: "source.dim() > 0 ? grad.index_select(dim, index).expand_as(source) : grad.index_select(dim, index.squeeze(0))"
+  index: non_differentiable
+  result: self_t.index_copy(dim, index, source_t)
+
+- name: index_fill.int_Scalar(Tensor self, int dim, Tensor index, Scalar value) -> Tensor
+  self: grad.index_fill(dim, index, 0)
+  index: non_differentiable
+  result: self_t.index_fill(dim, index, 0)
+
+- name: index_fill.int_Tensor(Tensor self, int dim, Tensor index, Tensor value) -> Tensor
+  self: grad.index_fill(dim, index, 0)
+  value: grad.index_select(dim, std::get<0>(at::_unique(index, /*sorted=*/false))).sum()
+  index: non_differentiable
+  result: self_t.index_fill(dim, index, value_t)
+
+- name: index_put(Tensor self, Tensor?[] indices, Tensor values, bool accumulate=False) -> Tensor
+  self: "accumulate ? grad : grad.index_put(indices, zeros_like(values), false)"
+  values: grad.index(indices)
+  result: self_t.index_put(indices, values_t, accumulate)
+
+- name: _unsafe_index_put(Tensor self, Tensor?[] indices, Tensor values, bool accumulate=False) -> Tensor
+  self: "accumulate ? grad : at::_unsafe_index_put(grad, indices, zeros_like(values), false)"
+  values: at::_unsafe_index(grad, indices)
+  result: at::_unsafe_index_put(self_t, indices, values_t, accumulate)
+
+- name: _index_put_impl_(Tensor(a!) self, Tensor?[] indices, Tensor values, bool accumulate=False, bool unsafe=False) -> Tensor(a!)
+  self: "accumulate ? grad : grad.index_put(indices, zeros_like(values), false)"
+  values: grad.index(indices)
+  result: at::_index_put_impl_(self_t, indices, values_t, accumulate, unsafe)
+
+- name: index_select(Tensor self, int dim, Tensor index) -> Tensor
+  self: index_select_backward_symint(grad, self.sym_sizes(), dim, index)
+  index: non_differentiable
+  result: auto_linear
+
+- name: linalg_inv_ex(Tensor A, *, bool check_errors=False) -> (Tensor inverse, Tensor info)
+  A: -at::matmul(inverse.mH(), at::matmul(grad, inverse.mH()))
+  inverse: -at::matmul(at::matmul(inverse, A_t), inverse)
+  output_differentiability: [True, False]
+
+- name: linalg_pinv.atol_rtol_tensor(Tensor self, *, Tensor? atol=None, Tensor? rtol=None, bool hermitian=False) -> Tensor
+  self: pinv_backward(grad, result, self)
+  result: pinv_jvp(self_p, result, self_t)
+
+- name: isnan(Tensor self) -> Tensor
+  self: non_differentiable
+
+- name: kthvalue(Tensor self, SymInt k, int dim=-1, bool keepdim=False) -> (Tensor values, Tensor indices)
+  self: value_selecting_reduction_backward_symint(grad, dim, indices, self.sym_sizes(), keepdim)
+  values: gather_with_keepdimed_indices(self_t, dim, indices, keepdim)
+
+- name: le_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  self: zeros_like(self)
+  result: self_t.zero_()
+
+- name: le_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  self: zeros_like(self)
+  other: zeros_like(other)
+  result: self_t.zero_()
+
+- name: lerp.Scalar(Tensor self, Tensor end, Scalar weight) -> Tensor
+  self: "weight.isComplex() ? grad * (1 - weight.conj().toComplexDouble()) : grad * (1 - weight.toDouble())"
+  end: grad * weight.conj()
+  result: at::lerp(self_t, end_t, weight)
+
+- name: lerp.Tensor(Tensor self, Tensor end, Tensor weight) -> Tensor
+  self: grad * (1 - weight).conj()
+  end: grad * weight.conj()
+  weight: grad * (end - self).conj()
+  result: at::lerp(self_t, end_t, weight_p) + weight_t * (end_p - self_p)
+
+- name: lgamma(Tensor self) -> Tensor
+  self: grad * digamma(self)
+  result: auto_element_wise
+
+- name: digamma(Tensor self) -> Tensor
+  self: grad * polygamma(1, self)
+  result: auto_element_wise
+
+- name: polygamma(int n, Tensor self) -> Tensor
+  self: grad * polygamma(n + 1, self)
+  result: auto_element_wise
+
+- name: polygamma_(Tensor(a!) self, int n) -> Tensor(a!)
+  self: grad * polygamma(n + 1, self)
+  result: self_t.mul_(polygamma(n + 1, original_self_p))
+
+- name: log(Tensor self) -> Tensor
+  self: grad.div(self.conj())
+  result: auto_element_wise
+
+- name: log10(Tensor self) -> Tensor
+  self: grad / (self.conj() * 2.3025850929940456)
+  result: auto_element_wise
+
+- name: log1p(Tensor self) -> Tensor
+  self: log1p_backward(grad, self)
+  result: auto_element_wise
+
+- name: log2(Tensor self) -> Tensor
+  self: grad / (self.conj() * 0.6931471805599453)
+  result: auto_element_wise
+
+- name: logaddexp(Tensor self, Tensor other) -> Tensor
+  self: grad / (1 + exp(other - self)).conj()
+  other: grad / (1 + exp(self - other)).conj()
+  result: self_t / (1 + exp(other_p - self_p)) + other_t / (1 + exp(self_p - other_p))
+
+- name: logaddexp2(Tensor self, Tensor other) -> Tensor
+  self: grad / (1 + pow(2, other - self))
+  other: grad / (1 + pow(2, self - other))
+  result: self_t / (1 + pow(2, other_p - self_p)) + other_t / (1 + pow(2, self_p - other_p))
+
+# Note [Gradient formula for xlogy at x = 0, y <= 0]
+# x * log(y) is not defined at y <= 0, so we cannot even talk about differentiability
+# Now, xlogy(0, y) = 0 by definition.
+# This does not make it differentiable as it's not defined in a neighbourhood of a point
+# (0, y) when y <= 0.
+# Now, when a function is non-differentiable, sometimes we return "a relatively sensible value"
+# In this case, as per the discussion in https://github.com/pytorch/pytorch/issues/80770, we choose
+# this value to be zero, which is the directional derivative along the line {x = 0}.
+- name: xlogy.Tensor(Tensor self, Tensor other) -> Tensor
+  self: at::xlogy(grad, other).masked_fill((self == 0.) & (other <= 0.), 0.)
+  other: grad * self / other
+  result: at::xlogy(self_t, other_p).masked_fill((self_p == 0.) & (other_p <= 0.), 0.) + other_t * self_p / other_p
+
+- name: xlogy.Scalar_Self(Scalar self, Tensor other) -> Tensor
+  other: grad * self / other
+  result: auto_element_wise
+
+- name: xlogy.Scalar_Other(Tensor self, Scalar other) -> Tensor
+  self: "other.toDouble() > 0.
+          ? at::xlogy(grad,  other)
+          : at::xlogy(grad,  other).masked_fill(self == 0., 0.)"
+  result: auto_element_wise
+
+# See Note [Gradient formula for xlogy at x = 0, y <= 0]
+# Same here but with y <= -1
+- name: special_xlog1py(Tensor self, Tensor other) -> Tensor
+  self: at::special_xlog1py(grad,  other).masked_fill((self == 0.) & (other <= -1.), 0.)
+  other: grad * self / (other + 1)
+  result: at::special_xlog1py(self_t,  other_p).masked_fill((self_p == 0.) & (other_p <= -1.), 0.) + other_t * self_p / (other_p + 1)
+
+- name: special_xlog1py.self_scalar(Scalar self, Tensor other) -> Tensor
+  other: grad * self / (other + 1)
+  result: auto_element_wise
+
+- name: special_xlog1py.other_scalar(Tensor self, Scalar other) -> Tensor
+  self: "other.toDouble() > -1.
+          ? at::special_xlog1py(grad,  other)
+          : at::special_xlog1py(grad,  other).masked_fill(self == 0., 0.)"
+  result: auto_element_wise
+
+- name: special_zeta(Tensor self, Tensor other) -> Tensor
+  self: not_implemented("zeta")
+  other:  grad * -self * special_zeta(self + 1., other)
+
+- name: special_zeta.self_scalar(Scalar self, Tensor other) -> Tensor
+  other:  grad * -self * special_zeta(self.toDouble() + 1., other)
+
+- name: special_zeta.other_scalar(Tensor self, Scalar other) -> Tensor
+  self: not_implemented("zeta")
+
+- name: log_normal_(Tensor(a!) self, float mean=1, float std=2, *, Generator? generator=None) -> Tensor(a!)
+  self: zeros_like(grad)
+  result: self_t.zero_()
+
+- name: logsumexp(Tensor self, int[1] dim, bool keepdim=False) -> Tensor
+  self: logsumexp_backward(grad, self, result, dim, keepdim)
+  result: logsumexp_jvp(self_p, self_t, dim, keepdim)
+
+- name: linalg_lstsq(Tensor self, Tensor b, float? rcond=None, *, str? driver=None) -> (Tensor solution, Tensor residuals, Tensor rank, Tensor singular_values)
+  self, b: linalg_lstsq_backward(grads[0], grads[1], self, b, solution, grad_input_mask)
+  solution: linalg_lstsq_solution_jvp(self_p, b_p, self_t, b_t)
+  residuals: linalg_lstsq_residuals_jvp(self_p, b_p, self_t, b_t, solution, residuals)
+  output_differentiability: [True, True, False, False]
+
+- name: lt_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  self: zeros_like(self)
+  result: self_t.zero_()
+
+- name: lt_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  self: zeros_like(self)
+  other: zeros_like(other)
+  result: self_t.zero_()
+
+- name: linalg_lu_factor_ex(Tensor A, *, bool pivot=True, bool check_errors=False) -> (Tensor LU, Tensor pivots, Tensor info)
+  A: lu_factor_ex_backward(grad, LU, pivots, pivot)
+  LU: lu_factor_ex_jvp(A_t, LU, pivots, pivot)
+  output_differentiability: [True, False, False]
+
+- name: linalg_lu_factor(Tensor A, *, bool pivot=True) -> (Tensor LU, Tensor pivots)
+  A: lu_factor_ex_backward(grad, LU, pivots, pivot)
+  LU: lu_factor_ex_jvp(A_t, LU, pivots, pivot)
+  output_differentiability: [True, False]
+
+- name: linalg_lu(Tensor A, *, bool pivot=True) -> (Tensor P, Tensor L, Tensor U)
+  A: linalg_lu_backward(grad_L, grad_U, P, L, U, pivot)
+  L: std::get<0>(linalg_lu_jvp(A_t, P, L, U, pivot))
+  U: std::get<1>(linalg_lu_jvp(A_t, P, L, U, pivot))
+  output_differentiability: [False, True, True]
+
+- name: linalg_lu_solve(Tensor LU, Tensor pivots, Tensor B, *, bool left=True, bool adjoint=False) -> Tensor
+  LU: linalg_lu_solve_LU(grad, LU, pivots, result, left, adjoint)
+  B: "at::linalg_lu_solve(LU, pivots, grad, left, !adjoint)"
+  result: linalg_lu_solve_jvp(result, LU_p, pivots, LU_t, B_t, left, adjoint)
+
+- name: lu_unpack(Tensor LU_data, Tensor LU_pivots, bool unpack_data=True, bool unpack_pivots=True) -> (Tensor P, Tensor L, Tensor U)
+  LU_data: lu_unpack_backward(grad_L, grad_U, LU_data.sym_size(-2), LU_data.sym_size(-1))
+  LU_pivots: non_differentiable
+  L: "LU_data_t.sym_size(-2) >= LU_data_t.sym_size(-1) ? LU_data_t.tril(-1) : LU_data_t.narrow_symint(-1, 0, LU_data_t.sym_size(-2)).tril(-1)"
+  U: "LU_data_t.sym_size(-1) >= LU_data_t.sym_size(-2) ? LU_data_t.triu() : LU_data_t.narrow_symint(-2, 0, LU_data_t.sym_size(-1)).triu()"
+  output_differentiability: [False, True, True]
+
+- name: masked_fill.Scalar(Tensor self, Tensor mask, Scalar value) -> Tensor
+  self: grad.masked_fill(mask, 0)
+  mask: non_differentiable
+  result: self_t.masked_fill(mask, 0)
+
+- name: masked_fill.Tensor(Tensor self, Tensor mask, Tensor value) -> Tensor
+  self: grad.masked_fill(mask, 0)
+  value: masked_fill_backward(grad, mask)
+  mask: non_differentiable
+  result: self_t.masked_fill(mask, value_t)
+
+- name: masked_scatter(Tensor self, Tensor mask, Tensor source) -> Tensor
+  self: grad.masked_fill(mask, 0)
+  source: masked_scatter_backward_symint(grad, mask, source.sym_sizes())
+  mask: non_differentiable
+  result: self_t.masked_scatter(mask, source_t)
+
+- name: masked_scatter_backward(Tensor grad_output, Tensor mask, SymInt[] sizes) -> Tensor
+  grad_output: zeros_like(grad_output).masked_scatter(mask, grad)
+  mask: non_differentiable
+  result: masked_scatter_backward(grad_output_t, mask, grad_output_t.sizes())
+
+- name: masked_select(Tensor self, Tensor mask) -> Tensor
+  self: masked_select_backward(grad, self, mask)
+  mask: non_differentiable
+  result: auto_linear
+
+- name: linalg_matrix_exp(Tensor self) -> Tensor
+  self: linalg_matrix_exp_differential(self, grad, /*adjoint*/ true)
+  result: linalg_matrix_exp_differential(self_p, self_t, /*adjoint*/ false)
+
+- name: max.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+  self: value_selecting_reduction_backward_symint(grad, dim, indices, self.sym_sizes(), keepdim)
+  values: gather_with_keepdimed_indices(self_t, dim, indices, keepdim)
+
+- name: max(Tensor self) -> Tensor
+  self: evenly_distribute_backward(grad, self, result)
+  result: evenly_read_jvp(self_t, self_p, result)
+
+- name: maximum(Tensor self, Tensor other) -> Tensor
+  self: at::where(self == other, grad / 2, grad).masked_fill_(self < other, 0)
+  other: at::where(self == other, grad / 2, grad).masked_fill_(self > other, 0)
+  result: other_t + at::where(self_p == other_p, at::scalar_tensor(0.5, result.options()), (self_p > other_p).to(result.scalar_type())) * (self_t - other_t)
+
+- name: fmax(Tensor self, Tensor other) -> Tensor
+  self: grad.masked_fill((self >= other).logical_or_(other.isnan()).logical_not_(), 0)
+  other: grad.masked_fill((self >= other).logical_or_(other.isnan()), 0)
+  result: other_t + (self_p > other_p).logical_or_(other_p.isnan()) * (self_t - other_t)
+
+- name: mean(Tensor self, *, ScalarType? dtype=None) -> Tensor
+  dispatch:
+    Default:
+      self: grad.expand_symint(self.sym_sizes()) / self.sym_numel()
+      result: auto_linear
+    AutogradNestedTensor:
+      # TODO: replace this with grad.expand_as(self) / self.sym_numel() when that is supported
+      self: (ones_like(self) * grad) / self.sym_numel()
+      result: auto_linear
+
+- name: mean.dim(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+  self: mean_backward(grad, self.sym_sizes(), dim, self.sym_numel(), keepdim)
+  result: auto_linear
+
+- name: median(Tensor self) -> Tensor
+  self: evenly_distribute_backward(grad, self, result)
+  result: evenly_read_jvp(self_t, self_p, result)
+
+- name: nanmedian(Tensor self) -> Tensor
+  self: evenly_distribute_backward(grad, self, result)
+  result: evenly_read_jvp(self_t, self_p, result)
+
+# This is in theory incorrect in the following case:
+#   sorted list: [..., a, b, b, ..., b, b, c, ...] with median = b and the value
+#                            |                     at middle position of the
+#                            |                     list between two `b`s. E.g.,
+#                            |
+#                            ^the middle position
+# The gradient exists and is essentially 0 in this case.
+#
+# In case where the middle position is at the boundary of `b` range, e.g.,
+#   sorted list: [..., a, b, b, ..., b, b, c, ...]
+#                                       |
+#                                       ^the middle position
+# The backward implementation is correct in the sense that it returns the
+# subgradient on one side.
+- name: median.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+  self: value_selecting_reduction_backward_symint(grad, dim, indices, self.sym_sizes(), keepdim)
+  values: gather_with_keepdimed_indices(self_t, dim, indices, keepdim)
+
+- name: nanmedian.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+  self: value_selecting_reduction_backward_symint(grad, dim, indices, self.sym_sizes(), keepdim)
+  values: gather_with_keepdimed_indices(self_t, dim, indices, keepdim)
+
+- name: min.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+  self: value_selecting_reduction_backward_symint(grad, dim, indices, self.sym_sizes(), keepdim)
+  values: gather_with_keepdimed_indices(self_t, dim, indices, keepdim)
+
+- name: min(Tensor self) -> Tensor
+  self: evenly_distribute_backward(grad, self, result)
+  result: evenly_read_jvp(self_t, self_p, result)
+
+- name: minimum(Tensor self, Tensor other) -> Tensor
+  self: at::where(self == other, grad / 2, grad).masked_fill_(self > other, 0)
+  other: at::where(self == other, grad / 2, grad).masked_fill_(self < other, 0)
+  result: other_t + at::where(self_p == other_p, at::scalar_tensor(0.5, result.options()), (self_p < other_p).to(result.scalar_type())) * (self_t - other_t)
+
+- name: fmin(Tensor self, Tensor other) -> Tensor
+  self: grad.masked_fill((self <= other).logical_or_(other.isnan()).logical_not_(), 0)
+  other: grad.masked_fill((self <= other).logical_or_(other.isnan()), 0)
+  result: other_t + (self_p <= other_p).logical_or_(other_p.isnan()) * (self_t - other_t)
+
+- name: amax(Tensor self, int[1] dim=[], bool keepdim=False) -> Tensor
+  self: scale_grad_by_count(restore_reduced_dims(grad, dim, keepdim), restore_reduced_dims(result, dim, keepdim) == self, dim)
+  result: amaxamin_jvp(self_p, self_t, result, dim, keepdim)
+
+- name: amin(Tensor self, int[1] dim=[], bool keepdim=False) -> Tensor
+  self: scale_grad_by_count(restore_reduced_dims(grad, dim, keepdim), restore_reduced_dims(result, dim, keepdim) == self, dim)
+  result: amaxamin_jvp(self_p, self_t, result, dim, keepdim)
+
+- name: mm(Tensor self, Tensor mat2) -> Tensor
+  self: mm_mat1_backward(grad, mat2, self.sym_sizes(), self.sym_strides(), self.layout(), 1)
+  mat2: mm_mat2_backward(grad, self, mat2.sym_sizes(), mat2.sym_strides(), mat2.layout(), 1)
+  result: at::mm(self_t, mat2_p) + at::mm(self_p, mat2_t)
+
+- name: _grouped_mm(Tensor self, Tensor mat2, Tensor? offs=None, Tensor? bias=None, ScalarType? out_dtype=None) -> Tensor
+  self: _grouped_mm_mat1_backward(grad, mat2, self.sym_sizes(), self.sym_strides(), self.layout(), offs, 1)
+  mat2: _grouped_mm_mat2_backward(grad, self, mat2.sym_sizes(), mat2.sym_strides(), mat2.layout(), offs, 1)
+
+- name: mode(Tensor self, int dim=-1, bool keepdim=False) -> (Tensor values, Tensor indices)
+  self: value_selecting_reduction_backward_symint(grad, dim, indices, self.sym_sizes(), keepdim)
+  values: gather_with_keepdimed_indices(self_t, dim, indices, keepdim)
+
+- name: mul.Tensor(Tensor self, Tensor other) -> Tensor
+  self: mul_tensor_backward(grad, other, self.scalar_type())
+  other: mul_tensor_backward(grad, self, other.scalar_type())
+  result: other_t * self_p + self_t * other_p
+
+- name: mul.Scalar(Tensor self, Scalar other) -> Tensor
+  self: mul_tensor_backward(grad, other, self.scalar_type())
+  result: self_t * other
+
+- name: mv(Tensor self, Tensor vec) -> Tensor
+  self: grad.ger(vec.conj())
+  vec: self.conj().t().mv(grad)
+  result: mv(self_t, vec_p) + mv(self_p, vec_t)
+
+- name: mvlgamma(Tensor self, int p) -> Tensor
+  self: mvlgamma_backward(grad, self, p)
+  result: auto_element_wise
+
+- name: nan_to_num(Tensor self, float? nan=None, float? posinf=None, float? neginf=None) -> Tensor
+  self: grad * at::isfinite(self)
+  result: auto_element_wise
+
+- name: native_batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor)
+  input, weight, bias: "grad.defined() ? native_batch_norm_backward(grad, input, weight, running_mean, running_var, result1, result2, training, eps, grad_input_mask) : std::tuple()"
+  result0: batch_norm_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, running_mean, running_var, result1, result2, training, eps)
+
+- name: _native_batch_norm_legit(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor)
+  input, weight, bias: "grad.defined() ? native_batch_norm_backward(grad, input, weight, running_mean, running_var, result1, result2, training, eps, grad_input_mask) : std::tuple()"
+  result0: batch_norm_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, running_mean, running_var, result1, result2, training, eps)
+
+- name: _native_batch_norm_legit_no_training(Tensor input, Tensor? weight, Tensor? bias, Tensor running_mean, Tensor running_var, float momentum, float eps) -> (Tensor, Tensor, Tensor)
+  input, weight, bias: "grad.defined() ? native_batch_norm_backward(grad, input, weight, running_mean, running_var, result1, result2, /*training=*/false, eps, grad_input_mask) : std::tuple()"
+  result0: batch_norm_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, running_mean, running_var, result1, result2, /*training=*/false, eps)
+
+- name: _native_batch_norm_legit.no_stats(Tensor input, Tensor? weight, Tensor? bias, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor)
+  input, weight, bias: "grad.defined() ? native_batch_norm_backward(grad, input, weight, Tensor(), Tensor(), result1, result2, training, eps, grad_input_mask) : std::tuple()"
+  result0: batch_norm_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, Tensor(), Tensor(), result1, result2, training, eps)
+
+- name: native_batch_norm_backward(Tensor grad_out, Tensor input, Tensor? weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_invstd, bool train, float eps, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+  input, weight, grad_out: batchnorm_double_backward(input, weight, grads[0], grads[1], grads[2], grad_out, running_mean, running_var, train, eps, save_mean, save_invstd, grad_input_mask)
+  save_mean: not_implemented("native_batch_norm_backward save_mean")
+  save_invstd: not_implemented("native_batch_norm_backward save_invstd")
+
+- name: native_layer_norm(Tensor input, SymInt[] normalized_shape, Tensor? weight, Tensor? bias, float eps) -> (Tensor, Tensor, Tensor)
+  input, weight, bias: "grad.defined() ? native_layer_norm_backward_symint(grad, input, normalized_shape, result1, result2, weight, bias, grad_input_mask) : std::tuple()"
+  result0: layer_norm_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, result1, result2, normalized_shape)
+
+- name: native_layer_norm_backward(Tensor grad_out, Tensor input, SymInt[] normalized_shape, Tensor mean, Tensor rstd, Tensor? weight, Tensor? bias, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+  input, weight, grad_out: layer_norm_double_backward(input, weight, grads[0], grads[1], grads[2], grad_out, mean, rstd, normalized_shape, grad_input_mask)
+  bias: Tensor()
+  mean: not_implemented("native_layer_norm_backward mean")
+  rstd: not_implemented("native_layer_norm_backward rstd")
+
+- name: _fused_rms_norm(Tensor input, int[] normalized_shape, Tensor? weight, float? eps) -> (Tensor, Tensor)
+  input, weight: "GradMode::is_enabled() || grads[1].defined() ? infinitely_differentiable_native_rms_norm_backward(grads[0], grads[1], input, normalized_shape, result1, weight, grad_input_mask) : (grads[0].defined() ? _fused_rms_norm_backward(grads[0], input, normalized_shape, result1, weight, grad_input_mask) : std::tuple())"
+  result0: rms_norm_jvp(input_p, input_t, weight_p, weight_t, result1, normalized_shape)
+  result1: rms_norm_rstd_jvp(input_p, input_t, result1, normalized_shape)
+
+- name: native_group_norm(Tensor input, Tensor? weight, Tensor? bias, SymInt N, SymInt C, SymInt HxW, int group, float eps) -> (Tensor, Tensor, Tensor)
+  input, weight, bias: "GradMode::is_enabled() || grads[1].defined() || grads[2].defined() ? infinitely_differentiable_native_group_norm_backward(grads[0], grads[1], grads[2], input, result1, result2, weight, N, C, HxW, group, eps, grad_input_mask) : (grads[0].defined() ? native_group_norm_backward_symint(grads[0].device().is_xpu() ? grads[0] : grads[0].contiguous(grads[0].device().is_cpu() ? input.suggest_memory_format() : c10::MemoryFormat::Contiguous), input.device().is_xpu() ? input : input.contiguous(input.device().is_cpu() ? input.suggest_memory_format() : c10::MemoryFormat::Contiguous), result1, result2, weight, N, C, HxW, group, grad_input_mask) : std::tuple())"
+  result0: group_norm_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, result1, result2, group)
+  result1: group_norm_mean_jvp(input_t, result1, group)
+  result2: group_norm_invstd_jvp(input_p, input_t, result1, result2, group)
+
+- name: ne_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+  self: zeros_like(self)
+  result: self_t.zero_()
+
+- name: ne_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+  self: zeros_like(self)
+  other: zeros_like(other)
+  result: self_t.zero_()
+
+- name: neg(Tensor self) -> Tensor
+  self: grad.neg()
+  result: auto_element_wise
+
+- name: _batch_norm_with_update(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, float momentum, float eps) -> (Tensor, Tensor, Tensor, Tensor)
+  input, weight, bias: "grad.defined() ? batch_norm_backward(grad, input, weight, running_mean, running_var, result1, result2, /*update*/true, eps, grad_input_mask, retain_variables ? result3.clone() : result3) : std::tuple()"
+  result0: batch_norm_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, running_mean, running_var, result1, result2, true, eps)
+
+- name: _batch_norm_no_update(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, float momentum, float eps) -> (Tensor, Tensor, Tensor, Tensor)
+  input, weight, bias: "grad.defined() ? batch_norm_backward(grad, input, weight, running_mean, running_var, result1, result2, /*update*/false, eps, grad_input_mask, retain_variables ? result3.clone() : result3) : std::tuple()"
+  result0: batch_norm_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, running_mean, running_var, result1, result2, false, eps)
+
+- name: batch_norm_backward(Tensor grad_out, Tensor input, Tensor weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var, bool update, float eps, bool[3] output_mask, Tensor reserve) -> (Tensor, Tensor, Tensor)
+  input, weight, grad_out: batchnorm_double_backward(input, weight, grads[0], grads[1], grads[2], grad_out, running_mean, running_var, update, eps, save_mean, save_var, grad_input_mask)
+  save_mean: not_implemented("batch_norm_backward save_mean")
+  save_var: not_implemented("batch_norm_backward save_var")
+  reserve: not_implemented("batch_norm_backward reserve")
+
+- name: nextafter(Tensor self, Tensor other) -> Tensor
+  self: not_implemented("nextafter")
+  other: not_implemented("nextafter")
+
+- name: norm.Scalar(Tensor self, Scalar p=2) -> Tensor
+  self: norm_backward(grad, self, p, result)
+  result: norm_jvp(self_p, self_t, p, result)
+
+- name: norm.ScalarOpt_dim(Tensor self, Scalar? p, int[1] dim, bool keepdim=False) -> Tensor
+  self: norm_backward(grad, self, p, result, dim, keepdim)
+  result: norm_jvp(self_p, self_t, p, result, dim, keepdim)
+
+- name: norm.ScalarOpt_dtype(Tensor self, Scalar? p, *, ScalarType dtype) -> Tensor
+  self: norm_backward(grad, self.to(grad.scalar_type()), p, result)
+  result: norm_jvp(self_p, self_t, p, result)
+
+- name: norm.ScalarOpt_dim_dtype(Tensor self, Scalar? p, int[1] dim, bool keepdim, *, ScalarType dtype) -> Tensor
+  self: norm_backward(grad, self.to(grad.scalar_type()), p, result, dim, keepdim)
+  result: norm_jvp(self_p, self_t, p, result, dim, keepdim)
+
+- name: linalg_vector_norm(Tensor self, Scalar ord=2, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+  self: linalg_vector_norm_backward(grad, self, ord, result, dim, keepdim)
+  result: linalg_vector_norm_jvp(self_p, self_t, ord, result, dim, keepdim)
+
+- name: _pdist_forward(Tensor self, float p=2) -> Tensor
+  self: _pdist_backward(grad, self, p, result)
+
+- name: _pdist_backward(Tensor grad, Tensor self, float p, Tensor pdist) -> Tensor
+  grad: not_implemented("_pdist_backward")
+  self: not_implemented("_pdist_backward")
+  pdist: not_implemented("_pdist_backward")
+
+- name: _euclidean_dist(Tensor x1, Tensor x2) -> Tensor
+  x1, x2: _euclidean_dist_backward(grad, x1, x2, result)
+
+- name: _cdist_forward(Tensor x1, Tensor x2, float p, int? compute_mode) -> Tensor
+  x1: _cdist_backward(grad.contiguous(), x1, x2, p, result)
+  x2: _cdist_backward(grad.mT().contiguous(), x2, x1, p, result.mT().contiguous())
+
+- name: _cdist_backward(Tensor grad, Tensor x1, Tensor x2, float p, Tensor cdist) -> Tensor
+  grad: not_implemented("_cdist_backward")
+  x1: not_implemented("_cdist_backward")
+  x2: not_implemented("_cdist_backward")
+  cdist: not_implemented("_cdist_backward")
+
+- name: normal_(Tensor(a!) self, float mean=0, float std=1, *, Generator? generator=None) -> Tensor(a!)
+  self: zeros_like(grad)
+  result: self_t.zero_()
+
+- name: normal.Tensor_float(Tensor mean, float std=1, *, Generator? generator=None) -> Tensor
+  mean: at::zeros_symint(mean.sym_sizes(), grad.options())
+  result: auto_element_wise
+
+- name: normal.float_Tensor(float mean, Tensor std, *, Generator? generator=None) -> Tensor
+  std: at::zeros_symint(std.sym_sizes(), grad.options())
+  result: auto_element_wise
+
+- name: normal.Tensor_Tensor(Tensor mean, Tensor std, *, Generator? generator=None) -> Tensor
+  mean: at::zeros_symint(mean.sym_sizes(), grad.options())
+  std: at::zeros_symint(std.sym_sizes(), grad.options())
+  result: zeros_like(mean_t)
+
+- name: linalg_householder_product(Tensor input, Tensor tau) -> Tensor
+  input, tau: householder_product_backward(grad, result, input, tau)
+  result: householder_product_jvp(input_t, tau_t, result, input_p, tau_p)
+
+- name: ormqr(Tensor self, Tensor input2, Tensor input3, bool left=True, bool transpose=False) -> Tensor
+  self, input2, input3: ormqr_backward(grad, result, self, input2, input3, left, transpose, grad_input_mask)
+
+- name: permute(Tensor(a) self, int[] dims) -> Tensor(a)
+  self: permute_backwards(grad, dims)
+  result: auto_linear
+
+- name: poisson(Tensor self, Generator? generator=None) -> Tensor
+  self: zeros_like(self)
+  result: auto_element_wise
+
+- name: pow.Tensor_Scalar(Tensor self, Scalar exponent) -> Tensor
+  self: pow_backward(grad, self, exponent)
+  result: auto_element_wise
+
+- name: pow.Tensor_Tensor(Tensor self, Tensor exponent) -> Tensor
+  self: pow_backward_self(grad, self, exponent)
+  exponent: pow_backward_exponent(grad, self, exponent, result)
+  result: (pow_backward_self(self_t.conj(), self_p, exponent_p) + pow_backward_exponent(exponent_t.conj(), self_p, exponent_p, result)).conj()
+
+- name: pow.Scalar(Scalar self, Tensor exponent) -> Tensor
+  exponent: pow_backward_exponent(grad, self, exponent, result)
+  result: auto_element_wise
+
+- name: prod(Tensor self, *, ScalarType? dtype=None) -> Tensor
+  self: prod_backward(grad, self.to(grad.scalar_type()), result)
+  result: (prod_backward(at::ones({}, result.options()).expand_as(result), self_p.to(result.scalar_type()), result) * self_t.conj()).sum().conj()
+
+- name: prod.dim_int(Tensor self, int dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+  self: prod_backward(grad, self.to(grad.scalar_type()), result, dim, keepdim)
+  result: (prod_backward(at::ones({}, result.options()).expand_as(result), self_p.to(result.scalar_type()), result, dim, keepdim) * self_t.conj()).sum(dim, keepdim).conj()
+
+- name: put(Tensor self, Tensor index, Tensor source, bool accumulate=False) -> Tensor
+  self: "accumulate ? grad : grad.put(index, zeros_like(source), false)"
+  index: non_differentiable
+  source: grad.take(index).reshape_as(source)
+  result: self_t.put(index, source_t, accumulate)
+
+- name: linalg_qr(Tensor A, str mode='reduced') -> (Tensor Q, Tensor R)
+  A: linalg_qr_backward(grad_Q, grad_R, Q, R, mode)
+  Q, R: linalg_qr_jvp(A_t, Q, R, mode)
+
+- name: rad2deg(Tensor self) -> Tensor
+  self: rad2deg_backward(grad)
+  result: auto_element_wise
+
+- name: random_.from(Tensor(a!) self, int from, int? to, *, Generator? generator=None) -> Tensor(a!)
+  self: zeros_like(grad)
+  result: self_t.zero_()
+
+- name: random_.to(Tensor(a!) self, int to, *, Generator? generator=None) -> Tensor(a!)
+  self: zeros_like(grad)
+  result: self_t.zero_()
+
+- name: random_(Tensor(a!) self, *, Generator? generator=None) -> Tensor(a!)
+  self: zeros_like(grad)
+  result: self_t.zero_()
+
+- name: reciprocal(Tensor self) -> Tensor
+  self: -grad * (result * result).conj()
+  result: auto_element_wise
+
+- name: remainder.Scalar(Tensor self, Scalar other) -> Tensor
+  self: grad
+  result: auto_element_wise
+
+- name: remainder.Tensor(Tensor self, Tensor other) -> Tensor
+  self: grad
+  other: -grad * self.div(other, /*rounding_mode=*/"floor")
+  result: self_t - other_t * self_p.div(other_p, /*rounding_mode=*/"floor")
+
+- name: renorm(Tensor self, Scalar p, int dim, Scalar maxnorm) -> Tensor
+  self: renorm_backward(grad, self, p, dim, maxnorm)
+  result: renorm_jvp(self_p, self_t, p, dim, maxnorm)
+
+- name: repeat(Tensor self, SymInt[] repeats) -> Tensor
+  self: repeat_backward(grad, repeats, self.sym_sizes())
+  result: auto_linear
+
+- name: special_entr(Tensor self) -> Tensor
+  self: grad * (-(1 + self.log()))
+  result: auto_element_wise
+
+- name: special_ndtri(Tensor self) -> Tensor
+  self: grad * std::sqrt(2 * M_PI) * (result.square() / 2).exp()
+  result: auto_element_wise
+
+- name: special_log_ndtr(Tensor self) -> Tensor
+  self: grad / std::sqrt(2 * M_PI) * (result + self.pow(2) / 2).neg().exp()
+  result: auto_element_wise
+
+# [Note: Sometimes view derivatives]
+# The following situation applies to other operations as well.
+# TODO: This note is only referenced by to_dense and to_sparse*. Make
+# this more generic if it's been referenced more than once.
+#
+# DO NOT define a backward for reshape!
+# reshape is special in that it sometimes returns a view, and sometimes not.
+# Defining a backward will make codegen spit out the forward call as
+#     as_variable(baseType->reshape(self)),
+# making it impossible (hard) to detect when it is actually a view.
+# - name: reshape(Tensor self, IntArrayRef shape)
+
+- name: _reshape_alias(Tensor(a) self, SymInt[] size, SymInt[] stride) -> Tensor(a)
+  self: grad.reshape_symint(self.sym_sizes())
+  result: auto_linear
+
+- name: round(Tensor self) -> Tensor
+  self: zeros_like(grad)
+  result: auto_element_wise
+
+- name: round.decimals(Tensor self, *, int decimals) -> Tensor
+  self: zeros_like(grad)
+  result: auto_element_wise
+
+- name: rsqrt(Tensor self) -> Tensor
+  self: -0.5 * grad * result.pow(3).conj()
+  result: auto_element_wise
+
+- name: scatter.src(Tensor self, int dim, Tensor index, Tensor src) -> Tensor
+  self: grad.scatter(dim, index, 0)
+  index: non_differentiable
+  src: grad.gather(dim, index)
+  result: self_t.scatter(dim, index, src_t)
+
+- name: scatter.value(Tensor self, int dim, Tensor index, Scalar value) -> Tensor
+  self: grad.scatter(dim, index, 0)
+  index: non_differentiable
+  result: self_t.scatter(dim, index, 0)
+
+- name: scatter_add(Tensor self, int dim, Tensor index, Tensor src) -> Tensor
+  self: grad
+  index: non_differentiable
+  src: grad.gather(dim, index)
+  result: scatter_add(self_t, dim, index, src_t)
+
+- name: select.int(Tensor(a) self, int dim, SymInt index) -> Tensor(a)
+  dispatch:
+    Default:
+      self: select_backward_symint(grad, self.sym_sizes(), dim, index)
+      result: auto_linear
+    AutogradNestedTensor:
+      self: _nested_select_backward_symint(grad, self, dim, index)
+
+- name: select_backward(Tensor grad_output, SymInt[] input_sizes, int dim, SymInt index) -> Tensor
+  grad_output: grad.select_symint(dim, index)
+  result: auto_linear
+
+- name: sigmoid(Tensor self) -> Tensor
+  self: sigmoid_backward(grad, result)
+  result: auto_element_wise
+
+- name: logit(Tensor self, float? eps=None) -> Tensor
+  self: "GradMode::is_enabled() ? infinitely_differentiable_logit_backward(grad, self, eps) : logit_backward(grad, self, eps)"
+  result: auto_element_wise
+
+- name: sign(Tensor self) -> Tensor
+  self: zeros_like(grad)
+  result: auto_element_wise
+
+- name: sgn(Tensor self) -> Tensor
+  self: sgn_backward(self, grad, result)
+  # Cannot use auto_element_wise here because the Jacobian is *not* Hermitian (in fact, it is symmetric)
+  # The function is not holomorphic, so there's no reason for its Jacobian to be Hermitian
+  # auto_element_wise has a name that's a bit deceiving in the complex case
+  result: sgn_backward(self_p, self_t, result)
+
+- name: sin(Tensor self) -> Tensor
+  self: grad * self.cos().conj()
+  result: auto_element_wise
+
+- name: sinc(Tensor self) -> Tensor
+  self: sinc_backward(grad, self)
+  result: auto_element_wise
+
+- name: sinh(Tensor self) -> Tensor
+  self: grad * self.cosh().conj()
+  result: auto_element_wise
+
+- name: slice.Tensor(Tensor(a) self, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor(a)
+  self: slice_backward_wrapper(grad, self.sym_sizes(), dim, start, end, step)
+  result: auto_linear
+
+- name: slice_backward(Tensor grad_output, SymInt[] input_sizes, int dim, SymInt start, SymInt end, SymInt step) -> Tensor
+  grad_output: grad.slice_symint(dim, start, end, step)
+  result: auto_linear
+
+- name: slice_inverse(Tensor(a) self, Tensor src, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor(a)
+  self: grad.slice_symint(dim, start, end, step)
+  src: slice_scatter_symint(grad, zeros_like(self), dim, start, end, step)
+  result: auto_linear
+
+- name: slice_scatter(Tensor self, Tensor src, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor
+  self: slice_scatter_symint(grad, zeros_like(src), dim, start, end, step)
+  src: grad.slice_symint(dim, start, end, step)
+  result: auto_linear
+
+- name: select_scatter(Tensor self, Tensor src, int dim, SymInt index) -> Tensor
+  self: select_scatter_symint(grad, zeros_like(src), dim, index)
+  src: grad.select_symint(dim, index)
+  result: auto_linear
+
+- name: diagonal_scatter(Tensor self, Tensor src, int offset=0, int dim1=0, int dim2=1) -> Tensor
+  self: diagonal_scatter(grad, zeros_like(src), offset, dim1, dim2)
+  src: grad.diagonal(offset, dim1, dim2)
+  result: auto_linear
+
+- name: as_strided_scatter(Tensor self, Tensor src, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor
+  self: as_strided_scatter_backward(grad, TensorGeometry(self), TensorGeometry(src), size, stride, storage_offset)
+  # See Note [as_strided_scatter backward support]
+  src: grad.contiguous().as_strided_symint(size, stride, storage_offset)
+  result: auto_linear
+
+- name: _linalg_solve_ex(Tensor A, Tensor B, *, bool left=True, bool check_errors=False) -> (Tensor result, Tensor LU, Tensor pivots, Tensor info)
+  A, B: linalg_solve_backward(grad, result, A, LU, pivots, left, grad_input_mask[1])
+  result: "linalg_solve_jvp(A_t, B_t, result, LU, pivots, left, A_p.is_contiguous() && !A_p.is_complex())"
+  output_differentiability: [True, False, False, False]  # LU is an auxiliary tensor not exposed to the user
+
+- name: sort(Tensor self, int dim=-1, bool descending=False) -> (Tensor values, Tensor indices)
+  self: value_selecting_reduction_backward_symint(grad, dim, indices, self.sym_sizes(), true)
+  output_differentiability: [True, False]
+  values: gather_with_keepdimed_indices(self_t, dim, indices, true)
+
+- name: sort.stable(Tensor self, *, bool? stable, int dim=-1, bool descending=False) -> (Tensor values, Tensor indices)
+  self: value_selecting_reduction_backward_symint(grad, dim, indices, self.sym_sizes(), true)
+  output_differentiability: [True, False]
+  values: gather_with_keepdimed_indices(self_t, dim, indices, true)
+
+- name: split.Tensor(Tensor(a -> *) self, SymInt split_size, int dim=0) -> Tensor(a)[]
+  self: split_backward(grads, split_size, dim, self.sym_sizes(), self.options())
+  result: auto_linear
+
+- name: unsafe_split.Tensor(Tensor self, SymInt split_size, int dim=0) -> Tensor[]
+  self: split_backward(grads, split_size, dim, self.sym_sizes(), self.options())
+  result: auto_linear
+
+- name: split_with_sizes(Tensor(a -> *) self, SymInt[] split_sizes, int dim=0) -> Tensor(a)[]
+  dispatch:
+    Default:
+      self: split_with_sizes_backward(grads, split_sizes, dim, self.sym_sizes(), self.options())
+      result: auto_linear
+    AutogradNestedTensor:
+      self: _nested_split_with_sizes_backward(grads, split_sizes, dim, at::native::get_nested_tensor_impl(self)->get_nested_sizes(), self.options())
+
+- name: unsafe_split_with_sizes(Tensor self, SymInt[] split_sizes, int dim=0) -> Tensor[]
+  self: split_with_sizes_backward(grads, split_sizes, dim, self.sym_sizes(), self.options())
+  result: auto_linear
+
+- name: sqrt(Tensor self) -> Tensor
+  self: grad / (2 * result.conj())
+  result: auto_element_wise
+
+- name: squeeze(Tensor(a) self) -> Tensor(a)
+  self: unsqueeze_to(grad, self.sym_sizes())
+  result: auto_linear
+
+- name: squeeze.dim(Tensor(a) self, int dim) -> Tensor(a)
+  dispatch:
+    Default:
+      self: unsqueeze_to(grad, dim, self.sym_sizes())
+      result: auto_linear
+    AutogradNestedTensor:
+      self: grad.unsqueeze(dim)
+
+- name: squeeze.dims(Tensor(a) self, int[] dim) -> Tensor(a)
+  dispatch:
+    Default:
+      self: unsqueeze_to(grad, dim, self.sym_sizes())
+      result: auto_linear
+    AutogradNestedTensor:
+      self: unsqueeze_multiple(grad, dim, self.dim())
+
+- name: squeeze_(Tensor(a!) self) -> Tensor(a!)
+  self: unsqueeze_to(grad, self.sym_sizes())
+  result: auto_linear
+
+- name: squeeze_.dim(Tensor(a!) self, int dim) -> Tensor(a!)
+  self: unsqueeze_to(grad, dim, self.sym_sizes())
+  result: auto_linear
+
+- name: squeeze_.dims(Tensor(a!) self, int[] dim) -> Tensor(a!)
+  self: unsqueeze_to(grad, dim, self.sym_sizes())
+  result: auto_linear
+
+- name: std.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> Tensor
+  self: std_backward(result, grad, self, dim, correction, keepdim)
+  # pointwise (variance) + sum + sqrt
+  result: (at::real(var_backward(self_t.conj(), self_p, dim, correction, true).sum(dim.value_or(IntArrayRef({})), keepdim)) / (2. * result)).masked_fill_(result == 0, 0)
+
+- name: std_mean.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> (Tensor, Tensor)
+  self: std_mean_backward(grads[0], grads[1], self, result0, dim, correction, keepdim)
+  result0: (at::real(var_backward(self_t.conj(), self_p, dim, correction, true).sum(dim.value_or(IntArrayRef({})), keepdim)) / (2. * result0)).masked_fill_(result0 == 0, 0)
+  # linear
+  result1: mean(self_t, dim.value_or(IntArrayRef({})), keepdim)
+
+- name: sub.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor
+  self: handle_r_to_c(self.scalar_type(), grad)
+  other: handle_r_to_c(other.scalar_type(), maybe_multiply(-grad, alpha.conj()))
+  result: self_t - maybe_multiply(other_t, alpha)
+
+- name: sub.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor
+  self: handle_r_to_c(self.scalar_type(), grad)
+  result: auto_element_wise
+
+- name: rsub.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor
+  self: handle_r_to_c(self.scalar_type(), maybe_multiply(-grad, alpha.conj()))
+  other: handle_r_to_c(other.scalar_type(), grad)
+  result: -maybe_multiply(self_t, alpha) + other_t
+
+- name: rsub.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor
+  self: handle_r_to_c(self.scalar_type(), maybe_multiply(-grad, alpha.conj()))
+  result: auto_element_wise
+
+- name: sum(Tensor self, *, ScalarType? dtype=None) -> Tensor
+  dispatch:
+    Default:
+      self: grad.expand_symint(self.sym_sizes())
+      result: auto_linear
+    AutogradNestedTensor:
+      # TODO: replace this with grad.expand_as(self) when that is supported
+      self: ones_like(self) * grad
+      result: auto_linear
+
+- name: sum.dim_IntList(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+  dispatch:
+    Default:
+      self: sum_backward(grad, self.sym_sizes(), dim, keepdim)
+      result: auto_linear
+    AutogradNestedTensor:
+      # TODO: replace this function once semantics for nested tensor expand have been settled on
+      self: _nested_sum_backward(grad, self, dim, keepdim)
+
+- name: nansum(Tensor self, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+  self: nansum_backward(grad.to(self.scalar_type()), self, dim, keepdim)
+  result: at::where(self_p.isnan(), 0, self_t).sum(dim, keepdim, dtype)
+
+# We never call _linalg_svd with compute_uv=False in an autograd context, so we don't even consider it here
+- name: _linalg_svd(Tensor A, bool full_matrices=False, bool compute_uv=True, *, str? driver=None) -> (Tensor U, Tensor S, Tensor Vh)
+  A: "svd_backward(full_matrices && grad_U.defined() ? grad_U.narrow_symint(-1, 0, S.sym_size(-1)) : grad_U,
+                   grad_S,
+                   full_matrices && grad_Vh.defined() ? grad_Vh.narrow_symint(-2, 0, S.sym_size(-1)) : grad_Vh,
+                   full_matrices ? U.narrow_symint(-1, 0, S.sym_size(-1)) : U,
+                   S,
+                   full_matrices ? Vh.narrow_symint(-2, 0, S.sym_size(-1)) : Vh)"
+  U, S, Vh: linalg_svd_jvp(A_t, U, S, Vh, full_matrices)
+
+- name: _linalg_eigh(Tensor A, str UPLO="L", bool compute_v=True) -> (Tensor eigenvalues, Tensor eigenvectors)
+  A: linalg_eig_backward(grads[0], grads[1], eigenvalues, eigenvectors, /*is_hermitian=*/true)
+  eigenvalues, eigenvectors: linalg_eig_jvp(A_t, eigenvalues, eigenvectors, /*is_hermitian=*/true)
+
+- name: linalg_eig(Tensor self) -> (Tensor eigenvalues, Tensor eigenvectors)
+  self: handle_r_to_c(self.scalar_type(), linalg_eig_backward(grads[0], grads[1], eigenvalues, eigenvectors, /*is_hermitian=*/false))
+  eigenvalues, eigenvectors: linalg_eig_jvp(self_t, eigenvalues, eigenvectors, /*is_hermitian=*/false)
+
+- name: t(Tensor(a) self) -> Tensor(a)
+  self: grad.t()
+  result: auto_linear
+
+- name: t_(Tensor(a!) self) -> Tensor(a!)
+  self: grad.t()
+  result: auto_linear
+
+- name: one_hot(Tensor self, int num_classes=-1) -> Tensor
+  self: non_differentiable
+
+- name: flip(Tensor self, int[] dims) -> Tensor
+  self: grad.flip(dims)
+  result: auto_linear
+
+- name: roll(Tensor self, SymInt[1] shifts, int[1] dims=[]) -> Tensor
+  self: grad.roll_symint(fmap(reverse_list_symint(shifts), [](c10::SymInt i){return -i;}), reverse_list(dims))
+  result: auto_linear
+
+- name: rot90(Tensor self, int k=1, int[] dims=[0,1]) -> Tensor
+  self: grad.rot90(-k, dims)
+  result: auto_linear
+
+- name: take(Tensor self, Tensor index) -> Tensor
+  self: take_backward(grad, self, index)
+  index: non_differentiable
+  result: auto_linear
+
+- name: tan(Tensor self) -> Tensor
+  self: grad * (1 + result.pow(2)).conj()
+  result: auto_element_wise
+
+- name: tanh(Tensor self) -> Tensor
+  self: tanh_backward(grad, result)
+  result: auto_element_wise
+
+- name: topk(Tensor self, SymInt k, int dim=-1, bool largest=True, bool sorted=True) -> (Tensor values, Tensor indices)
+  self: value_selecting_reduction_backward_symint(grad, dim, indices, self.sym_sizes(), true)
+  output_differentiability: [True, False]
+  values: gather(self_t, dim, indices)
+
+- name: trace(Tensor self) -> Tensor
+  self: trace_backward_symint(grad, self.sym_sizes())
+  result: auto_linear
+
+- name: transpose.int(Tensor(a) self, int dim0, int dim1) -> Tensor(a)
+  self: grad.transpose(dim0, dim1)
+  result: auto_linear
+
+- name: transpose_(Tensor(a!) self, int dim0, int dim1) -> Tensor(a!)
+  self: grad.transpose(dim0, dim1)
+  result: auto_linear
+
+- name: triangular_solve(Tensor self, Tensor A, bool upper=True, bool transpose=False, bool unitriangular=False) -> (Tensor solution, Tensor cloned_coefficient)
+  self, A: triangular_solve_backward(grad_solution, grad_cloned_coefficient, self, A, solution, upper, transpose, unitriangular, grad_input_mask)
+  solution: triangular_solve_jvp(solution, A_p, A_t, self_t, upper, transpose, unitriangular)
+  cloned_coefficient: A_t
+
+- name: linalg_solve_triangular(Tensor self, Tensor B, *, bool upper, bool left=True, bool unitriangular=False) -> Tensor
+  self, B: linalg_solve_triangular_backward(grad, self, result, upper, left, unitriangular, grad_input_mask)
+  result: linalg_solve_triangular_forward_AD(self_t, B_t, self_p, result, upper, left, unitriangular)
+
+- name: tril(Tensor self, int diagonal=0) -> Tensor
+  self: grad.tril(diagonal)
+  result: auto_linear
+
+- name: triu(Tensor self, int diagonal=0) -> Tensor
+  self: grad.triu(diagonal)
+  result: auto_linear
+
+- name: trunc(Tensor self) -> Tensor
+  self: zeros_like(grad)
+  result: auto_element_wise
+
+- name: hash_tensor(Tensor self, int[1] dim=[], *, bool keepdim=False, int mode=0) -> Tensor
+  output_differentiability: [False]
+
+# DO NOT define a backward for to_dense
+# See [Note: Sometimes view derivatives]
+# - name: to_dense(Tensor self, ScalarType? dtype=None, *, bool? masked_grad=None) -> Tensor
+#
+- name: _to_dense(Tensor self, ScalarType? dtype=None, bool? masked_grad=None) -> Tensor
+  self: to_dense_backward(grad, self, masked_grad)
+
+# DO NOT define a backward for to_sparse.sparse_dim
+# See [Note: Sometimes view derivatives]
+# - name: to_sparse.sparse_dim(Tensor self, int sparse_dim) -> Tensor
+#
+- name: _to_sparse.sparse_dim(Tensor self, int sparse_dim) -> Tensor
+  self: to_sparse_backward(grad, self.layout(), self.sym_blocksize())
+
+# DO NOT define a backward for to_sparse
+# See [Note: Sometimes view derivatives]
+# - name: to_sparse(Tensor self, *, Layout? layout=None, int[2]? blocksize=None, int? dense_dim=None) -> Tensor
+#
+- name: _to_sparse(Tensor self, *, Layout? layout=None, int[2]? blocksize=None, int? dense_dim=None) -> Tensor
+  self: to_sparse_backward(grad, self.layout(), self.sym_blocksize())
+
+# DO NOT define a backward for to_sparse_csr
+# See [Note: Sometimes view derivatives]
+# - name: to_sparse_csr(Tensor self, int? dense_dim=None) -> Tensor
+#
+- name: _to_sparse_csr(Tensor self, int? dense_dim=None) -> Tensor
+  self: to_sparse_backward(grad, self.layout(), self.sym_blocksize())
+
+# DO NOT define a backward for to_sparse_csc
+# See [Note: Sometimes view derivatives]
+# - name: to_sparse_csc(Tensor self, int? dense_dim=None) -> Tensor
+#
+- name: _to_sparse_csc(Tensor self, int? dense_dim=None) -> Tensor
+  self: to_sparse_backward(grad, self.layout(), self.sym_blocksize())
+
+# DO NOT define a backward for to_sparse_bsr
+# See [Note: Sometimes view derivatives]
+# - name: to_sparse_bsr(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor
+#
+- name: _to_sparse_bsr(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor
+  self: to_sparse_backward(grad, self.layout(), self.sym_blocksize())
+
+# DO NOT define a backward for to_sparse_bsc
+# See [Note: Sometimes view derivatives]
+# - name: to_sparse_bsc(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor
+#
+- name: _to_sparse_bsc(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor
+  self: to_sparse_backward(grad, self.layout(), self.sym_blocksize())
+
+- name: to_mkldnn(Tensor self, ScalarType? dtype=None) -> Tensor
+  self: to_mkldnn_backward(grad, self)
+
+- name: unfold(Tensor(a) self, int dimension, int size, int step) -> Tensor(a)
+  self: unfold_backward_symint(grad, self.sym_sizes(), dimension, size, step)
+  result: auto_linear
+
+- name: unfold_backward(Tensor grad_in, SymInt[] input_sizes, int dim, int size, int step) -> Tensor
+  grad_in: grad.unfold(dim, size, step)
+  result: auto_linear
+
+- name: uniform_(Tensor(a!) self, float from=0, float to=1, *, Generator? generator=None) -> Tensor(a!)
+  self: zeros_like(grad)
+  result: self_t.zero_()
+
+- name: _unique(Tensor self, bool sorted=True, bool return_inverse=False) -> (Tensor, Tensor)
+  output_differentiability: [True, False]
+  self: not_implemented("_unique")
+
+- name: unique_dim(Tensor self, int dim, bool sorted=True, bool return_inverse=False, bool return_counts=False) -> (Tensor, Tensor, Tensor)
+  output_differentiability: [True, False, False]
+  self: not_implemented("unique_dim")
+
+- name: unique_consecutive(Tensor self, bool return_inverse=False, bool return_counts=False, int? dim=None) -> (Tensor, Tensor, Tensor)
+  output_differentiability: [True, False, False]
+  self: not_implemented("unique_consecutive")
+
+- name: unique_dim_consecutive(Tensor self, int dim, bool return_inverse=False, bool return_counts=False) -> (Tensor, Tensor, Tensor)
+  output_differentiability: [True, False, False]
+  self: not_implemented("unique_dim_consecutive")
+
+- name: _unique2(Tensor self, bool sorted=True, bool return_inverse=False, bool return_counts=False) -> (Tensor, Tensor, Tensor)
+  output_differentiability: [True, False, False]
+  self: not_implemented("_unique2")
+
+- name: _unsafe_view(Tensor self, SymInt[] size) -> Tensor
+  self: grad.reshape_symint(self.sym_sizes())
+  result: auto_linear
+
+- name: lift(Tensor self) -> Tensor
+  self: grad
+  result: auto_linear
+
+- name: lift_fresh(Tensor(a) self) -> Tensor(a)
+  self: grad
+  result: auto_linear
+
+- name: unsqueeze(Tensor(a) self, int dim) -> Tensor(a)
+  self: grad.squeeze(dim)
+  result: auto_linear
+
+- name: unsqueeze_(Tensor(a!) self, int dim) -> Tensor(a!)
+  self: grad.squeeze(dim)
+  result: auto_linear
+
+- name: var.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> Tensor
+  self: var_backward(grad, self, dim, correction, keepdim)
+  # pointwise + sum
+  result: at::real(var_backward(self_t.conj(), self_p, dim, correction, true).sum(dim.value_or(IntArrayRef({})), keepdim))
+
+- name: var_mean.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> (Tensor, Tensor)
+  self: var_mean_backward(grads[0], grads[1], self, dim, correction, keepdim)
+  result0: at::real(var_backward(self_t.conj(), self_p, dim, correction, true).sum(dim.value_or(IntArrayRef({})), keepdim))
+  # linear
+  result1: mean(self_t, dim.value_or(IntArrayRef({})), keepdim)
+
+- name: view(Tensor(a) self, SymInt[] size) -> Tensor(a)
+  dispatch:
+    Default:
+      self: grad.reshape_symint(self.sym_sizes())
+      result: auto_linear
+    AutogradNestedTensor:
+      self: grad.reshape_as(self)
+      result: auto_linear
+
+- name: view.dtype(Tensor(a) self, ScalarType dtype) -> Tensor(a)
+  output_differentiability: [False]
+
+- name: view_as_real(Tensor(a) self) -> Tensor(a)
+  self: at::view_as_complex(grad.contiguous()) # gx0 + 1j * gx1
+  result: at::view_as_real(self_t)
+
+- name: view_as_complex(Tensor(a) self) -> Tensor(a)
+  self: at::view_as_real(grad.contiguous().resolve_conj()) # [gx, gy]
+  result: at::view_as_complex(self_t)
+
+- name: where.self(Tensor condition, Tensor self, Tensor other) -> Tensor
+  condition: non_differentiable
+  self: where(condition, grad, 0)
+  other: where(condition, 0, grad)
+  result: where(condition, self_t, other_t)
+
+# weight_norm_cuda_interface_backward does not have an explicitly defined derivative, so if we do happen
+# to be running backward with create_graph=True, fall back to a backward function that uses
+# differentiable ops.
+- name: _weight_norm_interface(Tensor v, Tensor g, int dim=0) -> (Tensor, Tensor)
+  v, g: "grad.defined() ? (GradMode::is_enabled() ? _weight_norm_differentiable_backward(grad.contiguous(), v, g, result1, dim) : _weight_norm_interface_backward(grad.contiguous(), v, g, result1, dim)) : std::tuple()"
+
+- name: zero_(Tensor(a!) self) -> Tensor(a!)
+  self: zeros_like(grad)
+  result: auto_linear
+
+- name: sparse_mask(Tensor self, Tensor mask) -> Tensor
+  self: sparse_mask_backward(grad, mask, self.layout())
+  mask: non_differentiable
+
+- name: _sparse_coo_tensor_with_dims_and_tensors(int sparse_dim, int dense_dim, SymInt[] size, Tensor indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False, bool? is_coalesced=None) -> Tensor
+  indices: non_differentiable
+  values: grad.sparse_mask(result)._values()
+
+- name: sparse_compressed_tensor.comp_plain_value_size(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+  compressed_indices: non_differentiable
+  plain_indices: non_differentiable
+  # TODO: remove to_dense after gh-107381 is fixed
+  values: grad.to_dense().sparse_mask(result).values()
+
+- name: _sparse_sum.dim(Tensor self, int[1] dim) -> Tensor
+  self: at::_sparse_sum_backward(grad, self, dim)
+
+- name: _standard_gamma(Tensor self, Generator? generator=None) -> Tensor
+  self: grad * _standard_gamma_grad(self, result)
+
+- name: _standard_gamma_grad(Tensor self, Tensor output) -> Tensor
+  self: not_implemented("_standard_gamma_grad")
+
+- name: values(Tensor(a) self) -> Tensor(a)
+  dispatch:
+    Default:
+      self: values_backward(grad, self)
+    AutogradNestedTensor:
+      self: at::_nested_view_from_buffer(grad.contiguous(), self._nested_tensor_size(), self._nested_tensor_strides(), self._nested_tensor_storage_offsets())
+
+# Why is _values() not differentiable?
+# See NOTE [ Sparse: autograd and API ]
+- name: _values(Tensor(a) self) -> Tensor(a)
+  output_differentiability: [False]
+
+# NN
+- name: _trilinear(Tensor i1, Tensor i2, Tensor i3, int[] expand1, int[] expand2, int[] expand3, int[] sumdim, int unroll_dim=1) -> Tensor
+  i1, i2, i3: "_trilinear_backward(grad,
+               wrap_opt_if(i1, grad_input_mask[1] || grad_input_mask[2]),
+               wrap_opt_if(i2, grad_input_mask[0] || grad_input_mask[2]),
+               wrap_opt_if(i3, grad_input_mask[0] || grad_input_mask[1]),
+               expand1, expand2, expand3, sumdim, grad_input_mask)"
+  result: "_trilinear(i1_t, i2_p, i3_p, expand1, expand2, expand3, sumdim, unroll_dim) +
+           _trilinear(i1_p, i2_t, i3_p, expand1, expand2, expand3, sumdim, unroll_dim) +
+           _trilinear(i1_p, i2_p, i3_t, expand1, expand2, expand3, sumdim, unroll_dim)"
+
+- name: constant_pad_nd(Tensor self, SymInt[] pad, Scalar value=0) -> Tensor
+  self: constant_pad_nd_backward(grad, pad)
+  result: constant_pad_nd_symint(self_t, pad, 0)
+
+- name: binary_cross_entropy(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean) -> Tensor
+  self: binary_cross_entropy_backward(grad, self, target, weight, reduction)
+  target: binary_cross_entropy_target_backward(grad, self, target, weight, reduction)
+  result: "apply_loss_reduction(
+               binary_cross_entropy_backward(self_t, self_p, target_p, weight, at::Reduction::None)
+             + binary_cross_entropy_target_backward(target_t, self_p, target_p, weight, at::Reduction::None),
+           reduction)"
+
+- name: binary_cross_entropy_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean) -> Tensor
+  self: binary_cross_entropy_double_backward(grad_output, grad, self, target, weight, reduction)
+  target: binary_cross_entropy_double_backward_target(grad, grad_output, self, target, weight, reduction)
+  grad_output: binary_cross_entropy_double_backward_grad_output(grad, self, target, weight, reduction)
+  result: " binary_cross_entropy_double_backward(grad_output_p, self_t, self_p, target_p, weight, reduction)
+          + binary_cross_entropy_double_backward_target(target_t, grad_output_p, self_p, target_p, weight, reduction)
+          + binary_cross_entropy_double_backward_grad_output(grad_output_t, self_p, target_p, weight, reduction)"
+
+- name: binary_cross_entropy_with_logits(Tensor self, Tensor target, Tensor? weight=None, Tensor? pos_weight=None, int reduction=Mean) -> Tensor
+  self: binary_cross_entropy_with_logits_backward(grad, self, target, weight, pos_weight, reduction)
+  target: binary_cross_entropy_with_logits_target_backward(grad, self, target, weight, pos_weight, reduction)
+  result: "apply_loss_reduction(
+               binary_cross_entropy_with_logits_backward(self_t, self_p, target_p, weight, pos_weight, at::Reduction::None)
+             + binary_cross_entropy_with_logits_target_backward(target_t, self_p, target_p, weight, pos_weight, at::Reduction::None),
+           reduction)"
+
+- name: embedding(Tensor weight, Tensor indices, SymInt padding_idx=-1, bool scale_grad_by_freq=False, bool sparse=False) -> Tensor
+  indices: non_differentiable
+  weight: embedding_backward_symint(grad, indices, weight.sym_size(0), padding_idx, scale_grad_by_freq, sparse)
+  result: auto_linear
+
+- name: embedding_dense_backward(Tensor grad_output, Tensor indices, SymInt num_weights, SymInt padding_idx, bool scale_grad_by_freq) -> Tensor
+  grad_output: embedding_dense_double_backward_symint(grad, indices, padding_idx)
+  indices: non_differentiable
+  result: auto_linear
+
+- name: _embedding_bag(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False, int padding_idx=-1) -> (Tensor, Tensor, Tensor, Tensor)
+  indices: non_differentiable
+  offsets: non_differentiable
+  weight: _embedding_bag_backward_symint(grad, indices, offsets, result1, result2, result3, weight.sym_size(0), scale_grad_by_freq, mode, sparse, per_sample_weights, padding_idx)
+  per_sample_weights: _embedding_bag_per_sample_weights_backward(grad, weight, indices, offsets, result1, mode, padding_idx)
+
+- name: _embedding_bag_backward(Tensor grad, Tensor indices, Tensor offsets, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, SymInt num_weights, bool scale_grad_by_freq, int mode, bool sparse, Tensor? per_sample_weights, int padding_idx=-1) -> Tensor
+  grad: not_implemented("_embedding_bag_backward")
+  indices: non_differentiable
+  offsets: non_differentiable
+  offset2bag: non_differentiable
+  bag_size: non_differentiable
+  maximum_indices: non_differentiable
+  per_sample_weights: not_implemented("_embedding_bag_backward")
+
+- name: _embedding_bag_dense_backward(Tensor grad, Tensor indices, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, SymInt num_weights, bool scale_grad_by_freq, int mode, Tensor? per_sample_weights, int padding_idx=-1) -> Tensor
+  grad: not_implemented("_embedding_bag_dense_backward")
+  indices: non_differentiable
+  offset2bag: non_differentiable
+  bag_size: non_differentiable
+  maximum_indices: non_differentiable
+  per_sample_weights: not_implemented("_embedding_bag_dense_backward")
+
+- name: embedding_renorm_(Tensor(a!) self, Tensor indices, float max_norm, float norm_type) -> Tensor(a!)
+  indices: non_differentiable
+  self: not_implemented("embedding_renorm")
+
+- name: mse_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor
+  self: mse_loss_backward(grad, self, target, reduction)
+  target: mse_loss_backward(grad, target, self, reduction)
+  result: apply_loss_reduction(mse_loss_backward(self_t.conj(), self_p, target_p, at::Reduction::None).conj() + mse_loss_backward(target_t.conj(), target_p, self_p, at::Reduction::None).conj(), reduction)
+
+- name: multi_margin_loss(Tensor self, Tensor target, Scalar p=1, Scalar margin=1, Tensor? weight=None, int reduction=Mean) -> Tensor
+  self: multi_margin_loss_backward(grad, self, target, p, margin, weight, reduction)
+  target: non_differentiable
+
+- name: multilabel_margin_loss_forward(Tensor self, Tensor target, int reduction) -> (Tensor output, Tensor is_target)
+  self: multilabel_margin_loss_backward(grad, self, target, reduction, is_target)
+  target: non_differentiable
+
+- name: nll_loss_forward(Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index) -> (Tensor output, Tensor total_weight)
+  self: nll_loss_backward_symint(grad, self, target, weight, reduction, ignore_index, total_weight)
+  target: non_differentiable
+  output: std::get<0>(nll_loss_forward_symint(self_t, target, weight, reduction, ignore_index))
+
+- name: nll_loss2d_forward(Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index) -> (Tensor output, Tensor total_weight)
+  self: nll_loss2d_backward_symint(grad, self, target, weight, reduction, ignore_index, total_weight)
+  target: non_differentiable
+  output: std::get<0>(nll_loss2d_forward_symint(self_t, target, weight, reduction, ignore_index))
+
+- name: smooth_l1_loss(Tensor self, Tensor target, int reduction=Mean, float beta=1.0) -> Tensor
+  self: smooth_l1_loss_backward(grad, self, target, reduction, beta)
+  target: smooth_l1_loss_backward(grad, target, self, reduction, beta)
+  result: apply_loss_reduction(smooth_l1_loss_backward(self_t.conj(), self_p, target_p, at::Reduction::None, beta).conj() + smooth_l1_loss_backward(target_t.conj(), target_p, self_p, at::Reduction::None, beta).conj(), reduction)
+
+- name: huber_loss(Tensor self, Tensor target, int reduction=Mean, float delta=1.0) -> Tensor
+  self: huber_loss_backward(grad, self, target, reduction, delta)
+  target: huber_loss_backward(grad, target, self, reduction, delta)
+  result: apply_loss_reduction(huber_loss_backward(self_t.conj(), self_p, target_p, at::Reduction::None, delta).conj() + huber_loss_backward(target_t.conj(), target_p, self_p, at::Reduction::None, delta).conj(), reduction)
+
+- name: soft_margin_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor
+  self: soft_margin_loss_backward(grad, self, target, reduction)
+  result: apply_loss_reduction(soft_margin_loss_backward(self_t.conj(), self_p, target, at::Reduction::None).conj(), reduction)
+
+- name: relu(Tensor self) -> Tensor
+  self: threshold_backward(grad, result, 0)
+  result: auto_element_wise
+
+- name: silu(Tensor self) -> Tensor
+  self: "GradMode::is_enabled() ? infinitely_differentiable_silu_backward(grad, self) : silu_backward(grad, self)"
+  result: auto_element_wise
+
+- name: mish(Tensor self) -> Tensor
+  self: "GradMode::is_enabled() ? infinitely_differentiable_mish_backward(grad, self) : mish_backward(grad, self)"
+  result: auto_element_wise
+
+- name: elu(Tensor self, Scalar alpha=1, Scalar scale=1, Scalar input_scale=1) -> Tensor
+  self: elu_backward(grad, alpha, scale, input_scale, /* is_result */ false, self)
+  result: auto_element_wise
+
+- name: elu_(Tensor(a!) self, Scalar alpha=1, Scalar scale=1, Scalar input_scale=1) -> Tensor(a!)
+  self: elu_backward(grad, alpha, scale, input_scale, /* is_result */ true, result)
+  result: self_t.copy_(elu_backward(original_self_t, alpha, scale, input_scale, /* is_result */ true, result))
+
+- name: celu(Tensor self, Scalar alpha=1.0) -> Tensor
+  self: elu_backward(grad, alpha, 1, 1.0/alpha.toFloat(), /* is_result */ false, self)
+  result: auto_element_wise
+
+- name: celu_(Tensor(a!) self, Scalar alpha=1.0) -> Tensor(a!)
+  self: elu_backward(grad, alpha, 1, 1.0/alpha.toFloat(), /* is_result */ true, result)
+  result: self_t.copy_(elu_backward(original_self_t, alpha, 1, 1.0/alpha.toFloat(), /* is_result */ true, result))
+
+- name: gelu(Tensor self, *, str approximate='none') -> Tensor
+  self: gelu_backward(grad, self, approximate)
+  result: auto_element_wise
+
+- name: gelu_backward(Tensor grad_output, Tensor self, *, str approximate='none') -> Tensor
+  grad_output: gelu_backward(grad, self, approximate)
+  self: gelu_double_backward(grad, grad_output, self, approximate)
+  result: gelu_backward(grad_output_t, self_p, approximate) + gelu_double_backward(self_t, grad_output_p, self_p, approximate)
+
+- name: glu(Tensor self, int dim=-1) -> Tensor
+  # TODO: glu_backward can benefit from forward result,
+  # and forward ad/forward over reverse ad for that matter
+  self: glu_backward(grad, self, dim)
+  result: glu_jvp(result, self_p, self_t, dim)
+
+- name: hardshrink(Tensor self, Scalar lambd=0.5) -> Tensor
+  self: hardshrink_backward(grad, self, lambd)
+  result: auto_element_wise
+
+- name: hardshrink_backward(Tensor grad_out, Tensor self, Scalar lambd) -> Tensor
+  grad_out: hardshrink_backward(grad, self, lambd)
+  self: zeros_like(grad)
+  result: at::where((self_p > lambd).logical_or(self_p < -lambd), grad_out_t, at::zeros({}, result.options()).expand_as(result))
+
+- name: hardtanh(Tensor self, Scalar min_val=-1, Scalar max_val=1) -> Tensor
+  self: hardtanh_backward(grad, self, min_val, max_val)
+  result: auto_element_wise
+
+- name: leaky_relu(Tensor self, Scalar negative_slope=0.01) -> Tensor
+  self: leaky_relu_backward(grad, self, negative_slope, false)
+  result: auto_element_wise
+
+- name: leaky_relu_(Tensor(a!) self, Scalar negative_slope=0.01) -> Tensor(a!)
+  self: leaky_relu_backward(grad, result, negative_slope, true)
+  result: self_t.copy_(leaky_relu_backward(original_self_t.conj(), result, negative_slope, true).conj())
+
+- name: log_sigmoid_forward(Tensor self) -> (Tensor output, Tensor buffer)
+  self: log_sigmoid_backward(grad, self, buffer)
+  output: log_sigmoid_backward(self_t.conj(), self_p, buffer).conj()
+  output_differentiability: [True, False]
+
+- name: _log_softmax(Tensor self, int dim, bool half_to_float) -> Tensor
+  self: _log_softmax_backward_data(grad, result, dim, self.scalar_type())
+  result: self_t - logsumexp_jvp(self_p, self_t, {dim}, true)
+
+- name: _sparse_log_softmax(Tensor self, int dim, bool half_to_float) -> Tensor
+  self: _sparse_log_softmax_backward_data(grad, result, dim, self)
+
+- name: _masked_softmax(Tensor self, Tensor mask, int? dim=None, int? mask_type=None) -> Tensor
+  self: _masked_softmax_backward(grad, result, mask, dim)
+  mask: non_differentiable
+
+- name: _prelu_kernel(Tensor self, Tensor weight) -> Tensor
+  self, weight: "grad.defined() ? _prelu_kernel_backward(grad, self, weight) : std::tuple()"
+  result: at::where(self_p >= 0, self_t, weight_p * self_t + weight_t * self_p)
+
+- name: _prelu_kernel_backward(Tensor grad_output, Tensor self, Tensor weight) -> (Tensor, Tensor)
+  grad_output: "grads[0].defined() ?
+                (grads[1].defined() ? at::where(self >= 0, grads[0], grads[0] * weight + grads[1] * self)
+                                    : at::where(self >= 0, grads[0], grads[0] * weight))
+                                    : at::where(self >= 0, at::zeros({}, grad_output.options()), grads[1] * self)"
+  self: "grads[1].defined() ? at::where(self >= 0, at::zeros({}, self.options()), grad_output * grads[1]) : zeros_like(self)"
+  weight: "grads[0].defined() ? at::where(self >= 0, at::zeros({}, weight.options()), grad_output * grads[0]) : zeros_like(self)"
+  result0: at::where(self_p >= 0, grad_output_t, grad_output_t * weight_p + grad_output_p * weight_t)
+  result1: at::where(self_p >= 0, at::zeros({}, self_p.options()), grad_output_p * self_t + grad_output_t * self_p)
+
+- name: rrelu_with_noise(Tensor self, Tensor(b!) noise, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor
+  self: rrelu_with_noise_backward(grad, self, noise, lower, upper, training, false)
+  result: auto_element_wise
+
+- name: rrelu_with_noise_(Tensor(a!) self, Tensor(b!) noise, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor(a!)
+  self: rrelu_with_noise_backward(grad, result, noise, lower, upper, training, true)
+
+- name: rrelu_with_noise_functional(Tensor self, Tensor noise, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> (Tensor, Tensor noise_out)
+  noise: non_differentiable
+  self: rrelu_with_noise_backward(grad, self, noise, lower, upper, training, false)
+
+- name: _softmax(Tensor self, int dim, bool half_to_float) -> Tensor
+  self: _softmax_backward_data(grad, result, dim, self.scalar_type())
+  result: result * (self_t - logsumexp_jvp(self_p, self_t, {dim}, true))
+
+- name: _sparse_softmax(Tensor self, int dim, bool half_to_float) -> Tensor
+  self: _sparse_softmax_backward_data(grad, result, dim, self)
+
+- name: _sparse_sparse_matmul(Tensor self, Tensor other) -> Tensor
+  self: sparse_sparse_matmul_backward(grad, self, other, 0)
+  other: sparse_sparse_matmul_backward(grad, self, other, 1)
+
+- name: softplus(Tensor self, Scalar beta=1, Scalar threshold=20) -> Tensor
+  self: softplus_backward(grad, self, beta, threshold)
+  result: auto_element_wise
+
+- name: softshrink(Tensor self, Scalar lambd=0.5) -> Tensor
+  self: softshrink_backward(grad, self, lambd)
+  result: auto_element_wise
+
+- name: threshold(Tensor self, Scalar threshold, Scalar value) -> Tensor
+  self: threshold_backward(grad, self, threshold)
+  result: auto_element_wise
+
+- name: threshold_(Tensor(a!) self, Scalar threshold, Scalar value) -> Tensor(a!)
+  self: threshold_backward(grad, self, threshold)
+  result: self_t.copy_(threshold_backward(self_t.conj(), original_self_p, threshold).conj())
+
+- name: reflection_pad1d(Tensor self, SymInt[2] padding) -> Tensor
+  self: reflection_pad1d_backward_symint(grad, self, padding)
+  result: auto_linear
+
+- name: reflection_pad2d(Tensor self, SymInt[4] padding) -> Tensor
+  self: reflection_pad2d_backward_symint(grad, self, padding)
+  result: auto_linear
+
+- name: reflection_pad3d(Tensor self, SymInt[6] padding) -> Tensor
+  self: reflection_pad3d_backward_symint(grad, self, padding)
+  result: auto_linear
+
+- name: replication_pad1d(Tensor self, SymInt[2] padding) -> Tensor
+  self: replication_pad1d_backward_symint(grad, self, padding)
+  result: auto_linear
+
+- name: replication_pad2d(Tensor self, SymInt[4] padding) -> Tensor
+  self: replication_pad2d_backward_symint(grad, self, padding)
+  result: auto_linear
+
+- name: replication_pad3d(Tensor self, SymInt[6] padding) -> Tensor
+  self: replication_pad3d_backward_symint(grad, self, padding)
+  result: auto_linear
+
+- name: upsample_linear1d(Tensor self, SymInt[1] output_size, bool align_corners, float? scales=None) -> Tensor
+  self: upsample_linear1d_backward_symint(grad, output_size, self.sym_sizes(), align_corners, scales)
+  result: auto_linear
+
+- name: upsample_bilinear2d(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+  self: upsample_bilinear2d_backward_symint(grad, output_size, self.sym_sizes(), align_corners, scales_h, scales_w)
+  result: auto_linear
+
+- name: _upsample_bilinear2d_aa(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+  self: _upsample_bilinear2d_aa_backward_symint(grad, output_size, self.sym_sizes(), align_corners, scales_h, scales_w)
+  result: auto_linear
+
+- name: upsample_bicubic2d(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+  self: upsample_bicubic2d_backward_symint(grad, output_size, self.sym_sizes(), align_corners, scales_h, scales_w)
+  result: auto_linear
+
+- name: _upsample_bicubic2d_aa(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+  self: _upsample_bicubic2d_aa_backward_symint(grad, output_size, self.sym_sizes(), align_corners, scales_h, scales_w)
+  result: auto_linear
+
+- name: upsample_trilinear3d(Tensor self, SymInt[3] output_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor
+  self: upsample_trilinear3d_backward_symint(grad, output_size, self.sym_sizes(), align_corners, scales_d, scales_h, scales_w)
+  result: auto_linear
+
+- name: upsample_nearest1d(Tensor self, SymInt[1] output_size, float? scales=None) -> Tensor
+  self: upsample_nearest1d_backward_symint(grad, output_size, self.sym_sizes(), scales)
+  result: auto_linear
+
+- name: _upsample_nearest_exact1d(Tensor self, SymInt[1] output_size, float? scales=None) -> Tensor
+  self: _upsample_nearest_exact1d_backward_symint(grad, output_size, self.sym_sizes(), scales)
+  result: auto_linear
+
+- name: upsample_nearest2d(Tensor self, SymInt[2] output_size, float? scales_h=None, float? scales_w=None) -> Tensor
+  self: upsample_nearest2d_backward_symint(grad, output_size, self.sym_sizes(), scales_h, scales_w)
+  result: auto_linear
+
+- name: _upsample_nearest_exact2d(Tensor self, SymInt[2] output_size, float? scales_h=None, float? scales_w=None) -> Tensor
+  self: _upsample_nearest_exact2d_backward_symint(grad, output_size, self.sym_sizes(), scales_h, scales_w)
+  result: auto_linear
+
+- name: upsample_nearest3d(Tensor self, SymInt[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor
+  self: upsample_nearest3d_backward_symint(grad, output_size, self.sym_sizes(), scales_d, scales_h, scales_w)
+  result: auto_linear
+
+- name: _upsample_nearest_exact3d(Tensor self, SymInt[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor
+  self: _upsample_nearest_exact3d_backward_symint(grad, output_size, self.sym_sizes(), scales_d, scales_h, scales_w)
+  result: auto_linear
+
+- name: pixel_shuffle(Tensor self, int upscale_factor) -> Tensor
+  self: pixel_unshuffle(grad, upscale_factor)
+  result: auto_linear
+
+- name: pixel_unshuffle(Tensor self, int downscale_factor) -> Tensor
+  self: pixel_shuffle(grad, downscale_factor)
+  result: auto_linear
+
+- name: channel_shuffle(Tensor self, SymInt groups) -> Tensor
+  self: channel_shuffle_symint(grad, grad.sym_size(1) / groups)
+  result: auto_linear
+
+- name: _adaptive_avg_pool2d(Tensor self, SymInt[2] output_size) -> Tensor
+  self: _adaptive_avg_pool2d_backward(grad, self)
+  result: auto_linear
+
+- name: _adaptive_avg_pool3d(Tensor self, SymInt[3] output_size) -> Tensor
+  self: _adaptive_avg_pool3d_backward(grad, self)
+  result: auto_linear
+
+- name: adaptive_max_pool2d(Tensor self, int[2] output_size) -> (Tensor, Tensor)
+  self: adaptive_max_pool2d_backward(grad, self, result1)
+  result0: gather(self_t.flatten(-2), -1, result1.flatten(-2)).view_as(result1)
+  output_differentiability: [True, False]
+
+- name: adaptive_max_pool3d(Tensor self, int[3] output_size) -> (Tensor, Tensor)
+  self: adaptive_max_pool3d_backward(grad, self, result1)
+  result0: gather(self_t.flatten(-3), -1, result1.flatten(-3)).view_as(result1)
+  output_differentiability: [True, False]
+
+- name: avg_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None) -> Tensor
+  self: avg_pool2d_backward(grad, self, kernel_size, stride, padding, ceil_mode, count_include_pad, divisor_override)
+  result: auto_linear
+
+- name: avg_pool3d(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None) -> Tensor
+  self: avg_pool3d_backward(grad, self, kernel_size, stride, padding, ceil_mode, count_include_pad, divisor_override)
+  result: auto_linear
+
+- name: fractional_max_pool2d(Tensor self, int[2] kernel_size, int[2] output_size, Tensor random_samples) -> (Tensor, Tensor)
+  self: fractional_max_pool2d_backward(grad, self, kernel_size, output_size, result1)
+  result0: gather(self_t.flatten(-2), -1, result1.flatten(-2)).view_as(result1)
+  output_differentiability: [True, False]
+
+- name: fractional_max_pool3d(Tensor self, int[3] kernel_size, int[3] output_size, Tensor random_samples) -> (Tensor, Tensor)
+  self: fractional_max_pool3d_backward(grad, self, kernel_size, output_size, result1)
+  result0: gather(self_t.flatten(-3), -1, result1.flatten(-3)).view_as(result1)
+  output_differentiability: [True, False]
+
+- name: linear(Tensor input, Tensor weight, Tensor? bias=None) -> Tensor
+  input, weight, bias: "grad.defined() ? linear_backward(input, grad, weight, grad_input_mask) : std::tuple()"
+
+- name: linear_backward(Tensor self, Tensor grad_output, Tensor weight, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+  self, grad_output, weight: linear_double_backward(grads, self, grad_output, weight)
+
+#mps
+- name: max_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor
+  self: max_pool2d_backward(grad, self, kernel_size, stride, padding, dilation, ceil_mode)
+
+- name: _mps_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups) -> Tensor
+  self, weight, bias: "grad.defined() ? mps_convolution_backward_symint(self, grad, weight, padding, stride, dilation, groups, grad_input_mask) : std::tuple()"
+
+- name: mps_convolution_backward(Tensor self, Tensor grad_output, Tensor weight, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+  grad_output, self, weight: _convolution_double_backward_symint(grads[0], grads[1], grads[2], grad_output, weight, self, stride, padding, dilation, false, std::vector(padding.size(), 0), groups, grad_input_mask)
+
+- name: max_pool2d_with_indices(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> (Tensor, Tensor)
+  self: max_pool2d_with_indices_backward(grad, self, kernel_size, stride, padding, dilation, ceil_mode, result1)
+  result0: gather(self_t.flatten(-2), -1, result1.flatten(-2)).view_as(result1)
+  output_differentiability: [True, False]
+
+- name: max_pool3d_with_indices(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> (Tensor, Tensor)
+  self: max_pool3d_with_indices_backward(grad, self, kernel_size, stride, padding, dilation, ceil_mode, result1)
+  result0: gather(self_t.flatten(-3), -1, result1.flatten(-3)).view_as(result1)
+  output_differentiability: [True, False]
+
+- name: max_unpool2d(Tensor self, Tensor indices, SymInt[2] output_size) -> Tensor
+  self: max_pool_double_backward(grad, indices, 2)
+  indices: non_differentiable
+  result: auto_linear
+
+- name: max_unpool3d(Tensor self, Tensor indices, SymInt[3] output_size, int[3] stride, int[3] padding) -> Tensor
+  self: max_pool_double_backward(grad, indices, 3)
+  indices: non_differentiable
+  result: auto_linear
+
+- name: convolution(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups) -> Tensor
+  input, weight, bias: "grad.defined() ? convolution_backward_symint(grad, input, weight, bias->sym_sizes(), stride, padding, dilation, transposed, output_padding, groups, grad_input_mask) : std::tuple()"
+  result: convolution_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, stride, padding, dilation, transposed, output_padding, groups)
+
+# TorchScript serializes calls to _convolution so this entry is present until that is changed to use convolution.
+# Note that the benchmark, deterministic, cudnn_enabled, and allow_tf32 flags are queried from the global context
+# by convolution_backward instead of being passed along from the forward pass.
+- name: _convolution(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool benchmark, bool deterministic, bool cudnn_enabled, bool allow_tf32) -> Tensor
+  input, weight, bias: "grad.defined() ? convolution_backward_symint(grad, input, weight, bias->sym_sizes(), stride, padding, dilation, transposed, output_padding, groups, grad_input_mask) : std::tuple()"
+  result: _convolution_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, stride, padding, dilation, transposed, output_padding, groups, benchmark, deterministic, cudnn_enabled, allow_tf32)
+
+- name: convolution_backward(Tensor grad_output, Tensor input, Tensor weight, SymInt[]? bias_sizes, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+  grad_output, input, weight: _convolution_double_backward_symint(grads[0], grads[1], grads[2], grad_output, weight, input, stride, padding, dilation, transposed, output_padding, groups, grad_input_mask)
+  result0: std::get<0>(convolution_backward_symint(grad_output_p, input_p, weight_t, bias_sizes, stride, padding, dilation, transposed, output_padding, groups, {true, false, false})) + std::get<0>(convolution_backward_symint(grad_output_t, input_p, weight_p, bias_sizes, stride, padding, dilation, transposed, output_padding, groups, {true, false, false}))
+  result1: std::get<1>(convolution_backward_symint(grad_output_p, input_t, weight_p, bias_sizes, stride, padding, dilation, transposed, output_padding, groups, {false, true, false})) + std::get<1>(convolution_backward_symint(grad_output_t, input_p, weight_p, bias_sizes, stride, padding, dilation, transposed, output_padding, groups, {false, true, false}))
+  result2: convolution_backward_jvp_grad_bias(grad_output_t, result2)
+
+- name: convolution_overrideable(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups) -> Tensor
+  input, weight, bias: "grad.defined() ? convolution_backward_overrideable_symint(grad, input, weight, stride, padding, dilation, transposed, output_padding, groups, grad_input_mask) : std::tuple()"
+
+- name: convolution_backward_overrideable(Tensor grad_output, Tensor input, Tensor weight, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias)
+  grad_output, input, weight: _convolution_double_backward_symint(grads[0], grads[1], grads[2], grad_output, weight, input, stride, padding, dilation, transposed, output_padding, groups, grad_input_mask)
+
+- name: slow_conv_transpose2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] output_padding=0, SymInt[2] dilation=1) -> Tensor
+  self, weight, bias: "grad.defined() ? convolution_backward_symint(grad, self, weight, bias->sym_sizes(), stride, padding, dilation, true, output_padding, 1, grad_input_mask) : std::tuple()"
+
+- name: slow_conv_transpose3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] output_padding=0, SymInt[3] dilation=1) -> Tensor
+  self, weight, bias: "grad.defined() ? convolution_backward_symint(grad, self, weight, bias->sym_sizes(), stride, padding, dilation, true, output_padding, 1, grad_input_mask) : std::tuple()"
+
+- name: _slow_conv2d_forward(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding) -> Tensor
+  self, weight, bias: "grad.defined() ? _slow_conv2d_backward_symint(grad, self, weight, kernel_size, stride, padding, grad_input_mask) : std::tuple()"
+
+- name: _slow_conv2d_backward.output_mask(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias)
+  grad_output, self, weight: _convolution_double_backward_symint(grads[0], grads[1], grads[2], grad_output, weight, self, stride, padding, {{1, 1}}, false, {{0, 0}}, 1, grad_input_mask)
+
+- name: _conv_depthwise2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding, SymInt[2] dilation) -> Tensor
+  self, weight, bias: "grad.defined() ? convolution_backward_symint(grad.contiguous(), self, weight, bias->sym_sizes(), stride, padding, dilation, /*transposed=*/ false, /*output_padding=*/ {{0, 0}}, /*groups=*/ 1, grad_input_mask) : std::tuple()"
+
+- name: conv_depthwise3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias, SymInt[3] stride, SymInt[3] padding, SymInt[3] dilation) -> Tensor
+  self, weight, bias: "grad.defined() ? convolution_backward_symint(grad.contiguous(), self, weight, bias->sym_sizes(), stride, padding, dilation, /*transposed=*/ false, /*output_padding=*/ {{0, 0, 0}}, /*groups=*/ 1, grad_input_mask) : std::tuple()"
+
+- name: slow_conv3d_forward(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias, SymInt[3] stride, SymInt[3] padding) -> Tensor
+  self, weight, bias: "grad.defined() ? convolution_backward_symint(grad, self, weight, bias->sym_sizes(), stride, padding, /*dilation=*/ {{1, 1, 1}}, false, /*output_padding=*/ {{0, 0, 0}}, 1, grad_input_mask) : std::tuple()"
+
+- name: slow_conv_dilated2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] dilation=1) -> Tensor
+  self, weight, bias: "grad.defined() ? convolution_backward_symint(grad, self, weight, bias->sym_sizes(), stride, padding, dilation, false, std::vector(padding.size(), 0), 1, grad_input_mask) : std::tuple()"
+
+- name: slow_conv_dilated3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] dilation=1) -> Tensor
+  self, weight, bias: "grad.defined() ? convolution_backward_symint(grad, self, weight, bias->sym_sizes(), stride, padding, dilation, false, std::vector(padding.size(), 0), 1, grad_input_mask) : std::tuple()"
+
+- name: col2im(Tensor self, SymInt[2] output_size, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride) -> Tensor
+  self: im2col(grad, kernel_size, dilation, padding, stride)
+  result: auto_linear
+
+- name: im2col(Tensor self, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride) -> Tensor
+  self: col2im_symint(grad, {self.sym_size(-2), self.sym_size(-1)}, kernel_size, dilation, padding, stride)
+  result: auto_linear
+
+- name: _adaptive_avg_pool2d_backward(Tensor grad_output, Tensor self) -> Tensor
+  grad_output: _adaptive_avg_pool2d_symint(grad, {grad_output.sym_size(-2), grad_output.sym_size(-1)})
+  self: zeros_like(self)
+  result: _adaptive_avg_pool2d_backward(grad_output_t, self_p)
+
+- name: _adaptive_avg_pool3d_backward(Tensor grad_output, Tensor self) -> Tensor
+  grad_output: _adaptive_avg_pool3d_symint(grad, { grad_output.sym_size(-3), grad_output.sym_size(-2), grad_output.sym_size(-1) })
+  self: zeros_like(self)
+  result: _adaptive_avg_pool3d_backward(grad_output_t, self_p)
+
+- name: adaptive_max_pool2d_backward(Tensor grad_output, Tensor self, Tensor indices) -> Tensor
+  grad_output: max_pool_double_backward(grad, indices, 2)
+  self: zeros_like(self)
+  result: auto_linear
+
+- name: adaptive_max_pool3d_backward(Tensor grad_output, Tensor self, Tensor indices) -> Tensor
+  grad_output: max_pool_double_backward(grad, indices, 3)
+  self: zeros_like(self)
+  result: auto_linear
+
+- name: avg_pool2d_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, bool ceil_mode, bool count_include_pad, int? divisor_override) -> Tensor
+  grad_output: avg_pool2d(grad, kernel_size, stride, padding, ceil_mode, count_include_pad, divisor_override)
+  self: zeros_like(self)
+  result: avg_pool2d_backward(grad_output_t, self_p, kernel_size, stride, padding, ceil_mode, count_include_pad, divisor_override)
+
+- name: avg_pool3d_backward(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] stride, int[3] padding, bool ceil_mode, bool count_include_pad, int? divisor_override) -> Tensor
+  grad_output: avg_pool3d(grad, kernel_size, stride, padding, ceil_mode, count_include_pad, divisor_override)
+  self: zeros_like(self)
+  result: avg_pool3d_backward(grad_output_t, self_p, kernel_size, stride, padding, ceil_mode, count_include_pad, divisor_override)
+
+- name: elu_backward(Tensor grad_output, Scalar alpha, Scalar scale, Scalar input_scale, bool is_result, Tensor self_or_result) -> Tensor
+  grad_output: elu_backward(grad, alpha, scale, input_scale, is_result, self_or_result)
+  self_or_result: elu_double_backward(grad, grad_output, alpha, scale, input_scale, is_result, self_or_result)
+  result: elu_backward(grad_output_t, alpha, scale, input_scale, is_result, self_or_result_p) + elu_double_backward(self_or_result_t, grad_output_p, alpha, scale, input_scale, is_result, self_or_result_p)
+
+- name: fractional_max_pool2d_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] output_size, Tensor indices) -> Tensor
+  grad_output: max_pool_double_backward(grad, indices, 2)
+  self: zeros_like(self)
+  result: auto_linear
+
+- name: fractional_max_pool3d_backward(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] output_size, Tensor indices) -> Tensor
+  grad_output: max_pool_double_backward(grad, indices, 3)
+  self: zeros_like(self)
+  result: auto_linear
+
+- name: glu_backward(Tensor grad_output, Tensor self, int dim) -> Tensor
+  grad_output: glu_double_backward_grad_output(grad, self, dim)
+  self: glu_double_backward(grad, grad_output, self, dim)
+  result: glu_backward_jvp(result, grad_output_p, self_p, grad_output_t, self_t, dim)
+
+- name: hardtanh_backward(Tensor grad_output, Tensor self, Scalar min_val, Scalar max_val) -> Tensor
+  grad_output: hardtanh_backward(grad, self, min_val, max_val)
+  self: zeros_like(grad)
+  result: at::where((self_p > min_val).logical_and(self_p < max_val), grad_output_t, at::zeros({}, result.options()).expand_as(result))
+
+- name: log_sigmoid_backward(Tensor grad_output, Tensor self, Tensor buffer) -> Tensor
+  grad_output: log_sigmoid_backward(grad, self, buffer)
+  self: log_sigmoid_double_backward(grad * grad_output, self)
+  result: log_sigmoid_backward(grad_output_t, self_p, buffer) + log_sigmoid_double_backward(self_t * grad_output_p, self_p)
+
+- name: _log_softmax_backward_data(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype) -> Tensor
+  grad_output: grad.to(output.dtype()) - (grad.to(output.dtype()) * output.exp()).sum(dim, true)
+  output: (-grad_output.sum(dim, true) * output.exp() * grad.to(output.dtype())).to(output.dtype())
+
+- name: leaky_relu_backward(Tensor grad_output, Tensor self, Scalar negative_slope, bool self_is_result) -> Tensor
+  # self_is_result is always false here since double backward call is an out-of-place call, self is input itself
+  grad_output: leaky_relu_backward(grad, self, negative_slope, false)
+  self: zeros_like(grad)
+  # leaky_relu_backward(grad_output, self, negative_slope, false)
+  # computes grad_output * at::where(self_p > 0, 1, negative_slope)
+  # so the jvp formula is the following:
+  # grad_output_t * at::where(self_p > 0, self_p.new_ones([]), negative_slope);
+  #
+  # leaky_relu_backward(grad_output, result, negative_slope, true)
+  # computes grad_output * at::where(result > 0, 1, negative_slope)
+  # under the assumption that `negative_slope` is positive (otherwise,
+  # it is not possible to compute the gradient).
+  #
+  # so the jvp formula is the following:
+  # grad_output_t * at::where(result_p > 0, result_p.new_ones([]), negative_slope);
+  # with the assumption that negative_slope is positive.
+  #
+  # Combined together that results in the following optimized kernel which
+  # also checks the assumption that negative_slope is positive when self_is_result
+  # is True:
+  result: leaky_relu_backward(grad_output_t, self_p, negative_slope, self_is_result)
+
+# This derivative is mps-only, and `error_for_max_pool2d_double_backward` just raises an error.
+- name: max_pool2d_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor
+  grad_output: error_for_max_pool2d_double_backward()
+  self: zeros_like(self)
+  result: auto_linear
+
+- name: max_pool2d_with_indices_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, int[2] dilation, bool ceil_mode, Tensor indices) -> Tensor
+  grad_output: max_pool_double_backward(grad, indices, 2)
+  self: zeros_like(self)
+  indices: non_differentiable
+  result: auto_linear
+
+- name: max_pool3d_with_indices_backward(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] stride, int[3] padding, int[3] dilation, bool ceil_mode, Tensor indices) -> Tensor
+  grad_output: max_pool_double_backward(grad, indices, 3)
+  self: zeros_like(self)
+  indices: non_differentiable
+  result: auto_linear
+
+- name: mse_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction) -> Tensor
+  grad_output: mse_loss_backward(grad, self, target, reduction)
+  self: mse_loss_double_backward(grad * grad_output, self, reduction)
+  target: -mse_loss_double_backward(grad * grad_output, target, reduction)
+  result: "  mse_loss_double_backward(self_t * grad_output_p, self_p, reduction)
+           - mse_loss_double_backward(target_t * grad_output_p, target_p, reduction)
+           + mse_loss_backward(grad_output_t, self_p, target_p, reduction)
+          "
+
+- name: nll_loss_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight) -> Tensor
+  grad_output: nll_loss_symint(grad, target, weight, reduction, ignore_index)
+  self: zeros_like(grad)
+  target: non_differentiable
+
+- name: nll_loss2d_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight) -> Tensor
+  grad_output: nll_loss2d_symint(grad, target, weight, reduction, ignore_index)
+  self: zeros_like(grad)
+  target: non_differentiable
+
+- name: rrelu_with_noise_backward(Tensor grad_output, Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, bool self_is_result) -> Tensor
+  # self_is_result is always false here since double backward call is an out-of-place call, self is input itself
+  grad_output: rrelu_with_noise_backward(grad, self, noise, lower, upper, training, false)
+  self: zeros_like(grad)
+  result: rrelu_with_noise_backward(grad_output_t, self_p, noise, lower, upper, training, false)
+
+- name: reflection_pad1d_backward(Tensor grad_output, Tensor self, SymInt[2] padding) -> Tensor
+  grad_output: reflection_pad1d_symint(grad, padding)
+  self: zeros_like(self)
+  result: reflection_pad1d_backward_symint(grad_output_t, self_p, padding)
+
+- name: reflection_pad2d_backward(Tensor grad_output, Tensor self, SymInt[4] padding) -> Tensor
+  grad_output: reflection_pad2d_symint(grad, padding)
+  self: zeros_like(self)
+  result: reflection_pad2d_backward_symint(grad_output_t, self_p, padding)
+
+- name: reflection_pad3d_backward(Tensor grad_output, Tensor self, SymInt[6] padding) -> Tensor
+  grad_output: reflection_pad3d_symint(grad, padding)
+  self: zeros_like(self)
+  result: reflection_pad3d_backward_symint(grad_output_t, self_p, padding)
+
+- name: replication_pad1d_backward(Tensor grad_output, Tensor self, SymInt[2] padding) -> Tensor
+  grad_output: replication_pad1d_symint(grad, padding)
+  self: zeros_like(self)
+  result: replication_pad1d_backward_symint(grad_output_t, self_p, padding)
+
+- name: replication_pad2d_backward(Tensor grad_output, Tensor self, SymInt[4] padding) -> Tensor
+  grad_output: replication_pad2d_symint(grad, padding)
+  self: zeros_like(self)
+  result: replication_pad2d_backward_symint(grad_output_t, self_p, padding)
+
+- name: replication_pad3d_backward(Tensor grad_output, Tensor self, SymInt[6] padding) -> Tensor
+  grad_output: replication_pad3d_symint(grad, padding)
+  self: zeros_like(self)
+  result: replication_pad3d_backward_symint(grad_output_t, self_p, padding)
+
+- name: sparse_sampled_addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+  self, mat1, mat2: "sparse_sampled_addmm_backward(grad,
+                                                   self,
+                                                   wrap_opt_if(mat1, grad_input_mask[2]),
+                                                   wrap_opt_if(mat2, grad_input_mask[1]),
+                                                   alpha, beta, grad_input_mask)"
+
+- name: _sparse_mm_reduce_impl(Tensor self, Tensor other, str reduce) -> (Tensor, Tensor)
+  output_differentiability: [True, False]
+  self, other: "grad.defined() ? _sparse_mm_reduce_impl_backward(self, grad, other, reduce, result1, grad_input_mask) :  std::tuple()"
+
+- name: smooth_l1_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction, float beta) -> Tensor
+  grad_output: smooth_l1_loss_backward(grad, self, target, reduction, beta)
+  self: smooth_l1_loss_double_backward(grad * grad_output, self, target, reduction, beta)
+  target: -smooth_l1_loss_double_backward(grad * grad_output, self, target, reduction, beta)
+  result: "  smooth_l1_loss_double_backward(self_t * grad_output_p, self_p, target_p, reduction, beta)
+           - smooth_l1_loss_double_backward(target_t * grad_output_p, self_p, target_p, reduction, beta)
+           + smooth_l1_loss_backward(grad_output_t, self_p, target_p, reduction, beta)
+          "
+
+- name: huber_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction, float delta) -> Tensor
+  grad_output: huber_loss_double_backward_grad_output(grad, grad_output, self, target, reduction, delta)
+  self: huber_loss_double_backward(grad * grad_output, self, target, reduction, delta)
+  target: -huber_loss_double_backward(grad * grad_output, self, target, reduction, delta)
+
+- name: softplus_backward(Tensor grad_output, Tensor self, Scalar beta, Scalar threshold) -> Tensor
+  grad_output: softplus_backward(grad, self, beta, threshold)
+  self: softplus_double_backward(grad * grad_output, self, beta, threshold)
+  result: "softplus_backward(grad_output_t, self_p, beta, threshold)
+         + softplus_double_backward(self_t * grad_output_p, self_p, beta, threshold)"
+
+- name: _softmax_backward_data(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype) -> Tensor
+  grad_output: _softmax_backward_data(grad.to(output.dtype()), output, dim, input_dtype)
+  output: softmax_double_backward(grad.to(output.dtype()), grad_output, dim, output).to(output.dtype())
+
+- name: soft_margin_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction) -> Tensor
+  grad_output: soft_margin_loss_double_backward_grad_output(grad, grad_output, self, target, reduction)
+  self: soft_margin_loss_double_backward(grad * grad_output, self, target, reduction)
+
+- name: softshrink_backward(Tensor grad_output, Tensor self, Scalar lambd) -> Tensor
+  grad_output: softshrink_backward(grad, self, lambd)
+  self: zeros_like(grad)
+  result: at::where((self_p > lambd).logical_or(self_p < -lambd), grad_output_t, at::zeros({}, result.options()).expand_as(result))
+
+- name: threshold_backward(Tensor grad_output, Tensor self, Scalar threshold) -> Tensor
+  grad_output: threshold_backward(grad, self, threshold)
+  self: zeros_like(grad)
+  result: zeros_like(self_t) + threshold_backward(grad_output_t, self_p, threshold)
+
+- name: upsample_linear1d_backward(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, bool align_corners, float? scales=None) -> Tensor
+  grad_output: upsample_linear1d_symint(grad, output_size, align_corners, scales)
+  result: auto_linear
+
+- name: upsample_bilinear2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+  grad_output: upsample_bilinear2d_symint(grad, output_size, align_corners, scales_h, scales_w)
+  result: auto_linear
+
+- name: _upsample_bilinear2d_aa_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+  grad_output: _upsample_bilinear2d_aa_symint(grad, output_size, align_corners, scales_h, scales_w)
+  result: auto_linear
+
+- name: upsample_bicubic2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+  grad_output: upsample_bicubic2d_symint(grad, output_size, align_corners, scales_h, scales_w)
+  result: auto_linear
+
+- name: _upsample_bicubic2d_aa_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+  grad_output: _upsample_bicubic2d_aa_symint(grad, output_size, align_corners, scales_h, scales_w)
+  result: auto_linear
+
+- name: upsample_trilinear3d_backward(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor
+  grad_output: upsample_trilinear3d_symint(grad, output_size, align_corners, scales_d, scales_h, scales_w)
+  result: auto_linear
+
+- name: upsample_nearest1d_backward(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None) -> Tensor
+  grad_output: upsample_nearest1d_symint(grad, output_size, scales)
+  result: auto_linear
+
+- name: _upsample_nearest_exact1d_backward(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None) -> Tensor
+  grad_output: _upsample_nearest_exact1d_symint(grad, output_size, scales)
+  result: auto_linear
+
+- name: upsample_nearest2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, float? scales_h=None, float? scales_w=None) -> Tensor
+  grad_output: upsample_nearest2d_symint(grad, output_size, scales_h, scales_w)
+  result: auto_linear
+
+- name: _upsample_nearest_exact2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, float? scales_h=None, float? scales_w=None) -> Tensor
+  grad_output: _upsample_nearest_exact2d_symint(grad, output_size, scales_h, scales_w)
+  result: auto_linear
+
+- name: upsample_nearest3d_backward(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor
+  grad_output: upsample_nearest3d_symint(grad, output_size, scales_d, scales_h, scales_w)
+  result: auto_linear
+
+- name: _upsample_nearest_exact3d_backward(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor
+  grad_output: _upsample_nearest_exact3d_symint(grad, output_size, scales_d, scales_h, scales_w)
+  result: auto_linear
+
+- name: sigmoid_backward(Tensor grad_output, Tensor output) -> Tensor
+  grad_output: sigmoid_backward(grad, output.conj())
+  output: grad.conj() * grad_output * (-2 * output.conj() + 1)
+  result: sigmoid_backward(grad_output_t, output_p) + output_t.conj() * grad_output_p * (-2 * output_p.conj() + 1)
+
+- name: tanh_backward(Tensor grad_output, Tensor output) -> Tensor
+  grad_output: tanh_backward(grad, output.conj())
+  output: grad.conj() * (-2 * output.conj() * grad_output)
+  result: tanh_backward(grad_output_t, output_p) + output_t.conj() * (-2 * output_p.conj() * grad_output_p)
+
+# cudnn
+- name: _cudnn_ctc_loss(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank, bool deterministic, bool zero_infinity) -> (Tensor, Tensor)
+  log_probs: _cudnn_ctc_loss_backward(grad, result0, result1, zero_infinity)
+
+- name: _cudnn_ctc_loss.Tensor(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank, bool deterministic, bool zero_infinity) -> (Tensor, Tensor)
+  log_probs: _cudnn_ctc_loss_backward(grad, result0, result1, zero_infinity)
+
+- name: cudnn_convolution_transpose(Tensor self, Tensor weight, SymInt[] padding, SymInt[] output_padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic, bool allow_tf32) -> Tensor
+  self, weight: "_cudnn_convolution_backward(self, grad, weight, padding, output_padding, stride, dilation, true, groups, {grad_input_mask[0], grad_input_mask[1]})"
+
+- name: _mps_convolution_transpose(Tensor self, Tensor weight, SymInt[] padding, SymInt[] output_padding, SymInt[] stride, SymInt[] dilation, SymInt groups) -> Tensor
+  self, weight: "grad.defined() ? mps_convolution_transpose_backward_symint(self, grad, weight, padding, output_padding, stride, dilation, groups, grad_input_mask) : std::tuple()"
+
+- name: cudnn_convolution(Tensor self, Tensor weight, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic, bool allow_tf32) -> Tensor
+  self, weight: "_cudnn_convolution_backward(self, grad, weight, padding, std::vector(padding.size(), 0), stride, dilation, false, groups, {grad_input_mask[0], grad_input_mask[1]})"
+
+- name: cudnn_grid_sampler(Tensor self, Tensor grid) -> Tensor output
+  self, grid: "grad.defined() ? cudnn_grid_sampler_backward(self, grid, grad) : std::tuple()"
+
+- name: cudnn_affine_grid_generator(Tensor theta, int N, int C, int H, int W) -> Tensor grid
+  theta: cudnn_affine_grid_generator_backward(grad, N, C, H, W)
+
+# NB: Why is the backwards here so complicated?  CuDNN cannot be used to compute
+# backward in evaluation mode, because the math for backward in evaluation mode
+# is different (since the forward math is different), and CuDNN does not support
+# it.  And in any case, you shouldn't be using this bn in evaluation mode,
+# because it should be merged into the previous convolution (left for future
+# work.)
+# NB2: The quotes around the gradient are needed to appease YAML parsing rules.
+- name: cudnn_batch_norm(Tensor input, Tensor weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float exponential_average_factor, float epsilon) -> (Tensor, Tensor, Tensor, Tensor)
+  input, weight, bias: "grad.defined() ? (training ? cudnn_batch_norm_backward(input, grad.contiguous(input.suggest_memory_format()), weight, running_mean, running_var, result1, result2, epsilon, retain_variables ? result3.clone() : result3) : native_batch_norm_backward(grad, input, weight, running_mean, running_var, result1, result2, training, epsilon, grad_input_mask)) : std::tuple()"
+  result0: batch_norm_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, running_mean, running_var, result1, result2, training, epsilon)
+
+# HACK: save_mean and save_var are going to be passed in as
+# requires_grad variables (even though we'll never backprop through
+# them) so we need to prevent the unpacking from triggering an error.
+- name: cudnn_batch_norm_backward(Tensor input, Tensor grad_output, Tensor weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var, float epsilon, Tensor reserveSpace) -> (Tensor, Tensor, Tensor)
+  save_mean: not_implemented("cudnn_batch_norm_backward save_mean")
+  save_var: not_implemented("cudnn_batch_norm_backward save_var")
+  reserveSpace: not_implemented("cudnn_batch_norm_backward reserveSpace")
+  input, weight, grad_output: batchnorm_double_backward(input, weight, grads[0], grads[1], grads[2], grad_output, running_mean, running_var, true, epsilon, save_mean, save_var, grad_input_mask)
+
+# nnpack
+
+- name: _nnpack_spatial_convolution(Tensor input, Tensor weight, Tensor? bias, SymInt[2] padding, SymInt[2] stride=1) -> Tensor
+  # NNPACK does not support strided convolutions in the backwards path, which is the reason why we are using the closest available function that does here.
+  input, weight, bias: "grad.defined() ? convolution_backward_symint(grad, input, weight, bias->sym_sizes(), stride, padding, std::vector(padding.size(), 1), false, std::vector(padding.size(), 0), 1, grad_input_mask) : std::tuple()"
+
+#LSTM MPS
+- name: _lstm_mps(Tensor input, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor)
+  output_differentiability: [True, True, True, False, False, False]
+  input, hx, params: "lstm_mps_backward(grads[0], grads[1], grads[2], result3, result4, input, result5, hx, params, has_biases, num_layers, dropout, train, bidirectional, batch_first)"
+
+- name: lstm_mps_backward(Tensor? grad_y, Tensor? grad_hy, Tensor? grad_cy, Tensor z_state, Tensor cell_state_fwd, Tensor input, Tensor layersOutputs, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor[], Tensor[])
+
+
+
+# Only frst three of _cudnn_rnn outputs can have gradients.
+# _cudnn_rnn outputs: (output, hy, cy, reserve, weight_buf)
+- name: _cudnn_rnn(Tensor input, Tensor[] weight, int weight_stride0, Tensor? weight_buf, Tensor hx, Tensor? cx, int mode, SymInt hidden_size, SymInt proj_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, SymInt[] batch_sizes, Tensor? dropout_state) -> (Tensor, Tensor, Tensor, Tensor, Tensor)
+  dropout_state: non_differentiable
+  output_differentiability: [True, True, True, False, False]
+  input, hx, cx, weight: "_cudnn_rnn_backward_symint(input, weight, weight_stride0, result4, hx, cx, result0, grads[0], grads[1], grads[2], mode, hidden_size, proj_size, num_layers, batch_first, dropout, train, bidirectional, batch_sizes, dropout_state, retain_variables ? result3.clone() : result3, grad_input_mask)"
+
+- name: _cudnn_rnn_backward(Tensor input, Tensor[] weight, int weight_stride0, Tensor weight_buf, Tensor hx, Tensor? cx, Tensor output, Tensor? grad_output, Tensor? grad_hy, Tensor? grad_cy, int mode, SymInt hidden_size, SymInt proj_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, SymInt[] batch_sizes, Tensor? dropout_state, Tensor reserve, bool[4] output_mask) -> (Tensor, Tensor, Tensor, Tensor[])
+  dropout_state: non_differentiable
+  input: not_implemented("_cudnn_rnn_backward", kCudnnDoubleBackwardMsg)
+  weight: not_implemented_list("_cudnn_rnn_backward", kCudnnDoubleBackwardMsg)
+  hx: not_implemented("_cudnn_rnn_backward", kCudnnDoubleBackwardMsg)
+  cx: not_implemented("_cudnn_rnn_backward", kCudnnDoubleBackwardMsg)
+  output: not_implemented("_cudnn_rnn_backward", kCudnnDoubleBackwardMsg)
+  grad_output: not_implemented("_cudnn_rnn_backward", kCudnnDoubleBackwardMsg)
+  grad_hy: not_implemented("_cudnn_rnn_backward", kCudnnDoubleBackwardMsg)
+  grad_cy: not_implemented("_cudnn_rnn_backward", kCudnnDoubleBackwardMsg)
+
+# miopen
+
+- name: miopen_convolution_transpose(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] output_padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic) -> Tensor
+  self, weight, bias: "grad.defined() ? convolution_backward_symint(grad, self, weight, bias->sym_sizes(), stride, padding, dilation, true, output_padding, groups, grad_input_mask) : std::tuple()"
+
+- name: miopen_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic) -> Tensor
+  self, weight, bias: "grad.defined() ? convolution_backward_symint(grad, self, weight, bias->sym_sizes(), stride, padding, dilation, false, std::vector(padding.size(), 0), groups, grad_input_mask) : std::tuple()"
+
+- name: miopen_depthwise_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic) -> Tensor
+  self, weight, bias: "grad.defined() ? convolution_backward_symint(grad, self, weight, bias->sym_sizes(), stride, padding, dilation, false, std::vector(padding.size(), 0), groups, grad_input_mask) : std::tuple()"
+
+- name: miopen_batch_norm(Tensor input, Tensor weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float exponential_average_factor, float epsilon) -> (Tensor, Tensor, Tensor)
+  input, weight, bias: "grad.defined() ? (training ? miopen_batch_norm_backward(input, grad.contiguous(), weight, running_mean, running_var, result1, result2, epsilon) : native_batch_norm_backward(grad, input, weight, running_mean, running_var, result1, result2, training, epsilon, grad_input_mask)) : std::tuple()"
+  result0: batch_norm_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, running_mean, running_var, result1, result2, training, epsilon)
+
+- name: miopen_batch_norm_backward(Tensor input, Tensor grad_output, Tensor weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var, float epsilon) -> (Tensor, Tensor, Tensor)
+  save_mean: not_implemented("miopen_batch_norm_backward save_mean")
+  save_var: not_implemented("miopen_batch_norm_backward save_var")
+  input, weight, grad_output: batchnorm_double_backward(input, weight, grads[0], grads[1], grads[2], grad_output, running_mean, running_var, true, epsilon, save_mean, save_var, grad_input_mask)
+
+- name: miopen_rnn(Tensor input, Tensor[] weight, int weight_stride0, Tensor hx, Tensor? cx, int mode, int hidden_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, int[] batch_sizes, Tensor? dropout_state) -> (Tensor, Tensor, Tensor, Tensor, Tensor)
+  dropout_state: non_differentiable
+  output_differentiability: [True, True, True, False, False]
+  input, hx, cx, weight: "miopen_rnn_backward(input, weight, weight_stride0, result4, hx, cx, result0, grads[0], grads[1], grads[2], mode, hidden_size, num_layers, batch_first, dropout, train, bidirectional, batch_sizes, dropout_state, retain_variables ? result3.clone() : result3, grad_input_mask)"
+
+- name: miopen_rnn_backward(Tensor input, Tensor[] weight, int weight_stride0, Tensor weight_buf, Tensor hx, Tensor? cx, Tensor output, Tensor? grad_output, Tensor? grad_hy, Tensor? grad_cy, int mode, int hidden_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, int[] batch_sizes, Tensor? dropout_state, Tensor reserve, bool[4] output_mask) -> (Tensor, Tensor, Tensor, Tensor[])
+  dropout_state: non_differentiable
+
+- name: mkldnn_rnn_layer(Tensor input, Tensor weight0, Tensor weight1, Tensor weight2, Tensor weight3, Tensor hx_, Tensor cx_, bool reverse, int[] batch_sizes, int mode, int hidden_size, int num_layers, bool has_biases, bool bidirectional, bool batch_first, bool train) -> (Tensor, Tensor, Tensor, Tensor)
+  output_differentiability: [True, True, True, False]
+  input, weight0, weight1, weight2, weight3, hx_, cx_: "GradMode::is_enabled() ? mkldnn_rnn_layer_differentiable_backward(input, weight0, weight1, weight2, weight3, hx_, cx_, result0, result1, result2, grads[0], grads[1], grads[2], reverse, mode, hidden_size, num_layers, has_biases, train, bidirectional, batch_sizes, batch_first, result3) : mkldnn_rnn_layer_backward(input, weight0, weight1, weight2, weight3, hx_, cx_, result0, result1, result2, grads[0], grads[1], grads[2], reverse, mode, hidden_size, num_layers, has_biases, train, bidirectional, batch_sizes, batch_first, result3)"
+
+- name: mkldnn_rnn_layer_backward(Tensor input, Tensor weight1, Tensor weight2, Tensor weight3, Tensor weight4, Tensor hx_, Tensor cx_tmp, Tensor output, Tensor hy_, Tensor cy_, Tensor? grad_output, Tensor? grad_hy, Tensor? grad_cy, bool reverse, int mode, int hidden_size, int num_layers, bool has_biases, bool train, bool bidirectional, int[] batch_sizes, bool batch_first, Tensor workspace) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor)
+
+# mkldnn
+- name: mkldnn_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups) -> Tensor
+  self, weight, bias: "grad.defined() ? convolution_backward_symint(grad, self, weight, bias->sym_sizes(), stride, padding, dilation, /*transposed=*/ false, /*output_padding=*/ std::vector(padding.size(), 0), groups, grad_input_mask) : std::tuple()"
+
+- name: mkldnn_linear(Tensor self, Tensor weight, Tensor? bias=None) -> Tensor
+  self, weight, bias: mkldnn_linear_backward(self, grad, weight, grad_input_mask)
+
+- name: mkldnn_max_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor
+  self: mkldnn_max_pool2d_backward(grad, result, self, kernel_size, stride, padding, dilation, ceil_mode)
+
+- name: mkldnn_max_pool3d(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> Tensor
+  self: mkldnn_max_pool3d_backward(grad, result, self, kernel_size, stride, padding, dilation, ceil_mode)
+
+- name: mkldnn_adaptive_avg_pool2d(Tensor self, int[2] output_size) -> Tensor
+  self: mkldnn_adaptive_avg_pool2d_backward(grad, self)
+
+- name: _mkldnn_reshape(Tensor self, int[] shape) -> Tensor
+  self: grad.reshape_symint(self.sym_sizes())
+
+# NestedTensor
+- name: _nested_tensor_from_tensor_list(Tensor[] list, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  list: "grad.defined()? at::unbind(grad) : std::vector(list.size())"
+
+- name: _nested_tensor_from_mask(Tensor t, Tensor mask, bool mask_check=True) -> Tensor
+  t: grad.to_padded_tensor_symint(0, t.sym_sizes())
+  mask: non_differentiable
+
+- name: _nested_from_padded(Tensor padded, Tensor cpu_nested_shape_example, bool fuse_transform_0213=False) -> Tensor
+  padded: _nested_from_padded_backward(grad, padded, fuse_transform_0213)
+  cpu_nested_shape_example: non_differentiable
+
+- name: to_padded_tensor(Tensor self, float padding, SymInt[]? output_size=None) -> Tensor
+  self: "self.layout() == c10::kJagged ? at::_nested_from_padded_tensor_symint(grad, at::_nested_get_offsets(self), at::_nested_get_jagged_dummy(self), at::_nested_get_ragged_idx(self), at::_nested_get_min_seqlen(self).defined() ? std::optional(at::_nested_get_min_seqlen(self)) : ::std::nullopt, at::_nested_get_max_seqlen(self).defined() ? std::optional(at::_nested_get_max_seqlen(self)) : ::std::nullopt, std::optional(at::_nested_get_values(self).sym_size(0))) : at::_nested_from_padded(grad, self._nested_tensor_size())"
+  padding: non_differentiable
+
+- name: _nested_from_padded_tensor(Tensor padded, Tensor offsets, Tensor dummy, int ragged_idx=1, Tensor? min_seqlen=None, Tensor? max_seqlen=None, SymInt? sum_S=None) -> Tensor
+  padded: grad.to_padded_tensor_symint(0.0, at::OptionalArrayRef(padded.sym_sizes()))
+  offsets: non_differentiable
+  dummy: non_differentiable
+
+- name:  _nested_view_from_buffer(Tensor(a) self, Tensor nested_size, Tensor nested_strides, Tensor offsets) -> Tensor(a)
+  self: grad.values()
+  nested_size: non_differentiable
+  nested_strides: non_differentiable
+
+- name: _nested_view_from_jagged(Tensor(a) self, Tensor offsets, Tensor dummy, Tensor? lengths=None, int ragged_idx=1, Tensor? min_seqlen=None, Tensor? max_seqlen=None) -> Tensor(a)
+  self: grad.values()
+  offsets: non_differentiable
+  lengths: non_differentiable
+  dummy: non_differentiable
+  min_seqlen: non_differentiable
+  max_seqlen: non_differentiable
+
+- name: _nested_get_values(Tensor(a) self) -> Tensor(a)
+  self: "_nested_view_from_jagged(grad, at::_nested_get_offsets(self), at::_nested_get_jagged_dummy(self), at::_nested_get_lengths(self), at::_nested_get_ragged_idx(self), at::_nested_get_min_seqlen(self).defined() ? std::optional(at::_nested_get_min_seqlen(self)) : ::std::nullopt, at::_nested_get_max_seqlen(self).defined() ? std::optional(at::_nested_get_max_seqlen(self)) : ::std::nullopt)"
+
+# Transformer
+- name:  _safe_softmax(Tensor self, int dim, ScalarType? dtype=None) -> Tensor
+  self: _softmax_backward_data(grad, result, dim, self.scalar_type())
+  result: result * (self_t - safe_logsumexp_jvp(self_p, self_t, {dim}, true))
+
+- name: _scaled_dot_product_efficient_attention(Tensor query, Tensor key, Tensor value, Tensor? attn_bias, bool compute_log_sumexp, float dropout_p=0.0, bool is_causal=False, *, float? scale=None) -> (Tensor output, Tensor log_sumexp, Tensor philox_seed, Tensor philox_offset)
+  output_differentiability: [True, False, False, False]
+  query, key, value, attn_bias: _scaled_dot_product_efficient_attention_backward(grad, query, key, value, attn_bias, output, log_sumexp, philox_seed, philox_offset, dropout_p, grad_input_mask, is_causal, scale)
+
+- name: _scaled_dot_product_flash_attention(Tensor query, Tensor key, Tensor value, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor rng_state, Tensor unused, Tensor debug_attn_mask)
+  output_differentiability: [True, False, False, False, False, False, False, False, False]
+  query, key, value: _scaled_dot_product_flash_attention_backward_symint(grad, query, key, value, output, logsumexp, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, rng_state, unused, scale)
+
+- name: _scaled_dot_product_flash_attention_for_cpu(Tensor query, Tensor key, Tensor value, float dropout_p=0.0, bool is_causal=False, *, Tensor? attn_mask=None, float? scale=None) -> (Tensor output, Tensor logsumexp)
+  output_differentiability: [True, False]
+  query, key, value: _scaled_dot_product_flash_attention_for_cpu_backward(grad, query, key, value, output, logsumexp, dropout_p, is_causal, attn_mask, scale)
+
+- name: _flash_attention_forward(Tensor query, Tensor key, Tensor value, Tensor? cum_seq_q, Tensor? cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, bool return_debug_mask, *, float? scale=None, SymInt? window_size_left=None, SymInt? window_size_right=None, Tensor? seqused_k=None, Tensor? alibi_slopes=None) -> (Tensor output, Tensor softmax_logsumexp, Tensor rng_state, Tensor unused, Tensor debug_attn_mask)
+  output_differentiability: [True, False, False, False, False]
+  query, key, value: _flash_attention_backward_symint(grad, query, key, value, output, softmax_logsumexp, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, rng_state, unused, scale, window_size_left, window_size_right)
+
+- name: _efficient_attention_forward(Tensor query, Tensor key, Tensor value, Tensor? bias, Tensor? cu_seqlens_q, Tensor? cu_seqlens_k, SymInt? max_seqlen_q, SymInt? max_seqlen_k, float dropout_p, int custom_mask_type, bool compute_log_sumexp=False, *, float? scale=None, Tensor? seqlen_k=None, int? window_size=None) -> (Tensor output, Tensor logsumexp, Tensor philox_seed, Tensor philox_offset, SymInt max_seqlen_batch_q, SymInt max_seqlen_batch_k)
+  output_differentiability: [True, False, False, False, False, False]
+  query, key, value, bias: _efficient_attention_backward_symint(grad, query, key, value, bias, output, cu_seqlens_q, cu_seqlens_k, max_seqlen_batch_q, max_seqlen_batch_k, logsumexp, dropout_p, philox_seed, philox_offset, custom_mask_type, bias.requires_grad(), scale)
+
+- name: _cudnn_attention_forward(Tensor query, Tensor key, Tensor value, Tensor? attn_bias, Tensor? cum_seq_q, Tensor? cum_seq_k, SymInt max_q, SymInt max_k, bool compute_log_sumexp, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor philox_seed, Tensor philox_offset, Tensor debug_attn_mask)
+  output_differentiability: [True, False, False, False, False, False, False, False, False]
+  query, key, value: _cudnn_attention_backward_symint(grad, query, key, value, output, logsumexp, philox_seed, philox_offset, attn_bias, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, scale)
+
+- name: _scaled_dot_product_cudnn_attention(Tensor query, Tensor key, Tensor value, Tensor? attn_bias, bool compute_log_sumexp, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor philox_seed, Tensor philox_offset, Tensor debug_attn_mask)
+  output_differentiability: [True, False, False, False, False, False, False, False, False]
+  query, key, value: _scaled_dot_product_cudnn_attention_backward_symint(grad, query, key, value, output, logsumexp, philox_seed, philox_offset, attn_bias, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, scale)
+
+- name: _scaled_dot_product_fused_attention_overrideable(Tensor query, Tensor key, Tensor value, Tensor? attn_bias=None, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor philox_seed, Tensor philox_offset, Tensor debug_attn_mask)
+  output_differentiability: [True, False, False, False, False, False, False, False, False]
+  query, key, value, attn_bias: _scaled_dot_product_fused_attention_overrideable_backward_symint(grad, query, key, value, attn_bias, grad_input_mask, output, logsumexp, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, philox_seed, philox_offset, scale)
+
+# fft
+- name: _fft_r2c(Tensor self, int[] dim, int normalization, bool onesided) -> Tensor
+  self: fft_r2c_backward(grad, dim, normalization, onesided, self.sym_size(dim.back()))
+  result: auto_linear
+
+- name: _fft_c2r(Tensor self, int[] dim, int normalization, SymInt last_dim_size) -> Tensor
+  self: fft_c2r_backward(grad, dim, normalization)
+  result: auto_linear
+
+- name: _fft_c2c(Tensor self, SymInt[] dim, int normalization, bool forward) -> Tensor
+  self: _fft_c2c_symint(grad, dim, normalization, !forward)
+  result: auto_linear
+
+- name: unbind.int(Tensor(a -> *) self, int dim=0) -> Tensor(a)[]
+  dispatch:
+    Default:
+      self: unbind_backward(grads, dim)
+      result: auto_linear
+    AutogradNestedTensor:
+      self: "self.layout() == c10::kJagged ? unbind_backward_nested_jagged(grads, self, dim) : unbind_backward_nested(grads, at::native::get_nested_tensor_impl(self)->get_nested_sizes(), dim, self.options())"
+      result: auto_linear
+
+- name: stack(Tensor[] tensors, int dim=0) -> Tensor
+  tensors: stack_tensors_backward(grad, dim, to_args_scalartypes(tensors))
+  result: stack_jvp(tensors, dim)
+
+# fused RNN kernels
+
+# Only frst two of _thnn_fused_lstm_cell outputs can have gradients.
+# _thnn_fused_lstm_cell outputs: (hy, cy, workspace)
+- name: _thnn_fused_lstm_cell(Tensor input_gates, Tensor hidden_gates, Tensor cx, Tensor? input_bias=None, Tensor? hidden_bias=None) -> (Tensor, Tensor, Tensor)
+  output_differentiability: [True, True, False]
+  input_gates, hidden_gates, cx, input_bias, hidden_bias: "GradMode::is_enabled() ? _thnn_differentiable_lstm_cell_backward(grads[0], grads[1], input_gates, hidden_gates, input_bias, hidden_bias, cx, result1) : _thnn_fused_lstm_cell_backward(grads[0], grads[1], cx, result1, result2, input_bias.defined())"
+
+- name: _thnn_fused_gru_cell(Tensor input_gates, Tensor hidden_gates, Tensor hx, Tensor? input_bias=None, Tensor? hidden_bias=None) -> (Tensor, Tensor)
+  input_gates, hidden_gates, hx, input_bias, hidden_bias: "grad.defined() ? (GradMode::is_enabled() ? _thnn_differentiable_gru_cell_backward(grad, input_gates, hidden_gates, hx, input_bias, hidden_bias) : _thnn_fused_gru_cell_backward(grad, result1, input_bias.defined())) : std::tuple()"
+
+# PackedSequence helpers
+- name: _pack_padded_sequence(Tensor input, Tensor lengths, bool batch_first) -> (Tensor, Tensor)
+  input: _pack_padded_sequence_backward_symint(grad, input.sym_sizes(), result1, batch_first)
+
+# TH wrappers
+- name: eq.Scalar(Tensor self, Scalar other) -> Tensor
+  output_differentiability: [False]
+
+- name: eq.Tensor(Tensor self, Tensor other) -> Tensor
+  output_differentiability: [False]
+
+- name: ge.Scalar(Tensor self, Scalar other) -> Tensor
+  output_differentiability: [False]
+
+- name: ge.Tensor(Tensor self, Tensor other) -> Tensor
+  output_differentiability: [False]
+
+- name: gt.Scalar(Tensor self, Scalar other) -> Tensor
+  output_differentiability: [False]
+
+- name: gt.Tensor(Tensor self, Tensor other) -> Tensor
+  output_differentiability: [False]
+
+- name: le.Scalar(Tensor self, Scalar other) -> Tensor
+  output_differentiability: [False]
+
+- name: le.Tensor(Tensor self, Tensor other) -> Tensor
+  output_differentiability: [False]
+
+- name: lt.Scalar(Tensor self, Scalar other) -> Tensor
+  output_differentiability: [False]
+
+- name: lt.Tensor(Tensor self, Tensor other) -> Tensor
+  output_differentiability: [False]
+
+- name: ne.Scalar(Tensor self, Scalar other) -> Tensor
+  output_differentiability: [False]
+
+- name: ne.Tensor(Tensor self, Tensor other) -> Tensor
+  output_differentiability: [False]
+
+- name: multinomial(Tensor self, SymInt num_samples, bool replacement=False, *, Generator? generator=None) -> Tensor
+  output_differentiability: [False]
+
+- name: nonzero(Tensor self) -> Tensor
+  output_differentiability: [False]
+
+- name: segment_reduce(Tensor data, str reduce, *, Tensor? lengths=None, Tensor? indices=None, Tensor? offsets=None, int axis=0, bool unsafe=False, Scalar? initial=None) -> Tensor
+  data: _segment_reduce_backward(grad, result, data, reduce, lengths, offsets, axis, initial)
+
+- name: _pin_memory(Tensor self, Device? device=None) -> Tensor
+  self: grad
+
+- name: _new_zeros_with_same_feature_meta(Tensor self, Tensor other, *, int self_num_batch_dims=0) -> Tensor
+  self: non_differentiable
+  other: non_differentiable
+  output_differentiability: [False]
+
+- name: _test_warn_in_autograd(Tensor self) -> Tensor
+  self: warn_backwards(grad)
+
+- name: _test_autograd_multiple_dispatch.fullcoverage(Tensor self) -> Tensor
+  dispatch:
+    Default:
+      self: grad.expand_symint(self.sym_sizes()) + 1
+      result: auto_linear
+    AutogradNestedTensor:
+      self: grad.mul(grad)
+    AutogradCUDA:
+      self: grad.expand_symint(self.sym_sizes()) * 2
+
+- name: _test_autograd_multiple_dispatch.ntonly(Tensor self, bool b) -> Tensor
+  dispatch:
+    AutogradNestedTensor:
+      self: grad.mul(grad).add(grad)
+
+- name: _test_autograd_multiple_dispatch_view(Tensor(a) self) -> Tensor(a)
+  dispatch:
+    Default:
+      self: grad.reshape_as(self)
+    AutogradCUDA:
+      self: grad.reshape_as(self) + 1
+
+- name: _efficientzerotensor(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+  output_differentiability: [False]
+
+- name: scatter_reduce.two(Tensor self, int dim, Tensor index, Tensor src, str reduce, *, bool include_self=True) -> Tensor
+  self, src: scatter_reduce_backward(grad, self, dim, index, src, reduce, include_self, result)
+  index: non_differentiable
+  result: scatter_reduce_jvp(self_p, self_t, dim, index, src_p, src_t, reduce, include_self, result)
+
+- name: special_airy_ai(Tensor x) -> Tensor
+  x: non_differentiable
+
+- name: special_bessel_j0(Tensor self) -> Tensor
+  self: non_differentiable
+
+- name: special_bessel_j1(Tensor self) -> Tensor
+  self: non_differentiable
+
+- name: special_bessel_y0(Tensor self) -> Tensor
+  self: non_differentiable
+
+- name: special_bessel_y1(Tensor self) -> Tensor
+  self: non_differentiable
+
+- name: special_chebyshev_polynomial_t(Tensor x, Tensor n) -> Tensor
+  x: non_differentiable
+  n: non_differentiable
+
+- name: special_chebyshev_polynomial_t.x_scalar(Scalar x, Tensor n) -> Tensor
+  n: non_differentiable
+
+- name: special_chebyshev_polynomial_t.n_scalar(Tensor x, Scalar n) -> Tensor
+  x: non_differentiable
+
+- name: special_chebyshev_polynomial_u(Tensor x, Tensor n) -> Tensor
+  x: non_differentiable
+  n: non_differentiable
+
+- name: special_chebyshev_polynomial_u.x_scalar(Scalar x, Tensor n) -> Tensor
+  n: non_differentiable
+
+- name: special_chebyshev_polynomial_u.n_scalar(Tensor x, Scalar n) -> Tensor
+  x: non_differentiable
+
+- name: special_chebyshev_polynomial_v(Tensor x, Tensor n) -> Tensor
+  x: non_differentiable
+  n: non_differentiable
+
+- name: special_chebyshev_polynomial_v.x_scalar(Scalar x, Tensor n) -> Tensor
+  n: non_differentiable
+
+- name: special_chebyshev_polynomial_v.n_scalar(Tensor x, Scalar n) -> Tensor
+  x: non_differentiable
+
+- name: special_chebyshev_polynomial_w(Tensor x, Tensor n) -> Tensor
+  x: non_differentiable
+  n: non_differentiable
+
+- name: special_chebyshev_polynomial_w.x_scalar(Scalar x, Tensor n) -> Tensor
+  n: non_differentiable
+
+- name: special_chebyshev_polynomial_w.n_scalar(Tensor x, Scalar n) -> Tensor
+  x: non_differentiable
+
+- name: special_hermite_polynomial_h(Tensor x, Tensor n) -> Tensor
+  x: non_differentiable
+  n: non_differentiable
+
+- name: special_hermite_polynomial_h.x_scalar(Scalar x, Tensor n) -> Tensor
+  n: non_differentiable
+
+- name: special_hermite_polynomial_h.n_scalar(Tensor x, Scalar n) -> Tensor
+  x: non_differentiable
+
+- name: special_hermite_polynomial_he(Tensor x, Tensor n) -> Tensor
+  x: non_differentiable
+  n: non_differentiable
+
+- name: special_hermite_polynomial_he.x_scalar(Scalar x, Tensor n) -> Tensor
+  n: non_differentiable
+
+- name: special_hermite_polynomial_he.n_scalar(Tensor x, Scalar n) -> Tensor
+  x: non_differentiable
+
+- name: special_laguerre_polynomial_l(Tensor x, Tensor n) -> Tensor
+  x: non_differentiable
+  n: non_differentiable
+
+- name: special_laguerre_polynomial_l.x_scalar(Scalar x, Tensor n) -> Tensor
+  n: non_differentiable
+
+- name: special_laguerre_polynomial_l.n_scalar(Tensor x, Scalar n) -> Tensor
+  x: non_differentiable
+
+- name: special_legendre_polynomial_p(Tensor x, Tensor n) -> Tensor
+  x: non_differentiable
+  n: non_differentiable
+
+- name: special_legendre_polynomial_p.x_scalar(Scalar x, Tensor n) -> Tensor
+  n: non_differentiable
+
+- name: special_legendre_polynomial_p.n_scalar(Tensor x, Scalar n) -> Tensor
+  x: non_differentiable
+
+- name: special_modified_bessel_i0(Tensor self) -> Tensor
+  self: non_differentiable
+
+- name: special_modified_bessel_i1(Tensor self) -> Tensor
+  self: non_differentiable
+
+- name: special_modified_bessel_k0(Tensor self) -> Tensor
+  self: non_differentiable
+
+- name: special_modified_bessel_k1(Tensor self) -> Tensor
+  self: non_differentiable
+
+- name: special_scaled_modified_bessel_k0(Tensor x) -> Tensor
+  x: non_differentiable
+
+- name: special_scaled_modified_bessel_k1(Tensor x) -> Tensor
+  x: non_differentiable
+
+- name: special_shifted_chebyshev_polynomial_t(Tensor x, Tensor n) -> Tensor
+  x: non_differentiable
+  n: non_differentiable
+
+- name: special_shifted_chebyshev_polynomial_t.x_scalar(Scalar x, Tensor n) -> Tensor
+  n: non_differentiable
+
+- name: special_shifted_chebyshev_polynomial_t.n_scalar(Tensor x, Scalar n) -> Tensor
+  x: non_differentiable
+
+- name: special_shifted_chebyshev_polynomial_u(Tensor x, Tensor n) -> Tensor
+  x: non_differentiable
+  n: non_differentiable
+
+- name: special_shifted_chebyshev_polynomial_u.x_scalar(Scalar x, Tensor n) -> Tensor
+  n: non_differentiable
+
+- name: special_shifted_chebyshev_polynomial_u.n_scalar(Tensor x, Scalar n) -> Tensor
+  x: non_differentiable
+
+- name: special_shifted_chebyshev_polynomial_v(Tensor x, Tensor n) -> Tensor
+  x: non_differentiable
+  n: non_differentiable
+
+- name: special_shifted_chebyshev_polynomial_v.x_scalar(Scalar x, Tensor n) -> Tensor
+  n: non_differentiable
+
+- name: special_shifted_chebyshev_polynomial_v.n_scalar(Tensor x, Scalar n) -> Tensor
+  x: non_differentiable
+
+- name: special_shifted_chebyshev_polynomial_w(Tensor x, Tensor n) -> Tensor
+  x: non_differentiable
+  n: non_differentiable
+
+- name: special_shifted_chebyshev_polynomial_w.x_scalar(Scalar x, Tensor n) -> Tensor
+  n: non_differentiable
+
+- name: special_shifted_chebyshev_polynomial_w.n_scalar(Tensor x, Scalar n) -> Tensor
+  x: non_differentiable
+
+- name: special_spherical_bessel_j0(Tensor x) -> Tensor
+  x: non_differentiable
+
+- name: _reshape_copy(Tensor self, SymInt[] size) -> Tensor
+  self: grad.reshape_symint(self.sym_sizes())
+  result: auto_linear
+
+# note(crcrpar): `torchgen/api/autograd` logic would unwantedly replace substrings of `self` and `other` of function names.
+- name: _foreach_div.List(Tensor[] self, Tensor[] other) -> Tensor[]
+  self: div_tensor_self_backward(grads[i], other[i], self[i].scalar_type())
+  other: div_tensor_other_backward(grads[i], self[i], other[i])
+  result: (self_t - other_t * result[i]) / other_p
+
+- name: _foreach_pow.List(Tensor[] self, Tensor[] exponent) -> Tensor[]
+  self: pow_backward_self(grads[i], self[i], exponent[i])
+  exponent: pow_backward_exponent(grads[i], self[i], exponent[i], result[i])
+  result: (pow_backward_self(self_t.conj(), self_p, exponent_p) + pow_backward_exponent(exponent_t.conj(), self_p, exponent_p, result[i])).conj()
+
+- name: _foreach_pow.ScalarList(Tensor[] self, Scalar[] exponent) -> Tensor[]
+  self: pow_backward(grads[i], self[i], exponent[i])
+  result: pow_backward(self_t.conj(), self_p, exponent[i]).conj()
+
+- name: _foreach_pow.ScalarAndTensor(Scalar self, Tensor[] exponent) -> Tensor[]
+  exponent: pow_backward_exponent(grads[i], self, exponent[i], result[i])
+
+# note(crcrpar): following definitions seem necessary because the reference native functions
+# of `maximum` and `minimum` don't have the overload def with Scalar as their second argument.
+- name: _foreach_minimum.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
+  self: at::where(self[i] == scalar, grads[i] / 2, grads[i]).masked_fill_(self[i] > scalar, 0)
+  result: scalar + at::where(self_p == scalar, at::scalar_tensor(0.5, result[i].options()), (self_p < scalar).to(result[i].scalar_type())) * (self_t - scalar)
+
+- name: _foreach_minimum.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
+  self: at::where(self[i] == scalars[i], grads[i] / 2, grads[i]).masked_fill_(self[i] > scalars[i], 0)
+  result: scalars[i] + at::where(self_p == scalars[i], at::scalar_tensor(0.5, result[i].options()), (self_p < scalars[i]).to(result[i].scalar_type())) * (self_t - scalars[i])
+
+- name: _foreach_maximum.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
+  self: at::where(self[i] == scalar, grads[i] / 2, grads[i]).masked_fill_(self[i] < scalar, 0)
+  result: scalar + at::where(self_p == scalar, at::scalar_tensor(0.5, result[i].options()), (self_p > scalar).to(result[i].scalar_type())) * (self_t - scalar)
+
+- name: _foreach_maximum.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
+  self: at::where(self[i] == scalars[i], grads[i] / 2, grads[i]).masked_fill_(self[i] < scalars[i], 0)
+  result: scalars[i] + at::where(self_p == scalars[i], at::scalar_tensor(0.5, result[i].options()), (self_p > scalars[i]).to(result[i].scalar_type())) * (self_t - scalars[i])
+
+# note(crcrpar): forward-mode AD is tricky for a simple string replace to handle:
+#   formula.replace("p", "ord") produces `norm_jvord(self_ord, self_t, ord, result)`
+- name: _foreach_norm.Scalar(Tensor[] self, Scalar ord=2, ScalarType? dtype=None) -> Tensor[]
+  self: norm_backward(grads[i], self[i], ord, result[i])
+  result: norm_jvp(self_p, self_t, ord, result[i])
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_annotated_fn_args.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_annotated_fn_args.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f61209fa6fd0041b732f1400e1162d2f124ad34
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_annotated_fn_args.py
@@ -0,0 +1,134 @@
+"""
+For procedural tests needed for __torch_function__, we use this function
+to export method names and signatures as needed by the tests in
+test/test_overrides.py.
+
+python -m tools.autograd.gen_annotated_fn_args \
+       aten/src/ATen/native/native_functions.yaml \
+       aten/src/ATen/native/tags.yaml \
+       $OUTPUT_DIR \
+       tools/autograd
+
+Where $OUTPUT_DIR is where you would like the files to be
+generated.  In the full build system, OUTPUT_DIR is
+torch/testing/_internal/generated
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import textwrap
+from collections import defaultdict
+from typing import Any, TYPE_CHECKING
+
+import torchgen.api.python as python
+from torchgen.context import with_native_function
+from torchgen.gen import parse_native_yaml
+from torchgen.utils import FileManager
+
+from .gen_python_functions import (
+    is_py_fft_function,
+    is_py_linalg_function,
+    is_py_nn_function,
+    is_py_special_function,
+    is_py_torch_function,
+    is_py_variable_method,
+    should_generate_py_binding,
+)
+
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+
+    from torchgen.model import Argument, BaseOperatorName, NativeFunction
+
+
+def gen_annotated(
+    native_yaml_path: str, tags_yaml_path: str, out: str, autograd_dir: str
+) -> None:
+    native_functions = parse_native_yaml(
+        native_yaml_path, tags_yaml_path
+    ).native_functions
+    mappings = (
+        (is_py_torch_function, "torch._C._VariableFunctions"),
+        (is_py_nn_function, "torch._C._nn"),
+        (is_py_linalg_function, "torch._C._linalg"),
+        (is_py_special_function, "torch._C._special"),
+        (is_py_fft_function, "torch._C._fft"),
+        (is_py_variable_method, "torch.Tensor"),
+    )
+    annotated_args: list[str] = []
+    for pred, namespace in mappings:
+        groups: dict[BaseOperatorName, list[NativeFunction]] = defaultdict(list)
+        for f in native_functions:
+            if not should_generate_py_binding(f) or not pred(f):
+                continue
+            groups[f.func.name.name].append(f)
+        for group in groups.values():
+            for f in group:
+                annotated_args.append(f"{namespace}.{gen_annotated_args(f)}")
+
+    template_path = os.path.join(autograd_dir, "templates")
+    fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
+    fm.write_with_template(
+        "annotated_fn_args.py",
+        "annotated_fn_args.py.in",
+        lambda: {
+            "annotated_args": textwrap.indent("\n".join(annotated_args), "    "),
+        },
+    )
+
+
+@with_native_function
+def gen_annotated_args(f: NativeFunction) -> str:
+    def _get_kwargs_func_exclusion_list() -> list[str]:
+        # functions that currently don't work with kwargs in test_overrides.py
+        return [
+            "diagonal",
+            "round_",
+            "round",
+            "scatter_",
+        ]
+
+    def _add_out_arg(
+        out_args: list[dict[str, Any]], args: Sequence[Argument], *, is_kwarg_only: bool
+    ) -> None:
+        for arg in args:
+            if arg.default is not None:
+                continue
+            out_arg: dict[str, Any] = {}
+            out_arg["is_kwarg_only"] = str(is_kwarg_only)
+            out_arg["name"] = arg.name
+            out_arg["simple_type"] = python.argument_type_str(
+                arg.type, simple_type=True
+            )
+            size_t = python.argument_type_size(arg.type)
+            if size_t:
+                out_arg["size"] = size_t
+            out_args.append(out_arg)
+
+    out_args: list[dict[str, Any]] = []
+    _add_out_arg(out_args, f.func.arguments.flat_positional, is_kwarg_only=False)
+    if f"{f.func.name.name}" not in _get_kwargs_func_exclusion_list():
+        _add_out_arg(out_args, f.func.arguments.flat_kwarg_only, is_kwarg_only=True)
+
+    return f"{f.func.name.name}: {repr(out_args)},"
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(description="Generate annotated_fn_args script")
+    parser.add_argument(
+        "native_functions", metavar="NATIVE", help="path to native_functions.yaml"
+    )
+    parser.add_argument("tags", metavar="TAGS", help="path to tags.yaml")
+    parser.add_argument("out", metavar="OUT", help="path to output directory")
+    parser.add_argument(
+        "autograd", metavar="AUTOGRAD", help="path to template directory"
+    )
+    args = parser.parse_args()
+    gen_annotated(args.native_functions, args.tags, args.out, args.autograd)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_autograd.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_autograd.py
new file mode 100644
index 0000000000000000000000000000000000000000..d93d3f4cab4a6f37c0c81c548b4da3b6c5b9dc95
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_autograd.py
@@ -0,0 +1,147 @@
+"""
+To run this file by hand from the root of the PyTorch
+repository, run:
+
+python -m tools.autograd.gen_autograd \
+       aten/src/ATen/native/native_functions.yaml \
+       aten/src/ATen/native/tags.yaml \
+       $OUTPUT_DIR \
+       tools/autograd
+
+Where $OUTPUT_DIR is where you would like the files to be
+generated.  In the full build system, OUTPUT_DIR is
+torch/csrc/autograd/generated/
+"""
+
+# gen_autograd.py generates C++ autograd functions and Python bindings.
+#
+# It delegates to the following scripts:
+#
+#  gen_autograd_functions.py: generates subclasses of torch::autograd::Node
+#  gen_variable_type.py: generates VariableType.h which contains all tensor methods
+#  gen_python_functions.py: generates Python bindings to THPVariable
+#
+
+from __future__ import annotations
+
+import argparse
+import os
+
+from torchgen.api import cpp
+from torchgen.api.autograd import (
+    match_differentiability_info,
+    NativeFunctionWithDifferentiabilityInfo,
+)
+from torchgen.gen import parse_native_yaml
+from torchgen.selective_build.selector import SelectiveBuilder
+
+from . import gen_python_functions
+from .gen_autograd_functions import (
+    gen_autograd_functions_lib,
+    gen_autograd_functions_python,
+)
+from .gen_inplace_or_view_type import gen_inplace_or_view_type
+from .gen_trace_type import gen_trace_type
+from .gen_variable_factories import gen_variable_factories
+from .gen_variable_type import gen_variable_type
+from .gen_view_funcs import gen_view_funcs
+from .load_derivatives import load_derivatives
+
+
+def gen_autograd(
+    native_functions_path: str,
+    tags_path: str,
+    out: str,
+    autograd_dir: str,
+    operator_selector: SelectiveBuilder,
+    disable_autograd: bool = False,
+) -> None:
+    # Parse and load derivatives.yaml
+    differentiability_infos, used_dispatch_keys = load_derivatives(
+        os.path.join(autograd_dir, "derivatives.yaml"), native_functions_path, tags_path
+    )
+
+    template_path = os.path.join(autograd_dir, "templates")
+
+    native_funcs = parse_native_yaml(native_functions_path, tags_path).native_functions
+    fns = sorted(
+        filter(
+            operator_selector.is_native_function_selected_for_training, native_funcs
+        ),
+        key=lambda f: cpp.name(f.func),
+    )
+    fns_with_diff_infos: list[NativeFunctionWithDifferentiabilityInfo] = (
+        match_differentiability_info(fns, differentiability_infos)
+    )
+
+    # Generate VariableType.h/cpp
+    if not disable_autograd:
+        gen_variable_type(
+            out,
+            native_functions_path,
+            tags_path,
+            fns_with_diff_infos,
+            template_path,
+            used_dispatch_keys,
+        )
+
+        gen_inplace_or_view_type(
+            out, native_functions_path, tags_path, fns_with_diff_infos, template_path
+        )
+
+        # operator filter not applied as tracing sources are excluded in selective build
+        gen_trace_type(out, native_funcs, template_path)
+    # Generate Functions.h/cpp
+    gen_autograd_functions_lib(out, differentiability_infos, template_path)
+
+    # Generate variable_factories.h
+    gen_variable_factories(out, native_functions_path, tags_path, template_path)
+
+    # Generate ViewFuncs.h/cpp
+    gen_view_funcs(out, fns_with_diff_infos, template_path)
+
+
+def gen_autograd_python(
+    native_functions_path: str,
+    tags_path: str,
+    out: str,
+    autograd_dir: str,
+) -> None:
+    differentiability_infos, _ = load_derivatives(
+        os.path.join(autograd_dir, "derivatives.yaml"), native_functions_path, tags_path
+    )
+
+    template_path = os.path.join(autograd_dir, "templates")
+
+    # Generate Functions.h/cpp
+    gen_autograd_functions_python(out, differentiability_infos, template_path)
+
+    # Generate Python bindings
+    deprecated_path = os.path.join(autograd_dir, "deprecated.yaml")
+    gen_python_functions.gen(
+        out, native_functions_path, tags_path, deprecated_path, template_path
+    )
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(description="Generate autograd C++ files script")
+    parser.add_argument(
+        "native_functions", metavar="NATIVE", help="path to native_functions.yaml"
+    )
+    parser.add_argument("tags", metavar="NATIVE", help="path to tags.yaml")
+    parser.add_argument("out", metavar="OUT", help="path to output directory")
+    parser.add_argument(
+        "autograd", metavar="AUTOGRAD", help="path to autograd directory"
+    )
+    args = parser.parse_args()
+    gen_autograd(
+        args.native_functions,
+        args.tags,
+        args.out,
+        args.autograd,
+        SelectiveBuilder.get_nop_selector(),
+    )
+
+
+if __name__ == "__main__":
+    main()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_autograd_functions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_autograd_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdc805d5a4b50aea474939e437716cad7b0231d0
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_autograd_functions.py
@@ -0,0 +1,1074 @@
+# Generates C++ autograd functions for the derivatives of ATen operations
+#
+# This writes two files:
+#  Functions.h/cpp: subclasses of autograd::Node
+#  python_functions.h/cpp: Python bindings for the above classes
+#
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from torchgen.api.autograd import (
+    Derivative,
+    DifferentiabilityInfo,
+    SavedAttribute,
+    uses_retain_variables,
+    uses_single_grad,
+)
+from torchgen.api.types import (
+    ArrayRefCType,
+    BaseCppType,
+    BaseCType,
+    Binding,
+    boolT,
+    doubleT,
+    intArrayRefT,
+    iTensorListRefT,
+    ListCType,
+    longT,
+    MutRefCType,
+    OptionalCType,
+    optionalIntArrayRefT,
+    optionalSymIntArrayRefT,
+    scalarT,
+    stringT,
+    symIntArrayRefT,
+    SymIntT,
+    TENSOR_LIST_LIKE_CTYPES,
+    tensorListT,
+    tensorT,
+    VectorCType,
+)
+from torchgen.code_template import CodeTemplate
+from torchgen.model import Argument, FunctionSchema
+from torchgen.utils import FileManager
+
+from .gen_inplace_or_view_type import VIEW_FUNCTIONS
+
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+
+
+FUNCTION_DECLARATION = CodeTemplate(
+    """\
+#ifdef _WIN32
+struct ${op} : public ${superclass} {
+  TORCH_API ${op}() = default;
+#else
+struct TORCH_API ${op} : public ${superclass} {
+#endif
+  using ${superclass}::${superclass};
+  variable_list apply(variable_list&& grads) override;
+  std::string name() const override { return "${op}"; }
+  void release_variables() override {
+    ${thread_lock}
+    ${release_variables}
+  }
+  ${will_release_variables}
+  void compiled_args(CompiledNodeArgs& args) const override;
+  variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override;
+  ${saved_variables}
+  ${saved_list_sizes}
+};
+"""
+)
+
+WILL_RELEASE_VARIABLES = CodeTemplate(
+    """\
+bool retain_variables = true;
+void will_release_variables() override {
+  retain_variables = false;
+}
+"""
+)
+
+# We generate e.g. MulBackward0::apply and have that call into
+# MulBackward0_apply_functional. The apply_functional is a pure function,
+# that is, it does not rely on global state. MulBackward0::apply
+# is responsible for querying the autograd engine for which outputs should
+# be computed (needs_input_grad), applying locks,
+# and unpacking saved variables to pass to MulBackward0_apply_functional.
+#
+# needs_input_grad is a mapping from input index to if that input needs
+# gradients computed. For operators that take in List[Tensor], the List[Tensor]
+# is one element in the needs_input_grad that specifies if *any* of the
+# List[Tensor] needs input grad. In theory this could be optimized.
+FUNCTION_DEFINITION = CodeTemplate(
+    """\
+static variable_list ${op}_apply_functional(
+  variable_list&& grads,
+  std::array needs_input_grad${,apply_functional_args_signature})
+{
+  IndexRangeGenerator gen;
+  ${compute_index_ranges}
+  variable_list grad_inputs(gen.size());
+  ${body}
+  return grad_inputs;
+}
+inline variable_list ${op}_apply_functional_ivalue(const variable_list& grads, const ivalue_list& args)
+{
+#ifdef C10_MOBILE
+  TORCH_INTERNAL_ASSERT(false, "compiled autograd doesn't work on mobile");
+#else
+  auto packed_args = PackedArgs(args);
+  auto needs_input_grad = packed_args.unpack>();
+  ${unpack_ivalues}
+  return ${op}_apply_functional(variable_list(grads), needs_input_grad${,apply_functional_args});
+#endif
+}
+
+variable_list ${op}::apply(variable_list&& grads) {
+  ${thread_lock}
+  ${asserts}
+  ${unpacks}
+  ${compute_needs_input_grad}
+  return ${op}_apply_functional(std::move(grads), needs_input_grad${,apply_functional_args});
+}
+
+void ${op}::compiled_args(CompiledNodeArgs& args) const {
+    ${compiled_args}
+}
+variable_list ${op}::apply_with_saved(const variable_list& grads, SwapSavedVariables& saved) {
+#ifdef C10_MOBILE
+  TORCH_INTERNAL_ASSERT(false, "compiled autograd doesn't work on mobile");
+#else
+  ${apply_with_saved_before}
+
+  static bool called = false;
+  if (!called) {
+    called = true;
+    ${compute_schema}
+    const auto& pyinterface = torch::dynamo::autograd::getPyCompilerInterface();
+    pyinterface->bind_function(saved.get_py_compiler(), name(), ${op}_apply_functional_ivalue, schema);
+  }
+
+  variable_list output_result;
+
+  PackedArgs packed_args;
+  ${asserts}
+  ${unpacks}
+  ${compute_needs_input_grad}
+  packed_args.pack(needs_input_grad);
+  ${get_packed_args}
+
+  output_result = compiled_autograd_apply_functional(packed_args, next_edges(), saved, grads, name());
+
+  ${apply_with_saved_after}
+  return output_result;
+#endif
+}
+
+"""
+)
+
+GRAD_INPUT_MASK = CodeTemplate(
+    """\
+  auto grad_input_mask = std::array{
+    ${masks}
+  };
+"""
+)
+
+COMPUTE_NEEDS_INPUT_GRAD = CodeTemplate(
+    """\
+IndexRangeGenerator gen;
+${compute_index_ranges}
+auto needs_input_grad = std::array{
+  ${masks}
+};\
+"""
+)
+
+
+DERIVATIVE_SINGLE = CodeTemplate(
+    """\
+if (needs_input_grad[/*${name}*/${idx}]) {
+  auto grad_result = ${derivative};
+  copy_range(grad_inputs, ${name}_ix, grad_result);
+}
+"""
+)
+
+# note(crcrpar): `self` argument and other optional positional argument
+# of foreach functions are basically a list of n `Tensor`s thus iterating over
+# `grads` in order to utilize and apply the existing derivative definitions
+# to each `Tensor`(s) of `self`, and the others.
+DERIVATIVE_SINGLE_FOREACH = CodeTemplate(
+    """\
+if (needs_input_grad[/*${name}*/${idx}]) {  // ${name}
+  std::vector grad_result;
+  grad_result.reserve(grads.size());
+  for (const auto & i : c10::irange(grads.size())) {
+    if (grads[i].defined()) {
+      grad_result.emplace_back(${derivative});
+    } else {
+      grad_result.emplace_back(Tensor());
+    }
+  }
+  copy_range(grad_inputs, ${name}_ix, grad_result);
+}
+"""
+)
+
+DERIVATIVE_MULTI_COPY_RANGE = CodeTemplate(
+    """\
+  if (needs_input_grad[/*${name}*/${idx}]) {
+    copy_range(grad_inputs, ${name}_ix, std::get<${i}>(grad_result));
+  }
+"""
+)
+
+DERIVATIVE_MULTI = CodeTemplate(
+    """\
+if (${needs_input_grad}) {
+  ${grad_input_mask}
+  auto grad_result = ${derivative};
+  ${copy_ranges}
+}
+"""
+)
+
+# Generates python bindings
+#
+# This generates the definitions for:
+#   (1) The PyTypeObject for each backward grad_fn subclassing Node
+#   (2) The entry for PyTypeObject's tp_getset slot (an array of PyGetSetDef structs)
+#       We generate one PyGetSetDef struct for each of grad_fn's saved inputs and outputs
+#       Each PyGetSetDef has a function ptr to a getter, also defined here (3).
+#   (3) Getters for each of grad_fn's saved inputs and outputs.
+#
+PY_FUNCTION_DEFINITION = CodeTemplate(
+    """\
+static PyTypeObject ${op}Class;
+addClass<${op}>(module, ${op}Class, "${op}", ${op}_properties);
+"""
+)
+
+PY_FUNCTION_PROPS_AND_GETTERS = CodeTemplate(
+    """\
+${all_getter_definitions}
+
+static struct PyGetSetDef ${op}_properties[] = {
+  THP_FUNCTION_DEFAULT_PROPERTIES,
+  ${all_getsetdef_structs}
+  {nullptr} /* sentinel */
+};
+
+"""
+)
+
+PY_GETSETDEF_STRUCT = CodeTemplate(
+    """\
+{(char*)"_saved_${name}", (getter)THP${op}_${name}_getter, nullptr, nullptr, nullptr}"""
+)
+
+PY_RAW_GETSETDEF_STRUCT = CodeTemplate(
+    """\
+{(char*)"_raw_saved_${name}", (getter)THP${op}_${name}_raw_getter, nullptr, nullptr, nullptr}"""
+)
+
+# Getter templates
+GETTER_DEFINITION = CodeTemplate(
+    """\
+static PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) {
+  HANDLE_TH_ERRORS
+  auto prop = static_cast<${op}*>(self->cdata.get())->${name};
+  ${body}
+  END_HANDLE_TH_ERRORS
+}
+"""
+)
+
+GETTER_DEFINITION_SAVEDVAR = CodeTemplate(
+    """\
+static PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) {
+  HANDLE_TH_ERRORS
+  const auto& prop = static_cast<${op}*>(self->cdata.get())->${name}_;
+  ${body}
+  END_HANDLE_TH_ERRORS
+}
+"""
+)
+
+GETTER_DEFINITION_RAW_SAVEDVAR = CodeTemplate(
+    """\
+static PyObject* THP${op}_${name}_raw_getter(THPCppFunction *self, void *_unused) {
+  HANDLE_TH_ERRORS
+  const auto& prop = static_cast<${op}*>(self->cdata.get())->${name}_;
+  ${body}
+  END_HANDLE_TH_ERRORS
+}
+"""
+)
+
+GETTER_DEFINITION_VEC_SAVEDVAR = CodeTemplate(
+    """\
+static PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) {
+  HANDLE_TH_ERRORS
+  const auto *node = static_cast<${op}*>(self->cdata.get());
+  const auto& prop = node->${name}_;
+  if (node->${name}_released_) {
+    PyErr_SetString(PyExc_RuntimeError, ERR_BACKWARD_TWICE);
+    return nullptr;
+  }
+  ${body}
+  END_HANDLE_TH_ERRORS
+}
+"""
+)
+
+GETTER_DEFINITION_RAW_VEC_SAVEDVAR = CodeTemplate(
+    """\
+static PyObject* THP${op}_${name}_raw_getter(THPCppFunction *self, void *_unused) {
+  HANDLE_TH_ERRORS
+  const auto *node = static_cast<${op}*>(self->cdata.get());
+  const auto& prop = node->${name}_;
+  if (node->${name}_released_) {
+    PyErr_SetString(PyExc_RuntimeError, ERR_BACKWARD_TWICE);
+    return nullptr;
+  }
+  ${body}
+  END_HANDLE_TH_ERRORS
+}
+"""
+)
+
+GETTER_DEFINITION_OPT = CodeTemplate(
+    """\
+static PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) {
+  HANDLE_TH_ERRORS
+  auto opt_prop = static_cast<${op}*>(self->cdata.get())->${name};
+  if (!opt_prop.has_value()) {
+    Py_RETURN_NONE;
+  }
+  auto prop = opt_prop.value();
+  ${body}
+  END_HANDLE_TH_ERRORS
+}
+"""
+)
+
+GETTER_DEFINITION_OPT_ARRAYREF = CodeTemplate(
+    """\
+static PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) {
+  HANDLE_TH_ERRORS
+  auto opt_prop = static_cast<${op}*>(self->cdata.get())->${name};
+  if (!opt_prop.list.has_value()) {
+    Py_RETURN_NONE;
+  }
+  auto prop = opt_prop.list.value();
+  ${body}
+  END_HANDLE_TH_ERRORS
+}
+"""
+)
+
+# Getter body
+GETTER_BODY_SAVEDVAR = """\
+return THPVariable_Wrap(prop.unpack(self->cdata));
+"""
+
+GETTER_BODY_RAW_SAVEDVAR = """\
+pybind11::object obj = pybind11::cast(prop, pybind11::return_value_policy::reference);
+return obj.release().ptr();
+"""
+
+GETTER_BODY_VEC_SAVEDVAR = """\
+PyObject* tup = PyTuple_New((Py_ssize_t) prop.size());
+for (auto i: c10::irange(prop.size())) {
+  PyTuple_SetItem(tup, (Py_ssize_t) i, THPVariable_Wrap(prop[i].unpack(self->cdata)));
+}
+return tup;
+"""
+
+GETTER_BODY_RAW_VEC_SAVEDVAR = """\
+PyObject* tup = PyTuple_New((Py_ssize_t) prop.size());
+for (auto i : c10::irange(prop.size())) {
+  pybind11::object obj = pybind11::cast(prop[i], pybind11::return_value_policy::reference);
+  PyTuple_SetItem(tup, (Py_ssize_t) i, obj.release().ptr());
+}
+return tup;
+"""
+
+GETTER_BODY_ARRAYREF_LONG = """\
+PyObject* tup = PyTuple_New((Py_ssize_t) prop.size());
+for (auto i : c10::irange(prop.size())) {
+  PyTuple_SetItem(tup, (Py_ssize_t) i, PyLong_FromUnsignedLong((uint64_t) prop[i]));
+}
+return tup;
+"""
+
+GETTER_BODY_ARRAYREF_SYMINT = """\
+PyObject* tup = PyTuple_New((Py_ssize_t) prop.size());
+for (auto i : c10::irange(prop.size())) {
+    auto si = prop[i];
+    if (auto m = si.maybe_as_int()) {
+      PyTuple_SetItem(tup, (Py_ssize_t) i, PyLong_FromUnsignedLong(*m));
+    } else {
+      auto py_symint = py::cast(si).release().ptr();
+      PyTuple_SetItem(tup, (Py_ssize_t) i, py_symint);
+    }
+}
+return tup;
+"""
+
+GETTER_BODY_ARRAYREF_DOUBLE = """\
+PyObject* tup = PyTuple_New((Py_ssize_t) prop.size());
+for (auto i : c10::irange(prop.size())) {
+  PyTuple_SetItem(tup, (Py_ssize_t) i, PyFloat_FromDouble((double) prop[i]));
+}
+return tup;
+"""
+
+GETTER_BODY_INT64_T = """\
+return PyLong_FromUnsignedLong((int64_t) prop);
+"""
+
+GETTER_BODY_SYMINT = """\
+if (auto m = prop.maybe_as_int()) {
+  return PyLong_FromUnsignedLong(*m);
+} else {
+  return py::cast(prop).release().ptr();
+}
+"""
+
+GETTER_BODY_DOUBLE = """\
+return PyFloat_FromDouble((double) prop);
+"""
+
+GETTER_BODY_BOOL = """\
+if (prop) {
+  Py_RETURN_TRUE;
+} else {
+  Py_RETURN_FALSE;
+}
+"""
+
+GETTER_BODY_STRING = """\
+return PyUnicode_FromStringAndSize(prop.data(), prop.size());
+"""
+
+GETTER_BODY_SCALAR = """\
+if (prop.isComplex()) {
+  auto cprop = prop.to>();
+  return PyComplex_FromDoubles(cprop.real(), cprop.imag());
+} else if (prop.isFloatingPoint()) {
+  return PyFloat_FromDouble(prop.to());
+} else if (prop.isIntegral(/*includeBool=*/false)) {
+  return PyLong_FromLong(prop.to());
+} else if (prop.isBoolean()) {
+  if (prop.to()) {
+    Py_RETURN_TRUE;
+  } else {
+    Py_RETURN_FALSE;
+  }
+} else {
+  PyErr_SetString(PyExc_RuntimeError, "Unknown scalar type");
+  return nullptr;
+}
+"""
+
+
+GETTER_BODY_VEC_SCALAR = """\
+PyObject* tup = PyTuple_New((Py_ssize_t) prop.size());
+for (auto i: c10::irange(prop.size())) {
+  if (prop[i].isComplex()) {
+    auto cprop = prop[i].to>();
+    PyTuple_SetItem(tup, (Py_ssize_t) i, PyComplex_FromDoubles(cprop.real(), cprop.imag()));
+  } else if (prop[i].isFloatingPoint()) {
+    auto double_prop = prop[i].to();
+    PyTuple_SetItem(tup, (Py_ssize_t) i, PyFloat_FromDouble(double_prop));
+  } else if (prop[i].isIntegral(/*includeBool=*/false)) {
+    auto long_prop = prop[i].to();
+    PyTuple_SetItem(tup, (Py_ssize_t) i, PyLong_FromLong(long_prop));
+  } else if (prop[i].isBoolean()) {
+    if (prop[i].to()) {
+      PyTuple_SetItem(tup, (Py_ssize_t) i, Py_True);
+    } else {
+      PyTuple_SetItem(tup, (Py_ssize_t) i, Py_False);
+    }
+  } else {
+    PyErr_SetString(PyExc_RuntimeError, "Unknown scalar type");
+    return nullptr;
+  }
+}
+return tup;
+"""
+
+
+MISC_GETTER_DEFS = {
+    OptionalCType(BaseCType(longT)): (GETTER_DEFINITION_OPT, GETTER_BODY_INT64_T),
+    OptionalCType(BaseCType(SymIntT)): (GETTER_DEFINITION_OPT, GETTER_BODY_SYMINT),
+    BaseCType(doubleT): (GETTER_DEFINITION, GETTER_BODY_DOUBLE),
+    OptionalCType(BaseCType(doubleT)): (GETTER_DEFINITION_OPT, GETTER_BODY_DOUBLE),
+    BaseCType(boolT): (GETTER_DEFINITION, GETTER_BODY_BOOL),
+    BaseCType(scalarT): (GETTER_DEFINITION, GETTER_BODY_SCALAR),
+    OptionalCType(BaseCType(scalarT)): (GETTER_DEFINITION_OPT, GETTER_BODY_SCALAR),
+}
+
+# These functions have backwards which cannot be traced, and so must have
+# their backward functions traced opaquely.
+# VIEW_FUNCTIONS are not traceable because they use as_strided, which
+# has an untraceable backwards, see
+# https://github.com/pytorch/pytorch/issues/4250
+# TODO: This is probably not exhaustive, but it's a start
+UNTRACEABLE_FUNCTIONS = VIEW_FUNCTIONS
+
+
+def get_infos_with_derivatives_list(
+    differentiability_infos: dict[FunctionSchema, dict[str, DifferentiabilityInfo]],
+) -> list[DifferentiabilityInfo]:
+    diff_info_list = [
+        info
+        for diffinfo_dict in differentiability_infos.values()
+        for info in diffinfo_dict.values()
+    ]
+
+    return list(filter(lambda info: info.args_with_derivatives, diff_info_list))
+
+
+def gen_autograd_functions_lib(
+    out: str,
+    differentiability_infos: dict[FunctionSchema, dict[str, DifferentiabilityInfo]],
+    template_path: str,
+) -> None:
+    """Functions.h and Functions.cpp body
+
+    These contain the auto-generated subclasses of torch::autograd::Node
+    for each every differentiable torch function.
+    """
+
+    # get a 1D list of diffinfos, we do not need them to be per FunctionSchema/DispatchKey here
+    # infos with the diff dispatchkeys but the same name will still be in the same shard.
+    infos = get_infos_with_derivatives_list(differentiability_infos)
+    declarations = [process_function(f, FUNCTION_DECLARATION) for f in infos]
+    definitions = [process_function(f, FUNCTION_DEFINITION) for f in infos]
+
+    file_basename = "Functions"
+    fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
+    for suffix in [".h", ".cpp"]:
+        fname = file_basename + suffix
+        fm.write_with_template(
+            fname,
+            fname,
+            lambda: {
+                "generated_comment": "@"
+                + f"generated from {fm.template_dir_for_comments()}/{fname}",
+                "autograd_function_declarations": declarations,
+                "autograd_function_definitions": definitions,
+            },
+        )
+
+
+def gen_autograd_functions_python(
+    out: str,
+    differentiability_infos: dict[FunctionSchema, dict[str, DifferentiabilityInfo]],
+    template_path: str,
+) -> None:
+    fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
+    num_shards = 5
+    fm.write(
+        "python_functions.h",
+        lambda: {
+            "generated_comment": "@"
+            + f"generated from {fm.template_dir_for_comments()}/python_functions.h",
+            "shard_forward_declare": [
+                f"void initialize_autogenerated_functions_{i}(PyObject* module);"
+                for i in range(num_shards)
+            ],
+            "shard_call": [
+                f"initialize_autogenerated_functions_{i}(module);"
+                for i in range(num_shards)
+            ],
+        },
+    )
+
+    # get a 1D list of diffinfos, we do not need them to be per FunctionSchema/DispatchKey here
+    # infos with the diff dispatchkeys but the same name will still be in the same shard.
+    infos = get_infos_with_derivatives_list(differentiability_infos)
+    fm.write_sharded(
+        "python_functions.cpp",
+        infos,
+        key_fn=lambda info: info.name,
+        base_env={
+            "generated_comment": "@"
+            + f"generated from {fm.template_dir_for_comments()}/python_functions.cpp",
+        },
+        env_callable=lambda info: {
+            "py_function_initializers": [
+                process_function(info, PY_FUNCTION_DEFINITION)
+            ],
+            "py_function_props_and_getters": [
+                process_function(info, PY_FUNCTION_PROPS_AND_GETTERS)
+            ],
+        },
+        num_shards=num_shards,
+        sharded_keys={"py_function_initializers", "py_function_props_and_getters"},
+    )
+
+
+def process_function(info: DifferentiabilityInfo, template: CodeTemplate) -> str:
+    saved_variables: list[str] = []
+    release_variables: list[str] = []
+    saved_list_sizes: list[str] = []
+    unpack: list[str] = []
+    asserts: list[str] = []
+    compute_index_ranges: list[str] = []
+    getter_definitions: list[str] = []
+    py_getsetdef_structs: list[str] = []
+    compiled_args: list[str] = []
+    apply_with_saved_before: list[str] = []
+    apply_with_saved_after: list[str] = []
+    apply_functional_args: list[str] = []
+    apply_functional_args_ref_types: list[str] = []
+    # Maps the name of an input (to the original forward operator;
+    # examples are "self", "other") to the order in which they appear in the
+    # operator.
+    # For example; if the operator is foo(Tensor self, int64_t k, Tensor other),
+    # the mapping is: {"self": 0, "other": 1}.
+    # We use this mapping to populate needs_input_grad in some order and then grab
+    # values from it.
+    input_name_to_idx: dict[str, int] = {}
+
+    for idx, arg in enumerate(info.args_with_derivatives):
+        if arg.type in TENSOR_LIST_LIKE_CTYPES:
+            size = f"{arg.name}_size_"
+            saved_list_sizes.append(f"size_t {arg.name}_size_;")
+            apply_functional_args.append(f"{arg.name}_size_")
+            apply_functional_args_ref_types.append("size_t")
+        else:
+            size = "1"
+        compute_index_ranges.append(f"auto {arg.name}_ix = gen.range({size});")
+        input_name_to_idx[arg.name] = idx
+
+    def save_var(var: SavedAttribute, is_output: bool) -> None:
+        name = var.nctype.name
+        type = var.nctype.type
+        should_append_getsetdef = True
+        should_append_raw_getsetdef = False
+        visit_name = name
+        uses_cpp_saved_variable_cls = False
+        unpacked_ref_type = None
+
+        if (
+            type == BaseCType(tensorT)
+            or type == OptionalCType(BaseCType(tensorT))
+            or type == MutRefCType(OptionalCType(BaseCType(tensorT)))
+            or (type == BaseCType(scalarT) and is_output)
+        ):
+            uses_cpp_saved_variable_cls = True
+            saved_variables.append(f"SavedVariable {name}_;")
+            release_variables.append(f"{name}_.reset_data();")
+            ptr = "shared_from_this()" if is_output else ""
+            unpack.append(f"auto {name} = {name}_.unpack({ptr});")
+            getter_definitions.append(
+                GETTER_DEFINITION_SAVEDVAR.substitute(
+                    op=info.op, name=name, body=GETTER_BODY_SAVEDVAR
+                )
+            )
+            getter_definitions.append(
+                GETTER_DEFINITION_RAW_SAVEDVAR.substitute(
+                    op=info.op, name=name, body=GETTER_BODY_RAW_SAVEDVAR
+                )
+            )
+            should_append_raw_getsetdef = True
+            visit_name = f"{name}_"
+            unpacked_ref_type = "Tensor&"
+        elif (
+            type == BaseCType(tensorListT)
+            or type == BaseCType(iTensorListRefT)
+            or type == VectorCType(BaseCType(tensorT))
+        ):
+            # note(crcrpar): [nuanced return type of out-of-place foreach functions]
+            # When an out-of-place foreach function whose return signature is `Tensor[]`
+            # spells out its backward definitions in `derivatives.yaml`, and some of them depend on
+            # `result`, `result`'s type is interpreted and treated as `std::vector`.
+            # An out-of-place foreach whose backwards rely on their output doesn't suffer from this
+            # difference if the definitions are codegen'ed.
+            # This special case is needed for `_foreach_pow.List` and `_foreach_pow.ScalarAndTensor`
+            # as of https://github.com/pytorch/pytorch/pull/105504.
+            if type == VectorCType(BaseCType(tensorT)):
+                assert (
+                    info.func.func.name.name.base.startswith("_foreach") and is_output
+                )
+            uses_cpp_saved_variable_cls = True
+            saved_variables.append(f"std::vector {name}_;")
+            saved_variables.append(f"bool {name}_released_ = false;")
+            # Just clear() is sufficient, we don't need to loop and clear each variable.
+            # Because the SavedVariable owns a tensor and a grad_fn, removing the SavedVariable makes them go away as well.
+            release_variables.append(f"{name}_.clear();")
+            release_variables.append(f"{name}_released_ = true;")
+            ptr = "shared_from_this()" if is_output else "nullptr"
+            unpack.append(f"auto {name} = unpack_list({name}_, {ptr});")
+            asserts.append(f"TORCH_CHECK(!{name}_released_, ERR_BACKWARD_TWICE);")
+            getter_definitions.append(
+                GETTER_DEFINITION_VEC_SAVEDVAR.substitute(
+                    op=info.op, name=name, body=GETTER_BODY_VEC_SAVEDVAR
+                )
+            )
+            getter_definitions.append(
+                GETTER_DEFINITION_RAW_VEC_SAVEDVAR.substitute(
+                    op=info.op, name=name, body=GETTER_BODY_RAW_VEC_SAVEDVAR
+                )
+            )
+            should_append_raw_getsetdef = True
+            visit_name = f"{name}_"
+            unpacked_ref_type = "std::vector&"
+        elif type == ListCType(OptionalCType(BaseCType(tensorT))):
+            uses_cpp_saved_variable_cls = True
+            saved_variables.append(f"std::vector {name}_;")
+            saved_variables.append(f"bool {name}_released_ = false;")
+            # Just clear() is sufficient, we don't need to loop and clear each variable.
+            # Because the SavedVariable owns a tensor and a grad_fn, removing the SavedVariable makes them go away as well.
+            release_variables.append(f"{name}_.clear();")
+            release_variables.append(f"{name}_released_ = true;")
+            unpack.append(f"auto {name} = unpack_opt_list({name}_);")
+            asserts.append(f"TORCH_CHECK(!{name}_released_, ERR_BACKWARD_TWICE);")
+            getter_definitions.append(
+                GETTER_DEFINITION_VEC_SAVEDVAR.substitute(
+                    op=info.op, name=name, body=GETTER_BODY_VEC_SAVEDVAR
+                )
+            )
+            getter_definitions.append(
+                GETTER_DEFINITION_RAW_VEC_SAVEDVAR.substitute(
+                    op=info.op, name=name, body=GETTER_BODY_RAW_VEC_SAVEDVAR
+                )
+            )
+            should_append_raw_getsetdef = True
+            visit_name = f"{name}_"
+            unpacked_ref_type = "torch::List>&"
+        elif type == BaseCType(intArrayRefT):
+            saved_variables.append(f"std::vector {name};")
+            getter_definitions.append(
+                GETTER_DEFINITION.substitute(
+                    op=info.op, name=name, body=GETTER_BODY_ARRAYREF_LONG
+                )
+            )
+        elif type == BaseCType(symIntArrayRefT):
+            saved_variables.append(f"std::vector {name};")
+            getter_definitions.append(
+                GETTER_DEFINITION.substitute(
+                    op=info.op, name=name, body=GETTER_BODY_ARRAYREF_SYMINT
+                )
+            )
+        elif type == BaseCType(optionalIntArrayRefT):
+            saved_variables.append(f"c10::OptionalArray {name};")
+            getter_definitions.append(
+                GETTER_DEFINITION_OPT_ARRAYREF.substitute(
+                    op=info.op, name=name, body=GETTER_BODY_ARRAYREF_LONG
+                )
+            )
+        elif type == BaseCType(optionalSymIntArrayRefT):
+            saved_variables.append(f"c10::OptionalArray {name};")
+            getter_definitions.append(
+                GETTER_DEFINITION_OPT_ARRAYREF.substitute(
+                    op=info.op, name=name, body=GETTER_BODY_ARRAYREF_SYMINT
+                )
+            )
+        elif type == OptionalCType(BaseCType(intArrayRefT)):
+            saved_variables.append(f"c10::OptionalArray {name};")
+            getter_definitions.append(
+                GETTER_DEFINITION_OPT_ARRAYREF.substitute(
+                    op=info.op, name=name, body=GETTER_BODY_ARRAYREF_LONG
+                )
+            )
+        elif type == OptionalCType(BaseCType(symIntArrayRefT)):
+            saved_variables.append(f"c10::OptionalArray {name};")
+            getter_definitions.append(
+                GETTER_DEFINITION_OPT_ARRAYREF.substitute(
+                    op=info.op, name=name, body=GETTER_BODY_ARRAYREF_SYMINT
+                )
+            )
+        elif type == OptionalCType(ArrayRefCType(BaseCType(doubleT))):
+            saved_variables.append(f"c10::OptionalArray {name};")
+            getter_definitions.append(
+                GETTER_DEFINITION_OPT_ARRAYREF.substitute(
+                    op=info.op, name=name, body=GETTER_BODY_ARRAYREF_DOUBLE
+                )
+            )
+        elif type == BaseCType(longT):
+            saved_variables.append(f"{type.cpp_type()} {name} = 0;")
+            getter_definitions.append(
+                GETTER_DEFINITION.substitute(
+                    op=info.op, name=name, body=GETTER_BODY_INT64_T
+                )
+            )
+        elif type == BaseCType(SymIntT):
+            saved_variables.append(f"c10::SymInt {name};")
+            getter_definitions.append(
+                GETTER_DEFINITION.substitute(
+                    op=info.op, name=name, body=GETTER_BODY_SYMINT
+                )
+            )
+        elif type == BaseCType(stringT):
+            saved_variables.append(f"std::string {name};")
+            getter_definitions.append(
+                GETTER_DEFINITION.substitute(
+                    op=info.op, name=name, body=GETTER_BODY_STRING
+                )
+            )
+        elif type == OptionalCType(BaseCType(stringT)):
+            saved_variables.append(f"std::optional {name};")
+            getter_definitions.append(
+                GETTER_DEFINITION_OPT.substitute(
+                    op=info.op, name=name, body=GETTER_BODY_STRING
+                )
+            )
+        elif type == ArrayRefCType(
+            elem=BaseCType(type=BaseCppType(ns="at", name="Scalar"))
+        ):
+            saved_variables.append(f"std::vector {name};")
+            unpacked_ref_type = "std::vector&"
+            saved_variables.append(f"bool {name}_released_ = false;")
+            # Just clear() is sufficient, we don't need to loop and clear each variable.
+            # Because the SavedVariable owns a tensor and a grad_fn, removing the SavedVariable makes them go away as well.
+            release_variables.append(f"{name}.clear();")
+            # release_variables.append(f"{name}_released_ = true;")
+            # unpack.append(f"auto {name} = unpack_list({name}_);")
+            # asserts.append(f"TORCH_CHECK(!{name}_released_, ERR_BACKWARD_TWICE);")
+            getter_definitions.append(
+                CodeTemplate(
+                    """\
+static PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) {
+  HANDLE_TH_ERRORS
+  const auto *node = static_cast<${op}*>(self->cdata.get());
+  const auto& prop = node->${name};
+  if (node->${name}_released_) {
+    PyErr_SetString(PyExc_RuntimeError, ERR_BACKWARD_TWICE);
+    return nullptr;
+  }
+  ${body}
+  END_HANDLE_TH_ERRORS
+}
+                            """
+                ).substitute(
+                    op=info.op,
+                    name=name,
+                    body=GETTER_BODY_VEC_SCALAR,
+                )
+            )
+        else:
+            # Check for indicators that you're putting a non-owning reference
+            # into the saved variable field.  If this is spuriously firing,
+            # edit this field.  Otherwise, you probably need to add a case
+            # above.
+            assert (
+                "ref" not in type.cpp_type().lower()
+                and "view" not in type.cpp_type().lower()
+                and "*" not in type.cpp_type()
+                and "&" not in type.cpp_type()
+            ), f"{type.cpp_type()} looks like it contains a non-owning reference"
+            saved_variables.append(f"{type.cpp_type()} {name};")
+
+            if type in MISC_GETTER_DEFS:
+                getter_def, body = MISC_GETTER_DEFS[type]
+                getter_definitions.append(
+                    getter_def.substitute(op=info.op, name=name, body=body)
+                )
+            else:
+                # Types we don't expose python bindings to yet:
+                #   TypeAndSize, at::ScalarType, TensorOptions, TensorGeometry,
+                #   std::vector>, std::vector
+                should_append_getsetdef = False
+
+        if should_append_getsetdef:
+            py_getsetdef_structs.append(
+                PY_GETSETDEF_STRUCT.substitute(op=info.op, name=name)
+            )
+        if should_append_raw_getsetdef:
+            py_getsetdef_structs.append(
+                PY_RAW_GETSETDEF_STRUCT.substitute(op=info.op, name=name)
+            )
+
+        if uses_cpp_saved_variable_cls:
+            compiled_args.append(
+                f"args.collect({visit_name}, {'true' if is_output else 'false'});"
+            )
+        else:
+            compiled_args.append(f"args.collect({visit_name});")
+        apply_with_saved_before.append(f"saved.before({visit_name});")
+        apply_with_saved_after.append(f"saved.after({visit_name});")
+
+        if unpacked_ref_type is None:
+            unpacked_ref_type = f"{saved_variables[-1].split(' ')[0]}&"
+        apply_functional_args.append(str(name))
+        apply_functional_args_ref_types.append(unpacked_ref_type)
+
+    for var in sorted(info.all_saved_inputs, key=lambda sa: str(sa.nctype.name)):
+        save_var(var, is_output=False)
+    for var in sorted(info.all_saved_outputs, key=lambda sa: str(sa.nctype.name)):
+        save_var(var, is_output=True)
+
+    # lock the mutex when we release variables and in Node::apply to protect thread safety
+    # see Note [Thread Safety on Autograd Node]
+    if len(release_variables) > 0:
+        thread_lock = "std::lock_guard lock(mutex_);"
+    else:
+        thread_lock = ""
+
+    if uses_retain_variables(info):
+        apply_functional_args.append("retain_variables")
+        apply_functional_args_ref_types.append("bool")
+        will_release_variables = WILL_RELEASE_VARIABLES.substitute()
+    else:
+        will_release_variables = ""
+
+    body: list[str] = []
+
+    if uses_single_grad(info):
+        body.append("const auto& grad = grads[0];")
+    else:
+        # Generate aliases for gradients named for returned values.
+        body.extend(
+            f"const auto& {name} = grads[{info.available_named_gradients.index(name)}];"
+            for name in sorted(info.used_named_gradients)
+        )
+
+    def emit_derivative(
+        derivative: Derivative,
+        args_with_derivatives: Sequence[Binding],
+    ) -> tuple[bool, str]:
+        formula = derivative.formula
+        var_names = derivative.var_names
+
+        if len(var_names) == 1:
+            checks_any_grad_defined = False
+            if "not_implemented" not in formula:
+                matching_args = [
+                    arg for arg in args_with_derivatives if arg.name == var_names[0]
+                ]
+                if len(matching_args) == 1:
+                    # We can add undefined grad support if the input variable is a Tensor
+                    arg = matching_args[0]
+                    if isinstance(arg.argument, Argument) and str(
+                        arg.argument.type
+                    ) in ("Tensor", "Tensor?"):
+                        formula = "any_grad_defined ? (" + formula + ") : Tensor()"
+                        checks_any_grad_defined = True
+            if info.name.startswith("_foreach_"):
+                derivative_template = DERIVATIVE_SINGLE_FOREACH
+            else:
+                derivative_template = DERIVATIVE_SINGLE
+            return (
+                checks_any_grad_defined,
+                derivative_template.substitute(
+                    name=var_names[0],
+                    derivative=formula,
+                    idx=input_name_to_idx[var_names[0]],
+                ),
+            )
+
+        else:
+            if "grad_input_mask" in formula:
+                masks = [
+                    f"needs_input_grad[{input_name_to_idx[name]}],"
+                    for name in var_names
+                ]
+                grad_input_mask = GRAD_INPUT_MASK.substitute(
+                    n=len(var_names), masks=masks
+                )
+            else:
+                grad_input_mask = ""
+            needs_input_grad = [
+                f"needs_input_grad[{input_name_to_idx[name]}]" for name in var_names
+            ]
+            needs_input_grad = " || ".join(needs_input_grad)
+            copy_ranges: list[str] = []
+            for i, n in enumerate(var_names):
+                copy_ranges.append(
+                    DERIVATIVE_MULTI_COPY_RANGE.substitute(
+                        name=n, i=i, idx=input_name_to_idx[n]
+                    )
+                )
+            return False, DERIVATIVE_MULTI.substitute(
+                needs_input_grad=needs_input_grad,
+                copy_ranges=copy_ranges,
+                derivative=formula,
+                grad_input_mask=grad_input_mask,
+            )
+
+    masks = []
+
+    need_any_grad_defined_var = False
+    for derivative in info.derivatives:
+        checks_any_grad_defined, derivative_text = emit_derivative(
+            derivative, info.args_with_derivatives
+        )
+        body.append(derivative_text)
+        need_any_grad_defined_var |= checks_any_grad_defined
+
+    for name in input_name_to_idx:
+        masks.append(f"task_should_compute_output({{ {name}_ix }}),")
+
+    # Since single-output derivative formulas need to check if grads are
+    # defined, only perform the check once, before all the formulas
+    if need_any_grad_defined_var:
+        body.insert(
+            -len(info.derivatives),
+            "bool any_grad_defined = any_variable_defined(grads);",
+        )
+
+    if info.name in UNTRACEABLE_FUNCTIONS:
+        superclass = "Node"
+    else:
+        superclass = "TraceableFunction"
+
+    all_getsetdef_structs = (
+        ",\n".join(py_getsetdef_structs) + "," if len(py_getsetdef_structs) != 0 else ""
+    )
+    all_getter_definitions = "\n".join(getter_definitions)
+
+    compute_needs_input_grad = COMPUTE_NEEDS_INPUT_GRAD.substitute(
+        n=len(masks), compute_index_ranges=compute_index_ranges, masks=masks
+    )
+    apply_functional_args_signature = [
+        f"{T} {x}"
+        for T, x in zip(apply_functional_args_ref_types, apply_functional_args)
+    ]
+    get_packed_args = "\n".join(
+        f"packed_args.pack({name});" for name in apply_functional_args
+    )
+    unpack_ivalues = []
+    for typ, name in zip(apply_functional_args_ref_types, apply_functional_args):
+        typ = typ.removesuffix("&")
+        unpack_ivalues.append(f"auto {name} = packed_args.unpack<{typ}>();")
+
+    schema_args = [f"std::array"]
+    for typ in apply_functional_args_ref_types:
+        typ = typ.removesuffix("&")
+        typ = typ.removeprefix("const")
+        schema_args.append(typ.strip())
+    compute_schema = ["std::vector schema = {"]
+    for schema_arg in schema_args:
+        compute_schema.append(
+            f"  torch::dynamo::autograd::IValuePacker<{schema_arg}>::packed_type(),"
+        )
+    compute_schema.append("};")
+
+    return template.substitute(
+        unpacks="\n".join(unpack),
+        op=info.op,
+        compute_schema="\n".join(compute_schema),
+        apply_functional_args=apply_functional_args,
+        apply_functional_args_signature=apply_functional_args_signature,
+        compute_needs_input_grad=compute_needs_input_grad,
+        num_inputs=len(input_name_to_idx),
+        unpack_ivalues="\n".join(unpack_ivalues),
+        compute_index_ranges=compute_index_ranges,
+        saved_variables=saved_variables,
+        release_variables=release_variables,
+        saved_list_sizes=saved_list_sizes,
+        asserts=asserts,
+        thread_lock=thread_lock,
+        will_release_variables=will_release_variables,
+        body=body,
+        superclass=superclass,
+        all_getter_definitions=all_getter_definitions,
+        all_getsetdef_structs=all_getsetdef_structs,
+        compiled_args=compiled_args,
+        apply_with_saved_before=apply_with_saved_before,
+        apply_with_saved_after=apply_with_saved_after,
+        get_packed_args=get_packed_args,
+    )
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_inplace_or_view_type.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_inplace_or_view_type.py
new file mode 100644
index 0000000000000000000000000000000000000000..684290da0a72601f457f2edb3aa13a4460b0ecd9
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_inplace_or_view_type.py
@@ -0,0 +1,673 @@
+# Generates ADInplaceOrViewType.h/cpp
+#
+# NOTE: If any changes are being made to the ADInplaceOrView codegen please also check
+# if updates are needed in torch/csrc/autograd/autograd_not_implemented_fallback.cpp
+# The fallback is expected to mimic this codegen, so we should keep the two in sync.
+
+from __future__ import annotations
+
+from torchgen.api import cpp
+from torchgen.api.autograd import (
+    dispatch_strategy,
+    gen_differentiable_outputs,
+    NativeFunctionWithDifferentiabilityInfo,
+)
+from torchgen.api.types import (
+    BaseCType,
+    Binding,
+    boolT,
+    ConstRefCType,
+    CType,
+    DispatcherSignature,
+    intArrayRefT,
+    longT,
+    OptionalCType,
+    symIntArrayRefT,
+    SymIntT,
+    tensorT,
+)
+from torchgen.code_template import CodeTemplate
+from torchgen.context import with_native_function
+from torchgen.model import (
+    NativeFunction,
+    SchemaKind,
+    SelfArgument,
+    TensorOptionsArguments,
+    Type,
+)
+from torchgen.utils import FileManager
+
+from .context import with_native_function_with_differentiability_info
+from .gen_trace_type import (
+    get_return_value,
+    MANUAL_AUTOGRAD,
+    tie_return_values,
+    type_wrapper_name,
+)
+
+
+# See NOTE [ Autograd View Variables ] in variable.h for details.
+# If you update list VIEW_FUNCTIONS or RETURNS_VIEWS_OF_INPUT,
+# you **MUST** also update the public list of view ops accordingly in
+# docs/source/tensor_view.rst. Note not all ATen functions are exposed to public,
+# e.g alias & sparse_coo_tensor_with_dims_and_tensors.
+#
+# A map: function name => name of the argument that all outputs are view of
+
+VIEW_FUNCTIONS_WITH_METADATA_CHANGE = [
+    "view_as_complex",
+    "view_as_real",
+    "_conj",
+    "_neg_view",
+    "_nested_get_values",
+    "_nested_view_from_buffer",
+    "_nested_view_from_jagged",
+]
+
+VIEW_FUNCTIONS = {
+    "numpy_T": "self",
+    "alias": "self",
+    "as_strided": "self",
+    "diagonal": "self",
+    "expand": "self",
+    "permute": "self",
+    "select": "self",
+    "slice": "self",
+    "slice_inverse": "self",
+    "split": "self",
+    "split_with_sizes": "self",
+    "squeeze": "self",
+    "t": "self",
+    "transpose": "self",
+    "unfold": "self",
+    "unsqueeze": "self",
+    "flatten": "self",
+    "view": "self",
+    "unbind": "self",
+    "_indices": "self",
+    "_values": "self",
+    "indices": "self",
+    "values": "self",
+    "crow_indices": "self",
+    "col_indices": "self",
+    "ccol_indices": "self",
+    "row_indices": "self",
+    # sparse_coo ctor output should really be views of both indices and values,
+    # but we only supports making as view of a single variable, and indices is
+    # discrete anyways.
+    # FIXME: clone indices on construction.
+    "sparse_coo_tensor_with_dims_and_tensors": "values",
+    "_reshape_alias": "self",
+    "_test_autograd_multiple_dispatch_view": "self",
+}
+
+for key in VIEW_FUNCTIONS_WITH_METADATA_CHANGE:
+    VIEW_FUNCTIONS[key] = "self"
+
+# note: some VIEW_FUNCTIONS are just compositions of the view functions above
+# this list contains both the root view functions and any that are purely composed
+# of viewing functions, and is used by the JIT to determine when an operator
+# may return a view of its inputs; however they may sometimes return a copy.
+# (e.g. `contiguous`)
+RETURNS_VIEWS_OF_INPUT = set(VIEW_FUNCTIONS.keys()).union(
+    {
+        "chunk",
+        "detach",
+        "contiguous",
+        "reshape",
+        "reshape_as",
+        "expand_as",
+        "view_as",
+        "real",
+        "imag",
+        "narrow",
+        "movedim",
+        "tensor_split",
+        "swapdims",
+        "swapaxes",
+        "mT",
+        "mH",
+        "adjoint",
+        "matrix_H",
+    }
+)
+
+# These are the functions we consider views for the purposes of validating
+# StorageImpl and TensorImpl in gen_variable_type.
+# `_unsafe_view` is not included in VIEW_FUNCTIONS above because it is not a
+# view for the purposes of ADInplaceOrView kernel, we do not want to call as_view
+# See NOTE [Unsafe View] for more info.
+ALL_VIEW_FUNCTIONS = {
+    **VIEW_FUNCTIONS,
+    "_unsafe_view": "self",
+}
+
+ARRAYREF_TO_VEC = CodeTemplate(
+    """\
+auto ${vec} = ${arg}.vec();
+"""
+)
+
+OPTIONAL_TO_VAL = CodeTemplate(
+    """\
+auto ${val} = ${arg}.value_or(${default});
+"""
+)
+
+CALL_DISPATCH = CodeTemplate(
+    """\
+at::_ops::${unambiguous_name}::call(${unpacked_args})"""
+)
+
+REVERSE_VIEW_DISPATCH = CodeTemplate(
+    """\
+${reverse_name}(${unpacked_args})"""
+)
+
+MULTI_OUTPUT_VIEW_ITERATION = CodeTemplate(
+    """\
+for (auto ${view_idx} : c10::irange(${var}.size())) {
+  ${body}
+}
+"""
+)
+
+SETUP_REPLAY_VIEW_IF_NOT_SUPPORT_AS_STRIDED_OR_VIEW_WITH_METADATA_CHANGE = CodeTemplate(
+    """\
+std::unique_ptr func(nullptr);
+std::function rev_func=nullptr;
+if (${is_view_with_metadata_change} ||
+    !self.unsafeGetTensorImpl()->support_as_strided() ||
+    self.unsafeGetTensorImpl()->is_python_dispatch() ||
+    c10::AutogradState::get_tls_state().get_view_replay_enabled()) {
+  ${replay_view_func}
+  ${reverse_replay_view_func}
+}
+"""
+)
+
+REPLAY_VIEW_FUNC = CodeTemplate(
+    """\
+func = std::make_unique<${view_func_name}>(${view_func_args});
+"""
+)
+
+REVERSE_REPLAY_VIEW_LAMBDA_FUNC = CodeTemplate(
+    """\
+rev_func = [=](const at::Tensor& ${input_view}) {
+  return ${reverse_replay_view_call};
+};
+"""
+)
+
+METHOD_DEFINITION = CodeTemplate(
+    """\
+${return_type} ${type_wrapper_name}(${formals}) {
+  ${type_definition_body}
+}
+"""
+)
+
+WRAPPER_REGISTRATION = CodeTemplate(
+    """\
+m.impl("${unqual_operator_name_with_overload}",
+       TORCH_FN(${class_type}::${type_wrapper_name})
+);
+"""
+)
+
+AUTOGRAD_NOT_IMPLEMENTED_REGISTRATION = CodeTemplate(
+    """\
+m.impl("${unqual_operator_name_with_overload}", torch::autograd::autogradNotImplementedFallback());
+"""
+)
+
+INPLACE_REDISPATCH = CodeTemplate(
+    """\
+{
+  at::AutoDispatchBelowADInplaceOrView guard;
+  at::_ops::${unambiguous_name}::redispatch(${unpacked_args});
+}
+"""
+)
+
+ASSIGN_RETURN_VALUE = CodeTemplate(
+    """\
+${return_values} = ${rhs_value};
+"""
+)
+
+VIEW_REDISPATCH = CodeTemplate(
+    """\
+${assign_return_values} ([&]() {
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return at::_ops::${unambiguous_name}::redispatch(${unpacked_args});
+})();
+"""
+)
+
+TMP_VAR = "_tmp"
+
+
+# FIXME: Ideally these functions should be methods on Type class, but we have a
+#        comment in codegen/model.py there saying these concepts are not well defined.
+#        Thus we put a version that commonly used by autograd codegen here.
+def is_tensor_type(t: Type) -> bool:
+    # TODO: Should handle optional here?
+    return t.is_tensor_like() and t.is_list_like() is None
+
+
+def is_tensor_list_type(t: Type) -> bool:
+    # TODO: Should handle optional here?
+    return t.is_tensor_like() and t.is_list_like() is not None
+
+
+UNPACK_TENSOR = CodeTemplate(
+    """\
+auto${ref} ${arg_name}_ = unpack${suffix}(${arg_name}, "${arg_name}", ${arg_pos});"""
+)
+
+
+def unpacked_name(arg_name: str) -> str:
+    return arg_name + "_"
+
+
+# e.g. select.int -> select_copy_int_inverse()
+def inverse_view_name(f: NativeFunction) -> str:
+    copy_variant = f"{f.root_name}_copy"
+    overload = f"{f.func.name.overload_name}"
+    if overload != "":
+        overload = "_" + overload
+    return f"{copy_variant}{overload}_inverse"
+
+
+def extract_bindings(f: NativeFunction) -> list[Binding]:
+    return [
+        r
+        for a in f.func.schema_order_arguments()
+        for r in cpp.argument(
+            a,
+            method=False,
+            symint=True,
+            cpp_no_default_args=set(),
+            faithful=False,
+            has_tensor_options=False,
+        )
+    ]
+
+
+@with_native_function
+def unpack_args(f: NativeFunction) -> tuple[list[str], list[Binding]]:
+    body: list[str] = []
+    unpacked_bindings: list[Binding] = []
+
+    for i, binding in enumerate(extract_bindings(f)):
+        assert not isinstance(binding.argument, SelfArgument)
+        if isinstance(binding.argument, TensorOptionsArguments):
+            raise RuntimeError("VariableKernel shouldn't take TensorOptions")
+
+        is_nullable = binding.argument.type.is_nullable()
+        if not binding.argument.type.is_tensor_like() or is_nullable:
+            unpacked_bindings.append(binding)
+            continue
+
+        is_tensor_list = is_tensor_list_type(binding.argument.type)
+        ref = (not is_nullable) and not is_tensor_list
+        suffix = "_opt" if is_nullable and not is_tensor_list else ""
+        body.append(
+            UNPACK_TENSOR.substitute(
+                arg_name=binding.name,
+                arg_pos=i,
+                suffix=suffix,
+                ref="&" if ref else "",
+            )
+        )
+        unpacked_bindings.append(
+            Binding(
+                name=unpacked_name(binding.name),
+                nctype=binding.nctype,
+                argument=binding.argument,
+                default=binding.default,
+            )
+        )
+
+    return body, unpacked_bindings
+
+
+def get_base_name(f: NativeFunction) -> str:
+    return f.func.name.name.base  # TODO: should be str(f.func.name.name)?
+
+
+def get_view_info(f: NativeFunction) -> str | None:
+    base_name = get_base_name(f)
+    view_info = VIEW_FUNCTIONS.get(base_name, None)
+    if view_info is None and base_name in RETURNS_VIEWS_OF_INPUT:
+        view_info = "self"
+    return view_info
+
+
+def emit_view_func(
+    f: NativeFunction, bindings: list[Binding], view_idx: str | None = None
+) -> str:
+    """Generate an additional lambda function to recover views in backward when as_strided is not supported.
+    See Note [View + Inplace update for base tensor] and [View + Inplace update for view tensor] for more details.
+    """
+    # TODO: Clean this logic up if we get rid of reverse view funcs or reify them.
+    input_base = "input_base"
+    replay_view_func = ""
+    updated_args: list[str] = []
+    known_view_arg_simple_types: list[CType] = [
+        BaseCType(longT),
+        OptionalCType(BaseCType(longT)),
+        BaseCType(SymIntT),
+        OptionalCType(BaseCType(SymIntT)),
+        BaseCType(boolT),
+        BaseCType(intArrayRefT),
+        BaseCType(symIntArrayRefT),
+        ConstRefCType(BaseCType(tensorT)),
+        ConstRefCType(OptionalCType(BaseCType(tensorT))),
+    ]
+    for binding in bindings:
+        arg, arg_type = binding.name, binding.nctype.type
+        if arg == "self":
+            updated_args.append(input_base)
+            continue
+        if arg_type not in known_view_arg_simple_types:
+            known_types_str = ", ".join([str(t) for t in known_view_arg_simple_types])
+            raise TypeError(
+                f"You are adding an {arg_type} {arg} argument to op {cpp.name(f.func)} in addition to known types: "
+                f"{known_types_str}. Please update the list or materialize it so that it can be closed "
+                "over by value, also add a test in pytorch/xla/test/test_operations.py where this code "
+                "is exercised."
+            )
+        if arg_type == BaseCType(intArrayRefT) or arg_type == BaseCType(
+            symIntArrayRefT
+        ):
+            # It's not safe to close over IntArrayRef by value, since this is a
+            # reference type, so materialize a vector to close over by value
+            arg_vec = arg + "_vec"
+            replay_view_func += ARRAYREF_TO_VEC.substitute(arg=arg, vec=arg_vec)
+            updated_args.append(arg_vec)
+        elif arg_type == OptionalCType(BaseCType(longT)):
+            # Materialize int64_t? to int64_t
+            arg_value = arg + "_val"
+            replay_view_func += OPTIONAL_TO_VAL.substitute(
+                arg=arg, val=arg_value, default="0"
+            )
+            updated_args.append(arg_value)
+        elif arg_type == ConstRefCType(BaseCType(tensorT)) or arg_type == ConstRefCType(
+            OptionalCType(BaseCType(tensorT))
+        ):
+            # NB: Closing over a tensor. If a user modifies this tensor, this will be silently
+            # incorrect. The proper thing to do is to store the version counter and copy on write.
+            updated_args.append(arg)
+        else:
+            updated_args.append(arg)
+
+    from .gen_view_funcs import view_func_name
+
+    view_func_args = [b.name for b in bindings if b.name != "self"]
+    if view_idx is not None:
+        view_func_args.append(f"{view_idx}")
+    replay_view_func += REPLAY_VIEW_FUNC.substitute(
+        view_func_name=view_func_name(f, include_namespace=True),
+        view_func_args=view_func_args,
+    )
+
+    input_view = "input_view"
+    reverse_unpacked_args = [
+        "self",
+        f"{input_view}",
+        # inverse_return_mode=
+        "at::functionalization::InverseReturnMode::AlwaysView",
+        *(() if view_idx is None else (f"{view_idx}",)),
+        # skip input_base arg
+        *updated_args[1:],
+    ]
+
+    from torchgen.api.functionalization import reverse_name
+
+    reverse_replay_view_call = REVERSE_VIEW_DISPATCH.substitute(
+        reverse_name=reverse_name(f, include_namespace=True),
+        unpacked_args=reverse_unpacked_args,
+    )
+    reverse_replay_view_func = REVERSE_REPLAY_VIEW_LAMBDA_FUNC.substitute(
+        input_view=input_view, reverse_replay_view_call=reverse_replay_view_call
+    )
+
+    is_view_with_metadata_change = (
+        "true" if cpp.name(f.func) in VIEW_FUNCTIONS_WITH_METADATA_CHANGE else "false"
+    )
+
+    return SETUP_REPLAY_VIEW_IF_NOT_SUPPORT_AS_STRIDED_OR_VIEW_WITH_METADATA_CHANGE.substitute(
+        is_view_with_metadata_change=is_view_with_metadata_change,
+        replay_view_func=replay_view_func,
+        reverse_replay_view_func=reverse_replay_view_func,
+    )
+
+
+def emit_view_body(
+    fn: NativeFunctionWithDifferentiabilityInfo, var: str
+) -> tuple[str, str]:
+    # See NOTE [ Autograd View Variables ] in variable.h for details.
+    f = fn.func
+    base_name = get_base_name(f)
+    view_info = get_view_info(f)
+    call = ""
+    differentiable_outputs = gen_differentiable_outputs(fn)
+    differentiable_output_vars = {r.name for r in differentiable_outputs}
+    if not isinstance(view_info, str):
+        raise TypeError(
+            f"The view info should be a string for {base_name}, but it is: {view_info}"
+        )
+    if len(differentiable_output_vars) == 0:
+        # no output is differentiable (.indices() for SparseTensors for example)
+        rhs_value = (
+            f"as_view({view_info}, {var}, "
+            f"/* is_bw_differentiable */ false, /* is_fw_differentiable */ false)"
+        )
+    elif len(differentiable_output_vars) == 1:
+        # Single differentiable output (Tensor or Tensor[])
+        return_info = differentiable_outputs[0]
+        # We only support simple Tensor or a TensorList for functions that return views
+        if not is_tensor_type(return_info.type) and not is_tensor_list_type(
+            return_info.type
+        ):
+            raise RuntimeError(
+                f"{base_name} that return differentiable views can only return Tensor or Tensor[]"
+            )
+
+        # See Note [ View + Inplace detection]
+        def get_creation_meta_in_mode(original: str) -> str:
+            creation_meta_with_grad_mode = f"(at::GradMode::is_enabled() ? {original} : CreationMeta::NO_GRAD_MODE)"
+            return f"InferenceMode::is_enabled() ? CreationMeta::INFERENCE_MODE : {creation_meta_with_grad_mode}"
+
+        # Only allow rebasing of the history if we return a single Tensor
+        # If we are in a no grad block, raise a warning
+        # See NOTE [ View + Inplace detection ] for more details about this logic
+        if is_tensor_list_type(return_info.type):
+            creation_meta = get_creation_meta_in_mode("CreationMeta::MULTI_OUTPUT_NODE")
+            view_idx = "view_idx"
+            view_func = emit_view_func(
+                f, extract_bindings(f), view_idx=view_idx
+            ).strip()
+            as_view_call = (
+                f"as_view(/* base */ {view_info}, /* output */ {var}[{view_idx}], "
+                "/* is_bw_differentiable */ true, /* is_fw_differentiable */ true, "
+                "/* view_func */ std::move(func), /* rev_view_func */ rev_func, "
+                f"/* creation_meta */ {creation_meta});"
+            )
+            call += MULTI_OUTPUT_VIEW_ITERATION.substitute(
+                var=var, view_idx=view_idx, body=f"{view_func}\n{as_view_call}"
+            )
+            rhs_value = f"std::move({var})"
+        else:
+            call += emit_view_func(f, extract_bindings(f), view_idx=None)
+            creation_meta = get_creation_meta_in_mode("CreationMeta::DEFAULT")
+            rhs_value = (
+                f"as_view(/* base */ {view_info}, /* output */ {var}, /* is_bw_differentiable */ true, "
+                "/* is_fw_differentiable */ true, "
+                f"/* view_func */ std::move(func), /* rev_view_func */ rev_func, /* creation_meta */ {creation_meta})"
+            )
+    else:
+        # This could be supported but we don't need it at the moment, so keeping things simple.
+        raise RuntimeError(
+            "Function that return multiple differentiable output "
+            "when at least one of them is view is not supported."
+        )
+    return call, rhs_value
+
+
+def modifies_arguments(f: NativeFunction) -> bool:
+    return f.func.kind() in [SchemaKind.inplace, SchemaKind.out]
+
+
+@with_native_function_with_differentiability_info
+def emit_inplace_or_view_body(fn: NativeFunctionWithDifferentiabilityInfo) -> list[str]:
+    f = fn.func
+    inplace_view_body: list[str] = []
+
+    dispatcher_sig = DispatcherSignature.from_schema(f.func)
+    dispatcher_exprs = dispatcher_sig.exprs()
+
+    # code-generated ADInplaceOrView kernels plumb and recompute dispatch keys directly through the kernel for performance.
+    # See Note [Plumbing Keys Through The Dispatcher] for details.
+    dispatch_key_set = "ks & c10::after_ADInplaceOrView_keyset"
+    redispatch_args = ", ".join([dispatch_key_set] + [a.expr for a in dispatcher_exprs])
+
+    # Note that this calls the slow, dispatching variants of manual_cpp_binding ops.
+    # We could probably work harder to ensure that the fast variants are called instead, but the perf benefit would be minimal.
+    if modifies_arguments(f):  # inplace op
+        inplace_view_body.append(
+            INPLACE_REDISPATCH.substitute(
+                unambiguous_name=f.func.name.unambiguous_name(),
+                unpacked_args=redispatch_args,
+            )
+        )
+        for r in cpp.return_names(f):
+            inplace_view_body.append(f"increment_version({r});")
+    else:
+        assert get_view_info(f) is not None
+        inplace_view_body.append(
+            VIEW_REDISPATCH.substitute(
+                assign_return_values="auto " + TMP_VAR + " = ",
+                unambiguous_name=f.func.name.unambiguous_name(),
+                unpacked_args=redispatch_args,
+            )
+        )
+        call, rhs_value = emit_view_body(fn, TMP_VAR)
+        inplace_view_body.append(call)
+        assert rhs_value is not None
+        inplace_view_body.append(
+            ASSIGN_RETURN_VALUE.substitute(
+                return_values=tie_return_values(f), rhs_value=rhs_value
+            )
+        )
+    if f.func.returns:
+        inplace_view_body.append(f"return {get_return_value(f)};")
+    return inplace_view_body
+
+
+@with_native_function
+def gen_formals(f: NativeFunction) -> str:
+    return ", ".join(
+        # code-generated autograd kernels plumb and recompute dispatch keys directly through the kernel for performance.
+        # See Note [Plumbing Keys Through The Dispatcher] for details.
+        ["c10::DispatchKeySet ks"]
+        + [
+            f"{cpp.argument_type(a, binds='__placeholder__', symint=True).cpp_type()} {a.name}"
+            for a in f.func.schema_order_arguments()
+        ]
+    )
+
+
+@with_native_function_with_differentiability_info
+def inplace_or_view_method_definition(
+    fn: NativeFunctionWithDifferentiabilityInfo,
+) -> str | None:
+    f = fn.func
+    if get_view_info(f) is None and (
+        # For functions that modify their inputs but don't return them,
+        # we can't give them autograd support.
+        # See https://github.com/pytorch/pytorch/issues/53796
+        not modifies_arguments(f) or len(f.func.returns) == 0
+    ):
+        return None
+    return METHOD_DEFINITION.substitute(
+        return_type=cpp.returns_type(f.func.returns, symint=True).cpp_type(),
+        type_wrapper_name=type_wrapper_name(f),
+        formals=gen_formals(f),
+        type_definition_body=emit_inplace_or_view_body(fn),
+    )
+
+
+@with_native_function_with_differentiability_info
+def inplace_or_view_method_registration(
+    fn: NativeFunctionWithDifferentiabilityInfo,
+) -> str | None:
+    f = fn.func
+    if get_view_info(f) is None and (
+        not modifies_arguments(f) or len(f.func.returns) == 0
+    ):
+        return None
+    return WRAPPER_REGISTRATION.substitute(
+        unqual_operator_name_with_overload=f.func.name,
+        type_wrapper_name=type_wrapper_name(f),
+        class_type="ADInplaceOrView",
+    )
+
+
+def use_derived(fn: NativeFunctionWithDifferentiabilityInfo) -> bool:
+    f = fn.func
+    name = cpp.name(f.func)
+    return name not in MANUAL_AUTOGRAD and dispatch_strategy(fn) == "use_derived"
+
+
+def gen_inplace_or_view_type_env(
+    fn: NativeFunctionWithDifferentiabilityInfo,
+) -> dict[str, list[str]]:
+    definition = inplace_or_view_method_definition(fn)
+    registration = inplace_or_view_method_registration(fn)
+
+    return {
+        "ops_headers": (
+            [f"#include "]
+            if definition is not None
+            else []
+        ),
+        "inplace_or_view_method_definitions": [definition]
+        if definition is not None
+        else [],
+        "inplace_or_view_wrapper_registrations": [registration]
+        if registration is not None
+        else [],
+    }
+
+
+def gen_inplace_or_view_type(
+    out: str,
+    native_yaml_path: str,
+    tags_yaml_path: str,
+    fns_with_infos: list[NativeFunctionWithDifferentiabilityInfo],
+    template_path: str,
+) -> None:
+    # NOTE: see Note [Sharded File] at the top of the VariableType.cpp
+    # template regarding sharding of the generated files.
+
+    fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
+    fm.write_sharded(
+        "ADInplaceOrViewType.cpp",
+        [fn for fn in fns_with_infos if use_derived(fn)],
+        key_fn=lambda fn: fn.func.root_name,
+        base_env={
+            "generated_comment": "@"
+            + f"generated from {fm.template_dir_for_comments()}/ADInplaceOrViewType.cpp",
+        },
+        env_callable=gen_inplace_or_view_type_env,
+        num_shards=2,
+        sharded_keys={
+            "ops_headers",
+            "inplace_or_view_method_definitions",
+            "inplace_or_view_wrapper_registrations",
+        },
+    )
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_python_functions.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_python_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a003cadf6b326b3b4e2a58abfd87599645089ae
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_python_functions.py
@@ -0,0 +1,1405 @@
+# Generates Python bindings for ATen functions
+#
+# The bindings are generated as methods on python_variable or functions on the
+# torch._C._nn. torch._C._fft, torch._C._linalg, torch._C._nested, torch._C._sparse
+# or torch._C._special objects.
+#
+
+# Code tries to stick to the following rules:
+#
+# - templates should be colocated with the functions that use them.
+#   no templates are currently shared between functions, but if that
+#   happens, maybe put the template with the first one
+#
+# - don't use environment dictionaries when calling template.substitute().
+#   pass named arguments directly for everything, otherwise it's much too
+#   hard to track what's actually being used and by who
+#
+# - colocate any new hacks/adjustments with existing ones of the same kind.
+#   ideally in a data structure rather than code if possible. See e.g.
+#   SCHEMA_DEFAULT_CONVERSION_HACKS, etc.
+#
+# - similarly, conversions from one format to another should ideally happen
+#   all at once in a single place.
+#
+# - no nontrivial nested functions. couple-liners are ok but please no more.
+#   especially avoid functions that read/write outer variables defined far away.
+#
+# - raise RuntimeError instead of asserting, and put as much
+#   information as is available into the message. I.e. no need to
+#   plumb in new params whose only purpose is to fill out an error
+#   message, but use what's there
+#
+
+from __future__ import annotations
+
+import itertools
+import re
+from collections import defaultdict
+from typing import Callable, TYPE_CHECKING
+
+import yaml
+
+from torchgen.api import cpp
+from torchgen.api.python import (
+    arg_parser_output_exprs,
+    cpp_dispatch_exprs,
+    cpp_dispatch_target,
+    dispatch_lambda_args,
+    dispatch_lambda_exprs,
+    dispatch_lambda_return_str,
+    has_tensor_options,
+    PythonSignature,
+    PythonSignatureDeprecated,
+    PythonSignatureGroup,
+    PythonSignatureNativeFunctionPair,
+    signature,
+    signature_from_schema,
+    structseq_fieldnames,
+)
+from torchgen.code_template import CodeTemplate
+from torchgen.context import with_native_function
+from torchgen.gen import cpp_string, parse_native_yaml, parse_tags_yaml
+from torchgen.model import (
+    Argument,
+    BaseOperatorName,
+    FunctionSchema,
+    NativeFunction,
+    SchemaKind,
+    Type,
+    Variant,
+)
+from torchgen.utils import FileManager, split_name_params
+from torchgen.yaml_utils import YamlLoader
+
+from .gen_inplace_or_view_type import is_tensor_list_type
+from .gen_trace_type import should_trace
+
+
+if TYPE_CHECKING:
+    from collections.abc import Iterable, Sequence
+
+
+#
+# declarations blocklist
+# We skip codegen for these functions, for various reasons.
+# Future PRs will categorize this list and eliminate or hoist
+# them out of eager-only codegen.
+# See https://github.com/pytorch/pytorch/issues/30788
+#
+
+# These functions require manual Python bindings or are not exposed to Python
+_SKIP_PYTHON_BINDINGS = [
+    "alias",
+    "contiguous",
+    "is_cuda",
+    "is_sparse",
+    "is_sparse_csr",
+    "size",
+    "stride",
+    "sym_is_contiguous",
+    "sym_size",
+    "sym_stride",
+    "sym_storage_offset",
+    "sym_numel",
+    ".*_backward",
+    ".*_backward_(out|input|weight|bias)",
+    ".*_forward",
+    ".*_forward_out",
+    ".*_jvp",
+    "_unsafe_view",
+    "tensor",
+    "_?sparse_(coo|compressed|csr|csc|bsr|bsc)_tensor.*",
+    "_range.*",
+    "_sparse_add_out",
+    "_sparse_div.*",
+    "_sparse_mul.*",
+    "_sparse_sub.*",
+    "_sparse_dense_add_out",
+    "index",
+    "index_out",
+    "unique_dim_consecutive",
+    "_cumsum.*",
+    "_cumprod.*",
+    "_sum.*",
+    "_prod.*",
+    "_th_.*",
+    "_thnn_.*",
+    "range.*",
+    "_solve.*",
+    "_inverse.*",
+    "_cholesky.*",
+    "_triangular_solve.*",
+    "_qr.*",
+    "_svd.*",
+    "slice",
+    "item",
+    "_local_scalar_dense",
+    "to",
+    "_to_copy",
+    "_to_copy_out",
+    "_reshape_copy",
+    "_reshape_copy_out",
+    "copy_sparse_to_sparse_",
+    "copy_",
+    "_foreach_copy",
+    "numpy_T",
+    "matrix_H",
+    "mT",
+    "mH",  # these need to be an attributes in Python, not functions
+    "nonzero(_(out|numpy))?",
+    "set_data",
+    ".*_overrideable",  # overridable functions for backend extension
+    "data",
+    "is_leaf",
+    "output_nr",
+    "_version",
+    "requires_grad_",
+    "retains_grad",
+    "set_",
+    "_fw_primal",
+    "fake_quantize_per_tensor_affine_cachemask",
+    "fake_quantize_per_channel_affine_cachemask",
+    "_new_zeros_with_same_feature_meta",
+    "_has_same_storage_numel",  # used for forward AD internals
+    "_reshape_alias",
+    "replace_",  # only used by the functionalization pass, doesn't need to be exposed to python
+    "copy",  # only used by the functionalization pass
+    "fill.Tensor",  # only used by the functionalization pass
+    "fill.Scalar",  # only used by the functionalization pass
+    "lift.*",
+    "normal_functional",  # only used by the functionalization pass
+    "nbytes",
+    "itemsize",
+    "_batch_norm_with_update",
+    "_batch_norm_with_update_out",
+    "_batch_norm_no_update",
+]
+
+SKIP_PYTHON_BINDINGS = [
+    re.compile(rf"^{pattern}$") for pattern in _SKIP_PYTHON_BINDINGS
+]
+
+# These function signatures are not exposed to Python. Note that this signature
+# list does not support regex.
+SKIP_PYTHON_BINDINGS_SIGNATURES = [
+    "add.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor",
+    "add_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!)",
+    "sub.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor",
+    "sub_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!)",
+    "mul.Scalar(Tensor self, Scalar other) -> Tensor",
+    "mul_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)",
+    "div.Scalar(Tensor self, Scalar other) -> Tensor",
+    "div_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)",
+]
+
+
+@with_native_function
+def should_generate_py_binding(f: NativeFunction) -> bool:
+    # NativeFunctions that are entirely code-generated should not get python bindings
+    # because these codegen implementations are often inefficient. A handful of
+    # view_copy style ops were exposed accidentally when they were handwritten and now
+    # that we are moving them to codegen for bc reasons we need to keep them exposed in
+    # python.
+    if "generated" in f.tags and "view_copy" not in f.tags:
+        return False
+
+    name = cpp.name(f.func)
+    for skip_regex in SKIP_PYTHON_BINDINGS:
+        if skip_regex.match(name):
+            return False
+
+    signature = str(f.func)
+    for pattern in SKIP_PYTHON_BINDINGS_SIGNATURES:
+        if pattern == signature:
+            return False
+    return True
+
+
+def get_pycname(name: BaseOperatorName) -> str:
+    return f"THPVariable_{name}"
+
+
+def is_noarg(overloads: Sequence[PythonSignatureNativeFunctionPair]) -> bool:
+    return len(overloads) == 1 and overloads[0].signature.arguments_count() == 0
+
+
+def is_py_variable_method(f: NativeFunction) -> bool:
+    return f.python_module is None and Variant.method in f.variants
+
+
+def is_py_torch_function(f: NativeFunction) -> bool:
+    return f.python_module is None and Variant.function in f.variants
+
+
+def is_py_nn_function(f: NativeFunction) -> bool:
+    return f.python_module == "nn"
+
+
+def is_py_fft_function(f: NativeFunction) -> bool:
+    return f.python_module == "fft"
+
+
+def is_py_linalg_function(f: NativeFunction) -> bool:
+    return f.python_module == "linalg"
+
+
+def is_py_nested_function(f: NativeFunction) -> bool:
+    return f.python_module == "nested"
+
+
+def is_py_sparse_function(f: NativeFunction) -> bool:
+    return f.python_module == "sparse"
+
+
+def is_py_special_function(f: NativeFunction) -> bool:
+    return f.python_module == "special"
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                            Main Function
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+def gen(
+    out: str,
+    native_yaml_path: str,
+    tags_yaml_path: str,
+    deprecated_yaml_path: str,
+    template_path: str,
+    *,
+    symint: bool = True,
+) -> None:
+    fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
+    native_functions = parse_native_yaml(
+        native_yaml_path, tags_yaml_path
+    ).native_functions
+    native_functions = list(filter(should_generate_py_binding, native_functions))
+
+    methods = load_signatures(native_functions, deprecated_yaml_path, method=True)
+    create_python_bindings(
+        fm,
+        methods,
+        is_py_variable_method,
+        None,
+        "python_variable_methods.cpp",
+        method=True,
+        symint=symint,
+    )
+
+    # NOTE: num_shards here must be synced with gatherTorchFunctions in
+    #       torch/csrc/autograd/python_torch_functions_manual.cpp
+    functions = load_signatures(native_functions, deprecated_yaml_path, method=False)
+    create_python_bindings_sharded(
+        fm,
+        functions,
+        is_py_torch_function,
+        "torch",
+        "python_torch_functions.cpp",
+        method=False,
+        num_shards=3,
+        symint=symint,
+    )
+
+    create_python_bindings(
+        fm,
+        functions,
+        is_py_nn_function,
+        "torch.nn",
+        "python_nn_functions.cpp",
+        method=False,
+        symint=symint,
+    )
+
+    create_python_bindings(
+        fm,
+        functions,
+        is_py_fft_function,
+        "torch.fft",
+        "python_fft_functions.cpp",
+        method=False,
+        symint=symint,
+    )
+
+    create_python_bindings(
+        fm,
+        functions,
+        is_py_linalg_function,
+        "torch.linalg",
+        "python_linalg_functions.cpp",
+        method=False,
+        symint=symint,
+    )
+
+    create_python_bindings(
+        fm,
+        functions,
+        is_py_nested_function,
+        "torch.nested",
+        "python_nested_functions.cpp",
+        method=False,
+    )
+
+    create_python_bindings(
+        fm,
+        functions,
+        is_py_sparse_function,
+        "torch.sparse",
+        "python_sparse_functions.cpp",
+        method=False,
+        symint=symint,
+    )
+
+    create_python_bindings(
+        fm,
+        functions,
+        is_py_special_function,
+        "torch.special",
+        "python_special_functions.cpp",
+        method=False,
+        symint=symint,
+    )
+
+    # Currently, we only use `functions` to generate `return_types` bindings.
+    # All methods which return structseq have function variant at this point.
+    # If any method only operator with structseq is added in the future,
+    # we will have to address that.
+    create_python_return_type_bindings(
+        fm, functions, lambda fn: True, "python_return_types.cpp"
+    )
+    create_python_return_type_bindings_header(
+        fm, functions, lambda fn: True, "python_return_types.h"
+    )
+
+    valid_tags = parse_tags_yaml(tags_yaml_path)
+
+    def gen_tags_enum() -> dict[str, str]:
+        return {
+            "enum_of_valid_tags": (
+                "".join(
+                    [f'\n.value("{tag}", at::Tag::{tag})' for tag in sorted(valid_tags)]
+                )
+            )
+        }
+
+    fm.write("python_enum_tag.cpp", gen_tags_enum)
+
+
+def group_filter_overloads(
+    pairs: Sequence[PythonSignatureNativeFunctionPair],
+    pred: Callable[[NativeFunction], bool],
+) -> dict[BaseOperatorName, list[PythonSignatureNativeFunctionPair]]:
+    grouped: dict[BaseOperatorName, list[PythonSignatureNativeFunctionPair]] = (
+        defaultdict(list)
+    )
+    for pair in pairs:
+        if pred(pair.function):
+            grouped[pair.function.func.name.name].append(pair)
+    return grouped
+
+
+def create_python_bindings(
+    fm: FileManager,
+    pairs: Sequence[PythonSignatureNativeFunctionPair],
+    pred: Callable[[NativeFunction], bool],
+    module: str | None,
+    filename: str,
+    *,
+    method: bool,
+    symint: bool = True,
+) -> None:
+    """Generates Python bindings to ATen functions"""
+    py_methods: list[str] = []
+    ops_headers: list[str] = []
+    py_method_defs: list[str] = []
+    py_forwards: list[str] = []
+
+    grouped = group_filter_overloads(pairs, pred)
+
+    for name in sorted(grouped.keys(), key=str):
+        overloads = grouped[name]
+        py_methods.append(
+            method_impl(name, module, overloads, method=method, symint=symint)
+        )
+        py_method_defs.append(method_def(name, module, overloads, method=method))
+        py_forwards.extend(forward_decls(name, overloads, method=method))
+        ops_headers.append(f"#include ")
+
+    fm.write_with_template(
+        filename,
+        filename,
+        lambda: {
+            "generated_comment": "@"
+            + f"generated from {fm.template_dir_for_comments()}/{filename}",
+            "ops_headers": ops_headers,
+            "py_forwards": py_forwards,
+            "py_methods": py_methods,
+            "py_method_defs": py_method_defs,
+        },
+    )
+
+
+def create_python_return_type_bindings(
+    fm: FileManager,
+    pairs: Sequence[PythonSignatureNativeFunctionPair],
+    pred: Callable[[NativeFunction], bool],
+    filename: str,
+) -> None:
+    """
+    Generate function to initialize and return named tuple for native functions
+    which returns named tuple and registration invocations in `python_return_types.cpp`.
+    """
+    py_return_types_definition: list[str] = []
+    py_return_types_registrations: list[str] = []
+
+    grouped = group_filter_overloads(pairs, pred)
+
+    for name in sorted(grouped.keys(), key=str):
+        overloads = grouped[name]
+        definitions, registrations = generate_return_type_definition_and_registrations(
+            overloads
+        )
+        py_return_types_definition.append(
+            "" if not definitions else "\n".join(definitions)
+        )
+        py_return_types_registrations.append(
+            "" if not registrations else "\n".join(registrations)
+        )
+
+    fm.write_with_template(
+        filename,
+        filename,
+        lambda: {
+            "generated_comment": "@"
+            + f"generated from {fm.template_dir_for_comments()}/{filename}",
+            "py_return_types": py_return_types_definition,
+            "py_return_types_registrations": py_return_types_registrations,
+        },
+    )
+
+
+def create_python_return_type_bindings_header(
+    fm: FileManager,
+    pairs: Sequence[PythonSignatureNativeFunctionPair],
+    pred: Callable[[NativeFunction], bool],
+    filename: str,
+) -> None:
+    """
+    Generate function to initialize and return named tuple for native functions
+    which returns named tuple and relevant entry for the map in `python_return_types.cpp`.
+    """
+    py_return_types_declarations: list[str] = []
+
+    grouped = group_filter_overloads(pairs, pred)
+
+    for name in sorted(grouped.keys(), key=str):
+        overloads = grouped[name]
+        declarations = generate_return_type_declarations(overloads)
+        py_return_types_declarations.append(
+            "" if not declarations else "\n".join(declarations)
+        )
+
+    fm.write_with_template(
+        filename,
+        filename,
+        lambda: {
+            "generated_comment": "@"
+            + f"generated from {fm.template_dir_for_comments()}/{filename}",
+            "py_return_types_declarations": py_return_types_declarations,
+        },
+    )
+
+
+def create_python_bindings_sharded(
+    fm: FileManager,
+    pairs: Sequence[PythonSignatureNativeFunctionPair],
+    pred: Callable[[NativeFunction], bool],
+    module: str | None,
+    filename: str,
+    *,
+    method: bool,
+    num_shards: int,
+    symint: bool = True,
+) -> None:
+    """Generates Python bindings to ATen functions"""
+    grouped = group_filter_overloads(pairs, pred)
+
+    def key_func(
+        kv: tuple[BaseOperatorName, list[PythonSignatureNativeFunctionPair]],
+    ) -> str:
+        return kv[0].base
+
+    def env_func(
+        kv: tuple[BaseOperatorName, list[PythonSignatureNativeFunctionPair]],
+    ) -> dict[str, list[str]]:
+        name, fn_pairs = kv
+        return {
+            "ops_headers": [f"#include "],
+            "py_forwards": list(forward_decls(name, fn_pairs, method=method)),
+            "py_methods": [
+                method_impl(name, module, fn_pairs, method=method, symint=symint)
+            ],
+            "py_method_defs": [method_def(name, module, fn_pairs, method=method)],
+        }
+
+    fm.write_sharded(
+        filename,
+        grouped.items(),
+        base_env={
+            "generated_comment": "@"
+            + f"generated from {fm.template_dir_for_comments()}/{filename}",
+        },
+        key_fn=key_func,
+        env_callable=env_func,
+        num_shards=num_shards,
+        sharded_keys={"ops_headers", "py_forwards", "py_methods", "py_method_defs"},
+    )
+
+
+def load_signatures(
+    native_functions: list[NativeFunction],
+    deprecated_yaml_path: str,
+    *,
+    method: bool,
+    skip_deprecated: bool = False,
+    pyi: bool = False,
+) -> Sequence[PythonSignatureNativeFunctionPair]:
+    @with_native_function
+    def gen_signature_pairs(f: NativeFunction) -> PythonSignatureNativeFunctionPair:
+        return PythonSignatureNativeFunctionPair(
+            signature=signature(f, method=method, pyi=pyi),
+            function=f,
+        )
+
+    pairs = list(map(gen_signature_pairs, native_functions))
+    deprecated = load_deprecated_signatures(
+        pairs, deprecated_yaml_path, method=method, pyi=pyi
+    )
+    return pairs if skip_deprecated else pairs + deprecated
+
+
+def load_deprecated_signatures(
+    pairs: Sequence[PythonSignatureNativeFunctionPair],
+    deprecated_yaml_path: str,
+    *,
+    method: bool,
+    pyi: bool,
+) -> list[PythonSignatureNativeFunctionPair]:
+    # The deprecated.yaml doesn't have complete type information, we need
+    # find and leverage the original ATen signature (to which it delegates
+    # the call) to generate the full python signature.
+    # We join the deprecated and the original signatures using type-only form.
+
+    # group the original ATen signatures by name
+    grouped: dict[str, list[PythonSignatureNativeFunctionPair]] = defaultdict(list)
+    for pair in pairs:
+        grouped[pair.signature.name].append(pair)
+
+    # find matching original signatures for each deprecated signature
+    results: list[PythonSignatureNativeFunctionPair] = []
+
+    with open(deprecated_yaml_path) as f:
+        deprecated_defs = yaml.load(f, Loader=YamlLoader)
+
+    for deprecated in deprecated_defs:
+        schema = FunctionSchema.parse(deprecated["name"])
+        aten_name, call_args = split_name_params(deprecated["aten"])
+        is_out = aten_name.endswith("_out")
+        if is_out:
+            aten_name = aten_name.replace("_out", "")
+
+        # HACK: these are fixed constants used to pass the aten function.
+        # The type must be known ahead of time
+        known_constants = {
+            "1": Type.parse("Scalar"),
+        }
+        schema_args_by_name = {a.name: a for a in schema.arguments.flat_all}
+        for name in call_args:
+            assert name in schema_args_by_name or name in known_constants, (
+                f"deprecation definition: Unrecognized value {name}"
+            )
+
+        # Map deprecated signature arguments to their aten signature and test
+        # if the types and alias annotation match.
+        def is_schema_compatible(
+            aten_schema: FunctionSchema,
+        ) -> bool:
+            arguments: Iterable[Argument]
+            if is_out:
+                arguments = itertools.chain(
+                    aten_schema.arguments.out, aten_schema.arguments.flat_non_out
+                )
+            else:
+                arguments = aten_schema.arguments.flat_all
+
+            for i, arg in enumerate(arguments):
+                if i < len(call_args):
+                    arg_name = call_args[i]
+                    if arg_name in known_constants:
+                        schema_type = known_constants[arg_name]
+                        schema_annotation = None
+                    else:
+                        schema_arg = schema_args_by_name[arg_name]
+                        schema_type = schema_arg.type
+                        schema_annotation = schema_arg.annotation
+
+                    if schema_type != arg.type or schema_annotation != arg.annotation:
+                        return False
+                else:
+                    if arg.default is None:
+                        return False
+
+            return len(schema.returns) == len(aten_schema.returns) and all(
+                a == b for a, b in zip(schema.returns, aten_schema.returns)
+            )
+
+        any_schema_found = False
+        for pair in grouped[aten_name]:
+            if not is_schema_compatible(pair.function.func):
+                continue
+            any_schema_found = True
+
+            python_sig = signature_from_schema(
+                schema,
+                category_override=pair.function.category_override,
+                method=method,
+                pyi=pyi,
+            )
+
+            results.append(
+                PythonSignatureNativeFunctionPair(
+                    signature=PythonSignatureDeprecated(
+                        name=python_sig.name,
+                        input_args=python_sig.input_args,
+                        input_kwargs=python_sig.input_kwargs,
+                        output_args=python_sig.output_args,
+                        tensor_options_args=python_sig.tensor_options_args,
+                        method=python_sig.method,
+                        deprecated_schema=schema,
+                        deprecated_args_exprs=tuple(call_args),
+                        returns=python_sig.returns,
+                    ),
+                    function=pair.function,
+                )
+            )
+        assert any_schema_found, (
+            f"No native function with name {aten_name} matched signature:\n  {str(schema)}"
+        )
+
+    return results
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                         Named Tuple Codegen
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+@with_native_function
+def gen_structseq_typename_key(f: NativeFunction) -> str:
+    name = cpp.name(f.func)
+    fieldnames = structseq_fieldnames(f.func.returns)
+    return "_".join([name] + fieldnames)
+
+
+def emit_structseq_call(
+    overloads: Sequence[PythonSignatureNativeFunctionPair],
+) -> tuple[list[str], dict[str, str]]:
+    """
+    Generate block of named tuple type def inits, and add typeref snippets
+    to declarations that use them
+    """
+    typenames: dict[
+        str, str
+    ] = {}  # map from unique name + field name lists to typedef name
+    typedefs: list[str] = []  # typedef declarations and init code
+
+    for overload in overloads:
+        fieldnames = structseq_fieldnames(overload.function.func.returns)
+        if not fieldnames:
+            continue
+
+        name = cpp.name(overload.function.func)  # use @with_native_function?
+        tn_key = gen_structseq_typename_key(overload.function)
+        typename = typenames.get(tn_key)
+        if typename is None:
+            typename = f"NamedTuple{'' if not typedefs else len(typedefs)}"
+            typenames[tn_key] = typename
+            typedefs.append(
+                f"""\
+static PyTypeObject* {typename} = generated::get_{name}_structseq();"""
+            )
+
+    return typedefs, typenames
+
+
+def generate_return_type_definition_and_registrations(
+    overloads: Sequence[PythonSignatureNativeFunctionPair],
+) -> tuple[list[str], list[str]]:
+    """
+    Generate block of function in `python_return_types.cpp` to initialize
+    and return named tuple for a native function which returns named tuple
+    and registration invocations in same file.
+    """
+    typenames: dict[
+        str, str
+    ] = {}  # map from unique name + field name lists to typedef name
+    definitions: list[str] = []  # function definition to register the typedef
+    registrations: list[str] = []  # register call for the typedef
+
+    for overload in overloads:
+        fieldnames = structseq_fieldnames(overload.function.func.returns)
+        if not fieldnames:
+            continue
+
+        fields = ", ".join(f'{{"{fn}", ""}}' for fn in fieldnames)
+
+        name = cpp.name(overload.function.func)  # use @with_native_function?
+        tn_key = gen_structseq_typename_key(overload.function)
+        typename = typenames.get(tn_key)
+
+        if typename is None:
+            typename = f"{name}NamedTuple{'' if not definitions else len(definitions)}"
+            typenames[tn_key] = typename
+            definitions.append(
+                f"""\
+PyTypeObject* get_{name}_structseq() {{
+    static PyStructSequence_Field NamedTuple_fields[] = {{ {fields},  {{nullptr}} }};
+    static PyTypeObject {typename};
+    static bool is_initialized = false;
+    static PyStructSequence_Desc desc = {{ "torch.return_types.{name}", nullptr, NamedTuple_fields, {len(fieldnames)} }};
+    if (!is_initialized) {{
+        PyStructSequence_InitType(&{typename}, &desc);
+        {typename}.tp_repr = (reprfunc)torch::utils::returned_structseq_repr;
+        is_initialized = true;
+    }}
+    return &{typename};
+}}
+"""
+            )
+            registrations.append(
+                f'addReturnType(return_types_module, "{name}", generated::get_{name}_structseq());'
+            )
+
+    return definitions, registrations
+
+
+def generate_return_type_declarations(
+    overloads: Sequence[PythonSignatureNativeFunctionPair],
+) -> list[str]:
+    """
+    Generate block of function declarations in `python_return_types.h` to initialize
+    and return named tuple for a native function.
+    """
+    typenames: dict[
+        str, str
+    ] = {}  # map from unique name + field name lists to typedef name
+    declarations: list[str] = []  # function declaration to register the typedef
+
+    for overload in overloads:
+        fieldnames = structseq_fieldnames(overload.function.func.returns)
+        if not fieldnames:
+            continue
+
+        name = cpp.name(overload.function.func)  # use @with_native_function?
+        tn_key = gen_structseq_typename_key(overload.function)
+        typename = typenames.get(tn_key)
+
+        if typename is None:
+            typename = (
+                f"{name}NamedTuple{'' if not declarations else len(declarations)}"
+            )
+            typenames[tn_key] = typename
+            declarations.append(f"PyTypeObject* get_{name}_structseq();")
+
+    return declarations
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                         Method Impl Codegen
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+# python binding for all overloads of a particular function/method
+PY_VARIABLE_METHOD_VARARGS = CodeTemplate(
+    r"""\
+// ${name}
+static PyObject * ${pycname}(PyObject* self_, PyObject* args, PyObject* kwargs)
+{
+  ${method_header}
+  static PythonArgParser parser({
+    ${signatures}
+  }, /*traceable=*/${traceable});
+
+  ParsedArgs<${max_args}> parsed_args;
+  auto _r = parser.parse(${self_}, args, kwargs, parsed_args);
+  ${check_has_torch_function}
+  switch (_r.idx) {
+    ${dispatch}
+  }
+  ${method_footer}
+}
+
+"""
+)
+
+# handler for a single parsed signature - may be a single overload or
+# a pair of overloads that whose signatures only differ in output params
+# (plugged into PY_VARIABLE_METHOD_VARARGS as an item in ${dispatch})
+PY_VARIABLE_CASE = CodeTemplate(
+    """\
+case ${overload_index}: {
+  ${body}
+}
+"""
+)
+
+# python binding for single-overload function/method
+PY_VARIABLE_METHOD_VARARGS_SINGLETON = CodeTemplate(
+    """\
+// ${name}
+static PyObject * ${pycname}(PyObject* self_, PyObject* args, PyObject* kwargs)
+{
+  ${method_header}
+  static PythonArgParser parser({
+    ${signatures}
+  }, /*traceable=*/${traceable});
+
+  ParsedArgs<${max_args}> parsed_args;
+  auto _r = parser.parse(${self_}, args, kwargs, parsed_args);
+  ${check_has_torch_function}
+  ${dispatch}
+  ${method_footer}
+}
+
+"""
+)
+
+# python binding for a method with no args, shortcuts parsing
+PY_VARIABLE_METHOD_NOARGS = CodeTemplate(
+    """\
+// ${name}
+static PyObject * ${pycname}(PyObject* self_, PyObject* args)
+{
+  ${method_header}
+  ${check_has_torch_function}
+  ${dispatch}
+  ${method_footer}
+}
+
+"""
+)
+
+
+def method_impl(
+    name: BaseOperatorName,
+    module: str | None,
+    overloads: Sequence[PythonSignatureNativeFunctionPair],
+    *,
+    method: bool,
+    symint: bool = True,
+) -> str:
+    """
+    Generate a python binding for all overloads of an op.
+    """
+    pycname = get_pycname(name)
+    noarg = is_noarg(overloads)
+    structseq_inits, structseq_typenames = emit_structseq_call(overloads)
+
+    method_header = ["HANDLE_TH_ERRORS"]
+    method_header += structseq_inits
+    method_header += (
+        ["const Tensor& self = THPVariable_Unpack(self_);"] if method else []
+    )
+
+    method_footer = ([] if noarg else ["Py_RETURN_NONE;"]) + ["END_HANDLE_TH_ERRORS"]
+
+    traceable = "true" if all(should_trace(o.function) for o in overloads) else "false"
+
+    grouped_overloads: Sequence[PythonSignatureGroup] = group_overloads(
+        overloads, symint=symint
+    )
+    is_singleton = len(grouped_overloads) == 1
+    signatures: list[str] = []
+    dispatch: list[str] = []
+    for overload_index, overload in enumerate(grouped_overloads):
+        signature = overload.signature.signature_str(symint=symint)
+        signatures.append(f"{cpp_string(str(signature))},")
+        dispatch_body = emit_dispatch_case(overload, structseq_typenames, symint=symint)
+        dispatch.append(
+            PY_VARIABLE_CASE.substitute(
+                overload_index=overload_index, body=dispatch_body
+            )
+            if not is_singleton
+            else dispatch_body
+        )
+
+    if noarg:
+        template = PY_VARIABLE_METHOD_NOARGS
+    elif is_singleton:
+        template = PY_VARIABLE_METHOD_VARARGS_SINGLETON
+    else:
+        template = PY_VARIABLE_METHOD_VARARGS
+
+    return template.substitute(
+        name=name,
+        pycname=pycname,
+        method_header=method_header,
+        max_args=max(o.signature.arguments_count() for o in overloads),
+        signatures=signatures,
+        traceable=traceable,
+        check_has_torch_function=gen_has_torch_function_check(
+            name=name,
+            module=module,
+            noarg=noarg,
+            method=method,
+        ),
+        dispatch=dispatch,
+        method_footer=method_footer,
+        self_="self_" if method else "nullptr",
+    )
+
+
+def gen_has_torch_function_check(
+    name: BaseOperatorName, module: str | None, *, noarg: bool, method: bool
+) -> str:
+    if noarg:
+        if method:
+            return f"""\
+if(check_has_torch_function(self_)) {{
+  return handle_torch_function(self_, "{name}");
+}}
+"""
+        else:
+            return ""
+
+    self_ = "self_" if method else "nullptr"
+    namespace = (
+        {
+            "torch": "THPVariableFunctionsModule",
+            "torch.nn": "THPNNVariableFunctionsModule",
+            "torch.fft": "THPFFTVariableFunctionsModule",
+            "torch.linalg": "THPLinalgVariableFunctionsModule",
+            "torch.nested": "THPNestedVariableFunctionsModule",
+            "torch.sparse": "THPSparseVariableFunctionsModule",
+            "torch.special": "THPSpecialVariableFunctionsModule",
+        }[module]
+        if module
+        else "THPVariableClass"
+    )
+
+    return f"""\
+if(_r.has_torch_function()) {{
+  return handle_torch_function(_r, {self_}, args, kwargs, {namespace}, "{module or "torch.Tensor"}");
+}}
+"""
+
+
+# handler for output/no-output overload pair
+PY_VARIABLE_OUT = CodeTemplate(
+    """\
+if (_r.isNone(${out_idx})) {
+  ${call_dispatch}
+} else {
+  ${call_dispatch_out}
+}
+"""
+)
+
+
+def emit_dispatch_case(
+    overload: PythonSignatureGroup,
+    structseq_typenames: dict[str, str],
+    *,
+    symint: bool = True,
+) -> str:
+    """
+    Emit dispatch code for a single parsed signature. This corresponds to either
+    a single native function, or a pair that differ only in output params. In the
+    latter case, a single python signature is used for both and dispatching
+    switches on the presence/absence of passed output args.
+    """
+    if overload.outplace is not None:
+        # dispatch output and no-output variants, branch on _r.isNone()
+        return PY_VARIABLE_OUT.substitute(
+            out_idx=overload.signature.output_idx(),
+            call_dispatch=emit_single_dispatch(
+                overload.signature, overload.base, structseq_typenames, symint=symint
+            ),
+            call_dispatch_out=emit_single_dispatch(
+                overload.signature,
+                overload.outplace,
+                structseq_typenames,
+                symint=symint,
+            ),
+        )
+    else:
+        # no-output version only
+        return emit_single_dispatch(
+            overload.signature, overload.base, structseq_typenames, symint=symint
+        )
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                    Forward Declarations Codegen
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+def forward_decls(
+    name: BaseOperatorName,
+    overloads: Sequence[PythonSignatureNativeFunctionPair],
+    *,
+    method: bool,
+) -> tuple[str, ...]:
+    if method:
+        return ()
+
+    pycname = get_pycname(name)
+    if is_noarg(overloads):
+        return (
+            f"""\
+static PyObject * {pycname}(PyObject* self_, PyObject* args);
+""",
+        )
+    else:
+        return (
+            f"""\
+static PyObject * {pycname}(PyObject* self_, PyObject* args, PyObject* kwargs);
+""",
+        )
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#              Method Def (Binding Table Entry) Codegen
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+def method_def(
+    name: BaseOperatorName,
+    module: str | None,
+    overloads: Sequence[PythonSignatureNativeFunctionPair],
+    *,
+    method: bool,
+) -> str:
+    """
+    Generate method def entry.
+    """
+    pycname = get_pycname(name)
+
+    if name.dunder_method:
+        # PyMethodDef entry for binary op, throws not implemented error
+        pycname = f"TypeError_to_NotImplemented_<{pycname}>"
+
+    if is_noarg(overloads):
+        flags = "METH_NOARGS" if method else "METH_VARARGS | METH_KEYWORDS"
+    else:
+        pycname = f"castPyCFunctionWithKeywords({pycname})"
+        flags = "METH_VARARGS | METH_KEYWORDS"
+
+    if module == "torch":
+        flags += " | METH_STATIC"
+
+    return f'{{"{name}", {pycname}, {flags}, nullptr}},'
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                   Overload Sorting and Grouping
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+def group_overloads(
+    overloads: Sequence[PythonSignatureNativeFunctionPair], *, symint: bool = True
+) -> Sequence[PythonSignatureGroup]:
+    bases: dict[str, PythonSignatureNativeFunctionPair] = {}
+    outplaces: dict[str, PythonSignatureNativeFunctionPair] = {}
+
+    # first group by signature ignoring out arguments
+    for overload in overloads:
+        sig = overload.signature.signature_str(skip_outputs=True, symint=symint)
+        if overload.function.func.is_out_fn():
+            if sig in outplaces:
+                raise RuntimeError(
+                    f"Found duplicated function definition:\n- {overload.function.func}.\n"
+                    f"Existing definition:\n- {outplaces[sig].function.func}."
+                )
+            outplaces[sig] = overload
+        else:
+            if sig in bases:
+                raise RuntimeError(
+                    f"Found duplicated function definition:\n- {overload.function.func}.\n"
+                    f"Existing definition:\n- {bases[sig].function.func}."
+                )
+            bases[sig] = overload
+
+    for sig, out in outplaces.items():
+        if sig not in bases:
+            candidates: list[str] = []
+            for overload in overloads:
+                if (
+                    str(overload.function.func.name.name)
+                    == str(out.function.func.name.name)
+                    and not overload.function.func.is_out_fn()
+                    and not overload.signature.deprecated
+                ):
+                    candidates.append(
+                        overload.signature.signature_str(
+                            skip_outputs=True, symint=symint
+                        )
+                    )
+            out_sig = out.signature.signature_str(symint=symint)
+            raise RuntimeError(
+                f"While identifying overloads, we found an out schema {out_sig} without a corresponding non-out variant. "
+                f"We expected the non-out variant to have schema: \n- {sig}\nPlease check that you spelled the schema "
+                "correctly in native_functions.yaml. We discovered the following candidate(s): \n"
+                + "\n".join(f"- {candidate}" for candidate in candidates)
+            )
+
+    grouped = [
+        PythonSignatureGroup.from_pairs(
+            functional=base,
+            out=outplaces.get(sig),
+        )
+        for sig, base in bases.items()
+    ]
+    return sort_overloads(grouped, symint=symint)
+
+
+# This function declares a partial order on declarations, and sorts them according
+# to its linear extension. This is necessary, because there's some ambiguity in the
+# choice of overload, and we want a different order.
+#
+# See Note[Order of overloads matters]
+#
+# A few examples of ambiguous python signature pairs.
+#
+#   All parameters have the same type, except one taking Tensor the other taking
+#   Scalar. A numeric PyObject can be casted into Tensor, and a zero-dim Tensor
+#   object can be accepted as Scalar type parameter (see python_arg_parser.cpp).
+#   Therefore, same input arguments might be accepted by either python signature.
+#   We want to always parse the one taking Tensor first.
+#
+#     bitwise_and(Tensor input, Tensor other, *, Tensor out=None)
+#     bitwise_and(Tensor input, Scalar other, *, Tensor out=None)
+#
+#   If they have different number of parameters then they are not ambiguous - but
+#   the difference on output param can be ignored as it's optional.
+#
+#     multiply(Tensor input, Tensor other, *, Tensor out=None)
+#     multiply(Tensor input, Scalar other)
+#
+#   Both positional args and keyword-only args are considered together.
+#
+#     subtract(Tensor other, *, Scalar alpha=1)
+#     subtract(Scalar other, Scalar alpha=1)
+#
+# A few ambiguous cases which it does NOT handle yet.
+#
+#   If there is any difference in other parameters besides the Tensor/Scalar
+#   difference, then they are not considered ambiguous by this method anymore.
+#   However, the difference could be too trivial to disambiguate.
+#
+#     foo(Tensor input, Scalar other, Scalar bar)
+#     foo(Tensor input, Tensor other, double bar)
+#
+#   If they are taking different number of parameters then they are not considered
+#   ambiguous anymore, even if the difference is only on optional kwargs.
+#
+#     foo(Scalar other, Scalar alpha=1)
+#     foo(Tensor other, *, Scalar alpha=1, Scalar beta=1)
+#
+
+
+def sort_overloads(
+    grouped_overloads: Sequence[PythonSignatureGroup], *, symint: bool = True
+) -> Sequence[PythonSignatureGroup]:
+    # NB: Smaller here means lower priority
+
+    def is_arg_smaller(t1: Type, t2: Type) -> bool:
+        return (
+            str(t1) == "Scalar"
+            and str(t2) == "Tensor"
+            or str(t1) == "Scalar?"
+            and str(t2) == "Tensor?"
+            or "Dimname" in str(t1)
+            and "Dimname" not in str(t2)
+            or
+            # In the discussion https://github.com/pytorch/pytorch/issues/54555 it has been
+            # discussed why it is important to prioritize int/int? over int[]
+            str(t1) == "int[]"
+            and (str(t2) == "int" or str(t2) == "int?")
+            or
+            # TensorList currently throws an error during argument parsing, that's why it needs to be
+            # last in signature ordering. See discussion: https://github.com/pytorch/pytorch/issues/58087
+            str(t1) == "Tensor[]"
+            and str(t2).find("[]") != -1
+            or
+            # Prioritize IntArrayRef overload over SymIntArrayRef
+            str(t1) == "SymInt[]"
+            and str(t2) == "int[]"
+            or
+            # Make sure both in, SymInt are sorted consistently w.r.t. Tensor since Tensor can be implicitly
+            # converted to either int or SymInt.  Prioritize the Tensor overload since it otherwise gets shadowed.
+            (str(t1) == "SymInt" or str(t1) == "int")
+            and str(t2) == "Tensor"
+        )
+
+    def is_smaller(s1: PythonSignature, s2: PythonSignature) -> bool:
+        """Returns True if s1 < s2 in the partial order."""
+        args1, args2 = s1.arguments(skip_outputs=True), s2.arguments(skip_outputs=True)
+        if len(args1) != len(args2):
+            return False
+        # TODO: should use some canonical form instead of 'str(arg.type)' - see comments
+        # above. The old codegen used the deprecated 'dynamic_type(arg.type)', which
+        # ignores the optional annotation, i.e. 'Scalar' and 'Scalar?'.
+        equal = all(arg1.type == arg2.type for arg1, arg2 in zip(args1, args2))
+        smaller_or_equal = all(
+            str(arg1.type) == str(arg2.type) or is_arg_smaller(arg1.type, arg2.type)
+            for arg1, arg2 in zip(args1, args2)
+        )
+        return smaller_or_equal and not equal
+
+    # First sort by signature
+    grouped_overloads = sorted(
+        grouped_overloads, key=lambda x: x.signature.signature_str(symint=symint)
+    )
+
+    # Construct the relation graph
+    larger_than: dict[int, set[int]] = defaultdict(set)
+    for i1, overload1 in enumerate(grouped_overloads):
+        for i2, overload2 in enumerate(grouped_overloads):
+            if is_smaller(overload1.signature, overload2.signature):
+                larger_than[i1].add(i2)
+
+    if not larger_than:
+        return list(grouped_overloads)
+
+    # Use a topological sort to sort overloads according to the partial order.
+    N = len(grouped_overloads)
+    sorted_ids: list[int] = list(filter(lambda x: x not in larger_than, range(N)))
+
+    for idx in range(N):
+        # The size of sorted_ids will grow to N eventually.
+        i = sorted_ids[idx]
+        for j in sorted(larger_than.keys()):
+            larger = larger_than[j]
+            larger.discard(i)
+            if not larger:
+                del larger_than[j]
+                sorted_ids.append(j)
+
+    return [grouped_overloads[x] for x in sorted_ids]
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+#                       Codegen API Integration
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+def emit_single_dispatch(
+    ps: PythonSignature,
+    f: NativeFunction,
+    structseq_typenames: dict[str, str],
+    *,
+    symint: bool = True,
+) -> str:
+    """
+    Emit dispatch code for a single native function.
+    """
+
+    @with_native_function
+    def go(f: NativeFunction) -> str:
+        # header comments
+        if isinstance(ps, PythonSignatureDeprecated):
+            schema_comment = f"// [deprecated] aten::{ps.deprecated_schema}"
+        else:
+            schema_comment = f"// aten::{f.func}"
+
+        # dispatch lambda signature
+        name = cpp.name(f.func)
+        lambda_formals = ", ".join(
+            f"{a.type_str} {a.name}" for a in dispatch_lambda_args(ps, f, symint=symint)
+        )
+        lambda_return = dispatch_lambda_return_str(f)
+
+        # dispatch lambda body
+        dispatch_callee = cpp_dispatch_target(f)
+        dispatch_args = ", ".join(cpp_dispatch_exprs(f, python_signature=ps))
+
+        # from arg parser outputs to dispatch lambda arguments
+        parser_outputs = arg_parser_output_exprs(ps, f, symint=symint)
+        lambda_arg_exprs = dispatch_lambda_exprs(ps, f, symint=symint)
+        inits = "\n".join(lambda_arg_exprs.inits)
+        lambda_args = ", ".join(lambda_arg_exprs.exprs)
+
+        # scatter fields
+        # TODO: Checking `ps.method and ('requires_grad' in parser_outputs)` is a hacky
+        #       solution for enabling the 'requires_grad' argument for tensor methods
+        #       new_full, new_empty, and new_zeros. A much better but more difficult to
+        #       implement solution involves refactoring according to Ed's description here:
+        #       https://github.com/pytorch/pytorch/issues/36455#issuecomment-614767589
+        need_set_requires_grad = ps.tensor_options_args and (
+            not has_tensor_options(f)
+            or (ps.method and ("requires_grad" in parser_outputs))
+        )
+        set_requires_grad = (
+            f".set_requires_grad({parser_outputs['requires_grad'].expr})"
+            if need_set_requires_grad
+            else ""
+        )
+
+        if lambda_return == "void":
+            # Make in-place foreach return `self` at python-binding level.
+            # ref: https://github.com/pytorch/pytorch/pull/118622#pullrequestreview-1904804954
+            self_arg = f.func.arguments.self_arg
+            return_stmt: str
+            if (
+                str(f.func.name).startswith("_foreach_")
+                and f.func.kind() == SchemaKind.inplace
+            ):
+                # note(crcrpar): `_foreach_pow.ScalarAndTensor` does NOT have its in-place
+                # variant and it unlikely to have it in the future. Thus it's safe to have the following assert.
+                assert self_arg is not None and is_tensor_list_type(
+                    self_arg.argument.type
+                )
+                return_stmt = """PyObject* self_tensorlist = _r.args[0];
+Py_INCREF(self_tensorlist);
+return self_tensorlist;
+"""
+            else:
+                return_stmt = "Py_RETURN_NONE;"
+            return f"""\
+{schema_comment}
+{inits}
+auto dispatch_{name} = []({lambda_formals}) -> {lambda_return} {{
+  pybind11::gil_scoped_release no_gil;
+  {dispatch_callee}({dispatch_args});
+}};
+dispatch_{name}({lambda_args}){set_requires_grad};
+{return_stmt}
+"""
+        else:
+            typename = structseq_typenames.get(gen_structseq_typename_key(f))
+            structseq_typeref = f"{typename}, " if typename is not None else ""
+            return f"""\
+{schema_comment}
+{inits}
+auto dispatch_{name} = []({lambda_formals}) -> {lambda_return} {{
+  pybind11::gil_scoped_release no_gil;
+  return {dispatch_callee}({dispatch_args});
+}};
+return wrap({structseq_typeref}dispatch_{name}({lambda_args}){set_requires_grad});
+"""
+
+    return go(f)
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_trace_type.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_trace_type.py
new file mode 100644
index 0000000000000000000000000000000000000000..21069b4671e24eab40106d27871282a5553416c6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_trace_type.py
@@ -0,0 +1,539 @@
+from __future__ import annotations
+
+import itertools
+from typing import TYPE_CHECKING
+
+from torchgen.api import cpp
+from torchgen.api.types import DispatcherSignature
+from torchgen.code_template import CodeTemplate
+from torchgen.context import with_native_function
+from torchgen.model import Argument, NativeFunction, SchemaKind, TensorOptionsArguments
+from torchgen.utils import FileManager
+
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+
+
+# Note [Manual Backend kernels]
+# For these ops, we want to manually register to dispatch key Backend and
+# skip codegen-ed registration to all keys before Backend.
+# For codegen this means:
+#   - op set below must match ops with manual_kernel_registration=True in native_functions.yaml
+#     where we skip codegen backend kernels
+#   - all ops below are part of MANUAL_AUTOGRAD to skip codegen Autograd kernel registration
+#   - all ops below are part of MANUAL_TRACER to skip codegen Tracer kernel registration
+# Note: we still register to dispatch key Profiler for these ops, keeping it untouched for now.
+# You can find the manual registration in torch/csrc/autograd/VariableTypeManual.cpp
+MANUAL_BACKEND = {
+    "options",
+    "data",
+    "set_data",
+    "is_leaf",
+    "output_nr",
+    "_version",
+    "retain_grad",
+    "_backward",
+    "requires_grad_",
+}
+
+# For these ops we want to skip the codegen-ed registration to both Autograd and Tracer keys.
+# You can find the manual registration in torch/csrc/autograd/VariableTypeManual.cpp
+MANUAL_AUTOGRAD_AND_TRACER = {
+    "resize_",
+    "resize_as_",
+    "detach",
+    "detach_",
+    "copy_",
+    "_fw_primal",
+    "_make_dual",
+}
+
+# Currently MANUAL_AUTOGRAD and MANUAL_TRACER share the same set of ops:
+#   union(MANUAL_BACKEND, MANUAL_AUTOGRAD_AND_TRACER)
+# You can find the manual registration in torch/csrc/autograd/VariableTypeManual.cpp
+MANUAL_AUTOGRAD = MANUAL_TRACER = MANUAL_BACKEND | MANUAL_AUTOGRAD_AND_TRACER
+
+# These functions we don't want to record for tracing, because we always want
+# to trace their constituent parts.  This is a temporary hack in lieue
+# of proper scopes, where subsequent compilation passes can ask for the unfolding
+# on demand.  Only concrete ATen methods can be disabled this way; it will have
+# NO EFFECT otherwise.
+DONT_RECORD_TRACE = {
+    "convolution",
+    "conv1d",
+    "conv2d",
+    "conv3d",
+    "conv_transpose1d",
+    "conv_transpose2d",
+    "conv_transpose3d",
+    "lstm_cell",
+    "gru_cell",
+    "rnn_tanh_cell",
+    "rnn_relu_cell",
+    # FIXME: figure out a better way when we support sparse tensors in jit
+    "_coalesced",
+}
+
+
+def should_trace(f: NativeFunction) -> bool:
+    # Operations involving Storage or Type are not traceable at the moment
+    if any(
+        str(arg.type) in {"Storage", "Type"} for arg in f.func.schema_order_arguments()
+    ):
+        return False
+    # We can't trace functions which don't have any Tensor or TensorList returns
+    if not any(r.type.is_tensor_like() for r in f.func.returns):
+        return False
+    return f.func.name.name.base not in DONT_RECORD_TRACE
+
+
+SELECT = CodeTemplate(
+    """\
+
+if (${cond}) {
+  ${true}
+} else {
+  ${false}
+}
+"""
+)
+
+OP_NAME = CodeTemplate(
+    """\
+op_name = c10::Symbol::fromQualString("aten::${trace_name}");
+"""
+)
+
+# These functions have their names recorded under trace renamed,
+RENAME_TRACE = {
+    "zero": "zeros_like",  # replacing aten::zero_ with aten::zeros_like
+    "fill": "full_like",  # replacing aten::fill_ with aten::full_like
+}
+
+
+def format_trace_op_name(f: NativeFunction) -> str:
+    # TODO: byte-for-byte compatible with old codegen behavior - should clean up
+    if (
+        f.func.kind() in (SchemaKind.functional, SchemaKind.out)
+        or f.func.name.name.dunder_method
+    ):
+        # special case for *_out functions: the in-place and out-of-place ops
+        # are overloaded with the same name in the JIT
+        trace_name = str(f.func.name.name)
+        trace_name = RENAME_TRACE.get(trace_name, trace_name)
+        return OP_NAME.substitute(trace_name=trace_name)
+
+    # otherwise, this is an in-place op and we need to emit both in- and
+    # out-of-place versions
+    outplace_trace_name = f.func.name.name.base
+    inplace_trace_name = cpp.name(f.func)
+    outplace_trace_name = RENAME_TRACE.get(outplace_trace_name, outplace_trace_name)
+    inplace_trace_name = RENAME_TRACE.get(inplace_trace_name, inplace_trace_name)
+
+    return SELECT.substitute(
+        cond="tracer_state->force_outplace",
+        true=OP_NAME.substitute(trace_name=outplace_trace_name),
+        false=OP_NAME.substitute(trace_name=inplace_trace_name),
+    )
+
+
+ADD_TRACE_INPUT = CodeTemplate("""jit::tracer::addInputs(node, "${name}", ${input});""")
+
+
+def format_trace_inputs(f: NativeFunction) -> str:
+    def dispatch_trace_input(arg: Argument | TensorOptionsArguments) -> Sequence[str]:
+        if isinstance(arg, TensorOptionsArguments):
+            name = "options"
+            return [
+                ADD_TRACE_INPUT.substitute(
+                    name=name, input="c10::optTypeMetaToScalarType(options.dtype_opt())"
+                ),
+                ADD_TRACE_INPUT.substitute(name=name, input="options.layout()"),
+                ADD_TRACE_INPUT.substitute(name=name, input="options.device()"),
+                ADD_TRACE_INPUT.substitute(name=name, input="options.pinned_memory()"),
+            ]
+        else:
+            name = arg.name
+            if str(arg.type) == "Tensor?[]":
+                return [f'jit::tracer::addInputs(node, "{name}", {name});']
+            else:
+                return [ADD_TRACE_INPUT.substitute(name=name, input=name)]
+
+    args: list[Argument | TensorOptionsArguments] = list(
+        f.func.schema_order_arguments()
+    )
+
+    if f.func.is_out_fn():
+        # *_out functions take the result as a separate argument, but we don't want to
+        # trace that argument directly. Instead, we trace its TensorOptions.
+        # So first, we need to remove the out argument from the list of arguments to trace.
+        num_out_args = len(f.func.arguments.out)
+        args = args[:-num_out_args]
+
+    trace_inputs = itertools.chain.from_iterable(
+        dispatch_trace_input(arg) for arg in args
+    )
+
+    if f.func.is_out_fn():
+        # for *_out functions, handle the result argument differently for inplace/outplace.
+        # For inplace: just add the input to the end to confirm with the JIT schema
+        inplace = [
+            ADD_TRACE_INPUT.substitute(
+                name=f.func.arguments.out[i].name, input=f.func.arguments.out[i].name
+            )
+            for i in range(num_out_args)
+        ]
+
+        # for outplace: do nothing, except if the function is a factory.
+        # Factories are a bit special because their out-of-place overloads
+        # take an extra TensorOptions argument, which is missing in the _out function
+        has_tensor_return = any(r.type.is_tensor_like() for r in f.func.returns)
+        has_tensor_input_arg = any(
+            a.type.is_tensor_like() for a in f.func.arguments.flat_non_out
+        )
+        is_factory_method = f.category_override == "factory" or (
+            has_tensor_return and not has_tensor_input_arg
+        )
+
+        # HACK: preserve old codegen behavior - the old codegen set the `is_factory_method`
+        # flag for the whole family of ops with the same basename if any of them is a
+        # factory method. For most cases the whole family of ops are indeed all factory
+        # method - 'normal' is the only exception. So we handle it specially here to avoid
+        # cloning the old logic.
+        if f.func.name.name.base == "normal":
+            is_factory_method = True
+
+        if is_factory_method:
+            outplace = [
+                ADD_TRACE_INPUT.substitute(
+                    name="out",
+                    input="c10::optTypeMetaToScalarType(out.options().dtype_opt())",
+                ),
+                ADD_TRACE_INPUT.substitute(name="out", input="out.options().layout()"),
+                ADD_TRACE_INPUT.substitute(name="out", input="out.options().device()"),
+                ADD_TRACE_INPUT.substitute(
+                    name="out", input="out.options().pinned_memory()"
+                ),
+            ]
+        else:
+            outplace = []
+
+        trace_inputs = itertools.chain(
+            trace_inputs,
+            [
+                SELECT.substitute(
+                    cond="tracer_state->force_outplace",
+                    true="\n".join(outplace),
+                    false="\n".join(inplace),
+                )
+            ],
+        )
+
+    return "\n".join(trace_inputs)
+
+
+# `torch.jit.trace` have undocumented keyword argument `_force_outplace`,
+# which force jit to replace functions with outplace variants (for
+# example `aten::add_` becomes `aten::add`).
+#
+# This replacement implemented in-place with minimum modifications of
+# arguments stack (as it assumes that outplace call has the same arguments
+# as inplace version).
+#
+# However there are no such substitutions available for `aten::fill_`
+# and `aten::zero_` operators, as we never implemented `aten::fill`
+# and `aten::zero`. So jit tracing hack replacing `aten::zero_` with
+# `aten::zeros_like` and replacing `aten::fill_` with `aten::full_like`.
+#
+# But as they potentially can have different arguments, we also have
+# to hack into the stack and add missing ones.
+#
+# A possible alternative would be:
+#
+#  - Add `aten::fill` and `aten::zero`
+#
+#  - Or keep `aten::zeros_like` arguments aligned with `aten::zero_`
+# arguments (inside of the `native_functions.yaml`)
+RENAME_TRACE_ADD_ARGS = {
+    "fill": """\
+    jit::tracer::addInputs(node, "options", ::std::optional());
+    jit::tracer::addInputs(node, "options", layout_or_default(::std::nullopt));
+    jit::tracer::addInputs(node, "options", device_or_default(::std::nullopt));
+    jit::tracer::addInputs(node, "options", pinned_memory_or_default(::std::nullopt));
+    ::std::optional memory_format = c10::MemoryFormat::Preserve;
+    jit::tracer::addInputs(node, "memory_format", memory_format);
+""",
+    "zero": """\
+    jit::tracer::addInputs(node, "options", ::std::optional());
+    jit::tracer::addInputs(node, "options", layout_or_default(::std::nullopt));
+    jit::tracer::addInputs(node, "options", device_or_default(::std::nullopt));
+    jit::tracer::addInputs(node, "options", pinned_memory_or_default(::std::nullopt));
+    ::std::optional memory_format = c10::MemoryFormat::Preserve;
+    jit::tracer::addInputs(node, "memory_format", memory_format);
+""",
+}
+
+INPLACE_GUARD = CodeTemplate(
+    """\
+jit::tracer::ensureUniqueIfOutOfPlaced("${name}", ${mutable_input});
+"""
+)
+
+PRE_RECORD_TRACE = CodeTemplate(
+    """\
+torch::jit::Node* node = nullptr;
+std::shared_ptr tracer_state;
+if (jit::tracer::isTracing()) {
+  tracer_state = jit::tracer::getTracingState();
+  at::Symbol op_name;
+  ${set_op_name}
+  node = tracer_state->createNode(op_name, /*num_outputs=*/0);
+  jit::tracer::recordSourceLocation(node);
+  ${add_trace_inputs}
+  tracer_state->insertNode(node);
+  ${inplace_guard}
+  jit::tracer::setTracingState(nullptr);
+}
+"""
+)
+
+
+def format_prerecord_trace(f: NativeFunction) -> str:
+    if not should_trace(f):
+        return ""
+
+    # TODO: clean up old codegen behavior
+    is_inplace = (
+        f.func.kind() in (SchemaKind.inplace, SchemaKind.out)
+        and not f.func.name.name.dunder_method
+    )
+    add_args = (
+        RENAME_TRACE_ADD_ARGS.get(f.func.name.name.base, "") if is_inplace else ""
+    )
+    additional_inputs = (
+        SELECT.substitute(
+            cond="tracer_state->force_outplace",
+            true=add_args,
+            false="",
+        )
+        if add_args
+        else ""
+    )
+
+    return PRE_RECORD_TRACE.substitute(
+        set_op_name=format_trace_op_name(f),
+        add_trace_inputs=format_trace_inputs(f) + additional_inputs,
+        inplace_guard=INPLACE_GUARD.substitute(
+            name=cpp.name(f.func),
+            mutable_input=f.func.arguments.out[0].name
+            if f.func.arguments.out
+            else "self",
+        )
+        if is_inplace
+        else "",
+    )
+
+
+POST_RECORD_TRACE = CodeTemplate(
+    """\
+if (tracer_state) {
+  jit::tracer::setTracingState(std::move(tracer_state));
+  ${add_trace_outputs}
+}
+"""
+)
+
+
+def format_postrecord_trace(f: NativeFunction) -> str:
+    if not should_trace(f):
+        return ""
+
+    # For outplacing ops, *_out overloads require special handling to move the
+    # output *argument* to a return value
+    if f.func.is_out_fn():
+        output_names_outplace = [arg.name for arg in f.func.arguments.out]
+        output_names_inplace = cpp.return_names(f)
+
+        # Code size optimization: the common case is that the return value is
+        # the same for both variants
+        if output_names_outplace == output_names_inplace:
+            outputs = [
+                f"jit::tracer::addOutput(node, {n});" for n in output_names_outplace
+            ]
+            return POST_RECORD_TRACE.substitute(add_trace_outputs=outputs)
+
+        selection = SELECT.substitute(
+            cond="force_outplace",
+            true="\n".join(
+                f"jit::tracer::addOutput(node, {n});" for n in output_names_outplace
+            ),
+            false="\n".join(
+                f"jit::tracer::addOutput(node, {n});" for n in output_names_inplace
+            ),
+        )
+        return POST_RECORD_TRACE.substitute(add_trace_outputs=selection)
+    else:
+        output_names = cpp.return_names(f)
+        outputs = [f"jit::tracer::addOutput(node, {n});" for n in output_names]
+        return POST_RECORD_TRACE.substitute(add_trace_outputs=outputs)
+
+
+def tie_return_values(f: NativeFunction) -> str:
+    if len(f.func.returns) == 1:
+        return f"auto {f.func.returns[0].name or 'result'}"
+    names = cpp.return_names(f)
+    return f"auto [{', '.join(names)}]"
+
+
+def get_return_value(f: NativeFunction) -> str:
+    names = cpp.return_names(f)
+    if len(f.func.returns) == 1:
+        return names[0]
+    if f.func.kind() == SchemaKind.out:
+        return f"std::forward_as_tuple({', '.join(names)})"
+    else:
+        moved = ", ".join(f"std::move({name})" for name in names)
+        return f"std::make_tuple({moved})"
+
+
+TRACE_DISPATCH = CodeTemplate(
+    """\
+${assign_return_values}at::_ops::${unambiguous_name}::redispatch(${unpacked_args});"""
+)
+
+
+def emit_trace_body(f: NativeFunction) -> list[str]:
+    trace_body: list[str] = []
+
+    trace_body.append(format_prerecord_trace(f))
+
+    dispatcher_sig = DispatcherSignature.from_schema(f.func)
+    dispatcher_exprs = dispatcher_sig.exprs()
+
+    # code-generated tracing kernels plumb and recompute dispatch keys directly through the kernel for performance.
+    # See Note [Plumbing Keys Through The Dispatcher] for details.
+    dispatch_key_set = "ks & c10::DispatchKeySet(c10::DispatchKeySet::FULL_AFTER, c10::DispatchKey::Tracer)"
+    redispatch_args = ", ".join([dispatch_key_set] + [a.expr for a in dispatcher_exprs])
+
+    assign_return_values = (
+        f"{tie_return_values(f)} = "
+        if f.func.kind() in [SchemaKind.functional, SchemaKind.mutable]
+        and f.func.returns
+        else ""
+    )
+
+    # Note that this calls the slow, dispatching variants of manual_cpp_binding ops.
+    # We could probably work harder to ensure that the fast variants are
+    # called instead, but the perf benefit would be minimal.
+    trace_body.append(
+        TRACE_DISPATCH.substitute(
+            assign_return_values=assign_return_values,
+            unambiguous_name=f.func.name.unambiguous_name(),
+            unpacked_args=redispatch_args,
+        )
+    )
+
+    trace_body.append(format_postrecord_trace(f))
+    if f.func.returns:
+        trace_body.append(f"return {get_return_value(f)};")
+    return trace_body
+
+
+METHOD_DEFINITION = CodeTemplate(
+    """\
+${return_type} ${type_wrapper_name}(${formals}) {
+  ${type_definition_body}
+}
+"""
+)
+
+
+def type_wrapper_name(f: NativeFunction, key: str = "Default") -> str:
+    if f.func.name.overload_name:
+        name = f"{cpp.name(f.func)}_{f.func.name.overload_name}"
+    else:
+        name = cpp.name(f.func)
+
+    # The key argument is only used in gen_variable_type where we need fns per autograd dispatch key.
+    # In gen_trace_type and gen_inplace_view_type where only one fn per native_fn must be generated,
+    # the key argument should not be passed.
+    # We do not append key if it is Default so that generated functions from
+    # before per-dispatch-key derivatives were added retain the same names.
+    if key != "Default":
+        name = name + f"_{key}"
+    return name
+
+
+@with_native_function
+def method_definition(f: NativeFunction) -> str:
+    assert cpp.name(f.func) not in MANUAL_TRACER
+
+    formals = ", ".join(
+        # code-generated tracing kernels plumb and recompute dispatch keys directly through the kernel for performance.
+        # See Note [Plumbing Keys Through The Dispatcher] for details.
+        ["c10::DispatchKeySet ks"]
+        + [
+            f"{cpp.argument_type(a, binds='__placeholder__', symint=True).cpp_type()} {a.name}"
+            for a in f.func.schema_order_arguments()
+        ]
+    )
+
+    return METHOD_DEFINITION.substitute(
+        return_type=cpp.returns_type(f.func.returns, symint=True).cpp_type(),
+        type_wrapper_name=type_wrapper_name(f),
+        formals=formals,
+        type_definition_body=emit_trace_body(f),
+    )
+
+
+WRAPPER_REGISTRATION = CodeTemplate(
+    """\
+m.impl("${name}",
+       TORCH_FN(${class_type}::${type_wrapper_name})
+);
+"""
+)
+
+
+@with_native_function
+def method_registration(f: NativeFunction) -> str:
+    assert cpp.name(f.func) not in MANUAL_TRACER
+
+    return WRAPPER_REGISTRATION.substitute(
+        name=f.func.name,
+        type_wrapper_name=type_wrapper_name(f),
+        class_type="TraceType",
+    )
+
+
+def gen_trace_type_func(fn: NativeFunction) -> dict[str, list[str]]:
+    return {
+        "ops_headers": [f"#include "],
+        "trace_method_definitions": [method_definition(fn)],
+        "trace_wrapper_registrations": [method_registration(fn)],
+    }
+
+
+def gen_trace_type(
+    out: str, native_functions: list[NativeFunction], template_path: str
+) -> None:
+    # NOTE: see Note [Sharded File] at the top of the VariableType.cpp
+    # template regarding sharding of the generated files.
+    fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
+    fm.write_sharded(
+        "TraceType.cpp",
+        [fn for fn in native_functions if cpp.name(fn.func) not in MANUAL_TRACER],
+        key_fn=lambda fn: fn.root_name,
+        base_env={
+            "generated_comment": "@"
+            + f"generated from {fm.template_dir_for_comments()}/TraceType.cpp",
+        },
+        env_callable=gen_trace_type_func,
+        num_shards=5,
+        sharded_keys={
+            "ops_headers",
+            "trace_method_definitions",
+            "trace_wrapper_registrations",
+        },
+    )
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_variable_factories.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_variable_factories.py
new file mode 100644
index 0000000000000000000000000000000000000000..9916a77385d38f01e83416d4303cb17ac17de700
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_variable_factories.py
@@ -0,0 +1,116 @@
+# Generates C++ functions that wrap ATen tensor factory methods to turn them into Variables.
+#
+# This writes one file: variable_factories.h
+
+from __future__ import annotations
+
+import re
+
+import torchgen.api.python as python
+from torchgen.api import cpp
+from torchgen.api.types import CppSignatureGroup
+from torchgen.context import with_native_function
+from torchgen.gen import parse_native_yaml
+from torchgen.model import NativeFunction, TensorOptionsArguments, Variant
+from torchgen.utils import FileManager, mapMaybe
+
+
+OPTIONAL_TYPE_PATTERN = re.compile(r"std::optional<(.+)>")
+TYPE_PATTERN = re.compile(r"(?:const\s+)?([A-Z]\w+)")
+
+
+# Add 'at::' to types defined in ATen namespace, e.g. Tensor, TensorList, IntArrayRef and etc.
+# TODO: maybe update the cpp argument API to take optional namespace argument?
+def fully_qualified_type(argument_type: str) -> str:
+    def maybe_optional_type(type: str, is_opt: bool) -> str:
+        return f"std::optional<{type}>" if is_opt else type
+
+    opt_match = OPTIONAL_TYPE_PATTERN.match(argument_type)
+    is_opt = opt_match is not None
+    if opt_match:
+        argument_type = argument_type[opt_match.start(1) : opt_match.end(1)]
+    match = TYPE_PATTERN.match(argument_type)
+    if match is None:
+        return maybe_optional_type(argument_type, is_opt)
+    index = match.start(1)
+    qualified_type = f"{argument_type[:index]}at::{argument_type[index:]}"
+    return maybe_optional_type(qualified_type, is_opt)
+
+
+def gen_variable_factories(
+    out: str, native_yaml_path: str, tags_yaml_path: str, template_path: str
+) -> None:
+    native_functions = parse_native_yaml(
+        native_yaml_path, tags_yaml_path
+    ).native_functions
+    factory_functions = [fn for fn in native_functions if is_factory_function(fn)]
+    fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
+    fm.write_with_template(
+        "variable_factories.h",
+        "variable_factories.h",
+        lambda: {
+            "generated_comment": "@"
+            + f"generated from {fm.template_dir_for_comments()}/variable_factories.h",
+            "ops_headers": [
+                f"#include " for fn in factory_functions
+            ],
+            "function_definitions": list(mapMaybe(process_function, factory_functions)),
+        },
+    )
+
+
+@with_native_function
+def is_factory_function(f: NativeFunction) -> bool:
+    if Variant.function not in f.variants:
+        return False
+
+    name = cpp.name(f.func)
+    has_tensor_options = python.has_tensor_options(f)
+    return has_tensor_options or name.endswith("_like")
+
+
+@with_native_function
+def process_function(f: NativeFunction) -> str | None:
+    name = cpp.name(f.func)
+    has_tensor_options = python.has_tensor_options(f)
+    is_factory = has_tensor_options or name.endswith("_like")
+
+    if Variant.function not in f.variants or not is_factory:
+        return None
+
+    cpp_sigs = CppSignatureGroup.from_native_function(f, method=False)
+    sigs = [cpp_sigs.signature]
+    if cpp_sigs.symint_signature is not None:
+        sigs.append(cpp_sigs.symint_signature)
+    r = ""
+    for sig in sigs:
+        formals: list[str] = []
+        exprs: list[str] = []
+        requires_grad = "false"
+        for arg in sig.arguments():
+            qualified_type = fully_qualified_type(arg.type)
+            if arg.default:
+                formals.append(f"{qualified_type} {arg.name} = {arg.default}")
+            else:
+                formals.append(f"{qualified_type} {arg.name}")
+
+            if isinstance(arg.argument, TensorOptionsArguments):
+                # note: we remove the requires_grad setting from the TensorOptions because
+                # it is ignored anyways (and we actually have an assertion that it isn't set
+                # which would fail otherwise). We handle requires_grad explicitly here
+                # instead of passing it through to the kernel.
+                exprs.append(
+                    f"at::TensorOptions({arg.name}).requires_grad(::std::nullopt)"
+                )
+                # Manually set the requires_grad bit on the result tensor.
+                requires_grad = f"{arg.name}.requires_grad()"
+            else:
+                exprs.append(arg.name)
+
+        r += f"""\
+inline at::Tensor {sig.name()}({", ".join(formals)}) {{
+  at::AutoDispatchBelowADInplaceOrView guard;
+  return autograd::make_variable(at::{sig.name()}({", ".join(exprs)}), /*requires_grad=*/{requires_grad});
+}}
+"""
+    return r
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_variable_type.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_variable_type.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed5a6e6cf39823856dc6403cf7ed90617ade5530
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_variable_type.py
@@ -0,0 +1,2186 @@
+# Generates VariableType.h/cpp
+#
+# **If any changes are being made to the VariableType codegen please also check
+# if updates are needed in torch/csrc/autograd/autograd_not_implemented_fallback.cpp
+#
+# VariableType is a subclass of at::Type that provides the binding code
+# necessary to provide a differentiable version of ATen operators. There are a
+# number of different things we could mean:
+#
+#   - Given a non-differentiable forward implementation, we might
+#     directly associate it with a backward implementation to make
+#     it differentiable.  This is the common case.
+#
+#   - Some functions don't need a backwards implementation, because
+#     backpropagation will never propagate beyond them.  There are a
+#     number of different reasons why this may be the case:
+#
+#       - The function has no differentiable inputs
+#       - The function's output is not differentiable
+#       - The function has no data dependency on its input
+#
+#   - Some function don't need a backwards implementation because they
+#     are implemented as a composition of other (differentiable) ATen
+#     functions.  These are dispatched directly to the Type superclass,
+#     which will in turn dispatch back to VariableType for its
+#     differentiable subcomponents.
+#
+
+from __future__ import annotations
+
+import re
+from typing import Callable, TYPE_CHECKING
+
+from torchgen.api import cpp
+from torchgen.api.autograd import (
+    DifferentiableInput,
+    dispatch_strategy,
+    ForwardDerivative,
+    gen_differentiable_outputs,
+    is_differentiable,
+    NativeFunctionWithDifferentiabilityInfo,
+    SavedAttribute,
+)
+from torchgen.api.types import (
+    ArrayRefCType,
+    BaseCppType,
+    BaseCType,
+    Binding,
+    intArrayRefT,
+    iTensorListRefT,
+    ListCType,
+    MutRefCType,
+    OptionalCType,
+    scalarT,
+    SpecialArgName,
+    stringT,
+    symIntArrayRefT,
+    TENSOR_LIST_LIKE_CTYPES,
+    tensorListT,
+    tensorT,
+    TupleCType,
+    VectorCType,
+)
+from torchgen.code_template import CodeTemplate
+from torchgen.context import (
+    native_function_manager,
+    with_native_function,
+    with_native_function_and,
+)
+from torchgen.model import (
+    Argument,
+    BaseType,
+    ListType,
+    NativeFunction,
+    SchemaKind,
+    SelfArgument,
+    TensorOptionsArguments,
+)
+from torchgen.utils import FileManager, mapMaybe
+
+from .context import with_native_function_with_differentiability_info_and_key
+from .gen_inplace_or_view_type import (
+    ALL_VIEW_FUNCTIONS,
+    ASSIGN_RETURN_VALUE,
+    AUTOGRAD_NOT_IMPLEMENTED_REGISTRATION,
+    gen_formals,
+    get_base_name,
+    get_view_info,
+    is_tensor_list_type,
+    is_tensor_type,
+    METHOD_DEFINITION,
+    modifies_arguments,
+    TMP_VAR,
+    unpack_args,
+    unpacked_name,
+    use_derived,
+    WRAPPER_REGISTRATION,
+)
+from .gen_trace_type import (
+    get_return_value,
+    MANUAL_AUTOGRAD_AND_TRACER,
+    MANUAL_BACKEND,
+    tie_return_values,
+    type_wrapper_name,
+)
+
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+
+
+# We don't set or modify grad_fn on these methods. Generally, they return
+# tensors that have requires_grad=False. In-place functions listed here will
+# not examine or modify requires_grad or grad_fn.
+# NB: this does NOT include overload name
+DONT_REQUIRE_DERIVATIVE = {
+    # These only depend on the input Tensor's shape and device, not the data
+    "empty_like",
+    "ones_like",
+    "full_like",
+    "zeros_like",
+    "rand_like",
+    "randn_like",
+    "new_empty",
+    "new_empty_strided",
+    "new_full",
+    "new_zeros",
+    "new_ones",
+    # These are only implemented on integral types
+    "__and__",
+    "__iand__",
+    "__ilshift__",
+    "__ior__",
+    "__irshift__",
+    "__ixor__",
+    "__lshift__",
+    "__or__",
+    "__rshift__",
+    "__xor__",
+    # These work on integral data types, and hence don't require derivative
+    "_sobol_engine_draw",
+    "_sobol_engine_ff",
+    "_sobol_engine_scramble_",
+    "_sobol_engine_initialize_state_",
+    # This is an unsafe method that is meant to be out of reach of autograd.
+    "_coalesced_",
+    # Quantize functions should not record gradients
+    "quantize_per_tensor",
+    "quantize_per_channel",
+    # Functions that return integers should not have output that require gradients
+    "argmax",
+    "argmin",
+    "argsort",
+    "searchsorted",
+    "bucketize",
+    # Functions that return booleans are not differentiable
+    "isnan",
+    "isposinf",
+    "isneginf",
+    "isinf",
+    "signbit",
+    "isin",
+    "allclose",
+    # Functions return none are not differentiable
+    "record_stream",
+    # These functions are not differentiable
+    "logical_and",
+    "logical_xor",
+    "logical_not",
+    "logical_or",
+    # This function returns nested_tensor shape as a tensor that is non-differentiable
+    "_nested_tensor_size",
+    "_nested_tensor_strides",
+    "_nested_tensor_storage_offsets",
+}
+
+# The C -> R functions at the time of adding this are still being audited and tested
+# but will not error out.
+# C -> C, R -> C functions for which backward is correctly implemented and tested
+GRADIENT_IMPLEMENTED_FOR_COMPLEX = {
+    "fill",
+    "t",
+    "t_copy",
+    "view",
+    "reshape",
+    "reshape_as",
+    "view_as",
+    "view_copy",
+    "roll",
+    "clone",
+    "block_diag",
+    "diag_embed",
+    "repeat",
+    "expand",
+    "expand_copy",
+    "flip",
+    "fliplr",
+    "flipud",
+    "rot90",
+    "nanmean",
+    "nansum",
+    "transpose",
+    "transpose_copy",
+    "permute",
+    "permute_copy",
+    "squeeze",
+    "squeeze_copy",
+    "unsqueeze",
+    "unsqueeze_copy",
+    "resize",
+    "resize_as",
+    "tril",
+    "triu",
+    "chunk",
+    "zero_",
+    "eq_",
+    "ne_",
+    "add",
+    "__radd__",
+    "sum",
+    "_conj",
+    "sin",
+    "cos",
+    "mul",
+    "sinc",
+    "sinh",
+    "cosh",
+    "__rmul__",
+    "sgn",
+    "asin",
+    "acos",
+    "sub",
+    "div",
+    "cat",
+    "view_as_complex",
+    "index_put",
+    "neg",
+    "complex",
+    "select",
+    "where",
+    "as_strided",
+    "as_strided_copy",
+    "as_strided_scatter",
+    "slice",
+    "constant_pad_nd",
+    "unbind",
+    "unbind_copy",
+    "split",
+    "split_with_sizes",
+    "unsafe_split",
+    "split_with_sizes_backward",
+    "dot",
+    "vdot",
+    "cholesky",
+    "triangular_solve",
+    "mm",
+    "_unsafe_view",
+    "mv",
+    "outer",
+    "bmm",
+    "diagonal",
+    "alias",
+    "atan",
+    "log",
+    "log10",
+    "log1p",
+    "log2",
+    "logaddexp",
+    "logsumexp",
+    "logcumsumexp",
+    "reciprocal",
+    "tan",
+    "pow",
+    "rsqrt",
+    "tanh",
+    "tanh_backward",
+    "asinh",
+    "acosh",
+    "atanh",
+    "take",
+    "fill_",
+    "exp",
+    "exp2",
+    "expm1",
+    "nonzero",
+    "mean",
+    "std_mean",
+    "var_mean",
+    "inverse",
+    "solve",
+    "linalg_cholesky",
+    "addcmul",
+    "addcdiv",
+    "matrix_exp",
+    "linalg_matrix_exp",
+    "_linalg_eigh",
+    "cholesky_solve",
+    "linalg_qr",
+    "_linalg_svd",
+    "_fft_c2c",
+    "_fft_r2c",
+    "linalg_solve",
+    "sqrt",
+    "stack",
+    "gather",
+    "index_select",
+    "index_add_",
+    "linalg_inv",
+    "linalg_inv_ex",
+    "baddbmm",
+    "addbmm",
+    "addmm",
+    "addmv",
+    "addr",
+    "linalg_householder_product",
+    "ormqr",
+    "reflection_pad1d",
+    "reflection_pad2d",
+    "reflection_pad3d",
+    "linalg_cholesky_ex",
+    "linalg_eig",
+    "diagonal_copy",
+    "diagonal_scatter",
+    "alias_copy",
+    "select_backward",
+    "diagonal_backward",
+    "slice_backward",
+    "reflection_pad1d_backward",
+    "reflection_pad2d_backward",
+    "reflection_pad3d_backward",
+    "_sparse_sparse_matmul",
+    "replication_pad1d",
+    "replication_pad2d",
+    "replication_pad3d",
+    "put",
+    "put_",
+    "_to_copy",
+    "replication_pad1d_backward",
+    "replication_pad2d_backward",
+    "replication_pad3d_backward",
+    "diag",
+    "masked_scatter",
+    "masked_select",
+    "index_add",
+    "index_fill",
+    "trace",
+    "polar",
+    "cumsum",
+    "rsub",
+    "eig",
+    "lerp",
+    "linalg_vector_norm",
+    "cumprod",
+    "prod",
+    "index_copy",
+    "lu",
+    "unfold",
+    "unfold_backward",
+    "index",
+    "masked_fill",
+    "masked_scatter_backward",
+    "linalg_cross",
+    "lu_unpack",
+    "renorm",
+    "_conj_physical",
+    "linalg_lu_factor_ex",
+    "scatter",
+    "scatter_add",
+    "sigmoid",
+    "sigmoid_backward",
+    "sparse_mask",
+    "trapezoid",
+    "cumulative_trapezoid",
+    "conj_physical_",
+    "_neg_view",
+    "_reshape_alias",
+    "_reshape_copy",
+    "_linalg_det",
+    "lu_solve",
+    "linalg_solve_triangular",
+    "linalg_pinv",
+    "linalg_lstsq",
+    "unfold_copy",
+    "col2im",
+    "im2col",
+    "cholesky_inverse",
+    "to_sparse",
+    "sparse_sampled_addmm",
+    "linalg_lu",
+    "pixel_shuffle",
+    "pixel_unshuffle",
+    "channel_shuffle",
+    "linalg_lu_solve",
+    "_linalg_slogdet",
+    "_linalg_solve_ex",
+    "_unsafe_index",
+    "_unsafe_index_put",
+    "_unsafe_masked_index",
+    "_unsafe_masked_index_put_accumulate",
+}
+
+GRADIENT_IMPLEMENTED_FOR_SPARSE_COMPLEX = {
+    "_to_dense",
+    "_coalesce",
+    "coalesce",
+    "values",
+    "_sparse_coo_tensor_with_dims_and_tensors",
+    "_sparse_addmm",
+}
+
+GRADIENT_IMPLEMENTED_FOR_COMPLEX.update(GRADIENT_IMPLEMENTED_FOR_SPARSE_COMPLEX)
+
+# Some operators invalidate the grad_accumulator. Let's reset it.
+RESET_GRAD_ACCUMULATOR = {"set_", "resize_"}
+
+# NOTE [ TensorImpl and Storage Pointer Sanity Checks ]
+#
+# We check the following properties:
+#   1) A function should never change the input tensors' underlying c10::TensorImpl
+#      pointers or c10::Storage pointers, even if it modifies its input tensors (via
+#      inplace or out-variants)
+# If the function does not modify its arguments, we also check the following properties
+# pertaining to its output:
+#   2) Its TensorImpl has use_count of 1
+#   3) If the function is a view function, it has the same StorageImpl as that of
+#      the input it is aliased with. Otherwise, its StorageImpl has use_count of 1
+#
+# The following code templates implement the checks for this invariant:
+SAVE_TENSOR_STORAGE = CodeTemplate(
+    """\
+auto ${tensor_name}_storage_saved =
+  ${tensor_name}.has_storage() ? ::std::optional(${tensor_name}.storage()) : ::std::nullopt;
+"""
+)
+
+
+# If tensor_name == out_tensor_name, used to enforce (1), otherwise used for (2)
+ENFORCE_SAME_TENSOR_STORAGE = CodeTemplate(
+    """\
+if (${tensor_name}_storage_saved.has_value() &&
+    !at::impl::dispatch_mode_enabled() &&
+    !at::impl::tensor_has_dispatch(${tensor_name}) &&
+    !at::impl::tensor_has_dispatch(${out_tensor_name}))
+  TORCH_INTERNAL_ASSERT(${tensor_name}_storage_saved.value().is_alias_of(${out_tensor_name}.storage()));
+"""
+)
+
+SAVE_TENSORLIST_STORAGE = CodeTemplate(
+    """\
+std::vector<::std::optional> ${tensorlist_name}_storage_saved(${tensorlist_name}.size());
+for (const Tensor& tensor : ${tensorlist_name})
+  ${tensorlist_name}_storage_saved.push_back(
+    tensor.has_storage() ? ::std::optional(tensor.storage()) : ::std::nullopt);
+"""
+)
+
+ENFORCE_SAME_TENSORLIST_STORAGE = CodeTemplate(
+    """\
+for (size_t i=0; i<${tensorlist_name}.size() && !at::impl::dispatch_mode_enabled(); i++) {
+  if (${tensorlist_name}_storage_saved[i].has_value() && !at::impl::tensorlist_has_dispatch(${tensorlist_name}))
+    TORCH_INTERNAL_ASSERT(${tensorlist_name}_storage_saved[i].value().is_alias_of(${tensorlist_name}[i].storage()));
+}
+"""
+)
+
+SAVE_OPTIONALTENSORLIST_STORAGE = CodeTemplate(
+    """\
+std::vector<::std::optional> ${tensorlist_name}_storage_saved(${tensorlist_name}.size());
+for (const ::std::optional& tensor : ${tensorlist_name})
+  ${tensorlist_name}_storage_saved.push_back(
+    tensor.has_value() && tensor->has_storage() ? ::std::optional(tensor->storage()) : ::std::nullopt);
+"""
+)
+
+ENFORCE_SAME_OPTIONALTENSORLIST_STORAGE = CodeTemplate(
+    """\
+for (size_t i=0; i<${tensorlist_name}.size() && !at::impl::dispatch_mode_enabled(); i++) {
+  if (${tensorlist_name}_storage_saved[i].has_value() && !at::impl::tensorlist_has_dispatch(${tensorlist_name}))
+    TORCH_INTERNAL_ASSERT(${tensorlist_name}_storage_saved[i].value().is_alias_of(
+        static_cast<::std::optional>(${tensorlist_name}[i])->storage()));
+}
+"""
+)
+
+SAVE_TENSOR_IMPL = CodeTemplate(
+    """\
+c10::intrusive_ptr ${tensor_name}_impl_saved;
+if (${tensor_name}.defined()) ${tensor_name}_impl_saved = ${tensor_name}.getIntrusivePtr();
+"""
+)
+
+ENFORCE_SAME_TENSOR_IMPL = CodeTemplate(
+    """\
+if (${tensor_name}_impl_saved && !at::impl::dispatch_mode_enabled() && !at::impl::tensor_has_dispatch(${tensor_name}))
+  TORCH_INTERNAL_ASSERT(${tensor_name}_impl_saved == ${tensor_name}.getIntrusivePtr());
+"""
+)
+
+ENFORCE_TENSOR_IMPL_USE_COUNT_LT_OR_EQ_ONE = CodeTemplate(
+    """\
+if (!at::impl::dispatch_mode_enabled() && !at::impl::tensor_has_dispatch(${tensor_name}))
+  TORCH_INTERNAL_ASSERT(${tensor_name}.use_count() <= 1, "function: ${fn_name}");
+"""
+)
+
+ENFORCE_TENSOR_STORAGE_USE_COUNT_EQUALS_ONE = CodeTemplate(
+    """\
+if (${tensor_name}.has_storage() && !at::impl::dispatch_mode_enabled() && !at::impl::tensor_has_dispatch(${tensor_name})) {
+  TORCH_INTERNAL_ASSERT(${tensor_name}.storage().use_count() == 1, "function: ${fn_name}");
+}
+"""
+)
+
+SAVE_TENSORLIST_IMPL = CodeTemplate(
+    """\
+std::vector> ${tensorlist_name}_impl_saved(${tensorlist_name}.size());
+for (size_t i=0; i<${tensorlist_name}.size(); i++)
+  if (${tensorlist_name}[i].defined()) ${tensorlist_name}_impl_saved[i] = ${tensorlist_name}[i].getIntrusivePtr();
+"""
+)
+
+ENFORCE_SAME_TENSORLIST_IMPL = CodeTemplate(
+    """\
+for (size_t i=0; i<${tensorlist_name}.size() && !at::impl::dispatch_mode_enabled(); i++) {
+  if (${tensorlist_name}_impl_saved[i] && !at::impl::tensorlist_has_dispatch(${tensorlist_name}))
+    TORCH_INTERNAL_ASSERT(${tensorlist_name}_impl_saved[i] == ${tensorlist_name}[i].getIntrusivePtr());
+}
+"""
+)
+
+SAVE_OPTIONALTENSORLIST_IMPL = CodeTemplate(
+    """\
+std::vector> ${tensorlist_name}_impl_saved(${tensorlist_name}.size());
+for (size_t i=0; i<${tensorlist_name}.size(); i++) {
+  ::std::optional t = ${tensorlist_name}[i];
+  if (t.has_value() && t->defined()) ${tensorlist_name}_impl_saved[i] = t->getIntrusivePtr();
+}
+"""
+)
+
+ENFORCE_SAME_OPTIONALTENSORLIST_IMPL = CodeTemplate(
+    """\
+for (size_t i=0; i<${tensorlist_name}.size() && !at::impl::dispatch_mode_enabled(); i++) {
+  if (${tensorlist_name}_impl_saved[i])
+    TORCH_INTERNAL_ASSERT(
+      ${tensorlist_name}_impl_saved[i] == static_cast<::std::optional>(${tensorlist_name}[i])->getIntrusivePtr());
+}
+"""
+)
+
+# The following list contains functions that we don't enforce the invariant on.
+DONT_ENFORCE_SAME_TENSOR_IMPL_OR_STORAGE = {
+    # These functions are expected to change impl or storage of input tensors
+    "set_",
+    "_cudnn_rnn_flatten_weight",
+    "_unsafe_masked_index",
+    "_unsafe_masked_index_put_accumulate",
+}
+DONT_ENFORCE_TENSOR_IMPL_USE_COUNT = {
+    # These non-inplace, non-out functions return tensors with use_count > 1
+    # Therefore, they MAY (but not necessarily) return one of its inputs as-is
+    # See https://github.com/pytorch/pytorch/issues/60426 for more information
+    "_embedding_bag",
+    "_embedding_bag_forward_only",
+    "q_per_channel_scales",
+    "q_per_channel_zero_points",
+    "lu_unpack",
+    "_cudnn_rnn_backward",
+    # The below failed StorageImpl use_count check but we skip tensor_impl check
+    # just in case
+    "_cudnn_rnn",
+    "dequantize_self",
+    # lift() should never actually be called with a requires_grad=True tensor,
+    "lift",
+    "lift_fresh",
+    "lift_fresh_copy",
+    # Nested Tensors related functions
+    # _nested_tensor_size() should never actually be called with requires_grad=True tensor
+    "_nested_tensor_size",
+    "_nested_tensor_strides",
+    "_nested_tensor_storage_offsets",
+}
+
+DONT_ENFORCE_STORAGE_IMPL_USE_COUNT = {
+    # These non-view functions return tensors with storage use_count != 1
+    "_slow_conv2d_forward",
+    "slow_conv3d_forward",
+    "channel_shuffle",
+    # If an input is returned as-is in output, we cannot guarantee its storage_impl
+    # use count to be 1 either.
+    *DONT_ENFORCE_TENSOR_IMPL_USE_COUNT,
+}
+# END CHECKS FOR [ TensorImpl and Storage Pointer Sanity Checks ]
+
+DECLARE_GRAD_FN = CodeTemplate(
+    """\
+std::shared_ptr<${op}> grad_fn;
+"""
+)
+
+DECLARE_VECTOR_OF_GRAD_FN = CodeTemplate(
+    """\
+std::vector> grad_fns;
+"""
+)
+
+SETUP_ANY_REQUIRES_GRAD = CodeTemplate(
+    """\
+[[maybe_unused]] auto _any_requires_grad = compute_requires_grad( ${args_with_derivatives} );
+${extra_differentiability_conditions}
+"""
+)
+
+SETUP_DERIVATIVE = CodeTemplate(
+    """\
+if (_any_requires_grad) {
+  ${setup}
+}
+"""
+)
+
+SETUP_NONE_REQUIRES_GRAD = CodeTemplate(
+    """\
+if (compute_requires_grad( ${args_to_check} )) {
+  throw_error_out_requires_grad("${base_name}");
+}
+"""
+)
+
+ASSIGN_GRAD_FN = CodeTemplate(
+    """\
+grad_fn = std::shared_ptr<${op}>(new ${op}(${op_ctor}), deleteNode);
+grad_fn->set_next_edges(collect_next_edges( ${args_with_derivatives} ));
+"""
+)
+
+# note(crcrpar): `compute_requires_grad` in the template below is supplied with arguments indexed with `i`
+# while the `SETUP_ANY_REQUIRES_GRAD` above takes whole tensors and scalars.
+ASSIGN_VECTOR_OF_GRAD_FN = CodeTemplate(
+    """\
+for (const auto& i : c10::irange( ${irange} )) {
+  const auto ith_requires_grad = compute_requires_grad(${args_with_derivatives});
+  check_inplace(self[i], ith_requires_grad);
+  grad_fns.push_back([&]() -> std::shared_ptr<${op}> {
+      if (!ith_requires_grad) {
+          return nullptr;
+      } else {
+          auto grad_fn = std::shared_ptr<${op}>(new ${op}(${op_ctor}), deleteNode);
+          grad_fn->set_next_edges(collect_next_edges( ${args_with_derivatives} ));
+          return grad_fn;
+      }
+  }());
+}
+"""
+)
+
+CALL_REDISPATCH = CodeTemplate(
+    """\
+at::redispatch::${api_name}(${unpacked_args})"""
+)
+# If the non-variable operation has return values, we use the `tmp` variable to hold the
+# values temporarily and pass the values to the return variables outside of the
+# `at::AutoDispatchBelowAutograd` guard block.
+DISPATCH_TO_NON_VAR_TYPE_WITH_TMP_RETURN_VALUES_JVP_DECOMP = CodeTemplate(
+    """\
+auto ${tmp_var} = ([&]() {
+  if (${any_has_forward_grad}) {
+    static c10::OperatorName full_name("aten::${op_name}", "${op_overload}");
+    static ::std::optional opt_op = c10::Dispatcher::singleton().findSchema(full_name);
+    return impl::run_jit_decomposition_with_args_for_jvp<${return_types}>("${op_name}", *opt_op, ks, ${arg_names});
+  } else {
+    ${guard}
+    return ${base_type_call};
+  }
+})();
+"""
+)
+
+DISPATCH_TO_NON_VAR_TYPE_WITH_TMP_RETURN_VALUES = CodeTemplate(
+    """\
+auto ${tmp_var} = ([&]() {
+  ${guard}
+  return ${base_type_call};
+})();
+"""
+)
+
+DISPATCH_TO_NON_VAR_TYPE_WITHOUT_RETURN_VALUES = CodeTemplate(
+    """\
+{
+  ${guard}
+  ${base_type_call};
+}
+"""
+)
+
+SET_HISTORY = CodeTemplate(
+    """\
+if (grad_fn) {
+    ${fn}_history(${differentiable_outputs}, grad_fn);
+}
+"""
+)
+
+LOOP_OVER_VECTOR_OF_GRAD_FNS = CodeTemplate(
+    """\
+if (!grad_fns.empty()) {
+    ${preamble}
+    for (const auto& i : c10::irange(grad_fns.size())) {
+        auto grad_fn = grad_fns[i];
+        if (grad_fn != nullptr) {
+            ${statements}
+        }
+    }
+}
+"""
+)
+
+CONDITIONAL = CodeTemplate(
+    """\
+if (${cond}) {
+  ${statements}
+}
+"""
+)
+
+RUN_ONLY_IN_DEBUG_MODE = CodeTemplate(
+    """\
+#ifndef NDEBUG
+${statements}
+#endif
+"""
+)
+
+FW_DERIVATIVE_CHECK_TEMPLATE = CodeTemplate(
+    """\
+isFwGradDefined(${req_inp})\
+"""
+)
+FW_DERIVATIVE_SIZE_CHECK_TEMPLATE = CodeTemplate(
+    """\
+TORCH_CHECK(
+    self.size() == ${inp_name}.size(),
+      "Tensor lists must have the same number of tensors, got ",
+    self.size(),
+      " and ",
+    ${inp_name}.size());
+"""
+)
+
+FW_DERIVATIVE_TENSORLIST_CHECK_TEMPLATE = CodeTemplate(
+    """\
+isFwGradDefinedTensorList(${req_inp})\
+"""
+)
+
+FW_DERIVATIVE_DEFINED_GRAD_TEMPLATE = CodeTemplate(
+    """\
+auto ${inp_name}_t_raw = toNonOptFwGrad(${inp});
+auto ${inp_name}_tensor = toNonOptTensor(${inp});
+auto ${inp_name}_t = (${inp_name}_t_raw.defined() || !${inp_name}_tensor.defined())
+  ? ${inp_name}_t_raw : at::${zeros_fn}(${inp_name}_tensor.sym_sizes(), ${inp_name}_tensor.options());
+"""
+)
+
+FW_DERIVATIVE_DEFINED_PRIMAL_TEMPLATE = CodeTemplate(
+    """\
+auto ${inp_name}_p = toNonOptPrimal(${inp});
+"""
+)
+
+FW_DERIVATIVE_SETTER_TENSOR = CodeTemplate(
+    """\
+if (${out_arg}_new_fw_grad_opt.has_value() && ${out_arg}_new_fw_grad_opt.value().defined() && ${out_arg}.defined()) {
+  // The hardcoded 0 here will need to be updated once we support multiple levels.
+  ${out_arg}._set_fw_grad(${out_arg}_new_fw_grad_opt.value(), /* level */ 0, /* is_inplace_op */ ${is_inplace});
+}
+"""
+)
+
+FW_DERIVATIVE_SETTER_TENSOR_FOREACH = CodeTemplate(
+    """\
+for (const auto& i : c10::irange(${out_arg}_new_fw_grad_opts.size())) {
+  auto& ${out_arg}_new_fw_grad_opt = ${out_arg}_new_fw_grad_opts[i];
+  if (${out_arg}_new_fw_grad_opt.has_value() && ${out_arg}_new_fw_grad_opt.value().defined() && ${out_arg}[i].defined()) {
+    // The hardcoded 0 here will need to be updated once we support multiple levels.
+    ${out_arg}[i]._set_fw_grad(${out_arg}_new_fw_grad_opt.value(), /* level */ 0, /* is_inplace_op */ ${is_inplace});
+  }
+}
+"""
+)
+
+FW_DERIVATIVE_SETTER_MULTI_OUTPUT = CodeTemplate(
+    """\
+if (${all_res}_new_fw_grad_opt.has_value() && std::get<${idx}>(${all_res}_new_fw_grad_opt.value()).defined()
+    && ${out_arg}.defined()) {
+  ${out_arg}._set_fw_grad(std::get<${idx}>(${all_res}_new_fw_grad_opt.value()), /* level */ 0, /* is_inplace_op */ false);
+}
+"""
+)
+
+FW_DERIVATIVE_SETTER_TENSOR_LIST = CodeTemplate(
+    """\
+if (${out_arg}_new_fw_grad_opt.has_value()) {
+  auto ${out_arg}_new_fw_grad = ${out_arg}_new_fw_grad_opt.value();
+  TORCH_INTERNAL_ASSERT(${out_arg}.size() == ${out_arg}_new_fw_grad.size());
+  for (const auto i : c10::irange(${out_arg}.size())) {
+    if (${out_arg}_new_fw_grad[i].defined() && ${out_arg}[i].defined()) {
+      // The hardcoded 0 here will need to be updated once we support multiple levels.
+      ${out_arg}[i]._set_fw_grad(${out_arg}_new_fw_grad[i], /* level */ 0, /* is_inplace_op */ ${is_inplace});
+    }
+  }
+}
+"""
+)
+
+FW_DERIVATIVE_TEMPLATE = CodeTemplate(
+    """\
+${fw_grad_opt_definition}
+if (${requires_fw_grad}) {
+    ${unpacked_arguments}
+    ${out_arg}_new_fw_grad_opt = ${formula};
+}
+"""
+)
+
+FW_DERIVATIVE_FOREACH_TEMPLATE = CodeTemplate(
+    """\
+${fw_grad_opt_definition}
+for (const auto& i : c10::irange(${vector_of_optional_tensor}.size())) {
+  if (${any_has_forward_grad_for_current_index}) {
+      ${unpacked_arguments}
+      ${vector_of_optional_tensor}[i] = ${formula};
+  }
+}
+"""
+)
+
+FW_DERIVATIVE_FORBID_TEMPLATE = CodeTemplate(
+    """\
+TORCH_CHECK_NOT_IMPLEMENTED(!(${cond}), "Trying to use forward AD with ${name} that does not support it ${msg}");
+"""
+)
+
+FW_DERIVATIVE_FORBID_LIST_TEMPLATE = CodeTemplate(
+    """\
+for (const auto& _t: ${arg}) {
+    TORCH_CHECK_NOT_IMPLEMENTED(!(${cond}), "Trying to use forward AD with ${name} that does not support it ${msg}");
+}
+"""
+)
+
+
+def gen_variable_type(
+    out: str,
+    native_yaml_path: str,
+    tags_yaml_path: str,
+    fns_with_diff_infos: list[NativeFunctionWithDifferentiabilityInfo],
+    template_path: str,
+    used_keys: set[str],
+) -> None:
+    """VariableType.h and VariableType.cpp body
+
+    This is the at::Type subclass for differentiable tensors. The
+    implementation of each function dispatches to the base tensor type to
+    compute the output. The grad_fn is attached to differentiable functions.
+    """
+    fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
+    fm.write(
+        "VariableType.h",
+        lambda: {
+            "generated_comment": "@"
+            + f"generated from {fm.template_dir_for_comments()}/VariableType.h"
+        },
+    )
+
+    # helper that generates a TORCH_LIBRARY_IMPL macro for each
+    # dispatch key that appears in derivatives.yaml
+    def wrapper_registrations(used_keys: set[str]) -> str:
+        library_impl_macro_list: list[str] = []
+        for key in sorted(used_keys):
+            dispatch_key = key
+            if key == "Default":
+                dispatch_key = "Autograd"
+            library_impl_macro = (
+                f"TORCH_LIBRARY_IMPL(aten, {dispatch_key}, m) "
+                + "{\n"
+                + "${"
+                + f"wrapper_registrations_{key}"
+                + "}\n}"
+            )
+            library_impl_macro_list += [library_impl_macro]
+        return "\n\n".join(library_impl_macro_list)
+
+    # Generate a new template from VariableType.cpp which replaces ${wrapper_registrations}
+    # with per key TORCH_LIBRARY_IMPL macros for each key that appears in derivatives.yaml
+    fm1 = FileManager(
+        install_dir=out + "/templates", template_dir=template_path, dry_run=False
+    )
+    fm1.write(
+        "VariableType.cpp",
+        lambda: {
+            "type_derived_method_definitions": "\n\n".join(
+                [
+                    "${" + f"type_derived_method_definitions_{key}" + "}"
+                    for key in sorted(used_keys)
+                ]
+            ),
+            "wrapper_registrations": wrapper_registrations(used_keys),
+        },
+    )
+
+    # Generate final VariableType_*.cpp files from the generated template
+    fm2 = FileManager(install_dir=out, template_dir=out + "/templates", dry_run=False)
+
+    sharded_keys = set(
+        [f"type_derived_method_definitions_{key}" for key in sorted(used_keys)]
+        + [f"wrapper_registrations_{key}" for key in sorted(used_keys)]
+    )
+    # NOTE: see Note [Sharded File] at the top of the VariableType.cpp
+    # template regarding sharding of the generated files.
+    fm2.write_sharded(
+        "VariableType.cpp",
+        [fn for fn in fns_with_diff_infos if use_derived(fn)],
+        key_fn=lambda fn: cpp.name(fn.func.func),
+        base_env={
+            "generated_comment": "@"
+            + f"generated from {fm.template_dir_for_comments()}/VariableType.cpp",
+        },
+        env_callable=gen_variable_type_func,
+        num_shards=5,
+        sharded_keys=sharded_keys,
+    )
+
+
+@with_native_function_and
+def gen_wrapper_registration(f: NativeFunction, key: str = "Default") -> str:
+    return WRAPPER_REGISTRATION.substitute(
+        unqual_operator_name_with_overload=f.func.name,
+        type_wrapper_name=type_wrapper_name(f, key),
+        class_type="VariableType",
+    )
+
+
+def gen_variable_type_func(
+    fn: NativeFunctionWithDifferentiabilityInfo,
+) -> dict[str, list[str]]:
+    f = fn.func
+    result = {}
+    with native_function_manager(f):
+        name = cpp.name(f.func)
+        formals = gen_formals(f)
+
+        if (
+            fn.info is None
+            and str(f.func.name.name) not in RESET_GRAD_ACCUMULATOR
+            and get_base_name(f) not in DONT_REQUIRE_DERIVATIVE
+            and len(gen_differentiable_outputs(fn)) > 0
+            and cpp.name(f.func) not in DONT_ENFORCE_SAME_TENSOR_IMPL_OR_STORAGE
+            and type_wrapper_name(f) not in DONT_ENFORCE_STORAGE_IMPL_USE_COUNT
+            and type_wrapper_name(f) not in DONT_ENFORCE_TENSOR_IMPL_USE_COUNT
+        ):
+            # NOTE: [ Registering AutogradNotImplemented boxed kernel ]
+            #
+            # When there is no derivatives.yaml entry, we register a generic boxed
+            # NotImplemented kernel to set grad_fn to be NotImplemented, so that forward
+            # proceeds as usual but an error is properly produced on backward.
+            # TODO: it would be nice to not have these special cases
+            #
+            # There are several cases where still let codegen handle it:
+            # 1) ops that need to reset grad accumulator (we let codegen handle this case
+            #     because) the list is (currently) only accessible in Python.
+            # 2) User explicitly specifies DONT_REQUIRE_DERIVATIVE. This basically makes
+            #    autograd a fallthrough with NDEBUG checks. This can be useful for when all
+            #    outputs are integral.
+            # 3) When there are no differentiable outputs. This is similar to (2).
+            # 4) There are certain ops where we skip certain NDEBUG checks. this is similar
+            #    to (1).
+            type_definition = ""
+            wrapper_registration = AUTOGRAD_NOT_IMPLEMENTED_REGISTRATION.substitute(
+                unqual_operator_name_with_overload=f.func.name
+            )
+            result["type_derived_method_definitions_Default"] = [type_definition]
+            result["wrapper_registrations_Default"] = [wrapper_registration]
+        else:
+            if not fn.info:
+                key = "Default"
+                type_definition = METHOD_DEFINITION.substitute(
+                    return_type=cpp.returns_type(
+                        f.func.returns, symint=True
+                    ).cpp_type(),
+                    type_wrapper_name=type_wrapper_name(f, key),
+                    type_definition_body=emit_body(fn, key),
+                    formals=formals,
+                )
+                wrapper_registration = gen_wrapper_registration(f, key)
+                result[f"type_derived_method_definitions_{key}"] = [type_definition]
+                result[f"wrapper_registrations_{key}"] = [wrapper_registration]
+            else:
+                for key in fn.info.keys():
+                    type_definition = METHOD_DEFINITION.substitute(
+                        return_type=cpp.returns_type(
+                            f.func.returns, symint=True
+                        ).cpp_type(),
+                        type_wrapper_name=type_wrapper_name(f, key),
+                        type_definition_body=emit_body(fn, key),
+                        formals=formals,
+                    )
+                    wrapper_registration = gen_wrapper_registration(f, key)
+                    result[f"type_derived_method_definitions_{key}"] = [type_definition]
+                    result[f"wrapper_registrations_{key}"] = [wrapper_registration]
+    # See Note [Manual Backend kernels]
+    assert (name in MANUAL_BACKEND) == f.manual_kernel_registration
+    # If you want to register a kernel to Autograd, you must make the op abstract.
+    # In other words, this op must have dispatch section in native_functions.yaml.
+    if name in MANUAL_AUTOGRAD_AND_TRACER or (
+        fn.info and any(info.has_derivatives for info in fn.info.values())
+    ):
+        msg = (
+            f"There's a formula for {name}(or its functional variant) in derivatives.yaml. "
+            f"It's required to add a dispatch section for it with explicit supported backends e.g CPU/CUDA "
+            f"or CompositeExplicitAutograd in native_functions.yaml. Please see "
+            f"https://github.com/pytorch/pytorch/tree/master/aten/src/ATen/native#choosing-the-right-dispatch-keyword "
+            f"for instructions to choose the right dispatch keyword."
+        )
+        assert f.is_abstract, msg
+
+    return result
+
+
+_foreach_ops_without_differentiability_info = {
+    # No reference backward available due to the lack of `{maximum, minimum}(tensor, scalar)`.
+    ("_foreach_maximum", "Scalar"),
+    ("_foreach_maximum", "ScalarList"),
+    ("_foreach_minimum", "Scalar"),
+    ("_foreach_minimum", "ScalarList"),
+    # No reference backward available as addcdiv/addcmul don't support Tensor as scaling factor.
+    ("_foreach_addcdiv", "Tensor"),
+    ("_foreach_addcmul", "Tensor"),
+    ("_foreach_copy", ""),
+}
+
+_foreach_ops_with_different_arity = {
+    # These ops lack `alpha` of scaling factor to applied to the right hand side argument.
+    ("_foreach_add", "Scalar"),
+    ("_foreach_add", "ScalarList"),
+    ("_foreach_sub", "Scalar"),
+    ("_foreach_sub", "ScalarList"),
+}
+
+
+@with_native_function_with_differentiability_info_and_key
+def emit_body(
+    fn: NativeFunctionWithDifferentiabilityInfo, key: str = "Default"
+) -> list[str]:
+    assert dispatch_strategy(fn) == "use_derived"
+    f = fn.func
+    info = fn.info[key] if fn.info else None
+    fw_derivatives = fn.fw_derivatives.get(key, []) if fn.fw_derivatives else []
+
+    name = cpp.name(f.func)
+    inplace = f.func.kind() == SchemaKind.inplace
+    is_out_fn = f.func.kind() == SchemaKind.out
+    returns_void = len(f.func.returns) == 0
+    base_name = get_base_name(f)
+    view_info = get_view_info(f)
+
+    is_foreach = name.startswith("_foreach")
+    is_inplace_foreach = is_foreach and inplace
+    if is_inplace_foreach:
+        inplace_foreacharg2refarg: dict[Argument, Argument] = {}
+        refargname2inplace_foreacharg: dict[str, Argument] = {}
+        base_name_and_overload_name = (f.func.name.name.base, f.func.name.overload_name)
+        if info is None:
+            assert (
+                base_name_and_overload_name
+                in _foreach_ops_without_differentiability_info
+            ), (
+                f"{'.'.join(base_name_and_overload_name)} should have a differentiability info"
+            )
+        else:
+            assert (
+                len(f.func.arguments.flat_non_out)
+                == len(info.func.func.arguments.flat_non_out)
+            ) or (base_name_and_overload_name in _foreach_ops_with_different_arity), (
+                f"{'.'.join(base_name_and_overload_name)} has {len(f.func.arguments.flat_non_out)} args "
+                f"but the reference has {len(info.func.func.arguments.flat_non_out)}"
+            )
+            for foreach_arg, ref_arg in zip(
+                f.func.arguments.flat_non_out, info.func.func.arguments.flat_non_out
+            ):
+                foreach_arg_type = foreach_arg.type
+                if isinstance(foreach_arg_type, ListType):
+                    foreach_arg_type = foreach_arg_type.elem
+                assert foreach_arg_type == ref_arg.type
+                inplace_foreacharg2refarg[foreach_arg] = ref_arg
+                refargname2inplace_foreacharg[ref_arg.name] = foreach_arg
+
+    def gen_differentiable_input(
+        arg: Argument | SelfArgument | TensorOptionsArguments,
+    ) -> DifferentiableInput | None:
+        if isinstance(arg, TensorOptionsArguments):
+            return None
+        a: Argument = arg.argument if isinstance(arg, SelfArgument) else arg
+
+        # TODO: `cpp_type` is only to keep it byte-for-byte compatible with the old codegen, should remove.
+        # NB: This is not a clone of cpp.argument() - TensorOptionsArguments / faithful / binds are
+        # not handled properly as they are irrelevant for this codegen.
+        cpp_type = cpp.argument_type(a, binds=a.name, symint=True).cpp_type()
+
+        if not is_differentiable(a.name, a.type, info):
+            return None
+        return DifferentiableInput(
+            name=a.name,
+            type=a.type,
+            cpp_type=cpp_type,
+        )
+
+    @with_native_function
+    def gen_differentiable_inputs(f: NativeFunction) -> list[DifferentiableInput]:
+        arguments = list(f.func.arguments.non_out)
+        if is_inplace_foreach and info is not None:
+            for i, arg in enumerate(f.func.arguments.flat_non_out):
+                if arg in inplace_foreacharg2refarg:
+                    # note(crcrpar): From what I understand, what matters is only the name.
+                    # Thus originally I only replace argument only when the names are different.
+                    # TODO(crcrpar): Make it simpler.
+                    mapped_arg = inplace_foreacharg2refarg[arg]
+                    arguments[i] = Argument(
+                        mapped_arg.name,
+                        mapped_arg.type,
+                        mapped_arg.default,
+                        mapped_arg.annotation,
+                    )
+        return list(mapMaybe(gen_differentiable_input, arguments))
+
+    def find_args_with_derivatives(
+        differentiable_inputs: list[DifferentiableInput],
+    ) -> list[DifferentiableInput]:
+        """Find arguments that have derivative definitions"""
+        if info is None or not info.has_derivatives:
+            return differentiable_inputs
+        names = {name for d in info.derivatives for name in d.var_names}
+        differentiable = [arg for arg in differentiable_inputs if arg.name in names]
+        if len(differentiable) != len(names):
+            missing = names - {arg.name for arg in differentiable}
+            raise RuntimeError(
+                f"Missing arguments for derivatives: {missing} in {info.name}"
+            )
+        return differentiable
+
+    differentiable_inputs = gen_differentiable_inputs(f)
+    args_with_derivatives = find_args_with_derivatives(differentiable_inputs)
+    differentiable_outputs = gen_differentiable_outputs(fn, key)
+
+    undifferentiable = (base_name in DONT_REQUIRE_DERIVATIVE) or (
+        name in DONT_REQUIRE_DERIVATIVE
+    )
+
+    requires_derivative = (
+        (not undifferentiable)
+        and (len(differentiable_inputs) > 0)
+        and (
+            (len(differentiable_outputs) > 0)
+            # note(crcrpar): In-place foreach functions are a void function.
+            or is_inplace_foreach
+        )
+    )
+
+    if (
+        info is not None
+        and info.has_derivatives
+        and not requires_derivative
+        # out= ops are allowed to have zero returns which cause requires_derivative to be False
+        # we shouldn't error out though (out= ops for autograd just redispatch)
+        and len(f.func.returns) > 0
+    ):
+        raise RuntimeError(
+            f"ERROR: derivative ignored for {name} -- specified an autograd function without derivative"
+        )
+
+    # note(crcrpar): In-place foreach functions do not support forward AD
+    if requires_derivative and len(fw_derivatives) > 0 and not is_inplace_foreach:
+        assert sum(len(derivative.var_names) for derivative in fw_derivatives) == len(
+            differentiable_outputs
+        ), (
+            "Expected the number of forward derivatives implemented to match the "
+            "number of differentiable outputs. NB: This only applies when at least "
+            "one forward derivative is implemented. Not implementing any forward "
+            "derivatives is also okay, and we would require inputs to the op to "
+            "not have associated tangents in that case."
+        )
+
+    try_jit_decomposition = (
+        requires_derivative
+        and len(fw_derivatives) == 0
+        and (not modifies_arguments(f))
+        and (not returns_void)
+    )
+
+    def emit_save_inputs() -> list[str]:
+        setup: list[str] = []
+        if info is None or not info.has_derivatives:
+            return setup
+
+        has_tensorlist_arg = any(
+            is_tensor_list_type(arg.type) for arg in args_with_derivatives
+        )
+
+        # We don't want to save tensors if we know that they will never be used
+        # when computing the derivative, so we add guards to those statements
+        def guard_for(arg: SavedAttribute) -> str | None:
+            assert info is not None
+
+            # It's hard to determine the edge offset if we have TensorLists
+            # NOTE(crcrpar): in-place foreach functions' arguments include tensorlist
+            # but their derivatives don't use it, so let them bypass this check.
+            if has_tensorlist_arg and (not is_inplace_foreach):
+                return None
+
+            # Empirical evaluation of the cases where we insert those guards in
+            # backward show that they are somewhat useless. E.g. there's no need
+            # to guard on some values captured from forward, because they had to
+            # require_grad if the backward function even gets executed. I don't
+            # have any good ideas for detecting those cases, so I simply disabled the
+            # checks.
+            if "backward" in info.name:
+                return None
+
+            # If there's a single derivative we could compute, we already have
+            # a requires_grad check that is sufficient
+            if len(args_with_derivatives) <= 1:
+                return None
+
+            # We really only care about trimming down the amount of tensors we save
+            if arg.nctype.type != BaseCType(tensorT):
+                return None
+
+            # We want to emit simple guards, so we only allow that if checking one
+            # input is enough to determine whether we need that value
+            used_in = [d for d in info.derivatives if arg in d.saved_inputs]
+            assert len(used_in) > 0
+            if len(used_in) != 1:
+                return None
+            derivative = used_in[0]
+
+            # Case with multioutput formulas
+            # TODO: process all derivative formulas!!!
+            if len(derivative.var_names) != 1:
+                wrap_opt_if_start = derivative.formula.find(
+                    f"wrap_opt_if({arg.nctype.name}"
+                )
+                if wrap_opt_if_start == -1:
+                    return None
+
+                wrap_opt_if_match = re.match(
+                    rf"wrap_opt_if\({arg.nctype.name},(.*?)\)",
+                    derivative.formula[wrap_opt_if_start:],
+                )
+                assert wrap_opt_if_match is not None
+
+                # Condition is between 'wrap_opt_if(var_name,' and ')'.
+                condition_slice = slice(len(rf"wrap_opt_if\({arg.nctype.name},"), -1)
+                wrap_opt_if_condition = wrap_opt_if_match.group(0)[
+                    condition_slice
+                ].strip()
+                # replace 'grad_input_mask[num]' with 'grad_fn->should_compute_output(num)'
+                wrap_opt_if_condition = re.sub(
+                    r"grad_input_mask\[(\d+)\]",
+                    r"grad_fn->should_compute_output(\1)",
+                    wrap_opt_if_condition,
+                )
+                return f"{wrap_opt_if_condition}"
+
+            # Figure out the offset of the edge that uses this variable
+            derivative_var_name = derivative.var_names[0]
+            for edge_off, a in enumerate(args_with_derivatives):
+                if a.name == derivative_var_name:
+                    break
+            else:
+                raise AssertionError
+            return f"grad_fn->should_compute_output({edge_off})"
+
+        if is_inplace_foreach:
+            save_input_stmts = save_variables(info.all_saved_inputs, False, guard_for)
+            if save_input_stmts:
+                setup.append(
+                    LOOP_OVER_VECTOR_OF_GRAD_FNS.substitute(
+                        preamble="", statements=save_input_stmts
+                    )
+                )
+        else:
+            setup.extend(save_variables(info.all_saved_inputs, False, guard_for))
+            for arg in args_with_derivatives:
+                if is_tensor_list_type(arg.type):
+                    setup.append(f"grad_fn->{arg.name}_size_ = {arg.name}.size();")
+        return setup
+
+    def setup_derivative(differentiable_inputs: list[DifferentiableInput]) -> list[str]:
+        body: list[str] = []
+        if is_out_fn:
+            # For out functions, ensure that no input or output requires grad
+            body.append(DECLARE_GRAD_FN.substitute(op="Node"))
+            body.append(
+                SETUP_NONE_REQUIRES_GRAD.substitute(
+                    base_name=base_name,
+                    args_to_check=[arg.name for arg in differentiable_inputs],
+                )
+            )
+            body.append(
+                SETUP_NONE_REQUIRES_GRAD.substitute(
+                    base_name=base_name,
+                    args_to_check=[arg.name for arg in differentiable_outputs],
+                )
+            )
+            return body
+
+        op = info.op if info is not None and info.has_derivatives else "NotImplemented"
+        setup = []
+        if not is_inplace_foreach:
+            setup.extend(
+                ASSIGN_GRAD_FN.substitute(
+                    op=op,
+                    op_ctor=""
+                    if info is not None and info.has_derivatives
+                    else f'"{cpp.name(f.func)}"',
+                    args_with_derivatives=[arg.name for arg in args_with_derivatives],
+                ).split("\n")
+            )
+        else:
+            # note(crcrpar): Assuming in-place foreach function's self_arg is always TensorList.
+            list_like_arg = "self"
+            args = [arg.name for arg in args_with_derivatives]
+            for i, arg in enumerate(args):
+                if is_inplace_foreach and info is not None:
+                    if arg in refargname2inplace_foreacharg:
+                        foreach_arg = refargname2inplace_foreacharg[arg]
+                        args[i] = foreach_arg.name + (
+                            "[i]" if isinstance(foreach_arg.type, ListType) else ""
+                        )
+                else:
+                    if arg == list_like_arg:
+                        args[i] = arg + "[i]"
+            setup.extend(
+                ASSIGN_VECTOR_OF_GRAD_FN.substitute(
+                    op=op,
+                    op_ctor=""
+                    if info is not None and info.has_derivatives
+                    else f'"{cpp.name(f.func)}"',
+                    args_with_derivatives=args,
+                    irange=f"{list_like_arg}.size()",
+                ).split("\n")
+            )
+        setup.extend(emit_save_inputs())
+
+        body.extend(
+            emit_check_no_requires_grad(differentiable_inputs, args_with_derivatives)
+        )
+        declare_grad_fn_template = (
+            DECLARE_GRAD_FN if not is_inplace_foreach else DECLARE_VECTOR_OF_GRAD_FN
+        )
+        body.append(declare_grad_fn_template.substitute(op=op))
+        body.append(SETUP_DERIVATIVE.substitute(setup=setup))
+        return body
+
+    def emit_check_if_in_complex_autograd_allowlist() -> list[str]:
+        body: list[str] = []
+        if base_name in GRADIENT_IMPLEMENTED_FOR_COMPLEX:
+            return body
+        for arg in differentiable_outputs:
+            name = arg.name
+            # TODO: should be `arg.type.is_tensor_like()`?
+            if arg.cpp_type == "at::Tensor" or arg.cpp_type in TENSOR_LIST_LIKE_CTYPES:
+                body.append(f'throw_error_for_complex_autograd({name}, "{base_name}");')
+        return body
+
+    def emit_check_no_requires_grad(
+        tensor_args: list[DifferentiableInput],
+        args_with_derivatives: list[DifferentiableInput],
+    ) -> list[str]:
+        """Checks that arguments without derivatives don't require grad"""
+        body: list[str] = []
+        for arg in tensor_args:
+            if arg in args_with_derivatives:
+                continue
+            arg_name = arg.name
+            if info and arg_name in info.non_differentiable_arg_names:
+                continue
+            if arg_name == "output":
+                # Double-backwards definitions sometimes take in 'input' and
+                # 'output', but only define the derivative for input.
+                continue
+            body.append(f'check_no_requires_grad({arg_name}, "{arg_name}", "{name}");')
+        return body
+
+    def emit_original_self_definition() -> list[str]:
+        body: list[str] = []
+        if inplace:
+            if is_inplace_foreach:
+                body.append(
+                    "std::vector<::std::optional> original_selfs(self.size());"
+                )
+            else:
+                body.append("::std::optional original_self;")
+
+            all_forward_grad_cond = []
+            for derivative in fw_derivatives:
+                if derivative.required_original_self_value:
+                    all_forward_grad_cond.append(
+                        get_any_has_forward_grad_name(derivative.var_names)
+                    )
+
+            if all_forward_grad_cond:
+                if not is_inplace_foreach:
+                    body.append(f"if ({' || '.join(all_forward_grad_cond)}) {{")
+                    body.append("  original_self = self.clone();")
+                    body.append("}")
+                else:
+                    current_all_forward_grad_cond = [
+                        f"{cond}[i]" for cond in all_forward_grad_cond
+                    ]
+                    body.append("for (const auto& i : c10::irange(self.size())) {")
+                    body.append(
+                        f"  if ({' || '.join(current_all_forward_grad_cond)}) {{"
+                    )
+                    body.append("    original_selfs[i] = self[i].clone();")
+                    body.append("  }")
+                    body.append("}")
+
+        return body
+
+    def save_variables(
+        saved_variables: Sequence[SavedAttribute],
+        is_output: bool,
+        guard_for: Callable[[SavedAttribute], str | None] = lambda name: None,
+    ) -> Sequence[str]:
+        # assign the saved variables to the generated grad_fn
+        stmts: list[str] = []
+        for arg in sorted(saved_variables, key=lambda sa: str(sa.nctype.name)):
+            name = (
+                arg.nctype.name.name
+                if isinstance(arg.nctype.name, SpecialArgName)
+                else arg.nctype.name
+            )
+            foreacharg: Argument | None = None
+            is_foreacharg_list_type: bool = False
+            type = arg.nctype.type
+            expr = arg.expr
+            stmts_prepend = None
+            if is_inplace_foreach and info is not None:
+                # todo(crcrpar): See if we can add some check e.g. `assert foreacharg is not None`.
+                # for now the example assert would fail.
+                name_to_query = name.split("_scalar_type")[0]
+                if name_to_query in refargname2inplace_foreacharg:
+                    foreacharg = refargname2inplace_foreacharg[name_to_query]
+                    is_foreacharg_list_type = isinstance(foreacharg.type, ListType)
+                if foreacharg is not None:
+                    name_in_expr = (
+                        f"{foreacharg.name}{'[i]' if is_foreacharg_list_type else ''}"
+                    )
+                    src_name = name
+                    if "_scalar_type" in src_name:
+                        split_src_name = src_name.split("_scalar_type")
+                        assert len(split_src_name) == 2
+                        src_name = split_src_name[0]
+                    expr = expr.replace(src_name, name_in_expr)
+            if (
+                type == BaseCType(tensorT)
+                or type == OptionalCType(BaseCType(tensorT))
+                or type == MutRefCType(OptionalCType(BaseCType(tensorT)))
+                or (is_output and type == BaseCType(scalarT))
+            ):
+                # note(crcrpar): Here `expr` is generated from scratch, `arg.expr` is ignored.
+                var = name
+                name += "_"
+                if var == "self" and inplace:
+                    original_self_var = (
+                        "original_self"
+                        if not is_inplace_foreach
+                        else "original_selfs[i]"
+                    )
+                    self_var = var if not is_inplace_foreach else var + "[i]"
+                    stmts_prepend = f"if (!{original_self_var}.has_value()) {original_self_var} = {self_var}.clone()"
+                    var = f"{original_self_var}.value()"
+                    assert not is_output
+                if inplace and is_output:
+                    assert name == "result_"
+                    var = (
+                        "self[i]"
+                        if is_inplace_foreach or is_foreacharg_list_type
+                        else "self"
+                    )
+                    is_inplace_view = f"{var}.is_view()"
+                    expr = f"SavedVariable({var}, {str(is_output).lower()}, {is_inplace_view})"
+                else:
+                    expr = f"SavedVariable({var}, {str(is_output).lower()})"
+                    if foreacharg is not None and "original_selfs" not in expr:
+                        expr = expr.replace(src_name, name_in_expr)
+            elif (
+                type == BaseCType(tensorListT)
+                or type == ListCType(OptionalCType(BaseCType(tensorT)))
+                or type == BaseCType(iTensorListRefT)
+                or type == VectorCType(BaseCType(tensorT))
+            ):
+                # See Note [nuanced return type of out-of-place foreach functions]
+                if type == VectorCType(BaseCType(tensorT)):
+                    assert is_foreach and is_output
+                expr = f"make_saved_variable_list({name}, {str(is_foreach and is_output).lower()})"
+                name += "_"
+            elif type == BaseCType(intArrayRefT):
+                expr = expr + ".vec()"
+            elif type == BaseCType(symIntArrayRefT):
+                expr = expr + ".vec()"
+            elif type == BaseCType(stringT):
+                expr = f"std::string({expr})"
+            elif type == OptionalCType(BaseCType(stringT)):
+                expr = f"{expr}.has_value() ? ::std::optional(std::string({expr}.value())) : ::std::nullopt"
+            elif type == ArrayRefCType(
+                elem=BaseCType(type=BaseCppType(ns="at", name="Scalar"))
+            ):
+                expr = expr + ".vec()"
+
+            guard = guard_for(arg)
+            if guard is None:
+                if stmts_prepend:
+                    stmts.append(f"{stmts_prepend};")
+                stmts.append(f"grad_fn->{name} = {expr};")
+            else:
+                stmts.append(f"if ({guard}) {{")
+                if stmts_prepend:
+                    stmts.append(f"  {stmts_prepend};")
+                stmts.append(f"  grad_fn->{name} = {expr};")
+                stmts.append("}")
+        return stmts
+
+    # Generates a Dispatcher::redispatch() call into the dispatcher. We do this mainly for performance reasons:
+    #  - Pre-compute the full DispatchKeySet. This saves the dispatcher from having to read from TLS.
+    #  - redispatch() avoids a redundant call to RecordFunction, which was already called right before
+    #    we entered this autograd kernel.
+    def emit_dispatch_call(
+        f: NativeFunction, input_base: str, unpacked_args: Sequence[str]
+    ) -> str:
+        """Dispatch call via function in a namespace or method on Tensor."""
+        # code-generated autograd kernels plumb and recompute dispatch keys directly through the kernel for performance.
+        # Ops also always have a function variant of the redispatch API.
+        # See Note [Plumbing Keys Through The Dispatcher] for details.
+        dispatch_key_set = "ks & c10::after_autograd_keyset"
+        call = CALL_REDISPATCH.substitute(
+            api_name=cpp.name(
+                f.func,
+                faithful_name_for_out_overloads=True,
+                symint_overload=f.func.has_symint(),
+            ),
+            unpacked_args=[dispatch_key_set] + list(unpacked_args),
+        )
+        return call
+
+    def wrap_output(
+        f: NativeFunction, unpacked_bindings: list[Binding], var: str
+    ) -> str:
+        call = ""
+        rhs_value: str | None = None
+        if not any(r.type.is_tensor_like() for r in f.func.returns):
+            rhs_value = var
+        else:
+            rhs_value = f"std::move({var})"
+        assert rhs_value is not None
+        call += ASSIGN_RETURN_VALUE.substitute(
+            return_values=tie_return_values(f), rhs_value=rhs_value
+        )
+        return call
+
+    def check_tensorimpl_and_storage(
+        call: str, unpacked_bindings: list[Binding]
+    ) -> str:
+        # See NOTE [ TensorImpl and Storage Pointer Sanity Checks ]
+        stmts_before_call: list[str] = []
+        stmts_after_call: list[str] = []
+
+        if cpp.name(f.func) in DONT_ENFORCE_SAME_TENSOR_IMPL_OR_STORAGE:
+            return call
+
+        # Check properties of inputs (enforce (1))
+        for unpacked_binding in unpacked_bindings:
+            arg = unpacked_binding.name
+            noref_cpp_type = unpacked_binding.nctype.type.remove_const_ref()
+            if noref_cpp_type == BaseCType(tensorListT) or noref_cpp_type == BaseCType(
+                iTensorListRefT
+            ):
+                stmts_before_call += [
+                    SAVE_TENSORLIST_STORAGE.substitute(tensorlist_name=arg),
+                    SAVE_TENSORLIST_IMPL.substitute(tensorlist_name=arg),
+                ]
+                stmts_after_call += [
+                    ENFORCE_SAME_TENSORLIST_STORAGE.substitute(tensorlist_name=arg),
+                    ENFORCE_SAME_TENSORLIST_IMPL.substitute(tensorlist_name=arg),
+                ]
+            elif noref_cpp_type == ListCType(OptionalCType(BaseCType(tensorT))):
+                stmts_before_call += [
+                    SAVE_OPTIONALTENSORLIST_STORAGE.substitute(tensorlist_name=arg),
+                    SAVE_OPTIONALTENSORLIST_IMPL.substitute(tensorlist_name=arg),
+                ]
+                stmts_after_call += [
+                    ENFORCE_SAME_OPTIONALTENSORLIST_STORAGE.substitute(
+                        tensorlist_name=arg
+                    ),
+                    ENFORCE_SAME_OPTIONALTENSORLIST_IMPL.substitute(
+                        tensorlist_name=arg
+                    ),
+                ]
+            elif noref_cpp_type == BaseCType(tensorT):
+                stmts_before_call += [
+                    SAVE_TENSOR_STORAGE.substitute(tensor_name=arg),
+                    SAVE_TENSOR_IMPL.substitute(tensor_name=arg),
+                ]
+                stmts_after_call += [
+                    ENFORCE_SAME_TENSOR_STORAGE.substitute(
+                        tensor_name=arg, out_tensor_name=arg
+                    ),
+                    ENFORCE_SAME_TENSOR_IMPL.substitute(tensor_name=arg),
+                ]
+
+        assert (stmts_before_call and stmts_after_call) or (
+            not stmts_before_call and not stmts_after_call
+        )
+
+        # Check properties of outputs (enforce (2), (3))
+        if f.func.kind() not in (SchemaKind.inplace, SchemaKind.out):
+            base_name = f.func.name.name.base  # TODO: should be str(f.func.name.name)?
+            aliased_arg_name = ALL_VIEW_FUNCTIONS.get(base_name, None)
+            if aliased_arg_name is not None:
+                aliased_arg_name = unpacked_name(aliased_arg_name)
+            for i, (ret, ret_name) in enumerate(
+                zip(f.func.returns, cpp.return_names(f))
+            ):
+                noref_cpp_type = cpp.return_type(ret, symint=True).remove_const_ref()
+                if noref_cpp_type == BaseCType(tensorT):
+                    if aliased_arg_name is not None:
+                        assert i == 0, (
+                            "Expect non-CompositeImplicitAutograd view function {base} to return single output"
+                        )
+                        stmts_after_call += [
+                            ENFORCE_SAME_TENSOR_STORAGE.substitute(
+                                tensor_name=aliased_arg_name, out_tensor_name=ret_name
+                            )
+                        ]
+                    else:
+                        if (
+                            type_wrapper_name(f)
+                            not in DONT_ENFORCE_STORAGE_IMPL_USE_COUNT
+                        ):
+                            stmts_after_call += [
+                                ENFORCE_TENSOR_STORAGE_USE_COUNT_EQUALS_ONE.substitute(
+                                    tensor_name=ret_name, fn_name=type_wrapper_name(f)
+                                )
+                            ]
+
+                    if type_wrapper_name(f) not in DONT_ENFORCE_TENSOR_IMPL_USE_COUNT:
+                        stmts_after_call += [
+                            ENFORCE_TENSOR_IMPL_USE_COUNT_LT_OR_EQ_ONE.substitute(
+                                tensor_name=ret_name, fn_name=type_wrapper_name(f)
+                            )
+                        ]
+
+                # Currently we don't have any functions that return the following types, but
+                # we should update the checks once we do
+                elif noref_cpp_type == ListCType(OptionalCType(BaseCType(tensorT))):
+                    raise AssertionError(
+                        f"Please add use_count checks for {noref_cpp_type}"
+                    )
+                elif noref_cpp_type == BaseCType(tensorListT):
+                    raise AssertionError(
+                        f"Please add use_count checks for {noref_cpp_type}"
+                    )
+
+        if stmts_before_call and stmts_after_call:
+            call = (
+                RUN_ONLY_IN_DEBUG_MODE.substitute(statements=stmts_before_call)
+                + call
+                + RUN_ONLY_IN_DEBUG_MODE.substitute(statements=stmts_after_call)
+            )
+        return call
+
+    def emit_call(
+        f: NativeFunction, unpacked_bindings: list[Binding], try_jit_decomposition: bool
+    ) -> str:
+        # We only care about adding `at::AutoDispatchBelowAutograd` guard for non-variable dispatch
+        # (which corresponds to 'use_derived' strategy). The purpose of this guard is to make sure
+        # the baseType operations still dispatch to non-Variable type, even if the arguments passed
+        # in are now Variables.
+        # See NOTE [ Treating Variables as non-Variables in type dispatch ] for details.
+        unpacked_args = [b.name for b in unpacked_bindings]
+        base_type_call = emit_dispatch_call(f, "self_", unpacked_args)
+
+        if get_view_info(f) is not None or modifies_arguments(f):
+            guard = "at::AutoDispatchBelowAutograd guard;"
+        else:
+            guard = "at::AutoDispatchBelowADInplaceOrView guard;"
+
+        any_has_forward_grad = (
+            get_any_has_fw_grad_cond(derivative=None)
+            if requires_derivative
+            else "false"
+        )
+        return_types = ", ".join(
+            [cpp.return_type(a, symint=True).cpp_type() for a in f.func.returns]
+        )
+        if len(f.func.returns) > 1:
+            return_types = f"std::tuple<{return_types}>"
+
+        arg_names = [
+            a.name
+            for a in cpp.arguments(
+                f.func.arguments,
+                faithful=True,
+                symint=True,
+                method=False,
+                cpp_no_default_args=set(),
+            )
+        ]
+
+        if not modifies_arguments(f) and not returns_void:
+            if try_jit_decomposition:
+                call = DISPATCH_TO_NON_VAR_TYPE_WITH_TMP_RETURN_VALUES_JVP_DECOMP.substitute(
+                    base_type_call=base_type_call,
+                    tmp_var=TMP_VAR,
+                    guard=guard,
+                    any_has_forward_grad=any_has_forward_grad,
+                    op_name=cpp.name(f.func),
+                    op_overload=f.func.name.overload_name,
+                    return_types=return_types,
+                    arg_names=arg_names,
+                )
+            else:
+                call = DISPATCH_TO_NON_VAR_TYPE_WITH_TMP_RETURN_VALUES.substitute(
+                    base_type_call=base_type_call,
+                    tmp_var=TMP_VAR,
+                    guard=guard,
+                )
+
+            call += wrap_output(f, unpacked_bindings, TMP_VAR)
+        else:
+            assert not try_jit_decomposition
+            call = DISPATCH_TO_NON_VAR_TYPE_WITHOUT_RETURN_VALUES.substitute(
+                base_type_call=base_type_call, guard=guard
+            )
+        call = check_tensorimpl_and_storage(call, unpacked_bindings)
+        return call
+
+    def emit_history() -> str:
+        fn = "rebase" if modifies_arguments(f) and view_info is None else "set"
+        output_names = [r.name for r in differentiable_outputs]
+        # TODO: flatten allocates a std::vector, which could be expensive
+        outs = CodeTemplate("flatten_tensor_args( ${outs} )").substitute(
+            outs=output_names if not is_inplace_foreach else "self"
+        )
+        if not is_inplace_foreach:
+            return SET_HISTORY.substitute(fn=fn, differentiable_outputs=outs)
+        else:
+            return LOOP_OVER_VECTOR_OF_GRAD_FNS.substitute(
+                preamble=(
+                    f"auto differentiable_outputs = {outs};\n"
+                    f"TORCH_INTERNAL_ASSERT(differentiable_outputs.size() == grad_fns.size());"
+                ),
+                statements=f"{fn}_history(differentiable_outputs[i], grad_fns[i]);",
+            )
+
+    def emit_save_outputs() -> str:
+        if is_out_fn:
+            # out functions don't currently support differentiation
+            return ""
+        if info is not None and info.has_derivatives:
+            stmts = save_variables(info.all_saved_outputs, True)
+            if len(stmts) == 0:
+                return ""
+            if not is_inplace_foreach:
+                return CONDITIONAL.substitute(cond="grad_fn", statements=stmts)
+            else:
+                return LOOP_OVER_VECTOR_OF_GRAD_FNS.substitute(
+                    preamble="", statements=stmts
+                )
+        return ""
+
+    def emit_any_requires_grad() -> list[str]:
+        extra_condition = ""
+        if info and info.output_differentiability_conditions:
+            assert len(info.output_differentiability_conditions) == 1
+            extra_condition = f"_any_requires_grad &= ({info.output_differentiability_conditions[0]});"
+        names_of_args_with_derivatives = [arg.name for arg in args_with_derivatives]
+        if is_inplace_foreach and info is not None:
+            for i, arg in enumerate(names_of_args_with_derivatives):
+                for f_arg, r_arg in inplace_foreacharg2refarg.items():
+                    if arg == r_arg.name:
+                        names_of_args_with_derivatives[i] = f_arg.name
+        return [
+            SETUP_ANY_REQUIRES_GRAD.substitute(
+                args_with_derivatives=names_of_args_with_derivatives,
+                extra_differentiability_conditions=extra_condition,
+            )
+        ]
+
+    def get_any_has_forward_grad_name(var_names: tuple[str, ...]) -> str:
+        if len(var_names) == 1:
+            return f"_any_has_forward_grad_{var_names[0]}"
+        else:
+            return f"_any_has_forward_grad_{'_'.join(var_names)}"
+
+    def emit_any_has_forward_grad() -> list[str]:
+        content: list[str] = []
+        if not is_foreach:
+            for derivative in fw_derivatives:
+                requires_fw_grad = get_any_has_fw_grad_cond(derivative=derivative)
+                if info and info.output_differentiability_conditions:
+                    assert len(info.output_differentiability_conditions) == 1
+                    requires_fw_grad = f"({info.output_differentiability_conditions[0]}) && {requires_fw_grad}"
+                content.append(
+                    f"[[maybe_unused]] auto {get_any_has_forward_grad_name(derivative.var_names)} = {requires_fw_grad};"
+                )
+        else:
+            for derivative in fw_derivatives:
+                bool_vector_name = get_any_has_forward_grad_name(derivative.var_names)
+                cur_derivative_conditions = []
+                for inp in differentiable_inputs:
+                    if derivative.required_inputs_fw_grad is None:
+                        continue
+                    if inp.name not in derivative.required_inputs_fw_grad:
+                        continue
+                    inp_name = (
+                        inp.name
+                        if not inplace
+                        else refargname2inplace_foreacharg[inp.name].name
+                    )
+                    inp_type = (
+                        inp.type
+                        if not inplace
+                        else refargname2inplace_foreacharg[inp.name].type
+                    )
+                    is_list_type = is_tensor_list_type(inp_type)
+                    if is_list_type:
+                        if inp_name != "self":
+                            content.append(
+                                FW_DERIVATIVE_SIZE_CHECK_TEMPLATE.substitute(
+                                    inp_name=inp_name
+                                )
+                            )
+                        cur_derivative_conditions.append(
+                            FW_DERIVATIVE_CHECK_TEMPLATE.substitute(
+                                req_inp=inp_name + "[i]"
+                            )
+                        )
+                    else:
+                        cur_derivative_conditions.append(
+                            FW_DERIVATIVE_CHECK_TEMPLATE.substitute(req_inp=inp_name)
+                        )
+
+                content.append(f"std::vector {bool_vector_name}(self.size());")
+                content.append("for (const auto& i : c10::irange(self.size())) {")
+                content.append(
+                    f"  {bool_vector_name}[i] = {' || '.join(cur_derivative_conditions)};"
+                )
+                content.append("}")
+        return content
+
+    def emit_check_inplace() -> list[str]:
+        if not inplace:
+            return []
+        return [
+            f"check_inplace({arg.name}, _any_requires_grad);"
+            for arg in differentiable_outputs
+        ]
+
+    def emit_fw_derivatives() -> list[str]:
+        content: list[str] = []
+        fw_grad_setters: list[str] = []
+        for derivative in fw_derivatives:
+            res = derivative.var_names
+            if f.func.name.name.inplace:
+                assert len(res) == 1, (
+                    "Expected number of outputs to be 1 if function is inplace"
+                )
+                # TODO update this when inplace namings are unified
+                res = ("self",)
+
+            assert derivative.required_inputs_fw_grad is not None
+
+            unpacked_arguments = ""
+            for inp in differentiable_inputs:
+                inp_name = inp.name
+                is_input_tensorlist = is_foreach and is_tensor_list_type(
+                    inp.type
+                    if not inplace
+                    else refargname2inplace_foreacharg[inp.name].type
+                )
+                input_suffix = "[i]" if is_input_tensorlist else ""
+                if is_inplace_foreach:
+                    if inp.name in refargname2inplace_foreacharg:
+                        inp_name = refargname2inplace_foreacharg[inp.name].name
+                zeros_fn = (
+                    "zeros_symint"
+                    if inplace and inp.name == "self"
+                    else "_efficientzerotensor_symint"
+                )
+                if inp.name in derivative.required_inputs_fw_grad:
+                    unpacked_arguments += (
+                        FW_DERIVATIVE_DEFINED_GRAD_TEMPLATE.substitute(
+                            inp_name=inp.name,
+                            inp=inp_name + input_suffix,
+                            zeros_fn=zeros_fn,
+                        )
+                    )
+                if inp.name in (derivative.required_inputs_primal or []):
+                    unpacked_arguments += (
+                        FW_DERIVATIVE_DEFINED_PRIMAL_TEMPLATE.substitute(
+                            inp_name=inp.name,
+                            inp=inp_name + input_suffix,
+                        )
+                    )
+            if derivative.required_original_self_value:
+                input_suffix = "s[i]" if is_inplace_foreach else ""
+                unpacked_arguments += FW_DERIVATIVE_DEFINED_GRAD_TEMPLATE.substitute(
+                    inp_name="original_self",
+                    inp="original_self" + input_suffix,
+                    zeros_fn=zeros_fn,
+                )
+                unpacked_arguments += FW_DERIVATIVE_DEFINED_PRIMAL_TEMPLATE.substitute(
+                    inp_name="original_self",
+                    inp="original_self" + input_suffix,
+                )
+            elif inplace and derivative.is_reusing_outplace_formula:
+                # The gradient wasn't already cloned, do it if grad mode is enabled
+                unpacked_arguments += (
+                    "self_t = GradMode::is_enabled() ? self_t.clone() : self_t;"
+                )
+
+            if inplace:
+                is_inplace_str = "true"
+            else:
+                is_inplace_str = "false"
+
+            requires_fw_grad = get_any_has_forward_grad_name(derivative.var_names)
+
+            if all(
+                (isinstance(var_type, BaseType) and var_type.is_tensor_like())
+                for var_type in derivative.var_types
+            ):
+                # Is there a way to get from BaseType to BaseCType
+                if len(derivative.var_types) == 1:
+                    opt_res_grad_type = OptionalCType(BaseCType(tensorT)).cpp_type()
+                    if not is_foreach:
+                        fw_grad_setters.append(
+                            FW_DERIVATIVE_SETTER_TENSOR.substitute(
+                                out_arg=res[0], is_inplace=is_inplace_str
+                            )
+                        )
+                    else:
+                        assert res[0] == ("result" if not inplace else "self")
+                        fw_grad_setters.append(
+                            FW_DERIVATIVE_SETTER_TENSOR_FOREACH.substitute(
+                                out_arg=res[0], is_inplace=is_inplace_str
+                            )
+                        )
+                    requires_fw_grad += f" && ({derivative.var_names[0]}.defined())"
+                else:
+                    tuple_type = TupleCType(
+                        [BaseCType(tensorT)] * len(derivative.var_types)
+                    )
+                    opt_res_grad_type = OptionalCType(tuple_type).cpp_type()
+                    for idx, single_res in enumerate(res):
+                        fw_grad_setters.append(
+                            FW_DERIVATIVE_SETTER_MULTI_OUTPUT.substitute(
+                                idx=idx, all_res="_".join(res), out_arg=single_res
+                            )
+                        )
+            elif (
+                isinstance(derivative.var_types[0], ListType)
+                and derivative.var_types[0].is_tensor_like()
+            ):
+                assert len(derivative.var_types) == 1, (
+                    "Expected number of outputs to be 1 if function returns ListType"
+                )
+                if not is_foreach:
+                    opt_res_grad_type = OptionalCType(
+                        VectorCType(BaseCType(tensorT))
+                    ).cpp_type()
+                    fw_grad_setters.append(
+                        FW_DERIVATIVE_SETTER_TENSOR_LIST.substitute(
+                            out_arg=res[0], is_inplace=is_inplace_str
+                        )
+                    )
+                else:
+                    # TODO(crcrpar): Should this (= the foreach specific logic) be refactored somehow?
+                    # Only out-place foreach functions that have entries in `tools/autograd/derivatives.yaml`
+                    # can reach here.
+                    opt_res_grad_type = OptionalCType(BaseCType(tensorT)).cpp_type()
+                    fw_grad_setters.append(
+                        FW_DERIVATIVE_SETTER_TENSOR_FOREACH.substitute(
+                            out_arg=res[0], is_inplace=is_inplace_str
+                        )
+                    )
+            else:
+                raise RuntimeError("Unsupported output type for forward derivative")
+
+            if not is_foreach:
+                fw_grad_opt_definition = f"{opt_res_grad_type} {'_'.join(res)}_new_fw_grad_opt = ::std::nullopt;"
+                # View ops create fw_grad that already is a view of the base's fw_grad so just use that
+                content.append(
+                    FW_DERIVATIVE_TEMPLATE.substitute(
+                        fw_grad_opt_definition=fw_grad_opt_definition,
+                        requires_fw_grad=requires_fw_grad,
+                        formula=derivative.formula,
+                        out_arg="_".join(res),
+                        unpacked_arguments=unpacked_arguments,
+                    )
+                )
+            else:
+                # note(crcrpar): Assuming `self` is TensorList.
+                fw_grad_opt_definition = (
+                    f"std::vector<{opt_res_grad_type}> {'_'.join(res)}_new_fw_grad_opts"
+                    "(self.size(), ::std::nullopt);"
+                )
+                foreach_forward_grad_formula = derivative.formula
+                _foreach_arg: Argument | DifferentiableInput
+                if inplace:
+                    for _foreach_arg, _ref_arg in inplace_foreacharg2refarg.items():
+                        # note(crcrpar): Massage only Scalar and ArrayRef here.
+                        if not (
+                            is_tensor_type(_foreach_arg.type)
+                            or is_tensor_list_type(_foreach_arg.type)
+                        ):
+                            pattern = _foreach_arg.name
+                            if isinstance(_foreach_arg.type, ListType):
+                                pattern += "[i]"
+                            foreach_forward_grad_formula = (
+                                foreach_forward_grad_formula.replace(
+                                    _ref_arg.name, pattern
+                                )
+                            )
+                else:
+                    if (
+                        "result" in foreach_forward_grad_formula
+                        and "result[i]" not in foreach_forward_grad_formula
+                    ):
+                        foreach_forward_grad_formula = (
+                            foreach_forward_grad_formula.replace("result", "result[i]")
+                        )
+
+                content.append(
+                    FW_DERIVATIVE_FOREACH_TEMPLATE.substitute(
+                        fw_grad_opt_definition=fw_grad_opt_definition,
+                        vector_of_optional_tensor=f"{'_'.join(res)}_new_fw_grad_opts",
+                        any_has_forward_grad_for_current_index=" || ".join(
+                            get_any_has_forward_grad_name(derivative.var_names) + "[i]"
+                            for derivative in fw_derivatives
+                        ),
+                        formula=foreach_forward_grad_formula,
+                        unpacked_arguments=unpacked_arguments,
+                    )
+                )
+
+        # Set all the grads at the end to avoid: https://github.com/pytorch/pytorch/issues/67367
+        content.append("\n".join(fw_grad_setters))
+        return content
+
+    def get_any_has_fw_grad_cond(derivative: ForwardDerivative | None) -> str:
+        #
+        # Produces a condition string (e.g, "isFwGradDefined(grad_output) || isFwGradDefined(output)")
+        #
+        if derivative is None:
+            # (1) If a derivative is NOT provided, cond will check fw_grad of ALL differentiable inputs
+            # - Used in the out_fn case when we want to forbid fw derivatives
+            # - Used in the case where the fw_derivative is not defined, but we want
+            #   To check if there is a decomposition registered for jvp
+            to_check: list[str] = []
+            for inp in list(
+                mapMaybe(
+                    gen_differentiable_input,
+                    f.func.arguments.non_out + list(f.func.arguments.out),  # type: ignore[operator]
+                )
+            ):
+                if is_tensor_type(inp.type):
+                    to_check.append(
+                        FW_DERIVATIVE_CHECK_TEMPLATE.substitute(req_inp=inp.name)
+                    )
+                elif is_tensor_list_type(inp.type):
+                    to_check.append(
+                        FW_DERIVATIVE_TENSORLIST_CHECK_TEMPLATE.substitute(
+                            req_inp=inp.name
+                        )
+                    )
+                else:
+                    raise RuntimeError(
+                        f'Unsupported input type for "{name}" when forbidding forward AD usage.'
+                    )
+            return f"({' || '.join(to_check)})"
+        else:
+            # (2) If derivative is provided, use that information to determine which inputs
+            #     to check fw_grad for
+            assert derivative.required_inputs_fw_grad is not None
+
+            if len(derivative.required_inputs_fw_grad) == 0:
+                # Handle functions like stack
+                # For these, we don't unpack anything and always call the user function
+                if not (
+                    len(differentiable_inputs) == 1
+                    and is_tensor_list_type(differentiable_inputs[0].type)
+                ):
+                    raise RuntimeError(
+                        f'No differentiable input to "{name}" is a differentiable Tensor (as the provided '
+                        "forward AD formula does not use any input tangent) even though a forward gradient "
+                        "formula has been defined for it. This case should only happen for function that "
+                        "take a single TensorList as input. All other cases are not supported right now."
+                    )
+                any_has_fw_grad = "true"
+            else:
+                any_has_fw_grad = " || ".join(
+                    [
+                        (
+                            FW_DERIVATIVE_TENSORLIST_CHECK_TEMPLATE
+                            if is_tensor_list_type(inp.type)
+                            else FW_DERIVATIVE_CHECK_TEMPLATE
+                        ).substitute(req_inp=inp.name)
+                        for inp in differentiable_inputs
+                        if inp.name in derivative.required_inputs_fw_grad
+                    ]
+                )
+                any_has_fw_grad = f"({any_has_fw_grad})"
+
+            return any_has_fw_grad
+
+    def emit_forbid_fw_derivatives(is_out_fn: bool = False) -> str:
+        if is_out_fn:
+            msg = "because it is an out= function"
+        else:
+            msg = (
+                "because it has not been implemented yet.\\nPlease file an issue "
+                "to PyTorch at https://github.com/pytorch/pytorch/issues/new?template=feature-request.yml "
+                "so that we can prioritize its implementation."
+            )
+        cond = get_any_has_fw_grad_cond(derivative=None)
+        return (
+            FW_DERIVATIVE_FORBID_TEMPLATE.substitute(cond=cond, name=name, msg=msg)
+            if cond != ""
+            else ""
+        )
+
+    body: list[str] = []
+    unpack_args_stats, unpacked_bindings = unpack_args(f)
+
+    body.extend(unpack_args_stats)
+    if requires_derivative:
+        body.extend(emit_any_requires_grad())
+        body.extend(emit_any_has_forward_grad())
+        body.extend(emit_check_inplace())
+        body.extend(emit_original_self_definition())
+        body.extend(setup_derivative(differentiable_inputs))
+
+    body.append(emit_call(f, unpacked_bindings, try_jit_decomposition))
+    if requires_derivative:
+        # set_flags has to appear after version_counter, because rebase_history
+        # requires that the counter is incremented before it is called
+        body.append(emit_history())
+        body.extend(emit_check_if_in_complex_autograd_allowlist())
+
+    if is_out_fn:
+        body.append(emit_forbid_fw_derivatives(is_out_fn=True))
+    else:
+        if requires_derivative and not try_jit_decomposition:
+            if len(fw_derivatives) > 0:
+                body.extend(emit_fw_derivatives())
+            else:
+                body.append(emit_forbid_fw_derivatives())
+
+    if requires_derivative:
+        # Save only after the forward AD has been set up
+        body.append(emit_save_outputs())
+
+    if str(f.func.name.name) in RESET_GRAD_ACCUMULATOR:
+        # `inplace` implies that there is exactly one output named `self`,
+        # so we can keep the generated code easy. If you need to
+        # `reset_grad_accumulator` in an operator that's not `inplace`, you can
+        # remove this assert but the code generation will get more elaborate
+        assert inplace
+        body.append("reset_grad_accumulator(self);")
+    if not returns_void:
+        body.append(f"return {get_return_value(f)};")
+    return body
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_view_funcs.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_view_funcs.py
new file mode 100644
index 0000000000000000000000000000000000000000..8cc8a2ffcecc4571c5101a265be3a5eeb766473a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_view_funcs.py
@@ -0,0 +1,339 @@
+# Generates ViewFuncs.h/cpp
+#
+# NOTE: If any changes are being made to the ViewFunc codegen please also check
+# if updates are needed in torch/csrc/autograd/autograd_not_implemented_fallback.cpp
+# The fallback is expected to mimic this codegen, so we should keep the two in sync.
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+import torchgen.api.dispatcher as dispatcher
+from torchgen.api.translate import translate
+from torchgen.api.types import (
+    BaseCType,
+    Binding,
+    NamedCType,
+    SymIntT,
+    tensorT,
+    VectorCType,
+)
+from torchgen.code_template import CodeTemplate
+from torchgen.model import Argument, NativeFunction, OptionalType
+from torchgen.utils import FileManager
+
+from .gen_inplace_or_view_type import (
+    CALL_DISPATCH,
+    extract_bindings,
+    get_view_info,
+    modifies_arguments,
+    use_derived,
+)
+
+
+if TYPE_CHECKING:
+    from torchgen.api.autograd import NativeFunctionWithDifferentiabilityInfo
+
+
+FUNCTION_DECLARATION = CodeTemplate(
+    """\
+#define ${uppercase_op}_AVAILABLE
+struct ${op} : public ${superclass} {
+  ${op}(${constructor_args}) ${initializer_list}
+  {}
+  virtual ~${op}() override = default;
+  virtual std::vector get_symints() const override;
+  virtual size_t num_symints() const override;
+  virtual std::vector get_tensors() const override;
+  virtual size_t num_tensors() const override;
+  virtual at::Tensor operator()(const at::Tensor&) const override;
+  virtual std::unique_ptr clone_and_set(
+      std::optional> = ::std::nullopt,
+      std::optional> = ::std::nullopt) const override;
+
+protected:
+  virtual void set_symints(std::vector) override;
+  virtual void set_tensors(std::vector) override;
+
+private:
+  ${state}
+};
+
+"""
+)
+
+FUNCTION_DEFINITION = CodeTemplate(
+    """\
+std::vector ${op}::get_symints() const {
+  ${get_symints}
+}
+
+size_t ${op}::num_symints() const {
+  return static_cast(${num_symints});
+}
+
+void ${op}::set_symints(std::vector ${symints_vec}) {
+  TORCH_INTERNAL_ASSERT(${symints_vec}.size() == num_symints());
+  ${set_symints}
+}
+
+std::vector ${op}::get_tensors() const {
+  ${get_tensors}
+}
+
+size_t ${op}::num_tensors() const {
+  return static_cast(${num_tensors});
+}
+
+void ${op}::set_tensors(std::vector ${tensors_vec}) {
+  TORCH_INTERNAL_ASSERT(${tensors_vec}.size() == num_tensors());
+  ${set_tensors}
+}
+
+at::Tensor ${op}::operator()(const at::Tensor& ${call_input_name}) const {
+  return ${op_call};
+}
+
+std::unique_ptr ${op}::clone_and_set(
+    std::optional> ${symints_vec},
+    std::optional> ${tensors_vec}) const {
+  auto output = std::make_unique<${op}>(${clone_args});
+  if (${symints_vec}.has_value()) {
+    output->set_symints(std::move(*(${symints_vec})));
+  }
+  if (${tensors_vec}.has_value()) {
+    output->set_tensors(std::move(*(${tensors_vec})));
+  }
+  return output;
+}
+
+"""
+)
+
+
+# e.g. as_strided -> AsStridedViewFunc for camel case or
+# as_strided_view_func otherwise
+def view_func_name(
+    f: NativeFunction, include_namespace: bool = False, camel_case: bool = True
+) -> str:
+    name = f.func.name.unambiguous_name()
+    view_func_name = f"{name.replace('.', '_')}_view_func"
+    if camel_case:
+        is_private = view_func_name.startswith("_")
+        view_func_name = "".join(
+            [p.title() for p in view_func_name.replace(".", "_").split("_")]
+        )
+        if is_private:
+            # put the leading underscore back in
+            view_func_name = f"_{view_func_name}"
+    namespace = "torch::autograd::generated::" if include_namespace else ""
+    return f"{namespace}{view_func_name}"
+
+
+def is_symint_or_tensor(arg: Argument) -> bool:
+    return arg.type.is_tensor_like() or arg.type.is_symint_like()
+
+
+def remove_const_ref(binding: Binding) -> Binding:
+    return Binding(
+        name=binding.name,
+        nctype=binding.nctype.remove_const_ref(),
+        argument=binding.argument,
+        default=binding.default,
+    )
+
+
+def returns_multi_tensor(fn: NativeFunction) -> bool:
+    returns = fn.func.returns
+    assert len(returns) == 1
+    returns_list_like = returns[0].type.is_list_like() is not None
+    returns_tensor_like = returns[0].type.is_tensor_like()
+    return returns_list_like and returns_tensor_like
+
+
+# Generates strings with logic for getting / setting state of a particular type.
+#
+# Args:
+#   bindings (list): List of state bindings of interest (may be empty)
+#   state_vec_type (NamedCType): Type of vector to either return or copy from
+#
+# Returns:
+#   tuple: (list of getter logic strings, list of setter logic strings, string
+#     with num items expression)
+def generate_state_getter_setter(
+    bindings: list[Binding],
+    state_vec_type: NamedCType,
+) -> tuple[list[str], list[str], str]:
+    getter_logic = []
+    setter_logic = []
+
+    state_vec = state_vec_type.name
+    getter_logic.append(f"{state_vec_type.cpp_type()} {state_vec};")
+    if len(bindings) > 0:
+        setter_logic.append("auto i = 0;")
+
+    num_exprs = []
+    for i, b in enumerate(bindings):
+        assert isinstance(b.argument, Argument)
+        if b.argument.type.is_list_like():
+            # Handle list-likes.
+            num_expr = f"{b.name}.size()"
+            num_exprs.append(num_expr)
+            getter = f"{state_vec}.insert({state_vec}.end(), {b.name}.begin(), {b.name}.end());"
+            setter = f"std::copy({state_vec}.begin() + i, {state_vec}.begin() + i + {b.name}.size(), {b.name}.begin());"
+        elif isinstance(b.argument.type, OptionalType):
+            # Handle optionals.
+            num_expr = f"({b.name}.has_value() ? 1 : 0)"
+            num_exprs.append(num_expr)
+            conditional = f"if({b.name}.has_value())"
+            getter = (
+                f"{conditional} {state_vec}.insert({state_vec}.end(), *({b.name}));"
+            )
+            setter = f"{conditional} {b.name} = {state_vec}[i];"
+        else:
+            num_expr = "1"
+            num_exprs.append(num_expr)
+            getter = f"{state_vec}.push_back({b.name});"
+            setter = f"{b.name} = {state_vec}[i];"
+
+        getter_logic.append(getter)
+        setter_logic.append(setter)
+        if i < len(bindings) - 1:
+            setter_logic.append(f"i += {num_expr};")
+
+    # Reserve / assert based on the total number of items expression.
+    num_items = "0" if len(num_exprs) == 0 else " + ".join(num_exprs)
+    if len(bindings) > 0:
+        getter_logic.insert(1, f"{state_vec}.reserve({num_items});")
+
+    getter_logic.append(f"return {state_vec};")
+
+    return getter_logic, setter_logic, num_items
+
+
+def process_function(fn: NativeFunction, template: CodeTemplate) -> str:
+    bindings = extract_bindings(fn)
+    non_self_bindings = [b for b in bindings if b.name != "self"]
+
+    non_self_args = fn.func.arguments.flat_all[1:]
+    non_self_value_bindings = [
+        dispatcher.argument(a, remove_non_owning_ref_types=True) for a in non_self_args
+    ]
+
+    # Generate constructor / clone args for the generated struct.
+    constructor_args = [b.defn() for b in non_self_bindings]
+    clone_args = [b.name for b in non_self_bindings]
+
+    # Generate state variable declarations for the generated struct.
+    state_variables = [
+        f"{remove_const_ref(b).defn()};" for b in non_self_value_bindings
+    ]
+
+    # Generate initializer list expressions for the generated struct.
+    # allow_expensive_conversions=True because we need to store e.g. SymIntArrayRefs as
+    # vectors.
+    init_exprs = translate(
+        non_self_bindings, non_self_value_bindings, allow_expensive_conversions=True
+    )
+    initializers = []
+    for b, init_expr in zip(non_self_bindings, init_exprs):
+        name = b.nctype.name
+        assert isinstance(name, str)
+        initializers.append(f"{name}({init_expr.expr})")
+
+    # Generate call to underlying view op
+    call_input_name = "input_base"
+    op_call_args = [call_input_name, *(b.name for b in non_self_bindings)]
+    op_call = CALL_DISPATCH.substitute(
+        unambiguous_name=fn.func.name.unambiguous_name(),
+        unpacked_args=op_call_args,
+    )
+
+    # Multi-output views additionally require a view_idx for disambiguation.
+    if returns_multi_tensor(fn):
+        view_idx_name = "view_idx"
+        view_idx_typename = "int64_t"
+        view_idx_decl = f"{view_idx_typename} {view_idx_name}"
+        constructor_args.append(view_idx_decl)
+        clone_args.append(view_idx_name)
+        state_variables.append(f"{view_idx_decl};")
+        initializers.append(f"{view_idx_name}({view_idx_name})")
+        op_call += f"[{view_idx_name}]"
+
+    # Generate initializer list for the generated struct.
+    initializer_list = f": {', '.join(initializers)}" if len(initializers) > 0 else ""
+
+    # Generate getter / setter logic for any symints.
+    symint_bindings = [
+        b
+        for b in non_self_bindings
+        if isinstance(b.argument, Argument) and b.argument.type.is_symint_like()
+    ]
+    symints_vec_type = NamedCType("symints", VectorCType(BaseCType(SymIntT)))
+    get_symints, set_symints, num_symints = generate_state_getter_setter(
+        symint_bindings, symints_vec_type
+    )
+
+    # Generate getter / setter logic for any tensors.
+    tensor_bindings = [
+        b
+        for b in non_self_bindings
+        if isinstance(b.argument, Argument) and b.argument.type.is_tensor_like()
+    ]
+    tensors_vec_type = NamedCType("tensors", VectorCType(BaseCType(tensorT)))
+    get_tensors, set_tensors, num_tensors = generate_state_getter_setter(
+        tensor_bindings, tensors_vec_type
+    )
+
+    return template.substitute(
+        op=view_func_name(fn),
+        uppercase_op=view_func_name(fn, camel_case=False).upper(),
+        superclass="torch::autograd::ViewFunc",
+        initializer_list=initializer_list,
+        state=state_variables,
+        constructor_args=constructor_args,
+        clone_args=clone_args,
+        symints_vec=symints_vec_type.name,
+        get_symints=get_symints,
+        set_symints=set_symints,
+        num_symints=num_symints,
+        tensors_vec=tensors_vec_type.name,
+        get_tensors=get_tensors,
+        set_tensors=set_tensors,
+        num_tensors=num_tensors,
+        call_input_name=call_input_name,
+        op_call=op_call,
+    )
+
+
+def gen_view_funcs(
+    out: str,
+    fns_with_infos: list[NativeFunctionWithDifferentiabilityInfo],
+    template_path: str,
+) -> None:
+    # don't need the info parts, just the function
+    fns = [fn.func for fn in fns_with_infos if use_derived(fn)]
+    # only want out-of-place views
+    view_fns = [
+        fn for fn in fns if get_view_info(fn) is not None and not modifies_arguments(fn)
+    ]
+
+    declarations = [process_function(fn, FUNCTION_DECLARATION) for fn in view_fns]
+    definitions = [process_function(fn, FUNCTION_DEFINITION) for fn in view_fns]
+    ops_headers = [f"#include " for fn in view_fns]
+
+    file_basename = "ViewFuncs"
+    fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
+    for suffix in [".h", ".cpp"]:
+        fname = file_basename + suffix
+        fm.write_with_template(
+            fname,
+            fname,
+            lambda: {
+                "generated_comment": "@"
+                + f"generated from {fm.template_dir_for_comments()}/{fname}",
+                "view_func_declarations": declarations,
+                "view_func_definitions": definitions,
+                "ops_headers": ops_headers,
+            },
+        )
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/load_derivatives.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/load_derivatives.py
new file mode 100644
index 0000000000000000000000000000000000000000..f61226f25fb90f7874597c43154e9fc53389a485
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/load_derivatives.py
@@ -0,0 +1,1019 @@
+# Parses derivatives.yaml into autograd functions
+#
+# Each autograd function is represented by `DifferentiabilityInfo` containing
+# a list of `Derivative`. See `torchgen.api.autograd` for the data models.
+
+from __future__ import annotations
+
+import re
+from collections import Counter, defaultdict
+from typing import Any, TYPE_CHECKING
+
+import yaml
+
+from torchgen.api import cpp
+from torchgen.api.autograd import (
+    Derivative,
+    DifferentiabilityInfo,
+    ForwardDerivative,
+    SavedAttribute,
+)
+from torchgen.api.types import (
+    BaseCType,
+    Binding,
+    boolT,
+    CppSignatureGroup,
+    layoutT,
+    longT,
+    NamedCType,
+    OptionalCType,
+    scalarTypeT,
+    SpecialArgName,
+    stringT,
+    symIntArrayRefT,
+    SymIntT,
+    tensorGeometryT,
+    tensorOptionsT,
+    typeAndSizeT,
+    VectorCType,
+)
+from torchgen.context import with_native_function
+from torchgen.gen import get_grouped_by_view_native_functions, parse_native_yaml
+from torchgen.model import (
+    AUTOGRAD_KEYS,
+    FunctionSchema,
+    NativeFunction,
+    NativeFunctionsViewGroup,
+    OperatorName,
+    SchemaKind,
+    Type,
+    Variant,
+)
+from torchgen.utils import concatMap, IDENT_REGEX, split_name_params
+from torchgen.yaml_utils import YamlLoader
+
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+
+
+DerivativeRet = tuple[dict[FunctionSchema, dict[str, DifferentiabilityInfo]], set[str]]
+
+_GLOBAL_LOAD_DERIVATIVE_CACHE: dict[tuple[str, str], DerivativeRet] = {}
+
+_VALID_AUTOGRAD_KEYS = set(AUTOGRAD_KEYS)
+
+
+# This function directly adds per-dispatchkey derivative entries for {view}_copy variants of each view op.
+# Since every {view} and {view}_copy op shares the same derivative formula,
+# we generate them here instead of duplicating them in the yaml.
+# See Note [Codegen'd {view}_copy Operators]
+def add_view_copy_derivatives(
+    infos: dict[FunctionSchema, dict[str, DifferentiabilityInfo]],
+    view_groups: list[NativeFunctionsViewGroup],
+) -> None:
+    # Get the map from each view op's name to its corresponding view group
+    view_name_to_group: dict[OperatorName, NativeFunctionsViewGroup] = {
+        g.view.func.name: g for g in view_groups
+    }
+
+    view_infos = {}
+
+    for info_dispatch_dict in infos.values():
+        # maybe_view_group only needs to be calculated once per info_dispatch_dict
+        maybe_view_group = None
+        view_copy_differentiability_infos = {}
+        for dispatch_key, info in info_dispatch_dict.items():
+            maybe_view_group = view_name_to_group.get(info.func.func.name, None)
+            if maybe_view_group is not None and maybe_view_group.view_copy is not None:
+                view_copy_info = info.create_view_copy_from_view_derivative(
+                    maybe_view_group
+                )
+                if view_copy_info is not None:
+                    fn_schema = view_copy_info.func.func
+                    view_copy_differentiability_infos[dispatch_key] = view_copy_info
+            else:
+                break
+        # prefer manually-defined derivatives if any
+        if len(view_copy_differentiability_infos) > 0 and fn_schema not in infos:
+            assert fn_schema is not None
+            view_infos[fn_schema] = view_copy_differentiability_infos
+
+    infos.update(view_infos)
+
+
+def load_derivatives(
+    derivatives_yaml_path: str, native_yaml_path: str, tags_yaml_path: str
+) -> DerivativeRet:
+    # Do some caching as this is a deterministic function
+    global _GLOBAL_LOAD_DERIVATIVE_CACHE
+    key = (derivatives_yaml_path, native_yaml_path)
+    if key not in _GLOBAL_LOAD_DERIVATIVE_CACHE:
+        with open(derivatives_yaml_path) as f:
+            definitions = yaml.load(f, Loader=YamlLoader)
+
+        funcs = parse_native_yaml(native_yaml_path, tags_yaml_path).native_functions
+        # From the parsed native functions, separate out the (generated) view_copy functions,
+        # so we can generate derivatives for them separately.
+        native_functions_with_view_groups = get_grouped_by_view_native_functions(funcs)
+        native_functions = concatMap(
+            lambda g: [g]
+            if isinstance(g, NativeFunction)
+            else list(g.functions(include_copy=True)),
+            native_functions_with_view_groups,
+        )
+        view_groups = [
+            g
+            for g in native_functions_with_view_groups
+            if isinstance(g, NativeFunctionsViewGroup)
+        ]
+
+        # What's the difference between function schema v.s. signature?
+        # function schema is the complete declaration including mutability annotation / default value and etc.
+        # signature is the canonical schema for a group of functions (in-place/out/functional variants)
+        # that are semantically related.
+        functions_by_signature: dict[FunctionSchema, list[NativeFunction]] = (
+            defaultdict(list)
+        )
+        functions_by_schema: dict[str, NativeFunction] = {}
+        for function in native_functions:
+            functions_by_signature[function.func.signature()].append(function)
+            assert str(function.func) not in functions_by_schema
+            functions_by_schema[str(function.func)] = function
+
+        # Keep track of how many of which ops we've seen so we can
+        # disambiguate them with a numeric suffix.
+        op_counter = Counter[str]()
+
+        # infos is a dict that maps FunctionSchema -> a dict of per dispatch key DifferentiabilityInfos
+        # this is useful because in tools/autograd/gen_autograd.py:match_differentiability_info
+        # we ultimately need to categorize the DifferentiabilityInfos by FunctionSchema
+        infos: dict[FunctionSchema, dict[str, DifferentiabilityInfo]] = {}
+        used_dispatch_keys: set[str] = set()
+        for defn_dict in definitions:
+            # Ensure that the old derivatives.yaml schema with no dispatch key can be loaded.
+            if "dispatch" not in defn_dict:
+                specification = defn_dict.pop("name")
+                output_differentiability = defn_dict.pop(
+                    "output_differentiability", None
+                )
+                defn_dict = {"name": specification, "dispatch": {"Default": defn_dict}}
+                if output_differentiability:
+                    defn_dict["output_differentiability"] = output_differentiability
+            name, per_dispatch_diffinfos = create_differentiability_info(
+                defn_dict,
+                functions_by_signature,
+                functions_by_schema,
+                op_counter,
+                used_dispatch_keys,
+            )
+            infos[name] = per_dispatch_diffinfos
+
+        add_view_copy_derivatives(infos, view_groups)
+
+        # cache both loaded infos as well a a set of all the dispatch_keys/aliases
+        # that appear in derivatives.yaml. used_dispatch_keys is useful for generating
+        # VariableType.cpp where we need a TORCH_LIBRARY_IMPL for every autograd dispatch key used
+        _GLOBAL_LOAD_DERIVATIVE_CACHE[key] = infos, used_dispatch_keys
+
+    return _GLOBAL_LOAD_DERIVATIVE_CACHE[key]
+
+
+# TODO: Why is this going through CppSignatureGroup, that doesn't make sense...
+@with_native_function
+def cpp_arguments(f: NativeFunction) -> Sequence[Binding]:
+    sigs = CppSignatureGroup.from_native_function(f, method=False)
+    if sigs.symint_signature is not None:
+        return sigs.symint_signature.arguments()
+    else:
+        return sigs.signature.arguments()
+
+
+def create_derivative(
+    f: NativeFunction,
+    formula: str,
+    var_names: tuple[str, ...],
+    available_named_gradients: Sequence[str],
+) -> Derivative:
+    original_formula = formula
+    arguments: list[NamedCType] = [
+        a.nctype.remove_const_ref() for a in cpp_arguments(f)
+    ]
+
+    return_names = tuple(n if n != "self" else "result" for n in cpp.return_names(f))
+    return_types = tuple(
+        cpp.return_type(r, symint=True).remove_const_ref() for r in f.func.returns
+    )
+
+    named_returns = [
+        NamedCType(name, type) for name, type in zip(return_names, return_types)
+    ]
+
+    formula, saved_inputs = saved_variables(formula, arguments, var_names)
+    formula, saved_outputs = saved_variables(formula, named_returns, var_names)
+
+    used_named_gradients = {
+        name
+        for name in available_named_gradients
+        if re.search(IDENT_REGEX.format(name), formula)
+    }
+
+    # Check that the referenced derivatives in the formula are in bounds
+    for i in used_gradient_indices(formula):
+        if i >= len(f.func.returns):
+            raise RuntimeError(
+                f"Out of bounds grads access: derivative formula for {cpp.name(f.func)} "
+                f"used grads[{i}], but the forward only returns {len(f.func.returns)} outputs."
+            )
+
+    return Derivative(
+        formula=formula,
+        original_formula=original_formula,
+        var_names=var_names,
+        saved_inputs=saved_inputs,
+        saved_outputs=saved_outputs,
+        named_gradients=used_named_gradients,
+    )
+
+
+def create_forward_derivative(
+    f: NativeFunction, formula: str, names: tuple[str, ...]
+) -> ForwardDerivative:
+    var_names = names
+    var_types: tuple[Type, ...] | None = None
+    for r in f.func.returns:
+        if r.name in var_names:
+            if var_types is None:
+                var_types = ()
+            var_types = var_types + (r.type,)
+
+    # Handle default return names
+    if var_types is None:
+        if var_names == ("result",):
+            assert len(f.func.returns) == 1
+            var_types = (f.func.returns[0].type,)
+        else:
+            for var_name in var_names:
+                res = re.findall(r"^result(\d+)$", var_name)
+                if len(res) == 1:
+                    if var_types is None:
+                        var_types = ()
+                    arg_idx = int(res[0])
+                    var_types = var_types + (f.func.returns[arg_idx].type,)
+
+    assert var_types is not None, "No matching output for forward derivative definition"
+    return ForwardDerivative(
+        formula=formula,
+        var_names=var_names,
+        var_types=var_types,
+        required_inputs_fw_grad=None,
+        required_inputs_primal=None,
+        required_original_self_value=False,
+        is_reusing_outplace_formula=False,
+    )
+
+
+def postprocess_forward_derivatives(
+    f: NativeFunction,
+    defn_name: str,
+    all_arg_names: list[str],
+    derivatives: list[Derivative],
+    forward_derivatives: list[ForwardDerivative],
+    args_with_derivatives: Sequence[Binding],
+) -> list[ForwardDerivative]:
+    def find_required_inputs(formula: str, postfix: str) -> tuple[str, ...]:
+        is_foreach = f.func.name.name.base.startswith("_foreach_")
+        required_inputs = set()
+        for arg in args_with_derivatives:
+            if (
+                arg.type in ("at::TensorList", "const at::ITensorListRef &")
+                and not is_foreach
+            ):
+                # The functions taking TensorList handle everything internally
+                continue
+            arg_name = arg.name
+
+            found = re.search(IDENT_REGEX.format(arg_name), formula)
+            if found:
+                raise RuntimeError(
+                    f"The forward formula for {defn_name} is using the base name of the {arg_name} "
+                    f"argument which is ambiguous. You should use {arg_name}_p to access the primal "
+                    f"value and {arg_name}_t to access the tangent."
+                )
+
+            found = re.search(IDENT_REGEX.format(arg_name + postfix), formula)
+            if found:
+                required_inputs.add(arg_name)
+
+        return tuple(required_inputs)
+
+    updated_derivatives: list[ForwardDerivative] = []
+
+    for defn in forward_derivatives:
+        formula = defn.formula
+        required_inputs_tangent = find_required_inputs(formula, "_t")
+        if formula == "auto_element_wise":
+            assert f.func.kind() != SchemaKind.inplace, (
+                f"Cannot use auto_element_wise with {f.func.name} because it is an in-place variant"
+            )
+            if (
+                (not len(args_with_derivatives) == 1)
+                or len(forward_derivatives) > 1
+                or len(forward_derivatives[0].var_names) > 1
+            ):
+                raise RuntimeError(
+                    f"Derivative definition of {defn_name} in derivatives.yaml defines the "
+                    "forward definition of gradient as element_wise but this only "
+                    "works for functions with a single differentiable input and a "
+                    "single differentiable output."
+                )
+            if not len(derivatives) == 1:
+                raise RuntimeError(
+                    f"Derivative definition of {defn_name} in derivatives.yaml defines the "
+                    "forward definition of gradient as element_wise but it does not "
+                    "defines the gradient formula for its argument which is required."
+                )
+            # This transformation is based on the observation that for element-wise functions, the Jacobian
+            # matrix is diagonal and thus doing J * v is the same as (v^T J)^T (in practice, we ignore the transpositions)
+            # For the complex case, we use hermitian transpose and get (v.conj() J).conj()
+            # So here we are going to reuse the backward formula and replace two things:
+            # 1) all occurrences of "grad" with "foo_t.conj()", where foo is the name of the unique differentiable input.
+            # 2) all usage of an original input "foo" with its primal value "foo_p".
+            # 3) conjugate the final result
+            # For example, for abs, the backward formula is:
+            #   grad * self.sgn()
+            # And this function generates a forward formula that is:
+            #   (self_t.conj() * self_p.sgn()).conj()
+
+            backward_formula = derivatives[0].original_formula
+            input_name = args_with_derivatives[0].name
+
+            # Do replacement 1) of the grad
+            def repl(m: Any) -> str:
+                return f"{m.group(1)}{input_name}_t.conj(){m.group(2)}"
+
+            fw_formula = re.sub(IDENT_REGEX.format("grad"), repl, backward_formula)
+
+            # Do replacement 2) of the input variables
+            for arg in args_with_derivatives:
+                arg_name = arg.name
+
+                def repl(m: Any) -> str:
+                    return f"{m.group(1)}{arg_name}_p{m.group(2)}"
+
+                fw_formula = re.sub(IDENT_REGEX.format(arg_name), repl, fw_formula)
+
+            # Do the final conjugate 3)
+            fw_formula = f"({fw_formula}).conj()"
+
+            # Since there is a single differentiable inputs and we necessarily need its tangent we can
+            # simply require all differentiable input's tangent.
+            required_inputs_tangent = tuple(all_arg_names)
+            formula = fw_formula
+        elif formula == "auto_linear":
+            if (
+                len(forward_derivatives) > 1
+                or len(forward_derivatives[0].var_names) > 1
+            ):
+                raise RuntimeError(
+                    f"Derivative definition of {defn_name} in derivatives.yaml defines the "
+                    "forward definition of gradient as linear but this only works "
+                    "for functions with a single differentiable output."
+                )
+            # This transformation is based on the observation that linear functions can be written as:
+            #   y = f(x) = A * x
+            # For some matrix A and the Jacobian of the function f is also A.
+            # So doing J * v = A * v = f(v).
+            # Hence to do the jvp, we simply need to evaluate the function at the point v instead of x.
+            # We do this by calling the forward again by replacing any occurrence of the differentiable
+            # input "foo" by it's tangent "foo_t".
+            # Note that multiple inputs are not a problem as long as the function is truly linear wrt to
+            # the vector where all the differentiable inputs are stacked.
+
+            diff_arg_names = [arg.name for arg in args_with_derivatives]
+            assert len(diff_arg_names) > 0
+
+            # Do replacement of input variables
+            new_args = []
+            for arg_name in all_arg_names:
+                if arg_name in diff_arg_names:
+                    arg_name = arg_name + "_t"
+                new_args.append(arg_name)
+
+            # TODO we are trolling
+            if f.func.has_symint():
+                defn_name += "_symint"
+
+            # Call into the forward again. We need two cases here to handle both Tensor methods and at:: functions.
+            if Variant.function in f.variants:
+                fw_formula = f"at::{defn_name}({', '.join(new_args)})"
+            else:
+                assert Variant.method in f.variants
+                fw_formula = f"{new_args[0]}.{defn_name}({', '.join(new_args[1:])})"
+
+            # All of the input tangents are always used so all of them are required here.
+            required_inputs_tangent = tuple(diff_arg_names)
+            formula = fw_formula
+
+        # At this point, the formula is final and is not modified anymore.
+
+        # During forward formula, we use the primal instead of the input Tensors.
+        # This call inspects the formula to find for which input's primal are used.
+        required_inputs_primal = find_required_inputs(formula, "_p")
+
+        updated_derivatives.append(
+            ForwardDerivative(
+                formula=formula,
+                var_names=defn.var_names,
+                var_types=defn.var_types,
+                required_inputs_fw_grad=required_inputs_tangent,
+                required_inputs_primal=required_inputs_primal,
+                required_original_self_value=False,
+                is_reusing_outplace_formula=False,
+            )
+        )
+
+    return updated_derivatives
+
+
+def is_forward_derivative_definition(
+    all_arg_names: list[str], names: tuple[str, ...]
+) -> bool:
+    for name in names:
+        return name not in all_arg_names
+    raise RuntimeError("Expected `names` to be non-empty")
+
+
+def create_differentiability_info(
+    defn_dict: dict[Any, Any],
+    functions_by_signature: dict[FunctionSchema, list[NativeFunction]],
+    functions_by_schema: dict[str, NativeFunction],
+    op_counter: Counter[str],
+    used_dispatch_keys: set[str],
+) -> tuple[FunctionSchema, dict[str, DifferentiabilityInfo]]:
+    """Processes a single entry `defn` in derivatives.yaml"""
+
+    def canonical_function(
+        functions: Sequence[NativeFunction], name: str
+    ) -> NativeFunction:
+        for f in functions:
+            if (
+                not f.func.is_functional_fn()
+                and not f.func.is_out_fn()
+                and name == str(f.func.name.name)
+            ):
+                return f
+        # some functions only have in-place variants
+        assert name + "_" == cpp.name(functions[0].func)
+        return functions[0]
+
+    def split_names(raw_names: str) -> tuple[str, ...]:
+        """Given "foo, bar", return ["foo", "bar"]."""
+        return tuple(x.strip() for x in raw_names.split(","))
+
+    def check_grad_usage(defn_name: str, derivatives: Sequence[Derivative]) -> None:
+        """
+        Check for some subtle mistakes one might make when writing derivatives.
+        These mistakes will compile, but will be latent until a function is
+        used with double backwards.
+        """
+
+        uses_grad = False  # true if any derivative uses "grad"
+        num_grads_uses = 0  # count of uses of "grads" or "grads[INDEX]"
+        uses_named_grads = False  # true if any derivative uses "grad_{name}"
+        used_grads_indices: list[int] = []  # which indices of grads are used
+        for d in derivatives:
+            formula = d.formula
+            uses_grad = uses_grad or bool(
+                re.findall(IDENT_REGEX.format("grad"), formula)
+            )
+            num_grads_uses += len(re.findall(IDENT_REGEX.format("grads"), formula))
+            uses_named_grads = uses_named_grads or bool(d.named_gradients)
+            used_grads_indices.extend(used_gradient_indices(formula))
+        # This is a basic sanity check: the number of places we see
+        # "grads" should be no fewer than the number of indices we see
+        # inside "grads". They may not be equal because we may use
+        # "grads" without an index.
+        assert num_grads_uses >= len(used_grads_indices)
+        # Thus if the number is equal, every use of grads is also
+        # indexed.
+        only_used_grads_indices = num_grads_uses == len(used_grads_indices)
+
+        if uses_grad and num_grads_uses > 0:
+            raise RuntimeError(
+                f"Derivative definition of {defn_name} in derivatives.yaml illegally "
+                "mixes use of 'grad' and 'grads'. Consider replacing "
+                "occurrences of 'grad' with 'grads[0]'"
+            )
+
+        if only_used_grads_indices and set(used_grads_indices) == {0}:
+            raise RuntimeError(
+                f"Derivative definition of {defn_name} in derivatives.yaml solely "
+                "refers to 'grads[0]'.  If the first output is indeed the "
+                "only differentiable output, replace 'grads[0]' with 'grad'; "
+                "otherwise, there is a likely error in your derivatives "
+                "declaration."
+            )
+
+        if uses_named_grads and (uses_grad or num_grads_uses > 0):
+            raise RuntimeError(
+                f"Derivative definition of {defn_name} in derivatives.yaml illegally "
+                'mixes use of "grad_RETURN_NAME" and "grad" or "grads[x]". Use '
+                "only one method for identifying gradients."
+            )
+
+    @with_native_function
+    def set_up_derivatives(
+        f: NativeFunction,
+    ) -> tuple[
+        Sequence[Derivative],
+        Sequence[ForwardDerivative],
+        Sequence[Binding],
+        Sequence[str],
+        Sequence[str],
+    ]:
+        # Set up the derivative information
+        derivatives: list[Derivative] = []
+        forward_derivatives: list[ForwardDerivative] = []
+        non_differentiable_arg_names: list[str] = []
+        args_with_derivatives_set: set[str] = set()
+
+        all_arg_names = [a.name for a in cpp_arguments(f)]
+        all_ret_names = [
+            r.name for r in f.func.returns
+        ]  # only used for the assert below
+        # output_differentiability is captured from the enclosed
+        # scope. Don't modify it.
+        #
+        # If it is not present, then no output is explicitly
+        # undifferentiable.
+        #
+        # It may be present and shorter than the length of return
+        # values. If that's the case, any return value that does not
+        # have a corresponding entry is considered not differentiable.
+        differentiability = output_differentiability or [True] * len(f.func.returns)
+        # A return is available as a named gradient ...
+        available_named_gradients = [
+            f"grad_{ret.name}"
+            for ret, differentiable in zip(f.func.returns, differentiability)
+            # if it has not been explicitly made undifferentiable
+            if differentiable
+            # and if it has a name
+            and ret.name is not None
+            # and if its type is differentiable
+            and ret.type.is_tensor_like()
+        ]
+
+        for raw_names in sorted(defn.keys()):
+            formula = defn[raw_names]
+            names = split_names(raw_names)
+
+            for name in names:
+                assert not (name in all_arg_names and name in all_ret_names), (
+                    f"While processing the derivative formula for '{f.func.name}' wrt '{name}', "
+                    f"expected '{name}' to not be both an input arg and named return. "
+                )
+
+            if is_forward_derivative_definition(all_arg_names, names):
+                forward_derivatives.append(create_forward_derivative(f, formula, names))
+            else:
+                if formula.lower().strip() == "non_differentiable":
+                    non_differentiable_arg_names += names
+                else:
+                    derivative = create_derivative(
+                        f, formula, names, available_named_gradients
+                    )
+                    derivatives.append(derivative)
+                    args_with_derivatives_set |= set(names)
+
+        overlap = args_with_derivatives_set.intersection(non_differentiable_arg_names)
+        if overlap:
+            raise RuntimeError(
+                f"derivatives definition for {defn} have overlapped non_differentiable "
+                f"and differentiable variables: {overlap}"
+            )
+
+        # Next, let us determine the list of inputs in order.
+        # TODO: do we need eagerly calculate and save it here? Can it be derived
+        # from NativeFunction and `derivatives` on callsites instead?
+        args_with_derivatives = [
+            a for a in cpp_arguments(f) if a.name in args_with_derivatives_set
+        ]
+
+        # Postprocess forward derivatives definitions now that we know the differentiable arguments
+        forward_derivatives = postprocess_forward_derivatives(
+            f,
+            defn_name,
+            all_arg_names,
+            derivatives,
+            forward_derivatives,
+            args_with_derivatives,
+        )
+
+        # Test to see if the use of 'grads' makes sense.
+        check_grad_usage(defn_name, derivatives)
+
+        return (
+            derivatives,
+            forward_derivatives,
+            args_with_derivatives,
+            non_differentiable_arg_names,
+            available_named_gradients,
+        )
+
+    # NB: Removes 'name' from defn dictionary
+    specification = defn_dict.pop("name")
+    defn_name, _ = split_name_params(specification)
+    # NB: Removes 'output_differentiability' from defn dictionary
+    #     `None` means all differentiable.
+    output_differentiability = defn_dict.pop("output_differentiability", None)
+    output_differentiability_conditions = None
+    if output_differentiability and any(
+        isinstance(diff, str) for diff in output_differentiability
+    ):
+        if len(output_differentiability) != 1:
+            raise RuntimeError(
+                f"Not supported: for {specification},"
+                f"output_differentiability must either be "
+                f"list[bool] or a list[str] where each str is a "
+                f"condition. In the case where it is a condition, "
+                f"we only support single-output functions. "
+                f"Please file us an issue. "
+            )
+        output_differentiability_conditions = output_differentiability
+        output_differentiability = [True]
+
+    schema_function = functions_by_schema.get(specification)
+    if not schema_function:
+        avail = "\n".join(
+            k for k, v in functions_by_schema.items() if cpp.name(v.func) == defn_name
+        )
+        raise RuntimeError(
+            f"could not find ATen function for schema: {specification} "
+            f".  Available signatures:\n{avail}"
+        )
+
+    # now map this to the legacy schema; this isn't technically necessary, but we'd need some logic here
+    # to map in-place schemas to the out-of-place variants.
+    # TODO: maybe the logic to handle the legacy schema is no longer necessary?
+    signature = schema_function.func.signature()
+    functions = functions_by_signature[signature]
+    if len(functions) == 0:
+        avail = "\n".join(
+            str(k)
+            for k, v in functions_by_signature.items()
+            if cpp.name(k) == defn_name
+        )
+        raise RuntimeError(
+            f"could not find ATen function for legacy signature: {signature} "
+            f"corresponding to schema {specification}.  Please report a bug to PyTorch. "
+            f"Available signatures:\n{avail}"
+        )
+
+    canonical = canonical_function(functions, defn_name)
+    if "grad_input_mask" in (a.name for a in cpp_arguments(canonical)):
+        raise RuntimeError(
+            f"Schema for {defn_name} has an argument named grad_input_mask, "
+            "but this name would be shadowed by our codegen. "
+            "Please use a different name in native_functions.yaml."
+        )
+
+    if "result" in (a.name for a in cpp_arguments(canonical)):
+        raise RuntimeError(
+            f"Schema for {defn_name} has an argument named result, "
+            "but this is only allowed for outputs."
+            "Please use a different name in native_functions.yaml."
+        )
+
+    diffinfo_dict = {}
+    for key, defn in defn_dict["dispatch"].items():
+        if key != "Default" and key not in _VALID_AUTOGRAD_KEYS:
+            raise RuntimeError(
+                f"Invalid dispatch key {key} in derivatives.yaml for {specification},"
+                f" expected key to be one of {_VALID_AUTOGRAD_KEYS}"
+            )
+        if key not in used_dispatch_keys:
+            used_dispatch_keys.add(key)
+
+        (
+            derivatives,
+            forward_derivatives,
+            args_with_derivatives,
+            non_differentiable_arg_names,
+            available_named_gradients,
+        ) = set_up_derivatives(canonical)
+
+        used_named_gradients: set[str] = set()
+        for d in derivatives:
+            used_named_gradients |= d.named_gradients
+
+        # only assign an op name if we are actually going to calculate a derivative
+        op = None
+        if args_with_derivatives:
+            op_prefix = _create_op_prefix(defn_name)
+            if key != "Default":
+                op_prefix = op_prefix + key
+            op = f"{op_prefix}{op_counter[op_prefix]}"
+            op_counter[op_prefix] += 1
+
+        diffinfo_dict[key] = DifferentiabilityInfo(
+            name=defn_name,
+            func=canonical,
+            op=op,
+            derivatives=derivatives,
+            forward_derivatives=forward_derivatives,
+            all_saved_inputs=dedup_vars(
+                [v for d in derivatives for v in d.saved_inputs]
+            ),
+            all_saved_outputs=dedup_vars(
+                [v for d in derivatives for v in d.saved_outputs]
+            ),
+            available_named_gradients=available_named_gradients,
+            used_named_gradients=used_named_gradients,
+            args_with_derivatives=args_with_derivatives,
+            non_differentiable_arg_names=non_differentiable_arg_names,
+            output_differentiability=output_differentiability,
+            output_differentiability_conditions=output_differentiability_conditions,
+        )
+
+    return canonical.func, diffinfo_dict
+
+
+GRAD_INDEX_REGEX = r"(?:^|\W)grads\[(\d+)\]"
+
+
+def used_gradient_indices(formula: str) -> list[int]:
+    """Determine a list of gradient indices (the i in grads[i]) that
+    are used by the formula.
+
+    >>> used_gradient_indices("foo(grads[0], grads[1])")
+    [0, 1]
+    """
+    return [int(i) for i in re.findall(GRAD_INDEX_REGEX, formula)]
+
+
+def saved_variables(
+    formula: str,
+    nctypes: list[NamedCType],
+    var_names: tuple[str, ...],
+) -> tuple[str, tuple[SavedAttribute, ...]]:
+    def stride_expr(name: str) -> str:
+        assert var_names == (name,), (
+            'Replacement for ".strides()" is currently only supported for single derivatives of the same tensor '
+            'that ".strides()" is being called on.'
+        )
+        return f'strides_or_error({name}, "{name}")'
+
+    REPLACEMENTS: list[tuple[str, dict[str, Any]]] = [
+        # replace self.sym_sizes() with self_sym_sizes
+        (
+            r"{}.sym_sizes\(\)",
+            {
+                "suffix": "_sym_sizes",
+                "nctype": lambda name: NamedCType(name, BaseCType(symIntArrayRefT)),
+            },
+        ),
+        # replace self->sym_sizes() with self_sym_sizes_opt
+        (
+            r"{}->sym_sizes\(\)",
+            {
+                "suffix": "_sym_sizes_opt",
+                "nctype": lambda name: NamedCType(
+                    name, OptionalCType(BaseCType(symIntArrayRefT))
+                ),
+                "expr": lambda name: f"{name}.has_value() ? std::optional({name}->sym_sizes()) : std::nullopt",
+            },
+        ),
+        # replace self.sym_blocksize() with self_sym_blocksize_opt
+        (
+            r"{}.sym_blocksize\(\)",
+            {
+                "suffix": "_self_sym_blocksize_opt",
+                "nctype": lambda name: NamedCType(
+                    name, OptionalCType(BaseCType(symIntArrayRefT))
+                ),
+                "expr": lambda name: f"at::sparse_csr::getSymIntBlockSize({name})",
+            },
+        ),
+        # replace self.options() with self_options
+        (
+            r"{}.options\(\)",
+            {
+                "suffix": "_options",
+                "nctype": lambda name: NamedCType(name, BaseCType(tensorOptionsT)),
+            },
+        ),
+        # replace zeros_like(self) with self_info
+        (
+            r"zeros_like\({}\)",
+            {
+                "suffix": "_info",
+                "nctype": lambda name: NamedCType(name, BaseCType(typeAndSizeT)),
+                "expr": lambda name: name,  # at save-time
+                "res": lambda name: name + "_info.zeros()",  # at eval-time
+            },
+        ),
+        # replace self.sym_size(2) with self_sym_size_2
+        (
+            r"{}.sym_size\((-?\w+)\)",
+            {
+                "suffix": lambda m: f"_sym_argsize_{m.groups()[0].replace('-', 'minus_')}",
+                "nctype": lambda name: NamedCType(name, BaseCType(SymIntT)),
+            },
+        ),
+        # replace self.numel() with self_numel
+        (
+            r"{}.numel\(\)",
+            {
+                "suffix": "_numel",
+                "nctype": lambda name: NamedCType(name, BaseCType(longT)),
+            },
+        ),
+        # replace self.sym_numel() with self_sym_numel
+        (
+            r"{}.sym_numel\(\)",
+            {
+                "suffix": "_sym_numel",
+                "nctype": lambda name: NamedCType(name, BaseCType(SymIntT)),
+            },
+        ),
+        # replace to_args_sizes(self) with self_args_sizes
+        (
+            r"to_args_sizes\({}\)",
+            {
+                "suffix": "_args_sizes",
+                "nctype": lambda name: NamedCType(
+                    name, VectorCType(VectorCType(BaseCType(longT)))
+                ),
+            },
+        ),
+        # replace to_args_sizes_symint(self) with self_args_sizes
+        (
+            r"to_args_sizes_symint\({}\)",
+            {
+                "suffix": "_args_sizes_symint",
+                "nctype": lambda name: NamedCType(
+                    name, VectorCType(VectorCType(BaseCType(SymIntT)))
+                ),
+            },
+        ),
+        # replace to_args_scalartypes(self) with self_args_scalartypes
+        (
+            r"to_args_scalartypes\({}\)",
+            {
+                "suffix": "_args_scalartypes",
+                "nctype": lambda name: NamedCType(
+                    name, VectorCType(BaseCType(scalarTypeT))
+                ),
+            },
+        ),
+        # replace TensorGeometry(self) with self_geometry
+        (
+            r"TensorGeometry\({}\)",
+            {
+                "suffix": "_geometry",
+                "nctype": lambda name: NamedCType(name, BaseCType(tensorGeometryT)),
+            },
+        ),
+        (
+            r"{}.scalar_type\(\)",
+            {
+                "suffix": "_scalar_type",
+                "nctype": lambda name: NamedCType(name, BaseCType(scalarTypeT)),
+            },
+        ),
+        # replace self.dim() with self_dim
+        (
+            r"{}.dim\(\)",
+            {
+                "suffix": "_dim",
+                "nctype": lambda name: NamedCType(name, BaseCType(longT)),
+            },
+        ),
+        # replace self.sym_strides() with self_sym_strides
+        (
+            r"{}.sym_strides\(\)",
+            {
+                "suffix": "_sym_strides",
+                "nctype": lambda name: NamedCType(name, BaseCType(symIntArrayRefT)),
+                "expr": stride_expr,
+            },
+        ),
+        # replace self.layout() with self_layout
+        (
+            r"{}.layout\(\)",
+            {
+                "suffix": "_layout",
+                "nctype": lambda name: NamedCType(name, BaseCType(layoutT)),
+            },
+        ),
+        # replace self.is_conj() with self_conjugate
+        (
+            r"{}.is_conj\(\)",
+            {
+                "suffix": "_conjugate",
+                "nctype": lambda name: NamedCType(name, BaseCType(boolT)),
+            },
+        ),
+    ]
+
+    # find which arguments need to be saved
+    saved: list[SavedAttribute] = []
+
+    if ".sizes()" in formula or "->sizes()" in formula:
+        raise RuntimeError(
+            ".sizes() is not supported in derivative formulas. Instead, please use the SymInt version,"
+            + f".sym_sizes(), which returned a c10::SymIntArrayRef. formula={formula}"
+        )
+    if re.search(r"\.size\([-]?\d+\)", formula) or re.search(
+        r"->size\([-]?\d+\)", formula
+    ):
+        raise RuntimeError(
+            ".size(int) is not supported in derivative formulas. Instead, please use the SymInt version,"
+            + f".sym_size(int), which returned a c10::SymIntArrayRef. formula={formula}"
+        )
+    if ".strides()" in formula or "->strides()" in formula:
+        raise RuntimeError(
+            ".strides() is not supported in derivative formulas. Instead, please use the SymInt version,"
+            + f".sym_strides(), which returned a c10::SymIntArrayRef. formula={formula}"
+        )
+    for nctype in nctypes:
+        name = (
+            nctype.name.name if isinstance(nctype.name, SpecialArgName) else nctype.name
+        )
+        # First search the formula for expressions which can be evaluated
+        # when the autograd Function is created to avoid saving variables
+        for regex, info in REPLACEMENTS:
+
+            def repl(m: re.Match[str]) -> str:
+                suffix: str = (
+                    info["suffix"](m) if callable(info["suffix"]) else info["suffix"]
+                )
+                expr: str = info["expr"](name) if "expr" in info else m.group(0)
+                saved.append(
+                    SavedAttribute(
+                        nctype=info["nctype"](name + suffix),
+                        expr=expr,
+                    )
+                )
+                if "res" in info:
+                    replacement: str = info["res"](name)
+                    return replacement
+                return name + suffix
+
+            formula = re.sub(regex.format(name), repl, formula)
+
+        # std::optional types stored in Backward nodes must be
+        # converted to std::optional before being passed into
+        # the backward function
+        if nctype.type == OptionalCType(BaseCType(stringT)):
+            formula = re.sub(
+                rf"\b{name}\b",
+                f"{name}.has_value() ? std::optional({name}.value()) : std::nullopt",
+                formula,
+            )
+
+        # Find any variables which remain in the formula and save them
+        if re.search(IDENT_REGEX.format(name), formula):
+            saved.append(
+                SavedAttribute(
+                    nctype=nctype,
+                    expr=name,
+                )
+            )
+
+    return formula, tuple(saved)
+
+
+def _create_op_prefix(name: str) -> str:
+    r"""Takes a native function name converts to an op prefix name.
+
+    Note that the "name" parameter must be the native function name
+    without the optional variant suffix, so "add" instead of
+    "add.out".
+
+    OP names correspond to classes, hence the change to title case.
+
+    Example::
+
+        >>> _create_op_prefix("add")
+        'AddBackward'
+    """
+    camel_case = "".join([p.title() for p in name.split("_")])
+    return (camel_case + "Backward").replace("ForwardBackward", "Backward")
+
+
+def dedup_vars(vars: Sequence[SavedAttribute]) -> Sequence[SavedAttribute]:
+    seen: set[str] = set()
+    saved: list[SavedAttribute] = []
+    for var in vars:
+        name = (
+            var.nctype.name.name
+            if isinstance(var.nctype.name, SpecialArgName)
+            else var.nctype.name
+        )
+        if name in seen:
+            continue
+        seen.add(name)
+        saved.append(var)
+    return saved
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/ADInplaceOrViewType.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/ADInplaceOrViewType.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..e8276697eee065a36d1b16e583a5f011f92541c2
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/ADInplaceOrViewType.cpp
@@ -0,0 +1,38 @@
+#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
+#include "torch/csrc/autograd/VariableTypeUtils.h"
+#include "torch/csrc/autograd/generated/ViewFuncs.h"
+
+#include 
+#include 
+#include 
+
+// ${generated_comment}
+
+#ifndef AT_PER_OPERATOR_HEADERS
+#include 
+#else
+$ops_headers
+#endif
+
+using namespace at;
+using torch::autograd::CreationMeta;
+using torch::autograd::as_view;
+using torch::autograd::increment_version;
+
+namespace torch {
+
+namespace ADInplaceOrView {
+
+namespace {
+${inplace_or_view_method_definitions}
+}  // namespace
+}  // namespace ADInplaceOrView
+
+namespace {
+
+TORCH_LIBRARY_IMPL(aten, ADInplaceOrView, m) {
+  ${inplace_or_view_wrapper_registrations};
+}
+
+}  // namespace
+} // namespace torch
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/Functions.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/Functions.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..ba5cb3d912c5d7a3bbf31f4b0d38d4413dfc160c
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/Functions.cpp
@@ -0,0 +1,44 @@
+#include "torch/csrc/autograd/FunctionsManual.h"
+#include "torch/csrc/dynamo/compiled_autograd.h"
+
+// ${generated_comment}
+
+// The manual function definitions that used to be here are now in torch/csrc/autograd/FunctionsManual.cpp
+// This speeds up re-compilation and allow to share these implementations so that they can be
+// used for forward mode AD formulas as well.
+
+using namespace torch::autograd::generated::details;
+using at::Tensor;
+using at::Scalar;
+using at::IntArrayRef;
+using at::TensorList;
+
+namespace torch::autograd::generated {
+
+static at::IValue compute_output_metadata(const torch::autograd::edge_list& next_edges) {
+  auto output_metadata = torch::dynamo::autograd::IValuePacker<
+      std::vector>>::pack(
+              torch::dynamo::autograd::get_input_metadata(next_edges));
+  return output_metadata;
+}
+
+static C10_NOINLINE variable_list compiled_autograd_apply_functional(
+    const PackedArgs& packed_args,
+    const edge_list& next_edges,
+    SwapSavedVariables& saved,
+    const variable_list& grads,
+    const std::string& name) {
+  auto output_metadata = compute_output_metadata(next_edges);
+  const auto& pyinterface = torch::dynamo::autograd::getPyCompilerInterface();
+  return pyinterface->call_function(
+      saved.get_py_compiler(),
+      "apply_functional",
+      name,
+      grads,
+      packed_args.vec(),
+      output_metadata);
+}
+
+${autograd_function_definitions}
+
+} // namespace torch::autograd::generated
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/Functions.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/Functions.h
new file mode 100644
index 0000000000000000000000000000000000000000..911d7d905c002b29941167ccff112a8079d48266
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/Functions.h
@@ -0,0 +1,51 @@
+#pragma once
+
+// ${generated_comment}
+
+#include 
+#include 
+#include 
+
+#include "torch/csrc/autograd/function.h"
+#include "torch/csrc/autograd/variable.h"
+#include "torch/csrc/autograd/saved_variable.h"
+#include 
+
+#include 
+
+namespace torch { namespace autograd { namespace generated {
+
+using at::Scalar;
+using at::Tensor;
+using at::IntArrayRef;
+using at::ArrayRef;
+using at::Type;
+using at::TensorGeometry;
+using at::ScalarType;
+using std::optional;
+using c10::fmap;
+
+inline std::vector unpack_list(at::ArrayRef xs, std::shared_ptr saved_for = nullptr) {
+  // NB: we must explicitly do the conversion in the lambda, otherwise template
+  // deduction will give a Tensor of Variable which is not convertible
+  return fmap(xs, [&saved_for](const SavedVariable& x) {
+    // TODO(crcrpar): Use `std::move(saved_for)` to avoid incrementing refcount, which would need refactoring.
+    return static_cast(x.unpack(saved_for));
+  });
+}
+
+inline c10::List> unpack_opt_list(at::ArrayRef xs, std::shared_ptr saved_for = nullptr) {
+  torch::List> result;
+  result.reserve(xs.size());
+  for (const SavedVariable& v : xs) {
+    auto var = v.unpack(saved_for);
+    result.push_back(var.defined() ? std::optional(var) : ::std::nullopt);
+  }
+  return result;
+}
+
+using torch::autograd::TypeAndSize;
+
+${autograd_function_declarations}
+
+}}} // namespace torch::autograd::generated
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/TraceType.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/TraceType.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..fb5e7ae44a5353a3cc2a90858fe33b7fc0ef8bfd
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/TraceType.cpp
@@ -0,0 +1,40 @@
+#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
+#include "torch/csrc/jit/frontend/tracer.h"
+
+#include 
+
+#include "torch/csrc/autograd/function.h"
+
+#include "ATen/quantized/Quantizer.h"
+
+// ${generated_comment}
+
+// See the `Tracer` section in `torch/csrc/jit/OVERVIEW.md`.
+// NOTE See [Sharded File] comment in VariableType
+
+#ifndef AT_PER_OPERATOR_HEADERS
+#include 
+#else
+$ops_headers
+#endif
+
+using namespace at;
+
+namespace torch {
+
+namespace TraceType {
+
+namespace {
+${trace_method_definitions}
+}  // namespace
+}  // namespace TraceType
+
+namespace {
+
+TORCH_LIBRARY_IMPL(aten, Tracer, m) {
+  ${trace_wrapper_registrations};
+}
+
+}  // namespace
+
+} // namespace torch
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/VariableType.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/VariableType.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..23976a48473a350e0f7281641d73307d64c338b9
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/VariableType.cpp
@@ -0,0 +1,65 @@
+#include "torch/csrc/autograd/VariableTypeUtils.h"
+#include "torch/csrc/autograd/generated/VariableType.h"
+#include "torch/csrc/autograd/FunctionsManual.h"
+
+#include 
+#include 
+#include 
+#include 
+
+#include 
+
+
+// ${generated_comment}
+
+// NOTE [Sharded File]: on this file's split-into-shards state
+//
+// Back in the good old days, VariableType.cpp was generated as one
+// file with every function in it, and everything was great and
+// simple.
+//
+// However, this file was also very large (over 36,000 lines), and
+// compiling it was very slow, and in fact was a significant
+// bottleneck for incremental rebuilds. To address this, we now
+// generate the file split across multiple shards, named
+// VariableType_0.cpp and so on, which can be compiled in parallel.
+//
+// For ease of inspection and debugging, so that it's not necessary to
+// go rooting around in multiple files, we also generate all the
+// functions together in VariableTypeEverything.cpp. This generated
+// file is only for convenience; it's not actually used in the
+// build. If the file you're looking at now is one of the shards, you
+// may want to switch over to the Everything variant to make you
+// grepping smoother.
+
+using namespace at;
+using namespace torch::autograd::generated;
+using namespace torch::autograd::generated::details;
+
+
+namespace torch::autograd {
+
+namespace VariableType {
+namespace{
+[[maybe_unused]] void reset_grad_accumulator(Variable& self) {
+  AutogradMeta* meta = torch::autograd::impl::get_autograd_meta(self);
+  if (meta != nullptr) {
+    meta->grad_accumulator_.reset();
+  }
+}
+}
+
+namespace {
+
+
+${type_derived_method_definitions}
+}
+}
+
+namespace {
+
+${wrapper_registrations}
+
+}
+
+} // namespace torch::autograd
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/VariableType.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/VariableType.h
new file mode 100644
index 0000000000000000000000000000000000000000..02959757e5c007a7d54526dc2ca18698748e95f1
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/VariableType.h
@@ -0,0 +1,55 @@
+#pragma once
+
+// ${generated_comment}
+
+#include 
+#include 
+
+#include 
+
+#include 
+#include 
+
+#include  // for size_t
+#include  // for function
+#include  // for unique_ptr
+#include 
+#include 
+
+namespace at {
+  struct Quantizer;
+}
+
+namespace torch { namespace autograd {
+
+using Variable = at::Tensor;
+using at::Context;
+using at::Device;
+using at::Dimname;
+using at::DimnameList;
+using at::Generator;
+using at::IntArrayRef;
+using at::MemoryFormat;
+using at::QScheme;
+using at::Scalar;
+using at::ScalarType;
+using at::Storage;
+using at::Tensor;
+using at::TensorList;
+using at::TensorOptions;
+using at::Quantizer;
+using std::optional;
+
+namespace VariableType {
+  TORCH_API std::vector allCUDATypes();
+  TORCH_API std::vector allXPUTypes();
+  TORCH_API std::vector allCPUTypes();
+  TORCH_API std::vector allPrivateUser1Types();
+
+  at::Tensor & unpack(Tensor & t, const char * name, int pos);
+  const at::Tensor & unpack(const Tensor & t, const char * name, int pos);
+  at::Tensor unpack_opt(const Tensor & t, const char * name, int pos);
+  std::vector unpack(const at::ITensorListRef& tl, const char *name, int pos);
+}
+
+}} // namespace torch::autograd
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/ViewFuncs.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/ViewFuncs.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..11b9b194fb46f924e863c4c1dab5cbb8dbb0601b
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/ViewFuncs.cpp
@@ -0,0 +1,14 @@
+#include 
+
+// ${generated_comment}
+
+using at::Tensor;
+using at::Scalar;
+using at::IntArrayRef;
+using at::TensorList;
+
+namespace torch::autograd::generated {
+
+${view_func_definitions}
+
+} // namespace torch::autograd::generated
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/ViewFuncs.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/ViewFuncs.h
new file mode 100644
index 0000000000000000000000000000000000000000..1f69c062d344e4cd5f98cf5f34fd4278019fdf8a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/ViewFuncs.h
@@ -0,0 +1,28 @@
+#pragma once
+
+// ${generated_comment}
+
+#include 
+#include 
+#include 
+
+#ifndef AT_PER_OPERATOR_HEADERS
+#include 
+#else
+$ops_headers
+#endif
+
+namespace torch::autograd::generated {
+
+using at::Scalar;
+using at::Tensor;
+using at::IntArrayRef;
+using at::ArrayRef;
+using at::Type;
+using at::ScalarType;
+using std::optional;
+using c10::fmap;
+
+${view_func_declarations}
+
+} // namespace torch::autograd::generated
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/annotated_fn_args.py.in b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/annotated_fn_args.py.in
new file mode 100644
index 0000000000000000000000000000000000000000..1012c008451745b8f1ed1454a864f666caf2618a
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/annotated_fn_args.py.in
@@ -0,0 +1,11 @@
+"""
+This file is needed for generating procedural tests required for
+testing __torch_function__. See tests/test_overrides.py.
+"""
+
+# flake8: noqa
+import torch
+
+annotated_args = {
+${annotated_args}
+}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_enum_tag.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_enum_tag.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..83cfad1d7ba4d6fc3529caf78e036c5883e7bc23
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_enum_tag.cpp
@@ -0,0 +1,15 @@
+#include 
+#include 
+#include 
+#include 
+
+namespace py = pybind11;
+namespace torch {
+    namespace autograd {
+    void initEnumTag(PyObject* module) {
+        auto m = py::handle(module).cast();
+        py::enum_(m, "Tag")
+        ${enum_of_valid_tags};
+        m.doc() = "An Enum that contains tags that can be assigned to an operator registered in C++.";
+    }
+}}
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_fft_functions.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_fft_functions.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..71ac4e2226d2db418eba5690995424d3f007e620
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_fft_functions.cpp
@@ -0,0 +1,81 @@
+#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
+// ${generated_comment}
+
+#include "torch/csrc/Device.h"
+#include "torch/csrc/DynamicTypes.h"
+#include "torch/csrc/Exceptions.h"
+#include "torch/csrc/autograd/python_fft_functions.h"
+#include "torch/csrc/autograd/generated/python_return_types.h"
+#include "torch/csrc/autograd/python_variable.h"
+#include "torch/csrc/autograd/utils/wrap_outputs.h"
+#include "torch/csrc/autograd/utils/python_arg_parsing.h"
+#include "torch/csrc/autograd/generated/variable_factories.h"
+#include "torch/csrc/utils/out_types.h"
+#include "torch/csrc/utils/pycfunction_helpers.h"
+#include "torch/csrc/utils/python_arg_parser.h"
+#include "torch/csrc/utils/structseq.h"
+#include "torch/csrc/utils/device_lazy_init.h"
+
+#include 
+
+#ifndef AT_PER_OPERATOR_HEADERS
+#include 
+#else
+$ops_headers
+#endif
+
+using at::Tensor;
+using at::Device;
+using at::Layout;
+using at::Scalar;
+using at::ScalarType;
+using at::Backend;
+using at::OptionalDeviceGuard;
+using at::DeviceGuard;
+using at::TensorOptions;
+using at::IntArrayRef;
+using at::Generator;
+using at::TensorList;
+using at::Dimname;
+using at::DimnameList;
+
+using torch::utils::check_out_type_matches;
+using namespace torch::autograd::utils;
+
+namespace torch::autograd {
+
+// generated forward declarations start here
+
+${py_forwards}
+
+static PyMethodDef fft_functions[] = {
+  ${py_method_defs}
+  {NULL}
+};
+
+static PyObject* THPFFTVariableFunctionsModule = NULL;
+
+void initFFTFunctions(PyObject* module) {
+  static struct PyModuleDef def = {
+     PyModuleDef_HEAD_INIT,
+     "torch._C._fft",
+     NULL,
+     -1,
+     fft_functions
+  };
+  PyObject* fft = PyModule_Create(&def);
+  THPFFTVariableFunctionsModule = fft;
+  if (!fft) {
+    throw python_error();
+  }
+  // steals a reference to fft
+  if (PyModule_AddObject(module, "_fft", fft) != 0) {
+    throw python_error();
+  }
+}
+
+// generated methods start here
+
+${py_methods}
+
+} // namespace torch::autograd
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_functions.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_functions.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..1522d6cd0f5a2a1fc0188bf9d6d0d59fe1b27d85
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_functions.cpp
@@ -0,0 +1,37 @@
+#include 
+
+// ${generated_comment}
+
+#include 
+#include 
+
+#include 
+#include "torch/csrc/autograd/generated/Functions.h"
+#include "torch/csrc/autograd/python_cpp_function.h"
+#include 
+#include 
+#include 
+#include 
+#include 
+
+// NOTE: See [Sharded File] comment in VariableType
+
+namespace torch::autograd::generated {
+
+template
+static void addClass(PyObject* module, PyTypeObject& type, const char* name,
+  PyGetSetDef* function_properties=NULL, PyMethodDef* function_methods=NULL)
+{
+  _initFunctionPyTypeObject(type, name, function_properties, function_methods);
+  Py_INCREF(&type);
+  PyModule_AddObject(module, name, (PyObject*)&type);
+  registerCppFunction(typeid(C), &type);
+}
+
+${py_function_props_and_getters}
+
+void initialize_autogenerated_functions${shard_id}(PyObject* module) {
+  ${py_function_initializers}
+}
+
+} // namespace torch::autograd::generated
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_functions.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_functions.h
new file mode 100644
index 0000000000000000000000000000000000000000..22e37207e219431100fefaf21b02e3ed0f63d956
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_functions.h
@@ -0,0 +1,17 @@
+#pragma once
+
+#include 
+
+// ${generated_comment}
+
+// Python bindings for automatically generated autograd functions
+
+namespace torch { namespace autograd { namespace generated {
+
+${shard_forward_declare}
+
+inline void initialize_autogenerated_functions(PyObject* module) {
+  ${shard_call}
+}
+
+}}} // namespace torch::autograd::generated
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_linalg_functions.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_linalg_functions.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..c93752a3ddbfcf111426f98c3ea68fc625e94def
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_linalg_functions.cpp
@@ -0,0 +1,68 @@
+#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
+// ${generated_comment}
+
+#include "torch/csrc/Device.h"
+#include "torch/csrc/DynamicTypes.h"
+#include "torch/csrc/Exceptions.h"
+#include "torch/csrc/autograd/python_linalg_functions.h"
+#include "torch/csrc/autograd/generated/python_return_types.h"
+#include "torch/csrc/autograd/python_variable.h"
+#include "torch/csrc/autograd/utils/wrap_outputs.h"
+#include "torch/csrc/autograd/utils/python_arg_parsing.h"
+#include "torch/csrc/utils/pycfunction_helpers.h"
+#include "torch/csrc/utils/python_arg_parser.h"
+#include "torch/csrc/utils/structseq.h"
+
+#ifndef AT_PER_OPERATOR_HEADERS
+#include 
+#else
+$ops_headers
+#endif
+
+using at::Tensor;
+using at::Scalar;
+using at::ScalarType;
+using at::MemoryFormat;
+using at::Generator;
+using at::IntArrayRef;
+using at::TensorList;
+
+using namespace torch::autograd::utils;
+
+namespace torch::autograd {
+
+// generated forward declarations start here
+
+${py_forwards}
+
+static PyMethodDef linalg_functions[] = {
+  ${py_method_defs}
+  {NULL}
+};
+
+static PyObject* THPLinalgVariableFunctionsModule = NULL;
+
+void initLinalgFunctions(PyObject* module) {
+  static struct PyModuleDef def = {
+     PyModuleDef_HEAD_INIT,
+     "torch._C._linalg",
+     NULL,
+     -1,
+     linalg_functions
+  };
+  PyObject* linalg = PyModule_Create(&def);
+  THPLinalgVariableFunctionsModule = linalg;
+  if (!linalg) {
+    throw python_error();
+  }
+  // steals a reference to linalg
+  if (PyModule_AddObject(module, "_linalg", linalg) != 0) {
+    throw python_error();
+  }
+}
+
+// generated methods start here
+
+${py_methods}
+
+} // namespace torch::autograd
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_nested_functions.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_nested_functions.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..3acb5128cee1e180de887080106e7cf5559f15ee
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_nested_functions.cpp
@@ -0,0 +1,81 @@
+#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
+// ${generated_comment}
+
+#include "torch/csrc/Device.h"
+#include "torch/csrc/DynamicTypes.h"
+#include "torch/csrc/Exceptions.h"
+#include "torch/csrc/autograd/python_nested_functions.h"
+#include "torch/csrc/autograd/generated/python_return_types.h"
+#include "torch/csrc/autograd/python_variable.h"
+#include "torch/csrc/autograd/utils/wrap_outputs.h"
+#include "torch/csrc/autograd/utils/python_arg_parsing.h"
+#include "torch/csrc/autograd/generated/variable_factories.h"
+#include "torch/csrc/utils/out_types.h"
+#include "torch/csrc/utils/pycfunction_helpers.h"
+#include "torch/csrc/utils/python_arg_parser.h"
+#include "torch/csrc/utils/structseq.h"
+#include "torch/csrc/utils/device_lazy_init.h"
+
+#ifndef AT_PER_OPERATOR_HEADERS
+#include 
+#else
+$ops_headers
+#endif
+
+using at::Tensor;
+using at::Device;
+using at::Layout;
+using at::Scalar;
+using at::ScalarType;
+using at::Backend;
+using at::OptionalDeviceGuard;
+using at::DeviceGuard;
+using at::TensorOptions;
+using at::IntArrayRef;
+using at::OptionalIntArrayRef;
+using at::Generator;
+using at::TensorList;
+using at::Dimname;
+using at::DimnameList;
+
+using namespace torch::autograd::utils;
+
+namespace torch::autograd {
+
+// generated forward declarations start here
+
+${py_forwards}
+
+static PyMethodDef nested_functions[] = {
+  {NULL, NULL, 0, NULL},
+  ${py_method_defs}
+  {NULL}
+};
+
+static PyObject* THPNestedVariableFunctionsModule = NULL;
+
+void initNestedFunctions(PyObject* module) {
+  nested_functions[0] = get_nested_functions_manual()[0];
+  static struct PyModuleDef def = {
+     PyModuleDef_HEAD_INIT,
+     "torch._C._nested",
+     NULL,
+     -1,
+     nested_functions
+  };
+  PyObject* nested = PyModule_Create(&def);
+  THPNestedVariableFunctionsModule = nested;
+  if (!nested) {
+    throw python_error();
+  }
+  // steals a reference to nested
+  if (PyModule_AddObject(module, "_nested", nested) != 0) {
+    throw python_error();
+  }
+}
+
+// generated methods start here
+
+${py_methods}
+
+} // namespace torch::autograd
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_nn_functions.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_nn_functions.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..8eabb0da2332283a02e98e54dd0a277a83a55ad6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_nn_functions.cpp
@@ -0,0 +1,113 @@
+#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
+// ${generated_comment}
+
+#include "torch/csrc/Device.h"
+#include "torch/csrc/DynamicTypes.h"
+#include "torch/csrc/Exceptions.h"
+#include "torch/csrc/autograd/python_nn_functions.h"
+#include "torch/csrc/autograd/generated/python_return_types.h"
+#include "torch/csrc/autograd/python_variable.h"
+#include "torch/csrc/autograd/utils/wrap_outputs.h"
+#include "torch/csrc/autograd/utils/python_arg_parsing.h"
+#include "torch/csrc/utils/pycfunction_helpers.h"
+#include "torch/csrc/utils/python_arg_parser.h"
+#include "torch/csrc/utils/structseq.h"
+#include "torch/csrc/utils/tensor_memoryformats.h"
+
+#ifndef AT_PER_OPERATOR_HEADERS
+#include 
+#else
+$ops_headers
+#endif
+
+using at::Tensor;
+using at::Scalar;
+using at::MemoryFormat;
+using at::Generator;
+using at::IntArrayRef;
+using at::ArrayRef;
+
+using namespace torch::autograd::utils;
+
+namespace torch::autograd {
+
+static PyObject* THPNNVariableFunctionsModule = nullptr;
+
+static PyObject * THPVariable__parse_to(PyObject* module, PyObject* args, PyObject* kwargs)
+{
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "to(Device device=None, ScalarType dtype=None, bool non_blocking=False, bool copy=False, *, MemoryFormat? memory_format=None)",
+    "to(ScalarType dtype, bool non_blocking=False, bool copy=False, *, MemoryFormat? memory_format=None)",
+    "to(Tensor tensor, bool non_blocking=False, bool copy=False, *, MemoryFormat? memory_format=None)",
+  });
+  ParsedArgs<5> parsed_args;
+  auto r = parser.parse(args, kwargs, parsed_args);
+  if (r.has_torch_function()) {
+    return handle_torch_function(r, args, kwargs, THPNNVariableFunctionsModule, "torch.nn", "_parse_to");
+  }
+  auto parsed = parse_to_conversion(r, /*allow_copy*/ false); // we don't want copy for nn.Module.to
+  auto& device = std::get<0>(parsed);
+  auto& scalarType = std::get<1>(parsed);
+  auto non_blocking = std::get<2>(parsed);
+  auto opt_memory_format = std::get<4>(parsed);
+  auto tuple = THPObjectPtr{PyTuple_New(4)};
+  if (!tuple) throw python_error();
+  if (device) {
+    PyTuple_SET_ITEM(tuple.get(), 0, THPDevice_New(*device));
+  } else {
+    Py_INCREF(Py_None);
+    PyTuple_SET_ITEM(tuple.get(), 0, Py_None);
+  }
+  if (scalarType) {
+    PyTuple_SET_ITEM(tuple.get(), 1, Py_NewRef(torch::getTHPDtype(*scalarType)));
+  } else {
+    Py_INCREF(Py_None);
+    PyTuple_SET_ITEM(tuple.get(), 1, Py_None);
+  }
+  PyTuple_SET_ITEM(tuple.get(), 2, torch::autograd::utils::wrap(non_blocking));
+  if (opt_memory_format.has_value()) {
+    PyTuple_SET_ITEM(tuple.get(), 3, Py_NewRef(torch::utils::getTHPMemoryFormat(opt_memory_format.value())));
+  } else {
+    Py_INCREF(Py_None);
+    PyTuple_SET_ITEM(tuple.get(), 3, Py_None);
+  }
+  return tuple.release();
+  END_HANDLE_TH_ERRORS
+}
+
+// generated forward declarations start here
+
+${py_forwards}
+
+static PyMethodDef nn_functions[] = {
+  {"_parse_to", castPyCFunctionWithKeywords(THPVariable__parse_to),
+    METH_VARARGS | METH_KEYWORDS, nullptr},
+  ${py_method_defs}
+  {nullptr}
+};
+
+void initNNFunctions(PyObject* module) {
+  static struct PyModuleDef def = {
+     PyModuleDef_HEAD_INIT,
+     "torch._C._nn",
+     nullptr,
+     -1,
+     nn_functions
+  };
+  PyObject* nn = PyModule_Create(&def);
+  THPNNVariableFunctionsModule = nn;
+  if (!nn) {
+    throw python_error();
+  }
+  // steals a reference to nn
+  if (PyModule_AddObject(module, "_nn", nn) != 0) {
+    throw python_error();
+  }
+}
+
+// generated methods start here
+
+${py_methods}
+
+} // namespace torch::autograd
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_return_types.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_return_types.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..139e6b8958336cfcc8328fa33581e9f1ab6d5532
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_return_types.cpp
@@ -0,0 +1,52 @@
+#include 
+
+#include 
+#include 
+#include 
+
+#include "torch/csrc/autograd/generated/python_return_types.h"
+#include "torch/csrc/utils/structseq.h"
+#include "torch/csrc/Exceptions.h"
+
+namespace torch { namespace autograd { namespace generated {
+
+${py_return_types}
+
+}}}
+
+namespace torch::autograd {
+
+static void addReturnType(
+    PyObject* module,
+    const char* name,
+    PyTypeObject* type) {
+  // hold onto the TypeObject for the unlikely case of user
+  // deleting or overriding it.
+  Py_INCREF(type);
+  if (PyModule_AddObject(
+          module,
+          name,
+          (PyObject*)type) != 0) {
+    Py_DECREF(type);
+    throw python_error();
+  }
+}
+
+void initReturnTypes(PyObject* module) {
+  static struct PyModuleDef def = {
+      PyModuleDef_HEAD_INIT, "torch._C._return_types", nullptr, -1, {}};
+  PyObject* return_types_module = PyModule_Create(&def);
+  if (!return_types_module) {
+    throw python_error();
+  }
+
+  ${py_return_types_registrations}
+
+  // steals a reference to return_types on success
+  if (PyModule_AddObject(module, "_return_types", return_types_module) != 0) {
+    Py_DECREF(return_types_module);
+    throw python_error();
+  }
+}
+
+} // namespace torch::autograd
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_return_types.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_return_types.h
new file mode 100644
index 0000000000000000000000000000000000000000..ce6c355ea146a272709255b898603764112168b9
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_return_types.h
@@ -0,0 +1,14 @@
+#pragma once
+
+namespace torch {
+namespace autograd {
+namespace generated {
+
+${py_return_types_declarations}
+
+}
+
+void initReturnTypes(PyObject* module);
+
+} // namespace autograd
+} // namespace torch
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_sparse_functions.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_sparse_functions.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..648d91442102e9b950cb2ddb8db545c4b4e1100e
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_sparse_functions.cpp
@@ -0,0 +1,67 @@
+#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
+// ${generated_comment}
+
+#include "torch/csrc/Device.h"
+#include "torch/csrc/DynamicTypes.h"
+#include "torch/csrc/Exceptions.h"
+#include "torch/csrc/autograd/python_sparse_functions.h"
+#include "torch/csrc/autograd/python_variable.h"
+#include "torch/csrc/autograd/utils/wrap_outputs.h"
+#include "torch/csrc/autograd/utils/python_arg_parsing.h"
+#include "torch/csrc/utils/pycfunction_helpers.h"
+#include "torch/csrc/utils/python_arg_parser.h"
+#include "torch/csrc/utils/structseq.h"
+
+#ifndef AT_PER_OPERATOR_HEADERS
+#include 
+#else
+$ops_headers
+#endif
+
+using at::Tensor;
+using at::Scalar;
+using at::ScalarType;
+using at::MemoryFormat;
+using at::Generator;
+using at::IntArrayRef;
+using at::TensorList;
+
+using namespace torch::autograd::utils;
+
+namespace torch::autograd {
+
+// generated forward declarations start here
+
+${py_forwards}
+
+static PyMethodDef sparse_functions[] = {
+  ${py_method_defs}
+  {NULL}
+};
+
+static PyObject* THPSparseVariableFunctionsModule = NULL;
+
+void initSparseFunctions(PyObject* module) {
+  static struct PyModuleDef def = {
+     PyModuleDef_HEAD_INIT,
+     "torch._C._sparse",
+     NULL,
+     -1,
+     sparse_functions
+  };
+  PyObject* sparse = PyModule_Create(&def);
+  THPSparseVariableFunctionsModule = sparse;
+  if (!sparse) {
+    throw python_error();
+  }
+  // steals a reference to sparse
+  if (PyModule_AddObject(module, "_sparse", sparse) != 0) {
+    throw python_error();
+  }
+}
+
+// generated methods start here
+
+${py_methods}
+
+} // namespace torch::autograd
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_special_functions.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_special_functions.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..bf9e109b4a77352cd85ba828b97d67d329543867
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_special_functions.cpp
@@ -0,0 +1,79 @@
+#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
+// ${generated_comment}
+
+#include "torch/csrc/Device.h"
+#include "torch/csrc/DynamicTypes.h"
+#include "torch/csrc/Exceptions.h"
+#include "torch/csrc/autograd/python_special_functions.h"
+#include "torch/csrc/autograd/generated/python_return_types.h"
+#include "torch/csrc/autograd/python_variable.h"
+#include "torch/csrc/autograd/utils/wrap_outputs.h"
+#include "torch/csrc/autograd/utils/python_arg_parsing.h"
+#include "torch/csrc/autograd/generated/variable_factories.h"
+#include "torch/csrc/utils/out_types.h"
+#include "torch/csrc/utils/pycfunction_helpers.h"
+#include "torch/csrc/utils/python_arg_parser.h"
+#include "torch/csrc/utils/structseq.h"
+#include "torch/csrc/utils/device_lazy_init.h"
+
+#ifndef AT_PER_OPERATOR_HEADERS
+#include 
+#else
+$ops_headers
+#endif
+
+using at::Tensor;
+using at::Device;
+using at::Layout;
+using at::Scalar;
+using at::ScalarType;
+using at::Backend;
+using at::OptionalDeviceGuard;
+using at::DeviceGuard;
+using at::TensorOptions;
+using at::IntArrayRef;
+using at::Generator;
+using at::TensorList;
+using at::Dimname;
+using at::DimnameList;
+
+using torch::utils::check_out_type_matches;
+using namespace torch::autograd::utils;
+
+namespace torch::autograd {
+
+// generated forward declarations start here
+
+${py_forwards}
+
+static PyMethodDef special_functions[] = {
+  ${py_method_defs}
+  {NULL}
+};
+
+static PyObject* THPSpecialVariableFunctionsModule = NULL;
+
+void initSpecialFunctions(PyObject* module) {
+  static struct PyModuleDef def = {
+     PyModuleDef_HEAD_INIT,
+     "torch._C._special",
+     NULL,
+     -1,
+     special_functions
+  };
+  PyObject* special = PyModule_Create(&def);
+  THPSpecialVariableFunctionsModule = special;
+  if (!special) {
+    throw python_error();
+  }
+  // steals a reference to special
+  if (PyModule_AddObject(module, "_special", special) != 0) {
+    throw python_error();
+  }
+}
+
+// generated methods start here
+
+${py_methods}
+
+} // namespace torch::autograd
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_torch_functions.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_torch_functions.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..c17d1040e1892b6a215a8c4264fe5a5345265bc7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_torch_functions.cpp
@@ -0,0 +1,93 @@
+#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
+// ${generated_comment}
+
+// Python bindings for torch.* functions implemented through ATen.
+//
+// The functions are bound as static methods on a class
+// torch._C._VariableFunctions which is also aliased as Variable._torch
+// and also copied into 'torch' module.
+
+#include 
+
+// Undefine the copysign macro so that at::copysign works as intended with MSVC
+// https://github.com/python/cpython/blob/c60394c7fc9cc09b16e9675a3eeb5844b6d8523f/PC/pyconfig.h#L196
+#ifdef _MSC_VER
+#undef copysign
+#endif // _MSC_VER
+
+#include "torch/csrc/autograd/python_torch_functions.h"
+#include "torch/csrc/autograd/python_variable.h"
+#include "torch/csrc/autograd/utils/wrap_outputs.h"
+#include "torch/csrc/Dtype.h"
+#include "torch/csrc/DynamicTypes.h"
+#include "torch/csrc/Exceptions.h"
+#include "torch/csrc/utils/out_types.h"
+#include "torch/csrc/utils/pybind.h"
+#include "torch/csrc/utils/pycfunction_helpers.h"
+#include "torch/csrc/utils/python_arg_parser.h"
+#include "torch/csrc/utils/tensor_layouts.h"
+#include "torch/csrc/utils/tensor_new.h"
+#include "torch/csrc/utils/tensor_numpy.h"
+#include "torch/csrc/jit/frontend/tracer.h"
+#include "torch/csrc/autograd/generated/variable_factories.h"
+#include "torch/csrc/utils/structseq.h"
+#include "torch/csrc/utils/device_lazy_init.h"
+#include "torch/csrc/autograd/generated/python_return_types.h"
+
+#include 
+
+#ifndef AT_PER_OPERATOR_HEADERS
+#include 
+#else
+$ops_headers
+#endif
+
+#include 
+#include 
+#include 
+#include 
+
+using at::Tensor;
+using at::Device;
+using at::Layout;
+using at::Scalar;
+using at::ScalarType;
+using at::Backend;
+using at::OptionalDeviceGuard;
+using at::DeviceGuard;
+using at::TensorOptions;
+using at::IntArrayRef;
+using at::Generator;
+using at::TensorList;
+using at::Dimname;
+using at::DimnameList;
+using at::ArrayRef;
+
+using torch::utils::check_out_type_matches;
+using namespace torch::autograd::utils;
+
+// NOTE: See [Sharded File] comment in VariableType
+
+namespace torch::autograd {
+
+// generated forward declarations start here
+
+${py_forwards}
+
+static PyMethodDef torch_functions_shard[] = {
+  ${py_method_defs}
+};
+
+void gatherTorchFunctions${shard_id}(std::vector &torch_functions) {
+  constexpr size_t num_functions = sizeof(torch_functions_shard) / sizeof(torch_functions_shard[0]);
+  torch_functions.insert(
+    torch_functions.end(),
+    torch_functions_shard,
+    torch_functions_shard + num_functions);
+}
+
+// generated methods start here
+
+${py_methods}
+
+} // namespace torch::autograd
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_variable_methods.cpp b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_variable_methods.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..bfc5b80835c4b203d96ea3a1952ae2fba897edf3
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/python_variable_methods.cpp
@@ -0,0 +1,1338 @@
+#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
+// ${generated_comment}
+
+#include 
+
+// Undefine the copysign macro so that at::copysign works as intended with MSVC
+// https://github.com/python/cpython/blob/c60394c7fc9cc09b16e9675a3eeb5844b6d8523f/PC/pyconfig.h#L196
+#ifdef _MSC_VER
+#undef copysign
+#endif // _MSC_VER
+
+#include "torch/csrc/DynamicTypes.h"
+#include "torch/csrc/Exceptions.h"
+#include "torch/csrc/Size.h"
+#include "torch/csrc/autograd/generated/VariableType.h"
+#include "torch/csrc/autograd/python_variable.h"
+#include "torch/csrc/autograd/utils/python_arg_parsing.h"
+#include "torch/csrc/autograd/utils/error_messages.h"
+#include "torch/csrc/autograd/utils/wrap_outputs.h"
+#include "torch/csrc/jit/frontend/tracer.h"
+#ifdef USE_CUDA
+#include "torch/csrc/cuda/Event.h"
+#endif
+#include "torch/csrc/utils/device_lazy_init.h"
+#include 
+#include "torch/csrc/utils/object_ptr.h"
+#include "torch/csrc/utils/pycfunction_helpers.h"
+#include "torch/csrc/utils/python_arg_parser.h"
+#include "torch/csrc/utils/python_numbers.h"
+#include "torch/csrc/utils/python_strings.h"
+#include "torch/csrc/utils/tensor_apply.h"
+#include "torch/csrc/utils/tensor_list.h"
+#include "torch/csrc/utils/tensor_new.h"
+#include "torch/csrc/utils/tensor_numpy.h"
+#include "torch/csrc/utils/tensor_types.h"
+#include "torch/csrc/autograd/generated/python_return_types.h"
+
+#include 
+#include 
+#include 
+#include "c10/core/Stream.h"
+
+#include 
+#include 
+
+#ifndef AT_PER_OPERATOR_HEADERS
+#include 
+#else
+$ops_headers
+#include 
+#endif
+
+using at::device_of;
+using at::OptionalDeviceGuard;
+using at::Scalar;
+using at::ScalarType;
+using at::Tensor;
+using c10::Stream;
+using namespace torch::autograd::utils;
+
+namespace torch::autograd {
+
+static PyObject * THPVariable__is_view(PyObject *self, PyObject* args)
+{
+  HANDLE_TH_ERRORS
+  if (check_has_torch_function(self)) {
+    return handle_torch_function(self, "_is_view", args);
+  }
+  auto& self_ = THPVariable_Unpack(self);
+  if (self_.is_view()) {
+    Py_RETURN_TRUE;
+  } else {
+    Py_RETURN_FALSE;
+  }
+  END_HANDLE_TH_ERRORS
+}
+
+// implemented on the python object bc no support for first-class functions in native_functions.yaml
+// See: ATen/native/README.md for more context
+static PyObject * THPVariable_apply_(PyObject* self, PyObject* arg)
+{
+  HANDLE_TH_ERRORS
+  if (check_has_torch_function(self)) {
+    auto args = py::make_tuple(py::handle(arg));
+    return handle_torch_function(self, "apply_", args.ptr());
+  }
+  auto& self_ = THPVariable_Unpack(self);
+  if (self_.requires_grad()) {
+    throw std::runtime_error(
+        "Can't call apply_() on Variable that requires grad. Use "
+        "var.detach().apply_() instead.");
+  }
+  return THPVariable_Wrap(torch::utils::apply_(self_, arg));
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_size(PyObject* self, PyObject* args, PyObject* kwargs)
+{
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "size(int64_t? dim=None)",
+    "size(Dimname dim)",
+  });
+  auto& self_ = THPVariable_Unpack(self);
+  ParsedArgs<3> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+  if (r.idx == 0) {
+    if (!r.toInt64Optional(0).has_value()) {
+      return THPSize_NewFromSymSizes(self_);
+    }
+    if (jit::tracer::isTracing()) {
+      // will error out if a tensor has symints
+      return wrap(jit::tracer::getSizeOf(self_, r.toInt64(0)));
+    } else {
+      return torch::toPyObject(self_.sym_size(r.toInt64(0)));
+    }
+  } else if (r.idx == 1) {
+    if (jit::tracer::isTracing()) {
+      TORCH_INTERNAL_ASSERT(false, "NYI: Named tensors w/ JIT");
+    }
+    return wrap(self_.size(r.dimname(0)));
+  }
+  Py_RETURN_NONE;
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_stride(PyObject* self, PyObject* args, PyObject* kwargs)
+{
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "stride(int64_t? dim=None)",
+    "stride(Dimname dim)",
+  });
+  auto& self_ = THPVariable_Unpack(self);
+  ParsedArgs<3> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  if (r.idx == 0) {
+    if (r.toInt64Optional(0).has_value()) {
+      return torch::toPyObject(self_.sym_stride(r.toInt64(0)));
+    }
+    // yes, this is called strides in ATen.
+    at::SymIntArrayRef strides = self_.sym_strides();
+    // we can't do the normal wrapping here because IntArrayRef maps to both
+    // torch.Size and tuple in python
+    // TODO: consider factoring this out
+    THPObjectPtr tuple(PyTuple_New(static_cast(strides.size())));
+    if (!tuple) throw python_error();
+    for (size_t i = 0; i != strides.size(); i++) {
+      PyObject* s = torch::toPyObject(strides[i]);
+      if (!s) throw python_error();
+      PyTuple_SET_ITEM(tuple.get(), i, s);
+    }
+    return tuple.release();
+  } else if (r.idx == 1) {
+    return wrap(self_.stride(r.dimname(0)));
+  }
+  Py_RETURN_NONE;
+  END_HANDLE_TH_ERRORS
+}
+
+// implemented on the python object to avoid dispatch overhead
+static PyObject * THPVariable_get_device(PyObject* self_, PyObject* args)
+{
+  HANDLE_TH_ERRORS
+  if (check_has_torch_function(self_)) {
+    return handle_torch_function(self_, "get_device", args, nullptr);
+  }
+  auto& self = THPVariable_Unpack(self_);
+  return wrap(self.get_device());
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_has_names(PyObject* self_, PyObject* args)
+{
+  HANDLE_TH_ERRORS
+  if (check_has_torch_function(self_)) {
+    return handle_torch_function(self_, "has_names", args);
+  }
+  auto& self = THPVariable_Unpack(self_);
+  return wrap(self.has_names());
+  END_HANDLE_TH_ERRORS
+}
+
+// implemented on the python object to avoid dispatch overhead
+static PyObject * THPVariable_data_ptr(PyObject* self_, PyObject* args)
+{
+  HANDLE_TH_ERRORS
+  if (check_has_torch_function(self_)) {
+    return handle_torch_function(self_, "data_ptr", args);
+  }
+  auto& self = THPVariable_Unpack(self_);
+  return wrap(self.data_ptr());
+  END_HANDLE_TH_ERRORS
+}
+
+// implemented on the python object to avoid dispatch overhead
+static PyObject * THPVariable_storage_offset(PyObject* self_, PyObject* args)
+{
+  HANDLE_TH_ERRORS
+  if (check_has_torch_function(self_)) {
+    return handle_torch_function(self_, "storage_offset");
+  }
+  auto& self = THPVariable_Unpack(self_);
+  return py::cast(self.sym_storage_offset()).release().ptr();
+  END_HANDLE_TH_ERRORS
+}
+
+// implemented on the python object to avoid dispatch overhead
+static PyObject * THPVariable_dim(PyObject* self, PyObject* args)
+{
+   HANDLE_TH_ERRORS
+   if (check_has_torch_function(self)) {
+     return handle_torch_function(self, "dim", args);
+   }
+   auto& self_ = THPVariable_Unpack(self);
+   return THPUtils_packInt64(self_.dim());
+   END_HANDLE_TH_ERRORS
+}
+
+// implemented on the python object to avoid dispatch overhead
+static PyObject * THPVariable_numel(PyObject* self, PyObject* args)
+{
+   HANDLE_TH_ERRORS
+   if (check_has_torch_function(self)) {
+     return handle_torch_function(self, "numel", args);
+   }
+   auto& self_ = THPVariable_Unpack(self);
+   if (jit::tracer::isTracing()) {
+     return wrap(jit::tracer::getNumelOf(self_));
+   } else {
+     return py::cast(self_.sym_numel()).release().ptr();
+   }
+   END_HANDLE_TH_ERRORS
+}
+
+static Tensor dispatch_contiguous(const Tensor & self, at::MemoryFormat memory_format) {
+  pybind11::gil_scoped_release no_gil;
+  OptionalDeviceGuard device_guard(device_of(self));
+  return self.contiguous(memory_format);
+}
+
+static PyObject * THPVariable_contiguous(PyObject* self, PyObject* args, PyObject* kwargs)
+{
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "contiguous(*, MemoryFormat memory_format=contiguous_format)",
+  });
+  ParsedArgs<1> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  auto& self_ = THPVariable_Unpack(self);
+  auto memory_format = r.memoryformat(0);
+  // avoids touching the GIL or current device if self is already contiguous
+  if (self_.is_contiguous_or_false(memory_format)) {
+    // NOTE: this logic is duplicated from VariableType.cpp. Since we need to
+    // record this call to contiguous() in the trace regardless of whether
+    // we actually call contiguous here, we need to record this information
+    // manually.
+    if (jit::tracer::isTracing()) {
+      const auto& tracer_state = jit::tracer::getTracingState();
+      auto op_name = c10::Symbol::fromQualString("aten::contiguous");
+      auto node = tracer_state->createNode(op_name, /*num_outputs=*/0);
+      jit::tracer::recordSourceLocation(node);
+      jit::tracer::addInputs(node, "self", self_);
+      jit::tracer::addInputs(node, "memory_format", memory_format);
+      tracer_state->insertNode(node);
+      jit::tracer::addOutput(node, self_);
+    }
+    Py_INCREF(self);
+    return self;
+  }
+  return THPVariable_Wrap(dispatch_contiguous(self_, memory_format));
+  END_HANDLE_TH_ERRORS
+}
+
+static Tensor dispatch_copy_(const Tensor & self, const Tensor & other, bool non_blocking) {
+  pybind11::gil_scoped_release no_gil;
+  OptionalDeviceGuard device_guard(device_of(self));
+  return self.copy_(other, non_blocking);
+}
+
+static void maybe_warn_requires_grad(const Tensor & self) {
+  if (at::GradMode::is_enabled() && self.requires_grad()) {
+    TORCH_WARN_ONCE("Converting a tensor with requires_grad=True to a scalar may lead to unexpected behavior.\n"
+                    "Consider using tensor.detach() first.");
+  }
+}
+
+ static PyObject * THPVariable_copy_(PyObject* self, PyObject* args, PyObject* kwargs)
+{
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "copy_(Tensor other, bool non_blocking=False)",
+    "copy_(Tensor other, bool async=False)|deprecated"
+  });
+  auto& self_ = THPVariable_Unpack(self);
+  ParsedArgs<2> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  return THPVariable_Wrap(dispatch_copy_(self_, r.tensor(0), r.toBool(1)));
+  END_HANDLE_TH_ERRORS
+}
+
+template
+static T dispatch_to(const Tensor & self) {
+  pybind11::gil_scoped_release no_gil;
+  OptionalDeviceGuard device_guard(device_of(self));
+  TORCH_CHECK_VALUE(self.sym_numel() == 1, "only one element tensors can be converted to Python scalars");
+  return self.template item();
+}
+
+static PyObject * THPVariable_float_scalar(PyObject* self, PyObject* args) {
+  HANDLE_TH_ERRORS
+  if (check_has_torch_function(self)) {
+    return handle_torch_function(self, "__float__", args);
+  }
+  jit::tracer::warn("Converting a tensor to a Python float", jit::tracer::WARN_PYTHON_DATAFLOW);
+  auto& self_ = THPVariable_Unpack(self);
+  maybe_warn_requires_grad(self_);
+  return wrap(dispatch_to(self_));
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_complex_scalar(PyObject* self, PyObject* args) {
+  HANDLE_TH_ERRORS
+  if (check_has_torch_function(self)) {
+    return handle_torch_function(self, "__complex__", args);
+  }
+  jit::tracer::warn("Converting a tensor to a Python complex", jit::tracer::WARN_PYTHON_DATAFLOW);
+  auto& self_ = THPVariable_Unpack(self);
+  maybe_warn_requires_grad(self_);
+  return wrap(dispatch_to>(self_));
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_integral_scalar(PyObject* self, PyObject* args) {
+  HANDLE_TH_ERRORS
+  if (check_has_torch_function(self)) {
+    return handle_torch_function(self, "__int__", args);
+  }
+  jit::tracer::warn("Converting a tensor to a Python integer", jit::tracer::WARN_PYTHON_DATAFLOW);
+  auto& self_ = THPVariable_Unpack(self);
+  if (isFloatingType(self_.scalar_type())) {
+    // we can't dispatch to item here because we want to avoid ATen overflow checks;
+    // the python integral type (long in python2) can't overflow.
+    return THPUtils_packDoubleAsInt(dispatch_to(self_));
+  } else {
+    return wrap(dispatch_to(self_));
+  }
+  END_HANDLE_TH_ERRORS
+}
+
+// This is the __index__ function in Python which is similar to __int__, but
+// called when used as a slice.
+static PyObject * THPVariable_index_scalar(PyObject* self, PyObject* args) {
+  HANDLE_TH_ERRORS
+  if (check_has_torch_function(self)) {
+    return handle_torch_function(self, "__index__", args);
+  }
+  auto& self_ = THPVariable_Unpack(self);
+  // TODO: change the condition to `self_.dim() != 0` once we expose scalars
+  // in PyTorch.
+  if (!isIntegralType(self_.scalar_type(), /*includeBool=*/true) || self_.sym_numel() != 1) {
+    throw TypeError("only integer tensors of a single element can be converted to an index");
+  }
+  return wrap(dispatch_to(self_));
+  END_HANDLE_TH_ERRORS
+}
+
+static Tensor dispatch_invert(const Tensor & self) {
+  pybind11::gil_scoped_release no_gil;
+  OptionalDeviceGuard device_guard(device_of(self));
+  return self.bitwise_not();
+}
+
+static PyObject * THPVariable_invert(PyObject* self, PyObject* args) {
+  HANDLE_TH_ERRORS
+  if (check_has_torch_function(self)) {
+    return handle_torch_function(self, "__invert__", args);
+  }
+  auto& self_ = THPVariable_Unpack(self);
+  if (!isIntegralType(self_.scalar_type(), /*includeBool=*/true)) {
+    throw TypeError("~ (operator.invert) is only implemented on integer and Boolean-type tensors");
+  }
+  return THPVariable_Wrap(dispatch_invert(self_));
+  END_HANDLE_TH_ERRORS
+}
+
+static Tensor dispatch_to(const Tensor & self, Device device, bool non_blocking, bool copy, std::optional optional_memory_format) {
+  pybind11::gil_scoped_release no_gil;
+  // NOTE: this is where we record aten::to in the graph during tracing. However, the behavior of aten::to
+  // is different with respect to TensorOptions fields that are not present: aten::to inherits fields that
+  // are missing from the self argument while the tracer assumes that they should be populated with the
+  // default values (eg. float for scalar type). By explicitly copying over the tensor options here we fully
+  // specify all tensor options and thus record the proper trace
+  return self.to(self.options().device(device).memory_format(optional_memory_format), non_blocking, copy);
+}
+
+static Tensor dispatch_to(const Tensor & self, bool non_blocking, bool copy, std::optional optional_memory_format) {
+  pybind11::gil_scoped_release no_gil;
+  return self.to(self.options().memory_format(optional_memory_format), non_blocking, copy);
+}
+
+static Tensor dispatch_to(const Tensor & self, ScalarType dtype, bool non_blocking, bool copy, std::optional optional_memory_format) {
+  pybind11::gil_scoped_release no_gil;
+  // TODO: Make this call the TensorOptions version, maybe?
+  return self.to(dtype, non_blocking, copy, optional_memory_format);
+}
+
+static Tensor dispatch_to(const Tensor & self, Device device, ScalarType dtype, bool non_blocking, bool copy, std::optional optional_memory_format) {
+  pybind11::gil_scoped_release no_gil;
+  // TODO: Make this call the TensorOptions version, maybe?
+  return self.to(device, dtype, non_blocking, copy, optional_memory_format);
+}
+
+static PyObject * THPVariable_cpu(PyObject* self, PyObject* args, PyObject* kwargs)
+{
+   HANDLE_TH_ERRORS
+   static PythonArgParser parser({
+     "cpu(*, MemoryFormat? memory_format=None)"
+   });
+   auto& self_ = THPVariable_Unpack(self);
+   ParsedArgs<1> parsed_args;
+   auto r = parser.parse(self, args, kwargs, parsed_args);
+
+   if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+    }
+
+   auto opt_memory_format = r.memoryformatOptional(0);
+   return THPVariable_Wrap(dispatch_to(self_, at::Device(at::DeviceType::CPU), false, false, opt_memory_format));
+   END_HANDLE_TH_ERRORS
+}
+
+static Tensor dispatch_nonzero(const Tensor & self) {
+  pybind11::gil_scoped_release no_gil;
+  OptionalDeviceGuard device_guard(device_of(self));
+  return self.nonzero();
+}
+
+static std::vector dispatch_nonzero_numpy(const Tensor & self) {
+  pybind11::gil_scoped_release no_gil;
+  OptionalDeviceGuard device_guard(device_of(self));
+  return self.nonzero_numpy();
+}
+
+static PyObject * THPVariable_nonzero(PyObject* self, PyObject* args, PyObject* kwargs)
+{
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "nonzero()",
+    "nonzero(*, bool as_tuple)",
+  });
+  auto& self_ = THPVariable_Unpack(self);
+  ParsedArgs<2> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  if (r.idx == 0 || (r.idx == 1 && !r.toBool(0))) {
+    return wrap(dispatch_nonzero(self_));
+  } else {
+    return wrap(dispatch_nonzero_numpy(self_));
+  }
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_cuda(PyObject* self, PyObject* args, PyObject* kwargs)
+{
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "cuda(Device? device=None, bool non_blocking=False, *, MemoryFormat? memory_format=None)",
+    "cuda(Device? device=None, bool async=False, *, MemoryFormat? memory_format=None)|deprecated"
+  });
+  auto& self_ = THPVariable_Unpack(self);
+  ParsedArgs<3> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  auto device = r.isNone(0) ? at::Device(at::DeviceType::CUDA) : r.device(0);
+  auto opt_memory_format = r.memoryformatOptional(2);
+  TORCH_CHECK(device.is_cuda(), "Invalid device, must be cuda device");
+  torch::utils::device_lazy_init(at::kCUDA);
+  return THPVariable_Wrap(dispatch_to(self_, device, r.toBool(1), false, opt_memory_format));
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_mtia(PyObject* self, PyObject* args, PyObject* kwargs)
+{
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "mtia(Device? device=None, bool non_blocking=False, *, MemoryFormat? memory_format=None)",
+    "mtia(Device? device=None, bool async=False, *, MemoryFormat? memory_format=None)|deprecated"
+  });
+  auto& self_ = THPVariable_Unpack(self);
+  ParsedArgs<3> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if (r.has_torch_function()) {
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  auto device = r.isNone(0) ? at::Device(at::DeviceType::MTIA) : r.device(0);
+  auto opt_memory_format = r.memoryformatOptional(2);
+  TORCH_CHECK(device.is_mtia(), "Invalid device, must be MTIA device");
+  torch::utils::device_lazy_init(at::kMTIA);
+  return THPVariable_Wrap(dispatch_to(self_, device, r.toBool(1), false, opt_memory_format));
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_xpu(PyObject* self, PyObject* args, PyObject* kwargs)
+{
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "xpu(Device? device=None, bool non_blocking=False, *, MemoryFormat? memory_format=None)",
+    "xpu(Device? device=None, bool async=False, *, MemoryFormat? memory_format=None)|deprecated"
+  });
+  auto& self_ = THPVariable_Unpack(self);
+  ParsedArgs<3> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if (r.has_torch_function()) {
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  auto device = r.isNone(0) ? at::Device(at::DeviceType::XPU) : r.device(0);
+  auto opt_memory_format = r.memoryformatOptional(2);
+  TORCH_CHECK(device.is_xpu(), "Invalid device, must be xpu device");
+  torch::utils::device_lazy_init(at::kXPU);
+  return THPVariable_Wrap(dispatch_to(self_, device, r.toBool(1), false, opt_memory_format));
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_ipu(PyObject* self, PyObject* args, PyObject* kwargs)
+{
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "ipu(Device? device=None, bool non_blocking=False, *, MemoryFormat? memory_format=None)",
+    "ipu(Device? device=None, bool async=False, *, MemoryFormat? memory_format=None)|deprecated"
+  });
+  auto& self_ = THPVariable_Unpack(self);
+  ParsedArgs<3> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if (r.has_torch_function()) {
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  auto device = r.isNone(0) ? at::Device(at::DeviceType::IPU) : r.device(0);
+  auto opt_memory_format = r.memoryformatOptional(2);
+  TORCH_CHECK(device.is_ipu(), "Invalid device, must be ipu device");
+  return THPVariable_Wrap(dispatch_to(self_, device, r.toBool(1), false, opt_memory_format));
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_to_type(PyObject* self, ScalarType scalarType, std::optional optional_memory_format) {
+  HANDLE_TH_ERRORS
+  auto& self_ = THPVariable_Unpack(self);
+  return THPVariable_Wrap(dispatch_to(self_, scalarType, false, false, optional_memory_format));
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_byte(PyObject* self, PyObject* args, PyObject* kwargs)  {
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "byte(*, MemoryFormat? memory_format=None)"
+  });
+  ParsedArgs<1> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  auto opt_memory_format = r.memoryformatOptional(0);
+  return THPVariable_to_type(self, ScalarType::Byte, opt_memory_format);
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_char(PyObject* self, PyObject* args, PyObject* kwargs)  {
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "char(*, MemoryFormat? memory_format=None)"
+  });
+  ParsedArgs<1> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  auto opt_memory_format = r.memoryformatOptional(0);
+  return THPVariable_to_type(self, ScalarType::Char, opt_memory_format);
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_double(PyObject* self, PyObject* args, PyObject* kwargs) {
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "double(*, MemoryFormat? memory_format=None)"
+  });
+  ParsedArgs<1> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  auto opt_memory_format = r.memoryformatOptional(0);
+  return THPVariable_to_type(self, ScalarType::Double, opt_memory_format);
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_float(PyObject* self, PyObject* args, PyObject* kwargs) {
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "float(*, MemoryFormat? memory_format=None)"
+  });
+  ParsedArgs<1> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  auto opt_memory_format = r.memoryformatOptional(0);
+  return THPVariable_to_type(self, ScalarType::Float, opt_memory_format);
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_cdouble(PyObject* self, PyObject* args, PyObject* kwargs) {
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "cdouble(*, MemoryFormat? memory_format=None)"
+  });
+  ParsedArgs<1> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  auto opt_memory_format = r.memoryformatOptional(0);
+  return THPVariable_to_type(self, ScalarType::ComplexDouble, opt_memory_format);
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_cfloat(PyObject* self, PyObject* args, PyObject* kwargs) {
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "cfloat(*, MemoryFormat? memory_format=None)"
+  });
+  ParsedArgs<1> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  auto opt_memory_format = r.memoryformatOptional(0);
+  return THPVariable_to_type(self, ScalarType::ComplexFloat, opt_memory_format);
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_half(PyObject* self, PyObject* args, PyObject* kwargs) {
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "half(*, MemoryFormat? memory_format=None)"
+  });
+  ParsedArgs<1> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  auto opt_memory_format = r.memoryformatOptional(0);
+  return THPVariable_to_type(self, ScalarType::Half, opt_memory_format);
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_int(PyObject* self, PyObject* args, PyObject* kwargs) {
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "int(*, MemoryFormat? memory_format=None)"
+  });
+  ParsedArgs<1> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  auto opt_memory_format = r.memoryformatOptional(0);
+  return THPVariable_to_type(self, ScalarType::Int, opt_memory_format);
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_long(PyObject* self, PyObject* args, PyObject* kwargs) {
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "long(*, MemoryFormat? memory_format=None)"
+  });
+  ParsedArgs<1> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  auto opt_memory_format = r.memoryformatOptional(0);
+  return THPVariable_to_type(self, ScalarType::Long, opt_memory_format);
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_short(PyObject* self, PyObject* args, PyObject* kwargs) {
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "short(*, MemoryFormat? memory_format=None)"
+  });
+  ParsedArgs<1> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  auto opt_memory_format = r.memoryformatOptional(0);
+  return THPVariable_to_type(self, ScalarType::Short, opt_memory_format);
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_bool(PyObject* self, PyObject* args, PyObject* kwargs) {
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "bool(*, MemoryFormat? memory_format=None)"
+  });
+  ParsedArgs<1> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  auto opt_memory_format = r.memoryformatOptional(0);
+  return THPVariable_to_type(self, ScalarType::Bool, opt_memory_format);
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_bfloat16(PyObject* self, PyObject* args, PyObject* kwargs) {
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "bfloat16(*, MemoryFormat? memory_format=None)"
+  });
+  ParsedArgs<1> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  auto opt_memory_format = r.memoryformatOptional(0);
+  return THPVariable_to_type(self, ScalarType::BFloat16, opt_memory_format);
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_element_size(PyObject* self, PyObject* args)
+{
+  HANDLE_TH_ERRORS
+  if (check_has_torch_function(self)) {
+    return handle_torch_function(self, "element_size", args);
+  }
+  auto& self_ = THPVariable_Unpack(self);
+  return THPUtils_packInt64(self_.element_size());
+  END_HANDLE_TH_ERRORS
+}
+
+// implemented on the python object bc PyObjects not declarable in native_functions.yaml
+// See: ATen/native/README.md for more context
+static PyObject * THPVariable_numpy(PyObject* self, PyObject* args, PyObject* kwargs)
+{
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "numpy(*, bool force=False)"
+  });
+  auto& self_ = THPVariable_Unpack(self);
+  ParsedArgs<1> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if (r.has_torch_function()) {
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  jit::tracer::warn("Converting a tensor to a NumPy array", jit::tracer::WARN_PYTHON_DATAFLOW);
+  return torch::utils::tensor_to_numpy(self_, r.toBool(0));
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_requires_grad_(PyObject* self, PyObject* args, PyObject* kwargs)
+{
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "requires_grad_(bool requires_grad=True)",
+  });
+  auto& self_ = THPVariable_Unpack(self);
+  ParsedArgs<1> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  // temporary hack to improve functorch UX.
+  const auto& functorch_tls = at::functorch::functorchTLSAccessor();
+  if (functorch_tls) {
+    functorch_tls->checkSupportsInplaceRequiresGrad();
+  }
+
+  auto requires_grad = r.toBool(0);
+  // should we throw if requires_grad is true?  var.requires_grad = True throws here
+  // but it's nice to let this be a no-op.
+  if (!self_.is_leaf() && !requires_grad) {
+    throw std::runtime_error(autograd::utils::requires_grad_leaf_error(requires_grad));
+  }
+  if (requires_grad && ! isDifferentiableType(at::typeMetaToScalarType(self_.dtype()))) {
+    throw std::runtime_error("only Tensors of floating point dtype can require gradients");
+  }
+  self_.set_requires_grad(requires_grad);
+  return THPVariable_Wrap(self_);
+  END_HANDLE_TH_ERRORS
+}
+
+static inline bool dispatch_is_contiguous(const Tensor & self, MemoryFormat memory_format) {
+  return self.is_contiguous(memory_format);
+}
+
+// implemented on the python object to avoid dispatch overhead
+static PyObject * THPVariable_is_contiguous(PyObject* self_, PyObject* args, PyObject* kwargs)
+{
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "is_contiguous(*, MemoryFormat memory_format=contiguous_format)",
+  });
+  ParsedArgs<1> parsed_args;
+  auto r = parser.parse(self_, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self_, args, kwargs, PyObject_Type(self_), "torch.Tensor");
+  }
+
+  auto memory_format = r.memoryformat(0);
+  auto& self = THPVariable_Unpack(self_);
+  return wrap(dispatch_is_contiguous(self, memory_format));
+  END_HANDLE_TH_ERRORS
+}
+
+// implemented on the python object to avoid dispatch overhead
+static PyObject * THPVariable_item(PyObject* self, PyObject* args)
+{
+  HANDLE_TH_ERRORS
+  if (check_has_torch_function(self)) {
+    return handle_torch_function(self, "item", args);
+  }
+  jit::tracer::warn("Converting a tensor to a Python number", jit::tracer::WARN_PYTHON_DATAFLOW);
+  auto& self_ = THPVariable_Unpack(self);
+  auto dispatch_item_ = [](const Tensor& self) -> at::Scalar {
+    pybind11::gil_scoped_release no_gil;
+    return self.item();
+  };
+  return py::cast(dispatch_item_(self_)).release().ptr();
+  END_HANDLE_TH_ERRORS
+}
+
+// implemented on the python object bc no support for first class functions in native_functions.yaml
+// See: ATen/native/README.md for more context
+static PyObject * THPVariable_map_(PyObject* self, PyObject* args, PyObject* kwargs)
+{
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({ "map_(Tensor other, PyObject* callable)" });
+  auto& self_ = THPVariable_Unpack(self);
+  ParsedArgs<2> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  Variable other = r.tensor(0);
+  if (self_.requires_grad() || other.requires_grad()) {
+    throw std::runtime_error(
+        "Can't call map_() on Variable that requires grad. Use "
+        "var.detach().map_() instead.");
+  }
+  TORCH_CHECK(
+      !self_.unsafeGetTensorImpl()->is_python_dispatch() && !other.unsafeGetTensorImpl()->is_python_dispatch(),
+      ".map_ is not supported for tensor subclasses.");
+
+  return THPVariable_Wrap(torch::utils::map_(self_, other, r.pyobject(1)));
+  END_HANDLE_TH_ERRORS
+}
+
+// implemented on the python object bc no support for first class functions in native_functions.yaml
+// See: ATen/native/README.md for more context
+static PyObject * THPVariable_map2_(PyObject* self, PyObject* args, PyObject* kwargs)
+{
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({ "map2_(Tensor x, Tensor y, PyObject* callable)" });
+  auto& self_ = THPVariable_Unpack(self);
+  ParsedArgs<3> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  Variable x = r.tensor(0);
+  Variable y = r.tensor(1);
+  if (self_.requires_grad() || x.requires_grad() || y.requires_grad()) {
+    throw std::runtime_error(
+        "Can't call map2_() on Variable that requires grad. Use "
+        "var.detach().map2_() instead.");
+  }
+  TORCH_CHECK(
+      !x.unsafeGetTensorImpl()->is_python_dispatch() && !y.unsafeGetTensorImpl()->is_python_dispatch(),
+      ".map2_ is not supported for tensor subclasses.");
+  return THPVariable_Wrap(torch::utils::map2_(self_, x, y, r.pyobject(2)));
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_new(PyObject* self, PyObject* args, PyObject* kwargs)
+{
+  HANDLE_TH_ERRORS
+  if (check_has_torch_function(self)) {
+    return handle_torch_function(self, "new", args, kwargs);
+  }
+  auto& self_ = THPVariable_Unpack(self);
+  OptionalDeviceGuard device_guard(device_of(self_));
+  return THPVariable_Wrap(torch::utils::legacy_tensor_new(legacyExtractDispatchKey(self_), self_.scalar_type(), args, kwargs));
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_new_tensor(PyObject* self, PyObject* args, PyObject* kwargs)
+{
+  HANDLE_TH_ERRORS
+  if (check_has_torch_function(self)) {
+    return handle_torch_function(self, "new_tensor", args, kwargs);
+  }
+  auto& self_ = THPVariable_Unpack(self);
+  OptionalDeviceGuard device_guard(device_of(self_));
+  return THPVariable_Wrap(torch::utils::new_tensor(legacyExtractDispatchKey(self_), self_.scalar_type(), args, kwargs));
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_storage(PyObject* self, PyObject* arg)
+{
+  HANDLE_TH_ERRORS
+  if (check_has_torch_function(self)) {
+    return handle_torch_function(self, "untyped_storage");
+  }
+  auto& self_ = THPVariable_Unpack(self);
+  return createPyObject(self_.storage());
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_to(PyObject* self, PyObject* args, PyObject* kwargs)
+{
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "to(Device device=None, ScalarType dtype=None, bool non_blocking=False, bool copy=False, *, MemoryFormat? memory_format=None)",
+    "to(ScalarType dtype, bool non_blocking=False, bool copy=False, *, MemoryFormat? memory_format=None)",
+    "to(Tensor tensor, bool non_blocking=False, bool copy=False, *, MemoryFormat? memory_format=None)",
+  });
+  ParsedArgs<5> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+  if (r.has_torch_function()) {
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+  auto parsed = parse_to_conversion(r, /*allow_copy*/ true);
+  auto& device = std::get<0>(parsed);
+  auto& scalarType = std::get<1>(parsed);
+  auto non_blocking = std::get<2>(parsed);
+  auto copy = std::get<3>(parsed);
+  auto opt_memory_format = std::get<4>(parsed);
+  auto& self_ = THPVariable_Unpack(self);
+  torch::utils::maybe_initialize_device(device);
+  if (!device && !scalarType && !copy && !opt_memory_format.has_value()) {
+    Py_INCREF(self);
+    return self;
+  } else if (!device && !scalarType) {
+    return THPVariable_Wrap(
+        dispatch_to(self_, non_blocking, copy, opt_memory_format));
+  } else if (!device) {
+    return THPVariable_Wrap(dispatch_to(self_, *scalarType, non_blocking, copy, opt_memory_format));
+  } else if (!scalarType) {
+    return THPVariable_Wrap(dispatch_to(self_, *device, non_blocking, copy, opt_memory_format));
+  } else {
+    return THPVariable_Wrap(dispatch_to(self_, *device, *scalarType, non_blocking, copy, opt_memory_format));
+  }
+  Py_RETURN_NONE;
+  END_HANDLE_TH_ERRORS
+}
+
+// implemented on the python object b/c arbitrarily nested list not declarable in native_functions.yaml
+// See: ATen/native/README.md for more context
+static PyObject * THPVariable_tolist(PyObject* self, PyObject* args)
+{
+  HANDLE_TH_ERRORS
+  if (check_has_torch_function(self)) {
+    return handle_torch_function(self, "tolist", args);
+  }
+  jit::tracer::warn("Converting a tensor to a Python list", jit::tracer::WARN_PYTHON_DATAFLOW);
+  auto self_ = THPVariable_Unpack(self);
+  return torch::utils::tensor_to_list(self_);
+  END_HANDLE_TH_ERRORS
+}
+
+static PyObject * THPVariable_type(PyObject* self, PyObject* args, PyObject* kwargs)
+{
+  HANDLE_TH_ERRORS
+  static PythonArgParser parser({
+    "type(PyObject* dtype=None, bool non_blocking=False, *, MemoryFormat? memory_format=None)",
+    "type(PyObject* dtype=None, bool async=False, *, MemoryFormat? memory_format=None)|deprecated"
+  });
+  auto& self_ = THPVariable_Unpack(self);
+  ParsedArgs<3> parsed_args;
+  auto r = parser.parse(self, args, kwargs, parsed_args);
+
+  if(r.has_torch_function()){
+    return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor");
+  }
+
+  if (r.isNone(0)) {
+    return THPUtils_packString(torch::utils::options_to_string(self_.options()));
+  }
+  auto obj = r.pyobject(0);
+  auto opt_memory_format = r.memoryformatOptional(2);
+  std::string type_name;
+  bool is_dtype = false;
+  if (PyType_Check(obj)) {
+    if (obj == THPVariableClass) {
+      type_name = "torch.Tensor";
+    } else {
+      type_name = ((PyTypeObject*)obj)->tp_name;
+    }
+  } else if (THPUtils_checkString(obj)) {
+    type_name = THPUtils_unpackString(obj);
+  } else if (THPDtype_Check(obj)) {
+    is_dtype = true;
+  } else {
+    throw TypeError("dtype must be a type, str, or dtype object");
+  }
+  Device device = self_.device();
+  if (is_dtype) {
+    auto scalar_type = r.scalartype(0);
+    return THPVariable_Wrap(dispatch_to(self_, scalar_type, /*non_blocking=*/ r.toBool(1), /*copy=*/ false, opt_memory_format));
+  }
+  at::TensorOptions options = torch::utils::options_from_string(type_name);
+  auto scalar_type = at::typeMetaToScalarType(options.dtype());
+  auto device_type = options.device().type();
+  if (device_type != device.type()) {
+    device = at::Device(device_type);
+  }
+  torch::utils::maybe_initialize_device(device);
+  return THPVariable_Wrap(dispatch_to(self_, device, scalar_type, /*non_blocking=*/ r.toBool(1), /*copy=*/ false, opt_memory_format));
+  END_HANDLE_TH_ERRORS
+}
+
+// generated methods start here
+
+${py_methods}
+
+static PyObject * THPVariable_bool_scalar(PyObject* self, PyObject* args) {
+  if (check_has_torch_function(self)) {
+    HANDLE_TH_ERRORS
+    return handle_torch_function(self, "__bool__", args);
+    END_HANDLE_TH_ERRORS
+  }
+  jit::tracer::warn("Converting a tensor to a Python boolean", jit::tracer::WARN_PYTHON_DATAFLOW);
+  return THPVariable_is_nonzero(self, args);
+}
+
+static PyObject * THPVariable___eq__(PyObject* self_, PyObject* args, PyObject* kwargs)
+{
+  HANDLE_TH_ERRORS
+#ifdef USE_NUMPY
+  if (torch::utils::is_numpy_available()) {
+    static PythonArgParser parser({
+      "__eq__(PyObject* other)",
+    }, /*traceable=*/true);
+
+    ParsedArgs<1> parsed_args;
+    auto _r = parser.parse(self_, args, kwargs, parsed_args);
+    if(_r.has_torch_function()) {
+      return handle_torch_function(_r, self_, args, kwargs, THPVariableClass, "torch.Tensor");
+    }
+    switch (_r.idx) {
+      case 0: {
+        auto other = _r.pyobject(0);
+        if (PyArray_Check(other)) {
+          auto other_tensor = torch::utils::tensor_from_numpy(other);
+          auto dispatch_eq = [](const at::Tensor & self, const at::Tensor & other) -> at::Tensor {
+            pybind11::gil_scoped_release no_gil;
+            return self.eq(other);
+          };
+          const Tensor& self = THPVariable_Unpack(self_);
+          return wrap(dispatch_eq(self, other_tensor));
+        }
+      }
+    }
+  }
+#endif
+  return THPVariable_eq(self_, args, kwargs);
+  Py_RETURN_NONE;
+  END_HANDLE_TH_ERRORS
+}
+
+// Wrapper converts a raised TypeError into returning NotImplemented
+// Used to implement binary arithmetic operators
+template 
+static PyObject * TypeError_to_NotImplemented_(PyObject* self, PyObject* args, PyObject* kwargs) {
+
+  PyObject* ret = Func(self, args, kwargs);
+  if (!ret && PyErr_ExceptionMatches(PyExc_TypeError)) {
+    PyErr_Clear();
+    Py_INCREF(Py_NotImplemented);
+    ret = Py_NotImplemented;
+  }
+  return ret;
+}
+
+// set_ has to be defined in the template because the c10::Storage object
+// does not have a type, and we need to make sure the Python storage object's
+// type matches the tensor's type
+static PyObject* THPVariable_set_(
+    PyObject* self_,
+    PyObject* args,
+    PyObject* kwargs) {
+  HANDLE_TH_ERRORS
+  const Tensor& self = THPVariable_Unpack(self_);
+  static PythonArgParser parser(
+      {
+          "set_()",
+          "set_(Storage source)",
+          "set_(Storage source, SymInt storage_offset, SymIntArrayRef size, SymIntArrayRef stride=None)",
+          "set_(Tensor source)",
+          "set_(Tensor source, SymInt storage_offset, SymIntArrayRef size, SymIntArrayRef stride=None)",
+      },
+      /*traceable=*/false);
+
+  ParsedArgs<4> parsed_args;
+  auto _r = parser.parse(args, kwargs, parsed_args);
+
+  switch (_r.idx) {
+    case 0: {
+      // aten::set_(Tensor(a!) self) -> Tensor(a!)
+      auto dispatch_set_ = [](const Tensor& self) -> Tensor {
+        pybind11::gil_scoped_release no_gil;
+        return self.set_();
+      };
+      return wrap(dispatch_set_(self));
+    }
+    case 1: {
+      // aten::set_.source_Storage(Tensor(a!) self, Storage source) ->
+      // Tensor(a!)
+      at::ScalarType storage_scalar_type{};
+      bool is_typed_storage = true;
+      at::Storage storage = _r.storage(0, storage_scalar_type, is_typed_storage);
+      TORCH_CHECK(storage_scalar_type == self.dtype() || !is_typed_storage,
+        "Expected a Storage of type ", self.dtype(),
+        " or an UntypedStorage, but got type ", storage_scalar_type,
+        " for argument 1 'storage'");
+      auto dispatch_set_ = [](const Tensor& self, Storage source) -> Tensor {
+        pybind11::gil_scoped_release no_gil;
+        return self.set_(std::move(source));
+      };
+      return wrap(dispatch_set_(self, storage));
+    }
+    case 2: {
+      // aten::set_.source_Storage_storage_offset(Tensor(a!) self, Storage
+      // source, int storage_offset, int[] size, int[] stride=[]) -> Tensor(a!)
+      at::ScalarType storage_scalar_type{};
+      bool is_typed_storage = true;
+      at::Storage storage = _r.storage(0, storage_scalar_type, is_typed_storage);
+      TORCH_CHECK(storage_scalar_type == self.dtype() || !is_typed_storage,
+        "Expected a Storage of type ", self.dtype(),
+        " or an UntypedStorage, but got type ", storage_scalar_type,
+        " for argument 1 'storage'");
+      auto dispatch_set_ = [](const Tensor& self,
+                              Storage source,
+                              c10::SymInt storage_offset,
+                              c10::SymIntArrayRef size,
+                              c10::SymIntArrayRef stride) -> Tensor {
+        pybind11::gil_scoped_release no_gil;
+        return self.set__symint(std::move(source), std::move(storage_offset), size, stride);
+      };
+      return wrap(dispatch_set_(
+          self, storage, _r.toSymInt(1), _r.symintlist(2), _r.symintlist(3)));
+    }
+    case 3: {
+      // aten::set_.source_Tensor(Tensor(a!) self, Tensor source) -> Tensor(a!)
+      auto dispatch_set_ = [](const Tensor& self, const Tensor& source) -> Tensor {
+        TORCH_CHECK(source.dtype() == self.dtype(), "Could not set tensor of type ", source.dtype(), " to a tensor of type ", self.dtype());
+        pybind11::gil_scoped_release no_gil;
+        return self.set_(source);
+      };
+      return wrap(dispatch_set_(self, _r.tensor(0)));
+    }
+    case 4: {
+      // aten::set_.source_Tensor_storage_offset(Tensor(a!) self, Tensor
+      // source, int storage_offset, int[] size, int[] stride=[]) -> Tensor(a!)
+      at::Tensor storage = _r.tensor(0);
+      auto dispatch_set_ = [](const Tensor& self,
+                              const Tensor& source,
+                              c10::SymInt storage_offset,
+                              c10::SymIntArrayRef size,
+                              c10::SymIntArrayRef stride) -> Tensor {
+        pybind11::gil_scoped_release no_gil;
+        return self.set__symint(source, std::move(storage_offset), size, stride);
+      };
+      return wrap(dispatch_set_(
+          self, storage, _r.toSymInt(1), _r.symintlist(2), _r.symintlist(3)));
+    }
+  }
+  Py_RETURN_NONE;
+  END_HANDLE_TH_ERRORS
+}
+
+// XXX: ops that are bound here are not exposed to the C++ api nor the JIT.
+// Any new ops added here should be accompanied with a comment why they are not
+// being registered through native_functions.yaml, and be tagged cpp / JIT
+PyMethodDef variable_methods[] = {
+  // These magic methods are all implemented on python object to wrap NotImplementedError
+  {"__add__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__radd__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__iadd__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__rmul__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__mul__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__imul__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__sub__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__isub__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__div__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__truediv__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__floordiv__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__idiv__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__ifloordiv__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__mod__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__imod__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__eq__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__ne__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__lt__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__le__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__gt__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__ge__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__rand__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__ror__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__rxor__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"__bool__", THPVariable_bool_scalar, METH_NOARGS, nullptr},
+  {"__float__", THPVariable_float_scalar, METH_NOARGS, nullptr},
+  {"__complex__", THPVariable_complex_scalar, METH_NOARGS, nullptr},
+  {"__int__", THPVariable_integral_scalar, METH_NOARGS, nullptr},
+  {"__long__", THPVariable_integral_scalar, METH_NOARGS, nullptr},
+  {"__index__", THPVariable_index_scalar, METH_NOARGS, nullptr},
+  {"__nonzero__", THPVariable_bool_scalar, METH_NOARGS, nullptr},
+  {"__invert__", THPVariable_invert, METH_NOARGS, nullptr},
+  {"__matmul__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"_is_view", THPVariable__is_view, METH_NOARGS, nullptr},
+  {"apply_", THPVariable_apply_, METH_O, nullptr},
+  {"bfloat16", castPyCFunctionWithKeywords(THPVariable_bfloat16), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"byte", castPyCFunctionWithKeywords(THPVariable_byte), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"char", castPyCFunctionWithKeywords(THPVariable_char), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"contiguous", castPyCFunctionWithKeywords(THPVariable_contiguous), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"copy_", castPyCFunctionWithKeywords(THPVariable_copy_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"cpu", castPyCFunctionWithKeywords(THPVariable_cpu), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"cuda", castPyCFunctionWithKeywords(THPVariable_cuda), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"mtia", castPyCFunctionWithKeywords(THPVariable_mtia), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"xpu", castPyCFunctionWithKeywords(THPVariable_xpu), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"ipu", castPyCFunctionWithKeywords(THPVariable_ipu), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"data_ptr", THPVariable_data_ptr, METH_NOARGS, nullptr},
+  {"dim", THPVariable_dim, METH_NOARGS, nullptr},
+  {"has_names", THPVariable_has_names, METH_NOARGS, nullptr},
+  {"double", castPyCFunctionWithKeywords(THPVariable_double), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"cdouble", castPyCFunctionWithKeywords(THPVariable_cdouble), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"element_size", THPVariable_element_size, METH_NOARGS, nullptr},
+  {"float", castPyCFunctionWithKeywords(THPVariable_float), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"cfloat", castPyCFunctionWithKeywords(THPVariable_cfloat), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"get_device", THPVariable_get_device, METH_NOARGS, nullptr},
+  {"bool", castPyCFunctionWithKeywords(THPVariable_bool), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"half", castPyCFunctionWithKeywords(THPVariable_half), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"int", castPyCFunctionWithKeywords(THPVariable_int), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"is_contiguous", castPyCFunctionWithKeywords(THPVariable_is_contiguous), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"item", THPVariable_item, METH_NOARGS, nullptr},
+  {"long", castPyCFunctionWithKeywords(THPVariable_long), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"map_", castPyCFunctionWithKeywords(THPVariable_map_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"map2_", castPyCFunctionWithKeywords(THPVariable_map2_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"ndimension", THPVariable_dim, METH_NOARGS, nullptr},
+  {"nelement", THPVariable_numel, METH_NOARGS, nullptr},
+  {"new", castPyCFunctionWithKeywords(THPVariable_new), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"new_tensor", castPyCFunctionWithKeywords(THPVariable_new_tensor), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"nonzero", castPyCFunctionWithKeywords(THPVariable_nonzero), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"numel", THPVariable_numel, METH_NOARGS, nullptr},
+  {"numpy", castPyCFunctionWithKeywords(THPVariable_numpy), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"requires_grad_", castPyCFunctionWithKeywords(THPVariable_requires_grad_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"set_", castPyCFunctionWithKeywords(THPVariable_set_), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"short", castPyCFunctionWithKeywords(THPVariable_short), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"size", castPyCFunctionWithKeywords(THPVariable_size), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"untyped_storage", THPVariable_storage, METH_NOARGS, nullptr},
+  {"storage_offset", THPVariable_storage_offset, METH_NOARGS, nullptr},
+  {"stride", castPyCFunctionWithKeywords(THPVariable_stride), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"to", castPyCFunctionWithKeywords(THPVariable_to), METH_VARARGS | METH_KEYWORDS, nullptr},
+  {"tolist", THPVariable_tolist, METH_NOARGS, nullptr},
+  {"type", castPyCFunctionWithKeywords(THPVariable_type), METH_VARARGS | METH_KEYWORDS, nullptr},
+  ${py_method_defs}
+  {nullptr}
+};
+
+} // namespace torch::autograd
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/variable_factories.h b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/variable_factories.h
new file mode 100644
index 0000000000000000000000000000000000000000..2b55f441ab6249cb7963c5e4a15070f626f775b7
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/variable_factories.h
@@ -0,0 +1,135 @@
+#pragma once
+
+// ${generated_comment}
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#ifndef AT_PER_OPERATOR_HEADERS
+#include 
+#else
+#include 
+$ops_headers
+#endif
+
+#include 
+#include 
+#include 
+
+namespace torch {
+
+/// NOTE: Currently `torch::tensor(...)` doesn't support mixed data types
+/// (i.e. `torch::tensor({{bool, 2.0}})` doesn't work). We might be able to
+/// support it in the future by iterating over all sub-lists to find
+/// the largest data type that can represent all of the elements, or by using
+/// variadic templates.
+///
+/// NOTE: C++ `torch::tensor` with a floating-point type or an `at::ArrayRef` / `std::vector` /
+/// (nested) braced-init-list of floating-point types always produces a tensor of dtype
+/// `torch::get_default_dtype()`, matching Python `torch.tensor` behavior.
+///
+/// NOTE: C++ `torch::tensor` with an integer type or an `at::ArrayRef` / `std::vector` /
+/// (nested) braced-init-list of integer types always produces a tensor of dtype `at::kLong`
+/// (aka. int64_t), matching Python `torch.tensor` behavior.
+///
+/// NOTE: The following dtypes are not supported by `torch::tensor` currently:
+/// - `unsigned int`
+/// - `unsigned long int`
+/// - `unsigned long long int`
+/// - `long long int`
+inline at::Tensor tensor(detail::TensorDataContainer tensor_data_container, const at::TensorOptions& options = {}) {
+  return autograd::make_variable(
+    // note: we remove the requires_grad setting from the TensorOptions because
+    // it is ignored anyways (and we actually have an assertion that it isn't set
+    // which would fail otherwise). We handle requires_grad explicitly here
+    // instead of passing it through to the kernel.
+    tensor_data_container.convert_to_tensor(options.requires_grad(::std::nullopt)),
+    options.requires_grad());
+}
+
+/// A generic deleter function.
+using Deleter = std::function;
+using at::MemoryFormat;
+
+/// Exposes the given `data` as a `Tensor` without taking ownership of the
+/// original data. `sizes` should specify the shape of the tensor, `strides` the
+/// stride in each dimension. The `deleter` function (a
+/// `std::function`) will be called on the `data` when the Tensor
+/// data would normally be deallocated. The `TensorOptions` specify additional
+/// configuration options for the returned tensor, such as what type to
+/// interpret the `data` as.
+inline at::Tensor from_blob(
+    void* data,
+    at::IntArrayRef sizes,
+    at::IntArrayRef strides,
+    const Deleter& deleter,
+    const at::TensorOptions& options = at::TensorOptions()) {
+  at::Tensor tensor = ([&]() {
+    at::AutoDispatchBelowAutograd guard;  // TODO: remove
+    at::tracer::impl::NoTracerDispatchMode tracer_guard;
+    return at::from_blob(data, sizes, strides, deleter, options.requires_grad(::std::nullopt));
+  })();
+  return autograd::make_variable(tensor, options.requires_grad());
+}
+
+/// Exposes the given `data` as a `Tensor` without taking ownership of the
+/// original data. `sizes` should specify the shape of the tensor, `strides` the
+/// stride in each dimension. The `TensorOptions`
+/// specify additional configuration options for the returned tensor, such as
+/// what type to interpret the `data` as.
+inline at::Tensor from_blob(
+    void* data,
+    at::IntArrayRef sizes,
+    at::IntArrayRef strides,
+    const at::TensorOptions& options = at::TensorOptions()) {
+  at::Tensor tensor = ([&]() {
+    at::AutoDispatchBelowAutograd guard;  // TODO: remove
+    at::tracer::impl::NoTracerDispatchMode tracer_guard;
+    return at::from_blob(data, sizes, strides, options.requires_grad(::std::nullopt));
+  })();
+  return autograd::make_variable(tensor, options.requires_grad());
+}
+
+/// Exposes the given `data` as a `Tensor` without taking ownership of the
+/// original data. `sizes` should specify the shape of the tensor. The `deleter`
+/// (a `std::function`) function will be called on the `data` when
+/// the Tensor data would normally be deallocated. The `TensorOptions` specify
+/// additional configuration options for the returned tensor, such as what type
+/// to interpret the `data` as.
+inline at::Tensor from_blob(
+    void* data,
+    at::IntArrayRef sizes,
+    const Deleter& deleter,
+    const at::TensorOptions& options = at::TensorOptions()) {
+  at::Tensor tensor = ([&]() {
+    at::AutoDispatchBelowAutograd guard;  // TODO: remove
+    at::tracer::impl::NoTracerDispatchMode tracer_guard;
+    return at::from_blob(data, sizes, deleter, options.requires_grad(::std::nullopt));
+  })();
+  return autograd::make_variable(tensor, options.requires_grad());
+}
+
+/// Exposes the given `data` as a `Tensor` without taking ownership of the
+/// original data. `sizes` should specify the shape of the tensor. The
+/// `TensorOptions` specify additional configuration options for the returned
+/// tensor, such as what type to interpret the `data` as.
+inline at::Tensor from_blob(
+    void* data,
+    at::IntArrayRef sizes,
+    const at::TensorOptions& options = at::TensorOptions()) {
+  at::Tensor tensor = ([&]() {
+    at::AutoDispatchBelowAutograd guard;  // TODO: remove
+    at::tracer::impl::NoTracerDispatchMode tracer_guard;
+    return at::from_blob(data, sizes, options.requires_grad(::std::nullopt));
+  })();
+  return autograd::make_variable(tensor, options.requires_grad());
+}
+
+${function_definitions}
+
+} // namespace torch
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/selective_build/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/selective_build/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/selective_build/operator.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/selective_build/operator.py
new file mode 100644
index 0000000000000000000000000000000000000000..8047f033e3d2b0209e03924b355e94a06eceace6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/selective_build/operator.py
@@ -0,0 +1,171 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+
+# This class holds information about a single operator used to determine
+# the outcome of a selective/custom PyTorch build that doesn't include
+# registration code for all the supported operators. This is done to
+# reduce the size of the generated binary so that it can be deployed in
+# situations where binary size comes at a premium.
+#
+@dataclass(frozen=True)
+class SelectiveBuildOperator:
+    # The name of the operator. This includes the aten::, etc... prefix
+    # The operator name may or may not have the overload name. If this
+    # operator name does not specify an overload name, the way to determine
+    # if this entry refers to the family of operators with this base name
+    # or just the operator with this name is to look at the value of the
+    # 'include_all_overloads' flag in this class.
+    name: str
+
+    # True if this is a root operator (i.e. called directly from a
+    # TorchScript model, etc...). An operator is considered to be a
+    # root operator if it is called directly from any one of the models
+    # that this instance of the pytorch library was built for. Hence, it
+    # may not be a root operator in all of the models that are used in
+    # this instance of the pytorch library.
+    is_root_operator: bool
+
+    # Is this operator used for on-device training? If True, then we need to
+    # use the information to generate code in VariableType_N.cpp for registration
+    # of training related operators. Again, this is True if this operator
+    # is used for training in one or more models used by this instance of the
+    # pytorch library.
+    is_used_for_training: bool
+
+    # If True, it indicates that this operator instance (object) refers to an
+    # operator without the overload name and should apply to all overloads
+    # which have this operator name as the base name. This flag is applicable
+    # only for objects that have operator names without a DOT (period) character
+    # in them.
+    #
+    # Note: This flag is a temporary workaround to grandfather in the current
+    # static selective (custom) build mechanism, which largely ignores overload
+    # names when determining whether to select operators for registration
+    # purposes.
+    include_all_overloads: bool
+
+    # Debug Information at the operator level
+    _debug_info: tuple[str, ...] | None
+
+    @staticmethod
+    def from_yaml_dict(
+        op_name: str, op_info: dict[str, object]
+    ) -> SelectiveBuildOperator:
+        allowed_keys = {
+            "name",
+            "is_root_operator",
+            "is_used_for_training",
+            "include_all_overloads",
+            "debug_info",
+        }
+
+        if len(set(op_info.keys()) - allowed_keys) > 0:
+            raise Exception(  # noqa: TRY002
+                "Got unexpected top level keys: {}".format(
+                    ",".join(set(op_info.keys()) - allowed_keys),
+                )
+            )
+
+        if "name" in op_info:
+            assert op_name == op_info["name"]
+
+        is_root_operator = op_info.get("is_root_operator", True)
+        assert isinstance(is_root_operator, bool)
+
+        is_used_for_training = op_info.get("is_used_for_training", True)
+        assert isinstance(is_used_for_training, bool)
+
+        include_all_overloads = op_info.get("include_all_overloads", True)
+        assert isinstance(include_all_overloads, bool)
+
+        debug_info: tuple[str, ...] | None = None
+        if "debug_info" in op_info:
+            di_list = op_info["debug_info"]
+            assert isinstance(di_list, list)
+            debug_info = tuple(str(x) for x in di_list)
+
+        return SelectiveBuildOperator(
+            name=op_name,
+            is_root_operator=is_root_operator,
+            is_used_for_training=is_used_for_training,
+            include_all_overloads=include_all_overloads,
+            _debug_info=debug_info,
+        )
+
+    @staticmethod
+    def from_legacy_operator_name_without_overload(
+        name: str,
+    ) -> SelectiveBuildOperator:
+        return SelectiveBuildOperator(
+            name=name,
+            is_root_operator=True,
+            is_used_for_training=True,
+            include_all_overloads=True,
+            _debug_info=None,
+        )
+
+    def to_dict(self) -> dict[str, object]:
+        ret: dict[str, object] = {
+            "is_root_operator": self.is_root_operator,
+            "is_used_for_training": self.is_used_for_training,
+            "include_all_overloads": self.include_all_overloads,
+        }
+        if self._debug_info is not None:
+            ret["debug_info"] = self._debug_info
+
+        return ret
+
+
+def merge_debug_info(
+    lhs: tuple[str, ...] | None,
+    rhs: tuple[str, ...] | None,
+) -> tuple[str, ...] | None:
+    # Ensure that when merging, each entry shows up just once.
+    if lhs is None and rhs is None:
+        return None
+
+    return tuple(set((lhs or ()) + (rhs or ())))
+
+
+def combine_operators(
+    lhs: SelectiveBuildOperator, rhs: SelectiveBuildOperator
+) -> SelectiveBuildOperator:
+    if str(lhs.name) != str(rhs.name):
+        raise Exception(  # noqa: TRY002
+            f"Expected both arguments to have the same name, but got '{str(lhs.name)}' and '{str(rhs.name)}' instead"
+        )
+
+    return SelectiveBuildOperator(
+        name=lhs.name,
+        # Consider this operator to be a root operator if it is a
+        # root operator in any of the models used in this instance of
+        # the pytorch library.
+        is_root_operator=lhs.is_root_operator or rhs.is_root_operator,
+        # Consider this operator to be a training operator if it is
+        # an operator used for training in any of the models used
+        # in this instance of the pytorch library.
+        is_used_for_training=lhs.is_used_for_training or rhs.is_used_for_training,
+        include_all_overloads=lhs.include_all_overloads or rhs.include_all_overloads,
+        _debug_info=merge_debug_info(lhs._debug_info, rhs._debug_info),
+    )
+
+
+def merge_operator_dicts(
+    lhs: dict[str, SelectiveBuildOperator],
+    rhs: dict[str, SelectiveBuildOperator],
+) -> dict[str, SelectiveBuildOperator]:
+    operators: dict[str, SelectiveBuildOperator] = {}
+    for op_name, op in list(lhs.items()) + list(rhs.items()):
+        new_op = op
+        if op_name in operators:
+            new_op = combine_operators(operators[op_name], op)
+
+        operators[op_name] = new_op
+
+    return operators
+
+
+def strip_operator_overload_name(op_name: str) -> str:
+    return op_name.split(".", maxsplit=1)[0]
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/selective_build/selector.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/selective_build/selector.py
new file mode 100644
index 0000000000000000000000000000000000000000..04acc354203ade2f48dcef56fd9d9ef70c82ad1d
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/selective_build/selector.py
@@ -0,0 +1,352 @@
+from __future__ import annotations
+
+from collections import defaultdict
+from collections.abc import Iterable
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+import yaml
+
+from torchgen.selective_build.operator import (
+    merge_debug_info,
+    merge_operator_dicts,
+    SelectiveBuildOperator,
+    strip_operator_overload_name,
+)
+
+
+if TYPE_CHECKING:
+    from torchgen.model import NativeFunction
+
+
+# A SelectiveBuilder holds information extracted from the selective build
+# YAML specification.
+#
+# It includes information about the build's selectivity, the debug_info
+# associated with this selective build (opaque string), and the set of
+# operators that should be included in the build.
+#
+@dataclass(frozen=True)
+class SelectiveBuilder:
+    # If true, then the build is not selective, and includes all
+    # operators.
+    include_all_operators: bool
+
+    # Debug Information at the selective/custom build level.
+    _debug_info: tuple[str, ...] | None
+
+    # A dictionary of operator -> operator metadata.
+    operators: dict[str, SelectiveBuildOperator]
+
+    # A dictionary of selected kernel tags and dtypes. Typically a
+    # PyTorch Operator Kernel (function) may have many code paths
+    # that are specialized for many many Tensor dtypes, so it's not
+    # one per kernel function, but there could be many per kernel
+    # function. The tag isn't a kernel function name, but some fragment
+    # of the kernel function implementation itself.
+    kernel_metadata: dict[str, list[str]]
+
+    # ExecuTorch only. A dictionary of kernel tag -> list of (list of input
+    # dtypes for tensor-like input args).
+    # This is from selective.yaml
+    et_kernel_metadata: dict[str, list[str]]
+
+    # A set of all the custom torch bind classes used by the selected models
+    # Stored as a set internally to remove duplicates proactively, but written
+    # as a list to yamls
+    custom_classes: set[str]
+
+    # A set of all the build features used by the selected models
+    # Stored as a set internally to remove duplicates proactively, but written
+    # as a list to yamls
+    build_features: set[str]
+
+    # If true, then fragments for all dtypes for all kernel functions
+    # are included as well as all custom classes. This is typically set when any one of the
+    # operator lists is generated from a mechanism other than
+    # tracing based selective build.
+    include_all_non_op_selectives: bool
+
+    @staticmethod
+    def get_nop_selector() -> SelectiveBuilder:
+        return SelectiveBuilder.from_yaml_dict({"include_all_operators": True})
+
+    @staticmethod
+    def from_yaml_dict(data: dict[str, object]) -> SelectiveBuilder:
+        valid_top_level_keys = {
+            "include_all_non_op_selectives",
+            "include_all_operators",
+            "debug_info",
+            "operators",
+            "kernel_metadata",
+            "et_kernel_metadata",
+            "custom_classes",
+            "build_features",
+        }
+        top_level_keys = set(data.keys())
+        if len(top_level_keys - valid_top_level_keys) > 0:
+            raise Exception(  # noqa: TRY002
+                "Got unexpected top level keys: {}".format(
+                    ",".join(top_level_keys - valid_top_level_keys),
+                )
+            )
+        include_all_operators = data.get("include_all_operators", False)
+        assert isinstance(include_all_operators, bool)
+
+        debug_info = None
+        if "debug_info" in data:
+            di_list = data["debug_info"]
+            assert isinstance(di_list, list)
+
+            debug_info = tuple(str(x) for x in di_list)
+
+        operators = {}
+        operators_dict = data.get("operators", {})
+        assert isinstance(operators_dict, dict)
+
+        for k, v in operators_dict.items():
+            operators[k] = SelectiveBuildOperator.from_yaml_dict(k, v)
+
+        kernel_metadata = {}
+        kernel_metadata_dict = data.get("kernel_metadata", {})
+        assert isinstance(kernel_metadata_dict, dict)
+
+        for k, v in kernel_metadata_dict.items():
+            kernel_metadata[str(k)] = [str(dtype) for dtype in v]
+
+        et_kernel_metadata = data.get("et_kernel_metadata", {})
+        assert isinstance(et_kernel_metadata, dict)
+
+        custom_classes = data.get("custom_classes", [])
+        assert isinstance(custom_classes, Iterable)
+        custom_classes = set(custom_classes)
+
+        build_features = data.get("build_features", [])
+        assert isinstance(build_features, Iterable)
+        build_features = set(build_features)
+
+        include_all_non_op_selectives = data.get("include_all_non_op_selectives", False)
+        assert isinstance(include_all_non_op_selectives, bool)
+
+        return SelectiveBuilder(
+            include_all_operators,
+            debug_info,
+            operators,
+            kernel_metadata,
+            et_kernel_metadata,
+            custom_classes,  # type: ignore[arg-type]
+            build_features,  # type: ignore[arg-type]
+            include_all_non_op_selectives,
+        )
+
+    @staticmethod
+    def from_yaml_str(config_contents: str) -> SelectiveBuilder:
+        contents = yaml.safe_load(config_contents)
+        return SelectiveBuilder.from_yaml_dict(contents)
+
+    @staticmethod
+    def from_yaml_path(config_path: str) -> SelectiveBuilder:
+        with open(config_path) as f:
+            contents = yaml.safe_load(f)
+            return SelectiveBuilder.from_yaml_dict(contents)
+
+    @staticmethod
+    def from_legacy_op_registration_allow_list(
+        allow_list: set[str], is_root_operator: bool, is_used_for_training: bool
+    ) -> SelectiveBuilder:
+        operators = {}
+        for op in allow_list:
+            operators[op] = {
+                "name": op,
+                "is_root_operator": is_root_operator,
+                "is_used_for_training": is_used_for_training,
+                "include_all_overloads": True,
+            }
+        return SelectiveBuilder.from_yaml_dict(
+            {
+                "operators": operators,
+                "include_all_non_op_selectives": True,
+            }
+        )
+
+    def is_operator_selected(self, name: str) -> bool:
+        if self.include_all_operators:
+            return True
+
+        if name in self.operators:
+            return True
+        name = strip_operator_overload_name(name)
+        return name in self.operators and self.operators[name].include_all_overloads
+
+    def is_native_function_selected(self, func: NativeFunction) -> bool:
+        op_name = op_name_from_native_function(func)
+        return self.is_operator_selected(op_name)
+
+    def is_operator_selected_for_training(self, name: str) -> bool:
+        if not self.is_operator_selected(name):
+            return False
+        if self.include_all_operators:
+            return True
+
+        not_training_op = SelectiveBuildOperator(
+            name="",
+            is_root_operator=False,
+            is_used_for_training=False,
+            include_all_overloads=False,
+            _debug_info=None,
+        )
+        op = not_training_op
+        if name in self.operators:
+            op = self.operators[name]
+
+        name = strip_operator_overload_name(name)
+        base_op = not_training_op
+        if name in self.operators:
+            base_op = self.operators[name]
+
+        return op.is_used_for_training or (
+            base_op.include_all_overloads and base_op.is_used_for_training
+        )
+
+    def is_native_function_selected_for_training(self, func: NativeFunction) -> bool:
+        op_name = op_name_from_native_function(func)
+        return self.is_operator_selected_for_training(op_name)
+
+    def is_root_operator(self, name: str) -> bool:
+        if not self.is_operator_selected(name):
+            return False
+        if self.include_all_operators:
+            return True
+
+        if name in self.operators:
+            op: SelectiveBuildOperator = self.operators[name]
+            return op.is_root_operator
+        name = strip_operator_overload_name(name)
+        if name not in self.operators:
+            return False
+        base_op: SelectiveBuildOperator = self.operators[name]
+        return base_op.include_all_overloads and base_op.is_root_operator
+
+    def is_kernel_dtype_selected(self, kernel_tag: str, dtype: str) -> bool:
+        if self.include_all_operators or self.include_all_non_op_selectives:
+            return True
+
+        return (
+            kernel_tag in self.kernel_metadata
+            and dtype in self.kernel_metadata[kernel_tag]
+        )
+
+    def et_get_selected_kernels(self, op_name: str, kernel_key: list[str]) -> list[str]:
+        """
+        Return a list of kernel keys that cover the used ops
+        """
+        # If no kernel metadata, either it's implied by include_all_operators=True or the op is not used.
+        if op_name not in self.et_kernel_metadata:
+            return kernel_key if self.include_all_operators else []
+        # Otherwise, only return the specific kernel keys.
+
+        result_set = set()
+
+        for model_kernel_keys in self.et_kernel_metadata[op_name]:
+            key_found = False
+            for key in kernel_key:
+                # Don't compare the version for now
+                if (
+                    key != "default"
+                    and key.split("/")[1] == model_kernel_keys.split("/")[1]
+                ):
+                    result_set.add(key)
+                    key_found = True
+                    break
+            if not key_found:
+                if "default" not in kernel_key:
+                    raise Exception("Missing kernel for the model")  # noqa: TRY002
+                else:
+                    result_set.add("default")
+
+        return list(result_set)
+
+    def to_dict(self) -> dict[str, object]:
+        ret: dict[str, object] = {
+            "include_all_non_op_selectives": self.include_all_non_op_selectives,
+            "include_all_operators": self.include_all_operators,
+        }
+        operators = {}
+        for op_name, op in self.operators.items():
+            operators[op_name] = op.to_dict()
+        ret["operators"] = operators
+
+        if self._debug_info is not None:
+            ret["debug_info"] = sorted(self._debug_info)
+
+        ret["kernel_metadata"] = {
+            k: sorted(v) for (k, v) in self.kernel_metadata.items()
+        }
+
+        ret["et_kernel_metadata"] = self.et_kernel_metadata
+
+        ret["custom_classes"] = sorted(self.custom_classes)
+
+        ret["build_features"] = sorted(self.build_features)
+
+        return ret
+
+
+def merge_kernel_metadata(
+    lhs: dict[str, list[str]],
+    rhs: dict[str, list[str]],
+) -> dict[str, list[str]]:
+    kernel_metadata: dict[str, list[str]] = {}
+    for tag_name, dtypes in list(lhs.items()) + list(rhs.items()):
+        dtypes_copy = set(dtypes)
+        if tag_name in kernel_metadata:
+            dtypes_copy |= set(kernel_metadata[tag_name])
+
+        kernel_metadata[tag_name] = list(dtypes_copy)
+
+    return kernel_metadata
+
+
+def merge_et_kernel_metadata(
+    lhs: dict[str, list[str]],
+    rhs: dict[str, list[str]],
+) -> dict[str, list[str]]:
+    merge_et_kernel_metadata: dict[str, set[str]] = defaultdict(set)
+    for op in list(lhs.keys()) + list(rhs.keys()):
+        merge_et_kernel_metadata[op].update(lhs.get(op, []))
+        merge_et_kernel_metadata[op].update(rhs.get(op, []))
+
+    return {op: sorted(val) for op, val in merge_et_kernel_metadata.items()}
+
+
+def combine_selective_builders(
+    lhs: SelectiveBuilder, rhs: SelectiveBuilder
+) -> SelectiveBuilder:
+    include_all_operators = lhs.include_all_operators or rhs.include_all_operators
+    debug_info = merge_debug_info(lhs._debug_info, rhs._debug_info)
+    operators = merge_operator_dicts(lhs.operators, rhs.operators)
+    kernel_metadata = merge_kernel_metadata(lhs.kernel_metadata, rhs.kernel_metadata)
+    et_kernel_metadata = merge_et_kernel_metadata(
+        lhs.et_kernel_metadata, rhs.et_kernel_metadata
+    )
+    include_all_non_op_selectives = (
+        lhs.include_all_non_op_selectives or rhs.include_all_non_op_selectives
+    )
+    custom_classes = lhs.custom_classes.union(rhs.custom_classes)
+    build_features = lhs.build_features.union(rhs.build_features)
+    return SelectiveBuilder(
+        include_all_operators,
+        debug_info,
+        operators,
+        kernel_metadata,
+        et_kernel_metadata,
+        custom_classes,
+        build_features,
+        include_all_non_op_selectives,
+    )
+
+
+def op_name_from_native_function(f: NativeFunction) -> str:
+    # This was originally read from the 'operator_name_with_overload' field in the
+    # declaration dict, which was the part before the first '(' in 'schema_string'.
+    return f"{f.namespace}::{f.func.name}"
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/static_runtime/__init__.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/static_runtime/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/static_runtime/config.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/static_runtime/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fe129f9754dd83a136fbf9dc4478e04a2242efa
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/static_runtime/config.py
@@ -0,0 +1,388 @@
+from __future__ import annotations
+
+from torchgen.model import NativeFunctionsGroup, NativeFunctionsViewGroup
+
+
+def func_name_base_str(g: NativeFunctionsGroup | NativeFunctionsViewGroup) -> str:
+    if isinstance(g, NativeFunctionsGroup):
+        return str(g.functional.func.name.name.base)
+    else:
+        return str(g.view.root_name)
+
+
+is_hand_written_ops_ = frozenset(
+    (
+        "abs",
+        "add",
+        "addmm",
+        "all",
+        "any",
+        "argmin",
+        "bmm",
+        "clamp",
+        "clamp_min",
+        "cumsum",
+        "div",
+        "fmod",
+        "index_select",
+        "leaky_relu",
+        "linear",
+        "log",
+        "matmul",
+        "mul",
+        "narrow_copy",
+        "nonzero",
+        "pow",
+        "remainder",
+        "sigmoid",
+        "sign",
+        "sub",
+        "tanh",
+        "detach",
+        "expand_as",
+        "flatten",
+        "narrow",
+        "reshape_as",
+        "select",
+        "slice",
+        "softmax",
+        "split",
+        "squeeze",
+        "transpose",
+        "view",
+        "where",
+    )
+)
+
+
+def is_hand_written(g: NativeFunctionsGroup | NativeFunctionsViewGroup) -> bool:
+    name_base = func_name_base_str(g)
+    return name_base in is_hand_written_ops_
+
+
+def override_test_values(arg_map: dict[str, str], op_name: str, index: int) -> None:
+    assert index == 0 or index == 1
+    if op_name == "addr":
+        if index == 0:
+            arg_map["self"] = "at::rand({6, 6})"
+            arg_map["vec1"] = "at::rand({6})"
+            arg_map["vec2"] = "at::rand({6})"
+        else:
+            arg_map["self"] = "at::rand({22, 22})"
+            arg_map["vec1"] = "at::rand({22})"
+            arg_map["vec2"] = "at::rand({22})"
+        return
+    if op_name == "mv":
+        if index == 0:
+            arg_map["self"] = "at::rand({6, 6})"
+            arg_map["vec"] = "at::rand({6})"
+        else:
+            arg_map["self"] = "at::rand({22, 22})"
+            arg_map["vec"] = "at::rand({22})"
+        return
+    if op_name == "addbmm":
+        if index == 0:
+            arg_map["self"] = "at::rand({6, 6})"
+        else:
+            arg_map["self"] = "at::rand({22, 22})"
+        return
+    if op_name == "cross":
+        if index == 0:
+            arg_map["self"] = "at::rand({3, 3, 3})"
+            arg_map["other"] = "at::rand({3, 3, 3})"
+        else:
+            arg_map["self"] = "at::rand({22, 3, 22})"
+            arg_map["other"] = "at::rand({22, 3, 22})"
+        return
+    if op_name == "take":
+        if index == 0:
+            arg_map["index"] = "at::randint(0, 216, {20}, torch::kInt64)"
+        else:
+            arg_map["index"] = "at::randint(0, 1000, {100}, torch::kInt64)"
+        return
+    if op_name == "take_along_dim":
+        if index == 0:
+            arg_map["indices"] = "at::argsort(self0, 1, true)"
+        else:
+            arg_map["indices"] = "at::argsort(self1, 1, true)"
+        return
+    if op_name == "masked_select":
+        if index == 0:
+            arg_map["mask"] = "at::randn({6, 6, 6}) > 0.5"
+        else:
+            arg_map["mask"] = "at::rand({22, 22, 22}) > 0.5"
+        return
+    if op_name == "orgqr":
+        if index == 0:
+            arg_map["input2"] = "at::rand({6, 6})"
+        else:
+            arg_map["input2"] = "at::rand({22, 22})"
+        return
+    if op_name == "ormqr":
+        if index == 0:
+            arg_map["input2"] = "at::rand({6, 6})"
+        else:
+            arg_map["input2"] = "at::rand({22, 22})"
+        return
+    if op_name == "quantile":
+        if index == 0:
+            arg_map["q"] = "at::rand({6})"
+            arg_map["interpolation"] = '"linear"'
+        else:
+            arg_map["q"] = "at::rand({22})"
+            arg_map["interpolation"] = '"linear"'
+        return
+    if op_name == "nanquantile":
+        if index == 0:
+            arg_map["q"] = "at::rand({6})"
+            arg_map["interpolation"] = '"linear"'
+        else:
+            arg_map["q"] = "at::rand({22})"
+            arg_map["interpolation"] = '"linear"'
+        return
+    if op_name == "multi_margin_loss":
+        if index == 0:
+            arg_map["self"] = "at::rand({6, 6})"
+            arg_map["target"] = "at::randint(6, {6}, torch::kInt64)"
+            arg_map["weight"] = "at::rand({6})"
+        else:
+            arg_map["self"] = "at::rand({22, 22})"
+            arg_map["target"] = "at::randint(22, {22}, torch::kInt64)"
+            arg_map["weight"] = "at::rand({22})"
+        return
+    if op_name == "multilabel_margin_loss":
+        if index == 0:
+            arg_map["self"] = "at::rand({6, 6})"
+            arg_map["target"] = "at::randint(6, {6, 6}, torch::kInt64)"
+        else:
+            arg_map["self"] = "at::rand({22, 22})"
+            arg_map["target"] = "at::randint(22, {22, 22}, torch::kInt64)"
+        return
+    if op_name == "nll_loss":
+        if index == 0:
+            arg_map["self"] = "at::rand({6, 6})"
+            arg_map["target"] = "at::randint(6, {6}, torch::kInt64)"
+            arg_map["weight"] = "at::rand({6})"
+        else:
+            arg_map["self"] = "at::rand({22, 22})"
+            arg_map["target"] = "at::randint(22, {22}, torch::kInt64)"
+            arg_map["weight"] = "at::rand({22})"
+        return
+    if op_name == "nll_loss2d":
+        if index == 0:
+            arg_map["self"] = "at::rand({6, 6, 6, 6})"
+            arg_map["target"] = "at::randint(6, {6, 6, 6}, torch::kInt64)"
+            arg_map["weight"] = "at::rand({6})"
+        else:
+            arg_map["self"] = "at::rand({22, 22, 22, 22})"
+            arg_map["target"] = "at::randint(22, {22, 22, 22}, torch::kInt64)"
+            arg_map["weight"] = "at::rand({22})"
+        return
+    if op_name in (
+        "fft_fft",
+        "fft_ifft",
+        "fft_rfft",
+        "fft_irfft",
+        "fft_hfft",
+        "fft_ihfft",
+    ):
+        arg_map["norm"] = '"forward"'
+        return
+    if op_name == "linalg_tensorinv":
+        if index == 0:
+            arg_map["self"] = "at::rand({6, 6, 6, 6})"
+            arg_map["ind"] = "2"
+        else:
+            arg_map["self"] = "at::rand({22, 22, 22, 22})"
+            arg_map["ind"] = "2"
+        return
+    if op_name == "addmv":
+        if index == 0:
+            arg_map["self"] = "at::rand({2})"
+            arg_map["mat"] = "at::rand({2, 2})"
+            arg_map["vec"] = "at::rand({2})"
+        else:
+            arg_map["self"] = "at::rand({35})"
+            arg_map["mat"] = "at::rand({35, 35})"
+            arg_map["vec"] = "at::rand({35})"
+        return
+    if op_name == "acosh":
+        if index == 0:
+            arg_map["self"] = "at::rand({2, 2, 2}) + at::ones({2, 2, 2})"
+        else:
+            arg_map["self"] = "at::rand({5, 5, 5}) + at::ones({5, 5, 5})"
+        return
+    if op_name == "adaptive_max_pool2d_backward":
+        if index == 0:
+            arg_map["grad_output"] = "at::rand({2, 2, 2}, at::kFloat)"
+            arg_map["self"] = "at::rand({2, 2, 2}, at::kFloat)"
+            arg_map["indices"] = "at::randint(0, 1, {2, 2, 2}, at::kLong)"
+        else:
+            arg_map["grad_output"] = "at::rand({3, 3, 3}, at::kFloat)"
+            arg_map["self"] = "at::rand({3, 3, 3}, at::kFloat)"
+            arg_map["indices"] = "at::randint(0, 1, {3, 3, 3}, at::kLong)"
+        return
+    if op_name == "adaptive_max_pool3d_backward":
+        if index == 0:
+            arg_map["grad_output"] = "at::rand({2, 2, 2, 2}, at::kFloat)"
+            arg_map["self"] = "at::rand({2, 2, 2, 2}, at::kFloat)"
+            arg_map["indices"] = "at::randint(0, 1, {2, 2, 2, 2}, at::kLong)"
+        else:
+            arg_map["grad_output"] = "at::rand({3, 3, 3, 3}, at::kFloat)"
+            arg_map["self"] = "at::rand({3, 3, 3, 3}, at::kFloat)"
+            arg_map["indices"] = "at::randint(0, 1, {3, 3, 3, 3}, at::kLong)"
+        return
+    if op_name == "bitwise_left_shift":
+        if index == 0:
+            arg_map["self"] = "at::randint(1, 1 << 4, {6, 6, 6}, at::kInt)"
+            arg_map["other"] = "at::randint(1, 26, {6, 6, 6}, at::kInt)"
+        else:
+            arg_map["self"] = "at::randint(1, 1 << 4, {22, 22, 22}, at::kInt)"
+            arg_map["other"] = "at::randint(1, 26, {22, 22, 22}, at::kInt)"
+        return
+    if op_name == "bitwise_right_shift":
+        if index == 0:
+            arg_map["self"] = "at::randint(1 << 21, 1 << 30, {6, 6, 6}, at::kInt)"
+            arg_map["other"] = "at::randint(1, 22, {6, 6, 6}, at::kInt)"
+        else:
+            arg_map["self"] = "at::randint(1 << 21, 1 << 30, {22, 22, 22}, at::kInt)"
+            arg_map["other"] = "at::randint(1, 22, {22, 22, 22}, at::kInt)"
+        return
+    if op_name == "gather":
+        if index == 0:
+            arg_map["self"] = "at::randint(1, 100, {2,2,2}, at::kInt)"
+            arg_map["dim"] = "1"
+            arg_map["index"] = "at::randint(0, 1, {2,2,2}, torch::kInt64)"
+            arg_map["sparse_grad"] = "false"
+        else:
+            arg_map["self"] = "at::randint(1, 100, {5,5,5}, at::kInt)"
+            arg_map["dim"] = "1"
+            arg_map["index"] = "at::randint(0, 4, {5,5,5}, torch::kInt64)"
+            arg_map["sparse_grad"] = "false"
+        return
+    if op_name == "gelu":
+        if index == 0:
+            arg_map["self"] = "at::rand({6, 6, 6})"
+            arg_map["approximate"] = '"tanh"'
+        else:
+            arg_map["self"] = "at::rand({22, 22, 22})"
+            arg_map["approximate"] = '"tanh"'
+        return
+    if op_name == "gelu_backward":
+        if index == 0:
+            arg_map["grad_output"] = "at::rand({6, 6, 6})"
+            arg_map["self"] = "at::rand({6, 6, 6})"
+            arg_map["approximate"] = '"tanh"'
+        else:
+            arg_map["grad_output"] = "at::rand({22, 22, 22})"
+            arg_map["self"] = "at::rand({22, 22, 22})"
+            arg_map["approximate"] = '"tanh"'
+        return
+    if op_name == "index_add":
+        if index == 0:
+            arg_map["self"] = "at::rand({2})"
+            arg_map["dim"] = "0"
+            arg_map["index"] = "at::randint(0, 1, {2}, at::kInt)"
+            arg_map["source"] = "at::rand({2})"
+            arg_map["alpha"] = "2"
+        else:
+            arg_map["self"] = "at::rand({16})"
+            arg_map["dim"] = "0"
+            arg_map["index"] = "at::randint(0, 10, {16}, at::kInt)"
+            arg_map["source"] = "at::rand({16})"
+            arg_map["alpha"] = "2"
+        return
+    if op_name == "index_copy":
+        if index == 0:
+            arg_map["self"] = "at::rand({2})"
+            arg_map["dim"] = "0"
+            arg_map["index"] = "at::randint(0, 1, {2}, at::kLong)"
+            arg_map["source"] = "at::rand({2})"
+        else:
+            arg_map["self"] = "at::rand({32})"
+            arg_map["dim"] = "0"
+            arg_map["index"] = "at::randint(0, 10, {32}, at::kLong)"
+            arg_map["source"] = "at::rand({32})"
+        return
+    if op_name == "linalg_cross":
+        if index == 0:
+            arg_map["self"] = "at::rand({6, 3, 6})"
+            arg_map["other"] = "at::rand({6, 3, 6})"
+            arg_map["dim"] = "1"
+        else:
+            arg_map["self"] = "at::rand({22, 3, 22})"
+            arg_map["other"] = "at::rand({22, 3, 22})"
+            arg_map["dim"] = "1"
+        return
+    if op_name == "nll_loss_backward":
+        if index == 0:
+            arg_map["grad_output"] = "at::rand({})"
+            arg_map["self"] = "at::rand({6})"
+            arg_map["target"] = "at::randint(0, 5, {6}, torch::kInt64)"
+            arg_map["weight"] = "at::rand({6})"
+            arg_map["reduction"] = "1"
+            arg_map["ignore_index"] = "1"
+            arg_map["total_weight"] = "at::rand({})"
+        else:
+            arg_map["grad_output"] = "at::rand({})"
+            arg_map["self"] = "at::rand({36})"
+            arg_map["target"] = "at::randint(0, 11, {36}, torch::kInt64)"
+            arg_map["weight"] = "at::rand({36})"
+            arg_map["reduction"] = "1"
+            arg_map["ignore_index"] = "1"
+            arg_map["total_weight"] = "at::rand({})"
+        return
+    if op_name in ["scatter", "scatter_add", "_scatter_reduce"]:
+        if index == 0:
+            arg_map["self"] = "at::randint(1, 100, {2,2,2}, torch::kInt64)"
+            arg_map["index"] = "at::randint(0, 1, {2,2,2}, torch::kInt64)"
+            arg_map["src"] = "at::randint(1, 100, {2,2,2}, torch::kInt64)"
+        else:
+            arg_map["self"] = "at::randint(1, 100, {5,5,5}, torch::kInt64)"
+            arg_map["index"] = "at::randint(0, 1, {5,5,5}, torch::kInt64)"
+            arg_map["src"] = "at::randint(1, 100, {5,5,5}, torch::kInt64)"
+        if "reduce" in arg_map:
+            arg_map["reduce"] = '"sum"' if op_name == "_scatter_reduce" else '"add"'
+        return
+    if op_name == "scatter_reduce":
+        arg_map["reduce"] = '"mean"'
+        if index == 0:
+            arg_map["index"] = "at::randint(6, {6, 6, 6}, torch::kInt64)"
+        else:
+            arg_map["index"] = "at::randint(22, {22, 22, 22}, torch::kInt64)"
+        return
+    if op_name == "special_zeta":
+        if index == 0:
+            arg_map["self"] = "at::rand({2,2,2}, at::kDouble) + at::ones({2,2,2})"
+            arg_map["other"] = "at::rand({2,2,2}, at::kDouble) + at::ones({2,2,2})"
+        else:
+            arg_map["self"] = "at::rand({5,5,5}, at::kDouble) + at::ones({5,5,5})"
+            arg_map["other"] = "at::rand({5,5,5}, at::kDouble) + at::ones({5,5,5})"
+        return
+    if op_name == "_convert_indices_from_csr_to_coo":
+        if index == 0:
+            arg_map["crow_indices"] = "torch::tensor({1}, torch::kInt32)"
+            arg_map["col_indices"] = "torch::tensor({0, 1, 0}, torch::kInt32)"
+            arg_map["out_int32"] = "false"
+        else:
+            arg_map["crow_indices"] = "torch::tensor({0}, torch::kInt32)"
+            arg_map["col_indices"] = (
+                "torch::tensor({0, 1, 0, 2, 1, 2, 0, 1, 0, 2, 1, 2}, torch::kInt32)"
+            )
+            arg_map["out_int32"] = "false"
+        return
+    if op_name == "_convert_indices_from_coo_to_csr":
+        if index == 0:
+            arg_map["self"] = "at::randint(0, 3, {2}, at::kInt)"
+            arg_map["size"] = "10"
+            arg_map["out_int32"] = "false"
+        else:
+            arg_map["self"] = "at::randint(0, 3, {12}, at::kInt)"
+            arg_map["size"] = "24"
+            arg_map["out_int32"] = "false"
+        return
+    if op_name in ("diagonal", "linalg_diagonal"):
+        arg_map["offset"] = "0"
+        arg_map["dim1"] = "2"
+        arg_map["dim2"] = "1"
+        return
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/static_runtime/gen_static_runtime_ops.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/static_runtime/gen_static_runtime_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..e35221c3f50eb4ae61acc219e01b512bf9615e00
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/static_runtime/gen_static_runtime_ops.py
@@ -0,0 +1,231 @@
+from __future__ import annotations
+
+import argparse
+import itertools
+import os
+from typing import TYPE_CHECKING, TypeVar, Union
+
+from libfb.py.log import set_simple_logging  # type: ignore[import]
+
+from torchgen import gen
+from torchgen.context import native_function_manager
+from torchgen.model import DispatchKey, NativeFunctionsGroup, NativeFunctionsViewGroup
+from torchgen.static_runtime import config, generator
+
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+
+
+# Given a list of `grouped_native_functions` sorted by their op names, return a list of
+# lists each of which groups ops that share the base name. For example, `mean` and
+# `mean.dim` are grouped together by this function.
+
+NativeGroupT = TypeVar(
+    "NativeGroupT",
+    bound=Union[NativeFunctionsGroup, NativeFunctionsViewGroup],
+)
+
+
+def group_functions_by_op_name(
+    grouped_native_functions: Sequence[NativeGroupT],
+) -> Sequence[Sequence[NativeGroupT]]:
+    if not grouped_native_functions:
+        return []
+    groups = []
+
+    def is_supported(g: NativeFunctionsGroup | NativeFunctionsViewGroup) -> bool:
+        with native_function_manager(g):
+            return generator.is_supported(g)
+
+    eligible_ops = (g for g in grouped_native_functions if is_supported(g))
+    groups = [
+        list(group)
+        for k, group in (
+            itertools.groupby(
+                eligible_ops,
+                key=config.func_name_base_str,
+            )
+        )
+    ]
+
+    return groups
+
+
+def clang_format(cpp_file_path: str) -> None:
+    import subprocess
+
+    subprocess.check_call(["clang-format", "-i", cpp_file_path])
+
+
+def write_cpp(cpp_ops: Sequence[str], file_path: str) -> None:
+    code = "\n".join(cpp_ops)
+    generated = f"""// @lint-ignore-every CLANGTIDY HOWTOEVEN
+// AUTO-GENERATED FROM: torchgen/static_runtime/gen_static_runtime_ops.py
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace torch {{
+namespace jit {{
+
+{code}
+
+}} // namespace jit
+}} // namespace torch
+"""
+    with open(file_path, "w") as f:
+        f.write(generated)
+    clang_format(file_path)
+
+
+def write_test_cpp(cpp_ops: Sequence[str], file_path: str) -> None:
+    code = "\n".join(cpp_ops)
+    generated = f"""// @lint-ignore-every CLANGTIDY HOWTOEVEN
+// AUTO-GENERATED FROM: torchgen/static_runtime/gen_static_runtime_ops.py
+#include 
+#include 
+#include 
+
+#include "test_utils.h"
+
+using namespace caffe2;
+using namespace torch;
+using namespace torch::jit;
+using namespace torch::jit::test;
+using c10::IValue;
+
+{code}
+
+"""
+    with open(file_path, "w") as f:
+        f.write(generated)
+    clang_format(file_path)
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser(description="Generate ATen source files")
+    parser.add_argument(
+        "-s",
+        "--source-path",
+        help="path to source directory for ATen",
+        default="caffe2/aten/src/ATen",
+    )
+    parser.add_argument(
+        "-p",
+        "--generated-ops-cpp-path",
+        help="path to directory to generate op dispatcher .cpp file",
+        default="caffe2/torch/csrc/jit/runtime/static/generated_ops.cpp",
+    )
+    parser.add_argument(
+        "-t",
+        "--generated-ops-test-cpp-path",
+        help="path to directory to generate op dispatcher .cpp file",
+        default="caffe2/benchmarks/static_runtime/test_generated_ops.cc",
+    )
+    options = parser.parse_args()
+    native_yaml_path = os.path.join(options.source_path, "native/native_functions.yaml")
+    tags_yaml_path = os.path.join(options.source_path, "native/tags.yaml")
+    parsed_yaml = gen.parse_native_yaml(native_yaml_path, tags_yaml_path)
+    native_functions, backend_indices = (
+        parsed_yaml.native_functions,
+        parsed_yaml.backend_indices,
+    )
+
+    op_generator = generator.GenOpDispatcher()
+    test_case_generator = generator.GenOpTestCase()
+
+    native_functions_groups = [
+        g
+        for g in gen.get_grouped_native_functions(native_functions)
+        if isinstance(g, NativeFunctionsGroup)
+    ]
+
+    supported_functions_groups = group_functions_by_op_name(native_functions_groups)
+
+    out_variant_op_result = [
+        op_generator.out_variant(groups, backend_indices[DispatchKey.CPU])
+        for groups in supported_functions_groups
+    ]
+    out_variant_test_result = [
+        test_case_generator.out_variant(groups) for groups in supported_functions_groups
+    ]
+
+    native_functions_view_groups = [
+        g
+        for g in gen.get_grouped_by_view_native_functions(native_functions)
+        if isinstance(g, NativeFunctionsViewGroup)
+    ]
+
+    supported_functions_view_groups = group_functions_by_op_name(
+        native_functions_view_groups
+    )
+
+    view_op_result = [
+        op_generator.view(groups, backend_indices[DispatchKey.CPU])
+        for groups in supported_functions_view_groups
+    ]
+    view_test_result = [
+        test_case_generator.view(groups) for groups in supported_functions_view_groups
+    ]
+
+    op_result = out_variant_op_result + ["\n\n"] + view_op_result
+    test_result = out_variant_test_result + ["\n\n"] + view_test_result
+
+    write_cpp(op_result, options.generated_ops_cpp_path)
+    write_test_cpp(test_result, options.generated_ops_test_cpp_path)
+
+    print(
+        f"\ntotal grouped native ops: {len(gen.get_grouped_native_functions(native_functions)):d}"
+    )
+
+    print(f"grouped native ops with out variant: {len(native_functions_groups):d}")
+    supported_functions_num = sum(len(groups) for groups in supported_functions_groups)
+    print(f"generated functions groups with out variant: {supported_functions_num:d}")
+
+    print(f"\nview grouped native ops: {len(native_functions_view_groups):d}")
+    supported_view_functions_num = sum(
+        len(groups) for groups in supported_functions_view_groups
+    )
+    print(f"generated functions view groups: {supported_view_functions_num:d}")
+
+    print(
+        f"\noverall generated : {supported_functions_num + supported_view_functions_num:d}"
+    )
+
+
+if __name__ == "__main__":
+    set_simple_logging(escape_newlines=False)
+    main()
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/static_runtime/generator.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/static_runtime/generator.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ad2fd3c458892568429f86e5cd53c26982b38fd
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/static_runtime/generator.py
@@ -0,0 +1,814 @@
+from __future__ import annotations
+
+import json
+import logging
+import math
+from typing import TYPE_CHECKING
+
+import torchgen.api.cpp as cpp
+from torchgen.context import native_function_manager
+from torchgen.model import (
+    Argument,
+    BackendIndex,
+    BaseTy,
+    BaseType,
+    FunctionSchema,
+    NativeFunctionsGroup,
+    NativeFunctionsViewGroup,
+    OptionalType,
+    SelfArgument,
+    TensorOptionsArguments,
+    Type,
+)
+from torchgen.static_runtime import config
+
+
+if TYPE_CHECKING:
+    from collections.abc import Sequence
+
+
+logger: logging.Logger = logging.getLogger()
+
+
+def has_alias(
+    arguments: Sequence[Argument | SelfArgument | TensorOptionsArguments],
+) -> bool:
+    for arg in arguments:
+        annotation = getattr(arg, "annotation", None)
+        if not annotation:
+            continue
+        alias_set = getattr(annotation, "alias_set", ())
+        if alias_set:
+            return True
+    return False
+
+
+BLOCKED_OPS = frozenset(
+    (
+        # non cpu ops
+        "sparse_sampled_addmm",
+        "hspmm",
+        "linalg_svdvals",
+        # sparse ops
+        "sspaddmm",
+        "coalesce",
+        "_indices",
+        "indices",
+        "_values",
+        "values",
+        "crow_indices",
+        "col_indices",
+        # deprecated ops
+        "floor_divide",
+        "ger",
+        # buggy ops
+        "conj_physical",  # P495807361
+        "binary_cross_entropy",  # P496394764
+        "arccosh",
+        # uncommon ops
+        "cholesky",
+        "lu_solve",
+        "linalg_cholesky",
+        "linalg_householder_product",
+        "linalg_ldl_solve",
+        "_compute_linear_combination",
+        # training related ops
+        "_make_dual",
+        # cannot call directly
+        "_fw_primal",
+        # no documentation
+        "_index_reduce",
+        # TODO: these ones got added recently and need manual inspection
+        "_new_zeros_with_same_feature_meta",
+        "_conj_physical",
+        "binary_cross_entropy_with_logits",
+        "bincount",
+        "conv_tbc",
+        "copy",
+        "_copy_from",
+        "_copy_from_and_resize",
+        "count_nonzero",
+        "cudnn_affine_grid_generator",
+        "cudnn_affine_grid_generator_backward",
+        "cudnn_grid_sampler",
+        "diag_embed",
+        "embedding",
+        "embedding_dense_backward",
+        "_embedding_bag_dense_backward",
+        "_embedding_bag_per_sample_weights_backward",
+        "grid_sampler_2d",
+        "_grid_sampler_2d_cpu_fallback",
+        "grid_sampler_3d",
+        "isnan",
+        "mkldnn_linear",
+        "median",
+        "nanmedian",
+        "_sparse_sparse_matmul",
+        "batch_norm_backward_elemt",
+        "_euclidean_dist",
+        "pixel_shuffle",
+        "pixel_unshuffle",
+        "channel_shuffle",
+        "_reshape_nested_backward",
+        "relu",
+        "prelu",
+        "celu",
+        "slice_scatter",
+        "select_scatter",
+        "diagonal_scatter",
+        "sum",
+        "_mkldnn_transpose",
+        "_nested_tensor_from_mask",
+        "_nested_from_padded",
+        "_nested_tensor_size",
+        "_nested_from_padded_and_nested_example",
+        "_standard_gamma_grad",
+        "_dirichlet_grad",
+        "native_norm",
+        "_sparse_softmax",
+        "_sparse_softmax_backward_data",
+        "_sparse_log_softmax",
+        "_sparse_log_softmax_backward_data",
+        "zero",
+        "_sparse_addmm",
+        "sparse_mask",
+        "_sparse_mask_projection",
+        "_to_dense",
+        "_coalesce",
+        "_coalesced",
+        "copy_sparse_to_sparse",
+        "to_sparse",
+        "to_sparse_csr",
+        "to_sparse_csc",
+        "to_mkldnn",
+        "quantize_per_tensor_dynamic",
+        "quantize_per_channel",
+        "q_per_channel_scales",
+        "q_per_channel_zero_points",
+        "int_repr",
+        "_make_per_channel_quantized_tensor",
+        "set",
+        "lift",
+        "lift_fresh",
+        "lift_fresh_copy",
+        "masked_scatter",
+        "_masked_softmax",
+        "_masked_softmax_backward",
+        "put",
+        "index_reduce",
+        "trace",
+        "_cholesky_solve_helper",
+        "dist",
+        "max",
+        "_torch_cuda_cu_linker_symbol_op",
+        "glu_jvp",
+        "glu_backward_jvp",
+        "hardswish_backward",
+        "rrelu_with_noise_backward",
+        "mkldnn_adaptive_avg_pool2d_backward",
+        "_adaptive_avg_pool2d_backward",
+        "_adaptive_avg_pool3d_backward",
+        "isinf",
+        "linalg_lu_solve",
+        "linalg_vecdot",
+        "linalg_matrix_exp",
+        "linalg_eigvalsh",
+        "_test_warn_in_autograd",
+        "_test_autograd_multiple_dispatch_view",
+        "_test_autograd_multiple_dispatch_view_copy",
+        "_segment_reduce",
+        "_segment_reduce_backward",
+        "_fw_primal_copy",
+        "_make_dual_copy",
+        "view_as_real_copy",
+        "view_as_complex_copy",
+        "_conj_copy",
+        "_neg_view_copy",
+        "diagonal_copy",
+        "detach_copy",
+        "squeeze_copy",
+        "t_copy",
+        "unsqueeze_copy",
+        "_indices_copy",
+        "_values_copy",
+        "indices_copy",
+        "values_copy",
+        "crow_indices_copy",
+        "col_indices_copy",
+        "ccol_indices",
+        "ccol_indices_copy",
+        "row_indices",
+        "row_indices_copy",
+        "unfold_copy",
+        "alias_copy",
+        "_triton_multi_head_attention",
+        "special_airy_ai",
+        "special_bessel_j0",
+        "special_bessel_j1",
+        "special_bessel_y0",
+        "special_bessel_y1",
+        "special_chebyshev_polynomial_t",
+        "special_chebyshev_polynomial_u",
+        "special_chebyshev_polynomial_v",
+        "special_chebyshev_polynomial_w",
+        "special_hermite_polynomial_h",
+        "special_hermite_polynomial_he",
+        "special_laguerre_polynomial_l",
+        "special_legendre_polynomial_p",
+        "special_modified_bessel_i0",
+        "special_modified_bessel_i1",
+        "special_modified_bessel_k0",
+        "special_modified_bessel_k1",
+        "special_scaled_modified_bessel_k0",
+        "special_scaled_modified_bessel_k1",
+        "special_shifted_chebyshev_polynomial_t",
+        "special_shifted_chebyshev_polynomial_u",
+        "special_shifted_chebyshev_polynomial_v",
+        "special_shifted_chebyshev_polynomial_w",
+        "special_spherical_bessel_j0",
+        "_foobar",
+        "_nested_tensor_strides",
+        "_nested_tensor_storage_offsets",
+        "_nested_get_values",  # no CPU backend
+        "_nested_get_values_copy",  # no CPU backend
+        "_nested_view_from_jagged",  # testing needs to be patched
+        "_nested_view_from_jagged_copy",  # testing needs to be patched
+        "_nested_view_from_buffer",  # testing needs to be patched
+        "_nested_view_from_buffer_copy",  # testing needs to be patched
+        "_int_mm",  # testing needs to be patched
+        "_to_sparse_csc",  # testing needs to be patched
+        "_to_sparse_csr",  # testing needs to be patched
+        "segment_reduce",  # testing needs to be patched
+    )
+)
+
+
+def is_supported(g: NativeFunctionsGroup | NativeFunctionsViewGroup) -> bool:
+    base_op_name = ""
+    func = None
+    if isinstance(g, NativeFunctionsViewGroup):
+        base_op_name = g.view.root_name
+        func = g.view.func
+    else:
+        base_op_name = g.out.func.name.name.base
+        func = g.out.func
+    if config.is_hand_written(g):
+        logger.info("HAND WRITTEN: %s", base_op_name)
+        return False
+    if base_op_name in BLOCKED_OPS:
+        logger.info("BLOCKED: %s", base_op_name)
+        return False
+    for arg in func.schema_order_arguments():
+        maybe_method = ivalue_type_conversion_method(arg.type)
+        if not maybe_method:
+            # Type converting is unsupported yet.
+            logger.info("NOT SUPPORTED TYPE CONVERTING: %s", func)
+            return False
+
+    if isinstance(g, NativeFunctionsViewGroup):
+        # TODO: stop doing type tests by converting to C++ and then testing
+        # the string, just test the dang thing directly
+        if "at::Tensor" != cpp.returns_type(func.returns, symint=False).cpp_type():
+            # Returns a non-Tensor value.
+            logger.info("NON-TENSOR RET TYPE: %s", str(func))
+            return False
+        return True
+
+    # For out variant ops, we need to check the arguments of its functional func.
+    for arg in g.functional.func.schema_order_arguments():
+        maybe_method = ivalue_type_conversion_method(arg.type)
+        if not maybe_method:
+            # Type converting is unsupported yet.
+            logger.info("NOT SUPPORTED TYPE CONVERTING: %s", g.functional.func)
+            return False
+
+    if not g.structured:
+        # In case of unstructured op, we check if it has out variant implementation.
+        # The out variant implementation satisfies the minimum requirement that it has the output tensor as the last
+        # parameter.
+        if (
+            not hasattr(g, "out")
+            or not str(func).endswith("Tensor(a!) out) -> Tensor(a!)")
+            or not str(func.name).endswith(".out")
+        ):
+            return False
+    # TODO: stop type testing by converting to C++
+    if "at::Tensor &" != cpp.returns_type(func.returns, symint=False).cpp_type():
+        logger.info("NON_TENSOR RET TYPE: %s", func)
+        return False
+    if has_alias(func.arguments.non_out):
+        # This op may create an alias of inputs.
+        logger.info("INPUTS ALIAS: %s", base_op_name)
+        return False
+    return True
+
+
+def ivalue_type_conversion_method(
+    arg_type: BaseType | OptionalType | Type,
+) -> tuple[bool, str] | None:
+    """
+    Return the method call expression of `c10::ivalue' to convert its contained value to
+    the expected value of `arg_type` type. For example, for `arg_type` == BaseTy.Tensor,
+    this function returns ".toTensor()", so that it can be appended to the ivalue's
+    variable name to get the value of the expected type.
+    """
+    type_conversion_methods = {
+        BaseTy.Tensor: ((True, "toTensor()"), (False, "toOptional()")),
+        BaseTy.int: ((False, "toInt()"), (False, "toOptional()")),
+        BaseTy.bool: ((False, "toBool()"), (False, "toOptional()")),
+        BaseTy.Scalar: ((False, "toScalar()"), (False, "toOptional()")),
+        BaseTy.ScalarType: (
+            (False, "toScalarType()"),
+            (False, "toOptional()"),
+        ),
+        BaseTy.str: (
+            (False, "toStringView()"),
+            (False, "toOptional()"),
+            (False, "toOptional<::std::string_view>()"),
+        ),
+    }
+
+    base_ty_object = None
+    if isinstance(arg_type, BaseType):
+        base_ty_object = arg_type.name
+    elif isinstance(arg_type, OptionalType):
+        if not isinstance(arg_type.elem, BaseType):
+            # ListType is currently unsupported.
+            return None
+        base_ty_object = arg_type.elem.name
+    else:
+        return None
+
+    if base_ty_object not in type_conversion_methods:
+        return None
+    methods = type_conversion_methods[base_ty_object]
+    if isinstance(arg_type, BaseType):
+        return methods[0]
+    return methods[1]
+
+
+should_use_int_tensor_ops_ = frozenset(
+    (
+        "bitwise_not",
+        "bitwise_and",
+        "bitwise_or",
+        "bitwise_xor",
+        "bitwise_left_shift",
+        "bitwise_right_shift",
+        "gcd",
+        "lcm",
+        "scatter",
+        "gather",
+        "_convert_indices_from_coo_to_csr",
+        "_convert_indices_from_csr_to_coo",
+    )
+)
+should_use_complex_tensor_ops_ = frozenset(("view_as_real", "imag", "_conj"))
+
+
+def should_use_int_tensor(op_name: str) -> bool:
+    return op_name in should_use_int_tensor_ops_
+
+
+def should_use_complex_tensor(op_name: str) -> bool:
+    return op_name in should_use_complex_tensor_ops_
+
+
+test_tensor_dim_ops_1_ = frozenset(
+    (
+        "addmv",
+        "index_add",
+        "_convert_indices_from_coo_to_csr",
+        "_convert_indices_from_csr_to_coo",
+        "nll_loss_backward",
+        "dot",
+        "vdot",
+        "outer",
+        "ger",
+    )
+)
+test_tensor_dim_ops_2_ = frozenset(
+    ("addmm", "mm", "nuclear_norm", "diag", "_addmm_activation", "matrix_H", "t")
+)
+
+
+def test_tensor_dim(op_name: str) -> int:
+    if op_name in test_tensor_dim_ops_1_:
+        return 1
+    if op_name in test_tensor_dim_ops_2_:
+        return 2
+    return 3
+
+
+test_tensor_shapes_string = '{"view_as_complex": "{2, 2}"}'
+test_tensor_shape_json: dict[str, str] = json.loads(test_tensor_shapes_string)
+
+
+def test_tensor_shape(op_name: str) -> str:
+    if op_name in test_tensor_shape_json:
+        return test_tensor_shape_json[op_name]
+    else:
+        return ""
+
+
+def test_value_expression(
+    arg_type: BaseType | OptionalType | Type, index: int, op_name: str
+) -> str:
+    tensor_size_ex = test_tensor_shape(op_name)
+    if tensor_size_ex == "":
+        num_tensors = 16 if index == 0 else 64
+        num_dim = test_tensor_dim(op_name)
+        size_per_dim = math.ceil(num_tensors / float(num_dim))
+        size_per_dim += size_per_dim % 2
+        tensor_size_ex = "{{{}}}".format(",".join([f"{size_per_dim}"] * num_dim))
+    if should_use_int_tensor(op_name):
+        tensor_expression = f"at::randint(1, 100, {tensor_size_ex}, at::kInt)"
+    elif should_use_complex_tensor(op_name):
+        tensor_expression = f"at::randn({tensor_size_ex}, at::kComplexFloat)"
+    else:
+        tensor_expression = f"at::rand({tensor_size_ex})"
+
+    value_expressions = {
+        BaseTy.Tensor: tensor_expression,
+        BaseTy.int: "1",
+        BaseTy.bool: "false",
+        BaseTy.Scalar: "2",
+        BaseTy.ScalarType: "at::ScalarType::Float",
+        BaseTy.str: '"floor"',
+    }
+
+    base_ty_object = None
+    if isinstance(arg_type, BaseType):
+        base_ty_object = arg_type.name
+    else:
+        assert isinstance(arg_type, OptionalType) and isinstance(
+            arg_type.elem, BaseType
+        )
+        base_ty_object = arg_type.elem.name
+    assert base_ty_object in value_expressions, "not expected type"
+    value_expression = value_expressions[base_ty_object]
+    return value_expression
+
+
+def generate_test_value_definitions(schema: FunctionSchema, index: int) -> str:
+    assert not schema.is_out_fn()
+    schema_name = schema.name.name.base
+    arg_map = {}
+    for arg in schema.schema_order_arguments():
+        test_value_exp = test_value_expression(arg.type, index, schema_name)
+        arg_map[arg.name] = test_value_exp
+    config.override_test_values(arg_map, schema_name, index)
+    arg_populations = []
+    for arg_name, arg_value in arg_map.items():
+        arg_populations.append(f"auto {arg_name}{index} = {arg_value}")
+    return ";\n    ".join(arg_populations) + ";"
+
+
+def generate_test_value_names(schema: FunctionSchema, index: int) -> str:
+    assert not schema.is_out_fn()
+    return ",".join(f"{arg.name}{index}" for arg in schema.schema_order_arguments())
+
+
+generate_test_ir_arguments_base_ty_to_type_str_ = {
+    BaseTy.Tensor: "Tensor",
+    BaseTy.int: "int",
+    BaseTy.float: "float",
+    BaseTy.str: "str",
+    BaseTy.Scalar: "int",
+    BaseTy.ScalarType: "int",
+    BaseTy.bool: "bool",
+}
+
+
+def generate_test_ir_arguments(
+    schema: FunctionSchema,
+) -> list[tuple[str, str | None]]:
+    def ir_argument(arg: Argument) -> tuple[str, str | None]:
+        t = arg.type
+        add_optional = False
+        if isinstance(t, OptionalType):
+            t = t.elem
+            add_optional = True
+        assert isinstance(t, BaseType)
+        type_str = None
+        if t.name in generate_test_ir_arguments_base_ty_to_type_str_:
+            type_str = generate_test_ir_arguments_base_ty_to_type_str_[t.name]
+        if type_str and add_optional:
+            type_str = f"{type_str}?"
+        return ("%" + arg.name, type_str)
+
+    return [ir_argument(arg) for arg in schema.schema_order_arguments()]
+
+
+def generate_arg_extraction(schema: FunctionSchema) -> str:
+    arg_populations = []
+    for i, arg in enumerate(schema.schema_order_arguments()):
+        maybe_method = ivalue_type_conversion_method(arg.type)
+        assert maybe_method
+        is_reference, type_conversion_method = maybe_method
+        reference = "&" if is_reference else ""
+        arg_populations.append(
+            f"const auto{reference} {arg.name} = p_node->Input({i}).{type_conversion_method}"
+        )
+    return ";\n    ".join(arg_populations) + ";"
+
+
+def get_kernel_name(g: NativeFunctionsGroup, backend_index: BackendIndex) -> str:
+    kernel = backend_index.get_kernel(g.functional)
+    if g.structured or kernel is None:
+        return cpp.name(g.functional.func)
+    return kernel.kernel
+
+
+def get_out_kernel_name(g: NativeFunctionsGroup, backend_index: BackendIndex) -> str:
+    kernel = backend_index.get_kernel(g.out)
+    if g.structured or kernel is None:
+        return cpp.name(g.out.func)
+    return kernel.kernel
+
+
+def generate_non_out_variant_call(
+    g: NativeFunctionsGroup, backend_index: BackendIndex
+) -> str:
+    schema = g.functional.func
+    assert not schema.is_out_fn()
+    kernel_name = get_kernel_name(g, backend_index)
+    arg_names = (arg.name for arg in schema.schema_order_arguments())
+    namespace_name = "cpu" if g.structured else "native"
+    return f"at::{namespace_name}::{kernel_name}({','.join(arg_names)})"
+
+
+def generate_call_to_view_ops(
+    g: NativeFunctionsViewGroup, backend_index: BackendIndex
+) -> str:
+    schema = g.view.func
+    kernel_name = cpp.name(schema)
+    kernel = backend_index.get_kernel(g.view)
+    if kernel:
+        kernel_name = kernel.kernel
+    arg_names = (arg.name for arg in schema.schema_order_arguments())
+    namespace_name = "native"
+    return f"at::{namespace_name}::{kernel_name}({','.join(arg_names)})"
+
+
+def generate_out_variant_call(
+    g: NativeFunctionsGroup, backend_index: BackendIndex
+) -> str:
+    schema = g.out.func
+    assert schema.is_out_fn()
+    arg_names = []
+    kernel_name = get_out_kernel_name(g, backend_index)
+    if g.structured:
+        # structured op starts with the output tensor argument.
+        arg_names = [out_arg.name for out_arg in schema.arguments.out]
+    else:
+        arg_names = []
+    for arg in schema.arguments.non_out:
+        if isinstance(arg, SelfArgument):
+            arg_names.append(arg.argument.name)
+        else:
+            assert isinstance(arg, Argument)
+            arg_names.append(arg.name)
+    if not g.structured:
+        assert len(schema.arguments.out) == 1
+        arg_names.append(schema.arguments.out[0].name)
+    cpp_arg_names = ",".join(arg_names)
+    namespace_name = "cpu" if g.structured else "native"
+    return f"at::{namespace_name}::{kernel_name}({cpp_arg_names})"
+
+
+no_memory_resize_ops = frozenset(
+    (
+        "isin.Scalar_Tensor",
+        "index_add",
+        "dot",
+        "vdot",
+        "nuclear_norm",
+        "histc",
+        "l1_loss",
+        "multi_margin_loss",
+        "multilabel_margin_loss",
+        "nll_loss",
+        "nll_loss2d",
+        "prod",
+    )
+)
+
+
+def should_check_resize(schema: FunctionSchema) -> bool:
+    schema_str = str(schema)
+    type_variant_op_name = schema_str[: schema_str.find("(")]
+    return type_variant_op_name not in no_memory_resize_ops
+
+
+def op_name_from_group(g: NativeFunctionsGroup) -> str:
+    return g.functional.func.name.name.base
+
+
+class GenOpDispatcher:
+    def out_variant(
+        self, groups: Sequence[NativeFunctionsGroup], backend_index: BackendIndex
+    ) -> str:
+        if not groups:
+            return ""
+        generated_type_variants = []
+        for g in groups:
+            with native_function_manager(g):
+                assert is_supported(g)
+                assert isinstance(g, NativeFunctionsGroup)
+                generated_type_variant = self.out_variant_op_generator(g, backend_index)
+                generated_type_variants.append(generated_type_variant)
+        op_name = op_name_from_group(groups[0])
+        body = "\n".join(generated_type_variants)
+        generated = f"""
+REGISTER_OPERATOR_FUNCTOR(
+    aten::{op_name},
+    aten_{op_name},
+    [](Node* n) -> SROperator {{
+      {body}
+      LogAndDumpSchema(n);
+      return nullptr;
+    }})
+"""
+        return generated
+
+    def view(
+        self, groups: Sequence[NativeFunctionsViewGroup], backend_index: BackendIndex
+    ) -> str:
+        if not groups:
+            return ""
+        generated_type_variants = []
+        for g in groups:
+            with native_function_manager(g):
+                assert is_supported(g)
+                assert isinstance(g, NativeFunctionsViewGroup)
+                generated_type_variant = self.view_op_generator(g, backend_index)
+                generated_type_variants.append(generated_type_variant)
+        op_name = config.func_name_base_str(groups[0])
+        body = "\n".join(generated_type_variants)
+        generated = f"""
+REGISTER_NATIVE_OPERATOR_FUNCTOR(
+    aten::{op_name},
+    aten_{op_name},
+    [](Node* n) -> SROperator {{
+      {body}
+      LogAndDumpSchema(n);
+      return nullptr;
+    }});
+"""
+        return generated
+
+    def out_variant_op_generator(
+        self, g: NativeFunctionsGroup, backend_index: BackendIndex
+    ) -> str:
+        functional = g.functional
+        schema = str(functional.func)
+        populated_argument = generate_arg_extraction(g.functional.func)
+        functional_variant_call = generate_non_out_variant_call(g, backend_index)
+        assert len(g.out.func.arguments.out) == 1
+        out_variable_name = str(g.out.func.arguments.out[0].name)
+        out_variant_call = generate_out_variant_call(g, backend_index)
+        generated = f"""
+      if (n->matches(torch::schema("aten::{schema}"))) {{
+        return [](ProcessedNode* p_node) {{
+          {populated_argument}
+          if (p_node->Output(0).isNone()) {{
+            p_node->Output(0) = {functional_variant_call};
+            return;
+          }}
+          auto& {out_variable_name} = p_node->Output(0).toTensor();
+          fastResizeToZero({out_variable_name});
+          {out_variant_call};
+        }};
+      }}"""
+        return generated
+
+    def view_op_generator(
+        self, g: NativeFunctionsViewGroup, backend_index: BackendIndex
+    ) -> str:
+        schema = str(g.view.func)
+        populated_argument = generate_arg_extraction(g.view.func)
+        functional_variant_call = generate_call_to_view_ops(g, backend_index)
+        generated = f"""
+      if (n->matches(torch::schema("aten::{schema}"))) {{
+        return [](ProcessedNode* p_node) {{
+          {populated_argument}
+            p_node->Output(0) = {functional_variant_call};
+        }};
+      }}"""
+        return generated
+
+
+class GenOpTestCase:
+    def out_variant(self, groups: Sequence[NativeFunctionsGroup]) -> str:
+        if not groups:
+            return ""
+        generated_type_variants = []
+        for g in groups:
+            with native_function_manager(g):
+                assert is_supported(g)
+                assert isinstance(g, NativeFunctionsGroup)
+                generated_type_variant = self.out_variant_op_test_case_generator(g)
+                generated_type_variants.append(generated_type_variant)
+        return "\n".join(generated_type_variants)
+
+    def view(self, groups: Sequence[NativeFunctionsViewGroup]) -> str:
+        if not groups:
+            return ""
+        generated_type_variants = []
+        for g in groups:
+            with native_function_manager(g):
+                assert is_supported(g)
+                assert isinstance(g, NativeFunctionsViewGroup)
+                generated_type_variant = self.view_op_test_case_generator(g)
+                generated_type_variants.append(generated_type_variant)
+        return "\n".join(generated_type_variants)
+
+    def out_variant_op_test_case_generator(self, g: NativeFunctionsGroup) -> str:
+        schema = g.functional.func
+        schema_str = str(schema)
+        assert schema_str.find("(") > 0
+        type_variant_op_name = schema_str[: schema_str.find("(")].replace(".", "_")
+        op_name = op_name_from_group(g)
+        assert type_variant_op_name.startswith(op_name)
+
+        arg_types = generate_test_ir_arguments(schema)
+        arg_declarations = ", ".join(
+            (
+                arg_name if arg_type is None else f"{arg_name}: {arg_type}"
+                for arg_name, arg_type in arg_types
+            )
+        )
+        arg_names = ", ".join((arg_name for arg_name, _ in arg_types))
+        assert (
+            len(schema.returns) == 1
+            and isinstance(schema.returns[0].type, BaseType)
+            and schema.returns[0].type.name is BaseTy.Tensor
+        )
+        test_value_definitions = generate_test_value_definitions(schema, 0)
+        test_value_names = generate_test_value_names(schema, 0)
+        test_value_definitions2 = generate_test_value_definitions(schema, 1)
+        test_value_names2 = generate_test_value_names(schema, 1)
+        check_resize = "true" if should_check_resize(schema) else "false"
+        generated = f"""
+TEST(StaticRuntime, autogen_{type_variant_op_name}) {{
+  const std::string script = R"IR(
+    graph({arg_declarations}):
+        %bias: None = prim::Constant()
+        %ret = aten::{op_name}({arg_names})
+        %cloned = aten::clone(%ret, %bias)
+        return (%cloned)
+  )IR";
+
+  {test_value_definitions}
+  std::vector args{{{test_value_names}}};
+  testStaticRuntime(script, args, {{}}, /*use_allclose=*/false, /*use_equalnan=*/false, /*check_resize=*/{check_resize});
+
+  {test_value_definitions2}
+  std::vector args2{{{test_value_names2}}};
+  testStaticRuntime(script, args, args2, /*use_allclose=*/false, /*use_equalnan=*/false, /*check_resize=*/{check_resize});
+
+}}
+"""
+        return generated
+
+    def view_op_test_case_generator(self, g: NativeFunctionsViewGroup) -> str:
+        schema = g.view.func
+        schema_str = str(schema)
+        assert schema_str.find("(") > 0
+        type_variant_op_name = schema_str[: schema_str.find("(")].replace(".", "_")
+        op_name = g.view.root_name
+        assert type_variant_op_name.startswith(op_name)
+
+        arg_types = generate_test_ir_arguments(schema)
+        arg_declarations = ", ".join(
+            (
+                arg_name if arg_type is None else f"{arg_name}: {arg_type}"
+                for arg_name, arg_type in arg_types
+            )
+        )
+        arg_names = ", ".join((arg_name for arg_name, _ in arg_types))
+        assert (
+            len(schema.returns) == 1
+            and isinstance(schema.returns[0].type, BaseType)
+            and schema.returns[0].type.name is BaseTy.Tensor
+        )
+        test_value_definitions = generate_test_value_definitions(schema, 0)
+        test_value_names = generate_test_value_names(schema, 0)
+        generated = f"""
+TEST(StaticRuntime, autogen_{type_variant_op_name}) {{
+  const std::string script = R"IR(
+    graph({arg_declarations}):
+        %bias: None = prim::Constant()
+        %ret = aten::{op_name}({arg_names})
+        %cloned = aten::clone(%ret, %bias)
+        return (%cloned)
+  )IR";
+
+  {test_value_definitions}
+  std::vector args{{{test_value_names}}};
+  testStaticRuntime(script, args);
+}}
+"""
+
+        return generated
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/utils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..905d6fd0c0b6c43283013d0bf75501a3e0fe9fb6
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/utils.py
@@ -0,0 +1,568 @@
+from __future__ import annotations
+
+import contextlib
+import functools
+import hashlib
+import os
+import re
+import sys
+import textwrap
+from dataclasses import fields, is_dataclass
+from enum import auto, Enum
+from pathlib import Path
+from typing import Any, Callable, Generic, Literal, NoReturn, TYPE_CHECKING, TypeVar
+from typing_extensions import assert_never, deprecated, Self
+
+from torchgen.code_template import CodeTemplate
+
+
+if TYPE_CHECKING:
+    from argparse import Namespace
+    from collections.abc import Iterable, Iterator, Sequence
+
+
+TORCHGEN_ROOT = Path(__file__).absolute().parent
+REPO_ROOT = TORCHGEN_ROOT.parent
+
+
+# Many of these functions share logic for defining both the definition
+# and declaration (for example, the function signature is the same), so
+# we organize them into one function that takes a Target to say which
+# code we want.
+#
+# This is an OPEN enum (we may add more cases to it in the future), so be sure
+# to explicitly specify with Literal[Target.XXX] or Literal[Target.XXX, Target.YYY]
+# what targets are valid for your use.
+class Target(Enum):
+    # top level namespace (not including at)
+    DEFINITION = auto()
+    DECLARATION = auto()
+    # TORCH_LIBRARY(...) { ... }
+    REGISTRATION = auto()
+    # namespace { ... }
+    ANONYMOUS_DEFINITION = auto()
+    # namespace cpu { ... }
+    NAMESPACED_DEFINITION = auto()
+    NAMESPACED_DECLARATION = auto()
+
+
+# Matches "foo" in "foo, bar" but not "foobar". Used to search for the
+# occurrence of a parameter in the derivative formula
+IDENT_REGEX = r"(^|\W){}($|\W)"
+
+
+# TODO: Use a real parser here; this will get bamboozled
+def split_name_params(schema: str) -> tuple[str, list[str]]:
+    m = re.match(r"(\w+)(\.\w+)?\((.*)\)", schema)
+    if m is None:
+        raise RuntimeError(f"Unsupported function schema: {schema}")
+    name, _, params = m.groups()
+    return name, params.split(", ")
+
+
+T = TypeVar("T")
+S = TypeVar("S")
+
+# These two functions purposely return generators in analogy to map()
+# so that you don't mix up when you need to list() them
+
+
+# Map over function that may return None; omit Nones from output sequence
+def mapMaybe(func: Callable[[T], S | None], xs: Iterable[T]) -> Iterator[S]:
+    for x in xs:
+        r = func(x)
+        if r is not None:
+            yield r
+
+
+# Map over function that returns sequences and cat them all together
+def concatMap(func: Callable[[T], Sequence[S]], xs: Iterable[T]) -> Iterator[S]:
+    for x in xs:
+        yield from func(x)
+
+
+# Conveniently add error context to exceptions raised.  Lets us
+# easily say that an error occurred while processing a specific
+# context.
+@contextlib.contextmanager
+def context(msg_fn: Callable[[], str]) -> Iterator[None]:
+    try:
+        yield
+    except Exception as e:
+        # TODO: this does the wrong thing with KeyError
+        msg = msg_fn()
+        msg = textwrap.indent(msg, "  ")
+        msg = f"{e.args[0]}\n{msg}" if e.args else msg
+        e.args = (msg,) + e.args[1:]
+        raise
+
+
+if TYPE_CHECKING:
+    # A little trick from https://github.com/python/mypy/issues/6366
+    # for getting mypy to do exhaustiveness checking
+    # TODO: put this somewhere else, maybe
+    @deprecated("Use typing_extensions.assert_never instead")
+    def assert_never(x: NoReturn) -> NoReturn:  # type: ignore[misc] # noqa: F811
+        raise AssertionError(f"Unhandled type: {type(x).__name__}")
+
+
+@functools.cache
+def _read_template(template_fn: str) -> CodeTemplate:
+    return CodeTemplate.from_file(template_fn)
+
+
+# String hash that's stable across different executions, unlike builtin hash
+def string_stable_hash(s: str) -> int:
+    sha1 = hashlib.sha1(s.encode("latin1"), usedforsecurity=False).digest()
+    return int.from_bytes(sha1, byteorder="little")
+
+
+# A small abstraction for writing out generated files and keeping track
+# of what files have been written (so you can write out a list of output
+# files)
+class FileManager:
+    def __init__(
+        self,
+        install_dir: str | Path,
+        template_dir: str | Path,
+        dry_run: bool,
+    ) -> None:
+        self.install_dir = Path(install_dir)
+        self.template_dir = Path(template_dir)
+        self.files: set[Path] = set()
+        self.dry_run = dry_run
+
+    @property
+    def filenames(self) -> frozenset[str]:
+        return frozenset({file.as_posix() for file in self.files})
+
+    def _write_if_changed(self, filename: str | Path, contents: str) -> None:
+        file = Path(filename)
+        old_contents: str | None = None
+        try:
+            old_contents = file.read_text(encoding="utf-8")
+        except OSError:
+            pass
+        if contents != old_contents:
+            # Create output directory if it doesn't exist
+            file.parent.mkdir(parents=True, exist_ok=True)
+            file.write_text(contents, encoding="utf-8")
+
+    # Read from template file and replace pattern with callable (type could be dict or str).
+    def substitute_with_template(
+        self,
+        template_fn: str | Path,
+        env_callable: Callable[[], str | dict[str, Any]],
+    ) -> str:
+        assert not Path(template_fn).is_absolute(), (
+            f"template_fn must be relative: {template_fn}"
+        )
+        template_path = self.template_dir / template_fn
+        env = env_callable()
+        if isinstance(env, dict):
+            if "generated_comment" not in env:
+                generator_default = TORCHGEN_ROOT / "gen.py"
+                try:
+                    generator = Path(
+                        sys.modules["__main__"].__file__ or generator_default
+                    ).absolute()
+                except (KeyError, AttributeError):
+                    generator = generator_default.absolute()
+
+                try:
+                    generator_path = generator.relative_to(REPO_ROOT).as_posix()
+                except ValueError:
+                    generator_path = generator.name
+
+                env = {
+                    **env,  # copy the original dict instead of mutating it
+                    "generated_comment": (
+                        "@" + f"generated by {generator_path} from {template_fn}"
+                    ),
+                }
+            template = _read_template(template_path)
+            substitute_out = template.substitute(env)
+            # Ensure an extra blank line between the class/function definition
+            # and the docstring of the previous class/function definition.
+            # NB: It is generally not recommended to have docstrings in pyi stub
+            #     files. But if there are any, we need to ensure that the file
+            #     is properly formatted.
+            return re.sub(
+                r'''
+                (""")\n+             # match triple quotes
+                (
+                    (\s*@.+\n)*     # match decorators if any
+                    \s*(class|def)  # match class/function definition
+                )
+                ''',
+                r"\g<1>\n\n\g<2>",
+                substitute_out,
+                flags=re.VERBOSE,
+            )
+        if isinstance(env, str):
+            return env
+        assert_never(env)
+
+    def write_with_template(
+        self,
+        filename: str | Path,
+        template_fn: str | Path,
+        env_callable: Callable[[], str | dict[str, Any]],
+    ) -> None:
+        filename = Path(filename)
+        assert not filename.is_absolute(), f"filename must be relative: {filename}"
+        file = self.install_dir / filename
+        assert file not in self.files, f"duplicate file write {file}"
+        self.files.add(file)
+        if not self.dry_run:
+            substitute_out = self.substitute_with_template(
+                template_fn=template_fn,
+                env_callable=env_callable,
+            )
+            self._write_if_changed(filename=file, contents=substitute_out)
+
+    def write(
+        self,
+        filename: str | Path,
+        env_callable: Callable[[], str | dict[str, Any]],
+    ) -> None:
+        self.write_with_template(filename, filename, env_callable)
+
+    def write_sharded(
+        self,
+        filename: str | Path,
+        items: Iterable[T],
+        *,
+        key_fn: Callable[[T], str],
+        env_callable: Callable[[T], dict[str, list[str]]],
+        num_shards: int,
+        base_env: dict[str, Any] | None = None,
+        sharded_keys: set[str],
+    ) -> None:
+        self.write_sharded_with_template(
+            filename,
+            filename,
+            items,
+            key_fn=key_fn,
+            env_callable=env_callable,
+            num_shards=num_shards,
+            base_env=base_env,
+            sharded_keys=sharded_keys,
+        )
+
+    def write_sharded_with_template(
+        self,
+        filename: str | Path,
+        template_fn: str | Path,
+        items: Iterable[T],
+        *,
+        key_fn: Callable[[T], str],
+        env_callable: Callable[[T], dict[str, list[str]]],
+        num_shards: int,
+        base_env: dict[str, Any] | None = None,
+        sharded_keys: set[str],
+    ) -> None:
+        file = Path(filename)
+        assert not file.is_absolute(), f"filename must be relative: {filename}"
+        everything: dict[str, Any] = {"shard_id": "Everything"}
+        shards: list[dict[str, Any]] = [
+            {"shard_id": f"_{i}"} for i in range(num_shards)
+        ]
+        all_shards = [everything] + shards
+
+        if base_env is not None:
+            for shard in all_shards:
+                shard.update(base_env)
+
+        for key in sharded_keys:
+            for shard in all_shards:
+                if key in shard:
+                    assert isinstance(shard[key], list), (
+                        "sharded keys in base_env must be a list"
+                    )
+                    shard[key] = shard[key].copy()
+                else:
+                    shard[key] = []
+
+        def merge_env(into: dict[str, list[str]], from_: dict[str, list[str]]) -> None:
+            for k, v in from_.items():
+                assert k in sharded_keys, f"undeclared sharded key {k}"
+                into[k] += v
+
+        if self.dry_run:
+            # Dry runs don't write any templates, so incomplete environments are fine
+            items = ()
+
+        for item in items:
+            key = key_fn(item)
+            sid = string_stable_hash(key) % num_shards
+            env = env_callable(item)
+
+            merge_env(shards[sid], env)
+            merge_env(everything, env)
+
+        for shard in all_shards:
+            shard_id = shard["shard_id"]
+            self.write_with_template(
+                file.with_stem(f"{file.stem}{shard_id}"),
+                template_fn,
+                lambda: shard,
+            )
+
+        # filenames is used to track compiled files, but FooEverything.cpp isn't meant to be compiled
+        self.files.discard(self.install_dir / file.with_stem(f"{file.stem}Everything"))
+
+    def write_outputs(self, variable_name: str, filename: str | Path) -> None:
+        """Write a file containing the list of all outputs which are generated by this script."""
+        content = "\n".join(
+            (
+                "set(",
+                variable_name,
+                # Use POSIX paths to avoid invalid escape sequences on Windows
+                *(f'    "{file.as_posix()}"' for file in sorted(self.files)),
+                ")",
+            )
+        )
+        self._write_if_changed(filename, content)
+
+    def template_dir_for_comments(self) -> str:
+        """
+        This needs to be deterministic. The template dir is an absolute path
+        that varies across builds. So, just use the path relative to this file,
+        which will point to the codegen source but will be stable.
+        """
+        return os.path.relpath(self.template_dir, os.path.dirname(__file__))
+
+
+# Helper function to generate file manager
+def make_file_manager(
+    options: Namespace,
+    install_dir: str | Path | None = None,
+) -> FileManager:
+    template_dir = os.path.join(options.source_path, "templates")
+    install_dir = install_dir if install_dir else options.install_dir
+    return FileManager(
+        install_dir=install_dir,
+        template_dir=template_dir,
+        dry_run=options.dry_run,
+    )
+
+
+# Helper function to create a pretty representation for dataclasses
+def dataclass_repr(
+    obj: Any,
+    indent: int = 0,
+    width: int = 80,
+) -> str:
+    # built-in pprint module support dataclasses from python 3.10
+    if sys.version_info >= (3, 10):
+        from pprint import pformat
+
+        return pformat(obj, indent, width)
+
+    return _pformat(obj, indent=indent, width=width)
+
+
+def _pformat(
+    obj: Any,
+    indent: int,
+    width: int,
+    curr_indent: int = 0,
+) -> str:
+    assert is_dataclass(obj), f"obj should be a dataclass, received: {type(obj)}"
+
+    class_name = obj.__class__.__name__
+    # update current indentation level with class name
+    curr_indent += len(class_name) + 1
+
+    fields_list = [(f.name, getattr(obj, f.name)) for f in fields(obj) if f.repr]
+
+    fields_str = []
+    for name, attr in fields_list:
+        # update the current indent level with the field name
+        # dict, list, set and tuple also add indent as done in pprint
+        _curr_indent = curr_indent + len(name) + 1
+        if is_dataclass(attr):
+            str_repr = _pformat(attr, indent, width, _curr_indent)
+        elif isinstance(attr, dict):
+            str_repr = _format_dict(attr, indent, width, _curr_indent)
+        elif isinstance(attr, (list, set, tuple)):
+            str_repr = _format_list(attr, indent, width, _curr_indent)
+        else:
+            str_repr = repr(attr)
+
+        fields_str.append(f"{name}={str_repr}")
+
+    indent_str = curr_indent * " "
+    body = f",\n{indent_str}".join(fields_str)
+    return f"{class_name}({body})"
+
+
+def _format_dict(
+    attr: dict[Any, Any],
+    indent: int,
+    width: int,
+    curr_indent: int,
+) -> str:
+    curr_indent += indent + 3
+    dict_repr = []
+    for k, v in attr.items():
+        k_repr = repr(k)
+        v_str = (
+            _pformat(v, indent, width, curr_indent + len(k_repr))
+            if is_dataclass(v)
+            else repr(v)
+        )
+        dict_repr.append(f"{k_repr}: {v_str}")
+
+    return _format(dict_repr, indent, width, curr_indent, "{", "}")
+
+
+def _format_list(
+    attr: list[Any] | set[Any] | tuple[Any, ...],
+    indent: int,
+    width: int,
+    curr_indent: int,
+) -> str:
+    curr_indent += indent + 1
+    list_repr = [
+        _pformat(l, indent, width, curr_indent) if is_dataclass(l) else repr(l)
+        for l in attr
+    ]
+    start, end = ("[", "]") if isinstance(attr, list) else ("(", ")")
+    return _format(list_repr, indent, width, curr_indent, start, end)
+
+
+def _format(
+    fields_str: list[str],
+    indent: int,
+    width: int,
+    curr_indent: int,
+    start: str,
+    end: str,
+) -> str:
+    delimiter, curr_indent_str = "", ""
+    # if it exceed the max width then we place one element per line
+    if len(repr(fields_str)) >= width:
+        delimiter = "\n"
+        curr_indent_str = " " * curr_indent
+
+    indent_str = " " * indent
+    body = f", {delimiter}{curr_indent_str}".join(fields_str)
+    return f"{start}{indent_str}{body}{end}"
+
+
+class NamespaceHelper:
+    """A helper for constructing the namespace open and close strings for a nested set of namespaces.
+
+    e.g. for namespace_str torch::lazy,
+
+    prologue:
+    namespace torch {
+    namespace lazy {
+
+    epilogue:
+    } // namespace lazy
+    } // namespace torch
+    """
+
+    def __init__(
+        self,
+        namespace_str: str,
+        entity_name: str = "",
+        max_level: int = 2,
+    ) -> None:
+        # cpp_namespace can be a colon joined string such as torch::lazy
+        cpp_namespaces = namespace_str.split("::")
+        assert len(cpp_namespaces) <= max_level, (
+            f"Codegen doesn't support more than {max_level} level(s) of custom namespace. Got {namespace_str}."
+        )
+        self.cpp_namespace_ = namespace_str
+        self.prologue_ = "\n".join([f"namespace {n} {{" for n in cpp_namespaces])
+        self.epilogue_ = "\n".join(
+            [f"}} // namespace {n}" for n in reversed(cpp_namespaces)]
+        )
+        self.namespaces_ = cpp_namespaces
+        self.entity_name_ = entity_name
+
+    @staticmethod
+    def from_namespaced_entity(
+        namespaced_entity: str,
+        max_level: int = 2,
+    ) -> NamespaceHelper:
+        """
+        Generate helper from nested namespaces as long as class/function name. E.g.: "torch::lazy::add"
+        """
+        names = namespaced_entity.split("::")
+        entity_name = names[-1]
+        namespace_str = "::".join(names[:-1])
+        return NamespaceHelper(
+            namespace_str=namespace_str, entity_name=entity_name, max_level=max_level
+        )
+
+    @property
+    def prologue(self) -> str:
+        return self.prologue_
+
+    @property
+    def epilogue(self) -> str:
+        return self.epilogue_
+
+    @property
+    def entity_name(self) -> str:
+        return self.entity_name_
+
+    # Only allow certain level of namespaces
+    def get_cpp_namespace(self, default: str = "") -> str:
+        """
+        Return the namespace string from joining all the namespaces by "::" (hence no leading "::").
+        Return default if namespace string is empty.
+        """
+        return self.cpp_namespace_ if self.cpp_namespace_ else default
+
+
+class OrderedSet(Generic[T]):
+    storage: dict[T, Literal[None]]
+
+    def __init__(self, iterable: Iterable[T] | None = None) -> None:
+        if iterable is None:
+            self.storage = {}
+        else:
+            self.storage = dict.fromkeys(iterable)
+
+    def __contains__(self, item: T) -> bool:
+        return item in self.storage
+
+    def __iter__(self) -> Iterator[T]:
+        return iter(self.storage.keys())
+
+    def update(self, items: OrderedSet[T]) -> None:
+        self.storage.update(items.storage)
+
+    def add(self, item: T) -> None:
+        self.storage[item] = None
+
+    def copy(self) -> OrderedSet[T]:
+        ret: OrderedSet[T] = OrderedSet()
+        ret.storage = self.storage.copy()
+        return ret
+
+    @staticmethod
+    def union(*args: OrderedSet[T]) -> OrderedSet[T]:
+        ret = args[0].copy()
+        for s in args[1:]:
+            ret.update(s)
+        return ret
+
+    def __or__(self, other: OrderedSet[T]) -> OrderedSet[T]:
+        return OrderedSet.union(self, other)
+
+    def __ior__(self, other: OrderedSet[T]) -> Self:
+        self.update(other)
+        return self
+
+    def __eq__(self, other: object) -> bool:
+        if isinstance(other, OrderedSet):
+            return self.storage == other.storage
+        else:
+            return set(self.storage.keys()) == other
diff --git a/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/yaml_utils.py b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/yaml_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..720d1944602e7c810138d71d7cf60fe351f87500
--- /dev/null
+++ b/Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/torchgen/yaml_utils.py
@@ -0,0 +1,26 @@
+# Safely load fast C Yaml loader/dumper if they are available
+try:
+    from yaml import CSafeLoader as Loader
+except ImportError:
+    from yaml import SafeLoader as Loader  # type: ignore[assignment, misc]
+
+try:
+    from yaml import CSafeDumper as Dumper
+except ImportError:
+    from yaml import SafeDumper as Dumper  # type: ignore[assignment, misc]
+YamlDumper = Dumper
+
+
+# A custom loader for YAML that errors on duplicate keys.
+# This doesn't happen by default: see https://github.com/yaml/pyyaml/issues/165
+class YamlLoader(Loader):
+    def construct_mapping(self, node, deep=False):  # type: ignore[no-untyped-def]
+        mapping = []
+        for key_node, value_node in node.value:
+            key = self.construct_object(key_node, deep=deep)  # type: ignore[no-untyped-call]
+            assert key not in mapping, (
+                f"Found a duplicate key in the yaml. key={key}, line={node.start_mark.line}"
+            )
+            mapping.append(key)
+        mapping = super().construct_mapping(node, deep=deep)  # type: ignore[no-untyped-call]
+        return mapping